diff --git a/lean/OAI/Combinatorics/LowSpaceSubsetSum.lean b/lean/OAI/Combinatorics/LowSpaceSubsetSum.lean new file mode 100644 index 0000000000000000000000000000000000000000..094107f37ae216e88eeb6025b80a180f730dd525 --- /dev/null +++ b/lean/OAI/Combinatorics/LowSpaceSubsetSum.lean @@ -0,0 +1,16 @@ +import OAI.Combinatorics.LowSpaceSubsetSum.Search.BudgetDecisionRound +import OAI.Combinatorics.LowSpaceSubsetSum.Search.BudgetedParentFill +import OAI.Combinatorics.LowSpaceSubsetSum.Search.BudgetedParentReplay +import OAI.Combinatorics.LowSpaceSubsetSum.Main +import OAI.Combinatorics.LowSpaceSubsetSum.Streams.PrefixAccounting +import OAI.Combinatorics.LowSpaceSubsetSum.Streams.PrefixMachineRun +import OAI.Combinatorics.LowSpaceSubsetSum.Representation.RepresentationLifetime +import OAI.Combinatorics.LowSpaceSubsetSum.Counting.SignRandomization +import OAI.Combinatorics.LowSpaceSubsetSum.Search.StoppedGuardedDecision +import OAI.Combinatorics.LowSpaceSubsetSum.Storage.StoredNodeCells + +/-! # Low-space worst-case Subset Sum + +One-sided randomized decision with bounded sampling, counted preprocessing, +streamed representations, and all-outcome operation and writable-storage counts. +-/ diff --git a/lean/OAI/Combinatorics/LowSpaceSubsetSum/Streams/FilteredRow.lean b/lean/OAI/Combinatorics/LowSpaceSubsetSum/Streams/FilteredRow.lean new file mode 100644 index 0000000000000000000000000000000000000000..5b694d53357e73c3440c3bc510b96d549aa5792f --- /dev/null +++ b/lean/OAI/Combinatorics/LowSpaceSubsetSum/Streams/FilteredRow.lean @@ -0,0 +1,126 @@ +import OAI.Combinatorics.LowSpaceSubsetSum.Counting.BinarySlice +import OAI.Combinatorics.LowSpaceSubsetSum.Counting.SliceModular +import OAI.Combinatorics.LowSpaceSubsetSum.Streams.PairCursor + +namespace OAI + +/-! +# The actual filtered modular row + +The row searches the shared array by the small residue, searches the large +residue within that slice, and stores only the first occurrence and cursor. +Its sorted output is exactly the eligible occurrences. Positivity of the +large modulus supplies normalized keys; no coprimality is used. +-/ + +namespace LowSpaceSubsetSum +namespace FilteredRow + +variable {α β : Type*} + +abbrev PrimarySorted (xs : Array β) (w : β → ℤ) (p : ℤ) : Prop := + Monotone (fun i : Fin xs.size => w xs[i.val] % p) + +abbrev SecondarySorted (xs : Array β) (w : β → ℤ) (p P : ℤ) : Prop := + ∀ i j : Fin xs.size, i ≤ j → w xs[i.val] % p = w xs[j.val] % p → + w xs[i.val] % P ≤ w xs[j.val] % P + +def range (xs : Array β) (w : β → ℤ) (p c wx : ℤ) (k : ℕ) + (hs : PrimarySorted xs w p) (hk : xs.size < 2 ^ k) : SliceCursor.Range xs.size := + BinarySlice.range xs (fun y => w y % p) ((c - wx) % p) k hs hk + +theorem range_length (xs : Array β) (w : β → ℤ) (p c wx : ℤ) (k : ℕ) + (hs : PrimarySorted xs w p) (hk : xs.size < 2 ^ k) : + (range xs w p c wx k hs hk).length < 2 ^ k := by + have := (range xs w p c wx k hs hk).bounded + omega + +theorem range_sorted (xs : Array β) (w : β → ℤ) (p P c wx : ℤ) (k : ℕ) + (hs : PrimarySorted xs w p) (ht : SecondarySorted xs w p P) (hk : xs.size < 2 ^ k) : + Monotone (fun i : Fin (range xs w p c wx k hs hk).length => + w (SliceCursor.values xs (range xs w p c wx k hs hk) i) % P) := + BinarySlice.slice_sorted xs (fun y => w y % p) (fun y => w y % P) + ((c - wx) % p) k hs hk ht + +def forward (xs : Array β) (wl : α → ℤ) (wr : β → ℤ) (p P c : ℤ) (k : ℕ) + (hs : PrimarySorted xs wr p) (hk : xs.size < 2 ^ k) (x : α) : PairCursor.State α xs.size := + ⟨x, SliceModular.forward xs (range xs wr p c (wl x) k hs hk) + (fun y => wr y % P) P (wl x % P) k⟩ + +def reverse (xs : Array β) (wl : α → ℤ) (wr : β → ℤ) (p P c v : ℤ) (k : ℕ) + (hs : PrimarySorted xs wr p) (hk : xs.size < 2 ^ k) (x : α) : PairCursor.State α xs.size := + ⟨x, SliceModular.reverse xs (range xs wr p c (wl x) k hs hk) + (fun y => wr y % P) ((v - wl x) % P) k⟩ + +theorem eligible (p c x y : ℤ) : + (x + y) % p = c % p ↔ y % p = (c - x) % p := by + change Int.ModEq p (x + y) c ↔ Int.ModEq p y (c - x) + constructor + · intro h + simpa only [add_sub_cancel_left] using h.sub_right x + · intro h + simpa only [add_sub_cancel] using h.add_left x + +theorem range_slice (xs : Array β) (wr : β → ℤ) (p c wx : ℤ) (k : ℕ) + (hs : PrimarySorted xs wr p) (hk : xs.size < 2 ^ k) : + SliceCursor.slice xs (range xs wr p c wx k hs hk) = + xs.toList.filter (fun y => decide ((wx + wr y) % p = c % p)) := by + rw [range, BinarySlice.slice_eq_filter] + congr 1 + funext y + simp only [← eligible p c wx (wr y)] + +theorem forward_perm (xs : Array β) (wl : α → ℤ) (wr : β → ℤ) (p P c : ℤ) (k : ℕ) + (hs : PrimarySorted xs wr p) (ht : SecondarySorted xs wr p P) + (hk : xs.size < 2 ^ k) (x : α) : + (PairCursor.output xs (forward xs wl wr p P c k hs hk x)).Perm + ((xs.toList.filter (fun y => decide ((wl x + wr y) % p = c % p))).map (fun y => (x, y))) := by + have h := SliceModular.forward_perm xs (range xs wr p c (wl x) k hs hk) + (fun y => wr y % P) P (wl x % P) k (range_length xs wr p c (wl x) k hs hk) + (range_sorted xs wr p P c (wl x) k hs ht hk) + rw [range_slice xs wr p c (wl x) k hs hk] at h + exact h.map (fun y => (x, y)) + +theorem reverse_perm (xs : Array β) (wl : α → ℤ) (wr : β → ℤ) (p P c v : ℤ) (k : ℕ) + (hs : PrimarySorted xs wr p) (ht : SecondarySorted xs wr p P) + (hk : xs.size < 2 ^ k) (x : α) : + (PairCursor.output xs (reverse xs wl wr p P c v k hs hk x)).Perm + ((xs.toList.filter (fun y => decide ((wl x + wr y) % p = c % p))).map (fun y => (x, y))) := by + have h := SliceModular.reverse_perm xs (range xs wr p c (wl x) k hs hk) + (fun y => wr y % P) ((v - wl x) % P) k (range_length xs wr p c (wl x) k hs hk) + (range_sorted xs wr p P c (wl x) k hs ht hk) + rw [range_slice xs wr p c (wl x) k hs hk] at h + exact h.map (fun y => (x, y)) + +theorem forward_sorted (xs : Array β) (wl : α → ℤ) (wr : β → ℤ) (p P c : ℤ) (k : ℕ) + (hs : PrimarySorted xs wr p) (ht : SecondarySorted xs wr p P) + (hk : xs.size < 2 ^ k) (hP : 0 < P) (x : α) : + (PairCursor.output xs (forward xs wl wr p P c k hs hk x)).Pairwise + (fun a b => (wl a.1 + wr a.2) % P ≤ (wl b.1 + wr b.2) % P) := by + have h := SliceModular.forward_sorted xs (range xs wr p c (wl x) k hs hk) + (fun y => wr y % P) P (wl x % P) k (range_length xs wr p c (wl x) k hs hk) + (range_sorted xs wr p P c (wl x) k hs ht hk) + (Int.emod_nonneg _ hP.ne') (Int.emod_lt_of_pos _ hP) + (fun y _ => ⟨Int.emod_nonneg _ hP.ne', Int.emod_lt_of_pos _ hP⟩) + change ((SliceCursor.output xs _).map (fun y => (x, y))).Pairwise _ + rw [List.pairwise_map] + simpa only [forward, Int.add_emod, Int.emod_emod] using h + +theorem reverse_sorted (xs : Array β) (wl : α → ℤ) (wr : β → ℤ) (p P c v : ℤ) (k : ℕ) + (hs : PrimarySorted xs wr p) (ht : SecondarySorted xs wr p P) + (hk : xs.size < 2 ^ k) (hP : 0 < P) (x : α) : + (PairCursor.output xs (reverse xs wl wr p P c v k hs hk x)).Pairwise + (fun a b => (v - wl a.1 - wr a.2) % P ≤ (v - wl b.1 - wr b.2) % P) := by + have h := SliceModular.reverse_sorted xs (range xs wr p c (wl x) k hs hk) + (fun y => wr y % P) P ((v - wl x) % P) k (range_length xs wr p c (wl x) k hs hk) + (range_sorted xs wr p P c (wl x) k hs ht hk) + (Int.emod_nonneg _ hP.ne') (Int.emod_lt_of_pos _ hP) + (fun y _ => ⟨Int.emod_nonneg _ hP.ne', Int.emod_lt_of_pos _ hP⟩) + change ((SliceCursor.output xs _).map (fun y => (x, y))).Pairwise _ + rw [List.pairwise_map] + simpa only [reverse, Int.sub_emod, Int.emod_emod] using h + +end FilteredRow +end LowSpaceSubsetSum + +end OAI diff --git a/lean/OAI/Combinatorics/LowSpaceSubsetSum/Streams/FilteredStream.lean b/lean/OAI/Combinatorics/LowSpaceSubsetSum/Streams/FilteredStream.lean new file mode 100644 index 0000000000000000000000000000000000000000..177af66e4783082403449c0ff0c5e9417f3c8e77 --- /dev/null +++ b/lean/OAI/Combinatorics/LowSpaceSubsetSum/Streams/FilteredStream.lean @@ -0,0 +1,187 @@ +import OAI.Combinatorics.LowSpaceSubsetSum.Streams.ResidueSort +import OAI.Combinatorics.LowSpaceSubsetSum.Streams.PaddedRows + +namespace OAI + +/-! +# The complete executable modular pair stream + +Concrete lexicographic sorting, binary slice/pivot row initialization, empty +leaf padding and tournament merging are composed here. The actual merge state +stores only its tree of constant-size row cursors. All Cartesian lists and +multisets in the statements are proof views. +-/ + +namespace LowSpaceSubsetSum +namespace FilteredStream + +variable {α β : Type*} + +inductive Mode where + | direct + | complementary (target : ℤ) + +def key (wl : α → ℤ) (wr : β → ℤ) (P : ℤ) : Mode → (α × β) → ℤ + | .direct, z => (wl z.1 + wr z.2) % P + | .complementary v, z => (v - wl z.1 - wr z.2) % P + +def steps (n : ℕ) : ℕ := Nat.clog 2 n + 1 + +theorem steps_sufficient (n : ℕ) : n < 2 ^ steps n := by + have h := Nat.le_pow_clog (by decide : 1 < 2) n + have hp : 0 < 2 ^ Nat.clog 2 n := by positivity + rw [steps, pow_succ] + omega + +theorem steps_le_index_bits (N n : ℕ) (hN : N ≤ 2 ^ n) : steps N ≤ n + 1 := by + exact Nat.add_le_add_right (Nat.clog_le_of_le_pow hN) 1 + +def row (right : Array β) (wl : α → ℤ) (wr : β → ℤ) (p P c : ℤ) + (hs : FilteredRow.PrimarySorted right wr p) (mode : Mode) (x : α) : + PairCursor.State α right.size := + match mode with + | .direct => FilteredRow.forward right wl wr p P c (steps right.size) + hs (steps_sufficient right.size) x + | .complementary v => FilteredRow.reverse right wl wr p P c v (steps right.size) + hs (steps_sufficient right.size) x + +theorem row_sorted (right : Array β) (wl : α → ℤ) (wr : β → ℤ) (p P c : ℤ) + (hs : FilteredRow.PrimarySorted right wr p) + (ht : FilteredRow.SecondarySorted right wr p P) (hP : 0 < P) (mode : Mode) (x : α) : + (PairCursor.output right (row right wl wr p P c hs mode x)).Pairwise + (fun a b => key wl wr P mode a ≤ key wl wr P mode b) := by + cases mode with + | direct => exact FilteredRow.forward_sorted right wl wr p P c _ hs ht _ hP x + | complementary v => exact FilteredRow.reverse_sorted right wl wr p P c v _ hs ht _ hP x + +theorem row_perm (right : Array β) (wl : α → ℤ) (wr : β → ℤ) (p P c : ℤ) + (hs : FilteredRow.PrimarySorted right wr p) + (ht : FilteredRow.SecondarySorted right wr p P) (mode : Mode) (x : α) : + (PairCursor.output right (row right wl wr p P c hs mode x)).Perm + ((right.toList.filter (fun y => decide ((wl x + wr y) % p = c % p))).map (fun y => (x, y))) := by + cases mode with + | direct => exact FilteredRow.forward_perm right wl wr p P c _ hs ht _ x + | complementary v => exact FilteredRow.reverse_perm right wl wr p P c v _ hs ht _ x + +abbrev Cursor (right : Array β) := Option (PairCursor.State α right.size) + +def read (right : Array β) : Cursor (α := α) right → Option ((α × β) × Cursor (α := α) right) := + PaddedRows.next (PairCursor.next right) + +def view (right : Array β) : Cursor (α := α) right → List (α × β) := + PaddedRows.view (PairCursor.output right) + +theorem reader (right : Array β) : RowMerge.IsReader (read (α := α) right) (view right) := + PaddedRows.reader _ _ (PairCursor.reader right) + +def rowArray (left : Array α) (right : Array β) (wl : α → ℤ) (wr : β → ℤ) (p P c : ℤ) + (hs : FilteredRow.PrimarySorted right wr p) (mode : Mode) : Array (PairCursor.State α right.size) := + left.map (row right wl wr p P c hs mode) + +theorem array_sorted (left : Array α) (right : Array β) (wl : α → ℤ) (wr : β → ℤ) (p P c : ℤ) + (hs : FilteredRow.PrimarySorted right wr p) (ht : FilteredRow.SecondarySorted right wr p P) + (hP : 0 < P) (mode : Mode) (d : ℕ) (path : RowMerge.Path d) : + (view right (PaddedRows.rows (rowArray left right wl wr p P c hs mode) d path)).Pairwise + (fun a b => key wl wr P mode a ≤ key wl wr P mode b) := by + apply PaddedRows.rows_sorted + intro s hmem + simp only [rowArray, Array.toList_map, List.mem_map] at hmem + obtain ⟨x, _, rfl⟩ := hmem + exact row_sorted right wl wr p P c hs ht hP mode x + +def start (left : Array α) (right : Array β) (wl : α → ℤ) (wr : β → ℤ) (p P c : ℤ) + (hs : FilteredRow.PrimarySorted right wr p) (ht : FilteredRow.SecondarySorted right wr p P) + (hP : 0 < P) (mode : Mode) : + MergedReader.State (key wl wr P mode) (view right) (Nat.clog 2 left.size) := + MergedReader.start (key wl wr P mode) (read right) (view right) (reader right) + (PaddedRows.rows (rowArray left right wl wr p P c hs mode) _) + (array_sorted left right wl wr p P c hs ht hP mode _) + +theorem output_bag (left : Array α) (right : Array β) (wl : α → ℤ) (wr : β → ℤ) (p P c : ℤ) + (hs : FilteredRow.PrimarySorted right wr p) (ht : FilteredRow.SecondarySorted right wr p P) + (hP : 0 < P) (mode : Mode) : + (MergedReader.output (key wl wr P mode) (read right) (view right) + (start left right wl wr p P c hs ht hP mode) : Multiset (α × β)) = + ∑ i : Fin left.size, + ((right.toList.filter (fun y => decide ((wl left[i.val] + wr y) % p = c % p))).map + (fun y => (left[i.val], y)) : Multiset (α × β)) := by + rw [start, MergedReader.start_output_bag] + have hd : (rowArray left right wl wr p P c hs mode).size ≤ 2 ^ Nat.clog 2 left.size := by + simpa only [rowArray, Array.size_map] using Nat.le_pow_clog (by decide : 1 < 2) left.size + change (∑ path : RowMerge.Path (Nat.clog 2 left.size), + (PaddedRows.view (PairCursor.output right) + (PaddedRows.rows (rowArray left right wl wr p P c hs mode) _ path) : Multiset (α × β))) = _ + rw [PaddedRows.row_bag _ _ hd] + have hsize : (rowArray left right wl wr p P c hs mode).size = left.size := by + simp only [rowArray, Array.size_map] + apply Fintype.sum_equiv (finCongr hsize) + intro i + have hin : i.val < left.size := by rw [← hsize]; exact i.isLt + simp only [rowArray, Array.getElem_map] + exact Quot.sound (row_perm right wl wr p P c hs ht mode left[i.val]) + +def sortedStart (left : Array α) (right : Array β) (wl : α → ℤ) (wr : β → ℤ) (p P c : ℤ) + (hP : 0 < P) (mode : Mode) : + MergedReader.State (key wl wr P mode) (view (ResidueSort.sort right wr p P)) + (Nat.clog 2 left.size) := + start left (ResidueSort.sort right wr p P) wl wr p P c + (ResidueSort.primary right wr p P) (ResidueSort.secondary right wr p P) hP mode + +theorem sorted_output_bag (left : Array α) (right : Array β) + (wl : α → ℤ) (wr : β → ℤ) (p P c : ℤ) (hP : 0 < P) (mode : Mode) : + (MergedReader.output (key wl wr P mode) (read (ResidueSort.sort right wr p P)) + (view (ResidueSort.sort right wr p P)) (sortedStart left right wl wr p P c hP mode) : + Multiset (α × β)) = + ∑ i : Fin left.size, + ((right.toList.filter (fun y => decide ((wl left[i.val] + wr y) % p = c % p))).map + (fun y => (left[i.val], y)) : Multiset (α × β)) := by + rw [sortedStart, output_bag] + apply Finset.sum_congr rfl + intro i _ + exact Quot.sound (((ResidueSort.permutation right wr p P).filter + (fun y => decide ((wl left[i.val] + wr y) % p = c % p))).map (fun y => (left[i.val], y))) + +theorem sorted_output_sorted (left : Array α) (right : Array β) + (wl : α → ℤ) (wr : β → ℤ) (p P c : ℤ) (hP : 0 < P) (mode : Mode) : + (MergedReader.output (key wl wr P mode) (read (ResidueSort.sort right wr p P)) + (view (ResidueSort.sort right wr p P)) (sortedStart left right wl wr p P c hP mode)).Pairwise + (fun a b => key wl wr P mode a ≤ key wl wr P mode b) := + MergedReader.output_sorted _ _ _ (reader _) _ + +theorem state_nodes (left : Array α) (right : Array β) + (wl : α → ℤ) (wr : β → ℤ) (p P c : ℤ) (hP : 0 < P) (mode : Mode) : + Tournament.nodes (sortedStart left right wl wr p P c hP mode).tree + 1 ≤ + 4 * (left.size + 1) := Tournament.padded_nodes_le left.size _ + +theorem sorted_output_mem (left : Array α) (right : Array β) + (wl : α → ℤ) (wr : β → ℤ) (p P c : ℤ) (hP : 0 < P) (mode : Mode) (z : α × β) : + z ∈ MergedReader.output (key wl wr P mode) (read (ResidueSort.sort right wr p P)) + (view (ResidueSort.sort right wr p P)) (sortedStart left right wl wr p P c hP mode) ↔ + z.1 ∈ left.toList ∧ z.2 ∈ right.toList ∧ (wl z.1 + wr z.2) % p = c % p := by + change z ∈ (MergedReader.output (key wl wr P mode) (read (ResidueSort.sort right wr p P)) + (view (ResidueSort.sort right wr p P)) (sortedStart left right wl wr p P c hP mode) : + Multiset (α × β)) ↔ _ + rw [sorted_output_bag] + simp only [Multiset.mem_sum, Finset.mem_univ, true_and, Multiset.mem_coe, + List.mem_map, List.mem_filter, decide_eq_true_eq] + constructor + · rintro ⟨i, y, ⟨hy, hmod⟩, heq⟩ + have hz₁ : left[i.val] = z.1 := congrArg Prod.fst heq + have hz₂ : y = z.2 := congrArg Prod.snd heq + subst y + refine ⟨?_, hy, ?_⟩ + · rw [← hz₁] + exact List.mem_iff_getElem.mpr ⟨i.val, by simp, by simp⟩ + · simpa only [hz₁] using hmod + · rintro ⟨hx, hy, hmod⟩ + obtain ⟨i, hi, hix⟩ := List.mem_iff_getElem.mp hx + have hin : i < left.size := by simpa only [Array.length_toList] using hi + rw [Array.getElem_toList] at hix + refine ⟨⟨i, hin⟩, z.2, ⟨hy, ?_⟩, ?_⟩ + · simpa only [hix] using hmod + · exact Prod.ext hix rfl + +end FilteredStream +end LowSpaceSubsetSum + +end OAI diff --git a/lean/OAI/Combinatorics/LowSpaceSubsetSum/Streams/JoinOne.lean b/lean/OAI/Combinatorics/LowSpaceSubsetSum/Streams/JoinOne.lean new file mode 100644 index 0000000000000000000000000000000000000000..c3dd438aac9a8db1ac3bba0b67374a8bbde52bc2 --- /dev/null +++ b/lean/OAI/Combinatorics/LowSpaceSubsetSum/Streams/JoinOne.lean @@ -0,0 +1,219 @@ +import OAI.Combinatorics.LowSpaceSubsetSum.Streams.BufferReplay + +namespace OAI + +/-! +# Reporting one item's matches against a buffered tie group + +The immutable prefix buffer is reused. A generator suffix is restored only +when the group was longer than the buffer. The callback may stop in either +part; its work and stream queries are bounded on every outcome. +-/ + +namespace LowSpaceSubsetSum +namespace JoinOne + +universe u v w + +variable {α : Type u} {σ : Type v} {τ : Type w} + +def run (read : σ → Option (α × σ)) (key : α → ℤ) (K : ℤ) + (report : α → τ → τ × Bool) (buffer : Array α) (saved : σ) + (long : Bool) (fuel : ℕ) (a : τ) : TieReplay.Result σ τ := + let first := BufferReplay.run key K report buffer a + if first.halted then + ⟨saved, first.state, first.queries, first.reports, false, true⟩ + else if long then + let rest := TieReplay.run read key K report fuel saved first.state + ⟨rest.cursor, rest.state, first.queries + rest.queries, + first.reports + rest.reports, rest.complete, rest.halted⟩ + else ⟨saved, first.state, first.queries, first.reports, true, false⟩ + +theorem reports_le (read : σ → Option (α × σ)) (key : α → ℤ) (K : ℤ) + (report : α → τ → τ × Bool) (view : σ → List α) (hread : RowMerge.IsReader read view) + (buffer : Array α) (saved : σ) (long : Bool) (fuel : ℕ) (a : τ) : + (run read key K report buffer saved long fuel a).reports ≤ + buffer.size + (TieBuffer.groupView key K view saved).length := by + have hb := BufferReplay.reports_le key K report buffer a + dsimp only [run] + split + · exact hb.trans (Nat.le_add_right _ _) + · split + · have hr := TieReplay.run_reports_le_potential read key K report view hread + fuel saved (BufferReplay.run key K report buffer a).state + exact Nat.add_le_add hb hr + · exact hb.trans (Nat.le_add_right _ _) + +theorem queries_le (read : σ → Option (α × σ)) (key : α → ℤ) (K : ℤ) + (report : α → τ → τ × Bool) (view : σ → List α) (hread : RowMerge.IsReader read view) + (buffer : Array α) (saved : σ) (long : Bool) (fuel : ℕ) (a : τ) : + (run read key K report buffer saved long fuel a).queries ≤ + buffer.size + (TieBuffer.groupView key K view saved).length + 1 := by + have hb := BufferReplay.queries_le key K report buffer a + dsimp only [run] + split + · dsimp only + omega + · split + · have hr := TieReplay.run_queries_le_potential read key K report view hread + fuel saved (BufferReplay.run key K report buffer a).state + dsimp only + omega + · dsimp only + omega + +theorem halted_false (read : σ → Option (α × σ)) (key : α → ℤ) (K : ℤ) + (report : α → τ → τ × Bool) (hreport : ∀ x a, (report x a).2 = false) + (buffer : Array α) (saved : σ) (long : Bool) (fuel : ℕ) (a : τ) : + (run read key K report buffer saved long fuel a).halted = false := by + have hb : (BufferReplay.run key K report buffer a).halted = false := + TieReplay.run_halted_false _ _ _ _ hreport _ _ _ + simp only [run, hb, Bool.false_eq_true, ite_false] + split + · exact TieReplay.run_halted_false _ _ _ _ hreport _ _ _ + · rfl + +/-- Completed reporting is precisely prefix reporting followed by suffix +reporting; a short group has no suffix to restore. -/ +theorem state_complete (read : σ → Option (α × σ)) (key : α → ℤ) (K : ℤ) + (report : α → τ → τ × Bool) (hreport : ∀ x a, (report x a).2 = false) + (view : σ → List α) (hread : RowMerge.IsReader read view) + (buffer : Array α) (hkeys : ∀ x ∈ buffer.toList, key x = K) + (saved : σ) (fuel : ℕ) (a : τ) + (hfuel : (TieBuffer.groupView key K view saved).length ≤ fuel) : + (run read key K report buffer saved (TieBuffer.hasKey read key K saved) fuel a).state = + (buffer.toList ++ TieBuffer.groupView key K view saved).foldl + (fun a x => (report x a).1) a := by + have hb : (BufferReplay.run key K report buffer a).halted = false := + TieReplay.run_halted_false _ _ _ _ hreport _ _ _ + have hs := BufferReplay.state_complete key K report hreport buffer a hkeys + simp only [run, hb, Bool.false_eq_true, ite_false] + by_cases hl : TieBuffer.hasKey read key K saved = true + · simp only [hl, ite_true] + rw [TieReplay.run_state_complete read key K report hreport view hread fuel saved _ hfuel, + hs, List.foldl_append] + · have he : TieBuffer.groupView key K view saved = [] := by + by_contra he + exact hl ((TieBuffer.hasKey_iff read key K view hread saved).mpr he) + have hfalse : TieBuffer.hasKey read key K saved = false := Bool.eq_false_iff.mpr hl + simp only [hfalse, Bool.false_eq_true, ite_false, he, List.append_nil] + exact hs + +theorem suffix_empty (read : σ → Option (α × σ)) (key : α → ℤ) (K : ℤ) + (report : α → τ → τ × Bool) (hreport : ∀ x a, (report x a).2 = false) + (view : σ → List α) (hread : RowMerge.IsReader read view) + (buffer : Array α) (saved : σ) (fuel : ℕ) (a : τ) + (hfuel : (TieBuffer.groupView key K view saved).length ≤ fuel) : + TieBuffer.groupView key K view + (run read key K report buffer saved (TieBuffer.hasKey read key K saved) fuel a).cursor = [] := by + have hb : (BufferReplay.run key K report buffer a).halted = false := + TieReplay.run_halted_false _ _ _ _ hreport _ _ _ + simp only [run, hb, Bool.false_eq_true, ite_false] + by_cases hl : TieBuffer.hasKey read key K saved = true + · simp only [hl, ite_true] + have h := (TieReplay.runAcc_nonhalting_spec read key K report hreport view hread + fuel saved (BufferReplay.run key K report buffer a).state 0 0).2.2.1 + exact h.trans (List.drop_eq_nil_of_le hfuel) + · simp only [Bool.eq_false_iff.mpr hl, Bool.false_eq_true, ite_false] + by_contra he + exact hl ((TieBuffer.hasKey_iff read key K view hread saved).mpr he) + +theorem view_complete (read : σ → Option (α × σ)) (key : α → ℤ) (K : ℤ) + (report : α → τ → τ × Bool) (hreport : ∀ x a, (report x a).2 = false) + (view : σ → List α) (hread : RowMerge.IsReader read view) + (buffer : Array α) (saved : σ) (fuel : ℕ) (a : τ) + (hfuel : (TieBuffer.groupView key K view saved).length ≤ fuel) : + view saved = TieBuffer.groupView key K view saved ++ + view (run read key K report buffer saved (TieBuffer.hasKey read key K saved) fuel a).cursor := by + have hb : (BufferReplay.run key K report buffer a).halted = false := + TieReplay.run_halted_false _ _ _ _ hreport _ _ _ + simp only [run, hb, Bool.false_eq_true, ite_false] + by_cases hl : TieBuffer.hasKey read key K saved = true + · simp only [hl, ite_true] + have h := (TieReplay.runAcc_nonhalting_spec read key K report hreport view hread + fuel saved (BufferReplay.run key K report buffer a).state 0 0).2.2.2 + simpa only [TieReplay.run, List.take_of_length_le hfuel] using h + · have he : TieBuffer.groupView key K view saved = [] := by + by_contra he + exact hl ((TieBuffer.hasKey_iff read key K view hread saved).mpr he) + simp only [Bool.eq_false_iff.mpr hl, Bool.false_eq_true, ite_false, he, List.nil_append] + +def runFilled (read : σ → Option (α × σ)) (key : α → ℤ) (K : ℤ) + (report : α → τ → τ × Bool) (B fuel : ℕ) (s : σ) (a : τ) : TieReplay.Result σ τ := + let filled := TieBuffer.fill read key K B s + run read key K report filled.buffer filled.cursor + (TieBuffer.hasKey read key K filled.cursor) fuel a + +theorem filled_reports_le (read : σ → Option (α × σ)) (key : α → ℤ) (K : ℤ) + (report : α → τ → τ × Bool) (view : σ → List α) (hread : RowMerge.IsReader read view) + (B fuel : ℕ) (s : σ) (a : τ) : + (runFilled read key K report B fuel s a).reports ≤ + (TieBuffer.groupView key K view s).length := by + have h := reports_le read key K report view hread (TieBuffer.fill read key K B s).buffer + (TieBuffer.fill read key K B s).cursor + (TieBuffer.hasKey read key K (TieBuffer.fill read key K B s).cursor) fuel a + have hb := congrArg List.length (TieBuffer.fill_buffer read key K view hread B s) + rw [TieBuffer.fill_suffix read key K view hread B s] at h + simp only [Array.length_toList, List.length_take] at hb + simp only [List.length_drop] at h + dsimp only [runFilled] + omega + +theorem filled_queries_le (read : σ → Option (α × σ)) (key : α → ℤ) (K : ℤ) + (report : α → τ → τ × Bool) (view : σ → List α) (hread : RowMerge.IsReader read view) + (B fuel : ℕ) (s : σ) (a : τ) : + (runFilled read key K report B fuel s a).queries ≤ + (TieBuffer.groupView key K view s).length + 1 := by + have h := queries_le read key K report view hread (TieBuffer.fill read key K B s).buffer + (TieBuffer.fill read key K B s).cursor + (TieBuffer.hasKey read key K (TieBuffer.fill read key K B s).cursor) fuel a + have hb := congrArg List.length (TieBuffer.fill_buffer read key K view hread B s) + rw [TieBuffer.fill_suffix read key K view hread B s] at h + simp only [Array.length_toList, List.length_take] at hb + simp only [List.length_drop] at h + dsimp only [runFilled] + omega + +theorem filled_state_complete (read : σ → Option (α × σ)) (key : α → ℤ) (K : ℤ) + (report : α → τ → τ × Bool) (hreport : ∀ x a, (report x a).2 = false) + (view : σ → List α) (hread : RowMerge.IsReader read view) + (B fuel : ℕ) (s : σ) (a : τ) + (hfuel : (TieBuffer.groupView key K view s).length ≤ fuel) : + (runFilled read key K report B fuel s a).state = + (TieBuffer.groupView key K view s).foldl (fun a x => (report x a).1) a := by + have hf : (TieBuffer.groupView key K view (TieBuffer.fill read key K B s).cursor).length ≤ + fuel := by + rw [TieBuffer.fill_suffix read key K view hread B s, List.length_drop] + omega + have h := state_complete read key K report hreport view hread + (TieBuffer.fill read key K B s).buffer + (BufferReplay.filled_buffer_keys read key K view hread B s) + (TieBuffer.fill read key K B s).cursor fuel a hf + rw [TieBuffer.fill_buffer read key K view hread B s, + TieBuffer.fill_suffix read key K view hread B s, List.take_append_drop] at h + exact h + +theorem filled_view_complete (read : σ → Option (α × σ)) (key : α → ℤ) (K : ℤ) + (report : α → τ → τ × Bool) (hreport : ∀ x a, (report x a).2 = false) + (view : σ → List α) (hread : RowMerge.IsReader read view) + (B fuel : ℕ) (s : σ) (a : τ) + (hfuel : (TieBuffer.groupView key K view s).length ≤ fuel) : + view s = TieBuffer.groupView key K view s ++ + view (runFilled read key K report B fuel s a).cursor := by + have hf : (TieBuffer.groupView key K view (TieBuffer.fill read key K B s).cursor).length ≤ + fuel := by + rw [TieBuffer.fill_suffix read key K view hread B s, List.length_drop] + omega + have hs := view_complete read key K report hreport view hread + (TieBuffer.fill read key K B s).buffer (TieBuffer.fill read key K B s).cursor fuel a hf + have h := (TieBuffer.fillAcc_spec read key K view hread B s #[] 0).2.1 + change view s = (TieBuffer.groupView key K view s).take B ++ + view (TieBuffer.fill read key K B s).cursor at h + rw [hs, TieBuffer.fill_suffix read key K view hread B s, ← List.append_assoc, + List.take_append_drop] at h + exact h + +end JoinOne +end LowSpaceSubsetSum + +end OAI diff --git a/lean/OAI/Combinatorics/LowSpaceSubsetSum/Streams/JoinReaderMap.lean b/lean/OAI/Combinatorics/LowSpaceSubsetSum/Streams/JoinReaderMap.lean new file mode 100644 index 0000000000000000000000000000000000000000..2cc1fd758e3890a9f2feb7c3b36bfa714e25895f --- /dev/null +++ b/lean/OAI/Combinatorics/LowSpaceSubsetSum/Streams/JoinReaderMap.lean @@ -0,0 +1,269 @@ +import OAI.Combinatorics.LowSpaceSubsetSum.Streams.JoinUserMap + +namespace OAI + +/-! # Stored-record erasure through buffered joins + +The erasure maps both emitted records and reader cursors. Counters and stop +flags are preserved, so the work ledger can be transferred to the source +parent task without changing the order of equal-weight occurrences. +-/ + +namespace LowSpaceSubsetSum + +universe u v s t w z +variable {α : Type u} {β : Type v} {σ : Type s} {σ' : Type t} + {τ : Type w} {τ' : Type z} + +namespace TieBuffer + +def mapAll (f : α → β) (g : σ → σ') (r : Result α σ) : Result β σ' := + ⟨r.buffer.map f, g r.cursor, r.queries⟩ + +theorem fillAcc_map (f : α → β) (g : σ → σ') + (read : σ → Option (α × σ)) (read' : σ' → Option (β × σ')) + (hr : ∀ s, read' (g s) = (read s).map (Prod.map f g)) (key : β → ℤ) (K : ℤ) + (fuel : ℕ) (s : σ) (buf : Array α) (q : ℕ) : + mapAll f g (fillAcc read (fun x => key (f x)) K fuel s buf q) = + fillAcc read' key K fuel (g s) (buf.map f) q := by + induction fuel generalizing s buf q with + | zero => rfl + | succ fuel ih => + cases h : read s with + | none => simp only [fillAcc, hr, h, Option.map_none, mapAll] + | some p => + rcases p with ⟨x, s'⟩ + simp only [fillAcc, hr, h, Option.map_some, Prod.map] + split + · simpa only [Array.map_push] using ih s' (buf.push x) (q + 1) + · rfl + +theorem fill_map (f : α → β) (g : σ → σ') + (read : σ → Option (α × σ)) (read' : σ' → Option (β × σ')) + (hr : ∀ s, read' (g s) = (read s).map (Prod.map f g)) (key : β → ℤ) (K : ℤ) + (B : ℕ) (s : σ) : + mapAll f g (fill read (fun x => key (f x)) K B s) = fill read' key K B (g s) := + by simpa only [fill, Array.map_empty] using fillAcc_map f g read read' hr key K B s #[] 0 + +theorem hasKey_map (f : α → β) (g : σ → σ') + (read : σ → Option (α × σ)) (read' : σ' → Option (β × σ')) + (hr : ∀ s, read' (g s) = (read s).map (Prod.map f g)) (key : β → ℤ) + (K : ℤ) (s : σ) : + hasKey read' key K (g s) = hasKey read (fun x => key (f x)) K s := by + cases h : read s <;> simp only [hasKey, hr, h, Option.map_none, Option.map_some, Prod.map] + +end TieBuffer + +namespace TieReplay + +def mapAll (g : σ → σ') (h : τ → τ') (r : Result σ τ) : Result σ' τ' := + ⟨g r.cursor, h r.state, r.queries, r.reports, r.complete, r.halted⟩ + +theorem runAcc_map (f : α → β) (g : σ → σ') (h : τ → τ') + (read : σ → Option (α × σ)) (read' : σ' → Option (β × σ')) + (hr : ∀ s, read' (g s) = (read s).map (Prod.map f g)) (key : β → ℤ) (K : ℤ) + (report : α → τ → τ × Bool) (report' : β → τ' → τ' × Bool) + (hp : ∀ x a, report' (f x) (h a) = (h (report x a).1, (report x a).2)) + (fuel : ℕ) (s : σ) (a : τ) (q r : ℕ) : + mapAll g h (runAcc read (fun x => key (f x)) K report fuel s a q r) = + runAcc read' key K report' fuel (g s) (h a) q r := by + induction fuel generalizing s a q r with + | zero => rfl + | succ fuel ih => + cases hs : read s with + | none => simp only [runAcc, hr, hs, Option.map_none, mapAll] + | some p => + rcases p with ⟨x, s'⟩ + simp only [runAcc, hr, hs, Option.map_some, Prod.map] + split + · rw [hp] + split + · rfl + · exact ih _ _ _ _ + · rfl + +theorem run_map (f : α → β) (g : σ → σ') (h : τ → τ') + (read : σ → Option (α × σ)) (read' : σ' → Option (β × σ')) + (hr : ∀ s, read' (g s) = (read s).map (Prod.map f g)) (key : β → ℤ) (K : ℤ) + (report : α → τ → τ × Bool) (report' : β → τ' → τ' × Bool) + (hp : ∀ x a, report' (f x) (h a) = (h (report x a).1, (report x a).2)) + (fuel : ℕ) (s : σ) (a : τ) : + mapAll g h (run read (fun x => key (f x)) K report fuel s a) = + run read' key K report' fuel (g s) (h a) := + runAcc_map f g h read read' hr key K report report' hp fuel s a 0 0 + +end TieReplay + +namespace BufferReplay + +theorem read_map (f : α → β) (xs : Array α) (i : ℕ) : + read (xs.map f) i = (read xs i).map (Prod.map f id) := by + simp only [read, Array.size_map] + split <;> simp only [Option.map_some, Option.map_none, Array.getElem_map, Prod.map, id_eq] + +theorem run_map (f : α → β) (key : β → ℤ) (K : ℤ) + (report : β → τ → τ × Bool) (xs : Array α) (a : τ) : + run (fun x => key (f x)) K (fun x => report (f x)) xs a = + run key K report (xs.map f) a := by + have h := TieReplay.run_map f id id (read xs) (read (xs.map f)) + (read_map f xs) key K (fun x => report (f x)) report (fun _ _ => rfl) xs.size 0 a + cases he : TieReplay.run (read xs) (fun x => key (f x)) K + (fun x => report (f x)) xs.size 0 a + simpa only [run, he, TieReplay.mapAll, id_eq, Array.size_map] using h + +end BufferReplay + +namespace JoinOne + +theorem run_map (f : α → β) (g : σ → σ') + (read : σ → Option (α × σ)) (read' : σ' → Option (β × σ')) + (hr : ∀ s, read' (g s) = (read s).map (Prod.map f g)) (key : β → ℤ) (K : ℤ) + (report : β → τ → τ × Bool) (buffer : Array α) (saved : σ) + (long : Bool) (fuel : ℕ) (a : τ) : + TieReplay.mapAll g id + (run read (fun x => key (f x)) K (fun x => report (f x)) buffer saved long fuel a) = + run read' key K report (buffer.map f) (g saved) long fuel a := by + simp only [run, BufferReplay.run_map f key K report] + split + · rfl + · split + · have h := TieReplay.run_map f g id read read' hr key K + (fun x => report (f x)) report (fun _ _ => rfl) fuel saved + (BufferReplay.run key K report (buffer.map f) a).state + cases he : TieReplay.run read (fun x => key (f x)) K + (fun x => report (f x)) fuel saved + (BufferReplay.run key K report (buffer.map f) a).state + simp only [he, TieReplay.mapAll, id_eq] at h + rw [← h] + rfl + · rfl + +end JoinOne + +namespace TieGroup + +variable {α' β' σ₁' σ₂' : Type*} + +def mapReaders (g : σ → σ') (a : State σ τ) : State σ' τ := + ⟨g a.last, a.user, a.queries, a.reports, a.restores⟩ + +def mapReadersResult (g₁ : σ → σ₁') (g₂ : σ' → σ₂') + (r : Result σ σ' τ) : Result σ₁' σ₂' τ := + ⟨TieReplay.mapAll g₁ (mapReaders g₂) r.outer, + r.fillQueries, r.bufferSize, r.snapshot⟩ + +theorem step_mapReaders (f₁ : α → α') (f₂ : β → β') (g : σ → σ') + (read : σ → Option (β × σ)) (read' : σ' → Option (β' × σ')) + (hr : ∀ s, read' (g s) = (read s).map (Prod.map f₂ g)) (key : β' → ℤ) (K : ℤ) + (report : α' → β' → τ → τ × Bool) (buffer : Array β) (saved : σ) + (long : Bool) (fuel : ℕ) (x : α) (a : State σ τ) : + (mapReaders g (step read (fun y => key (f₂ y)) K + (fun x y => report (f₁ x) (f₂ y)) buffer saved long fuel x a).1, + (step read (fun y => key (f₂ y)) K + (fun x y => report (f₁ x) (f₂ y)) buffer saved long fuel x a).2) = + step read' key K report (buffer.map f₂) (g saved) long fuel (f₁ x) (mapReaders g a) := by + simp only [step, ← JoinOne.run_map f₂ g read read' hr key K (report (f₁ x))] + rfl + +theorem run_mapReaders (f₁ : α → α') (f₂ : β → β') (g₁ : σ → σ₁') (g₂ : σ' → σ₂') + (read₁ : σ → Option (α × σ)) (read₁' : σ₁' → Option (α' × σ₁')) + (read₂ : σ' → Option (β × σ')) (read₂' : σ₂' → Option (β' × σ₂')) + (hr₁ : ∀ s, read₁' (g₁ s) = (read₁ s).map (Prod.map f₁ g₁)) + (hr₂ : ∀ s, read₂' (g₂ s) = (read₂ s).map (Prod.map f₂ g₂)) + (key₁ : α' → ℤ) (key₂ : β' → ℤ) (K : ℤ) + (report : α' → β' → τ → τ × Bool) (B fuel₁ fuel₂ : ℕ) + (s₁ : σ) (s₂ : σ') (a : τ) : + mapReadersResult g₁ g₂ + (run read₁ (fun x => key₁ (f₁ x)) read₂ (fun y => key₂ (f₂ y)) K + (fun x y => report (f₁ x) (f₂ y)) B fuel₁ fuel₂ s₁ s₂ a) = + run read₁' key₁ read₂' key₂ K report B fuel₁ fuel₂ (g₁ s₁) (g₂ s₂) a := by + let filled := TieBuffer.fill read₂ (fun y => key₂ (f₂ y)) K B s₂ + let long := TieBuffer.hasKey read₂ (fun y => key₂ (f₂ y)) K filled.cursor + have hp := fun x st => (step_mapReaders f₁ f₂ g₂ read₂ read₂' hr₂ key₂ K + report filled.buffer filled.cursor long fuel₂ x st).symm + have hm := TieReplay.run_map f₁ g₁ (mapReaders g₂) read₁ read₁' hr₁ key₁ K + (step read₂ (fun y => key₂ (f₂ y)) K (fun x y => report (f₁ x) (f₂ y)) + filled.buffer filled.cursor long fuel₂) + (step read₂' key₂ K report (filled.buffer.map f₂) (g₂ filled.cursor) long fuel₂) + hp fuel₁ s₁ ⟨filled.cursor, a, 0, 0, 0⟩ + simp only [run, mapReadersResult, + ← TieBuffer.fill_map f₂ g₂ read₂ read₂' hr₂ key₂ K B s₂, + TieBuffer.mapAll, Array.size_map, + TieBuffer.hasKey_map f₂ g₂ read₂ read₂' hr₂ key₂ K, + TieBuffer.hasKey_map f₁ g₁ read₁ read₁' hr₁ key₁ K] + rw [hm] + rfl + +end TieGroup + +namespace StreamJoin + +variable {α' β' σ₁' σ₂' : Type*} + +def mapReaders (g₁ : σ → σ₁') (g₂ : σ' → σ₂') (a : State σ σ' τ) : State σ₁' σ₂' τ := + ⟨g₁ a.left, g₂ a.right, a.user, a.queries, a.reports, a.copies, a.done⟩ + +def mapReadersStopped (g₁ : σ → σ₁') (g₂ : σ' → σ₂') + (a : StoppedResult σ σ' τ) : StoppedResult σ₁' σ₂' τ := + ⟨mapReaders g₁ g₂ a.state, a.steps⟩ + +theorem step_mapReaders (f₁ : α → α') (f₂ : β → β') (g₁ : σ → σ₁') (g₂ : σ' → σ₂') + (read₁ : σ → Option (α × σ)) (read₁' : σ₁' → Option (α' × σ₁')) + (read₂ : σ' → Option (β × σ')) (read₂' : σ₂' → Option (β' × σ₂')) + (hr₁ : ∀ s, read₁' (g₁ s) = (read₁ s).map (Prod.map f₁ g₁)) + (hr₂ : ∀ s, read₂' (g₂ s) = (read₂ s).map (Prod.map f₂ g₂)) + (key₁ : α' → ℤ) (key₂ : β' → ℤ) (report : α' → β' → τ → τ × Bool) + (B fuel₁ fuel₂ : ℕ) (a : State σ σ' τ) : + mapReaders g₁ g₂ (step read₁ (fun x => key₁ (f₁ x)) read₂ (fun y => key₂ (f₂ y)) + (fun x y => report (f₁ x) (f₂ y)) B fuel₁ fuel₂ a) = + step read₁' key₁ read₂' key₂ report B fuel₁ fuel₂ (mapReaders g₁ g₂ a) := by + by_cases hd : a.done = true + · simp only [step, mapReaders, hd, ↓reduceIte] + · cases h₁ : read₁ a.left with + | none => simp only [step, mapReaders, hd, Bool.false_eq_true, ↓reduceIte, + hr₁, h₁, Option.map_none] + | some p₁ => + rcases p₁ with ⟨x, l⟩ + cases h₂ : read₂ a.right with + | none => simp only [step, mapReaders, hd, Bool.false_eq_true, ↓reduceIte, + hr₁, hr₂, h₁, h₂, Option.map_none, Option.map_some, Prod.map] + | some p₂ => + rcases p₂ with ⟨y, r⟩ + simp only [step, mapReaders, hd, Bool.false_eq_true, ↓reduceIte, + hr₁, hr₂, h₁, h₂, Option.map_some, Prod.map, + ← TieGroup.run_mapReaders f₁ f₂ g₁ g₂ read₁ read₁' read₂ read₂' hr₁ hr₂ + key₁ key₂ (key₁ (f₁ x)) report B fuel₁ fuel₂, + TieGroup.mapReadersResult, TieReplay.mapAll, TieGroup.mapReaders] + split + · rfl + · split <;> rfl + +theorem stoppedAcc_mapReaders (f₁ : α → α') (f₂ : β → β') + (g₁ : σ → σ₁') (g₂ : σ' → σ₂') + (read₁ : σ → Option (α × σ)) (read₁' : σ₁' → Option (α' × σ₁')) + (read₂ : σ' → Option (β × σ')) (read₂' : σ₂' → Option (β' × σ₂')) + (hr₁ : ∀ s, read₁' (g₁ s) = (read₁ s).map (Prod.map f₁ g₁)) + (hr₂ : ∀ s, read₂' (g₂ s) = (read₂ s).map (Prod.map f₂ g₂)) + (key₁ : α' → ℤ) (key₂ : β' → ℤ) (report : α' → β' → τ → τ × Bool) + (B fuel₁ fuel₂ fuel : ℕ) (a : State σ σ' τ) : + mapReadersStopped g₁ g₂ (stoppedAcc read₁ (fun x => key₁ (f₁ x)) + read₂ (fun y => key₂ (f₂ y)) (fun x y => report (f₁ x) (f₂ y)) B fuel₁ fuel₂ fuel a) = + stoppedAcc read₁' key₁ read₂' key₂ report B fuel₁ fuel₂ fuel (mapReaders g₁ g₂ a) := by + induction fuel generalizing a with + | zero => rfl + | succ fuel ih => + by_cases hd : a.done = true + · simp only [stoppedAcc, mapReadersStopped, mapReaders, hd, ↓reduceIte] + · have hdone : (mapReaders g₁ g₂ a).done = a.done := rfl + have hm := ih (step read₁ (fun x => key₁ (f₁ x)) read₂ (fun y => key₂ (f₂ y)) + (fun x y => report (f₁ x) (f₂ y)) B fuel₁ fuel₂ a) + simp only [stoppedAcc, hdone, hd, Bool.false_eq_true, ↓reduceIte] + rw [← step_mapReaders f₁ f₂ g₁ g₂ read₁ read₁' read₂ read₂' hr₁ hr₂ + key₁ key₂ report B fuel₁ fuel₂, ← hm] + rfl + +end StreamJoin + +end LowSpaceSubsetSum + +end OAI diff --git a/lean/OAI/Combinatorics/LowSpaceSubsetSum/Streams/JoinUserMap.lean b/lean/OAI/Combinatorics/LowSpaceSubsetSum/Streams/JoinUserMap.lean new file mode 100644 index 0000000000000000000000000000000000000000..7f68873c4eb5b97e0978ce72f5e2e35601b287ba --- /dev/null +++ b/lean/OAI/Combinatorics/LowSpaceSubsetSum/Streams/JoinUserMap.lean @@ -0,0 +1,187 @@ +import OAI.Combinatorics.LowSpaceSubsetSum.Search.StoppedStreamJoin + +namespace OAI + +/-! # Erasing proof-carrying callback states through the actual join + +This refinement lets a counted dictionary carry its invariant intrinsically, +while retaining exactly the original join's cursors, counters and halt behavior. +-/ + +namespace LowSpaceSubsetSum + +universe u v s t w z +variable {α : Type u} {β : Type v} {σ : Type s} {τ : Type w} {τ' : Type z} + +namespace TieReplay + +def mapUser (f : τ → τ') (r : Result σ τ) : Result σ τ' := + ⟨r.cursor, f r.state, r.queries, r.reports, r.complete, r.halted⟩ + +theorem runAcc_mapUser (read : σ → Option (α × σ)) (key : α → ℤ) (K : ℤ) + (report : α → τ → τ × Bool) (report' : α → τ' → τ' × Bool) (f : τ → τ') + (hf : ∀ x a, report' x (f a) = (f (report x a).1, (report x a).2)) + (fuel : ℕ) (s : σ) (a : τ) (q r : ℕ) : + mapUser f (runAcc read key K report fuel s a q r) = + runAcc read key K report' fuel s (f a) q r := by + induction fuel generalizing s a q r with + | zero => rfl + | succ fuel ih => + cases hr : read s with + | none => simp only [runAcc, hr, mapUser] + | some p => + rcases p with ⟨x, s'⟩ + simp only [runAcc, hr] + split + · rw [hf] + split + · rfl + · exact ih _ _ _ _ + · rfl + +theorem run_mapUser (read : σ → Option (α × σ)) (key : α → ℤ) (K : ℤ) + (report : α → τ → τ × Bool) (report' : α → τ' → τ' × Bool) (f : τ → τ') + (hf : ∀ x a, report' x (f a) = (f (report x a).1, (report x a).2)) + (fuel : ℕ) (s : σ) (a : τ) : + mapUser f (run read key K report fuel s a) = + run read key K report' fuel s (f a) := + runAcc_mapUser read key K report report' f hf fuel s a 0 0 + +end TieReplay + +namespace JoinOne + +theorem run_mapUser (read : σ → Option (α × σ)) (key : α → ℤ) (K : ℤ) + (report : α → τ → τ × Bool) (report' : α → τ' → τ' × Bool) (f : τ → τ') + (hf : ∀ x a, report' x (f a) = (f (report x a).1, (report x a).2)) + (buffer : Array α) (saved : σ) (long : Bool) (fuel : ℕ) (a : τ) : + TieReplay.mapUser f (run read key K report buffer saved long fuel a) = + run read key K report' buffer saved long fuel (f a) := by + simp only [run, BufferReplay.run, + ← TieReplay.run_mapUser (BufferReplay.read buffer) key K report report' f hf, + TieReplay.mapUser] + split + · simp_all only [↓reduceIte] + · simp_all only [Bool.false_eq_true, ↓reduceIte] + split + · simp_all only + have h := TieReplay.run_mapUser read key K report report' f hf fuel saved + (TieReplay.run (BufferReplay.read buffer) key K report buffer.size 0 a).state + cases h₁ : TieReplay.run read key K report fuel saved + (TieReplay.run (BufferReplay.read buffer) key K report buffer.size 0 a).state + simp only [h₁, TieReplay.mapUser] at h + rw [← h] + · simp_all only + +end JoinOne + +namespace TieGroup + +variable {σ₂ : Type t} + +def mapUser (f : τ → τ') (a : State σ₂ τ) : State σ₂ τ' := + ⟨a.last, f a.user, a.queries, a.reports, a.restores⟩ + +def mapResult (f : τ → τ') (r : Result σ σ₂ τ) : Result σ σ₂ τ' := + ⟨TieReplay.mapUser (mapUser f) r.outer, r.fillQueries, r.bufferSize, r.snapshot⟩ + +theorem step_mapUser (read : σ₂ → Option (β × σ₂)) (key : β → ℤ) (K : ℤ) + (report : α → β → τ → τ × Bool) (report' : α → β → τ' → τ' × Bool) (f : τ → τ') + (hf : ∀ x y a, report' x y (f a) = (f (report x y a).1, (report x y a).2)) + (buffer : Array β) (saved : σ₂) (long : Bool) (fuel : ℕ) (x : α) (a : State σ₂ τ) : + (mapUser f (step read key K report buffer saved long fuel x a).1, + (step read key K report buffer saved long fuel x a).2) = + step read key K report' buffer saved long fuel x (mapUser f a) := by + simp only [step, mapUser, + ← JoinOne.run_mapUser read key K (report x) (report' x) f (hf x), TieReplay.mapUser] + +theorem run_mapUser (read₁ : σ → Option (α × σ)) (key₁ : α → ℤ) + (read₂ : σ₂ → Option (β × σ₂)) (key₂ : β → ℤ) (K : ℤ) + (report : α → β → τ → τ × Bool) (report' : α → β → τ' → τ' × Bool) (f : τ → τ') + (hf : ∀ x y a, report' x y (f a) = (f (report x y a).1, (report x y a).2)) + (B fuel₁ fuel₂ : ℕ) (s₁ : σ) (s₂ : σ₂) (a : τ) : + mapResult f (run read₁ key₁ read₂ key₂ K report B fuel₁ fuel₂ s₁ s₂ a) = + run read₁ key₁ read₂ key₂ K report' B fuel₁ fuel₂ s₁ s₂ (f a) := by + let filled := TieBuffer.fill read₂ key₂ K B s₂ + let long := TieBuffer.hasKey read₂ key₂ K filled.cursor + have hstep := fun x st => (step_mapUser read₂ key₂ K report report' f hf + filled.buffer filled.cursor long fuel₂ x st).symm + have h := TieReplay.run_mapUser read₁ key₁ K + (step read₂ key₂ K report filled.buffer filled.cursor long fuel₂) + (step read₂ key₂ K report' filled.buffer filled.cursor long fuel₂) + (mapUser f) hstep fuel₁ s₁ ⟨filled.cursor, a, 0, 0, 0⟩ + change mapResult f ⟨_, filled.queries, filled.buffer.size, _⟩ = _ + unfold mapResult + rw [h] + rfl + +end TieGroup +namespace StreamJoin + +variable {σ₂ : Type t} + +def mapUser (f : τ → τ') (a : State σ σ₂ τ) : State σ σ₂ τ' := + ⟨a.left, a.right, f a.user, a.queries, a.reports, a.copies, a.done⟩ + +def mapStopped (f : τ → τ') (a : StoppedResult σ σ₂ τ) : StoppedResult σ σ₂ τ' := + ⟨mapUser f a.state, a.steps⟩ + +theorem step_mapUser (read₁ : σ → Option (α × σ)) (key₁ : α → ℤ) + (read₂ : σ₂ → Option (β × σ₂)) (key₂ : β → ℤ) + (report : α → β → τ → τ × Bool) (report' : α → β → τ' → τ' × Bool) (f : τ → τ') + (hf : ∀ x y a, report' x y (f a) = (f (report x y a).1, (report x y a).2)) + (B fuel₁ fuel₂ : ℕ) (a : State σ σ₂ τ) : + mapUser f (step read₁ key₁ read₂ key₂ report B fuel₁ fuel₂ a) = + step read₁ key₁ read₂ key₂ report' B fuel₁ fuel₂ (mapUser f a) := by + by_cases hd : a.done = true + · simp only [step, mapUser, hd, ↓reduceIte] + · cases h₁ : read₁ a.left with + | none => simp only [step, mapUser, hd, Bool.false_eq_true, ↓reduceIte, h₁] + | some p₁ => + rcases p₁ with ⟨x, l⟩ + cases h₂ : read₂ a.right with + | none => simp only [step, mapUser, hd, Bool.false_eq_true, ↓reduceIte, h₁, h₂] + | some p₂ => + rcases p₂ with ⟨y, r⟩ + simp only [step, mapUser, hd, Bool.false_eq_true, ↓reduceIte, h₁, h₂, + ← TieGroup.run_mapUser read₁ key₁ read₂ key₂ (key₁ x) report report' f hf, + TieGroup.mapResult, TieReplay.mapUser, TieGroup.mapUser] + split + · simp_all only + · split <;> simp_all only + +theorem stoppedAcc_mapUser (read₁ : σ → Option (α × σ)) (key₁ : α → ℤ) + (read₂ : σ₂ → Option (β × σ₂)) (key₂ : β → ℤ) + (report : α → β → τ → τ × Bool) (report' : α → β → τ' → τ' × Bool) (f : τ → τ') + (hf : ∀ x y a, report' x y (f a) = (f (report x y a).1, (report x y a).2)) + (B fuel₁ fuel₂ fuel : ℕ) (a : State σ σ₂ τ) : + mapStopped f (stoppedAcc read₁ key₁ read₂ key₂ report B fuel₁ fuel₂ fuel a) = + stoppedAcc read₁ key₁ read₂ key₂ report' B fuel₁ fuel₂ fuel (mapUser f a) := by + induction fuel generalizing a with + | zero => rfl + | succ fuel ih => + by_cases hd : a.done = true + · simp only [stoppedAcc, mapStopped, mapUser, hd, ↓reduceIte] + · have h := ih (step read₁ key₁ read₂ key₂ report B fuel₁ fuel₂ a) + have hdone : (mapUser f a).done = a.done := rfl + simp only [stoppedAcc, hdone, hd, Bool.false_eq_true, ↓reduceIte] + rw [← step_mapUser read₁ key₁ read₂ key₂ report report' f hf] + rw [← h] + rfl + +theorem run_mapUser (read₁ : σ → Option (α × σ)) (key₁ : α → ℤ) + (read₂ : σ₂ → Option (β × σ₂)) (key₂ : β → ℤ) + (report : α → β → τ → τ × Bool) (report' : α → β → τ' → τ' × Bool) (f : τ → τ') + (hf : ∀ x y a, report' x y (f a) = (f (report x y a).1, (report x y a).2)) + (B fuel₁ fuel₂ fuel : ℕ) (s₁ : σ) (s₂ : σ₂) (a : τ) : + mapUser f (run read₁ key₁ read₂ key₂ report B fuel₁ fuel₂ fuel s₁ s₂ a) = + run read₁ key₁ read₂ key₂ report' B fuel₁ fuel₂ fuel s₁ s₂ (f a) := by + have h := congrArg StoppedResult.state (stoppedAcc_mapUser read₁ key₁ read₂ key₂ + report report' f hf B fuel₁ fuel₂ fuel (start s₁ s₂ a)) + simpa only [mapStopped, stoppedAcc_eq, mapUser, start, run] using h + +end StreamJoin + +end LowSpaceSubsetSum + +end OAI diff --git a/lean/OAI/Combinatorics/LowSpaceSubsetSum/Streams/MeasuredDistinctCount.lean b/lean/OAI/Combinatorics/LowSpaceSubsetSum/Streams/MeasuredDistinctCount.lean new file mode 100644 index 0000000000000000000000000000000000000000..7115531f40f79d3c195a75f6f8d1e87e3a4ca8f5 --- /dev/null +++ b/lean/OAI/Combinatorics/LowSpaceSubsetSum/Streams/MeasuredDistinctCount.lean @@ -0,0 +1,93 @@ +import OAI.Combinatorics.LowSpaceSubsetSum.Streams.DistinctStreamCount + +namespace OAI + +/-! # Tail-recursive distinct counting with measured reader calls + +Only the current reader state, previous key, count, remaining fuel and work +counter survive each iteration. No list of emitted keys is constructed. +-/ + +namespace LowSpaceSubsetSum.MeasuredDistinctCount + +variable {α σ : Type*} + +def loop (read : σ → Option (α × σ) × ℕ) (key : α → ℤ × ℕ) : + ℕ → σ → Option ℤ → ℕ → ℕ → ℕ × ℕ + | 0, _, _, count, work => (count, work + 1) + | fuel + 1, state, previous, count, work => + let out := read state + match out.1 with + | none => (count, work + out.2 + 1) + | some (x, next) => + let k := key x + let fresh := match previous with | none => true | some p => decide (p ≠ k.1) + loop read key fuel next (some k.1) (count + if fresh then 1 else 0) + (work + out.2 + k.2 + 3) + +theorem loop_value (read : σ → Option (α × σ) × ℕ) (key : α → ℤ × ℕ) + (fuel : ℕ) (s : σ) (previous : Option ℤ) (count work : ℕ) : + (loop read key fuel s previous count work).1 = count + + match previous with + | none => (DistinctStreamCount.run (fun s => (read s).1) (fun x => (key x).1) fuel s).1 + | some p => (DistinctStreamCount.tail (fun s => (read s).1) (fun x => (key x).1) fuel s p).1 := by + induction fuel generalizing s previous count work with + | zero => cases previous <;> simp only [loop, DistinctStreamCount.run, DistinctStreamCount.tail, Nat.add_zero] + | succ fuel ih => + cases previous with + | none => + cases hr : (read s).1 with + | none => simp only [loop, hr, DistinctStreamCount.run, Nat.add_zero] + | some out => + rcases out with ⟨x, next⟩ + simp only [loop, hr, ↓reduceIte, ih, DistinctStreamCount.run] + omega + | some p => + cases hr : (read s).1 with + | none => simp only [loop, hr, DistinctStreamCount.tail, Nat.add_zero] + | some out => + rcases out with ⟨x, next⟩ + by_cases he : p = (key x).1 + · subst p + simp only [loop, hr, ne_eq, not_true_eq_false, decide_false, Bool.false_eq_true, + ↓reduceIte, Nat.add_zero, ih, DistinctStreamCount.tail] + · simp only [loop, hr, ne_eq, he, not_false_eq_true, decide_true, ↓reduceIte, + ih, DistinctStreamCount.tail] + omega + +theorem loop_work (read : σ → Option (α × σ) × ℕ) (key : α → ℤ × ℕ) + (R K : ℕ) (hread : ∀ s, (read s).2 ≤ R) (hkey : ∀ x, (key x).2 ≤ K) + (fuel : ℕ) (s : σ) (previous : Option ℤ) (count work : ℕ) : + (loop read key fuel s previous count work).2 ≤ work + (R + K + 4) * fuel + 1 := by + induction fuel generalizing s previous count work with + | zero => simp only [loop, Nat.mul_zero, Nat.add_zero, le_refl] + | succ fuel ih => + have hr := hread s + simp only [loop] + split + · dsimp only + nlinarith only [hr, Nat.zero_le ((R + K + 4) * fuel)] + next x next _ => + have hk := hkey x + have ht := ih next (some (key x).1) + (count + if (match previous with | none => true | some p => decide (p ≠ (key x).1)) + then 1 else 0) (work + (read s).2 + (key x).2 + 3) + nlinarith only [hr, hk, ht] + +def run (read : σ → Option (α × σ) × ℕ) (key : α → ℤ × ℕ) (fuel : ℕ) (s : σ) : ℕ × ℕ := + loop read key fuel s none 0 0 + +theorem run_value (read : σ → Option (α × σ) × ℕ) (key : α → ℤ × ℕ) (fuel : ℕ) (s : σ) : + (run read key fuel s).1 = + (DistinctStreamCount.run (fun s => (read s).1) (fun x => (key x).1) fuel s).1 := by + simpa only [run, Nat.zero_add] using loop_value read key fuel s none 0 0 + +theorem run_work (read : σ → Option (α × σ) × ℕ) (key : α → ℤ × ℕ) + (R K : ℕ) (hread : ∀ s, (read s).2 ≤ R) (hkey : ∀ x, (key x).2 ≤ K) + (fuel : ℕ) (s : σ) : + (run read key fuel s).2 ≤ (R + K + 4) * fuel + 1 := by + simpa only [run, Nat.zero_add] using loop_work read key R K hread hkey fuel s none 0 0 + +end LowSpaceSubsetSum.MeasuredDistinctCount + +end OAI diff --git a/lean/OAI/Combinatorics/LowSpaceSubsetSum/Streams/MeasuredInitialization.lean b/lean/OAI/Combinatorics/LowSpaceSubsetSum/Streams/MeasuredInitialization.lean new file mode 100644 index 0000000000000000000000000000000000000000..993a961b0ef5c2e9e7f25741ba1b9b6efa39ad9c --- /dev/null +++ b/lean/OAI/Combinatorics/LowSpaceSubsetSum/Streams/MeasuredInitialization.lean @@ -0,0 +1,170 @@ +import OAI.Combinatorics.LowSpaceSubsetSum.Representation.RepresentationWeightedReader + +namespace OAI + +/-! # Measured construction of the row tournament + +Each leaf calls its measured initializer once; each internal node evaluates +its two candidate keys. Binary paths are converted to array indices by an +explicit recursive computation. No row array is constructed by this routine. +-/ + +namespace LowSpaceSubsetSum + +namespace Tournament + +variable {α : Type*} + +def measuredBuild (key : α → ℤ × ℕ) : (d : ℕ) → + ((Fin d → Bool) → Option α × ℕ) → Tree α d × ℕ + | 0, front => + let x := front Fin.elim0 + (.leaf x.1, x.2 + 1) + | d + 1, front => + let l := measuredBuild key d (fun p => front (Fin.cons false p)) + let r := measuredBuild key d (fun p => front (Fin.cons true p)) + let w := measuredPick key (winner l.1) (winner r.1) + (.node w.1 l.1 r.1, l.2 + r.2 + w.2 + 5) + +theorem measuredBuild_value (key : α → ℤ × ℕ) (d : ℕ) + (front : (Fin d → Bool) → Option α × ℕ) : + (measuredBuild key d front).1 = build (fun x => (key x).1) d (fun p => (front p).1) := by + induction d with + | zero => rfl + | succ d ih => simp only [measuredBuild, build, measuredPick_value, ih, node] + +theorem measuredBuild_work (key : α → ℤ × ℕ) (K R : ℕ) + (hk : ∀ x, (key x).2 ≤ K) (d : ℕ) + (front : (Fin d → Bool) → Option α × ℕ) (hf : ∀ p, (front p).2 ≤ R) : + (measuredBuild key d front).2 ≤ (R + 2 * K + 9) * 2 ^ d - (2 * K + 8) := by + induction d with + | zero => simp only [measuredBuild, pow_zero, Nat.mul_one]; have := hf Fin.elim0; omega + | succ d ih => + have hl := ih (fun p => front (Fin.cons false p)) (fun p => hf _) + have hr := ih (fun p => front (Fin.cons true p)) (fun p => hf _) + have hp := measuredPick_work key K hk + (winner (measuredBuild key d (fun p => front (Fin.cons false p))).1) + (winner (measuredBuild key d (fun p => front (Fin.cons true p))).1) + have hpow : 1 ≤ 2 ^ d := Nat.one_le_pow _ _ (by decide) + have hbase : 2 * K + 8 ≤ (R + 2 * K + 9) * 2 ^ d := by nlinarith + simp only [measuredBuild, pow_succ, ← Nat.mul_assoc] + omega + +end Tournament + +namespace PaddedRows + +/-- Little-endian binary evaluation. The cost includes access to a bit in a +path built by at most `d` nested `Fin.cons` nodes. -/ +def measuredIndex : (d : ℕ) → (RowMerge.Path d) → ℕ × ℕ + | 0, _ => (0, 1) + | d + 1, p => + let t := measuredIndex d (fun i => p i.succ) + ((if p 0 then 1 else 0) + 2 * t.1, t.2 + 2 * d + 6) + +private theorem index_sum (d : ℕ) (p : RowMerge.Path d) : + (index d p).val = ∑ i : Fin d, (if p i then 1 else 0) * 2 ^ i.val := by + change (∑ i : Fin d, (finTwoEquiv.symm (p i)).val * 2 ^ i.val) = _ + apply Finset.sum_congr rfl + intro i _ + cases h : p i <;> rfl + +theorem measuredIndex_value (d : ℕ) (p : RowMerge.Path d) : + (measuredIndex d p).1 = (index d p).val := by + induction d with + | zero => simp [measuredIndex] + | succ d ih => + rw [index_sum, Fin.sum_univ_succ] + simp only [measuredIndex, ih, index_sum, Fin.val_zero, pow_zero, Nat.mul_one, + Fin.val_succ, pow_succ'] + rw [Finset.mul_sum] + congr 1 + apply Finset.sum_congr rfl + intro i _ + ring + +theorem measuredIndex_work (d : ℕ) (p : RowMerge.Path d) : + (measuredIndex d p).2 ≤ 4 * (d + 1) ^ 2 := by + induction d with + | zero => norm_num [measuredIndex] + | succ d ih => + have h := ih (fun i => p i.succ) + change _ + 2 * d + 6 ≤ _ + nlinarith + +end PaddedRows +end LowSpaceSubsetSum + +namespace LowSpaceSubsetSum.FilteredStream + +variable {α β : Type*} + +/-- Initialize and read one padded row, directly from the shared arrays. -/ +def measuredFront (left : Array α) (right : Array β) + (row : α → PairCursor.State α right.size × ℕ) (d : ℕ) (p : RowMerge.Path d) : + Option (RowMerge.Front d (α × β) (Cursor (α := α) right)) × ℕ := + let i := PaddedRows.measuredIndex d p + if h : i.1 < left.size then + let r := row left[i.1] + let q := countedRead right (some r.1) + (q.1.map (fun z => ⟨p, z.1, z.2⟩), i.2 + r.2 + q.2 + 6) + else (none, i.2 + 2) + +theorem measuredFront_value (left : Array α) (right : Array β) + (row : α → PairCursor.State α right.size × ℕ) (d : ℕ) (p : RowMerge.Path d) : + (measuredFront left right row d p).1 = + RowMerge.front (read right) p + (PaddedRows.rows (left.map (fun x => (row x).1)) d p) := by + simp only [measuredFront, PaddedRows.measuredIndex_value, PaddedRows.rows, + Array.size_map, RowMerge.front] + split_ifs with h + · simp only [Array.getElem_map, countedRead_value] + · rfl + +theorem measuredFront_work (left : Array α) (right : Array β) + (row : α → PairCursor.State α right.size × ℕ) (R : ℕ) + (hr : ∀ x, (row x).2 ≤ R) (d : ℕ) (p : RowMerge.Path d) : + (measuredFront left right row d p).2 ≤ 4 * (d + 1) ^ 2 + R + 30 := by + have hi := PaddedRows.measuredIndex_work d p + unfold measuredFront + dsimp only + split + · have hr' := hr left[(PaddedRows.measuredIndex d p).1] + have hq := countedRead_work right (some (row left[(PaddedRows.measuredIndex d p).1]).1) + dsimp only + omega + · dsimp only + omega + +def measuredInitialTree (left : Array α) (right : Array β) (key : α × β → ℤ × ℕ) + (row : α → PairCursor.State α right.size × ℕ) (d : ℕ) := + Tournament.measuredBuild + (fun x : RowMerge.Front d (α × β) (Cursor (α := α) right) => key x.value) + d (measuredFront left right row d) + +theorem measuredInitialTree_value (left : Array α) (right : Array β) + (key : α × β → ℤ × ℕ) (row : α → PairCursor.State α right.size × ℕ) (d : ℕ) : + (measuredInitialTree left right key row d).1 = + RowMerge.start (fun x => (key x).1) (read right) + (PaddedRows.rows (left.map (fun x => (row x).1)) d) := by + simp only [measuredInitialTree, Tournament.measuredBuild_value, RowMerge.start] + congr 1 + funext p + exact measuredFront_value left right row d p + +theorem measuredInitialTree_work (left : Array α) (right : Array β) + (key : α × β → ℤ × ℕ) (row : α → PairCursor.State α right.size × ℕ) + (K R : ℕ) (hk : ∀ x, (key x).2 ≤ K) (hr : ∀ x, (row x).2 ≤ R) (d : ℕ) : + (measuredInitialTree left right key row d).2 ≤ + (4 * (d + 1) ^ 2 + R + 2 * K + 39) * 2 ^ d := by + have h := Tournament.measuredBuild_work (fun x => key x.value) K + (4 * (d + 1) ^ 2 + R + 30) (fun x => hk x.value) d + (measuredFront left right row d) (measuredFront_work left right row R hr d) + calc + _ ≤ (4 * (d + 1) ^ 2 + R + 30 + 2 * K + 9) * 2 ^ d - (2 * K + 8) := h + _ ≤ (4 * (d + 1) ^ 2 + R + 30 + 2 * K + 9) * 2 ^ d := Nat.sub_le _ _ + _ = _ := by ring + +end LowSpaceSubsetSum.FilteredStream + +end OAI diff --git a/lean/OAI/Combinatorics/LowSpaceSubsetSum/Streams/MeasuredLog2.lean b/lean/OAI/Combinatorics/LowSpaceSubsetSum/Streams/MeasuredLog2.lean new file mode 100644 index 0000000000000000000000000000000000000000..cb57f37343f2d259ba7b06239d927f17186d8967 --- /dev/null +++ b/lean/OAI/Combinatorics/LowSpaceSubsetSum/Streams/MeasuredLog2.lean @@ -0,0 +1,60 @@ +import Mathlib.Data.Nat.Log + +namespace OAI + +/-! # A bounded tail-recursive binary logarithm + +This is the integer operation needed to turn measured mixer counts into +prime widths. Each iteration divides by two and updates two counters. +-/ + +namespace LowSpaceSubsetSum.MeasuredLog2 + +def loop : ℕ → ℕ → ℕ → ℕ → ℕ × ℕ + | 0, _, value, work => (value, work + 1) + | fuel + 1, x, value, work => + if 2 ≤ x then loop fuel (x / 2) (value + 1) (work + 3) + else (value, work + 1) + +theorem loop_value (fuel x value work : ℕ) (hx : Nat.log2 x ≤ fuel) : + (loop fuel x value work).1 = value + Nat.log2 x := by + induction fuel generalizing x value work with + | zero => + have hz : Nat.log2 x = 0 := by omega + simp [loop, hz] + | succ fuel ih => + rw [loop] + split + next h => + have he := Nat.log2_def x + rw [ite_eq_left h] at he + rw [ih _ _ _ (by omega), he] + omega + next h => simp only [Nat.log2_def x, ite_eq_right h, Nat.add_zero] + +theorem loop_work (fuel x value work : ℕ) : + (loop fuel x value work).2 ≤ work + 3 * fuel + 1 := by + induction fuel generalizing x value work with + | zero => simp [loop] + | succ fuel ih => + rw [loop] + split + · have h := ih (x / 2) (value + 1) (work + 3); omega + · simp only; omega + +def run (bits x : ℕ) : ℕ × ℕ := loop bits x 0 0 + +theorem run_value (bits x : ℕ) (hx : x ≤ 2 ^ bits) : + (run bits x).1 = Nat.log2 x := by + have hlog : Nat.log2 x ≤ bits := by + rw [Nat.log2_eq_log_two] + have h := Nat.log_mono_right (b := 2) hx + simpa only [Nat.log_pow (by decide : 1 < 2)] using h + simpa only [run, Nat.zero_add] using loop_value bits x 0 0 hlog + +theorem run_work (bits x : ℕ) : (run bits x).2 ≤ 3 * bits + 1 := by + simpa only [run, Nat.zero_add] using loop_work bits x 0 0 + +end LowSpaceSubsetSum.MeasuredLog2 + +end OAI diff --git a/lean/OAI/Combinatorics/LowSpaceSubsetSum/Streams/MeasuredMixerCount.lean b/lean/OAI/Combinatorics/LowSpaceSubsetSum/Streams/MeasuredMixerCount.lean new file mode 100644 index 0000000000000000000000000000000000000000..0ce12c5258c11824d6b7ce1a75bfddaa1888935b --- /dev/null +++ b/lean/OAI/Combinatorics/LowSpaceSubsetSum/Streams/MeasuredMixerCount.lean @@ -0,0 +1,93 @@ +import OAI.Combinatorics.LowSpaceSubsetSum.Streams.MeasuredSumReader +import OAI.Combinatorics.LowSpaceSubsetSum.Counting.MixerParameterCount +import OAI.Combinatorics.LowSpaceSubsetSum.Compression.CompressionWeights + +namespace OAI + +/-! # Mixer counts from generated and sorted half-sum arrays + +All subset weights, comparisons, array copies and streamed sum keys are +charged. The returned natural number is the exact distinct-sum count. +-/ + +namespace LowSpaceSubsetSum.MeasuredMixerCount + +variable {n : ℕ} + +def sortedWeights (a : Fin n → ℤ) (indices : List (Fin n)) : Array ℤ × ℕ := + let raw := CompressionWeights.raw a indices + let out := MeasuredSort.sort (fun x y : ℤ => (decide (x ≤ y), 1)) raw.1 + (out.1.toArray, raw.2 + out.2 + out.1.length + 1) + +theorem sortedWeights_value (a : Fin n → ℤ) (V : Finset (Fin n)) : + (sortedWeights a (V.sort (· ≤ ·))).1 = MixerParameterCount.sortedWeights a V := by + simp only [sortedWeights, CompressionWeights.raw_source, MeasuredSort.sort_value, + MixerParameterCount.sortedWeights, CountedSort.sort_value] + +theorem sortedWeights_size (a : Fin n → ℤ) (indices : List (Fin n)) : + (sortedWeights a indices).1.size = 2 ^ indices.length := by + simp only [sortedWeights, List.size_toArray, MeasuredSort.sort_value, + List.length_mergeSort, CompressionWeights.raw_length] + +theorem sortedWeights_sorted (a : Fin n → ℤ) (indices : List (Fin n)) : + (sortedWeights a indices).1.toList.Pairwise (· ≤ ·) := by + simp only [sortedWeights, List.toList_toArray, MeasuredSort.sort_value] + simpa only [decide_eq_true_eq] using + (List.pairwise_mergeSort (le := fun x y : ℤ => decide (x ≤ y)) + (fun x y z hxy hyz => decide_eq_true (le_trans (of_decide_eq_true hxy) (of_decide_eq_true hyz))) + (fun x y => by simpa only [Bool.or_eq_true, decide_eq_true_eq] using le_total x y) + (CompressionWeights.raw a indices).1) + +def coefficient (n : ℕ) : ℕ := (n + 4) * n + 12 * n + 20 + +theorem sortedWeights_work (a : Fin n → ℤ) (indices : List (Fin n)) + (hi : indices.length ≤ n) : + (sortedWeights a indices).2 ≤ coefficient n * 2 ^ indices.length := by + have hr := CompressionWeights.raw_work a indices hi + have hs := MeasuredSort.sort_work (fun x y : ℤ => (decide (x ≤ y), 1)) + 1 (fun _ _ => le_rfl) (CompressionWeights.raw a indices).1 n + (by rw [CompressionWeights.raw_length]; exact Nat.pow_le_pow_right (by decide) hi) + have hp : 1 ≤ 2 ^ indices.length := Nat.one_le_two_pow + simp only [CompressionWeights.raw_length] at hs + change _ + _ + _ + 1 ≤ _ + simp only [MeasuredSort.sort_value, List.length_mergeSort, CompressionWeights.raw_length] + unfold coefficient + nlinarith only [hr, hs, hp] + +def run (a : Fin n → ℤ) (left right : List (Fin n)) : ℕ × ℕ := + let xs := sortedWeights a left + let ys := sortedWeights a right + let out := MeasuredSumReader.count xs.1 ys.1 (sortedWeights_sorted a right) + (out.1, xs.2 + ys.2 + out.2 + 3) + +theorem run_source (a : Fin n → ℤ) (V W : Finset (Fin n)) (hd : Disjoint V W) : + (run a (V.sort (· ≤ ·)) (W.sort (· ≤ ·))).1 = distinctSumCount a (V ∪ W) := by + simp only [run, MeasuredSumReader.count_value, sortedWeights_value] + exact MixerParameterCount.count_value a V W hd + +theorem run_work (a : Fin n → ℤ) (left right : List (Fin n)) + (hleft : left.length ≤ n) (hright : right.length ≤ n) : + (run a left right).2 ≤ + coefficient n * 2 ^ left.length + coefficient n * 2 ^ right.length + + (4 * (left.length + 1) ^ 2 + 32) * 2 ^ left.length + + (10 * left.length + 21) * 2 ^ (left.length + right.length) + 6 := by + have hl := sortedWeights_work a left hleft + have hr := sortedWeights_work a right hright + have hc := MeasuredSumReader.count_work (sortedWeights a left).1 + (sortedWeights a right).1 (sortedWeights_sorted a right) + simp only [sortedWeights_size, Nat.clog_pow 2 _ (by decide), ← pow_add] at hc + change _ + _ + _ + 3 ≤ _ + omega + +def mixerCount (a : Fin n → ℤ) (V : Finset (Fin n)) : ℕ × ℕ := + run a ((MixerParameterCount.firstHalf V).sort (· ≤ ·)) + ((MixerParameterCount.secondHalf V).sort (· ≤ ·)) + +theorem mixerCount_value (a : Fin n → ℤ) (V : Finset (Fin n)) : + (mixerCount a V).1 = distinctSumCount a V := by + rw [mixerCount, run_source a _ _ (MixerParameterCount.halves_disjoint V), + MixerParameterCount.halves_union] + +end LowSpaceSubsetSum.MeasuredMixerCount + +end OAI diff --git a/lean/OAI/Combinatorics/LowSpaceSubsetSum/Streams/MeasuredPivot.lean b/lean/OAI/Combinatorics/LowSpaceSubsetSum/Streams/MeasuredPivot.lean new file mode 100644 index 0000000000000000000000000000000000000000..a6c22f96a1cedd201e0fb73f7ee004aa8dd719e8 --- /dev/null +++ b/lean/OAI/Combinatorics/LowSpaceSubsetSum/Streams/MeasuredPivot.lean @@ -0,0 +1,80 @@ +import OAI.Combinatorics.LowSpaceSubsetSum.Representation.RepresentationPivotWork + +namespace OAI + +/-! # Binary search with counted predicate evaluations + +The predicate is evaluated exactly once at each nonempty interval. The +count includes endpoint arithmetic and the actual predicate callback cost. +-/ + +namespace LowSpaceSubsetSum.BinaryPivot + +variable {n : ℕ} + +def measuredStep (p : Fin n → Bool × ℕ) (c : Cut n) : Cut n × ℕ := + if h : c.lo < c.hi then + let mid := (c.lo + c.hi) / 2 + have hmid : mid < n := by have := c.bounded; dsimp [mid]; omega + let q := p ⟨mid, hmid⟩ + (if q.1 then + ⟨mid + 1, c.hi, by dsimp [mid]; omega, c.bounded⟩ + else + ⟨c.lo, mid, by dsimp [mid]; omega, by have := c.bounded; dsimp [mid]; omega⟩, + q.2 + 8) + else (c, 1) + +theorem measuredStep_value (p : Fin n → Bool × ℕ) (c : Cut n) : + (measuredStep p c).1 = step (fun i => (p i).1) c := by + unfold measuredStep step + split <;> rfl + +theorem measuredStep_work (p : Fin n → Bool × ℕ) (K : ℕ) + (hp : ∀ i, (p i).2 ≤ K) (c : Cut n) : + (measuredStep p c).2 ≤ K + 8 := by + unfold measuredStep + split + · rename_i h + exact Nat.add_le_add_right (hp ⟨(c.lo + c.hi) / 2, by have := c.bounded; omega⟩) 8 + · omega + +/-- The accumulator makes the search loop tail recursive. -/ +def measuredRun (p : Fin n → Bool × ℕ) : ℕ → Cut n → ℕ → Cut n × ℕ + | 0, c, work => (c, work) + | k + 1, c, work => + let q := measuredStep p c + measuredRun p k q.1 (work + q.2) + +theorem measuredRun_value (p : Fin n → Bool × ℕ) (k : ℕ) (c : Cut n) (work : ℕ) : + (measuredRun p k c work).1 = (step (fun i => (p i).1))^[k] c := by + induction k generalizing c work with + | zero => rfl + | succ k ih => + rw [measuredRun, ih, measuredStep_value, Function.iterate_succ_apply] + +theorem measuredRun_work (p : Fin n → Bool × ℕ) (K : ℕ) + (hp : ∀ i, (p i).2 ≤ K) (k : ℕ) (c : Cut n) (work : ℕ) : + (measuredRun p k c work).2 ≤ work + (K + 8) * k := by + induction k generalizing c work with + | zero => simp only [measuredRun, Nat.mul_zero, Nat.add_zero, le_refl] + | succ k ih => + have hi := ih (measuredStep p c).1 (work + (measuredStep p c).2) + have hs := measuredStep_work p K hp c + change (measuredRun p k (measuredStep p c).1 (work + (measuredStep p c).2)).2 ≤ _ + simp only [Nat.mul_add, Nat.mul_one] + omega + +def measuredSearch (p : Fin n → Bool × ℕ) (k : ℕ) : Cut n × ℕ := + measuredRun p k (initial n) 0 + +theorem measuredSearch_value (p : Fin n → Bool × ℕ) (k : ℕ) : + (measuredSearch p k).1 = search (fun i => (p i).1) k := measuredRun_value _ _ _ _ + +theorem measuredSearch_work (p : Fin n → Bool × ℕ) (K : ℕ) + (hp : ∀ i, (p i).2 ≤ K) (k : ℕ) : + (measuredSearch p k).2 ≤ (K + 8) * k := by + simpa only [measuredSearch, Nat.zero_add] using measuredRun_work p K hp k (initial n) 0 + +end LowSpaceSubsetSum.BinaryPivot + +end OAI diff --git a/lean/OAI/Combinatorics/LowSpaceSubsetSum/Streams/MeasuredRow.lean b/lean/OAI/Combinatorics/LowSpaceSubsetSum/Streams/MeasuredRow.lean new file mode 100644 index 0000000000000000000000000000000000000000..1a092a80050f3b563cb700e83d6359b9c5f8b540 --- /dev/null +++ b/lean/OAI/Combinatorics/LowSpaceSubsetSum/Streams/MeasuredRow.lean @@ -0,0 +1,212 @@ +import OAI.Combinatorics.LowSpaceSubsetSum.Streams.MeasuredPivot +import OAI.Combinatorics.LowSpaceSubsetSum.Representation.RepresentationKeys + +namespace OAI + +/-! # Modular row initialization with measured weight evaluation + +Every binary-search predicate executes the stored-record weight routine. +The left weight is computed once, and all searches address the shared right +array directly. The resulting cursor is the original filtered row cursor. +-/ + +namespace LowSpaceSubsetSum +namespace BinarySlice + +variable {α : Type*} + +def measuredRange (xs : Array α) (key : α → ℤ × ℕ) (r : ℤ) (k : ℕ) + (hs : Monotone (fun i : Fin xs.size => (key xs[i.val]).1)) + (hk : xs.size < 2 ^ k) : SliceCursor.Range xs.size × ℕ := + let lo := BinaryPivot.measuredSearch (fun i : Fin xs.size => + let q := key xs[i.val]; (decide (q.1 < r), q.2 + 2)) k + let hi := BinaryPivot.measuredSearch (fun i : Fin xs.size => + let q := key xs[i.val]; (decide (q.1 ≤ r), q.2 + 2)) k + have hlo : lo.1.lo = lower xs (fun x => (key x).1) r k := + congrArg BinaryPivot.Cut.lo (BinaryPivot.measuredSearch_value _ _) + have hhi : hi.1.lo = upper xs (fun x => (key x).1) r k := + congrArg BinaryPivot.Cut.lo (BinaryPivot.measuredSearch_value _ _) + (⟨lo.1.lo, hi.1.lo - lo.1.lo, by + rw [hlo, hhi] + exact (range xs (fun x => (key x).1) r k hs hk).bounded⟩, + lo.2 + hi.2 + 4) + +theorem measuredRange_value (xs : Array α) (key : α → ℤ × ℕ) (r : ℤ) (k : ℕ) + (hs : Monotone (fun i : Fin xs.size => (key xs[i.val]).1)) + (hk : xs.size < 2 ^ k) : + (measuredRange xs key r k hs hk).1 = range xs (fun x => (key x).1) r k hs hk := by + simp only [measuredRange, BinaryPivot.measuredSearch_value, range, lower, upper] + +theorem measuredRange_work (xs : Array α) (key : α → ℤ × ℕ) (r : ℤ) (k K : ℕ) + (hkey : ∀ x, (key x).2 ≤ K) + (hs : Monotone (fun i : Fin xs.size => (key xs[i.val]).1)) + (hk : xs.size < 2 ^ k) : + (measuredRange xs key r k hs hk).2 ≤ 2 * (K + 10) * k + 4 := by + have hl := BinaryPivot.measuredSearch_work + (fun i : Fin xs.size => let q := key xs[i.val]; (decide (q.1 < r), q.2 + 2)) + (K + 2) (fun i => Nat.add_le_add_right (hkey xs[i.val]) 2) k + have hh := BinaryPivot.measuredSearch_work + (fun i : Fin xs.size => let q := key xs[i.val]; (decide (q.1 ≤ r), q.2 + 2)) + (K + 2) (fun i => Nat.add_le_add_right (hkey xs[i.val]) 2) k + change _ + _ + 4 ≤ _ + simp only [Nat.add_assoc, Nat.mul_assoc, Nat.reduceAdd] at hl hh ⊢ + omega + +end BinarySlice +namespace ModularCursor + +open scoped Fin.NatCast + +variable {n : ℕ} [NeZero n] {α : Type*} + +def measuredForward (a : Fin n → α) (key : α → ℤ × ℕ) (P r : ℤ) (k : ℕ) : + CyclicCursor.State n × ℕ := + let q := BinaryPivot.measuredSearch (fun i => + let w := key (a i); (decide (w.1 < P - r), w.2 + 2)) k + (⟨Fin.ofNat n q.1.lo, n, false⟩, q.2 + 6) + +def measuredReverse (a : Fin n → α) (key : α → ℤ × ℕ) (r : ℤ) (k : ℕ) : + CyclicCursor.State n × ℕ := + let q := BinaryPivot.measuredSearch (fun i => + let w := key (a i); (decide (w.1 ≤ r), w.2 + 2)) k + (⟨Fin.ofNat n q.1.lo - 1, n, true⟩, q.2 + 6) + +theorem measuredForward_value (a : Fin n → α) (key : α → ℤ × ℕ) (P r : ℤ) (k : ℕ) : + (measuredForward a key P r k).1 = forwardStart a (fun x => (key x).1) P r k := by + simp only [measuredForward, BinaryPivot.measuredSearch_value, forwardStart] + +theorem measuredReverse_value (a : Fin n → α) (key : α → ℤ × ℕ) (r : ℤ) (k : ℕ) : + (measuredReverse a key r k).1 = reverseStart a (fun x => (key x).1) r k := by + simp only [measuredReverse, BinaryPivot.measuredSearch_value, reverseStart] + +theorem measuredForward_work (a : Fin n → α) (key : α → ℤ × ℕ) (P r : ℤ) (k K : ℕ) + (hkey : ∀ x, (key x).2 ≤ K) : + (measuredForward a key P r k).2 ≤ (K + 10) * k + 6 := by + exact Nat.add_le_add_right (BinaryPivot.measuredSearch_work _ (K + 2) + (fun i => Nat.add_le_add_right (hkey (a i)) 2) k) 6 + +theorem measuredReverse_work (a : Fin n → α) (key : α → ℤ × ℕ) (r : ℤ) (k K : ℕ) + (hkey : ∀ x, (key x).2 ≤ K) : + (measuredReverse a key r k).2 ≤ (K + 10) * k + 6 := by + exact Nat.add_le_add_right (BinaryPivot.measuredSearch_work _ (K + 2) + (fun i => Nat.add_le_add_right (hkey (a i)) 2) k) 6 + +end ModularCursor +namespace SliceModular + +variable {α : Type*} + +def measuredForward (xs : Array α) (rr : SliceCursor.Range xs.size) + (key : α → ℤ × ℕ) (P r : ℤ) (k : ℕ) : SliceCursor.State xs.size × ℕ := + if h : 0 < rr.length then + haveI : NeZero rr.length := ⟨by omega⟩ + let q := ModularCursor.measuredForward (SliceCursor.values xs rr) key P r k + (⟨rr, some q.1⟩, q.2 + 2) + else (⟨rr, none⟩, 1) + +def measuredReverse (xs : Array α) (rr : SliceCursor.Range xs.size) + (key : α → ℤ × ℕ) (r : ℤ) (k : ℕ) : SliceCursor.State xs.size × ℕ := + if h : 0 < rr.length then + haveI : NeZero rr.length := ⟨by omega⟩ + let q := ModularCursor.measuredReverse (SliceCursor.values xs rr) key r k + (⟨rr, some q.1⟩, q.2 + 2) + else (⟨rr, none⟩, 1) + +theorem measuredForward_value (xs : Array α) (rr : SliceCursor.Range xs.size) + (key : α → ℤ × ℕ) (P r : ℤ) (k : ℕ) : + (measuredForward xs rr key P r k).1 = forward xs rr (fun x => (key x).1) P r k := by + unfold measuredForward forward + split <;> simp only [ModularCursor.measuredForward_value] + +theorem measuredReverse_value (xs : Array α) (rr : SliceCursor.Range xs.size) + (key : α → ℤ × ℕ) (r : ℤ) (k : ℕ) : + (measuredReverse xs rr key r k).1 = reverse xs rr (fun x => (key x).1) r k := by + unfold measuredReverse reverse + split <;> simp only [ModularCursor.measuredReverse_value] + +theorem measuredForward_work (xs : Array α) (rr : SliceCursor.Range xs.size) + (key : α → ℤ × ℕ) (P r : ℤ) (k K : ℕ) (hkey : ∀ x, (key x).2 ≤ K) : + (measuredForward xs rr key P r k).2 ≤ (K + 10) * k + 8 := by + unfold measuredForward + split + · rename_i h + have : NeZero rr.length := ⟨by omega⟩ + exact Nat.add_le_add_right (ModularCursor.measuredForward_work _ key P r k K hkey) 2 + · omega + +theorem measuredReverse_work (xs : Array α) (rr : SliceCursor.Range xs.size) + (key : α → ℤ × ℕ) (r : ℤ) (k K : ℕ) (hkey : ∀ x, (key x).2 ≤ K) : + (measuredReverse xs rr key r k).2 ≤ (K + 10) * k + 8 := by + unfold measuredReverse + split + · rename_i h + have : NeZero rr.length := ⟨by omega⟩ + exact Nat.add_le_add_right (ModularCursor.measuredReverse_work _ key r k K hkey) 2 + · omega + +end SliceModular +end LowSpaceSubsetSum +namespace LowSpaceSubsetSum.FilteredStream + +variable {α β : Type*} + +def measuredRow (right : Array β) (wl : α → ℤ × ℕ) (wr : β → ℤ × ℕ) + (p P c : ℤ) (hs : FilteredRow.PrimarySorted right (fun y => (wr y).1) p) + (mode : Mode) (x : α) : PairCursor.State α right.size × ℕ := + let wx := wl x + let k := steps right.size + let low := fun y => let w := wr y; (w.1 % p, w.2 + 2) + let high := fun y => let w := wr y; (w.1 % P, w.2 + 2) + let rr := BinarySlice.measuredRange right low ((c - wx.1) % p) k + hs (steps_sufficient right.size) + let q := match mode with + | .direct => SliceModular.measuredForward right rr.1 high P (wx.1 % P) k + | .complementary v => SliceModular.measuredReverse right rr.1 high ((v - wx.1) % P) k + (⟨x, q.1⟩, wx.2 + rr.2 + q.2 + 4) + +theorem measuredRow_value (right : Array β) (wl : α → ℤ × ℕ) (wr : β → ℤ × ℕ) + (p P c : ℤ) (hs : FilteredRow.PrimarySorted right (fun y => (wr y).1) p) + (mode : Mode) (x : α) : + (measuredRow right wl wr p P c hs mode x).1 = + row right (fun x => (wl x).1) (fun y => (wr y).1) p P c hs mode x := by + cases mode <;> simp only [measuredRow, row, FilteredRow.forward, FilteredRow.reverse, + BinarySlice.measuredRange_value, SliceModular.measuredForward_value, + SliceModular.measuredReverse_value, FilteredRow.range] + +theorem measuredRow_work (right : Array β) (wl : α → ℤ × ℕ) (wr : β → ℤ × ℕ) + (p P c : ℤ) (hs : FilteredRow.PrimarySorted right (fun y => (wr y).1) p) + (mode : Mode) (x : α) (K : ℕ) + (hl : ∀ x, (wl x).2 ≤ K) (hr : ∀ y, (wr y).2 ≤ K) : + (measuredRow right wl wr p P c hs mode x).2 ≤ + 3 * (K + 12) * steps right.size + K + 16 := by + let low := fun y => let w := wr y; (w.1 % p, w.2 + 2) + let high := fun y => let w := wr y; (w.1 % P, w.2 + 2) + let k := steps right.size + let rr := BinarySlice.measuredRange right low ((c - (wl x).1) % p) k + hs (steps_sufficient right.size) + have hrr := BinarySlice.measuredRange_work right low ((c - (wl x).1) % p) k (K + 2) + (fun y => Nat.add_le_add_right (hr y) 2) hs (steps_sufficient right.size) + have hx := hl x + cases mode with + | direct => + have hq := SliceModular.measuredForward_work right rr.1 high P ((wl x).1 % P) k + (K + 2) (fun y => Nat.add_le_add_right (hr y) 2) + change (wl x).2 + rr.2 + + (SliceModular.measuredForward right rr.1 high P ((wl x).1 % P) k).2 + 4 ≤ _ + change rr.2 ≤ 2 * (K + 2 + 10) * k + 4 at hrr + change _ ≤ 3 * (K + 12) * k + K + 16 + simp only [Nat.add_assoc, Nat.mul_assoc, Nat.reduceAdd] at hrr hq ⊢ + omega + | complementary v => + have hq := SliceModular.measuredReverse_work right rr.1 high ((v - (wl x).1) % P) k + (K + 2) (fun y => Nat.add_le_add_right (hr y) 2) + change (wl x).2 + rr.2 + + (SliceModular.measuredReverse right rr.1 high ((v - (wl x).1) % P) k).2 + 4 ≤ _ + change rr.2 ≤ 2 * (K + 2 + 10) * k + 4 at hrr + change _ ≤ 3 * (K + 12) * k + K + 16 + simp only [Nat.add_assoc, Nat.mul_assoc, Nat.reduceAdd] at hrr hq ⊢ + omega + +end LowSpaceSubsetSum.FilteredStream + +end OAI diff --git a/lean/OAI/Combinatorics/LowSpaceSubsetSum/Streams/MeasuredSort.lean b/lean/OAI/Combinatorics/LowSpaceSubsetSum/Streams/MeasuredSort.lean new file mode 100644 index 0000000000000000000000000000000000000000..9c3df3ed5475a48d1d0ca9e78f670f02db3646b2 --- /dev/null +++ b/lean/OAI/Combinatorics/LowSpaceSubsetSum/Streams/MeasuredSort.lean @@ -0,0 +1,128 @@ +import OAI.Combinatorics.LowSpaceSubsetSum.Streams.CountedSort + +namespace OAI + +/-! # Mergesort including every comparator callback + +The value agrees exactly with the counted merge and sort. The work theorem +scales its structural ledger by a bound on the supplied comparison work. +-/ + +namespace LowSpaceSubsetSum.MeasuredSort + +variable {α : Type*} + +def merge (cmp : α → α → Bool × ℕ) (xs ys : List α) : List α × ℕ := + match xs, ys with + | [], ys => (ys, 1) + | xs, [] => (xs, 1) + | x :: xs, y :: ys => + let c := cmp x y + if c.1 then + let out := merge cmp xs (y :: ys) + (x :: out.1, out.2 + c.2 + 1) + else + let out := merge cmp (x :: xs) ys + (y :: out.1, out.2 + c.2 + 1) +termination_by xs.length + ys.length + +theorem merge_value (cmp : α → α → Bool × ℕ) (xs ys : List α) : + (merge cmp xs ys).1 = (CountedSort.merge (fun x y => (cmp x y).1) xs ys).1 := by + induction xs generalizing ys with + | nil => simp [merge, CountedSort.merge] + | cons x xs ih => + induction ys with + | nil => simp [merge, CountedSort.merge] + | cons y ys ihy => + cases h : (cmp x y).1 <;> simp [merge, CountedSort.merge, h, ih, ihy] + +theorem merge_work (cmp : α → α → Bool × ℕ) (K : ℕ) + (hc : ∀ x y, (cmp x y).2 ≤ K) (xs ys : List α) : + (merge cmp xs ys).2 ≤ + (K + 1) * (CountedSort.merge (fun x y => (cmp x y).1) xs ys).2 := by + induction xs generalizing ys with + | nil => simp [merge, CountedSort.merge] + | cons x xs ih => + induction ys with + | nil => simp [merge, CountedSort.merge] + | cons y ys ihy => + have hcost := hc x y + cases h : (cmp x y).1 + · simp only [merge, CountedSort.merge, h, Bool.false_eq_true, ↓reduceIte] + simp only [Nat.mul_add, Nat.mul_one] + omega + · have hi := ih (y :: ys) + simp only [merge, CountedSort.merge, h, ↓reduceIte] + simp only [Nat.mul_add, Nat.mul_one] + omega + +def run (cmp : α → α → Bool × ℕ) : ℕ → List α → List α × ℕ + | 0, xs => (xs, 1) + | _ + 1, [] => ([], 1) + | _ + 1, [x] => ([x], 1) + | k + 1, x :: y :: rest => + let xs := x :: y :: rest + let cut := (xs.length + 1) / 2 + let left := run cmp k (xs.take cut) + let right := run cmp k (xs.drop cut) + let out := merge cmp left.1 right.1 + (out.1, left.2 + right.2 + 3 * xs.length + out.2 + 1) + +theorem run_value (cmp : α → α → Bool × ℕ) (k : ℕ) (xs : List α) : + (run cmp k xs).1 = (CountedSort.run (fun x y => (cmp x y).1) k xs).1 := by + induction k generalizing xs with + | zero => rfl + | succ k ih => + cases xs with + | nil => rfl + | cons x xs => + cases xs with + | nil => rfl + | cons y rest => simp only [run, merge_value, ih, CountedSort.run] + +theorem run_work (cmp : α → α → Bool × ℕ) (K : ℕ) + (hc : ∀ x y, (cmp x y).2 ≤ K) (k : ℕ) (xs : List α) : + (run cmp k xs).2 ≤ (K + 1) * (CountedSort.run (fun x y => (cmp x y).1) k xs).2 := by + induction k generalizing xs with + | zero => simp only [run, CountedSort.run]; omega + | succ k ih => + cases xs with + | nil => simp only [run, CountedSort.run]; omega + | cons x xs => + cases xs with + | nil => simp only [run, CountedSort.run]; omega + | cons y rest => + let xs := x :: y :: rest + let cut := (xs.length + 1) / 2 + have hl := ih (xs.take cut) + have hr := ih (xs.drop cut) + have hm := merge_work cmp K hc (run cmp k (xs.take cut)).1 (run cmp k (xs.drop cut)).1 + rw [run_value, run_value] at hm + change (run cmp k (xs.take cut)).2 + (run cmp k (xs.drop cut)).2 + + 3 * xs.length + (merge cmp (run cmp k (xs.take cut)).1 + (run cmp k (xs.drop cut)).1).2 + 1 ≤ + (K + 1) * ((CountedSort.run (fun x y => (cmp x y).1) k (xs.take cut)).2 + + (CountedSort.run (fun x y => (cmp x y).1) k (xs.drop cut)).2 + 3 * xs.length + + (CountedSort.merge (fun x y => (cmp x y).1) + (CountedSort.run (fun x y => (cmp x y).1) k (xs.take cut)).1 + (CountedSort.run (fun x y => (cmp x y).1) k (xs.drop cut)).1).2 + 1) + rw [run_value, run_value] + nlinarith only [hl, hr, hm, Nat.zero_le (K * (3 * xs.length + 1))] + +def sort (cmp : α → α → Bool × ℕ) (xs : List α) : List α × ℕ := + run cmp (Nat.clog 2 xs.length) xs + +theorem sort_value (cmp : α → α → Bool × ℕ) (xs : List α) : + (sort cmp xs).1 = xs.mergeSort (fun x y => (cmp x y).1) := by + rw [sort, run_value, CountedSort.run_value] + exact Nat.le_pow_clog (by decide) _ + +theorem sort_work (cmp : α → α → Bool × ℕ) (K : ℕ) + (hc : ∀ x y, (cmp x y).2 ≤ K) (xs : List α) (n : ℕ) (hn : xs.length ≤ 2 ^ n) : + (sort cmp xs).2 ≤ (K + 1) * ((6 * n + 1) * xs.length + 1) := by + exact (run_work cmp K hc _ _).trans + (Nat.mul_le_mul_left _ (CountedSort.sort_steps_of_index_bits _ xs n hn)) + +end LowSpaceSubsetSum.MeasuredSort + +end OAI diff --git a/lean/OAI/Combinatorics/LowSpaceSubsetSum/Streams/MeasuredSortSpace.lean b/lean/OAI/Combinatorics/LowSpaceSubsetSum/Streams/MeasuredSortSpace.lean new file mode 100644 index 0000000000000000000000000000000000000000..eea1f07d15667906bb8eb0ba0789bc28dc0f5a5a --- /dev/null +++ b/lean/OAI/Combinatorics/LowSpaceSubsetSum/Streams/MeasuredSortSpace.lean @@ -0,0 +1,128 @@ +import OAI.Combinatorics.LowSpaceSubsetSum.Streams.MeasuredSort + +namespace OAI + +/-! # Live list and continuation cells of the executed mergesort + +The first projection is exactly the measured sort, including its work +counter. The second projection records list and continuation storage; +comparison callbacks are scalar operations at the terminal application. +Input record payloads are shared and are not copied by a list cons. +-/ + +namespace LowSpaceSubsetSum.MeasuredSortSpace + +variable {α : Type*} + +/-- The merge retains its input tails, one continuation per selected head, +and the newly constructed result spine. -/ +def merge (cmp : α → α → Bool × ℕ) (xs ys : List α) : (List α × ℕ) × ℕ := + match xs, ys with + | [], ys => ((ys, 1), ys.length + 2) + | xs, [] => ((xs, 1), xs.length + 2) + | x :: xs, y :: ys => + let c := cmp x y + if c.1 then + let out := merge cmp xs (y :: ys) + ((x :: out.1.1, out.1.2 + c.2 + 1), + max ((x :: xs).length + (y :: ys).length + 2) (out.2 + 4)) + else + let out := merge cmp (x :: xs) ys + ((y :: out.1.1, out.1.2 + c.2 + 1), + max ((x :: xs).length + (y :: ys).length + 2) (out.2 + 4)) +termination_by xs.length + ys.length + +theorem merge_value (cmp : α → α → Bool × ℕ) (xs ys : List α) : + (merge cmp xs ys).1 = MeasuredSort.merge cmp xs ys := by + induction xs generalizing ys with + | nil => simp [merge, MeasuredSort.merge] + | cons x xs ih => + induction ys with + | nil => simp [merge, MeasuredSort.merge] + | cons y ys ihy => + cases h : (cmp x y).1 <;> simp [merge, MeasuredSort.merge, h, ih, ihy] + +theorem merge_cells (cmp : α → α → Bool × ℕ) (xs ys : List α) : + (merge cmp xs ys).2 ≤ 6 * (xs.length + ys.length + 1) := by + induction xs generalizing ys with + | nil => simp only [merge, List.length_nil]; omega + | cons x xs ih => + induction ys with + | nil => simp only [merge, List.length_nil]; omega + | cons y ys ihy => + have hx := ih (y :: ys) + cases h : (cmp x y).1 <;> + simp only [merge, h, Bool.false_eq_true, ↓reduceIte, List.length_cons, max_le_iff] <;> + simp only [List.length_cons] at hx ihy <;> constructor <;> omega + +/-- One branch runs at a time. The parent input, split spines and completed +sibling fit in the eight-cell-per-input local allowance. -/ +def run (cmp : α → α → Bool × ℕ) : ℕ → List α → (List α × ℕ) × ℕ + | 0, xs => ((xs, 1), xs.length + 2) + | _ + 1, [] => (([], 1), 2) + | _ + 1, [x] => (([x], 1), 3) + | k + 1, x :: y :: rest => + let xs := x :: y :: rest + let cut := (xs.length + 1) / 2 + let left := run cmp k (xs.take cut) + let right := run cmp k (xs.drop cut) + let out := merge cmp left.1.1 right.1.1 + ((out.1.1, left.1.2 + right.1.2 + 3 * xs.length + out.1.2 + 1), + 8 * (xs.length + 1) + max left.2 (max right.2 out.2)) + +theorem run_value (cmp : α → α → Bool × ℕ) (k : ℕ) (xs : List α) : + (run cmp k xs).1 = MeasuredSort.run cmp k xs := by + induction k generalizing xs with + | zero => rfl + | succ k ih => + cases xs with + | nil => rfl + | cons x xs => + cases xs with + | nil => rfl + | cons y rest => simp only [run, merge_value, ih, MeasuredSort.run] + +theorem run_length (cmp : α → α → Bool × ℕ) (k : ℕ) (xs : List α) : + (run cmp k xs).1.1.length = xs.length := by + rw [run_value, MeasuredSort.run_value] + exact CountedSort.run_length _ _ _ + +theorem run_cells (cmp : α → α → Bool × ℕ) (k : ℕ) (xs : List α) : + (run cmp k xs).2 ≤ 32 * (k + 1) * (xs.length + 1) := by + induction k generalizing xs with + | zero => simp only [run]; omega + | succ k ih => + cases xs with + | nil => simp only [run, List.length_nil]; omega + | cons x tail => + cases tail with + | nil => simp only [run, List.length_cons, List.length_nil]; omega + | cons y rest => + let xs := x :: y :: rest + let cut := (xs.length + 1) / 2 + have hl := ih (xs.take cut) + have hr := ih (xs.drop cut) + have hll : (xs.take cut).length ≤ xs.length := by + simp only [List.length_take] + exact Nat.min_le_right _ _ + have hrl : (xs.drop cut).length ≤ xs.length := by simp only [List.length_drop]; omega + have hleft := hl.trans (Nat.mul_le_mul_left (32 * (k + 1)) (by omega : + (xs.take cut).length + 1 ≤ xs.length + 1)) + have hright := hr.trans (Nat.mul_le_mul_left (32 * (k + 1)) (by omega : + (xs.drop cut).length + 1 ≤ xs.length + 1)) + have hm := merge_cells cmp (run cmp k (xs.take cut)).1.1 + (run cmp k (xs.drop cut)).1.1 + rw [run_length, run_length, List.length_take, List.length_drop] at hm + have hm' : (merge cmp (run cmp k (xs.take cut)).1.1 + (run cmp k (xs.drop cut)).1.1).2 ≤ 6 * (xs.length + 1) := by + convert hm using 1 + omega + have hm'' := hm'.trans (Nat.mul_le_mul_right (xs.length + 1) + (show 6 ≤ 32 * (k + 1) by omega)) + have hmax := max_le hleft (max_le hright hm'') + change 8 * (xs.length + 1) + _ ≤ 32 * (k + 1 + 1) * (xs.length + 1) + nlinarith only [hmax, Nat.zero_le xs.length] + +end LowSpaceSubsetSum.MeasuredSortSpace + +end OAI diff --git a/lean/OAI/Combinatorics/LowSpaceSubsetSum/Streams/MeasuredStoredRecords.lean b/lean/OAI/Combinatorics/LowSpaceSubsetSum/Streams/MeasuredStoredRecords.lean new file mode 100644 index 0000000000000000000000000000000000000000..8839a7d30872e1abd5fc6ad1fed577f779f011d2 --- /dev/null +++ b/lean/OAI/Combinatorics/LowSpaceSubsetSum/Streams/MeasuredStoredRecords.lean @@ -0,0 +1,122 @@ +import OAI.Combinatorics.LowSpaceSubsetSum.Representation.RepresentationStoredRecords + +namespace OAI + +/-! # Executed generation retaining bounded index lists + +The subset generators return index lists. Wrapping them as bounded masks +retains those lists; finite sets occur only in the semantic specification. +The work counter includes wrapping and both Cartesian-product traversals. +-/ + +namespace LowSpaceSubsetSum +namespace IndexedMask + +variable {n : ℕ} + +private theorem selectedList_length (xs ys : List (Fin n)) (k : ℕ) + (h : ys ∈ (CountedSubsets.select k xs).1) : ys.length ≤ xs.length := by + rw [CountedSubsets.select_value] at h + exact (List.mem_sublistsLen.mp h).1.length_le + +private theorem allList_length (xs ys : List (Fin n)) + (h : ys ∈ (CountedSubsets.all xs).1) : ys.length ≤ xs.length := by + rw [CountedSubsets.all_value] at h + exact (List.mem_sublists.mp h).length_le + +def measuredSelected (xs : List (Fin n)) (hx : xs.length ≤ n) (k : ℕ) : + List (IndexedMask n) × ℕ := + let out := CountedSubsets.select k xs + (out.1.attach.map (fun y => ⟨y.val, + (selectedList_length xs y.val k y.property).trans hx⟩), out.2 + out.1.length) + +def measuredAll (xs : List (Fin n)) (hx : xs.length ≤ n) : List (IndexedMask n) × ℕ := + let out := CountedSubsets.all xs + (out.1.attach.map (fun y => ⟨y.val, + (allList_length xs y.val y.property).trans hx⟩), out.2 + out.1.length) + +@[simp] theorem measuredSelected_value (xs : List (Fin n)) (hx : xs.length ≤ n) (k : ℕ) : + (measuredSelected xs hx k).1 = selected xs hx k := rfl + +@[simp] theorem measuredAll_value (xs : List (Fin n)) (hx : xs.length ≤ n) : + (measuredAll xs hx).1 = all xs hx := rfl + +@[simp] theorem selected_length (xs : List (Fin n)) (hx : xs.length ≤ n) (k : ℕ) : + (selected xs hx k).length = xs.length.choose k := by + simp only [selected, List.length_map, List.length_attach, CountedSubsets.select_length] + +@[simp] theorem all_length (xs : List (Fin n)) (hx : xs.length ≤ n) : + (all xs hx).length = 2 ^ xs.length := by + simp only [all, List.length_map, List.length_attach, CountedSubsets.all_length] + +end IndexedMask + +namespace RepresentationLeaf + +variable {n : ℕ} + +def measuredStoredRecords (L : RepresentationLeaf (Fin n)) : List (LeafRecord n) × ℕ := + if L.topCount ≤ L.top.card ∧ L.localCount ≤ L.mixer.card then + let dt := domainSort L.top + let dm := domainSort L.mixer + let db := domainSort L.background + let t := IndexedMask.measuredSelected dt.1 + (by rw [domainSort_length]; simpa using Finset.card_le_univ L.top) L.topCount + let m := IndexedMask.measuredSelected dm.1 + (by rw [domainSort_length]; simpa using Finset.card_le_univ L.mixer) L.localCount + let b := IndexedMask.measuredAll db.1 + (by rw [domainSort_length]; simpa using Finset.card_le_univ L.background) + let tm := t.1 ×ˢ m.1 + let out := (tm ×ˢ b.1).map (fun y => (⟨y.1.1, y.1.2, y.2⟩ : LeafRecord n)) + (out, dt.2 + dm.2 + db.2 + t.2 + m.2 + b.2 + + 4 * tm.length + 8 * out.length + 3 * (n + 1)) + else ([], 3 * (n + 1)) + +theorem measuredStoredRecords_value (L : RepresentationLeaf (Fin n)) : + L.measuredStoredRecords.1 = L.storedRecords := by + simp only [measuredStoredRecords, storedRecords] + split <;> simp only [IndexedMask.measuredSelected_value, IndexedMask.measuredAll_value] + +theorem measuredStoredRecords_cost (L : RepresentationLeaf (Fin n)) : + L.measuredStoredRecords.2 ≤ 3 * L.countedEnumerate.2 := by + by_cases hf : L.topCount ≤ L.top.card ∧ L.localCount ≤ L.mixer.card + · have hc : 1 ≤ 2 ^ L.background.card := Nat.one_le_two_pow + have hp : 1 ≤ (n + 1) ^ 2 := Nat.one_le_pow _ _ (by omega) + have htm : L.top.card.choose L.topCount * L.mixer.card.choose L.localCount ≤ + L.top.card.choose L.topCount * L.mixer.card.choose L.localCount * + 2 ^ L.background.card := by + simpa only [Nat.mul_one] using Nat.mul_le_mul_left + (L.top.card.choose L.topCount * L.mixer.card.choose L.localCount) hc + have hsum : L.top.card.choose L.topCount + L.mixer.card.choose L.localCount + + 2 ^ L.background.card ≤ (n + 1) ^ 2 * + (L.top.card.choose L.topCount + L.mixer.card.choose L.localCount + + 2 ^ L.background.card) := by + simpa only [Nat.one_mul] using Nat.mul_le_mul_right + (L.top.card.choose L.topCount + L.mixer.card.choose L.localCount + 2 ^ L.background.card) hp + simp only [measuredStoredRecords, countedEnumerate, ite_eq_left hf, + IndexedMask.measuredSelected, IndexedMask.measuredAll, List.length_product, + List.length_map, List.length_attach, CountedSubsets.select_length, + CountedSubsets.all_length, domainSort_length] + omega + · simp only [measuredStoredRecords, countedEnumerate, ite_eq_right hf] + omega + +theorem measuredStoredRecords_work (L : RepresentationLeaf (Fin n)) : + L.measuredStoredRecords.2 ≤ 192 * (n + 1) ^ 2 * (L.occurrences.card + 1) := by + have h := Nat.mul_le_mul_left 3 L.countedEnumerate_work + exact L.measuredStoredRecords_cost.trans (by nlinarith only [h]) + +theorem measuredStoredRecords_scale (I : Instance n) (L : RepresentationLeaf (Fin n)) + (hn : 10000 ≤ n) : + L.measuredStoredRecords.2 ≤ inputScale I ^ 3 * (L.occurrences.card + 1) := by + have hnu : n + 1 ≤ inputScale I := by unfold inputScale; omega + have hs := Nat.pow_le_pow_left hnu 2 + have hm := Nat.mul_le_mul_right (inputScale I ^ 2) + (show 192 ≤ inputScale I by omega) + have hp : 192 * (n + 1) ^ 2 ≤ inputScale I ^ 3 := by nlinarith only [hs, hm] + exact L.measuredStoredRecords_work.trans (Nat.mul_le_mul_right _ hp) + +end RepresentationLeaf +end LowSpaceSubsetSum + +end OAI diff --git a/lean/OAI/Combinatorics/LowSpaceSubsetSum/Streams/MeasuredSumReader.lean b/lean/OAI/Combinatorics/LowSpaceSubsetSum/Streams/MeasuredSumReader.lean new file mode 100644 index 0000000000000000000000000000000000000000..4e67493241e2d7e2e0e8884b5f19270add480d08 --- /dev/null +++ b/lean/OAI/Combinatorics/LowSpaceSubsetSum/Streams/MeasuredSumReader.lean @@ -0,0 +1,132 @@ +import OAI.Combinatorics.LowSpaceSubsetSum.Streams.SumReader +import OAI.Combinatorics.LowSpaceSubsetSum.Streams.MeasuredInitialization +import OAI.Combinatorics.LowSpaceSubsetSum.Streams.MeasuredDistinctCount + +namespace OAI + +/-! # Executed integer-sum counting + +The initializer reads the shared half-sum arrays directly. Its tournament +and the tail-recursive counter are the only evolving state; the full output +stream remains a proof view. Work includes initial rows and every key read. +-/ + +namespace LowSpaceSubsetSum.MeasuredSumReader + +abbrev key (p : ℤ × ℤ) : ℤ × ℕ := (SumReader.key p, 1) + +def read (ys : Array ℤ) (s : Option SumReader.Row) : + Option ((ℤ × ℤ) × Option SumReader.Row) × ℕ := + (PaddedRows.next (SumReader.read ys) s, 6) + +def front (xs ys : Array ℤ) (d : ℕ) (p : RowMerge.Path d) : + Option (RowMerge.Front d (ℤ × ℤ) (Option SumReader.Row)) × ℕ := + let i := PaddedRows.measuredIndex d p + if h : i.1 < xs.size then + let q := read ys (some ⟨xs[i.1], 0⟩) + (q.1.map (fun z => ⟨p, z.1, z.2⟩), i.2 + q.2 + 5) + else (none, i.2 + 2) + +theorem front_value (xs ys : Array ℤ) (d : ℕ) (p : RowMerge.Path d) : + (front xs ys d p).1 = RowMerge.front (PaddedRows.next (SumReader.read ys)) p + (PaddedRows.rows (SumReader.rows xs) d p) := by + by_cases h : (PaddedRows.index d p).val < xs.size + · simp [front, PaddedRows.measuredIndex_value, PaddedRows.rows, SumReader.rows, + RowMerge.front, read, h] + · simp [front, PaddedRows.measuredIndex_value, PaddedRows.rows, SumReader.rows, + RowMerge.front, h, PaddedRows.next] + +theorem front_work (xs ys : Array ℤ) (d : ℕ) (p : RowMerge.Path d) : + (front xs ys d p).2 ≤ 4 * (d + 1) ^ 2 + 11 := by + have hi := PaddedRows.measuredIndex_work d p + unfold front + dsimp only + split <;> dsimp only [read] <;> omega + +def tree (xs ys : Array ℤ) := + Tournament.measuredBuild + (fun x : RowMerge.Front (Nat.clog 2 xs.size) (ℤ × ℤ) (Option SumReader.Row) => key x.value) + (Nat.clog 2 xs.size) (front xs ys (Nat.clog 2 xs.size)) + +theorem tree_value (xs ys : Array ℤ) (hs : ys.toList.Pairwise (· ≤ ·)) : + (tree xs ys).1 = (SumReader.start xs ys hs).tree := by + simp only [tree, Tournament.measuredBuild_value, SumReader.start, + MergedReader.start, RowMerge.start] + congr 1 + funext p + exact front_value xs ys _ p + +def start (xs ys : Array ℤ) (hs : ys.toList.Pairwise (· ≤ ·)) : + SumReader.State xs ys × ℕ := + let out := tree xs ys + let source := SumReader.start xs ys hs + have he : out.1 = source.tree := tree_value xs ys hs + (⟨out.1, he.symm ▸ source.valid, he.symm ▸ source.aligned, he.symm ▸ source.sorted⟩, out.2) + +theorem start_value (xs ys : Array ℤ) (hs : ys.toList.Pairwise (· ≤ ·)) : + (start xs ys hs).1 = SumReader.start xs ys hs := by + have ext {a b : SumReader.State xs ys} (h : a.tree = b.tree) : a = b := by + cases a + cases b + cases h + rfl + apply ext + exact tree_value xs ys hs + +theorem start_work (xs ys : Array ℤ) (hs : ys.toList.Pairwise (· ≤ ·)) : + (start xs ys hs).2 ≤ (4 * (Nat.clog 2 xs.size + 1) ^ 2 + 32) * + 2 ^ Nat.clog 2 xs.size := by + have h := Tournament.measuredBuild_work + (fun x : RowMerge.Front (Nat.clog 2 xs.size) (ℤ × ℤ) (Option SumReader.Row) => key x.value) + 1 (4 * (Nat.clog 2 xs.size + 1) ^ 2 + 11) (fun _ => le_rfl) + (Nat.clog 2 xs.size) (front xs ys (Nat.clog 2 xs.size)) + (front_work xs ys (Nat.clog 2 xs.size)) + change (tree xs ys).2 ≤ _ + exact h.trans ((Nat.sub_le _ _).trans (Nat.mul_le_mul_right _ (by omega))) + +def next (xs ys : Array ℤ) (s : SumReader.State xs ys) : + Option ((ℤ × ℤ) × SumReader.State xs ys) × ℕ := + MergedReader.measuredNext key (read ys) (PaddedRows.view (SumReader.view ys)) + (PaddedRows.reader _ _ (SumReader.reader ys)) s + +theorem next_value (xs ys : Array ℤ) (s : SumReader.State xs ys) : + (next xs ys s).1 = SumReader.next xs ys s := + MergedReader.measuredNext_value key (read ys) (PaddedRows.view (SumReader.view ys)) + (PaddedRows.reader _ _ (SumReader.reader ys)) s + +theorem next_work (xs ys : Array ℤ) (s : SumReader.State xs ys) : + (next xs ys s).2 ≤ 10 * Nat.clog 2 xs.size + 16 := by + have h := MergedReader.measuredNext_work key (read ys) + (PaddedRows.view (SumReader.view ys)) (PaddedRows.reader _ _ (SumReader.reader ys)) + s 1 6 (fun _ => le_rfl) (fun _ => le_rfl) + change (next xs ys s).2 ≤ _ at h + omega + +def count (xs ys : Array ℤ) (hs : ys.toList.Pairwise (· ≤ ·)) : ℕ × ℕ := + let initial := start xs ys hs + let out := MeasuredDistinctCount.run (next xs ys) key (xs.size * ys.size) initial.1 + (out.1, initial.2 + out.2 + 2) + +theorem count_value (xs ys : Array ℤ) (hs : ys.toList.Pairwise (· ≤ ·)) : + (count xs ys hs).1 = (SumReader.count xs ys hs).1 := by + simp only [count, MeasuredDistinctCount.run_value, next_value, start_value] + rfl + +theorem count_work (xs ys : Array ℤ) (hs : ys.toList.Pairwise (· ≤ ·)) : + (count xs ys hs).2 ≤ (4 * (Nat.clog 2 xs.size + 1) ^ 2 + 32) * + 2 ^ Nat.clog 2 xs.size + (10 * Nat.clog 2 xs.size + 21) * + (xs.size * ys.size) + 3 := by + have hi := start_work xs ys hs + have hc := MeasuredDistinctCount.run_work (next xs ys) key + (10 * Nat.clog 2 xs.size + 16) 1 (next_work xs ys) (fun _ => le_rfl) + (xs.size * ys.size) (start xs ys hs).1 + have hc' : (MeasuredDistinctCount.run (next xs ys) key (xs.size * ys.size) + (start xs ys hs).1).2 ≤ + (10 * Nat.clog 2 xs.size + 21) * (xs.size * ys.size) + 1 := by + convert hc using 1 + change _ + _ + 2 ≤ _ + omega + +end LowSpaceSubsetSum.MeasuredSumReader + +end OAI diff --git a/lean/OAI/Combinatorics/LowSpaceSubsetSum/Streams/MergeCorrectness.lean b/lean/OAI/Combinatorics/LowSpaceSubsetSum/Streams/MergeCorrectness.lean new file mode 100644 index 0000000000000000000000000000000000000000..cd10c3d3cd86890d941e0a1ae92547c7c13619e1 --- /dev/null +++ b/lean/OAI/Combinatorics/LowSpaceSubsetSum/Streams/MergeCorrectness.lean @@ -0,0 +1,131 @@ +import OAI.Combinatorics.LowSpaceSubsetSum.Streams.RowMerge +import Mathlib.Algebra.BigOperators.Group.Finset.Basic +import Mathlib.Data.Multiset.AddSub + +namespace OAI + +/-! +# Complete and stopped tournament merges + +The multiset view counts every row occurrence, even when all item fields +coincide. Each successful advance removes exactly the reported occurrence. +A sufficiently long trace therefore enumerates the whole product stream; +the potential also bounds every stopped execution's number of advances. +-/ + +namespace LowSpaceSubsetSum +namespace RowMerge + +universe u v + +variable {α : Type u} {σ : Type v} {d : ℕ} + +def bag (view : σ → List α) (t : Tournament.Tree (Front d α σ) d) : Multiset α := + ∑ p : Path d, (remaining view t p : Multiset α) + +theorem bag_card (view : σ → List α) (t : Tournament.Tree (Front d α σ) d) : + (bag view t).card = potential view t := by simp [bag, potential] + +theorem replacement_bag (key : α → ℤ) (read : σ → Option (α × σ)) + (view : σ → List α) (hread : IsReader read view) + (t : Tournament.Tree (Front d α σ) d) + (ht : Tournament.Valid (fun y => key y.value) t) (halign : Aligned t) + {x : Front d α σ} (hx : Tournament.winner t = some x) : + bag view t = {x.value} + bag view (Tournament.replace (fun y => key y.value) t + x.row (front read x.row x.after)) := by + have hrow := winner_at_own_row key t ht halign hx + let t' := Tournament.replace (fun y => key y.value) t x.row (front read x.row x.after) + have hpoint (p : Path d) : (remaining view t p : Multiset α) = + (remaining view t' p : Multiset α) + if p = x.row then {x.value} else 0 := by + have hnew := replace_remaining key read view hread t x p + change remaining view t' p = _ at hnew + by_cases hp : p = x.row + · subst p + rw [ite_eq_left rfl] at hnew + rw [hnew] + simp only [remaining, hrow, ↓reduceIte] + change x.value ::ₘ (view x.after : Multiset α) = (view x.after : Multiset α) + {x.value} + rw [← Multiset.singleton_add, add_comm] + · rw [ite_eq_right (Ne.symm hp)] at hnew + rw [hnew, ite_eq_right hp, add_zero] + unfold bag + rw [show (∑ p : Path d, (remaining view t p : Multiset α)) = + ∑ p : Path d, ((remaining view t' p : Multiset α) + if p = x.row then {x.value} else 0) + from Finset.sum_congr rfl (fun p _ => hpoint p)] + simp [Finset.sum_add_distrib, t', add_comm] + +theorem bag_eq_zero_of_winner_none (key : α → ℤ) + (view : σ → List α) (t : Tournament.Tree (Front d α σ) d) + (ht : Tournament.Valid (fun y => key y.value) t) (hn : Tournament.winner t = none) : + bag view t = 0 := by + have hc := (Tournament.winner_none_iff (fun y => key y.value) t ht).mp hn + have hlookup (p : Path d) : Tournament.lookup t p = none := by + cases h : Tournament.lookup t p with + | none => rfl + | some x => + have hm := (Tournament.mem_candidates_iff t x).mpr ⟨p, h⟩ + simp [hc] at hm + simp [bag, remaining, hlookup] + +/-- Analysis view of repeated advances. The program can stop between them. -/ +def trace (key : α → ℤ) (read : σ → Option (α × σ)) : + ℕ → Tournament.Tree (Front d α σ) d → List α + | 0, _ => [] + | k + 1, t => match advance key read t with + | none => [] + | some (a, t') => a :: trace key read k t' + +theorem trace_complete (key : α → ℤ) (read : σ → Option (α × σ)) + (view : σ → List α) (hread : IsReader read view) (k : ℕ) + (t : Tournament.Tree (Front d α σ) d) + (ht : Tournament.Valid (fun y => key y.value) t) (halign : Aligned t) + (hk : potential view t ≤ k) : (trace key read k t : Multiset α) = bag view t := by + induction k generalizing t with + | zero => + have hz : (bag view t).card = 0 := by rw [bag_card]; omega + simpa [trace] using (Multiset.card_eq_zero.mp hz).symm + | succ k ih => + cases hw : Tournament.winner t with + | none => + have hb := bag_eq_zero_of_winner_none key view t ht hw + simp [trace, advance, hw, hb] + | some x => + let t' := Tournament.replace (fun y => key y.value) t x.row (front read x.row x.after) + have ha : advance key read t = some (x.value, t') := by simp [advance, hw, t'] + have ht' := advance_valid key read t ht ha + have halign' := advance_aligned key read t halign ha + have hdec := replacement_consumes_one key read view hread t ht halign hw + change potential view t' + 1 = potential view t at hdec + have hk' : potential view t' ≤ k := by omega + have hbag := replacement_bag key read view hread t ht halign hw + change bag view t = {x.value} + bag view t' at hbag + rw [trace, ha] + change x.value ::ₘ (trace key read k t' : Multiset α) = bag view t + rw [ih t' ht' halign' hk', hbag] + simp + +theorem trace_length_le (key : α → ℤ) (read : σ → Option (α × σ)) + (view : σ → List α) (hread : IsReader read view) (k : ℕ) + (t : Tournament.Tree (Front d α σ) d) + (ht : Tournament.Valid (fun y => key y.value) t) (halign : Aligned t) : + (trace key read k t).length ≤ potential view t := by + induction k generalizing t with + | zero => simp [trace] + | succ k ih => + cases hw : Tournament.winner t with + | none => simp [trace, advance, hw] + | some x => + let t' := Tournament.replace (fun y => key y.value) t x.row (front read x.row x.after) + have ha : advance key read t = some (x.value, t') := by simp [advance, hw, t'] + have ht' := advance_valid key read t ht ha + have halign' := advance_aligned key read t halign ha + have hdec := replacement_consumes_one key read view hread t ht halign hw + have hlen := ih t' ht' halign' + rw [trace, ha, List.length_cons] + change potential view t' + 1 = potential view t at hdec + omega + +end RowMerge +end LowSpaceSubsetSum + +end OAI diff --git a/lean/OAI/Combinatorics/LowSpaceSubsetSum/Streams/MergeOrdering.lean b/lean/OAI/Combinatorics/LowSpaceSubsetSum/Streams/MergeOrdering.lean new file mode 100644 index 0000000000000000000000000000000000000000..ff1f668c3161e7f7b80d89cba5f3dc2138ee569c --- /dev/null +++ b/lean/OAI/Combinatorics/LowSpaceSubsetSum/Streams/MergeOrdering.lean @@ -0,0 +1,133 @@ +import OAI.Combinatorics.LowSpaceSubsetSum.Streams.MergeCorrectness + +namespace OAI + +/-! +# Sortedness of complete and stopped row merges + +Only each row's individual order is required. The tournament minimum is +no larger than every remaining occurrence; replacing its front by its +successor preserves this invariant. Every finite trace is therefore sorted, +including traces stopped by the operation cap. +-/ + +namespace LowSpaceSubsetSum +namespace RowMerge + +universe u v + +variable {α : Type u} {σ : Type v} {d : ℕ} + +def RowsSorted (key : α → ℤ) (view : σ → List α) + (t : Tournament.Tree (Front d α σ) d) : Prop := + ∀ p, (remaining view t p).Pairwise (fun x y => key x ≤ key y) + +theorem replacement_remaining_subset (key : α → ℤ) (read : σ → Option (α × σ)) + (view : σ → List α) (hread : IsReader read view) + (t : Tournament.Tree (Front d α σ) d) + (ht : Tournament.Valid (fun y => key y.value) t) (halign : Aligned t) + {x : Front d α σ} (hx : Tournament.winner t = some x) (p : Path d) : + remaining view (Tournament.replace (fun y => key y.value) t x.row + (front read x.row x.after)) p ⊆ remaining view t p := by + have hnew := replace_remaining key read view hread t x p + have hrow := winner_at_own_row key t ht halign hx + rw [hnew] + by_cases hp : x.row = p + · subst p + rw [ite_eq_left rfl] + simp only [remaining, hrow] + intro y hy + exact List.mem_cons_of_mem _ hy + · rw [ite_eq_right hp] + +theorem replacement_rowsSorted (key : α → ℤ) (read : σ → Option (α × σ)) + (view : σ → List α) (hread : IsReader read view) + (t : Tournament.Tree (Front d α σ) d) + (ht : Tournament.Valid (fun y => key y.value) t) (halign : Aligned t) + (hsort : RowsSorted key view t) {x : Front d α σ} + (hx : Tournament.winner t = some x) : + RowsSorted key view (Tournament.replace (fun y => key y.value) t x.row + (front read x.row x.after)) := by + intro p + rw [replace_remaining key read view hread t x p] + by_cases hp : x.row = p + · subst p + rw [ite_eq_left rfl] + have hs := hsort x.row + have hrow := winner_at_own_row key t ht halign hx + simp only [remaining, hrow] at hs + exact (List.pairwise_cons.mp hs).2 + · rw [ite_eq_right hp] + exact hsort p + +theorem winner_le_remaining (key : α → ℤ) (view : σ → List α) + (t : Tournament.Tree (Front d α σ) d) + (ht : Tournament.Valid (fun y => key y.value) t) (hsort : RowsSorted key view t) + {x : Front d α σ} (hx : Tournament.winner t = some x) + (p : Path d) {y : α} (hy : y ∈ remaining view t p) : key x.value ≤ key y := by + cases hp : Tournament.lookup t p with + | none => simp [remaining, hp] at hy + | some z => + have hmin := winner_is_minimum key t ht hx p hp + have hs := hsort p + simp only [remaining, hp] at hy hs + rcases List.mem_cons.mp hy with hy | hy + · simpa [hy] using hmin + · exact hmin.trans ((List.pairwise_cons.mp hs).1 y hy) + +theorem trace_lower_bound (key : α → ℤ) (read : σ → Option (α × σ)) + (view : σ → List α) (hread : IsReader read view) (k : ℕ) + (t : Tournament.Tree (Front d α σ) d) + (ht : Tournament.Valid (fun y => key y.value) t) (halign : Aligned t) + (c : ℤ) (hc : ∀ p, ∀ y ∈ remaining view t p, c ≤ key y) : + ∀ y ∈ trace key read k t, c ≤ key y := by + induction k generalizing t with + | zero => simp [trace] + | succ k ih => + cases hw : Tournament.winner t with + | none => simp [trace, advance, hw] + | some x => + let t' := Tournament.replace (fun y => key y.value) t x.row (front read x.row x.after) + have ha : advance key read t = some (x.value, t') := by simp [advance, hw, t'] + have ht' := advance_valid key read t ht ha + have halign' := advance_aligned key read t halign ha + have hrow := winner_at_own_row key t ht halign hw + have hfront : c ≤ key x.value := hc x.row x.value (by simp [remaining, hrow]) + have hc' : ∀ p, ∀ y ∈ remaining view t' p, c ≤ key y := by + intro p y hy + exact hc p y (replacement_remaining_subset key read view hread t ht halign hw p hy) + rw [trace, ha] + intro y hy + rcases List.mem_cons.mp hy with hy | hy + · simpa [hy] using hfront + · exact ih t' ht' halign' hc' y hy + +theorem trace_sorted (key : α → ℤ) (read : σ → Option (α × σ)) + (view : σ → List α) (hread : IsReader read view) (k : ℕ) + (t : Tournament.Tree (Front d α σ) d) + (ht : Tournament.Valid (fun y => key y.value) t) (halign : Aligned t) + (hsort : RowsSorted key view t) : + (trace key read k t).Pairwise (fun x y => key x ≤ key y) := by + induction k generalizing t with + | zero => simp [trace] + | succ k ih => + cases hw : Tournament.winner t with + | none => simp [trace, advance, hw] + | some x => + let t' := Tournament.replace (fun y => key y.value) t x.row (front read x.row x.after) + have ha : advance key read t = some (x.value, t') := by simp [advance, hw, t'] + have ht' := advance_valid key read t ht ha + have halign' := advance_aligned key read t halign ha + have hsort' := replacement_rowsSorted key read view hread t ht halign hsort hw + rw [trace, ha] + apply List.pairwise_cons.mpr + refine ⟨?_, ih t' ht' halign' hsort'⟩ + apply trace_lower_bound key read view hread k t' ht' halign' (key x.value) + intro p y hy + exact winner_le_remaining key view t ht hsort hw p + (replacement_remaining_subset key read view hread t ht halign hw p hy) + +end RowMerge +end LowSpaceSubsetSum + +end OAI diff --git a/lean/OAI/Combinatorics/LowSpaceSubsetSum/Streams/MergedReader.lean b/lean/OAI/Combinatorics/LowSpaceSubsetSum/Streams/MergedReader.lean new file mode 100644 index 0000000000000000000000000000000000000000..336968f024b4b3df6ef83a2c91d65969ba2339ca --- /dev/null +++ b/lean/OAI/Combinatorics/LowSpaceSubsetSum/Streams/MergedReader.lean @@ -0,0 +1,182 @@ +import OAI.Combinatorics.LowSpaceSubsetSum.Streams.MergeOrdering + +namespace OAI + +/-! +# The executable tournament merge as a finite reader + +Only the tournament and its row cursors are stored. The complete output list +is a proof view, defined by the remaining-occurrence potential. The reader +law connects this actual merge to the stopped joins and bounded dictionaries. +-/ + +namespace LowSpaceSubsetSum +namespace MergedReader + +universe u v + +variable {α : Type u} {σ : Type v} {d : ℕ} + +structure State (key : α → ℤ) (view : σ → List α) (d : ℕ) where + tree : Tournament.Tree (RowMerge.Front d α σ) d + valid : Tournament.Valid (fun x => key x.value) tree + aligned : RowMerge.Aligned tree + sorted : RowMerge.RowsSorted key view tree + +theorem advance_sorted (key : α → ℤ) (read : σ → Option (α × σ)) + (view : σ → List α) (hread : RowMerge.IsReader read view) + (s : State key view d) {a : α} {t : Tournament.Tree (RowMerge.Front d α σ) d} + (ha : RowMerge.advance key read s.tree = some (a, t)) : + RowMerge.RowsSorted key view t := by + cases hw : Tournament.winner s.tree with + | none => simp [RowMerge.advance, hw] at ha + | some x => + have heq : (x.value, Tournament.replace (fun y => key y.value) s.tree x.row + (RowMerge.front read x.row x.after)) = (a, t) := by + simpa [RowMerge.advance, hw] using ha + rw [← (Prod.mk.inj heq).2] + exact RowMerge.replacement_rowsSorted key read view hread s.tree + s.valid s.aligned s.sorted hw + +theorem advance_consumes_one (key : α → ℤ) (read : σ → Option (α × σ)) + (view : σ → List α) (hread : RowMerge.IsReader read view) + (s : State key view d) {a : α} {t : Tournament.Tree (RowMerge.Front d α σ) d} + (ha : RowMerge.advance key read s.tree = some (a, t)) : + RowMerge.potential view t + 1 = RowMerge.potential view s.tree := by + cases hw : Tournament.winner s.tree with + | none => simp [RowMerge.advance, hw] at ha + | some x => + have heq : (x.value, Tournament.replace (fun y => key y.value) s.tree x.row + (RowMerge.front read x.row x.after)) = (a, t) := by + simpa [RowMerge.advance, hw] using ha + rw [← (Prod.mk.inj heq).2] + exact RowMerge.replacement_consumes_one key read view hread s.tree + s.valid s.aligned hw + +def next (key : α → ℤ) (read : σ → Option (α × σ)) + (view : σ → List α) (hread : RowMerge.IsReader read view) + (s : State key view d) : Option (α × State key view d) := + match ha : RowMerge.advance key read s.tree with + | none => none + | some (a, t) => some (a, ⟨t, + RowMerge.advance_valid key read s.tree s.valid ha, + RowMerge.advance_aligned key read s.tree s.aligned ha, + advance_sorted key read view hread s ha⟩) + +/-- The output view is never a field of the executable state. -/ +def output (key : α → ℤ) (read : σ → Option (α × σ)) + (view : σ → List α) (s : State key view d) : List α := + RowMerge.trace key read (RowMerge.potential view s.tree) s.tree + +theorem next_none (key : α → ℤ) (read : σ → Option (α × σ)) + (view : σ → List α) (hread : RowMerge.IsReader read view) + (s : State key view d) (ha : RowMerge.advance key read s.tree = none) : + next key read view hread s = none := by + unfold next + split + · rfl + · rename_i a t ht + rw [ha] at ht + cases ht + +theorem next_some (key : α → ℤ) (read : σ → Option (α × σ)) + (view : σ → List α) (hread : RowMerge.IsReader read view) + (s : State key view d) {a : α} {t : Tournament.Tree (RowMerge.Front d α σ) d} + (ha : RowMerge.advance key read s.tree = some (a, t)) : + next key read view hread s = some (a, ⟨t, + RowMerge.advance_valid key read s.tree s.valid ha, + RowMerge.advance_aligned key read s.tree s.aligned ha, + advance_sorted key read view hread s ha⟩) := by + unfold next + split + · rename_i hn + rw [ha] at hn + cases hn + · rename_i b t' ht + have heq : (a, t) = (b, t') := Option.some.inj (ha.symm.trans ht) + obtain ⟨rfl, rfl⟩ := Prod.mk.inj heq + rfl + +theorem reader (key : α → ℤ) (read : σ → Option (α × σ)) + (view : σ → List α) (hread : RowMerge.IsReader read view) : + RowMerge.IsReader (next (d := d) key read view hread) (output key read view) := by + intro s + cases ha : RowMerge.advance key read s.tree with + | none => + rw [next_none key read view hread s ha] + unfold output + cases hp : RowMerge.potential view s.tree with + | zero => rfl + | succ k => simp only [RowMerge.trace, ha] + | some z => + obtain ⟨a, t⟩ := z + rw [next_some key read view hread s ha] + have hdec := advance_consumes_one key read view hread s ha + simp only [output, ← hdec, RowMerge.trace, ha] + +theorem output_bag (key : α → ℤ) (read : σ → Option (α × σ)) + (view : σ → List α) (hread : RowMerge.IsReader read view) + (s : State key view d) : + (output key read view s : Multiset α) = RowMerge.bag view s.tree := + RowMerge.trace_complete key read view hread _ s.tree s.valid s.aligned le_rfl + +theorem output_length (key : α → ℤ) (read : σ → Option (α × σ)) + (view : σ → List α) (hread : RowMerge.IsReader read view) + (s : State key view d) : + (output key read view s).length = RowMerge.potential view s.tree := by + have h := congrArg Multiset.card (output_bag key read view hread s) + simpa only [Multiset.coe_card, RowMerge.bag_card] using h + +theorem output_sorted (key : α → ℤ) (read : σ → Option (α × σ)) + (view : σ → List α) (hread : RowMerge.IsReader read view) + (s : State key view d) : + (output key read view s).Pairwise (fun x y => key x ≤ key y) := + RowMerge.trace_sorted key read view hread _ s.tree s.valid s.aligned s.sorted + +def start (key : α → ℤ) (read : σ → Option (α × σ)) + (view : σ → List α) (hread : RowMerge.IsReader read view) + (rows : RowMerge.Path d → σ) + (hsort : ∀ p, (view (rows p)).Pairwise (fun x y => key x ≤ key y)) : + State key view d := + ⟨RowMerge.start key read rows, RowMerge.start_valid key read rows, + RowMerge.start_aligned key read rows, fun p => by + rw [RowMerge.start_remaining key read view hread rows p] + exact hsort p⟩ + +theorem start_output_bag (key : α → ℤ) (read : σ → Option (α × σ)) + (view : σ → List α) (hread : RowMerge.IsReader read view) + (rows : RowMerge.Path d → σ) + (hsort : ∀ p, (view (rows p)).Pairwise (fun x y => key x ≤ key y)) : + (output key read view (start key read view hread rows hsort) : Multiset α) = + ∑ p : RowMerge.Path d, (view (rows p) : Multiset α) := by + rw [output_bag key read view hread] + simp only [RowMerge.bag, start, RowMerge.start_remaining key read view hread] + +theorem start_output_length (key : α → ℤ) (read : σ → Option (α × σ)) + (view : σ → List α) (hread : RowMerge.IsReader read view) + (rows : RowMerge.Path d → σ) + (hsort : ∀ p, (view (rows p)).Pairwise (fun x y => key x ≤ key y)) : + (output key read view (start key read view hread rows hsort)).length = + ∑ p : RowMerge.Path d, (view (rows p)).length := by + rw [output_length key read view hread] + simp only [RowMerge.potential, start, RowMerge.start_remaining key read view hread] + +theorem nodes_exact (key : α → ℤ) (view : σ → List α) (s : State key view d) : + Tournament.nodes s.tree + 1 = 2 ^ (d + 1) := Tournament.nodes_exact s.tree + +def advanceComparisons (key : α → ℤ) (view : σ → List α) (s : State key view d) : ℕ := + match Tournament.winner s.tree with + | none => 0 + | some x => Tournament.replaceComparisons s.tree x.row + +theorem advanceComparisons_le (key : α → ℤ) (view : σ → List α) (s : State key view d) : + advanceComparisons key view s ≤ d := by + unfold advanceComparisons + split + · exact Nat.zero_le d + · exact (Tournament.replaceComparisons_eq _ _).le + +end MergedReader +end LowSpaceSubsetSum + +end OAI diff --git a/lean/OAI/Combinatorics/LowSpaceSubsetSum/Streams/ModularCursor.lean b/lean/OAI/Combinatorics/LowSpaceSubsetSum/Streams/ModularCursor.lean new file mode 100644 index 0000000000000000000000000000000000000000..42f8ae611e641b702d3bbc5cdc18fc3e79958903 --- /dev/null +++ b/lean/OAI/Combinatorics/LowSpaceSubsetSum/Streams/ModularCursor.lean @@ -0,0 +1,104 @@ +import OAI.Combinatorics.LowSpaceSubsetSum.Streams.CyclicCursor +import OAI.Combinatorics.LowSpaceSubsetSum.Streams.BinaryPivot + +namespace OAI + +/-! +# Executable modular row initialization + +Binary search finds the first direct pivot and the position after the last +complementary pivot. The resulting constant-state cyclic cursor produces +the corresponding sorted modular row exactly. The cutoff search uses a +supplied number of steps; the theorem requires only that the array length +be smaller than `2^k`. Equal residues stay separate array occurrences. +-/ + +namespace LowSpaceSubsetSum +namespace ModularCursor + +open scoped Fin.NatCast + +variable {n : ℕ} [NeZero n] {α : Type*} + +def forwardStart (a : Fin n → α) (residue : α → ℤ) (P r : ℤ) (k : ℕ) : + CyclicCursor.State n := + ⟨Fin.ofNat n (BinaryPivot.search (fun i => decide (residue (a i) < P - r)) k).lo, + n, false⟩ + +def reverseStart (a : Fin n → α) (residue : α → ℤ) (K : ℤ) (k : ℕ) : + CyclicCursor.State n := + ⟨Fin.ofNat n (BinaryPivot.search (fun i => decide (residue (a i) ≤ K)) k).lo - 1, + n, true⟩ + +theorem forward_trace (a : Fin n → α) (residue : α → ℤ) (P r : ℤ) (k : ℕ) + (hk : n < 2 ^ k) (hsort : Monotone (fun i => residue (a i))) : + CyclicCursor.trace a n (forwardStart a residue P r k) = + ModularRows.direct P r residue (List.ofFn a) := by + have hprefix : BinaryPivot.PrefixPredicate + (fun i : Fin n => decide (residue (a i) < P - r)) := by + intro i j hij hj + apply decide_eq_true + exact lt_of_le_of_lt (hsort hij) (of_decide_eq_true hj) + have hsplit := BinaryPivot.search_split a + (fun x => decide (residue x < P - r)) hprefix k hk + let c := BinaryPivot.search (fun i : Fin n => decide (residue (a i) < P - r)) k + let lo := (List.ofFn a).take c.lo + let hi := (List.ofFn a).drop c.lo + have hc : c.lo ≤ n := c.ordered.trans c.bounded + have hlist : List.ofFn a = lo ++ hi := (List.take_append_drop c.lo _).symm + apply CyclicCursor.forward_trace_eq_direct a P r residue lo hi hlist + (Fin.ofNat n c.lo) + · simp [lo, hc] + · simpa only [decide_eq_true_eq] using hsplit.1 + · simpa only [decide_eq_false_iff_not, not_lt] using hsplit.2 + +theorem reverse_trace (a : Fin n → α) (residue : α → ℤ) (K : ℤ) (k : ℕ) + (hk : n < 2 ^ k) (hsort : Monotone (fun i => residue (a i))) : + CyclicCursor.trace a n (reverseStart a residue K k) = + ModularRows.complementary K residue (List.ofFn a) := by + have hprefix : BinaryPivot.PrefixPredicate + (fun i : Fin n => decide (residue (a i) ≤ K)) := by + intro i j hij hj + apply decide_eq_true + exact (hsort hij).trans (of_decide_eq_true hj) + have hsplit := BinaryPivot.search_split a + (fun x => decide (residue x ≤ K)) hprefix k hk + let c := BinaryPivot.search (fun i : Fin n => decide (residue (a i) ≤ K)) k + let lo := (List.ofFn a).take c.lo + let hi := (List.ofFn a).drop c.lo + have hc : c.lo ≤ n := c.ordered.trans c.bounded + have hlist : List.ofFn a = lo ++ hi := (List.take_append_drop c.lo _).symm + apply CyclicCursor.reverse_trace_eq_complementary a K residue lo hi hlist + (Fin.ofNat n c.lo) + · simp [lo, hc] + · simpa only [decide_eq_true_eq] using hsplit.1 + · simpa only [decide_eq_false_iff_not, not_le] using hsplit.2 + +theorem forward_sorted (a : Fin n → α) (residue : α → ℤ) (P r : ℤ) (k : ℕ) + (hk : n < 2 ^ k) (hsort : Monotone (fun i => residue (a i))) + (hr : 0 ≤ r) (hrP : r < P) (hbound : ∀ i, 0 ≤ residue (a i) ∧ residue (a i) < P) : + (CyclicCursor.trace a n (forwardStart a residue P r k)).Pairwise + (fun x y => (r + residue x) % P ≤ (r + residue y) % P) := by + rw [forward_trace a residue P r k hk hsort] + apply ModularRows.direct_sorted hr hrP + · intro x hx + obtain ⟨i, rfl⟩ := List.mem_ofFn.mp hx + exact hbound i + · exact List.pairwise_ofFn.mpr (fun _ _ h => hsort h.le) + +theorem reverse_sorted (a : Fin n → α) (residue : α → ℤ) (P K : ℤ) (k : ℕ) + (hk : n < 2 ^ k) (hsort : Monotone (fun i => residue (a i))) + (hK : 0 ≤ K) (hKP : K < P) (hbound : ∀ i, 0 ≤ residue (a i) ∧ residue (a i) < P) : + (CyclicCursor.trace a n (reverseStart a residue K k)).Pairwise + (fun x y => (K - residue x) % P ≤ (K - residue y) % P) := by + rw [reverse_trace a residue K k hk hsort] + apply ModularRows.complementary_sorted hK hKP + · intro x hx + obtain ⟨i, rfl⟩ := List.mem_ofFn.mp hx + exact hbound i + · exact List.pairwise_ofFn.mpr (fun _ _ h => hsort h.le) + +end ModularCursor +end LowSpaceSubsetSum + +end OAI diff --git a/lean/OAI/Combinatorics/LowSpaceSubsetSum/Streams/ModularFilters.lean b/lean/OAI/Combinatorics/LowSpaceSubsetSum/Streams/ModularFilters.lean new file mode 100644 index 0000000000000000000000000000000000000000..283d75fef1721b1711b3348fc6b4637cf8cf88cd --- /dev/null +++ b/lean/OAI/Combinatorics/LowSpaceSubsetSum/Streams/ModularFilters.lean @@ -0,0 +1,62 @@ +import Mathlib.Data.Int.ModEq +import Mathlib.Tactic + +namespace OAI + +/-! +# Nested filters and enumeration of parent residue classes + +The congruence and finite-loop facts used by both trials. No coprimality of +the low modulus and the additional prime is required. +-/ + +namespace LowSpaceSubsetSum + +/-- A passing parent and first child force the second child's low filter. -/ +theorem nested_second_child_filter {p p0 x1 x2 w rho : ℤ} + (hdiv : p ∣ p0) (hparent : x1 + x2 ≡ w [ZMOD p0]) + (hchild : x1 ≡ rho [ZMOD p]) : x2 ≡ w - rho [ZMOD p] := by + have h := (hparent.of_dvd hdiv).sub hchild + convert h using 1 + ring + +/-- Every lifted class has the prescribed low residue. -/ +theorem lift_low_residue {p rho z : ℕ} (hrho : rho < p) : + (rho + p * z) % p = rho := by + simp [Nat.add_mod, Nat.mod_eq_of_lt hrho] + +/-- The program's lift lies within the product modulus. -/ +theorem lift_lt_product {p q rho z : ℕ} (hrho : rho < p) (hz : z < q) : + rho + p * z < p * q := by + have hz' : z + 1 ≤ q := by omega + have hp := Nat.mul_le_mul_left p hz' + nlinarith + +/-- All product-modulus residues with a given low base occur exactly once in +the loop over `z < q`, including when `q` and `p` have a common factor. -/ +theorem lift_residue_exists_unique {p q rho r : ℕ} + (hp : 0 < p) (hr : r < p * q) (hbase : r % p = rho) : + ∃! z : ℕ, z < q ∧ r = rho + p * z := by + have hz : r / p < q := (Nat.div_lt_iff_lt_mul hp).mpr (by simpa [mul_comm] using hr) + have heq : r = rho + p * (r / p) := by + have h := Nat.mod_add_div r p + omega + refine ⟨r / p, ⟨hz, heq⟩, ?_⟩ + intro z hz' + have hprod : p * z = p * (r / p) := by omega + exact Nat.eq_of_mul_eq_mul_left hp hprod + +/-- Complementing the target gives a bijection of the product residue ring. -/ +theorem complementary_residue_injective {P t : ℤ} {x y : ℤ} + (hx : 0 ≤ x ∧ x < P) (hy : 0 ≤ y ∧ y < P) + (h : (t - x) % P = (t - y) % P) : x = y := by + have hm : t - x ≡ t - y [ZMOD P] := h + have hxym := hm.neg.add_left t + have hxy : x % P = y % P := by + change x ≡ y [ZMOD P] + convert hxym using 1 <;> ring + rwa [Int.emod_eq_of_lt hx.1 hx.2, Int.emod_eq_of_lt hy.1 hy.2] at hxy + +end LowSpaceSubsetSum + +end OAI diff --git a/lean/OAI/Combinatorics/LowSpaceSubsetSum/Streams/ModularRows.lean b/lean/OAI/Combinatorics/LowSpaceSubsetSum/Streams/ModularRows.lean new file mode 100644 index 0000000000000000000000000000000000000000..85d77f07adf14095291855b8042b7114d9679e7d --- /dev/null +++ b/lean/OAI/Combinatorics/LowSpaceSubsetSum/Streams/ModularRows.lean @@ -0,0 +1,137 @@ +import Mathlib.Data.List.Pairwise +import Mathlib.Data.List.Perm.Basic +import Mathlib.Data.Int.ModEq +import Mathlib.Tactic + +namespace OAI + +/-! +# The modular pivot order of a pair-stream row + +These are the two cyclic orders in `lem:streams`. The list is an analysis view +of one sorted slice: implementation can traverse the slice by its pivot and +cursor, rather than allocating the reordered list. The permutation theorems +preserve occurrence multiplicity, including repeated residues. +-/ + +namespace LowSpaceSubsetSum +namespace ModularRows + +variable {α : Type*} + +def direct (P r : ℤ) (residue : α → ℤ) (xs : List α) : List α := + xs.filter (fun x => decide (P - r ≤ residue x)) ++ + xs.filter (fun x => decide (residue x < P - r)) + +def complementary (K : ℤ) (residue : α → ℤ) (xs : List α) : List α := + (xs.filter (fun x => decide (residue x ≤ K))).reverse ++ + (xs.filter (fun x => decide (K < residue x))).reverse + +theorem direct_perm (P r : ℤ) (residue : α → ℤ) (xs : List α) : + (direct P r residue xs).Perm xs := by + simpa only [direct, ← decide_not, not_le] using + List.filter_append_perm (fun x => decide (P - r ≤ residue x)) xs + +theorem complementary_perm (K : ℤ) (residue : α → ℤ) (xs : List α) : + (complementary K residue xs).Perm xs := by + apply ((List.reverse_perm _).append (List.reverse_perm _)).trans + simpa only [← decide_not, not_le] using List.filter_append_perm (fun x => decide (residue x ≤ K)) xs + +theorem direct_wrapped {P r x : ℤ} (_hr : 0 ≤ r) (hrP : r < P) + (_hx : 0 ≤ x) (hxP : x < P) (hwrap : P - r ≤ x) : + (r + x) % P = r + x - P := by + rw [← Int.sub_emod_right (r + x) P] + exact Int.emod_eq_of_lt (by omega) (by omega) + +theorem direct_unwrapped {P r x : ℤ} (hr : 0 ≤ r) + (hx : 0 ≤ x) (hwrap : x < P - r) : (r + x) % P = r + x := + Int.emod_eq_of_lt (by omega) (by omega) + +theorem complementary_low {P K x : ℤ} (_hK : 0 ≤ K) (hKP : K < P) + (hx : 0 ≤ x) (hsmall : x ≤ K) : (K - x) % P = K - x := + Int.emod_eq_of_lt (by omega) (by omega) + +theorem complementary_high {P K x : ℤ} (hK : 0 ≤ K) (_hKP : K < P) + (hxP : x < P) (hlarge : K < x) : (K - x) % P = K - x + P := by + rw [← Int.add_emod_right (K - x) P] + exact Int.emod_eq_of_lt (by omega) (by omega) + +/-- Direct cyclic traversal is sorted by normalized pair residue. -/ +theorem direct_sorted {P r : ℤ} (hr : 0 ≤ r) (hrP : r < P) + (residue : α → ℤ) (xs : List α) + (hbound : ∀ x ∈ xs, 0 ≤ residue x ∧ residue x < P) + (hsort : xs.Pairwise (fun x y => residue x ≤ residue y)) : + (direct P r residue xs).Pairwise + (fun x y => (r + residue x) % P ≤ (r + residue y) % P) := by + apply List.pairwise_append.mpr + refine ⟨?_, ?_, ?_⟩ + · apply (hsort.filter (fun x => decide (P - r ≤ residue x))).imp_of_mem + intro x y hx hy hxy + obtain ⟨hxmem, hxwrap⟩ := List.mem_filter.mp hx + obtain ⟨hymem, hywrap⟩ := List.mem_filter.mp hy + have hxw : P - r ≤ residue x := of_decide_eq_true hxwrap + have hyw : P - r ≤ residue y := of_decide_eq_true hywrap + rw [direct_wrapped hr hrP (hbound x hxmem).1 (hbound x hxmem).2 hxw, + direct_wrapped hr hrP (hbound y hymem).1 (hbound y hymem).2 hyw] + omega + · apply (hsort.filter (fun x => decide (residue x < P - r))).imp_of_mem + intro x y hx hy hxy + obtain ⟨hxmem, hxwrap⟩ := List.mem_filter.mp hx + obtain ⟨hymem, hywrap⟩ := List.mem_filter.mp hy + rw [direct_unwrapped hr (hbound x hxmem).1 (of_decide_eq_true hxwrap), + direct_unwrapped hr (hbound y hymem).1 (of_decide_eq_true hywrap)] + omega + · intro x hx y hy + obtain ⟨hxmem, hxwrap⟩ := List.mem_filter.mp hx + obtain ⟨hymem, hywrap⟩ := List.mem_filter.mp hy + rw [direct_wrapped hr hrP (hbound x hxmem).1 (hbound x hxmem).2 + (of_decide_eq_true hxwrap), + direct_unwrapped hr (hbound y hymem).1 (of_decide_eq_true hywrap)] + have := (hbound x hxmem).2 + have := (hbound y hymem).1 + omega + +/-- Reverse cyclic traversal is sorted by the complementary residue. -/ +theorem complementary_sorted {P K : ℤ} (hK : 0 ≤ K) (hKP : K < P) + (residue : α → ℤ) (xs : List α) + (hbound : ∀ x ∈ xs, 0 ≤ residue x ∧ residue x < P) + (hsort : xs.Pairwise (fun x y => residue x ≤ residue y)) : + (complementary K residue xs).Pairwise + (fun x y => (K - residue x) % P ≤ (K - residue y) % P) := by + apply List.pairwise_append.mpr + refine ⟨?_, ?_, ?_⟩ + · apply List.pairwise_reverse.mpr + apply (hsort.filter (fun x => decide (residue x ≤ K))).imp_of_mem + intro x y hx hy hxy + obtain ⟨hxmem, hxsmall⟩ := List.mem_filter.mp hx + obtain ⟨hymem, hysmall⟩ := List.mem_filter.mp hy + rw [complementary_low hK hKP (hbound x hxmem).1 (of_decide_eq_true hxsmall), + complementary_low hK hKP (hbound y hymem).1 (of_decide_eq_true hysmall)] + omega + · apply List.pairwise_reverse.mpr + apply (hsort.filter (fun x => decide (K < residue x))).imp_of_mem + intro x y hx hy hxy + obtain ⟨hxmem, hxlarge⟩ := List.mem_filter.mp hx + obtain ⟨hymem, hylarge⟩ := List.mem_filter.mp hy + rw [complementary_high hK hKP (hbound x hxmem).2 (of_decide_eq_true hxlarge), + complementary_high hK hKP (hbound y hymem).2 (of_decide_eq_true hylarge)] + omega + · intro x hx y hy + obtain ⟨hxmem, hxsmall⟩ := List.mem_filter.mp (List.mem_reverse.mp hx) + obtain ⟨hymem, hylarge⟩ := List.mem_filter.mp (List.mem_reverse.mp hy) + rw [complementary_low hK hKP (hbound x hxmem).1 (of_decide_eq_true hxsmall), + complementary_high hK hKP (hbound y hymem).2 (of_decide_eq_true hylarge)] + have := (hbound x hxmem).1 + have := (hbound y hymem).2 + omega + +/-- Filtering a row by the small modulus preserves its residue ordering. -/ +theorem filtered_sorted (p c : ℤ) (weight residue : α → ℤ) (xs : List α) + (hsort : xs.Pairwise (fun x y => residue x ≤ residue y)) : + (xs.filter (fun x => decide (weight x % p = c % p))).Pairwise + (fun x y => residue x ≤ residue y) := hsort.filter _ + +end ModularRows +end LowSpaceSubsetSum + +end OAI diff --git a/lean/OAI/Combinatorics/LowSpaceSubsetSum/Streams/PaddedRows.lean b/lean/OAI/Combinatorics/LowSpaceSubsetSum/Streams/PaddedRows.lean new file mode 100644 index 0000000000000000000000000000000000000000..06fcd12c19f68ec6a59cc0bd650e5122957f90cf --- /dev/null +++ b/lean/OAI/Combinatorics/LowSpaceSubsetSum/Streams/PaddedRows.lean @@ -0,0 +1,101 @@ +import OAI.Combinatorics.LowSpaceSubsetSum.Streams.MergedReader +import Mathlib.Algebra.BigOperators.Fin + +namespace OAI + +/-! +# Binary indexing and empty padding for the row tournament + +Binary paths index a power-of-two set of leaves. Array indices occupy the +initial segment and all other leaves are empty. The reindexing proof counts +exact occurrences; its finite sums and lists are analysis views only. +-/ + +namespace LowSpaceSubsetSum +namespace PaddedRows + +variable {α σ : Type*} + +def index (d : ℕ) : RowMerge.Path d ≃ Fin (2 ^ d) := + (Equiv.piCongrRight (fun _ : Fin d => finTwoEquiv.symm)).trans finFunctionFinEquiv + +def next (read : σ → Option (α × σ)) : Option σ → Option (α × Option σ) + | none => none + | some s => (read s).map (fun z => (z.1, some z.2)) + +def view (output : σ → List α) : Option σ → List α + | none => [] + | some s => output s + +theorem reader (read : σ → Option (α × σ)) (output : σ → List α) + (hread : RowMerge.IsReader read output) : RowMerge.IsReader (next read) (view output) := by + intro s + cases s with + | none => rfl + | some s => + have h := hread s + cases hr : read s with + | none => simpa only [next, hr, Option.map_none, view] using h + | some z => simpa only [next, hr, Option.map_some, view] using h + +def rows (xs : Array σ) (d : ℕ) (p : RowMerge.Path d) : Option σ := + if h : (index d p).val < xs.size then some xs[(index d p).val] else none + +theorem rows_sorted (xs : Array σ) (d : ℕ) (output : σ → List α) (key : α → ℤ) + (hs : ∀ s ∈ xs.toList, (output s).Pairwise (fun x y => key x ≤ key y)) + (p : RowMerge.Path d) : + (view output (rows xs d p)).Pairwise (fun x y => key x ≤ key y) := by + unfold rows + split_ifs with h + · apply hs + exact List.mem_iff_getElem.mpr ⟨(index d p).val, + by simpa only [Array.length_toList] using h, by simp⟩ + · simp [view] + +theorem sum_padding {M : Type*} [AddCommMonoid M] (n m : ℕ) (hnm : n ≤ m) + (f : Fin n → M) : + (∑ i : Fin m, if h : i.val < n then f ⟨i.val, h⟩ else 0) = ∑ i : Fin n, f i := by + induction m with + | zero => + have hn : n = 0 := by omega + subst n + simp + | succ m ih => + by_cases hn : n ≤ m + · rw [Fin.sum_univ_castSucc] + have hlast : ¬ m < n := by omega + simp only [Fin.val_castSucc, Fin.val_last, dite_eq_right hlast, add_zero] + exact ih hn + · have hn : n = m + 1 := by omega + subst n + apply Finset.sum_congr rfl + intro i _ + exact dite_eq_left i.isLt + +theorem sum_rows {M : Type*} [AddCommMonoid M] (xs : Array σ) (d : ℕ) + (hd : xs.size ≤ 2 ^ d) (f : σ → M) : + (∑ p : RowMerge.Path d, match rows xs d p with | none => 0 | some s => f s) = + ∑ i : Fin xs.size, f xs[i.val] := by + calc + _ = ∑ i : Fin (2 ^ d), if h : i.val < xs.size then f xs[i.val] else 0 := by + apply Fintype.sum_equiv (index d) + intro p + dsimp only [rows] + split_ifs <;> rfl + _ = _ := sum_padding xs.size (2 ^ d) hd (fun i => f xs[i.val]) + +theorem row_bag (xs : Array σ) (d : ℕ) (hd : xs.size ≤ 2 ^ d) (output : σ → List α) : + (∑ p : RowMerge.Path d, (view output (rows xs d p) : Multiset α)) = + ∑ i : Fin xs.size, (output xs[i.val] : Multiset α) := by + calc + _ = ∑ p : RowMerge.Path d, + match rows xs d p with | none => 0 | some s => (output s : Multiset α) := by + apply Finset.sum_congr rfl + intro p _ + cases rows xs d p <;> rfl + _ = _ := sum_rows xs d hd (fun s => (output s : Multiset α)) + +end PaddedRows +end LowSpaceSubsetSum + +end OAI diff --git a/lean/OAI/Combinatorics/LowSpaceSubsetSum/Streams/PairCursor.lean b/lean/OAI/Combinatorics/LowSpaceSubsetSum/Streams/PairCursor.lean new file mode 100644 index 0000000000000000000000000000000000000000..7c23f5053be320b57a58e9ea0e1f94ec53193704 --- /dev/null +++ b/lean/OAI/Combinatorics/LowSpaceSubsetSum/Streams/PairCursor.lean @@ -0,0 +1,37 @@ +import OAI.Combinatorics.LowSpaceSubsetSum.Streams.SliceCursor + +namespace OAI + +/-! # Attach one fixed first-array occurrence to a shared-array row reader -/ + +namespace LowSpaceSubsetSum +namespace PairCursor + +variable {α β : Type*} + +structure State (α : Type*) (n : ℕ) where + left : α + cursor : SliceCursor.State n + +def next (xs : Array β) (s : State α xs.size) : Option ((α × β) × State α xs.size) := + (SliceCursor.next xs s.cursor).map (fun z => ((s.left, z.1), ⟨s.left, z.2⟩)) + +def output (xs : Array β) (s : State α xs.size) : List (α × β) := + (SliceCursor.output xs s.cursor).map (fun y => (s.left, y)) + +theorem reader (xs : Array β) : RowMerge.IsReader (next (α := α) xs) (output xs) := by + intro s + have hr := SliceCursor.reader xs s.cursor + cases h : SliceCursor.next xs s.cursor with + | none => + simp only [h] at hr + simp only [next, h, Option.map_none, output, hr, List.map_nil] + | some z => + obtain ⟨y, c⟩ := z + simp only [h] at hr + simp only [next, h, Option.map_some, output, hr, List.map_cons] + +end PairCursor +end LowSpaceSubsetSum + +end OAI diff --git a/lean/OAI/Combinatorics/LowSpaceSubsetSum/Streams/ParentPrefixSearch.lean b/lean/OAI/Combinatorics/LowSpaceSubsetSum/Streams/ParentPrefixSearch.lean new file mode 100644 index 0000000000000000000000000000000000000000..9f12e3b8ec2e15e0a79d93437fdc79da1d2dd802 --- /dev/null +++ b/lean/OAI/Combinatorics/LowSpaceSubsetSum/Streams/ParentPrefixSearch.lean @@ -0,0 +1,144 @@ +import OAI.Combinatorics.LowSpaceSubsetSum.Representation.RepresentationParentComplete +import OAI.Combinatorics.LowSpaceSubsetSum.Streams.DictionaryCompleted +import OAI.Combinatorics.LowSpaceSubsetSum.Separators.SeparatorEncodedCheck + +namespace OAI + +/-! # Actual depth-first right-parent prefix recomputation -/ + +namespace LowSpaceSubsetSum + +namespace MaskRestriction + +variable {n : ℕ} + +def force (P : MaskRestriction n) (i : Fin n) (side : Bool) : MaskRestriction n := + if side then { P with ones := Insert.insert i P.ones } + else { P with zeros := Insert.insert i P.zeros } + +def follow (P : MaskRestriction n) (order : List (Fin n)) (S : Finset (Fin n)) : MaskRestriction n := + order.foldl (fun P i => P.force i (decide (i ∈ S))) P + +theorem force_compatible (P : MaskRestriction n) (domain S : Finset (Fin n)) + (h : P.Compatible domain S) (i : Fin n) : + (P.force i (decide (i ∈ S))).Compatible domain S := by + by_cases hi : i ∈ S + · simp only [hi, decide_true, force, ↓reduceIte, Compatible] + refine ⟨?_, h.2⟩ + intro j hj + obtain ⟨hj, hjD⟩ := Finset.mem_inter.mp hj + rcases Finset.mem_insert.mp hj with rfl | hj + · exact hi + · exact h.1 (Finset.mem_inter.mpr ⟨hj, hjD⟩) + · simp only [hi, decide_false, force, Bool.false_eq_true, ↓reduceIte, Compatible] + refine ⟨h.1, Finset.disjoint_left.mpr ?_⟩ + intro j hj hjS + rcases Finset.mem_insert.mp hj with rfl | hj + · exact hi hjS + · exact Finset.disjoint_left.mp h.2 hj hjS + +end MaskRestriction + +namespace RepresentationParentData + +variable {n : ℕ} (D : RepresentationParentData n) + +/-- Each task regenerates its restricted leaves and streams. An overflowing +full prefix is dropped; a completed array is passed to the actual checker. +The first YES returns immediately. -/ +def searchRight (B : ℕ) (check : Array (Entry (Fin n)) → Bool) : + List (Fin n) → MaskRestriction n → Bool + | order, P => + let task := { D with maskRestriction := P } + let out := (task.collect B).state.user + if out.keys.overflow then + match order with + | [] => false + | i :: rest => + if searchRight B check rest (P.force i false) then true + else searchRight B check rest (P.force i true) + else check out.records + +theorem searchRight_sound (B : ℕ) (check : Array (Entry (Fin n)) → Bool) + (Q : Prop) (hcheck : ∀ P, check ({ D with maskRestriction := P }.entries B) = true → Q) + (order : List (Fin n)) (P : MaskRestriction n) (hyes : D.searchRight B check order P = true) : Q := by + induction order generalizing P with + | nil => + simp only [searchRight] at hyes + split at hyes + · contradiction + · exact hcheck P hyes + | cons i order ih => + simp only [searchRight] at hyes + split at hyes + · split at hyes + · rename_i hl + exact ih _ hl + · exact ih _ hyes + · exact hcheck P hyes + +/-- A fitting task at the end of a designated mask path suffices. Earlier +completion reaches the checker; earlier YES also returns immediately. -/ +theorem searchRight_complete (B : ℕ) (check : Array (Entry (Fin n)) → Bool) + (domain S : Finset (Fin n)) + (hfind : ∀ P, P.Compatible domain S → + ({ D with maskRestriction := P }.collect B).state.user.keys.overflow = false → + check ({ D with maskRestriction := P }.entries B) = true) + (order : List (Fin n)) (P : MaskRestriction n) (hP : P.Compatible domain S) + (hfull : ({ D with maskRestriction := P.follow order S }.collect B).state.user.keys.overflow = false) : + D.searchRight B check order P = true := by + induction order generalizing P with + | nil => + have hc : ({ D with maskRestriction := P }.collect B).state.user.keys.overflow = false := hfull + simpa only [searchRight, hc, Bool.false_eq_true, ↓reduceIte, entries] using hfind P hP hc + | cons i order ih => + by_cases ho : ({ D with maskRestriction := P }.collect B).state.user.keys.overflow = true + · have hnext := ih (P.force i (decide (i ∈ S))) (P.force_compatible domain S hP i) hfull + cases hb : decide (i ∈ S) with + | false => + simp only [hb] at hnext + simp only [searchRight, ho, ↓reduceIte, hnext] + | true => + simp only [hb] at hnext + simp only [searchRight, ho, ↓reduceIte] + split + · rfl + · exact hnext + · have hc : ({ D with maskRestriction := P }.collect B).state.user.keys.overflow = false := + Bool.eq_false_iff.mpr ho + simpa only [searchRight, hc, Bool.false_eq_true, ↓reduceIte, entries] using hfind P hP hc +/-- No prefix task can introduce a false YES. This applies to every family +outcome and every overflow pattern, rather than just the surviving bucket. -/ +theorem searchRight_subset_sum_sound {g : ℕ} (B : ℕ) (C : TopCoordinates n g) + (families : Fin 4 → Array (Finset (Fin g))) (left : Array (Entry (Fin n))) + (order : List (Fin n)) (P : MaskRestriction n) (leftDomain : Finset (Fin n)) + (htop : RepresentationUniverse.topDomain D.leaves = C.domain) + (htl : Disjoint (RepresentationUniverse.topDomain D.leaves) + (RepresentationUniverse.mixerDomain D.leaves)) + (htb : Disjoint (RepresentationUniverse.topDomain D.leaves) + (RepresentationUniverse.backgroundDomain D.leaves)) + (hlb : Disjoint (RepresentationUniverse.mixerDomain D.leaves) + (RepresentationUniverse.backgroundDomain D.leaves)) + (hshared : leftDomain ∩ RepresentationUniverse.parentDomain D.leaves ⊆ C.domain) + (hleft : ∀ e ∈ left.toList, Represents D.weights leftDomain C.domain e) + (hsize : left.size + (D.capacity + 1) ≤ 2 ^ n) + (hyes : D.searchRight B (fun right => (C.check families + ((D.input.target : ℤ) - weight (fun i => (D.input.values i : ℤ)) D.signs) + left.toList right.toList).accepted) order P = true) : Solvable D.input := by + apply D.searchRight_sound B _ (Solvable D.input) ?_ order P hyes + intro P hp + let task := { D with maskRestriction := P } + apply C.subset_sum_sound D.input D.signs families left.toList (task.entries B).toList + (leftDomain := leftDomain) (rightDomain := RepresentationUniverse.parentDomain D.leaves) + (by + simp only [Array.length_toList] + exact (Nat.add_le_add_left (task.storage B).1 _).trans hsize) + hshared hleft ?_ hp + intro e he + rw [← htop] + exact task.entry_represents B htl htb hlb e he + +end RepresentationParentData +end LowSpaceSubsetSum + +end OAI diff --git a/lean/OAI/Combinatorics/LowSpaceSubsetSum/Streams/PrefixAccounting.lean b/lean/OAI/Combinatorics/LowSpaceSubsetSum/Streams/PrefixAccounting.lean new file mode 100644 index 0000000000000000000000000000000000000000..8c4afea5ead2511fd44186598bc5587caa8f9ab1 --- /dev/null +++ b/lean/OAI/Combinatorics/LowSpaceSubsetSum/Streams/PrefixAccounting.lean @@ -0,0 +1,210 @@ +import Mathlib.Data.Finset.Card +import Mathlib.Data.Finset.Filter +import Mathlib.Tactic + +namespace OAI + +/-! +# Deterministic accounting for right-prefix refinement + +The tree depends on distinct entries for overflow, while raw tuple occurrences +are charged separately. The finite sets in this mathematical accounting are +ambient analysis sets, not arrays that the implementation is allowed to store. +The resulting combinatorial bounds give the accounting in `lem:prefix`. +-/ + +namespace LowSpaceSubsetSum + +variable {α : Type*} + +/-- Labels of the successive mask bits, in the fixed processing order. -/ +abbrev MaskBits (α : Type*) := ℕ → α → Bool + +def bitPart (bits : MaskBits α) (depth : ℕ) (side : Bool) (U : Finset α) : Finset α := + U.filter fun x => bits depth x = side + +theorem bitPart_card_add (bits : MaskBits α) (depth : ℕ) (U : Finset α) : + (bitPart bits depth false U).card + (bitPart bits depth true U).card = U.card := by + have h := Finset.card_filter_add_card_filter_not (s := U) + (p := fun x => bits depth x = false) + simpa [bitPart, Bool.not_eq_false] using h + +/-- Overflow count includes an overflowing full-prefix node that is dropped. -/ +def overflowNodes (C : ℕ) (bits : MaskBits α) (depth : ℕ) : ℕ → Finset α → ℕ + | 0, U => if C < U.card then 1 else 0 + | fuel + 1, U => if C < U.card then + 1 + overflowNodes C bits (depth + 1) fuel (bitPart bits depth false U) + + overflowNodes C bits (depth + 1) fuel (bitPart bits depth true U) + else 0 + +/-- The task count includes empty completed tasks and dropped full prefixes. -/ +def prefixTasks (C : ℕ) (bits : MaskBits α) (depth : ℕ) : ℕ → Finset α → ℕ + | 0, _ => 1 + | fuel + 1, U => if C < U.card then + 1 + prefixTasks C bits (depth + 1) fuel (bitPart bits depth false U) + + prefixTasks C bits (depth + 1) fuel (bitPart bits depth true U) + else 1 + +/-- Sum of the lengths of all completed right dictionaries. -/ +def completedEntries (C : ℕ) (bits : MaskBits α) (depth : ℕ) : ℕ → Finset α → ℕ + | 0, U => if C < U.card then 0 else U.card + | fuel + 1, U => if C < U.card then + completedEntries C bits (depth + 1) fuel (bitPart bits depth false U) + + completedEntries C bits (depth + 1) fuel (bitPart bits depth true U) + else U.card + +/-- The sum of ambient entry counts over all task nodes, for charging by depth. -/ +def potentialVisits (C : ℕ) (bits : MaskBits α) (depth : ℕ) : ℕ → Finset α → ℕ + | 0, U => U.card + | fuel + 1, U => if C < U.card then + U.card + potentialVisits C bits (depth + 1) fuel (bitPart bits depth false U) + + potentialVisits C bits (depth + 1) fuel (bitPart bits depth true U) + else U.card + +/-- Raw occurrences are a separate type and retain all multiplicities. Task +branching is decided by `U`, the distinct entries, rather than by `T`. -/ +def rawVisits {β : Type*} (C : ℕ) (bits : MaskBits α) (rawBits : MaskBits β) + (depth : ℕ) : ℕ → Finset α → Finset β → ℕ + | 0, _, T => T.card + | fuel + 1, U, T => if C < U.card then + T.card + rawVisits C bits rawBits (depth + 1) fuel + (bitPart bits depth false U) (bitPart rawBits depth false T) + + rawVisits C bits rawBits (depth + 1) fuel + (bitPart bits depth true U) (bitPart rawBits depth true T) + else T.card + +/-- The bucket reached by following a designated entry's complete prefix. -/ +def fullPrefixBucket (bits : MaskBits α) (depth : ℕ) (e : α) : ℕ → Finset α → Finset α + | 0, U => U + | fuel + 1, U => fullPrefixBucket bits (depth + 1) e fuel + (bitPart bits depth (bits depth e) U) + +/-- The actual refinement path stops at the first dictionary that fits. -/ +def reachesCompleted (C : ℕ) (bits : MaskBits α) (depth : ℕ) (e : α) : + ℕ → Finset α → Prop + | 0, U => U.card ≤ C + | fuel + 1, U => U.card ≤ C ∨ reachesCompleted C bits (depth + 1) e fuel + (bitPart bits depth (bits depth e) U) + +theorem mem_fullPrefixBucket (bits : MaskBits α) (depth fuel : ℕ) + {e : α} {U : Finset α} (he : e ∈ U) : + e ∈ fullPrefixBucket bits depth e fuel U := by + induction fuel generalizing depth U with + | zero => exact he + | succ fuel ih => + apply ih + exact Finset.mem_filter.mpr ⟨he, rfl⟩ + +/-- A fitting full-prefix bucket ensures that the designated path completes, +even if larger ancestors overflow. -/ +theorem reachesCompleted_of_fullPrefix_fits (C : ℕ) (bits : MaskBits α) + (depth fuel : ℕ) (e : α) (U : Finset α) + (hfit : (fullPrefixBucket bits depth e fuel U).card ≤ C) : + reachesCompleted C bits depth e fuel U := by + induction fuel generalizing depth U with + | zero => exact hfit + | succ fuel ih => + right + exact ih (depth + 1) (bitPart bits depth (bits depth e) U) hfit + +theorem overflowNodes_capacity_bound (C : ℕ) (bits : MaskBits α) + (depth fuel : ℕ) (U : Finset α) : + C * overflowNodes C bits depth fuel U ≤ (fuel + 1) * U.card := by + induction fuel generalizing depth U with + | zero => + simp only [overflowNodes] + split_ifs with h <;> simp_all + omega + | succ fuel ih => + simp only [overflowNodes] + split_ifs with h + · have h0 := ih (depth + 1) (bitPart bits depth false U) + have h1 := ih (depth + 1) (bitPart bits depth true U) + have hc := bitPart_card_add bits depth U + nlinarith + · simp + +theorem prefixTasks_le_overflowNodes (C : ℕ) (bits : MaskBits α) + (depth fuel : ℕ) (U : Finset α) : + prefixTasks C bits depth fuel U ≤ 1 + 2 * overflowNodes C bits depth fuel U := by + induction fuel generalizing depth U with + | zero => simp [prefixTasks, overflowNodes] + | succ fuel ih => + simp only [prefixTasks, overflowNodes] + split_ifs with h + · have h0 := ih (depth + 1) (bitPart bits depth false U) + have h1 := ih (depth + 1) (bitPart bits depth true U) + omega + · simp + +/-- Division-free version of the right task-start bound. -/ +theorem prefixTasks_capacity_bound (C : ℕ) (bits : MaskBits α) + (depth fuel : ℕ) (U : Finset α) : + C * prefixTasks C bits depth fuel U ≤ C + 2 * (fuel + 1) * U.card := by + have ht := prefixTasks_le_overflowNodes C bits depth fuel U + have ho := overflowNodes_capacity_bound C bits depth fuel U + nlinarith + +theorem completedEntries_le_card (C : ℕ) (bits : MaskBits α) + (depth fuel : ℕ) (U : Finset α) : + completedEntries C bits depth fuel U ≤ U.card := by + induction fuel generalizing depth U with + | zero => simp only [completedEntries]; split_ifs <;> omega + | succ fuel ih => + simp only [completedEntries] + split_ifs with h + · have h0 := ih (depth + 1) (bitPart bits depth false U) + have h1 := ih (depth + 1) (bitPart bits depth true U) + have hc := bitPart_card_add bits depth U + omega + · rfl + +/-- Every occurrence has exactly one prefix at a fixed depth. The total +potential work is charged by depth, even for occurrences later rejected. -/ +theorem potentialVisits_le_depth_mul_card (C : ℕ) (bits : MaskBits α) + (depth fuel : ℕ) (U : Finset α) : + potentialVisits C bits depth fuel U ≤ (fuel + 1) * U.card := by + induction fuel generalizing depth U with + | zero => simp [potentialVisits] + | succ fuel ih => + simp only [potentialVisits] + split_ifs with h + · have h0 := ih (depth + 1) (bitPart bits depth false U) + have h1 := ih (depth + 1) (bitPart bits depth true U) + have hc := bitPart_card_add bits depth U + nlinarith + · nlinarith + +/-- The occurrence bound is independent of deduplication and validity tests. -/ +theorem rawVisits_le_depth_mul_card {β : Type*} + (C : ℕ) (bits : MaskBits α) (rawBits : MaskBits β) + (depth fuel : ℕ) (U : Finset α) (T : Finset β) : + rawVisits C bits rawBits depth fuel U T ≤ (fuel + 1) * T.card := by + induction fuel generalizing depth U T with + | zero => simp [rawVisits] + | succ fuel ih => + simp only [rawVisits] + split_ifs with h + · have h0 := ih (depth + 1) (bitPart bits depth false U) + (bitPart rawBits depth false T) + have h1 := ih (depth + 1) (bitPart bits depth true U) + (bitPart rawBits depth true T) + have hc := bitPart_card_add rawBits depth T + nlinarith + · nlinarith + +/-- Even charging the left array at every task bounds all actual final-check +inputs. This includes every reuse of the same retained left array. -/ +theorem checkInputs_le (C L : ℕ) (hL : L ≤ C) (bits : MaskBits α) + (depth fuel : ℕ) (U : Finset α) : + completedEntries C bits depth fuel U + L * prefixTasks C bits depth fuel U ≤ + L + (2 * fuel + 3) * U.card := by + have ht := prefixTasks_le_overflowNodes C bits depth fuel U + have ho := overflowNodes_capacity_bound C bits depth fuel U + have he := completedEntries_le_card C bits depth fuel U + have hscale := Nat.mul_le_mul_left (overflowNodes C bits depth fuel U) hL + nlinarith + +end LowSpaceSubsetSum + +end OAI diff --git a/lean/OAI/Combinatorics/LowSpaceSubsetSum/Streams/PrefixCheckList.lean b/lean/OAI/Combinatorics/LowSpaceSubsetSum/Streams/PrefixCheckList.lean new file mode 100644 index 0000000000000000000000000000000000000000..94469b89dd0f67e9c5bb467389851a302ee95876 --- /dev/null +++ b/lean/OAI/Combinatorics/LowSpaceSubsetSum/Streams/PrefixCheckList.lean @@ -0,0 +1,90 @@ +import OAI.Combinatorics.LowSpaceSubsetSum.Representation.RepresentationBucketProgram + +namespace OAI + +/-! # A family-independent list of the completed prefix checks + +These lists describe the hypothetical full traversal for analysis. The +executable search regenerates one task at a time and stops at its first YES. +-/ + +namespace LowSpaceSubsetSum.RepresentationParentData + +variable {n : ℕ} (D : RepresentationParentData n) + +def completedArrays (B : ℕ) : List (Fin n) → MaskRestriction n → List (Array (Entry (Fin n))) + | order, P => + let task := { D with maskRestriction := P } + let out := (task.collect B).state.user + if out.keys.overflow then + match order with + | [] => [] + | i :: rest => completedArrays B rest (P.force i false) ++ + completedArrays B rest (P.force i true) + else [out.records] + +theorem searchRight_eq_any (B : ℕ) (check : Array (Entry (Fin n)) → Bool) + (order : List (Fin n)) (P : MaskRestriction n) : + D.searchRight B check order P = (D.completedArrays B order P).any check := by + induction order generalizing P with + | nil => + simp only [searchRight, completedArrays] + split <;> simp + | cons i order ih => + simp only [searchRight, completedArrays] + split + · rw [List.any_append, ← ih, ← ih] + split <;> simp_all + · simp + +theorem mem_completedArrays (B : ℕ) (order : List (Fin n)) (P : MaskRestriction n) + (a : Array (Entry (Fin n))) (ha : a ∈ D.completedArrays B order P) : + ∃ Q : MaskRestriction n, + ({ D with maskRestriction := Q }.collect B).state.user.keys.overflow = false ∧ + a = { D with maskRestriction := Q }.entries B := by + induction order generalizing P with + | nil => + simp only [completedArrays] at ha + split at ha + · simp at ha + · rename_i hc + have he : a = ({ D with maskRestriction := P }.collect B).state.user.records := by + simpa only [List.mem_singleton] using ha + exact ⟨P, Bool.eq_false_iff.mpr hc, he⟩ + | cons i order ih => + simp only [completedArrays] at ha + split at ha + · rcases List.mem_append.mp ha with hl | hr + · exact ih (P.force i false) hl + · exact ih (P.force i true) hr + · rename_i hc + have he : a = ({ D with maskRestriction := P }.collect B).state.user.records := by + simpa only [List.mem_singleton] using ha + exact ⟨P, Bool.eq_false_iff.mpr hc, he⟩ + +end LowSpaceSubsetSum.RepresentationParentData + +namespace LowSpaceSubsetSum.RepresentationBucketData + +variable {n g : ℕ} (D : RepresentationBucketData n g) + +def checkList (B : ℕ) : List (Array (Entry (Fin n)) × Array (Entry (Fin n))) := + let left := (D.left.collect B).state.user + if left.keys.overflow then [] + else if left.records.isEmpty then [] + else (D.right.completedArrays B D.topOrder MaskRestriction.empty).map (left.records, ·) + +theorem run_eq_any (B : ℕ) (families : Fin 4 → Array (Finset (Fin g))) : + D.run B families = (D.checkList B).any (fun p => D.check families p.1 p.2) := by + unfold run checkList + dsimp only + split + · simp + split + · simp + rw [D.right.searchRight_eq_any, List.any_map] + rfl + +end LowSpaceSubsetSum.RepresentationBucketData + +end OAI diff --git a/lean/OAI/Combinatorics/LowSpaceSubsetSum/Streams/PrefixMachine.lean b/lean/OAI/Combinatorics/LowSpaceSubsetSum/Streams/PrefixMachine.lean new file mode 100644 index 0000000000000000000000000000000000000000..3e2ccd0a93aa2ee0d8912e37b630b25cbb84379e --- /dev/null +++ b/lean/OAI/Combinatorics/LowSpaceSubsetSum/Streams/PrefixMachine.lean @@ -0,0 +1,197 @@ +import OAI.Combinatorics.LowSpaceSubsetSum.Streams.ParentPrefixSearch +import OAI.Combinatorics.LowSpaceSubsetSum.Search.Watchdog + +namespace OAI + +/-! # Explicit pending-sibling stack for prefix recomputation + +A collector result is inspected and discarded in one task action. A frame +contains only the next restriction and remaining index order. In particular, +no overflowing dictionary or reader state is retained in a frame. Task +execution inside this action is accounted for separately by the join ledger. +-/ + +namespace LowSpaceSubsetSum.PrefixMachine + +variable {n : ℕ} + +structure Job (n : ℕ) where + order : List (Fin n) + restriction : MaskRestriction n + +inductive Control (n : ℕ) + | eval : Job n → List (Job n) → Control n + | ret : Bool → List (Job n) → Control n + +namespace Control + +def stack : Control n → List (Job n) + | .eval _ pending => pending + | .ret _ pending => pending + +/-- Masks and an order pointer can use fewer cells. Counting every mask bit +and every remaining order element still gives this conservative bound. -/ +def cells (s : Control n) : ℕ := (4 * n + 16) * (s.stack.length + 1) + +end Control + +def step (D : RepresentationParentData n) (B : ℕ) + (check : Array (Entry (Fin n)) → Bool) : Control n → Watchdog.Transition (Control n) + | .eval job pending => + let out := ({ D with maskRestriction := job.restriction }.collect B).state.user + if out.keys.overflow then + match job.order with + | [] => .next (.ret false pending) + | i :: rest => .next (.eval ⟨rest, job.restriction.force i false⟩ + (⟨rest, job.restriction.force i true⟩ :: pending)) + else .next (.ret (check out.records) pending) + | .ret true _ => .halt true + | .ret false [] => .halt false + | .ret false (job :: pending) => .next (.eval job pending) + +def GoodStack (N : ℕ) (pending : List (Job n)) : Prop := + pending.Pairwise (fun a b => a.order.length < b.order.length) ∧ + ∀ job ∈ pending, job.order.length ≤ N + +def Invariant (N : ℕ) : Control n → Prop + | .eval job pending => GoodStack N pending ∧ job.order.length ≤ N ∧ + ∀ next ∈ pending, job.order.length ≤ next.order.length + | .ret _ pending => GoodStack N pending + +theorem goodStack_length {N : ℕ} {pending : List (Job n)} (h : GoodStack N pending) : + pending.length ≤ N + 1 := by + have hpair : (pending.map (fun j => j.order.length)).Pairwise (· < ·) := + List.pairwise_map.mpr h.1 + have hnd : (pending.map (fun j => j.order.length)).Nodup := + hpair.imp (fun hlt => Nat.ne_of_lt hlt) + have hsub : (pending.map (fun j => j.order.length)).toFinset ⊆ Finset.range (N + 1) := by + intro r hr + obtain ⟨job, hj, rfl⟩ := List.mem_map.mp (List.mem_toFinset.mp hr) + exact Finset.mem_range.mpr (Nat.lt_succ_of_le (h.2 job hj)) + have hc := Finset.card_le_card hsub + simpa only [List.toFinset_card_of_nodup hnd, List.length_map, Finset.card_range] using hc + +theorem invariant_next (D : RepresentationParentData n) (B : ℕ) + (check : Array (Entry (Fin n)) → Bool) (N : ℕ) (s t : Control n) + (hs : Invariant N s) (ht : step D B check s = .next t) : Invariant N t := by + cases s with + | eval job pending => + obtain ⟨hstack, hjob, hhead⟩ := hs + simp only [step] at ht + split at ht + · cases ho : job.order with + | nil => + simp only [ho] at ht + cases ht + exact hstack + | cons i rest => + simp only [ho] at ht + cases ht + have hlen : rest.length + 1 = job.order.length := by simp [ho] + refine ⟨⟨List.pairwise_cons.mpr ⟨?_, hstack.1⟩, ?_⟩, ?_, ?_⟩ + · intro next hn + exact lt_of_lt_of_le (by omega : rest.length < job.order.length) (hhead next hn) + · intro next hn + rcases List.mem_cons.mp hn with rfl | hn + · dsimp only; omega + · exact hstack.2 next hn + · dsimp only; omega + · intro next hn + rcases List.mem_cons.mp hn with rfl | hn + · exact le_rfl + · exact (show rest.length ≤ job.order.length by omega).trans (hhead next hn) + · cases ht + exact hstack + | ret b pending => + cases b with + | true => simp [step] at ht + | false => + cases pending with + | nil => simp [step] at ht + | cons job pending => + simp only [step] at ht + cases ht + obtain ⟨hpair, hbound⟩ := hs + obtain ⟨hhead, htail⟩ := List.pairwise_cons.mp hpair + refine ⟨⟨htail, fun j hj => hbound j (List.mem_cons_of_mem _ hj)⟩, + hbound job (List.mem_cons_self), ?_⟩ + exact fun j hj => (hhead j hj).le + +theorem cells_le (N : ℕ) (s : Control n) (hs : Invariant N s) : + s.cells ≤ (4 * n + 16) * (N + 2) := by + have hg : GoodStack N s.stack := by + cases s with + | eval job pending => exact hs.1 + | ret b pending => exact hs + have hl := goodStack_length hg + exact Nat.mul_le_mul_left _ (by omega) + +def jobValue (D : RepresentationParentData n) (B : ℕ) + (check : Array (Entry (Fin n)) → Bool) (job : Job n) : Bool := + D.searchRight B check job.order job.restriction + +def meaning (D : RepresentationParentData n) (B : ℕ) + (check : Array (Entry (Fin n)) → Bool) : Control n → Bool + | .eval job pending => jobValue D B check job || pending.any (jobValue D B check) + | .ret b pending => b || pending.any (jobValue D B check) + +theorem step_meaning (D : RepresentationParentData n) (B : ℕ) + (check : Array (Entry (Fin n)) → Bool) (s : Control n) : + match step D B check s with + | .halt b => meaning D B check s = b + | .next t => meaning D B check s = meaning D B check t := by + cases s with + | eval job pending => + cases job with + | mk order P => + by_cases ho : ({ D with maskRestriction := P }.collect B).state.user.keys.overflow = true + · cases order with + | nil => simp [step, ho, meaning, jobValue, RepresentationParentData.searchRight] + | cons i rest => + simp only [step, ho, ↓reduceIte, meaning, List.any_cons, jobValue] + rw [RepresentationParentData.searchRight] + simp only [ho, ↓reduceIte] + by_cases hv : D.searchRight B check rest (P.force i false) = true + · simp only [hv, ↓reduceIte, Bool.true_or] + · have hf : D.searchRight B check rest (P.force i false) = false := Bool.eq_false_iff.mpr hv + simp [hf] + · have hf : ({ D with maskRestriction := P }.collect B).state.user.keys.overflow = false := + Bool.eq_false_iff.mpr ho + rw [step] + simp only [hf, Bool.false_eq_true, ↓reduceIte, meaning, jobValue] + rw [RepresentationParentData.searchRight.eq_def] + simp only [hf, Bool.false_eq_true, ↓reduceIte] + | ret b pending => + cases b <;> cases pending <;> simp [step, meaning] + +theorem watchdog_sound (D : RepresentationParentData n) (B : ℕ) + (check : Array (Entry (Fin n)) → Bool) (Q : Prop) + (hcheck : ∀ P, check ({ D with maskRestriction := P }.entries B) = true → Q) + (job : Job n) (budget : ℕ) + (hyes : Watchdog.accepted (Watchdog.run (step D B check) Control.cells + budget (.eval job [])) = true) : Q := by + apply Watchdog.sound (step D B check) Control.cells + (fun s => meaning D B check s = true → Q) Q ?_ ?_ budget (.eval job []) ?_ hyes + · intro s t hs ht h + have hm := step_meaning D B check s + rw [ht] at hm + exact hs (hm.trans h) + · intro s hs ht + have hm := step_meaning D B check s + rw [ht] at hm + exact hs hm + · intro h + have hj : jobValue D B check job = true := by simpa only [meaning, List.any_nil, Bool.or_false] using h + exact D.searchRight_sound B check Q hcheck job.order job.restriction hj + +theorem watchdog_stack_peak (D : RepresentationParentData n) (B : ℕ) + (check : Array (Entry (Fin n)) → Bool) (job : Job n) (budget : ℕ) : + (Watchdog.run (step D B check) Control.cells budget (.eval job [])).peak ≤ + (4 * n + 16) * (job.order.length + 2) := by + apply Watchdog.peak_le _ _ (Invariant job.order.length) _ + (invariant_next D B check job.order.length) (cells_le job.order.length) + simp [Invariant, GoodStack] + +end LowSpaceSubsetSum.PrefixMachine + +end OAI diff --git a/lean/OAI/Combinatorics/LowSpaceSubsetSum/Streams/PrefixMachineRun.lean b/lean/OAI/Combinatorics/LowSpaceSubsetSum/Streams/PrefixMachineRun.lean new file mode 100644 index 0000000000000000000000000000000000000000..707f2416660ff74313996e588f27b43609484f00 --- /dev/null +++ b/lean/OAI/Combinatorics/LowSpaceSubsetSum/Streams/PrefixMachineRun.lean @@ -0,0 +1,85 @@ +import OAI.Combinatorics.LowSpaceSubsetSum.Streams.PrefixMachine +import OAI.Combinatorics.LowSpaceSubsetSum.Streams.PrefixTaskCount +import OAI.Combinatorics.LowSpaceSubsetSum.Search.WatchdogRanking + +namespace OAI + +/-! # Termination of the explicit prefix stack + +The rank charges all possible task starts, including the sibling skipped +after an early YES. The stack machine terminates in at most three times +this task count plus two control actions. A collector action is a macro, +whose internal primitive operations still need their own watchdog. +-/ + +namespace LowSpaceSubsetSum.PrefixMachine + +variable {n : ℕ} + +def pendingWeight (D : RepresentationParentData n) (B : ℕ) (pending : List (Job n)) : ℕ := + (pending.map (fun job => 3 * D.taskStarts B job.order job.restriction + 2)).sum + +def rank (D : RepresentationParentData n) (B : ℕ) : Control n → ℕ + | .eval job pending => + 3 * D.taskStarts B job.order job.restriction + pendingWeight D B pending + 2 + | .ret _ pending => pendingWeight D B pending + 1 + +theorem rank_pos (D : RepresentationParentData n) (B : ℕ) (s : Control n) : + 1 ≤ rank D B s := by cases s <;> simp only [rank] <;> omega + +theorem rank_next (D : RepresentationParentData n) (B : ℕ) + (check : Array (Entry (Fin n)) → Bool) (s t : Control n) + (ht : step D B check s = .next t) : rank D B t < rank D B s := by + cases s with + | eval job pending => + cases job with + | mk order P => + by_cases ho : ({ D with maskRestriction := P }.collect B).state.user.keys.overflow = true + · cases order with + | nil => + simp only [step, ho, ↓reduceIte] at ht + cases ht + simp only [rank, RepresentationParentData.taskStarts] + omega + | cons i rest => + simp only [step, ho, ↓reduceIte] at ht + cases ht + simp only [rank, pendingWeight, List.map_cons, List.sum_cons, + RepresentationParentData.taskStarts, ho, ↓reduceIte] + omega + · have hf : ({ D with maskRestriction := P }.collect B).state.user.keys.overflow = false := + Bool.eq_false_iff.mpr ho + simp only [step, hf, Bool.false_eq_true, ↓reduceIte] at ht + cases ht + cases order <;> + simp only [rank, RepresentationParentData.taskStarts, hf, Bool.false_eq_true, ↓reduceIte] <;> + omega + | ret b pending => + cases b with + | true => simp [step] at ht + | false => + cases pending with + | nil => simp [step] at ht + | cons job pending => + simp only [step] at ht + cases ht + simp only [rank, pendingWeight, List.map_cons, List.sum_cons] + omega + +/-- The explicit stack performs exactly the original prefix search. -/ +theorem output_eq_searchRight (D : RepresentationParentData n) (B : ℕ) + (check : Array (Entry (Fin n)) → Bool) (job : Job n) : + (Watchdog.run (step D B check) Control.cells + (3 * D.taskStarts B job.order job.restriction + 2) (.eval job [])).output = + some (D.searchRight B check job.order job.restriction) := by + have h := Watchdog.ranked_complete (step D B check) Control.cells (rank D B) + (rank_pos D B) (rank_next D B check) (meaning D B check) (fun s => by + have hs := step_meaning D B check s + cases ht : step D B check s <;> simp only [ht] at hs ⊢ <;> exact hs) + (.eval job []) (3 * D.taskStarts B job.order job.restriction + 2) + (by simp [rank, pendingWeight]) + simpa only [meaning, List.any_nil, Bool.or_false, jobValue] using h + +end LowSpaceSubsetSum.PrefixMachine + +end OAI diff --git a/lean/OAI/Combinatorics/LowSpaceSubsetSum/Streams/PrefixTaskCount.lean b/lean/OAI/Combinatorics/LowSpaceSubsetSum/Streams/PrefixTaskCount.lean new file mode 100644 index 0000000000000000000000000000000000000000..8c5a94c064d67e73a1ccdf5dfd0db6bc1e810d25 --- /dev/null +++ b/lean/OAI/Combinatorics/LowSpaceSubsetSum/Streams/PrefixTaskCount.lean @@ -0,0 +1,180 @@ +import OAI.Combinatorics.LowSpaceSubsetSum.Counting.ParentRestrictionUniverse +import OAI.Combinatorics.LowSpaceSubsetSum.Streams.PrefixCheckList + +namespace OAI + +/-! # Task-start bounds for the executable prefix recursion -/ + +noncomputable section + +namespace LowSpaceSubsetSum.RepresentationParentData + +variable {n : ℕ} (D : RepresentationParentData n) + +def overflowCount (B : ℕ) : List (Fin n) → MaskRestriction n → ℕ + | order, P => + if ({ D with maskRestriction := P }.collect B).state.user.keys.overflow then + match order with + | [] => 1 + | i :: rest => 1 + overflowCount B rest (P.force i false) + overflowCount B rest (P.force i true) + else 0 + +def taskStarts (B : ℕ) : List (Fin n) → MaskRestriction n → ℕ + | [], _ => 1 + | i :: rest, P => + if ({ D with maskRestriction := P }.collect B).state.user.keys.overflow then + 1 + taskStarts B rest (P.force i false) + taskStarts B rest (P.force i true) + else 1 + +theorem taskStarts_le_overflow (B : ℕ) (order : List (Fin n)) (P : MaskRestriction n) : + D.taskStarts B order P ≤ 1 + 2 * D.overflowCount B order P := by + induction order generalizing P with + | nil => simp [taskStarts, overflowCount] + | cons i order ih => + simp only [taskStarts, overflowCount] + split + · change 1 + D.taskStarts B order (P.force i false) + + D.taskStarts B order (P.force i true) ≤ + 1 + 2 * (1 + D.overflowCount B order (P.force i false) + + D.overflowCount B order (P.force i true)) + have h0 := ih (P.force i false) + have h1 := ih (P.force i true) + omega + · omega + +theorem entryUniverse_force_card_add (P : MaskRestriction n) + (hd : ∀ i j, i ≠ j → Disjoint (D.leaves i).top (D.leaves j).top) + (i : Fin n) (hi : i ∈ RepresentationUniverse.topDomain D.leaves) : + ({ D with maskRestriction := P.force i false }).entryUniverse.card + + ({ D with maskRestriction := P.force i true }).entryUniverse.card = + ({ D with maskRestriction := P }).entryUniverse.card := by + classical + rw [D.entryUniverse_force P hd i hi false, D.entryUniverse_force P hd i hi true] + have h := Finset.card_filter_add_card_filter_not + (s := ({ D with maskRestriction := P }).entryUniverse) (p := fun e => i ∈ e.mask) + simpa only [decide_eq_false_iff_not, decide_eq_true_eq, add_comm] using h + +theorem overflowCount_capacity (B : ℕ) + (hd : ∀ i j, i ≠ j → Disjoint (D.leaves i).top (D.leaves j).top) + (hbounded : ∀ P, ∀ e ∈ ({ D with maskRestriction := P }).rawEntries, + WeightEncoding.BoundedWeight D.input e.value) + (order : List (Fin n)) (horder : ∀ i ∈ order, i ∈ RepresentationUniverse.topDomain D.leaves) + (P : MaskRestriction n) : + D.capacity * D.overflowCount B order P ≤ + (order.length + 1) * ({ D with maskRestriction := P }).entryUniverse.card := by + induction order generalizing P with + | nil => + simp only [overflowCount, List.length_nil] + split + · rename_i ho + have hc : D.capacity < ({ D with maskRestriction := P }).entryUniverse.card := + (({ D with maskRestriction := P }).collect_overflow_iff_card B (hbounded P)).mp ho + simp only [Nat.zero_add, one_mul, mul_one] + omega + · simp + | cons i order ih => + simp only [overflowCount, List.length_cons] + split + · rename_i ho + have hc : D.capacity < ({ D with maskRestriction := P }).entryUniverse.card := + (({ D with maskRestriction := P }).collect_overflow_iff_card B (hbounded P)).mp ho + have h0 := ih (fun j hj => horder j (by simp [hj])) (P.force i false) + have h1 := ih (fun j hj => horder j (by simp [hj])) (P.force i true) + have hs := D.entryUniverse_force_card_add P hd i (horder i (by simp)) + generalize ({ D with maskRestriction := P }).entryUniverse.card = U at hc hs ⊢ + generalize ({ D with maskRestriction := P.force i false }).entryUniverse.card = U0 at h0 hs + generalize ({ D with maskRestriction := P.force i true }).entryUniverse.card = U1 at h1 hs + nlinarith only [hc, h0, h1, hs] + · simp + +theorem taskStarts_capacity (B : ℕ) + (hd : ∀ i j, i ≠ j → Disjoint (D.leaves i).top (D.leaves j).top) + (hbounded : ∀ P, ∀ e ∈ ({ D with maskRestriction := P }).rawEntries, + WeightEncoding.BoundedWeight D.input e.value) + (order : List (Fin n)) (horder : ∀ i ∈ order, i ∈ RepresentationUniverse.topDomain D.leaves) + (P : MaskRestriction n) : + D.capacity * D.taskStarts B order P ≤ D.capacity + + 2 * (order.length + 1) * ({ D with maskRestriction := P }).entryUniverse.card := by + have ht := D.taskStarts_le_overflow B order P + have ho := D.overflowCount_capacity B hd hbounded order horder P + nlinarith + +theorem completedArrays_length_le (B : ℕ) (order : List (Fin n)) (P : MaskRestriction n) : + (D.completedArrays B order P).length ≤ D.taskStarts B order P := by + induction order generalizing P with + | nil => + simp only [completedArrays, taskStarts] + split <;> simp + | cons i order ih => + simp only [completedArrays, taskStarts] + split + · change (D.completedArrays B order (P.force i false) ++ + D.completedArrays B order (P.force i true)).length ≤ + 1 + D.taskStarts B order (P.force i false) + D.taskStarts B order (P.force i true) + simp only [List.length_append] + have h0 := ih (P.force i false) + have h1 := ih (P.force i true) + omega + · simp + +theorem completedArrays_size_sum_le (B : ℕ) + (hd : ∀ i j, i ≠ j → Disjoint (D.leaves i).top (D.leaves j).top) + (hbounded : ∀ P, ∀ e ∈ ({ D with maskRestriction := P }).rawEntries, + WeightEncoding.BoundedWeight D.input e.value) + (order : List (Fin n)) (horder : ∀ i ∈ order, i ∈ RepresentationUniverse.topDomain D.leaves) + (P : MaskRestriction n) : + ((D.completedArrays B order P).map Array.size).sum ≤ + ({ D with maskRestriction := P }).entryUniverse.card := by + induction order generalizing P with + | nil => + simp only [completedArrays] + split + · simp + · rename_i hc + have hclear := Bool.eq_false_iff.mpr hc + simpa only [List.map_singleton, List.sum_singleton, entries] using + (({ D with maskRestriction := P }).completed_size_eq_card B (hbounded P) hclear).le + | cons i order ih => + simp only [completedArrays] + split + · simp only [List.map_append, List.sum_append] + have h0 := ih (fun j hj => horder j (by simp [hj])) (P.force i false) + have h1 := ih (fun j hj => horder j (by simp [hj])) (P.force i true) + have hs := D.entryUniverse_force_card_add P hd i (horder i (by simp)) + omega + · rename_i hc + have hclear := Bool.eq_false_iff.mpr hc + simpa only [List.map_singleton, List.sum_singleton, entries] using + (({ D with maskRestriction := P }).completed_size_eq_card B (hbounded P) hclear).le + +private theorem input_sum (L : ℕ) (arrays : List (Array (Entry (Fin n)))) : + (arrays.map (fun a => L + a.size)).sum = (arrays.map Array.size).sum + L * arrays.length := by + induction arrays with + | nil => simp + | cons a arrays ih => + simp only [List.map_cons, List.sum_cons, List.length_cons, ih, Nat.mul_add, Nat.mul_one] + omega + +/-- Includes every reuse of the retained left array at a completed right +prefix; it is the actual check list's input-occurrence bound. -/ +theorem completed_check_inputs_le (B L : ℕ) (hL : L ≤ D.capacity) + (hd : ∀ i j, i ≠ j → Disjoint (D.leaves i).top (D.leaves j).top) + (hbounded : ∀ P, ∀ e ∈ ({ D with maskRestriction := P }).rawEntries, + WeightEncoding.BoundedWeight D.input e.value) + (order : List (Fin n)) (horder : ∀ i ∈ order, i ∈ RepresentationUniverse.topDomain D.leaves) + (P : MaskRestriction n) : + ((D.completedArrays B order P).map (fun a => L + a.size)).sum ≤ + L + (2 * order.length + 3) * ({ D with maskRestriction := P }).entryUniverse.card := by + rw [input_sum] + have hn := D.completedArrays_length_le B order P + have he := D.completedArrays_size_sum_le B hd hbounded order horder P + have ht := D.taskStarts_le_overflow B order P + have ho := D.overflowCount_capacity B hd hbounded order horder P + have hscale := Nat.mul_le_mul_left (D.overflowCount B order P) hL + nlinarith + +end LowSpaceSubsetSum.RepresentationParentData + +end + +end OAI diff --git a/lean/OAI/Combinatorics/LowSpaceSubsetSum/Streams/ReaderInitializationMap.lean b/lean/OAI/Combinatorics/LowSpaceSubsetSum/Streams/ReaderInitializationMap.lean new file mode 100644 index 0000000000000000000000000000000000000000..d9386c2eb58f8df6bf413255716940cd0e385f99 --- /dev/null +++ b/lean/OAI/Combinatorics/LowSpaceSubsetSum/Streams/ReaderInitializationMap.lean @@ -0,0 +1,171 @@ +import OAI.Combinatorics.LowSpaceSubsetSum.Streams.ReaderMap + +namespace OAI + +/-! # Semantic maps commute with the actual binary-search initialization -/ + +namespace LowSpaceSubsetSum +namespace BinarySlice + +variable {α β : Type*} + +private theorem search_lo_congr {m n : ℕ} (h : m = n) + (p : Fin m → Bool) (q : Fin n → Bool) + (hpq : ∀ i j, i.val = j.val → p i = q j) (k : ℕ) : + (BinaryPivot.search p k).lo = (BinaryPivot.search q k).lo := by + subst n + have he : p = q := funext (fun i => hpq i i rfl) + rw [he] + +theorem lower_map (f : α → β) (xs : Array α) (key : β → ℤ) (r : ℤ) (k : ℕ) : + lower (xs.map f) key r k = lower xs (fun x => key (f x)) r k := by + unfold lower + apply search_lo_congr Array.size_map + intro i j hij + simp only [Array.getElem_map, hij] + +theorem upper_map (f : α → β) (xs : Array α) (key : β → ℤ) (r : ℤ) (k : ℕ) : + upper (xs.map f) key r k = upper xs (fun x => key (f x)) r k := by + unfold upper + apply search_lo_congr Array.size_map + intro i j hij + simp only [Array.getElem_map, hij] + +theorem range_map (f : α → β) (xs : Array α) (key : β → ℤ) (r : ℤ) (k : ℕ) + (hs : Monotone (fun i : Fin xs.size => key (f xs[i.val]))) + (ht : Monotone (fun i : Fin (xs.map f).size => key (xs.map f)[i.val])) + (hk : xs.size < 2 ^ k) (hk' : (xs.map f).size < 2 ^ k) : + SliceCursor.mapRange f xs (range xs (fun x => key (f x)) r k hs hk) = + range (xs.map f) key r k ht hk' := by + simp only [SliceCursor.mapRange, range, lower_map, upper_map] + +end BinarySlice +namespace SliceModular + +variable {α β : Type*} + +theorem forward_map (f : α → β) (xs : Array α) (rr : SliceCursor.Range xs.size) + (key : β → ℤ) (P r : ℤ) (k : ℕ) : + SliceCursor.mapState f xs (forward xs rr (fun x => key (f x)) P r k) = + forward (xs.map f) (SliceCursor.mapRange f xs rr) key P r k := by + by_cases h : 0 < rr.length + · have : NeZero rr.length := ⟨by omega⟩ + rw [forward, dite_eq_left h, forward, dite_eq_left (show 0 < (SliceCursor.mapRange f xs rr).length from h)] + simp only [SliceCursor.mapState, SliceCursor.mapRange, + ModularCursor.forwardStart, SliceCursor.values, Array.getElem_map] + rfl + · rw [forward, dite_eq_right h, forward, dite_eq_right (show ¬ 0 < (SliceCursor.mapRange f xs rr).length from h)] + rfl + +theorem reverse_map (f : α → β) (xs : Array α) (rr : SliceCursor.Range xs.size) + (key : β → ℤ) (r : ℤ) (k : ℕ) : + SliceCursor.mapState f xs (reverse xs rr (fun x => key (f x)) r k) = + reverse (xs.map f) (SliceCursor.mapRange f xs rr) key r k := by + by_cases h : 0 < rr.length + · have : NeZero rr.length := ⟨by omega⟩ + rw [reverse, dite_eq_left h, reverse, dite_eq_left (show 0 < (SliceCursor.mapRange f xs rr).length from h)] + simp only [SliceCursor.mapState, SliceCursor.mapRange, + ModularCursor.reverseStart, SliceCursor.values, Array.getElem_map] + rfl + · rw [reverse, dite_eq_right h, reverse, dite_eq_right (show ¬ 0 < (SliceCursor.mapRange f xs rr).length from h)] + rfl + +end SliceModular +namespace FilteredRow + +variable {α β γ δ : Type*} + +theorem forward_map (f : α → γ) (g : β → δ) (xs : Array β) + (wl : γ → ℤ) (wr : δ → ℤ) (p P c : ℤ) (k : ℕ) + (hs : PrimarySorted xs (fun y => wr (g y)) p) + (ht : PrimarySorted (xs.map g) wr p) + (hk : xs.size < 2 ^ k) (hk' : (xs.map g).size < 2 ^ k) (x : α) : + PairCursor.mapState f g xs + (forward xs (fun y => wl (f y)) (fun y => wr (g y)) p P c k hs hk x) = + forward (xs.map g) wl wr p P c k ht hk' (f x) := by + simp only [forward, PairCursor.mapState, range] + congr 1 + rw [SliceModular.forward_map g xs _ (fun y => wr y % P) P (wl (f x) % P) k] + congr 1 + exact BinarySlice.range_map g xs (fun y => wr y % p) _ k hs ht hk hk' + +theorem reverse_map (f : α → γ) (g : β → δ) (xs : Array β) + (wl : γ → ℤ) (wr : δ → ℤ) (p P c v : ℤ) (k : ℕ) + (hs : PrimarySorted xs (fun y => wr (g y)) p) + (ht : PrimarySorted (xs.map g) wr p) + (hk : xs.size < 2 ^ k) (hk' : (xs.map g).size < 2 ^ k) (x : α) : + PairCursor.mapState f g xs + (reverse xs (fun y => wl (f y)) (fun y => wr (g y)) p P c v k hs hk x) = + reverse (xs.map g) wl wr p P c v k ht hk' (f x) := by + simp only [reverse, PairCursor.mapState, range] + congr 1 + rw [SliceModular.reverse_map g xs _ (fun y => wr y % P) ((v - wl (f x)) % P) k] + congr 1 + exact BinarySlice.range_map g xs (fun y => wr y % p) _ k hs ht hk hk' + +end FilteredRow +namespace FilteredStream + +variable {α β γ δ : Type*} + +theorem key_map (f : α → γ) (g : β → δ) (wl : γ → ℤ) (wr : δ → ℤ) + (P : ℤ) (mode : Mode) (x : α × β) : + key (fun y => wl (f y)) (fun y => wr (g y)) P mode x = + key wl wr P mode (Prod.map f g x) := by + cases mode <;> rfl + +theorem row_map (f : α → γ) (g : β → δ) (right : Array β) + (wl : γ → ℤ) (wr : δ → ℤ) (p P c : ℤ) + (hs : FilteredRow.PrimarySorted right (fun y => wr (g y)) p) + (ht : FilteredRow.PrimarySorted (right.map g) wr p) (mode : Mode) (x : α) : + PairCursor.mapState f g right + (row right (fun y => wl (f y)) (fun y => wr (g y)) p P c hs mode x) = + row (right.map g) wl wr p P c ht mode (f x) := by + cases mode with + | direct => + simpa only [row, Array.size_map] using + FilteredRow.forward_map f g right wl wr p P c (steps right.size) hs ht + (steps_sufficient right.size) (by simpa using steps_sufficient right.size) x + | complementary v => + simpa only [row, Array.size_map] using + FilteredRow.reverse_map f g right wl wr p P c v (steps right.size) hs ht + (steps_sufficient right.size) (by simpa using steps_sufficient right.size) x + +theorem rowArray_map (f : α → γ) (g : β → δ) (left : Array α) (right : Array β) + (wl : γ → ℤ) (wr : δ → ℤ) (p P c : ℤ) + (hs : FilteredRow.PrimarySorted right (fun y => wr (g y)) p) + (ht : FilteredRow.PrimarySorted (right.map g) wr p) (mode : Mode) : + (rowArray left right (fun y => wl (f y)) (fun y => wr (g y)) p P c hs mode).map + (PairCursor.mapState f g right) = + rowArray (left.map f) (right.map g) wl wr p P c ht mode := by + apply Array.toList_inj.mp + simp only [rowArray, Array.toList_map, List.map_map] + congr 1 + funext x + exact row_map f g right wl wr p P c hs ht mode x + +theorem initial_tree_map (f : α → γ) (g : β → δ) (left : Array α) (right : Array β) + (wl : γ → ℤ) (wr : δ → ℤ) (p P c : ℤ) + (hs : FilteredRow.PrimarySorted right (fun y => wr (g y)) p) + (ht : FilteredRow.PrimarySorted (right.map g) wr p) (mode : Mode) (d : ℕ) : + Tournament.map (RowMerge.mapFront (Prod.map f g) (mapCursor f g right)) + (RowMerge.start (key (fun y => wl (f y)) (fun y => wr (g y)) P mode) + (read right) + (PaddedRows.rows (rowArray left right (fun y => wl (f y)) + (fun y => wr (g y)) p P c hs mode) d)) = + RowMerge.start (key wl wr P mode) (read (right.map g)) + (PaddedRows.rows (rowArray (left.map f) (right.map g) wl wr p P c ht mode) d) := by + have he : key (fun y => wl (f y)) (fun y => wr (g y)) P mode = + (fun x => key wl wr P mode (Prod.map f g x)) := by cases mode <;> rfl + rw [he, RowMerge.start_map (Prod.map f g) (mapCursor f g right) + (key wl wr P mode) (read right) (read (right.map g)) (read_map f g right)] + congr 1 + funext path + change (PaddedRows.rows _ d path).map (PairCursor.mapState f g right) = _ + rw [PaddedRows.rows_map, rowArray_map f g left right wl wr p P c hs ht mode] + +end FilteredStream + +end LowSpaceSubsetSum + +end OAI diff --git a/lean/OAI/Combinatorics/LowSpaceSubsetSum/Streams/ReaderMap.lean b/lean/OAI/Combinatorics/LowSpaceSubsetSum/Streams/ReaderMap.lean new file mode 100644 index 0000000000000000000000000000000000000000..4c1fa6d6ccaf9db12d451f0fc923c4f79ce73f1e --- /dev/null +++ b/lean/OAI/Combinatorics/LowSpaceSubsetSum/Streams/ReaderMap.lean @@ -0,0 +1,363 @@ +import OAI.Combinatorics.LowSpaceSubsetSum.Representation.RepresentationStoredRecords + +namespace OAI + +/-! # Semantic maps for the mutable reader structures + +Mapping records preserves the tournament paths and all cursor coordinates. +Immutable backing arrays are mapped once; they are not copied by a read. +-/ + +namespace LowSpaceSubsetSum + +namespace Tournament + +variable {α β : Type*} + +def map (f : α → β) : {d : ℕ} → Tree α d → Tree β d + | 0, .leaf v => .leaf (v.map f) + | _d + 1, .node w l r => .node (w.map f) (map f l) (map f r) + +@[simp] theorem winner_map (f : α → β) {d : ℕ} (t : Tree α d) : + winner (map f t) = (winner t).map f := by cases t <;> rfl + +@[simp] theorem nodes_map (f : α → β) {d : ℕ} (t : Tree α d) : + nodes (map f t) = nodes t := by + induction t with + | leaf _ => rfl + | node _ _ _ ihl ihr => simp only [map, nodes, ihl, ihr] + +theorem pick_map (f : α → β) (key : β → ℤ) (a b : Option α) : + (pick (fun x => key (f x)) a b).map f = pick key (a.map f) (b.map f) := by + cases a <;> cases b <;> simp only [pick, Option.map_none, Option.map_some] + split <;> rfl + +theorem node_map (f : α → β) (key : β → ℤ) {d : ℕ} (l r : Tree α d) : + map f (node (fun x => key (f x)) l r) = node key (map f l) (map f r) := by + simp only [node, map, pick_map, winner_map] + +theorem valid_map (f : α → β) (key : β → ℤ) {d : ℕ} (t : Tree α d) + (h : Valid (fun x => key (f x)) t) : Valid key (map f t) := by + induction t with + | leaf _ => trivial + | node w l r ihl ihr => + refine ⟨?_, ihl h.2.1, ihr h.2.2⟩ + rw [h.1, pick_map, winner_map, winner_map] + +theorem lookup_map (f : α → β) {d : ℕ} (t : Tree α d) (p : Fin d → Bool) : + lookup (map f t) p = (lookup t p).map f := by + induction t with + | leaf _ => rfl + | node _ _ _ ihl ihr => + simp only [map, lookup] + split <;> simp only [ihl, ihr] + +theorem replace_map (f : α → β) (key : β → ℤ) {d : ℕ} (t : Tree α d) + (p : Fin d → Bool) (v : Option α) : + map f (replace (fun x => key (f x)) t p v) = replace key (map f t) p (v.map f) := by + induction t with + | leaf _ => rfl + | node _ _ _ ihl ihr => + simp only [map, replace] + split <;> simp only [node_map, ihl, ihr] + +theorem build_map (f : α → β) (key : β → ℤ) (d : ℕ) + (front : (Fin d → Bool) → Option α) : + map f (build (fun x => key (f x)) d front) = + build key d (fun p => (front p).map f) := by + induction d with + | zero => rfl + | succ d ih => simp only [build, node_map, ih] + +end Tournament + +namespace CyclicCursor + +variable {α β : Type*} {n : ℕ} [NeZero n] + +theorem trace_map (f : α → β) (a : Fin n → α) (k : ℕ) (c : State n) : + (trace a k c).map f = trace (fun i => f (a i)) k c := by + induction k generalizing c with + | zero => rfl + | succ k ih => + simp only [trace] + split <;> simp only [List.map_nil, List.map_cons, ih] + +end CyclicCursor + +namespace SliceCursor + +variable {α β : Type*} + +def mapRange (f : α → β) (xs : Array α) (r : Range xs.size) : Range (xs.map f).size := + ⟨r.lo, r.length, by simpa using r.bounded⟩ + +def mapState (f : α → β) (xs : Array α) (s : State xs.size) : State (xs.map f).size := + ⟨mapRange f xs s.range, s.cursor⟩ + +theorem values_map (f : α → β) (xs : Array α) (r : Range xs.size) (i : Fin r.length) : + values (xs.map f) (mapRange f xs r) i = f (values xs r i) := by + simp only [values, mapRange, Array.getElem_map] + +theorem next_map (f : α → β) (xs : Array α) (s : State xs.size) : + (next xs s).map (fun z => (f z.1, mapState f xs z.2)) = + next (xs.map f) (mapState f xs s) := by + cases h : s.cursor with + | none => simp only [next, mapState, h, Option.map_none] + | some c => + simp only [next, mapState, h] + split <;> simp only [Option.map_none, Option.map_some, values_map] + rfl + +theorem output_map (f : α → β) (xs : Array α) (s : State xs.size) : + (output xs s).map f = output (xs.map f) (mapState f xs s) := by + cases h : s.cursor with + | none => simp only [output, mapState, h, List.map_nil] + | some c => + have : NeZero s.range.length := ⟨by have := c.position.isLt; omega⟩ + simp only [output, mapState, h, CyclicCursor.trace_map] + congr 1 + funext i + exact (values_map f xs s.range i).symm + +end SliceCursor + +namespace PairCursor + +variable {α β γ δ : Type*} + +def mapState (f : α → γ) (g : β → δ) (xs : Array β) (s : State α xs.size) : + State γ (xs.map g).size := ⟨f s.left, SliceCursor.mapState g xs s.cursor⟩ + +theorem next_map (f : α → γ) (g : β → δ) (xs : Array β) (s : State α xs.size) : + (next xs s).map (fun z => (Prod.map f g z.1, mapState f g xs z.2)) = + next (xs.map g) (mapState f g xs s) := by + have h := SliceCursor.next_map g xs s.cursor + simp only [next, mapState] + rw [← h] + simp only [Option.map_map] + rfl + +theorem output_map (f : α → γ) (g : β → δ) (xs : Array β) (s : State α xs.size) : + (output xs s).map (Prod.map f g) = output (xs.map g) (mapState f g xs s) := by + change ((SliceCursor.output xs s.cursor).map (fun y => (s.left, y))).map (Prod.map f g) = + (SliceCursor.output (xs.map g) (SliceCursor.mapState g xs s.cursor)).map + (fun y => (f s.left, y)) + rw [← SliceCursor.output_map g xs s.cursor] + simp only [List.map_map] + rfl + +end PairCursor + +namespace FilteredStream + +variable {α β γ δ : Type*} + +def mapCursor (f : α → γ) (g : β → δ) (xs : Array β) : + Cursor (α := α) xs → Cursor (α := γ) (xs.map g) := + Option.map (PairCursor.mapState f g xs) + +theorem read_map (f : α → γ) (g : β → δ) (xs : Array β) (s : Cursor (α := α) xs) : + (read xs s).map (fun z => (Prod.map f g z.1, mapCursor f g xs z.2)) = + read (xs.map g) (mapCursor f g xs s) := by + cases s with + | none => rfl + | some s => + simp only [read, PaddedRows.next, mapCursor, Option.map_some] + rw [← PairCursor.next_map f g xs s] + simp only [Option.map_map] + rfl + +theorem view_map (f : α → γ) (g : β → δ) (xs : Array β) (s : Cursor (α := α) xs) : + (view xs s).map (Prod.map f g) = view (xs.map g) (mapCursor f g xs s) := by + cases s with + | none => rfl + | some s => exact PairCursor.output_map f g xs s + +end FilteredStream + +namespace PaddedRows + +variable {α β : Type*} + +theorem rows_map (f : α → β) (xs : Array α) (d : ℕ) (p : RowMerge.Path d) : + (rows xs d p).map f = rows (xs.map f) d p := by + simp only [rows, Array.size_map] + split <;> simp only [Option.map_some, Option.map_none, Array.getElem_map] + +end PaddedRows + +namespace RowMerge + +variable {α β σ τ : Type*} {d : ℕ} + +def mapFront (f : α → β) (g : σ → τ) (x : Front d α σ) : Front d β τ := + ⟨x.row, f x.value, g x.after⟩ + +theorem front_map (f : α → β) (g : σ → τ) + (readA : σ → Option (α × σ)) (readB : τ → Option (β × τ)) + (hr : ∀ s, (readA s).map (fun z => (f z.1, g z.2)) = readB (g s)) + (p : Path d) (s : σ) : + (front readA p s).map (mapFront f g) = front readB p (g s) := by + unfold front + rw [← hr] + simp only [Option.map_map] + rfl + +theorem start_map (f : α → β) (g : σ → τ) (key : β → ℤ) + (readA : σ → Option (α × σ)) (readB : τ → Option (β × τ)) + (hr : ∀ s, (readA s).map (fun z => (f z.1, g z.2)) = readB (g s)) + (rows : Path d → σ) : + Tournament.map (mapFront f g) (start (fun x => key (f x)) readA rows) = + start key readB (fun p => g (rows p)) := by + unfold start + change Tournament.map (mapFront f g) + (Tournament.build (fun x => (fun y : Front d β τ => key y.value) (mapFront f g x)) + d (fun p => front readA p (rows p))) = _ + rw [Tournament.build_map (mapFront f g) (fun y : Front d β τ => key y.value) d + (fun p => front readA p (rows p))] + congr 1 + funext p + exact front_map f g readA readB hr p (rows p) + +theorem advance_map (f : α → β) (g : σ → τ) (key : β → ℤ) + (readA : σ → Option (α × σ)) (readB : τ → Option (β × τ)) + (hr : ∀ s, (readA s).map (fun z => (f z.1, g z.2)) = readB (g s)) + (t : Tournament.Tree (Front d α σ) d) : + (advance (fun x => key (f x)) readA t).map + (fun z => (f z.1, Tournament.map (mapFront f g) z.2)) = + advance key readB (Tournament.map (mapFront f g) t) := by + simp only [advance, Tournament.winner_map] + cases h : Tournament.winner t with + | none => rfl + | some x => + simp only [Option.map_some] + congr 1 + apply Prod.ext + · rfl + change Tournament.map (mapFront f g) + (Tournament.replace (fun y => key (mapFront f g y).value) t x.row + (front readA x.row x.after)) = + Tournament.replace (fun y => key y.value) (Tournament.map (mapFront f g) t) + x.row (front readB x.row (g x.after)) + rw [Tournament.replace_map (mapFront f g) (fun y : Front d β τ => key y.value) + t x.row (front readA x.row x.after), front_map f g readA readB hr] + +theorem aligned_map (f : α → β) (g : σ → τ) + (t : Tournament.Tree (Front d α σ) d) (h : Aligned t) : + Aligned (Tournament.map (mapFront f g) t) := by + intro p y hy + rw [Tournament.lookup_map] at hy + obtain ⟨x, hx, he⟩ := Option.map_eq_some_iff.mp hy + rw [← he] + exact h p x hx + +theorem remaining_map (f : α → β) (g : σ → τ) + (viewA : σ → List α) (viewB : τ → List β) + (hv : ∀ s, (viewA s).map f = viewB (g s)) + (t : Tournament.Tree (Front d α σ) d) (p : Path d) : + remaining viewB (Tournament.map (mapFront f g) t) p = (remaining viewA t p).map f := by + unfold remaining + rw [Tournament.lookup_map] + cases ht : Tournament.lookup t p with + | none => rfl + | some x => simp only [Option.map_some, mapFront, List.map_cons, hv] + +theorem rowsSorted_map (f : α → β) (g : σ → τ) (key : β → ℤ) + (viewA : σ → List α) (viewB : τ → List β) + (hv : ∀ s, (viewA s).map f = viewB (g s)) + (t : Tournament.Tree (Front d α σ) d) (h : RowsSorted (fun x => key (f x)) viewA t) : + RowsSorted key viewB (Tournament.map (mapFront f g) t) := by + intro p + rw [remaining_map f g viewA viewB hv, List.pairwise_map] + exact h p + +theorem potential_map (f : α → β) (g : σ → τ) + (viewA : σ → List α) (viewB : τ → List β) + (hv : ∀ s, (viewA s).map f = viewB (g s)) + (t : Tournament.Tree (Front d α σ) d) : + potential viewB (Tournament.map (mapFront f g) t) = potential viewA t := by + unfold potential + apply Finset.sum_congr rfl + intro p _ + rw [remaining_map f g viewA viewB hv, List.length_map] + +theorem trace_map (f : α → β) (g : σ → τ) (key : β → ℤ) + (readA : σ → Option (α × σ)) (readB : τ → Option (β × τ)) + (hr : ∀ s, (readA s).map (fun z => (f z.1, g z.2)) = readB (g s)) + (k : ℕ) (t : Tournament.Tree (Front d α σ) d) : + (trace (fun x => key (f x)) readA k t).map f = + trace key readB k (Tournament.map (mapFront f g) t) := by + induction k generalizing t with + | zero => rfl + | succ k ih => + have h := advance_map f g key readA readB hr t + cases ha : advance (fun x => key (f x)) readA t with + | none => + have hb : advance key readB (Tournament.map (mapFront f g) t) = none := by + simpa only [ha, Option.map_none] using h.symm + simp only [trace, ha, hb, List.map_nil] + | some z => + obtain ⟨a, t'⟩ := z + have hb : advance key readB (Tournament.map (mapFront f g) t) = + some (f a, Tournament.map (mapFront f g) t') := by + simpa only [ha, Option.map_some] using h.symm + simp only [trace, ha, hb, List.map_cons, ih] + +end RowMerge + +namespace MergedReader + +variable {α β σ τ : Type*} {d : ℕ} + +def mapState (f : α → β) (g : σ → τ) (key : β → ℤ) + (viewA : σ → List α) (viewB : τ → List β) + (hv : ∀ s, (viewA s).map f = viewB (g s)) + (s : State (fun x => key (f x)) viewA d) : State key viewB d := + ⟨Tournament.map (RowMerge.mapFront f g) s.tree, + Tournament.valid_map (RowMerge.mapFront f g) (fun x => key x.value) s.tree s.valid, + RowMerge.aligned_map f g s.tree s.aligned, + RowMerge.rowsSorted_map f g key viewA viewB hv s.tree s.sorted⟩ + +theorem next_map (f : α → β) (g : σ → τ) (key : β → ℤ) + (readA : σ → Option (α × σ)) (readB : τ → Option (β × τ)) + (hr : ∀ s, (readA s).map (fun z => (f z.1, g z.2)) = readB (g s)) + (viewA : σ → List α) (viewB : τ → List β) + (hv : ∀ s, (viewA s).map f = viewB (g s)) + (ha : RowMerge.IsReader readA viewA) (hb : RowMerge.IsReader readB viewB) + (s : State (fun x => key (f x)) viewA d) : + (next (fun x => key (f x)) readA viewA ha s).map + (fun z => (f z.1, mapState f g key viewA viewB hv z.2)) = + next key readB viewB hb (mapState f g key viewA viewB hv s) := by + have h := RowMerge.advance_map f g key readA readB hr s.tree + cases he : RowMerge.advance (fun x => key (f x)) readA s.tree with + | none => + have h' : RowMerge.advance key readB (Tournament.map (RowMerge.mapFront f g) s.tree) = none := by + simpa only [he, Option.map_none] using h.symm + rw [next_none _ _ _ _ _ he, next_none _ _ _ _ _ h'] + rfl + | some z => + obtain ⟨a, t⟩ := z + have h' : RowMerge.advance key readB (Tournament.map (RowMerge.mapFront f g) s.tree) = + some (f a, Tournament.map (RowMerge.mapFront f g) t) := by + simpa only [he, Option.map_some] using h.symm + rw [next_some _ _ _ _ _ he, next_some _ _ _ _ _ h'] + rfl + +theorem output_map (f : α → β) (g : σ → τ) (key : β → ℤ) + (readA : σ → Option (α × σ)) (readB : τ → Option (β × τ)) + (hr : ∀ s, (readA s).map (fun z => (f z.1, g z.2)) = readB (g s)) + (viewA : σ → List α) (viewB : τ → List β) + (hv : ∀ s, (viewA s).map f = viewB (g s)) + (s : State (fun x => key (f x)) viewA d) : + (output (fun x => key (f x)) readA viewA s).map f = + output key readB viewB (mapState f g key viewA viewB hv s) := by + unfold output + rw [show RowMerge.potential viewB (mapState f g key viewA viewB hv s).tree = + RowMerge.potential viewA s.tree from RowMerge.potential_map f g viewA viewB hv s.tree] + exact RowMerge.trace_map f g key readA readB hr _ _ + +end MergedReader +end LowSpaceSubsetSum + +end OAI diff --git a/lean/OAI/Combinatorics/LowSpaceSubsetSum/Streams/RecordedDictionary.lean b/lean/OAI/Combinatorics/LowSpaceSubsetSum/Streams/RecordedDictionary.lean new file mode 100644 index 0000000000000000000000000000000000000000..62a5402323a2d43d6116c2df7c1664901f4ca9ee --- /dev/null +++ b/lean/OAI/Combinatorics/LowSpaceSubsetSum/Streams/RecordedDictionary.lean @@ -0,0 +1,166 @@ +import OAI.Combinatorics.LowSpaceSubsetSum.Streams.DictionaryPrefixes +import OAI.Combinatorics.LowSpaceSubsetSum.Streams.DictionaryProvenance +import OAI.Combinatorics.LowSpaceSubsetSum.Search.StoppedStreamJoin + +namespace OAI + +/-! # Bounded dictionaries with an actual array of retained records -/ + +namespace LowSpaceSubsetSum.RecordedDictionary + +universe u +variable {α : Type u} + +structure State (α : Type u) where + keys : BinaryTrie.BuildResult + records : Array α + +def empty : State α := ⟨⟨.empty, false, 0⟩, #[]⟩ + +/-- The first rejected record is retained, as is its newly allocated trie key. +Further callbacks freeze both structures. -/ +def feed (C : ℕ) (encode : α → List Bool) (x : α) (r : State α) : State α := + ⟨BinaryTrie.feed C (encode x) r.keys, + if r.keys.overflow || BinaryTrie.contains r.keys.tree (encode x) + then r.records else r.records.push x⟩ + +@[simp] theorem feed_keys (C : ℕ) (encode : α → List Bool) (x : α) (r : State α) : + (feed C encode x r).keys = BinaryTrie.feed C (encode x) r.keys := rfl + +structure Invariant (C width : ℕ) (encode : α → List Bool) (r : State α) : Prop where + safe : BinaryTrie.Safe C width r.keys + keys_eq : BinaryTrie.keySet r.keys.tree = (r.records.toList.map encode).toFinset + size_eq : r.records.size = BinaryTrie.entries r.keys.tree + +theorem empty_invariant (C width : ℕ) (encode : α → List Bool) : + Invariant C width encode empty := by + exact ⟨BinaryTrie.empty_safe C width, rfl, rfl⟩ + +theorem feed_invariant {C width : ℕ} {encode : α → List Bool} {r : State α} + (hr : Invariant C width encode r) (x : α) (hx : (encode x).length = width) : + Invariant C width encode (feed C encode x r) := by + refine ⟨BinaryTrie.feed_safe hr.safe (encode x) hx, ?_, ?_⟩ + · by_cases ho : r.keys.overflow = true + · simpa only [feed, ho, Bool.true_or, ↓reduceIte, + BinaryTrie.feed_frozen C (encode x) r.keys ho] using hr.keys_eq + have hoc : r.keys.overflow = false := Bool.eq_false_iff.mpr ho + by_cases hd : BinaryTrie.contains r.keys.tree (encode x) = true + · simpa only [feed, hoc, hd, Bool.false_or, ↓reduceIte, + BinaryTrie.feed, Bool.false_eq_true, BinaryTrie.tick] using hr.keys_eq + have hdc : BinaryTrie.contains r.keys.tree (encode x) = false := Bool.eq_false_iff.mpr hd + simp only [feed, hoc, hdc, Bool.false_or, Bool.false_eq_true, ↓reduceIte, + BinaryTrie.feed, Array.toList_push, List.map_append, List.map_cons, + List.map_nil, List.toFinset_append, List.toFinset_cons, List.toFinset_nil] + rw [BinaryTrie.keySet_insert hr.safe.hasWidth hx, hr.keys_eq] + ext q + simp + · by_cases ho : r.keys.overflow = true + · simpa only [feed, ho, Bool.true_or, ↓reduceIte, + BinaryTrie.feed_frozen C (encode x) r.keys ho] using hr.size_eq + have hoc : r.keys.overflow = false := Bool.eq_false_iff.mpr ho + by_cases hd : BinaryTrie.contains r.keys.tree (encode x) = true + · simpa only [feed, hoc, hd, Bool.false_or, ↓reduceIte, + BinaryTrie.feed, Bool.false_eq_true, BinaryTrie.tick] using hr.size_eq + have hdc : BinaryTrie.contains r.keys.tree (encode x) = false := Bool.eq_false_iff.mpr hd + simp only [feed, hoc, hdc, Bool.false_or, Bool.false_eq_true, ↓reduceIte, + BinaryTrie.feed, Array.size_push] + rw [BinaryTrie.entries_insert hr.safe.hasWidth hx, hdc] + simpa using hr.size_eq + +/-- Every stopped state stores at most the capacity plus the rejected record. -/ +theorem storage {C width : ℕ} {encode : α → List Bool} {r : State α} + (hr : Invariant C width encode r) : + r.records.size ≤ C + 1 ∧ BinaryTrie.nodes r.keys.tree ≤ (width + 1) * (C + 1) := by + exact ⟨hr.size_eq.trans_le hr.safe.bound, + (BinaryTrie.nodes_le_width_mul_entries hr.safe.hasWidth hr.safe.compact).trans + (Nat.mul_le_mul_left _ hr.safe.bound)⟩ + +theorem contains_iff {C width : ℕ} {encode : α → List Bool} {r : State α} + (hr : Invariant C width encode r) (q : List Bool) : + BinaryTrie.contains r.keys.tree q = true ↔ ∃ x ∈ r.records.toList, encode x = q := by + rw [← BinaryTrie.mem_keySet, hr.keys_eq, List.mem_toFinset, List.mem_map] + +theorem feed_provenance (C : ℕ) (encode : α → List Bool) (x : α) (r : State α) + (P : α → Prop) (hr : ∀ y ∈ r.records.toList, P y) (hx : P x) : + ∀ y ∈ (feed C encode x r).records.toList, P y := by + intro y hy + simp only [feed] at hy + split at hy + · exact hr y hy + · simp only [Array.toList_push, List.mem_append, List.mem_singleton] at hy + rcases hy with hy | rfl + · exact hr y hy + · exact hx + +theorem fold_invariant {C width : ℕ} {encode : α → List Bool} {r : State α} + (hr : Invariant C width encode r) (xs : List α) + (hw : ∀ x ∈ xs, (encode x).length = width) : + Invariant C width encode (xs.foldl (fun r x => feed C encode x r) r) := by + induction xs generalizing r with + | nil => exact hr + | cons x xs ih => + exact ih (feed_invariant hr x (hw x (by simp))) (fun y hy => hw y (by simp [hy])) + +theorem fold_keys (C : ℕ) (encode : α → List Bool) (xs : List α) (r : State α) : + (xs.foldl (fun r x => feed C encode x r) r).keys = + (xs.map encode).foldl (fun r key => BinaryTrie.feed C key r) r.keys := by + induction xs generalizing r with + | nil => rfl + | cons x xs ih => exact ih (feed C encode x r) + +/-- A cardinality bound concerns distinct keys, rather than repeated callbacks. +When it holds, every supplied record has its key retained in the array. -/ +theorem fold_fits {C width : ℕ} (encode : α → List Bool) (xs : List α) + (U : Finset (List Bool)) (hwidth : ∀ q ∈ U, q.length = width) + (hcap : U.card ≤ C) (hkeys : ∀ x ∈ xs, encode x ∈ U) : + let r := xs.foldl (fun r x => feed C encode x r) empty + r.keys.overflow = false ∧ + ∀ q, (∃ x ∈ r.records.toList, encode x = q) ↔ ∃ x ∈ xs, encode x = q := by + have hw : ∀ x ∈ xs, (encode x).length = width := fun x hx => hwidth _ (hkeys x hx) + have hi := fold_invariant (empty_invariant C width encode) xs hw + have hf := BinaryTrie.fold_fits (r := ⟨.empty, false, 0⟩) rfl + (width := width) (by trivial) hwidth (by simp [BinaryTrie.keySet]) hcap + (xs.map encode) (by + intro q hq + obtain ⟨x, hx, rfl⟩ := List.mem_map.mp hq + exact hkeys x hx) + dsimp only + refine ⟨?_, ?_⟩ + · rw [fold_keys] + exact hf.1 + · intro q + rw [← contains_iff hi q, ← BinaryTrie.mem_keySet, fold_keys] + dsimp only [empty] + rw [hf.2.1] + simp only [BinaryTrie.keySet, Finset.empty_union, List.mem_toFinset, List.mem_map] + +/-- The option-valued emitter applies local overlap and prefix checks before +an entry is retained. A rejected tuple consumes no dictionary space. -/ +def callback {β γ : Type*} (C : ℕ) (encode : α → List Bool) + (emit : β → γ → Option α) (x : β) (y : γ) (r : State α) : State α × Bool := + (match emit x y with | none => r | some z => feed C encode z r, false) + +theorem callback_invariant {β γ : Type*} {C width : ℕ} (encode : α → List Bool) + (hw : ∀ z, (encode z).length = width) (emit : β → γ → Option α) + (x : β) (y : γ) (r : State α) (hr : Invariant C width encode r) : + Invariant C width encode (callback C encode emit x y r).1 := by + cases h : emit x y with + | none => simpa only [callback, h] using hr + | some z => simpa only [callback, h] using feed_invariant hr z (hw z) + +/-- Array and trie storage are bounded even at incomplete join prefixes. -/ +theorem stopped_invariant {β γ σ₁ σ₂ : Type*} {C width : ℕ} + (read₁ : σ₁ → Option (β × σ₁)) (key₁ : β → ℤ) + (read₂ : σ₂ → Option (γ × σ₂)) (key₂ : γ → ℤ) + (encode : α → List Bool) (hw : ∀ z, (encode z).length = width) + (emit : β → γ → Option α) (B fuel₁ fuel₂ controlFuel : ℕ) (s₁ : σ₁) (s₂ : σ₂) : + Invariant C width encode (StreamJoin.stopped read₁ key₁ read₂ key₂ + (callback C encode emit) B fuel₁ fuel₂ controlFuel s₁ s₂ empty).state.user := by + rw [StreamJoin.stopped_eq] + exact DictionaryPrefixes.run_preserves read₁ key₁ read₂ key₂ (callback C encode emit) + (Invariant C width encode) (callback_invariant encode hw emit) B fuel₁ fuel₂ controlFuel + (StreamJoin.start s₁ s₂ empty) (empty_invariant C width encode) + +end LowSpaceSubsetSum.RecordedDictionary + +end OAI diff --git a/lean/OAI/Combinatorics/LowSpaceSubsetSum/Streams/RecordedJoin.lean b/lean/OAI/Combinatorics/LowSpaceSubsetSum/Streams/RecordedJoin.lean new file mode 100644 index 0000000000000000000000000000000000000000..9707cc7d4cf7f5bdf1afe82e2a7b235178fec614 --- /dev/null +++ b/lean/OAI/Combinatorics/LowSpaceSubsetSum/Streams/RecordedJoin.lean @@ -0,0 +1,120 @@ +import OAI.Combinatorics.LowSpaceSubsetSum.Streams.RecordedDictionary + +namespace OAI + +/-! # Exact retained-record semantics for a filtered stream join -/ + +namespace LowSpaceSubsetSum.RecordedDictionary + +variable {α β γ : Type*} + +/-- A proof view; the runtime never constructs this Cartesian list. -/ +def matchingRecords (key₁ : β → ℤ) (key₂ : γ → ℤ) (emit : β → γ → Option α) + (xs : List β) (ys : List γ) : List α := + xs.flatMap (fun x => (ys.filter (fun y => decide (key₁ x = key₂ y))).filterMap (emit x)) + +theorem mem_matchingRecords (key₁ : β → ℤ) (key₂ : γ → ℤ) (emit : β → γ → Option α) + (xs : List β) (ys : List γ) (z : α) : + z ∈ matchingRecords key₁ key₂ emit xs ys ↔ + ∃ x ∈ xs, ∃ y ∈ ys, key₁ x = key₂ y ∧ emit x y = some z := by + simp only [matchingRecords, List.mem_flatMap, List.mem_filterMap, List.mem_filter, + decide_eq_true_eq] + constructor + · rintro ⟨x, hx, y, ⟨hy, he⟩, hz⟩ + exact ⟨x, hx, y, hy, he, hz⟩ + · rintro ⟨x, hx, y, hy, he, hz⟩ + exact ⟨x, hx, y, ⟨hy, he⟩, hz⟩ + +theorem matchFold_eq_records (C : ℕ) (encode : α → List Bool) + (key₁ : β → ℤ) (key₂ : γ → ℤ) (emit : β → γ → Option α) + (xs : List β) (ys : List γ) (r : State α) : + MatchFold.run key₁ key₂ (callback C encode emit) xs ys r = + (matchingRecords key₁ key₂ emit xs ys).foldl (fun r z => feed C encode z r) r := by + induction xs generalizing r with + | nil => rfl + | cons x xs ih => + simp only [MatchFold.run, matchingRecords, List.flatMap_cons, List.foldl_append, + List.foldl_filterMap, callback, ih] + congr 2 + funext a y + cases emit x y <;> rfl + +theorem fold_provenance (C : ℕ) (encode : α → List Bool) (xs : List α) (r : State α) + (P : α → Prop) (hr : ∀ z ∈ r.records.toList, P z) (hx : ∀ z ∈ xs, P z) : + ∀ z ∈ (xs.foldl (fun r z => feed C encode z r) r).records.toList, P z := by + induction xs generalizing r with + | nil => exact hr + | cons x xs ih => + exact ih (feed C encode x r) (feed_provenance C encode x r P hr (hx x (by simp))) + (fun y hy => hx y (by simp [hy])) + +theorem matchFold_fits {C width : ℕ} (encode : α → List Bool) + (key₁ : β → ℤ) (key₂ : γ → ℤ) (emit : β → γ → Option α) + (xs : List β) (ys : List γ) (U : Finset (List Bool)) + (hwidth : ∀ q ∈ U, q.length = width) (hcap : U.card ≤ C) + (hkeys : ∀ x ∈ xs, ∀ y ∈ ys, key₁ x = key₂ y → + ∀ z, emit x y = some z → encode z ∈ U) : + let r := MatchFold.run key₁ key₂ (callback C encode emit) xs ys empty + r.keys.overflow = false ∧ ∀ q, + (∃ z ∈ r.records.toList, encode z = q) ↔ + ∃ x ∈ xs, ∃ y ∈ ys, key₁ x = key₂ y ∧ + ∃ z, emit x y = some z ∧ encode z = q := by + rw [matchFold_eq_records] + have hf := fold_fits (width := width) encode (matchingRecords key₁ key₂ emit xs ys) + U hwidth hcap (by + intro z hz + obtain ⟨x, hx, y, hy, he, hz⟩ := (mem_matchingRecords _ _ _ _ _ _).mp hz + exact hkeys x hx y hy he z hz) + refine ⟨hf.1, ?_⟩ + intro q + rw [hf.2] + constructor + · rintro ⟨z, hz, he⟩ + obtain ⟨x, hx, y, hy, hm, hz⟩ := (mem_matchingRecords _ _ _ _ _ _).mp hz + exact ⟨x, hx, y, hy, hm, z, hz, he⟩ + · rintro ⟨x, hx, y, hy, hm, z, hz, he⟩ + exact ⟨z, (mem_matchingRecords _ _ _ _ _ _).mpr ⟨x, hx, y, hy, hm, hz⟩, he⟩ + +theorem join_eq_records {σ₁ σ₂ : Type*} (C : ℕ) (encode : α → List Bool) + (read₁ : σ₁ → Option (β × σ₁)) (key₁ : β → ℤ) + (read₂ : σ₂ → Option (γ × σ₂)) (key₂ : γ → ℤ) (emit : β → γ → Option α) + (view₁ : σ₁ → List β) (hread₁ : RowMerge.IsReader read₁ view₁) + (view₂ : σ₂ → List γ) (hread₂ : RowMerge.IsReader read₂ view₂) + (B fuel₁ fuel₂ controlFuel : ℕ) (s₁ : σ₁) (s₂ : σ₂) (r : State α) + (hsort₁ : (view₁ s₁).Pairwise (fun x y => key₁ x ≤ key₁ y)) + (hsort₂ : (view₂ s₂).Pairwise (fun x y => key₂ x ≤ key₂ y)) + (hcap₁ : (view₁ s₁).length ≤ fuel₁) (hcap₂ : (view₂ s₂).length ≤ fuel₂) + (hfuel : (view₁ s₁).length + (view₂ s₂).length < controlFuel) : + (StreamJoin.stopped read₁ key₁ read₂ key₂ (callback C encode emit) + B fuel₁ fuel₂ controlFuel s₁ s₂ r).state.user = + (matchingRecords key₁ key₂ emit (view₁ s₁) (view₂ s₂)).foldl + (fun r z => feed C encode z r) r := by + rw [StreamJoin.stopped_eq, StreamJoin.run_complete read₁ key₁ read₂ key₂ + (callback C encode emit) (fun _ _ _ => rfl) view₁ hread₁ view₂ hread₂ B fuel₁ fuel₂ + controlFuel s₁ s₂ r hsort₁ hsort₂ hcap₁ hcap₂ hfuel, matchFold_eq_records] + +/-- No capacity hypothesis is needed for provenance: overflowing joins retain +only entries emitted by a matching pair. -/ +theorem join_provenance {σ₁ σ₂ : Type*} (C : ℕ) (encode : α → List Bool) + (read₁ : σ₁ → Option (β × σ₁)) (key₁ : β → ℤ) + (read₂ : σ₂ → Option (γ × σ₂)) (key₂ : γ → ℤ) (emit : β → γ → Option α) + (view₁ : σ₁ → List β) (hread₁ : RowMerge.IsReader read₁ view₁) + (view₂ : σ₂ → List γ) (hread₂ : RowMerge.IsReader read₂ view₂) + (B fuel₁ fuel₂ controlFuel : ℕ) (s₁ : σ₁) (s₂ : σ₂) + (hsort₁ : (view₁ s₁).Pairwise (fun x y => key₁ x ≤ key₁ y)) + (hsort₂ : (view₂ s₂).Pairwise (fun x y => key₂ x ≤ key₂ y)) + (hcap₁ : (view₁ s₁).length ≤ fuel₁) (hcap₂ : (view₂ s₂).length ≤ fuel₂) + (hfuel : (view₁ s₁).length + (view₂ s₂).length < controlFuel) + (z : α) (hz : z ∈ (StreamJoin.stopped read₁ key₁ read₂ key₂ (callback C encode emit) + B fuel₁ fuel₂ controlFuel s₁ s₂ empty).state.user.records.toList) : + ∃ x ∈ view₁ s₁, ∃ y ∈ view₂ s₂, key₁ x = key₂ y ∧ emit x y = some z := by + rw [join_eq_records C encode read₁ key₁ read₂ key₂ emit view₁ hread₁ view₂ hread₂ + B fuel₁ fuel₂ controlFuel s₁ s₂ empty hsort₁ hsort₂ hcap₁ hcap₂ hfuel] at hz + exact (mem_matchingRecords key₁ key₂ emit _ _ z).mp + (fold_provenance C encode (matchingRecords key₁ key₂ emit (view₁ s₁) (view₂ s₂)) + empty (fun z => z ∈ matchingRecords key₁ key₂ emit (view₁ s₁) (view₂ s₂)) + (by simp [empty]) (fun _ h => h) z hz) + +end LowSpaceSubsetSum.RecordedDictionary + +end OAI diff --git a/lean/OAI/Combinatorics/LowSpaceSubsetSum/Streams/ResidueFilters.lean b/lean/OAI/Combinatorics/LowSpaceSubsetSum/Streams/ResidueFilters.lean new file mode 100644 index 0000000000000000000000000000000000000000..aede69f54c18f9bcbb59e5a783c60cbaca5f447e --- /dev/null +++ b/lean/OAI/Combinatorics/LowSpaceSubsetSum/Streams/ResidueFilters.lean @@ -0,0 +1,121 @@ +import OAI.Combinatorics.LowSpaceSubsetSum.Streams.ModularFilters +import Mathlib.Algebra.BigOperators.Group.Finset.Basic +import Mathlib.Data.Fintype.Prod + +namespace OAI + +/-! +# Exact counts under uniform low-residue choices + +Raw occurrence identities and distinct entry keys may be different types. +Neither is deduplicated here: each supplied finite set is partitioned by its +residue labels. This is the exact uniform-residue calculation for the counts +`G`, `J`, and `U` in the resource proof. +-/ + +namespace LowSpaceSubsetSum + +open scoped BigOperators + +variable {α : Type*} + +def normalizedResidue {p : ℕ} (hp : 0 < p) (x : ℤ) : Fin p := + ⟨(x % (p : ℤ)).toNat, by + have hpZ : (0 : ℤ) < p := by exact_mod_cast hp + exact (Int.toNat_lt (Int.emod_nonneg _ hpZ.ne')).mpr + (Int.emod_lt_of_pos _ hpZ)⟩ + +theorem normalizedResidue_eq_iff {p : ℕ} (hp : 0 < p) (x : ℤ) (r : Fin p) : + normalizedResidue hp x = r ↔ x % (p : ℤ) = r := by + have hpZ : (0 : ℤ) < p := by exact_mod_cast hp + have hnonneg := Int.emod_nonneg x hpZ.ne' + constructor + · intro h + have hval := congrArg (fun r : Fin p => (r.val : ℤ)) h + simpa only [normalizedResidue, Int.toNat_of_nonneg hnonneg] using hval + · intro h + apply Fin.ext + simp only [normalizedResidue] + rw [h] + rfl + +theorem sum_label_fibers {Ω : Type*} [Fintype Ω] [DecidableEq Ω] + (T : Finset α) (label : α → Ω) : + ∑ r : Ω, (T.filter fun x => label x = r).card = T.card := by + exact (Finset.card_eq_sum_card_fiberwise + (s := T) (t := Finset.univ) (f := label) (by simp)).symm + +theorem mean_label_fiber {Ω : Type*} [Fintype Ω] [DecidableEq Ω] + (T : Finset α) (label : α → Ω) : + (∑ r : Ω, ((T.filter fun x => label x = r).card : ℝ)) / Fintype.card Ω = + (T.card : ℝ) / Fintype.card Ω := by + congr 1 + exact_mod_cast sum_label_fibers T label + +def residueFiltered {p : ℕ} (hp : 0 < p) (T : Finset α) (w : α → ℤ) + (r : Fin p) : Finset α := T.filter fun x => normalizedResidue hp (w x) = r + +theorem mean_residueFiltered {p : ℕ} (hp : 0 < p) (T : Finset α) (w : α → ℤ) : + (∑ r : Fin p, ((residueFiltered hp T w r).card : ℝ)) / p = (T.card : ℝ) / p := by + simpa only [residueFiltered, Fintype.card_fin] using + mean_label_fiber T (fun x => normalizedResidue hp (w x)) + +def twiceResidueFiltered {p q : ℕ} (hp : 0 < p) (hq : 0 < q) + (T : Finset α) (parent child : α → ℤ) (r : Fin p × Fin q) : Finset α := + T.filter fun x => normalizedResidue hp (parent x) = r.1 ∧ + normalizedResidue hq (child x) = r.2 + +/-- Each raw four-leaf occurrence passes one and only one parent/first-child +residue pair. The second child's required residue follows by nesting. -/ +theorem mean_twiceResidueFiltered {p q : ℕ} (hp : 0 < p) (hq : 0 < q) + (T : Finset α) (parent child : α → ℤ) : + (∑ r : Fin p × Fin q, ((twiceResidueFiltered hp hq T parent child r).card : ℝ)) / + (p * q : ℕ) = (T.card : ℝ) / (p * q : ℕ) := by + simpa only [twiceResidueFiltered, Prod.ext_iff, Fintype.card_prod, + Fintype.card_fin] using mean_label_fiber T + (fun x => (normalizedResidue hp (parent x), normalizedResidue hq (child x))) + +/-- Finite Markov bound for a counted resource. No independence between +different resources is required when these marginal bounds are combined. -/ +theorem finite_count_markov {Ω : Type*} [Fintype Ω] [DecidableEq Ω] [Nonempty Ω] + (count : Ω → ℕ) {T : ℝ} (hT : 0 < T) : + (((Finset.univ.filter fun r => T < (count r : ℝ)).card : ℝ) / Fintype.card Ω) ≤ + ((∑ r : Ω, (count r : ℝ)) / Fintype.card Ω) / T := by + classical + have hcard : (0 : ℝ) < Fintype.card Ω := by exact_mod_cast Fintype.card_pos + have hind : ∀ r : Ω, (if T < (count r : ℝ) then T else 0) ≤ count r := by + intro r + split_ifs with h + · exact h.le + · exact Nat.cast_nonneg _ + have hsum := Finset.sum_le_sum (s := (Finset.univ : Finset Ω)) + (fun r _ => hind r) + rw [← Finset.sum_filter] at hsum + simp only [Finset.sum_const, nsmul_eq_mul] at hsum + apply (le_div_iff₀ hT).mpr + rw [div_mul_eq_mul_div] + exact (div_le_div_iff_of_pos_right hcard).mpr hsum + +theorem residueFiltered_tail {p : ℕ} (hp : 0 < p) (X : Finset α) (w : α → ℤ) + {T : ℝ} (hT : 0 < T) : + (((Finset.univ.filter fun r : Fin p => T < (residueFiltered hp X w r).card).card : ℝ) / + p) ≤ ((X.card : ℝ) / p) / T := by + let : Nonempty (Fin p) := ⟨⟨0, hp⟩⟩ + have h := finite_count_markov (fun r => (residueFiltered hp X w r).card) hT + simpa only [Fintype.card_fin, mean_residueFiltered] using h + +theorem twiceResidueFiltered_tail {p q : ℕ} (hp : 0 < p) (hq : 0 < q) + (X : Finset α) (parent child : α → ℤ) {T : ℝ} (hT : 0 < T) : + (((Finset.univ.filter fun r : Fin p × Fin q => + T < (twiceResidueFiltered hp hq X parent child r).card).card : ℝ) / + (p * q : ℕ)) ≤ ((X.card : ℝ) / (p * q : ℕ)) / T := by + let : Nonempty (Fin p) := ⟨⟨0, hp⟩⟩ + let : Nonempty (Fin q) := ⟨⟨0, hq⟩⟩ + have h := finite_count_markov + (fun r => (twiceResidueFiltered hp hq X parent child r).card) hT + simpa only [Fintype.card_prod, Fintype.card_fin, ← Nat.cast_mul, + mean_twiceResidueFiltered] using h + +end LowSpaceSubsetSum + +end OAI diff --git a/lean/OAI/Combinatorics/LowSpaceSubsetSum/Streams/ResidueSort.lean b/lean/OAI/Combinatorics/LowSpaceSubsetSum/Streams/ResidueSort.lean new file mode 100644 index 0000000000000000000000000000000000000000..6212fc52f1511b1c113de8c44f199d7829f84622 --- /dev/null +++ b/lean/OAI/Combinatorics/LowSpaceSubsetSum/Streams/ResidueSort.lean @@ -0,0 +1,81 @@ +import OAI.Combinatorics.LowSpaceSubsetSum.Streams.FilteredRow +import Mathlib.Data.List.Sort + +namespace OAI + +/-! # Concrete lexicographic residue sorting of the shared right array -/ + +namespace LowSpaceSubsetSum +namespace ResidueSort + +variable {α : Type*} + +def relation (w : α → ℤ) (p P : ℤ) (x y : α) : Prop := + w x % p < w y % p ∨ w x % p = w y % p ∧ w x % P ≤ w y % P + +instance (w : α → ℤ) (p P : ℤ) : DecidableRel (relation w p P) := + fun _ _ => inferInstanceAs (Decidable (_ ∨ _ ∧ _)) + +theorem transitive (w : α → ℤ) (p P : ℤ) : + ∀ {x y z}, relation w p P x y → relation w p P y z → relation w p P x z := by + intro x y z hxy hyz + dsimp only [relation] at * + omega + +theorem total (w : α → ℤ) (p P : ℤ) (x y : α) : + relation w p P x y ∨ relation w p P y x := by + dsimp only [relation] + omega + +def sort (xs : Array α) (w : α → ℤ) (p P : ℤ) : Array α := + (xs.toList.mergeSort (fun x y => decide (relation w p P x y))).toArray + +theorem permutation (xs : Array α) (w : α → ℤ) (p P : ℤ) : + (sort xs w p P).toList.Perm xs.toList := by + simpa only [sort, List.toList_toArray] using + List.mergeSort_perm xs.toList (fun x y => decide (relation w p P x y)) + +theorem size (xs : Array α) (w : α → ℤ) (p P : ℤ) : + (sort xs w p P).size = xs.size := by + have h := (permutation xs w p P).length_eq + simpa only [Array.length_toList] using h + +theorem sorted (xs : Array α) (w : α → ℤ) (p P : ℤ) : + (sort xs w p P).toList.Pairwise (relation w p P) := by + simpa only [sort, List.toList_toArray, decide_eq_true_eq] using + List.pairwise_mergeSort (le := fun x y => decide (relation w p P x y)) + (fun x y z hxy hyz => by + exact decide_eq_true (transitive w p P (of_decide_eq_true hxy) (of_decide_eq_true hyz))) + (fun x y => by simpa only [Bool.or_eq_true, decide_eq_true_eq] using total w p P x y) + xs.toList + +theorem index_order (xs : Array α) (w : α → ℤ) (p P : ℤ) + (i j : Fin (sort xs w p P).size) (hij : i ≤ j) : + relation w p P (sort xs w p P)[i.val] (sort xs w p P)[j.val] := by + rcases lt_or_eq_of_le hij with hlt | heq + · have h := (sorted xs w p P).rel_getElem_of_lt + (by simpa only [Array.length_toList] using i.isLt) + (by simpa only [Array.length_toList] using j.isLt) hlt + simpa only [Array.getElem_toList] using h + · subst j + exact Or.inr ⟨rfl, le_rfl⟩ + +theorem primary (xs : Array α) (w : α → ℤ) (p P : ℤ) : + FilteredRow.PrimarySorted (sort xs w p P) w p := by + intro i j hij + change w (sort xs w p P)[i.val] % p ≤ w (sort xs w p P)[j.val] % p + have h := index_order xs w p P i j hij + dsimp only [relation] at h + omega + +theorem secondary (xs : Array α) (w : α → ℤ) (p P : ℤ) : + FilteredRow.SecondarySorted (sort xs w p P) w p P := by + intro i j hij heq + have h := index_order xs w p P i j hij + dsimp only [relation] at h + omega + +end ResidueSort +end LowSpaceSubsetSum + +end OAI diff --git a/lean/OAI/Combinatorics/LowSpaceSubsetSum/Streams/RowMerge.lean b/lean/OAI/Combinatorics/LowSpaceSubsetSum/Streams/RowMerge.lean new file mode 100644 index 0000000000000000000000000000000000000000..221e30817c9b0bdfb1c66e70c520a926a3a742ae --- /dev/null +++ b/lean/OAI/Combinatorics/LowSpaceSubsetSum/Streams/RowMerge.lean @@ -0,0 +1,199 @@ +import OAI.Combinatorics.LowSpaceSubsetSum.Streams.Tournament +import OAI.Combinatorics.LowSpaceSubsetSum.Streams.CyclicCursor + +namespace OAI + +/-! +# A tournament merge with one current occurrence per row + +The shared immutable input arrays are parameters of the row reader. Each +leaf contains a row identifier, its current item, and its cursor after that +item. Advancing the winning row performs one row read and one tournament +replacement. The remaining lists below are ghost views used for correctness; +the merge state stores no pair-product list. +-/ + +namespace LowSpaceSubsetSum +namespace RowMerge + +universe u v + +variable {α : Type u} {σ : Type v} {d : ℕ} + +abbrev Path (d : ℕ) := Fin d → Bool + +structure Front (d : ℕ) (α : Type u) (σ : Type v) where + row : Path d + value : α + after : σ + +def front (read : σ → Option (α × σ)) (p : Path d) (s : σ) : Option (Front d α σ) := + (read s).map (fun z => ⟨p, z.1, z.2⟩) + +def start (key : α → ℤ) (read : σ → Option (α × σ)) (s : Path d → σ) : + Tournament.Tree (Front d α σ) d := + Tournament.build (fun x => key x.value) d (fun p => front read p (s p)) + +def Aligned (t : Tournament.Tree (Front d α σ) d) : Prop := + ∀ p x, Tournament.lookup t p = some x → x.row = p + +theorem front_row (read : σ → Option (α × σ)) (p : Path d) (s : σ) + {x : Front d α σ} (hx : front read p s = some x) : x.row = p := by + cases hr : read s with + | none => simp [front, hr] at hx + | some z => + have heq : (⟨p, z.1, z.2⟩ : Front d α σ) = x := by simpa [front, hr] using hx + rw [← heq] + +theorem start_aligned (key : α → ℤ) (read : σ → Option (α × σ)) (s : Path d → σ) : + Aligned (start key read s) := by + intro p x hx + rw [start, Tournament.lookup_build] at hx + exact front_row read p (s p) hx + +theorem start_valid (key : α → ℤ) (read : σ → Option (α × σ)) (s : Path d → σ) : + Tournament.Valid (fun x => key x.value) (start key read s) := + Tournament.build_valid _ _ _ + +def advance (key : α → ℤ) (read : σ → Option (α × σ)) + (t : Tournament.Tree (Front d α σ) d) : + Option (α × Tournament.Tree (Front d α σ) d) := + (Tournament.winner t).map fun x => + (x.value, Tournament.replace (fun y => key y.value) t x.row (front read x.row x.after)) + +theorem advance_valid (key : α → ℤ) (read : σ → Option (α × σ)) + (t : Tournament.Tree (Front d α σ) d) + (ht : Tournament.Valid (fun x => key x.value) t) {a : α} + {t' : Tournament.Tree (Front d α σ) d} (ha : advance key read t = some (a, t')) : + Tournament.Valid (fun x => key x.value) t' := by + cases hw : Tournament.winner t with + | none => simp [advance, hw] at ha + | some x => + have heq : (x.value, Tournament.replace (fun y => key y.value) t x.row + (front read x.row x.after)) = (a, t') := by simpa [advance, hw] using ha + rw [← (Prod.mk.inj heq).2] + exact Tournament.replace_valid _ t ht _ _ + +theorem advance_aligned (key : α → ℤ) (read : σ → Option (α × σ)) + (t : Tournament.Tree (Front d α σ) d) (ht : Aligned t) {a : α} + {t' : Tournament.Tree (Front d α σ) d} (ha : advance key read t = some (a, t')) : + Aligned t' := by + cases hw : Tournament.winner t with + | none => simp [advance, hw] at ha + | some x => + have heq : (x.value, Tournament.replace (fun y => key y.value) t x.row + (front read x.row x.after)) = (a, t') := by simpa [advance, hw] using ha + rw [← (Prod.mk.inj heq).2] + intro p y hy + rw [Tournament.lookup_replace] at hy + by_cases hp : x.row = p + · rw [ite_eq_left hp] at hy + exact (front_row read x.row x.after hy).trans hp + · rw [ite_eq_right hp] at hy + exact ht p y hy + +theorem winner_at_own_row (key : α → ℤ) (t : Tournament.Tree (Front d α σ) d) + (ht : Tournament.Valid (fun x => key x.value) t) (halign : Aligned t) + {x : Front d α σ} (hx : Tournament.winner t = some x) : + Tournament.lookup t x.row = some x := by + have hm := (Tournament.winner_best (fun x => key x.value) t ht).1 x hx + obtain ⟨p, hp⟩ := (Tournament.mem_candidates_iff t x).mp hm + rw [halign p x hp] + exact hp + +theorem winner_is_minimum (key : α → ℤ) (t : Tournament.Tree (Front d α σ) d) + (ht : Tournament.Valid (fun x => key x.value) t) {x : Front d α σ} + (hx : Tournament.winner t = some x) (p : Path d) {y : Front d α σ} + (hy : Tournament.lookup t p = some y) : key x.value ≤ key y.value := by + obtain ⟨w, hw, hwy⟩ := Tournament.winner_le_lookup (fun x => key x.value) t ht p hy + have h : w = x := Option.some.inj (hw.symm.trans hx) + simpa [h] using hwy + +/-- A row reader's finite output law, used only in the correctness proof. -/ +def IsReader (read : σ → Option (α × σ)) (view : σ → List α) : Prop := + ∀ s, match read s with + | none => view s = [] + | some (a, s') => view s = a :: view s' + +theorem cyclic_next_reader (xs : Array α) [NeZero xs.size] : + IsReader (CyclicCursor.next xs) + (fun c => CyclicCursor.trace (fun i : Fin xs.size => xs[i.val]) c.remaining c) := by + intro c + cases h : c.remaining with + | zero => simp [CyclicCursor.next, CyclicCursor.trace, h] + | succ k => + simp [CyclicCursor.next, CyclicCursor.trace, h, CyclicCursor.advance_remaining] + +def remaining (view : σ → List α) (t : Tournament.Tree (Front d α σ) d) + (p : Path d) : List α := + match Tournament.lookup t p with + | none => [] + | some x => x.value :: view x.after + +theorem start_remaining (key : α → ℤ) (read : σ → Option (α × σ)) + (view : σ → List α) (hread : IsReader read view) (s : Path d → σ) (p : Path d) : + remaining view (start key read s) p = view (s p) := by + simp only [remaining, start, Tournament.lookup_build, front] + have hr := hread (s p) + cases h : read (s p) with + | none => + simp only [h] at hr + simpa using hr.symm + | some z => + simp only [h] at hr + simpa using hr.symm + +theorem replace_remaining (key : α → ℤ) (read : σ → Option (α × σ)) + (view : σ → List α) (hread : IsReader read view) + (t : Tournament.Tree (Front d α σ) d) (x : Front d α σ) (q : Path d) : + remaining view (Tournament.replace (fun y => key y.value) t x.row + (front read x.row x.after)) q = + if x.row = q then view x.after else remaining view t q := by + unfold remaining + rw [Tournament.lookup_replace] + by_cases hq : x.row = q + · rw [ite_eq_left hq, ite_eq_left hq] + have hr := hread x.after + cases h : read x.after with + | none => + simp only [h] at hr + simpa [front, h] using hr.symm + | some z => + simp only [h] at hr + simpa [front, h] using hr.symm + · rw [ite_eq_right hq, ite_eq_right hq] + +def potential (view : σ → List α) (t : Tournament.Tree (Front d α σ) d) : ℕ := + ∑ p : Path d, (remaining view t p).length + +theorem replacement_consumes_one (key : α → ℤ) (read : σ → Option (α × σ)) + (view : σ → List α) (hread : IsReader read view) + (t : Tournament.Tree (Front d α σ) d) + (ht : Tournament.Valid (fun y => key y.value) t) (halign : Aligned t) + {x : Front d α σ} (hx : Tournament.winner t = some x) : + potential view (Tournament.replace (fun y => key y.value) t x.row + (front read x.row x.after)) + 1 = potential view t := by + have hrow := winner_at_own_row key t ht halign hx + let t' := Tournament.replace (fun y => key y.value) t x.row (front read x.row x.after) + have hpoint (p : Path d) : (remaining view t p).length = + (remaining view t' p).length + if p = x.row then 1 else 0 := by + have hnew := replace_remaining key read view hread t x p + change remaining view t' p = _ at hnew + by_cases hp : p = x.row + · subst p + rw [ite_eq_left rfl] at hnew + rw [hnew] + simp [remaining, hrow] + · rw [ite_eq_right (Ne.symm hp)] at hnew + rw [hnew, ite_eq_right hp] + omega + unfold potential + rw [show (∑ p : Path d, (remaining view t p).length) = + ∑ p : Path d, ((remaining view t' p).length + if p = x.row then 1 else 0) from + Finset.sum_congr rfl (fun p _ => hpoint p)] + simp [Finset.sum_add_distrib, t'] + +end RowMerge +end LowSpaceSubsetSum + +end OAI diff --git a/lean/OAI/Combinatorics/LowSpaceSubsetSum/Streams/SliceCursor.lean b/lean/OAI/Combinatorics/LowSpaceSubsetSum/Streams/SliceCursor.lean new file mode 100644 index 0000000000000000000000000000000000000000..b468c782df41317653457e76bdc2c2ac2d26daf6 --- /dev/null +++ b/lean/OAI/Combinatorics/LowSpaceSubsetSum/Streams/SliceCursor.lean @@ -0,0 +1,102 @@ +import OAI.Combinatorics.LowSpaceSubsetSum.Streams.RowMerge + +namespace OAI + +/-! +# Cyclic row cursors into one shared immutable array + +Each cursor stores its slice endpoints and the constant-size cyclic state. +Reading a row accesses the original array; it does not allocate a row array. +Empty slices have no cursor. The list slice and full trace are proof views. +-/ + +namespace LowSpaceSubsetSum +namespace SliceCursor + +variable {α : Type*} {n : ℕ} + +structure Range (n : ℕ) where + lo : ℕ + length : ℕ + bounded : lo + length ≤ n + deriving DecidableEq + +structure State (n : ℕ) where + range : Range n + cursor : Option (CyclicCursor.State range.length) + +def values (xs : Array α) (r : Range xs.size) (i : Fin r.length) : α := + xs[r.lo + i.val]'(by have := r.bounded; have := i.isLt; omega) + +def next (xs : Array α) (s : State xs.size) : Option (α × State xs.size) := + match s.cursor with + | none => none + | some c => + haveI : NeZero s.range.length := ⟨by have := c.position.isLt; omega⟩ + if c.remaining = 0 then none + else some (values xs s.range c.position, ⟨s.range, some (CyclicCursor.advance c)⟩) + +def output (xs : Array α) (s : State xs.size) : List α := + match s.cursor with + | none => [] + | some c => + haveI : NeZero s.range.length := ⟨by have := c.position.isLt; omega⟩ + CyclicCursor.trace (values xs s.range) c.remaining c + +theorem reader (xs : Array α) : RowMerge.IsReader (next xs) (output xs) := by + rintro ⟨r, c⟩ + cases c with + | none => rfl + | some c => + have : NeZero r.length := ⟨by have := c.position.isLt; omega⟩ + cases h : c.remaining with + | zero => simp [next, output, h, CyclicCursor.trace] + | succ k => + simp [next, output, h, CyclicCursor.trace, CyclicCursor.advance_remaining] + +def initial (r : Range n) (pivot : ℕ) (reverse : Bool) : State n := + if h : 0 < r.length then + ⟨r, some ⟨⟨pivot % r.length, Nat.mod_lt _ h⟩, r.length, reverse⟩⟩ + else ⟨r, none⟩ + +/-- A slice is a proof view, not a newly allocated row array. -/ +def slice (xs : Array α) (r : Range xs.size) : List α := List.ofFn (values xs r) + +theorem initial_perm (xs : Array α) (r : Range xs.size) (pivot : ℕ) (reverse : Bool) : + (output xs (initial r pivot reverse)).Perm (slice xs r) := by + by_cases h : 0 < r.length + · have : NeZero r.length := ⟨by omega⟩ + rw [initial, dite_eq_left h] + exact + CyclicCursor.full_trace_perm (values xs r) ⟨pivot % r.length, Nat.mod_lt _ h⟩ reverse + · have hz : r.length = 0 := by omega + rw [initial, dite_eq_right h] + simp [output, slice, hz] + +theorem initial_length (xs : Array α) (r : Range xs.size) (pivot : ℕ) (reverse : Bool) : + (output xs (initial r pivot reverse)).length = r.length := by + rw [(initial_perm xs r pivot reverse).length_eq] + simp [slice] + +theorem slice_eq_drop_take (xs : Array α) (r : Range xs.size) : + slice xs r = (xs.toList.drop r.lo).take r.length := by + have hlo : r.lo ≤ xs.size := by have := r.bounded; omega + apply List.ext_getElem + · simp only [slice, List.length_ofFn, List.length_take, List.length_drop, Array.length_toList] + have := r.bounded + omega + · intro i hi hj + simp only [slice, List.getElem_ofFn, List.getElem_take, List.getElem_drop, + Array.getElem_toList, values] + +theorem initial_occurrences (xs : Array α) (r : Range xs.size) + (pivot : ℕ) (reverse : Bool) : + (output xs (initial r pivot reverse) : Multiset α) = + ((xs.toList.drop r.lo).take r.length : Multiset α) := by + rw [← slice_eq_drop_take xs r] + exact Quot.sound (initial_perm xs r pivot reverse) + +end SliceCursor +end LowSpaceSubsetSum + +end OAI diff --git a/lean/OAI/Combinatorics/LowSpaceSubsetSum/Streams/SortedFind.lean b/lean/OAI/Combinatorics/LowSpaceSubsetSum/Streams/SortedFind.lean new file mode 100644 index 0000000000000000000000000000000000000000..57d1b5dc87a5536dd5d716451665bbc0ee7e076b --- /dev/null +++ b/lean/OAI/Combinatorics/LowSpaceSubsetSum/Streams/SortedFind.lean @@ -0,0 +1,146 @@ +import OAI.Combinatorics.LowSpaceSubsetSum.Counting.MatchPotential + +namespace OAI + +/-! +# Linear exact-key search for the separator's terminal arrays + +At a terminal separator node every left/right pair is disjoint. One equal +weight key therefore suffices. This loop stops at the first equal key and +never enumerates its Cartesian tie group. The finite reader law supplies +exactness, and the ledger charges at most two reads per control step. +-/ + +namespace LowSpaceSubsetSum +namespace SortedFind + +variable {α β σ₁ σ₂ : Type*} + +def runAcc (read₁ : σ₁ → Option (α × σ₁)) (key₁ : α → ℤ) + (read₂ : σ₂ → Option (β × σ₂)) (key₂ : β → ℤ) : + ℕ → σ₁ → σ₂ → ℕ → Bool × ℕ + | 0, _, _, queries => (false, queries) + | fuel + 1, s₁, s₂, queries => + match read₁ s₁ with + | none => (false, queries + 1) + | some (x, s₁') => match read₂ s₂ with + | none => (false, queries + 2) + | some (y, s₂') => + if key₁ x < key₂ y then runAcc read₁ key₁ read₂ key₂ fuel s₁' s₂ (queries + 2) + else if key₂ y < key₁ x then runAcc read₁ key₁ read₂ key₂ fuel s₁ s₂' (queries + 2) + else (true, queries + 2) + +theorem queries_le (read₁ : σ₁ → Option (α × σ₁)) (key₁ : α → ℤ) + (read₂ : σ₂ → Option (β × σ₂)) (key₂ : β → ℤ) + (fuel : ℕ) (s₁ : σ₁) (s₂ : σ₂) (queries : ℕ) : + (runAcc read₁ key₁ read₂ key₂ fuel s₁ s₂ queries).2 ≤ queries + 2 * fuel := by + induction fuel generalizing s₁ s₂ queries with + | zero => simp [runAcc] + | succ fuel ih => + unfold runAcc + split + · dsimp + omega + · split + · dsimp + omega + · split + · exact (ih _ _ _).trans (by omega) + · split + · exact (ih _ _ _).trans (by omega) + · dsimp + omega + +theorem sound (read₁ : σ₁ → Option (α × σ₁)) (key₁ : α → ℤ) + (read₂ : σ₂ → Option (β × σ₂)) (key₂ : β → ℤ) + (view₁ : σ₁ → List α) (hread₁ : RowMerge.IsReader read₁ view₁) + (view₂ : σ₂ → List β) (hread₂ : RowMerge.IsReader read₂ view₂) + (fuel : ℕ) (s₁ : σ₁) (s₂ : σ₂) (queries : ℕ) + (hyes : (runAcc read₁ key₁ read₂ key₂ fuel s₁ s₂ queries).1 = true) : + ∃ x ∈ view₁ s₁, ∃ y ∈ view₂ s₂, key₁ x = key₂ y := by + induction fuel generalizing s₁ s₂ queries with + | zero => simp [runAcc] at hyes + | succ fuel ih => + have h₁ := hread₁ s₁ + have h₂ := hread₂ s₂ + cases hx : read₁ s₁ with + | none => simp [runAcc, hx] at hyes + | some xp => + obtain ⟨x, s₁'⟩ := xp + simp only [hx] at h₁ + cases hy : read₂ s₂ with + | none => simp [runAcc, hx, hy] at hyes + | some yp => + obtain ⟨y, s₂'⟩ := yp + simp only [hy] at h₂ + by_cases hlt : key₁ x < key₂ y + · simp only [runAcc, hx, hy, hlt, ↓reduceIte] at hyes + obtain ⟨a, ha, b, hb, heq⟩ := ih _ _ _ hyes + exact ⟨a, by rw [h₁]; exact List.mem_cons_of_mem _ ha, b, hb, heq⟩ + · by_cases hgt : key₂ y < key₁ x + · simp only [runAcc, hx, hy, hlt, hgt, ↓reduceIte] at hyes + obtain ⟨a, ha, b, hb, heq⟩ := ih _ _ _ hyes + exact ⟨a, ha, b, by rw [h₂]; exact List.mem_cons_of_mem _ hb, heq⟩ + · exact ⟨x, by rw [h₁]; simp, y, by rw [h₂]; simp, by omega⟩ + +theorem correct (read₁ : σ₁ → Option (α × σ₁)) (key₁ : α → ℤ) + (read₂ : σ₂ → Option (β × σ₂)) (key₂ : β → ℤ) + (view₁ : σ₁ → List α) (hread₁ : RowMerge.IsReader read₁ view₁) + (view₂ : σ₂ → List β) (hread₂ : RowMerge.IsReader read₂ view₂) + (fuel : ℕ) (s₁ : σ₁) (s₂ : σ₂) (queries : ℕ) + (hs₁ : (view₁ s₁).Pairwise (fun x y => key₁ x ≤ key₁ y)) + (hs₂ : (view₂ s₂).Pairwise (fun x y => key₂ x ≤ key₂ y)) + (hfuel : (view₁ s₁).length + (view₂ s₂).length < fuel) : + (runAcc read₁ key₁ read₂ key₂ fuel s₁ s₂ queries).1 = true ↔ + 0 < MatchPotential.count key₁ key₂ (view₁ s₁) (view₂ s₂) := by + induction fuel generalizing s₁ s₂ queries with + | zero => omega + | succ fuel ih => + have h₁ := hread₁ s₁ + have h₂ := hread₂ s₂ + cases hx : read₁ s₁ with + | none => + simp only [hx] at h₁ + simp [runAcc, hx, h₁, MatchPotential.count] + | some xp => + obtain ⟨x, s₁'⟩ := xp + simp only [hx] at h₁ + cases hy : read₂ s₂ with + | none => + simp only [hy] at h₂ + have hz := MatchPotential.eq_zero key₁ key₂ (view₁ s₁) [] (by simp) + simp [runAcc, hx, hy, h₂, hz] + | some yp => + obtain ⟨y, s₂'⟩ := yp + simp only [hy] at h₂ + have hs₁' := (List.pairwise_cons.mp (h₁ ▸ hs₁)).2 + have hs₂' := (List.pairwise_cons.mp (h₂ ▸ hs₂)).2 + by_cases hlt : key₁ x < key₂ y + · have hskip := MatchPotential.skip_left key₁ key₂ x (view₁ s₁') (view₂ s₂) (by + intro z hz + rw [h₂] at hz + rcases List.mem_cons.mp hz with rfl | hz + · exact hlt + · exact hlt.trans_le ((List.pairwise_cons.mp (h₂ ▸ hs₂)).1 z hz)) + rw [← h₁] at hskip + simp only [runAcc, hx, hy, hlt, ↓reduceIte, hskip] + exact ih s₁' s₂ _ hs₁' hs₂ (by rw [h₁] at hfuel; simp only [List.length_cons] at hfuel; omega) + · by_cases hgt : key₂ y < key₁ x + · have hskip := MatchPotential.skip_right key₁ key₂ (view₁ s₁) y (view₂ s₂') (by + intro z hz + rw [h₁] at hz + rcases List.mem_cons.mp hz with rfl | hz + · exact hgt + · exact hgt.trans_le ((List.pairwise_cons.mp (h₁ ▸ hs₁)).1 z hz)) + rw [← h₂] at hskip + simp only [runAcc, hx, hy, hlt, hgt, ↓reduceIte, hskip] + exact ih s₁ s₂' _ hs₁ hs₂' (by rw [h₂] at hfuel; simp only [List.length_cons] at hfuel; omega) + · have heq : key₁ x = key₂ y := by omega + have hpos := (MatchPotential.positive_iff key₁ key₂ (view₁ s₁) (view₂ s₂)).mpr + ⟨x, by rw [h₁]; simp, y, by rw [h₂]; simp, heq⟩ + simp [runAcc, hx, hy, hlt, hgt, hpos] + +end SortedFind +end LowSpaceSubsetSum + +end OAI diff --git a/lean/OAI/Combinatorics/LowSpaceSubsetSum/Streams/StreamGroupFacts.lean b/lean/OAI/Combinatorics/LowSpaceSubsetSum/Streams/StreamGroupFacts.lean new file mode 100644 index 0000000000000000000000000000000000000000..a586630119d1b2c7e7f672cec8b0c0bdff1b7766 --- /dev/null +++ b/lean/OAI/Combinatorics/LowSpaceSubsetSum/Streams/StreamGroupFacts.lean @@ -0,0 +1,80 @@ +import OAI.Combinatorics.LowSpaceSubsetSum.Streams.StreamJoin + +namespace OAI + +/-! The exact potential and cursor facts for one equal-key stream step. -/ + +namespace LowSpaceSubsetSum +namespace StreamJoin + +universe u v s t w +variable {α : Type u} {β : Type v} {σ₁ : Type s} {σ₂ : Type t} {τ : Type w} + +theorem equal_group_facts (read₁ : σ₁ → Option (α × σ₁)) (key₁ : α → ℤ) + (read₂ : σ₂ → Option (β × σ₂)) (key₂ : β → ℤ) + (report : α → β → τ → τ × Bool) (hreport : ∀ x y a, (report x y a).2 = false) + (view₁ : σ₁ → List α) (hread₁ : RowMerge.IsReader read₁ view₁) + (view₂ : σ₂ → List β) (hread₂ : RowMerge.IsReader read₂ view₂) + (B fuel₁ fuel₂ : ℕ) (st : State σ₁ σ₂ τ) + (hst : WellFormed key₁ key₂ view₁ view₂ fuel₁ fuel₂ st) + (x : α) (left' : σ₁) (y : β) (right' : σ₂) + (hx : read₁ st.left = some (x, left')) (hy : read₂ st.right = some (y, right')) + (hkey : key₁ x = key₂ y) : + let out := TieGroup.run read₁ key₁ read₂ key₂ (key₁ x) report B fuel₁ fuel₂ + st.left st.right st.user + let G₁ := TieBuffer.groupView key₁ (key₁ x) view₁ st.left + let G₂ := TieBuffer.groupView key₂ (key₁ x) view₂ st.right + (view₁ out.outer.cursor).Pairwise (fun x y => key₁ x ≤ key₁ y) ∧ + (view₂ out.outer.state.last).Pairwise (fun x y => key₂ x ≤ key₂ y) ∧ + (view₁ st.left).length = G₁.length + (view₁ out.outer.cursor).length ∧ + (view₂ st.right).length = G₂.length + (view₂ out.outer.state.last).length ∧ + 0 < G₁.length ∧ 0 < G₂.length ∧ + MatchPotential.count key₁ key₂ (view₁ st.left) (view₂ st.right) = + G₁.length * G₂.length + + MatchPotential.count key₁ key₂ (view₁ out.outer.cursor) (view₂ out.outer.state.last) := by + let out := TieGroup.run read₁ key₁ read₂ key₂ (key₁ x) report B fuel₁ fuel₂ + st.left st.right st.user + let G₁ := TieBuffer.groupView key₁ (key₁ x) view₁ st.left + let G₂ := TieBuffer.groupView key₂ (key₁ x) view₂ st.right + have hv₁ : view₁ st.left = x :: view₁ left' := by simpa only [hx] using hread₁ st.left + have hv₂ : view₂ st.right = y :: view₂ right' := by simpa only [hy] using hread₂ st.right + have hg₁ : G₁ ≠ [] := by simp [G₁, TieBuffer.groupView, hv₁] + have hg₂ : G₂ ≠ [] := by simp [G₂, TieBuffer.groupView, hv₂, ← hkey] + have hlen₁ : G₁.length ≤ fuel₁ := + (List.takeWhile_sublist (fun z => decide (key₁ z = key₁ x))).length_le.trans hst.2.2.1 + have hlen₂ : G₂.length ≤ fuel₂ := + (List.takeWhile_sublist (fun z => decide (key₂ z = key₁ x))).length_le.trans hst.2.2.2 + have hviews := TieGroup.views_complete read₁ key₁ read₂ key₂ (key₁ x) report hreport + view₁ hread₁ view₂ hread₂ B fuel₁ fuel₂ st.left st.right st.user hlen₁ hlen₂ hg₁ + change view₁ st.left = G₁ ++ view₁ out.outer.cursor ∧ + view₂ st.right = G₂ ++ view₂ out.outer.state.last at hviews + have hsub₁ := MatchPotential.remaining_sublist _ _ _ hviews.1 + have hsub₂ := MatchPotential.remaining_sublist _ _ _ hviews.2 + have hlower₁ : ∀ z ∈ view₁ st.left, key₁ x ≤ key₁ z := by + have hsort : (x :: view₁ left').Pairwise (fun x y => key₁ x ≤ key₁ y) := + by simpa only [hv₁] using hst.1 + simpa only [hv₁] using MatchPotential.lower_bound_head key₁ x _ hsort + have hlower₂ : ∀ z ∈ view₂ st.right, key₁ x ≤ key₂ z := by + rw [hkey, hv₂] + exact MatchPotential.lower_bound_head key₂ y _ (by simpa only [hv₂] using hst.2.1) + have hr₁ := MatchPotential.remaining_avoids key₁ (key₁ x) _ _ hviews.1 hst.1 hlower₁ + have hr₂ := MatchPotential.remaining_avoids key₂ (key₁ x) _ _ hviews.2 hst.2.1 hlower₂ + refine ⟨hst.1.sublist hsub₁, hst.2.1.sublist hsub₂, ?_, ?_, + List.length_pos_iff.mpr hg₁, List.length_pos_iff.mpr hg₂, ?_⟩ + · simpa only [List.length_append] using congrArg List.length hviews.1 + · simpa only [List.length_append] using congrArg List.length hviews.2 + · have hG₁ : ∀ z ∈ G₁, key₁ z = key₁ x := by + intro z hz + exact of_decide_eq_true (List.mem_takeWhile_imp (p := fun z => decide (key₁ z = key₁ x)) hz) + have hG₂ : ∀ z ∈ G₂, key₂ z = key₁ x := by + intro z hz + exact of_decide_eq_true (List.mem_takeWhile_imp (p := fun z => decide (key₂ z = key₁ x)) hz) + have hsplit := MatchPotential.split_groups key₁ key₂ (key₁ x) G₁ + (view₁ out.outer.cursor) G₂ (view₂ out.outer.state.last) hG₁ hG₂ hr₁ hr₂ + rw [← hviews.1, ← hviews.2] at hsplit + exact hsplit + +end StreamJoin +end LowSpaceSubsetSum + +end OAI diff --git a/lean/OAI/Combinatorics/LowSpaceSubsetSum/Streams/StreamJoin.lean b/lean/OAI/Combinatorics/LowSpaceSubsetSum/Streams/StreamJoin.lean new file mode 100644 index 0000000000000000000000000000000000000000..fdaa9ff9b21b4f4730622d80a341e53d0af159f4 --- /dev/null +++ b/lean/OAI/Combinatorics/LowSpaceSubsetSum/Streams/StreamJoin.lean @@ -0,0 +1,100 @@ +import OAI.Combinatorics.LowSpaceSubsetSum.Counting.MatchPotential + +namespace OAI + +/-! +# A finite-state join of two sorted streams + +Unequal keys consume one occurrence. Equal keys invoke the bounded-buffer +Cartesian reporter and continue from its two saved endpoints. The loop keeps +only the two generator states, callback state, and counters. Its finite output +lists and matching potential are analysis objects only. +-/ + +namespace LowSpaceSubsetSum +namespace StreamJoin + +universe u v s t w + +variable {α : Type u} {β : Type v} {σ₁ : Type s} {σ₂ : Type t} {τ : Type w} + +structure State (σ₁ : Type s) (σ₂ : Type t) (τ : Type w) where + left : σ₁ + right : σ₂ + user : τ + queries : ℕ + reports : ℕ + copies : ℕ + done : Bool + +def start (s₁ : σ₁) (s₂ : σ₂) (a : τ) : State σ₁ σ₂ τ := ⟨s₁, s₂, a, 0, 0, 0, false⟩ + +def step (read₁ : σ₁ → Option (α × σ₁)) (key₁ : α → ℤ) + (read₂ : σ₂ → Option (β × σ₂)) (key₂ : β → ℤ) + (report : α → β → τ → τ × Bool) (B fuel₁ fuel₂ : ℕ) + (s : State σ₁ σ₂ τ) : State σ₁ σ₂ τ := + if s.done then s else + match read₁ s.left with + | none => { s with queries := s.queries + 1, done := true } + | some (x, left') => match read₂ s.right with + | none => { s with queries := s.queries + 2, done := true } + | some (y, right') => + if key₁ x < key₂ y then { s with left := left', queries := s.queries + 2 } + else if key₂ y < key₁ x then { s with right := right', queries := s.queries + 2 } + else + let out := TieGroup.run read₁ key₁ read₂ key₂ (key₁ x) report B fuel₁ fuel₂ + s.left s.right s.user + ⟨out.outer.cursor, out.outer.state.last, out.outer.state.user, + s.queries + 2 + out.outer.queries + out.fillQueries + out.outer.state.queries, + s.reports + out.outer.state.reports, + s.copies + (if out.snapshot then 1 else 0) + out.outer.state.restores, + out.outer.halted⟩ + +def runAcc (read₁ : σ₁ → Option (α × σ₁)) (key₁ : α → ℤ) + (read₂ : σ₂ → Option (β × σ₂)) (key₂ : β → ℤ) + (report : α → β → τ → τ × Bool) (B fuel₁ fuel₂ : ℕ) : + ℕ → State σ₁ σ₂ τ → State σ₁ σ₂ τ + | 0, s => s + | fuel + 1, s => runAcc read₁ key₁ read₂ key₂ report B fuel₁ fuel₂ fuel + (step read₁ key₁ read₂ key₂ report B fuel₁ fuel₂ s) + +def run (read₁ : σ₁ → Option (α × σ₁)) (key₁ : α → ℤ) + (read₂ : σ₂ → Option (β × σ₂)) (key₂ : β → ℤ) + (report : α → β → τ → τ × Bool) (B fuel₁ fuel₂ controlFuel : ℕ) + (s₁ : σ₁) (s₂ : σ₂) (a : τ) : State σ₁ σ₂ τ := + runAcc read₁ key₁ read₂ key₂ report B fuel₁ fuel₂ controlFuel (start s₁ s₂ a) + +def rank (view₁ : σ₁ → List α) (view₂ : σ₂ → List β) (s : State σ₁ σ₂ τ) : ℕ := + (view₁ s.left).length + (view₂ s.right).length + +def potential (key₁ : α → ℤ) (key₂ : β → ℤ) + (view₁ : σ₁ → List α) (view₂ : σ₂ → List β) (s : State σ₁ σ₂ τ) : ℕ := + MatchPotential.count key₁ key₂ (view₁ s.left) (view₂ s.right) + +def WellFormed (key₁ : α → ℤ) (key₂ : β → ℤ) + (view₁ : σ₁ → List α) (view₂ : σ₂ → List β) (fuel₁ fuel₂ : ℕ) + (s : State σ₁ σ₂ τ) : Prop := + (view₁ s.left).Pairwise (fun x y => key₁ x ≤ key₁ y) ∧ + (view₂ s.right).Pairwise (fun x y => key₂ x ≤ key₂ y) ∧ + (view₁ s.left).length ≤ fuel₁ ∧ (view₂ s.right).length ≤ fuel₂ + +theorem step_done (read₁ : σ₁ → Option (α × σ₁)) (key₁ : α → ℤ) + (read₂ : σ₂ → Option (β × σ₂)) (key₂ : β → ℤ) + (report : α → β → τ → τ × Bool) (B fuel₁ fuel₂ : ℕ) + (s : State σ₁ σ₂ τ) (hs : s.done = true) : + step read₁ key₁ read₂ key₂ report B fuel₁ fuel₂ s = s := by + simp only [step, hs, ite_true] + +theorem runAcc_done (read₁ : σ₁ → Option (α × σ₁)) (key₁ : α → ℤ) + (read₂ : σ₂ → Option (β × σ₂)) (key₂ : β → ℤ) + (report : α → β → τ → τ × Bool) (B fuel₁ fuel₂ fuel : ℕ) + (s : State σ₁ σ₂ τ) (hs : s.done = true) : + runAcc read₁ key₁ read₂ key₂ report B fuel₁ fuel₂ fuel s = s := by + induction fuel with + | zero => rfl + | succ fuel ih => rw [runAcc, step_done _ _ _ _ _ _ _ _ s hs, ih] + +end StreamJoin +end LowSpaceSubsetSum + +end OAI diff --git a/lean/OAI/Combinatorics/LowSpaceSubsetSum/Streams/StreamJoinBounds.lean b/lean/OAI/Combinatorics/LowSpaceSubsetSum/Streams/StreamJoinBounds.lean new file mode 100644 index 0000000000000000000000000000000000000000..b457ddeaa2652e6a9a3d264b978f2b3d1c6cf72e --- /dev/null +++ b/lean/OAI/Combinatorics/LowSpaceSubsetSum/Streams/StreamJoinBounds.lean @@ -0,0 +1,241 @@ +import OAI.Combinatorics.LowSpaceSubsetSum.Streams.StreamGroupFacts + +namespace OAI + +/-! Amortized accounts for the executable global stream join. -/ + +namespace LowSpaceSubsetSum +namespace StreamJoin + +universe u v s t w +variable {α : Type u} {β : Type v} {σ₁ : Type s} {σ₂ : Type t} {τ : Type w} + +def queryAccount (key₁ : α → ℤ) (key₂ : β → ℤ) + (view₁ : σ₁ → List α) (view₂ : σ₂ → List β) (s : State σ₁ σ₂ τ) : ℕ := + s.queries + 6 * rank view₁ view₂ s + potential key₁ key₂ view₁ view₂ s + if s.done then 0 else 2 + +def reportAccount (key₁ : α → ℤ) (key₂ : β → ℤ) + (view₁ : σ₁ → List α) (view₂ : σ₂ → List β) (s : State σ₁ σ₂ τ) : ℕ := + s.reports + potential key₁ key₂ view₁ view₂ s + +def copyAccount (key₁ : α → ℤ) (key₂ : β → ℤ) + (view₁ : σ₁ → List α) (view₂ : σ₂ → List β) (B : ℕ) (s : State σ₁ σ₂ τ) : ℕ := + B * s.copies + 2 * potential key₁ key₂ view₁ view₂ s + +theorem step_accounts (read₁ : σ₁ → Option (α × σ₁)) (key₁ : α → ℤ) + (read₂ : σ₂ → Option (β × σ₂)) (key₂ : β → ℤ) + (report : α → β → τ → τ × Bool) (hreport : ∀ x y a, (report x y a).2 = false) + (view₁ : σ₁ → List α) (hread₁ : RowMerge.IsReader read₁ view₁) + (view₂ : σ₂ → List β) (hread₂ : RowMerge.IsReader read₂ view₂) + (B fuel₁ fuel₂ : ℕ) (st : State σ₁ σ₂ τ) + (hst : WellFormed key₁ key₂ view₁ view₂ fuel₁ fuel₂ st) : + let next := step read₁ key₁ read₂ key₂ report B fuel₁ fuel₂ st + WellFormed key₁ key₂ view₁ view₂ fuel₁ fuel₂ next ∧ + queryAccount key₁ key₂ view₁ view₂ next ≤ queryAccount key₁ key₂ view₁ view₂ st ∧ + reportAccount key₁ key₂ view₁ view₂ next ≤ reportAccount key₁ key₂ view₁ view₂ st ∧ + copyAccount key₁ key₂ view₁ view₂ B next ≤ copyAccount key₁ key₂ view₁ view₂ B st ∧ + (st.done = false → next.done = true ∨ rank view₁ view₂ next < rank view₁ view₂ st) := by + by_cases hd : st.done = true + · simp only [step_done _ _ _ _ _ _ _ _ st hd, le_refl, hd, Bool.true_eq_false, + false_implies, and_true] + exact hst + have hdf : st.done = false := Bool.eq_false_iff.mpr hd + cases hx : read₁ st.left with + | none => + simp only [step, hdf, Bool.false_eq_true, ite_false, hx] + refine ⟨hst, ?_, le_rfl, le_rfl, ?_⟩ + · dsimp only [queryAccount, rank, potential] + simp only [hdf, Bool.false_eq_true, ↓reduceIte] + omega + · simp + | some xp => + rcases xp with ⟨x, left'⟩ + have hv₁ : view₁ st.left = x :: view₁ left' := by simpa only [hx] using hread₁ st.left + cases hy : read₂ st.right with + | none => + simp only [step, hdf, Bool.false_eq_true, ite_false, hx, hy] + refine ⟨hst, ?_, le_rfl, le_rfl, ?_⟩ + · dsimp only [queryAccount, rank, potential] + simp only [hdf, Bool.false_eq_true, ↓reduceIte] + omega + · simp + | some yp => + rcases yp with ⟨y, right'⟩ + have hv₂ : view₂ st.right = y :: view₂ right' := by simpa only [hy] using hread₂ st.right + by_cases hxy : key₁ x < key₂ y + · have hsort₁ := hst.1 + rw [hv₁] at hsort₁ + have hlower₂ := MatchPotential.lower_bound_head key₂ y (view₂ right') + (show (y :: view₂ right').Pairwise (fun x y => key₂ x ≤ key₂ y) from + by simpa only [hv₂] using hst.2.1) + have hp : MatchPotential.count key₁ key₂ (view₁ st.left) (view₂ st.right) = + MatchPotential.count key₁ key₂ (view₁ left') (view₂ st.right) := by + rw [hv₁] + apply MatchPotential.skip_left + intro z hz + exact hxy.trans_le (hlower₂ z (by simpa only [hv₂] using hz)) + simp only [step, hdf, Bool.false_eq_true, ite_false, hx, hy, ite_eq_left hxy] + refine ⟨⟨(List.pairwise_cons.mp hsort₁).2, hst.2.1, ?_, hst.2.2.2⟩, ?_, ?_, ?_, ?_⟩ + · have hc := hst.2.2.1 + rw [hv₁, List.length_cons] at hc + dsimp only + omega + · dsimp only [queryAccount, rank, potential] + simp only [hdf, Bool.false_eq_true, ite_false] + rw [← hp, hv₁, List.length_cons] + omega + · dsimp only [reportAccount, potential] + rw [hp] + · dsimp only [copyAccount, potential] + rw [hp] + · intro _ + right + dsimp only [rank] + rw [hv₁, List.length_cons] + omega + · by_cases hyx : key₂ y < key₁ x + · have hsort₂ := hst.2.1 + rw [hv₂] at hsort₂ + have hlower₁ := MatchPotential.lower_bound_head key₁ x (view₁ left') + (show (x :: view₁ left').Pairwise (fun x y => key₁ x ≤ key₁ y) from + by simpa only [hv₁] using hst.1) + have hp : MatchPotential.count key₁ key₂ (view₁ st.left) (view₂ st.right) = + MatchPotential.count key₁ key₂ (view₁ st.left) (view₂ right') := by + rw [hv₂] + apply MatchPotential.skip_right + intro z hz + exact hyx.trans_le (hlower₁ z (by simpa only [hv₁] using hz)) + simp only [step, hdf, Bool.false_eq_true, ite_false, hx, hy, + ite_eq_right hxy, ite_eq_left hyx] + refine ⟨⟨hst.1, (List.pairwise_cons.mp hsort₂).2, hst.2.2.1, ?_⟩, ?_, ?_, ?_, ?_⟩ + · have hc := hst.2.2.2 + rw [hv₂, List.length_cons] at hc + dsimp only + omega + · dsimp only [queryAccount, rank, potential] + simp only [hdf, Bool.false_eq_true, ite_false] + rw [← hp, hv₂, List.length_cons] + omega + · dsimp only [reportAccount, potential] + rw [hp] + · dsimp only [copyAccount, potential] + rw [hp] + · intro _ + right + dsimp only [rank] + rw [hv₂, List.length_cons] + omega + · have hkey : key₁ x = key₂ y := by omega + let out := TieGroup.run read₁ key₁ read₂ key₂ (key₁ x) report B fuel₁ fuel₂ + st.left st.right st.user + have hg := equal_group_facts read₁ key₁ read₂ key₂ report hreport + view₁ hread₁ view₂ hread₂ B fuel₁ fuel₂ st hst x left' y right' hx hy hkey + rcases hg with ⟨hs₁, hs₂, hl₁, hl₂, hn₁, hn₂, hp⟩ + have hq := TieGroup.query_bound read₁ key₁ read₂ key₂ (key₁ x) report + view₁ hread₁ view₂ hread₂ B fuel₁ fuel₂ st.left st.right st.user + have hr := (TieGroup.run_bounds read₁ key₁ read₂ key₂ (key₁ x) report + view₁ hread₁ view₂ hread₂ B fuel₁ fuel₂ st.left st.right st.user).1 + have hc := TieGroup.copies_charged read₁ key₁ read₂ key₂ (key₁ x) report + view₁ hread₁ view₂ hread₂ B fuel₁ fuel₂ st.left st.right st.user + have hhalt : out.outer.halted = false := TieGroup.halted_false + read₁ key₁ read₂ key₂ (key₁ x) report hreport B fuel₁ fuel₂ st.left st.right st.user + dsimp only [out] at hhalt + simp only [step, hdf, Bool.false_eq_true, ite_false, hx, hy, + ite_eq_right hxy, ite_eq_right hyx] + change WellFormed key₁ key₂ view₁ view₂ fuel₁ fuel₂ + (⟨out.outer.cursor, out.outer.state.last, out.outer.state.user, + st.queries + 2 + out.outer.queries + out.fillQueries + out.outer.state.queries, + st.reports + out.outer.state.reports, + st.copies + (if out.snapshot then 1 else 0) + out.outer.state.restores, + out.outer.halted⟩ : State σ₁ σ₂ τ) ∧ _ + refine ⟨⟨hs₁, hs₂, ?_, ?_⟩, ?_, ?_, ?_, ?_⟩ + · have hcap := hst.2.2.1 + dsimp only [out] + omega + · have hcap := hst.2.2.2 + dsimp only [out] + omega + · dsimp only [queryAccount, rank, potential] + simp only [hhalt, hdf, Bool.false_eq_true, ite_false] + nlinarith + · dsimp only [reportAccount, potential] + omega + · dsimp only [copyAccount, potential] + nlinarith + · intro _ + right + dsimp only [rank] + omega + +theorem runAcc_accounts (read₁ : σ₁ → Option (α × σ₁)) (key₁ : α → ℤ) + (read₂ : σ₂ → Option (β × σ₂)) (key₂ : β → ℤ) + (report : α → β → τ → τ × Bool) (hreport : ∀ x y a, (report x y a).2 = false) + (view₁ : σ₁ → List α) (hread₁ : RowMerge.IsReader read₁ view₁) + (view₂ : σ₂ → List β) (hread₂ : RowMerge.IsReader read₂ view₂) + (B fuel₁ fuel₂ controlFuel : ℕ) (st : State σ₁ σ₂ τ) + (hst : WellFormed key₁ key₂ view₁ view₂ fuel₁ fuel₂ st) : + let out := runAcc read₁ key₁ read₂ key₂ report B fuel₁ fuel₂ controlFuel st + WellFormed key₁ key₂ view₁ view₂ fuel₁ fuel₂ out ∧ + queryAccount key₁ key₂ view₁ view₂ out ≤ queryAccount key₁ key₂ view₁ view₂ st ∧ + reportAccount key₁ key₂ view₁ view₂ out ≤ reportAccount key₁ key₂ view₁ view₂ st ∧ + copyAccount key₁ key₂ view₁ view₂ B out ≤ copyAccount key₁ key₂ view₁ view₂ B st := by + induction controlFuel generalizing st with + | zero => exact ⟨hst, le_rfl, le_rfl, le_rfl⟩ + | succ controlFuel ih => + have hs := step_accounts read₁ key₁ read₂ key₂ report hreport view₁ hread₁ view₂ hread₂ + B fuel₁ fuel₂ st hst + have hi := ih _ hs.1 + exact ⟨hi.1, hi.2.1.trans hs.2.1, hi.2.2.1.trans hs.2.2.1, + hi.2.2.2.trans hs.2.2.2.1⟩ + +theorem runAcc_terminates (read₁ : σ₁ → Option (α × σ₁)) (key₁ : α → ℤ) + (read₂ : σ₂ → Option (β × σ₂)) (key₂ : β → ℤ) + (report : α → β → τ → τ × Bool) (hreport : ∀ x y a, (report x y a).2 = false) + (view₁ : σ₁ → List α) (hread₁ : RowMerge.IsReader read₁ view₁) + (view₂ : σ₂ → List β) (hread₂ : RowMerge.IsReader read₂ view₂) + (B fuel₁ fuel₂ controlFuel : ℕ) (st : State σ₁ σ₂ τ) + (hst : WellFormed key₁ key₂ view₁ view₂ fuel₁ fuel₂ st) + (hfuel : rank view₁ view₂ st < controlFuel) : + (runAcc read₁ key₁ read₂ key₂ report B fuel₁ fuel₂ controlFuel st).done = true := by + induction controlFuel generalizing st with + | zero => omega + | succ controlFuel ih => + by_cases hd : st.done = true + · rw [runAcc_done _ _ _ _ _ _ _ _ _ st hd] + exact hd + have hs := step_accounts read₁ key₁ read₂ key₂ report hreport view₁ hread₁ view₂ hread₂ + B fuel₁ fuel₂ st hst + rcases hs.2.2.2.2 (Bool.eq_false_iff.mpr hd) with hdone | hprogress + · rw [runAcc, runAcc_done _ _ _ _ _ _ _ _ _ _ hdone] + exact hdone + · rw [runAcc] + exact ih _ hs.1 (by omega) + +theorem run_bounds (read₁ : σ₁ → Option (α × σ₁)) (key₁ : α → ℤ) + (read₂ : σ₂ → Option (β × σ₂)) (key₂ : β → ℤ) + (report : α → β → τ → τ × Bool) (hreport : ∀ x y a, (report x y a).2 = false) + (view₁ : σ₁ → List α) (hread₁ : RowMerge.IsReader read₁ view₁) + (view₂ : σ₂ → List β) (hread₂ : RowMerge.IsReader read₂ view₂) + (B fuel₁ fuel₂ controlFuel : ℕ) (s₁ : σ₁) (s₂ : σ₂) (a : τ) + (hsort₁ : (view₁ s₁).Pairwise (fun x y => key₁ x ≤ key₁ y)) + (hsort₂ : (view₂ s₂).Pairwise (fun x y => key₂ x ≤ key₂ y)) + (hcap₁ : (view₁ s₁).length ≤ fuel₁) (hcap₂ : (view₂ s₂).length ≤ fuel₂) : + let out := run read₁ key₁ read₂ key₂ report B fuel₁ fuel₂ controlFuel s₁ s₂ a + out.queries ≤ 6 * ((view₁ s₁).length + (view₂ s₂).length) + + MatchPotential.count key₁ key₂ (view₁ s₁) (view₂ s₂) + 2 ∧ + out.reports ≤ MatchPotential.count key₁ key₂ (view₁ s₁) (view₂ s₂) ∧ + B * out.copies ≤ 2 * MatchPotential.count key₁ key₂ (view₁ s₁) (view₂ s₂) := by + have h := runAcc_accounts read₁ key₁ read₂ key₂ report hreport view₁ hread₁ view₂ hread₂ + B fuel₁ fuel₂ controlFuel (start s₁ s₂ a) ⟨hsort₁, hsort₂, hcap₁, hcap₂⟩ + have hq := h.2.1 + have hr := h.2.2.1 + have hc := h.2.2.2 + dsimp only [queryAccount, reportAccount, copyAccount, rank, potential, start] at hq hr hc + simp only [Bool.false_eq_true, ite_false, Nat.zero_add, Nat.mul_zero] at hq hr hc + dsimp only [run, start] + omega + +end StreamJoin +end LowSpaceSubsetSum + +end OAI diff --git a/lean/OAI/Combinatorics/LowSpaceSubsetSum/Streams/StreamJoinCorrectness.lean b/lean/OAI/Combinatorics/LowSpaceSubsetSum/Streams/StreamJoinCorrectness.lean new file mode 100644 index 0000000000000000000000000000000000000000..2a684d5d5185aa1c5a64317443fc64c91a3d7c13 --- /dev/null +++ b/lean/OAI/Combinatorics/LowSpaceSubsetSum/Streams/StreamJoinCorrectness.lean @@ -0,0 +1,203 @@ +import OAI.Combinatorics.LowSpaceSubsetSum.Streams.StreamJoinBounds +import OAI.Combinatorics.LowSpaceSubsetSum.Counting.MatchFold + +namespace OAI + +/-! Exact callback semantics of the finite-state global join. -/ + +namespace LowSpaceSubsetSum +namespace StreamJoin + +universe u v s t w +variable {α : Type u} {β : Type v} {σ₁ : Type s} {σ₂ : Type t} {τ : Type w} + +def semanticAccount (key₁ : α → ℤ) (key₂ : β → ℤ) + (report : α → β → τ → τ × Bool) (view₁ : σ₁ → List α) (view₂ : σ₂ → List β) + (st : State σ₁ σ₂ τ) : τ := MatchFold.run key₁ key₂ report (view₁ st.left) (view₂ st.right) st.user + +theorem step_semantics (read₁ : σ₁ → Option (α × σ₁)) (key₁ : α → ℤ) + (read₂ : σ₂ → Option (β × σ₂)) (key₂ : β → ℤ) + (report : α → β → τ → τ × Bool) (hreport : ∀ x y a, (report x y a).2 = false) + (view₁ : σ₁ → List α) (hread₁ : RowMerge.IsReader read₁ view₁) + (view₂ : σ₂ → List β) (hread₂ : RowMerge.IsReader read₂ view₂) + (B fuel₁ fuel₂ : ℕ) (st : State σ₁ σ₂ τ) + (hst : WellFormed key₁ key₂ view₁ view₂ fuel₁ fuel₂ st) : + semanticAccount key₁ key₂ report view₁ view₂ + (step read₁ key₁ read₂ key₂ report B fuel₁ fuel₂ st) = + semanticAccount key₁ key₂ report view₁ view₂ st := by + by_cases hd : st.done = true + · rw [step_done _ _ _ _ _ _ _ _ st hd] + have hdf := Bool.eq_false_iff.mpr hd + cases hx : read₁ st.left with + | none => + have hv : view₁ st.left = [] := by simpa only [hx] using hread₁ st.left + simp only [step, hdf, Bool.false_eq_true, ite_false, hx, semanticAccount, hv, MatchFold.run] + | some xp => + rcases xp with ⟨x, left'⟩ + have hv₁ : view₁ st.left = x :: view₁ left' := by simpa only [hx] using hread₁ st.left + cases hy : read₂ st.right with + | none => + have hv : view₂ st.right = [] := by simpa only [hy] using hread₂ st.right + simp only [step, hdf, Bool.false_eq_true, ite_false, hx, hy, semanticAccount, hv, + MatchFold.nil_right] + | some yp => + rcases yp with ⟨y, right'⟩ + have hv₂ : view₂ st.right = y :: view₂ right' := by simpa only [hy] using hread₂ st.right + by_cases hxy : key₁ x < key₂ y + · have hlower₂ : ∀ z ∈ view₂ st.right, key₂ y ≤ key₂ z := by + rw [hv₂] + exact MatchPotential.lower_bound_head key₂ y _ (by simpa only [hv₂] using hst.2.1) + simp only [step, hdf, Bool.false_eq_true, ite_false, hx, hy, ite_eq_left hxy, semanticAccount] + rw [hv₁] + exact (MatchFold.skip_left key₁ key₂ report x _ _ st.user + (fun z hz => hxy.trans_le (hlower₂ z hz))).symm + · by_cases hyx : key₂ y < key₁ x + · have hlower₁ : ∀ z ∈ view₁ st.left, key₁ x ≤ key₁ z := by + rw [hv₁] + exact MatchPotential.lower_bound_head key₁ x _ (by simpa only [hv₁] using hst.1) + simp only [step, hdf, Bool.false_eq_true, ite_false, hx, hy, + ite_eq_right hxy, ite_eq_left hyx, semanticAccount] + rw [hv₂] + exact (MatchFold.skip_right key₁ key₂ report _ y _ st.user + (fun z hz => hyx.trans_le (hlower₁ z hz))).symm + · have hkey : key₁ x = key₂ y := by omega + let out := TieGroup.run read₁ key₁ read₂ key₂ (key₁ x) report B fuel₁ fuel₂ + st.left st.right st.user + let G₁ := TieBuffer.groupView key₁ (key₁ x) view₁ st.left + let G₂ := TieBuffer.groupView key₂ (key₁ x) view₂ st.right + have hg₁ : G₁ ≠ [] := by simp [G₁, TieBuffer.groupView, hv₁] + have hcap₁ : G₁.length ≤ fuel₁ := + (List.takeWhile_sublist _).length_le.trans hst.2.2.1 + have hcap₂ : G₂.length ≤ fuel₂ := + (List.takeWhile_sublist _).length_le.trans hst.2.2.2 + have hviews := TieGroup.views_complete read₁ key₁ read₂ key₂ (key₁ x) report hreport + view₁ hread₁ view₂ hread₂ B fuel₁ fuel₂ st.left st.right st.user hcap₁ hcap₂ hg₁ + change view₁ st.left = G₁ ++ view₁ out.outer.cursor ∧ + view₂ st.right = G₂ ++ view₂ out.outer.state.last at hviews + have hlower₁ : ∀ z ∈ view₁ st.left, key₁ x ≤ key₁ z := by + rw [hv₁] + exact MatchPotential.lower_bound_head key₁ x _ (by simpa only [hv₁] using hst.1) + have hlower₂ : ∀ z ∈ view₂ st.right, key₁ x ≤ key₂ z := by + rw [hkey, hv₂] + exact MatchPotential.lower_bound_head key₂ y _ (by simpa only [hv₂] using hst.2.1) + have hr₁ := MatchPotential.remaining_avoids key₁ (key₁ x) _ _ hviews.1 hst.1 hlower₁ + have hr₂ := MatchPotential.remaining_avoids key₂ (key₁ x) _ _ hviews.2 hst.2.1 hlower₂ + have hG₁ : ∀ z ∈ G₁, key₁ z = key₁ x := by + intro z hz + exact of_decide_eq_true (List.mem_takeWhile_imp (p := fun z => decide (key₁ z = key₁ x)) hz) + have hG₂ : ∀ z ∈ G₂, key₂ z = key₁ x := by + intro z hz + exact of_decide_eq_true (List.mem_takeWhile_imp (p := fun z => decide (key₂ z = key₁ x)) hz) + have hsplit := MatchFold.split_groups key₁ key₂ report (key₁ x) G₁ + (view₁ out.outer.cursor) G₂ (view₂ out.outer.state.last) st.user hG₁ hG₂ hr₁ hr₂ + rw [← hviews.1, ← hviews.2] at hsplit + have hstate := TieGroup.state_complete read₁ key₁ read₂ key₂ (key₁ x) report hreport + view₁ hread₁ view₂ hread₂ B fuel₁ fuel₂ st.left st.right st.user hcap₁ hcap₂ + rw [← hstate] at hsplit + simp only [step, hdf, Bool.false_eq_true, ite_false, hx, hy, + ite_eq_right hxy, ite_eq_right hyx, semanticAccount] + exact hsplit.symm + +theorem runAcc_semantics (read₁ : σ₁ → Option (α × σ₁)) (key₁ : α → ℤ) + (read₂ : σ₂ → Option (β × σ₂)) (key₂ : β → ℤ) + (report : α → β → τ → τ × Bool) (hreport : ∀ x y a, (report x y a).2 = false) + (view₁ : σ₁ → List α) (hread₁ : RowMerge.IsReader read₁ view₁) + (view₂ : σ₂ → List β) (hread₂ : RowMerge.IsReader read₂ view₂) + (B fuel₁ fuel₂ controlFuel : ℕ) (st : State σ₁ σ₂ τ) + (hst : WellFormed key₁ key₂ view₁ view₂ fuel₁ fuel₂ st) : + semanticAccount key₁ key₂ report view₁ view₂ + (runAcc read₁ key₁ read₂ key₂ report B fuel₁ fuel₂ controlFuel st) = + semanticAccount key₁ key₂ report view₁ view₂ st := by + induction controlFuel generalizing st with + | zero => rfl + | succ controlFuel ih => + rw [runAcc, ih _ (step_accounts read₁ key₁ read₂ key₂ report hreport view₁ hread₁ + view₂ hread₂ B fuel₁ fuel₂ st hst).1] + exact step_semantics read₁ key₁ read₂ key₂ report hreport view₁ hread₁ view₂ hread₂ B fuel₁ fuel₂ st hst + +def DoneEmpty (view₁ : σ₁ → List α) (view₂ : σ₂ → List β) (st : State σ₁ σ₂ τ) : Prop := + st.done = true → view₁ st.left = [] ∨ view₂ st.right = [] + +theorem step_doneEmpty (read₁ : σ₁ → Option (α × σ₁)) (key₁ : α → ℤ) + (read₂ : σ₂ → Option (β × σ₂)) (key₂ : β → ℤ) + (report : α → β → τ → τ × Bool) (hreport : ∀ x y a, (report x y a).2 = false) + (view₁ : σ₁ → List α) (hread₁ : RowMerge.IsReader read₁ view₁) + (view₂ : σ₂ → List β) (hread₂ : RowMerge.IsReader read₂ view₂) + (B fuel₁ fuel₂ : ℕ) (st : State σ₁ σ₂ τ) (hst : DoneEmpty view₁ view₂ st) : + DoneEmpty view₁ view₂ (step read₁ key₁ read₂ key₂ report B fuel₁ fuel₂ st) := by + by_cases hd : st.done = true + · rw [step_done _ _ _ _ _ _ _ _ st hd] + exact hst + have hdf := Bool.eq_false_iff.mpr hd + cases hx : read₁ st.left with + | none => + have hv : view₁ st.left = [] := by simpa only [hx] using hread₁ st.left + simp only [DoneEmpty, step, hdf, Bool.false_eq_true, ite_false, hx] + exact fun _ => Or.inl hv + | some xp => + rcases xp with ⟨x, left'⟩ + cases hy : read₂ st.right with + | none => + have hv : view₂ st.right = [] := by simpa only [hy] using hread₂ st.right + simp only [DoneEmpty, step, hdf, Bool.false_eq_true, ite_false, hx, hy] + exact fun _ => Or.inr hv + | some yp => + rcases yp with ⟨y, right'⟩ + by_cases hxy : key₁ x < key₂ y + · simp only [DoneEmpty, step, hdf, Bool.false_eq_true, ite_false, hx, hy, ite_eq_left hxy, + false_implies] + · by_cases hyx : key₂ y < key₁ x + · simp only [DoneEmpty, step, hdf, Bool.false_eq_true, ite_false, hx, hy, + ite_eq_right hxy, ite_eq_left hyx, false_implies] + · have hhalt := TieGroup.halted_false read₁ key₁ read₂ key₂ (key₁ x) report hreport + B fuel₁ fuel₂ st.left st.right st.user + simp only [DoneEmpty, step, hdf, Bool.false_eq_true, ite_false, hx, hy, + ite_eq_right hxy, ite_eq_right hyx, hhalt, false_implies] + +theorem runAcc_doneEmpty (read₁ : σ₁ → Option (α × σ₁)) (key₁ : α → ℤ) + (read₂ : σ₂ → Option (β × σ₂)) (key₂ : β → ℤ) + (report : α → β → τ → τ × Bool) (hreport : ∀ x y a, (report x y a).2 = false) + (view₁ : σ₁ → List α) (hread₁ : RowMerge.IsReader read₁ view₁) + (view₂ : σ₂ → List β) (hread₂ : RowMerge.IsReader read₂ view₂) + (B fuel₁ fuel₂ controlFuel : ℕ) (st : State σ₁ σ₂ τ) (hst : DoneEmpty view₁ view₂ st) : + DoneEmpty view₁ view₂ (runAcc read₁ key₁ read₂ key₂ report B fuel₁ fuel₂ controlFuel st) := by + induction controlFuel generalizing st with + | zero => exact hst + | succ controlFuel ih => + exact ih _ (step_doneEmpty read₁ key₁ read₂ key₂ report hreport + view₁ hread₁ view₂ hread₂ B fuel₁ fuel₂ st hst) + +/-- Enough control fuel gives the exact Cartesian-match fold. Occurrences +with identical fields are still processed separately in this equation. -/ +theorem run_complete (read₁ : σ₁ → Option (α × σ₁)) (key₁ : α → ℤ) + (read₂ : σ₂ → Option (β × σ₂)) (key₂ : β → ℤ) + (report : α → β → τ → τ × Bool) (hreport : ∀ x y a, (report x y a).2 = false) + (view₁ : σ₁ → List α) (hread₁ : RowMerge.IsReader read₁ view₁) + (view₂ : σ₂ → List β) (hread₂ : RowMerge.IsReader read₂ view₂) + (B fuel₁ fuel₂ controlFuel : ℕ) (s₁ : σ₁) (s₂ : σ₂) (a : τ) + (hsort₁ : (view₁ s₁).Pairwise (fun x y => key₁ x ≤ key₁ y)) + (hsort₂ : (view₂ s₂).Pairwise (fun x y => key₂ x ≤ key₂ y)) + (hcap₁ : (view₁ s₁).length ≤ fuel₁) (hcap₂ : (view₂ s₂).length ≤ fuel₂) + (hfuel : (view₁ s₁).length + (view₂ s₂).length < controlFuel) : + (run read₁ key₁ read₂ key₂ report B fuel₁ fuel₂ controlFuel s₁ s₂ a).user = + MatchFold.run key₁ key₂ report (view₁ s₁) (view₂ s₂) a := by + have hw : WellFormed key₁ key₂ view₁ view₂ fuel₁ fuel₂ (start s₁ s₂ a) := + ⟨hsort₁, hsort₂, hcap₁, hcap₂⟩ + have ht := runAcc_terminates read₁ key₁ read₂ key₂ report hreport view₁ hread₁ view₂ hread₂ + B fuel₁ fuel₂ controlFuel (start s₁ s₂ a) hw hfuel + have he := runAcc_doneEmpty read₁ key₁ read₂ key₂ report hreport view₁ hread₁ view₂ hread₂ + B fuel₁ fuel₂ controlFuel (start s₁ s₂ a) (by simp [DoneEmpty, start]) + have hs := runAcc_semantics read₁ key₁ read₂ key₂ report hreport view₁ hread₁ view₂ hread₂ + B fuel₁ fuel₂ controlFuel (start s₁ s₂ a) hw + rcases he ht with hleft | hright + · dsimp only [semanticAccount] at hs + rw [hleft] at hs + exact hs + · dsimp only [semanticAccount] at hs + rw [hright, MatchFold.nil_right] at hs + exact hs + +end StreamJoin +end LowSpaceSubsetSum + +end OAI diff --git a/lean/OAI/Combinatorics/LowSpaceSubsetSum/Streams/StreamPrimitiveWork.lean b/lean/OAI/Combinatorics/LowSpaceSubsetSum/Streams/StreamPrimitiveWork.lean new file mode 100644 index 0000000000000000000000000000000000000000..b742d2184c010d37c8029d7c5616c7f50afeb6ab --- /dev/null +++ b/lean/OAI/Combinatorics/LowSpaceSubsetSum/Streams/StreamPrimitiveWork.lean @@ -0,0 +1,94 @@ +import OAI.Combinatorics.LowSpaceSubsetSum.Streams.BinaryPivot +import OAI.Combinatorics.LowSpaceSubsetSum.Streams.CountedSort +import OAI.Combinatorics.LowSpaceSubsetSum.Representation.RepresentationLeafSpace + +namespace OAI + +/-! # Counted binary searches and residue sorting + +The counted routines follow the same branches as the executable +search and sort. Their first components agree exactly with those routines. +The counters charge predicate calls and merge/split operations, respectively; +word arithmetic and mask access still require separate compilation charges. +-/ + +namespace LowSpaceSubsetSum + +namespace BinaryPivot + +def counted {n : ℕ} (p : Fin n → Bool) : ℕ → Cut n → Cut n × ℕ + | 0, c => (c, 0) + | k + 1, c => + let queried := if c.lo < c.hi then 1 else 0 + let rest := counted p k (step p c) + (rest.1, queried + rest.2) + +theorem counted_value {n : ℕ} (p : Fin n → Bool) (k : ℕ) (c : Cut n) : + (counted p k c).1 = (step p)^[k] c := by + induction k generalizing c with + | zero => rfl + | succ k ih => simpa only [counted, Function.iterate_succ_apply] using ih (step p c) + +theorem counted_queries {n : ℕ} (p : Fin n → Bool) (k : ℕ) (c : Cut n) : + (counted p k c).2 ≤ k := by + induction k generalizing c with + | zero => rfl + | succ k ih => + have h := ih (step p c) + simp only [counted] + split <;> omega + +def countedSearch {n : ℕ} (p : Fin n → Bool) (k : ℕ) : Cut n × ℕ := + counted p k (initial n) + +theorem countedSearch_value {n : ℕ} (p : Fin n → Bool) (k : ℕ) : + (countedSearch p k).1 = search p k := counted_value p k (initial n) + +theorem countedSearch_queries {n : ℕ} (p : Fin n → Bool) (k : ℕ) : + (countedSearch p k).2 ≤ k := counted_queries p k (initial n) + +end BinaryPivot + +namespace ResidueSort + +variable {α : Type*} + +def counted (xs : Array α) (w : α → ℤ) (p P : ℤ) : Array α × ℕ := + let r := CountedSort.sort (fun x y => decide (relation w p P x y)) xs.toList + (r.1.toArray, r.2) + +theorem counted_value (xs : Array α) (w : α → ℤ) (p P : ℤ) : + (counted xs w p P).1 = sort xs w p P := by + simp only [counted, CountedSort.sort_value, sort] + +theorem counted_work (xs : Array α) (w : α → ℤ) (p P : ℤ) (n : ℕ) + (hn : xs.size ≤ 2 ^ n) : + (counted xs w p P).2 ≤ (6 * n + 1) * xs.size + 1 := by + exact CountedSort.sort_steps_of_index_bits _ xs.toList n (by simpa using hn) + +end ResidueSort + +namespace RepresentationPairData + +variable {n : ℕ} (D : RepresentationPairData n) + +theorem counted_sort_value : + (ResidueSort.counted D.rightArray D.wl D.lowModulus D.modulus).1 = D.storedRight := + ResidueSort.counted_value _ _ _ _ + +theorem counted_sort_work (hR : D.rightArray.size ≤ 2 ^ n) : + (ResidueSort.counted D.rightArray D.wl D.lowModulus D.modulus).2 ≤ + (6 * n + 1) * D.right.occurrences.card + 1 := by + exact (ResidueSort.counted_work _ _ _ _ n hR).trans + (Nat.add_le_add_right (Nat.mul_le_mul_left _ D.rightArray_size_le) 1) + +theorem any_state_comparisons (hL : D.leftArray.size ≤ 2 ^ n) (s : D.State) : + MergedReader.advanceComparisons + (FilteredStream.key D.wl D.wl D.modulus D.mode) + (FilteredStream.view D.storedRight) s ≤ n := + (D.reader_comparisons_le s).trans (Nat.clog_le_of_le_pow hL) + +end RepresentationPairData +end LowSpaceSubsetSum + +end OAI diff --git a/lean/OAI/Combinatorics/LowSpaceSubsetSum/Streams/StreamWitness.lean b/lean/OAI/Combinatorics/LowSpaceSubsetSum/Streams/StreamWitness.lean new file mode 100644 index 0000000000000000000000000000000000000000..415a65acefb2f8573f15e58e71d5f963ac784072 --- /dev/null +++ b/lean/OAI/Combinatorics/LowSpaceSubsetSum/Streams/StreamWitness.lean @@ -0,0 +1,88 @@ +import OAI.Combinatorics.LowSpaceSubsetSum.Streams.StreamJoinCorrectness + +namespace OAI + +/-! A concrete Boolean match collector for the finite-state stream join. -/ + +namespace LowSpaceSubsetSum +namespace StreamWitness + +universe u v +variable {α : Type u} {β : Type v} + +def remember (hit : α → β → Bool) (x : α) (y : β) (a : Bool) : Bool × Bool := + (a || hit x y, false) + +theorem foldl_remember (hit : α → β → Bool) (x : α) (ys : List β) (a : Bool) : + ys.foldl (fun a y => (remember hit x y a).1) a = true ↔ + a = true ∨ ∃ y ∈ ys, hit x y = true := by + induction ys generalizing a with + | nil => simp + | cons y ys ih => + rw [List.foldl_cons, ih] + simp only [remember, Bool.or_eq_true, List.mem_cons] + aesop + +theorem matchFold_iff (key₁ : α → ℤ) (key₂ : β → ℤ) (hit : α → β → Bool) + (xs : List α) (ys : List β) (a : Bool) : + MatchFold.run key₁ key₂ (remember hit) xs ys a = true ↔ + a = true ∨ ∃ x ∈ xs, ∃ y ∈ ys, key₁ x = key₂ y ∧ hit x y = true := by + induction xs generalizing a with + | nil => simp [MatchFold.run] + | cons x xs ih => + rw [MatchFold.run, ih, foldl_remember] + simp only [List.mem_cons, List.mem_filter, decide_eq_true_eq] + aesop + +theorem matchFold_true (key₁ : α → ℤ) (key₂ : β → ℤ) (hit : α → β → Bool) + (xs : List α) (ys : List β) : + MatchFold.run key₁ key₂ (remember hit) xs ys true = true := + (matchFold_iff key₁ key₂ hit xs ys true).mpr (Or.inl rfl) + +/-- The actual finite-state join finds exactly the matching occurrences +accepted by its pair predicate. The callback retains one Boolean word. -/ +theorem run_iff {σ₁ σ₂ : Type*} + (read₁ : σ₁ → Option (α × σ₁)) (key₁ : α → ℤ) + (read₂ : σ₂ → Option (β × σ₂)) (key₂ : β → ℤ) (hit : α → β → Bool) + (view₁ : σ₁ → List α) (hread₁ : RowMerge.IsReader read₁ view₁) + (view₂ : σ₂ → List β) (hread₂ : RowMerge.IsReader read₂ view₂) + (B fuel₁ fuel₂ controlFuel : ℕ) (s₁ : σ₁) (s₂ : σ₂) + (hsort₁ : (view₁ s₁).Pairwise (fun x y => key₁ x ≤ key₁ y)) + (hsort₂ : (view₂ s₂).Pairwise (fun x y => key₂ x ≤ key₂ y)) + (hcap₁ : (view₁ s₁).length ≤ fuel₁) (hcap₂ : (view₂ s₂).length ≤ fuel₂) + (hfuel : (view₁ s₁).length + (view₂ s₂).length < controlFuel) : + (StreamJoin.run read₁ key₁ read₂ key₂ (remember hit) B fuel₁ fuel₂ controlFuel s₁ s₂ false).user = true ↔ + ∃ x ∈ view₁ s₁, ∃ y ∈ view₂ s₂, key₁ x = key₂ y ∧ hit x y = true := by + rw [StreamJoin.run_complete read₁ key₁ read₂ key₂ (remember hit) (fun _ _ _ => rfl) + view₁ hread₁ view₂ hread₂ B fuel₁ fuel₂ controlFuel s₁ s₂ false + hsort₁ hsort₂ hcap₁ hcap₂ hfuel, matchFold_iff] + simp + +/-- An arbitrary stopped control prefix also has one-sided soundness. -/ +theorem stopped_sound {σ₁ σ₂ : Type*} + (read₁ : σ₁ → Option (α × σ₁)) (key₁ : α → ℤ) + (read₂ : σ₂ → Option (β × σ₂)) (key₂ : β → ℤ) (hit : α → β → Bool) + (view₁ : σ₁ → List α) (hread₁ : RowMerge.IsReader read₁ view₁) + (view₂ : σ₂ → List β) (hread₂ : RowMerge.IsReader read₂ view₂) + (B fuel₁ fuel₂ controlFuel : ℕ) (s₁ : σ₁) (s₂ : σ₂) + (hsort₁ : (view₁ s₁).Pairwise (fun x y => key₁ x ≤ key₁ y)) + (hsort₂ : (view₂ s₂).Pairwise (fun x y => key₂ x ≤ key₂ y)) + (hcap₁ : (view₁ s₁).length ≤ fuel₁) (hcap₂ : (view₂ s₂).length ≤ fuel₂) + (hyes : (StreamJoin.run read₁ key₁ read₂ key₂ (remember hit) B fuel₁ fuel₂ + controlFuel s₁ s₂ false).user = true) : + ∃ x ∈ view₁ s₁, ∃ y ∈ view₂ s₂, key₁ x = key₂ y ∧ hit x y = true := by + let out := StreamJoin.run read₁ key₁ read₂ key₂ (remember hit) B fuel₁ fuel₂ controlFuel s₁ s₂ false + have hs := StreamJoin.runAcc_semantics read₁ key₁ read₂ key₂ (remember hit) (fun _ _ _ => rfl) + view₁ hread₁ view₂ hread₂ B fuel₁ fuel₂ controlFuel (StreamJoin.start s₁ s₂ false) + ⟨hsort₁, hsort₂, hcap₁, hcap₂⟩ + change MatchFold.run key₁ key₂ (remember hit) (view₁ out.left) (view₂ out.right) out.user = + MatchFold.run key₁ key₂ (remember hit) (view₁ s₁) (view₂ s₂) false at hs + have ht : MatchFold.run key₁ key₂ (remember hit) (view₁ s₁) (view₂ s₂) false = true := by + rw [← hs, hyes] + exact matchFold_true key₁ key₂ hit _ _ + exact (matchFold_iff key₁ key₂ hit _ _ false).mp ht |>.resolve_left (by decide) + +end StreamWitness +end LowSpaceSubsetSum + +end OAI diff --git a/lean/OAI/Combinatorics/LowSpaceSubsetSum/Streams/SumReader.lean b/lean/OAI/Combinatorics/LowSpaceSubsetSum/Streams/SumReader.lean new file mode 100644 index 0000000000000000000000000000000000000000..9c0d5585cabf2af40fe14834379ad327c792042b --- /dev/null +++ b/lean/OAI/Combinatorics/LowSpaceSubsetSum/Streams/SumReader.lean @@ -0,0 +1,131 @@ +import OAI.Combinatorics.LowSpaceSubsetSum.Streams.PaddedRows +import OAI.Combinatorics.LowSpaceSubsetSum.Streams.DistinctStreamCount +import OAI.Combinatorics.LowSpaceSubsetSum.Compression.CompressionDictionary + +namespace OAI + +/-! # Counting a mixer through a tournament of ordinary sum rows + +Only the two half-mixer arrays and a tournament of constant-size cursors +are stored. The output lists in the proofs are views, not runtime fields. +Sorting and counting use integer sums and require no modulus or real oracle. +-/ + +namespace LowSpaceSubsetSum.SumReader + +open scoped BigOperators + +structure Row where + left : ℤ + position : ℕ + +def read (ys : Array ℤ) (s : Row) : Option ((ℤ × ℤ) × Row) := + if h : s.position < ys.size then + some ((s.left, ys[s.position]), ⟨s.left, s.position + 1⟩) + else none + +def view (ys : Array ℤ) (s : Row) : List (ℤ × ℤ) := + (ys.toList.drop s.position).map (fun y => (s.left, y)) + +theorem reader (ys : Array ℤ) : RowMerge.IsReader (read ys) (view ys) := by + intro s + by_cases h : s.position < ys.size + · have hlist : s.position < ys.toList.length := by simpa using h + simp only [read, dite_eq_left h, view] + rw [List.drop_eq_getElem_cons hlist, List.map_cons] + rfl + · have he : ys.toList.drop s.position = [] := List.drop_eq_nil_iff.mpr (by simpa using Nat.le_of_not_gt h) + simp [read, h, view, he] + +def key (p : ℤ × ℤ) : ℤ := p.1 + p.2 + +def rows (xs : Array ℤ) : Array Row := xs.map (fun x => ⟨x, 0⟩) + +theorem row_sorted (ys : Array ℤ) (hs : ys.toList.Pairwise (· ≤ ·)) (s : Row) : + (view ys s).Pairwise (fun x y => key x ≤ key y) := by + rw [view, List.pairwise_map] + exact (hs.sublist (List.drop_sublist s.position ys.toList)).imp + (fun h => by dsimp only [key]; omega) + +abbrev State (xs ys : Array ℤ) := + MergedReader.State key (PaddedRows.view (view ys)) (Nat.clog 2 xs.size) + +def start (xs ys : Array ℤ) (hs : ys.toList.Pairwise (· ≤ ·)) : State xs ys := + MergedReader.start key (PaddedRows.next (read ys)) (PaddedRows.view (view ys)) + (PaddedRows.reader _ _ (reader ys)) + (PaddedRows.rows (rows xs) (Nat.clog 2 xs.size)) + (PaddedRows.rows_sorted _ _ _ key (fun s _ => row_sorted ys hs s)) + +def next (xs ys : Array ℤ) : State xs ys → Option ((ℤ × ℤ) × State xs ys) := + MergedReader.next key (PaddedRows.next (read ys)) (PaddedRows.view (view ys)) + (PaddedRows.reader _ _ (reader ys)) + +def output (xs ys : Array ℤ) : State xs ys → List (ℤ × ℤ) := + MergedReader.output key (PaddedRows.next (read ys)) (PaddedRows.view (view ys)) + +theorem next_law (xs ys : Array ℤ) : RowMerge.IsReader (next xs ys) (output xs ys) := + MergedReader.reader _ _ _ (PaddedRows.reader _ _ (reader ys)) + +theorem output_sorted (xs ys : Array ℤ) (s : State xs ys) : + ((output xs ys s).map key).Pairwise (· ≤ ·) := by + rw [List.pairwise_map] + exact MergedReader.output_sorted _ _ _ (PaddedRows.reader _ _ (reader ys)) s + +theorem start_bag (xs ys : Array ℤ) (hs : ys.toList.Pairwise (· ≤ ·)) : + (output xs ys (start xs ys hs) : Multiset (ℤ × ℤ)) = + ∑ i : Fin xs.size, ((ys.toList.map (fun y => (xs[i.val], y))) : Multiset (ℤ × ℤ)) := by + rw [output, start, MergedReader.start_output_bag] + calc + _ = ∑ i : Fin (rows xs).size, (view ys (rows xs)[i.val] : Multiset (ℤ × ℤ)) := + PaddedRows.row_bag (rows xs) (Nat.clog 2 xs.size) + (by simpa [rows] using Nat.le_pow_clog (by decide : 1 < 2) xs.size) (view ys) + _ = _ := by + apply Fintype.sum_equiv (finCongr (show (rows xs).size = xs.size by simp [rows])) + intro i + simp only [rows, Array.getElem_map, view, List.drop_zero] + rfl + +theorem output_mem (xs ys : Array ℤ) (hs : ys.toList.Pairwise (· ≤ ·)) (p : ℤ × ℤ) : + p ∈ output xs ys (start xs ys hs) ↔ p.1 ∈ xs.toList ∧ p.2 ∈ ys.toList := by + change p ∈ (output xs ys (start xs ys hs) : Multiset (ℤ × ℤ)) ↔ _ + rw [start_bag, Multiset.mem_sum] + simp only [Finset.mem_univ, true_and, Multiset.mem_coe, List.mem_map] + constructor + · rintro ⟨i, y, hy, he⟩ + obtain rfl := he + exact ⟨List.mem_iff_getElem.mpr ⟨i.val, by simpa only [Array.length_toList] using i.isLt, by simp⟩, hy⟩ + · rintro ⟨hx, hy⟩ + obtain ⟨i, hi, he⟩ := List.mem_iff_getElem.mp hx + refine ⟨⟨i, by simpa using hi⟩, p.2, hy, ?_⟩ + simpa using congrArg (fun x => (x, p.2)) he + +theorem output_length (xs ys : Array ℤ) (hs : ys.toList.Pairwise (· ≤ ·)) : + (output xs ys (start xs ys hs)).length = xs.size * ys.size := by + have h := congrArg Multiset.card (start_bag xs ys hs) + simpa only [Multiset.coe_card, Multiset.card_sum, List.length_map, + Array.length_toList, Finset.sum_const, Finset.card_univ, Fintype.card_fin, smul_eq_mul] using h + +def count (xs ys : Array ℤ) (hs : ys.toList.Pairwise (· ≤ ·)) : ℕ × ℕ := + DistinctStreamCount.run (next xs ys) key (xs.size * ys.size) (start xs ys hs) + +theorem count_value (xs ys : Array ℤ) (hs : ys.toList.Pairwise (· ≤ ·)) : + (count xs ys hs).1 = ((output xs ys (start xs ys hs)).map key).toFinset.card := + DistinctStreamCount.run_value _ _ _ (next_law xs ys) _ _ + (le_of_eq (output_length xs ys hs)) (output_sorted xs ys _) + +theorem count_queries (xs ys : Array ℤ) (hs : ys.toList.Pairwise (· ≤ ·)) : + (count xs ys hs).2 ≤ xs.size * ys.size := DistinctStreamCount.run_queries _ _ _ _ + +/-- Every cursor and cached front occupies a constant number of flat cells. -/ +def footprint (xs ys : Array ℤ) (s : State xs ys) : ℕ := + xs.size + ys.size + 10 * (Tournament.nodes s.tree + 1) + 3 + +theorem footprint_bound (xs ys : Array ℤ) (s : State xs ys) : + footprint xs ys s ≤ 41 * xs.size + ys.size + 43 := by + have h := Tournament.padded_nodes_le xs.size s.tree + unfold footprint + omega + +end LowSpaceSubsetSum.SumReader + +end OAI diff --git a/lean/OAI/Combinatorics/LowSpaceSubsetSum/Streams/TieBuffer.lean b/lean/OAI/Combinatorics/LowSpaceSubsetSum/Streams/TieBuffer.lean new file mode 100644 index 0000000000000000000000000000000000000000..dd94083060cc256961bce0fea5854c44246a9c47 --- /dev/null +++ b/lean/OAI/Combinatorics/LowSpaceSubsetSum/Streams/TieBuffer.lean @@ -0,0 +1,172 @@ +import OAI.Combinatorics.LowSpaceSubsetSum.Streams.MergeOrdering + +namespace OAI + +/-! +# A bounded tie-group buffer + +The tail-recursive collector stores at most the requested number of matching +occurrences and leaves the first different-key occurrence unconsumed. Its +instrumented query counter counts every reader call, including the final +lookahead. No clearing of unused buffer positions is performed. +-/ + +namespace LowSpaceSubsetSum +namespace TieBuffer + +universe u v + +variable {α : Type u} {σ : Type v} + +def groupView (key : α → ℤ) (K : ℤ) (view : σ → List α) (s : σ) : List α := + (view s).takeWhile (fun a => decide (key a = K)) + +structure Result (α : Type u) (σ : Type v) where + buffer : Array α + cursor : σ + queries : ℕ + +def fillAcc (read : σ → Option (α × σ)) (key : α → ℤ) (K : ℤ) : + ℕ → σ → Array α → ℕ → Result α σ + | 0, s, buf, q => ⟨buf, s, q⟩ + | k + 1, s, buf, q => match read s with + | none => ⟨buf, s, q + 1⟩ + | some (a, s') => if key a = K then fillAcc read key K k s' (buf.push a) (q + 1) + else ⟨buf, s, q + 1⟩ + +def fill (read : σ → Option (α × σ)) (key : α → ℤ) (K : ℤ) (B : ℕ) (s : σ) : + Result α σ := fillAcc read key K B s #[] 0 + +theorem fillAcc_spec (read : σ → Option (α × σ)) (key : α → ℤ) (K : ℤ) + (view : σ → List α) (hread : RowMerge.IsReader read view) + (fuel : ℕ) (s : σ) (buf : Array α) (q : ℕ) : + (fillAcc read key K fuel s buf q).buffer.toList = + buf.toList ++ (groupView key K view s).take fuel ∧ + view s = (groupView key K view s).take fuel ++ + view (fillAcc read key K fuel s buf q).cursor ∧ + groupView key K view (fillAcc read key K fuel s buf q).cursor = + (groupView key K view s).drop fuel ∧ + (fillAcc read key K fuel s buf q).queries ≤ q + fuel := by + induction fuel generalizing s buf q with + | zero => simp [fillAcc] + | succ fuel ih => + have hr := hread s + cases h : read s with + | none => + simp only [h] at hr + simp [fillAcc, h, groupView, hr] + | some z => + rcases z with ⟨a, s'⟩ + simp only [h] at hr + by_cases ha : key a = K + · have hg : groupView key K view s = a :: groupView key K view s' := by + simp [groupView, hr, ha] + have hi := ih s' (buf.push a) (q + 1) + simp only [fillAcc, h, ite_eq_left ha] + refine ⟨?_, ?_, ?_, ?_⟩ + · rw [hi.1, hg] + simp [List.append_assoc] + · rw [hr, hi.2.1, hg] + simp + · rw [hi.2.2.1, hg] + simp + · have := hi.2.2.2 + omega + · have hg : groupView key K view s = [] := by simp [groupView, hr, ha] + simp [fillAcc, h, ha, hg] + +theorem fill_buffer (read : σ → Option (α × σ)) (key : α → ℤ) (K : ℤ) + (view : σ → List α) (hread : RowMerge.IsReader read view) (B : ℕ) (s : σ) : + (fill read key K B s).buffer.toList = (groupView key K view s).take B := by + simpa [fill] using (fillAcc_spec read key K view hread B s #[] 0).1 + +theorem fill_size_le (read : σ → Option (α × σ)) (key : α → ℤ) (K : ℤ) + (view : σ → List α) (hread : RowMerge.IsReader read view) (B : ℕ) (s : σ) : + (fill read key K B s).buffer.size ≤ B := by + have h := congrArg List.length (fill_buffer read key K view hread B s) + simp only [Array.length_toList, List.length_take] at h + omega + +theorem fill_suffix (read : σ → Option (α × σ)) (key : α → ℤ) (K : ℤ) + (view : σ → List α) (hread : RowMerge.IsReader read view) (B : ℕ) (s : σ) : + groupView key K view (fill read key K B s).cursor = + (groupView key K view s).drop B := + (fillAcc_spec read key K view hread B s #[] 0).2.2.1 + +theorem fill_queries_le (read : σ → Option (α × σ)) (key : α → ℤ) (K : ℤ) + (view : σ → List α) (hread : RowMerge.IsReader read view) (B : ℕ) (s : σ) : + (fill read key K B s).queries ≤ B := by + simpa [fill] using (fillAcc_spec read key K view hread B s #[] 0).2.2.2 + +/-- The collector reads each stored occurrence once and performs at most +one additional lookahead, irrespective of the chosen buffer capacity. -/ +theorem fillAcc_queries_le_potential (read : σ → Option (α × σ)) (key : α → ℤ) (K : ℤ) + (view : σ → List α) (hread : RowMerge.IsReader read view) + (fuel : ℕ) (s : σ) (buf : Array α) (q : ℕ) : + (fillAcc read key K fuel s buf q).queries ≤ + q + min fuel ((groupView key K view s).length + 1) := by + induction fuel generalizing s buf q with + | zero => simp [fillAcc] + | succ fuel ih => + have hr := hread s + cases h : read s with + | none => + simp only [h] at hr + simp [fillAcc, h, groupView, hr] + | some z => + rcases z with ⟨x, s'⟩ + simp only [h] at hr + by_cases hx : key x = K + · have hg : groupView key K view s = x :: groupView key K view s' := by + simp [groupView, hr, hx] + have hi := ih s' (buf.push x) (q + 1) + simp only [fillAcc, h, ite_eq_left hx, hg, List.length_cons] + omega + · have hg : groupView key K view s = [] := by simp [groupView, hr, hx] + simp [fillAcc, h, hx, hg] + +theorem fill_queries_le_potential (read : σ → Option (α × σ)) (key : α → ℤ) (K : ℤ) + (view : σ → List α) (hread : RowMerge.IsReader read view) (B : ℕ) (s : σ) : + (fill read key K B s).queries ≤ (groupView key K view s).length + 1 := by + have h := fillAcc_queries_le_potential read key K view hread B s #[] 0 + simp only [fill, zero_add] at h ⊢ + exact h.trans (Nat.min_le_right _ _) + +def hasKey (read : σ → Option (α × σ)) (key : α → ℤ) (K : ℤ) (s : σ) : Bool := + match read s with + | none => false + | some (a, _) => decide (key a = K) + +theorem hasKey_iff (read : σ → Option (α × σ)) (key : α → ℤ) (K : ℤ) + (view : σ → List α) (hread : RowMerge.IsReader read view) (s : σ) : + hasKey read key K s = true ↔ groupView key K view s ≠ [] := by + have hr := hread s + cases h : read s with + | none => + simp only [h] at hr + simp [hasKey, h, groupView, hr] + | some z => + rcases z with ⟨a, s'⟩ + simp only [h] at hr + by_cases ha : key a = K <;> simp [hasKey, h, groupView, hr, ha] + +/-- A snapshot is needed only if more than `B` second-row occurrences have +this key. In particular the buffer is full when a snapshot is taken. -/ +theorem long_group_full_buffer (read : σ → Option (α × σ)) (key : α → ℤ) (K : ℤ) + (view : σ → List α) (hread : RowMerge.IsReader read view) (B : ℕ) (s : σ) + (hlong : hasKey read key K (fill read key K B s).cursor = true) : + B < (groupView key K view s).length ∧ (fill read key K B s).buffer.size = B := by + have hn := (hasKey_iff read key K view hread _).mp hlong + rw [fill_suffix read key K view hread B s] at hn + have hB : B < (groupView key K view s).length := by + by_contra h + apply hn + exact List.drop_eq_nil_of_le (by omega) + refine ⟨hB, ?_⟩ + have h := congrArg List.length (fill_buffer read key K view hread B s) + simpa only [Array.length_toList, List.length_take, Nat.min_eq_left hB.le] using h + +end TieBuffer +end LowSpaceSubsetSum + +end OAI diff --git a/lean/OAI/Combinatorics/LowSpaceSubsetSum/Streams/TieGroup.lean b/lean/OAI/Combinatorics/LowSpaceSubsetSum/Streams/TieGroup.lean new file mode 100644 index 0000000000000000000000000000000000000000..69814b340753ac74be1557b9a86be7d4e5e38d23 --- /dev/null +++ b/lean/OAI/Combinatorics/LowSpaceSubsetSum/Streams/TieGroup.lean @@ -0,0 +1,298 @@ +import OAI.Combinatorics.LowSpaceSubsetSum.Streams.JoinOne + +namespace OAI + +/-! +# A stopped Cartesian tie-group join + +A single second-stream prefix buffer and optional suffix snapshot serve every +first-stream occurrence with this key. Counters charge every attempted report, +including executions halted inside either part of a replay. Lists occur only +in the correctness specification. +-/ + +namespace LowSpaceSubsetSum +namespace TieGroup + +universe u v s t w + +variable {α : Type u} {β : Type v} {σ₁ : Type s} {σ₂ : Type t} {τ : Type w} + +structure State (σ₂ : Type t) (τ : Type w) where + last : σ₂ + user : τ + queries : ℕ + reports : ℕ + restores : ℕ + +def step (read₂ : σ₂ → Option (β × σ₂)) (key₂ : β → ℤ) (K : ℤ) + (report : α → β → τ → τ × Bool) (buffer : Array β) (saved : σ₂) + (long : Bool) (fuel₂ : ℕ) (x : α) (a : State σ₂ τ) : State σ₂ τ × Bool := + let out := JoinOne.run read₂ key₂ K (report x) buffer saved long fuel₂ a.user + (⟨out.cursor, out.state, a.queries + out.queries, a.reports + out.reports, + a.restores + if long then 1 else 0⟩, out.halted) + +structure Result (σ₁ : Type s) (σ₂ : Type t) (τ : Type w) where + outer : TieReplay.Result σ₁ (State σ₂ τ) + fillQueries : ℕ + bufferSize : ℕ + snapshot : Bool + +def run (read₁ : σ₁ → Option (α × σ₁)) (key₁ : α → ℤ) + (read₂ : σ₂ → Option (β × σ₂)) (key₂ : β → ℤ) (K : ℤ) + (report : α → β → τ → τ × Bool) (B fuel₁ fuel₂ : ℕ) + (s₁ : σ₁) (s₂ : σ₂) (a : τ) : Result σ₁ σ₂ τ := + let filled := TieBuffer.fill read₂ key₂ K B s₂ + let long := TieBuffer.hasKey read₂ key₂ K filled.cursor + let out := TieReplay.run read₁ key₁ K + (step read₂ key₂ K report filled.buffer filled.cursor long fuel₂) + fuel₁ s₁ ⟨filled.cursor, a, 0, 0, 0⟩ + ⟨out, filled.queries, filled.buffer.size, long && TieBuffer.hasKey read₁ key₁ K s₁⟩ + +/-- Bounds on callbacks follow from the actual suffix reporter, not from +assumed trial or implementation bounds. -/ +theorem step_bounds (read₂ : σ₂ → Option (β × σ₂)) (key₂ : β → ℤ) (K : ℤ) + (report : α → β → τ → τ × Bool) (view₂ : σ₂ → List β) + (hread₂ : RowMerge.IsReader read₂ view₂) (buffer : Array β) (saved : σ₂) + (long : Bool) (fuel₂ : ℕ) (x : α) (a : State σ₂ τ) : + (step read₂ key₂ K report buffer saved long fuel₂ x a).1.reports ≤ + a.reports + (buffer.size + (TieBuffer.groupView key₂ K view₂ saved).length) ∧ + (step read₂ key₂ K report buffer saved long fuel₂ x a).1.queries ≤ + a.queries + (buffer.size + (TieBuffer.groupView key₂ K view₂ saved).length + 1) ∧ + (step read₂ key₂ K report buffer saved long fuel₂ x a).1.restores ≤ a.restores + 1 := by + have hr := JoinOne.reports_le read₂ key₂ K (report x) view₂ hread₂ buffer saved long fuel₂ a.user + have hq := JoinOne.queries_le read₂ key₂ K (report x) view₂ hread₂ buffer saved long fuel₂ a.user + dsimp only [step] + refine ⟨Nat.add_le_add_left hr _, Nat.add_le_add_left hq _, ?_⟩ + split <;> omega + +theorem run_bounds (read₁ : σ₁ → Option (α × σ₁)) (key₁ : α → ℤ) + (read₂ : σ₂ → Option (β × σ₂)) (key₂ : β → ℤ) (K : ℤ) + (report : α → β → τ → τ × Bool) + (view₁ : σ₁ → List α) (hread₁ : RowMerge.IsReader read₁ view₁) + (view₂ : σ₂ → List β) (hread₂ : RowMerge.IsReader read₂ view₂) + (B fuel₁ fuel₂ : ℕ) (s₁ : σ₁) (s₂ : σ₂) (a : τ) : + (run read₁ key₁ read₂ key₂ K report B fuel₁ fuel₂ s₁ s₂ a).outer.state.reports ≤ + (TieBuffer.groupView key₁ K view₁ s₁).length * + (TieBuffer.groupView key₂ K view₂ s₂).length ∧ + (run read₁ key₁ read₂ key₂ K report B fuel₁ fuel₂ s₁ s₂ a).outer.state.queries ≤ + (TieBuffer.groupView key₁ K view₁ s₁).length * + ((TieBuffer.groupView key₂ K view₂ s₂).length + 1) ∧ + (run read₁ key₁ read₂ key₂ K report B fuel₁ fuel₂ s₁ s₂ a).outer.state.restores ≤ + (TieBuffer.groupView key₁ K view₁ s₁).length := by + let filled := TieBuffer.fill read₂ key₂ K B s₂ + let long := TieBuffer.hasKey read₂ key₂ K filled.cursor + let N := (TieBuffer.groupView key₂ K view₂ s₂).length + let P := fun (st : State σ₂ τ) (r : ℕ) => + st.reports ≤ r * N ∧ st.queries ≤ r * (N + 1) ∧ st.restores ≤ r + have hsplit : filled.buffer.size + + (TieBuffer.groupView key₂ K view₂ filled.cursor).length = N := by + have hb := congrArg List.length (TieBuffer.fill_buffer read₂ key₂ K view₂ hread₂ B s₂) + rw [TieBuffer.fill_suffix read₂ key₂ K view₂ hread₂ B s₂] + simp only [Array.length_toList, List.length_take] at hb + simp only [List.length_drop] + dsimp only [filled, N] + omega + have hstep : ∀ x st r, P st r → + P (step read₂ key₂ K report filled.buffer filled.cursor long fuel₂ x st).1 (r + 1) := by + intro x st r hr + have h := step_bounds read₂ key₂ K report view₂ hread₂ filled.buffer filled.cursor long fuel₂ x st + rw [hsplit] at h + dsimp only [P] at hr ⊢ + rcases hr with ⟨hr, hq, hc⟩ + rcases h with ⟨hr', hq', hc'⟩ + rw [Nat.add_mul, Nat.add_mul] + simp only [one_mul] + exact ⟨hr'.trans (Nat.add_le_add_right hr _), hq'.trans (Nat.add_le_add_right hq _), by omega⟩ + have h := TieReplay.run_preserves read₁ key₁ K + (step read₂ key₂ K report filled.buffer filled.cursor long fuel₂) P hstep fuel₁ s₁ + ⟨filled.cursor, a, 0, 0, 0⟩ (by simp [P]) + have hr := TieReplay.run_reports_le_potential read₁ key₁ K + (step read₂ key₂ K report filled.buffer filled.cursor long fuel₂) + view₁ hread₁ fuel₁ s₁ ⟨filled.cursor, a, 0, 0, 0⟩ + dsimp only [P] at h + refine ⟨h.1.trans (Nat.mul_le_mul_right N hr), + h.2.1.trans (Nat.mul_le_mul_right (N + 1) hr), h.2.2.trans hr⟩ + +/-- On a continuing run every occurrence in the Cartesian tie group is +reported, in first-stream order and then second-stream order. -/ +theorem state_complete (read₁ : σ₁ → Option (α × σ₁)) (key₁ : α → ℤ) + (read₂ : σ₂ → Option (β × σ₂)) (key₂ : β → ℤ) (K : ℤ) + (report : α → β → τ → τ × Bool) (hreport : ∀ x y a, (report x y a).2 = false) + (view₁ : σ₁ → List α) (hread₁ : RowMerge.IsReader read₁ view₁) + (view₂ : σ₂ → List β) (hread₂ : RowMerge.IsReader read₂ view₂) + (B fuel₁ fuel₂ : ℕ) (s₁ : σ₁) (s₂ : σ₂) (a : τ) + (hfuel₁ : (TieBuffer.groupView key₁ K view₁ s₁).length ≤ fuel₁) + (hfuel₂ : (TieBuffer.groupView key₂ K view₂ s₂).length ≤ fuel₂) : + (run read₁ key₁ read₂ key₂ K report B fuel₁ fuel₂ s₁ s₂ a).outer.state.user = + (TieBuffer.groupView key₁ K view₁ s₁).foldl + (fun a x => (TieBuffer.groupView key₂ K view₂ s₂).foldl + (fun a y => (report x y a).1) a) a := by + let filled := TieBuffer.fill read₂ key₂ K B s₂ + let long := TieBuffer.hasKey read₂ key₂ K filled.cursor + let f := step read₂ key₂ K report filled.buffer filled.cursor long fuel₂ + have hnonhalt : ∀ x st, (f x st).2 = false := by + intro x st + exact JoinOne.halted_false read₂ key₂ K (report x) (hreport x) + filled.buffer filled.cursor long fuel₂ st.user + have huser : ∀ x st, (f x st).1.user = + (TieBuffer.groupView key₂ K view₂ s₂).foldl (fun a y => (report x y a).1) st.user := by + intro x st + exact JoinOne.filled_state_complete read₂ key₂ K (report x) (hreport x) + view₂ hread₂ B fuel₂ s₂ st.user hfuel₂ + have h := TieReplay.run_state_complete read₁ key₁ K f hnonhalt view₁ hread₁ fuel₁ s₁ + (⟨filled.cursor, a, 0, 0, 0⟩ : State σ₂ τ) hfuel₁ + change (TieReplay.run read₁ key₁ K f fuel₁ s₁ _).state.user = _ + rw [h] + exact (List.foldl_hom State.user (g₁ := fun st x => (f x st).1) + (fun st x => (huser x st).symm)).symm + +theorem step_halted_false (read₂ : σ₂ → Option (β × σ₂)) (key₂ : β → ℤ) (K : ℤ) + (report : α → β → τ → τ × Bool) (hreport : ∀ x y a, (report x y a).2 = false) + (buffer : Array β) (saved : σ₂) (long : Bool) (fuel₂ : ℕ) (x : α) (a : State σ₂ τ) : + (step read₂ key₂ K report buffer saved long fuel₂ x a).2 = false := + JoinOne.halted_false read₂ key₂ K (report x) (hreport x) buffer saved long fuel₂ a.user + +theorem halted_false (read₁ : σ₁ → Option (α × σ₁)) (key₁ : α → ℤ) + (read₂ : σ₂ → Option (β × σ₂)) (key₂ : β → ℤ) (K : ℤ) + (report : α → β → τ → τ × Bool) (hreport : ∀ x y a, (report x y a).2 = false) + (B fuel₁ fuel₂ : ℕ) (s₁ : σ₁) (s₂ : σ₂) (a : τ) : + (run read₁ key₁ read₂ key₂ K report B fuel₁ fuel₂ s₁ s₂ a).outer.halted = false := + TieReplay.run_halted_false read₁ key₁ K _ + (step_halted_false read₂ key₂ K report hreport _ _ _ _) _ _ _ + +/-- Both generator cursors end immediately after this key, so a surrounding +merge join can continue without losing its next different-key occurrences. -/ +theorem views_complete (read₁ : σ₁ → Option (α × σ₁)) (key₁ : α → ℤ) + (read₂ : σ₂ → Option (β × σ₂)) (key₂ : β → ℤ) (K : ℤ) + (report : α → β → τ → τ × Bool) (hreport : ∀ x y a, (report x y a).2 = false) + (view₁ : σ₁ → List α) (hread₁ : RowMerge.IsReader read₁ view₁) + (view₂ : σ₂ → List β) (hread₂ : RowMerge.IsReader read₂ view₂) + (B fuel₁ fuel₂ : ℕ) (s₁ : σ₁) (s₂ : σ₂) (a : τ) + (hfuel₁ : (TieBuffer.groupView key₁ K view₁ s₁).length ≤ fuel₁) + (hfuel₂ : (TieBuffer.groupView key₂ K view₂ s₂).length ≤ fuel₂) + (hne : TieBuffer.groupView key₁ K view₁ s₁ ≠ []) : + view₁ s₁ = TieBuffer.groupView key₁ K view₁ s₁ ++ + view₁ (run read₁ key₁ read₂ key₂ K report B fuel₁ fuel₂ s₁ s₂ a).outer.cursor ∧ + view₂ s₂ = TieBuffer.groupView key₂ K view₂ s₂ ++ + view₂ (run read₁ key₁ read₂ key₂ K report B fuel₁ fuel₂ s₁ s₂ a).outer.state.last := by + let filled := TieBuffer.fill read₂ key₂ K B s₂ + let long := TieBuffer.hasKey read₂ key₂ K filled.cursor + let f := step read₂ key₂ K report filled.buffer filled.cursor long fuel₂ + have hnonhalt : ∀ x st, (f x st).2 = false := + step_halted_false read₂ key₂ K report hreport filled.buffer filled.cursor long fuel₂ + have hspec := TieReplay.runAcc_nonhalting_spec read₁ key₁ K f hnonhalt view₁ hread₁ fuel₁ s₁ + (⟨filled.cursor, a, 0, 0, 0⟩ : State σ₂ τ) 0 0 + have hfirst : view₁ s₁ = TieBuffer.groupView key₁ K view₁ s₁ ++ + view₁ (run read₁ key₁ read₂ key₂ K report B fuel₁ fuel₂ s₁ s₂ a).outer.cursor := by + simpa only [run, TieReplay.run, f, long, filled, List.take_of_length_le hfuel₁] using hspec.2.2.2 + refine ⟨hfirst, ?_⟩ + let P := fun (st : State σ₂ τ) (r : ℕ) => r = 0 ∨ + view₂ s₂ = TieBuffer.groupView key₂ K view₂ s₂ ++ view₂ st.last + have hstep : ∀ x st r, P st r → P (f x st).1 (r + 1) := by + intro x st r _ + exact Or.inr (JoinOne.filled_view_complete read₂ key₂ K (report x) (hreport x) + view₂ hread₂ B fuel₂ s₂ st.user hfuel₂) + have hP := TieReplay.run_preserves read₁ key₁ K f P hstep fuel₁ s₁ + (⟨filled.cursor, a, 0, 0, 0⟩ : State σ₂ τ) (Or.inl rfl) + have hcount : (run read₁ key₁ read₂ key₂ K report B fuel₁ fuel₂ s₁ s₂ a).outer.reports = + (TieBuffer.groupView key₁ K view₁ s₁).length := by + simpa only [run, TieReplay.run, f, long, filled, Nat.zero_add, Nat.min_eq_right hfuel₁] using hspec.2.1 + change (run read₁ key₁ read₂ key₂ K report B fuel₁ fuel₂ s₁ s₂ a).outer.reports = 0 ∨ _ at hP + rcases hP with hz | hP + · rw [hcount] at hz + exact False.elim (hne (List.length_eq_zero_iff.mp hz)) + · exact hP + +theorem query_bound (read₁ : σ₁ → Option (α × σ₁)) (key₁ : α → ℤ) + (read₂ : σ₂ → Option (β × σ₂)) (key₂ : β → ℤ) (K : ℤ) + (report : α → β → τ → τ × Bool) + (view₁ : σ₁ → List α) (hread₁ : RowMerge.IsReader read₁ view₁) + (view₂ : σ₂ → List β) (hread₂ : RowMerge.IsReader read₂ view₂) + (B fuel₁ fuel₂ : ℕ) (s₁ : σ₁) (s₂ : σ₂) (a : τ) : + (run read₁ key₁ read₂ key₂ K report B fuel₁ fuel₂ s₁ s₂ a).outer.queries + + (run read₁ key₁ read₂ key₂ K report B fuel₁ fuel₂ s₁ s₂ a).fillQueries + + (run read₁ key₁ read₂ key₂ K report B fuel₁ fuel₂ s₁ s₂ a).outer.state.queries ≤ + 2 * (TieBuffer.groupView key₁ K view₁ s₁).length + + (TieBuffer.groupView key₂ K view₂ s₂).length + + (TieBuffer.groupView key₁ K view₁ s₁).length * + (TieBuffer.groupView key₂ K view₂ s₂).length + 2 := by + have hq := (run_bounds read₁ key₁ read₂ key₂ K report view₁ hread₁ view₂ hread₂ + B fuel₁ fuel₂ s₁ s₂ a).2.1 + have hf := TieBuffer.fill_queries_le_potential read₂ key₂ K view₂ hread₂ B s₂ + have ho := TieReplay.run_queries_le_potential read₁ key₁ K + (step read₂ key₂ K report (TieBuffer.fill read₂ key₂ K B s₂).buffer + (TieBuffer.fill read₂ key₂ K B s₂).cursor + (TieBuffer.hasKey read₂ key₂ K (TieBuffer.fill read₂ key₂ K B s₂).cursor) fuel₂) + view₁ hread₁ fuel₁ s₁ ⟨(TieBuffer.fill read₂ key₂ K B s₂).cursor, a, 0, 0, 0⟩ + change (run read₁ key₁ read₂ key₂ K report B fuel₁ fuel₂ s₁ s₂ a).outer.queries ≤ _ at ho + change (run read₁ key₁ read₂ key₂ K report B fuel₁ fuel₂ s₁ s₂ a).fillQueries ≤ _ at hf + nlinarith + +theorem bufferSize_le (read₁ : σ₁ → Option (α × σ₁)) (key₁ : α → ℤ) + (read₂ : σ₂ → Option (β × σ₂)) (key₂ : β → ℤ) (K : ℤ) + (report : α → β → τ → τ × Bool) + (view₂ : σ₂ → List β) (hread₂ : RowMerge.IsReader read₂ view₂) + (B fuel₁ fuel₂ : ℕ) (s₁ : σ₁) (s₂ : σ₂) (a : τ) : + (run read₁ key₁ read₂ key₂ K report B fuel₁ fuel₂ s₁ s₂ a).bufferSize ≤ B := + TieBuffer.fill_size_le read₂ key₂ K view₂ hread₂ B s₂ + +/-- Without a long suffix, there are no generator restores. -/ +theorem restores_eq_zero_of_short (read₁ : σ₁ → Option (α × σ₁)) (key₁ : α → ℤ) + (read₂ : σ₂ → Option (β × σ₂)) (key₂ : β → ℤ) (K : ℤ) + (report : α → β → τ → τ × Bool) (B fuel₁ fuel₂ : ℕ) + (s₁ : σ₁) (s₂ : σ₂) (a : τ) + (hshort : TieBuffer.hasKey read₂ key₂ K (TieBuffer.fill read₂ key₂ K B s₂).cursor = false) : + (run read₁ key₁ read₂ key₂ K report B fuel₁ fuel₂ s₁ s₂ a).outer.state.restores = 0 := by + dsimp only [run] + apply TieReplay.run_preserves read₁ key₁ K _ + (fun (st : State σ₂ τ) (_ : ℕ) => st.restores = 0) _ _ _ _ rfl + intro x st r hst + simpa only [step, hshort, Bool.false_eq_true, ite_false, Nat.add_zero] using hst + +/-- Every snapshot/restore is charged to potential partners, including +partners not reached when the execution halts. -/ +theorem copies_charged (read₁ : σ₁ → Option (α × σ₁)) (key₁ : α → ℤ) + (read₂ : σ₂ → Option (β × σ₂)) (key₂ : β → ℤ) (K : ℤ) + (report : α → β → τ → τ × Bool) + (view₁ : σ₁ → List α) (hread₁ : RowMerge.IsReader read₁ view₁) + (view₂ : σ₂ → List β) (hread₂ : RowMerge.IsReader read₂ view₂) + (B fuel₁ fuel₂ : ℕ) (s₁ : σ₁) (s₂ : σ₂) (a : τ) : + B * ((if (run read₁ key₁ read₂ key₂ K report B fuel₁ fuel₂ s₁ s₂ a).snapshot then 1 else 0) + + (run read₁ key₁ read₂ key₂ K report B fuel₁ fuel₂ s₁ s₂ a).outer.state.restores) ≤ + 2 * ((TieBuffer.groupView key₁ K view₁ s₁).length * + (TieBuffer.groupView key₂ K view₂ s₂).length) := by + have hc := (run_bounds read₁ key₁ read₂ key₂ K report view₁ hread₁ view₂ hread₂ + B fuel₁ fuel₂ s₁ s₂ a).2.2 + by_cases hl : TieBuffer.hasKey read₂ key₂ K (TieBuffer.fill read₂ key₂ K B s₂).cursor = true + · have hB := (TieBuffer.long_group_full_buffer read₂ key₂ K view₂ hread₂ B s₂ hl).1.le + by_cases hfirst : TieBuffer.hasKey read₁ key₁ K s₁ = true + · have hpos : 0 < (TieBuffer.groupView key₁ K view₁ s₁).length := + List.length_pos_iff.mpr ((TieBuffer.hasKey_iff read₁ key₁ K view₁ hread₁ s₁).mp hfirst) + have hs : (run read₁ key₁ read₂ key₂ K report B fuel₁ fuel₂ s₁ s₂ a).snapshot = true := by + simp [run, hl, hfirst] + simp only [hs, ↓reduceIte] + calc + B * (1 + _) ≤ B * (2 * (TieBuffer.groupView key₁ K view₁ s₁).length) := by + apply Nat.mul_le_mul_left + omega + _ ≤ (TieBuffer.groupView key₂ K view₂ s₂).length * + (2 * (TieBuffer.groupView key₁ K view₁ s₁).length) := Nat.mul_le_mul_right _ hB + _ = _ := by ring + · have he : TieBuffer.groupView key₁ K view₁ s₁ = [] := by + by_contra he + exact hfirst ((TieBuffer.hasKey_iff read₁ key₁ K view₁ hread₁ s₁).mpr he) + have hs : (run read₁ key₁ read₂ key₂ K report B fuel₁ fuel₂ s₁ s₂ a).snapshot = false := by + simp [run, Bool.eq_false_iff.mpr hfirst] + rw [he, List.length_nil] at hc ⊢ + simp [hs, Nat.eq_zero_of_le_zero hc] + · have hshort := Bool.eq_false_iff.mpr hl + have hz := restores_eq_zero_of_short read₁ key₁ read₂ key₂ K report B fuel₁ fuel₂ s₁ s₂ a hshort + have hs : (run read₁ key₁ read₂ key₂ K report B fuel₁ fuel₂ s₁ s₂ a).snapshot = false := by + simp [run, hshort] + simp [hs, hz] + +end TieGroup +end LowSpaceSubsetSum + +end OAI diff --git a/lean/OAI/Combinatorics/LowSpaceSubsetSum/Streams/TieReplay.lean b/lean/OAI/Combinatorics/LowSpaceSubsetSum/Streams/TieReplay.lean new file mode 100644 index 0000000000000000000000000000000000000000..bb3c6d736b3a36329453c9954ecea251776bc692 --- /dev/null +++ b/lean/OAI/Combinatorics/LowSpaceSubsetSum/Streams/TieReplay.lean @@ -0,0 +1,239 @@ +import OAI.Combinatorics.LowSpaceSubsetSum.Streams.TieBuffer + +namespace OAI + +/-! +# Bounded replay of one tie suffix + +The reporter can stop after any matching occurrence. The replay retains +only its cursor, callback state, counters, and fixed key. Its recursion is +tail recursion. All attempted reports are bounded by the complete suffix +length, even if the callback or fuel stops execution early. +-/ + +namespace LowSpaceSubsetSum +namespace TieReplay + +universe u v w + +variable {α : Type u} {σ : Type v} {τ : Type w} + +structure Result (σ : Type v) (τ : Type w) where + cursor : σ + state : τ + queries : ℕ + reports : ℕ + complete : Bool + halted : Bool + +def runAcc (read : σ → Option (α × σ)) (key : α → ℤ) (K : ℤ) + (report : α → τ → τ × Bool) : ℕ → σ → τ → ℕ → ℕ → Result σ τ + | 0, s, a, q, r => ⟨s, a, q, r, false, false⟩ + | fuel + 1, s, a, q, r => match read s with + | none => ⟨s, a, q + 1, r, true, false⟩ + | some (x, s') => if key x = K then + let out := report x a + if out.2 then ⟨s', out.1, q + 1, r + 1, false, true⟩ + else runAcc read key K report fuel s' out.1 (q + 1) (r + 1) + else ⟨s, a, q + 1, r, true, false⟩ + +def run (read : σ → Option (α × σ)) (key : α → ℤ) (K : ℤ) + (report : α → τ → τ × Bool) (fuel : ℕ) (s : σ) (a : τ) : Result σ τ := + runAcc read key K report fuel s a 0 0 + +theorem runAcc_bounds (read : σ → Option (α × σ)) (key : α → ℤ) (K : ℤ) + (report : α → τ → τ × Bool) (view : σ → List α) (hread : RowMerge.IsReader read view) + (fuel : ℕ) (s : σ) (a : τ) (q r : ℕ) : + (runAcc read key K report fuel s a q r).queries ≤ q + fuel ∧ + r ≤ (runAcc read key K report fuel s a q r).reports ∧ + (runAcc read key K report fuel s a q r).reports ≤ + r + min fuel (TieBuffer.groupView key K view s).length := by + induction fuel generalizing s a q r with + | zero => simp [runAcc] + | succ fuel ih => + have hr := hread s + cases h : read s with + | none => + simp only [h] at hr + simp [runAcc, h, TieBuffer.groupView, hr] + | some z => + rcases z with ⟨x, s'⟩ + simp only [h] at hr + by_cases hx : key x = K + · have hg : TieBuffer.groupView key K view s = + x :: TieBuffer.groupView key K view s' := by + simp [TieBuffer.groupView, hr, hx] + simp only [runAcc, h, ite_eq_left hx] + split + · simp only [hg, List.length_cons] + omega + · have hi := ih s' (report x a).1 (q + 1) (r + 1) + simp only [hg, List.length_cons] + omega + · have hg : TieBuffer.groupView key K view s = [] := by + simp [TieBuffer.groupView, hr, hx] + simp [runAcc, h, hx, hg] + +theorem run_queries_le (read : σ → Option (α × σ)) (key : α → ℤ) (K : ℤ) + (report : α → τ → τ × Bool) (view : σ → List α) (hread : RowMerge.IsReader read view) + (fuel : ℕ) (s : σ) (a : τ) : (run read key K report fuel s a).queries ≤ fuel := by + simpa [run] using (runAcc_bounds read key K report view hread fuel s a 0 0).1 + +theorem run_reports_le_potential (read : σ → Option (α × σ)) (key : α → ℤ) (K : ℤ) + (report : α → τ → τ × Bool) (view : σ → List α) (hread : RowMerge.IsReader read view) + (fuel : ℕ) (s : σ) (a : τ) : + (run read key K report fuel s a).reports ≤ (TieBuffer.groupView key K view s).length := by + have h := (runAcc_bounds read key K report view hread fuel s a 0 0).2.2 + simp only [run, zero_add] at h ⊢ + exact h.trans (Nat.min_le_right _ _) + +/-- The one final lookahead is the only read not charged to a reportable +occurrence, even when the fuel is much larger than the tie group. -/ +theorem runAcc_queries_le_potential (read : σ → Option (α × σ)) (key : α → ℤ) (K : ℤ) + (report : α → τ → τ × Bool) (view : σ → List α) (hread : RowMerge.IsReader read view) + (fuel : ℕ) (s : σ) (a : τ) (q r : ℕ) : + (runAcc read key K report fuel s a q r).queries ≤ + q + min fuel ((TieBuffer.groupView key K view s).length + 1) := by + induction fuel generalizing s a q r with + | zero => simp [runAcc] + | succ fuel ih => + have hr := hread s + cases h : read s with + | none => + simp only [h] at hr + simp [runAcc, h, TieBuffer.groupView, hr] + | some z => + rcases z with ⟨x, s'⟩ + simp only [h] at hr + by_cases hx : key x = K + · have hg : TieBuffer.groupView key K view s = + x :: TieBuffer.groupView key K view s' := by + simp [TieBuffer.groupView, hr, hx] + simp only [runAcc, h, ite_eq_left hx, hg, List.length_cons] + split + · dsimp only + omega + · have hi := ih s' (report x a).1 (q + 1) (r + 1) + omega + · have hg : TieBuffer.groupView key K view s = [] := by + simp [TieBuffer.groupView, hr, hx] + simp [runAcc, h, hx, hg] + +theorem run_queries_le_potential (read : σ → Option (α × σ)) (key : α → ℤ) (K : ℤ) + (report : α → τ → τ × Bool) (view : σ → List α) (hread : RowMerge.IsReader read view) + (fuel : ℕ) (s : σ) (a : τ) : + (run read key K report fuel s a).queries ≤ (TieBuffer.groupView key K view s).length + 1 := by + have h := runAcc_queries_le_potential read key K report view hread fuel s a 0 0 + simp only [run, zero_add] at h ⊢ + exact h.trans (Nat.min_le_right _ _) + +theorem runAcc_halted_false (read : σ → Option (α × σ)) (key : α → ℤ) (K : ℤ) + (report : α → τ → τ × Bool) (hreport : ∀ x a, (report x a).2 = false) + (fuel : ℕ) (s : σ) (a : τ) (q r : ℕ) : + (runAcc read key K report fuel s a q r).halted = false := by + induction fuel generalizing s a q r with + | zero => rfl + | succ fuel ih => + cases h : read s with + | none => simp [runAcc, h] + | some z => + rcases z with ⟨x, s'⟩ + by_cases hx : key x = K + · simp only [runAcc, h, ite_eq_left hx, hreport, Bool.false_eq_true, ite_false] + exact ih _ _ _ _ + · simp [runAcc, h, hx] + +theorem run_halted_false (read : σ → Option (α × σ)) (key : α → ℤ) (K : ℤ) + (report : α → τ → τ × Bool) (hreport : ∀ x a, (report x a).2 = false) + (fuel : ℕ) (s : σ) (a : τ) : + (run read key K report fuel s a).halted = false := + runAcc_halted_false read key K report hreport fuel s a 0 0 + +/-- A callback invariant can depend on the exact number of reports. This +also applies to executions stopped by the callback or by the fuel. -/ +theorem runAcc_preserves (read : σ → Option (α × σ)) (key : α → ℤ) (K : ℤ) + (report : α → τ → τ × Bool) (P : τ → ℕ → Prop) + (hstep : ∀ x a r, P a r → P (report x a).1 (r + 1)) + (fuel : ℕ) (s : σ) (a : τ) (q r : ℕ) (ha : P a r) : + P (runAcc read key K report fuel s a q r).state + (runAcc read key K report fuel s a q r).reports := by + induction fuel generalizing s a q r with + | zero => exact ha + | succ fuel ih => + cases h : read s with + | none => simpa only [runAcc, h] using ha + | some z => + rcases z with ⟨x, s'⟩ + by_cases hx : key x = K + · simp only [runAcc, h, ite_eq_left hx] + split + · exact hstep x a r ha + · exact ih s' (report x a).1 (q + 1) (r + 1) (hstep x a r ha) + · simpa only [runAcc, h, ite_eq_right hx] using ha + +theorem run_preserves (read : σ → Option (α × σ)) (key : α → ℤ) (K : ℤ) + (report : α → τ → τ × Bool) (P : τ → ℕ → Prop) + (hstep : ∀ x a r, P a r → P (report x a).1 (r + 1)) + (fuel : ℕ) (s : σ) (a : τ) (ha : P a 0) : + P (run read key K report fuel s a).state (run read key K report fuel s a).reports := + runAcc_preserves read key K report P hstep fuel s a 0 0 ha + +/-- If reporting continues, replay processes exactly the requested prefix +of the tie suffix and leaves every following occurrence untouched. -/ +theorem runAcc_nonhalting_spec (read : σ → Option (α × σ)) (key : α → ℤ) (K : ℤ) + (report : α → τ → τ × Bool) (hreport : ∀ x a, (report x a).2 = false) + (view : σ → List α) (hread : RowMerge.IsReader read view) + (fuel : ℕ) (s : σ) (a : τ) (q r : ℕ) : + (runAcc read key K report fuel s a q r).state = + ((TieBuffer.groupView key K view s).take fuel).foldl (fun a x => (report x a).1) a ∧ + (runAcc read key K report fuel s a q r).reports = + r + min fuel (TieBuffer.groupView key K view s).length ∧ + TieBuffer.groupView key K view (runAcc read key K report fuel s a q r).cursor = + (TieBuffer.groupView key K view s).drop fuel ∧ + view s = (TieBuffer.groupView key K view s).take fuel ++ + view (runAcc read key K report fuel s a q r).cursor := by + induction fuel generalizing s a q r with + | zero => simp [runAcc] + | succ fuel ih => + have hr := hread s + cases h : read s with + | none => + simp only [h] at hr + simp [runAcc, h, TieBuffer.groupView, hr] + | some z => + rcases z with ⟨x, s'⟩ + simp only [h] at hr + by_cases hx : key x = K + · have hg : TieBuffer.groupView key K view s = + x :: TieBuffer.groupView key K view s' := by + simp [TieBuffer.groupView, hr, hx] + have hi := ih s' (report x a).1 (q + 1) (r + 1) + simp only [runAcc, h, ite_eq_left hx, hreport, Bool.false_eq_true, ite_false] + refine ⟨?_, ?_, ?_, ?_⟩ + · rw [hi.1, hg] + simp + · rw [hi.2.1, hg] + simp only [List.length_cons] + omega + · rw [hi.2.2.1, hg] + simp + · rw [hr, hi.2.2.2, hg] + simp + · have hg : TieBuffer.groupView key K view s = [] := by + simp [TieBuffer.groupView, hr, hx] + simp [runAcc, h, hx, hg] + +theorem run_state_complete (read : σ → Option (α × σ)) (key : α → ℤ) (K : ℤ) + (report : α → τ → τ × Bool) (hreport : ∀ x a, (report x a).2 = false) + (view : σ → List α) (hread : RowMerge.IsReader read view) + (fuel : ℕ) (s : σ) (a : τ) + (hfuel : (TieBuffer.groupView key K view s).length ≤ fuel) : + (run read key K report fuel s a).state = + (TieBuffer.groupView key K view s).foldl (fun a x => (report x a).1) a := by + have h := (runAcc_nonhalting_spec read key K report hreport view hread fuel s a 0 0).1 + simpa [run, List.take_of_length_le hfuel] using h + +end TieReplay +end LowSpaceSubsetSum + +end OAI diff --git a/lean/OAI/Combinatorics/LowSpaceSubsetSum/Streams/Tournament.lean b/lean/OAI/Combinatorics/LowSpaceSubsetSum/Streams/Tournament.lean new file mode 100644 index 0000000000000000000000000000000000000000..93f2743067212ab3e3ca1e05f3567cbea0b0a27e --- /dev/null +++ b/lean/OAI/Combinatorics/LowSpaceSubsetSum/Streams/Tournament.lean @@ -0,0 +1,281 @@ +import Mathlib.Data.Fin.Tuple.Basic +import Mathlib.Data.List.Basic +import Mathlib.Data.Nat.Log +import Mathlib.Tactic + +namespace OAI + +/-! +# Cached tournament for merging row fronts + +Each leaf holds at most one current occurrence of a row. Internal nodes +cache the smaller child winner. Reading the winner is constant time; +replacing one leaf recomputes just its root path. The candidate list below +is an analysis view and is never stored in the tournament. +-/ + +namespace LowSpaceSubsetSum +namespace Tournament + +universe u + +variable {α : Type u} + +def pick (key : α → ℤ) : Option α → Option α → Option α + | none, v => v + | u, none => u + | some x, some y => if key x ≤ key y then some x else some y + +theorem pick_member (key : α → ℤ) (u v : Option α) {x : α} + (h : pick key u v = some x) : u = some x ∨ v = some x := by + cases u with + | none => exact Or.inr h + | some a => + cases v with + | none => exact Or.inl h + | some b => + by_cases hab : key a ≤ key b + · exact Or.inl (by simpa [pick, hab] using h) + · exact Or.inr (by simpa [pick, hab] using h) + +theorem pick_le_left (key : α → ℤ) (a : α) (v : Option α) : + ∃ x, pick key (some a) v = some x ∧ key x ≤ key a := by + cases v with + | none => exact ⟨a, rfl, le_rfl⟩ + | some b => + by_cases hab : key a ≤ key b + · exact ⟨a, by simp [pick, hab], le_rfl⟩ + · exact ⟨b, by simp [pick, hab], (not_le.mp hab).le⟩ + +theorem pick_le_right (key : α → ℤ) (u : Option α) (b : α) : + ∃ x, pick key u (some b) = some x ∧ key x ≤ key b := by + cases u with + | none => exact ⟨b, rfl, le_rfl⟩ + | some a => + by_cases hab : key a ≤ key b + · exact ⟨a, by simp [pick, hab], hab⟩ + · exact ⟨b, by simp [pick, hab], le_rfl⟩ + +def Best (key : α → ℤ) (v : Option α) (xs : List α) : Prop := + (∀ x, v = some x → x ∈ xs) ∧ (∀ y ∈ xs, ∃ x, v = some x ∧ key x ≤ key y) + +theorem best_append (key : α → ℤ) {u v : Option α} {xs ys : List α} + (hu : Best key u xs) (hv : Best key v ys) : + Best key (pick key u v) (xs ++ ys) := by + constructor + · intro x hx + rcases pick_member key u v hx with hx | hx + · exact List.mem_append_left _ (hu.1 x hx) + · exact List.mem_append_right _ (hv.1 x hx) + · intro y hy + rcases List.mem_append.mp hy with hy | hy + · obtain ⟨z, hz, hzy⟩ := hu.2 y hy + obtain ⟨x, hx, hxz⟩ := pick_le_left key z v + rw [← hz] at hx + exact ⟨x, hx, hxz.trans hzy⟩ + · obtain ⟨z, hz, hzy⟩ := hv.2 y hy + obtain ⟨x, hx, hxz⟩ := pick_le_right key u z + rw [← hz] at hx + exact ⟨x, hx, hxz.trans hzy⟩ + +inductive Tree (α : Type u) : ℕ → Type u + | leaf (value : Option α) : Tree α 0 + | node {d : ℕ} (winner : Option α) (left right : Tree α d) : Tree α (d + 1) + +def winner {d : ℕ} : Tree α d → Option α + | .leaf v => v + | .node v _ _ => v + +def candidates {d : ℕ} : Tree α d → List α + | .leaf v => v.toList + | .node _ l r => candidates l ++ candidates r + +def Valid (key : α → ℤ) {d : ℕ} : Tree α d → Prop + | .leaf _ => True + | .node v l r => v = pick key (winner l) (winner r) ∧ Valid key l ∧ Valid key r + +def node (key : α → ℤ) {d : ℕ} (l r : Tree α d) : Tree α (d + 1) := + .node (pick key (winner l) (winner r)) l r + +theorem winner_best (key : α → ℤ) {d : ℕ} (t : Tree α d) (ht : Valid key t) : + Best key (winner t) (candidates t) := by + induction t with + | leaf v => cases v <;> simp [winner, candidates, Best] + | node v l r ihl ihr => + obtain ⟨hv, hl, hr⟩ := ht + change Best key v (candidates l ++ candidates r) + rw [hv] + exact best_append key (ihl hl) (ihr hr) + +theorem winner_none_iff (key : α → ℤ) {d : ℕ} (t : Tree α d) (ht : Valid key t) : + winner t = none ↔ candidates t = [] := by + have hb := winner_best key t ht + constructor + · intro hn + apply List.eq_nil_iff_forall_not_mem.mpr + intro y hy + obtain ⟨x, hx, _⟩ := hb.2 y hy + simp [hn] at hx + · intro hn + cases hw : winner t with + | none => rfl + | some x => simpa [hn] using hb.1 x hw + +def lookup : {d : ℕ} → Tree α d → (Fin d → Bool) → Option α + | 0, .leaf v, _ => v + | _d + 1, .node _ l r, path => + if path 0 then lookup r (fun i => path i.succ) else lookup l (fun i => path i.succ) + +def replace (key : α → ℤ) : {d : ℕ} → Tree α d → (Fin d → Bool) → Option α → Tree α d + | 0, .leaf _, _, v => .leaf v + | _d + 1, .node _ l r, path, v => + if path 0 then node key l (replace key r (fun i => path i.succ) v) + else node key (replace key l (fun i => path i.succ) v) r + +theorem replace_valid (key : α → ℤ) {d : ℕ} (t : Tree α d) + (ht : Valid key t) (path : Fin d → Bool) (v : Option α) : + Valid key (replace key t path v) := by + induction t with + | leaf _ => trivial + | node w l r ihl ihr => + obtain ⟨_, hl, hr⟩ := ht + simp only [replace] + split + · exact ⟨rfl, hl, ihr hr _⟩ + · exact ⟨rfl, ihl hl _, hr⟩ + +theorem lookup_replace_same (key : α → ℤ) {d : ℕ} (t : Tree α d) + (path : Fin d → Bool) (v : Option α) : lookup (replace key t path v) path = v := by + induction t with + | leaf _ => rfl + | node w l r ihl ihr => + simp only [replace] + split <;> simp_all [node, lookup] + +theorem lookup_replace (key : α → ℤ) {d : ℕ} (t : Tree α d) + (path q : Fin d → Bool) (v : Option α) : + lookup (replace key t path v) q = if path = q then v else lookup t q := by + induction t with + | leaf _ => + have heq : path = q := Subsingleton.elim _ _ + simp [replace, lookup, heq] + | @node d w l r ihl ihr => + have heq : path = q ↔ path 0 = q 0 ∧ + (fun i : Fin d => path i.succ) = (fun i : Fin d => q i.succ) := by + constructor + · intro h + subst q + exact ⟨rfl, rfl⟩ + · rintro ⟨hh, ht⟩ + funext i + exact Fin.cases hh (fun j => congrFun ht j) i + cases hp : path 0 <;> cases hq : q 0 <;> + simp [replace, node, lookup, hp, hq, ihl, ihr, heq] + +def build (key : α → ℤ) : (d : ℕ) → ((Fin d → Bool) → Option α) → Tree α d + | 0, front => .leaf (front Fin.elim0) + | d + 1, front => node key + (build key d (fun p => front (Fin.cons false p))) + (build key d (fun p => front (Fin.cons true p))) + +theorem build_valid (key : α → ℤ) (d : ℕ) (front : (Fin d → Bool) → Option α) : + Valid key (build key d front) := by + induction d with + | zero => trivial + | succ d ih => exact ⟨rfl, ih _, ih _⟩ + +theorem lookup_build (key : α → ℤ) (d : ℕ) (front : (Fin d → Bool) → Option α) + (path : Fin d → Bool) : lookup (build key d front) path = front path := by + induction d with + | zero => + have hpath : (Fin.elim0 : Fin 0 → Bool) = path := Subsingleton.elim _ _ + simpa [build, lookup] using congrArg front hpath + | succ d ih => + simp only [build, node, lookup] + cases hp : path 0 + · simp only [Bool.false_eq_true, ↓reduceIte] + rw [ih] + apply congrArg front + funext i + exact Fin.cases (by simp [hp]) (fun j => by simp) i + · simp only [↓reduceIte] + rw [ih] + apply congrArg front + funext i + exact Fin.cases (by simp [hp]) (fun j => by simp) i + +theorem mem_candidates_iff {d : ℕ} (t : Tree α d) (v : α) : + v ∈ candidates t ↔ ∃ path, lookup t path = some v := by + induction t with + | leaf w => + constructor + · intro hv + exact ⟨Fin.elim0, by simpa [candidates, lookup] using hv⟩ + · rintro ⟨_, hv⟩ + simpa [candidates, lookup] using hv + | @node d w l r ihl ihr => + rw [candidates, List.mem_append, ihl, ihr] + constructor + · rintro (⟨p, hp⟩ | ⟨p, hp⟩) + · exact ⟨Fin.cons false p, by simpa [lookup] using hp⟩ + · exact ⟨Fin.cons true p, by simpa [lookup] using hp⟩ + · rintro ⟨p, hp⟩ + cases h : p 0 + · exact Or.inl ⟨fun i => p i.succ, by simpa [lookup, h] using hp⟩ + · exact Or.inr ⟨fun i => p i.succ, by simpa [lookup, h] using hp⟩ + +theorem winner_le_lookup (key : α → ℤ) {d : ℕ} (t : Tree α d) (ht : Valid key t) + (path : Fin d → Bool) {v : α} (hv : lookup t path = some v) : + ∃ w, winner t = some w ∧ key w ≤ key v := + (winner_best key t ht).2 v ((mem_candidates_iff t v).mpr ⟨path, hv⟩) + +def nodes : {d : ℕ} → Tree α d → ℕ + | 0, .leaf _ => 1 + | _ + 1, .node _ l r => 1 + nodes l + nodes r + +theorem nodes_exact {d : ℕ} (t : Tree α d) : nodes t + 1 = 2 ^ (d + 1) := by + induction t with + | leaf _ => norm_num [nodes] + | @node d w l r ihl ihr => + simp only [nodes] + rw [pow_succ] + omega + +theorem padded_nodes_le (R : ℕ) (t : Tree α (Nat.clog 2 R)) : + nodes t + 1 ≤ 4 * (R + 1) := by + rw [nodes_exact, pow_succ] + by_cases hR : R ≤ 1 + · rw [Nat.clog_of_right_le_one hR] + norm_num + omega + · have hR' : 1 < R := by omega + have hp := Nat.pow_pred_clog_lt_self (by decide : 1 < 2) hR' + have hpos := Nat.clog_pos (by decide : 1 < 2) hR' + have hbits : 2 ^ Nat.clog 2 R ≤ 2 * R := by + rw [show Nat.clog 2 R = (Nat.clog 2 R).pred + 1 from + (Nat.succ_pred_eq_of_pos hpos).symm, pow_succ] + omega + omega + +theorem depth_le_index_bits {R n : ℕ} (hR : R ≤ 2 ^ n) : Nat.clog 2 R ≤ n := + Nat.clog_le_of_le_pow hR + +/-- Number of cached comparisons made by a leaf replacement. -/ +def replaceComparisons : {d : ℕ} → Tree α d → (Fin d → Bool) → ℕ + | 0, .leaf _, _ => 0 + | _d + 1, .node _ l r, path => + 1 + if path 0 then replaceComparisons r (fun i => path i.succ) + else replaceComparisons l (fun i => path i.succ) + +theorem replaceComparisons_eq {d : ℕ} (t : Tree α d) (path : Fin d → Bool) : + replaceComparisons t path = d := by + induction t with + | leaf _ => rfl + | @node d w l r ihl ihr => + simp only [replaceComparisons] + split <;> simp [ihl, ihr, Nat.add_comm] + +end Tournament +end LowSpaceSubsetSum + +end OAI diff --git a/lean/OAI/Combinatorics/LowSpaceSubsetSum/Streams/Trie.lean b/lean/OAI/Combinatorics/LowSpaceSubsetSum/Streams/Trie.lean new file mode 100644 index 0000000000000000000000000000000000000000..a41735adea660f9a27f5ec0575bdc02574340330 --- /dev/null +++ b/lean/OAI/Combinatorics/LowSpaceSubsetSum/Streams/Trie.lean @@ -0,0 +1,248 @@ +import Mathlib.Data.Finset.Card +import Mathlib.Tactic + +namespace OAI + +/-! +# Fixed-width binary dictionaries + +An executable sparse binary trie for fixed-width keys, with exact membership +and insertion semantics and a node-count bound. The array of retained records +is separate; the trie is used to decide whether a key is new. This is the +bounded dictionary component in the paper's stream implementation. +-/ + +namespace LowSpaceSubsetSum +namespace BinaryTrie + +inductive Tree where + | empty + | leaf + | node (zero one : Tree) + deriving DecidableEq + +def contains : Tree → List Bool → Bool + | .empty, _ => false + | .leaf, [] => true + | .leaf, _ :: _ => false + | .node _ _, [] => false + | .node zero one, b :: key => contains (if b then one else zero) key + +def insert : Tree → List Bool → Tree + | _, [] => .leaf + | .node zero one, b :: key => + if b then .node zero (insert one key) else .node (insert zero key) one + | _, b :: key => + if b then .node .empty (insert .empty key) else .node (insert .empty key) .empty + +def nodes : Tree → ℕ + | .empty => 0 + | .leaf => 1 + | .node zero one => 1 + nodes zero + nodes one + +def entries : Tree → ℕ + | .empty => 0 + | .leaf => 1 + | .node zero one => entries zero + entries one + +/-- All present keys have the specified length. Empty subtrees are allowed. -/ +def HasWidth : Tree → ℕ → Prop + | .empty, _ => True + | .leaf, width => width = 0 + | .node _ _, 0 => False + | .node zero one, width + 1 => HasWidth zero width ∧ HasWidth one width + +/-- No internal node is retained if both its branches are empty. -/ +def Compact : Tree → Prop + | .empty => True + | .leaf => True + | .node zero one => Compact zero ∧ Compact one ∧ (zero ≠ .empty ∨ one ≠ .empty) + +theorem insert_ne_empty (t : Tree) (key : List Bool) : insert t key ≠ .empty := by + cases key with + | nil => simp [insert] + | cons b key => cases t <;> cases b <;> simp [insert] + +theorem entries_pos_of_ne_empty {t : Tree} (hc : Compact t) (ht : t ≠ .empty) : + 0 < entries t := by + induction t with + | empty => exact (ht rfl).elim + | leaf => simp [entries] + | node zero one ih0 ih1 => + obtain ⟨hc0, hc1, hne⟩ := hc + rcases hne with h0 | h1 + · have h := ih0 hc0 h0 + simp only [entries] + omega + · have h := ih1 hc1 h1 + simp only [entries] + omega + +theorem insert_hasWidth {t : Tree} {key : List Bool} {width : ℕ} + (ht : HasWidth t width) (hk : key.length = width) : + HasWidth (insert t key) width := by + induction key generalizing t width with + | nil => simp_all [HasWidth, insert] + | cons b key ih => + cases width with + | zero => simp at hk + | succ width => + have hk' : key.length = width := by simpa using hk + cases t with + | empty => + have he := ih (t := .empty) (width := width) trivial hk' + cases b <;> simp [insert, HasWidth, he] + | leaf => simp [HasWidth] at ht + | node zero one => + obtain ⟨h0, h1⟩ := ht + cases b <;> simp [insert, HasWidth, h0, h1, ih h0 hk', ih h1 hk'] + +theorem insert_compact {t : Tree} (ht : Compact t) (key : List Bool) : + Compact (insert t key) := by + induction key generalizing t with + | nil => simp [insert, Compact] + | cons b key ih => + cases t with + | empty => + have he := ih (t := .empty) trivial + cases b <;> simp [insert, Compact, he, insert_ne_empty] + | leaf => + have he := ih (t := .empty) trivial + cases b <;> simp [insert, Compact, he, insert_ne_empty] + | node zero one => + obtain ⟨h0, h1, _⟩ := ht + cases b <;> simp [insert, Compact, h0, h1, ih h0, ih h1, insert_ne_empty] + +/-- The number of retained nodes is linear in key width times distinct keys. -/ +theorem nodes_le_width_mul_entries {t : Tree} {width : ℕ} + (ht : HasWidth t width) (hc : Compact t) : nodes t ≤ (width + 1) * entries t := by + induction t generalizing width with + | empty => simp [nodes, entries] + | leaf => simp [nodes, entries] + | node zero one ih0 ih1 => + cases width with + | zero => exact ht.elim + | succ width => + obtain ⟨hw0, hw1⟩ := ht + obtain ⟨hc0, hc1, hne⟩ := hc + have h0 := ih0 hw0 hc0 + have h1 := ih1 hw1 hc1 + have hp : 0 < entries (.node zero one) := + entries_pos_of_ne_empty ⟨hc0, hc1, hne⟩ (by simp) + simp only [nodes, entries] at * + nlinarith + +/-- One insertion adds a key exactly when membership previously failed. -/ +theorem entries_insert {t : Tree} {key : List Bool} {width : ℕ} + (ht : HasWidth t width) (hk : key.length = width) : + entries (insert t key) = entries t + if contains t key then 0 else 1 := by + induction key generalizing t width with + | nil => + have hw : width = 0 := by simpa using hk.symm + subst width + cases t <;> simp_all [insert, contains, entries, HasWidth] + | cons b key ih => + cases width with + | zero => simp at hk + | succ width => + have hk' : key.length = width := by simpa using hk + cases t with + | empty => + have he := ih (t := .empty) (by trivial) hk' + cases b <;> simp_all [insert, contains, entries] + | leaf => simp [HasWidth] at ht + | node zero one => + obtain ⟨h0, h1⟩ := ht + have he0 := ih h0 hk' + have he1 := ih h1 hk' + cases b <;> simp_all [insert, contains, entries] <;> omega + +/-- Exact set insertion semantics for keys of the fixed width. -/ +theorem contains_insert_iff {t : Tree} {key query : List Bool} {width : ℕ} + (ht : HasWidth t width) (hk : key.length = width) (hq : query.length = width) : + contains (insert t key) query = true ↔ query = key ∨ contains t query = true := by + induction key generalizing t query width with + | nil => + have hw : width = 0 := by simpa using hk.symm + subst width + have hquery : query = [] := List.length_eq_zero_iff.mp hq + subst query + cases t <;> simp_all [insert, contains, HasWidth] + | cons b key ih => + cases query with + | nil => simp at hk hq; omega + | cons qb query => + cases width with + | zero => simp at hk + | succ width => + have hk' : key.length = width := by simpa using hk + have hq' : query.length = width := by simpa using hq + cases t with + | empty => + have hi := ih (t := .empty) (by trivial) hk' hq' + cases b <;> cases qb <;> simp_all [insert, contains] + | leaf => simp [HasWidth] at ht + | node zero one => + obtain ⟨h0, h1⟩ := ht + have hi0 := ih h0 hk' hq' + have hi1 := ih h1 hk' hq' + cases b <;> cases qb <;> simp_all [insert, contains] + +/-- The number of nodes examined by a membership lookup. -/ +def lookupSteps : Tree → List Bool → ℕ + | .node zero one, b :: key => 1 + lookupSteps (if b then one else zero) key + | _, _ => 1 + +theorem lookupSteps_le (t : Tree) (key : List Bool) : + lookupSteps t key ≤ key.length + 1 := by + induction key generalizing t with + | nil => cases t <;> simp [lookupSteps] + | cons b key ih => + cases t with + | empty => simp [lookupSteps] + | leaf => simp [lookupSteps] + | node zero one => + cases b <;> simp only [lookupSteps, Bool.false_eq_true, ↓reduceIte, + List.length_cons] + · have h := ih zero + omega + · have h := ih one + omega + +theorem nodes_insert_le (t : Tree) (key : List Bool) : + nodes (insert t key) ≤ nodes t + key.length + 1 := by + induction key generalizing t with + | nil => cases t <;> simp [insert, nodes] + | cons b key ih => + cases t with + | empty => + have h := ih .empty + simp only [nodes] at h + cases b <;> simp only [insert, nodes, List.length_cons, + Bool.false_eq_true, ↓reduceIte] <;> omega + | leaf => + have h := ih .empty + simp only [nodes] at h + cases b <;> simp only [insert, nodes, List.length_cons, + Bool.false_eq_true, ↓reduceIte] <;> omega + | node zero one => + have h0 := ih zero + have h1 := ih one + cases b <;> simp only [insert, nodes, List.length_cons, + Bool.false_eq_true, ↓reduceIte] <;> omega + +/-- A hard entry capacity also bounds nodes, including a first rejected key. -/ +theorem nodes_insert_le_capacity {t : Tree} {key : List Bool} {width C : ℕ} + (ht : HasWidth t width) (hc : Compact t) (hk : key.length = width) + (hcap : entries t ≤ C) : nodes (insert t key) ≤ (width + 1) * (C + 1) := by + have hn := nodes_le_width_mul_entries (insert_hasWidth ht hk) (insert_compact hc key) + have he := entries_insert ht hk + have hnew : entries (insert t key) ≤ C + 1 := by + rw [he] + split <;> omega + exact hn.trans (Nat.mul_le_mul_left (width + 1) hnew) + +end BinaryTrie +end LowSpaceSubsetSum + +end OAI diff --git a/lean/OAI/Combinatorics/LowSpaceSubsetSum/Streams/WeightEncoding.lean b/lean/OAI/Combinatorics/LowSpaceSubsetSum/Streams/WeightEncoding.lean new file mode 100644 index 0000000000000000000000000000000000000000..6df530efbf701875d5b971849d53064795710ba5 --- /dev/null +++ b/lean/OAI/Combinatorics/LowSpaceSubsetSum/Streams/WeightEncoding.lean @@ -0,0 +1,162 @@ +import OAI.Combinatorics.LowSpaceSubsetSum.Counting.Magnitudes +import OAI.Combinatorics.LowSpaceSubsetSum.Streams.DictionaryPrefixes +import Mathlib.Data.Nat.Bitwise +import Mathlib.Data.List.OfFn + +namespace OAI + +/-! +# Exact fixed-width keys for weights and top masks + +Weights use a sign bit followed by `2u` magnitude bits. Representation keys +append the entire indexed mask, using one bit per input index. Every key has +the same width, even on an outcome where its numerical value is not used. +The input magnitude bounds guarantee injectivity for all actual weights. +-/ + +namespace LowSpaceSubsetSum.WeightEncoding + +def natBits (width value : ℕ) : List Bool := + List.ofFn (fun i : Fin width => value.testBit i.val) + +@[simp] theorem natBits_length (width value : ℕ) : (natBits width value).length = width := by + simp [natBits] + +theorem natBits_injective {width x y : ℕ} (hx : x < 2 ^ width) (hy : y < 2 ^ width) + (h : natBits width x = natBits width y) : x = y := by + have he : (fun i : Fin width => x.testBit i.val) = fun i : Fin width => y.testBit i.val := + List.ofFn_injective h + apply Nat.eq_of_testBit_eq + intro i + by_cases hi : i < width + · exact congrFun he ⟨i, hi⟩ + · have hw : width ≤ i := by omega + have hp := Nat.pow_le_pow_right (by decide : 0 < (2 : ℕ)) hw + rw [Nat.testBit_eq_false_of_lt (hx.trans_le hp), + Nat.testBit_eq_false_of_lt (hy.trans_le hp)] + +def signedBits (width : ℕ) (value : ℤ) : List Bool := + decide (value < 0) :: natBits width value.natAbs + +@[simp] theorem signedBits_length (width : ℕ) (value : ℤ) : + (signedBits width value).length = width + 1 := by simp [signedBits] + +theorem signedBits_injective {width : ℕ} {x y : ℤ} + (hx : x.natAbs < 2 ^ width) (hy : y.natAbs < 2 ^ width) + (h : signedBits width x = signedBits width y) : x = y := by + obtain ⟨hs, hm⟩ := List.cons.inj h + have habs := natBits_injective hx hy hm + have hsign : x < 0 ↔ y < 0 := decide_eq_decide.mp hs + by_cases hn : x < 0 + · have hyn := hsign.mp hn + calc + x = -(x.natAbs : ℤ) := Int.eq_neg_natAbs_of_nonpos hn.le + _ = -(y.natAbs : ℤ) := by rw [habs] + _ = y := (Int.eq_neg_natAbs_of_nonpos hyn.le).symm + · have hyn : ¬ y < 0 := fun h => hn (hsign.mpr h) + calc + x = (x.natAbs : ℤ) := Int.eq_natAbs_of_nonneg (by omega) + _ = (y.natAbs : ℤ) := by rw [habs] + _ = y := (Int.eq_natAbs_of_nonneg (by omega)).symm + +def maskBits {n : ℕ} (S : Finset (Fin n)) : List Bool := + List.ofFn (fun i : Fin n => decide (i ∈ S)) + +@[simp] theorem maskBits_length {n : ℕ} (S : Finset (Fin n)) : + (maskBits S).length = n := by simp [maskBits] + +theorem maskBits_injective {n : ℕ} : Function.Injective (@maskBits n) := by + intro S T h + have he : (fun i : Fin n => decide (i ∈ S)) = fun i : Fin n => decide (i ∈ T) := + List.ofFn_injective h + apply Finset.ext + intro i + exact decide_eq_decide.mp (congrFun he i) + +def weightWidth {n : ℕ} (I : Instance n) : ℕ := 2 * inputScale I + 1 +def entryWidth {n : ℕ} (I : Instance n) : ℕ := weightWidth I + n + +def weightKey {n : ℕ} (I : Instance n) (x : ℤ) : List Bool := + signedBits (2 * inputScale I) x + +def entryKey {n : ℕ} (I : Instance n) (e : Entry (Fin n)) : List Bool := + weightKey I e.value ++ maskBits e.mask + +@[simp] theorem weightKey_length {n : ℕ} (I : Instance n) (x : ℤ) : + (weightKey I x).length = weightWidth I := by simp [weightKey, weightWidth] + +@[simp] theorem entryKey_length {n : ℕ} (I : Instance n) (e : Entry (Fin n)) : + (entryKey I e).length = entryWidth I := by simp [entryKey, entryWidth] + +def BoundedWeight {n : ℕ} (I : Instance n) (x : ℤ) : Prop := + x.natAbs ≤ (2 * n + 1) * 2 ^ inputBits I + +theorem boundedWeight_bits {n : ℕ} (I : Instance n) {x : ℤ} (hx : BoundedWeight I x) : + x.natAbs < 2 ^ (2 * inputScale I) := by + simpa only [sub_zero] using relevant_difference_bits I hx + (show (0 : ℤ).natAbs ≤ (2 * n + 1) * 2 ^ inputBits I by simp) + +theorem weightKey_injective {n : ℕ} (I : Instance n) {x y : ℤ} + (hx : BoundedWeight I x) (hy : BoundedWeight I y) + (h : weightKey I x = weightKey I y) : x = y := + signedBits_injective (boundedWeight_bits I hx) (boundedWeight_bits I hy) h + +theorem weightKey_eq_iff {n : ℕ} (I : Instance n) {x y : ℤ} + (hx : BoundedWeight I x) (hy : BoundedWeight I y) : + weightKey I x = weightKey I y ↔ x = y := + ⟨weightKey_injective I hx hy, congrArg (weightKey I)⟩ + +theorem entryKey_injective {n : ℕ} (I : Instance n) {e f : Entry (Fin n)} + (he : BoundedWeight I e.value) (hf : BoundedWeight I f.value) + (h : entryKey I e = entryKey I f) : e = f := by + have hw : (weightKey I e.value).length = (weightKey I f.value).length := by simp + have hp := List.append_inj h hw + have hv := weightKey_injective I he hf hp.1 + have hm := maskBits_injective hp.2 + cases e + cases f + simp_all + +theorem signed_weight_bounded {n : ℕ} (I : Instance n) (F S : Finset (Fin n)) : + BoundedWeight I (weight (flip (fun i => (I.values i : ℤ)) F) S) := by + exact (signed_weight_natAbs_le I F S).trans (Nat.mul_le_mul_right _ (by omega)) + +theorem signed_target_bounded {n : ℕ} (I : Instance n) (F : Finset (Fin n)) : + BoundedWeight I ((I.target : ℤ) - weight (fun i => (I.values i : ℤ)) F) := by + exact (signed_target_natAbs_le I F).trans (Nat.mul_le_mul_right _ (by omega)) + +theorem raw_signed_weight_bounded {n : ℕ} (I : Instance n) + (F : Finset (Fin n)) (xs : List (Fin n)) (hlen : xs.length ≤ 2 * n) : + BoundedWeight I (occurrenceWeight (flip (fun i => (I.values i : ℤ)) F) xs) := by + exact (raw_signed_weight_natAbs_le I F xs hlen).trans (Nat.mul_le_mul_right _ (by omega)) + +/-- The exact number of encoded bits is linear in the original input scale. -/ +theorem widths_le {n : ℕ} (I : Instance n) : + weightWidth I ≤ 2 * inputScale I + 1 ∧ entryWidth I ≤ 3 * inputScale I + 1 := by + dsimp only [weightWidth, entryWidth, inputScale] + omega + +theorem weight_lookup_steps {n : ℕ} (I : Instance n) (t : BinaryTrie.Tree) (x : ℤ) : + BinaryTrie.lookupSteps t (weightKey I x) ≤ 2 * inputScale I + 2 := by + simpa only [weightKey_length, weightWidth, Nat.add_assoc] using + BinaryTrie.lookupSteps_le t (weightKey I x) + +theorem entry_lookup_steps {n : ℕ} (I : Instance n) (t : BinaryTrie.Tree) + (e : Entry (Fin n)) : + BinaryTrie.lookupSteps t (entryKey I e) ≤ 3 * inputScale I + 2 := by + exact (BinaryTrie.lookupSteps_le t (entryKey I e)).trans (by + rw [entryKey_length] + have h := (widths_le I).2 + omega) + +theorem entry_insert_nodes {n C : ℕ} (I : Instance n) {t : BinaryTrie.Tree} + (ht : BinaryTrie.HasWidth t (entryWidth I)) (hc : BinaryTrie.Compact t) + (hcap : BinaryTrie.entries t ≤ C) (e : Entry (Fin n)) : + BinaryTrie.nodes (BinaryTrie.insert t (entryKey I e)) ≤ + (3 * inputScale I + 2) * (C + 1) := by + apply (BinaryTrie.nodes_insert_le_capacity ht hc (entryKey_length I e) hcap).trans + exact Nat.mul_le_mul_right _ (by have h := (widths_le I).2; omega) + +end LowSpaceSubsetSum.WeightEncoding + +end OAI diff --git a/lean/OAI/Combinatorics/LowSpaceSubsetSum/Word/WordActionBounds.lean b/lean/OAI/Combinatorics/LowSpaceSubsetSum/Word/WordActionBounds.lean new file mode 100644 index 0000000000000000000000000000000000000000..825a55442e34e9cab282626863c7a6659f85af1c --- /dev/null +++ b/lean/OAI/Combinatorics/LowSpaceSubsetSum/Word/WordActionBounds.lean @@ -0,0 +1,229 @@ +import OAI.Combinatorics.LowSpaceSubsetSum.Word.WordDecisionRound + +namespace OAI + +/-! # Prepared-action costs on every finite word stream + +These counters account for the prepared action after seed generation. Seed +construction work and its live buffer are separate from these bounds. +-/ + +noncomputable section +namespace LowSpaceSubsetSum.WordActionBounds + +variable {n : ℕ} + +private theorem pow_product_positive (u H k : ℕ) (hu : 0 < u) (hH : 0 < H) : + 1 ≤ u^k*H := Nat.mul_pos (Nat.pow_pos hu) hH + +private theorem pow_product_mono (u H j k : ℕ) (hu : 0 < u) (hH : 1 ≤ H) + (hjk : j ≤ k) : u^j ≤ u^k*H := + (Nat.pow_le_pow_right hu hjk).trans (Nat.le_mul_of_pos_right _ hH) + +private theorem combine_work (c r : (Bool × ℕ) × ℕ) (T : ℕ) + (hc : c.1.2 ≤ T) (hr : r.1.2 ≤ T) : + (WordDecisionRound.combine c r).1.2 ≤ 2*T+3 := by + change c.1.2+r.1.2+3 ≤ 2*T+3 + omega + +private theorem round_work_generic (I : Instance n) (hn : 180000000 ≤ n) + (hlog : Real.logb 2 ((mixerSize n : ℝ)+1)+1 ≤ (n : ℝ)/1000) + (words : WordDecisionRound.Words I) (T : ℕ) + (hc : (WordDecisionBranches.compression I (by omega) words.1).1.2 ≤ T) + (hr : (WordDecisionBranches.representation I (by omega) hlog words.2).1.2 ≤ T) : + (WordDecisionRound.run I hn hlog words).1.2 ≤ 2*T+3 := + combine_work _ _ T hc hr + +private theorem combine_cells (c r : (Bool × ℕ) × ℕ) (L : ℕ) + (hc : c.2 ≤ L) (hr : r.2 ≤ 36*L) (hL : 24 ≤ L) : + (WordDecisionRound.combine c r).2 ≤ 40*L := by + change max c.2 (r.2+8)+16 ≤ 40*L + omega + +private theorem scale_large (u C : ℕ) (hu : 10000 ≤ u) : 24 ≤ u^14*(C+1) := by + have hp : u ≤ u^14 := by + simpa only [pow_one] using Nat.pow_le_pow_right (by omega : 0 < u) (by decide : 1 ≤ 14) + have hm : u^14 ≤ u^14*(C+1) := Nat.le_mul_of_pos_right _ (by omega) + omega + +private theorem law_nonempty {Ω : Type} [Fintype Ω] (μ : FiniteLaw Ω) : Nonempty Ω := by + classical + by_contra h + let : IsEmpty Ω := ⟨fun x => h ⟨x⟩⟩ + have ht := μ.total + simp at ht + +theorem compression_source_work (I : Instance n) (hn : 180000000 ≤ n) + (hscale : Real.logb 2 (inputScale I : ℝ) ≤ (n : ℝ)/1000000000) + (s : ((CompressionData.mk I).sampler (by omega)).Seed) : + (SampledCompressionCells.run (CompressionData.mk I) (by omega) s).1.2 ≤ + inputScale I^501*2^((n+1)/2) := by + let R := (canonicalRepresentationData I).zeroSetup.bucketHistoryCoupling (by omega : 10000 ≤ n) + let t : R.Seed := Classical.choice (law_nonempty R.law) + have h := PreparedDecisionWork.round I hn (roundLogBudget I (by omega) hscale) hscale (s,t) + dsimp only [PreparedDecisionRound.run] at h + rw [SampledCompressionCells.value] + omega + +theorem representation_source_work (I : Instance n) (hn : 180000000 ≤ n) + (hlog : Real.logb 2 ((mixerSize n : ℝ)+1)+1 ≤ (n : ℝ)/1000) + (hscale : Real.logb 2 (inputScale I : ℝ) ≤ (n : ℝ)/1000000000) + (s : ((canonicalRepresentationData I).zeroSetup.bucketHistoryCoupling (by omega)).Seed) : + (WordDecisionBranches.representationAction I (by omega) hlog s).1.2 ≤ + inputScale I^501*2^((n+1)/2) := by + let C := (CompressionData.mk I).sampler (by omega : 168000000 ≤ n) + let t : C.Seed := Classical.choice (law_nonempty C.law) + have h := PreparedDecisionWork.round I hn hlog hscale (t,s) + dsimp only [PreparedDecisionRound.run] at h + simp only [WordDecisionBranches.representationAction,RepresentationTrialCells.value] + omega + +theorem compression_work (I : Instance n) (hn : 180000000 ≤ n) + (hscale : Real.logb 2 (inputScale I : ℝ) ≤ (n : ℝ)/1000000000) + (words : WordDecisionBranches.CompressionWords I) : + (WordDecisionBranches.compression I (by omega) words).1.2 ≤ + inputScale I^501*2^((n+1)/2) := by + unfold WordDecisionBranches.compression WordSeedRealization.execute + split + · have hu : 0 < inputScale I := by unfold inputScale; omega + exact pow_product_positive (inputScale I) (2^((n+1)/2)) 501 hu (Nat.two_pow_pos _) + · exact compression_source_work I hn hscale _ + +theorem representation_work (I : Instance n) (hn : 180000000 ≤ n) + (hlog : Real.logb 2 ((mixerSize n : ℝ)+1)+1 ≤ (n : ℝ)/1000) + (hscale : Real.logb 2 (inputScale I : ℝ) ≤ (n : ℝ)/1000000000) + (words : WordDecisionBranches.RepresentationWords I) : + (WordDecisionBranches.representation I (by omega) hlog words).1.2 ≤ + inputScale I^501*2^((n+1)/2) := by + unfold WordDecisionBranches.representation WordSeedRealization.execute + split + · have hu : 0 < inputScale I := by unfold inputScale; omega + exact pow_product_positive (inputScale I) (2^((n+1)/2)) 501 hu (Nat.two_pow_pos _) + · exact representation_source_work I hn hlog hscale _ + +private theorem combine_majorize (u H k W : ℕ) (hu : 3 ≤ u) (hH : 1 ≤ H) + (hk : 1 ≤ k) (hW : W ≤ 2*(u^k*H)+3) : W ≤ u^(k+1)*H := by + have hp : u ≤ u^k := by simpa only [pow_one] using Nat.pow_le_pow_right (by omega : 0 < u) hk + have hm : u^k ≤ u^k*H := Nat.le_mul_of_pos_right _ hH + calc + W ≤ 3*(u^k*H) := by omega + _ ≤ u*(u^k*H) := Nat.mul_le_mul_right _ hu + _ = _ := by rw [←Nat.mul_assoc,←pow_succ'] + +theorem round_work (I : Instance n) (hn : 180000000 ≤ n) + (hlog : Real.logb 2 ((mixerSize n : ℝ)+1)+1 ≤ (n : ℝ)/1000) + (hscale : Real.logb 2 (inputScale I : ℝ) ≤ (n : ℝ)/1000000000) + (words : WordDecisionRound.Words I) : + (WordDecisionRound.run I hn hlog words).1.2 ≤ inputScale I^502*2^((n+1)/2) := by + have h := combine_majorize (inputScale I) (2^((n+1)/2)) 501 _ + (by unfold inputScale; omega) Nat.one_le_two_pow (by decide) + (round_work_generic I hn hlog words _ (compression_work I hn hscale words.1) + (representation_work I hn hlog hscale words.2)) + rw [show (501 : ℕ)+1 = 502 from rfl] at h + exact h + +theorem compression_cells (I : Instance n) (hn : 180000000 ≤ n) + (words : WordDecisionBranches.CompressionWords I) : + (WordDecisionBranches.compression I (by omega) words).2 ≤ + inputScale I^12*(compressionDictionaryCapacity n+1) := by + unfold WordDecisionBranches.compression WordSeedRealization.execute + split + · have hu : 10000 ≤ inputScale I := by unfold inputScale; omega + have hp : inputScale I ≤ inputScale I^12 := by + simpa only [pow_one] using Nat.pow_le_pow_right (by omega : 1 ≤ inputScale I) + (by decide : 1 ≤ 12) + have hm := Nat.le_mul_of_pos_right (inputScale I^12) + (show 0 < compressionDictionaryCapacity n+1 by omega) + exact (by omega : 8 ≤ inputScale I^12*(compressionDictionaryCapacity n+1)) + · exact SampledCompressionCells.cells _ (by omega) _ + +theorem representation_cells (I : Instance n) (hn : 180000000 ≤ n) + (hlog : Real.logb 2 ((mixerSize n : ℝ)+1)+1 ≤ (n : ℝ)/1000) + (hscale : Real.logb 2 (inputScale I : ℝ) ≤ (n : ℝ)/1000000000) + (words : WordDecisionBranches.RepresentationWords I) : + (WordDecisionBranches.representation I (by omega) hlog words).2 ≤ + 36*inputScale I^14*(compressionDictionaryCapacity n+1) := by + unfold WordDecisionBranches.representation WordSeedRealization.execute + split + · have hp : 1 ≤ inputScale I^14 := Nat.one_le_pow _ _ (by unfold inputScale; omega) + have hm : inputScale I^14 ≤ inputScale I^14*(compressionDictionaryCapacity n+1) := + Nat.le_mul_of_pos_right _ (by omega) + nlinarith only [hp,hm] + · exact RepresentationTrialCells.cells I (by omega) hlog hscale _ _ + +theorem round_cells (I : Instance n) (hn : 180000000 ≤ n) + (hlog : Real.logb 2 ((mixerSize n : ℝ)+1)+1 ≤ (n : ℝ)/1000) + (hscale : Real.logb 2 (inputScale I : ℝ) ≤ (n : ℝ)/1000000000) + (words : WordDecisionRound.Words I) : + (WordDecisionRound.run I hn hlog words).2 ≤ + 40*inputScale I^14*(compressionDictionaryCapacity n+1) := by + let L := inputScale I^14*(compressionDictionaryCapacity n+1) + have hu : 10000 ≤ inputScale I := by unfold inputScale; omega + have hc : (WordDecisionBranches.compression I (by omega) words.1).2 ≤ L := + (compression_cells I hn words.1).trans + (Nat.mul_le_mul_right _ (Nat.pow_le_pow_right (n := inputScale I) + (by omega) (by decide : 12 ≤ 14))) + have hr : (WordDecisionBranches.representation I (by omega) hlog words.2).2 ≤ 36*L := by + apply (representation_cells I hn hlog hscale words.2).trans + exact le_of_eq (Nat.mul_assoc _ _ _) + have h := combine_cells _ _ L hc hr (scale_large _ _ hu) + exact h.trans (le_of_eq (Nat.mul_assoc _ _ _).symm) + +private theorem repeat_majorize (u H r k W : ℕ) (hu : 3 ≤ u) (hH : 1 ≤ H) + (hW : W ≤ u^r*(u^k*H+1)+1) : W ≤ u^(r+k+1)*H := by + have hp : u^r ≤ u^(r+k)*H := pow_product_mono u H r (r+k) (by omega) hH (by omega) + have hs : 1 ≤ u^(r+k)*H := pow_product_positive u H (r+k) (by omega) hH + have he : u^r*(u^k*H) = u^(r+k)*H := by rw [←Nat.mul_assoc,←pow_add] + rw [Nat.mul_add,Nat.mul_one,he] at hW + calc + W ≤ 3*(u^(r+k)*H) := by omega + _ ≤ u*(u^(r+k)*H) := Nat.mul_le_mul_right _ hu + _ = _ := by rw [←Nat.mul_assoc,←pow_succ'] + +theorem repeated_work (I : Instance n) (hn : 180000000 ≤ n) + (hscale : Real.logb 2 (inputScale I : ℝ) ≤ (n : ℝ)/1000000000) + (words : Fin (inputScale I^120) → WordDecisionRound.Words I) : + (WordDecisionRound.repeated I hn hscale words).1.2 ≤ + inputScale I^623*2^((n+1)/2) := by + rw [WordDecisionRound.repeated,DecisionRepetitionCells.value] + have h := repeat_majorize (inputScale I) (2^((n+1)/2)) 120 502 _ + (by unfold inputScale; omega) Nat.one_le_two_pow + (DecisionRepetition.work _ words _ + (round_work I hn (roundLogBudget I (by omega) hscale) hscale)) + rw [show (120 : ℕ)+502+1 = 623 from rfl] at h + exact h + +theorem repeated_cells (I : Instance n) (hn : 180000000 ≤ n) + (hscale : Real.logb 2 (inputScale I : ℝ) ≤ (n : ℝ)/1000000000) + (words : Fin (inputScale I^120) → WordDecisionRound.Words I) : + (WordDecisionRound.repeated I hn hscale words).2 ≤ writableWordLimit I := by + let u := inputScale I + let C := compressionDictionaryCapacity n + have hu : 10000 ≤ u := by unfold u inputScale; omega + have hC : 1 ≤ C := Nat.one_le_pow _ _ (by decide) + have h := DecisionRepetitionCells.cells + (WordDecisionRound.run I hn (roundLogBudget I (by omega) hscale)) words + (40*u^14*(C+1)) (round_cells I hn _ hscale) + change (WordDecisionRound.repeated I hn hscale words).2 ≤ 40*u^14*(C+1)+8 at h + apply h.trans + change 40*u^14*(C+1)+8 ≤ u^15*C + have hc : C+1 ≤ 2*C := by omega + have hs : 40*u^14*(C+1) ≤ 80*u^14*C := by + calc + _ ≤ 40*u^14*(2*C) := Nat.mul_le_mul_left _ hc + _ = _ := by ring + have h8 : 8 ≤ u^14*C := by + have hpow : u ≤ u^14 := by + simpa only [pow_one] using Nat.pow_le_pow_right (by omega : 0 < u) (by decide : 1 ≤ 14) + exact (show 8 ≤ u by omega).trans (hpow.trans (Nat.le_mul_of_pos_right _ hC)) + have ht : 81*u^14*C ≤ u^15*C := by + calc + _ ≤ u*u^14*C := Nat.mul_le_mul_right _ (Nat.mul_le_mul_right _ (by omega)) + _ = _ := by rw [←pow_succ'] + nlinarith only [hs,ht,h8] + +end LowSpaceSubsetSum.WordActionBounds + +end + +end OAI diff --git a/lean/OAI/Combinatorics/LowSpaceSubsetSum/Word/WordAddressBounds.lean b/lean/OAI/Combinatorics/LowSpaceSubsetSum/Word/WordAddressBounds.lean new file mode 100644 index 0000000000000000000000000000000000000000..712a2b46a0b0e0b88a8d5fac1fc4868a648789f5 --- /dev/null +++ b/lean/OAI/Combinatorics/LowSpaceSubsetSum/Word/WordAddressBounds.lean @@ -0,0 +1,77 @@ +import OAI.Combinatorics.LowSpaceSubsetSum.Word.WordSamplingBounds +import OAI.Combinatorics.LowSpaceSubsetSum.Search.PreparedAsymptotics + +namespace OAI + +/-! # Finite random-word addresses fit the fixed machine word -/ + +noncomputable section +namespace LowSpaceSubsetSum.WordAddressBounds + +def roundReads (n : ℕ) : ℕ := n*n^3+n^3+WordRealization.historyReads n + +def totalReads {n : ℕ} (I : Instance n) : ℕ := inputScale I^120*roundReads n + +theorem round_reads {n : ℕ} (I : Instance n) (hn : 10000 ≤ n) : + roundReads n ≤ inputScale I^6*(compressionDictionaryCapacity n+1) := by + let u := inputScale I + let C := compressionDictionaryCapacity n + have hu : 10000 ≤ u := by unfold u inputScale; omega + have hnu : n ≤ u := by unfold u inputScale; omega + have hp : n*n^3+n^3 ≤ 2*u^4 := by + have h1 : n*n^3 ≤ u^4 := by + simpa only [←pow_succ'] using Nat.mul_le_mul hnu (Nat.pow_le_pow_left hnu 3) + have h2 : n^3 ≤ u^4 := (Nat.pow_le_pow_left hnu 3).trans + (Nat.pow_le_pow_right (by omega) (by decide : 3 ≤ 4)) + omega + have hh := WordSamplingBounds.history_reads I hn + change WordRealization.historyReads n ≤ u^5*(C+1) at hh + have hs : 2*u^4 ≤ u^5*(C+1) := by + have h1 : 2*u^4 ≤ u*u^4 := Nat.mul_le_mul_right _ (by omega) + have h2 : u^5 ≤ u^5*(C+1) := Nat.le_mul_of_pos_right _ (by omega) + rw [←pow_succ'] at h1 + exact h1.trans h2 + have hround : roundReads n ≤ 2*(u^5*(C+1)) := by + unfold roundReads + omega + apply hround.trans + calc + _ ≤ u*(u^5*(C+1)) := Nat.mul_le_mul_right _ (by omega) + _ = _ := by rw [←Nat.mul_assoc,←pow_succ'] + +theorem total_reads {n : ℕ} (I : Instance n) (hn : 10000 ≤ n) : + totalReads I ≤ inputScale I^126*(compressionDictionaryCapacity n+1) := by + have h := Nat.mul_le_mul_left (inputScale I^120) (round_reads I hn) + simpa only [totalReads,←Nat.mul_assoc,←pow_add] using h + +theorem total_limit {n : ℕ} (I : Instance n) (hn : 10000 ≤ n) + (hscale : Real.logb 2 (inputScale I : ℝ) ≤ (n : ℝ)/1000000000) : + totalReads I < 2^n := by + have hu : (0 : ℝ) < inputScale I := by + exact_mod_cast (show 0 < inputScale I by unfold inputScale; omega) + have hC : (1 : ℝ) ≤ compressionDictionaryCapacity n := by + exact_mod_cast (show 1 ≤ compressionDictionaryCapacity n from Nat.one_le_two_pow) + have hc := PreparedAsymptotics.capacity_upper n + have hsum : (compressionDictionaryCapacity n : ℝ)+1 ≤ + (2 : ℝ)^((199/1000 : ℝ)*n+1) := by + rw [Real.rpow_add (by norm_num : (0 : ℝ) < 2),Real.rpow_one] + linarith only [hC,hc] + have hs := mul_le_mul_of_nonneg_left hsum + (show 0 ≤ (inputScale I : ℝ)^126 by positivity) + have ht := guarded_polynomial_exponential hn hu hscale 126 + (a := (199/1000 : ℝ)) (by norm_num) + have hb : ((totalReads I : ℕ) : ℝ) ≤ + (inputScale I : ℝ)^126*((compressionDictionaryCapacity n : ℝ)+1) := by + exact_mod_cast total_reads I hn + have hfin := hb.trans_lt (hs.trans_lt ht) + exact_mod_cast hfin + +theorem total_fits {n : ℕ} (I : Instance n) (hn : 10000 ≤ n) + (hscale : Real.logb 2 (inputScale I : ℝ) ≤ (n : ℝ)/1000000000) : + totalReads I < 2^wordWidth I := cutoff_fits_word I (total_limit I hn hscale) + +end LowSpaceSubsetSum.WordAddressBounds + +end + +end OAI diff --git a/lean/OAI/Combinatorics/LowSpaceSubsetSum/Word/WordCandidateExecution.lean b/lean/OAI/Combinatorics/LowSpaceSubsetSum/Word/WordCandidateExecution.lean new file mode 100644 index 0000000000000000000000000000000000000000..23ec3933978384ad959e2231262f8a9c0f666258 --- /dev/null +++ b/lean/OAI/Combinatorics/LowSpaceSubsetSum/Word/WordCandidateExecution.lean @@ -0,0 +1,149 @@ +import OAI.Combinatorics.LowSpaceSubsetSum.Word.WordSeedExecution +import OAI.Combinatorics.LowSpaceSubsetSum.Word.WordSeedConstructors + +namespace OAI + +/-! # Materializing the actual words used by bounded rejection + +The modulus is an already computed scalar argument. Each tail step reads +one word, reduces it modulo that scalar, and pushes the result into the +candidate array. The array is retained as part of the successful seed. +The counter charges five scalar operations per step and the final return; +the cell trace permits both the old and new array during a push. +-/ + +namespace LowSpaceSubsetSum.WordCandidateExecution + +variable {w k : ℕ} + +def low (modulus : ℕ) (hm : modulus = 2^k) (x : Fin (2^w)) : Fin (2^k) := + ⟨x.val % modulus, by rw [hm]; exact Nat.mod_lt _ (by positivity)⟩ + +theorem low_eq (modulus : ℕ) (hm : modulus = 2^k) (x : Fin (2^w)) : + low modulus hm x = ExactWordDraw.low w k x := by + subst modulus + rfl + +structure Raw (k : ℕ) where + data : Array (Fin (2^k)) + cursor : ℕ + work : ℕ + cells : ℕ + +def loop (stream : ℕ → Fin (2^w)) (modulus : ℕ) (hm : modulus = 2^k) : + ℕ → ℕ → Array (Fin (2^k)) → ℕ → ℕ → Raw k + | 0, cursor, acc, work, peak => + ⟨acc, cursor, work+1, max peak (2*acc.size+12)⟩ + | fuel+1, cursor, acc, work, peak => + let x := low modulus hm (stream cursor) + loop stream modulus hm fuel (cursor+1) (acc.push x) (work+5) + (max peak (2*(acc.size+1)+12)) + +theorem loop_data (stream : ℕ → Fin (2^w)) (modulus : ℕ) (hm : modulus = 2^k) + (fuel cursor : ℕ) (acc : Array (Fin (2^k))) (work peak : ℕ) : + (loop stream modulus hm fuel cursor acc work peak).data.toList = + acc.toList ++ List.ofFn (fun i : Fin fuel => low modulus hm (stream (cursor+i.val))) := by + induction fuel generalizing cursor acc work peak with + | zero => + change acc.toList = acc.toList ++ List.ofFn (fun i : Fin 0 => _) + simp only [List.ofFn_zero,List.append_nil] + | succ fuel ih => + change (loop stream modulus hm fuel (cursor+1) + (acc.push (low modulus hm (stream cursor))) (work+5) + (max peak (2*(acc.size+1)+12))).data.toList = _ + rw [ih] + simp only [Array.toList_push,List.ofFn_succ,Fin.val_zero,Nat.add_zero, + Fin.val_succ,List.append_assoc,List.singleton_append] + congr 2 + congr 1 + funext i + congr 2 + omega + +theorem loop_size (stream : ℕ → Fin (2^w)) (modulus : ℕ) (hm : modulus = 2^k) + (fuel cursor : ℕ) (acc : Array (Fin (2^k))) (work peak : ℕ) : + (loop stream modulus hm fuel cursor acc work peak).data.size = acc.size+fuel := by + have h := congrArg List.length (loop_data stream modulus hm fuel cursor acc work peak) + simpa only [Array.length_toList,List.length_append,List.length_ofFn] using h + +theorem loop_cursor (stream : ℕ → Fin (2^w)) (modulus : ℕ) (hm : modulus = 2^k) + (fuel cursor : ℕ) (acc : Array (Fin (2^k))) (work peak : ℕ) : + (loop stream modulus hm fuel cursor acc work peak).cursor = cursor+fuel := by + induction fuel generalizing cursor acc work peak with + | zero => rfl + | succ fuel ih => + change (loop stream modulus hm fuel (cursor+1) + (acc.push (low modulus hm (stream cursor))) (work+5) + (max peak (2*(acc.size+1)+12))).cursor = _ + rw [ih] + omega + +theorem loop_work (stream : ℕ → Fin (2^w)) (modulus : ℕ) (hm : modulus = 2^k) + (fuel cursor : ℕ) (acc : Array (Fin (2^k))) (work peak : ℕ) : + (loop stream modulus hm fuel cursor acc work peak).work = work+5*fuel+1 := by + induction fuel generalizing cursor acc work peak with + | zero => + change work+1 = work+5*0+1 + omega + | succ fuel ih => + change (loop stream modulus hm fuel (cursor+1) + (acc.push (low modulus hm (stream cursor))) (work+5) + (max peak (2*(acc.size+1)+12))).work = _ + rw [ih] + omega + +theorem loop_cells (stream : ℕ → Fin (2^w)) (modulus : ℕ) (hm : modulus = 2^k) + (fuel cursor : ℕ) (acc : Array (Fin (2^k))) (work peak : ℕ) : + (loop stream modulus hm fuel cursor acc work peak).cells ≤ + max peak (2*(acc.size+fuel)+12) := by + induction fuel generalizing cursor acc work peak with + | zero => + change max peak (2*acc.size+12) ≤ max peak (2*(acc.size+0)+12) + omega + | succ fuel ih => + change (loop stream modulus hm fuel (cursor+1) + (acc.push (low modulus hm (stream cursor))) (work+5) + (max peak (2*(acc.size+1)+12))).cells ≤ _ + refine (ih _ _ _ _).trans ?_ + simp only [Array.size_push] + omega + +structure Buffer (k N : ℕ) where + data : Vector (Fin (2^k)) N + cursor : ℕ + work : ℕ + cells : ℕ + +def run (stream : ℕ → Fin (2^w)) (modulus : ℕ) (hm : modulus = 2^k) + (N cursor : ℕ) : Buffer k N := + let r := loop stream modulus hm N cursor #[] 0 0 + ⟨⟨r.data, by simpa only [Array.size_empty,Nat.zero_add] using + loop_size stream modulus hm N cursor #[] 0 0⟩, + r.cursor,r.work,r.cells⟩ + +theorem run_data (stream : ℕ → Fin (2^w)) (modulus : ℕ) (hm : modulus = 2^k) + (N cursor : ℕ) : + (run stream modulus hm N cursor).data = Vector.ofFn + (fun i : Fin N => ExactWordDraw.low w k (stream (cursor+i.val))) := by + apply Vector.toArray_inj.mp + apply Array.toList_inj.mp + simpa only [run,Array.toList_empty,List.nil_append,low_eq, + Vector.toArray_ofFn,Array.toList_ofFn] using + loop_data stream modulus hm N cursor #[] 0 0 + +theorem run_cursor (stream : ℕ → Fin (2^w)) (modulus : ℕ) (hm : modulus = 2^k) + (N cursor : ℕ) : (run stream modulus hm N cursor).cursor = cursor+N := + loop_cursor stream modulus hm N cursor #[] 0 0 + +theorem run_work (stream : ℕ → Fin (2^w)) (modulus : ℕ) (hm : modulus = 2^k) + (N cursor : ℕ) : (run stream modulus hm N cursor).work = 5*N+1 := by + simpa only [run,Nat.zero_add] using loop_work stream modulus hm N cursor #[] 0 0 + +theorem run_cells (stream : ℕ → Fin (2^w)) (modulus : ℕ) (hm : modulus = 2^k) + (N cursor : ℕ) : (run stream modulus hm N cursor).cells ≤ 2*N+12 := by + simpa only [run,Array.size_empty,Nat.zero_add,Nat.zero_max] using + loop_cells stream modulus hm N cursor #[] 0 0 + +end LowSpaceSubsetSum.WordCandidateExecution + +end OAI diff --git a/lean/OAI/Combinatorics/LowSpaceSubsetSum/Word/WordDecisionBranches.lean b/lean/OAI/Combinatorics/LowSpaceSubsetSum/Word/WordDecisionBranches.lean new file mode 100644 index 0000000000000000000000000000000000000000..5994f7b8e02e440db41b3a8d6ffa5ba25098f7b7 --- /dev/null +++ b/lean/OAI/Combinatorics/LowSpaceSubsetSum/Word/WordDecisionBranches.lean @@ -0,0 +1,144 @@ +import OAI.Combinatorics.LowSpaceSubsetSum.Representation.RepresentationTrialCells +import OAI.Combinatorics.LowSpaceSubsetSum.Compression.SampledCompressionCells +import OAI.Combinatorics.LowSpaceSubsetSum.Search.PreparedDecisionWork +import OAI.Combinatorics.LowSpaceSubsetSum.Storage.DecisionRepetitionCells +import OAI.Combinatorics.LowSpaceSubsetSum.Word.WordSeedHistory +import OAI.Combinatorics.LowSpaceSubsetSum.Word.WordSeedExecution +import OAI.Combinatorics.LowSpaceSubsetSum.Word.WordSamplingBounds + +namespace OAI + +/-! # The two prepared branches driven by finite fair-word streams + +The returned work counter measures the prepared action. The number of words +read by seed generation has its own bound; generation arithmetic is separate. +-/ + +noncomputable section +namespace LowSpaceSubsetSum.WordDecisionBranches + +variable {n : ℕ} + +def compressionSampler (I : Instance n) (hn : 168000000 ≤ n) := + WordSeedRealization.compression (CompressionData.mk I) hn (wordWidth I) + ((Nat.clog_le_of_le_pow Nat.lt_two_pow_self.le).trans (by + unfold wordWidth inputScale; omega)) + (by unfold compressionPrimeExponent wordWidth inputScale; omega) + +def representationSampler (I : Instance n) (hn : 10000 ≤ n) := + WordSeedRealization.bucketHistory (canonicalRepresentationData I).zeroSetup hn + (wordWidth I) (WordSamplingBounds.word_width I) + +abbrev CompressionWords (I : Instance n) := Fin (n*n^3+n^3) → Fin (2^wordWidth I) +abbrev RepresentationWords (I : Instance n) := + Fin (WordRealization.historyReads n) → Fin (2^wordWidth I) + +def compression (I : Instance n) (hn : 168000000 ≤ n) (words : CompressionWords I) := + WordSeedRealization.execute (compressionSampler I hn) + (SampledCompressionCells.run (CompressionData.mk I) hn) ((false,1),8) words + +def representationAction (I : Instance n) (hn : 10000 ≤ n) + (hlog : Real.logb 2 ((mixerSize n : ℝ)+1)+1 ≤ (n : ℝ)/1000) + (s : ((canonicalRepresentationData I).zeroSetup.bucketHistoryCoupling hn).Seed) := + let out := RepresentationTrialCells.run I hn hlog s (2*trialWatchdog I) + ((match out.1.1 with | none => false | some (yes,_) => yes,out.1.2),out.2) + +def representation (I : Instance n) (hn : 10000 ≤ n) + (hlog : Real.logb 2 ((mixerSize n : ℝ)+1)+1 ≤ (n : ℝ)/1000) + (words : RepresentationWords I) := + WordSeedRealization.execute (representationSampler I hn) + (representationAction I hn hlog) ((false,1),8) words + +theorem representationAction_value (I : Instance n) (hn : 10000 ≤ n) + (hlog : Real.logb 2 ((mixerSize n : ℝ)+1)+1 ≤ (n : ℝ)/1000) + (s : ((canonicalRepresentationData I).zeroSetup.bucketHistoryCoupling hn).Seed) : + (representationAction I hn hlog s).1.1 = + RepresentationPreparedAcceptance.accept I hn hlog s := by + change (match (RepresentationTrialCells.run I hn hlog s (2*trialWatchdog I)).1.1 with + | none => false | some (yes,_) => yes) = _ + rw [RepresentationTrialCells.value] + rfl + +theorem compression_value (I : Instance n) (hn : 168000000 ≤ n) + (words : CompressionWords I) : + (compression I hn words).1.1 = WordSeedRealization.execute (compressionSampler I hn) + (fun s => (SampledCompressionTrial.run (CompressionData.mk I) hn s).1) false words := by + unfold compression WordSeedRealization.execute + split + · rfl + · exact congrArg Prod.fst (SampledCompressionCells.value _ _ _) + +theorem representation_value (I : Instance n) (hn : 10000 ≤ n) + (hlog : Real.logb 2 ((mixerSize n : ℝ)+1)+1 ≤ (n : ℝ)/1000) + (words : RepresentationWords I) : + (representation I hn hlog words).1.1 = + WordSeedRealization.execute (representationSampler I hn) + (RepresentationPreparedAcceptance.accept I hn hlog) false words := by + unfold representation + cases h : (WordSeedRealization.run (representationSampler I hn) words).1 with + | none => simp only [WordSeedRealization.execute,h] + | some s => + simp only [WordSeedRealization.execute,h] + exact representationAction_value I hn hlog s.val + +theorem compression_sound (I : Instance n) (hn : 168000000 ≤ n) + (words : CompressionWords I) (hy : (compression I hn words).1.1 = true) : Solvable I := by + rw [compression_value] at hy + unfold WordSeedRealization.execute at hy + split at hy + · contradiction + · exact SampledCompressionTrial.sound _ _ _ hy + +theorem representation_sound (I : Instance n) (hn : 10000 ≤ n) + (hlog : Real.logb 2 ((mixerSize n : ℝ)+1)+1 ≤ (n : ℝ)/1000) + (words : RepresentationWords I) + (hy : (representation I hn hlog words).1.1 = true) : Solvable I := by + rw [representation_value] at hy + unfold WordSeedRealization.execute at hy + split at hy + · contradiction + · exact RepresentationPreparedAcceptance.sound _ _ _ _ hy + +theorem compression_probability (I : Instance n) (hn : 168000000 ≤ n) + (hs : Solvable I) + (hm : (153/20000 : ℝ)*n ≤ + meanDeficiency (CompressionData.mk I).weights Finset.univ (compressionHalfSize n)) + (hscale : Real.logb 2 (inputScale I : ℝ) ≤ (n : ℝ)/1000000000) : + (1/8 : ℝ) ≤ (FiniteLaw.uniform : FiniteLaw (CompressionWords I)).probability + (fun words => (compression I hn words).1.1 = true) := by + simp only [compression_value] + apply ((CompressionData.mk I).bounded_compact_acceptance_probability + (representationBufferCapacity n) hn hs hm hscale).trans + exact WordSeedRealization.probability_success (compressionSampler I hn) + (fun s => (SampledCompressionTrial.run (CompressionData.mk I) hn s).1) + ((CompressionData.mk I).AcceptedWithCompactTests (representationBufferCapacity n)) + (SampledCompressionTrial.accepts (CompressionData.mk I) hn) + +theorem representation_probability (I : Instance n) (hn : 180000000 ≤ n) + (hlog : Real.logb 2 ((mixerSize n : ℝ)+1)+1 ≤ (n : ℝ)/1000) + (hs : Solvable I) + (hm : meanDeficiency (canonicalRepresentationData I).zeroSetup.originalWeights + Finset.univ (mixerSize n/2) < (153/20000 : ℝ)*n) + (hden : ((mixerSize n/2 : ℕ) : ℝ)+1 < + (2 : ℝ)^((1/1500 : ℝ)*(mixerSize n/2 : ℕ))) + (hscale : Real.logb 2 (inputScale I : ℝ) ≤ (n : ℝ)/1000000000) : + 1/(inputScale I : ℝ)^110 ≤ + (FiniteLaw.uniform : FiniteLaw (RepresentationWords I)).probability + (fun words => (representation I (by omega) hlog words).1.1 = true) := by + obtain ⟨solution,hsolution⟩ := hs + let D := canonicalRepresentationData I + let R : RepresentationSetup n := ⟨I,solution,hsolution,D.mixers,D.disjoint,D.card⟩ + have hp := R.bounded_runtime_core_probability hn hm hden hscale + (representationBufferCapacity n) + apply hp.trans + simp only [representation_value] + exact WordSeedRealization.probability_success (representationSampler I (by omega)) + (RepresentationPreparedAcceptance.accept I (by omega) hlog) + (D.CoreFavorable (by omega) hlog (representationBufferCapacity n)) + (RepresentationPreparedAcceptance.of_core I (by omega) hlog) + +end LowSpaceSubsetSum.WordDecisionBranches + +end + +end OAI diff --git a/lean/OAI/Combinatorics/LowSpaceSubsetSum/Word/WordDecisionRound.lean b/lean/OAI/Combinatorics/LowSpaceSubsetSum/Word/WordDecisionRound.lean new file mode 100644 index 0000000000000000000000000000000000000000..67aa27551e91014c6270e3dd14977f606c760d99 --- /dev/null +++ b/lean/OAI/Combinatorics/LowSpaceSubsetSum/Word/WordDecisionRound.lean @@ -0,0 +1,102 @@ +import OAI.Combinatorics.LowSpaceSubsetSum.Word.WordDecisionBranches +import OAI.Combinatorics.LowSpaceSubsetSum.Search.DecisionRound + +namespace OAI + +/-! # Independent fair-word rounds and counter-executed amplification -/ + +noncomputable section +namespace LowSpaceSubsetSum.WordDecisionRound + +variable {n : ℕ} + +abbrev Words (I : Instance n) := + WordDecisionBranches.CompressionWords I × WordDecisionBranches.RepresentationWords I + +def law (I : Instance n) : FiniteLaw (Words I) := + (FiniteLaw.uniform : FiniteLaw (WordDecisionBranches.CompressionWords I)).prod + (FiniteLaw.uniform : FiniteLaw (WordDecisionBranches.RepresentationWords I)) + +def combine (c r : (Bool × ℕ) × ℕ) : (Bool × ℕ) × ℕ := + ((c.1.1 || r.1.1,c.1.2+r.1.2+3),max c.2 (r.2+8)+16) + +def run (I : Instance n) (hn : 180000000 ≤ n) + (hlog : Real.logb 2 ((mixerSize n : ℝ)+1)+1 ≤ (n : ℝ)/1000) + (words : Words I) : (Bool × ℕ) × ℕ := + combine (WordDecisionBranches.compression I (by omega) words.1) + (WordDecisionBranches.representation I (by omega) hlog words.2) + +theorem value (I : Instance n) (hn : 180000000 ≤ n) + (hlog : Real.logb 2 ((mixerSize n : ℝ)+1)+1 ≤ (n : ℝ)/1000) + (words : Words I) : + (run I hn hlog words).1.1 = + ((WordDecisionBranches.compression I (by omega) words.1).1.1 || + (WordDecisionBranches.representation I (by omega) hlog words.2).1.1) := rfl + +theorem sound (I : Instance n) (hn : 180000000 ≤ n) + (hlog : Real.logb 2 ((mixerSize n : ℝ)+1)+1 ≤ (n : ℝ)/1000) + (words : Words I) (hy : (run I hn hlog words).1.1 = true) : Solvable I := by + rw [value,Bool.or_eq_true] at hy + rcases hy with hc | hr + · exact WordDecisionBranches.compression_sound I (by omega) words.1 hc + · exact WordDecisionBranches.representation_sound I (by omega) hlog words.2 hr + +theorem probability (I : Instance n) (hn : 180000000 ≤ n) + (hlog : Real.logb 2 ((mixerSize n : ℝ)+1)+1 ≤ (n : ℝ)/1000) + (hs : Solvable I) + (hden : ((mixerSize n/2 : ℕ) : ℝ)+1 < + (2 : ℝ)^((1/1500 : ℝ)*(mixerSize n/2 : ℕ))) + (hscale : Real.logb 2 (inputScale I : ℝ) ≤ (n : ℝ)/1000000000) : + 1/(inputScale I : ℝ)^110 ≤ + (law I).probability (fun words => (run I hn hlog words).1.1 = true) := by + let P : WordDecisionBranches.CompressionWords I → Prop := fun words => + (WordDecisionBranches.compression I (by omega) words).1.1 = true + let Q : WordDecisionBranches.RepresentationWords I → Prop := fun words => + (WordDecisionBranches.representation I (by omega) hlog words).1.1 = true + by_cases hm : (153/20000 : ℝ)*n ≤ + meanDeficiency (CompressionData.mk I).weights Finset.univ (compressionHalfSize n) + · have hp := WordDecisionBranches.compression_probability I (by omega) hs hm hscale + have hu : (2 : ℝ) ≤ inputScale I := by + exact_mod_cast (show 2 ≤ inputScale I by unfold inputScale; omega) + have hd : (8 : ℝ) ≤ (inputScale I : ℝ)^110 := + (by norm_num : (8 : ℝ) ≤ 2^110).trans (pow_le_pow_left₀ (by norm_num) hu _) + apply ((one_div_le_one_div_of_le (by norm_num) hd).trans hp).trans + simpa only [law,value,Bool.or_eq_true,P,Q] using + FiniteLaw.prod_or_ge_left + (FiniteLaw.uniform : FiniteLaw (WordDecisionBranches.CompressionWords I)) + (FiniteLaw.uniform : FiniteLaw (WordDecisionBranches.RepresentationWords I)) P Q + · have hm' : meanDeficiency (canonicalRepresentationData I).zeroSetup.originalWeights + Finset.univ (mixerSize n/2) < (153/20000 : ℝ)*n := lt_of_not_ge hm + apply (WordDecisionBranches.representation_probability I hn hlog hs hm' hden hscale).trans + simpa only [law,value,Bool.or_eq_true,P,Q] using + FiniteLaw.prod_or_ge_right + (FiniteLaw.uniform : FiniteLaw (WordDecisionBranches.CompressionWords I)) + (FiniteLaw.uniform : FiniteLaw (WordDecisionBranches.RepresentationWords I)) P Q + +def repeated (I : Instance n) (hn : 180000000 ≤ n) + (hscale : Real.logb 2 (inputScale I : ℝ) ≤ (n : ℝ)/1000000000) + (words : Fin (inputScale I^120) → Words I) : (Bool × ℕ) × ℕ := + DecisionRepetitionCells.run (run I hn (roundLogBudget I (by omega) hscale)) words + +theorem repeated_sound (I : Instance n) (hn : 180000000 ≤ n) + (hscale : Real.logb 2 (inputScale I : ℝ) ≤ (n : ℝ)/1000000000) + (words : Fin (inputScale I^120) → Words I) + (hy : (repeated I hn hscale words).1.1 = true) : Solvable I := by + rw [repeated,DecisionRepetitionCells.value,DecisionRepetition.value] at hy + exact repeatAccept_sound _ _ (sound I hn _) words hy + +theorem repeated_probability (I : Instance n) (hn : 180000000 ≤ n) + (hscale : Real.logb 2 (inputScale I : ℝ) ≤ (n : ℝ)/1000000000) + (hden : ((mixerSize n/2 : ℕ) : ℝ)+1 < + (2 : ℝ)^((1/1500 : ℝ)*(mixerSize n/2 : ℕ))) (hs : Solvable I) : + (2/3 : ℝ) < ((law I).iid (inputScale I^120)).probability + (fun words => (repeated I hn hscale words).1.1 = true) := by + simp only [repeated,DecisionRepetitionCells.value,DecisionRepetition.value] + exact repetition_acceptance_probability (law I) _ (by unfold inputScale; omega) + (probability I hn _ hs hden hscale) + +end LowSpaceSubsetSum.WordDecisionRound + +end + +end OAI diff --git a/lean/OAI/Combinatorics/LowSpaceSubsetSum/Word/WordDecisionUniform.lean b/lean/OAI/Combinatorics/LowSpaceSubsetSum/Word/WordDecisionUniform.lean new file mode 100644 index 0000000000000000000000000000000000000000..f22c89afc30619a1ac135f4c601fe6f2c79188b9 --- /dev/null +++ b/lean/OAI/Combinatorics/LowSpaceSubsetSum/Word/WordDecisionUniform.lean @@ -0,0 +1,54 @@ +import OAI.Combinatorics.LowSpaceSubsetSum.Word.WordDecisionRound + +namespace OAI + +/-! # The round and repetition laws are uniform on finite fair-word tables -/ + +noncomputable section +namespace LowSpaceSubsetSum.WordDecisionUniform + +open scoped BigOperators + +private theorem law_ext {A : Type} [Fintype A] (μ ν : FiniteLaw A) + (h : μ.mass = ν.mass) : μ = ν := by + cases μ + cases ν + cases h + rfl + +theorem uniform_prod {A B : Type} [Fintype A] [Fintype B] [Nonempty A] [Nonempty B] : + (FiniteLaw.uniform : FiniteLaw A).prod (FiniteLaw.uniform : FiniteLaw B) = + (FiniteLaw.uniform : FiniteLaw (A × B)) := by + apply law_ext + funext x + simp only [FiniteLaw.prod,FiniteLaw.uniform,Fintype.card_prod,Nat.cast_mul] + exact one_div_mul_one_div _ _ + +theorem uniform_iid {A : Type} [Fintype A] [Nonempty A] (k : ℕ) : + (FiniteLaw.uniform : FiniteLaw A).iid k = + (FiniteLaw.uniform : FiniteLaw (Fin k → A)) := by + apply law_ext + funext x + simp only [FiniteLaw.iid,FiniteLaw.pi,FiniteLaw.uniform,Finset.prod_const, + Finset.card_univ,Fintype.card_fin,Fintype.card_fun,Nat.cast_pow,one_div_pow] + +theorem round_law {n : ℕ} (I : Instance n) : + WordDecisionRound.law I = (FiniteLaw.uniform : FiniteLaw (WordDecisionRound.Words I)) := + uniform_prod + +theorem repeated_probability {n : ℕ} (I : Instance n) (hn : 180000000 ≤ n) + (hscale : Real.logb 2 (inputScale I : ℝ) ≤ (n : ℝ)/1000000000) + (hden : ((mixerSize n/2 : ℕ) : ℝ)+1 < + (2 : ℝ)^((1/1500 : ℝ)*(mixerSize n/2 : ℕ))) (hs : Solvable I) : + (2/3 : ℝ) < + (FiniteLaw.uniform : FiniteLaw (Fin (inputScale I^120) → WordDecisionRound.Words I)).probability + (fun words => (WordDecisionRound.repeated I hn hscale words).1.1 = true) := by + have h := WordDecisionRound.repeated_probability I hn hscale hden hs + rw [round_law,uniform_iid] at h + exact h + +end LowSpaceSubsetSum.WordDecisionUniform + +end + +end OAI diff --git a/lean/OAI/Combinatorics/LowSpaceSubsetSum/Word/WordExecutionAsymptotics.lean b/lean/OAI/Combinatorics/LowSpaceSubsetSum/Word/WordExecutionAsymptotics.lean new file mode 100644 index 0000000000000000000000000000000000000000..4db8372ebb64530f741ad1d75892eb81e2884e0d --- /dev/null +++ b/lean/OAI/Combinatorics/LowSpaceSubsetSum/Word/WordExecutionAsymptotics.lean @@ -0,0 +1,53 @@ +import OAI.Combinatorics.LowSpaceSubsetSum.Search.PreparedAsymptotics + +namespace OAI + +/-! # Resource envelopes including the executed word generators -/ + +noncomputable section +namespace LowSpaceSubsetSum.WordExecutionAsymptotics + +variable {n : ℕ} + +theorem counter_limit (I : Instance n) (hn : 10000 ≤ n) + (hscale : Real.logb 2 (inputScale I : ℝ) ≤ (n : ℝ)/1000000000) : + inputScale I^624*2^((n+1)/2) < 2^n := by + have hu : (0 : ℝ) < inputScale I := by + exact_mod_cast (show 0 < inputScale I by unfold inputScale; omega) + have he : (((n+1)/2 : ℕ) : ℝ) ≤ (1/2 : ℝ)*n+1 := by + have h : 2*((n+1)/2) ≤ n+1 := by omega + have h' : (2 : ℝ)*((n+1)/2 : ℕ) ≤ n+1 := by exact_mod_cast h + linarith only [h'] + have h := guarded_polynomial_exponential hn hu hscale 624 + (a := (1/2 : ℝ)) (by norm_num) + have hm := mul_le_mul_of_nonneg_left + (Real.rpow_le_rpow_of_exponent_le (by norm_num : (1 : ℝ) ≤ 2) he) + (show 0 ≤ (inputScale I : ℝ)^624 by positivity) + have hh : ((inputScale I^624*2^((n+1)/2) : ℕ) : ℝ) < (2 : ℝ)^n := by + simpa only [Nat.cast_mul,Nat.cast_pow,Nat.cast_ofNat,Real.rpow_natCast] using hm.trans_lt h + exact_mod_cast hh + +theorem time (c : ℕ) (hc : 0 < c) (n : ℕ) (hn : 2 ≤ n) + (I : Instance n) (hI : inputBits I ≤ n^c) : + ((inputScale I^624*2^((n+1)/2) : ℕ) : ℝ) ≤ + ((3 : ℝ)^624*2)*(n : ℝ)^(624*c)*(2 : ℝ)^((1/2 : ℝ)*n) := by + have hu : (inputScale I : ℝ) ≤ 3*(n : ℝ)^c := by + exact_mod_cast polynomial_bit_bound hn hc hI + have hp := pow_le_pow_left₀ (by positivity : (0 : ℝ) ≤ inputScale I) hu 624 + have hhalf : (((n+1)/2 : ℕ) : ℝ) ≤ (1/2 : ℝ)*n+1 := by + have h : 2*((n+1)/2) ≤ n+1 := by omega + have hh : (2 : ℝ)*((n+1)/2 : ℕ) ≤ n+1 := by exact_mod_cast h + linarith only [hh] + have he := Real.rpow_le_rpow_of_exponent_le (by norm_num : (1 : ℝ) ≤ 2) hhalf + simp only [Nat.cast_mul,Nat.cast_pow,Nat.cast_ofNat] + apply (mul_le_mul hp (by simpa only [Real.rpow_natCast] using he) + (by positivity) (by positivity)).trans + rw [mul_pow,←pow_mul,Nat.mul_comm c 624, + Real.rpow_add (by norm_num : (0 : ℝ) < 2),Real.rpow_one] + exact le_of_eq (by ac_rfl) + +end LowSpaceSubsetSum.WordExecutionAsymptotics + +end + +end OAI diff --git a/lean/OAI/Combinatorics/LowSpaceSubsetSum/Word/WordFinalDecision.lean b/lean/OAI/Combinatorics/LowSpaceSubsetSum/Word/WordFinalDecision.lean new file mode 100644 index 0000000000000000000000000000000000000000..858eafe6e16af60756059a7087bc1a98487eb7b8 --- /dev/null +++ b/lean/OAI/Combinatorics/LowSpaceSubsetSum/Word/WordFinalDecision.lean @@ -0,0 +1,119 @@ +import OAI.Combinatorics.LowSpaceSubsetSum.Word.WordMeasuredBounds +import OAI.Combinatorics.LowSpaceSubsetSum.Word.WordInputDescriptor +import OAI.Combinatorics.LowSpaceSubsetSum.Storage.FallbackCells +import OAI.Combinatorics.LowSpaceSubsetSum.Word.WordAddressBounds + +namespace OAI + +/-! # One input-only algorithm with counted preprocessing and fallback + +Finite word tables represent fresh independent draws. Only the entries read +by the sequential generators are consumed; reused draws are in their counted +retained candidate buffers. The input descriptor is computed before the guard. +-/ + +noncomputable section +namespace LowSpaceSubsetSum.WordFinalDecision + +variable {n : ℕ} + +abbrev Words (I : Instance n) := Fin (inputScale I^120) → WordDecisionRound.Words I + +def run (T : DecisionThreshold) (I : Instance n) (words : Words I) : (Bool × ℕ) × ℕ := + let d := WordInputDescriptor.run T.value I + let out := if h : d.guard = true then + WordMeasuredDecision.repeated I + (T.large.trans (of_decide_eq_true ((WordInputDescriptor.run_guard T.value I).symm.trans h)).1) + (mainGuard_log (by unfold inputScale; omega) + ((WordInputDescriptor.run_guard T.value I).symm.trans h)) words + else FallbackCells.decision I + ((out.1.1,d.work+out.1.2+3),max d.cells (out.2+8)) + +theorem sound (T : DecisionThreshold) (I : Instance n) (words : Words I) + (hy : (run T I words).1.1 = true) : Solvable I := by + dsimp only [run] at hy + split at hy + · exact WordMeasuredDecision.sound I _ _ words hy + · exact (ExactFallback.decision_correct I).mp ((FallbackCells.decision_value I).symm.trans hy) + +theorem probability (T : DecisionThreshold) (I : Instance n) (hs : Solvable I) : + (2/3 : ℝ) ≤ (FiniteLaw.uniform : FiniteLaw (Words I)).probability + (fun words => (run T I words).1.1 = true) := by + by_cases hg : (WordInputDescriptor.run T.value I).guard = true + · have hm := (WordInputDescriptor.run_guard T.value I).symm.trans hg + have hn := T.large.trans (of_decide_eq_true hm).1 + have hscale := mainGuard_log (by unfold inputScale; omega : 0 < inputScale I) hm + have he : (fun words : Words I => (run T I words).1.1 = true) = + (fun words => (WordMeasuredDecision.repeated I hn hscale words).1.1 = true) := by + funext words + simp only [run,hg,↓reduceDIte] + rw [he] + exact (WordMeasuredDecision.probability I hn hscale + (T.halfGap n (of_decide_eq_true hm).1) hs).le + · have he : (fun words : Words I => (run T I words).1.1 = true) = (fun _ => True) := by + funext words + simp [run,hg,FallbackCells.decision_value,(ExactFallback.decision_correct I).mpr hs] + rw [he,FiniteLaw.probability_true] + norm_num + +theorem rejects (T : DecisionThreshold) (I : Instance n) (hs : ¬Solvable I) + (words : Words I) : (run T I words).1.1 = false := by + apply Bool.eq_false_iff.mpr + exact fun h => hs (sound T I words h) + +private theorem overhead (u C H k l : ℕ) (hu : 10000 ≤ u) (hC : 1 ≤ C) (hH : 1 ≤ H) + (hk : 2 ≤ k) (hl : 2 ≤ l) : + 100*u+3 ≤ u^k*H ∧ 100*u+8 ≤ u^l*C := by + have hsmall : 100*u+8 ≤ u^2 := by nlinarith + have ht : u^2 ≤ u^k := Nat.pow_le_pow_right (by omega) hk + have hc : u^2 ≤ u^l := Nat.pow_le_pow_right (by omega) hl + exact ⟨(show 100*u+3 ≤ u^2 by omega).trans (ht.trans (Nat.le_mul_of_pos_right _ hH)), + hsmall.trans (hc.trans (Nat.le_mul_of_pos_right _ hC))⟩ + +theorem main_bounds (T : DecisionThreshold) (I : Instance n) + (hm : mainGuard T.value n (inputScale I) = true) (words : Words I) : + (run T I words).1.2 ≤ 2*(inputScale I^624*2^((n+1)/2)) ∧ + (run T I words).2 ≤ 2*writableWordLimit I := by + have hg := (WordInputDescriptor.run_guard T.value I).trans hm + have hn := T.large.trans (of_decide_eq_true hm).1 + have hscale := mainGuard_log (by unfold inputScale; omega : 0 < inputScale I) hm + have hw := WordMeasuredBounds.repeated_work I hn hscale words + have hc := WordMeasuredBounds.repeated_cells I hn hscale words + have hdw := WordInputDescriptor.run_work T.value I + have hdc := WordInputDescriptor.run_cells T.value I + have hO := overhead (inputScale I) (compressionDictionaryCapacity n) (2^((n+1)/2)) 624 15 + (by unfold inputScale; omega) Nat.one_le_two_pow Nat.one_le_two_pow (by decide) (by decide) + unfold run + simp only [hg,↓reduceDIte] + constructor + · omega + · unfold writableWordLimit at hc ⊢ + apply max_le <;> omega + +theorem work_fits (T : DecisionThreshold) (I : Instance n) + (hm : mainGuard T.value n (inputScale I) = true) (words : Words I) : + (run T I words).1.2 < 2^wordWidth I := by + have hn := T.large.trans (of_decide_eq_true hm).1 + have hl := mainGuard_log (by unfold inputScale; omega : 0 < inputScale I) hm + have hc := WordExecutionAsymptotics.counter_limit I (by omega) hl + have ht := Nat.mul_lt_mul_of_pos_left hc (by decide : 0 < 2) + rw [←pow_succ'] at ht + exact ((main_bounds T I hm words).1.trans_lt ht).trans_le + (Nat.pow_le_pow_right (by decide) (by unfold wordWidth inputScale; omega)) + +theorem cells_fits (T : DecisionThreshold) (I : Instance n) + (hm : mainGuard T.value n (inputScale I) = true) (words : Words I) : + (run T I words).2 < 2^wordWidth I := by + have hn := T.large.trans (of_decide_eq_true hm).1 + have hl := mainGuard_log (by unfold inputScale; omega : 0 < inputScale I) hm + have hc := writableWordLimit_lt_two_pow I (by omega) hl + have ht := Nat.mul_lt_mul_of_pos_left hc (by decide : 0 < 2) + rw [←pow_succ'] at ht + exact ((main_bounds T I hm words).2.trans_lt ht).trans_le + (Nat.pow_le_pow_right (by decide) (by unfold wordWidth inputScale; omega)) + +end LowSpaceSubsetSum.WordFinalDecision + +end + +end OAI diff --git a/lean/OAI/Combinatorics/LowSpaceSubsetSum/Word/WordInputDescriptor.lean b/lean/OAI/Combinatorics/LowSpaceSubsetSum/Word/WordInputDescriptor.lean new file mode 100644 index 0000000000000000000000000000000000000000..236d77829bbbe67b8ae5e275511f1fb234a64186 --- /dev/null +++ b/lean/OAI/Combinatorics/LowSpaceSubsetSum/Word/WordInputDescriptor.lean @@ -0,0 +1,161 @@ +import OAI.Combinatorics.LowSpaceSubsetSum.Search.MainGuard +import OAI.Combinatorics.LowSpaceSubsetSum.Word.WordSeedModulusExecution + +namespace OAI + +/-! # Executed input descriptor and main-branch guard + +An indexed tail scan computes the maximum original input word. Two doubling +cursors then compute the input bit length and the guard's ceiling logarithm. +The original input is read-only throughout. +-/ + +namespace LowSpaceSubsetSum.WordInputDescriptor + +variable {n : ℕ} + +def maximumLoop (I : Instance n) : ℕ → ℕ → ℕ → ℕ → ℕ → (ℕ × ℕ) × ℕ + | 0, _, top, work, peak => ((top,work+1),max peak 12) + | fuel+1, cursor, top, work, peak => + if h : cursor < n then + maximumLoop I fuel (cursor+1) (max top (I.values ⟨cursor,h⟩)) + (work+6) (max peak 12) + else ((top,work+1),max peak 12) + +theorem maximumLoop_upper (I : Instance n) (fuel cursor top work peak M : ℕ) + (htop : top ≤ M) (hI : ∀ i, I.values i ≤ M) : + (maximumLoop I fuel cursor top work peak).1.1 ≤ M := by + induction fuel generalizing cursor top work peak with + | zero => exact htop + | succ fuel ih => + rw [maximumLoop] + split + · exact ih _ _ _ _ (max_le htop (hI _)) + · exact htop + +theorem maximumLoop_lower (I : Instance n) (fuel cursor top work peak : ℕ) + (hbound : cursor+fuel ≤ n) : + top ≤ (maximumLoop I fuel cursor top work peak).1.1 ∧ + ∀ i : Fin n, cursor ≤ i.val → i.val < cursor+fuel → + I.values i ≤ (maximumLoop I fuel cursor top work peak).1.1 := by + induction fuel generalizing cursor top work peak with + | zero => exact ⟨le_rfl,fun i hi hj => by omega⟩ + | succ fuel ih => + have hc : cursor < n := by omega + simp only [maximumLoop, dite_eq_left hc] + have h := ih (cursor+1) (max top (I.values ⟨cursor,hc⟩)) + (work+6) (max peak 12) (by omega) + refine ⟨(le_max_left _ _).trans h.1,?_⟩ + intro i hi hj + by_cases he : i.val = cursor + · have hfin : i = ⟨cursor,hc⟩ := Fin.ext he + subst i + exact (le_max_right _ _).trans h.1 + · exact h.2 i (by omega) (by omega) + +theorem maximumLoop_work (I : Instance n) (fuel cursor top work peak : ℕ) + (hbound : cursor+fuel ≤ n) : + (maximumLoop I fuel cursor top work peak).1.2 = work+6*fuel+1 := by + induction fuel generalizing cursor top work peak with + | zero => simp only [maximumLoop,Nat.mul_zero,Nat.add_zero] + | succ fuel ih => + have hc : cursor < n := by omega + simp only [maximumLoop,dite_eq_left hc] + rw [ih _ _ _ _ (by omega)] + omega + +theorem maximumLoop_cells (I : Instance n) (fuel cursor top work peak : ℕ) : + (maximumLoop I fuel cursor top work peak).2 ≤ max peak 12 := by + induction fuel generalizing cursor top work peak with + | zero => exact le_rfl + | succ fuel ih => + rw [maximumLoop] + split + · simpa only [max_assoc,max_self] using ih (cursor+1) _ (work+6) (max peak 12) + · exact le_rfl + +def maximum (I : Instance n) : (ℕ × ℕ) × ℕ := maximumLoop I n 0 I.target 0 0 + +theorem maximum_value (I : Instance n) : (maximum I).1.1 = inputMaximum I := by + apply le_antisymm + · exact maximumLoop_upper I n 0 I.target 0 0 _ (le_max_left _ _) (fun i => + (Finset.le_sup (Finset.mem_univ i)).trans (le_max_right _ _)) + · have h := maximumLoop_lower I n 0 I.target 0 0 (by omega) + apply max_le h.1 + exact Finset.sup_le (fun i _ => h.2 i (Nat.zero_le _) (by simp)) + +theorem maximum_work (I : Instance n) : (maximum I).1.2 = 6*n+1 := by + simpa only [maximum,Nat.zero_add] using maximumLoop_work I n 0 I.target 0 0 (by omega) + +theorem maximum_cells (I : Instance n) : (maximum I).2 ≤ 12 := by + simpa only [maximum,Nat.zero_max] using maximumLoop_cells I n 0 I.target 0 0 + +structure Result where + maximum : ℕ + bits : ℕ + scale : ℕ + guardWidth : ℕ + guard : Bool + work : ℕ + cells : ℕ + +def run (T : ℕ) (I : Instance n) : Result := + let top := maximum I + let bits := WordSeedModulusExecution.run (1+top.1.1) + let b := max 1 bits.width + let u := n+b+2 + let guardBits := WordSeedModulusExecution.run u + ⟨top.1.1,b,u,guardBits.width, + decide (T ≤ n ∧ guardBits.width ≤ n/1000000000), + top.1.2+bits.work+guardBits.work+18,max top.2 40⟩ + +theorem run_maximum (T : ℕ) (I : Instance n) : (run T I).maximum = inputMaximum I := by + exact maximum_value I + +theorem run_bits (T : ℕ) (I : Instance n) : (run T I).bits = inputBits I := by + simp only [run,maximum_value,WordSeedModulusExecution.run_width,inputBits] + +theorem run_scale (T : ℕ) (I : Instance n) : (run T I).scale = inputScale I := by + change n+(run T I).bits+2 = inputScale I + rw [run_bits,inputScale] + +theorem run_guardWidth (T : ℕ) (I : Instance n) : + (run T I).guardWidth = Nat.clog 2 (inputScale I) := by + change (WordSeedModulusExecution.run (run T I).scale).width = _ + rw [WordSeedModulusExecution.run_width,run_scale] + +theorem run_guard (T : ℕ) (I : Instance n) : + (run T I).guard = mainGuard T n (inputScale I) := by + change decide (T ≤ n ∧ (run T I).guardWidth ≤ n/1000000000) = _ + rw [run_guardWidth] + rfl + +theorem run_work_exact (T : ℕ) (I : Instance n) : + (run T I).work = 6*n+5*Nat.clog 2 (1+inputMaximum I)+ + 5*Nat.clog 2 (inputScale I)+21 := by + change (maximum I).1.2+(WordSeedModulusExecution.run (1+(maximum I).1.1)).work+ + (WordSeedModulusExecution.run (run T I).scale).work+18 = _ + rw [maximum_work,maximum_value,run_scale,WordSeedModulusExecution.run_work, + WordSeedModulusExecution.run_work] + omega + +theorem run_work (T : ℕ) (I : Instance n) : (run T I).work ≤ 100*inputScale I := by + have hb : Nat.clog 2 (1+inputMaximum I) ≤ inputBits I := le_max_right _ _ + have hu : Nat.clog 2 (inputScale I) ≤ inputScale I := + Nat.clog_le_of_le_pow Nat.lt_two_pow_self.le + have hp := inputBits_pos I + rw [run_work_exact] + unfold inputScale at hu ⊢ + omega + +theorem run_cells_small (T : ℕ) (I : Instance n) : (run T I).cells = 40 := by + exact max_eq_right ((maximum_cells I).trans (by decide)) + +theorem run_cells (T : ℕ) (I : Instance n) : (run T I).cells ≤ 100*inputScale I := by + rw [run_cells_small] + unfold inputScale + omega + +end LowSpaceSubsetSum.WordInputDescriptor + +end OAI diff --git a/lean/OAI/Combinatorics/LowSpaceSubsetSum/Word/WordLayoutPreparation.lean b/lean/OAI/Combinatorics/LowSpaceSubsetSum/Word/WordLayoutPreparation.lean new file mode 100644 index 0000000000000000000000000000000000000000..00fcac3bae0e0740cdea4ddc23dbcf3423f97181 --- /dev/null +++ b/lean/OAI/Combinatorics/LowSpaceSubsetSum/Word/WordLayoutPreparation.lean @@ -0,0 +1,88 @@ +import OAI.Combinatorics.LowSpaceSubsetSum.Word.WordSeedPreparedBind +import OAI.Combinatorics.LowSpaceSubsetSum.Storage.LayoutPreparationCells + +namespace OAI + +/-! # Computing layout-dependent sampling parameters from a stored seed + +The mixer counts, order and prime widths are obtained by the counted stored +preparation. They are not evaluated implicitly while selecting a sampler. +-/ + +noncomputable section +namespace LowSpaceSubsetSum.WordLayoutPreparation + +variable {n : ℕ} + +abbrev Layout (I : Instance n) := + WordSeedMeasured.Accepted (canonicalRepresentationData I).zeroSetup.layoutCoupling + +abbrev Prepared (I : Instance n) (a : Layout I) := + {d : RepresentationLayoutPreparation.Data n // + (LayoutPreparationCells.run I a.seed.val).1.1 = some d} + +theorem source (I : Instance n) (a : Layout I) : + (canonicalRepresentationData I).zeroSetup.layoutCoupling.bounded a.seed.val = some a.value := + (WordSeedRealization.successful_agrees a.seed).trans (congrArg some a.correct.symm) + +theorem exists_data (I : Instance n) (a : Layout I) : Nonempty (Prepared I a) := by + obtain ⟨d,hd,_⟩ := RepresentationLayoutPreparation.complete + (canonicalRepresentationData I) a.seed.val a.value.1 a.value.2 (source I a) + exact ⟨⟨d,(congrArg Prod.fst (LayoutPreparationCells.value I a.seed.val)).trans hd⟩⟩ + +def compute (I : Instance n) (a : Layout I) : (Prepared I a × ℕ) × ℕ := + let out := LayoutPreparationCells.run I a.seed.val + match h : out.1.1 with + | none => False.elim (by + obtain ⟨d⟩ := exists_data I a + cases h.symm.trans d.property) + | some d => ((⟨d,h⟩,out.1.2+1),out.2+8) + +theorem fields (I : Instance n) (a : Layout I) (d : Prepared I a) : + (∀ i : Fin n, d.val.permutation[i.val] = a.value.1 i) ∧ + (∀ i : Fin 4, d.val.parameters.widths[i.val] = + (canonicalRepresentationData I).zeroSetup.samplerPrimeWidths a.value i) := by + have hd := (congrArg Prod.fst (LayoutPreparationCells.value I a.seed.val)).symm.trans d.property + obtain ⟨e,he,hv,_,hw⟩ := RepresentationLayoutPreparation.value + (canonicalRepresentationData I) a.seed.val d.val hd + have heq : (e,d.val.signs.semantic) = a.value := Option.some.inj (he.symm.trans (source I a)) + constructor + · intro i + have hi := congrArg (fun z => z.1 i) heq + exact (hv i).trans hi + · intro i + exact (hw i).trans (congrArg + (fun z => (canonicalRepresentationData I).zeroSetup.samplerPrimeWidths z i) heq) + +theorem work (I : Instance n) (hn : 10000 ≤ n) (a : Layout I) : + (compute I a).1.2 ≤ n*n^3+10*(n+1)^2+4*n+7+ + inputScale I^6*2^mixerSize n := by + have hw := RepresentationLayoutPreparation.work (canonicalRepresentationData I) hn a.seed.val + change (RepresentationLayoutPreparation.run (canonicalRepresentationData I) a.seed.val).2 ≤ + n*n^3+10*(n+1)^2+4*n+6+inputScale I^6*2^mixerSize n at hw + have hv := congrArg Prod.snd (LayoutPreparationCells.value I a.seed.val) + rw [←hv] at hw + obtain ⟨d⟩ := exists_data I a + unfold compute + dsimp only + split + next h => cases h.symm.trans d.property + · dsimp only + omega + +theorem cells (I : Instance n) (hn : 10000 ≤ n) (a : Layout I) : + (compute I a).2 ≤ inputScale I^10*(compressionDictionaryCapacity n+1)+8 := by + have hc := LayoutPreparationCells.cells I hn a.seed.val + obtain ⟨d⟩ := exists_data I a + unfold compute + dsimp only + split + next h => cases h.symm.trans d.property + · dsimp only + omega + +end LowSpaceSubsetSum.WordLayoutPreparation + +end + +end OAI diff --git a/lean/OAI/Combinatorics/LowSpaceSubsetSum/Word/WordMain.lean b/lean/OAI/Combinatorics/LowSpaceSubsetSum/Word/WordMain.lean new file mode 100644 index 0000000000000000000000000000000000000000..60a3982d78f6f2c7ecf6935350d49e4d326bb488 --- /dev/null +++ b/lean/OAI/Combinatorics/LowSpaceSubsetSum/Word/WordMain.lean @@ -0,0 +1,83 @@ +import OAI.Combinatorics.LowSpaceSubsetSum.Word.WordFinalDecision + +namespace OAI + +/-! # Time and space guarantees for the bounded randomized decision procedure + +`main_resources` bounds the work and storage counters with fixed threshold +`T`. `space_corollary` absorbs the polynomial storage factor for every rate +above .199. All resource quantifiers range over every random-word outcome, +while the procedure and threshold are independent of the polynomial-bit exponent. +-/ + +noncomputable section +namespace LowSpaceSubsetSum.WordMain + +open Filter + +private theorem double_time (a b c : ℝ) : 2*((a*2)*b*c) = (4*a)*b*c := by ring + +theorem main_resources (T : DecisionThreshold) (c : ℕ) (hc : 0 < c) : + ∀ᶠ n : ℕ in atTop, ∀ I : Instance n, inputBits I ≤ n^c → + ∀ words : WordFinalDecision.Words I, + ((WordFinalDecision.run T I words).1.2 : ℝ) ≤ + (4*(3 : ℝ)^624)*(n : ℝ)^(624*c)*(2 : ℝ)^((1/2 : ℝ)*n) ∧ + ((WordFinalDecision.run T I words).2 : ℝ) ≤ + 2*(inputScale I : ℝ)^15*(2 : ℝ)^((199/1000 : ℝ)*n) := by + filter_upwards [eventually_mainGuard T.value c hc,eventually_ge_atTop 2] with n hg hn + intro I hI words + have hm : mainGuard T.value n (inputScale I) = true := hg (inputBits I) hI + have hb := WordFinalDecision.main_bounds T I hm words + constructor + · have hnat : ((WordFinalDecision.run T I words).1.2 : ℝ) ≤ + ((2*(inputScale I^624*2^((n+1)/2)) : ℕ) : ℝ) := Nat.cast_le.mpr hb.1 + rw [Nat.cast_mul,Nat.cast_ofNat] at hnat + apply hnat.trans + have h := mul_le_mul_of_nonneg_left (WordExecutionAsymptotics.time c hc n hn I hI) + (by norm_num : (0 : ℝ) ≤ 2) + simpa only [double_time] using h + · have hnat : ((WordFinalDecision.run T I words).2 : ℝ) ≤ + ((2*writableWordLimit I : ℕ) : ℝ) := Nat.cast_le.mpr hb.2 + simp only [writableWordLimit,Nat.cast_mul,Nat.cast_pow,Nat.cast_ofNat] at hnat + rw [←mul_assoc] at hnat + exact hnat.trans (mul_le_mul_of_nonneg_left (PreparedAsymptotics.capacity_upper n) + (by positivity)) + +theorem space_corollary (T : DecisionThreshold) (rho : ℝ) + (hrho : (199/1000 : ℝ) < rho) (c : ℕ) (hc : 0 < c) : + ∀ᶠ n : ℕ in atTop, ∀ I : Instance n, inputBits I ≤ n^c → + ∀ words : WordFinalDecision.Words I, + ((WordFinalDecision.run T I words).1.2 : ℝ) ≤ + (4*(3 : ℝ)^624)*(n : ℝ)^(624*c)*(2 : ℝ)^((1/2 : ℝ)*n) ∧ + ((WordFinalDecision.run T I words).2 : ℝ) ≤ + (2*(3 : ℝ)^15)*(2 : ℝ)^(rho*n) := by + filter_upwards [main_resources T c hc,absorb_space_polynomial hrho c hc] with n hm hs + intro I hI words + refine ⟨(hm I hI words).1,(hm I hI words).2.trans ?_⟩ + have h := mul_le_mul_of_nonneg_left (hs (inputBits I) hI) (by norm_num : (0 : ℝ) ≤ 2) + simpa only [inputScale,Nat.cast_add,Nat.cast_ofNat,mul_assoc] using h + +/-- One-sided correctness and one-fifth-exponential storage for any fixed +threshold satisfying the large-input conditions. -/ +theorem conditional_main (T : DecisionThreshold) : + (∀ (n : ℕ) (I : Instance n) (words : WordFinalDecision.Words I), + (WordFinalDecision.run T I words).1.1 = true → Solvable I) ∧ + (∀ (n : ℕ) (I : Instance n), Solvable I → + (2/3 : ℝ) ≤ (FiniteLaw.uniform : FiniteLaw (WordFinalDecision.Words I)).probability + (fun words => (WordFinalDecision.run T I words).1.1 = true)) ∧ + (∀ c : ℕ, 0 < c → ∀ᶠ n : ℕ in atTop, + ∀ I : Instance n, inputBits I ≤ n^c → ∀ words : WordFinalDecision.Words I, + ((WordFinalDecision.run T I words).1.2 : ℝ) ≤ + (4*(3 : ℝ)^624)*(n : ℝ)^(624*c)*(2 : ℝ)^((1/2 : ℝ)*n) ∧ + ((WordFinalDecision.run T I words).2 : ℝ) ≤ + (2*(3 : ℝ)^15)*(2 : ℝ)^((1/5 : ℝ)*n)) := by + refine ⟨fun _ I words => WordFinalDecision.sound T I words, + fun _ I => WordFinalDecision.probability T I,?_⟩ + intro c hc + exact space_corollary T (1/5) (by norm_num) c hc + +end LowSpaceSubsetSum.WordMain + +end + +end OAI diff --git a/lean/OAI/Combinatorics/LowSpaceSubsetSum/Word/WordMeasuredBounds.lean b/lean/OAI/Combinatorics/LowSpaceSubsetSum/Word/WordMeasuredBounds.lean new file mode 100644 index 0000000000000000000000000000000000000000..de36d66b94885091eba99d3ade3e882f537e6506 --- /dev/null +++ b/lean/OAI/Combinatorics/LowSpaceSubsetSum/Word/WordMeasuredBounds.lean @@ -0,0 +1,203 @@ +import OAI.Combinatorics.LowSpaceSubsetSum.Word.WordMeasuredDecision +import OAI.Combinatorics.LowSpaceSubsetSum.Word.WordActionBounds +import OAI.Combinatorics.LowSpaceSubsetSum.Word.WordExecutionAsymptotics + +namespace OAI + +/-! # All-execution bounds including word sampling and retained seeds -/ + +noncomputable section +namespace LowSpaceSubsetSum.WordMeasuredBounds + +open WordSeedMeasured + +variable {n : ℕ} + +private theorem add_work (u H k W : ℕ) (hu : 3 ≤ u) (hH : 1 ≤ H) + (hk : 1 ≤ k) (hW : W ≤ 2*(u^k*H)+3) : W ≤ u^(k+1)*H := by + have hp : u ≤ u^k := by + simpa only [pow_one] using Nat.pow_le_pow_right (by omega : 0 < u) hk + have hm : u^k ≤ u^k*H := Nat.le_mul_of_pos_right _ hH + calc + W ≤ 3*(u^k*H) := by omega + _ ≤ u*(u^k*H) := Nat.mul_le_mul_right _ hu + _ = _ := by rw [←Nat.mul_assoc,←pow_succ'] + +private theorem add_work_input (A B : ℕ) (h : A ≤ B) : + A+B+1 ≤ 2*B+3 := by omega + +private theorem sampled {α : Type} [Fintype α] {w N : ℕ} + {S : SamplerCoupling α} {X : WordSeedRealization.Realization w N S} + (I : Instance n) (hn : 10000 ≤ n) (E : Execution X) + (action : S.Seed → (Bool × ℕ) × ℕ) + (hE : E.Bounded (inputScale I^11*2^((n+1)/2)) + (inputScale I^11*(compressionDictionaryCapacity n+1)) + (inputScale I^11*(compressionDictionaryCapacity n+1))) + (k : ℕ) (hk : 11 ≤ k) + (hW : ∀ s, (action s).1.2 ≤ inputScale I^k*2^((n+1)/2)) + (hD : ∀ s, (action s).2 ≤ 36*inputScale I^14*(compressionDictionaryCapacity n+1)) + (stream : ℕ → Fin (2^w)) (cursor : ℕ) : + (WordSampledAction.run E action stream cursor).work ≤ inputScale I^(k+1)*2^((n+1)/2) ∧ + (WordSampledAction.run E action stream cursor).cells ≤ + 38*inputScale I^14*(compressionDictionaryCapacity n+1) := by + have h := WordSampledAction.bounded E action _ _ _ _ _ hE hW hD stream cursor + have hu : 10000 ≤ inputScale I := by unfold inputScale; omega + have hp := Nat.mul_le_mul_right (2^((n+1)/2)) + (Nat.pow_le_pow_right (n := inputScale I) (by omega) hk) + have hsum := h.1.trans (add_work_input + (inputScale I^11*2^((n+1)/2)) (inputScale I^k*2^((n+1)/2)) hp) + have hw := add_work (inputScale I) (2^((n+1)/2)) k _ + (by omega) Nat.one_le_two_pow (by omega) hsum + refine ⟨hw,h.2.trans ?_⟩ + have hm := Nat.mul_le_mul_right (compressionDictionaryCapacity n+1) + (Nat.pow_le_pow_right (n := inputScale I) (by omega) (by decide : 11 ≤ 14)) + have hl : 8 ≤ inputScale I^14*(compressionDictionaryCapacity n+1) := by + have hp : inputScale I ≤ inputScale I^14 := by + simpa only [pow_one] using Nat.pow_le_pow_right (by omega : 0 < inputScale I) (by decide : 1 ≤ 14) + exact (show 8 ≤ inputScale I by omega).trans (hp.trans (Nat.le_mul_of_pos_right _ (by omega))) + rw [Nat.mul_assoc 36, Nat.mul_assoc 38] + apply max_le <;> omega + +private theorem sampled_501 {α : Type} [Fintype α] {w N : ℕ} + {S : SamplerCoupling α} {X : WordSeedRealization.Realization w N S} + (I : Instance n) (hn : 10000 ≤ n) (E : Execution X) + (action : S.Seed → (Bool × ℕ) × ℕ) + (hE : E.Bounded (inputScale I^11*2^((n+1)/2)) + (inputScale I^11*(compressionDictionaryCapacity n+1)) + (inputScale I^11*(compressionDictionaryCapacity n+1))) + (hW : ∀ s, (action s).1.2 ≤ inputScale I^501*2^((n+1)/2)) + (hD : ∀ s, (action s).2 ≤ 36*inputScale I^14*(compressionDictionaryCapacity n+1)) + (stream : ℕ → Fin (2^w)) (cursor : ℕ) : + (WordSampledAction.run E action stream cursor).work ≤ inputScale I^502*2^((n+1)/2) ∧ + (WordSampledAction.run E action stream cursor).cells ≤ + 38*inputScale I^14*(compressionDictionaryCapacity n+1) := by + have h := sampled I hn E action hE 501 (by decide) hW hD stream cursor + rw [show (501 : ℕ)+1 = 502 from rfl] at h + exact h + +theorem compression (I : Instance n) (hn : 180000000 ≤ n) + (hscale : Real.logb 2 (inputScale I : ℝ) ≤ (n : ℝ)/1000000000) + (words : WordDecisionBranches.CompressionWords I) : + (WordMeasuredDecision.compression I (by omega) words).1.2 ≤ inputScale I^502*2^((n+1)/2) ∧ + (WordMeasuredDecision.compression I (by omega) words).2 ≤ + 38*inputScale I^14*(compressionDictionaryCapacity n+1) := by + unfold WordMeasuredDecision.compression WordMeasuredDecision.asAction + apply sampled_501 I (by omega) + · apply bounded_mono _ (WordSeedScalarBounds.compression_bounded_scale I _ _ _ _ _) + · exact Nat.mul_le_mul_right _ (Nat.pow_le_pow_right (by unfold inputScale; omega) (by decide : 6 ≤ 11)) + · exact (Nat.pow_le_pow_right (by unfold inputScale; omega) (by decide : 5 ≤ 11)).trans + (Nat.le_mul_of_pos_right _ (by omega)) + · exact (Nat.pow_le_pow_right (by unfold inputScale; omega) (by decide : 5 ≤ 11)).trans + (Nat.le_mul_of_pos_right _ (by omega)) + · exact WordActionBounds.compression_source_work I hn hscale + · intro s + apply (SampledCompressionCells.cells (CompressionData.mk I) (by omega) s).trans + have hp := Nat.mul_le_mul_right (compressionDictionaryCapacity n+1) + (Nat.pow_le_pow_right (n := inputScale I) (by unfold inputScale; omega) (by decide : 12 ≤ 14)) + have ht : inputScale I^14*(compressionDictionaryCapacity n+1) ≤ + 36*inputScale I^14*(compressionDictionaryCapacity n+1) := + Nat.mul_le_mul_right _ (Nat.le_mul_of_pos_left _ (by decide)) + exact hp.trans ht + +theorem representation (I : Instance n) (hn : 180000000 ≤ n) + (hlog : Real.logb 2 ((mixerSize n : ℝ)+1)+1 ≤ (n : ℝ)/1000) + (hscale : Real.logb 2 (inputScale I : ℝ) ≤ (n : ℝ)/1000000000) + (words : WordDecisionBranches.RepresentationWords I) : + (WordMeasuredDecision.representation I (by omega) hlog words).1.2 ≤ inputScale I^502*2^((n+1)/2) ∧ + (WordMeasuredDecision.representation I (by omega) hlog words).2 ≤ + 38*inputScale I^14*(compressionDictionaryCapacity n+1) := by + unfold WordMeasuredDecision.representation WordMeasuredDecision.asAction + dsimp only [WordMeasuredDecision.representationGenerator] + apply sampled_501 I (by omega) + · exact WordSeedHistoryBounds.bucketHistory_bounded I (by omega) _ _ + · exact WordActionBounds.representation_source_work I hn hlog hscale + · intro s + exact RepresentationTrialCells.cells I (by omega) hlog hscale s _ + +theorem round (I : Instance n) (hn : 180000000 ≤ n) + (hlog : Real.logb 2 ((mixerSize n : ℝ)+1)+1 ≤ (n : ℝ)/1000) + (hscale : Real.logb 2 (inputScale I : ℝ) ≤ (n : ℝ)/1000000000) + (words : WordDecisionRound.Words I) : + (WordMeasuredDecision.round I hn hlog words).1.2 ≤ inputScale I^503*2^((n+1)/2) ∧ + (WordMeasuredDecision.round I hn hlog words).2 ≤ + 40*inputScale I^14*(compressionDictionaryCapacity n+1) := by + have hc := compression I hn hscale words.1 + have hr := representation I hn hlog hscale words.2 + have hw := add_work (inputScale I) (2^((n+1)/2)) 502 _ + (by unfold inputScale; omega) Nat.one_le_two_pow (by decide) + (show (WordMeasuredDecision.round I hn hlog words).1.2 ≤ _ from by + change _+_+3 ≤ _ + omega) + rw [show (502 : ℕ)+1 = 503 from rfl] at hw + refine ⟨hw,?_⟩ + have hl : 24 ≤ inputScale I^14*(compressionDictionaryCapacity n+1) := by + have hu : 10000 ≤ inputScale I := by unfold inputScale; omega + have hp : inputScale I ≤ inputScale I^14 := by + simpa only [pow_one] using Nat.pow_le_pow_right (by omega : 0 < inputScale I) (by decide : 1 ≤ 14) + exact (show 24 ≤ inputScale I by omega).trans (hp.trans (Nat.le_mul_of_pos_right _ (by omega))) + change max _ (_+8)+16 ≤ _ + have hc' := hc.2 + have hr' := hr.2 + rw [Nat.mul_assoc 38] at hc' hr' + rw [Nat.mul_assoc 40] + omega + +private theorem repetition_work (u H r k W : ℕ) (hu : 3 ≤ u) (hH : 1 ≤ H) + (hW : W ≤ u^r*(u^k*H+1)+1) : W ≤ u^(r+k+1)*H := by + have hp : u^r ≤ u^(r+k)*H := + (Nat.pow_le_pow_right (by omega : 0 < u) (Nat.le_add_right r k)).trans + (Nat.le_mul_of_pos_right _ hH) + have hs : 1 ≤ u^(r+k)*H := Nat.mul_pos (pow_pos (by omega) _) hH + have he : u^r*(u^k*H) = u^(r+k)*H := by rw [←Nat.mul_assoc,←pow_add] + rw [Nat.mul_add,Nat.mul_one,he] at hW + calc + W ≤ 3*(u^(r+k)*H) := by omega + _ ≤ u*(u^(r+k)*H) := Nat.mul_le_mul_right _ hu + _ = _ := by rw [←Nat.mul_assoc,←pow_succ'] + +theorem repeated_work (I : Instance n) (hn : 180000000 ≤ n) + (hscale : Real.logb 2 (inputScale I : ℝ) ≤ (n : ℝ)/1000000000) + (words : Fin (inputScale I^120) → WordDecisionRound.Words I) : + (WordMeasuredDecision.repeated I hn hscale words).1.2 ≤ inputScale I^624*2^((n+1)/2) := by + rw [WordMeasuredDecision.repeated,DecisionRepetitionCells.value] + have h := repetition_work (inputScale I) (2^((n+1)/2)) 120 503 _ + (by unfold inputScale; omega) Nat.one_le_two_pow + (DecisionRepetition.work + (fun x => (WordMeasuredDecision.round I hn (roundLogBudget I (by omega) hscale) x).1) + words _ (fun x => (round I hn (roundLogBudget I (by omega) hscale) hscale x).1)) + rw [show (120 : ℕ)+503+1 = 624 from rfl] at h + exact h + +theorem repeated_cells (I : Instance n) (hn : 180000000 ≤ n) + (hscale : Real.logb 2 (inputScale I : ℝ) ≤ (n : ℝ)/1000000000) + (words : Fin (inputScale I^120) → WordDecisionRound.Words I) : + (WordMeasuredDecision.repeated I hn hscale words).2 ≤ writableWordLimit I := by + let u := inputScale I + let C := compressionDictionaryCapacity n + have hu : 10000 ≤ u := by unfold u inputScale; omega + have hC : 1 ≤ C := Nat.one_le_pow _ _ (by decide) + have h := DecisionRepetitionCells.cells + (WordMeasuredDecision.round I hn (roundLogBudget I (by omega) hscale)) words + (40*u^14*(C+1)) (fun x => (round I hn _ hscale x).2) + apply h.trans + change 40*u^14*(C+1)+8 ≤ u^15*C + have hc : C+1 ≤ 2*C := by omega + have hs : 40*u^14*(C+1) ≤ 80*u^14*C := by + calc + _ ≤ 40*u^14*(2*C) := Nat.mul_le_mul_left _ hc + _ = _ := by ring + have h8 : 8 ≤ u^14*C := by + have hpow : u ≤ u^14 := by + simpa only [pow_one] using Nat.pow_le_pow_right (by omega : 0 < u) (by decide : 1 ≤ 14) + exact (show 8 ≤ u by omega).trans (hpow.trans (Nat.le_mul_of_pos_right _ hC)) + have ht : 81*u^14*C ≤ u^15*C := by + calc + _ ≤ u*u^14*C := Nat.mul_le_mul_right _ (Nat.mul_le_mul_right _ (by omega)) + _ = _ := by rw [←pow_succ'] + nlinarith only [hs,ht,h8] + +end LowSpaceSubsetSum.WordMeasuredBounds + +end + +end OAI diff --git a/lean/OAI/Combinatorics/LowSpaceSubsetSum/Word/WordMeasuredDecision.lean b/lean/OAI/Combinatorics/LowSpaceSubsetSum/Word/WordMeasuredDecision.lean new file mode 100644 index 0000000000000000000000000000000000000000..399e004e025945ade75dba3965131b14d239f662 --- /dev/null +++ b/lean/OAI/Combinatorics/LowSpaceSubsetSum/Word/WordMeasuredDecision.lean @@ -0,0 +1,117 @@ +import OAI.Combinatorics.LowSpaceSubsetSum.Word.WordSeedHistoryBounds +import OAI.Combinatorics.LowSpaceSubsetSum.Word.WordDecisionUniform +import OAI.Combinatorics.LowSpaceSubsetSum.Word.WordSampledAction + +namespace OAI + +/-! # Decision rounds with executed random-word generation + +The finite-word experiment carries the work and peak storage of seed +generation, retained seeds, and the prepared actions. +-/ + +noncomputable section +namespace LowSpaceSubsetSum.WordMeasuredDecision + +variable {n : ℕ} + +def asAction (r : WordSampledAction.Result) : (Bool × ℕ) × ℕ := + ((r.answer,r.work),r.cells) + +def compression (I : Instance n) (hn : 168000000 ≤ n) + (words : WordDecisionBranches.CompressionWords I) : (Bool × ℕ) × ℕ := + asAction (WordSampledAction.run + (WordSeedMeasured.compression (CompressionData.mk I) hn (wordWidth I) + ((Nat.clog_le_of_le_pow Nat.lt_two_pow_self.le).trans (by + unfold wordWidth inputScale; omega)) + (by unfold compressionPrimeExponent wordWidth inputScale; omega)) + (SampledCompressionCells.run (CompressionData.mk I) hn) + (WordProgram.finiteStream words) 0) + +def representationGenerator (I : Instance n) (hn : 10000 ≤ n) : + WordSeedMeasured.Execution (WordDecisionBranches.representationSampler I hn) := + WordSeedMeasured.bucketHistory I hn (wordWidth I) (WordSamplingBounds.word_width I) + +def representation (I : Instance n) (hn : 10000 ≤ n) + (hlog : Real.logb 2 ((mixerSize n : ℝ)+1)+1 ≤ (n : ℝ)/1000) + (words : WordDecisionBranches.RepresentationWords I) : (Bool × ℕ) × ℕ := + asAction (WordSampledAction.run + (representationGenerator I hn) + (WordDecisionBranches.representationAction I hn hlog) + (WordProgram.finiteStream words) 0) + +private theorem execute_projection {α : Type} [Fintype α] {w N : ℕ} + {S : SamplerCoupling α} (X : WordSeedRealization.Realization w N S) + (a : S.Seed → (Bool × ℕ) × ℕ) (words : Fin N → Fin (2^w)) : + WordSeedRealization.execute X (fun s => (a s).1.1) false words = + (WordSeedRealization.execute X a ((false,1),8) words).1.1 := by + unfold WordSeedRealization.execute + split <;> rfl + +theorem compression_value (I : Instance n) (hn : 168000000 ≤ n) + (words : WordDecisionBranches.CompressionWords I) : + (compression I hn words).1.1 = (WordDecisionBranches.compression I hn words).1.1 := by + unfold compression asAction + rw [WordSampledAction.finite_value,execute_projection] + rfl + +theorem representation_value (I : Instance n) (hn : 10000 ≤ n) + (hlog : Real.logb 2 ((mixerSize n : ℝ)+1)+1 ≤ (n : ℝ)/1000) + (words : WordDecisionBranches.RepresentationWords I) : + (representation I hn hlog words).1.1 = + (WordDecisionBranches.representation I hn hlog words).1.1 := by + have h := WordSampledAction.finite_value (representationGenerator I hn) + (WordDecisionBranches.representationAction I hn hlog) words + exact h.trans (execute_projection (WordDecisionBranches.representationSampler I hn) + (WordDecisionBranches.representationAction I hn hlog) words) + +def round (I : Instance n) (hn : 180000000 ≤ n) + (hlog : Real.logb 2 ((mixerSize n : ℝ)+1)+1 ≤ (n : ℝ)/1000) + (words : WordDecisionRound.Words I) : (Bool × ℕ) × ℕ := + WordDecisionRound.combine (compression I (by omega) words.1) + (representation I (by omega) hlog words.2) + +theorem round_value (I : Instance n) (hn : 180000000 ≤ n) + (hlog : Real.logb 2 ((mixerSize n : ℝ)+1)+1 ≤ (n : ℝ)/1000) + (words : WordDecisionRound.Words I) : + (round I hn hlog words).1.1 = (WordDecisionRound.run I hn hlog words).1.1 := by + change (_ || _) = (_ || _) + rw [compression_value,representation_value] + +def repeated (I : Instance n) (hn : 180000000 ≤ n) + (hscale : Real.logb 2 (inputScale I : ℝ) ≤ (n : ℝ)/1000000000) + (words : Fin (inputScale I^120) → WordDecisionRound.Words I) : (Bool × ℕ) × ℕ := + DecisionRepetitionCells.run (round I hn (roundLogBudget I (by omega) hscale)) words + +theorem repeated_value (I : Instance n) (hn : 180000000 ≤ n) + (hscale : Real.logb 2 (inputScale I : ℝ) ≤ (n : ℝ)/1000000000) + (words : Fin (inputScale I^120) → WordDecisionRound.Words I) : + (repeated I hn hscale words).1.1 = + (WordDecisionRound.repeated I hn hscale words).1.1 := by + simp only [repeated,WordDecisionRound.repeated,DecisionRepetitionCells.value, + DecisionRepetition.value] + congr 1 + funext x + exact round_value I hn _ x + +theorem sound (I : Instance n) (hn : 180000000 ≤ n) + (hscale : Real.logb 2 (inputScale I : ℝ) ≤ (n : ℝ)/1000000000) + (words : Fin (inputScale I^120) → WordDecisionRound.Words I) + (hy : (repeated I hn hscale words).1.1 = true) : Solvable I := + WordDecisionRound.repeated_sound I hn hscale words ((repeated_value I hn hscale words).symm.trans hy) + +theorem probability (I : Instance n) (hn : 180000000 ≤ n) + (hscale : Real.logb 2 (inputScale I : ℝ) ≤ (n : ℝ)/1000000000) + (hden : ((mixerSize n/2 : ℕ) : ℝ)+1 < + (2 : ℝ)^((1/1500 : ℝ)*(mixerSize n/2 : ℕ))) (hs : Solvable I) : + (2/3 : ℝ) < + (FiniteLaw.uniform : FiniteLaw (Fin (inputScale I^120) → WordDecisionRound.Words I)).probability + (fun words => (repeated I hn hscale words).1.1 = true) := by + simp only [repeated_value] + exact WordDecisionUniform.repeated_probability I hn hscale hden hs + +end LowSpaceSubsetSum.WordMeasuredDecision + +end + +end OAI diff --git a/lean/OAI/Combinatorics/LowSpaceSubsetSum/Word/WordPrimeRealization.lean b/lean/OAI/Combinatorics/LowSpaceSubsetSum/Word/WordPrimeRealization.lean new file mode 100644 index 0000000000000000000000000000000000000000..0fc8db8ca358e761fcc54dd48410a933a207526a --- /dev/null +++ b/lean/OAI/Combinatorics/LowSpaceSubsetSum/Word/WordPrimeRealization.lean @@ -0,0 +1,44 @@ +import OAI.Combinatorics.LowSpaceSubsetSum.Word.WordRangeRealization +import OAI.Combinatorics.LowSpaceSubsetSum.Counting.PrimeSamplerCoupling +import OAI.Combinatorics.LowSpaceSubsetSum.Compression.CompressionSamplerCoupling + +namespace OAI + +/-! # Word refinements for the prime calls used in both branches -/ + +noncomputable section +namespace LowSpaceSubsetSum.WordRealization + +def prime (w n ell : ℕ) (hell : 4 ≤ ell) (hw : ell ≤ w) : + Realization w (n^3) (primeCoupling hell n) := by + let : Nonempty ↥(primeRange ell) := (primeRange_nonempty hell).to_subtype + let : Nonempty {x : Fin (2 ^ ell) // primeEligible ell x} := + ⟨(primeEligibleEquiv hell).symm (Classical.choice inferInstance)⟩ + exact map (rejection w ell hw (n^3) (primeEligible ell)) (primeEligibleEquiv hell) + +def factor (w n ell : ℕ) (hw : ell ≤ w) : + Realization w (n^3) (factorCoupling n ell) := by + unfold factorCoupling + split + next h => exact enlarge (map (pure ()) (factorOneEquiv h)) (Nat.zero_le _) + next h => exact map (prime w n ell (by omega) hw) (factorPrimeEquiv (by omega)) + +def triplePrime (w n a b c : ℕ) (ha : a ≤ w) (hb : b ≤ w) (hc : c ≤ w) : + Realization w (3*n^3) (triplePrimeCoupling n a b c) := by + have h := map (prod (prod (factor w n a ha) (factor w n b hb)) + (factor w n c hc)) (tripleFactorEquiv a b c) + simpa only [triplePrimeCoupling, show (n^3+n^3)+n^3 = 3*n^3 by omega] using h + +def compression {n : ℕ} (D : CompressionData n) (hn : 168000000 ≤ n) + (w : ℕ) (hp : Nat.clog 2 n ≤ w) (hq : compressionPrimeExponent n ≤ w) : + Realization w (n*n^3+n^3) (D.sampler hn) := + bind (permutation w n n hp) (fun _ => CompressionSetup.PrimeSpace n) + (fun _ => primeCoupling (by unfold compressionPrimeExponent; omega) n) + (fun _ => prime w n (compressionPrimeExponent n) + (by unfold compressionPrimeExponent; omega) hq) + +end LowSpaceSubsetSum.WordRealization + +end + +end OAI diff --git a/lean/OAI/Combinatorics/LowSpaceSubsetSum/Word/WordProgram.lean b/lean/OAI/Combinatorics/LowSpaceSubsetSum/Word/WordProgram.lean new file mode 100644 index 0000000000000000000000000000000000000000..8ba42a8b479983a95dc19cd05b76ab15d66544de --- /dev/null +++ b/lean/OAI/Combinatorics/LowSpaceSubsetSum/Word/WordProgram.lean @@ -0,0 +1,147 @@ +import OAI.Combinatorics.LowSpaceSubsetSum.Counting.ExactWordDraw + +namespace OAI + +/-! # Sequential fair-word programs for the bounded samplers + +A draw reads one fresh word. Continuations are evaluated only after that +word is read. The finite expectation is the operational probability law; +there are no eligible-backup draws in this interface. +-/ + +namespace LowSpaceSubsetSum.WordProgram + +open scoped BigOperators +attribute [local instance] Classical.propDecidable + +inductive Program (w : ℕ) (α : Type) where + | pure : α → Program w α + | draw : (Fin (2^w) → Program w α) → Program w α + +variable {w : ℕ} {α β : Type} + +def bind : Program w α → (α → Program w β) → Program w β + | .pure a, next => next a + | .draw next, tail => .draw (fun x => bind (next x) tail) + +def map (f : α → β) (p : Program w α) : Program w β := bind p (fun a => .pure (f a)) + +noncomputable def expectation : Program w α → (α → ℝ) → ℝ + | .pure a, f => f a + | .draw next, f => (∑ x, expectation (next x) f) / (2^w : ℕ) + +noncomputable def probability (p : Program w α) (P : α → Prop) : ℝ := + expectation p (fun a => if P a then 1 else 0) + +theorem expectation_bind (p : Program w α) (next : α → Program w β) (f : β → ℝ) : + expectation (bind p next) f = expectation p (fun a => expectation (next a) f) := by + induction p with + | pure a => rfl + | draw branch ih => + simp only [bind, expectation, ih] + +theorem probability_map (f : α → β) (p : Program w α) (P : β → Prop) : + probability (map f p) P = probability p (fun a => P (f a)) := by + simp only [map, probability, expectation_bind, expectation] + +theorem expectation_sum {ι : Type} [Fintype ι] (p : Program w α) (f : ι → α → ℝ) : + expectation p (fun a => ∑ i, f i a) = ∑ i, expectation p (f i) := by + induction p with + | pure a => rfl + | draw branch ih => + simp only [expectation, ih] + rw [Finset.sum_comm, Finset.sum_div] + +theorem expectation_mul (p : Program w α) (f : α → ℝ) (c : ℝ) : + expectation p (fun a => f a*c) = expectation p f*c := by + induction p with + | pure a => rfl + | draw branch ih => + simp only [expectation, ih, ← Finset.sum_mul] + ring + +theorem expectation_eq_sum [Fintype α] (p : Program w α) (f : α → ℝ) : + expectation p f = ∑ a, probability p (fun x => x=a)*f a := by + classical + calc + expectation p f = expectation p (fun x => ∑ a, (if x=a then 1 else 0)*f a) := by + congr 1 + funext x + simp + _ = ∑ a, expectation p (fun x => (if x=a then 1 else 0)*f a) := expectation_sum p _ + _ = _ := by simp only [expectation_mul, probability] + +theorem expectation_of_probability [Fintype α] (p : Program w α) (μ : FiniteLaw α) + (h : ∀ P, probability p P = μ.probability P) (f : α → ℝ) : + expectation p f = μ.expectation f := by + rw [expectation_eq_sum] + simp only [h, FiniteLaw.probability_eq, FiniteLaw.expectation] + +theorem expectation_const (p : Program w α) (c : ℝ) : expectation p (fun _ => c) = c := by + induction p with + | pure a => rfl + | draw branch ih => + simp only [expectation, ih, Finset.sum_const, Finset.card_univ, Fintype.card_fin, + nsmul_eq_mul] + have h : ((2^w : ℕ) : ℝ) ≠ 0 := by positivity + exact mul_div_cancel_left₀ c h + +theorem probability_true (p : Program w α) : probability p (fun _ => True) = 1 := by + simp only [probability, ↓reduceIte] + exact expectation_const p 1 + +theorem expectation_nonneg (p : Program w α) (f : α → ℝ) (hf : ∀ a, 0 ≤ f a) : + 0 ≤ expectation p f := by + induction p with + | pure a => exact hf a + | draw branch ih => + exact div_nonneg (Finset.sum_nonneg (fun x _ => ih x)) (by positivity) + +theorem expectation_mono (p : Program w α) (f g : α → ℝ) (h : ∀ a, f a ≤ g a) : + expectation p f ≤ expectation p g := by + induction p with + | pure a => exact h a + | draw branch ih => + exact div_le_div_of_nonneg_right (Finset.sum_le_sum (fun x _ => ih x)) (by positivity) + +/-- A read-only random stream supplies the words in order. -/ +def run (stream : ℕ → Fin (2^w)) : Program w α → ℕ → α × ℕ + | .pure a, offset => (a, offset) + | .draw next, offset => run stream (next (stream offset)) (offset+1) + +/-- A structural draw bound, independent of the stream's values. -/ +inductive Bounded : Program w α → ℕ → Prop where + | pure (a : α) (N : ℕ) : Bounded (.pure a) N + | draw (next : Fin (2^w) → Program w α) (N : ℕ) + (bound : ∀ x, Bounded (next x) N) : Bounded (.draw next) (N+1) + +theorem run_bound (p : Program w α) (N : ℕ) (h : Bounded p N) + (stream : ℕ → Fin (2^w)) (offset : ℕ) : + offset ≤ (run stream p offset).2 ∧ (run stream p offset).2 ≤ offset+N := by + induction h generalizing offset with + | pure a N => exact ⟨le_rfl, Nat.le_add_right _ _⟩ + | draw next N bound ih => + have ht := ih (stream offset) (offset+1) + change offset ≤ (run stream (next (stream offset)) (offset+1)).2 ∧ + (run stream (next (stream offset)) (offset+1)).2 ≤ offset+(N+1) + omega + +theorem bound_add (p : Program w α) (M : ℕ) (hp : Bounded p M) (N : ℕ) : + Bounded p (N+M) := by + induction hp with + | pure a M => exact Bounded.pure a (N+M) + | draw branch M hb ih => + simpa only [Nat.add_assoc] using Bounded.draw branch (N+M) ih + +theorem bind_bound (p : Program w α) (N : ℕ) (hp : Bounded p N) + (next : α → Program w β) (M : ℕ) (hn : ∀ a, Bounded (next a) M) : + Bounded (bind p next) (N+M) := by + induction hp with + | pure a N => exact bound_add (next a) M (hn a) N + | draw branch N hb ih => + simpa only [bind, Nat.add_assoc, Nat.add_comm 1 M, Nat.add_left_comm] using + Bounded.draw (fun x => bind (branch x) next) (N+M) ih + +end LowSpaceSubsetSum.WordProgram + +end OAI diff --git a/lean/OAI/Combinatorics/LowSpaceSubsetSum/Word/WordRangeRealization.lean b/lean/OAI/Combinatorics/LowSpaceSubsetSum/Word/WordRangeRealization.lean new file mode 100644 index 0000000000000000000000000000000000000000..055e2d9059c75f6cb7269912999ea417b99f716b --- /dev/null +++ b/lean/OAI/Combinatorics/LowSpaceSubsetSum/Word/WordRangeRealization.lean @@ -0,0 +1,76 @@ +import OAI.Combinatorics.LowSpaceSubsetSum.Word.WordRealization +import OAI.Combinatorics.LowSpaceSubsetSum.Counting.FiniteProductSamplerCoupling + +namespace OAI + +/-! # Exact bounded word programs for range and permutation calls -/ + +noncomputable section +namespace LowSpaceSubsetSum.WordRealization + +def enlarge {w N M : ℕ} {α : Type} [Fintype α] {S : SamplerCoupling α} + (X : Realization w N S) (h : N ≤ M) : Realization w M S where + program := X.program + faithful := X.faithful + bounded := by + have hb := WordProgram.bound_add X.program N X.bounded (M-N) + simpa only [Nat.sub_add_cancel h] using hb + +def prod {w N M : ℕ} {α β : Type} [Fintype α] [Fintype β] + {S : SamplerCoupling α} {T : SamplerCoupling β} + (X : Realization w N S) (Y : Realization w M T) : + Realization w (N+M) (S.prod T) := + map (bind X (fun _ => β) (fun _ => T) (fun _ => Y)) (Equiv.sigmaEquivProd α β) + +def range (w n D : ℕ) (hD : 1 < D) (hw : Nat.clog 2 D ≤ w) : + Realization w (n^3) (rangeCoupling hD n) := by + let : Nonempty (Fin D) := ⟨⟨0, by omega⟩⟩ + let : Nonempty {x : Fin (2 ^ Nat.clog 2 D) // rangeEligible D x} := + ⟨(rangeEligibleEquiv D).symm ⟨0, by omega⟩⟩ + exact map (rejection w (Nat.clog 2 D) hw (n^3) (rangeEligible D)) (rangeEligibleEquiv D) + +def fin (w n D : ℕ) [NeZero D] (hw : Nat.clog 2 D ≤ w) : + Realization w (n^3) (finCoupling n D) := by + unfold finCoupling + split + next h => exact range w n D h hw + next h => exact enlarge (pure (⟨0, Nat.pos_of_ne_zero (NeZero.ne D)⟩ : Fin D)) (Nat.zero_le _) + +def pi (w N : ℕ) : (k : ℕ) → (A : Fin k → Type) → [∀ i, Fintype (A i)] → + (S : ∀ i, SamplerCoupling (A i)) → (∀ i, Realization w N (S i)) → + Realization w (k*N) (SamplerCoupling.pi k A S) + | 0, A, _, _, _ => by + simpa only [Nat.zero_mul, SamplerCoupling.pi] using + (pure (w := w) (fun i : Fin 0 => (Fin.elim0 i : A i))) + | k+1, A, _, S, X => by + have h := map (prod (X 0) + (pi w N k (fun i => A i.succ) (fun i => S i.succ) (fun i => X i.succ))) + (Fin.consEquiv A) + simpa only [SamplerCoupling.pi, Nat.add_mul, Nat.one_mul, Nat.add_comm] using h + +def permutation (w n : ℕ) : (k : ℕ) → Nat.clog 2 k ≤ w → + Realization w (k*n^3) (permutationCoupling n k) + | 0, _ => by + simpa only [Nat.zero_mul, permutationCoupling] using (pure (w := w) (Equiv.refl (Fin 0))) + | k+1, hw => by + have hk : Nat.clog 2 k ≤ w := + (Nat.clog_mono_right 2 (by omega : k ≤ k+1)).trans hw + have h := map (prod (fin w n (k+1) hw) (permutation w n k hk)) + Equiv.Perm.decomposeFin.symm + simpa only [permutationCoupling, Nat.add_mul, Nat.one_mul, Nat.add_comm] using h + +def finiteChoice (w n : ℕ) (A : Type) [Fintype A] [Nonempty A] + (hw : Nat.clog 2 (Fintype.card A) ≤ w) : + Realization w (n^3) (finiteChoiceCoupling n A) := + map (fin w n (Fintype.card A) hw) (Fintype.equivFin A).symm + +def finitePermutation (w n : ℕ) (A : Type) [Fintype A] [DecidableEq A] + (hw : Nat.clog 2 (Fintype.card A) ≤ w) : + Realization w (Fintype.card A*n^3) (finitePermutationCoupling n A) := + map (permutation w n (Fintype.card A) hw) (Equiv.permCongr (Fintype.equivFin A).symm) + +end LowSpaceSubsetSum.WordRealization + +end + +end OAI diff --git a/lean/OAI/Combinatorics/LowSpaceSubsetSum/Word/WordRealization.lean b/lean/OAI/Combinatorics/LowSpaceSubsetSum/Word/WordRealization.lean new file mode 100644 index 0000000000000000000000000000000000000000..ef8f1bd8dbe4c5d7a2f84f8d1da7f5d080c7224b --- /dev/null +++ b/lean/OAI/Combinatorics/LowSpaceSubsetSum/Word/WordRealization.lean @@ -0,0 +1,96 @@ +import OAI.Combinatorics.LowSpaceSubsetSum.Word.WordRejection +import OAI.Combinatorics.LowSpaceSubsetSum.Search.StoppedSamplerLaw + +namespace OAI + +/-! # Exact fair-word refinements of the stopped sampler constructors -/ + +noncomputable section +namespace LowSpaceSubsetSum.WordRealization + +open WordProgram +attribute [local instance] Classical.propDecidable + +structure Realization (w N : ℕ) {α : Type} [Fintype α] (S : SamplerCoupling α) where + program : Program w (Option α) + faithful : ∀ P, WordProgram.probability program P = S.boundedLaw.probability P + bounded : WordProgram.Bounded program N + +variable {w N M : ℕ} {α β : Type} [Fintype α] [Fintype β] + +def pure (a : α) : Realization w 0 (SamplerCoupling.pure a) where + program := .pure (some a) + faithful P := by + change (if P (some a) then (1 : ℝ) else 0) = + ((FiniteLaw.uniform (Ω := Unit)).map (fun _ => some a)).probability P + rw [FiniteLaw.map_probability] + by_cases h : P (some a) + · simp only [h, ↓reduceIte, FiniteLaw.probability_true] + · simp only [h, ↓reduceIte, FiniteLaw.probability, Finset.sum_const_zero] + bounded := Bounded.pure _ 0 + +def map {S : SamplerCoupling α} (X : Realization w N S) (f : α → β) : + Realization w N (S.map f) where + program := WordProgram.map (Option.map f) X.program + faithful P := by + rw [WordProgram.probability_map, X.faithful] + dsimp only [SamplerCoupling.boundedLaw, SamplerCoupling.map] + rw [FiniteLaw.map_probability, FiniteLaw.map_probability] + + bounded := by + simpa only [WordProgram.map, Nat.add_zero] using + WordProgram.bind_bound X.program N X.bounded (fun a => .pure (a.map f)) 0 + (fun _ => Bounded.pure _ 0) + +def continuation (B : α → Type) [∀ a, Fintype (B a)] + (T : ∀ a, SamplerCoupling (B a)) (Y : ∀ a, Realization w M (T a)) : + Option α → Program w (Option (Sigma B)) + | none => .pure none + | some a => WordProgram.map (Option.map (fun b => ⟨a,b⟩)) (Y a).program + +omit [Fintype α] in +theorem continuation_probability (B : α → Type) [∀ a, Fintype (B a)] + (T : ∀ a, SamplerCoupling (B a)) (Y : ∀ a, Realization w M (T a)) + (P : Option (Sigma B) → Prop) (a : Option α) : + WordProgram.probability (continuation B T Y a) P = + StoppedSamplerLaw.nextProbability B T P a := by + cases a with + | none => rfl + | some a => + exact (WordProgram.probability_map _ (Y a).program P).trans ((Y a).faithful _) + +def bind {S : SamplerCoupling α} (X : Realization w N S) + (B : α → Type) [∀ a, Fintype (B a)] (T : ∀ a, SamplerCoupling (B a)) + (Y : ∀ a, Realization w M (T a)) : Realization w (N+M) (S.bind B T) where + program := WordProgram.bind X.program (continuation B T Y) + faithful P := by + change WordProgram.expectation (WordProgram.bind X.program (continuation B T Y)) + (fun x => if P x then 1 else 0) = _ + rw [WordProgram.expectation_bind] + change WordProgram.expectation X.program + (fun a => WordProgram.probability (continuation B T Y a) P) = _ + simp only [continuation_probability] + rw [WordProgram.expectation_of_probability X.program S.boundedLaw X.faithful] + exact (StoppedSamplerLaw.bind_probability S B T P).symm + bounded := by + apply WordProgram.bind_bound X.program N X.bounded _ M + intro a + cases a with + | none => exact Bounded.pure none M + | some a => + simpa only [continuation, WordProgram.map, Nat.add_zero] using + WordProgram.bind_bound (Y a).program M (Y a).bounded + (fun x => .pure (x.map (fun b => (⟨a,b⟩ : Sigma B)))) 0 (fun _ => Bounded.pure _ 0) + +def rejection (w k : ℕ) (hk : k ≤ w) (N : ℕ) + (A : Fin (2^k) → Prop) [DecidablePred A] [Nonempty {a : Fin (2^k) // A a}] : + Realization w N (firstAcceptCoupling A N) where + program := WordRejection.sample w k N A + faithful := WordRejection.sample_probability w k hk N A + bounded := WordRejection.sample_bounded w k N A + +end LowSpaceSubsetSum.WordRealization + +end + +end OAI diff --git a/lean/OAI/Combinatorics/LowSpaceSubsetSum/Word/WordRejection.lean b/lean/OAI/Combinatorics/LowSpaceSubsetSum/Word/WordRejection.lean new file mode 100644 index 0000000000000000000000000000000000000000..74e29d36547a45b37a78e1d0d6ee9b0ea199323d --- /dev/null +++ b/lean/OAI/Combinatorics/LowSpaceSubsetSum/Word/WordRejection.lean @@ -0,0 +1,69 @@ +import OAI.Combinatorics.LowSpaceSubsetSum.Word.WordTuple +import OAI.Combinatorics.LowSpaceSubsetSum.Counting.SamplerAttempts + +namespace OAI + +/-! # A fair-word implementation of the measured bounded rejection loop + +Only the polynomial-size candidate tuple is drawn and retained. The same +measured evaluator then supplies output, read count, and test-work count. +-/ + +namespace LowSpaceSubsetSum.WordRejection + +open WordProgram + +def run (w k N : ℕ) (evaluate : Fin (2^k) → Bool × ℕ) : + Program w (Option (Fin (2^k)) × ℕ × ℕ) := + WordProgram.map (fun f => SamplerAttempts.runCostAcc evaluate N + (fun i => ExactWordDraw.low w k (f i)) 0 0) (WordTuple.sample N) + +theorem bounded (w k N : ℕ) (evaluate : Fin (2^k) → Bool × ℕ) : + Bounded (run w k N evaluate) N := by + simpa only [run, WordProgram.map, Nat.add_zero] using + WordProgram.bind_bound (WordTuple.sample (w := w) N) N (WordTuple.bounded N) + (fun f => .pure (SamplerAttempts.runCostAcc evaluate N + (fun i => ExactWordDraw.low w k (f i)) 0 0)) 0 (fun _ => Bounded.pure _ 0) + +theorem probability (w k : ℕ) (hk : k ≤ w) (N : ℕ) + (A : Fin (2^k) → Prop) [DecidablePred A] [Nonempty {a : Fin (2^k) // A a}] + (evaluate : Fin (2^k) → Bool × ℕ) + (P : (Option (Fin (2^k)) × ℕ × ℕ) → Prop) : + WordProgram.probability (run w k N evaluate) P = + (firstAcceptCoupling A N).law.probability + (fun s => P (SamplerAttempts.runCostAcc evaluate N s.1 0 0)) := by + rw [run, WordProgram.probability_map, WordTuple.probability] + exact (ExactWordDraw.candidates_words w k hk A N + (fun f => P (SamplerAttempts.runCostAcc evaluate N f 0 0))).symm + +def sample (w k N : ℕ) (A : Fin (2^k) → Prop) [DecidablePred A] : + Program w (Option {a : Fin (2^k) // A a}) := + WordProgram.map (fun f => firstAcceptSubtype A N + (fun i => ExactWordDraw.low w k (f i))) (WordTuple.sample N) + +theorem sample_bounded (w k N : ℕ) (A : Fin (2^k) → Prop) [DecidablePred A] : + Bounded (sample w k N A) N := by + simpa only [sample, WordProgram.map, Nat.add_zero] using + WordProgram.bind_bound (WordTuple.sample (w := w) N) N (WordTuple.bounded N) + (fun f => .pure (firstAcceptSubtype A N (fun i => ExactWordDraw.low w k (f i)))) 0 + (fun _ => Bounded.pure _ 0) + +theorem sample_probability (w k : ℕ) (hk : k ≤ w) (N : ℕ) + (A : Fin (2^k) → Prop) [DecidablePred A] [Nonempty {a : Fin (2^k) // A a}] + (P : Option {a : Fin (2^k) // A a} → Prop) : + WordProgram.probability (sample w k N A) P = + (firstAcceptCoupling A N).boundedLaw.probability P := by + rw [sample, WordProgram.probability_map, WordTuple.probability, + SamplerCoupling.boundedLaw, FiniteLaw.map_probability] + exact (ExactWordDraw.firstAccept_words w k hk A N P).symm + +theorem sample_expectation (w k : ℕ) (hk : k ≤ w) (N : ℕ) + (A : Fin (2^k) → Prop) [DecidablePred A] [Nonempty {a : Fin (2^k) // A a}] + (f : Option {a : Fin (2^k) // A a} → ℝ) : + WordProgram.expectation (sample w k N A) f = + (firstAcceptCoupling A N).boundedLaw.expectation f := + WordProgram.expectation_of_probability _ _ (sample_probability w k hk N A) f + +end LowSpaceSubsetSum.WordRejection + +end OAI diff --git a/lean/OAI/Combinatorics/LowSpaceSubsetSum/Word/WordRepresentationDraws.lean b/lean/OAI/Combinatorics/LowSpaceSubsetSum/Word/WordRepresentationDraws.lean new file mode 100644 index 0000000000000000000000000000000000000000..cf0da5f45b41820d6906190037227d3e12e63097 --- /dev/null +++ b/lean/OAI/Combinatorics/LowSpaceSubsetSum/Word/WordRepresentationDraws.lean @@ -0,0 +1,79 @@ +import OAI.Combinatorics.LowSpaceSubsetSum.Word.WordPrimeRealization +import OAI.Combinatorics.LowSpaceSubsetSum.Separators.SeparatorSamplerCoupling + +namespace OAI + +/-! # Word programs for signs, fixed-size samples, and separator families -/ + +noncomputable section +namespace LowSpaceSubsetSum.WordRealization + +def bits (w n : ℕ) (hw : 1 ≤ w) : Realization w n (bitArrayCoupling n) where + program := WordProgram.map + (fun f => some (fun i => finTwoEquiv (ExactWordDraw.low w 1 (f i)))) (WordTuple.sample n) + faithful P := by + rw [WordProgram.probability_map, WordTuple.probability] + rw [ExactWordDraw.uniform_tuple w 1 hw n + (fun f => P (some (fun i => finTwoEquiv (f i))))] + let e : (Fin n → Fin 2) ≃ (Fin n → Bool) := + Equiv.piCongrRight (fun _ => finTwoEquiv) + have he := FiniteLaw.map_equiv_uniform e + change (FiniteLaw.uniform : FiniteLaw (Fin n → Fin 2)).probability + (fun f => P (some (e f))) = _ + have hp := congrArg (fun μ : FiniteLaw (Fin n → Bool) => + μ.probability (fun f => P (some f))) he + rw [FiniteLaw.map_probability] at hp + apply hp.trans + change (FiniteLaw.uniform : FiniteLaw (Fin n → Bool)).probability (fun f => P (some f)) = + ((FiniteLaw.uniform : FiniteLaw (Fin n → Bool)).map some).probability P + rw [FiniteLaw.map_probability] + bounded := by + simpa only [WordProgram.map, Nat.add_zero] using + WordProgram.bind_bound (WordTuple.sample (w := w) n) n (WordTuple.bounded n) + (fun f => .pure (some (fun i => finTwoEquiv (ExactWordDraw.low w 1 (f i))))) 0 + (fun _ => WordProgram.Bounded.pure _ 0) + +def signs (w n : ℕ) (hw : 1 ≤ w) : Realization w n (signCoupling n) := + map (bits w n hw) (bitsSubsetEquiv n) + +def subset (w n g : ℕ) (K : Finset (Fin g)) (hw : Nat.clog 2 g ≤ w) : + Realization w (g*n^3) (subsetCoupling n g K) := + map (permutation w n g hw) (permutationBlock K) + +def fixedSize (w n g e : ℕ) (he : e ≤ g) (hw : Nat.clog 2 g ≤ w) : + Realization w (g*n^3) (fixedSizeCoupling n g e he) := + map (subset w n g (initialSubset g e he) hw) (initialSubsetEquiv g e he) + +def families {g : ℕ} (S : SeparatorExpectation.RoundedParameters g) + (w n : ℕ) (hw : Nat.clog 2 g ≤ w) : + Realization w (4*(11*2^g*(g*n^3))) (S.samplerCoupling n) := + pi w (11*2^g*(g*n^3)) 4 _ _ (fun i => + enlarge (pi w (g*n^3) (S.counts i) _ _ + (fun _ => fixedSize w n g (S.e i) (S.size_le i) hw)) + (Nat.mul_le_mul_right _ (S.counts_le i))) + +def layout {n : ℕ} (R : RepresentationSetup n) (w : ℕ) + (hp : Nat.clog 2 n ≤ w) (hb : 1 ≤ w) : + Realization w (n*n^3+n) R.layoutCoupling := + prod (permutation w n n hp) (signs w n hb) + +def guesses {n : ℕ} (R : RepresentationSetup n) (w : ℕ) + (hw : Nat.clog 2 (CanonicalGuesses.width n) ≤ w) : + Realization w (3*n^3) R.guessesCoupling := + pi w (n^3) 3 _ _ (fun _ => map (fin w n (CanonicalGuesses.width n) hw) + (CanonicalGuesses.encoding n)) + +def partition {n : ℕ} (R : RepresentationSetup n) (z : RepresentationSetup.Layout n) + (i : Fin 3) (w : ℕ) + (hw : Nat.clog 2 (RepresentationSetup.blockCount i * + (2 * RepresentationSetup.blockHalf n i)) ≤ w) : + Realization w ((RepresentationSetup.blockCount i * + (2 * RepresentationSetup.blockHalf n i))*n^3) (CanonicalPartition.coupling R z i) := + map (map (permutation w n _ hw) (Equiv.permCongr (CanonicalPartition.ranks R z i).symm)) + (coloringOfPermutation (CanonicalPartition.base R z i)) + +end LowSpaceSubsetSum.WordRealization + +end + +end OAI diff --git a/lean/OAI/Combinatorics/LowSpaceSubsetSum/Word/WordRepresentationHistory.lean b/lean/OAI/Combinatorics/LowSpaceSubsetSum/Word/WordRepresentationHistory.lean new file mode 100644 index 0000000000000000000000000000000000000000..965350b7b4b145f3ccb20196dbf00269fcdb425b --- /dev/null +++ b/lean/OAI/Combinatorics/LowSpaceSubsetSum/Word/WordRepresentationHistory.lean @@ -0,0 +1,106 @@ +import OAI.Combinatorics.LowSpaceSubsetSum.Word.WordRepresentationDraws +import OAI.Combinatorics.LowSpaceSubsetSum.Representation.RepresentationScalarBounds + +namespace OAI + +/-! # Exact word programs for the complete dependent representation history -/ + +noncomputable section +namespace LowSpaceSubsetSum.WordRealization + +private theorem clog_le (k w : ℕ) (h : k ≤ w) : Nat.clog 2 k ≤ w := + (Nat.clog_le_of_le_pow (Nat.lt_two_pow_self.le)).trans h + +def partitions {n : ℕ} (R : RepresentationSetup n) (z : RepresentationSetup.Layout n) + (w : ℕ) (hw : n ≤ w) : Realization w (3*(n*n^3)) (R.partitionsCoupling z) := + pi w (n*n^3) 3 _ _ (fun i => by + have hs : RepresentationSetup.blockCount i * (2*RepresentationSetup.blockHalf n i) ≤ n := by + rw [← CanonicalPartition.size_eq R z i] + simpa only [Fintype.card_fin] using Finset.card_le_univ (R.orderedMixers z i) + exact enlarge (partition R z i w (clog_le _ _ (hs.trans hw))) + (Nat.mul_le_mul_right _ hs)) + +def nested {n : ℕ} (R : RepresentationSetup n) (z : RepresentationSetup.Layout n) + (w : ℕ) (hw : n ≤ w) : Realization w (3*n^3) (R.nestedCoupling z) := + triplePrime w n _ _ _ ((R.factorExponents_le_n z 0).trans hw) + ((R.factorExponents_le_n z 1).trans hw) ((R.factorExponents_le_n z 2).trans hw) + +def residues {n : ℕ} (R : RepresentationSetup n) (hn : 1 ≤ n) + {z : RepresentationSetup.Layout n} (p : R.PrimeSpace z) (w : ℕ) (hw : 3*n ≤ w) : + Realization w (n^3+(n^3+n^3)) (R.residuesCoupling p) := by + let : NeZero (prefixModulus p.val 0) := ⟨(prefixModulus_pos p 0).ne'⟩ + let : NeZero (prefixModulus p.val 1) := ⟨(prefixModulus_pos p 1).ne'⟩ + let : NeZero (prefixModulus p.val 2) := ⟨(prefixModulus_pos p 2).ne'⟩ + have h (i : Fin 3) : Nat.clog 2 (prefixModulus p.val i) ≤ w := + (Nat.clog_le_of_le_pow (RepresentationScalarBounds.prefix_bound R hn z p i)).trans hw + exact prod (fin w n _ (h 0)) (prod (fin w n _ (h 1)) (fin w n _ (h 2))) + +def extraPrime {n : ℕ} (R : RepresentationSetup n) (z : RepresentationSetup.Layout n) + (hn : 100 ≤ n) (w : ℕ) (hw : n ≤ w) : + Realization w (n^3) (R.extraPrimeCoupling z hn) := + prime w n _ (R.extraPrimeParameter_range z hn).1 + ((R.extraPrimeParameter_range z hn).2.trans hw) + +def guessHistory {n : ℕ} (R : RepresentationSetup n) (w : ℕ) (hw : n+1 ≤ w) : + Realization w ((n*n^3+n)+3*n^3) R.guessHistoryCoupling := by + have hg : CanonicalGuesses.width n ≤ n+1 := by + unfold CanonicalGuesses.width CanonicalGuesses.upper CanonicalGuesses.lower mixerSize + omega + exact bind (layout R w (clog_le _ _ (by omega)) (by omega)) + (fun _ => RepresentationSetup.Guesses n) (fun _ => R.guessesCoupling) + (fun _ => guesses R w (clog_le _ _ (hg.trans hw))) + +def partitionHistory {n : ℕ} (R : RepresentationSetup n) (w : ℕ) (hw : n+1 ≤ w) : + Realization w (((n*n^3+n)+3*n^3)+3*(n*n^3)) R.partitionHistoryCoupling := + bind (guessHistory R w hw) (fun h => R.Partitions h.1) + (fun h => R.partitionsCoupling h.1) (fun h => partitions R h.1 w (by omega)) + +def primeHistory {n : ℕ} (R : RepresentationSetup n) (w : ℕ) (hw : n+1 ≤ w) : + Realization w ((((n*n^3+n)+3*n^3)+3*(n*n^3))+3*n^3) R.primeHistoryCoupling := + bind (partitionHistory R w hw) (fun h => R.PrimeSpace h.1.1) + (fun h => R.nestedCoupling h.1.1) (fun h => nested R h.1.1 w (by omega)) + +def trialHistory {n : ℕ} (R : RepresentationSetup n) (hn : 1 ≤ n) + (w : ℕ) (hw : 3*n+1 ≤ w) : + Realization w (((((n*n^3+n)+3*n^3)+3*(n*n^3))+3*n^3)+(n^3+(n^3+n^3))) + R.trialHistoryCoupling := + bind (primeHistory R w (by omega)) (fun h => R.Residues h.2) + (fun h => R.residuesCoupling h.2) (fun h => residues R hn h.2 w (by omega)) + +def extraHistory {n : ℕ} (R : RepresentationSetup n) (hn : 100 ≤ n) + (w : ℕ) (hw : 3*n+1 ≤ w) : + Realization w ((((((n*n^3+n)+3*n^3)+3*(n*n^3))+3*n^3)+(n^3+(n^3+n^3)))+n^3) + (R.extraHistoryCoupling hn) := by + unfold RepresentationSetup.extraHistoryCoupling + exact bind (S := R.trialHistoryCoupling) (trialHistory R (by omega) w hw) (fun h => R.ExtraPrimeSpace h.1.1.1.1) + (fun h => R.extraPrimeCoupling h.1.1.1.1 hn) + (fun h => extraPrime R h.1.1.1.1 hn w (by omega)) + +def historyReads (n : ℕ) : ℕ := + ((((((n*n^3+n)+3*n^3)+3*(n*n^3))+3*n^3)+(n^3+(n^3+n^3)))+n^3)+ + 4*(11*2^(2*RepresentationSetup.blockHalf n 0)*((2*RepresentationSetup.blockHalf n 0)*n^3)) + +def separatorDraws {n : ℕ} (R : RepresentationSetup n) + (h : R.PrimeHistory) (hn : 2200 ≤ n) (w : ℕ) + (hw : Nat.clog 2 (2*RepresentationSetup.blockHalf n 0) ≤ w) : + Realization w (4*(11*2^(2*RepresentationSetup.blockHalf n 0)* + ((2*RepresentationSetup.blockHalf n 0)*n^3))) (R.separatorCoupling h hn) := + families (RepresentationSetup.separatorParameters h.1.1.2 hn) w n hw + +def bucketHistory {n : ℕ} (R : RepresentationSetup n) (hn : 10000 ≤ n) + (w : ℕ) (hw : 3*n+1 ≤ w) := + bind (S := R.extraHistoryCoupling (by omega)) (extraHistory R (by omega) w hw) + (fun h => R.SeparatorDraws h.1.1 (by omega)) + (fun h => R.separatorCoupling h.1.1 (by omega)) + (fun h => separatorDraws R h.1.1 (by omega) w (clog_le _ _ (by + have hg : 2*RepresentationSetup.blockHalf n 0 ≤ n := by + unfold RepresentationSetup.blockHalf + simp only [Matrix.cons_val_zero] + omega + omega))) + +end LowSpaceSubsetSum.WordRealization + +end + +end OAI diff --git a/lean/OAI/Combinatorics/LowSpaceSubsetSum/Word/WordRunLaw.lean b/lean/OAI/Combinatorics/LowSpaceSubsetSum/Word/WordRunLaw.lean new file mode 100644 index 0000000000000000000000000000000000000000..49c3462ce8dd5539372ce7b2bc6ac191c183c8a9 --- /dev/null +++ b/lean/OAI/Combinatorics/LowSpaceSubsetSum/Word/WordRunLaw.lean @@ -0,0 +1,67 @@ +import OAI.Combinatorics.LowSpaceSubsetSum.Word.WordTuple + +namespace OAI + +/-! # Finite fair-word streams realize the sequential operational law -/ + +noncomputable section +namespace LowSpaceSubsetSum.WordProgram + +open scoped BigOperators +variable {w : ℕ} {α : Type} + +def finiteStream {N : ℕ} (words : Fin N → Fin (2^w)) (i : ℕ) : Fin (2^w) := + if h : i < N then words ⟨i,h⟩ else 0 + +theorem run_shift (stream : ℕ → Fin (2^w)) (p : Program w α) (offset k : ℕ) : + run stream p (offset+k) = + let out := run (fun i => stream (i+k)) p offset + (out.1,out.2+k) := by + induction p generalizing offset with + | pure a => rfl + | draw branch ih => + simp only [run] + simpa only [Nat.add_assoc, Nat.add_comm k 1, Nat.add_left_comm] using + ih (stream (offset+k)) (offset+1) + +theorem finiteStream_cons (x : Fin (2^w)) {N : ℕ} (xs : Fin N → Fin (2^w)) : + (fun i => finiteStream (Fin.cons x xs) (i+1)) = finiteStream xs := by + funext i + unfold finiteStream + by_cases h : i < N + · simp only [show i+1 < N+1 by omega, ↓reduceDIte, h] + change Fin.cons (n := N) (α := fun _ => Fin (2^w)) x xs (Fin.succ ⟨i,h⟩) = xs ⟨i,h⟩ + rfl + · simp only [show ¬i+1 < N+1 by omega, ↓reduceDIte, h] + +theorem draw_cons_value (branch : Fin (2^w) → Program w α) {N : ℕ} + (x : Fin (2^w)) (xs : Fin N → Fin (2^w)) : + (run (finiteStream (Fin.cons x xs)) (.draw branch) 0).1 = + (run (finiteStream xs) (branch x) 0).1 := by + have hzero : finiteStream (Fin.cons x xs) 0 = x := by + simp [finiteStream] + simp only [run, hzero, Nat.zero_add] + have h := congrArg Prod.fst (run_shift (finiteStream (Fin.cons x xs)) (branch x) 0 1) + simpa only [Nat.zero_add, finiteStream_cons] using h + +theorem run_expectation (p : Program w α) (N : ℕ) (hp : Bounded p N) (f : α → ℝ) : + expectation p f = (FiniteLaw.uniform : FiniteLaw (Fin N → Fin (2^w))).expectation + (fun words => f (run (finiteStream words) p 0).1) := by + induction hp with + | pure a N => + simp only [expectation, run, FiniteLaw.expectation, ← Finset.sum_mul, + FiniteLaw.total, one_mul] + | draw branch N hb ih => + rw [WordTuple.cons_expectation] + simp only [expectation, draw_cons_value, ih] + +theorem run_probability (p : Program w α) (N : ℕ) (hp : Bounded p N) (P : α → Prop) : + probability p P = (FiniteLaw.uniform : FiniteLaw (Fin N → Fin (2^w))).probability + (fun words => P (run (finiteStream words) p 0).1) := by + rw [probability, run_expectation p N hp, FiniteLaw.probability_eq_expectation] + +end LowSpaceSubsetSum.WordProgram + +end + +end OAI diff --git a/lean/OAI/Combinatorics/LowSpaceSubsetSum/Word/WordSampledAction.lean b/lean/OAI/Combinatorics/LowSpaceSubsetSum/Word/WordSampledAction.lean new file mode 100644 index 0000000000000000000000000000000000000000..db30e98789b48055d94f5bc70ff28e024b5ae623 --- /dev/null +++ b/lean/OAI/Combinatorics/LowSpaceSubsetSum/Word/WordSampledAction.lean @@ -0,0 +1,91 @@ +import OAI.Combinatorics.LowSpaceSubsetSum.Word.WordSeedMeasured +import OAI.Combinatorics.LowSpaceSubsetSum.Word.WordSeedExecution + +namespace OAI + +/-! # Sequential composition of measured seed generation and a stored action + +The generated seed stays resident while the prepared action runs. Generation +work and action work are both charged, including the exhaustion branch. +-/ + +noncomputable section +namespace LowSpaceSubsetSum.WordSampledAction + +open WordSeedRealization WordSeedMeasured + +variable {w N : ℕ} {α : Type} [Fintype α] {S : SamplerCoupling α} + +structure Result where + answer : Bool + work : ℕ + cells : ℕ + cursor : ℕ + +def run {X : Realization w N S} (E : Execution X) + (action : S.Seed → (Bool × ℕ) × ℕ) + (stream : ℕ → Fin (2^w)) (cursor : ℕ) : Result := + let generated := E.run stream cursor + match generated.accepted with + | none => ⟨false,generated.work+1,max generated.cells 8,generated.cursor⟩ + | some accepted => + let out := action accepted.seed.val + ⟨out.1.1,generated.work+out.1.2+1, + max generated.cells (generated.retained+out.2+8),generated.cursor⟩ + +theorem value {X : Realization w N S} (E : Execution X) + (action : S.Seed → (Bool × ℕ) × ℕ) + (stream : ℕ → Fin (2^w)) (cursor : ℕ) : + (run E action stream cursor).answer = + match (WordProgram.run stream X.program cursor).1 with + | none => false | some s => (action s.val).1.1 := by + have h := congrArg Prod.fst (E.value stream cursor) + rw [←h] + cases hg : (E.run stream cursor).accepted <;> + simp only [run,hg,Option.map_none,Option.map_some] + +theorem finite_value {X : Realization w N S} (E : Execution X) + (action : S.Seed → (Bool × ℕ) × ℕ) (words : Fin N → Fin (2^w)) : + (run E action (WordProgram.finiteStream words) 0).answer = + WordSeedRealization.execute X (fun s => (action s).1.1) false words := + value E action _ 0 + +theorem cursor_eq {X : Realization w N S} (E : Execution X) + (action : S.Seed → (Bool × ℕ) × ℕ) + (stream : ℕ → Fin (2^w)) (cursor : ℕ) : + (run E action stream cursor).cursor = (WordProgram.run stream X.program cursor).2 := by + have h := congrArg Prod.snd (E.value stream cursor) + rw [←h] + cases hg : (E.run stream cursor).accepted <;> simp only [run,hg] + +theorem cursor_le {X : Realization w N S} (E : Execution X) + (action : S.Seed → (Bool × ℕ) × ℕ) + (stream : ℕ → Fin (2^w)) (cursor : ℕ) : + (run E action stream cursor).cursor ≤ cursor+N := by + rw [cursor_eq] + exact (WordProgram.run_bound X.program N X.bounded stream cursor).2 + +theorem bounded {X : Realization w N S} (E : Execution X) + (action : S.Seed → (Bool × ℕ) × ℕ) (W C R V D : ℕ) + (hE : E.Bounded W C R) (hV : ∀ s, (action s).1.2 ≤ V) + (hD : ∀ s, (action s).2 ≤ D) + (stream : ℕ → Fin (2^w)) (cursor : ℕ) : + (run E action stream cursor).work ≤ W+V+1 ∧ + (run E action stream cursor).cells ≤ max C (R+D+8) := by + have he := hE stream cursor + cases ha : (E.run stream cursor).accepted with + | none => + simp only [run,ha] + exact ⟨by omega,max_le (he.2.1.trans (le_max_left _ _)) + ((show 8 ≤ R+D+8 by omega).trans (le_max_right _ _))⟩ + | some a => + simp only [run,ha] + have hv := hV a.seed.val + have hd := hD a.seed.val + exact ⟨by omega,max_le_max he.2.1 (by omega)⟩ + +end LowSpaceSubsetSum.WordSampledAction + +end + +end OAI diff --git a/lean/OAI/Combinatorics/LowSpaceSubsetSum/Word/WordSamplingBounds.lean b/lean/OAI/Combinatorics/LowSpaceSubsetSum/Word/WordSamplingBounds.lean new file mode 100644 index 0000000000000000000000000000000000000000..585500de8fb98d35ca2eb01de8ef97ebcacc12e8 --- /dev/null +++ b/lean/OAI/Combinatorics/LowSpaceSubsetSum/Word/WordSamplingBounds.lean @@ -0,0 +1,82 @@ +import OAI.Combinatorics.LowSpaceSubsetSum.Word.WordRepresentationHistory +import OAI.Combinatorics.LowSpaceSubsetSum.Word.WordRunLaw +import OAI.Combinatorics.LowSpaceSubsetSum.Separators.SeparatorStoredSpace + +namespace OAI + +/-! # The complete word draw buffer fits below the branch workspace -/ + +noncomputable section +namespace LowSpaceSubsetSum.WordSamplingBounds + +variable {n : ℕ} + +theorem family_width (n : ℕ) : 2*RepresentationSetup.blockHalf n 0 ≤ n := by + unfold RepresentationSetup.blockHalf + simp only [Matrix.cons_val_zero] + omega + +theorem family_codes (n : ℕ) : + 2^(2*RepresentationSetup.blockHalf n 0) ≤ compressionDictionaryCapacity n := by + apply (Nat.pow_le_pow_right (by decide) + (show 2*RepresentationSetup.blockHalf n 0 ≤ 2*(2*RepresentationSetup.blockHalf n 0) by omega)).trans + exact RepresentationSetup.separator_table_rate_le_capacity + +theorem history_normalize (n : ℕ) : WordRealization.historyReads n = + 4*n^4+10*n^3+n+44*2^(2*RepresentationSetup.blockHalf n 0)* + (2*RepresentationSetup.blockHalf n 0)*n^3 := by + unfold WordRealization.historyReads + ring + +theorem history_reads (I : Instance n) (hn : 10000 ≤ n) : + WordRealization.historyReads n ≤ inputScale I^5*(compressionDictionaryCapacity n+1) := by + let u := inputScale I + let C := compressionDictionaryCapacity n + have hu : 10000 ≤ u := by unfold u inputScale; omega + have hnu : n ≤ u := by unfold u inputScale; omega + have hn1 : 1 ≤ u := by omega + have h34 : n^3 ≤ u^4 := + (Nat.pow_le_pow_left hnu 3).trans (Nat.pow_le_pow_right hn1 (by decide : 3 ≤ 4)) + have hn4 : n ≤ u^4 := by + exact hnu.trans (by simpa only [pow_one] using + Nat.pow_le_pow_right hn1 (by decide : 1 ≤ 4)) + have hnfour : n^4 ≤ u^4 := Nat.pow_le_pow_left hnu 4 + have hf : 44*2^(2*RepresentationSetup.blockHalf n 0)* + (2*RepresentationSetup.blockHalf n 0)*n^3 ≤ 44*u^4*C := by + calc + _ ≤ 44*C*u*u^3 := by + gcongr + · exact family_codes n + · exact (family_width n).trans hnu + _ = _ := by ring + have hp : WordRealization.historyReads n ≤ 59*u^4*(C+1) := by + rw [history_normalize] + nlinarith only [h34,hn4,hnfour,hf] + apply hp.trans + calc + _ ≤ u*u^4*(C+1) := Nat.mul_le_mul_right _ (Nat.mul_le_mul_right _ (by omega)) + _ = _ := by rw [← pow_succ'] + +theorem word_width (I : Instance n) : 3*n+1 ≤ wordWidth I := by + unfold wordWidth inputScale + omega + +def representation (I : Instance n) (hn : 10000 ≤ n) : + WordRealization.Realization (wordWidth I) (WordRealization.historyReads n) + ((canonicalRepresentationData I).zeroSetup.bucketHistoryCoupling hn) := + WordRealization.bucketHistory _ hn _ (word_width I) + +theorem representation_probability (I : Instance n) (hn : 10000 ≤ n) + (P : Option ((canonicalRepresentationData I).zeroSetup.BucketTrialHistory (by omega)) → Prop) : + (FiniteLaw.uniform : FiniteLaw (Fin (WordRealization.historyReads n) → Fin (2^wordWidth I))).probability + (fun words => P (WordProgram.run (WordProgram.finiteStream words) + (representation I hn).program 0).1) = + ((canonicalRepresentationData I).zeroSetup.bucketHistoryCoupling hn).boundedLaw.probability P := by + rw [← WordProgram.run_probability _ _ (representation I hn).bounded] + exact (representation I hn).faithful P + +end LowSpaceSubsetSum.WordSamplingBounds + +end + +end OAI diff --git a/lean/OAI/Combinatorics/LowSpaceSubsetSum/Word/WordSeedAdditiveBudget.lean b/lean/OAI/Combinatorics/LowSpaceSubsetSum/Word/WordSeedAdditiveBudget.lean new file mode 100644 index 0000000000000000000000000000000000000000..ef1c94658859660c85ef781c1e54e2a603b81eee --- /dev/null +++ b/lean/OAI/Combinatorics/LowSpaceSubsetSum/Word/WordSeedAdditiveBudget.lean @@ -0,0 +1,55 @@ +import OAI.Combinatorics.LowSpaceSubsetSum.Word.WordSeedPreparedBind + +namespace OAI + +/-! # Adding the seven sequential generation stages without inflating exponents -/ + +noncomputable section +namespace LowSpaceSubsetSum.WordSeedMeasured + +open WordSeedRealization + +variable {w N M : ℕ} {α : Type} [Fintype α] + +/-- Each completed stage releases scratch space and retains its bounded seed. -/ +def Budgeted {S : SamplerCoupling α} {X : Realization w N S} + (E : Execution X) (B D k : ℕ) : Prop := + E.Bounded (k*(B+2)) (k*(D+8)) (k*(D+8)) + +theorem budgeted_one {S : SamplerCoupling α} {X : Realization w N S} + (E : Execution X) (B D : ℕ) (h : E.Bounded B D D) : Budgeted E B D 1 := by + intro stream cursor + have hh := h stream cursor + exact ⟨by simpa only [Nat.one_mul] using hh.1.trans (Nat.le_add_right B 2), + by simpa only [Nat.one_mul] using hh.2.1.trans (Nat.le_add_right D 8), + by simpa only [Nat.one_mul] using hh.2.2.trans (Nat.le_add_right D 8)⟩ + +theorem budgeted_bind {S : SamplerCoupling α} {X : Realization w N S} + (E : Execution X) (A : α → Type) [∀ a, Fintype (A a)] + (T : ∀ a, SamplerCoupling (A a)) (Y : ∀ a, Realization w M (T a)) + (F : ∀ a, Execution (Y a)) (B D k : ℕ) (hE : Budgeted E B D k) + (hF : ∀ a, (F a).Bounded B D D) : + Budgeted (bind E A T Y F) B D (k+1) := by + have h := bind_bounded E A T Y F _ _ _ _ _ _ hE hF + intro stream cursor + have hh := h stream cursor + refine ⟨hh.1.trans (by nlinarith),hh.2.1.trans ?_,hh.2.2.trans (by nlinarith)⟩ + exact max_le (by nlinarith) (by nlinarith) + +theorem budgeted_bindSeed {S : SamplerCoupling α} {X : Realization w N S} + (E : Execution X) (A : α → Type) [∀ a, Fintype (A a)] + (T : ∀ a, SamplerCoupling (A a)) (Y : ∀ a, Realization w M (T a)) + (F : ∀ a : Accepted S, Execution (Y a.value)) (B D k : ℕ) (hE : Budgeted E B D k) + (hF : ∀ a, (F a).Bounded B D D) : + Budgeted (bindSeed E A T Y F) B D (k+1) := by + have h := bindSeed_bounded E A T Y F _ _ _ _ _ _ hE hF + intro stream cursor + have hh := h stream cursor + refine ⟨hh.1.trans (by nlinarith),hh.2.1.trans ?_,hh.2.2.trans (by nlinarith)⟩ + exact max_le (by nlinarith) (by nlinarith) + +end LowSpaceSubsetSum.WordSeedMeasured + +end + +end OAI diff --git a/lean/OAI/Combinatorics/LowSpaceSubsetSum/Word/WordSeedBitsExecution.lean b/lean/OAI/Combinatorics/LowSpaceSubsetSum/Word/WordSeedBitsExecution.lean new file mode 100644 index 0000000000000000000000000000000000000000..c566d952fe76db5c777146b7611fb9ec83e94336 --- /dev/null +++ b/lean/OAI/Combinatorics/LowSpaceSubsetSum/Word/WordSeedBitsExecution.lean @@ -0,0 +1,71 @@ +import OAI.Combinatorics.LowSpaceSubsetSum.Word.WordSeedMeasured +import OAI.Combinatorics.LowSpaceSubsetSum.Word.WordSeedDraws +import OAI.Combinatorics.LowSpaceSubsetSum.Storage.SignMaskExecution + +namespace OAI + +/-! # Stored fair sign bits and the explicitly scanned sign mask -/ + +noncomputable section +namespace LowSpaceSubsetSum.WordSeedMeasured + +def bitsRun (w n : ℕ) (stream : ℕ → Fin (2^w)) (cursor : ℕ) : + Result (bitArrayCoupling n) := + let buffer := WordCandidateExecution.run (k := 1) stream 2 (by norm_num) n cursor + let f : Fin n → Bool := fun i => finTwoEquiv (buffer.data[i.val]) + ⟨some ⟨WordSeedRealization.bitsSeed n f,f,rfl⟩,buffer.cursor, + buffer.work+2,buffer.cells+8,n+8⟩ + +def bits (w n : ℕ) (hw : 1 ≤ w) : Execution (WordSeedRealization.bits w n hw) where + run := bitsRun w n + value stream cursor := by + simp only [WordSeedRealization.bits,WordSeedRejectionExecution.program_run_map, + WordSeedRejectionExecution.tuple_run,bitsRun,WordCandidateExecution.run_data, + WordCandidateExecution.run_cursor,Vector.getElem_ofFn,Option.map_some] + +theorem bits_bounded (w n : ℕ) (hw : 1 ≤ w) : + (bits w n hw).Bounded (5*n+3) (2*n+20) (n+8) := by + intro stream cursor + have hc := WordCandidateExecution.run_cells stream 2 (by norm_num : 2=2^1) n cursor + have hw := WordCandidateExecution.run_work stream 2 (by norm_num : 2=2^1) n cursor + change _+2 ≤ _ ∧ _+8 ≤ _ ∧ n+8 ≤ n+8 + exact ⟨by omega,by omega,le_rfl⟩ + +def signsCompute (n : ℕ) (f : Fin n → Bool) : (Finset (Fin n) × ℕ) × ℕ := + let out := SignMaskExecution.run n f + let value : Finset (Fin n) := + ⟨(out.1.indices : Multiset (Fin n)),by + change ((List.finRange n).filter f).Nodup + exact (List.nodup_finRange n).filter _⟩ + ((value,out.2+1),SignMaskExecution.cells n f+4) + +theorem signsCompute_value (n : ℕ) (f : Fin n → Bool) : + (signsCompute n f).1.1 = bitsSubsetEquiv n f := by + ext i + simp [signsCompute,SignMaskExecution.run,bitsSubsetEquiv] + +def signs (w n : ℕ) (hw : 1 ≤ w) : Execution (WordSeedRealization.signs w n hw) := + map (bits w n hw) (bitsSubsetEquiv n) (signsCompute n) (signsCompute_value n) + +theorem signs_bounded (w n : ℕ) (hw : 1 ≤ w) : + (signs w n hw).Bounded (9*n+8) (3*n+26) (3*n+24) := by + unfold signs + have hc (f : Fin n → Bool) : (signsCompute n f).2 ≤ 2*n+8 := by + have h := SignMaskExecution.cells_le n f + change SignMaskExecution.cells n f+4 ≤ _ + omega + have hwork (f : Fin n → Bool) : (signsCompute n f).1.2 ≤ 4*n+3 := by + simp only [signsCompute,SignMaskExecution.work] + omega + have h := map_bounded (bits w n hw) (bitsSubsetEquiv n) (signsCompute n) + (signsCompute_value n) (5*n+3) (2*n+20) (n+8) (4*n+3) (2*n+8) + (bits_bounded w n hw) hwork hc + intro stream cursor + have hh := h stream cursor + exact ⟨by omega,hh.2.1.trans (by omega),by omega⟩ + +end LowSpaceSubsetSum.WordSeedMeasured + +end + +end OAI diff --git a/lean/OAI/Combinatorics/LowSpaceSubsetSum/Word/WordSeedBucketExecution.lean b/lean/OAI/Combinatorics/LowSpaceSubsetSum/Word/WordSeedBucketExecution.lean new file mode 100644 index 0000000000000000000000000000000000000000..156515cb204587402c2f10687d71adad5ba07ee5 --- /dev/null +++ b/lean/OAI/Combinatorics/LowSpaceSubsetSum/Word/WordSeedBucketExecution.lean @@ -0,0 +1,42 @@ +import OAI.Combinatorics.LowSpaceSubsetSum.Word.WordSeedHistoryExecution +import OAI.Combinatorics.LowSpaceSubsetSum.Word.WordSeedSeparatorPreparation +import OAI.Combinatorics.LowSpaceSubsetSum.Word.WordSamplingBounds + +namespace OAI + +/-! # Executed separator families complete the representation history -/ + +noncomputable section +namespace LowSpaceSubsetSum.WordSeedMeasured + +variable {n : ℕ} + +private theorem clog_le (k w : ℕ) (h : k ≤ w) : Nat.clog 2 k ≤ w := + (Nat.clog_le_of_le_pow Nat.lt_two_pow_self.le).trans h + +def separatorDraws (R : RepresentationSetup n) (h : R.PrimeHistory) + (hn : 2200 ≤ n) (w : ℕ) + (hw : Nat.clog 2 (2*RepresentationSetup.blockHalf n 0) ≤ w) : + Execution (WordSeedRealization.separatorDraws R h hn w hw) := by + unfold WordSeedRealization.separatorDraws RepresentationSetup.separatorParameters + exact familiesPrepared _ _ _ _ _ _ w n hw + +def bucketHistory (I : Instance n) (hn : 10000 ≤ n) (w : ℕ) (hw : 3*n+1 ≤ w) : + Execution (WordSeedRealization.bucketHistory (canonicalRepresentationData I).zeroSetup hn w hw) := + bind (extraHistory I (by omega) w hw) + (fun h => (canonicalRepresentationData I).zeroSetup.SeparatorDraws h.1.1 (by omega)) + (fun h => (canonicalRepresentationData I).zeroSetup.separatorCoupling h.1.1 (by omega)) + (fun h => WordSeedRealization.separatorDraws _ h.1.1 (by omega) w + (clog_le _ _ (by + have hg := WordSamplingBounds.family_width n + omega))) + (fun h => separatorDraws _ h.1.1 (by omega) w + (clog_le _ _ (by + have hg := WordSamplingBounds.family_width n + omega))) + +end LowSpaceSubsetSum.WordSeedMeasured + +end + +end OAI diff --git a/lean/OAI/Combinatorics/LowSpaceSubsetSum/Word/WordSeedCompressionExecution.lean b/lean/OAI/Combinatorics/LowSpaceSubsetSum/Word/WordSeedCompressionExecution.lean new file mode 100644 index 0000000000000000000000000000000000000000..0d07c30b6cc19e1f5c8bacf863382594b1ecf945 --- /dev/null +++ b/lean/OAI/Combinatorics/LowSpaceSubsetSum/Word/WordSeedCompressionExecution.lean @@ -0,0 +1,77 @@ +import OAI.Combinatorics.LowSpaceSubsetSum.Word.WordSeedPermutationExecution +import OAI.Combinatorics.LowSpaceSubsetSum.Word.WordSeedPrimeInitialization + +namespace OAI + +/-! # Actual word-driven compression sampler + +The permutation generator retains its range candidate buffers. The prime +width is computed by one multiplication and one division before its +modulus and bounded rejection routine. Exhaustion remains `none`. +-/ + +noncomputable section +namespace LowSpaceSubsetSum.WordSeedMeasured + +private def compressionCore {n : ℕ} (D : CompressionData n) (hn : 168000000 ≤ n) + (w : ℕ) (hp : Nat.clog 2 n ≤ w) (hq : compressionPrimeExponent n ≤ w) : + Execution (WordSeedRealization.compression D hn w hp hq) := + let ell := 249*n/1000 + bind (permutation w n n hp) (fun _ => CompressionSetup.PrimeSpace n) + (fun _ => primeCoupling (by unfold compressionPrimeExponent; omega) n) + (fun _ => WordSeedRealization.prime w n ell (by omega) hq) + (fun _ => primeInitialized w n ell (by omega) hq) + +def compression {n : ℕ} (D : CompressionData n) (hn : 168000000 ≤ n) + (w : ℕ) (hp : Nat.clog 2 n ≤ w) (hq : compressionPrimeExponent n ≤ w) : + Execution (WordSeedRealization.compression D hn w hp hq) where + run stream cursor := + let out := (compressionCore D hn w hp hq).run stream cursor + ⟨out.accepted,out.cursor,out.work+6,max 8 (out.cells+8),out.retained+1⟩ + value stream cursor := (compressionCore D hn w hp hq).value stream cursor + +def compressionWork (n : ℕ) : ℕ := + n*(13*n^3+5*n+64)+ + (n^3*(12*2^((compressionPrimeExponent n+1)/2)+ + 12*(compressionPrimeExponent n+1)+11)+3*compressionPrimeExponent n+17)+9 + +theorem compression_bounded {n : ℕ} (D : CompressionData n) (hn : 168000000 ≤ n) + (w : ℕ) (hp : Nat.clog 2 n ≤ w) (hq : compressionPrimeExponent n ≤ w) : + (compression D hn w hp hq).Bounded (compressionWork n) + ((n+3)*(2*n^3+256)) ((n+2)*(n^3+64)) := by + have hh := bind_bounded (permutation w n n hp) + (fun _ => CompressionSetup.PrimeSpace n) + (fun _ => primeCoupling (by unfold compressionPrimeExponent; omega) n) + (fun _ => WordSeedRealization.prime w n (compressionPrimeExponent n) + (by unfold compressionPrimeExponent; omega) hq) + (fun _ => primeInitialized w n (compressionPrimeExponent n) + (by unfold compressionPrimeExponent; omega) hq) + _ _ _ _ _ _ (permutation_bounded w n n hp) + (fun _ => primeInitialized_bounded w n (compressionPrimeExponent n) + (by unfold compressionPrimeExponent; omega) hq) + intro stream cursor + have h := hh stream cursor + dsimp only [compression,compressionCore] + change _+6 ≤ compressionWork n ∧ max 8 (_+8) ≤ (n+3)*(2*n^3+256) ∧ + _+1 ≤ (n+2)*(n^3+64) + refine ⟨?_,?_,?_⟩ + · have hwork := Nat.add_le_add_right h.1 6 + apply hwork.trans + unfold compressionWork + omega + · apply max_le + · nlinarith + · have hc := Nat.add_le_add_right h.2.1 8 + apply hc.trans + have hA : (n+1)*(2*n^3+256)+8 ≤ (n+3)*(2*n^3+256) := by nlinarith + have hB : ((n+1)*(n^3+64)+(2*n^3+124)+8)+8 ≤ + (n+3)*(2*n^3+256) := by nlinarith + omega + · have hr := Nat.add_le_add_right h.2.2 1 + exact hr.trans (by nlinarith) + +end LowSpaceSubsetSum.WordSeedMeasured + +end + +end OAI diff --git a/lean/OAI/Combinatorics/LowSpaceSubsetSum/Word/WordSeedConstructors.lean b/lean/OAI/Combinatorics/LowSpaceSubsetSum/Word/WordSeedConstructors.lean new file mode 100644 index 0000000000000000000000000000000000000000..dac8650ac668a2b860910b6653383b7007f9925e --- /dev/null +++ b/lean/OAI/Combinatorics/LowSpaceSubsetSum/Word/WordSeedConstructors.lean @@ -0,0 +1,89 @@ +import OAI.Combinatorics.LowSpaceSubsetSum.Word.WordSeedRealization +import OAI.Combinatorics.LowSpaceSubsetSum.Word.WordRangeRealization + +namespace OAI + +/-! # Successful seed constructors for products and bounded rejection + +The rejection constructor draws and retains the full candidate tuple. +Its backup coordinate is the accepted value, so no backup word is read. +-/ + +noncomputable section +namespace LowSpaceSubsetSum.WordSeedRealization + +open WordProgram +attribute [local instance] Classical.propDecidable + +def enlarge {w N M : ℕ} {α : Type} [Fintype α] {S : SamplerCoupling α} + (X : Realization w N S) (h : N ≤ M) : Realization w M S where + program := X.program + faithful := X.faithful + bounded := by + have hb := WordProgram.bound_add X.program N X.bounded (M-N) + simpa only [Nat.sub_add_cancel h] using hb + +def prod {w N M : ℕ} {α β : Type} [Fintype α] [Fintype β] + {S : SamplerCoupling α} {T : SamplerCoupling β} + (X : Realization w N S) (Y : Realization w M T) : Realization w (N+M) (S.prod T) := + map (bind X (fun _ => β) (fun _ => T) (fun _ => Y)) (Equiv.sigmaEquivProd α β) + +def pi (w N : ℕ) : (k : ℕ) → (A : Fin k → Type) → [∀ i, Fintype (A i)] → + (S : ∀ i, SamplerCoupling (A i)) → (∀ i, Realization w N (S i)) → + Realization w (k*N) (SamplerCoupling.pi k A S) + | 0, A, _, _, _ => by + simpa only [Nat.zero_mul,SamplerCoupling.pi] using + (pure (w := w) (fun i : Fin 0 => (Fin.elim0 i : A i))) + | k+1, A, _, S, X => by + have h := map (prod (X 0) + (pi w N k (fun i => A i.succ) (fun i => S i.succ) (fun i => X i.succ))) + (Fin.consEquiv A) + simpa only [SamplerCoupling.pi,Nat.add_mul,Nat.one_mul,Nat.add_comm] using h + +variable {Ω : Type} [Fintype Ω] [Nonempty Ω] + +def rejectionSeed (A : Ω → Prop) [DecidablePred A] [Nonempty {a : Ω // A a}] + (N : ℕ) (f : Fin N → Ω) : Option (SuccessfulSeed (firstAcceptCoupling A N)) := + match h : firstAcceptSubtype A N f with + | none => none + | some a => some ⟨(f,a),a,h⟩ + +theorem rejectionSeed_observe (A : Ω → Prop) [DecidablePred A] + [Nonempty {a : Ω // A a}] (N : ℕ) (f : Fin N → Ω) : + observe (firstAcceptCoupling A N) (rejectionSeed A N f) = firstAcceptSubtype A N f := by + unfold rejectionSeed + split + next h => exact h.symm + next => rfl + +theorem rejectionSeed_candidates (A : Ω → Prop) [DecidablePred A] + [Nonempty {a : Ω // A a}] (N : ℕ) (f : Fin N → Ω) + (s : SuccessfulSeed (firstAcceptCoupling A N)) (h : rejectionSeed A N f = some s) : + s.val.1 = f := by + unfold rejectionSeed at h + split at h + · contradiction + · cases h + rfl + +def rejection (w k : ℕ) (hk : k ≤ w) (N : ℕ) + (A : Fin (2^k) → Prop) [DecidablePred A] [Nonempty {a : Fin (2^k) // A a}] : + Realization w N (firstAcceptCoupling A N) where + program := WordProgram.map + (fun f => rejectionSeed A N (fun i => ExactWordDraw.low w k (f i))) (WordTuple.sample N) + faithful P := by + rw [WordProgram.probability_map,WordProgram.probability_map] + simp only [rejectionSeed_observe] + rw [WordTuple.probability,SamplerCoupling.boundedLaw,FiniteLaw.map_probability] + exact (ExactWordDraw.firstAccept_words w k hk A N P).symm + bounded := by + simpa only [WordProgram.map,Nat.add_zero] using + WordProgram.bind_bound (WordTuple.sample (w := w) N) N (WordTuple.bounded N) + (fun f => .pure (rejectionSeed A N (fun i => ExactWordDraw.low w k (f i)))) 0 + (fun _ => Bounded.pure _ 0) + +end LowSpaceSubsetSum.WordSeedRealization + +end + +end OAI diff --git a/lean/OAI/Combinatorics/LowSpaceSubsetSum/Word/WordSeedDraws.lean b/lean/OAI/Combinatorics/LowSpaceSubsetSum/Word/WordSeedDraws.lean new file mode 100644 index 0000000000000000000000000000000000000000..5a4c1b8d57e99c35ff3d117b68364b53f1725951 --- /dev/null +++ b/lean/OAI/Combinatorics/LowSpaceSubsetSum/Word/WordSeedDraws.lean @@ -0,0 +1,77 @@ +import OAI.Combinatorics.LowSpaceSubsetSum.Word.WordSeedPrimitives +import OAI.Combinatorics.LowSpaceSubsetSum.Word.WordRepresentationDraws + +namespace OAI + +/-! # Successful seeds for signs, partitions and separator families -/ + +noncomputable section +namespace LowSpaceSubsetSum.WordSeedRealization + +def bitsSeed (n : ℕ) (f : Fin n → Bool) : SuccessfulSeed (bitArrayCoupling n) := + ⟨f,f,rfl⟩ + +def bits (w n : ℕ) (hw : 1 ≤ w) : Realization w n (bitArrayCoupling n) where + program := WordProgram.map + (fun f => some (bitsSeed n (fun i => finTwoEquiv (ExactWordDraw.low w 1 (f i))))) + (WordTuple.sample n) + faithful P := by + have he : WordProgram.map (observe (bitArrayCoupling n)) + (WordProgram.map + (fun f => some (bitsSeed n (fun i => finTwoEquiv (ExactWordDraw.low w 1 (f i))))) + (WordTuple.sample n)) = (WordRealization.bits w n hw).program := by + rw [map_map] + rfl + rw [he] + exact (WordRealization.bits w n hw).faithful P + bounded := by + simpa only [WordProgram.map,Nat.add_zero] using + WordProgram.bind_bound (WordTuple.sample (w := w) n) n (WordTuple.bounded n) + (fun f => .pure (some (bitsSeed n + (fun i => finTwoEquiv (ExactWordDraw.low w 1 (f i)))))) 0 + (fun _ => WordProgram.Bounded.pure _ 0) + +def signs (w n : ℕ) (hw : 1 ≤ w) : Realization w n (signCoupling n) := + map (bits w n hw) (bitsSubsetEquiv n) + +def subset (w n g : ℕ) (K : Finset (Fin g)) (hw : Nat.clog 2 g ≤ w) : + Realization w (g*n^3) (subsetCoupling n g K) := + map (permutation w n g hw) (permutationBlock K) + +def fixedSize (w n g e : ℕ) (he : e ≤ g) (hw : Nat.clog 2 g ≤ w) : + Realization w (g*n^3) (fixedSizeCoupling n g e he) := + map (subset w n g (initialSubset g e he) hw) (initialSubsetEquiv g e he) + +def families {g : ℕ} (S : SeparatorExpectation.RoundedParameters g) + (w n : ℕ) (hw : Nat.clog 2 g ≤ w) : + Realization w (4*(11*2^g*(g*n^3))) (S.samplerCoupling n) := + pi w (11*2^g*(g*n^3)) 4 _ _ (fun i => + enlarge (pi w (g*n^3) (S.counts i) _ _ + (fun _ => fixedSize w n g (S.e i) (S.size_le i) hw)) + (Nat.mul_le_mul_right _ (S.counts_le i))) + +def layout {n : ℕ} (R : RepresentationSetup n) (w : ℕ) + (hp : Nat.clog 2 n ≤ w) (hb : 1 ≤ w) : + Realization w (n*n^3+n) R.layoutCoupling := + prod (permutation w n n hp) (signs w n hb) + +def guesses {n : ℕ} (R : RepresentationSetup n) (w : ℕ) + (hw : Nat.clog 2 (CanonicalGuesses.width n) ≤ w) : + Realization w (3*n^3) R.guessesCoupling := + pi w (n^3) 3 _ _ (fun _ => map (fin w n (CanonicalGuesses.width n) hw) + (CanonicalGuesses.encoding n)) + +def partition {n : ℕ} (R : RepresentationSetup n) (z : RepresentationSetup.Layout n) + (i : Fin 3) (w : ℕ) + (hw : Nat.clog 2 (RepresentationSetup.blockCount i * + (2*RepresentationSetup.blockHalf n i)) ≤ w) : + Realization w ((RepresentationSetup.blockCount i * + (2*RepresentationSetup.blockHalf n i))*n^3) (CanonicalPartition.coupling R z i) := + map (map (permutation w n _ hw) (Equiv.permCongr (CanonicalPartition.ranks R z i).symm)) + (coloringOfPermutation (CanonicalPartition.base R z i)) + +end LowSpaceSubsetSum.WordSeedRealization + +end + +end OAI diff --git a/lean/OAI/Combinatorics/LowSpaceSubsetSum/Word/WordSeedExecution.lean b/lean/OAI/Combinatorics/LowSpaceSubsetSum/Word/WordSeedExecution.lean new file mode 100644 index 0000000000000000000000000000000000000000..6fd79e320efcbff37a1ad5677164d1a1da3b14bd --- /dev/null +++ b/lean/OAI/Combinatorics/LowSpaceSubsetSum/Word/WordSeedExecution.lean @@ -0,0 +1,78 @@ +import OAI.Combinatorics.LowSpaceSubsetSum.Word.WordSeedRealization +import OAI.Combinatorics.LowSpaceSubsetSum.Word.WordRunLaw + +namespace OAI + +/-! # Running the prepared action on actual word-generated seeds -/ + +noncomputable section +namespace LowSpaceSubsetSum.WordSeedRealization + +variable {w N : ℕ} {α β : Type} [Fintype α] {S : SamplerCoupling α} + +def run (X : Realization w N S) (words : Fin N → Fin (2^w)) := + WordProgram.run (WordProgram.finiteStream words) X.program 0 + +theorem run_reads (X : Realization w N S) (words : Fin N → Fin (2^w)) : + (run X words).2 ≤ N := by + simpa only [run,Nat.zero_add] using + (WordProgram.run_bound X.program N X.bounded (WordProgram.finiteStream words) 0).2 + +theorem run_probability (X : Realization w N S) (P : Option α → Prop) : + (FiniteLaw.uniform : FiniteLaw (Fin N → Fin (2^w))).probability + (fun words => P (observe S (run X words).1)) = S.boundedLaw.probability P := by + unfold run + exact (WordProgram.run_probability X.program N X.bounded + (fun s => P (observe S s))).symm.trans + ((WordProgram.probability_map (observe S) X.program P).symm.trans (X.faithful P)) + +def execute (X : Realization w N S) (action : S.Seed → β) (failure : β) + (words : Fin N → Fin (2^w)) : β := + match (run X words).1 with + | none => failure + | some s => action s.val + +/-- The action's value (which may itself contain its work counter) and +the separate number of fair words read. This does not charge continuations +as free machine operations. -/ +def executeCounted (X : Realization w N S) (action : S.Seed → β) (failure : β) + (words : Fin N → Fin (2^w)) : β × ℕ := + let out := run X words + (match out.1 with | none => failure | some s => action s.val,out.2) + +theorem executeCounted_value (X : Realization w N S) (action : S.Seed → β) (failure : β) + (words : Fin N → Fin (2^w)) : + (executeCounted X action failure words).1 = execute X action failure words := rfl + +theorem executeCounted_reads (X : Realization w N S) (action : S.Seed → β) (failure : β) + (words : Fin N → Fin (2^w)) : (executeCounted X action failure words).2 ≤ N := + run_reads X words + +theorem execute_success (X : Realization w N S) (action : S.Seed → β) (failure : β) + (words : Fin N → Fin (2^w)) (s : SuccessfulSeed S) + (h : (run X words).1 = some s) : execute X action failure words = action s.val := by + simp only [execute,h] + +theorem probability_success (X : Realization w N S) (test : S.Seed → Bool) + (P : α → Prop) + (h : ∀ s a, S.bounded s = some a → P a → test s = true) : + S.boundedLaw.probability (fun a => ∃ x, a = some x ∧ P x) ≤ + (FiniteLaw.uniform : FiniteLaw (Fin N → Fin (2^w))).probability + (fun words => execute X test false words = true) := by + rw [←run_probability X (fun a => ∃ x, a = some x ∧ P x)] + apply FiniteLaw.probability_mono + intro words hw + cases hs : (run X words).1 with + | none => + simp only [hs,observe,Option.bind_none,reduceCtorEq,false_and,exists_false] at hw + | some s => + obtain ⟨a,ha,hpa⟩ := hw + have hb : S.bounded s.val = some a := by + simpa only [hs,observe,Option.bind_some] using ha + exact (execute_success X test false words s hs).trans (h s.val a hb hpa) + +end LowSpaceSubsetSum.WordSeedRealization + +end + +end OAI diff --git a/lean/OAI/Combinatorics/LowSpaceSubsetSum/Word/WordSeedFactorExecution.lean b/lean/OAI/Combinatorics/LowSpaceSubsetSum/Word/WordSeedFactorExecution.lean new file mode 100644 index 0000000000000000000000000000000000000000..03cf9748daa5a0a416e39c0c02363215d99ee12f --- /dev/null +++ b/lean/OAI/Combinatorics/LowSpaceSubsetSum/Word/WordSeedFactorExecution.lean @@ -0,0 +1,89 @@ +import OAI.Combinatorics.LowSpaceSubsetSum.Word.WordSeedPrimeInitialization +import OAI.Combinatorics.LowSpaceSubsetSum.Word.WordSeedMeasuredTransport + +namespace OAI + +/-! # Initialized nested-prime seed execution + +Widths below four use the constant unit factor. Every larger factor executes +its modulus construction, actual bounded prime test, and retained candidate +buffer. Tuple assembly has an explicit fixed charge. +-/ + +noncomputable section +namespace LowSpaceSubsetSum.WordSeedMeasured + +open WordSeedRealization + +def factorWork (n ell : ℕ) : ℕ := + n^3*(12*2^((ell+1)/2)+12*(ell+1)+11)+3*ell+21 + +def factor (w n ell : ℕ) (hw : ell ≤ w) : + Execution (WordSeedRealization.factor w n ell hw) := + if h : ell < 4 then + transportSampler (by simp only [factorCoupling,dite_eq_left h]) + (source_factor_small w n ell hw h) + (enlarge (map (pure (w := w) ()) (factorOneEquiv h) + (fun a => (((factorOneEquiv h) a,2),2)) (fun _ => rfl)) (Nat.zero_le (n^3))) + else + transportSampler (by simp only [factorCoupling,dite_eq_right h]) + (source_factor_large w n ell hw h) + (map (primeInitialized w n ell (by omega) hw) (factorPrimeEquiv (by omega)) + (fun a => (((factorPrimeEquiv (by omega)) a,2),2)) (fun _ => rfl)) + +theorem factor_bounded (w n ell : ℕ) (hw : ell ≤ w) : + (factor w n ell hw).Bounded (factorWork n ell) (2*n^3+124) (n^3+28) := by + unfold factor + split + next h => + have hm := map_bounded (pure (w := w) ()) (factorOneEquiv h) + (fun a => (((factorOneEquiv h) a,2),2)) (fun _ => rfl) + 1 4 4 2 2 (pure_bounded ()) (fun _ => le_rfl) (fun _ => le_rfl) + apply bounded_mono _ (transportSampler_bounded _ _ _ _ _ _ + (enlarge_bounded _ _ _ _ _ hm)) + · unfold factorWork; omega + · omega + · omega + next h => + have hp := primeInitialized_bounded w n ell (by omega) hw + have hm := map_bounded (primeInitialized w n ell (by omega) hw) + (factorPrimeEquiv (by omega)) + (fun a => (((factorPrimeEquiv (by omega)) a,2),2)) (fun _ => rfl) + _ _ _ 2 2 hp (fun _ => le_rfl) (fun _ => le_rfl) + apply bounded_mono _ (transportSampler_bounded _ _ _ _ _ _ hm) + · unfold factorWork; omega + · omega + · omega + +def triplePrime (w n a b c : ℕ) (ha : a ≤ w) (hb : b ≤ w) (hc : c ≤ w) : + Execution (WordSeedRealization.triplePrime w n a b c ha hb hc) := + reprogram + (map (prod (prod (factor w n a ha) (factor w n b hb)) (factor w n c hc)) + (tripleFactorEquiv a b c) + (fun p => (((tripleFactorEquiv a b c) p,8),8)) (fun _ => rfl)) (by + conv_lhs => rw [WordSeedRealization.triplePrime] + exact mpr_program (w := w) (α := ↥(tripleRange a b c)) + (by omega : 3*n^3 = (n^3+n^3)+n^3) _) + +theorem triplePrime_bounded (w n a b c : ℕ) (ha : a ≤ w) (hb : b ≤ w) (hc : c ≤ w) : + (triplePrime w n a b c ha hb hc).Bounded + (factorWork n a+factorWork n b+factorWork n c+20) + (4*n^3+256) (3*n^3+136) := by + have hp := prod_bounded (factor w n a ha) (factor w n b hb) _ _ _ _ _ _ + (factor_bounded w n a ha) (factor_bounded w n b hb) + have hq := prod_bounded _ (factor w n c hc) _ _ _ _ _ _ hp + (factor_bounded w n c hc) + have hm := map_bounded _ (tripleFactorEquiv a b c) + (fun p => (((tripleFactorEquiv a b c) p,8),8)) (fun _ => rfl) + _ _ _ 8 8 hq (fun _ => le_rfl) (fun _ => le_rfl) + intro stream cursor + have ht := hm stream cursor + change _ ≤ factorWork n a+factorWork n b+factorWork n c+20 ∧ + _ ≤ 4*n^3+256 ∧ _ ≤ 3*n^3+136 + exact ⟨ht.1.trans (by omega),ht.2.1.trans (by omega),ht.2.2.trans (by omega)⟩ + +end LowSpaceSubsetSum.WordSeedMeasured + +end + +end OAI diff --git a/lean/OAI/Combinatorics/LowSpaceSubsetSum/Word/WordSeedFamilyBounds.lean b/lean/OAI/Combinatorics/LowSpaceSubsetSum/Word/WordSeedFamilyBounds.lean new file mode 100644 index 0000000000000000000000000000000000000000..1e6fecb30c033be5c329aaa0bcdfb63acf518d98 --- /dev/null +++ b/lean/OAI/Combinatorics/LowSpaceSubsetSum/Word/WordSeedFamilyBounds.lean @@ -0,0 +1,124 @@ +import OAI.Combinatorics.LowSpaceSubsetSum.Word.WordSeedSeparatorPreparation +import OAI.Combinatorics.LowSpaceSubsetSum.Word.WordSeedScalarBounds +import OAI.Combinatorics.LowSpaceSubsetSum.Separators.SeparatorStoredSpace + +namespace OAI + +/-! # Family generation stays inside the application budgets + +The family count is exponential only in one top block. Range tests and +permutation materialization keep polynomial work per sampled mask. +-/ + +namespace LowSpaceSubsetSum.WordSeedFamilyBounds + +open WordSeedMeasured + +variable {n : ℕ} + +private theorem self_le_power {u k : ℕ} (hu : 1 ≤ u) (hk : 1 ≤ k) : u ≤ u^k := by + simpa only [Nat.pow_one] using Nat.pow_le_pow_right hu hk + +private theorem coefficient_power {u c k : ℕ} (hc : c ≤ u) : c*u^k ≤ u^(k+1) := by + simpa only [Nat.pow_succ,Nat.mul_comm] using Nat.mul_le_mul_right (u^k) hc + +theorem maskBudget_add_le (I : Instance n) (hn : 10000 ≤ n) {g : ℕ} (hg : g ≤ n) : + maskBudget n g+100 ≤ inputScale I^5 := by + let u := inputScale I + have hu : 10000 ≤ u := by dsimp only [u,inputScale]; omega + have hnu : n+1 ≤ u := by dsimp only [u,inputScale]; omega + have hgu : g+1 ≤ u := by omega + have hn3 : n^3 ≤ u^3 := Nat.pow_le_pow_left (by omega) 3 + have hu1 : u ≤ u^4 := self_le_power (by omega) (by decide) + have hu2 : u^2 ≤ u^4 := Nat.pow_le_pow_right (by omega) (by decide) + have hone : 1 ≤ u^4 := by omega + have ha : g*(14*n^3+5*g+68) ≤ 14*u^4+5*u^2+68*u := by + calc + _ ≤ u*(14*u^3+5*u+68) := Nat.mul_le_mul (by omega) (by omega) + _ = _ := by ring + have hb : 10*(g+1)^2 ≤ 10*u^2 := Nat.mul_le_mul_left _ (Nat.pow_le_pow_left hgu 2) + have hc : 10*(g+1)*(n^3+256) ≤ 10*u^4+2560*u := by + calc + _ ≤ (10*u)*(u^3+256) := Nat.mul_le_mul (by omega) (by omega) + _ = _ := by ring + have hpoly : maskBudget n g+100 ≤ 3000*u^4 := by + unfold maskBudget + nlinarith only [ha,hb,hc,hu1,hu2,hone] + exact hpoly.trans (coefficient_power (by omega : 3000 ≤ u)) + +theorem family_envelope (I : Instance n) (hn : 10000 ≤ n) {g : ℕ} (hg : g ≤ n) : + 100*(11*2^g+1)*(maskBudget n g+100) ≤ inputScale I^6*2^g := by + have hm := maskBudget_add_le I hn hg + have hp : 1 ≤ 2^g := Nat.one_le_two_pow + have hu : 10000 ≤ inputScale I := by unfold inputScale; omega + calc + _ ≤ (100*(12*2^g))*inputScale I^5 := Nat.mul_le_mul (by omega) hm + _ = (1200*inputScale I^5)*2^g := by ring + _ ≤ _ := Nat.mul_le_mul_right _ (coefficient_power (by omega : 1200 ≤ inputScale I)) + +theorem prepared_envelope (I : Instance n) (hn : 10000 ≤ n) {g : ℕ} (hg : g ≤ n) : + 60*g+55+100*(11*2^g+1)*(maskBudget n g+100) ≤ inputScale I^7*2^g ∧ + 264+100*(11*2^g+1)*(maskBudget n g+100) ≤ inputScale I^7*2^g := by + let u := inputScale I + let P := 2^g + have hu : 10000 ≤ u := by dsimp only [u,inputScale]; omega + have hgu : g ≤ u := by dsimp only [u,inputScale]; omega + have hP : 1 ≤ P := Nat.one_le_two_pow + have hbase := family_envelope I hn hg + change _ ≤ u^6*P at hbase + have hlow : 60*g+55 ≤ u^5 := by + have h : 115*u ≤ u^2 := by + simpa only [Nat.pow_one] using + (coefficient_power (u := u) (c := 115) (k := 1) (by omega)) + have hp : u^2 ≤ u^5 := Nat.pow_le_pow_right (by omega : 1 ≤ u) (by decide : 2 ≤ 5) + omega + have hsmall : 264 ≤ u^5 := (show 264 ≤ u by omega).trans + (self_le_power (by omega) (by decide)) + have h5 : u^5 ≤ u^6*P := by + calc + _ ≤ u^6 := Nat.pow_le_pow_right (by omega : 1 ≤ u) (by decide : 5 ≤ 6) + _ = u^6*1 := by omega + _ ≤ _ := Nat.mul_le_mul_left (u^6) hP + have hs : 2*u^6*P ≤ u^7*P := Nat.mul_le_mul_right P + (coefficient_power (u := u) (c := 2) (k := 6) (by omega)) + rw [Nat.mul_assoc] at hs + change _ ≤ u^7*P ∧ _ ≤ u^7*P + constructor <;> omega + +theorem familiesPrepared_bounded_scale (I : Instance n) (hn : 10000 ≤ n) + (g k : ℕ) (hg : g ≤ n) (hlarge : 64 ≤ g) (heven : 2 ∣ g) + (hk : k ≤ g) (hklo : 2*g ≤ 3*k) (w : ℕ) (hw : Nat.clog 2 g ≤ w) : + (familiesPrepared g k hlarge heven hk hklo w n hw).Bounded + (inputScale I^7*2^g) (inputScale I^7*2^g) (inputScale I^7*2^g) := by + have h := prepared_envelope I hn hg + exact WordSeedMeasured.bounded_mono _ + (familiesPrepared_bounded g k hlarge heven hk hklo w n hw) h.1 h.2 h.2 + +theorem familiesPrepared_application (I : Instance n) (hn : 10000 ≤ n) + (g k C : ℕ) (hg : g ≤ n) (hlarge : 64 ≤ g) (heven : 2 ∣ g) + (hk : k ≤ g) (hklo : 2*g ≤ 3*k) (w : ℕ) (hw : Nat.clog 2 g ≤ w) + (hcodes : 2^g ≤ C) (hhalf : g ≤ (n+1)/2) : + (familiesPrepared g k hlarge heven hk hklo w n hw).Bounded + (inputScale I^9*2^((n+1)/2)) (inputScale I^9*(C+1)) (inputScale I^9*(C+1)) := by + have hu : 1 ≤ inputScale I := by unfold inputScale; omega + have hp : inputScale I^7 ≤ inputScale I^9 := Nat.pow_le_pow_right hu (by decide) + apply WordSeedMeasured.bounded_mono _ (familiesPrepared_bounded_scale I hn g k hg + hlarge heven hk hklo w hw) + · exact Nat.mul_le_mul hp (Nat.pow_le_pow_right (by decide) hhalf) + · exact Nat.mul_le_mul hp (hcodes.trans (by omega)) + · exact Nat.mul_le_mul hp (hcodes.trans (by omega)) + +theorem canonical_family_half (n : ℕ) : + 2*RepresentationSetup.blockHalf n 0 ≤ (n+1)/2 := by + simp only [RepresentationSetup.blockHalf,Matrix.cons_val_zero] + omega + +theorem canonical_family_codes (n : ℕ) : + 2^(2*RepresentationSetup.blockHalf n 0) ≤ compressionDictionaryCapacity n := by + apply (Nat.pow_le_pow_right (by decide) + (show 2*RepresentationSetup.blockHalf n 0 ≤ 2*(2*RepresentationSetup.blockHalf n 0) by omega)).trans + exact RepresentationSetup.separator_table_rate_le_capacity + +end LowSpaceSubsetSum.WordSeedFamilyBounds + +end OAI diff --git a/lean/OAI/Combinatorics/LowSpaceSubsetSum/Word/WordSeedFamilyExecution.lean b/lean/OAI/Combinatorics/LowSpaceSubsetSum/Word/WordSeedFamilyExecution.lean new file mode 100644 index 0000000000000000000000000000000000000000..1818aab9da4cc5105a94a9de63590cb9bfac4806 --- /dev/null +++ b/lean/OAI/Combinatorics/LowSpaceSubsetSum/Word/WordSeedFamilyExecution.lean @@ -0,0 +1,102 @@ +import OAI.Combinatorics.LowSpaceSubsetSum.Word.WordSeedMaskExecution +import OAI.Combinatorics.LowSpaceSubsetSum.Separators.ComputedSeparatorFamilies + +namespace OAI + +/-! # Measured independent separator-family draws + +The inner loop bounds are supplied as explicit integer parameters. The +application wrapper obtains these integers from `SeparatorParameterExecution`. +-/ + +noncomputable section +namespace LowSpaceSubsetSum.WordSeedMeasured + +variable {g : ℕ} + +def families (S : SeparatorExpectation.RoundedParameters g) + (w n : ℕ) (hw : Nat.clog 2 g ≤ w) : + Execution (WordSeedRealization.families S w n hw) := + pi w (11*2^g*(g*n^3)) 4 _ _ _ (fun i => + enlarge (pi w (g*n^3) (S.counts i) _ _ _ + (fun _ => fixedSize w n g (S.e i) (S.size_le i) hw)) + (Nat.mul_le_mul_right _ (S.counts_le i))) + +def familyUsing (S : SeparatorExpectation.RoundedParameters g) (i : Fin 4) + (size count : ℕ) (hs : size = S.e i) (hc : count = S.counts i) + (w n : ℕ) (hw : Nat.clog 2 g ≤ w) : + Execution (WordSeedRealization.enlarge + (WordSeedRealization.pi w (g*n^3) (S.counts i) _ _ + (fun _ => WordSeedRealization.fixedSize w n g (S.e i) (S.size_le i) hw)) + (Nat.mul_le_mul_right _ (S.counts_le i))) := by + have hsize : size ≤ g := by rw [hs]; exact S.size_le i + have hcount : count ≤ 11*2^g := by rw [hc]; exact S.counts_le i + let actual := enlarge (pi w (g*n^3) count _ _ _ + (fun _ => fixedSize w n g size hsize hw)) (Nat.mul_le_mul_right _ hcount) + cases hs + cases hc + exact actual + +def familiesUsing (S : SeparatorExpectation.RoundedParameters g) + (sizes counts : Fin 4 → ℕ) (hs : ∀ i, sizes i = S.e i) + (hc : ∀ i, counts i = S.counts i) (w n : ℕ) (hw : Nat.clog 2 g ≤ w) : + Execution (WordSeedRealization.families S w n hw) := + pi w (11*2^g*(g*n^3)) 4 _ _ _ + (fun i => familyUsing S i (sizes i) (counts i) (hs i) (hc i) w n hw) + +def maskBudget (n g : ℕ) : ℕ := + (g*(14*n^3+5*g+68)+10*(g+1)^2+11)+10*(g+1)*(n^3+256)+100 + +theorem fixedSize_budget (w n g k : ℕ) (hk : k ≤ g) (hw : Nat.clog 2 g ≤ w) : + (fixedSize w n g k hk hw).Bounded (maskBudget n g) (maskBudget n g) (maskBudget n g) := by + intro stream cursor + have h := fixedSize_bounded w n g k hk hw stream cursor + unfold maskBudget + exact ⟨h.1.trans (by omega),h.2.1.trans (by omega),h.2.2.trans (by omega)⟩ + +theorem families_bounded (S : SeparatorExpectation.RoundedParameters g) + (w n : ℕ) (hw : Nat.clog 2 g ≤ w) : + (families S w n hw).Bounded + (100*(11*2^g+1)*(maskBudget n g+100)) + (100*(11*2^g+1)*(maskBudget n g+100)) + (100*(11*2^g+1)*(maskBudget n g+100)) := by + let F := 11*2^g + let B := maskBudget n g + have hi (i : Fin 4) : + (enlarge (pi w (g*n^3) (S.counts i) _ _ _ + (fun _ => fixedSize w n g (S.e i) (S.size_le i) hw)) + (Nat.mul_le_mul_right _ (S.counts_le i))).Bounded + ((F+1)*(2*B+100)) ((F+1)*(2*B+100)) ((F+1)*(2*B+100)) := by + have h := pi_bounded w (g*n^3) (S.counts i) _ _ _ _ B B B + (fun _ => fixedSize_budget w n g (S.e i) (S.size_le i) hw) + intro stream cursor + have ht := h stream cursor + have hc := S.counts_le i + change S.counts i ≤ F at hc + change _ ≤ _ ∧ _ ≤ _ ∧ _ ≤ _ + refine ⟨ht.1.trans ?_,ht.2.1.trans ?_,ht.2.2.trans ?_⟩ <;> nlinarith + have h := pi_bounded w (11*2^g*(g*n^3)) 4 _ _ _ _ + ((F+1)*(2*B+100)) ((F+1)*(2*B+100)) ((F+1)*(2*B+100)) hi + intro stream cursor + have ht := h stream cursor + change _ ≤ 100*(F+1)*(B+100) ∧ _ ≤ 100*(F+1)*(B+100) ∧ _ ≤ 100*(F+1)*(B+100) + refine ⟨ht.1.trans ?_,ht.2.1.trans ?_,ht.2.2.trans ?_⟩ <;> nlinarith + +theorem familiesUsing_bounded (S : SeparatorExpectation.RoundedParameters g) + (sizes counts : Fin 4 → ℕ) (hs : ∀ i, sizes i = S.e i) + (hc : ∀ i, counts i = S.counts i) (w n : ℕ) (hw : Nat.clog 2 g ≤ w) : + (familiesUsing S sizes counts hs hc w n hw).Bounded + (100*(11*2^g+1)*(maskBudget n g+100)) + (100*(11*2^g+1)*(maskBudget n g+100)) + (100*(11*2^g+1)*(maskBudget n g+100)) := by + have he : sizes = S.e := funext hs + have hm : counts = S.counts := funext hc + subst sizes + subst counts + simpa only [familiesUsing,familyUsing,families] using families_bounded S w n hw + +end LowSpaceSubsetSum.WordSeedMeasured + +end + +end OAI diff --git a/lean/OAI/Combinatorics/LowSpaceSubsetSum/Word/WordSeedFiniteBounds.lean b/lean/OAI/Combinatorics/LowSpaceSubsetSum/Word/WordSeedFiniteBounds.lean new file mode 100644 index 0000000000000000000000000000000000000000..2a00283efb76cabe88a5eaf22fd1ac931b752857 --- /dev/null +++ b/lean/OAI/Combinatorics/LowSpaceSubsetSum/Word/WordSeedFiniteBounds.lean @@ -0,0 +1,40 @@ +import OAI.Combinatorics.LowSpaceSubsetSum.Word.WordSeedScalarBounds + +namespace OAI + +/-! # Polynomial cost of a bounded finite-range draw -/ + +namespace LowSpaceSubsetSum.WordSeedScalarBounds + +open WordSeedMeasured + +variable {n : ℕ} + +theorem fin_bounded_scale (I : Instance n) (hn : 10000 ≤ n) (D : ℕ) [NeZero D] + (hD : Nat.clog 2 D ≤ 3*n) (w : ℕ) (hw : Nat.clog 2 D ≤ w) : + (fin w n D hw).Bounded (inputScale I^5) (inputScale I^5) (inputScale I^5) := by + let u := inputScale I + have hu : 10000 ≤ u := by dsimp only [u,inputScale]; omega + have hn3 : n^3 ≤ u^3 := Nat.pow_le_pow_left (by dsimp only [u,inputScale]; omega) 3 + have hnu : n ≤ u^3 := by + have h := Nat.pow_le_pow_right (by omega : 1 ≤ u) (by decide : 1 ≤ 3) + simp only [Nat.pow_one] at h + have hn' : n ≤ u := by dsimp only [u,inputScale]; omega + exact hn'.trans h + have hone : 1 ≤ u^3 := by omega + have hpoly : 45*u^3 ≤ u^5 := by + calc + _ ≤ u*u^3 := Nat.mul_le_mul_right _ (by omega) + _ = u^4 := by ring + _ ≤ _ := Nat.pow_le_pow_right (by omega) (by decide) + have hwork : 13*n^3+5*Nat.clog 2 D+17 ≤ u^5 := by + apply le_trans _ hpoly + omega + have hc := scalar_cells_le I hn + exact bounded_mono _ (fin_bounded w n D hw) hwork + ((show 2*n^3+104 ≤ 2*n^3+124 by omega).trans hc.1) + ((show n^3+18 ≤ n^3+28 by omega).trans hc.2) + +end LowSpaceSubsetSum.WordSeedScalarBounds + +end OAI diff --git a/lean/OAI/Combinatorics/LowSpaceSubsetSum/Word/WordSeedHistory.lean b/lean/OAI/Combinatorics/LowSpaceSubsetSum/Word/WordSeedHistory.lean new file mode 100644 index 0000000000000000000000000000000000000000..2fe78db706dae0b4f1c4ce3f70de77f893111834 --- /dev/null +++ b/lean/OAI/Combinatorics/LowSpaceSubsetSum/Word/WordSeedHistory.lean @@ -0,0 +1,102 @@ +import OAI.Combinatorics.LowSpaceSubsetSum.Word.WordSeedDraws +import OAI.Combinatorics.LowSpaceSubsetSum.Word.WordRepresentationHistory + +namespace OAI + +/-! # The whole dependent representation history retains successful seeds -/ + +noncomputable section +namespace LowSpaceSubsetSum.WordSeedRealization + +private theorem clog_le (k w : ℕ) (h : k ≤ w) : Nat.clog 2 k ≤ w := + (Nat.clog_le_of_le_pow (Nat.lt_two_pow_self.le)).trans h + +def partitions {n : ℕ} (R : RepresentationSetup n) (z : RepresentationSetup.Layout n) + (w : ℕ) (hw : n ≤ w) : Realization w (3*(n*n^3)) (R.partitionsCoupling z) := + pi w (n*n^3) 3 _ _ (fun i => by + have hs : RepresentationSetup.blockCount i*(2*RepresentationSetup.blockHalf n i) ≤ n := by + rw [←CanonicalPartition.size_eq R z i] + simpa only [Fintype.card_fin] using Finset.card_le_univ (R.orderedMixers z i) + exact enlarge (partition R z i w (clog_le _ _ (hs.trans hw))) + (Nat.mul_le_mul_right _ hs)) + +def nested {n : ℕ} (R : RepresentationSetup n) (z : RepresentationSetup.Layout n) + (w : ℕ) (hw : n ≤ w) : Realization w (3*n^3) (R.nestedCoupling z) := + triplePrime w n _ _ _ ((R.factorExponents_le_n z 0).trans hw) + ((R.factorExponents_le_n z 1).trans hw) ((R.factorExponents_le_n z 2).trans hw) + +def residues {n : ℕ} (R : RepresentationSetup n) (hn : 1 ≤ n) + {z : RepresentationSetup.Layout n} (p : R.PrimeSpace z) (w : ℕ) (hw : 3*n ≤ w) : + Realization w (n^3+(n^3+n^3)) (R.residuesCoupling p) := by + let : NeZero (prefixModulus p.val 0) := ⟨(prefixModulus_pos p 0).ne'⟩ + let : NeZero (prefixModulus p.val 1) := ⟨(prefixModulus_pos p 1).ne'⟩ + let : NeZero (prefixModulus p.val 2) := ⟨(prefixModulus_pos p 2).ne'⟩ + have h (i : Fin 3) : Nat.clog 2 (prefixModulus p.val i) ≤ w := + (Nat.clog_le_of_le_pow (RepresentationScalarBounds.prefix_bound R hn z p i)).trans hw + exact prod (fin w n _ (h 0)) (prod (fin w n _ (h 1)) (fin w n _ (h 2))) + +def extraPrime {n : ℕ} (R : RepresentationSetup n) (z : RepresentationSetup.Layout n) + (hn : 100 ≤ n) (w : ℕ) (hw : n ≤ w) : + Realization w (n^3) (R.extraPrimeCoupling z hn) := + prime w n _ (R.extraPrimeParameter_range z hn).1 + ((R.extraPrimeParameter_range z hn).2.trans hw) + +def guessHistory {n : ℕ} (R : RepresentationSetup n) (w : ℕ) (hw : n+1 ≤ w) : + Realization w ((n*n^3+n)+3*n^3) R.guessHistoryCoupling := by + have hg : CanonicalGuesses.width n ≤ n+1 := by + unfold CanonicalGuesses.width CanonicalGuesses.upper CanonicalGuesses.lower mixerSize + omega + exact bind (layout R w (clog_le _ _ (by omega)) (by omega)) + (fun _ => RepresentationSetup.Guesses n) (fun _ => R.guessesCoupling) + (fun _ => guesses R w (clog_le _ _ (hg.trans hw))) + +def partitionHistory {n : ℕ} (R : RepresentationSetup n) (w : ℕ) (hw : n+1 ≤ w) : + Realization w (((n*n^3+n)+3*n^3)+3*(n*n^3)) R.partitionHistoryCoupling := + bind (guessHistory R w hw) (fun h => R.Partitions h.1) + (fun h => R.partitionsCoupling h.1) (fun h => partitions R h.1 w (by omega)) + +def primeHistory {n : ℕ} (R : RepresentationSetup n) (w : ℕ) (hw : n+1 ≤ w) : + Realization w ((((n*n^3+n)+3*n^3)+3*(n*n^3))+3*n^3) R.primeHistoryCoupling := + bind (partitionHistory R w hw) (fun h => R.PrimeSpace h.1.1) + (fun h => R.nestedCoupling h.1.1) (fun h => nested R h.1.1 w (by omega)) + +def trialHistory {n : ℕ} (R : RepresentationSetup n) (hn : 1 ≤ n) + (w : ℕ) (hw : 3*n+1 ≤ w) : + Realization w (((((n*n^3+n)+3*n^3)+3*(n*n^3))+3*n^3)+(n^3+(n^3+n^3))) + R.trialHistoryCoupling := + bind (primeHistory R w (by omega)) (fun h => R.Residues h.2) + (fun h => R.residuesCoupling h.2) (fun h => residues R hn h.2 w (by omega)) + +def extraHistory {n : ℕ} (R : RepresentationSetup n) (hn : 100 ≤ n) + (w : ℕ) (hw : 3*n+1 ≤ w) : + Realization w ((((((n*n^3+n)+3*n^3)+3*(n*n^3))+3*n^3)+(n^3+(n^3+n^3)))+n^3) + (R.extraHistoryCoupling hn) := by + unfold RepresentationSetup.extraHistoryCoupling + exact bind (S := R.trialHistoryCoupling) (trialHistory R (by omega) w hw) + (fun h => R.ExtraPrimeSpace h.1.1.1.1) (fun h => R.extraPrimeCoupling h.1.1.1.1 hn) + (fun h => extraPrime R h.1.1.1.1 hn w (by omega)) + +def separatorDraws {n : ℕ} (R : RepresentationSetup n) + (h : R.PrimeHistory) (hn : 2200 ≤ n) (w : ℕ) + (hw : Nat.clog 2 (2*RepresentationSetup.blockHalf n 0) ≤ w) : + Realization w (4*(11*2^(2*RepresentationSetup.blockHalf n 0)* + ((2*RepresentationSetup.blockHalf n 0)*n^3))) (R.separatorCoupling h hn) := + families (RepresentationSetup.separatorParameters h.1.1.2 hn) w n hw + +def bucketHistory {n : ℕ} (R : RepresentationSetup n) (hn : 10000 ≤ n) + (w : ℕ) (hw : 3*n+1 ≤ w) := + bind (S := R.extraHistoryCoupling (by omega)) (extraHistory R (by omega) w hw) + (fun h => R.SeparatorDraws h.1.1 (by omega)) + (fun h => R.separatorCoupling h.1.1 (by omega)) + (fun h => separatorDraws R h.1.1 (by omega) w (clog_le _ _ (by + have hg : 2*RepresentationSetup.blockHalf n 0 ≤ n := by + unfold RepresentationSetup.blockHalf + simp only [Matrix.cons_val_zero] + omega + omega))) + +end LowSpaceSubsetSum.WordSeedRealization + +end + +end OAI diff --git a/lean/OAI/Combinatorics/LowSpaceSubsetSum/Word/WordSeedHistoryBounds.lean b/lean/OAI/Combinatorics/LowSpaceSubsetSum/Word/WordSeedHistoryBounds.lean new file mode 100644 index 0000000000000000000000000000000000000000..ff87a8eeae951be9bffa65a865213e4dad8a4087 --- /dev/null +++ b/lean/OAI/Combinatorics/LowSpaceSubsetSum/Word/WordSeedHistoryBounds.lean @@ -0,0 +1,195 @@ +import OAI.Combinatorics.LowSpaceSubsetSum.Word.WordSeedAdditiveBudget +import OAI.Combinatorics.LowSpaceSubsetSum.Word.WordSeedPreparedBounds +import OAI.Combinatorics.LowSpaceSubsetSum.Word.WordSeedStructuralBounds +import OAI.Combinatorics.LowSpaceSubsetSum.Word.WordSeedFiniteBounds +import OAI.Combinatorics.LowSpaceSubsetSum.Word.WordSeedFamilyBounds +import OAI.Combinatorics.LowSpaceSubsetSum.Word.WordSeedBucketExecution + +namespace OAI + +/-! # Resource bounds for the complete executed word history + +The seven stages add their retained seed buffers. Exponents are bounded +only after this addition, so repeated preparation cannot hide storage. +-/ + +noncomputable section +namespace LowSpaceSubsetSum.WordSeedHistoryBounds + +open WordSeedMeasured + +variable {n : ℕ} + +def workBudget (I : Instance n) := inputScale I^10*2^((n+1)/2) +def liveBudget (I : Instance n) := 3*inputScale I^10*(compressionDictionaryCapacity n+1) + +private theorem polynomial_stage {α : Type} [Fintype α] {w N : ℕ} + {S : SamplerCoupling α} {X : WordSeedRealization.Realization w N S} + (I : Instance n) (E : Execution X) (k : ℕ) (hk : k ≤ 10) + (hE : E.Bounded (inputScale I^k) (inputScale I^k) (inputScale I^k)) : + E.Bounded (workBudget I) (liveBudget I) (liveBudget I) := by + have hu : 0 < inputScale I := by unfold inputScale; omega + have hp : inputScale I^k ≤ inputScale I^10 := Nat.pow_le_pow_right hu hk + have hW := hp.trans (Nat.le_mul_of_pos_right _ (Nat.one_le_two_pow (n := (n+1)/2))) + have hC := hp.trans (Nat.le_mul_of_pos_right _ (show 0 < compressionDictionaryCapacity n+1 by omega)) + apply bounded_mono E hE hW + · unfold liveBudget + exact hC.trans (Nat.mul_le_mul_right _ (Nat.le_mul_of_pos_left _ (by decide : 0 < 3))) + · unfold liveBudget + exact hC.trans (Nat.mul_le_mul_right _ (Nat.le_mul_of_pos_left _ (by decide : 0 < 3))) + +private theorem prepared_stage {α : Type} [Fintype α] {w N : ℕ} + {S : SamplerCoupling α} {X : WordSeedRealization.Realization w N S} + (I : Instance n) (E : Execution X) + (hE : E.Bounded (inputScale I^8*2^((n+1)/2)) + (2*inputScale I^10*(compressionDictionaryCapacity n+1)) + (2*inputScale I^10*(compressionDictionaryCapacity n+1))) : + E.Bounded (workBudget I) (liveBudget I) (liveBudget I) := by + apply bounded_mono E hE + · exact Nat.mul_le_mul_right _ (Nat.pow_le_pow_right (by unfold inputScale; omega) (by decide : 8 ≤ 10)) + · unfold liveBudget + exact Nat.mul_le_mul_right _ (Nat.mul_le_mul_right _ (by decide : 2 ≤ 3)) + · unfold liveBudget + exact Nat.mul_le_mul_right _ (Nat.mul_le_mul_right _ (by decide : 2 ≤ 3)) + +private theorem family_stage {α : Type} [Fintype α] {w N : ℕ} + {S : SamplerCoupling α} {X : WordSeedRealization.Realization w N S} + (I : Instance n) (E : Execution X) + (hE : E.Bounded (inputScale I^9*2^((n+1)/2)) + (inputScale I^9*(compressionDictionaryCapacity n+1)) + (inputScale I^9*(compressionDictionaryCapacity n+1))) : + E.Bounded (workBudget I) (liveBudget I) (liveBudget I) := by + have hp : inputScale I^9 ≤ inputScale I^10 := Nat.pow_le_pow_right (by unfold inputScale; omega) (by decide) + have hc := Nat.mul_le_mul_right (compressionDictionaryCapacity n+1) hp + apply bounded_mono E hE (Nat.mul_le_mul_right _ hp) + · unfold liveBudget + exact hc.trans (Nat.mul_le_mul_right _ (Nat.le_mul_of_pos_left _ (by decide : 0 < 3))) + · unfold liveBudget + exact hc.trans (Nat.mul_le_mul_right _ (Nat.le_mul_of_pos_left _ (by decide : 0 < 3))) + +theorem residues_bounded_scale (I : Instance n) (hn : 10000 ≤ n) + (R : RepresentationSetup n) {z : RepresentationSetup.Layout n} (p : R.PrimeSpace z) + (w : ℕ) (hw : 3*n ≤ w) : + (residues R (by omega) p w hw).Bounded (inputScale I^6) (inputScale I^6) (inputScale I^6) := by + let : NeZero (prefixModulus p.val 0) := ⟨(prefixModulus_pos p 0).ne'⟩ + let : NeZero (prefixModulus p.val 1) := ⟨(prefixModulus_pos p 1).ne'⟩ + let : NeZero (prefixModulus p.val 2) := ⟨(prefixModulus_pos p 2).ne'⟩ + have h (i : Fin 3) : Nat.clog 2 (prefixModulus p.val i) ≤ 3*n := + Nat.clog_le_of_le_pow (RepresentationScalarBounds.prefix_bound R (by omega) z p i) + have hi (i : Fin 3) := by + letI : NeZero (prefixModulus p.val i) := ⟨(prefixModulus_pos p i).ne'⟩ + exact WordSeedScalarBounds.fin_bounded_scale I hn (prefixModulus p.val i) + (h i) w ((h i).trans hw) + have h12 := prod_bounded _ _ _ _ _ _ _ _ (hi 1) (hi 2) + have h012 := prod_bounded _ _ _ _ _ _ _ _ (hi 0) h12 + have hall := prepareThen_bounded (fun _ => (((),6),8)) _ _ _ _ _ _ + (le_refl 6) (le_refl 8) (fun _ => h012) + let u := inputScale I + have hu : 10000 ≤ u := by unfold u inputScale; omega + have hup : u ≤ u^5 := by simpa only [pow_one] using Nat.pow_le_pow_right (by omega : 0 < u) (by decide : 1 ≤ 5) + have hs : 10*u^5 ≤ u^6 := by + calc + _ ≤ u*u^5 := Nat.mul_le_mul_right _ (by omega) + _ = _ := by ring + intro stream cursor + have ht := hall stream cursor + dsimp only [u] at hs hup hu + change _ ≤ inputScale I^6 ∧ _ ≤ inputScale I^6 ∧ _ ≤ inputScale I^6 + exact ⟨ht.1.trans (by omega),ht.2.1.trans (by omega),ht.2.2.trans (by omega)⟩ + +theorem guessHistory_budget (I : Instance n) (hn : 10000 ≤ n) (w : ℕ) (hw : n+1 ≤ w) : + Budgeted (guessHistory I w hw) (workBudget I) (liveBudget I) 2 := by + unfold guessHistory + apply budgeted_bind + · apply budgeted_one + exact polynomial_stage I _ 6 (by decide) + (WordSeedStructuralBounds.layout_bounded_scale I hn _ _ _ _) + · intro a + exact polynomial_stage I _ 6 (by decide) + (WordSeedStructuralBounds.guesses_bounded_scale I hn _ _ _) + +theorem partitionHistory_budget (I : Instance n) (hn : 10000 ≤ n) (w : ℕ) (hw : n+1 ≤ w) : + Budgeted (partitionHistory I w hw) (workBudget I) (liveBudget I) 3 := by + unfold partitionHistory + apply budgeted_bind + · exact guessHistory_budget I hn w hw + · intro a + exact polynomial_stage I _ 7 (by decide) + (WordSeedStructuralBounds.partitions_bounded_scale I hn _ _ _ _) + +theorem primeHistory_budget (I : Instance n) (hn : 10000 ≤ n) (w : ℕ) (hw : n+1 ≤ w) : + Budgeted (primeHistory I w hw) (workBudget I) (liveBudget I) 4 := by + unfold primeHistory + apply budgeted_bindSeed + · exact partitionHistory_budget I hn w hw + · intro a + exact prepared_stage I _ (nestedPrepared_bounded I hn _ _ _) + +theorem trialHistory_budget (I : Instance n) (hn : 10000 ≤ n) (w : ℕ) (hw : 3*n+1 ≤ w) : + Budgeted (trialHistory I (by omega) w hw) (workBudget I) (liveBudget I) 5 := by + unfold trialHistory + apply budgeted_bind + · exact primeHistory_budget I hn w (by omega) + · intro a + exact polynomial_stage I _ 6 (by decide) (residues_bounded_scale I hn _ _ _ _) + +theorem extraHistory_budget (I : Instance n) (hn : 10000 ≤ n) (w : ℕ) (hw : 3*n+1 ≤ w) : + Budgeted (extraHistory I (by omega) w hw) (workBudget I) (liveBudget I) 6 := by + unfold extraHistory + apply budgeted_bindSeed + · exact trialHistory_budget I hn w hw + · intro a + exact prepared_stage I _ (extraPrepared_bounded I hn _ _ _) + +theorem separatorDraws_stage (I : Instance n) (hn : 10000 ≤ n) (R : RepresentationSetup n) + (h : R.PrimeHistory) (w : ℕ) (hw : Nat.clog 2 (2*RepresentationSetup.blockHalf n 0) ≤ w) : + (separatorDraws R h (by omega) w hw).Bounded (workBudget I) (liveBudget I) (liveBudget I) := by + unfold separatorDraws + apply family_stage + exact WordSeedFamilyBounds.familiesPrepared_application I hn _ _ _ + (WordSamplingBounds.family_width n) _ _ _ _ w hw + (WordSeedFamilyBounds.canonical_family_codes n) (WordSeedFamilyBounds.canonical_family_half n) + +theorem bucketHistory_budget (I : Instance n) (hn : 10000 ≤ n) (w : ℕ) (hw : 3*n+1 ≤ w) : + Budgeted (bucketHistory I hn w hw) (workBudget I) (liveBudget I) 7 := by + unfold bucketHistory + apply budgeted_bind + · exact extraHistory_budget I hn w hw + · intro a + exact separatorDraws_stage I hn _ _ _ _ + +theorem bucketHistory_bounded (I : Instance n) (hn : 10000 ≤ n) (w : ℕ) (hw : 3*n+1 ≤ w) : + (bucketHistory I hn w hw).Bounded (inputScale I^11*2^((n+1)/2)) + (inputScale I^11*(compressionDictionaryCapacity n+1)) + (inputScale I^11*(compressionDictionaryCapacity n+1)) := by + have h := bucketHistory_budget I hn w hw + let u := inputScale I + let C := compressionDictionaryCapacity n+1 + let H := 2^((n+1)/2) + have hu : 10000 ≤ u := by unfold u inputScale; omega + have hC : 1 ≤ C := by unfold C; omega + have hH : 1 ≤ H := Nat.one_le_two_pow + have hp : u ≤ u^10 := by simpa only [pow_one] using Nat.pow_le_pow_right (by omega : 0 < u) (by decide : 1 ≤ 10) + have hmc := Nat.le_mul_of_pos_right (u^10) hC + have hmh := Nat.le_mul_of_pos_right (u^10) hH + have hc : 22*u^10*C ≤ u^11*C := by + calc + _ ≤ u*u^10*C := Nat.mul_le_mul_right _ (Nat.mul_le_mul_right _ (by omega)) + _ = _ := by ring + have ht : 8*u^10*H ≤ u^11*H := by + calc + _ ≤ u*u^10*H := Nat.mul_le_mul_right _ (Nat.mul_le_mul_right _ (by omega)) + _ = _ := by ring + apply bounded_mono _ h + · change 7*(u^10*H+2) ≤ u^11*H + nlinarith only [ht,hmh,hp,hu] + · change 7*(3*u^10*C+8) ≤ u^11*C + nlinarith only [hc,hmc,hp,hu] + · change 7*(3*u^10*C+8) ≤ u^11*C + nlinarith only [hc,hmc,hp,hu] + +end LowSpaceSubsetSum.WordSeedHistoryBounds + +end + +end OAI diff --git a/lean/OAI/Combinatorics/LowSpaceSubsetSum/Word/WordSeedHistoryExecution.lean b/lean/OAI/Combinatorics/LowSpaceSubsetSum/Word/WordSeedHistoryExecution.lean new file mode 100644 index 0000000000000000000000000000000000000000..f6cd6b6e8497fcdb3d6649103150e8742e1ec68f --- /dev/null +++ b/lean/OAI/Combinatorics/LowSpaceSubsetSum/Word/WordSeedHistoryExecution.lean @@ -0,0 +1,93 @@ +import OAI.Combinatorics.LowSpaceSubsetSum.Word.WordSeedStructuralExecution +import OAI.Combinatorics.LowSpaceSubsetSum.Word.WordSeedPreparedPrimes + +namespace OAI + +/-! # Executing the dependent representation sampling history + +Every continuation uses the cached accepted layout. At the prime stages it +runs the counted mixer preparation on that layout's stored accepted seed. +-/ + +noncomputable section +namespace LowSpaceSubsetSum.WordSeedMeasured + +variable {n : ℕ} + +private theorem clog_le (k w : ℕ) (h : k ≤ w) : Nat.clog 2 k ≤ w := + (Nat.clog_le_of_le_pow Nat.lt_two_pow_self.le).trans h + +def guessHistory (I : Instance n) (w : ℕ) (hw : n+1 ≤ w) : + Execution (WordSeedRealization.guessHistory (canonicalRepresentationData I).zeroSetup w hw) := by + have hg : CanonicalGuesses.width n ≤ n+1 := by + unfold CanonicalGuesses.width CanonicalGuesses.upper CanonicalGuesses.lower mixerSize + omega + exact bind (layout _ w (clog_le _ _ (by omega)) (by omega)) + (fun _ => RepresentationSetup.Guesses n) (fun _ => (canonicalRepresentationData I).zeroSetup.guessesCoupling) + (fun _ => WordSeedRealization.guesses _ w (clog_le _ _ (hg.trans hw))) + (fun _ => guesses _ w (clog_le _ _ (hg.trans hw))) + +def partitionHistory (I : Instance n) (w : ℕ) (hw : n+1 ≤ w) : + Execution (WordSeedRealization.partitionHistory (canonicalRepresentationData I).zeroSetup w hw) := + bind (guessHistory I w hw) (fun h => (canonicalRepresentationData I).zeroSetup.Partitions h.1) + (fun h => (canonicalRepresentationData I).zeroSetup.partitionsCoupling h.1) + (fun h => WordSeedRealization.partitions _ h.1 w (by omega)) + (fun h => partitions _ h.1 w (by omega)) + +def layoutOfPartition (I : Instance n) + (a : Accepted (canonicalRepresentationData I).zeroSetup.partitionHistoryCoupling) : + WordLayoutPreparation.Layout I := + firstAccepted (fun _ => RepresentationSetup.Guesses n) + (fun _ => (canonicalRepresentationData I).zeroSetup.guessesCoupling) + (firstAccepted (fun h => (canonicalRepresentationData I).zeroSetup.Partitions h.1) + (fun h => (canonicalRepresentationData I).zeroSetup.partitionsCoupling h.1) a) + +def primeHistory (I : Instance n) (w : ℕ) (hw : n+1 ≤ w) : + Execution (WordSeedRealization.primeHistory (canonicalRepresentationData I).zeroSetup w hw) := + bindSeed (partitionHistory I w hw) + (fun h => (canonicalRepresentationData I).zeroSetup.PrimeSpace h.1.1) + (fun h => (canonicalRepresentationData I).zeroSetup.nestedCoupling h.1.1) + (fun h => WordSeedRealization.nested _ h.1.1 w (by omega)) + (fun a => nestedPrepared I (layoutOfPartition I a) w (by omega)) + +def residues (R : RepresentationSetup n) (hn : 1 ≤ n) + {z : RepresentationSetup.Layout n} (p : R.PrimeSpace z) (w : ℕ) (hw : 3*n ≤ w) : + Execution (WordSeedRealization.residues R hn p w hw) := by + let : NeZero (prefixModulus p.val 0) := ⟨(prefixModulus_pos p 0).ne'⟩ + let : NeZero (prefixModulus p.val 1) := ⟨(prefixModulus_pos p 1).ne'⟩ + let : NeZero (prefixModulus p.val 2) := ⟨(prefixModulus_pos p 2).ne'⟩ + have h (i : Fin 3) : Nat.clog 2 (prefixModulus p.val i) ≤ w := + (Nat.clog_le_of_le_pow (RepresentationScalarBounds.prefix_bound R hn z p i)).trans hw + exact prepareThen (fun _ => (((),6),8)) (fun _ => + prod (fin w n _ (h 0)) (prod (fin w n _ (h 1)) (fin w n _ (h 2)))) + +def trialHistory (I : Instance n) (hn : 1 ≤ n) (w : ℕ) (hw : 3*n+1 ≤ w) : + Execution (WordSeedRealization.trialHistory (canonicalRepresentationData I).zeroSetup hn w hw) := + bind (primeHistory I w (by omega)) + (fun h => (canonicalRepresentationData I).zeroSetup.Residues h.2) + (fun h => (canonicalRepresentationData I).zeroSetup.residuesCoupling h.2) + (fun h => WordSeedRealization.residues _ hn h.2 w (by omega)) + (fun h => residues _ hn h.2 w (by omega)) + +def layoutOfTrial (I : Instance n) + (a : Accepted (canonicalRepresentationData I).zeroSetup.trialHistoryCoupling) : + WordLayoutPreparation.Layout I := + layoutOfPartition I + (firstAccepted (fun h => (canonicalRepresentationData I).zeroSetup.PrimeSpace h.1.1) + (fun h => (canonicalRepresentationData I).zeroSetup.nestedCoupling h.1.1) + (firstAccepted (fun h => (canonicalRepresentationData I).zeroSetup.Residues h.2) + (fun h => (canonicalRepresentationData I).zeroSetup.residuesCoupling h.2) a)) + +def extraHistory (I : Instance n) (hn : 100 ≤ n) (w : ℕ) (hw : 3*n+1 ≤ w) : + Execution (WordSeedRealization.extraHistory (canonicalRepresentationData I).zeroSetup hn w hw) := + bindSeed (trialHistory I (by omega) w hw) + (fun h => (canonicalRepresentationData I).zeroSetup.ExtraPrimeSpace h.1.1.1.1) + (fun h => (canonicalRepresentationData I).zeroSetup.extraPrimeCoupling h.1.1.1.1 hn) + (fun h => WordSeedRealization.extraPrime _ h.1.1.1.1 hn w (by omega)) + (fun a => extraPrepared I (layoutOfTrial I a) hn w (by omega)) + +end LowSpaceSubsetSum.WordSeedMeasured + +end + +end OAI diff --git a/lean/OAI/Combinatorics/LowSpaceSubsetSum/Word/WordSeedMaskExecution.lean b/lean/OAI/Combinatorics/LowSpaceSubsetSum/Word/WordSeedMaskExecution.lean new file mode 100644 index 0000000000000000000000000000000000000000..85afedf2ba399c3e1614d7d8b3433330791e8245 --- /dev/null +++ b/lean/OAI/Combinatorics/LowSpaceSubsetSum/Word/WordSeedMaskExecution.lean @@ -0,0 +1,153 @@ +import OAI.Combinatorics.LowSpaceSubsetSum.Word.WordSeedPreparedBind +import OAI.Combinatorics.LowSpaceSubsetSum.Word.WordSeedDraws +import OAI.Combinatorics.LowSpaceSubsetSum.Word.WordSeedPermutationExecution +import OAI.Combinatorics.LowSpaceSubsetSum.Storage.FixedSizeSampleCells + +namespace OAI + +/-! # Building sampled subsets from stored permutation entries + +The sampled permutation is materialized and its first selected entries are +scanned into a duplicate-free list. The Finset constructor uses that list +without a further deduplication pass. +-/ + +noncomputable section +namespace LowSpaceSubsetSum.WordSeedMeasured + +abbrev PermutationAccepted (n g : ℕ) := Accepted (permutationCoupling n g) + +theorem permutation_materializes (n g : ℕ) (a : PermutationAccepted n g) : + ∃ v, (PermutationSamplerCells.materialize n g a.seed.val).1.1 = some v := by + have hv := PermutationDigitsExecution.value n g a.seed.val + rw [(SamplerExecution.permutation n g).value_eq,accepted_source a] at hv + cases hd : (PermutationDigitsExecution.run n g a.seed.val).value with + | none => simp only [hd,Option.map_none,reduceCtorEq] at hv + | some d => + refine ⟨(PermutationArray.build g d).1,?_⟩ + rw [PermutationSamplerCells.materialize_value] + simp only [PermutationDigitsExecution.materialize,hd] + +theorem permutation_materialized_value (n g : ℕ) (a : PermutationAccepted n g) + (v : Vector (Fin g) g) + (hv : (PermutationSamplerCells.materialize n g a.seed.val).1.1 = some v) : + ∀ i : Fin g, v[i.val] = a.value i := by + rw [PermutationSamplerCells.materialize_value] at hv + obtain ⟨e,he,hv⟩ := PermutationDigitsExecution.materialize_value n g a.seed.val v hv + rw [(SamplerExecution.permutation n g).value_eq,accepted_source a] at he + cases Option.some.inj he + exact hv + +abbrev Materialized (n g : ℕ) (a : PermutationAccepted n g) := + {v : Vector (Fin g) g // + (PermutationSamplerCells.materialize n g a.seed.val).1.1 = some v} + +def materializeAccepted (n g : ℕ) (a : PermutationAccepted n g) : + (Materialized n g a × ℕ) × ℕ := + let r := PermutationSamplerCells.materialize n g a.seed.val + match h : r.1.1 with + | none => False.elim (by + obtain ⟨v,hv⟩ := permutation_materializes n g a + cases h.symm.trans hv) + | some v => ((⟨v,h⟩,g*n^3+r.1.2+1),r.2+8) + +def selectedCompute (n g k : ℕ) (_hk : k ≤ g) (a : PermutationAccepted n g) : + (Finset (Fin g) × ℕ) × ℕ := + let material := materializeAccepted n g a + let v := material.1.1 + let xs := FixedSizeSampleCells.selected v.val k + let set : Finset (Fin g) := ⟨(xs.1 : Multiset (Fin g)),by + rw [FixedSizeSampleCells.prefix_value] + change (((List.finRange g).filter (fun i => decide (i.val < k))).map + (fun i => v.val[i.val])).Nodup + apply List.Nodup.map + · intro i j h + have hv := permutation_materialized_value n g a v.val v.property + exact a.value.injective ((hv i).symm.trans (h.trans (hv j))) + · exact (List.nodup_finRange g).filter _⟩ + ((set,material.1.2+4*g+3),material.2+xs.2+g+8) + +theorem selectedCompute_value (n g k : ℕ) (hk : k ≤ g) (a : PermutationAccepted n g) : + (selectedCompute n g k hk a).1.1 = (permutationBlock (initialSubset g k hk) a.value).val := by + let v := (materializeAccepted n g a).1.1 + have hv := permutation_materialized_value n g a v.val v.property + have h := PermutationSubsetCode.prefix_value v.val a.value hv k hk + apply Finset.ext + intro i + change i ∈ (FixedSizeSampleCells.selected v.val k).1 ↔ _ + rw [FixedSizeSampleCells.prefix_value] + have hm := Finset.ext_iff.mp h i + simpa only [List.mem_toFinset,permutationBlock] using hm + +theorem selectedCompute_work (n g k : ℕ) (hk : k ≤ g) (a : PermutationAccepted n g) : + (selectedCompute n g k hk a).1.2 ≤ g*n^3+10*(g+1)^2+4*g+5 := by + have hm := PermutationDigitsExecution.materialize_work n g a.seed.val + rw [←PermutationSamplerCells.materialize_value] at hm + obtain ⟨v,hv⟩ := permutation_materializes n g a + unfold selectedCompute materializeAccepted + dsimp only + split + next h => cases h.symm.trans hv + · dsimp only + omega + +theorem selectedCompute_cells (n g k : ℕ) (hk : k ≤ g) (a : PermutationAccepted n g) : + (selectedCompute n g k hk a).2 ≤ (g+1)*(3*n^3+128)+6*g+32 := by + have hm := PermutationSamplerCells.materialize_cells n g a.seed.val + obtain ⟨v,hv⟩ := permutation_materializes n g a + unfold selectedCompute materializeAccepted + dsimp only + split + next h => cases h.symm.trans hv + next v' h => + have hx := FixedSizeSampleCells.prefix_cells v' k + dsimp only + omega + +def selectedTyped (n g k : ℕ) (hk : k ≤ g) (a : PermutationAccepted n g) : + (↥((Finset.univ : Finset (Fin g)).powersetCard (initialSubset g k hk).card) × ℕ) × ℕ := + let r := selectedCompute n g k hk a + ((⟨r.1.1,by + rw [selectedCompute_value] + exact (permutationBlock (initialSubset g k hk) a.value).property⟩,r.1.2),r.2) + +theorem selectedTyped_value (n g k : ℕ) (hk : k ≤ g) (a : PermutationAccepted n g) : + (selectedTyped n g k hk a).1.1 = permutationBlock (initialSubset g k hk) a.value := by + apply Subtype.ext + exact selectedCompute_value n g k hk a + +def subsetInitial (w n g k : ℕ) (hk : k ≤ g) (hw : Nat.clog 2 g ≤ w) : + Execution (WordSeedRealization.subset w n g (initialSubset g k hk) hw) := + mapStored (permutation w n g hw) (permutationBlock (initialSubset g k hk)) + (selectedTyped n g k hk) (selectedTyped_value n g k hk) + +def fixedSize (w n g k : ℕ) (hk : k ≤ g) (hw : Nat.clog 2 g ≤ w) : + Execution (WordSeedRealization.fixedSize w n g k hk hw) := + map (subsetInitial w n g k hk hw) (initialSubsetEquiv g k hk) + (fun a => (((initialSubsetEquiv g k hk) a,1),2)) (fun _ => rfl) + +theorem fixedSize_bounded (w n g k : ℕ) (hk : k ≤ g) (hw : Nat.clog 2 g ≤ w) : + (fixedSize w n g k hk hw).Bounded + (g*(14*n^3+5*g+68)+10*(g+1)^2+11) + (10*(g+1)*(n^3+256)) (10*(g+1)*(n^3+256)) := by + have hs := mapStored_bounded (permutation w n g hw) + (permutationBlock (initialSubset g k hk)) (selectedTyped n g k hk) + (selectedTyped_value n g k hk) _ _ _ _ _ (permutation_bounded w n g hw) + (selectedCompute_work n g k hk) (selectedCompute_cells n g k hk) + have ht := map_bounded (subsetInitial w n g k hk hw) (initialSubsetEquiv g k hk) + (fun a => (((initialSubsetEquiv g k hk) a,1),2)) (fun _ => rfl) + _ _ _ 1 2 hs (fun _ => le_rfl) (fun _ => le_rfl) + intro stream cursor + have h := ht stream cursor + change _ ≤ _ ∧ _ ≤ _ ∧ _ ≤ _ + refine ⟨h.1.trans (by nlinarith),h.2.1.trans ?_,h.2.2.trans ?_⟩ + · apply max_le + · apply max_le <;> nlinarith + · nlinarith + · nlinarith + +end LowSpaceSubsetSum.WordSeedMeasured + +end + +end OAI diff --git a/lean/OAI/Combinatorics/LowSpaceSubsetSum/Word/WordSeedMeasured.lean b/lean/OAI/Combinatorics/LowSpaceSubsetSum/Word/WordSeedMeasured.lean new file mode 100644 index 0000000000000000000000000000000000000000..ccdd82cd464470cac232cc56a4501e1fdc0d7ff4 --- /dev/null +++ b/lean/OAI/Combinatorics/LowSpaceSubsetSum/Word/WordSeedMeasured.lean @@ -0,0 +1,155 @@ +import OAI.Combinatorics.LowSpaceSubsetSum.Word.WordSeedRejectionExecution + +namespace OAI + +/-! # Measured seed generation with cached accepted outputs + +Dependent continuations use the stored output of the preceding call. +The equality with its ideal value is used only for type transport. A map +must provide an actual measured evaluator; its work is added explicitly. +-/ + +noncomputable section +namespace LowSpaceSubsetSum.WordSeedMeasured + +open WordSeedRealization + +variable {w N M : ℕ} {α β : Type} [Fintype α] [Fintype β] + +structure Accepted (S : SamplerCoupling α) where + seed : SuccessfulSeed S + value : α + correct : value = S.ideal seed.val + +structure Result (S : SamplerCoupling α) where + accepted : Option (Accepted S) + cursor : ℕ + work : ℕ + cells : ℕ + retained : ℕ + +structure Execution {S : SamplerCoupling α} (X : Realization w N S) where + run : (ℕ → Fin (2^w)) → ℕ → Result S + value : ∀ stream cursor, + ((run stream cursor).accepted.map Accepted.seed,(run stream cursor).cursor) = + WordProgram.run stream X.program cursor + +def Execution.Bounded {S : SamplerCoupling α} {X : Realization w N S} + (E : Execution X) (W C R : ℕ) : Prop := + ∀ stream cursor, (E.run stream cursor).work ≤ W ∧ + (E.run stream cursor).cells ≤ C ∧ (E.run stream cursor).retained ≤ R + +def pure (a : α) : Execution (WordSeedRealization.pure (w := w) a) where + run _ cursor := ⟨some ⟨⟨(),a,rfl⟩,a,rfl⟩,cursor,1,4,4⟩ + value _ _ := rfl + +theorem pure_bounded (a : α) : (pure (w := w) a).Bounded 1 4 4 := + fun _ _ => ⟨le_rfl,le_rfl,le_rfl⟩ + +def mapAccepted {S : SamplerCoupling α} (f : α → β) (a : Accepted S) + (b : β) (hb : b = f a.value) : Accepted (S.map f) where + seed := mapSeed f a.seed + value := b + correct := hb.trans (congrArg f a.correct) + +def mapRun {S : SamplerCoupling α} {X : Realization w N S} (E : Execution X) + (f : α → β) (compute : α → (β × ℕ) × ℕ) (hc : ∀ a, (compute a).1.1 = f a) + (stream : ℕ → Fin (2^w)) (cursor : ℕ) : Result (S.map f) := + let r := E.run stream cursor + match r.accepted with + | none => ⟨none,r.cursor,r.work+1,r.cells,r.retained⟩ + | some a => + let b := compute a.value + ⟨some (mapAccepted f a b.1.1 (hc a.value)),r.cursor, + r.work+b.1.2+2,max r.cells (r.retained+b.2+8),r.retained+b.2+8⟩ + +def map {S : SamplerCoupling α} {X : Realization w N S} (E : Execution X) + (f : α → β) (compute : α → (β × ℕ) × ℕ) (hc : ∀ a, (compute a).1.1 = f a) : + Execution (WordSeedRealization.map X f) where + run := mapRun E f compute hc + value stream cursor := by + have h := E.value stream cursor + rw [WordSeedRealization.map,WordSeedRejectionExecution.program_run_map,←h] + cases ha : (E.run stream cursor).accepted <;> + simp only [mapRun,ha,Option.map_none,Option.map_some,mapAccepted] + +theorem map_bounded {S : SamplerCoupling α} {X : Realization w N S} (E : Execution X) + (f : α → β) (compute : α → (β × ℕ) × ℕ) (hc : ∀ a, (compute a).1.1 = f a) + (W C R F H : ℕ) (hE : E.Bounded W C R) + (hF : ∀ a, (compute a).1.2 ≤ F) (hH : ∀ a, (compute a).2 ≤ H) : + (map E f compute hc).Bounded (W+F+2) (max C (R+H+8)) (R+H+8) := by + intro stream cursor + have hr := hE stream cursor + dsimp only [map,mapRun] + split + · dsimp only + exact ⟨by omega,hr.2.1.trans (le_max_left _ _),by omega⟩ + next a ha => + dsimp only + have hf := hF a.value + have hh := hH a.value + exact ⟨by omega,max_le_max hr.2.1 (by omega),by omega⟩ + +def pairAccepted {S : SamplerCoupling α} (B : α → Type) [∀ a, Fintype (B a)] + (T : ∀ a, SamplerCoupling (B a)) (a : Accepted S) (b : Accepted (T a.value)) : + Accepted (S.bind B T) where + seed := pairSeed B T a.seed (a.correct ▸ b.seed) + value := ⟨a.value,b.value⟩ + correct := by + rcases a with ⟨s,a,ha⟩ + dsimp only at * + subst a + exact congrArg (Sigma.mk (S.ideal s.val)) b.correct + +def bindRun {S : SamplerCoupling α} {X : Realization w N S} (E : Execution X) + (B : α → Type) [∀ a, Fintype (B a)] (T : ∀ a, SamplerCoupling (B a)) + (Y : ∀ a, Realization w M (T a)) (F : ∀ a, Execution (Y a)) + (stream : ℕ → Fin (2^w)) (cursor : ℕ) : Result (S.bind B T) := + let r := E.run stream cursor + match r.accepted with + | none => ⟨none,r.cursor,r.work+1,r.cells,r.retained⟩ + | some a => + let t := (F a.value).run stream r.cursor + ⟨t.accepted.map (pairAccepted B T a),t.cursor,r.work+t.work+2, + max r.cells (r.retained+t.cells+8),r.retained+t.retained+8⟩ + +def bind {S : SamplerCoupling α} {X : Realization w N S} (E : Execution X) + (B : α → Type) [∀ a, Fintype (B a)] (T : ∀ a, SamplerCoupling (B a)) + (Y : ∀ a, Realization w M (T a)) (F : ∀ a, Execution (Y a)) : + Execution (WordSeedRealization.bind X B T Y) where + run := bindRun E B T Y F + value stream cursor := by + have hr := E.value stream cursor + rw [WordSeedRealization.bind,WordSeedRejectionExecution.program_run_bind,←hr] + cases ha : (E.run stream cursor).accepted with + | none => simp only [bindRun,ha,Option.map_none,continuation,WordProgram.run] + | some a => + rcases a with ⟨s,a,ha'⟩ + subst a + have ht := (F (S.ideal s.val)).value stream (E.run stream cursor).cursor + simp only [bindRun,ha,Option.map_some,continuation, + WordSeedRejectionExecution.program_run_map,←ht] + cases hb : ((F (S.ideal s.val)).run stream (E.run stream cursor).cursor).accepted <;> + simp only [Option.map_none,Option.map_some,pairAccepted] + +theorem bind_bounded {S : SamplerCoupling α} {X : Realization w N S} (E : Execution X) + (B : α → Type) [∀ a, Fintype (B a)] (T : ∀ a, SamplerCoupling (B a)) + (Y : ∀ a, Realization w M (T a)) (F : ∀ a, Execution (Y a)) + (W C R V D Q : ℕ) (hE : E.Bounded W C R) (hF : ∀ a, (F a).Bounded V D Q) : + (bind E B T Y F).Bounded (W+V+2) (max C (R+D+8)) (R+Q+8) := by + intro stream cursor + have hr := hE stream cursor + dsimp only [bind,bindRun] + split + · dsimp only + exact ⟨by omega,hr.2.1.trans (le_max_left _ _),by omega⟩ + next a ha => + have ht := hF a.value stream (E.run stream cursor).cursor + dsimp only + exact ⟨by omega,max_le_max hr.2.1 (by omega),by omega⟩ + +end LowSpaceSubsetSum.WordSeedMeasured + +end + +end OAI diff --git a/lean/OAI/Combinatorics/LowSpaceSubsetSum/Word/WordSeedMeasuredProduct.lean b/lean/OAI/Combinatorics/LowSpaceSubsetSum/Word/WordSeedMeasuredProduct.lean new file mode 100644 index 0000000000000000000000000000000000000000..fc8e7614a508016cc68c4ce67a3bb0c83297b835 --- /dev/null +++ b/lean/OAI/Combinatorics/LowSpaceSubsetSum/Word/WordSeedMeasuredProduct.lean @@ -0,0 +1,115 @@ +import OAI.Combinatorics.LowSpaceSubsetSum.Word.WordSeedMeasured + +namespace OAI + +/-! # Measured products and finite families of seed generators -/ + +noncomputable section +namespace LowSpaceSubsetSum.WordSeedMeasured + +open WordSeedRealization + +variable {w N M : ℕ} {α β : Type} [Fintype α] [Fintype β] + +/-- Changing a certified read bound preserves the executed program. -/ +theorem mpr_program {S : SamplerCoupling α} (h : M = N) (X : Realization w N S) : + (Eq.mpr (congrArg (fun j => Realization w j S) h) X).program = X.program := by + cases h + rfl + +/-- Transport only the proof-facing program index, leaving the executed result intact. -/ +def reprogram {S : SamplerCoupling α} {X : Realization w N S} + {Y : Realization w M S} (E : Execution X) (h : Y.program = X.program) : + Execution Y where + run := E.run + value stream cursor := by rw [h]; exact E.value stream cursor + +def enlarge {S : SamplerCoupling α} {X : Realization w N S} + (E : Execution X) (h : N ≤ M) : Execution (WordSeedRealization.enlarge X h) where + run := E.run + value := E.value + +theorem enlarge_bounded {S : SamplerCoupling α} {X : Realization w N S} + (E : Execution X) (h : N ≤ M) (W C R : ℕ) (hE : E.Bounded W C R) : + (enlarge E h).Bounded W C R := hE + +def prod {S : SamplerCoupling α} {T : SamplerCoupling β} + {X : Realization w N S} {Y : Realization w M T} + (E : Execution X) (F : Execution Y) : Execution (WordSeedRealization.prod X Y) := + map (bind E (fun _ => β) (fun _ => T) (fun _ => Y) (fun _ => F)) + (Equiv.sigmaEquivProd α β) + (fun p => (((Equiv.sigmaEquivProd α β) p,1),2)) (fun _ => rfl) + +theorem prod_bounded {S : SamplerCoupling α} {T : SamplerCoupling β} + {X : Realization w N S} {Y : Realization w M T} + (E : Execution X) (F : Execution Y) (W C R V D Q : ℕ) + (hE : E.Bounded W C R) (hF : F.Bounded V D Q) : + (prod E F).Bounded (W+V+5) + (max (max C (R+D+8)) (R+Q+18)) (R+Q+18) := by + have h := map_bounded + (bind E (fun _ => β) (fun _ => T) (fun _ => Y) (fun _ => F)) + (Equiv.sigmaEquivProd α β) + (fun p => (((Equiv.sigmaEquivProd α β) p,1),2)) (fun _ => rfl) + _ _ _ 1 2 (bind_bounded E _ _ _ _ W C R V D Q hE (fun _ => hF)) + (fun _ => le_rfl) (fun _ => le_rfl) + have hw : W+V+2+1+2 = W+V+5 := by omega + have hr : R+Q+8+2+8 = R+Q+18 := by omega + simpa only [prod,Execution.Bounded,SamplerCoupling.prod,WordSeedRealization.prod,hw,hr] using h + +def pi (w N : ℕ) : (k : ℕ) → (A : Fin k → Type) → [∀ i, Fintype (A i)] → + (S : ∀ i, SamplerCoupling (A i)) → (X : ∀ i, Realization w N (S i)) → + (∀ i, Execution (X i)) → Execution (WordSeedRealization.pi w N k A S X) + | 0, A, _, _, _, _ => by + exact reprogram (pure (w := w) (fun i : Fin 0 => (Fin.elim0 i : A i))) (by + unfold WordSeedRealization.pi + exact mpr_program (Nat.zero_mul N) _) + | k+1, A, _, S, X, E => by + let tail := pi w N k (fun i => A i.succ) (fun i => S i.succ) + (fun i => X i.succ) (fun i => E i.succ) + exact reprogram (map (prod (E 0) tail) (Fin.consEquiv A) + (fun p => (((Fin.consEquiv A) p,2),4)) (fun _ => rfl)) (by + conv_lhs => rw [WordSeedRealization.pi] + exact mpr_program (w := w) (α := ∀ i, A i) + (by simp only [Nat.add_mul,Nat.one_mul,Nat.add_comm] : (k+1)*N = N+k*N) _) + +theorem pi_bounded (w N : ℕ) : ∀ (k : ℕ) (A : Fin k → Type) [∀ i, Fintype (A i)] + (S : ∀ i, SamplerCoupling (A i)) (X : ∀ i, Realization w N (S i)) + (E : ∀ i, Execution (X i)) (W C R : ℕ), + (∀ i, (E i).Bounded W C R) → + (pi w N k A S X E).Bounded (k*(W+10)+1) + ((k+1)*(C+R+64)) ((k+1)*(R+32)) := by + intro k + induction k with + | zero => + intro A _ S X E W C R hE stream cursor + change 1 ≤ _ ∧ 4 ≤ _ ∧ 4 ≤ _ + constructor + · omega + · constructor <;> nlinarith + | succ k ih => + intro A _ S X E W C R hE + have ht := ih (fun i => A i.succ) (fun i => S i.succ) (fun i => X i.succ) + (fun i => E i.succ) W C R (fun i => hE i.succ) + have hp := prod_bounded (E 0) + (pi w N k (fun i => A i.succ) (fun i => S i.succ) + (fun i => X i.succ) (fun i => E i.succ)) + W C R _ _ _ (hE 0) ht + have hm := map_bounded _ (Fin.consEquiv A) + (fun p => (((Fin.consEquiv A) p,2),4)) (fun _ => rfl) + _ _ _ 2 4 hp (fun _ => le_rfl) (fun _ => le_rfl) + intro stream cursor + have h := hm stream cursor + change _ ≤ (k+1)*(W+10)+1 ∧ + _ ≤ (k+1+1)*(C+R+64) ∧ _ ≤ (k+1+1)*(R+32) + refine ⟨h.1.trans (by nlinarith),h.2.1.trans ?_,h.2.2.trans (by nlinarith)⟩ + apply max_le + · apply max_le + · apply max_le <;> nlinarith + · nlinarith + · nlinarith + +end LowSpaceSubsetSum.WordSeedMeasured + +end + +end OAI diff --git a/lean/OAI/Combinatorics/LowSpaceSubsetSum/Word/WordSeedMeasuredRejection.lean b/lean/OAI/Combinatorics/LowSpaceSubsetSum/Word/WordSeedMeasuredRejection.lean new file mode 100644 index 0000000000000000000000000000000000000000..1f02edbcf028bb78615c8aac1bf1ed31caadfd82 --- /dev/null +++ b/lean/OAI/Combinatorics/LowSpaceSubsetSum/Word/WordSeedMeasuredRejection.lean @@ -0,0 +1,70 @@ +import OAI.Combinatorics.LowSpaceSubsetSum.Word.WordSeedMeasured + +namespace OAI + +/-! # Measured rejection as a cached seed-generator primitive -/ + +noncomputable section +namespace LowSpaceSubsetSum.WordSeedMeasured + +open WordSeedRealization + +variable {w k : ℕ} (A : Fin (2^k) → Prop) [DecidablePred A] + [Nonempty {a : Fin (2^k) // A a}] + +theorem rejectionSeed_backup (N : ℕ) (f : Fin N → Fin (2^k)) + (s : SuccessfulSeed (firstAcceptCoupling A N)) (h : rejectionSeed A N f = some s) : + (firstAcceptCoupling A N).bounded s.val = some s.val.2 := by + unfold rejectionSeed at h + split at h + · contradiction + next a ha => + cases h + exact ha + +def cacheRejection (N : ℕ) (f : Fin N → Fin (2^k)) + (out : Option (SuccessfulSeed (firstAcceptCoupling A N))) + (ho : out = rejectionSeed A N f) : Option (Accepted (firstAcceptCoupling A N)) := + out.pmap (fun s hs => + ⟨s,s.val.2,Option.some.inj ((rejectionSeed_backup A N f s (ho.symm.trans hs)).symm.trans + (successful_agrees s))⟩) (fun _ h => h) + +theorem cacheRejection_seed (N : ℕ) (f : Fin N → Fin (2^k)) + (out : Option (SuccessfulSeed (firstAcceptCoupling A N))) + (ho : out = rejectionSeed A N f) : + (cacheRejection A N f out ho).map Accepted.seed = out := by + cases out <;> rfl + +variable (evaluate : Fin (2^k) → (Bool × ℕ) × ℕ) + (he : ∀ a, (evaluate a).1.1 = true ↔ A a) + +def rejectionRun (stream : ℕ → Fin (2^w)) (modulus : ℕ) (hm : modulus = 2^k) + (N cursor : ℕ) : Result (firstAcceptCoupling A N) := + let r := WordSeedRejectionExecution.run A evaluate he stream modulus hm N cursor + ⟨cacheRejection A N (fun i => ExactWordDraw.low w k (stream (cursor+i.val))) + r.seed (WordSeedRejectionExecution.run_seed A evaluate he stream modulus hm N cursor), + r.cursor,r.work+2,r.cells+8,N+8⟩ + +def rejection (hk : k ≤ w) (modulus : ℕ) (hm : modulus = 2^k) (N : ℕ) : + Execution (WordSeedRealization.rejection w k hk N A) where + run stream cursor := rejectionRun A evaluate he stream modulus hm N cursor + value stream cursor := by + dsimp only [rejectionRun] + rw [cacheRejection_seed] + exact WordSeedRejectionExecution.program_value A evaluate he hk stream modulus hm N cursor + +theorem rejection_bounded (hk : k ≤ w) (modulus : ℕ) (hm : modulus = 2^k) + (N K H : ℕ) (hK : ∀ a, (evaluate a).1.2 ≤ K) (hH : ∀ a, (evaluate a).2 ≤ H) : + (rejection A evaluate he hk modulus hm N).Bounded + (N*(K+11)+11) (2*N+H+64) (N+8) := by + intro stream cursor + have hw := WordSeedRejectionExecution.run_work A evaluate he stream modulus hm K N cursor hK + have hc := WordSeedRejectionExecution.run_cells A evaluate he stream modulus hm H N cursor hH + change _+2 ≤ _ ∧ _+8 ≤ _ ∧ N+8 ≤ N+8 + exact ⟨by omega,by omega,le_rfl⟩ + +end LowSpaceSubsetSum.WordSeedMeasured + +end + +end OAI diff --git a/lean/OAI/Combinatorics/LowSpaceSubsetSum/Word/WordSeedMeasuredTransport.lean b/lean/OAI/Combinatorics/LowSpaceSubsetSum/Word/WordSeedMeasuredTransport.lean new file mode 100644 index 0000000000000000000000000000000000000000..745526213f9263ef68392e92ed0bfa021d071165 --- /dev/null +++ b/lean/OAI/Combinatorics/LowSpaceSubsetSum/Word/WordSeedMeasuredTransport.lean @@ -0,0 +1,87 @@ +import OAI.Combinatorics.LowSpaceSubsetSum.Word.WordSeedMeasuredProduct +import OAI.Combinatorics.LowSpaceSubsetSum.Word.WordSeedPrimitives + +namespace OAI + +/-! # Proof-only transport for the conditional seed programs + +The source sampler uses dependent decidable recursors. These lemmas expose +which conditional program is selected, preserving its probability law. +-/ + +noncomputable section +namespace LowSpaceSubsetSum.WordSeedMeasured + +open WordSeedRealization + +private theorem rec_heq_pos {p : Prop} (h : p) {C : Decidable p → Sort*} + (f : ∀ h : ¬p,C (.isFalse h)) (g : ∀ h : p,C (.isTrue h)) (d : Decidable p) : + HEq (@Decidable.rec p C f g d) (g h) := by + cases d with + | isFalse hh => exact False.elim (hh h) + | isTrue hh => rfl + +private theorem rec_heq_neg {p : Prop} (h : ¬p) {C : Decidable p → Sort*} + (f : ∀ h : ¬p,C (.isFalse h)) (g : ∀ h : p,C (.isTrue h)) (d : Decidable p) : + HEq (@Decidable.rec p C f g d) (f h) := by + cases d with + | isFalse hh => rfl + | isTrue hh => exact False.elim (h hh) + +def transportSampler {w N : ℕ} {α : Type} [Fintype α] {S T : SamplerCoupling α} + {X : Realization w N S} {Y : Realization w N T} (hS : T = S) + (hX : HEq Y X) (E : Execution X) : Execution Y := by + subst T + cases eq_of_heq hX + exact E + +theorem transportSampler_bounded {w N : ℕ} {α : Type} [Fintype α] + {S T : SamplerCoupling α} {X : Realization w N S} {Y : Realization w N T} + (hS : T = S) (hX : HEq Y X) (E : Execution X) (W C R : ℕ) + (hE : E.Bounded W C R) : (transportSampler hS hX E).Bounded W C R := by + subst T + cases eq_of_heq hX + exact hE + +theorem bounded_mono {w N : ℕ} {α : Type} [Fintype α] {S : SamplerCoupling α} + {X : Realization w N S} (E : Execution X) {W C R V D Q : ℕ} + (h : E.Bounded W C R) (hW : W ≤ V) (hC : C ≤ D) (hR : R ≤ Q) : + E.Bounded V D Q := fun stream cursor => + ⟨(h stream cursor).1.trans hW,(h stream cursor).2.1.trans hC, + (h stream cursor).2.2.trans hR⟩ + +theorem source_fin_pos (w n D : ℕ) [NeZero D] (hw : Nat.clog 2 D ≤ w) (h : 1 < D) : + HEq (WordSeedRealization.fin w n D hw) (WordSeedRealization.range w n D h hw) := by + unfold WordSeedRealization.fin + dsimp only [id_eq] + exact (rec_heq_pos h _ _ _).trans (cast_heq _ _) + +theorem source_fin_neg (w n D : ℕ) [NeZero D] (hw : Nat.clog 2 D ≤ w) (h : ¬1 < D) : + HEq (WordSeedRealization.fin w n D hw) + (WordSeedRealization.enlarge (WordSeedRealization.pure (w := w) + (⟨0,Nat.pos_of_ne_zero (NeZero.ne D)⟩ : Fin D)) (Nat.zero_le (n^3))) := by + unfold WordSeedRealization.fin + dsimp only [id_eq] + exact (rec_heq_neg h _ _ _).trans (cast_heq _ _) + +theorem source_factor_small (w n ell : ℕ) (hw : ell ≤ w) (h : ell < 4) : + HEq (WordSeedRealization.factor w n ell hw) + (WordSeedRealization.enlarge (WordSeedRealization.map + (WordSeedRealization.pure (w := w) ()) (factorOneEquiv h)) (Nat.zero_le (n^3))) := by + unfold WordSeedRealization.factor + dsimp only [id_eq] + exact (rec_heq_pos h _ _ _).trans (cast_heq _ _) + +theorem source_factor_large (w n ell : ℕ) (hw : ell ≤ w) (h : ¬ell < 4) : + HEq (WordSeedRealization.factor w n ell hw) + (WordSeedRealization.map (WordSeedRealization.prime w n ell (by omega) hw) + (factorPrimeEquiv (by omega))) := by + unfold WordSeedRealization.factor + dsimp only [id_eq] + exact (rec_heq_neg h _ _ _).trans (cast_heq _ _) + +end LowSpaceSubsetSum.WordSeedMeasured + +end + +end OAI diff --git a/lean/OAI/Combinatorics/LowSpaceSubsetSum/Word/WordSeedModulusExecution.lean b/lean/OAI/Combinatorics/LowSpaceSubsetSum/Word/WordSeedModulusExecution.lean new file mode 100644 index 0000000000000000000000000000000000000000..6111315bc289d176c49df4b6dfb598b9e3d78f41 --- /dev/null +++ b/lean/OAI/Combinatorics/LowSpaceSubsetSum/Word/WordSeedModulusExecution.lean @@ -0,0 +1,75 @@ +import Mathlib.Data.Nat.Log + +namespace OAI + +/-! # Computing a rejection range width and its cached modulus + +A doubling cursor starts at one and stops at the first power of two at +least the requested range size. The width and modulus are computed together. +-/ + +namespace LowSpaceSubsetSum.WordSeedModulusExecution + +structure Result where + width : ℕ + modulus : ℕ + work : ℕ + +def loop (D : ℕ) : ℕ → ℕ → ℕ → ℕ → Result + | 0, width, modulus, work => ⟨width,modulus,work+1⟩ + | fuel+1, width, modulus, work => + if modulus < D then loop D fuel (width+1) (2*modulus) (work+5) + else ⟨width,modulus,work+1⟩ + +theorem loop_value (D fuel width modulus work : ℕ) + (hm : modulus = 2^width) (hw : width ≤ Nat.clog 2 D) + (hf : Nat.clog 2 D ≤ width+fuel) : + loop D fuel width modulus work = + ⟨Nat.clog 2 D,2^Nat.clog 2 D,work+5*(Nat.clog 2 D-width)+1⟩ := by + induction fuel generalizing width modulus work with + | zero => + have he : width = Nat.clog 2 D := by omega + subst width + subst modulus + simp only [loop,Nat.sub_self,Nat.mul_zero,Nat.add_zero] + | succ fuel ih => + change (if modulus < D then loop D fuel (width+1) (2*modulus) (work+5) + else ⟨width,modulus,work+1⟩) = _ + split + next h => + have hlt : width < Nat.clog 2 D := by + exact (Nat.lt_clog_iff_pow_lt (by decide : 1 < 2)).mpr (hm ▸ h) + have hm' : 2*modulus = 2^(width+1) := by rw [hm,Nat.pow_succ]; omega + rw [ih _ _ _ hm' (by omega) (by omega)] + congr 1 + omega + next h => + have hge : Nat.clog 2 D ≤ width := by + apply Nat.clog_le_of_le_pow + omega + have he : width = Nat.clog 2 D := by omega + subst width + subst modulus + simp only [Nat.sub_self,Nat.mul_zero,Nat.add_zero] + +def run (D : ℕ) : Result := loop D D 0 1 0 + +theorem run_value (D : ℕ) : run D = ⟨Nat.clog 2 D,2^Nat.clog 2 D,5*Nat.clog 2 D+1⟩ := by + have hf : Nat.clog 2 D ≤ D := Nat.clog_le_of_le_pow (Nat.lt_two_pow_self.le) + simpa only [run,Nat.pow_zero,Nat.zero_add,Nat.sub_zero] using + loop_value D D 0 1 0 (by simp) (Nat.zero_le _) (by omega) + +theorem run_width (D : ℕ) : (run D).width = Nat.clog 2 D := by rw [run_value] + +theorem run_modulus (D : ℕ) : (run D).modulus = 2^Nat.clog 2 D := by rw [run_value] + +theorem run_work (D : ℕ) : (run D).work = 5*Nat.clog 2 D+1 := by rw [run_value] + +theorem run_modulus_fits (D w : ℕ) (hw : Nat.clog 2 D < w) : + (run D).modulus < 2^w := by + rw [run_modulus] + exact Nat.pow_lt_pow_right (by decide : 1 < 2) hw + +end LowSpaceSubsetSum.WordSeedModulusExecution + +end OAI diff --git a/lean/OAI/Combinatorics/LowSpaceSubsetSum/Word/WordSeedPermutationExecution.lean b/lean/OAI/Combinatorics/LowSpaceSubsetSum/Word/WordSeedPermutationExecution.lean new file mode 100644 index 0000000000000000000000000000000000000000..ec4adb89b36a8d70715a9edda862da5234373fbe --- /dev/null +++ b/lean/OAI/Combinatorics/LowSpaceSubsetSum/Word/WordSeedPermutationExecution.lean @@ -0,0 +1,73 @@ +import OAI.Combinatorics.LowSpaceSubsetSum.Word.WordSeedRangeInitialization + +namespace OAI + +/-! # Measured permutation seed generation + +Each range call computes its modulus, draws and retains the actual candidate +tuple, and caches its accepted digit. Permutation values are composition +closures; their application or array materialization remains a separate +measured operation, as in `PermutationArray`. +-/ + +noncomputable section +namespace LowSpaceSubsetSum.WordSeedMeasured + +def permutation (w n : ℕ) : (k : ℕ) → (hw : Nat.clog 2 k ≤ w) → + Execution (WordSeedRealization.permutation w n k hw) + | 0, _ => by + exact reprogram (pure (w := w) (Equiv.refl (Fin 0))) (by + unfold WordSeedRealization.permutation + exact mpr_program (Nat.zero_mul (n^3)) _) + | k+1, hw => by + have hk : Nat.clog 2 k ≤ w := + (Nat.clog_mono_right 2 (by omega : k ≤ k+1)).trans hw + exact reprogram + (map (prod (fin w n (k+1) hw) (permutation w n k hk)) + Equiv.Perm.decomposeFin.symm + (fun p => ((Equiv.Perm.decomposeFin.symm p,6),8)) (fun _ => rfl)) (by + conv_lhs => rw [WordSeedRealization.permutation] + exact mpr_program (w := w) (α := Equiv.Perm (Fin (k+1))) + (by simp only [Nat.add_mul,Nat.one_mul,Nat.add_comm] : + (k+1)*n^3 = n^3+k*n^3) _) + +theorem permutation_bounded (w n : ℕ) : ∀ (k : ℕ) (hw : Nat.clog 2 k ≤ w), + (permutation w n k hw).Bounded + (k*(13*n^3+5*k+64)+1) ((k+1)*(2*n^3+256)) ((k+1)*(n^3+64)) := by + intro k + induction k with + | zero => + intro hw stream cursor + change 1 ≤ _ ∧ 4 ≤ _ ∧ 4 ≤ _ + constructor + · omega + · constructor <;> omega + | succ k ih => + intro hw + have hk : Nat.clog 2 k ≤ w := + (Nat.clog_mono_right 2 (by omega : k ≤ k+1)).trans hw + have ht := ih hk + have hf := fin_bounded w n (k+1) hw + have hp := prod_bounded (fin w n (k+1) hw) (permutation w n k hk) + _ _ _ _ _ _ hf ht + have hm := map_bounded _ Equiv.Perm.decomposeFin.symm + (fun p => ((Equiv.Perm.decomposeFin.symm p,6),8)) (fun _ => rfl) + _ _ _ 6 8 hp (fun _ => le_rfl) (fun _ => le_rfl) + have hclog : Nat.clog 2 (k+1) ≤ k+1 := + Nat.clog_le_of_le_pow Nat.lt_two_pow_self.le + intro stream cursor + have h := hm stream cursor + change _ ≤ (k+1)*(13*n^3+5*(k+1)+64)+1 ∧ + _ ≤ (k+1+1)*(2*n^3+256) ∧ _ ≤ (k+1+1)*(n^3+64) + refine ⟨h.1.trans (by nlinarith),h.2.1.trans ?_,h.2.2.trans (by nlinarith)⟩ + apply max_le + · apply max_le + · apply max_le <;> nlinarith + · nlinarith + · nlinarith + +end LowSpaceSubsetSum.WordSeedMeasured + +end + +end OAI diff --git a/lean/OAI/Combinatorics/LowSpaceSubsetSum/Word/WordSeedPowerExecution.lean b/lean/OAI/Combinatorics/LowSpaceSubsetSum/Word/WordSeedPowerExecution.lean new file mode 100644 index 0000000000000000000000000000000000000000..caa551c59e097b4c7fe89bb7eec6469bf4756b9e --- /dev/null +++ b/lean/OAI/Combinatorics/LowSpaceSubsetSum/Word/WordSeedPowerExecution.lean @@ -0,0 +1,38 @@ +import Mathlib.Data.Nat.Log + +namespace OAI + +/-! # Constant-state power-of-two initialization + +The same executed doubling cursor supplies both prime candidate moduli +and trial-division limits. +-/ + +namespace LowSpaceSubsetSum.WordSeedPowerExecution + +def loop : ℕ → ℕ → ℕ → ℕ × ℕ + | 0, value, work => (value,work+1) + | fuel+1, value, work => loop fuel (2*value) (work+3) + +theorem loop_value (fuel value work : ℕ) : + loop fuel value work = (value*2^fuel,work+3*fuel+1) := by + induction fuel generalizing value work with + | zero => simp only [loop,Nat.pow_zero,Nat.mul_one,Nat.mul_zero,Nat.add_zero] + | succ fuel ih => + change loop fuel (2*value) (work+3) = _ + rw [ih,Nat.pow_succ] + apply Prod.ext + · simp only [Nat.mul_assoc,Nat.mul_comm] + · omega + +def run (width : ℕ) := loop width 1 0 + +theorem run_value (width : ℕ) : (run width).1 = 2^width := by + simp only [run,loop_value,Nat.one_mul] + +theorem run_work (width : ℕ) : (run width).2 = 3*width+1 := by + simp only [run,loop_value,Nat.zero_add] + +end LowSpaceSubsetSum.WordSeedPowerExecution + +end OAI diff --git a/lean/OAI/Combinatorics/LowSpaceSubsetSum/Word/WordSeedPreparedBind.lean b/lean/OAI/Combinatorics/LowSpaceSubsetSum/Word/WordSeedPreparedBind.lean new file mode 100644 index 0000000000000000000000000000000000000000..a8701d4a35f50bececcb3a058cf8f601fac70ef5 --- /dev/null +++ b/lean/OAI/Combinatorics/LowSpaceSubsetSum/Word/WordSeedPreparedBind.lean @@ -0,0 +1,150 @@ +import OAI.Combinatorics.LowSpaceSubsetSum.Word.WordSeedMeasured + +namespace OAI + +/-! # Dependent generation with access to the preceding stored seed + +This variant permits the next stage to run the already counted layout or +parameter preparation on the actual preceding seed. Its charge is part of +that stage's Execution, rather than an implicit evaluation of ideal data. +-/ + +noncomputable section +namespace LowSpaceSubsetSum.WordSeedMeasured + +open WordSeedRealization + +variable {w N M : ℕ} {α : Type} [Fintype α] + +def firstAccepted {S : SamplerCoupling α} (B : α → Type) [∀ a, Fintype (B a)] + (T : ∀ a, SamplerCoupling (B a)) (a : Accepted (S.bind B T)) : Accepted S where + seed := ⟨a.seed.val.1,by + rcases S.agrees a.seed.val.1 with hn | hs + · have h := WordSeedRealization.successful_agrees a.seed + simp only [SamplerCoupling.bind,hn,↓reduceIte] at h + contradiction + · exact ⟨_,hs⟩⟩ + value := a.value.1 + correct := congrArg Sigma.fst a.correct + +def bindSeedRun {S : SamplerCoupling α} {X : Realization w N S} (E : Execution X) + (B : α → Type) [∀ a, Fintype (B a)] (T : ∀ a, SamplerCoupling (B a)) + (Y : ∀ a, Realization w M (T a)) (F : ∀ a : Accepted S, Execution (Y a.value)) + (stream : ℕ → Fin (2^w)) (cursor : ℕ) : Result (S.bind B T) := + let r := E.run stream cursor + match r.accepted with + | none => ⟨none,r.cursor,r.work+1,r.cells,r.retained⟩ + | some a => + let t := (F a).run stream r.cursor + ⟨t.accepted.map (pairAccepted B T a),t.cursor,r.work+t.work+2, + max r.cells (r.retained+t.cells+8),r.retained+t.retained+8⟩ + +def bindSeed {S : SamplerCoupling α} {X : Realization w N S} (E : Execution X) + (B : α → Type) [∀ a, Fintype (B a)] (T : ∀ a, SamplerCoupling (B a)) + (Y : ∀ a, Realization w M (T a)) (F : ∀ a : Accepted S, Execution (Y a.value)) : + Execution (WordSeedRealization.bind X B T Y) where + run := bindSeedRun E B T Y F + value stream cursor := by + have hr := E.value stream cursor + rw [WordSeedRealization.bind,WordSeedRejectionExecution.program_run_bind,←hr] + cases ha : (E.run stream cursor).accepted with + | none => simp only [bindSeedRun,ha,Option.map_none,continuation,WordProgram.run] + | some a => + rcases a with ⟨s,a,ha'⟩ + subst a + have ht := (F ⟨s,S.ideal s.val,rfl⟩).value stream (E.run stream cursor).cursor + simp only [bindSeedRun,ha,Option.map_some,continuation, + WordSeedRejectionExecution.program_run_map,←ht] + cases hb : ((F ⟨s,S.ideal s.val,rfl⟩).run stream + (E.run stream cursor).cursor).accepted <;> + simp only [Option.map_none,Option.map_some,pairAccepted] + +theorem bindSeed_bounded {S : SamplerCoupling α} {X : Realization w N S} (E : Execution X) + (B : α → Type) [∀ a, Fintype (B a)] (T : ∀ a, SamplerCoupling (B a)) + (Y : ∀ a, Realization w M (T a)) (F : ∀ a : Accepted S, Execution (Y a.value)) + (W C R V D Q : ℕ) (hE : E.Bounded W C R) + (hF : ∀ a, (F a).Bounded V D Q) : + (bindSeed E B T Y F).Bounded (W+V+2) (max C (R+D+8)) (R+Q+8) := by + intro stream cursor + have he := hE stream cursor + cases ha : (E.run stream cursor).accepted with + | none => + simp only [bindSeed,bindSeedRun,ha] + exact ⟨by omega,he.2.1.trans (le_max_left _ _),by omega⟩ + | some a => + have hf := hF a stream (E.run stream cursor).cursor + simp only [bindSeed,bindSeedRun,ha] + exact ⟨by omega,max_le_max he.2.1 (by omega),by omega⟩ + +def prepareThen {P : Type} {S : SamplerCoupling α} {X : Realization w N S} + (prepare : Unit → (P × ℕ) × ℕ) (next : P → Execution X) : Execution X where + run stream cursor := + let prepared := prepare () + let out := (next prepared.1.1).run stream cursor + ⟨out.accepted,out.cursor,prepared.1.2+out.work+2, + max prepared.2 (prepared.2+out.cells+8),prepared.2+out.retained+8⟩ + value stream cursor := (next (prepare ()).1.1).value stream cursor + +theorem prepareThen_bounded {P : Type} {S : SamplerCoupling α} {X : Realization w N S} + (prepare : Unit → (P × ℕ) × ℕ) (next : P → Execution X) + (W C V D Q : ℕ) (hW : (prepare ()).1.2 ≤ W) (hC : (prepare ()).2 ≤ C) + (hNext : ∀ p, (next p).Bounded V D Q) : + (prepareThen prepare next).Bounded (W+V+2) (C+D+8) (C+Q+8) := by + intro stream cursor + have h := hNext (prepare ()).1.1 stream cursor + change _+_+2 ≤ _ ∧ max _ (_+_+8) ≤ _ ∧ _+_+8 ≤ _ + exact ⟨by omega,max_le (by omega) (by omega),by omega⟩ + +/-- The concrete cached value is the successful sampler output. -/ +theorem accepted_source {S : SamplerCoupling α} (a : Accepted S) : + S.bounded a.seed.val = some a.value := + (WordSeedRealization.successful_agrees a.seed).trans (congrArg some a.correct.symm) + +def mapStoredRun {β : Type} [Fintype β] {S : SamplerCoupling α} + {X : Realization w N S} (E : Execution X) (f : α → β) + (compute : Accepted S → (β × ℕ) × ℕ) + (hc : ∀ a, (compute a).1.1 = f a.value) + (stream : ℕ → Fin (2^w)) (cursor : ℕ) : Result (S.map f) := + let r := E.run stream cursor + match r.accepted with + | none => ⟨none,r.cursor,r.work+1,r.cells,r.retained⟩ + | some a => + let b := compute a + ⟨some (mapAccepted f a b.1.1 (hc a)),r.cursor, + r.work+b.1.2+2,max r.cells (r.retained+b.2+8),r.retained+b.2+8⟩ + +def mapStored {β : Type} [Fintype β] {S : SamplerCoupling α} + {X : Realization w N S} (E : Execution X) (f : α → β) + (compute : Accepted S → (β × ℕ) × ℕ) + (hc : ∀ a, (compute a).1.1 = f a.value) : + Execution (WordSeedRealization.map X f) where + run := mapStoredRun E f compute hc + value stream cursor := by + have h := E.value stream cursor + rw [WordSeedRealization.map,WordSeedRejectionExecution.program_run_map,←h] + cases ha : (E.run stream cursor).accepted <;> + simp only [mapStoredRun,ha,Option.map_none,Option.map_some,mapAccepted] + +theorem mapStored_bounded {β : Type} [Fintype β] {S : SamplerCoupling α} + {X : Realization w N S} (E : Execution X) (f : α → β) + (compute : Accepted S → (β × ℕ) × ℕ) (hc : ∀ a, (compute a).1.1 = f a.value) + (W C R F H : ℕ) (hE : E.Bounded W C R) + (hF : ∀ a, (compute a).1.2 ≤ F) (hH : ∀ a, (compute a).2 ≤ H) : + (mapStored E f compute hc).Bounded (W+F+2) (max C (R+H+8)) (R+H+8) := by + intro stream cursor + have hr := hE stream cursor + dsimp only [mapStored,mapStoredRun] + split + · dsimp only + exact ⟨by omega,hr.2.1.trans (le_max_left _ _),by omega⟩ + next a ha => + dsimp only + have hf := hF a + have hh := hH a + exact ⟨by omega,max_le_max hr.2.1 (by omega),by omega⟩ + +end LowSpaceSubsetSum.WordSeedMeasured + +end + +end OAI diff --git a/lean/OAI/Combinatorics/LowSpaceSubsetSum/Word/WordSeedPreparedBounds.lean b/lean/OAI/Combinatorics/LowSpaceSubsetSum/Word/WordSeedPreparedBounds.lean new file mode 100644 index 0000000000000000000000000000000000000000..6a84181c91bb2c548299eeee2a0ccaf8998da087 --- /dev/null +++ b/lean/OAI/Combinatorics/LowSpaceSubsetSum/Word/WordSeedPreparedBounds.lean @@ -0,0 +1,166 @@ +import OAI.Combinatorics.LowSpaceSubsetSum.Word.WordSeedPreparedPrimes +import OAI.Combinatorics.LowSpaceSubsetSum.Word.WordSeedScalarBounds +import OAI.Combinatorics.LowSpaceSubsetSum.Word.WordSamplingBounds + +namespace OAI + +/-! # Work and live storage of the counted prime preparation stages -/ + +noncomputable section +namespace LowSpaceSubsetSum.WordSeedMeasured + +variable {n : ℕ} + +private theorem scale_power (I : Instance n) (hn : 10000 ≤ n) (j k : ℕ) (hjk : j ≤ k) : + inputScale I^j ≤ inputScale I^k := + Nat.pow_le_pow_right (by unfold inputScale; omega) hjk + +private theorem scale_positive (I : Instance n) (k : ℕ) : 1 ≤ inputScale I^k := + Nat.one_le_pow _ _ (by unfold inputScale; omega) + +theorem nestedAtWidths_bounded (I : Instance n) (hn : 10000 ≤ n) + (R : RepresentationSetup n) (z : RepresentationSetup.Layout n) + (x y q : ℕ) (hx : x = R.factorExponents z 0) + (hy : y = R.factorExponents z 1) (hq : q = R.factorExponents z 2) + (w : ℕ) (hw : n ≤ w) : + (nestedAtWidths R z x y q hx hy hq w hw).Bounded + (4*inputScale I^5*2^((n+1)/2)) (4*inputScale I^5) (4*inputScale I^5) := by + cases hx + cases hy + cases hq + have h := triplePrime_bounded w n (R.factorExponents z 0) (R.factorExponents z 1) + (R.factorExponents z 2) ((R.factorExponents_le_n z 0).trans hw) + ((R.factorExponents_le_n z 1).trans hw) ((R.factorExponents_le_n z 2).trans hw) + have h0 := WordSeedScalarBounds.factorWork_le I hn (R.factorExponents_le_n z 0) + have h1 := WordSeedScalarBounds.factorWork_le I hn (R.factorExponents_le_n z 1) + have h2 := WordSeedScalarBounds.factorWork_le I hn (R.factorExponents_le_n z 2) + have hs := (WordSeedScalarBounds.scalar_cells_le I hn).1 + have hu : 10000 ≤ inputScale I := by unfold inputScale; omega + have hp : inputScale I ≤ inputScale I^5 := by + simpa only [pow_one] using scale_power I hn 1 5 (by decide) + have hH := Nat.le_mul_of_pos_right (inputScale I^5) + (Nat.one_le_two_pow (n := (n+1)/2)) + apply bounded_mono _ h + · nlinarith only [h0,h1,h2,hu,hp,hH] + · omega + · omega + +theorem extraAtWidth_bounded (I : Instance n) (hn : 10000 ≤ n) + (R : RepresentationSetup n) (z : RepresentationSetup.Layout n) + (x : ℕ) (hx : x = R.extraPrimeParameter z) (w : ℕ) (hw : n ≤ w) : + (extraAtWidth R z x hx (by omega) w hw).Bounded + (inputScale I^5*2^((n+1)/2)) (inputScale I^5) (inputScale I^5) := by + cases hx + exact WordSeedScalarBounds.prime_bounded_scale I hn + (R.extraPrimeParameter_range z (by omega)).2 + (R.extraPrimeParameter_range z (by omega)).1 w + ((R.extraPrimeParameter_range z (by omega)).2.trans hw) + +private theorem preparation_work (I : Instance n) (hn : 10000 ≤ n) + (a : WordLayoutPreparation.Layout I) : + (WordLayoutPreparation.compute I a).1.2 ≤ inputScale I^7*2^((n+1)/2) := by + let u := inputScale I + let H := 2^((n+1)/2) + have hu : 10000 ≤ u := by unfold u inputScale; omega + have hnu : n+1 ≤ u := by unfold u inputScale; omega + have hH : 1 ≤ H := Nat.one_le_two_pow + have hm : 2^mixerSize n ≤ H := Nat.pow_le_pow_right (by decide) (by unfold mixerSize; omega) + have hw := WordLayoutPreparation.work I hn a + have hp : n*n^3+10*(n+1)^2+4*n+7 ≤ u^6 := by + have hn3 : n^3 ≤ u^3 := Nat.pow_le_pow_left (by omega) 3 + have hn2 : (n+1)^2 ≤ u^2 := Nat.pow_le_pow_left hnu 2 + have hn4 : n*n^3 ≤ u^4 := by + calc + _ ≤ u*u^3 := Nat.mul_le_mul (by omega) hn3 + _ = _ := by ring + have h24 : u^2 ≤ u^4 := scale_power I hn 2 4 (by decide) + have h14 : u ≤ u^4 := by simpa only [pow_one] using scale_power I hn 1 4 (by decide) + have h46 : 20*u^4 ≤ u^6 := by + have h20 : 20 ≤ u^2 := by nlinarith only [hu] + calc + _ ≤ u^2*u^4 := Nat.mul_le_mul_right _ h20 + _ = _ := by ring + nlinarith only [hn4,hn2,h24,h14,hnu,hu,h46] + have h67 : 2*u^6 ≤ u^7 := by + calc + _ ≤ u*u^6 := Nat.mul_le_mul_right _ (by omega) + _ = _ := by ring + have hm' := Nat.mul_le_mul_left (u^6) hm + have hp' := Nat.le_mul_of_pos_right (u^6) hH + have hlast := Nat.mul_le_mul_right H h67 + change (WordLayoutPreparation.compute I a).1.2 ≤ u^7*H + change (WordLayoutPreparation.compute I a).1.2 ≤ + n*n^3+10*(n+1)^2+4*n+7+u^6*2^mixerSize n at hw + nlinarith only [hw,hp,hm',hp',hlast] + +private theorem preparation_combine (u C H W D Q V : ℕ) (hu : 10000 ≤ u) + (hC : 1 ≤ C) (hH : 1 ≤ H) (hW : W ≤ u^7*H) (hD : D ≤ u^10*C+8) + (hQ : Q ≤ 4*u^5) (hV : V ≤ 4*u^5*H) : + W+V+2 ≤ u^8*H ∧ D+Q+8 ≤ 2*u^10*C := by + have h57 : u^5 ≤ u^7 := Nat.pow_le_pow_right (by omega) (by decide) + have h510 : u^5 ≤ u^10 := Nat.pow_le_pow_right (by omega) (by decide) + have h17 : u ≤ u^7 := by simpa only [pow_one] using Nat.pow_le_pow_right (by omega : 0 < u) (by decide : 1 ≤ 7) + have h110 : u ≤ u^10 := by simpa only [pow_one] using Nat.pow_le_pow_right (by omega : 0 < u) (by decide : 1 ≤ 10) + have hm := Nat.le_mul_of_pos_right (u^7) hH + have hc := Nat.le_mul_of_pos_right (u^10) hC + have hs : 6*u^7*H ≤ u^8*H := by + calc + _ ≤ u*u^7*H := Nat.mul_le_mul_right _ (Nat.mul_le_mul_right _ (by omega)) + _ = _ := by ring + have hf := Nat.mul_le_mul_right H h57 + constructor + · nlinarith only [hW,hV,hm,h17,hu,hs,hf] + · have h510' : 4*u^5+16 ≤ u^10 := by + have h59 : u^5 ≤ u^9 := Nat.pow_le_pow_right (by omega) (by decide) + have h19 : u ≤ u^9 := by simpa only [pow_one] using Nat.pow_le_pow_right (by omega : 0 < u) (by decide : 1 ≤ 9) + have hx : 5*u^9 ≤ u^10 := by + calc + _ ≤ u*u^9 := Nat.mul_le_mul_right _ (by omega) + _ = _ := by ring + omega + nlinarith only [hD,hQ,h510',hc] + +theorem nestedPrepared_bounded (I : Instance n) (hn : 10000 ≤ n) + (a : WordLayoutPreparation.Layout I) (w : ℕ) (hw : n ≤ w) : + (nestedPrepared I a w hw).Bounded (inputScale I^8*2^((n+1)/2)) + (2*inputScale I^10*(compressionDictionaryCapacity n+1)) + (2*inputScale I^10*(compressionDictionaryCapacity n+1)) := by + have hp := prepareThen_bounded (fun _ => WordLayoutPreparation.compute I a) + (fun d => nestedFromPrepared I a d w hw) _ _ _ _ _ + (preparation_work I hn a) (WordLayoutPreparation.cells I hn a) + (fun d => nestedAtWidths_bounded I hn _ a.value _ _ _ _ _ _ w hw) + have hc := preparation_combine (inputScale I) (compressionDictionaryCapacity n+1) + (2^((n+1)/2)) _ _ _ _ (by unfold inputScale; omega) (by omega) + Nat.one_le_two_pow (le_rfl) (le_rfl) (le_rfl) (le_rfl) + apply bounded_mono _ hp hc.1 + · simpa only [Nat.mul_assoc] using hc.2 + · simpa only [Nat.mul_assoc] using hc.2 + +theorem extraPrepared_bounded (I : Instance n) (hn : 10000 ≤ n) + (a : WordLayoutPreparation.Layout I) (w : ℕ) (hw : n ≤ w) : + (extraPrepared I a (by omega) w hw).Bounded (inputScale I^8*2^((n+1)/2)) + (2*inputScale I^10*(compressionDictionaryCapacity n+1)) + (2*inputScale I^10*(compressionDictionaryCapacity n+1)) := by + have he (d : WordLayoutPreparation.Prepared I a) : + (extraFromPrepared I a d (by omega) w hw).Bounded + (4*inputScale I^5*2^((n+1)/2)) (4*inputScale I^5) (4*inputScale I^5) := + bounded_mono _ (extraAtWidth_bounded I hn _ a.value _ (by simpa [RepresentationSetup.samplerPrimeWidths] using (WordLayoutPreparation.fields I a d).2 3) w hw) + (by + calc + _ ≤ 4*(inputScale I^5*2^((n+1)/2)) := Nat.le_mul_of_pos_left _ (by decide) + _ = _ := by ring) (by omega) (by omega) + have hp := prepareThen_bounded (fun _ => WordLayoutPreparation.compute I a) + (fun d => extraFromPrepared I a d (by omega) w hw) _ _ _ _ _ + (preparation_work I hn a) (WordLayoutPreparation.cells I hn a) he + have hc := preparation_combine (inputScale I) (compressionDictionaryCapacity n+1) + (2^((n+1)/2)) _ _ _ _ (by unfold inputScale; omega) (by omega) + Nat.one_le_two_pow (le_rfl) (le_rfl) (le_rfl) (le_rfl) + apply bounded_mono _ hp hc.1 + · simpa only [Nat.mul_assoc] using hc.2 + · simpa only [Nat.mul_assoc] using hc.2 + +end LowSpaceSubsetSum.WordSeedMeasured + +end + +end OAI diff --git a/lean/OAI/Combinatorics/LowSpaceSubsetSum/Word/WordSeedPreparedPrimes.lean b/lean/OAI/Combinatorics/LowSpaceSubsetSum/Word/WordSeedPreparedPrimes.lean new file mode 100644 index 0000000000000000000000000000000000000000..13ad0847e9374f16baa84464dda08ac6b26e9712 --- /dev/null +++ b/lean/OAI/Combinatorics/LowSpaceSubsetSum/Word/WordSeedPreparedPrimes.lean @@ -0,0 +1,88 @@ +import OAI.Combinatorics.LowSpaceSubsetSum.Word.WordLayoutPreparation +import OAI.Combinatorics.LowSpaceSubsetSum.Word.WordSeedFactorExecution +import OAI.Combinatorics.LowSpaceSubsetSum.Word.WordSeedHistory + +namespace OAI + +/-! # Prime draws from the counted layout preparation + +The widths passed to the sampler are stored integers returned by the mixer +counting procedure. Equalities with ideal parameters are type transports. +-/ + +noncomputable section +namespace LowSpaceSubsetSum.WordSeedMeasured + +variable {n : ℕ} + +private theorem nested_width (I : Instance n) (a : WordLayoutPreparation.Layout I) + (d : WordLayoutPreparation.Prepared I a) (i : Fin 3) : + d.val.parameters.widths[i.val] = + (canonicalRepresentationData I).zeroSetup.factorExponents a.value i := by + have h := (WordLayoutPreparation.fields I a d).2 + fin_cases i + · simpa [RepresentationSetup.samplerPrimeWidths] using h 0 + · simpa [RepresentationSetup.samplerPrimeWidths] using h 1 + · simpa [RepresentationSetup.samplerPrimeWidths] using h 2 + +def nestedAtWidths (R : RepresentationSetup n) (z : RepresentationSetup.Layout n) + (x y q : ℕ) (hx : x = R.factorExponents z 0) + (hy : y = R.factorExponents z 1) (hq : q = R.factorExponents z 2) + (w : ℕ) (hw : n ≤ w) : Execution (WordSeedRealization.nested R z w hw) := by + have bx : x ≤ w := (le_of_eq hx).trans ((R.factorExponents_le_n z 0).trans hw) + have by' : y ≤ w := (le_of_eq hy).trans ((R.factorExponents_le_n z 1).trans hw) + have bq : q ≤ w := (le_of_eq hq).trans ((R.factorExponents_le_n z 2).trans hw) + let E := triplePrime w n x y q bx by' bq + cases hx + cases hy + cases hq + exact E + +def nestedFromPrepared (I : Instance n) (a : WordLayoutPreparation.Layout I) + (d : WordLayoutPreparation.Prepared I a) (w : ℕ) (hw : n ≤ w) : + Execution (WordSeedRealization.nested (canonicalRepresentationData I).zeroSetup a.value w hw) := + nestedAtWidths _ a.value d.val.parameters.widths[0] d.val.parameters.widths[1] + d.val.parameters.widths[2] (nested_width I a d 0) (nested_width I a d 1) + (nested_width I a d 2) w hw + +def nestedPrepared (I : Instance n) (a : WordLayoutPreparation.Layout I) + (w : ℕ) (hw : n ≤ w) : + Execution (WordSeedRealization.nested (canonicalRepresentationData I).zeroSetup a.value w hw) := + prepareThen (fun _ => WordLayoutPreparation.compute I a) + (fun d => nestedFromPrepared I a d w hw) + +private theorem extra_width (I : Instance n) (a : WordLayoutPreparation.Layout I) + (d : WordLayoutPreparation.Prepared I a) : + d.val.parameters.widths[3] = + (canonicalRepresentationData I).zeroSetup.extraPrimeParameter a.value := by + simpa [RepresentationSetup.samplerPrimeWidths] using + (WordLayoutPreparation.fields I a d).2 3 + +def extraAtWidth (R : RepresentationSetup n) (z : RepresentationSetup.Layout n) + (x : ℕ) (hx : x = R.extraPrimeParameter z) (hn : 100 ≤ n) (w : ℕ) (hw : n ≤ w) : + Execution (WordSeedRealization.extraPrime R z hn w hw) := by + have hr := R.extraPrimeParameter_range z hn + have lo : 4 ≤ x := hr.1.trans (le_of_eq hx.symm) + have hi : x ≤ w := (le_of_eq hx).trans (hr.2.trans hw) + let E := primeInitialized w n x lo hi + cases hx + exact E + +def extraFromPrepared (I : Instance n) (a : WordLayoutPreparation.Layout I) + (d : WordLayoutPreparation.Prepared I a) (hn : 100 ≤ n) (w : ℕ) (hw : n ≤ w) : + Execution (WordSeedRealization.extraPrime (canonicalRepresentationData I).zeroSetup + a.value hn w hw) := + extraAtWidth _ a.value d.val.parameters.widths[3] (extra_width I a d) hn w hw + +def extraPrepared (I : Instance n) (a : WordLayoutPreparation.Layout I) + (hn : 100 ≤ n) (w : ℕ) (hw : n ≤ w) : + Execution (WordSeedRealization.extraPrime (canonicalRepresentationData I).zeroSetup + a.value hn w hw) := + prepareThen (fun _ => WordLayoutPreparation.compute I a) + (fun d => extraFromPrepared I a d hn w hw) + +end LowSpaceSubsetSum.WordSeedMeasured + +end + +end OAI diff --git a/lean/OAI/Combinatorics/LowSpaceSubsetSum/Word/WordSeedPrimeInitialization.lean b/lean/OAI/Combinatorics/LowSpaceSubsetSum/Word/WordSeedPrimeInitialization.lean new file mode 100644 index 0000000000000000000000000000000000000000..1326b198fa20436175284fe9ca71f54c2bf89e4a --- /dev/null +++ b/lean/OAI/Combinatorics/LowSpaceSubsetSum/Word/WordSeedPrimeInitialization.lean @@ -0,0 +1,36 @@ +import OAI.Combinatorics.LowSpaceSubsetSum.Word.WordSeedScalarExecution + +namespace OAI + +/-! # Executed prime-modulus initialization from its known width -/ + +noncomputable section +namespace LowSpaceSubsetSum.WordSeedMeasured + +def primeInitialized (w n ell : ℕ) (hell : 4 ≤ ell) (hw : ell ≤ w) : + Execution (WordSeedRealization.prime w n ell hell hw) where + run stream cursor := + let modulus := WordSeedPowerExecution.run ell + let r := (prime w n ell hell hw modulus.1 + (WordSeedPowerExecution.run_value ell)).run stream cursor + ⟨r.accepted,r.cursor,modulus.2+r.work+1,max 16 (r.cells+8),r.retained⟩ + value stream cursor := + (prime w n ell hell hw (WordSeedPowerExecution.run ell).1 + (WordSeedPowerExecution.run_value ell)).value stream cursor + +theorem primeInitialized_bounded (w n ell : ℕ) (hell : 4 ≤ ell) (hw : ell ≤ w) : + (primeInitialized w n ell hell hw).Bounded + (n^3*(12*2^((ell+1)/2)+12*(ell+1)+11)+3*ell+17) + (2*n^3+124) (n^3+18) := by + intro stream cursor + have h := prime_bounded w n ell hell hw (WordSeedPowerExecution.run ell).1 + (WordSeedPowerExecution.run_value ell) stream cursor + dsimp only [primeInitialized] + rw [WordSeedPowerExecution.run_work] + exact ⟨by omega,max_le (by omega) (by omega),h.2.2⟩ + +end LowSpaceSubsetSum.WordSeedMeasured + +end + +end OAI diff --git a/lean/OAI/Combinatorics/LowSpaceSubsetSum/Word/WordSeedPrimeTestExecution.lean b/lean/OAI/Combinatorics/LowSpaceSubsetSum/Word/WordSeedPrimeTestExecution.lean new file mode 100644 index 0000000000000000000000000000000000000000..44252e2c5cf6748b5d970030939c50a323836a98 --- /dev/null +++ b/lean/OAI/Combinatorics/LowSpaceSubsetSum/Word/WordSeedPrimeTestExecution.lean @@ -0,0 +1,41 @@ +import OAI.Combinatorics.LowSpaceSubsetSum.Word.WordSeedPowerExecution +import OAI.Combinatorics.LowSpaceSubsetSum.Storage.PrimeTestCells + +namespace OAI + +/-! # Prime testing with executed scalar initialization + +Both powers used by the test are produced by the doubling cursor. The +divisor scan consumes the computed limit directly and retains scalar state. +-/ + +namespace LowSpaceSubsetSum.WordSeedPrimeTestExecution + +def run (ell : ℕ) (p : Fin (2^ell)) : (Bool × ℕ) × ℕ := + let modulus := WordSeedPowerExecution.run ell + let limit := WordSeedPowerExecution.run ((ell+1)/2) + let r := PrimeTestCells.scan p.val (limit.1-1) 2 0 + ((decide (modulus.1 ≤ 4*ell*p.val) && (decide (2 ≤ p.val) && r.1.1.isNone), + 12*r.1.2+modulus.2+limit.2+7), max 16 (r.2+16)) + +theorem run_value (ell : ℕ) (p : Fin (2^ell)) : + (run ell p).1.1 = (SamplerAttempts.primeTest ell p).1 := by + rw [← PrimeTestCells.test_value] + simp only [run, WordSeedPowerExecution.run_value, PrimeTestCells.test, + PrimeTestCells.divisors] + +theorem run_work (ell : ℕ) (p : Fin (2^ell)) : + (run ell p).1.2 ≤ 12*2^((ell+1)/2)+12*(ell+1) := by + have h := SamplerAttempts.divisorsBits_tests ell p + rw [← PrimeTestCells.divisors_value] at h + dsimp only [PrimeTestCells.divisors] at h + simp only [run, WordSeedPowerExecution.run_value, WordSeedPowerExecution.run_work] + omega + +theorem run_cells (ell : ℕ) (p : Fin (2^ell)) : (run ell p).2 = 28 := by + simp only [run, PrimeTestCells.scan_cells] + rfl + +end LowSpaceSubsetSum.WordSeedPrimeTestExecution + +end OAI diff --git a/lean/OAI/Combinatorics/LowSpaceSubsetSum/Word/WordSeedPrimitives.lean b/lean/OAI/Combinatorics/LowSpaceSubsetSum/Word/WordSeedPrimitives.lean new file mode 100644 index 0000000000000000000000000000000000000000..06e91982ee3ce215baa1a2e6d5690196a1b2f9f9 --- /dev/null +++ b/lean/OAI/Combinatorics/LowSpaceSubsetSum/Word/WordSeedPrimitives.lean @@ -0,0 +1,78 @@ +import OAI.Combinatorics.LowSpaceSubsetSum.Word.WordSeedConstructors +import OAI.Combinatorics.LowSpaceSubsetSum.Word.WordPrimeRealization + +namespace OAI + +/-! # Successful sampler seeds for the concrete range and prime samplers -/ + +noncomputable section +namespace LowSpaceSubsetSum.WordSeedRealization + +def range (w n D : ℕ) (hD : 1 < D) (hw : Nat.clog 2 D ≤ w) : + Realization w (n^3) (rangeCoupling hD n) := by + let : Nonempty (Fin D) := ⟨⟨0,by omega⟩⟩ + let : Nonempty {x : Fin (2^Nat.clog 2 D) // rangeEligible D x} := + ⟨(rangeEligibleEquiv D).symm ⟨0,by omega⟩⟩ + exact map (rejection w (Nat.clog 2 D) hw (n^3) (rangeEligible D)) (rangeEligibleEquiv D) + +def fin (w n D : ℕ) [NeZero D] (hw : Nat.clog 2 D ≤ w) : + Realization w (n^3) (finCoupling n D) := by + unfold finCoupling + split + next h => exact range w n D h hw + next => exact enlarge (pure (⟨0,Nat.pos_of_ne_zero (NeZero.ne D)⟩ : Fin D)) (Nat.zero_le _) + +def permutation (w n : ℕ) : (k : ℕ) → Nat.clog 2 k ≤ w → + Realization w (k*n^3) (permutationCoupling n k) + | 0, _ => by + simpa only [Nat.zero_mul,permutationCoupling] using (pure (w := w) (Equiv.refl (Fin 0))) + | k+1, hw => by + have hk : Nat.clog 2 k ≤ w := + (Nat.clog_mono_right 2 (by omega : k ≤ k+1)).trans hw + have h := map (prod (fin w n (k+1) hw) (permutation w n k hk)) + Equiv.Perm.decomposeFin.symm + simpa only [permutationCoupling,Nat.add_mul,Nat.one_mul,Nat.add_comm] using h + +def finiteChoice (w n : ℕ) (A : Type) [Fintype A] [Nonempty A] + (hw : Nat.clog 2 (Fintype.card A) ≤ w) : + Realization w (n^3) (finiteChoiceCoupling n A) := + map (fin w n (Fintype.card A) hw) (Fintype.equivFin A).symm + +def finitePermutation (w n : ℕ) (A : Type) [Fintype A] [DecidableEq A] + (hw : Nat.clog 2 (Fintype.card A) ≤ w) : + Realization w (Fintype.card A*n^3) (finitePermutationCoupling n A) := + map (permutation w n (Fintype.card A) hw) (Equiv.permCongr (Fintype.equivFin A).symm) + +def prime (w n ell : ℕ) (hell : 4 ≤ ell) (hw : ell ≤ w) : + Realization w (n^3) (primeCoupling hell n) := by + let : Nonempty ↥(primeRange ell) := (primeRange_nonempty hell).to_subtype + let : Nonempty {x : Fin (2^ell) // primeEligible ell x} := + ⟨(primeEligibleEquiv hell).symm (Classical.choice inferInstance)⟩ + exact map (rejection w ell hw (n^3) (primeEligible ell)) (primeEligibleEquiv hell) + +def factor (w n ell : ℕ) (hw : ell ≤ w) : + Realization w (n^3) (factorCoupling n ell) := by + unfold factorCoupling + split + next h => exact enlarge (map (pure ()) (factorOneEquiv h)) (Nat.zero_le _) + next => exact map (prime w n ell (by omega) hw) (factorPrimeEquiv (by omega)) + +def triplePrime (w n a b c : ℕ) (ha : a ≤ w) (hb : b ≤ w) (hc : c ≤ w) : + Realization w (3*n^3) (triplePrimeCoupling n a b c) := by + have h := map (prod (prod (factor w n a ha) (factor w n b hb)) + (factor w n c hc)) (tripleFactorEquiv a b c) + simpa only [triplePrimeCoupling,show (n^3+n^3)+n^3 = 3*n^3 by omega] using h + +def compression {n : ℕ} (D : CompressionData n) (hn : 168000000 ≤ n) + (w : ℕ) (hp : Nat.clog 2 n ≤ w) (hq : compressionPrimeExponent n ≤ w) : + Realization w (n*n^3+n^3) (D.sampler hn) := + bind (permutation w n n hp) (fun _ => CompressionSetup.PrimeSpace n) + (fun _ => primeCoupling (by unfold compressionPrimeExponent; omega) n) + (fun _ => prime w n (compressionPrimeExponent n) + (by unfold compressionPrimeExponent; omega) hq) + +end LowSpaceSubsetSum.WordSeedRealization + +end + +end OAI diff --git a/lean/OAI/Combinatorics/LowSpaceSubsetSum/Word/WordSeedRangeInitialization.lean b/lean/OAI/Combinatorics/LowSpaceSubsetSum/Word/WordSeedRangeInitialization.lean new file mode 100644 index 0000000000000000000000000000000000000000..1a9d30b157ee08118be61000eb13442fc4e06e43 --- /dev/null +++ b/lean/OAI/Combinatorics/LowSpaceSubsetSum/Word/WordSeedRangeInitialization.lean @@ -0,0 +1,58 @@ +import OAI.Combinatorics.LowSpaceSubsetSum.Word.WordSeedScalarExecution +import OAI.Combinatorics.LowSpaceSubsetSum.Word.WordSeedModulusExecution +import OAI.Combinatorics.LowSpaceSubsetSum.Word.WordSeedMeasuredTransport + +namespace OAI + +/-! # Range draws with an executed modulus initialization -/ + +noncomputable section +namespace LowSpaceSubsetSum.WordSeedMeasured + +def rangeInitialized (w n D : ℕ) (hD : 1 < D) (hw : Nat.clog 2 D ≤ w) : + Execution (WordSeedRealization.range w n D hD hw) where + run stream cursor := + let scalar := WordSeedModulusExecution.run D + let r := (range w n D hD hw scalar.modulus + (WordSeedModulusExecution.run_modulus D)).run stream cursor + ⟨r.accepted,r.cursor,scalar.work+r.work+1,max 16 (r.cells+8),r.retained⟩ + value stream cursor := + (range w n D hD hw (WordSeedModulusExecution.run D).modulus + (WordSeedModulusExecution.run_modulus D)).value stream cursor + +theorem rangeInitialized_bounded (w n D : ℕ) (hD : 1 < D) (hw : Nat.clog 2 D ≤ w) : + (rangeInitialized w n D hD hw).Bounded + (13*n^3+5*Nat.clog 2 D+17) (2*n^3+104) (n^3+18) := by + intro stream cursor + have h := range_bounded w n D hD hw (WordSeedModulusExecution.run D).modulus + (WordSeedModulusExecution.run_modulus D) stream cursor + dsimp only [rangeInitialized] + rw [WordSeedModulusExecution.run_work] + exact ⟨by omega,max_le (by omega) (by omega),h.2.2⟩ + +def fin (w n D : ℕ) [NeZero D] (hw : Nat.clog 2 D ≤ w) : + Execution (WordSeedRealization.fin w n D hw) := + if h : 1 < D then + transportSampler (by simp only [finCoupling,dite_eq_left h]) + (source_fin_pos w n D hw h) (rangeInitialized w n D h hw) + else + transportSampler (by simp only [finCoupling,dite_eq_right h]) + (source_fin_neg w n D hw h) + (enlarge (pure (w := w) (⟨0,Nat.pos_of_ne_zero (NeZero.ne D)⟩ : Fin D)) + (Nat.zero_le (n^3))) + +theorem fin_bounded (w n D : ℕ) [NeZero D] (hw : Nat.clog 2 D ≤ w) : + (fin w n D hw).Bounded (13*n^3+5*Nat.clog 2 D+17) (2*n^3+104) (n^3+18) := by + unfold fin + split + next h => + exact transportSampler_bounded _ _ _ _ _ _ (rangeInitialized_bounded w n D h hw) + next h => + apply bounded_mono _ (transportSampler_bounded _ _ _ 1 4 4 + (enlarge_bounded _ _ _ _ _ (pure_bounded _))) <;> omega + +end LowSpaceSubsetSum.WordSeedMeasured + +end + +end OAI diff --git a/lean/OAI/Combinatorics/LowSpaceSubsetSum/Word/WordSeedRealization.lean b/lean/OAI/Combinatorics/LowSpaceSubsetSum/Word/WordSeedRealization.lean new file mode 100644 index 0000000000000000000000000000000000000000..737fa230e05deeb7bb01ad7d04a84e1694036145 --- /dev/null +++ b/lean/OAI/Combinatorics/LowSpaceSubsetSum/Word/WordSeedRealization.lean @@ -0,0 +1,188 @@ +import OAI.Combinatorics.LowSpaceSubsetSum.Word.WordRealization + +namespace OAI + +/-! # Fair-word programs returning successful bounded sampler seeds + +Failure returns no seed. Success retains the actual candidate tuples, so +the prepared algorithm can consume the bounded sampler seed type. Only the law +of the observed bounded output is asserted; unused backup coordinates +need not have their ideal distribution. +-/ + +noncomputable section +namespace LowSpaceSubsetSum.WordSeedRealization + +open WordProgram +attribute [local instance] Classical.propDecidable + +variable {w N M : ℕ} {α β : Type} [Fintype α] [Fintype β] + +def SuccessfulSeed (S : SamplerCoupling α) := + {s : S.Seed // ∃ a, S.bounded s = some a} + +def observe (S : SamplerCoupling α) (s : Option (SuccessfulSeed S)) : Option α := + s.bind (fun t => S.bounded t.val) + +theorem successful_agrees {S : SamplerCoupling α} (s : SuccessfulSeed S) : + S.bounded s.val = some (S.ideal s.val) := by + rcases S.agrees s.val with hf | hs + · obtain ⟨a,ha⟩ := s.property + rw [ha] at hf + contradiction + · exact hs + +theorem observe_some {S : SamplerCoupling α} (s : SuccessfulSeed S) : + observe S (some s) = some (S.ideal s.val) := successful_agrees s + +structure Realization (w N : ℕ) {α : Type} [Fintype α] (S : SamplerCoupling α) where + program : Program w (Option (SuccessfulSeed S)) + faithful : ∀ P, WordProgram.probability (WordProgram.map (observe S) program) P = + S.boundedLaw.probability P + bounded : WordProgram.Bounded program N + +theorem bind_assoc {A B C : Type} (p : Program w A) + (f : A → Program w B) (g : B → Program w C) : + WordProgram.bind (WordProgram.bind p f) g = + WordProgram.bind p (fun a => WordProgram.bind (f a) g) := by + induction p with + | pure a => rfl + | draw next ih => simp only [WordProgram.bind,ih] + +theorem map_bind {A B C : Type} (f : B → C) (p : Program w A) + (next : A → Program w B) : + WordProgram.map f (WordProgram.bind p next) = + WordProgram.bind p (fun a => WordProgram.map f (next a)) := by + exact bind_assoc p next (fun b => .pure (f b)) + +theorem bind_map {A B C : Type} (f : A → B) (p : Program w A) + (next : B → Program w C) : + WordProgram.bind (WordProgram.map f p) next = + WordProgram.bind p (fun a => next (f a)) := by + rw [WordProgram.map,bind_assoc] + rfl + +theorem map_map {A B C : Type} (g : B → C) (f : A → B) (p : Program w A) : + WordProgram.map g (WordProgram.map f p) = WordProgram.map (fun a => g (f a)) p := by + exact bind_map f p (fun b => .pure (g b)) + +def toRealization {S : SamplerCoupling α} (X : Realization w N S) : + WordRealization.Realization w N S where + program := WordProgram.map (observe S) X.program + faithful := X.faithful + bounded := by + simpa only [WordProgram.map,Nat.add_zero] using + WordProgram.bind_bound X.program N X.bounded + (fun s => .pure (observe S s)) 0 (fun _ => Bounded.pure _ 0) + +def pure (a : α) : Realization w 0 (SamplerCoupling.pure a) where + program := .pure (some ⟨(),a,rfl⟩) + faithful P := (WordRealization.pure (w := w) a).faithful P + bounded := Bounded.pure _ 0 + +def mapSeed {S : SamplerCoupling α} (f : α → β) (s : SuccessfulSeed S) : + SuccessfulSeed (S.map f) := by + refine ⟨s.val,?_⟩ + obtain ⟨a,ha⟩ := s.property + refine ⟨f a,?_⟩ + change (S.bounded s.val).map f = some (f a) + rw [ha] + rfl + +theorem observe_map {S : SamplerCoupling α} (f : α → β) (s : Option (SuccessfulSeed S)) : + observe (S.map f) (s.map (mapSeed f)) = (observe S s).map f := by + cases s <;> rfl + +def map {S : SamplerCoupling α} (X : Realization w N S) (f : α → β) : + Realization w N (S.map f) where + program := WordProgram.map (Option.map (mapSeed f)) X.program + faithful P := by + have he : WordProgram.map (observe (S.map f)) + (WordProgram.map (Option.map (mapSeed f)) X.program) = + WordProgram.map (Option.map f) (toRealization X).program := by + rw [map_map] + change _ = WordProgram.map (Option.map f) (WordProgram.map (observe S) X.program) + rw [map_map] + congr 1 + funext s + exact observe_map f s + rw [he] + exact (WordRealization.map (toRealization X) f).faithful P + bounded := by + simpa only [WordProgram.map,Nat.add_zero] using + WordProgram.bind_bound X.program N X.bounded + (fun s => .pure (s.map (mapSeed f))) 0 (fun _ => Bounded.pure _ 0) + +def pairSeed {S : SamplerCoupling α} (B : α → Type) [∀ a, Fintype (B a)] + (T : ∀ a, SamplerCoupling (B a)) (s : SuccessfulSeed S) + (t : SuccessfulSeed (T (S.ideal s.val))) : SuccessfulSeed (S.bind B T) := by + refine ⟨⟨s.val,t.val⟩,?_⟩ + obtain ⟨b,hb⟩ := t.property + refine ⟨⟨S.ideal s.val,b⟩,?_⟩ + simp only [SamplerCoupling.bind,successful_agrees s,Option.some_ne_none,↓reduceIte,hb, + Option.map_some] + +theorem observe_pair {S : SamplerCoupling α} (B : α → Type) [∀ a, Fintype (B a)] + (T : ∀ a, SamplerCoupling (B a)) (s : SuccessfulSeed S) + (t : Option (SuccessfulSeed (T (S.ideal s.val)))) : + observe (S.bind B T) (t.map (pairSeed B T s)) = + (observe (T (S.ideal s.val)) t).map (fun b => (⟨S.ideal s.val,b⟩ : Sigma B)) := by + cases t with + | none => rfl + | some t => + change (S.bind B T).bounded ⟨s.val,t.val⟩ = + ((T (S.ideal s.val)).bounded t.val).map _ + simp only [SamplerCoupling.bind,successful_agrees s,Option.some_ne_none,↓reduceIte] + +def continuation {S : SamplerCoupling α} (B : α → Type) [∀ a, Fintype (B a)] + (T : ∀ a, SamplerCoupling (B a)) (Y : ∀ a, Realization w M (T a)) : + Option (SuccessfulSeed S) → Program w (Option (SuccessfulSeed (S.bind B T))) + | none => .pure none + | some s => WordProgram.map (Option.map (pairSeed B T s)) (Y (S.ideal s.val)).program + +theorem continuation_observed {S : SamplerCoupling α} + (B : α → Type) [∀ a, Fintype (B a)] (T : ∀ a, SamplerCoupling (B a)) + (Y : ∀ a, Realization w M (T a)) (s : Option (SuccessfulSeed S)) : + WordProgram.map (observe (S.bind B T)) (continuation B T Y s) = + WordRealization.continuation B T (fun a => toRealization (Y a)) (observe S s) := by + cases s with + | none => rfl + | some s => + rw [observe_some] + simp only [continuation,WordRealization.continuation,toRealization,map_map] + congr 1 + funext t + exact observe_pair B T s t + +def bind {S : SamplerCoupling α} (X : Realization w N S) + (B : α → Type) [∀ a, Fintype (B a)] (T : ∀ a, SamplerCoupling (B a)) + (Y : ∀ a, Realization w M (T a)) : Realization w (N+M) (S.bind B T) where + program := WordProgram.bind X.program (continuation B T Y) + faithful P := by + have he : WordProgram.map (observe (S.bind B T)) + (WordProgram.bind X.program (continuation B T Y)) = + WordProgram.bind (toRealization X).program + (WordRealization.continuation B T (fun a => toRealization (Y a))) := by + rw [map_bind] + change _ = WordProgram.bind (WordProgram.map (observe S) X.program) _ + rw [bind_map] + congr 1 + funext s + exact continuation_observed B T Y s + rw [he] + exact (WordRealization.bind (toRealization X) B T (fun a => toRealization (Y a))).faithful P + bounded := by + apply WordProgram.bind_bound X.program N X.bounded _ M + intro s + cases s with + | none => exact Bounded.pure none M + | some s => + simpa only [continuation,WordProgram.map,Nat.add_zero] using + WordProgram.bind_bound (Y (S.ideal s.val)).program M (Y (S.ideal s.val)).bounded + (fun t => .pure (t.map (pairSeed B T s))) 0 (fun _ => Bounded.pure _ 0) + +end LowSpaceSubsetSum.WordSeedRealization + +end + +end OAI diff --git a/lean/OAI/Combinatorics/LowSpaceSubsetSum/Word/WordSeedRejectionExecution.lean b/lean/OAI/Combinatorics/LowSpaceSubsetSum/Word/WordSeedRejectionExecution.lean new file mode 100644 index 0000000000000000000000000000000000000000..c95a7d80c772ff2941b099f6510215294d44f3eb --- /dev/null +++ b/lean/OAI/Combinatorics/LowSpaceSubsetSum/Word/WordSeedRejectionExecution.lean @@ -0,0 +1,178 @@ +import OAI.Combinatorics.LowSpaceSubsetSum.Word.WordCandidateExecution +import OAI.Combinatorics.LowSpaceSubsetSum.Storage.SamplerVectorCells + +namespace OAI + +/-! # Counted rejection returning the successful sampler seed + +The full candidate buffer is produced once from the word stream and tested +by the tail rejection loop. The accepted value supplies the unused +backup coordinate. Generation work, evaluator work and peak storage are +explicit; no execution cost is assigned to arbitrary program continuations. +-/ + +namespace LowSpaceSubsetSum.WordSeedRejectionExecution + +open WordSeedRealization + +variable {w k : ℕ} + +theorem program_run_bind {α β : Type} (stream : ℕ → Fin (2^w)) + (p : WordProgram.Program w α) (next : α → WordProgram.Program w β) (cursor : ℕ) : + WordProgram.run stream (WordProgram.bind p next) cursor = + let r := WordProgram.run stream p cursor + WordProgram.run stream (next r.1) r.2 := by + induction p generalizing cursor with + | pure a => rfl + | draw branch ih => + simp only [WordProgram.bind,WordProgram.run] + exact ih _ _ + +theorem program_run_map {α β : Type} (stream : ℕ → Fin (2^w)) + (p : WordProgram.Program w α) (f : α → β) (cursor : ℕ) : + WordProgram.run stream (WordProgram.map f p) cursor = + let r := WordProgram.run stream p cursor + (f r.1,r.2) := by + exact program_run_bind stream p (fun a => .pure (f a)) cursor + +theorem tuple_run (stream : ℕ → Fin (2^w)) (N cursor : ℕ) : + WordProgram.run stream (WordTuple.sample N) cursor = + ((fun i : Fin N => stream (cursor+i.val)),cursor+N) := by + induction N generalizing cursor with + | zero => + apply Prod.ext + · funext i + exact Fin.elim0 i + · rfl + | succ N ih => + simp only [WordTuple.sample,WordProgram.run,program_run_map,ih] + apply Prod.ext + · funext i + refine Fin.cases ?_ (fun j => ?_) i + · simp only [Fin.cons_zero,Fin.val_zero,Nat.add_zero] + · simp only [Fin.cons_succ,Fin.val_succ] + congr 1 + omega + · omega + +variable (A : Fin (2^k) → Prop) [DecidablePred A] + [Nonempty {a : Fin (2^k) // A a}] + +def attach (N : ℕ) (f : Fin N → Fin (2^k)) (o : Option {a : Fin (2^k) // A a}) + (ho : o = firstAcceptSubtype A N f) : + Option (SuccessfulSeed (firstAcceptCoupling A N)) := + match o with + | none => none + | some a => some ⟨(f,a),a,ho.symm⟩ + +theorem attach_eq (N : ℕ) (f : Fin N → Fin (2^k)) (o : Option {a : Fin (2^k) // A a}) + (ho : o = firstAcceptSubtype A N f) : + attach A N f o ho = rejectionSeed A N f := by + cases o with + | none => + dsimp only [attach] + unfold rejectionSeed + split + · rfl + next a ha => + have h := ho.trans ha + contradiction + | some a => + dsimp only [attach] + unfold rejectionSeed + split + next hnone => + have h := ho.trans hnone + contradiction + next b hb => + have h : a = b := Option.some.inj (ho.trans hb) + subst b + rfl + +variable (evaluate : Fin (2^k) → (Bool × ℕ) × ℕ) + (he : ∀ a, (evaluate a).1.1 = true ↔ A a) + +theorem tested_value (N : ℕ) (v : Vector (Fin (2^k)) N) : + (SamplerVectorCells.test A evaluate he 1 N v).1.value = + firstAcceptSubtype A N (SamplerVectorCells.candidates v) := by + let backup : {a : Fin (2^k) // A a} := Classical.choice inferInstance + exact (congrArg SamplerExecution.Trace.value + (SamplerVectorCells.test_value A evaluate he 1 N v backup)).trans + ((SamplerExecution.test A (fun a => (evaluate a).1) he N).value_eq + (SamplerVectorCells.candidates v,backup)) + +structure Trace (N : ℕ) where + seed : Option (SuccessfulSeed (firstAcceptCoupling A N)) + cursor : ℕ + testedCandidates : ℕ + testWork : ℕ + work : ℕ + cells : ℕ + +def run (stream : ℕ → Fin (2^w)) (modulus : ℕ) (hm : modulus = 2^k) + (N cursor : ℕ) : Trace A N := + let words := WordCandidateExecution.run stream modulus hm N cursor + let tested := SamplerVectorCells.test A evaluate he 1 N words.data + ⟨attach A N (SamplerVectorCells.candidates words.data) tested.1.value + (tested_value A evaluate he N words.data), + words.cursor,tested.1.reads,tested.1.tests, + words.work+6*tested.1.reads+tested.1.tests+8, + max words.cells (N+tested.2+16)⟩ + +theorem run_seed (stream : ℕ → Fin (2^w)) (modulus : ℕ) (hm : modulus = 2^k) + (N cursor : ℕ) : + (run A evaluate he stream modulus hm N cursor).seed = + rejectionSeed A N (fun i => ExactWordDraw.low w k (stream (cursor+i.val))) := by + unfold run + dsimp only + rw [attach_eq,WordCandidateExecution.run_data] + congr 1 + funext i + simp only [SamplerVectorCells.candidates,Vector.getElem_ofFn] + +theorem run_cursor (stream : ℕ → Fin (2^w)) (modulus : ℕ) (hm : modulus = 2^k) + (N cursor : ℕ) : (run A evaluate he stream modulus hm N cursor).cursor = cursor+N := + WordCandidateExecution.run_cursor stream modulus hm N cursor + +theorem program_value (hk : k ≤ w) (stream : ℕ → Fin (2^w)) + (modulus : ℕ) (hm : modulus = 2^k) (N cursor : ℕ) : + ((run A evaluate he stream modulus hm N cursor).seed, + (run A evaluate he stream modulus hm N cursor).cursor) = + WordProgram.run stream (rejection w k hk N A).program cursor := by + rw [run_seed,run_cursor] + change _ = WordProgram.run stream + (WordProgram.map (fun f => rejectionSeed A N + (fun i => ExactWordDraw.low w k (f i))) (WordTuple.sample N)) cursor + rw [program_run_map,tuple_run] + +theorem tested_bounds (K N : ℕ) (hK : ∀ a, (evaluate a).1.2 ≤ K) + (v : Vector (Fin (2^k)) N) : + (SamplerVectorCells.test A evaluate he 1 N v).1.reads ≤ N ∧ + (SamplerVectorCells.test A evaluate he 1 N v).1.tests ≤ N*K := by + let backup : {a : Fin (2^k) // A a} := Classical.choice inferInstance + rw [SamplerVectorCells.test_value A evaluate he 1 N v backup] + exact SamplerExecution.test_bounded A (fun a => (evaluate a).1) he N K hK + (SamplerVectorCells.candidates v,backup) + +theorem run_work (stream : ℕ → Fin (2^w)) (modulus : ℕ) (hm : modulus = 2^k) + (K N cursor : ℕ) (hK : ∀ a, (evaluate a).1.2 ≤ K) : + (run A evaluate he stream modulus hm N cursor).work ≤ N*(K+11)+9 := by + have h := tested_bounds A evaluate he K N hK + (WordCandidateExecution.run stream modulus hm N cursor).data + change (WordCandidateExecution.run stream modulus hm N cursor).work+_+_+8 ≤ _ + rw [WordCandidateExecution.run_work] + nlinarith only [h.1,h.2] + +theorem run_cells (stream : ℕ → Fin (2^w)) (modulus : ℕ) (hm : modulus = 2^k) + (H N cursor : ℕ) (hH : ∀ a, (evaluate a).2 ≤ H) : + (run A evaluate he stream modulus hm N cursor).cells ≤ 2*N+H+56 := by + have hw := WordCandidateExecution.run_cells stream modulus hm N cursor + have ht := SamplerVectorCells.test_cells A evaluate he 1 H N + (WordCandidateExecution.run stream modulus hm N cursor).data hH + change max _ (N+_+16) ≤ _ + simp only [Nat.mul_one] at ht + omega + +end LowSpaceSubsetSum.WordSeedRejectionExecution + +end OAI diff --git a/lean/OAI/Combinatorics/LowSpaceSubsetSum/Word/WordSeedScalarBounds.lean b/lean/OAI/Combinatorics/LowSpaceSubsetSum/Word/WordSeedScalarBounds.lean new file mode 100644 index 0000000000000000000000000000000000000000..3ce3a34120de7508f16e58571a2235397a92c210 --- /dev/null +++ b/lean/OAI/Combinatorics/LowSpaceSubsetSum/Word/WordSeedScalarBounds.lean @@ -0,0 +1,188 @@ +import OAI.Combinatorics.LowSpaceSubsetSum.Word.WordSeedFactorExecution +import OAI.Combinatorics.LowSpaceSubsetSum.Word.WordSeedCompressionExecution +import OAI.Combinatorics.LowSpaceSubsetSum.Word.WordWidthBounds + +namespace OAI + +/-! # Application-scale bounds for measured scalar samplers + +Only the actual prime tests incur the half-exponential factor. Permutation +range tests, retained candidate buffers and tuple assembly remain polynomial. +-/ + +namespace LowSpaceSubsetSum.WordSeedScalarBounds + +open WordSeedMeasured + +private theorem self_le_pow {u : ℕ} (hu : 1 ≤ u) {k : ℕ} (hk : 1 ≤ k) : u ≤ u^k := by + simpa only [Nat.pow_one] using Nat.pow_le_pow_right hu hk + +private theorem multiple_power {u c k : ℕ} (hc : c ≤ u) : c*u^k ≤ u^(k+1) := by + simpa only [Nat.pow_succ,Nat.mul_comm] using Nat.mul_le_mul_right (u^k) hc + +private theorem small_tail {u : ℕ} (hu : 10000 ≤ u) : + 5*u+64 ≤ u^3 := by + have hsq : 10000*u ≤ u^2 := by + simpa only [pow_two] using Nat.mul_le_mul_right u hu + have hcube : u^2 ≤ u^3 := Nat.pow_le_pow_right (by omega) (by decide) + nlinarith + +private theorem factor_numeric {n ell u H : ℕ} (hu : 10000 ≤ u) + (hnu : n+2 ≤ u) (hell : ell ≤ n) (hH : 1 ≤ H) + (hexp : 2^((ell+1)/2) ≤ H) : factorWork n ell ≤ u^5*H := by + have hn3 : n^3 ≤ u^3 := Nat.pow_le_pow_left (by omega) 3 + have hu4 : u ≤ u^4 := self_le_pow (by omega) (by decide) + have hsmall : 3*ell+21 ≤ 5*u := by omega + have hinner : 12*2^((ell+1)/2)+12*(ell+1)+11 ≤ 35*u*H := by + have ht := Nat.mul_le_mul_left (12*u+11) hH + have he := Nat.mul_le_mul_left 12 hexp + have hl : ell+1 ≤ u := by omega + have hc : 12+12*u+11 ≤ 35*u := by omega + have hm := Nat.mul_le_mul_right H hc + nlinarith + have hmain : n^3*(12*2^((ell+1)/2)+12*(ell+1)+11) ≤ 35*u^4*H := by + calc + _ ≤ u^3*(35*u*H) := Nat.mul_le_mul hn3 hinner + _ = _ := by ring + have htail : 3*ell+21 ≤ 5*u^4*H := by + have ht := Nat.mul_le_mul_right (5*u^4) hH + have hm := Nat.mul_le_mul_left 5 hu4 + nlinarith + have hscale : 40*u^4*H ≤ u^5*H := + Nat.mul_le_mul_right H (multiple_power (by omega : 40 ≤ u)) + unfold factorWork + nlinarith + +private theorem permutation_numeric {n k u : ℕ} (hu : 10000 ≤ u) + (hnu : n+2 ≤ u) (hk : k ≤ n) : + k*(13*n^3+5*k+64)+1 ≤ u^5 ∧ + (k+1)*(2*n^3+256) ≤ u^5 ∧ (k+1)*(n^3+64) ≤ u^5 := by + have hn3 : n^3 ≤ u^3 := Nat.pow_le_pow_left (by omega) 3 + have hu3 : u ≤ u^3 := self_le_pow (by omega) (by decide) + have hu4 : 1 ≤ u^4 := (show 1 ≤ u by omega).trans + (self_le_pow (by omega) (by decide)) + have hlow := small_tail hu + have hinner : 13*n^3+5*k+64 ≤ 14*u^3 := by omega + have hw : k*(13*n^3+5*k+64) ≤ 14*u^4 := by + calc + _ ≤ u*(14*u^3) := Nat.mul_le_mul (by omega) hinner + _ = _ := by ring + have hW : k*(13*n^3+5*k+64)+1 ≤ u^5 := by + have hs := multiple_power (k := 4) (by omega : 15 ≤ u) + nlinarith + have hc : (k+1)*(2*n^3+256) ≤ 3*u^4 := by + calc + _ ≤ u*(3*u^3) := Nat.mul_le_mul (by omega) (by omega) + _ = _ := by ring + have hr : (k+1)*(n^3+64) ≤ 2*u^4 := by + calc + _ ≤ u*(2*u^3) := Nat.mul_le_mul (by omega) (by omega) + _ = _ := by ring + exact ⟨hW,hc.trans (multiple_power (by omega : 3 ≤ u)), + hr.trans (multiple_power (by omega : 2 ≤ u))⟩ + +variable {n : ℕ} + +/-- The executed modulus itself fits, using strict width slack in the application. -/ +theorem prime_modulus_fits (I : Instance n) {ell : ℕ} (hell : ell ≤ n) : + (WordSeedPowerExecution.run ell).1 < 2^wordWidth I := by + rw [WordSeedPowerExecution.run_value] + exact Nat.pow_lt_pow_right (by decide) (by unfold wordWidth inputScale; omega) + +theorem factorWork_le (I : Instance n) (hn : 10000 ≤ n) {ell : ℕ} (hell : ell ≤ n) : + factorWork n ell ≤ inputScale I^5*2^((n+1)/2) := by + exact factor_numeric (by unfold inputScale; omega) (by unfold inputScale; omega) + hell Nat.one_le_two_pow (Nat.pow_le_pow_right (by decide) (by omega)) + +theorem prime_work_le (I : Instance n) (hn : 10000 ≤ n) {ell : ℕ} (hell : ell ≤ n) : + n^3*(12*2^((ell+1)/2)+12*(ell+1)+11)+3*ell+17 ≤ + inputScale I^5*2^((n+1)/2) := by + have h := factorWork_le I hn hell + unfold factorWork at h + omega + +theorem permutation_bounds (I : Instance n) (hn : 10000 ≤ n) {k : ℕ} (hk : k ≤ n) : + k*(13*n^3+5*k+64)+1 ≤ inputScale I^5 ∧ + (k+1)*(2*n^3+256) ≤ inputScale I^5 ∧ + (k+1)*(n^3+64) ≤ inputScale I^5 := + permutation_numeric (by unfold inputScale; omega) (by unfold inputScale; omega) hk + +theorem permutation_bounded_scale (I : Instance n) (hn : 10000 ≤ n) {k : ℕ} + (hk : k ≤ n) (w : ℕ) (hw : Nat.clog 2 k ≤ w) : + (permutation w n k hw).Bounded (inputScale I^5) (inputScale I^5) (inputScale I^5) := + bounded_mono _ (permutation_bounded w n k hw) + (permutation_bounds I hn hk).1 (permutation_bounds I hn hk).2.1 + (permutation_bounds I hn hk).2.2 + +theorem scalar_cells_le (I : Instance n) (hn : 10000 ≤ n) : + 2*n^3+124 ≤ inputScale I^5 ∧ n^3+28 ≤ inputScale I^5 := by + let u := inputScale I + have hu : 10000 ≤ u := by dsimp only [u,inputScale]; omega + have hn3 : n^3 ≤ u^3 := Nat.pow_le_pow_left (by dsimp only [u,inputScale]; omega) 3 + have hu3 : u ≤ u^3 := self_le_pow (by omega) (by decide) + have hu2 : 3 ≤ u^2 := by nlinarith + have hp : 3*u^3 ≤ u^5 := by + calc + _ ≤ u^2*u^3 := Nat.mul_le_mul_right _ hu2 + _ = _ := by ring + constructor <;> change _ ≤ u^5 <;> omega + +theorem factor_bounded_scale (I : Instance n) (hn : 10000 ≤ n) {ell : ℕ} + (hell : ell ≤ n) (w : ℕ) (hw : ell ≤ w) : + (factor w n ell hw).Bounded (inputScale I^5*2^((n+1)/2)) + (inputScale I^5) (inputScale I^5) := + bounded_mono _ (factor_bounded w n ell hw) (factorWork_le I hn hell) + (scalar_cells_le I hn).1 (scalar_cells_le I hn).2 + +theorem prime_bounded_scale (I : Instance n) (hn : 10000 ≤ n) {ell : ℕ} + (hell : ell ≤ n) (hfour : 4 ≤ ell) (w : ℕ) (hw : ell ≤ w) : + (primeInitialized w n ell hfour hw).Bounded (inputScale I^5*2^((n+1)/2)) + (inputScale I^5) (inputScale I^5) := + bounded_mono _ (primeInitialized_bounded w n ell hfour hw) (prime_work_le I hn hell) + (scalar_cells_le I hn).1 ((show n^3+18 ≤ n^3+28 by omega).trans (scalar_cells_le I hn).2) + +theorem compression_bounds (I : Instance n) (hn : 10000 ≤ n) : + compressionWork n ≤ inputScale I^6*2^((n+1)/2) ∧ + (n+3)*(2*n^3+256) ≤ inputScale I^5 ∧ + (n+2)*(n^3+64) ≤ inputScale I^5 := by + let u := inputScale I + let H := 2^((n+1)/2) + have hu : 10000 ≤ u := by dsimp only [u,inputScale]; omega + have hH : 1 ≤ H := Nat.one_le_two_pow + have hp := (permutation_bounds I hn (le_refl n)).1 + have hq := prime_work_le I hn (show compressionPrimeExponent n ≤ n by + unfold compressionPrimeExponent; omega) + have hwork : compressionWork n ≤ u^6*H := by + change n*(13*n^3+5*n+64)+1 ≤ u^5 at hp + change n^3*(12*2^((compressionPrimeExponent n+1)/2)+ + 12*(compressionPrimeExponent n+1)+11)+3*compressionPrimeExponent n+17 ≤ u^5*H at hq + have hph := Nat.mul_le_mul_left (u^5) hH + have hu5 : 8 ≤ u^5 := (show 8 ≤ u by omega).trans (self_le_pow (by omega) (by decide)) + have hscale : 3*u^5*H ≤ u^6*H := + Nat.mul_le_mul_right _ (multiple_power (by omega : 3 ≤ u)) + unfold compressionWork + nlinarith + have hn3 : n^3 ≤ u^3 := Nat.pow_le_pow_left (by dsimp only [u,inputScale]; omega) 3 + have hu3 : u ≤ u^3 := self_le_pow (by omega) (by decide) + have hc : (n+3)*(2*n^3+256) ≤ 6*u^4 := by + calc + _ ≤ (2*u)*(3*u^3) := Nat.mul_le_mul (by dsimp only [u,inputScale]; omega) (by omega) + _ = _ := by ring + have hr : (n+2)*(n^3+64) ≤ 2*u^4 := by + calc + _ ≤ u*(2*u^3) := Nat.mul_le_mul (by dsimp only [u,inputScale]; omega) (by omega) + _ = _ := by ring + exact ⟨hwork,hc.trans (multiple_power (by omega : 6 ≤ u)), + hr.trans (multiple_power (by omega : 2 ≤ u))⟩ + +theorem compression_bounded_scale (I : Instance n) (D : CompressionData n) + (hn : 168000000 ≤ n) (w : ℕ) (hp : Nat.clog 2 n ≤ w) + (hq : compressionPrimeExponent n ≤ w) : + (compression D hn w hp hq).Bounded (inputScale I^6*2^((n+1)/2)) + (inputScale I^5) (inputScale I^5) := by + have h := compression_bounds I (by omega : 10000 ≤ n) + exact bounded_mono _ (compression_bounded D hn w hp hq) h.1 h.2.1 h.2.2 + +end LowSpaceSubsetSum.WordSeedScalarBounds + +end OAI diff --git a/lean/OAI/Combinatorics/LowSpaceSubsetSum/Word/WordSeedScalarExecution.lean b/lean/OAI/Combinatorics/LowSpaceSubsetSum/Word/WordSeedScalarExecution.lean new file mode 100644 index 0000000000000000000000000000000000000000..89301405c898672e104231552ac3423c735a7140 --- /dev/null +++ b/lean/OAI/Combinatorics/LowSpaceSubsetSum/Word/WordSeedScalarExecution.lean @@ -0,0 +1,97 @@ +import OAI.Combinatorics.LowSpaceSubsetSum.Word.WordSeedMeasuredRejection +import OAI.Combinatorics.LowSpaceSubsetSum.Word.WordSeedPrimitives +import OAI.Combinatorics.LowSpaceSubsetSum.Word.WordSeedPrimeTestExecution + +namespace OAI + +/-! # Concrete measured range and prime seed generation + +The cached modulus is an input scalar. The range evaluator is a comparison; +the prime evaluator explicitly computes its powers and then runs the scalar +trial-division cursor. Its charge includes both executed power loops. +-/ + +noncomputable section +namespace LowSpaceSubsetSum.WordSeedMeasured + +open WordSeedRealization + +def rangeTest (D : ℕ) (p : Fin (2^Nat.clog 2 D)) : (Bool × ℕ) × ℕ := + ((decide (rangeEligible D p),2),8) + +def primeTest (ell : ℕ) (p : Fin (2^ell)) : (Bool × ℕ) × ℕ := + WordSeedPrimeTestExecution.run ell p + +theorem primeTest_value (ell : ℕ) (p : Fin (2^ell)) : + (primeTest ell p).1.1 = true ↔ primeEligible ell p := by + rw [primeTest,WordSeedPrimeTestExecution.run_value] + exact SamplerAttempts.primeTest_correct ell p + +theorem primeTest_work (ell : ℕ) (p : Fin (2^ell)) : + (primeTest ell p).1.2 ≤ 12*2^((ell+1)/2)+12*(ell+1) := by + exact WordSeedPrimeTestExecution.run_work ell p + +theorem primeTest_cells (ell : ℕ) (p : Fin (2^ell)) : + (primeTest ell p).2 = 28 := by + exact WordSeedPrimeTestExecution.run_cells ell p + +def range (w n D : ℕ) (hD : 1 < D) (hw : Nat.clog 2 D ≤ w) + (modulus : ℕ) (hm : modulus = 2^Nat.clog 2 D) : + Execution (WordSeedRealization.range w n D hD hw) := by + let : Nonempty (Fin D) := ⟨⟨0,by omega⟩⟩ + let : Nonempty {x : Fin (2^Nat.clog 2 D) // rangeEligible D x} := + ⟨(rangeEligibleEquiv D).symm ⟨0,by omega⟩⟩ + exact map + (rejection (rangeEligible D) (rangeTest D) (fun _ => by + simp only [rangeTest,decide_eq_true_eq]) hw modulus hm (n^3)) + (rangeEligibleEquiv D) (fun a => (((rangeEligibleEquiv D) a,2),2)) (fun _ => rfl) + +theorem range_bounded (w n D : ℕ) (hD : 1 < D) (hw : Nat.clog 2 D ≤ w) + (modulus : ℕ) (hm : modulus = 2^Nat.clog 2 D) : + (range w n D hD hw modulus hm).Bounded (13*n^3+15) (2*n^3+96) (n^3+18) := by + let : Nonempty (Fin D) := ⟨⟨0,by omega⟩⟩ + let : Nonempty {x : Fin (2^Nat.clog 2 D) // rangeEligible D x} := + ⟨(rangeEligibleEquiv D).symm ⟨0,by omega⟩⟩ + have hr := rejection_bounded (rangeEligible D) (rangeTest D) + (fun _ => by simp only [rangeTest,decide_eq_true_eq]) hw modulus hm + (n^3) 2 8 (fun _ => le_rfl) (fun _ => le_rfl) + have h := map_bounded _ (rangeEligibleEquiv D) + (fun a => (((rangeEligibleEquiv D) a,2),2)) (fun _ => rfl) + _ _ _ 2 2 hr (fun _ => le_rfl) (fun _ => le_rfl) + intro stream cursor + have hh := h stream cursor + dsimp only [range] + exact ⟨by omega,hh.2.1.trans (by omega),by omega⟩ + +def prime (w n ell : ℕ) (hell : 4 ≤ ell) (hw : ell ≤ w) + (modulus : ℕ) (hm : modulus = 2^ell) : + Execution (WordSeedRealization.prime w n ell hell hw) := by + let : Nonempty ↥(primeRange ell) := (primeRange_nonempty hell).to_subtype + let : Nonempty {x : Fin (2^ell) // primeEligible ell x} := + ⟨(primeEligibleEquiv hell).symm (Classical.choice inferInstance)⟩ + exact map (rejection (primeEligible ell) (primeTest ell) (primeTest_value ell) + hw modulus hm (n^3)) (primeEligibleEquiv hell) + (fun a => (((primeEligibleEquiv hell) a,2),2)) (fun _ => rfl) + +theorem prime_bounded (w n ell : ℕ) (hell : 4 ≤ ell) (hw : ell ≤ w) + (modulus : ℕ) (hm : modulus = 2^ell) : + (prime w n ell hell hw modulus hm).Bounded + (n^3*(12*2^((ell+1)/2)+12*(ell+1)+11)+15) (2*n^3+116) (n^3+18) := by + let : Nonempty ↥(primeRange ell) := (primeRange_nonempty hell).to_subtype + let : Nonempty {x : Fin (2^ell) // primeEligible ell x} := + ⟨(primeEligibleEquiv hell).symm (Classical.choice inferInstance)⟩ + have hr := rejection_bounded (primeEligible ell) (primeTest ell) (primeTest_value ell) + hw modulus hm (n^3) _ 28 (primeTest_work ell) (fun p => (primeTest_cells ell p).le) + have h := map_bounded _ (primeEligibleEquiv hell) + (fun a => (((primeEligibleEquiv hell) a,2),2)) (fun _ => rfl) + _ _ _ 2 2 hr (fun _ => le_rfl) (fun _ => le_rfl) + intro stream cursor + have hh := h stream cursor + dsimp only [prime] + exact ⟨by omega,hh.2.1.trans (by omega),by omega⟩ + +end LowSpaceSubsetSum.WordSeedMeasured + +end + +end OAI diff --git a/lean/OAI/Combinatorics/LowSpaceSubsetSum/Word/WordSeedSeparatorPreparation.lean b/lean/OAI/Combinatorics/LowSpaceSubsetSum/Word/WordSeedSeparatorPreparation.lean new file mode 100644 index 0000000000000000000000000000000000000000..7841fce9586df362854317e19706c05d89c7a005 --- /dev/null +++ b/lean/OAI/Combinatorics/LowSpaceSubsetSum/Word/WordSeedSeparatorPreparation.lean @@ -0,0 +1,66 @@ +import OAI.Combinatorics.LowSpaceSubsetSum.Word.WordSeedFamilyExecution +import OAI.Combinatorics.LowSpaceSubsetSum.Separators.SeparatorParameterCells + +namespace OAI + +/-! # Executing the integer separator parameters before family generation -/ + +noncomputable section +namespace LowSpaceSubsetSum.WordSeedMeasured + +abbrev SeparatorPrepared (g k : ℕ) := + {d : SeparatorParameterExecution.Data // d = (SeparatorParameterExecution.run g k).1} + +def separatorCompute (g k : ℕ) : (SeparatorPrepared g k × ℕ) × ℕ := + let r := SeparatorParameterCells.run g k + ((⟨r.1.1,congrArg Prod.fst (SeparatorParameterCells.run_value g k)⟩,r.1.2+2),r.2+16) + +def familiesFromSeparatorData (g k : ℕ) (hg : 64 ≤ g) (heven : 2 ∣ g) + (hk : k ≤ g) (hklo : 2*g ≤ 3*k) (w n : ℕ) (hw : Nat.clog 2 g ≤ w) + (d : SeparatorPrepared g k) : + Execution (WordSeedRealization.families + (SeparatorParameters.rounded g k hg heven hk hklo) w n hw) := + familiesUsing (SeparatorParameters.rounded g k hg heven hk hklo) + (fun _ => d.val.size) (fun i => d.val.counts[i.val]) + (fun i => by rw [d.property]; exact SeparatorParameterExecution.rounded_size g k hg heven hk hklo i) + (fun i => by rw [d.property]; exact SeparatorParameterExecution.rounded_counts g k hg heven hk hklo i) + w n hw + +def familiesPrepared (g k : ℕ) (hg : 64 ≤ g) (heven : 2 ∣ g) + (hk : k ≤ g) (hklo : 2*g ≤ 3*k) (w n : ℕ) (hw : Nat.clog 2 g ≤ w) : + Execution (WordSeedRealization.families + (SeparatorParameters.rounded g k hg heven hk hklo) w n hw) := + prepareThen (fun _ => separatorCompute g k) + (familiesFromSeparatorData g k hg heven hk hklo w n hw) + +theorem separatorCompute_work (g k : ℕ) : + (separatorCompute g k).1.2 ≤ 60*g+53 := by + have h := SeparatorParameterExecution.work g k + rw [←SeparatorParameterCells.run_value] at h + change (SeparatorParameterCells.run g k).1.2+2 ≤ _ + omega + +theorem separatorCompute_cells (g k : ℕ) : + (separatorCompute g k).2 ≤ 256 := by + have h := SeparatorParameterCells.run_cells g k + change (SeparatorParameterCells.run g k).2+16 ≤ _ + omega + +theorem familiesPrepared_bounded (g k : ℕ) (hg : 64 ≤ g) (heven : 2 ∣ g) + (hk : k ≤ g) (hklo : 2*g ≤ 3*k) (w n : ℕ) (hw : Nat.clog 2 g ≤ w) : + (familiesPrepared g k hg heven hk hklo w n hw).Bounded + (60*g+55+100*(11*2^g+1)*(maskBudget n g+100)) + (264+100*(11*2^g+1)*(maskBudget n g+100)) + (264+100*(11*2^g+1)*(maskBudget n g+100)) := by + have h := prepareThen_bounded (fun _ => separatorCompute g k) + (familiesFromSeparatorData g k hg heven hk hklo w n hw) + (60*g+53) 256 _ _ _ (separatorCompute_work g k) (separatorCompute_cells g k) + (fun d => by + apply familiesUsing_bounded) + exact bounded_mono _ h (by omega) (by omega) (by omega) + +end LowSpaceSubsetSum.WordSeedMeasured + +end + +end OAI diff --git a/lean/OAI/Combinatorics/LowSpaceSubsetSum/Word/WordSeedStructuralBounds.lean b/lean/OAI/Combinatorics/LowSpaceSubsetSum/Word/WordSeedStructuralBounds.lean new file mode 100644 index 0000000000000000000000000000000000000000..573fa0bfae53dda8d3dacca1f1a3758a27f1d529 --- /dev/null +++ b/lean/OAI/Combinatorics/LowSpaceSubsetSum/Word/WordSeedStructuralBounds.lean @@ -0,0 +1,112 @@ +import OAI.Combinatorics.LowSpaceSubsetSum.Word.WordSeedFiniteBounds +import OAI.Combinatorics.LowSpaceSubsetSum.Word.WordSeedStructuralExecution + +namespace OAI + +/-! # Polynomial envelopes for the structural history draws + +These bounds charge measured permutation generation and the actual constant +size tuple/closure constructors. Materialization is charged by the later +preparation stage. +-/ + +namespace LowSpaceSubsetSum.WordSeedStructuralBounds + +open WordSeedMeasured WordSeedScalarBounds + +variable {n : ℕ} + +private theorem self_le_power {u k : ℕ} (hu : 1 ≤ u) (hk : 1 ≤ k) : u ≤ u^k := by + simpa only [Nat.pow_one] using Nat.pow_le_pow_right hu hk + +private theorem coefficient_power {u c k : ℕ} (hc : c ≤ u) : c*u^k ≤ u^(k+1) := by + simpa only [Nat.pow_succ,Nat.mul_comm] using Nat.mul_le_mul_right (u^k) hc + +private theorem additive_slack {u : ℕ} (hu : 10000 ≤ u) : u^5+24 ≤ u^6 := by + have hp : u ≤ u^5 := self_le_power (by omega) (by decide) + have hs : 2*u^5 ≤ u^6 := coefficient_power (by omega) + omega + +private theorem triple_slack {u : ℕ} (hu : 10000 ≤ u) : 8*u^6+256 ≤ u^7 := by + have hp : u ≤ u^6 := self_le_power (by omega) (by decide) + have hs : 9*u^6 ≤ u^7 := coefficient_power (by omega) + omega + +private theorem layout_numeric {n u : ℕ} (hu : 10000 ≤ u) (hnu : n+2 ≤ u) : + (n+1)*(30*n^3+100*n+1000) ≤ u^6 := by + have hn3 : n^3 ≤ u^3 := Nat.pow_le_pow_left (by omega) 3 + have hu3 : u ≤ u^3 := self_le_power (by omega) (by decide) + have hinner : 30*n^3+100*n+1000 ≤ 1130*u^3 := by nlinarith + calc + _ ≤ u*(1130*u^3) := Nat.mul_le_mul (by omega) hinner + _ = 1130*u^4 := by ring + _ ≤ u^5 := coefficient_power (by omega) + _ ≤ u^6 := Nat.pow_le_pow_right (by omega) (by decide) + +private theorem guesses_numeric {n u : ℕ} (hu : 10000 ≤ u) (hnu : n+2 ≤ u) : + 2000*(n+1)^4 ≤ u^6 := by + calc + _ ≤ 2000*u^4 := Nat.mul_le_mul_left _ (Nat.pow_le_pow_left (by omega) 4) + _ ≤ u^5 := coefficient_power (by omega) + _ ≤ u^6 := Nat.pow_le_pow_right (by omega) (by decide) + +theorem layout_bounded_scale (I : Instance n) (hn : 10000 ≤ n) + (R : RepresentationSetup n) (w : ℕ) (hp : Nat.clog 2 n ≤ w) (hb : 1 ≤ w) : + (layout R w hp hb).Bounded (inputScale I^6) (inputScale I^6) (inputScale I^6) := by + have h := layout_numeric (n := n) (u := inputScale I) + (by unfold inputScale; omega) (by unfold inputScale; omega) + exact bounded_mono _ (layout_bounded R w hp hb) h h h + +theorem guesses_bounded_scale (I : Instance n) (hn : 10000 ≤ n) + (R : RepresentationSetup n) (w : ℕ) (hw : Nat.clog 2 (CanonicalGuesses.width n) ≤ w) : + (guesses R w hw).Bounded (inputScale I^6) (inputScale I^6) (inputScale I^6) := by + have h := guesses_numeric (n := n) (u := inputScale I) + (by unfold inputScale; omega) (by unfold inputScale; omega) + exact bounded_mono _ (guesses_bounded R w hw) h h h + +theorem block_size_le (R : RepresentationSetup n) (z : RepresentationSetup.Layout n) + (i : Fin 3) : RepresentationSetup.blockCount i*(2*RepresentationSetup.blockHalf n i) ≤ n := by + rw [←CanonicalPartition.size_eq R z i] + simpa only [Fintype.card_fin] using Finset.card_le_univ (R.orderedMixers z i) + +theorem partition_bounded_scale (I : Instance n) (hn : 10000 ≤ n) + (R : RepresentationSetup n) (z : RepresentationSetup.Layout n) (i : Fin 3) (w : ℕ) + (hw : Nat.clog 2 (RepresentationSetup.blockCount i* + (2*RepresentationSetup.blockHalf n i)) ≤ w) : + (partition R z i w hw).Bounded (inputScale I^6) (inputScale I^6) (inputScale I^6) := by + have hp := permutation_bounded_scale I hn (block_size_le R z i) w hw + have h1 := map_bounded _ (Equiv.permCongr (CanonicalPartition.ranks R z i).symm) + (fun p => (((Equiv.permCongr (CanonicalPartition.ranks R z i).symm) p,2),4)) + (fun _ => rfl) _ _ _ 2 4 hp (fun _ => le_rfl) (fun _ => le_rfl) + have h2 := map_bounded _ (coloringOfPermutation (CanonicalPartition.base R z i)) + (fun p => (((coloringOfPermutation (CanonicalPartition.base R z i)) p,2),4)) + (fun _ => rfl) _ _ _ 2 4 h1 (fun _ => le_rfl) (fun _ => le_rfl) + have hs := additive_slack (show 10000 ≤ inputScale I by unfold inputScale; omega) + intro stream cursor + have h := h2 stream cursor + change _ ≤ inputScale I^6 ∧ _ ≤ inputScale I^6 ∧ _ ≤ inputScale I^6 + refine ⟨h.1.trans (by omega),h.2.1.trans (by omega),h.2.2.trans (by omega)⟩ + +theorem partitions_bounded_scale (I : Instance n) (hn : 10000 ≤ n) + (R : RepresentationSetup n) (z : RepresentationSetup.Layout n) (w : ℕ) (hw : n ≤ w) : + (partitions R z w hw).Bounded (inputScale I^7) (inputScale I^7) (inputScale I^7) := by + have hi (i : Fin 3) := block_size_le R z i + let hwidth (i : Fin 3) : Nat.clog 2 (RepresentationSetup.blockCount i* + (2*RepresentationSetup.blockHalf n i)) ≤ w := + (Nat.clog_le_of_le_pow Nat.lt_two_pow_self.le).trans ((hi i).trans hw) + have hp := pi_bounded w (n*n^3) 3 (fun i => R.Partition z i) + (fun i => CanonicalPartition.coupling R z i) + (fun i => WordSeedRealization.enlarge (WordSeedRealization.partition R z i w (hwidth i)) + (Nat.mul_le_mul_right _ (hi i))) + (fun i => enlarge (partition R z i w (hwidth i)) (Nat.mul_le_mul_right _ (hi i))) + (inputScale I^6) (inputScale I^6) (inputScale I^6) (fun i => + enlarge_bounded _ _ _ _ _ (partition_bounded_scale I hn R z i w (hwidth i))) + have hs := triple_slack (show 10000 ≤ inputScale I by unfold inputScale; omega) + intro stream cursor + have h := hp stream cursor + change _ ≤ inputScale I^7 ∧ _ ≤ inputScale I^7 ∧ _ ≤ inputScale I^7 + exact ⟨h.1.trans (by omega),h.2.1.trans (by omega),h.2.2.trans (by omega)⟩ + +end LowSpaceSubsetSum.WordSeedStructuralBounds + +end OAI diff --git a/lean/OAI/Combinatorics/LowSpaceSubsetSum/Word/WordSeedStructuralExecution.lean b/lean/OAI/Combinatorics/LowSpaceSubsetSum/Word/WordSeedStructuralExecution.lean new file mode 100644 index 0000000000000000000000000000000000000000..4150d91eece3a3a76ef7f7fe65c512e78050db08 --- /dev/null +++ b/lean/OAI/Combinatorics/LowSpaceSubsetSum/Word/WordSeedStructuralExecution.lean @@ -0,0 +1,104 @@ +import OAI.Combinatorics.LowSpaceSubsetSum.Word.WordSeedBitsExecution +import OAI.Combinatorics.LowSpaceSubsetSum.Word.WordSeedPermutationExecution +import OAI.Combinatorics.LowSpaceSubsetSum.Word.WordSeedHistory + +namespace OAI + +/-! # Measured structural draws in a representation history + +Permutation composition and balanced-coloring maps create closures. These +closures are not applied during the next prime draw; the prepared action +later materializes all queried coordinates with its own counted routines. +The guess encoding performs its explicit endpoint arithmetic. +-/ + +noncomputable section +namespace LowSpaceSubsetSum.WordSeedMeasured + +variable {n : ℕ} + +def layout (R : RepresentationSetup n) (w : ℕ) + (hp : Nat.clog 2 n ≤ w) (hb : 1 ≤ w) : + Execution (WordSeedRealization.layout R w hp hb) := + prod (permutation w n n hp) (signs w n hb) + +def guesses (R : RepresentationSetup n) (w : ℕ) + (hw : Nat.clog 2 (CanonicalGuesses.width n) ≤ w) : + Execution (WordSeedRealization.guesses R w hw) := + pi w (n^3) 3 _ _ _ (fun _ => + map (fin w n (CanonicalGuesses.width n) hw) (CanonicalGuesses.encoding n) + (fun a => ((CanonicalGuesses.encode n a,12),4)) (fun _ => rfl)) + +def partition (R : RepresentationSetup n) (z : RepresentationSetup.Layout n) + (i : Fin 3) (w : ℕ) + (hw : Nat.clog 2 (RepresentationSetup.blockCount i * + (2*RepresentationSetup.blockHalf n i)) ≤ w) : + Execution (WordSeedRealization.partition R z i w hw) := + map (map (permutation w n _ hw) (Equiv.permCongr (CanonicalPartition.ranks R z i).symm) + (fun p => (((Equiv.permCongr (CanonicalPartition.ranks R z i).symm) p,2),4)) + (fun _ => rfl)) (coloringOfPermutation (CanonicalPartition.base R z i)) + (fun p => (((coloringOfPermutation (CanonicalPartition.base R z i)) p,2),4)) + (fun _ => rfl) + +private theorem clog_le (k w : ℕ) (h : k ≤ w) : Nat.clog 2 k ≤ w := + (Nat.clog_le_of_le_pow (Nat.lt_two_pow_self.le)).trans h + +def partitions (R : RepresentationSetup n) (z : RepresentationSetup.Layout n) + (w : ℕ) (hw : n ≤ w) : + Execution (WordSeedRealization.partitions R z w hw) := + pi w (n*n^3) 3 _ _ _ (fun i => by + have hs : RepresentationSetup.blockCount i*(2*RepresentationSetup.blockHalf n i) ≤ n := by + rw [←CanonicalPartition.size_eq R z i] + simpa only [Fintype.card_fin] using Finset.card_le_univ (R.orderedMixers z i) + exact enlarge (partition R z i w (clog_le _ _ (hs.trans hw))) + (Nat.mul_le_mul_right _ hs)) + +theorem layout_bounded (R : RepresentationSetup n) (w : ℕ) + (hp : Nat.clog 2 n ≤ w) (hb : 1 ≤ w) : + (layout R w hp hb).Bounded + ((n+1)*(30*n^3+100*n+1000)) ((n+1)*(30*n^3+100*n+1000)) + ((n+1)*(30*n^3+100*n+1000)) := by + have h := prod_bounded (permutation w n n hp) (signs w n hb) _ _ _ _ _ _ + (permutation_bounded w n n hp) (signs_bounded w n hb) + intro stream cursor + have ht := h stream cursor + refine ⟨ht.1.trans (by nlinarith),ht.2.1.trans ?_,ht.2.2.trans (by nlinarith)⟩ + apply max_le + · apply max_le <;> nlinarith + · nlinarith + +theorem guesses_bounded (R : RepresentationSetup n) (w : ℕ) + (hw : Nat.clog 2 (CanonicalGuesses.width n) ≤ w) : + (guesses R w hw).Bounded (2000*(n+1)^4) (2000*(n+1)^4) (2000*(n+1)^4) := by + have hc : Nat.clog 2 (CanonicalGuesses.width n) ≤ n+1 := by + apply Nat.clog_le_of_le_pow + apply (show CanonicalGuesses.width n ≤ n+1 by + unfold CanonicalGuesses.width CanonicalGuesses.upper CanonicalGuesses.lower mixerSize + omega).trans + exact Nat.lt_two_pow_self.le + have hm := map_bounded (fin w n (CanonicalGuesses.width n) hw) + (CanonicalGuesses.encoding n) (fun a => ((CanonicalGuesses.encode n a,12),4)) + (fun _ => rfl) _ _ _ 12 4 (fin_bounded w n (CanonicalGuesses.width n) hw) + (fun _ => le_rfl) (fun _ => le_rfl) + have hp := pi_bounded w (n^3) 3 _ _ _ _ + (13*n^3+5*Nat.clog 2 (CanonicalGuesses.width n)+31) + (3*n^3+134) (n^3+30) (fun _ stream cursor => by + have h := hm stream cursor + exact ⟨h.1,h.2.1.trans (by omega),h.2.2⟩) + intro stream cursor + have h := hp stream cursor + have h3 : n^3 ≤ (n+1)^4 := + (Nat.pow_le_pow_left (by omega : n ≤ n+1) 3).trans + (Nat.pow_le_pow_right (by omega : 0 < n+1) (by decide : 3 ≤ 4)) + have h1 : n ≤ (n+1)^4 := by + exact (show n ≤ n+1 by omega).trans (by + simpa only [pow_one] using Nat.pow_le_pow_right (by omega : 0 < n+1) (by decide : 1 ≤ 4)) + have hB : 1 ≤ (n+1)^4 := Nat.one_le_pow _ _ (by omega) + refine ⟨h.1.trans ?_,h.2.1.trans ?_,h.2.2.trans ?_⟩ <;> + nlinarith only [hc,h3,h1,hB] + +end LowSpaceSubsetSum.WordSeedMeasured + +end + +end OAI diff --git a/lean/OAI/Combinatorics/LowSpaceSubsetSum/Word/WordTuple.lean b/lean/OAI/Combinatorics/LowSpaceSubsetSum/Word/WordTuple.lean new file mode 100644 index 0000000000000000000000000000000000000000..1c3666d8f08559e54f0c6f0d7dcfd96783191433 --- /dev/null +++ b/lean/OAI/Combinatorics/LowSpaceSubsetSum/Word/WordTuple.lean @@ -0,0 +1,84 @@ +import OAI.Combinatorics.LowSpaceSubsetSum.Word.WordProgram +import OAI.Combinatorics.LowSpaceSubsetSum.Counting.FiniteRepetition + +namespace OAI + +/-! # Finite tuples drawn by sequential fair-word reads -/ + +noncomputable section +namespace LowSpaceSubsetSum.WordTuple + +open scoped BigOperators +open WordProgram + +variable {w : ℕ} + +def sample : (N : ℕ) → Program w (Fin N → Fin (2^w)) + | 0 => .pure Fin.elim0 + | N+1 => .draw (fun x => WordProgram.map (Fin.cons x) (sample N)) + +theorem bounded (N : ℕ) : Bounded (sample (w := w) N) N := by + induction N with + | zero => exact Bounded.pure _ 0 + | succ N ih => + apply Bounded.draw + intro x + simpa only [WordProgram.map, Nat.add_zero] using + WordProgram.bind_bound (sample N) N ih (fun f : Fin N → Fin (2^w) => .pure (Fin.cons (n := N) (α := fun _ => Fin (2^w)) x f)) 0 + (fun _ => Bounded.pure _ 0) + +private theorem uniform_product {α β : Type} [Fintype α] [Fintype β] + [Nonempty α] [Nonempty β] : + (FiniteLaw.uniform : FiniteLaw (α × β)) = + (FiniteLaw.uniform : FiniteLaw α).prod (FiniteLaw.uniform : FiniteLaw β) := by + apply FiniteLaw.eq_of_mass + intro p + simp only [FiniteLaw.uniform, FiniteLaw.prod, Fintype.card_prod, Nat.cast_mul] + exact (one_div_mul_one_div _ _).symm + +private theorem product_expectation {α β : Type} [Fintype α] [Fintype β] + (μ : FiniteLaw α) (ν : FiniteLaw β) (f : α × β → ℝ) : + (μ.prod ν).expectation f = μ.expectation (fun a => ν.expectation (fun b => f (a,b))) := by + simp only [FiniteLaw.expectation, FiniteLaw.prod, Fintype.sum_prod_type, Finset.mul_sum, + mul_assoc] + +private theorem uniform_word_expectation (f : Fin (2^w) → ℝ) : + (FiniteLaw.uniform : FiniteLaw (Fin (2^w))).expectation f = + (∑ x, f x) / (2^w : ℕ) := by + simp only [FiniteLaw.expectation, FiniteLaw.uniform, Fintype.card_fin, + one_div_mul_eq_div, Finset.sum_div] + +theorem cons_expectation (N : ℕ) (f : (Fin (N+1) → Fin (2^w)) → ℝ) : + (FiniteLaw.uniform : FiniteLaw (Fin (N+1) → Fin (2^w))).expectation f = + (∑ x, (FiniteLaw.uniform : FiniteLaw (Fin N → Fin (2^w))).expectation + (fun xs => f (Fin.cons x xs))) / (2^w : ℕ) := by + have he := FiniteLaw.map_equiv_uniform (Fin.consEquiv (fun _ : Fin (N+1) => Fin (2^w))) + rw [← he, FiniteLaw.map_expectation, uniform_product, product_expectation, + uniform_word_expectation] + rfl + +theorem expectation (N : ℕ) (f : (Fin N → Fin (2^w)) → ℝ) : + WordProgram.expectation (sample N) f = + (FiniteLaw.uniform : FiniteLaw (Fin N → Fin (2^w))).expectation f := by + induction N with + | zero => + simp only [sample, WordProgram.expectation, FiniteLaw.expectation, FiniteLaw.uniform, + Fintype.card_unique, Nat.cast_one, div_one, one_mul, Finset.univ_unique, + Finset.sum_singleton] + rfl + | succ N ih => + rw [cons_expectation] + simp only [sample, WordProgram.expectation, WordProgram.map, WordProgram.expectation_bind] + simp only [ih] + +theorem probability (N : ℕ) (P : (Fin N → Fin (2^w)) → Prop) : + WordProgram.probability (sample N) P = + (FiniteLaw.uniform : FiniteLaw (Fin N → Fin (2^w))).probability P := by + classical + rw [WordProgram.probability, expectation, ← FiniteLaw.probability_eq_expectation] + +end LowSpaceSubsetSum.WordTuple + +end + +end OAI diff --git a/lean/OAI/Combinatorics/LowSpaceSubsetSum/Word/WordWidthBounds.lean b/lean/OAI/Combinatorics/LowSpaceSubsetSum/Word/WordWidthBounds.lean new file mode 100644 index 0000000000000000000000000000000000000000..6b647d42a7c9994262c1df6e1c17d7ec5bac79e7 --- /dev/null +++ b/lean/OAI/Combinatorics/LowSpaceSubsetSum/Word/WordWidthBounds.lean @@ -0,0 +1,88 @@ +import OAI.Combinatorics.LowSpaceSubsetSum.Counting.Magnitudes +import OAI.Combinatorics.LowSpaceSubsetSum.Compression.CompressionSurvival + +namespace OAI + +/-! # Fixed word widths, watchdog counters and memory addresses + +These are arithmetic bounds on the manuscript's concrete finite cutoffs. +They do not assert that the algorithm has been compiled to a RAM program. +-/ + +noncomputable section + +namespace LowSpaceSubsetSum + +def wordWidth {n : ℕ} (I : Instance n) : ℕ := 4 * inputScale I + +def trialWatchdog {n : ℕ} (I : Instance n) : ℕ := + inputScale I ^ 500 * 2 ^ ((n + 1) / 2) + +def writableWordLimit {n : ℕ} (I : Instance n) : ℕ := + inputScale I ^ 15 * compressionDictionaryCapacity n + +theorem guarded_polynomial_exponential {n : ℕ} {u a : ℝ} (hn : 10000 ≤ n) + (hu : 0 < u) (hlog : Real.logb 2 u ≤ (n : ℝ) / 1000000000) + (k : ℕ) (hmargin : (k : ℝ) / 1000000000 + a ≤ 9 / 10) : + u ^ k * (2 : ℝ) ^ (a * n + 1) < (2 : ℝ) ^ n := by + have hp : u ^ k = (2 : ℝ) ^ ((k : ℝ) * Real.logb 2 u) := by + have hh := Real.rpow_mul_natCast (by norm_num : (0 : ℝ) ≤ 2) (Real.logb 2 u) k + rw [Real.rpow_logb (by norm_num) (by norm_num) hu] at hh + simpa only [mul_comm] using hh.symm + rw [hp, ← Real.rpow_add (by norm_num), ← Real.rpow_natCast] + apply Real.rpow_lt_rpow_of_exponent_lt (by norm_num) + have hnR : (10000 : ℝ) ≤ n := by exact_mod_cast hn + have hk := mul_le_mul_of_nonneg_left hlog (Nat.cast_nonneg k (α := ℝ)) + have hm := mul_le_mul_of_nonneg_right hmargin (Nat.cast_nonneg n (α := ℝ)) + nlinarith only [hk, hm, hnR] + +theorem trialWatchdog_lt_two_pow {n : ℕ} (I : Instance n) (hn : 10000 ≤ n) + (hlog : Real.logb 2 (inputScale I : ℝ) ≤ (n : ℝ) / 1000000000) : + trialWatchdog I < 2 ^ n := by + have hu : (0 : ℝ) < inputScale I := by + exact_mod_cast (show 0 < inputScale I by unfold inputScale; omega) + have he : (((n + 1) / 2 : ℕ) : ℝ) ≤ (1 / 2 : ℝ) * n + 1 := by + have hh : 2 * ((n + 1) / 2) ≤ n + 1 := by omega + have hhR : (2 : ℝ) * ((n + 1) / 2 : ℕ) ≤ n + 1 := by exact_mod_cast hh + linarith only [hhR] + have hh := guarded_polynomial_exponential hn hu hlog 500 + (a := (1 / 2 : ℝ)) (by norm_num) + have hm := mul_le_mul_of_nonneg_left + (Real.rpow_le_rpow_of_exponent_le (by norm_num : (1 : ℝ) ≤ 2) he) + (show 0 ≤ (inputScale I : ℝ) ^ 500 by positivity) + have hcast : (trialWatchdog I : ℝ) < (2 : ℝ) ^ n := by + simpa only [trialWatchdog, Nat.cast_mul, Nat.cast_pow, Nat.cast_ofNat, + Real.rpow_natCast] using hm.trans_lt hh + exact_mod_cast hcast + +theorem writableWordLimit_lt_two_pow {n : ℕ} (I : Instance n) (hn : 10000 ≤ n) + (hlog : Real.logb 2 (inputScale I : ℝ) ≤ (n : ℝ) / 1000000000) : + writableWordLimit I < 2 ^ n := by + have hu : (0 : ℝ) < inputScale I := by + exact_mod_cast (show 0 < inputScale I by unfold inputScale; omega) + have he : ((199 * n / 1000 : ℕ) : ℝ) ≤ (199 / 1000 : ℝ) * n + 1 := by + have hh : 1000 * (199 * n / 1000) ≤ 199 * n := by omega + have hhR : (1000 : ℝ) * (199 * n / 1000 : ℕ) ≤ 199 * n := by exact_mod_cast hh + linarith only [hhR] + have hh := guarded_polynomial_exponential hn hu hlog 15 + (a := (199 / 1000 : ℝ)) (by norm_num) + have hm := mul_le_mul_of_nonneg_left + (Real.rpow_le_rpow_of_exponent_le (by norm_num : (1 : ℝ) ≤ 2) he) + (show 0 ≤ (inputScale I : ℝ) ^ 15 by positivity) + have hcast : (writableWordLimit I : ℝ) < (2 : ℝ) ^ n := by + simpa only [writableWordLimit, compressionDictionaryCapacity, Nat.cast_mul, + Nat.cast_pow, Nat.cast_ofNat, Real.rpow_natCast] using hm.trans_lt hh + exact_mod_cast hcast + +theorem cutoff_fits_word {n : ℕ} (I : Instance n) {x : ℕ} (hx : x < 2 ^ n) : + x < 2 ^ wordWidth I := by + apply hx.trans_le + apply Nat.pow_le_pow_right (by decide) + unfold wordWidth inputScale + omega + +end LowSpaceSubsetSum + +end + +end OAI diff --git a/lean/OAI/Combinatorics/MatchingCount/Algorithm/AffineWeights.lean b/lean/OAI/Combinatorics/MatchingCount/Algorithm/AffineWeights.lean new file mode 100644 index 0000000000000000000000000000000000000000..653dd1474e0c94af02b6c9665b44b4c43114c7f5 --- /dev/null +++ b/lean/OAI/Combinatorics/MatchingCount/Algorithm/AffineWeights.lean @@ -0,0 +1,451 @@ +import Mathlib +import OAI.Combinatorics.MatchingCount.Graphs.PathStrength + +namespace OAI + +namespace MatchingFPRAS.Switching +open Finset +open scoped Classical symmDiff + +variable {V : Type*} +theorem erasePair_weight_of_lt [Fintype V] [LinearOrder V] + (w : V → V → ℝ) (m : Mate V) (a b : V) (h : m.1 a = b) (hab : a < b) : + weight w (erasePair m a b) = + ∏ v ∈ Finset.univ.erase a, if v < m.1 v then w v (m.1 v) else 1 := by + have hba : m.1 b = a := by rw [← h, mate_mate] + unfold weight + rw [← Finset.prod_erase_mul _ _ (Finset.mem_univ a)] + simp only [erasePair_apply m a b a h, true_or, ite_true, lt_self_iff_false, ite_false, + mul_one] + apply Finset.prod_congr rfl + intro v hv + have hva := (Finset.mem_erase.mp hv).1 + by_cases hvb : v = b + · subst v + simp [hba, erasePair_apply, h, hab.not_gt] + · simp [erasePair_apply, h, hva, hvb] + +theorem sum_erased_weights [Fintype V] [LinearOrder V] + (w : V → V → ℝ) (S : Finset V) (a b : V) + (ha : a ∉ S) (hb : b ∉ S) (hab : a ≠ b) : + ∑ m ∈ (matchings S).filter (fun m => m.1 a = b), weight w (erasePair m a b) = + partition w (insert a (insert b S)) := by + let A := (matchings S).filter (fun m => m.1 a = b) + let f := fun m : Mate V => erasePair m a b + have hi : Set.InjOn f A := by + intro m hm n hn he + have hm' := (Finset.mem_filter.mp hm).2 + have hn' := (Finset.mem_filter.mp hn).2 + have h := congrArg (fun p => withEdge p a b) he + simpa [f, withEdge_erasePair, hm', hn'] using h + have himg : A.image f = matchings (insert a (insert b S)) := by + ext m + constructor + · intro hm + obtain ⟨n,hn,rfl⟩ := Finset.mem_image.mp hm + obtain ⟨hnS,hnab⟩ := Finset.mem_filter.mp hn + exact (mem_matchings _ _).mpr + (erasePair_holes n S ((mem_matchings n S).mp hnS) a b hnab) + · intro hm + have hholes := (mem_matchings m (insert a (insert b S))).mp hm + have hma : m.1 a = a := (hholes a).mpr (by simp) + have hmb : m.1 b = b := (hholes b).mpr (by simp) + refine Finset.mem_image.mpr ⟨withEdge m a b, ?_, ?_⟩ + · apply Finset.mem_filter.mpr + constructor + · apply (mem_matchings _ _).mpr + have hh := withEdge_holes m (insert a (insert b S)) hholes a b + (by simp) (by simp) hab + have he : insert a (insert b S) \ {a,b} = S := by + ext v + simp only [Finset.mem_sdiff, Finset.mem_insert, Finset.mem_singleton] + grind + rwa [he] at hh + · simp [hma,hmb] + · exact erasePair_withEdge m a b hma hmb + change ∑ m ∈ A, weight w (f m) = _ + rw [← Finset.sum_image hi, himg] + rfl + +def affineWeights (w d : V → V → ℝ) (t : ℝ) (a b : V) : ℝ := w a b + t * d a b + +theorem weight_hasDerivAt [Fintype V] [LinearOrder V] + (w d : V → V → ℝ) (m : Mate V) (t : ℝ) : + HasDerivAt (fun s => weight (affineWeights w d s) m) + (∑ a, if a < m.1 a then d a (m.1 a) * + weight (affineWeights w d t) (erasePair m a (m.1 a)) else 0) t := by + have hf : ∀ a ∈ (Finset.univ : Finset V), + HasDerivAt (fun s => if a < m.1 a then affineWeights w d s a (m.1 a) else 1) + (if a < m.1 a then d a (m.1 a) else 0) t := by + intro a _ + by_cases ha : a < m.1 a + · simp only [ha, ite_true, affineWeights] + exact (hasDerivAt_mul_const (x := t) (d a (m.1 a))).const_add (w a (m.1 a)) + · simp only [ha, ite_false] + exact hasDerivAt_const t 1 + have hh := HasDerivAt.fun_finsetProd hf + apply hh.congr_deriv + apply Finset.sum_congr rfl + intro a _ + by_cases ha : a < m.1 a + · simp only [ha, ite_true, smul_eq_mul] + rw [erasePair_weight_of_lt _ m a (m.1 a) rfl ha] + ring + · simp [ha] + +theorem mate_endpoints_not_holes [DecidableEq V] (m : Mate V) (S : Finset V) + (hm : HasHoles m S) (a b : V) (h : m.1 a = b) (hab : a ≠ b) : + a ∉ S ∧ b ∉ S := by + constructor + · intro ha + exact hab (((hm a).mpr ha).symm.trans h) + · intro hb + have hba : m.1 b = a := by rw [← h, mate_mate] + exact hab (hba.symm.trans ((hm b).mpr hb)) + +noncomputable def edgeSum [Fintype V] [LinearOrder V] + (S : Finset V) (f : V → V → ℝ) : ℝ := + ∑ a, ∑ b, if a < b ∧ a ∉ S ∧ b ∉ S then f a b else 0 + +theorem partition_hasDerivAt [Fintype V] [LinearOrder V] + (w d : V → V → ℝ) (S : Finset V) (t : ℝ) : + HasDerivAt (fun s => partition (affineWeights w d s) S) + (edgeSum S (fun a b => d a b * + partition (affineWeights w d t) (insert a (insert b S)))) t := by + have hh := HasDerivAt.fun_sum (fun m (_ : m ∈ matchings S) => weight_hasDerivAt w d m t) + change HasDerivAt (fun s => partition (affineWeights w d s) S) _ t at hh + convert hh using 1 + unfold edgeSum + conv_rhs => rw [Finset.sum_comm] + apply Finset.sum_congr rfl + intro a _ + rw [← Finset.sum_fiberwise (matchings S) (fun m => m.1 a) + (fun m => if a < m.1 a then d a (m.1 a) * + weight (affineWeights w d t) (erasePair m a (m.1 a)) else 0)] + apply Finset.sum_congr rfl + intro b _ + by_cases hab : a < b + · by_cases hS : a ∉ S ∧ b ∉ S + · simp only [hab, hS.1, hS.2, and_self] + rw [← sum_erased_weights (affineWeights w d t) S a b hS.1 hS.2 hab.ne, + Finset.mul_sum] + apply Finset.sum_congr rfl + intro m hm + have he := (Finset.mem_filter.mp hm).2 + simp [he,hab] + · have hempty : (matchings S).filter (fun m => m.1 a = b) = ∅ := by + apply Finset.eq_empty_iff_forall_notMem.mpr + intro m hm + obtain ⟨hm,he⟩ := Finset.mem_filter.mp hm + exact hS (mate_endpoints_not_holes m S ((mem_matchings m S).mp hm) a b he hab.ne) + simp [hS,hempty] + · simp only [hab, false_and, ite_false] + symm + apply Finset.sum_eq_zero + intro m hm + have he := (Finset.mem_filter.mp hm).2 + simp [he,hab] + +theorem weight_mono [Fintype V] [LinearOrder V] (w u : V → V → ℝ) + (hw : ∀ a b, 0 ≤ w a b) (hwu : ∀ a b, w a b ≤ u a b) (m : Mate V) : + weight w m ≤ weight u m := by + apply Finset.prod_le_prod₀ + · intro a _ + split_ifs + · exact hw a (m.1 a) + · norm_num + · intro a _ + split_ifs + · exact hwu a (m.1 a) + · rfl + +theorem partition_mono [Fintype V] [LinearOrder V] (w u : V → V → ℝ) + (hw : ∀ a b, 0 ≤ w a b) (hwu : ∀ a b, w a b ≤ u a b) (S : Finset V) : + partition w S ≤ partition u S := + Finset.sum_le_sum (fun m _ => weight_mono w u hw hwu m) + +theorem edgeSum_div [Fintype V] [LinearOrder V] (S : Finset V) + (f : V → V → ℝ) (c : ℝ) : + edgeSum S (fun a b => f a b / c) = edgeSum S f / c := by + simp only [edgeSum, Finset.sum_div] + apply Finset.sum_congr rfl + intro a _ + apply Finset.sum_congr rfl + intro b _ + split_ifs <;> simp + +theorem edgeSum_nonneg [Fintype V] [LinearOrder V] (S : Finset V) + (f : V → V → ℝ) (hf : ∀ a b, a < b → a ∉ S → b ∉ S → 0 ≤ f a b) : + 0 ≤ edgeSum S f := by + apply Finset.sum_nonneg + intro a _ + apply Finset.sum_nonneg + intro b _ + split_ifs with h + · exact hf a b h.1 h.2.1 h.2.2 + · rfl + +theorem holeRatio_hasDerivAt [Fintype V] [LinearOrder V] + (w d : V → V → ℝ) (S : Finset V) (t : ℝ) + (hz : partition (affineWeights w d t) ∅ ≠ 0) : + HasDerivAt (fun s => holeRatio (affineWeights w d s) S) + (edgeSum S (fun a b => d a b * + holeRatio (affineWeights w d t) (insert a (insert b S))) - + holeRatio (affineWeights w d t) S * + edgeSum ∅ (fun a b => d a b * holeRatio (affineWeights w d t) {a,b})) t := by + have hh := (partition_hasDerivAt w d S t).div (partition_hasDerivAt w d ∅ t) hz + apply hh.congr_deriv + simp only [holeRatio, ← mul_div_assoc, edgeSum_div, Finset.insert_empty] + field_simp + +theorem affine_partition_pos [Fintype V] [LinearOrder V] + (w d : V → V → ℝ) (hw : ∀ a b, 0 ≤ w a b) (hd : ∀ a b, 0 ≤ d a b) + (hz : 0 < partition w ∅) (t : ℝ) (ht : 0 ≤ t) : + 0 < partition (affineWeights w d t) ∅ := by + apply hz.trans_le (partition_mono w _ hw _ ∅) + intro a b + exact le_add_of_nonneg_right (mul_nonneg ht (hd a b)) + +theorem finite_family_barrier {I : Type*} [Fintype I] + (f f' : I → ℝ → ℝ) (c : ℝ) (hc : 0 ≤ c) (hc1 : c < 1) + (hf : ∀ i, ContinuousOn (f i) (Set.Icc 0 1)) + (hinit : ∀ i, f i 0 ≤ 1) + (hderiv : ∀ t ∈ Set.Ioo 0 1, (∀ i, f i t < 2) → + ∀ i, HasDerivAt (f i) (f' i t) t ∧ f' i t ≤ c) : + ∀ t ∈ Set.Icc 0 1, ∀ i, f i t < 2 := by + classical + let S : Set ℝ := {t | t ∈ Set.Icc 0 1 ∧ ∃ i, 2 ≤ f i t} + have hsclosed : IsClosed S := by + have he : S = ⋃ i, {t | t ∈ Set.Icc 0 1 ∧ 2 ≤ f i t} := by + ext t + simp only [S, Set.mem_ofPred_eq, Set.mem_iUnion] + aesop + rw [he] + apply isClosed_iUnion_of_finite + intro i + exact (hf i).preimage_isClosed_of_isClosed isClosed_Icc isClosed_Ici + by_contra hfail + push Not at hfail + obtain ⟨t,ht,i,hi⟩ := hfail + obtain ⟨x,hx,hxmin⟩ := (isCompact_Icc.of_isClosed_subset hsclosed + (show S ⊆ Set.Icc (0:ℝ) 1 from fun _ h => h.1)).exists_isLeast ⟨t,ht,i,hi⟩ + obtain ⟨j,hj⟩ := hx.2 + have hxpos : 0 < x := by + have := hinit j + rcases hx.1.1.eq_or_lt with h | h + · rw [← h] at hj + linarith + · exact h + have hbefore : ∀ y ∈ Set.Ioo 0 x, ∀ k, f k y < 2 := by + intro y hy k + by_contra h + have hym : y ∈ S := ⟨⟨hy.1.le,hy.2.le.trans hx.1.2⟩,k,le_of_not_gt h⟩ + exact (not_le_of_gt hy.2) (hxmin hym) + have hdiff : ∀ y ∈ Set.Ioo 0 x, HasDerivAt (f j) (f' j y) y := by + intro y hy + exact (hderiv y ⟨hy.1,hy.2.trans_le hx.1.2⟩ (hbefore y hy) j).1 + obtain ⟨y,hy,he⟩ := exists_hasDerivAt_eq_slope (f j) (f' j) hxpos + ((hf j).mono (Set.Icc_subset_Icc_right hx.1.2)) hdiff + have hbound := (hderiv y ⟨hy.1,hy.2.trans_le hx.1.2⟩ (hbefore y hy) j).2 + rw [he, sub_zero] at hbound + have hbound' := (div_le_iff₀ hxpos).mp hbound + have hcx := mul_le_of_le_one_right hc hx.1.2 + have := hinit j + linarith + +noncomputable def holeScale (V : Type*) [Fintype V] : ℝ := + 100000000 * ((Fintype.card V : ℝ) + 1)^4 + +theorem holeScale_pos [Fintype V] : 0 < holeScale V := by + unfold holeScale + positivity + +noncomputable def holeAugmentation [Fintype V] [LinearOrder V] + (w : V → V → ℝ) (a b : V) : ℝ := bottleneck w a b / holeScale V + +theorem holeAugmentation_nonneg [Fintype V] [LinearOrder V] + (w : V → V → ℝ) (a b : V) : 0 ≤ holeAugmentation w a b := + div_nonneg (le_trans (by norm_num) (one_le_bottleneck w a b)) holeScale_pos.le + +theorem edgeSum_le_card_sq [Fintype V] [LinearOrder V] (S : Finset V) + (f : V → V → ℝ) (c : ℝ) (hc : 0 ≤ c) + (hf : ∀ a b, a < b → a ∉ S → b ∉ S → f a b ≤ c) : + edgeSum S f ≤ (Fintype.card V : ℝ)^2 * c := by + calc + _ ≤ ∑ _a : V, ∑ _b : V, c := by + apply Finset.sum_le_sum + intro a _ + apply Finset.sum_le_sum + intro b _ + split_ifs with h + · exact hf a b h.1 h.2.1 h.2.2 + · exact hc + _ = _ := by simp; ring + +theorem augmented_hole_summand [Fintype V] [LinearOrder V] + (hn : 2 ≤ Fintype.card V) (w u : V → V → ℝ) + (hu : ∀ a b, 0 ≤ u a b) (hz : 0 < partition u ∅) + (hwu : ∀ a b, w a b ≤ u a b) + (hrlo : ∀ a, (1:ℝ)/8 ≤ rowMax hn u a) (hrhi : ∀ a, rowMax hn u a ≤ 4) + (S : Finset V) (hS : S.card = 0 ∨ S.card = 2) + (a b : V) (hab : a < b) (ha : a ∉ S) (hb : b ∉ S) : + holeAugmentation w a b * holeRatio u (insert a (insert b S)) ≤ + 100000 * Fintype.card V / holeScale V := by + have hcard : (insert a (insert b S)).card = 2 ∨ + (insert a (insert b S)).card = 4 := by + rw [Finset.card_insert_of_notMem (by simp [ha,hab.ne]), + Finset.card_insert_of_notMem hb] + omega + have h := hole_relocation hn w u hu hz hwu hrlo hrhi + (insert a (insert b S)) hcard a b (by simp) (by simp) hab.ne + have hB : 0 < bottleneck w a b := lt_of_lt_of_le (by norm_num) (one_le_bottleneck w a b) + have hmul : bottleneck w a b * holeRatio u (insert a (insert b S)) ≤ + 100000 * Fintype.card V := by + have hh := (le_div_iff₀ hB).mp h + simpa only [mul_comm] using hh + unfold holeAugmentation + rw [div_mul_eq_mul_div] + exact div_le_div_of_nonneg_right hmul holeScale_pos.le + +theorem augmented_hole_rate_le [Fintype V] [LinearOrder V] + (hn : 2 ≤ Fintype.card V) (w u : V → V → ℝ) + (hu : ∀ a b, 0 ≤ u a b) (hz : 0 < partition u ∅) + (hwu : ∀ a b, w a b ≤ u a b) + (hrlo : ∀ a, (1:ℝ)/8 ≤ rowMax hn u a) (hrhi : ∀ a, rowMax hn u a ≤ 4) + (S : Finset V) (hS : S.card = 0 ∨ S.card = 2) : + edgeSum S (fun a b => holeAugmentation w a b * + holeRatio u (insert a (insert b S))) ≤ (1:ℝ)/1000 := by + have hsum := edgeSum_le_card_sq S _ _ + (show 0 ≤ 100000 * (Fintype.card V : ℝ) / holeScale V by + exact div_nonneg (by positivity) holeScale_pos.le) + (augmented_hole_summand hn w u hu hz hwu hrlo hrhi S hS) + apply hsum.trans + rw [← mul_div_assoc, div_le_iff₀ holeScale_pos] + have hnon : (0:ℝ) ≤ Fintype.card V := Nat.cast_nonneg _ + have hp : (Fintype.card V : ℝ)^3 ≤ ((Fintype.card V : ℝ)+1)^4 := by + calc + _ ≤ ((Fintype.card V : ℝ)+1)^3 := pow_le_pow_left₀ hnon (by linarith) 3 + _ ≤ _ := pow_le_pow_right₀ (by linarith) (by omega) + unfold holeScale + nlinarith only [hp] + +theorem row_lower_of_partition_inflation [Fintype V] [LinearOrder V] + (hn : 2 ≤ Fintype.card V) (w u : V → V → ℝ) + (hw : ∀ a b, 0 ≤ w a b) (hz : 0 < partition w ∅) (huZ : 0 < partition u ∅) + (hwu : ∀ a b, w a b ≤ u a b) (hinfl : partition u ∅ ≤ 2 * partition w ∅) + (hrlo : ∀ a, (1:ℝ)/4 ≤ rowMax hn w a) : + ∀ a, (1:ℝ)/8 ≤ rowMax hn u a := by + intro a + obtain ⟨b,hba,hb⟩ := rowMax_attained hn w a + apply le_trans _ (holeRatio_le_rowMax hn u a b hba.symm) + have hg0 : (1:ℝ)/4 ≤ holeRatio w {a,b} := by rw [hb]; exact hrlo a + have hnum := partition_mono w u hw hwu {a,b} + rw [holeRatio, le_div_iff₀ hz] at hg0 + rw [holeRatio, le_div_iff₀ huZ] + linarith + +theorem normalized_partition_hasDerivAt [Fintype V] [LinearOrder V] + (w d : V → V → ℝ) (t : ℝ) (hz0 : partition w ∅ ≠ 0) + (hzt : partition (affineWeights w d t) ∅ ≠ 0) : + HasDerivAt (fun s => partition (affineWeights w d s) ∅ / partition w ∅) + ((edgeSum ∅ (fun a b => d a b * holeRatio (affineWeights w d t) {a,b})) * + (partition (affineWeights w d t) ∅ / partition w ∅)) t := by + have hh := (partition_hasDerivAt w d ∅ t).div_const (partition w ∅) + apply hh.congr_deriv + simp only [holeRatio, ← mul_div_assoc, edgeSum_div, Finset.insert_empty] + field_simp + +theorem logical_inflation [Fintype V] [LinearOrder V] + (hn : 2 ≤ Fintype.card V) (w : V → V → ℝ) + (hw : ∀ a b, 0 ≤ w a b) (hz : 0 < partition w ∅) + (hrlo : ∀ a, (1:ℝ)/4 ≤ rowMax hn w a) (hrhi : ∀ a, rowMax hn w a ≤ 1) : + partition (affineWeights w (holeAugmentation w) 1) ∅ < 2 * partition w ∅ := by + let d := holeAugmentation w + let u := affineWeights w d + have hd : ∀ a b, 0 ≤ d a b := holeAugmentation_nonneg w + have hwu : ∀ t, 0 ≤ t → ∀ a b, w a b ≤ u t a b := by + intro t ht a b + exact le_add_of_nonneg_right (mul_nonneg ht (hd a b)) + have hun : ∀ t, 0 ≤ t → ∀ a b, 0 ≤ u t a b := by + intro t ht a b + exact (hw a b).trans (hwu t ht a b) + have huz : ∀ t, 0 ≤ t → 0 < partition (u t) ∅ := by + intro t ht + exact affine_partition_pos w d hw hd hz t ht + let I := Option {p : V × V // p.1 ≠ p.2} + let f : I → ℝ → ℝ := fun i t => match i with + | none => partition (u t) ∅ / partition w ∅ + | some p => holeRatio (u t) {p.1.1,p.1.2} + have hf : ∀ i, ContinuousOn (f i) (Set.Icc 0 1) := by + intro i t ht + cases i with + | none => + exact ((partition_hasDerivAt w d ∅ t).div_const (partition w ∅)).continuousAt.continuousWithinAt + | some p => + exact (holeRatio_hasDerivAt w d _ t (huz t ht.1).ne').continuousAt.continuousWithinAt + have hinit : ∀ i, f i 0 ≤ 1 := by + intro i + cases i with + | none => + change partition (u 0) ∅ / partition w ∅ ≤ 1 + have he : u 0 = w := by funext a b; simp [u,affineWeights] + rw [he,div_self hz.ne'] + | some p => + change holeRatio (u 0) {p.1.1,p.1.2} ≤ 1 + have he : u 0 = w := by funext a b; simp [u,affineWeights] + rw [he] + exact (holeRatio_le_rowMax hn w p.1.1 p.1.2 p.2).trans (hrhi p.1.1) + have hderiv : ∀ t ∈ Set.Ioo 0 1, (∀ i, f i t < 2) → + ∀ i, HasDerivAt (f i) (deriv (f i) t) t ∧ deriv (f i) t ≤ (1:ℝ)/500 := by + intro t ht hstay + have hZ : partition (u t) ∅ < 2 * partition w ∅ := + (div_lt_iff₀ hz).mp (hstay none) + have hl := row_lower_of_partition_inflation hn w (u t) hw hz (huz t ht.1.le) + (hwu t ht.1.le) hZ.le hrlo + have hh : ∀ a, rowMax hn (u t) a ≤ 4 := by + intro a + obtain ⟨b,hba,hb⟩ := rowMax_attained hn (u t) a + have hh := hstay (some ⟨(a,b),hba.symm⟩) + change holeRatio (u t) {a,b} < 2 at hh + rw [hb] at hh + linarith + let rate := edgeSum ∅ (fun a b => d a b * holeRatio (u t) {a,b}) + have hrate0 : 0 ≤ rate := edgeSum_nonneg ∅ _ (fun a b _ _ _ => + mul_nonneg (hd a b) (holeRatio_nonneg (u t) (hun t ht.1.le) {a,b})) + have hrate : rate ≤ (1:ℝ)/1000 := by + simpa only [Finset.insert_empty] using + augmented_hole_rate_le hn w (u t) (hun t ht.1.le) (huz t ht.1.le) + (hwu t ht.1.le) hl hh ∅ (Or.inl rfl) + intro i + cases i with + | none => + have hdf := normalized_partition_hasDerivAt w d t hz.ne' (huz t ht.1.le).ne' + change HasDerivAt (f none) (rate * f none t) t at hdf + refine ⟨hdf.differentiableAt.hasDerivAt, ?_⟩ + rw [hdf.deriv] + have hle : rate * f none t ≤ rate * 2 := mul_le_mul_of_nonneg_left (hstay none).le hrate0 + linarith + | some p => + have hdf := holeRatio_hasDerivAt w d {p.1.1,p.1.2} t (huz t ht.1.le).ne' + change HasDerivAt (f (some p)) _ t at hdf + refine ⟨hdf.differentiableAt.hasDerivAt, ?_⟩ + rw [hdf.deriv] + have hpcard : ({p.1.1,p.1.2} : Finset V).card = 2 := by simp [p.2] + have hnum := augmented_hole_rate_le hn w (u t) (hun t ht.1.le) (huz t ht.1.le) + (hwu t ht.1.le) hl hh {p.1.1,p.1.2} (Or.inr hpcard) + have hg := holeRatio_nonneg (u t) (hun t ht.1.le) {p.1.1,p.1.2} + have hprod := mul_nonneg hg hrate0 + change 0 ≤ holeRatio (u t) {p.1.1,p.1.2} * rate at hprod + change edgeSum {p.1.1,p.1.2} (fun a b => d a b * + holeRatio (u t) (insert a (insert b {p.1.1,p.1.2}))) - + holeRatio (u t) {p.1.1,p.1.2} * rate ≤ (1:ℝ)/500 + change edgeSum {p.1.1,p.1.2} (fun a b => d a b * + holeRatio (u t) (insert a (insert b {p.1.1,p.1.2}))) ≤ (1:ℝ)/1000 at hnum + linarith + have hstay := finite_family_barrier f (fun i => deriv (f i)) ((1:ℝ)/500) + (by norm_num) (by norm_num) hf hinit hderiv 1 (by constructor <;> norm_num) none + exact (div_lt_iff₀ hz).mp hstay + +end MatchingFPRAS.Switching + +end OAI diff --git a/lean/OAI/Combinatorics/MatchingCount/Algorithm/Algorithm.lean b/lean/OAI/Combinatorics/MatchingCount/Algorithm/Algorithm.lean new file mode 100644 index 0000000000000000000000000000000000000000..af4c13e519e7f10523004af4ccf128be5d0336f4 --- /dev/null +++ b/lean/OAI/Combinatorics/MatchingCount/Algorithm/Algorithm.lean @@ -0,0 +1,103 @@ +import Mathlib +import OAI.Combinatorics.MatchingCount.Algorithm.OnlineInitialLaw +import OAI.Combinatorics.MatchingCount.Tapes.Input +import OAI.Combinatorics.MatchingCount.Sampling.Endpoints2 +import OAI.Combinatorics.MatchingCount.Machines.OnlineCase +import OAI.Combinatorics.MatchingCount.Graphs.OnlineGraphInvariant + +namespace OAI + +namespace MatchingFPRAS.LiteralAlgorithm +open TreeTyped TreeFraction PhysicalStream LiteralInput Polynomial + +def empty (x : Parsed) : Bool := decide (x.1=0) +def emptyRealizer : Realizer empty := composition (pair first (constant 0)) natEqual +lemma polynomial_empty : PolynomialTime emptyRealizer := by + exact polynomial_composition (polynomial_pair polynomial_first (polynomial_constant 0)) polynomial_natEqual + +def invalid (x : Parsed) : Bool := !(decide (x.1%2=0)) || ExecutableInput.tooSparse (x.1,x.2.1) +def invalidRealizer : Realizer invalid := + (choose (composition first ExecutableSource.evenTest) + (composition (pair first second.fst) ExecutableInput.tooSparseRealizer) (constant true)).congr (by + intro x + unfold invalid + cases h : decide (x.1%2=0) <;> simp only [Function.comp_apply,h,Bool.not_true,Bool.not_false,Bool.false_or,Bool.true_or,Bool.false_eq_true,ite_false,ite_true]) +lemma polynomial_invalid : PolynomialTime invalidRealizer := by + unfold invalidRealizer Realizer.fst + apply polynomial_congr + have := ExecutableSource.polynomial_evenTest + have := ExecutableInput.polynomial_tooSparse + tree_cost + +def materialize (x : Parsed) : OnlineInitial.Seed := ((List.range x.1,x.2.1),x.2.2) +def materializeRealizer : Realizer materialize := + pair (pair (composition first range) second.fst) second.snd +lemma work_materialize : WorkBound materializeRealizer (fun x=>x.1+weight x) := by + have lift {A : Type} [Codec A] {f : Parsed→A} {F : Realizer f} (hF : PolynomialTime F) : + WorkBound F (fun x=>x.1+weight x) := work_of_polynomial hF X (by intro x;simp) + unfold materializeRealizer Realizer.fst Realizer.snd + apply work_pair _ (lift (by tree_cost)) X (by intro x;simp) + apply work_pair _ (lift (by tree_cost)) X (by intro x;simp) + apply work_composition (lift polynomial_first) range_numeric_work X + intro x;simp + +def compute (x : Parsed) : Experiment Fraction := + OnlineAmplification.run (OnlineInitial.initializeInput (materialize x)) +noncomputable def computeRealizer : OnlineTree.Realizer compute := + (OnlineTree.composition (OnlineTree.deterministic + (composition materializeRealizer OnlineInitial.initializeInputRealizer)) OnlineAmplification.runRealizer).congr (fun _ _=>rfl) + +def count (x : Parsed) : Experiment Fraction := + if empty x then .done (1,1) else if invalid x then .done (0,1) else compute x +noncomputable def countRealizer : OnlineTree.Realizer count := + (OnlineTree.conditional emptyRealizer (OnlineTree.deterministic (constant (1,1))) + (OnlineTree.conditional invalidRealizer (OnlineTree.deterministic (constant (0,1))) computeRealizer)).congr (fun _ _=>rfl) + +def algorithm (as : List Symbol) : Experiment (List Symbol) := + (count (parseInput as)).map LiteralCodec.ratWord +noncomputable def algorithmRealizer : OnlineTree.Realizer algorithm := + (OnlineTree.composition (OnlineTree.composition (OnlineTree.deterministic parseInputRealizer) countRealizer) + (OnlineTree.deterministic LiteralCodec.ratWordRealizer)).congr (by + intro as h;simp only [algorithm,Experiment.mean_bind,Experiment.mean,Experiment.mean_map]) + +lemma edgeNumbers_length (G : GraphInput) : (edgeNumbers G).length=G.edges.card := by + simp only [edgeNumbers,List.length_map,Finset.length_sort,Finset.card_map] +lemma edgeNumbers_mem (G : GraphInput) (e : ℕ×ℕ) : + e∈edgeNumbers G ↔ e∈(ExecutableAdaptive.graphRep G).2 := by + classical + simp only [edgeNumbers,ExecutableAdaptive.graphRep,List.mem_map,Finset.mem_sort, + Finset.mem_map,Finset.mem_toList] + constructor + · rintro ⟨a,⟨b,hb,rfl⟩,he⟩ + exact ⟨b,hb,he⟩ + · rintro ⟨b,hb,he⟩ + exact ⟨toLex b,⟨b,hb,rfl⟩,he⟩ +noncomputable def reorder (G : GraphInput) (es : OnlineGraph.Edges) : OnlineGraph.Edges := + if es=(ExecutableAdaptive.graphRep G).2 then edgeNumbers G else es +lemma reorder_mem (G : GraphInput) (es : OnlineGraph.Edges) (e : ℕ×ℕ) : + e∈reorder G es ↔ e∈es := by + classical + unfold reorder + split + · rename_i he;rw [he];exact edgeNumbers_mem G e + · rfl +lemma materialize_source (G : GraphInput) (ε δ : ℚ) : + materialize (parseInput (encodeInput G ε δ))= + OnlineGraph.seed (reorder G) (OnlineInitial.sourceSeed (G:=G) ε δ) := by + rw [parseInput_source] + unfold materialize OnlineGraph.seed OnlineGraph.graph OnlineInitial.sourceSeed reorder + simp only [ite_true] + rfl +lemma compute_mean {G : GraphInput} [Nontrivial (Fin G.n)] + (hn : 2≤G.n) (hev : Even G.n) (ε δ : ℚ) (he : 0<ε) (he1 : ε<1) (hd : 0≤δ) + (h : Fraction→ℚ) : + (compute (parseInput (encodeInput G ε δ))).mean h= + PhysicalStream.qaverage (fun b=>h (TreeFraction.repr + (FiniteTrial.guardedAmplifiedBitOutput (FiniteTrial.parameters G hn hev ε he he1) δ b))) := by + unfold compute + rw [materialize_source,OnlineGraph.initialize_mean (reorder G) (reorder_mem G), + OnlineInitial.initializeInput_source hn hev ε δ he he1 hd] + exact OnlineAmplification.run_mean _ δ h +end MatchingFPRAS.LiteralAlgorithm + +end OAI diff --git a/lean/OAI/Combinatorics/MatchingCount/Algorithm/AlgorithmLaw.lean b/lean/OAI/Combinatorics/MatchingCount/Algorithm/AlgorithmLaw.lean new file mode 100644 index 0000000000000000000000000000000000000000..984815b7192308b4ae486423c1a612de2e997aae --- /dev/null +++ b/lean/OAI/Combinatorics/MatchingCount/Algorithm/AlgorithmLaw.lean @@ -0,0 +1,152 @@ +import Mathlib +import OAI.Combinatorics.MatchingCount.Algorithm.Algorithm +import OAI.Combinatorics.MatchingCount.Complexity.OnlineHistoryCost + +namespace OAI + +namespace MatchingFPRAS.PhysicalStream +lemma qaverage_mono {A : Type} [Fintype A] (f g : A→ℚ) (h : ∀ a,f a≤g a) : qaverage f≤qaverage g := by + unfold qaverage + exact div_le_div_of_nonneg_right (Finset.sum_le_sum (fun a _=>h a)) (Nat.cast_nonneg _) +lemma qaverage_indicator {A : Type} [Fintype A] (P : A→Prop) [DecidablePred P] : + qaverage (fun a=>if P a then 1 else 0)=((Finset.univ.filter P).card:ℚ)/Fintype.card A := by + simp only [qaverage,Finset.sum_boole] +namespace Experiment +lemma mean_mono {A : Type} (p : Experiment A) (f g : A→ℚ) (h : p.All (fun a=>f a≤g a)) : p.mean f≤p.mean g := by + induction p with + | done a => exact h + | delay n p ih => exact ih h + | read p ih => exact div_le_div_of_nonneg_right (add_le_add (ih false h.1) (ih true h.2)) (by norm_num) +lemma mean_const {A : Type} (p : Experiment A) (q : ℚ) : p.mean (fun _=>q)=q := by + induction p with + | done a => rfl + | delay n p ih => exact ih + | read p ih => simp only [mean,ih];ring +lemma mean_indicator_eq_one {A : Type} (p : Experiment A) (P : A→Prop) [DecidablePred P] + (h : p.All P) : p.mean (fun a=>if P a then 1 else 0)=1 := by + induction p with + | done value => exact ite_eq_left h + | delay ticks experiment ih => exact ih h + | read next ih => norm_num [mean,ih false h.1,ih true h.2] +end Experiment +end MatchingFPRAS.PhysicalStream + +namespace MatchingFPRAS.LiteralAlgorithm +open scoped Classical +open TreeTyped TreeFraction PhysicalStream LiteralInput + +lemma empty_source (G : GraphInput) (ε δ : ℚ) : empty (parseInput (encodeInput G ε δ))=decide (G.n=0) := by + rw [parseInput_source];rfl +lemma invalid_source (G : GraphInput) (ε δ : ℚ) : invalid (parseInput (encodeInput G ε δ))= + (!(decide (G.n%2=0)) || decide (2*G.edges.cardhe (Nat.even_iff.mpr hm) + simp only [he',decide_false,Bool.not_false,Bool.true_or,Bool.true_eq_false] at h +lemma valid_size (G : GraphInput) (ε δ : ℚ) (h : invalid (parseInput (encodeInput G ε δ))=false) : + G.n≤2*(encodeInput G ε δ).length := by + rw [invalid_source] at h + have hh : ¬2*G.edges.card + have hn : G.n=0 := of_decide_eq_true (by rwa [empty_source] at hE) + have hz:=count_empty_graph hn + simp only [count,hE,ite_true,Experiment.All] + exact ⟨1,by norm_num,hen,by intro h;omega⟩ + | false => + cases hI:invalid (parseInput (encodeInput G ε δ)) with + | true => + simp only [count,hE,hI,Bool.false_eq_true,ite_false,ite_true,Experiment.All] + exact ⟨0,by norm_num,hzero,fun _=>rfl⟩ + | false => + simp only [count,hE,hI,Bool.false_eq_true,ite_false] + have hn:=valid_two G ε δ hE hI + have hev:=valid_even G ε δ hI + let : Nontrivial (Fin G.n):=Fin.nontrivial_iff_two_le.mpr hn + apply Experiment.all_of_qaverage _ (fun b=>TreeFraction.repr + (FiniteTrial.guardedAmplifiedBitOutput (FiniteTrial.parameters G hn hev ε he he1) δ b)) + · exact compute_mean hn hev ε δ he he1 hd + · intro b + let p:=FiniteTrial.parameters G hn hev ε he he1 + have hq:=FiniteTrial.guardedAmplifiedBitOutput_nonneg p δ b + exact ⟨_,hq,LiteralCodec.ratWord_repr _ hq,fun hz=>FiniteTrial.guardedAmplifiedBitOutput_zero p hz δ b⟩ + +lemma accurate_zero (G : GraphInput) (ε : ℚ) (hz : Z G=0) : AccurateWord G ε (encodeRat 0) := by + refine ⟨0,rfl,?_,?_⟩ <;> simp [hz] +lemma proper_accurate_zero (G : GraphInput) (ε : ℚ) (hz : Z G=0) (as : List Symbol) (ha : Proper G as) : + AccurateWord G ε as := by + obtain ⟨q,_,rfl,hq⟩:=ha + rw [hq hz] + exact accurate_zero G ε hz + +lemma algorithm_success (G : GraphInput) (ε δ : ℚ) (he : 0<ε) (he1 : ε<1) (hd : 0<δ) : + 1-δ≤(algorithm (encodeInput G ε δ)).mean (fun as=>if AccurateWord G ε as then 1 else 0) := by + classical + by_cases hz:Z G=0 + · rw [Experiment.mean_indicator_eq_one _ _ ((algorithm_proper G ε δ he he1 hd.le).mono + (proper_accurate_zero G ε hz))] + linarith + have hZ:0 + have hn : G.n=0 := of_decide_eq_true (by rwa [empty_source] at hE) + have hz:=count_empty_graph hn + have hq : AccurateWord G ε (LiteralCodec.ratWord (1,1)) := by + refine ⟨1,LiteralCodec.ratWord_repr 1 (by norm_num),?_,?_⟩ <;> rw [hz] <;> norm_num <;> linarith + simp only [algorithm,Experiment.mean_map,count,hE,ite_true,Experiment.mean,ite_eq_left hq] + linarith + | false => + have hI:invalid (parseInput (encodeInput G ε δ))=false := by + cases hi:invalid (parseInput (encodeInput G ε δ)) with + | false => rfl + | true => exact False.elim (hz (invalid_zero G ε δ hi)) + have hn:=valid_two G ε δ hE hI + have hev:=valid_even G ε δ hI + let : Nontrivial (Fin G.n):=Fin.nontrivial_iff_two_le.mpr hn + let p:=FiniteTrial.parameters G hn hev ε he he1 + have hs:=FiniteTrial.guardedAmplifiedBitOutput_success p hZ δ hd + have hb : qaverage (fun b=>if FiniteTrial.Accurate p (FiniteTrial.guardedAmplifiedBitOutput p δ b) then 1 else 0)≥1-δ := by + rw [qaverage_indicator] + simpa only [FiniteTrial.guardedAccurateBits,Fintype.card_fun,Fintype.card_fin,Fintype.card_bool,Nat.cast_pow,Nat.cast_ofNat] using hs + simp only [algorithm,Experiment.mean_map,count,hE,hI,Bool.false_eq_true,ite_false] + rw [compute_mean hn hev ε δ he he1 hd.le] + apply hb.trans (qaverage_mono _ _ (fun b=>?_)) + split_ifs with ha hword hword + · rfl + · exfalso + apply hword + exact ⟨_,LiteralCodec.ratWord_repr _ (FiniteTrial.guardedAmplifiedBitOutput_nonneg p δ b),ha⟩ + · norm_num + · rfl +end MatchingFPRAS.LiteralAlgorithm + +end OAI diff --git a/lean/OAI/Combinatorics/MatchingCount/Algorithm/EmpiricalDenom.lean b/lean/OAI/Combinatorics/MatchingCount/Algorithm/EmpiricalDenom.lean new file mode 100644 index 0000000000000000000000000000000000000000..3bd3bad61995d818fe9992779c336cf7b2c13c66 --- /dev/null +++ b/lean/OAI/Combinatorics/MatchingCount/Algorithm/EmpiricalDenom.lean @@ -0,0 +1,424 @@ +import Mathlib +import OAI.Combinatorics.MatchingCount.Algorithm.SortedList + +namespace OAI + +namespace MatchingFPRAS.Trial +open Finset Switching Subdivision RealGeometry Hierarchy Transport Enlargement StageAnalysis BitArithmetic +open scoped Classical + +variable {G : GraphInput} {j K S : ℕ} [Nontrivial (Fin G.n)] +def empiricalDenom (G : GraphInput) (K : ℕ) : ℕ := (G.n+1)^Fintype.card (SourceVertex (Fin G.n) K) +lemma empiricalDenom_pos (G : GraphInput) (K : ℕ) : 0(s.observables_grid hn (x i)).1)).fractionBound hpos + · exact (GridFraction.average _ x (fun i=>(s.observables_grid hn (x i)).2.1)).fractionBound hpos + · intro e₀ + exact (GridFraction.average _ x (fun i=>(s.observables_grid hn (x i)).2.2 e₀)).fractionBound hpos +end MatchingFPRAS.Trial + +namespace MatchingFPRAS.BitArithmetic +open Finset + +lemma alpha_bits : FractionBound 100000 RealStage.alpha := by + exact ⟨1,100000,by norm_num,by norm_num,le_rfl,by norm_num [RealStage.alpha]⟩ +def matrixBound (D B : ℕ) : ℕ := 200000*(D+1)*B^2 +lemma matrixBound_large (D B : ℕ) (hB : 1≤B) : 100000 ≤ matrixBound D B := by + unfold matrixBound + have hb2 : 1≤B^2 := one_le_pow₀ hB + nlinarith +lemma ratioEstimate_bits {B : ℕ} {a d : ℝ} (hB : 1≤B) + (ha : FractionBound B a) (hd : FractionBound B d) : + FractionBound (B^2) (RealStage.ratioEstimate a d) := by + unfold RealStage.ratioEstimate + split_ifs with h + · simpa [pow_two] using hd.div ha h + · exact FractionBound.one (one_le_pow₀ hB) +lemma upperEstimate_bits (D : ℕ) {B : ℕ} {d z : ℝ} (hB : 1≤B) + (hd : FractionBound B d) (hz : FractionBound B z) : + FractionBound (matrixBound D B) (RealStage.upperEstimate D d z) := by + have hlarge := matrixBound_large D B hB + unfold RealStage.upperEstimate + split_ifs with h + · have ht : FractionBound (matrixBound D B) ((D:ℝ)*z/d+RealStage.alpha) := by + convert (((FractionBound.nat D).mul hz).div hd h).add alpha_bits using 1 + unfold matrixBound + ring + exact (alpha_bits.mono hlarge).max + ((FractionBound.nat 3 |>.mono (by omega)).min ht) + · exact FractionBound.one (by omega) +lemma scalingTrace_bits {n : ℕ} (hn : 2≤n) (G : Fin n → Fin n → ℝ) + (hsym : ∀ i j,G i j=G j i) (hG : ∀ i j,i≠j → RealStage.alpha≤G i j ∧ G i j≤3) + (B : ℕ) (hB : 2≤B) (hb : ∀ i j,FractionBound B (G i j)) (k : ℕ) : + ∀ i,FractionBound (B^(k+1)) (RealStage.scalingTrace hn G k i) := by + have hB1 : 1≤B := by omega + induction k with + | zero => + intro i + change FractionBound (B^(0+1)) 2 + simpa using (show FractionBound B (2:ℝ) from ⟨2,1,by omega,hB,hB1,by norm_num⟩) + | succ k ih => + intro i + have hmono : B^(k+1)≤B^(k+1+1) := Nat.pow_le_pow_right hB1 (by omega) + dsimp only [RealStage.scalingTrace] + split_ifs with hk + · unfold RealStage.scaleUpdate + by_cases hi : i=⟨k,hk⟩ + · subst i + simp only [Function.update_self] + unfold RealStage.rowMaximum + have hpos := (RealStage.scalingTrace_invariant hn G hsym hG k).1.pos + convert FractionBound.sup' (univ.erase (⟨k,hk⟩ : Fin n)) (RealStage.others_nonempty hn _) + (fun j=>G ⟨k,hk⟩ j / RealStage.scalingTrace hn G k j) (B*B^(k+1)) + (fun j _=>(hb ⟨k,hk⟩ j).div (ih j) (hpos j)) using 1 + rw [pow_succ,Nat.mul_comm] + · rw [Function.update_of_ne hi] + exact (ih i).mono hmono + · exact (ih i).mono hmono +end MatchingFPRAS.BitArithmetic + +namespace MatchingFPRAS.Trial +open Finset Switching Subdivision RealGeometry Hierarchy Transport Enlargement StageAnalysis BitArithmetic +open scoped Classical + +variable {G : GraphInput} {j K S : ℕ} [Nontrivial (Fin G.n)] +lemma ScaleState.ratioEstimate_bits (hn : 0s.matrix_bounds x a b) _ _ (fun a b=>s.matrix_bits (by omega) hS x a b) + have hh := matrixBound_large (sourceD (V:=Fin G.n) K) (S*empiricalDenom G K) + (Nat.mul_pos hS (empiricalDenom_pos G K)) + omega +open Finset Switching Subdivision RealGeometry Hierarchy Transport Enlargement StageAnalysis BitArithmetic +open scoped Classical + +variable {G : GraphInput} [Nontrivial (Fin G.n)] +omit [Nontrivial (Fin G.n)] in +lemma initial_scale_bits (hn : 2≤G.n) (a : Fin G.n) : + FractionBound (G.n+1) ((initialScaleState G hn).scale a) := by + refine ⟨1,Nat.sqrt (G.n-1),?_,by omega,?_,?_⟩ + · exact Nat.le_sqrt.mpr (by omega) + · exact (Nat.sqrt_le_self _).trans (by omega) + · change (Initializer.initialScale G.n:ℝ)=_ + simp [Initializer.initialScale] + +noncomputable def Parameters.empiricalBound (p : Parameters G) : ℕ := p.S*empiricalDenom G p.K +noncomputable def Parameters.matrixBound (p : Parameters G) : ℕ := BitArithmetic.matrixBound p.D p.empiricalBound +lemma Parameters.empiricalBound_pos (p : Parameters G) : 0.scale a) := by + induction j with + | zero => simpa [layers,firstLayer,Parameters.scaleBound] using initial_scale_bits p.hn a + | succ j ih => + change FractionBound _ (((layers p j (by omega)).state x.1).scale a * + ((layers p j (by omega)).state x.1).updateVector p.hn x.2 a) + have hv := ((layers p j (by omega)).state x.1).updateVector_bits p.hn p.S_pos x.2 a + have hh := (ih (by omega) x.1).mul hv + convert hh using 1 + change (G.n+1)*p.matrixBound^((j+1)*(G.n+1))= + ((G.n+1)*p.matrixBound^(j*(G.n+1)))*p.matrixBound^(G.n+1) + rw [add_mul, one_mul, pow_add] + ring +lemma layers_ratio_bits (p : Parameters G) (j : ℕ) (hj : j≤p.K) + (x : (layers p j hj).Ω) (i : Fin j) : + FractionBound (p.empiricalBound^2) ((layers p j hj).ratios x i) := by + induction j with + | zero => exact Fin.elim0 i + | succ j ih => + refine Fin.lastCases ?_ (fun i=>?_) i + · simpa only [layers,Layer.append,Fin.snoc_last,Parameters.empiricalBound] using + ((layers p j (by omega)).state x.1).ratioEstimate_bits (by have := p.hn; omega) p.S_pos x.2 + · simpa only [layers,Layer.append,Fin.snoc_castSucc] using ih (by omega) x.1 i +lemma output_bits (p : Parameters G) (x : (layers p p.K le_rfl).Ω) : + FractionBound ((Z (completeGraph G.n)+1)*(p.empiricalBound^2)^p.K) (output p x) := by + have h := FractionBound.prod univ ((layers p p.K le_rfl).ratios x) (p.empiricalBound^2) + (fun i _=>layers_ratio_bits p p.K le_rfl x i) + simpa [output] using (FractionBound.nat (Z (completeGraph G.n))).mul h + +noncomputable def rationalOutput (p : Parameters G) (x : (layers p p.K le_rfl).Ω) : ℚ := + (output_bits p x).choose / (output_bits p x).choose_spec.choose +lemma rationalOutput_cast (p : Parameters G) (x : (layers p p.K le_rfl).Ω) : + (rationalOutput p x:ℝ)=output p x := by + have h := (output_bits p x).choose_spec.choose_spec.2.2.2 + simpa [rationalOutput] using h.symm +lemma rationalOutput_nonneg (p : Parameters G) (x : (layers p p.K le_rfl).Ω) : + 0≤rationalOutput p x := by + exact_mod_cast (show (0:ℝ)≤(rationalOutput p x:ℝ) by rw [rationalOutput_cast]; exact output_nonneg p x) +lemma rationalOutput_accurate (p : Parameters G) (x : (layers p p.K le_rfl).Ω) : + Accurate p (output p x) ↔ + (1-p.epsilon)*(Z G:ℚ)≤rationalOutput p x ∧ rationalOutput p x≤(1+p.epsilon)*(Z G:ℚ) := by + rw [← rationalOutput_cast p x] + unfold Accurate + norm_cast +end MatchingFPRAS.Trial + +namespace MatchingFPRAS.FiniteTrial +open Finset Enlargement Transport BitArithmetic +open scoped Classical + +variable {G : GraphInput} {j K S : ℕ} [Nontrivial (Fin G.n)] +attribute [local instance] NumberedHierarchy.labelOrder sym2Order bagEdgeOrder bagEdgeFintype +attribute [local instance] UnitRefresh.Computable.allowedDec prodOrder sumOrder +noncomputable local instance (w : Fin G.n → Fin G.n → ℚ) (K : ℕ) : + DecidableEq (SourceLabel (fun x y=>(w x y:ℝ)) K) := Classical.decEq _ +noncomputable local instance (w : Fin G.n → Fin G.n → ℚ) (K : ℕ) : + Fintype (BagEdge (sourceBags (fun x y=>(w x y:ℝ)) K)) := Fintype.ofFinite _ +noncomputable local instance (w : Fin G.n → Fin G.n → ℚ) (K : ℕ) : + Fintype (SourceMarked (fun x y=>(w x y:ℝ)) K) := Fintype.ofFinite _ +lemma ScaleState.ratioEstimate_bits (hn : 0(s.activity a b:ℝ)) K) : + FractionBound ((S*Trial.empiricalDenom G K)^2) + (s.ratioEstimate (RationalSource.sourceMarkedEquiv s.activity K ∘ x):ℝ) := by + have hb := s.toReal.ratioEstimate_bits (K:=K) (S:=S) hn hS + unfold Trial.ScaleState.ratioEstimate at hb + rw [←s.activity_cast,←s.nextActivity_cast] at hb + rw [s.ratioEstimate_cast] + exact hb x +lemma ScaleState.matrix_bits (hn : 0(s.activity a b:ℝ)) K) (a b : Fin G.n) : + FractionBound (matrixBound (Enlargement.sourceD (V:=Fin G.n) K) (S*Trial.empiricalDenom G K)) + (s.matrix (RationalSource.sourceMarkedEquiv s.activity K ∘ x) a b:ℝ) := by + have hb := s.toReal.matrix_bits (K:=K) (S:=S) hn hS + unfold Trial.ScaleState.matrix at hb + rw [←s.activity_cast,←s.nextActivity_cast] at hb + have he := congrFun (congrFun (s.matrix_cast x) a) b + rw [he,sourceD_eq] + exact hb x a b +lemma ScaleState.updateVector_bits (hn : 2≤G.n) (s : ScaleState G j) (hS : 0(s.activity a b:ℝ)) K) (a : Fin G.n) : + FractionBound ((matrixBound (Enlargement.sourceD (V:=Fin G.n) K) (S*Trial.empiricalDenom G K))^(G.n+1)) + (s.updateVector hn (RationalSource.sourceMarkedEquiv s.activity K ∘ x) a:ℝ) := by + rw [ScaleState.updateVector,Counting.scalingTrace_cast] + apply scalingTrace_bits hn _ _ _ _ _ _ _ a + · intro a b + exact_mod_cast s.matrix_symm _ a b + · intro a b _ + have h:=s.matrix_bounds (RationalSource.sourceMarkedEquiv s.activity K ∘ x) a b + constructor + · have hh : ((Counting.alpha:ℚ):ℝ) ≤ (s.matrix (RationalSource.sourceMarkedEquiv s.activity K ∘ x) a b:ℝ) := by exact_mod_cast h.1 + simpa [Counting.alpha,RealStage.alpha] using hh + · exact_mod_cast h.2 + · have h:=matrixBound_large (Enlargement.sourceD (V:=Fin G.n) K) (S*Trial.empiricalDenom G K) + (Nat.mul_pos hS (Trial.empiricalDenom_pos G K)) + omega + · intro a b + exact s.matrix_bits (by omega) hS x a b +omit [Nontrivial (Fin G.n)] in +lemma initial_scale_bits (hn : 2≤G.n) (a : Fin G.n) : + FractionBound (G.n+1) ((initialScaleState G hn).scale a:ℝ) := by + exact Trial.initial_scale_bits hn a +lemma layers_scale_bits (p : Trial.Parameters G) (j : ℕ) (hj : j≤p.K) + (x : (layers p j hj).Ω) (a : Fin G.n) : + FractionBound (p.scaleBound j) ((layers p j hj).state x |>.scale a:ℝ) := by + induction j with + | zero => simpa [layers,firstLayer,Trial.Parameters.scaleBound] using initial_scale_bits p.hn a + | succ j ih => + change FractionBound _ ((((layers p j (by omega)).state x.1).scale a * + ((layers p j (by omega)).state x.1).updateVector p.hn + (RationalSource.sourceMarkedEquiv ((layers p j (by omega)).state x.1).activity p.K ∘ x.2) a:ℚ):ℝ) + rw [Rat.cast_mul] + have hv := ((layers p j (by omega)).state x.1).updateVector_bits p.hn p.S_pos x.2 a + have hh := (ih (by omega) x.1).mul hv + convert hh using 1 + change (G.n+1)*p.matrixBound^((j+1)*(G.n+1))= + ((G.n+1)*p.matrixBound^(j*(G.n+1)))*p.matrixBound^(G.n+1) + rw [add_mul,one_mul,pow_add] + ring +lemma layers_ratio_bits (p : Trial.Parameters G) (j : ℕ) (hj : j≤p.K) + (x : (layers p j hj).Ω) (i : Fin j) : + FractionBound (p.empiricalBound^2) ((layers p j hj).ratios x i:ℝ) := by + induction j with + | zero => exact Fin.elim0 i + | succ j ih => + refine Fin.lastCases ?_ (fun i=>?_) i + · simpa only [layers,Layer.append,Fin.snoc_last,Trial.Parameters.empiricalBound] using + ((layers p j (by omega)).state x.1).ratioEstimate_bits (by have := p.hn; omega) p.S_pos x.2 + · simpa only [layers,Layer.append,Fin.snoc_castSucc] using ih (by omega) x.1 i +lemma output_bits (p : Trial.Parameters G) (x : (layers p p.K le_rfl).Ω) : + FractionBound ((Z (completeGraph G.n)+1)*(p.empiricalBound^2)^p.K) (output p x:ℝ) := by + have h := FractionBound.prod univ (fun i=>((layers p p.K le_rfl).ratios x i:ℝ)) (p.empiricalBound^2) + (fun i _=>layers_ratio_bits p p.K le_rfl x i) + simpa [output,Rat.cast_mul,Rat.cast_prod] using (FractionBound.nat (Z (completeGraph G.n))).mul h +end MatchingFPRAS.FiniteTrial + +namespace MatchingFPRAS.BitArithmetic +lemma FractionBound.num_den {B : ℕ} {q : ℚ} (h : FractionBound B (q:ℝ)) : + q.num.natAbs≤B ∧ q.den≤B := by + obtain ⟨a,b,hb,ha,hbb,he⟩:=h + have hq : q=(a:ℚ)/b := by + apply Rat.cast_injective (α:=ℝ) + simpa only [Rat.cast_div,Rat.cast_natCast] using he + have hq' : q=Rat.divInt (a:ℤ) (b:ℤ) := by simpa only [Rat.divInt_eq_div,Int.cast_natCast] using hq + have hb0 : (b:ℤ)≠0 := by exact_mod_cast hb.ne' + have hd : q.den∣b := by + have hh:=Rat.den_dvd (a:ℤ) (b:ℤ) + rw [←hq'] at hh + exact_mod_cast hh + refine ⟨?_,(Nat.le_of_dvd hb hd).trans hbb⟩ + by_cases ha0 : a=0 + · simp [ha0] at hq + simp [hq] + · have hh:=Rat.num_dvd (a:ℤ) hb0 + rw [←hq'] at hh + have hn : q.num.natAbs∣a := by simpa using Int.natAbs_dvd_natAbs.mpr hh + exact (Nat.le_of_dvd (Nat.pos_of_ne_zero ha0) hn).trans ha +lemma size_mul_le (a b : ℕ) : (a*b).size≤a.size+b.size := by + apply Nat.size_le.mpr + rw [pow_add] + have h₁:=Nat.lt_size_self a + have h₂:=Nat.lt_size_self b + have h₃ : 0<(2:ℕ)^a.size := by positivity + nlinarith +lemma size_pow_le (a k : ℕ) : (a^k).size≤k*a.size+1 := by + induction k with + | zero => simp + | succ k ih => + rw [pow_succ] + have h:=size_mul_le (a^k) a + rw [Nat.succ_mul] + omega +lemma FractionBound.encode_length {B : ℕ} {q : ℚ} (h : FractionBound B (q:ℝ)) : + (encodeRat q).length≤2*B.size+3 := by + have hd:=h.num_den + have hn:=Nat.size_le_size hd.1 + have hb:=Nat.size_le_size hd.2 + have he : (encodeRat q).length=q.num.natAbs.size+q.den.size+3 := by + unfold encodeRat encodeInt encodeNat + split_ifs <;> simp [Nat.size_eq_bits_len] <;> omega + rw [he] + omega +lemma size_empiricalBound {G : GraphInput} (p : Trial.Parameters G) : + p.empiricalBound.size≤p.S.size+Fintype.card (Enlargement.SourceVertex (Fin G.n) p.K)*(G.n+1).size+1 := by + unfold Trial.Parameters.empiricalBound Trial.empiricalDenom + exact (size_mul_le _ _).trans (by have h:=size_pow_le (G.n+1) (Fintype.card (Enlargement.SourceVertex (Fin G.n) p.K)); omega) +lemma size_matrixBound {G : GraphInput} (p : Trial.Parameters G) : + p.matrixBound.size≤19+(p.D+1).size+2*p.empiricalBound.size := by + unfold Trial.Parameters.matrixBound matrixBound + have h₁:=size_mul_le (200000*(p.D+1)) (p.empiricalBound^2) + have h₂:=size_mul_le 200000 (p.D+1) + have h₃:=size_pow_le p.empiricalBound 2 + have h₄ : (200000:ℕ).size=18 := by decide + omega +lemma size_scaleBound {G : GraphInput} (p : Trial.Parameters G) (j : ℕ) : + (p.scaleBound j).size≤(G.n+1).size+j*(G.n+1)*p.matrixBound.size+1 := by + unfold Trial.Parameters.scaleBound + have h₁:=size_mul_le (G.n+1) (p.matrixBound^(j*(G.n+1))) + have h₂:=size_pow_le p.matrixBound (j*(G.n+1)) + omega +end MatchingFPRAS.BitArithmetic +namespace MatchingFPRAS.FiniteTrial +open BitArithmetic + +variable {G : GraphInput} [Nontrivial (Fin G.n)] +lemma scale_encode_length (p : Trial.Parameters G) (j : ℕ) (hj : j≤p.K) + (x : (layers p j hj).Ω) (a : Fin G.n) : + (encodeRat (((layers p j hj).state x).scale a)).length ≤ + 2*((G.n+1).size+j*(G.n+1)*(19+(p.D+1).size+2*(p.S.size+ + Fintype.card (Enlargement.SourceVertex (Fin G.n) p.K)*(G.n+1).size+1))+1)+3 := by + have h₁:=(layers_scale_bits p j hj x a).encode_length + have h₂:=size_scaleBound p j + have h₃:=size_matrixBound p + have h₄:=size_empiricalBound p + have hb : (p.scaleBound j).size≤ + (G.n+1).size+j*(G.n+1)*(19+(p.D+1).size+2*(p.S.size+ + Fintype.card (Enlargement.SourceVertex (Fin G.n) p.K)*(G.n+1).size+1))+1 := by + calc + _ ≤ (G.n+1).size+j*(G.n+1)*p.matrixBound.size+1 := h₂ + _ ≤ (G.n+1).size+j*(G.n+1)*(19+(p.D+1).size+2*p.empiricalBound.size)+1 := by gcongr + _ ≤ _ := by gcongr + omega +end MatchingFPRAS.FiniteTrial + +namespace MatchingFPRAS.Counting + +def schedulePolynomial (n : ℕ) (e : ℚ) : ℕ := n*(n*n+32*⌈e⁻¹⌉₊) +lemma polynomial_schedule (n : ℕ) (hn : 2≤n) (e : ℚ) (he : 0(w x y:ℝ)) K) := Classical.decEq _ +noncomputable local instance finiteStageSourceBagEdgeFintype (w : V → V → ℚ) (K : ℕ) : + Fintype (BagEdge (sourceBags (fun x y=>(w x y:ℝ)) K)) := Fintype.ofFinite _ +noncomputable local instance (w : V → V → ℚ) (K : ℕ) : + DecidableEq (BagPM (bags w K)) := Classical.decEq _ +noncomputable local instance (w : V → V → ℚ) (K : ℕ) : + Fintype (BagPM (bags w K)) := Fintype.ofFinite _ +noncomputable local instance (w : V → V → ℚ) (K : ℕ) : + Fintype (Marked w K) := Fintype.ofFinite _ +noncomputable local instance (w : V → V → ℚ) (K : ℕ) : + Fintype (SourceMarked (fun x y=>(w x y:ℝ)) K) := Fintype.ofFinite _ +noncomputable local instance (w : V → V → ℚ) (K t k : ℕ) : + Fintype ((Fin t → Bool) × (BagEdge (bags w K) → Fin k → Bool)) := Fintype.ofFinite _ +local instance (w : V → V → ℚ) (K t k : ℕ) : + Nonempty ((Fin t → Bool) × (BagEdge (bags w K) → Fin k → Bool)) := ⟨(fun _=>false,fun _ _=>false)⟩ +lemma source_transfer_tv (w : V → V → ℚ) (hw : ∀ x y,0(w x y:ℝ)) K D)=tv p (markedLaw w K D) := by + have he : sourceLaw (fun x y=>(w x y:ℝ)) K D=markedLaw w K D ∘ sourceMarkedEquiv w K := by + funext a + exact (markedLaw_equiv w hw K D hD a).symm + rw [he] + exact tv_equiv (sourceMarkedEquiv w K) p (markedLaw w K D) + +noncomputable def finiteSourceLaw (w : V → V → ℚ) (hw : ∀ x y,0(w x y:ℝ)) K → ℝ := + markedSamplerLaw w hw K D m hD hN h hq M η ∘ sourceMarkedEquiv w K +lemma finiteSourceLaw_nonneg (w : V → V → ℚ) (hw : ∀ x y,0(w x y:ℝ)) K) : + 0≤finiteSourceLaw w hw K D m hD hN h hq M η a := imageLaw_nonneg _ _ +lemma finiteSourceLaw_sum (w : V → V → ℚ) (hw : ∀ x y,0(w x y:ℝ)) K D)≤2*(η:ℝ)+(m:ℝ)⁻¹ := by + rw [finiteSourceLaw,source_transfer_tv w hw K D (by omega)] + exact markedSampler_tv w hw K D m hD hN hm h hq M η hη + +lemma sampling_denominator_gt (T S : ℕ) (hT : 0(w x y:ℝ)) ∅) + (K T S : ℕ) (hT : 0¬StageGood (fun x y=>(w x y:ℝ)) w₁ K σ x)<13/(1000*T) := by + dsimp only + have hN : 2≤Fintype.card (SourceVertex V K) := + (Fintype.one_lt_card_iff_nontrivial.mpr (inferInstance : Nontrivial V)).trans_le (sourceVertex_card_ge K) + let p := finiteSourceLaw w hw K (sourceD (V:=V) K) (1000*T*S) + (sourceD_one K) Fintype.card_pos h hq M (1/(1000*T*S)) + have hv := finiteSourceLaw_tv w hw K (sourceD (V:=V) K) (1000*T*S) (sourceD_one K) + hN (sampling_denominator_gt T S hT hS) h hq M (1/(1000*T*S)) (by positivity) + rw [sampling_budget T S hT hS] at hv + have hh:=source_nearby_budget (fun x y=>(w x y:ℝ)) w₁ + (fun x y=>by exact_mod_cast hw x y) hw₁ hle hz K T S hT hS σ hσ hsize p + (finiteSourceLaw_nonneg w hw K _ _ _ _ h hq M _) ?_ ?_ + · rw [event_instances _ (inferInstance : Fintype (Fin S → SourceMarked (fun x y=>(w x y:ℝ)) K))] at hh + exact hh + · rw [sum_instances _ (inferInstance : Fintype (SourceMarked (fun x y=>(w x y:ℝ)) K))] + exact finiteSourceLaw_sum w hw K _ _ _ _ h hq M _ + · rw [tv_instances _ (inferInstance : Fintype (SourceMarked (fun x y=>(w x y:ℝ)) K))] + exact hv +end MatchingFPRAS.RationalSource + +end OAI diff --git a/lean/OAI/Combinatorics/MatchingCount/Algorithm/FiniteTrial.lean b/lean/OAI/Combinatorics/MatchingCount/Algorithm/FiniteTrial.lean new file mode 100644 index 0000000000000000000000000000000000000000..8c82922849b270466b46110b588fa6c78fad5bde --- /dev/null +++ b/lean/OAI/Combinatorics/MatchingCount/Algorithm/FiniteTrial.lean @@ -0,0 +1,126 @@ +import Mathlib +import OAI.Combinatorics.MatchingCount.Algorithm.RationalUpdate +import OAI.Combinatorics.MatchingCount.Algorithm.FiniteTrialLaw + +namespace OAI + +namespace MatchingFPRAS.FiniteTrial +open Finset Switching Transport Enlargement Adaptive Initializer +open scoped Classical + +variable {G : GraphInput} [Nontrivial (Fin G.n)] +attribute [local instance] NumberedHierarchy.labelOrder sym2Order bagEdgeOrder bagEdgeFintype +attribute [local instance] UnitRefresh.Computable.allowedDec prodOrder sumOrder +noncomputable local instance (w : Fin G.n → Fin G.n → ℚ) (K : ℕ) : + DecidableEq (SourceLabel (fun x y=>(w x y:ℝ)) K) := Classical.decEq _ +noncomputable local instance (w : Fin G.n → Fin G.n → ℚ) (K : ℕ) : + Fintype (BagEdge (sourceBags (fun x y=>(w x y:ℝ)) K)) := Fintype.ofFinite _ +noncomputable local instance (w : Fin G.n → Fin G.n → ℚ) (K : ℕ) : + Fintype (SourceMarked (fun x y=>(w x y:ℝ)) K) := Fintype.ofFinite _ +structure Layer (p : Trial.Parameters G) (j : ℕ) where + Ω : Type + finite : Fintype Ω + law : @Law Ω finite + state : Ω → ScaleState G j + ratios : Ω → Fin j → ℚ + ratios_nonneg : ∀ x i,0 ≤ ratios x i + +attribute [instance] Layer.finite + +noncomputable def Layer.good (p : Trial.Parameters G) {j : ℕ} (L : Layer p j) (x : L.Ω) : Prop := + (L.state x).Balanced p.hn ∧ ∀ i : Fin j, + |(L.ratios x i:ℝ)/(partition (Trial.raw G (i.val+1)) ∅/partition (Trial.raw G i.val) ∅)-1| ≤ (p.epsilon:ℝ)/(100*p.K) + +noncomputable def firstLayer (p : Trial.Parameters G) : Layer p 0 where + Ω := PUnit + finite := inferInstance + law := ⟨fun _=>1,fun _=>by norm_num,by simp⟩ + state _ := initialScaleState G p.hn + ratios _ := Fin.elim0 + ratios_nonneg _ i := Fin.elim0 i + +noncomputable def Layer.append (p : Trial.Parameters G) {j : ℕ} (hj : j ≤ p.K) (L : Layer p j) : Layer p (j+1) where + Ω := Σ x : L.Ω, Fin p.S → SourceMarked (fun a b=>((L.state x).activity a b:ℝ)) p.K + finite := inferInstance + law := L.law.sigma (fun x=>(L.state x).sampleLaw p hj) + state x := (L.state x.1).update p.hn (RationalSource.sourceMarkedEquiv (L.state x.1).activity p.K ∘ x.2) + ratios x := Fin.snoc (L.ratios x.1) ((L.state x.1).ratioEstimate (RationalSource.sourceMarkedEquiv (L.state x.1).activity p.K ∘ x.2)) + ratios_nonneg x i := by + refine Fin.lastCases ?_ (fun i=>?_) i + · simpa using (L.state x.1).ratioEstimate_nonneg x.2 + · simpa using L.ratios_nonneg x.1 i + +theorem Layer.append_good (p : Trial.Parameters G) {j : ℕ} (hj : j ≤ p.K) (L : Layer p j) (x : L.Ω) + (hx : L.good p x) (y : Fin p.S → SourceMarked (fun a b=>((L.state x).activity a b:ℝ)) p.K) + (hy : StageGood (fun a b=>((L.state x).activity a b:ℝ)) (fun a b=>((L.state x).nextActivity a b:ℝ)) p.K p.sigma y) : + (L.append p hj).good p ⟨x,y⟩ := by + have h := successful_update p hj (L.state x) hx.1 y hy + refine ⟨h.1,?_⟩ + intro i + refine Fin.lastCases ?_ (fun i=>?_) i + · simpa [Layer.append] using h.2 + · simpa [Layer.append] using hx.2 i + +theorem Layer.append_failure (p : Trial.Parameters G) {j : ℕ} (hj : j ≤ p.K) (L : Layer p j) : + (L.append p hj).law.event (fun x=>¬(L.append p hj).good p x) ≤ + L.law.event (fun x=>¬L.good p x)+13/(1000*p.K) := by + apply first_failure_sigma L.law (fun x=>(L.state x).sampleLaw p hj) (L.good p) + ((L.append p hj).good p) _ (by positivity) + intro x hx + apply le_trans ((L.state x).sampleLaw p hj |>.event_mono ?_) + ((L.state x).sampleLaw_budget p hj).le + intro y hy hgood + exact hy (L.append_good p hj x hx y hgood) + +noncomputable def layers (p : Trial.Parameters G) : (j : ℕ) → j ≤ p.K → Layer p j + | 0, _ => firstLayer p + | j+1, h => (layers p j (by omega)).append p (by omega) + +theorem layers_failure (p : Trial.Parameters G) (j : ℕ) (hj : j ≤ p.K) : + (layers p j hj).law.event (fun x=>¬(layers p j hj).good p x) ≤ j*(13/(1000*p.K)) := by + induction j with + | zero => + have hg : ∀ x,(firstLayer p).good p x := by + intro x + constructor + · exact initial_balanced p.hn p.even + · intro i; exact Fin.elim0 i + simp [layers,Law.event,hg] + | succ j ih => + refine le_trans ((layers p j (by omega)).append_failure p (by omega)) ?_ + calc + _ ≤ (j:ℝ)*(13/(1000*p.K))+13/(1000*p.K) := by linarith only [ih (by omega)] + _ = _ := by push_cast; ring + +noncomputable def output (p : Trial.Parameters G) (x : (layers p p.K le_rfl).Ω) : ℚ := + (Z (completeGraph G.n):ℚ)*∏ i,(layers p p.K le_rfl).ratios x i + +lemma output_nonneg (p : Trial.Parameters G) (x : (layers p p.K le_rfl).Ω) : 0 ≤ output p x := by + apply mul_nonneg (Nat.cast_nonneg _) + exact prod_nonneg fun i _=>(layers p p.K le_rfl).ratios_nonneg x i + +def Accurate (p : Trial.Parameters G) (y : ℚ) : Prop := + (1-p.epsilon)*(Z G:ℚ)≤y ∧ y≤(1+p.epsilon)*(Z G:ℚ) + +theorem good_output (p : Trial.Parameters G) (hZ : 0((layers p p.K le_rfl).ratios x i:ℝ)) hx.2 + unfold Accurate output + dsimp only at h + exact_mod_cast h + +theorem actual_finite_trial_failure (p : Trial.Parameters G) (hZ : 0¬Accurate p (output p x)) ≤ 13/1000 := by + have hh := layers_failure p p.K le_rfl + have he : (p.K:ℝ)*(13/(1000*p.K))=13/1000 := by + have hk : (p.K:ℝ)≠0 := by exact_mod_cast p.K_pos.ne' + rw [←mul_div_assoc,mul_comm (1000:ℝ),mul_div_mul_left _ _ hk] + rw [he] at hh + apply le_trans ((layers p p.K le_rfl).law.event_mono ?_) hh + intro x hx hg + exact hx (good_output p hZ x hg) + +end MatchingFPRAS.FiniteTrial + +end OAI diff --git a/lean/OAI/Combinatorics/MatchingCount/Algorithm/FiniteTrialLaw.lean b/lean/OAI/Combinatorics/MatchingCount/Algorithm/FiniteTrialLaw.lean new file mode 100644 index 0000000000000000000000000000000000000000..d062e69d6caa8ceb610dac9bf9b6a412f25aa620 --- /dev/null +++ b/lean/OAI/Combinatorics/MatchingCount/Algorithm/FiniteTrialLaw.lean @@ -0,0 +1,61 @@ +import Mathlib +import OAI.Combinatorics.MatchingCount.Algorithm.FiniteStage +import OAI.Combinatorics.MatchingCount.Algorithm.RationalScale +import OAI.Combinatorics.MatchingCount.Algorithm.RationalStart + +namespace OAI + +namespace MatchingFPRAS.FiniteTrial +open Finset Switching Transport Enlargement Adaptive +open scoped Classical + +variable {G : GraphInput} [Nontrivial (Fin G.n)] +attribute [local instance] NumberedHierarchy.labelOrder sym2Order bagEdgeOrder bagEdgeFintype +attribute [local instance] UnitRefresh.Computable.allowedDec prodOrder sumOrder +noncomputable local instance finiteTrialLawSourceLabelDecidableEq (w : Fin G.n → Fin G.n → ℚ) (K : ℕ) : + DecidableEq (SourceLabel (fun x y=>(w x y:ℝ)) K) := Classical.decEq _ +noncomputable local instance finiteTrialLawSourceBagEdgeFintype (w : Fin G.n → Fin G.n → ℚ) (K : ℕ) : + Fintype (BagEdge (sourceBags (fun x y=>(w x y:ℝ)) K)) := Fintype.ofFinite _ +noncomputable local instance (w : Fin G.n → Fin G.n → ℚ) (K : ℕ) : + Fintype (SourceMarked (fun x y=>(w x y:ℝ)) K) := Fintype.ofFinite _ + +omit [Nontrivial (Fin G.n)] in +lemma ScaleState.cap {j K : ℕ} (s : ScaleState G j) (hj : j≤K) (a b : Fin G.n) (hab : a≠b) : + BottleneckAlgorithm.edge s.activity a b≤(4:ℚ)^K := by + have h:=s.toReal.cap hj a b hab + rw [←s.activity_cast] at h + have he : ((BottleneckAlgorithm.edge s.activity a b:ℚ):ℝ)=edgeActivity (fun a b=>(s.activity a b:ℝ)) a b := by + unfold BottleneckAlgorithm.edge edgeActivity + split_ifs <;> rfl + rw [←he] at h + exact_mod_cast h + +noncomputable def ScaleState.runLaw (p : Trial.Parameters G) {j : ℕ} (hj : j≤p.K) (s : ScaleState G j) : + Law (SourceMarked (fun a b=>(s.activity a b:ℝ)) p.K) where + mass := RationalSource.finiteSourceLaw s.activity s.activity_pos p.K + (Enlargement.sourceD (V:=Fin G.n) p.K) (1000*p.K*p.S) + (sourceD_one p.K) Fintype.card_pos (s.cap hj) p.q_pos + (RationalSource.startMatching s.activity p.K p.even) (1/(1000*p.K*p.S)) + nonneg := RationalSource.finiteSourceLaw_nonneg _ _ _ _ _ _ _ _ _ _ _ + total := RationalSource.finiteSourceLaw_sum _ _ _ _ _ _ _ _ _ _ _ + +noncomputable def ScaleState.sampleLaw (p : Trial.Parameters G) {j : ℕ} (hj : j≤p.K) (s : ScaleState G j) : + Law (Fin p.S → SourceMarked (fun a b=>(s.activity a b:ℝ)) p.K) := (s.runLaw p hj).iid p.S + +theorem ScaleState.sampleLaw_budget (p : Trial.Parameters G) {j : ℕ} (hj : j≤p.K) (s : ScaleState G j) : + (s.sampleLaw p hj).event + (fun x=>¬StageGood (fun a b=>(s.activity a b:ℝ)) (fun a b=>(s.nextActivity a b:ℝ)) p.K p.sigma x) + <13/(1000*p.K) := by + have h:=RationalSource.finite_source_stage_budget s.activity s.activity_pos + (fun a b=>(s.nextActivity a b:ℝ)) + (fun a b=>by exact_mod_cast (s.nextActivity_pos a b).le) + (fun a b _=>by have h:=(s.toReal.cooling a b).2; rw [←s.activity_cast,←s.nextActivity_cast] at h; exact h) + (by rw [s.activity_cast]; exact s.toReal.partition_pos p.even) + p.K p.K p.S p.K_pos p.S_pos p.sigma p.sigma_pos.le (by simpa using p.S_bound) + (s.cap hj) p.q_pos (RationalSource.startMatching s.activity p.K p.even) + convert h using 1 + unfold ScaleState.sampleLaw ScaleState.runLaw Law.event Law.iid Variation.event + rfl +end MatchingFPRAS.FiniteTrial + +end OAI diff --git a/lean/OAI/Combinatorics/MatchingCount/Algorithm/Guard.lean b/lean/OAI/Combinatorics/MatchingCount/Algorithm/Guard.lean new file mode 100644 index 0000000000000000000000000000000000000000..775a80f3442d2fd7736a2193e9dbf0b75f4179d1 --- /dev/null +++ b/lean/OAI/Combinatorics/MatchingCount/Algorithm/Guard.lean @@ -0,0 +1,300 @@ +import Mathlib +import OAI.Combinatorics.MatchingCount.Algorithm.OutputLengthBound + +namespace OAI + +namespace MatchingFPRAS.WeightedOptions +open Finset FiniteChoice + +lemma draw_law_pos {Ω : Type*} [Fintype Ω] [DecidableEq Ω] + (c : WeightedOptions Ω) (k : ℕ) (bits : Fin k → Bool) : + 0 < c.law (c.draw k bits) := by + let i := chooseBits c.mass c.total k bits + have hi : 0 < c.mass i := chooseBits_pos c.mass c.total k bits + apply hi.trans_le + unfold law + calc + c.mass i = (if c.out i = c.draw k bits then c.mass i else 0) := by simp [draw, i] + _ ≤ ∑ j, if c.out j = c.draw k bits then c.mass j else 0 := + single_le_sum (f := fun j => if c.out j = c.draw k bits then c.mass j else 0) + (fun j _ => by split_ifs <;> [exact c.nonneg j; exact le_rfl]) (mem_univ i) + +end MatchingFPRAS.WeightedOptions + +namespace MatchingFPRAS.Enlargement +open Finset Switching Subdivision RealGeometry MatchingFPRAS.Representation + +theorem intact_partition_identity_even {V : Type*} [Fintype V] [LinearOrder V] + (he : Even (Fintype.card V)) (w : V → V → ℝ) + (p : ℕ) (B Hu Hv : LogicalEdge V → ℝ) : + realHolePartition source target (4*p) ∅ (fun _ => ∅) + (pathActivity p B Hu Hv (logicalActivity w)) = + (∏ e, pathConstant p (B e) (Hu e) (Hv e)) * partition w ∅ := by + classical + have hz := StageAnalysis.partition_pos_of_even (fun _ _ : V => (1:ℝ)) (by intros; norm_num) ∅ + (by simpa using he) + have hn : (matchings (∅ : Finset V)).Nonempty := by + by_contra hn + have hz0 : partition (fun _ _ : V => (1:ℝ)) ∅ = 0 := by + simp [partition, Finset.not_nonempty_iff_eq_empty.mp hn] + linarith + obtain ⟨m, hm⟩ := hn + let b := fun (e : LogicalEdge V) (i : Fin (4*p+1)) => alternating (select m e) i.val + have hb := intact_family p m ((mem_matchings m ∅).mp hm) + have hid := deletion_partition_identity (show Even (4*p) from ⟨2*p,by omega⟩) + source target ∅ (fun _ => ∅) b hb (pathActivity p B Hu Hv (logicalActivity w)) + (fun e => List.ofFn fun r : Fin p => max (B e) (Hu e/2^r.val)) + (fun e => (List.ofFn fun r : Fin p => max (B e) (Hv e/2^r.val)).reverse) _ + (fun e => profileActivity_ofFn p (B e) (Hu e) (Hv e) (logicalActivity w e)) + simpa [residualHoles, broken, deletionConstant, List.prod_ofFn, pathConstant, + logical_partition_eq] using hid + +open Transport +open scoped Classical + +variable {V : Type*} [Fintype V] [LinearOrder V] [Nontrivial V] +noncomputable local instance (w : V → V → ℝ) (K : ℕ) : DecidableEq (SourceLabel w K) := Classical.decEq _ +noncomputable local instance (w : V → V → ℝ) (K : ℕ) : Fintype (BagEdge (sourceBags w K)) := Fintype.ofFinite _ + +theorem frozenPortion_full_even (he : Even (Fintype.card V)) + (w w₁ : V → V → ℝ) (K : ℕ) : + Transport.partitionWeight BagEdge.Incident (frozenPortion w w₁ K) Finset.univ = + sourceC w K * Switching.partition w₁ ∅ := by + rw [←survivors_empty (V:=V) K, frozenPortion_partition, + intact_partition_identity_even he w₁] + rfl + +theorem observableD_mean_even (he : Even (Fintype.card V)) + (w w₁ : V → V → ℝ) (hw : ∀ x y, 0 < w x y) (K D : ℕ) : + (∑ a : SourceMarked w K, sourceLaw w K D a * observableD w w₁ K a) = + sourceC w K * Switching.partition w₁ ∅ / sourceBagZ w K D := by + classical + have h := Marking.allReal_mean BagEdge.Incident (sourcePortions w K D) (0 : Fin 3) (bagReweight w w₁ K) + simp only [sourcePortions, Matrix.cons_val_zero] at h + rw [bagReweight_identity w w₁ hw K, frozenPortion_full_even he w w₁] at h + simpa only [sourceLaw, observableD, sourcePortions_collapse, sourceBagZ] using h + +theorem observableD_zero_of_partition_zero (he : Even (Fintype.card V)) + (w w₁ : V → V → ℝ) (hw : ∀ x y, 0 < w x y) + (hw₁ : ∀ x y, 0 ≤ w₁ x y) (hle : ∀ x y, w₁ x y ≤ w x y) + (hz : 0 < Switching.partition w ∅) (K D : ℕ) + (hz₁ : Switching.partition w₁ ∅ = 0) (a : SourceMarked w K) + (ha : 0 < sourceLaw w K D a) : observableD w w₁ K a = 0 := by + have hB : 0 < sourceBagZ w K D := sourceBagZ_pos w hw hz K D + have hmean := observableD_mean_even he w w₁ hw K D + rw [hz₁, mul_zero, zero_div] at hmean + have hnonneg (b : SourceMarked w K) : 0 ≤ sourceLaw w K D b * observableD w w₁ K b := + mul_nonneg (sourceLaw_nonneg w hw K D hB.le b) + (observableD_range w w₁ hw hw₁ hle K b).1 + have hz' := (sum_eq_zero_iff_of_nonneg (fun b _ => hnonneg b)).mp hmean a (mem_univ a) + exact (mul_eq_zero.mp hz').resolve_left ha.ne' + +end MatchingFPRAS.Enlargement + +namespace MatchingFPRAS.TableMarking +open Finset Transport Variation + +variable {V E I : Type*} [Fintype V] [Fintype E] [DecidableEq E] [Fintype I] [DecidableEq I] +variable (inc : E → V → Prop) +variable {A : Type*} [Fintype A] [Nonempty A] + +omit [Fintype A] [Nonempty A] [DecidableEq E] in +lemma draw_law_pos [DecidableEq E] (f : A → PM inc) (w : E → ℝ) (hw : ∀ e, 0 < w e) + (c : E → WeightedOptions I) (k : ℕ) (bits : A × (E → Fin k → Bool)) : + 0 < law inc w c (draw inc f c k bits) := by + classical + change 0 < gibbs w (f bits.1) * ∏ e : (f bits.1).val, ((c e.val).law ((c e.val).draw k (bits.2 e.val)) : ℝ) + apply mul_pos (gibbs_pos w hw _) + exact Finset.prod_pos fun e _ => by exact_mod_cast (c e.val).draw_law_pos k (bits.2 e.val) + +end MatchingFPRAS.TableMarking + +namespace MatchingFPRAS.RationalSource +open Finset Transport Variation Enlargement + +variable {V : Type*} [Fintype V] [LinearOrder V] [Nontrivial V] +attribute [local instance] NumberedHierarchy.labelOrder sym2Order bagEdgeOrder bagEdgeFintype +attribute [local instance] UnitRefresh.Computable.allowedDec prodOrder sumOrder +noncomputable local instance (w : V → V → ℚ) (K : ℕ) : + DecidableEq (SourceLabel (fun x y=>(w x y:ℝ)) K) := Classical.decEq _ +noncomputable local instance (w : V → V → ℚ) (K : ℕ) : + Fintype (BagEdge (sourceBags (fun x y=>(w x y:ℝ)) K)) := Fintype.ofFinite _ +noncomputable local instance (w : V → V → ℚ) (K : ℕ) : + DecidableEq (BagPM (bags w K)) := Classical.decEq _ +noncomputable local instance (w : V → V → ℚ) (K : ℕ) : + Fintype (BagPM (bags w K)) := Fintype.ofFinite _ +noncomputable local instance (w : V → V → ℚ) (K : ℕ) : + Fintype (Marked w K) := Fintype.ofFinite _ + +lemma marking_law_eq (w : V → V → ℚ) (hw : ∀ x y, 0 < w x y) + (K D : ℕ) (hD : 0 < D) : + TableMarking.law BagEdge.Incident (fun e => (bagWeight w K D e : ℝ)) + (markingTable w hw K D hD) = markedLaw w K D := by + funext a + simp only [TableMarking.law, markedLaw, Variation.sigmaLift, Variation.product, TableMarking.portion, markingTable_law] + +theorem source_draw_support {A : Type*} [Fintype A] [Nonempty A] + (w : V → V → ℚ) (hw : ∀ x y, 0 < w x y) (K D k : ℕ) (hD : 0 < D) + (f : A → BagPM (bags w K)) (bits : A × (BagEdge (bags w K) → Fin k → Bool)) : + 0 < sourceLaw (fun x y => (w x y : ℝ)) K D + ((sourceMarkedEquiv w K).symm + (TableMarking.draw BagEdge.Incident f (markingTable w hw K D hD) k bits)) := by + rw [←markedLaw_equiv w hw K D hD, Equiv.apply_symm_apply, ←marking_law_eq w hw K D hD] + apply TableMarking.draw_law_pos + intro e + exact_mod_cast bagWeight_pos w hw K D hD e + +end MatchingFPRAS.RationalSource + +namespace MatchingFPRAS.GraphBridge +open Finset Switching + +lemma unpadded_partition (G : GraphInput) : + partition (rawActivity G 0) ∅ = (Z G : ℝ) := by + have h := raw_padding_bound G 0 (by norm_num) (by norm_num) + have he : rawPartition G 0 = (Z G : ℚ) := le_antisymm (by simpa using h.2) h.1 + have hc := raw_partition G 0 + rw [he] at hc + simpa using hc.symm + +end MatchingFPRAS.GraphBridge + +namespace MatchingFPRAS.Trial +open Finset Switching Transport Enlargement StageAnalysis +open scoped Classical + +variable {G : GraphInput} {j K : ℕ} [Nontrivial (Fin G.n)] +noncomputable local instance (w : Fin G.n → Fin G.n → ℝ) (K : ℕ) : + DecidableEq (SourceLabel w K) := Classical.decEq _ +noncomputable local instance (w : Fin G.n → Fin G.n → ℝ) (K : ℕ) : + Fintype (BagEdge (sourceBags w K)) := Fintype.ofFinite _ + +noncomputable def ScaleState.certificateActivity (s : ScaleState G j) : Fin G.n → Fin G.n → ℝ := + fun a b => GraphBridge.rawActivity G 0 a b * s.scale a * s.scale b + +omit [Nontrivial (Fin G.n)] in +lemma ScaleState.certificateActivity_nonneg (s : ScaleState G j) (a b : Fin G.n) : + 0 ≤ s.certificateActivity a b := by + unfold ScaleState.certificateActivity GraphBridge.rawActivity + split_ifs + · simpa only [one_mul] using mul_nonneg (s.positive a).le (s.positive b).le + · simp + +omit [Nontrivial (Fin G.n)] in +lemma ScaleState.certificateActivity_le (s : ScaleState G j) (a b : Fin G.n) : + s.certificateActivity a b ≤ s.activity a b := by + unfold ScaleState.certificateActivity ScaleState.activity raw GraphBridge.rawActivity + split_ifs + · rfl + · simp only [zero_mul] + exact mul_nonneg (mul_nonneg (pow_pos (cooling_pos G.n) j).le (s.positive a).le) (s.positive b).le + +omit [Nontrivial (Fin G.n)] in +lemma ScaleState.certificateActivity_partition (s : ScaleState G j) : + Switching.partition s.certificateActivity ∅ = (Z G : ℝ) * ∏ i, s.scale i := by + change Switching.partition (fun a b => GraphBridge.rawActivity G 0 a b * s.scale a * s.scale b) ∅ = _ + rw [partition_vertex_scaling, GraphBridge.unpadded_partition] + simp + +theorem ScaleState.certificate_zero (s : ScaleState G j) (he : Even G.n) + (hZ : Z G = 0) (D : ℕ) (a : SourceMarked s.activity K) + (ha : 0 < sourceLaw s.activity K D a) : + observableD s.activity s.certificateActivity K a = 0 := by + apply observableD_zero_of_partition_zero (by simpa using he) s.activity s.certificateActivity + s.activity_pos s.certificateActivity_nonneg s.certificateActivity_le + (s.partition_pos he) K D + · rw [s.certificateActivity_partition, hZ] + simp + · exact ha + +open Finset Switching Transport Enlargement StageAnalysis +open scoped Classical + +variable {G : GraphInput} [Nontrivial (Fin G.n)] +noncomputable local instance (w : Fin G.n → Fin G.n → ℝ) (K : ℕ) : + DecidableEq (SourceLabel w K) := Classical.decEq _ +noncomputable local instance (w : Fin G.n → Fin G.n → ℝ) (K : ℕ) : + Fintype (BagEdge (sourceBags w K)) := Fintype.ofFinite _ + +theorem ScaleState.certificate_mean_lower (p : Parameters G) (s : ScaleState G p.K) + (hs : s.Balanced p.hn) (hZ : 0 < Z G) : + (1:ℝ)/4 ≤ ∑ a : SourceMarked s.activity p.K, + sourceLaw s.activity p.K p.D a * observableD s.activity s.certificateActivity p.K a := by + have hm : (∑ a : SourceMarked s.activity p.K, + sourceLaw s.activity p.K p.D a * observableD s.activity s.certificateActivity p.K a) = + sourceC s.activity p.K * partition s.certificateActivity ∅ / sourceBagZ s.activity p.K p.D := by + convert observableD_mean_even (by simpa using p.even) s.activity s.certificateActivity + s.activity_pos p.K p.D using 1 + exact Variation.sum_instances _ _ _ + rw [hm] + have hB := (sourceBagZ_bounds (by simpa using p.hn) s.activity s.activity_pos + (s.partition_pos p.even) hs.1 hs.2 p.K (s.cap le_rfl)).2 + have hp := (final_padding G p.epsilon p.epsilon_pos p.K p.schedule hZ).2 + have hsmall : partition (raw G p.K) ∅ ≤ 2 * (Z G : ℝ) := by + have hz : (0:ℝ) ≤ Z G := Nat.cast_nonneg _ + have he := p.epsilon_real_lt_one + nlinarith + have hprod : 0 < ∏ i, s.scale i := prod_pos fun i _ => s.positive i + have hact : partition s.activity ∅ ≤ 2 * partition s.certificateActivity ∅ := by + rw [s.certificateActivity_partition] + change partition (fun a b => raw G p.K a b * s.scale a * s.scale b) ∅ ≤ _ + rw [partition_vertex_scaling] + simpa [mul_assoc] using mul_le_mul_of_nonneg_right hsmall hprod.le + have hc := sourceC_pos s.activity p.K + have hb0 := sourceBagZ_pos s.activity s.activity_pos (s.partition_pos p.even) p.K p.D + apply (le_div_iff₀ hb0).mpr + change sourceBagZ s.activity p.K (sourceD (V:=Fin G.n) p.K) ≤ _ at hB + have hmul := mul_le_mul_of_nonneg_left hact hc.le + change (1:ℝ)/4 * sourceBagZ s.activity p.K (sourceD (V:=Fin G.n) p.K) ≤ _ + nlinarith + +end MatchingFPRAS.Trial + +namespace MatchingFPRAS.Variation +open Finset +open scoped Classical + +variable {Ω : Type*} [Fintype Ω] + +lemma mean_le_positive_event (p X : Ω → ℝ) (hp : ∀ x, 0 ≤ p x) + (hX : ∀ x, 0 ≤ X x ∧ X x ≤ 1) : + (∑ x, p x * X x) ≤ event p (fun x => 0 < X x) := by + apply sum_le_sum + intro x _ + change p x * X x ≤ if 0 < X x then p x else 0 + by_cases hx : 0 < X x + · simp only [hx, ite_true] + exact mul_le_of_le_one_right (hp x) (hX x).2 + · have hz : X x = 0 := le_antisymm (le_of_not_gt hx) (hX x).1 + simp [hz] + +end MatchingFPRAS.Variation + +namespace MatchingFPRAS.RationalSource +open Finset Transport Variation Enlargement + +variable {V : Type*} [Fintype V] [LinearOrder V] [Nontrivial V] +attribute [local instance] NumberedHierarchy.labelOrder sym2Order bagEdgeOrder bagEdgeFintype +attribute [local instance] UnitRefresh.Computable.allowedDec prodOrder sumOrder +noncomputable local instance (w : V → V → ℚ) (K : ℕ) : + DecidableEq (SourceLabel (fun x y=>(w x y:ℝ)) K) := Classical.decEq _ +noncomputable local instance (w : V → V → ℚ) (K : ℕ) : + Fintype (BagEdge (sourceBags (fun x y=>(w x y:ℝ)) K)) := Fintype.ofFinite _ +noncomputable local instance (w : V → V → ℚ) (K : ℕ) : + DecidableEq (BagPM (bags w K)) := Classical.decEq _ +noncomputable local instance (w : V → V → ℚ) (K : ℕ) : + Fintype (BagPM (bags w K)) := Fintype.ofFinite _ + +theorem fixedSampler_support (w : V → V → ℚ) (hw : ∀ x y,0 (w x y : ℝ)) K D + (fixedSampler w hw K D m hD hN h hq M η bits) := by + simp only [fixedSampler, padSampler, bitSampler, Function.comp_apply, markedSampler] + exact source_draw_support w hw K D _ hD _ _ + +end MatchingFPRAS.RationalSource + +end OAI diff --git a/lean/OAI/Combinatorics/MatchingCount/Algorithm/GuardBudget.lean b/lean/OAI/Combinatorics/MatchingCount/Algorithm/GuardBudget.lean new file mode 100644 index 0000000000000000000000000000000000000000..3dc447e001711d5bcf0103ba859bf0b4009cabba --- /dev/null +++ b/lean/OAI/Combinatorics/MatchingCount/Algorithm/GuardBudget.lean @@ -0,0 +1,82 @@ +import Mathlib +import OAI.Combinatorics.MatchingCount.Tapes.GuardBits + +namespace OAI + +namespace MatchingFPRAS.FiniteTrial +open BitComplexity Amplification + +variable {G : GraphInput} [Nontrivial (Fin G.n)] +lemma oneBits_le_trial (p : Trial.Parameters G) : oneBits p ≤ p.K*stageBits p := by + have hk : 1≤p.K := p.K_pos + have hs : 1≤p.S := p.S_pos + unfold stageBits + have h := Nat.mul_le_mul hk hs + have hh := Nat.mul_le_mul_right (oneBits p) h + simpa only [one_mul, Nat.mul_assoc] using hh +lemma guardedBits_le (p : Trial.Parameters G) : guardedBits p≤17*(p.K*stageBits p) := by + unfold guardedBits guardBits + have h := Nat.mul_le_mul_left 16 (oneBits_le_trial p) + omega +lemma guardedAmplifiedBits_le (p : Trial.Parameters G) (δ : ℚ) : + guardedAmplifiedBits p δ≤17*amplifiedBits p δ := by + have h := Nat.mul_le_mul_left (2*halfRepetitions δ+1) (guardedBits_le p) + simpa only [guardedAmplifiedBits, amplifiedBits, Nat.mul_left_comm, Nat.mul_assoc] using h +end MatchingFPRAS.FiniteTrial + +namespace MatchingFPRAS.BitComplexity +open FiniteTrial Trial + +theorem polynomial_guarded_bits : ∃ C d : ℕ, ∀ (G : GraphInput) [Nontrivial (Fin G.n)] + (hn : 2 ≤ G.n) (hev : Even G.n) (e δ : ℚ) (he : 0?_⟩ + apply (guardedAmplifiedBits_le _ δ).trans + have hh := Nat.mul_le_mul_left 17 (h G hn hev e δ he he1 hs) + simpa only [timeBound,Nat.mul_assoc] using hh +end MatchingFPRAS.BitComplexity + +namespace MatchingFPRAS.FiniteTrial +open BitComplexity Variation Finset +open scoped Classical + +lemma padded_guarded_success {G : GraphInput} [Nontrivial (Fin G.n)] + (p : Trial.Parameters G) (δ : ℚ) (B : ℕ) (ht : guardedAmplifiedBits p δ≤B) + (hz : 0Accurate p (padSampler ht (guardedAmplifiedBitOutput p δ) b))).card:ℚ)/ + (2:ℚ)^B≥1-δ := by + rw [padSampler_success] + exact guardedAmplifiedBitOutput_success p hz δ hd + +theorem guarded_scheduled_fair_tapes : ∃ C d : ℕ, 0(1-e)*(Z G:ℚ)≤f b ∧ f b≤(1+e)*(Z G:ℚ))).card:ℚ) / + (2:ℚ)^(timeBound C d G e δ)≥1-δ) := by + obtain ⟨C,d,h⟩:=polynomial_guarded_bits + refine ⟨C+1,d,by omega,fun G _ hn hev e δ he he1 hs=>?_⟩ + let p:=parameters G hn hev e he he1 + have ht : guardedAmplifiedBits p δ ≤ timeBound (C+1) d G e δ := by + exact (h G hn hev e δ he he1 hs).trans (Nat.mul_le_mul_right _ (by omega)) + let f:=padSampler ht (guardedAmplifiedBitOutput p δ) + have hz : Z G=0 → ∀ b,f b=0 := fun hZ b => guardedAmplifiedBitOutput_zero p hZ δ _ + refine ⟨f,fun b=>guardedAmplifiedBitOutput_nonneg p δ _,hz,fun hd=>?_⟩ + by_cases hZ : Z G=0 + · have hf : (univ.filter (fun b=>(1-e)*(Z G:ℚ)≤f b ∧ f b≤(1+e)*(Z G:ℚ)))=univ := by + ext b + simp [hZ,hz hZ b] + rw [hf,card_univ] + simp only [Fintype.card_fun,Fintype.card_bool,Fintype.card_fin,Nat.cast_pow,Nat.cast_ofNat] + rw [div_self (by positivity : (2:ℚ)^timeBound (C+1) d G e δ≠0)] + linarith + · convert padded_guarded_success p δ _ ht (Nat.pos_of_ne_zero hZ) hd using 3 + congr 1 + ext b + simp only [mem_filter,mem_univ,true_and] + rfl +end MatchingFPRAS.FiniteTrial + +end OAI diff --git a/lean/OAI/Combinatorics/MatchingCount/Algorithm/GuardProbability.lean b/lean/OAI/Combinatorics/MatchingCount/Algorithm/GuardProbability.lean new file mode 100644 index 0000000000000000000000000000000000000000..aa1542e1cf827fed8888fe2d44a5ea5be38ad9c5 --- /dev/null +++ b/lean/OAI/Combinatorics/MatchingCount/Algorithm/GuardProbability.lean @@ -0,0 +1,231 @@ +import Mathlib +import OAI.Combinatorics.MatchingCount.Algorithm.Guard + +namespace OAI + +namespace MatchingFPRAS.FiniteTrial +open Finset Switching Transport Enlargement Adaptive Variation +open scoped Classical + +variable {G : GraphInput} [Nontrivial (Fin G.n)] +attribute [local instance] NumberedHierarchy.labelOrder sym2Order bagEdgeOrder bagEdgeFintype +attribute [local instance] UnitRefresh.Computable.allowedDec prodOrder sumOrder +noncomputable local instance (w : Fin G.n → Fin G.n → ℚ) (K : ℕ) : + DecidableEq (SourceLabel (fun x y=>(w x y:ℝ)) K) := Classical.decEq _ +noncomputable local instance (w : Fin G.n → Fin G.n → ℚ) (K : ℕ) : + Fintype (BagEdge (sourceBags (fun x y=>(w x y:ℝ)) K)) := Fintype.ofFinite _ +noncomputable local instance (w : Fin G.n → Fin G.n → ℚ) (K : ℕ) : + Fintype (SourceMarked (fun x y=>(w x y:ℝ)) K) := Fintype.ofFinite _ + +def ScaleState.certificateActivity {j : ℕ} (s : ScaleState G j) : Fin G.n → Fin G.n → ℚ := + fun a b => (if (min a b,max a b) ∈ G.edges then 1 else 0) * s.scale a * s.scale b +omit [Nontrivial (Fin G.n)] in +lemma ScaleState.certificateActivity_cast [Nontrivial (Fin G.n)] {j : ℕ} (s : ScaleState G j) : + (fun a b => (s.certificateActivity a b : ℝ)) = s.toReal.certificateActivity := by + funext a b + unfold ScaleState.certificateActivity Trial.ScaleState.certificateActivity GraphBridge.rawActivity + split_ifs <;> simp [ScaleState.toReal] + +noncomputable def ScaleState.certificate {j : ℕ} (s : ScaleState G j) (K : ℕ) + (a : SourceMarked (fun x y => (s.activity x y : ℝ)) K) : ℚ := + RationalSource.observableD s.activity s.certificateActivity K (RationalSource.sourceMarkedEquiv s.activity K a) + +lemma ScaleState.certificate_cast {j : ℕ} (s : ScaleState G j) (K : ℕ) + (a : SourceMarked (fun x y => (s.activity x y : ℝ)) K) : + (s.certificate K a : ℝ) = observableD (fun x y => (s.activity x y : ℝ)) + (fun x y => (s.certificateActivity x y : ℝ)) K a := + RationalSource.observableD_cast _ _ _ _ + +lemma ScaleState.certificate_range {j : ℕ} (s : ScaleState G j) (K : ℕ) + (a : SourceMarked (fun x y => (s.activity x y : ℝ)) K) : + 0 ≤ s.certificate K a ∧ s.certificate K a ≤ 1 := by + have h : 0 ≤ (s.certificate K a : ℝ) ∧ (s.certificate K a : ℝ) ≤ 1 := by + rw [s.certificate_cast] + apply observableD_range _ _ (fun x y => by exact_mod_cast s.activity_pos x y) + · intro x y + have hc := s.toReal.certificateActivity_nonneg x y + rw [←s.certificateActivity_cast] at hc + exact hc + · intro x y + have hc := s.toReal.certificateActivity_le x y + rw [←s.certificateActivity_cast, ←s.activity_cast] at hc + exact hc + exact_mod_cast h + +theorem ScaleState.drawOne_certificate_zero (p : Trial.Parameters G) {j : ℕ} + (hj : j ≤ p.K) (s : ScaleState G j) (hZ : Z G = 0) (b : Fin (oneBits p) → Bool) : + s.certificate p.K (s.drawOne p hj b) = 0 := by + have hs : 0 < sourceLaw (fun x y => (s.activity x y : ℝ)) p.K p.D (s.drawOne p hj b) := + RationalSource.fixedSampler_support _ _ _ _ _ _ _ _ _ _ _ _ + have hc := s.toReal.certificate_zero (K:=p.K) p.even hZ p.D + rw [←s.activity_cast, ←s.certificateActivity_cast] at hc + have hh := hc (s.drawOne p hj b) hs + rw [←s.certificate_cast] at hh + exact_mod_cast hh + +lemma ScaleState.certificate_mean_lower (p : Trial.Parameters G) (s : ScaleState G p.K) + (hs : s.Balanced p.hn) (hZ : 0 < Z G) : + (1:ℝ)/4 ≤ ∑ a : SourceMarked (fun x y => (s.activity x y : ℝ)) p.K, + sourceLaw (fun x y => (s.activity x y : ℝ)) p.K p.D a * (s.certificate p.K a : ℝ) := by + have h := s.toReal.certificate_mean_lower p hs hZ + rw [←s.activity_cast, ←s.certificateActivity_cast] at h + simp_rw [←s.certificate_cast] at h + convert h using 1 + exact Variation.sum_instances _ _ _ + +lemma ScaleState.runLaw_tv (p : Trial.Parameters G) {j : ℕ} (hj : j ≤ p.K) (s : ScaleState G j) : + tv (s.runLaw p hj).mass (sourceLaw (fun x y => (s.activity x y : ℝ)) p.K p.D) ≤ + 3/(1000*p.K*p.S) := by + have hN : 2 ≤ Fintype.card (SourceVertex (Fin G.n) p.K) := by + have h := sourceVertex_card_ge (V:=Fin G.n) p.K + simp only [Fintype.card_fin] at h + have hn := p.hn + omega + have h := RationalSource.finiteSourceLaw_tv s.activity s.activity_pos p.K p.D + (1000*p.K*p.S) (sourceD_one p.K) hN (RationalSource.sampling_denominator_gt _ _ p.K_pos p.S_pos) + (s.cap hj) p.q_pos (RationalSource.startMatching _ _ p.even) (1/(1000*p.K*p.S)) (by have := p.K_pos; have := p.S_pos; positivity) + rw [RationalSource.sampling_budget _ _ p.K_pos p.S_pos] at h + convert h using 1 + exact tv_instances _ _ _ _ + +theorem ScaleState.guard_success (p : Trial.Parameters G) (s : ScaleState G p.K) + (hs : s.Balanced p.hn) (hZ : 0 < Z G) : + (1:ℝ)/5 ≤ (s.runLaw p le_rfl).event (fun a => 0 < s.certificate p.K a) := by + let q := sourceLaw (fun x y => (s.activity x y : ℝ)) p.K p.D + have hz : 0 < sourceBagZ (fun x y => (s.activity x y : ℝ)) p.K p.D := by + rw [s.activity_cast] + exact sourceBagZ_pos _ s.toReal.activity_pos (s.toReal.partition_pos p.even) _ _ + have hq0 : ∀ a, 0 ≤ q a := sourceLaw_nonneg _ (fun x y => by exact_mod_cast s.activity_pos x y) _ _ hz.le + have hq1 : ∑ a, q a = 1 := by + convert sourceLaw_sum (fun x y => (s.activity x y : ℝ)) p.K p.D hz.ne' using 1 + exact Variation.sum_instances _ _ _ + have hm := (s.certificate_mean_lower p hs hZ).trans + (mean_le_positive_event q (fun a => (s.certificate p.K a : ℝ)) hq0 + (fun a => by exact_mod_cast s.certificate_range p.K a)) + have hev : event q (fun a => 0 < (s.certificate p.K a : ℝ)) = + event q (fun a => 0 < s.certificate p.K a) := by + congr 1 + ext a + exact_mod_cast Iff.rfl + rw [hev] at hm + have hd := event_sub_le (s.runLaw p le_rfl).mass q ((s.runLaw p le_rfl).total.trans hq1.symm) + (fun a => 0 < s.certificate p.K a) + have ht := s.runLaw_tv p le_rfl + have hk : (1:ℝ) ≤ p.K := by exact_mod_cast p.K_pos + have hS : (1:ℝ) ≤ p.S := by exact_mod_cast p.S_pos + have hc : 3/(1000*(p.K:ℝ)*p.S) ≤ (3:ℝ)/1000 := by + apply (div_le_div_iff₀ (by positivity) (by norm_num)).mpr + nlinarith [mul_le_mul hk hS (by norm_num) (by positivity)] + have hh := (abs_sub_le_iff.mp hd).2 + change 1/5 ≤ event (s.runLaw p le_rfl).mass (fun a => 0 < s.certificate p.K a) + dsimp only [q] at * + linarith + +end MatchingFPRAS.FiniteTrial + +namespace MatchingFPRAS.Adaptive +open Finset +open scoped Classical + +variable {Ω : Type*} [Fintype Ω] + +lemma Law.iid_all (μ : Law Ω) (r : ℕ) (P : Ω → Prop) : + (μ.iid r).event (fun x => ∀ i, P (x i)) = (μ.event P)^r := by + unfold Law.event Law.iid Variation.iid + calc + _ = ∑ x : Fin r → Ω, ∏ i, if P (x i) then μ (x i) else 0 := by + apply sum_congr rfl + intro x _ + by_cases hx : ∀ i, P (x i) + · simp [hx] + · obtain ⟨i, hi⟩ := not_forall.mp hx + simp only [hx, ite_false] + symm + apply prod_eq_zero (mem_univ i) + simp [hi] + _ = ∏ _ : Fin r, (∑ x, if P x then μ x else 0) := by + convert (Fintype.prod_sum (fun (_ : Fin r) (x : Ω) => if P x then μ x else 0)).symm using 1 + _ = _ := by simp + +lemma Law.iid_no_certificate (μ : Law Ω) (P : Ω → Prop) (hP : (1:ℝ)/5 ≤ μ.event P) : + (μ.iid 16).event (fun x => ¬∃ i, P (x i)) ≤ 1/16 := by + have hc : μ.event (fun x => ¬P x) ≤ 4/5 := by + have h := Variation.event_complement μ.mass P + change μ.event P + μ.event (fun x => ¬P x) = ∑ x, μ.mass x at h + rw [μ.total] at h + linarith + have he : (fun x : Fin 16 → Ω => ¬∃ i, P (x i)) = (fun x => ∀ i, ¬P (x i)) := by + funext x + simp + rw [he] + have hi := μ.iid_all 16 (fun x => ¬P x) + change Variation.event _ _ = _ at hi + have hie : (μ.iid 16).event (fun x => ∀ i, ¬P (x i)) = (μ.event (fun x => ¬P x))^16 := by + convert hi using 1 + exact Variation.sum_instances _ _ _ + rw [hie] + calc + _ ≤ (4/5:ℝ)^16 := pow_le_pow_left₀ (μ.event_nonneg _) hc _ + _ ≤ 1/16 := by norm_num + +end MatchingFPRAS.Adaptive + +namespace MatchingFPRAS.FiniteTrial +open Finset Switching Transport Enlargement Adaptive Variation +open scoped Classical + +variable {G : GraphInput} [Nontrivial (Fin G.n)] +attribute [local instance] NumberedHierarchy.labelOrder sym2Order bagEdgeOrder bagEdgeFintype +attribute [local instance] UnitRefresh.Computable.allowedDec prodOrder sumOrder +noncomputable local instance (w : Fin G.n → Fin G.n → ℚ) (K : ℕ) : + DecidableEq (SourceLabel (fun x y=>(w x y:ℝ)) K) := Classical.decEq _ +noncomputable local instance (w : Fin G.n → Fin G.n → ℚ) (K : ℕ) : + Fintype (BagEdge (sourceBags (fun x y=>(w x y:ℝ)) K)) := Fintype.ofFinite _ +noncomputable local instance (w : Fin G.n → Fin G.n → ℚ) (K : ℕ) : + Fintype (SourceMarked (fun x y=>(w x y:ℝ)) K) := Fintype.ofFinite _ + +abbrev GuardSamples (p : Trial.Parameters G) (s : ScaleState G p.K) := + Fin 16 → SourceMarked (fun x y => (s.activity x y : ℝ)) p.K +noncomputable def guardPass (p : Trial.Parameters G) (s : ScaleState G p.K) (x : GuardSamples p s) : Prop := + ∃ i, 0 < s.certificate p.K (x i) +noncomputable def guardLaw (p : Trial.Parameters G) (s : ScaleState G p.K) : Law (GuardSamples p s) := + (s.runLaw p le_rfl).iid 16 +lemma guard_failure (p : Trial.Parameters G) (s : ScaleState G p.K) + (hs : s.Balanced p.hn) (hZ : 0 < Z G) : + (guardLaw p s).event (fun x => ¬guardPass p s x) ≤ 1/16 := by + have h := (s.runLaw p le_rfl).iid_no_certificate + (fun x => 0 < s.certificate p.K x) (s.guard_success p hs hZ) + exact h + +abbrev GuardedTrial (p : Trial.Parameters G) := + Σ x : (layers p p.K le_rfl).Ω, GuardSamples p ((layers p p.K le_rfl).state x) +noncomputable def guardedLaw (p : Trial.Parameters G) : Law (GuardedTrial p) := + (layers p p.K le_rfl).law.sigma (fun x => guardLaw p ((layers p p.K le_rfl).state x)) +noncomputable def guardedOutput (p : Trial.Parameters G) (x : GuardedTrial p) : ℚ := + if guardPass p ((layers p p.K le_rfl).state x.1) x.2 then output p x.1 else 0 +lemma guardedOutput_nonneg (p : Trial.Parameters G) (x : GuardedTrial p) : 0 ≤ guardedOutput p x := by + unfold guardedOutput + split_ifs + · exact output_nonneg _ _ + · rfl + +theorem guarded_trial_failure (p : Trial.Parameters G) (hZ : 0 < Z G) : + (guardedLaw p).event (fun x => ¬Accurate p (guardedOutput p x)) ≤ 1/10 := by + have hf := first_failure_sigma (layers p p.K le_rfl).law + (fun x => guardLaw p ((layers p p.K le_rfl).state x)) + ((layers p p.K le_rfl).good p) (fun x => Accurate p (guardedOutput p x)) (1/16) (by norm_num) + (fun x hx => ((guardLaw p ((layers p p.K le_rfl).state x)).event_mono + (fun y hy hp => by + apply hy + simp only [guardedOutput, hp, ite_true] + exact good_output p hZ x hx)).trans (guard_failure p _ hx.1 hZ)) + have hb := layers_failure p p.K le_rfl + have hk : (p.K:ℝ) ≠ 0 := by exact_mod_cast p.K_pos.ne' + have he : (p.K:ℝ) * (13/(1000*p.K)) = 13/1000 := by field_simp + rw [he] at hb + change (guardedLaw p).event _ ≤ _ at hf + linarith + +end MatchingFPRAS.FiniteTrial + +end OAI diff --git a/lean/OAI/Combinatorics/MatchingCount/Algorithm/OnlineAmplification.lean b/lean/OAI/Combinatorics/MatchingCount/Algorithm/OnlineAmplification.lean new file mode 100644 index 0000000000000000000000000000000000000000..2118a961fdfbf0f1c8cdbd4bf355902a90bd0453 --- /dev/null +++ b/lean/OAI/Combinatorics/MatchingCount/Algorithm/OnlineAmplification.lean @@ -0,0 +1,42 @@ +import Mathlib +import OAI.Combinatorics.MatchingCount.Algorithm.OnlineGuardLaw +import OAI.Combinatorics.MatchingCount.Algorithm.OnlineMedian + +namespace OAI + +namespace MatchingFPRAS.OnlineAmplification +open PhysicalStream TreeTyped + +abbrev TrialInput := List Bool×OnlineTrial.State + +def trials (x : ℕ×TrialInput) : Experiment (List TreeFraction.Fraction) := + OnlineTree.traverseM OnlineGuard.trial (List.replicate x.1 x.2) +noncomputable def trialsRealizer : OnlineTree.Realizer trials := + OnlineTree.composition (OnlineTree.deterministic OnlineSample.repeatInputRealizer) + (OnlineTree.traverse OnlineGuard.trialRealizer) +def run (x : ℕ×TrialInput) : Experiment TreeFraction.Fraction := (trials x).map OnlineMedian.median +noncomputable def runRealizer : OnlineTree.Realizer run := + (OnlineTree.composition trialsRealizer (OnlineTree.deterministic OnlineMedian.medianRealizer)).congr (by + intro x h; simp only [run,Experiment.mean_map,Experiment.mean_bind,Experiment.mean]) + +variable {G : GraphInput} [Nontrivial (Fin G.n)] +noncomputable def initial (p : Trial.Parameters G) : TrialInput := + (List.replicate p.K false,OnlineTrial.represent p (FiniteTrial.firstLayer p) PUnit.unit) +lemma trials_mean (p : Trial.Parameters G) (r : ℕ) (h : List TreeFraction.Fraction→ℚ) : + (trials (r,initial p)).mean h=qaverage (fun bs : Fin r→(Fin (FiniteTrial.guardedBits p)→Bool)=> + h (List.ofFn (fun i=>TreeFraction.repr (FiniteTrial.guardedBitOutput p (bs i))))) := by + rw [trials,←List.ofFn_const] + exact mean_traverse_ofFn OnlineGuard.trial r (fun _=>initial p) + (fun _ b=>TreeFraction.repr (FiniteTrial.guardedBitOutput p b)) (fun _=>OnlineGuard.trial_mean p) h +lemma run_mean (p : Trial.Parameters G) (δ : ℚ) (h : TreeFraction.Fraction→ℚ) : + (run (2*Amplification.halfRepetitions δ+1,initial p)).mean h= + qaverage (fun b=>h (TreeFraction.repr (FiniteTrial.guardedAmplifiedBitOutput p δ b))) := by + rw [run,Experiment.mean_map,trials_mean] + simp_rw [OnlineMedian.median_repr _ (fun _=>FiniteTrial.guardedBitOutput_nonneg p _)] + change _=qaverage ((fun bs : Fin (2*Amplification.halfRepetitions δ+1)→(Fin (FiniteTrial.guardedBits p)→Bool)=> + h (TreeFraction.repr (Amplification.median (fun i=>FiniteTrial.guardedBitOutput p (bs i))))) ∘ + Transport.matrixBitsEquiv (2*Amplification.halfRepetitions δ+1) (FiniteTrial.guardedBits p)) + exact (qaverage_equiv _ _).symm +end MatchingFPRAS.OnlineAmplification + +end OAI diff --git a/lean/OAI/Combinatorics/MatchingCount/Algorithm/OnlineCoolingSchedule.lean b/lean/OAI/Combinatorics/MatchingCount/Algorithm/OnlineCoolingSchedule.lean new file mode 100644 index 0000000000000000000000000000000000000000..bc50fe0ed6e9318b310effe78a53c60a5fe25d19 --- /dev/null +++ b/lean/OAI/Combinatorics/MatchingCount/Algorithm/OnlineCoolingSchedule.lean @@ -0,0 +1,134 @@ +import Mathlib +import OAI.Combinatorics.MatchingCount.Algorithm.EmpiricalDenom +import OAI.Combinatorics.MatchingCount.Complexity.TreeNumericCosts +import OAI.Combinatorics.MatchingCount.Algorithm.OnlinePowerSearch +import OAI.Combinatorics.MatchingCount.Arithmetic.OnlineFractionParam + +namespace OAI + +namespace MatchingFPRAS.OnlineSchedule +open TreeTyped TreeFraction Polynomial + +def fuelRealizer : Realizer (fun n : ℕ=>List.replicate n false) := + (composition range (map (constant false))).congr (by intro n; simp) +lemma fuel_numeric_work : WorkBound fuelRealizer id := + work_congr _ (work_then_polynomial range_numeric_work (polynomial_map (polynomial_constant false))) +lemma work_fuelAfter {A : Type} [Codec A] {f : A→ℕ} {F : Realizer f} {m : A→ℕ} + (hF : WorkBound F m) (p : Polynomial ℕ) (hf : ∀ a,f a≤p.eval (m a)) : + WorkBound (composition F fuelRealizer) m := work_composition hF fuel_numeric_work p hf + +abbrev CoolingInput := ℕ×Fraction +def scheduleBound (x : CoolingInput) : ℕ := x.1*(x.1*x.1+32*natCeil (inverse x.2)) +def scheduleBoundRealizer : Realizer scheduleBound := + (first.mulNat ((first.mulNat first).addNat + ((constant 32).mulNat (composition (composition second inverseRealizer) natCeilRealizer)))).congr (fun _=>rfl) +lemma polynomial_scheduleBound : PolynomialTime scheduleBoundRealizer := by + unfold scheduleBoundRealizer; apply polynomial_congr + have := polynomial_inverse + have := polynomial_natCeil + simp only [Realizer.addNat,Realizer.mulNat] + tree_cost +lemma scheduleBound_repr (n : ℕ) (e : ℚ) (he : 0≤e) : + scheduleBound (n,TreeFraction.repr e)=Counting.schedulePolynomial n e := by + unfold scheduleBound Counting.schedulePolynomial + rw [inverse_repr e he,natCeil_repr _ (by positivity)] + +abbrev CoolingPowerInput := CoolingInput×List Bool +def coolingPowerPlan (x : CoolingPowerInput) : Fraction×Fraction := + (TreeFraction.add ((1,1),TreeFraction.div ((1,1),(x.1.1,1))), + TreeFraction.div (TreeFraction.mul ((32,1),fuelPower ((x.1.1,1),x.2)),x.1.2)) +def coolingPowerPlanRealizer : Realizer coolingPowerPlan := + (pair (composition (pair (constant (1,1)) + (composition (pair (constant (1,1)) (pair first.fst (constant 1))) divRealizer)) addRealizer) + (composition (pair (composition (pair (constant (32,1)) + (composition (pair (pair first.fst (constant 1)) second) fuelPowerRealizer)) mulRealizer) + first.snd) divRealizer)).congr (fun _=>rfl) +lemma polynomial_coolingPowerPlan : PolynomialTime coolingPowerPlanRealizer := by + unfold coolingPowerPlanRealizer; apply polynomial_congr + dsimp only [Realizer.fst, Realizer.snd] + have := polynomial_div + have := polynomial_mul + have := TreeFraction.polynomial_add + have := polynomial_fuelPower + tree_cost +lemma coolingPowerPlan_repr (n : ℕ) (e : ℚ) (he : 0≤e) (fuel : List Bool) : + coolingPowerPlan ((n,TreeFraction.repr e),fuel)= + (TreeFraction.repr (1+1/(n:ℚ)),TreeFraction.repr (32*(n:ℚ)^fuel.length/e)) := by + unfold coolingPowerPlan + rw [←repr_nat n,show ((1,1) : Fraction)=TreeFraction.repr (1:ℚ) from rfl, + show ((32,1) : Fraction)=TreeFraction.repr (32:ℚ) from rfl, + div_repr (by decide) (by positivity),add_repr (by decide) (by positivity), + fuelPower_repr _ (by positivity),mul_repr (by decide) (by positivity), + div_repr (by positivity) he] + +def coolingSearchInput (x : CoolingInput) : PowerSearchInput := + (coolingPowerPlan (x,List.replicate (x.1/2) false),List.replicate (scheduleBound x) false) +def coolingSearchInputRealizer : Realizer coolingSearchInput := + pair (composition (pair identity (composition (composition (pair first (constant 2)) quotient) fuelRealizer)) + coolingPowerPlanRealizer) (composition scheduleBoundRealizer fuelRealizer) +def coolingSchedule (x : CoolingInput) : ℕ := findPower (coolingSearchInput x) +def coolingScheduleRealizer : Realizer coolingSchedule := composition coolingSearchInputRealizer findPowerRealizer + +def coolingMeasure (x : CoolingInput) : ℕ := x.1+natCeil (inverse x.2)+weight x +lemma weight_le_coolingMeasure (x : CoolingInput) : weight x≤coolingMeasure x := by unfold coolingMeasure; omega +lemma work_coolingSearchInput : WorkBound coolingSearchInputRealizer coolingMeasure := by + have lift {A : Type} [Codec A] {f : CoolingInput→A} {F : Realizer f} (hF : PolynomialTime F) : + WorkBound F coolingMeasure := work_of_polynomial hF X (fun x=>by simpa using weight_le_coolingMeasure x) + have hp {A B : Type} [Codec A] [Codec B] {f : CoolingInput→A} {g : CoolingInput→B} + {F : Realizer f} {G : Realizer g} (hF : WorkBound F coolingMeasure) (hG : WorkBound G coolingMeasure) : + WorkBound (pair F G) coolingMeasure := work_pair hF hG X (fun x=>by simpa using weight_le_coolingMeasure x) + unfold coolingSearchInputRealizer + apply hp + · apply work_then_polynomial _ polynomial_coolingPowerPlan + apply hp (lift polynomial_identity) + apply work_fuelAfter (lift (polynomial_composition + (polynomial_pair polynomial_first (polynomial_constant 2)) polynomial_quotient)) X + intro x + have h:=Nat.div_le_self x.1 2 + simp only [Polynomial.eval_X,Function.comp_apply] + unfold coolingMeasure + omega + · apply work_fuelAfter (lift polynomial_scheduleBound) (X*(X*X+32*X)) + intro x + have hn : x.1≤coolingMeasure x := by unfold coolingMeasure; omega + have he : natCeil (inverse x.2)≤coolingMeasure x := by unfold coolingMeasure; omega + simp only [scheduleBound,Polynomial.eval_mul,Polynomial.eval_X,Polynomial.eval_add,Polynomial.eval_ofNat] + gcongr +lemma work_coolingSchedule : WorkBound coolingScheduleRealizer coolingMeasure := + work_then_polynomial work_coolingSearchInput polynomial_findPower + +lemma schedule_power_iff (n : ℕ) (hn : 2≤n) (e : ℚ) (he : 0positive (sparseCertificate (x.1,b))) +def acceptRealizer : TreeTyped.Realizer accept := + (composition (mapWith (composition sparseCertificateRealizer positiveRealizer)) any).congr (by + intro x; simp only [accept,Function.comp_def,List.any_map,Function.id_def]) +lemma polynomial_accept : PolynomialTime acceptRealizer := by + unfold acceptRealizer + apply polynomial_congr + exact polynomial_composition (polynomial_mapWith (polynomial_composition polynomial_sparseCertificate polynomial_positive)) polynomial_any + +def test (x : RequestInput) : Experiment Bool := + (OnlineSample.many (16,sourceRequest x)).map (fun bs=>accept (x.1,bs)) +noncomputable def testRealizer : OnlineTree.Realizer test := + (OnlineTree.composition (OnlineTree.pair (OnlineTree.deterministic first) + (OnlineTree.composition (OnlineTree.deterministic (pair (constant 16) sourceRequestRealizer)) OnlineSample.manyRealizer)) + (OnlineTree.deterministic acceptRealizer)).congr (by + intro x h; simp only [test,Experiment.mean_bind,Experiment.mean_map,Experiment.mean]) + +def finish (x : Fraction×Bool) : Fraction := if x.2 then x.1 else (0,1) +def finishRealizer : TreeTyped.Realizer finish := + (choose second first (constant (0,1))).congr (fun _=>rfl) +lemma polynomial_finish : PolynomialTime finishRealizer := by + unfold finishRealizer; apply polynomial_congr; tree_cost + +def checked (x : OnlineTrial.State) : Experiment Fraction := + (test x.1).map (fun b=>finish (x.2,b)) +noncomputable def checkedRealizer : OnlineTree.Realizer checked := + (OnlineTree.composition (OnlineTree.pair (OnlineTree.deterministic second) + (OnlineTree.composition (OnlineTree.deterministic first) testRealizer)) + (OnlineTree.deterministic finishRealizer)).congr (by + intro x h; simp only [checked,Experiment.mean_bind,Experiment.mean_map,Experiment.mean]) + +def trial (x : List Bool×OnlineTrial.State) : Experiment Fraction := + (OnlineTrial.sweep x).bind checked +noncomputable def trialRealizer : OnlineTree.Realizer trial := + OnlineTree.composition OnlineTrial.sweepRealizer checkedRealizer +end MatchingFPRAS.OnlineGuard + +end OAI diff --git a/lean/OAI/Combinatorics/MatchingCount/Algorithm/OnlineGuardLaw.lean b/lean/OAI/Combinatorics/MatchingCount/Algorithm/OnlineGuardLaw.lean new file mode 100644 index 0000000000000000000000000000000000000000..d9d81875026efa07946313601f1cd5624a82bc59 --- /dev/null +++ b/lean/OAI/Combinatorics/MatchingCount/Algorithm/OnlineGuardLaw.lean @@ -0,0 +1,100 @@ +import Mathlib +import OAI.Combinatorics.MatchingCount.Tapes.GuardBits +import OAI.Combinatorics.MatchingCount.Algorithm.OnlineGuard +import OAI.Combinatorics.MatchingCount.Algorithm.OnlineTrialLaw + +namespace OAI + +namespace MatchingFPRAS.OnlineGuard +open PhysicalStream TreeTyped TreeFraction ExecutableSource ExecutableScaling OnlineSchedule OnlineStage +open Transport UnitRefresh Enlargement Variation TreeTyped.Numbered +open scoped Classical + +noncomputable local instance {n : ℕ} [Nontrivial (Fin n)] (w : Fin n→Fin n→ℝ) (K : ℕ) : + Fintype (SourceMarked w K) := Fintype.ofFinite _ +attribute [local instance] NumberedHierarchy.labelOrder +attribute [local instance] Transport.sym2Order Transport.bagEdgeOrder Transport.bagEdgeFintype +attribute [local instance] UnitRefresh.Computable.allowedDec Transport.prodOrder Transport.sumOrder +variable {G : GraphInput} [Nontrivial (Fin G.n)] + +lemma guard_many_mean (p : Trial.Parameters G) (s : FiniteTrial.ScaleState G p.K) (h : Bool→ℚ) : + (test (fixedData p s,p.S)).mean h= + qaverage (fun b=>h (decide (FiniteTrial.guardPass p s (s.drawGuard p b)))) := by + classical + have hD : 0fun i=>raw (bs i))=imageLaw (s.drawGuard p) := by + rw [imageLaw_componentwise,hr,FiniteTrial.ScaleState.drawGuard_law] + rfl + unfold test + rw [Experiment.mean_map,sourceRequest_source] + unfold fixedRequest + simp only [Trial.Parameters.N] + rw [OnlineSample.mean_many] + apply Eq.trans _ (qaverage_eq_of_imageLaw_eq _ _ hp (fun x=>h (decide (FiniteTrial.guardPass p s x)))) + apply qaverage_congr + intro bs + apply congrArg h + have hcert (b : Raw s.activity p.K (FiniteTrial.sourceD (G:=G) p.K) (denominator p) (1/denominator p)) : + sparseCertificate (fixedData p s,OnlineSample.sampleRep + (fun i=>index (orderedEnum (BagEdge (RationalSource.bags s.activity p.K)) i)) b)= + TreeFraction.repr (s.certificate p.K (raw b)) := by + have hc:=sparseCertificate_source p.hn p.even s p.K (FiniteTrial.sourceD (G:=G) p.K) + hD (s.cap le_rfl) + (List.replicate (tierCount (n:=G.n) p.K (FiniteTrial.sourceD (G:=G) p.K)) false) + (List.replicate (copies (n:=G.n) p.K (FiniteTrial.sourceD (G:=G) p.K)) false) + (by simpa using hq) b.1 (fun e=>b.2 ((orderedEnum _).symm e)) + dsimp only at hc + simp only [List.map_ofFn] at hc + change sparseCertificate (fixedData p s,_) = _ at hc + rw [generated_eq_raw] at hc + rw [FiniteTrial.ScaleState.certificate,realRawDraw_inverse] + simpa only [OnlineSample.sampleRep,OnlineSample.scanRep,OnlineSample.localRep, + List.map_ofFn,Function.comp_def,Equiv.symm_apply_apply,NumericLadder.localBitsRep] using hc + apply Bool.eq_iff_iff.mpr + rw [decide_eq_true_eq] + simp only [accept,List.any_eq_true,List.mem_ofFn,FiniteTrial.guardPass] + constructor + · rintro ⟨x,⟨i,rfl⟩,hi⟩ + rw [hcert,positive_repr (s.certificate_range p.K _).1,decide_eq_true_eq] at hi + exact ⟨i,hi⟩ + · rintro ⟨i,hi⟩ + refine ⟨_,⟨i,rfl⟩,?_⟩ + rw [hcert,positive_repr (s.certificate_range p.K _).1,decide_eq_true_eq] + exact hi + +lemma checked_mean (p : Trial.Parameters G) (x : (FiniteTrial.layers p p.K le_rfl).Ω) (h : Fraction→ℚ) : + (checked (OnlineTrial.represent p (FiniteTrial.layers p p.K le_rfl) x)).mean h= + qaverage (fun b=>h (TreeFraction.repr (FiniteTrial.guardedOutput p ⟨x,((FiniteTrial.layers p p.K le_rfl).state x).drawGuard p b⟩))) := by + unfold checked OnlineTrial.represent + rw [Experiment.mean_map,guard_many_mean] + apply qaverage_congr + intro b + simp only [finish,decide_eq_true_eq,FiniteTrial.guardedOutput,OnlineTrial.product,FiniteTrial.output] + split_ifs <;> rfl + +lemma trial_mean (p : Trial.Parameters G) (h : Fraction→ℚ) : + (trial (List.replicate p.K false,OnlineTrial.represent p (FiniteTrial.firstLayer p) PUnit.unit)).mean h= + qaverage (fun b=>h (TreeFraction.repr (FiniteTrial.guardedBitOutput p b))) := by + unfold trial + rw [Experiment.mean_bind,OnlineTrial.sweep_mean p p.K le_rfl] + simp_rw [checked_mean] + change _=qaverage ((fun c : (Fin (p.K*FiniteTrial.stageBits p)→Bool)×(Fin (FiniteTrial.guardBits p)→Bool)=> + h (TreeFraction.repr (FiniteTrial.guardedOutput p ⟨FiniteTrial.drawLayer p p.K le_rfl c.1, + ((FiniteTrial.layers p p.K le_rfl).state (FiniteTrial.drawLayer p p.K le_rfl c.1)).drawGuard p c.2⟩))) ∘ + pairBitsEquiv (p.K*FiniteTrial.stageBits p) (FiniteTrial.guardBits p)) + rw [qaverage_equiv,qaverage_prod] +end MatchingFPRAS.OnlineGuard + +end OAI diff --git a/lean/OAI/Combinatorics/MatchingCount/Algorithm/OnlineHistorySize.lean b/lean/OAI/Combinatorics/MatchingCount/Algorithm/OnlineHistorySize.lean new file mode 100644 index 0000000000000000000000000000000000000000..97e8daa65e6ad3d7ab7e89a8534586dc98fc33bd --- /dev/null +++ b/lean/OAI/Combinatorics/MatchingCount/Algorithm/OnlineHistorySize.lean @@ -0,0 +1,126 @@ +import Mathlib +import OAI.Combinatorics.MatchingCount.Machines.TreeHistorySize +import OAI.Combinatorics.MatchingCount.Graphs.OnlineGraphInvariant +import OAI.Combinatorics.MatchingCount.Complexity.OnlineStageCost + +namespace OAI + +namespace MatchingFPRAS.OnlineTrial +open TreeTyped TreeFraction PhysicalStream ExecutableSource ExecutableScaling +open BitArithmetic Polynomial OnlineStage OnlineSchedule OnlineSample + +variable {G : GraphInput} [Nontrivial (Fin G.n)] + +lemma product_bits (p : Trial.Parameters G) (j : ℕ) (hj : j ≤ p.K) + (x : (FiniteTrial.layers p j hj).Ω) : + FractionBound ((Z (completeGraph G.n)+1)*(p.empiricalBound^2)^j) + (product p (FiniteTrial.layers p j hj) x : ℝ) := by + have h := FractionBound.prod Finset.univ (fun i=>((FiniteTrial.layers p j hj).ratios x i : ℝ)) (p.empiricalBound^2) + (fun i _=>FiniteTrial.layers_ratio_bits p j hj x i) + simpa only [product,Rat.cast_mul,Rat.cast_natCast,Rat.cast_prod,Finset.card_univ,Fintype.card_fin] using + (FractionBound.nat (Z (completeGraph G.n))).mul h + +noncomputable def sizeNorm (p : Trial.Parameters G) (g : ExecutableAdaptive.GraphData) : ℕ := + G.n+p.K+p.N+p.D+p.S+p.T+p.q+weight g+(Z (completeGraph G.n)+1).size +omit [Nontrivial (Fin G.n)] in +lemma sizeNorm_fields (p : Trial.Parameters G) (g : ExecutableAdaptive.GraphData) : + G.n ≤ sizeNorm p g ∧ p.K ≤ sizeNorm p g ∧ p.N ≤ sizeNorm p g ∧ p.D ≤ sizeNorm p g ∧ + p.S ≤ sizeNorm p g ∧ p.T ≤ sizeNorm p g ∧ p.q ≤ sizeNorm p g ∧ weight g ≤ sizeNorm p g ∧ + (Z (completeGraph G.n)+1).size ≤ sizeNorm p g := by + unfold sizeNorm;omega + +noncomputable def vectorPolynomial : Polynomial ℕ := + let B : Polynomial ℕ := X+1 + B*(4*B+8*(B+B*B*(19+B+2*(B+B*B+1))+1)+6)+1 +noncomputable def productPolynomial : Polynomial ℕ := + let B : Polynomial ℕ := X+1 + 8*(B+B*(2*(B+B*B+1)+1)+1)+3 +lemma vector_weight_bound (p : Trial.Parameters G) (g : ExecutableAdaptive.GraphData) + (j : ℕ) (hj : j ≤ p.K) (x : (FiniteTrial.layers p j hj).Ω) : + weight (vectorRep ((FiniteTrial.layers p j hj).state x).scale) ≤ vectorPolynomial.eval (sizeNorm p g) := by + obtain ⟨hn,hk,hN,hd,hs,ht,hq,hg,hz⟩:=sizeNorm_fields p g + have hn' := (Nat.size_le.mpr Nat.lt_two_pow_self : G.n.size ≤ G.n) + have hn1 := (Nat.size_le.mpr Nat.lt_two_pow_self : (G.n+1).size ≤ G.n+1) + have hd1 := (Nat.size_le.mpr Nat.lt_two_pow_self : (p.D+1).size ≤ p.D+1) + have hs' := (Nat.size_le.mpr Nat.lt_two_pow_self : p.S.size ≤ p.S) + have hv:=history_vector_weight p j hj x + have hj' : j ≤ sizeNorm p g+1 := by omega + simp only [vectorPolynomial,Polynomial.eval_add,Polynomial.eval_mul,Polynomial.eval_ofNat,Polynomial.eval_X,Polynomial.eval_one] + change _ ≤ (sizeNorm p g+1)*(4*(sizeNorm p g+1)+8*((sizeNorm p g+1)+(sizeNorm p g+1)*(sizeNorm p g+1)* + (19+(sizeNorm p g+1)+2*((sizeNorm p g+1)+(sizeNorm p g+1)*(sizeNorm p g+1)+1))+1)+6)+1 + apply hv.trans + have hNN : Fintype.card (Enlargement.SourceVertex (Fin G.n) p.K) ≤ sizeNorm p g+1 := by + change p.N ≤ _;omega + gcongr <;> omega +lemma product_weight_bound (p : Trial.Parameters G) (g : ExecutableAdaptive.GraphData) + (j : ℕ) (hj : j ≤ p.K) (x : (FiniteTrial.layers p j hj).Ω) : + weight (TreeFraction.repr (product p (FiniteTrial.layers p j hj) x)) ≤ productPolynomial.eval (sizeNorm p g) := by + obtain ⟨hn,hk,hN,hd,hs,ht,hq,hg,hz⟩:=sizeNorm_fields p g + have he := size_empiricalBound p + have hS:=(Nat.size_le.mpr Nat.lt_two_pow_self : p.S.size ≤ p.S) + have hnn:=(Nat.size_le.mpr Nat.lt_two_pow_self : (G.n+1).size ≤ G.n+1) + have he' : p.empiricalBound.size ≤ (sizeNorm p g+1)+(sizeNorm p g+1)*(sizeNorm p g+1)+1 := by + apply he.trans + change p.S.size+p.N*(G.n+1).size+1 ≤ _ + gcongr <;> omega + have hp2:=size_pow_le p.empiricalBound 2 + have hpj:=size_pow_le (p.empiricalBound^2) j + have hmul:=size_mul_le (Z (completeGraph G.n)+1) ((p.empiricalBound^2)^j) + have hb : ((Z (completeGraph G.n)+1)*(p.empiricalBound^2)^j).size ≤ + (sizeNorm p g+1)+(sizeNorm p g+1)*(2*((sizeNorm p g+1)+(sizeNorm p g+1)*(sizeNorm p g+1)+1)+1)+1 := by + calc + _ ≤ (Z (completeGraph G.n)+1).size+j*(2*p.empiricalBound.size+1)+1 := by + have h:=Nat.mul_le_mul_left j hp2;omega + _ ≤ _ := by gcongr <;> omega + have hw:=fraction_weight_of_bound (product_bits p j hj x) + simp only [productPolynomial,Polynomial.eval_add,Polynomial.eval_mul,Polynomial.eval_ofNat,Polynomial.eval_X,Polynomial.eval_one] + change _ ≤ 8*((sizeNorm p g+1)+(sizeNorm p g+1)*(2*((sizeNorm p g+1)+(sizeNorm p g+1)*(sizeNorm p g+1)+1)+1)+1)+3 + omega + +noncomputable def statePolynomial : Polynomial ℕ := 100*(X+1)+2*vectorPolynomial+2*productPolynomial +lemma data_weight (g : ExecutableAdaptive.GraphData) (j K D T Q : ℕ) (v : Vector) : + weight ((((g,List.replicate j false),(((List.replicate (2*K+2) false,List.replicate (2*K) false),D), + (List.replicate T false,List.replicate Q false))),v))= + weight g+2*j+8*K+weight D+2*T+2*Q+weight v+16 := by + simp only [weight_prod,weight_replicate,show weight false=1 from rfl] + omega +lemma stateSize_mk (d : SparseStageData) (S : ℕ) (q : Fraction) : + stateSize ((d,S),q)=d.1.2.1.2+S+3+2*weight d+2*weight S+weight q := by + unfold stateSize requestSize + simp only [weight_prod] + omega +lemma state_weight_bound (f : OnlineGraph.Edges→OnlineGraph.Edges) (p : Trial.Parameters G) + (j : ℕ) (hj : j ≤ p.K) (x : (FiniteTrial.layers p j hj).Ω) : + stateSize (OnlineGraph.state f (represent p (FiniteTrial.layers p j hj) x)) ≤ + statePolynomial.eval (sizeNorm p (OnlineGraph.graph f (ExecutableAdaptive.graphRep G))) := by + let g:=OnlineGraph.graph f (ExecutableAdaptive.graphRep G) + obtain ⟨hn,hk,hN,hd,hs,ht,hq,hg,hz⟩:=sizeNorm_fields p g + have hv:=vector_weight_bound p g j hj x + have hp:=product_weight_bound p g j hj x + have hD : FiniteTrial.sourceD (G:=G) p.K=p.D := FiniteTrial.sourceD_eq p.K + have hT : tierCount (n:=G.n) p.K (FiniteTrial.sourceD (G:=G) p.K)=p.T := by + rw [hD];exact Transport.endpoint_eq p.N p.D p.K _ + have hQ : copies (n:=G.n) p.K (FiniteTrial.sourceD (G:=G) p.K)=p.q := by rw [hD];rfl + have hwd:=weight_nat_numeric p.D + have hws:=weight_nat_numeric p.S + change stateSize ((OnlineGraph.data f (fixedData p ((FiniteTrial.layers p j hj).state x)),p.S), + TreeFraction.repr (product p (FiniteTrial.layers p j hj) x)) ≤ _ + rw [stateSize_mk] + have hw : weight (OnlineGraph.data f (fixedData p ((FiniteTrial.layers p j hj).state x)))= + weight g+2*j+8*p.K+weight p.D+2*p.T+2*p.q+ + weight (vectorRep ((FiniteTrial.layers p j hj).state x).scale)+16 := by + change weight ((((g,List.replicate j false),(((List.replicate (2*p.K+2) false,List.replicate (2*p.K) false), + FiniteTrial.sourceD (G:=G) p.K),(List.replicate (tierCount (n:=G.n) p.K (FiniteTrial.sourceD (G:=G) p.K)) false, + List.replicate (copies (n:=G.n) p.K (FiniteTrial.sourceD (G:=G) p.K)) false))), + vectorRep ((FiniteTrial.layers p j hj).state x).scale))=_ + rw [data_weight,hT,hQ,hD] + rw [hw] + change FiniteTrial.sourceD (G:=G) p.K+p.S+3+2*(weight g+2*j+8*p.K+weight p.D+2*p.T+2*p.q+ + weight (vectorRep ((FiniteTrial.layers p j hj).state x).scale)+16)+2*weight p.S+ + weight (TreeFraction.repr (product p (FiniteTrial.layers p j hj) x)) ≤ statePolynomial.eval (sizeNorm p g) + rw [hD] + simp only [statePolynomial,Polynomial.eval_add,Polynomial.eval_mul,Polynomial.eval_ofNat,Polynomial.eval_X,Polynomial.eval_one] + omega +end MatchingFPRAS.OnlineTrial + +end OAI diff --git a/lean/OAI/Combinatorics/MatchingCount/Algorithm/OnlineInitial.lean b/lean/OAI/Combinatorics/MatchingCount/Algorithm/OnlineInitial.lean new file mode 100644 index 0000000000000000000000000000000000000000..b329160cc4a3921cba365c4553d0375468c2360a --- /dev/null +++ b/lean/OAI/Combinatorics/MatchingCount/Algorithm/OnlineInitial.lean @@ -0,0 +1,86 @@ +import Mathlib +import OAI.Combinatorics.MatchingCount.Algorithm.OnlineLadderSchedule +import OAI.Combinatorics.MatchingCount.Algorithm.OnlineSampleCount +import OAI.Combinatorics.MatchingCount.Algorithm.OnlineAmplification + +namespace OAI + +namespace MatchingFPRAS.OnlineInitial +open TreeTyped TreeFraction ExecutableAdaptive ExecutableScaling ExecutableSource OnlineSchedule + +abbrev Seed := GraphData×(Fraction×Fraction) +abbrev Config := (Seed×ℕ)×(ℕ×ℕ) + +def seedK (x : Seed) : Seed×ℕ := (x,coolingSchedule (x.1.1.length,x.2.1)) +def seedKRealizer : Realizer seedK := + (pair identity (composition (g:=coolingSchedule) (pair (composition first.fst listLength) second.fst) coolingScheduleRealizer)).congr (fun _=>rfl) +def seedN (x : Seed×ℕ) : (Seed×ℕ)×ℕ := (x,vertexNumber (x.1.1.1.length,x.2)) +def seedNRealizer : Realizer seedN := + (pair identity (composition (g:=vertexNumber) (pair (composition first.fst.fst listLength) second) vertexNumberRealizer)).congr (fun _=>rfl) +def seedD (x : (Seed×ℕ)×ℕ) : Config := + (x.1,(x.2,distortion (x.1.1.1.1.length,x.2))) +def seedDRealizer : Realizer seedD := + pair first (pair second (composition (pair (composition first.fst.fst.fst listLength) second) distortionRealizer)) +def config (x : Seed) : Config := seedD (seedN (seedK x)) +def configRealizer : Realizer config := composition (composition seedKRealizer seedNRealizer) seedDRealizer + +def root (n : ℕ) : ℕ := findRoot (n-1,List.replicate n false) +def rootRealizer : Realizer root := + composition (pair (composition (pair identity (constant 1)) subtract) (composition identity fuelRealizer)) findRootRealizer +lemma root_eq (n : ℕ) : root n=(n-1).sqrt := by + apply findRoot_eq + simpa using (Nat.sqrt_le_self (n-1)).trans (Nat.sub_le n 1) +def initialScale (n : ℕ) : Fraction := TreeFraction.div ((1,1),(root n,1)) +def initialScaleRealizer : Realizer initialScale := + composition (pair (constant (1,1)) (pair rootRealizer (constant 1))) divRealizer +lemma initialScale_repr (n : ℕ) : initialScale n=TreeFraction.repr (Initializer.initialScale n) := by + unfold initialScale + rw [root_eq,←repr_nat ((n-1).sqrt),show ((1,1) : Fraction)=TreeFraction.repr (1:ℚ) from rfl,div_repr (by decide) (by positivity)] + rfl + +def scaleVector (vs : List ℕ) : Vector := vs.map (fun i=>(i,initialScale vs.length)) +def scaleVectorRealizer : Realizer scaleVector := + (composition (pair (composition listLength initialScaleRealizer) identity) + (mapWith (pair second first))).congr (fun _=>rfl) +lemma scaleVector_source (G : GraphInput) (hn : 2≤G.n) : + scaleVector (List.range G.n)=vectorRep (FiniteTrial.initialScaleState G hn).scale := by + unfold scaleVector vectorRep + rw [List.length_range,initialScale_repr] + apply List.ext_getElem + · simp + · intro _ _ _ + simp [FiniteTrial.initialScaleState] + +def nRealizer : Realizer (fun x : Config=>x.1.1.1.1.length) := composition first.fst.fst.fst listLength + +def count (x : Config) : ℕ := sampleCount (x.1.1.1.1.length,((x.2.2,x.1.2),x.1.1.2.1)) +def countRealizer : Realizer count := + composition (pair nRealizer (pair (pair second.snd first.snd) first.fst.snd.fst)) sampleCountRealizer + +def data (x : Config) : SparseStageData := + (((x.1.1.1,[]),(((List.replicate (2*x.1.2+2) false,List.replicate (2*x.1.2) false),x.2.2), + (List.replicate (ladderSchedule (x.2,x.1.2)) false,List.replicate (Transport.ladderQ x.2.1 x.2.2) false))), + scaleVector x.1.1.1.1) +def dataRealizer : Realizer data := + (pair (pair (pair first.fst.fst (constant [])) + (pair (pair (pair (composition (g:=fun n=>List.replicate n false) (((constant 2).mulNat first.snd).addNat (constant 2)) fuelRealizer) + (composition ((constant 2).mulNat first.snd) fuelRealizer)) second.snd) + (pair (composition (composition (pair second first.snd) ladderScheduleRealizer) fuelRealizer) + (composition (composition second qRealizer) fuelRealizer)))) + (composition first.fst.fst.fst scaleVectorRealizer)).congr (fun _=>rfl) + +def trialInput (x : Config) : OnlineAmplification.TrialInput := + (List.replicate x.1.2 false,((data x,count x),(UnitRefresh.pairingCount x.1.1.1.1.length,1))) +def trialInputRealizer : Realizer trialInput := + pair (composition first.snd fuelRealizer) + (pair (pair dataRealizer countRealizer) (pair (composition nRealizer pairingNumber) (constant 1))) +def runInput (x : Config) : ℕ×OnlineAmplification.TrialInput := + (repetitions x.1.1.2.2,trialInput x) +def runInputRealizer : Realizer runInput := + (pair (composition (g:=repetitions) first.fst.snd.snd repetitionsRealizer) trialInputRealizer).congr (fun _=>rfl) + +def initializeInput (x : Seed) : ℕ×OnlineAmplification.TrialInput := runInput (config x) +def initializeInputRealizer : Realizer initializeInput := composition configRealizer runInputRealizer +end MatchingFPRAS.OnlineInitial + +end OAI diff --git a/lean/OAI/Combinatorics/MatchingCount/Algorithm/OnlineInitialLaw.lean b/lean/OAI/Combinatorics/MatchingCount/Algorithm/OnlineInitialLaw.lean new file mode 100644 index 0000000000000000000000000000000000000000..83d25160e3223be2c9475c188409288112b1ebb7 --- /dev/null +++ b/lean/OAI/Combinatorics/MatchingCount/Algorithm/OnlineInitialLaw.lean @@ -0,0 +1,53 @@ +import Mathlib +import OAI.Combinatorics.MatchingCount.Algorithm.OnlineInitial + +namespace OAI + +namespace MatchingFPRAS.OnlineInitial +open TreeTyped TreeFraction ExecutableAdaptive ExecutableScaling ExecutableSource OnlineSchedule +open Transport Enlargement + +variable {G : GraphInput} [Nontrivial (Fin G.n)] +variable (hn : 2≤G.n) (heven : Even G.n) (ε δ : ℚ) (he : 0<ε) (he1 : ε<1) +local notation "p" => FiniteTrial.parameters G hn heven ε he he1 +noncomputable def sourceSeed : Seed := (graphRep G,(TreeFraction.repr ε,TreeFraction.repr δ)) +lemma config_source : config (sourceSeed (G:=G) ε δ)= + ((sourceSeed (G:=G) ε δ,(p).K),((p).N,FiniteTrial.sourceD (G:=G) (p).K)) := by + have hl : (graphRep G).1.length=G.n := by simp [graphRep] + unfold config seedK seedN seedD sourceSeed + dsimp only + rw [hl,coolingSchedule_eq G.n hn ε he he1] + change ((_,(p).K),(vertexNumber (G.n,(p).K),distortion (G.n,vertexNumber (G.n,(p).K))))=_ + rw [distortion_source,vertexNumber_eq] + rfl +lemma data_source : data (config (sourceSeed (G:=G) ε δ))= + OnlineStage.fixedData p (FiniteTrial.initialScaleState G hn) := by + rw [config_source hn heven ε δ he he1] + unfold data sourceSeed OnlineStage.fixedData OnlineStage.data + dsimp only + rw [show (graphRep G).1=List.range G.n from rfl,scaleVector_source G hn,ladderSchedule_eq _ _ _ (p).N_pos] + rfl +lemma count_source : count (config (sourceSeed (G:=G) ε δ))=(p).S := by + rw [config_source hn heven ε δ he he1] + unfold count sourceSeed + dsimp only + have hl : (graphRep G).1.length=G.n := by simp [graphRep] + rw [hl] + exact sampleCount_source p +lemma trialInput_source : trialInput (config (sourceSeed (G:=G) ε δ))=OnlineAmplification.initial p := by + unfold trialInput + rw [data_source hn heven ε δ he he1,count_source hn heven ε δ he he1,config_source hn heven ε δ he he1] + unfold OnlineAmplification.initial OnlineTrial.represent OnlineTrial.product + simp only [FiniteTrial.firstLayer,Fin.prod_univ_zero,mul_one] + have hg : (sourceSeed (G:=G) ε δ).1.1.length=G.n := by simp [sourceSeed,graphRep] + rw [hg,GraphBridge.complete_count] + rw [TreeFraction.repr_nat] +lemma initializeInput_source (hd : 0≤δ) : initializeInput (sourceSeed (G:=G) ε δ)= + (2*Amplification.halfRepetitions δ+1,OnlineAmplification.initial p) := by + unfold initializeInput runInput + rw [trialInput_source hn heven ε δ he he1,config_source hn heven ε δ he he1] + dsimp only [sourceSeed] + rw [repetitions_repr δ hd] +end MatchingFPRAS.OnlineInitial + +end OAI diff --git a/lean/OAI/Combinatorics/MatchingCount/Algorithm/OnlineLadderSchedule.lean b/lean/OAI/Combinatorics/MatchingCount/Algorithm/OnlineLadderSchedule.lean new file mode 100644 index 0000000000000000000000000000000000000000..6cbf326d59b2f7d92d9c3214bca2f4a154e1725d --- /dev/null +++ b/lean/OAI/Combinatorics/MatchingCount/Algorithm/OnlineLadderSchedule.lean @@ -0,0 +1,99 @@ +import Mathlib +import OAI.Combinatorics.MatchingCount.Machines.TreeBuild +import OAI.Combinatorics.MatchingCount.Algorithm.OnlineCoolingSchedule + +namespace OAI + +namespace MatchingFPRAS.OnlineSchedule +open TreeTyped TreeFraction Polynomial ExecutableSource Transport Enlargement + +abbrev LadderInput := (ℕ×ℕ)×ℕ + +def vertexNumber (x : ℕ×ℕ) : ℕ := + (vertices (List.range x.1,List.replicate (2*x.2+2) false)).length +def vertexNumberRealizer : Realizer vertexNumber := + composition (composition (pair (composition first range) + (composition (((constant 2).mulNat second).addNat (constant 2)) fuelRealizer)) verticesRealizer) listLength +lemma vertexNumber_eq (n K : ℕ) : vertexNumber (n,K)=Fintype.card (SourceVertex (Fin n) K) := by + unfold vertexNumber + rw [vertices_eq_ofFn_length n _ (4*(2*K+2)) (by simp),List.length_ofFn] +lemma vertexNumber_bound (n K : ℕ) : vertexNumber (n,K)≤n+n^2*(4*(2*K+2)) := by + have hprod {A B : Type} (a : List A) (b : List B) : + (a.product b).length=a.length*b.length := List.length_product a b + unfold vertexNumber vertices internalCount + simp only [List.length_append,List.length_map,hprod,List.length_range,List.length_replicate] + have h : (logicalEdges (List.range n)).length≤n*n := by + simpa only [logicalEdges,hprod,List.length_range] using + List.length_filter_le (fun e : ℕ×ℕ=>decide (e.1rfl) +lemma polynomial_distortion : PolynomialTime distortionRealizer := by + unfold distortionRealizer;apply polynomial_congr + have := polynomial_fixedPower 2 + have := polynomial_fixedPower 4 + have := polynomial_successor + simp only [Realizer.mulNat]; tree_cost +lemma distortion_source {G : GraphInput} [Nontrivial (Fin G.n)] (K : ℕ) : + distortion (G.n,vertexNumber (G.n,K))=FiniteTrial.sourceD (G:=G) K := by + simp only [distortion,vertexNumber_eq,FiniteTrial.sourceD] + +def tierBoundRealizer : Realizer (fun x : LadderInput=>tierBound x.1.1 x.1.2 x.2) := + ((composition first.fst (fixedPower 2)).mulNat + (((composition first.snd clogTwo).addNat ((constant 2).mulNat second)).addNat (constant 2))).congr (fun _=>rfl) +lemma polynomial_tierBound : PolynomialTime tierBoundRealizer := by + unfold tierBoundRealizer;apply polynomial_congr + dsimp only [Realizer.fst, Realizer.snd] + have := polynomial_fixedPower 2 + have := polynomial_clogTwo + simp only [Realizer.mulNat,Realizer.addNat]; tree_cost + +def ladderPowerPlan (x : (ℕ×ℕ)×List Bool) : Fraction×Fraction := + (TreeFraction.add ((1,1),TreeFraction.div ((1,1),(x.1.1^2,1))), + TreeFraction.maximum ((x.1.2,1),TreeFraction.mul ((3,1),fuelPower ((4,1),x.2)))) +def ladderPowerPlanRealizer : Realizer ladderPowerPlan := + (pair (composition (pair (constant (1,1)) + (composition (pair (constant (1,1)) (pair (composition first.fst (fixedPower 2)) (constant 1))) divRealizer)) addRealizer) + (composition (pair (pair first.snd (constant 1)) + (composition (pair (constant (3,1)) (composition (pair (constant (4,1)) second) fuelPowerRealizer)) mulRealizer)) maximumRealizer)).congr (fun _=>rfl) +lemma polynomial_ladderPowerPlan : PolynomialTime ladderPowerPlanRealizer := by + unfold ladderPowerPlanRealizer; apply polynomial_congr + dsimp only [Realizer.fst, Realizer.snd] + have := polynomial_div + have := polynomial_mul + have := TreeFraction.polynomial_add + have := TreeFraction.polynomial_maximum + have := polynomial_fuelPower + have := polynomial_fixedPower 2 + tree_cost +lemma ladderPowerPlan_repr (N D : ℕ) (fuel : List Bool) : + ladderPowerPlan ((N,D),fuel)= + (TreeFraction.repr (rationalBase N),TreeFraction.repr (max (D:ℚ) (3*4^fuel.length))) := by + unfold ladderPowerPlan + rw [←repr_nat (N^2),←repr_nat D, + show ((1,1) : Fraction)=TreeFraction.repr (1:ℚ) from rfl, + show ((3,1) : Fraction)=TreeFraction.repr (3:ℚ) from rfl, + show ((4,1) : Fraction)=TreeFraction.repr (4:ℚ) from rfl, + div_repr (by decide) (by positivity),add_repr (by decide) (by positivity), + fuelPower_repr _ (by positivity),mul_repr (by decide) (by positivity), + maximum_repr (by positivity) (by positivity)] + simp only [rationalBase,Nat.cast_pow,one_div] + +def ladderSearchInput (x : LadderInput) : PowerSearchInput := + (ladderPowerPlan (x.1,List.replicate x.2 false),List.replicate (tierBound x.1.1 x.1.2 x.2) false) +def ladderSearchInputRealizer : Realizer ladderSearchInput := + pair (composition (pair first (composition second fuelRealizer)) ladderPowerPlanRealizer) + (composition tierBoundRealizer fuelRealizer) +def ladderSchedule (x : LadderInput) : ℕ := findPower (ladderSearchInput x) +def ladderScheduleRealizer : Realizer ladderSchedule := composition ladderSearchInputRealizer findPowerRealizer +lemma ladderSchedule_eq (N D K : ℕ) (hN : 0l.1.val) (RationalSource.parent w K) + (RationalSource.bags_ranked w K hu) (RationalSource.bags_nonempty w K) + (RationalSource.parent_rank w K) hq (RationalSource.bagWeight w K D) + (RationalSource.startMatching w K he) k r (fun _=>RationalSource.startMatching w K he) bits + (topSlot T q hq)) + (fun e=>(RationalSource.markingTable w hw K D hD e).draw km (mb e)) +lemma generated_eq_core (hw : ∀ a b,0bs.2 ((orderedEnum (BagEdge (RationalSource.bags w K))).symm e)) = + rawDraw w K D m hw hD hu hq he η bs := by + rw [generated_eq_core] + simp only [List.length_replicate] + unfold core rawDraw RationalSource.markedSampler TableMarking.draw RationalSource.topSampler + RationalSource.sampler finiteLadder ladderBitRun + simp only [Function.comp_apply,raw_scan,raw_marks] + +noncomputable local instance : Fintype (BagPM (RationalSource.bags w K)) := Fintype.ofFinite _ +noncomputable local instance : Fintype (RationalSource.Marked w K) := Fintype.ofFinite _ +lemma rawDraw_law (hw : ∀ a b,0inferInstanceAs (Decidable (_≤_)) +def compareRealizer : TreeTyped.Realizer (fun x : Fraction×Fraction=>decide (relation x.1 x.2)) := + (composition (composition (pair second first) lessRealizer) boolNot).congr (by + intro x + change (!(decide (x.2.1*x.1.2b=true) hl + exact Iff.of_eq (by simpa only [TreeFraction.less,decide_eq_true_eq] using this) + exact (not_lt).symm.trans (not_congr hlt) + exact he.trans not_lt + +def sorted (xs : List Fraction) : List Fraction := xs.insertionSort relation +def sortedRealizer : TreeTyped.Realizer sorted := insertionSort relation compareRealizer +lemma polynomial_sorted : PolynomialTime sortedRealizer := polynomial_insertionSort relation polynomial_compare + +def median (xs : List Fraction) : Fraction := (sorted xs).getD (xs.length/2) (0,1) +def medianRealizer : TreeTyped.Realizer median := + composition (pair sortedRealizer (composition (pair listLength (constant 2)) quotient)) (getDFast (0,1)) +lemma polynomial_median : PolynomialTime medianRealizer := + polynomial_composition (polynomial_pair polynomial_sorted + (polynomial_composition (polynomial_pair polynomial_listLength (polynomial_constant _)) polynomial_quotient)) (polynomial_getDFast _) + +lemma sorted_repr (xs : List ℚ) (hs : ∀ q∈xs,0≤q) : + sorted (xs.map TreeFraction.repr)=(xs.mergeSort (·≤·)).map TreeFraction.repr := by + rw [List.mergeSort_eq_insertionSort (·≤·)] + symm + apply List.map_insertionSort (·≤·) relation TreeFraction.repr xs + intro a ha b hb + exact (relation_repr a b (hs a ha) (hs b hb)).symm + +lemma median_repr {k : ℕ} (x : Fin (2*k+1)→ℚ) (hx : ∀ i,0≤x i) : + median (List.ofFn (fun i=>TreeFraction.repr (x i)))=TreeFraction.repr (Amplification.median x) := by + rw [show List.ofFn (fun i=>TreeFraction.repr (x i))=(List.ofFn x).map TreeFraction.repr by rw [List.map_ofFn]; rfl] + unfold median + rw [sorted_repr _ (by intro q hq; obtain ⟨i,rfl⟩:=List.mem_ofFn.mp hq; exact hx i)] + rw [List.length_map,List.length_ofFn,show (2*k+1)/2=k by omega] + change (List.map TreeFraction.repr ((List.ofFn x).mergeSort (·≤·))).getD k (TreeFraction.repr 0)=_ + rw [List.getD_map _ 0 TreeFraction.repr] + rw [List.getD_eq_getElem _ _ (by simp; omega)] + rfl +end MatchingFPRAS.OnlineMedian + +end OAI diff --git a/lean/OAI/Combinatorics/MatchingCount/Algorithm/OnlinePowerSearch.lean b/lean/OAI/Combinatorics/MatchingCount/Algorithm/OnlinePowerSearch.lean new file mode 100644 index 0000000000000000000000000000000000000000..c7be53cd1f995ed2c44f9b57649f901c1a022863 --- /dev/null +++ b/lean/OAI/Combinatorics/MatchingCount/Algorithm/OnlinePowerSearch.lean @@ -0,0 +1,113 @@ +import Mathlib +import OAI.Combinatorics.MatchingCount.Graphs.LabelOrder +import OAI.Combinatorics.MatchingCount.Machines.TreeLabelTable +import OAI.Combinatorics.MatchingCount.Machines.TreeSlotWeight + +namespace OAI + +namespace MatchingFPRAS.OnlineSchedule +open TreeTyped TreeFraction Polynomial + +abbrev PowerSearchInput := (Fraction×Fraction)×List Bool + +def powerCandidate (x : PowerSearchInput×ℕ) : Bool := + !(TreeFraction.less (fuelPower (x.1.1.1,x.1.2.take x.2),x.1.1.2)) +def powerCandidateRealizer : Realizer powerCandidate := + (composition (composition (pair + (composition (pair first.fst.fst (composition (pair first.snd second) takeFast)) fuelPowerRealizer) + first.fst.snd) lessRealizer) boolNot).congr (fun _=>rfl) +lemma polynomial_powerCandidate : PolynomialTime powerCandidateRealizer := by + unfold powerCandidateRealizer; apply polynomial_congr + exact polynomial_composition (polynomial_composition + (polynomial_pair + (polynomial_composition + (polynomial_pair (polynomial_fst (polynomial_fst polynomial_first)) + (polynomial_composition (polynomial_pair (polynomial_snd polynomial_first) polynomial_second) + polynomial_takeFast)) polynomial_fuelPower) + (polynomial_snd (polynomial_fst polynomial_first))) TreeFraction.polynomial_less) polynomial_boolNot + +def findPower (x : PowerSearchInput) : ℕ := + listMin ((List.range (x.2.length+1)).filter (fun i=>powerCandidate (x,i)),x.2.length) +def findPowerRealizer : Realizer findPower := by + let B : Realizer (fun x : PowerSearchInput=>x.2.length) := composition second listLength + let R := composition (composition B successor) range + let F := composition (pair identity R) (filterWith powerCandidateRealizer) + exact (composition (pair F B) listMinRealizer).congr (fun _=>rfl) +lemma polynomial_findPower : PolynomialTime findPowerRealizer := by + unfold findPowerRealizer + dsimp only + apply polynomial_congr + apply polynomial_composition _ polynomial_listMin + apply polynomial_pair _ (polynomial_composition polynomial_second polynomial_listLength) + apply polynomial_composition _ (polynomial_filterWithList polynomial_powerCandidate) + apply polynomial_pair polynomial_identity + apply polynomial_boundedRange + (polynomial_composition (polynomial_composition polynomial_second polynomial_listLength) polynomial_successor) + (X+1) + intro x + have h:=list_length_le_weight x.2 + change x.2.length+1≤(X+1).eval (weight x) + simp only [Polynomial.eval_add,Polynomial.eval_X,Polynomial.eval_one] + rw [weight_prod] + omega +lemma powerCandidate_repr (a b : ℚ) (ha : 0≤a) (hb : 0≤b) (fuel : List Bool) (i : ℕ) + (hi : i≤fuel.length) : + powerCandidate (((repr a,repr b),fuel),i)=decide (b≤a^i) := by + unfold powerCandidate + rw [fuelPower_repr a ha,List.length_take,min_eq_left hi] + rw [less_val _ _ (a^i).pos b.pos, + val_repr (by positivity),val_repr hb] + apply Bool.eq_iff_iff.mpr + simp +lemma findPower_le_fuel (x : PowerSearchInput) : findPower x≤x.2.length := + listMin_le_default _ _ +lemma findPower_le (a b : ℚ) (ha : 0≤a) (hb : 0≤b) (fuel : List Bool) (i : ℕ) + (hi : i≤fuel.length) (hr : b ≤ a ^ i) : findPower ((repr a, repr b), fuel) ≤ i := by + apply listMin_le + simp only [List.mem_filter,List.mem_range,powerCandidate_repr a b ha hb fuel i hi, + decide_eq_true_eq] + exact ⟨by omega,hr⟩ +lemma le_findPower (a b : ℚ) (ha : 0≤a) (hb : 0≤b) (fuel : List Bool) (i : ℕ) + (hi : i≤fuel.length) + (hmin : ∀ j,j≤fuel.length→b≤a^j→i≤j) : i≤findPower ((repr a,repr b),fuel) := by + apply le_listMin hi + intro j hj + simp only [List.mem_filter,List.mem_range] at hj + have hj' : j≤fuel.length := by omega + rw [powerCandidate_repr a b ha hb fuel j hj',decide_eq_true_eq] at hj + exact hmin j hj' hj.2 +lemma findPower_eq (a b : ℚ) (ha : 0≤a) (hb : 0≤b) (fuel : List Bool) (T : ℕ) + (hT : T≤fuel.length) (hr : b≤a^T) (hmin : ∀ j,b≤a^j→T≤j) : + findPower ((repr a,repr b),fuel)=T := + Nat.le_antisymm (findPower_le a b ha hb fuel T hT hr) + (le_findPower a b ha hb fuel T hT (fun j _ hj=>hmin j hj)) + +lemma endpoint_le_bound (N D K : ℕ) (hN : 0(f a).length) := composition F listLength +lemma polynomial_lengthAfter {A B : Type} [Codec A] [Codec B] {f : A→List B} {F : Realizer f} + (hF : PolynomialTime F) : PolynomialTime (lengthAfter F) := + polynomial_composition hF polynomial_listLength + +def rangeAfter {A : Type} [Codec A] {f : A→ℕ} (F : Realizer f) : + Realizer (fun a=>List.range (f a)) := composition F range + +def listIndices {A : Type} [Codec A] : Realizer (fun xs : List A=>List.range xs.length) := + composition listLength range +lemma polynomial_listIndices {A : Type} [Codec A] : PolynomialTime (listIndices (A:=A)) := + polynomial_boundedRange polynomial_listLength Polynomial.X (fun xs=>by simpa using list_length_le_weight xs) + +def indicesAfter {A B : Type} [Codec A] [Codec B] {f : A→List B} (F : Realizer f) : + Realizer (fun a=>List.range (f a).length) := composition F listIndices +lemma polynomial_indicesAfter {A B : Type} [Codec A] [Codec B] {f : A→List B} {F : Realizer f} + (hF : PolynomialTime F) : PolynomialTime (indicesAfter F) := + polynomial_composition hF polynomial_listIndices + +abbrev PrecisionData := ScanInput×(ℕ×ℕ) + +def scanError (x : PrecisionData) : ℕ := + 2*(1+(x.1.1.2.2*(ladderQ x.1.1.1.1 x.1.1.1.2)^2+ladderQ x.1.1.1.1 x.1.1.1.2))+ + 4*(8*x.2.1^2+4*x.2.1+3)+2*x.1.1.1.1^2*x.2.2 + +def scanErrorRealizer : Realizer scanError := + ((((constant 2).mulNat ((constant 1).addNat + ((first.fst.snd.snd.mulNat (composition (composition first.fst.fst qRealizer) (fixedPower 2))).addNat + (composition first.fst.fst qRealizer)))).addNat + ((constant 4).mulNat ((((constant 8).mulNat (composition second.fst (fixedPower 2))).addNat + ((constant 4).mulNat second.fst)).addNat (constant 3)))).addNat + (((constant 2).mulNat (composition first.fst.fst.fst (fixedPower 2))).mulNat second.snd)).congr (fun _=>rfl) +lemma polynomial_scanError : PolynomialTime scanErrorRealizer := by + unfold scanErrorRealizer + apply polynomial_congr + dsimp only [Realizer.fst, Realizer.snd] + have := polynomial_q + have := polynomial_fixedPower 2 + simp only [Realizer.addNat,Realizer.mulNat] + tree_cost + +def precisionPlan (x : PrecisionData) : ((ℕ×ℕ)×ℕ)×ℕ := + (((Nat.clog 2 (discreteLadderSteps x.1.1.1.1 x.1.1.1.2 x.1.1.2.1 x.1.1.2.2 x.1.2 *scanError x*x.1.2), + x.1.1.1.1),discreteLadderSteps x.1.1.1.1 x.1.1.1.2 x.1.1.2.1 x.1.1.2.2 x.1.2), + Nat.clog 2 (6*x.2.1*x.1.2)) +def precisionPlanRealizer : Realizer precisionPlan := + (pair (pair (pair + (composition (((composition first scansRealizer).mulNat scanErrorRealizer).mulNat first.snd) clogTwo) + first.fst.fst.fst) (composition first scansRealizer)) + (composition (((constant 6).mulNat second.fst).mulNat first.snd) clogTwo)).congr (fun _=>rfl) +lemma polynomial_precisionPlan : PolynomialTime precisionPlanRealizer := by + unfold precisionPlanRealizer + apply polynomial_congr + dsimp only [Realizer.fst, Realizer.snd] + have := polynomial_scanError + have := polynomial_scans + have := polynomial_clogTwo + simp only [Realizer.mulNat] + tree_cost + +abbrev RequestInput := SparseStageData×ℕ + +def sourcePrecision (x : RequestInput) : PrecisionData := + let b:=sparseBagInput x.1 + (((((sourceVertices b).length,x.1.1.2.1.2),(x.1.1.2.1.1.2.length/2,x.1.1.2.2.1.length)), + 1000*(x.1.1.2.1.1.2.length/2)*x.2), + ((sourceTables b).1.length,(sourceParents b).length)) +def requestBagRealizer : Realizer (fun x : RequestInput=>sparseBagInput x.1) := + composition first sparseBagInputRealizer +def requestKRealizer : Realizer (fun x : RequestInput=>x.1.1.2.1.1.2.length/2) := + composition (pair (composition first.fst.snd.fst.fst.snd listLength) (constant 2)) quotient +def requestNDRealizer : Realizer (fun x : RequestInput=>((sourceVertices (sparseBagInput x.1)).length,x.1.1.2.1.2)) := + pair (composition (composition (g:=sourceVertices) requestBagRealizer sourceVerticesRealizer) listLength) first.fst.snd.fst.snd +def requestKTRealizer : Realizer (fun x : RequestInput=>(x.1.1.2.1.1.2.length/2,x.1.1.2.2.1.length)) := + pair requestKRealizer (composition first.fst.snd.snd.fst listLength) +def requestMRealizer : Realizer (fun x : RequestInput=>1000*(x.1.1.2.1.1.2.length/2)*x.2) := + ((constant 1000).mulNat requestKRealizer).mulNat second +def requestScanRealizer : Realizer (fun x : RequestInput=> + ((((sourceVertices (sparseBagInput x.1)).length,x.1.1.2.1.2), + (x.1.1.2.1.1.2.length/2,x.1.1.2.2.1.length)),1000*(x.1.1.2.1.1.2.length/2)*x.2)) := + pair (pair requestNDRealizer requestKTRealizer) requestMRealizer +def requestTablesRealizer : Realizer (fun x : RequestInput=>sourceTables (sparseBagInput x.1)) := + composition (f:=fun x : RequestInput=>sparseBagInput x.1) (g:=sourceTables) + requestBagRealizer sourceTablesRealizer +def requestCatalogRealizer : Realizer (fun x : RequestInput=>(sourceTables (sparseBagInput x.1)).1) := + Realizer.fst (f:=fun x : RequestInput=>sourceTables (sparseBagInput x.1)) requestTablesRealizer +def requestEdgesRealizer : Realizer (fun x : RequestInput=>(sourceTables (sparseBagInput x.1)).1.length) := + lengthAfter (f:=fun x : RequestInput=>(sourceTables (sparseBagInput x.1)).1) requestCatalogRealizer +def requestLabelsRealizer : Realizer (fun x : RequestInput=>(sourceParents (sparseBagInput x.1)).length) := + composition (composition (g:=sourceParents) requestBagRealizer sourceParentsRealizer) listLength +def sourcePrecisionRealizer : Realizer sourcePrecision := + pair requestScanRealizer (pair requestEdgesRealizer requestLabelsRealizer) +lemma polynomial_requestBag : PolynomialTime requestBagRealizer := + polynomial_composition polynomial_first polynomial_sparseBagInput +lemma polynomial_requestK : PolynomialTime requestKRealizer := by + unfold requestKRealizer + dsimp only [Realizer.fst, Realizer.snd] + have := polynomial_quotient + tree_cost +lemma polynomial_requestND : PolynomialTime requestNDRealizer := by + unfold requestNDRealizer + dsimp only [Realizer.fst, Realizer.snd] + have := polynomial_requestBag + have := polynomial_sourceVertices + tree_cost +lemma polynomial_requestKT : PolynomialTime requestKTRealizer := by + unfold requestKTRealizer + dsimp only [Realizer.fst, Realizer.snd] + have := polynomial_requestK + tree_cost +lemma polynomial_requestM : PolynomialTime requestMRealizer := + polynomial_mulNat (polynomial_mulNat (polynomial_constant _) polynomial_requestK) polynomial_second +lemma polynomial_requestScan : PolynomialTime requestScanRealizer := + TreeTyped.polynomial_pair (TreeTyped.polynomial_pair polynomial_requestND polynomial_requestKT) polynomial_requestM +lemma polynomial_requestTables : PolynomialTime requestTablesRealizer := + polynomial_composition polynomial_requestBag polynomial_sourceTables +lemma polynomial_requestCatalog : PolynomialTime requestCatalogRealizer := + polynomial_fst polynomial_requestTables +lemma polynomial_requestEdges : PolynomialTime requestEdgesRealizer := + polynomial_lengthAfter polynomial_requestCatalog +lemma polynomial_requestLabels : PolynomialTime requestLabelsRealizer := + polynomial_composition (polynomial_composition polynomial_requestBag + polynomial_sourceParents) polynomial_listLength +lemma polynomial_sourcePrecision : PolynomialTime sourcePrecisionRealizer := + TreeTyped.polynomial_pair polynomial_requestScan (TreeTyped.polynomial_pair polynomial_requestEdges polynomial_requestLabels) + +def sourceRequest (x : RequestInput) : OnlineSample.Request := + let plan:=precisionPlan (sourcePrecision x) + (plan.1,(plan.2,List.range ((sourceTables (sparseBagInput x.1)).1.length))) +def requestPlanRealizer : Realizer (fun x : RequestInput=>precisionPlan (sourcePrecision x)) := + composition (g:=precisionPlan) sourcePrecisionRealizer precisionPlanRealizer +def requestIndicesRealizer : Realizer (fun x : RequestInput=>List.range (sourceTables (sparseBagInput x.1)).1.length) := + indicesAfter (f:=fun x : RequestInput=>(sourceTables (sparseBagInput x.1)).1) requestCatalogRealizer +def sourceRequestRealizer : Realizer sourceRequest := + pair requestPlanRealizer.fst (pair requestPlanRealizer.snd requestIndicesRealizer) +lemma polynomial_requestPlan : PolynomialTime requestPlanRealizer := + polynomial_composition polynomial_sourcePrecision polynomial_precisionPlan +lemma polynomial_requestIndices : PolynomialTime requestIndicesRealizer := + polynomial_indicesAfter polynomial_requestCatalog +lemma polynomial_sourceRequest : PolynomialTime sourceRequestRealizer := + TreeTyped.polynomial_pair (polynomial_fst polynomial_requestPlan) + (TreeTyped.polynomial_pair (polynomial_snd polynomial_requestPlan) polynomial_requestIndices) + +lemma sparseBagInput_source {G : GraphInput} {j : ℕ} (s : FiniteTrial.ScaleState G j) + (K D : ℕ) (ft fq : List Bool) : + sparseBagInput (OnlineStage.data s K D ft fq)= + (((matrixRep s.activity,List.replicate (2*K+2) false),List.range G.n),List.replicate (2*K) false) := by + have h:=sparseUpdateData_source s K D ft fq + exact congrArg (fun x=>x.1.1.1.1) h + +lemma sourcePrecision_source {G : GraphInput} [Nontrivial (Fin G.n)] (hn : 2≤G.n) + {j : ℕ} (s : FiniteTrial.ScaleState G j) (K D S : ℕ) (ft fq : List Bool) : + sourcePrecision (OnlineStage.data s K D ft fq,S)= + (((((Fintype.card (SourceVertex (Fin G.n) K)),D),(K,ft.length)),1000*K*S), + (Fintype.card (BagEdge (RationalSource.bags s.activity K)),Fintype.card (RationalSource.Label s.activity K))) := by + unfold sourcePrecision + rw [sparseBagInput_source] + dsimp only [OnlineStage.data] + rw [sourceVertices_length,sourceTables_catalog hn s.activity + (fun i j=>(s.activity_pos i j).le) K,sourceParents_source hn s.activity + (fun i j=>(s.activity_pos i j).le) K] + simp only [List.length_replicate,Nat.mul_div_cancel_left _ (by decide : 0<2),sourceCatalog,List.length_ofFn, + ExecutableDP.parentRep_length] + +end MatchingFPRAS.OnlineSchedule + +end OAI diff --git a/lean/OAI/Combinatorics/MatchingCount/Algorithm/OnlineRequestLaw.lean b/lean/OAI/Combinatorics/MatchingCount/Algorithm/OnlineRequestLaw.lean new file mode 100644 index 0000000000000000000000000000000000000000..ebd489870e647e97a9f531f1df10b0d09ff6f022 --- /dev/null +++ b/lean/OAI/Combinatorics/MatchingCount/Algorithm/OnlineRequestLaw.lean @@ -0,0 +1,47 @@ +import Mathlib +import OAI.Combinatorics.MatchingCount.Algorithm.OnlineRequest +import OAI.Combinatorics.MatchingCount.Algorithm.OnlineTransitionLaw + +namespace OAI + +namespace MatchingFPRAS.OnlineSchedule +open PhysicalStream TreeTyped TreeFraction ExecutableSource ExecutableScaling Transport +open UnitRefresh Enlargement TreeTyped.Numbered OnlineStage ExecutableRefresh + +attribute [local instance] NumberedHierarchy.labelOrder +attribute [local instance] Transport.sym2Order Transport.bagEdgeOrder Transport.bagEdgeFintype +attribute [local instance] UnitRefresh.Computable.allowedDec Transport.prodOrder Transport.sumOrder + +lemma bitPrecision_inverseNat (R m : ℕ) : bitPrecision R (1/(m:ℚ))=Nat.clog 2 (R*m) := by + simp [bitPrecision] + +variable {G : GraphInput} [Nontrivial (Fin G.n)] +lemma sourceRequest_source {j : ℕ} (p : Trial.Parameters G) (s : FiniteTrial.ScaleState G j) : + sourceRequest (fixedData p s,p.S)=fixedRequest p s := by + unfold sourceRequest + rw [show sourcePrecision (fixedData p s,p.S)= + (((((Fintype.card (SourceVertex (Fin G.n) p.K)),FiniteTrial.sourceD (G:=G) p.K), + (p.K,tierCount (n:=G.n) p.K (FiniteTrial.sourceD (G:=G) p.K))),denominator p), + (edgeCount s.activity p.K,labelCount s.activity p.K)) from by + simpa only [fixedData,denominator,edgeCount,labelCount,List.length_replicate] using + sourcePrecision_source p.hn s p.K (FiniteTrial.sourceD (G:=G) p.K) p.S + (List.replicate (tierCount (n:=G.n) p.K (FiniteTrial.sourceD (G:=G) p.K)) false) + (List.replicate (copies (n:=G.n) p.K (FiniteTrial.sourceD (G:=G) p.K)) false)] + have hc : (sourceTables (sparseBagInput (fixedData p s))).1.length=edgeCount s.activity p.K := by + unfold fixedData + rw [sparseBagInput_source,sourceTables_catalog p.hn s.activity + (fun i j=>(s.activity_pos i j).le) p.K] + simp only [sourceCatalog,List.length_ofFn] + simp only [hc,precisionPlan,fixedRequest,choiceWidth,markWidth,bitPrecision_inverseNat] + apply Prod.ext + · rfl + · apply Prod.ext + · rfl + · simp only [index_orderedEnum] + apply List.ext_getElem + · simp + · intro _ _ _ + simp +end MatchingFPRAS.OnlineSchedule + +end OAI diff --git a/lean/OAI/Combinatorics/MatchingCount/Algorithm/OnlineSampleCount.lean b/lean/OAI/Combinatorics/MatchingCount/Algorithm/OnlineSampleCount.lean new file mode 100644 index 0000000000000000000000000000000000000000..ee056347f33ae462379c0d4c306b733fda8da7ce --- /dev/null +++ b/lean/OAI/Combinatorics/MatchingCount/Algorithm/OnlineSampleCount.lean @@ -0,0 +1,113 @@ +import Mathlib +import OAI.Combinatorics.MatchingCount.Algorithm.RationalCounts +import OAI.Combinatorics.MatchingCount.Algorithm.SortedList +import OAI.Combinatorics.MatchingCount.Machines.TreeSlotWeight +import OAI.Combinatorics.MatchingCount.Arithmetic.OnlineFractionParam + +namespace OAI + +namespace MatchingFPRAS.OnlineSchedule +open TreeTyped TreeFraction Polynomial + +abbrev SigmaInput := (ℕ×ℕ)×Fraction + +def sigma (x : SigmaInput) : Fraction := + TreeFraction.minimum + (TreeFraction.div ((1,100000),(100*x.1.1,1)),TreeFraction.div (x.2,(1000*x.1.2,1))) +def sigmaRealizer : Realizer sigma := + (composition (pair + (composition (pair (constant (1,100000)) (pair ((constant 100).mulNat first.fst) (constant 1))) divRealizer) + (composition (pair second (pair ((constant 1000).mulNat first.snd) (constant 1))) divRealizer)) minimumRealizer).congr (fun _=>rfl) +lemma polynomial_sigma : PolynomialTime sigmaRealizer := by + unfold sigmaRealizer Realizer.fst Realizer.snd; apply polynomial_congr + have := polynomial_div + have := TreeFraction.polynomial_minimum + simp only [Realizer.mulNat] + tree_cost +lemma sigma_repr (D K : ℕ) (e : ℚ) (he : 0≤e) : + sigma ((D,K),TreeFraction.repr e)=TreeFraction.repr (Counting.sigma D K e) := by + unfold sigma + rw [←repr_nat (100*D),←repr_nat (1000*K), + show ((1,100000) : Fraction)=TreeFraction.repr ((1:ℚ)/100000) from by norm_num [TreeFraction.repr], + div_repr (by positivity) (by positivity), div_repr he (by positivity), + minimum_repr (by positivity) (by positivity)] + congr 1 + simp only [Counting.sigma,Counting.alpha,Nat.cast_mul,Nat.cast_ofNat] + +abbrev SampleCountInput := ℕ×SigmaInput + +def invSigma (x : SampleCountInput) : Fraction := inverse (sigma x.2) +def reciprocalSigma : Realizer invSigma := + composition (f:=sigma ∘ Prod.snd) (g:=inverse) + (composition (f:=Prod.snd) (g:=sigma) second sigmaRealizer) inverseRealizer +lemma polynomial_reciprocalSigma : PolynomialTime reciprocalSigma := by + unfold reciprocalSigma + exact polynomial_composition (polynomial_composition polynomial_second polynomial_sigma) polynomial_inverse + +def fracProduct {A : Type} [Codec A] {f g : A→Fraction} (F : Realizer f) (G : Realizer g) : + Realizer (fun x=>TreeFraction.mul (f x,g x)) := composition (f:=fun x=>(f x,g x)) (g:=TreeFraction.mul) (pair F G) mulRealizer +lemma polynomial_fracProduct {A : Type} [Codec A] {f g : A→Fraction} {F : Realizer f} {G : Realizer g} + (hF : PolynomialTime F) (hG : PolynomialTime G) : PolynomialTime (fracProduct F G) := + polynomial_composition (polynomial_pair hF hG) polynomial_mul + +def sampleFactorFn (x : SampleCountInput) : Fraction := TreeFraction.mul ((10,1),TreeFraction.mul (invSigma x,invSigma x)) +def sampleFactor : Realizer sampleFactorFn := fracProduct (constant (10,1)) (fracProduct reciprocalSigma reciprocalSigma) +lemma polynomial_sampleFactor : PolynomialTime sampleFactor := + polynomial_fracProduct (polynomial_constant _) (polynomial_fracProduct polynomial_reciprocalSigma polynomial_reciprocalSigma) + +def sampleSumFn (x : SampleCountInput) : Fraction := (x.1+x.2.1.2+1,1) +def sampleSum : Realizer sampleSumFn := + pair ((first.addNat second.fst.snd).addNat (constant 1)) (constant 1) +lemma polynomial_sampleSum : PolynomialTime sampleSum := by + exact polynomial_pair (polynomial_addNat (polynomial_addNat polynomial_first + (polynomial_snd (polynomial_fst polynomial_second))) (polynomial_constant 1)) (polynomial_constant 1) + +def sampleProduct (x : SampleCountInput) : Fraction := TreeFraction.mul (sampleFactorFn x,sampleSumFn x) +def sampleProductRealizer : Realizer sampleProduct := fracProduct sampleFactor sampleSum +lemma polynomial_sampleProduct : PolynomialTime sampleProductRealizer := + polynomial_fracProduct polynomial_sampleFactor polynomial_sampleSum + +def sampleCount (x : SampleCountInput) : ℕ := natCeil (sampleProduct x) +def sampleCountRealizer : Realizer sampleCount := + composition (f:=sampleProduct) (g:=natCeil) sampleProductRealizer natCeilRealizer +lemma polynomial_sampleCount : PolynomialTime sampleCountRealizer := + polynomial_composition polynomial_sampleProduct polynomial_natCeil +lemma sampleCount_repr (n D K : ℕ) (e : ℚ) (he : 0≤e) : + sampleCount (n,((D,K),TreeFraction.repr e))= + ⌈10*(Counting.sigma D K e)⁻¹^2*((n:ℚ)+K+1)⌉₊ := by + have hs := Counting.sigma_nonneg D K e he + unfold sampleCount sampleProduct sampleFactorFn sampleSumFn invSigma + rw [sigma_repr D K e he,inverse_repr _ (Counting.sigma_nonneg D K e he), + show ((10,1) : Fraction)=TreeFraction.repr (10:ℚ) from rfl, + ←repr_nat (n+K+1),mul_repr (by positivity) (by positivity), + mul_repr (by positivity) (by positivity),mul_repr (by positivity) (by positivity), + natCeil_repr _ (by positivity)] + congr 1 + simp only [Nat.cast_add,Nat.cast_one,pow_two] + +variable {G : GraphInput} [Nontrivial (Fin G.n)] +omit [Nontrivial (Fin G.n)] in +lemma sampleCount_source (p : Trial.Parameters G) : + sampleCount (G.n,((FiniteTrial.sourceD (G:=G) p.K,p.K),TreeFraction.repr p.epsilon))=p.S := by + rw [sampleCount_repr _ _ _ _ p.epsilon_pos.le] + exact FiniteTrial.sampleCount_eq p + +def repetitions (x : Fraction) : ℕ := 10*(Nat.clog 2 (natCeil (inverse x))+1)+1 +def repetitionsRealizer : Realizer repetitions := + (((constant 10).mulNat ((composition (composition inverseRealizer natCeilRealizer) clogTwo).addNat (constant 1))).addNat (constant 1)).congr (fun _=>rfl) +lemma polynomial_repetitions : PolynomialTime repetitionsRealizer := by + unfold repetitionsRealizer;apply polynomial_congr + have := polynomial_clogTwo + have := polynomial_natCeil + have := polynomial_inverse + simp only [Realizer.addNat,Realizer.mulNat] + tree_cost +lemma repetitions_repr (d : ℚ) (hd : 0≤d) : + repetitions (TreeFraction.repr d)=2*Amplification.halfRepetitions d+1 := by + unfold repetitions + rw [inverse_repr d hd,natCeil_repr _ (by positivity)] + unfold Amplification.halfRepetitions + omega +end MatchingFPRAS.OnlineSchedule + +end OAI diff --git a/lean/OAI/Combinatorics/MatchingCount/Algorithm/OnlineScheduleNat.lean b/lean/OAI/Combinatorics/MatchingCount/Algorithm/OnlineScheduleNat.lean new file mode 100644 index 0000000000000000000000000000000000000000..aa101273c213f13da45f8b8ab2f5e320a2ea16f1 --- /dev/null +++ b/lean/OAI/Combinatorics/MatchingCount/Algorithm/OnlineScheduleNat.lean @@ -0,0 +1,110 @@ +import Mathlib +import OAI.Combinatorics.MatchingCount.Sampling.DiscreteLadderSteps +import OAI.Combinatorics.MatchingCount.Machines.TreeSum + +namespace OAI + +namespace MatchingFPRAS.TreeTyped +variable {A : Type} [Codec A] +def Realizer.addNat {f g : A→ℕ} (F : Realizer f) (G : Realizer g) : + Realizer (fun a=>f a+g a) := composition (pair F G) add +def Realizer.mulNat {f g : A→ℕ} (F : Realizer f) (G : Realizer g) : + Realizer (fun a=>f a*g a) := composition (pair F G) multiply +lemma polynomial_addNat {f g : A→ℕ} {F : Realizer f} {G : Realizer g} + (hF : PolynomialTime F) (hG : PolynomialTime G) : PolynomialTime (F.addNat G) := + polynomial_composition (polynomial_pair hF hG) polynomial_add +lemma polynomial_mulNat {f g : A→ℕ} {F : Realizer f} {G : Realizer g} + (hF : PolynomialTime F) (hG : PolynomialTime G) : PolynomialTime (F.mulNat G) := + polynomial_composition (polynomial_pair hF hG) polynomial_multiply + +def fixedPower : (k : ℕ)→Realizer (fun n : ℕ=>n^k) + | 0 => (constant 1).congr (by intro n; simp) + | k+1 => ((fixedPower k).mulNat identity).congr (by intro n; simp [pow_succ]) +lemma polynomial_fixedPower (k : ℕ) : PolynomialTime (fixedPower k) := by + induction k with + | zero => exact polynomial_congr _ (polynomial_constant 1) + | succ k ih => exact polynomial_congr _ (polynomial_mulNat ih polynomial_identity) +lemma clog_two_size_pred (n : ℕ) : Nat.clog 2 n=Nat.size (n-1) := by + apply Nat.le_antisymm + · apply Nat.clog_le_of_le_pow + have hp:=Nat.lt_size_self (n-1) + omega + · apply Nat.size_le.mpr + have hp:=Nat.le_pow_clog (by decide : 1<2) n + have hpos:=Nat.two_pow_pos (Nat.clog 2 n) + omega +def clogTwo : Realizer (Nat.clog 2) := + (composition predecessor bitSize).congr (fun n=>(clog_two_size_pred n).symm) +lemma polynomial_clogTwo : PolynomialTime clogTwo := + polynomial_congr _ (polynomial_composition polynomial_predecessor polynomial_bitSize) +end MatchingFPRAS.TreeTyped + +namespace MatchingFPRAS.OnlineSchedule +open TreeTyped Transport + +def lRealizer : Realizer (fun x : ℕ×ℕ=>ladderL x.1 x.2) := + (composition (((constant (10^4)).mulNat first).mulNat second) (fixedPower 100)).congr (fun _=>rfl) +lemma polynomial_l : PolynomialTime lRealizer := by + unfold lRealizer + apply polynomial_congr + exact polynomial_composition (polynomial_mulNat (polynomial_mulNat (polynomial_constant _) polynomial_first) + polynomial_second) (polynomial_fixedPower _) +def qRealizer : Realizer (fun x : ℕ×ℕ=>ladderQ x.1 x.2) := + ((constant 32).mulNat lRealizer).congr (fun _=>rfl) +lemma polynomial_q : PolynomialTime qRealizer := + polynomial_congr _ (polynomial_mulNat (polynomial_constant _) polynomial_l) + +abbrev ScanInput := ((ℕ×ℕ)×(ℕ×ℕ))×ℕ + +def mRealizer : Realizer (fun x : (ℕ×ℕ)×ℕ=>ladderM x.1.1 x.1.2 x.2) := + ((second.mulNat (composition (composition first qRealizer) (fixedPower 2))).addNat + (composition first qRealizer)).congr (fun _=>rfl) +lemma polynomial_m : PolynomialTime mRealizer := by + unfold mRealizer + apply polynomial_congr + exact polynomial_addNat (polynomial_mulNat polynomial_second + (polynomial_composition (polynomial_composition polynomial_first polynomial_q) (polynomial_fixedPower 2))) + (polynomial_composition polynomial_first polynomial_q) +def lambdaRealizer : Realizer (fun x : (ℕ×ℕ)×(ℕ×ℕ)=>ladderLambda x.1.1 x.1.2 x.2.1 x.2.2) := + (((((constant 10).mulNat first.fst).mulNat (composition first qRealizer)).mulNat + (second.snd.addNat (constant 1))).mulNat + ((second.fst.addNat (composition ((first.fst.mulNat first.snd).addNat (constant 2)) clogTwo)).addNat (constant 1))).congr + (fun _=>rfl) +lemma polynomial_lambda : PolynomialTime lambdaRealizer := by + unfold lambdaRealizer + apply polynomial_congr + exact polynomial_mulNat + (polynomial_mulNat + (polynomial_mulNat (polynomial_mulNat (polynomial_constant _) (polynomial_fst polynomial_first)) + (polynomial_composition polynomial_first polynomial_q)) + (polynomial_addNat (polynomial_snd polynomial_second) (polynomial_constant _))) + (polynomial_addNat + (polynomial_addNat (polynomial_fst polynomial_second) + (polynomial_composition + (polynomial_addNat (polynomial_mulNat (polynomial_fst polynomial_first) + (polynomial_snd polynomial_first)) (polynomial_constant _)) polynomial_clogTwo)) + (polynomial_constant _)) + +def scansRealizer : Realizer (fun x : ScanInput=>discreteLadderSteps x.1.1.1 x.1.1.2 x.1.2.1 x.1.2.2 x.2) := + ((((constant 20).mulNat (composition first.fst lRealizer)).mulNat + (composition (pair first.fst first.snd.snd) mRealizer)).mulNat + (((composition first lambdaRealizer).addNat (composition second clogTwo)).addNat (constant 1))).congr + (fun _=>rfl) +lemma polynomial_scans : PolynomialTime scansRealizer := by + unfold scansRealizer + apply polynomial_congr + exact polynomial_mulNat + (polynomial_mulNat + (polynomial_mulNat (polynomial_constant _) + (polynomial_composition (polynomial_fst polynomial_first) polynomial_l)) + (polynomial_composition + (polynomial_pair (polynomial_fst polynomial_first) (polynomial_snd (polynomial_snd polynomial_first))) + polynomial_m)) + (polynomial_addNat + (polynomial_addNat (polynomial_composition polynomial_first polynomial_lambda) + (polynomial_composition polynomial_second polynomial_clogTwo)) + (polynomial_constant _)) + +end MatchingFPRAS.OnlineSchedule + +end OAI diff --git a/lean/OAI/Combinatorics/MatchingCount/Algorithm/OnlineStage.lean b/lean/OAI/Combinatorics/MatchingCount/Algorithm/OnlineStage.lean new file mode 100644 index 0000000000000000000000000000000000000000..8fa735e6c9bd00377170a461fc348bae60352161 --- /dev/null +++ b/lean/OAI/Combinatorics/MatchingCount/Algorithm/OnlineStage.lean @@ -0,0 +1,62 @@ +import Mathlib +import OAI.Combinatorics.MatchingCount.Tapes.TreeSparseStage +import OAI.Combinatorics.MatchingCount.Probability.OnlineSampleLaw + +namespace OAI + +namespace MatchingFPRAS.OnlineStage +open PhysicalStream TreeTyped ExecutableSource NumericLadder TreeFraction ExecutableScaling +open UnitRefresh Transport Enlargement TreeTyped.Numbered ExecutableAdaptive + +attribute [local instance] NumberedHierarchy.labelOrder +attribute [local instance] Transport.sym2Order Transport.bagEdgeOrder Transport.bagEdgeFintype +attribute [local instance] UnitRefresh.Computable.allowedDec Transport.prodOrder Transport.sumOrder + +abbrev Input := SparseStageData×(ℕ×OnlineSample.Request) +def execute (x : Input) : Experiment (Fraction×Vector) := + (OnlineSample.many x.2).map (fun bs=>sparseStage (x.1,bs)) +noncomputable def executeRealizer : OnlineTree.Realizer execute := + (OnlineTree.composition (OnlineTree.pair (OnlineTree.deterministic TreeTyped.first) + (OnlineTree.composition (OnlineTree.deterministic TreeTyped.second) OnlineSample.manyRealizer)) + (OnlineTree.deterministic sparseStageRealizer)).congr (by + intro x h; simp only [execute,Experiment.mean_bind,Experiment.mean_map,Experiment.mean]) + +variable {G : GraphInput} [Nontrivial (Fin G.n)] +noncomputable def data {j : ℕ} (s : FiniteTrial.ScaleState G j) (K D : ℕ) (ft fq : List Bool) : SparseStageData := + (((graphRep G,List.replicate j false), + (((List.replicate (2*K+2) false,List.replicate (2*K) false),D),(ft,fq))),vectorRep s.scale) + +lemma source_mean (hn : 2≤G.n) (he : Even G.n) {j : ℕ} (s : FiniteTrial.ScaleState G j) + (K : ℕ) (hD : 0index (orderedEnum E i) + let req : OnlineSample.Request := + (((k,Fintype.card (SourceVertex (Fin G.n) K)),r),(km,List.ofFn keys)) + (execute (data s K (FiniteTrial.sourceD (G:=G) K) ft fq,(S,req))).mean h= + qaverage (fun bs : Fin S→OnlineSample.Random (Fintype.card (SourceVertex (Fin G.n) K)) k r (Fintype.card E) km=> + let x := fun i=>generatedSourceSample he s.activity s.activity_pos K + (FiniteTrial.sourceD (G:=G) K) hD hu ft fq hq (bs i).1 + (fun e=>(bs i).2 ((orderedEnum E).symm e)) + h (repr (s.ratioEstimate x),vectorRep (s.update hn x).scale)) := by + dsimp only + rw [execute,Experiment.mean_map,OnlineSample.mean_many] + apply qaverage_congr + intro bs + have hs:=sparseStage_source hn he s K hD hu ft fq hq (fun i=>(bs i).1) + (fun i e=>(bs i).2 ((orderedEnum (BagEdge (RationalSource.bags s.activity K))).symm e)) + dsimp only at hs + have rows : List.ofFn (fun i=>OnlineSample.sampleRep + (fun e=>index (orderedEnum (BagEdge (RationalSource.bags s.activity K)) e)) (bs i)) = + List.ofFn (fun i=>(List.ofFn (fun z=>(List.ofFn ((bs i).1 z).1,localBitsRep ((bs i).1 z).2)), + (List.ofFn (orderedEnum (BagEdge (RationalSource.bags s.activity K)))).map + (fun e=>(index e,List.ofFn ((bs i).2 ((orderedEnum _).symm e)))))) := by + simp only [OnlineSample.sampleRep,OnlineSample.scanRep,OnlineSample.localRep,List.map_ofFn, + Function.comp_def,Equiv.symm_apply_apply,localBitsRep] + rw [rows] + exact congrArg h hs +end MatchingFPRAS.OnlineStage + +end OAI diff --git a/lean/OAI/Combinatorics/MatchingCount/Algorithm/OnlineTransitionLaw.lean b/lean/OAI/Combinatorics/MatchingCount/Algorithm/OnlineTransitionLaw.lean new file mode 100644 index 0000000000000000000000000000000000000000..576e2a0584b4d133d2b50d58100b7cdc8a3cd657 --- /dev/null +++ b/lean/OAI/Combinatorics/MatchingCount/Algorithm/OnlineTransitionLaw.lean @@ -0,0 +1,110 @@ +import Mathlib +import OAI.Combinatorics.MatchingCount.Algorithm.FiniteTrialLaw +import OAI.Combinatorics.MatchingCount.Algorithm.OutputLengthBound +import OAI.Combinatorics.MatchingCount.Algorithm.OnlineStage +import OAI.Combinatorics.MatchingCount.Probability.OnlineLawBridge +import OAI.Combinatorics.MatchingCount.Algorithm.OnlineLaw + +namespace OAI + +namespace MatchingFPRAS.OnlineStage +open PhysicalStream TreeTyped ExecutableSource NumericLadder TreeFraction ExecutableScaling +open UnitRefresh Transport Enlargement TreeTyped.Numbered ExecutableAdaptive Variation + +attribute [local instance] NumberedHierarchy.labelOrder +attribute [local instance] Transport.sym2Order Transport.bagEdgeOrder Transport.bagEdgeFintype +attribute [local instance] UnitRefresh.Computable.allowedDec Transport.prodOrder Transport.sumOrder +variable {n : ℕ} [Nontrivial (Fin n)] +variable (w : Fin n→Fin n→ℚ) (K D m : ℕ) +noncomputable local instance : Fintype (BagPM (RationalSource.bags w K)) := Fintype.ofFinite _ +noncomputable local instance : Fintype (RationalSource.Marked w K) := Fintype.ofFinite _ +noncomputable local instance : Fintype (SourceMarked (fun a b=>(w a b:ℝ)) K) := Fintype.ofFinite _ +noncomputable def realRawDraw (hw : ∀ a b,0(w a b:ℝ)) K := + (RationalSource.sourceMarkedEquiv w K).symm ∘ rawDraw w K D m hw hD hu hq he η +lemma realRawDraw_law (hw : ∀ a b,0index (orderedEnum (BagEdge (RationalSource.bags s.activity p.K)) i)))) +noncomputable def fixedData {j : ℕ} (p : Trial.Parameters G) (s : FiniteTrial.ScaleState G j) : SparseStageData := + data s p.K (FiniteTrial.sourceD (G:=G) p.K) + (List.replicate (tierCount (n:=G.n) p.K (FiniteTrial.sourceD (G:=G) p.K)) false) + (List.replicate (copies (n:=G.n) p.K (FiniteTrial.sourceD (G:=G) p.K)) false) +noncomputable def transition {j : ℕ} (p : Trial.Parameters G) (s : FiniteTrial.ScaleState G j) : + Experiment (Fraction×Vector) := execute (fixedData p s,(p.S,fixedRequest p s)) + +lemma transition_mean {j : ℕ} (p : Trial.Parameters G) (hj : j≤p.K) + (s : FiniteTrial.ScaleState G j) (h : Fraction×Vector→ℚ) : + (transition p s).mean h= + qaverage (fun bits : Fin (FiniteTrial.stageBits p)→Bool=> + let x := RationalSource.sourceMarkedEquiv s.activity p.K ∘ s.drawStage p hj bits + h (repr (s.ratioEstimate x),vectorRep (s.update p.hn x).scale)) := by + have hD : 0fun i=>raw (bs i)) = imageLaw (s.drawStage p hj) := by + rw [imageLaw_componentwise,hr,FiniteTrial.ScaleState.drawStage_law] + rfl + have hmean := qaverage_eq_of_imageLaw_eq _ _ hp (fun y=> + let x:=RationalSource.sourceMarkedEquiv s.activity p.K ∘ y + h (repr (s.ratioEstimate x),vectorRep (s.update p.hn x).scale)) + apply Eq.trans _ hmean + apply qaverage_congr + intro bs + have hx : (fun i=>generatedSourceSample p.even s.activity s.activity_pos p.K + (FiniteTrial.sourceD (G:=G) p.K) hD (s.cap hj) + (List.replicate (tierCount (n:=G.n) p.K (FiniteTrial.sourceD (G:=G) p.K)) false) + (List.replicate (copies (n:=G.n) p.K (FiniteTrial.sourceD (G:=G) p.K)) false) + (by simpa using hq) (bs i).1 (fun e=>(bs i).2 ((orderedEnum _).symm e))) = + RationalSource.sourceMarkedEquiv s.activity p.K ∘ (fun i=>raw (bs i)) := by + funext i + rw [generated_eq_raw] + exact (realRawDraw_inverse ..).symm + rw [hx] +end MatchingFPRAS.OnlineStage + +end OAI diff --git a/lean/OAI/Combinatorics/MatchingCount/Algorithm/OnlineTrial.lean b/lean/OAI/Combinatorics/MatchingCount/Algorithm/OnlineTrial.lean new file mode 100644 index 0000000000000000000000000000000000000000..5e4d13e98ee7c930d040d222504e88a767931bfe --- /dev/null +++ b/lean/OAI/Combinatorics/MatchingCount/Algorithm/OnlineTrial.lean @@ -0,0 +1,62 @@ +import Mathlib +import OAI.Combinatorics.MatchingCount.Algorithm.OnlineRequest + +namespace OAI + +namespace MatchingFPRAS.OnlineTrial +open PhysicalStream TreeTyped TreeFraction ExecutableSource ExecutableScaling OnlineSchedule + +abbrev State := RequestInput×Fraction + +def advance (x : SparseStageData×Vector) : SparseStageData := + (((x.1.1.1.1,false::x.1.1.1.2),x.1.1.2),x.2) +def advanceRealizer : TreeTyped.Realizer advance := + (TreeTyped.pair (TreeTyped.pair + (TreeTyped.pair first.fst.fst.fst (composition (TreeTyped.pair (constant false) first.fst.fst.snd) listCons)) + first.fst.snd) second).congr (fun _=>rfl) +lemma polynomial_advance : PolynomialTime advanceRealizer := by + unfold advanceRealizer + apply polynomial_congr + dsimp only [Realizer.fst, Realizer.snd] + tree_cost + +def carry (x : State×(Fraction×Vector)) : State := + ((advance (x.1.1.1,x.2.2),x.1.1.2),TreeFraction.mul (x.1.2,x.2.1)) +def carryRealizer : TreeTyped.Realizer carry := + (TreeTyped.pair (TreeTyped.pair + (composition (TreeTyped.pair first.fst.fst second.snd) advanceRealizer) first.fst.snd) + (composition (TreeTyped.pair first.snd second.fst) mulRealizer)).congr (fun _=>rfl) +lemma polynomial_carry : PolynomialTime carryRealizer := by + unfold carryRealizer + apply polynomial_congr + dsimp only [Realizer.fst, Realizer.snd] + have := polynomial_advance + have := polynomial_mul + tree_cost + +def prepare (x : RequestInput) : OnlineStage.Input := + (x.1,(x.2,sourceRequest x)) +def prepareRealizer : TreeTyped.Realizer prepare := + TreeTyped.pair first (TreeTyped.pair second sourceRequestRealizer) +lemma polynomial_prepare : PolynomialTime prepareRealizer := + TreeTyped.polynomial_pair polynomial_first (TreeTyped.polynomial_pair polynomial_second polynomial_sourceRequest) + +def step (x : State) : Experiment State := + (OnlineStage.execute (prepare x.1)).map (fun y=>carry (x,y)) +noncomputable def stepRealizer : OnlineTree.Realizer step := + (OnlineTree.composition (OnlineTree.pair (OnlineTree.deterministic TreeTyped.identity) + (OnlineTree.composition (OnlineTree.deterministic (composition first prepareRealizer)) OnlineStage.executeRealizer)) + (OnlineTree.deterministic carryRealizer)).congr (by + intro x h + simp only [step,Experiment.mean_bind,Experiment.mean_map,Experiment.mean,Function.comp_apply,id_eq]) + +def body (x : Bool×State) : Experiment State := step x.2 +noncomputable def bodyRealizer : OnlineTree.Realizer body := + (OnlineTree.composition (OnlineTree.deterministic TreeTyped.second) stepRealizer).congr (by + intro x h; rfl) + +def sweep (x : List Bool×State) : Experiment State := OnlineTree.foldM body x.1 x.2 +noncomputable def sweepRealizer : OnlineTree.Realizer sweep := OnlineTree.fold bodyRealizer +end MatchingFPRAS.OnlineTrial + +end OAI diff --git a/lean/OAI/Combinatorics/MatchingCount/Algorithm/OnlineTrialLaw.lean b/lean/OAI/Combinatorics/MatchingCount/Algorithm/OnlineTrialLaw.lean new file mode 100644 index 0000000000000000000000000000000000000000..8dba7d7ee23c162c15584ba0c0b68341d9a25d29 --- /dev/null +++ b/lean/OAI/Combinatorics/MatchingCount/Algorithm/OnlineTrialLaw.lean @@ -0,0 +1,83 @@ +import Mathlib +import OAI.Combinatorics.MatchingCount.Algorithm.OnlineTrial +import OAI.Combinatorics.MatchingCount.Algorithm.OnlineRequestLaw +import OAI.Combinatorics.MatchingCount.Probability.OnlineLayerLaw + +namespace OAI + +namespace MatchingFPRAS.OnlineTree +open PhysicalStream + +lemma foldM_append_mean {A B : Type} (f : A×B→Experiment B) (as bs : List A) (b : B) (h : B→ℚ) : + (foldM f (as++bs) b).mean h=(foldM f as b).mean (fun c=>(foldM f bs c).mean h) := by + induction as generalizing b with + | nil => rfl + | cons a as ih => simp only [List.cons_append,foldM,Experiment.mean_bind,ih] +end MatchingFPRAS.OnlineTree + +namespace MatchingFPRAS.OnlineTrial +open PhysicalStream TreeTyped TreeFraction ExecutableSource ExecutableScaling OnlineSchedule OnlineStage +open Transport UnitRefresh Enlargement + +attribute [local instance] NumberedHierarchy.labelOrder +attribute [local instance] Transport.sym2Order Transport.bagEdgeOrder Transport.bagEdgeFintype +attribute [local instance] UnitRefresh.Computable.allowedDec Transport.prodOrder Transport.sumOrder +variable {G : GraphInput} [Nontrivial (Fin G.n)] + +noncomputable def represent {j : ℕ} (p : Trial.Parameters G) (L : FiniteTrial.Layer p j) (x : L.Ω) : State := + ((fixedData p (L.state x),p.S),repr (product p L x)) +lemma advance_source {j : ℕ} (p : Trial.Parameters G) (s : FiniteTrial.ScaleState G j) + (xs : Fin p.S→RationalSource.Marked s.activity p.K) : + advance (fixedData p s,vectorRep (s.update p.hn xs).scale)=fixedData p (s.update p.hn xs) := by + unfold advance fixedData data + simp only [List.replicate_succ] + +lemma carry_represent {j : ℕ} (p : Trial.Parameters G) (hj : j≤p.K) (L : FiniteTrial.Layer p j) + (x : (L.append p hj).Ω) : + carry (represent p L x.1, + (repr ((L.state x.1).ratioEstimate (RationalSource.sourceMarkedEquiv (L.state x.1).activity p.K ∘ x.2)), + vectorRep ((L.state x.1).update p.hn (RationalSource.sourceMarkedEquiv (L.state x.1).activity p.K ∘ x.2)).scale))= + represent p (L.append p hj) x := by + unfold carry represent + dsimp only + rw [advance_source,mul_repr (product_nonneg p L _) ((L.state x.1).ratioEstimate_nonneg x.2),←product_append] + rfl + +lemma step_mean {j : ℕ} (p : Trial.Parameters G) (hj : j≤p.K) (L : FiniteTrial.Layer p j) + (x : L.Ω) (h : State→ℚ) : + (step (represent p L x)).mean h= + qaverage (fun b=>h (represent p (L.append p hj) ⟨x,(L.state x).drawStage p hj b⟩)) := by + unfold step + rw [Experiment.mean_map] + have hp : prepare (represent p L x).1 = (fixedData p (L.state x),(p.S,fixedRequest p (L.state x))) := by + change (fixedData p (L.state x),(p.S,sourceRequest (fixedData p (L.state x),p.S)))=_ + rw [sourceRequest_source] + rw [hp] + change (transition p (L.state x)).mean (fun y=>h (carry (represent p L x,y)))=_ + rw [transition_mean p hj] + apply qaverage_congr + intro b + have hc := carry_represent p hj L ⟨x,(L.state x).drawStage p hj b⟩ + dsimp only at hc ⊢ + exact congrArg h hc + +lemma sweep_mean (p : Trial.Parameters G) (j : ℕ) (hj : j≤p.K) (h : State→ℚ) : + (sweep (List.replicate j false,represent p (FiniteTrial.firstLayer p) PUnit.unit)).mean h= + qaverage (fun b=>h (represent p (FiniteTrial.layers p j hj) (FiniteTrial.drawLayer p j hj b))) := by + induction j generalizing h with + | zero => + change h (represent p (FiniteTrial.firstLayer p) PUnit.unit)=qaverage (fun _=>h (represent p (FiniteTrial.firstLayer p) PUnit.unit)) + rw [qaverage_const] + | succ j ih => + change (OnlineTree.foldM body (List.replicate (j+1) false) _).mean h=_ + rw [List.replicate_add,OnlineTree.foldM_append_mean] + simp only [List.replicate_one,OnlineTree.foldM,body,Experiment.mean_bind,Experiment.mean] + change (sweep (List.replicate j false,represent p (FiniteTrial.firstLayer p) PUnit.unit)).mean (fun x=>(step x).mean h)=_ + rw [ih (by omega)] + rw [mean_layer_succ p hj (fun x=>h (represent p (FiniteTrial.layers p (j+1) hj) x))] + apply qaverage_congr + intro b + exact step_mean p (by omega) (FiniteTrial.layers p j (by omega)) (FiniteTrial.drawLayer p j (by omega) b) h +end MatchingFPRAS.OnlineTrial + +end OAI diff --git a/lean/OAI/Combinatorics/MatchingCount/Algorithm/OutputLengthBound.lean b/lean/OAI/Combinatorics/MatchingCount/Algorithm/OutputLengthBound.lean new file mode 100644 index 0000000000000000000000000000000000000000..b362c70d6d4790942ab029a484cd36d4cc97d21f --- /dev/null +++ b/lean/OAI/Combinatorics/MatchingCount/Algorithm/OutputLengthBound.lean @@ -0,0 +1,800 @@ +import Mathlib +import OAI.Combinatorics.MatchingCount.Algorithm.FiniteStage +import OAI.Combinatorics.MatchingCount.Algorithm.RationalStart +import OAI.Combinatorics.MatchingCount.Algorithm.RationalCounts +import OAI.Combinatorics.MatchingCount.Algorithm.EmpiricalDenom + +namespace OAI + +namespace MatchingFPRAS +open Finset + +lemma Perfect.vertices_le_twice_edges {G : GraphInput} {M : Finset (Fin G.n × Fin G.n)} + (h : Perfect G M) : G.n≤2*G.edges.card := by + classical + have hs : (univ : Finset (Fin G.n)) ⊆ G.edges.image Prod.fst ∪ G.edges.image Prod.snd := by + intro v _ + obtain ⟨e,⟨he,hi⟩,_⟩:=h.2 v + rcases hi with hi|hi + · exact mem_union_left _ (mem_image.mpr ⟨e,h.1 he,hi⟩) + · exact mem_union_right _ (mem_image.mpr ⟨e,h.1 he,hi⟩) + calc + G.n = (univ : Finset (Fin G.n)).card := by simp + _ ≤ (G.edges.image Prod.fst ∪ G.edges.image Prod.snd).card := card_le_card hs + _ ≤ (G.edges.image Prod.fst).card+(G.edges.image Prod.snd).card := card_union_le _ _ + _ ≤ G.edges.card+G.edges.card := Nat.add_le_add (card_image_le) (card_image_le) + _ = _ := by omega +lemma positive_count_vertices (G : GraphInput) (hZ : 0 simp + | cons a L ih => + have ha:=hf a + simp only [List.length_cons,List.flatMap_cons,List.length_append] + omega +lemma edges_le_input_length (G : GraphInput) (e d : ℚ) : G.edges.card≤(encodeInput G e d).length := by + classical + let L := (G.edges.map toLex.toEmbedding).sort (· ≤ ·) + let f := fun a : Lex (Fin G.n × Fin G.n)=>encodeNat (ofLex a).1.val ++ encodeNat (ofLex a).2.val + have hf : ∀ a,0<(f a).length := by + intro a + have hh:=encodeNat_length_pos (ofLex a).1.val + simpa only [f,List.length_append] using (lt_of_lt_of_le hh (Nat.le_add_right _ _)) + have hh:=flatMap_length_ge f hf L + have hL : L.length=G.edges.card := by simp [L] + rw [hL] at hh + unfold encodeInput + change G.edges.card≤(encodeNat G.n ++ encodeNat G.edges.card ++ L.flatMap f ++ encodeRat e ++ encodeRat d).length + simp only [List.length_append] + omega +lemma nonzero_vertices_le_input_twice (G : GraphInput) (e d : ℚ) (h : 2*G.edges.card≥G.n) : + G.n≤2*(encodeInput G e d).length := + h.trans (Nat.mul_le_mul_left 2 (edges_le_input_length G e d)) +end MatchingFPRAS + +namespace MatchingFPRAS.Counting +lemma sigma_inv_polynomial (D K : ℕ) (e : ℚ) (he : 0a.1output p (x i)) + change (encodeRat (Amplification.median (fun i=>output p (x i)))).length≤_ + rw [hi] + exact output_encode_length p (x i) +end MatchingFPRAS.FiniteTrial + +namespace MatchingFPRAS.Transport +open Finset + +lemma clog_two_le_self (m : ℕ) : Nat.clog 2 m ≤ m := + Nat.clog_le_of_le_pow (Nat.lt_two_pow_self (n:=m)).le +lemma bitPrecision_le (R : ℕ) (η : ℚ) : bitPrecision R η ≤ R*⌈η⁻¹⌉₊ := + clog_two_le_self _ +lemma sym2_card_le_square (V : Type*) [Fintype V] : Fintype.card (Sym2 V) ≤ (Fintype.card V)^2 := by + simpa only [Fintype.card_prod,pow_two] using Fintype.card_le_of_surjective _ (Sym2.mk_surjective (α:=V)) +lemma bagEdge_card_le {V L : Type*} [Fintype V] [DecidableEq V] [Fintype L] [DecidableEq L] + (bags : V → Finset L) [Fintype (BagEdge bags)] : + Fintype.card (BagEdge bags) ≤ (Fintype.card V)^2*Fintype.card L := by + classical + have hi : Function.Injective (fun e : BagEdge bags=>e.val.val) := + Subtype.val_injective.comp Subtype.val_injective + exact (Fintype.card_le_of_injective _ hi).trans (by + rw [Fintype.card_prod] + exact Nat.mul_le_mul_right _ (sym2_card_le_square V)) +def tierPolynomial (N D K : ℕ) := N^2*(D+2*K+2) +def lambdaPolynomial (N D K T : ℕ) := 10*N*ladderQ N D*(T+1)*(K+(N*D+2)+1) +def stepsPolynomial (N D K m : ℕ) := + 20*ladderL N D*ladderM N D (tierPolynomial N D K)* + (lambdaPolynomial N D K (tierPolynomial N D K)+m+1) +def edgePolynomial (N K : ℕ) := N^2*((2*K+1)*N) +def scanErrorPolynomial (N D K : ℕ) := + 2*(1+ladderM N D (tierPolynomial N D K))+ + 4*(8*(edgePolynomial N K)^2+4*edgePolynomial N K+3)+2*N^2*((2*K+1)*N) +def totalBitsPolynomial (N D K m H : ℕ) := + let t:=stepsPolynomial N D K m + let R:=scanErrorPolynomial N D K + t*((t*R*H)+(t*R*H+N*(t*R*H)))+edgePolynomial N K*(6*edgePolynomial N K*H) +lemma endpoint_le_polynomial (N D K : ℕ) (hN : 0f x.1)=imageLaw f := by + have hh:=imageLaw_comp_equiv (Equiv.prodComm A B) (fun x : B×A=>f x.2) + exact hh.trans (imageLaw_ignore f) +def paddedBits {k B : ℕ} (h : k≤B) : + (Fin B → Bool) ≃ ((Fin k → Bool) × (Fin (B-k) → Bool)) := + (Equiv.arrowCongr (finCongr (Nat.add_sub_of_le h).symm) (Equiv.refl Bool)).trans (pairBitsEquiv k (B-k)) +def padSampler {k B : ℕ} (h : k≤B) (f : (Fin k → Bool) → A) : (Fin B → Bool) → A := + fun bits=>f ((paddedBits h bits).1) +omit [Fintype A] in +lemma padSampler_law {k B : ℕ} (h : k≤B) (f : (Fin k → Bool) → A) : + imageLaw (padSampler h f)=imageLaw f := + (imageLaw_comp_equiv (paddedBits h) (fun x=>f x.1)).trans (imageLaw_ignore_right f) +noncomputable def markedBitsEquiv (E : Type*) [Fintype E] (t k : ℕ) : + (Fin (t+Fintype.card E*k) → Bool) ≃ ((Fin t → Bool) × (E → Fin k → Bool)) := + (pairBitsEquiv t (Fintype.card E*k)).trans (Equiv.prodCongr (Equiv.refl _) + ((matrixBitsEquiv (Fintype.card E) k).trans + (Equiv.arrowCongr (Fintype.equivFin E).symm (Equiv.refl _)))) +end MatchingFPRAS.Variation +namespace MatchingFPRAS.RationalSource +open Transport Enlargement Variation + +variable {V : Type*} [Fintype V] [LinearOrder V] [Nontrivial V] +attribute [local instance] NumberedHierarchy.labelOrder sym2Order bagEdgeOrder bagEdgeFintype +attribute [local instance] UnitRefresh.Computable.allowedDec prodOrder sumOrder +noncomputable local instance (w : V → V → ℚ) (K : ℕ) : + DecidableEq (SourceLabel (fun x y=>(w x y:ℝ)) K) := Classical.decEq _ +noncomputable local instance (w : V → V → ℚ) (K : ℕ) : + Fintype (BagEdge (sourceBags (fun x y=>(w x y:ℝ)) K)) := Fintype.ofFinite _ +noncomputable local instance (w : V → V → ℚ) (K : ℕ) : + DecidableEq (BagPM (bags w K)) := Classical.decEq _ +noncomputable local instance (w : V → V → ℚ) (K : ℕ) : + Fintype (BagPM (bags w K)) := Fintype.ofFinite _ +noncomputable local instance (w : V → V → ℚ) (K : ℕ) : + Fintype (Marked w K) := Fintype.ofFinite _ +noncomputable local instance (w : V → V → ℚ) (K : ℕ) : + Fintype (SourceMarked (fun x y=>(w x y:ℝ)) K) := Fintype.ofFinite _ +noncomputable local instance (w : V → V → ℚ) (K t k : ℕ) : + Fintype ((Fin t → Bool) × (BagEdge (bags w K) → Fin k → Bool)) := Fintype.ofFinite _ +noncomputable def bitSampler (w : V → V → ℚ) (hw : ∀ x y,0(w x y:ℝ)) K := + (sourceMarkedEquiv w K).symm ∘ markedSampler w hw K D m hD hN h hq M η ∘ + markedBitsEquiv (BagEdge (bags w K)) _ _ +lemma bitSampler_law (w : V → V → ℚ) (hw : ∀ x y,0(w x y:ℝ)) K := + padSampler (samplerBitCount_le w K D m hN η) (bitSampler w hw K D m hD hN h hq M η) +lemma fixedSampler_law (w : V → V → ℚ) (hw : ∀ x y,0(⟨f z.1,g (f z.1) z.2⟩ : Sigma E))= + sigmaLift (imageLaw f) (fun x=>imageLaw (g x)) := by + rw [imageLaw_adaptive_pair f (fun x b=>(⟨x,g x b⟩ : Sigma E))] + funext ⟨x,y⟩ + unfold bind sigmaLift + dsimp only + have he : imageLaw (fun b=>(⟨x,g x b⟩ : Sigma E)) ⟨x,y⟩=imageLaw (g x) y := by + unfold imageLaw push + simp only [Sigma.mk.inj_iff,heq_eq_eq,true_and] + rw [←he] + apply sum_eq_single x + · intro a _ ha + have hz : imageLaw (fun b=>(⟨a,g a b⟩ : Sigma E)) ⟨x,y⟩=0 := by + unfold imageLaw push + apply sum_eq_zero + intro b _ + exact ite_eq_right (fun hh=>ha (congrArg Sigma.fst hh)) + rw [hz,mul_zero] + · simp +end MatchingFPRAS.Variation + +namespace MatchingFPRAS.FiniteTrial +open Transport Enlargement Variation Adaptive + +variable {G : GraphInput} [Nontrivial (Fin G.n)] +attribute [local instance] NumberedHierarchy.labelOrder sym2Order bagEdgeOrder bagEdgeFintype +attribute [local instance] UnitRefresh.Computable.allowedDec prodOrder sumOrder +noncomputable local instance (w : Fin G.n → Fin G.n → ℚ) (K : ℕ) : + DecidableEq (SourceLabel (fun x y=>(w x y:ℝ)) K) := Classical.decEq _ +noncomputable local instance (w : Fin G.n → Fin G.n → ℚ) (K : ℕ) : + Fintype (BagEdge (sourceBags (fun x y=>(w x y:ℝ)) K)) := Fintype.ofFinite _ +noncomputable local instance (w : Fin G.n → Fin G.n → ℚ) (K : ℕ) : + Fintype (SourceMarked (fun x y=>(w x y:ℝ)) K) := Fintype.ofFinite _ +noncomputable def oneBits (p : Trial.Parameters G) : ℕ := + totalBitsPolynomial p.N p.D p.K (1000*p.K*p.S) ⌈(1/(1000*p.K*p.S):ℚ)⁻¹⌉₊ +omit [Nontrivial (Fin G.n)] in +lemma oneBits_eq (p : Trial.Parameters G) : oneBits p=totalBitsPolynomial p.N p.D p.K (1000*p.K*p.S) (1000*p.K*p.S) := by + unfold oneBits + congr 1 + rw [one_div,inv_inv] + simpa only [Nat.cast_mul,Nat.cast_ofNat] using (Nat.ceil_natCast (R:=ℚ) (1000*p.K*p.S)) +noncomputable def ScaleState.drawOne (p : Trial.Parameters G) {j : ℕ} (hj : j≤p.K) (s : ScaleState G j) : + (Fin (oneBits p) → Bool) → SourceMarked (fun a b=>(s.activity a b:ℝ)) p.K := + RationalSource.fixedSampler s.activity s.activity_pos p.K + (Enlargement.sourceD (V:=Fin G.n) p.K) (1000*p.K*p.S) + (sourceD_one p.K) Fintype.card_pos (s.cap hj) p.q_pos + (RationalSource.startMatching s.activity p.K p.even) (1/(1000*p.K*p.S)) +lemma ScaleState.drawOne_law (p : Trial.Parameters G) {j : ℕ} (hj : j≤p.K) (s : ScaleState G j) : + imageLaw (s.drawOne p hj)=(s.runLaw p hj).mass := by + exact RationalSource.fixedSampler_law _ _ _ _ _ _ _ _ _ _ _ +noncomputable def stageBits (p : Trial.Parameters G) : ℕ := p.S*oneBits p +noncomputable def ScaleState.drawStage (p : Trial.Parameters G) {j : ℕ} (hj : j≤p.K) (s : ScaleState G j) : + (Fin (stageBits p) → Bool) → Fin p.S → SourceMarked (fun a b=>(s.activity a b:ℝ)) p.K := + (fun b i=>s.drawOne p hj (b i)) ∘ matrixBitsEquiv p.S (oneBits p) +lemma ScaleState.drawStage_law (p : Trial.Parameters G) {j : ℕ} (hj : j≤p.K) (s : ScaleState G j) : + imageLaw (s.drawStage p hj)=(s.sampleLaw p hj).mass := by + unfold ScaleState.drawStage + erw [imageLaw_comp_equiv,imageLaw_componentwise] + rw [ScaleState.drawOne_law] + rfl + +open Transport Enlargement Variation Adaptive + +variable {G : GraphInput} [Nontrivial (Fin G.n)] +attribute [local instance] NumberedHierarchy.labelOrder sym2Order bagEdgeOrder bagEdgeFintype +attribute [local instance] UnitRefresh.Computable.allowedDec prodOrder sumOrder +noncomputable local instance (w : Fin G.n → Fin G.n → ℚ) (K : ℕ) : + DecidableEq (SourceLabel (fun x y=>(w x y:ℝ)) K) := Classical.decEq _ +noncomputable local instance (w : Fin G.n → Fin G.n → ℚ) (K : ℕ) : + Fintype (BagEdge (sourceBags (fun x y=>(w x y:ℝ)) K)) := Fintype.ofFinite _ +noncomputable local instance (w : Fin G.n → Fin G.n → ℚ) (K : ℕ) : + Fintype (SourceMarked (fun x y=>(w x y:ℝ)) K) := Fintype.ofFinite _ +noncomputable def Layer.drawAppend (p : Trial.Parameters G) {j : ℕ} (hj : j≤p.K) + (L : Layer p j) {a : ℕ} (f : (Fin a → Bool) → L.Ω) : + (Fin (a+stageBits p) → Bool) → (L.append p hj).Ω := + fun b => + let c : (Fin a → Bool) × (Fin (stageBits p) → Bool) := pairBitsEquiv a (stageBits p) b + (⟨f c.1,(L.state (f c.1)).drawStage p hj c.2⟩ : + Σ x : L.Ω, Fin p.S → SourceMarked (fun v w=>((L.state x).activity v w:ℝ)) p.K) +lemma Layer.drawAppend_law (p : Trial.Parameters G) {j : ℕ} (hj : j≤p.K) + (L : Layer p j) {a : ℕ} (f : (Fin a → Bool) → L.Ω) (hf : imageLaw f=L.law.mass) : + imageLaw (L.drawAppend p hj f)=(L.append p hj).law.mass := by + change imageLaw ((fun b : (Fin a → Bool) × (Fin (stageBits p) → Bool) => + (⟨f b.1,(L.state (f b.1)).drawStage p hj b.2⟩ : + Σ x : L.Ω, Fin p.S → SourceMarked (fun v w=>((L.state x).activity v w:ℝ)) p.K)) ∘ + pairBitsEquiv a (stageBits p)) = _ + erw [imageLaw_comp_equiv] + change imageLaw _ = sigmaLift L.law.mass (fun x=>(L.state x).sampleLaw p hj |>.mass) + rw [imageLaw_sigma_pair f (fun x=>(L.state x).drawStage p hj)] + simp_rw [ScaleState.drawStage_law] + rw [hf] +def successorBitsEquiv (j B : ℕ) : (Fin ((j+1)*B) → Bool) ≃ (Fin (j*B+B) → Bool) := + Equiv.arrowCongr (finCongr (Nat.succ_mul j B)) (Equiv.refl Bool) +noncomputable def drawLayer (p : Trial.Parameters G) : (j : ℕ) → (hj : j≤p.K) → + (Fin (j*stageBits p) → Bool) → (layers p j hj).Ω + | 0,_ => fun _=>PUnit.unit + | j+1,hj => (layers p j (by omega)).drawAppend p (by omega) (drawLayer p j (by omega)) ∘ successorBitsEquiv j (stageBits p) +lemma drawLayer_law (p : Trial.Parameters G) (j : ℕ) (hj : j≤p.K) : + imageLaw (drawLayer p j hj)=(layers p j hj).law.mass := by + induction j with + | zero => + change imageLaw (fun _ : Fin (0*stageBits p) → Bool=>PUnit.unit)=(firstLayer p).law.mass + rw [imageLaw_subsingleton] + funext x + simp [uniform,firstLayer] + | succ j ih => + unfold drawLayer + erw [imageLaw_comp_equiv] + exact Layer.drawAppend_law p (by omega) (layers p j (by omega)) _ (ih (by omega)) +noncomputable def bitOutput (p : Trial.Parameters G) : (Fin (p.K*stageBits p) → Bool) → ℚ := + output p ∘ drawLayer p p.K le_rfl +lemma bitOutput_nonneg (p : Trial.Parameters G) (b : Fin (p.K*stageBits p) → Bool) : + 0≤bitOutput p b := output_nonneg p _ +end MatchingFPRAS.FiniteTrial + +namespace MatchingFPRAS.Variation +open Finset +open scoped Classical + +variable {A B : Type*} [Fintype A] [Fintype B] +lemma event_push (p : A → ℝ) (f : A → B) (P : B → Prop) : + event (push p f) P=event p (fun x=>P (f x)) := by + unfold event push + have h : (∑ y,if P y then ∑ x,if f x=y then p x else 0 else 0)= + ∑ y,∑ x,if f x=y then (if P y then p x else 0) else 0 := by + apply sum_congr rfl + intro y _ + by_cases hy:P y <;> simp [hy] + rw [h,sum_comm] + simp +lemma event_imageLaw (f : A → B) (P : B → Prop) : + event (imageLaw f) P=((univ.filter (fun x=>P (f x))).card:ℝ)/Fintype.card A := by + rw [imageLaw,event_push] + unfold event uniform + rw [show (∑ x,if P (f x) then (1:ℝ)/Fintype.card A else 0)= + (∑ x,if P (f x) then (1:ℝ) else 0)/Fintype.card A by + simp only [sum_div,ite_div,zero_div]] + simp +lemma event_complement (p : A → ℝ) (P : A → Prop) : + event p P+event p (fun x=>¬P x)=∑ x,p x := by + unfold event + rw [←sum_add_distrib] + apply sum_congr rfl + intro x _ + by_cases hx:P x <;> simp [hx] +end MatchingFPRAS.Variation + +namespace MatchingFPRAS.FiniteTrial +open Variation Adaptive Amplification Finset Transport +open scoped Classical + +variable {G : GraphInput} [Nontrivial (Fin G.n)] +noncomputable def amplifiedBits (p : Trial.Parameters G) (δ : ℚ) : ℕ := + (2*halfRepetitions δ+1)*(p.K*stageBits p) +noncomputable def drawTrials (p : Trial.Parameters G) (δ : ℚ) : + (Fin (amplifiedBits p δ) → Bool) → Fin (2*halfRepetitions δ+1) → (layers p p.K le_rfl).Ω := + (fun bits i=>drawLayer p p.K le_rfl (bits i)) ∘ matrixBitsEquiv (2*halfRepetitions δ+1) (p.K*stageBits p) +lemma drawTrials_law (p : Trial.Parameters G) (δ : ℚ) : + imageLaw (drawTrials p δ)=((layers p p.K le_rfl).law.iid (2*halfRepetitions δ+1)).mass := by + unfold drawTrials + erw [imageLaw_comp_equiv,imageLaw_componentwise] + rw [drawLayer_law] + rfl +noncomputable def amplifiedBitOutput (p : Trial.Parameters G) (δ : ℚ) : + (Fin (amplifiedBits p δ) → Bool) → ℚ := amplifiedOutput p δ ∘ drawTrials p δ +lemma amplifiedBitOutput_nonneg (p : Trial.Parameters G) (δ : ℚ) + (b : Fin (amplifiedBits p δ) → Bool) : 0≤amplifiedBitOutput p δ b := + amplifiedOutput_nonneg p δ _ +noncomputable def accurateBits (p : Trial.Parameters G) (δ : ℚ) : Finset (Fin (amplifiedBits p δ) → Bool) := + univ.filter fun b=>Accurate p (amplifiedBitOutput p δ b) +theorem amplifiedBitOutput_success (p : Trial.Parameters G) (hZ : 0Accurate p (amplifiedOutput p δ x)) + rw [Law.total] at hc + have hh : 1-(δ:ℝ) ≤ event ((layers p p.K le_rfl).law.iid (2*halfRepetitions δ+1)).mass + (fun x=>Accurate p (amplifiedOutput p δ x)) := by + change event _ (fun x=>¬Accurate p (amplifiedOutput p δ x))≤(δ:ℝ) at hf + linarith only [hc,hf] + rw [←drawTrials_law,event_imageLaw] at hh + have he : Fintype.card (Fin (amplifiedBits p δ) → Bool)=2^(amplifiedBits p δ) := by simp + rw [he] at hh + change 1-(δ:ℝ) ≤ ((accurateBits p δ).card:ℝ)/(2^(amplifiedBits p δ):ℕ) at hh + have hr : ((1-δ:ℚ):ℝ) ≤ (((((accurateBits p δ).card:ℚ)/(2:ℚ)^(amplifiedBits p δ)):ℚ):ℝ) := by + push_cast + simpa only [Nat.cast_pow,Nat.cast_ofNat] using hh + exact Rat.cast_le.mp hr +end MatchingFPRAS.FiniteTrial + +namespace MatchingFPRAS.BitComplexity + +def PolynomiallyBounded (f : ℕ → ℕ) : Prop := ∃ C d : ℕ, ∀ x,1≤x → f x≤C*x^d +lemma PolynomiallyBounded.const (c : ℕ) : PolynomiallyBounded (fun _=>c) := by + exact ⟨c,0,fun _ _=>by simp⟩ +lemma PolynomiallyBounded.id : PolynomiallyBounded (fun x=>x) := by + exact ⟨1,1,fun _ _=>by simp⟩ +lemma PolynomiallyBounded.add {f g : ℕ → ℕ} (hf : PolynomiallyBounded f) (hg : PolynomiallyBounded g) : + PolynomiallyBounded (fun x=>f x+g x) := by + obtain ⟨C,d,hf⟩:=hf + obtain ⟨E,k,hg⟩:=hg + refine ⟨C+E,d+k,fun x hx=>?_⟩ + have h₁ : x^d≤x^(d+k) := Nat.pow_le_pow_right hx (by omega) + have h₂ : x^k≤x^(d+k) := Nat.pow_le_pow_right hx (by omega) + calc + _ ≤ C*x^d+E*x^k := Nat.add_le_add (hf x hx) (hg x hx) + _ ≤ C*x^(d+k)+E*x^(d+k) := Nat.add_le_add (Nat.mul_le_mul_left C h₁) (Nat.mul_le_mul_left E h₂) + _ = _ := (Nat.add_mul _ _ _).symm +lemma PolynomiallyBounded.mul {f g : ℕ → ℕ} (hf : PolynomiallyBounded f) (hg : PolynomiallyBounded g) : + PolynomiallyBounded (fun x=>f x*g x) := by + obtain ⟨C,d,hf⟩:=hf + obtain ⟨E,k,hg⟩:=hg + refine ⟨C*E,d+k,fun x hx=>?_⟩ + calc + _ ≤ (C*x^d)*(E*x^k) := Nat.mul_le_mul (hf x hx) (hg x hx) + _ = _ := by rw [pow_add]; ac_rfl +lemma PolynomiallyBounded.pow {f : ℕ → ℕ} (hf : PolynomiallyBounded f) (k : ℕ) : + PolynomiallyBounded (fun x=>(f x)^k) := by + obtain ⟨C,d,hf⟩:=hf + refine ⟨C^k,d*k,fun x hx=>?_⟩ + calc + _ ≤ (C*x^d)^k := Nat.pow_le_pow_left (hf x hx) k + _ = _ := by rw [mul_pow,pow_mul] +def boundK (x : ℕ) : ℕ := (2*x)*((2*x)*(2*x)+32*x) +def boundN (x : ℕ) : ℕ := 2*x+(2*x)^2*(4*(2*boundK x+2)) +def boundD (x : ℕ) : ℕ := 100*(boundN x)^2*(100000000*(2*x+1)^4) +def boundS (x : ℕ) : ℕ := 10*(10000000*boundD x+1000*boundK x*x)^2*(2*x+boundK x+1) +def boundBits (x : ℕ) : ℕ := (10*(x+1)+1)*(boundK x*(boundS x* + Transport.totalBitsPolynomial (boundN x) (boundD x) (boundK x) (1000*boundK x*boundS x) (1000*boundK x*boundS x))) +private lemma c (n : ℕ) : PolynomiallyBounded (fun _=>n) := PolynomiallyBounded.const n +private lemma X : PolynomiallyBounded (fun n=>n) := PolynomiallyBounded.id +lemma boundK_polynomial : PolynomiallyBounded boundK := by + exact ((c 2).mul X).mul ((((c 2).mul X).mul ((c 2).mul X)).add ((c 32).mul X)) +lemma boundN_polynomial : PolynomiallyBounded boundN := by + exact ((c 2).mul X).add (((((c 2).mul X).pow 2)).mul ((c 4).mul (((c 2).mul boundK_polynomial).add (c 2)))) +lemma boundD_polynomial : PolynomiallyBounded boundD := by + exact ((c 100).mul (boundN_polynomial.pow 2)).mul ((c 100000000).mul ((((c 2).mul X).add (c 1)).pow 4)) +lemma boundS_polynomial : PolynomiallyBounded boundS := by + exact ((c 10).mul ((((c 10000000).mul boundD_polynomial).add (((c 1000).mul boundK_polynomial).mul X)).pow 2)).mul ((((c 2).mul X).add boundK_polynomial).add (c 1)) +open Transport + +lemma ladderL_polynomial {f g : ℕ → ℕ} (hf : PolynomiallyBounded f) (hg : PolynomiallyBounded g) : + PolynomiallyBounded (fun x=>ladderL (f x) (g x)) := by + exact (((c (10^4)).mul hf).mul hg).pow 100 +lemma ladderQ_polynomial {f g : ℕ → ℕ} (hf : PolynomiallyBounded f) (hg : PolynomiallyBounded g) : + PolynomiallyBounded (fun x=>ladderQ (f x) (g x)) := by + exact (c 32).mul (ladderL_polynomial hf hg) +lemma ladderM_polynomial {f g h : ℕ → ℕ} (hf : PolynomiallyBounded f) (hg : PolynomiallyBounded g) + (hh : PolynomiallyBounded h) : PolynomiallyBounded (fun x=>ladderM (f x) (g x) (h x)) := by + exact (hh.mul ((ladderQ_polynomial hf hg).pow 2)).add (ladderQ_polynomial hf hg) +lemma tier_polynomial {f g h : ℕ → ℕ} (hf : PolynomiallyBounded f) (hg : PolynomiallyBounded g) + (hh : PolynomiallyBounded h) : PolynomiallyBounded (fun x=>tierPolynomial (f x) (g x) (h x)) := by + exact (hf.pow 2).mul ((hg.add ((c 2).mul hh)).add (c 2)) +lemma edge_polynomial {f h : ℕ → ℕ} (hf : PolynomiallyBounded f) (hh : PolynomiallyBounded h) : + PolynomiallyBounded (fun x=>edgePolynomial (f x) (h x)) := by + exact (hf.pow 2).mul ((((c 2).mul hh).add (c 1)).mul hf) +lemma lambda_polynomial {f g h t : ℕ → ℕ} (hf : PolynomiallyBounded f) (hg : PolynomiallyBounded g) + (hh : PolynomiallyBounded h) (ht : PolynomiallyBounded t) : + PolynomiallyBounded (fun x=>lambdaPolynomial (f x) (g x) (h x) (t x)) := by + exact ((((c 10).mul hf).mul (ladderQ_polynomial hf hg)).mul (ht.add (c 1))).mul + ((hh.add ((hf.mul hg).add (c 2))).add (c 1)) +lemma steps_polynomial {f g h m : ℕ → ℕ} (hf : PolynomiallyBounded f) (hg : PolynomiallyBounded g) + (hh : PolynomiallyBounded h) (hm : PolynomiallyBounded m) : + PolynomiallyBounded (fun x=>stepsPolynomial (f x) (g x) (h x) (m x)) := by + have ht:=tier_polynomial hf hg hh + exact (((c 20).mul (ladderL_polynomial hf hg)).mul (ladderM_polynomial hf hg ht)).mul + (((lambda_polynomial hf hg hh ht).add hm).add (c 1)) +lemma scan_polynomial {f g h : ℕ → ℕ} (hf : PolynomiallyBounded f) (hg : PolynomiallyBounded g) + (hh : PolynomiallyBounded h) : PolynomiallyBounded (fun x=>scanErrorPolynomial (f x) (g x) (h x)) := by + have ht:=tier_polynomial hf hg hh + have he:=edge_polynomial hf hh + exact (((c 2).mul ((c 1).add (ladderM_polynomial hf hg ht))).add + ((c 4).mul (((((c 8).mul (he.pow 2)).add ((c 4).mul he))).add (c 3)))).add + (((c 2).mul (hf.pow 2)).mul ((((c 2).mul hh).add (c 1)).mul hf)) +lemma total_polynomial {f g h m H : ℕ → ℕ} (hf : PolynomiallyBounded f) (hg : PolynomiallyBounded g) + (hh : PolynomiallyBounded h) (hm : PolynomiallyBounded m) (hH : PolynomiallyBounded H) : + PolynomiallyBounded (fun x=>totalBitsPolynomial (f x) (g x) (h x) (m x) (H x)) := by + have ht:=steps_polynomial hf hg hh hm + have hR:=scan_polynomial hf hg hh + have he:=edge_polynomial hf hh + have ha:=(ht.mul hR).mul hH + exact (ht.mul (ha.add (ha.add (hf.mul ha)))).add (he.mul (((c 6).mul he).mul hH)) +lemma boundBits_polynomial : PolynomiallyBounded boundBits := by + have hm:=((c 1000).mul boundK_polynomial).mul boundS_polynomial + exact (((c 10).mul (X.add (c 1))).add (c 1)).mul (boundK_polynomial.mul + (boundS_polynomial.mul (total_polynomial boundN_polynomial boundD_polynomial boundK_polynomial hm hm))) +end MatchingFPRAS.BitComplexity + +namespace MatchingFPRAS.Transport +lemma totalBitsPolynomial_mono {N N' D D' K K' m m' H H' : ℕ} + (hN : N ≤ N') (hD : D ≤ D') (hK : K ≤ K') (hm : m ≤ m') (hH : H ≤ H') : + totalBitsPolynomial N D K m H ≤ totalBitsPolynomial N' D' K' m' H' := by + unfold totalBitsPolynomial stepsPolynomial scanErrorPolynomial lambdaPolynomial tierPolynomial + edgePolynomial ladderM ladderQ ladderL + dsimp only + gcongr +end MatchingFPRAS.Transport +namespace MatchingFPRAS.BitComplexity +open FiniteTrial Trial Transport Amplification + +lemma parameters_K_le {G : GraphInput} (hn : 2 ≤ G.n) (heven : Even G.n) + (e : ℚ) (he : 0?_⟩ + exact (scheduledBits_le hn hev e δ he he1 hs).trans (h _ (inputSize_pos G e δ)) +end MatchingFPRAS.BitComplexity + +namespace MatchingFPRAS.UnitRefresh +lemma pairingCount_pos_even (n : ℕ) : 0 intro _; decide + | one => simp + | more n ih _ => + intro hh + rw [pairingCount_add_two] at hh + have hp:0P (padSampler h f b))).card:ℚ)/(2:ℚ)^B = + ((univ.filter (fun b=>P (f b))).card:ℚ)/(2:ℚ)^k := by + have hh:=congrArg (fun p=>event p (fun b=>P (f b))) (padSampler_law h (id : (Fin k → Bool) → (Fin k → Bool))) + rw [event_imageLaw,event_imageLaw] at hh + simp only [id_eq,Fintype.card_fun,Fintype.card_bool,Fintype.card_fin,Nat.cast_pow,Nat.cast_ofNat] at hh + apply Rat.cast_injective (α:=ℝ) + push_cast + exact hh +end MatchingFPRAS.Variation + +namespace MatchingFPRAS.FiniteTrial +open BitComplexity Variation Finset +open scoped Classical + +lemma padded_amplified_success {G : GraphInput} [Nontrivial (Fin G.n)] + (p : Trial.Parameters G) (δ : ℚ) (B : ℕ) (ht : amplifiedBits p δ≤B) + (hz : 0Accurate p (padSampler ht (amplifiedBitOutput p δ) b))).card:ℚ)/ + (2:ℚ)^B≥1-δ := by + rw [padSampler_success] + exact amplifiedBitOutput_success p hz δ hd + +theorem scheduled_fair_tapes : ∃ C d : ℕ, 0(1-e)*(Z G:ℚ)≤f b ∧ f b≤(1+e)*(Z G:ℚ))).card:ℚ) / + (2:ℚ)^(timeBound C d G e δ)≥1-δ) := by + obtain ⟨C,d,h⟩:=polynomial_fair_bits + refine ⟨C+1,d,by omega,fun G _ hn hev e δ he he1 hs=>?_⟩ + let p:=parameters G hn hev e he he1 + have ht : amplifiedBits p δ ≤ timeBound (C+1) d G e δ := by + exact (h G hn hev e δ he he1 hs).trans (Nat.mul_le_mul_right _ (by omega)) + let f:=padSampler ht (amplifiedBitOutput p δ) + refine ⟨f,fun b=>amplifiedBitOutput_nonneg p δ _,fun hz hd=>?_⟩ + convert padded_amplified_success p δ _ ht hz hd using 3 + congr 1 + ext b + simp only [mem_filter,mem_univ,true_and] + rfl +end MatchingFPRAS.FiniteTrial + +end OAI diff --git a/lean/OAI/Combinatorics/MatchingCount/Algorithm/RationalCounts.lean b/lean/OAI/Combinatorics/MatchingCount/Algorithm/RationalCounts.lean new file mode 100644 index 0000000000000000000000000000000000000000..27fb7bd4218b347d68aa4cc895e47ed71bb95540 --- /dev/null +++ b/lean/OAI/Combinatorics/MatchingCount/Algorithm/RationalCounts.lean @@ -0,0 +1,22 @@ +import Mathlib +import OAI.Combinatorics.MatchingCount.Algorithm.RationalEstimator + +namespace OAI + +namespace MatchingFPRAS.FiniteTrial +variable {G : GraphInput} [Nontrivial (Fin G.n)] +def sampleCount (p : Trial.Parameters G) : ℕ := + ⌈10*(Counting.sigma (sourceD (G:=G) p.K) p.K p.epsilon)⁻¹^2*((G.n:ℚ)+p.K+1)⌉₊ +omit [Nontrivial (Fin G.n)] in +lemma sampleCount_eq (p : Trial.Parameters G) : sampleCount p=p.S := by + unfold sampleCount Trial.Parameters.S Enlargement.stageSampleCount + apply Nat.ceil_congr + intro s + unfold Trial.Parameters.D + rw [←sourceD_eq (G:=G)] + have hh:=Counting.sigma_cast (sourceD (G:=G) p.K) p.K p.epsilon + rw [←hh] + exact_mod_cast Iff.rfl +end MatchingFPRAS.FiniteTrial + +end OAI diff --git a/lean/OAI/Combinatorics/MatchingCount/Algorithm/RationalEstimator.lean b/lean/OAI/Combinatorics/MatchingCount/Algorithm/RationalEstimator.lean new file mode 100644 index 0000000000000000000000000000000000000000..20be9863a469604eddda007f287b2e1ccecfdad1 --- /dev/null +++ b/lean/OAI/Combinatorics/MatchingCount/Algorithm/RationalEstimator.lean @@ -0,0 +1,129 @@ +import Mathlib +import OAI.Combinatorics.MatchingCount.Algorithm.RationalObservables +import OAI.Combinatorics.MatchingCount.Algorithm.RationalScale + +namespace OAI + +namespace MatchingFPRAS.FiniteTrial +open Finset Enlargement Transport + +variable {V : Type*} [LinearOrder V] +def sampleAverage {Ω : Type*} {S : ℕ} (f : Ω → ℚ) (x : Fin S → Ω) : ℚ := + (∑ i,f (x i))/(S:ℚ) +lemma sampleAverage_cast {Ω : Type*} {S : ℕ} (f : Ω → ℚ) (x : Fin S → Ω) : + (sampleAverage f x:ℝ)=Enlargement.sampleAverage (fun a=>(f a:ℝ)) x := by + simp only [sampleAverage,Enlargement.sampleAverage,Rat.cast_div,Rat.cast_sum,Rat.cast_natCast] +def probeMatrix (z : LogicalEdge V → ℚ) (i j : V) : ℚ := + if hij : i=j then 0 else z (pairEdge i j hij) +lemma probeMatrix_cast (z : LogicalEdge V → ℚ) (i j : V) : + (probeMatrix z i j:ℝ)=Enlargement.probeMatrix (fun e=>(z e:ℝ)) i j := by + simp only [probeMatrix,Enlargement.probeMatrix] + split_ifs <;> norm_cast +lemma probeMatrix_symm (z : LogicalEdge V → ℚ) (i j : V) : probeMatrix z i j=probeMatrix z j i := by + apply Rat.cast_injective (α:=ℝ) + rw [probeMatrix_cast,probeMatrix_cast,Enlargement.probeMatrix_symm] +def estimateMatrix (D : ℕ) (dbar : ℚ) (zbar : LogicalEdge V → ℚ) (i j : V) : ℚ := + Counting.upperEstimate D dbar (probeMatrix zbar i j) +lemma estimateMatrix_cast (D : ℕ) (dbar : ℚ) (zbar : LogicalEdge V → ℚ) (i j : V) : + (estimateMatrix D dbar zbar i j:ℝ)=Enlargement.estimateMatrix D dbar (fun e=>(zbar e:ℝ)) i j := by + rw [estimateMatrix,Counting.upperEstimate_cast,probeMatrix_cast] + rfl +lemma estimateMatrix_symm (D : ℕ) (dbar : ℚ) (zbar : LogicalEdge V → ℚ) (i j : V) : + estimateMatrix D dbar zbar i j=estimateMatrix D dbar zbar j i := by + rw [estimateMatrix,estimateMatrix,probeMatrix_symm] +lemma estimateMatrix_bounds (D : ℕ) (dbar : ℚ) (zbar : LogicalEdge V → ℚ) (i j : V) : + Counting.alpha≤estimateMatrix D dbar zbar i j ∧ estimateMatrix D dbar zbar i j≤3 := by + unfold estimateMatrix Counting.upperEstimate + split_ifs + · exact ⟨le_max_left _ _,max_le (by norm_num [Counting.alpha]) (min_le_left _ _)⟩ + · norm_num [Counting.alpha] + +variable {G : GraphInput} {j K S : ℕ} [Nontrivial (Fin G.n)] +attribute [local instance] NumberedHierarchy.labelOrder sym2Order bagEdgeOrder bagEdgeFintype +attribute [local instance] UnitRefresh.Computable.allowedDec prodOrder sumOrder +noncomputable local instance (w : Fin G.n → Fin G.n → ℚ) (K : ℕ) : + DecidableEq (SourceLabel (fun x y=>(w x y:ℝ)) K) := Classical.decEq _ +noncomputable local instance (w : Fin G.n → Fin G.n → ℚ) (K : ℕ) : + Fintype (Transport.BagEdge (sourceBags (fun x y=>(w x y:ℝ)) K)) := Fintype.ofFinite _ + +def sourceD (K : ℕ) : ℕ := + 100*Fintype.card (SourceVertex (Fin G.n) K)^2*(100000000*(G.n+1)^4) +omit [Nontrivial (Fin G.n)] in +lemma sourceD_eq (K : ℕ) : sourceD (G:=G) K=Enlargement.sourceD (V:=Fin G.n) K := by + simp only [sourceD,Enlargement.sourceD,Fintype.card_fin] + +def ScaleState.matrix (s : ScaleState G j) (x : Fin S → RationalSource.Marked s.activity K) : + Fin G.n → Fin G.n → ℚ := + estimateMatrix (sourceD (G:=G) K) + (sampleAverage (RationalSource.observableD s.activity s.nextActivity K) x) + (fun e=>sampleAverage (RationalSource.observableProbe s.activity s.nextActivity K e) x) +lemma ScaleState.matrix_bounds (s : ScaleState G j) (x : Fin S → RationalSource.Marked s.activity K) (a b : Fin G.n) : + Counting.alpha ≤ s.matrix x a b ∧ s.matrix x a b≤3 := estimateMatrix_bounds _ _ _ _ _ +lemma ScaleState.matrix_symm (s : ScaleState G j) (x : Fin S → RationalSource.Marked s.activity K) (a b : Fin G.n) : + s.matrix x a b=s.matrix x b a := estimateMatrix_symm _ _ _ _ _ +def ScaleState.updateVector (hn : 2≤G.n) (s : ScaleState G j) + (x : Fin S → RationalSource.Marked s.activity K) : Fin G.n → ℚ := + Counting.scalingTrace hn (s.matrix x) G.n +lemma ScaleState.updateVector_bounds (hn : 2≤G.n) (s : ScaleState G j) + (x : Fin S → RationalSource.Marked s.activity K) (i : Fin G.n) : + 0s.matrix_bounds x a b) G.n).1 + exact ⟨h.pos i,h.upper i⟩ +def ScaleState.update (hn : 2≤G.n) (s : ScaleState G j) + (x : Fin S → RationalSource.Marked s.activity K) : ScaleState G (j+1) where + scale i:=s.scale i*s.updateVector hn x i + positive i:=mul_pos (s.positive i) (s.updateVector_bounds hn x i).1 + upper i:=by + rw [pow_succ] + exact mul_le_mul (s.upper i) (s.updateVector_bounds hn x i).2 (s.updateVector_bounds hn x i).1.le (by positivity) +lemma ScaleState.update_activity (hn : 2≤G.n) (s : ScaleState G j) + (x : Fin S → RationalSource.Marked s.activity K) : + (s.update hn x).activity=(fun a b=>s.nextActivity a b*s.updateVector hn x a*s.updateVector hn x b) := by + funext a b + simp only [ScaleState.activity,ScaleState.update,ScaleState.nextActivity] + ring + +def ScaleState.ratioEstimate (s : ScaleState G j) (x : Fin S → RationalSource.Marked s.activity K) : ℚ := + Counting.ratioEstimate (sampleAverage (RationalSource.observableA s.activity K) x) + (sampleAverage (RationalSource.observableD s.activity s.nextActivity K) x) + +lemma average_A (w : Fin G.n → Fin G.n → ℚ) (K : ℕ) + (x : Fin S → SourceMarked (fun a b=>(w a b:ℝ)) K) : + (sampleAverage (RationalSource.observableA w K) (RationalSource.sourceMarkedEquiv w K ∘ x):ℝ)= + Enlargement.sampleAverage (Enlargement.observableA (fun a b=>(w a b:ℝ)) K) x := by + simp only [sampleAverage,Enlargement.sampleAverage,Rat.cast_div,Rat.cast_sum,Rat.cast_natCast,Function.comp_apply, + RationalSource.observableA_cast] +lemma average_D (w w₁ : Fin G.n → Fin G.n → ℚ) (K : ℕ) + (x : Fin S → SourceMarked (fun a b=>(w a b:ℝ)) K) : + (sampleAverage (RationalSource.observableD w w₁ K) (RationalSource.sourceMarkedEquiv w K ∘ x):ℝ)= + Enlargement.sampleAverage (Enlargement.observableD (fun a b=>(w a b:ℝ)) (fun a b=>(w₁ a b:ℝ)) K) x := by + simp only [sampleAverage,Enlargement.sampleAverage,Rat.cast_div,Rat.cast_sum,Rat.cast_natCast,Function.comp_apply, + RationalSource.observableD_cast] +lemma average_Probe (w w₁ : Fin G.n → Fin G.n → ℚ) (K : ℕ) (e : LogicalEdge (Fin G.n)) + (x : Fin S → SourceMarked (fun a b=>(w a b:ℝ)) K) : + (sampleAverage (RationalSource.observableProbe w w₁ K e) (RationalSource.sourceMarkedEquiv w K ∘ x):ℝ)= + Enlargement.sampleAverage (Enlargement.observableProbe (fun a b=>(w a b:ℝ)) (fun a b=>(w₁ a b:ℝ)) K e) x := by + simp only [sampleAverage,Enlargement.sampleAverage,Rat.cast_div,Rat.cast_sum,Rat.cast_natCast,Function.comp_apply, + RationalSource.observableProbe_cast] +lemma ScaleState.matrix_cast (s : ScaleState G j) + (x : Fin S → SourceMarked (fun a b=>(s.activity a b:ℝ)) K) : + (fun a b=>(s.matrix (RationalSource.sourceMarkedEquiv s.activity K ∘ x) a b:ℝ))= + Enlargement.estimateMatrix (sourceD (G:=G) K) + (Enlargement.sampleAverage (Enlargement.observableD (fun a b=>(s.activity a b:ℝ)) + (fun a b=>(s.nextActivity a b:ℝ)) K) x) + (fun e=>Enlargement.sampleAverage (Enlargement.observableProbe (fun a b=>(s.activity a b:ℝ)) + (fun a b=>(s.nextActivity a b:ℝ)) K e) x) := by + funext a b + simp only [ScaleState.matrix,estimateMatrix_cast,average_D,average_Probe] +lemma ScaleState.ratioEstimate_cast (s : ScaleState G j) + (x : Fin S → SourceMarked (fun a b=>(s.activity a b:ℝ)) K) : + (s.ratioEstimate (RationalSource.sourceMarkedEquiv s.activity K ∘ x):ℝ)= + RealStage.ratioEstimate + (Enlargement.sampleAverage (Enlargement.observableA (fun a b=>(s.activity a b:ℝ)) K) x) + (Enlargement.sampleAverage (Enlargement.observableD (fun a b=>(s.activity a b:ℝ)) + (fun a b=>(s.nextActivity a b:ℝ)) K) x) := by + simp only [ScaleState.ratioEstimate,Counting.ratioEstimate_cast,average_A,average_D] +end MatchingFPRAS.FiniteTrial + +end OAI diff --git a/lean/OAI/Combinatorics/MatchingCount/Algorithm/RationalObservables.lean b/lean/OAI/Combinatorics/MatchingCount/Algorithm/RationalObservables.lean new file mode 100644 index 0000000000000000000000000000000000000000..19961f559e6602d7f042e1ee11daa3f346bbe6f2 --- /dev/null +++ b/lean/OAI/Combinatorics/MatchingCount/Algorithm/RationalObservables.lean @@ -0,0 +1,191 @@ +import Mathlib +import OAI.Combinatorics.MatchingCount.Sampling.MarkBridge + +namespace OAI + +namespace MatchingFPRAS.RationalSource +open Finset Transport Variation Enlargement + +variable {V : Type*} [Fintype V] [LinearOrder V] [Nontrivial V] +attribute [local instance] NumberedHierarchy.labelOrder sym2Order bagEdgeOrder bagEdgeFintype +attribute [local instance] UnitRefresh.Computable.allowedDec prodOrder sumOrder +noncomputable local instance (w : V → V → ℚ) (K : ℕ) : + DecidableEq (SourceLabel (fun x y=>(w x y:ℝ)) K) := Classical.decEq _ +noncomputable local instance (w : V → V → ℚ) (K : ℕ) : + Fintype (BagEdge (sourceBags (fun x y=>(w x y:ℝ)) K)) := Fintype.ofFinite _ + +def rawReweight (w w₁ : V → V → ℚ) (K : ℕ) (e : SourceRealEdge V K) : ℚ := + if e.2.val=2*(2*K+2) then BottleneckAlgorithm.edge w₁ (source e.1) (target e.1)/ + BottleneckAlgorithm.edge w (source e.1) (target e.1) else 1 + +def bagReweight (w w₁ : V → V → ℚ) (K : ℕ) (e : BagEdge (bags w K)) : ℚ := + 1+∑ q : SourceRealEdge V K,if coloredReal w K q=e then rawReweight w w₁ K q-1 else 0 +lemma bagReweight_on (w w₁ : V → V → ℚ) (K : ℕ) (q : SourceRealEdge V K) : + bagReweight w w₁ K (coloredReal w K q)=rawReweight w w₁ K q := by + simp only [bagReweight,(coloredReal_injective w K).eq_iff,sum_ite_eq',mem_univ,ite_true] + ring +lemma bagReweight_off (w w₁ : V → V → ℚ) (K : ℕ) (e : BagEdge (bags w K)) + (he : ¬∃ q,coloredReal w K q=e) : bagReweight w w₁ K e=1 := by + have hz : (∑ q : SourceRealEdge V K,if coloredReal w K q=e then rawReweight w w₁ K q-1 else 0)=0 := by + apply sum_eq_zero + intro q _ + exact ite_eq_right (fun h=>he ⟨q,h⟩) + rw [bagReweight,hz,add_zero] +omit [Fintype V] [Nontrivial V] in +lemma rawReweight_cast (w w₁ : V → V → ℚ) (K : ℕ) (q : SourceRealEdge V K) : + (rawReweight w w₁ K q:ℝ)=Enlargement.rawReweight (fun x y=>(w x y:ℝ)) + (fun x y=>(w₁ x y:ℝ)) K q := by + simp only [rawReweight,Enlargement.rawReweight] + split_ifs + · simp only [Rat.cast_div,BottleneckAlgorithm.edge,logicalActivity,Switching.edgeActivity] + split_ifs <;> rfl + · norm_cast +lemma bagReweight_cast (w w₁ : V → V → ℚ) (K : ℕ) + (e : BagEdge (sourceBags (fun x y=>(w x y:ℝ)) K)) : + (bagReweight w w₁ K (sourceEdgeEquiv w K e):ℝ)= + Enlargement.bagReweight (fun x y=>(w x y:ℝ)) (fun x y=>(w₁ x y:ℝ)) K e := by + classical + by_cases he : ∃ q,sourceColoredReal (fun x y=>(w x y:ℝ)) K q=e + · obtain ⟨q,rfl⟩:=he + rw [sourceEdgeEquiv_real,bagReweight_on] + exact (rawReweight_cast w w₁ K q).trans (Enlargement.bagReweight_on _ _ K q).symm + · rw [bagReweight_off w w₁ K _ ?_] + · unfold Enlargement.bagReweight + change ¬∃ q,sourceRealEmbedding (fun x y=>(w x y:ℝ)) K q=e at he + rw [dite_eq_right he] + norm_cast + · rintro ⟨q,hq⟩ + apply he + refine ⟨q,(sourceEdgeEquiv w K).injective ?_⟩ + rwa [sourceEdgeEquiv_real] + +def observableA (w : V → V → ℚ) (K : ℕ) (a : Marked w K) : ℚ := + if a.2=(fun _=>0) then 1 else 0 + +def observableD (w w₁ : V → V → ℚ) (K : ℕ) (a : Marked w K) : ℚ := + if a.2=(fun _=>0) then ∏ e ∈ a.1.val,bagReweight w w₁ K e else 0 + +def observableProbe (w w₁ : V → V → ℚ) (K : ℕ) (e₀ : LogicalEdge V) (a : Marked w K) : ℚ := + if {centralEdge w K e₀}⊆a.1.val ∧ + a.2=(fun e=>if e.val∈({centralEdge w K e₀}:Finset _) then 2 else 0) + then ∏ e ∈ a.1.val \ {centralEdge w K e₀},bagReweight w w₁ K e else 0 +end MatchingFPRAS.RationalSource +namespace MatchingFPRAS.Transport +open Finset + +variable {V E F I : Type*} [Fintype V] [DecidableEq V] +variable [Fintype E] [DecidableEq E] [Fintype F] [DecidableEq F] [Fintype I] +variable {inc : E → V → Prop} {j : F → V → Prop} +omit [DecidableEq V] [Fintype E] [Fintype F] [Fintype I] in +lemma markedEquiv_marks_eq (e : E ≃ F) (he : ∀ a v,j (e a) v ↔ inc a v) + (a : Marking.Marked (I:=I) inc) (r : F → I) : + (markedEquiv e he a).2=(fun x=>r x.val) ↔ a.2=(fun x=>r (e x.val)) := by + constructor + · intro h + funext x + have hh:=congrFun h (selectedEquiv e he a.1 x) + rw [markedEquiv_mark] at hh + exact hh + · intro h + funext x + obtain ⟨y,rfl⟩:=(selectedEquiv e he a.1).surjective x + rw [markedEquiv_mark,congrFun h] + rfl +omit [DecidableEq V] [Fintype E] [Fintype F] in +lemma markedEquiv_zero (e : E ≃ F) (he : ∀ a v,j (e a) v ↔ inc a v) + (a : Marking.Marked (I:=Fin 3) inc) : + (markedEquiv e he a).2=(fun _=>0) ↔ a.2=(fun _=>0) := + markedEquiv_marks_eq e he a (fun _=>0) +omit [DecidableEq V] [Fintype E] [Fintype F] in +lemma markedEquiv_probe (e : E ≃ F) (he : ∀ a v,j (e a) v ↔ inc a v) + (a : Marking.Marked (I:=Fin 3) inc) (u : E) : + ({e u}⊆(markedEquiv e he a).1.val ∧ + (markedEquiv e he a).2=(fun x=>if x.val∈({e u}:Finset _) then 2 else 0)) ↔ + ({u}⊆a.1.val ∧ a.2=(fun x=>if x.val∈({u}:Finset _) then 2 else 0)) := by + rw [markedEquiv_marks_eq e he a (fun x=>if x∈({e u}:Finset F) then 2 else 0)] + rw [singleton_subset_iff,singleton_subset_iff] + change (e u∈a.1.val.image e ∧ _) ↔ (u∈a.1.val ∧ _) + simp only [mem_singleton,e.injective.eq_iff, + mem_image,exists_eq_right] +omit [DecidableEq V] [Fintype E] [Fintype F] in +lemma pmEquiv_product_erase {R : Type*} [CommMonoid R] + (e : E ≃ F) (he : ∀ a v,j (e a) v ↔ inc a v) (M : PM inc) (u : E) (f : F → R) : + (∏ x ∈ (pmEquiv e he M).val \ {e u},f x)=∏ x ∈ M.val \ {u},f (e x) := by + have hh : (pmEquiv e he M).val \ {e u}=(M.val \ {u}).image e := by + change M.val.image e \ {e u}=(M.val \ {u}).image e + ext x + simp only [mem_sdiff,mem_image,mem_singleton] + constructor + · rintro ⟨⟨y,hy,rfl⟩,hu⟩ + exact ⟨y,⟨hy,fun h=>hu (congrArg e h)⟩,rfl⟩ + · rintro ⟨y,⟨hy,hu⟩,rfl⟩ + exact ⟨⟨y,hy,rfl⟩,fun h=>hu (e.injective h)⟩ + rw [hh] + exact prod_image (fun _ _ _ _ h=>e.injective h) +end MatchingFPRAS.Transport +namespace MatchingFPRAS.RationalSource +open Finset Transport Variation Enlargement + +variable {V : Type*} [Fintype V] [LinearOrder V] [Nontrivial V] +attribute [local instance] NumberedHierarchy.labelOrder sym2Order bagEdgeOrder bagEdgeFintype +attribute [local instance] UnitRefresh.Computable.allowedDec prodOrder sumOrder +noncomputable local instance (w : V → V → ℚ) (K : ℕ) : + DecidableEq (SourceLabel (fun x y=>(w x y:ℝ)) K) := Classical.decEq _ +noncomputable local instance (w : V → V → ℚ) (K : ℕ) : + Fintype (BagEdge (sourceBags (fun x y=>(w x y:ℝ)) K)) := Fintype.ofFinite _ +lemma sourceEdgeEquiv_incidence (w : V → V → ℚ) (K : ℕ) + (e : BagEdge (sourceBags (fun x y=>(w x y:ℝ)) K)) (x : SourceVertex V K) : + (sourceEdgeEquiv w K e).Incident x ↔ e.Incident x := Iff.rfl +lemma sourceMarkedEquiv_zero (w : V → V → ℚ) (K : ℕ) + (a : SourceMarked (fun x y=>(w x y:ℝ)) K) : + (sourceMarkedEquiv w K a).2=(fun _=>0) ↔ a.2=(fun _=>0) := + markedEquiv_zero (inc:=BagEdge.Incident (bags:=sourceBags (fun x y=>(w x y:ℝ)) K)) + (j:=BagEdge.Incident (bags:=bags w K)) (sourceEdgeEquiv w K) (sourceEdgeEquiv_incidence w K) a +lemma observableA_cast (w : V → V → ℚ) (K : ℕ) + (a : SourceMarked (fun x y=>(w x y:ℝ)) K) : + (observableA w K (sourceMarkedEquiv w K a):ℝ)=Enlargement.observableA (fun x y=>(w x y:ℝ)) K a := by + simp only [observableA,Enlargement.observableA,sourceMarkedEquiv_zero] + split_ifs <;> norm_cast +lemma observableD_cast (w w₁ : V → V → ℚ) (K : ℕ) + (a : SourceMarked (fun x y=>(w x y:ℝ)) K) : + (observableD w w₁ K (sourceMarkedEquiv w K a):ℝ)= + Enlargement.observableD (fun x y=>(w x y:ℝ)) (fun x y=>(w₁ x y:ℝ)) K a := by + simp only [observableD,Enlargement.observableD,sourceMarkedEquiv_zero] + split_ifs + · push_cast + change matchingWeight (fun e=>(bagReweight w w₁ K e:ℝ)) + (pmEquiv (inc:=BagEdge.Incident (bags:=sourceBags (fun x y=>(w x y:ℝ)) K)) + (j:=BagEdge.Incident (bags:=bags w K)) (sourceEdgeEquiv w K) (sourceEdgeEquiv_incidence w K) a.1)=_ + rw [matchingWeight_pmEquiv (sourceEdgeEquiv w K) (sourceEdgeEquiv_incidence w K)] + unfold matchingWeight + apply prod_congr rfl + intro e _ + exact bagReweight_cast w w₁ K e + · norm_cast +lemma observableProbe_cast (w w₁ : V → V → ℚ) (K : ℕ) (u : LogicalEdge V) + (a : SourceMarked (fun x y=>(w x y:ℝ)) K) : + (observableProbe w w₁ K u (sourceMarkedEquiv w K a):ℝ)= + Enlargement.observableProbe (fun x y=>(w x y:ℝ)) (fun x y=>(w₁ x y:ℝ)) K u a := by + have hh:=markedEquiv_probe (inc:=BagEdge.Incident (bags:=sourceBags (fun x y=>(w x y:ℝ)) K)) + (j:=BagEdge.Incident (bags:=bags w K)) (sourceEdgeEquiv w K) (sourceEdgeEquiv_incidence w K) a + (Enlargement.centralEdge (fun x y=>(w x y:ℝ)) K u) + rw [sourceEdgeEquiv_central] at hh + change ({centralEdge w K u}⊆(sourceMarkedEquiv w K a).1.val ∧ + (sourceMarkedEquiv w K a).2=(fun e=>if e.val∈({centralEdge w K u}:Finset _) then 2 else 0)) ↔ _ at hh + simp only [observableProbe,Enlargement.observableProbe,hh] + simp only [mem_singleton] at hh ⊢ + split_ifs <;> try contradiction + · push_cast + rw [←sourceEdgeEquiv_central w K u] + change (∏ e ∈ (pmEquiv (inc:=BagEdge.Incident (bags:=sourceBags (fun x y=>(w x y:ℝ)) K)) + (j:=BagEdge.Incident (bags:=bags w K)) (sourceEdgeEquiv w K) (sourceEdgeEquiv_incidence w K) a.1).val \ + {sourceEdgeEquiv w K (Enlargement.centralEdge (fun x y=>(w x y:ℝ)) K u)}, + (bagReweight w w₁ K e:ℝ))=_ + rw [pmEquiv_product_erase (sourceEdgeEquiv w K) (sourceEdgeEquiv_incidence w K)] + refine prod_congr (by ext; simp) ?_ + intro e _ + exact bagReweight_cast w w₁ K e + · norm_cast +end MatchingFPRAS.RationalSource + +end OAI diff --git a/lean/OAI/Combinatorics/MatchingCount/Algorithm/RationalScale.lean b/lean/OAI/Combinatorics/MatchingCount/Algorithm/RationalScale.lean new file mode 100644 index 0000000000000000000000000000000000000000..ca8a51cc97fb7d943ef9034a7e310d8ba7c9fbc8 --- /dev/null +++ b/lean/OAI/Combinatorics/MatchingCount/Algorithm/RationalScale.lean @@ -0,0 +1,113 @@ +import Mathlib +import OAI.Combinatorics.MatchingCount.Sampling.Endpoints +import OAI.Combinatorics.MatchingCount.Tapes.RunBits + +namespace OAI + +namespace MatchingFPRAS.Counting +open Finset + +variable {n : ℕ} +lemma rowMaximum_cast (hn : 2≤n) (G : Fin n → Fin n → ℚ) (v : Fin n → ℚ) (i : Fin n) : + (rowMaximum hn G v i:ℝ)=RealStage.rowMaximum hn (fun i j=>(G i j:ℝ)) (fun i=>(v i:ℝ)) i := by + unfold rowMaximum RealStage.rowMaximum + rw [Finset.apply_sup'_eq_sup'_comp _ (fun q : ℚ=>(q:ℝ)) (by intro a b; exact Rat.cast_max a b)] + simp only [Function.comp_apply,Rat.cast_div] +lemma scaleUpdate_cast (hn : 2≤n) (G : Fin n → Fin n → ℚ) (v : Fin n → ℚ) (i j : Fin n) : + (scaleUpdate hn G v i j:ℝ)=RealStage.scaleUpdate hn (fun i j=>(G i j:ℝ)) (fun i=>(v i:ℝ)) i j := by + by_cases h : j=i + · subst j + simp only [scaleUpdate,RealStage.scaleUpdate,Function.update_self,rowMaximum_cast] + · simp only [scaleUpdate,RealStage.scaleUpdate,Function.update_of_ne h] +lemma scalingTrace_cast (hn : 2≤n) (G : Fin n → Fin n → ℚ) (k : ℕ) (i : Fin n) : + (scalingTrace hn G k i:ℝ)=RealStage.scalingTrace hn (fun i j=>(G i j:ℝ)) k i := by + induction k generalizing i with + | zero => norm_num [scalingTrace,RealStage.scalingTrace] + | succ k ih => + simp only [scalingTrace,RealStage.scalingTrace] + split_ifs with h + · rw [scaleUpdate_cast] + have hi : (fun j=>(Counting.scalingTrace hn G k j:ℝ))=RealStage.scalingTrace hn (fun i j=>(G i j:ℝ)) k := by + funext j + exact ih j + rw [hi] + · exact ih i +lemma ratioEstimate_cast (a d : ℚ) : + (ratioEstimate a d:ℝ)=RealStage.ratioEstimate a d := by + simp only [ratioEstimate,RealStage.ratioEstimate] + have hp : (0:ℝ) push_cast <;> rfl +lemma upperEstimate_cast (D : ℕ) (d z : ℚ) : + (upperEstimate D d z:ℝ)=RealStage.upperEstimate D d z := by + simp only [upperEstimate,RealStage.upperEstimate] + have hp : (0:ℝ) push_cast <;> norm_num [alpha,RealStage.alpha] +lemma sigma_cast (D K : ℕ) (e : ℚ) : (sigma D K e:ℝ)=RealStage.sigma D K e := by + simp only [sigma,RealStage.sigma,alpha,RealStage.alpha] + push_cast + rfl +end MatchingFPRAS.Counting +namespace MatchingFPRAS.FiniteTrial +open Finset + +def cooling (n : ℕ) : ℚ := (1+1/(n:ℚ))⁻¹ +lemma cooling_cast (n : ℕ) : (cooling n:ℝ)=Trial.cooling n := by + simp [cooling,Trial.cooling] + +def raw (G : GraphInput) (j : ℕ) (a b : Fin G.n) : ℚ := + if (min a b,max a b)∈G.edges then 1 else cooling G.n^j +lemma raw_cast (G : GraphInput) (j : ℕ) (a b : Fin G.n) : + (raw G j a b:ℝ)=Trial.raw G j a b := by + unfold raw Trial.raw GraphBridge.rawActivity + split_ifs <;> simp [cooling_cast] + +structure ScaleState (G : GraphInput) (j : ℕ) where + scale : Fin G.n → ℚ + positive : ∀ i,0raw G j a b*s.scale a*s.scale b + +def ScaleState.nextActivity {G : GraphInput} {j : ℕ} (s : ScaleState G j) : Fin G.n → Fin G.n → ℚ := + fun a b=>raw G (j+1) a b*s.scale a*s.scale b +lemma ScaleState.activity_cast {G : GraphInput} {j : ℕ} (s : ScaleState G j) : + (fun a b=>(s.activity a b:ℝ))=s.toReal.activity := by + funext a b + simp only [ScaleState.activity,Trial.ScaleState.activity,Rat.cast_mul,raw_cast,ScaleState.toReal] +lemma ScaleState.nextActivity_cast {G : GraphInput} {j : ℕ} (s : ScaleState G j) : + (fun a b=>(s.nextActivity a b:ℝ))=s.toReal.nextActivity := by + funext a b + simp only [ScaleState.nextActivity,Trial.ScaleState.nextActivity,Rat.cast_mul,raw_cast,ScaleState.toReal] +lemma ScaleState.activity_pos {G : GraphInput} {j : ℕ} (s : ScaleState G j) (a b : Fin G.n) : + 0 simp only at hh <;> omega + +def orderedMate (he : Even n) : Mate (Fin n) := ⟨pairIndex he,pairIndex_involutive he⟩ +lemma orderedMate_holes (he : Even n) : HasHoles (orderedMate he) ∅ := by + intro i + simp only [Finset.notMem_empty,iff_false] + exact pairIndex_ne he i + +def selectMate (m : Mate (Fin n)) (e : LogicalEdge (Fin n)) : Bool := + decide (m.val (source e)=target e) +lemma selectMate_eq (m : Mate (Fin n)) : selectMate m=Representation.select m := by + funext e + exact rfl + +def startSet (K : ℕ) (he : Even n) : Finset (SourceRealEdge (Fin n) K) := + univ.filter fun q=>alternating (selectMate (orderedMate he) q.1) q.2.val=true +variable [Nontrivial (Fin n)] +lemma startSet_matching (K : ℕ) (he : Even n) : + MatchingOn (fun (q : SourceRealEdge (Fin n) K) x=>x∈edge source target (4*(2*K+2)) q.1 q.2) + (startSet K he) univ := by + have h:= (family_iff_matching source target (4*(2*K+2)) source_ne_target ∅ (fun _=>∅) + (fun e i=>alternating (Representation.select (orderedMate he) e) i.val)).mp + (intact_family (2*K+2) (orderedMate he) (orderedMate_holes he)) + rw [survivors_empty] at h + convert h using 1 + unfold startSet selectedSet + rw [selectMate_eq] + +attribute [local instance] NumberedHierarchy.labelOrder sym2Order bagEdgeOrder bagEdgeFintype +attribute [local instance] UnitRefresh.Computable.allowedDec prodOrder sumOrder + +def startMatching (w : Fin n → Fin n → ℚ) (K : ℕ) (he : Even n) : BagPM (bags w K) := + ⟨(startSet K he).map ⟨coloredReal w K,coloredReal_injective w K⟩,by + exact (matching_map_iff + (fun (q : SourceRealEdge (Fin n) K) x=>x∈edge source target (4*(2*K+2)) q.1 q.2) + BagEdge.Incident ⟨coloredReal w K,coloredReal_injective w K⟩ + (fun _ _=>Iff.rfl) (startSet K he) univ).mpr (startSet_matching K he)⟩ +end MatchingFPRAS.RationalSource + +end OAI diff --git a/lean/OAI/Combinatorics/MatchingCount/Algorithm/RationalUpdate.lean b/lean/OAI/Combinatorics/MatchingCount/Algorithm/RationalUpdate.lean new file mode 100644 index 0000000000000000000000000000000000000000..3ee3468fa4b4f18890d69f3fc36df4a166cd3dec --- /dev/null +++ b/lean/OAI/Combinatorics/MatchingCount/Algorithm/RationalUpdate.lean @@ -0,0 +1,103 @@ +import Mathlib +import OAI.Combinatorics.MatchingCount.Algorithm.RationalEstimator + +namespace OAI + +namespace MatchingFPRAS.FiniteTrial +open Finset Enlargement Transport Switching + +variable {G : GraphInput} {j K S : ℕ} [Nontrivial (Fin G.n)] +attribute [local instance] NumberedHierarchy.labelOrder sym2Order bagEdgeOrder bagEdgeFintype +attribute [local instance] UnitRefresh.Computable.allowedDec prodOrder sumOrder +noncomputable local instance (w : Fin G.n → Fin G.n → ℚ) (K : ℕ) : + DecidableEq (SourceLabel (fun x y=>(w x y:ℝ)) K) := Classical.decEq _ +noncomputable local instance (w : Fin G.n → Fin G.n → ℚ) (K : ℕ) : + Fintype (BagEdge (sourceBags (fun x y=>(w x y:ℝ)) K)) := Fintype.ofFinite _ +def ScaleState.Balanced (hn : 2≤G.n) (s : ScaleState G j) : Prop := s.toReal.Balanced hn +omit [Nontrivial (Fin G.n)] in +lemma initial_balanced (hn : 2≤G.n) (he : Even G.n) : (initialScaleState G hn).Balanced hn := + Trial.initial_balanced G hn he +noncomputable def stageData (p : Trial.Parameters G) (hj : j≤p.K) (s : ScaleState G j) + (hs : s.Balanced p.hn) : StageData G.n p.K p.K where + hn:=p.hn + w a b:=(s.activity a b:ℝ) + next a b:=(s.nextActivity a b:ℝ) + positive a b:=by exact_mod_cast s.activity_pos a b + next_positive a b:=by exact_mod_cast s.nextActivity_pos a b + partition_positive:=by rw [s.activity_cast]; exact s.toReal.partition_pos p.even + lower:=by rw [s.activity_cast]; exact hs.1 + upper:=by rw [s.activity_cast]; exact hs.2 + cool_lower a b _:=by + have h:=(s.toReal.cooling a b).1 + rw [←s.activity_cast,←s.nextActivity_cast] at h + exact h + cool_upper a b _:=by + have h:=(s.toReal.cooling a b).2 + rw [←s.activity_cast,←s.nextActivity_cast] at h + exact h + cap:=by rw [s.activity_cast]; exact s.toReal.cap hj + stages:=p.K_pos + epsilon:=p.epsilon + epsilon_positive:=p.epsilon_real_pos + epsilon_lt_one:=p.epsilon_real_lt_one + +theorem successful_update (p : Trial.Parameters G) (hj : j≤p.K) (s : ScaleState G j) + (hs : s.Balanced p.hn) (x : Fin S → SourceMarked (fun a b=>(s.activity a b:ℝ)) p.K) + (hx : StageGood (fun a b=>(s.activity a b:ℝ)) (fun a b=>(s.nextActivity a b:ℝ)) p.K p.sigma x) : + (s.update p.hn (RationalSource.sourceMarkedEquiv s.activity p.K ∘ x)).Balanced p.hn ∧ + |(s.ratioEstimate (RationalSource.sourceMarkedEquiv s.activity p.K ∘ x):ℝ)/ + (partition (Trial.raw G (j+1)) ∅/partition (Trial.raw G j) ∅)-1|≤(p.epsilon:ℝ)/(100*p.K) := by + let c:=stageData p hj s hs + let obs : EmpiricalData c:=empiricalData c x hx + have hh:=actual_successful_stage c obs + dsimp only at hh + let y:=RationalSource.sourceMarkedEquiv s.activity p.K ∘ x + have hm : (fun a b=>(s.matrix y a b:ℝ))=Enlargement.estimateMatrix (Enlargement.sourceD (V:=Fin G.n) p.K) obs.dbar obs.zbar := by + rw [s.matrix_cast,sourceD_eq] + rfl + have hv : (fun i=>(s.updateVector p.hn y i:ℝ))= + RealStage.scalingTrace c.hn (Enlargement.estimateMatrix (Enlargement.sourceD (V:=Fin G.n) p.K) obs.dbar obs.zbar) G.n := by + funext i + rw [ScaleState.updateVector,Counting.scalingTrace_cast,hm] + constructor + · unfold ScaleState.Balanced Trial.ScaleState.Balanced + rw [←ScaleState.activity_cast,ScaleState.update_activity] + have ha : (fun a b=>((s.nextActivity a b*s.updateVector p.hn y a*s.updateVector p.hn y b:ℚ):ℝ))= + (fun a b=>c.next a b*(RealStage.scalingTrace c.hn (Enlargement.estimateMatrix + (Enlargement.sourceD (V:=Fin G.n) p.K) obs.dbar obs.zbar) G.n a)* + (RealStage.scalingTrace c.hn (Enlargement.estimateMatrix + (Enlargement.sourceD (V:=Fin G.n) p.K) obs.dbar obs.zbar) G.n b)) := by + funext a z + simp only [Rat.cast_mul,congrFun hv] + rfl + rw [ha] + exact ⟨fun i=>(hh.2.1 i).1,fun i=>(hh.2.1 i).2⟩ + · rw [s.ratioEstimate_cast] + have hr : partition c.next ∅/partition c.w ∅= + partition (Trial.raw G (j+1)) ∅/partition (Trial.raw G j) ∅ := by + change partition (fun a b=>(s.nextActivity a b:ℝ)) ∅/partition (fun a b=>(s.activity a b:ℝ)) ∅=_ + rw [s.nextActivity_cast,s.activity_cast,s.toReal.ratio] + rw [←hr] + exact hh.2.2 + +lemma ScaleState.ratioEstimate_nonneg (s : ScaleState G j) + (x : Fin S → SourceMarked (fun a b=>(s.activity a b:ℝ)) K) : + 0 ≤ s.ratioEstimate (RationalSource.sourceMarkedEquiv s.activity K ∘ x) := by + have h : (0:ℝ)≤(s.ratioEstimate (RationalSource.sourceMarkedEquiv s.activity K ∘ x):ℝ) := by + rw [s.ratioEstimate_cast] + unfold RealStage.ratioEstimate + split_ifs with h + · apply div_nonneg _ h.le + unfold Enlargement.sampleAverage + apply div_nonneg _ (Nat.cast_nonneg S) + apply sum_nonneg + intro i _ + exact (observableD_range_off (fun a b=>(s.activity a b:ℝ)) (fun a b=>(s.nextActivity a b:ℝ)) + (fun a b=>by exact_mod_cast s.activity_pos a b) + (fun a b=>by exact_mod_cast (s.nextActivity_pos a b).le) + (fun a b _=>by have h:=(s.toReal.cooling a b).2; rw [←s.activity_cast,←s.nextActivity_cast] at h; exact h) K (x i)).1 + · norm_num + exact_mod_cast h +end MatchingFPRAS.FiniteTrial + +end OAI diff --git a/lean/OAI/Combinatorics/MatchingCount/Algorithm/RelabelWeights.lean b/lean/OAI/Combinatorics/MatchingCount/Algorithm/RelabelWeights.lean new file mode 100644 index 0000000000000000000000000000000000000000..36a27b11713af9592deebb09880ff71d10e9ce20 --- /dev/null +++ b/lean/OAI/Combinatorics/MatchingCount/Algorithm/RelabelWeights.lean @@ -0,0 +1,70 @@ +import Mathlib +import OAI.Combinatorics.MatchingCount.Graphs.RelabelMore + +namespace OAI + +namespace MatchingFPRAS.Enlargement +open Transport + +variable {V : Type*} [Fintype V] [LinearOrder V] [Nontrivial V] +noncomputable local instance relabelWeightsSourceLabelDecidableEq (w : V → V → ℝ) (K : ℕ) : DecidableEq (SourceLabel w K) := Classical.decEq _ +noncomputable local instance relabelWeightsSourceBagEdgeFintype (w : V → V → ℝ) (K : ℕ) : Fintype (BagEdge (sourceBags w K)) := Fintype.ofFinite _ +lemma realPortion_on (w : V → V → ℝ) (K : ℕ) (q : SourceRealEdge V K) : + sourceRealPortion w K (sourceColoredReal w K q)=sourceRealActivity w K q := by + classical + exact edgeExtension_on (sourceRealEmbedding w K) (sourceRealActivity w K) q +lemma realPortion_off (w : V → V → ℝ) (K : ℕ) (e : BagEdge (sourceBags w K)) + (he : ¬∃ q,sourceColoredReal w K q=e) : sourceRealPortion w K e=0 := by + classical + exact edgeExtension_off (sourceRealEmbedding w K) (sourceRealActivity w K) e he +end MatchingFPRAS.Enlargement +namespace MatchingFPRAS.RationalSource +open MatchingFPRAS Transport Enlargement Finset + +variable {V : Type*} [Fintype V] [LinearOrder V] [Nontrivial V] +attribute [local instance] NumberedHierarchy.labelOrder sym2Order bagEdgeOrder bagEdgeFintype +attribute [local instance] UnitRefresh.Computable.allowedDec prodOrder sumOrder +noncomputable local instance (w : V → V → ℚ) (K : ℕ) : + DecidableEq (SourceLabel (fun x y=>(w x y:ℝ)) K) := Classical.decEq _ +noncomputable local instance (w : V → V → ℚ) (K : ℕ) : + Fintype (BagEdge (sourceBags (fun x y=>(w x y:ℝ)) K)) := Fintype.ofFinite _ +noncomputable def sourceEdgeEquiv (w : V → V → ℚ) (K : ℕ) : + BagEdge (sourceBags (fun x y=>(w x y:ℝ)) K) ≃ BagEdge (bags w K) := + relabelEdgeEquiv (labelsEquiv w K) (source_bags_equiv w K) +lemma sourceEdgeEquiv_real (w : V → V → ℚ) (K : ℕ) (q : SourceRealEdge V K) : + sourceEdgeEquiv w K (sourceColoredReal (fun x y=>(w x y:ℝ)) K q)=coloredReal w K q := by + apply Subtype.ext + apply Subtype.ext + apply Prod.ext + · rfl + · exact labelsEquiv_edgeLabel w K q +lemma sourceEdgeEquiv_color (w : V → V → ℚ) (K : ℕ) + (e : BagEdge (sourceBags (fun x y=>(w x y:ℝ)) K)) : + (sourceEdgeEquiv w K e).color=labelsEquiv w K e.color := rfl +lemma bagHeight_cast (w : V → V → ℚ) (K : ℕ) (l : SourceLabel (fun x y=>(w x y:ℝ)) K) : + (bagHeight w K (labelsEquiv w K l):ℝ)=Enlargement.bagHeight (fun x y=>(w x y:ℝ)) K l := by + simp only [bagHeight,Enlargement.bagHeight,labelsEquiv_level] + norm_cast +lemma realPortion_cast (w : V → V → ℚ) (K : ℕ) + (e : BagEdge (sourceBags (fun x y=>(w x y:ℝ)) K)) : + (realPortion w K (sourceEdgeEquiv w K e):ℝ)=sourceRealPortion (fun x y=>(w x y:ℝ)) K e := by + classical + by_cases he : ∃ q,sourceColoredReal (fun x y=>(w x y:ℝ)) K q=e + · obtain ⟨q,rfl⟩:=he + rw [sourceEdgeEquiv_real,realPortion_on,Enlargement.realPortion_on] + exact pathActivity_cast w K q.1 q.2 + · rw [realPortion_off w K _ ?_,Enlargement.realPortion_off _ _ _ he] + norm_num + rintro ⟨q,hq⟩ + apply he + refine ⟨q,(sourceEdgeEquiv w K).injective ?_⟩ + rwa [sourceEdgeEquiv_real] +lemma bagWeight_cast (w : V → V → ℚ) (K D : ℕ) + (e : BagEdge (sourceBags (fun x y=>(w x y:ℝ)) K)) : + (bagWeight w K D (sourceEdgeEquiv w K e):ℝ)=sourceBagWeight (fun x y=>(w x y:ℝ)) K D e := by + simp only [bagWeight,Rat.cast_add,Rat.cast_div,Rat.cast_natCast,realPortion_cast, + sourceEdgeEquiv_color,bagHeight_cast,sourceBagWeight] + rfl +end MatchingFPRAS.RationalSource + +end OAI diff --git a/lean/OAI/Combinatorics/MatchingCount/Algorithm/SortedList.lean b/lean/OAI/Combinatorics/MatchingCount/Algorithm/SortedList.lean new file mode 100644 index 0000000000000000000000000000000000000000..071c611fa1bf46fe0197a4fc31328cc9cd3be943 --- /dev/null +++ b/lean/OAI/Combinatorics/MatchingCount/Algorithm/SortedList.lean @@ -0,0 +1,452 @@ +import Mathlib +import OAI.Combinatorics.MatchingCount.Algorithm.FiniteTrial + +namespace OAI + +namespace MatchingFPRAS.Amplification +open Finset + +variable {k : ℕ} + +def sortedList (x : Fin (2*k+1) → ℚ) : List ℚ := + (List.ofFn x).mergeSort (· ≤ ·) + +lemma sortedList_length (x : Fin (2*k+1) → ℚ) : (sortedList x).length=2*k+1 := by + simp [sortedList] + +def sortedValue (x : Fin (2*k+1) → ℚ) (i : Fin (2*k+1)) : ℚ := + (sortedList x)[i.val]'(by rw [sortedList_length]; exact i.isLt) + +def median (x : Fin (2*k+1) → ℚ) : ℚ := sortedValue x ⟨k,by omega⟩ + +lemma sortedValue_monotone (x : Fin (2*k+1) → ℚ) : Monotone (sortedValue x) := by + intro i j hij + exact ((List.ofFn x).sortedLE_mergeSort).getElem_le_getElem_of_le hij + +lemma ofFn_sortedValue (x : Fin (2*k+1) → ℚ) : List.ofFn (sortedValue x)=sortedList x := by + apply List.ext_getElem + · simp [sortedList_length] + · intro i hi hj + rw [List.getElem_ofFn] + rfl + +lemma majority_sorted (f : Fin (2*k+1) → ℚ) (hf : Monotone f) (a b : ℚ) + (h : k < (univ.filter fun i => a ≤ f i ∧ f i ≤ b).card) : + a ≤ f ⟨k,by omega⟩ ∧ f ⟨k,by omega⟩ ≤ b := by + let z : Fin (2*k+1) := ⟨k,by omega⟩ + constructor + · by_contra hc + have hc' : f z < a := lt_of_not_ge hc + have hs : (univ.filter fun i => a ≤ f i ∧ f i ≤ b) ⊆ Ioi z := by + intro i hi + apply mem_Ioi.mpr + by_contra hnot + have hlow := (mem_filter.mp hi).2.1 + have hm := hf (le_of_not_gt hnot) + exact (not_lt_of_ge (hlow.trans hm)) hc' + have hh := card_le_card hs + rw [Fin.card_Ioi] at hh + dsimp [z] at hh + omega + · by_contra hc + have hc' : b < f z := lt_of_not_ge hc + have hs : (univ.filter fun i => a ≤ f i ∧ f i ≤ b) ⊆ Iio z := by + intro i hi + apply mem_Iio.mpr + by_contra hnot + have hupp := (mem_filter.mp hi).2.2 + have hm := hf (le_of_not_gt hnot) + exact (not_lt_of_ge (hm.trans hupp)) hc' + have hh := card_le_card hs + rw [Fin.card_Iio] at hh + dsimp [z] at hh + omega + +lemma good_count (x : Fin (2*k+1) → ℚ) (a b : ℚ) : + (univ.filter fun i => a ≤ x i ∧ x i ≤ b).card= + ((List.ofFn x).map (fun q => if a ≤ q ∧ q ≤ b then 1 else 0)).sum := by + rw [List.map_ofFn,List.sum_ofFn] + exact Finset.card_filter _ _ + +lemma sorted_good_count (x : Fin (2*k+1) → ℚ) (a b : ℚ) : + (univ.filter fun i => a ≤ sortedValue x i ∧ sortedValue x i ≤ b).card= + (univ.filter fun i => a ≤ x i ∧ x i ≤ b).card := by + rw [good_count,good_count,ofFn_sortedValue] + exact ((List.mergeSort_perm (List.ofFn x) (· ≤ ·)).map _).sum_eq + +theorem median_majority (x : Fin (2*k+1) → ℚ) (a b : ℚ) + (h : k < (univ.filter fun i => a ≤ x i ∧ x i ≤ b).card) : + a ≤ median x ∧ median x ≤ b := by + apply majority_sorted (sortedValue x) (sortedValue_monotone x) a b + rwa [sorted_good_count] + +open Finset MatchingFPRAS.Adaptive MatchingFPRAS.Transport +open scoped Classical + +variable {Ω : Type*} [Fintype Ω] + +omit [Fintype Ω] in +lemma product_bad (r : ℕ) (B : Ω → Prop) (x : Fin r → Ω) : + (∏ i : Fin r, (if B (x i) then (10:ℝ) else 1)) = + (10:ℝ)^(univ.filter fun i=>B (x i)).card := by + rw [← prod_filter] + simp + +lemma product_moment (μ : Law Ω) (r : ℕ) (B : Ω → Prop) : + ∑ x : Fin r → Ω,(μ.iid r) x * (∏ i,if B (x i) then (10:ℝ) else 1) = + (1+9*μ.event B)^r := by + have he : (∑ x : Ω, μ x*(if B x then (10:ℝ) else 1))=1+9*μ.event B := by + calc + _ = ∑ x : Ω, (μ x+9*(if B x then μ x else 0)) := by + apply sum_congr rfl + intro x _ + split_ifs <;> ring + _ = _ := by rw [sum_add_distrib,←mul_sum,μ.total]; rfl + change (∑ x : Fin r → Ω,(∏ i,μ (x i)) * ∏ i,if B (x i) then (10:ℝ) else 1) = _ + simp_rw [←prod_mul_distrib] + rw [←Fintype.prod_sum (fun (_ : Fin r) (x : Ω)=>μ x*(if B x then (10:ℝ) else 1))] + simp only [he,prod_const,card_univ,Fintype.card_fin] + +lemma majority_tail (μ : Law Ω) (B : Ω → Prop) (hB : μ.event B≤1/10) (k : ℕ) : + (μ.iid (2*k+1)).event (fun x=>k<(univ.filter fun i=>B (x i)).card) ≤ (2:ℝ)⁻¹^k := by + have hM : (10:ℝ)^(k+1) * (μ.iid (2*k+1)).event + (fun x=>k<(univ.filter fun i=>B (x i)).card) ≤ (1+9*μ.event B)^(2*k+1) := by + rw [←product_moment μ (2*k+1) B] + unfold Law.event + rw [mul_sum] + apply sum_le_sum + intro x _ + rw [product_bad] + split_ifs with hx + · exact mul_le_mul_of_nonneg_right (pow_le_pow_right₀ (by norm_num) (by omega)) + ((μ.iid (2*k+1)).nonneg x) |>.trans_eq (mul_comm _ _) + · rw [mul_zero] + exact mul_nonneg ((μ.iid (2*k+1)).nonneg x) (by positivity) + have hn : 0≤1+9*μ.event B := by have := μ.event_nonneg B; linarith + have hu : (1+9*μ.event B)^(2*k+1) ≤ (2:ℝ)^(2*k+1) := + pow_le_pow_left₀ hn (by linarith) _ + have hdiv : (μ.iid (2*k+1)).event (fun x=>k<(univ.filter fun i=>B (x i)).card) ≤ (2:ℝ)^(2*k+1)/10^(k+1) := (le_div_iff₀ (by positivity : (0:ℝ)<10^(k+1))).mpr (by rw [mul_comm]; exact hM.trans hu) + apply hdiv.trans + calc + (2:ℝ)^(2*k+1)/10^(k+1) = (1/5:ℝ)*(4/10)^k := by + rw [pow_add,pow_add,pow_mul] + simp only [pow_one] + rw [div_mul_eq_div_mul_one_div,div_pow] + ring + _ ≤ (1/2:ℝ)^k := by + have hpow : (4/10:ℝ)^k ≤ (1/2:ℝ)^k := pow_le_pow_left₀ (by norm_num) (by norm_num) _ + calc + _ ≤ (1:ℝ)*(4/10)^k := mul_le_mul_of_nonneg_right (by norm_num) (by positivity) + _ ≤ _ := by simpa using hpow + _ = _ := by norm_num + +lemma median_failure (μ : Law Ω) (out : Ω → ℚ) (a b : ℚ) + (h : μ.event (fun x=>¬(a≤out x ∧ out x≤b))≤1/10) (k : ℕ) : + (μ.iid (2*k+1)).event (fun x=>¬(a ≤ median (fun i=>out (x i)) ∧ median (fun i=>out (x i))≤b)) + ≤ (2:ℝ)⁻¹^k := by + apply (Law.event_mono _ (fun x hx=>?_)).trans (majority_tail μ (fun y=>¬(a≤out y ∧ out y≤b)) h k) + by_contra hh + have hb := not_lt.mp hh + have hs := card_filter_add_card_filter_not (s:=univ) (p:=fun i : Fin (2*k+1)=>a≤out (x i) ∧ out (x i)≤b) + simp only [card_univ,Fintype.card_fin] at hs + apply hx + apply median_majority (k:=k) (fun i=>out (x i)) a b + have hc : (univ.filter fun i : Fin (2*k+1)=>¬(a≤out (x i) ∧ out (x i)≤b)).card ≤ k := by + convert hb using 1 + congr 1 + ext i + simp + omega + +omit [Fintype Ω] in +lemma median_nonneg {k : ℕ} (out : Fin (2*k+1) → ℚ) (h : ∀ i,0≤out i) : 0 ≤ median out := by + unfold median sortedValue + have hp := List.mergeSort_perm (List.ofFn out) (· ≤ ·) + have hx : (sortedList out)[k]'(by rw [sortedList_length]; omega) ∈ List.ofFn out := + hp.mem_iff.mp (List.getElem_mem _) + obtain ⟨i,hi⟩ := List.mem_ofFn.mp hx + rw [←hi] + exact h i + +open Finset MatchingFPRAS.Adaptive +open scoped Classical + +def halfRepetitions (δ : ℚ) : ℕ := 5*(Nat.clog 2 ⌈δ⁻¹⌉₊+1) +lemma repetitions_source (δ : ℚ) : 2*halfRepetitions δ+1=10*(Nat.clog 2 ⌈δ⁻¹⌉₊+1)+1 := by + unfold halfRepetitions + ring +lemma amplification_precision (δ : ℚ) (hδ : 0<δ) : (2:ℝ)⁻¹^(halfRepetitions δ)≤(δ:ℝ) := by + let m := Nat.clog 2 ⌈δ⁻¹⌉₊ + have hc : (δ:ℝ)⁻¹≤(⌈δ⁻¹⌉₊:ℝ) := by + exact_mod_cast Nat.le_ceil (δ⁻¹) + have hp : (⌈δ⁻¹⌉₊:ℝ)≤(2:ℝ)^m := by + exact_mod_cast Nat.le_pow_clog (by decide : 1<2) ⌈δ⁻¹⌉₊ + have hd : (0:ℝ)<δ := by exact_mod_cast hδ + have hh : (2:ℝ)⁻¹^m≤(δ:ℝ) := by + rw [inv_pow] + apply (inv_le_iff_one_le_mul₀ (by positivity)).mpr + nlinarith [hc.trans hp,inv_pos.mpr hd,mul_inv_cancel₀ hd.ne'] + apply (pow_le_pow_of_le_one (by norm_num : (0:ℝ)≤2⁻¹) (by norm_num) (show m≤halfRepetitions δ by dsimp [m,halfRepetitions]; omega)).trans hh + +variable {Ω : Type*} [Fintype Ω] +lemma median_delta (μ : Law Ω) (out : Ω → ℚ) (a b : ℚ) + (h : μ.event (fun x=>¬(a≤out x ∧ out x≤b))≤1/10) (δ : ℚ) (hδ : 0<δ) : + (μ.iid (2*halfRepetitions δ+1)).event + (fun x=>¬(a≤ median (fun i=>out (x i)) ∧ median (fun i=>out (x i))≤b)) ≤ (δ:ℝ) := + (median_failure μ out a b h _).trans (amplification_precision δ hδ) +end MatchingFPRAS.Amplification + +namespace MatchingFPRAS.FiniteTrial +open Finset Adaptive Amplification +open scoped Classical + +variable {G : GraphInput} [Nontrivial (Fin G.n)] +noncomputable def amplifiedOutput (p : Trial.Parameters G) (δ : ℚ) + (x : Fin (2*halfRepetitions δ+1) → (layers p p.K le_rfl).Ω) : ℚ := + median (fun i=>output p (x i)) +lemma amplifiedOutput_nonneg (p : Trial.Parameters G) (δ : ℚ) + (x : Fin (2*halfRepetitions δ+1) → (layers p p.K le_rfl).Ω) : 0≤amplifiedOutput p δ x := + median_nonneg _ (fun i=>output_nonneg p (x i)) +theorem actual_finite_amplified_failure (p : Trial.Parameters G) (hZ : 0¬((1-p.epsilon)*(Z G:ℚ)≤amplifiedOutput p δ x ∧ + amplifiedOutput p δ x≤(1+p.epsilon)*(Z G:ℚ))) ≤ (δ:ℝ) := by + apply median_delta + · exact (actual_finite_trial_failure p hZ).trans (by norm_num) + · exact hδ +end MatchingFPRAS.FiniteTrial + +namespace MatchingFPRAS.Counting +instance scheduleDecidable (n : ℕ) (epsilon : ℚ) (k : ℕ) : Decidable (scheduleAdmissible n epsilon k) := + inferInstanceAs (Decidable (1≤k ∧ (n:ℚ)^(n/2)/(1+1/(n:ℚ))^k≤epsilon/32)) +lemma schedule_exists (n : ℕ) (hn : 2≤n) (e : ℚ) (he : 0 exact s.edge_ratio _ _ + · exact Or.inl rfl + · exact Or.inl rfl +lemma product_binary_power {E : Type*} (A : Finset E) (f : E → ℝ) (c : ℝ) + (hf : ∀ e∈A,f e=1 ∨ f e=c) : ∃ a≤A.card,∏ e∈A,f e=c^a := by + classical + induction A using Finset.induction_on with + | empty => exact ⟨0,by simp,by simp⟩ + | @insert e A he ih => + obtain ⟨a,ha,hea⟩ := ih (fun i hi=>hf i (mem_insert_of_mem hi)) + rcases hf e (mem_insert_self _ _) with h|h + · refine ⟨a,by simpa [card_insert_of_notMem he] using (Nat.le_succ_of_le ha),?_⟩ + rw [prod_insert he,h,one_mul,hea] + · refine ⟨a+1,by simpa [card_insert_of_notMem he] using Nat.succ_le_succ ha,?_⟩ + rw [prod_insert he,h,hea,pow_succ,mul_comm] +lemma ScaleState.pm_card (s : ScaleState G j) (a : SourceMarked s.activity K) : + a.1.val.card≤ Fintype.card (SourceVertex (Fin G.n) K) := by + let : Fintype (BagEdge (sourceBags s.activity K)) := Fintype.ofFinite _ + apply PM.card_le_vertices + intro e + exact ⟨e.val.val.1.out.1,by + change e.val.val.1.out.1∈e.val.val.1 + exact Sym2.out_fst_mem _⟩ +lemma ScaleState.observable_power (s : ScaleState G j) (a : SourceMarked s.activity K) : + (observableA s.activity K a=0 ∨ observableA s.activity K a=1) ∧ + (observableD s.activity s.nextActivity K a=0 ∨ + ∃ t≤Fintype.card (SourceVertex (Fin G.n) K),observableD s.activity s.nextActivity K a=Trial.cooling G.n^t) ∧ + (∀ e₀,observableProbe s.activity s.nextActivity K e₀ a=0 ∨ + ∃ t≤Fintype.card (SourceVertex (Fin G.n) K),observableProbe s.activity s.nextActivity K e₀ a=Trial.cooling G.n^t) := by + refine ⟨?_,?_,?_⟩ + · unfold observableA + split_ifs <;> simp + · unfold observableD + split_ifs + · right + obtain ⟨t,ht,he⟩ := product_binary_power a.1.val _ (Trial.cooling G.n) (fun e _=>s.bag_reweight e) + exact ⟨t,ht.trans (s.pm_card a),he⟩ + · exact Or.inl rfl + · intro e₀ + unfold observableProbe + split_ifs + · right + obtain ⟨t,ht,he⟩ := product_binary_power (a.1.val\{centralEdge s.activity K e₀}) _ + (Trial.cooling G.n) (fun e _=>s.bag_reweight e) + refine ⟨t,ht.trans ((card_le_card sdiff_subset).trans (s.pm_card a)),?_⟩ + convert he using 1 + congr 1 + ext e + simp only [mem_sdiff,mem_singleton] + · exact Or.inl rfl +end MatchingFPRAS.Trial + +namespace MatchingFPRAS.BitArithmetic +open Finset + +def GridFraction (Q : ℕ) (x : ℝ) : Prop := ∃ a : ℕ,a≤Q ∧ x=(a:ℝ)/Q +lemma GridFraction.zero (Q : ℕ) : GridFraction Q 0 := ⟨0,Nat.zero_le _,by simp⟩ +lemma GridFraction.one {Q : ℕ} (hQ : 0ha i + _ = S*Q := by simp + · unfold Enlargement.sampleAverage + simp_rw [he] + rw [← sum_div] + push_cast + ring +lemma GridFraction.cooling_power (n N t : ℕ) (ht : t≤N) : + GridFraction ((n+1)^N) (((n:ℝ)/(n+1))^t) := by + refine ⟨n^t*(n+1)^(N-t),?_,?_⟩ + · calc + _ ≤ (n+1)^t*(n+1)^(N-t) := Nat.mul_le_mul_right _ (Nat.pow_le_pow_left (by omega) _) + _ = (n+1)^N := by rw [←pow_add,Nat.add_sub_of_le ht] + · have hpos : (0:ℝ) simpa using FractionBound.one (B:=1) le_rfl + | succ k ih => simpa [pow_succ] using ih.mul h +lemma FractionBound.prod {ι : Type*} (A : Finset ι) (f : ι → ℝ) (B : ℕ) + (h : ∀ i∈A,FractionBound B (f i)) : FractionBound (B^A.card) (∏ i∈A,f i) := by + classical + induction A using Finset.induction_on with + | empty => simpa using FractionBound.one (B:=1) le_rfl + | @insert i A hi ih => + simpa [prod_insert hi,card_insert_of_notMem hi,pow_succ,Nat.mul_comm] using + (h i (mem_insert_self _ _)).mul (ih (fun j hj=>h j (mem_insert_of_mem hj))) +end MatchingFPRAS.BitArithmetic + +end OAI diff --git a/lean/OAI/Combinatorics/MatchingCount/Algorithm/TreeCertificate.lean b/lean/OAI/Combinatorics/MatchingCount/Algorithm/TreeCertificate.lean new file mode 100644 index 0000000000000000000000000000000000000000..0edd24000e747ec89c70325121adc7dce84920a9 --- /dev/null +++ b/lean/OAI/Combinatorics/MatchingCount/Algorithm/TreeCertificate.lean @@ -0,0 +1,49 @@ +import Mathlib +import OAI.Combinatorics.MatchingCount.Algorithm.GuardProbability +import OAI.Combinatorics.MatchingCount.Algorithm.TreeGeneratedUpdate + +namespace OAI + +namespace MatchingFPRAS.ExecutableSource +open TreeTyped TreeFraction TreeTyped.Numbered ExecutableBottleneck ExecutableHierarchy ExecutableRefresh Enlargement RealGeometry NumericLadder +open ExecutableLadder UnitRefresh Replica.Ladder Transport NumericMarking ExecutableStatistics ExecutableScaling ExecutableAdaptive + +attribute [local instance] NumberedHierarchy.labelOrder +attribute [local instance] Transport.sym2Order Transport.bagEdgeOrder Transport.bagEdgeFintype +attribute [local instance] UnitRefresh.Computable.allowedDec Transport.prodOrder Transport.sumOrder + +lemma generatedSourceSample_support {n : ℕ} [Nontrivial (Fin n)] + (he : Even n) (w : Fin n→Fin n→ℚ) (hw : ∀ a b,0(w a b:ℝ)) K D ((RationalSource.sourceMarkedEquiv w K).symm + (generatedSourceSample he w hw K D hD hu ft fq hq bits mb)) := by + let x:=generatedSourceSample he w hw K D hD hu ft fq hq bits mb + have hs:=RationalSource.source_draw_support w hw K D km hD + (fun _ : Unit=>x.1) ((),mb) + exact hs + +lemma generated_certificate_zero {G : GraphInput} [Nontrivial (Fin G.n)] + (he : Even G.n) {j : ℕ} (s : FiniteTrial.ScaleState G j) (hZ : Z G=0) + (K D : ℕ) (hD : 0add (b,a)) (repr a))=repr (xs.sum+a) := by + induction xs generalizing a with + | nil => simp + | cons x xs ih => + have h : 0≤x:=hx x (by simp) + simp only [List.map_cons,List.foldl_cons,add_repr h ha] + rw [ih (fun y hy=>hx y (by simp [hy])) (x+a) (add_nonneg h ha)] + congr 1 + simp only [List.sum_cons] + ring +lemma sum_repr (xs : List ℚ) (hx : ∀ x∈xs,0≤x) : sum (xs.map repr)=repr xs.sum := by + unfold sum + have h:=fold_sum_repr xs hx 0 (by decide) + simpa only [add_zero,show repr (0:ℚ)=(0,1) from rfl] using h +end MatchingFPRAS.TreeFraction + +namespace MatchingFPRAS.ExecutableEstimator +open TreeTyped TreeFraction + +def mean (xs : List Fraction) : Fraction := div (sum xs,(xs.length,1)) +def meanRealizer : Realizer mean := composition + (pair sumRealizer (pair listLength (constant 1))) divRealizer +lemma polynomial_mean : PolynomialTime meanRealizer := by + unfold meanRealizer + apply polynomial_composition _ polynomial_div + exact polynomial_pair polynomial_sum (polynomial_pair polynomial_listLength (polynomial_constant _)) +lemma mean_rep (xs : List ℚ) (hx : ∀ x∈xs,0≤x) : + mean (xs.map TreeFraction.repr)=TreeFraction.repr (xs.sum/xs.length) := by + unfold mean + rw [sum_repr xs hx,List.length_map,←repr_nat xs.length,div_repr (List.sum_nonneg hx) (by positivity)] + +def ratio (x : Fraction×Fraction) : Fraction := + if less ((0,1),x.1) then div (x.2,x.1) else (1,1) +def ratioRealizer : Realizer ratio := + (choose (composition (pair (constant (0,1)) first) lessRealizer) + (composition (pair second first) divRealizer) (constant (1,1))).congr (fun _=>rfl) +lemma polynomial_ratio : PolynomialTime ratioRealizer := by + unfold ratioRealizer + apply polynomial_congr + have := TreeFraction.polynomial_less + have := polynomial_div + tree_cost +lemma ratio_rep (a d : ℚ) (ha : 0≤a) (hd : 0≤d) : + ratio (TreeFraction.repr a,TreeFraction.repr d)=TreeFraction.repr (Counting.ratioEstimate a d) := by + unfold ratio Counting.ratioEstimate + rw [show ((0,1) : Fraction)=TreeFraction.repr (0:ℚ) from rfl, + less_val _ _ (by decide) a.pos,val_repr (by decide),val_repr ha] + simp only [decide_eq_true_eq] + split_ifs + · exact div_repr hd ha + · rfl + +def upper (x : ℕ×(Fraction×Fraction)) : Fraction := + if less ((0,1),x.2.1) then + maximum ((1,100000),minimum ((3,1),add (div (mul ((x.1,1),x.2.2),x.2.1),(1,100000)))) + else (1,1) +def upperRealizer : Realizer upper := by + let q : Realizer (fun x : ℕ×(Fraction×Fraction)=> + div (mul ((x.1,1),x.2.2),x.2.1)) := + (composition (pair (composition (pair (pair first (constant 1)) second.snd) mulRealizer) second.fst) divRealizer).congr (fun _=>rfl) + exact (choose (composition (pair (constant (0,1)) second.fst) lessRealizer) + (composition (pair (constant (1,100000)) (composition (pair (constant (3,1)) + (composition (pair q (constant (1,100000))) addRealizer)) minimumRealizer)) maximumRealizer) + (constant (1,1))).congr (fun _=>rfl) +lemma polynomial_upper : PolynomialTime upperRealizer := by + unfold upperRealizer Realizer.fst Realizer.snd + dsimp only + apply polynomial_congr + have := TreeFraction.polynomial_less + have := polynomial_div + have := polynomial_mul + have := TreeFraction.polynomial_add + have := TreeFraction.polynomial_minimum + have := polynomial_maximum + tree_cost +lemma upper_rep (D : ℕ) (d z : ℚ) (hd : 0≤d) (hz : 0≤z) : + upper (D,(TreeFraction.repr d,TreeFraction.repr z))=TreeFraction.repr (Counting.upperEstimate D d z) := by + have ha : ((1,100000) : Fraction)=TreeFraction.repr Counting.alpha := by norm_num [TreeFraction.repr,Counting.alpha] + have ha0 : (0:ℚ)≤Counting.alpha := by norm_num [Counting.alpha] + have h0 : ((0,1) : Fraction)=TreeFraction.repr (0:ℚ) := rfl + have h3 : ((3,1) : Fraction)=TreeFraction.repr (3:ℚ) := rfl + unfold upper Counting.upperEstimate + rw [h0,less_val _ _ (by decide) d.pos,val_repr (by decide),val_repr hd] + simp only [decide_eq_true_eq] + split_ifs + · rw [ha,h3,←repr_nat D,mul_repr (by positivity) hz,div_repr (by positivity) hd, + add_repr (by positivity) ha0,minimum_repr (by decide) (by positivity),maximum_repr ha0 (by positivity)] + · rfl +end MatchingFPRAS.ExecutableEstimator + +end OAI diff --git a/lean/OAI/Combinatorics/MatchingCount/Algorithm/TreeGeneratedCertificate.lean b/lean/OAI/Combinatorics/MatchingCount/Algorithm/TreeGeneratedCertificate.lean new file mode 100644 index 0000000000000000000000000000000000000000..c7a7caaf777e599ba6055a77f7a017031bec6ec2 --- /dev/null +++ b/lean/OAI/Combinatorics/MatchingCount/Algorithm/TreeGeneratedCertificate.lean @@ -0,0 +1,105 @@ +import Mathlib +import OAI.Combinatorics.MatchingCount.Algorithm.TreeGeneratedUpdate + +namespace OAI + +namespace MatchingFPRAS.NumericMarking +open TreeTyped TreeFraction TreeTyped.Numbered ExecutableMarking ExecutableStatistics + +lemma numeric_observableD_rep {E : Type} [Fintype E] [LinearOrder E] + (s : Finset E) (m : E→Fin 3) (r : E→ℚ) (hr : ∀ e,0≤r e) : + ExecutableMarking.observableD reweight (reweightsRep r,numericMarks s m)= + TreeFraction.repr (if ∀ e∈s,m e=0 then ∏ e∈s,r e else 0) := by + rw [numericMarks_eq,observableD_rep reweight (reweightsRep r) (extend 1 r) + (extend_nonneg r hr) (reweight_rep r)] + apply congrArg TreeFraction.repr + simpa only [scalarD] using scalarD_numbered (fun _ : Fin 1=>s) (fun _ : Fin 1=>m) r 0 +end MatchingFPRAS.NumericMarking + +namespace MatchingFPRAS.TreeTyped +variable {A B C : Type} [Codec A] [Codec B] [Codec C] +def applyFirst {f : A→C} (F : Realizer f) : Realizer (fun x : A×B=>f x.1) := + composition first F +lemma polynomial_applyFirst {f : A→C} {F : Realizer f} (hF : PolynomialTime F) : + PolynomialTime (applyFirst (B:=B) F) := polynomial_composition polynomial_first hF +end MatchingFPRAS.TreeTyped + +namespace MatchingFPRAS.ExecutableSource +open TreeTyped TreeFraction TreeTyped.Numbered ExecutableBottleneck ExecutableHierarchy ExecutableRefresh Enlargement RealGeometry NumericLadder +open ExecutableMarking ExecutableLadder UnitRefresh Replica.Ladder Transport NumericMarking ExecutableStatistics ExecutableScaling ExecutableAdaptive + +attribute [local instance] NumberedHierarchy.labelOrder +attribute [local instance] Transport.sym2Order Transport.bagEdgeOrder Transport.bagEdgeFintype +attribute [local instance] UnitRefresh.Computable.allowedDec Transport.prodOrder Transport.sumOrder + +abbrev GeneratedCertificateInput := GeneratedStageData×SampleBits +def generatedCertificate (x : GeneratedCertificateInput) : Fraction := + ExecutableMarking.observableD reweight (generatedReweights x.1,generatedMarked (x.1.1,x.2)) +def certificateSampleArg (x : GeneratedCertificateInput) : GeneratedInput×SampleBits := (x.1.1,x.2) +def certificateSampleArgRealizer : Realizer certificateSampleArg := + (TreeTyped.pair (first (A:=GeneratedStageData) (B:=SampleBits)).fst second).congr (fun _=>rfl) +lemma polynomial_certificateSampleArg : PolynomialTime certificateSampleArgRealizer := + polynomial_congr _ (TreeTyped.polynomial_pair (polynomial_fst polynomial_first) polynomial_second) +def certificateSample (x : GeneratedCertificateInput) : ExecutableMarking.Marks ℕ := generatedMarked (certificateSampleArg x) +def certificateSampleRealizer : Realizer certificateSample := + (composition certificateSampleArgRealizer generatedMarkedRealizer).congr (fun _=>rfl) +lemma polynomial_certificateSample : PolynomialTime certificateSampleRealizer := + polynomial_congr _ (polynomial_composition polynomial_certificateSampleArg polynomial_generatedMarked) +def certificateReweights (x : GeneratedCertificateInput) : Reweights := generatedReweights x.1 +def certificateReweightsRealizer : Realizer certificateReweights := + applyFirst (B:=SampleBits) generatedReweightsRealizer +lemma polynomial_certificateReweights : PolynomialTime certificateReweightsRealizer := + polynomial_applyFirst polynomial_generatedReweights +def certificateArgs (x : GeneratedCertificateInput) : Reweights×ExecutableMarking.Marks ℕ := + (certificateReweights x,certificateSample x) +def certificateArgsRealizer : Realizer certificateArgs := + (TreeTyped.pair certificateReweightsRealizer certificateSampleRealizer).congr (fun _=>rfl) +lemma polynomial_certificateArgs : PolynomialTime certificateArgsRealizer := + polynomial_congr _ (TreeTyped.polynomial_pair polynomial_certificateReweights polynomial_certificateSample) +def generatedCertificateRealizer : Realizer generatedCertificate := + (composition (f:=certificateArgs) (g:=ExecutableMarking.observableD reweight) + certificateArgsRealizer (observableDRealizer reweightRealizer)).congr (fun _=>rfl) +lemma polynomial_generatedCertificate : PolynomialTime generatedCertificateRealizer := + polynomial_congr _ (polynomial_composition polynomial_certificateArgs (polynomial_observableD polynomial_reweight)) + +lemma numeric_certificate_source {n : ℕ} [Nontrivial (Fin n)] + (w w₁ : Fin n→Fin n→ℚ) (hw : ∀ a b,0≤w a b) (hw₁ : ∀ a b,0≤w₁ a b) + (K : ℕ) (x : RationalSource.Marked w K) : + ExecutableMarking.observableD reweight (reweightsRep (RationalSource.bagReweight w w₁ K), + numericMarks x.1.val (selectedMarks x.1.val x.2))= + TreeFraction.repr (RationalSource.observableD w w₁ K x) := by + rw [numeric_observableD_rep _ _ _ (reweight_nonneg w w₁ hw hw₁ K)] + apply congrArg TreeFraction.repr + unfold RationalSource.observableD + simp only [selectedMarks_eq] + +lemma generatedCertificate_source {n : ℕ} [Nontrivial (Fin n)] + (hn : 2≤n) (he : Even n) (w w₁ : Fin n→Fin n→ℚ) + (hw : ∀ a b,0(List.ofFn (bits z).1,localBitsRep (bits z).2)), + (List.ofFn (orderedEnum (BagEdge (RationalSource.bags w K)))).map (fun e=>(index e,List.ofFn (mb e)))))= + TreeFraction.repr (RationalSource.observableD w w₁ K + (generatedSourceSample he w hw K D hD hu ft fq hq bits mb)) := by + unfold generatedCertificate generatedReweights + dsimp only + rw [sourceReweights_source hn w w₁ (fun a b=>(hw a b).le) hw₁ K, + generatedMarked_sourceSample hn he w hw K D hD hu ft fq hq bits mb] + exact numeric_certificate_source w w₁ (fun a b=>(hw a b).le) hw₁ K _ + +open TreePost Turing + +theorem generatedCertificate_post : ∃ p : Polynomial ℕ,∀ x : GeneratedCertificateInput,∀ t : ℕ, + p.eval (packed x).length≤t → ∀ coins : Fin t→Bool, + (run (machine generatedCertificateRealizer.program) (packed x) coins).state=none ∧ + (run (machine generatedCertificateRealizer.program) (packed x) coins).tape.right₀= + ListBlank.mk (packed (generatedCertificate x)) := + polynomial_compiles generatedCertificateRealizer polynomial_generatedCertificate +end MatchingFPRAS.ExecutableSource + +end OAI diff --git a/lean/OAI/Combinatorics/MatchingCount/Algorithm/TreeGeneratedMarked.lean b/lean/OAI/Combinatorics/MatchingCount/Algorithm/TreeGeneratedMarked.lean new file mode 100644 index 0000000000000000000000000000000000000000..da71f7dea0281cf460084ffe437d828d2be5d111 --- /dev/null +++ b/lean/OAI/Combinatorics/MatchingCount/Algorithm/TreeGeneratedMarked.lean @@ -0,0 +1,78 @@ +import Mathlib +import OAI.Combinatorics.MatchingCount.Algorithm.TreeGeneratedTop +import OAI.Combinatorics.MatchingCount.Machines.TreeMarkTable +import OAI.Combinatorics.MatchingCount.Sampling.TreePreparedMarked + +namespace OAI + +namespace MatchingFPRAS.ExecutableSource +open TreeTyped TreeFraction TreeTyped.Numbered ExecutableBottleneck ExecutableHierarchy ExecutableRefresh Enlargement RealGeometry NumericLadder +open ExecutableLadder UnitRefresh Replica.Ladder Transport NumericMarking + +attribute [local instance] NumberedHierarchy.labelOrder +attribute [local instance] Transport.sym2Order Transport.bagEdgeOrder Transport.bagEdgeFintype +attribute [local instance] UnitRefresh.Computable.allowedDec Transport.prodOrder Transport.sumOrder + +def generatedContext (x : GeneratedInput) : SampleContext := + ((generatedPrepared x,exactStart x.1.1),sourceMarks x.1) +def generatedContextRealizer : Realizer generatedContext := (pair + (pair generatedPreparedRealizer (composition first.fst exactStartRealizer)) + (composition first sourceMarksRealizer)).congr (fun _=>rfl) +lemma polynomial_generatedContext : PolynomialTime generatedContextRealizer := by + unfold generatedContextRealizer + apply polynomial_congr + dsimp only [Realizer.fst, Realizer.snd] + have := polynomial_generatedPrepared + have := polynomial_exactStart + have := polynomial_sourceMarks + tree_cost + +def generatedMarked (x : GeneratedInput×SampleBits) : ExecutableMarking.Marks ℕ := + NumericMarking.sample (generatedContext x.1,x.2) +def generatedMarkedRealizer : Realizer generatedMarked := (composition + (pair (composition first generatedContextRealizer) second) sampleRealizer).congr (fun _=>rfl) +lemma polynomial_generatedMarked : PolynomialTime generatedMarkedRealizer := + polynomial_congr _ (polynomial_composition + (polynomial_pair (polynomial_composition polynomial_first polynomial_generatedContext) polynomial_second) + polynomial_sample) + +lemma generatedMarked_source {n : ℕ} [Nontrivial (Fin n)] (hn : 2≤n) (he : Even n) + (w : Fin n→Fin n→ℚ) (hw : ∀ a b,0(List.ofFn (bits i).1,localBitsRep (bits i).2)), + (List.ofFn (orderedEnum (BagEdge (RationalSource.bags w K)))).map (fun e=>(index e,List.ofFn (mb e)))))= + numericMarks (ladderRun (RationalSource.bags_adjacent w K hu) (RationalSource.tree_acyclic w K) + (fun l : RationalSource.Label w K=>l.1.val) (RationalSource.parent w K) + (RationalSource.bags_ranked w K hu) (RationalSource.bags_nonempty w K) + (RationalSource.parent_rank w K) hq (RationalSource.bagWeight w K D) + (RationalSource.startMatching w K he) k r (fun _=>RationalSource.startMatching w K he) bits + (toLex ((0 : Fin (ft.length+1)),(⟨0,hq⟩ : Fin fq.length)))).val + (fun e=>(RationalSource.markingTable w hw K D hD e).draw km (mb e)) := by + unfold generatedMarked generatedContext + dsimp only + rw [generatedPrepared_source hn w (fun a b=>(hw a b).le) K D ft fq, + exactStart_source hn he w (fun a b=>(hw a b).le) K, + sourceMarks_source hn w hw K D hD] + exact sample_source (RationalSource.bags_adjacent w K hu) (RationalSource.tree_acyclic w K) + (fun l : RationalSource.Label w K=>l.1.val) (RationalSource.parent w K) + (RationalSource.bags_ranked w K hu) (RationalSource.bags_nonempty w K) + (RationalSource.parent_rank w K) ft fq hq (RationalSource.bagWeight w K D) + (bagWeight_nonneg w hw K D) (RationalSource.startMatching w K he) _ + (setupBags_source hn w (fun a b=>(hw a b).le) K) _ bits mb + +open TreePost Turing + +theorem generatedMarked_post : ∃ p : Polynomial ℕ,∀ x : GeneratedInput×SampleBits,∀ t : ℕ, + p.eval (packed x).length≤t → ∀ coins : Fin t→Bool, + (run (machine generatedMarkedRealizer.program) (packed x) coins).state=none ∧ + (run (machine generatedMarkedRealizer.program) (packed x) coins).tape.right₀= + ListBlank.mk (packed (generatedMarked x)) := + polynomial_compiles generatedMarkedRealizer polynomial_generatedMarked +end MatchingFPRAS.ExecutableSource + +end OAI diff --git a/lean/OAI/Combinatorics/MatchingCount/Algorithm/TreeGeneratedPrepared.lean b/lean/OAI/Combinatorics/MatchingCount/Algorithm/TreeGeneratedPrepared.lean new file mode 100644 index 0000000000000000000000000000000000000000..f5a896dbb3bb802ee05425761e306e9747e7b694 --- /dev/null +++ b/lean/OAI/Combinatorics/MatchingCount/Algorithm/TreeGeneratedPrepared.lean @@ -0,0 +1,133 @@ +import Mathlib +import OAI.Combinatorics.MatchingCount.Machines.TreeWeightTable +import OAI.Combinatorics.MatchingCount.Machines.TreeMetadata +import OAI.Combinatorics.MatchingCount.Sampling.TreePrepared + +namespace OAI + +namespace MatchingFPRAS.ExecutableSource +open TreeTyped TreeFraction TreeTyped.Numbered ExecutableBottleneck ExecutableHierarchy ExecutableRefresh Enlargement RealGeometry NumericLadder + +attribute [local instance] NumberedHierarchy.labelOrder +attribute [local instance] Transport.sym2Order Transport.bagEdgeOrder Transport.bagEdgeFintype + +def rangeFromList {A : Type} (xs : List A) : Finset ℕ := (List.range xs.length).toFinset +def rangeFromListRealizer {A : Type} [Codec A] : Realizer (rangeFromList (A:=A)) := + composition (composition listLength range) (listFinset natEqual leNat) +lemma polynomial_rangeFromList {A : Type} [Codec A] : PolynomialTime (rangeFromListRealizer (A:=A)) := by + apply polynomial_composition _ (polynomial_listFinset polynomial_natEqual polynomial_leNat) + exact polynomial_boundedRange polynomial_listLength Polynomial.X (fun x=>by + simpa using list_length_le_weight x) +lemma range_card_set (A : Type) [Fintype A] [LinearOrder A] : + Finset.range (Fintype.card A)=Numbered.set (Finset.univ : Finset A) := by + ext i + simp only [Finset.mem_range,Numbered.set,Finset.mem_map,Finset.mem_univ,true_and,Numbered.embedding] + constructor + · intro h + exact ⟨UnitRefresh.orderedEnum A ⟨i,h⟩,index_orderedEnum _⟩ + · rintro ⟨a,rfl⟩ + exact ((UnitRefresh.orderedEnum A).symm a).isLt + +def sourceVertices (x : BagBuildInput) : List RawVertex := vertices (x.1.2,x.1.1.2) +def sourceVerticesRealizer : Realizer sourceVertices := composition + (pair first.snd first.fst.snd) verticesRealizer +lemma polynomial_sourceVertices : PolynomialTime sourceVerticesRealizer := + polynomial_composition (polynomial_pair (polynomial_snd polynomial_first) + (polynomial_snd (polynomial_fst polynomial_first))) polynomial_vertices +lemma sourceVertices_length {n : ℕ} (w : Fin n→Fin n→ℚ) (K : ℕ) : + (sourceVertices (((matrixRep w,List.replicate (2*K+2) false),List.range n),List.replicate (2*K) false)).length= + Fintype.card (SourceVertex (Fin n) K) := by + unfold sourceVertices + dsimp only + rw [vertices_eq_ofFn_length n _ (4*(2*K+2)) (by simp),List.length_ofFn] + +def sourceEdgeData (x : BagBuildInput) : List (ℕ×ℕ)×(Finset ℕ×Finset ℕ) := + (((sourceTables x).1.map Prod.fst),(rangeFromList (sourceVertices x),rangeFromList (sourceTables x).1)) +def sourceEdgeDataRealizer : Realizer sourceEdgeData := (pair + (composition sourceTablesRealizer.fst (map first)) + (pair (composition sourceVerticesRealizer rangeFromListRealizer) + (composition sourceTablesRealizer.fst rangeFromListRealizer))).congr (fun _=>rfl) +lemma polynomial_sourceEdgeData : PolynomialTime sourceEdgeDataRealizer := by + unfold sourceEdgeDataRealizer + apply polynomial_congr + dsimp only [Realizer.fst, Realizer.snd] + have := polynomial_sourceTables + have := polynomial_sourceVertices + have hrv := polynomial_rangeFromList (A:=RawVertex) + have hrk := polynomial_rangeFromList (A:=Key) + tree_cost +lemma sourceCatalog_endpoints {V L : Type} [Fintype V] [LinearOrder V] [Fintype L] [LinearOrder L] + (bags : V→Finset L) : (sourceCatalog bags).map Prod.fst= + List.ofFn (fun e=>ExecutablePair.endpointRep (UnitRefresh.orderedEnum (Transport.BagEdge bags) e).val.val.1) := by + unfold sourceCatalog + rw [List.map_ofFn] + rfl +lemma sourceEdgeData_source {n : ℕ} [Nontrivial (Fin n)] (hn : 2≤n) + (w : Fin n→Fin n→ℚ) (hw : ∀ a b,0≤w a b) (K : ℕ) : + sourceEdgeData (((matrixRep w,List.replicate (2*K+2) false),List.range n),List.replicate (2*K) false)= + (List.ofFn (fun e=>ExecutablePair.endpointRep + (UnitRefresh.orderedEnum (Transport.BagEdge (RationalSource.bags w K)) e).val.val.1), + (Numbered.set (Finset.univ : Finset (SourceVertex (Fin n) K)), + Numbered.set (Finset.univ : Finset (Transport.BagEdge (RationalSource.bags w K))))) := by + unfold sourceEdgeData + rw [sourceTables_catalog hn w hw K,sourceCatalog_endpoints] + apply Prod.ext + · rfl + unfold rangeFromList + rw [sourceVertices_length,List.toFinset_range,range_card_set] + unfold sourceCatalog + rw [List.length_ofFn,List.toFinset_range,range_card_set] + +abbrev GeneratedInput := (BagBuildInput×ℕ)×(List Bool×List Bool) +def generatedTier (x : GeneratedInput) : TierData := + (((sourceVertices x.1.1).length,x.2.1),(x.2.2,sourceWeights x.1)) +def generatedTierRealizer : Realizer generatedTier := (pair + (pair (composition (composition first.fst sourceVerticesRealizer) listLength) second.fst) + (pair second.snd (composition first sourceWeightsRealizer))).congr (fun _=>rfl) +lemma polynomial_generatedTier : PolynomialTime generatedTierRealizer := by + unfold generatedTierRealizer + apply polynomial_congr + dsimp only [Realizer.fst, Realizer.snd] + have := polynomial_sourceVertices + have := polynomial_sourceWeights + tree_cost + +def generatedPrepared (x : GeneratedInput) : Prepared := + ((generatedTier x,sourceEdgeData x.1.1),sourceTables x.1.1) +def generatedPreparedRealizer : Realizer generatedPrepared := (pair + (pair generatedTierRealizer (composition first.fst sourceEdgeDataRealizer)) + (composition first.fst sourceTablesRealizer)).congr (fun _=>rfl) +lemma polynomial_generatedPrepared : PolynomialTime generatedPreparedRealizer := by + unfold generatedPreparedRealizer + apply polynomial_congr + dsimp only [Realizer.fst, Realizer.snd] + have := polynomial_generatedTier + have := polynomial_sourceEdgeData + have := polynomial_sourceTables + tree_cost + +lemma generatedPrepared_source {n : ℕ} [Nontrivial (Fin n)] (hn : 2≤n) + (w : Fin n→Fin n→ℚ) (hw : ∀ a b,0≤w a b) (K D : ℕ) (ft fq : List Bool) : + let x : BagBuildInput:=(((matrixRep w,List.replicate (2*K+2) false),List.range n),List.replicate (2*K) false) + generatedPrepared ((x,D),(ft,fq))= + sourcePrepared (fun l : RationalSource.Label w K=>l.1.val) (RationalSource.parent w K) + (RationalSource.bagWeight w K D) (setupBags x) ft fq := by + dsimp only + unfold generatedPrepared generatedTier + dsimp only + rw [sourceVertices_length,sourceWeights_source hn w hw K D,sourceEdgeData_source hn w hw K, + sourceTables_source hn w hw K] + unfold sourcePrepared + rw [storedCatalog_source _ (setupBags_source hn w hw K)] + +open TreePost Turing + +theorem generatedPrepared_post : ∃ p : Polynomial ℕ,∀ x : GeneratedInput,∀ t : ℕ, + p.eval (packed x).length≤t → ∀ coins : Fin t→Bool, + (run (machine generatedPreparedRealizer.program) (packed x) coins).state=none ∧ + (run (machine generatedPreparedRealizer.program) (packed x) coins).tape.right₀= + ListBlank.mk (packed (generatedPrepared x)) := + polynomial_compiles generatedPreparedRealizer polynomial_generatedPrepared +end MatchingFPRAS.ExecutableSource + +end OAI diff --git a/lean/OAI/Combinatorics/MatchingCount/Algorithm/TreeGeneratedStage.lean b/lean/OAI/Combinatorics/MatchingCount/Algorithm/TreeGeneratedStage.lean new file mode 100644 index 0000000000000000000000000000000000000000..adb54f9228de8991c7400a3383442170e6fb674f --- /dev/null +++ b/lean/OAI/Combinatorics/MatchingCount/Algorithm/TreeGeneratedStage.lean @@ -0,0 +1,146 @@ +import Mathlib +import OAI.Combinatorics.MatchingCount.Algorithm.TreeGeneratedMarked +import OAI.Combinatorics.MatchingCount.Algorithm.TreeReweightTable +import OAI.Combinatorics.MatchingCount.Algorithm.TreeNumericStage +import OAI.Combinatorics.MatchingCount.Algorithm.TreeStatistics + +namespace OAI + +namespace MatchingFPRAS.ExecutableSource +open TreeTyped TreeFraction TreeTyped.Numbered ExecutableBottleneck ExecutableHierarchy ExecutableRefresh Enlargement RealGeometry NumericLadder +open ExecutableLadder UnitRefresh Replica.Ladder Transport NumericMarking ExecutableStatistics + +attribute [local instance] NumberedHierarchy.labelOrder +attribute [local instance] Transport.sym2Order Transport.bagEdgeOrder Transport.bagEdgeFintype +attribute [local instance] UnitRefresh.Computable.allowedDec Transport.prodOrder Transport.sumOrder + +def tableIndex (x : BagBuildInput×Key) : ℕ := (sourceTables x.1).1.idxOf x.2 +def tableIndexRealizer : Realizer tableIndex := keyLookup second + (composition (first (A:=BagBuildInput) (B:=Key)) sourceTablesRealizer).fst +lemma polynomial_tableIndex : PolynomialTime tableIndexRealizer := + polynomial_keyLookup polynomial_second + (polynomial_fst (polynomial_composition polynomial_first polynomial_sourceTables)) +def sourceAllIndices (x : BagBuildInput) : List ℕ := + (sourceTables x).1.map (fun key=>tableIndex (x,key)) +def sourceAllIndicesRealizer : Realizer sourceAllIndices := rowsWith tableIndexRealizer sourceTablesRealizer.fst +lemma polynomial_sourceAllIndices : PolynomialTime sourceAllIndicesRealizer := + polynomial_rowsWith polynomial_tableIndex (polynomial_fst polynomial_sourceTables) +lemma sourceAllIndices_source {n : ℕ} [Nontrivial (Fin n)] (hn : 2≤n) + (w : Fin n→Fin n→ℚ) (hw : ∀ a b,0≤w a b) (K : ℕ) : + sourceAllIndices (((matrixRep w,List.replicate (2*K+2) false),List.range n),List.replicate (2*K) false)= + (List.ofFn (orderedEnum (BagEdge (RationalSource.bags w K)))).map index := by + unfold sourceAllIndices + rw [sourceTables_catalog hn w hw K] + unfold sourceCatalog + rw [List.map_ofFn,List.map_ofFn] + congr 1 + funext i + dsimp only [Function.comp_apply,tableIndex] + rw [sourceTables_catalog hn w hw K,sourceCatalog_index] + +abbrev GeneratedStageData := GeneratedInput×Matrix +abbrev GeneratedStageInput := GeneratedStageData×List SampleBits +def generatedObservables (x : GeneratedStageData) : Reweights×(ℕ×List ℕ) := + (sourceReweights (x.1.1.1,x.2),(x.1.1.2,sourceAllIndices x.1.1.1)) +def generatedReweightArg : Realizer (fun x : GeneratedStageData=>(x.1.1.1,x.2)) := + (pair (first (A:=GeneratedInput) (B:=Matrix)).fst.fst second).congr (fun _=>rfl) +lemma polynomial_generatedReweightArg : PolynomialTime generatedReweightArg := by + unfold generatedReweightArg + apply polynomial_congr + dsimp only [Realizer.fst, Realizer.snd] + tree_cost + +def generatedReweights (x : GeneratedStageData) : Reweights := sourceReweights (x.1.1.1,x.2) +def generatedReweightsRealizer : Realizer generatedReweights := + (composition generatedReweightArg sourceReweightsRealizer).congr (fun _=>rfl) +lemma polynomial_generatedReweights : PolynomialTime generatedReweightsRealizer := + polynomial_congr _ (polynomial_composition polynomial_generatedReweightArg polynomial_sourceReweights) + +def generatedIndexData (x : GeneratedStageData) : ℕ×List ℕ := + (x.1.1.2,sourceAllIndices x.1.1.1) +def generatedIndexDataRealizer : Realizer generatedIndexData := (pair + (first (A:=GeneratedInput) (B:=Matrix)).fst.snd + (composition (first (A:=GeneratedInput) (B:=Matrix)).fst.fst sourceAllIndicesRealizer)).congr (fun _=>rfl) +lemma polynomial_generatedIndexData : PolynomialTime generatedIndexDataRealizer := by + unfold generatedIndexDataRealizer + apply polynomial_congr + dsimp only [Realizer.fst, Realizer.snd] + have := polynomial_sourceAllIndices + tree_cost + +def generatedObservablesRealizer : Realizer generatedObservables := + (TreeTyped.pair generatedReweightsRealizer generatedIndexDataRealizer).congr (fun _=>rfl) +lemma polynomial_generatedObservables : PolynomialTime generatedObservablesRealizer := + polynomial_congr _ (TreeTyped.polynomial_pair polynomial_generatedReweights polynomial_generatedIndexData) + +def generatedStageSetup (x : GeneratedStageData) : (Reweights×(ℕ×List ℕ))×SampleContext := + (generatedObservables x,generatedContext x.1) +def generatedStageSetupRealizer : Realizer generatedStageSetup := (pair generatedObservablesRealizer + (composition first generatedContextRealizer)).congr (fun _=>rfl) +lemma polynomial_generatedStageSetup : PolynomialTime generatedStageSetupRealizer := + polynomial_congr _ (TreeTyped.polynomial_pair polynomial_generatedObservables (polynomial_composition polynomial_first polynomial_generatedContext)) + +def stageWith {A : Type} [Codec A] {f : A→(Reweights×(ℕ×List ℕ))×SampleContext} + (F : Realizer f) : Realizer (fun x : A×List SampleBits=>stage (f x.1,x.2)) := + (composition (pair (composition (first (A:=A) (B:=List SampleBits)) F) second) stageRealizer).congr (fun _=>rfl) +lemma polynomial_stageWith {A : Type} [Codec A] {f : A→(Reweights×(ℕ×List ℕ))×SampleContext} + {F : Realizer f} (hF : PolynomialTime F) : PolynomialTime (stageWith F) := + polynomial_congr _ (polynomial_composition (TreeTyped.polynomial_pair (polynomial_composition polynomial_first hF) polynomial_second) + polynomial_stage) + +def generatedStage (x : GeneratedStageInput) : Fraction×List (ℕ×Fraction) := + stage (generatedStageSetup x.1,x.2) +def generatedStageRealizer : Realizer generatedStage := stageWith generatedStageSetupRealizer +lemma polynomial_generatedStage : PolynomialTime generatedStageRealizer := + polynomial_stageWith polynomial_generatedStageSetup + +lemma generatedStage_source {n : ℕ} [Nontrivial (Fin n)] (hn : 2≤n) (he : Even n) + (w w₁ : Fin n→Fin n→ℚ) (hw : ∀ a b,0(ladderRun (RationalSource.bags_adjacent w K hu) (RationalSource.tree_acyclic w K) + (fun l : RationalSource.Label w K=>l.1.val) (RationalSource.parent w K) + (RationalSource.bags_ranked w K hu) (RationalSource.bags_nonempty w K) + (RationalSource.parent_rank w K) hq (RationalSource.bagWeight w K D) + (RationalSource.startMatching w K he) k r (fun _=>RationalSource.startMatching w K he) (bits j) + (toLex ((0 : Fin (ft.length+1)),(⟨0,hq⟩ : Fin fq.length)))).val + let m := fun j e=>(RationalSource.markingTable w hw K D hD e).draw km (mb j e) + let keys := List.ofFn (orderedEnum (BagEdge (RationalSource.bags w K))) + generatedStage + (((((((matrixRep w,List.replicate (2*K+2) false),List.range n),List.replicate (2*K) false),D),(ft,fq)),matrixRep w₁), + List.ofFn (fun j=>(List.ofFn (fun i=>(List.ofFn (bits j i).1,localBitsRep (bits j i).2)), + keys.map (fun e=>(index e,List.ofFn (mb j e))))))= + (TreeFraction.repr (Counting.ratioEstimate ((∑ i,scalarA s m i)/(S:ℚ)) + ((∑ i,scalarD s m (RationalSource.bagReweight w w₁ K) i)/(S:ℚ))), + keys.map (fun e=>(index e,TreeFraction.repr (Counting.upperEstimate D + ((∑ i,scalarD s m (RationalSource.bagReweight w w₁ K) i)/(S:ℚ)) + ((∑ i,scalarProbe s m (RationalSource.bagReweight w w₁ K) e i)/(S:ℚ)))))) := by + dsimp only + unfold generatedStage generatedStageSetup generatedObservables generatedContext + dsimp only + rw [sourceReweights_source hn w w₁ (fun a b=>(hw a b).le) hw₁ K, + sourceAllIndices_source hn w (fun a b=>(hw a b).le) K, + generatedPrepared_source hn w (fun a b=>(hw a b).le) K D ft fq, + exactStart_source hn he w (fun a b=>(hw a b).le) K,sourceMarks_source hn w hw K D hD] + exact stage_source (RationalSource.bags_adjacent w K hu) (RationalSource.tree_acyclic w K) + (fun l : RationalSource.Label w K=>l.1.val) (RationalSource.parent w K) + (RationalSource.bags_ranked w K hu) (RationalSource.bags_nonempty w K) + (RationalSource.parent_rank w K) ft fq hq (RationalSource.bagWeight w K D) + (bagWeight_nonneg w hw K D) (RationalSource.startMatching w K he) _ + (setupBags_source hn w (fun a b=>(hw a b).le) K) _ _ + (reweight_nonneg w w₁ (fun a b=>(hw a b).le) hw₁ K) D _ bits mb + +open TreePost Turing + +theorem generatedStage_post : ∃ p : Polynomial ℕ,∀ x : GeneratedStageInput,∀ t : ℕ, + p.eval (packed x).length≤t → ∀ coins : Fin t→Bool, + (run (machine generatedStageRealizer.program) (packed x) coins).state=none ∧ + (run (machine generatedStageRealizer.program) (packed x) coins).tape.right₀= + ListBlank.mk (packed (generatedStage x)) := + polynomial_compiles generatedStageRealizer polynomial_generatedStage +end MatchingFPRAS.ExecutableSource + +end OAI diff --git a/lean/OAI/Combinatorics/MatchingCount/Algorithm/TreeGeneratedTop.lean b/lean/OAI/Combinatorics/MatchingCount/Algorithm/TreeGeneratedTop.lean new file mode 100644 index 0000000000000000000000000000000000000000..bd57c73fc325820873013e962eee6078f900e273 --- /dev/null +++ b/lean/OAI/Combinatorics/MatchingCount/Algorithm/TreeGeneratedTop.lean @@ -0,0 +1,71 @@ +import Mathlib +import OAI.Combinatorics.MatchingCount.Algorithm.TreeGeneratedPrepared +import OAI.Combinatorics.MatchingCount.Machines.TreeStart +import OAI.Combinatorics.MatchingCount.Sampling.TreePreparedTop + +namespace OAI + +namespace MatchingFPRAS.ExecutableSource +open TreeTyped TreeFraction TreeTyped.Numbered ExecutableBottleneck ExecutableHierarchy ExecutableRefresh Enlargement RealGeometry NumericLadder +open ExecutableLadder UnitRefresh Replica.Ladder Transport + +attribute [local instance] NumberedHierarchy.labelOrder +attribute [local instance] Transport.sym2Order Transport.bagEdgeOrder Transport.bagEdgeFintype +attribute [local instance] UnitRefresh.Computable.allowedDec Transport.prodOrder Transport.sumOrder + +abbrev GeneratedTopInput := List (List Bool×Bits)×GeneratedInput +def generatedTop (x : GeneratedTopInput) : Finset ℕ := + preparedTop (x.1,(generatedPrepared x.2,exactStart x.2.1.1)) +def generatedTopRealizer : Realizer generatedTop := (composition + (pair first (pair (composition second generatedPreparedRealizer) + (composition second.fst.fst exactStartRealizer))) preparedTopRealizer).congr (fun _=>rfl) +lemma polynomial_generatedTop : PolynomialTime generatedTopRealizer := by + unfold generatedTopRealizer + apply polynomial_congr + dsimp only [Realizer.fst, Realizer.snd] + have := polynomial_generatedPrepared + have := polynomial_exactStart + have := polynomial_preparedTop + tree_cost + +lemma bagWeight_nonneg {n : ℕ} [Nontrivial (Fin n)] + (w : Fin n→Fin n→ℚ) (hw : ∀ a b,0(List.ofFn (bits i).1,localBitsRep (bits i).2)), + (((((matrixRep w,List.replicate (2*K+2) false),List.range n),List.replicate (2*K) false),D),(ft,fq)))= + Numbered.set (ladderRun (RationalSource.bags_adjacent w K hu) (RationalSource.tree_acyclic w K) + (fun l : RationalSource.Label w K=>l.1.val) (RationalSource.parent w K) + (RationalSource.bags_ranked w K hu) (RationalSource.bags_nonempty w K) + (RationalSource.parent_rank w K) hq (RationalSource.bagWeight w K D) + (RationalSource.startMatching w K he) k r (fun _=>RationalSource.startMatching w K he) bits + (toLex ((0 : Fin (ft.length+1)),(⟨0,hq⟩ : Fin fq.length)))).val := by + unfold generatedTop + dsimp only + rw [generatedPrepared_source hn w (fun a b=>(hw a b).le) K D ft fq, + exactStart_source hn he w (fun a b=>(hw a b).le) K] + exact preparedTop_source (RationalSource.bags_adjacent w K hu) (RationalSource.tree_acyclic w K) + (fun l : RationalSource.Label w K=>l.1.val) (RationalSource.parent w K) + (RationalSource.bags_ranked w K hu) (RationalSource.bags_nonempty w K) + (RationalSource.parent_rank w K) ft fq hq (RationalSource.bagWeight w K D) + (bagWeight_nonneg w hw K D) (RationalSource.startMatching w K he) _ + (setupBags_source hn w (fun a b=>(hw a b).le) K) bits + +open TreePost Turing + +theorem generatedTop_post : ∃ p : Polynomial ℕ,∀ x : GeneratedTopInput,∀ t : ℕ, + p.eval (packed x).length≤t → ∀ coins : Fin t→Bool, + (run (machine generatedTopRealizer.program) (packed x) coins).state=none ∧ + (run (machine generatedTopRealizer.program) (packed x) coins).tape.right₀= + ListBlank.mk (packed (generatedTop x)) := + polynomial_compiles generatedTopRealizer polynomial_generatedTop +end MatchingFPRAS.ExecutableSource + +end OAI diff --git a/lean/OAI/Combinatorics/MatchingCount/Algorithm/TreeGeneratedUpdate.lean b/lean/OAI/Combinatorics/MatchingCount/Algorithm/TreeGeneratedUpdate.lean new file mode 100644 index 0000000000000000000000000000000000000000..69e57d3b522ab282ebca4a2b6ee1b10b076b5d94 --- /dev/null +++ b/lean/OAI/Combinatorics/MatchingCount/Algorithm/TreeGeneratedUpdate.lean @@ -0,0 +1,156 @@ +import Mathlib +import OAI.Combinatorics.MatchingCount.Machines.TreeBindings + +namespace OAI + +namespace MatchingFPRAS.ExecutableSource +open TreeTyped TreeFraction TreeTyped.Numbered ExecutableBottleneck ExecutableHierarchy ExecutableRefresh Enlargement RealGeometry NumericLadder +open ExecutableLadder UnitRefresh Replica.Ladder Transport NumericMarking ExecutableStatistics ExecutableScaling + +attribute [local instance] NumberedHierarchy.labelOrder +attribute [local instance] Transport.sym2Order Transport.bagEdgeOrder Transport.bagEdgeFintype +attribute [local instance] UnitRefresh.Computable.allowedDec Transport.prodOrder Transport.sumOrder + +abbrev GeneratedUpdateData := GeneratedStageData×Vector +abbrev GeneratedUpdateInput := GeneratedUpdateData×List SampleBits + +def generatedUpdateArg : Realizer (fun x : GeneratedUpdateData=>(x.1.1.1,x.2)) := + (TreeTyped.pair (first (A:=GeneratedStageData) (B:=Vector)).fst.fst second).congr (fun _=>rfl) +lemma polynomial_generatedUpdateArg : PolynomialTime generatedUpdateArg := by + unfold generatedUpdateArg + apply polynomial_congr + dsimp only [Realizer.fst, Realizer.snd] + tree_cost + +def generatedUpdateSetup (x : GeneratedUpdateData) : UpdateConfig×((Reweights×(ℕ×List ℕ))×SampleContext) := + (generatedUpdateConfig (x.1.1.1,x.2),generatedStageSetup x.1) +def generatedUpdateSetupRealizer : Realizer generatedUpdateSetup := (TreeTyped.pair + (composition generatedUpdateArg generatedUpdateConfigRealizer) + (composition (first (A:=GeneratedStageData) (B:=Vector)) generatedStageSetupRealizer)).congr (fun _=>rfl) +lemma polynomial_generatedUpdateSetup : PolynomialTime generatedUpdateSetupRealizer := + polynomial_congr _ (TreeTyped.polynomial_pair + (polynomial_composition polynomial_generatedUpdateArg polynomial_generatedUpdateConfig) + (polynomial_composition polynomial_first polynomial_generatedStageSetup)) + +def updateWith {A : Type} [Codec A] + {f : A→UpdateConfig×((Reweights×(ℕ×List ℕ))×SampleContext)} (F : Realizer f) : + Realizer (fun x : A×List SampleBits=>stageUpdate ((f x.1).1,((f x.1).2,x.2))) := + (composition (TreeTyped.pair (composition (first (A:=A) (B:=List SampleBits)) F) second) + ((composition (TreeTyped.pair first.fst (TreeTyped.pair first.snd second)) stageUpdateRealizer))).congr (fun _=>rfl) +lemma polynomial_updateWith {A : Type} [Codec A] + {f : A→UpdateConfig×((Reweights×(ℕ×List ℕ))×SampleContext)} + {F : Realizer f} (hF : PolynomialTime F) : PolynomialTime (updateWith F) := by + unfold updateWith + apply polynomial_congr + dsimp only [Realizer.fst, Realizer.snd] + have := polynomial_stageUpdate + tree_cost + +def generatedUpdate (x : GeneratedUpdateInput) : Fraction×Vector := + stageUpdate ((generatedUpdateSetup x.1).1,((generatedUpdateSetup x.1).2,x.2)) +def generatedUpdateRealizer : Realizer generatedUpdate := updateWith generatedUpdateSetupRealizer +lemma polynomial_generatedUpdate : PolynomialTime generatedUpdateRealizer := + polynomial_updateWith polynomial_generatedUpdateSetup + +variable {n : ℕ} [Nontrivial (Fin n)] +noncomputable def generatedSourceSample (he : Even n) (w : Fin n→Fin n→ℚ) + (hw : ∀ a b,0l.1.val) (RationalSource.parent w K) + (RationalSource.bags_ranked w K hu) (RationalSource.bags_nonempty w K) + (RationalSource.parent_rank w K) hq (RationalSource.bagWeight w K D) + (RationalSource.startMatching w K he) k r (fun _=>RationalSource.startMatching w K he) bits + (toLex ((0 : Fin (ft.length+1)),(⟨0,hq⟩ : Fin fq.length)))) + (fun e=>(RationalSource.markingTable w hw K D hD e).draw km (mb e)) + +lemma numericMarks_selected {E : Type} [Fintype E] [LinearOrder E] + (s : Finset E) (m : E→Fin 3) (de : DecidableEq E) : + numericMarks s (@selectedMarks E de s (fun e=>m e.val))=numericMarks s m := by + unfold numericMarks + apply List.map_congr_left + intro e he + have hm : e∈s := (Finset.mem_sort _).mp he + simp only [selectedMarks,hm,↓reduceDIte] + +lemma generatedMarked_sourceSample (hn : 2≤n) (he : Even n) (w : Fin n→Fin n→ℚ) + (hw : ∀ a b,0(List.ofFn (bits z).1,localBitsRep (bits z).2)), + (List.ofFn (orderedEnum (BagEdge (RationalSource.bags w K)))).map (fun e=>(index e,List.ofFn (mb e)))))= + numericMarks x.1.val (selectedMarks x.1.val x.2) := by + dsimp only + rw [generatedMarked_source hn he w hw K D hD hu ft fq hq bits mb] + dsimp only [generatedSourceSample,TableMarking.reveal] + exact (numericMarks_selected (E:=BagEdge (RationalSource.bags w K)) _ _ _).symm + +lemma generatedSamples_source (hn : 2≤n) (he : Even n) (w : Fin n→Fin n→ℚ) + (hw : ∀ a b,0(List.ofFn (fun z=>(List.ofFn (bits i z).1,localBitsRep (bits i z).2)), + (List.ofFn (orderedEnum (BagEdge (RationalSource.bags w K)))).map (fun e=>(index e,List.ofFn (mb i e))))))= + sourceSamples w K (fun i=>generatedSourceSample he w hw K D hD hu ft fq hq (bits i) (mb i)) := by + unfold sampleMany sourceSamples + rw [List.map_ofFn] + apply congrArg List.ofFn + funext i + have hm := generatedMarked_sourceSample hn he w hw K D hD hu ft fq hq (bits i) (mb i) + simpa only [generatedMarked,Function.comp_def] using hm + +lemma generatedUpdate_source {G : GraphInput} [Nontrivial (Fin G.n)] (hn : 2≤G.n) + (he : Even G.n) {j : ℕ} (s : FiniteTrial.ScaleState G j) (K : ℕ) + (hD : 0generatedSourceSample he s.activity s.activity_pos K + (FiniteTrial.sourceD (G:=G) K) hD hu ft fq hq (bits i) (mb i) + let keys := List.ofFn (orderedEnum (BagEdge (RationalSource.bags s.activity K))) + generatedUpdate + ((((((((matrixRep s.activity,List.replicate (2*K+2) false),List.range G.n),List.replicate (2*K) false), + FiniteTrial.sourceD (G:=G) K),(ft,fq)),matrixRep s.nextActivity),vectorRep s.scale), + List.ofFn (fun i=>(List.ofFn (fun z=>(List.ofFn (bits i z).1,localBitsRep (bits i z).2)), + keys.map (fun e=>(index e,List.ofFn (mb i e))))))= + (TreeFraction.repr (s.ratioEstimate x),vectorRep (s.update hn x).scale) := by + dsimp only + let x := fun i=>generatedSourceSample he s.activity s.activity_pos K + (FiniteTrial.sourceD (G:=G) K) hD hu ft fq hq (bits i) (mb i) + unfold generatedUpdate generatedUpdateSetup + rw [generatedUpdateConfig_source hn s K] + unfold stageUpdate generatedStageSetup + dsimp only + rw [generatedSamples_source hn he s.activity s.activity_pos K (FiniteTrial.sourceD (G:=G) K) hD hu ft fq hq bits mb] + unfold generatedObservables + dsimp only + rw [sourceReweights_source hn s.activity s.nextActivity (fun a b=>(s.activity_pos a b).le) + (fun a b=>(s.nextActivity_pos a b).le) K, + sourceAllIndices_source hn s.activity (fun a b=>(s.activity_pos a b).le) K] + exact scaleState_update_rep hn s x + +open TreePost Turing + +theorem generatedUpdate_post : ∃ p : Polynomial ℕ,∀ x : GeneratedUpdateInput,∀ t : ℕ, + p.eval (packed x).length≤t → ∀ coins : Fin t→Bool, + (run (machine generatedUpdateRealizer.program) (packed x) coins).state=none ∧ + (run (machine generatedUpdateRealizer.program) (packed x) coins).tape.right₀= + ListBlank.mk (packed (generatedUpdate x)) := + polynomial_compiles generatedUpdateRealizer polynomial_generatedUpdate +end MatchingFPRAS.ExecutableSource + +end OAI diff --git a/lean/OAI/Combinatorics/MatchingCount/Algorithm/TreeNumericStage.lean b/lean/OAI/Combinatorics/MatchingCount/Algorithm/TreeNumericStage.lean new file mode 100644 index 0000000000000000000000000000000000000000..a0ba2db5e04acc7c36c8fd727bab44e8aca18602 --- /dev/null +++ b/lean/OAI/Combinatorics/MatchingCount/Algorithm/TreeNumericStage.lean @@ -0,0 +1,68 @@ +import Mathlib +import OAI.Combinatorics.MatchingCount.Sampling.TreePreparedMarked +import OAI.Combinatorics.MatchingCount.Algorithm.TreeNumericStatisticsCorrect + +namespace OAI + +namespace MatchingFPRAS.NumericMarking +open TreeTyped TreeFraction TreeTyped.Numbered ExecutableMarking ExecutableStatistics + + ExecutableLadder UnitRefresh NumericLadder Replica.Ladder Transport +abbrev StageInput := ((Reweights×(ℕ×List ℕ))×SampleContext)×List SampleBits + +def stage (x : StageInput) : Fraction×List (ℕ×Fraction) := + statistics (x.1.1,sampleMany (x.1.2,x.2)) +def stageRealizer : Realizer stage := (composition + (pair first.fst (composition (pair first.snd second) sampleManyRealizer)) + statisticsRealizer).congr (fun _=>rfl) +lemma polynomial_stage : PolynomialTime stageRealizer := by + unfold stageRealizer Realizer.fst Realizer.snd + apply polynomial_congr + have := polynomial_sampleMany + have := polynomial_statistics + tree_cost + +theorem stage_post : ∃ p : Polynomial ℕ,∀ x : StageInput,∀ t : ℕ, + p.eval (TreePost.packed x).length≤t → ∀ coins : Fin t→Bool, + (run (TreePost.machine stageRealizer.program) (TreePost.packed x) coins).state=none ∧ + (run (TreePost.machine stageRealizer.program) (TreePost.packed x) coins).tape.right₀= + Turing.ListBlank.mk (TreePost.packed (stage x)) := + TreePost.polynomial_compiles stageRealizer polynomial_stage + +attribute [local instance] Transport.sym2Order Transport.bagEdgeOrder Transport.bagEdgeFintype +attribute [local instance] UnitRefresh.Computable.allowedDec Transport.prodOrder Transport.sumOrder +variable {V L : Type} [Fintype V] [LinearOrder V] [Fintype L] [LinearOrder L] +variable {bags : V→Finset L} {G : SimpleGraph L} +variable (hbags : ∀ v,∀ a∈bags v,∀ b∈bags v,a=b ∨ G.Adj a b) (hG : G.IsAcyclic) +variable (rank : L→ℕ) (parent : L→Option L) +variable (hb : RankedBags bags rank parent) (hne : ∀ v,(bags v).Nonempty) +variable (hp : ∀ l p,parent l=some p → rank p(ladderRun hbags hG rank parent hb hne hp hq w M k n (fun _=>M) (bits j) + (toLex ((0 : Fin (ft.length+1)),(⟨0,hq⟩ : Fin fq.length)))).val + let m := fun j e=>(f e).draw km (mb j e) + stage (((reweightsRep r,(D,keys.map index)), + ((sourcePrepared rank parent w a ft fq,Numbered.set M.val),tableRep f)), + List.ofFn (fun j=> + (List.ofFn (fun i=>(List.ofFn (bits j i).1,localBitsRep (bits j i).2)), + (List.ofFn (orderedEnum (BagEdge bags))).map (fun e=>(index e,List.ofFn (mb j e))))))= + (TreeFraction.repr (Counting.ratioEstimate ((∑ i,scalarA s m i)/(S:ℚ)) + ((∑ i,scalarD s m r i)/(S:ℚ))), + keys.map (fun e=>(index e,TreeFraction.repr (Counting.upperEstimate D + ((∑ i,scalarD s m r i)/(S:ℚ)) ((∑ i,scalarProbe s m r e i)/(S:ℚ)))))) := by + dsimp only + unfold stage sampleMany + dsimp only + rw [List.map_ofFn] + simp only [Function.comp_def,sample_source hbags hG rank parent hb hne hp ft fq hq w hw M a ha f] + exact statistics_rep _ _ r hr D keys + +end MatchingFPRAS.NumericMarking + +end OAI diff --git a/lean/OAI/Combinatorics/MatchingCount/Algorithm/TreeNumericStatistics.lean b/lean/OAI/Combinatorics/MatchingCount/Algorithm/TreeNumericStatistics.lean new file mode 100644 index 0000000000000000000000000000000000000000..8ca233c205cbe211da77d9a5efcbdf000b25b71c --- /dev/null +++ b/lean/OAI/Combinatorics/MatchingCount/Algorithm/TreeNumericStatistics.lean @@ -0,0 +1,68 @@ +import Mathlib +import OAI.Combinatorics.MatchingCount.Sampling.TreeNumericMarking +import OAI.Combinatorics.MatchingCount.Algorithm.TreeStageStatisticsCorrect + +namespace OAI + +namespace MatchingFPRAS.TreeTyped.Numbered +variable {E A : Type} [Fintype E] [LinearOrder E] +def extend (d : A) (f : E→A) (i : ℕ) : A := + if h:iNumbered.set (s j)) (fun j=>extend 0 (m j)) i=scalarA s m i := by + by_cases h : ∀ e∈s i,m i e=0 + · have hh := (zero_numbered (s i) (m i)).mpr h + simp only [scalarA,ite_eq_left h,ite_eq_left hh] + · have hh : ¬∀e∈Numbered.set (s i),extend 0 (m i) e=0 := fun hh=>h ((zero_numbered _ _).mp hh) + simp only [scalarA,ite_eq_right h,ite_eq_right hh] + +lemma scalarD_numbered {S : ℕ} (s : Fin S→Finset E) (m : Fin S→E→Fin 3) (r : E→ℚ) (i : Fin S) : + scalarD (fun j=>Numbered.set (s j)) (fun j=>extend 0 (m j)) (extend 1 r) i=scalarD s m r i := by + by_cases h : ∀ e∈s i,m i e=0 + · have hh := (zero_numbered (s i) (m i)).mpr h + simp only [scalarD,ite_eq_left h,ite_eq_left hh] + simp only [Numbered.set,Finset.prod_map,Numbered.embedding,Function.Embedding.coeFn_mk,extend_index] + · have hh : ¬∀e∈Numbered.set (s i),extend 0 (m i) e=0 := fun hh=>h ((zero_numbered _ _).mp hh) + simp only [scalarD,ite_eq_right h,ite_eq_right hh] + +abbrev Reweights := List (ℕ×Fraction) +def reweight (x : Reweights×ℕ) : Fraction := ExecutableLadder.lookup (1,1) x +def reweightRealizer : Realizer reweight := ExecutableLadder.lookupRealizer (1,1) natEqual +lemma polynomial_reweight : PolynomialTime reweightRealizer := ExecutableLadder.polynomial_lookup (1,1) polynomial_natEqual +abbrev Inputs := (Reweights×(ℕ×List ℕ))×List (Marks ℕ) +def statistics (x : Inputs) : Fraction×List (ℕ×Fraction) := estimates reweight x +def statisticsRealizer : Realizer statistics := estimatesRealizer reweightRealizer natEqual +lemma polynomial_statistics : PolynomialTime statisticsRealizer := polynomial_estimates polynomial_reweight polynomial_natEqual + +theorem statistics_post : ∃ p : Polynomial ℕ,∀ x : Inputs,∀ t : ℕ, + p.eval (TreePost.packed x).length≤t → ∀ coins : Fin t→Bool, + (run (TreePost.machine statisticsRealizer.program) (TreePost.packed x) coins).state=none ∧ + (run (TreePost.machine statisticsRealizer.program) (TreePost.packed x) coins).tape.right₀= + Turing.ListBlank.mk (TreePost.packed (statistics x)) := + TreePost.polynomial_compiles statisticsRealizer polynomial_statistics +end MatchingFPRAS.NumericMarking + +end OAI diff --git a/lean/OAI/Combinatorics/MatchingCount/Algorithm/TreeNumericStatisticsCorrect.lean b/lean/OAI/Combinatorics/MatchingCount/Algorithm/TreeNumericStatisticsCorrect.lean new file mode 100644 index 0000000000000000000000000000000000000000..bca91338fa01c4e131519509503867ee7411a5f6 --- /dev/null +++ b/lean/OAI/Combinatorics/MatchingCount/Algorithm/TreeNumericStatisticsCorrect.lean @@ -0,0 +1,97 @@ +import Mathlib +import OAI.Combinatorics.MatchingCount.Algorithm.TreeNumericStatistics + +namespace OAI + +namespace MatchingFPRAS.NumericMarking +open TreeTyped TreeFraction TreeTyped.Numbered ExecutableMarking ExecutableStatistics ExecutableLadder UnitRefresh + +variable {E : Type} [Fintype E] [LinearOrder E] +lemma probe_numbered (s : Finset E) (m : E→Fin 3) (e : E) : + (index e∈Numbered.set s ∧ ∀ a∈Numbered.set s,extend 0 m a=if a=index e then 2 else 0) ↔ + (e∈s ∧ ∀ a∈s,m a=if a=e then 2 else 0) := by + have hm : index e∈Numbered.set s ↔ e∈s := by + simp only [Numbered.set,Finset.mem_map,Numbered.embedding,Function.Embedding.coeFn_mk] + constructor + · rintro ⟨a,ha,he⟩ + exact index_injective he ▸ ha + · intro h; exact ⟨e,h,rfl⟩ + rw [hm] + apply and_congr_right + intro _he + constructor + · intro h a ha + have hh:=h (index a) (Finset.mem_map.mpr ⟨a,ha,rfl⟩) + simpa only [extend_index,index_injective.eq_iff] using hh + · intro h a ha + obtain ⟨b,hb,rfl⟩:=Finset.mem_map.mp ha + simpa only [Numbered.embedding,Function.Embedding.coeFn_mk,extend_index,index_injective.eq_iff] using h b hb + +lemma scalarProbe_numbered {S : ℕ} (s : Fin S→Finset E) (m : Fin S→E→Fin 3) + (r : E→ℚ) (e : E) (i : Fin S) : + scalarProbe (fun j=>Numbered.set (s j)) (fun j=>extend 0 (m j)) (extend 1 r) (index e) i= + scalarProbe s m r e i := by + by_cases h : e∈s i ∧ ∀ a∈s i,m i a=if a=e then 2 else 0 + · have hh:=(probe_numbered (s i) (m i) e).mpr h + simp only [scalarProbe,ite_eq_left h,ite_eq_left hh] + have hs : Numbered.set (s i)\{index e}=Numbered.set (s i\{e}) := by + simp only [Numbered.set,Finset.map_sdiff,Finset.map_singleton,Numbered.embedding, + Function.Embedding.coeFn_mk] + rw [hs] + simp only [Numbered.set,Finset.prod_map,Numbered.embedding,Function.Embedding.coeFn_mk,extend_index] + · have hh : ¬(index e∈Numbered.set (s i) ∧ ∀ a∈Numbered.set (s i), + extend 0 (m i) a=if a=index e then 2 else 0) := fun hh=>h ((probe_numbered _ _ _).mp hh) + simp only [scalarProbe,ite_eq_right h,ite_eq_right hh] + +noncomputable def reweightsRep (r : E→ℚ) : Reweights := + (List.ofFn (orderedEnum E)).map (fun e=>(index e,TreeFraction.repr (r e))) +lemma reweight_rep (r : E→ℚ) (i : ℕ) : + reweight (reweightsRep r,i)=TreeFraction.repr (extend 1 r i) := by + by_cases h : iTreeFraction.repr (r e)) + index_injective e (List.mem_ofFn.mpr ⟨⟨i,h⟩,rfl⟩),extend_index] + · have hoff : ∀ p∈reweightsRep r,p.1≠i := by + intro p hp + obtain ⟨e,_he,rfl⟩:=List.mem_map.mp hp + intro heq + have hi : index enumericMarks (s i) (m i)))= + (TreeFraction.repr (Counting.ratioEstimate ((∑ i,scalarA s m i)/(S:ℚ)) + ((∑ i,scalarD s m r i)/(S:ℚ))), + keys.map (fun e=>(index e,TreeFraction.repr (Counting.upperEstimate D + ((∑ i,scalarD s m r i)/(S:ℚ)) ((∑ i,scalarProbe s m r e i)/(S:ℚ)))))) := by + have hs : List.ofFn (fun i=>numericMarks (s i) (m i))= + sampleRep (fun i=>Numbered.set (s i)) (fun i=>extend 0 (m i)) := by + simp only [sampleRep,numericMarks_eq] + rw [statistics,hs,estimates_rep (fun i=>Numbered.set (s i)) (fun i=>extend 0 (m i)) + reweight (reweightsRep r) (extend 1 r) (extend_nonneg r hr) (reweight_rep r) D (keys.map index)] + simp only [scalarA_numbered,scalarD_numbered,List.map_map,Function.comp_def,scalarProbe_numbered] + +end MatchingFPRAS.NumericMarking + +end OAI diff --git a/lean/OAI/Combinatorics/MatchingCount/Algorithm/TreeNumericSummaries.lean b/lean/OAI/Combinatorics/MatchingCount/Algorithm/TreeNumericSummaries.lean new file mode 100644 index 0000000000000000000000000000000000000000..82373e49b50d077eaa436abac38fdf14e27a6474 --- /dev/null +++ b/lean/OAI/Combinatorics/MatchingCount/Algorithm/TreeNumericSummaries.lean @@ -0,0 +1,115 @@ +import Mathlib +import OAI.Combinatorics.MatchingCount.Algorithm.TreeNumericStatisticsCorrect +import OAI.Combinatorics.MatchingCount.Arithmetic.TreeAdaptiveArithmetic + +namespace OAI + +namespace MatchingFPRAS.NumericMarking +open TreeTyped TreeFraction TreeTyped.Numbered ExecutableStatistics ExecutableLadder ExecutableEstimator + +abbrev Summaries := (Fraction×Fraction)×List (ℕ×Fraction) + +def rawProbe (x : (Reweights×List (ExecutableMarking.Marks ℕ))×ℕ) : ℕ×Fraction := + (x.2,averageProbe reweight ((x.1.1,x.2),x.1.2)) +def rawProbeRealizer : Realizer rawProbe := (pair second + (composition (pair (pair first.fst second) first.snd) (averageProbeRealizer reweightRealizer natEqual))).congr (fun _=>rfl) +lemma polynomial_rawProbe : PolynomialTime rawProbeRealizer := by + unfold rawProbeRealizer Realizer.fst Realizer.snd + apply polynomial_congr + have := polynomial_averageProbe polynomial_reweight polynomial_natEqual + tree_cost + +def summaries (x : Inputs) : Summaries := + ((ratio (averageA x.2,averageD reweight (x.1.1,x.2)),averageD reweight (x.1.1,x.2)), + x.1.2.2.map (fun e=>rawProbe ((x.1.1,x.2),e))) +def summariesRealizer : Realizer summaries := + (pair (pair (composition (pair (composition second averageARealizer) + (composition (pair first.fst second) (averageDRealizer reweightRealizer))) ratioRealizer) + (composition (pair first.fst second) (averageDRealizer reweightRealizer))) + (composition (pair (pair first.fst second) first.snd.snd) (mapWith rawProbeRealizer))).congr (fun _=>rfl) +lemma polynomial_summaries : PolynomialTime summariesRealizer := by + unfold summariesRealizer Realizer.fst Realizer.snd + apply polynomial_congr + have := polynomial_averageA (E:=ℕ) + have := polynomial_averageD polynomial_reweight + have := polynomial_ratio + have := polynomial_rawProbe + tree_cost + +lemma summaries_rep {E : Type} [Fintype E] [LinearOrder E] {S : ℕ} + (s : Fin S→Finset E) (m : Fin S→E→Fin 3) + (r : E→ℚ) (hr : ∀ e,0≤r e) (D : ℕ) (keys : List E) : + summaries ((reweightsRep r,(D,keys.map index)),List.ofFn (fun i=>numericMarks (s i) (m i)))= + ((TreeFraction.repr (Counting.ratioEstimate ((∑ i,scalarA s m i)/(S:ℚ)) + ((∑ i,scalarD s m r i)/(S:ℚ))),TreeFraction.repr ((∑ i,scalarD s m r i)/(S:ℚ))), + keys.map (fun e=>(index e,TreeFraction.repr ((∑ i,scalarProbe s m r e i)/(S:ℚ))))) := by + have hs : List.ofFn (fun i=>numericMarks (s i) (m i))= + sampleRep (fun i=>Numbered.set (s i)) (fun i=>extend 0 (m i)) := by + simp only [sampleRep,numericMarks_eq] + rw [summaries,hs] + dsimp only + rw [averageA_rep,averageD_rep _ _ reweight (reweightsRep r) (extend 1 r) + (extend_nonneg r hr) (reweight_rep r)] + simp only [scalarA_numbered,scalarD_numbered] + have ha (i : Fin S) : 0 ≤ scalarA s m i := by + unfold scalarA; split_ifs <;> norm_num + have hd (i : Fin S) : 0 ≤ scalarD s m r i := by + unfold scalarD; split_ifs + · exact Finset.prod_nonneg (fun e _=>hr e) + · exact le_rfl + rw [ratio_rep _ _ (div_nonneg (Finset.sum_nonneg (fun i _=>ha i)) (Nat.cast_nonneg _)) + (div_nonneg (Finset.sum_nonneg (fun i _=>hd i)) (Nat.cast_nonneg _))] + congr 1 + rw [List.map_map] + apply List.map_congr_left + intro e _he + unfold rawProbe + dsimp only [Function.comp_def] + rw [averageProbe_rep _ _ reweight (reweightsRep r) (extend 1 r) + (extend_nonneg r hr) (reweight_rep r)] + simp only [scalarProbe_numbered] + +abbrev Bindings := List ((ℕ×ℕ)×ℕ) +def logicalProbes (x : Bindings×List (ℕ×Fraction)) : ExecutableAdaptive.ProbeTable := + x.1.map (fun z=>(z.1,lookup (0,1) (x.2,z.2))) +def logicalProbesRealizer : Realizer logicalProbes := (composition (pair second first) + (mapWith (pair second.fst (composition (pair first second.snd) (lookupRealizer (0,1) natEqual))))).congr (fun _=>rfl) +lemma polynomial_logicalProbes : PolynomialTime logicalProbesRealizer := by + unfold logicalProbesRealizer Realizer.fst Realizer.snd + apply polynomial_congr + have := polynomial_lookup ((0,1) : Fraction) polynomial_natEqual + tree_cost + +lemma logicalProbes_rep {E : Type} [Fintype E] [LinearOrder E] {n : ℕ} + (c : Enlargement.LogicalEdge (Fin n)→E) (keys : List E) (hk : ∀ e,e∈keys) (z : E→ℚ) : + logicalProbes ((List.ofFn (UnitRefresh.orderedEnum (Enlargement.LogicalEdge (Fin n)))).map + (fun e=>(ExecutableSource.logicalRepr e,index (c e))), + keys.map (fun e=>(index e,TreeFraction.repr (z e))))= + (List.ofFn (UnitRefresh.orderedEnum (Enlargement.LogicalEdge (Fin n)))).map + (fun e=>(ExecutableSource.logicalRepr e,TreeFraction.repr (z (c e)))) := by + unfold logicalProbes + rw [List.map_map] + apply List.map_congr_left + intro e _he + dsimp only [Function.comp_def] + rw [lookup_image (0,1) keys index (fun e=>TreeFraction.repr (z e)) index_injective (c e) (hk _)] + +abbrev UpdateConfig := (ℕ×List ℕ)×(Bindings×ExecutableScaling.Vector) +def finishUpdate (x : UpdateConfig×Summaries) : Fraction×ExecutableScaling.Vector := + (x.2.1.1,ExecutableAdaptive.updateVector + (ExecutableAdaptive.estimateMatrix (((x.1.1.1,x.2.1.2),logicalProbes (x.1.2.1,x.2.2)),x.1.1.2),x.1.2.2)) +def finishUpdateRealizer : Realizer finishUpdate := (pair second.fst.fst + (composition (pair (composition (pair (pair (pair first.fst.fst second.fst.snd) + (composition (pair first.snd.fst second.snd) logicalProbesRealizer)) first.fst.snd) + ExecutableAdaptive.estimateMatrixRealizer) first.snd.snd) ExecutableAdaptive.updateVectorRealizer)).congr (fun _=>rfl) +lemma polynomial_finishUpdate : PolynomialTime finishUpdateRealizer := by + unfold finishUpdateRealizer Realizer.fst Realizer.snd + apply polynomial_congr + have := polynomial_logicalProbes + have := ExecutableAdaptive.polynomial_estimateMatrix + have := ExecutableAdaptive.polynomial_updateVector + tree_cost + +end MatchingFPRAS.NumericMarking + +end OAI diff --git a/lean/OAI/Combinatorics/MatchingCount/Algorithm/TreeObservables.lean b/lean/OAI/Combinatorics/MatchingCount/Algorithm/TreeObservables.lean new file mode 100644 index 0000000000000000000000000000000000000000..da838eac33eb7f110f662ddd4484161a2a085f57 --- /dev/null +++ b/lean/OAI/Combinatorics/MatchingCount/Algorithm/TreeObservables.lean @@ -0,0 +1,115 @@ +import Mathlib +import OAI.Combinatorics.MatchingCount.Sampling.TreeMarking + +namespace OAI + +namespace MatchingFPRAS.ExecutableMarking +open TreeTyped TreeFraction + +variable {C E : Type} [Codec C] [Codec E] [LinearOrder E] [Inhabited E] + +def zeroMarks (xs : Marks E) : Bool := xs.all (fun z=>decide (z.2=0)) +def zeroMarksRealizer : Realizer (zeroMarks (E:=E)) := + (composition (map (composition (pair second (constant 0)) natEqual)) all).congr (by + intro xs; simp only [zeroMarks,Function.comp_def,List.all_map,Function.id_def]) +omit [Codec C] [LinearOrder E] [Inhabited E] in +lemma polynomial_zeroMarks : PolynomialTime (zeroMarksRealizer (E:=E)) := by + unfold zeroMarksRealizer + apply polynomial_congr + have := polynomial_all + tree_cost + +def probeExpected (x : E×(E×ℕ)) : ℕ := if x.2.1=x.1 then 2 else 0 +def probeExpectedRealizer (Eq : Realizer (fun x : E×E=>decide (x.1=x.2))) : + Realizer (probeExpected (E:=E)) := + (choose (composition (pair second.fst first) Eq) (constant 2) (constant 0)).congr (by + intro x; simp only [probeExpected,Function.comp_apply,decide_eq_true_eq]) +omit [Codec C] [Inhabited E] in +lemma polynomial_probeExpected {Eq : Realizer (fun x : E×E=>decide (x.1=x.2))} + (hE : PolynomialTime Eq) : PolynomialTime (probeExpectedRealizer Eq) := by + unfold probeExpectedRealizer Realizer.fst + apply polynomial_congr + tree_cost + +def probeFlag (x : E×Marks E) : Bool := + x.2.any (fun z=>decide (z.1=x.1)) && x.2.all (fun z=>decide (z.2=probeExpected (x.1,z))) +def probeFlagRealizer (Eq : Realizer (fun x : E×E=>decide (x.1=x.2))) : Realizer (probeFlag (E:=E)) := + (composition (pair (composition (mapWith (composition (pair second.fst first) Eq)) any) + (composition (mapWith (composition (pair second.snd (probeExpectedRealizer Eq)) natEqual)) all)) boolAnd).congr (by + intro x; simp only [probeFlag,Function.comp_def,List.any_map,List.all_map,Function.id_def]) +omit [Codec C] [Inhabited E] in +lemma polynomial_probeFlag {Eq : Realizer (fun x : E×E=>decide (x.1=x.2))} + (hE : PolynomialTime Eq) : PolynomialTime (probeFlagRealizer Eq) := by + unfold probeFlagRealizer Realizer.fst Realizer.snd + apply polynomial_congr + have := polynomial_probeExpected hE + have := polynomial_all + have := polynomial_any + tree_cost + +def weighted (q : C×E→Fraction) (x : C×Marks E) : Fraction := + product (x.2.map (fun z=>q (x.1,z.1))) +def weightedRealizer {q : C×E→Fraction} (Q : Realizer q) : Realizer (weighted q) := + (composition (mapWith (composition (pair first second.fst) Q)) productRealizer).congr (fun _=>rfl) +omit [LinearOrder E] [Inhabited E] in +lemma polynomial_weighted {q : C×E→Fraction} {Q : Realizer q} (hQ : PolynomialTime Q) : + PolynomialTime (weightedRealizer Q) := by + unfold weightedRealizer Realizer.fst + apply polynomial_congr + have := polynomial_product + tree_cost + +def observableA (x : Marks E) : Fraction := if zeroMarks x then (1,1) else (0,1) +def observableARealizer : Realizer (observableA (E:=E)) := + (choose zeroMarksRealizer (constant (1,1)) (constant (0,1))).congr (fun _=>rfl) +omit [Codec C] [LinearOrder E] [Inhabited E] in +lemma polynomial_observableA : PolynomialTime (observableARealizer (E:=E)) := by + unfold observableARealizer + apply polynomial_congr + have := polynomial_zeroMarks (E:=E) + tree_cost + +def observableD (q : C×E→Fraction) (x : C×Marks E) : Fraction := + if zeroMarks x.2 then weighted q x else (0,1) +def observableDRealizer {q : C×E→Fraction} (Q : Realizer q) : Realizer (observableD q) := + (choose (composition second zeroMarksRealizer) (weightedRealizer Q) (constant (0,1))).congr (fun _=>rfl) +omit [LinearOrder E] [Inhabited E] in +lemma polynomial_observableD {q : C×E→Fraction} {Q : Realizer q} (hQ : PolynomialTime Q) : + PolynomialTime (observableDRealizer Q) := by + unfold observableDRealizer + apply polynomial_congr + have := polynomial_zeroMarks (E:=E) + have := polynomial_weighted hQ + tree_cost + +def eraseMark (x : E×Marks E) : Marks E := x.2.filter (fun z=>decide (z.1≠x.1)) +def eraseMarkRealizer (Eq : Realizer (fun x : E×E=>decide (x.1=x.2))) : Realizer (eraseMark (E:=E)) := + (filterWith (composition (composition (pair second.fst first) Eq) boolNot)).congr (by + intro x; simp only [eraseMark,Function.comp_apply,decide_not]) +omit [Codec C] [Inhabited E] in +lemma polynomial_eraseMark {Eq : Realizer (fun x : E×E=>decide (x.1=x.2))} + (hE : PolynomialTime Eq) : PolynomialTime (eraseMarkRealizer Eq) := by + unfold eraseMarkRealizer Realizer.fst + apply polynomial_congr + apply polynomial_filterWithList + tree_cost + +def observableProbe (q : C×E→Fraction) (x : C×(E×Marks E)) : Fraction := + if probeFlag x.2 then weighted q (x.1,eraseMark x.2) else (0,1) +def observableProbeRealizer {q : C×E→Fraction} (Q : Realizer q) + (Eq : Realizer (fun x : E×E=>decide (x.1=x.2))) : Realizer (observableProbe q) := + (choose (composition second (probeFlagRealizer Eq)) + (composition (pair first (composition second (eraseMarkRealizer Eq))) (weightedRealizer Q)) (constant (0,1))).congr (fun _=>rfl) +omit [Inhabited E] in +lemma polynomial_observableProbe {q : C×E→Fraction} {Q : Realizer q} + {Eq : Realizer (fun x : E×E=>decide (x.1=x.2))} + (hQ : PolynomialTime Q) (hE : PolynomialTime Eq) : PolynomialTime (observableProbeRealizer Q Eq) := by + unfold observableProbeRealizer + apply polynomial_congr + have := polynomial_probeFlag hE + have := polynomial_eraseMark hE + have := polynomial_weighted hQ + tree_cost +end MatchingFPRAS.ExecutableMarking + +end OAI diff --git a/lean/OAI/Combinatorics/MatchingCount/Algorithm/TreeObservablesCorrect.lean b/lean/OAI/Combinatorics/MatchingCount/Algorithm/TreeObservablesCorrect.lean new file mode 100644 index 0000000000000000000000000000000000000000..837f25ad55807a20a012ae69707a075c52ee30d4 --- /dev/null +++ b/lean/OAI/Combinatorics/MatchingCount/Algorithm/TreeObservablesCorrect.lean @@ -0,0 +1,82 @@ +import Mathlib +import OAI.Combinatorics.MatchingCount.Machines.TreeRationalWeight +import OAI.Combinatorics.MatchingCount.Algorithm.TreeObservables + +namespace OAI + +namespace MatchingFPRAS.ExecutableMarking +open TreeTyped TreeFraction + +variable {C E : Type} [LinearOrder E] + +lemma zeroMarks_rep (s : Finset E) (m : E→Fin 3) : + zeroMarks (marksRep s m)=true ↔ ∀ e∈s,m e=0 := by + simp only [zeroMarks,marksRep,List.all_map,List.all_eq_true,Function.comp_apply, + decide_eq_true_eq,Finset.mem_sort] + constructor + · intro h e he; exact Fin.ext (h e he) + · intro h e he; exact congrArg Fin.val (h e he) + +lemma probeFlag_rep (s : Finset E) (m : E→Fin 3) (e : E) : + probeFlag (e,marksRep s m)=true ↔ e∈s ∧ ∀ a∈s,m a=if a=e then 2 else 0 := by + simp only [probeFlag,marksRep,Bool.and_eq_true,List.any_map,List.all_map,List.any_eq_true, + List.all_eq_true,Function.comp_def,probeExpected] + constructor + · rintro ⟨⟨a,ha,hae⟩,h⟩ + have hae' : a=e := of_decide_eq_true hae + subst a + refine ⟨(Finset.mem_sort (·≤·)).mp ha,fun b hb=>Fin.ext ?_⟩ + have hh:=of_decide_eq_true (h b ((Finset.mem_sort (·≤·)).mpr hb)) + by_cases hbe : b=e <;> simp [hbe] at hh ⊢ <;> exact hh + · rintro ⟨he,h⟩ + refine ⟨⟨e,(Finset.mem_sort (·≤·)).mpr he,by simp⟩,fun b hb=>?_⟩ + apply decide_eq_true + have hh:=congrArg Fin.val (h b ((Finset.mem_sort (·≤·)).mp hb)) + by_cases hbe : b=e <;> simp [hbe] at hh ⊢ <;> exact hh + +lemma weighted_rep (q : C×E→Fraction) (c : C) (r : E→ℚ) + (hr : ∀ e,0≤r e) (hq : ∀ e,q (c,e)=TreeFraction.repr (r e)) + (s : Finset E) (m : E→Fin 3) : + weighted q (c,marksRep s m)=TreeFraction.repr (∏ e∈s,r e) := by + unfold weighted marksRep + simp only [List.map_map] + exact TreeTyped.SparseProgram.weight_repr q c r hr hq s + +lemma eraseMark_rep (s : Finset E) (m : E→Fin 3) (e : E) : + eraseMark (e,marksRep s m)=marksRep (s\{e}) m := by + unfold eraseMark marksRep + simp only [List.filter_map] + congr 1 + apply List.Pairwise.eq_of_mem_iff (s.sortedLT_sort.pairwise.filter _) (Finset.sortedLT_sort _).pairwise + intro a + simp + +lemma observableA_rep (s : Finset E) (m : E→Fin 3) : + observableA (marksRep s m)=TreeFraction.repr (if ∀ e∈s,m e=0 then (1:ℚ) else 0) := by + unfold observableA + simp only [zeroMarks_rep] + split_ifs <;> rfl +lemma observableD_rep (q : C×E→Fraction) (c : C) (r : E→ℚ) + (hr : ∀ e,0≤r e) (hq : ∀ e,q (c,e)=TreeFraction.repr (r e)) + (s : Finset E) (m : E→Fin 3) : + observableD q (c,marksRep s m)= + TreeFraction.repr (if ∀ e∈s,m e=0 then ∏ e∈s,r e else 0) := by + unfold observableD + simp only [zeroMarks_rep] + split_ifs + · exact weighted_rep q c r hr hq s m + · rfl +lemma observableProbe_rep (q : C×E→Fraction) (c : C) (r : E→ℚ) + (hr : ∀ e,0≤r e) (hq : ∀ e,q (c,e)=TreeFraction.repr (r e)) + (s : Finset E) (m : E→Fin 3) (e : E) : + observableProbe q (c,(e,marksRep s m))= + TreeFraction.repr (if e∈s ∧ ∀ a∈s,m a=if a=e then 2 else 0 then ∏ a∈s\{e},r a else 0) := by + unfold observableProbe + simp only [probeFlag_rep] + split_ifs + · rw [eraseMark_rep] + exact weighted_rep q c r hr hq _ m + · rfl +end MatchingFPRAS.ExecutableMarking + +end OAI diff --git a/lean/OAI/Combinatorics/MatchingCount/Algorithm/TreeReweight.lean b/lean/OAI/Combinatorics/MatchingCount/Algorithm/TreeReweight.lean new file mode 100644 index 0000000000000000000000000000000000000000..a1dfc1c056ff54006b50ed88ccb8c3949d87d310 --- /dev/null +++ b/lean/OAI/Combinatorics/MatchingCount/Algorithm/TreeReweight.lean @@ -0,0 +1,98 @@ +import Mathlib +import OAI.Combinatorics.MatchingCount.Algorithm.RationalObservables +import OAI.Combinatorics.MatchingCount.Arithmetic.TreeFractionExtra +import OAI.Combinatorics.MatchingCount.Machines.TreeStateTable +import OAI.Combinatorics.MatchingCount.Graphs.TreeGeometry + +namespace OAI + +namespace MatchingFPRAS.ExecutableSource +open TreeTyped TreeFraction ExecutableBottleneck ExecutableLadder Enlargement RealGeometry + +abbrev ReweightData := (Matrix×Matrix)×List Bool + +def rawReweight (x : ReweightData×RawReal) : Fraction := + if x.2.2=2*x.1.2.length then div (cell (x.1.1.2,x.2.1),cell (x.1.1.1,x.2.1)) else (1,1) +def rawReweightRealizer : Realizer rawReweight := + (choose (composition (pair second.snd (composition + (pair (constant 2) (composition first.snd listLength)) multiply)) natEqual) + (composition (pair (composition (pair first.fst.snd second.fst) cellRealizer) + (composition (pair first.fst.fst second.fst) cellRealizer)) divRealizer) + (constant (1,1))).congr (by intro x; simp only [rawReweight,Function.comp_apply,decide_eq_true_eq]) +lemma polynomial_rawReweight : PolynomialTime rawReweightRealizer := by + unfold rawReweightRealizer Realizer.fst Realizer.snd + apply polynomial_congr + have := polynomial_cell + have := polynomial_div + tree_cost +lemma rawReweight_rep {n : ℕ} (w w₁ : Fin n→Fin n→ℚ) + (hw : ∀ i j,0≤w i j) (hw₁ : ∀ i j,0≤w₁ i j) (K : ℕ) + (fuel : List Bool) (hf : fuel.length=2*K+2) (e : SourceRealEdge (Fin n) K) : + rawReweight (((matrixRep w,matrixRep w₁),fuel),(logicalRepr e.1,e.2.val))= + TreeFraction.repr (RationalSource.rawReweight w w₁ K e) := by + unfold rawReweight RationalSource.rawReweight + dsimp only + rw [hf] + split_ifs + · dsimp only [logicalRepr] + rw [cell_matrixRep,cell_matrixRep,div_repr (hw₁ _ _) (hw _ _)] + congr 1 + have hp : source e.1rfl) +omit [DecidableEq E] [Inhabited E] in +lemma polynomial_reweightRow {color : C×RawReal→E} {F : Realizer color} (hF : PolynomialTime F) : + PolynomialTime (reweightRowRealizer F) := by + unfold reweightRowRealizer Realizer.fst Realizer.snd + apply polynomial_congr + have := polynomial_rawReweight + tree_cost + +def reweightTable (color : C×RawReal→E) (x : (C×ReweightData)×List RawReal) : List (E×Fraction) := + x.2.map (fun r=>reweightRow color (x.1,r)) +def reweightTableRealizer {color : C×RawReal→E} (F : Realizer color) : Realizer (reweightTable color) := + mapWith (reweightRowRealizer F) +omit [DecidableEq E] [Inhabited E] in +lemma polynomial_reweightTable {color : C×RawReal→E} {F : Realizer color} (hF : PolynomialTime F) : + PolynomialTime (reweightTableRealizer F) := polynomial_mapWith (polynomial_reweightRow hF) + +def bagReweight (x : List (E×Fraction)×E) : Fraction := lookup (1,1) x +def bagReweightRealizer (Eq : Realizer (fun x : E×E=>decide (x.1=x.2))) : Realizer (bagReweight (E:=E)) := + lookupRealizer (1,1) Eq +omit [Codec C] in +lemma polynomial_bagReweight {Eq : Realizer (fun x : E×E=>decide (x.1=x.2))} + (hE : PolynomialTime Eq) : PolynomialTime (bagReweightRealizer Eq) := polynomial_lookup _ hE +end MatchingFPRAS.ExecutableSource + +namespace MatchingFPRAS.ExecutableLadder +lemma lookup_image {I E A : Type} [DecidableEq E] (d : A) (keys : List I) + (f : I→E) (g : I→A) (hf : Function.Injective f) (i : I) (hi : i∈keys) : + lookup d (keys.map (fun j=>(f j,g j)),f i)=g i := by + induction keys with + | nil=>simp at hi + | cons j keys ih=> + by_cases hji : j=i + · subst j; simp [lookup] + · have hne : f j≠f i:=fun h=>hji (hf h) + have hi' : i∈keys:=(List.mem_cons.mp hi).resolve_left (Ne.symm hji) + simpa [lookup,hne] using ih hi' +lemma lookup_off {I E A : Type} [DecidableEq E] (d : A) (keys : List I) + (f : I→E) (g : I→A) (e : E) (he : ∀ i∈keys,f i≠e) : + lookup d (keys.map (fun j=>(f j,g j)),e)=d := by + induction keys with + | nil=>simp [lookup] + | cons i keys ih=> + have hne:=he i (by simp) + have ht:=ih (fun j hj=>he j (by simp [hj])) + simpa [lookup,hne] using ht +end MatchingFPRAS.ExecutableLadder + +end OAI diff --git a/lean/OAI/Combinatorics/MatchingCount/Algorithm/TreeReweightTable.lean b/lean/OAI/Combinatorics/MatchingCount/Algorithm/TreeReweightTable.lean new file mode 100644 index 0000000000000000000000000000000000000000..dbc7da1d4c6aaa3b1e4bc21e0414368c598a1360 --- /dev/null +++ b/lean/OAI/Combinatorics/MatchingCount/Algorithm/TreeReweightTable.lean @@ -0,0 +1,142 @@ +import Mathlib +import OAI.Combinatorics.MatchingCount.Machines.TreeWeightTable +import OAI.Combinatorics.MatchingCount.Algorithm.TreeNumericStatisticsCorrect + +namespace OAI + +namespace MatchingFPRAS.ExecutableLadder +lemma lookup_valid {A E B : Type} [DecidableEq E] (d : B) (xs : List A) + (key : A→E) (value : A→B) (e : E) (b : B) + (hv : ∀ a∈xs,key a=e→value a=b) + (hd : (∀ a∈xs,key a≠e)→d=b) : + lookup d (xs.map (fun a=>(key a,value a)),e)=b := by + induction xs with + | nil => simpa [lookup] using hd (by simp) + | cons a xs ih => + by_cases h : key a=e + · simpa [lookup,h] using hv a (by simp) h + · have hm:=ih (fun z hz=>hv z (by simp [hz])) + (fun hh=>hd (by intro z hz; rcases List.mem_cons.mp hz with rfl|hz; exact h; exact hh z hz)) + simpa [lookup,h] using hm +end MatchingFPRAS.ExecutableLadder + +namespace MatchingFPRAS.ExecutableSource +open TreeTyped TreeFraction TreeTyped.Numbered ExecutableBottleneck ExecutableHierarchy ExecutableRefresh Enlargement RealGeometry ExecutableLadder + +attribute [local instance] NumberedHierarchy.labelOrder +attribute [local instance] Transport.sym2Order Transport.bagEdgeOrder Transport.bagEdgeFintype +abbrev SourceReweightInput := BagBuildInput×Matrix + +def sourceReweightData (x : SourceReweightInput) : ReweightData := + ((x.1.1.1.1,x.2),x.1.1.1.2) +def sourceReweightDataRealizer : Realizer sourceReweightData := (pair + (pair first.fst.fst.fst second) first.fst.fst.snd).congr (fun _=>rfl) +lemma polynomial_sourceReweightData : PolynomialTime sourceReweightDataRealizer := by + unfold sourceReweightDataRealizer Realizer.fst Realizer.snd + apply polynomial_congr + tree_cost + +def sourceReweightRows (x : SourceReweightInput) : List (Key×Fraction) := + reweightTable sourceRealKey ((x.1,sourceReweightData x),realEdges (x.1.1.2,x.1.1.1.2)) +def sourceReweightRowsRealizer : Realizer sourceReweightRows := (composition + (pair (pair first sourceReweightDataRealizer) + (composition (pair first.fst.snd first.fst.fst.snd) realEdgesRealizer)) + (reweightTableRealizer sourceRealKeyRealizer)).congr (fun _=>rfl) +lemma polynomial_sourceReweightRows : PolynomialTime sourceReweightRowsRealizer := by + unfold sourceReweightRowsRealizer Realizer.fst Realizer.snd + apply polynomial_congr + have := polynomial_sourceReweightData + have := polynomial_realEdges + have := polynomial_reweightTable polynomial_sourceRealKey + tree_cost + +def sourceReweightValue (x : SourceReweightInput×Key) : Fraction := + lookup (1,1) (sourceReweightRows x.1,x.2) +def sourceReweightValueRealizer : Realizer sourceReweightValue := (composition + (pair (composition first sourceReweightRowsRealizer) second) + (lookupRealizer (1,1) (pairEqual (pairEqual natEqual natEqual) natEqual))).congr (fun _=>rfl) +lemma polynomial_sourceReweightValue : PolynomialTime sourceReweightValueRealizer := by + unfold sourceReweightValueRealizer + apply polynomial_congr + have := polynomial_sourceReweightRows + have := polynomial_lookup ((1,1) : Fraction) + (polynomial_pairEqual (polynomial_pairEqual polynomial_natEqual polynomial_natEqual) polynomial_natEqual) + tree_cost + +lemma sourceReweightValue_source {n : ℕ} [Nontrivial (Fin n)] (hn : 2≤n) + (w w₁ : Fin n→Fin n→ℚ) (hw : ∀ a b,0≤w a b) (hw₁ : ∀ a b,0≤w₁ a b) + (K : ℕ) (e : Transport.BagEdge (RationalSource.bags w K)) : + sourceReweightValue (((((matrixRep w,List.replicate (2*K+2) false),List.range n),List.replicate (2*K) false),matrixRep w₁),sourceKey e)= + TreeFraction.repr (RationalSource.bagReweight w w₁ K e) := by + unfold sourceReweightValue sourceReweightRows reweightTable reweightRow sourceReweightData + dsimp only + apply lookup_valid + · intro a ha he + have hm : a∈(realEdges (List.range n,List.replicate (2*K+2) false)).toFinset:=List.mem_toFinset.mpr ha + rw [realEdges_finset n K _ (List.length_replicate ..)] at hm + obtain ⟨q,_,rfl⟩:=Finset.mem_image.mp hm + rw [sourceRealKey_source hn w hw K] at he + have hq:=sourceKey_injective he + change rawReweight (((matrixRep w,matrixRep w₁),List.replicate (2*K+2) false), + (logicalRepr q.1,q.2.val))=_ + rw [rawReweight_rep w w₁ hw hw₁ K _ (List.length_replicate ..)] + rw [←hq,RationalSource.bagReweight_on] + · intro hoff + have he : ¬∃q,RationalSource.coloredReal w K q=e := by + rintro ⟨q,hq⟩ + have hm : realRepr q∈realEdges (List.range n,List.replicate (2*K+2) false) := by + apply List.mem_toFinset.mp + rw [realEdges_finset n K _ (List.length_replicate ..)] + exact Finset.mem_image.mpr ⟨q,Finset.mem_univ _,rfl⟩ + have hh:=hoff (realRepr q) hm + apply hh + rw [sourceRealKey_source hn w hw K,hq] + rw [RationalSource.bagReweight_off w w₁ K e he] + rfl + +def sourceReweightEntry (x : SourceReweightInput×Key) : ℕ×Fraction := + ((sourceTables x.1.1).1.idxOf x.2,sourceReweightValue x) +def sourceReweightEntryRealizer : Realizer sourceReweightEntry := (pair + (keyLookup second (composition first.fst sourceTablesRealizer).fst) + sourceReweightValueRealizer).congr (fun _=>rfl) +lemma polynomial_sourceReweightEntry : PolynomialTime sourceReweightEntryRealizer := by + unfold sourceReweightEntryRealizer + apply polynomial_congr + exact polynomial_pair (polynomial_keyLookup polynomial_second + (polynomial_fst (polynomial_composition (polynomial_fst polynomial_first) polynomial_sourceTables))) + polynomial_sourceReweightValue + +def sourceReweights (x : SourceReweightInput) : NumericMarking.Reweights := + (sourceTables x.1).1.map (fun key=>sourceReweightEntry (x,key)) +def sourceReweightsRealizer : Realizer sourceReweights := rowsWith sourceReweightEntryRealizer + (composition (first (A:=BagBuildInput) (B:=Matrix)) sourceTablesRealizer).fst +lemma polynomial_sourceReweights : PolynomialTime sourceReweightsRealizer := + polynomial_rowsWith polynomial_sourceReweightEntry + (polynomial_fst (polynomial_composition polynomial_first polynomial_sourceTables)) +lemma sourceReweights_source {n : ℕ} [Nontrivial (Fin n)] (hn : 2≤n) + (w w₁ : Fin n→Fin n→ℚ) (hw : ∀ a b,0≤w a b) (hw₁ : ∀ a b,0≤w₁ a b) (K : ℕ) : + sourceReweights ((((matrixRep w,List.replicate (2*K+2) false),List.range n),List.replicate (2*K) false),matrixRep w₁)= + NumericMarking.reweightsRep (RationalSource.bagReweight w w₁ K) := by + unfold sourceReweights NumericMarking.reweightsRep + dsimp only + rw [sourceTables_catalog hn w hw K] + unfold sourceCatalog + rw [List.map_ofFn,List.map_ofFn] + congr 1 + funext i + unfold sourceReweightEntry + dsimp only [Function.comp_apply] + rw [sourceTables_catalog hn w hw K,sourceCatalog_index, + sourceReweightValue_source hn w w₁ hw hw₁ K] + +open TreePost Turing + +theorem sourceReweights_post : ∃ p : Polynomial ℕ,∀ x : SourceReweightInput,∀ t : ℕ, + p.eval (packed x).length≤t → ∀ coins : Fin t→Bool, + (run (machine sourceReweightsRealizer.program) (packed x) coins).state=none ∧ + (run (machine sourceReweightsRealizer.program) (packed x) coins).tape.right₀= + ListBlank.mk (packed (sourceReweights x)) := + polynomial_compiles sourceReweightsRealizer polynomial_sourceReweights +end MatchingFPRAS.ExecutableSource + +end OAI diff --git a/lean/OAI/Combinatorics/MatchingCount/Algorithm/TreeScaling.lean b/lean/OAI/Combinatorics/MatchingCount/Algorithm/TreeScaling.lean new file mode 100644 index 0000000000000000000000000000000000000000..51db9519002e9f5276c1dea26cd2cdf7c2a91aeb --- /dev/null +++ b/lean/OAI/Combinatorics/MatchingCount/Algorithm/TreeScaling.lean @@ -0,0 +1,201 @@ +import Mathlib +import OAI.Combinatorics.MatchingCount.Machines.TreeStateTable + +namespace OAI + +namespace MatchingFPRAS.TreeFraction +open TreeTyped + +lemma height_div (a b : Fraction) : height (div (a,b))≤height a+height b+1 := by + have hn:=normalize_size_num (a.1*b.2,a.2*b.1) + have hd:=normalize_size_den (a.1*b.2,a.2*b.1) + have hm:=nat_size_mul a.1 b.2 + have hm':=nat_size_mul a.2 b.1 + have ha:=le_max_left a.1.size a.2.size + have ha':=le_max_right a.1.size a.2.size + have hb:=le_max_left b.1.size b.2.size + have hb':=le_max_right b.1.size b.2.size + dsimp only at hn hd + change (div (a,b)).1.size≤_ at hn + change (div (a,b)).2.size≤_ at hd + unfold height + apply max_le <;> omega +lemma maximum_height (a b : Fraction) : height (maximum (a,b))≤ max (height a) (height b) := by + rcases maximum_eq a b with h|h <;> rw [h] + · exact le_max_left _ _ + · exact le_max_right _ _ +lemma maximum_fold_height (xs : List Fraction) (z : Fraction) (B : ℕ) + (hz : height z≤B) (hx : ∀ x∈xs,height x≤B) : + height (xs.foldl (fun z x=>maximum (x,z)) z)≤B := by + induction xs generalizing z with + | nil=>exact hz + | cons x xs ih=> + apply ih _ ((maximum_height x z).trans (max_le (hx x (by simp)) hz)) + intro x hx'; exact hx x (by simp [hx']) +end MatchingFPRAS.TreeFraction + +namespace MatchingFPRAS.ExecutableScaling +open TreeTyped TreeFraction ExecutableBottleneck ExecutableLadder Polynomial + +abbrev Vector := List (ℕ×Fraction) +abbrev State := Matrix×Vector + +def ratio (x : (Matrix×ℕ)×(ℕ×Fraction)) : Fraction := + div (cell (x.1.1,(x.1.2,x.2.1)),x.2.2) +def ratioRealizer : Realizer ratio := composition (pair + (composition (pair first.fst (pair first.snd second.fst)) cellRealizer) + second.snd) divRealizer +lemma polynomial_ratio : PolynomialTime ratioRealizer := by + unfold ratioRealizer + apply polynomial_composition _ polynomial_div + apply polynomial_pair _ (polynomial_snd polynomial_second) + apply polynomial_composition _ polynomial_cell + dsimp only [Realizer.fst,Realizer.snd] + tree_cost + +def rowMax (x : State×ℕ) : Fraction := + ((x.1.2.filter (fun z=>decide (z.1≠x.2))).map (fun z=>ratio ((x.1.1,x.2),z))).foldl + (fun a b=>maximum (b,a)) (0,1) +def rowMaxRealizer : Realizer rowMax := by + let neq : Realizer (fun z : ℕ×(ℕ×Fraction)=>decide (z.2.1≠z.1)) := + (composition (composition (pair second.fst first) natEqual) boolNot).congr (by intro x; simp) + let vs : Realizer (fun x : State×ℕ=>x.1.2.filter (fun z=>decide (z.1≠x.2))) := + composition (pair second first.snd) (filterWith neq) + let vals : Realizer (fun x : State×ℕ=>(x.1.2.filter (fun z=>decide (z.1≠x.2))).map (fun z=>ratio ((x.1.1,x.2),z))) := + composition (pair (pair first.fst second) vs) (mapWith ratioRealizer) + exact (composition (pair vals (constant (0,1))) (fold maximumRealizer)).congr (fun _=>rfl) +lemma polynomial_rowMax : PolynomialTime rowMaxRealizer := by + unfold rowMaxRealizer + dsimp only + apply polynomial_congr + have := polynomial_maximumFold + have := polynomial_ratio + have : PolynomialTime (composition (composition (pair (second (A:=ℕ) (B:=ℕ×Fraction)).fst first) natEqual) boolNot) := by + dsimp only [Realizer.fst,Realizer.snd] + tree_cost + dsimp only [Realizer.fst,Realizer.snd] + tree_cost + +def step (x : ℕ×State) : State := + (x.2.1,setState (x.2.2,(x.1,rowMax (x.2,x.1)))) +def stepRealizer : Realizer step := + pair second.fst (composition (pair second.snd (pair first + (composition (pair second first) rowMaxRealizer))) (setStateRealizer natEqual)) +lemma polynomial_step : PolynomialTime stepRealizer := by + unfold stepRealizer + apply polynomial_pair (polynomial_fst polynomial_second) + apply polynomial_composition _ (polynomial_setState (A:=Fraction) polynomial_natEqual) + apply polynomial_pair (polynomial_snd polynomial_second) + exact polynomial_pair polynomial_first (polynomial_composition (polynomial_pair polynomial_second polynomial_first) polynomial_rowMax) + +lemma cell_height (M : Matrix) (i j : ℕ) : height (cell (M,(i,j)))≤weight M+1 := by + unfold cell + dsimp only + by_cases hi : isimp only [List.map_nil,weight_nil]; omega + | cons z zs ih=> + have hz:weight z.2≤8*H+3:=(weight_le_height z.2).trans (by have :=hv z (by simp);omega) + have ht:=ih (fun a ha=>hv a (by simp [ha])) + rw [List.map_cons,weight_cons,weight_cons,←Prod.eta z,weight_prod] + nlinarith + +lemma vector_keys_weight (v : Vector) : weight (v.map Prod.fst)≤weight v := by + induction v with + | nil=>rfl + | cons a as ih=> + rw [List.map_cons,weight_cons,weight_cons,←Prod.eta a,weight_prod] + dsimp only + omega +lemma fold_step_data (is : List ℕ) (M : Matrix) (v : Vector) (H : ℕ) + (hv : ∀ z∈v,height z.2≤H) : + (is.foldl (fun s i=>step (i,s)) (M,v)).1=M ∧ + (is.foldl (fun s i=>step (i,s)) (M,v)).2.map Prod.fst=v.map Prod.fst ∧ + ∀ z∈(is.foldl (fun s i=>step (i,s)) (M,v)).2, + height z.2≤H+is.length*(weight M+2) := by + induction is generalizing v H with + | nil=>exact ⟨rfl,rfl,by simpa using hv⟩ + | cons i is ih=> + have ht:=ih (step (i,(M,v))).2 (H+weight M+2) (step_height i M v H hv) + refine ⟨ht.1,ht.2.1.trans (step_keys i (M,v)),?_⟩ + intro z hz + have h:=ht.2.2 z hz + simp only [List.length_cons] + nlinarith +lemma polynomial_sweep : PolynomialTime (fold stepRealizer) := by + apply polynomial_fold polynomial_step (1+X+(X+1)*(8*(X+X*(X+2))+5)) + intro is ⟨M,v⟩ pre post he + let S:=weight (is,(M,v)) + have hM : weight M≤S := (weight_fst (M,v)).trans (weight_snd (is,(M,v))) + have hv : weight v≤S := (weight_snd (M,v)).trans (weight_snd (is,(M,v))) + have hk : weight (v.map Prod.fst)≤S := (vector_keys_weight v).trans hv + have hp : pre.length≤S := (list_length_le_weight pre).trans ((weight_prefix he).trans (weight_fst (is,(M,v)))) + have ht:=fold_step_data pre M v S (fun z hz=>(height_le_weight z.2).trans ((weight_snd z).trans ((weight_mem hz).trans hv))) + have hw:=vector_weight (pre.foldl (fun s i=>step (i,s)) (M,v)).2 (S+pre.length*(weight M+2)) ht.2.2 + rw [ht.2.1] at hw + rw [←Prod.eta (pre.foldl (fun s i=>step (i,s)) (M,v)),weight_prod,ht.1] + simp only [eval_add,eval_mul,eval_X,eval_one,eval_ofNat] + change _≤1+S+(S+1)*(8*(S+S*(S+2))+5) + have hi : S+pre.length*(weight M+2)≤S+S*(S+2) := Nat.add_le_add_left (Nat.mul_le_mul hp (by omega)) S + exact Nat.add_le_add (by omega) (hw.trans (Nat.mul_le_mul (by omega) (by omega))) + +def initial (M : Matrix) : State := (M,(List.range M.length).map fun i=>(i,(2,1))) +def initialRealizer : Realizer initial := + pair identity (composition (composition listLength range) (map (pair identity (constant (2,1))))) +lemma polynomial_initial : PolynomialTime initialRealizer := by + unfold initialRealizer + apply polynomial_pair polynomial_identity + apply polynomial_composition + · exact polynomial_boundedRange polynomial_listLength X (fun a=>by simpa using list_length_le_weight a) + · tree_cost + +def scale (M : Matrix) : Vector := + ((List.range M.length).foldl (fun s i=>step (i,s)) (initial M)).2 +def scaleRealizer : Realizer scale := + composition (composition (pair (composition listLength range) initialRealizer) (fold stepRealizer)) second +lemma polynomial_scale : PolynomialTime scaleRealizer := by + unfold scaleRealizer + apply polynomial_composition _ polynomial_second + apply polynomial_composition _ polynomial_sweep + apply polynomial_pair _ polynomial_initial + exact polynomial_boundedRange polynomial_listLength X (fun a=>by simpa using list_length_le_weight a) +end MatchingFPRAS.ExecutableScaling + +end OAI diff --git a/lean/OAI/Combinatorics/MatchingCount/Algorithm/TreeScalingCorrect.lean b/lean/OAI/Combinatorics/MatchingCount/Algorithm/TreeScalingCorrect.lean new file mode 100644 index 0000000000000000000000000000000000000000..980422adbbfe1410d7367dba77cff6651b1bb6d9 --- /dev/null +++ b/lean/OAI/Combinatorics/MatchingCount/Algorithm/TreeScalingCorrect.lean @@ -0,0 +1,104 @@ +import Mathlib +import OAI.Combinatorics.MatchingCount.Arithmetic.TreeFractionExtra +import OAI.Combinatorics.MatchingCount.Algorithm.TreeScaling + +namespace OAI + +namespace MatchingFPRAS.ExecutableScaling +open TreeTyped TreeFraction ExecutableBottleneck ExecutableLadder + +variable {n : ℕ} +def vectorRep (v : Fin n→ℚ) : Vector := List.ofFn fun j=>(j.val,TreeFraction.repr (v j)) + +lemma rowMax_rep (hn : 2≤n) (G : Fin n→Fin n→ℚ) (v : Fin n→ℚ) + (hG : ∀ i j,i≠j→0≤G i j) (hv : ∀ j,0≤v j) (i : Fin n) : + rowMax ((matrixRep G,vectorRep v),i.val)=TreeFraction.repr (Counting.rowMaximum hn G v i) := by + let js := (List.finRange n).filter (fun j=>decide (j≠i)) + let qs := js.map (fun j=>G i j/v j) + have hj : ∀ j,j∈js↔j≠i := by intro j; simp [js] + have hq : ∀ q∈qs,0≤q := by + intro q h + obtain ⟨j,hj',rfl⟩:=List.mem_map.mp h + exact div_nonneg (hG i j ((hj j).mp hj').symm) (hv j) + have he : ((vectorRep v).filter (fun z=>decide (z.1≠i.val))).map + (fun z=>ratio ((matrixRep G,i.val),z))=qs.map TreeFraction.repr := by + unfold vectorRep qs + rw [List.ofFn_eq_map,List.filter_map,List.map_map,List.map_map] + have hp : (fun j : Fin n=>decide ((j.val,TreeFraction.repr (v j)).1≠i.val))= + (fun j=>decide (j≠i)) := by + funext j + simp only [ne_eq,Fin.val_inj] + change List.map _ (List.filter _ (List.finRange n))=_ + rw [show ((fun z : ℕ×Fraction=>decide (z.1≠i.val)) ∘ (fun j : Fin n=>(j.val,TreeFraction.repr (v j))))= + (fun j=>decide (j≠i)) from hp] + apply List.map_congr_left + intro j hj' + dsimp only [Function.comp_apply,ratio] + rw [cell_matrixRep,div_repr (hG i j ((hj j).mp hj').symm) (hv j)] + unfold rowMax + dsimp only + rw [he,show ((0,1) : Fraction)=TreeFraction.repr (0:ℚ) from rfl,maximum_fold_repr qs 0 (by decide) hq] + congr 1 + apply le_antisymm + · apply fold_max_le + · obtain ⟨j,hjj⟩:=Counting.others_nonempty hn i + have hnz:=div_nonneg (hG i j (Finset.mem_erase.mp hjj).1.symm) (hv j) + exact hnz.trans (Counting.ratio_le_rowMaximum hn G v i j (Finset.mem_erase.mp hjj).1) + · intro q h + obtain ⟨j,hj',rfl⟩:=List.mem_map.mp h + exact Counting.ratio_le_rowMaximum hn G v i j ((hj j).mp hj') + · apply Finset.sup'_le + intro j hj' + exact mem_le_fold_max qs 0 _ (List.mem_map.mpr ⟨j,(hj j).mpr (Finset.mem_erase.mp hj').1,rfl⟩) + +lemma set_vectorRep (v : Fin n→ℚ) (i : Fin n) (a : ℚ) : + setState (vectorRep v,(i.val,TreeFraction.repr a))=vectorRep (Function.update v i a) := by + unfold setState vectorRep + rw [List.map_ofFn] + apply congrArg List.ofFn + funext j + simp only [Function.comp_apply,Function.update_apply,Fin.val_inj] + split_ifs <;> rfl +lemma step_rep (hn : 2≤n) (G : Fin n→Fin n→ℚ) (v : Fin n→ℚ) + (hG : ∀ i j,i≠j→0≤G i j) (hv : ∀ j,0≤v j) (i : Fin n) : + step (i.val,(matrixRep G,vectorRep v))=(matrixRep G,vectorRep (Counting.scaleUpdate hn G v i)) := by + unfold step + dsimp only + rw [rowMax_rep hn G v hG hv i,set_vectorRep] + rfl +lemma initial_rep (G : Fin n→Fin n→ℚ) : initial (matrixRep G)=(matrixRep G,vectorRep (fun _ : Fin n=>2)) := by + unfold initial vectorRep + rw [matrixRep_length] + congr 1 + apply List.ext_getElem + · simp + · intro k hk hk' + simp only [List.getElem_map,List.getElem_range,List.getElem_ofFn] + rfl +lemma sweep_rep (hn : 2≤n) (G : Fin n→Fin n→ℚ) + (hsym : ∀ i j,G i j=G j i) + (hG : ∀ i j,i≠j→ Counting.alpha≤G i j ∧ G i j≤3) (k : ℕ) (hk : k≤n) : + (List.range k).foldl (fun s i=>step (i,s)) (initial (matrixRep G))= + (matrixRep G,vectorRep (Counting.scalingTrace hn G k)) := by + induction k with + | zero=>exact initial_rep G + | succ k ih=> + rw [List.range_succ,List.foldl_append,ih (by omega)] + simp only [List.foldl_cons,List.foldl_nil] + have hp : ∀ j,0≤Counting.scalingTrace hn G k j := fun j=> + ((Counting.scalingTrace_invariant hn G hsym hG k).1.pos j).le + have hG' : ∀ i j,i≠j→0≤G i j := by + intro i j hij + exact (by norm_num [Counting.alpha] : (0:ℚ)≤Counting.alpha).trans (hG i j hij).1 + rw [step_rep hn G _ hG' hp (⟨k,by omega⟩ : Fin n)] + congr 2 + simp only [Counting.scalingTrace,dite_eq_left (show kTreeFraction.repr (v j)) + Fin.val_injective i (by simp) +end MatchingFPRAS.ExecutableScaling + +namespace MatchingFPRAS.ExecutableAdaptive +open TreeTyped TreeFraction ExecutableBottleneck ExecutableScaling ExecutableLadder ExecutableSource + +abbrev GraphData := List ℕ×List RawLogical +abbrev ActivityData := (GraphData×List Bool)×Vector +abbrev CellData := (List RawLogical×Fraction)×Vector + +def cooling (n : ℕ) : Fraction := div ((1,1),add ((1,1),div ((1,1),(n,1)))) +def coolingRealizer : Realizer cooling := (composition (pair (constant (1,1)) + (composition (pair (constant (1,1)) (composition (pair (constant (1,1)) + (pair identity (constant 1))) divRealizer)) addRealizer)) divRealizer).congr (fun _=>rfl) +lemma polynomial_cooling : PolynomialTime coolingRealizer := by + unfold coolingRealizer; apply polynomial_congr + have := polynomial_div + have := TreeFraction.polynomial_add + tree_cost +lemma cooling_rep (n : ℕ) : cooling n=TreeFraction.repr (FiniteTrial.cooling n) := by + unfold cooling FiniteTrial.cooling + rw [←repr_nat n,show ((1,1) : Fraction)=TreeFraction.repr (1:ℚ) from rfl, + div_repr (by decide) (by positivity),add_repr (by decide) (by positivity), + div_repr (by decide) (by positivity),one_div] + +def cellData (x : ActivityData) : CellData := + ((x.1.1.2,fuelPower (cooling x.1.1.1.length,x.1.2)),x.2) +def cellDataRealizer : Realizer cellData := (pair + (pair first.fst.snd (composition (pair (composition (composition first.fst.fst listLength) coolingRealizer) + first.snd) fuelPowerRealizer)) second).congr (fun _=>rfl) +lemma polynomial_cellData : PolynomialTime cellDataRealizer := by + unfold cellDataRealizer; apply polynomial_congr + have := polynomial_cooling + have := polynomial_fuelPower + dsimp only [Realizer.fst,Realizer.snd] + tree_cost + +def rawCell (x : CellData×RawLogical) : Fraction := + if orderedPair x.2∈x.1.1.1 then (1,1) else x.1.1.2 +def rawCellRealizer : Realizer rawCell := (choose + (composition (pair (composition second orderedPairRealizer) first.fst.fst) + (contains (pairEqual natEqual natEqual))) (constant (1,1)) first.fst.snd).congr (by + intro x; simp [rawCell]) +lemma polynomial_rawCell : PolynomialTime rawCellRealizer := by + unfold rawCellRealizer; apply polynomial_congr + have := polynomial_orderedPair + have := polynomial_contains (polynomial_pairEqual polynomial_natEqual polynomial_natEqual) + dsimp only [Realizer.fst,Realizer.snd] + tree_cost + +def stageCell (x : CellData×RawLogical) : Fraction := + mul (mul (rawCell x,lookup (1,1) (x.1.2,x.2.1)),lookup (1,1) (x.1.2,x.2.2)) +def stageCellRealizer : Realizer stageCell := (composition + (pair (composition (pair rawCellRealizer (composition (pair first.snd second.fst) + (lookupRealizer (1,1) natEqual))) mulRealizer) + (composition (pair first.snd second.snd) (lookupRealizer (1,1) natEqual))) mulRealizer).congr (fun _=>rfl) +lemma polynomial_stageCell : PolynomialTime stageCellRealizer := by + unfold stageCellRealizer; apply polynomial_congr + have := polynomial_rawCell + have := polynomial_lookup ((1,1) : Fraction) polynomial_natEqual + have := polynomial_mul + dsimp only [Realizer.fst,Realizer.snd] + tree_cost + +def stageRow (x : (CellData×List ℕ)×ℕ) : List Fraction := + x.1.2.map (fun j=>stageCell (x.1.1,(x.2,j))) +def stageRowRealizer : Realizer stageRow := (composition (pair (pair first.fst second) first.snd) + (mapWith (composition (pair first.fst (pair first.snd second)) stageCellRealizer))).congr (fun _=>rfl) +lemma polynomial_stageRow : PolynomialTime stageRowRealizer := by + unfold stageRowRealizer; apply polynomial_congr + have := polynomial_stageCell + dsimp only [Realizer.fst,Realizer.snd] + tree_cost + +def stageMatrix (x : ActivityData) : Matrix := + x.1.1.1.map (fun i=>stageRow ((cellData x,x.1.1.1),i)) +def stageMatrixRealizer : Realizer stageMatrix := (composition + (pair (pair cellDataRealizer first.fst.fst) first.fst.fst) (mapWith stageRowRealizer)).congr (fun _=>rfl) +lemma polynomial_stageMatrix : PolynomialTime stageMatrixRealizer := by + unfold stageMatrixRealizer; apply polynomial_congr + have := polynomial_cellData + have := polynomial_stageRow + dsimp only [Realizer.fst,Realizer.snd] + tree_cost + +noncomputable def graphRep (G : GraphInput) : GraphData := + (List.range G.n,G.edges.toList.map (fun e=>(e.1.val,e.2.val))) +lemma orderedPair_minmax (a b : ℕ) : orderedPair (a,b)=(min a b,max a b) := by + unfold orderedPair + by_cases h : aFiniteTrial.raw G fuel.length i j*a i*a j) := by + have hr (i j : Fin G.n) : 0 ≤ FiniteTrial.raw G fuel.length i j := by + unfold FiniteTrial.raw FiniteTrial.cooling + split_ifs <;> positivity + unfold stageMatrix stageRow matrixRep + change (List.range G.n).map _=(List.ofFn _) + simp only [ExecutableDP.map_range_ofFn] + congr 1 + funext i + change (List.range G.n).map _=List.ofFn _ + rw [ExecutableDP.map_range_ofFn] + congr 1 + funext j + unfold stageCell + rw [rawCell_rep,show (cellData ((graphRep G,fuel),vectorRep a)).2=vectorRep a from rfl, + lookup_vectorRep a i,lookup_vectorRep a j,mul_repr (hr i j) (ha i), + mul_repr (mul_nonneg (hr i j) (ha i)) (ha j)] +end MatchingFPRAS.ExecutableAdaptive + +end OAI diff --git a/lean/OAI/Combinatorics/MatchingCount/Algorithm/TreeStageStatistics.lean b/lean/OAI/Combinatorics/MatchingCount/Algorithm/TreeStageStatistics.lean new file mode 100644 index 0000000000000000000000000000000000000000..49315a1f22a6a7e687b81ce1b530931989722f97 --- /dev/null +++ b/lean/OAI/Combinatorics/MatchingCount/Algorithm/TreeStageStatistics.lean @@ -0,0 +1,87 @@ +import Mathlib +import OAI.Combinatorics.MatchingCount.Algorithm.TreeEstimator +import OAI.Combinatorics.MatchingCount.Algorithm.TreeObservables + +namespace OAI + +namespace MatchingFPRAS.ExecutableStatistics +open TreeTyped TreeFraction ExecutableMarking ExecutableEstimator + +variable {C E : Type} [Codec C] [Codec E] [LinearOrder E] [Inhabited E] + +def averageA (xs : List (Marks E)) : Fraction := mean (xs.map observableA) +def averageARealizer : Realizer (averageA (E:=E)) := composition (map observableARealizer) meanRealizer +omit [LinearOrder E] [Inhabited E] in +lemma polynomial_averageA : PolynomialTime (averageARealizer (E:=E)) := + polynomial_composition (polynomial_map polynomial_observableA) polynomial_mean + +def averageD (q : C×E→Fraction) (x : C×List (Marks E)) : Fraction := + mean (x.2.map fun s=>observableD q (x.1,s)) +def averageDRealizer {q : C×E→Fraction} (Q : Realizer q) : Realizer (averageD q) := + (composition (mapWith (observableDRealizer Q)) meanRealizer).congr (fun _=>rfl) +omit [LinearOrder E] [Inhabited E] in +lemma polynomial_averageD {q : C×E→Fraction} {Q : Realizer q} (hQ : PolynomialTime Q) : + PolynomialTime (averageDRealizer Q) := by + unfold averageDRealizer + exact polynomial_congr _ (polynomial_composition + (polynomial_mapWith (polynomial_observableD hQ)) polynomial_mean) + +def averageProbe (q : C×E→Fraction) (x : (C×E)×List (Marks E)) : Fraction := + mean (x.2.map fun s=>observableProbe q (x.1.1,(x.1.2,s))) +def averageProbeRealizer {q : C×E→Fraction} (Q : Realizer q) + (Eq : Realizer (fun x : E×E=>decide (x.1=x.2))) : Realizer (averageProbe q) := + (composition (mapWith (composition (pair first.fst (pair first.snd second)) + (observableProbeRealizer Q Eq))) meanRealizer).congr (fun _=>rfl) +omit [Inhabited E] in +lemma polynomial_averageProbe {q : C×E→Fraction} {Q : Realizer q} + {Eq : Realizer (fun x : E×E=>decide (x.1=x.2))} + (hQ : PolynomialTime Q) (hE : PolynomialTime Eq) : PolynomialTime (averageProbeRealizer Q Eq) := by + unfold averageProbeRealizer Realizer.fst Realizer.snd + apply polynomial_congr + have := polynomial_observableProbe hQ hE + have := polynomial_mean + tree_cost + +abbrev ProbeContext (C E : Type) := (C×ℕ)×(Fraction×List (Marks E)) +def estimateProbe (q : C×E→Fraction) (x : ProbeContext C E×E) : E×Fraction := + (x.2,upper (x.1.1.2,(x.1.2.1,averageProbe q ((x.1.1.1,x.2),x.1.2.2)))) +def estimateProbeRealizer {q : C×E→Fraction} (Q : Realizer q) + (Eq : Realizer (fun x : E×E=>decide (x.1=x.2))) : Realizer (estimateProbe q) := + (pair second (composition (pair first.fst.snd (pair first.snd.fst + (composition (pair (pair first.fst.fst second) first.snd.snd) (averageProbeRealizer Q Eq)))) upperRealizer)).congr (fun _=>rfl) +omit [Inhabited E] in +lemma polynomial_estimateProbe {q : C×E→Fraction} {Q : Realizer q} + {Eq : Realizer (fun x : E×E=>decide (x.1=x.2))} + (hQ : PolynomialTime Q) (hE : PolynomialTime Eq) : PolynomialTime (estimateProbeRealizer Q Eq) := by + unfold estimateProbeRealizer Realizer.fst Realizer.snd + apply polynomial_congr + have := polynomial_averageProbe hQ hE + have := polynomial_upper + tree_cost + +abbrev StageInput (C E : Type) := (C×(ℕ×List E))×List (Marks E) +def estimates (q : C×E→Fraction) (x : StageInput C E) : Fraction×List (E×Fraction) := + let dbar:=averageD q (x.1.1,x.2) + (ratio (averageA x.2,dbar),x.1.2.2.map fun e=>estimateProbe q (((x.1.1,x.1.2.1),(dbar,x.2)),e)) +def estimatesRealizer {q : C×E→Fraction} (Q : Realizer q) + (Eq : Realizer (fun x : E×E=>decide (x.1=x.2))) : Realizer (estimates q) := by + let dbar : Realizer (fun x : StageInput C E=>averageD q (x.1.1,x.2)) := + (composition (pair first.fst second) (averageDRealizer Q)).congr (fun _=>rfl) + exact (pair (composition (pair (composition second averageARealizer) dbar) ratioRealizer) + (composition (pair (pair (pair first.fst first.snd.fst) (pair dbar second)) first.snd.snd) + (mapWith (estimateProbeRealizer Q Eq)))).congr (fun _=>rfl) +omit [Inhabited E] in +lemma polynomial_estimates {q : C×E→Fraction} {Q : Realizer q} + {Eq : Realizer (fun x : E×E=>decide (x.1=x.2))} + (hQ : PolynomialTime Q) (hE : PolynomialTime Eq) : PolynomialTime (estimatesRealizer Q Eq) := by + unfold estimatesRealizer Realizer.fst Realizer.snd + dsimp only + apply polynomial_congr + have := polynomial_averageA (E:=E) + have := polynomial_averageD hQ + have := polynomial_estimateProbe hQ hE + have := polynomial_ratio + tree_cost +end MatchingFPRAS.ExecutableStatistics + +end OAI diff --git a/lean/OAI/Combinatorics/MatchingCount/Algorithm/TreeStageStatisticsCorrect.lean b/lean/OAI/Combinatorics/MatchingCount/Algorithm/TreeStageStatisticsCorrect.lean new file mode 100644 index 0000000000000000000000000000000000000000..a33de826cda4165931316fc52107a82db1a67776 --- /dev/null +++ b/lean/OAI/Combinatorics/MatchingCount/Algorithm/TreeStageStatisticsCorrect.lean @@ -0,0 +1,86 @@ +import Mathlib +import OAI.Combinatorics.MatchingCount.Algorithm.TreeStageStatistics +import OAI.Combinatorics.MatchingCount.Algorithm.TreeObservablesCorrect + +namespace OAI + +namespace MatchingFPRAS.ExecutableEstimator +open TreeFraction + +lemma mean_ofFn {S : ℕ} (f : Fin S→ℚ) (hf : ∀ i,0≤f i) : + mean (List.ofFn (fun i=>TreeFraction.repr (f i)))=TreeFraction.repr ((∑ i,f i)/(S:ℚ)) := by + have he : List.ofFn (fun i=>TreeFraction.repr (f i))=(List.ofFn f).map TreeFraction.repr := + by rw [List.map_ofFn]; rfl + rw [he,mean_rep _ (by intro a ha; obtain ⟨i,rfl⟩:=List.mem_ofFn.mp ha; exact hf i)] + simp only [List.sum_ofFn,List.length_ofFn] +end MatchingFPRAS.ExecutableEstimator + +namespace MatchingFPRAS.ExecutableStatistics +open TreeTyped TreeFraction ExecutableMarking ExecutableEstimator + +variable {C E : Type} [Codec C] [Codec E] [LinearOrder E] [Inhabited E] +variable {S : ℕ} (s : Fin S→Finset E) (m : Fin S→E→Fin 3) +def sampleRep : List (Marks E) := List.ofFn (fun i=>marksRep (s i) (m i)) +def scalarA (i : Fin S) : ℚ := if ∀ e∈s i,m i e=0 then 1 else 0 +def scalarD (r : E→ℚ) (i : Fin S) : ℚ := if ∀ e∈s i,m i e=0 then ∏ e∈s i,r e else 0 +def scalarProbe (r : E→ℚ) (e : E) (i : Fin S) : ℚ := + if e∈s i ∧ ∀ a∈s i,m i a=if a=e then 2 else 0 then ∏ a∈s i\{e},r a else 0 +omit [Codec C] [Codec E] [Inhabited E] [LinearOrder E] in +lemma scalarA_nonneg [LinearOrder E] (i : Fin S) : 0 ≤ scalarA s m i := by unfold scalarA; split_ifs <;> norm_num +omit [Codec C] [Codec E] [Inhabited E] [LinearOrder E] in +lemma scalarD_nonneg [LinearOrder E] (r : E→ℚ) (hr : ∀ e,0≤r e) (i : Fin S) : 0 ≤ scalarD s m r i := by + unfold scalarD; split_ifs; exact Finset.prod_nonneg (fun e _=>hr e); exact le_rfl +omit [Codec C] [Codec E] [Inhabited E] in +lemma scalarProbe_nonneg (r : E→ℚ) (hr : ∀ e,0≤r e) (e : E) (i : Fin S) : + 0 ≤ scalarProbe s m r e i := by + unfold scalarProbe; split_ifs; exact Finset.prod_nonneg (fun a _=>hr a); exact le_rfl + +omit [Codec E] [Inhabited E] in +lemma averageA_rep [Codec E] [Inhabited E] : + averageA (sampleRep s m)=TreeFraction.repr ((∑ i,scalarA s m i)/(S:ℚ)) := by + unfold averageA sampleRep + rw [List.map_ofFn] + simp only [Function.comp_def,observableA_rep] + exact mean_ofFn (scalarA s m) (scalarA_nonneg s m) +omit [Codec C] [Codec E] [Inhabited E] in +lemma averageD_rep [Codec C] [Codec E] [Inhabited E] (q : C×E→Fraction) (c : C) (r : E→ℚ) + (hr : ∀ e,0≤r e) (hq : ∀ e,q (c,e)=TreeFraction.repr (r e)) : + averageD q (c,sampleRep s m)=TreeFraction.repr ((∑ i,scalarD s m r i)/(S:ℚ)) := by + unfold averageD sampleRep + dsimp only + rw [List.map_ofFn] + simp only [Function.comp_def,observableD_rep q c r hr hq] + exact mean_ofFn (scalarD s m r) (scalarD_nonneg s m r hr) +omit [Codec C] [Codec E] [Inhabited E] in +lemma averageProbe_rep [Codec C] [Codec E] [Inhabited E] (q : C×E→Fraction) (c : C) (r : E→ℚ) + (hr : ∀ e,0≤r e) (hq : ∀ e,q (c,e)=TreeFraction.repr (r e)) (e : E) : + averageProbe q ((c,e),sampleRep s m)=TreeFraction.repr ((∑ i,scalarProbe s m r e i)/(S:ℚ)) := by + unfold averageProbe sampleRep + dsimp only + rw [List.map_ofFn] + simp only [Function.comp_def,observableProbe_rep q c r hr hq] + exact mean_ofFn (scalarProbe s m r e) (scalarProbe_nonneg s m r hr e) + +lemma estimates_rep (q : C×E→Fraction) (c : C) (r : E→ℚ) + (hr : ∀ e,0≤r e) (hq : ∀ e,q (c,e)=TreeFraction.repr (r e)) (D : ℕ) (keys : List E) : + estimates q ((c,(D,keys)),sampleRep s m)= + (TreeFraction.repr (Counting.ratioEstimate ((∑ i,scalarA s m i)/(S:ℚ)) + ((∑ i,scalarD s m r i)/(S:ℚ))), + keys.map (fun e=>(e,TreeFraction.repr (Counting.upperEstimate D + ((∑ i,scalarD s m r i)/(S:ℚ)) ((∑ i,scalarProbe s m r e i)/(S:ℚ)))))) := by + have ha : 0≤(∑ i,scalarA s m i)/(S:ℚ):=div_nonneg (Finset.sum_nonneg (fun i _=>scalarA_nonneg s m i)) (Nat.cast_nonneg _) + have hd : 0≤(∑ i,scalarD s m r i)/(S:ℚ):=div_nonneg (Finset.sum_nonneg (fun i _=>scalarD_nonneg s m r hr i)) (Nat.cast_nonneg _) + have hz (e : E) : 0≤(∑ i,scalarProbe s m r e i)/(S:ℚ):=div_nonneg + (Finset.sum_nonneg (fun i _=>scalarProbe_nonneg s m r hr e i)) (Nat.cast_nonneg _) + unfold estimates + dsimp only + rw [averageD_rep s m q c r hr hq,averageA_rep s m,ratio_rep _ _ ha hd] + congr 1 + apply List.map_congr_left + intro e _he + unfold estimateProbe + dsimp only + rw [averageProbe_rep s m q c r hr hq e,upper_rep D _ _ hd (hz e)] +end MatchingFPRAS.ExecutableStatistics + +end OAI diff --git a/lean/OAI/Combinatorics/MatchingCount/Algorithm/TreeStageUpdateCorrect.lean b/lean/OAI/Combinatorics/MatchingCount/Algorithm/TreeStageUpdateCorrect.lean new file mode 100644 index 0000000000000000000000000000000000000000..6e1c7e24808089408e491ceca106a5d9f056701b --- /dev/null +++ b/lean/OAI/Combinatorics/MatchingCount/Algorithm/TreeStageUpdateCorrect.lean @@ -0,0 +1,56 @@ +import Mathlib +import OAI.Combinatorics.MatchingCount.Algorithm.TreeNumericStage +import OAI.Combinatorics.MatchingCount.Algorithm.TreeNumericSummaries + +namespace OAI + +namespace MatchingFPRAS.NumericMarking +open TreeTyped TreeFraction TreeTyped.Numbered ExecutableStatistics ExecutableLadder + + ExecutableEstimator ExecutableBottleneck ExecutableScaling ExecutableAdaptive ExecutableSource +lemma finishUpdate_rep {E : Type} [Fintype E] [LinearOrder E] {n : ℕ} (hn : 2≤n) + (c : Enlargement.LogicalEdge (Fin n)→E) (keys : List E) (hk : ∀ e,e∈keys) + (z : E→ℚ) (hz : ∀ e,0≤z e) (D : ℕ) (d q : ℚ) (hd : 0≤d) + (a : Fin n→ℚ) (ha : ∀ i,0≤a i) : + finishUpdate (((D,List.range n), + ((List.ofFn (UnitRefresh.orderedEnum (Enlargement.LogicalEdge (Fin n)))).map + (fun e=>(logicalRepr e,index (c e))),vectorRep a)), + ((TreeFraction.repr q,TreeFraction.repr d),keys.map (fun e=>(index e,TreeFraction.repr (z e)))))= + (TreeFraction.repr q,vectorRep (fun i=>a i* + Counting.scalingTrace hn (FiniteTrial.estimateMatrix D d (z ∘ c)) n i)) := by + unfold finishUpdate + dsimp only + rw [logicalProbes_rep c keys hk z] + have ht (e : Enlargement.LogicalEdge (Fin n)) : + lookup (0,1) ((List.ofFn (UnitRefresh.orderedEnum (Enlargement.LogicalEdge (Fin n)))).map + (fun e=>(logicalRepr e,TreeFraction.repr (z (c e)))),logicalRepr e)= + TreeFraction.repr ((z ∘ c) e) := by + apply lookup_image (0,1) _ logicalRepr (fun e=>TreeFraction.repr (z (c e))) logicalRepr_injective + exact List.mem_ofFn.mpr ⟨(UnitRefresh.orderedEnum _).symm e,Equiv.apply_symm_apply _ _⟩ + rw [estimateMatrix_rep D d hd (z ∘ c) (fun e=>hz (c e)) _ ht, + updateVector_rep hn _ (FiniteTrial.estimateMatrix_symm D d (z ∘ c)) + (fun i j _=>FiniteTrial.estimateMatrix_bounds D d (z ∘ c) i j) a ha] + +abbrev AdaptiveInput := UpdateConfig×StageInput +def stageUpdate (x : AdaptiveInput) : Fraction×Vector := + finishUpdate (x.1,summaries (x.2.1.1,sampleMany (x.2.1.2,x.2.2))) +def stageUpdateRealizer : Realizer stageUpdate := (composition + (pair first (composition (pair second.fst.fst + (composition (pair second.fst.snd second.snd) sampleManyRealizer)) summariesRealizer)) finishUpdateRealizer).congr (fun _=>rfl) +lemma polynomial_stageUpdate : PolynomialTime stageUpdateRealizer := by + unfold stageUpdateRealizer Realizer.fst Realizer.snd + apply polynomial_congr + have := polynomial_sampleMany + have := polynomial_summaries + have := polynomial_finishUpdate + tree_cost + +theorem stageUpdate_post : ∃ p : Polynomial ℕ,∀ x : AdaptiveInput,∀ t : ℕ, + p.eval (TreePost.packed x).length≤t → ∀ coins : Fin t→Bool, + (run (TreePost.machine stageUpdateRealizer.program) (TreePost.packed x) coins).state=none ∧ + (run (TreePost.machine stageUpdateRealizer.program) (TreePost.packed x) coins).tape.right₀= + Turing.ListBlank.mk (TreePost.packed (stageUpdate x)) := + TreePost.polynomial_compiles stageUpdateRealizer polynomial_stageUpdate +end MatchingFPRAS.NumericMarking + +end OAI diff --git a/lean/OAI/Combinatorics/MatchingCount/Algorithm/TreeStatistics.lean b/lean/OAI/Combinatorics/MatchingCount/Algorithm/TreeStatistics.lean new file mode 100644 index 0000000000000000000000000000000000000000..29abf404b1cd2e07a63cb106bca42609743a58ca --- /dev/null +++ b/lean/OAI/Combinatorics/MatchingCount/Algorithm/TreeStatistics.lean @@ -0,0 +1,93 @@ +import Mathlib +import OAI.Combinatorics.MatchingCount.Algorithm.TreeNumericSummaries + +namespace OAI + +namespace MatchingFPRAS.NumericMarking +open TreeTyped TreeFraction TreeTyped.Numbered ExecutableStatistics ExecutableLadder + + ExecutableEstimator ExecutableBottleneck ExecutableScaling ExecutableAdaptive ExecutableSource +open Finset Transport Enlargement + +variable {E : Type} [DecidableEq E] +def selectedMarks (s : Finset E) (m : ↥s→Fin 3) (e : E) : Fin 3 := + if h:e∈s then m ⟨e,h⟩ else 0 +lemma selectedMarks_on (s : Finset E) (m : ↥s→Fin 3) (e : ↥s) : + selectedMarks s m e.val=m e := dite_eq_left e.property +lemma selectedMarks_eq (s : Finset E) (m : ↥s→Fin 3) (r : E→Fin 3) : + (∀ e∈s,selectedMarks s m e=r e) ↔ m=(fun e=>r e.val) := by + constructor + · intro h; funext e; exact (selectedMarks_on s m e).symm.trans (h e.val e.property) + · intro h e he; subst m; simp only [selectedMarks,he,↓reduceDIte] + +variable {V : Type} [Fintype V] [LinearOrder V] [Nontrivial V] +attribute [local instance] NumberedHierarchy.labelOrder sym2Order bagEdgeOrder bagEdgeFintype +attribute [local instance] UnitRefresh.Computable.allowedDec prodOrder sumOrder +noncomputable local instance (w : V→V→ℚ) (K : ℕ) : + DecidableEq (SourceLabel (fun x y=>(w x y:ℝ)) K) := Classical.decEq _ +noncomputable local instance (w : V→V→ℚ) (K : ℕ) : + Fintype (BagEdge (sourceBags (fun x y=>(w x y:ℝ)) K)) := Fintype.ofFinite _ + +lemma reweight_nonneg (w w₁ : V→V→ℚ) (hw : ∀ i j,0≤w i j) + (hw₁ : ∀ i j,0≤w₁ i j) (K : ℕ) (e : BagEdge (RationalSource.bags w K)) : + 0≤RationalSource.bagReweight w w₁ K e := by + classical + by_cases h : ∃ q,RationalSource.coloredReal w K q=e + · obtain ⟨q,rfl⟩:=h + rw [RationalSource.bagReweight_on] + unfold RationalSource.rawReweight + split_ifs + · apply div_nonneg + · unfold BottleneckAlgorithm.edge; split_ifs <;> apply hw₁ + · unfold BottleneckAlgorithm.edge; split_ifs <;> apply hw + · exact zero_le_one + · rw [RationalSource.bagReweight_off w w₁ K e h]; exact zero_le_one + +variable (w w₁ : V→V→ℚ) (K : ℕ) {S : ℕ} + (x : Fin S→RationalSource.Marked w K) +lemma scalarA_source (i : Fin S) : + scalarA (fun j=>(x j).1.val) (fun j=>selectedMarks (x j).1.val (x j).2) i= + RationalSource.observableA w K (x i) := by + unfold scalarA RationalSource.observableA + simp only [selectedMarks_eq] +lemma scalarD_source (i : Fin S) : + scalarD (fun j=>(x j).1.val) (fun j=>selectedMarks (x j).1.val (x j).2) + (RationalSource.bagReweight w w₁ K) i=RationalSource.observableD w w₁ K (x i) := by + unfold scalarD RationalSource.observableD + simp only [selectedMarks_eq] +lemma scalarProbe_source (e : LogicalEdge V) (i : Fin S) : + scalarProbe (fun j=>(x j).1.val) (fun j=>selectedMarks (x j).1.val (x j).2) + (RationalSource.bagReweight w w₁ K) (RationalSource.centralEdge w K e) i= + RationalSource.observableProbe w w₁ K e (x i) := by + unfold scalarProbe RationalSource.observableProbe + simp only [selectedMarks_eq] + simp only [singleton_subset_iff,mem_singleton] + congr 3 + · funext a + split_ifs <;> rfl + · congr 1 + exact Subsingleton.elim _ _ + +noncomputable def sourceSamples : List (ExecutableMarking.Marks ℕ) := + List.ofFn (fun i=>numericMarks (x i).1.val (selectedMarks (x i).1.val (x i).2)) +noncomputable def sourceKeys : List (BagEdge (RationalSource.bags w K)) := + List.ofFn (UnitRefresh.orderedEnum _) +lemma mem_sourceKeys (e : BagEdge (RationalSource.bags w K)) : e∈sourceKeys w K := + List.mem_ofFn.mpr ⟨(UnitRefresh.orderedEnum _).symm e,Equiv.apply_symm_apply _ _⟩ + +lemma summaries_source (hw : ∀ i j,0≤w i j) (hw₁ : ∀ i j,0≤w₁ i j) (D : ℕ) : + summaries ((reweightsRep (RationalSource.bagReweight w w₁ K),(D,(sourceKeys w K).map index)), + sourceSamples w K x)= + ((TreeFraction.repr (Counting.ratioEstimate + (FiniteTrial.sampleAverage (RationalSource.observableA w K) x) + (FiniteTrial.sampleAverage (RationalSource.observableD w w₁ K) x)), + TreeFraction.repr (FiniteTrial.sampleAverage (RationalSource.observableD w w₁ K) x)), + (sourceKeys w K).map (fun e=>(index e,TreeFraction.repr + ((∑ i,scalarProbe (fun j=>(x j).1.val) (fun j=>selectedMarks (x j).1.val (x j).2) + (RationalSource.bagReweight w w₁ K) e i)/(S:ℚ))))) := by + unfold sourceSamples + rw [summaries_rep _ _ _ (reweight_nonneg w w₁ hw hw₁ K)] + simp only [scalarA_source,scalarD_source,FiniteTrial.sampleAverage] +end MatchingFPRAS.NumericMarking + +end OAI diff --git a/lean/OAI/Combinatorics/MatchingCount/Algorithm/TreeTierWeights.lean b/lean/OAI/Combinatorics/MatchingCount/Algorithm/TreeTierWeights.lean new file mode 100644 index 0000000000000000000000000000000000000000..caa3453e6232f76bbc8b3d8799e72057d206d949 --- /dev/null +++ b/lean/OAI/Combinatorics/MatchingCount/Algorithm/TreeTierWeights.lean @@ -0,0 +1,90 @@ +import Mathlib +import OAI.Combinatorics.MatchingCount.Sampling.TreeDPCount +import OAI.Combinatorics.MatchingCount.Machines.TreeSlotWeight +import OAI.Combinatorics.MatchingCount.Machines.TreePostRealization +import OAI.Combinatorics.MatchingCount.Machines.TreeSlotIndex + +namespace OAI + +namespace MatchingFPRAS.NumericLadder +open TreeTyped TreeFraction ExecutableLadder Polynomial TreeTyped.Numbered Replica.Ladder + +attribute [local instance] Transport.sym2Order Transport.bagEdgeOrder Transport.bagEdgeFintype +abbrev TierData := (ℕ×List Bool)×(List Bool×List Fraction) + +def slotCount (x : TierData) : ℕ := (x.1.2.length+1)*x.2.1.length +def slotCountRealizer : Realizer slotCount := (composition + (pair (composition (composition first.snd listLength) successor) + (composition second.fst listLength)) multiply).congr (fun _=>rfl) +lemma polynomial_slotCount : PolynomialTime slotCountRealizer := by + unfold slotCountRealizer Realizer.fst Realizer.snd + apply polynomial_congr + have := polynomial_successor + tree_cost +lemma slotCount_bound (x : TierData) : slotCount x≤((X+1)*X : Polynomial ℕ).eval (weight x) := by + have ht := (list_length_le_weight x.1.2).trans ((weight_snd x.1).trans (weight_fst x)) + have hq := (list_length_le_weight x.2.1).trans ((weight_fst x.2).trans (weight_snd x)) + simpa [slotCount] using Nat.mul_le_mul (Nat.add_le_add_right ht 1) hq + +def slots (x : TierData) : List ℕ := List.range (slotCount x) +def slotsRealizer : Realizer slots := composition slotCountRealizer range +lemma polynomial_slots : PolynomialTime slotsRealizer := + polynomial_boundedRange polynomial_slotCount ((X+1)*X) slotCount_bound + +def weightRow (x : TierData×ℕ) : List Fraction := + x.1.2.2.map (fun w=>slotWeight ((x.1.1,x.2/x.1.2.1.length),w)) +def weightRowRealizer : Realizer weightRow := (composition + (pair (pair first.fst (composition (pair second (composition first.snd.fst listLength)) quotient)) first.snd.snd) + (mapWith slotWeightRealizer)).congr (fun _=>rfl) +lemma polynomial_weightRow : PolynomialTime weightRowRealizer := by + unfold weightRowRealizer Realizer.fst Realizer.snd + apply polynomial_congr + have := polynomial_slotWeight + have := polynomial_quotient + tree_cost + +def weightRows (x : TierData) : List (List Fraction) := (slots x).map (fun i=>weightRow (x,i)) +def weightRowsRealizer : Realizer weightRows := composition (pair identity slotsRealizer) (mapWith weightRowRealizer) +lemma polynomial_weightRows : PolynomialTime weightRowsRealizer := by + unfold weightRowsRealizer + exact polynomial_composition (TreeTyped.polynomial_pair polynomial_identity polynomial_slots) + (polynomial_mapWith polynomial_weightRow) + +lemma index_enum {I : Type} [Fintype I] [LinearOrder I] + (i : Fin (Fintype.card I)) : index (UnitRefresh.orderedEnum I i)=i.val := by simp [index] +lemma range_slot_indices (T q : ℕ) : List.range ((T+1)*q)= + List.ofFn (fun i : Fin (Fintype.card (Slot T q))=>index (UnitRefresh.orderedEnum (Slot T q) i)) := by + simp only [index_enum] + rw [show Fintype.card (Slot T q)=(T+1)*q from slot_card T q] + simpa using (ExecutableDP.map_range_ofFn (fun n=>n) ((T+1)*q)) + +lemma weightRows_source {V L : Type} [Fintype V] [LinearOrder V] [Fintype L] [LinearOrder L] + {bags : V→Finset L} (w : Transport.BagEdge bags→ℚ) (hw : ∀ e,0≤w e) + (ft fq : List Bool) : + weightRows ((Fintype.card V,ft),(fq,List.ofFn (fun e=>TreeFraction.repr (w (UnitRefresh.orderedEnum _ e)))))= + List.ofFn (fun i : Fin (Fintype.card (Slot ft.length fq.length))=> + List.ofFn (fun e=>TreeFraction.repr + (Transport.rationalSlotWeight w (UnitRefresh.orderedEnum _ i) (UnitRefresh.orderedEnum _ e)))) := by + have hrow (slot : Slot ft.length fq.length) : + weightRow (((Fintype.card V,ft),(fq,List.ofFn + (fun edge=>TreeFraction.repr (w (UnitRefresh.orderedEnum _ edge))))),index slot)= + List.ofFn (fun edge=>TreeFraction.repr + (Transport.rationalSlotWeight w slot (UnitRefresh.orderedEnum _ edge))) := by + unfold weightRow + dsimp only + rw [slot_index_div,List.map_ofFn] + exact congrArg List.ofFn (funext (fun edge=>slotWeight_source ft w hw slot + (UnitRefresh.orderedEnum (Transport.BagEdge bags) edge))) + rw [weightRows,slots,slotCount,range_slot_indices,List.map_ofFn] + exact congrArg List.ofFn (funext (fun slot=>hrow + (UnitRefresh.orderedEnum (Slot ft.length fq.length) slot))) + +theorem weightRows_post : ∃ p : Polynomial ℕ,∀ x : TierData,∀ t : ℕ, + p.eval (TreePost.packed x).length≤t → ∀ coins : Fin t→Bool, + (run (TreePost.machine weightRowsRealizer.program) (TreePost.packed x) coins).state=none ∧ + (run (TreePost.machine weightRowsRealizer.program) (TreePost.packed x) coins).tape.right₀= + Turing.ListBlank.mk (TreePost.packed (weightRows x)) := + TreePost.polynomial_compiles weightRowsRealizer polynomial_weightRows +end MatchingFPRAS.NumericLadder + +end OAI diff --git a/lean/OAI/Combinatorics/MatchingCount/Algorithm/TreeWeights.lean b/lean/OAI/Combinatorics/MatchingCount/Algorithm/TreeWeights.lean new file mode 100644 index 0000000000000000000000000000000000000000..af191c8a47fa9ae748d40d9369407c66f8b9b02f --- /dev/null +++ b/lean/OAI/Combinatorics/MatchingCount/Algorithm/TreeWeights.lean @@ -0,0 +1,131 @@ +import Mathlib +import OAI.Combinatorics.MatchingCount.Graphs.TreeProfile +import OAI.Combinatorics.MatchingCount.Graphs.TreeGeometry + +namespace OAI + +namespace MatchingFPRAS.ExecutableSource +open TreeTyped TreeFraction ExecutableBottleneck Polynomial Enlargement RealGeometry + +abbrev PathData := (Matrix×Matrix)×List Bool + +def path (x : PathData×RawReal) : Fraction := + profile ((x.1.2,(cell (x.1.1.2,x.2.1), + (height (x.1.1.2,x.2.1.1),(height (x.1.1.2,x.2.1.2),cell (x.1.1.1,x.2.1))))),x.2.2) +def pathRealizer : Realizer path := + (composition (pair (pair first.snd (pair + (composition (pair first.fst.snd second.fst) cellRealizer) + (pair (composition (pair first.fst.snd second.fst.fst) heightRealizer) + (pair (composition (pair first.fst.snd second.fst.snd) heightRealizer) + (composition (pair first.fst.fst second.fst) cellRealizer))))) second.snd) profileRealizer).congr (fun _=>rfl) +lemma polynomial_path : PolynomialTime pathRealizer := by + unfold pathRealizer + apply polynomial_congr + have := polynomial_cell + have := polynomial_height + have := polynomial_profile + dsimp only [Realizer.fst,Realizer.snd] + tree_cost + +lemma path_repr {n : ℕ} [Nontrivial (Fin n)] (hn : 2≤n) (w : Fin n→Fin n→ℚ) + (hw : ∀ i j,0≤w i j) (K : ℕ) (fuel : List Bool) (hf : fuel.length=2*K+2) + (e : LogicalEdge (Fin n)) (i : Fin (4*fuel.length+1)) : + path (((matrixRep w,matrixRep (RationalSource.logicalB w)),fuel),(logicalRepr e,i.val))= + TreeFraction.repr (RationalSource.pathActivity w K e (Fin.cast (by rw [hf]) i)) := by + have hB : ∀ a b,0≤RationalSource.logicalB w a b := by + intro a b + exact (by norm_num : (0:ℚ)≤1).trans (BottleneckAlgorithm.close_one w _ a b) + have hHt : ∀ a,0≤RationalSource.height w a := by + intro a + obtain ⟨b,hb⟩:=Counting.others_nonempty hn a + exact (hB a b).trans (Finset.le_sup' _ hb) + have hheight (a : Fin n) : height (matrixRep (RationalSource.logicalB w),a.val)= + TreeFraction.repr (RationalSource.height w a) := by + exact height_rep hn _ hB a + rw [path,logicalRepr,cell_matrixRep,cell_matrixRep,hheight,hheight] + rw [profile_repr fuel _ _ _ _ (hB _ _) (hHt _) (hHt _) (hw _ _) i] + congr 1 + have he : BottleneckAlgorithm.edge w (source e) (target e)=w (source e) (target e) := by + have hp : source edecide (x.1=x.2)) := + sumEqual natEqual (pairEqual (pairEqual natEqual natEqual) natEqual) +lemma polynomial_vertexEqual : PolynomialTime vertexEqual := + polynomial_sumEqual polynomial_natEqual (polynomial_pairEqual + (polynomial_pairEqual polynomial_natEqual polynomial_natEqual) polynomial_natEqual) + +def sameEnds (x : (RawVertex×RawVertex)×(RawVertex×RawVertex)) : Bool := + decide ((x.1.1=x.2.1 ∧ x.1.2=x.2.2) ∨ (x.1.1=x.2.2 ∧ x.1.2=x.2.1)) +def sameEndsRealizer : Realizer sameEnds := + (composition (pair + (composition (pair (composition (pair first.fst second.fst) vertexEqual) + (composition (pair first.snd second.snd) vertexEqual)) boolAnd) + (composition (pair (composition (pair first.fst second.snd) vertexEqual) + (composition (pair first.snd second.fst) vertexEqual)) boolAnd)) boolOr).congr (by + intro x; simp [sameEnds]) +lemma polynomial_sameEnds : PolynomialTime sameEndsRealizer := by + unfold sameEndsRealizer + apply polynomial_congr + have := polynomial_vertexEqual + dsimp only [Realizer.fst,Realizer.snd] + tree_cost +lemma sameEnds_sym2 (a b c d : RawVertex) : sameEnds ((a,b),(c,d))=decide (s(a,b)=s(c,d)) := by + simp only [sameEnds,Sym2.eq_iff] + +abbrev WeightedEdge := (RawVertex×RawVertex)×Fraction +abbrev PathTableInput := PathData×List ℕ + +def pathRow (x : PathTableInput×RawReal) : WeightedEdge := + ((left ((x.1.2,x.1.1.2),x.2),right ((x.1.2,x.1.1.2),x.2)),path (x.1.1,x.2)) +def pathRowRealizer : Realizer pathRow := + (pair (pair (composition (pair (pair first.snd first.fst.snd) second) leftRealizer) + (composition (pair (pair first.snd first.fst.snd) second) rightRealizer)) + (composition (pair first.fst second) pathRealizer)).congr (fun _=>rfl) +lemma polynomial_pathRow : PolynomialTime pathRowRealizer := by + unfold pathRowRealizer + apply polynomial_congr + have := polynomial_left + have := polynomial_right + have := polynomial_path + dsimp only [Realizer.fst,Realizer.snd] + tree_cost + +def pathTable (x : PathTableInput) : List WeightedEdge := + (realEdges (x.2,x.1.2)).map (fun e=>pathRow (x,e)) +def pathTableRealizer : Realizer pathTable := + (composition (pair identity (composition (pair second first.snd) realEdgesRealizer)) (mapWith pathRowRealizer)).congr (fun _=>rfl) +lemma polynomial_pathTable : PolynomialTime pathTableRealizer := by + unfold pathTableRealizer + apply polynomial_congr + have := polynomial_realEdges + have := polynomial_mapWith polynomial_pathRow + dsimp only [Realizer.fst,Realizer.snd] + tree_cost + +def contribution (x : (RawVertex×RawVertex)×WeightedEdge) : Fraction := + if sameEnds (x.1,x.2.1) then x.2.2 else (0,1) +def contributionRealizer : Realizer contribution := + (choose (composition (pair first second.fst) sameEndsRealizer) second.snd (constant (0,1))).congr (fun _=>rfl) +lemma polynomial_contribution : PolynomialTime contributionRealizer := by + unfold contributionRealizer + apply polynomial_congr + have := polynomial_sameEnds + dsimp only [Realizer.fst,Realizer.snd] + tree_cost + +def activity (x : List WeightedEdge×(RawVertex×RawVertex)) : Fraction := + sum (x.1.map (fun e=>contribution (x.2,e))) +def activityRealizer : Realizer activity := + (composition (composition (pair second first) (mapWith contributionRealizer)) sumRealizer).congr (fun _=>rfl) +lemma polynomial_activity : PolynomialTime activityRealizer := by + unfold activityRealizer + apply polynomial_congr + have := polynomial_mapWith polynomial_contribution + have := polynomial_sum + tree_cost +end MatchingFPRAS.ExecutableSource + +end OAI diff --git a/lean/OAI/Combinatorics/MatchingCount/Algorithm/TreeWeightsCorrect.lean b/lean/OAI/Combinatorics/MatchingCount/Algorithm/TreeWeightsCorrect.lean new file mode 100644 index 0000000000000000000000000000000000000000..83a3cbf1f3333fec8e41d96086237a1b5e7e18da --- /dev/null +++ b/lean/OAI/Combinatorics/MatchingCount/Algorithm/TreeWeightsCorrect.lean @@ -0,0 +1,162 @@ +import Mathlib +import OAI.Combinatorics.MatchingCount.Algorithm.TreeEstimator +import OAI.Combinatorics.MatchingCount.Algorithm.TreeWeights + +namespace OAI + +namespace MatchingFPRAS.ExecutableSource +open TreeTyped TreeFraction ExecutableBottleneck Enlargement RealGeometry + +lemma logicalEdges_nodup {vs : List ℕ} (hv : vs.Nodup) : (logicalEdges vs).Nodup := + List.Nodup.filter _ (hv.product hv) +lemma realEdges_nodup {vs : List ℕ} (hv : vs.Nodup) (fuel : List Bool) : + (realEdges (vs,fuel)).Nodup := (logicalEdges_nodup hv).product List.nodup_range +lemma realRepr_injective {n m : ℕ} : Function.Injective (realRepr (n:=n) (m:=m)) := by + intro a b h + exact Prod.ext (logicalRepr_injective (congrArg Prod.fst h)) (Fin.ext (congrArg Prod.snd h)) + +lemma realEdges_finset (n K : ℕ) (fuel : List Bool) (hf : fuel.length=2*K+2) : + (realEdges (List.range n,fuel)).toFinset= + Finset.univ.image (realRepr (n:=n) (m:=4*(2*K+2))) := by + ext e + simp only [List.mem_toFinset,Finset.mem_image,Finset.mem_univ,true_and] + constructor + · intro he + obtain ⟨⟨a,i⟩,hi⟩:=realEdges_complete fuel e he + exact ⟨(a,Fin.cast (by rw [hf]) i),hi⟩ + · rintro ⟨⟨a,i⟩,rfl⟩ + exact realRepr_mem fuel (a,Fin.cast (by rw [hf]) i) + +lemma sum_realEdges (n K : ℕ) (fuel : List Bool) (hf : fuel.length=2*K+2) (f : RawReal→ℚ) : + ((realEdges (List.range n,fuel)).map f).sum = + ∑ e : SourceRealEdge (Fin n) K, f (realRepr e) := by + rw [←List.sum_toFinset f (realEdges_nodup List.nodup_range fuel),realEdges_finset n K fuel hf] + exact Finset.sum_image (fun a _ b _ h=>realRepr_injective h) + +lemma path_source_repr {n : ℕ} [Nontrivial (Fin n)] (hn : 2≤n) (w : Fin n→Fin n→ℚ) + (hw : ∀ i j,0≤w i j) (K : ℕ) (fuel : List Bool) (hf : fuel.length=2*K+2) + (e : SourceRealEdge (Fin n) K) : + path (((matrixRep w,matrixRep (RationalSource.logicalB w)),fuel),realRepr e)= + TreeFraction.repr (RationalSource.pathActivity w K e.1 e.2) := by + have h:=path_repr hn w hw K fuel hf e.1 (Fin.cast (by rw [hf]) e.2) + simpa only [Fin.cast_cast,Fin.cast_refl,Fin.val_cast,realRepr,id] using h + +lemma ends_source_repr {n : ℕ} (K : ℕ) (fuel : List Bool) (hf : fuel.length=2*K+2) + (e : SourceRealEdge (Fin n) K) : + (left ((List.range n,fuel),realRepr e),right ((List.range n,fuel),realRepr e))= + (vertexRepr (atVertex source target (4*(2*K+2)) e.1 e.2.castSucc), + vertexRepr (atVertex source target (4*(2*K+2)) e.1 e.2.succ)) := by + apply Prod.ext + · unfold left internalCount + dsimp only + rw [hf] + exact at_repr e.1 e.2.castSucc + · unfold right internalCount + dsimp only + rw [hf] + exact at_repr e.1 e.2.succ + +lemma sameEnds_source {n : ℕ} (K : ℕ) (a b x y : SourceVertex (Fin n) K) : + sameEnds ((vertexRepr x,vertexRepr y),(vertexRepr a,vertexRepr b))= + decide (s(a,b)=s(x,y)) := by + simp only [sameEnds,vertexRepr_injective.eq_iff] + congr 1 + rw [Sym2.eq_iff] + apply propext + constructor + · rintro (⟨h₁,h₂⟩|⟨h₁,h₂⟩) + · exact Or.inl ⟨h₁.symm,h₂.symm⟩ + · exact Or.inr ⟨h₂.symm,h₁.symm⟩ + · rintro (⟨h₁,h₂⟩|⟨h₁,h₂⟩) + · exact Or.inl ⟨h₁.symm,h₂.symm⟩ + · exact Or.inr ⟨h₂.symm,h₁.symm⟩ + +lemma contribution_source_repr {n : ℕ} [Nontrivial (Fin n)] (hn : 2≤n) + (w : Fin n→Fin n→ℚ) (hw : ∀ i j,0≤w i j) (K : ℕ) (fuel : List Bool) + (hf : fuel.length=2*K+2) (x y : SourceVertex (Fin n) K) (e : SourceRealEdge (Fin n) K) : + contribution ((vertexRepr x,vertexRepr y), + pathRow ((((matrixRep w,matrixRep (RationalSource.logicalB w)),fuel),List.range n),realRepr e))= + TreeFraction.repr (if RealGeometry.edge source target (4*(2*K+2)) e.1 e.2=s(x,y) + then RationalSource.pathActivity w K e.1 e.2 else 0) := by + unfold contribution pathRow + rw [path_source_repr hn w hw K fuel hf e,ends_source_repr K fuel hf e, + sameEnds_source K] + simp only [decide_eq_true_eq] + change (if RealGeometry.edge source target (4*(2*K+2)) e.1 e.2=s(x,y) + then TreeFraction.repr (RationalSource.pathActivity w K e.1 e.2) else TreeFraction.repr (0:ℚ))=_ + split_ifs <;> rfl + +lemma pathActivity_nonneg {n : ℕ} [Nontrivial (Fin n)] (_hn : 2≤n) (w : Fin n→Fin n→ℚ) + (hw : ∀ i j,0≤w i j) (K : ℕ) (e : LogicalEdge (Fin n)) (i : Fin (4*(2*K+2)+1)) : + 0≤RationalSource.pathActivity w K e i := by + have hB : 0≤RationalSource.logicalB w (source e) (target e) := + (by norm_num : (0:ℚ)≤1).trans (BottleneckAlgorithm.close_one w _ _ _) + unfold RationalSource.pathActivity RationalSource.profile + split_ifs + · exact hB.trans (le_max_left _ _) + · unfold BottleneckAlgorithm.edge + split_ifs <;> exact hw _ _ + · exact hB.trans (le_max_left _ _) + +lemma activity_source_repr {n : ℕ} [Nontrivial (Fin n)] (hn : 2≤n) + (w : Fin n→Fin n→ℚ) (hw : ∀ i j,0≤w i j) (K : ℕ) (fuel : List Bool) + (hf : fuel.length=2*K+2) (x y : SourceVertex (Fin n) K) : + activity (pathTable (((matrixRep w,matrixRep (RationalSource.logicalB w)),fuel),List.range n), + (vertexRepr x,vertexRepr y))=TreeFraction.repr (RationalSource.activity w K x y) := by + let f : RawReal→ℚ := fun e=> + if sameEnds ((vertexRepr x,vertexRepr y), + (left ((List.range n,fuel),e),right ((List.range n,fuel),e))) then + (path (((matrixRep w,matrixRep (RationalSource.logicalB w)),fuel),e)).1 / + ((path (((matrixRep w,matrixRep (RationalSource.logicalB w)),fuel),e)).2 : ℚ) + else 0 + let es:=realEdges (List.range n,fuel) + let g : SourceRealEdge (Fin n) K→ℚ := fun e=> + if RealGeometry.edge source target (4*(2*K+2)) e.1 e.2=s(x,y) + then RationalSource.pathActivity w K e.1 e.2 else 0 + have hg (e) : 0≤g e := by + dsimp only [g] + split_ifs + · exact pathActivity_nonneg hn w hw K _ _ + · exact le_rfl + have hre (e : SourceRealEdge (Fin n) K) : f (realRepr e)=g e := by + dsimp only [f,g] + rw [ends_source_repr K fuel hf e,sameEnds_source K,path_source_repr hn w hw K fuel hf e] + simp only [decide_eq_true_eq] + change (if RealGeometry.edge source target (4*(2*K+2)) e.1 e.2=s(x,y) + then val (TreeFraction.repr (RationalSource.pathActivity w K e.1 e.2)) else 0)=_ + split_ifs + · exact val_repr (pathActivity_nonneg hn w hw K _ _) + · rfl + have hrow (e : RawReal) (he : e∈es) : + contribution ((vertexRepr x,vertexRepr y),pathRow + ((((matrixRep w,matrixRep (RationalSource.logicalB w)),fuel),List.range n),e))= + TreeFraction.repr (f e) := by + have hm : e∈(realEdges (List.range n,fuel)).toFinset:=List.mem_toFinset.mpr he + rw [realEdges_finset n K fuel hf] at hm + obtain ⟨a,_,rfl⟩:=Finset.mem_image.mp hm + rw [hre] + exact contribution_source_repr hn w hw K fuel hf x y a + unfold activity pathTable + rw [List.map_map] + dsimp only [Function.comp,Prod.fst,Prod.snd] + have hmap : (es.map fun e=>contribution ((vertexRepr x,vertexRepr y),pathRow + ((((matrixRep w,matrixRep (RationalSource.logicalB w)),fuel),List.range n),e)))= + (es.map f).map TreeFraction.repr := by + rw [List.map_map] + exact List.map_congr_left hrow + change sum (es.map (fun e=>contribution ((vertexRepr x,vertexRepr y),pathRow + ((((matrixRep w,matrixRep (RationalSource.logicalB w)),fuel),List.range n),e)))) = _ + rw [hmap,sum_repr] + · congr 1 + rw [sum_realEdges n K fuel hf] + exact Finset.sum_congr rfl (fun e _=>hre e) + · intro q hq + obtain ⟨e,he,rfl⟩:=List.mem_map.mp hq + have hm : e∈(realEdges (List.range n,fuel)).toFinset:=List.mem_toFinset.mpr he + rw [realEdges_finset n K fuel hf] at hm + obtain ⟨a,_,rfl⟩:=Finset.mem_image.mp hm + rw [hre] + exact hg a +end MatchingFPRAS.ExecutableSource + +end OAI diff --git a/lean/OAI/Combinatorics/MatchingCount/Arithmetic/ArithmeticSize.lean b/lean/OAI/Combinatorics/MatchingCount/Arithmetic/ArithmeticSize.lean new file mode 100644 index 0000000000000000000000000000000000000000..4566badf0a8c7a79d65d203f3121eda533082081 --- /dev/null +++ b/lean/OAI/Combinatorics/MatchingCount/Arithmetic/ArithmeticSize.lean @@ -0,0 +1,494 @@ +import Mathlib +import OAI.Combinatorics.MatchingCount.Probability.Variance +import OAI.Combinatorics.MatchingCount.Arithmetic.PostAddition +import OAI.Combinatorics.MatchingCount.Arithmetic.PostComparison + +namespace OAI + +namespace MatchingFPRAS.StackWords +open Turing + +lemma encoded_length {K : Type*} {Γ : K → Type*} {w : ℕ} + (enc : TM2to1.Γ' K Γ → List.Vector Bool w) (S : ∀ k,List (Γ k)) (H : ℕ) : + (encoded enc S H).length=w*(H-1+1) := by + unfold encoded FixedAlphabetCompiler.word + rw [List.length_map,FixedEncoding.bitsWord_length] + congr 1 + change ((rows S H).tail.map (fun a=>(false,a))).length+1=H-1+1 + rw [List.length_map,List.length_tail] + simp only [rows,List.length_ofFn] +end MatchingFPRAS.StackWords +namespace MatchingFPRAS.PostAddition +lemma input_length (A B : List Bool) : + (input A B).length=Fintype.card Alphabet*(A.length+B.length-1+1) := + StackWords.encoded_length _ _ _ +lemma input_length_bounds (A B : List Bool) : + A.length+B.length≤(input A B).length ∧ 1≤(input A B).length := by + have hw : 1≤Fintype.card Alphabet := Fintype.card_pos + have h := Nat.mul_le_mul_right (A.length+B.length-1+1) hw + rw [one_mul,←input_length A B] at h + omega +lemma bit_time_bound (A B : List Bool) : + steps A B ≤ (100*overhead+2)*(input A B).length^2 := by + obtain ⟨hs,hp⟩:=input_length_bounds A B + have hc : 1+6*(A.length+B.length+3*(A.length+B.length+1)+1)≤25*(A.length+B.length+1) := by omega + have ht : steps A B≤25*overhead*(A.length+B.length+1)^2+2 := by + unfold steps + calc + _ ≤ overhead*((A.length+B.length+1)*(25*(A.length+B.length+1)))+2 := by gcongr + _ = _ := by ring + have hsq : (A.length+B.length+1)^2≤4*(input A B).length^2 := by nlinarith + have hh:=Nat.mul_le_mul_left (25*overhead) hsq + have hh' : 1≤(input A B).length^2 := by nlinarith + nlinarith +end MatchingFPRAS.PostAddition +namespace MatchingFPRAS.PostComparison +lemma input_length (A B : List Bool) : + (input A B).length=Fintype.card Alphabet*(A.length+B.length-1+1) := + StackWords.encoded_length _ _ _ +lemma input_length_bounds (A B : List Bool) : + A.length+B.length≤(input A B).length ∧ 1≤(input A B).length := by + have hw : 1≤Fintype.card Alphabet := Fintype.card_pos + have h := Nat.mul_le_mul_right (A.length+B.length-1+1) hw + rw [one_mul,←input_length A B] at h + omega +lemma bit_time_bound (A B : List Bool) : + steps A B ≤ (164*overhead+2)*(input A B).length^2 := by + obtain ⟨hs,hp⟩:=input_length_bounds A B + have hc : 1+8*(A.length+B.length+4*(A.length+B.length+1)+1)≤41*(A.length+B.length+1) := by omega + have ht : steps A B≤41*overhead*(A.length+B.length+1)^2+2 := by + unfold steps + calc + _ ≤ overhead*((A.length+B.length+1)*(41*(A.length+B.length+1)))+2 := by gcongr + _ = _ := by ring + have hsq : (A.length+B.length+1)^2≤4*(input A B).length^2 := by nlinarith + have hh:=Nat.mul_le_mul_left (41*overhead) hsq + have hh' : 1≤(input A B).length^2 := by nlinarith + nlinarith +end MatchingFPRAS.PostComparison + +namespace MatchingFPRAS.StackComposition +open Turing MachineCost + +variable {K Λ P σ : Type*} {Γ : K → Type*} [DecidableEq K] +def relabel (f : Λ → P) (h : Option P) : TM2.Stmt Γ Λ σ → TM2.Stmt Γ P σ + | .push k a q => .push k a (relabel f h q) + | .peek k a q => .peek k a (relabel f h q) + | .pop k a q => .pop k a (relabel f h q) + | .load a q => .load a (relabel f h q) + | .branch p q r => .branch p (relabel f h q) (relabel f h r) + | .goto l => .goto (fun a=>f (l a)) + | .halt => match h with | none=>.halt | some k=>.goto (fun _=>k) +def mapCfg (f : Λ → P) (h : Option P) (c : TM2.Cfg Γ Λ σ) : TM2.Cfg Γ P σ := + ⟨c.l.bind (fun l=>some (f l)) |>.or h,c.var,c.stk⟩ +omit [DecidableEq K] in +lemma mapCfg_some (f : Λ → P) (h : Option P) (l : Λ) (v : σ) (S : ∀ k,List (Γ k)) : + mapCfg f h ⟨some l,v,S⟩=⟨some (f l),v,S⟩ := rfl +omit [DecidableEq K] in +lemma mapCfg_none (f : Λ → P) (h : Option P) (v : σ) (S : ∀ k,List (Γ k)) : + mapCfg f h ⟨none,v,S⟩=⟨h,v,S⟩ := rfl +lemma relabel_eval (f : Λ → P) (h : Option P) (q : TM2.Stmt Γ Λ σ) + (v : σ) (S : ∀ k,List (Γ k)) : + TM2.stepAux (relabel f h q) v S=mapCfg f h (TM2.stepAux q v S) := by + induction q generalizing v S with + | push k a q ih => exact ih v _ + | peek k a q ih => exact ih _ S + | pop k a q ih => exact ih _ _ + | load a q ih => exact ih (a v) S + | branch p q r ihq ihr => + cases hp:p v <;> simp only [relabel,TM2.stepAux,hp,Bool.cond_false,Bool.cond_true] <;> + first | apply ihr | apply ihq + | goto l => rfl + | halt => cases h <;> rfl +omit [DecidableEq K] in +lemma relabel_accesses (f : Λ → P) (h : Option P) (q : TM2.Stmt Γ Λ σ) : + StackCost.accesses (relabel f h q)=StackCost.accesses q := by + induction q with + | push k a q ih | peek k a q ih | pop k a q ih | load a q ih => + simp only [relabel,StackCost.accesses,ih] + | branch p q r ihq ihr => simp only [relabel,StackCost.accesses,ihq,ihr] + | goto l => rfl + | halt => cases h <;> rfl +lemma run_halted (M : Λ → TM2.Stmt Γ Λ σ) (n : ℕ) + (v : σ) (S : ∀ k,List (Γ k)) : + MachineCost.run (TM2.step M) n ⟨none,v,S⟩=⟨none,v,S⟩ := by + induction n with + | zero => rfl + | succ n ih => simpa only [MachineCost.run,advance,TM2.step,Option.getD_none] using ih +lemma run_relabel_to_halt (M : Λ → TM2.Stmt Γ Λ σ) (N : P → TM2.Stmt Γ P σ) + (f : Λ → P) (h : Option P) (hN : ∀ l,N (f l)=relabel f h (M l)) + (n : ℕ) (c : TM2.Cfg Γ Λ σ) (v : σ) (S : ∀ k,List (Γ k)) + (he : MachineCost.run (TM2.step M) n c=⟨none,v,S⟩) : + ∃ k≤n,MachineCost.run (TM2.step N) k (mapCfg f h c)=⟨h,v,S⟩ := by + induction n generalizing c with + | zero => + have hc : c=⟨none,v,S⟩:=he + subst c + exact ⟨0,le_rfl,rfl⟩ + | succ n ih => + rcases c with ⟨l,v',S'⟩ + cases l with + | none => + rw [run_halted] at he + cases he + exact ⟨0,Nat.zero_le _,rfl⟩ + | some l => + have he' : MachineCost.run (TM2.step M) n (TM2.stepAux (M l) v' S')=⟨none,v,S⟩ := he + obtain ⟨k,hk,hh⟩:=ih _ he' + refine ⟨k+1,by omega,?_⟩ + rw [MachineCost.run,mapCfg_some] + have hs : advance (TM2.step N) ⟨some (f l),v',S'⟩= + mapCfg f h (TM2.stepAux (M l) v' S') := by + simp only [advance,TM2.step,Option.getD_some,hN,relabel_eval] + rw [hs,hh] +variable [Inhabited Λ] [Inhabited P] +def sequence (M : Λ → TM2.Stmt Γ Λ σ) (N : P → TM2.Stmt Γ P σ) : + Λ⊕P → TM2.Stmt Γ (Λ⊕P) σ + | .inl l => relabel Sum.inl (some (Sum.inr default)) (M l) + | .inr k => relabel Sum.inr none (N k) +omit [Inhabited Λ] in +lemma sequence_run (M : Λ → TM2.Stmt Γ Λ σ) (N : P → TM2.Stmt Γ P σ) + (c : TM2.Cfg Γ Λ σ) (m n : ℕ) (v v' : σ) (S S' : ∀ k,List (Γ k)) + (hM : MachineCost.run (TM2.step M) m c=⟨none,v,S⟩) + (hN : MachineCost.run (TM2.step N) n ⟨some default,v,S⟩=⟨none,v',S'⟩) : + ∃ k ≤ m+n,MachineCost.run (TM2.step (sequence M N)) k + (mapCfg Sum.inl (some (Sum.inr default)) c)=⟨none,v',S'⟩ := by + obtain ⟨i,hi,hei⟩:=run_relabel_to_halt M (sequence M N) Sum.inl + (some (Sum.inr default)) (fun _=>rfl) m c v S hM + obtain ⟨j,hj,hej⟩:=run_relabel_to_halt N (sequence M N) Sum.inr + none (fun _=>rfl) n ⟨some default,v,S⟩ v' S' hN + refine ⟨i+j,by omega,?_⟩ + rw [run_add,hei] + exact hej +omit [DecidableEq K] [Inhabited Λ] in +lemma sequence_accesses (M : Λ → TM2.Stmt Γ Λ σ) (N : P → TM2.Stmt Γ P σ) + (A B : ℕ) (hM : ∀ l,StackCost.accesses (M l)≤A) (hN : ∀ l,StackCost.accesses (N l)≤B) + (l : Λ⊕P) : StackCost.accesses (sequence M N l) ≤ max A B := by + cases l with + | inl l => exact (by rw [sequence,relabel_accesses]; exact (hM l).trans (le_max_left _ _)) + | inr l => exact (by rw [sequence,relabel_accesses]; exact (hN l).trans (le_max_right _ _)) +omit [DecidableEq K] in +lemma supports_univ [Fintype Λ] (M : Λ → TM2.Stmt Γ Λ σ) : TM2.Supports M Finset.univ := by + constructor + · simp + · intro l _ + induction M l with + | push k a q ih | peek k a q ih | pop k a q ih | load a q ih => exact ih + | branch p q r ihq ihr => exact ⟨ihq,ihr⟩ + | goto l => simp [TM2.SupportsStmt] + | halt => trivial + +open Turing MachineCost + +variable {K Λ σ : Type*} {Γ : K → Type*} [DecidableEq K] [Inhabited Λ] +def loop (M : Λ → TM2.Stmt Γ Λ σ) (p : σ → Bool) : + Unit ⊕ Λ → TM2.Stmt Γ (Unit ⊕ Λ) σ + | .inl _ => .branch p (.goto (fun _ => .inr default)) .halt + | .inr l => relabel Sum.inr (some (Sum.inl ())) (M l) +lemma loop_stop (M : Λ → TM2.Stmt Γ Λ σ) (p : σ → Bool) + (v : σ) (S : ∀ k,List (Γ k)) (hp : p v=false) : + MachineCost.run (TM2.step (loop M p)) 1 ⟨some (.inl ()),v,S⟩=⟨none,v,S⟩ := by + simp [MachineCost.run,advance,TM2.step,loop,TM2.stepAux,hp] +lemma loop_once (M : Λ → TM2.Stmt Γ Λ σ) (p : σ → Bool) + (m : ℕ) (v v' : σ) (S S' : ∀ k,List (Γ k)) (hp : p v=true) + (hM : MachineCost.run (TM2.step M) m ⟨some default,v,S⟩=⟨none,v',S'⟩) : + ∃ k ≤ m+1,MachineCost.run (TM2.step (loop M p)) k + ⟨some (.inl ()),v,S⟩=⟨some (.inl ()),v',S'⟩ := by + obtain ⟨k,hk,he⟩:=run_relabel_to_halt M (loop M p) Sum.inr + (some (Sum.inl ())) (fun _=>rfl) m ⟨some default,v,S⟩ v' S' hM + refine ⟨k+1,by omega,?_⟩ + simpa [MachineCost.run,advance,TM2.step,loop,TM2.stepAux,hp,mapCfg] using he +omit [DecidableEq K] in +lemma loop_accesses (M : Λ → TM2.Stmt Γ Λ σ) (p : σ → Bool) (a : ℕ) + (hM : ∀ l,StackCost.accesses (M l)≤a) (l : Unit⊕Λ) : + StackCost.accesses (loop M p l)≤a := by + cases l with + | inl l => simp [loop,StackCost.accesses] + | inr l => simpa [loop,relabel_accesses] using hM l + +lemma loop_bounded (M : Λ → TM2.Stmt Γ Λ σ) (p : σ → Bool) + (I : ℕ → σ → (∀ k,List (Γ k)) → Prop) (b : ℕ) + (hz : ∀ v S,I 0 v S → p v=false) + (hn : ∀ n v S,I (n+1) v S → p v=true ∧ + ∃ m≤b,∃ v' S',I n v' S' ∧ + MachineCost.run (TM2.step M) m ⟨some default,v,S⟩=⟨none,v',S'⟩) + (n : ℕ) (v : σ) (S : ∀ k,List (Γ k)) (hI : I n v S) : + ∃ k≤n*(b+1)+1,∃ v' S',I 0 v' S' ∧ + MachineCost.run (TM2.step (loop M p)) k ⟨some (.inl ()),v,S⟩=⟨none,v',S'⟩ := by + induction n generalizing v S with + | zero => exact ⟨1,by simp,v,S,hI,loop_stop M p v S (hz _ _ hI)⟩ + | succ n ih => + obtain ⟨hp,m,hm,w,T,hT,he⟩:=hn n v S hI + obtain ⟨j,hj,hjrun⟩:=loop_once M p m v w S T hp he + obtain ⟨k,hk,w',T',hT',hkrun⟩:=ih w T hT + refine ⟨j+k,?_,w',T',hT',?_⟩ + · calc + j+k ≤ (b+1)+(n*(b+1)+1) := by omega + _ = (n+1)*(b+1)+1 := by ring + · rw [run_add,hjrun,hkrun] +end MatchingFPRAS.StackComposition + +namespace MatchingFPRAS.StackReverse +open Turing MachineCost StackAddition + +abbrev S := Option Bool +abbrev Γ := fun _ : Fin 3 => Bool +def program : Unit → TM2.Stmt Γ Unit S := fun _ => + .pop 0 (fun _ a=>a) + (.branch Option.isNone (.load (fun _=>none) .halt) + (.push 1 (fun v=>v.getD false) (.goto (fun _=>())))) +def cfg (l : Option Unit) (A B C : List Bool) (v : S) : TM2.Cfg Γ Unit S := + ⟨l,v,stackData A B C⟩ +lemma next_empty (B C : List Bool) (v : S) : + advance (TM2.step program) (cfg (some ()) [] B C v)=cfg none [] B C none := by + simp [advance,TM2.step,program,TM2.stepAux,cfg,update_zero] +lemma next_cons (a : Bool) (A B C : List Bool) (v : S) : + advance (TM2.step program) (cfg (some ()) (a::A) B C v)= + cfg (some ()) A (a::B) C (some a) := by + simp [advance,TM2.step,program,TM2.stepAux,cfg,update_zero,update_one] +theorem run_reverse (A B C : List Bool) (v : S) : + MachineCost.run (TM2.step program) (A.length+1) (cfg (some ()) A B C v)= + cfg none [] (A.reverse++B) C none := by + induction A generalizing B v with + | nil => simpa only [List.length_nil,List.reverse_nil,List.nil_append,MachineCost.run] using next_empty B C v + | cons a A ih => + rw [List.length_cons,show A.length+1+1=(A.length+1)+1 by rfl,MachineCost.run,next_cons,ih] + simp [List.reverse_cons,List.append_assoc] +lemma accesses_bound (l : Unit) : StackCost.accesses (program l)≤2 := by + simp [program,StackCost.accesses] +lemma finite_support : TM2.Supports program Finset.univ := by + constructor + · simp + · intro l _ + simp [program,TM2.SupportsStmt] +lemma reverse_addition_numerals (m n : ℕ) : + value ((addDigits false m.bits n.bits).reverse.reverse++[]) = m+n := by + simpa only [List.reverse_reverse,List.append_nil] using addition_numerals m n +end MatchingFPRAS.StackReverse + +namespace MatchingFPRAS.PostReverse +open Turing StackReverse StackAddition + +abbrev Alphabet := TM2to1.Γ' (Fin 3) (fun _=>Bool) +noncomputable def machine : RandomMachine := + StackWords.compiled (FixedEncoding.enc Alphabet) (FixedEncoding.dec Alphabet) + StackReverse.program Finset.univ StackReverse.finite_support +noncomputable def overhead : ℕ := + StackWords.cost (FixedEncoding.enc Alphabet) (FixedEncoding.dec Alphabet) + StackReverse.program Finset.univ +noncomputable def input (A B : List Bool) : List Symbol := + StackWords.encoded (FixedEncoding.enc Alphabet) (stackData A B []) (A.length+B.length) +noncomputable def output (A B : List Bool) : List Symbol := + StackWords.encoded (FixedEncoding.enc Alphabet) (stackData [] (A.reverse++B) []) (A.length+B.length) +noncomputable def steps (A B : List Bool) : ℕ := + overhead*((A.length+B.length+1)*(12*(A.length+B.length)+13))+2 +theorem computes (A B : List Bool) (t : ℕ) (ht : steps A B≤t) (bits : Fin t → Bool) : + (run machine (input A B) bits).state=none ∧ + (run machine (input A B) bits).tape.right₀=ListBlank.mk (output A B) := by + have h₀ : StackCost.StackBound (stackData A B []) (A.length+B.length) := by + intro i + fin_cases i <;> simp [stackData] + have he : MachineCost.run (TM2.step StackReverse.program) (A.length+1) + ⟨some (default : Unit),(default : StackReverse.S),stackData A B []⟩= + StackReverse.cfg none [] (A.reverse++B) [] none := run_reverse A B [] none + have hh : (MachineCost.run (TM2.step StackReverse.program) (A.length+1) + ⟨some (default : Unit),(default : StackReverse.S),stackData A B []⟩).l=none := by rw [he]; rfl + have ho : StackCost.StackBound (MachineCost.run (TM2.step StackReverse.program) (A.length+1) + ⟨some (default : Unit),(default : StackReverse.S),stackData A B []⟩).stk (A.length+B.length) := by + rw [he] + intro i + fin_cases i <;> simp [StackReverse.cfg,stackData] + have htime : StackWords.cost (FixedEncoding.enc Alphabet) (FixedEncoding.dec Alphabet) + StackReverse.program Finset.univ*((A.length+1)*(1+2*2*(A.length+B.length+(A.length+1)*2+1)))+2≤t := by + apply le_trans _ ht + unfold steps overhead + apply Nat.add_le_add_right + apply Nat.mul_le_mul_left + apply Nat.mul_le_mul <;> omega + have hc:=StackWords.compiled_execution (FixedEncoding.enc Alphabet) + (FixedEncoding.dec Alphabet) (FixedEncoding.blank Alphabet) (FixedEncoding.left_inverse Alphabet) + StackReverse.program Finset.univ StackReverse.finite_support 2 StackReverse.accesses_bound + (stackData A B []) (A.length+B.length) h₀ (A.length+1) (A.length+B.length) hh ho t htime bits + change (run machine (input A B) bits).state=none ∧ + (run machine (input A B) bits).tape.right₀=ListBlank.mk + (StackWords.encoded (FixedEncoding.enc Alphabet) + (MachineCost.run (TM2.step StackReverse.program) (A.length+1) + ⟨some (default : Unit),(default : StackReverse.S),stackData A B []⟩).stk + (A.length+B.length)) at hc + rw [he] at hc + exact hc +lemma time_quadratic (A B : List Bool) : + steps A B=overhead*(12*(A.length+B.length)^2+25*(A.length+B.length)+13)+2 := by + unfold steps + congr 2 + ring +end MatchingFPRAS.PostReverse + +namespace MatchingFPRAS.ForwardAddition +open Turing MachineCost StackAddition + +local instance initialControl : Inhabited (Bool⊕Unit) := ⟨.inl false⟩ +abbrev Γ := fun _ : Fin 3 => Bool +def reverseProgram : Unit → TM2.Stmt Γ Unit Store := fun _ => + .pop 2 (fun v a=>(a,v.2)) + (.branch (fun v=>v.1.isNone) (.load (fun _=>default) .halt) + (.push 0 (fun v=>v.1.getD false) (.goto (fun _=>())))) +def rcfg (l : Option Unit) (A B C : List Bool) (v : Store) : TM2.Cfg Γ Unit Store := + ⟨l,v,stackData A B C⟩ +lemma next_empty (A B : List Bool) (v : Store) : + advance (TM2.step reverseProgram) (rcfg (some ()) A B [] v)=rcfg none A B [] default := by + simp [advance,TM2.step,reverseProgram,TM2.stepAux,rcfg,update_two] +lemma next_cons (a : Bool) (A B C : List Bool) (v : Store) : + advance (TM2.step reverseProgram) (rcfg (some ()) A B (a::C) v)= + rcfg (some ()) (a::A) B C (some a,v.2) := by + simp [advance,TM2.step,reverseProgram,TM2.stepAux,rcfg,update_zero,update_two] +lemma run_reverse (A B C : List Bool) (v : Store) : + MachineCost.run (TM2.step reverseProgram) (C.length+1) (rcfg (some ()) A B C v)= + rcfg none (C.reverse++A) B [] default := by + induction C generalizing A v with + | nil => simpa only [List.length_nil,List.reverse_nil,List.nil_append,MachineCost.run] using next_empty A B v + | cons c C ih => + rw [List.length_cons,MachineCost.run,next_cons,ih] + simp [List.reverse_cons,List.append_assoc] +def program : Bool⊕Unit → TM2.Stmt Γ (Bool⊕Unit) Store := + StackComposition.sequence StackAddition.program reverseProgram +lemma run_add (A B : List Bool) : + ∃ k≤2*(A.length+B.length)+3, + MachineCost.run (TM2.step program) k ⟨some default,default,stackData A B []⟩= + ⟨none,default,stackData (addDigits false A B) [] []⟩ := by + obtain ⟨n,hn,he⟩:=run_addition A B [] false default + have he' : MachineCost.run (TM2.step StackAddition.program) n + (cfg (some false) A B [] default)=cfg none [] [] (addDigits false A B).reverse default := by + simpa only [List.append_nil] using he + have hr := run_reverse [] [] (addDigits false A B).reverse default + have hr' : MachineCost.run (TM2.step reverseProgram) ((addDigits false A B).length+1) + ⟨some default,default,stackData [] [] (addDigits false A B).reverse⟩= + ⟨none,default,stackData (addDigits false A B) [] []⟩ := by + simpa only [rcfg,List.length_reverse,List.reverse_reverse,List.append_nil] using hr + obtain ⟨k,hk,hkrun⟩:=StackComposition.sequence_run StackAddition.program reverseProgram + (cfg (some false) A B [] default) n ((addDigits false A B).length+1) + (default : Store) (default : Store) (stackData [] [] (addDigits false A B).reverse) + (stackData (addDigits false A B) [] []) he' hr' + refine ⟨k,?_,?_⟩ + · have hl:=addDigits_length A B false + omega + · exact hkrun +lemma accesses_bound (l : Bool⊕Unit) : StackCost.accesses (program l)≤3 := by + apply StackComposition.sequence_accesses StackAddition.program reverseProgram 3 3 StackAddition.accesses_bound + intro k + simp [reverseProgram,StackCost.accesses] +lemma support : TM2.Supports program Finset.univ := StackComposition.supports_univ program +lemma result_value (m n : ℕ) : value (addDigits false m.bits n.bits)=m+n := addition_numerals m n +end MatchingFPRAS.ForwardAddition + +namespace MatchingFPRAS.PostForwardAddition +open Turing StackAddition ForwardAddition + +local instance initialControl : Inhabited (Bool⊕Unit) := ⟨.inl false⟩ +abbrev Alphabet := TM2to1.Γ' (Fin 3) (fun _=>Bool) +lemma support : TM2.Supports ForwardAddition.program Finset.univ := + StackComposition.supports_univ ForwardAddition.program +noncomputable def machine : RandomMachine := + StackWords.compiled (FixedEncoding.enc Alphabet) (FixedEncoding.dec Alphabet) + ForwardAddition.program Finset.univ support +noncomputable def overhead : ℕ := + StackWords.cost (FixedEncoding.enc Alphabet) (FixedEncoding.dec Alphabet) + ForwardAddition.program Finset.univ +noncomputable def input (A B : List Bool) : List Symbol := + StackWords.encoded (FixedEncoding.enc Alphabet) (stackData A B []) (A.length+B.length) +noncomputable def output (A B : List Bool) : List Symbol := + StackWords.encoded (FixedEncoding.enc Alphabet) + (stackData (addDigits false A B) [] []) (A.length+B.length+1) +noncomputable def steps (A B : List Bool) : ℕ := + overhead*((2*(A.length+B.length)+3)*(42*(A.length+B.length)+61))+2 +theorem computes (A B : List Bool) (t : ℕ) (ht : steps A B≤t) (bits : Fin t → Bool) : + (run machine (input A B) bits).state=none ∧ + (run machine (input A B) bits).tape.right₀=ListBlank.mk (output A B) := by + obtain ⟨n,hn,he⟩:=ForwardAddition.run_add A B + have h₀ : StackCost.StackBound (stackData A B []) (A.length+B.length) := by + intro i + fin_cases i <;> simp [stackData] + have hh : (MachineCost.run (TM2.step ForwardAddition.program) n + ⟨some (default : Bool⊕Unit),(default : Store),stackData A B []⟩).l=none := by rw [he] + have ho : StackCost.StackBound (MachineCost.run (TM2.step ForwardAddition.program) n + ⟨some (default : Bool⊕Unit),(default : Store),stackData A B []⟩).stk (A.length+B.length+1) := by + rw [he] + intro i + have hl:=addDigits_length A B false + fin_cases i <;> simp [stackData] + omega + have htime : StackWords.cost (FixedEncoding.enc Alphabet) (FixedEncoding.dec Alphabet) + ForwardAddition.program Finset.univ*(n*(1+2*3*(A.length+B.length+n*3+1)))+2≤t := by + apply le_trans _ ht + unfold steps overhead + apply Nat.add_le_add_right + apply Nat.mul_le_mul_left + apply Nat.mul_le_mul hn + omega + have hc:=StackWords.compiled_execution (FixedEncoding.enc Alphabet) + (FixedEncoding.dec Alphabet) (FixedEncoding.blank Alphabet) (FixedEncoding.left_inverse Alphabet) + ForwardAddition.program Finset.univ support 3 ForwardAddition.accesses_bound + (stackData A B []) (A.length+B.length) h₀ n (A.length+B.length+1) hh ho t htime bits + change (run machine (input A B) bits).state=none ∧ + (run machine (input A B) bits).tape.right₀=ListBlank.mk + (StackWords.encoded (FixedEncoding.enc Alphabet) + (MachineCost.run (TM2.step ForwardAddition.program) n + ⟨some (default : Bool⊕Unit),(default : Store),stackData A B []⟩).stk + (A.length+B.length+1)) at hc + rw [he] at hc + exact hc +lemma time_quadratic (A B : List Bool) : + steps A B=overhead*(84*(A.length+B.length)^2+248*(A.length+B.length)+183)+2 := by + unfold steps + congr 2 + ring +end MatchingFPRAS.PostForwardAddition + +namespace MatchingFPRAS.PostReverse +lemma input_length (A B : List Bool) : + (input A B).length=Fintype.card Alphabet*(A.length+B.length-1+1) := + StackWords.encoded_length _ _ _ +lemma input_length_bounds (A B : List Bool) : + A.length+B.length≤(input A B).length ∧ 1≤(input A B).length := by + have hw : 1≤Fintype.card Alphabet := Fintype.card_pos + have h := Nat.mul_le_mul_right (A.length+B.length-1+1) hw + rw [one_mul,←input_length A B] at h + omega +lemma bit_time_bound (A B : List Bool) : + steps A B≤(52*overhead+2)*(input A B).length^2 := by + obtain ⟨hs,hp⟩:=input_length_bounds A B + have ht : steps A B≤13*overhead*(A.length+B.length+1)^2+2 := by + unfold steps + calc + _ ≤ overhead*((A.length+B.length+1)*(13*(A.length+B.length+1)))+2 := by gcongr; omega + _ = _ := by ring + have hsq : (A.length+B.length+1)^2≤4*(input A B).length^2 := by nlinarith + have hh:=Nat.mul_le_mul_left (13*overhead) hsq + have hh' : 1≤(input A B).length^2 := by nlinarith + nlinarith +end MatchingFPRAS.PostReverse +namespace MatchingFPRAS.PostForwardAddition +lemma input_length (A B : List Bool) : + (input A B).length=Fintype.card Alphabet*(A.length+B.length-1+1) := + StackWords.encoded_length _ _ _ +lemma input_length_bounds (A B : List Bool) : + A.length+B.length≤(input A B).length ∧ 1≤(input A B).length := by + have hw : 1≤Fintype.card Alphabet := Fintype.card_pos + have h := Nat.mul_le_mul_right (A.length+B.length-1+1) hw + rw [one_mul,←input_length A B] at h + omega +lemma bit_time_bound (A B : List Bool) : + steps A B≤(732*overhead+2)*(input A B).length^2 := by + obtain ⟨hs,hp⟩:=input_length_bounds A B + have ht : steps A B≤183*overhead*(A.length+B.length+1)^2+2 := by + unfold steps + calc + _ ≤ overhead*((3*(A.length+B.length+1))*(61*(A.length+B.length+1)))+2 := by gcongr <;> omega + _ = _ := by ring + have hsq : (A.length+B.length+1)^2≤4*(input A B).length^2 := by nlinarith + have hh:=Nat.mul_le_mul_left (183*overhead) hsq + have hh' : 1≤(input A B).length^2 := by nlinarith + nlinarith +end MatchingFPRAS.PostForwardAddition + +end OAI diff --git a/lean/OAI/Combinatorics/MatchingCount/Arithmetic/BinaryAddition.lean b/lean/OAI/Combinatorics/MatchingCount/Arithmetic/BinaryAddition.lean new file mode 100644 index 0000000000000000000000000000000000000000..247361e31369c1c57cb1679cf60e8bbfef323f96 --- /dev/null +++ b/lean/OAI/Combinatorics/MatchingCount/Arithmetic/BinaryAddition.lean @@ -0,0 +1,168 @@ +import Mathlib +import OAI.Combinatorics.MatchingCount.Complexity.StackCompilerCost + +namespace OAI + +namespace MatchingFPRAS.StackAddition +open Turing MachineCost + +abbrev Stacks := Fin 3 → List Bool +abbrev Store := Option Bool × Option Bool +def value : List Bool → ℕ + | [] => 0 + | b::bs => b.toNat+2*value bs +def digit (c a b : Bool) : Bool := xor (xor c a) b +def carry (c a b : Bool) : Bool := (c && a) || (c && b) || (a && b) +lemma digit_identity (c a b : Bool) : + (digit c a b).toNat+2*(carry c a b).toNat=c.toNat+a.toNat+b.toNat := by + cases c <;> cases a <;> cases b <;> rfl + +def addDigits (c : Bool) (A B : List Bool) : List Bool := + match A,B with + | [],[] => if c then [true] else [] + | a::A,[] => digit c a false::addDigits (carry c a false) A [] + | [],b::B => digit c false b::addDigits (carry c false b) [] B + | a::A,b::B => digit c a b::addDigits (carry c a b) A B +termination_by A.length+B.length + +lemma addDigits_value (A B : List Bool) (c : Bool) : + value (addDigits c A B)=value A+value B+c.toNat := by + induction A generalizing B c with + | nil => + induction B generalizing c with + | nil => cases c <;> simp [addDigits,value] + | cons b B ih => + rw [addDigits] + simp only [value] + rw [ih] + have h:=digit_identity c false b + simp only [Bool.toNat_false,Nat.add_zero] at h + simp only [value] + omega + | cons a A ih => + cases B with + | nil => + rw [addDigits] + simp only [value] + rw [ih] + have h:=digit_identity c a false + simp only [Bool.toNat_false,Nat.add_zero] at h + simp only [value] + omega + | cons b B => + rw [addDigits] + simp only [value] + rw [ih] + have h:=digit_identity c a b + omega +lemma addDigits_length (A B : List Bool) (c : Bool) : + (addDigits c A B).length ≤ max A.length B.length+1 := by + induction A generalizing B c with + | nil => + induction B generalizing c with + | nil => cases c <;> simp [addDigits] + | cons b B ih => + rw [addDigits,List.length_cons] + have h:=ih (carry c false b) + simp only [List.length_nil,Nat.zero_max,List.length_cons] at h ⊢ + omega + | cons a A ih => + cases B with + | nil => + rw [addDigits,List.length_cons] + have h:=ih [] (carry c a false) + simp only [List.length_nil,Nat.max_zero,List.length_cons] at h ⊢ + omega + | cons b B => + rw [addDigits,List.length_cons] + have h:=ih B (carry c a b) + simp only [List.length_cons] + omega + +def program (c : Bool) : TM2.Stmt (fun _ : Fin 3=>Bool) Bool Store := + .pop 0 (fun v a=>(a,v.2)) (.pop 1 (fun v b=>(v.1,b)) + (.branch (fun v=>v.1.isNone && v.2.isNone) + (.branch (fun _=>c) (.push 2 (fun _=>true) (.load (fun _=>default) .halt)) + (.load (fun _=>default) .halt)) + (.push 2 (fun v=>digit c (v.1.getD false) (v.2.getD false)) + (.goto (fun v=>carry c (v.1.getD false) (v.2.getD false)))))) +def stackData (A B L : List Bool) : Stacks := ![A,B,L] +@[simp] lemma stackData_zero (A B L : List Bool) : stackData A B L 0=A := rfl +@[simp] lemma stackData_one (A B L : List Bool) : stackData A B L 1=B := rfl +@[simp] lemma stackData_two (A B L : List Bool) : stackData A B L 2=L := rfl +def cfg (c : Option Bool) (A B L : List Bool) (v : Store) : + TM2.Cfg (fun _ : Fin 3=>Bool) Bool Store := ⟨c,v,stackData A B L⟩ +lemma update_zero (A B L X : List Bool) : + Function.update (stackData A B L) 0 X=stackData X B L := by + funext i + fin_cases i <;> simp [stackData] +lemma update_one (A B L X : List Bool) : + Function.update (stackData A B L) 1 X=stackData A X L := by + funext i + fin_cases i <;> simp [stackData] +lemma update_two (A B L X : List Bool) : + Function.update (stackData A B L) 2 X=stackData A B X := by + funext i + fin_cases i <;> simp [stackData] +lemma step_empty (c : Bool) (L : List Bool) (v : Store) : + advance (TM2.step program) (cfg (some c) [] [] L v)= + cfg none [] [] ((addDigits c [] []).reverse++L) default := by + cases c <;> simp [advance,TM2.step,program,TM2.stepAux,cfg, + update_zero,update_one,update_two,addDigits] +lemma step_digits (c : Bool) (A B L : List Bool) (v : Store) + (h : A≠[] ∨ B≠[]) : + advance (TM2.step program) (cfg (some c) A B L v)= + cfg (some (carry c (A.headD false) (B.headD false))) A.tail B.tail + (digit c (A.headD false) (B.headD false)::L) (A.head?,B.head?) := by + cases A <;> cases B <;> simp_all [advance,TM2.step,program,TM2.stepAux,cfg, + update_zero,update_one,update_two] +lemma addDigits_step (c : Bool) (A B : List Bool) (h : A ≠ [] ∨ B ≠ []) : + addDigits c A B=digit c (A.headD false) (B.headD false):: + addDigits (carry c (A.headD false) (B.headD false)) A.tail B.tail := by + cases A <;> cases B <;> simp_all [addDigits] + +theorem run_addition (A B L : List Bool) (c : Bool) (v : Store) : + ∃ t ≤ A.length+B.length+1, + MachineCost.run (TM2.step program) t (cfg (some c) A B L v)= + cfg none [] [] ((addDigits c A B).reverse++L) default := by + have aux : ∀ n (A B : List Bool), A.length+B.length=n → + ∀ (c : Bool) (L : List Bool) (v : Store), + ∃ t ≤ A.length+B.length+1, + MachineCost.run (TM2.step program) t (cfg (some c) A B L v)= + cfg none [] [] ((addDigits c A B).reverse++L) default := by + intro n + induction n using Nat.strong_induction_on with + | h n ih => + intro A B hn c L v + by_cases he : A=[] ∧ B=[] + · rcases he with ⟨rfl,rfl⟩ + exact ⟨1,by simp,step_empty c L v⟩ + · have hne : A≠[] ∨ B≠[] := by tauto + have hlt : A.tail.length+B.tail.length cases B <;> simp_all + all_goals omega + obtain ⟨t,ht,hr⟩:=ih _ hlt A.tail B.tail rfl + (carry c (A.headD false) (B.headD false)) + (digit c (A.headD false) (B.headD false)::L) (A.head?,B.head?) + refine ⟨t+1,by omega,?_⟩ + rw [MachineCost.run,step_digits c A B L v hne,hr,addDigits_step c A B hne] + simp only [List.reverse_cons,List.append_assoc,List.singleton_append] + exact aux _ A B rfl c L v +lemma accesses_bound (c : Bool) : StackCost.accesses (program c) ≤ 3 := by + cases c <;> decide +lemma finite_support : TM2.Supports program Finset.univ := by + simp [TM2.Supports,program,TM2.SupportsStmt] +lemma value_bits (n : ℕ) : value n.bits=n := by + induction n using Nat.binaryRec' with + | zero => rfl + | bit b n h ih => + rw [Nat.bits_append_bit n b h] + simp only [value,ih] + cases b <;> simp [Nat.bit,Bool.toNat] + omega + +lemma addition_numerals (m n : ℕ) : value (addDigits false m.bits n.bits)=m+n := by + simp only [addDigits_value,value_bits,Bool.toNat_false,Nat.add_zero] +end MatchingFPRAS.StackAddition + +end OAI diff --git a/lean/OAI/Combinatorics/MatchingCount/Arithmetic/BinaryCompare.lean b/lean/OAI/Combinatorics/MatchingCount/Arithmetic/BinaryCompare.lean new file mode 100644 index 0000000000000000000000000000000000000000..a982033fbe5097230f2ec8d5d090e87ad148b744 --- /dev/null +++ b/lean/OAI/Combinatorics/MatchingCount/Arithmetic/BinaryCompare.lean @@ -0,0 +1,118 @@ +import Mathlib +import OAI.Combinatorics.MatchingCount.Arithmetic.BinaryAddition + +namespace OAI + +namespace MatchingFPRAS.StackCompare +open Turing MachineCost StackAddition + +def updateOrder (c : Ordering) (a b : Bool) : Ordering := + if a=b then c else if a then .gt else .lt + +def compareDigits (c : Ordering) (A B : List Bool) : Ordering := + match A,B with + | [],[] => c + | a::A,[] => compareDigits (updateOrder c a false) A [] + | [],b::B => compareDigits (updateOrder c false b) [] B + | a::A,b::B => compareDigits (updateOrder c a b) A B +termination_by A.length+B.length + +def result (c : Ordering) (m n : ℕ) : Ordering := if m=n then c else compare m n +lemma result_digits (c : Ordering) (a b : Bool) (m n : ℕ) : + result (updateOrder c a b) m n=result c (a.toNat+2*m) (b.toNat+2*n) := by + rcases lt_trichotomy m n with h|h|h + · have hb : a.toNat+2*m < b.toNat+2*n := by + cases a <;> cases b <;> simp only [Bool.toNat_true,Bool.toNat_false] <;> omega + simp [result,ne_of_lt h,ne_of_lt hb,compare_lt_iff_lt.mpr h,compare_lt_iff_lt.mpr hb] + · subst n + cases a <;> cases b <;> cases c <;> + simp [result,updateOrder,eq_comm] + all_goals first + | exact (compare_lt_iff_lt.mpr (by omega)).symm + | exact (compare_gt_iff_gt.mpr (by omega)).symm + · have hb : b.toNat+2*n < a.toNat+2*m := by + cases a <;> cases b <;> simp only [Bool.toNat_true,Bool.toNat_false] <;> omega + simp [result,ne_of_gt h,ne_of_gt hb,compare_gt_iff_gt.mpr h,compare_gt_iff_gt.mpr hb] +lemma compareDigits_result (A B : List Bool) (c : Ordering) : + compareDigits c A B=result c (value A) (value B) := by + induction A generalizing B c with + | nil => + induction B generalizing c with + | nil => simp [compareDigits,result,value] + | cons b B ih => + rw [compareDigits,ih] + simpa only [value,Bool.toNat_false,Nat.zero_add,Nat.mul_zero] using result_digits c false b 0 (value B) + | cons a A ih => + cases B with + | nil => + rw [compareDigits,ih] + simpa only [value,Bool.toNat_false,Nat.zero_add,Nat.mul_zero,Nat.add_zero] using result_digits c a false (value A) 0 + | cons b B => + rw [compareDigits,ih] + exact result_digits c a b (value A) (value B) +lemma compares_values (A B : List Bool) : + compareDigits .eq A B=compare (value A) (value B) := by + rw [compareDigits_result] + unfold result + split_ifs with h + · simp [h] + · rfl +def flags (c : Ordering) : List Bool := [decide (c=.lt),decide (c=.gt)] +def program (c : Ordering) : TM2.Stmt (fun _ : Fin 3=>Bool) Ordering Store := + .pop 0 (fun v a=>(a,v.2)) (.pop 1 (fun v b=>(v.1,b)) + (.branch (fun v=>v.1.isNone && v.2.isNone) + (.push 2 (fun _=>decide (c=.gt)) (.push 2 (fun _=>decide (c=.lt)) + (.load (fun _=>default) .halt))) + (.goto (fun v=>updateOrder c (v.1.getD false) (v.2.getD false))))) +def cfg (c : Option Ordering) (A B L : List Bool) (v : Store) : + TM2.Cfg (fun _ : Fin 3=>Bool) Ordering Store := ⟨c,v,stackData A B L⟩ +lemma step_empty (c : Ordering) (L : List Bool) (v : Store) : + advance (TM2.step program) (cfg (some c) [] [] L v)= + cfg none [] [] (flags c++L) default := by + cases c <;> simp [advance,TM2.step,program,TM2.stepAux,cfg,flags, + update_zero,update_one,update_two] +lemma step_digits (c : Ordering) (A B L : List Bool) (v : Store) + (h : A≠[] ∨ B≠[]) : + advance (TM2.step program) (cfg (some c) A B L v)= + cfg (some (updateOrder c (A.headD false) (B.headD false))) A.tail B.tail L (A.head?,B.head?) := by + cases A <;> cases B <;> simp_all [advance,TM2.step,program,TM2.stepAux,cfg, + update_zero,update_one,update_two,List.headD] +lemma compareDigits_step (c : Ordering) (A B : List Bool) (h : A ≠ [] ∨ B ≠ []) : + compareDigits c A B= + compareDigits (updateOrder c (A.headD false) (B.headD false)) A.tail B.tail := by + cases A <;> cases B <;> simp_all [compareDigits,List.headD] +theorem run_comparison (A B L : List Bool) (c : Ordering) (v : Store) : + ∃ t ≤ A.length+B.length+1, + MachineCost.run (TM2.step program) t (cfg (some c) A B L v)= + cfg none [] [] (flags (compareDigits c A B)++L) default := by + have aux : ∀ n (A B : List Bool), A.length+B.length=n → + ∀ (c : Ordering) (L : List Bool) (v : Store), + ∃ t ≤ A.length+B.length+1, + MachineCost.run (TM2.step program) t (cfg (some c) A B L v)= + cfg none [] [] (flags (compareDigits c A B)++L) default := by + intro n + induction n using Nat.strong_induction_on with + | h n ih => + intro A B hn c L v + by_cases he : A=[] ∧ B=[] + · rcases he with ⟨rfl,rfl⟩ + refine ⟨1,by simp,?_⟩ + simpa only [MachineCost.run,compareDigits] using step_empty c L v + · have hne : A≠[] ∨ B≠[] := by tauto + have hlt : A.tail.length+B.tail.length cases B <;> simp_all + all_goals omega + obtain ⟨t,ht,hr⟩:=ih _ hlt A.tail B.tail rfl + (updateOrder c (A.headD false) (B.headD false)) L (A.head?,B.head?) + refine ⟨t+1,by omega,?_⟩ + rw [MachineCost.run,step_digits c A B L v hne,hr,compareDigits_step c A B hne] + exact aux _ A B rfl c L v +lemma accesses_bound (c : Ordering) : StackCost.accesses (program c) ≤ 4 := by + cases c <;> decide +lemma finite_support : TM2.Supports program Finset.univ := by + simp [TM2.Supports,program,TM2.SupportsStmt] +lemma numerical_comparison (m n : ℕ) : compareDigits .eq m.bits n.bits=compare m n := by + simp only [compares_values,value_bits] +end MatchingFPRAS.StackCompare + +end OAI diff --git a/lean/OAI/Combinatorics/MatchingCount/Arithmetic/BinaryCopy.lean b/lean/OAI/Combinatorics/MatchingCount/Arithmetic/BinaryCopy.lean new file mode 100644 index 0000000000000000000000000000000000000000..dc0d127c74e3197e198d4c900144cb9dad0667d5 --- /dev/null +++ b/lean/OAI/Combinatorics/MatchingCount/Arithmetic/BinaryCopy.lean @@ -0,0 +1,249 @@ +import Mathlib +import OAI.Combinatorics.MatchingCount.Complexity.GuardMachineBase + +namespace OAI + +namespace MatchingFPRAS.BinaryArithmetic +open Turing MachineCost + +inductive CopyPhase + | seek | append (b : Bool) | rewind | finish | restore + deriving DecidableEq, Fintype, Inhabited + +def bitSymbol (b : Bool) : Symbol := if b then 2 else 1 +def markSymbol (b : Bool) : Symbol := if b then 5 else 4 +def unmarkSymbol (a : Symbol) : Symbol := if a=4 then 1 else if a=5 then 2 else a +lemma bitSymbol_ne_zero (b : Bool) : bitSymbol b≠0 := by cases b <;> decide +lemma markSymbol_ne_zero (b : Bool) : markSymbol b≠0 := by cases b <;> decide +@[simp] lemma unmark_mark (b : Bool) : unmarkSymbol (markSymbol b)=bitSymbol b := by cases b <;> decide +@[simp] lemma unmark_bit (b : Bool) : unmarkSymbol (bitSymbol b)=bitSymbol b := by cases b <;> decide +@[simp] lemma unmark_three : unmarkSymbol 3=3 := by decide + +def copyProgram : CopyPhase → TM1.Stmt Symbol CopyPhase Unit + | .seek => .branch (fun a _=>a==4 || a==5) (.move .right (.goto (fun _ _=>.seek))) + (.branch (fun a _=>a==1) (.write (fun _ _=>4) (.goto (fun _ _=>.append false))) + (.branch (fun a _=>a==2) (.write (fun _ _=>5) (.goto (fun _ _=>.append true))) + (.move .right (.goto (fun _ _=>.finish))))) + | .append b => .branch (fun a _=>a==0) + (.write (fun _ _=>bitSymbol b) (.goto (fun _ _=>.rewind))) + (.move .right (.goto (fun _ _=>.append b))) + | .rewind => .branch (fun a _=>a==0) + (.move .right (.goto (fun _ _=>.seek))) (.move .left (.goto (fun _ _=>.rewind))) + | .finish => .branch (fun a _=>a==0) + (.write (fun _ _=>3) (.goto (fun _ _=>.restore))) + (.move .right (.goto (fun _ _=>.finish))) + | .restore => .branch (fun a _=>a==0) (.move .right .halt) + (.write (fun a _=>unmarkSymbol a) (.move .left (.goto (fun _ _=>.restore)))) +abbrev copyCfg (s : Option CopyPhase) (L R : List Symbol) : TM1.Cfg Symbol CopyPhase Unit := + ⟨s,(),Tape.mk₂ L R⟩ +lemma seek_marks (P : List Bool) (L R : List Symbol) : + MachineCost.run (TM1.step copyProgram) P.length (copyCfg (some .seek) L (P.map markSymbol++R))= + copyCfg (some .seek) ((P.map markSymbol).reverse++L) R := by + induction P generalizing L with + | nil => simp [MachineCost.run,copyCfg] + | cons b P ih => + rw [List.length_cons,MachineCost.run] + have hs : advance (TM1.step copyProgram) (copyCfg (some .seek) L ((b::P).map markSymbol++R))= + copyCfg (some .seek) (markSymbol b::L) (P.map markSymbol++R) := by + cases b <;> simp [advance,TM1.step,TM1.stepAux,copyProgram,copyCfg,markSymbol,Tape.mk₂,Tape.mk',Tape.move] + rw [hs,ih] + simp [copyCfg,List.reverse_cons,List.append_assoc] +lemma seek_bit (b : Bool) (L R : List Symbol) : + advance (TM1.step copyProgram) (copyCfg (some .seek) L (bitSymbol b::R))= + copyCfg (some (.append b)) L (markSymbol b::R) := by + cases b <;> simp [advance,TM1.step,TM1.stepAux,copyProgram,copyCfg,markSymbol,bitSymbol,Tape.mk₂,Tape.mk',Tape.write] +lemma append_run (b : Bool) (R L : List Symbol) (hR : ∀ a∈R,a≠0) : + MachineCost.run (TM1.step copyProgram) (R.length+1) (copyCfg (some (.append b)) L R)= + copyCfg (some .rewind) (R.reverse++L) [bitSymbol b] := by + induction R generalizing L with + | nil => simp [MachineCost.run,advance,TM1.step,TM1.stepAux,copyProgram,copyCfg,Tape.mk₂,Tape.mk',Tape.write] + | cons a R ih => + have ha : (a==0)=false := beq_eq_false_iff_ne.mpr (hR a (by simp)) + rw [List.length_cons,Nat.succ_add,MachineCost.run] + have hs : advance (TM1.step copyProgram) (copyCfg (some (.append b)) L (a::R))= + copyCfg (some (.append b)) (a::L) R := by + simp [advance,TM1.step,TM1.stepAux,copyProgram,copyCfg,Tape.mk₂,Tape.mk',Tape.move,ha] + rw [hs,ih _ (fun c hc=>hR c (by simp [hc]))] + simp [copyCfg,List.reverse_cons,List.append_assoc] +lemma rewind_run (L R : List Symbol) (a : Symbol) (ha : a≠0) (hL : ∀ b∈L,b≠0) : + MachineCost.run (TM1.step copyProgram) (L.length+2) (copyCfg (some .rewind) L (a::R))= + copyCfg (some .seek) [] (L.reverse++a::R) := by + have ha' : (a==0)=false := beq_eq_false_iff_ne.mpr ha + induction L generalizing a R with + | nil => + simp [MachineCost.run,advance,TM1.step,TM1.stepAux,copyProgram,copyCfg, + Tape.mk₂,Tape.mk',Tape.move,ha',ListBlank.cons_mk] + apply Quotient.sound + exact Or.inr ⟨1,rfl⟩ + | cons b L ih => + have hb : b≠0:=hL b (by simp) + rw [List.length_cons,Nat.succ_add,MachineCost.run] + have hs : advance (TM1.step copyProgram) (copyCfg (some .rewind) (b::L) (a::R))= + copyCfg (some .rewind) L (b::a::R) := by + simp [advance,TM1.step,TM1.stepAux,copyProgram,copyCfg,Tape.mk₂,Tape.mk',Tape.move,ha'] + rw [hs,ih (a::R) b hb (fun c hc=>hL c (by simp [hc])) (beq_eq_false_iff_ne.mpr hb)] + simp [copyCfg,List.reverse_cons,List.append_assoc] + +lemma finish_run (R L : List Symbol) (hR : ∀ a∈R,a≠0) : + MachineCost.run (TM1.step copyProgram) (R.length+1) (copyCfg (some .finish) L R)= + copyCfg (some .restore) (R.reverse++L) [3] := by + induction R generalizing L with + | nil => simp [MachineCost.run,advance,TM1.step,TM1.stepAux,copyProgram,copyCfg,Tape.mk₂,Tape.mk',Tape.write] + | cons a R ih => + have ha : (a==0)=false := beq_eq_false_iff_ne.mpr (hR a (by simp)) + rw [List.length_cons,Nat.succ_add,MachineCost.run] + have hs : advance (TM1.step copyProgram) (copyCfg (some .finish) L (a::R))= + copyCfg (some .finish) (a::L) R := by + simp [advance,TM1.step,TM1.stepAux,copyProgram,copyCfg,Tape.mk₂,Tape.mk',Tape.move,ha] + rw [hs,ih _ (fun c hc=>hR c (by simp [hc]))] + simp [copyCfg,List.reverse_cons,List.append_assoc] +lemma restore_run (L R : List Symbol) (a : Symbol) (ha : a≠0) (hL : ∀ b∈L,b≠0) : + MachineCost.run (TM1.step copyProgram) (L.length+2) (copyCfg (some .restore) L (a::R))= + copyCfg none [] (L.reverse.map unmarkSymbol++unmarkSymbol a::R) := by + have ha' : (a==0)=false := beq_eq_false_iff_ne.mpr ha + induction L generalizing a R with + | nil => + simp [MachineCost.run,advance,TM1.step,TM1.stepAux,copyProgram,copyCfg, + Tape.mk₂,Tape.mk',Tape.move,Tape.write,ha',ListBlank.cons_mk] + apply Quotient.sound + exact Or.inr ⟨1,rfl⟩ + | cons b L ih => + have hb : b≠0:=hL b (by simp) + rw [List.length_cons,Nat.succ_add,MachineCost.run] + have hs : advance (TM1.step copyProgram) (copyCfg (some .restore) (b::L) (a::R))= + copyCfg (some .restore) L (b::unmarkSymbol a::R) := by + simp [advance,TM1.step,TM1.stepAux,copyProgram,copyCfg,Tape.mk₂,Tape.mk',Tape.move,Tape.write,ha'] + rw [hs,ih (unmarkSymbol a::R) b hb (fun c hc=>hL c (by simp [hc])) (beq_eq_false_iff_ne.mpr hb)] + simp [copyCfg,List.reverse_cons,List.append_assoc] +def copyWord (P Q : List Bool) : List Symbol := P.map markSymbol++Q.map bitSymbol++[3]++P.map bitSymbol +lemma copy_cycle (P Q : List Bool) (b : Bool) : + MachineCost.run (TM1.step copyProgram) (4*P.length+2*Q.length+8) + (copyCfg (some .seek) [] (copyWord P (b::Q)))= + copyCfg (some .seek) [] (copyWord (P++[b]) Q) := by + let L:=(P.map markSymbol).reverse + let R:=markSymbol b::(Q.map bitSymbol++[3]++P.map bitSymbol) + have hR : ∀ a∈R,a≠0 := by + intro a ha + simp only [R,List.mem_cons,List.mem_append,List.mem_map,List.not_mem_nil,or_false] at ha + rcases ha with rfl|((⟨c,hc,rfl⟩|rfl)|⟨c,hc,rfl⟩) + · exact markSymbol_ne_zero _ + · exact bitSymbol_ne_zero _ + · decide + · exact bitSymbol_ne_zero _ + have hL : ∀ a∈L,a≠0 := by + intro a ha + obtain ⟨c,hc,rfl⟩:=List.mem_map.mp (List.mem_reverse.mp ha) + exact markSymbol_ne_zero _ + have hRL : ∀ a∈R.reverse++L,a≠0 := by + intro a ha + rcases List.mem_append.mp ha with ha|ha + · exact hR a (List.mem_reverse.mp ha) + · exact hL a ha + have hfirst : MachineCost.run (TM1.step copyProgram) (P.length+1) + (copyCfg (some .seek) [] (copyWord P (b::Q)))= + copyCfg (some (.append b)) L R := by + rw [run_add] + have he : copyWord P (b::Q)=P.map markSymbol++(bitSymbol b::(Q.map bitSymbol++[3]++P.map bitSymbol)) := by + simp [copyWord,List.append_assoc] + rw [he,seek_marks] + simpa only [MachineCost.run,List.append_nil] using seek_bit b L (Q.map bitSymbol++[3]++P.map bitSymbol) + have hrun : MachineCost.run (TM1.step copyProgram) + ((P.length+1)+(R.length+1)+((R.reverse++L).length+2)) + (copyCfg (some .seek) [] (copyWord P (b::Q)))= + copyCfg (some .seek) [] (copyWord (P++[b]) Q) := by + rw [run_add _ ((P.length+1)+(R.length+1)) ((R.reverse++L).length+2), + run_add _ (P.length+1) (R.length+1),hfirst,append_run b R L hR, + rewind_run (R.reverse++L) [] (bitSymbol b) (bitSymbol_ne_zero b) hRL] + simp [copyWord,R,L,List.reverse_append,List.append_assoc] + have hlen : (P.length+1)+(R.length+1)+((R.reverse++L).length+2)= + 4*P.length+2*Q.length+8 := by simp [R,L]; omega + rw [hlen] at hrun + exact hrun + +lemma copy_finish (P : List Bool) : + MachineCost.run (TM1.step copyProgram) (4*P.length+5) + (copyCfg (some .seek) [] (copyWord P []))= + copyCfg none [] ((P.map bitSymbol++[3])++(P.map bitSymbol++[3])) := by + let R:=P.map bitSymbol + let L:=(3:Symbol)::(P.map markSymbol).reverse + have hR : ∀ a∈R,a≠0 := by + intro a ha + obtain ⟨c,hc,rfl⟩:=List.mem_map.mp ha + exact bitSymbol_ne_zero _ + have hRL : ∀ a∈R.reverse++L,a≠0 := by + intro a ha + rcases List.mem_append.mp ha with ha|ha + · exact hR a (List.mem_reverse.mp ha) + · rcases List.mem_cons.mp ha with rfl|ha + · decide + · obtain ⟨c,hc,rfl⟩:=List.mem_map.mp (List.mem_reverse.mp ha) + exact markSymbol_ne_zero _ + have hfirst : MachineCost.run (TM1.step copyProgram) (P.length+1) + (copyCfg (some .seek) [] (copyWord P []))=copyCfg (some .finish) L R := by + rw [run_add] + have he : copyWord P []=P.map markSymbol++(3::R) := by simp [copyWord,R,List.append_assoc] + rw [he,seek_marks] + simp [MachineCost.run,advance,TM1.step,TM1.stepAux,copyProgram,copyCfg,Tape.mk₂,Tape.mk',Tape.move,L] + have hrun : MachineCost.run (TM1.step copyProgram) + ((P.length+1)+(R.length+1)+((R.reverse++L).length+2)) + (copyCfg (some .seek) [] (copyWord P []))= + copyCfg none [] ((P.map bitSymbol++[3])++(P.map bitSymbol++[3])) := by + rw [run_add _ ((P.length+1)+(R.length+1)) ((R.reverse++L).length+2), + run_add _ (P.length+1) (R.length+1),hfirst,finish_run R L hR, + restore_run (R.reverse++L) [] 3 (by decide) hRL] + simp [R,L,List.reverse_append,List.map_map,Function.comp_def,List.append_assoc] + have hlen : (P.length+1)+(R.length+1)+((R.reverse++L).length+2)=4*P.length+5 := by + simp [R,L] + omega + rw [hlen] at hrun + exact hrun +lemma copy_run (P Q : List Bool) : + ∃ k≤8*(P.length+Q.length+1)*(Q.length+1), + MachineCost.run (TM1.step copyProgram) k (copyCfg (some .seek) [] (copyWord P Q))= + copyCfg none [] (((P++Q).map bitSymbol++[3])++((P++Q).map bitSymbol++[3])) := by + induction Q generalizing P with + | nil => + refine ⟨4*P.length+5,by simp; omega,?_⟩ + simpa using copy_finish P + | cons b Q ih => + obtain ⟨k,hk,he⟩:=ih (P++[b]) + refine ⟨(4*P.length+2*Q.length+8)+k,?_,?_⟩ + · simp only [List.length_append,List.length_cons,List.length_nil] at * + nlinarith + · rw [run_add,copy_cycle,he] + simp [List.append_assoc] +lemma copy_natural (n : ℕ) : ∃ k≤8*(n.size+1)^2, + MachineCost.run (TM1.step copyProgram) k (TM1.init (encodeNat n))= + copyCfg none [] (encodeNat n++encodeNat n) := by + obtain ⟨k,hk,he⟩:=copy_run [] n.bits + refine ⟨k,?_,?_⟩ + · simpa only [List.length_nil,zero_add,Nat.size_eq_bits_len,pow_two,mul_assoc] using hk + · have hi : TM1.init (encodeNat n)=copyCfg (some .seek) [] (encodeNat n) := rfl + rw [hi] + have henc : n.bits.map bitSymbol++[3]=encodeNat n := rfl + simpa only [copyWord,List.map_nil,List.nil_append,List.append_nil,henc] using he +lemma copyProgram_cost : programCost copyProgram≤3 := by + apply Finset.sup_le + intro p _ + cases p with + | append b => cases b <;> decide + | _ => decide + +theorem copy_post (n : ℕ) (bits : Fin (24*(n.size+1)^2+2) → Bool) : + (MatchingFPRAS.run (PostCompiler.compiled copyProgram) (encodeNat n) bits).state=none ∧ + (MatchingFPRAS.run (PostCompiler.compiled copyProgram) (encodeNat n) bits).tape.right₀= + ListBlank.mk (encodeNat n++encodeNat n) := by + obtain ⟨k,hk,he⟩:=copy_natural n + apply PostCompiler.compiled_words copyProgram (encodeNat n) (encodeNat n++encodeNat n) k + · rw [he] + · rw [he] + change (Tape.mk₁ (encodeNat n++encodeNat n)).right₀=ListBlank.mk _ + exact Tape.mk'_right₀ _ _ + · have hc:=copyProgram_cost + calc + programCost copyProgram*k+2≤3*(8*(n.size+1)^2)+2 := + Nat.add_le_add_right (Nat.mul_le_mul hc hk) 2 + _=24*(n.size+1)^2+2 := by ring +end MatchingFPRAS.BinaryArithmetic + +end OAI diff --git a/lean/OAI/Combinatorics/MatchingCount/Arithmetic/BinaryDivision.lean b/lean/OAI/Combinatorics/MatchingCount/Arithmetic/BinaryDivision.lean new file mode 100644 index 0000000000000000000000000000000000000000..cae2925255aaf5d83c339461126753a9d298bf08 --- /dev/null +++ b/lean/OAI/Combinatorics/MatchingCount/Arithmetic/BinaryDivision.lean @@ -0,0 +1,96 @@ +import Mathlib +import OAI.Combinatorics.MatchingCount.Arithmetic.BinaryNormalize + +namespace OAI + +namespace MatchingFPRAS.BinaryDivision +open StackAddition (value value_bits) + +def low (b : Bool) (B R : List Bool) : Bool := decide (value (b::R) (Q,R) + | b::A,B,Q,R => run A B (nextQ b B Q R) (nextR b B R) + +lemma value_bits_length (A : List Bool) : (value A).bits.length≤A.length := by + simpa only [BinaryNormalize.normalize_bits] using BinaryNormalize.normalize_length A +lemma bits_length_mono {m n : ℕ} (h : m≤n) : m.bits.length≤n.bits.length := by + simpa only [Nat.size_eq_bits_len] using Nat.size_le_size h +lemma nextR_length (b : Bool) (B R : List Bool) : (nextR b B R).length≤R.length+1 := by + unfold nextR + split_ifs + · simp + · exact (bits_length_mono (Nat.sub_le _ _)).trans (value_bits_length (b::R)) +lemma nextQ_length (b : Bool) (B Q R : List Bool) : (nextQ b B Q R).length=Q.length+1 := rfl + +lemma step_remainder (b : Bool) (B R : List Bool) (h : value R decide + unfold nextR low + split_ifs with hl + · simpa using hl + · rw [value_bits] + simp only [value] at * + omega +lemma step_mass (b : Bool) (B Q R : List Bool) : + value (nextQ b B Q R)*value B+value (nextR b B R)= + 2*(value Q*value B+value R)+b.toNat := by + by_cases hh : value (b::R) simp [value] + | cons a A ih => simp only [List.cons_append,value,ih,List.length_cons,pow_succ]; ring +lemma value_reverse_cons (b : Bool) (A : List Bool) : + value (b::A).reverse=value A.reverse+2^A.length*b.toNat := by + rw [List.reverse_cons,value_append] + simp [value,List.length_reverse] + +lemma run_mass (A B Q R : List Bool) : + value (run A B Q R).1*value B+value (run A B Q R).2= + (value Q*value B+value R)*2^A.length+value A.reverse := by + induction A generalizing Q R with + | nil => simp [run,value] + | cons b A ih => + rw [run,ih,step_mass,value_reverse_cons,List.length_cons,pow_succ] + ring +lemma run_remainder (A B Q R : List Bool) (h : value R exact h + | cons b A ih => exact ih _ _ (step_remainder b B R h) +lemma run_lengths (A B Q R : List Bool) : + (run A B Q R).1.length=Q.length+A.length ∧ + (run A B Q R).2.length≤R.length+A.length := by + induction A generalizing Q R with + | nil => simp [run] + | cons b A ih => + obtain ⟨hQ,hR⟩:=ih (nextQ b B Q R) (nextR b B R) + have hr:=nextR_length b B R + simp only [run,List.length_cons] + rw [hQ,nextQ_length] + exact ⟨by omega,by omega⟩ + +theorem correct (m n : ℕ) (hn : 0 [true] + | false::bs => true::bs + | true::bs => false::incrementBits bs +lemma incrementBits_bits (n : ℕ) : incrementBits n.bits=(n+1).bits := by + induction n using Nat.binaryRec' with + | zero => simp [incrementBits] + | bit b n h ih => + cases b with + | false => + have hn : n≠0 := by intro hh; have := h hh; contradiction + simp only [Nat.bit, Bool.cond_false, Nat.bit0_bits _ hn, incrementBits] + exact (Nat.bit1_bits n).symm + | true => + simp only [Nat.bits_append_bit _ _ h,incrementBits,ih] + have hn : n+1≠0 := by omega + have he : Nat.bit true n+1=2*(n+1) := by simp [Nat.bit]; omega + rw [he,Nat.bit0_bits _ hn] + +def numeral (bs : List Bool) : List Symbol := (bs.map fun b=>if b then 2 else 1)++[3] + +def incrementProgram : Bool → TM1.Stmt Symbol Bool Unit + | false => .branch (fun a _=>a==1) + (.write (fun _ _=>2) (.goto (fun _ _=>true))) + (.branch (fun a _=>a==2) + (.write (fun _ _=>1) (.move .right (.goto (fun _ _=>false)))) + (.write (fun _ _=>2) (.move .right (.write (fun _ _=>3) (.move .left (.goto (fun _ _=>true))))))) + | true => .branch (fun a _=>a==0) (.move .right .halt) (.move .left (.goto (fun _ _=>true))) +abbrev cfg (s : Option Bool) (L R : List Symbol) : TM1.Cfg Symbol Bool Unit := + ⟨s,(),Tape.mk₂ L R⟩ +lemma back_step (L R : List Symbol) (a : Symbol) (ha : a≠0) : + advance (TM1.step incrementProgram) (cfg (some true) L (a::R))= + ⟨some true,(),(Tape.mk₂ L (a::R)).move .left⟩ := by + have ha' : (a==0)=false := by simpa using ha + simp [advance,TM1.step,incrementProgram,TM1.stepAux,cfg,Tape.mk₂,Tape.mk',ha'] +lemma back_run (L R : List Symbol) (a : Symbol) (ha : a≠0) + (hL : ∀ b∈L,b≠0) : + MachineCost.run (TM1.step incrementProgram) (L.length+2) (cfg (some true) L (a::R))= + cfg none [] (L.reverse++a::R) := by + induction L generalizing a R with + | nil => + rw [show ([]:List Symbol).length+2=2 from rfl] + rw [show 2=1+1 from rfl,MachineCost.run,back_step _ _ _ ha] + simp [MachineCost.run,advance,TM1.step,incrementProgram,TM1.stepAux,cfg, + Tape.mk₂,Tape.mk',Tape.move,ListBlank.cons_mk] + apply Quotient.sound + exact Or.inr ⟨1,rfl⟩ + | cons b L ih => + have hb : b≠0:=hL b (by simp) + have hL' : ∀ c∈L,c≠0:=fun c hc=>hL c (by simp [hc]) + rw [List.length_cons,Nat.succ_add,MachineCost.run,back_step _ _ _ ha] + simpa only [cfg,Tape.mk₂,Tape.move_left_mk',ListBlank.head_mk,ListBlank.tail_mk, + List.headI_cons,List.tail_cons,ListBlank.cons_mk,List.reverse_cons,List.append_assoc, + List.singleton_append] using ih (a::R) b hb hL' +lemma carry_false (L : List Symbol) (bs : List Bool) : + advance (TM1.step incrementProgram) (cfg (some false) L (numeral (false::bs)))= + cfg (some true) L (2::numeral bs) := by + simp [advance,TM1.step,incrementProgram,TM1.stepAux,cfg,numeral,Tape.mk₂,Tape.mk',Tape.write] +lemma carry_true (L : List Symbol) (bs : List Bool) : + advance (TM1.step incrementProgram) (cfg (some false) L (numeral (true::bs)))= + cfg (some false) (1::L) (numeral bs) := by + simp [advance,TM1.step,incrementProgram,TM1.stepAux,cfg,numeral,Tape.mk₂,Tape.mk',Tape.write,Tape.move] +lemma carry_nil (L : List Symbol) : + advance (TM1.step incrementProgram) (cfg (some false) L (numeral []))= + cfg (some true) L [2,3] := by + simp [advance,TM1.step,incrementProgram,TM1.stepAux,cfg,numeral,Tape.mk₂,Tape.mk',Tape.write,Tape.move] +lemma increment_run (bs : List Bool) (L : List Symbol) (hL : ∀ b∈L,b≠0) : + ∃ k≤2*bs.length+L.length+3, + MachineCost.run (TM1.step incrementProgram) k (cfg (some false) L (numeral bs))= + cfg none [] (L.reverse++numeral (incrementBits bs)) := by + induction bs generalizing L with + | nil => + refine ⟨(L.length+2)+1,by simp,?_⟩ + rw [MachineCost.run,carry_nil] + exact back_run L [3] 2 (by decide) hL + | cons b bs ih => + cases b with + | false => + refine ⟨(L.length+2)+1,by simp,?_⟩ + rw [MachineCost.run,carry_false] + exact back_run L (numeral bs) 2 (by decide) hL + | true => + have hL' : ∀ b∈(1:Symbol)::L,b≠0 := by + intro b hb + rcases List.mem_cons.mp hb with rfl|hb + · decide + · exact hL b hb + obtain ⟨k,hk,he⟩:=ih (1::L) hL' + refine ⟨k+1,by simp only [List.length_cons] at *; omega,?_⟩ + rw [MachineCost.run,carry_true,he] + simp [cfg,numeral,incrementBits,List.reverse_cons,List.append_assoc] +theorem increment_natural (n : ℕ) : ∃ k≤2*n.size+3, + MachineCost.run (TM1.step incrementProgram) k (TM1.init (encodeNat n))= + cfg none [] (encodeNat (n+1)) := by + obtain ⟨k,hk,he⟩:=increment_run n.bits [] (by simp) + refine ⟨k,by simpa only [List.length_nil,Nat.add_zero,Nat.size_eq_bits_len] using hk,?_⟩ + have hi : TM1.init (encodeNat n)=cfg (some false) [] (encodeNat n) := rfl + rw [hi] + simpa only [List.reverse_nil,List.nil_append,incrementBits_bits,numeral,encodeNat] using he +lemma incrementProgram_cost : programCost incrementProgram≤5 := by + apply Finset.sup_le + intro b _ + cases b <;> decide + +theorem increment_post (n : ℕ) (bits : Fin (10*n.size+17) → Bool) : + (MatchingFPRAS.run (PostCompiler.compiled incrementProgram) (encodeNat n) bits).state=none ∧ + (MatchingFPRAS.run (PostCompiler.compiled incrementProgram) (encodeNat n) bits).tape.right₀= + ListBlank.mk (encodeNat (n+1)) := by + obtain ⟨k,hk,he⟩:=increment_natural n + apply PostCompiler.compiled_words incrementProgram (encodeNat n) (encodeNat (n+1)) k + · rw [he] + · rw [he] + change (Tape.mk₁ (encodeNat (n+1))).right₀=ListBlank.mk _ + exact Tape.mk'_right₀ _ _ + · have hc:=incrementProgram_cost + calc + programCost incrementProgram*k+2 ≤ 5*(2*n.size+3)+2 := + Nat.add_le_add_right (Nat.mul_le_mul hc hk) 2 + _ = 10*n.size+17 := by ring +end MatchingFPRAS.BinaryArithmetic + +end OAI diff --git a/lean/OAI/Combinatorics/MatchingCount/Arithmetic/BinaryNormalize.lean b/lean/OAI/Combinatorics/MatchingCount/Arithmetic/BinaryNormalize.lean new file mode 100644 index 0000000000000000000000000000000000000000..b0289df183f4c76157103068a6b69f3feeac529d --- /dev/null +++ b/lean/OAI/Combinatorics/MatchingCount/Arithmetic/BinaryNormalize.lean @@ -0,0 +1,93 @@ +import Mathlib +import OAI.Combinatorics.MatchingCount.Machines.TreeMachine + +namespace OAI + +namespace MatchingFPRAS.BinaryNormalize +open Turing MachineCost RegisterProc TreeTransfer +open StackAddition (value value_bits) + +def normalize (A : List Bool) : List Bool := (A.reverse.dropWhile Bool.not).reverse +lemma normalize_nil : normalize []=[] := rfl +lemma normalize_cons (b : Bool) (A : List Bool) : + normalize (b::A)=if normalize A=[] ∧ b=false then [] else b::normalize A := by + simp only [normalize,List.reverse_cons,List.dropWhile_append] + have hh (B : List Bool) : + (if B.isEmpty then [b].dropWhile Bool.not else B++[b]).reverse= + if B.reverse=[] ∧ b=false then [] else b::B.reverse := by + cases B <;> cases b <;> simp + exact hh _ +lemma normalize_bits (A : List Bool) : normalize A=(value A).bits := by + induction A with + | nil => rfl + | cons b A ih => + rw [normalize_cons,ih] + cases b with + | false => + by_cases hz : value A=0 + · simp [hz,value] + · have hne : (value A).bits≠[] := by + intro emptyBits + exact hz ((value_bits (value A)).symm.trans (congrArg value emptyBits)) + simp only [value,Bool.toNat_false,Nat.zero_add, Nat.bit0_bits _ hz,hne,false_and,↓reduceIte] + | true => + simp only [Bool.true_eq_false,and_false,↓reduceIte,value,Bool.toNat_true] + rw [Nat.add_comm 1 (2*value A),Nat.bit1_bits] +lemma normalize_length (A : List Bool) : (normalize A).length≤A.length := by + simpa only [normalize,List.length_reverse] using List.length_dropWhile_le Bool.not A.reverse + +def stripProgram : Unit→TM2.Stmt (fun _ : Fin 3=>Bool) Unit (Option Bool) := fun _=> + .peek 0 (fun _ x=>x) (.branch (fun x=>x.isNone || x.getD false) + (.load (fun _=>none) .halt) + (.pop 0 (fun v _=>v) (.goto (fun _=>())))) +lemma strip_nil (B C : List Bool) (v : Option Bool) : + advance (TM2.step stripProgram) (cfg (some ()) [] B C v)=cfg none [] B C none := by + simp [advance,TM2.step,stripProgram,TM2.stepAux,cfg] +lemma strip_true (A B C : List Bool) (v : Option Bool) : + advance (TM2.step stripProgram) (cfg (some ()) (true::A) B C v)=cfg none (true::A) B C none := by + simp [advance,TM2.step,stripProgram,TM2.stepAux,cfg] +lemma strip_false (A B C : List Bool) (v : Option Bool) : + advance (TM2.step stripProgram) (cfg (some ()) (false::A) B C v)=cfg (some ()) A B C (some false) := by + simp [advance,TM2.step,stripProgram,TM2.stepAux,cfg,update_zero] +lemma run_strip (A B C : List Bool) (v : Option Bool) : + ∃ n≤A.length+1,MachineCost.run (TM2.step stripProgram) n (cfg (some ()) A B C v)= + cfg none (A.dropWhile Bool.not) B C none := by + induction A generalizing v with + | nil => exact ⟨1,le_rfl,strip_nil B C v⟩ + | cons a A ih => cases a with + | false => + obtain ⟨n,hn,he⟩:=ih (some false) + refine ⟨n+1,by simp only [List.length_cons]; omega,?_⟩ + rw [MachineCost.run,strip_false,he] + rfl + | true => exact ⟨1,by simp,strip_true A B C v⟩ +def stripRaw : Proc (Fin 3) := ⟨Unit,stripProgram⟩ +lemma stripRaw_exec (A B C : List Bool) : + Exec stripRaw ![A,B,C] ![A.dropWhile Bool.not,B,C] (A.length+1) := run_strip A B C none + +def swap01 : Fin 3 ↪ Fin 3 := triple 1 0 2 (by decide) (by decide) (by decide) +lemma reindex_swap (P : Proc (Fin 3)) (A B C A' B' C' : List Bool) (n : ℕ) + (h : Exec P ![A,B,C] ![A',B',C'] n) : + Exec (reindex P swap01) ![B,A,C] ![B',A',C'] n := by + have hh:=exec_on P (1 : Fin 3) 0 2 (by decide) (by decide) (by decide) ![B,A,C] A' B' C' n h + have hout : put3 ![B,A,C] (1 : Fin 3) 0 2 A' B' C'=![B',A',C'] := by + funext i; fin_cases i <;> simp [put3] + rw [hout] at hh + exact hh + +def program : Proc (Fin 3) := seq reverseRaw (seq (reindex stripRaw swap01) (reindex reverseRaw swap01)) +theorem exec (A C : List Bool) : Exec program ![A,[],C] ![normalize A,[],C] (3*A.length+3) := by + have h₁:=reverseRaw_exec A [] C + simp only [List.append_nil] at h₁ + have h₂:=reindex_swap stripRaw A.reverse [] C _ [] C _ (stripRaw_exec A.reverse [] C) + have h₃:=reindex_swap reverseRaw (A.reverse.dropWhile Bool.not) [] C [] _ C _ + (reverseRaw_exec (A.reverse.dropWhile Bool.not) [] C) + simp only [List.append_nil] at h₃ + have hh:=h₁.seq (h₂.seq h₃) + apply hh.mono + have hl:=List.length_dropWhile_le Bool.not A.reverse + simp only [List.length_reverse] at hl ⊢ + omega +end MatchingFPRAS.BinaryNormalize + +end OAI diff --git a/lean/OAI/Combinatorics/MatchingCount/Arithmetic/BinarySubtract.lean b/lean/OAI/Combinatorics/MatchingCount/Arithmetic/BinarySubtract.lean new file mode 100644 index 0000000000000000000000000000000000000000..1490e47088b21389cf179da8411ea04f32483f00 --- /dev/null +++ b/lean/OAI/Combinatorics/MatchingCount/Arithmetic/BinarySubtract.lean @@ -0,0 +1,129 @@ +import Mathlib +import OAI.Combinatorics.MatchingCount.Arithmetic.BinaryAddition + +namespace OAI + +namespace MatchingFPRAS.StackSubtract +open Turing MachineCost StackAddition + +def borrow (c a b : Bool) : Bool := decide (a.toNat < b.toNat+c.toNat) +lemma digit_balance (c a b : Bool) : + a.toNat+2*(borrow c a b).toNat=(digit c a b).toNat+b.toNat+c.toNat := by + cases c <;> cases a <;> cases b <;> decide + +def subDigits (c : Bool) (A B : List Bool) : Bool × List Bool := + match A,B with + | [],[] => (c,[]) + | a::A,[] => let r:=subDigits (borrow c a false) A []; (r.1,digit c a false::r.2) + | [],b::B => let r:=subDigits (borrow c false b) [] B; (r.1,digit c false b::r.2) + | a::A,b::B => let r:=subDigits (borrow c a b) A B; (r.1,digit c a b::r.2) +termination_by A.length+B.length + +lemma subDigits_length (A B : List Bool) (c : Bool) : + (subDigits c A B).2.length=max A.length B.length := by + induction A generalizing B c with + | nil => + induction B generalizing c with + | nil => simp [subDigits] + | cons b B ih => simp [subDigits,ih] + | cons a A ih => + cases B with + | nil => simp [subDigits,ih] + | cons b B => simp [subDigits,ih,max_add_add_right] + +lemma subDigits_balance (A B : List Bool) (c : Bool) : + value A+2^(max A.length B.length)*(subDigits c A B).1.toNat= + value (subDigits c A B).2+value B+c.toNat := by + induction A generalizing B c with + | nil => + induction B generalizing c with + | nil => simp [subDigits,value] + | cons b B ih => + have hh:=ih (borrow c false b) + have hd:=digit_balance c false b + simp only [List.length_nil,Nat.zero_max,value] at hh + simp only [subDigits,List.length_nil,List.length_cons,Nat.zero_max,value,pow_succ, + Bool.toNat_false] at hd ⊢ + nlinarith + | cons a A ih => + cases B with + | nil => + have hh:=ih [] (borrow c a false) + have hd:=digit_balance c a false + simp only [List.length_nil,Nat.max_zero,value] at hh + simp only [subDigits,List.length_nil,List.length_cons,Nat.max_zero,value,pow_succ, + Bool.toNat_false] at hd ⊢ + nlinarith + | cons b B => + have hh:=ih B (borrow c a b) + have hd:=digit_balance c a b + simp only [subDigits,List.length_cons,max_add_add_right,value,pow_succ] + nlinarith + +lemma value_lt (A : List Bool) : value A<2^A.length := by + induction A with + | nil => simp [value] + | cons a A ih => + have ha : a.toNat≤1 := by cases a <;> decide + simp only [value,List.length_cons,pow_succ] + omega + +lemma subDigits_correct (A B : List Bool) (c : Bool) (h : value B+c.toNat≤value A) : + (subDigits c A B).1=false ∧ value (subDigits c A B).2=value A-value B-c.toNat := by + have hh:=subDigits_balance A B c + have hl:=value_lt (subDigits c A B).2 + rw [subDigits_length] at hl + cases hc : (subDigits c A B).1 with + | false => simp only [hc,Bool.toNat_false,Nat.mul_zero,Nat.add_zero] at hh; exact ⟨rfl,by omega⟩ + | true => simp only [hc,Bool.toNat_true,Nat.mul_one] at hh; omega + +def program (c : Bool) : TM2.Stmt (fun _ : Fin 3=>Bool) Bool Store := + .pop 0 (fun v a=>(a,v.2)) (.pop 1 (fun v b=>(v.1,b)) + (.branch (fun v=>v.1.isNone && v.2.isNone) + (.load (fun _=>default) .halt) + (.push 2 (fun v=>digit c (v.1.getD false) (v.2.getD false)) + (.goto (fun v=>borrow c (v.1.getD false) (v.2.getD false)))))) +def cfg (c : Option Bool) (A B L : List Bool) (v : Store) : + TM2.Cfg (fun _ : Fin 3=>Bool) Bool Store := ⟨c,v,stackData A B L⟩ +lemma step_empty (c : Bool) (L : List Bool) (v : Store) : + advance (TM2.step program) (cfg (some c) [] [] L v)=cfg none [] [] L default := by + simp [advance,TM2.step,program,TM2.stepAux,cfg,update_zero,update_one] +lemma step_digits (c : Bool) (A B L : List Bool) (v : Store) (h : A ≠ [] ∨ B ≠ []) : + advance (TM2.step program) (cfg (some c) A B L v)= + cfg (some (borrow c (A.headD false) (B.headD false))) A.tail B.tail + (digit c (A.headD false) (B.headD false)::L) (A.head?,B.head?) := by + cases A <;> cases B <;> simp_all [advance,TM2.step,program,TM2.stepAux,cfg, + update_zero,update_one,update_two] +lemma subDigits_step (c : Bool) (A B : List Bool) (h : A ≠ [] ∨ B ≠ []) : + (subDigits c A B).2 = digit c (A.headD false) (B.headD false):: + (subDigits (borrow c (A.headD false) (B.headD false)) A.tail B.tail).2 := by + cases A <;> cases B <;> simp_all [subDigits] + +theorem run_subtraction (A B L : List Bool) (c : Bool) (v : Store) : + ∃ t≤A.length+B.length+1,MachineCost.run (TM2.step program) t (cfg (some c) A B L v)= + cfg none [] [] ((subDigits c A B).2.reverse++L) default := by + have aux : ∀ n (A B : List Bool),A.length+B.length=n → ∀ (c : Bool) (L : List Bool) (v : Store), + ∃ t≤A.length+B.length+1,MachineCost.run (TM2.step program) t (cfg (some c) A B L v)= + cfg none [] [] ((subDigits c A B).2.reverse++L) default := by + intro n + induction n using Nat.strong_induction_on with + | h n ih => + intro A B hn c L v + by_cases he : A=[] ∧ B=[] + · rcases he with ⟨rfl,rfl⟩ + refine ⟨1,by simp,?_⟩ + simpa only [MachineCost.run,subDigits,List.reverse_nil,List.nil_append] using step_empty c L v + · have hne : A≠[] ∨ B≠[] := by tauto + have hlt : A.tail.length+B.tail.length cases B <;> simp_all + all_goals omega + obtain ⟨t,ht,hr⟩:=ih _ hlt A.tail B.tail rfl + (borrow c (A.headD false) (B.headD false)) + (digit c (A.headD false) (B.headD false)::L) (A.head?,B.head?) + refine ⟨t+1,by omega,?_⟩ + rw [MachineCost.run,step_digits c A B L v hne,hr,subDigits_step c A B hne] + simp only [List.reverse_cons,List.append_assoc,List.singleton_append] + exact aux _ A B rfl c L v +end MatchingFPRAS.StackSubtract + +end OAI diff --git a/lean/OAI/Combinatorics/MatchingCount/Arithmetic/OnlineFractionParam.lean b/lean/OAI/Combinatorics/MatchingCount/Arithmetic/OnlineFractionParam.lean new file mode 100644 index 0000000000000000000000000000000000000000..1f8a59dd1f79acdbb3c0df542331d6760a33fa23 --- /dev/null +++ b/lean/OAI/Combinatorics/MatchingCount/Arithmetic/OnlineFractionParam.lean @@ -0,0 +1,95 @@ +import Mathlib +import OAI.Combinatorics.MatchingCount.Machines.TreeLabelTable +import OAI.Combinatorics.MatchingCount.Algorithm.OnlineScheduleNat + +namespace OAI + +namespace MatchingFPRAS.TreeFraction +open TreeTyped Polynomial + +def natCeil (x : Fraction) : ℕ := (x.1+x.2-1)/x.2 +def natCeilRealizer : Realizer natCeil := + (composition (pair (composition (composition (pair first second) TreeTyped.add) predecessor) second) quotient).congr (fun _=>rfl) +lemma polynomial_natCeil : PolynomialTime natCeilRealizer := by + unfold natCeilRealizer; apply polynomial_congr + have := polynomial_predecessor + have := polynomial_quotient + tree_cost +lemma natCeil_eq (x : Fraction) : natCeil x=⌈val x⌉₊ := by + by_cases hd : x.2=0 + · simp [natCeil,val,hd] + have hd' : (0:ℚ)rfl) +lemma polynomial_rootCandidate : PolynomialTime rootCandidateRealizer := by + unfold rootCandidateRealizer Realizer.fst; apply polynomial_congr + have := polynomial_fixedPower 2 + have := polynomial_successor + tree_cost + +def findRoot (x : RootInput) : ℕ := + listMin ((List.range (x.2.length+1)).filter (fun i=>rootCandidate (x,i)),x.2.length) +def findRootRealizer : Realizer findRoot := by + let B : Realizer (fun x : RootInput=>x.2.length) := composition second listLength + let R := composition (composition B successor) range + let F := composition (pair identity R) (filterWith rootCandidateRealizer) + exact (composition (pair F B) listMinRealizer).congr (fun _=>rfl) +lemma polynomial_findRoot : PolynomialTime findRootRealizer := by + unfold findRootRealizer + dsimp only + apply polynomial_congr + apply polynomial_composition _ polynomial_listMin + apply polynomial_pair _ (polynomial_composition polynomial_second polynomial_listLength) + apply polynomial_composition _ (polynomial_filterWithList polynomial_rootCandidate) + apply polynomial_pair polynomial_identity + apply polynomial_boundedRange + (polynomial_composition (polynomial_composition polynomial_second polynomial_listLength) polynomial_successor) + (X+1) + intro x + have h:=list_length_le_weight x.2 + change x.2.length+1≤(X+1).eval (weight x) + simp only [Polynomial.eval_add,Polynomial.eval_X,Polynomial.eval_one] + rw [weight_prod] + omega +lemma findRoot_eq (n : ℕ) (fuel : List Bool) (hf : n.sqrt≤fuel.length) : + findRoot (n,fuel)=n.sqrt := by + apply Nat.le_antisymm + · apply listMin_le + simp only [List.mem_filter,List.mem_range,rootCandidate,decide_eq_true_eq] + exact ⟨by omega,by simpa [pow_two,Nat.succ_eq_add_one] using Nat.lt_succ_sqrt n⟩ + · apply le_listMin hf + intro i hi + simp only [List.mem_filter,List.mem_range,rootCandidate,decide_eq_true_eq,pow_two] at hi + have h:=Nat.sqrt_lt.mpr hi.2 + omega +end MatchingFPRAS.OnlineSchedule + +end OAI diff --git a/lean/OAI/Combinatorics/MatchingCount/Arithmetic/PostAddition.lean b/lean/OAI/Combinatorics/MatchingCount/Arithmetic/PostAddition.lean new file mode 100644 index 0000000000000000000000000000000000000000..d3e67ac682be7c32b495e1aebbe66ee55e32b29e --- /dev/null +++ b/lean/OAI/Combinatorics/MatchingCount/Arithmetic/PostAddition.lean @@ -0,0 +1,77 @@ +import Mathlib +import OAI.Combinatorics.MatchingCount.Arithmetic.BinaryAddition +import OAI.Combinatorics.MatchingCount.Tapes.StackWords +import OAI.Combinatorics.MatchingCount.Tapes.FixedEncoding + +namespace OAI + +namespace MatchingFPRAS.PostAddition +open Turing StackAddition + +local instance initialCarry : Inhabited Bool := ⟨false⟩ +abbrev Alphabet := TM2to1.Γ' (Fin 3) (fun _=>Bool) +noncomputable def machine : RandomMachine := + StackWords.compiled (FixedEncoding.enc Alphabet) (FixedEncoding.dec Alphabet) + program Finset.univ finite_support +noncomputable def overhead : ℕ := + StackWords.cost (FixedEncoding.enc Alphabet) (FixedEncoding.dec Alphabet) + program Finset.univ +noncomputable def input (A B : List Bool) : List Symbol := + StackWords.encoded (FixedEncoding.enc Alphabet) (stackData A B []) (A.length+B.length) +noncomputable def output (A B : List Bool) : List Symbol := + StackWords.encoded (FixedEncoding.enc Alphabet) + (stackData [] [] (addDigits false A B).reverse) (A.length+B.length+1) +noncomputable def steps (A B : List Bool) : ℕ := + overhead*((A.length+B.length+1)*(1+6*(A.length+B.length+3*(A.length+B.length+1)+1)))+2 + +theorem computes (A B : List Bool) (t : ℕ) (ht : steps A B≤t) (bits : Fin t → Bool) : + (run machine (input A B) bits).state=none ∧ + (run machine (input A B) bits).tape.right₀=ListBlank.mk (output A B) := by + obtain ⟨n,hn,hr⟩:=run_addition A B [] false default + have h₀ : StackCost.StackBound (stackData A B []) (A.length+B.length) := by + intro i + fin_cases i <;> simp [stackData] + have he : MachineCost.run (TM2.step program) n + ⟨some (default : Bool),(default : Store),stackData A B []⟩= + cfg none [] [] (addDigits false A B).reverse default := by + change MachineCost.run (TM2.step program) n (cfg (some false) A B [] default)=_ + simpa only [List.append_nil] using hr + have hh : (MachineCost.run (TM2.step program) n + ⟨some (default : Bool),(default : Store),stackData A B []⟩).l=none := by rw [he]; rfl + have ho : StackCost.StackBound (MachineCost.run (TM2.step program) n + ⟨some (default : Bool),(default : Store),stackData A B []⟩).stk (A.length+B.length+1) := by + rw [he] + intro i + have hl:=addDigits_length A B false + fin_cases i <;> simp [cfg,stackData] + omega + have htime : StackWords.cost (FixedEncoding.enc Alphabet) (FixedEncoding.dec Alphabet) + program Finset.univ*(n*(1+2*3*(A.length+B.length+n*3+1)))+2≤t := by + apply le_trans _ ht + unfold steps overhead + apply Nat.add_le_add_right + apply Nat.mul_le_mul_left + apply Nat.mul_le_mul hn + omega + have hc:=StackWords.compiled_execution (FixedEncoding.enc Alphabet) + (FixedEncoding.dec Alphabet) (FixedEncoding.blank Alphabet) (FixedEncoding.left_inverse Alphabet) + program Finset.univ finite_support 3 accesses_bound + (stackData A B []) (A.length+B.length) h₀ n (A.length+B.length+1) hh ho t htime bits + change (run machine (input A B) bits).state=none ∧ + (run machine (input A B) bits).tape.right₀=ListBlank.mk + (StackWords.encoded (FixedEncoding.enc Alphabet) + (MachineCost.run (TM2.step program) n + ⟨some (default : Bool),(default : Store),stackData A B []⟩).stk + (A.length+B.length+1)) at hc + rw [he] at hc + exact hc +lemma result_value (m n : ℕ) : + value ((addDigits false m.bits n.bits).reverse.reverse)=m+n := by + simpa only [List.reverse_reverse] using addition_numerals m n +lemma time_quadratic (A B : List Bool) : + steps A B=overhead*(24*(A.length+B.length)^2+49*(A.length+B.length)+25)+2 := by + unfold steps + ring +end MatchingFPRAS.PostAddition + +end OAI diff --git a/lean/OAI/Combinatorics/MatchingCount/Arithmetic/PostComparison.lean b/lean/OAI/Combinatorics/MatchingCount/Arithmetic/PostComparison.lean new file mode 100644 index 0000000000000000000000000000000000000000..c7b46a3cdb1a5409f45ea8fd217347c67c4ba5c2 --- /dev/null +++ b/lean/OAI/Combinatorics/MatchingCount/Arithmetic/PostComparison.lean @@ -0,0 +1,81 @@ +import Mathlib +import OAI.Combinatorics.MatchingCount.Tapes.StackWords +import OAI.Combinatorics.MatchingCount.Tapes.FixedEncoding +import OAI.Combinatorics.MatchingCount.Arithmetic.BinaryCompare + +namespace OAI + +namespace MatchingFPRAS.PostComparison +open Turing StackCompare + +local instance initialOrder : Inhabited Ordering := ⟨.eq⟩ +abbrev Alphabet := TM2to1.Γ' (Fin 3) (fun _=>Bool) +lemma support : TM2.Supports program Finset.univ := by + simp [TM2.Supports,program,TM2.SupportsStmt] +noncomputable def machine : RandomMachine := + StackWords.compiled (FixedEncoding.enc Alphabet) (FixedEncoding.dec Alphabet) + program Finset.univ support +noncomputable def overhead : ℕ := + StackWords.cost (FixedEncoding.enc Alphabet) (FixedEncoding.dec Alphabet) + program Finset.univ +noncomputable def input (A B : List Bool) : List Symbol := + StackWords.encoded (FixedEncoding.enc Alphabet) (StackAddition.stackData A B []) (A.length+B.length) +noncomputable def output (c : Ordering) : List Symbol := + StackWords.encoded (FixedEncoding.enc Alphabet) + (StackAddition.stackData [] [] (flags c)) 2 +noncomputable def steps (A B : List Bool) : ℕ := + overhead*((A.length+B.length+1)*(1+8*(A.length+B.length+4*(A.length+B.length+1)+1)))+2 + +theorem computes (A B : List Bool) (t : ℕ) (ht : steps A B≤t) (bits : Fin t → Bool) : + (run machine (input A B) bits).state=none ∧ + (run machine (input A B) bits).tape.right₀= + ListBlank.mk (output (compare (StackAddition.value A) (StackAddition.value B))) := by + obtain ⟨n,hn,hr⟩:=run_comparison A B [] .eq default + have h₀ : StackCost.StackBound (StackAddition.stackData A B []) (A.length+B.length) := by + intro i + fin_cases i <;> simp [StackAddition.stackData] + have he : MachineCost.run (TM2.step program) n + ⟨some (default : Ordering),(default : StackAddition.Store),StackAddition.stackData A B []⟩= + cfg none [] [] (flags (compareDigits .eq A B)) default := by + change MachineCost.run (TM2.step program) n (cfg (some .eq) A B [] default)=_ + simpa only [List.append_nil] using hr + have hh : (MachineCost.run (TM2.step program) n + ⟨some (default : Ordering),(default : StackAddition.Store),StackAddition.stackData A B []⟩).l=none := by rw [he]; rfl + have ho : StackCost.StackBound (MachineCost.run (TM2.step program) n + ⟨some (default : Ordering),(default : StackAddition.Store),StackAddition.stackData A B []⟩).stk 2 := by + rw [he] + change StackCost.StackBound (StackAddition.stackData [] [] (flags (compareDigits .eq A B))) 2 + intro i + fin_cases i <;> simp [StackAddition.stackData,flags] + have htime : StackWords.cost (FixedEncoding.enc Alphabet) (FixedEncoding.dec Alphabet) + program Finset.univ*(n*(1+2*4*(A.length+B.length+n*4+1)))+2≤t := by + apply le_trans _ ht + unfold steps overhead + apply Nat.add_le_add_right + apply Nat.mul_le_mul_left + apply Nat.mul_le_mul hn + omega + have hc:=StackWords.compiled_execution (FixedEncoding.enc Alphabet) + (FixedEncoding.dec Alphabet) (FixedEncoding.blank Alphabet) (FixedEncoding.left_inverse Alphabet) + program Finset.univ support 4 accesses_bound + (StackAddition.stackData A B []) (A.length+B.length) h₀ n 2 hh ho t htime bits + change (run machine (input A B) bits).state=none ∧ + (run machine (input A B) bits).tape.right₀=ListBlank.mk + (StackWords.encoded (FixedEncoding.enc Alphabet) + (MachineCost.run (TM2.step program) n + ⟨some (default : Ordering),(default : StackAddition.Store),StackAddition.stackData A B []⟩).stk + 2) at hc + rw [he,compares_values] at hc + exact hc +lemma time_quadratic (A B : List Bool) : + steps A B=overhead*(40*(A.length+B.length)^2+81*(A.length+B.length)+41)+2 := by + unfold steps + congr 2 + ring +lemma computes_numerals (m n : ℕ) (t : ℕ) (ht : steps m.bits n.bits≤t) (bits : Fin t → Bool) : + (run machine (input m.bits n.bits) bits).state=none ∧ + (run machine (input m.bits n.bits) bits).tape.right₀=ListBlank.mk (output (compare m n)) := by + simpa only [StackAddition.value_bits] using computes m.bits n.bits t ht bits +end MatchingFPRAS.PostComparison + +end OAI diff --git a/lean/OAI/Combinatorics/MatchingCount/Arithmetic/SubtractProc.lean b/lean/OAI/Combinatorics/MatchingCount/Arithmetic/SubtractProc.lean new file mode 100644 index 0000000000000000000000000000000000000000..507d2eda00f9577360c0823fb2c0ee27ecd47433 --- /dev/null +++ b/lean/OAI/Combinatorics/MatchingCount/Arithmetic/SubtractProc.lean @@ -0,0 +1,48 @@ +import Mathlib +import OAI.Combinatorics.MatchingCount.Machines.FiniteStore +import OAI.Combinatorics.MatchingCount.Arithmetic.BinarySubtract + +namespace OAI + +namespace MatchingFPRAS.ForwardSubtract +open Turing MachineCost StackAddition StackSubtract + +local instance initialControl : Inhabited (Bool⊕Unit) := ⟨.inl false⟩ +abbrev Γ := fun _ : Fin 3 => Bool +def program : Bool⊕Unit → TM2.Stmt Γ (Bool⊕Unit) Store := + StackComposition.sequence StackSubtract.program ForwardAddition.reverseProgram +lemma run_sub (A B : List Bool) : + ∃ k≤2*(A.length+B.length)+2, + MachineCost.run (TM2.step program) k ⟨some default,default,stackData A B []⟩= + ⟨none,default,stackData ((subDigits false A B).2) [] []⟩ := by + obtain ⟨n,hn,he⟩:=run_subtraction A B [] false default + have he' : MachineCost.run (TM2.step StackSubtract.program) n + (StackSubtract.cfg (some false) A B [] default)=StackSubtract.cfg none [] [] ((subDigits false A B).2).reverse default := by + simpa only [List.append_nil] using he + have hr := ForwardAddition.run_reverse [] [] ((subDigits false A B).2).reverse default + have hr' : MachineCost.run (TM2.step ForwardAddition.reverseProgram) (((subDigits false A B).2).length+1) + ⟨some default,default,stackData [] [] ((subDigits false A B).2).reverse⟩= + ⟨none,default,stackData ((subDigits false A B).2) [] []⟩ := by + simpa only [ForwardAddition.rcfg,List.length_reverse,List.reverse_reverse,List.append_nil] using hr + obtain ⟨k,hk,hkrun⟩:=StackComposition.sequence_run StackSubtract.program ForwardAddition.reverseProgram + (StackSubtract.cfg (some false) A B [] default) n (((subDigits false A B).2).length+1) + (default : Store) (default : Store) (stackData [] [] ((subDigits false A B).2).reverse) + (stackData ((subDigits false A B).2) [] []) he' hr' + refine ⟨k,?_,?_⟩ + · have hl:=subDigits_length A B false + omega + · exact hkrun +end MatchingFPRAS.ForwardSubtract + +namespace MatchingFPRAS.BinaryArithmeticProc +open RegisterProc Turing + +local instance subEntry : Inhabited (Bool⊕Unit) := ⟨.inl false⟩ +def sub : Proc (Fin 3) := FiniteStore.procedure ForwardSubtract.program (default : StackAddition.Store) +lemma sub_exec (A B : List Bool) : + Exec sub ![A,B,[]] ![(StackSubtract.subDigits false A B).2,[],[]] (2*(A.length+B.length)+2) := by + obtain ⟨n,hn,he⟩:=ForwardSubtract.run_sub A B + exact (FiniteStore.exec ForwardSubtract.program default default _ _ n he).mono hn +end MatchingFPRAS.BinaryArithmeticProc + +end OAI diff --git a/lean/OAI/Combinatorics/MatchingCount/Arithmetic/TreeAdaptiveArithmetic.lean b/lean/OAI/Combinatorics/MatchingCount/Arithmetic/TreeAdaptiveArithmetic.lean new file mode 100644 index 0000000000000000000000000000000000000000..4228a21d0d46a380fa70fc0cd0ff2fa7df9e14e4 --- /dev/null +++ b/lean/OAI/Combinatorics/MatchingCount/Arithmetic/TreeAdaptiveArithmetic.lean @@ -0,0 +1,140 @@ +import Mathlib +import OAI.Combinatorics.MatchingCount.Algorithm.RationalEstimator +import OAI.Combinatorics.MatchingCount.Sampling.TreeDPCount +import OAI.Combinatorics.MatchingCount.Algorithm.TreeEstimator +import OAI.Combinatorics.MatchingCount.Algorithm.TreeScalingCorrect +import OAI.Combinatorics.MatchingCount.Algorithm.TreeReweight + +namespace OAI + +namespace MatchingFPRAS.ExecutableAdaptive +open TreeTyped TreeFraction ExecutableBottleneck ExecutableScaling ExecutableEstimator ExecutableLadder + +abbrev ProbeTable := List ((ℕ×ℕ)×Fraction) +abbrev MatrixData := (ℕ×Fraction)×ProbeTable + +def orderedPair (x : ℕ×ℕ) : ℕ×ℕ := if x.1rfl) +lemma polynomial_estimateCell : PolynomialTime estimateCellRealizer := by + unfold estimateCellRealizer Realizer.fst Realizer.snd; apply polynomial_congr + have := polynomial_probeValue + have := polynomial_upper + tree_cost + +def estimateRow (x : (MatrixData×List ℕ)×ℕ) : List Fraction := + x.1.2.map (fun j=>estimateCell (x.1.1,(x.2,j))) +def estimateRowRealizer : Realizer estimateRow := (composition + (pair (pair first.fst second) first.snd) + (mapWith (composition (pair first.fst (pair first.snd second)) estimateCellRealizer))).congr (fun _=>rfl) +lemma polynomial_estimateRow : PolynomialTime estimateRowRealizer := by + unfold estimateRowRealizer Realizer.fst Realizer.snd; apply polynomial_congr + have := polynomial_estimateCell + tree_cost + +def estimateMatrix (x : MatrixData×List ℕ) : Matrix := x.2.map (fun i=>estimateRow (x,i)) +def estimateMatrixRealizer : Realizer estimateMatrix := composition (pair identity second) (mapWith estimateRowRealizer) +lemma polynomial_estimateMatrix : PolynomialTime estimateMatrixRealizer := + polynomial_composition (polynomial_pair polynomial_identity polynomial_second) + (polynomial_mapWith polynomial_estimateRow) + +def multiplyVector (x : Vector×Vector) : Vector := + x.1.map (fun z=>(z.1,mul (z.2,lookup (1,1) (x.2,z.1)))) +def multiplyVectorRealizer : Realizer multiplyVector := (composition (pair second first) + (mapWith (pair second.fst (composition (pair second.snd + (composition (pair first second.fst) (lookupRealizer (1,1) natEqual))) mulRealizer)))).congr (fun _=>rfl) +lemma polynomial_multiplyVector : PolynomialTime multiplyVectorRealizer := by + unfold multiplyVectorRealizer Realizer.fst Realizer.snd; apply polynomial_congr + have := polynomial_lookup ((1,1) : Fraction) polynomial_natEqual + have := polynomial_mul + tree_cost + +def updateVector (x : Matrix×Vector) : Vector := multiplyVector (x.2,scale x.1) +def updateVectorRealizer : Realizer updateVector := (composition + (pair (second : Realizer (Prod.snd : Matrix×Vector→Vector)) + (composition (first : Realizer (Prod.fst : Matrix×Vector→Matrix)) scaleRealizer)) multiplyVectorRealizer).congr (fun _=>rfl) +lemma polynomial_updateVector : PolynomialTime updateVectorRealizer := by + unfold updateVectorRealizer + apply polynomial_congr + exact polynomial_composition (polynomial_pair polynomial_second + (polynomial_composition polynomial_first polynomial_scale)) polynomial_multiplyVector + +lemma orderedPair_fin {n : ℕ} (i j : Fin n) (h : i≠j) : + orderedPair (i.val,j.val)=ExecutableSource.logicalRepr (Enlargement.pairEdge i j h) := by + unfold orderedPair Enlargement.pairEdge ExecutableSource.logicalRepr + by_cases hij : ihe (Fin.ext h) + simp only [ite_eq_right hv,dite_eq_right he] + rw [orderedPair_fin i j he,ht] + +lemma estimateMatrix_rep {n : ℕ} (D : ℕ) (d : ℚ) (hd : 0≤d) + (z : Enlargement.LogicalEdge (Fin n)→ℚ) (hz : ∀ e,0≤z e) (tab : ProbeTable) + (ht : ∀ e,lookup (0,1) (tab,ExecutableSource.logicalRepr e)=TreeFraction.repr (z e)) : + estimateMatrix (((D,TreeFraction.repr d),tab),List.range n)= + matrixRep (FiniteTrial.estimateMatrix D d z) := by + unfold estimateMatrix estimateRow matrixRep + simp only [ExecutableDP.map_range_ofFn] + congr 1 + funext i + congr 1 + funext j + unfold estimateCell + rw [probeValue_rep z tab ht i j] + apply upper_rep _ _ _ hd + unfold FiniteTrial.probeMatrix + split_ifs + · exact le_rfl + · exact hz _ + +lemma multiplyVector_rep {n : ℕ} (a b : Fin n→ℚ) (ha : ∀ i,0≤a i) (hb : ∀ i,0≤b i) : + multiplyVector (vectorRep a,vectorRep b)=vectorRep (fun i=>a i*b i) := by + unfold multiplyVector vectorRep + rw [List.map_ofFn] + congr 1 + funext i + dsimp only [Function.comp_def] + congr 1 + rw [List.ofFn_eq_map,lookup_image (1,1) (List.finRange n) Fin.val + (fun j=>TreeFraction.repr (b j)) Fin.val_injective i (by simp),mul_repr (ha i) (hb i)] + +lemma updateVector_rep {n : ℕ} (hn : 2≤n) (G : Fin n→Fin n→ℚ) + (hsym : ∀ i j,G i j=G j i) + (hG : ∀ i j,i≠j→ Counting.alpha≤G i j ∧ G i j≤3) + (a : Fin n→ℚ) (ha : ∀ i,0≤a i) : + updateVector (matrixRep G,vectorRep a)=vectorRep (fun i=>a i*Counting.scalingTrace hn G n i) := by + unfold updateVector + rw [scale_rep hn G hsym hG] + apply multiplyVector_rep a _ ha + intro i + exact ((Counting.scalingTrace_invariant hn G hsym hG n).1.pos i).le +end MatchingFPRAS.ExecutableAdaptive + +end OAI diff --git a/lean/OAI/Combinatorics/MatchingCount/Arithmetic/TreeCompare.lean b/lean/OAI/Combinatorics/MatchingCount/Arithmetic/TreeCompare.lean new file mode 100644 index 0000000000000000000000000000000000000000..402575901cb256064b790e0acae696e98ce75f2d --- /dev/null +++ b/lean/OAI/Combinatorics/MatchingCount/Arithmetic/TreeCompare.lean @@ -0,0 +1,72 @@ +import Mathlib +import OAI.Combinatorics.MatchingCount.Arithmetic.TreeNumberOps + +namespace OAI + +namespace MatchingFPRAS.BinaryArithmeticProc +open RegisterProc TreeData Turing + +def pickLt : Proc (Fin 3) := atom + (.pop 2 (fun _ x=>x) (.pop 2 (fun x _=>x) + (.branch (fun x=>x.getD false) + (.push 0 (fun _=>false) (.push 0 (fun _=>false) (.push 0 (fun _=>true) + (.load (fun _=>none) .halt)))) + (.push 0 (fun _=>false) (.load (fun _=>none) .halt))))) +lemma pickLt_exec (c : Ordering) : + Exec pickLt ![[],[],StackCompare.flags c] ![encode (bit (decide (c=.lt))),[],[]] 1 := by + apply exec_atom + cases c <;> simp [TM2.stepAux,StackCompare.flags,encode,bit] + all_goals funext k; fin_cases k <;> simp + +def less : Proc (Fin 3) := seq compare pickLt +lemma less_exec (A B : List Bool) : + Exec less ![A,B,[]] ![encode (bit (decide (StackAddition.value Afalse) .halt)))) + +theorem less_bits_exec (E : Env R) (i j : R) (hij : i≠j) (A B : List Bool) + (hi : E i=bits A) (hj : E j=bits B) : + Exec (less i j hij) (encodeEnv E) + (encodeEnv (putPair E i j (bit (decide (StackAddition.value Afalse) .halt)) + (rawPair E i j (TreeData.encode (bit (decide (StackAddition.value A simp⟩ +def program : Point → RegisterControl.Instr Reg Point + | .loop => .branch 0 .halt .split + | .split => .call (procedure (TreeMachine.Instr.split (Λ:=Unit) 4 0 (by decide) ())) .shift + | .shift => .call (procedure (TreeMachine.Instr.cons (Λ:=Unit) 4 2 (by decide) ())) .copyR + | .copyR => .call (procedure (TreeMachine.Instr.copy (Λ:=Unit) 2 4 (by decide) ())) .copyD + | .copyD => .call (procedure (TreeMachine.Instr.copy (Λ:=Unit) 1 5 (by decide) ())) .cmp + | .cmp => .call (TreeArithmetic.less 4 5 (by decide)) .test + | .test => .branch 4 .copyD2 .zero + | .copyD2 => .call (procedure (TreeMachine.Instr.copy (Λ:=Unit) 1 5 (by decide) ())) .sub + | .sub => .call (TreeArithmetic.sub 2 5 (by decide)) .one + | .one => .call (procedure (TreeMachine.Instr.cons (Λ:=Unit) 5 4 (by decide) ())) .pushQ + | .zero => .call (procedure (TreeMachine.Instr.nil (Λ:=Unit) 4 ())) .pushQ + | .pushQ => .call (procedure (TreeMachine.Instr.cons (Λ:=Unit) 4 3 (by decide) ())) .loop + | .halt => .halt + +def splitState (E : Env Reg) (b : Bool) (A : List Bool) := putPair E 4 0 (bit b) (bits A) +def shiftState (E : Env Reg) (b : Bool) (A C : List Bool) := + putPair (splitState E b A) 4 2 .nil (bits (b::C)) +def copyState (E : Env Reg) (b : Bool) (A B C : List Bool) := + putPair (putPair (shiftState E b A C) 2 4 (bits (b::C)) (bits (b::C))) 1 5 (bits B) (bits B) +def tested (E : Env Reg) (b : Bool) (A B C : List Bool) := + putPair (copyState E b A B C) 4 5 (bit (low b B C)) .nil +def reduced (E : Env Reg) (b : Bool) (A B C : List Bool) := + putPair (putPair (tested E b A B C) 1 5 (bits B) (bits B)) 2 5 + (nat (value (b::C)-value B)) .nil +def digitState (E : Env Reg) (b : Bool) (A B C : List Bool) : Env Reg := + if low b B C then Function.update (tested E b A B C) 4 .nil + else putPair (reduced E b A B C) 5 4 .nil (bit true) +def next (E : Env Reg) (b : Bool) (A B Q C : List Bool) : Env Reg := + putPair (digitState E b A B C) 4 3 .nil (bits (nextQ b B Q C)) +def result (E : Env Reg) : List Bool → List Bool → List Bool → List Bool → Env Reg + | [],_,_,_ => E + | b::A,B,Q,C => result (next E b A B Q C) A B (nextQ b B Q C) (nextR b B C) + +lemma next_zero (E : Env Reg) (b : Bool) (A B Q C : List Bool) : next E b A B Q C 0=bits A := by + unfold next digitState + split_ifs <;> simp [tested,copyState,shiftState,splitState,reduced,putPair] +lemma next_one (E : Env Reg) (b : Bool) (A B Q C : List Bool) : next E b A B Q C 1=bits B := by + unfold next digitState + split_ifs <;> simp [tested,copyState,reduced,putPair] +lemma next_two (E : Env Reg) (b : Bool) (A B Q C : List Bool) : + next E b A B Q C 2=bits (nextR b B C) := by + unfold next digitState nextR + split_ifs <;> simp [tested,copyState,shiftState,splitState,reduced,putPair,nat,bits] +lemma next_three (E : Env Reg) (b : Bool) (A B Q C : List Bool) : + next E b A B Q C 3=bits (nextQ b B Q C) := by simp [next,putPair] +lemma next_four (E : Env Reg) (b : Bool) (A B Q C : List Bool) : next E b A B Q C 4=.nil := by + simp [next,putPair] +lemma next_five (E : Env Reg) (b : Bool) (A B Q C : List Bool) : next E b A B Q C 5=.nil := by + unfold next digitState + split_ifs <;> simp [tested,reduced,putPair] +lemma next_six (E : Env Reg) (b : Bool) (A B Q C : List Bool) : next E b A B Q C 6=E 6 := by + unfold next digitState + split_ifs <;> simp [tested,copyState,shiftState,splitState,reduced,putPair] + +lemma outputs (E : Env Reg) (A B Q C : List Bool) (h2 : E 2=bits C) (h3 : E 3=bits Q) : + result E A B Q C 2=bits (BinaryDivision.run A B Q C).2 ∧ + result E A B Q C 3=bits (BinaryDivision.run A B Q C).1 := by + induction A generalizing E Q C with + | nil => exact ⟨h2,h3⟩ + | cons b A ih => exact ih _ _ _ (next_two E b A B Q C) (next_three E b A B Q C) + +open RegisterControl (Runs) + +lemma cycle_runs (E F : Env Reg) (b : Bool) (A B Q C : List Bool) (D n : ℕ) + (h0 : E 0=bits (b::A)) (h1 : E 1=bits B) (h2 : E 2=bits C) (h3 : E 3=bits Q) + (h4 : E 4=.nil) (h5 : E 5=.nil) (hB : B.length ≤ D) (hC : C.length ≤ D) + (rest : Runs program (some Point.loop) (next E b A B Q C) F n) : + Runs program (some Point.loop) E F (100*(D+2)+n) := by + have hf4 : digitState E b A B C 4=bit (!low b B C) := by + cases hl : low b B C <;> simp [digitState,hl,putPair,bit] + have hf3 : digitState E b A B C 3=bits Q := by + unfold digitState + split_ifs <;> simp [tested,reduced,copyState,shiftState,splitState,putPair,h3] + have hpush := cons_exec (digitState E b A B C) 4 3 (by decide) () + rw [hf4,hf3] at hpush + change Exec _ _ (encodeEnv (next E b A B Q C)) _ at hpush + have hpush' := hpush.mono (show 2*(encode (bit (!low b B C))).length+3 ≤ 9 by + have := TreeMultiply.bit_length (!low b B C); omega) + have tail : Runs program (some Point.pushQ) (digitState E b A B C) F (10+n) := + Runs.step Point.pushQ _ _ _ _ _ 10 (Effect.call _ _ _ _ 9 hpush') rest + have ht : Runs program (some Point.test) (tested E b A B C) F (31*D+60+n) := by + cases hl : low b B C with + | true => + have hx : tested E b A B C 4=.cons .nil .nil := by simp [tested,putPair,hl,bit] + have hzero := nil_exec (tested E b A B C) 4 () + rw [hx] at hzero + change Exec _ _ (encodeEnv (Function.update (tested E b A B C) 4 .nil)) 5 at hzero + simp only [digitState,hl,↓reduceIte] at tail + have hz : Runs program (some Point.zero) (tested E b A B C) F (6+(10+n)) := + Runs.step Point.zero _ _ _ _ _ 6 (Effect.call _ _ _ _ 5 hzero) tail + have htest : Runs program (some Point.test) (tested E b A B C) F (1+(6+(10+n))) := + Runs.step Point.test _ _ _ _ _ 1 (Effect.consBranch _ 4 _ _ .nil .nil hx) hz + exact Runs.weaken _ _ _ _ _ htest (by omega) + | false => + have hx : tested E b A B C 4=.nil := by simp [tested,putPair,hl,bit] + have hlower : value B ≤ value (b::C) := by + have hn : ¬ value (b::C) + have hh : Runs program (some Point.halt) E E 1 := + Runs.step Point.halt _ _ _ _ 0 1 (Effect.halt _) (Runs.done _) + have hl : Runs program (some Point.loop) E E 2 := + Runs.step Point.loop _ _ _ _ 1 1 (Effect.nilBranch _ 0 _ _ h0) hh + exact Runs.weaken _ _ _ _ _ hl (by simp only [List.length_nil]; omega) + | cons b A ih => + have hr := ih (next E b A B Q C) (nextQ b B Q C) (nextR b B C) + (next_zero E b A B Q C) (next_one E b A B Q C) (next_two E b A B Q C) + (next_three E b A B Q C) (next_four E b A B Q C) (next_five E b A B Q C) + (by have := BinaryDivision.nextR_length b B C; simp only [List.length_cons] at hC; omega) + have hh := cycle_runs E _ b A B Q C D _ h0 h1 h2 h3 h4 h5 hB + (by simp only [List.length_cons] at hC; omega) hr + convert hh using 1 <;> simp only [result,List.length_cons] + ring + +def divide : Proc (K Reg) := RegisterControl.compile program + +theorem exec (E : Env Reg) (A B Q C : List Bool) (D : ℕ) + (h0 : E 0=bits A) (h1 : E 1=bits B) (h2 : E 2=bits C) (h3 : E 3=bits Q) + (h4 : E 4=.nil) (h5 : E 5=.nil) (hB : B.length ≤ D) (hC : C.length+A.length ≤ D) : + Exec divide (encodeEnv E) (encodeEnv (result E A B Q C)) (100*(A.length+1)*(D+2)) := + RegisterControl.compile_exec program _ E _ (runs E A B Q C D h0 h1 h2 h3 h4 h5 hB hC) + +end MatchingFPRAS.TreeDivision + +end OAI diff --git a/lean/OAI/Combinatorics/MatchingCount/Arithmetic/TreeDyadic.lean b/lean/OAI/Combinatorics/MatchingCount/Arithmetic/TreeDyadic.lean new file mode 100644 index 0000000000000000000000000000000000000000..1f2de071bdce14a658195139be05ce561a96e3e2 --- /dev/null +++ b/lean/OAI/Combinatorics/MatchingCount/Arithmetic/TreeDyadic.lean @@ -0,0 +1,52 @@ +import Mathlib +import OAI.Combinatorics.MatchingCount.Graphs.Related2 +import OAI.Combinatorics.MatchingCount.Complexity.TreeChoiceCosts + +namespace OAI + +namespace MatchingFPRAS.ExecutableHierarchy +open TreeTyped TreeFraction Polynomial + +def level (x : ℕ×Fraction) : ℕ := min x.1 ((x.2.1/x.2.2).size-1) +def levelRealizer : Realizer level := composition (pair first + (composition (composition (composition second quotient) bitSize) predecessor)) minNat +lemma polynomial_level : PolynomialTime levelRealizer := by + exact polynomial_composition (polynomial_pair polynomial_first + (polynomial_composition (polynomial_composition (polynomial_composition polynomial_second + polynomial_quotient) polynomial_bitSize) polynomial_predecessor)) polynomial_minNat +lemma findGreatest_lt_size (H s : ℕ) : Nat.findGreatest (fun k=>k(2:ℚ)^k≤val x)=(fun k=>k<(x.1/x.2).size) := by + funext k + apply propext + rw [Nat.lt_size] + rw [←Rat.natFloor_natCast_div_natCast] + have h:=Nat.le_floor_iff' (R:=ℚ) (n:=2^k) (a:=val x) (by positivity) + simpa only [val,Nat.cast_pow,Nat.cast_ofNat] using h.symm + simp only [NumberedHierarchy.level,level,hp,findGreatest_lt_size] +lemma level_repr (H : ℕ) (q : ℚ) (hq : 0≤q) : + level (H,TreeFraction.repr q)=(NumberedHierarchy.level H q).val := by + rw [level_val,TreeFraction.val_repr hq] + +def threshold (x : List Bool×ℕ) : Fraction := (bitDenominator (x.1.take x.2),1) +def thresholdRealizer : Realizer threshold := pair (composition takeFast bitDenominatorRealizer) (constant 1) +lemma polynomial_threshold : PolynomialTime thresholdRealizer := by + unfold thresholdRealizer + exact polynomial_pair (polynomial_composition polynomial_takeFast polynomial_bitDenominator) (polynomial_constant 1) +lemma threshold_repr (xs : List Bool) (k : ℕ) (hk : k≤xs.length) : + threshold (xs,k)=TreeFraction.repr ((2:ℚ)^k) := by + simp only [threshold,bitDenominator_eq,List.length_take,min_eq_left hk] + have h : val ((2^k,1):Fraction)=(2:ℚ)^k := by simp [val] + rw [←h,←normalize_repr] + simp [TreeFraction.normalize] +end MatchingFPRAS.ExecutableHierarchy + +end OAI diff --git a/lean/OAI/Combinatorics/MatchingCount/Arithmetic/TreeFraction.lean b/lean/OAI/Combinatorics/MatchingCount/Arithmetic/TreeFraction.lean new file mode 100644 index 0000000000000000000000000000000000000000..16d936130d41a288f56776964eb21d65fd79fbd5 --- /dev/null +++ b/lean/OAI/Combinatorics/MatchingCount/Arithmetic/TreeFraction.lean @@ -0,0 +1,101 @@ +import Mathlib +import OAI.Combinatorics.MatchingCount.Arithmetic.TreeGCD + +namespace OAI + +namespace MatchingFPRAS.TreeFraction +open TreeTyped + +abbrev Fraction := ℕ×ℕ +def val (x : Fraction) : ℚ := (x.1:ℚ)/x.2 +def repr (q : ℚ) : Fraction := (q.num.natAbs,q.den) + +def normalize (x : Fraction) : Fraction := + if x.2=0 then (0,1) else (x.1/(x.1.gcd x.2),x.2/(x.1.gcd x.2)) + +def normalizeRealizer : Realizer normalize := by + let G := gcd + let Q := pair (composition (pair first G) quotient) (composition (pair second G) quotient) + exact (choose (composition (pair second (constant 0)) natEqual) (constant (0,1)) Q).congr + (fun x=>by simp only [normalize,Function.comp_apply,decide_eq_true_eq]) + +lemma normalize_repr (x : Fraction) : normalize x=repr (val x) := by + by_cases hd : x.2=0 + · simp [normalize,repr,val,hd] + · have he : val x=mkRat (x.1:Int) x.2 := by simp [val,Rat.mkRat_eq_div] + simp only [normalize,hd,↓reduceIte,he,repr,Rat.num_mkRat,Rat.den_mkRat] + simp [Nat.gcd_comm,←Int.natCast_ediv] + +lemma val_nonneg (x : Fraction) : 0≤val x := by unfold val; positivity +lemma val_repr {q : ℚ} (h : 0≤q) : val (repr q)=q := by + have hn : 0≤q.num := by exact Rat.num_nonneg.mpr h + have he : (q.num.natAbs : ℤ)=q.num := Int.natAbs_of_nonneg hn + change (q.num.natAbs:ℚ)/(q.den:ℚ)=q + rw [←Int.cast_natCast q.num.natAbs,he] + exact Rat.num_div_den q + +lemma normalize_val (x : Fraction) : val (normalize x)=val x := by + rw [normalize_repr] + exact val_repr (val_nonneg x) + +lemma normalize_den_pos (x : Fraction) : 0<(normalize x).2 := by + rw [normalize_repr]; exact (val x).pos + +lemma normalize_size_num (x : Fraction) : (normalize x).1.size≤x.1.size := by + unfold normalize; split_ifs + · simp + · exact Nat.size_le_size (Nat.div_le_self _ _) +lemma normalize_size_den (x : Fraction) : (normalize x).2.size≤x.2.size+1 := by + unfold normalize; split_ifs + · simp + · exact (Nat.size_le_size (Nat.div_le_self _ _)).trans (Nat.le_succ _) + +def mul (x : Fraction×Fraction) : Fraction := normalize (x.1.1*x.2.1,x.1.2*x.2.2) +def mulRealizer : Realizer mul := + composition (pair (composition (pair (composition first first) (composition second first)) multiply) + (composition (pair (composition first second) (composition second second)) multiply)) normalizeRealizer +lemma mul_val (x y : Fraction) : val (mul (x,y))=val x*val y := by + rw [mul,normalize_val] + simp only [val,Nat.cast_mul] + exact (div_mul_div_comm _ _ _ _).symm + +def add (x : Fraction×Fraction) : Fraction := + normalize (x.1.1*x.2.2+x.2.1*x.1.2,x.1.2*x.2.2) +def addRealizer : Realizer add := + composition (pair (composition (pair + (composition (pair (composition first first) (composition second second)) multiply) + (composition (pair (composition second first) (composition first second)) multiply)) TreeTyped.add) + (composition (pair (composition first second) (composition second second)) multiply)) normalizeRealizer +lemma add_val (x y : Fraction) (hx : x.2≠0) (hy : y.2≠0) : + val (add (x,y))=val x+val y := by + rw [add,normalize_val] + simp only [val,Nat.cast_add,Nat.cast_mul] + rw [div_add_div (x.1:ℚ) (y.1:ℚ) (b:=(x.2:ℚ)) (d:=(y.2:ℚ)) + (by exact_mod_cast hx) (by exact_mod_cast hy)] + ring + +def div (x : Fraction×Fraction) : Fraction := normalize (x.1.1*x.2.2,x.1.2*x.2.1) +def divRealizer : Realizer div := + composition (pair (composition (pair (composition first first) (composition second second)) multiply) + (composition (pair (composition first second) (composition second first)) multiply)) normalizeRealizer +lemma div_val (x y : Fraction) : val (div (x,y))=val x/val y := by + rw [div,normalize_val] + simp only [val,Nat.cast_mul] + simp only [div_eq_mul_inv,mul_inv_rev,inv_inv] + ring + +def less (x : Fraction×Fraction) : Bool := decide (x.1.1*x.2.2 omega +lemma fractionProduct_height (xs : List Fraction) (a : Fraction) (M : ℕ) + (hx : ∀ b∈xs,height b≤M) : + height (xs.foldl (fun a b=>mul (b,a)) a)≤height a+xs.length*(M+1) := by + induction xs generalizing a with + | nil => simp + | cons b bs ih => + have hh:=height_mul b a + have hb:=hx b (by simp) + have ht:=ih (mul (b,a)) (fun c h=>hx c (by simp [h])) + simp only [List.foldl_cons,List.length_cons] + nlinarith +lemma polynomial_fractionProduct : PolynomialTime (fold mulRealizer) := by + apply polynomial_fold polynomial_mul (8*X+8*X*(X+1)+3) + intro xs a pre post he + let S:=weight (xs,a) + have hpre : pre.length≤S := (list_length_le_weight pre).trans ((weight_prefix he).trans (weight_fst (xs,a))) + have hb : ∀ b∈pre,height b≤S := by + intro b hb + exact (height_le_weight b).trans ((weight_mem (as:=xs) (by simp [he,hb])).trans (weight_fst (xs,a))) + have ha : height a≤S := (height_le_weight a).trans (weight_snd (xs,a)) + have hh:=fractionProduct_height pre a S hb + have hw:=weight_le_height (pre.foldl (fun a b=>mul (b,a)) a) + have hm:=Nat.mul_le_mul_right (S+1) hpre + simp only [Polynomial.eval_add,Polynomial.eval_mul,Polynomial.eval_ofNat,Polynomial.eval_X,Polynomial.eval_one] + change _≤8*S+8*S*(S+1)+3 + nlinarith + +def product (xs : List Fraction) : Fraction := xs.foldl (fun a b=>mul (b,a)) (1,1) +def productRealizer : Realizer product := + (composition (pair identity (constant (1,1))) (fold mulRealizer)).congr (fun _=>rfl) +lemma polynomial_product : PolynomialTime productRealizer := + polynomial_congr _ (polynomial_composition (polynomial_pair polynomial_identity (polynomial_constant _)) polynomial_fractionProduct) +end MatchingFPRAS.TreeFraction + +end OAI diff --git a/lean/OAI/Combinatorics/MatchingCount/Arithmetic/TreeGCD.lean b/lean/OAI/Combinatorics/MatchingCount/Arithmetic/TreeGCD.lean new file mode 100644 index 0000000000000000000000000000000000000000..4f8d83509316bf46f214f5f6d2882ef49b04cf7a --- /dev/null +++ b/lean/OAI/Combinatorics/MatchingCount/Arithmetic/TreeGCD.lean @@ -0,0 +1,98 @@ +import Mathlib +import OAI.Combinatorics.MatchingCount.Machines.TreeNaturalComb +import OAI.Combinatorics.MatchingCount.Machines.TreePredicate + +namespace OAI + +namespace MatchingFPRAS.TreeTyped +open TreeData TreeMachine RegisterProc TreeFunction + +def digits : Realizer Nat.bits where + program := identity.program (A:=ℕ) + cost := fun _=>1 + correct := fun a s=>identity.correct a s + +def bitSize : Realizer Nat.size := + (composition digits listLength).congr (fun a=>Nat.size_eq_bits_len a) + +def sortedPair (x : ℕ×ℕ) : ℕ×ℕ := if x.1by simp [sortedPair]) + +lemma sortedPair_order (x : ℕ×ℕ) : (sortedPair x).2≤(sortedPair x).1 := by + unfold sortedPair; split_ifs <;> (try dsimp only) <;> omega +lemma sortedPair_gcd (x : ℕ×ℕ) : (sortedPair x).1.gcd (sortedPair x).2=x.1.gcd x.2 := by + unfold sortedPair; split_ifs <;> simp [Nat.gcd_comm] +lemma sortedPair_size (x : ℕ×ℕ) : (sortedPair x).1.size+(sortedPair x).2.size=x.1.size+x.2.size := by + unfold sortedPair + split_ifs + · exact Nat.add_comm _ _ + · rfl + +def gcdStep (x : ℕ×ℕ) : ℕ×ℕ := if x.2=0 then x else (x.2,x.1%x.2) +def gcdStepRealizer : Realizer gcdStep := + (choose (composition (pair second (constant 0)) natEqual) identity (pair second remainder)).congr + (fun x=>by simp only [gcdStep,Function.comp_apply,decide_eq_true_eq,id_eq]) + +lemma mod_size_lt {a b : ℕ} (hb : 0 rfl + | succ k ih => simpa only [countDown,gcdIterStep,gcdStep,↓reduceIte] using ih + +lemma gcdIter_result (k : ℕ) (x : ℕ×ℕ) (h : x.2≤x.1) (hs : x.1.size+x.2.size≤k) : + countDown gcdIterStep k x=(x.1.gcd x.2,0) := by + induction k generalizing x with + | zero => + have hsz : x.1.size=0 := by omega + have ha:=Nat.size_eq_zero.mp hsz + have hb : x.2=0 := by omega + simp [countDown,ha,hb] + exact Prod.ext ha hb + | succ k ih => + by_cases hz : x.2=0 + · obtain ⟨a,b⟩:=x; dsimp only at hz; subst b + simp only [gcdIter_zero,Nat.gcd_zero_right] + · rw [countDown] + change countDown gcdIterStep k (gcdStep x)=_ + rw [ih _ (gcdStep_order h) (by have hd:=gcdStep_decrease h hz; omega),gcdStep_gcd] + +def gcd : Realizer (fun x : ℕ×ℕ=>x.1.gcd x.2) := + (composition (composition (pair (composition (pair (composition first bitSize) + (composition second bitSize)) add) sortedPairRealizer) + (iterateDown (composition second gcdStepRealizer))) first).congr (by + intro x + change (countDown gcdIterStep (x.1.size+x.2.size) (sortedPair x)).1=x.1.gcd x.2 + rw [gcdIter_result _ _ (sortedPair_order x) (by rw [sortedPair_size]),sortedPair_gcd]) + +end MatchingFPRAS.TreeTyped + +end OAI diff --git a/lean/OAI/Combinatorics/MatchingCount/Arithmetic/TreeMultiply.lean b/lean/OAI/Combinatorics/MatchingCount/Arithmetic/TreeMultiply.lean new file mode 100644 index 0000000000000000000000000000000000000000..2a7cff49d6a15fcb40748541c9e62d7185614b8a --- /dev/null +++ b/lean/OAI/Combinatorics/MatchingCount/Arithmetic/TreeMultiply.lean @@ -0,0 +1,175 @@ +import Mathlib +import OAI.Combinatorics.MatchingCount.Machines.RegisterControl +import OAI.Combinatorics.MatchingCount.Tapes.TreeAddBits + +namespace OAI + +namespace MatchingFPRAS.TreeMultiply +open TreeData TreeMachine RegisterProc Turing +open StackAddition (value value_bits) +open RegisterControl (Instr Runs Effect) + +abbrev R := Fin 6 +inductive Point where + | loop | split | test | copy | add | shift | halt + deriving DecidableEq, Inhabited +instance : Fintype Point := ⟨{.loop,.split,.test,.copy,.add,.shift,.halt},by intro p; cases p <;> simp⟩ +def program : Point → RegisterControl.Instr R Point + | .loop => .branch 0 .halt .split + | .split => .call (procedure (TreeMachine.Instr.split (Λ:=Unit) 3 0 (by decide) ())) .test + | .test => .branch 3 .shift .copy + | .copy => .call (procedure (TreeMachine.Instr.copy (Λ:=Unit) 1 4 (by decide) ())) .add + | .add => .call (TreeArithmetic.add 2 4 (by decide)) .shift + | .shift => .call (procedure (TreeMachine.Instr.cons (Λ:=Unit) 4 1 (by decide) ())) .loop + | .halt => .halt + +def prep (E : Env R) (b : Bool) (A : List Bool) : Env R := putPair E 3 0 (bit b) (bits A) +def summed (E : Env R) (b : Bool) (B : List Bool) (c : ℕ) : Env R := + if b then putPair (putPair E 1 4 (bits B) (bits B)) 2 4 (nat (c+value B)) .nil else E +def next (E : Env R) (b : Bool) (A B : List Bool) (c : ℕ) : Env R := + putPair (summed (prep E b A) b B c) 4 1 .nil (bits (false::B)) +def accum (b : Bool) (B : List Bool) (c : ℕ) : ℕ := if b then c+value B else c +def result (E : Env R) : List Bool → List Bool → ℕ → Env R + | [],_,_ => E + | b::A,B,c => result (next E b A B c) A (false::B) (accum b B c) + +lemma bits_add_length (A B : List Bool) : + (value A+value B).bits.length≤ max A.length B.length+1 := by + have hh := BinaryNormalize.normalize_length (StackAddition.addDigits false A B) + rw [BinaryNormalize.normalize_bits,StackAddition.addDigits_value,Bool.toNat_false,Nat.add_zero] at hh + exact hh.trans (StackAddition.addDigits_length A B false) +lemma bit_length (b : Bool) : (encode (bit b)).length≤3 := by cases b <;> simp [bit,encode] +lemma next_zero (E : Env R) (b : Bool) (A B : List Bool) (c : ℕ) : next E b A B c 0=bits A := by + cases b <;> simp [next,summed,prep,putPair] +lemma next_one (E : Env R) (b : Bool) (A B : List Bool) (c : ℕ) : next E b A B c 1=bits (false::B) := by + simp [next,putPair] +lemma next_two (E : Env R) (b : Bool) (A B : List Bool) (c : ℕ) (hc : E 2=nat c) : + next E b A B c 2=nat (accum b B c) := by + cases b <;> simp [next,summed,prep,putPair,accum,hc] +lemma next_three (E : Env R) (b : Bool) (A B : List Bool) (c : ℕ) : next E b A B c 3=bit b := by + cases b <;> simp [next,summed,prep,putPair] +lemma next_four (E : Env R) (b : Bool) (A B : List Bool) (c : ℕ) : next E b A B c 4=.nil := by + simp [next,putPair] +lemma next_five (E : Env R) (b : Bool) (A B : List Bool) (c : ℕ) : next E b A B c 5=E 5 := by + cases b <;> simp [next,summed,prep,putPair] +lemma accum_bound (b : Bool) (A B : List Bool) (c D : ℕ) + (hB : B.length+(b::A).length≤D) (hc : c.bits.length+(b::A).length≤D) : + (accum b B c).bits.length+A.length≤D := by + cases b with + | false => + simp only [accum,Bool.false_eq_true,↓reduceIte] + simp only [List.length_cons] at hc + omega + | true => + have hh:=bits_add_length c.bits B + rw [value_bits] at hh + simp only [accum,↓reduceIte] + simp only [List.length_cons] at hB hc + omega + +lemma output (E : Env R) (A B : List Bool) (c : ℕ) (hc : E 2=nat c) : + result E A B c 2=nat (c+value A*value B) := by + induction A generalizing E B c with + | nil => simpa only [result,value,Nat.zero_mul,Nat.add_zero] using hc + | cons b A ih => + rw [result,ih _ _ _ (next_two E b A B c hc)] + congr 1 + cases b <;> simp only [accum,Bool.false_eq_true,↓reduceIte,value,Bool.toNat_false, + Bool.toNat_true,Nat.zero_add] <;> ring +lemma frame (E : Env R) (A B : List Bool) (c : ℕ) : result E A B c 5=E 5 := by + induction A generalizing E B c with + | nil => rfl + | cons b A ih => rw [result,ih,next_five] + +lemma halt_runs (E : Env R) : Runs program (some Point.halt) E E 1 := by + exact (Runs.step Point.halt E none E E 0 1 (Effect.halt E) (Runs.done E)) + +lemma cycle_runs (E F : Env R) (b : Bool) (A B : List Bool) (c D n : ℕ) + (h0 : E 0=bits (b::A)) (h1 : E 1=bits B) (h2 : E 2=nat c) (h4 : E 4=.nil) + (hB : B.length≤D) (hc : c.bits.length≤D) (h3 : (encode (E 3)).length≤D+3) + (rest : Runs program (some Point.loop) (next E b A B c) F n) : + Runs program (some Point.loop) E F (40*(D+2)+n) := by + have hshift := cons_exec (summed (prep E b A) b B c) 4 1 (by decide) () + have hs4 : summed (prep E b A) b B c 4=.nil := by + cases b <;> simp [summed,prep,putPair,h4] + have hs1 : summed (prep E b A) b B c 1=bits B := by + cases b <;> simp [summed,prep,putPair,h1] + rw [hs4,hs1] at hshift + change Exec _ _ (encodeEnv (next E b A B c)) 5 at hshift + have tail : Runs program (some Point.shift) (summed (prep E b A) b B c) F (6+n) := + Runs.step Point.shift _ _ _ _ n 6 (Effect.call _ _ _ _ 5 hshift) rest + have hh : Runs program (some Point.test) (prep E b A) F (31*D+38+n) := by + cases b with + | false => + have hx : prep E false A 3=.nil := by simp [prep,putPair,bit] + have ht : Runs program (some Point.test) (prep E false A) F (1+(6+n)) := + Runs.step Point.test _ _ _ _ _ 1 (Effect.nilBranch _ 3 _ _ hx) tail + exact Runs.weaken _ _ _ _ _ ht (by omega) + | true => + let E' := putPair (prep E true A) 1 4 (bits B) (bits B) + have hp1 : prep E true A 1=bits B := by simp [prep,putPair,h1] + have hp4 : prep E true A 4=.nil := by simp [prep,putPair,h4] + have hcopy := copy_exec (prep E true A) 1 4 (by decide) () + rw [hp1,hp4] at hcopy + change Exec _ _ (encodeEnv E') (1+3*(encode (bits B)).length+4) at hcopy + have hcopy' := hcopy.mono (show 1+3*(encode (bits B)).length+4≤12*D+8 by + have := bits_length B; omega) + have ha2 : E' 2=bits c.bits := by simp [E',prep,putPair,nat,bits,h2] + have ha4 : E' 4=bits B := by simp [E',putPair] + have hadd := TreeArithmetic.add_bits_exec E' 2 4 (by decide) c.bits B ha2 ha4 + rw [value_bits] at hadd + change Exec _ _ (encodeEnv (summed (prep E true A) true B c)) _ at hadd + have hadd' := hadd.mono (show 9*(c.bits.length+B.length)+20≤18*D+20 by omega) + have ha : Runs program (some Point.add) E' F ((18*D+21)+(6+n)) := + Runs.step Point.add _ _ _ _ _ (18*D+21) (Effect.call _ _ _ _ _ hadd') tail + have hcp : Runs program (some Point.copy) (prep E true A) F + ((12*D+9)+((18*D+21)+(6+n))) := + Runs.step Point.copy _ _ _ _ _ (12*D+9) (Effect.call _ _ _ _ _ hcopy') ha + have hx : prep E true A 3=.cons .nil .nil := by simp [prep,putPair,bit] + have ht : Runs program (some Point.test) (prep E true A) F + (1+((12*D+9)+((18*D+21)+(6+n)))) := + Runs.step Point.test _ _ _ _ _ 1 (Effect.consBranch _ 3 _ _ .nil .nil hx) hcp + exact Runs.weaken _ _ _ _ _ ht (by omega) + have he0 : E 0=.cons (bit b) (bits A) := h0 + have hsplit := split_exec E 3 0 (by decide) () (bit b) (bits A) he0 + have hsplit' := hsplit.mono (show (encode (E 3)).length+2*(encode (bit b)).length+4≤D+13 by + have := bit_length b; omega) + have hs : Runs program (some Point.split) E F ((D+14)+(31*D+38+n)) := + Runs.step Point.split _ _ _ _ _ (D+14) (Effect.call _ _ _ _ _ hsplit') hh + have hl : Runs program (some Point.loop) E F (1+((D+14)+(31*D+38+n))) := + Runs.step Point.loop _ _ _ _ _ 1 (Effect.consBranch _ 0 _ _ (bit b) (bits A) he0) hs + exact Runs.weaken _ _ _ _ _ hl (by omega) + +lemma runs (E : Env R) (A B : List Bool) (c D : ℕ) + (h0 : E 0=bits A) (h1 : E 1=bits B) (h2 : E 2=nat c) (h4 : E 4=.nil) + (hB : B.length+A.length≤D) (hc : c.bits.length+A.length≤D) + (h3 : (encode (E 3)).length≤D+3) : + Runs program (some Point.loop) E (result E A B c) (40*(A.length+1)*(D+2)) := by + induction A generalizing E B c with + | nil => + have hl : Runs program (some Point.loop) E E 2 := + Runs.step Point.loop E _ E E 1 1 (Effect.nilBranch _ 0 _ _ h0) (halt_runs E) + exact Runs.weaken _ _ _ _ _ hl (by simp only [List.length_nil]; omega) + | cons b A ih => + have hr := ih (next E b A B c) (false::B) (accum b B c) + (next_zero E b A B c) (next_one E b A B c) (next_two E b A B c h2) + (next_four E b A B c) (by simp only [List.length_cons] at hB ⊢; omega) + (accum_bound b A B c D hB hc) (by rw [next_three]; have := bit_length b; omega) + have hh := cycle_runs E (result (next E b A B c) A (false::B) (accum b B c)) + b A B c D _ h0 h1 h2 h4 (by simp only [List.length_cons] at hB; omega) + (by simp only [List.length_cons] at hc; omega) h3 hr + convert hh using 1 <;> simp only [result,List.length_cons] + ring + +def multiply : Proc (K R) := RegisterControl.compile program + +theorem exec (E : Env R) (A B : List Bool) (c D : ℕ) + (h0 : E 0=bits A) (h1 : E 1=bits B) (h2 : E 2=nat c) (h4 : E 4=.nil) + (hB : B.length+A.length≤D) (hc : c.bits.length+A.length≤D) + (h3 : (encode (E 3)).length≤D+3) : + Exec multiply (encodeEnv E) (encodeEnv (result E A B c)) (40*(A.length+1)*(D+2)) := + RegisterControl.compile_exec program _ E _ (runs E A B c D h0 h1 h2 h4 hB hc h3) + +end MatchingFPRAS.TreeMultiply + +end OAI diff --git a/lean/OAI/Combinatorics/MatchingCount/Arithmetic/TreeNatDivision.lean b/lean/OAI/Combinatorics/MatchingCount/Arithmetic/TreeNatDivision.lean new file mode 100644 index 0000000000000000000000000000000000000000..3858cf2e7d2f7d627e8f01837edf369468532e84 --- /dev/null +++ b/lean/OAI/Combinatorics/MatchingCount/Arithmetic/TreeNatDivision.lean @@ -0,0 +1,118 @@ +import Mathlib +import OAI.Combinatorics.MatchingCount.Machines.TreeList +import OAI.Combinatorics.MatchingCount.Machines.TreePartialChoice + +namespace OAI + +namespace MatchingFPRAS.TreeTyped +open TreeData TreeMachine RegisterProc TreeFunction + +def digitValue : Realizer Bool.toNat := + (choose identity (constant 1) (constant 0)).congr (fun b=>by cases b <;> rfl) + +def divStep (x : Bool×(ℕ×(ℕ×ℕ))) : ℕ×(ℕ×ℕ) := + let n:=x.2.1 + let q:=x.2.2.1 + let r:=2*x.2.2.2+x.1.toNat + (n,if rx.2.1) := composition second first + let qP : Realizer (fun x : Bool×(ℕ×(ℕ×ℕ))=>2*x.2.2.1) := + composition (composition (composition second second) first) double + let rP : Realizer (fun x : Bool×(ℕ×(ℕ×ℕ))=>2*x.2.2.2+x.1.toNat) := + composition (pair (composition (composition (composition second second) second) double) + (composition first digitValue)) add + let lP := composition (pair rP nP) less + let q1P := composition (pair qP (constant 1)) add + let r1P := composition (pair rP nP) subtract + exact (pair nP (choose lP (pair qP rP) (pair q1P r1P))).congr (by + intro x; simp only [Function.comp_apply,divStep,decide_eq_true_eq]) + +lemma divStep_first (b : Bool) (n q r : ℕ) : (divStep (b,(n,q,r))).1=n := rfl +lemma divStep_lt (b : Bool) (n q r : ℕ) (_ : 0 simp only + · assumption + · omega +lemma divStep_mass (b : Bool) (n q r : ℕ) : + n*(divStep (b,(n,q,r))).2.1+(divStep (b,(n,q,r))).2.2= + 2*(n*q+r)+b.toNat := by + simp only [divStep] + split_ifs with h + · simp only; ring + · simp only + have hh : n ≤ 2*r+b.toNat := by omega + have hs:=Nat.sub_add_cancel hh + nlinarith + +lemma divFold_first (A : List Bool) (n q r : ℕ) : + (A.foldl (fun z b=>divStep (b,z)) (n,q,r)).1=n := by + induction A generalizing q r with + | nil => rfl + | cons b A ih => + change (A.foldl _ (divStep (b,(n,q,r)))).1=n + rw [←Prod.eta (divStep (b,(n,q,r))),divStep_first] + rw [←Prod.eta (divStep (b,(n,q,r))).2] + exact ih _ _ + +lemma divFold_lt (A : List Bool) (n q r : ℕ) (hn : 0divStep (b,z)) (n,q,r)).2.2 exact hr + | cons b A ih => + change (A.foldl _ (divStep (b,(n,q,r)))).2.2divStep (b,z)) (n,q,r)).2.1+ + (A.reverse.foldl (fun z b=>divStep (b,z)) (n,q,r)).2.2= + (n*q+r)*2^A.length+StackAddition.value A := by + induction A with + | nil => simp [StackAddition.value] + | cons b A ih => + simp only [List.reverse_cons,List.foldl_append,List.foldl_cons,List.foldl_nil] + let z := A.reverse.foldl (fun z b=>divStep (b,z)) (n,q,r) + have hz : z=(n,z.2.1,z.2.2) := by + apply Prod.ext + · exact divFold_first A.reverse n q r + · rfl + change n*(divStep (b,z)).2.1+(divStep (b,z)).2.2=_ + rw [hz,divStep_mass] + change n*z.2.1+z.2.2=_ at ih + rw [ih] + simp only [StackAddition.value,List.length_cons,pow_succ] + ring + +lemma divFold_correct (m n : ℕ) (hn : 0divStep (b,z)) (n,0,0)).2=(m/n,m%n) := by + have hm:=divFold_mass m.bits n 0 0 + have hr:=divFold_lt m.bits.reverse n 0 0 hn hn + simp only [Nat.mul_zero,Nat.zero_add,Nat.zero_mul,StackAddition.value_bits] at hm + have hu : m/n=(m.bits.reverse.foldl (fun z b=>divStep (b,z)) (n,0,0)).2.1 ∧ + m%n=(m.bits.reverse.foldl (fun z b=>divStep (b,z)) (n,0,0)).2.2 := + (Nat.div_mod_unique hn).2 ⟨by omega,hr⟩ + exact Prod.ext hu.1.symm hu.2.symm + +def divCore : Realizer (fun ab : ℕ×ℕ=> + (ab.1.bits.reverse.foldl (fun z b=>divStep (b,z)) (ab.2,0,0)).2) := + composition (composition (pair (composition (composition first toBits) reverse) + (pair second (pair (constant 0) (constant 0)))) (fold divStepRealizer)) second + +def division : Realizer (fun ab : ℕ×ℕ=>(ab.1/ab.2,ab.1%ab.2)) := by + let posP : Realizer (fun ab : ℕ×ℕ=>decide (0(0,ab.1)) := pair (constant 0) first + exact (choose posP divCore zeroP).congr (by + intro ab + by_cases h : 0false) .halt)) (reindex encodeRaw swap01)) +lemma encodeForward_exec (A C : List Bool) : + Exec encodeForward ![A,[],C] ![encode (bits A),[],C] (2*A.length+3) := by + have h₁:=reverseRaw_exec A [] C + simp only [List.append_nil] at h₁ + have h₂ : Exec (atom (.push (0 : Fin 3) (fun _=>false) .halt)) + ![[],A.reverse,C] ![[false],A.reverse,C] 1 := by + apply exec_atom + simp only [TM2.stepAux] + congr 1 + funext i; fin_cases i <;> simp + have h₃:=reindex_swap encodeRaw A.reverse [false] C [] _ C _ (encodeRaw_exec A C) + apply (h₁.seq (h₂.seq h₃)).mono + omega +end MatchingFPRAS.TreeBits + +namespace MatchingFPRAS.BinaryArithmeticProc +open RegisterProc Turing MachineCost + +local instance addEntry : Inhabited (Bool⊕Unit) := ⟨.inl false⟩ +def add : Proc (Fin 3) := FiniteStore.procedure ForwardAddition.program (default : StackAddition.Store) +lemma add_exec (A B : List Bool) : + Exec add ![A,B,[]] ![StackAddition.addDigits false A B,[],[]] (2*(A.length+B.length)+3) := by + obtain ⟨n,hn,he⟩:=ForwardAddition.run_add A B + exact (FiniteStore.exec ForwardAddition.program default default _ _ n he).mono hn + +local instance compareEntry : Inhabited Ordering := ⟨.eq⟩ +def compare : Proc (Fin 3) := FiniteStore.procedure StackCompare.program (default : StackAddition.Store) +lemma compare_exec (A B : List Bool) : + Exec compare ![A,B,[]] ![[],[],StackCompare.flags (Ord.compare (StackAddition.value A) (StackAddition.value B))] + (A.length+B.length+1) := by + obtain ⟨n,hn,he⟩:=StackCompare.run_comparison A B [] .eq default + have h:=FiniteStore.exec StackCompare.program default default _ _ n he + simp only [StackCompare.compares_values,List.append_nil] at h + exact h.mono hn +end MatchingFPRAS.BinaryArithmeticProc + +namespace MatchingFPRAS.TreeArithmetic +open RegisterProc TreeData TreeMachine Turing + +variable {R : Type} [DecidableEq R] + +def decode (i : R) : Proc (K R) := reindex TreeBits.decodeForward (singleEmbedding i) +def encode (i : R) : Proc (K R) := reindex TreeBits.encodeForward (singleEmbedding i) +def normalize (i : R) : Proc (K R) := reindex BinaryNormalize.program (singleEmbedding i) +def add (i j : R) (hij : i≠j) : Proc (K R) := + seq (decode i) (seq (decode j) + (seq (reindex BinaryArithmeticProc.add (pairEmbedding i j hij)) + (seq (normalize i) (seq (encode i) (atom (.push (.inl j) (fun _=>false) .halt)))))) + +def rawPair (E : Env R) (i j : R) (A B : List Bool) : Stack (K R) := + Function.update (Function.update (encodeEnv E) (.inl i) A) (.inl j) B +lemma rawPair_scratch (E : Env R) (i j : R) (A B : List Bool) (k : Fin 2) : + rawPair E i j A B (.inr k)=[] := by simp [rawPair,encodeEnv] +lemma rawPair_left (E : Env R) (i j : R) (hij : i≠j) (A B : List Bool) : + rawPair E i j A B (.inl i)=A := by simp [rawPair,hij] +lemma rawPair_right (E : Env R) (i j : R) (A B : List Bool) : + rawPair E i j A B (.inl j)=B := by simp [rawPair] +lemma rawPair_encode (E : Env R) (i j : R) (x y : Data) : + rawPair E i j (TreeData.encode x) (TreeData.encode y)=encodeEnv (putPair E i j x y) := by + funext k + cases k with + | inr k => simp [rawPair,encodeEnv] + | inl k => by_cases hi : k=i <;> by_cases hj : k=j <;> simp_all [rawPair,encodeEnv,putPair] +lemma rawPair_same (E : Env R) (i j : R) : + rawPair E i j (TreeData.encode (E i)) (TreeData.encode (E j))=encodeEnv E := by + funext k + cases k with + | inr k => simp [rawPair,encodeEnv] + | inl k => by_cases hi : k=i <;> by_cases hj : k=j <;> simp_all [rawPair,encodeEnv] +lemma put3_raw_left (E : Env R) (i j : R) (hij : i≠j) (A B F : List Bool) : + put3 (rawPair E i j A B) (.inl i) (.inr 0) (.inr 1) F [] []=rawPair E i j F B := by + funext k + cases k with + | inr k => fin_cases k <;> simp [put3,rawPair,encodeEnv] + | inl k => by_cases hi : k=i <;> by_cases hj : k=j <;> simp_all [put3,rawPair] +lemma put3_raw_right (E : Env R) (i j : R) (hij : i≠j) (A B F : List Bool) : + put3 (rawPair E i j A B) (.inl j) (.inr 0) (.inr 1) F [] []=rawPair E i j A F := by + funext k + cases k with + | inr k => fin_cases k <;> simp [put3,rawPair,encodeEnv] + | inl k => by_cases hi : k=i <;> by_cases hj : k=j <;> simp_all [put3,rawPair] +lemma on_left (P : Proc (Fin 3)) (E : Env R) (i j : R) (hij : i≠j) (A B F : List Bool) (n : ℕ) + (h : Exec P ![A,[],[]] ![F,[],[]] n) : + Exec (reindex P (singleEmbedding i)) (rawPair E i j A B) (rawPair E i j F B) n := by + have hh:=exec_on P (.inl i : K R) (.inr 0) (.inr 1) (by simp) (by simp) (by simp) + (rawPair E i j A B) F [] [] n + rw [rawPair_left E i j hij,rawPair_scratch,rawPair_scratch] at hh + simpa only [singleEmbedding,put3_raw_left E i j hij] using hh h +lemma on_right (P : Proc (Fin 3)) (E : Env R) (i j : R) (hij : i≠j) (A B F : List Bool) (n : ℕ) + (h : Exec P ![B,[],[]] ![F,[],[]] n) : + Exec (reindex P (singleEmbedding j)) (rawPair E i j A B) (rawPair E i j A F) n := by + have hh:=exec_on P (.inl j : K R) (.inr 0) (.inr 1) (by simp) (by simp) (by simp) + (rawPair E i j A B) F [] [] n + rw [rawPair_right,rawPair_scratch,rawPair_scratch] at hh + simpa only [singleEmbedding,put3_raw_right E i j hij] using hh h +lemma on_pair (P : Proc (Fin 3)) (E : Env R) (i j : R) (hij : i≠j) (A B F G : List Bool) (n : ℕ) + (h : Exec P ![A,B,[]] ![F,G,[]] n) : + Exec (reindex P (pairEmbedding i j hij)) (rawPair E i j A B) (rawPair E i j F G) n := by + have hh:=exec_on P (.inl i : K R) (.inl j) (.inr 0) (by simpa) (by simp) (by simp) + (rawPair E i j A B) F G [] n + rw [rawPair_left E i j hij,rawPair_right,rawPair_scratch] at hh + have he : put3 (rawPair E i j A B) (.inl i) (.inl j) (.inr 0) F G []=rawPair E i j F G := by + funext k + cases k with + | inr k => fin_cases k <;> simp [put3,rawPair,encodeEnv] + | inl k => by_cases hi : k=i <;> by_cases hj : k=j <;> simp_all [put3,rawPair] + exact he ▸ hh h + +theorem add_exec (E : Env R) (i j : R) (hij : i≠j) (m n : ℕ) + (hm : E i=nat m) (hn : E j=nat n) : + Exec (add i j hij) (encodeEnv E) (encodeEnv (putPair E i j (nat (m+n)) .nil)) + (9*(m.bits.length+n.bits.length)+20) := by + let A:=m.bits + let B:=n.bits + let S:=StackAddition.addDigits false A B + have h₁:=on_left TreeBits.decodeForward E i j hij (TreeData.encode (bits A)) (TreeData.encode (bits B)) A _ + (TreeBits.decodeForward_exec A []) + have h₂:=on_right TreeBits.decodeForward E i j hij A (TreeData.encode (bits B)) B _ + (TreeBits.decodeForward_exec B []) + have h₃:=on_pair BinaryArithmeticProc.add E i j hij A B S [] _ (BinaryArithmeticProc.add_exec A B) + have h₄:=on_left BinaryNormalize.program E i j hij S [] (BinaryNormalize.normalize S) _ + (BinaryNormalize.exec S []) + have h₅:=on_left TreeBits.encodeForward E i j hij (BinaryNormalize.normalize S) [] + (TreeData.encode (bits (BinaryNormalize.normalize S))) _ (TreeBits.encodeForward_exec _ []) + have h₆ : Exec (atom (.push (.inl j) (fun _=>false) .halt)) + (rawPair E i j (TreeData.encode (bits (BinaryNormalize.normalize S))) []) + (rawPair E i j (TreeData.encode (bits (BinaryNormalize.normalize S))) [false]) 1 := by + apply exec_atom + simp only [TM2.stepAux,rawPair_right] + congr 1 + simp [rawPair] + have hh:=h₁.seq (h₂.seq (h₃.seq (h₄.seq (h₅.seq h₆)))) + have hS : BinaryNormalize.normalize S=(m+n).bits := by + rw [BinaryNormalize.normalize_bits,StackAddition.addition_numerals] + rw [hS] at hh + have hstart : rawPair E i j (TreeData.encode (bits A)) (TreeData.encode (bits B))=encodeEnv E := by + change rawPair E i j (TreeData.encode (nat m)) (TreeData.encode (nat n))=encodeEnv E + rw [←hm,←hn] + exact rawPair_same E i j + have hend : rawPair E i j (TreeData.encode (bits (m+n).bits)) [false]= + encodeEnv (putPair E i j (nat (m+n)) .nil) := rawPair_encode E i j (nat (m+n)) .nil + rw [hstart,hend] at hh + apply hh.mono + have hl:=StackAddition.addDigits_length A B false + have hl' := BinaryNormalize.normalize_length S + rw [hS] at hl' + dsimp only [A,B,S] at hl hl' ⊢ + omega +end MatchingFPRAS.TreeArithmetic + +end OAI diff --git a/lean/OAI/Combinatorics/MatchingCount/Arithmetic/TreeStateNormalize.lean b/lean/OAI/Combinatorics/MatchingCount/Arithmetic/TreeStateNormalize.lean new file mode 100644 index 0000000000000000000000000000000000000000..acf9659ef2d263ca4adcd58a0a90c43cc9698c30 --- /dev/null +++ b/lean/OAI/Combinatorics/MatchingCount/Arithmetic/TreeStateNormalize.lean @@ -0,0 +1,51 @@ +import Mathlib +import OAI.Combinatorics.MatchingCount.Machines.TreeReach +import OAI.Combinatorics.MatchingCount.Machines.TreeStateTable + +namespace OAI + +namespace MatchingFPRAS.ExecutableLadder +open TreeTyped Polynomial + +variable {I E : Type} [Codec I] [Codec E] [DecidableEq I] [Inhabited I] [LinearOrder E] +abbrev StateEnvelope (I E : Type) := List I×Finset E + +def normalizeState (x : StateEnvelope I E×StateTable I (Finset E)) : StateTable I (Finset E) := + x.1.1.map (fun i=>(i,lookup ∅ (x.2,i)∩x.1.2)) +def normalizeStateRealizer (Eq : Realizer (fun x : I×I=>decide (x.1=x.2))) + (EqE : Realizer (fun x : E×E=>decide (x.1=x.2))) : Realizer (normalizeState (I:=I) (E:=E)) := + (composition (pair identity first.fst) (mapWith (pair second + (composition (pair (composition (pair first.snd second) (lookupRealizer ∅ Eq)) first.fst.snd) + (finsetInter EqE))))).congr (fun _=>rfl) +lemma polynomial_normalizeState {Eq : Realizer (fun x : I×I=>decide (x.1=x.2))} + {EqE : Realizer (fun x : E×E=>decide (x.1=x.2))} + (hEq : PolynomialTime Eq) (hE : PolynomialTime EqE) : PolynomialTime (normalizeStateRealizer Eq EqE) := by + unfold normalizeStateRealizer Realizer.fst Realizer.snd + apply polynomial_congr + have := polynomial_lookup (∅ : Finset E) hEq + tree_cost + +omit [Inhabited I] in +lemma normalizeState_weight (keys : List I) (univ : Finset E) (s : StateTable I (Finset E)) : + weight (normalizeState ((keys,univ),s))≤(weight keys+1)*(weight univ+3) := by + induction keys with + | nil=>simp only [normalizeState,List.map_nil,weight_nil]; omega + | cons i keys ih=> + have hu : weight (lookup ∅ (s,i)∩univ)≤weight univ := weight_finset_subset Finset.inter_subset_right + change weight ((i,lookup ∅ (s,i)∩univ)::normalizeState ((keys,univ),s))≤_ + rw [weight_cons,weight_prod,weight_cons] + nlinarith + +omit [Codec I] [Codec E] [Inhabited I] in +lemma normalizeState_rep {Ω : Type} (keys : List I) (univ : Finset E) (e : Ω→Finset E) + (he : ∀ a,e a⊆univ) (s : I→Ω) : + normalizeState ((keys,univ),stateRep keys (e ∘ s))=stateRep keys (e ∘ s) := by + unfold normalizeState stateRep + apply List.map_congr_left + intro i hi + change (i,lookup ∅ (stateRep keys (e ∘ s),i)∩univ)=(i,e (s i)) + rw [lookup_stateRep ∅ keys (e ∘ s) i hi] + simp only [Function.comp_apply,Finset.inter_eq_left.mpr (he (s i))] +end MatchingFPRAS.ExecutableLadder + +end OAI diff --git a/lean/OAI/Combinatorics/MatchingCount/Arithmetic/TreeSubtract.lean b/lean/OAI/Combinatorics/MatchingCount/Arithmetic/TreeSubtract.lean new file mode 100644 index 0000000000000000000000000000000000000000..3a392e923d9fd8d5540e595cce5177a9d9c00b64 --- /dev/null +++ b/lean/OAI/Combinatorics/MatchingCount/Arithmetic/TreeSubtract.lean @@ -0,0 +1,66 @@ +import Mathlib +import OAI.Combinatorics.MatchingCount.Arithmetic.TreeNumberOps +import OAI.Combinatorics.MatchingCount.Arithmetic.SubtractProc + +namespace OAI + +namespace MatchingFPRAS.TreeArithmetic +open RegisterProc TreeData TreeMachine Turing + +variable {R : Type} [DecidableEq R] + +def sub (i j : R) (hij : i≠j) : Proc (K R) := + seq (decode i) (seq (decode j) + (seq (reindex BinaryArithmeticProc.sub (pairEmbedding i j hij)) + (seq (normalize i) (seq (encode i) (atom (.push (.inl j) (fun _=>false) .halt)))))) + +theorem sub_bits_exec (E : Env R) (i j : R) (hij : i≠j) (A B : List Bool) + (hm : E i=bits A) (hn : E j=bits B) (hle : StackAddition.value B≤StackAddition.value A) : + Exec (sub i j hij) (encodeEnv E) (encodeEnv (putPair E i j (nat (StackAddition.value A-StackAddition.value B)) .nil)) + (9*(A.length+B.length)+20) := by + let S:=(StackSubtract.subDigits false A B).2 + have h₁:=on_left TreeBits.decodeForward E i j hij (TreeData.encode (bits A)) (TreeData.encode (bits B)) A _ + (TreeBits.decodeForward_exec A []) + have h₂:=on_right TreeBits.decodeForward E i j hij A (TreeData.encode (bits B)) B _ + (TreeBits.decodeForward_exec B []) + have h₃:=on_pair BinaryArithmeticProc.sub E i j hij A B S [] _ (BinaryArithmeticProc.sub_exec A B) + have h₄:=on_left BinaryNormalize.program E i j hij S [] (BinaryNormalize.normalize S) _ + (BinaryNormalize.exec S []) + have h₅:=on_left TreeBits.encodeForward E i j hij (BinaryNormalize.normalize S) [] + (TreeData.encode (bits (BinaryNormalize.normalize S))) _ (TreeBits.encodeForward_exec _ []) + have h₆ : Exec (atom (.push (.inl j) (fun _=>false) .halt)) + (rawPair E i j (TreeData.encode (bits (BinaryNormalize.normalize S))) []) + (rawPair E i j (TreeData.encode (bits (BinaryNormalize.normalize S))) [false]) 1 := by + apply exec_atom + simp only [TM2.stepAux,rawPair_right] + congr 1 + simp [rawPair] + have hh:=h₁.seq (h₂.seq (h₃.seq (h₄.seq (h₅.seq h₆)))) + have hS : BinaryNormalize.normalize S=(StackAddition.value A-StackAddition.value B).bits := by + rw [BinaryNormalize.normalize_bits] + congr 1 + simpa only [Bool.toNat_false,Nat.add_zero,Nat.sub_zero] using + (StackSubtract.subDigits_correct A B false (by simpa using hle)).2 + rw [hS] at hh + have hstart : rawPair E i j (TreeData.encode (bits A)) (TreeData.encode (bits B))=encodeEnv E := by + rw [←hm,←hn] + exact rawPair_same E i j + have hend : rawPair E i j (TreeData.encode (bits (StackAddition.value A-StackAddition.value B).bits)) [false]= + encodeEnv (putPair E i j (nat (StackAddition.value A-StackAddition.value B)) .nil) := rawPair_encode E i j (nat (StackAddition.value A-StackAddition.value B)) .nil + rw [hstart,hend] at hh + apply hh.mono + have hl:=StackSubtract.subDigits_length A B false + have hl' := BinaryNormalize.normalize_length S + rw [hS] at hl' + dsimp only [S] at hl hl' ⊢ + omega + +lemma sub_exec (E : Env R) (i j : R) (hij : i≠j) (m n : ℕ) + (hi : E i=nat m) (hj : E j=nat n) (hle : n ≤ m) : + Exec (sub i j hij) (encodeEnv E) (encodeEnv (putPair E i j (nat (m-n)) .nil)) + (9*(m.bits.length+n.bits.length)+20) := by + simpa only [StackAddition.value_bits] using sub_bits_exec E i j hij m.bits n.bits hi hj + (by simpa only [StackAddition.value_bits] using hle) +end MatchingFPRAS.TreeArithmetic + +end OAI diff --git a/lean/OAI/Combinatorics/MatchingCount/Complexity/AlphabetCompilerCost.lean b/lean/OAI/Combinatorics/MatchingCount/Complexity/AlphabetCompilerCost.lean new file mode 100644 index 0000000000000000000000000000000000000000..224a5aa991e8da036aaf94d1ed0298ea2c7a3559 --- /dev/null +++ b/lean/OAI/Combinatorics/MatchingCount/Complexity/AlphabetCompilerCost.lean @@ -0,0 +1,95 @@ +import Mathlib +import OAI.Combinatorics.MatchingCount.Complexity.GuardMachineBase + +namespace OAI + +namespace MatchingFPRAS.AlphabetCost +open Turing Turing.TM1 Turing.TM1to1 MachineCost + +variable {Γ Λ σ : Type*} [Inhabited Γ] + +def writesCount : TM1.Stmt Γ Λ σ → ℕ + | .move _ q => writesCount q + | .write _ q => writesCount q+1 + | .load _ q => writesCount q + | .branch _ q r => max (writesCount q) (writesCount r) + | .goto _ => 0 + | .halt => 0 +variable {n : ℕ} (enc : Γ → List.Vector Bool n) (dec : List.Vector Bool n → Γ) + (enc0 : enc default = List.Vector.replicate n false) + (encdec : ∀ a,dec (enc a)=a) (M : Λ → TM1.Stmt Γ Λ σ) +include encdec + +theorem statement_time (q : TM1.Stmt Γ Λ σ) (v : σ) (L R : ListBlank Γ) : + ∃ t : ℕ, t≤writesCount q ∧ + MachineCost.run (TM1.step (tr enc dec M)) t + (stepAux (trNormal dec q) v (trTape' enc0 L R)) = + trCfg enc enc0 (stepAux q v (Tape.mk' L R)) := by + induction q generalizing v L R with + | move d q ih => + cases d <;> + simp only [trNormal,stepAux_move,stepAux,Tape.move_left_mk', + trTape'_move_left enc0,trTape'_move_right enc0,writesCount] <;> + apply ih + | write f q ih => + simp only [trNormal,stepAux_read dec enc0 encdec,stepAux,writesCount] + obtain ⟨a,R,rfl⟩:=R.exists_cons + obtain ⟨t,ht,he⟩:=ih v L (R.cons (f a v)) + refine ⟨t+1,by omega,?_⟩ + rw [MachineCost.run] + simp only [advance,TM1.step,tr,Option.getD_some,Tape.mk'_head, + ListBlank.head_cons] + rw [stepAux_write enc0,stepAux_move,trTape'_move_left enc0] + simpa using he + | load f q ih => + simp only [trNormal,stepAux_read dec enc0 encdec,stepAux,writesCount] + exact ih _ _ _ + | branch p q r ihq ihr => + simp only [trNormal,stepAux_read dec enc0 encdec,stepAux,Tape.mk'_head,writesCount] + cases h:p R.head v + · simp only [Bool.cond_false] + obtain ⟨t,ht,he⟩:=ihr v L R + exact ⟨t,ht.trans (le_max_right _ _),he⟩ + · simp only [Bool.cond_true] + obtain ⟨t,ht,he⟩:=ihq v L R + exact ⟨t,ht.trans (le_max_left _ _),he⟩ + | goto l => + refine ⟨0,le_rfl,?_⟩ + simp only [trNormal,stepAux_read dec enc0 encdec,stepAux,trCfg,trTape_mk', + MachineCost.run,Tape.mk'_head,Option.map_some] + | halt => + refine ⟨0,le_rfl,?_⟩ + simp only [trNormal,stepAux,trCfg,trTape_mk',MachineCost.run,Option.map_none] + +lemma one_step_time (W : ℕ) (hW : ∀ l,writesCount (M l)≤W) (c : TM1.Cfg Γ Λ σ) : + ∃ t : ℕ,t≤W+1 ∧ + MachineCost.run (TM1.step (tr enc dec M)) t (trCfg enc enc0 c)= + trCfg enc enc0 (advance (TM1.step M) c) := by + rcases c with ⟨l,v,T⟩ + obtain ⟨L,R,rfl⟩:=T.exists_mk' + cases l with + | none => exact ⟨0,Nat.zero_le _,rfl⟩ + | some l => + obtain ⟨t,ht,he⟩:=statement_time enc dec enc0 encdec M (M l) v L R + refine ⟨t+1,by have:=hW l;omega,?_⟩ + simpa only [MachineCost.run,advance,TM1.step,Option.map_some,trCfg,tr, + Option.getD_some,trTape_mk'] using he + +theorem execution_time (W : ℕ) (hW : ∀ l,writesCount (M l)≤W) + (c : TM1.Cfg Γ Λ σ) (k : ℕ) : + ∃ t : ℕ,t≤k*(W+1) ∧ + MachineCost.run (TM1.step (tr enc dec M)) t (trCfg enc enc0 c)= + trCfg enc enc0 (MachineCost.run (TM1.step M) k c) := by + induction k generalizing c with + | zero => exact ⟨0,by simp,rfl⟩ + | succ k ih => + obtain ⟨t₁,ht₁,he₁⟩:=one_step_time enc dec enc0 encdec M W hW c + obtain ⟨t₂,ht₂,he₂⟩:=ih (advance (TM1.step M) c) + refine ⟨t₁+t₂,?_,?_⟩ + · calc + t₁+t₂≤(W+1)+k*(W+1) := Nat.add_le_add ht₁ ht₂ + _=(k+1)*(W+1) := by ring + · rw [run_add,he₁,he₂]; rfl +end MatchingFPRAS.AlphabetCost + +end OAI diff --git a/lean/OAI/Combinatorics/MatchingCount/Complexity/ComputeCost.lean b/lean/OAI/Combinatorics/MatchingCount/Complexity/ComputeCost.lean new file mode 100644 index 0000000000000000000000000000000000000000..81c06ae01ece07e75987887df19f349f9adc07ad --- /dev/null +++ b/lean/OAI/Combinatorics/MatchingCount/Complexity/ComputeCost.lean @@ -0,0 +1,103 @@ +import Mathlib +import OAI.Combinatorics.MatchingCount.Complexity.OnlineInitialDataCost +import OAI.Combinatorics.MatchingCount.Algorithm.Algorithm +import OAI.Combinatorics.MatchingCount.Complexity.OnlineRunCost +import OAI.Combinatorics.MatchingCount.Machines.OnlineBounds + +namespace OAI + +namespace MatchingFPRAS.LiteralAlgorithm +open TreeTyped TreeFraction PhysicalStream Polynomial OnlineSourceBounds LiteralInput + +lemma initialize_materialize {G : GraphInput} [Nontrivial (Fin G.n)] + (hn : 2≤G.n) (hev : Even G.n) (ε δ : ℚ) (he : 0<ε) (he1 : ε<1) (hd : 0≤δ) : + OnlineInitial.initializeInput (materialize (parseInput (encodeInput G ε δ)))= + (2*Amplification.halfRepetitions δ+1, + OnlineTrial.initial (reorder G) (FiniteTrial.parameters G hn hev ε he he1)) := by + rw [materialize_source,OnlineGraph.initialize_eq, + OnlineInitial.initializeInput_source hn hev ε δ he he1 hd] + rfl +lemma numeric_materialize (G : GraphInput) (ε δ : ℚ) : + OnlineInitial.configNumeric (OnlineInitial.config (materialize (parseInput (encodeInput G ε δ))))= + OnlineInitial.configNumeric (OnlineInitial.config (OnlineInitial.sourceSeed (G:=G) ε δ)) := by + rw [materialize_source] + rfl +lemma materialize_vertices (G : GraphInput) (ε δ : ℚ) : + (materialize (parseInput (encodeInput G ε δ))).1.1.length=G.n := by + rw [LiteralInput.parseInput_source];simp only [materialize,List.length_range] +lemma materialize_epsilon (G : GraphInput) (ε δ : ℚ) : + (materialize (parseInput (encodeInput G ε δ))).2.1=TreeFraction.repr ε := by + rw [LiteralInput.parseInput_source];rfl +lemma graph_weight_materialize (G : GraphInput) (ε δ : ℚ) : + weight (OnlineGraph.graph (reorder G) (ExecutableAdaptive.graphRep G))≤ + weight (materialize (parseInput (encodeInput G ε δ))) := by + rw [materialize_source] + change weight _≤weight (OnlineGraph.graph (reorder G) (ExecutableAdaptive.graphRep G),_) + rw [weight_prod (OnlineGraph.graph (reorder G) (ExecutableAdaptive.graphRep G))] + omega + +lemma compute_cost (a : Parsed) : computeRealizer.cost a= + materializeRealizer.cost a+OnlineInitial.initializeInputRealizer.cost (materialize a)+ + OnlineAmplification.runRealizer.cost (OnlineInitial.initializeInput (materialize a)) := rfl + +lemma compute_bound : ∃ q : Polynomial ℕ,∀ (G : GraphInput) [Nontrivial (Fin G.n)] + (_hn : 2≤G.n) (_hev : Even G.n) (ε δ : ℚ) (_he : 0<ε) (_he1 : ε<1) (_hd : 0≤δ) + (x : ℕ),1≤x→G.n≤x→⌈ε⁻¹⌉₊≤x→Nat.clog 2 ⌈δ⁻¹⌉₊≤x→ + weight (parseInput (encodeInput G ε δ))≤x→ + computeRealizer.cost (parseInput (encodeInput G ε δ))+ + (compute (parseInput (encodeInput G ε δ))).worst weight≤q.eval x := by + obtain ⟨m,hm⟩:=work_materialize + obtain ⟨i,hi⟩:=OnlineInitial.work_initializeInput + obtain ⟨r,hr⟩:=OnlineAmplification.run_bound + obtain ⟨b,hb⟩:=polynomial_bound normBound_polynomial + let M:=m.comp (2*X) + let S:Polynomial ℕ:=2*X+b+M + let R:Polynomial ℕ:=11*X+11+b+M + refine ⟨M+i.comp S+r.comp R,?_⟩ + intro G inst hn hev ε δ he he1 hd x hx hnx hex hdx hwx + let a:=parseInput (encodeInput G ε δ) + let seed:=materialize a + let p:=FiniteTrial.parameters G hn hev ε he he1 + have hn2:G.n≤2*x := by omega + have ha:a.1=G.n := by dsimp only [a];rw [LiteralInput.parseInput_source] + have hmat:materializeRealizer.cost a+weight seed≤M.eval x := by + apply (hm a).trans + apply (polynomial_eval_monotone m (show a.1+weight a≤2*x by dsimp only [a] at *;omega)).trans + simp only [M,Polynomial.eval_comp,Polynomial.eval_mul,Polynomial.eval_ofNat,Polynomial.eval_X];rfl + have hseed:OnlineInitial.seedSize seed≤S.eval x := by + have hnum:OnlineInitial.configNumeric (OnlineInitial.config seed)≤b.eval x := by + dsimp only [seed,a] + rw [numeric_materialize] + exact (numeric_le hn hev ε δ he he1 x hn2 hex).trans (hb x hx) + have hlen:(seed.1.1).length=G.n:=materialize_vertices G ε δ + have hep:natCeil (inverse seed.2.1)=⌈ε⁻¹⌉₊ := by + rw [show seed.2.1=TreeFraction.repr ε from materialize_epsilon G ε δ,inverse_repr ε he.le,natCeil_repr _ (inv_nonneg.mpr he.le)] + simp only [OnlineInitial.seedSize,hlen,hep,S,Polynomial.eval_add,Polynomial.eval_mul, + Polynomial.eval_ofNat,Polynomial.eval_X] + omega + have hini:OnlineInitial.initializeInputRealizer.cost seed ≤ i.eval (S.eval x) := + (Nat.le_trans (Nat.le_add_right _ _) (hi seed)).trans (polynomial_eval_monotone i hseed) + have hnorm:OnlineTrial.sizeNorm p (OnlineGraph.graph (reorder G) (ExecutableAdaptive.graphRep G))≤b.eval x+M.eval x := by + apply (norm_le hn hev ε he he1 x hn2 hex _).trans + have hg:=graph_weight_materialize G ε δ + have hnb:=hb x hx + dsimp only [seed,a] at hmat + omega + have hrep:2*Amplification.halfRepetitions δ+1≤10*x+11:=by + rw [Amplification.repetitions_source];omega + have harg:2*Amplification.halfRepetitions δ+1+ + OnlineTrial.sizeNorm p (OnlineGraph.graph (reorder G) (ExecutableAdaptive.graphRep G))≤R.eval x := by + simp only [R,Polynomial.eval_add,Polynomial.eval_mul,Polynomial.eval_ofNat,Polynomial.eval_X] + omega + have hrun:= (hr G (reorder G) (reorder_mem G) p (2*Amplification.halfRepetitions δ+1)).trans + (polynomial_eval_monotone r harg) + have hinput:=initialize_materialize hn hev ε δ he he1 hd + rw [compute_cost] + unfold compute + rw [hinput] + simp only [Polynomial.eval_add,Polynomial.eval_comp] + dsimp only [a,seed,p] at hini hmat hrun + omega +end MatchingFPRAS.LiteralAlgorithm + +end OAI diff --git a/lean/OAI/Combinatorics/MatchingCount/Complexity/GuardMachineBase.lean b/lean/OAI/Combinatorics/MatchingCount/Complexity/GuardMachineBase.lean new file mode 100644 index 0000000000000000000000000000000000000000..e37411d50e09017843b196269ec15c6054109f20 --- /dev/null +++ b/lean/OAI/Combinatorics/MatchingCount/Complexity/GuardMachineBase.lean @@ -0,0 +1,416 @@ +import Mathlib +import OAI.Combinatorics.MatchingCount.Model + +namespace OAI + +namespace MatchingFPRAS.MachineCost +open Turing + +def advance {α : Type*} (f : α → Option α) (x : α) : α := (f x).getD x +def run {α : Type*} (f : α → Option α) : ℕ → α → α + | 0,x => x + | n+1,x => run f n (advance f x) + +lemma run_add {α : Type*} (f : α → Option α) (n m : ℕ) (x : α) : + run f (n+m) x=run f m (run f n x) := by + induction n generalizing x with + | zero => simp only [Nat.zero_add,run] + | succ n ih => simpa only [Nat.succ_add,run] using ih (advance f x) + +lemma run_step_eq {α : Type*} (f : α → Option α) {x y : α} + (h : advance f x=advance f y) {n : ℕ} (hn : 0 omega + | succ n => simp only [run,h] + +def statementCost {Γ Λ σ : Type*} : TM1.Stmt Γ Λ σ → ℕ + | .move _ q => statementCost q+1 + | .write _ q => statementCost q+1 + | .load _ q => statementCost q + | .branch _ q r => max (statementCost q) (statementCost r) + | .goto _ => 1 + | .halt => 1 +lemma statementCost_pos {Γ Λ σ : Type*} (q : TM1.Stmt Γ Λ σ) : 0 simp only [statementCost]; omega + | write _ q ih => simp only [statementCost]; omega + | load _ q ih => exact ih + | branch _ q r ihq ihr => exact lt_of_lt_of_le ihq (le_max_left _ _) + | goto _ => exact Nat.zero_lt_one + | halt => exact Nat.zero_lt_one + +variable {Γ Λ σ : Type*} [Inhabited Γ] [Inhabited Λ] [Inhabited σ] +variable (M : Λ → TM1.Stmt Γ Λ σ) + +theorem statement_translation_time (q : TM1.Stmt Γ Λ σ) (v : σ) (T : Tape Γ) : + ∃ k, 0 < k ∧ k ≤ statementCost q ∧ + run (TM0.step (TM1to0.tr M)) k ⟨(some q,v),T⟩ = + TM1to0.trCfg M (TM1.stepAux q v T) := by + induction q generalizing v T with + | move d q ih => + obtain ⟨k,hk,hc,he⟩ := ih v (T.move d) + refine ⟨k+1,by omega,by simpa only [statementCost] using Nat.add_le_add_right hc 1,?_⟩ + simpa only [run,advance,TM0.step,TM1to0.tr,TM1to0.trAux,Option.map_some, + Option.getD_some,TM1.stepAux] using he + | write a q ih => + obtain ⟨k,hk,hc,he⟩ := ih v (T.write (a T.head v)) + refine ⟨k+1,by omega,by simpa only [statementCost] using Nat.add_le_add_right hc 1,?_⟩ + simpa only [run,advance,TM0.step,TM1to0.tr,TM1to0.trAux,Option.map_some, + Option.getD_some,TM1.stepAux] using he + | load a q ih => + obtain ⟨k,hk,hc,he⟩ := ih (a T.head v) T + refine ⟨k,hk,hc,?_⟩ + rw [run_step_eq (TM0.step (TM1to0.tr M)) (x:=⟨(some (.load a q),v),T⟩) + (y:=⟨(some q,a T.head v),T⟩) rfl hk] + exact he + | branch p q r ihq ihr => + cases hp : p T.head v with + | false => + obtain ⟨k,hk,hc,he⟩ := ihr v T + refine ⟨k,hk,hc.trans (le_max_right _ _),?_⟩ + have hs : advance (TM0.step (TM1to0.tr M)) ⟨(some (.branch p q r),v),T⟩ = + advance (TM0.step (TM1to0.tr M)) ⟨(some r,v),T⟩ := by + simp only [advance,TM0.step,TM1to0.tr,TM1to0.trAux,hp,Bool.cond_false,Option.map_some,Option.getD_some] + rw [run_step_eq _ hs hk] + simpa only [TM1.stepAux,hp,Bool.cond_false] using he + | true => + obtain ⟨k,hk,hc,he⟩ := ihq v T + refine ⟨k,hk,hc.trans (le_max_left _ _),?_⟩ + have hs : advance (TM0.step (TM1to0.tr M)) ⟨(some (.branch p q r),v),T⟩ = + advance (TM0.step (TM1to0.tr M)) ⟨(some q,v),T⟩ := by + simp only [advance,TM0.step,TM1to0.tr,TM1to0.trAux,hp,Bool.cond_true,Option.map_some,Option.getD_some] + rw [run_step_eq _ hs hk] + simpa only [TM1.stepAux,hp,Bool.cond_true] using he + | goto l => + refine ⟨1,by decide,le_rfl,?_⟩ + simp only [run,advance,TM0.step,TM1to0.tr,TM1to0.trAux,Option.map_some, + Option.getD_some,TM1.stepAux,TM1to0.trCfg,Tape.write_self] + | halt => + refine ⟨1,by decide,le_rfl,?_⟩ + simp only [run,advance,TM0.step,TM1to0.tr,TM1to0.trAux,Option.map_some, + Option.getD_some,TM1.stepAux,TM1to0.trCfg,Tape.write_self,Option.map_none] + +noncomputable def programCost [Fintype Λ] : ℕ := Finset.univ.sup (fun l=>statementCost (M l)) +omit [Inhabited Γ] [Inhabited Λ] [Inhabited σ] in +lemma statementCost_le_programCost [Fintype Λ] (l : Λ) : + statementCost (M l)≤programCost M := Finset.le_sup (f:=fun l=>statementCost (M l)) (Finset.mem_univ l) +omit [Inhabited Γ] [Inhabited σ] in +lemma programCost_pos [Fintype Λ] : 0 exact ⟨0,by omega,rfl⟩ + | succ n ih => + rcases c with ⟨l,v,T⟩ + cases l with + | none => + have he : run (TM1.step M) (n+1) ⟨none,v,T⟩=⟨none,v,T⟩ := by + have h : ∀ k, run (TM1.step M) k ⟨none,v,T⟩=⟨none,v,T⟩ := by + intro k; induction k with + | zero => simp only [run] + | succ k ihk => simpa only [run,advance,TM1.step,Option.getD_none] using ihk + exact h _ + exact ⟨0,by omega,by rw [run,he]⟩ + | some l => + obtain ⟨j,hj,hjc,hje⟩ := statement_translation_time M (M l) v T + obtain ⟨k,hk,hke⟩ := ih (TM1.stepAux (M l) v T) + refine ⟨j+k,?_,?_⟩ + · have := hjc.trans (statementCost_le_programCost M l) + simpa only [Nat.mul_succ] using Nat.add_le_add this hk |>.trans_eq (Nat.add_comm _ _) + · rw [run_add] + change run (TM0.step (TM1to0.tr M)) k + (run (TM0.step (TM1to0.tr M)) j ⟨(some (M l),v),T⟩)=_ + rw [hje,hke] + rfl +end MatchingFPRAS.MachineCost + +namespace MatchingFPRAS.PostCompiler +open Turing MachineCost +open scoped Classical + +variable {Λ : Type*} [Inhabited Λ] +variable (M : Λ → Symbol → Option (Λ × TM0.Stmt Symbol)) (S : Finset Λ) (hS : TM0.Supports M (S : Set Λ)) + +noncomputable def index : S ≃ Fin S.card := Fintype.equivFinOfCardEq (by simp) +noncomputable def pack (q : S) : Fin (S.card+1) := (index S q).succ +noncomputable def unpack (i : Fin (S.card+1)) : S := + if h : i.val=0 then ⟨default,hS.1⟩ else + (index S).symm ⟨i.val-1,by have := i.isLt; omega⟩ +lemma unpack_pack (q : S) : unpack M S hS (pack S q)=q := by + simp [unpack,pack] +omit [Inhabited Λ] in +lemma pack_ne_zero (q : S) : pack S q≠0 := by simp [pack] + +noncomputable def packState (q : Λ) : Fin (S.card+1) := + if h : q∈S then pack S ⟨q,h⟩ else 0 +omit [Inhabited Λ] in +lemma packState_of_mem (q : Λ) (hq : q∈S) : packState S q=pack S ⟨q,hq⟩ := by + simp [packState,hq] + +noncomputable def sealedMachine : RandomMachine where + states := S.card + transition i a _ := if i=0 then some (pack S ⟨default,hS.1⟩,.write a) else + (M (unpack M S hS i).val a).map (fun (q,s)=>(packState S q,s)) + +abbrev Phase (Λ : Type*) := TM0.Cfg Symbol Λ × Bool + +def perform (s : TM0.Stmt Symbol) (T : Tape Symbol) : Tape Symbol := match s with + | .move d => T.move d + | .write a => T.write a + +noncomputable def phaseStep (x : Phase Λ) : Phase Λ := + if x.2 then + match M x.1.q x.1.Tape.head with + | none => (x.1,false) + | some (q,s) => (⟨q,perform s x.1.Tape⟩,true) + else x + +def well (x : Phase Λ) : Prop := x.1.q∈S ∧ (x.2=false → TM0.step M x.1=none) +noncomputable def embed (x : Phase Λ) : Configuration (sealedMachine M S hS) := + ⟨if x.2 then some (packState S x.1.q) else none,x.1.Tape⟩ + +include hS + +lemma phaseStep_well (x : Phase Λ) (hx : well M S x) : well M S (phaseStep M x) := by + rcases x with ⟨⟨q,T⟩,b⟩ + cases b with + | false => exact hx + | true => + cases he : M q T.head with + | none => simpa [well,phaseStep,he,TM0.step] using hx.1 + | some ys => + rcases ys with ⟨y,s⟩ + simpa [well,phaseStep,he] using hS.2 he hx.1 + +omit hS in +lemma phaseStep_first (_hS : TM0.Supports M (S : Set Λ)) (x : Phase Λ) (hx : well M S x) : + (phaseStep M x).1=advance (TM0.step M) x.1 := by + rcases x with ⟨⟨q,T⟩,b⟩ + cases b with + | false => simp [phaseStep,advance,hx.2 rfl] + | true => + cases he : M q T.head with + | none => simp [phaseStep,advance,TM0.step,he] + | some ys => rcases ys with ⟨y,s⟩; cases s <;> simp [phaseStep,advance,TM0.step,he,perform] + +lemma embed_step (x : Phase Λ) (hx : well M S x) (b : Bool) : + tick (sealedMachine M S hS) (embed M S hS x) b=embed M S hS (phaseStep M x) := by + rcases x with ⟨⟨q,T⟩,live⟩ + cases live with + | false => rfl + | true => + have hp := pack_ne_zero S (⟨q,hx.1⟩ : S) + cases he : M q T.head with + | none => simp [embed,tick,sealedMachine,phaseStep,packState_of_mem S q hx.1,hp,unpack_pack,he] + | some ys => + rcases ys with ⟨y,s⟩ + cases s <;> simp [embed,tick,sealedMachine,phaseStep,packState_of_mem S q hx.1,hp,unpack_pack,he,perform] + +lemma phaseRun (n : ℕ) (x : Phase Λ) (hx : well M S x) : + well M S ((phaseStep M)^[n] x) ∧ + ((phaseStep M)^[n] x).1=MachineCost.run (TM0.step M) n x.1 := by + induction n generalizing x with + | zero => exact ⟨hx,rfl⟩ + | succ n ih => + have h := ih (phaseStep M x) (phaseStep_well M S hS x hx) + rw [Function.iterate_succ_apply] + exact ⟨h.1,by rw [h.2,phaseStep_first M S hS x hx]; rfl⟩ + +lemma phaseRun_stops (n : ℕ) (x : Phase Λ) (hx : well M S x) + (hh : TM0.step M (MachineCost.run (TM0.step M) n x.1)=none) : + ((phaseStep M)^[n+1] x).2=false ∧ + ((phaseStep M)^[n+1] x).1=MachineCost.run (TM0.step M) n x.1 := by + obtain ⟨hw,he⟩ := phaseRun M S hS n x hx + rw [Function.iterate_succ_apply'] + rw [←he] at hh ⊢ + generalize (phaseStep M)^[n] x=y at * + rcases y with ⟨⟨q,T⟩,live⟩ + have hq0 : M q T.head=none := Option.map_eq_none_iff.mp hh + cases live <;> simp [phaseStep,hq0] + +lemma embed_fold (bits : List Bool) (x : Phase Λ) (hx : well M S x) : + bits.foldl (tick (sealedMachine M S hS)) (embed M S hS x)= + embed M S hS ((phaseStep M)^[bits.length] x) := by + induction bits generalizing x with + | nil => rfl + | cons b bits ih => + rw [List.foldl_cons,embed_step M S hS x hx,ih _ (phaseStep_well M S hS x hx), + List.length_cons,Function.iterate_succ_apply] + +lemma entry (a : Symbol) (b : Bool) : + (sealedMachine M S hS).transition 0 a b=some (pack S ⟨default,hS.1⟩,.write a) := by + dsimp only [sealedMachine] + split + · rfl + · rename_i h; exact False.elim (h rfl) + +lemma initial_tick (input : List Symbol) (b : Bool) : + tick (sealedMachine M S hS) (initial (sealedMachine M S hS) input) b= + embed M S hS (TM0.init input,true) := by + simp only [tick,initial,entry,Tape.write_self,embed,TM0.init,packState_of_mem S default hS.1, + ↓reduceIte] + +omit hS in +lemma halted_tick (A : RandomMachine) (c : Configuration A) (h : c.state=none) (b : Bool) : tick A c b=c := by + rcases c with ⟨s,T⟩ + change s=none at h + subst s + rfl +omit hS in +lemma halted_fold (A : RandomMachine) (c : Configuration A) (h : c.state=none) (bits : List Bool) : + bits.foldl (tick A) c=c := by + induction bits with + | nil => rfl + | cons b bits ih => rw [List.foldl_cons,halted_tick A c h b,ih] + +theorem seal_words (input output : List Symbol) (n : ℕ) + (hhalt : TM0.step M (MachineCost.run (TM0.step M) n (TM0.init input))=none) + (hout : (MachineCost.run (TM0.step M) n (TM0.init input)).Tape.right₀= + ListBlank.mk output) (bits : Fin (n+2) → Bool) : + (MatchingFPRAS.run (sealedMachine M S hS) input bits).state=none ∧ + (MatchingFPRAS.run (sealedMachine M S hS) input bits).tape.right₀=ListBlank.mk output := by + let x : Phase Λ := (TM0.init input,true) + have hx : well M S x := ⟨hS.1,by intro h; cases h⟩ + obtain ⟨hs,he⟩ := phaseRun_stops M S hS n x hx hhalt + have hr : MatchingFPRAS.run (sealedMachine M S hS) input bits=embed M S hS ((phaseStep M)^[n+1] x) := by + unfold MatchingFPRAS.run + rw [List.ofFn_succ,List.foldl_cons,initial_tick,embed_fold M S hS _ x hx,List.length_ofFn] + constructor + · rw [hr] + simp only [embed,hs,Bool.false_eq_true,↓reduceIte] + · rw [hr] + change ((phaseStep M)^[n+1] x).1.Tape.right₀=_ + rw [he] + exact hout + +theorem seal_outputs (input : List Symbol) (n : ℕ) (q : ℚ) + (hhalt : TM0.step M (MachineCost.run (TM0.step M) n (TM0.init input))=none) + (hout : (MachineCost.run (TM0.step M) n (TM0.init input)).Tape.right₀= + ListBlank.mk (encodeRat q)) (bits : Fin (n+2) → Bool) : + Outputs (sealedMachine M S hS) input bits q := by + let x : Phase Λ := (TM0.init input,true) + have hx : well M S x := ⟨hS.1,by intro h; cases h⟩ + obtain ⟨hs,he⟩ := phaseRun_stops M S hS n x hx hhalt + have hr : MatchingFPRAS.run (sealedMachine M S hS) input bits=embed M S hS ((phaseStep M)^[n+1] x) := by + unfold MatchingFPRAS.run + rw [List.ofFn_succ,List.foldl_cons,initial_tick,embed_fold M S hS _ x hx,List.length_ofFn] + constructor + · rw [hr] + simp only [embed,hs,Bool.false_eq_true,↓reduceIte] + · rw [hr] + change ((phaseStep M)^[n+1] x).1.Tape.right₀=_ + rw [he] + exact hout + +omit hS + +open Turing MachineCost +open scoped Classical + +theorem outputs_extend (A : RandomMachine) (input : List Symbol) (q : ℚ) + {n t : ℕ} (hnt : n ≤ t) (bits : Fin t → Bool) + (h : Outputs A input (fun i : Fin n=>bits (Fin.castLE hnt i)) q) : + Outputs A input bits q := by + obtain ⟨m,rfl⟩ := Nat.exists_eq_add_of_le hnt + have hr : MatchingFPRAS.run A input bits= + MatchingFPRAS.run A input (fun i : Fin n=>bits (Fin.castLE hnt i)) := by + unfold MatchingFPRAS.run + rw [List.ofFn_add,List.foldl_append] + exact halted_fold A _ h.1 _ + constructor + · rw [hr]; exact h.1 + · rw [hr]; exact h.2 + +theorem words_extend (A : RandomMachine) (input output : List Symbol) + {n t : ℕ} (hnt : n ≤ t) (bits : Fin t → Bool) + (h : (MatchingFPRAS.run A input (fun i : Fin n=>bits (Fin.castLE hnt i))).state=none ∧ + (MatchingFPRAS.run A input (fun i : Fin n=>bits (Fin.castLE hnt i))).tape.right₀=ListBlank.mk output) : + (MatchingFPRAS.run A input bits).state=none ∧ + (MatchingFPRAS.run A input bits).tape.right₀=ListBlank.mk output := by + obtain ⟨m,rfl⟩ := Nat.exists_eq_add_of_le hnt + have hr : MatchingFPRAS.run A input bits= + MatchingFPRAS.run A input (fun i : Fin n=>bits (Fin.castLE hnt i)) := by + unfold MatchingFPRAS.run + rw [List.ofFn_add,List.foldl_append] + exact halted_fold A _ h.1 _ + rw [hr] + exact h + +variable {Λ σ : Type*} [Inhabited Λ] [Inhabited σ] [Fintype Λ] [Fintype σ] +variable (M : Λ → TM1.Stmt Symbol Λ σ) + +omit [Inhabited σ] [Fintype σ] in +lemma finite_supported : TM1.Supports M Finset.univ := by + constructor + · exact Finset.mem_univ _ + · intro l hl + induction M l with + | move _ q ih => exact ih + | write _ q ih => exact ih + | load _ q ih => exact ih + | branch _ q r ihq ihr => exact ⟨ihq,ihr⟩ + | goto _ => exact fun _ _=>Finset.mem_univ _ + | halt => trivial + +noncomputable def compiled : RandomMachine := + sealedMachine (TM1to0.tr M) (TM1to0.trStmts M Finset.univ) + (TM1to0.tr_supports M (finite_supported M)) + +theorem compiled_outputs (input : List Symbol) (n t : ℕ) (q : ℚ) + (hhalt : (MachineCost.run (TM1.step M) n (TM1.init input)).l=none) + (hout : (MachineCost.run (TM1.step M) n (TM1.init input)).Tape.right₀= + ListBlank.mk (encodeRat q)) + (ht : programCost M*n+2 ≤ t) (bits : Fin t → Bool) : Outputs (compiled M) input bits q := by + obtain ⟨k,hk,he⟩ := run_translation_time M n (TM1.init input) + have hi : TM1to0.trCfg M (TM1.init input)=TM0.init input := rfl + rw [hi] at he + have hh : TM0.step (TM1to0.tr M) + (MachineCost.run (TM0.step (TM1to0.tr M)) k (TM0.init input))=none := by + rw [he] + generalize hc : MachineCost.run (TM1.step M) n (TM1.init input)=c at hhalt ⊢ + rcases c with ⟨l,v,T⟩ + change l=none at hhalt + subst l + rfl + have ho : (MachineCost.run (TM0.step (TM1to0.tr M)) k (TM0.init input)).Tape.right₀= + ListBlank.mk (encodeRat q) := by + rw [he] + exact hout + have hkt : k+2 ≤ t := (Nat.add_le_add_right hk 2).trans ht + exact outputs_extend (compiled M) input q hkt bits + (seal_outputs (TM1to0.tr M) (TM1to0.trStmts M Finset.univ) + (TM1to0.tr_supports M (finite_supported M)) input k q hh ho _) + +theorem compiled_words (input output : List Symbol) (n t : ℕ) + (hhalt : (MachineCost.run (TM1.step M) n (TM1.init input)).l=none) + (hout : (MachineCost.run (TM1.step M) n (TM1.init input)).Tape.right₀= + ListBlank.mk output) + (ht : programCost M*n+2 ≤ t) (bits : Fin t → Bool) : + (MatchingFPRAS.run (compiled M) input bits).state=none ∧ + (MatchingFPRAS.run (compiled M) input bits).tape.right₀=ListBlank.mk output := by + obtain ⟨k,hk,he⟩ := run_translation_time M n (TM1.init input) + have hi : TM1to0.trCfg M (TM1.init input)=TM0.init input := rfl + rw [hi] at he + have hh : TM0.step (TM1to0.tr M) + (MachineCost.run (TM0.step (TM1to0.tr M)) k (TM0.init input))=none := by + rw [he] + generalize hc : MachineCost.run (TM1.step M) n (TM1.init input)=c at hhalt ⊢ + rcases c with ⟨l,v,T⟩ + change l=none at hhalt + subst l + rfl + have ho : (MachineCost.run (TM0.step (TM1to0.tr M)) k (TM0.init input)).Tape.right₀= + ListBlank.mk output := by + rw [he] + exact hout + have hkt : k+2 ≤ t := (Nat.add_le_add_right hk 2).trans ht + exact words_extend (compiled M) input output hkt bits + (seal_words (TM1to0.tr M) (TM1to0.trStmts M Finset.univ) + (TM1to0.tr_supports M (finite_supported M)) input output k hh ho _) +end MatchingFPRAS.PostCompiler + +end OAI diff --git a/lean/OAI/Combinatorics/MatchingCount/Complexity/OnlineCost.lean b/lean/OAI/Combinatorics/MatchingCount/Complexity/OnlineCost.lean new file mode 100644 index 0000000000000000000000000000000000000000..24c4f23f278125218e683ea2f789d666b7c504b5 --- /dev/null +++ b/lean/OAI/Combinatorics/MatchingCount/Complexity/OnlineCost.lean @@ -0,0 +1,92 @@ +import Mathlib +import OAI.Combinatorics.MatchingCount.Complexity.TreeCostMeasure +import OAI.Combinatorics.MatchingCount.Machines.OnlineTree + +namespace OAI + +namespace MatchingFPRAS.PhysicalStream.Experiment +variable {A B : Type} +lemma worst_mono (p : Experiment A) (f g : A→ℕ) (h : p.All (fun a=>f a≤g a)) : + p.worst f≤p.worst g := by + induction p with + | done a => exact h + | read p ih => exact max_le_max (ih false h.1) (ih true h.2) + | delay n p ih => exact ih h +lemma All.and {p : Experiment A} {P Q : A→Prop} (hp : p.All P) (hq : p.All Q) : + p.All (fun a=>P a ∧ Q a) := by + induction p with + | done a => exact ⟨hp,hq⟩ + | read p ih => exact ⟨ih false hp.1 hq.1,ih true hp.2 hq.2⟩ + | delay n p ih => exact ih hp hq +lemma worst_const (p : Experiment A) (n : ℕ) : p.worst (fun _=>n)=n := by + induction p with + | done a => rfl + | read p ih => simp only [worst,ih, max_self] + | delay n p ih => exact ih +lemma worst_bind (p : Experiment A) (f : A→Experiment B) (h : B→ℕ) : + (p.bind f).worst h=p.worst (fun a=>(f a).worst h) := by + induction p with + | done a => rfl + | read p ih => simp only [bind,worst,ih] + | delay n p ih => exact ih +lemma worst_map (p : Experiment A) (f : A→B) (h : B→ℕ) : + (p.map f).worst h=p.worst (h ∘ f) := worst_bind _ _ _ +lemma worst_eq_of_mean_eq {p q : Experiment A} (h : ∀ f : A→ℚ,p.mean f=q.mean f) (g : A→ℕ) : + p.worst g=q.worst g := by + apply Nat.le_antisymm + · exact worst_le _ _ _ (all_of_mean_eq h _ (all_worst q g)) + · exact worst_le _ _ _ (all_of_mean_eq (fun f=>(h f).symm) _ (all_worst p g)) +end MatchingFPRAS.PhysicalStream.Experiment + +namespace MatchingFPRAS.OnlineTree +open TreeTyped PhysicalStream Polynomial + +variable {A B C : Type} [Codec A] [Codec B] [Codec C] +def WorkBound {f : A→Experiment B} (F : Realizer f) (measure : A→ℕ) : Prop := + ∃ p : Polynomial ℕ,∀ a,F.cost a+(f a).worst weight≤p.eval (measure a) +abbrev PolynomialTime {f : A→Experiment B} (F : Realizer f) : Prop := WorkBound F weight +lemma work_deterministic {f : A→B} {F : TreeTyped.Realizer f} {m : A→ℕ} + (hF : TreeTyped.WorkBound F m) : WorkBound (deterministic F) m := hF +lemma work_congr {f g : A→Experiment B} {F : Realizer f} {m : A→ℕ} + (h : ∀ a w,(f a).mean w=(g a).mean w) (hF : WorkBound F m) : WorkBound (F.congr h) m := by + obtain ⟨p,hp⟩:=hF + refine ⟨p,fun a=>?_⟩ + change F.cost a+(g a).worst weight≤_ + rw [←Experiment.worst_eq_of_mean_eq (h a)] + exact hp a +lemma work_remeasure {f : A→Experiment B} {F : Realizer f} {m n : A→ℕ} + (hF : WorkBound F m) (p : Polynomial ℕ) (hm : ∀ a,m a≤p.eval (n a)) : WorkBound F n := by + obtain ⟨q,hq⟩:=hF + exact ⟨q.comp p,fun a=>(hq a).trans (by simpa using polynomial_eval_monotone q (hm a))⟩ +lemma work_of_polynomial {f : A→Experiment B} {F : Realizer f} {m : A→ℕ} + (hF : PolynomialTime F) (p : Polynomial ℕ) (hm : ∀ a,weight a≤p.eval (m a)) : WorkBound F m := + work_remeasure hF p hm +lemma work_composition {f : A→Experiment B} {g : B→Experiment C} {F : Realizer f} {G : Realizer g} + {m : A→ℕ} {n : B→ℕ} (hF : WorkBound F m) (hG : WorkBound G n) + (p : Polynomial ℕ) (hm : ∀ a,(f a).All (fun b=>n b≤p.eval (m a))) : + WorkBound (composition F G) m := by + obtain ⟨q,hq⟩:=hF + obtain ⟨r,hr⟩:=hG + refine ⟨q+2*(r.comp p),fun a=>?_⟩ + have hb : (f a).All (fun b=>G.cost b+(g b).worst weight≤r.eval (p.eval (m a))) := + (hm a).mono (fun b hb=>(hr b).trans (polynomial_eval_monotone r hb)) + have h1:=Experiment.worst_le _ _ _ (hb.mono (fun b hb=>Nat.le_trans (Nat.le_add_right _ _) hb)) + have h2:=Experiment.worst_le _ _ _ (hb.mono (fun b hb=>Nat.le_trans (Nat.le_add_left _ _) hb)) + have h3:=hq a + change F.cost a+(f a).worst G.cost+((f a).bind g).worst weight≤_ + rw [Experiment.worst_bind] + simp only [Polynomial.eval_add,Polynomial.eval_mul,Polynomial.eval_ofNat,Polynomial.eval_comp] + omega +lemma work_then_polynomial {f : A→Experiment B} {g : B→Experiment C} {F : Realizer f} {G : Realizer g} + {m : A→ℕ} (hF : WorkBound F m) (hG : PolynomialTime G) : WorkBound (composition F G) m := by + obtain ⟨p,hp⟩:=hF + apply work_composition ⟨p,hp⟩ hG p + intro a + exact (Experiment.all_worst (f a) weight).mono (fun b hb=>hb.trans (Nat.le_trans (Nat.le_add_left _ _) (hp a))) +lemma polynomial_composition {f : A→Experiment B} {g : B→Experiment C} {F : Realizer f} {G : Realizer g} + (hF : PolynomialTime F) (hG : PolynomialTime G) : PolynomialTime (composition F G) := work_then_polynomial hF hG +lemma polynomial_deterministic {f : A→B} {F : TreeTyped.Realizer f} (hF : TreeTyped.PolynomialTime F) : + PolynomialTime (deterministic F) := hF +end MatchingFPRAS.OnlineTree + +end OAI diff --git a/lean/OAI/Combinatorics/MatchingCount/Complexity/OnlineFoldCost.lean b/lean/OAI/Combinatorics/MatchingCount/Complexity/OnlineFoldCost.lean new file mode 100644 index 0000000000000000000000000000000000000000..f93e213e338067e9255a13f605bfac92025550ae --- /dev/null +++ b/lean/OAI/Combinatorics/MatchingCount/Complexity/OnlineFoldCost.lean @@ -0,0 +1,51 @@ +import Mathlib +import OAI.Combinatorics.MatchingCount.Machines.OnlineFold + +namespace OAI + +namespace MatchingFPRAS.OnlineTree +open TreeTyped PhysicalStream Polynomial + +variable {A B : Type} [Codec A] [Codec B] + +omit [Codec B] in +lemma fold_cost_bound (f : A×B→Experiment B) (t : A×B→ℕ) + (as : List A) (b : B) (P : ℕ→B→Prop) (C M : ℕ) + (hb : P as.length b) (hw : weight as≤M) + (hs : ∀ a∈as,∀ k exact ⟨by simp [Fold.cost],hb⟩ + | cons a as ih => + have hwa : weight a≤M := by rw [weight_cons] at hw; omega + have hwt : weight as≤M := by rw [weight_cons] at hw; omega + have hb' : P (as.length+1) b := hb + have hstep := hs a (by simp) as.length (by simp) b hb' + have htime := hc a (by simp) as.length (by simp) b hb' + have htt : (f (a,b)).All (fun v=>Fold.cost f t as v≤as.length*(C+14*M+34)+10 ∧ + (foldM f as v).All (P 0)) := hstep.mono (fun v hv=>ih v hv hwt + (fun a ha k hk v hv=>hs a (by simp [ha]) k (by simp only [List.length_cons]; omega) v hv) + (fun a ha k hk v hv=>hc a (by simp [ha]) k (by simp only [List.length_cons]; omega) v hv)) + constructor + · have hworst := Experiment.worst_le _ _ _ (htt.mono (fun _ h=>h.1)) + change t (a,b)+6*weight a+8*weight as+34+_≤_ + simp only [List.length_cons,Nat.add_mul,Nat.one_mul] + omega + · rw [foldM,Experiment.all_bind] + exact htt.mono (fun _ h=>h.2) + +omit [Codec A] in +lemma all_fold_weight (f : A×B→Experiment B) (as : List A) (b : B) (C : ℕ) + (hs : ∀ a∈as,∀ b,(f (a,b)).All (fun v=>weight v≤weight b+C)) : + (foldM f as b).All (fun v=>weight v≤weight b+as.length*C) := by + induction as generalizing b with + | nil => simp [foldM,Experiment.All] + | cons a as ih => + rw [foldM,Experiment.all_bind] + exact (hs a (by simp) b).mono (fun c hc=> + (ih c (fun a ha b=>hs a (by simp [ha]) b)).mono (fun v hv=>by + simp only [List.length_cons,Nat.add_mul,Nat.one_mul]; omega)) +end MatchingFPRAS.OnlineTree + +end OAI diff --git a/lean/OAI/Combinatorics/MatchingCount/Complexity/OnlineFrameCost.lean b/lean/OAI/Combinatorics/MatchingCount/Complexity/OnlineFrameCost.lean new file mode 100644 index 0000000000000000000000000000000000000000..3dc122fad78e2eef8e91eeb580d903b0f3eb6313 --- /dev/null +++ b/lean/OAI/Combinatorics/MatchingCount/Complexity/OnlineFrameCost.lean @@ -0,0 +1,112 @@ +import Mathlib +import OAI.Combinatorics.MatchingCount.Complexity.TreeNumericCosts +import OAI.Combinatorics.MatchingCount.Complexity.TreePolynomialGrid +import OAI.Combinatorics.MatchingCount.Machines.OnlineFrame +import OAI.Combinatorics.MatchingCount.Complexity.OnlineCost + +namespace OAI + +namespace MatchingFPRAS.PhysicalStream.Experiment +variable {A : Type} +lemma worst_affine (p : Experiment A) (g : A→ℕ) (k c : ℕ) : + p.worst (fun a=>k*g a+c)=k*p.worst g+c := by + induction p with + | done a => rfl + | read p ih => + simp only [worst,ih] + rcases le_total ((p false).worst g) ((p true).worst g) with h|h + · rw [max_eq_right h,max_eq_right (Nat.add_le_add_right (Nat.mul_le_mul_left k h) c)] + · rw [max_eq_left h,max_eq_left (Nat.add_le_add_right (Nat.mul_le_mul_left k h) c)] + | delay n p ih => exact ih +lemma worst_const_add (p : Experiment A) (c : ℕ) (g : A→ℕ) : + p.worst (fun a=>c+g a)=c+p.worst g := by + simpa only [one_mul,Nat.add_comm c] using worst_affine p g 1 c +lemma worst_add_const (p : Experiment A) (g : A→ℕ) (c : ℕ) : + p.worst (fun a=>g a+c)=p.worst g+c := by + simpa only [one_mul] using worst_affine p g 1 c +lemma worst_add_le (p : Experiment A) (f g : A→ℕ) : + p.worst (fun a=>f a+g a)≤p.worst f+p.worst g := by + exact worst_le _ _ _ ((all_worst p f).and (all_worst p g) |>.mono (fun _ h=>Nat.add_le_add h.1 h.2)) +end MatchingFPRAS.PhysicalStream.Experiment + +namespace MatchingFPRAS.OnlineTree +open TreeTyped PhysicalStream Polynomial + +variable {A B C : Type} [Codec A] [Codec B] [Codec C] +lemma mapSecond_cost {f : B→Experiment C} (F : Realizer f) (x : A×B) : + (mapSecond F).cost x=F.cost x.2+8*weight x.1+22 := rfl +omit [Codec B] in +lemma mapSecond_weight [Codec B] {f : B→Experiment C} (x : A×B) : + ((f x.2).map (Prod.mk x.1)).worst weight=1+weight x.1+(f x.2).worst weight := by + rw [Experiment.worst_map] + simp only [Function.comp_def,weight_prod] + exact Experiment.worst_const_add _ _ _ +lemma work_mapSecond {f : B→Experiment C} {F : Realizer f} {m : B→ℕ} {n : A×B→ℕ} + (hF : WorkBound F m) (p q : Polynomial ℕ) + (hm : ∀ x,m x.2≤p.eval (n x)) (hw : ∀ x,weight x.1≤q.eval (n x)) : + WorkBound (mapSecond F) n := by + obtain ⟨r,hr⟩:=hF + refine ⟨r.comp p+9*q+23,fun x=>?_⟩ + change (mapSecond F).cost x+((f x.2).map (Prod.mk x.1)).worst weight≤_ + rw [mapSecond_cost,mapSecond_weight] + have h:=(hr x.2).trans (polynomial_eval_monotone r (hm x)) + dsimp only at h + have hh:=hw x + simp only [Polynomial.eval_add,Polynomial.eval_mul,Polynomial.eval_comp,Polynomial.eval_ofNat] + omega +lemma polynomial_mapSecond {f : B→Experiment C} {F : Realizer f} (hF : PolynomialTime F) : + PolynomialTime (mapSecond (A:=A) F) := + work_mapSecond hF X X (fun x=>by simpa using weight_snd x) (fun x=>by simpa using weight_fst x) + +lemma pair_cost {f : A→Experiment B} {g : A→Experiment C} (F : Realizer f) (G : Realizer g) (a : A) : + (pair F G).cost a=F.cost a+G.cost a+45*weight a+26*(f a).worst weight+137 := by + simp only [pair,Realizer.congr,composition,deterministic,mapSecond,TreeTyped.pair, + TreeTyped.identity,TreeTyped.first,TreeTyped.second,Experiment.worst_map, + Experiment.worst,Function.comp_def,id_eq] + change 1+1+11*weight a+6*weight a+31+ + (F.cost a+8*weight a+22+(f a).worst (fun b=> + 3*weight a+7+(6*weight a+weight b+11)+11*weight (a,b)+6*weight b+31+ + (G.cost a+8*weight b+22)))=_ + simp only [weight_prod] + have h : (fun b : B=>3*weight a+7+(6*weight a+weight b+11)+11*(1+weight a+weight b)+6*weight b+31+ + (G.cost a+8*weight b+22))=(fun b=>26*weight b+(20*weight a+G.cost a+82)) := by funext b; omega + rw [h,Experiment.worst_affine] + omega +omit [Codec A] in +lemma pair_weight [Codec A] {f : A→Experiment B} {g : A→Experiment C} (a : A) : + ((f a).bind (fun b=>(g a).map (Prod.mk b))).worst weight= + 1+(f a).worst weight+(g a).worst weight := by + rw [Experiment.worst_bind] + simp only [Experiment.worst_map,Function.comp_def,weight_prod, + Experiment.worst_const_add,Experiment.worst_add_const] +lemma work_pair {f : A→Experiment B} {g : A→Experiment C} {F : Realizer f} {G : Realizer g} + {m : A→ℕ} (hF : WorkBound F m) (hG : WorkBound G m) + (p : Polynomial ℕ) (hw : ∀ a,weight a≤p.eval (m a)) : WorkBound (pair F G) m := by + obtain ⟨q,hq⟩:=hF + obtain ⟨r,hr⟩:=hG + refine ⟨27*q+r+45*p+138,fun a=>?_⟩ + change (pair F G).cost a+((f a).bind (fun b=>(g a).map (Prod.mk b))).worst weight≤_ + rw [pair_cost,pair_weight] + have h1:=hq a + have h2:=hr a + have h3:=hw a + simp only [Polynomial.eval_add,Polynomial.eval_mul,Polynomial.eval_ofNat] + omega +lemma polynomial_pair {f : A→Experiment B} {g : A→Experiment C} {F : Realizer f} {G : Realizer g} + (hF : PolynomialTime F) (hG : PolynomialTime G) : PolynomialTime (pair F G) := + work_pair hF hG X (by intro a; simp) +lemma work_choose {f g : A→Experiment B} {F : Realizer f} {G : Realizer g} {m : A→ℕ} + (hF : WorkBound F m) (hG : WorkBound G m) : WorkBound (choose F G) m := by + obtain ⟨p,hp⟩:=hF + obtain ⟨q,hq⟩:=hG + refine ⟨p+q+1,fun a=>?_⟩ + change 1+max (F.cost a) (G.cost a)+max ((f a).worst weight) ((g a).worst weight)≤_ + have h1:=hp a + have h2:=hq a + simp only [Polynomial.eval_add,Polynomial.eval_one] + omega +lemma polynomial_choose {f g : A→Experiment B} {F : Realizer f} {G : Realizer g} + (hF : PolynomialTime F) (hG : PolynomialTime G) : PolynomialTime (choose F G) := work_choose hF hG +end MatchingFPRAS.OnlineTree + +end OAI diff --git a/lean/OAI/Combinatorics/MatchingCount/Complexity/OnlineHistoryCost.lean b/lean/OAI/Combinatorics/MatchingCount/Complexity/OnlineHistoryCost.lean new file mode 100644 index 0000000000000000000000000000000000000000..8d5fffcac011bcd387f2e1c1e45e00461b84ddc4 --- /dev/null +++ b/lean/OAI/Combinatorics/MatchingCount/Complexity/OnlineHistoryCost.lean @@ -0,0 +1,106 @@ +import Mathlib +import OAI.Combinatorics.MatchingCount.Algorithm.OnlineHistorySize + +namespace OAI + +namespace MatchingFPRAS.PhysicalStream.Experiment +lemma all_of_qaverage {A B : Type} [Fintype B] [Nonempty B] (p : Experiment A) (f : B→A) + (hm : ∀ h,p.mean h=qaverage (h ∘ f)) (P : A→Prop) (hf : ∀ b,P (f b)) : p.All P := by + classical + rw [all_indicator,hm] + calc + _=qaverage (fun _ : B=>(0:ℚ)) := by + apply qaverage_congr + intro b + simp only [Function.comp_apply,ite_eq_left (hf b)] + _=0 := qaverage_const 0 +end MatchingFPRAS.PhysicalStream.Experiment + +namespace MatchingFPRAS.OnlineTrial +open TreeTyped PhysicalStream Polynomial OnlineGraph OnlineSample + +variable {G : GraphInput} [Nontrivial (Fin G.n)] +noncomputable def initial (f : Edges→Edges) (p : Trial.Parameters G) : List Bool×State := + (List.replicate p.K false,state f (represent p (FiniteTrial.firstLayer p) PUnit.unit)) +def History (f : Edges→Edges) (p : Trial.Parameters G) (k : ℕ) (s : State) : Prop := + ∃ (j : ℕ) (hj : j≤p.K) (x : (FiniteTrial.layers p j hj).Ω),j+k=p.K ∧ + s=state f (represent p (FiniteTrial.layers p j hj) x) +lemma history_initial (f : Edges→Edges) (p : Trial.Parameters G) : History f p p.K (initial f p).2 := by + exact ⟨0,by omega,PUnit.unit,by omega,rfl⟩ +lemma history_size (f : Edges→Edges) (p : Trial.Parameters G) (k : ℕ) (s : State) + (hs : History f p k s) : stateSize s≤ statePolynomial.eval (sizeNorm p (graph f (ExecutableAdaptive.graphRep G))) := by + obtain ⟨j,hj,x,_,rfl⟩:=hs + exact state_weight_bound f p j hj x +lemma history_step (f : Edges→Edges) (hf : ∀ es e,e∈f es↔e∈es) (p : Trial.Parameters G) + (k : ℕ) (s : State) (hs : History f p (k+1) s) : (step s).All (History f p k) := by + classical + obtain ⟨j,hj,x,hjk,rfl⟩:=hs + apply Experiment.all_of_qaverage _ + (fun b=>state f (represent p ((FiniteTrial.layers p j hj).append p hj) + ⟨x,((FiniteTrial.layers p j hj).state x).drawStage p hj b⟩)) + · intro h + rw [OnlineGraph.step_mean f hf,step_mean p hj] + rfl + · intro b + exact ⟨j+1,by omega,⟨x,((FiniteTrial.layers p j hj).state x).drawStage p hj b⟩,by omega,rfl⟩ +lemma sweep_history (f : Edges→Edges) (hf : ∀ es e,e∈f es↔e∈es) (p : Trial.Parameters G) : + (sweep (initial f p)).All (History f p 0) := by + have hall : ∀ as : List Bool,∀ s,History f p as.length s→ + (OnlineTree.foldM body as s).All (History f p 0) := by + intro as + induction as with + | nil => intro s hs;exact hs + | cons a as ih => + intro s hs + rw [OnlineTree.foldM,Experiment.all_bind] + exact (history_step f hf p as.length s hs).mono (fun v hv=>ih v hv) + exact hall _ _ (by simpa only [initial,List.length_replicate] using history_initial f p) + +open TreeTyped PhysicalStream Polynomial OnlineGraph OnlineSample + +lemma sweep_bound : ∃ q : Polynomial ℕ,∀ (G : GraphInput) [Nontrivial (Fin G.n)] + (f : Edges→Edges) (_hf : ∀ es e,e∈f es↔e∈es) (p : Trial.Parameters G), + sweepRealizer.cost (initial f p)+(sweep (initial f p)).worst weight≤ + q.eval (sizeNorm p (graph f (ExecutableAdaptive.graphRep G))) := by + obtain ⟨q,hq⟩:=work_body + let C := q.comp (2*statePolynomial+2) + let M : Polynomial ℕ := 2*X+1 + refine ⟨X*(C+14*M+34)+10+statePolynomial,?_⟩ + intro G inst f hf p + let n:=sizeNorm p (graph f (ExecutableAdaptive.graphRep G)) + have hk : p.K ≤ n := (sizeNorm_fields p _).2.1 + have hw : weight (initial f p).1≤M.eval n := by + simp only [initial,weight_replicate,show weight false=1 from rfl,M,Polynomial.eval_add, + Polynomial.eval_mul,Polynomial.eval_ofNat,Polynomial.eval_X,Polynomial.eval_one] + omega + have hc : ∀ a∈(initial f p).1,∀ k<(initial f p).1.length,∀ s,History f p (k+1) s→ + bodyRealizer.cost (a,s)≤C.eval n := by + intro a ha k hk s hs + have hsz : stateSize s ≤ statePolynomial.eval n := history_size f p (k+1) s hs + have hw:=weight_le_stateSize s + have hb:=hq (a,s) + have ha' : weight a=1 := by + have he : a=false := (List.mem_replicate.mp ha).2 + rw [he];rfl + simp only [weight_prod,ha'] at hb + have hm : stateSize s+(1+1+weight s)≤(2*statePolynomial+2).eval n := by + simp only [Polynomial.eval_add,Polynomial.eval_mul,Polynomial.eval_ofNat] + omega + exact (Nat.le_add_right _ _).trans (hb.trans (by simpa only [C,Polynomial.eval_comp] using polynomial_eval_monotone q hm)) + have hh:=OnlineTree.fold_cost_bound body bodyRealizer.cost (initial f p).1 (initial f p).2 + (History f p) (C.eval n) (M.eval n) + (by simpa only [initial,List.length_replicate] using history_initial f p) hw + (fun a ha k hk s hs=>history_step f hf p k s hs) hc + have hout : (sweep (initial f p)).worst weight≤ statePolynomial.eval n := by + apply Experiment.worst_le _ _ _ + exact hh.2.mono (fun s hs=>(weight_le_stateSize s).trans (history_size f p 0 s hs)) + have hmul:=Nat.mul_le_mul_right (C.eval n+14*M.eval n+34) hk + change OnlineTree.Fold.cost body bodyRealizer.cost (initial f p).1 (initial f p).2+_≤_ + have hlen : (initial f p).1.length=p.K := List.length_replicate + rw [hlen] at hh + simp only [Polynomial.eval_add,Polynomial.eval_mul,Polynomial.eval_ofNat,Polynomial.eval_X] + change _ ≤ n*(C.eval n+14*M.eval n+34)+10+statePolynomial.eval n + omega +end MatchingFPRAS.OnlineTrial + +end OAI diff --git a/lean/OAI/Combinatorics/MatchingCount/Complexity/OnlineInitialCost.lean b/lean/OAI/Combinatorics/MatchingCount/Complexity/OnlineInitialCost.lean new file mode 100644 index 0000000000000000000000000000000000000000..7c66dc3c2599d94a47bd2c8e8ae1e541c0fea463 --- /dev/null +++ b/lean/OAI/Combinatorics/MatchingCount/Complexity/OnlineInitialCost.lean @@ -0,0 +1,92 @@ +import Mathlib +import OAI.Combinatorics.MatchingCount.Algorithm.OnlineInitial +import OAI.Combinatorics.MatchingCount.Complexity.OnlineScheduleCost + +namespace OAI + +namespace MatchingFPRAS.OnlineInitial +open TreeTyped TreeFraction OnlineSchedule Polynomial NumericBounds + +lemma work_root : WorkBound rootRealizer id := by + unfold rootRealizer + apply work_then_polynomial _ polynomial_findRoot + apply work_pair _ _ (4*X+1) (fun n=>by simpa using weight_nat_numeric n) + · exact work_of_polynomial (polynomial_composition (polynomial_pair polynomial_identity (polynomial_constant _)) + polynomial_subtract) (4*X+1) (fun n=>by simpa using weight_nat_numeric n) + · exact work_composition (work_of_polynomial polynomial_identity (4*X+1) + (fun n=>by simpa using weight_nat_numeric n)) fuel_numeric_work X (by simp) +lemma work_initialScale : WorkBound initialScaleRealizer id := by + unfold initialScaleRealizer + apply work_then_polynomial _ polynomial_div + apply work_pair _ _ (4*X+1) (fun n=>by simpa using weight_nat_numeric n) + · exact work_of_polynomial (polynomial_constant _) (4*X+1) (fun n=>by simpa using weight_nat_numeric n) + · exact work_pair work_root (work_of_polynomial (polynomial_constant _) (4*X+1) + (fun n=>by simpa using weight_nat_numeric n)) (4*X+1) (fun n=>by simpa using weight_nat_numeric n) +lemma polynomial_scaleVector : PolynomialTime scaleVectorRealizer := by + unfold scaleVectorRealizer + apply polynomial_congr + apply work_then_polynomial _ (polynomial_mapWith (polynomial_pair polynomial_second polynomial_first)) + apply work_pair _ polynomial_identity X (by simp) + exact work_composition polynomial_listLength work_initialScale X (fun vs=>by simpa using list_length_le_weight vs) +lemma polynomial_count : PolynomialTime countRealizer := by + unfold countRealizer nRealizer Realizer.fst Realizer.snd + apply polynomial_composition _ polynomial_sampleCount + tree_cost +lemma polynomial_seedD : PolynomialTime seedDRealizer := by + unfold seedDRealizer Realizer.fst + apply polynomial_pair polynomial_first + apply polynomial_pair polynomial_second + apply polynomial_composition _ polynomial_distortion + tree_cost + +def configNumeric (x : Config) : ℕ := x.1.1.1.1.length+x.1.2+x.2.1+x.2.2+ + ladderSchedule (x.2,x.1.2)+Transport.ladderQ x.2.1 x.2.2 +def configSize (x : Config) : ℕ := configNumeric x+weight x +def seedSize (x : Seed) : ℕ := x.1.1.length+natCeil (inverse x.2.1)+configNumeric (config x)+weight x +lemma weight_configSize (x : Config) : weight x ≤ configSize x := by unfold configSize;omega +lemma weight_seedSize (x : Seed) : weight x ≤ seedSize x := by unfold seedSize;omega +lemma config_fields (x : Config) : x.1.1.1.1.length ≤ configSize x ∧ x.1.2 ≤ configSize x ∧ + x.2.1 ≤ configSize x ∧ x.2.2 ≤ configSize x ∧ + ladderSchedule (x.2,x.1.2) ≤ configSize x ∧Transport.ladderQ x.2.1 x.2.2 ≤ configSize x := by + unfold configSize configNumeric;omega +lemma seed_fields (x : Seed) : x.1.1.length ≤ seedSize x ∧ natCeil (inverse x.2.1) ≤ seedSize x ∧ + coolingSchedule (x.1.1.length,x.2.1) ≤ seedSize x ∧configNumeric (config x) ≤ seedSize x := by + unfold seedSize configNumeric config seedD seedN seedK + dsimp only + omega + +lemma work_seedK : WorkBound seedKRealizer seedSize := by + have lift {A : Type} [Codec A] {f : Seed→A} {F : Realizer f} (hF : PolynomialTime F) : + WorkBound F seedSize := work_of_polynomial hF X (fun x=>by simpa using weight_seedSize x) + unfold seedKRealizer + apply work_congr + apply work_pair (lift polynomial_identity) _ X (fun x=>by simpa using weight_seedSize x) + apply work_comp_bound (lift (polynomial_pair (polynomial_composition (polynomial_fst polynomial_first) + polynomial_listLength) (polynomial_fst polynomial_second))) work_coolingSchedule + have hw:=NumericBounds.weight (lift (polynomial_pair (polynomial_composition (polynomial_fst polynomial_first) + polynomial_listLength) (polynomial_fst polynomial_second))) + exact add (add (of_le (fun x=>(seed_fields x).1)) (of_le (fun x=>(seed_fields x).2.1))) hw + +def seedNSize (x : Seed×ℕ) : ℕ := x.1.1.1.length+x.2+weight x +lemma work_seedN : WorkBound seedNRealizer seedNSize := by + have lift {A : Type} [Codec A] {f : (Seed×ℕ)→A} {F : Realizer f} (hF : PolynomialTime F) : + WorkBound F seedNSize := work_of_polynomial hF X (fun x=>by simp [seedNSize]) + unfold seedNRealizer + apply work_congr + apply work_pair (lift polynomial_identity) _ X (fun x=>by simp [seedNSize]) + apply work_comp_bound (lift (polynomial_pair (polynomial_composition (polynomial_fst (polynomial_fst polynomial_first)) + polynomial_listLength) polynomial_second)) work_vertexNumber + have hw:=NumericBounds.weight (lift (polynomial_pair (polynomial_composition (polynomial_fst (polynomial_fst polynomial_first)) + polynomial_listLength) polynomial_second)) + exact add (add (of_le (fun x=>by dsimp only [Function.comp_apply]; unfold seedNSize;omega)) (of_le (fun x=>by dsimp only [Function.comp_apply]; unfold seedNSize;omega))) hw +lemma work_config : WorkBound configRealizer seedSize := by + unfold configRealizer + apply work_then_polynomial _ polynomial_seedD + apply work_comp_bound work_seedK work_seedN + have hw:=NumericBounds.weight work_seedK + exact add (add (of_le (fun x=>(seed_fields x).1)) (of_le (fun x=>(seed_fields x).2.2.1))) hw +lemma bound_configSize : Bound (configSize ∘ config) seedSize := + add (of_le (fun x=>(seed_fields x).2.2.2)) (NumericBounds.weight work_config) +end MatchingFPRAS.OnlineInitial + +end OAI diff --git a/lean/OAI/Combinatorics/MatchingCount/Complexity/OnlineInitialDataCost.lean b/lean/OAI/Combinatorics/MatchingCount/Complexity/OnlineInitialDataCost.lean new file mode 100644 index 0000000000000000000000000000000000000000..aaf939a988d8b748cf76fb384b800cb907265f52 --- /dev/null +++ b/lean/OAI/Combinatorics/MatchingCount/Complexity/OnlineInitialDataCost.lean @@ -0,0 +1,60 @@ +import Mathlib +import OAI.Combinatorics.MatchingCount.Complexity.OnlineInitialCost + +namespace OAI + +namespace MatchingFPRAS.OnlineInitial +open TreeTyped TreeFraction OnlineSchedule Polynomial NumericBounds ExecutableSource ExecutableScaling + +lemma work_data : WorkBound dataRealizer configSize := by + have lift {A : Type} [Codec A] {f : Config→A} {F : Realizer f} (hF : PolynomialTime F) : + WorkBound F configSize := work_of_polynomial hF X (fun x=>by simpa using weight_configSize x) + have wb : ∀ x : Config,weight x≤X.eval (configSize x) := fun x=>by simpa using weight_configSize x + have _workK : WorkBound (first.snd : Realizer (fun x : Config=>x.1.2)) configSize := lift (by unfold Realizer.snd; tree_cost) + have hk : Bound (fun x : Config=>x.1.2) configSize := of_le (fun x=>(config_fields x).2.1) + have hN : Bound (fun x : Config=>x.2.1) configSize := of_le (fun x=>(config_fields x).2.2.1) + have hD : Bound (fun x : Config=>x.2.2) configSize := of_le (fun x=>(config_fields x).2.2.2.1) + have hT : Bound (fun x : Config=>ladderSchedule (x.2,x.1.2)) configSize := of_le (fun x=>(config_fields x).2.2.2.2.1) + have hq : Bound (fun x : Config=>Transport.ladderQ x.2.1 x.2.2) configSize := of_le (fun x=>(config_fields x).2.2.2.2.2) + unfold dataRealizer Realizer.fst Realizer.snd + apply work_congr + apply work_pair _ _ X wb + · apply work_pair _ _ X wb + · exact lift (by tree_cost) + · apply work_pair _ _ X wb + · apply work_pair _ (lift (by tree_cost)) X wb + apply work_pair _ _ X wb + · apply work_comp_bound (lift (by apply polynomial_addNat (polynomial_mulNat (polynomial_constant _) (by tree_cost)) (polynomial_constant _))) fuel_numeric_work + exact add (mul (const 2 _) hk) (const 2 _) + · apply work_comp_bound (lift (by apply polynomial_mulNat (polynomial_constant _) (by tree_cost))) fuel_numeric_work + exact mul (const 2 _) hk + · apply work_pair _ _ X wb + · apply work_comp_bound _ fuel_numeric_work hT + apply work_comp_bound (lift (by tree_cost)) work_ladderSchedule + exact add (add (add hN hD) hk) (NumericBounds.weight (lift (by tree_cost))) + · apply work_comp_bound (lift (polynomial_composition polynomial_second polynomial_q)) fuel_numeric_work hq + · exact lift (polynomial_composition (by tree_cost) polynomial_scaleVector) + +lemma work_trialInput : WorkBound trialInputRealizer configSize := by + have lift {A : Type} [Codec A] {f : Config→A} {F : Realizer f} (hF : PolynomialTime F) : + WorkBound F configSize := work_of_polynomial hF X (fun x=>by simpa using weight_configSize x) + have wb : ∀ x : Config,weight x≤X.eval (configSize x) := fun x=>by simpa using weight_configSize x + unfold trialInputRealizer Realizer.snd + apply work_pair _ _ X wb + · exact work_comp_bound (lift (by tree_cost)) fuel_numeric_work (of_le (fun x=>(config_fields x).2.1)) + · apply work_pair _ _ X wb + · exact work_pair work_data (lift polynomial_count) X wb + · apply work_pair _ (lift (polynomial_constant _)) X wb + apply work_comp_bound (lift (by unfold nRealizer Realizer.fst;tree_cost)) pairingNumber_numeric_work + exact of_le (fun x=>(config_fields x).1) +lemma work_runInput : WorkBound runInputRealizer configSize := by + unfold runInputRealizer Realizer.fst Realizer.snd + apply work_congr + apply work_pair _ work_trialInput X (fun x=>by simpa using weight_configSize x) + apply work_of_polynomial (polynomial_composition (by tree_cost) polynomial_repetitions) X + exact fun x=>by simpa using weight_configSize x +lemma work_initializeInput : WorkBound initializeInputRealizer seedSize := + work_comp_bound work_config work_runInput bound_configSize +end MatchingFPRAS.OnlineInitial + +end OAI diff --git a/lean/OAI/Combinatorics/MatchingCount/Complexity/OnlineRequestCost.lean b/lean/OAI/Combinatorics/MatchingCount/Complexity/OnlineRequestCost.lean new file mode 100644 index 0000000000000000000000000000000000000000..82ee453fec281be335c8a8cc9f3e60b97e30258f --- /dev/null +++ b/lean/OAI/Combinatorics/MatchingCount/Complexity/OnlineRequestCost.lean @@ -0,0 +1,125 @@ +import Mathlib +import OAI.Combinatorics.MatchingCount.Algorithm.OnlineRequest +import OAI.Combinatorics.MatchingCount.Complexity.OnlineSampleCost + +namespace OAI + +namespace MatchingFPRAS.NumericBounds +open Polynomial TreeTyped + +variable {A B : Type} +def Bound (f m : A→ℕ) : Prop := ∃ p : Polynomial ℕ,∀ x,f x≤p.eval (m x) +lemma self (m : A→ℕ) : Bound m m := ⟨X,fun _=>by simp⟩ +lemma of_le {f m : A→ℕ} (h : ∀ x,f x ≤ m x) : Bound f m := ⟨X,fun x=>by simpa using h x⟩ +lemma const (n : ℕ) (m : A→ℕ) : Bound (fun _=>n) m := ⟨C n,fun _=>by simp⟩ +lemma mono {f g m : A→ℕ} (hf : Bound f m) (h : ∀ x,g x≤f x) : Bound g m := by + obtain ⟨p,hp⟩:=hf;exact ⟨p,fun x=>(h x).trans (hp x)⟩ +lemma add {f g m : A→ℕ} (hf : Bound f m) (hg : Bound g m) : Bound (fun x=>f x+g x) m := by + obtain ⟨p,hp⟩:=hf;obtain ⟨q,hq⟩:=hg + exact ⟨p+q,fun x=>by simpa using Nat.add_le_add (hp x) (hq x)⟩ +lemma mul {f g m : A→ℕ} (hf : Bound f m) (hg : Bound g m) : Bound (fun x=>f x*g x) m := by + obtain ⟨p,hp⟩:=hf;obtain ⟨q,hq⟩:=hg + exact ⟨p*q,fun x=>by simpa using Nat.mul_le_mul (hp x) (hq x)⟩ +lemma pow {f m : A→ℕ} (hf : Bound f m) (n : ℕ) : Bound (fun x=>f x^n) m := by + obtain ⟨p,hp⟩:=hf + exact ⟨p^n,fun x=>by simpa using Nat.pow_le_pow_left (hp x) n⟩ +lemma clog_le (n : ℕ) : Nat.clog 2 n≤n := by + apply Nat.clog_le_of_le_pow + exact (Nat.lt_two_pow_self (n:=n)).le +lemma clog {f m : A→ℕ} (hf : Bound f m) : Bound (fun x=>Nat.clog 2 (f x)) m := + mono hf (fun _=>clog_le _) +lemma comp {f : A→B} {m : A→ℕ} {n g : B→ℕ} (hg : Bound g n) (hf : Bound (n ∘ f) m) : + Bound (g ∘ f) m := by + obtain ⟨p,hp⟩:=hg;obtain ⟨q,hq⟩:=hf + exact ⟨p.comp q,fun x=>by simpa using (hp (f x)).trans (polynomial_eval_monotone p (hq x))⟩ +lemma weight [Codec A] [Codec B] {f : A→B} {F : Realizer f} {m : A→ℕ} + (hF : WorkBound F m) : Bound (fun x=>TreeTyped.weight (f x)) m := by + obtain ⟨p,hp⟩:=hF + exact ⟨p,fun x=>(Nat.le_add_left _ _).trans (hp x)⟩ +lemma length [Codec A] [Codec B] {f : A→List B} {F : Realizer f} {m : A→ℕ} + (hF : WorkBound F m) : Bound (fun x=>(f x).length) m := + mono (weight hF) (fun _=>list_length_le_weight _) +end MatchingFPRAS.NumericBounds + +namespace MatchingFPRAS.OnlineSchedule +open TreeTyped Polynomial NumericBounds Transport ExecutableSource + +def precisionNorm (x : PrecisionData) : ℕ := + x.1.1.1.1+x.1.1.1.2+x.1.1.2.1+x.1.1.2.2+x.1.2+x.2.1+x.2.2 +lemma bound_plan : Bound (fun x : PrecisionData=> + (precisionPlan x).1.1.1+(precisionPlan x).1.1.2+(precisionPlan x).1.2+(precisionPlan x).2) precisionNorm := by + have hN : Bound (fun x : PrecisionData=>x.1.1.1.1) precisionNorm := of_le (fun x=>by unfold precisionNorm;omega) + have hD : Bound (fun x : PrecisionData=>x.1.1.1.2) precisionNorm := of_le (fun x=>by unfold precisionNorm;omega) + have hK : Bound (fun x : PrecisionData=>x.1.1.2.1) precisionNorm := of_le (fun x=>by unfold precisionNorm;omega) + have hT : Bound (fun x : PrecisionData=>x.1.1.2.2) precisionNorm := of_le (fun x=>by unfold precisionNorm;omega) + have hm : Bound (fun x : PrecisionData=>x.1.2) precisionNorm := of_le (fun x=>by unfold precisionNorm;omega) + have hE : Bound (fun x : PrecisionData=>x.2.1) precisionNorm := of_le (fun x=>by unfold precisionNorm;omega) + have hB : Bound (fun x : PrecisionData=>x.2.2) precisionNorm := of_le (fun x=>by unfold precisionNorm;omega) + have hL : Bound (fun x : PrecisionData=>ladderL x.1.1.1.1 x.1.1.1.2) precisionNorm := + pow (mul (mul (const (10^4) _) hN) hD) 100 + have hQ : Bound (fun x : PrecisionData=>ladderQ x.1.1.1.1 x.1.1.1.2) precisionNorm := mul (const 32 _) hL + have hM : Bound (fun x : PrecisionData=>ladderM x.1.1.1.1 x.1.1.1.2 x.1.1.2.2) precisionNorm := + add (mul hT (pow hQ 2)) hQ + have hlambda : Bound (fun x : PrecisionData=>ladderLambda x.1.1.1.1 x.1.1.1.2 x.1.1.2.1 x.1.1.2.2) precisionNorm := + mul (mul (mul (mul (const 10 _) hN) hQ) (add hT (const 1 _))) + (add (add hK (clog (add (mul hN hD) (const 2 _)))) (const 1 _)) + have hr : Bound (fun x : PrecisionData=>discreteLadderSteps x.1.1.1.1 x.1.1.1.2 x.1.1.2.1 x.1.1.2.2 x.1.2) precisionNorm := + mul (mul (mul (const 20 _) hL) hM) (add (add hlambda (clog hm)) (const 1 _)) + have he : Bound scanError precisionNorm := + add (add (mul (const 2 _) (add (const 1 _) hM)) + (mul (const 4 _) (add (add (mul (const 8 _) (pow hE 2)) (mul (const 4 _) hE)) (const 3 _)))) + (mul (mul (const 2 _) (pow hN 2)) hB) + exact add (add (add (clog (mul (mul hr he) hm)) hN) hr) (clog (mul (mul (const 6 _) hE) hm)) + +def requestSize (x : RequestInput) : ℕ := x.1.1.2.1.2+x.2+TreeTyped.weight x +lemma weight_le_requestSize (x : RequestInput) : TreeTyped.weight x≤requestSize x := by unfold requestSize;omega +lemma bound_precision : Bound (precisionNorm ∘ sourcePrecision) requestSize := by + have hn := NumericBounds.length (work_of_polynomial + (polynomial_composition polynomial_requestBag polynomial_sourceVertices) X + (fun x=>by simpa using weight_le_requestSize x)) + have he := NumericBounds.length (work_of_polynomial polynomial_requestCatalog X + (fun x=>by simpa using weight_le_requestSize x)) + have hb := NumericBounds.length (work_of_polynomial + (polynomial_composition polynomial_requestBag polynomial_sourceParents) X + (fun x=>by simpa using weight_le_requestSize x)) + have hd : Bound (fun x : RequestInput=>x.1.1.2.1.2) requestSize := of_le (fun x=>by unfold requestSize;omega) + have hs : Bound (fun x : RequestInput=>x.2) requestSize := of_le (fun x=>by unfold requestSize;omega) + have hk : Bound (fun x : RequestInput=>x.1.1.2.1.1.2.length/2) requestSize := by + apply of_le;intro x + have h:=list_length_le_weight x.1.1.2.1.1.2 + have hd:=Nat.div_le_self x.1.1.2.1.1.2.length 2 + unfold requestSize + have h1:=weight_fst x + have h2:=weight_fst x.1 + have h3:=weight_snd x.1.1 + have h4:=weight_fst x.1.1.2 + have h5:=weight_fst x.1.1.2.1 + have h6:=weight_snd x.1.1.2.1.1 + omega + have ht : Bound (fun x : RequestInput=>x.1.1.2.2.1.length) requestSize := by + apply of_le;intro x + have h:=list_length_le_weight x.1.1.2.2.1 + unfold requestSize + have h1:=weight_fst x + have h2:=weight_fst x.1 + have h3:=weight_snd x.1.1 + have h7:=weight_snd x.1.1.2 + have h8:=weight_fst x.1.1.2.2 + omega + exact add (add (add (add (add (add hn hd) hk) ht) (mul (mul (const 1000 _) hk) hs)) he) hb +lemma bound_sourceRequest : Bound (OnlineSample.requestMeasure ∘ sourceRequest) requestSize := by + have hp := NumericBounds.comp bound_plan bound_precision + have hw := NumericBounds.weight (work_of_polynomial polynomial_sourceRequest X + (fun x=>by simpa using weight_le_requestSize x)) + apply NumericBounds.mono (NumericBounds.add hp (NumericBounds.mul (NumericBounds.const 4 _) hw)) + intro x + dsimp only [Function.comp_apply,sourceRequest,OnlineSample.requestMeasure,OnlineSample.scansMeasure, + OnlineSample.pairMeasure,OnlineSample.marksMeasure] + have h1:=weight_fst (sourceRequest x) + have h2:=weight_fst (sourceRequest x).1 + have h3:=weight_snd (sourceRequest x) + dsimp only [sourceRequest] at h1 h2 h3 + omega +end MatchingFPRAS.OnlineSchedule + +end OAI diff --git a/lean/OAI/Combinatorics/MatchingCount/Complexity/OnlineRunCost.lean b/lean/OAI/Combinatorics/MatchingCount/Complexity/OnlineRunCost.lean new file mode 100644 index 0000000000000000000000000000000000000000..a8366bd14718d402c596c70ff3f6612aa670b71d --- /dev/null +++ b/lean/OAI/Combinatorics/MatchingCount/Complexity/OnlineRunCost.lean @@ -0,0 +1,112 @@ +import Mathlib +import OAI.Combinatorics.MatchingCount.Complexity.OnlineHistoryCost + +namespace OAI + +namespace MatchingFPRAS.OnlineTrial +open TreeTyped PhysicalStream Polynomial OnlineGraph OnlineSample + +noncomputable def initialWeightPolynomial : Polynomial ℕ := 2*X+3+statePolynomial +lemma initial_weight {G : GraphInput} [Nontrivial (Fin G.n)] (f : Edges→Edges) (p : Trial.Parameters G) : + weight (initial f p) ≤ initialWeightPolynomial.eval (sizeNorm p (graph f (ExecutableAdaptive.graphRep G))) := by + have hs:=history_size f p p.K (initial f p).2 (history_initial f p) + have hw:=weight_le_stateSize (initial f p).2 + have hk:=(sizeNorm_fields p (graph f (ExecutableAdaptive.graphRep G))).2.1 + rw [weight_prod] + have hl : weight (initial f p).1=2*p.K+1 := by simp only [initial,weight_replicate,show weight false=1 from rfl];omega + rw [hl] + simp only [initialWeightPolynomial,Polynomial.eval_add,Polynomial.eval_mul,Polynomial.eval_X,Polynomial.eval_ofNat] + omega +end MatchingFPRAS.OnlineTrial + +namespace MatchingFPRAS.OnlineGuard +open TreeTyped PhysicalStream Polynomial OnlineGraph OnlineTrial + +lemma trial_bound : ∃ q : Polynomial ℕ,∀ (G : GraphInput) [Nontrivial (Fin G.n)] + (f : Edges→Edges) (_hf : ∀ es e,e∈f es↔e∈es) (p : Trial.Parameters G), + trialRealizer.cost (OnlineTrial.initial f p)+(trial (OnlineTrial.initial f p)).worst weight≤ + q.eval (sizeNorm p (graph f (ExecutableAdaptive.graphRep G))) := by + obtain ⟨q,hq⟩:=sweep_bound + obtain ⟨r,hr⟩:=work_checked + refine ⟨q+2*(r.comp statePolynomial),?_⟩ + intro G inst f hf p + let n:=sizeNorm p (graph f (ExecutableAdaptive.graphRep G)) + have hs:=hq G f hf p + have hb : (sweep (OnlineTrial.initial f p)).All (fun s=>checkedRealizer.cost s+(checked s).worst weight≤r.eval (statePolynomial.eval n)) := + (sweep_history f hf p).mono (fun s hs=>(hr s).trans (polynomial_eval_monotone r (history_size f p 0 s hs))) + have h1:=Experiment.worst_le _ _ _ (hb.mono (fun s hs=>Nat.le_trans (Nat.le_add_right _ _) hs)) + have h2:=Experiment.worst_le _ _ _ (hb.mono (fun s hs=>Nat.le_trans (Nat.le_add_left _ _) hs)) + change sweepRealizer.cost _+(sweep _).worst checkedRealizer.cost+((sweep _).bind checked).worst weight≤_ + rw [Experiment.worst_bind] + simp only [Polynomial.eval_add,Polynomial.eval_mul,Polynomial.eval_ofNat,Polynomial.eval_comp] + dsimp only [n] at * + omega +end MatchingFPRAS.OnlineGuard + +namespace MatchingFPRAS.OnlineAmplification +open TreeTyped PhysicalStream Polynomial OnlineGraph OnlineTrial OnlineSample + +lemma run_bound : ∃ q : Polynomial ℕ,∀ (G : GraphInput) [Nontrivial (Fin G.n)] + (f : Edges→Edges) (_hf : ∀ es e,e∈f es↔e∈es) (p : Trial.Parameters G) (r : ℕ), + runRealizer.cost (r,OnlineTrial.initial f p)+(run (r,OnlineTrial.initial f p)).worst weight≤ + q.eval (r+sizeNorm p (graph f (ExecutableAdaptive.graphRep G))) := by + obtain ⟨q,hq⟩:=OnlineGuard.trial_bound + obtain ⟨s,hs⟩:=OnlineTree.traverse_bound OnlineGuard.trialRealizer + obtain ⟨u,hu⟩:=work_repeatInput (A:=TrialInput) + obtain ⟨v,hv⟩:=OnlineMedian.polynomial_median + let I := initialWeightPolynomial + let R : Polynomial ℕ := 5*X+2+I + let B : Polynomial ℕ := X*(I+1)+1+q + let T := u.comp R+s.comp B + refine ⟨T+2*(v.comp T),?_⟩ + intro G inst f hf p r + let n:=sizeNorm p (graph f (ExecutableAdaptive.graphRep G)) + let z:=r+n + let x : TrialInput:=OnlineTrial.initial f p + have hn:n≤z := by dsimp [z];omega + have hr:r≤z := by dsimp [z];omega + have hx : weight x≤I.eval z := (initial_weight f p).trans (polynomial_eval_monotone I hn) + have hinput : r+weight (r,x) ≤R.eval z := by + have hw:=weight_nat_numeric r + simp only [weight_prod,R,Polynomial.eval_add,Polynomial.eval_mul,Polynomial.eval_X,Polynomial.eval_ofNat] + omega + have hrep := (hu (r,x)).trans (polynomial_eval_monotone u hinput) + have hwrep : weight (List.replicate r x)≤B.eval z := by + rw [weight_replicate] + simp only [B,Polynomial.eval_add,Polynomial.eval_mul,Polynomial.eval_X,Polynomial.eval_one] + nlinarith + have ht : ∀ a∈List.replicate r x,OnlineGuard.trialRealizer.cost a+(OnlineGuard.trial a).worst weight≤B.eval z := by + intro a ha + have he: a=x := (List.mem_replicate.mp ha).2 + rw [he] + exact ((hq G f hf p).trans (polynomial_eval_monotone q hn)).trans (by + simp only [B,Polynomial.eval_add,Polynomial.eval_mul,Polynomial.eval_X,Polynomial.eval_one];omega) + have htrav:=hs (List.replicate r x) (B.eval z) hwrep ht + have htrial : trialsRealizer.cost (r,x)+(trials (r,x)).worst weight≤T.eval z := by + change repeatInputRealizer.cost (r,x)+(OnlineTree.traverse OnlineGuard.trialRealizer).cost (List.replicate r x)+ + (OnlineTree.traverseM OnlineGuard.trial (List.replicate r x)).worst weight≤_ + simp only [T,Polynomial.eval_add,Polynomial.eval_comp] + change repeatInputRealizer.cost (r,x)+weight (List.replicate r x)≤u.eval (R.eval z) at hrep + omega + have htail : (trials (r,x)).worst (fun as=>OnlineMedian.medianRealizer.cost as+weight (OnlineMedian.median as))≤v.eval (T.eval z) := by + apply Experiment.worst_le _ _ _ + exact (Experiment.all_worst (trials (r,x)) weight).mono (fun as hw=>(hv as).trans + (polynomial_eval_monotone v (hw.trans (by omega)))) + have hcost : (trials (r,x)).worst OnlineMedian.medianRealizer.cost≤v.eval (T.eval z) := + (Experiment.worst_mono _ _ _ ((Experiment.all_true _).mono (fun _ _=>Nat.le_add_right _ _))).trans htail + have hout : (trials (r,x)).worst (weight ∘ OnlineMedian.median)≤v.eval (T.eval z) := + (Experiment.worst_mono _ _ _ ((Experiment.all_true _).mono (fun _ _=>Nat.le_add_left _ _))).trans htail + + have hboth : (trials (r,x)).worst OnlineMedian.medianRealizer.cost+ + (trials (r,x)).worst (weight ∘ OnlineMedian.median)≤2*v.eval (T.eval z) := by omega + + clear hcost hout htail + change trialsRealizer.cost (r,x)+(trials (r,x)).worst OnlineMedian.medianRealizer.cost+ + (run (r,x)).worst weight≤_ + rw [run,Experiment.worst_map] + simp only [Polynomial.eval_add,Polynomial.eval_mul,Polynomial.eval_ofNat,Polynomial.eval_comp] + change _ ≤ T.eval z+2*v.eval (T.eval z) + omega +end MatchingFPRAS.OnlineAmplification + +end OAI diff --git a/lean/OAI/Combinatorics/MatchingCount/Complexity/OnlineSampleCost.lean b/lean/OAI/Combinatorics/MatchingCount/Complexity/OnlineSampleCost.lean new file mode 100644 index 0000000000000000000000000000000000000000..b49285399c12817b67ccd88ecef13d8910d45777 --- /dev/null +++ b/lean/OAI/Combinatorics/MatchingCount/Complexity/OnlineSampleCost.lean @@ -0,0 +1,197 @@ +import Mathlib +import OAI.Combinatorics.MatchingCount.Sampling.OnlineSample +import OAI.Combinatorics.MatchingCount.Complexity.OnlineWordCost +import OAI.Combinatorics.MatchingCount.Complexity.OnlineTraverseCost + +namespace OAI + +namespace MatchingFPRAS.OnlineSample +open TreeTyped PhysicalStream Polynomial + +variable {A B : Type} [Codec A] [Codec B] +lemma work_repeatInput : TreeTyped.WorkBound (repeatInputRealizer (A:=A)) (fun x=>x.1+weight x) := by + unfold repeatInputRealizer + apply TreeTyped.work_congr + apply TreeTyped.work_then_polynomial _ (polynomial_mapWith polynomial_first) + apply TreeTyped.work_pair _ _ X (by intro x; simp only [Polynomial.eval_X];omega) + · exact TreeTyped.work_of_polynomial polynomial_second X (fun x=>by simp only [Polynomial.eval_X];omega) + · apply TreeTyped.work_composition + (TreeTyped.work_of_polynomial polynomial_first X (fun x=>by simp only [Polynomial.eval_X];omega)) + range_numeric_work X + intro x + simp only [Polynomial.eval_X,id_eq] + omega + +def mass (m : A→ℕ) (as : List A) : ℕ := weight as+(as.map m).sum +lemma weight_le_mass (m : A→ℕ) (as : List A) : weight as ≤ mass m as := Nat.le_add_right _ _ +lemma mass_mem (m : A→ℕ) (as : List A) (a : A) (ha : a∈as) : m a ≤ mass m as := + by + have h : m a ≤ (as.map m).sum := by + induction as with + | nil => simp at ha + | cons b bs ih => + simp only [List.mem_cons] at ha + simp only [List.map_cons,List.sum_cons] + rcases ha with rfl | ha + · omega + · have := ih ha;omega + unfold mass;omega +lemma weight_replicate (n : ℕ) (a : A) : weight (List.replicate n a)=n*(1+weight a)+1 := by + induction n with + | zero => simp + | succ n ih => rw [List.replicate_succ,weight_cons,ih,Nat.succ_mul];omega +lemma mass_replicate (m : A→ℕ) (n : ℕ) (a : A) : + mass m (List.replicate n a)=n*(1+weight a+m a)+1 := by + simp only [mass,weight_replicate,List.map_replicate,List.sum_replicate,Nat.nsmul_eq_mul] + ring +lemma work_traverse_mass {f : A→Experiment B} {F : OnlineTree.Realizer f} {m : A→ℕ} + (hF : OnlineTree.WorkBound F m) : OnlineTree.WorkBound (OnlineTree.traverse F) (mass m) := + OnlineTree.work_traverse hF X X (by intro as;simpa using weight_le_mass m as) + (by intro as a ha;simpa using mass_mem m as a ha) + +def repeatMeasure (m : A→ℕ) (x : ℕ×A) : ℕ := x.1+weight x+m x.2 +lemma work_repeat {f : A→Experiment B} {F : OnlineTree.Realizer f} {m : A→ℕ} + (hF : OnlineTree.WorkBound F m) : OnlineTree.WorkBound + (OnlineTree.composition (OnlineTree.deterministic repeatInputRealizer) (OnlineTree.traverse F)) + (repeatMeasure m) := by + apply OnlineTree.work_composition + (OnlineTree.work_deterministic (TreeTyped.work_remeasure work_repeatInput X + (fun x=>by simp only [Polynomial.eval_X,repeatMeasure];omega))) (work_traverse_mass hF) (X*(X+1)+1) + intro x + change mass m (List.replicate x.1 x.2) ≤ _ + rw [mass_replicate] + simp only [Polynomial.eval_add,Polynomial.eval_mul,Polynomial.eval_X,Polynomial.eval_one] + have hx : x.1 ≤ repeatMeasure m x := by unfold repeatMeasure;omega + have hw : weight x.2+m x.2 ≤ repeatMeasure m x := by + have := weight_snd x;unfold repeatMeasure;omega + nlinarith + +def pairMeasure (x : ℕ×ℕ) : ℕ := x.1+x.2+weight x +lemma work_firstWord : OnlineTree.WorkBound + (OnlineTree.composition (OnlineTree.deterministic (TreeTyped.first (A:=ℕ) (B:=ℕ))) OnlineWord.naturalRealizer) + pairMeasure := by + apply OnlineTree.work_composition + (OnlineTree.work_deterministic (TreeTyped.work_of_polynomial polynomial_first X + (fun x=>by simp [pairMeasure]))) OnlineWord.work_natural X + intro x + change x.1+weight x.1 ≤ _ + simp only [Polynomial.eval_X,pairMeasure] + have := weight_fst x + omega +lemma work_words : OnlineTree.WorkBound wordsRealizer pairMeasure := by + unfold wordsRealizer + apply OnlineTree.work_congr + apply OnlineTree.work_composition + (OnlineTree.work_deterministic (TreeTyped.work_composition + (TreeTyped.work_of_polynomial (polynomial_pair polynomial_second polynomial_first) X + (fun x=>by simp [pairMeasure])) work_repeatInput (2*X+1) (by + intro x;simp only [Polynomial.eval_add,Polynomial.eval_mul,Polynomial.eval_ofNat,Polynomial.eval_X, + Polynomial.eval_one] + simp only [pairMeasure,weight_prod];have := weight_fst x;have := weight_snd x;omega))) + (work_traverse_mass OnlineWord.work_natural) (X*(2*X+1)+1) + intro x + change mass (fun n=>n+weight n) (List.replicate x.2 x.1) ≤ _ + rw [mass_replicate] + simp only [Polynomial.eval_add,Polynomial.eval_mul,Polynomial.eval_X,Polynomial.eval_one,Polynomial.eval_ofNat] + have h1 : x.2 ≤ pairMeasure x := by unfold pairMeasure;omega + have h2 : weight x.1+x.1+weight x.1 ≤ 2*pairMeasure x := by have := weight_fst x;unfold pairMeasure;omega + + have h := Nat.mul_le_mul h1 (show 1+weight x.1+(x.1+weight x.1) ≤ 2*pairMeasure x+1 by omega) + nlinarith +lemma work_local : OnlineTree.WorkBound localRealizer pairMeasure := by + unfold localRealizer + exact OnlineTree.work_pair work_firstWord work_words X (fun x=>by simp [pairMeasure]) +lemma work_scan : OnlineTree.WorkBound scanRealizer pairMeasure := by + unfold scanRealizer + exact OnlineTree.work_pair work_firstWord work_local X (fun x=>by simp [pairMeasure]) + +def scansMeasure (x : (ℕ×ℕ)×ℕ) : ℕ := pairMeasure x.1+x.2+weight x +lemma work_scans : OnlineTree.WorkBound scansRealizer scansMeasure := by + unfold scansRealizer + apply OnlineTree.work_congr + apply OnlineTree.work_composition + (OnlineTree.work_deterministic (TreeTyped.work_composition + (TreeTyped.work_of_polynomial (polynomial_pair polynomial_second polynomial_first) X + (fun x=>by simp [scansMeasure])) work_repeatInput (2*X+1) (by + intro x + simp only [Polynomial.eval_add,Polynomial.eval_mul,Polynomial.eval_ofNat,Polynomial.eval_X,Polynomial.eval_one] + simp only [scansMeasure,weight_prod] + have := weight_fst x;have := weight_snd x;omega))) + (work_traverse_mass work_scan) (X*(2*X+1)+1) + intro x + change mass pairMeasure (List.replicate x.2 x.1) ≤ _ + rw [mass_replicate] + simp only [Polynomial.eval_add,Polynomial.eval_mul,Polynomial.eval_X,Polynomial.eval_one,Polynomial.eval_ofNat] + have h1 : x.2 ≤ scansMeasure x := by unfold scansMeasure;omega + have h2 : weight x.1+pairMeasure x.1 ≤ 2*scansMeasure x := by + have := weight_fst x;unfold scansMeasure;omega + have h := Nat.mul_le_mul h1 (show 1+weight x.1+pairMeasure x.1 ≤ 2*scansMeasure x+1 by omega) + omega + +def markMeasure (x : ℕ×ℕ) : ℕ := x.2+weight x +lemma work_markWord : OnlineTree.WorkBound markWordRealizer markMeasure := by + apply OnlineTree.work_mapSecond OnlineWord.work_natural X X + · intro x;simp only [Polynomial.eval_X,markMeasure];have := weight_snd x;omega + · intro x;simp only [Polynomial.eval_X,markMeasure];have := weight_fst x;omega +omit [Codec A] in +lemma sum_map_le (m : A→ℕ) (as : List A) (M : ℕ) (h : ∀ a∈as,m a ≤ M) : + (as.map m).sum ≤ as.length*M := by + induction as with + | nil => simp + | cons a as ih => + have h1 := h a (by simp) + have h2 := ih (fun a ha=>h a (by simp [ha])) + simp only [List.length_cons,List.map_cons,List.sum_cons,Nat.add_mul,Nat.one_mul] + omega +lemma mass_le (m : A→ℕ) (as : List A) (M : ℕ) (hw : weight as ≤ M) (h : ∀ a∈as,m a ≤ M) : + mass m as ≤ M*(M+1) := by + have h1 := sum_map_le m as M h + have h2 := Nat.mul_le_mul_right M ((list_length_le_weight as).trans hw) + unfold mass + nlinarith + +def marksMeasure (x : ℕ×List ℕ) : ℕ := x.1+weight x +lemma work_marks : OnlineTree.WorkBound marksRealizer marksMeasure := by + have hp : TreeTyped.PolynomialTime markRequestsRealizer := polynomial_congr _ + (polynomial_mapWith (polynomial_pair polynomial_second polynomial_first)) + obtain ⟨p,hp'⟩ := hp + have hp : TreeTyped.PolynomialTime markRequestsRealizer := ⟨p,hp'⟩ + apply OnlineTree.work_composition + (OnlineTree.work_deterministic (TreeTyped.work_of_polynomial hp X (fun x=>by simp [marksMeasure]))) + (work_traverse_mass work_markWord) ((p+X)*((p+X)+1)) + intro x + simp only [Polynomial.eval_add,Polynomial.eval_mul,Polynomial.eval_X,Polynomial.eval_one] + apply mass_le + · have hw : weight (markRequests x) ≤ p.eval (marksMeasure x) := + (Nat.le_add_left _ _).trans ((hp' x).trans (polynomial_eval_monotone p (by unfold marksMeasure;omega))) + omega + · intro a ha + have hw := weight_mem ha + have hb : weight (markRequests x) ≤ p.eval (marksMeasure x) := + (Nat.le_add_left _ _).trans ((hp' x).trans (polynomial_eval_monotone p (by unfold marksMeasure;omega))) + obtain ⟨i,hi,rfl⟩ := List.mem_map.mp ha + unfold marksMeasure at hb + unfold markMeasure marksMeasure + dsimp only + omega + +def requestMeasure (x : Request) : ℕ := scansMeasure x.1+marksMeasure x.2+weight x +lemma work_sample : OnlineTree.WorkBound sampleRealizer requestMeasure := by + unfold sampleRealizer + apply OnlineTree.work_pair _ _ X (fun x=>by simp [requestMeasure]) + · apply OnlineTree.work_composition + (OnlineTree.work_deterministic (TreeTyped.work_of_polynomial polynomial_first X + (fun x=>by simp [requestMeasure]))) work_scans X + intro x + simp only [Experiment.All,Polynomial.eval_X] + unfold requestMeasure;omega + · apply OnlineTree.work_composition + (OnlineTree.work_deterministic (TreeTyped.work_of_polynomial polynomial_second X + (fun x=>by simp [requestMeasure]))) work_marks X + intro x + simp only [Experiment.All,Polynomial.eval_X] + unfold requestMeasure;omega +lemma work_many : OnlineTree.WorkBound manyRealizer (repeatMeasure requestMeasure) := work_repeat work_sample +end MatchingFPRAS.OnlineSample + +end OAI diff --git a/lean/OAI/Combinatorics/MatchingCount/Complexity/OnlineScheduleCost.lean b/lean/OAI/Combinatorics/MatchingCount/Complexity/OnlineScheduleCost.lean new file mode 100644 index 0000000000000000000000000000000000000000..133a6b5eefb701ecec7a75778976dd2578085c22 --- /dev/null +++ b/lean/OAI/Combinatorics/MatchingCount/Complexity/OnlineScheduleCost.lean @@ -0,0 +1,70 @@ +import Mathlib +import OAI.Combinatorics.MatchingCount.Algorithm.OnlineLadderSchedule +import OAI.Combinatorics.MatchingCount.Complexity.OnlineRequestCost + +namespace OAI + +namespace MatchingFPRAS.TreeTyped +open NumericBounds + +variable {A B C : Type} [Codec A] [Codec B] [Codec C] +lemma work_comp_bound {f : A→B} {g : B→C} {F : Realizer f} {G : Realizer g} + {m : A→ℕ} {n : B→ℕ} (hF : WorkBound F m) (hG : WorkBound G n) + (h : Bound (n ∘ f) m) : WorkBound (composition F G) m := by + obtain ⟨p,hp⟩:=h + exact work_composition hF hG p hp +lemma work_lift_bound {f : A→B} {F : Realizer f} {m : A→ℕ} + (hF : PolynomialTime F) (h : Bound weight m) : WorkBound F m := by + obtain ⟨p,hp⟩:=h + exact work_of_polynomial hF p hp +lemma work_remeasure_bound {f : A→B} {F : Realizer f} {m n : A→ℕ} + (hF : WorkBound F m) (h : Bound m n) : WorkBound F n := by + obtain ⟨p,hp⟩:=h + exact work_remeasure hF p hp +end MatchingFPRAS.TreeTyped + +namespace MatchingFPRAS.OnlineSchedule +open TreeTyped TreeFraction Polynomial NumericBounds ExecutableSource Transport + +def vertexMeasure (x : ℕ×ℕ) : ℕ := x.1+x.2+TreeTyped.weight x +lemma work_vertexNumber : WorkBound vertexNumberRealizer vertexMeasure := by + have lift {A : Type} [Codec A] {f : (ℕ×ℕ)→A} {F : Realizer f} (hF : PolynomialTime F) : + WorkBound F vertexMeasure := work_of_polynomial hF X (fun x=>by simp [vertexMeasure]) + unfold vertexNumberRealizer + apply work_then_polynomial _ polynomial_listLength + apply work_then_polynomial _ polynomial_vertices + apply work_pair _ _ X (fun x=>by simp [vertexMeasure]) + · exact work_composition (lift polynomial_first) range_numeric_work X (by + intro x;simp only [Polynomial.eval_X,id_eq];unfold vertexMeasure;omega) + · apply work_fuelAfter (lift (polynomial_addNat + (polynomial_mulNat (polynomial_constant _) polynomial_second) (polynomial_constant _))) (2*X+2) + intro x + simp only [Polynomial.eval_add,Polynomial.eval_mul,Polynomial.eval_ofNat,Polynomial.eval_X] + change 2*x.2+2 ≤ 2*vertexMeasure x+2 + unfold vertexMeasure;omega + +def ladderMeasure (x : LadderInput) : ℕ := x.1.1+x.1.2+x.2+TreeTyped.weight x +lemma work_ladderSearchInput : WorkBound ladderSearchInputRealizer ladderMeasure := by + have lift {A : Type} [Codec A] {f : LadderInput→A} {F : Realizer f} (hF : PolynomialTime F) : + WorkBound F ladderMeasure := work_of_polynomial hF X (fun x=>by simp [ladderMeasure]) + unfold ladderSearchInputRealizer + apply work_pair _ _ X (fun x=>by simp [ladderMeasure]) + · apply work_then_polynomial _ polynomial_ladderPowerPlan + apply work_pair (lift polynomial_first) _ X (fun x=>by simp [ladderMeasure]) + apply work_fuelAfter (lift polynomial_second) X + intro x;simp only [Polynomial.eval_X];unfold ladderMeasure;omega + · apply work_fuelAfter (lift polynomial_tierBound) (X^2*(X+2*X+2)) + intro x + have hn : x.1.1 ≤ ladderMeasure x := by unfold ladderMeasure;omega + have hd : x.1.2 ≤ ladderMeasure x := by unfold ladderMeasure;omega + have hk : x.2 ≤ ladderMeasure x := by unfold ladderMeasure;omega + have hb:=NumericBounds.clog_le x.1.2 + simp only [Polynomial.eval_mul,Polynomial.eval_pow,Polynomial.eval_add,Polynomial.eval_X,Polynomial.eval_ofNat] + change tierBound x.1.1 x.1.2 x.2 ≤ _ + unfold tierBound + gcongr; omega +lemma work_ladderSchedule : WorkBound ladderScheduleRealizer ladderMeasure := + work_then_polynomial work_ladderSearchInput polynomial_findPower +end MatchingFPRAS.OnlineSchedule + +end OAI diff --git a/lean/OAI/Combinatorics/MatchingCount/Complexity/OnlineStageCost.lean b/lean/OAI/Combinatorics/MatchingCount/Complexity/OnlineStageCost.lean new file mode 100644 index 0000000000000000000000000000000000000000..74da412c27958688b471000a47a1045d2548d718 --- /dev/null +++ b/lean/OAI/Combinatorics/MatchingCount/Complexity/OnlineStageCost.lean @@ -0,0 +1,103 @@ +import Mathlib +import OAI.Combinatorics.MatchingCount.Algorithm.OnlineGuard +import OAI.Combinatorics.MatchingCount.Complexity.OnlineRequestCost + +namespace OAI + +namespace MatchingFPRAS.OnlineTree +open TreeTyped PhysicalStream Polynomial NumericBounds + +variable {A B C : Type} [Codec A] [Codec B] [Codec C] +lemma work_precompose {f : A→B} {g : B→Experiment C} {F : TreeTyped.Realizer f} {G : Realizer g} + {m : A→ℕ} {n : B→ℕ} (hF : TreeTyped.WorkBound F m) (hG : WorkBound G n) + (h : Bound (n ∘ f) m) : WorkBound (composition (deterministic F) G) m := by + obtain ⟨p,hp⟩:=h + exact work_composition (work_deterministic hF) hG p (fun a=>hp a) +lemma work_from_weight {f : A→Experiment B} {F : Realizer f} {m : A→ℕ} + (hF : PolynomialTime F) (h : Bound weight m) : WorkBound F m := by + obtain ⟨p,hp⟩:=h + exact work_of_polynomial hF p hp +end MatchingFPRAS.OnlineTree + +namespace MatchingFPRAS.OnlineStage +open TreeTyped PhysicalStream Polynomial NumericBounds OnlineSample + +def inputSize (x : Input) : ℕ := repeatMeasure requestMeasure x.2+weight x +lemma work_execute : OnlineTree.WorkBound executeRealizer inputSize := by + unfold executeRealizer + apply OnlineTree.work_congr + apply OnlineTree.work_then_polynomial + · apply OnlineTree.work_pair _ _ X (fun x=>by simp [inputSize]) + · apply OnlineTree.work_deterministic + exact work_of_polynomial polynomial_first X (fun x=>by simp [inputSize]) + · apply OnlineTree.work_precompose + (work_of_polynomial polynomial_second X (fun x=>by simp [inputSize])) work_many + exact of_le (fun x=>by simp only [Function.comp_apply]; unfold inputSize;omega) + · exact OnlineTree.work_deterministic ExecutableSource.polynomial_sparseStage +end MatchingFPRAS.OnlineStage + +namespace MatchingFPRAS.OnlineTrial +open TreeTyped PhysicalStream Polynomial NumericBounds OnlineSchedule OnlineSample + +def stateSize (x : State) : ℕ := requestSize x.1+weight x +lemma weight_le_stateSize (x : State) : weight x ≤ stateSize x := by unfold stateSize;omega +lemma bound_prepare : Bound (OnlineStage.inputSize ∘ prepare) requestSize := by + have hw:=NumericBounds.weight (work_of_polynomial polynomial_prepare X + (fun x=>by simpa using weight_le_requestSize x)) + have hs : Bound (fun x : RequestInput=>x.2) requestSize := of_le (fun x=>by unfold requestSize;omega) + have hm:=bound_sourceRequest + exact add (add (add hs (mono hw (fun x=>weight_snd (prepare x)))) hm) hw +lemma work_step : OnlineTree.WorkBound stepRealizer stateSize := by + unfold stepRealizer + apply OnlineTree.work_congr + apply OnlineTree.work_then_polynomial + · apply OnlineTree.work_pair _ _ X (fun x=>by simpa using weight_le_stateSize x) + · apply OnlineTree.work_deterministic + exact work_of_polynomial polynomial_identity X (fun x=>by simpa using weight_le_stateSize x) + · apply OnlineTree.work_precompose + (work_of_polynomial (polynomial_composition polynomial_first polynomial_prepare) X + (fun x=>by simpa using weight_le_stateSize x)) OnlineStage.work_execute + exact NumericBounds.comp (f:=Prod.fst) (g:=OnlineStage.inputSize ∘ prepare) bound_prepare + (of_le (fun x=>by simp only [Function.comp_apply]; unfold stateSize;omega)) + · exact OnlineTree.work_deterministic polynomial_carry +lemma work_body : OnlineTree.WorkBound bodyRealizer (fun x=>stateSize x.2+weight x) := by + unfold bodyRealizer + apply OnlineTree.work_congr + apply OnlineTree.work_precompose + (work_of_polynomial polynomial_second X (fun x=>by simp)) work_step + exact of_le (fun x=>by dsimp;omega) +end MatchingFPRAS.OnlineTrial + +namespace MatchingFPRAS.OnlineGuard +open TreeTyped PhysicalStream Polynomial NumericBounds OnlineSchedule OnlineSample + +lemma bound_testRequest : Bound (fun x : RequestInput=>repeatMeasure requestMeasure (16,sourceRequest x)) requestSize := by + have hw := NumericBounds.weight (work_of_polynomial polynomial_sourceRequest X + (fun x=>by simpa using weight_le_requestSize x)) + simp only [repeatMeasure,weight_prod] + exact add (add (const 16 _) (add (const (1+weight (16:ℕ)) _) hw)) bound_sourceRequest +lemma work_test : OnlineTree.WorkBound testRealizer requestSize := by + unfold testRealizer + apply OnlineTree.work_congr + apply OnlineTree.work_then_polynomial + · apply OnlineTree.work_pair _ _ X (fun x=>by simpa using weight_le_requestSize x) + · exact OnlineTree.work_deterministic (work_of_polynomial polynomial_first X + (fun x=>by simpa using weight_le_requestSize x)) + · exact OnlineTree.work_precompose (work_of_polynomial + (polynomial_pair (polynomial_constant _) polynomial_sourceRequest) X + (fun x=>by simpa using weight_le_requestSize x)) work_many bound_testRequest + · exact OnlineTree.work_deterministic polynomial_accept +lemma work_checked : OnlineTree.WorkBound checkedRealizer OnlineTrial.stateSize := by + unfold checkedRealizer + apply OnlineTree.work_congr + apply OnlineTree.work_then_polynomial + · apply OnlineTree.work_pair _ _ X (fun x=>by simpa using OnlineTrial.weight_le_stateSize x) + · exact OnlineTree.work_deterministic (work_of_polynomial polynomial_second X + (fun x=>by simpa using OnlineTrial.weight_le_stateSize x)) + · exact OnlineTree.work_precompose (work_of_polynomial polynomial_first X + (fun x=>by simpa using OnlineTrial.weight_le_stateSize x)) work_test + (of_le (fun x=>by simp only [Function.comp_apply]; unfold OnlineTrial.stateSize;omega)) + · exact OnlineTree.work_deterministic polynomial_finish +end MatchingFPRAS.OnlineGuard + +end OAI diff --git a/lean/OAI/Combinatorics/MatchingCount/Complexity/OnlineTraverseCost.lean b/lean/OAI/Combinatorics/MatchingCount/Complexity/OnlineTraverseCost.lean new file mode 100644 index 0000000000000000000000000000000000000000..fed102876ff1eb38250445649d495732bd8da04f --- /dev/null +++ b/lean/OAI/Combinatorics/MatchingCount/Complexity/OnlineTraverseCost.lean @@ -0,0 +1,96 @@ +import Mathlib +import OAI.Combinatorics.MatchingCount.Machines.OnlineTraverse +import OAI.Combinatorics.MatchingCount.Complexity.OnlineFrameCost +import OAI.Combinatorics.MatchingCount.Complexity.OnlineFoldCost + +namespace OAI + +namespace MatchingFPRAS.OnlineTree +open TreeTyped PhysicalStream Polynomial + +variable {A B : Type} [Codec A] [Codec B] +lemma collectStep_cost {f : A→Experiment B} (F : Realizer f) (a : A) (bs : List B) : + (collectStepRealizer F).cost (a,bs)=F.cost a+54*weight a+46*weight bs+ + 26*(f a).worst weight+201 := by + change (pair (composition (deterministic TreeTyped.first) F) (deterministic TreeTyped.second)).cost (a,bs)+ + (((f a).bind (fun b=>Experiment.done (b,bs))).worst (fun _=>1))=_ + rw [pair_cost,Experiment.worst_const] + simp only [composition,deterministic,TreeTyped.first,TreeTyped.second,Experiment.worst, + Experiment.bind,weight_prod] + change (6*weight a+weight bs+11+F.cost a)+(3*weight a+7)+45*(1+weight a+weight bs)+ + 26*(f a).worst weight+137+1=_ + omega + +lemma traverse_bound {f : A→Experiment B} (F : Realizer f) : + ∃ p : Polynomial ℕ,∀ as M,weight as≤M→(∀ a∈as,F.cost a+(f a).worst weight≤M)→ + (traverse F).cost as+(traverseM f as).worst weight≤p.eval M := by + obtain ⟨q,hq⟩:=TreeTyped.polynomial_pair (TreeTyped.polynomial_identity (A:=List A)) + (TreeTyped.polynomial_constant ([] : List B)) + obtain ⟨r,hr⟩:=TreeTyped.polynomial_reverse (A:=B) + let H : Polynomial ℕ := X*(X+1)+1 + let D : Polynomial ℕ := 27*X+54*X+46*H+201 + refine ⟨q+X*(D+14*X+34)+10+r.comp H+H,?_⟩ + intro as M hw ht + have hl : as.length≤M := (list_length_le_weight as).trans hw + have hH : H.eval M=M*(M+1)+1 := by simp [H] + have hD : D.eval M=27*M+54*M+46*H.eval M+201 := by simp [D] + have hf := fold_cost_bound (collectStep f) (collectStepRealizer F).cost as ([] : List B) + (fun k bs=>weight bs+k*(M+1)≤as.length*(M+1)+1) (D.eval M) M + (by simp; omega) hw + (by + intro a ha k _bounded bs hb + rw [collectStep,Experiment.all_map] + exact (Experiment.all_worst (f a) weight).mono (fun c hc=>by + have hc':=ht a ha + simp only [weight_cons,Nat.add_mul,Nat.one_mul] at * + omega)) + (by + intro a ha k _bounded bs hb + rw [collectStep_cost] + have ha':=(weight_mem ha).trans hw + have hc':=ht a ha + have hmul:=Nat.mul_le_mul_right (M+1) hl + rw [hD,hH] + omega) + have hout : (foldM (collectStep f) as []).All (fun bs=>weight bs≤H.eval M) := + hf.2.mono (fun bs hb=>by + have hmul:=Nat.mul_le_mul_right (M+1) hl + rw [hH];simp only [Nat.zero_mul,Nat.add_zero] at hb;omega) + have hrev : (foldM (collectStep f) as []).worst TreeTyped.reverse.cost≤r.eval (H.eval M) := by + apply Experiment.worst_le _ _ _ + exact hout.mono (fun bs hb=>(Nat.le_add_right _ _).trans + ((hr bs).trans (polynomial_eval_monotone r hb))) + have hfinal : (traverseM f as).worst weight≤H.eval M := by + apply Experiment.worst_le _ _ _ + apply Experiment.all_of_mean_eq (p:=(foldM (collectStep f) as []).map List.reverse) + (fun h=>by + rw [Experiment.mean_map,mean_fold_collect] + simp only [List.append_nil,List.reverse_reverse]) _ + rw [Experiment.all_map] + exact hout.mono (fun bs hb=>by simpa only [weight_reverse] using hb) + have hpre:=(hq as).trans (polynomial_eval_monotone q hw) + dsimp only at hpre + have hmul:=Nat.mul_le_mul_right (D.eval M+14*M+34) hl + change (TreeTyped.pair TreeTyped.identity (TreeTyped.constant ([] : List B))).cost as+ + Fold.cost (collectStep f) (collectStepRealizer F).cost as []+ + (foldM (collectStep f) as []).worst TreeTyped.reverse.cost+(traverseM f as).worst weight≤_ + simp only [Polynomial.eval_add,Polynomial.eval_mul,Polynomial.eval_X,Polynomial.eval_ofNat,Polynomial.eval_comp] + omega + +lemma work_traverse {f : A→Experiment B} {F : Realizer f} {m : A→ℕ} {n : List A→ℕ} + (hF : WorkBound F m) (p q : Polynomial ℕ) + (hw : ∀ as,weight as≤p.eval (n as)) (hm : ∀ as,∀ a∈as,m a≤q.eval (n as)) : + WorkBound (traverse F) n := by + obtain ⟨r,hr⟩:=hF + obtain ⟨s,hs⟩:=traverse_bound F + refine ⟨s.comp (p+r.comp q),fun as=>?_⟩ + simp only [Polynomial.eval_comp,Polynomial.eval_add] + apply hs + · exact (hw as).trans (Nat.le_add_right _ _) + · intro a ha + exact ((hr a).trans (polynomial_eval_monotone r (hm as a ha))).trans (Nat.le_add_left _ _) +lemma polynomial_traverse {f : A→Experiment B} {F : Realizer f} (hF : PolynomialTime F) : + PolynomialTime (traverse F) := work_traverse hF X X (by simp) (by intro as a ha;simpa using weight_mem ha) +end MatchingFPRAS.OnlineTree + +end OAI diff --git a/lean/OAI/Combinatorics/MatchingCount/Complexity/OnlineWordCost.lean b/lean/OAI/Combinatorics/MatchingCount/Complexity/OnlineWordCost.lean new file mode 100644 index 0000000000000000000000000000000000000000..34cefbd195729bf98a408c25c370748568287701 --- /dev/null +++ b/lean/OAI/Combinatorics/MatchingCount/Complexity/OnlineWordCost.lean @@ -0,0 +1,61 @@ +import Mathlib +import OAI.Combinatorics.MatchingCount.Tapes.OnlineWord +import OAI.Combinatorics.MatchingCount.Complexity.OnlineFrameCost +import OAI.Combinatorics.MatchingCount.Complexity.OnlineFoldCost + +namespace OAI + +namespace MatchingFPRAS.OnlineWord +open TreeTyped OnlineTree PhysicalStream Polynomial + +lemma polynomial_step : OnlineTree.PolynomialTime stepRealizer := by + unfold stepRealizer + apply OnlineTree.work_congr + apply OnlineTree.polynomial_choose <;> apply OnlineTree.polynomial_deterministic <;> + apply TreeTyped.polynomial_composition <;> first | exact TreeTyped.polynomial_listCons | + exact TreeTyped.polynomial_pair (TreeTyped.polynomial_constant _) TreeTyped.polynomial_second + +lemma weight_bools (bs : List Bool) : weight bs≤4*bs.length+1 := by + induction bs with + | nil => simp + | cons b bs ih => have hb:=TreeTyped.weight_bool b; simp only [weight_cons,List.length_cons];omega +lemma all_weight (n : ℕ) (acc : List Bool) : + (prepend n acc).All (fun bs=>weight bs≤4*(n+acc.length)+1) := + (all_length n acc).mono (fun bs hb=>by rw [←hb]; exact weight_bools bs) + +lemma polynomial_list : OnlineTree.PolynomialTime listRealizer := by + obtain ⟨p,hp⟩:=polynomial_step + have prep := TreeTyped.polynomial_pair (TreeTyped.polynomial_identity (A:=List ℕ)) + (TreeTyped.polynomial_constant ([] : List Bool)) + obtain ⟨q,hq⟩:=prep + refine ⟨q+X*((p.comp (5*X+2))+14*X+34)+4*X+11,fun as=>?_⟩ + let S:=weight as + have hlen : as.length≤S := list_length_le_weight as + have bound := OnlineTree.fold_cost_bound step stepRealizer.cost as ([] : List Bool) + (fun k bs=>bs.length+k=as.length) (p.eval (5*S+2)) S (by simp) le_rfl + (by + intro a ha k hk bs hb + simp only [step,Experiment.All,List.length_cons] + constructor <;> omega) + (by + intro a ha k hk bs hb + have ha' : weight a≤S := weight_mem ha + have hbs:=weight_bools bs + have hw : weight (a,bs)≤5*S+2 := by rw [weight_prod];omega + exact (Nat.le_add_right _ _).trans ((hp (a,bs)).trans (polynomial_eval_monotone p hw))) + have hlenmul := Nat.mul_le_mul_right (p.eval (5*S+2)+14*S+34) hlen + have hout := Experiment.worst_le _ _ _ (all_weight as.length []) + have hpre:=hq as + change (TreeTyped.pair TreeTyped.identity (TreeTyped.constant ([] : List Bool))).cost as+ + OnlineTree.Fold.cost step stepRealizer.cost as []+(prepend as.length []).worst weight≤_ + simp only [Polynomial.eval_add,Polynomial.eval_mul,Polynomial.eval_comp,Polynomial.eval_X,Polynomial.eval_ofNat] + dsimp [S] at * + omega + +lemma work_natural : OnlineTree.WorkBound naturalRealizer (fun n=>n+weight n) := by + apply OnlineTree.work_congr + apply OnlineTree.work_then_polynomial _ polynomial_list + exact OnlineTree.work_deterministic (TreeTyped.work_remeasure TreeTyped.range_numeric_work X (fun n=>by simp)) +end MatchingFPRAS.OnlineWord + +end OAI diff --git a/lean/OAI/Combinatorics/MatchingCount/Complexity/OriginalCost.lean b/lean/OAI/Combinatorics/MatchingCount/Complexity/OriginalCost.lean new file mode 100644 index 0000000000000000000000000000000000000000..fd23f34b2a778c9359ed1fcdfb1d51af3c826207 --- /dev/null +++ b/lean/OAI/Combinatorics/MatchingCount/Complexity/OriginalCost.lean @@ -0,0 +1,93 @@ +import Mathlib +import OAI.Combinatorics.MatchingCount.Algorithm.AlgorithmLaw +import OAI.Combinatorics.MatchingCount.Complexity.ComputeCost + +namespace OAI + +namespace MatchingFPRAS.LiteralAlgorithm +open TreeTyped TreeFraction PhysicalStream LiteralInput Polynomial + +lemma count_cost (a : Parsed) : countRealizer.cost a= + (pair emptyRealizer identity).cost a+ + (if empty a then (constant ((1,1) : Fraction)).cost a else + (pair invalidRealizer identity).cost a+ + (if invalid a then (constant ((0,1) : Fraction)).cost a else computeRealizer.cost a)+30)+30 := by + simp only [countRealizer,OnlineTree.Realizer.congr,OnlineTree.conditional, + OnlineTree.composition,OnlineTree.deterministic,Experiment.worst,OnlineTree.caseBool,id_eq] + split <;> omega +lemma algorithm_cost (as : List Symbol) : algorithmRealizer.cost as= + parseInputRealizer.cost as+countRealizer.cost (parseInput as)+ + (count (parseInput as)).worst LiteralCodec.ratWordRealizer.cost := rfl +lemma algorithm_bound : ∃ q : Polynomial ℕ,∀ (G : GraphInput) (ε δ : ℚ) + (_he : 0<ε) (_he1 : ε<1) (_hd : 0≤δ) (x : ℕ),1≤x→ + (encodeInput G ε δ).length≤x→⌈ε⁻¹⌉₊≤x→Nat.clog 2 ⌈δ⁻¹⌉₊≤x→ + algorithmRealizer.cost (encodeInput G ε δ)+(algorithm (encodeInput G ε δ)).worst weight≤q.eval x := by + obtain ⟨p,hp⟩:=polynomial_parseInput + obtain ⟨e,he⟩:=polynomial_pair polynomial_empty polynomial_identity + obtain ⟨j,hj⟩:=polynomial_pair polynomial_invalid polynomial_identity + obtain ⟨c,hc⟩:=polynomial_constant ((1,1) : Fraction) (A:=Parsed) + obtain ⟨d,hd⟩:=polynomial_constant ((0,1) : Fraction) (A:=Parsed) + obtain ⟨k,hk⟩:=compute_bound + obtain ⟨v,hv⟩:=LiteralCodec.polynomial_ratWord + let P:=p.comp (18*X+1) + let B:Polynomial ℕ:=2*X+P+1 + let Q:=e.comp P+j.comp P+c.comp P+d.comp P+k.comp B+60 + refine ⟨P+Q+2*(v.comp Q),?_⟩ + intro G ε δ hε hε1 hδ x hx hl hεx hδx + let as:=encodeInput G ε δ + let a:=parseInput as + have hparse : parseInputRealizer.cost as+weight a≤P.eval x := by + apply (hp as).trans + rw [LiteralCodec.weight_word] + simpa only [P,Polynomial.eval_comp,Polynomial.eval_add,Polynomial.eval_mul,Polynomial.eval_ofNat,Polynomial.eval_X,Polynomial.eval_one] using + polynomial_eval_monotone p (show 18*as.length+1≤18*x+1 by dsimp only [as];omega) + have hwa : weight a≤P.eval x := by omega + have hep : (pair emptyRealizer identity).cost a≤e.eval (P.eval x) := + (Nat.le_add_right _ _).trans ((he a).trans (polynomial_eval_monotone e hwa)) + have hjp : (pair invalidRealizer identity).cost a≤j.eval (P.eval x) := + (Nat.le_add_right _ _).trans ((hj a).trans (polynomial_eval_monotone j hwa)) + have hcp : (constant ((1,1) : Fraction)).cost a+weight ((1,1) : Fraction)≤c.eval (P.eval x) := + (hc a).trans (polynomial_eval_monotone c hwa) + have hdp : (constant ((0,1) : Fraction)).cost a+weight ((0,1) : Fraction)≤d.eval (P.eval x) := + (hd a).trans (polynomial_eval_monotone d hwa) + have hb : x≤B.eval x ∧ 2*x≤B.eval x ∧ P.eval x≤B.eval x := by + simp only [B,Polynomial.eval_add,Polynomial.eval_mul,Polynomial.eval_ofNat,Polynomial.eval_X,Polynomial.eval_one] + omega + have hcount : countRealizer.cost a+(count a).worst weight≤Q.eval x := by + cases hE:empty a with + | true => + rw [count_cost] + simp only [count,hE,ite_true,Experiment.worst,Q,Polynomial.eval_add,Polynomial.eval_comp,Polynomial.eval_ofNat] + omega + | false => + cases hI:invalid a with + | true => + rw [count_cost] + simp only [count,hE,hI,Bool.false_eq_true,ite_false,ite_true,Experiment.worst,Q,Polynomial.eval_add,Polynomial.eval_comp,Polynomial.eval_ofNat] + omega + | false => + have hn:=valid_two G ε δ hE hI + have hev:=valid_even G ε δ hI + let : Nontrivial (Fin G.n):=Fin.nontrivial_iff_two_le.mpr hn + have hnx : G.n≤B.eval x := (valid_size G ε δ hI).trans ((Nat.mul_le_mul_left 2 hl).trans hb.2.1) + have hcompute:=hk G hn hev ε δ hε hε1 hδ (B.eval x) (hx.trans hb.1) hnx (hεx.trans hb.1) (hδx.trans hb.1) (hwa.trans hb.2.2) + rw [count_cost] + simp only [count,hE,hI,Bool.false_eq_true,ite_false,Q,Polynomial.eval_add,Polynomial.eval_comp,Polynomial.eval_ofNat] + dsimp only [as,a] at * + omega + have hout : (count a).All (fun z=>LiteralCodec.ratWordRealizer.cost z+weight (LiteralCodec.ratWord z)≤v.eval (Q.eval x)) := + (Experiment.all_worst (count a) weight).mono (fun z hz=>(hv z).trans + (polynomial_eval_monotone v (hz.trans (by omega)))) + have htail : (count a).worst LiteralCodec.ratWordRealizer.cost≤v.eval (Q.eval x) := + Experiment.worst_le _ _ _ (hout.mono (fun z hz=>(Nat.le_add_right _ _).trans hz)) + have hword : (count a).worst (weight ∘ LiteralCodec.ratWord)≤v.eval (Q.eval x) := + Experiment.worst_le _ _ _ (hout.mono (fun z hz=>(Nat.le_add_left _ _).trans hz)) + rw [algorithm_cost] + unfold algorithm + rw [Experiment.worst_map] + simp only [Polynomial.eval_add,Polynomial.eval_mul,Polynomial.eval_ofNat,Polynomial.eval_comp] + dsimp only [a,as] at * + omega +end MatchingFPRAS.LiteralAlgorithm + +end OAI diff --git a/lean/OAI/Combinatorics/MatchingCount/Complexity/PhysicalCost.lean b/lean/OAI/Combinatorics/MatchingCount/Complexity/PhysicalCost.lean new file mode 100644 index 0000000000000000000000000000000000000000..53fe532282a4b18012375c5e25aeaecb94e765a5 --- /dev/null +++ b/lean/OAI/Combinatorics/MatchingCount/Complexity/PhysicalCost.lean @@ -0,0 +1,73 @@ +import Mathlib +import OAI.Combinatorics.MatchingCount.Machines.Wrapper +import OAI.Combinatorics.MatchingCount.Complexity.OriginalCost + +namespace OAI + +namespace MatchingFPRAS.LiteralPhysical +open Polynomial PhysicalStream TreeTyped BitComplexity LiteralPacked + +lemma polynomial_eval (p : Polynomial ℕ) : PolynomiallyBounded (fun x=>p.eval x) := by + refine Polynomial.induction_on' p ?_ ?_ + · intro p q hp hq + simpa only [Polynomial.eval_add] using hp.add hq + · intro n a + simpa only [Polynomial.eval_monomial] using (PolynomiallyBounded.const a).mul (PolynomiallyBounded.id.pow n) +lemma polynomial_budget (w H : ℕ) {f g : ℕ→ℕ} + (hf : PolynomiallyBounded f) (hg : PolynomiallyBounded g) : + PolynomiallyBounded (fun x=>LiteralBlockMap.budget w H (f x) (g x)) := + (hf.add (PolynomiallyBounded.const 1)).mul + ((PolynomiallyBounded.const (3+w+H)).add ((PolynomiallyBounded.const 2).mul + (hg.add (hf.mul (PolynomiallyBounded.const (H+w)))))) +lemma polynomial_packTime {f : ℕ→ℕ} (hf : PolynomiallyBounded f) : + PolynomiallyBounded (fun x=>packTime (f x)) := + ((PolynomiallyBounded.const 1).add (polynomial_budget 1 (18*width) hf (PolynomiallyBounded.const 0))).mul + (PolynomiallyBounded.const (MachineCost.programCost packCode)) +lemma polynomial_postTime {f : ℕ→ℕ} (hf : PolynomiallyBounded f) : + PolynomiallyBounded (fun x=>postTime (f x)) := + (PolynomiallyBounded.const eraseTime).add + (((PolynomiallyBounded.const 1).add (polynomial_budget (18*width) 1 hf (PolynomiallyBounded.const 0))).mul + (PolynomiallyBounded.const (MachineCost.programCost unpackCode))) +lemma polynomial_factor {A B : Type} [Codec A] [Codec B] {f : A→Experiment B} + (F : OnlineTree.Realizer f) {H n : ℕ→ℕ} + (hH : PolynomiallyBounded H) (hn : PolynomiallyBounded n) : + PolynomiallyBounded (fun x=>OnlineStack.Executes.factor F.program.code (H x) (n x)) := by + let a:=OnlineStack.accesses F.program.code + let o:=OnlineStack.overhead F.program.code + exact ((PolynomiallyBounded.const o).mul ((PolynomiallyBounded.const 1).add + ((PolynomiallyBounded.const (2*a)).mul ((hH.add (hn.mul (PolynomiallyBounded.const a))).add + (PolynomiallyBounded.const 1))))).add (PolynomiallyBounded.const 1) + +lemma mainTime_bound : ∃ C d : ℕ,0packTime x+q.eval x*OnlineStack.Executes.factor F.program.code (18*x+1) (q.eval x)+postTime (q.eval x) + have hb : PolynomiallyBounded bound := + ((polynomial_packTime PolynomiallyBounded.id).add ((polynomial_eval q).mul + (polynomial_factor F (((PolynomiallyBounded.const 18).mul PolynomiallyBounded.id).add + (PolynomiallyBounded.const 1)) (polynomial_eval q)))).add (polynomial_postTime (polynomial_eval q)) + obtain ⟨C,d,hb⟩:=hb + refine ⟨C+1,d,by omega,?_⟩ + intro G ε δ he he1 hd + let as:=encodeInput G ε δ + let x:=as.length+⌈ε⁻¹⌉₊+Nat.clog 2 ⌈δ⁻¹⌉₊+1 + have hx : 1≤x := by dsimp only [x];omega + have hl : as.length≤x := by dsimp only [x];omega + have hc := hq G ε δ he he1 hd x hx hl (by dsimp only [x];omega) (by dsimp only [x];omega) + have hcost : F.cost as≤q.eval x := by dsimp only [F,as];omega + have hout : (LiteralAlgorithm.algorithm as).worst weight≤q.eval x := by dsimp only [as];omega + have hword : (LiteralAlgorithm.algorithm as).worst List.length≤q.eval x := + Experiment.worst_le _ _ _ ((Experiment.all_worst _ weight).mono (fun bs hbs=> + (list_length_le_weight bs).trans (hbs.trans hout))) + have hweight : weight as≤18*x+1 := by rw [LiteralCodec.weight_word];omega + have hwrap : wrapTime F as≤bound x := by + unfold wrapTime OnlineTree.physicalCost + exact Nat.add_le_add (Nat.add_le_add (packTime_mono hl) + (Nat.mul_le_mul hcost (OnlineStack.Executes.factor_mono _ _ _ _ hweight hcost))) (postTime_mono hword) + apply hwrap.trans ((hb x hx).trans ?_) + change C*x^d≤(C+1)*x^d + exact Nat.mul_le_mul_right _ (by omega) +end MatchingFPRAS.LiteralPhysical + +end OAI diff --git a/lean/OAI/Combinatorics/MatchingCount/Complexity/StackCompilerCost.lean b/lean/OAI/Combinatorics/MatchingCount/Complexity/StackCompilerCost.lean new file mode 100644 index 0000000000000000000000000000000000000000..5ee7f6a14e36879158671140fbf58d2bda5954b8 --- /dev/null +++ b/lean/OAI/Combinatorics/MatchingCount/Complexity/StackCompilerCost.lean @@ -0,0 +1,194 @@ +import Mathlib +import OAI.Combinatorics.MatchingCount.Complexity.GuardMachineBase + +namespace OAI + +namespace MatchingFPRAS.StackCost +open Turing Turing.TM2to1 Turing.TM2to1.Λ' MachineCost + +variable {K : Type*} {Γ : K → Type*} {Λ σ : Type*} [DecidableEq K] + +def accesses : TM2.Stmt Γ Λ σ → ℕ + | .push _ _ q => accesses q+1 + | .peek _ _ q => accesses q+1 + | .pop _ _ q => accesses q+1 + | .load _ q => accesses q + | .branch _ q r => max (accesses q) (accesses r) + | .goto _ => 0 + | .halt => 0 +def StackBound (S : ∀ k,List (Γ k)) (H : ℕ) : Prop := ∀ k,(S k).length≤H +omit [DecidableEq K] in +lemma accesses_run {k : K} (o : StAct K Γ σ k) (q : TM2.Stmt Γ Λ σ) : + accesses (stRun o q)=accesses q+1 := by cases o <;> rfl +variable (M : Λ → TM2.Stmt Γ Λ σ) +lemma go_time {k : K} (o : StAct K Γ σ k) (q : TM2.Stmt Γ Λ σ) (v : σ) + {S : List (Γ k)} {L : ListBlank (∀ k,Option (Γ k))} + (hL : L.map (proj k)=ListBlank.mk (S.map some).reverse) + (n : ℕ) (hn : n≤S.length) : + MachineCost.run (TM1.step (tr M)) n ⟨some (go k o q),v,Tape.mk' ∅ (addBottom L)⟩= + ⟨some (go k o q),v,(Tape.move .right)^[n] (Tape.mk' ∅ (addBottom L))⟩ := by + induction n with + | zero => rfl + | succ n ih => + rw [show n+1=n+1 from rfl,run_add,ih (by omega)] + simp only [MachineCost.run,advance,TM1.step] + rw [tr,TM1.stepAux,Tape.move_right_n_head,Tape.mk'_nth_nat,addBottom_nth_snd, + stk_nth_val _ hL,List.getElem?_eq_getElem (by simpa using (show n rfl + | succ n ih => + rw [MachineCost.run] + have hs : advance (TM1.step (tr M)) + ⟨some (ret q),v,(Tape.move .right)^[n+1] (Tape.mk' ∅ (addBottom L))⟩= + ⟨some (ret q),v,(Tape.move .right)^[n] (Tape.mk' ∅ (addBottom L))⟩ := by + simp only [advance,TM1.step,tr,TM1.stepAux,Tape.move_right_n_head,Tape.mk'_nth_nat, + addBottom_nth_succ_fst,Bool.cond_false] + rw [Function.iterate_succ_apply',Tape.move_right_left] + rfl + rw [hs,ih] +lemma action_bound {S : ∀ k,List (Γ k)} {H : ℕ} (hS : StackBound S H) + {k : K} (o : StAct K Γ σ k) (v : σ) : + StackBound (Function.update S k (stWrite v (S k) o)) (H+1) := by + intro j + by_cases hj : j=k + · subst j + rw [Function.update_self] + have hk:=hS k + cases o <;> simp only [stWrite,List.length_cons,List.length_tail] <;> omega + · rw [Function.update_of_ne hj] + exact (hS j).trans (by omega) +lemma stepAux_bound (q : TM2.Stmt Γ Λ σ) (v : σ) (S : ∀ k,List (Γ k)) + (H : ℕ) (hS : StackBound S H) : StackBound (TM2.stepAux q v S).stk (H+accesses q) := by + induction q using stmtStRec generalizing v S H with + | run k o q ih => + rw [step_run,accesses_run] + have hh:=ih (stVar v (S k) o) _ (H+1) (action_bound hS o v) + convert hh using 1; omega + | load a q ih => exact ih (a v) S H hS + | branch p q r ihq ihr => + cases hp:p v + · simp only [TM2.stepAux,hp,Bool.cond_false,accesses] + exact fun k=>(ihr v S H hS k).trans (Nat.add_le_add_left (le_max_right _ _) H) + · simp only [TM2.stepAux,hp,Bool.cond_true,accesses] + exact fun k=>(ihq v S H hS k).trans (Nat.add_le_add_left (le_max_left _ _) H) + | goto f => simpa only [TM2.stepAux,accesses,Nat.add_zero] using hS + | halt => simpa only [TM2.stepAux,accesses,Nat.add_zero] using hS + +theorem statement_time (q : TM2.Stmt Γ Λ σ) (v : σ) (S : ∀ k,List (Γ k)) + (L : ListBlank (∀ k,Option (Γ k))) (H : ℕ) (hS : StackBound S H) + (hL : ∀ k,L.map (proj k)=ListBlank.mk ((S k).map some).reverse) : + ∃ (t : ℕ) (b : TM1.Cfg (Γ' K Γ) (Λ' K Γ Λ σ) σ), + t≤2*accesses q*(H+accesses q+1) ∧ TrCfg (TM2.stepAux q v S) b ∧ + MachineCost.run (TM1.step (tr M)) t + (TM1.stepAux (trNormal q) v (Tape.mk' ∅ (addBottom L)))=b := by + induction q using stmtStRec generalizing v S L H with + | run k o q ih => + let v':=stVar v (S k) o + let S':=Function.update S k (stWrite v (S k) o) + have hS' : StackBound S' (H+1):=action_bound hS o v + obtain ⟨L',hL',hact⟩:=tr_respects_aux₂ + (q:=TM1.Stmt.goto fun _ _=>ret q) hL o + obtain ⟨t,b,ht,hb,he⟩:=ih v' S' L' (H+1) hS' hL' + have hgo:=go_time M o q v (hL k) (S k).length le_rfl + have hs : advance (TM1.step (tr M)) + ⟨some (go k o q),v,(Tape.move .right)^[(S k).length] (Tape.mk' ∅ (addBottom L))⟩= + ⟨some (ret q),v',(Tape.move .right)^[(S' k).length] (Tape.mk' ∅ (addBottom L'))⟩ := by + simp only [advance,TM1.step] + rw [tr,TM1.stepAux,Tape.move_right_n_head,Tape.mk'_nth_nat,addBottom_nth_snd, + stk_nth_val _ (hL k),List.getElem?_eq_none (le_of_eq List.length_reverse)] + simp only [Option.isNone_none,Bool.cond_true] + rw [hact] + rfl + have hr : MachineCost.run (TM1.step (tr M)) + ((S k).length+1+(S' k).length+1) + ⟨some (go k o q),v,Tape.mk' ∅ (addBottom L)⟩= + TM1.stepAux (trNormal q) v' (Tape.mk' ∅ (addBottom L')) := by + rw [run_add _ ((S k).length+1+(S' k).length) 1, + run_add _ ((S k).length+1) (S' k).length, + run_add _ (S k).length 1,hgo] + simp only [MachineCost.run] + rw [hs,return_time] + simp only [advance,TM1.step,tr,TM1.stepAux,Tape.mk'_head,addBottom_head_fst, + Bool.cond_true,Option.getD_some] + refine ⟨(S k).length+1+(S' k).length+1+t,b,?_,?_,?_⟩ + · rw [accesses_run] + have h₁:=hS k + have h₂:=hS' k + nlinarith + · simpa only [step_run] using hb + · rw [trNormal_run,TM1.stepAux,run_add,hr,he] + | load a q ih => exact ih (a v) S L H hS hL + | branch p q r ihq ihr => + cases hp:p v + · obtain ⟨t,b,ht,hb,he⟩:=ihr v S L H hS hL + refine ⟨t,b,ht.trans ?_,?_,?_⟩ + · simp only [accesses]; gcongr <;> exact le_max_right _ _ + · simpa only [TM2.stepAux,hp,Bool.cond_false] using hb + · simpa only [trNormal,TM1.stepAux,hp,Bool.cond_false] using he + · obtain ⟨t,b,ht,hb,he⟩:=ihq v S L H hS hL + refine ⟨t,b,ht.trans ?_,?_,?_⟩ + · simp only [accesses]; gcongr <;> exact le_max_left _ _ + · simpa only [TM2.stepAux,hp,Bool.cond_true] using hb + · simpa only [trNormal,TM1.stepAux,hp,Bool.cond_true] using he + | goto f => exact ⟨0,_,Nat.zero_le _,⟨L,hL⟩,rfl⟩ + | halt => exact ⟨0,_,Nat.zero_le _,⟨L,hL⟩,rfl⟩ + +lemma advance_bound (A : ℕ) (hA : ∀ l,accesses (M l)≤A) + (c : TM2.Cfg Γ Λ σ) (H : ℕ) (hS : StackBound c.stk H) : + StackBound (advance (TM2.step M) c).stk (H+A) := by + rcases c with ⟨l,v,S⟩ + cases l with + | none => exact fun k=>(hS k).trans (Nat.le_add_right H A) + | some l => + have hh:=stepAux_bound (M l) v S H hS + exact fun k=>(hh k).trans (Nat.add_le_add_left (hA l) H) +lemma one_step_time (A : ℕ) (hA : ∀ l,accesses (M l)≤A) + {c : TM2.Cfg Γ Λ σ} {a : TM1.Cfg (Γ' K Γ) (Λ' K Γ Λ σ) σ} + (hca : TrCfg c a) (H : ℕ) (hS : StackBound c.stk H) : + ∃ (t : ℕ) (b : TM1.Cfg (Γ' K Γ) (Λ' K Γ Λ σ) σ), + t≤1+2*A*(H+A+1) ∧ TrCfg (advance (TM2.step M) c) b ∧ + MachineCost.run (TM1.step (tr M)) t a=b := by + rcases hca with ⟨L,hL⟩ + rename_i l v S + cases l with + | none => exact ⟨0,_,Nat.zero_le _,⟨L,hL⟩,rfl⟩ + | some l => + obtain ⟨t,b,ht,hb,he⟩:=statement_time M (M l) v S L H hS hL + refine ⟨t+1,b,?_,hb,?_⟩ + · have hh : 2*accesses (M l)*(H+accesses (M l)+1)≤2*A*(H+A+1) := by + gcongr <;> exact hA l + omega + · simpa only [MachineCost.run,advance,TM1.step,Option.map_some,tr,Option.getD_some] using he + +theorem execution_time (A : ℕ) (hA : ∀ l,accesses (M l)≤A) + {c : TM2.Cfg Γ Λ σ} {a : TM1.Cfg (Γ' K Γ) (Λ' K Γ Λ σ) σ} + (hca : TrCfg c a) (H : ℕ) (hS : StackBound c.stk H) (n : ℕ) : + ∃ (t : ℕ) (b : TM1.Cfg (Γ' K Γ) (Λ' K Γ Λ σ) σ), + t≤n*(1+2*A*(H+n*A+1)) ∧ TrCfg (MachineCost.run (TM2.step M) n c) b ∧ + MachineCost.run (TM1.step (tr M)) t a=b := by + induction n generalizing c a H with + | zero => exact ⟨0,a,by simp,hca,rfl⟩ + | succ n ih => + obtain ⟨t₁,b₁,ht₁,hb₁,he₁⟩:=one_step_time M A hA hca H hS + obtain ⟨t₂,b₂,ht₂,hb₂,he₂⟩:=ih hb₁ (H+A) (advance_bound M A hA c H hS) + refine ⟨t₁+t₂,b₂,?_,hb₂,?_⟩ + · have hcommon : 1+2*A*(H+A+1)≤1+2*A*(H+(n+1)*A+1) := by + gcongr + simp only [Nat.add_mul,Nat.one_mul] + omega + have heq : H+A+n*A+1=H+(n+1)*A+1 := by ring + rw [heq] at ht₂ + calc + t₁+t₂≤(1+2*A*(H+(n+1)*A+1))+n*(1+2*A*(H+(n+1)*A+1)) := + Nat.add_le_add (ht₁.trans hcommon) ht₂ + _=(n+1)*(1+2*A*(H+(n+1)*A+1)) := by ring + · rw [run_add,he₁,he₂] +end MatchingFPRAS.StackCost + +end OAI diff --git a/lean/OAI/Combinatorics/MatchingCount/Complexity/TreeChoiceCosts.lean b/lean/OAI/Combinatorics/MatchingCount/Complexity/TreeChoiceCosts.lean new file mode 100644 index 0000000000000000000000000000000000000000..b4b417cc89dccd8d792e171b0eeeb7e8ede1744a --- /dev/null +++ b/lean/OAI/Combinatorics/MatchingCount/Complexity/TreeChoiceCosts.lean @@ -0,0 +1,131 @@ +import Mathlib +import OAI.Combinatorics.MatchingCount.Machines.TreeFastLookup +import OAI.Combinatorics.MatchingCount.Complexity.TreeFractionCosts + +namespace OAI + +namespace MatchingFPRAS.TreeTyped +open Polynomial + +variable {A : Type} [Codec A] + +def takeFast : Realizer (fun x : List A×ℕ=>x.1.take x.2) := + (composition (composition (pair (composition first reverse) + (composition (pair (composition first listLength) second) subtract)) dropFast) reverse).congr (by + intro x + change (x.1.reverse.drop (x.1.length-x.2)).reverse=x.1.take x.2 + rw [←List.reverse_take,List.reverse_reverse]) +lemma polynomial_takeFast : PolynomialTime (takeFast (A:=A)) := by + unfold takeFast + apply polynomial_congr + exact polynomial_composition (polynomial_composition (polynomial_pair + (polynomial_composition polynomial_first polynomial_reverse) + (polynomial_composition (polynomial_pair (polynomial_composition polynomial_first polynomial_listLength) + polynomial_second) polynomial_subtract)) polynomial_dropFast) polynomial_reverse +omit [Codec A] in +lemma polynomial_bitValue : PolynomialTime bitValue := by + unfold bitValue + apply polynomial_congr + exact polynomial_composition (polynomial_composition (polynomial_pair polynomial_reverse + (polynomial_constant (1,0))) polynomial_mulFold) polynomial_second +omit [Codec A] in +lemma polynomial_bitDenominator : PolynomialTime bitDenominatorRealizer := by + unfold bitDenominatorRealizer + apply polynomial_congr + apply polynomial_composition (polynomial_pair polynomial_identity (polynomial_constant 1)) + apply polynomial_fold (polynomial_composition polynomial_second polynomial_double) (4*X+8*X+1) + intro bs n pre post he + have hfold : ∀ z,(pre.foldl (fun a (_ : Bool)=>2*a) z).size≤z.size+pre.length*2 := by + clear he + induction pre with + | nil => intro z; simp + | cons b pre ih => + intro z + have hh:=nat_size_mul 2 z + have ht:=ih (2*z) + simp only [List.foldl_cons,List.length_cons] + have h2 : Nat.size 2=2 := by decide + omega + let S:=weight (bs,n) + have hn : n.size≤S := (size_le_weight n).trans (weight_snd (bs,n)) + have hp : pre.length≤S := (list_length_le_weight pre).trans ((weight_prefix he).trans (weight_fst (bs,n))) + have hw:=weight_nat_le (pre.foldl (fun a (_ : Bool)=>2*a) n) + have hh:=hfold n + simp only [Polynomial.eval_add,Polynomial.eval_mul,Polynomial.eval_ofNat,Polynomial.eval_X,Polynomial.eval_one] + change weight (pre.foldl (fun a (_ : Bool)=>2*a) n)≤4*S+8*S+1 + omega +omit [Codec A] in +lemma polynomial_minimum : PolynomialTime minimum := by + unfold minimum + exact polynomial_congr _ (polynomial_choose polynomial_less polynomial_first polynomial_second) +omit [Codec A] in +lemma polynomial_listMin : PolynomialTime listMinRealizer := by + unfold listMinRealizer + apply polynomial_congr + apply polynomial_fold polynomial_minimum (4*X+1) + intro as n pre post he + have hm : pre.foldl (fun z a=>min a z) n=listMin (pre,n) := by + unfold listMin + congr 1 + funext z a + exact Nat.min_comm _ _ + change weight (pre.foldl (fun z a=>min a z) n)≤_ + rw [hm] + have hl:=listMin_le_default pre n + have hs:=(Nat.size_le_size hl).trans (size_le_weight n) + have hw:=weight_nat_le (listMin (pre,n)) + have hn : weight n≤weight (as,n) := weight_snd (as,n) + simp only [Polynomial.eval_add,Polynomial.eval_mul,Polynomial.eval_ofNat,Polynomial.eval_X,Polynomial.eval_one] + omega +end MatchingFPRAS.TreeTyped + +namespace MatchingFPRAS.TreeFraction +open TreeTyped + +def cumulativeFast : Realizer cumulativeFraction := composition takeFast sumRealizer +lemma polynomial_cumulativeFast : PolynomialTime cumulativeFast := + polynomial_composition polynomial_takeFast polynomial_sum +end MatchingFPRAS.TreeFraction + +namespace MatchingFPRAS.ExecutableChoice +open TreeTyped TreeFraction Polynomial + +def predicateFast : Realizer predicate := by + let C : Realizer (fun x : (List Fraction×Fraction)×ℕ=>cumulativeFraction (x.1.1,x.2+1)) := + (composition (pair first.fst (composition second successor)) cumulativeFast).congr (fun _=>rfl) + exact (composition (pair first.snd C) lessRealizer).congr (fun _=>rfl) +lemma polynomial_predicateFast : PolynomialTime predicateFast := by + unfold predicateFast + dsimp only + apply polynomial_congr + apply polynomial_composition _ TreeFraction.polynomial_less + apply polynomial_pair (polynomial_snd polynomial_first) + apply polynomial_congr + exact polynomial_composition (polynomial_pair (polynomial_fst polynomial_first) + (polynomial_composition polynomial_second polynomial_successor)) polynomial_cumulativeFast + +def chooseFast : Realizer choose := by + let rs : Realizer (fun x : List Fraction×Fraction=>List.range x.1.length) := + composition (composition first listLength) range + let good:=composition (pair identity rs) (filterWith predicateFast) + exact (composition (pair good (composition first listLength)) listMinRealizer).congr (fun _=>rfl) +lemma polynomial_chooseFast : PolynomialTime chooseFast := by + unfold chooseFast + dsimp only + apply polynomial_congr + apply polynomial_composition _ polynomial_listMin + apply polynomial_pair _ (polynomial_composition polynomial_first polynomial_listLength) + apply polynomial_composition _ (polynomial_filterWith polynomial_predicateFast) + apply polynomial_pair polynomial_identity + exact polynomial_boundedRange (polynomial_composition polynomial_first polynomial_listLength) X + (fun x=>by simpa using (list_length_le_weight x.1).trans (weight_fst x)) + +def chooseBitsFast : Realizer chooseBits := + composition (pair first (pair (composition second bitValue) (composition second bitDenominatorRealizer))) chooseFast +lemma polynomial_chooseBitsFast : PolynomialTime chooseBitsFast := + polynomial_composition (polynomial_pair polynomial_first (polynomial_pair + (polynomial_composition polynomial_second polynomial_bitValue) + (polynomial_composition polynomial_second polynomial_bitDenominator))) polynomial_chooseFast +end MatchingFPRAS.ExecutableChoice + +end OAI diff --git a/lean/OAI/Combinatorics/MatchingCount/Complexity/TreeCostMeasure.lean b/lean/OAI/Combinatorics/MatchingCount/Complexity/TreeCostMeasure.lean new file mode 100644 index 0000000000000000000000000000000000000000..59d4282549e9b7a794bb12e884da4913c2ded2bb --- /dev/null +++ b/lean/OAI/Combinatorics/MatchingCount/Complexity/TreeCostMeasure.lean @@ -0,0 +1,135 @@ +import Mathlib +import OAI.Combinatorics.MatchingCount.Machines.TreeFinite + +namespace OAI + +namespace MatchingFPRAS.TreeTyped +open Polynomial + +variable {A B C : Type} [Codec A] [Codec B] [Codec C] + +def WorkBound {f : A → B} (F : Realizer f) (measure : A → ℕ) : Prop := + ∃ p : Polynomial ℕ, ∀ a,F.cost a+weight (f a)≤p.eval (measure a) + +lemma work_of_polynomial {f : A → B} {F : Realizer f} (hF : PolynomialTime F) + {measure : A → ℕ} (p : Polynomial ℕ) (hp : ∀ a,weight a≤p.eval (measure a)) : WorkBound F measure := by + obtain ⟨q,hq⟩:=hF + exact ⟨q.comp p,fun a=>(hq a).trans (by simpa using polynomial_eval_monotone q (hp a))⟩ +lemma work_congr {f g : A → B} {F : Realizer f} {measure : A → ℕ} + (h : ∀ a,f a=g a) (hF : WorkBound F measure) : WorkBound (F.congr h) measure := by + obtain ⟨p,hp⟩:=hF + exact ⟨p,fun a=>by simpa only [Realizer.congr,←h a] using hp a⟩ +lemma work_composition {f : A → B} {g : B → C} {F : Realizer f} {G : Realizer g} + {measure : A → ℕ} {other : B → ℕ} + (hF : WorkBound F measure) (hG : WorkBound G other) (p : Polynomial ℕ) + (hm : ∀ a,other (f a)≤p.eval (measure a)) : WorkBound (composition F G) measure := by + obtain ⟨q,hq⟩:=hF + obtain ⟨r,hr⟩:=hG + refine ⟨q+r.comp p,fun a=>?_⟩ + have h1:=hq a + have h2:=hr (f a) + have h3:=polynomial_eval_monotone r (hm a) + simp only [Polynomial.eval_add,Polynomial.eval_comp] + change F.cost a+G.cost (f a)+weight (g (f a))≤_ + dsimp only at h3 + omega +lemma work_then_polynomial {f : A → B} {g : B → C} {F : Realizer f} {G : Realizer g} + {measure : A → ℕ} (hF : WorkBound F measure) (hG : PolynomialTime G) : + WorkBound (composition F G) measure := by + obtain ⟨p,hp⟩:=hF + exact work_composition ⟨p,hp⟩ hG p (fun a=>Nat.le_trans (Nat.le_add_left _ _) (hp a)) +lemma work_remeasure {f : A → B} {F : Realizer f} {measure other : A → ℕ} + (hF : WorkBound F measure) (p : Polynomial ℕ) (hm : ∀ a,measure a≤p.eval (other a)) : + WorkBound F other := by + obtain ⟨q,hq⟩:=hF + exact ⟨q.comp p,fun a=>(hq a).trans (by simpa using polynomial_eval_monotone q (hm a))⟩ + +lemma work_boundedRepeat {init : A → ℕ×B} {f : ℕ×B → B} + {Init : Realizer init} {F : Realizer f} {measure : A → ℕ} + (hInit : WorkBound Init measure) (hF : PolynomialTime F) + (p q : Polynomial ℕ) (I : A → ℕ → B → Prop) + (hn : ∀ a,(init a).1≤p.eval (measure a)) + (hi : ∀ a,I a (init a).1 (init a).2) + (hs : ∀ a k,(k<(init a).1) → ∀ z,I a (k+1) z → I a k (f (k+1,z))) + (hw : ∀ a k z,I a k z → weight z≤q.eval (measure a)) : + WorkBound (composition Init (iterateDown F)) measure := by + obtain ⟨r,hr⟩:=hInit + obtain ⟨t,ht⟩:=polynomial_repeatNext hF + refine ⟨r+p*(t.comp (2+4*p+q)+4*(4*p+1)+12)+10+q,fun a=>?_⟩ + let S:=measure a + let N:=(init a).1 + let T:=t.eval (2+4*p.eval S+q.eval S) + have hN : N≤p.eval S:=hn a + have hsz : ∀ kby simpa using weight_nat_numeric n)) polynomial_rangeStep X (4*X^2+2*X+1) + (fun n k zs=>zs.length+k=n ∧ ∀ z∈zs,z `(tactic| + (with_reducible repeat' (first + | assumption + | exact polynomial_identity + | exact polynomial_first + | exact polynomial_second + | exact polynomial_boolAnd + | exact polynomial_boolOr + | exact polynomial_boolNot + | exact polynomial_add + | exact polynomial_subtract + | exact polynomial_multiply + | exact polynomial_less + | exact polynomial_leNat + | exact polynomial_natEqual + | exact polynomial_finsetList + | exact polynomial_finsetCard + | exact polynomial_finsetSingleton + | exact polynomial_listCons + | exact polynomial_listLength + | exact polynomial_append + | exact polynomial_reverse + | exact polynomial_flatten + | apply polynomial_recode + | apply polynomial_composition + | apply polynomial_pair + | apply polynomial_choose + | apply polynomial_constant + | apply polynomial_fst + | apply polynomial_snd + | apply polynomial_map + | apply polynomial_mapWith + | apply polynomial_flatMapPoly + | apply polynomial_filter + | apply polynomial_filterWith + | apply polynomial_finsetBiUnion + | apply polynomial_finsetFilter + | apply polynomial_finsetFilterWith + | apply polynomial_finsetImage + | apply polynomial_finsetUnion + | apply polynomial_finsetSDiff + | apply polynomial_finsetInter + | apply polynomial_finsetErase + | apply polynomial_finsetInsert + | apply polynomial_finsetEqual + | apply polynomial_finsetSubset + | apply polynomial_finsetMember + | apply polynomial_finsetAny + | apply polynomial_finsetAll + | apply polynomial_pairEqual + | apply polynomial_lexLe + | apply polynomial_colexLe + | apply polynomial_congr))) + +end OAI diff --git a/lean/OAI/Combinatorics/MatchingCount/Complexity/TreeFractionCosts.lean b/lean/OAI/Combinatorics/MatchingCount/Complexity/TreeFractionCosts.lean new file mode 100644 index 0000000000000000000000000000000000000000..0838253a09e0fa51f7604d716bf1598cf1ec7cf5 --- /dev/null +++ b/lean/OAI/Combinatorics/MatchingCount/Complexity/TreeFractionCosts.lean @@ -0,0 +1,73 @@ +import Mathlib +import OAI.Combinatorics.MatchingCount.Sampling.TreeCategorical +import OAI.Combinatorics.MatchingCount.Complexity.TreePolynomialGrid + +namespace OAI + +namespace MatchingFPRAS.TreeFraction +open TreeTyped Polynomial + +def height (x : Fraction) : ℕ := max x.1.size x.2.size +lemma height_le_weight (x : Fraction) : height x≤weight x := by + rcases x with ⟨a,b⟩ + have ha:=size_le_weight a + have hb:=size_le_weight b + simp only [height,weight_prod] + exact max_le (by omega) (by omega) +lemma weight_le_height (x : Fraction) : weight x≤8*height x+3 := by + rcases x with ⟨a,b⟩ + have ha:=weight_nat_le a + have hb:=weight_nat_le b + have h1:=le_max_left a.size b.size + have h2:=le_max_right a.size b.size + simp only [height,weight_prod] + omega +lemma height_add (a b : Fraction) : height (add (a,b))≤height a+height b+2 := by + have hn:=normalize_size_num (a.1*b.2+b.1*a.2,a.2*b.2) + have hd:=normalize_size_den (a.1*b.2+b.1*a.2,a.2*b.2) + have hs:=nat_size_add (a.1*b.2) (b.1*a.2) + have hm:=nat_size_mul a.1 b.2 + have hm':=nat_size_mul b.1 a.2 + have hm'':=nat_size_mul a.2 b.2 + have ha:=le_max_left a.1.size a.2.size + have ha':=le_max_right a.1.size a.2.size + have hb:=le_max_left b.1.size b.2.size + have hb':=le_max_right b.1.size b.2.size + dsimp only at hn hd + change (add (a,b)).1.size≤_ at hn + change (add (a,b)).2.size≤_ at hd + unfold height + apply max_le <;> omega +lemma fractionFold_height (xs : List Fraction) (a : Fraction) (M : ℕ) + (hx : ∀ b∈xs,height b≤M) : + height (xs.foldl (fun a b=>add (b,a)) a)≤height a+xs.length*(M+2) := by + induction xs generalizing a with + | nil => simp + | cons b bs ih => + have hh:=height_add b a + have hb:=hx b (by simp) + have ht:=ih (add (b,a)) (fun c h=>hx c (by simp [h])) + simp only [List.foldl_cons,List.length_cons] + nlinarith +lemma polynomial_fractionFold : PolynomialTime (fold addRealizer) := by + apply polynomial_fold polynomial_add (8*X+8*X*(X+2)+3) + intro xs a pre post he + let S:=weight (xs,a) + have hpre : pre.length≤S := (list_length_le_weight pre).trans ((weight_prefix he).trans (weight_fst (xs,a))) + have hb : ∀ b∈pre,height b≤S := by + intro b hb + exact (height_le_weight b).trans ((weight_mem (as:=xs) (by simp [he,hb])).trans (weight_fst (xs,a))) + have ha : height a≤S := (height_le_weight a).trans (weight_snd (xs,a)) + have hh:=fractionFold_height pre a S hb + have hw:=weight_le_height (pre.foldl (fun a b=>add (b,a)) a) + have hm:=Nat.mul_le_mul_right (S+2) hpre + simp only [Polynomial.eval_add,Polynomial.eval_mul,Polynomial.eval_ofNat,Polynomial.eval_X] + change _≤8*S+8*S*(S+2)+3 + nlinarith +lemma polynomial_sum : PolynomialTime sumRealizer := by + unfold sumRealizer + apply polynomial_congr + exact polynomial_composition (polynomial_pair polynomial_identity (polynomial_constant _)) polynomial_fractionFold +end MatchingFPRAS.TreeFraction + +end OAI diff --git a/lean/OAI/Combinatorics/MatchingCount/Complexity/TreeNumericCosts.lean b/lean/OAI/Combinatorics/MatchingCount/Complexity/TreeNumericCosts.lean new file mode 100644 index 0000000000000000000000000000000000000000..a299b0f16af724b2c8e1be1f26ed1820aa444c8c --- /dev/null +++ b/lean/OAI/Combinatorics/MatchingCount/Complexity/TreeNumericCosts.lean @@ -0,0 +1,106 @@ +import Mathlib +import OAI.Combinatorics.MatchingCount.Complexity.TreeCostMeasure + +namespace OAI + +namespace MatchingFPRAS.TreeTyped +open Polynomial + +variable {A B C : Type} [Codec A] [Codec B] [Codec C] + +lemma work_pair {f : A → B} {g : A → C} {F : Realizer f} {G : Realizer g} + {measure : A → ℕ} (hF : WorkBound F measure) (hG : WorkBound G measure) + (u : Polynomial ℕ) (hu : ∀ a,weight a≤u.eval (measure a)) : WorkBound (pair F G) measure := by + obtain ⟨p,hp⟩:=hF + obtain ⟨q,hq⟩:=hG + refine ⟨7*p+q+11*u+32,fun a=>?_⟩ + have h1:=hp a + have h2:=hq a + have h3:=hu a + simp only [Polynomial.eval_add,Polynomial.eval_mul,Polynomial.eval_ofNat] + rw [weight_prod] + change F.cost a+G.cost a+11*weight a+6*weight (f a)+31+(1+weight (f a)+weight (g a))≤_ + omega +omit [Codec C] in +lemma work_choose {f : A → Bool} {g h : A → B} {F : Realizer f} {G : Realizer g} {H : Realizer h} + {measure : A → ℕ} (hF : WorkBound F measure) (hG : WorkBound G measure) (hH : WorkBound H measure) + (u : Polynomial ℕ) (hu : ∀ a,weight a≤u.eval (measure a)) : WorkBound (choose F G H) measure := by + obtain ⟨p,hp⟩:=hF + obtain ⟨q,hq⟩:=hG + obtain ⟨r,hr⟩:=hH + refine ⟨p+q+r+7*u+18,fun a=>?_⟩ + have h1:=hp a + have h2:=hq a + have h3:=hr a + have h4:=hu a + simp only [Polynomial.eval_add,Polynomial.eval_mul,Polynomial.eval_ofNat] + change F.cost a+(if f a then G.cost a else H.cost a)+7*weight a+18+ + weight (if f a then g a else h a)≤_ + cases f a <;> simp only [Bool.false_eq_true,↓reduceIte] <;> omega + +omit [Codec A] [Codec B] [Codec C] in +lemma factorial_numeric_work : WorkBound factorial id := by + unfold factorial + apply work_congr + apply work_boundedRepeat (work_of_polynomial (polynomial_pair polynomial_identity (polynomial_constant 1)) + (4*X+1) (fun n=>by simpa using weight_nat_numeric n)) polynomial_multiply X (4*X^2+5) + (fun n k z=>k≤n ∧ z.size≤1+(n-k)*n) + · intro n; simp + · intro n; simp + · intro n k hk z hz + change kx.1+x.2) := by + have ht : ∀ {f : ℕ×ℕ → ℕ} {F : Realizer f},PolynomialTime F → WorkBound F (fun x=>x.1+x.2) := + fun h=>work_of_polynomial h (4*X+3) (fun x=>by simpa using pair_nat_weight_numeric x) + have hb : ∀ {f : ℕ×ℕ → Bool} {F : Realizer f},PolynomialTime F → WorkBound F (fun x=>x.1+x.2) := + fun h=>work_of_polynomial h (4*X+3) (fun x=>by simpa using pair_nat_weight_numeric x) + have hpair : ∀ {f g : ℕ×ℕ → ℕ} {F : Realizer f} {G : Realizer g}, + WorkBound F (fun x=>x.1+x.2) → WorkBound G (fun x=>x.1+x.2) → WorkBound (pair F G) (fun x=>x.1+x.2) := + fun h1 h2=>work_pair h1 h2 (4*X+3) (fun x=>by simpa using pair_nat_weight_numeric x) + have hf : WorkBound (composition (first (A:=ℕ) (B:=ℕ)) factorial) (fun x=>x.1+x.2) := + work_composition (ht polynomial_first) factorial_numeric_work X (fun x=>by simp only [Polynomial.eval_X,id_eq]; omega) + have hs : WorkBound (composition (second (A:=ℕ) (B:=ℕ)) factorial) (fun x=>x.1+x.2) := + work_composition (ht polynomial_second) factorial_numeric_work X (fun x=>by simp only [Polynomial.eval_X,id_eq]; omega) + have hd : WorkBound (composition subtract factorial) (fun x=>x.1+x.2) := + work_composition (ht polynomial_subtract) factorial_numeric_work X (fun x=>by simp only [Polynomial.eval_X,id_eq]; omega) + unfold natChoose + apply work_congr + exact work_choose + (hb (polynomial_composition (polynomial_pair polynomial_second polynomial_first) polynomial_less)) + (work_then_polynomial (hpair hf (work_then_polynomial (hpair hs hd) polynomial_multiply)) polynomial_quotient) + (work_choose (hb (polynomial_composition (polynomial_pair polynomial_first polynomial_second) polynomial_less)) + (ht (polynomial_constant 0)) (ht (polynomial_constant 1)) (4*X+3) (fun x=>by simpa using pair_nat_weight_numeric x)) + (4*X+3) (fun x=>by simpa using pair_nat_weight_numeric x) + +omit [Codec B] [Codec C] in +lemma polynomial_boundedFactorial {f : A → ℕ} {F : Realizer f} (hF : PolynomialTime F) + (p : Polynomial ℕ) (hn : ∀ a,f a≤p.eval (weight a)) : PolynomialTime (composition F factorial) := + work_composition hF factorial_numeric_work p hn +omit [Codec B] [Codec C] in +lemma polynomial_boundedChoose {f : A → ℕ×ℕ} {F : Realizer f} (hF : PolynomialTime F) + (p : Polynomial ℕ) (hn : ∀ a,(f a).1+(f a).2≤p.eval (weight a)) : PolynomialTime (composition F natChoose) := + work_composition hF natChoose_numeric_work p hn +end MatchingFPRAS.TreeTyped + +end OAI diff --git a/lean/OAI/Combinatorics/MatchingCount/Complexity/TreePolyTactic.lean b/lean/OAI/Combinatorics/MatchingCount/Complexity/TreePolyTactic.lean new file mode 100644 index 0000000000000000000000000000000000000000..f080135fd2e3eca128191f5772a529c3420df802 --- /dev/null +++ b/lean/OAI/Combinatorics/MatchingCount/Complexity/TreePolyTactic.lean @@ -0,0 +1,63 @@ +import Mathlib +import OAI.Combinatorics.MatchingCount.Machines.TreeColex +import OAI.Combinatorics.MatchingCount.Machines.TreeFiniteCollections + +namespace OAI + +open MatchingFPRAS.TreeTyped + +macro "tree_poly" : tactic => `(tactic| + (with_reducible repeat' (first + | assumption + | exact polynomial_identity + | exact polynomial_first + | exact polynomial_second + | exact polynomial_boolAnd + | exact polynomial_boolOr + | exact polynomial_boolNot + | exact polynomial_add + | exact polynomial_subtract + | exact polynomial_multiply + | exact polynomial_less + | exact polynomial_leNat + | exact polynomial_natEqual + | exact polynomial_finsetList + | exact polynomial_finsetCard + | exact polynomial_finsetSingleton + | exact polynomial_listCons + | exact polynomial_listLength + | exact polynomial_append + | exact polynomial_reverse + | exact polynomial_flatten + | apply polynomial_congr + | apply polynomial_recode + | apply polynomial_composition + | apply polynomial_pair + | apply polynomial_choose + | apply polynomial_constant + | apply polynomial_fst + | apply polynomial_snd + | apply polynomial_map + | apply polynomial_mapWith + | apply polynomial_flatMapPoly + | apply polynomial_filter + | apply polynomial_filterWith + | apply polynomial_finsetBiUnion + | apply polynomial_finsetFilter + | apply polynomial_finsetFilterWith + | apply polynomial_finsetImage + | apply polynomial_finsetUnion + | apply polynomial_finsetSDiff + | apply polynomial_finsetInter + | apply polynomial_finsetErase + | apply polynomial_finsetInsert + | apply polynomial_finsetEqual + | apply polynomial_finsetSubset + | apply polynomial_finsetMember + | apply polynomial_finsetAny + | apply polynomial_finsetAll + | apply polynomial_pairEqual + | apply polynomial_lexLe + | apply polynomial_colexLe))) + +end OAI diff --git a/lean/OAI/Combinatorics/MatchingCount/Complexity/TreePolynomial.lean b/lean/OAI/Combinatorics/MatchingCount/Complexity/TreePolynomial.lean new file mode 100644 index 0000000000000000000000000000000000000000..53a56130cc05c89d10bf00e3f77ddfea6cc5a2c5 --- /dev/null +++ b/lean/OAI/Combinatorics/MatchingCount/Complexity/TreePolynomial.lean @@ -0,0 +1,147 @@ +import Mathlib +import OAI.Combinatorics.MatchingCount.Machines.TreeList + +namespace OAI + +namespace MatchingFPRAS.TreeTyped +open TreeData TreeFunction Polynomial + +variable {A B C : Type} [Codec A] [Codec B] [Codec C] + +def weight (a : A) : ℕ := TreeFunction.size (encode a) +@[simp] lemma weight_prod (a : A) (b : B) : weight (a,b)=1+weight a+weight b := by simp [weight]; omega +@[simp] lemma weight_nil : weight ([] : List A)=1 := rfl +@[simp] lemma weight_cons (a : A) (as : List A) : weight (a::as)=1+weight a+weight as := by simp [weight]; omega +lemma weight_pos (a : A) : 0 simp only [size_nil,size_cons] <;> omega +lemma list_length_le_weight (as : List A) : as.length≤weight as := by + rw [weight,size_encode_list]; omega +lemma weight_mem {as : List A} {a : A} (ha : a∈as) : weight a≤weight as := size_encode_mem ha + +lemma polynomial_eval_monotone (p : Polynomial ℕ) : Monotone (fun n=>p.eval n) := by + intro a b hab + simp only [Polynomial.eval_eq_sum,Polynomial.sum_def] + exact Finset.sum_le_sum (fun i _=>Nat.mul_le_mul_left _ (Nat.pow_le_pow_left hab i)) + +def PolynomialBound {f : A → B} (F : Realizer f) (p : Polynomial ℕ) : Prop := + ∀ a,F.cost a+weight (f a)≤p.eval (weight a) +def PolynomialTime {f : A → B} (F : Realizer f) : Prop := ∃ p,PolynomialBound F p + +lemma polynomial_identity : PolynomialTime (identity (A:=A)) := by + refine ⟨X+1,?_⟩ + intro a + simp [identity,weight,Polynomial.eval_add,Polynomial.eval_X, Nat.add_comm] +lemma polynomial_first : PolynomialTime (first (A:=A) (B:=B)) := by + refine ⟨7*X+11,?_⟩ + intro ⟨a,b⟩ + simp only [Polynomial.eval_add,Polynomial.eval_mul,Polynomial.eval_ofNat,Polynomial.eval_X,weight_prod] + change 6*weight a+weight b+11+weight a≤7*(1+weight a+weight b)+11 + omega +lemma polynomial_second : PolynomialTime (second (A:=A) (B:=B)) := by + refine ⟨4*X+7,?_⟩ + intro ⟨a,b⟩ + simp only [Polynomial.eval_add,Polynomial.eval_mul,Polynomial.eval_ofNat,Polynomial.eval_X,weight_prod] + change 3*weight a+7+weight b≤4*(1+weight a+weight b)+7 + omega + +lemma polynomial_composition {f : A → B} {g : B → C} {F : Realizer f} {G : Realizer g} + (hF : PolynomialTime F) (hG : PolynomialTime G) : PolynomialTime (composition F G) := by + obtain ⟨p,hp⟩ := hF + obtain ⟨q,hq⟩ := hG + refine ⟨p+q.comp p,fun a=>?_⟩ + have h1 := hp a + have h2 := hq (f a) + have h3 := polynomial_eval_monotone q (show weight (f a)≤p.eval (weight a) by omega) + simp only [Polynomial.eval_add,Polynomial.eval_comp] + change F.cost a+G.cost (f a)+weight (g (f a))≤_ + dsimp only at h3 + omega +lemma polynomial_pair {f : A → B} {g : A → C} {F : Realizer f} {G : Realizer g} + (hF : PolynomialTime F) (hG : PolynomialTime G) : PolynomialTime (pair F G) := by + obtain ⟨p,hp⟩ := hF + obtain ⟨q,hq⟩ := hG + refine ⟨7*p+q+11*X+32,fun a=>?_⟩ + have h1 := hp a + have h2 := hq a + simp only [Polynomial.eval_add,Polynomial.eval_mul,Polynomial.eval_ofNat,Polynomial.eval_X] + rw [weight_prod] + change F.cost a+G.cost a+11*weight a+6*weight (f a)+31+(1+weight (f a)+weight (g a))≤_ + omega +lemma polynomial_congr {f g : A → B} {F : Realizer f} (h : ∀ a,f a=g a) + (hF : PolynomialTime F) : PolynomialTime (F.congr h) := by + obtain ⟨p,hp⟩ := hF + exact ⟨p,fun a=>by simpa only [Realizer.congr,←h a] using hp a⟩ +lemma polynomial_choose {f : A → Bool} {g h : A → B} {F : Realizer f} {G : Realizer g} {H : Realizer h} + (hF : PolynomialTime F) (hG : PolynomialTime G) (hH : PolynomialTime H) : + PolynomialTime (choose F G H) := by + obtain ⟨p,hp⟩ := hF + obtain ⟨q,hq⟩ := hG + obtain ⟨r,hr⟩ := hH + refine ⟨p+q+r+7*X+18,fun a=>?_⟩ + have h1 := hp a + have h2 := hq a + have h3 := hr a + simp only [Polynomial.eval_add,Polynomial.eval_mul,Polynomial.eval_ofNat,Polynomial.eval_X] + change F.cost a+(if f a then G.cost a else H.cost a)+7*weight a+18+ + weight (if f a then g a else h a)≤_ + cases f a <;> simp only [Bool.false_eq_true,↓reduceIte] <;> omega +lemma polynomial_constantData (b : Data) : PolynomialTime (constantData (A:=A) b) := by + induction b with + | nil => refine ⟨X+3,fun a=>?_⟩; simp [constantData,weight,Codec.encode,size_nil] + | cons b c hb hc => + obtain ⟨p,hp⟩ := polynomial_pair hb hc + exact ⟨p,hp⟩ +lemma polynomial_constant (b : B) : PolynomialTime (constant (A:=A) b) := + polynomial_constantData (encode b) + +omit [Codec B] in +lemma Fold.cost_prefix_bound {f : A×B → B} (t : A×B → ℕ) (as : List A) (b : B) (T S : ℕ) + (hs : weight as≤S) + (hstep : ∀ pre a post,as=pre++a::post → t (a,pre.foldl (fun z c=>f (c,z)) b)≤T) : + Fold.cost f t as b≤as.length*(T+14*S+34)+10 := by + induction as generalizing b with + | nil => simp [Fold.cost] + | cons a as ih => + have ht := hstep [] a as rfl + simp only [List.foldl_nil] at ht + have hs' : weight as≤S := by rw [weight_cons] at hs; omega + have hi := ih (f (a,b)) hs' (by + intro pre c post he + have hh := hstep (a::pre) c post (by simp only [List.cons_append,he]) + exact hh) + simp only [Fold.cost,List.length_cons] + change t (a,b)+6*weight a+8*weight as+34+Fold.cost f t as (f (a,b))≤_ + have ha : weight a≤S := by rw [weight_cons] at hs; omega + nlinarith + +lemma polynomial_fold {f : A×B → B} {F : Realizer f} (hF : PolynomialTime F) + (p : Polynomial ℕ) + (hsize : ∀ (as : List A) (b : B) pre post,as=pre++post → + weight (pre.foldl (fun z a=>f (a,z)) b)≤p.eval (weight (as,b))) : + PolynomialTime (fold F) := by + obtain ⟨q,hq⟩ := hF + refine ⟨X*(q.comp (1+X+p)+14*X+34)+10+p,fun ⟨as,b⟩=>?_⟩ + let S:=weight (as,b) + let T:=q.eval (1+S+p.eval S) + have hs : weight as≤S := by dsimp [S]; rw [weight_prod]; omega + have hc := Fold.cost_prefix_bound (f:=f) F.cost as b T S hs (by + intro pre a post he + have hz := hsize as b pre (a::post) he + change _≤p.eval S at hz + have ha : weight a≤S := (weight_mem (by simp [he])).trans hs + have hq' := hq (a,pre.foldl (fun z c=>f (c,z)) b) + have hm := polynomial_eval_monotone q (show weight (a,pre.foldl (fun z c=>f (c,z)) b)≤1+S+p.eval S by rw [weight_prod]; omega) + dsimp only at hm + dsimp only [T] + omega) + have hout := hsize as b as [] (by simp) + change _≤p.eval S at hout + have hlen : as.length≤S := (list_length_le_weight as).trans hs + simp only [Polynomial.eval_add,Polynomial.eval_mul,Polynomial.eval_ofNat,Polynomial.eval_X,Polynomial.eval_one,Polynomial.eval_comp] + change Fold.cost f F.cost as b+weight (as.foldl (fun z a=>f (a,z)) b)≤_ + change _≤S*(T+14*S+34)+10+p.eval S + nlinarith +end MatchingFPRAS.TreeTyped + +end OAI diff --git a/lean/OAI/Combinatorics/MatchingCount/Complexity/TreePolynomialArithmetic.lean b/lean/OAI/Combinatorics/MatchingCount/Complexity/TreePolynomialArithmetic.lean new file mode 100644 index 0000000000000000000000000000000000000000..e6f7e909962d180ba364569466c7595e4fcf8537 --- /dev/null +++ b/lean/OAI/Combinatorics/MatchingCount/Complexity/TreePolynomialArithmetic.lean @@ -0,0 +1,84 @@ +import Mathlib +import OAI.Combinatorics.MatchingCount.Machines.TreePartialChoice +import OAI.Combinatorics.MatchingCount.Complexity.TreePolynomial + +namespace OAI + +namespace MatchingFPRAS.TreeTyped +open TreeData TreeFunction Polynomial + +lemma weight_bool (b : Bool) : weight b≤3 := by cases b <;> decide +lemma weight_bits (bs : List Bool) : weight bs≤4*bs.length+1 := TreeData.bits_length bs +lemma weight_nat (n : ℕ) : weight n=weight n.bits := rfl +lemma weight_nat_le (n : ℕ) : weight n≤4*n.size+1 := by + rw [weight_nat,←Nat.size_eq_bits_len]; exact weight_bits _ +lemma size_le_weight (n : ℕ) : n.size≤weight n := by + rw [weight_nat,←Nat.size_eq_bits_len]; exact list_length_le_weight _ +lemma weight_nat_small {a b : ℕ} (h : a≤b) : weight a≤4*weight b+1 := by + have h1:=Nat.size_le_size h + have h2:=weight_nat_le a + have h3:=size_le_weight b + omega +lemma nat_size_add (a b : ℕ) : (a+b).size≤ max a.size b.size+1 := by + apply Nat.size_le.mpr + have ha : a<2^(max a.size b.size) := (Nat.lt_size_self a).trans_le (Nat.pow_le_pow_right (by decide) (le_max_left _ _)) + have hb : b<2^(max a.size b.size) := (Nat.lt_size_self b).trans_le (Nat.pow_le_pow_right (by decide) (le_max_right _ _)) + rw [pow_succ]; omega +lemma nat_size_mul (a b : ℕ) : (a*b).size≤a.size+b.size := by + apply Nat.size_le.mpr + rw [pow_add] + exact (Nat.mul_le_mul_left a (Nat.le_of_lt (Nat.lt_size_self b))).trans_lt + (Nat.mul_lt_mul_of_pos_right (Nat.lt_size_self a) (by positivity)) +lemma weight_add (a b : ℕ) : weight (a+b)≤4*(weight a+weight b+1)+1 := by + have h:=weight_nat_le (a+b) + have h1:=nat_size_add a b + have h2:=size_le_weight a + have h3:=size_le_weight b + have hm : max a.size b.size≤weight a+weight b := max_le (by omega) (by omega) + omega +lemma polynomial_add : PolynomialTime add := by + refine ⟨20*X+30,fun ⟨a,b⟩=>?_⟩ + have ha:=size_le_weight a + have hb:=size_le_weight b + have ho:=weight_add a b + simp only [Polynomial.eval_add,Polynomial.eval_mul,Polynomial.eval_ofNat,Polynomial.eval_X,weight_prod] + change (2*weight a+5+9*(a.bits.length+b.bits.length)+20)+weight (a+b)≤_ + rw [Nat.size_eq_bits_len,Nat.size_eq_bits_len] + omega +lemma polynomial_less : PolynomialTime less := by + refine ⟨8*X+40,fun ⟨a,b⟩=>?_⟩ + have ha:=size_le_weight a + have hb:=size_le_weight b + have ho:=weight_bool (decide (a?_⟩ + have ha:=size_le_weight a + have hb:=size_le_weight b + have hc:=weight_nat_small (Nat.sub_le a b) + have ho:=weight_bool (decide (a omega +lemma polynomial_toBits : PolynomialTime toBits := by + refine ⟨X+1,fun _=>?_⟩ + simp only [Polynomial.eval_add,Polynomial.eval_X,Polynomial.eval_one] + change 1+weight _ ≤ weight _+1 + rw [weight_nat]; omega +lemma polynomial_listCons {A : Type} [Codec A] : PolynomialTime (listCons (A:=A)) := by + refine ⟨X+1,fun ⟨a,as⟩=>?_⟩ + simp only [Polynomial.eval_add,Polynomial.eval_X,Polynomial.eval_one,weight_prod,weight_cons] + change 1+(1+weight a+weight as)≤(1+weight a+weight as)+1 + omega +lemma polynomial_double : PolynomialTime double := + polynomial_congr _ (polynomial_composition (polynomial_pair polynomial_identity polynomial_identity) polynomial_add) +end MatchingFPRAS.TreeTyped + +end OAI diff --git a/lean/OAI/Combinatorics/MatchingCount/Complexity/TreePolynomialCollections.lean b/lean/OAI/Combinatorics/MatchingCount/Complexity/TreePolynomialCollections.lean new file mode 100644 index 0000000000000000000000000000000000000000..3b64a17abdc2f7e119570014905743ae14832a85 --- /dev/null +++ b/lean/OAI/Combinatorics/MatchingCount/Complexity/TreePolynomialCollections.lean @@ -0,0 +1,150 @@ +import Mathlib +import OAI.Combinatorics.MatchingCount.Complexity.TreePolynomialGCD + +namespace OAI + +namespace MatchingFPRAS.TreeTyped +open Polynomial + +variable {A B C : Type} [Codec A] [Codec B] [Codec C] +lemma polynomial_listCase (b : B) {g : A×List A → B} {G : Realizer g} + (hG : PolynomialTime G) : PolynomialTime (listCase b G) := by + obtain ⟨p,hp⟩:=hG + obtain ⟨q,hq⟩:=polynomial_constant (A:=List A) b + refine ⟨p+q+3,fun as=>?_⟩ + simp only [Polynomial.eval_add,Polynomial.eval_ofNat] + cases as with + | nil => + have hh:=hq [] + change (constant b (A:=List A)).cost []+weight b≤_ at hh + change 3+(constant b (A:=List A)).cost []+weight b≤_ + omega + | cons a as => + have hh:=hp (a,as) + have he : weight (a,as)=weight (a::as) := rfl + rw [he] at hh + change 3+G.cost (a,as)+weight (g (a,as))≤_ + omega +lemma polynomial_head (d : A) : PolynomialTime (head d) := by + unfold head + exact polynomial_congr _ (polynomial_listCase d polynomial_first) +lemma polynomial_tail : PolynomialTime (tail (A:=A)) := polynomial_listCase [] polynomial_second +lemma polynomial_isEmpty : PolynomialTime (isEmpty (A:=A)) := polynomial_listCase true (polynomial_constant false) +lemma weight_sublist {as bs : List A} (h : as.Sublist bs) : weight as≤weight bs := by + induction h with + | slnil => exact le_rfl + | cons a h ih => rw [weight_cons]; omega + | cons_cons a h ih => simp only [weight_cons]; omega +lemma polynomial_append : PolynomialTime (append (A:=A)) := by + unfold append + apply polynomial_congr + apply polynomial_composition (polynomial_pair (polynomial_composition polynomial_first polynomial_reverse) polynomial_second) + apply polynomial_fold polynomial_listCons (2*X+1) + intro as bs pre post he + simp only [List.foldl_flip_cons_eq_append'] + have hh:=weight_append pre.reverse bs + rw [weight_reverse] at hh + have hp:=weight_prefix he + simp only [Polynomial.eval_add,Polynomial.eval_mul,Polynomial.eval_ofNat,Polynomial.eval_X,weight_prod] + omega +lemma polynomial_mapStep {f : A×B → C} {F : Realizer f} (hF : PolynomialTime F) : + PolynomialTime (mapStepRealizer F) := by + unfold mapStepRealizer + exact polynomial_pair (polynomial_composition polynomial_second polynomial_first) + (polynomial_composition (polynomial_pair + (polynomial_composition (polynomial_pair (polynomial_composition polynomial_second polynomial_first) polynomial_first) hF) + (polynomial_composition polynomial_second polynomial_second)) polynomial_listCons) +lemma polynomial_mapWith {f : A×B → C} {F : Realizer f} (hF : PolynomialTime F) : + PolynomialTime (mapWith F) := by + unfold mapWith + apply polynomial_congr + apply polynomial_composition _ (polynomial_composition polynomial_second polynomial_reverse) + apply polynomial_composition (polynomial_pair polynomial_second (polynomial_pair polynomial_first (polynomial_constant []))) + obtain ⟨p,hp⟩:=hF + apply polynomial_fold (polynomial_mapStep ⟨p,hp⟩) (2*X+X*(p.comp (1+2*X)+1)+2) + rintro bs ⟨a,cs⟩ pre post he + let S:=weight (bs,(a,cs)) + have hb : weight bs≤S := by dsimp [S]; simp only [weight_prod]; omega + have ha : weight a≤S := by dsimp [S]; simp only [weight_prod]; omega + have hc : weight cs≤S := by dsimp [S]; simp only [weight_prod]; omega + have hl : pre.length≤S := (list_length_le_weight pre).trans ((weight_prefix he).trans hb) + have hm:=weight_map_bound (f:=fun b=>f (a,b)) (as:=pre) (N:=p.eval (1+2*S)) (by + intro b hmem + have hbs:=weight_mem hmem + have hpre:=weight_prefix he + have hh:=hp (a,b) + have ht:=polynomial_eval_monotone p (show weight (a,b)≤1+2*S by rw [weight_prod]; omega) + dsimp only at ht + omega) + rw [mapStep_fold,weight_prod] + have happ:=weight_append (pre.map fun b=>f (a,b)).reverse cs + rw [weight_reverse] at happ + simp only [Polynomial.eval_add,Polynomial.eval_mul,Polynomial.eval_ofNat,Polynomial.eval_X,Polynomial.eval_one,Polynomial.eval_comp] + change _≤2*S+S*(p.eval (1+2*S)+1)+2 + nlinarith [Nat.mul_le_mul_right (p.eval (1+2*S)+1) hl] +lemma polynomial_map {f : A → B} {F : Realizer f} (hF : PolynomialTime F) : + PolynomialTime (map F) := by + unfold map + apply polynomial_congr + apply polynomial_composition _ polynomial_reverse + apply polynomial_composition (polynomial_pair polynomial_identity (polynomial_constant [])) + obtain ⟨p,hp⟩:=hF + apply polynomial_fold (polynomial_composition (polynomial_pair (polynomial_composition polynomial_first ⟨p,hp⟩) polynomial_second) polynomial_listCons) + (X+X*(p+1)+1) + intro as bs pre post he + let S:=weight (as,bs) + have ha : weight as≤S := by dsimp [S]; rw [weight_prod]; omega + have hb : weight bs≤S := by dsimp [S]; rw [weight_prod]; omega + have hl : pre.length≤S := (list_length_le_weight pre).trans ((weight_prefix he).trans ha) + have hm:=weight_map_bound (f:=f) (as:=pre) (N:=p.eval S) (by + intro a hmem + have hh:=hp a + have ht:=polynomial_eval_monotone p ((weight_mem hmem).trans ((weight_prefix he).trans ha)) + dsimp only at ht + omega) + have hfold : pre.foldl (fun bs a=>f a::bs) bs=(pre.map f).reverse++bs := by + simp [List.foldl_flip_cons_eq_append] + change weight (pre.foldl (fun bs a=>f a::bs) bs)≤_ + rw [hfold] + have happ:=weight_append (pre.map f).reverse bs + rw [weight_reverse] at happ + simp only [Polynomial.eval_add,Polynomial.eval_mul,Polynomial.eval_X,Polynomial.eval_one] + change _≤S+S*(p.eval S+1)+1 + nlinarith [Nat.mul_le_mul_right (p.eval S+1) hl] +omit [Codec A] in +lemma filter_fold (f : A → Bool) (as bs : List A) : + as.foldl (fun bs a=>if f a then a::bs else bs) bs=(as.filter f).reverse++bs := by + induction as generalizing bs with + | nil => rfl + | cons a as ih => cases hf:f a <;> simp [List.foldl_cons,hf,ih,List.append_assoc] +lemma polynomial_filter {f : A → Bool} {F : Realizer f} (hF : PolynomialTime F) : + PolynomialTime (filter F) := by + unfold filter + apply polynomial_congr + apply polynomial_composition _ polynomial_reverse + apply polynomial_composition (polynomial_pair polynomial_identity (polynomial_constant [])) + apply polynomial_fold (polynomial_choose (polynomial_composition polynomial_first hF) polynomial_listCons polynomial_second) (2*X+1) + intro as bs pre post he + change weight (pre.foldl (fun bs a=>if f a then a::bs else bs) bs)≤_ + rw [filter_fold] + have happ:=weight_append (pre.filter f).reverse bs + rw [weight_reverse] at happ + have hf:=weight_sublist (List.filter_sublist (p:=f) (l:=pre)) + have hp:=weight_prefix he + simp only [Polynomial.eval_add,Polynomial.eval_mul,Polynomial.eval_ofNat,Polynomial.eval_X,weight_prod] + omega +lemma weight_bool_le (b : Bool) : weight b≤3 := by cases b <;> decide +lemma polynomial_any : PolynomialTime any := by + unfold any + apply polynomial_congr + apply polynomial_composition (polynomial_pair polynomial_identity (polynomial_constant false)) + apply polynomial_fold (polynomial_choose polynomial_first (polynomial_constant true) polynomial_second) 3 + intro as b pre post he + simpa using weight_bool_le (pre.foldl (fun z b=>if b then true else z) b) +lemma polynomial_membership : PolynomialTime membership := by + unfold membership + exact polynomial_congr _ (polynomial_composition + (polynomial_composition (polynomial_pair polynomial_second polynomial_first) (polynomial_mapWith polynomial_natEqual)) polynomial_any) +end MatchingFPRAS.TreeTyped + +end OAI diff --git a/lean/OAI/Combinatorics/MatchingCount/Complexity/TreePolynomialDivision.lean b/lean/OAI/Combinatorics/MatchingCount/Complexity/TreePolynomialDivision.lean new file mode 100644 index 0000000000000000000000000000000000000000..49d079c0816f5320b2ee23b22fe56dc63b5ccc8c --- /dev/null +++ b/lean/OAI/Combinatorics/MatchingCount/Complexity/TreePolynomialDivision.lean @@ -0,0 +1,101 @@ +import Mathlib +import OAI.Combinatorics.MatchingCount.Arithmetic.TreeNatDivision +import OAI.Combinatorics.MatchingCount.Complexity.TreePolynomialLists + +namespace OAI + +namespace MatchingFPRAS.TreeTyped +open Polynomial + +lemma polynomial_digitValue : PolynomialTime digitValue := by + unfold digitValue + exact polynomial_congr _ (polynomial_choose polynomial_identity (polynomial_constant 1) (polynomial_constant 0)) +lemma polynomial_divStep : PolynomialTime divStepRealizer := by + unfold divStepRealizer + apply polynomial_congr + apply polynomial_pair (polynomial_fst polynomial_second) + apply polynomial_choose + · apply polynomial_composition _ polynomial_less + apply polynomial_pair + · apply polynomial_composition _ polynomial_add + exact polynomial_pair (polynomial_composition (polynomial_snd (polynomial_snd polynomial_second)) polynomial_double) + (polynomial_composition polynomial_first polynomial_digitValue) + · exact polynomial_fst polynomial_second + · apply polynomial_pair + · exact polynomial_composition (polynomial_fst (polynomial_snd polynomial_second)) polynomial_double + · apply polynomial_composition _ polynomial_add + exact polynomial_pair (polynomial_composition (polynomial_snd (polynomial_snd polynomial_second)) polynomial_double) + (polynomial_composition polynomial_first polynomial_digitValue) + · apply polynomial_pair + · apply polynomial_composition _ polynomial_add + exact polynomial_pair + (polynomial_composition (polynomial_fst (polynomial_snd polynomial_second)) polynomial_double) (polynomial_constant 1) + · apply polynomial_composition _ polynomial_subtract + apply polynomial_pair + · apply polynomial_composition _ polynomial_add + exact polynomial_pair (polynomial_composition (polynomial_snd (polynomial_snd polynomial_second)) polynomial_double) + (polynomial_composition polynomial_first polynomial_digitValue) + · exact polynomial_fst polynomial_second +lemma nat_size_double_digit (r : ℕ) (b : Bool) : (2*r+b.toNat).size≤r.size+3 := by + have h1:=nat_size_mul 2 r + have h2:=nat_size_add (2*r) b.toNat + have h3 : b.toNat.size≤1 := Nat.size_le_size (Bool.toNat_le b) + have h4 : Nat.size 2=2 := by decide + have hm : max (2*r).size b.toNat.size≤r.size+2 := max_le (by omega) (by omega) + omega +lemma divStep_sizes (b : Bool) (n q r : ℕ) : + (divStep (b,(n,q,r))).2.1.size≤q.size+3 ∧ (divStep (b,(n,q,r))).2.2.size≤r.size+3 := by + have hq:=nat_size_double_digit q true + have hq0:=nat_size_double_digit q false + have hr:=nat_size_double_digit r b + have hsub:=Nat.size_le_size (Nat.sub_le (2*r+b.toNat) n) + simp only [Bool.toNat_true] at hq + simp only [Bool.toNat_false,Nat.add_zero] at hq0 + dsimp only [divStep] + split_ifs <;> simp only <;> constructor <;> omega +lemma divFold_sizes (bs : List Bool) (n q r : ℕ) : + (bs.foldl (fun z b=>divStep (b,z)) (n,q,r)).2.1.size≤q.size+3*bs.length ∧ + (bs.foldl (fun z b=>divStep (b,z)) (n,q,r)).2.2.size≤r.size+3*bs.length := by + induction bs generalizing q r with + | nil => simp + | cons b bs ih => + have hs:=divStep_sizes b n q r + have ht:=ih (divStep (b,(n,q,r))).2.1 (divStep (b,(n,q,r))).2.2 + have he : divStep (b,(n,q,r))=(n,(divStep (b,(n,q,r))).2.1,(divStep (b,(n,q,r))).2.2) := by + exact Prod.ext rfl (Prod.eta _).symm + change (bs.foldl _ (divStep (b,(n,q,r)))).2.1.size≤_ ∧ (bs.foldl _ (divStep (b,(n,q,r)))).2.2.size≤_ + rw [he] + simp only [List.length_cons] + constructor <;> omega +lemma polynomial_divFold : PolynomialTime (fold divStepRealizer) := by + apply polynomial_fold polynomial_divStep (40*X+10) + rintro bs ⟨n,q,r⟩ pre post he + let S:=weight (bs,(n,q,r)) + have hpre : pre.length≤S := (list_length_le_weight pre).trans ((weight_prefix he).trans (by dsimp [S]; simp only [weight_prod]; omega)) + have hq : q.size≤S := by have h:=size_le_weight q; dsimp [S]; simp only [weight_prod]; omega + have hr : r.size≤S := by have h:=size_le_weight r; dsimp [S]; simp only [weight_prod]; omega + have hn : weight n≤S := by dsimp [S]; simp only [weight_prod]; omega + have hs:=divFold_sizes pre n q r + have hqo:=weight_nat_le (pre.foldl (fun z b=>divStep (b,z)) (n,q,r)).2.1 + have hro:=weight_nat_le (pre.foldl (fun z b=>divStep (b,z)) (n,q,r)).2.2 + have hf:=divFold_first pre n q r + rw [←Prod.eta (pre.foldl (fun z b=>divStep (b,z)) (n,q,r)),weight_prod,hf, + ←Prod.eta (pre.foldl (fun z b=>divStep (b,z)) (n,q,r)).2,weight_prod] + simp only [Polynomial.eval_add,Polynomial.eval_mul,Polynomial.eval_ofNat,Polynomial.eval_X] + change _≤40*S+10 + omega +lemma polynomial_divCore : PolynomialTime divCore := by + unfold divCore + apply polynomial_composition _ polynomial_second + apply polynomial_composition _ polynomial_divFold + exact polynomial_pair + (polynomial_composition (polynomial_composition polynomial_first polynomial_toBits) polynomial_reverse) + (polynomial_pair polynomial_second (polynomial_pair (polynomial_constant 0) (polynomial_constant 0))) +lemma polynomial_division : PolynomialTime division := by + unfold division + apply polynomial_congr + exact polynomial_choose (polynomial_composition (polynomial_pair (polynomial_constant 0) polynomial_second) polynomial_less) + polynomial_divCore (polynomial_pair (polynomial_constant 0) polynomial_first) +end MatchingFPRAS.TreeTyped + +end OAI diff --git a/lean/OAI/Combinatorics/MatchingCount/Complexity/TreePolynomialGCD.lean b/lean/OAI/Combinatorics/MatchingCount/Complexity/TreePolynomialGCD.lean new file mode 100644 index 0000000000000000000000000000000000000000..9c211f797e81476c54b9a885ceba3805eece5708 --- /dev/null +++ b/lean/OAI/Combinatorics/MatchingCount/Complexity/TreePolynomialGCD.lean @@ -0,0 +1,119 @@ +import Mathlib +import OAI.Combinatorics.MatchingCount.Arithmetic.TreeFraction +import OAI.Combinatorics.MatchingCount.Complexity.TreePolynomialDivision +import OAI.Combinatorics.MatchingCount.Complexity.TreePolynomialLoop + +namespace OAI + +namespace MatchingFPRAS.TreeTyped +open Polynomial + +lemma polynomial_boolNot : PolynomialTime boolNot := by + unfold boolNot + exact polynomial_congr _ (polynomial_choose polynomial_identity (polynomial_constant false) (polynomial_constant true)) +lemma polynomial_boolAnd : PolynomialTime boolAnd := by + unfold boolAnd + exact polynomial_congr _ (polynomial_choose polynomial_first polynomial_second (polynomial_constant false)) +lemma polynomial_natEqual : PolynomialTime natEqual := by + unfold natEqual + apply polynomial_congr + apply polynomial_choose polynomial_less (polynomial_constant false) + exact polynomial_choose (polynomial_composition (polynomial_pair polynomial_second polynomial_first) polynomial_less) + (polynomial_constant false) (polynomial_constant true) +lemma polynomial_quotient : PolynomialTime quotient := polynomial_composition polynomial_division polynomial_first +lemma polynomial_remainder : PolynomialTime remainder := polynomial_composition polynomial_division polynomial_second +lemma polynomial_digits : PolynomialTime digits := by + refine ⟨X+1,?_⟩ + intro a + change 1+weight a≤_ + simp only [Polynomial.eval_add,Polynomial.eval_X,Polynomial.eval_one] + omega +lemma polynomial_bitSize : PolynomialTime bitSize := by + unfold bitSize + exact polynomial_congr _ (polynomial_composition polynomial_digits polynomial_listLength) +lemma polynomial_sortedPair : PolynomialTime sortedPairRealizer := by + unfold sortedPairRealizer + exact polynomial_congr _ (polynomial_choose polynomial_less (polynomial_pair polynomial_second polynomial_first) polynomial_identity) +lemma polynomial_gcdStep : PolynomialTime gcdStepRealizer := by + unfold gcdStepRealizer + exact polynomial_congr _ (polynomial_choose + (polynomial_composition (polynomial_pair polynomial_second (polynomial_constant 0)) polynomial_natEqual) + polynomial_identity (polynomial_pair polynomial_second polynomial_remainder)) +lemma gcdStep_size_le (x : ℕ×ℕ) : (gcdStep x).1.size+(gcdStep x).2.size≤x.1.size+x.2.size := by + dsimp only [gcdStep] + split_ifs with h + · exact le_rfl + · simp only + have hm:=Nat.size_le_size (Nat.mod_le x.1 x.2) + omega +lemma polynomial_gcd : PolynomialTime gcd := by + unfold gcd + apply polynomial_congr + apply polynomial_composition _ polynomial_first + apply polynomial_boundedRepeat + (polynomial_pair (polynomial_composition (polynomial_pair (polynomial_composition polynomial_first polynomial_bitSize) + (polynomial_composition polynomial_second polynomial_bitSize)) polynomial_add) polynomial_sortedPair) + (polynomial_composition polynomial_second polynomial_gcdStep) X (4*X+3) + (fun x _ z=>z.1.size+z.2.size≤x.1.size+x.2.size) + · intro x + simp only [Polynomial.eval_X,Function.comp_apply] + have h1:=size_le_weight x.1 + have h2:=size_le_weight x.2 + rw [←Prod.eta x,weight_prod] + try dsimp only + omega + · intro x + exact (sortedPair_size x).le + · intro x _iteration _bounded z hz + exact (gcdStep_size_le z).trans hz + · intro x _iteration z hz + have ha:=weight_nat_le z.1 + have hb:=weight_nat_le z.2 + have hx:=size_le_weight x.1 + have hy:=size_le_weight x.2 + rw [←Prod.eta z,weight_prod] + simp only [Polynomial.eval_add,Polynomial.eval_mul,Polynomial.eval_ofNat,Polynomial.eval_X] + rw [←Prod.eta x,weight_prod] + try dsimp only + omega +end MatchingFPRAS.TreeTyped + +namespace MatchingFPRAS.TreeFraction +open TreeTyped + +lemma polynomial_normalize : PolynomialTime normalizeRealizer := by + unfold normalizeRealizer + apply polynomial_congr + apply polynomial_choose + · exact polynomial_composition (polynomial_pair polynomial_second (polynomial_constant 0)) polynomial_natEqual + · exact polynomial_constant (0,1) + · exact polynomial_pair + (polynomial_composition (polynomial_pair polynomial_first polynomial_gcd) polynomial_quotient) + (polynomial_composition (polynomial_pair polynomial_second polynomial_gcd) polynomial_quotient) +lemma polynomial_mul : PolynomialTime mulRealizer := by + unfold mulRealizer + exact polynomial_composition (polynomial_pair + (polynomial_composition (polynomial_pair (polynomial_fst polynomial_first) (polynomial_fst polynomial_second)) polynomial_multiply) + (polynomial_composition (polynomial_pair (polynomial_snd polynomial_first) (polynomial_snd polynomial_second)) polynomial_multiply)) polynomial_normalize +lemma polynomial_add : PolynomialTime addRealizer := by + unfold addRealizer + apply polynomial_composition _ polynomial_normalize + apply polynomial_pair + · apply polynomial_composition _ TreeTyped.polynomial_add + exact polynomial_pair + (polynomial_composition (polynomial_pair (polynomial_fst polynomial_first) (polynomial_snd polynomial_second)) polynomial_multiply) + (polynomial_composition (polynomial_pair (polynomial_fst polynomial_second) (polynomial_snd polynomial_first)) polynomial_multiply) + · exact polynomial_composition (polynomial_pair (polynomial_snd polynomial_first) (polynomial_snd polynomial_second)) polynomial_multiply +lemma polynomial_div : PolynomialTime divRealizer := by + unfold divRealizer + exact polynomial_composition (polynomial_pair + (polynomial_composition (polynomial_pair (polynomial_fst polynomial_first) (polynomial_snd polynomial_second)) polynomial_multiply) + (polynomial_composition (polynomial_pair (polynomial_snd polynomial_first) (polynomial_fst polynomial_second)) polynomial_multiply)) polynomial_normalize +lemma polynomial_less : PolynomialTime lessRealizer := by + unfold lessRealizer + exact polynomial_composition (polynomial_pair + (polynomial_composition (polynomial_pair (polynomial_fst polynomial_first) (polynomial_snd polynomial_second)) polynomial_multiply) + (polynomial_composition (polynomial_pair (polynomial_fst polynomial_second) (polynomial_snd polynomial_first)) polynomial_multiply)) TreeTyped.polynomial_less +end MatchingFPRAS.TreeFraction + +end OAI diff --git a/lean/OAI/Combinatorics/MatchingCount/Complexity/TreePolynomialGrid.lean b/lean/OAI/Combinatorics/MatchingCount/Complexity/TreePolynomialGrid.lean new file mode 100644 index 0000000000000000000000000000000000000000..98aba705fdb5323afdf3246461ab2345cc14aaef --- /dev/null +++ b/lean/OAI/Combinatorics/MatchingCount/Complexity/TreePolynomialGrid.lean @@ -0,0 +1,62 @@ +import Mathlib +import OAI.Combinatorics.MatchingCount.Complexity.TreePolyTactic +import OAI.Combinatorics.MatchingCount.Complexity.TreeCostMeasure + +namespace OAI + +namespace MatchingFPRAS.TreeTyped +open Polynomial + +variable {A B : Type} [Codec A] [Codec B] +lemma weight_fst (a : A×B) : weight a.1≤weight a := by rcases a with ⟨a,b⟩; simp only [weight_prod]; omega +lemma weight_snd (a : A×B) : weight a.2≤weight a := by rcases a with ⟨a,b⟩; simp only [weight_prod]; omega + +variable {m n : A → ℕ} {f : A×(ℕ×ℕ) → B} +def grid (M : Realizer m) (N : Realizer n) (F : Realizer f) : + Realizer (fun a=>ExecutableDP.tabulate f (a,(m a,n a))) := by + let rowF : Realizer (fun x : (A×ℕ)×ℕ=>f (x.1.1,(x.1.2,x.2))) := + composition (pair first.fst (pair first.snd second)) F + let row : Realizer (fun x : A×ℕ=>(List.range (n x.1+1)).map fun r=>f (x.1,(x.2,r))) := + composition (pair identity (composition (composition (composition first N) successor) range)) (mapWith rowF) + exact composition (pair identity (composition M range)) (mapWith row) +lemma polynomial_grid {M : Realizer m} {N : Realizer n} {F : Realizer f} + (hM : PolynomialTime M) (hN : PolynomialTime N) (hF : PolynomialTime F) + (p q : Polynomial ℕ) (hm : ∀ a,m a≤p.eval (weight a)) (hn : ∀ a,n a≤q.eval (weight a)) : + PolynomialTime (grid M N F) := by + have hrows : PolynomialTime (composition (composition (composition (first (A:=A) (B:=ℕ)) N) successor) range) := by + apply polynomial_boundedRange (polynomial_composition (polynomial_composition polynomial_first hN) polynomial_successor) (q+1) + intro x + have hb:=(hn x.1).trans (polynomial_eval_monotone q (weight_fst x)) + simpa only [Function.comp_apply,Polynomial.eval_add,Polynomial.eval_one] using Nat.add_le_add_right hb 1 + unfold grid + dsimp only + apply polynomial_composition (polynomial_pair polynomial_identity (polynomial_boundedRange hM p hm)) + apply polynomial_mapWith + apply polynomial_composition (polynomial_pair polynomial_identity hrows) + apply polynomial_mapWith + apply polynomial_composition _ hF + exact polynomial_pair (polynomial_fst polynomial_first) + (polynomial_pair (polynomial_snd polynomial_first) polynomial_second) + +def clip (x : ℕ×ℕ) : ℕ := if x.2.size≤x.1 then x.2 else 0 +def clipRealizer : Realizer clip := + (choose (composition (pair (composition second bitSize) first) leNat) second (constant 0)).congr (by + intro x; simp only [clip,Function.comp_apply,decide_eq_true_eq]) +omit [Codec A] [Codec B] in +lemma polynomial_clip : PolynomialTime clipRealizer := by + unfold clipRealizer + apply polynomial_congr + apply polynomial_choose _ polynomial_second (polynomial_constant 0) + apply polynomial_composition _ polynomial_leNat + apply polynomial_pair (polynomial_composition polynomial_second polynomial_bitSize) polynomial_first +omit [Codec A] [Codec B] in +lemma clip_size (K n : ℕ) : (clip (K,n)).size≤K := by + unfold clip + split_ifs with h + · exact h + · simp +omit [Codec A] [Codec B] in +lemma clip_eq (K n : ℕ) (h : n.size≤K) : clip (K,n)=n := by simp [clip,h] +end MatchingFPRAS.TreeTyped + +end OAI diff --git a/lean/OAI/Combinatorics/MatchingCount/Complexity/TreePolynomialLists.lean b/lean/OAI/Combinatorics/MatchingCount/Complexity/TreePolynomialLists.lean new file mode 100644 index 0000000000000000000000000000000000000000..6617bcd9386ba8ca7d612023165e6509522f23ba --- /dev/null +++ b/lean/OAI/Combinatorics/MatchingCount/Complexity/TreePolynomialLists.lean @@ -0,0 +1,106 @@ +import Mathlib +import OAI.Combinatorics.MatchingCount.Complexity.TreePolynomialArithmetic + +namespace OAI + +namespace MatchingFPRAS.TreeTyped +open Polynomial + +variable {A B C D : Type} [Codec A] [Codec B] [Codec C] [Codec D] +lemma polynomial_fst {f : A → B×C} {F : Realizer f} (h : PolynomialTime F) : + PolynomialTime (composition F first) := polynomial_composition h polynomial_first +lemma polynomial_snd {f : A → B×C} {F : Realizer f} (h : PolynomialTime F) : + PolynomialTime (composition F second) := polynomial_composition h polynomial_second +lemma weight_append (as bs : List A) : weight (as++bs)+1=weight as+weight bs := by + induction as with + | nil => simp only [List.nil_append,weight_nil]; omega + | cons a as ih => simp only [List.cons_append,weight_cons]; omega +lemma weight_reverse (as : List A) : weight as.reverse=weight as := by + simp only [weight,size_encode_list,List.length_reverse,List.map_reverse,List.sum_reverse] +lemma weight_prefix {as pre post : List A} (h : as=pre++post) : weight pre≤weight as := by + have := weight_append pre post + have := weight_pos post + rw [h]; omega +omit [Codec A] in +lemma weight_map_bound {f : A → B} {as : List A} {N : ℕ} + (h : ∀ a∈as,weight (f a)≤N) : weight (as.map f)≤as.length*(N+1)+1 := by + induction as with + | nil => simp + | cons a as ih => + have ht:=ih (fun b hb=>h b (by simp [hb])) + have ha:=h a (by simp) + simp only [List.map_cons,weight_cons,List.length_cons] + nlinarith +lemma polynomial_reverse : PolynomialTime (reverse (A:=A)) := by + unfold reverse + apply polynomial_congr + apply polynomial_composition (polynomial_pair polynomial_identity (polynomial_constant [])) + apply polynomial_fold polynomial_listCons (2*X+1) + intro as bs pre post he + have hp := weight_prefix he + have h:=weight_append pre.reverse bs + rw [weight_reverse] at h + simp only [List.foldl_flip_cons_eq_append'] + simp only [Polynomial.eval_add,Polynomial.eval_mul,Polynomial.eval_ofNat,Polynomial.eval_X,weight_prod] + omega +lemma polynomial_mulStep : PolynomialTime mulStepRealizer := by + unfold mulStepRealizer + apply polynomial_congr + apply polynomial_pair (polynomial_composition polynomial_second polynomial_first) + apply polynomial_composition _ polynomial_add + apply polynomial_pair + · exact polynomial_composition (polynomial_composition polynomial_second polynomial_second) polynomial_double + · exact polynomial_choose polynomial_first + (polynomial_composition polynomial_second polynomial_first) (polynomial_constant 0) +lemma mulStep_size (b : Bool) (n c : ℕ) : (mulStep (b,(n,c))).2.size≤c.size+n.size+3 := by + have hh:=nat_size_mul 2 c + have ha:=nat_size_add (2*c) (if b then n else 0) + have hb : (if b then n else 0).size≤n.size := by cases b <;> simp + have h2 : Nat.size 2=2 := by decide + have hm : max (2*c).size (if b then n else 0).size≤c.size+n.size+2 := max_le (by omega) (by omega) + change (2*c+(if b then n else 0)).size≤_ + omega +lemma mulStep_fold_first (bs : List Bool) (n c : ℕ) : + (bs.foldl (fun z b=>mulStep (b,z)) (n,c)).1=n := by + induction bs generalizing c with + | nil => rfl + | cons b bs ih => exact ih _ +lemma mulStep_fold_size (bs : List Bool) (n c : ℕ) : + (bs.foldl (fun z b=>mulStep (b,z)) (n,c)).2.size≤c.size+bs.length*(n.size+3) := by + induction bs generalizing c with + | nil => simp + | cons b bs ih => + have hs:=mulStep_size b n c + have ht:=ih (2*c+(if b then n else 0)) + change (bs.foldl _ (mulStep (b,(n,c)))).2.size≤_ + simp only [mulStep] at hs + simp only [List.length_cons] + change (bs.foldl _ (n,2*c+(if b then n else 0))).2.size≤_ + nlinarith +lemma polynomial_mulFold : PolynomialTime (fold mulStepRealizer) := by + apply polynomial_fold polynomial_mulStep (10*(X+1)^2) + rintro bs ⟨n,c⟩ pre post he + let S:=weight (bs,(n,c)) + have hpre : pre.length≤S := (list_length_le_weight pre).trans ((weight_prefix he).trans (by dsimp [S]; simp only [weight_prod]; omega)) + have hn : n.size≤S := by have h:=size_le_weight n; dsimp [S]; simp only [weight_prod]; omega + have hc : c.size≤S := by have h:=size_le_weight c; dsimp [S]; simp only [weight_prod]; omega + have hn' : weight n≤S := by dsimp [S]; simp only [weight_prod]; omega + have hs:=mulStep_fold_size pre n c + have ho:=weight_nat_le (pre.foldl (fun z b=>mulStep (b,z)) (n,c)).2 + have hr:=mulStep_fold_first pre n c + rw [←Prod.eta (pre.foldl (fun z b=>mulStep (b,z)) (n,c)),weight_prod,hr] + simp only [Polynomial.eval_mul,Polynomial.eval_ofNat,Polynomial.eval_pow,Polynomial.eval_add,Polynomial.eval_X,Polynomial.eval_one] + change _≤10*(S+1)^2 + have hmul : pre.length*(n.size+3)≤S*(S+3) := Nat.mul_le_mul hpre (by omega) + nlinarith +lemma polynomial_multiply : PolynomialTime multiply := by + unfold multiply + apply polynomial_congr + apply polynomial_composition _ polynomial_second + apply polynomial_composition _ polynomial_mulFold + apply polynomial_pair + · exact polynomial_composition (polynomial_composition polynomial_first polynomial_toBits) polynomial_reverse + · exact polynomial_pair polynomial_second (polynomial_constant 0) +end MatchingFPRAS.TreeTyped + +end OAI diff --git a/lean/OAI/Combinatorics/MatchingCount/Complexity/TreePolynomialLoop.lean b/lean/OAI/Combinatorics/MatchingCount/Complexity/TreePolynomialLoop.lean new file mode 100644 index 0000000000000000000000000000000000000000..d1049241f980ff9616453efbf5f7be38f9d580d6 --- /dev/null +++ b/lean/OAI/Combinatorics/MatchingCount/Complexity/TreePolynomialLoop.lean @@ -0,0 +1,92 @@ +import Mathlib +import OAI.Combinatorics.MatchingCount.Machines.TreeListOps +import OAI.Combinatorics.MatchingCount.Complexity.TreePolynomialLists + +namespace OAI + +namespace MatchingFPRAS.TreeTyped +open Polynomial + +variable {A B : Type} [Codec A] [Codec B] +lemma polynomial_predecessor : PolynomialTime predecessor := + polynomial_composition (polynomial_pair polynomial_identity (polynomial_constant 1)) polynomial_subtract +lemma polynomial_repeatNext {f : ℕ×B → B} {F : Realizer f} (hF : PolynomialTime F) : + PolynomialTime (Repeat.nextRealizer F) := + polynomial_pair (polynomial_composition polynomial_first polynomial_predecessor) hF + +omit [Codec A] [Codec B] in +lemma countDown_invariant {f : ℕ×B → B} (I : ℕ → B → Prop) {n : ℕ} {b : B} + (hi : I n b) (hs : ∀ k exact hi + | succ n ih => exact ih (hs n (by omega) b hi) (fun k hk z hz=>hs k (by omega) z hz) + +lemma polynomial_boundedRepeat {init : A → ℕ×B} {f : ℕ×B → B} + {Init : Realizer init} {F : Realizer f} (hInit : PolynomialTime Init) (hF : PolynomialTime F) + (p q : Polynomial ℕ) (I : A → ℕ → B → Prop) + (hn : ∀ a,(init a).1≤p.eval (weight a)) + (hi : ∀ a,I a (init a).1 (init a).2) + (hs : ∀ a k,(k<(init a).1) → ∀ z,I a (k+1) z → I a k (f (k+1,z))) + (hw : ∀ a k z,I a k z → weight z≤q.eval (weight a)) : + PolynomialTime (composition Init (iterateDown F)) := by + obtain ⟨r,hr⟩ := hInit + obtain ⟨t,ht⟩ := polynomial_repeatNext hF + refine ⟨r+p*(t.comp (2+4*p+q)+4*(4*p+1)+12)+10+q,fun a=>?_⟩ + let S:=weight a + let N:=(init a).1 + let T:=t.eval (2+4*p.eval S+q.eval S) + have hN : N≤p.eval S := hn a + have hsz : ∀ kz+1) n=n+pre.length := by + clear he + induction pre generalizing n with + | nil => simp + | cons a pre ih => simp only [List.foldl_cons,ih,List.length_cons]; omega + change weight (pre.foldl (fun z (_ : A)=>z+1) n)≤_ + rw [hf] + have h:=weight_nat_le (n+pre.length) + have hs:=nat_size_add n pre.length + have hl : pre.length.size≤pre.length := Nat.size_le.mpr Nat.lt_two_pow_self + have hn:=size_le_weight n + have hp:pre.length≤weight as := (list_length_le_weight pre).trans (weight_prefix he) + have hm : max n.size pre.length.size≤weight as+weight n := max_le (by omega) (by omega) + simp only [Polynomial.eval_add,Polynomial.eval_mul,Polynomial.eval_ofNat,Polynomial.eval_X,weight_prod] + omega +end MatchingFPRAS.TreeTyped + +end OAI diff --git a/lean/OAI/Combinatorics/MatchingCount/Complexity/TreePolynomialSums.lean b/lean/OAI/Combinatorics/MatchingCount/Complexity/TreePolynomialSums.lean new file mode 100644 index 0000000000000000000000000000000000000000..a68c068ea3ebab2a35e9f77c2b80a4617e81447a --- /dev/null +++ b/lean/OAI/Combinatorics/MatchingCount/Complexity/TreePolynomialSums.lean @@ -0,0 +1,111 @@ +import Mathlib +import OAI.Combinatorics.MatchingCount.Complexity.TreeNumericCosts + +namespace OAI + +namespace MatchingFPRAS.TreeTyped +open Polynomial + +lemma nat_fold_size_bound (f : ℕ×ℕ → ℕ) (K M : ℕ) + (hf : ∀ a b,(f (a,b)).size≤a.size+b.size+K) (as : List ℕ) (z : ℕ) + (ha : ∀ a∈as,a.size≤M) : + (as.foldl (fun z a=>f (a,z)) z).size≤z.size+as.length*(M+K) := by + induction as generalizing z with + | nil => simp + | cons a as ih => + have hh:=hf a z + have ha':=ha a (by simp) + have ht:=ih (f (a,z)) (fun a h=>ha a (by simp [h])) + simp only [List.foldl_cons,List.length_cons] + nlinarith +lemma polynomial_nat_fold {f : ℕ×ℕ → ℕ} {F : Realizer f} (hF : PolynomialTime F) + (K : ℕ) (hf : ∀ a b,(f (a,b)).size≤a.size+b.size+K) : PolynomialTime (fold F) := by + apply polynomial_fold hF (4*X+4*X*(X+Polynomial.C K)+1) + intro as z pre post he + let S:=weight (as,z) + have hp : pre.length≤S := (list_length_le_weight pre).trans ((weight_prefix he).trans (by dsimp [S]; rw [weight_prod]; omega)) + have ha : ∀ a∈pre,a.size≤S := by + intro a ha + exact (size_le_weight a).trans ((weight_mem (as := as) (by simp [he,ha])).trans (by dsimp [S]; rw [weight_prod]; omega)) + have hz : z.size≤S := (size_le_weight z).trans (by dsimp [S]; rw [weight_prod]; omega) + have hb:=nat_fold_size_bound f K S hf pre z ha + have hw:=weight_nat_le (pre.foldl (fun z a=>f (a,z)) z) + have hm:=Nat.mul_le_mul_right (S+K) hp + simp only [Polynomial.eval_add,Polynomial.eval_mul,Polynomial.eval_ofNat,Polynomial.eval_X,Polynomial.eval_C,Polynomial.eval_one] + change _≤4*S+4*S*(S+K)+1 + nlinarith +lemma polynomial_listSum : PolynomialTime listSum := by + unfold listSum + apply polynomial_congr + exact polynomial_composition (polynomial_pair polynomial_identity (polynomial_constant 0)) + (polynomial_nat_fold polynomial_add 1 (fun a b=>(nat_size_add a b).trans (by omega))) +lemma polynomial_listProd : PolynomialTime listProd := by + unfold listProd + apply polynomial_congr + exact polynomial_composition (polynomial_pair polynomial_identity (polynomial_constant 1)) + (polynomial_nat_fold polynomial_multiply 0 (fun a b=>by simpa using nat_size_mul a b)) + +lemma pairingStep_fold_size (as : List ℕ) (a b M : ℕ) (ha : ∀ i∈as,i.size≤M) : + max (as.foldl (fun z i=>pairingStep (i,z)) (a,b)).1.size + (as.foldl (fun z i=>pairingStep (i,z)) (a,b)).2.size ≤ + max a.size b.size+as.length*(M+2) := by + induction as generalizing a b with + | nil => simp + | cons i as ih => + have hi:=ha i (by simp) + have hsmall:=nat_size_add i 1 + have he : Nat.size 1=1:=by decide + have hm:=nat_size_mul (i+1) a + have hmax : max i.size 1≤M+1:=max_le (by omega) (by omega) + have hstep : max b.size ((i+1)*a).size ≤ max a.size b.size+(M+2) := by + rw [he] at hsmall + have h1:=le_max_left a.size b.size + have h2:=le_max_right a.size b.size + exact max_le (by omega) (by omega) + have ht:=ih b ((i+1)*a) (fun j h=>ha j (by simp [h])) + simp only [pairingStep] at ht + simp only [List.foldl_cons,List.length_cons,pairingStep] + nlinarith +lemma polynomial_pairingFold : PolynomialTime (fold + (pair (composition (second (A:=ℕ) (B:=ℕ×ℕ)) second) + (composition (pair (composition first successor) (composition second first)) multiply))) := by + apply polynomial_fold (polynomial_pair (polynomial_composition polynomial_second polynomial_second) + (polynomial_composition (polynomial_pair (polynomial_composition polynomial_first polynomial_successor) + (polynomial_composition polynomial_second polynomial_first)) polynomial_multiply)) (8*X+8*X*(X+2)+3) + rintro as ⟨a,b⟩ pre post he + let S:=weight (as,(a,b)) + have hp : pre.length≤S := (list_length_le_weight pre).trans ((weight_prefix he).trans (by dsimp [S]; simp only [weight_prod]; omega)) + have ha : ∀ i∈pre,i.size≤S := by + intro i hi + exact (size_le_weight i).trans ((weight_mem (as := as) (by simp [he,hi])).trans (by dsimp [S]; simp only [weight_prod]; omega)) + have hab : max a.size b.size≤S := by + have hh:=size_le_weight a + have hh':=size_le_weight b + apply max_le <;> dsimp [S] <;> simp only [weight_prod] <;> omega + let z:=pre.foldl (fun z i=>pairingStep (i,z)) (a,b) + have hm:=pairingStep_fold_size pre a b S ha + have h1:=weight_nat_le z.1 + have h2:=weight_nat_le z.2 + have h3:=le_max_left z.1.size z.2.size + have h4:=le_max_right z.1.size z.2.size + change max z.1.size z.2.size≤_ at hm + have hmul:=Nat.mul_le_mul_right (S+2) hp + change weight z≤_ + rw [←Prod.eta z,weight_prod] + simp only [Polynomial.eval_add,Polynomial.eval_mul,Polynomial.eval_ofNat,Polynomial.eval_X] + change _≤8*S+8*S*(S+2)+3 + nlinarith +lemma pairingNumber_numeric_work : WorkBound pairingNumber id := by + unfold pairingNumber + apply work_congr + apply work_then_polynomial _ polynomial_first + apply work_then_polynomial _ polynomial_pairingFold + exact work_pair range_numeric_work + (work_of_polynomial (polynomial_constant (1,0)) (4*X+1) (fun n=>by simpa using weight_nat_numeric n)) + (4*X+1) (fun n=>by simpa using weight_nat_numeric n) +lemma polynomial_boundedPairingNumber {A : Type} [Codec A] {f : A → ℕ} {F : Realizer f} (hF : PolynomialTime F) + (p : Polynomial ℕ) (hn : ∀ a,f a≤p.eval (weight a)) : PolynomialTime (composition F pairingNumber) := + work_composition hF pairingNumber_numeric_work p hn +end MatchingFPRAS.TreeTyped + +end OAI diff --git a/lean/OAI/Combinatorics/MatchingCount/Graphs/AdaptiveStream.lean b/lean/OAI/Combinatorics/MatchingCount/Graphs/AdaptiveStream.lean new file mode 100644 index 0000000000000000000000000000000000000000..cf3622647d6b8fcb808131999eca34f3294101fd --- /dev/null +++ b/lean/OAI/Combinatorics/MatchingCount/Graphs/AdaptiveStream.lean @@ -0,0 +1,264 @@ +import Mathlib +import OAI.Combinatorics.MatchingCount.Model + +namespace OAI + +namespace MatchingFPRAS.PhysicalStream +open Finset + +abbrev Bits (n : ℕ) := Fin n → Bool +abbrev Stream := ℕ → Bool + +def shift (n : ℕ) (b : Stream) : Stream := fun i => b (n+i) +@[simp] lemma shift_zero (b : Stream) : shift 0 b=b := by funext i; simp [shift] +def extend {n : ℕ} (b : Bits n) : Stream := fun i => if h : ib (Fin.castAdd m i), fun j=>b (Fin.natAdd n j)) + invFun b := concat b.1 b.2 + left_inv b := by funext i; exact Fin.addCases (by simp [concat]) (by simp [concat]) i + right_inv b := by ext i <;> simp [concat] + +@[simp] lemma concat_left {n m : ℕ} (a : Bits n) (b : Bits m) (i : Fin n) : + concat a b (Fin.castAdd m i)=a i := by simp [concat] +@[simp] lemma concat_right {n m : ℕ} (a : Bits n) (b : Bits m) (i : Fin m) : + concat a b (Fin.natAdd n i)=b i := by simp [concat] + +noncomputable def average {n : ℕ} (f : Bits n → ℚ) : ℚ := + (∑ b,f b)/(2:ℚ)^n + +lemma average_const (n : ℕ) (a : ℚ) : average (fun _ : Bits n=>a)=a := by + simp [average] + +lemma average_add {n : ℕ} (f g : Bits n → ℚ) : + average (fun b=>f b+g b)=average f+average g := by + simp [average,sum_add_distrib,add_div] + +lemma average_mul {n : ℕ} (a : ℚ) (f : Bits n → ℚ) : + average (fun b=>a*f b)=a*average f := by + simp [average,←mul_sum,mul_div_assoc] + +lemma average_split {n m : ℕ} (f : Bits (n+m) → ℚ) : + average f=average (fun a : Bits n=>average (fun b : Bits m=>f (concat a b))) := by + unfold average + have h : (∑ b : Bits (n+m),f b)=∑ a : Bits n,∑ b : Bits m,f (concat a b) := by + calc + _ = ∑ ab : Bits n × Bits m,f (concat ab.1 ab.2) := + Fintype.sum_equiv (split n m) f (fun ab=>f (concat ab.1 ab.2)) (fun b=>by + change f b=f ((split n m).symm ((split n m) b)) + rw [Equiv.symm_apply_apply]) + _ = _ := Fintype.sum_prod_type _ + rw [h,←sum_div,pow_add,div_div] + congr 1 + ring + +lemma average_one (f : Bits 1 → ℚ) : + average f=(f (fun _=>false)+f (fun _=>true))/2 := by + have h : (∑ b : Bits 1,f b)=f (fun _=>false)+f (fun _=>true) := by + let e : Bits 1 ≃ Bool := Equiv.funUnique (Fin 1) Bool + have hh:=Fintype.sum_equiv e f (fun b=>f (fun _=>b)) (fun b=>by + congr 1; funext i; exact congrArg b (Subsingleton.elim i default)) + simpa only [Fintype.sum_bool,add_comm] using hh + simp only [average,h,pow_one] + +lemma shift_extend_concat {n m : ℕ} (a : Bits n) (b : Bits m) (i : ℕ) (hi : i < m) : + shift n (extend (concat a b)) i=extend b i := by + have hni : n+i 0 + | .read f => 1+max (cost (f false)) (cost (f true)) + | .delay n p => n+cost p + +def run : Experiment α → Stream → α × ℕ + | .done a,_ => (a,0) + | .read f,b => let r := run (f (b 0)) (shift 1 b); (r.1,1+r.2) + | .delay n p,b => let r := run p (shift n b); (r.1,n+r.2) + +def mean : Experiment α → (α → ℚ) → ℚ + | .done a,f => f a + | .read p,f => (mean (p false) f+mean (p true) f)/2 + | .delay _ p,f => mean p f + +lemma run_cost (p : Experiment α) (b : Stream) : (p.run b).2≤p.cost := by + induction p generalizing b with + | done a => rfl + | read p ih => + simp only [run,cost] + have h:=ih (b 0) (shift 1 b) + cases hb : b 0 <;> simp only [hb] at h <;> omega + | delay n p ih => exact Nat.add_le_add_left (ih (shift n b)) n + +lemma run_congr (p : Experiment α) (a b : Stream) + (h : ∀ i,i rfl + | read p ih => + have h0 : a 0=b 0 := h 0 (by simp [cost]) + simp only [run,h0] + have hh : run (p (b 0)) (shift 1 a)=run (p (b 0)) (shift 1 b) := by + apply ih + intro i hi + apply h + cases he : b 0 <;> simp only [he] at hi <;> simp only [cost] <;> omega + rw [hh] + | delay n p ih => + simp only [run] + have hh : run p (shift n a)=run p (shift n b) := by + apply ih + intro i hi + exact h (n+i) (by simp only [cost]; omega) + rw [hh] + +lemma run_suffix {n m : ℕ} (p : Experiment α) (h : p.cost ≤ m) + (a : Bits n) (b : Bits m) : + p.run (shift n (extend (concat a b)))=p.run (extend b) := by + apply run_congr + intro i hi + exact shift_extend_concat a b i (lt_of_lt_of_le hi h) + +theorem average_run (p : Experiment α) (f : α → ℚ) (n : ℕ) (hn : p.cost≤n) : + average (fun b : Bits n=>f (p.run (extend b)).1)=p.mean f := by + induction p generalizing n with + | done a => exact average_const n (f a) + | delay k p ih => + have hk : k≤n := by simp only [cost] at hn; omega + obtain ⟨m,rfl⟩:=Nat.exists_eq_add_of_le hk + have hm : p.cost ≤ m := by simpa only [cost,Nat.add_le_add_iff_left] using hn + rw [average_split] + have hrun (a : Bits k) (b : Bits m) : + f ((delay k p).run (extend (concat a b))).1=f (p.run (extend b)).1 := by + simp only [run,run_suffix p hm a b] + simp_rw [hrun,ih m hm] + exact average_const k (p.mean f) + | read p ih => + have hk : 1≤n := by simp only [cost] at hn; omega + obtain ⟨m,rfl⟩:=Nat.exists_eq_add_of_le hk + have hm (b : Bool) : (p b).cost ≤ m := by + simp only [cost,Nat.add_le_add_iff_left] at hn + cases b <;> omega + rw [average_split] + have hrun (a : Bits 1) (b : Bits m) : + f ((read p).run (extend (concat a b))).1=f ((p (a 0)).run (extend b)).1 := by + simp only [run,extend_concat_zero,run_suffix _ (hm (a 0)) a b] + simp_rw [hrun,ih _ m (hm _)] + rw [average_one] + rfl + +def bind : Experiment α → (α → Experiment β) → Experiment β + | .done a,f => f a + | .read p,f => .read (fun b=>(p b).bind f) + | .delay n p,f => .delay n (p.bind f) + +lemma mean_bind (p : Experiment α) (q : α → Experiment β) (f : β → ℚ) : + (p.bind q).mean f=p.mean (fun a=>(q a).mean f) := by + induction p with + | done a => rfl + | read p ih => simp [bind,mean,ih] + | delay n p ih => exact ih + +lemma run_bind (p : Experiment α) (q : α → Experiment β) (b : Stream) : + (p.bind q).run b= + let r:=p.run b + let s:=(q r.1).run (shift r.2 b) + (s.1,r.2+s.2) := by + induction p generalizing b with + | done a => simp [bind,run] + | read p ih => + simp only [bind,run,ih] + have hs (n : ℕ) : shift n (shift 1 b)=shift (1+n) b := by + funext i; simp [shift,Nat.add_assoc] + simp only [hs,Nat.add_assoc] + | delay n p ih => + simp only [bind,run,ih] + have hs (m : ℕ) : shift m (shift n b)=shift (n+m) b := by + funext i; simp [shift,Nat.add_assoc] + simp only [hs,Nat.add_assoc] + +lemma cost_bind_le (p : Experiment α) (q : α → Experiment β) (N : ℕ) + (hq : ∀ a,(q a).cost ≤ N) : (p.bind q).cost ≤ p.cost+N := by + induction p with + | done a => simpa only [bind,cost,Nat.zero_add] using hq a + | read p ih => + simp only [bind,cost] + have h0:=ih false + have h1:=ih true + omega + | delay n p ih => simpa only [bind,cost,Nat.add_assoc] using Nat.add_le_add_left ih n + +def map (f : α → β) (p : Experiment α) : Experiment β := p.bind (fun a=>.done (f a)) + +@[simp] lemma cost_map (f : α → β) (p : Experiment α) : (p.map f).cost=p.cost := by + induction p with + | done a => rfl + | read p ih => simp only [map,bind,cost]; change 1+max ((p false).map f).cost ((p true).map f).cost=_; rw [ih false,ih true] + | delay n p ih => change n+(p.map f).cost=n+p.cost; rw [ih] + +lemma run_map (f : α → β) (p : Experiment α) (b : Stream) : + (p.map f).run b=(f (p.run b).1,(p.run b).2) := by simp [map,run_bind,run] + +lemma mean_map (f : α → β) (p : Experiment α) (g : β → ℚ) : + (p.map f).mean g=p.mean (fun a=>g (f a)) := by simp [map,mean_bind,mean] + +def word : (n : ℕ) → Experiment (Bits n) + | 0 => .done Fin.elim0 + | n+1 => .read (fun b=>(word n).map (Fin.cons b)) + +@[simp] lemma cost_word (n : ℕ) : (word n).cost=n := by + induction n with + | zero => rfl + | succ n ih => simp only [word,cost,cost_map,ih,max_self]; omega + +lemma run_word (n : ℕ) (b : Stream) : + (word n).run b=((fun i : Fin n=>b i),n) := by + induction n generalizing b with + | zero => exact Prod.ext (funext (fun i=>Fin.elim0 i)) rfl + | succ n ih => + simp only [word,run,run_map,ih,shift] + congr 1 + · funext i + refine Fin.cases ?_ (fun j=>?_) i + · rfl + · simp only [Fin.cons_succ,Fin.val_succ]; congr 1; omega + · omega + +lemma mean_word (n : ℕ) (f : Bits n → ℚ) : (word n).mean f=average f := by + rw [←average_run (word n) f n (by rw [cost_word])] + congr 1 + funext b + rw [run_word] + congr 1 + funext i + simp [extend,i.isLt] + +theorem adaptive_word_law (p : Experiment α) (width : α → ℕ) + (q : (a : α) → Bits (width a) → Experiment β) (f : β → ℚ) + (n : ℕ) (hn : (p.bind (fun a=>(word (width a)).bind (q a))).cost ≤ n) : + average (fun b : Bits n=> f ((p.bind (fun a=>(word (width a)).bind (q a))).run (extend b)).1)= + p.mean (fun a=>average (fun w=>(q a w).mean f)) := by + rw [average_run _ _ _ hn,mean_bind] + congr 1 + funext a + rw [mean_bind,mean_word] + +end Experiment +end MatchingFPRAS.PhysicalStream + +end OAI diff --git a/lean/OAI/Combinatorics/MatchingCount/Graphs/Admissible.lean b/lean/OAI/Combinatorics/MatchingCount/Graphs/Admissible.lean new file mode 100644 index 0000000000000000000000000000000000000000..46c195243ad3ffa7ebd7255026626becea96f85d --- /dev/null +++ b/lean/OAI/Combinatorics/MatchingCount/Graphs/Admissible.lean @@ -0,0 +1,443 @@ +import Mathlib +import OAI.Combinatorics.MatchingCount.Graphs.EnlargementRun +import OAI.Combinatorics.MatchingCount.Sampling.PairStep + +namespace OAI + +namespace MatchingFPRAS.Variation + +open Finset + +variable {Ω Ψ : Type*} [Fintype Ω] [Fintype Ψ] + +lemma bind_perturbation_on (p : Ω → ℝ) (k l : Ω → Ψ → ℝ) + (hp : ∀ x,0 ≤ p x) (hs : ∑ x,p x=1) (ε : ℝ) + (he : ∀ x,p x≠0 → tv (k x) (l x) ≤ ε) : + tv (bind p k) (bind p l) ≤ ε := by + unfold tv bind + have h : ∑ y,|∑ x,p x*k x y-∑ x,p x*l x y| ≤ 2*ε := by + calc + _ = ∑ y,|∑ x,p x*(k x y-l x y)| := by simp only [mul_sub,sum_sub_distrib] + _ ≤ ∑ y,∑ x,|p x*(k x y-l x y)| := sum_le_sum (fun y _ => abs_sum_le_sum_abs _ _) + _ = ∑ x,p x*(∑ y,|k x y-l x y|) := by + rw [sum_comm]; simp_rw [abs_mul,abs_of_nonneg (hp _),←mul_sum] + _ ≤ ∑ x,p x*(2*ε) := by + apply sum_le_sum + intro x _ + by_cases hx : p x=0 + · simp [hx] + · apply mul_le_mul_of_nonneg_left _ (hp x) + have hh:=he x hx + unfold tv at hh + linarith + _ = _ := by rw [←sum_mul,hs,one_mul] + linarith + +end MatchingFPRAS.Variation + +namespace MatchingFPRAS.WeightedOptions + +open Finset Variation + +variable {J Ω B : Type*} [Fintype J] [DecidableEq J] [Fintype Ω] [DecidableEq Ω] + +variable [Fintype B] [Nonempty B] + +theorem drawThen_tv_on (c : WeightedOptions J) (g : J → B → Ω) (k : ℕ) + (P : J → Ω → ℝ) (e : ℝ) (he : ∀ j,c.law j≠0 → tv (imageLaw (g j)) (P j)≤e) : + tv (imageLaw (c.drawThen g k)) (bind (fun j=>(c.law j:ℝ)) P)≤ + 2*c.size/(2:ℝ)^k+e := by + rw [drawThen_law] + calc + _ ≤ tv (bind (imageLaw (c.draw k)) (fun j=>imageLaw (g j))) + (bind (fun j=>(c.law j:ℝ)) (fun j=>imageLaw (g j)))+ + tv (bind (fun j=>(c.law j:ℝ)) (fun j=>imageLaw (g j))) + (bind (fun j=>(c.law j:ℝ)) P) := tv_triangle _ _ _ + _ ≤ 2*c.size/(2:ℝ)^k+e := add_le_add + ((bind_contraction _ _ _ (fun _=>imageLaw_nonneg _) (fun _=>imageLaw_sum _)).trans (c.draw_tv k)) + (bind_perturbation_on _ _ _ (fun j=>by exact_mod_cast c.law_nonneg j) + (c.real_law_sum) e (fun j hj=>he j (by exact_mod_cast hj))) + +end MatchingFPRAS.WeightedOptions + +namespace MatchingFPRAS.Replica + +open Finset Variation + +variable {I Ω B : Type*} [Fintype I] [DecidableEq I] [Fintype Ω] [DecidableEq Ω] + +variable [Fintype B] [Nonempty B] [LinearOrder (Update I)] + +def admissible (guides : I → Finset I) (base : Finset I) : Option (Update I) → Prop + | none => True + | some (.inl ij) => ij.2∈guides ij.1 + | some (.inr i) => i∈base + +lemma scanChoice_support (guides : I → Finset I) (base : Finset I) (hb : base.Nonempty) + (u : Option (Update I)) (hu : (scanChoice guides base hb).law u≠0) : + admissible guides base u := by + cases u with + | none => trivial + | some u => + by_contra h + apply hu + simp only [scanChoice,WeightedOptions.mix_law,WeightedOptions.pure_law, + WeightedOptions.map_law] + simp only [reduceCtorEq,ite_false,Option.some.injEq,sum_ite_eq',mem_univ,ite_true] + rw [WeightedOptions.uniform_law] + have hn : u∉updates guides base := by + cases u <;> simpa [updates,admissible] using h + simp [hn] + +omit [LinearOrder (Update I)] in +lemma localSampler_tv_on [LinearOrder (Update I)] (p : I → Ω → ℝ) (Q : ∀ x y,PairCapacity p x y) + (guides : I → Finset I) (base : Finset I) + (pair : I → I → (Ω×Ω) → B → Ω×Ω) (refresh : I → B → Ω) (e : ℝ) (he : 0≤e) + (hp : ∀ x y,y∈guides x → ∀ a,tv (imageLaw (pair x y a)) + (fun b=>(Q x y).q a b/(p x a.1*p y a.2))≤e) + (hr : ∀ i,i∈base → tv (imageLaw (refresh i)) (p i)≤e) + (s : I → Ω) (u : Option (Update I)) (hu : admissible guides base u) : + tv (imageLaw (localSampler pair refresh s u)) (updateKernel p Q s u)≤e := by + cases u with + | none => + have h : imageLaw (localSampler pair refresh s none)=updateKernel p Q s none := by + funext t + simp only [imageLaw,push,localSampler,updateKernel] + by_cases hst : s=t + · subst t + simpa using uniform_sum (A:=B) + · simp [hst] + rw [h,tv_self] + exact he + | some u => cases u with + | inl ij => + have hk : updateKernel p Q s (some (.inl ij))= + push (fun b=>(Q ij.1 ij.2).q (s ij.1,s ij.2) b/(p ij.1 (s ij.1)*p ij.2 (s ij.2))) + (replacePair ij.1 ij.2 s) := by + funext t + simp only [updateKernel,pairStep,push] + rw [hk] + change tv (imageLaw ((replacePair ij.1 ij.2 s) ∘ pair ij.1 ij.2 (s ij.1,s ij.2))) + (push (fun b=>(Q ij.1 ij.2).q (s ij.1,s ij.2) b/(p ij.1 (s ij.1)*p ij.2 (s ij.2))) + (replacePair ij.1 ij.2 s))≤e + rw [imageLaw_comp] + exact (push_contraction _ _ _).trans (hp _ _ hu _) + | inr i => + have hk : updateKernel p Q s (some (.inr i))=push (p i) (Function.update s i) := by + funext t + simp only [updateKernel,baseStep,push] + apply sum_congr rfl + intro a _ + congr 1 + rw [hk] + change tv (imageLaw ((Function.update s i) ∘ refresh i)) (push (p i) (Function.update s i))≤e + rw [imageLaw_comp] + exact (push_contraction _ _ _).trans (hr i hu) + +theorem sampleScan_tv_on (p : I → Ω → ℝ) (hp : ∀ i a,0

if r=s then pairStep p x y Q r t else 0 + have hf := slice_mean p hs x y f + have hmean : mean p f=density p s*pairStep p x y Q s t := by + simp only [mean,f,mul_ite,mul_zero,sum_ite_eq',mem_univ,ite_true] + rw [hmean] at hf + rw [←hf] + unfold pairFlow pushedFlow mean + rw [Fintype.sum_prod_type] + apply sum_congr rfl + intro r _ + rw [Fintype.sum_prod_type,mul_sum] + apply sum_congr rfl + intro a _ + have hpa : ((replacePair x y r a) x,(replacePair x y r a) y)=a := replacePair_at x y hxy r a + rcases a with ⟨ax,ay⟩ + have hx : (replacePair x y r (ax,ay)) x=ax := congrArg Prod.fst hpa + have hy : (replacePair x y r (ax,ay)) y=ay := congrArg Prod.snd hpa + by_cases ha : replacePair x y r (ax,ay)=s + · simp only [f,ha,ite_true] + rw [←ha] + simp only [pairStep,hx,hy,replacePair_idem,mul_sum] + apply sum_congr rfl + intro b _ + by_cases hb : replacePair x y r b=t + · simp only [ha,hb,ite_true] + field_simp [ne_of_gt (hp x ax),ne_of_gt (hp y ay)] + · simp only [Prod.mk.injEq,ha,hb,true_and,ite_false,mul_zero] + · simp only [f,ite_eq_right ha,mul_zero] + apply sum_eq_zero + intro b _ + simp only [Prod.mk.injEq,ha,false_and,ite_false] + +lemma local_baseFlow (_hp : ∀ i a,0

if r=s then baseStep p i r t else 0 + have hf := mean_average p hs i f + have hmean : mean p f=density p s*baseStep p i s t := by + simp only [mean,f,mul_ite,mul_zero,sum_ite_eq',mem_univ,ite_true] + rw [hmean] at hf + rw [←hf] + unfold baseFlow pushedFlow mean + rw [Fintype.sum_prod_type] + simp only [average_apply] + apply sum_congr rfl + intro r _ + rw [Fintype.sum_prod_type,mul_sum] + apply sum_congr rfl + intro a _ + by_cases ha : Function.update r i a=s + · simp only [f,ite_eq_left ha] + rw [←ha] + simp only [baseStep,Function.update_idem,mul_sum] + apply sum_congr rfl + intro b _ + by_cases hb : Function.update r i b=t + · simp only [ha,hb,ite_true] + · simp only [Prod.mk.injEq,ha,hb,true_and,ite_false,mul_zero] + · simp only [f,ite_eq_right ha,mul_zero] + apply sum_eq_zero + intro b _ + simp only [Prod.mk.injEq,ha,false_and,ite_false] + +noncomputable def localScan (guides : I → Finset I) (base : Finset I) + (Q : ∀ x y,PairCapacity p x y) (s t : I → Ω) : ℝ := + (if s=t then (1:ℝ) else 0)/2+ + ((∑ x,∑ y ∈ guides x,pairStep p x y (Q x y) s t)+∑ i ∈ base,baseStep p i s t)/ + (2*(updateCount guides base:ℝ)) + +theorem localScan_kernel (hp : ∀ i a,0

hp i (s i) + have hpair : (∑ x,∑ y ∈ guides x,pairFlow p x y (Q x y) s t)= + density p s*(∑ x,∑ y ∈ guides x,pairStep p x y (Q x y) s t) := by + simp only [mul_sum] + apply sum_congr rfl + intro x _ + apply sum_congr rfl + intro y hy + exact local_pairFlow p hp hs x y (hself x y hy) (Q x y) s t + have hbase : (∑ i ∈ base,baseFlow p i s t)=density p s*(∑ i ∈ base,baseStep p i s t) := by + simp only [mul_sum] + apply sum_congr rfl + intro i hi + exact local_baseFlow p hp hs i s t + unfold FiniteChain.kernel scanFlow localScan + rw [hpair,hbase] + have hn := ne_of_gt hpos + by_cases hst : s=t + · subst t + simp only [ite_true] + field_simp [hn] + · simp only [ite_eq_right hst,zero_div] + field_simp [hn] + ring + +end MatchingFPRAS.Replica + +namespace MatchingFPRAS.WeightedOptions + +open Finset Variation + +variable {J Ω B : Type*} [Fintype J] [DecidableEq J] [Fintype Ω] [DecidableEq Ω] + +variable [Fintype B] [Nonempty B] + +def drawThen (c : WeightedOptions J) (g : J → B → Ω) (k : ℕ) + (bits : (Fin k → Bool) × B) : Ω := g (c.draw k bits.1) bits.2 + +omit [DecidableEq J] [Fintype Ω] [DecidableEq Ω] [Nonempty B] in +lemma drawThen_law [DecidableEq J] [Fintype Ω] [DecidableEq Ω] [Nonempty B] + (c : WeightedOptions J) (g : J → B → Ω) (k : ℕ) : + imageLaw (c.drawThen g k)=bind (imageLaw (c.draw k)) (fun j=>imageLaw (g j)) := + imageLaw_adaptive_pair (c.draw k) g + +theorem drawThen_tv (c : WeightedOptions J) (g : J → B → Ω) (k : ℕ) + (P : J → Ω → ℝ) (hn : ∀ j x,0≤P j x) (hs : ∀ j,∑ x,P j x=1) + (e : ℝ) (he : ∀ j,tv (imageLaw (g j)) (P j)≤e) : + tv (imageLaw (c.drawThen g k)) (bind (fun j=>(c.law j:ℝ)) P)≤ + 2*c.size/(2:ℝ)^k+e := by + rw [drawThen_law] + calc + _ ≤ tv (bind (imageLaw (c.draw k)) (fun j=>imageLaw (g j))) + (bind (imageLaw (c.draw k)) P)+ + tv (bind (imageLaw (c.draw k)) P) (bind (fun j=>(c.law j:ℝ)) P) := tv_triangle _ _ _ + _ ≤ e+2*c.size/(2:ℝ)^k := add_le_add + (bind_perturbation _ _ _ (imageLaw_nonneg _) (imageLaw_sum _) e he) + ((bind_contraction _ _ P hn hs).trans (c.draw_tv k)) + _ = _ := add_comm _ _ + +end MatchingFPRAS.WeightedOptions + +namespace MatchingFPRAS.Replica + +open Finset Variation + +variable {I Ω : Type*} [Fintype I] [DecidableEq I] [Fintype Ω] [DecidableEq Ω] + +abbrev Update (I : Type*) := (I×I) ⊕ I + +def updates (guides : I → Finset I) (base : Finset I) : Finset (Update I) := + ((univ : Finset (I×I)).filter (fun ij=>ij.2∈guides ij.1)).disjSum base + +lemma updates_card (guides : I → Finset I) (base : Finset I) : + (updates guides base).card=updateCount guides base := by + simp only [updates,card_disjSum,updateCount] + congr 1 + rw [card_eq_sum_ones,sum_filter,Fintype.sum_prod_type] + apply sum_congr rfl + intro x _ + simp + +lemma updates_nonempty (guides : I → Finset I) (base : Finset I) (hb : base.Nonempty) : + (updates guides base).Nonempty := by + obtain ⟨i,hi⟩:=hb + exact ⟨Sum.inr i,by simp [updates,hi]⟩ + +variable (p : I → Ω → ℝ) + +noncomputable def updateKernel (Q : ∀ x y,PairCapacity p x y) (s : I → Ω) : + Option (Update I) → (I → Ω) → ℝ + | none,t => if s=t then 1 else 0 + | some (.inl ij),t => pairStep p ij.1 ij.2 (Q ij.1 ij.2) s t + | some (.inr i),t => baseStep p i s t + +lemma pairStep_nonneg (hp : ∀ i a,0

dsimp [updateKernel]; split_ifs <;> norm_num + | some u => cases u with + | inl ij => exact pairStep_nonneg p hp _ _ _ _ _ + | inr i => exact baseStep_nonneg p (fun i a=>(hp i a).le) _ _ _ + +lemma updateKernel_sum (hp : ∀ i a,0

simp [updateKernel] + | some u => cases u with + | inl ij => exact pairStep_sum p hp _ _ _ _ + | inr i => exact baseStep_sum p hs _ _ + +variable [LinearOrder (Update I)] + +def scanChoice (guides : I → Finset I) (base : Finset I) (hb : base.Nonempty) : + WeightedOptions (Option (Update I)) := + WeightedOptions.mix (1/2) (by norm_num) (by norm_num) (WeightedOptions.pure none) + ((WeightedOptions.uniform (updates guides base) (updates_nonempty guides base hb)).map some) + +lemma scanChoice_size (guides : I → Finset I) (base : Finset I) (hb : base.Nonempty) : + (scanChoice guides base hb).size=1+updateCount guides base := by + simp only [scanChoice,WeightedOptions.mix,WeightedOptions.map,WeightedOptions.pure, + WeightedOptions.uniform,updates_card] + +lemma scanChoice_law (guides : I → Finset I) (base : Finset I) (hb : base.Nonempty) + (Q : ∀ x y,PairCapacity p x y) (s t : I → Ω) : + bind (fun u=>((scanChoice guides base hb).law u:ℝ)) (updateKernel p Q s) t= + localScan p guides base Q s t := by + unfold Variation.bind + rw [Fintype.sum_option] + simp only [scanChoice,WeightedOptions.mix_law,WeightedOptions.pure_law, + WeightedOptions.map_law] + simp only [Option.some.injEq,reduceCtorEq,ite_false,sum_const_zero,mul_zero,zero_add] + simp only [sum_ite_eq',mem_univ,ite_true,WeightedOptions.uniform_law] + push_cast + rw [updates_card] + simp only [updateKernel,Fintype.sum_sum_type,Fintype.sum_prod_type,updates, + inl_mem_disjSum,inr_mem_disjSum, + mem_filter,mem_univ,true_and] + unfold localScan + simp only [apply_ite,Rat.cast_inv,Rat.cast_natCast,Rat.cast_zero, + ite_mul,zero_mul,mul_zero,sum_ite_mem,univ_inter] + simp only [←mul_sum] + by_cases h : s=t <;> simp only [h,ite_true,ite_false] <;> ring + + + +open Finset Variation + +variable {I Ω B : Type*} [Fintype I] [DecidableEq I] [Fintype Ω] [DecidableEq Ω] + +variable [Fintype B] [Nonempty B] + +def localSampler (pair : I → I → (Ω×Ω) → B → Ω×Ω) (refresh : I → B → Ω) + (s : I → Ω) : Option (Update I) → B → (I → Ω) + | none,_ => s + | some (.inl ij),b => replacePair ij.1 ij.2 s (pair ij.1 ij.2 (s ij.1,s ij.2) b) + | some (.inr i),b => Function.update s i (refresh i b) + +lemma localSampler_tv (p : I → Ω → ℝ) (Q : ∀ x y,PairCapacity p x y) + (pair : I → I → (Ω×Ω) → B → Ω×Ω) (refresh : I → B → Ω) (e : ℝ) (he : 0≤e) + (hp : ∀ x y a,tv (imageLaw (pair x y a)) (fun b=>(Q x y).q a b/(p x a.1*p y a.2))≤e) + (hr : ∀ i,tv (imageLaw (refresh i)) (p i)≤e) (s : I → Ω) (u : Option (Update I)) : + tv (imageLaw (localSampler pair refresh s u)) (updateKernel p Q s u)≤e := by + cases u with + | none => + have h : imageLaw (localSampler pair refresh s none)=updateKernel p Q s none := by + funext t + simp only [imageLaw,push,localSampler,updateKernel] + by_cases hst : s=t + · subst t + simpa using uniform_sum (A:=B) + · simp [hst] + rw [h,tv_self] + exact he + | some u => cases u with + | inl ij => + have hk : updateKernel p Q s (some (.inl ij))= + push (fun b=>(Q ij.1 ij.2).q (s ij.1,s ij.2) b/(p ij.1 (s ij.1)*p ij.2 (s ij.2))) + (replacePair ij.1 ij.2 s) := by + funext t + simp only [updateKernel,pairStep,push] + rw [hk] + change tv (imageLaw ((replacePair ij.1 ij.2 s) ∘ pair ij.1 ij.2 (s ij.1,s ij.2))) + (push (fun b=>(Q ij.1 ij.2).q (s ij.1,s ij.2) b/(p ij.1 (s ij.1)*p ij.2 (s ij.2))) + (replacePair ij.1 ij.2 s))≤e + rw [imageLaw_comp] + exact (push_contraction _ _ _).trans (hp _ _ _) + | inr i => + have hk : updateKernel p Q s (some (.inr i))=push (p i) (Function.update s i) := by + funext t + simp only [updateKernel,baseStep,push] + apply sum_congr rfl + intro a _ + congr 1 + rw [hk] + change tv (imageLaw ((Function.update s i) ∘ refresh i)) (push (p i) (Function.update s i))≤e + rw [imageLaw_comp] + exact (push_contraction _ _ _).trans (hr i) + +variable [LinearOrder (Update I)] + +def sampleScan (guides : I → Finset I) (base : Finset I) (hb : base.Nonempty) + (pair : I → I → (Ω×Ω) → B → Ω×Ω) (refresh : I → B → Ω) (k : ℕ) (s : I → Ω) : + ((Fin k → Bool) × B) → (I → Ω) := + (scanChoice guides base hb).drawThen (localSampler pair refresh s) k + +theorem sampleScan_tv (p : I → Ω → ℝ) (hp : ∀ i a,0

(Q x y).q a b/(p x a.1*p y a.2))≤e) + (hr : ∀ i,tv (imageLaw (refresh i)) (p i)≤e) (k : ℕ) (s : I → Ω) : + tv (imageLaw (sampleScan guides base hb pair refresh k s)) + (FiniteChain.kernel (density p) (scanFlow p guides base Q) s)≤ + 2*(1+updateCount guides base)/(2:ℝ)^k+e := by + have ht := WeightedOptions.drawThen_tv (scanChoice guides base hb) (localSampler pair refresh s) + k (updateKernel p Q s) (updateKernel_nonneg p hp Q s) (updateKernel_sum p hp hs Q s) + e (localSampler_tv p Q pair refresh e he hpr hr s) + have hl : Variation.bind (fun u=>((scanChoice guides base hb).law u:ℝ)) (updateKernel p Q s)= + FiniteChain.kernel (density p) (scanFlow p guides base Q) s := by + funext t + rw [scanChoice_law,localScan_kernel p hp hs guides hself base Q] + rw [hl,scanChoice_size] at ht + simpa only [Nat.cast_add,Nat.cast_one,sampleScan] using ht + +end MatchingFPRAS.Replica + +namespace MatchingFPRAS.Variation + +open Finset + +variable {Ω B : Type*} [Fintype Ω] [DecidableEq Ω] [Fintype B] [Nonempty B] + +def runSample (g : Ω → B → Ω) (z : Ω) : (n : ℕ) → (Fin n → B) → Ω + | 0,_ => z + | n+1,bits => g (runSample g z n (Fin.init bits)) (bits (Fin.last n)) + +omit [DecidableEq Ω] [Nonempty B] in +lemma runSample_law [DecidableEq Ω] [Nonempty B] (g : Ω → B → Ω) (z : Ω) (n : ℕ) : + imageLaw (runSample g z (n+1))=bind (imageLaw (runSample g z n)) (fun s=>imageLaw (g s)) := by + let e : ((Fin n → B) × B) ≃ (Fin (n+1) → B) := + (Equiv.prodComm _ _).trans (Fin.snocEquiv (fun _=>B)) + have h : runSample g z (n+1) ∘ e=(fun u=>g (runSample g z n u.1) u.2) := by + funext u + change g (runSample g z n (Fin.init (Fin.snoc (α:=fun _ : Fin (n+1)=>B) u.1 u.2))) + (Fin.snoc (α:=fun _ : Fin (n+1)=>B) u.1 u.2 (Fin.last n))=_ + simp only [Fin.init_snoc,Fin.snoc_last] + rw [←imageLaw_comp_equiv e,h] + exact imageLaw_adaptive_pair (runSample g z n) g + +theorem runSample_walk_tv (π : Ω → ℝ) (C : Ω → Ω → ℝ) + (hn : ∀ s t,0≤FiniteChain.kernel π C s t) (hs : ∀ s,∑ t,FiniteChain.kernel π C s t=1) + (g : Ω → B → Ω) (d : ℝ) + (hd : ∀ s,tv (imageLaw (g s)) (FiniteChain.kernel π C s)≤d) (z : Ω) (n : ℕ) : + tv (imageLaw (runSample g z n)) (FiniteChain.walk π C z n)≤n*d := by + induction n with + | zero => + have h : imageLaw (runSample g z 0)=FiniteChain.walk π C z 0 := by + funext b + by_cases hb : b=z + · subst b; simp [imageLaw,push,uniform,runSample,FiniteChain.walk] + · simp [imageLaw,push,runSample,FiniteChain.walk,hb,Ne.symm hb] + rw [h,tv_self] + simp + | succ n ih => + rw [runSample_law] + change tv (bind _ _) (bind _ _)≤_ + calc + _ ≤ tv (bind (imageLaw (runSample g z n)) (fun s=>imageLaw (g s))) + (bind (imageLaw (runSample g z n)) (FiniteChain.kernel π C))+ + tv (bind (imageLaw (runSample g z n)) (FiniteChain.kernel π C)) + (bind (FiniteChain.walk π C z n) (FiniteChain.kernel π C)) := tv_triangle _ _ _ + _ ≤ d+n*d := add_le_add + (bind_perturbation _ _ _ (imageLaw_nonneg _) (imageLaw_sum _) d hd) + ((bind_contraction _ _ _ hn hs).trans ih) + _ = _ := by push_cast; ring + +end MatchingFPRAS.Variation + +end OAI diff --git a/lean/OAI/Combinatorics/MatchingCount/Sampling/Plan.lean b/lean/OAI/Combinatorics/MatchingCount/Sampling/Plan.lean new file mode 100644 index 0000000000000000000000000000000000000000..2f7d7cc8dc5f046d7d735e5a663dd8c8e2d3a9a1 --- /dev/null +++ b/lean/OAI/Combinatorics/MatchingCount/Sampling/Plan.lean @@ -0,0 +1,383 @@ +import Mathlib +import OAI.Combinatorics.MatchingCount.Sampling.RankOrder + +namespace OAI + +namespace MatchingFPRAS.UnitRefresh.Materialized + +open Finset + +variable {V : Type*} [Fintype V] [DecidableEq V] + +def plan {m : ℕ} (rank : Fin m → ℕ) : List (Fin m) := + (List.ofFn (fun l : Fin m => l)).mergeSort (fun a b=>decide (rank b≤rank a)) + +lemma plan_mem {m : ℕ} (rank : Fin m → ℕ) (a : Fin m) : a∈plan rank := by + unfold plan + rw [(List.mergeSort_perm _ _).mem_iff] + simp + +lemma plan_length {m : ℕ} (rank : Fin m → ℕ) : (plan rank).length=m := by + unfold plan + rw [(List.mergeSort_perm _ _).length_eq] + simp + +lemma plan_sorted {m : ℕ} (rank : Fin m → ℕ) : + (plan rank).Pairwise (fun a b=>rank b≤rank a) := by + let r := fun a b : Fin m => rank b≤rank a + let : Std.Total r := ⟨fun a b => le_total (rank b) (rank a)⟩ + let : IsTrans (Fin m) r := ⟨fun a b c hab hbc => hbc.trans hab⟩ + exact List.pairwise_mergeSort' r _ + +lemma plan_legal {m : ℕ} (bags : V → Finset (Fin m)) (rank : Fin m → ℕ) + (parent : Fin m → Option (Fin m)) (hb : RankedBags bags rank parent) + (hne : ∀ x,(bags x).Nonempty) (hp : ∀ l p,parent l=some p → rank ppairingCount) + rw [←active_univ] + rw [tableDP_correct bags parent _ _ (plan_legal bags rank parent hb hne hp)] + unfold count + apply prod_congr rfl + intro a _ + rw [read_run] + apply finiteDP_correct + intro b r hr + rw [plan_length] at hr + simp [initial,read_tabulate,hr] + +def branchCount {m : ℕ} (bags : V → Finset (Fin m)) (rank : Fin m → ℕ) + (parent : Fin m → Option (Fin m)) (a b : V) : ℕ := + count (residualBags bags a b) parent (plan rank) + +lemma branchCount_eq {m : ℕ} (bags : V → Finset (Fin m)) (rank : Fin m → ℕ) + (parent : Fin m → Option (Fin m)) (hb : RankedBags bags rank parent) + (hne : ∀ x,(bags x).Nonempty) (hp : ∀ l p,parent l=some p → rank pedgeCount bags rank parent a (finProdFinEquiv.symm i))] + simp only [Equiv.symm_apply_apply] + rw [edgeCount_sum bags rank parent hb hne hp a] + exact div_self (by exact_mod_cast hz.ne') + +def drawEdge (bags : Fin n → Finset (Fin m)) (rank : Fin m → ℕ) + (parent : Fin m → Option (Fin m)) (hb : RankedBags bags rank parent) + (hne : ∀ x,(bags x).Nonempty) (hp : ∀ l p,parent l=some p → rank pbags (e x))) : ColoredPairing bags where + pair := p.pair.map e + color x := p.color (e.symm x) + allowed x := by simpa using p.allowed (e.symm x) + same_color x := by simpa [Pairing.map] using p.same_color (e.symm x) + +def ColoredPairing.comap (bags : V → Finset L) (e : U ≃ V) + (p : ColoredPairing bags) : ColoredPairing (fun x=>bags (e x)) where + pair := p.pair.map e.symm + color x := p.color (e x) + allowed x := p.allowed (e x) + same_color x := by simpa [Pairing.map] using p.same_color (e x) + +def ColoredPairing.equiv (bags : V → Finset L) (e : U ≃ V) : + ColoredPairing (fun x=>bags (e x)) ≃ ColoredPairing bags where + toFun := ColoredPairing.map bags e + invFun := ColoredPairing.comap bags e + left_inv p := by + apply ColoredPairing.ext + · ext x; simp [ColoredPairing.map,ColoredPairing.comap,Pairing.map] + · funext x; simp [ColoredPairing.map,ColoredPairing.comap] + right_inv p := by + apply ColoredPairing.ext + · ext x; simp [ColoredPairing.map,ColoredPairing.comap,Pairing.map] + · funext x; simp [ColoredPairing.map,ColoredPairing.comap] + +def gapEquiv {n : ℕ} (a : Fin (n+1)) : Fin n ≃ {x : Fin (n+1) // x≠a} := + Equiv.optionSubtype a ⟨(finSuccEquiv' a).symm,rfl⟩ + +def removePairEquiv {n : ℕ} (a b : Fin (n+2)) (hb : b≠a) : + Fin n ≃ withoutPair a b := by + let e := gapEquiv a + let b' := e.symm ⟨b,hb⟩ + let f := gapEquiv b' + refine { + toFun := fun i=>⟨(e (f i).val).val,(e (f i).val).property,?_⟩ + invFun := fun x=>f.symm ⟨e.symm ⟨x.val,x.property.1⟩,?_⟩ + left_inv := ?_ + right_inv := ?_ } + · intro h + apply (f i).property + apply e.injective + apply Subtype.ext + simpa [b'] using h + · intro h + have hh := congrArg (fun i=>(e i).val) h + apply x.property.2 + simpa [b'] using hh + · intro i + apply f.injective + simp + · intro x + apply Subtype.ext + simp + +end MatchingFPRAS.UnitRefresh + +namespace MatchingFPRAS.UnitRefresh.Materialized + +open Finset MatchingFPRAS.FiniteChoice + +variable {m : ℕ} + +lemma singleton_count_zero (bags : Fin 1 → Finset (Fin m)) (rank : Fin m → ℕ) + (parent : Fin m → Option (Fin m)) (hb : RankedBags bags rank parent) + (hne : ∀ x,(bags x).Nonempty) (hp : ∀ l p,parent l=some p → rank pp.pair.no_fixed 0 (Subsingleton.elim _ _)⟩ + exact Fintype.card_eq_zero + +def sampleUnit (k : ℕ) : (n : ℕ) → (bags : Fin n → Finset (Fin m)) → + (rank : Fin m → ℕ) → (parent : Fin m → Option (Fin m)) → + (hb : RankedBags bags rank parent) → (hne : ∀ x,(bags x).Nonempty) → + (hp : ∀ l p,parent l=some p → rank p + ⟨⟨fun x=>Fin.elim0 x,fun x=>Fin.elim0 x,fun x=>Fin.elim0 x⟩, + (fun x=>Fin.elim0 x),(fun x=>Fin.elim0 x),(fun x=>Fin.elim0 x)⟩ + | 1,bags,rank,parent,hb,hne,hp,hz,_ => + False.elim (by rw [singleton_count_zero bags rank parent hb hne hp] at hz; omega) + | n+2,bags,rank,parent,hb,hne,hp,hz,bits => by + let a : Fin (n+2) := Fin.last (n+1) + let c := drawEdge bags rank parent hb hne hp a hz k (bits a) + let e := removePairEquiv a c.val.val.1 c.val.property.1 + let b' : Fin n → Finset (Fin m) := fun x=>bags (e x).val + have hb' : RankedBags b' rank parent := by + intro x l hl r hr; exact hb (e x).val l hl r hr + have hne' : ∀ x,(b' x).Nonempty := fun x=>hne (e x).val + have hz' : 0bits i.castSucc.castSucc) + exact (ColoredPairing.map (residualBags bags a c.val.val.1) e p).insert a c.val + + + +open Finset MatchingFPRAS.FiniteChoice MatchingFPRAS.Variation +open scoped Classical + +variable {n m : ℕ} + +abbrev PositivePartner (bags : Fin n → Finset (Fin m)) (rank : Fin m → ℕ) + (parent : Fin m → Option (Fin m)) (a : Fin n) := + {c : Partner bags a // 0(branchCount bags rank parent a c.val.val.1:ℝ)/count bags parent (plan rank)) + ≤ 2*n*m/(2:ℝ)^k := by + let idx := partnerIndex bags rank parent a + let p := edgeProbability bags rank parent a + let hs := edgeProbability_sum bags rank parent hb hne hp a hz + have he (c : PositivePartner bags rank parent a) : + (p (idx c):ℝ)=(branchCount bags rank parent a c.val.val.1:ℝ)/count bags parent (plan rank) := by + have hv : validBranch bags a c.val.val := c.val.property + simp [p,idx,partnerIndex,edgeProbability,edgeCount,hv] + have hg : ∑ c : PositivePartner bags rank parent a,|(tapeLaw p hs k (idx c):ℝ)-(p (idx c):ℝ)| ≤ + ∑ i : Fin (n*m),|(tapeLaw p hs k i:ℝ)-(p i:ℝ)| := by + change (∑ c,|(tapeLaw p hs k (partnerIndex bags rank parent a c):ℝ)-(p (partnerIndex bags rank parent a c):ℝ)|)≤_ + rw [←Finset.sum_image (s:=univ) (f:=fun i=>|(tapeLaw p hs k i:ℝ)-(p i:ℝ)|) + (fun c _ d _ h=>(partnerIndex_injective bags rank parent a) h)] + exact Finset.sum_le_univ_sum_of_nonneg (fun _=>abs_nonneg _) + have ht : (∑ i : Fin (n*m),|(tapeLaw p hs k i:ℝ)-(p i:ℝ)|)/2 ≤ 2*(n*m)/(2:ℝ)^k := by + have hh := drawEdge_tv bags rank parent hb hne hp a hz k + have hcast := (Rat.cast_le (K:=ℝ)).mpr hh + push_cast at hcast + simpa only [p,hs,Nat.cast_mul] using hcast + unfold tv + have hg' : (∑ c : PositivePartner bags rank parent a, + |imageLaw (drawEdge bags rank parent hb hne hp a hz k) c- + (branchCount bags rank parent a c.val.val.1:ℝ)/count bags parent (plan rank)|)≤ + ∑ i : Fin (n*m),|(tapeLaw p hs k i:ℝ)-(p i:ℝ)| := by + simpa only [drawEdge_law,he] using hg + exact (div_le_div_of_nonneg_right hg' (by norm_num)).trans (by simpa only [mul_assoc] using ht) + +noncomputable def positiveSplitEquiv (bags : Fin n → Finset (Fin m)) (rank : Fin m → ℕ) + (parent : Fin m → Option (Fin m)) (hb : RankedBags bags rank parent) + (hne : ∀ x,(bags x).Nonempty) (hp : ∀ l p,parent l=some p → rank p⟨s.1.val,s.2⟩ + invFun := fun s=>⟨⟨s.1,by + rw [branchCount_eq bags rank parent hb hne hp] + exact Fintype.card_pos_iff.mpr ⟨s.2⟩⟩,s.2⟩ + left_inv := fun s=>by rcases s with ⟨⟨c,hc⟩,x⟩; rfl + right_inv := fun s=>by cases s; rfl } + exact e.trans (ColoredPairing.split a).symm + +lemma positiveSplitEquiv_apply (bags : Fin n → Finset (Fin m)) (rank : Fin m → ℕ) + (parent : Fin m → Option (Fin m)) (hb : RankedBags bags rank parent) + (hne : ∀ x,(bags x).Nonempty) (hp : ∀ l p,parent l=some p → rank p(branchCount bags rank parent a c.val.val.1:ℝ)/count bags parent (plan rank)) + (fun c=>uniform (ColoredPairing (residualBags bags a c.val.val.1)))) + (positiveSplitEquiv bags rank parent hb hne hp a) z=uniform (ColoredPairing bags) z := by + let : Nonempty (ColoredPairing bags) := Fintype.card_pos_iff.mp (by + rwa [←computable_count_eq bags rank parent hb hne hp]) + simp_rw [branchCount_eq bags rank parent hb hne hp,computable_count_eq bags rank parent hb hne hp] + exact uniform_sigma (positiveSplitEquiv bags rank parent hb hne hp a) z + +end MatchingFPRAS.UnitRefresh.Materialized + +end OAI diff --git a/lean/OAI/Combinatorics/MatchingCount/Sampling/RankOrder.lean b/lean/OAI/Combinatorics/MatchingCount/Sampling/RankOrder.lean new file mode 100644 index 0000000000000000000000000000000000000000..804974529429c3b17ca57fd420fbd4c1a604ff37 --- /dev/null +++ b/lean/OAI/Combinatorics/MatchingCount/Sampling/RankOrder.lean @@ -0,0 +1,430 @@ +import Mathlib +import OAI.Combinatorics.MatchingCount.Model +import OAI.Combinatorics.MatchingCount.Sampling.AssignmentEquiv + +namespace OAI + +namespace MatchingFPRAS.UnitRefresh + +open Finset + +variable {V L : Type*} [Fintype V] [Fintype L] [DecidableEq V] [DecidableEq L] + +noncomputable def rankOrder (rank : L → ℕ) : List L := + (univ : Finset L).toList.mergeSort (fun a a' => decide (rank a'≤rank a)) + +omit [DecidableEq L] in +lemma rankOrder_mem [DecidableEq L] (rank : L → ℕ) (a : L) : a∈rankOrder rank := by + unfold rankOrder + rw [(List.mergeSort_perm _ _).mem_iff] + simp + +omit [DecidableEq L] in +lemma rankOrder_length [DecidableEq L] (rank : L → ℕ) : (rankOrder rank).length=Fintype.card L := by + unfold rankOrder + rw [(List.mergeSort_perm _ _).length_eq] + simp + +omit [DecidableEq L] in +lemma rankOrder_sorted [DecidableEq L] (rank : L → ℕ) : + (rankOrder rank).Pairwise (fun a a' => rank a'≤rank a) := by + let r := fun a a' : L => rank a'≤rank a + let : Std.Total r := ⟨fun a b => le_total (rank b) (rank a)⟩ + let : IsTrans L r := ⟨fun a b c hab hbc => hbc.trans hab⟩ + exact List.pairwise_mergeSort' r _ + +lemma rankOrder_legal (b : V → Finset L) (rank : L → ℕ) (parent : L → Option L) + (hb : RankedBags b rank parent) (hne : ∀ x,(b x).Nonempty) + (hp : ∀ l p,parent l=some p → rank p b x.val) w=assignmentPartition b w + let e : (univ : Finset V) ≃ V := + { toFun := Subtype.val + invFun := fun x => ⟨x,mem_univ x⟩ + left_inv := fun x => rfl + right_inv := fun x => rfl } + apply assignmentPartition_equiv _ _ e + intro x; rfl + +theorem ranked_tableDP_correct (b : V → Finset L) (rank : L → ℕ) (parent : L → Option L) + (hb : RankedBags b rank parent) (hne : ∀ x,(b x).Nonempty) + (hp : ∀ l p,parent l=some p → rank p b x={l}) ∪ (R.filter fun x => l∈b x ∧ b x≠{l}) = + R.filter (fun x => l∈b x) := by + ext x + simp only [mem_union,mem_filter] + constructor + · rintro (⟨hx,hb⟩|⟨hx,hl,_⟩) + · exact ⟨hx,by simp [hb]⟩ + · exact ⟨hx,hl⟩ + · rintro ⟨hx,hl⟩ + by_cases h : b x={l} + · exact Or.inl ⟨hx,h⟩ + · exact Or.inr ⟨hx,hl,h⟩ + have hd : Disjoint (R.filter fun x => b x={l}) (R.filter fun x => l∈b x ∧ b x≠{l}) := by + apply disjoint_left.mpr + intro x hx hx' + exact (mem_filter.mp hx').2.2 (mem_filter.mp hx).2 + unfold privateCount sharedCount + rw [← card_union_of_disjoint hd,he] + exact (card_filter_le _ _).trans (card_le_univ R) + +lemma advanceTable_congr (b : V → Finset L) (R : Finset V) (parent : L → Option L) + (l : L) (w z : L → ℕ → ℕ) (B : ℕ) + (h : ∀ a r,r≤B+Fintype.card V → w a r=z a r) (a : L) (r : ℕ) (hr : r≤B) : + advanceTable b R parent l w a r=advanceTable b R parent l z a r := by + classical + have hs := shared_le_card b R l + have hu := private_add_shared b R l + unfold advanceTable + cases hpar : parent l with + | some p => + simp only + unfold leafUpdate + split_ifs + · rfl + · apply sum_congr rfl + intro k hk + have hk' : k ≤ sharedCount b R l := by simpa using (mem_range.mp hk) + rw [h l _ (by omega),h _ _ (by omega)] + · exact h a r (by omega) + | none => + simp only + unfold rootUpdate + split_ifs + · apply h + have ht := (card_filter_le (s:=R) (p:=fun x => l∈b x)).trans (card_le_univ R) + omega + · exact h a r (by omega) + +noncomputable def capTable (B : ℕ) (w : L → ℕ → ℕ) : L → ℕ → ℕ := + fun a r => if r≤B then w a r else 0 + +noncomputable def finiteDP (b : V → Finset L) (parent : L → Option L) : + List L → Finset V → (L → ℕ → ℕ) → (L → ℕ → ℕ) + | [],_,w => w + | l::ls,R,w => finiteDP b parent ls (trim b R l) + (capTable (Fintype.card V*ls.length) + (advanceTable b R parent l w)) + +lemma finiteDP_correct (b : V → Finset L) (parent : L → Option L) (ls : List L) + (R : Finset V) (w z : L → ℕ → ℕ) + (h : ∀ a r,r≤Fintype.card V*ls.length → w a r=z a r) (a : L) : + finiteDP b parent ls R w a 0=tableDP b parent ls R z a 0 := by + induction ls generalizing R w z with + | nil => exact h a 0 (by simp) + | cons l ls ih => + apply ih + intro a r hr + rw [capTable,ite_eq_left hr] + apply advanceTable_congr b R parent l w z (Fintype.card V*ls.length) + · intro a r hr + apply h + simpa only [List.length_cons,Nat.mul_add,Nat.mul_one] using hr + · exact hr + +theorem finite_ranked_count (b : V → Finset L) (rank : L → ℕ) (parent : L → Option L) + (hb : RankedBags b rank parent) (hne : ∀ x,(b x).Nonempty) + (hp : ∀ l p,parent l=some p → rank p bags x.val + +abbrev Partner (bags : V → Finset L) (a : V) := + {bc : V × L // bc.1≠a ∧ bc.2∈bags a ∧ bc.2∈bags bc.1} + +omit [Fintype V] [Fintype L] [DecidableEq V] [DecidableEq L] in +lemma ColoredPairing.subtype_hext [Fintype V] [Fintype L] [DecidableEq V] [DecidableEq L] + {bags : V → Finset L} {P Q : V → Prop} + [DecidablePred P] [DecidablePred Q] + (p : ColoredPairing (fun x : {x // P x} => bags x.val)) + (q : ColoredPairing (fun x : {x // Q x} => bags x.val)) + (hPQ : ∀ x,P x ↔ Q x) + (hm : ∀ (x : {x // P x}) (y : {x // Q x}),x.val=y.val → + (p.pair.mate x).val=(q.pair.mate y).val) + (hc : ∀ (x : {x // P x}) (y : {x // Q x}),x.val=y.val → p.color x=q.color y) : + HEq p q := by + have he : P=Q := funext fun x => propext (hPQ x) + subst Q + apply heq_of_eq + apply ColoredPairing.ext + · ext x; exact hm x x rfl + · funext x; exact hc x x rfl + +def ColoredPairing.remove {bags : V → Finset L} (p : ColoredPairing bags) (a : V) : + ColoredPairing (residualBags bags a (p.pair.mate a)) where + pair := p.pair.remove a + color x := p.color x.val + allowed x := p.allowed x.val + same_color x := p.same_color x.val + +def ColoredPairing.insert {bags : V → Finset L} (a : V) (c : Partner bags a) + (p : ColoredPairing (residualBags bags a c.val.1)) : ColoredPairing bags where + pair := p.pair.insert a c.val.1 c.property.1 + color x := if hx : x=a ∨ x=c.val.1 then c.val.2 else p.color ⟨x,by tauto⟩ + allowed x := by + dsimp + split_ifs with hx + · rcases hx with rfl|rfl + · exact c.property.2.1 + · exact c.property.2.2 + · exact p.allowed _ + same_color x := by + by_cases ha : x=a + · subst x + simp [Pairing.insert,c.property.1] + by_cases hb : x=c.val.1 + · subst x + simp [Pairing.insert,c.property.1] + simp only [Pairing.insert,dite_eq_right ha,dite_eq_right hb] + rw [dite_eq_right (by exact not_or.mpr (p.pair.mate ⟨x,ha,hb⟩).property), + dite_eq_right (not_or.mpr ⟨ha,hb⟩)] + exact p.same_color ⟨x,ha,hb⟩ + +omit [Fintype V] [Fintype L] [DecidableEq L] in +@[simp] lemma ColoredPairing.insert_color [Fintype V] [Fintype L] [DecidableEq L] + {bags : V → Finset L} (a : V) (c : Partner bags a) + (p : ColoredPairing (residualBags bags a c.val.1)) : + (p.insert a c).color a=c.val.2 := by simp [ColoredPairing.insert] + +omit [Fintype V] [Fintype L] [DecidableEq L] in +@[simp] lemma ColoredPairing.insert_color_residual [Fintype V] [Fintype L] [DecidableEq L] + {bags : V → Finset L} (a : V) + (c : Partner bags a) (p : ColoredPairing (residualBags bags a c.val.1)) + (x : withoutPair a c.val.1) : + (p.insert a c).color x.val=p.color x := by + simp [ColoredPairing.insert,x.property.1,x.property.2] + +noncomputable def ColoredPairing.split {bags : V → Finset L} (a : V) : + ColoredPairing bags ≃ Σ c : Partner bags a,ColoredPairing (residualBags bags a c.val.1) where + toFun p := ⟨⟨(p.pair.mate a,p.color a),p.pair.no_fixed a,p.allowed a, + by rw [← p.same_color a]; exact p.allowed _⟩,p.remove a⟩ + invFun q := q.2.insert a q.1 + left_inv p := by + apply ColoredPairing.ext + · ext x + by_cases ha : x=a + · subst x; simp [ColoredPairing.insert,Pairing.insert] + by_cases hb : x=p.pair.mate a + · subst x; simp [ColoredPairing.insert,Pairing.insert,p.pair.no_fixed,p.pair.involutive a] + simp [ColoredPairing.insert,Pairing.insert,ColoredPairing.remove,Pairing.remove,ha,hb] + · funext x + by_cases ha : x=a + · subst x; simp [ColoredPairing.insert] + by_cases hb : x=p.pair.mate a + · subst x; simp [ColoredPairing.insert,p.same_color] + simp [ColoredPairing.insert,ColoredPairing.remove,ha,hb] + right_inv q := by + rcases q with ⟨c,p⟩ + apply Sigma.ext + · apply Subtype.ext + exact Prod.ext (Pairing.insert_at a c.val.1 c.property.1 p.pair) (ColoredPairing.insert_color a c p) + · apply ColoredPairing.subtype_hext + · intro x; simp only [ColoredPairing.insert,Pairing.insert_at] + · intro x y hxy + change (p.pair.insert a c.val.1 c.property.1).mate x.val=(p.pair.mate y).val + rw [hxy] + exact Pairing.insert_other _ _ _ _ y + · intro x y hxy + change (p.insert a c).color x.val=p.color y + rw [hxy] + exact ColoredPairing.insert_color_residual _ _ _ y + +lemma partner_card (bags : V → Finset L) (a : V) : + Fintype.card (Partner bags a)≤Fintype.card V*Fintype.card L := by + exact (Fintype.card_subtype_le _).trans_eq (Fintype.card_prod V L) + +noncomputable def residualCount (bags : V → Finset L) (rank : L → ℕ) + (parent : L → Option L) (a b : V) : ℕ := + ∏ l,finiteDP (residualBags bags a b) parent (rankOrder rank) univ + (capTable (Fintype.card (withoutPair a b)*Fintype.card L) (fun _ => pairingCount)) l 0 + +lemma residualCount_eq (bags : V → Finset L) (rank : L → ℕ) (parent : L → Option L) + (hb : RankedBags bags rank parent) (hne : ∀ x,(bags x).Nonempty) + (hp : ∀ l p,parent l=some p → rank p List.ofFn fun r : Fin (B+1) => f a r.val + +lemma read_tabulate {m B : ℕ} (f : Fin m → ℕ → ℕ) (a : Fin m) (r : ℕ) : + read (tabulate m B f) a.val r = if r≤B then f a r else 0 := by + unfold read tabulate List.getD + simp only [List.getElem?_ofFn, a.isLt, dite_eq_left, Option.getD_some] + by_cases hr : r≤B + · have h : r if a=l then read t l.val ((R.filter fun x=>l∈bags x).card) else read t a.val r + | some p => if a=l then 1 else if a=p then + ∑ k∈range (sharedCount bags R l+1), + (sharedCount bags R l).choose k * read t l.val (privateCount bags R l+k) * + read t p.val (sharedCount bags R l-k+r) + else read t a.val r + +omit [Fintype V] [DecidableEq V] in +lemma entry_eq [Fintype V] [DecidableEq V] {m : ℕ} (bags : V → Finset (Fin m)) (R : Finset V) + (parent : Fin m → Option (Fin m)) (l a : Fin m) (t : Table) (r : ℕ) : + entry bags R parent l a t r = + advanceTable bags R parent l (fun a r => read t a.val r) a r := by + unfold entry advanceTable leafUpdate rootUpdate + cases parent l <;> rfl + +def update {m : ℕ} (bags : V → Finset (Fin m)) (R : Finset V) + (parent : Fin m → Option (Fin m)) (l : Fin m) (B : ℕ) (t : Table) : Table := + tabulate m B (fun a r=>entry bags R parent l a t r) + +lemma read_update {m : ℕ} (bags : V → Finset (Fin m)) (R : Finset V) + (parent : Fin m → Option (Fin m)) (l a : Fin m) (B r : ℕ) (t : Table) : + read (update bags R parent l B t) a.val r = + capTable B (advanceTable bags R parent l (fun a r=>read t a.val r)) a r := by + rw [update,read_tabulate] + unfold capTable + split_ifs <;> simp [entry_eq] + +def run {m : ℕ} (bags : V → Finset (Fin m)) (parent : Fin m → Option (Fin m)) : + List (Fin m) → Finset V → Table → Table + | [],_,t => t + | l::ls,R,t => run bags parent ls (trim bags R l) + (update bags R parent l (Fintype.card V*ls.length) t) + +lemma read_run {m : ℕ} (bags : V → Finset (Fin m)) (parent : Fin m → Option (Fin m)) + (ls : List (Fin m)) (R : Finset V) (t : Table) (a : Fin m) (r : ℕ) : + read (run bags parent ls R t) a.val r = + finiteDP bags parent ls R (fun a r=>read t a.val r) a r := by + induction ls generalizing R t with + | nil => rfl + | cons l ls ih => + rw [run,finiteDP,ih] + congr 2 + funext a r + exact read_update bags R parent l a _ r t + +def initial (m B : ℕ) : Table := tabulate m B (fun _=>pairingCount) + +def count {m : ℕ} (bags : V → Finset (Fin m)) (parent : Fin m → Option (Fin m)) + (plan : List (Fin m)) : ℕ := + let t := run bags parent plan univ (initial m (Fintype.card V*m)) + ∏ a : Fin m,read t a.val 0 + +lemma count_eq {m : ℕ} (bags : V → Finset (Fin m)) (rank : Fin m → ℕ) + (parent : Fin m → Option (Fin m)) + (hb : RankedBags bags rank parent) (hne : ∀ x,(bags x).Nonempty) + (hp : ∀ l p,parent l=some p → rank ppairingCount) + rw [finite_ranked_count bags rank parent hb hne hp] + unfold count + apply prod_congr rfl + intro a _ + rw [read_run] + congr 2 + funext b r + simp only [initial,read_tabulate,capTable,Fintype.card_fin] + +def cellsWritten {m : ℕ} (bags : V → Finset (Fin m)) : List (Fin m) → ℕ + | [] => 0 + | _::ls => m*(Fintype.card V*ls.length+1)+cellsWritten bags ls + +omit [DecidableEq V] in +lemma cellsWritten_bound [DecidableEq V] {m : ℕ} (bags : V → Finset (Fin m)) (ls : List (Fin m)) : + cellsWritten bags ls ≤ ls.length*m*(Fintype.card V*ls.length+1) := by + induction ls with + | nil => simp [cellsWritten] + | cons l ls ih => + simp only [cellsWritten,List.length_cons] + calc + _ ≤ m*(Fintype.card V*ls.length+1)+ls.length*m*(Fintype.card V*ls.length+1) := + Nat.add_le_add_left ih _ + _ = (ls.length+1)*m*(Fintype.card V*ls.length+1) := by ring + _ ≤ _ := Nat.mul_le_mul_left _ (Nat.add_le_add_right (Nat.mul_le_mul_left _ (Nat.le_succ _)) _) + +end MatchingFPRAS.UnitRefresh.Materialized + +end OAI diff --git a/lean/OAI/Combinatorics/MatchingCount/Sampling/Relabel.lean b/lean/OAI/Combinatorics/MatchingCount/Sampling/Relabel.lean new file mode 100644 index 0000000000000000000000000000000000000000..2bf56ffcbdb6b7e560ecf8e7e59ce895d923897a --- /dev/null +++ b/lean/OAI/Combinatorics/MatchingCount/Sampling/Relabel.lean @@ -0,0 +1,140 @@ +import Mathlib +import OAI.Combinatorics.MatchingCount.Graphs.LabelOrder + +namespace OAI + +namespace MatchingFPRAS.Transport + +open Finset + +variable {V L J : Type*} [Fintype V] [DecidableEq V] [Fintype L] [DecidableEq L] + [Fintype J] [DecidableEq J] + +variable {b : V → Finset L} {c : V → Finset J} + +def relabelEdge (e : L ≃ J) (h : ∀ v,(b v).image e=c v) (a : BagEdge b) : BagEdge c := + ⟨⟨(a.val.val.1,e a.val.val.2),a.val.property⟩,by + intro v hv + change e a.val.val.2∈c v + rw [←h v] + exact mem_image.mpr ⟨a.val.val.2,a.property v hv,rfl⟩⟩ + +omit [Fintype V] [DecidableEq V] [Fintype L] [Fintype J] in +lemma image_symm_bags (e : L ≃ J) (h : ∀ v,(b v).image e=c v) (v : V) : + (c v).image e.symm=b v := by + rw [←h v,image_image] + simp + +def relabelEdgeEquiv (e : L ≃ J) (h : ∀ v,(b v).image e=c v) : BagEdge b ≃ BagEdge c where + toFun:=relabelEdge e h + invFun:=relabelEdge e.symm (image_symm_bags e h) + left_inv a := by apply Subtype.ext; apply Subtype.ext; simp [relabelEdge] + right_inv a := by apply Subtype.ext; apply Subtype.ext; simp [relabelEdge] + +omit [Fintype V] [DecidableEq V] [Fintype L] [Fintype J] in +lemma relabelEdge_incident (e : L ≃ J) (h : ∀ v,(b v).image e=c v) (a : BagEdge b) (v : V) : + (relabelEdgeEquiv e h a).Incident v ↔ a.Incident v := Iff.rfl + + +variable {E F : Type*} [Fintype E] [DecidableEq E] [Fintype F] [DecidableEq F] + +variable {inc : E → V → Prop} {j : F → V → Prop} + +omit [Fintype V] [DecidableEq V] [Fintype E] [DecidableEq E] [Fintype F] in +lemma MatchingOn.image (e : E ≃ F) (he : ∀ a v,j (e a) v ↔ inc a v) + {M : Finset E} {U : Finset V} (hM : MatchingOn inc M U) : + MatchingOn j (M.image e) U := by + constructor + · intro f hf v hv + obtain ⟨a,ha,rfl⟩:=mem_image.mp hf + exact hM.1 a ha v ((he a v).mp hv) + · intro v hv + obtain ⟨a,⟨ha,hav⟩,hu⟩:=hM.2 v hv + refine ⟨e a,⟨mem_image.mpr ⟨a,ha,rfl⟩,(he a v).mpr hav⟩,?_⟩ + rintro f ⟨hf,hfv⟩ + obtain ⟨d,hd,rfl⟩:=mem_image.mp hf + exact congrArg e (hu d ⟨hd,(he d v).mp hfv⟩) + +def pmEquiv (e : E ≃ F) (he : ∀ a v,j (e a) v ↔ inc a v) : PM inc ≃ PM j where + toFun M:=⟨M.val.image e,M.property.image e he⟩ + invFun M:=⟨M.val.image e.symm,M.property.image e.symm (by intro a v; simpa using (he (e.symm a) v).symm)⟩ + left_inv M:=by apply Subtype.ext; simp [image_image] + right_inv M:=by apply Subtype.ext; simp [image_image] + +omit [DecidableEq V] [Fintype E] [Fintype F] in +lemma matchingWeight_pmEquiv [DecidableEq V] [Fintype E] [Fintype F] + (e : E ≃ F) (he : ∀ a v,j (e a) v ↔ inc a v) + (w : F → ℝ) (M : PM inc) : matchingWeight w (pmEquiv e he M)=matchingWeight (w ∘ e) M := by + unfold matchingWeight pmEquiv + exact Finset.prod_image (fun _ _ _ _ h=>e.injective h) + +lemma partition_pmEquiv (e : E ≃ F) (he : ∀ a v,j (e a) v ↔ inc a v) + (w : F → ℝ) : partition (inc:=j) w=partition (inc:=inc) (w ∘ e) := by + classical + unfold partition + symm + exact Finset.sum_equiv (pmEquiv e he) (by simp) (fun M _=>(matchingWeight_pmEquiv e he w M).symm) + +lemma gibbs_pmEquiv (e : E ≃ F) (he : ∀ a v,j (e a) v ↔ inc a v) + (w : F → ℝ) (M : PM inc) : gibbs w (pmEquiv e he M)=gibbs (w ∘ e) M := by + unfold gibbs + rw [matchingWeight_pmEquiv,partition_pmEquiv e he w] + + +end MatchingFPRAS.Transport + +namespace MatchingFPRAS.RationalSource + +open MatchingFPRAS Switching Subdivision RealGeometry Hierarchy Enlargement Transport Finset + +variable {V : Type*} [Fintype V] [LinearOrder V] [Nontrivial V] + +attribute [local instance] NumberedHierarchy.labelOrder sym2Order bagEdgeOrder bagEdgeFintype + +attribute [local instance] UnitRefresh.Computable.allowedDec prodOrder sumOrder + +noncomputable local instance {X : Type*} [Fintype X] (B : X → X → ℝ) + (s : ∀ x y,B x y=B y x) + (t : ∀ x y z,x≠y → x≠z → y≠z → min (B x z) (B z y)≤B x y) (H : ℕ) : + DecidableEq (Hierarchy.Label B s t H) := Classical.decEq _ + +noncomputable def labelCast {X : Type*} [Fintype X] {B B' : X → X → ℝ} + (s : ∀ x y,B x y=B y x) + (t : ∀ x y z,x≠y → x≠z → y≠z → min (B x z) (B z y)≤B x y) + (s' : ∀ x y,B' x y=B' y x) + (t' : ∀ x y z,x≠y → x≠z → y≠z → min (B' x z) (B' z y)≤B' x y) + {H H' : ℕ} (hB : B=B') (hH : H=H') : + Hierarchy.Label B s t H ≃ Hierarchy.Label B' s' t' H' := + Equiv.cast (by cases hB;cases hH;rfl) + +lemma labelCast_bags {X E : Type*} [Fintype X] [DecidableEq X] [Fintype E] + {B B' : X → X → ℝ} + (s : ∀ x y,B x y=B y x) + (t : ∀ x y z,x≠y → x≠z → y≠z → min (B x z) (B z y)≤B x y) + (s' : ∀ x y,B' x y=B' y x) + (t' : ∀ x y z,x≠y → x≠z → y≠z → min (B' x z) (B' z y)≤B' x y) + (u v : E → X) {H H' : ℕ} (hB : B=B') (hH : H=H') (x : X) : + (memberships B s t u v H x).image (labelCast s t s' t' hB hH)= + memberships B' s' t' u v H' x := by + classical + cases hB;cases hH + simp [labelCast] + +noncomputable def labelsEquiv (w : V → V → ℚ) (K : ℕ) : + SourceLabel (fun x y=>(w x y:ℝ)) K ≃ Label w K := + (labelCast (sourceRealB_comm _ _) (sourceRealB_tri _ _) + (NumberedHierarchy.symmetric (realB w K) (realB_symm w K)) + (NumberedHierarchy.triangular (realB w K) (realB_tri w K)) + (by funext x y;exact (realB_cast w K x y).symm) (levels_eq w K).symm).trans + (NumberedHierarchy.labelEquiv (realB w K) (realB_symm w K) (realB_tri w K) (levels w K)) + +lemma source_bags_equiv (w : V → V → ℚ) (K : ℕ) (x : SourceVertex V K) : + (sourceBags (fun a b=>(w a b:ℝ)) K x).image (labelsEquiv w K)=bags w K x := by + change image ((NumberedHierarchy.labelEquiv _ _ _ _) ∘ _ ) _=_ + rw [←image_image,sourceBags,labelCast_bags] + exact NumberedHierarchy.bags_equiv (realB w K) (realB_symm w K) (realB_tri w K) + (realLeft K) (realRight K) (levels w K) x + +end MatchingFPRAS.RationalSource + +end OAI diff --git a/lean/OAI/Combinatorics/MatchingCount/Sampling/RelabelMarking.lean b/lean/OAI/Combinatorics/MatchingCount/Sampling/RelabelMarking.lean new file mode 100644 index 0000000000000000000000000000000000000000..946a204d11dc35a7aa00dc423a1e3066b17f9c93 --- /dev/null +++ b/lean/OAI/Combinatorics/MatchingCount/Sampling/RelabelMarking.lean @@ -0,0 +1,59 @@ +import Mathlib +import OAI.Combinatorics.MatchingCount.Sampling.Relabel + +namespace OAI + +namespace MatchingFPRAS.Transport +open Finset + +variable {V E F I : Type*} [Fintype V] [DecidableEq V] +variable [Fintype E] [DecidableEq E] [Fintype F] [DecidableEq F] [Fintype I] +variable {inc : E → V → Prop} {j : F → V → Prop} +def selectedEquiv (e : E ≃ F) (he : ∀ a v,j (e a) v ↔ inc a v) (M : PM inc) : + ↥M.val ≃ ↥(pmEquiv e he M).val where + toFun a:=⟨e a.val,mem_image.mpr ⟨a.val,a.property,rfl⟩⟩ + invFun a:=⟨e.symm a.val,by + obtain ⟨b,hb,heq⟩:=mem_image.mp a.property + simpa [←heq] using hb⟩ + left_inv a:=by apply Subtype.ext; exact e.symm_apply_apply _ + right_inv a:=by apply Subtype.ext; exact e.apply_symm_apply _ +def markedEquiv (e : E ≃ F) (he : ∀ a v,j (e a) v ↔ inc a v) : + Marking.Marked (I:=I) inc ≃ Marking.Marked (I:=I) j := + Equiv.sigmaCongr (pmEquiv e he) (fun M=>Equiv.arrowCongr (selectedEquiv e he M) (Equiv.refl I)) +omit [DecidableEq V] [Fintype E] [Fintype F] [Fintype I] in +lemma markedEquiv_fst (e : E ≃ F) (he : ∀ a v,j (e a) v ↔ inc a v) + (a : Marking.Marked (I:=I) inc) : (markedEquiv e he a).1=pmEquiv e he a.1 := rfl +omit [DecidableEq V] [Fintype E] [Fintype F] [Fintype I] in +lemma markedEquiv_mark (e : E ≃ F) (he : ∀ a v,j (e a) v ↔ inc a v) + (a : Marking.Marked (I:=I) inc) (x : a.1.val) : + (markedEquiv e he a).2 (selectedEquiv e he a.1 x)=a.2 x := by + change a.2 ((selectedEquiv e he a.1).symm (selectedEquiv e he a.1 x))=a.2 x + rw [Equiv.symm_apply_apply] +omit [DecidableEq V] [Fintype E] [Fintype F] [Fintype I] in +lemma mass_markedEquiv (e : E ≃ F) (he : ∀ a v,j (e a) v ↔ inc a v) + (part : F → I → ℝ) (a : Marking.Marked (I:=I) inc) : + Marking.mass j part (markedEquiv e he a)=Marking.mass inc (part ∘ e) a := by + apply Fintype.prod_equiv (selectedEquiv e he a.1).symm + intro x + change part x.val ((markedEquiv e he a).2 x)=part (e ((selectedEquiv e he a.1).symm x).val) (a.2 ((selectedEquiv e he a.1).symm x)) + rw [←markedEquiv_mark e he a] + simp only [Equiv.apply_symm_apply] + congr 1 + exact (e.apply_symm_apply x.val).symm +lemma partitionWeight_pmEquiv (e : E ≃ F) (he : ∀ a v,j (e a) v ↔ inc a v) + (w : F → ℝ) : partitionWeight j w univ=partitionWeight inc (w ∘ e) univ := by + classical + unfold partitionWeight + symm + apply Fintype.sum_equiv (pmEquiv e he) + intro M + exact (matchingWeight_pmEquiv e he w M).symm +lemma law_markedEquiv (e : E ≃ F) (he : ∀ a v,j (e a) v ↔ inc a v) + (part : F → I → ℝ) (a : Marking.Marked (I:=I) inc) : + Marking.law j part (markedEquiv e he a)=Marking.law inc (part ∘ e) a := by + unfold Marking.law + rw [mass_markedEquiv,partitionWeight_pmEquiv e he] + rfl +end MatchingFPRAS.Transport + +end OAI diff --git a/lean/OAI/Combinatorics/MatchingCount/Sampling/RelationDestinations.lean b/lean/OAI/Combinatorics/MatchingCount/Sampling/RelationDestinations.lean new file mode 100644 index 0000000000000000000000000000000000000000..7ce41f9ffb78c20d4126237b9e11148312494bf2 --- /dev/null +++ b/lean/OAI/Combinatorics/MatchingCount/Sampling/RelationDestinations.lean @@ -0,0 +1,451 @@ +import Mathlib +import OAI.Combinatorics.MatchingCount.Sampling.TierClamp + +namespace OAI + +namespace MatchingFPRAS.Transport + +section + +open Finset + +variable {Ω : Type*} [Fintype Ω] [DecidableEq Ω] + +noncomputable def relationDestinations (R : Ω → Ω → Prop) (a : Ω) : Finset Ω := by + classical + exact Finset.univ.filter (fun b => a ≠ b ∧ R a b) + +noncomputable def relationOff (R : Ω → Ω → Prop) (d : ℕ) (a b : Ω) : ℝ := by + classical + exact if b ∈ relationDestinations R a then (d:ℝ)⁻¹ else 0 + +noncomputable def relationProposal (R : Ω → Ω → Prop) (d : ℕ) (a b : Ω) : ℝ := by + classical + exact if a = b then 1-∑ z, relationOff R d a z else relationOff R d a b + +lemma relationOff_self (R : Ω → Ω → Prop) (d : ℕ) (a : Ω) : relationOff R d a a = 0 := by + classical + simp [relationOff,relationDestinations] + +lemma relationOff_nonneg (R : Ω → Ω → Prop) (d : ℕ) (a b : Ω) : 0 ≤ relationOff R d a b := by + classical + unfold relationOff; split_ifs <;> positivity + +lemma relationOff_sum (R : Ω → Ω → Prop) (d : ℕ) (a : Ω) : + (∑ b, relationOff R d a b) = (relationDestinations R a).card / (d:ℝ) := by + classical + unfold relationOff + rw [← Finset.sum_filter] + simp [div_eq_mul_inv] + +lemma relationOff_sum_le_one (R : Ω → Ω → Prop) (d : ℕ) (a : Ω) + (hd : (relationDestinations R a).card ≤ d) : (∑ b, relationOff R d a b) ≤ 1 := by + rw [relationOff_sum] + by_cases h : d = 0 + · simp [h] + · apply (div_le_one (by positivity)).mpr + exact_mod_cast hd + +lemma relationProposal_nonneg (R : Ω → Ω → Prop) (d : ℕ) + (hd : ∀ a, (relationDestinations R a).card ≤ d) (a b : Ω) : 0 ≤ relationProposal R d a b := by + classical + unfold relationProposal; split_ifs + · exact sub_nonneg.mpr (relationOff_sum_le_one R d a (hd a)) + · exact relationOff_nonneg _ _ _ _ + +lemma relationProposal_row (R : Ω → Ω → Prop) (d : ℕ) (a : Ω) : + (∑ b, relationProposal R d a b) = 1 := by + classical + rw [← Finset.sum_erase_add _ _ (Finset.mem_univ a)] + have hh : (∑ b ∈ Finset.univ.erase a, relationProposal R d a b) = + ∑ b, relationOff R d a b := by + rw [← Finset.sum_erase_add _ _ (Finset.mem_univ a),relationOff_self,add_zero] + apply Finset.sum_congr rfl; intro b hb + simp only [relationProposal,ite_eq_right (Finset.ne_of_mem_erase hb).symm] + rw [hh] + simp only [relationProposal,ite_true] + ring + +lemma relationProposal_symmetric (R : Ω → Ω → Prop) (d : ℕ) + (hR : ∀ a b, R a b ↔ R b a) (a b : Ω) : relationProposal R d a b = relationProposal R d b a := by + classical + by_cases h : a = b + · subst b; rfl + · simp [relationProposal,h,Ne.symm h,relationOff,relationDestinations,hR a b] + +end + +section + +open Finset + +variable {V E : Type*} [Fintype V] [DecidableEq V] [Fintype E] [DecidableEq E] + +variable (ends : E → Sym2 V) + +attribute [local instance] Classical.propDecidable + +noncomputable def colorProposal (A B : PM (fun e v => v ∈ ends e)) : ℝ := + relationProposal (ColorChange ends) (Fintype.card V) A B + +omit [DecidableEq V] in +lemma colorProposal_row (A : PM (fun e v => v ∈ ends e)) : (∑ B, colorProposal ends A B) = 1 := + relationProposal_row _ _ _ + +omit [DecidableEq V] in +lemma colorProposal_symmetric (A B : PM (fun e v => v ∈ ends e)) : + colorProposal ends A B = colorProposal ends B A := + relationProposal_symmetric _ _ (fun _ _ => ⟨ColorChange.symm ends,ColorChange.symm ends⟩) A B + +lemma colorProposal_nonneg (hloop : ∀ e, ¬(ends e).IsDiag) + (hpar : ∀ e, (Finset.univ.filter (fun f => ends f = ends e)).card ≤ 2) + (A B : PM (fun e v => v ∈ ends e)) : 0 ≤ colorProposal ends A B := by + classical + apply relationProposal_nonneg + intro C + calc + _ ≤ (colorDestinations ends C).card := Finset.card_le_card (by + intro D hD; exact Finset.mem_filter.mpr ⟨Finset.mem_univ _,((Finset.mem_filter.mp hD).2).2⟩) + _ ≤ 2*C.val.card := colorDestinations_card_bound ends hpar C + _ = _ := C.twice_card ends hloop + +lemma colorProposal_off (hloop : ∀ e, ¬(ends e).IsDiag) + (A B : PM (fun e v => v ∈ ends e)) (h : A ≠ B) : + colorProposal ends A B = if ColorChange ends A B then (2*(A.val.card:ℝ))⁻¹ else 0 := by + classical + have hn : (Fintype.card V:ℝ) = 2*(A.val.card:ℝ) := by exact_mod_cast (A.twice_card ends hloop).symm + simp [colorProposal,relationProposal,relationOff,relationDestinations,h,hn] + +theorem colorProposal_dirichlet (hloop : ∀ e, ¬(ends e).IsDiag) + (w : E → ℝ) (f : Finset E → ℝ) : + (∑ A : PM (fun e v => v ∈ ends e), ∑ B : PM (fun e v => v ∈ ends e), + min (gibbs w A) (gibbs w B)*colorProposal ends A B*(f A.val-f B.val)^2) / 6 = + colorDirichlet ends w f := by + classical + unfold colorDirichlet + rw [Finset.sum_div] + apply Finset.sum_congr rfl; intro A _ + rw [Finset.sum_div] + unfold colorDestinations + rw [Finset.sum_filter] + apply Finset.sum_congr rfl; intro B _ + by_cases h : A = B + · subst B; simp + · rw [colorProposal_off ends hloop A B h] + by_cases hc : ColorChange ends A B + · rw [ite_eq_left hc,ite_eq_left hc] + simp only [div_eq_mul_inv,mul_inv_rev] + ring + · simp [hc] + +end + +section + +open Finset + +variable {V E : Type*} [Fintype V] [DecidableEq V] [Fintype E] [DecidableEq E] + +variable {inc : E → V → Prop} + +omit [DecidableEq V] [Fintype E] in +lemma TwoEdgeSwitch.symm {A B : PM inc} (h : TwoEdgeSwitch A B) : TwoEdgeSwitch B A := by + obtain ⟨v,e,R,hv,he,hA,hB⟩ := h + refine ⟨(fun i => v (i+1)),(fun i => e (i+1)),R,?_,?_,?_,?_⟩ + · exact hv.comp (fun _ _ h => add_right_cancel h) + · intro i x + simpa only [add_assoc] using he (i+1) x + · simpa using hB + · simpa [Finset.pair_comm] using hA + +omit [DecidableEq V] [Fintype E] in +lemma TwoEdgeSwitch.normal_form {A B : PM inc} (h : TwoEdgeSwitch A B) : + ∃ (v : Fin 4 → V) (e : Fin 4 → E), Function.Injective v ∧ + (∀ i x, inc (e i) x ↔ x = v i ∨ x = v (i+1)) ∧ + e 0 ≠ e 2 ∧ {e 0,e 2} ⊆ A.val ∧ + B.val = (A.val \ {e 0,e 2}) ∪ {e 1,e 3} := by + classical + obtain ⟨v,e,R,hv,he,hA,hB⟩ := h + have hne (i j : Fin 4) (hij : i ≠ j) (hij' : i ≠ j+1) : e i ≠ e j := by + intro h + have hi := (he i (v i)).mpr (Or.inl rfl) + rw [h] at hi + rcases (he j (v i)).mp hi with h | h + · exact hij (hv h) + · exact hij' (hv h) + have h01 : e 0 ≠ e 1 := hne 0 1 (by decide) (by decide) + have h23 : e 2 ≠ e 3 := hne 2 3 (by decide) (by decide) + have h02 : e 0 ≠ e 2 := hne 0 2 (by decide) (by decide) + have hRB : R ⊆ B.val := by rw [hB]; exact Finset.subset_union_left + have hb1 : e 1 ∈ B.val := by rw [hB]; simp + have hb3 : e 3 ∈ B.val := by rw [hB]; simp + have hr0 : e 0 ∉ R := by + intro hr + exact h01 (B.property.unique (Finset.mem_univ (v 1)) (hRB hr) + ((he 0 (v 1)).mpr (Or.inr rfl)) hb1 ((he 1 (v 1)).mpr (Or.inl rfl))) + have hr2 : e 2 ∉ R := by + intro hr + exact h23 (B.property.unique (Finset.mem_univ (v 3)) (hRB hr) + ((he 2 (v 3)).mpr (Or.inr rfl)) hb3 ((he 3 (v 3)).mpr (Or.inl rfl))) + have hR : A.val \ {e 0,e 2} = R := by + rw [hA] + ext a + simp only [Finset.mem_sdiff,Finset.mem_union,Finset.mem_insert,Finset.mem_singleton] + constructor + · tauto + · intro ha + exact ⟨Or.inl ha,by rintro (rfl|rfl) <;> contradiction⟩ + exact ⟨v,e,hv,he,h02,by rw [hA]; exact Finset.subset_union_right,by rw [hR]; exact hB⟩ + +variable (ends : E → Sym2 V) + +noncomputable def edgeEndpoints (e : E) : V × V := + Classical.choose (show ∃ p : V × V, ends e = s(p.1,p.2) from + Sym2.inductionOn (ends e) (fun a b => ⟨(a,b),rfl⟩)) + +omit [Fintype V] [DecidableEq V] [Fintype E] [DecidableEq E] in +lemma edgeEndpoints_spec (e : E) : ends e = s((edgeEndpoints ends e).1,(edgeEndpoints ends e).2) := + Classical.choose_spec (show ∃ p : V × V, ends e = s(p.1,p.2) from + Sym2.inductionOn (ends e) (fun a b => ⟨(a,b),rfl⟩)) + +noncomputable def pairRep (I : Finset E) (h : I.card = 2) : E × E := + Classical.choose (show ∃ p : E × E, p.1 ≠ p.2 ∧ I = {p.1,p.2} from by + obtain ⟨a,b,hab,he⟩ := Finset.card_eq_two.mp h + exact ⟨(a,b),hab,he⟩) + +omit [Fintype E] in +lemma pairRep_spec (I : Finset E) (h : I.card = 2) : + (pairRep I h).1 ≠ (pairRep I h).2 ∧ I = {(pairRep I h).1,(pairRep I h).2} := + Classical.choose_spec (show ∃ p : E × E, p.1 ≠ p.2 ∧ I = {p.1,p.2} from by + obtain ⟨a,b,hab,he⟩ := Finset.card_eq_two.mp h + exact ⟨(a,b),hab,he⟩) + +noncomputable def withEnds (a b : V) : Finset E := by + classical + exact Finset.univ.filter (fun e => ends e = s(a,b)) + +omit [Fintype V] [DecidableEq E] in +lemma mem_withEnds (a b : V) (e : E) : e ∈ withEnds ends a b ↔ ends e = s(a,b) := by + classical + simp [withEnds] + +omit [Fintype V] [DecidableEq E] in +lemma withEnds_card_le (hpar : ∀ e, (Finset.univ.filter (fun f => ends f = ends e)).card ≤ 2) + (a b : V) : (withEnds ends a b).card ≤ 2 := by + classical + by_cases h : (withEnds ends a b).Nonempty + · obtain ⟨e,he⟩ := h + have hh : withEnds ends a b = Finset.univ.filter (fun f => ends f = ends e) := by + unfold withEnds + rw [(mem_withEnds ends a b e).mp he] + rw [hh]; exact hpar e + · simp [Finset.not_nonempty_iff_eq_empty.mp h] + +noncomputable def edgePairOptions (R : Finset E) (a b c d : V) : Finset (Finset E) := by + classical + exact (withEnds ends a b).biUnion fun e => + (withEnds ends c d).image fun f => R ∪ {e,f} + +omit [Fintype V] in +lemma mem_edgePairOptions (R : Finset E) (a b c d : V) (e f : E) + (he : ends e = s(a,b)) (hf : ends f = s(c,d)) : + R ∪ {e,f} ∈ edgePairOptions ends R a b c d := by + classical + exact Finset.mem_biUnion.mpr ⟨e,(mem_withEnds ends a b e).mpr he, + Finset.mem_image.mpr ⟨f,(mem_withEnds ends c d f).mpr hf,rfl⟩⟩ + +omit [Fintype V] in +lemma edgePairOptions_card_le + (hpar : ∀ e, (Finset.univ.filter (fun f => ends f = ends e)).card ≤ 2) + (R : Finset E) (a b c d : V) : (edgePairOptions ends R a b c d).card ≤ 4 := by + classical + calc + _ ≤ ∑ e ∈ withEnds ends a b, ((withEnds ends c d).image (fun f => R ∪ {e,f})).card := Finset.card_biUnion_le + _ ≤ ∑ e ∈ withEnds ends a b, 2 := Finset.sum_le_sum (fun _ _ => + Finset.card_image_le.trans (withEnds_card_le ends hpar c d)) + _ ≤ 4 := by simp only [Finset.sum_const,smul_eq_mul]; have := withEnds_card_le ends hpar a b; omega + +noncomputable def switchOptions (A : Finset E) (I : Finset E) : Finset (Finset E) := by + classical + exact if h : I.card = 2 then + let p := pairRep I h + let u := edgeEndpoints ends p.1 + let v := edgeEndpoints ends p.2 + edgePairOptions ends (A\I) u.1 v.1 u.2 v.2 ∪ + edgePairOptions ends (A\I) u.1 v.2 u.2 v.1 + else ∅ + +omit [Fintype V] in +lemma switchOptions_card_le + (hpar : ∀ e, (Finset.univ.filter (fun f => ends f = ends e)).card ≤ 2) + (A I : Finset E) : (switchOptions ends A I).card ≤ 8 := by + classical + unfold switchOptions + split_ifs with h + · exact (Finset.card_union_le _ _).trans (Nat.add_le_add + (edgePairOptions_card_le ends hpar _ _ _ _ _) (edgePairOptions_card_le ends hpar _ _ _ _ _)) + · simp + +end + +section + +open Finset + +variable {V E : Type*} [Fintype V] [DecidableEq V] [Fintype E] [DecidableEq E] + +variable (ends : E → Sym2 V) + +omit [Fintype V] in +lemma mem_pairOptions_of_endpoints (R : Finset E) (p q f g : E) (a b c d : V) + (hp : ends p = s(a,b)) (hq : ends q = s(c,d)) + (hf : ends f = s(b,c)) (hg : ends g = s(d,a)) : + R ∪ {f,g} ∈ + edgePairOptions ends R (edgeEndpoints ends p).1 (edgeEndpoints ends q).1 + (edgeEndpoints ends p).2 (edgeEndpoints ends q).2 ∪ + edgePairOptions ends R (edgeEndpoints ends p).1 (edgeEndpoints ends q).2 + (edgeEndpoints ends p).2 (edgeEndpoints ends q).1 := by + classical + have hu := Sym2.eq_iff.mp ((edgeEndpoints_spec ends p).symm.trans hp) + have hv := Sym2.eq_iff.mp ((edgeEndpoints_spec ends q).symm.trans hq) + rcases hu with ⟨h1,h2⟩ | ⟨h1,h2⟩ <;> rcases hv with ⟨h3,h4⟩ | ⟨h3,h4⟩ + · rw [h1,h2,h3,h4] + apply Finset.mem_union_right + rw [Finset.pair_comm f g] + exact mem_edgePairOptions ends R a d b c g f (hg.trans (Sym2.eq_swap)) hf + · rw [h1,h2,h3,h4] + apply Finset.mem_union_left + rw [Finset.pair_comm f g] + exact mem_edgePairOptions ends R a d b c g f (hg.trans (Sym2.eq_swap)) hf + · rw [h1,h2,h3,h4] + apply Finset.mem_union_left + exact mem_edgePairOptions ends R b c a d f g hf (hg.trans (Sym2.eq_swap)) + · rw [h1,h2,h3,h4] + apply Finset.mem_union_right + exact mem_edgePairOptions ends R b c a d f g hf (hg.trans (Sym2.eq_swap)) + +omit [Fintype V] [DecidableEq V] [Fintype E] [DecidableEq E] in +lemma inc_eq_ends (e : E) (a b : V) (hab : a ≠ b) + (h : ∀ x, x ∈ ends e ↔ x = a ∨ x = b) : ends e = s(a,b) := by + exact (Sym2.mem_and_mem_iff hab).mp ⟨(h a).mpr (Or.inl rfl),(h b).mpr (Or.inr rfl)⟩ + +lemma switch_mem_options {A B : PM (fun e v => v ∈ ends e)} (h : TwoEdgeSwitch A B) : + ∃ I ∈ A.val.powersetCard 2, B.val ∈ switchOptions ends A.val I := by + classical + obtain ⟨v,e,hv,he,h02,hsub,hB⟩ := h.normal_form + let I : Finset E := {e 0,e 2} + have hI : I.card = 2 := by simp [I,h02] + refine ⟨I,Finset.mem_powersetCard.mpr ⟨hsub,hI⟩,?_⟩ + have hend (i : Fin 4) : ends (e i) = s(v i,v (i+1)) := + inc_eq_ends ends (e i) (v i) (v (i+1)) + (fun h => (by omega : i ≠ i+1) (hv h)) (he i) + unfold switchOptions + rw [dite_eq_left hI] + dsimp only + obtain ⟨hne,hr⟩ := pairRep_spec I hI + have h1 : (pairRep I hI).1 = e 0 ∨ (pairRep I hI).1 = e 2 := by + have : (pairRep I hI).1 ∈ I := by + exact (congrArg (fun S : Finset E => (pairRep I hI).1 ∈ S) hr).mpr (by simp) + simpa [I] using this + have h2 : (pairRep I hI).2 = e 0 ∨ (pairRep I hI).2 = e 2 := by + have : (pairRep I hI).2 ∈ I := by + exact (congrArg (fun S : Finset E => (pairRep I hI).2 ∈ S) hr).mpr (by simp) + simpa [I] using this + rw [hB] + rcases h1 with h1 | h1 <;> rcases h2 with h2 | h2 + · exact False.elim (hne (h1.trans h2.symm)) + · rw [h1,h2] + exact mem_pairOptions_of_endpoints ends (A.val\I) (e 0) (e 2) (e 1) (e 3) + (v 0) (v 1) (v 2) (v 3) (hend 0) (hend 2) (hend 1) (hend 3) + · rw [h1,h2,Finset.pair_comm (e 1) (e 3)] + exact mem_pairOptions_of_endpoints ends (A.val\I) (e 2) (e 0) (e 3) (e 1) + (v 2) (v 3) (v 0) (v 1) (hend 2) (hend 0) (hend 3) (hend 1) + · exact False.elim (hne (h1.trans h2.symm)) + +lemma switchDestinations_card_bound + (hpar : ∀ e, (Finset.univ.filter (fun f => ends f = ends e)).card ≤ 2) + (A : PM (fun e v => v ∈ ends e)) : + (switchDestinations A).card ≤ 8 * A.val.card.choose 2 := by + classical + have hsub : (switchDestinations A).image Subtype.val ⊆ + (A.val.powersetCard 2).biUnion (switchOptions ends A.val) := by + intro B hB + obtain ⟨C,hC,hCB⟩ := Finset.mem_image.mp hB + rw [← hCB] + obtain ⟨I,hI,hB⟩ := switch_mem_options ends ((Finset.mem_filter.mp hC).2) + exact Finset.mem_biUnion.mpr ⟨I,hI,hB⟩ + calc + _ = ((switchDestinations A).image Subtype.val).card := + (Finset.card_image_of_injective _ Subtype.val_injective).symm + _ ≤ ((A.val.powersetCard 2).biUnion (switchOptions ends A.val)).card := Finset.card_le_card hsub + _ ≤ ∑ I ∈ A.val.powersetCard 2, (switchOptions ends A.val I).card := Finset.card_biUnion_le + _ ≤ ∑ I ∈ A.val.powersetCard 2, 8 := + Finset.sum_le_sum fun I _ => switchOptions_card_le ends hpar A.val I + _ = _ := by simp [Nat.mul_comm] + +end + +open Finset + +variable {V E : Type*} [Fintype V] [DecidableEq V] [Fintype E] [DecidableEq E] + +variable (ends : E → Sym2 V) + +attribute [local instance] Classical.propDecidable + +noncomputable def switchProposal (A B : PM (fun e v => v ∈ ends e)) : ℝ := + relationProposal TwoEdgeSwitch (8*(Fintype.card V/2).choose 2) A B + +omit [DecidableEq V] in +lemma switchProposal_row (A : PM (fun e v => v ∈ ends e)) : (∑ B, switchProposal ends A B) = 1 := + relationProposal_row _ _ _ + +omit [DecidableEq V] in +lemma switchProposal_symmetric (A B : PM (fun e v => v ∈ ends e)) : + switchProposal ends A B = switchProposal ends B A := + relationProposal_symmetric _ _ (fun _ _ => ⟨TwoEdgeSwitch.symm,TwoEdgeSwitch.symm⟩) A B + +lemma switchProposal_nonneg (hloop : ∀ e, ¬(ends e).IsDiag) + (hpar : ∀ e, (Finset.univ.filter (fun f => ends f = ends e)).card ≤ 2) + (A B : PM (fun e v => v ∈ ends e)) : 0 ≤ switchProposal ends A B := by + classical + apply relationProposal_nonneg + intro C + have hn : Fintype.card V/2 = C.val.card := by have := C.twice_card ends hloop; omega + calc + _ ≤ (switchDestinations C).card := Finset.card_le_card (by + intro D hD; exact Finset.mem_filter.mpr ⟨Finset.mem_univ _,((Finset.mem_filter.mp hD).2).2⟩) + _ ≤ 8*C.val.card.choose 2 := switchDestinations_card_bound ends hpar C + _ = _ := by rw [hn] + +lemma switchProposal_off (hloop : ∀ e, ¬(ends e).IsDiag) + (A B : PM (fun e v => v ∈ ends e)) (h : A ≠ B) : + switchProposal ends A B = if TwoEdgeSwitch A B then (8*(A.val.card.choose 2:ℝ))⁻¹ else 0 := by + have hn : Fintype.card V/2 = A.val.card := by have := A.twice_card ends hloop; omega + simp [switchProposal,relationProposal,relationOff,relationDestinations,h,hn] + +theorem switchProposal_dirichlet (hloop : ∀ e, ¬(ends e).IsDiag) + (w : E → ℝ) (f : Finset E → ℝ) : + (∑ A : PM (fun e v => v ∈ ends e), ∑ B : PM (fun e v => v ∈ ends e), + min (gibbs w A) (gibbs w B)*switchProposal ends A B*(f A.val-f B.val)^2) / 6 = + switchDirichlet (inc := fun e v => v ∈ ends e) w f := by + classical + unfold switchDirichlet + rw [Finset.sum_div] + apply Finset.sum_congr rfl; intro A _ + rw [Finset.sum_div] + unfold switchDestinations + rw [Finset.sum_filter] + apply Finset.sum_congr rfl; intro B _ + by_cases h : A = B + · subst B; simp + · rw [switchProposal_off ends hloop A B h] + by_cases hc : TwoEdgeSwitch A B + · rw [ite_eq_left hc,ite_eq_left hc] + simp only [div_eq_mul_inv,mul_inv_rev] + ring + · simp [hc] + +end MatchingFPRAS.Transport + +end OAI diff --git a/lean/OAI/Combinatorics/MatchingCount/Sampling/Sewn.lean b/lean/OAI/Combinatorics/MatchingCount/Sampling/Sewn.lean new file mode 100644 index 0000000000000000000000000000000000000000..ec481c3a8ad320db4cbc5c02a8d8490ccf24dff8 --- /dev/null +++ b/lean/OAI/Combinatorics/MatchingCount/Sampling/Sewn.lean @@ -0,0 +1,377 @@ +import Mathlib +import OAI.Combinatorics.MatchingCount.Sampling.Components + +namespace OAI + +namespace MatchingFPRAS.Transport + +section +variable {V E : Type*} [DecidableEq V] [DecidableEq E] +variable {inc : E → V → Prop} +namespace IndexedCycle.Corners + +variable {c : IndexedCycle inc} (k : c.Corners) + +lemma embeddedPair_outside [Fintype V] (M N : PM inc) (hU : ∀ i, c.edgeAt i ∈ M.val ∪ N.val) + (chord : Fin 4 → E) + (hc : ∀ i v, inc (chord i) v ↔ + v = (k.side i).vertex 0 ∨ v = (k.side i).vertex (k.side i).length) + (flags : Fin 64) : + (k.embeddedPair M N hU chord hc flags).outsideFirst = M.val \ c.edgeSet := by + classical + change M.val \ (k.cellPaths chord hc).orientation + (decide (k.a₀ % 2 = if c.edgeAt 0 ∈ M.val then 0 else 1)) = _ + rw [k.cell_orientation_parity] + have hp := c.inter_edgeSet_parity M.property N.property hU + have he : (if decide (k.a₀ % 2 = if c.edgeAt 0 ∈ M.val then 0 else 1) + then k.a₀ % 2 else 1-k.a₀ % 2) = (if c.edgeAt 0 ∈ M.val then 0 else 1) := by + by_cases hz : c.edgeAt 0 ∈ M.val <;> simp only [hz,ite_true,ite_false] + all_goals split_ifs <;> simp_all + rw [he,← hp] + ext e + simp + +end IndexedCycle.Corners + +namespace CellPaths + +variable (c : CellPaths inc) + +lemma through_subset_contextOne (b : Bool) (X Y : Fin 4) + (hX : sideBit X = b) (hY : sideBit Y = b) (hne : X ≠ Y) + (hinc : ∀ e, ∃ v, inc e v) : + (c.side X).through ⊆ c.contextOne b Y := by + have hd := (c.side X).through_matching.disjoint_edges (c.side Y).through_matching hinc + (c.same_bit_spans X Y hne (hX.trans hY.symm)) + intro e he + exact Finset.mem_union_left _ (Finset.mem_sdiff.mpr + ⟨c.through_subset_orientation b X hX he,fun hy => Finset.disjoint_left.mp hd he hy⟩) + +lemma contextOne_self (b : Bool) (i : Fin 4) (hi : sideBit i = b) + (he : (c.side i).closed (c.chord i) = (c.side i).through) : + c.contextOne b i = c.orientation b := by + rw [contextOne,he,Finset.sdiff_union_of_subset (c.through_subset_orientation b i hi)] + +lemma contextError_short_left (R : Finset E) (f : Finset E → ℝ) (b : Bool) + (X Y : Fin 4) (hX : sideBit X = b) (hY : sideBit Y = b) (hne : X ≠ Y) + (hinc : ∀ e, ∃ v, inc e v) + (he : (c.side X).closed (c.chord X) = (c.side X).through) : + c.contextError R f b X Y = 0 := by + rw [contextError,he,Finset.sdiff_union_of_subset + (c.through_subset_contextOne b X Y hX hY hne hinc),c.contextOne_self b X hX he] + ring + +lemma contextError_short_right (R : Finset E) (f : Finset E → ℝ) (b : Bool) + (X Y : Fin 4) (hY : sideBit Y = b) + (he : (c.side Y).closed (c.chord Y) = (c.side Y).through) : + c.contextError R f b X Y = 0 := by + rw [contextError,c.contextOne_self b Y hY he] + simp only [contextOne,sub_self] + +lemma contextError_derivative (R : Finset E) (f : Finset E → ℝ) (b : Bool) + (X Y : Fin 4) (hdis : Disjoint R (c.side X).through) : + c.contextError R f b X Y = + (f (R ∪ c.contextOne b Y) - + f (((R ∪ c.contextOne b Y) \ (c.side X).through) ∪ (c.side X).closed (c.chord X))) - + (f (R ∪ c.orientation b) - + f (((R ∪ c.orientation b) \ (c.side X).through) ∪ (c.side X).closed (c.chord X))) := by + have h (S : Finset E) : + ((R ∪ S) \ (c.side X).through) ∪ (c.side X).closed (c.chord X) = + R ∪ ((S \ (c.side X).through) ∪ (c.side X).closed (c.chord X)) := by + have hr : R \ (c.side X).through = R := by + ext e + simp only [Finset.mem_sdiff] + exact ⟨And.left,fun he => ⟨he,fun hn => Finset.disjoint_left.mp hdis he hn⟩⟩ + rw [Finset.union_sdiff_distrib,hr,Finset.union_assoc] + rw [h,h] + rfl + +end CellPaths + +end + +section + +variable {V E : Type*} + +variable {inc : E → V → Prop} + +namespace IndexedCycle + +variable (c : IndexedCycle inc) + +lemma edgeAt_injective_range {i j : ℕ} (hi : i < c.size) (hj : j < c.size) + (he : c.edgeAt i = c.edgeAt j) : i = j := by + have hf := c.four_le + have h₀ := (c.edgeAt_incidence j (c.vertexAt i)).mp + (he ▸ (c.edgeAt_incidence i _).mpr (Or.inl rfl)) + have h₁ := (c.edgeAt_incidence j (c.vertexAt (i+1))).mp + (he ▸ (c.edgeAt_incidence i _).mpr (Or.inr rfl)) + have hv : ∀ a b, c.vertexAt a = c.vertexAt b → a % c.size = b % c.size := by + intro a b h + exact congrArg Fin.val (c.simple h) + rcases h₀ with h₀ | h₀ + · have hh := hv _ _ h₀ + simpa only [Nat.mod_eq_of_lt hi, Nat.mod_eq_of_lt hj] using hh + · have hh₀ := hv _ _ h₀ + rcases h₁ with h₁ | h₁ <;> have hh₁ := hv _ _ h₁ <;> + rw [Nat.mod_eq_of_lt hi, mod_of_lt_twice (by omega)] at hh₀ <;> + rw [mod_of_lt_twice (by omega)] at hh₁ + · rw [Nat.mod_eq_of_lt hj] at hh₁ + split_ifs at hh₀ hh₁ <;> omega + · rw [mod_of_lt_twice (by omega)] at hh₁ + split_ifs at hh₀ hh₁ <;> omega + +lemma edgeAt_eq_iff {a x y : ℕ} (ha : a < c.size) + (hx : a ≤ x ∧ x < a+c.size) (hy : a ≤ y ∧ y < a+c.size) : + c.edgeAt x = c.edgeAt y ↔ x = y := by + constructor + · intro he + have hh := c.edgeAt_injective_range + (Nat.mod_lt x (by have := c.four_le; omega)) + (Nat.mod_lt y (by have := c.four_le; omega)) + (by simpa only [c.edgeAt_mod] using he) + rw [mod_of_lt_twice (by omega), mod_of_lt_twice (by omega)] at hh + split_ifs at hh <;> omega + · exact congrArg c.edgeAt + +variable [DecidableEq E] + +lemma intervalPattern_disjoint {x y z : ℕ} (hx : x < c.size) + (hxy : x ≤ y) (hyz : y ≤ z) (hz : z ≤ x+c.size) (a b : ℕ) : + Disjoint (c.intervalPattern x y a) (c.intervalPattern y z b) := by + apply Finset.disjoint_left.mpr + intro e he hf + obtain ⟨i,hi,hj,_,he⟩ := (c.mem_intervalPattern e _ _ _).mp he + obtain ⟨j,hk,hl,_,hf⟩ := (c.mem_intervalPattern e _ _ _).mp hf + have hh := (c.edgeAt_eq_iff hx ⟨hi,by omega⟩ ⟨by omega,by omega⟩).mp (he.trans hf.symm) + omega + +lemma parity_sdiff_interval {x y : ℕ} (hx : x < c.size) + (hxy : x ≤ y) (hy : y ≤ x+c.size) (a : ℕ) : + c.parityPattern a \ c.intervalPattern x y a = c.intervalPattern y (x+c.size) a := by + have hu := c.intervalPattern_union hxy hy a + rw [c.rotatedPattern (by omega) a] at hu + rw [← hu] + have hd := c.intervalPattern_disjoint hx hxy hy (by omega) a a + ext e + simp only [Finset.mem_sdiff, Finset.mem_union] + have hh : ¬ (e ∈ c.intervalPattern x y a ∧ e ∈ c.intervalPattern y (x+c.size) a) := by + rintro ⟨h,h'⟩ + exact Finset.disjoint_left.mp hd h h' + tauto + +def sewn (x y : ℕ) (e : E) : Finset E := + (c.intervalPattern x y (1-x%2) ∪ c.intervalPattern y (x+c.size) (x%2)) ∪ {e} + +lemma forward_conversion {x y : ℕ} (hx : x < c.size) (hxy : x < y) + (hy : y < c.size) (ho : (y-x)%2=1) (e : E) : + (c.parityPattern (x%2) \ (c.arc x (y-x) hx (by omega) (by omega) ho).through) ∪ + (c.arc x (y-x) hx (by omega) (by omega) ho).closed e = c.sewn x y e := by + rw [OddPath.closed, c.arc_through, c.arc_interior] + have he : x+(y-x)=y := by omega + rw [he, c.parity_sdiff_interval hx (by omega) (by omega)] + unfold sewn + ext z + simp only [Finset.mem_union] + tauto + +lemma complementary_conversion {x y : ℕ} (_hx : x < c.size) (hxy : x < y) + (hy : y < c.size) (ho : (y-x)%2=1) (e : E) : + (c.parityPattern (y%2) \ + (c.arc y (c.size+x-y) hy (by omega) (by omega) (by have := c.even; omega)).through) ∪ + (c.arc y (c.size+x-y) hy (by omega) (by omega) (by have := c.even; omega)).closed e = + c.sewn x y e := by + have hev := c.even + have hp : y%2=1-x%2 := by omega + have hp' : 1-y%2=x%2 := by omega + have he : y+(c.size+x-y)=x+c.size := by omega + rw [OddPath.closed, c.arc_through, c.arc_interior, he, + c.parity_sdiff_interval hy (by omega) (by omega)] + have hshift : c.intervalPattern (x+c.size) (y+c.size) (y%2) = + c.intervalPattern x y (y%2) := c.intervalPattern_periodic _ + rw [hshift, hp', hp] + unfold sewn + ext z + simp only [Finset.mem_union] + tauto + +lemma edgeAt_mem_parity (i : ℕ) : c.edgeAt i ∈ c.parityPattern (i%2) := by + rw [parityPattern, c.mem_intervalPattern] + have hdiv : 2 ∣ c.size := Nat.dvd_of_mod_eq_zero c.even + exact ⟨i%c.size,by omega,Nat.mod_lt _ (by have := c.four_le; omega), + Nat.mod_mod_of_dvd i hdiv,c.edgeAt_mod i⟩ + +lemma short_through (x : ℕ) (hx : x < c.size) : + (c.arc x 1 hx (by omega) (by have := c.four_le; omega) (by omega)).through = + {c.edgeAt x} := by + norm_num [OddPath.through, pathPattern, arc] + rw [show ({i ∈ ({0} : Finset ℕ) | i % 2 = 0}) = {0} by decide] + simp + +lemma short_closed (x : ℕ) (hx : x < c.size) : + (c.arc x 1 hx (by omega) (by have := c.four_le; omega) (by omega)).closed (c.edgeAt x) = + {c.edgeAt x} := by + simp [OddPath.closed, OddPath.interior, pathPattern, arc] + +lemma sewn_short (x : ℕ) (hx : x+1 < c.size) : + c.sewn x (x+1) (c.edgeAt x) = c.parityPattern (x%2) := by + have hh := c.forward_conversion (x := x) (y := x+1) (by omega) (by omega) hx (by omega) (c.edgeAt x) + have ord : x+1-x=1 := by omega + simp only [ord] at hh + rw [c.short_through, c.short_closed] at hh + rw [← hh] + have hm : {c.edgeAt x} ⊆ c.parityPattern (x%2) := by + simpa only [Finset.singleton_subset_iff] using c.edgeAt_mem_parity x + exact Finset.sdiff_union_of_subset hm + +lemma sewn_root : c.sewn 0 (c.size-1) (c.edgeAt (c.size-1)) = c.parityPattern 1 := by + have hf := c.four_le + have hev := c.even + have hh := c.complementary_conversion (x := 0) (y := c.size-1) (by omega) (by omega) + (by omega) (by omega) (c.edgeAt (c.size-1)) + have he : c.size+0-(c.size-1)=1 := by omega + have hp : (c.size-1)%2=1 := by omega + simp only [he, hp] at hh + rw [c.short_through, c.short_closed] at hh + rw [← hh] + have hm : {c.edgeAt (c.size-1)} ⊆ c.parityPattern 1 := by + simpa only [Finset.singleton_subset_iff, hp] using c.edgeAt_mem_parity (c.size-1) + exact Finset.sdiff_union_of_subset hm + +end IndexedCycle + +end + +variable {V E : Type*} [DecidableEq E] + +variable {inc : E → V → Prop} + +namespace IndexedCycle + +variable (c : IndexedCycle inc) + +def signedGain (R : Finset E) (f : Finset E → ℝ) (x y : ℕ) (e : E) : ℝ := + if x%2=0 then f (R ∪ c.parityPattern 0) - f (R ∪ c.sewn x y e) + else f (R ∪ c.sewn x y e) - f (R ∪ c.parityPattern 1) + +lemma signedGain_short (R : Finset E) (f : Finset E → ℝ) (x : ℕ) (hx : x+1 simpa only [h, sumCells] using hshort _ (by omega) + | node cell Q₁ Q₂ Q₃ h₁ h₂ h₃ => + have hpq := cell.middle_pos + have hqy := cell.third_pos + simpa only [sumCells, h₁ (by omega), h₂ (by omega), h₃ hy] + using hcell _ _ _ _ cell hy + +end MatchingFPRAS.Cells.CycleData.Subdivision + +end OAI diff --git a/lean/OAI/Combinatorics/MatchingCount/Sampling/Span.lean b/lean/OAI/Combinatorics/MatchingCount/Sampling/Span.lean new file mode 100644 index 0000000000000000000000000000000000000000..39eb2a46a9facc274944bc6b0350826a8802b760 --- /dev/null +++ b/lean/OAI/Combinatorics/MatchingCount/Sampling/Span.lean @@ -0,0 +1,211 @@ +import Mathlib +import OAI.Combinatorics.MatchingCount.Graphs.ColoredEdge + +namespace OAI + +namespace MatchingFPRAS.Transport +variable {V L : Type*} [DecidableEq V] +variable {E : Type*} [DecidableEq E] (inc : E → V → Prop) +namespace OddPath + +variable {inc} + +variable (p : OddPath inc) + +def span : Finset V := (Finset.Icc 0 p.length).image p.vertex + +def inside : Finset V := (Finset.Icc 1 (p.length - 1)).image p.vertex + +def ends : Finset V := {p.vertex 0, p.vertex p.length} + +def through : Finset E := pathPattern p.edge 0 p.length + +def interior : Finset E := pathPattern p.edge 1 (p.length - 1) + +def closed (chord : E) : Finset E := p.interior ∪ {chord} + +def boundary : Finset E := if p.length = 1 then {p.edge 0} + else {p.edge 0, p.edge (p.length - 1)} + +def repaired (repair : E) : Finset E := if p.length = 1 then ∅ + else pathPattern p.edge 2 (p.length - 2) ∪ {repair} + +def repairAdded (repair : E) : Multiset E := if p.length = 1 then 0 else {repair} + +lemma through_matching : MatchingOn inc p.through p.span := by + apply pathPattern_matching inc p.vertex p.edge 0 p.length p.positive + · simpa using p.odd + · exact p.simple + · intro i _ hi v + exact p.incidence i hi v + +lemma interior_matching : MatchingOn inc p.interior p.inside := by + by_cases h : p.length = 1 + · simpa [interior, inside, h, pathPattern] using + (empty_matching (V := V) (E := E) inc) + · have hpos := p.positive + have hodd := p.odd + apply pathPattern_matching inc p.vertex p.edge 1 (p.length - 1) + · omega + · omega + · intro i hi j hj heq + simp only [Set.mem_Icc] at hi hj + exact p.simple ⟨by omega, by omega⟩ ⟨by omega, by omega⟩ heq + · intro i hi hj v + exact p.incidence i (by omega) v + +omit [DecidableEq E] in +lemma inside_disjoint_ends : Disjoint p.inside p.ends := by + apply Finset.disjoint_left.mpr + intro v hv hw + obtain ⟨i, hi, rfl⟩ := Finset.mem_image.mp hv + obtain ⟨hil, hih⟩ := Finset.mem_Icc.mp hi + simp only [ends, Finset.mem_insert, Finset.mem_singleton] at hw + rcases hw with h | h + · have hh := p.simple ⟨by omega, by omega⟩ ⟨le_rfl, Nat.zero_le _⟩ h + omega + · have hh := p.simple ⟨by omega, by omega⟩ ⟨Nat.zero_le _, le_rfl⟩ h + omega + +omit [DecidableEq E] in +lemma inside_union_ends : p.inside ∪ p.ends = p.span := by + ext v + simp only [inside, ends, span, Finset.mem_union, Finset.mem_image, + Finset.mem_Icc, Finset.mem_insert, Finset.mem_singleton] + constructor + · rintro (⟨i, hi, rfl⟩ | rfl | rfl) + · exact ⟨i, ⟨by omega, by omega⟩, rfl⟩ + · exact ⟨0, ⟨le_rfl, Nat.zero_le _⟩, rfl⟩ + · exact ⟨p.length, ⟨Nat.zero_le _, le_rfl⟩, rfl⟩ + · rintro ⟨i, hi, rfl⟩ + by_cases h0 : i = 0 + · exact Or.inr (Or.inl (congrArg p.vertex h0)) + by_cases hh : i = p.length + · exact Or.inr (Or.inr (congrArg p.vertex hh)) + · exact Or.inl ⟨i, ⟨by omega, by omega⟩, rfl⟩ + +lemma closed_matching (chord : E) + (hc : ∀ v, inc chord v ↔ v = p.vertex 0 ∨ v = p.vertex p.length) : + MatchingOn inc (p.closed chord) p.span := by + have hm := p.interior_matching.union (singleton_matching inc chord _ _ hc) + p.inside_disjoint_ends + change MatchingOn inc (p.closed chord) (p.inside ∪ p.ends) at hm + rwa [p.inside_union_ends] at hm + +lemma repaired_matching (repair : E) + (hr : p.length ≠ 1 → ∀ v, + inc repair v ↔ v = p.vertex 1 ∨ v = p.vertex (p.length - 1)) : + MatchingOn inc (p.repaired repair) p.inside := by + by_cases h : p.length = 1 + · simpa [repaired, inside, h] using (empty_matching (V := V) (E := E) inc) + · have hpos := p.positive + have hodd := p.odd + simp only [repaired, ite_eq_right h] + simpa only [Nat.zero_add, inside] using repairedThrough_matching inc p.vertex p.edge 0 + p.length (by omega) (by simpa using p.odd) p.simple + (fun i _ hi v => p.incidence i hi v) repair (hr h) + +lemma closed_val (chord : E) + (hc : ∀ v, inc chord v ↔ v = p.vertex 0 ∨ v = p.vertex p.length) + (hinc : ∀ e, ∃ v, inc e v) : + (p.closed chord).val = p.interior.val + {chord} := by + apply union_val_add + exact p.interior_matching.disjoint_edges (singleton_matching inc chord _ _ hc) + hinc p.inside_disjoint_ends + +omit [DecidableEq V] [DecidableEq E] in +lemma edge_injective : Set.InjOn p.edge (Set.Ico 0 p.length) := by + intro i hi j hj heq + simp only [Set.mem_Ico] at hi hj + have hiinc : inc (p.edge i) (p.vertex i) := (p.incidence i hi.2 _).mpr (Or.inl rfl) + rw [heq] at hiinc + have hjinc : inc (p.edge j) (p.vertex (i+1)) := by + rw [← heq] + exact (p.incidence i hi.2 _).mpr (Or.inr rfl) + have hi₁ := (p.incidence j hj.2 _).mp hiinc + have hi₂ := (p.incidence j hj.2 _).mp hjinc + have hs₁ : i = j ∨ i = j + 1 := hi₁.imp + (p.simple ⟨by omega, by omega⟩ ⟨by omega, by omega⟩) + (p.simple ⟨by omega, by omega⟩ ⟨by omega, by omega⟩) + have hs₂ : i+1 = j ∨ i+1 = j+1 := hi₂.imp + (p.simple ⟨by omega, by omega⟩ ⟨by omega, by omega⟩) + (p.simple ⟨by omega, by omega⟩ ⟨by omega, by omega⟩) + omega + +omit [DecidableEq V] in +lemma boundary_card : p.boundary.card = if p.length = 1 then 1 else 2 := by + by_cases h : p.length = 1 + · simp [boundary, h] + · have hpos := p.positive + have hodd := p.odd + have hneq : p.edge 0 ≠ p.edge (p.length - 1) := by + intro heq + have hh := p.edge_injective ⟨le_rfl, hpos⟩ ⟨by omega, by omega⟩ heq + omega + simp [boundary, h, hneq] + +omit [DecidableEq V] in +lemma repair_conservation (repair : E) + (hr : p.length ≠ 1 → ∀ v, + inc repair v ↔ v = p.vertex 1 ∨ v = p.vertex (p.length - 1)) + (_hinc : ∀ e, ∃ v, inc e v) : + (p.repaired repair).val + p.boundary.val = p.through.val + p.repairAdded repair := by + by_cases h : p.length = 1 + · have ht : p.through = {p.edge 0} := by simp [through, pathPattern, h, Finset.filter_singleton] + simp only [repaired, boundary, repairAdded, ite_eq_left h, ht, Finset.empty_val, + zero_add, add_zero] + · have hpos := p.positive + have hodd := p.odd + have hlen : 3 ≤ p.length := by omega + let trim := pathPattern p.edge 2 (p.length - 2) + have ht : p.through = trim ∪ p.boundary := by + simpa only [through, trim, Nat.zero_add, boundary, ite_eq_right h] using + pathPattern_boundary p.edge 0 p.length hlen (by simpa using hodd) + have hbdis : Disjoint trim p.boundary := by + apply Finset.disjoint_left.mpr + intro e he hb + obtain ⟨i, hi, rfl⟩ := Finset.mem_image.mp he + obtain ⟨hi, _⟩ := Finset.mem_filter.mp hi + obtain ⟨hil, hih⟩ := Finset.mem_Ico.mp hi + simp only [boundary, ite_eq_right h, Finset.mem_insert, Finset.mem_singleton] at hb + rcases hb with hh | hh + · have hh' := p.edge_injective ⟨by omega, by omega⟩ ⟨by omega, by omega⟩ hh + omega + · have hh' := p.edge_injective ⟨by omega, by omega⟩ ⟨by omega, by omega⟩ hh + omega + have hrdis : Disjoint trim {repair} := by + apply Finset.disjoint_left.mpr + intro e he hr' + obtain ⟨i, hi, rfl⟩ := Finset.mem_image.mp he + obtain ⟨hi, _⟩ := Finset.mem_filter.mp hi + obtain ⟨hil, hih⟩ := Finset.mem_Ico.mp hi + have heq := Finset.mem_singleton.mp hr' + have hiinc : inc repair (p.vertex i) := by + rw [← heq] + exact (p.incidence i (by omega) _).mpr (Or.inl rfl) + rcases (hr h _).mp hiinc with hh | hh + · have hh' := p.simple ⟨by omega, by omega⟩ ⟨by omega, by omega⟩ hh + omega + · have hh' := p.simple ⟨by omega, by omega⟩ ⟨by omega, by omega⟩ hh + omega + rw [ht, union_val_add hbdis] + simp only [repaired, ite_eq_right h, repairAdded] + rw [union_val_add hrdis] + simp only [Finset.singleton_val] + ac_rfl + +end OddPath + +structure CellPaths where + side : Fin 4 → OddPath inc + joins : ∀ i, (side i).vertex (side i).length = (side (i+1)).vertex 0 + corners_injective : Function.Injective fun i => (side i).vertex 0 + interiors_disjoint : Pairwise fun i j => Disjoint (side i).inside (side j).inside + interior_ends_disjoint : ∀ i j, Disjoint (side i).inside (side j).ends + chord : Fin 4 → E + chord_incidence : ∀ i v, inc (chord i) v ↔ + v = (side i).vertex 0 ∨ v = (side i).vertex (side i).length + +end MatchingFPRAS.Transport + +end OAI diff --git a/lean/OAI/Combinatorics/MatchingCount/Sampling/Sym2Order.lean b/lean/OAI/Combinatorics/MatchingCount/Sampling/Sym2Order.lean new file mode 100644 index 0000000000000000000000000000000000000000..d9bca19fc18cf9db26da4ee588f516f6eac05c1b --- /dev/null +++ b/lean/OAI/Combinatorics/MatchingCount/Sampling/Sym2Order.lean @@ -0,0 +1,420 @@ +import Mathlib +import OAI.Combinatorics.MatchingCount.Graphs.RemainingBags + +namespace OAI + +namespace MatchingFPRAS.Transport + +open Finset Replica Replica.Ladder Variation + +variable {V L : Type*} [Fintype V] [LinearOrder V] [Fintype L] [LinearOrder L] + +@[instance_reducible] def sym2Order : LinearOrder (Sym2 V) := + LinearOrder.lift' (fun e=>toLex (Sym2.sortEquiv e).val) + (fun _ _ h=>Sym2.sortEquiv.injective (Subtype.ext (toLex.injective h))) + +attribute [local instance] sym2Order + +@[instance_reducible] def bagEdgeOrder {bags : V → Finset L} : LinearOrder (BagEdge bags) := + LinearOrder.lift' (fun e : BagEdge bags=>toLex e.val.val) + (fun _ _ h=>Subtype.ext (Subtype.ext (toLex.injective h))) + +attribute [local instance] bagEdgeOrder + +def rationalTierBase (V : Type*) [Fintype V] : ℚ := 1+((Fintype.card V:ℚ)^2)⁻¹ + +omit [LinearOrder V] in +lemma rationalTierBase_cast : (rationalTierBase V:ℝ)=tierBase V := by + simp [rationalTierBase,tierBase] + +def rationalSlotWeight {bags : V → Finset L} {T q : ℕ} (w : BagEdge bags → ℚ) + (x : Slot T q) (e : BagEdge bags) : ℚ := + max ((rationalTierBase V)^tier x)⁻¹ (min ((rationalTierBase V)^tier x) (w e)) + +omit [LinearOrder V] [Fintype L] [LinearOrder L] in +lemma rationalSlotWeight_cast [LinearOrder V] [Fintype L] [LinearOrder L] + {bags : V → Finset L} {T q : ℕ} (w : BagEdge bags → ℚ) + (x : Slot T q) (e : BagEdge bags) : + (rationalSlotWeight w x e:ℝ)=slotWeight (fun e=>(w e:ℝ)) x e := by + simp [rationalSlotWeight,slotWeight,tierClamp,rationalTierBase_cast] + +lemma rationalSlotWeight_pos {bags : V → Finset L} {T q : ℕ} (w : BagEdge bags → ℚ) + (x : Slot T q) (e : BagEdge bags) : 0(w e:ℝ)) x e + rw [←rationalSlotWeight_cast] at h + exact_mod_cast h + +variable {bags : V → Finset L} {G : SimpleGraph L} + +variable (hbags : ∀ v,∀ a∈bags v,∀ b∈bags v,a=b ∨ G.Adj a b) (hG : G.IsAcyclic) + +attribute [local instance] UnitRefresh.Computable.allowedDec + +@[instance_reducible] def bagEdgeFintype : Fintype (BagEdge bags) := Subtype.fintype (Allowed bags) + +attribute [local instance] bagEdgeFintype + +abbrev BagPM (bags : V → Finset L) := PM (BagEdge.Incident (bags:=bags)) + +noncomputable local instance : DecidableEq (BagPM bags) := Classical.decEq _ + +include hbags hG in +lemma parallels_bound (e : BagEdge bags) : + (univ.filter (fun f : BagEdge bags=>f.val.val.1=e.val.val.1)).card≤2 := by + have h:=BagEdge.parallels_card_le (label_memberships_le_two hbags hG) e + unfold BagEdge.parallels at h + have instances_eq : tierClampBagEdgeFintype (bags:=bags) = + (inferInstance : Fintype (BagEdge bags)) := Subsingleton.elim _ _ + rw [instances_eq] at h + exact h + +def sampleLadderPair {T q : ℕ} (w : BagEdge bags → ℚ) (x y : Slot T q) + (a : BagPM bags × BagPM bags) (k : ℕ) : (Fin k → Bool) → BagPM bags × BagPM bags := + (Sparse.pairStepTable (fun e : BagEdge bags=>e.val.val.1) (fun e=>e.val.property) + (parallels_bound hbags hG) + (rationalSlotWeight w x) (rationalSlotWeight w y) + (rationalSlotWeight_pos w x) (rationalSlotWeight_pos w y) a).draw k + +lemma pairProposal_instances {E : Type*} (F₁ F₂ : Fintype E) (D₁ D₂ : DecidableEq E) + (ends : E → Sym2 V) (hloop : ∀ e,¬(ends e).IsDiag) + (hp₁ : ∀ e,(@univ E F₁ |>.filter (fun f=>ends f=ends e)).card≤2) + (hp₂ : ∀ e,(@univ E F₂ |>.filter (fun f=>ends f=ends e)).card≤2) : + @pairProposal V E _ _ F₁ D₁ ends hloop hp₁ = + @pairProposal V E _ _ F₂ D₂ ends hloop hp₂ := by + cases Subsingleton.elim F₁ F₂ + cases Subsingleton.elim D₁ D₂ + rfl + +omit [LinearOrder V] in +lemma pairLaw_instances [LinearOrder V] {E : Type*} (F₁ F₂ : Fintype E) (ends : E → Sym2 V) + (w z : E → ℝ) : @pairLaw V E _ F₁ ends w z = @pairLaw V E _ F₂ ends w z := by + cases Subsingleton.elim F₁ F₂ + rfl + +lemma pairProposal_eq (F : Fintype (BagEdge bags)) (D : DecidableEq (BagEdge bags)) + (hpar : ∀ e : BagEdge bags,(@univ (BagEdge bags) F |>.filter + (fun f=>f.val.val.1=e.val.val.1)).card≤2) : + @pairProposal V (BagEdge bags) _ _ F D (fun e=>e.val.val.1) (fun e=>e.val.property) + hpar = treePairProposal hbags hG := by + unfold treePairProposal + exact pairProposal_instances _ _ _ _ _ _ _ _ + +omit [LinearOrder L] in +lemma pairLaw_eq [LinearOrder L] (F : Fintype (BagEdge bags)) {T q : ℕ} (w : BagEdge bags → ℚ) + (x y : Slot T q) : + @pairLaw V (BagEdge bags) _ F (fun e=>e.val.val.1) (slotWeight (fun e=>(w e:ℝ)) x) + (slotWeight (fun e=>(w e:ℝ)) y) = + (fun a : BagPM bags × BagPM bags=>slotLaw (fun e=>(w e:ℝ)) x a.1* + slotLaw (fun e=>(w e:ℝ)) y a.2) := by + exact pairLaw_instances F (instFintypeBagEdge_5 (bags:=bags)) + (fun e : BagEdge bags=>e.val.val.1) (slotWeight (fun e=>(w e:ℝ)) x) + (slotWeight (fun e=>(w e:ℝ)) y) + +lemma metropolis_eq_capacity (D : DecidableEq (BagPM bags × BagPM bags)) + {T q : ℕ} (w : BagEdge bags → ℚ) (x y : Slot T q) (a : BagPM bags × BagPM bags) : + (@metropolis _ _ D (treePairProposal hbags hG) + (fun a=>slotLaw (fun e=>(w e:ℝ)) x a.1*slotLaw (fun e=>(w e:ℝ)) y a.2) a)= + (fun b=>(treeLadderCapacity hbags hG (fun e=>(w e:ℝ)) x y).q a b / + (slotLaw (fun e=>(w e:ℝ)) x a.1*slotLaw (fun e=>(w e:ℝ)) y a.2)) := by + rw [Subsingleton.elim D (inferInstance : DecidableEq (BagPM bags × BagPM bags))] + unfold metropolis treeLadderCapacity + funext b + congr 2 + +lemma sampleLadderPair_tv {T q : ℕ} (w : BagEdge bags → ℚ) (x y : Slot T q) + (a : BagPM bags × BagPM bags) (k : ℕ) : + tv (imageLaw (sampleLadderPair hbags hG w x y a k)) + (fun b=>(treeLadderCapacity hbags hG (fun e=>(w e:ℝ)) x y).q a b / + (slotLaw (fun e=>(w e:ℝ)) x a.1*slotLaw (fun e=>(w e:ℝ)) y a.2)) ≤ + 4*(8*(Fintype.card (BagEdge bags):ℝ)^2+4*Fintype.card (BagEdge bags)+3)/(2:ℝ)^k := by + classical + have ht := Sparse.pairStepTable_tv (fun e : BagEdge bags=>e.val.val.1) + (fun e=>e.val.property) + (parallels_bound hbags hG) + (rationalSlotWeight w x) (rationalSlotWeight w y) + (rationalSlotWeight_pos w x) (rationalSlotWeight_pos w y) a k + simp_rw [rationalSlotWeight_cast] at ht + change tv (imageLaw (sampleLadderPair hbags hG w x y a k)) _ ≤ _ at ht + erw [pairProposal_eq hbags hG,pairLaw_eq,metropolis_eq_capacity] at ht + apply ht.trans + apply div_le_div_of_nonneg_right _ (by positivity) + have ha : (a.1.val.card:ℝ)≤Fintype.card (BagEdge bags) := by exact_mod_cast card_le_univ a.1.val + have hb : (a.2.val.card:ℝ)≤Fintype.card (BagEdge bags) := by exact_mod_cast card_le_univ a.2.val + have hc : (a.1.val.card.choose 2:ℝ)≤(a.1.val.card:ℝ)^2 := by exact_mod_cast Nat.choose_le_pow a.1.val.card 2 + have hd : (a.1.val.card:ℝ)^2≤(Fintype.card (BagEdge bags):ℝ)^2 := + pow_le_pow_left₀ (Nat.cast_nonneg _) ha 2 + nlinarith + +end MatchingFPRAS.Transport + +namespace MatchingFPRAS.Variation + +open Finset + +variable {A B C : Type*} [Fintype A] [Fintype B] [Fintype C] + +omit [Fintype C] in +lemma imageLaw_ignoreRight [Fintype C] [Nonempty B] (f : A → C) : + imageLaw (fun x : A×B=>f x.1)=imageLaw f := by + change imageLaw ((fun x : B×A=>f x.2) ∘ Equiv.prodComm A B)=_ + rw [imageLaw_comp_equiv,imageLaw_ignore] + +end MatchingFPRAS.Variation + +namespace MatchingFPRAS.Transport + +open Finset Replica Replica.Ladder Variation + +variable {V L : Type*} [Fintype V] [LinearOrder V] [Fintype L] [LinearOrder L] + +variable {bags : V → Finset L} + +attribute [local instance] sym2Order bagEdgeOrder bagEdgeFintype UnitRefresh.Computable.allowedDec + +noncomputable local instance : DecidableEq (BagPM bags) := Classical.decEq _ + +lemma gibbs_one_uniform (A : BagPM bags) : gibbs (fun _ : BagEdge bags=>(1:ℝ)) A= + uniform (BagPM bags) A := by + classical + simp only [gibbs,partition,matchingWeight,prod_const_one,sum_const,nsmul_eq_mul, + card_univ,mul_one,uniform,Fintype.card_eq_nat_card] + +lemma base_slotLaw {T q : ℕ} (w : BagEdge bags → ℚ) (x : Slot T q) (hx : x∈base T q) : + slotLaw (fun e=>(w e:ℝ)) x=uniform (BagPM bags) := by + classical + have he : slotWeight (fun e=>(w e:ℝ)) x=fun _ : BagEdge bags=>(1:ℝ) := by + funext e + have ht : tier x=0 := by simp only [tier,(mem_base x).mp hx,Nat.sub_self] + simp only [slotWeight,tierClamp,ht,pow_zero,inv_one] + exact max_eq_left (min_le_left _ _) + unfold slotLaw + rw [he] + funext A + simp only [gibbs,partition,matchingWeight,prod_const_one,sum_const,nsmul_eq_mul, + card_univ,mul_one,uniform,Fintype.card_eq_nat_card] + + + +open Finset Replica Replica.Ladder Variation + +variable {V L : Type*} [Fintype V] [LinearOrder V] [Fintype L] [LinearOrder L] + +variable {bags : V → Finset L} {G : SimpleGraph L} + +attribute [local instance] sym2Order bagEdgeOrder bagEdgeFintype UnitRefresh.Computable.allowedDec + +noncomputable local instance : DecidableEq (BagPM bags) := Classical.decEq _ + +@[instance_reducible] def prodOrder {A B : Type*} [LinearOrder A] [LinearOrder B] : + LinearOrder (A×B) := LinearOrder.lift' toLex toLex.injective + +@[instance_reducible] def sumOrder {A B : Type*} [LinearOrder A] [LinearOrder B] : + LinearOrder (A⊕B) := LinearOrder.lift' toLex toLex.injective + +attribute [local instance] prodOrder sumOrder + +variable (hbags : ∀ v,∀ a∈bags v,∀ b∈bags v,a=b ∨ G.Adj a b) (hG : G.IsAcyclic) + +variable (rank : L → ℕ) (parent : L → Option L) + +variable (hb : UnitRefresh.RankedBags bags rank parent) (hne : ∀ v,(bags v).Nonempty) + +variable (hp : ∀ l p,parent l=some p → rank pbaseDraw rank parent hb hne hp M k) k s bits + +def scanErrorNumerator (V L : Type*) [Fintype V] [LinearOrder V] [Fintype L] [LinearOrder L] (bags : V → Finset L) + (T q : ℕ) : ℕ := + 2*(1+(T*q^2+q))+ + 4*(8*(Fintype.card (BagEdge bags))^2+4*Fintype.card (BagEdge bags)+3)+ + 2*(Fintype.card V)^2*Fintype.card L + +lemma ladderScan_tv {T q : ℕ} (hq : 0(w e:ℝ)) T q) + (ladderFlow hbags hG (fun e=>(w e:ℝ)) T q) s) ≤ + (scanErrorNumerator V L bags T q:ℝ)/(2:ℝ)^k := by + classical + let eP : ℝ := 4*(8*(Fintype.card (BagEdge bags):ℝ)^2+4*Fintype.card (BagEdge bags)+3)/(2:ℝ)^k + let eU : ℝ := 2*(Fintype.card V:ℝ)^2*Fintype.card L/(2:ℝ)^k + have hep : 0≤eP := by dsimp [eP]; positivity + have heu : 0≤eU := by dsimp [eU]; positivity + have hpr : ∀ x y : Slot T q,y∈guides x → ∀ a : BagPM bags × BagPM bags, + tv (imageLaw (pairDraw hbags hG w k x y a)) + (fun b=>(treeLadderCapacity hbags hG (fun e=>(w e:ℝ)) x y).q a b / + (slotLaw (fun e=>(w e:ℝ)) x a.1*slotLaw (fun e=>(w e:ℝ)) y a.2))≤eP+eU := by + intro x y _ a + unfold pairDraw + rw [imageLaw_ignoreRight] + exact (sampleLadderPair_tv hbags hG w x y a k).trans (le_add_of_nonneg_right heu) + have hr : ∀ i : Slot T q,i∈base T q → + tv (imageLaw (baseDraw rank parent hb hne hp M k)) (slotLaw (fun e=>(w e:ℝ)) i)≤eP+eU := by + intro i hi + rw [base_slotLaw w i hi] + unfold baseDraw + rw [imageLaw_ignore] + exact (UnitRefresh.sampleMatching_tv k bags rank parent hb hne hp M).trans + (le_add_of_nonneg_left hep) + have ht:= sampleScan_tv_on (slotLaw (fun e=>(w e:ℝ))) (slotLaw_pos _) + (fun x=>slotLaw_sum _ x M) guides (fun x y hy=>(guides_order x y hy).ne) + (base T q) (base_nonempty T q hq) (treeLadderCapacity hbags hG (fun e=>(w e:ℝ))) + (pairDraw hbags hG w k) (fun _=>baseDraw rank parent hb hne hp M k) (eP+eU) + (add_nonneg hep heu) hpr hr k s + change tv (imageLaw (ladderScan hbags hG rank parent hb hne hp hq w M k s)) + (FiniteChain.kernel (ladderLaw (fun e=>(w e:ℝ)) T q) + (ladderFlow hbags hG (fun e=>(w e:ℝ)) T q) s) ≤ _ at ht + convert ht using 1 + have hcount : updateCount (@guides T q) (base T q)=T*q^2+q := updates_count T q + rw [hcount] + simp only [scanErrorNumerator,Nat.cast_add,Nat.cast_mul,Nat.cast_pow,Nat.cast_ofNat, + Nat.cast_one,eP,eU,add_div] + ring + +def ladderRun {T q : ℕ} (hq : 0(w e:ℝ)) T q) + (ladderFlow hbags hG (fun e=>(w e:ℝ)) T q) s t := by + apply div_nonneg + · exact scanFlow_nonneg (slotLaw _) (fun i a=>(slotLaw_pos _ i a).le) _ _ _ s t + · exact (Finset.prod_pos (fun i _=>slotLaw_pos _ i (s i))).le + +lemma ladderKernel_sum {T q : ℕ} (hq : 0(w e:ℝ)) T q) + (ladderFlow hbags hG (fun e=>(w e:ℝ)) T q) s t)=1 := by + unfold FiniteChain.kernel + rw [←sum_div] + have hr:=scanFlow_row (slotLaw (fun e=>(w e:ℝ))) (fun i=>slotLaw_sum _ i M) + guides (base T q) (base_nonempty T q hq) (treeLadderCapacity hbags hG (fun e=>(w e:ℝ))) s + change (∑ t,ladderFlow hbags hG (fun e=>(w e:ℝ)) T q s t)=_ at hr + rw [hr] + exact div_self (Finset.prod_pos (fun i _=>slotLaw_pos _ i (s i))).ne' + +lemma ladderRun_walk_tv {T q : ℕ} (hq : 0(w e:ℝ)) T q) + (ladderFlow hbags hG (fun e=>(w e:ℝ)) T q) s n) ≤ + n * (scanErrorNumerator V L bags T q:ℝ)/(2:ℝ)^k := by + have ht:=runSample_walk_tv _ _ (ladderKernel_nonneg hbags hG w) + (ladderKernel_sum hbags hG hq w M) + (ladderScan hbags hG rank parent hb hne hp hq w M k) _ + (ladderScan_tv hbags hG rank parent hb hne hp hq w M k) s n + change tv (imageLaw (ladderRun hbags hG rank parent hb hne hp hq w M k n s)) _ ≤ _ at ht + simpa only [mul_div_assoc] using ht + +lemma ladderRun_gibbs_tv (height : L → ℝ) (hheight : ∀ l,0(w e:ℝ)) T (ladderQ (Fintype.card V) D)) ≤ + (ladderSteps (Fintype.card V) D K T ξ : ℝ) * + scanErrorNumerator V L bags T (ladderQ (Fintype.card V) D)/(2:ℝ)^k+ξ := by + have hi:=ideal_ladder_sampling hbags hG height hheight hstep D K hD hN + (fun e=>(w e:ℝ)) hw hglobal M T s ξ hξ hξ1 + have hb:=ladderRun_walk_tv hbags hG rank parent hb hne hp hq w M k + (ladderSteps (Fintype.card V) D K T ξ) s + exact (tv_triangle _ _ _).trans (add_le_add hb hi) + + + +open Finset Replica Replica.Ladder Variation + +def bitPrecision (R : ℕ) (η : ℚ) : ℕ := Nat.clog 2 (R*⌈η⁻¹⌉₊) + +lemma bitPrecision_error (R : ℕ) (η : ℚ) (hη : 0<η) : + (R:ℝ)/(2:ℝ)^bitPrecision R η ≤ (η:ℝ) := by + have hp : (R:ℝ)*(⌈η⁻¹⌉₊:ℝ)≤(2:ℝ)^bitPrecision R η := by + exact_mod_cast Nat.le_pow_clog (by decide : 1<2) (R*⌈η⁻¹⌉₊) + have hh : (η:ℝ)⁻¹≤(⌈η⁻¹⌉₊:ℝ) := by + exact_mod_cast Nat.le_ceil (η⁻¹) + have he : (0:ℝ)<(η:ℝ) := by exact_mod_cast hη + apply (div_le_iff₀ (by positivity : (0:ℝ)<2^bitPrecision R η)).mpr + calc + (R:ℝ) = (η:ℝ)*((R:ℝ)*(η:ℝ)⁻¹) := by field_simp + _ ≤ (η:ℝ)*((R:ℝ)*(⌈η⁻¹⌉₊:ℝ)) := by gcongr + _ ≤ _ := mul_le_mul_of_nonneg_left hp he.le + +def pairBitsEquiv (m n : ℕ) : (Fin (m+n) → Bool) ≃ ((Fin m → Bool) × (Fin n → Bool)) := + (Equiv.arrowCongr finSumFinEquiv.symm (Equiv.refl Bool)).trans + (Equiv.sumArrowEquivProdArrow _ _ _) + +def matrixBitsEquiv (m n : ℕ) : (Fin (m*n) → Bool) ≃ (Fin m → Fin n → Bool) := + (Equiv.arrowCongr finProdFinEquiv.symm (Equiv.refl Bool)).trans (Equiv.curry _ _ _) + +def scanBitCount (N k : ℕ) : ℕ := k+(k+N*k) + +def scanBitsEquiv (V : Type*) [Fintype V] (k : ℕ) : + (Fin (scanBitCount (Fintype.card V) k) → Bool) ≃ ScanBits V k := + (pairBitsEquiv k (k+Fintype.card V*k)).trans + (Equiv.prodCongr (Equiv.refl _) ((pairBitsEquiv k (Fintype.card V*k)).trans + (Equiv.prodCongr (Equiv.refl _) (matrixBitsEquiv (Fintype.card V) k)))) + +def runBitsEquiv (V : Type*) [Fintype V] (k n : ℕ) : + (Fin (n*scanBitCount (Fintype.card V) k) → Bool) ≃ (Fin n → ScanBits V k) := + (matrixBitsEquiv n _).trans (Equiv.piCongrRight fun _=>scanBitsEquiv V k) + +variable {V L : Type*} [Fintype V] [LinearOrder V] [Fintype L] [LinearOrder L] + +variable {bags : V → Finset L} {G : SimpleGraph L} + +attribute [local instance] sym2Order bagEdgeOrder bagEdgeFintype UnitRefresh.Computable.allowedDec + +noncomputable local instance : DecidableEq (BagPM bags) := Classical.decEq _ + +attribute [local instance] prodOrder sumOrder + +variable (hbags : ∀ v,∀ a∈bags v,∀ b∈bags v,a=b ∨ G.Adj a b) (hG : G.IsAcyclic) + +variable (rank : L → ℕ) (parent : L → Option L) + +variable (hb : UnitRefresh.RankedBags bags rank parent) (hne : ∀ v,(bags v).Nonempty) + +variable (hp : ∀ l p,parent l=some p → rank p(w e:ℝ)) T q) + (ladderFlow hbags hG (fun e=>(w e:ℝ)) T q) s n) ≤ (η:ℝ) := by + dsimp only + unfold ladderBitRun + change tv (imageLaw (_ ∘ runBitsEquiv V _ n)) _ ≤ _ + rw [imageLaw_comp_equiv] + exact (ladderRun_walk_tv hbags hG rank parent hb hne hp hq w M _ n s).trans + (by simpa only [Nat.cast_mul] using bitPrecision_error (n*scanErrorNumerator V L bags T q) η hη) + +end MatchingFPRAS.Transport + +end OAI diff --git a/lean/OAI/Combinatorics/MatchingCount/Sampling/TableMarking.lean b/lean/OAI/Combinatorics/MatchingCount/Sampling/TableMarking.lean new file mode 100644 index 0000000000000000000000000000000000000000..85d5666f71f453b305d1ffc6765b310d974bdd6a --- /dev/null +++ b/lean/OAI/Combinatorics/MatchingCount/Sampling/TableMarking.lean @@ -0,0 +1,76 @@ +import Mathlib +import OAI.Combinatorics.MatchingCount.Tapes.ProductBits + +namespace OAI + +namespace MatchingFPRAS.TableMarking + +open Finset Transport Variation + +variable {V E I : Type*} [Fintype V] [Fintype E] [DecidableEq E] [Fintype I] [DecidableEq I] + +variable (inc : E → V → Prop) + +abbrev Marked := Σ M : PM inc, (↥M.val → I) + +def reveal (M : PM inc) (marks : E → I) : Marked (I:=I) inc := ⟨M,fun e=>marks e.val⟩ + +variable {A : Type*} [Fintype A] [Nonempty A] + +def draw (f : A → PM inc) (c : E → WeightedOptions I) (k : ℕ) + (bits : A×(E → Fin k → Bool)) : Marked (I:=I) inc := + reveal inc (f bits.1) (fun e=>(c e).draw k (bits.2 e)) + +noncomputable def portion (c : E → WeightedOptions I) (e : E) (i : I) : ℝ := (c e).law i + +noncomputable def law (w : E → ℝ) (c : E → WeightedOptions I) : Marked (I:=I) inc → ℝ := + sigmaLift (gibbs w) (fun M=>product (fun e : M.val=>portion c e.val)) + +lemma reveal_law (p : PM inc → ℝ) (c : E → WeightedOptions I) : + push (tensor p (product (portion c))) (fun x : PM inc×(E → I)=>reveal inc x.1 x.2)= + sigmaLift p (fun M=>product (fun e : M.val=>portion c e.val)) := by + calc + _ = sigmaLift p (fun M=>push (product (portion c)) (fun m=>fun e : M.val=>m e.val)) := by + exact push_tensor_sigma p (product (portion c)) (fun M m=>fun e : M.val=>m e.val) + _ = _ := ?_ + congr 1 + funext M + apply product_restrict + intro e + exact WeightedOptions.real_law_sum (c e) + +lemma draw_tv (f : A → PM inc) (w : E → ℝ) (c : E → WeightedOptions I) (k : ℕ) : + tv (imageLaw (draw inc f c k)) (law inc w c)≤ + tv (imageLaw f) (gibbs w)+(∑ e : E,(2:ℝ)*(c e).size)/(2:ℝ)^k := by + let mark : (E → Fin k → Bool) → E → I := fun bits e=>(c e).draw k (bits e) + have hs (e : E) : ∑ b,portion c e b=1 := WeightedOptions.real_law_sum _ + have hn (e : E) (b : I) : 0≤portion c e b := (Rat.cast_nonneg (K:=ℝ)).mpr ((c e).law_nonneg b) + have hm : tv (imageLaw mark) (product (portion c))≤(∑ e : E,(2:ℝ)*(c e).size)/(2:ℝ)^k := by + rw [show mark=(fun bits : E → Fin k → Bool=>fun e=>(c e).draw k (bits e)) from rfl, + imageLaw_componentwise] + have hh:=product_tv (fun e=>imageLaw ((c e).draw k)) (portion c) + (fun e=>imageLaw_nonneg _) (fun e=>imageLaw_sum _) hn hs + refine hh.trans ?_ + rw [sum_div] + apply sum_le_sum + intro e _ + exact (c e).draw_tv k + have htv:=tensor_tv (imageLaw f) (gibbs w) (imageLaw mark) (product (portion c)) + (imageLaw_nonneg f) (imageLaw_sum f) (product_nonneg _ hn) (product_sum _ hs) + have hc:=push_contraction (tensor (imageLaw f) (imageLaw mark)) + (tensor (gibbs w) (product (portion c))) (fun x : PM inc×(E → I)=>reveal inc x.1 x.2) + rw [reveal_law inc _ c,←imageLaw_tensor f mark,←imageLaw_comp] at hc + change tv (imageLaw (draw inc f c k)) (law inc w c)≤_ at hc + rw [imageLaw_tensor f mark] at hc + exact hc.trans (htv.trans (add_le_add_right hm _)) + +lemma draw_tv_size (f : A → PM inc) (w : E → ℝ) (c : E → WeightedOptions I) (k s : ℕ) + (h : ∀ e,(c e).size=s) : + tv (imageLaw (draw inc f c k)) (law inc w c)≤ + tv (imageLaw f) (gibbs w)+2*s*Fintype.card E/(2:ℝ)^k := by + have hh:=draw_tv inc f w c k + simpa [h,mul_comm,mul_left_comm,mul_assoc] using hh + +end MatchingFPRAS.TableMarking + +end OAI diff --git a/lean/OAI/Combinatorics/MatchingCount/Sampling/Through.lean b/lean/OAI/Combinatorics/MatchingCount/Sampling/Through.lean new file mode 100644 index 0000000000000000000000000000000000000000..134293ec942a5eb03f3841b1aff1b5a9504d2cb1 --- /dev/null +++ b/lean/OAI/Combinatorics/MatchingCount/Sampling/Through.lean @@ -0,0 +1,456 @@ +import Mathlib +import OAI.Combinatorics.MatchingCount.Graphs.Cycle + +namespace OAI + +namespace MatchingFPRAS.Transport +variable {V E : Type*} [Fintype V] [DecidableEq V] [DecidableEq E] +variable {inc : E → V → Prop} +namespace PatternCode + +variable (x : PatternCode inc) + +def through : Finset E := x.val.1 + +def closed : Finset E := x.val.2 + +def total : Finset E := x.through ∪ x.closed + +noncomputable def ofPath (p : OddPath inc) (chord : E) (hlong : 3 ≤ p.length) + (hc : ∀ v, inc chord v ↔ v = p.vertex 0 ∨ v = p.vertex p.length) : PatternCode inc := + ⟨(p.through,p.closed chord),p.closedCycle chord hlong hc, + p.closedCycle_parity_zero chord hlong hc,p.closedCycle_parity_one chord hlong hc⟩ + +omit [DecidableEq V] in +lemma activated {A B : Finset E} + (hA : MatchingOn inc A Finset.univ) (hB : MatchingOn inc B Finset.univ) + (hT : x.through ⊆ A) (hC : x.closed ⊆ B) : + x.total ∈ components (inc := inc) (A ∪ B) ∧ + A ∩ x.total = x.through ∧ B ∩ x.total = x.closed := by + obtain ⟨c,ht,hc⟩ := x.property + have heq : c.edgeSet = x.total := by + rw [c.edgeSet_eq_parity_union,ht,hc] + rfl + have hU : ∀ i, c.edgeAt i ∈ A ∪ B := by + intro i + have he := c.edgeAt_mem_edgeSet i + rw [heq] at he + rcases Finset.mem_union.mp he with he | he + · exact Finset.mem_union_left _ (hT he) + · exact Finset.mem_union_right _ (hC he) + have hz : c.edgeAt 0 ∈ A := hT (by change c.edgeAt 0 ∈ x.val.1; rw [← ht]; exact c.zero_mem_parity) + have hzn : c.edgeAt 0 ∉ B := fun hb => ((c.cycle_edge_mem_complement hA hB hU 0).mp hb) hz + have hUr : ∀ i, c.edgeAt i ∈ B ∪ A := by simpa only [Finset.union_comm] using hU + refine ⟨heq ▸ c.edgeSet_mem_components hA hB hU,?_,?_⟩ + · have h := c.inter_edgeSet_parity hA hB hU + simpa only [ite_eq_left hz,heq,ht,through] using h + · have h := c.inter_edgeSet_parity hB hA hUr + simpa only [ite_eq_right hzn,heq,hc,closed] using h + +omit [DecidableEq V] in +lemma activated_injective {A B : Finset E} + (hA : MatchingOn inc A Finset.univ) (hB : MatchingOn inc B Finset.univ) : + Set.InjOn (fun x : PatternCode inc => x.total) + {x | x.through ⊆ A ∧ x.closed ⊆ B} := by + intro x hx y hy he + change x.total = y.total at he + have hxx := x.activated hA hB hx.1 hx.2 + have hyy := y.activated hA hB hy.1 hy.2 + apply Subtype.ext + apply Prod.ext + · change x.through = y.through + rw [← hxx.2.1,← hyy.2.1,he] + · change x.closed = y.closed + rw [← hxx.2.2,← hyy.2.2,he] + +omit [DecidableEq V] in +lemma activated_derivative {A B : Finset E} + (hA : MatchingOn inc A Finset.univ) (hB : MatchingOn inc B Finset.univ) + (hT : x.through ⊆ A) (hC : x.closed ⊆ B) + (f g : Finset E → ℝ) : + (f ((A \ x.through) ∪ x.through) - f ((A \ x.through) ∪ x.closed)) - + (g ((B \ x.closed) ∪ x.through) - g ((B \ x.closed) ∪ x.closed)) = + (f A + g B) - (f (exchange A B x.total) + g (exchange B A x.total)) := by + have hx := x.activated hA hB hT hC + have hAT : A \ x.through = A \ x.total := by rw [← hx.2.1]; ext e; simp + have hBC : B \ x.closed = B \ x.total := by rw [← hx.2.2]; ext e; simp + rw [Finset.sdiff_union_of_subset hT,Finset.sdiff_union_of_subset hC,hAT,hBC] + simp only [exchange,hx.2.1,hx.2.2] + ring + +variable [Fintype E] + +noncomputable instance : Fintype (PatternCode inc) := Fintype.ofFinite _ + +omit [DecidableEq V] in +theorem activated_sum_le {A B : Finset E} + (hA : MatchingOn inc A Finset.univ) (hB : MatchingOn inc B Finset.univ) + (f g : Finset E → ℝ) : + (∑ x : PatternCode inc, if x.through ⊆ A ∧ x.closed ⊆ B then + ((f ((A \ x.through) ∪ x.through) - f ((A \ x.through) ∪ x.closed)) - + (g ((B \ x.closed) ∪ x.through) - g ((B \ x.closed) ∪ x.closed)))^2 else 0) + ≤ ∑ S ∈ components (inc := inc) (A ∪ B), + ((f A + g B) - (f (exchange A B S) + g (exchange B A S)))^2 := by + classical + rw [← Finset.sum_filter] + let active : Finset (PatternCode inc) := Finset.univ.filter (fun x => x.through ⊆ A ∧ x.closed ⊆ B) + let cost : Finset E → ℝ := fun S => + ((f A + g B) - (f (exchange A B S) + g (exchange B A S)))^2 + change (∑ x ∈ active, _) ≤ ∑ S ∈ components (inc := inc) (A ∪ B), cost S + have hinj : Set.InjOn (fun x : PatternCode inc => x.total) (active : Set (PatternCode inc)) := by + intro x hx y hy h + exact activated_injective hA hB (Finset.mem_filter.mp hx).2 (Finset.mem_filter.mp hy).2 h + calc + _ = ∑ x ∈ active, cost x.total := by + apply Finset.sum_congr rfl + intro x hx + have hh := (Finset.mem_filter.mp hx).2 + rw [x.activated_derivative hA hB hh.1 hh.2 f g] + _ = ∑ S ∈ active.image (fun x => x.total), cost S := (Finset.sum_image hinj).symm + _ ≤ _ := Finset.sum_le_sum_of_subset_of_nonneg (by + intro S hS + obtain ⟨x,hx,rfl⟩ := Finset.mem_image.mp hS + have hh := (Finset.mem_filter.mp hx).2 + exact (x.activated hA hB hh.1 hh.2).1) (fun S _ _ => sq_nonneg _) + +end PatternCode + +end MatchingFPRAS.Transport + +namespace MatchingFPRAS.PairEnergy + +open scoped BigOperators + +structure Law (Ω : Type*) [Fintype Ω] where + weight : Ω → ℝ + nonneg : ∀ x, 0 ≤ weight x + total : ∑ x, weight x = 1 + +variable {ι Ω Δ : Type*} [Fintype ι] [Fintype Ω] [Fintype Δ] + +noncomputable def guideMass (π : Law Ω) (closed : ι → Finset Ω) (X : ι) : ℝ := + ∑ B ∈ closed X, π.weight B + +noncomputable def guideMean (π : Law Ω) (closed : ι → Finset Ω) + (derivative : ι → Ω → ℝ) (X : ι) : ℝ := + (∑ B ∈ closed X, π.weight B * derivative X B) / guideMass π closed X + +noncomputable def contextMass (ρ : Δ → ℝ) (arc : Δ → ι) (context : Δ → Ω) + (X : ι) (A : Ω) : ℝ := by + classical + exact ∑ d with arc d = X ∧ context d = A, ρ d + +noncomputable def swapSum (π : Law Ω) (through closed : ι → Finset Ω) + (d₁ d₂ : ι → Ω → ℝ) : ℝ := + ∑ X, ∑ A ∈ through X, ∑ B ∈ closed X, + π.weight A * π.weight B * (d₁ X A - d₂ X B) ^ 2 + +omit [Fintype Ω] in +lemma weighted_jensen (s : Finset Ω) (w b : Ω → ℝ) (a : ℝ) + (hw : ∀ i ∈ s, 0 ≤ w i) : + (∑ i ∈ s, w i) * (a - (∑ i ∈ s, w i * b i) / (∑ i ∈ s, w i)) ^ 2 ≤ + ∑ i ∈ s, w i * (a - b i) ^ 2 := by + have hm : 0 ≤ ∑ i ∈ s, w i := Finset.sum_nonneg hw + obtain hm0 | hmpos := hm.eq_or_lt + · rw [← hm0, zero_mul] + exact Finset.sum_nonneg fun i hi => mul_nonneg (hw i hi) (sq_nonneg _) + · have hc := Finset.sum_sq_le_sum_mul_sum_of_sq_le_mul s + (r := fun i => w i * (a - b i)) + (f := w) (g := fun i => w i * (a - b i) ^ 2) + hw (fun i hi => mul_nonneg (hw i hi) (sq_nonneg _)) + (fun i hi => by nlinarith [sq_nonneg (w i * (a - b i))]) + have heq : (∑ i ∈ s, w i * (a - b i)) = + (∑ i ∈ s, w i) * + (a - (∑ i ∈ s, w i * b i) / (∑ i ∈ s, w i)) := by + simp_rw [mul_sub, Finset.sum_sub_distrib, ← Finset.sum_mul] + rw [mul_div_cancel₀ _ (ne_of_gt hmpos)] + rw [heq, mul_pow] at hc + apply (mul_le_mul_iff_right₀ hmpos).mp + nlinarith [hc] + +omit [Fintype Ω] in +lemma sum_contextMass (ρ : Δ → ℝ) (arc : Δ → ι) (context : Δ → Ω) + (through : ι → Finset Ω) (hcontext : ∀ d, context d ∈ through (arc d)) + (h : ι → Ω → ℝ) : + (∑ d, ρ d * h (arc d) (context d)) = + ∑ X, ∑ A ∈ through X, contextMass ρ arc context X A * h X A := by + classical + symm + simp only [contextMass, Finset.sum_mul] + calc + _ = ∑ X, ∑ A ∈ through X, + ∑ d with arc d = X ∧ context d = A, ρ d * h (arc d) (context d) := by + apply Finset.sum_congr rfl + intro X _ + apply Finset.sum_congr rfl + intro A _ + apply Finset.sum_congr rfl + intro d hd + obtain ⟨hX, hA⟩ := (Finset.mem_filter.mp hd).2 + rw [hX, hA] + _ = ∑ X, ∑ d with arc d = X, ρ d * h (arc d) (context d) := by + apply Finset.sum_congr rfl + intro X _ + have ht : ∀ d ∈ Finset.univ.filter (fun d => arc d = X), context d ∈ through X := by + intro d hd + simpa only [(Finset.mem_filter.mp hd).2] using hcontext d + simpa only [Finset.filter_filter] using + Finset.sum_fiberwise_of_maps_to ht (fun d => ρ d * h (arc d) (context d)) + _ = ∑ d, ρ d * h (arc d) (context d) := Finset.sum_fiberwise _ arc _ + +omit [Fintype ι] in +lemma tagged_context_bound {Tag : Type*} [Fintype Tag] + (π : Law Ω) (closed : ι → Finset Ω) (ρ : Δ → ℝ) + (arc : Δ → ι) (context guide : Δ → Ω) (tag : Δ → Tag) (C : ℝ) + (hC : 0 ≤ C) + (hguide : ∀ d, guide d ∈ closed (arc d)) + (hinj : Function.Injective fun d => (context d, guide d, tag d)) + (hweight : ∀ d, ρ d ≤ C * π.weight (context d) * π.weight (guide d)) + (X : ι) (A : Ω) : + contextMass ρ arc context X A ≤ + (C * Fintype.card Tag) * π.weight A * guideMass π closed X := by + classical + let s : Finset Δ := Finset.univ.filter (fun d => arc d = X ∧ context d = A) + have hmaps : ∀ d ∈ s, guide d ∈ closed X := by + intro d hd + have hX := (Finset.mem_filter.mp hd).2.1 + simpa only [hX] using hguide d + have hfiber (B : Ω) : (s.filter (fun d => guide d = B)).card ≤ Fintype.card Tag := by + apply Finset.card_le_card_of_injOn tag (t := Finset.univ) + · intro d hd + exact Finset.mem_univ _ + · intro d hd e he heq + apply hinj + have hd' := (Finset.mem_filter.mp (Finset.mem_filter.mp hd).1).2 + have he' := (Finset.mem_filter.mp (Finset.mem_filter.mp he).1).2 + have hdB := (Finset.mem_filter.mp hd).2 + have heB := (Finset.mem_filter.mp he).2 + exact Prod.ext (hd'.2.trans he'.2.symm) (Prod.ext (hdB.trans heB.symm) heq) + change (∑ d ∈ s, ρ d) ≤ _ + rw [← Finset.sum_fiberwise_of_maps_to hmaps ρ] + calc + _ ≤ ∑ B ∈ closed X, (Fintype.card Tag : ℝ) * (C * π.weight A * π.weight B) := by + apply Finset.sum_le_sum + intro B hB + calc + _ ≤ ∑ d ∈ s with guide d = B, C * π.weight A * π.weight B := by + apply Finset.sum_le_sum + intro d hd + have hdA := (Finset.mem_filter.mp (Finset.mem_filter.mp hd).1).2.2 + have hdB := (Finset.mem_filter.mp hd).2 + simpa only [hdA, hdB] using hweight d + _ = ((s.filter (fun d => guide d = B)).card : ℝ) * + (C * π.weight A * π.weight B) := by simp + _ ≤ _ := mul_le_mul_of_nonneg_right (by exact_mod_cast hfiber B) + (mul_nonneg (mul_nonneg hC (π.nonneg A)) (π.nonneg B)) + _ = _ := by + simp only [guideMass, Finset.mul_sum] + apply Finset.sum_congr rfl + intro B hB + ring + +theorem error_demand_load + (π : Law Ω) (through closed : ι → Finset Ω) (d₁ d₂ : ι → Ω → ℝ) + (ρ : Δ → ℝ) (arc : Δ → ι) (c₀ c₁ : Δ → Ω) (C : ℝ) + (hρ : ∀ d, 0 ≤ ρ d) (hC : 0 ≤ C) + (hc₀ : ∀ d, c₀ d ∈ through (arc d)) + (hc₁ : ∀ d, c₁ d ∈ through (arc d)) + (hm₀ : ∀ X A, contextMass ρ arc c₀ X A ≤ C * π.weight A * guideMass π closed X) + (hm₁ : ∀ X A, contextMass ρ arc c₁ X A ≤ C * π.weight A * guideMass π closed X) : + (∑ d, ρ d * (d₁ (arc d) (c₁ d) - d₁ (arc d) (c₀ d)) ^ 2) ≤ + 4 * C * swapSum π through closed d₁ d₂ := by + classical + let μ := guideMean π closed d₂ + have hcontext (c : Δ → Ω) (hc : ∀ d, c d ∈ through (arc d)) + (hm : ∀ X A, contextMass ρ arc c X A ≤ C * π.weight A * guideMass π closed X) : + (∑ d, ρ d * (d₁ (arc d) (c d) - μ (arc d)) ^ 2) ≤ + C * swapSum π through closed d₁ d₂ := by + rw [sum_contextMass ρ arc c through hc (fun X A => (d₁ X A - μ X) ^ 2)] + calc + _ ≤ ∑ X, ∑ A ∈ through X, + C * π.weight A * guideMass π closed X * (d₁ X A - μ X) ^ 2 := by + apply Finset.sum_le_sum + intro X _ + exact Finset.sum_le_sum fun A _ => + mul_le_mul_of_nonneg_right (hm X A) (sq_nonneg _) + _ ≤ ∑ X, ∑ A ∈ through X, C * π.weight A * + (∑ B ∈ closed X, π.weight B * (d₁ X A - d₂ X B) ^ 2) := by + apply Finset.sum_le_sum + intro X _ + apply Finset.sum_le_sum + intro A _ + have hj := weighted_jensen (closed X) π.weight (d₂ X) (d₁ X A) + (fun B _ => π.nonneg B) + change guideMass π closed X * (d₁ X A - μ X) ^ 2 ≤ _ at hj + convert mul_le_mul_of_nonneg_left hj (mul_nonneg hC (π.nonneg A)) using 1 + ring + _ = C * swapSum π through closed d₁ d₂ := by + simp only [swapSum, Finset.mul_sum] + apply Finset.sum_congr rfl + intro X _ + apply Finset.sum_congr rfl + intro A _ + apply Finset.sum_congr rfl + intro B _ + ring + have h₀ := hcontext c₀ hc₀ hm₀ + have h₁ := hcontext c₁ hc₁ hm₁ + calc + _ ≤ ∑ d, (2 * (ρ d * (d₁ (arc d) (c₁ d) - μ (arc d)) ^ 2) + + 2 * (ρ d * (d₁ (arc d) (c₀ d) - μ (arc d)) ^ 2)) := by + apply Finset.sum_le_sum + intro d _ + nlinarith [mul_nonneg (hρ d) + (sq_nonneg (d₁ (arc d) (c₁ d) + d₁ (arc d) (c₀ d) - 2 * μ (arc d)))] + _ = 2 * (∑ d, ρ d * (d₁ (arc d) (c₁ d) - μ (arc d)) ^ 2) + + 2 * (∑ d, ρ d * (d₁ (arc d) (c₀ d) - μ (arc d)) ^ 2) := by + rw [Finset.sum_add_distrib, ← Finset.mul_sum, ← Finset.mul_sum] + _ ≤ 4 * C * swapSum π through closed d₁ d₂ := by linarith + +end MatchingFPRAS.PairEnergy + +namespace MatchingFPRAS.Transport + +variable {V E : Type*} [Fintype V] [DecidableEq V] [Fintype E] [DecidableEq E] + +variable {inc : E → V → Prop} + +noncomputable instance instFintypePM : Fintype (PM inc) := Fintype.ofFinite _ + +noncomputable def gibbsLaw (w : E → ℝ) (hw : ∀ e, 0 < w e) (M : PM inc) : + MatchingFPRAS.PairEnergy.Law (PM inc) where + weight := gibbs w + nonneg := fun A => le_of_lt (gibbs_pos w hw A) + total := gibbs_sum w hw M + +namespace PatternCode + +noncomputable def throughStates (x : PatternCode inc) : Finset (PM inc) := by + classical + exact Finset.univ.filter (fun A => x.through ⊆ A.val) + +noncomputable def closedStates (x : PatternCode inc) : Finset (PM inc) := by + classical + exact Finset.univ.filter (fun A => x.closed ⊆ A.val) + +omit [DecidableEq V] in +lemma mem_throughStates (x : PatternCode inc) (A : PM inc) : + A ∈ x.throughStates ↔ x.through ⊆ A.val := by + classical + simp [throughStates] + +omit [DecidableEq V] in +lemma mem_closedStates (x : PatternCode inc) (A : PM inc) : + A ∈ x.closedStates ↔ x.closed ⊆ A.val := by + classical + simp [closedStates] + +def firstDerivative (f : Finset E → ℝ) (x : PatternCode inc) (A : PM inc) : ℝ := + f A.val - f ((A.val \ x.through) ∪ x.closed) + +def secondDerivative (g : Finset E → ℝ) (x : PatternCode inc) (B : PM inc) : ℝ := + g ((B.val \ x.closed) ∪ x.through) - g B.val + +end PatternCode + +end MatchingFPRAS.Transport + +namespace MatchingFPRAS.Transport.CellDemands + +variable {V L : Type*} [Fintype V] [DecidableEq V] [Fintype L] [DecidableEq L] + +variable {bags : V → Finset L} {G : SimpleGraph L} + +noncomputable local instance : Fintype (BagEdge bags) := Fintype.ofFinite _ + +variable {hbags : ∀ v, ∀ a ∈ bags v, ∀ b ∈ bags v, a = b ∨ G.Adj a b} + +variable {hG : G.IsAcyclic} + +namespace ErrorDemand + +variable (e : ErrorDemand hbags hG) + +omit [Fintype L] in +lemma X_long : 3 ≤ (e.demand.paths.side e.X).length := by + have hp := (e.demand.paths.side e.X).positive + have ho := (e.demand.paths.side e.X).odd + have hn := e.property e.X e.X_bit + change (e.demand.paths.side e.X).length ≠ 1 at hn + omega + +noncomputable def pattern : PatternCode (BagEdge.Incident (bags := bags)) := + PatternCode.ofPath (e.demand.paths.side e.X) (e.demand.paths.chord e.X) e.X_long + (e.demand.paths.chord_incidence e.X) + +variable (height : L → ℝ) (hheight : ∀ l, 0 < height l) + +variable (hstep : ∀ a b, G.Adj a b → height a ≤ 2 * height b) + +variable (D : ℝ) (hD : 1 ≤ D) (w : BagEdge bags → ℝ) + +variable (hw : ∀ e, height e.color / D ≤ w e ∧ w e ≤ 3 * height e.color) + +variable (lo hi : ℝ) (hlo : 0 < lo) (hlohi : lo ≤ hi) + +noncomputable def choice (j : Bool) : DemandEncoding BagEdge.Incident e.raw := + if j then e.errorOne height hheight hstep D hD w hw lo hi hlo hlohi + else e.errorZero height hheight hstep D hD w hw lo hi hlo hlohi + +lemma choice_spec (j : Bool) : + let enc := e.choice height hheight hstep D hD w hw lo hi hlo hlohi j + enc.first.val = e.demand.outside ∪ + (if j then e.demand.paths.contextOne e.bit e.Y else e.demand.paths.orientation e.bit) ∧ + e.pattern.closed ⊆ enc.second.val ∧ + gibbs (fun e => max lo (min hi (w e))) e.demand.1.1 * + gibbs (fun e => max lo (min hi (w e))) e.demand.1.2 ≤ + (1000*D)^4 * gibbs (fun e => max lo (min hi (w e))) enc.first * + gibbs (fun e => max lo (min hi (w e))) enc.second := by + have h := (e.exists_errors height hheight hstep D hD w hw lo hi hlo hlohi).choose_spec.choose_spec + change _ ∧ _ ∧ _ ∧ _ ∧ _ ∧ _ at h + cases j + · exact ⟨h.1,h.2.2.1,h.2.2.2.2.1⟩ + · exact ⟨h.2.1,h.2.2.2.1,h.2.2.2.2.2⟩ + +lemma choice_injective (j : Bool) : Function.Injective (fun e : ErrorDemand hbags hG => + (e.choice height hheight hstep D hD w hw lo hi hlo hlohi j).finiteCode) := by + intro e f h + exact raw_injective (DemandEncoding.finiteCode_recovers _ _ h) + +lemma choice_through (j : Bool) : + (e.choice height hheight hstep D hD w hw lo hi hlo hlohi j).first ∈ e.pattern.throughStates := by + apply (e.pattern.mem_throughStates _).mpr + rw [(e.choice_spec height hheight hstep D hD w hw lo hi hlo hlohi j).1] + change (e.demand.paths.side e.X).through ⊆ _ + apply Finset.Subset.trans _ (Finset.subset_union_right) + cases j + · exact e.demand.paths.through_subset_orientation e.bit e.X e.X_bit + · exact e.demand.paths.through_subset_contextOne e.bit e.X e.Y e.X_bit e.Y_bit e.X_ne_Y + BagEdge.exists_incident + +theorem context_load (M : PM (BagEdge.Incident (bags := bags))) (j : Bool) + (X : PatternCode (BagEdge.Incident (bags := bags))) (A : PM BagEdge.Incident) : + let wt := fun e => max lo (min hi (w e)) + let π := gibbsLaw wt (fun _ => lt_of_lt_of_le hlo (le_max_left _ _)) M + let ρ := fun e : ErrorDemand hbags hG => gibbs wt e.demand.1.1 * gibbs wt e.demand.1.2 + let enc := fun e : ErrorDemand hbags hG => e.choice height hheight hstep D hD w hw lo hi hlo hlohi j + MatchingFPRAS.PairEnergy.contextMass ρ pattern (fun e => (enc e).first) X A ≤ + ((1000*D)^4 * Fintype.card (DemandTag (V := V) (E := BagEdge bags))) * + π.weight A * MatchingFPRAS.PairEnergy.guideMass π PatternCode.closedStates X := by + dsimp only + apply MatchingFPRAS.PairEnergy.tagged_context_bound + (guide := fun e => (e.choice height hheight hstep D hD w hw lo hi hlo hlohi j).second) + (tag := fun e => (e.choice height hheight hstep D hD w hw lo hi hlo hlohi j).tag) + · positivity + · intro e + exact (e.pattern.mem_closedStates _).mpr + (e.choice_spec height hheight hstep D hD w hw lo hi hlo hlohi j).2.1 + · exact choice_injective height hheight hstep D hD w hw lo hi hlo hlohi j + · intro e + exact (e.choice_spec height hheight hstep D hD w hw lo hi hlo hlohi j).2.2 + +end ErrorDemand + +end MatchingFPRAS.Transport.CellDemands + +end OAI diff --git a/lean/OAI/Combinatorics/MatchingCount/Sampling/TierClamp.lean b/lean/OAI/Combinatorics/MatchingCount/Sampling/TierClamp.lean new file mode 100644 index 0000000000000000000000000000000000000000..9c1ac7e26981cc8f1e6ad2939108ae6b70d843b9 --- /dev/null +++ b/lean/OAI/Combinatorics/MatchingCount/Sampling/TierClamp.lean @@ -0,0 +1,441 @@ +import Mathlib +import OAI.Combinatorics.MatchingCount.Probability.Variance + +namespace OAI + +namespace MatchingFPRAS.Transport + +section + +noncomputable def tierClamp (c : ℝ) (t : ℕ) (w : ℝ) : ℝ := + max (c^t)⁻¹ (min (c^t) w) + +lemma tierClamp_pos {c : ℝ} (hc : 0 < c) (t : ℕ) (w : ℝ) : 0 < tierClamp c t w := + lt_of_lt_of_le (inv_pos.mpr (pow_pos hc t)) (le_max_left _ _) + +lemma clamp_comparison {c lo hi lo' hi' w : ℝ} (hc : 0 ≤ c) + (hlo : lo' ≤ c*lo) (hhi : hi' ≤ c*hi) (hw : w ≤ c*w) : + max lo' (min hi' w) ≤ c*max lo (min hi w) := by + rw [mul_max_of_nonneg _ _ hc,mul_min_of_nonneg _ _ hc] + exact max_le_max hlo (min_le_min hhi hw) + +lemma tierClamp_adjacent {c : ℝ} (hc : 1 ≤ c) (t : ℕ) {w : ℝ} (hw : 0 ≤ w) : + tierClamp c (t+1) w ≤ c*tierClamp c t w ∧ + tierClamp c t w ≤ c*tierClamp c (t+1) w := by + have hc0 : 0 < c := lt_of_lt_of_le (by norm_num) hc + have ht : 0 < c^t := pow_pos hc0 t + have ht1 : 0 < c^(t+1) := pow_pos hc0 _ + have hpow : c^t ≤ c^(t+1) := pow_le_pow_right₀ hc (by omega) + have hi : (c^(t+1))⁻¹ ≤ (c^t)⁻¹ := inv_anti₀ ht hpow + have hwc : w ≤ c*w := by nlinarith + constructor + · apply clamp_comparison hc0.le _ _ hwc + · exact hi.trans (by nlinarith [inv_pos.mpr ht]) + · rw [pow_succ]; nlinarith + · apply clamp_comparison hc0.le _ _ hwc + · have he : (c^t)⁻¹ = c*(c^(t+1))⁻¹ := by + rw [pow_succ,mul_inv_rev]; field_simp + exact he.le + · exact hpow.trans (by nlinarith) + +lemma ladder_base_pow_bound (N : ℕ) (hN : 2 ≤ N) : + (1+((N:ℝ)^2)⁻¹)^N ≤ 2 := by + have hn2 : (2:ℝ) ≤ N := by exact_mod_cast hN + have hn : (0:ℝ) < N := by positivity + have hx : 0 ≤ ((N:ℝ)^2)⁻¹ := by positivity + have hbase : 0 ≤ 1+((N:ℝ)^2)⁻¹ := by positivity + have hb : 1+((N:ℝ)^2)⁻¹ ≤ Real.exp (((N:ℝ)^2)⁻¹) := by simpa [add_comm] using Real.add_one_le_exp (((N:ℝ)^2)⁻¹) + have hp := pow_le_pow_left₀ hbase hb N + have he : (Real.exp (((N:ℝ)^2)⁻¹))^N = Real.exp ((N:ℝ)⁻¹) := by + rw [← Real.exp_nat_mul] + congr 1 + field_simp + rw [he] at hp + have hinv : (N:ℝ)⁻¹ ≤ 1/2 := (inv_le_comm₀ hn (by norm_num)).mpr (by nlinarith) + have hexp : Real.exp (1/2:ℝ) < 2 := by + have hs : (Real.exp (1/2:ℝ))^2 = Real.exp 1 := by + rw [← Real.exp_nat_mul]; norm_num + have h := Real.exp_one_lt_three + have hpos := Real.exp_pos (1/2:ℝ) + nlinarith + exact hp.trans ((Real.exp_le_exp.mpr hinv).trans hexp.le) + +variable {V E : Type*} [Fintype V] [DecidableEq V] [Fintype E] [DecidableEq E] + +variable (ends : E → Sym2 V) (hloop : ∀ e, ¬(ends e).IsDiag) + +include hloop + +omit [DecidableEq E] in +theorem adjacent_gibbs (hN : 2 ≤ Fintype.card V) (w : E → ℝ) (hw : ∀ e, 0 < w e) + (t : ℕ) (A : PM (fun e v => v ∈ ends e)) : + let c : ℝ := 1+((Fintype.card V:ℝ)^2)⁻¹ + let πt := gibbs (fun e => tierClamp c t (w e)) A + let πnext := gibbs (fun e => tierClamp c (t+1) (w e)) A + πnext/2 ≤ πt ∧ πt ≤ 2*πnext := by + let c : ℝ := 1+((Fintype.card V:ℝ)^2)⁻¹ + have hc : 1 ≤ c := by + dsimp [c] + have : 0 ≤ ((Fintype.card V:ℝ)^2)⁻¹ := by positivity + linarith + have hc0 : 0 < c := lt_of_lt_of_le (by norm_num) hc + let z := fun e => tierClamp c t (w e) + let z' := fun e => tierClamp c (t+1) (w e) + have hz : ∀ e, 0 < z e := fun e => tierClamp_pos hc0 t (w e) + have hz' : ∀ e, 0 < z' e := fun e => tierClamp_pos hc0 (t+1) (w e) + have hh := fun e => tierClamp_adjacent hc t (hw e).le + have h1 := gibbs_compare ends hloop hz hz' c hc0.le (fun e => (hh e).2) (fun e => (hh e).1) A + have h2 := gibbs_compare ends hloop hz' hz c hc0.le (fun e => (hh e).1) (fun e => (hh e).2) A + have hb : c^(Fintype.card V) ≤ 2 := ladder_base_pow_bound _ hN + have hp := gibbs_pos z hz A + have hp' := gibbs_pos z' hz' A + change gibbs z' A/2 ≤ gibbs z A ∧ gibbs z A ≤ 2*gibbs z' A + constructor <;> nlinarith [mul_nonneg (sub_nonneg.mpr hb) hp.le, + mul_nonneg (sub_nonneg.mpr hb) hp'.le] + +end + +section + +open Finset + +variable {V E : Type*} [Fintype V] [DecidableEq V] [Fintype E] [DecidableEq E] + +variable {inc : E → V → Prop} + +omit [Fintype E] in +lemma exchange_inter (M N S : Finset E) : + exchange M N S ∩ exchange N M S = M ∩ N := by + ext e + simp only [Finset.mem_inter,mem_exchange] + tauto + +noncomputable def cycleMove (p : PM inc × PM inc) (S : Finset E) : PM inc × PM inc := by + classical + exact if h : S ∈ components (inc := inc) (p.1.val ∪ p.2.val) then + (⟨exchange p.1.val p.2.val S, exchange_matching p.1.property p.2.property + (component_exchange_compatible h)⟩, + ⟨exchange p.2.val p.1.val S, exchange_matching p.2.property p.1.property + (component_exchange_compatible h).symm⟩) else p + +omit [DecidableEq V] [Fintype E] in +lemma cycleMove_val (p : PM inc × PM inc) (S : Finset E) + (h : S ∈ components (inc := inc) (p.1.val ∪ p.2.val)) : + (cycleMove p S).1.val = exchange p.1.val p.2.val S ∧ + (cycleMove p S).2.val = exchange p.2.val p.1.val S := by + classical + simp only [cycleMove,dite_eq_left h,Subtype.coe_mk,and_self] + +omit [DecidableEq V] [Fintype E] in +lemma cycleMove_union (p : PM inc × PM inc) (S : Finset E) : + (cycleMove p S).1.val ∪ (cycleMove p S).2.val = p.1.val ∪ p.2.val := by + classical + unfold cycleMove + split_ifs with h + · exact exchange_union _ _ _ + · rfl + +omit [DecidableEq V] [Fintype E] in +lemma cycleMove_inter (p : PM inc × PM inc) (S : Finset E) : + (cycleMove p S).1.val ∩ (cycleMove p S).2.val = p.1.val ∩ p.2.val := by + classical + unfold cycleMove + split_ifs with h + · exact exchange_inter _ _ _ + · rfl + +omit [DecidableEq V] [Fintype E] in +lemma cycleMove_discrepancy (p : PM inc × PM inc) (S : Finset E) : + discrepancyComponents (cycleMove p S).1 (cycleMove p S).2 = discrepancyComponents p.1 p.2 := by + classical + unfold discrepancyComponents + rw [cycleMove_union,cycleMove_inter] + +omit [DecidableEq V] [Fintype E] in +lemma cycleMove_involution (p : PM inc × PM inc) (S : Finset E) : + cycleMove (cycleMove p S) S = p := by + classical + by_cases h : S ∈ components (inc := inc) (p.1.val ∪ p.2.val) + · have h' : S ∈ components (inc := inc) ((cycleMove p S).1.val ∪ (cycleMove p S).2.val) := by + rwa [cycleMove_union] + apply Prod.ext <;> apply Subtype.ext + · rw [(cycleMove_val _ _ h').1,(cycleMove_val _ _ h).1,(cycleMove_val _ _ h).2] + exact exchange_involution _ _ _ + · rw [(cycleMove_val _ _ h').2,(cycleMove_val _ _ h).1,(cycleMove_val _ _ h).2] + exact exchange_involution _ _ _ + · simp only [cycleMove,dite_eq_right h] + +omit [DecidableEq V] [Fintype E] in +lemma cycleMove_eq_iff (p q : PM inc × PM inc) (S : Finset E) : + cycleMove p S = q ↔ cycleMove q S = p := by + constructor <;> intro h <;> rw [← h,cycleMove_involution] + +omit [DecidableEq V] in +lemma cycleMove_gibbs (w : E → ℝ) (p : PM inc × PM inc) (S : Finset E) : + gibbs w (cycleMove p S).1*gibbs w (cycleMove p S).2 = gibbs w p.1*gibbs w p.2 := by + classical + by_cases h : S ∈ components (inc := inc) (p.1.val ∪ p.2.val) + · unfold gibbs matchingWeight + rw [(cycleMove_val _ _ h).1,(cycleMove_val _ _ h).2,div_mul_div_comm,exchange_weight] + rw [div_mul_div_comm] + · simp only [cycleMove,dite_eq_right h] + +noncomputable def cycleTerm (p q : PM inc × PM inc) (S : Finset E) : ℝ := by + classical + exact if S ∈ discrepancyComponents p.1 p.2 ∧ cycleMove p S = q then + ((discrepancyComponents p.1 p.2).card : ℝ)⁻¹ else 0 + +noncomputable def cycleProposal (p q : PM inc × PM inc) : ℝ := by + classical + exact if (discrepancyComponents p.1 p.2).Nonempty then ∑ S, cycleTerm p q S + else if p = q then 1 else 0 + +omit [DecidableEq V] [Fintype E] in +lemma cycleTerm_symmetric (p q : PM inc × PM inc) (S : Finset E) : + cycleTerm p q S = cycleTerm q p S := by + classical + have he : (S ∈ discrepancyComponents p.1 p.2 ∧ cycleMove p S = q) ↔ + (S ∈ discrepancyComponents q.1 q.2 ∧ cycleMove q S = p) := by + constructor + · rintro ⟨h,rfl⟩ + exact ⟨by rwa [cycleMove_discrepancy],cycleMove_involution _ _⟩ + · rintro ⟨h,rfl⟩ + exact ⟨by rwa [cycleMove_discrepancy],cycleMove_involution _ _⟩ + unfold cycleTerm + by_cases h : S ∈ discrepancyComponents p.1 p.2 ∧ cycleMove p S = q + · rw [ite_eq_left h,ite_eq_left (he.mp h),← h.2,cycleMove_discrepancy] + · rw [ite_eq_right h,ite_eq_right (mt he.mpr h)] + +omit [DecidableEq V] [Fintype E] in +lemma cycleTerm_nonneg (p q : PM inc × PM inc) (S : Finset E) : 0 ≤ cycleTerm p q S := by + classical + unfold cycleTerm + split_ifs <;> positivity + +omit [DecidableEq V] in +lemma cycleTerm_sum (p : PM inc × PM inc) (S : Finset E) : + (∑ q, cycleTerm p q S) = if S ∈ discrepancyComponents p.1 p.2 then + ((discrepancyComponents p.1 p.2).card : ℝ)⁻¹ else 0 := by + classical + by_cases h : S ∈ discrepancyComponents p.1 p.2 + · simp only [cycleTerm,h,true_and] + simp + · simp [cycleTerm,h] + +omit [DecidableEq V] [Fintype E] in +lemma cycleTerm_zero (p q : PM inc × PM inc) (h : ¬(discrepancyComponents p.1 p.2).Nonempty) + (S : Finset E) : cycleTerm p q S = 0 := by + classical + have he := Finset.not_nonempty_iff_eq_empty.mp h + simp [cycleTerm,he] + +omit [DecidableEq V] in +lemma cycleProposal_nonneg (p q : PM inc × PM inc) : 0 ≤ cycleProposal p q := by + classical + unfold cycleProposal + split_ifs + · exact Finset.sum_nonneg (fun S _ => cycleTerm_nonneg p q S) + · norm_num + · norm_num + +omit [DecidableEq V] in +lemma cycleProposal_row (p : PM inc × PM inc) : (∑ q, cycleProposal p q) = 1 := by + classical + by_cases h : (discrepancyComponents p.1 p.2).Nonempty + · simp only [cycleProposal,ite_eq_left h] + rw [Finset.sum_comm] + simp_rw [cycleTerm_sum] + rw [← Finset.sum_filter] + simp only [Finset.filter_mem_eq_inter,Finset.univ_inter,Finset.sum_const,nsmul_eq_mul] + exact mul_inv_cancel₀ (by exact_mod_cast ne_of_gt (Finset.card_pos.mpr h)) + · simp [cycleProposal,h] + +omit [DecidableEq V] in +lemma cycleProposal_symmetric (p q : PM inc × PM inc) : cycleProposal p q = cycleProposal q p := by + classical + by_cases hp : (discrepancyComponents p.1 p.2).Nonempty <;> + by_cases hq : (discrepancyComponents q.1 q.2).Nonempty + · simp only [cycleProposal,ite_eq_left hp,ite_eq_left hq,cycleTerm_symmetric p q] + · have hpq : p ≠ q := by rintro rfl; exact hq hp + simp only [cycleProposal,ite_eq_left hp,ite_eq_right hq,ite_eq_right (Ne.symm hpq)] + apply Finset.sum_eq_zero; intro S _ + rw [cycleTerm_symmetric,cycleTerm_zero _ _ hq] + · exact (by + have hpq : q ≠ p := by rintro rfl; exact hp hq + simp only [cycleProposal,ite_eq_right hp,ite_eq_left hq,ite_eq_right (Ne.symm hpq)] + symm; apply Finset.sum_eq_zero; intro S _ + rw [cycleTerm_symmetric,cycleTerm_zero _ _ hp]) + · simp only [cycleProposal,ite_eq_right hp,ite_eq_right hq,eq_comm] + +omit [DecidableEq V] in +lemma cycleProposal_gibbs (w : E → ℝ) (p q : PM inc × PM inc) : + gibbs w p.1*gibbs w p.2*cycleProposal p q = + gibbs w q.1*gibbs w q.2*cycleProposal q p := by + classical + rw [cycleProposal_symmetric q p] + by_cases h : (discrepancyComponents p.1 p.2).Nonempty + · simp only [cycleProposal,ite_eq_left h,Finset.mul_sum] + apply Finset.sum_congr rfl + intro S _ + unfold cycleTerm + split_ifs with he + · rw [← he.2,cycleMove_gibbs] + · simp + · by_cases he : p = q + · subst q; rfl + · simp [cycleProposal,h,he] + +omit [DecidableEq V] in +lemma cycleProposal_expectation (p : PM inc × PM inc) (F : PM inc × PM inc → ℝ) : + (∑ q, cycleProposal p q * F q) = + if (discrepancyComponents p.1 p.2).Nonempty then + (∑ S ∈ discrepancyComponents p.1 p.2, F (cycleMove p S)) / + (discrepancyComponents p.1 p.2).card else F p := by + classical + by_cases h : (discrepancyComponents p.1 p.2).Nonempty + · simp only [cycleProposal,ite_eq_left h,Finset.sum_mul] + rw [Finset.sum_comm] + have hs (S : Finset E) : (∑ q, cycleTerm p q S*F q) = + if S ∈ discrepancyComponents p.1 p.2 then + F (cycleMove p S) / (discrepancyComponents p.1 p.2).card else 0 := by + by_cases hm : S ∈ discrepancyComponents p.1 p.2 + · simp only [cycleTerm,hm,true_and,ite_eq_left,ite_mul,zero_mul] + simp [div_eq_mul_inv,mul_comm] + · simp [cycleTerm,hm] + simp_rw [hs] + rw [← Finset.sum_filter] + simp only [Finset.filter_mem_eq_inter,Finset.univ_inter,Finset.sum_div] + · simp [cycleProposal,h] + + + + +omit [DecidableEq V] in +theorem cycleProposal_dirichlet (w : E → ℝ) (f g : Finset E → ℝ) : + (∑ A : PM inc, ∑ B : PM inc, gibbs w A*gibbs w B * + (∑ q : PM inc × PM inc, cycleProposal (A,B) q * + ((f A.val+g B.val)-(f q.1.val+g q.2.val))^2)) / 6 = + cycleDirichlet (inc := inc) w f g := by + classical + unfold cycleDirichlet + rw [Finset.sum_div] + apply Finset.sum_congr rfl; intro A _ + rw [Finset.sum_div] + apply Finset.sum_congr rfl; intro B _ + rw [mul_div_assoc] + congr 1 + rw [cycleProposal_expectation] + by_cases h : (discrepancyComponents A B).Nonempty + · rw [ite_eq_left h,div_div] + rw [Finset.sum_div] + apply Finset.sum_congr rfl; intro S hS + have hc : S ∈ components (inc := inc) (A.val ∪ B.val) := (Finset.mem_filter.mp hS).1 + rw [(cycleMove_val (A,B) S hc).1,(cycleMove_val (A,B) S hc).2] + dsimp only [cycleSquare] + rw [mul_comm ((discrepancyComponents A B).card:ℝ)] + · have he := Finset.not_nonempty_iff_eq_empty.mp h + simp [he] + +end + +section + +open Finset + +variable {V L : Type*} [Fintype V] [DecidableEq V] [Fintype L] [DecidableEq L] + +variable {bags : V → Finset L} + +noncomputable local instance tierClampBagEdgeFintype : Fintype (BagEdge bags) := + Fintype.ofFinite _ + +namespace BagEdge + +noncomputable def parallels (e : BagEdge bags) : Finset (BagEdge bags) := by + classical + exact Finset.univ.filter (fun f => f.val.val.1 = e.val.val.1) + +omit [DecidableEq L] in +lemma parallels_card_le (hb : ∀ v, (bags v).card ≤ 2) (e : BagEdge bags) : + (parallels e).card ≤ 2 := by + classical + obtain ⟨v,hv⟩ := e.exists_incident + let colorMap : ↥(parallels e) → ↥(bags v) := fun f => ⟨f.val.color, by + apply f.val.color_mem + change v ∈ f.val.val.val.1 + rw [(Finset.mem_filter.mp f.property).2] + exact hv⟩ + have hinj : Function.Injective colorMap := by + intro f g h + apply Subtype.ext; apply Subtype.ext; apply Subtype.ext + apply Prod.ext + · exact (Finset.mem_filter.mp f.property).2.trans (Finset.mem_filter.mp g.property).2.symm + · exact congrArg Subtype.val h + have hc : (parallels e).card ≤ (bags v).card := by + simpa only [Fintype.card_coe] using Fintype.card_le_of_injective colorMap hinj + exact hc.trans (hb v) + +end BagEdge + +end + +open Finset + +variable {V E : Type*} [Fintype V] [DecidableEq V] [Fintype E] [DecidableEq E] + +variable (ends : E → Sym2 V) + +omit [DecidableEq V] [Fintype E] in +lemma ColorChange.symm {A B : PM (fun e v => v ∈ ends e)} (h : ColorChange ends A B) : + ColorChange ends B A := by + obtain ⟨e,f,R,hef,hA,hB⟩ := h + exact ⟨f,e,R,hef.symm,hB,hA⟩ + +omit [DecidableEq V] [Fintype E] in +lemma ColorChange.edit {A B : PM (fun e v => v ∈ ends e)} (h : ColorChange ends A B) : + ∃ e ∈ A.val, ∃ f, ends f = ends e ∧ B.val = insert f (A.val.erase e) := by + classical + obtain ⟨e,f,R,hef,hA,hB⟩ := h + have he : e ∈ A.val := by rw [hA]; simp + refine ⟨e,he,f,hef.symm,?_⟩ + by_cases h : e = f + · subst f + rw [Finset.insert_erase he] + exact hB.trans hA.symm + · obtain ⟨v,hv⟩ : ∃ v, v ∈ ends e := Sym2.inductionOn (ends e) (fun u v => ⟨u,by simp⟩) + have hr : e ∉ R := by + intro hr + exact h (B.property.unique (Finset.mem_univ v) (by rw [hB]; simp [hr]) hv + (by rw [hB]; simp) (hef ▸ hv)) + rw [hA,hB] + ext a + simp only [Finset.mem_union,Finset.mem_singleton,Finset.mem_insert,Finset.mem_erase] + by_cases ha : a = e + · subst a; simp [hr,h] + · tauto + +lemma colorDestinations_card_bound + (hpar : ∀ e, (Finset.univ.filter (fun f => ends f = ends e)).card ≤ 2) + (A : PM (fun e v => v ∈ ends e)) : (colorDestinations ends A).card ≤ 2*A.val.card := by + classical + let options (e : E) : Finset (Finset E) := + (Finset.univ.filter (fun f => ends f = ends e)).image (fun f => insert f (A.val.erase e)) + have hsub : (colorDestinations ends A).image Subtype.val ⊆ A.val.biUnion options := by + intro B hB + obtain ⟨C,hC,hCB⟩ := Finset.mem_image.mp hB + rw [← hCB] + obtain ⟨e,he,f,hf,hval⟩ := ColorChange.edit ends ((Finset.mem_filter.mp hC).2) + apply Finset.mem_biUnion.mpr + exact ⟨e,he,Finset.mem_image.mpr ⟨f,Finset.mem_filter.mpr ⟨Finset.mem_univ _,hf⟩,hval.symm⟩⟩ + have hi : (colorDestinations ends A).card = ((colorDestinations ends A).image Subtype.val).card := by + symm; exact Finset.card_image_of_injective _ Subtype.val_injective + calc + _ = _ := hi + _ ≤ (A.val.biUnion options).card := Finset.card_le_card hsub + _ ≤ ∑ e ∈ A.val, (options e).card := Finset.card_biUnion_le + _ ≤ ∑ e ∈ A.val, 2 := Finset.sum_le_sum (fun e _ => (Finset.card_image_le).trans (hpar e)) + _ = _ := by simp [Nat.mul_comm] + +end MatchingFPRAS.Transport + +end OAI diff --git a/lean/OAI/Combinatorics/MatchingCount/Sampling/TreeCategorical.lean b/lean/OAI/Combinatorics/MatchingCount/Sampling/TreeCategorical.lean new file mode 100644 index 0000000000000000000000000000000000000000..3fa40e56e4b6aee4b3829e2d74da7e1405975b42 --- /dev/null +++ b/lean/OAI/Combinatorics/MatchingCount/Sampling/TreeCategorical.lean @@ -0,0 +1,142 @@ +import Mathlib +import OAI.Combinatorics.MatchingCount.Sampling.TreeDPCounts +import OAI.Combinatorics.MatchingCount.Arithmetic.TreeFraction +import OAI.Combinatorics.MatchingCount.Machines.TreeListMore + +namespace OAI + +namespace MatchingFPRAS.TreeFraction +open TreeTyped + +def sum (xs : List Fraction) : Fraction := xs.foldl (fun a b=>add (b,a)) (0,1) +def sumRealizer : Realizer sum := + (composition (pair (identity (A:=List Fraction)) (constant (0,1))) (fold addRealizer)).congr (fun _=>rfl) + +lemma fold_den (xs : List Fraction) (a : Fraction) (ha : 0add (b,a)) a).2 := by + induction xs generalizing a with + | nil => exact ha + | cons _ _ ih => exact ih _ (normalize_den_pos _) +lemma fold_val (xs : List Fraction) (a : Fraction) (ha : 0add (b,a)) a)=val a+(xs.map val).sum := by + induction xs generalizing a with + | nil => simp + | cons b bs ih => + have hab : 0<(add (b,a)).2 := normalize_den_pos _ + rw [List.foldl_cons,ih _ hab (fun c hc=>hx c (by simp [hc])), + add_val b a (Nat.ne_of_gt (hx b (by simp))) (Nat.ne_of_gt ha)] + simp only [List.map_cons,List.sum_cons] + ring +lemma sum_den (xs : List Fraction) : 0<(sum xs).2 := fold_den xs (0,1) (by decide) +lemma sum_val (xs : List Fraction) (hx : ∀ b∈xs,0rfl) +lemma cumulativeFraction_val {r : ℕ} (p : Fin r → ℚ) (hp : ∀ i,0≤p i) (n : ℕ) : + val (cumulativeFraction (List.ofFn (fun i=>repr (p i)),n))=FiniteChoice.cumulative p n := by + rw [cumulativeFraction,sum_val] + · simp only [List.map_take,List.map_ofFn,Function.comp_apply,val_repr (hp _),List.sum_take_ofFn, + FiniteChoice.cumulative,Finset.sum_filter] + · intro b hb + obtain ⟨i,hi⟩ := List.mem_ofFn.mp (List.mem_of_mem_take hb) + subst b + exact (p i).pos + +end MatchingFPRAS.TreeFraction + +namespace MatchingFPRAS.TreeTyped + +def bitValue : Realizer StackAddition.value := + (composition (composition (pair (reverse (A:=Bool)) (constant (1,0))) + (fold mulStepRealizer)) second).congr (by + intro bs + change (bs.reverse.foldl (fun z b=>mulStep (b,z)) (1,0)).2=_ + rw [mulStep_fold] + simp) + +def bitDenominator (bs : List Bool) : ℕ := bs.foldl (fun a _=>2*a) 1 +lemma bitDenominator_eq (bs : List Bool) : bitDenominator bs=2^bs.length := by + have h : ∀ a,bs.foldl (fun a _=>2*a) a=a*2^bs.length := by + induction bs with + | nil => intro a; simp + | cons _ _ ih => intro a; simp only [List.foldl_cons,ih,List.length_cons,pow_succ]; ring + simpa [bitDenominator] using h 1 + +def bitDenominatorRealizer : Realizer bitDenominator := + (composition (pair (identity (A:=List Bool)) (constant 1)) + (fold (composition second double))).congr (fun _=>rfl) +end MatchingFPRAS.TreeTyped + +namespace MatchingFPRAS.ExecutableChoice +open TreeTyped TreeFraction + +def predicate (x : (List Fraction×Fraction)×ℕ) : Bool := + TreeFraction.less (x.1.2,cumulativeFraction (x.1.1,x.2+1)) +def predicateRealizer : Realizer predicate := by + let C : Realizer (fun x : (List Fraction×Fraction)×ℕ=>cumulativeFraction (x.1.1,x.2+1)) := + (composition (pair first.fst (composition second successor)) cumulativeFractionRealizer).congr (fun _=>rfl) + exact (composition (pair first.snd C) lessRealizer).congr (fun _=>rfl) + +def choose (x : List Fraction×Fraction) : ℕ := + listMin ((List.range x.1.length).filter (fun i=>predicate (x,i)),x.1.length) + +def chooseRealizer : Realizer choose := by + let rs : Realizer (fun x : List Fraction×Fraction=>List.range x.1.length) := + composition (composition first listLength) range + let good := composition (pair identity rs) (filterWith predicateRealizer) + exact (composition (pair good (composition first listLength)) listMinRealizer).congr (fun _=>rfl) + +lemma choose_eq {r K : ℕ} (p : Fin r → ℚ) (hp : ∀ i,0≤p i) + (hs : ∑ i,p i=1) (hK : 0repr (p i)),(J.val,K))=(FiniteChoice.choose p hs hK J).val := by + let j := FiniteChoice.choose p hs hK J + have hpred (i : ℕ) : predicate ((List.ofFn (fun i=>repr (p i)),(J.val,K)),i)= + decide ((J.val:ℚ)/Krepr (p i)),i+1)) hK (sum_den _),cumulativeFraction_val p hp] + rfl + unfold choose + simp only [List.length_ofFn] + apply le_antisymm + · apply listMin_le + simp only [List.mem_filter,List.mem_range,hpred,decide_eq_true_eq] + exact ⟨j.isLt,FiniteChoice.choose_upper p hs hK J⟩ + · apply le_listMin j.isLt.le + intro i hi + simp only [List.mem_filter,List.mem_range,hpred,decide_eq_true_eq] at hi + exact FiniteChoice.choose_le p hs hK J ⟨i,hi.1⟩ hi.2 + +def chooseBits (x : List Fraction×List Bool) : ℕ := + choose (x.1,(StackAddition.value x.2,bitDenominator x.2)) +def chooseBitsRealizer : Realizer chooseBits := + composition (pair first (pair (composition second bitValue) (composition second bitDenominatorRealizer))) + chooseRealizer + +lemma chooseBits_eq {r k : ℕ} (p : Fin r → ℚ) (hp : ∀ i,0≤p i) + (hs : ∑ i,p i=1) (bits : Fin k → Bool) : + chooseBits (List.ofFn (fun i=>repr (p i)),List.ofFn bits)= + (FiniteChoice.chooseBits p hs k bits).val := by + have hv' (k : ℕ) (bits : Fin k → Bool) : + StackAddition.value (List.ofFn bits)=∑ i, (if bits i then 1 else 0)*2^i.val := by + induction k with + | zero => simp [StackAddition.value] + | succ k ih => + rw [List.ofFn_succ,StackAddition.value,ih,Fin.sum_univ_succ] + simp only [Fin.val_zero,pow_zero,Nat.mul_one,Fin.val_succ,pow_succ] + rw [Finset.mul_sum] + have hn : (bits 0).toNat=(if bits 0 then 1 else 0) := by cases bits 0 <;> rfl + rw [hn] + congr 1 + apply Finset.sum_congr rfl + intro i _ + ring + have hv : StackAddition.value (List.ofFn bits)=(FiniteChoice.tapeIndex k bits).val := by + rw [FiniteChoice.tapeIndex_value,hv'] + rw [chooseBits,bitDenominator_eq,List.length_ofFn,hv] + exact choose_eq p hp hs (by positivity) (FiniteChoice.tapeIndex k bits) +end MatchingFPRAS.ExecutableChoice + +end OAI diff --git a/lean/OAI/Combinatorics/MatchingCount/Sampling/TreeCategoricalValues.lean b/lean/OAI/Combinatorics/MatchingCount/Sampling/TreeCategoricalValues.lean new file mode 100644 index 0000000000000000000000000000000000000000..d6aa386cca63c4a09c862d6596b975a8b721609c --- /dev/null +++ b/lean/OAI/Combinatorics/MatchingCount/Sampling/TreeCategoricalValues.lean @@ -0,0 +1,65 @@ +import Mathlib +import OAI.Combinatorics.MatchingCount.Sampling.TreeCategorical + +namespace OAI + +namespace MatchingFPRAS.TreeFraction +lemma cumulativeFraction_val_ofFn {r : ℕ} (q : Fin r → Fraction) (hq : ∀ i,0<(q i).2) (n : ℕ) : + val (cumulativeFraction (List.ofFn q,n))=FiniteChoice.cumulative (fun i=>val (q i)) n := by + rw [cumulativeFraction,sum_val] + · simp only [List.map_take,List.map_ofFn,Function.comp_apply,List.sum_take_ofFn, + FiniteChoice.cumulative,Finset.sum_filter] + · intro b hb + obtain ⟨i,hi⟩ := List.mem_ofFn.mp (List.mem_of_mem_take hb) + subst b + exact hq i +end MatchingFPRAS.TreeFraction + +namespace MatchingFPRAS.ExecutableChoice +open TreeTyped TreeFraction + +lemma choose_values {r K : ℕ} (q : Fin r → Fraction) (hq : ∀ i,0<(q i).2) + (hs : ∑ i,val (q i)=1) (hK : 0val (q i)) hs hK J).val := by + let j := FiniteChoice.choose (fun i=>val (q i)) hs hK J + have hpred (i : ℕ) : predicate ((List.ofFn q,(J.val,K)),i)= + decide ((J.val:ℚ)/Kval (q i)) (i+1)) := by + rw [predicate,less_val (J.val,K) (cumulativeFraction (List.ofFn q,i+1)) hK (sum_den _),cumulativeFraction_val_ofFn q hq] + rfl + unfold choose + simp only [List.length_ofFn] + apply le_antisymm + · apply listMin_le + simp only [List.mem_filter,List.mem_range,hpred,decide_eq_true_eq] + exact ⟨j.isLt,FiniteChoice.choose_upper _ hs hK J⟩ + · apply le_listMin j.isLt.le + intro i hi + simp only [List.mem_filter,List.mem_range,hpred,decide_eq_true_eq] at hi + exact FiniteChoice.choose_le _ hs hK J ⟨i,hi.1⟩ hi.2 + +lemma bitValue_ofFn (k : ℕ) (bits : Fin k → Bool) : + StackAddition.value (List.ofFn bits)=(FiniteChoice.tapeIndex k bits).val := by + have hv' (k : ℕ) (bits : Fin k → Bool) : + StackAddition.value (List.ofFn bits)=∑ i, (if bits i then 1 else 0)*2^i.val := by + induction k with + | zero => simp [StackAddition.value] + | succ k ih => + rw [List.ofFn_succ,StackAddition.value,ih,Fin.sum_univ_succ] + simp only [Fin.val_zero,pow_zero,Nat.mul_one,Fin.val_succ,pow_succ] + rw [Finset.mul_sum] + rw [Bool.toNat,Bool.cond_eq_ite] + congr 1 + apply Finset.sum_congr rfl + intro i _ + ring + rw [FiniteChoice.tapeIndex_value,hv'] + +lemma chooseBits_values {r k : ℕ} (q : Fin r → Fraction) (hq : ∀ i,0<(q i).2) + (hs : ∑ i,val (q i)=1) (bits : Fin k → Bool) : + chooseBits (List.ofFn q,List.ofFn bits)= + (FiniteChoice.chooseBits (fun i=>val (q i)) hs k bits).val := by + rw [chooseBits,bitDenominator_eq,List.length_ofFn,bitValue_ofFn] + exact choose_values q hq hs (by positivity) (FiniteChoice.tapeIndex k bits) +end MatchingFPRAS.ExecutableChoice + +end OAI diff --git a/lean/OAI/Combinatorics/MatchingCount/Sampling/TreeClippedDP.lean b/lean/OAI/Combinatorics/MatchingCount/Sampling/TreeClippedDP.lean new file mode 100644 index 0000000000000000000000000000000000000000..a6a2d3da41acdea6cbeec5487dff0c42fd806f8e --- /dev/null +++ b/lean/OAI/Combinatorics/MatchingCount/Sampling/TreeClippedDP.lean @@ -0,0 +1,129 @@ +import Mathlib +import OAI.Combinatorics.MatchingCount.Sampling.TreeDPCount +import OAI.Combinatorics.MatchingCount.Sampling.TreeFastDPEntry +import OAI.Combinatorics.MatchingCount.Complexity.TreePolynomialGrid + +namespace OAI + +namespace MatchingFPRAS.ExecutableDP +open TreeTyped Polynomial + +def nVertices (o : CountInput) : ℕ := o.1.1.length +def nLabels (o : CountInput) : ℕ := o.1.2.length +def nPlan (o : CountInput) : ℕ := o.2.length +def BInitial (o : CountInput) : ℕ := nVertices o*nLabels o +def capBits (o : CountInput) : ℕ := nVertices o*nPlan o+(BInitial o)^2*nLabels o+1 + +def nVerticesRealizer : Realizer nVertices := composition first.fst listLength +def nLabelsRealizer : Realizer nLabels := composition first.snd listLength +def nPlanRealizer : Realizer nPlan := composition second listLength +def BInitialRealizer : Realizer BInitial := composition (pair nVerticesRealizer nLabelsRealizer) multiply +def capBitsRealizer : Realizer capBits := by + let b:= BInitialRealizer + let q:= composition (pair b b) multiply + let v:= composition (pair q nLabelsRealizer) multiply + let w:= composition (pair nVerticesRealizer nPlanRealizer) multiply + exact (composition (composition (pair w v) add) successor).congr (by intro o; simp only [capBits,pow_two]; rfl) +lemma polynomial_nVertices : PolynomialTime nVerticesRealizer := by unfold nVerticesRealizer; exact polynomial_composition (polynomial_fst polynomial_first) polynomial_listLength +lemma polynomial_nLabels : PolynomialTime nLabelsRealizer := by unfold nLabelsRealizer; exact polynomial_composition (polynomial_snd polynomial_first) polynomial_listLength +lemma polynomial_nPlan : PolynomialTime nPlanRealizer := by unfold nPlanRealizer; exact polynomial_composition polynomial_second polynomial_listLength +lemma polynomial_BInitial : PolynomialTime BInitialRealizer := + polynomial_composition (polynomial_pair polynomial_nVertices polynomial_nLabels) polynomial_multiply +lemma polynomial_capBits : PolynomialTime capBitsRealizer := by + unfold capBitsRealizer + dsimp only + apply polynomial_congr + apply polynomial_composition _ polynomial_successor + apply polynomial_composition _ polynomial_add + have := polynomial_BInitial + have := polynomial_nVertices + have := polynomial_nLabels + have := polynomial_nPlan + tree_poly +lemma input_lengths (o : CountInput) : nVertices o≤weight o ∧ nLabels o≤weight o ∧ nPlan o≤weight o := by + refine ⟨(list_length_le_weight _).trans ((weight_fst o.1).trans (weight_fst o)), + (list_length_le_weight _).trans ((weight_snd o.1).trans (weight_fst o)), + (list_length_le_weight _).trans (weight_snd o)⟩ +lemma BInitial_bound (o : CountInput) : BInitial o≤(weight o)^2 := by + obtain ⟨hn,hm,_⟩:=input_lengths o + exact (Nat.mul_le_mul hn hm).trans_eq (pow_two _).symm +lemma capBits_bound (o : CountInput) : capBits o≤(weight o)^2+(weight o)^5+1 := by + obtain ⟨hn,hm,hL⟩:=input_lengths o + have hB:=BInitial_bound o + have h1:=Nat.mul_le_mul hn hL + have h2:=Nat.mul_le_mul (Nat.pow_le_pow_left hB 2) hm + calc + _ ≤ weight o*weight o+((weight o)^2)^2*weight o+1 := by unfold capBits; omega + _ = _ := by ring + +def initialEntry (x : CountInput×(ℕ×ℕ)) : ℕ := UnitRefresh.pairingCount (min x.2.2 (BInitial x.1)) +def initialEntryRealizer : Realizer initialEntry := + composition (composition (pair second.snd (composition first BInitialRealizer)) minNat) pairingNumber +lemma polynomial_initialEntry : PolynomialTime initialEntryRealizer := by + unfold initialEntryRealizer + refine polynomial_boundedPairingNumber ?_ (X^2) ?_ + · apply polynomial_composition _ polynomial_minNat + apply polynomial_pair (polynomial_snd polynomial_second) (polynomial_composition polynomial_first polynomial_BInitial) + · intro x + simp only [Polynomial.eval_pow,Polynomial.eval_X] + exact (min_le_right _ _).trans ((BInitial_bound x.1).trans (Nat.pow_le_pow_left (weight_fst x) 2)) +def initialFast : Realizer (fun o : CountInput=>initial (nLabels o,BInitial o)) := + (grid nLabelsRealizer BInitialRealizer initialEntryRealizer).congr (by + intro o + unfold tabulate initial initialEntry + apply List.map_congr_left + intro a _row_mem + apply List.map_congr_left + intro r hr + have hh : r≤BInitial o := by have :=List.mem_range.mp hr; dsimp only at this; omega + simp only [Nat.min_eq_left hh]) +lemma polynomial_initialFast : PolynomialTime initialFast := by + unfold initialFast + apply polynomial_congr + exact polynomial_grid polynomial_nLabels polynomial_BInitial polynomial_initialEntry X (X^2) + (fun o=>by simpa using (input_lengths o).2.1) (fun o=>by simpa using BInitial_bound o) + +abbrev UpdateInput := (CountInput×RawCtx)×ℕ +def updateRows (x : UpdateInput) := nLabels x.1.1 +def updateColumns (x : UpdateInput) := nVertices x.1.1*min x.2 (nPlan x.1.1) +def updateRowsRealizer : Realizer updateRows := composition first.fst nLabelsRealizer +def updateColumnsRealizer : Realizer updateColumns := + composition (pair (composition first.fst nVerticesRealizer) + (composition (pair second (composition first.fst nPlanRealizer)) minNat)) multiply +lemma polynomial_updateRows : PolynomialTime updateRowsRealizer := + polynomial_composition (polynomial_fst polynomial_first) polynomial_nLabels +lemma polynomial_updateColumns : PolynomialTime updateColumnsRealizer := by + unfold updateColumnsRealizer + exact polynomial_composition (polynomial_pair + (polynomial_composition (polynomial_fst polynomial_first) polynomial_nVertices) + (polynomial_composition (polynomial_pair polynomial_second + (polynomial_composition (polynomial_fst polynomial_first) polynomial_nPlan)) polynomial_minNat)) polynomial_multiply +lemma update_dimensions (x : UpdateInput) : updateRows x≤weight x ∧ updateColumns x≤(weight x)^2 := by + have hwo:weight x.1.1≤weight x := (weight_fst x.1).trans (weight_fst x) + obtain ⟨hn,hm,hL⟩:=input_lengths x.1.1 + refine ⟨hm.trans hwo,?_⟩ + exact (Nat.mul_le_mul (hn.trans hwo) ((min_le_right _ _).trans (hL.trans hwo))).trans_eq (pow_two _).symm + +def cappedEntry (x : UpdateInput×(ℕ×ℕ)) : ℕ := clip (capBits x.1.1.1,rawEntry (x.1.1.2,x.2)) +def cappedEntryRealizer : Realizer cappedEntry := + (composition (pair (composition first.fst.fst capBitsRealizer) + (composition (pair first.fst.snd second) rawEntryRealizer)) clipRealizer).congr (fun _=>rfl) +lemma polynomial_cappedEntry : PolynomialTime cappedEntryRealizer := by + unfold cappedEntryRealizer Realizer.fst Realizer.snd + apply polynomial_congr + apply polynomial_composition _ polynomial_clip + apply polynomial_pair + · apply polynomial_composition _ polynomial_capBits + tree_poly + · apply polynomial_composition _ polynomial_rawEntry + tree_poly + +def cappedUpdate (x : UpdateInput) : Table := tabulate cappedEntry (x,(updateRows x,updateColumns x)) +def cappedUpdateRealizer : Realizer cappedUpdate := grid updateRowsRealizer updateColumnsRealizer cappedEntryRealizer +lemma polynomial_cappedUpdate : PolynomialTime cappedUpdateRealizer := + polynomial_grid polynomial_updateRows polynomial_updateColumns polynomial_cappedEntry X (X^2) + (fun x=>by simpa using (update_dimensions x).1) (fun x=>by simpa using (update_dimensions x).2) + +end MatchingFPRAS.ExecutableDP + +end OAI diff --git a/lean/OAI/Combinatorics/MatchingCount/Sampling/TreeDPCount.lean b/lean/OAI/Combinatorics/MatchingCount/Sampling/TreeDPCount.lean new file mode 100644 index 0000000000000000000000000000000000000000..f1bc274985e290dc339ad12be0cb2c3e18f6a772 --- /dev/null +++ b/lean/OAI/Combinatorics/MatchingCount/Sampling/TreeDPCount.lean @@ -0,0 +1,79 @@ +import Mathlib +import OAI.Combinatorics.MatchingCount.Sampling.TreeDPProgram + +namespace OAI + +namespace MatchingFPRAS.ExecutableDP +open TreeTyped + +def initial (x : ℕ×ℕ) : Table := + tabulate (fun ar : ℕ×(ℕ×ℕ)=>UnitRefresh.pairingCount ar.2.2) (0,x) + +def initialRealizer : Realizer initial := + composition (pair (constant 0) identity) + (tabulateRealizer (composition second.snd pairingNumber)) + +lemma initial_eq (m B : ℕ) : initial (m,B)=UnitRefresh.Materialized.initial m B := by + exact tabulate_materialized (fun x : ℕ×(ℕ×ℕ)=>UnitRefresh.pairingCount x.2.2) 0 m B + +def finish (x : Table×ℕ) : ℕ := ((List.range x.2).map fun a=>read (x.1,(a,0))).prod + +def finishRealizer : Realizer finish := + composition (composition (pair first (composition second range)) + (mapWith (composition (pair first (pair second (constant 0))) readRealizer))) listProd + +lemma map_range_ofFn {A : Type} (f : ℕ → A) (n : ℕ) : + (List.range n).map f=List.ofFn (fun i : Fin n=>f i.val) := by + apply List.ext_getElem + · simp + · intro i hi hi'; simp only [List.getElem_map,List.getElem_range,List.getElem_ofFn] + +lemma finish_eq (t : Table) (m : ℕ) : + finish (t,m)=∏ a : Fin m,UnitRefresh.Materialized.read t a.val 0 := by + rw [finish,map_range_ofFn,List.prod_ofFn] + rfl + +abbrev CountInput := (Bags×Parents)×List ℕ + +def count (x : CountInput) : ℕ := + let n:=x.1.1.length + let m:=x.1.2.length + finish (run ((n,(m,x.1.2)),(x.2,(x.1.1,initial (m,n*m)))),m) + +def countRealizer : Realizer count := by + let bs : Realizer (fun x : CountInput=>x.1.1) := first.fst + let ps : Realizer (fun x : CountInput=>x.1.2) := first.snd + let ls : Realizer (fun x : CountInput=>x.2) := second + let n := composition bs listLength + let m := composition ps listLength + let B := composition (pair n m) multiply + let t := composition (pair m B) initialRealizer + let p := pair n (pair m ps) + let table := composition (pair p (pair ls (pair bs t))) runRealizer + exact (composition (pair table m) finishRealizer).congr (fun _=>rfl) + +lemma count_eq {V : Type} [Fintype V] [DecidableEq V] {m : ℕ} + (bags : V → Finset (Fin m)) (parent : Fin m → Option (Fin m)) (ls : List (Fin m)) : + count ((activeRep bags Finset.univ,parentRep parent),ls.map Fin.val)= + UnitRefresh.Materialized.count bags parent ls := by + unfold count + rw [show (activeRep bags Finset.univ).length=Fintype.card V by simp [activeRep]] + rw [parentRep_length] + dsimp only + rw [initial_eq] + unfold run + rw [run_eq bags parent ls Finset.univ _ _ (List.Perm.refl _),finish_eq] + rfl + +theorem count_coloredPairings {V : Type} [Fintype V] [DecidableEq V] {m : ℕ} + (bags : V → Finset (Fin m)) (rank : Fin m → ℕ) (parent : Fin m → Option (Fin m)) + (hb : UnitRefresh.RankedBags bags rank parent) (hne : ∀ x,(bags x).Nonempty) + (hp : ∀ l p,parent l=some p → rank px.2.filter fun b=>f (x.1,b)) := + (composition (composition (mapWith (pair second F)) (filter second)) (map first)).congr (by + intro x + simp only [Function.comp_apply,List.filter_map,List.map_map] + simp [Function.comp_def]) +end MatchingFPRAS.TreeTyped + +namespace MatchingFPRAS.ExecutableDP +open TreeTyped + +abbrev Bag := List ℕ +abbrev Bags := List Bag +abbrev Parents := List (Bool×ℕ) + +def privateFlag (x : ℕ×Bag) : Bool := decide (x.2.length=1) && decide (x.1∈x.2) +def sharedFlag (x : ℕ×Bag) : Bool := decide (x.1∈x.2) && !(privateFlag x) +def totalFlag (x : ℕ×Bag) : Bool := decide (x.1∈x.2) +def privateNumber (bs : Bags) (l : ℕ) := (bs.filter fun b=>privateFlag (l,b)).length +def sharedNumber (bs : Bags) (l : ℕ) := (bs.filter fun b=>sharedFlag (l,b)).length +def totalNumber (bs : Bags) (l : ℕ) := (bs.filter fun b=>totalFlag (l,b)).length +def trim (bs : Bags) (l : ℕ) := bs.filter fun b=>!(totalFlag (l,b)) + +def totalFlagRealizer : Realizer totalFlag := composition (pair second first) membership +def privateFlagRealizer : Realizer privateFlag := composition + (pair (composition (pair (composition second listLength) (constant 1)) natEqual) totalFlagRealizer) boolAnd +def sharedFlagRealizer : Realizer sharedFlag := composition + (pair totalFlagRealizer (composition privateFlagRealizer boolNot)) boolAnd + +def privateNumberRealizer : Realizer (fun x : Bags×ℕ=>privateNumber x.1 x.2) := + (composition (pair second first) (countWith privateFlagRealizer)).congr (fun _=>rfl) +def sharedNumberRealizer : Realizer (fun x : Bags×ℕ=>sharedNumber x.1 x.2) := + (composition (pair second first) (countWith sharedFlagRealizer)).congr (fun _=>rfl) +def totalNumberRealizer : Realizer (fun x : Bags×ℕ=>totalNumber x.1 x.2) := + (composition (pair second first) (countWith totalFlagRealizer)).congr (fun _=>rfl) +def trimRealizer : Realizer (fun x : Bags×ℕ=>trim x.1 x.2) := + composition (pair second first) (filterWith (composition totalFlagRealizer boolNot)) + +def context (x : (Bags×Parents)×(ℕ×Table)) : EntryCtx := + (x.1.2.getD x.2.1 (false,0), + (x.2.1,(x.2.2,(privateNumber x.1.1 x.2.1, + (sharedNumber x.1.1 x.2.1,totalNumber x.1.1 x.2.1))))) +def contextRealizer : Realizer context := by + let bl : Realizer (fun x : (Bags×Parents)×(ℕ×Table)=>(x.1.1,x.2.1)) := pair first.fst second.fst + let p := composition bl privateNumberRealizer + let q := composition bl sharedNumberRealizer + let r := composition bl totalNumberRealizer + exact (pair (composition (pair first.snd second.fst) (getD (false,0))) + (pair second.fst (pair second.snd (pair p (pair q r))))).congr (fun _=>rfl) + +variable {V : Type} [Fintype V] [DecidableEq V] {m : ℕ} +noncomputable def bagRep (b : Finset (Fin m)) : Bag := b.toList.map Fin.val + +noncomputable def activeRep (bags : V → Finset (Fin m)) (R : Finset V) : Bags := R.toList.map (bagRep ∘ bags) + +@[simp] lemma mem_bagRep (b : Finset (Fin m)) (l : Fin m) : l.val∈bagRep b ↔ l∈b := by + simp [bagRep,Fin.val_inj] +@[simp] lemma length_bagRep (b : Finset (Fin m)) : (bagRep b).length=b.card := by + simp [bagRep] +lemma card_one_mem (b : Finset (Fin m)) (l : Fin m) : b.card=1 ∧ l∈b ↔ b={l} := by + constructor + · rintro ⟨h,hl⟩ + obtain ⟨a,ha⟩ := Finset.card_eq_one.mp h + have e : l=a := by simpa [ha] using hl + simpa [e] using ha + · rintro rfl; simp +@[simp] lemma privateFlag_bagRep (b : Finset (Fin m)) (l : Fin m) : + privateFlag (l.val,bagRep b)=decide (b={l}) := by + apply Bool.eq_iff_iff.mpr + simp [privateFlag,card_one_mem] +@[simp] lemma sharedFlag_bagRep (b : Finset (Fin m)) (l : Fin m) : + sharedFlag (l.val,bagRep b)=decide (l∈b ∧ b≠{l}) := by + apply Bool.eq_iff_iff.mpr + simp [sharedFlag,privateFlag_bagRep] +@[simp] lemma totalFlag_bagRep (b : Finset (Fin m)) (l : Fin m) : + totalFlag (l.val,bagRep b)=decide (l∈b) := by simp [totalFlag] + +omit [Fintype V] [DecidableEq V] in +lemma filter_length_toList [Fintype V] [DecidableEq V] + (R : Finset V) (P : V → Prop) [DecidablePred P] : + (R.toList.filter fun x=>decide (P x)).length=(R.filter P).card := by + rw [←List.toFinset_card_of_nodup ((Finset.nodup_toList R).filter _)] + simp + +@[simp] lemma privateNumber_activeRep (bags : V → Finset (Fin m)) (R : Finset V) (l : Fin m) : + privateNumber (activeRep bags R) l.val=UnitRefresh.privateCount bags R l := by + simp only [privateNumber,activeRep,List.filter_map,List.length_map,Function.comp_def,privateFlag_bagRep] + exact filter_length_toList R (fun x=>bags x={l}) +@[simp] lemma sharedNumber_activeRep (bags : V → Finset (Fin m)) (R : Finset V) (l : Fin m) : + sharedNumber (activeRep bags R) l.val=UnitRefresh.sharedCount bags R l := by + simp only [sharedNumber,activeRep,List.filter_map,List.length_map,Function.comp_def,sharedFlag_bagRep] + exact filter_length_toList R (fun x=>l∈bags x ∧ bags x≠{l}) +@[simp] lemma totalNumber_activeRep (bags : V → Finset (Fin m)) (R : Finset V) (l : Fin m) : + totalNumber (activeRep bags R) l.val=(R.filter fun x=>l∈bags x).card := by + simp only [totalNumber,activeRep,List.filter_map,List.length_map,Function.comp_def,totalFlag_bagRep] + exact filter_length_toList R (fun x=>l∈bags x) + +omit [Fintype V] in +lemma trim_activeRep (bags : V → Finset (Fin m)) (R : Finset V) (l : Fin m) : + (trim (activeRep bags R) l.val).Perm (activeRep bags (UnitRefresh.trim bags R l)) := by + unfold trim activeRep UnitRefresh.trim + rw [List.filter_map] + apply List.Perm.map + apply List.perm_of_nodup_nodup_toFinset_eq ((Finset.nodup_toList R).filter _) (Finset.nodup_toList _) + ext x + simp +end MatchingFPRAS.ExecutableDP + +end OAI diff --git a/lean/OAI/Combinatorics/MatchingCount/Sampling/TreeDPEntry.lean b/lean/OAI/Combinatorics/MatchingCount/Sampling/TreeDPEntry.lean new file mode 100644 index 0000000000000000000000000000000000000000..70dd90f363a9e7bda61f18e6e1e9cfc7980067f5 --- /dev/null +++ b/lean/OAI/Combinatorics/MatchingCount/Sampling/TreeDPEntry.lean @@ -0,0 +1,115 @@ +import Mathlib +import OAI.Combinatorics.MatchingCount.Machines.TreeNaturalComb +import OAI.Combinatorics.MatchingCount.Machines.TreePredicate + +namespace OAI + +namespace MatchingFPRAS.TreeTyped +variable {A B C : Type} [Codec A] [Codec B] [Codec C] +def Realizer.fst {f : A → B×C} (F : Realizer f) : Realizer (fun a=>(f a).1) := composition F first +def Realizer.snd {f : A → B×C} (F : Realizer f) : Realizer (fun a=>(f a).2) := composition F second +end MatchingFPRAS.TreeTyped + +namespace MatchingFPRAS.ExecutableDP +open TreeTyped + +abbrev Table := List (List ℕ) +def read (x : Table×(ℕ×ℕ)) : ℕ := (x.1.getD x.2.1 []).getD x.2.2 0 + +def readRealizer : Realizer read := + composition (pair (composition (pair first second.fst) (getD [])) second.snd) (getD 0) + +abbrev EntryCtx := (Bool×ℕ) × (ℕ × (Table × (ℕ × (ℕ × ℕ)))) +def term (x : (EntryCtx×ℕ)×ℕ) : ℕ := + let c := x.1.1 + let r := x.1.2 + let k := x.2 + c.2.2.2.2.1.choose k * read (c.2.2.1,(c.2.1,c.2.2.2.1+k)) * + read (c.2.2.1,(c.1.2,c.2.2.2.2.1-k+r)) + +def termRealizer : Realizer term := by + let c : Realizer (fun x : (EntryCtx×ℕ)×ℕ=>x.1.1) := first.fst + let r : Realizer (fun x : (EntryCtx×ℕ)×ℕ=>x.1.2) := first.snd + let k : Realizer (fun x : (EntryCtx×ℕ)×ℕ=>x.2) := second + let s := c.snd.snd.snd.snd.fst + let u := c.snd.snd.snd.fst + let t := c.snd.snd.fst + let l := c.snd.fst + let p := c.fst.snd + let ch := composition (pair s k) natChoose + let L := composition (pair t (pair l (composition (pair u k) add))) readRealizer + let R := composition (pair t (pair p (composition (pair (composition (pair s k) subtract) r) add))) readRealizer + exact composition (pair (composition (pair ch L) multiply) R) multiply + +def entry (x : EntryCtx×(ℕ×ℕ)) : ℕ := + let c:=x.1 + let a:=x.2.1 + let r:=x.2.2 + if c.1.1 then + if a=c.2.1 then 1 else if a=c.1.2 then + ((List.range (c.2.2.2.2.1+1)).map fun k=>term ((c,r),k)).sum + else read (c.2.2.1,(a,r)) + else if a=c.2.1 then read (c.2.2.1,(c.2.1,c.2.2.2.2.2)) + else read (c.2.2.1,(a,r)) + +def entryRealizer : Realizer entry := by + let c : Realizer (fun x : EntryCtx×(ℕ×ℕ)=>x.1) := first + let a : Realizer (fun x : EntryCtx×(ℕ×ℕ)=>x.2.1) := second.fst + let r : Realizer (fun x : EntryCtx×(ℕ×ℕ)=>x.2.2) := second.snd + let l := c.snd.fst + let rd := composition (pair c.snd.snd.fst (pair a r)) readRealizer + let al := composition (pair a l) natEqual + let ap := composition (pair a c.fst.snd) natEqual + let ks := composition (composition c.snd.snd.snd.snd.fst successor) range + let sm := composition (composition (pair (pair c r) ks) (mapWith termRealizer)) listSum + let rt := composition (pair c.snd.snd.fst (pair l c.snd.snd.snd.snd.snd)) readRealizer + exact (choose c.fst.fst (choose al (constant 1) (choose ap sm rd)) (choose al rt rd)).congr (by + intro x; simp only [entry,Function.comp_apply,decide_eq_true_eq]) + +variable {X Y : Type} [Codec X] [Codec Y] +def tabulate (f : X×(ℕ×ℕ) → Y) (x : X×(ℕ×ℕ)) : List (List Y) := + (List.range x.2.1).map fun a=>(List.range (x.2.2+1)).map fun r=>f (x.1,(a,r)) + +def tabulateRealizer {f : X×(ℕ×ℕ) → Y} (F : Realizer f) : Realizer (tabulate f) := by + let rowF : Realizer (fun x : (X×ℕ)×ℕ=>f (x.1.1,(x.1.2,x.2))) := + composition (pair first.fst (pair first.snd second)) F + let rows : Realizer (fun x : (X×ℕ)×ℕ=> + (List.range (x.1.2+1)).map fun r=>f (x.1.1,(x.2,r))) := + composition (pair (pair first.fst second) (composition (composition first.snd successor) range)) + (mapWith rowF) + exact composition (pair (pair first second.snd) (composition second.fst range)) (mapWith rows) + +def updateRealizer : Realizer (tabulate entry) := tabulateRealizer entryRealizer + +lemma read_eq (t : Table) (a r : ℕ) : read (t,(a,r))=UnitRefresh.Materialized.read t a r := rfl + +lemma entry_eq {V : Type} {m : ℕ} + (bags : V → Finset (Fin m)) (R : Finset V) (parent : Fin m → Option (Fin m)) + (l a : Fin m) (t : Table) (r : ℕ) : + entry (((match parent l with | none=>(false,0) | some p=>(true,p.val)), + (l.val,(t,(UnitRefresh.privateCount bags R l, + (UnitRefresh.sharedCount bags R l,(R.filter fun x=>l∈bags x).card))))),(a.val,r))= + UnitRefresh.Materialized.entry bags R parent l a t r := by + have he : (a.val=l.val) ↔ a=l := Fin.val_inj + cases hp : parent l with + | none => simp only [entry,UnitRefresh.Materialized.entry,hp,Bool.false_eq_true,↓reduceIte,he,read_eq] + | some p => + have he' : (a.val=p.val) ↔ a=p := Fin.val_inj + simp only [entry,UnitRefresh.Materialized.entry,hp,↓reduceIte,he,he'] + split_ifs <;> try rfl + +lemma tabulate_eq {m B : ℕ} (f : ℕ×ℕ → ℕ) : + (List.range m).map (fun a=>(List.range (B+1)).map fun r=>f (a,r))= + UnitRefresh.Materialized.tabulate m B (fun a r=>f (a.val,r)) := by + unfold UnitRefresh.Materialized.tabulate + apply List.ext_getElem + · simp + · intro i hi hi' + simp only [List.getElem_map,List.getElem_range,List.getElem_ofFn] + apply List.ext_getElem + · simp + · intro j hj hj' + simp only [List.getElem_map,List.getElem_range,List.getElem_ofFn] +end MatchingFPRAS.ExecutableDP + +end OAI diff --git a/lean/OAI/Combinatorics/MatchingCount/Sampling/TreeDPProgram.lean b/lean/OAI/Combinatorics/MatchingCount/Sampling/TreeDPProgram.lean new file mode 100644 index 0000000000000000000000000000000000000000..a747cfa46bcd93bb91e5db4b8ad391ba2552dd82 --- /dev/null +++ b/lean/OAI/Combinatorics/MatchingCount/Sampling/TreeDPProgram.lean @@ -0,0 +1,120 @@ +import Mathlib +import OAI.Combinatorics.MatchingCount.Sampling.TreeDPCounts + +namespace OAI + +namespace MatchingFPRAS.ExecutableDP +open TreeTyped + +abbrev Params := ℕ×(ℕ×Parents) +abbrev State := ℕ×(Bags×Table) + +def update (x : ((Bags×Parents)×(ℕ×Table))×(ℕ×ℕ)) : Table := + tabulate entry (context x.1,x.2) +def updateProgram : Realizer update := + composition (pair (composition first contextRealizer) second) updateRealizer + +def step (x : ℕ×(Params×State)) : Params×State := + let p:=x.2.1 + let st:=x.2.2 + let l:=x.1 + let rem:=st.1-1 + (p,(rem,(trim st.2.1 l, + update (((st.2.1,p.2.2),(l,st.2.2)),(p.2.1,p.1*rem))))) + +def stepRealizer : Realizer step := by + let p : Realizer (fun x : ℕ×(Params×State)=>x.2.1) := second.fst + let st : Realizer (fun x : ℕ×(Params×State)=>x.2.2) := second.snd + let l : Realizer (fun x : ℕ×(Params×State)=>x.1) := first + let rem := composition st.fst predecessor + let bs := composition (pair st.snd.fst l) trimRealizer + let B := composition (pair p.fst rem) multiply + let inp := pair (pair (pair st.snd.fst p.snd.snd) (pair l st.snd.snd)) (pair p.snd.fst B) + let tbl := composition inp updateProgram + exact (pair p (pair rem (pair bs tbl))).congr (fun _=>rfl) + +def runState (p : Params) : List ℕ → Bags → Table → Bags×Table + | [],bs,t => (bs,t) + | l::ls,bs,t => runState p ls (trim bs l) + (update (((bs,p.2.2),(l,t)),(p.2.1,p.1*ls.length))) + +def run (x : Params×(List ℕ×(Bags×Table))) : Table := (runState x.1 x.2.1 x.2.2.1 x.2.2.2).2 + +lemma step_fold (p : Params) (ls : List ℕ) (bs : Bags) (t : Table) : + ls.foldl (fun z l=>step (l,z)) (p,(ls.length,(bs,t)))= + (p,(0,runState p ls bs t)) := by + induction ls generalizing bs t with + | nil => rfl + | cons l ls ih => + simp only [List.foldl_cons,List.length_cons,step,Nat.add_sub_cancel] + exact ih _ _ + +def runRealizer : Realizer run := by + let init : Realizer (fun x : Params×(List ℕ×(Bags×Table))=> + (x.2.1,(x.1,(x.2.1.length,x.2.2)))) := + pair second.fst (pair first (pair (composition second.fst listLength) second.snd)) + exact (composition (composition init (fold stepRealizer)) second.snd.snd).congr (by + intro x + change ((x.2.1.foldl (fun z l=>step (l,z)) (x.1,(x.2.1.length,x.2.2))).2.2).2=_ + rw [step_fold] + rfl) + +lemma tabulate_materialized {X : Type} (f : X×(ℕ×ℕ) → ℕ) (x : X) (m B : ℕ) : + tabulate f (x,(m,B))=UnitRefresh.Materialized.tabulate m B (fun a r=>f (x,(a.val,r))) := + tabulate_eq (fun ar=>f (x,ar)) + +lemma update_eq {V : Type} [Fintype V] [DecidableEq V] {m : ℕ} + (bags : V → Finset (Fin m)) (R : Finset V) (parent : Fin m → Option (Fin m)) + (l : Fin m) (t : Table) (B : ℕ) (ps : Parents) + (hps : ps.getD l.val (false,0)=match parent l with | none=>(false,0) | some p=>(true,p.val)) : + update (((activeRep bags R,ps),(l.val,t)),(m,B))= + UnitRefresh.Materialized.update bags R parent l B t := by + unfold update context + simp only [hps,privateNumber_activeRep,sharedNumber_activeRep,totalNumber_activeRep] + rw [tabulate_materialized] + unfold UnitRefresh.Materialized.update + congr 1 + funext a r + exact entry_eq bags R parent l a t r + +lemma privateNumber_perm {a b : Bags} (h : a.Perm b) (l : ℕ) : privateNumber a l=privateNumber b l := + (h.filter _).length_eq +lemma sharedNumber_perm {a b : Bags} (h : a.Perm b) (l : ℕ) : sharedNumber a l=sharedNumber b l := + (h.filter _).length_eq +lemma totalNumber_perm {a b : Bags} (h : a.Perm b) (l : ℕ) : totalNumber a l=totalNumber b l := + (h.filter _).length_eq +lemma context_perm {a b : Bags} (h : a.Perm b) (ps : Parents) (l : ℕ) (t : Table) : + context ((a,ps),(l,t))=context ((b,ps),(l,t)) := by + simp only [context,privateNumber_perm h,sharedNumber_perm h,totalNumber_perm h] +lemma update_perm {a b : Bags} (h : a.Perm b) (ps : Parents) (l m B : ℕ) (t : Table) : + update (((a,ps),(l,t)),(m,B))=update (((b,ps),(l,t)),(m,B)) := by + simp only [update,context_perm h] + +def parentTag {m : ℕ} : Option (Fin m) → Bool×ℕ + | none => (false,0) + | some p => (true,p.val) +def parentRep {m : ℕ} (p : Fin m → Option (Fin m)) : Parents := List.ofFn (parentTag ∘ p) +@[simp] lemma parentRep_length {m : ℕ} (p : Fin m → Option (Fin m)) : (parentRep p).length=m := by + simp [parentRep] +@[simp] lemma parentRep_getD {m : ℕ} (p : Fin m → Option (Fin m)) (l : Fin m) : + (parentRep p).getD l.val (false,0)=parentTag (p l) := by + simp [parentRep,List.getD,l.isLt] + +lemma run_eq {V : Type} [Fintype V] [DecidableEq V] {m : ℕ} + (bags : V → Finset (Fin m)) (parent : Fin m → Option (Fin m)) + (ls : List (Fin m)) (R : Finset V) (t : Table) (bs : Bags) + (hbs : bs.Perm (activeRep bags R)) : + (runState (Fintype.card V,(m,parentRep parent)) (ls.map Fin.val) bs t).2= + UnitRefresh.Materialized.run bags parent ls R t := by + induction ls generalizing R bs t with + | nil => rfl + | cons l ls ih => + simp only [List.map_cons,runState,UnitRefresh.Materialized.run,List.length_map] + rw [update_perm hbs] + rw [update_eq bags R parent l t _ _ (parentRep_getD parent l)] + apply ih + exact ((hbs.filter _).trans (trim_activeRep bags R l)) + +end MatchingFPRAS.ExecutableDP + +end OAI diff --git a/lean/OAI/Combinatorics/MatchingCount/Sampling/TreeDPRepresentation.lean b/lean/OAI/Combinatorics/MatchingCount/Sampling/TreeDPRepresentation.lean new file mode 100644 index 0000000000000000000000000000000000000000..8dc24232f834f9c7200c3e9598351b203c551494 --- /dev/null +++ b/lean/OAI/Combinatorics/MatchingCount/Sampling/TreeDPRepresentation.lean @@ -0,0 +1,91 @@ +import Mathlib +import OAI.Combinatorics.MatchingCount.Sampling.TreeDPCount + +namespace OAI + +namespace MatchingFPRAS.ExecutableDP + +lemma privateFlag_perm {b c : Bag} (h : b.Perm c) (l : ℕ) : + privateFlag (l,b)=privateFlag (l,c) := by simp only [privateFlag,h.length_eq,h.mem_iff] +lemma sharedFlag_perm {b c : Bag} (h : b.Perm c) (l : ℕ) : + sharedFlag (l,b)=sharedFlag (l,c) := by simp only [sharedFlag,privateFlag_perm h,h.mem_iff] +lemma totalFlag_perm {b c : Bag} (h : b.Perm c) (l : ℕ) : + totalFlag (l,b)=totalFlag (l,c) := by simp only [totalFlag,h.mem_iff] + +lemma forall₂_filter {A B : Type} {R : A → B → Prop} {as : List A} {bs : List B} + (h : List.Forall₂ R as bs) (p : A → Bool) (q : B → Bool) + (he : ∀ a b,R a b → p a=q b) : List.Forall₂ R (as.filter p) (bs.filter q) := by + induction h with + | nil => exact .nil + | @cons a b as bs hab hs ih => + simp only [List.filter_cons,he a b hab] + cases q b <;> simp only [Bool.false_eq_true,↓reduceIte] + · exact ih + · exact .cons hab ih + +lemma privateNumber_rows {a b : Bags} (h : List.Forall₂ List.Perm a b) (l : ℕ) : + privateNumber a l=privateNumber b l := + (forall₂_filter h _ _ (fun _ _ hh=>privateFlag_perm hh l)).length_eq +lemma sharedNumber_rows {a b : Bags} (h : List.Forall₂ List.Perm a b) (l : ℕ) : + sharedNumber a l=sharedNumber b l := + (forall₂_filter h _ _ (fun _ _ hh=>sharedFlag_perm hh l)).length_eq +lemma totalNumber_rows {a b : Bags} (h : List.Forall₂ List.Perm a b) (l : ℕ) : + totalNumber a l=totalNumber b l := + (forall₂_filter h _ _ (fun _ _ hh=>totalFlag_perm hh l)).length_eq +lemma trim_rows {a b : Bags} (h : List.Forall₂ List.Perm a b) (l : ℕ) : + List.Forall₂ List.Perm (trim a l) (trim b l) := + forall₂_filter h _ _ (fun _ _ hh=>congrArg Bool.not (totalFlag_perm hh l)) +lemma update_rows {a b : Bags} (h : List.Forall₂ List.Perm a b) + (ps : Parents) (l m B : ℕ) (t : Table) : + update (((a,ps),(l,t)),(m,B))=update (((b,ps),(l,t)),(m,B)) := by + simp only [update,context,privateNumber_rows h,sharedNumber_rows h,totalNumber_rows h] +lemma run_rows {a b : Bags} (h : List.Forall₂ List.Perm a b) + (p : Params) (ls : List ℕ) (t : Table) : + (runState p ls a t).2=(runState p ls b t).2 := by + induction ls generalizing a b t with + | nil => rfl + | cons l ls ih => + simp only [runState,update_rows h] + exact ih (trim_rows h l) _ +lemma count_rows {a b : Bags} (h : List.Forall₂ List.Perm a b) (ps : Parents) (ls : List ℕ) : + count ((a,ps),ls)=count ((b,ps),ls) := by + simp only [count,run,h.length_eq,run_rows h] +lemma run_perm {a b : Bags} (h : a.Perm b) (p : Params) (ls : List ℕ) (t : Table) : + (runState p ls a t).2=(runState p ls b t).2 := by + induction ls generalizing a b t with + | nil => rfl + | cons l ls ih => + simp only [runState,update_perm h] + exact ih (h.filter _) _ +lemma count_perm {a b : Bags} (h : a.Perm b) (ps : Parents) (ls : List ℕ) : + count ((a,ps),ls)=count ((b,ps),ls) := by + simp only [count,run,h.length_eq,run_perm h] + +noncomputable def orderedRep {n m : ℕ} (bags : Fin n → Finset (Fin m)) : Bags := + List.ofFn (fun i=>bagRep (bags i)) + +lemma orderedRep_perm {n m : ℕ} (bags : Fin n → Finset (Fin m)) : + (orderedRep bags).Perm (activeRep bags Finset.univ) := by + unfold orderedRep activeRep + change (List.ofFn ((bagRep ∘ bags) ∘ id)).Perm _ + rw [← List.map_ofFn] + apply List.Perm.map + apply List.perm_of_nodup_nodup_toFinset_eq + · exact List.nodup_ofFn.mpr Function.injective_id + · exact Finset.nodup_toList _ + · ext i; simp + +lemma count_ordered {n m : ℕ} (bags : Fin n → Finset (Fin m)) + (parent : Fin m → Option (Fin m)) (ls : List (Fin m)) : + count ((orderedRep bags,parentRep parent),ls.map Fin.val)=UnitRefresh.Materialized.count bags parent ls := by + rw [count_perm (orderedRep_perm bags),count_eq] + +lemma count_represented {n m : ℕ} (bags : Fin n → Finset (Fin m)) + (parent : Fin m → Option (Fin m)) (ls : List (Fin m)) (bs : Bags) + (hbs : List.Forall₂ List.Perm bs (orderedRep bags)) : + count ((bs,parentRep parent),ls.map Fin.val)=UnitRefresh.Materialized.count bags parent ls := by + rw [count_rows hbs,count_ordered] + +end MatchingFPRAS.ExecutableDP + +end OAI diff --git a/lean/OAI/Combinatorics/MatchingCount/Sampling/TreeFastDPEntry.lean b/lean/OAI/Combinatorics/MatchingCount/Sampling/TreeFastDPEntry.lean new file mode 100644 index 0000000000000000000000000000000000000000..edd303c85a422ee7aed001449569d3d90c908121 --- /dev/null +++ b/lean/OAI/Combinatorics/MatchingCount/Sampling/TreeFastDPEntry.lean @@ -0,0 +1,162 @@ +import Mathlib +import OAI.Combinatorics.MatchingCount.Complexity.TreePolyTactic +import OAI.Combinatorics.MatchingCount.Machines.TreeFastLookup +import OAI.Combinatorics.MatchingCount.Complexity.TreePolynomialSums +import OAI.Combinatorics.MatchingCount.Machines.TreeFastChoose + +namespace OAI + +namespace MatchingFPRAS.ExecutableDP +open TreeTyped Polynomial + +def readFast : Realizer read := + composition (pair (composition (pair first second.fst) (getDFast [])) second.snd) (getDFast 0) +lemma polynomial_readFast : PolynomialTime readFast := by + unfold readFast + dsimp only [Realizer.fst, Realizer.snd] + apply polynomial_composition _ (polynomial_getDFast 0) + apply polynomial_pair _ (polynomial_snd polynomial_second) + apply polynomial_composition _ (polynomial_getDFast []) + tree_poly + +lemma polynomial_totalFlag : PolynomialTime totalFlagRealizer := by + unfold totalFlagRealizer + apply polynomial_composition _ polynomial_membership + tree_poly +lemma polynomial_countWith {A B : Type} [Codec A] [Codec B] {p : A×B → Bool} + {P : Realizer p} (hP : PolynomialTime P) : PolynomialTime (countWith P) := by + unfold countWith countTrue + exact polynomial_congr _ (polynomial_composition (polynomial_mapWith hP) + (polynomial_composition (polynomial_filter polynomial_identity) polynomial_listLength)) + +lemma polynomial_privateFlag : PolynomialTime privateFlagRealizer := by + unfold privateFlagRealizer + apply polynomial_composition _ polynomial_boolAnd + apply polynomial_pair _ polynomial_totalFlag + tree_poly +lemma polynomial_sharedFlag : PolynomialTime sharedFlagRealizer := by + unfold sharedFlagRealizer + exact polynomial_composition (polynomial_pair polynomial_totalFlag + (polynomial_composition polynomial_privateFlag polynomial_boolNot)) polynomial_boolAnd +lemma polynomial_privateNumber : PolynomialTime privateNumberRealizer := by + unfold privateNumberRealizer + apply polynomial_congr + apply polynomial_composition _ (polynomial_countWith polynomial_privateFlag) + tree_poly +lemma polynomial_sharedNumber : PolynomialTime sharedNumberRealizer := by + unfold sharedNumberRealizer + apply polynomial_congr + apply polynomial_composition _ (polynomial_countWith polynomial_sharedFlag) + tree_poly +lemma polynomial_totalNumber : PolynomialTime totalNumberRealizer := by + unfold totalNumberRealizer + apply polynomial_congr + apply polynomial_composition _ (polynomial_countWith polynomial_totalFlag) + tree_poly +lemma polynomial_trim : PolynomialTime trimRealizer := by + unfold trimRealizer + apply polynomial_composition _ (polynomial_filterWith (polynomial_composition polynomial_totalFlag polynomial_boolNot)) + tree_poly + +abbrev RawCtx := (Bags×Parents)×(ℕ×Table) +def contextFast : Realizer context := by + let bl : Realizer (fun x : RawCtx=>(x.1.1,x.2.1)) := pair first.fst second.fst + let p := composition bl privateNumberRealizer + let q := composition bl sharedNumberRealizer + let r := composition bl totalNumberRealizer + exact (pair (composition (pair first.snd second.fst) (getDFast (false,0))) + (pair second.fst (pair second.snd (pair p (pair q r))))).congr (fun _=>rfl) +lemma polynomial_contextFast : PolynomialTime contextFast := by + unfold contextFast + dsimp only [Realizer.fst, Realizer.snd] + apply polynomial_congr + apply polynomial_pair + · apply polynomial_composition _ (polynomial_getDFast (false,0)) + tree_poly + · apply polynomial_pair (polynomial_fst polynomial_second) + apply polynomial_pair (polynomial_snd polynomial_second) + apply polynomial_pair + · apply polynomial_composition _ polynomial_privateNumber + tree_poly + · apply polynomial_pair + · apply polynomial_composition _ polynomial_sharedNumber + tree_poly + · apply polynomial_composition _ polynomial_totalNumber + tree_poly + +def rawTerm (x : (RawCtx×ℕ)×ℕ) : ℕ := term ((context x.1.1,x.1.2),x.2) +def rawTermRealizer : Realizer rawTerm := by + let raw : Realizer (fun x : (RawCtx×ℕ)×ℕ=>x.1.1) := first.fst + let c := composition raw contextFast + let r : Realizer (fun x : (RawCtx×ℕ)×ℕ=>x.1.2) := first.snd + let k : Realizer (fun x : (RawCtx×ℕ)×ℕ=>x.2) := second + let s := c.snd.snd.snd.snd.fst + let u := c.snd.snd.snd.fst + let t := c.snd.snd.fst + let l := c.snd.fst + let p := c.fst.snd + let ch := composition (pair s k) fastChoose + let L := composition (pair t (pair l (composition (pair u k) add))) readFast + let R := composition (pair t (pair p (composition (pair (composition (pair s k) subtract) r) add))) readFast + exact (composition (pair (composition (pair ch L) multiply) R) multiply).congr (fun _=>rfl) +lemma sharedNumber_le (bs : Bags) (l : ℕ) : sharedNumber bs l≤bs.length := List.length_filter_le _ _ +lemma polynomial_rawTerm : PolynomialTime rawTermRealizer := by + unfold rawTermRealizer + dsimp only [Realizer.fst, Realizer.snd] + apply polynomial_congr + have hc:=polynomial_contextFast + have hr:=polynomial_readFast + have hch : PolynomialTime (composition + (pair (composition first.fst contextFast).snd.snd.snd.snd.fst (second (A:=RawCtx×ℕ) (B:=ℕ))) fastChoose) := by + apply polynomial_boundedFastChoose (by dsimp only [Realizer.fst, Realizer.snd]; tree_poly) X + intro x + simp only [Polynomial.eval_X] + change sharedNumber x.1.1.1.1 x.1.1.2.1≤weight x + exact (sharedNumber_le _ _).trans ((list_length_le_weight _).trans (by + rcases x with ⟨⟨⟨⟨bs,ps⟩,⟨l,t⟩⟩,r⟩,k⟩ + simp only [weight_prod]; omega)) + dsimp only [Realizer.fst, Realizer.snd] at hch + tree_poly + +def rawEntry (x : RawCtx×(ℕ×ℕ)) : ℕ := entry (context x.1,x.2) +def rawEntryRealizer : Realizer rawEntry := by + let raw : Realizer (fun x : RawCtx×(ℕ×ℕ)=>x.1) := first + let c := composition raw contextFast + let a : Realizer (fun x : RawCtx×(ℕ×ℕ)=>x.2.1) := second.fst + let r : Realizer (fun x : RawCtx×(ℕ×ℕ)=>x.2.2) := second.snd + let l := c.snd.fst + let rd := composition (pair c.snd.snd.fst (pair a r)) readFast + let al := composition (pair a l) natEqual + let ap := composition (pair a c.fst.snd) natEqual + let ks := composition (composition c.snd.snd.snd.snd.fst successor) range + let sm := composition (composition (pair (pair raw r) ks) (mapWith rawTermRealizer)) listSum + let rt := composition (pair c.snd.snd.fst (pair l c.snd.snd.snd.snd.snd)) readFast + exact (choose c.fst.fst (choose al (constant 1) (choose ap sm rd)) (choose al rt rd)).congr (by + intro x; simp only [rawEntry,entry,rawTerm,Function.comp_apply,decide_eq_true_eq]) +lemma polynomial_rawEntry : PolynomialTime rawEntryRealizer := by + unfold rawEntryRealizer + dsimp only [Realizer.fst, Realizer.snd] + have hc:=polynomial_contextFast + have hr:=polynomial_readFast + have ht:=polynomial_rawTerm + have hs:=polynomial_listSum + have hks : PolynomialTime (composition (composition + (composition (first (A:=RawCtx) (B:=ℕ×ℕ)) contextFast).snd.snd.snd.snd.fst successor) range) := by + apply polynomial_boundedRange (by + have := polynomial_successor + dsimp only [Realizer.fst, Realizer.snd] + tree_poly) (X+1) + intro x + simp only [Polynomial.eval_add,Polynomial.eval_X,Polynomial.eval_one] + change sharedNumber x.1.1.1 x.1.2.1+1≤weight x+1 + have hh:=sharedNumber_le x.1.1.1 x.1.2.1 + have hw:=list_length_le_weight x.1.1.1 + rcases x with ⟨⟨⟨bs,ps⟩,⟨l,t⟩⟩,ar⟩ + simp only [weight_prod] + dsimp only at hh hw + omega + dsimp only [Realizer.fst, Realizer.snd] at hks + tree_poly +end MatchingFPRAS.ExecutableDP + +end OAI diff --git a/lean/OAI/Combinatorics/MatchingCount/Sampling/TreeFastDescent.lean b/lean/OAI/Combinatorics/MatchingCount/Sampling/TreeFastDescent.lean new file mode 100644 index 0000000000000000000000000000000000000000..84f52dd3f32ab5c5589737e9b076f2723612db32 --- /dev/null +++ b/lean/OAI/Combinatorics/MatchingCount/Sampling/TreeFastDescent.lean @@ -0,0 +1,157 @@ +import Mathlib +import OAI.Combinatorics.MatchingCount.Sampling.TreeUnitSampler +import OAI.Combinatorics.MatchingCount.Sampling.TreeFastUnit + +namespace OAI + +namespace MatchingFPRAS.ExecutableUnit +open TreeTyped ExecutableDP Polynomial + +def fastSelected (x : Context×Bits) : ℕ×ℕ := fastDraw (x.1,x.2.getD (x.1.1.1.length-1) []) +def fastSelectedRealizer : Realizer fastSelected := by + let n : Realizer (fun x : Context×Bits=>x.1.1.1.length-1) := composition (composition first.fst.fst listLength) predecessor + exact (composition (pair first (composition (pair second n) (getDFast []))) fastDrawRealizer).congr (fun _=>rfl) +lemma polynomial_fastSelected : PolynomialTime fastSelectedRealizer := by + unfold fastSelectedRealizer + dsimp only + apply polynomial_congr + apply polynomial_composition _ polynomial_fastDraw + have := polynomial_getDFast ([] : List Bool) + have := polynomial_predecessor + dsimp only [Realizer.fst,Realizer.snd] + tree_poly + +def nextContextFast : Realizer nextContext := + (pair (pair (composition (pair first.fst.fst second.fst) residualFast) first.fst.snd) first.snd).congr (fun _=>rfl) +lemma polynomial_nextContextFast : PolynomialTime nextContextFast := by + unfold nextContextFast + apply polynomial_congr + have := polynomial_residualFast + dsimp only [Realizer.fst,Realizer.snd] + tree_poly + +def fastStep (x : State) : State := + if 2≤x.1.1.1.length then + let c:=fastSelected (x.1,x.2.1) + (nextContext (x.1,c),(x.2.1,(x.1.1.1.length-2,c)::x.2.2)) + else x +def fastStepRealizer : Realizer fastStep := by + let n : Realizer (fun x : State=>x.1.1.1.length) := composition first.fst.fst listLength + let c : Realizer (fun x : State=>fastSelected (x.1,x.2.1)) := (composition (f:=fun x : State=>(x.1,x.2.1)) (pair first second.fst) fastSelectedRealizer).congr (fun _=>rfl) + let ctx := composition (pair first c) nextContextFast + let k := composition (pair n (constant 2)) subtract + let fs := composition (pair (pair k c) second.snd) listCons + let r := pair ctx (pair second.fst fs) + exact (choose (composition (composition (pair n (constant 2)) less) boolNot) r identity).congr (by + intro x; simp [fastStep,Nat.succ_le_iff]) +lemma polynomial_fastStep : PolynomialTime fastStepRealizer := by + unfold fastStepRealizer + dsimp only + apply polynomial_congr + have := polynomial_fastSelected + have := polynomial_nextContextFast + dsimp only [Realizer.fst,Realizer.snd] + tree_poly + +lemma chooseBits_le_length (x : List TreeFraction.Fraction×List Bool) : ExecutableChoice.chooseBits x≤x.1.length := by + exact TreeTyped.listMin_le_default _ _ +lemma fastDraw_bounds (x : Context×List Bool) : + (fastDraw x).1≤x.1.1.1.length*x.1.1.2.length ∧ (fastDraw x).2≤x.1.1.1.length*x.1.1.2.length := by + have h:=chooseBits_le_length (fastProbabilities x.1,x.2) + simp only [fastProbabilities,List.length_map,List.length_range] at h + exact ⟨(Nat.div_le_self _ _).trans h,(Nat.mod_le _ _).trans h⟩ +lemma fastSelected_bounds (x : Context×Bits) : + (fastSelected x).1≤x.1.1.1.length*x.1.1.2.length ∧ (fastSelected x).2≤x.1.1.1.length*x.1.1.2.length := + fastDraw_bounds _ +lemma residual_length (bs : Bags) (b : ℕ) : (residual (bs,b)).length=bs.length-2 := by + simp [residual] +lemma residual_mem {bs : Bags} {b : ℕ} {a : Bag} (ha : a∈residual (bs,b)) : a∈bs := by + simp only [residual,List.mem_map,List.mem_range] at ha + obtain ⟨i,hi,rfl⟩:=ha + have hj : skip (i,b) omega + rw [List.getD_eq_getElem _ _ hj] + exact List.getElem_mem _ + +def DescentInvariant (a : Context×Bits) (k : ℕ) (z : State) : Prop := + z.1.1.1.length≤a.1.1.1.length ∧ + (∀ b∈z.1.1.1,b∈a.1.1.1) ∧ z.1.1.2=a.1.1.2 ∧ z.1.2=a.1.2 ∧ z.2.1=a.2 ∧ + z.2.2.length+k≤a.1.1.1.length ∧ + ∀ f∈z.2.2,f.1≤a.1.1.1.length ∧ f.2.1≤a.1.1.1.length*a.1.1.2.length ∧ f.2.2≤a.1.1.1.length*a.1.1.2.length +lemma descent_init (a : Context×Bits) : DescentInvariant a a.1.1.1.length (a.1,(a.2,[])) := by + simp only [DescentInvariant,List.length_nil,Nat.zero_add,List.not_mem_nil,IsEmpty.forall_iff,le_refl,implies_true,true_and,and_true] + exact fun b h=>h +lemma descent_step (a : Context×Bits) (k : ℕ) (z : State) (hz : DescentInvariant a (k+1) z) : + DescentInvariant a k (fastStep z) := by + obtain ⟨hl,hb,hp,ho,ht,hf,hm⟩:=hz + by_cases hn : 2≤z.1.1.1.length + · rw [fastStep,ite_eq_left hn] + have hc:=fastSelected_bounds (z.1,z.2.1) + rw [hp] at hc + have hmul:=Nat.mul_le_mul_right a.1.1.2.length hl + refine ⟨?_,?_,hp,ho,ht,?_,?_⟩ + · change (residual (z.1.1.1,(fastSelected (z.1,z.2.1)).1)).length≤_ + rw [residual_length]; omega + · intro b hb' + exact hb b (residual_mem hb') + · change ( _ :: z.2.2).length+k≤_ + simp only [List.length_cons]; omega + · intro f hh + rcases List.mem_cons.mp hh with rfl | hh + · exact ⟨(Nat.sub_le _ _).trans hl,hc.1.trans hmul,hc.2.trans hmul⟩ + · exact hm f hh + · rw [fastStep,ite_eq_right hn] + exact ⟨hl,hb,hp,ho,ht,by omega,hm⟩ + +lemma descent_weight (a : Context×Bits) (k : ℕ) (z : State) (hz : DescentInvariant a k z) : + weight z≤ 20*(weight a+1)^3 := by + obtain ⟨hl,hb,hp,ho,ht,hf,hm⟩:=hz + let S:=weight a + have hn : a.1.1.1.length≤S := (list_length_le_weight _).trans ((weight_fst a.1.1).trans ((weight_fst a.1).trans (weight_fst a))) + have hn' : a.1.1.2.length≤S := (list_length_le_weight _).trans ((weight_snd a.1.1).trans ((weight_fst a.1).trans (weight_fst a))) + have hbn:weight z.1.1.1≤S*(S+1)+1 := by + have hh:=weight_map_bound (as:=z.1.1.1) (f:=id) (N:=S) (fun b hh=>(weight_mem (hb b hh)).trans ((weight_fst a.1.1).trans ((weight_fst a.1).trans (weight_fst a)))) + simpa only [List.map_id] using hh.trans (Nat.add_le_add_right (Nat.mul_le_mul_right (S+1) (hl.trans hn)) 1) + have hmfn:weight z.2.2≤S*(8*S*S+4*S+6)+1 := by + have hh:=weight_map_bound (as:=z.2.2) (f:=id) (N:=8*S*S+4*S+5) (by + intro f hh + obtain ⟨h1,h2,h3⟩:=hm f hh + have hm:=Nat.mul_le_mul hn hn' + have hf1:=weight_nat_numeric f.1 + have hf2:=weight_nat_numeric f.2.1 + have hf3:=weight_nat_numeric f.2.2 + change weight f≤_ + rw [←Prod.eta f,weight_prod,←Prod.eta f.2,weight_prod] + nlinarith) + simp only [List.map_id] at hh + have hlen :z.2.2.length≤S:=by omega + have he : 8*S*S+4*S+5+1=8*S*S+4*S+6 := by omega + rw [he] at hh + exact hh.trans (Nat.add_le_add_right (Nat.mul_le_mul_right _ hlen) 1) + have hpar :weight a.1.1.2≤S := (weight_snd a.1.1).trans ((weight_fst a.1).trans (weight_fst a)) + have hplan :weight a.1.2≤S := (weight_snd a.1).trans (weight_fst a) + have hbits :weight a.2≤S := weight_snd a + rw [←Prod.eta z,weight_prod,←Prod.eta z.1,weight_prod,←Prod.eta z.1.1,weight_prod,←Prod.eta z.2,weight_prod,hp,ho,ht] + change _≤20*(S+1)^3 + nlinarith + +def fastDescend (a : Context×Bits) : State := + countDown (fun y : ℕ×State=>fastStep y.2) a.1.1.1.length (a.1,(a.2,[])) +def fastDescendRealizer : Realizer fastDescend := + (composition (pair (composition first.fst.fst listLength) (pair first (pair second (constant ([] : List Frame))))) + (iterateDown (composition second fastStepRealizer))).congr (fun _=>rfl) +lemma polynomial_fastDescend : PolynomialTime fastDescendRealizer := by + unfold fastDescendRealizer + apply polynomial_congr + apply polynomial_boundedRepeat (by dsimp only [Realizer.fst,Realizer.snd]; tree_poly) + (polynomial_composition polynomial_second polynomial_fastStep) + X (20*(X+1)^3) DescentInvariant + · intro a + simpa only [Function.comp_apply,Polynomial.eval_X] using (list_length_le_weight a.1.1.1).trans ((weight_fst a.1.1).trans ((weight_fst a.1).trans (weight_fst a))) + · exact descent_init + · intro a k _hk z hz + exact descent_step a k z hz + · intro a k z hz + simpa only [Polynomial.eval_mul,Polynomial.eval_ofNat,Polynomial.eval_pow,Polynomial.eval_add,Polynomial.eval_X,Polynomial.eval_one] using descent_weight a k z hz +end MatchingFPRAS.ExecutableUnit + +end OAI diff --git a/lean/OAI/Combinatorics/MatchingCount/Sampling/TreeFastSample.lean b/lean/OAI/Combinatorics/MatchingCount/Sampling/TreeFastSample.lean new file mode 100644 index 0000000000000000000000000000000000000000..d4b2aee3e96987c50843da3ee640b9e746843d77 --- /dev/null +++ b/lean/OAI/Combinatorics/MatchingCount/Sampling/TreeFastSample.lean @@ -0,0 +1,135 @@ +import Mathlib +import OAI.Combinatorics.MatchingCount.Graphs.RemainingBags +import OAI.Combinatorics.MatchingCount.Sampling.TreeFastDescent +import OAI.Combinatorics.MatchingCount.Sampling.TreeFastUnitCorrect +import OAI.Combinatorics.MatchingCount.Machines.TreeCappedAssembly + +namespace OAI + +namespace MatchingFPRAS.ExecutableUnit +open TreeTyped ExecutableDP + +def fastRawSample (cap : Context) : ℕ → Context → Bits → Result + | 0,_,_ => [] + | f+1,x,bits => if 2≤x.1.1.length then + let c:=fastSelected (x,bits) + clippedAssemble (cap,((x.1.1.length-2,c),fastRawSample cap f (nextContext (x,c)) bits)) + else [] +def unwindClipped (cap : Context) (fs : List Frame) (r : Result) : Result := + (fs.foldl (fun z f=>assemblyFoldStep (f,z)) (cap,r)).2 +lemma fastDescend_unwind (cap : Context) (f : ℕ) (x : Context) (bs : Bits) (fs : List Frame) : + unwindClipped cap (countDown (fun y : ℕ×State=>fastStep y.2) f (x,(bs,fs))).2.2 []= + unwindClipped cap fs (fastRawSample cap f x bs) := by + induction f generalizing x bs fs with + | zero => rfl + | succ f ih => + rw [countDown] + by_cases h : 2≤x.1.1.length + · have he : fastStep (x,(bs,fs))=(nextContext (x,fastSelected (x,bs)),(bs,(x.1.1.length-2,fastSelected (x,bs))::fs)) := by simp only [fastStep,h,↓reduceIte] + rw [he,ih] + simp only [fastRawSample,h,↓reduceIte] + rfl + · have he : fastStep (x,(bs,fs))=(x,(bs,fs)) := by simp only [fastStep,h,↓reduceIte] + rw [he,ih] + simp only [fastRawSample,h,↓reduceIte] + have hz : fastRawSample cap f x bs=[] := by cases f <;> simp [fastRawSample,h] + rw [hz] + +def fastSample (x : Context×Bits) : Result := fastRawSample x.1 x.1.1.1.length x.1 x.2 +def fastSampleRealizer : Realizer fastSample := + (composition (composition (pair fastDescendRealizer.snd.snd (pair first (constant ([] : Result)))) + (fold assemblyFoldStepRealizer)) second).congr (by + intro x + exact (fastDescend_unwind x.1 _ _ _ []).trans rfl) +lemma polynomial_fastSample : PolynomialTime fastSampleRealizer := by + unfold fastSampleRealizer + apply polynomial_congr + apply polynomial_composition _ polynomial_second + apply polynomial_composition _ polynomial_assemblyFold + exact polynomial_pair (polynomial_snd (polynomial_snd polynomial_fastDescend)) + (polynomial_pair polynomial_first (polynomial_constant [])) + +lemma fastSelected_eq_of_getD {n m k : ℕ} (bags : Fin (n+2) → Finset (Fin m)) + (rank : Fin m → ℕ) (parent : Fin m → Option (Fin m)) + (hb : UnitRefresh.RankedBags bags rank parent) (hne : ∀ x,(bags x).Nonempty) + (hp : ∀ l p,parent l=some p → rank p + cases n with + | zero => + cases fuel <;> simp [fastRawSample,orderedRep,resultRep] + | succ n => + cases n with + | zero => + have hzero := singleton_count_zero bags rank parent hb hne hp + omega + | succ n => + let a : Fin (n+2) := Fin.last (n+1) + let c := drawEdge bags rank parent hb hne hp a hz k (bits a) + let bags' := remainingBags bags a c.val + have hb' := remainingRanked bags rank parent hb a c.val + have hne' := remainingNonempty bags hne a c.val + have hz' := remainingPositive bags rank parent hb hne hp a c + let bits' : Fin n → Fin k → Bool := fun i=>bits i.castSucc.castSucc + have hbits' : ∀ i : Fin n,bs.getD i.val []=List.ofFn (bits' i) := + fun i=>hbs i.castSucc.castSucc + have hc := fastSelected_eq_of_getD bags rank parent hb hne hp hz bits bs (hbs a) + change fastSelected (((orderedRep bags,parentRep parent),(plan rank).map Fin.val),bs)= + (c.val.val.1.val,c.val.val.2.val) at hc + have hnext : nextContext (((orderedRep bags,parentRep parent),(plan rank).map Fin.val), + (c.val.val.1.val,c.val.val.2.val))= + ((orderedRep bags',parentRep parent),(plan rank).map Fin.val) := by + unfold nextContext + rw [residual_ordered bags c.val.val.1 c.val.property.1] + rfl + cases fuel with + | zero => omega + | succ fuel => + have hr := ih n (by omega) (by omega) bags' hb' hne' hz' bits' hbits' fuel (by omega) + have hl : (orderedRep bags).length=n+2 := List.length_ofFn + rw [fastRawSample] + simp only [hl,show 2≤n+2 by omega,↓reduceIte,hc,hnext,Nat.add_sub_cancel] + rw [hr] + rw [sampleUnit_step] + exact clippedAssemble_eq cap hcapn hcapm bags c.val _ + +lemma fastSample_eq {n m k : ℕ} (bags : Fin n → Finset (Fin m)) + (rank : Fin m → ℕ) (parent : Fin m → Option (Fin m)) + (hb : UnitRefresh.RankedBags bags rank parent) (hne : ∀ x,(bags x).Nonempty) + (hp : ∀ l p,parent l=some p → rank pList.ofFn (bits i)))= + resultRep (sampleUnit k n bags rank parent hb hne hp hz bits) := by + unfold fastSample + apply fastRawSample_eq _ n (by simp [orderedRep]) (by simp [parentRep_length]) bags rank parent hb hne hp hz bits + · intro i + simp only [List.getD,List.getElem?_ofFn,i.isLt,↓reduceDIte,Option.getD_some] + · simp only [orderedRep,List.length_ofFn,le_refl] +end MatchingFPRAS.ExecutableUnit + +end OAI diff --git a/lean/OAI/Combinatorics/MatchingCount/Sampling/TreeFastUnit.lean b/lean/OAI/Combinatorics/MatchingCount/Sampling/TreeFastUnit.lean new file mode 100644 index 0000000000000000000000000000000000000000..535c10877118a433ec44a5842fe726a889a7be40 --- /dev/null +++ b/lean/OAI/Combinatorics/MatchingCount/Sampling/TreeFastUnit.lean @@ -0,0 +1,130 @@ +import Mathlib +import OAI.Combinatorics.MatchingCount.Machines.TreeClippedRun +import OAI.Combinatorics.MatchingCount.Complexity.TreeChoiceCosts +import OAI.Combinatorics.MatchingCount.Sampling.TreeUnitDraw + +namespace OAI + +namespace MatchingFPRAS.ExecutableUnit +open TreeTyped ExecutableDP Polynomial + +def skipFast : Realizer skip := skipRealizer +lemma polynomial_skipFast : PolynomialTime skipFast := by + unfold skipFast skipRealizer + apply polynomial_congr + exact polynomial_choose polynomial_less polynomial_first + (polynomial_composition polynomial_first polynomial_successor) + +def residualFast : Realizer residual := by + let p : Realizer (fun x : (Bags×ℕ)×ℕ=>(x.1.1,skip (x.2,x.1.2))) := + pair first.fst (composition (pair second first.snd) skipFast) + let n : Realizer (fun x : Bags×ℕ=>x.1.length-2) := composition (pair (composition first listLength) (constant 2)) subtract + exact (composition (pair identity (composition n range)) + (mapWith (composition p (getDFast ([] : Bag))))).congr (fun _=>rfl) +lemma polynomial_residualFast : PolynomialTime residualFast := by + unfold residualFast Realizer.fst Realizer.snd + dsimp only + apply polynomial_congr + apply polynomial_composition + · apply polynomial_pair polynomial_identity + apply polynomial_boundedRange (by tree_poly) X + intro x + simpa only [Polynomial.eval_X] using (Nat.sub_le x.1.length 2).trans ((list_length_le_weight x.1).trans (weight_fst x)) + · apply polynomial_mapWith + apply polynomial_composition _ (polynomial_getDFast []) + have := polynomial_skipFast + tree_poly + +def validFast : Realizer valid := by + let bs : Realizer (fun x : Context×(ℕ×ℕ)=>x.1.1.1) := first.fst.fst + let b : Realizer (fun x : Context×(ℕ×ℕ)=>x.2.1) := second.fst + let c : Realizer (fun x : Context×(ℕ×ℕ)=>x.2.2) := second.snd + let a := composition (composition bs listLength) predecessor + let ba := composition (pair bs a) (getDFast ([] : Bag)) + let bb := composition (pair bs b) (getDFast ([] : Bag)) + let p := composition (composition (pair b a) natEqual) boolNot + let q := composition (pair ba c) membership + let r := composition (pair bb c) membership + exact (composition (pair (composition (pair p q) boolAnd) r) boolAnd).congr (by intro x; simp [valid]) +lemma polynomial_validFast : PolynomialTime validFast := by + unfold validFast Realizer.fst Realizer.snd + dsimp only + apply polynomial_congr + have := polynomial_predecessor + have := polynomial_getDFast ([] : Bag) + have := polynomial_membership + tree_poly + +def fastBranch (x : Context×ℕ) : ℕ := cappedCount ((residual (x.1.1.1,x.2),x.1.1.2),x.1.2) +def fastBranchRealizer : Realizer fastBranch := + (composition (pair (pair (composition (pair first.fst.fst second) residualFast) first.fst.snd) + first.snd) cappedCountRealizer).congr (fun _=>rfl) +lemma polynomial_fastBranch : PolynomialTime fastBranchRealizer := by + unfold fastBranchRealizer Realizer.fst Realizer.snd + apply polynomial_congr + apply polynomial_composition _ polynomial_cappedCount + have := polynomial_residualFast + tree_poly + +def fastEdgeCount (x : Context×(ℕ×ℕ)) : ℕ := if valid x then fastBranch (x.1,x.2.1) else 0 +def fastEdgeCountRealizer : Realizer fastEdgeCount := + (choose validFast (composition (pair first second.fst) fastBranchRealizer) (constant 0)).congr (fun _=>rfl) +lemma polynomial_fastEdgeCount : PolynomialTime fastEdgeCountRealizer := by + unfold fastEdgeCountRealizer + apply polynomial_congr + exact polynomial_choose polynomial_validFast + (polynomial_composition (polynomial_pair polynomial_first (polynomial_fst polynomial_second)) polynomial_fastBranch) + (polynomial_constant 0) + +def fastProbability (x : Context×ℕ) : TreeFraction.Fraction := + (fastEdgeCount (x.1,decodeIndex (x.2,x.1.1.2.length)),cappedCount x.1) +def fastProbabilityRealizer : Realizer fastProbability := by + let m : Realizer (fun x : Context×ℕ=>x.1.1.2.length) := composition first.fst.snd listLength + let bc := composition (pair second m) decodeIndexRealizer + exact (pair (composition (pair first bc) fastEdgeCountRealizer) + (composition first cappedCountRealizer)).congr (fun _=>rfl) +lemma polynomial_fastProbability : PolynomialTime fastProbabilityRealizer := by + unfold fastProbabilityRealizer + dsimp only + apply polynomial_congr + apply polynomial_pair _ (polynomial_composition polynomial_first polynomial_cappedCount) + apply polynomial_composition _ polynomial_fastEdgeCount + apply polynomial_pair polynomial_first + apply polynomial_composition _ polynomial_division + exact polynomial_pair polynomial_second + (polynomial_composition (polynomial_snd (polynomial_fst polynomial_first)) polynomial_listLength) + +def fastProbabilities (x : Context) : List TreeFraction.Fraction := + (List.range (x.1.1.length*x.1.2.length)).map (fun i=>fastProbability (x,i)) +def fastProbabilitiesRealizer : Realizer fastProbabilities := by + let n : Realizer (fun x : Context=>x.1.1.length) := composition first.fst listLength + let m : Realizer (fun x : Context=>x.1.2.length) := composition first.snd listLength + exact (composition (pair identity (composition (composition (pair n m) multiply) range)) + (mapWith fastProbabilityRealizer)).congr (fun _=>rfl) +lemma polynomial_fastProbabilities : PolynomialTime fastProbabilitiesRealizer := by + unfold fastProbabilitiesRealizer Realizer.fst Realizer.snd + dsimp only + apply polynomial_congr + apply polynomial_composition _ (polynomial_mapWith polynomial_fastProbability) + apply polynomial_pair polynomial_identity + apply polynomial_boundedRange (by tree_poly) (X^2) + intro x + simp only [Function.comp_apply,Polynomial.eval_pow,Polynomial.eval_X] + simpa only [pow_two] using Nat.mul_le_mul ((list_length_le_weight x.1.1).trans ((weight_fst x.1).trans (weight_fst x))) + ((list_length_le_weight x.1.2).trans ((weight_snd x.1).trans (weight_fst x))) + +def fastDraw (x : Context×List Bool) : ℕ×ℕ := + decodeIndex (ExecutableChoice.chooseBits (fastProbabilities x.1,x.2),x.1.1.2.length) +def fastDrawRealizer : Realizer fastDraw := + (composition (pair (composition (pair (composition first fastProbabilitiesRealizer) second) + ExecutableChoice.chooseBitsFast) (composition first.fst.snd listLength)) decodeIndexRealizer).congr (fun _=>rfl) +lemma polynomial_fastDraw : PolynomialTime fastDrawRealizer := by + unfold fastDrawRealizer decodeIndexRealizer + apply polynomial_congr + apply polynomial_composition _ polynomial_division + apply polynomial_pair _ (polynomial_composition (polynomial_snd (polynomial_fst polynomial_first)) polynomial_listLength) + exact polynomial_composition (polynomial_pair + (polynomial_composition polynomial_first polynomial_fastProbabilities) polynomial_second) ExecutableChoice.polynomial_chooseBitsFast +end MatchingFPRAS.ExecutableUnit + +end OAI diff --git a/lean/OAI/Combinatorics/MatchingCount/Sampling/TreeFastUnitCorrect.lean b/lean/OAI/Combinatorics/MatchingCount/Sampling/TreeFastUnitCorrect.lean new file mode 100644 index 0000000000000000000000000000000000000000..87457d0428e8df672f8d296a30c2d11a5e477f01 --- /dev/null +++ b/lean/OAI/Combinatorics/MatchingCount/Sampling/TreeFastUnitCorrect.lean @@ -0,0 +1,74 @@ +import Mathlib +import OAI.Combinatorics.MatchingCount.Machines.TreeClippedCorrect +import OAI.Combinatorics.MatchingCount.Sampling.TreeFastUnit + +namespace OAI + +namespace MatchingFPRAS.ExecutableUnit +open TreeTyped ExecutableDP TreeFraction + +lemma fastBranch_eq {n m : ℕ} (bags : Fin (n+2) → Finset (Fin m)) + (rank : Fin m → ℕ) (parent : Fin m → Option (Fin m)) + (hb : UnitRefresh.RankedBags bags rank parent) (hne : ∀ x,(bags x).Nonempty) + (hp : ∀ l p,parent l=some p → rank pbags (e i).val) rank parent := fun v l hl r hr=>hb (e v).val l hl r hr + rw [UnitRefresh.Materialized.computable_count_eq _ rank parent hbe (fun i=>hne (e i).val) hp] + rw [Fintype.card_congr (UnitRefresh.ColoredPairing.equiv (UnitRefresh.residualBags bags (Fin.last (n+1)) b) e)] + exact (UnitRefresh.Materialized.branchCount_eq bags rank parent hb hne hp _ _).symm + +lemma fastEdgeCount_eq {n m : ℕ} (bags : Fin (n+2) → Finset (Fin m)) + (rank : Fin m → ℕ) (parent : Fin m → Option (Fin m)) + (hb : UnitRefresh.RankedBags bags rank parent) (hne : ∀ x,(bags x).Nonempty) + (hp : ∀ l p,parent l=some p → rank p + (UnitRefresh.Materialized.edgeCount bags rank parent (Fin.last (n+1)) (finProdFinEquiv.symm i), + UnitRefresh.Materialized.count bags parent (UnitRefresh.Materialized.plan rank))) := by + unfold fastProbabilities + simp only [orderedRep,List.length_ofFn,parentRep_length] + rw [map_range_ofFn] + apply List.ofFn_inj.mpr + funext i + change fastProbability (((orderedRep bags,parentRep parent),(UnitRefresh.Materialized.plan rank).map Fin.val),i.val)=_ + rw [fastProbability,parentRep_length,decodeIndex_fin,fastEdgeCount_eq bags rank parent hb hne hp,cappedCount_ordered (parent:=parent) _ _ (by + intro l p hh; have :=hp l p hh; intro e; subst p; omega)] + +lemma fastDraw_eq {n m k : ℕ} (bags : Fin (n+2) → Finset (Fin m)) + (rank : Fin m → ℕ) (parent : Fin m → Option (Fin m)) + (hb : UnitRefresh.RankedBags bags rank parent) (hne : ∀ x,(bags x).Nonempty) + (hp : ∀ l p,parent l=some p → rank p + (UnitRefresh.Materialized.edgeCount bags rank parent (Fin.last (n+1)) (finProdFinEquiv.symm i), + UnitRefresh.Materialized.count bags parent (UnitRefresh.Materialized.plan rank)) + have hq : ∀ i,0<(q i).2 := fun _=>hz + have hs : ∑ i,val (q i)=1 := + UnitRefresh.Materialized.edgeProbability_sum bags rank parent hb hne hp _ hz + rw [fastDraw,fastProbabilities_eq bags rank parent hb hne hp] + change decodeIndex (ExecutableChoice.chooseBits (List.ofFn q,List.ofFn bits), (parentRep parent).length)=_ + rw [ExecutableChoice.chooseBits_values q hq hs,parentRep_length,decodeIndex_fin] + rfl + +end MatchingFPRAS.ExecutableUnit + +end OAI diff --git a/lean/OAI/Combinatorics/MatchingCount/Sampling/TreeIndexedPair.lean b/lean/OAI/Combinatorics/MatchingCount/Sampling/TreeIndexedPair.lean new file mode 100644 index 0000000000000000000000000000000000000000..c08f3e369df25301515258c82a351a820e76cf04 --- /dev/null +++ b/lean/OAI/Combinatorics/MatchingCount/Sampling/TreeIndexedPair.lean @@ -0,0 +1,99 @@ +import Mathlib +import OAI.Combinatorics.MatchingCount.Sampling.TreePairStep + +namespace OAI + +namespace MatchingFPRAS.ExecutablePair +open TreeTyped TreeFraction TreeTyped.SparseProgram + +abbrev Context := List (ℕ×ℕ)×(List Fraction×List Fraction) +def endpoints (x : Context×ℕ) : ℕ×ℕ := x.1.1.getD x.2 (0,0) +def endpointsRealizer : Realizer endpoints := composition (pair first.fst second) (getDFast (0,0)) +lemma polynomial_endpoints : PolynomialTime endpointsRealizer := + polynomial_composition (polynomial_pair (polynomial_fst polynomial_first) polynomial_second) + (polynomial_getDFast (0,0)) + +def incident (x : (ℕ×ℕ)×ℕ) : Bool := decide (x.1.1=x.2 ∨ x.1.2=x.2) +def incidentRealizer : Realizer incident := (composition (pair + (composition (pair first.fst second) natEqual) (composition (pair first.snd second) natEqual)) + boolOr).congr (by intro x; simp [incident]) +lemma polynomial_incident : PolynomialTime incidentRealizer := by + unfold incidentRealizer Realizer.fst Realizer.snd + apply polynomial_congr + tree_cost + +def same (x : (ℕ×ℕ)×(ℕ×ℕ)) : Bool := + decide ((x.1.1=x.2.1 ∧ x.1.2=x.2.2) ∨ (x.1.1=x.2.2 ∧ x.1.2=x.2.1)) +def sameRealizer : Realizer same := (composition (pair + (composition (pair (composition (pair first.fst second.fst) natEqual) + (composition (pair first.snd second.snd) natEqual)) boolAnd) + (composition (pair (composition (pair first.fst second.snd) natEqual) + (composition (pair first.snd second.fst) natEqual)) boolAnd)) boolOr).congr + (by intro x; simp [same]) +lemma polynomial_same : PolynomialTime sameRealizer := by + unfold sameRealizer Realizer.fst Realizer.snd + apply polynomial_congr + tree_cost + +def adjacent (x : (ℕ×ℕ)×(ℕ×ℕ)) : Bool := + incident (x.1,x.2.1) || incident (x.1,x.2.2) +def adjacentRealizer : Realizer adjacent := composition (pair + (composition (pair first second.fst) incidentRealizer) + (composition (pair first second.snd) incidentRealizer)) boolOr +lemma polynomial_adjacent : PolynomialTime adjacentRealizer := by + unfold adjacentRealizer adjacent Realizer.fst Realizer.snd + have := polynomial_incident + tree_cost + +def p (x : Context×(ℕ×ℕ)) : Bool := incident (endpoints (x.1,x.2.1),x.2.2) +def q (x : Context×(ℕ×ℕ)) : Bool := same (endpoints (x.1,x.2.1),endpoints (x.1,x.2.2)) +def r (x : Context×(ℕ×(ℕ×ℕ))) : Bool := same (endpoints (x.1,x.2.1),x.2.2) +def t (x : Context×(ℕ×ℕ)) : Bool := adjacent (endpoints (x.1,x.2.1),endpoints (x.1,x.2.2)) +def u (x : Context×ℕ) : Fraction := x.1.2.1.getD x.2 (0,1) +def v (x : Context×ℕ) : Fraction := x.1.2.2.getD x.2 (0,1) +def pRealizer : Realizer p := composition (pair (composition (pair first second.fst) endpointsRealizer) second.snd) incidentRealizer +def qRealizer : Realizer q := composition (pair (composition (pair first second.fst) endpointsRealizer) + (composition (pair first second.snd) endpointsRealizer)) sameRealizer +def rRealizer : Realizer r := composition (pair (composition (pair first second.fst) endpointsRealizer) second.snd) sameRealizer +def tRealizer : Realizer t := composition (pair (composition (pair first second.fst) endpointsRealizer) + (composition (pair first second.snd) endpointsRealizer)) adjacentRealizer +def uRealizer : Realizer u := composition (pair first.snd.fst second) (getDFast (0,1)) +def vRealizer : Realizer v := composition (pair first.snd.snd second) (getDFast (0,1)) +lemma polynomial_p : PolynomialTime pRealizer := by + unfold pRealizer p Realizer.fst Realizer.snd + have := polynomial_endpoints + have := polynomial_incident + tree_cost +lemma polynomial_q : PolynomialTime qRealizer := by + unfold qRealizer q Realizer.fst Realizer.snd + have := polynomial_endpoints + have := polynomial_same + tree_cost +lemma polynomial_r : PolynomialTime rRealizer := by + unfold rRealizer r Realizer.fst Realizer.snd + have := polynomial_endpoints + have := polynomial_same + tree_cost +lemma polynomial_t : PolynomialTime tRealizer := by + unfold tRealizer t Realizer.fst Realizer.snd + have := polynomial_endpoints + have := polynomial_adjacent + tree_cost +lemma polynomial_u : PolynomialTime uRealizer := + polynomial_composition + (polynomial_pair (polynomial_fst (polynomial_snd polynomial_first)) polynomial_second) + (polynomial_getDFast ((0,1) : Fraction)) +lemma polynomial_v : PolynomialTime vRealizer := + polynomial_composition + (polynomial_pair (polynomial_snd (polynomial_snd polynomial_first)) polynomial_second) + (polynomial_getDFast ((0,1) : Fraction)) + +def draw := pairDraw p q r t u v +def drawRealizer : Realizer draw := pairDrawRealizer pRealizer qRealizer rRealizer tRealizer + uRealizer vRealizer natEqual leNat natEqual leNat +lemma polynomial_draw : PolynomialTime drawRealizer := + polynomial_pairDraw polynomial_p polynomial_q polynomial_r polynomial_t polynomial_u polynomial_v + polynomial_natEqual polynomial_leNat polynomial_natEqual polynomial_leNat +end MatchingFPRAS.ExecutablePair + +end OAI diff --git a/lean/OAI/Combinatorics/MatchingCount/Sampling/TreeIndexedPairCorrect.lean b/lean/OAI/Combinatorics/MatchingCount/Sampling/TreeIndexedPairCorrect.lean new file mode 100644 index 0000000000000000000000000000000000000000..d7c6220e0ffa7abedee6059bec485fa85901615a --- /dev/null +++ b/lean/OAI/Combinatorics/MatchingCount/Sampling/TreeIndexedPairCorrect.lean @@ -0,0 +1,80 @@ +import Mathlib +import OAI.Combinatorics.MatchingCount.Tapes.TreeNumberedCodec +import OAI.Combinatorics.MatchingCount.Sampling.TreeIndexedPair + +namespace OAI + +namespace MatchingFPRAS.ExecutablePair +open TreeTyped TreeFraction TreeTyped.SparseProgram TreeTyped.Numbered + +variable {E V : Type} [Fintype E] [LinearOrder E] [Fintype V] [LinearOrder V] +def endpointRep (s : Sym2 V) : ℕ×ℕ := (index s.inf,index s.sup) +def contextRep (ends : E→Sym2 V) (w z : E→ℚ) : Context := + (List.ofFn (fun i=>endpointRep (ends (UnitRefresh.orderedEnum E i))), + (List.ofFn (fun i=>TreeFraction.repr (w (UnitRefresh.orderedEnum E i))), + List.ofFn (fun i=>TreeFraction.repr (z (UnitRefresh.orderedEnum E i))))) +lemma endpoints_rep (ends : E→Sym2 V) (w z : E→ℚ) (e : E) : + endpoints (contextRep ends w z,index e)=endpointRep (ends e) := by + simp [endpoints,contextRep,index,List.getD_eq_getElem?_getD] +lemma u_rep (ends : E→Sym2 V) (w z : E→ℚ) (e : E) : + u (contextRep ends w z,index e)=TreeFraction.repr (w e) := by + simp [u,contextRep,index,List.getD_eq_getElem?_getD] +lemma v_rep (ends : E→Sym2 V) (w z : E→ℚ) (e : E) : + v (contextRep ends w z,index e)=TreeFraction.repr (z e) := by + simp [v,contextRep,index,List.getD_eq_getElem?_getD] +omit [Fintype V] in +lemma pair_inf_sup [Fintype V] (s : Sym2 V) : s(s.inf,s.sup)=s := Sym2.sortEquiv.symm_apply_apply s +lemma incident_rep (s : Sym2 V) (x : V) : + incident (endpointRep s,index x)=decide (x∈s) := by + simp only [incident,endpointRep,(index_injective (A:=V)).eq_iff] + congr 1 + rw [←pair_inf_sup s,Sym2.mem_iff] + simp only [Sym2.inf_mk,Sym2.sup_mk] + rw [min_eq_left (Sym2.inf_le_sup s),max_eq_right (Sym2.inf_le_sup s)] + exact propext (by tauto) +lemma same_rep (s t : Sym2 V) : + same (endpointRep s,endpointRep t)=decide (s=t) := by + simp only [same,endpointRep,(index_injective (A:=V)).eq_iff] + congr 1 + exact propext (by rw [←Sym2.eq_iff,pair_inf_sup,pair_inf_sup]) +lemma same_pair_rep (s : Sym2 V) (a b : V) : + same (endpointRep s,(index a,index b))=decide (s=s(a,b)) := by + simp only [same,endpointRep,(index_injective (A:=V)).eq_iff] + congr 1 + exact propext (by rw [←Sym2.eq_iff,pair_inf_sup]) +lemma adjacent_rep (s t : Sym2 V) : + adjacent (endpointRep s,endpointRep t)=decide (∃ v,v∈s ∧ v∈t) := by + simp only [adjacent,endpointRep] + change (incident (endpointRep s,index t.inf) || incident (endpointRep s,index t.sup))=_ + rw [incident_rep,incident_rep] + apply Bool.eq_iff_iff.mpr + simp only [Bool.or_eq_true,decide_eq_true_eq] + constructor + · rintro (h|h) + · refine ⟨t.inf,h,?_⟩ + simpa only [pair_inf_sup] using (Sym2.mem_mk_left t.inf t.sup) + · refine ⟨t.sup,h,?_⟩ + simpa only [pair_inf_sup] using (Sym2.mem_mk_right t.inf t.sup) + · rintro ⟨a,ha,ht⟩ + rw [←pair_inf_sup t,Sym2.mem_iff] at ht + rcases ht with h|h <;> subst a <;> simp [ha] + +lemma p_rep (ends : E→Sym2 V) (w z : E→ℚ) (e : E) (x : V) : + p (contextRep ends w z,(index e,index x))=decide (x∈ends e) := by + unfold p + rw [endpoints_rep,incident_rep] +lemma q_rep (ends : E→Sym2 V) (w z : E→ℚ) (e f : E) : + q (contextRep ends w z,(index e,index f))=decide (ends e=ends f) := by + unfold q + rw [endpoints_rep,endpoints_rep,same_rep] +lemma r_rep (ends : E→Sym2 V) (w z : E→ℚ) (e : E) (a b : V) : + r (contextRep ends w z,(index e,(index a,index b)))=decide (ends e=s(a,b)) := by + unfold r + rw [endpoints_rep,same_pair_rep] +lemma t_rep (ends : E→Sym2 V) (w z : E→ℚ) (e f : E) : + t (contextRep ends w z,(index e,index f))=decide (∃ v,v∈ends e ∧ v∈ends f) := by + unfold t + rw [endpoints_rep,endpoints_rep,adjacent_rep] +end MatchingFPRAS.ExecutablePair + +end OAI diff --git a/lean/OAI/Combinatorics/MatchingCount/Sampling/TreeIndexedPairPost.lean b/lean/OAI/Combinatorics/MatchingCount/Sampling/TreeIndexedPairPost.lean new file mode 100644 index 0000000000000000000000000000000000000000..8b9943eca718d7a731a61041a85e144aa68c8b83 --- /dev/null +++ b/lean/OAI/Combinatorics/MatchingCount/Sampling/TreeIndexedPairPost.lean @@ -0,0 +1,55 @@ +import Mathlib +import OAI.Combinatorics.MatchingCount.Machines.TreeNumberedSets +import OAI.Combinatorics.MatchingCount.Sampling.TreeIndexedPairUniform +import OAI.Combinatorics.MatchingCount.Machines.TreeProgramUnique + +namespace OAI + +namespace MatchingFPRAS.ExecutablePair +open TreeTyped TreeTyped.SparseProgram TreeTyped.Numbered TreePost Turing + +variable {E V : Type} [Fintype E] [LinearOrder E] [Fintype V] [LinearOrder V] +def numericInput (x : PairInput Context E V×List Bool) : PairInput Context ℕ ℕ×List Bool := + (((x.1.1.1,(Numbered.set x.1.1.2.1,Numbered.set x.1.1.2.2)), + (Numbered.set x.1.2.1,Numbered.set x.1.2.2)),x.2) +lemma numericInput_encode (x : PairInput Context E V×List Bool) : encode (numericInput x)=encode x := by + rcases x with ⟨⟨⟨c,e,v⟩,a,b⟩,bits⟩ + simp only [numericInput,encode_prod,Numbered.encode_set] +lemma packed_draw (x : PairInput Context E V×List Bool) : + packed (draw (numericInput x))=packed (typedDraw x) := + sameProgram_output drawRealizer typedDrawRealizer typedDraw_program.symm _ _ (numericInput_encode x) + +theorem uniform_pair_post : ∃ p : Polynomial ℕ, + ∀ {E V : Type} [Fintype E] [LinearOrder E] [Fintype V] [LinearOrder V] + (x : PairInput Context E V×List Bool) (t : ℕ),p.eval (packed x).length≤t → + ∀ coins : Fin t→Bool, + (run (machine drawRealizer.program) (packed x) coins).state=none ∧ + (run (machine drawRealizer.program) (packed x) coins).tape.right₀= + ListBlank.mk (packed (typedDraw x)) := by + obtain ⟨p,hp⟩:=polynomial_compiles drawRealizer polynomial_draw + refine ⟨p,fun {E V} _ _ _ _ x t ht coins=>?_⟩ + have hi:=packed_eq_of_encode (numericInput_encode x) + have h:=hp (numericInput x) t (by simpa only [hi] using ht) coins + simpa only [hi,packed_draw] using h + +attribute [local instance] Transport.Sparse.pmOrder + +theorem source_pair_post : ∃ p : Polynomial ℕ, + ∀ {E V : Type} [Fintype E] [LinearOrder E] [Fintype V] [LinearOrder V] + (ends : E→Sym2 V) (hloop : ∀ e,¬(ends e).IsDiag) + (hpar : ∀ e,(Finset.univ.filter (fun f=>ends f=ends e)).card≤2) + (w z : E→ℚ) (hw : ∀ e,0v∈ends e)×Transport.PM (fun e v=>v∈ends e)) + {k : ℕ} (bits : Fin k→Bool) (t : ℕ), + let x := (((contextRep ends w z,((Finset.univ : Finset V),(Finset.univ : Finset E))),pairRepr ends a),List.ofFn bits) + p.eval (packed x).length≤t → ∀ coins : Fin t→Bool, + (run (machine drawRealizer.program) (packed x) coins).state=none ∧ + (run (machine drawRealizer.program) (packed x) coins).tape.right₀= + ListBlank.mk (packed (pairRepr ends ((Transport.Sparse.pairStepTable ends hloop hpar w z hw hz a).draw k bits))) := by + obtain ⟨p,hp⟩:=uniform_pair_post + refine ⟨p,fun {E V} _ _ _ _ ends hloop hpar w z hw hz a {k} bits t ht coins=>?_⟩ + have h:=hp (E:=E) (V:=V) (((contextRep ends w z,((Finset.univ : Finset V),(Finset.univ : Finset E))),pairRepr ends a),List.ofFn bits) t ht coins + rwa [typedDraw_source ends hloop hpar w z hw hz a bits] at h +end MatchingFPRAS.ExecutablePair + +end OAI diff --git a/lean/OAI/Combinatorics/MatchingCount/Sampling/TreeIndexedPairResult.lean b/lean/OAI/Combinatorics/MatchingCount/Sampling/TreeIndexedPairResult.lean new file mode 100644 index 0000000000000000000000000000000000000000..0aae6ff686d846b55d55560ffaceb52cc1bf5e61 --- /dev/null +++ b/lean/OAI/Combinatorics/MatchingCount/Sampling/TreeIndexedPairResult.lean @@ -0,0 +1,33 @@ +import Mathlib +import OAI.Combinatorics.MatchingCount.Sampling.TreeIndexedPairPost +import OAI.Combinatorics.MatchingCount.Tapes.TreeEncodingInjective + +namespace OAI + +namespace MatchingFPRAS.ExecutablePair +open TreeTyped TreeTyped.Numbered TreeTyped.SparseProgram TreePost + +variable {E V : Type} [Fintype E] [LinearOrder E] [Fintype V] [LinearOrder V] +lemma numeric_draw (x : PairInput Context E V×List Bool) : + draw (numericInput x)=(Numbered.set (typedDraw x).1,Numbered.set (typedDraw x).2) := by + apply pair_encode_injective finsetNat_encode_injective finsetNat_encode_injective + have h:=sameProgram_encode drawRealizer typedDrawRealizer typedDraw_program.symm _ _ (numericInput_encode x) + have he : encode (Numbered.set (typedDraw x).1,Numbered.set (typedDraw x).2)=encode (typedDraw x) := + congrArg₂ TreeData.Data.cons (Numbered.encode_set _) (Numbered.encode_set _) + exact h.trans he.symm +attribute [local instance] Transport.Sparse.pmOrder +lemma numeric_draw_source (ends : E→Sym2 V) (hloop : ∀ e,¬(ends e).IsDiag) + (hpar : ∀ e,(Finset.univ.filter (fun f=>ends f=ends e)).card≤2) + (w z : E→ℚ) (hw : ∀ e,0v∈ends e)×Transport.PM (fun e v=>v∈ends e)) + {k : ℕ} (bits : Fin k→Bool) : + draw ((((contextRep ends w z,(Numbered.set (Finset.univ : Finset V),Numbered.set (Finset.univ : Finset E))), + (Numbered.set a.1.val,Numbered.set a.2.val)),List.ofFn bits))= + (Numbered.set ((Transport.Sparse.pairStepTable ends hloop hpar w z hw hz a).draw k bits).1.val, + Numbered.set ((Transport.Sparse.pairStepTable ends hloop hpar w z hw hz a).draw k bits).2.val) := by + have h:=numeric_draw (E:=E) (V:=V) (((contextRep ends w z,(Finset.univ,Finset.univ)),pairRepr ends a),List.ofFn bits) + rw [typedDraw_source ends hloop hpar w z hw hz a bits] at h + exact h +end MatchingFPRAS.ExecutablePair + +end OAI diff --git a/lean/OAI/Combinatorics/MatchingCount/Sampling/TreeIndexedPairUniform.lean b/lean/OAI/Combinatorics/MatchingCount/Sampling/TreeIndexedPairUniform.lean new file mode 100644 index 0000000000000000000000000000000000000000..738ad22063145ea9174e65cde81813131e73a33d --- /dev/null +++ b/lean/OAI/Combinatorics/MatchingCount/Sampling/TreeIndexedPairUniform.lean @@ -0,0 +1,70 @@ +import Mathlib +import OAI.Combinatorics.MatchingCount.Tapes.TreeErasure +import OAI.Combinatorics.MatchingCount.Sampling.TreeIndexedPairCorrect + +namespace OAI + +namespace MatchingFPRAS.ExecutablePair +open TreeTyped TreeFraction TreeTyped.SparseProgram TreeTyped.Numbered + +variable {E V : Type} [Fintype E] [LinearOrder E] [Fintype V] [LinearOrder V] +def typedP (x : Context×(E×V)) : Bool := p (x.1,(index x.2.1,index x.2.2)) +def typedQ (x : Context×(E×E)) : Bool := q (x.1,(index x.2.1,index x.2.2)) +def typedR (x : Context×(E×(V×V))) : Bool := r (x.1,(index x.2.1,(index x.2.2.1,index x.2.2.2))) +def typedT (x : Context×(E×E)) : Bool := t (x.1,(index x.2.1,index x.2.2)) +def typedU (x : Context×E) : Fraction := u (x.1,index x.2) +def typedV (x : Context×E) : Fraction := v (x.1,index x.2) +def typedPRealizer : Realizer (typedP (E:=E) (V:=V)) := pRealizer.recode + (fun x : Context×(E×V)=>(x.1,(index x.2.1,index x.2.2))) _ (fun _=>rfl) (fun _=>rfl) +def typedQRealizer : Realizer (typedQ (E:=E)) := qRealizer.recode + (fun x : Context×(E×E)=>(x.1,(index x.2.1,index x.2.2))) _ (fun _=>rfl) (fun _=>rfl) +def typedRRealizer : Realizer (typedR (E:=E) (V:=V)) := rRealizer.recode + (fun x : Context×(E×(V×V))=>(x.1,(index x.2.1,(index x.2.2.1,index x.2.2.2)))) _ (fun _=>rfl) (fun _=>rfl) +def typedTRealizer : Realizer (typedT (E:=E)) := tRealizer.recode + (fun x : Context×(E×E)=>(x.1,(index x.2.1,index x.2.2))) _ (fun _=>rfl) (fun _=>rfl) +def typedURealizer : Realizer (typedU (E:=E)) := uRealizer.recode + (fun x : Context×E=>(x.1,index x.2)) _ (fun _=>rfl) (fun _=>rfl) +def typedVRealizer : Realizer (typedV (E:=E)) := vRealizer.recode + (fun x : Context×E=>(x.1,index x.2)) _ (fun _=>rfl) (fun _=>rfl) +lemma polynomial_typedP : PolynomialTime (typedPRealizer (E:=E) (V:=V)) := + polynomial_recode _ _ _ _ polynomial_p +lemma polynomial_typedQ : PolynomialTime (typedQRealizer (E:=E)) := + polynomial_recode _ _ _ _ polynomial_q +lemma polynomial_typedR : PolynomialTime (typedRRealizer (E:=E) (V:=V)) := + polynomial_recode _ _ _ _ polynomial_r +lemma polynomial_typedT : PolynomialTime (typedTRealizer (E:=E)) := + polynomial_recode _ _ _ _ polynomial_t +lemma polynomial_typedU : PolynomialTime (typedURealizer (E:=E)) := + polynomial_recode _ _ _ _ polynomial_u +lemma polynomial_typedV : PolynomialTime (typedVRealizer (E:=E)) := + polynomial_recode _ _ _ _ polynomial_v + +def typedDraw := pairDraw (typedP (E:=E) (V:=V)) typedQ typedR typedT typedU typedV +def typedDrawRealizer : Realizer (typedDraw (E:=E) (V:=V)) := + pairDrawRealizer typedPRealizer typedQRealizer typedRRealizer typedTRealizer + typedURealizer typedVRealizer Numbered.equal Numbered.lessEqual Numbered.equal Numbered.lessEqual +lemma polynomial_typedDraw : PolynomialTime (typedDrawRealizer (E:=E) (V:=V)) := + polynomial_pairDraw polynomial_typedP polynomial_typedQ polynomial_typedR polynomial_typedT + polynomial_typedU polynomial_typedV polynomial_equal polynomial_lessEqual polynomial_equal polynomial_lessEqual + +lemma typedDraw_program : (typedDrawRealizer (E:=E) (V:=V)).program=drawRealizer.program := by + simp only [typedDrawRealizer, drawRealizer, pairDrawRealizer, Realizer.congr, + composition, pair] + rw [draw_program ((∅,∅) : PairState E) ((∅,∅) : PairState ℕ) (by + simp only [encode_prod,encode_empty_finset])] + rfl + +attribute [local instance] Transport.Sparse.pmOrder +lemma typedDraw_source (ends : E→Sym2 V) (hloop : ∀ e,¬(ends e).IsDiag) + (hpar : ∀ e,(Finset.univ.filter (fun f=>ends f=ends e)).card≤2) + (w z : E→ℚ) (hw : ∀ e,0v∈ends e)×Transport.PM (fun e v=>v∈ends e)) + {k : ℕ} (bits : Fin k→Bool) : + typedDraw (E:=E) (V:=V) (((contextRep ends w z,(Finset.univ,Finset.univ)),pairRepr ends a),List.ofFn bits)= + pairRepr ends ((Transport.Sparse.pairStepTable ends hloop hpar w z hw hz a).draw k bits) := by + exact pairDraw_eq ends hloop hpar typedP typedQ typedR typedT typedU typedV (contextRep ends w z) + (p_rep ends w z) (q_rep ends w z) (r_rep ends w z) (t_rep ends w z) w z hw hz + (u_rep ends w z) (v_rep ends w z) a bits +end MatchingFPRAS.ExecutablePair + +end OAI diff --git a/lean/OAI/Combinatorics/MatchingCount/Sampling/TreeLadder.lean b/lean/OAI/Combinatorics/MatchingCount/Sampling/TreeLadder.lean new file mode 100644 index 0000000000000000000000000000000000000000..9d6d0af4d14c96801f63cb3cd54e082554190131 --- /dev/null +++ b/lean/OAI/Combinatorics/MatchingCount/Sampling/TreeLadder.lean @@ -0,0 +1,107 @@ +import Mathlib +import OAI.Combinatorics.MatchingCount.Machines.TreeRefresh +import OAI.Combinatorics.MatchingCount.Sampling.TreeLadderContext +import OAI.Combinatorics.MatchingCount.Sampling.TreeLadderPost + +namespace OAI + +namespace MatchingFPRAS.NumericLadder +open TreeTyped TreeTyped.Numbered ExecutableLadder UnitRefresh Transport Replica.Ladder + +attribute [local instance] Transport.sym2Order Transport.bagEdgeOrder Transport.bagEdgeFintype +attribute [local instance] UnitRefresh.Computable.allowedDec Transport.prodOrder Transport.sumOrder +variable {V L : Type} [Fintype V] [LinearOrder V] [Fintype L] [LinearOrder L] +variable {bags : V→Finset L} {G : SimpleGraph L} +variable (hbags : ∀ v,∀ a∈bags v,∀ b∈bags v,a=b ∨ G.Adj a b) (hG : G.IsAcyclic) +variable (rank : L→ℕ) (parent : L→Option L) +variable (hb : RankedBags bags rank parent) (hne : ∀ v,(bags v).Nonempty) +variable (hp : ∀ l p,parent l=some p → rank pe.val.val.1) (rationalSlotWeight (T:=T) (q:=q) w) guides + (ExecutableRefresh.storedCatalog (a,List.range (Fintype.card L)), + ((a,ExecutableDP.parentRep (numberedParent parent)),(Materialized.plan (numberedRank rank)).map Fin.val)) + +def localBitsRep {k : ℕ} (b : LocalBits V k) : Bits := + (List.ofFn b.1,List.ofFn (fun i=>List.ofFn (b.2 i))) +omit [Inhabited (Slot T q)] in +lemma source_guide (w : BagEdge bags→ℚ) (a : ExecutableDP.Bags) (i j : Slot T q) : + typedGuide (sourceContext (T:=T) (q:=q) rank parent w a,(i,j))=decide (j∈guides i) := + guides_rep (fun e : BagEdge bags=>e.val.val.1) (rationalSlotWeight (T:=T) (q:=q) w) guides + (ExecutableRefresh.storedCatalog (a,List.range (Fintype.card L)), + ((a,ExecutableDP.parentRep (numberedParent parent)),(Materialized.plan (numberedRank rank)).map Fin.val)) i j +omit [Inhabited (Slot T q)] in +lemma source_pair (w : BagEdge bags→ℚ) (a : ExecutableDP.Bags) (i j : Slot T q) + (s : BagPM bags×BagPM bags) {k : ℕ} (bits : LocalBits V k) : + typedPair ((sourceContext (T:=T) (q:=q) rank parent w a,(i,j)), + ((Numbered.set s.1.val,Numbered.set s.2.val),localBitsRep bits))= + (Numbered.set (Transport.pairDraw hbags hG w k i j s bits).1.val, + Numbered.set (Transport.pairDraw hbags hG w k i j s bits).2.val) := by + exact pairDraw_rep (fun e : BagEdge bags=>e.val.val.1) (fun e=>e.val.property) + (parallels_bound hbags hG) (rationalSlotWeight w) (rationalSlotWeight_pos w) guides _ i j s bits.1 _ +omit [Inhabited (Slot T q)] in +lemma source_refresh (w : BagEdge bags→ℚ) (M : BagPM bags) + (a : ExecutableDP.Bags) (ha : List.Forall₂ List.Perm a (ExecutableDP.orderedRep (numberedBags bags))) + (i : Slot T q) {k : ℕ} (bits : LocalBits V k) : + typedRefresh ((sourceContext (T:=T) (q:=q) rank parent w a,i),localBitsRep bits)= + Numbered.set (baseDraw rank parent hb hne hp M k bits).val := by + exact ExecutableRefresh.refresh_sampleMatching bags rank parent hb hne hp M a ha bits.2 + +noncomputable local instance : DecidableEq (BagPM bags) := Classical.decEq _ +omit [Inhabited (Slot T q)] in +lemma source_run (hq : 0(List.ofFn (bits i).1,localBitsRep (bits i).2)), + (setup,stateRep keys (fun i=>Numbered.set (s i).val)))= + (setup,stateRep keys (fun i=>Numbered.set + (ladderRun hbags hG rank parent hb hne hp hq w M k n s bits i).val)) := by + dsimp only + have hk : ∀ i : Slot T q,i∈List.ofFn (orderedEnum (Slot T q)) := by + intro i + simp only [List.mem_ofFn] + exact ⟨(orderedEnum (Slot T q)).symm i,Equiv.apply_symm_apply _ _⟩ + have hu : ∀ m : BagPM bags,Numbered.set m.val⊆Numbered.set (Finset.univ : Finset (BagEdge bags)) := by + intro m + exact Finset.map_subset_map.mpr (Finset.subset_univ _) + exact scanRun_rep (fun m : BagPM bags=>Numbered.set m.val) localBitsRep + (sourceContext (T:=T) (q:=q) rank parent w a) (List.ofFn (orderedEnum (Slot T q))) hk _ hu + guides (base T q) (base_nonempty T q hq) typedGuide (source_guide (T:=T) (q:=q) rank parent w a) + typedPair typedRefresh (Transport.pairDraw hbags hG w k) (fun _=>baseDraw rank parent hb hne hp M k) + (fun i j s b=>source_pair (T:=T) (q:=q) hbags hG rank parent w a i j s b) (fun i b=>source_refresh (T:=T) (q:=q) rank parent hb hne hp w M a ha i b) s bits + +theorem source_ladder_post : ∃ p : Polynomial ℕ, + ∀ {V L : Type} [Fintype V] [LinearOrder V] [Fintype L] [LinearOrder L] + {bags : V→Finset L} {G : SimpleGraph L} + (hbags : ∀ v,∀ a∈bags v,∀ b∈bags v,a=b ∨ G.Adj a b) (hG : G.IsAcyclic) + (rank : L→ℕ) (parent : L→Option L) (hb : RankedBags bags rank parent) + (hne : ∀ v,(bags v).Nonempty) (hp : ∀ l p,parent l=some p → rank p(List.ofFn (bits i).1,localBitsRep (bits i).2)), + (setup,stateRep keys (fun i=>Numbered.set (s i).val))) + p.eval (TreePost.packed x).length≤t → ∀ coins : Fin t→Bool, + (run (TreePost.machine executeRealizer.program) (TreePost.packed x) coins).state=none ∧ + (run (TreePost.machine executeRealizer.program) (TreePost.packed x) coins).tape.right₀= + Turing.ListBlank.mk (TreePost.packed (setup,stateRep keys (fun i=>Numbered.set + (ladderRun hbags hG rank parent hb hne hp hq w M k n s bits i).val))) := by + obtain ⟨p,hp⟩:=uniform_ladder_post + refine ⟨p,fun {V L} _ _ _ _ {bags G} hbags hG rank parent hb hne hparent {T q} _ hz hq w M a ha {k n} s bits t ht coins=>?_⟩ + have h:=hp (I:=Slot T q) hz + (List.ofFn (fun i=>(List.ofFn (bits i).1,localBitsRep (bits i).2)), + (((sourceContext (T:=T) (q:=q) rank parent w a,(Finset.univ,base T q)), + (List.ofFn (orderedEnum (Slot T q)),Numbered.set (Finset.univ : Finset (BagEdge bags)))), + stateRep (List.ofFn (orderedEnum (Slot T q))) (fun i=>Numbered.set (s i).val))) t ht coins + rwa [source_run hbags hG rank parent hb hne hparent hq w M a ha s bits] at h +end MatchingFPRAS.NumericLadder + +end OAI diff --git a/lean/OAI/Combinatorics/MatchingCount/Sampling/TreeLadderContext.lean b/lean/OAI/Combinatorics/MatchingCount/Sampling/TreeLadderContext.lean new file mode 100644 index 0000000000000000000000000000000000000000..6d8eca2016beeb325627a86d797118ef2ab5ce77 --- /dev/null +++ b/lean/OAI/Combinatorics/MatchingCount/Sampling/TreeLadderContext.lean @@ -0,0 +1,47 @@ +import Mathlib +import OAI.Combinatorics.MatchingCount.Sampling.TreeNumericLadder +import OAI.Combinatorics.MatchingCount.Sampling.TreeIndexedPairResult + +namespace OAI + +namespace MatchingFPRAS.NumericLadder +open TreeTyped TreeTyped.Numbered UnitRefresh ExecutablePair + +variable {I E V : Type} [Fintype I] [LinearOrder I] [Fintype E] [LinearOrder E] [Fintype V] [LinearOrder V] +def contextRep (ends : E→Sym2 V) (w : I→E→ℚ) (guides : I→Finset I) (refresh : RefreshSetup) : Context := + let eps := List.ofFn (fun e=>endpointRep (ends (orderedEnum E e))) + let rows := List.ofFn (fun i=>List.ofFn (fun e=>TreeFraction.repr (w (orderedEnum I i) (orderedEnum E e)))) + let univ := (Numbered.set (Finset.univ : Finset V),Numbered.set (Finset.univ : Finset E)) + let gs := List.ofFn (fun i=>(Numbered.set (guides (orderedEnum I i))).sort (·≤·)) + ((((eps,rows),univ),refresh),gs) +lemma row_rep (ends : E→Sym2 V) (w : I→E→ℚ) (guides : I→Finset I) (refresh : RefreshSetup) (i : I) : + row (contextRep ends w guides refresh,index i)=List.ofFn (fun e=>TreeFraction.repr (w i (orderedEnum E e))) := by + simp [row,contextRep,index,List.getD_eq_getElem?_getD] +lemma guides_rep (ends : E→Sym2 V) (w : I→E→ℚ) (guides : I→Finset I) (refresh : RefreshSetup) (i j : I) : + guide (contextRep ends w guides refresh,(index i,index j))=decide (j∈guides i) := by + simp [guide,contextRep,index,List.getD_eq_getElem?_getD,Numbered.set,Numbered.embedding,Numbered.index] + constructor + · rintro ⟨a,ha,h⟩ + have he : a=j := (orderedEnum I).symm.injective (Fin.ext h) + simpa [he] using ha + · intro hj; exact ⟨j,hj,rfl⟩ +lemma pairContext_rep (ends : E→Sym2 V) (w : I→E→ℚ) (guides : I→Finset I) (refresh : RefreshSetup) (i j : I) : + pairContext (contextRep ends w guides refresh,(index i,index j))=ExecutablePair.contextRep ends (w i) (w j) := by + simp only [pairContext,row_rep] + rfl +attribute [local instance] Transport.Sparse.pmOrder +lemma pairDraw_rep (ends : E→Sym2 V) (hloop : ∀ e,¬(ends e).IsDiag) + (hpar : ∀ e,(Finset.univ.filter (fun f=>ends f=ends e)).card≤2) + (w : I→E→ℚ) (hw : ∀ i e,0v∈ends e)×Transport.PM (fun e v=>v∈ends e)) + {k : ℕ} (bits : Fin k→Bool) (other : ExecutableUnit.Bits) : + pairDraw ((contextRep ends w guides refresh,(index i,index j)), + ((Numbered.set a.1.val,Numbered.set a.2.val),(List.ofFn bits,other)))= + (Numbered.set ((Transport.Sparse.pairStepTable ends hloop hpar (w i) (w j) (hw i) (hw j) a).draw k bits).1.val, + Numbered.set ((Transport.Sparse.pairStepTable ends hloop hpar (w i) (w j) (hw i) (hw j) a).draw k bits).2.val) := by + unfold pairDraw + rw [pairContext_rep] + exact numeric_draw_source ends hloop hpar (w i) (w j) (hw i) (hw j) a bits +end MatchingFPRAS.NumericLadder + +end OAI diff --git a/lean/OAI/Combinatorics/MatchingCount/Sampling/TreeLadderIndexed.lean b/lean/OAI/Combinatorics/MatchingCount/Sampling/TreeLadderIndexed.lean new file mode 100644 index 0000000000000000000000000000000000000000..82d1aa15edbd7e64558255d2005036c6fe5b7ce7 --- /dev/null +++ b/lean/OAI/Combinatorics/MatchingCount/Sampling/TreeLadderIndexed.lean @@ -0,0 +1,102 @@ +import Mathlib +import OAI.Combinatorics.MatchingCount.Sampling.TreeNumericLadder +import OAI.Combinatorics.MatchingCount.Tapes.TreeErasurePrimitives + +namespace OAI + +namespace MatchingFPRAS.NumericLadder +open TreeTyped TreeTyped.Numbered ExecutableLadder + +attribute [local instance] Transport.prodOrder Transport.sumOrder +variable {I : Type} [Fintype I] [LinearOrder I] [Inhabited I] +local instance : Inhabited (Replica.Update I) := ⟨Sum.inr default⟩ + +def typedGuide (x : Context×(I×I)) : Bool := guide (x.1,(index x.2.1,index x.2.2)) +def typedPair (x : LocalPairInput Context I (Finset ℕ) Bits) : Finset ℕ×Finset ℕ := + pairDraw ((x.1.1,(index x.1.2.1,index x.1.2.2)),x.2) +def typedRefresh (x : LocalRefreshInput Context I Bits) : Finset ℕ := refresh ((x.1.1,index x.1.2),x.2) +def typedGuideRealizer : Realizer (typedGuide (I:=I)) := guideRealizer.recode + (fun x : Context×(I×I)=>(x.1,(index x.2.1,index x.2.2))) _ (fun _=>rfl) (fun _=>rfl) +def typedPairRealizer : Realizer (typedPair (I:=I)) := pairRealizer.recode + (fun x : LocalPairInput Context I (Finset ℕ) Bits=>((x.1.1,(index x.1.2.1,index x.1.2.2)),x.2)) _ (fun _=>rfl) (fun _=>rfl) +def typedRefreshRealizer : Realizer (typedRefresh (I:=I)) := refreshRealizer.recode + (fun x : LocalRefreshInput Context I Bits=>((x.1.1,index x.1.2),x.2)) _ (fun _=>rfl) (fun _=>rfl) +abbrev TypedInput (I : Type) := List (List Bool×Bits)×(RunSetup Context I ℕ×StateTable I (Finset ℕ)) +def typedExecute (x : TypedInput I) : RunSetup Context I ℕ×StateTable I (Finset ℕ) := + x.1.foldl (fun z b=>runStep typedGuide typedPair typedRefresh (b,z)) x.2 +def typedExecuteRealizer : Realizer (typedExecute (I:=I)) := + fold (runStepRealizer typedGuideRealizer typedPairRealizer typedRefreshRealizer Numbered.equal Numbered.lessEqual natEqual) +lemma polynomial_typedExecute : PolynomialTime (typedExecuteRealizer (I:=I)) := + polynomial_scanRun (polynomial_recode _ _ _ _ polynomial_guide) + (polynomial_recode _ _ _ _ polynomial_pair) (polynomial_recode _ _ _ _ polynomial_refresh) + Numbered.polynomial_equal Numbered.polynomial_lessEqual polynomial_natEqual + +lemma inl_program_zero (hz : index (default : I)=0) : + (TreeTyped.inl (A:=I×I) (B:=I)).program=(TreeTyped.inl (A:=ℕ×ℕ) (B:=ℕ)).program := by + simp only [TreeTyped.inl,Realizer.recode,pair] + rw [constant_program (default : I) (default : ℕ) (C:=I×I) (D:=ℕ×ℕ) (by change TreeData.nat (index (default : I))=TreeData.nat 0; rw [hz])] + rfl +lemma inr_program_zero (hz : index (default : I)=0) : + (TreeTyped.inr (A:=I×I) (B:=I)).program=(TreeTyped.inr (A:=ℕ×ℕ) (B:=ℕ)).program := by + simp only [TreeTyped.inr,Realizer.recode,pair] + rw [constant_program (default : I×I) (default : ℕ×ℕ) (C:=I) (D:=ℕ) (by + change TreeData.Data.cons (TreeData.nat (index (default : I))) (TreeData.nat (index (default : I)))= + TreeData.Data.cons (TreeData.nat 0) (TreeData.nat 0) + rw [hz])] + rfl +lemma lookup_program_zero (d : Finset ℕ) (hz : index (default : I)=0) : + (lookupRealizer (I:=I) d Numbered.equal).program=(lookupRealizer (I:=ℕ) d natEqual).program := by + dsimp only [lookupRealizer,filterWith,mapWith,mapStepRealizer,TreeTyped.map,TreeTyped.filter, + Realizer.congr,composition,pair,choose,fold, Numbered.equal,Realizer.recode] + simp only [program_constant,encode_list_nil] + rw [head_program ((default : I),d) ((default : ℕ),d) (by + change TreeData.Data.cons (TreeData.nat (index (default : I))) (encode d)= + TreeData.Data.cons (TreeData.nat 0) (encode d) + rw [hz])] + rfl +lemma normalize_program_zero (hz : index (default : I)=0) : + (normalizeStateRealizer (I:=I) (E:=ℕ) Numbered.equal natEqual).program= + (normalizeStateRealizer (I:=ℕ) (E:=ℕ) natEqual natEqual).program := by + dsimp only [normalizeStateRealizer,mapWith,mapStepRealizer,Realizer.congr,composition,pair,fold] + simp only [program_constant,encode_list_nil] + rw [lookup_program_zero ∅ hz] + rfl +lemma none_encode_zero (hz : index (default : I)=0) : + encode (none : Option (Replica.Update I))=encode (none : Option (Replica.Update ℕ)) := by + have hd : encode (default : I)=encode (0 : ℕ) := by + change TreeData.nat (index (default : I))=TreeData.nat 0; rw [hz] + change encode (false,(false,(((default : I),(default : I)),(default : I))))= + encode (false,(false,(((0 : ℕ),(0 : ℕ)),(0 : ℕ)))) + simp only [encode_prod,hd] +lemma choice_program_zero (hz : index (default : I)=0) : + (scanChoiceRealizer (I:=I) typedGuideRealizer Numbered.equal Numbered.lessEqual).program= + (scanChoiceRealizer guideRealizer natEqual leNat).program := by + dsimp only [scanChoiceRealizer,updateSetRealizer,updateListRealizer, TreeTyped.map, + Realizer.congr,composition,pair,fold] + rw [inl_program_zero hz,inr_program_zero hz] + rw [constant_program (none : Option (Replica.Update I)) (none : Option (Replica.Update ℕ)) + (none_encode_zero hz) (C:=ScanSetup Context I) (D:=ScanSetup Context ℕ)] + simp only [program_constant,encode_list_nil] + rfl +lemma local_program_zero (hz : index (default : I)=0) : + (localSamplerRealizer (I:=I) typedPairRealizer typedRefreshRealizer Numbered.equal).program= + (localSamplerRealizer pairRealizer refreshRealizer natEqual).program := by + dsimp only [localSamplerRealizer,optionCases,sumCases,localPairRealizer,localRefreshRealizer, + Realizer.congr,Realizer.recode,composition,pair,choose] + rw [lookup_program_zero (default : Finset ℕ) hz] + rfl +lemma scan_program_zero (hz : index (default : I)=0) : + (scanRealizer (I:=I) typedGuideRealizer typedPairRealizer typedRefreshRealizer Numbered.equal Numbered.lessEqual).program= + (scanRealizer guideRealizer pairRealizer refreshRealizer natEqual leNat).program := by + dsimp only [scanRealizer,Realizer.congr,composition,pair] + rw [choice_program_zero hz,local_program_zero hz,draw_program + (none : Option (Replica.Update I)) (none : Option (Replica.Update ℕ)) (none_encode_zero hz)] + rfl +lemma typedExecute_program (hz : index (default : I)=0) : + (typedExecuteRealizer (I:=I)).program=executeRealizer.program := by + dsimp only [typedExecuteRealizer,executeRealizer,fold,runStepRealizer,Realizer.congr,composition,pair] + rw [scan_program_zero hz,normalize_program_zero hz] + rfl +end MatchingFPRAS.NumericLadder + +end OAI diff --git a/lean/OAI/Combinatorics/MatchingCount/Sampling/TreeLadderPost.lean b/lean/OAI/Combinatorics/MatchingCount/Sampling/TreeLadderPost.lean new file mode 100644 index 0000000000000000000000000000000000000000..f4e047f848d894ff66f38c3f5ebe5688605571a7 --- /dev/null +++ b/lean/OAI/Combinatorics/MatchingCount/Sampling/TreeLadderPost.lean @@ -0,0 +1,49 @@ +import Mathlib +import OAI.Combinatorics.MatchingCount.Machines.TreeProgramUnique +import OAI.Combinatorics.MatchingCount.Sampling.TreeLadderIndexed + +namespace OAI + +namespace MatchingFPRAS.NumericLadder +open TreeTyped TreeTyped.Numbered ExecutableLadder TreePost Turing + +variable {I : Type} [Fintype I] [LinearOrder I] [Inhabited I] +def numericSetup (x : RunSetup Context I ℕ) : RunSetup Context ℕ ℕ := + ((x.1.1,(Numbered.set x.1.2.1,Numbered.set x.1.2.2)),(x.2.1.map index,x.2.2)) +def numericState (x : StateTable I (Finset ℕ)) : StateTable ℕ (Finset ℕ) := x.map (fun a=>(index a.1,a.2)) +def numericInput (x : TypedInput I) : Input := (x.1,(numericSetup x.2.1,numericState x.2.2)) +omit [Inhabited I] in +lemma encode_indices (xs : List I) : encode (xs.map index)=encode xs := by + induction xs with + | nil=>rfl + | cons a as ih=>simp only [List.map_cons,encode_list_cons,ih]; rfl +omit [Inhabited I] in +lemma numericState_encode (x : StateTable I (Finset ℕ)) : encode (numericState x)=encode x := by + induction x with + | nil=>rfl + | cons a as ih=> + change TreeData.Data.cons (encode (index a.1,a.2)) (encode (numericState as))=TreeData.Data.cons (encode a) (encode as) + rw [ih] + rfl +omit [Inhabited I] in +lemma numericInput_encode (x : TypedInput I) : encode (numericInput x)=encode x := by + rcases x with ⟨bits,⟨⟨c,u,b⟩,keys,e⟩,s⟩ + simp only [numericInput,numericSetup,encode_prod,Numbered.encode_set,encode_indices,numericState_encode] +lemma packed_execute (hz : index (default : I)=0) (x : TypedInput I) : + packed (execute (numericInput x))=packed (typedExecute x) := + sameProgram_output executeRealizer typedExecuteRealizer (typedExecute_program hz).symm _ _ (numericInput_encode x) + +theorem uniform_ladder_post : ∃ p : Polynomial ℕ, + ∀ {I : Type} [Fintype I] [LinearOrder I] [Inhabited I], index (default : I)=0 → + ∀ (x : TypedInput I) (t : ℕ),p.eval (packed x).length≤t → ∀ coins : Fin t→Bool, + (run (machine executeRealizer.program) (packed x) coins).state=none ∧ + (run (machine executeRealizer.program) (packed x) coins).tape.right₀= + ListBlank.mk (packed (typedExecute x)) := by + obtain ⟨p,hp⟩:=polynomial_compiles executeRealizer polynomial_execute + refine ⟨p,fun {I} _ _ _ hz x t ht coins=>?_⟩ + have hi:=packed_eq_of_encode (numericInput_encode x) + have h:=hp (numericInput x) t (by simpa only [hi] using ht) coins + simpa only [hi,packed_execute hz] using h +end MatchingFPRAS.NumericLadder + +end OAI diff --git a/lean/OAI/Combinatorics/MatchingCount/Sampling/TreeLocalSampler.lean b/lean/OAI/Combinatorics/MatchingCount/Sampling/TreeLocalSampler.lean new file mode 100644 index 0000000000000000000000000000000000000000..0e77dc361145001d5d61173439231f0ba2b1ca03 --- /dev/null +++ b/lean/OAI/Combinatorics/MatchingCount/Sampling/TreeLocalSampler.lean @@ -0,0 +1,107 @@ +import Mathlib +import OAI.Combinatorics.MatchingCount.Machines.TreeStateTable + +namespace OAI + +namespace MatchingFPRAS.ExecutableLadder +open TreeTyped + +variable {I A B C : Type} [Codec I] [Codec A] [Codec B] [Codec C] +variable [DecidableEq I] [Inhabited I] [Inhabited A] +local instance treeLocalSamplerUpdateInhabited : Inhabited (Replica.Update I) := ⟨Sum.inr default⟩ + +abbrev LocalContext (C I A B : Type) := C×(StateTable I A×B) +abbrev LocalPairInput (C I A B : Type) := (C×(I×I))×((A×A)×B) +abbrev LocalRefreshInput (C I B : Type) := (C×I)×B + +def localPair (p : LocalPairInput C I A B→A×A) + (x : LocalContext C I A B×(I×I)) : StateTable I A := + setPair (x.1.2.1,(x.2,p ((x.1.1,x.2), + ((lookup default (x.1.2.1,x.2.1),lookup default (x.1.2.1,x.2.2)),x.1.2.2)))) +def localPairRealizer {p : LocalPairInput C I A B→A×A} (P : Realizer p) + (E : Realizer (fun x : I×I=>decide (x.1=x.2))) : Realizer (localPair p) := by + let a : Realizer (fun x : LocalContext C I A B×(I×I)=>lookup default (x.1.2.1,x.2.1)) := + (composition (pair first.snd.fst second.fst) (lookupRealizer (default : A) E)).congr (fun _=>rfl) + let b : Realizer (fun x : LocalContext C I A B×(I×I)=>lookup default (x.1.2.1,x.2.2)) := + (composition (pair first.snd.fst second.snd) (lookupRealizer (default : A) E)).congr (fun _=>rfl) + exact (composition (pair first.snd.fst (pair second + (composition (pair (pair first.fst second) (pair (pair a b) first.snd.snd)) P))) + (setPairRealizer E)).congr (fun _=>rfl) +lemma polynomial_localPair {p : LocalPairInput C I A B→A×A} {P : Realizer p} + {E : Realizer (fun x : I×I=>decide (x.1=x.2))} + (hP : PolynomialTime P) (hE : PolynomialTime E) : PolynomialTime (localPairRealizer P E) := by + unfold localPairRealizer + dsimp only [Realizer.fst,Realizer.snd] + apply polynomial_congr + have := polynomial_lookup (default : A) hE + have := polynomial_setPair (A:=A) hE + tree_cost + +def localRefresh (r : LocalRefreshInput C I B→A) + (x : LocalContext C I A B×I) : StateTable I A := + setState (x.1.2.1,(x.2,r ((x.1.1,x.2),x.1.2.2))) +def localRefreshRealizer {r : LocalRefreshInput C I B→A} (R : Realizer r) + (E : Realizer (fun x : I×I=>decide (x.1=x.2))) : Realizer (localRefresh r) := + (composition (pair first.snd.fst (pair second + (composition (pair (pair first.fst second) first.snd.snd) R))) (setStateRealizer E)).congr (fun _=>rfl) +omit [Inhabited I] [Inhabited A] in +lemma polynomial_localRefresh {r : LocalRefreshInput C I B→A} {R : Realizer r} + {E : Realizer (fun x : I×I=>decide (x.1=x.2))} + (hR : PolynomialTime R) (hE : PolynomialTime E) : PolynomialTime (localRefreshRealizer R E) := by + unfold localRefreshRealizer + dsimp only [Realizer.fst,Realizer.snd] + apply polynomial_congr + have := polynomial_setState (A:=A) hE + tree_cost + +def localSampler (p : LocalPairInput C I A B→A×A) (r : LocalRefreshInput C I B→A) + (x : LocalContext C I A B×Option (Replica.Update I)) : StateTable I A := + x.2.elim x.1.2.1 (Sum.elim (fun ij=>localPair p (x.1,ij)) (fun i=>localRefresh r (x.1,i))) +def localSamplerRealizer {p : LocalPairInput C I A B→A×A} {r : LocalRefreshInput C I B→A} + (P : Realizer p) (R : Realizer r) (E : Realizer (fun x : I×I=>decide (x.1=x.2))) : + Realizer (localSampler p r) := + (optionCases second.fst (sumCases (localPairRealizer P E) (localRefreshRealizer R E))).congr (fun _=>rfl) +lemma polynomial_localSampler {p : LocalPairInput C I A B→A×A} {r : LocalRefreshInput C I B→A} + {P : Realizer p} {R : Realizer r} {E : Realizer (fun x : I×I=>decide (x.1=x.2))} + (hP : PolynomialTime P) (hR : PolynomialTime R) (hE : PolynomialTime E) : + PolynomialTime (localSamplerRealizer P R E) := by + unfold localSamplerRealizer + apply polynomial_congr + exact polynomial_optionCases (polynomial_fst polynomial_second) + (polynomial_sumCases (polynomial_localPair hP hE) (polynomial_localRefresh hR hE)) + +variable {Ω D : Type} [Fintype I] [Fintype Ω] [DecidableEq Ω] [Fintype D] [Nonempty D] +variable (e : Ω→A) (d : D→B) (c : C) (keys : List I) (hk : ∀ i,i∈keys) +variable (p : LocalPairInput C I A B→A×A) (r : LocalRefreshInput C I B→A) +variable (sp : I→I→(Ω×Ω)→D→Ω×Ω) (sr : I→D→Ω) + (hp : ∀ i j a b,p ((c,(i,j)),((e a.1,e a.2),d b))=(e (sp i j a b).1,e (sp i j a b).2)) + (hr : ∀ i b,r ((c,i),d b)=e (sr i b)) +omit [Codec I] [Codec A] [Codec B] [Codec C] [Inhabited I] + [Fintype I] [Fintype Ω] [DecidableEq Ω] [Fintype D] [Nonempty D] in +include hp hr hk in +lemma localSampler_rep [Fintype I] [Fintype Ω] [DecidableEq Ω] [Fintype D] [Nonempty D] + (s : I→Ω) (u : Option (Replica.Update I)) (b : D) : + localSampler p r ((c,(stateRep keys (e ∘ s),d b)),u)= + stateRep keys (e ∘ Replica.localSampler sp sr s u b) := by + cases u with + | none => rfl + | some u=>cases u with + | inl ij=> + rcases ij with ⟨i,j⟩ + simp only [localSampler,Option.elim_some,Sum.elim_inl,localPair, + lookup_stateRep default keys (e ∘ s) _ (hk _),Function.comp_apply,hp i j (s i,s j) b,setPair_rep, + Replica.localSampler] + congr 1 + funext z + simp only [Replica.replacePair,Function.comp_apply,Function.update_apply] + split_ifs <;> rfl + | inr i=> + simp only [localSampler,Option.elim_some,Sum.elim_inr,localRefresh,hr,setState_rep, + Replica.localSampler] + congr 1 + funext z + simp only [Function.comp_apply,Function.update_apply] + split_ifs <;> rfl +end MatchingFPRAS.ExecutableLadder + +end OAI diff --git a/lean/OAI/Combinatorics/MatchingCount/Sampling/TreeMarking.lean b/lean/OAI/Combinatorics/MatchingCount/Sampling/TreeMarking.lean new file mode 100644 index 0000000000000000000000000000000000000000..1657b130cfdda79b3a2ae7455df2d0ad89b641dd --- /dev/null +++ b/lean/OAI/Combinatorics/MatchingCount/Sampling/TreeMarking.lean @@ -0,0 +1,68 @@ +import Mathlib +import OAI.Combinatorics.MatchingCount.Sampling.TableMarking +import OAI.Combinatorics.MatchingCount.Sampling.TreeOptions +import OAI.Combinatorics.MatchingCount.Machines.TreeStateTable + +namespace OAI + +namespace MatchingFPRAS.ExecutableMarking +open TreeTyped TreeFraction ExecutableOptions ExecutableLadder + +variable {C E : Type} [Codec C] [Codec E] [LinearOrder E] [Inhabited E] +abbrev MarkInput (C E : Type) := (C×StateTable E (List Bool))×Finset E +abbrev Marks (E : Type) := List (E×ℕ) + +def markEdge (g : C×E→Options ℕ) (x : (C×StateTable E (List Bool))×E) : E×ℕ := + (x.2,draw 0 (g (x.1.1,x.2),lookup [] (x.1.2,x.2))) +def markEdgeRealizer {g : C×E→Options ℕ} (G : Realizer g) + (Eq : Realizer (fun x : E×E=>decide (x.1=x.2))) : Realizer (markEdge g) := + (pair second (composition (pair (composition (pair first.fst second) G) + (composition (pair first.snd second) (lookupRealizer [] Eq))) (drawRealizer 0))).congr (fun _=>rfl) +lemma polynomial_markEdge {g : C×E→Options ℕ} {G : Realizer g} + {Eq : Realizer (fun x : E×E=>decide (x.1=x.2))} + (hG : PolynomialTime G) (hE : PolynomialTime Eq) : PolynomialTime (markEdgeRealizer G Eq) := by + unfold markEdgeRealizer Realizer.fst Realizer.snd + apply polynomial_congr + have := polynomial_lookup ([] : List Bool) hE + have := polynomial_draw (0 : ℕ) + tree_cost + +def assign (g : C×E→Options ℕ) (x : MarkInput C E) : Marks E := + (x.2.sort (·≤·)).map (fun e=>markEdge g (x.1,e)) +def assignRealizer {g : C×E→Options ℕ} (G : Realizer g) + (Eq : Realizer (fun x : E×E=>decide (x.1=x.2))) : Realizer (assign g) := + composition (pair first (composition second finsetList)) (mapWith (markEdgeRealizer G Eq)) +lemma polynomial_assign {g : C×E→Options ℕ} {G : Realizer g} + {Eq : Realizer (fun x : E×E=>decide (x.1=x.2))} + (hG : PolynomialTime G) (hE : PolynomialTime Eq) : PolynomialTime (assignRealizer G Eq) := by + unfold assignRealizer + exact polynomial_composition (polynomial_pair polynomial_first + (polynomial_composition polynomial_second polynomial_finsetList)) + (polynomial_mapWith (polynomial_markEdge hG hE)) + +def marksRep (s : Finset E) (f : E→Fin 3) : Marks E := + (s.sort (·≤·)).map (fun e=>(e,(f e).val)) +omit [Codec C] [Codec E] [Inhabited E] in +lemma assign_rep (g : C×E→Options ℕ) (c : C) (tables : E→WeightedOptions (Fin 3)) + (hg : ∀ e,g (c,e)=ExecutableOptions.repr Fin.val (tables e)) + (keys : List E) (hk : ∀ e,e∈keys) (s : Finset E) {k : ℕ} (bits : E→Fin k→Bool) : + assign g ((c,stateRep keys (fun e=>List.ofFn (bits e))),s)= + marksRep s (fun e=>(tables e).draw k (bits e)) := by + unfold assign marksRep + apply List.map_congr_left + intro e he + unfold markEdge + rw [hg,lookup_stateRep [] keys _ e (hk e),draw_repr Fin.val (tables e) 0 (bits e)] + +omit [Codec C] [Codec E] [Inhabited E] in +lemma assign_draw (g : C×E→Options ℕ) (c : C) (tables : E→WeightedOptions (Fin 3)) + (hg : ∀ e,g (c,e)=ExecutableOptions.repr Fin.val (tables e)) + (keys : List E) (hk : ∀ e,e∈keys) {V A : Type} [Fintype V] [Fintype E] + [Fintype A] [Nonempty A] (inc : E→V→Prop) (f : A→Transport.PM inc) + {k : ℕ} (a : A) (bits : E→Fin k→Bool) : + assign g ((c,stateRep keys (fun e=>List.ofFn (bits e))),(f a).val)= + marksRep (TableMarking.draw inc f tables k (a,bits)).1.val + (fun e=>(tables e).draw k (bits e)) := assign_rep g c tables hg keys hk _ bits +end MatchingFPRAS.ExecutableMarking + +end OAI diff --git a/lean/OAI/Combinatorics/MatchingCount/Sampling/TreeNumericLadder.lean b/lean/OAI/Combinatorics/MatchingCount/Sampling/TreeNumericLadder.lean new file mode 100644 index 0000000000000000000000000000000000000000..248abb5845b90282ed7c87f523247beb8afb9d29 --- /dev/null +++ b/lean/OAI/Combinatorics/MatchingCount/Sampling/TreeNumericLadder.lean @@ -0,0 +1,80 @@ +import Mathlib +import OAI.Combinatorics.MatchingCount.Sampling.TreeScanRun +import OAI.Combinatorics.MatchingCount.Machines.TreeRefreshIndexed +import OAI.Combinatorics.MatchingCount.Machines.TreePostRealization +import OAI.Combinatorics.MatchingCount.Sampling.TreeIndexedPair + +namespace OAI + +namespace MatchingFPRAS.NumericLadder +open TreeTyped TreeFraction ExecutableLadder + +abbrev PairSetup := (List (ℕ×ℕ)×List (List Fraction))×(Finset ℕ×Finset ℕ) +abbrev RefreshSetup := List ExecutableRefresh.Key×ExecutableDP.CountInput +abbrev Context := (PairSetup×RefreshSetup)×List (List ℕ) +abbrev Bits := List Bool×ExecutableUnit.Bits + +def row (x : Context×ℕ) : List Fraction := x.1.1.1.1.2.getD x.2 [] +def rowRealizer : Realizer row := composition (pair first.fst.fst.fst.snd second) (getDFast []) +lemma polynomial_row : PolynomialTime rowRealizer := by + unfold rowRealizer row Realizer.fst Realizer.snd + have := polynomial_getDFast ([] : List Fraction) + tree_cost + +def guide (x : Context×(ℕ×ℕ)) : Bool := decide (x.2.2∈x.1.2.getD x.2.1 []) +def guideRealizer : Realizer guide := composition + (pair (composition (pair first.snd second.fst) (getDFast [])) second.snd) membership +lemma polynomial_guide : PolynomialTime guideRealizer := by + unfold guideRealizer guide Realizer.fst Realizer.snd + have := polynomial_membership + have := polynomial_getDFast ([] : List ℕ) + tree_cost + +def pairContext (x : Context×(ℕ×ℕ)) : ExecutablePair.Context := + (x.1.1.1.1.1,(row (x.1,x.2.1),row (x.1,x.2.2))) +def pairContextRealizer : Realizer pairContext := pair first.fst.fst.fst.fst + (pair (composition (pair first second.fst) rowRealizer) (composition (pair first second.snd) rowRealizer)) +lemma polynomial_pairContext : PolynomialTime pairContextRealizer := by + unfold pairContextRealizer pairContext Realizer.fst Realizer.snd + have := polynomial_row + tree_cost + +def pairDraw (x : LocalPairInput Context ℕ (Finset ℕ) Bits) : Finset ℕ×Finset ℕ := + ExecutablePair.draw ((((pairContext x.1,x.1.1.1.1.2),x.2.1)),x.2.2.1) +def pairRealizer : Realizer pairDraw := (composition + (pair (pair (pair (composition first pairContextRealizer) first.fst.fst.fst.snd) second.fst) + second.snd.fst) ExecutablePair.drawRealizer).congr (fun _=>rfl) +lemma polynomial_pair : PolynomialTime pairRealizer := by + unfold pairRealizer Realizer.fst Realizer.snd + apply polynomial_congr + have := polynomial_pairContext + have := ExecutablePair.polynomial_draw + tree_cost + +def refresh (x : LocalRefreshInput Context ℕ Bits) : Finset ℕ := + ExecutableRefresh.refresh (x.1.1.1.2,x.2.2) +def refreshRealizer : Realizer refresh := composition + (pair first.fst.fst.snd second.snd) ExecutableRefresh.refreshRealizer +lemma polynomial_refresh : PolynomialTime refreshRealizer := by + unfold refreshRealizer refresh Realizer.fst Realizer.snd + have := ExecutableRefresh.polynomial_refresh + tree_cost + +abbrev Input := List (List Bool×Bits)×(RunSetup Context ℕ ℕ×StateTable ℕ (Finset ℕ)) +def execute (x : Input) : RunSetup Context ℕ ℕ×StateTable ℕ (Finset ℕ) := + x.1.foldl (fun z b=>runStep guide pairDraw refresh (b,z)) x.2 +def executeRealizer : Realizer execute := + fold (runStepRealizer guideRealizer pairRealizer refreshRealizer natEqual leNat natEqual) +lemma polynomial_execute : PolynomialTime executeRealizer := + polynomial_scanRun polynomial_guide polynomial_pair polynomial_refresh polynomial_natEqual + polynomial_leNat polynomial_natEqual + +theorem execute_post : ∃ p : Polynomial ℕ,∀ x : Input,∀ t : ℕ, + p.eval (TreePost.packed x).length≤t → ∀ coins : Fin t→Bool, + (run (TreePost.machine executeRealizer.program) (TreePost.packed x) coins).state=none ∧ + (run (TreePost.machine executeRealizer.program) (TreePost.packed x) coins).tape.right₀= + Turing.ListBlank.mk (TreePost.packed (execute x)) := + TreePost.polynomial_compiles executeRealizer polynomial_execute +end MatchingFPRAS.NumericLadder + +end OAI diff --git a/lean/OAI/Combinatorics/MatchingCount/Sampling/TreeNumericMarking.lean b/lean/OAI/Combinatorics/MatchingCount/Sampling/TreeNumericMarking.lean new file mode 100644 index 0000000000000000000000000000000000000000..d5ebb2cb6646633aa1f04034f15e7fd57e669d3c --- /dev/null +++ b/lean/OAI/Combinatorics/MatchingCount/Sampling/TreeNumericMarking.lean @@ -0,0 +1,56 @@ +import Mathlib +import OAI.Combinatorics.MatchingCount.Machines.TreeNumberedSets +import OAI.Combinatorics.MatchingCount.Machines.TreePostRealization +import OAI.Combinatorics.MatchingCount.Algorithm.TreeReweight +import OAI.Combinatorics.MatchingCount.Sampling.TreeMarking + +namespace OAI + +namespace MatchingFPRAS.NumericMarking +open TreeTyped TreeFraction ExecutableLadder ExecutableMarking ExecutableOptions TreeTyped.Numbered UnitRefresh + +abbrev Tables := List (Options ℕ) +def table (x : Tables×ℕ) : Options ℕ := x.1.getD x.2 [] +def tableRealizer : Realizer table := getDFast [] +lemma polynomial_table : PolynomialTime tableRealizer := polynomial_getDFast [] +def assign (x : MarkInput Tables ℕ) : Marks ℕ := ExecutableMarking.assign table x +def assignRealizer : Realizer assign := ExecutableMarking.assignRealizer tableRealizer natEqual +lemma polynomial_assign : PolynomialTime assignRealizer := + ExecutableMarking.polynomial_assign polynomial_table polynomial_natEqual + +variable {E : Type} [Fintype E] [LinearOrder E] +noncomputable def tableRep (f : E→WeightedOptions (Fin 3)) : Tables := + List.ofFn (fun i=>ExecutableOptions.repr Fin.val (f (orderedEnum E i))) +def numericMarks (s : Finset E) (f : E→Fin 3) : Marks ℕ := + (s.sort (·≤·)).map (fun e=>(index e,(f e).val)) +lemma table_rep (f : E→WeightedOptions (Fin 3)) (e : E) : + table (tableRep f,index e)=ExecutableOptions.repr Fin.val (f e) := by + simp only [table,tableRep,index,List.getD,List.getElem?_ofFn, + ((orderedEnum E).symm e).isLt,↓reduceDIte,Fin.eta,Option.getD_some,Equiv.apply_symm_apply] + +lemma assign_rep (f : E→WeightedOptions (Fin 3)) (keys : List E) (hk : ∀ e,e∈keys) + (s : Finset E) {k : ℕ} (bits : E→Fin k→Bool) : + assign ((tableRep f,keys.map (fun e=>(index e,List.ofFn (bits e)))),Numbered.set s)= + numericMarks s (fun e=>(f e).draw k (bits e)) := by + unfold assign ExecutableMarking.assign numericMarks + rw [sort_set,List.map_map] + apply List.map_congr_left + intro e _ + dsimp only [Function.comp_def,markEdge] + rw [table_rep,lookup_image [] keys index (fun e=>List.ofFn (bits e)) index_injective e (hk e),draw_repr Fin.val (f e) 0 (bits e)] + +theorem source_marking_post : ∃ p : Polynomial ℕ, + ∀ {E : Type} [Fintype E] [LinearOrder E] (f : E→WeightedOptions (Fin 3)) + (keys : List E), (∀ e,e∈keys) → ∀ (s : Finset E) {k : ℕ} (bits : E→Fin k→Bool) (t : ℕ), + let x := ((tableRep f,keys.map (fun e=>(index e,List.ofFn (bits e)))),Numbered.set s) + p.eval (TreePost.packed x).length≤t → ∀ coins : Fin t→Bool, + (run (TreePost.machine assignRealizer.program) (TreePost.packed x) coins).state=none ∧ + (run (TreePost.machine assignRealizer.program) (TreePost.packed x) coins).tape.right₀= + Turing.ListBlank.mk (TreePost.packed (numericMarks s (fun e=>(f e).draw k (bits e)))) := by + obtain ⟨p,hp⟩:=TreePost.polynomial_compiles assignRealizer polynomial_assign + refine ⟨p,fun {E} _ _ f keys hk s {k} bits t ht coins=>?_⟩ + have h:=hp ((tableRep f,keys.map (fun e=>(index e,List.ofFn (bits e)))),Numbered.set s) t ht coins + rwa [assign_rep f keys hk s bits] at h +end MatchingFPRAS.NumericMarking + +end OAI diff --git a/lean/OAI/Combinatorics/MatchingCount/Sampling/TreeOptions.lean b/lean/OAI/Combinatorics/MatchingCount/Sampling/TreeOptions.lean new file mode 100644 index 0000000000000000000000000000000000000000..c6670cdf337bd5c4932cc232ee577a3b531f43a3 --- /dev/null +++ b/lean/OAI/Combinatorics/MatchingCount/Sampling/TreeOptions.lean @@ -0,0 +1,113 @@ +import Mathlib +import OAI.Combinatorics.MatchingCount.Complexity.TreeChoiceCosts +import OAI.Combinatorics.MatchingCount.Arithmetic.TreeFractionExtra + +namespace OAI + +namespace MatchingFPRAS.ExecutableOptions +open TreeTyped TreeFraction + +abbrev Options (A : Type) := List (A×Fraction) +variable {A B C Ω : Type} [Codec A] [Codec B] [Codec C] + +noncomputable def repr (e : Ω→A) (c : WeightedOptions Ω) : Options A := + List.ofFn (fun i=>(e (c.out i),TreeFraction.repr (c.mass i))) + +def listSingleton : Realizer (fun a : A=>[a]) := + composition (pair identity (constant ([] : List A))) listCons +omit [Codec B] [Codec C] in +lemma polynomial_listSingleton : PolynomialTime (listSingleton (A:=A)) := + polynomial_composition (polynomial_pair polynomial_identity (polynomial_constant _)) polynomial_listCons + +def pure (a : A) : Options A := [(a,(1,1))] +def pureRealizer : Realizer (pure (A:=A)) := + (composition (pair identity (constant (1,1))) listSingleton).congr (fun _=>rfl) +omit [Codec B] [Codec C] in +lemma polynomial_pure : PolynomialTime (pureRealizer (A:=A)) := + polynomial_congr _ (polynomial_composition (polynomial_pair polynomial_identity (polynomial_constant _)) polynomial_listSingleton) +omit [Codec A] [Codec B] [Codec C] in +lemma pure_repr (e : Ω→A) (a : Ω) : pure (e a)=repr e (.pure a) := by + simp [pure,repr,WeightedOptions.pure,TreeFraction.repr,List.ofFn_succ] + +def scale (x : Fraction×Options A) : Options A := x.2.map fun a=>(a.1,mul (x.1,a.2)) +def scaleRealizer : Realizer (scale (A:=A)) := + (mapWith (pair second.fst (composition (pair first second.snd) mulRealizer))).congr (fun _=>rfl) +omit [Codec B] [Codec C] in +lemma polynomial_scale : PolynomialTime (scaleRealizer (A:=A)) := by + unfold scaleRealizer + apply polynomial_congr + exact polynomial_mapWith (polynomial_pair (polynomial_fst polynomial_second) + (polynomial_composition (polynomial_pair polynomial_first (polynomial_snd polynomial_second)) polynomial_mul)) + +def mix (x : Fraction×(Options A×Options A)) : Options A := + scale (x.1,x.2.1)++scale (sub ((1,1),x.1),x.2.2) +def mixRealizer : Realizer (mix (A:=A)) := composition + (pair (composition (pair first second.fst) scaleRealizer) + (composition (pair (composition (pair (constant (1,1)) first) subRealizer) second.snd) scaleRealizer)) append +omit [Codec B] [Codec C] in +lemma polynomial_mix : PolynomialTime (mixRealizer (A:=A)) := by + unfold mixRealizer + apply polynomial_composition _ polynomial_append + have := polynomial_scale (A:=A) + have := polynomial_sub + dsimp only [Realizer.fst, Realizer.snd] + tree_cost +omit [Codec A] [Codec B] [Codec C] in +lemma mix_repr (e : Ω→A) (p : ℚ) (hp : 0≤p) (hp1 : p≤1) (a b : WeightedOptions Ω) : + mix (TreeFraction.repr p,(repr e a,repr e b))=repr e (.mix p hp hp1 a b) := by + have h1 : (1,1)=TreeFraction.repr 1 := rfl + simp only [mix,scale,repr,List.map_ofFn,h1,sub_repr (by decide) hp hp1] + simp only [WeightedOptions.mix] + rw [List.ofFn_add] + apply congrArg₂ List.append <;> apply List.ofFn_inj.mpr <;> funext i + · change (e (a.out i),mul (TreeFraction.repr p,TreeFraction.repr (a.mass i))) = + (e (Fin.addCases a.out b.out (i.castAdd b.size)),TreeFraction.repr (Fin.addCases (fun i=>p*a.mass i) (fun i=>(1-p)*b.mass i) (i.castAdd b.size))) + simp only [Fin.addCases_left,mul_repr hp (a.nonneg i)] + · simp only [Function.comp_def,Fin.addCases_right] + rw [mul_repr (sub_nonneg.mpr hp1) (b.nonneg i)] + +def map (f : C×A→B) (x : C×Options A) : Options B := x.2.map fun a=>(f (x.1,a.1),a.2) +def mapRealizer {f : C×A→B} (F : Realizer f) : Realizer (map f) := + (mapWith (pair (composition (pair first second.fst) F) second.snd)).congr (fun _=>rfl) +lemma polynomial_map {f : C×A→B} {F : Realizer f} (hF : PolynomialTime F) : + PolynomialTime (mapRealizer F) := by + unfold mapRealizer + apply polynomial_congr + exact polynomial_mapWith (polynomial_pair (polynomial_composition + (polynomial_pair polynomial_first (polynomial_fst polynomial_second)) hF) (polynomial_snd polynomial_second)) +omit [Codec A] [Codec B] [Codec C] in +lemma map_repr {Ψ : Type} (e : Ω→A) (d : Ψ→B) (f : Ω→Ψ) (g : C×A→B) (z : C) + (h : ∀ a,g (z,e a)=d (f a)) (c : WeightedOptions Ω) : + map g (z,repr e c)=repr d (c.map f) := by + simp only [map,repr,List.map_ofFn] + apply List.ofFn_inj.mpr + funext i + simp only [WeightedOptions.map,Function.comp_apply,h] + +def draw (d : A) (x : Options A×List Bool) : A := + (x.1.map Prod.fst).getD (ExecutableChoice.chooseBits (x.1.map Prod.snd,x.2)) d +def drawRealizer (d : A) : Realizer (draw d) := by + let index : Realizer (fun x : Options A×List Bool=> + ExecutableChoice.chooseBits (x.1.map Prod.snd,x.2)) := + (composition (pair (composition first (TreeTyped.map second)) second) ExecutableChoice.chooseBitsFast).congr (fun _=>rfl) + exact (composition (pair (composition first (TreeTyped.map first)) index) (getDFast d)).congr (fun _=>rfl) +omit [Codec B] [Codec C] in +lemma polynomial_draw (d : A) : PolynomialTime (drawRealizer d) := by + unfold drawRealizer + dsimp only + apply polynomial_congr + have := ExecutableChoice.polynomial_chooseBitsFast + have := polynomial_getDFast d + tree_cost +omit [Codec A] [Codec B] [Codec C] in +lemma draw_repr [Fintype Ω] [DecidableEq Ω] (e : Ω→A) (c : WeightedOptions Ω) (d : A) + {k : ℕ} (bits : Fin k→Bool) : + draw d (repr e c,List.ofFn bits)=e (c.draw k bits) := by + simp only [draw,repr,List.map_ofFn,Function.comp_def] + rw [ExecutableChoice.chooseBits_eq c.mass c.nonneg c.total bits] + simp only [List.getD,List.getElem?_ofFn,(FiniteChoice.chooseBits c.mass c.total k bits).isLt, + ↓reduceDIte,Option.getD_some,WeightedOptions.draw] + +end MatchingFPRAS.ExecutableOptions + +end OAI diff --git a/lean/OAI/Combinatorics/MatchingCount/Sampling/TreeOptionsAccept.lean b/lean/OAI/Combinatorics/MatchingCount/Sampling/TreeOptionsAccept.lean new file mode 100644 index 0000000000000000000000000000000000000000..7b78da8725489a4b40617aabb41e59f3b071a7a3 --- /dev/null +++ b/lean/OAI/Combinatorics/MatchingCount/Sampling/TreeOptionsAccept.lean @@ -0,0 +1,69 @@ +import Mathlib +import OAI.Combinatorics.MatchingCount.Machines.TreeBottleneck +import OAI.Combinatorics.MatchingCount.Sampling.TreeOptions + +namespace OAI + +namespace MatchingFPRAS.ExecutableOptions +open TreeTyped TreeFraction + +variable {A C Ω : Type} [Codec A] [Codec C] + +def accept (p : C×A→Fraction) (x : (C×A)×Options A) : Options A := + (x.2.map fun a=>(a.1,mul (a.2,p (x.1.1,a.1))))++ + (x.2.map fun a=>(x.1.2,mul (a.2,sub ((1,1),p (x.1.1,a.1))))) +def acceptRealizer {p : C×A→Fraction} (P : Realizer p) : Realizer (accept p) := by + let probability : Realizer (fun x : (C×A)×(A×Fraction)=>p (x.1.1,x.2.1)) := + composition (pair first.fst second.fst) P + let yes := pair second.fst (composition (pair second.snd probability) mulRealizer) + let no := pair first.snd (composition (pair second.snd + (composition (pair (constant (1,1)) probability) subRealizer)) mulRealizer) + exact (composition (pair (mapWith yes) (mapWith no)) append).congr (fun _=>rfl) +lemma polynomial_accept {p : C×A→Fraction} {P : Realizer p} (hP : PolynomialTime P) : + PolynomialTime (acceptRealizer P) := by + unfold acceptRealizer + dsimp only [Realizer.fst,Realizer.snd] + apply polynomial_congr + have := polynomial_mul + have := polynomial_sub + tree_cost +omit [Codec A] [Codec C] in +lemma accept_repr [Codec A] [Codec C] (e : Ω→A) (p : C×A→Fraction) (z : C) (a : Ω) (c : WeightedOptions Ω) + (q : Ω→ℚ) (hq : ∀ a,0≤q a) (hq1 : ∀ a,q a≤1) + (he : ∀ a,p (z,e a)=TreeFraction.repr (q a)) : + accept p ((z,e a),repr e c)=repr e (c.accept a q hq hq1) := by + have h1 : (1,1)=TreeFraction.repr 1 := rfl + simp only [accept,repr,List.map_ofFn,h1] + simp only [WeightedOptions.accept] + rw [List.ofFn_add] + apply congrArg₂ List.append <;> apply List.ofFn_inj.mpr <;> funext i + · simp only [Function.comp_def,he] + change (e (c.out i),mul (TreeFraction.repr (c.mass i),TreeFraction.repr (q (c.out i)))) = + (e (Fin.addCases c.out (fun _=>a) (i.castAdd c.size)),TreeFraction.repr (Fin.addCases (fun i=>c.mass i*q (c.out i)) (fun i=>c.mass i*(1-q (c.out i))) (i.castAdd c.size))) + simp only [Fin.addCases_left,mul_repr (c.nonneg i) (hq _)] + · simp only [Function.comp_def,Fin.addCases_right,he] + rw [sub_repr (by decide) (hq _) (hq1 _),mul_repr (c.nonneg i) (sub_nonneg.mpr (hq1 _))] + +def metropolisProbability (w : C×A→Fraction) (x : (C×A)×A) : Fraction := + minimum ((1,1),div (w (x.1.1,x.2),w x.1)) +def metropolisProbabilityRealizer {w : C×A→Fraction} (W : Realizer w) : + Realizer (metropolisProbability w) := + (composition (pair (constant (1,1)) (composition (pair (composition (pair first.fst second) W) + (composition first W)) divRealizer)) minimumRealizer).congr (fun _=>rfl) +lemma polynomial_metropolisProbability {w : C×A→Fraction} {W : Realizer w} + (hW : PolynomialTime W) : PolynomialTime (metropolisProbabilityRealizer W) := by + unfold metropolisProbabilityRealizer Realizer.fst + apply polynomial_congr + have := polynomial_div + have := TreeFraction.polynomial_minimum + tree_cost +omit [Codec A] [Codec C] in +lemma metropolisProbability_repr [Codec A] [Codec C] (e : Ω→A) (w : C×A→Fraction) (z : C) + (q : Ω→ℚ) (hq : ∀ a,0≤q a) (he : ∀ a,w (z,e a)=TreeFraction.repr (q a)) (a b : Ω) : + metropolisProbability w ((z,e a),e b)=TreeFraction.repr (min 1 (q b/q a)) := by + unfold metropolisProbability + rw [he,he,div_repr (hq _) (hq _)] + exact minimum_repr (x:=1) (y:=q b/q a) (by decide) (div_nonneg (hq _) (hq _)) +end MatchingFPRAS.ExecutableOptions + +end OAI diff --git a/lean/OAI/Combinatorics/MatchingCount/Sampling/TreeOptionsFinite.lean b/lean/OAI/Combinatorics/MatchingCount/Sampling/TreeOptionsFinite.lean new file mode 100644 index 0000000000000000000000000000000000000000..9951fed80399d973c1d3a34f20593eaf42d80dc9 --- /dev/null +++ b/lean/OAI/Combinatorics/MatchingCount/Sampling/TreeOptionsFinite.lean @@ -0,0 +1,84 @@ +import Mathlib +import OAI.Combinatorics.MatchingCount.Sampling.TreeOptions + +namespace OAI + +namespace MatchingFPRAS.ExecutableOptions +open TreeTyped TreeFraction + +variable {A : Type} [Codec A] [LinearOrder A] + +def uniform (s : Finset A) : Options A := + (s.sort (·≤·)).map fun a=>(a,TreeFraction.normalize (1,s.card)) +def uniformRealizer : Realizer (uniform (A:=A)) := + (composition (pair (composition (pair (constant 1) finsetCard) normalizeRealizer) finsetList) + (mapWith (pair second first))).congr (fun _=>rfl) +lemma polynomial_uniform : PolynomialTime (uniformRealizer (A:=A)) := by + unfold uniformRealizer + apply polynomial_congr + have := polynomial_normalize + have := polynomial_mapWith (polynomial_pair (polynomial_second (A:=Fraction) (B:=A)) polynomial_first) + tree_cost +omit [Codec A] in +lemma numbering_ofFn (s : Finset A) : + List.ofFn (fun i=>(WeightedOptions.numbering s i).val)=s.sort (·≤·) := by + apply List.ext_getElem + · simp + · intro i hi _ + simp only [List.getElem_ofFn] + change s.orderEmbOfFin rfl ⟨i,by simpa using hi⟩ = (s.sort (·≤·))[i] + rw [Finset.orderEmbOfFin_apply] + rfl +omit [Codec A] in +lemma uniform_repr (s : Finset A) (hs : s.Nonempty) : + uniform s=repr id (WeightedOptions.uniform s hs) := by + unfold uniform repr + rw [←numbering_ofFn,List.map_ofFn] + apply List.ofFn_inj.mpr + funext i + simp only [WeightedOptions.uniform,id_eq] + simp only [Function.comp_def] + rw [normalize_repr] + congr 1 + simp only [val,Nat.cast_one,one_div] + +def neighbors (x : (A×Finset A)×ℕ) : Options A := + ((x.1.2.sort (·≤·)).map fun a=>(a,TreeFraction.normalize (1,x.2)))++ + [(x.1.1,sub ((1,1),TreeFraction.normalize (x.1.2.card,x.2)))] +def neighborsRealizer : Realizer (neighbors (A:=A)) := by + let headOptions : Realizer (fun x : (A×Finset A)×ℕ=> + (x.1.2.sort (·≤·)).map fun a=>(a,TreeFraction.normalize (1,x.2))) := + (composition (pair (composition (pair (constant 1) second) normalizeRealizer) + (composition first.snd finsetList)) (mapWith (pair second first))).congr (fun _=>rfl) + let tailOptions : Realizer (fun x : (A×Finset A)×ℕ=> + [(x.1.1,sub ((1,1),TreeFraction.normalize (x.1.2.card,x.2)))]) := + (composition (pair first.fst (composition (pair (constant (1,1)) + (composition (pair (composition first.snd finsetCard) second) normalizeRealizer)) subRealizer)) listSingleton).congr (fun _=>rfl) + exact (composition (pair headOptions tailOptions) append).congr (fun _=>rfl) +lemma polynomial_neighbors : PolynomialTime (neighborsRealizer (A:=A)) := by + unfold neighborsRealizer + dsimp only [Realizer.fst, Realizer.snd] + apply polynomial_congr + have := polynomial_normalize + have := polynomial_sub + have := polynomial_listSingleton (A:=A×Fraction) + have := polynomial_mapWith (polynomial_pair (polynomial_second (A:=Fraction) (B:=A)) polynomial_first) + tree_cost +omit [Codec A] in +lemma neighbors_repr (a : A) (s : Finset A) (d : ℕ) (hd : s.card≤d) : + neighbors ((a,s),d)=repr id (WeightedOptions.neighbors a s d hd) := by + have hsub : (s.card:ℚ)/d≤1 := by + by_cases hz : d=0 + · simp [hz] + · exact (div_le_one (by exact_mod_cast Nat.pos_of_ne_zero hz)).mpr (by exact_mod_cast hd) + have hn : TreeFraction.normalize (s.card,d)=TreeFraction.repr ((s.card:ℚ)/d) := normalize_repr _ + have hu : TreeFraction.normalize (1,d)=TreeFraction.repr ((d:ℚ)⁻¹) := by + simpa only [val,Nat.cast_one,one_div] using normalize_repr (1,d) + have h1 : (1,1)=TreeFraction.repr 1 := rfl + simp only [neighbors,repr,hn,hu,h1,sub_repr (by decide) (by positivity) hsub] + simp only [WeightedOptions.neighbors] + rw [List.ofFn_succ_last,←numbering_ofFn,List.map_ofFn] + simp only [Fin.lastCases_castSucc,Fin.lastCases_last,id_eq,Function.comp_def] +end MatchingFPRAS.ExecutableOptions + +end OAI diff --git a/lean/OAI/Combinatorics/MatchingCount/Sampling/TreeOptionsMaps.lean b/lean/OAI/Combinatorics/MatchingCount/Sampling/TreeOptionsMaps.lean new file mode 100644 index 0000000000000000000000000000000000000000..a06f8f4eaa13e137341e325f3f9908ad85c785ad --- /dev/null +++ b/lean/OAI/Combinatorics/MatchingCount/Sampling/TreeOptionsMaps.lean @@ -0,0 +1,37 @@ +import Mathlib +import OAI.Combinatorics.MatchingCount.Sampling.TreeOptionsFinite + +namespace OAI + +namespace MatchingFPRAS.ExecutableOptions +variable {A Ω : Type} [LinearOrder A] [LinearOrder Ω] +omit [LinearOrder A] [LinearOrder Ω] in +lemma repr_map (e : Ω→A) (c : WeightedOptions Ω) : + repr e c=(repr id c).map (fun a=>(e a.1,a.2)) := by + simp only [repr,List.map_ofFn,Function.comp_def,id_eq] + +lemma uniform_map (e : Ω↪oA) (s : Finset Ω) : + uniform (s.map e.toEmbedding)=(uniform s).map (fun a=>(e a.1,a.2)) := by + unfold uniform + rw [Finset.card_map,←Finset.map_sort (r:=fun x y : Ω=>x≤y) (r':=fun x y : A=>x≤y) + (f:=e.toEmbedding) (s:=s) (fun a _ b _=>(e.le_iff_le).symm)] + simp only [List.map_map,Function.comp_def] + rfl +lemma uniform_repr_map (e : Ω↪oA) (s : Finset Ω) (hs : s.Nonempty) : + uniform (s.map e.toEmbedding)=repr e (WeightedOptions.uniform s hs) := by + rw [uniform_map,uniform_repr s hs,repr_map e] + +lemma neighbors_map (e : Ω↪oA) (a : Ω) (s : Finset Ω) (d : ℕ) : + neighbors ((e a,s.map e.toEmbedding),d)= + (neighbors ((a,s),d)).map (fun a=>(e a.1,a.2)) := by + unfold neighbors + rw [Finset.card_map,←Finset.map_sort (r:=fun x y : Ω=>x≤y) (r':=fun x y : A=>x≤y) + (f:=e.toEmbedding) (s:=s) (fun a _ b _=>(e.le_iff_le).symm)] + simp only [List.map_map,List.map_append,List.map_cons,List.map_nil,Function.comp_def] + rfl +lemma neighbors_repr_map (e : Ω↪oA) (a : Ω) (s : Finset Ω) (d : ℕ) (hd : s.card≤d) : + neighbors ((e a,s.map e.toEmbedding),d)=repr e (WeightedOptions.neighbors a s d hd) := by + rw [neighbors_map,neighbors_repr a s d hd,repr_map e] +end MatchingFPRAS.ExecutableOptions + +end OAI diff --git a/lean/OAI/Combinatorics/MatchingCount/Sampling/TreePairStep.lean b/lean/OAI/Combinatorics/MatchingCount/Sampling/TreePairStep.lean new file mode 100644 index 0000000000000000000000000000000000000000..80406a58c18082569877c64572a0aa1b6c903749 --- /dev/null +++ b/lean/OAI/Combinatorics/MatchingCount/Sampling/TreePairStep.lean @@ -0,0 +1,109 @@ +import Mathlib +import OAI.Combinatorics.MatchingCount.Sampling.TreePairTable +import OAI.Combinatorics.MatchingCount.Sampling.TreeOptionsAccept +import OAI.Combinatorics.MatchingCount.Machines.TreeRationalWeight + +namespace OAI + +namespace MatchingFPRAS.TreeTyped.SparseProgram +open TreeTyped ExecutableOptions TreeFraction + +variable {E V C : Type} [Codec E] [Codec V] [Codec C] [LinearOrder E] [LinearOrder V] +attribute [local instance] Transport.Sparse.finsetOrder + +def pairStepTable (p : C×(E×V)→Bool) (q : C×(E×E)→Bool) (r : C×(E×(V×V))→Bool) + (t : C×(E×E)→Bool) (w z : C×E→Fraction) (x : PairInput C E V) : Options (PairState E) := + accept (metropolisProbability (pairWeight w z)) (((x.1.1,x.2),x.2),pairTable p q r t x) +def pairStepRealizer {p : C×(E×V)→Bool} {q : C×(E×E)→Bool} {r : C×(E×(V×V))→Bool} + {t : C×(E×E)→Bool} {w z : C×E→Fraction} + (P : Realizer p) (Q : Realizer q) (R : Realizer r) (T : Realizer t) (W : Realizer w) (Z : Realizer z) + (Eq : Realizer (fun x : E×E=>decide (x.1=x.2))) + (Le : Realizer (fun x : E×E=>decide (x.1≤x.2))) + (EqV : Realizer (fun x : V×V=>decide (x.1=x.2))) + (LeV : Realizer (fun x : V×V=>decide (x.1≤x.2))) : Realizer (pairStepTable p q r t w z) := + (composition (pair (pair (pair first.fst second) second) (pairTableRealizer P Q R T Eq Le EqV LeV)) + (acceptRealizer (metropolisProbabilityRealizer (pairWeightRealizer W Z)))).congr (fun _=>rfl) +lemma polynomial_pairStep {p : C×(E×V)→Bool} {q : C×(E×E)→Bool} {r : C×(E×(V×V))→Bool} + {t : C×(E×E)→Bool} {w z : C×E→Fraction} + {P : Realizer p} {Q : Realizer q} {R : Realizer r} {T : Realizer t} {W : Realizer w} {Z : Realizer z} + {Eq : Realizer (fun x : E×E=>decide (x.1=x.2))} + {Le : Realizer (fun x : E×E=>decide (x.1≤x.2))} + {EqV : Realizer (fun x : V×V=>decide (x.1=x.2))} + {LeV : Realizer (fun x : V×V=>decide (x.1≤x.2))} + (hP : PolynomialTime P) (hQ : PolynomialTime Q) (hR : PolynomialTime R) (hT : PolynomialTime T) + (hW : PolynomialTime W) (hZ : PolynomialTime Z) + (hE : PolynomialTime Eq) (hL : PolynomialTime Le) (hV : PolynomialTime EqV) (hlV : PolynomialTime LeV) : + PolynomialTime (pairStepRealizer P Q R T W Z Eq Le EqV LeV) := by + unfold pairStepRealizer Realizer.fst + apply polynomial_congr + have := polynomial_pairTable hP hQ hR hT hE hL hV hlV + have := polynomial_accept (polynomial_metropolisProbability (polynomial_pairWeight hW hZ)) + tree_cost + +def pairDraw (p : C×(E×V)→Bool) (q : C×(E×E)→Bool) (r : C×(E×(V×V))→Bool) + (t : C×(E×E)→Bool) (w z : C×E→Fraction) (x : PairInput C E V×List Bool) : PairState E := + draw (∅,∅) (pairStepTable p q r t w z x.1,x.2) +def pairDrawRealizer {p : C×(E×V)→Bool} {q : C×(E×E)→Bool} {r : C×(E×(V×V))→Bool} + {t : C×(E×E)→Bool} {w z : C×E→Fraction} + (P : Realizer p) (Q : Realizer q) (R : Realizer r) (T : Realizer t) (W : Realizer w) (Z : Realizer z) + (Eq : Realizer (fun x : E×E=>decide (x.1=x.2))) + (Le : Realizer (fun x : E×E=>decide (x.1≤x.2))) + (EqV : Realizer (fun x : V×V=>decide (x.1=x.2))) + (LeV : Realizer (fun x : V×V=>decide (x.1≤x.2))) : Realizer (pairDraw p q r t w z) := + (composition (pair (composition first (pairStepRealizer P Q R T W Z Eq Le EqV LeV)) second) + (drawRealizer (∅,∅))).congr (fun _=>rfl) +lemma polynomial_pairDraw {p : C×(E×V)→Bool} {q : C×(E×E)→Bool} {r : C×(E×(V×V))→Bool} + {t : C×(E×E)→Bool} {w z : C×E→Fraction} + {P : Realizer p} {Q : Realizer q} {R : Realizer r} {T : Realizer t} {W : Realizer w} {Z : Realizer z} + {Eq : Realizer (fun x : E×E=>decide (x.1=x.2))} + {Le : Realizer (fun x : E×E=>decide (x.1≤x.2))} + {EqV : Realizer (fun x : V×V=>decide (x.1=x.2))} + {LeV : Realizer (fun x : V×V=>decide (x.1≤x.2))} + (hP : PolynomialTime P) (hQ : PolynomialTime Q) (hR : PolynomialTime R) (hT : PolynomialTime T) + (hW : PolynomialTime W) (hZ : PolynomialTime Z) + (hE : PolynomialTime Eq) (hL : PolynomialTime Le) (hV : PolynomialTime EqV) (hlV : PolynomialTime LeV) : + PolynomialTime (pairDrawRealizer P Q R T W Z Eq Le EqV LeV) := by + unfold pairDrawRealizer + apply polynomial_congr + have := polynomial_pairStep hP hQ hR hT hW hZ hE hL hV hlV + have := polynomial_draw ((∅,∅) : PairState E) + tree_cost + +variable [Fintype E] [Fintype V] (ends : E→Sym2 V) +attribute [local instance] Transport.Sparse.pmOrder +variable (hloop : ∀ e,¬(ends e).IsDiag) (hpar : ∀ e,(Finset.univ.filter (fun f=>ends f=ends e)).card≤2) +variable (p : C×(E×V)→Bool) (q : C×(E×E)→Bool) (r : C×(E×(V×V))→Bool) + (t : C×(E×E)→Bool) (w z : C×E→Fraction) (c : C) + (hp : ∀ e v,p (c,(e,v))=decide (v∈ends e)) (hq : ∀ e f,q (c,(e,f))=decide (ends e=ends f)) + (hr : ∀ e v w,r (c,(e,(v,w)))=decide (ends e=s(v,w))) + (ht : ∀ e f,t (c,(e,f))=decide (∃ v,v∈ends e ∧ v∈ends f)) + (u v : E→ℚ) (hu : ∀ e,0v∈ends e)×Transport.PM (fun e v=>v∈ends e)) : + pairStepTable p q r t w z ((c,(Finset.univ,Finset.univ)),pairRepr ends a)= + ExecutableOptions.repr (pairRepr ends) (Transport.Sparse.pairStepTable ends hloop hpar u v hu hv a) := by + unfold pairStepTable + rw [pairTable_eq ends hloop hpar p q r t c hp hq hr ht] + unfold Transport.Sparse.pairStepTable WeightedOptions.metropolisChoice + refine accept_repr (pairRepr ends) (metropolisProbability (pairWeight w z)) (c,pairRepr ends a) a + (Transport.Sparse.pairTable ends hloop hpar a) _ _ _ ?_ + intro b + exact metropolisProbability_repr (pairRepr ends) (pairWeight w z) c _ + (fun b=>(Transport.Sparse.rationalPairWeight_pos ends u v hu hv b).le) + (pairWeight_repr ends w z c u v (fun e=>(hu e).le) (fun e=>(hv e).le) hw hz) a b +include hp hq hr ht hw hz in +omit [Codec E] [Codec V] [Codec C] in +lemma pairDraw_eq [Codec E] [Codec V] [Codec C] + (a : Transport.PM (fun e v=>v∈ends e)×Transport.PM (fun e v=>v∈ends e)) + {k : ℕ} (bits : Fin k→Bool) : + pairDraw p q r t w z (((c,(Finset.univ,Finset.univ)),pairRepr ends a),List.ofFn bits)= + pairRepr ends ((Transport.Sparse.pairStepTable ends hloop hpar u v hu hv a).draw k bits) := by + unfold pairDraw + rw [pairStep_eq ends hloop hpar p q r t w z c hp hq hr ht u v hu hv hw hz] + exact draw_repr _ _ _ bits +end MatchingFPRAS.TreeTyped.SparseProgram + +end OAI diff --git a/lean/OAI/Combinatorics/MatchingCount/Sampling/TreePairTable.lean b/lean/OAI/Combinatorics/MatchingCount/Sampling/TreePairTable.lean new file mode 100644 index 0000000000000000000000000000000000000000..34c65c2a83ee1088db40ee9584572aca00af09ec --- /dev/null +++ b/lean/OAI/Combinatorics/MatchingCount/Sampling/TreePairTable.lean @@ -0,0 +1,80 @@ +import Mathlib +import OAI.Combinatorics.MatchingCount.Tapes.TreeSparseNeighbors +import OAI.Combinatorics.MatchingCount.Graphs.TreeCycleTable + +namespace OAI + +namespace MatchingFPRAS.TreeTyped.SparseProgram +open TreeTyped ExecutableOptions + +variable {E V C : Type} [Codec E] [Codec V] [Codec C] [LinearOrder E] [LinearOrder V] +attribute [local instance] Transport.Sparse.finsetOrder +abbrev PairInput (C E V : Type) := (C×(Finset V×Finset E))×PairState E + +def pairTable (p : C×(E×V)→Bool) (q : C×(E×E)→Bool) (r : C×(E×(V×V))→Bool) + (t : C×(E×E)→Bool) (x : PairInput C E V) : Options (PairState E) := + mix ((1,3),(ExecutableOptions.map (fun y : Finset E×Finset E=>(y.2,y.1)) + (x.2.2,switchTable p r (x.1,x.2.1)), + mix ((1,2),(ExecutableOptions.map (fun y : Finset E×Finset E=>(y.2,y.1)) + (x.2.2,colorTable p q (x.1,x.2.1)),cycleTable t ((x.1.1,x.1.2.2),x.2))))) +def pairTableRealizer {p : C×(E×V)→Bool} {q : C×(E×E)→Bool} {r : C×(E×(V×V))→Bool} + {t : C×(E×E)→Bool} (P : Realizer p) (Q : Realizer q) (R : Realizer r) (T : Realizer t) + (Eq : Realizer (fun x : E×E=>decide (x.1=x.2))) + (Le : Realizer (fun x : E×E=>decide (x.1≤x.2))) + (EqV : Realizer (fun x : V×V=>decide (x.1=x.2))) + (LeV : Realizer (fun x : V×V=>decide (x.1≤x.2))) : Realizer (pairTable p q r t) := + (composition (pair (constant (1,3)) (pair + (composition (pair second.snd (composition (pair first second.fst) (switchTableRealizer P R Eq Le EqV LeV))) + (mapRealizer (pair second first))) + (composition (pair (constant (1,2)) (pair + (composition (pair second.snd (composition (pair first second.fst) (colorTableRealizer P Q Eq Le))) + (mapRealizer (pair second first))) + (composition (pair (pair first.fst first.snd.snd) second) (cycleTableRealizer T Eq Le)))) mixRealizer))) + mixRealizer).congr (fun _=>rfl) +lemma polynomial_pairTable {p : C×(E×V)→Bool} {q : C×(E×E)→Bool} {r : C×(E×(V×V))→Bool} + {t : C×(E×E)→Bool} {P : Realizer p} {Q : Realizer q} {R : Realizer r} {T : Realizer t} + {Eq : Realizer (fun x : E×E=>decide (x.1=x.2))} + {Le : Realizer (fun x : E×E=>decide (x.1≤x.2))} + {EqV : Realizer (fun x : V×V=>decide (x.1=x.2))} + {LeV : Realizer (fun x : V×V=>decide (x.1≤x.2))} + (hP : PolynomialTime P) (hQ : PolynomialTime Q) (hR : PolynomialTime R) (hT : PolynomialTime T) + (hE : PolynomialTime Eq) (hL : PolynomialTime Le) (hV : PolynomialTime EqV) (hlV : PolynomialTime LeV) : + PolynomialTime (pairTableRealizer P Q R T Eq Le EqV LeV) := by + unfold pairTableRealizer Realizer.fst Realizer.snd + apply polynomial_congr + have := polynomial_colorTable hP hQ hE hL + have := polynomial_switchTable hP hR hE hL hV hlV + have := polynomial_cycleTable hT hE hL + have := ExecutableOptions.polynomial_mix (A:=PairState E) + have := ExecutableOptions.polynomial_map (polynomial_pair + (polynomial_second (A:=Finset E) (B:=Finset E)) polynomial_first) + tree_cost + +variable [Fintype E] [Fintype V] (ends : E→Sym2 V) +attribute [local instance] Transport.Sparse.pmOrder +variable (hloop : ∀ e,¬(ends e).IsDiag) (hpar : ∀ e,(Finset.univ.filter (fun f=>ends f=ends e)).card≤2) +omit [Codec E] [Codec V] [Codec C] in +lemma pairTable_eq (p : C×(E×V)→Bool) (q : C×(E×E)→Bool) (r : C×(E×(V×V))→Bool) + (t : C×(E×E)→Bool) (c : C) + (hp : ∀ e v,p (c,(e,v))=decide (v∈ends e)) (hq : ∀ e f,q (c,(e,f))=decide (ends e=ends f)) + (hr : ∀ e v w,r (c,(e,(v,w)))=decide (ends e=s(v,w))) + (ht : ∀ e f,t (c,(e,f))=decide (∃ v,v∈ends e ∧ v∈ends f)) + (a : Transport.PM (fun e v=>v∈ends e)×Transport.PM (fun e v=>v∈ends e)) : + pairTable p q r t ((c,(Finset.univ,Finset.univ)),pairRepr ends a)= + repr (pairRepr ends) (Transport.Sparse.pairTable ends hloop hpar a) := by + unfold pairTable + simp only [pairRepr] + rw [switchTable_eq ends hloop hpar p r c hp hr,colorTable_eq ends hloop hpar p q c hp hq] + have hc:=cycleTable_eq ends t c ht a + rw [show pairRepr ends a=(a.1.val,a.2.val) from rfl] at hc + rw [hc] + rw [map_repr Subtype.val (pairRepr ends) (fun b=>(b,a.2)) _ a.2.val (fun _=>rfl), + map_repr Subtype.val (pairRepr ends) (fun b=>(b,a.2)) _ a.2.val (fun _=>rfl)] + have h3 : (1,3)=TreeFraction.repr ((1:ℚ)/3) := by norm_num [TreeFraction.repr] + have h2 : (1,2)=TreeFraction.repr ((1:ℚ)/2) := by norm_num [TreeFraction.repr] + rw [h3,h2] + rw [mix_repr _ _ (by norm_num) (by norm_num),mix_repr _ _ (by norm_num) (by norm_num)] + rfl +end MatchingFPRAS.TreeTyped.SparseProgram + +end OAI diff --git a/lean/OAI/Combinatorics/MatchingCount/Sampling/TreePrepareLadder.lean b/lean/OAI/Combinatorics/MatchingCount/Sampling/TreePrepareLadder.lean new file mode 100644 index 0000000000000000000000000000000000000000..45dc8706a53c8ffd47f9581714d9a4485d31c9e9 --- /dev/null +++ b/lean/OAI/Combinatorics/MatchingCount/Sampling/TreePrepareLadder.lean @@ -0,0 +1,111 @@ +import Mathlib +import OAI.Combinatorics.MatchingCount.Sampling.TreeNumericLadder +import OAI.Combinatorics.MatchingCount.Machines.TreeGuideTables + +namespace OAI + +namespace MatchingFPRAS.NumericLadder +open TreeTyped TreeFraction ExecutableLadder Polynomial TreeTyped.Numbered Replica.Ladder + +abbrev Prepared := (TierData×(List (ℕ×ℕ)×(Finset ℕ×Finset ℕ)))×RefreshSetup + +def prepareContext (x : Prepared) : Context := + ((((x.1.2.1,weightRows x.1.1),x.1.2.2),x.2),guideRows x.1.1) +def prepareContextRealizer : Realizer prepareContext := (pair + (pair (pair (pair first.snd.fst (composition first.fst weightRowsRealizer)) first.snd.snd) second) + (composition first.fst guideRowsRealizer)).congr (fun _=>rfl) +lemma polynomial_prepareContext : PolynomialTime prepareContextRealizer := by + unfold prepareContextRealizer + dsimp only [Realizer.fst,Realizer.snd] + apply polynomial_congr + have := polynomial_weightRows + have := polynomial_guideRows + tree_cost + +def baseTest (x : TierData×ℕ) : Bool := decide (x.2/x.1.2.1.length=x.1.1.2.length) +def baseTestRealizer : Realizer baseTest := (composition + (pair (composition (pair second (composition first.snd.fst listLength)) quotient) + (composition first.fst.snd listLength)) natEqual).congr (fun _=>rfl) +lemma polynomial_baseTest : PolynomialTime baseTestRealizer := by + unfold baseTestRealizer + dsimp only [Realizer.fst,Realizer.snd] + apply polynomial_congr + have := polynomial_quotient + tree_cost + +def baseSet (x : TierData) : Finset ℕ := (slotUniverse x).filter fun i=>baseTest (x,i) +def baseSetRealizer : Realizer baseSet := composition (pair identity slotUniverseRealizer) + (finsetFilterWith baseTestRealizer) +lemma polynomial_baseSet : PolynomialTime baseSetRealizer := by + unfold baseSetRealizer + exact polynomial_composition (TreeTyped.polynomial_pair polynomial_identity polynomial_slotUniverse) + (polynomial_finsetFilterWith polynomial_baseTest) +lemma baseSet_source (n : ℕ) (ft fq : List Bool) (ws : List Fraction) : + baseSet ((n,ft),(fq,ws))=Numbered.set (base ft.length fq.length) := by + rw [baseSet,slotUniverse_source] + ext j + simp only [Finset.mem_filter,Numbered.set,Finset.mem_map,Finset.mem_univ,true_and,Numbered.embedding] + constructor + · rintro ⟨⟨z,rfl⟩,h⟩ + refine ⟨z,?_,rfl⟩ + rw [mem_base] + simpa [baseTest,slot_index_div] using h + · rintro ⟨z,h,rfl⟩ + refine ⟨⟨z,rfl⟩,?_⟩ + simpa [baseTest,slot_index_div] using (mem_base z).mp h + +def prepareSetup (x : Prepared) : RunSetup Context ℕ ℕ := + ((prepareContext x,(slotUniverse x.1.1,baseSet x.1.1)),(slots x.1.1,x.1.2.2.2)) +def prepareSetupRealizer : Realizer prepareSetup := (pair + (pair prepareContextRealizer (pair (composition first.fst slotUniverseRealizer) + (composition first.fst baseSetRealizer))) + (pair (composition first.fst slotsRealizer) first.snd.snd.snd)).congr (fun _=>rfl) +lemma polynomial_prepareSetup : PolynomialTime prepareSetupRealizer := by + unfold prepareSetupRealizer + dsimp only [Realizer.fst,Realizer.snd] + apply polynomial_congr + have := polynomial_prepareContext + have := polynomial_slotUniverse + have := polynomial_baseSet + have := polynomial_slots + tree_cost + +def prepareState (x : Prepared×Finset ℕ) : RunState Context ℕ ℕ := + (prepareSetup x.1,(slots x.1.1.1).map (fun i=>(i,x.2))) +def prepareStateRealizer : Realizer prepareState := (pair (composition first prepareSetupRealizer) + (composition (pair second (composition first.fst.fst slotsRealizer)) (mapWith (pair second first)))).congr (fun _=>rfl) +lemma polynomial_prepareState : PolynomialTime prepareStateRealizer := by + unfold prepareStateRealizer + dsimp only [Realizer.fst,Realizer.snd] + apply polynomial_congr + have := polynomial_prepareSetup + have := polynomial_slots + tree_cost + +abbrev PreparedInput := List (List Bool×Bits)×(Prepared×Finset ℕ) +def preparedRun (x : PreparedInput) : RunState Context ℕ ℕ := execute (x.1,prepareState x.2) +def preparedRunRealizer : Realizer preparedRun := composition (pair first (composition second prepareStateRealizer)) executeRealizer +lemma polynomial_preparedRun : PolynomialTime preparedRunRealizer := by + unfold preparedRunRealizer + exact polynomial_composition (TreeTyped.polynomial_pair polynomial_first + (polynomial_composition polynomial_second polynomial_prepareState)) polynomial_execute + +def preparedTop (x : PreparedInput) : Finset ℕ := lookup ∅ ((preparedRun x).2,0) +def preparedTopRealizer : Realizer preparedTop := (composition + (pair (composition (composition preparedRunRealizer second) identity) (constant 0)) (lookupRealizer ∅ natEqual)).congr (fun _=>rfl) +lemma polynomial_preparedTop : PolynomialTime preparedTopRealizer := by + unfold preparedTopRealizer + apply polynomial_congr + have := polynomial_preparedRun + have := polynomial_lookup (∅ : Finset ℕ) polynomial_natEqual + tree_cost + +theorem preparedTop_post : ∃ p : Polynomial ℕ,∀ x : PreparedInput,∀ t : ℕ, + p.eval (TreePost.packed x).length≤t → ∀ coins : Fin t→Bool, + (run (TreePost.machine preparedTopRealizer.program) (TreePost.packed x) coins).state=none ∧ + (run (TreePost.machine preparedTopRealizer.program) (TreePost.packed x) coins).tape.right₀= + Turing.ListBlank.mk (TreePost.packed (preparedTop x)) := + TreePost.polynomial_compiles preparedTopRealizer polynomial_preparedTop +end MatchingFPRAS.NumericLadder + +end OAI diff --git a/lean/OAI/Combinatorics/MatchingCount/Sampling/TreePrepared.lean b/lean/OAI/Combinatorics/MatchingCount/Sampling/TreePrepared.lean new file mode 100644 index 0000000000000000000000000000000000000000..7a72fc6489acc8e78b92e7d3d3b2a10c4682758c --- /dev/null +++ b/lean/OAI/Combinatorics/MatchingCount/Sampling/TreePrepared.lean @@ -0,0 +1,80 @@ +import Mathlib +import OAI.Combinatorics.MatchingCount.Sampling.TreeLadder +import OAI.Combinatorics.MatchingCount.Sampling.TreePrepareLadder +import OAI.Combinatorics.MatchingCount.Algorithm.TreeReweight + +namespace OAI + +namespace MatchingFPRAS.NumericLadder +open TreeTyped TreeFraction ExecutableLadder Polynomial TreeTyped.Numbered Replica.Ladder UnitRefresh Transport + +attribute [local instance] Transport.sym2Order Transport.bagEdgeOrder Transport.bagEdgeFintype +attribute [local instance] UnitRefresh.Computable.allowedDec Transport.prodOrder Transport.sumOrder + +lemma execute_state {I : Type} [Fintype I] [LinearOrder I] [Inhabited I] + (hz : index (default : I)=0) (x : TypedInput I) : + (execute (numericInput x)).2=numericState (typedExecute x).2 := by + apply list_encode_injective (pair_encode_injective nat_encode_injective finsetNat_encode_injective) + have h:=TreePost.sameProgram_encode executeRealizer typedExecuteRealizer (typedExecute_program hz).symm + _ _ (numericInput_encode x) + exact (TreeData.Data.cons.inj h).2.trans (numericState_encode _).symm + +variable {V L : Type} [Fintype V] [LinearOrder V] [Fintype L] [LinearOrder L] +variable {bags : V→Finset L} +def sourcePrepared (rank : L→ℕ) (parent : L→Option L) (w : BagEdge bags→ℚ) + (a : ExecutableDP.Bags) (ft fq : List Bool) : Prepared := + ((((Fintype.card V,ft),(fq,List.ofFn (fun e=>TreeFraction.repr (w (orderedEnum _ e))))), + (List.ofFn (fun e=>ExecutablePair.endpointRep (orderedEnum (BagEdge bags) e).val.val.1), + (Numbered.set (Finset.univ : Finset V),Numbered.set (Finset.univ : Finset (BagEdge bags))))), + (ExecutableRefresh.storedCatalog (a,List.range (Fintype.card L)), + ((a,ExecutableDP.parentRep (numberedParent parent)),(Materialized.plan (numberedRank rank)).map Fin.val))) + +lemma prepareContext_source (rank : L→ℕ) (parent : L→Option L) (w : BagEdge bags→ℚ) + (hw : ∀ e,0≤w e) (a : ExecutableDP.Bags) (ft fq : List Bool) : + prepareContext (sourcePrepared rank parent w a ft fq)= + sourceContext (T:=ft.length) (q:=fq.length) rank parent w a := by + unfold prepareContext sourcePrepared + dsimp only + rw [weightRows_source w hw ft fq,guideRows_source] + rfl + +lemma slots_source (n : ℕ) (ft fq : List Bool) (ws : List Fraction) : + slots ((n,ft),(fq,ws))=(List.ofFn (orderedEnum (Slot ft.length fq.length))).map index := by + rw [List.map_ofFn] + exact range_slot_indices ft.length fq.length + +lemma prepareSetup_source + (rank : L→ℕ) (parent : L→Option L) (w : BagEdge bags→ℚ) + (hw : ∀ e,0≤w e) (a : ExecutableDP.Bags) (ft fq : List Bool) : + prepareSetup (sourcePrepared rank parent w a ft fq)=numericSetup + ((sourceContext (T:=ft.length) (q:=fq.length) rank parent w a,(Finset.univ,base ft.length fq.length)), + (List.ofFn (orderedEnum (Slot ft.length fq.length)),Numbered.set (Finset.univ : Finset (BagEdge bags)))) := by + unfold prepareSetup + rw [prepareContext_source rank parent w hw a ft fq] + dsimp only [sourcePrepared] + rw [slotUniverse_source,baseSet_source,slots_source] + rfl + +lemma prepareState_source (ft fq : List Bool) [Inhabited (Slot ft.length fq.length)] + (rank : L→ℕ) (parent : L→Option L) (w : BagEdge bags→ℚ) + (hw : ∀ e,0≤w e) (a : ExecutableDP.Bags) (M : BagPM bags) : + prepareState (sourcePrepared rank parent w a ft fq,Numbered.set M.val)= + (numericSetup ((sourceContext (T:=ft.length) (q:=fq.length) rank parent w a,(Finset.univ,base ft.length fq.length)), + (List.ofFn (orderedEnum (Slot ft.length fq.length)),Numbered.set (Finset.univ : Finset (BagEdge bags)))), + numericState (stateRep (List.ofFn (orderedEnum (Slot ft.length fq.length))) (fun _=>Numbered.set M.val))) := by + unfold prepareState + dsimp only + rw [prepareSetup_source rank parent w hw a ft fq] + refine Prod.ext rfl ?_ + dsimp only [sourcePrepared] + rw [slots_source] + simp only [numericState,stateRep,List.map_map,Function.comp_def] + +lemma lookup_numeric_state {I : Type} [Fintype I] [LinearOrder I] [Inhabited I] + (keys : List I) (f : I→Finset ℕ) (i : I) (hi : i∈keys) : + lookup ∅ (numericState (stateRep keys f),index i)=f i := by + simp only [numericState,stateRep,List.map_map,Function.comp_def] + exact lookup_image ∅ keys index f index_injective i hi +end MatchingFPRAS.NumericLadder + +end OAI diff --git a/lean/OAI/Combinatorics/MatchingCount/Sampling/TreePreparedMarked.lean b/lean/OAI/Combinatorics/MatchingCount/Sampling/TreePreparedMarked.lean new file mode 100644 index 0000000000000000000000000000000000000000..c32e0e8a14c7ce73aa8dbdcd416a81e6e71da37f --- /dev/null +++ b/lean/OAI/Combinatorics/MatchingCount/Sampling/TreePreparedMarked.lean @@ -0,0 +1,64 @@ +import Mathlib +import OAI.Combinatorics.MatchingCount.Sampling.TreePreparedTop +import OAI.Combinatorics.MatchingCount.Sampling.TreeNumericMarking + +namespace OAI + +namespace MatchingFPRAS.NumericMarking +open TreeTyped TreeFraction ExecutableLadder TreeTyped.Numbered UnitRefresh NumericLadder + +abbrev SampleContext := (Prepared×Finset ℕ)×Tables +abbrev SampleBits := List (List Bool×Bits)×StateTable ℕ (List Bool) +abbrev SampleInput := SampleContext×SampleBits + +def sample (x : SampleInput) : ExecutableMarking.Marks ℕ := + assign ((x.1.2,x.2.2),preparedTop (x.2.1,x.1.1)) +def sampleRealizer : Realizer sample := (composition (pair (pair first.snd second.snd) + (composition (pair second.fst first.fst) preparedTopRealizer)) assignRealizer).congr (fun _=>rfl) +lemma polynomial_sample : PolynomialTime sampleRealizer := by + unfold sampleRealizer Realizer.fst Realizer.snd + apply polynomial_congr + have := polynomial_preparedTop + have := polynomial_assign + tree_cost + +def sampleMany (x : SampleContext×List SampleBits) : List (ExecutableMarking.Marks ℕ) := + x.2.map (fun b=>sample (x.1,b)) +def sampleManyRealizer : Realizer sampleMany := mapWith sampleRealizer +lemma polynomial_sampleMany : PolynomialTime sampleManyRealizer := polynomial_mapWith polynomial_sample + +theorem sampleMany_post : ∃ p : Polynomial ℕ,∀ x : SampleContext×List SampleBits,∀ t : ℕ, + p.eval (TreePost.packed x).length≤t → ∀ coins : Fin t→Bool, + (run (TreePost.machine sampleManyRealizer.program) (TreePost.packed x) coins).state=none ∧ + (run (TreePost.machine sampleManyRealizer.program) (TreePost.packed x) coins).tape.right₀= + Turing.ListBlank.mk (TreePost.packed (sampleMany x)) := + TreePost.polynomial_compiles sampleManyRealizer polynomial_sampleMany + +open Replica.Ladder Transport + +attribute [local instance] Transport.sym2Order Transport.bagEdgeOrder Transport.bagEdgeFintype +attribute [local instance] UnitRefresh.Computable.allowedDec Transport.prodOrder Transport.sumOrder +variable {V L : Type} [Fintype V] [LinearOrder V] [Fintype L] [LinearOrder L] +variable {bags : V→Finset L} {G : SimpleGraph L} +variable (hbags : ∀ v,∀ a∈bags v,∀ b∈bags v,a=b ∨ G.Adj a b) (hG : G.IsAcyclic) +variable (rank : L→ℕ) (parent : L→Option L) +variable (hb : RankedBags bags rank parent) (hne : ∀ v,(bags v).Nonempty) +variable (hp : ∀ l p,parent l=some p → rank p(List.ofFn (bits i).1,localBitsRep (bits i).2)), + (List.ofFn (orderedEnum (BagEdge bags))).map (fun e=>(index e,List.ofFn (mb e)))))= + numericMarks (ladderRun hbags hG rank parent hb hne hp hq w M k n (fun _=>M) bits + (toLex ((0 : Fin (ft.length+1)),(⟨0,hq⟩ : Fin fq.length)))).val + (fun e=>(f e).draw km (mb e)) := by + rw [sample,preparedTop_source hbags hG rank parent hb hne hp ft fq hq w hw M a ha bits] + apply assign_rep + intro e + exact List.mem_ofFn.mpr ⟨(orderedEnum _).symm e,Equiv.apply_symm_apply _ _⟩ +end MatchingFPRAS.NumericMarking + +end OAI diff --git a/lean/OAI/Combinatorics/MatchingCount/Sampling/TreePreparedTop.lean b/lean/OAI/Combinatorics/MatchingCount/Sampling/TreePreparedTop.lean new file mode 100644 index 0000000000000000000000000000000000000000..7ff626ef9d3e95124d7453a114a8af2e9bfe292c --- /dev/null +++ b/lean/OAI/Combinatorics/MatchingCount/Sampling/TreePreparedTop.lean @@ -0,0 +1,83 @@ +import Mathlib +import OAI.Combinatorics.MatchingCount.Sampling.TreePrepared + +namespace OAI + +namespace MatchingFPRAS.NumericLadder +open TreeTyped TreeFraction ExecutableLadder Polynomial TreeTyped.Numbered Replica.Ladder UnitRefresh Transport + +attribute [local instance] Transport.sym2Order Transport.bagEdgeOrder Transport.bagEdgeFintype +attribute [local instance] UnitRefresh.Computable.allowedDec Transport.prodOrder Transport.sumOrder +variable {V L : Type} [Fintype V] [LinearOrder V] [Fintype L] [LinearOrder L] +variable {bags : V→Finset L} {G : SimpleGraph L} +variable (hbags : ∀ v,∀ a∈bags v,∀ b∈bags v,a=b ∨ G.Adj a b) (hG : G.IsAcyclic) +variable (rank : L→ℕ) (parent : L→Option L) +variable (hb : RankedBags bags rank parent) (hne : ∀ v,(bags v).Nonempty) +variable (hp : ∀ l p,parent l=some p → rank p(List.ofFn (bits i).1,localBitsRep (bits i).2)), + (sourcePrepared rank parent w a ft fq,Numbered.set M.val))= + Numbered.set (ladderRun hbags hG rank parent hb hne hp hq w M k n (fun _=>M) bits + (toLex ((0 : Fin (ft.length+1)),(⟨0,hq⟩ : Fin fq.length)))).val := by + let z : Slot ft.length fq.length := toLex ((0 : Fin (ft.length+1)),(⟨0,hq⟩ : Fin fq.length)) + let : Inhabited (Slot ft.length fq.length) := ⟨z⟩ + have hz : index (default : Slot ft.length fq.length)=0 := slot_default_zero _ _ hq + let keys := List.ofFn (orderedEnum (Slot ft.length fq.length)) + let setup := ((sourceContext (T:=ft.length) (q:=fq.length) rank parent w a, + ((Finset.univ : Finset (Slot ft.length fq.length)),base ft.length fq.length)), + (keys,Numbered.set (Finset.univ : Finset (BagEdge bags)))) + let tx : TypedInput (Slot ft.length fq.length) := + (List.ofFn (fun i=>(List.ofFn (bits i).1,localBitsRep (bits i).2)), + (setup,stateRep keys (fun _=>Numbered.set M.val))) + have hi : (List.ofFn (fun i=>(List.ofFn (bits i).1,localBitsRep (bits i).2)), + prepareState (sourcePrepared rank parent w a ft fq,Numbered.set M.val))=numericInput tx := by + refine Prod.ext rfl ?_ + exact prepareState_source ft fq rank parent w hw a M + unfold preparedTop preparedRun + dsimp only + rw [hi,execute_state hz] + have hr := source_run (T:=ft.length) (q:=fq.length) hbags hG rank parent hb hne hp hq w M a ha + (fun _=>M) bits + change typedExecute tx=(setup,stateRep keys (fun i=>Numbered.set + (ladderRun hbags hG rank parent hb hne hp hq w M k n (fun _=>M) bits i).val)) at hr + rw [hr] + change lookup ∅ (numericState (stateRep keys (fun i=>Numbered.set + (ladderRun hbags hG rank parent hb hne hp hq w M k n (fun _=>M) bits i).val)),0)=_ + have hz' : index z=0 := hz + have hmem : z∈keys := by + simp only [keys,List.mem_ofFn] + exact ⟨(orderedEnum _).symm z,Equiv.apply_symm_apply _ _⟩ + have hl := lookup_numeric_state keys (fun i=>Numbered.set + (ladderRun hbags hG rank parent hb hne hp hq w M k n (fun _=>M) bits i).val) z hmem + simpa only [hz'] using hl + +theorem source_preparedTop_post : ∃ p : Polynomial ℕ, + ∀ {V L : Type} [Fintype V] [LinearOrder V] [Fintype L] [LinearOrder L] + {bags : V→Finset L} {G : SimpleGraph L} + (hbags : ∀ v,∀ a∈bags v,∀ b∈bags v,a=b ∨ G.Adj a b) (hG : G.IsAcyclic) + (rank : L→ℕ) (parent : L→Option L) (hb : RankedBags bags rank parent) + (hne : ∀ v,(bags v).Nonempty) (hp : ∀ l p,parent l=some p → rank p(List.ofFn (bits i).1,localBitsRep (bits i).2)), + (sourcePrepared rank parent w a ft fq,Numbered.set M.val)) + p.eval (TreePost.packed x).length≤t → ∀ coins : Fin t→Bool, + (run (TreePost.machine preparedTopRealizer.program) (TreePost.packed x) coins).state=none ∧ + (run (TreePost.machine preparedTopRealizer.program) (TreePost.packed x) coins).tape.right₀= + Turing.ListBlank.mk (TreePost.packed (Numbered.set + (ladderRun hbags hG rank parent hb hne hp hq w M k n (fun _=>M) bits + (toLex ((0 : Fin (ft.length+1)),(⟨0,hq⟩ : Fin fq.length)))).val)) := by + obtain ⟨p,hp⟩:=preparedTop_post + refine ⟨p,fun {V L} _ _ _ _ {bags G} hbags hG rank parent hb hne hparent ft fq hq w hw M a ha {k n} bits t ht coins=>?_⟩ + have h:=hp (List.ofFn (fun i=>(List.ofFn (bits i).1,localBitsRep (bits i).2)), + (sourcePrepared rank parent w a ft fq,Numbered.set M.val)) t ht coins + rwa [preparedTop_source hbags hG rank parent hb hne hparent ft fq hq w hw M a ha bits] at h +end MatchingFPRAS.NumericLadder + +end OAI diff --git a/lean/OAI/Combinatorics/MatchingCount/Sampling/TreeProbe.lean b/lean/OAI/Combinatorics/MatchingCount/Sampling/TreeProbe.lean new file mode 100644 index 0000000000000000000000000000000000000000..95f88a663c5271c72fc7fa2bdca238b01a6ca39c --- /dev/null +++ b/lean/OAI/Combinatorics/MatchingCount/Sampling/TreeProbe.lean @@ -0,0 +1,95 @@ +import Mathlib +import OAI.Combinatorics.MatchingCount.Probability.Marking +import OAI.Combinatorics.MatchingCount.Machines.TreeWeightTable + +namespace OAI + +namespace MatchingFPRAS.ExecutableSource +open TreeTyped TreeFraction TreeTyped.Numbered ExecutableBottleneck ExecutableHierarchy ExecutableRefresh Enlargement RealGeometry + +attribute [local instance] NumberedHierarchy.labelOrder +attribute [local instance] Transport.sym2Order Transport.bagEdgeOrder Transport.bagEdgeFintype + +def centralKey (x : BagBuildInput×RawLogical) : Key := + sourceRealKey (x.1,(x.2,2*x.1.1.1.2.length)) +def centralKeyRealizer : Realizer centralKey := (composition + (pair first (pair second (composition (pair (constant 2) (composition first.fst.fst.snd listLength)) multiply))) + sourceRealKeyRealizer).congr (fun _=>rfl) +lemma polynomial_centralKey : PolynomialTime centralKeyRealizer := by + unfold centralKeyRealizer + apply polynomial_congr + have := polynomial_sourceRealKey + dsimp only [Realizer.fst,Realizer.snd] + tree_cost +lemma centralKey_source {n : ℕ} [Nontrivial (Fin n)] (hn : 2≤n) + (w : Fin n→Fin n→ℚ) (hw : ∀ i j,0≤w i j) (K : ℕ) + (e : LogicalEdge (Fin n)) : + centralKey ((((matrixRep w,List.replicate (2*K+2) false),List.range n),List.replicate (2*K) false),logicalRepr e)= + sourceKey (RationalSource.centralEdge w K e) := by + unfold centralKey + dsimp only + rw [List.length_replicate] + exact sourceRealKey_source hn w hw K (e,⟨2*(2*K+2),by omega⟩) + +def centralKeys (x : BagBuildInput) : List Key := + (logicalEdges x.1.2).map (fun e=>centralKey (x,e)) +def centralKeysRealizer : Realizer centralKeys := (rowsWith centralKeyRealizer + (composition (first (A:=BuildInput) (B:=List Bool)).snd logicalEdgesRealizer)).congr (fun _=>rfl) +lemma polynomial_centralKeys : PolynomialTime centralKeysRealizer := + polynomial_congr _ (polynomial_rowsWith polynomial_centralKey + (polynomial_composition (polynomial_snd polynomial_first) polynomial_logicalEdges)) +lemma mem_centralKeys {n : ℕ} [Nontrivial (Fin n)] (hn : 2≤n) + (w : Fin n→Fin n→ℚ) (hw : ∀ i j,0≤w i j) (K : ℕ) + (e : Transport.BagEdge (RationalSource.bags w K)) : + sourceKey e∈centralKeys (((matrixRep w,List.replicate (2*K+2) false),List.range n),List.replicate (2*K) false) ↔ + ∃ q,RationalSource.centralEdge w K q=e := by + unfold centralKeys + rw [List.mem_map] + constructor + · rintro ⟨q,hq,he⟩ + obtain ⟨a,rfl⟩:=logicalEdges_complete q hq + rw [centralKey_source hn w hw K] at he + exact ⟨a,sourceKey_injective he⟩ + · rintro ⟨q,rfl⟩ + exact ⟨logicalRepr q,logicalRepr_mem q,centralKey_source hn w hw K q⟩ + +def isCentral (x : BagBuildInput×Key) : Bool := decide (x.2∈centralKeys x.1) +def isCentralRealizer : Realizer isCentral := (composition + (pair second (composition first centralKeysRealizer)) + (contains (pairEqual (pairEqual natEqual natEqual) natEqual))).congr (by + intro x; apply Bool.eq_iff_iff.mpr; simp [isCentral]) +lemma polynomial_isCentral : PolynomialTime isCentralRealizer := + polynomial_congr _ (polynomial_composition (polynomial_pair polynomial_second + (polynomial_composition polynomial_first polynomial_centralKeys)) + (polynomial_contains (polynomial_pairEqual (polynomial_pairEqual polynomial_natEqual polynomial_natEqual) polynomial_natEqual))) + +def probePart (x : (BagBuildInput×ℕ)×Key) : Fraction := + if isCentral (x.1.1,x.2) then TreeFraction.div ((1,1),(x.1.2,1)) else (0,1) +def probePartRealizer : Realizer probePart := (choose + (composition (pair first.fst second) isCentralRealizer) + (composition (pair (constant (1,1)) (pair first.snd (constant 1))) divRealizer) + (constant (0,1))).congr (fun _=>rfl) +lemma polynomial_probePart : PolynomialTime probePartRealizer := by + unfold probePartRealizer + apply polynomial_congr + have := polynomial_isCentral + have := polynomial_div + dsimp only [Realizer.fst,Realizer.snd] + tree_cost +lemma probePart_source {n : ℕ} [Nontrivial (Fin n)] (hn : 2≤n) + (w : Fin n→Fin n→ℚ) (hw : ∀ i j,0≤w i j) (K D : ℕ) + (e : Transport.BagEdge (RationalSource.bags w K)) : + probePart (((((matrixRep w,List.replicate (2*K+2) false),List.range n),List.replicate (2*K) false),D),sourceKey e)= + TreeFraction.repr (RationalSource.probePortion w K D e) := by + unfold probePart isCentral + dsimp only + simp only [decide_eq_true_eq,RationalSource.probePortion] + simp only [mem_centralKeys hn w hw K] + split_ifs + · have hD : ((D,1) : Fraction)=TreeFraction.repr (D:ℚ) := by simp [TreeFraction.repr] + rw [hD] + exact div_repr (by decide : (0:ℚ)≤1) (Nat.cast_nonneg D) + · rfl +end MatchingFPRAS.ExecutableSource + +end OAI diff --git a/lean/OAI/Combinatorics/MatchingCount/Sampling/TreeSamplerRows.lean b/lean/OAI/Combinatorics/MatchingCount/Sampling/TreeSamplerRows.lean new file mode 100644 index 0000000000000000000000000000000000000000..767ecf164d0d03d527028db05983778877a22e4e --- /dev/null +++ b/lean/OAI/Combinatorics/MatchingCount/Sampling/TreeSamplerRows.lean @@ -0,0 +1,96 @@ +import Mathlib +import OAI.Combinatorics.MatchingCount.Sampling.TreeFastSample + +namespace OAI + +namespace MatchingFPRAS.ExecutableDP +lemma context_rows {a b : Bags} (h : List.Forall₂ List.Perm a b) (ps : Parents) (l : ℕ) (t : Table) : + context ((a,ps),(l,t))=context ((b,ps),(l,t)) := by + simp only [context,privateNumber_rows h,sharedNumber_rows h,totalNumber_rows h] +lemma cappedUpdate_rows {a b as bs : Bags} (h : List.Forall₂ List.Perm a b) + (ho : List.Forall₂ List.Perm as bs) (ps : Parents) (ls : List ℕ) (l r : ℕ) (t : Table) : + cappedUpdate ((((as,ps),ls),((a,ps),(l,t))),r)= + cappedUpdate ((((bs,ps),ls),((b,ps),(l,t))),r) := by + simp only [cappedUpdate,tabulate,cappedEntry,capBits,BInitial,nVertices,nLabels,nPlan, + updateRows,updateColumns,rawEntry,context_rows h,ho.length_eq] +lemma runCapped_rows {a b as bs : Bags} (h : List.Forall₂ List.Perm a b) + (ho : List.Forall₂ List.Perm as bs) (ps : Parents) (ls ks : List ℕ) (t : Table) : + (runCapped ((as,ps),ls) ks a t).2=(runCapped ((bs,ps),ls) ks b t).2 := by + induction ks generalizing a b t with + | nil=>rfl + | cons k ks ih=> + simp only [runCapped,cappedUpdate_rows h ho] + exact ih (trim_rows h k) _ +lemma cappedCount_rows {a b : Bags} (h : List.Forall₂ List.Perm a b) (ps : Parents) (ls : List ℕ) : + cappedCount ((a,ps),ls)=cappedCount ((b,ps),ls) := by + rw [cappedCount_run,cappedCount_run] + simp only [nLabels,BInitial,nVertices,h.length_eq,runCapped_rows h h] +lemma rows_getD {a b : Bags} (h : List.Forall₂ List.Perm a b) (i : ℕ) : + (a.getD i []).Perm (b.getD i []) := by + induction h generalizing i with + | nil=>exact List.Perm.refl [] + | @cons a b as bs hab _hs ih=> + cases i with + | zero=>exact hab + | succ i=>exact ih i +end MatchingFPRAS.ExecutableDP + +namespace MatchingFPRAS.ExecutableUnit +open ExecutableDP + +lemma residual_rows {a b : Bags} (h : List.Forall₂ List.Perm a b) (v : ℕ) : + List.Forall₂ List.Perm (residual (a,v)) (residual (b,v)) := by + unfold residual + rw [h.length_eq] + apply List.forall₂_map_right_iff.mpr + apply List.forall₂_map_left_iff.mpr + generalize List.range (b.length-2)=is + induction is with + | nil=>exact .nil + | cons i is ih=>exact .cons (rows_getD h _) ih +lemma valid_rows {a b : Bags} (h : List.Forall₂ List.Perm a b) (ps : Parents) (ls : List ℕ) (e : ℕ×ℕ) : + valid (((a,ps),ls),e)=valid (((b,ps),ls),e) := by + simp only [valid,h.length_eq,(rows_getD h _).mem_iff] +lemma fastBranch_rows {a b : Bags} (h : List.Forall₂ List.Perm a b) (ps : Parents) (ls : List ℕ) (v : ℕ) : + fastBranch (((a,ps),ls),v)=fastBranch (((b,ps),ls),v) := + cappedCount_rows (residual_rows h v) ps ls +lemma fastEdgeCount_rows {a b : Bags} (h : List.Forall₂ List.Perm a b) (ps : Parents) (ls : List ℕ) (e : ℕ×ℕ) : + fastEdgeCount (((a,ps),ls),e)=fastEdgeCount (((b,ps),ls),e) := by + simp only [fastEdgeCount,valid_rows h,fastBranch_rows h] +lemma fastProbabilities_rows {a b : Bags} (h : List.Forall₂ List.Perm a b) (ps : Parents) (ls : List ℕ) : + fastProbabilities ((a,ps),ls)=fastProbabilities ((b,ps),ls) := by + simp only [fastProbabilities,fastProbability,h.length_eq,fastEdgeCount_rows h,cappedCount_rows h] +lemma fastDraw_rows {a b : Bags} (h : List.Forall₂ List.Perm a b) (ps : Parents) (ls : List ℕ) (bits : List Bool) : + fastDraw (((a,ps),ls),bits)=fastDraw (((b,ps),ls),bits) := by + simp only [fastDraw,fastProbabilities_rows h] +lemma fastSelected_rows {a b : Bags} (h : List.Forall₂ List.Perm a b) (ps : Parents) (ls : List ℕ) (bits : Bits) : + fastSelected (((a,ps),ls),bits)=fastSelected (((b,ps),ls),bits) := by + simp only [fastSelected,h.length_eq,fastDraw_rows h] +lemma clippedAssemble_cap {as bs : Bags} (h : as.length=bs.length) (ps : Parents) (ls : List ℕ) (x : Frame×Result) : + clippedAssemble (((as,ps),ls),x)=clippedAssemble (((bs,ps),ls),x) := by + simp only [clippedAssemble,clippedAt,capacity,h] +lemma fastRawSample_rows {as bs : Bags} (ho : List.Forall₂ List.Perm as bs) + (ps : Parents) (ls : List ℕ) (f : ℕ) {a b : Bags} (h : List.Forall₂ List.Perm a b) (bits : Bits) : + fastRawSample ((as,ps),ls) f ((a,ps),ls) bits=fastRawSample ((bs,ps),ls) f ((b,ps),ls) bits := by + induction f generalizing a b with + | zero=>rfl + | succ f ih=> + simp only [fastRawSample,h.length_eq,fastSelected_rows h,nextContext] + split_ifs + · rw [ih (residual_rows h _),clippedAssemble_cap ho.length_eq] + · rfl +lemma fastSample_rows {a b : Bags} (h : List.Forall₂ List.Perm a b) (ps : Parents) (ls : List ℕ) (bits : Bits) : + fastSample (((a,ps),ls),bits)=fastSample (((b,ps),ls),bits) := by + simp only [fastSample,h.length_eq,fastRawSample_rows h ps ls _ h] +lemma fastSample_represented {n m k : ℕ} (bags : Fin n → Finset (Fin m)) + (rank : Fin m → ℕ) (parent : Fin m → Option (Fin m)) + (hb : UnitRefresh.RankedBags bags rank parent) (hne : ∀ x,(bags x).Nonempty) + (hp : ∀ l p,parent l=some p → rank pList.ofFn (bits i)))= + resultRep (UnitRefresh.Materialized.sampleUnit k n bags rank parent hb hne hp hz bits) := by + rw [fastSample_rows h,fastSample_eq bags rank parent hb hne hp hz bits] +end MatchingFPRAS.ExecutableUnit + +end OAI diff --git a/lean/OAI/Combinatorics/MatchingCount/Sampling/TreeScan.lean b/lean/OAI/Combinatorics/MatchingCount/Sampling/TreeScan.lean new file mode 100644 index 0000000000000000000000000000000000000000..de3dd4e548b5fce5ed203d1a468f77053e8dbd64 --- /dev/null +++ b/lean/OAI/Combinatorics/MatchingCount/Sampling/TreeScan.lean @@ -0,0 +1,60 @@ +import Mathlib +import OAI.Combinatorics.MatchingCount.Sampling.TreeScanChoice +import OAI.Combinatorics.MatchingCount.Sampling.TreeLocalSampler + +namespace OAI + +namespace MatchingFPRAS.ExecutableLadder +open TreeTyped ExecutableOptions + +variable {I A B C : Type} [Codec I] [Codec A] [Codec B] [Codec C] +variable [LinearOrder I] [Inhabited I] [Inhabited A] +attribute [local instance] Transport.prodOrder Transport.sumOrder +local instance treeScanUpdateInhabited : Inhabited (Replica.Update I) := ⟨Sum.inr default⟩ +abbrev ScanInput (C I A B : Type) := (ScanSetup C I×StateTable I A)×(List Bool×B) + +def scan (g : C×(I×I)→Bool) (p : LocalPairInput C I A B→A×A) + (r : LocalRefreshInput C I B→A) (x : ScanInput C I A B) : StateTable I A := + localSampler p r ((x.1.1.1,(x.1.2,x.2.2)),draw none (scanChoice g x.1.1,x.2.1)) +def scanRealizer {g : C×(I×I)→Bool} {p : LocalPairInput C I A B→A×A} + {r : LocalRefreshInput C I B→A} (G : Realizer g) (P : Realizer p) (R : Realizer r) + (E : Realizer (fun x : I×I=>decide (x.1=x.2))) + (L : Realizer (fun x : I×I=>decide (x.1≤x.2))) : Realizer (scan g p r) := + (composition (pair (pair first.fst.fst (pair first.snd second.snd)) + (composition (pair (composition first.fst (scanChoiceRealizer G E L)) second.fst) (drawRealizer none))) + (localSamplerRealizer P R E)).congr (fun _=>rfl) +lemma polynomial_scan {g : C×(I×I)→Bool} {p : LocalPairInput C I A B→A×A} + {r : LocalRefreshInput C I B→A} {G : Realizer g} {P : Realizer p} {R : Realizer r} + {E : Realizer (fun x : I×I=>decide (x.1=x.2))} + {L : Realizer (fun x : I×I=>decide (x.1≤x.2))} + (hG : PolynomialTime G) (hP : PolynomialTime P) (hR : PolynomialTime R) + (hE : PolynomialTime E) (hL : PolynomialTime L) : PolynomialTime (scanRealizer G P R E L) := by + unfold scanRealizer Realizer.fst Realizer.snd + apply polynomial_congr + have := polynomial_scanChoice hG hE hL + have := polynomial_draw (none : Option (Replica.Update I)) + have := polynomial_localSampler hP hR hE + tree_cost + +variable {Ω D : Type} [Fintype I] [Fintype Ω] [DecidableEq Ω] [Fintype D] [Nonempty D] +variable (e : Ω→A) (d : D→B) (c : C) (keys : List I) (hk : ∀ i,i∈keys) +variable (guides : I→Finset I) (base : Finset I) (hb : base.Nonempty) +variable (g : C×(I×I)→Bool) (hg : ∀ i j,g (c,(i,j))=decide (j∈guides i)) +variable (p : LocalPairInput C I A B→A×A) (r : LocalRefreshInput C I B→A) +variable (sp : I→I→(Ω×Ω)→D→Ω×Ω) (sr : I→D→Ω) + (hp : ∀ i j a b,p ((c,(i,j)),((e a.1,e a.2),d b))=(e (sp i j a b).1,e (sp i j a b).2)) + (hr : ∀ i b,r ((c,i),d b)=e (sr i b)) +omit [Codec I] [Codec A] [Codec B] [Codec C] [Inhabited I] in +include hp hr hk hg in +lemma scan_rep {k : ℕ} (s : I→Ω) (bs : Fin k→Bool) (b : D) : + scan g p r (((c,(Finset.univ,base)),stateRep keys (e ∘ s)),(List.ofFn bs,d b))= + stateRep keys (e ∘ Replica.sampleScan guides base hb sp sr k s (bs,b)) := by + unfold scan + rw [scanChoice_eq guides base hb g c hg] + have hh := draw_repr id (Replica.scanChoice guides base hb) (none : Option (Replica.Update I)) bs + dsimp only [id_eq] at hh + rw [hh] + exact localSampler_rep e d c keys hk p r sp sr hp hr s _ b +end MatchingFPRAS.ExecutableLadder + +end OAI diff --git a/lean/OAI/Combinatorics/MatchingCount/Sampling/TreeScanChoice.lean b/lean/OAI/Combinatorics/MatchingCount/Sampling/TreeScanChoice.lean new file mode 100644 index 0000000000000000000000000000000000000000..98342701d872f66ba8767f68ca39f553c7fe6103 --- /dev/null +++ b/lean/OAI/Combinatorics/MatchingCount/Sampling/TreeScanChoice.lean @@ -0,0 +1,111 @@ +import Mathlib +import OAI.Combinatorics.MatchingCount.Sampling.TreeOptionsFinite +import OAI.Combinatorics.MatchingCount.Machines.TreeLabelTable +import OAI.Combinatorics.MatchingCount.Machines.TreeQuad +import OAI.Combinatorics.MatchingCount.Machines.TreeSum + +namespace OAI + +namespace MatchingFPRAS.ExecutableLadder +open TreeTyped ExecutableOptions + +variable {I C : Type} [Codec I] [Codec C] [Inhabited I] [LinearOrder I] +attribute [local instance] Transport.prodOrder Transport.sumOrder +local instance : Inhabited (Replica.Update I) := ⟨Sum.inr default⟩ +abbrev ScanSetup (C I : Type) := C×(Finset I×Finset I) + +def updateList (g : C×(I×I)→Bool) (x : ScanSetup C I) : List (Replica.Update I) := + (((x.2.1.sort (·≤·)).product (x.2.1.sort (·≤·))).filter (fun ij=>g (x.1,ij))).map Sum.inl++ + (x.2.2.sort (·≤·)).map Sum.inr + +def updateListRealizer {g : C×(I×I)→Bool} (G : Realizer g) : Realizer (updateList g) := by + let xs : Realizer (fun x : ScanSetup C I=>x.2.1.sort (·≤·)) := (composition second.fst finsetList).congr (fun _=>rfl) + let ps := composition (pair xs xs) listProduct + let good := composition (pair first ps) (filterWith G) + exact (composition (pair (composition good (TreeTyped.map inl)) + (composition (composition second.snd finsetList) (TreeTyped.map inr))) append).congr (fun _=>rfl) +lemma polynomial_updateList {g : C×(I×I)→Bool} {G : Realizer g} (hG : PolynomialTime G) : + PolynomialTime (updateListRealizer G) := by + unfold updateListRealizer + dsimp only [Realizer.fst, Realizer.snd] + apply polynomial_congr + have := polynomial_listProduct (A:=I) (B:=I) + have := polynomial_filterWithList hG + have := polynomial_inl (A:=I×I) (B:=I) + have := polynomial_inr (A:=I×I) (B:=I) + tree_cost + +def updateEqual (E : Realizer (fun x : I×I=>decide (x.1=x.2))) : + Realizer (fun x : Replica.Update I×Replica.Update I=>@decide (x.1=x.2) (LinearOrder.toDecidableEq x.1 x.2)) := + (sumEqual (pairEqual E E) E).congr (by + intro x; apply Bool.eq_iff_iff.mpr; simp only [decide_eq_true_eq]) +omit [Codec C] in +lemma polynomial_updateEqual {E : Realizer (fun x : I×I=>decide (x.1=x.2))} (hE : PolynomialTime E) : + PolynomialTime (updateEqual E) := + polynomial_congr _ (polynomial_sumEqual (polynomial_pairEqual hE hE) hE) + +def updateSetRealizer {g : C×(I×I)→Bool} (G : Realizer g) + (E : Realizer (fun x : I×I=>decide (x.1=x.2))) + (R : Realizer (fun x : I×I=>decide (x.1≤x.2))) : + Realizer (fun x=> (updateList g x).toFinset) := + (composition (updateListRealizer G) + (listFinset (updateEqual E) (sumLexLe (lexLe E R R) R))).congr (by intro x; ext a; simp) +lemma polynomial_updateSet {g : C×(I×I)→Bool} {G : Realizer g} + {E : Realizer (fun x : I×I=>decide (x.1=x.2))} + {R : Realizer (fun x : I×I=>decide (x.1≤x.2))} + (hG : PolynomialTime G) (hE : PolynomialTime E) (hR : PolynomialTime R) : + PolynomialTime (updateSetRealizer G E R) := by + unfold updateSetRealizer + apply polynomial_congr + exact polynomial_composition (polynomial_updateList hG) + (polynomial_listFinset (polynomial_updateEqual hE) + (polynomial_sumLexLe (polynomial_lexLe hE hR hR) hR)) + +def scanChoice (g : C×(I×I)→Bool) (x : ScanSetup C I) : Options (Option (Replica.Update I)) := + mix ((1,2),(pure none,ExecutableOptions.map (fun x : Bool×Replica.Update I=>Option.some x.2) + (false,uniform (updateList g x).toFinset))) +def scanChoiceRealizer {g : C×(I×I)→Bool} (G : Realizer g) + (E : Realizer (fun x : I×I=>decide (x.1=x.2))) + (R : Realizer (fun x : I×I=>decide (x.1≤x.2))) : Realizer (scanChoice g) := + (composition (pair (constant (1,2)) (pair (composition (constant none) pureRealizer) + (composition (pair (constant false) (composition (updateSetRealizer G E R) uniformRealizer)) + (mapRealizer (composition second TreeTyped.some))))) mixRealizer).congr (fun _=>rfl) +lemma polynomial_scanChoice {g : C×(I×I)→Bool} {G : Realizer g} + {E : Realizer (fun x : I×I=>decide (x.1=x.2))} + {R : Realizer (fun x : I×I=>decide (x.1≤x.2))} + (hG : PolynomialTime G) (hE : PolynomialTime E) (hR : PolynomialTime R) : + PolynomialTime (scanChoiceRealizer G E R) := by + unfold scanChoiceRealizer + apply polynomial_congr + have := polynomial_updateSet hG hE hR + have := polynomial_uniform (A:=Replica.Update I) + have := polynomial_pure (A:=Option (Replica.Update I)) + have := polynomial_mix (A:=Option (Replica.Update I)) + have := ExecutableOptions.polynomial_map (polynomial_composition (polynomial_second (A:=Bool) (B:=Replica.Update I)) (polynomial_some (A:=Replica.Update I))) + tree_cost + +variable [Fintype I] +variable (guides : I→Finset I) (base : Finset I) (hb : base.Nonempty) +variable (g : C×(I×I)→Bool) (c : C) (hg : ∀ i j,g (c,(i,j))=decide (j∈guides i)) +omit [Codec I] [Codec C] [Inhabited I] in +include hg in +lemma updateSet_eq : (updateList g (c,(Finset.univ,base))).toFinset=Replica.updates guides base := by + ext u + cases u with + | inl ij => rcases ij with ⟨i,j⟩; simp [updateList,Replica.updates,hg] + | inr i => simp [updateList,Replica.updates] +omit [Codec I] [Codec C] [Inhabited I] in +include hg in +lemma scanChoice_eq : scanChoice g (c,(Finset.univ,base))= + ExecutableOptions.repr id (Replica.scanChoice guides base hb) := by + unfold scanChoice Replica.scanChoice + rw [updateSet_eq guides base g c hg,uniform_repr _ (Replica.updates_nonempty guides base hb)] + rw [map_repr id id Option.some (fun x : Bool×Replica.Update I=>Option.some x.2) false (fun _=>rfl)] + have hp := pure_repr (id : Option (Replica.Update I)→_) (none : Option (Replica.Update I)) + dsimp only [id_eq] at hp + rw [hp] + have hh : (1,2)=TreeFraction.repr (1/2:ℚ) := by norm_num [TreeFraction.repr] + rw [hh,mix_repr id (1/2) (by norm_num) (by norm_num)] +end MatchingFPRAS.ExecutableLadder + +end OAI diff --git a/lean/OAI/Combinatorics/MatchingCount/Sampling/TreeScanRun.lean b/lean/OAI/Combinatorics/MatchingCount/Sampling/TreeScanRun.lean new file mode 100644 index 0000000000000000000000000000000000000000..28d041d3bfb088bc263ae7b2339c17e01ff9b2ac --- /dev/null +++ b/lean/OAI/Combinatorics/MatchingCount/Sampling/TreeScanRun.lean @@ -0,0 +1,113 @@ +import Mathlib +import OAI.Combinatorics.MatchingCount.Sampling.TreeScan +import OAI.Combinatorics.MatchingCount.Arithmetic.TreeStateNormalize + +namespace OAI + +namespace MatchingFPRAS.ExecutableLadder +open TreeTyped Polynomial + +variable {I E B C : Type} [Codec I] [Codec E] [Codec B] [Codec C] +variable [LinearOrder I] [Inhabited I] [LinearOrder E] +attribute [local instance] Transport.prodOrder Transport.sumOrder +local instance treeScanRunUpdateInhabited : Inhabited (Replica.Update I) := ⟨Sum.inr default⟩ +abbrev RunSetup (C I E : Type) := ScanSetup C I×StateEnvelope I E +abbrev RunState (C I E : Type) := RunSetup C I E×StateTable I (Finset E) + +def runStep (g : C×(I×I)→Bool) (p : LocalPairInput C I (Finset E) B→Finset E×Finset E) + (r : LocalRefreshInput C I B→Finset E) (x : (List Bool×B)×RunState C I E) : RunState C I E := + (x.2.1,normalizeState (x.2.1.2,scan g p r ((x.2.1.1,x.2.2),x.1))) +def runStepRealizer {g : C×(I×I)→Bool} {p : LocalPairInput C I (Finset E) B→Finset E×Finset E} + {r : LocalRefreshInput C I B→Finset E} (G : Realizer g) (P : Realizer p) (R : Realizer r) + (Eq : Realizer (fun x : I×I=>decide (x.1=x.2))) + (Le : Realizer (fun x : I×I=>decide (x.1≤x.2))) + (EqE : Realizer (fun x : E×E=>decide (x.1=x.2))) : Realizer (runStep g p r) := + (pair second.fst (composition (pair second.fst.snd + (composition (pair (pair second.fst.fst second.snd) first) (scanRealizer G P R Eq Le))) + (normalizeStateRealizer Eq EqE))).congr (fun _=>rfl) +lemma polynomial_runStep {g : C×(I×I)→Bool} {p : LocalPairInput C I (Finset E) B→Finset E×Finset E} + {r : LocalRefreshInput C I B→Finset E} {G : Realizer g} {P : Realizer p} {R : Realizer r} + {Eq : Realizer (fun x : I×I=>decide (x.1=x.2))} + {Le : Realizer (fun x : I×I=>decide (x.1≤x.2))} + {EqE : Realizer (fun x : E×E=>decide (x.1=x.2))} + (hG : PolynomialTime G) (hP : PolynomialTime P) (hR : PolynomialTime R) + (hEq : PolynomialTime Eq) (hLe : PolynomialTime Le) (hE : PolynomialTime EqE) : + PolynomialTime (runStepRealizer G P R Eq Le EqE) := by + unfold runStepRealizer Realizer.fst Realizer.snd + apply polynomial_congr + have := polynomial_scan hG hP hR hEq hLe + have := polynomial_normalizeState hEq hE + tree_cost + +omit [Codec I] [Codec E] [Codec B] [Codec C] [Inhabited I] in +lemma fold_runStep {g : C×(I×I)→Bool} {p : LocalPairInput C I (Finset E) B→Finset E×Finset E} + {r : LocalRefreshInput C I B→Finset E} (bs : List (List Bool×B)) (c : RunSetup C I E) + (s : StateTable I (Finset E)) : + bs.foldl (fun z b=>runStep g p r (b,z)) (c,s)= + (c,bs.foldl (fun t b=>normalizeState (c.2,scan g p r ((c.1,t),b))) s) := by + induction bs generalizing s with + | nil=>rfl + | cons b bs ih=>exact ih _ + +omit [Codec B] [Codec C] [Inhabited I] in +lemma fold_normalized_weight {g : C×(I×I)→Bool} {p : LocalPairInput C I (Finset E) B→Finset E×Finset E} + {r : LocalRefreshInput C I B→Finset E} (bs : List (List Bool×B)) (c : RunSetup C I E) + (s : StateTable I (Finset E)) : + weight (bs.foldl (fun t b=>normalizeState (c.2,scan g p r ((c.1,t),b))) s)≤ + max (weight s) ((weight c.2.1+1)*(weight c.2.2+3)) := by + induction bs generalizing s with + | nil=>exact le_max_left _ _ + | cons b bs ih=> + exact (ih _).trans (max_le (le_trans (normalizeState_weight _ _ _) (le_max_right _ _)) (le_max_right _ _)) + +lemma polynomial_scanRun {g : C×(I×I)→Bool} {p : LocalPairInput C I (Finset E) B→Finset E×Finset E} + {r : LocalRefreshInput C I B→Finset E} {G : Realizer g} {P : Realizer p} {R : Realizer r} + {Eq : Realizer (fun x : I×I=>decide (x.1=x.2))} + {Le : Realizer (fun x : I×I=>decide (x.1≤x.2))} + {EqE : Realizer (fun x : E×E=>decide (x.1=x.2))} + (hG : PolynomialTime G) (hP : PolynomialTime P) (hR : PolynomialTime R) + (hEq : PolynomialTime Eq) (hLe : PolynomialTime Le) (hE : PolynomialTime EqE) : + PolynomialTime (fold (runStepRealizer G P R Eq Le EqE)) := by + apply polynomial_fold (polynomial_runStep hG hP hR hEq hLe hE) (2*X+(X+1)*(X+3)) + intro _ ⟨c,s⟩ pre _ _ + rw [fold_runStep,weight_prod] + have h:=fold_normalized_weight (g:=g) (p:=p) (r:=r) pre c s + simp only [eval_mul,eval_add,eval_X,eval_one,eval_ofNat,weight_prod] + have hm : max (weight s) ((weight c.2.1+1)*(weight c.2.2+3))≤ + weight s+(weight c.2.1+1)*(weight c.2.2+3) := max_le (by omega) (by omega) + have hc1 : weight c.2.1≤weight c := by rcases c with ⟨a,⟨k,u⟩⟩; simp only [weight_prod]; omega + have hc2 : weight c.2.2≤weight c := by rcases c with ⟨a,⟨k,u⟩⟩; simp only [weight_prod]; omega + have hp : (weight c.2.1+1)*(weight c.2.2+3)≤(weight c+1)*(weight c+3) := Nat.mul_le_mul (by omega) (by omega) + calc + _ ≤ 1+weight c+weight s+(weight c+1)*(weight c+3) := by omega + _ ≤ _ := Nat.add_le_add (by omega) (Nat.mul_le_mul (by omega) (by omega)) + +variable {Ω D : Type} [Fintype I] [Fintype Ω] [DecidableEq Ω] [Fintype D] [Nonempty D] +variable (e : Ω→Finset E) (d : D→B) (c : C) (keys : List I) (hk : ∀ i,i∈keys) + (univ : Finset E) (he : ∀ a,e a⊆univ) +variable (guides : I→Finset I) (base : Finset I) (hb : base.Nonempty) +variable (g : C×(I×I)→Bool) (hg : ∀ i j,g (c,(i,j))=decide (j∈guides i)) +variable (p : LocalPairInput C I (Finset E) B→Finset E×Finset E) (r : LocalRefreshInput C I B→Finset E) +variable (sp : I→I→(Ω×Ω)→D→Ω×Ω) (sr : I→D→Ω) + (hp : ∀ i j a b,p ((c,(i,j)),((e a.1,e a.2),d b))=(e (sp i j a b).1,e (sp i j a b).2)) + (hr : ∀ i b,r ((c,i),d b)=e (sr i b)) +omit [Codec I] [Codec E] [Codec B] [Codec C] [Inhabited I] in +include hp hr hk hg he in +lemma scanRun_rep {k n : ℕ} (s : I→Ω) (bs : Fin n→((Fin k→Bool)×D)) : + (List.ofFn (fun i=>(List.ofFn (bs i).1,d (bs i).2))).foldl + (fun z b=>runStep g p r (b,z)) (((c,(Finset.univ,base)),(keys,univ)),stateRep keys (e ∘ s))= + (((c,(Finset.univ,base)),(keys,univ)),stateRep keys + (e ∘ Variation.runSample (Replica.sampleScan guides base hb sp sr k) s n bs)) := by + induction n with + | zero=>rfl + | succ n ih=> + rw [List.ofFn_succ_last,List.foldl_append] + change runStep g p r ((List.ofFn (bs (Fin.last n)).1,d (bs (Fin.last n)).2),_)=_ + rw [ih (fun i=>bs i.castSucc)] + unfold runStep + rw [scan_rep e d c keys hk guides base hb g hg p r sp sr hp hr, + normalizeState_rep keys univ e he] + rfl +end MatchingFPRAS.ExecutableLadder + +end OAI diff --git a/lean/OAI/Combinatorics/MatchingCount/Sampling/TreeUnitAssemble.lean b/lean/OAI/Combinatorics/MatchingCount/Sampling/TreeUnitAssemble.lean new file mode 100644 index 0000000000000000000000000000000000000000..fea9ab1b89ff256a8c79192fea908a437569aefd --- /dev/null +++ b/lean/OAI/Combinatorics/MatchingCount/Sampling/TreeUnitAssemble.lean @@ -0,0 +1,103 @@ +import Mathlib +import OAI.Combinatorics.MatchingCount.Sampling.TreeUnitBranch + +namespace OAI + +namespace MatchingFPRAS.UnitRefresh +lemma removePair_last_symm_val {n : ℕ} (b : Fin (n+2)) (hb : b≠Fin.last (n+1)) + (x : withoutPair (Fin.last (n+1)) b) : + ((removePairEquiv (Fin.last (n+1)) b hb).symm x).val = + if x.val.valx.val.val) (e.apply_symm_apply x) + change (e j).val.val=_ at hj + rw [hx] at hj + change j.val=_ + by_cases h : j.val simp only [h,↓reduceIte] at hj + · rw [ite_eq_left (by omega)] + omega + · rw [ite_eq_right (by omega)] + omega +end MatchingFPRAS.UnitRefresh + +namespace MatchingFPRAS.ExecutableUnit +open TreeTyped ExecutableDP + +abbrev Result := List (ℕ×ℕ) +abbrev Frame := ℕ×(ℕ×ℕ) + +def unskip (x : ℕ×ℕ) : ℕ := if x.1by simp [unskip]) + +def assembleAt (x : (Frame×Result)×ℕ) : ℕ×ℕ := + let n:=x.1.1.1 + let b:=x.1.1.2.1 + let c:=x.1.1.2.2 + let i:=x.2 + if i=n+1 then (b,c) else if i=b then (n+1,c) else + let z:=x.1.2.getD (unskip (i,b)) (0,0) + (skip (z.1,b),z.2) +def assembleAtRealizer : Realizer assembleAt := by + let n : Realizer (fun x : (Frame×Result)×ℕ=>x.1.1.1) := first.fst.fst + let b : Realizer (fun x : (Frame×Result)×ℕ=>x.1.1.2.1) := first.fst.snd.fst + let c : Realizer (fun x : (Frame×Result)×ℕ=>x.1.1.2.2) := first.fst.snd.snd + let i : Realizer (fun x : (Frame×Result)×ℕ=>x.2) := second + let a := composition n successor + let j := composition (pair i b) unskipRealizer + let z := composition (pair first.snd j) (getD (0,0)) + let r := pair (composition (pair z.fst b) skipRealizer) z.snd + exact (choose (composition (pair i a) natEqual) (pair b c) + (choose (composition (pair i b) natEqual) (pair a c) r)).congr (by intro x; simp [assembleAt]) + +def assemble (x : Frame×Result) : Result := + (List.range (x.1.1+2)).map (fun i=>assembleAt (x,i)) +def assembleRealizer : Realizer assemble := by + let n : Realizer (fun x : Frame×Result=>x.1.1+2) := + (composition (pair first.fst (constant 2)) add).congr (fun _=>rfl) + exact (composition (pair identity (composition n range)) (mapWith assembleAtRealizer)).congr (fun _=>rfl) + +noncomputable def resultRep {n m : ℕ} {bags : Fin n → Finset (Fin m)} + (p : UnitRefresh.ColoredPairing bags) : Result := List.ofFn (fun i=>(p.pair.mate i |>.val,p.color i |>.val)) + +lemma resultRep_getD {n m : ℕ} {bags : Fin n → Finset (Fin m)} + (p : UnitRefresh.ColoredPairing bags) (i : Fin n) : + (resultRep p).getD i.val (0,0)=((p.pair.mate i).val,(p.color i).val) := by + simp [resultRep,List.getD] + +lemma assemble_eq {n m : ℕ} (bags : Fin (n+2) → Finset (Fin m)) + (c : UnitRefresh.Partner bags (Fin.last (n+1))) + (p : UnitRefresh.ColoredPairing (fun i=>bags (UnitRefresh.removePairEquiv (Fin.last (n+1)) c.val.1 c.property.1 i).val)) : + assemble ((n,(c.val.1.val,c.val.2.val)),resultRep p)= + resultRep ((UnitRefresh.ColoredPairing.map (UnitRefresh.residualBags bags (Fin.last (n+1)) c.val.1) + (UnitRefresh.removePairEquiv (Fin.last (n+1)) c.val.1 c.property.1) p).insert (Fin.last (n+1)) c) := by + rw [assemble,map_range_ofFn] + apply List.ofFn_inj.mpr + funext i + let e := UnitRefresh.removePairEquiv (Fin.last (n+1)) c.val.1 c.property.1 + change assembleAt (((n,(c.val.1.val,c.val.2.val)),resultRep p),i.val)=_ + by_cases ha : i=Fin.last (n+1) + · subst i + simp only [assembleAt,Fin.val_last,↓reduceIte,UnitRefresh.ColoredPairing.insert, + UnitRefresh.Pairing.insert,↓reduceDIte,true_or] + by_cases hb : i=c.val.1 + · subst i + have han : c.val.1.val≠n+1 := by intro he; exact ha (Fin.ext he) + simp only [assembleAt,han,↓reduceIte,UnitRefresh.ColoredPairing.insert, + UnitRefresh.Pairing.insert,ha,↓reduceDIte,or_true,Fin.val_last] + · let x : UnitRefresh.withoutPair (Fin.last (n+1)) c.val.1 := ⟨i,ha,hb⟩ + have hi : i.val≠n+1 := by intro he; exact ha (Fin.ext he) + have hi' : i.val≠c.val.1.val := by intro he; exact hb (Fin.ext he) + have hj : unskip (i.val,c.val.1.val)=(e.symm x).val := + (UnitRefresh.removePair_last_symm_val c.val.1 c.property.1 x).symm + simp only [assembleAt,hi,hi',↓reduceIte,hj,resultRep_getD, + UnitRefresh.ColoredPairing.insert,UnitRefresh.Pairing.insert,ha,hb,↓reduceDIte,or_self] + change (skip ((p.pair.mate (e.symm x)).val,c.val.1.val),(p.color (e.symm x)).val)= + ((e (p.pair.mate (e.symm x))).val.val,(p.color (e.symm x)).val) + rw [UnitRefresh.removePair_last_val] + rfl +end MatchingFPRAS.ExecutableUnit + +end OAI diff --git a/lean/OAI/Combinatorics/MatchingCount/Sampling/TreeUnitBranch.lean b/lean/OAI/Combinatorics/MatchingCount/Sampling/TreeUnitBranch.lean new file mode 100644 index 0000000000000000000000000000000000000000..0c5828053ca2c31d8049e94bde717021805e3623 --- /dev/null +++ b/lean/OAI/Combinatorics/MatchingCount/Sampling/TreeUnitBranch.lean @@ -0,0 +1,133 @@ +import Mathlib +import OAI.Combinatorics.MatchingCount.Sampling.Plan +import OAI.Combinatorics.MatchingCount.Sampling.TreeDPRepresentation + +namespace OAI + +namespace MatchingFPRAS.UnitRefresh +lemma gapEquiv_val {n : ℕ} (a : Fin (n+1)) (i : Fin n) : + (gapEquiv a i).val=a.succAbove i := rfl +lemma removePair_last_val {n : ℕ} (b : Fin (n+2)) (hb : b≠Fin.last (n+1)) (i : Fin n) : + (removePairEquiv (Fin.last (n+1)) b hb i).val.val=if i.valx.val.val) (e.apply_symm_apply ⟨b,hb⟩) + simpa only [e,gapEquiv_val,Fin.succAbove_last,Fin.val_castSucc] using h + change ((gapEquiv (Fin.last (n+1)) (gapEquiv b' i).val).val).val=_ + rw [gapEquiv_val,Fin.succAbove_last,Fin.val_castSucc,gapEquiv_val] + by_cases hi : i.valby simp [skip]) + +def residual (x : Bags×ℕ) : Bags := + (List.range (x.1.length-2)).map (fun i=>x.1.getD (skip (i,x.2)) []) +def residualRealizer : Realizer residual := by + let p : Realizer (fun x : (Bags×ℕ)×ℕ=>(x.1.1,skip (x.2,x.1.2))) := + pair first.fst (composition (pair second first.snd) skipRealizer) + let n : Realizer (fun x : Bags×ℕ=>x.1.length-2) := composition (pair (composition first listLength) (constant 2)) subtract + exact (composition (pair identity (composition n range)) + (mapWith (composition p (getD ([] : Bag))))).congr (fun _=>rfl) + +lemma residual_ordered {n m : ℕ} (bags : Fin (n+2) → Finset (Fin m)) + (b : Fin (n+2)) (hb : b≠Fin.last (n+1)) : + residual (orderedRep bags,b.val)= + orderedRep (fun i=>bags (UnitRefresh.removePairEquiv (Fin.last (n+1)) b hb i).val) := by + unfold residual orderedRep + simp only [List.length_ofFn, Nat.add_sub_cancel] + rw [map_range_ofFn] + apply List.ofFn_inj.mpr + funext i + have hv := UnitRefresh.removePair_last_val b hb i + have hl : skip (i.val,b.val) omega + simp only [List.getD,List.getElem?_ofFn,hl,↓reduceDIte,Option.getD_some] + congr 2 + apply Fin.ext + exact hv.symm + +abbrev Context := CountInput + +def valid (x : Context×(ℕ×ℕ)) : Bool := + let bs:=x.1.1.1 + let b:=x.2.1 + let c:=x.2.2 + decide (b≠bs.length-1) && decide (c∈bs.getD (bs.length-1) []) && decide (c∈bs.getD b []) + +def validRealizer : Realizer valid := by + let bs : Realizer (fun x : Context×(ℕ×ℕ)=>x.1.1.1) := first.fst.fst + let b : Realizer (fun x : Context×(ℕ×ℕ)=>x.2.1) := second.fst + let c : Realizer (fun x : Context×(ℕ×ℕ)=>x.2.2) := second.snd + let a := composition (composition bs listLength) predecessor + let ba := composition (pair bs a) (getD ([] : Bag)) + let bb := composition (pair bs b) (getD ([] : Bag)) + let p := composition (composition (pair b a) natEqual) boolNot + let q := composition (pair ba c) membership + let r := composition (pair bb c) membership + exact (composition (pair (composition (pair p q) boolAnd) r) boolAnd).congr (by intro x; simp [valid]) + +def branch (x : Context×ℕ) : ℕ := + count ((residual (x.1.1.1,x.2),x.1.1.2),x.1.2) +def branchRealizer : Realizer branch := + (composition (pair (pair (composition (pair first.fst.fst second) residualRealizer) first.fst.snd) + first.snd) countRealizer).congr (fun _=>rfl) + +def edgeCount (x : Context×(ℕ×ℕ)) : ℕ := if valid x then branch (x.1,x.2.1) else 0 +def edgeCountRealizer : Realizer edgeCount := + (choose validRealizer (composition (pair first second.fst) branchRealizer) (constant 0)).congr (fun _=>rfl) + +lemma branch_eq {n m : ℕ} (bags : Fin (n+2) → Finset (Fin m)) + (rank : Fin m → ℕ) (parent : Fin m → Option (Fin m)) + (hb : UnitRefresh.RankedBags bags rank parent) (hne : ∀ x,(bags x).Nonempty) + (hp : ∀ l p,parent l=some p → rank pbags (e i).val) rank parent := fun v l hl r hr=>hb (e v).val l hl r hr + rw [UnitRefresh.Materialized.computable_count_eq _ rank parent hbe (fun i=>hne (e i).val) hp] + rw [Fintype.card_congr (UnitRefresh.ColoredPairing.equiv (UnitRefresh.residualBags bags (Fin.last (n+1)) b) e)] + exact (UnitRefresh.Materialized.branchCount_eq bags rank parent hb hne hp _ _).symm + +lemma valid_eq {n m : ℕ} (bags : Fin (n+2) → Finset (Fin m)) + (ps : Parents) (ls : List ℕ) (b : Fin (n+2)) (c : Fin m) : + valid (((orderedRep bags,ps),ls),(b.val,c.val))= + decide (UnitRefresh.Materialized.validBranch bags (Fin.last (n+1)) (b,c)) := by + have ha : n+2-1=n+1 := by omega + have hget (i : Fin (n+2)) : (orderedRep bags).getD i.val []=bagRep (bags i) := by + simp only [orderedRep,List.getD,List.getElem?_ofFn,i.isLt,↓reduceDIte,Option.getD_some] + have hgeta : (orderedRep bags).getD (n+1) []=bagRep (bags (Fin.last (n+1))) := hget (Fin.last (n+1)) + apply Bool.eq_iff_iff.mpr + simp only [valid,show (orderedRep bags).length=n+2 from List.length_ofFn,ha, + hgeta,hget,Bool.and_eq_true,decide_eq_true_eq,mem_bagRep, + UnitRefresh.Materialized.validBranch] + constructor + · rintro ⟨⟨hb,hc⟩,hd⟩ + apply decide_eq_true + exact ⟨by intro he; exact hb (congrArg Fin.val he),hc,hd⟩ + · intro h + have hh := of_decide_eq_true h + exact ⟨⟨by intro he; exact hh.1 (Fin.ext he),hh.2.1⟩,hh.2.2⟩ + +lemma edgeCount_eq {n m : ℕ} (bags : Fin (n+2) → Finset (Fin m)) + (rank : Fin m → ℕ) (parent : Fin m → Option (Fin m)) + (hb : UnitRefresh.RankedBags bags rank parent) (hne : ∀ x,(bags x).Nonempty) + (hp : ∀ l p,parent l=some p → rank p + cases n with + | zero => + cases fuel <;> simp [rawSample,orderedRep,resultRep] + | succ n => + cases n with + | zero => + have hzero := singleton_count_zero bags rank parent hb hne hp + omega + | succ n => + let a : Fin (n+2) := Fin.last (n+1) + let c := drawEdge bags rank parent hb hne hp a hz k (bits a) + let bags' := remainingBags bags a c.val + have hb' := remainingRanked bags rank parent hb a c.val + have hne' := remainingNonempty bags hne a c.val + have hz' := remainingPositive bags rank parent hb hne hp a c + let bits' : Fin n → Fin k → Bool := fun i=>bits i.castSucc.castSucc + have hbits' : ∀ i : Fin n,bs.getD i.val []=List.ofFn (bits' i) := + fun i=>hbs i.castSucc.castSucc + have hc := selected_eq_of_getD bags rank parent hb hne hp hz bits bs (hbs a) + change selected (((orderedRep bags,parentRep parent),(plan rank).map Fin.val),bs)= + (c.val.val.1.val,c.val.val.2.val) at hc + have hnext : nextContext (((orderedRep bags,parentRep parent),(plan rank).map Fin.val), + (c.val.val.1.val,c.val.val.2.val))= + ((orderedRep bags',parentRep parent),(plan rank).map Fin.val) := by + unfold nextContext + rw [residual_ordered bags c.val.val.1 c.val.property.1] + rfl + cases fuel with + | zero => omega + | succ fuel => + have hr := ih n (by omega) bags' hb' hne' hz' bits' hbits' fuel (by omega) + have hl : (orderedRep bags).length=n+2 := List.length_ofFn + rw [rawSample] + simp only [hl,show 2≤n+2 by omega,↓reduceIte,hc,hnext,Nat.add_sub_cancel] + rw [hr] + rw [sampleUnit_step] + exact assemble_eq bags c.val _ + +lemma sample_eq {n m k : ℕ} (bags : Fin n → Finset (Fin m)) + (rank : Fin m → ℕ) (parent : Fin m → Option (Fin m)) + (hb : UnitRefresh.RankedBags bags rank parent) (hne : ∀ x,(bags x).Nonempty) + (hp : ∀ l p,parent l=some p → rank pList.ofFn (bits i)))= + resultRep (sampleUnit k n bags rank parent hb hne hp hz bits) := by + unfold sample + apply rawSample_eq n bags rank parent hb hne hp hz bits + · intro i + simp only [List.getD,List.getElem?_ofFn,i.isLt,↓reduceDIte,Option.getD_some] + · simp only [orderedRep,List.length_ofFn,le_refl] +end MatchingFPRAS.ExecutableUnit + +end OAI diff --git a/lean/OAI/Combinatorics/MatchingCount/Sampling/TreeUnitDraw.lean b/lean/OAI/Combinatorics/MatchingCount/Sampling/TreeUnitDraw.lean new file mode 100644 index 0000000000000000000000000000000000000000..dd8fcf105eeedc452b88d1a3afbcdf34cfda93a5 --- /dev/null +++ b/lean/OAI/Combinatorics/MatchingCount/Sampling/TreeUnitDraw.lean @@ -0,0 +1,77 @@ +import Mathlib +import OAI.Combinatorics.MatchingCount.Sampling.TreeUnitBranch +import OAI.Combinatorics.MatchingCount.Sampling.TreeCategoricalValues + +namespace OAI + +namespace MatchingFPRAS.ExecutableUnit +open TreeTyped ExecutableDP TreeFraction + +def decodeIndex (x : ℕ×ℕ) : ℕ×ℕ := (x.1/x.2,x.1%x.2) +def decodeIndexRealizer : Realizer decodeIndex := division + +def probability (x : Context×ℕ) : Fraction := + (edgeCount (x.1,decodeIndex (x.2,x.1.1.2.length)),count x.1) +def probabilityRealizer : Realizer probability := by + let m : Realizer (fun x : Context×ℕ=>x.1.1.2.length) := composition first.fst.snd listLength + let bc := composition (pair second m) decodeIndexRealizer + exact (pair (composition (pair first bc) edgeCountRealizer) + (composition first countRealizer)).congr (fun _=>rfl) + +def probabilities (x : Context) : List Fraction := + (List.range (x.1.1.length*x.1.2.length)).map (fun i=>probability (x,i)) +def probabilitiesRealizer : Realizer probabilities := by + let n : Realizer (fun x : Context=>x.1.1.length) := composition first.fst listLength + let m : Realizer (fun x : Context=>x.1.2.length) := composition first.snd listLength + exact (composition (pair identity (composition (composition (pair n m) multiply) range)) + (mapWith probabilityRealizer)).congr (fun _=>rfl) + +def draw (x : Context×List Bool) : ℕ×ℕ := + decodeIndex (ExecutableChoice.chooseBits (probabilities x.1,x.2),x.1.1.2.length) +def drawRealizer : Realizer draw := + (composition (pair (composition (pair (composition first probabilitiesRealizer) second) + ExecutableChoice.chooseBitsRealizer) (composition first.fst.snd listLength)) + decodeIndexRealizer).congr (fun _=>rfl) + +lemma decodeIndex_fin {n m : ℕ} (i : Fin (n*m)) : + decodeIndex (i.val,m)=((finProdFinEquiv.symm i).1.val,(finProdFinEquiv.symm i).2.val) := rfl + +lemma probabilities_eq {n m : ℕ} (bags : Fin (n+2) → Finset (Fin m)) + (rank : Fin m → ℕ) (parent : Fin m → Option (Fin m)) + (hb : UnitRefresh.RankedBags bags rank parent) (hne : ∀ x,(bags x).Nonempty) + (hp : ∀ l p,parent l=some p → rank p + (UnitRefresh.Materialized.edgeCount bags rank parent (Fin.last (n+1)) (finProdFinEquiv.symm i), + UnitRefresh.Materialized.count bags parent (UnitRefresh.Materialized.plan rank))) := by + unfold probabilities + simp only [orderedRep,List.length_ofFn,parentRep_length] + rw [map_range_ofFn] + apply List.ofFn_inj.mpr + funext i + change probability (((orderedRep bags,parentRep parent),(UnitRefresh.Materialized.plan rank).map Fin.val),i.val)=_ + rw [probability,parentRep_length,decodeIndex_fin,edgeCount_eq bags rank parent hb hne hp,count_ordered] + +lemma draw_eq {n m k : ℕ} (bags : Fin (n+2) → Finset (Fin m)) + (rank : Fin m → ℕ) (parent : Fin m → Option (Fin m)) + (hb : UnitRefresh.RankedBags bags rank parent) (hne : ∀ x,(bags x).Nonempty) + (hp : ∀ l p,parent l=some p → rank p + (UnitRefresh.Materialized.edgeCount bags rank parent (Fin.last (n+1)) (finProdFinEquiv.symm i), + UnitRefresh.Materialized.count bags parent (UnitRefresh.Materialized.plan rank)) + have hq : ∀ i,0<(q i).2 := fun _=>hz + have hs : ∑ i,val (q i)=1 := + UnitRefresh.Materialized.edgeProbability_sum bags rank parent hb hne hp _ hz + rw [draw,probabilities_eq bags rank parent hb hne hp] + change decodeIndex (ExecutableChoice.chooseBits (List.ofFn q,List.ofFn bits), (parentRep parent).length)=_ + rw [ExecutableChoice.chooseBits_values q hq hs,parentRep_length,decodeIndex_fin] + rfl + +end MatchingFPRAS.ExecutableUnit + +end OAI diff --git a/lean/OAI/Combinatorics/MatchingCount/Sampling/TreeUnitSampler.lean b/lean/OAI/Combinatorics/MatchingCount/Sampling/TreeUnitSampler.lean new file mode 100644 index 0000000000000000000000000000000000000000..b8379a6c823d4d23838ed2630e88423f6ec64300 --- /dev/null +++ b/lean/OAI/Combinatorics/MatchingCount/Sampling/TreeUnitSampler.lean @@ -0,0 +1,85 @@ +import Mathlib +import OAI.Combinatorics.MatchingCount.Sampling.TreeUnitDraw +import OAI.Combinatorics.MatchingCount.Sampling.TreeUnitAssemble + +namespace OAI + +namespace MatchingFPRAS.ExecutableUnit +open TreeTyped ExecutableDP + +abbrev Bits := List (List Bool) +abbrev State := Context×(Bits×List Frame) +def nextContext (x : Context×(ℕ×ℕ)) : Context := + ((residual (x.1.1.1,x.2.1),x.1.1.2),x.1.2) +def nextContextRealizer : Realizer nextContext := + (pair (pair (composition (pair first.fst.fst second.fst) residualRealizer) first.fst.snd) first.snd).congr (fun _=>rfl) +def selected (x : Context×Bits) : ℕ×ℕ := draw (x.1,x.2.getD (x.1.1.1.length-1) []) +def selectedRealizer : Realizer selected := by + let n : Realizer (fun x : Context×Bits=>x.1.1.1.length-1) := composition (composition first.fst.fst listLength) predecessor + exact (composition (pair first (composition (pair second n) (getD []))) drawRealizer).congr (fun _=>rfl) +def step (x : State) : State := + if 2≤x.1.1.1.length then + let c:=selected (x.1,x.2.1) + (nextContext (x.1,c),(x.2.1,(x.1.1.1.length-2,c)::x.2.2)) + else x +def stepRealizer : Realizer step := by + let n : Realizer (fun x : State=>x.1.1.1.length) := composition first.fst.fst listLength + let c : Realizer (fun x : State=>selected (x.1,x.2.1)) := (composition (f:=fun x : State=>(x.1,x.2.1)) (pair first second.fst) selectedRealizer).congr (fun _=>rfl) + let ctx := composition (pair first c) nextContextRealizer + let k := composition (pair n (constant 2)) subtract + let fs := composition (pair (pair k c) second.snd) listCons + let r := pair ctx (pair second.fst fs) + exact (choose (composition (composition (pair n (constant 2)) less) boolNot) r identity).congr (by + intro x; simp [step,Nat.succ_le_iff]) + +def rawSample : ℕ → Context → Bits → Result + | 0,_,_ => [] + | f+1,x,bits => if 2≤x.1.1.length then + let c:=selected (x,bits) + assemble ((x.1.1.length-2,c),rawSample f (nextContext (x,c)) bits) + else [] +def unwind (fs : List Frame) (r : Result) : Result := fs.foldl (fun z a=>assemble (a,z)) r +lemma descend_unwind (f : ℕ) (x : Context) (bs : Bits) (fs : List Frame) : + unwind (countDown (fun y : ℕ×State=>step y.2) f (x,(bs,fs))).2.2 []= + unwind fs (rawSample f x bs) := by + induction f generalizing x bs fs with + | zero => rfl + | succ f ih => + rw [countDown] + by_cases h : 2≤x.1.1.length + · have he : step (x,(bs,fs))=(nextContext (x,selected (x,bs)),(bs,(x.1.1.length-2,selected (x,bs))::fs)) := by simp only [step,h,↓reduceIte] + rw [he,ih] + simp only [rawSample,h,↓reduceIte] + rfl + · have he : step (x,(bs,fs))=(x,(bs,fs)) := by simp only [step,h,↓reduceIte] + rw [he,ih] + simp only [rawSample,h,↓reduceIte] + have hz : rawSample f x bs=[] := by cases f <;> simp [rawSample,h] + rw [hz] + +def sample (x : Context×Bits) : Result := rawSample x.1.1.1.length x.1 x.2 +def sampleRealizer : Realizer sample := by + let st : Realizer (fun x : Context×Bits=>(x.1,(x.2,([] : List Frame)))) := pair first (pair second (constant [])) + let fuel : Realizer (fun x : Context×Bits=>x.1.1.1.length) := composition first.fst.fst listLength + let run := composition (pair fuel st) (iterateDown (composition second stepRealizer)) + let fs := run.snd.snd + let res := composition (pair fs (constant ([] : Result))) (fold assembleRealizer) + exact res.congr (by intro x; exact (descend_unwind _ _ _ []).trans rfl) + +lemma selected_eq_of_getD {n m k : ℕ} (bags : Fin (n+2) → Finset (Fin m)) + (rank : Fin m → ℕ) (parent : Fin m → Option (Fin m)) + (hb : UnitRefresh.RankedBags bags rank parent) (hne : ∀ x,(bags x).Nonempty) + (hp : ∀ l p,parent l=some p → rank p v ∈ ends e) M Finset.univ) : + (SimpleGraph.toSubgraph (G := ⊤) (underlying ends hloop M) le_top).IsPerfectMatching := by + rw [SimpleGraph.Subgraph.isPerfectMatching_iff] + intro v + obtain ⟨e, ⟨he, hev⟩, heuniq⟩ := hM.2 v (Finset.mem_univ v) + obtain ⟨w, hw⟩ := exists_partner ends hev + refine ⟨w, ⟨e, he, hw⟩, ?_⟩ + rintro u ⟨f, hf, hfu⟩ + have hfv : v ∈ ends f := by rw [hfu]; simp + have hfe := heuniq f ⟨hf, hfv⟩ + have hsym : s(v,u) = s(v,w) := hfu.symm.trans ((congrArg ends hfe).trans hw) + have h : u = w ∨ v = w ∧ u = v := by simpa using hsym + exact h.elim id (fun h => h.2.trans h.1) + +open scoped symmDiff + +def discrepancy (M N : Finset E) : SimpleGraph V := + underlying ends hloop M ∆ underlying ends hloop N + +lemma discrepancy_cycles (M N : Finset E) + (hM : MatchingOn (fun e v => v ∈ ends e) M Finset.univ) + (hN : MatchingOn (fun e v => v ∈ ends e) N Finset.univ) : + (discrepancy ends hloop M N).IsCycles := by + have h := (underlying_perfect ends hloop M hM).symmDiff_isCycles + (underlying_perfect ends hloop N hN) + exact h + +lemma discrepancy_alternating (M N : Finset E) + (hM : MatchingOn (fun e v => v ∈ ends e) M Finset.univ) + (hN : MatchingOn (fun e v => v ∈ ends e) N Finset.univ) : + (discrepancy ends hloop M N).IsAlternating (underlying ends hloop M) := by + have h := (underlying_perfect ends hloop M hM).isAlternating_symmDiff_left + (underlying_perfect ends hloop N hN) + exact h + +lemma discrepancy_component_cycle (M N : Finset E) + (hM : MatchingOn (fun e v => v ∈ ends e) M Finset.univ) + (hN : MatchingOn (fun e v => v ∈ ends e) N Finset.univ) + (c : (discrepancy ends hloop M N).ConnectedComponent) (v : V) + (hv : v ∈ c.supp) (hn : ((discrepancy ends hloop M N).neighborSet v).Nonempty) : + ∃ p : (discrepancy ends hloop M N).Walk v v, + p.IsCycle ∧ p.toSubgraph.verts = c.supp := + (discrepancy_cycles ends hloop M N hM hN).exists_cycle_toSubgraph_verts_eq_connectedComponentSupp hv hn + +omit [Fintype V] [DecidableEq V] [DecidableEq E] in +lemma discrepancy_adj_iff [Fintype V] [DecidableEq V] [DecidableEq E] (M N : Finset E) (v w : V) : + (discrepancy ends hloop M N).Adj v w ↔ + ((underlying ends hloop M).Adj v w ∧ ¬ (underlying ends hloop N).Adj v w) ∨ + ((underlying ends hloop N).Adj v w ∧ ¬ (underlying ends hloop M).Adj v w) := by + rfl + +lemma unique_colored_lift (M N : Finset E) + (hM : MatchingOn (fun e v => v ∈ ends e) M Finset.univ) + (hN : MatchingOn (fun e v => v ∈ ends e) N Finset.univ) + {v w : V} (hadj : (discrepancy ends hloop M N).Adj v w) : + ∃! e, e ∈ M ∪ N ∧ ends e = s(v,w) := by + rcases (discrepancy_adj_iff ends hloop M N v w).mp hadj with h | h + · obtain ⟨e, he, hend⟩ := h.1 + refine ⟨e, ⟨Finset.mem_union_left N he, hend⟩, ?_⟩ + rintro f ⟨hf, hfend⟩ + rcases Finset.mem_union.mp hf with hf | hf + · obtain ⟨g, hg, hu⟩ := hM.2 v (Finset.mem_univ v) + exact (hu f ⟨hf, by change v ∈ ends f; rw [hfend]; simp⟩).trans + (hu e ⟨he, by change v ∈ ends e; rw [hend]; simp⟩).symm + · exact (h.2 ⟨f, hf, hfend⟩).elim + · obtain ⟨e, he, hend⟩ := h.1 + refine ⟨e, ⟨Finset.mem_union_right M he, hend⟩, ?_⟩ + rintro f ⟨hf, hfend⟩ + rcases Finset.mem_union.mp hf with hf | hf + · exact (h.2 ⟨f, hf, hfend⟩).elim + · obtain ⟨g, hg, hu⟩ := hN.2 v (Finset.mem_univ v) + exact (hu f ⟨hf, by change v ∈ ends f; rw [hfend]; simp⟩).trans + (hu e ⟨he, by change v ∈ ends e; rw [hend]; simp⟩).symm + +lemma colored_lift_mem_iff (M N : Finset E) + {v w : V} (hadj : (discrepancy ends hloop M N).Adj v w) + {e : E} (he : e ∈ M ∪ N) (hend : ends e = s(v,w)) : + (e ∈ M ↔ (underlying ends hloop M).Adj v w) ∧ + (e ∈ N ↔ (underlying ends hloop N).Adj v w) := by + rcases (discrepancy_adj_iff ends hloop M N v w).mp hadj with h | h + · have hen : e ∉ N := fun hen => h.2 ⟨e, hen, hend⟩ + have hem : e ∈ M := (Finset.mem_union.mp he).resolve_right hen + simp only [hem, hen, h.1, h.2, and_self] + · have hem : e ∉ M := fun hem => h.2 ⟨e, hem, hend⟩ + have hen : e ∈ N := (Finset.mem_union.mp he).resolve_left hem + simp only [hem, hen, h.1, h.2, and_self] + +omit [Fintype V] [DecidableEq V] in +lemma alternating_cycle_parity [Fintype V] [DecidableEq V] {G H : SimpleGraph V} {v : V} + (p : G.Walk v v) (hp : p.IsCycle) (halt : G.IsAlternating H) : + p.length % 2 = 0 := by + let Q : ℕ → Prop := fun i => H.Adj (p.getVert i) (p.getVert (i + 1)) + have recur : ∀ i, i + 1 < p.length → (Q (i + 1) ↔ ¬ Q i) := by + intro i hi + have hn : p.getVert i ≠ p.getVert (i + 2) := by + simpa using hp.getVert_sub_one_ne_getVert_add_one (i := i + 1) (by omega) + have h := halt hn (p.adj_getVert_succ (i := i) (by omega)).symm + (p.adj_getVert_succ (i := i + 1) hi) + dsimp [Q] + have hsym := H.adj_comm (u := p.getVert (i + 1)) (v := p.getVert i) + tauto + have parity : ∀ i, i < p.length → + (Q i ↔ if i % 2 = 0 then Q 0 else ¬ Q 0) := by + intro i + induction i with + | zero => simp + | succ i ih => + intro hi + rw [recur i hi, ih (by omega)] + split_ifs <;> first | omega | tauto + have hn : p.getVert 1 ≠ p.getVert (p.length - 1) := by + simpa [SimpleGraph.Walk.snd, SimpleGraph.Walk.penultimate] using hp.snd_ne_penultimate + have hfirst := p.adj_getVert_succ (i := 0) (by have := hp.three_le_length; omega) + have hlast := p.adj_getVert_succ (i := p.length - 1) (by have := hp.three_le_length; omega) + have he : p.length - 1 + 1 = p.length := by have := hp.three_le_length; omega + have hclose : Q 0 ↔ ¬ Q (p.length - 1) := by + have h := halt hn (by simpa using hfirst) (by simpa [he] using hlast.symm) + simpa [Q, he, H.adj_comm] using h + have hr := parity (p.length - 1) (by have := hp.three_le_length; omega) + split_ifs at hr + · tauto + · have := hp.three_le_length + omega + +lemma discrepancy_component_even_cycle (M N : Finset E) + (hM : MatchingOn (fun e v => v ∈ ends e) M Finset.univ) + (hN : MatchingOn (fun e v => v ∈ ends e) N Finset.univ) + (c : (discrepancy ends hloop M N).ConnectedComponent) (v : V) + (hv : v ∈ c.supp) (hn : ((discrepancy ends hloop M N).neighborSet v).Nonempty) : + ∃ p : (discrepancy ends hloop M N).Walk v v, + p.IsCycle ∧ p.toSubgraph.verts = c.supp ∧ p.length % 2 = 0 ∧ 4 ≤ p.length := by + obtain ⟨p, hp, hc⟩ := discrepancy_component_cycle ends hloop M N hM hN c v hv hn + have he := alternating_cycle_parity p hp (discrepancy_alternating ends hloop M N hM hN) + exact ⟨p, hp, hc, he, by have := hp.three_le_length; omega⟩ + +def cyclicVertex {G : SimpleGraph V} {v : V} (p : G.Walk v v) (i : ℕ) : V := + p.getVert (i % p.length) + +omit [Fintype V] [DecidableEq V] in +lemma cyclicVertex_periodic [Fintype V] [DecidableEq V] {G : SimpleGraph V} {v : V} (p : G.Walk v v) (i : ℕ) : + cyclicVertex p (i + p.length) = cyclicVertex p i := by + simp [cyclicVertex] + +omit [Fintype V] [DecidableEq V] in +lemma cyclicVertex_injOn [Fintype V] [DecidableEq V] {G : SimpleGraph V} {v : V} (p : G.Walk v v) + (hp : p.IsCycle) : Set.InjOn (cyclicVertex p) (Set.Ico 0 p.length) := by + intro i hi j hj h + have hi' := hi.2 + have hj' := hj.2 + simp only [cyclicVertex, Nat.mod_eq_of_lt hi', Nat.mod_eq_of_lt hj'] at h + exact hp.getVert_injOn' (by change i ≤ p.length - 1; omega) + (by change j ≤ p.length - 1; omega) h + +omit [Fintype V] [DecidableEq V] in +lemma cyclicVertex_next [Fintype V] [DecidableEq V] {G : SimpleGraph V} {v : V} (p : G.Walk v v) + (i : ℕ) (hi : i < p.length) : cyclicVertex p (i + 1) = p.getVert (i + 1) := by + by_cases h : i + 1 < p.length + · simp [cyclicVertex, Nat.mod_eq_of_lt h] + · have he : i + 1 = p.length := by omega + simp [he, cyclicVertex] + +lemma cyclicVertex_adj {G : SimpleGraph V} {v : V} (p : G.Walk v v) + (hp : p.IsCycle) (i : ℕ) : G.Adj (cyclicVertex p i) (cyclicVertex p (i + 1)) := by + have hm : i % p.length < p.length := Nat.mod_lt i (by have := hp.three_le_length; omega) + have he : cyclicVertex p (i + 1) = cyclicVertex p (i % p.length + 1) := by + simp only [cyclicVertex, Nat.add_mod, Nat.mod_mod] + rw [he, cyclicVertex_next p _ hm] + exact p.adj_getVert_succ hm + +noncomputable def cyclicEdge (M N : Finset E) + (hM : MatchingOn (fun e v => v ∈ ends e) M Finset.univ) + (hN : MatchingOn (fun e v => v ∈ ends e) N Finset.univ) + {v : V} (p : (discrepancy ends hloop M N).Walk v v) (hp : p.IsCycle) (i : ℕ) : E := + (unique_colored_lift ends hloop M N hM hN (cyclicVertex_adj p hp i)).choose + +lemma cyclicEdge_spec (M N : Finset E) + (hM : MatchingOn (fun e v => v ∈ ends e) M Finset.univ) + (hN : MatchingOn (fun e v => v ∈ ends e) N Finset.univ) + {v : V} (p : (discrepancy ends hloop M N).Walk v v) (hp : p.IsCycle) (i : ℕ) : + cyclicEdge ends hloop M N hM hN p hp i ∈ M ∪ N ∧ + ends (cyclicEdge ends hloop M N hM hN p hp i) = + s(cyclicVertex p i, cyclicVertex p (i + 1)) := + (unique_colored_lift ends hloop M N hM hN (cyclicVertex_adj p hp i)).choose_spec.1 + +lemma cyclicEdge_periodic (M N : Finset E) + (hM : MatchingOn (fun e v => v ∈ ends e) M Finset.univ) + (hN : MatchingOn (fun e v => v ∈ ends e) N Finset.univ) + {v : V} (p : (discrepancy ends hloop M N).Walk v v) (hp : p.IsCycle) (i : ℕ) : + cyclicEdge ends hloop M N hM hN p hp (i + p.length) = + cyclicEdge ends hloop M N hM hN p hp i := by + have hs := cyclicEdge_spec ends hloop M N hM hN p hp (i + p.length) + apply (unique_colored_lift ends hloop M N hM hN (cyclicVertex_adj p hp i)).choose_spec.2 + refine ⟨hs.1, ?_⟩ + simpa [cyclicVertex_periodic, show i + p.length + 1 = i + 1 + p.length by omega] using hs.2 + +end Overlay + +end MatchingFPRAS.Transport + +namespace MatchingFPRAS.Transport.Overlay + +section + +variable {V E : Type*} [Fintype V] [DecidableEq V] [DecidableEq E] + +variable (ends : E → Sym2 V) (hloop : ∀ e, ¬ (ends e).IsDiag) + +variable (M N : Finset E) + +variable (hM : MatchingOn (fun e v => v ∈ ends e) M Finset.univ) + +variable (hN : MatchingOn (fun e v => v ∈ ends e) N Finset.univ) + +noncomputable def indexedCycle {v : V} + (p : (discrepancy ends hloop M N).Walk v v) (hp : p.IsCycle) : + IndexedCycle (fun e v => v ∈ ends e) where + size := p.length + four_le := by + have hh := hp.three_le_length + have he := alternating_cycle_parity p hp (discrepancy_alternating ends hloop M N hM hN) + omega + even := alternating_cycle_parity p hp (discrepancy_alternating ends hloop M N hM hN) + vertex i := cyclicVertex p i.val + simple := by + intro i j h + apply Fin.ext + exact cyclicVertex_injOn p hp ⟨Nat.zero_le _, i.isLt⟩ ⟨Nat.zero_le _, j.isLt⟩ h + edge i := cyclicEdge ends hloop M N hM hN p hp i.val + incidence := by + intro i w + rw [(cyclicEdge_spec ends hloop M N hM hN p hp i.val).2] + simp only [Sym2.mem_iff, cyclicVertex, Nat.mod_mod] + +lemma indexedCycle_edge_mem {v : V} + (p : (discrepancy ends hloop M N).Walk v v) (hp : p.IsCycle) + (i : Fin p.length) : (indexedCycle ends hloop M N hM hN p hp).edge i ∈ M ∪ N := + (cyclicEdge_spec ends hloop M N hM hN p hp i.val).1 + +lemma cyclicEdge_injective {v : V} + (p : (discrepancy ends hloop M N).Walk v v) (hp : p.IsCycle) : + Set.InjOn (cyclicEdge ends hloop M N hM hN p hp) (Set.Ico 0 p.length) := by + intro i hi j hj h + have hi' : i < p.edges.length := by simpa using hi.2 + have hj' : j < p.edges.length := by simpa using hj.2 + apply (hp.isCircuit.isTrail.edges_nodup.getElem_inj_iff (hi := hi') (hj := hj')).mp + rw [SimpleGraph.Walk.getElem_edges hi', SimpleGraph.Walk.getElem_edges hj'] + have hh := congrArg ends h + rw [(cyclicEdge_spec ends hloop M N hM hN p hp i).2, + (cyclicEdge_spec ends hloop M N hM hN p hp j).2] at hh + rw [cyclicVertex_next p i hi.2, cyclicVertex_next p j hj.2] at hh + simpa only [cyclicVertex, Nat.mod_eq_of_lt hi.2, Nat.mod_eq_of_lt hj.2] using hh + +omit [Fintype V] [DecidableEq V] in +lemma alternating_edge_parity [Fintype V] [DecidableEq V] {G H : SimpleGraph V} {v : V} + (p : G.Walk v v) (hp : p.IsCycle) (halt : G.IsAlternating H) + (i : ℕ) (hi : i < p.length) : + H.Adj (p.getVert i) (p.getVert (i+1)) ↔ + if i % 2 = 0 then H.Adj (p.getVert 0) (p.getVert 1) + else ¬H.Adj (p.getVert 0) (p.getVert 1) := by + let Q : ℕ → Prop := fun j => H.Adj (p.getVert j) (p.getVert (j+1)) + have recur : ∀ j, j + 1 < p.length → (Q (j + 1) ↔ ¬Q j) := by + intro j hj + have hn : p.getVert j ≠ p.getVert (j + 2) := by + simpa using hp.getVert_sub_one_ne_getVert_add_one (i := j+1) (by omega) + have h := halt hn (p.adj_getVert_succ (i := j) (by omega)).symm + (p.adj_getVert_succ (i := j+1) hj) + dsimp [Q] + have hsym := H.adj_comm (u := p.getVert (j+1)) (v := p.getVert j) + tauto + change Q i ↔ if i % 2 = 0 then Q 0 else ¬Q 0 + induction i with + | zero => simp + | succ i ih => + rw [recur i hi, ih (by omega)] + split_ifs <;> first | omega | tauto + +lemma cyclicEdge_mem_parity {v : V} + (p : (discrepancy ends hloop M N).Walk v v) (hp : p.IsCycle) + (i : ℕ) (hi : i < p.length) : + cyclicEdge ends hloop M N hM hN p hp i ∈ M ↔ + if i % 2 = 0 then cyclicEdge ends hloop M N hM hN p hp 0 ∈ M + else cyclicEdge ends hloop M N hM hN p hp 0 ∉ M := by + have hi_spec := cyclicEdge_spec ends hloop M N hM hN p hp i + have h0_spec := cyclicEdge_spec ends hloop M N hM hN p hp 0 + have hi_mem := (colored_lift_mem_iff ends hloop M N (cyclicVertex_adj p hp i) + hi_spec.1 hi_spec.2).1 + have h0_mem := (colored_lift_mem_iff ends hloop M N (cyclicVertex_adj p hp 0) + h0_spec.1 h0_spec.2).1 + rw [hi_mem, h0_mem] + have hn : 0 < p.length := by have := hp.three_le_length; omega + rw [cyclicVertex_next p i hi, cyclicVertex_next p 0 hn] + simpa only [cyclicVertex, Nat.zero_mod, Nat.mod_eq_of_lt hi] using + alternating_edge_parity p hp (discrepancy_alternating ends hloop M N hM hN) i hi + +end + +variable {V E : Type*} [Fintype V] [DecidableEq V] [DecidableEq E] + +variable (ends : E → Sym2 V) (hloop : ∀ e, ¬ (ends e).IsDiag) + +variable {M N : Finset E} + +variable (hM : MatchingOn (fun e v => v ∈ ends e) M Finset.univ) + +variable (hN : MatchingOn (fun e v => v ∈ ends e) N Finset.univ) + +include hM hN + +omit [DecidableEq V] in +lemma parallel_component [DecidableEq V] {e f : E} (he : e ∈ M) (hf : f ∈ N) + (hef : ends e = ends f) : + componentEdges (inc := fun e v => v ∈ ends e) (M ∪ N) e = {e,f} := by + classical + obtain ⟨v,hv⟩ : ∃ v, v ∈ ends e := by + induction ends e using Sym2.inductionOn with | hf a b => exact ⟨a,by simp⟩ + have hfv : v ∈ ends f := hef ▸ hv + have closed : ∀ {a b}, a ∈ ({e,f} : Finset E) → + (overlayLineGraph (fun e v => v ∈ ends e) (M ∪ N)).Adj a b → b ∈ ({e,f} : Finset E) := by + intro a b ha hab + obtain ⟨_,_,hb,w,haw,hbw⟩ := hab + have hew : w ∈ ends e := by + rcases Finset.mem_insert.mp ha with rfl | ha + · exact haw + · have haf := Finset.mem_singleton.mp ha + simpa only [haf,← hef] using haw + have hfw : w ∈ ends f := hef ▸ hew + rcases Finset.mem_union.mp hb with hb | hb + · have hbe := hM.unique (Finset.mem_univ w) hb hbw he hew + simp [hbe] + · have hbf := hN.unique (Finset.mem_univ w) hb hbw hf hfw + simp [hbf] + ext a + constructor + · intro ha + obtain ⟨hau,hr⟩ := (mem_componentEdges _ _ _).mp ha + have hrel := (SimpleGraph.reachable_iff_reflTransGen _ _).mp hr + clear ha hau hr + induction hrel with + | refl => simp + | tail hpath hadj ih => exact closed ih hadj + · intro ha + rcases Finset.mem_insert.mp ha with rfl | ha + · exact componentEdges_self (Finset.mem_union_left N he) + · have haf := Finset.mem_singleton.mp ha + subst a + exact (mem_componentEdges _ _ _).mpr ⟨Finset.mem_union_right M hf, + shares_reachable (Finset.mem_union_left N he) (Finset.mem_union_right M hf) hv hfv⟩ + +include hloop + +theorem component_classification {S : Finset E} + (hS : S ∈ components (inc := fun e v => v ∈ ends e) (M ∪ N)) : + (∃ e ∈ M, ∃ f ∈ N, ends e = ends f ∧ S = {e,f}) ∨ + (∃ c : IndexedCycle (fun e v => v ∈ ends e), + (∀ i, c.edgeAt i ∈ M ∪ N) ∧ S = c.edgeSet) := by + classical + obtain ⟨a,ha,haS⟩ := mem_components.mp hS + obtain ⟨v,hav⟩ : ∃ v, v ∈ ends a := by + induction ends a using Sym2.inductionOn with | hf x y => exact ⟨x,by simp⟩ + obtain ⟨e,⟨he,hev⟩,_⟩ := hM.2 v (Finset.mem_univ v) + obtain ⟨f,⟨hf,hfv⟩,_⟩ := hN.2 v (Finset.mem_univ v) + have heU : e ∈ M ∪ N := Finset.mem_union_left N he + have heS : e ∈ S := by + rw [← haS] + exact (mem_componentEdges _ _ _).mpr ⟨heU, shares_reachable ha heU hav hev⟩ + by_cases hef : ends e = ends f + · left + refine ⟨e,he,f,hf,hef,?_⟩ + rw [← haS, componentEdges_eq (shares_reachable ha heU hav hev)] + exact parallel_component ends hM hN he hf hef + · right + obtain ⟨w,hw⟩ := exists_partner ends hev + have hadj : (discrepancy ends hloop M N).Adj v w := by + apply (discrepancy_adj_iff ends hloop M N v w).mpr + refine Or.inl ⟨⟨e,he,hw⟩,?_⟩ + rintro ⟨g,hg,hgw⟩ + have hgv : v ∈ ends g := by rw [hgw]; simp + have hgf := hN.unique (Finset.mem_univ v) hg hgv hf hfv + apply hef + rw [hw,← hgf,hgw] + let H := discrepancy ends hloop M N + obtain ⟨p,hp,_,_,_⟩ := discrepancy_component_even_cycle ends hloop M N hM hN + (H.connectedComponentMk v) v rfl ⟨w,hadj⟩ + let c := indexedCycle ends hloop M N hM hN p hp + have hU : ∀ i, c.edgeAt i ∈ M ∪ N := by + intro i + exact indexedCycle_edge_mem ends hloop M N hM hN p hp (c.index i) + have hv0 : c.vertexAt 0 = v := by + simp [c,IndexedCycle.vertexAt,IndexedCycle.index,indexedCycle,cyclicVertex] + have hec : e ∈ c.edgeSet := + c.edge_incident_cycle_mem hM hN hU heU 0 (by have := c.four_le; omega) (hv0.symm ▸ hev) + refine ⟨c,hU,?_⟩ + exact component_eq_of_shares hS (c.edgeSet_mem_components hM hN hU) heS hec hev hev + +end MatchingFPRAS.Transport.Overlay + +end OAI diff --git a/lean/OAI/Combinatorics/MatchingCount/Tapes/BlockMap.lean b/lean/OAI/Combinatorics/MatchingCount/Tapes/BlockMap.lean new file mode 100644 index 0000000000000000000000000000000000000000..dd8fbc16c8b73c54647aafa6c555eb6bfe843544 --- /dev/null +++ b/lean/OAI/Combinatorics/MatchingCount/Tapes/BlockMap.lean @@ -0,0 +1,265 @@ +import Mathlib +import OAI.Combinatorics.MatchingCount.Tapes.TapeTools +import OAI.Combinatorics.MatchingCount.Tapes.Codec + +namespace OAI + +namespace MatchingFPRAS.LiteralTape +open Turing MachineCost + +variable {Λ σ : Type} +lemma scan_left (M : Λ→TM1.Stmt Symbol Λ σ) (l : Λ) (mark : Symbol) + (hs : ∀ v T,T.head≠mark→TM1.stepAux (M l) v T=⟨some l,v,T.move .left⟩) + (xs L R : List Symbol) (v : σ) (hx : ∀ a∈xs,a≠mark) : + Exec M ⟨some l,v,(Tape.mk₂ (xs++mark::L) R).move .left⟩ + ⟨some l,v,Tape.mk₂ L (mark::(xs.reverse++R))⟩ xs.length := by + induction xs generalizing R with + | nil => simpa using Exec.refl M (⟨some l,v,Tape.mk₂ L (mark::R)⟩ : TM1.Cfg Symbol Λ σ) + | cons a xs ih => + simp only [List.cons_append,mk₂_left] + have h1:=Exec.step M l v (Tape.mk₂ (xs++mark::L) (a::R)) + rw [hs v _ (by simpa using hx a (by simp))] at h1 + have h2:=ih (a::R) (fun b hb=>hx b (by simp [hb])) + have h:=h1.trans h2 + simpa only [List.length_cons,List.reverse_cons,List.append_assoc,List.singleton_append,Nat.add_comm] using h +lemma scan_right (M : Λ→TM1.Stmt Symbol Λ σ) (l : Λ) (mark : Symbol) + (hs : ∀ v T,T.head≠mark→TM1.stepAux (M l) v T=⟨some l,v,T.move .right⟩) + (xs L R : List Symbol) (v : σ) (hx : ∀ a∈xs,a≠mark) : + Exec M ⟨some l,v,Tape.mk₂ L (xs++mark::R)⟩ + ⟨some l,v,Tape.mk₂ (xs.reverse++L) (mark::R)⟩ xs.length := by + induction xs generalizing L with + | nil => exact Exec.refl M _ + | cons a xs ih => + simp only [List.cons_append] + have h1:=Exec.step M l v (Tape.mk₂ L (a::(xs++mark::R))) + rw [hs v _ (by simpa using hx a (by simp)),mk₂_right] at h1 + have h2:=ih (a::L) (fun b hb=>hx b (by simp [hb])) + have h:=h1.trans h2 + simpa only [List.length_cons,List.reverse_cons,List.append_assoc,List.singleton_append,Nat.add_comm] using h +end MatchingFPRAS.LiteralTape + +namespace MatchingFPRAS.LiteralBlockMap +open Turing LiteralTape + +inductive Label + | start | read | seek | back | stopSep | stopOut + deriving DecidableEq, Inhabited +instance : Fintype Label := ⟨{.start,.read,.seek,.back,.stopSep,.stopOut}, by intro a; cases a <;> simp⟩ +abbrev Block (w : ℕ) := Fin w→Symbol +noncomputable def code (w : ℕ) (h : Block w→List Symbol) (header : List Symbol) : + Label→TM1.Stmt Symbol Label (Block w) + | .start => .move .left (.write (fun _ _=>7) (.move .left (.write (fun _ _=>6) + (.move .right (.move .right (.goto (fun _ _=>.read))))))) + | .read => grab (List.finRange w) + (.branch (fun _ b=>decide (b=fun _=>0)) + (.move .left (.goto (fun _ _=>.stopSep))) + (.move .left (.write (fun _ _=>7) (eraseToLeft w (.move .left (.goto (fun _ _=>.seek))))))) + | .seek => .branch (fun a _=>decide (a=6)) + (select Finset.univ.toList (fun b=>.write (fun _ _=>0) + (writeLeft (h b).reverse (.write (fun _ _=>6) (.move .right (.goto (fun _ _=>.back)))))) .halt) + (.move .left (.goto (fun _ _=>.seek))) + | .back => .branch (fun a _=>decide (a=7)) + (.move .right (.goto (fun _ _=>.read))) + (.move .right (.goto (fun _ _=>.back))) + | .stopSep => .branch (fun a _=>decide (a=7)) + (.write (fun _ _=>0) (.move .left (.goto (fun _ _=>.stopOut)))) + (.move .left (.goto (fun _ _=>.stopSep))) + | .stopOut => .branch (fun a _=>decide (a=6)) + (.write (fun _ _=>0) (writeLeft header.reverse (.write (fun _ _=>0) (.move .right .halt)))) + (.move .left (.goto (fun _ _=>.stopOut))) +variable (w : ℕ) (h : Block w→List Symbol) (header : List Symbol) +local notation "M" => code w h header +lemma seek_path (v : Block w) (T : Tape Symbol) (ht : T.head≠6) : + TM1.stepAux (M .seek) v T=⟨some .seek,v,T.move .left⟩ := by + simp only [code,TM1.stepAux,ht,decide_false,Bool.cond_false] +lemma back_path (v : Block w) (T : Tape Symbol) (ht : T.head≠7) : + TM1.stepAux (M .back) v T=⟨some .back,v,T.move .right⟩ := by + simp only [code,TM1.stepAux,ht,decide_false,Bool.cond_false] +lemma stopSep_path (v : Block w) (T : Tape Symbol) (ht : T.head≠7) : + TM1.stepAux (M .stopSep) v T=⟨some .stopSep,v,T.move .left⟩ := by + simp only [code,TM1.stepAux,ht,decide_false,Bool.cond_false] +lemma stopOut_path (v : Block w) (T : Tape Symbol) (ht : T.head≠6) : + TM1.stepAux (M .stopOut) v T=⟨some .stopOut,v,T.move .left⟩ := by + simp only [code,TM1.stepAux,ht,decide_false,Bool.cond_false] + +def working (out : List Symbol) (gap : ℕ) (input : List Symbol) : Tape Symbol := + Tape.mk₂ (7::(List.replicate gap 0++out.reverse++[6])) input +lemma start_step (input : List Symbol) (v : Block w) : + Exec M ⟨some .start,v,Tape.mk₁ input⟩ ⟨some .read,v,working [] 0 input⟩ 1 := by + have hh:=Exec.step M .start v (Tape.mk₁ input) + simpa only [code,TM1.stepAux,Tape.mk₁,mk₂_left_nil,mk₂_write,mk₂_right,working,List.replicate_zero, + List.reverse_nil,List.nil_append] using hh + +lemma seek_write (v : Block w) (R : List Symbol) : + Exec M ⟨some .seek,v,Tape.mk₂ [] (6::R)⟩ + ⟨some .back,v,Tape.mk₂ [6] (h v++R)⟩ 1 := by + have hh:=Exec.step M .seek v (Tape.mk₂ [] (6::R)) + simp only [code,TM1.stepAux,mk₂_head,decide_true,Bool.cond_true] at hh + rw [select_step _ _ _ v (by simp)] at hh + have hs:=writeLeft_step (Γ:=Symbol) (h v).reverse + (.write (fun _ _=>6) (.move .right (.goto (fun _ _=>Label.back)))) v R + simp only [Fin.default_eq_zero,List.reverse_reverse,List.cons_append,TM1.stepAux,mk₂_write,mk₂_right] at hs + simpa only [TM1.stepAux,mk₂_write,hs] using hh +lemma stopOut_write (v : Block w) (R : List Symbol) : + Exec M ⟨some .stopOut,v,Tape.mk₂ [] (6::R)⟩ + ⟨none,v,Tape.mk₂ [0] (header++R)⟩ 1 := by + have hh:=Exec.step M .stopOut v (Tape.mk₂ [] (6::R)) + have hs:=writeLeft_step (Γ:=Symbol) header.reverse + (.write (fun _ _=>0) (.move .right (.halt : TM1.Stmt Symbol Label (Block w)))) v R + simp only [Fin.default_eq_zero,List.reverse_reverse,List.cons_append,TM1.stepAux,mk₂_write,mk₂_right] at hs + simpa only [code,TM1.stepAux,mk₂_head,decide_true,Bool.cond_true,mk₂_write,hs] using hh + +lemma read_block (hw : 00) + (out input : List Symbol) (gap : ℕ) : + Exec M ⟨some .read,v,working out gap (List.ofFn b++input)⟩ + ⟨some .seek,b,(Tape.mk₂ (List.replicate gap 0++out.reverse++[6]) + (List.replicate w 0++7::input)).move .left⟩ 1 := by + have hh:=Exec.step M .read v (working out gap (List.ofFn b++input)) + change Exec M _ (TM1.stepAux (grab _ _) v _) 1 at hh + rw [working,grab_fin] at hh + simp only [TM1.stepAux,hb,decide_false,Bool.cond_false] at hh + cases hr : (List.ofFn b).reverse with + | nil => have hl:=congrArg List.length hr; simp at hl; omega + | cons a xs => + have hl : (xs++[7]).length=w := by + have hh:=congrArg List.length hr + simp only [List.length_reverse,List.length_ofFn,List.length_cons] at hh + simp only [List.length_append,List.length_singleton]; omega + rw [hr] at hh + simp only [List.cons_append,mk₂_left,mk₂_write] at hh + rw [show xs++7::(List.replicate gap 0++out.reverse++[6])= + (xs++[7])++(List.replicate gap 0++out.reverse++[6]) by simp] at hh + have ht:=eraseToLeft_step (xs++[7]) (List.replicate gap 0++out.reverse++[6]) (7::input) + (.move .left (.goto (fun _ _=>Label.seek))) b + rw [hl] at ht + rw [ht] at hh + exact hh +lemma cycle (hw : 00) + (out input : List Symbol) (gap : ℕ) + (ho : ∀ a∈out,a≠6 ∧ a≠7) (hh : ∀ a∈h b,a≠6 ∧ a≠7) : + Exec M ⟨some .read,v,working out gap (List.ofFn b++input)⟩ + ⟨some .read,b,working (h b++out) (gap+w) input⟩ + (3+2*(out.length+gap)+(h b).length+w) := by + have ha:=read_block w h header hw b v hb out input gap + have hx : ∀ a∈List.replicate gap (0:Symbol)++out.reverse,a≠6 := by + intro a ha + rcases List.mem_append.mp ha with ha|ha + · have := (List.eq_of_mem_replicate ha); subst a; decide + · exact (ho a (List.mem_reverse.mp ha)).1 + have hs:=scan_left M .seek 6 (seek_path w h header) + (List.replicate gap 0++out.reverse) [] (List.replicate w 0++7::input) b hx + have he : (List.replicate gap (0:Symbol)++out.reverse).reverse++(List.replicate w 0++7::input)= + out++List.replicate (gap+w) 0++7::input := by + simp only [List.reverse_append,List.reverse_reverse,List.reverse_replicate,List.replicate_add,List.append_assoc] + rw [he] at hs + have ht:=seek_write w h header b (out++List.replicate (gap+w) 0++7::input) + have hy : ∀ a∈h b++out++List.replicate (gap+w) (0:Symbol),a≠7 := by + intro a ha + rcases List.mem_append.mp ha with ha|ha + · rcases List.mem_append.mp ha with ha|ha + · exact (hh a ha).2 + · exact (ho a ha).2 + · have := List.eq_of_mem_replicate ha; subst a; decide + have hu:=scan_right M .back 7 (back_path w h header) + (h b++out++List.replicate (gap+w) 0) [6] input b hy + have hv:=Exec.step M .back b + (Tape.mk₂ ((h b++out++List.replicate (gap+w) 0).reverse++[6]) (7::input)) + simp only [code,TM1.stepAux,mk₂_head,decide_true,Bool.cond_true,mk₂_right] at hv + simp only [List.append_assoc] at ha hs ht hu hv + have hh:=((ha.trans hs).trans ht).trans (hu.trans hv) + simp only [working,List.append_assoc,List.reverse_append,List.reverse_replicate,List.length_append, + List.length_replicate,List.length_reverse] at hh ⊢ + apply Exec.mono hh + omega + +lemma mk₂_blanks (L R : List Symbol) (n : ℕ) : + Tape.mk₂ L (R++List.replicate n 0)=Tape.mk₂ L R := by + simp only [Tape.mk₂,show (0:Symbol)=default from rfl,blank_append_zero] +lemma mk₂_replicate (L : List Symbol) (n : ℕ) : + Tape.mk₂ L (List.replicate n 0)=Tape.mk₂ L [] := by + simpa only [List.nil_append] using mk₂_blanks L [] n +lemma mk₂_zero_left (R : List Symbol) : Tape.mk₂ [0] R=Tape.mk₁ R := by + change Tape.mk' (ListBlank.mk (List.replicate 1 (default:Symbol))) _=Tape.mk' (ListBlank.mk []) _ + rw [blank_zero] + +lemma finish (v : Block w) (out : List Symbol) (gap : ℕ) + (ho : ∀ a∈out,a≠6 ∧ a≠7) : + Exec M ⟨some .read,v,working out gap []⟩ + ⟨none,(fun _=>0),Tape.mk₁ (header++out)⟩ (3+w+gap+out.length) := by + have hz : List.ofFn (fun _ : Fin w=>(0:Symbol))=List.replicate w 0 := by simp + have ha:=Exec.step M .read v (working out gap []) + change Exec M _ (TM1.stepAux (grab _ _) v _) 1 at ha + rw [working,←mk₂_blanks _ [] w] at ha + simp only [List.nil_append,←hz] at ha + rw [show List.ofFn (fun _ : Fin w=>(0:Symbol))= + List.ofFn (fun _ : Fin w=>(0:Symbol))++[] by simp,grab_fin] at ha + simp only [TM1.stepAux,decide_true,Bool.cond_true,hz,List.reverse_replicate] at ha + have hs:=scan_left M .stopSep 7 (stopSep_path w h header) (List.replicate w 0) + (List.replicate gap 0++out.reverse++[6]) [] (fun _=>0) + (by intro a ha; have := List.eq_of_mem_replicate ha; subst a; decide) + have ht:=Exec.step M .stopSep (fun _ : Fin w=>(0:Symbol)) + (Tape.mk₂ (List.replicate gap 0++out.reverse++[6]) (7::List.replicate w 0)) + simp only [code,TM1.stepAux,mk₂_head,decide_true,Bool.cond_true,mk₂_write] at ht + have hx : ∀ a∈List.replicate gap (0:Symbol)++out.reverse,a≠6 := by + intro a ha + rcases List.mem_append.mp ha with ha|ha + · have := List.eq_of_mem_replicate ha; subst a; decide + · exact (ho a (List.mem_reverse.mp ha)).1 + have hu:=scan_left M .stopOut 6 (stopOut_path w h header) + (List.replicate gap 0++out.reverse) [] (0::List.replicate w 0) (fun _=>0) hx + have hv:=stopOut_write w h header (fun _=>0) + (out++List.replicate (gap+1+w) 0) + have he : (List.replicate gap (0:Symbol)++out.reverse).reverse++(0::List.replicate w 0)= + out++List.replicate (gap+1+w) 0 := by + simp only [List.reverse_append,List.reverse_reverse,List.reverse_replicate,List.replicate_add,List.append_assoc,List.replicate_one,List.singleton_append] + rw [he] at hu + simp only [List.length_replicate,List.reverse_replicate,List.append_nil] at hs + have hb:=((ha.trans hs).trans ht).trans (hu.trans hv) + rw [←List.append_assoc,mk₂_blanks,mk₂_zero_left] at hb + simp only [List.append_assoc,List.length_append,List.length_reverse,List.length_replicate] at hb + simp only [List.append_nil,mk₂_replicate] at hb + simp only [working,List.append_assoc] + apply Exec.mono hb + omega + +def budget (H n s : ℕ) : ℕ := (n+1)*(3+w+H+2*(s+n*(H+w))) +lemma blocks (hw : 00) + (hh : ∀ b∈bs,∀ a∈h b,a≠6 ∧ a≠7) + (hH : ∀ b∈bs,(h b).length≤H) + (ho : ∀ a∈out,a≠6 ∧ a≠7) : + Exec M ⟨some .read,v,working out gap (bs.flatMap List.ofFn)⟩ + ⟨none,(fun _=>0),Tape.mk₁ (header++bs.reverse.flatMap h++out)⟩ + (budget w H bs.length (out.length+gap)) := by + induction bs generalizing v out gap with + | nil => + simpa only [List.flatMap_nil,List.reverse_nil,List.append_nil,List.nil_append] + using (finish w h header v out gap ho).mono (by simp only [budget,List.length_nil,Nat.zero_mul,Nat.zero_add,Nat.add_zero,Nat.one_mul]; omega) + | cons b bs ih => + have ha:=cycle w h header hw b v (hb b (by simp)) out (bs.flatMap List.ofFn) gap ho (hh b (by simp)) + have hs:=ih b (h b++out) (gap+w) + (fun a ha=>hb a (by simp [ha])) (fun a ha=>hh a (by simp [ha])) + (fun a ha=>hH a (by simp [ha])) + (by intro a ha; rcases List.mem_append.mp ha with ha|ha; exact hh b (by simp) a ha; exact ho a ha) + have he:=ha.trans hs + simp only [List.reverse_cons,List.flatMap_append,List.append_assoc, + List.flatMap_cons] at he ⊢ + apply he.mono + have hlen:=hH b (by simp) + simp only [budget,List.length_cons,List.length_append] + nlinarith + +lemma computes (hw : 00) + (hh : ∀ b∈bs,∀ a∈h b,a≠6 ∧ a≠7) + (hH : ∀ b∈bs,(h b).length≤H) : + Exec M ⟨some .start,(fun _=>0),Tape.mk₁ (bs.flatMap List.ofFn)⟩ + ⟨none,(fun _=>0),Tape.mk₁ (header++bs.reverse.flatMap h)⟩ + (1+budget w H bs.length 0) := by + have ha:=start_step w h header (bs.flatMap List.ofFn) (fun _=>0) + have hs:=blocks w h header hw bs (fun _=>0) [] 0 H hb hh hH (by simp) + simpa only [List.append_nil,List.length_nil,Nat.zero_add] using ha.trans hs + +end MatchingFPRAS.LiteralBlockMap + +end OAI diff --git a/lean/OAI/Combinatorics/MatchingCount/Tapes/Codec.lean b/lean/OAI/Combinatorics/MatchingCount/Tapes/Codec.lean new file mode 100644 index 0000000000000000000000000000000000000000..772036c1fbbe3573dd462280b946c20735a2f481 --- /dev/null +++ b/lean/OAI/Combinatorics/MatchingCount/Tapes/Codec.lean @@ -0,0 +1,82 @@ +import Mathlib +import OAI.Combinatorics.MatchingCount.Machines.TreeSum + +namespace OAI + +namespace MatchingFPRAS.TreeTyped +variable {A B A' B' : Type} [Codec A] [Codec B] [Codec A'] [Codec B'] +def Realizer.reencode {f : A→B} (F : Realizer f) (i : A'→A) (g : A'→B') + (hi : ∀ a,encode (i a)=encode a) (hg : ∀ a,encode (g a)=encode (f (i a))) : Realizer g where + program := F.program + cost a := F.cost (i a) + correct := by + intro a s + have h:=F.correct (i a) s + rw [hi a,←hg a] at h + exact h +lemma polynomial_reencode {f : A→B} (F : Realizer f) (i : A'→A) (g : A'→B') + (hi : ∀ a,encode (i a)=encode a) (hg : ∀ a,encode (g a)=encode (f (i a))) + (hF : PolynomialTime F) : PolynomialTime (F.reencode i g hi hg) := by + obtain ⟨p,hp⟩:=hF + refine ⟨p,fun a=>?_⟩ + have h:=hp (i a) + simpa only [Realizer.reencode,weight,hi a,←hg a] using h +end MatchingFPRAS.TreeTyped + +namespace MatchingFPRAS.LiteralCodec +open TreeTyped TreeData TreeFunction + +def parts (a : Symbol) : List Bool×List Bool := + (List.replicate a.val false,List.replicate (7-a.val) false) +instance : Codec Symbol := ⟨fun a=>TreeTyped.encode (parts a)⟩ +lemma encode_parts (a : Symbol) : TreeTyped.encode (parts a)=TreeTyped.encode a := rfl +lemma weight_false_list (n : ℕ) : weight (List.replicate n false)=2*n+1 := by + induction n with + | zero => rfl + | succ n ih => rw [List.replicate_succ,weight_cons,ih]; change 1+1+(2*n+1)=_; omega +lemma weight_symbol (a : Symbol) : weight a=17 := by + change weight (parts a)=17 + simp only [parts,weight_prod,weight_false_list] + have ha:=a.isLt + omega +lemma weight_word (as : List Symbol) : weight as=18*as.length+1 := by + induction as with + | nil => rfl + | cons a as ih => rw [weight_cons,weight_symbol,ih,List.length_cons]; omega + +def valRealizer : Realizer (Fin.val : Symbol→ℕ) := + (composition first listLength).reencode parts Fin.val encode_parts (fun a=>by simp [parts]) +lemma polynomial_val : PolynomialTime valRealizer := + polynomial_reencode _ _ _ _ _ (polynomial_composition polynomial_first polynomial_listLength) + +def fromBit (b : Bool) : Symbol := if b then 2 else 1 +def fromBitRealizer : Realizer fromBit := choose identity (constant 2) (constant 1) +lemma polynomial_fromBit : PolynomialTime fromBitRealizer := + polynomial_choose polynomial_identity (polynomial_constant _) (polynomial_constant _) +def natWord (n : ℕ) : List Symbol := (n.bits.map fromBit)++[3] +def natWordRealizer : Realizer natWord := + (composition (pair (composition toBits (map fromBitRealizer)) (constant [3])) append).congr (fun _=>rfl) +lemma polynomial_natWord : PolynomialTime natWordRealizer := by + unfold natWordRealizer + apply polynomial_congr + have := polynomial_fromBit + have := polynomial_toBits + have := polynomial_map polynomial_fromBit + tree_cost +lemma natWord_eq (n : ℕ) : natWord n=encodeNat n := rfl + +def ratWord (x : TreeFraction.Fraction) : List Symbol := 4::natWord x.1++natWord x.2 +def ratWordRealizer : Realizer ratWord := + (composition (pair (constant 4) (composition (pair (composition first natWordRealizer) + (composition second natWordRealizer)) append)) listCons).congr (fun _=>rfl) +lemma polynomial_ratWord : PolynomialTime ratWordRealizer := by + unfold ratWordRealizer + apply polynomial_congr + have := polynomial_natWord + tree_cost +lemma ratWord_repr (q : ℚ) (hq : 0≤q) : ratWord (TreeFraction.repr q)=encodeRat q := by + have hn : ¬q.num<0 := not_lt.mpr (Rat.num_nonneg.mpr hq) + simp only [ratWord,TreeFraction.repr,natWord_eq,encodeRat,encodeInt,ite_eq_right hn,List.singleton_append] +end MatchingFPRAS.LiteralCodec + +end OAI diff --git a/lean/OAI/Combinatorics/MatchingCount/Tapes/CoinAlphabet.lean b/lean/OAI/Combinatorics/MatchingCount/Tapes/CoinAlphabet.lean new file mode 100644 index 0000000000000000000000000000000000000000..f44d322515e2834ead7c7497bdb4f7d15e644bc0 --- /dev/null +++ b/lean/OAI/Combinatorics/MatchingCount/Tapes/CoinAlphabet.lean @@ -0,0 +1,113 @@ +import Mathlib +import OAI.Combinatorics.MatchingCount.Machines.SupportedCompiler +import OAI.Combinatorics.MatchingCount.Graphs.SafeTrace + +namespace OAI + +namespace MatchingFPRAS.CoinAlphabet +open Turing TM1 TM1to1 MachineCost SafeTrace + +variable {Γ Λ σ : Type} [Inhabited Γ] +def safe (p : Λ → Prop) : Λ' Γ Λ σ → Prop + | .normal l => p l + | .write _ _ => True + +def coins (c : CoinTM1.Coins Λ) : CoinTM1.Coins (Λ' Γ Λ σ) + | .normal l => (c l).map (fun f b=>.normal (f b)) + | .write _ _ => none + +variable {n : ℕ} (enc : Γ → List.Vector Bool n) (dec : List.Vector Bool n → Γ) + (enc0 : enc default=List.Vector.replicate n false) + (encdec : ∀ a,dec (enc a)=a) (M : Λ → TM1.Stmt Γ Λ σ) + +include encdec + +theorem statement_path (p : Λ → Prop) (q : TM1.Stmt Γ Λ σ) (v : σ) (L R : ListBlank Γ) : + ∃ t,t≤AlphabetCost.writesCount q ∧ + Path (tr enc dec M) (safe p) t + (stepAux (trNormal dec q) v (trTape' enc0 L R)) + (trCfg enc enc0 (stepAux q v (Tape.mk' L R))) := by + induction q generalizing v L R with + | move d q ih => + cases d <;> + simp only [trNormal,stepAux_move,stepAux,Tape.move_left_mk', + trTape'_move_left enc0,trTape'_move_right enc0,AlphabetCost.writesCount] <;> + apply ih + | write f q ih => + simp only [trNormal,stepAux_read dec enc0 encdec,stepAux,AlphabetCost.writesCount] + obtain ⟨a,R,rfl⟩:=R.exists_cons + obtain ⟨t,ht,he⟩:=ih v L (R.cons (f a v)) + refine ⟨t+1,Nat.add_le_add_right ht 1,?_⟩ + apply Path.cons (by intro l hl; cases hl; trivial) + simp only [advance,TM1.step,tr,Option.getD_some,Tape.mk'_head,ListBlank.head_cons] + rw [stepAux_write enc0,stepAux_move,trTape'_move_left enc0] + simpa using he + | load f q ih => + simp only [trNormal,stepAux_read dec enc0 encdec,stepAux,AlphabetCost.writesCount] + exact ih _ _ _ + | branch p' q r ihq ihr => + simp only [trNormal,stepAux_read dec enc0 encdec,stepAux,Tape.mk'_head,AlphabetCost.writesCount] + cases h:p' R.head v + · simp only [Bool.cond_false] + obtain ⟨t,ht,he⟩:=ihr v L R + exact ⟨t,ht.trans (le_max_right _ _),he⟩ + · simp only [Bool.cond_true] + obtain ⟨t,ht,he⟩:=ihq v L R + exact ⟨t,ht.trans (le_max_left _ _),he⟩ + | goto f => + refine ⟨0,le_rfl,?_⟩ + simp only [trNormal,stepAux_read dec enc0 encdec,stepAux,trCfg,trTape_mk',Tape.mk'_head,Option.map_some] + exact .refl _ + | halt => + refine ⟨0,le_rfl,?_⟩ + simp only [trNormal,stepAux,trCfg,trTape_mk',Option.map_none] + exact .refl _ + +lemma one_step_path (p : Λ → Prop) (c : TM1.Cfg Γ Λ σ) (hc : ∀ l,c.l=some l→p l) : + ∃ t,t≤(match c.l with | none=>0 | some l=>AlphabetCost.writesCount (M l)+1) ∧ + Path (tr enc dec M) (safe p) t (trCfg enc enc0 c) + (trCfg enc enc0 (advance (TM1.step M) c)) := by + rcases c with ⟨l,v,T⟩ + obtain ⟨L,R,rfl⟩:=T.exists_mk' + cases l with + | none => exact ⟨0,le_rfl,.refl _⟩ + | some l => + obtain ⟨t,ht,he⟩:=statement_path enc dec enc0 encdec M p (M l) v L R + refine ⟨t+1,Nat.add_le_add_right ht 1,?_⟩ + apply Path.cons (by intro l' hl; cases hl; exact hc l rfl) + simpa only [advance,TM1.step,Option.map_some,trCfg,tr,Option.getD_some,trTape_mk'] using he + +theorem path_supported [Inhabited Λ] [Inhabited σ] (S : Finset Λ) (hS : TM1.Supports M S) + {p : Λ → Prop} {k : ℕ} {a b : TM1.Cfg Γ Λ σ} + (h : Path M p k a b) (ha : a.l∈S.insertNone) : + ∃ t,t≤k*(AlphabetCost.supportedWrites M S+1) ∧ + Path (tr enc dec M) (safe p) t (trCfg enc enc0 a) (trCfg enc enc0 b) := by + classical + induction h with + | refl a => exact ⟨0,by simp,.refl _⟩ + | @cons k a b hs hr ih => + obtain ⟨i,hi,hiP⟩:=one_step_path enc dec enc0 encdec M p a hs + obtain ⟨j,hj,hjP⟩:=ih (SupportedCompiler.advance_supported M S hS ha) + have hi' : i≤AlphabetCost.supportedWrites M S+1 := by + rcases a with ⟨l,v,T⟩ + cases l with + | none => dsimp at hi; omega + | some l => + have hl:=Finset.some_mem_insertNone.mp ha + have hw : AlphabetCost.writesCount (M l)≤AlphabetCost.supportedWrites M S := + Finset.le_sup (f:=fun l=>AlphabetCost.writesCount (M l)) hl + dsimp at hi + omega + refine ⟨i+j,?_,hiP.trans hjP⟩ + calc i+j≤(AlphabetCost.supportedWrites M S+1)+k*(AlphabetCost.supportedWrites M S+1) := Nat.add_le_add hi' hj + _=(k+1)*(AlphabetCost.supportedWrites M S+1) := by ring + +omit [Inhabited Γ] encdec in +lemma coins_none {c : CoinTM1.Coins Λ} {l : Λ' Γ Λ σ} + (h : safe (fun l=>c l=none) l) : coins c l=none := by + cases l with + | normal l => simp only [coins,safe] at *; rw [h]; rfl + | write a q => rfl +end MatchingFPRAS.CoinAlphabet + +end OAI diff --git a/lean/OAI/Combinatorics/MatchingCount/Tapes/CoinStack.lean b/lean/OAI/Combinatorics/MatchingCount/Tapes/CoinStack.lean new file mode 100644 index 0000000000000000000000000000000000000000..848f7a2e2f336479d1245ec719de657646e1abf3 --- /dev/null +++ b/lean/OAI/Combinatorics/MatchingCount/Tapes/CoinStack.lean @@ -0,0 +1,140 @@ +import Mathlib +import OAI.Combinatorics.MatchingCount.Complexity.StackCompilerCost +import OAI.Combinatorics.MatchingCount.Graphs.SafeTrace + +namespace OAI + +namespace MatchingFPRAS.CoinStack +open Turing TM2to1 TM2to1.Λ' MachineCost StackCost SafeTrace + +variable {K : Type} {Γ : K → Type} {Λ σ : Type} [DecidableEq K] + +def safe (p : Λ → Prop) : Λ' K Γ Λ σ → Prop + | .normal l => p l + | .go _ _ _ | .ret _ => True + +def coins (c : CoinTM1.Coins Λ) : CoinTM1.Coins (Λ' K Γ Λ σ) + | .normal l => (c l).map (fun f b=>.normal (f b)) + | .go _ _ _ | .ret _ => none + +variable (M : Λ → TM2.Stmt Γ Λ σ) (p : Λ → Prop) +lemma go_path {k : K} (o : StAct K Γ σ k) (q : TM2.Stmt Γ Λ σ) (v : σ) + {S : List (Γ k)} {L : ListBlank (∀ k,Option (Γ k))} + (hL : L.map (proj k)=ListBlank.mk (S.map some).reverse) + (n : ℕ) (hn : n≤ S.length) : + Path (tr M) (safe p) n ⟨some (go k o q),v,Tape.mk' ∅ (addBottom L)⟩ + ⟨some (go k o q),v,(Tape.move .right)^[n] (Tape.mk' ∅ (addBottom L))⟩ := by + rw [←go_time M o q v hL n hn] + apply Path.of_run + intro i hi l hl + rw [go_time M o q v hL i (by omega)] at hl + cases hl + trivial + +lemma return_path (q : TM2.Stmt Γ Λ σ) (v : σ) (L : ListBlank (∀ k,Option (Γ k))) (n : ℕ) : + Path (tr M) (safe p) n + ⟨some (ret q),v,(Tape.move .right)^[n] (Tape.mk' ∅ (addBottom L))⟩ + ⟨some (ret q),v,Tape.mk' ∅ (addBottom L)⟩ := by + induction n with + | zero => exact .refl _ + | succ n ih => + apply Path.cons (by intro l hl; cases hl; trivial) + have hs : advance (TM1.step (tr M)) + ⟨some (ret q),v,(Tape.move .right)^[n+1] (Tape.mk' ∅ (addBottom L))⟩= + ⟨some (ret q),v,(Tape.move .right)^[n] (Tape.mk' ∅ (addBottom L))⟩ := by + simp only [advance,TM1.step,tr,TM1.stepAux,Tape.move_right_n_head,Tape.mk'_nth_nat, + addBottom_nth_succ_fst,Bool.cond_false] + rw [Function.iterate_succ_apply',Tape.move_right_left] + rfl + rw [hs] + exact ih + +theorem statement_path (q : TM2.Stmt Γ Λ σ) (v : σ) (S : ∀ k,List (Γ k)) + (L : ListBlank (∀ k,Option (Γ k))) (H : ℕ) (hS : StackBound S H) + (hL : ∀ k,L.map (proj k)=ListBlank.mk ((S k).map some).reverse) : + ∃ (t : ℕ) (b : TM1.Cfg (Γ' K Γ) (Λ' K Γ Λ σ) σ), + t≤ 2*accesses q*(H+accesses q+1) ∧ TrCfg (TM2.stepAux q v S) b ∧ + Path (tr M) (safe p) t + (TM1.stepAux (trNormal q) v (Tape.mk' ∅ (addBottom L))) b := by + induction q using stmtStRec generalizing v S L H with + | run k o q ih => + let v':=stVar v (S k) o + let S':=Function.update S k (stWrite v (S k) o) + have hS' : StackBound S' (H+1):=action_bound hS o v + obtain ⟨L',hL',hact⟩:=tr_respects_aux₂ + (q:=TM1.Stmt.goto fun _ _=>ret q) hL o + obtain ⟨t,b,ht,hb,he⟩:=ih v' S' L' (H+1) hS' hL' + have hgo:=go_path M p o q v (hL k) (S k).length le_rfl + have hs : advance (TM1.step (tr M)) + ⟨some (go k o q),v,(Tape.move .right)^[(S k).length] (Tape.mk' ∅ (addBottom L))⟩= + ⟨some (ret q),v',(Tape.move .right)^[(S' k).length] (Tape.mk' ∅ (addBottom L'))⟩ := by + simp only [advance,TM1.step] + rw [tr,TM1.stepAux,Tape.move_right_n_head,Tape.mk'_nth_nat,addBottom_nth_snd, + stk_nth_val _ (hL k),List.getElem?_eq_none (le_of_eq List.length_reverse)] + simp only [Option.isNone_none,Bool.cond_true] + rw [hact] + rfl + have hstep:=Path.single (M:=tr M) (safe:=safe p) + (⟨some (go k o q),v,(Tape.move .right)^[(S k).length] (Tape.mk' ∅ (addBottom L))⟩) + (by intro l hl; cases hl; trivial) + rw [hs] at hstep + have hret:=return_path M p q v' L' (S' k).length + have hlast:=Path.single (M:=tr M) (safe:=safe p) + (⟨some (ret q),v',Tape.mk' ∅ (addBottom L')⟩) + (by intro l hl; cases hl; trivial) + have hf : advance (TM1.step (tr M)) ⟨some (ret q),v',Tape.mk' ∅ (addBottom L')⟩= + TM1.stepAux (trNormal q) v' (Tape.mk' ∅ (addBottom L')) := by + simp only [advance,TM1.step,tr,TM1.stepAux,Tape.mk'_head,addBottom_head_fst, + Bool.cond_true,Option.getD_some] + rw [hf] at hlast + refine ⟨(S k).length+1+(S' k).length+1+t,b,?_,?_,?_⟩ + · rw [accesses_run] + have h₁:=hS k + have h₂:=hS' k + nlinarith + · simpa only [step_run] using hb + · simpa only [trNormal_run,TM1.stepAux] using (((hgo.trans hstep).trans hret).trans hlast).trans he + | load a q ih => exact ih (a v) S L H hS hL + | branch f q r ihq ihr => + cases hp:f v + · obtain ⟨t,b,ht,hb,he⟩:=ihr v S L H hS hL + refine ⟨t,b,ht.trans ?_,?_,?_⟩ + · simp only [accesses]; gcongr <;> exact le_max_right _ _ + · simpa only [TM2.stepAux,hp,Bool.cond_false] using hb + · simpa only [trNormal,TM1.stepAux,hp,Bool.cond_false] using he + · obtain ⟨t,b,ht,hb,he⟩:=ihq v S L H hS hL + refine ⟨t,b,ht.trans ?_,?_,?_⟩ + · simp only [accesses]; gcongr <;> exact le_max_left _ _ + · simpa only [TM2.stepAux,hp,Bool.cond_true] using hb + · simpa only [trNormal,TM1.stepAux,hp,Bool.cond_true] using he + | goto f => exact ⟨0,_,Nat.zero_le _,⟨L,hL⟩,.refl _⟩ + | halt => exact ⟨0,_,Nat.zero_le _,⟨L,hL⟩,.refl _⟩ + +lemma one_step_path (A : ℕ) (hA : ∀ l,accesses (M l)≤ A) + {c : TM2.Cfg Γ Λ σ} {a : TM1.Cfg (Γ' K Γ) (Λ' K Γ Λ σ) σ} + (hca : TrCfg c a) (hc : ∀ l,c.l=some l→p l) (H : ℕ) (hS : StackBound c.stk H) : + ∃ (t : ℕ) (b : TM1.Cfg (Γ' K Γ) (Λ' K Γ Λ σ) σ), + t≤ 1+2*A*(H+A+1) ∧ TrCfg (advance (TM2.step M) c) b ∧ Path (tr M) (safe p) t a b := by + rcases hca with ⟨L,hL⟩ + rename_i l v S + cases l with + | none => exact ⟨0,_,Nat.zero_le _,⟨L,hL⟩,.refl _⟩ + | some l => + obtain ⟨t,b,ht,hb,he⟩:=statement_path M p (M l) v S L H hS hL + refine ⟨t+1,b,?_,hb,?_⟩ + · have hh : 2*accesses (M l)*(H+accesses (M l)+1)≤ 2*A*(H+A+1) := by + gcongr <;> exact hA l + omega + · apply Path.cons (by intro l' hl; cases hl; exact hc l rfl) + simpa only [advance,TM1.step,Option.map_some,tr,Option.getD_some] using he + +omit [DecidableEq K] in +lemma coins_none {c : CoinTM1.Coins Λ} {l : Λ' K Γ Λ σ} + (h : safe (fun l=>c l=none) l) : coins c l=none := by + cases l with + | normal l => simp only [coins,safe] at *; rw [h]; rfl + | go k o q => rfl + | ret q => rfl +end MatchingFPRAS.CoinStack + +end OAI diff --git a/lean/OAI/Combinatorics/MatchingCount/Tapes/CoinSupport.lean b/lean/OAI/Combinatorics/MatchingCount/Tapes/CoinSupport.lean new file mode 100644 index 0000000000000000000000000000000000000000..10d75c1182e99c216a43331c93b12f518c2dc2df --- /dev/null +++ b/lean/OAI/Combinatorics/MatchingCount/Tapes/CoinSupport.lean @@ -0,0 +1,90 @@ +import Mathlib +import OAI.Combinatorics.MatchingCount.Tapes.CoinAlphabet +import OAI.Combinatorics.MatchingCount.Tapes.CoinStack + +namespace OAI + +namespace MatchingFPRAS.CoinAlphabet +open Turing +open scoped Classical + +variable {Γ Λ σ : Type} [Inhabited Γ] [Fintype Γ] +omit [Inhabited Γ] in +lemma normal_not_writes (l : Λ) (q : TM1.Stmt Γ Λ σ) : TM1to1.Λ'.normal l∉TM1to1.writes q := by + induction q <;> simp_all [TM1to1.writes] +omit [Inhabited Γ] in +lemma normal_mem (M : Λ → TM1.Stmt Γ Λ σ) (S : Finset Λ) (l : Λ) : + TM1to1.Λ'.normal l∈TM1to1.trSupp M S ↔ l∈S := by + simp only [TM1to1.trSupp,Finset.mem_biUnion,Finset.mem_insert,TM1to1.Λ'.normal.injEq, + normal_not_writes,or_false] + constructor + · rintro ⟨l',hl',rfl⟩; exact hl' + · intro hl; exact ⟨l,hl,rfl⟩ +omit [Inhabited Γ] in +lemma coins_supported (M : Λ → TM1.Stmt Γ Λ σ) (S : Finset Λ) (c : CoinTM1.Coins Λ) + (hc : ∀ l∈S,∀ f,c l=some f→∀ b,f b∈S) : + ∀ l∈TM1to1.trSupp M S,∀ f,coins c l=some f→∀ b,f b∈TM1to1.trSupp M S := by + intro l hl f hf b + cases l with + | normal l => + have hl':= (normal_mem M S l).mp hl + simp only [coins,Option.map_eq_some_iff] at hf + obtain ⟨g,hg,rfl⟩:=hf + exact (normal_mem M S (g b)).mpr (hc l hl' g hg b) + | write a q => simp [coins] at hf +lemma cfg_supported (M : Λ → TM1.Stmt Γ Λ σ) (S : Finset Λ) + {n : ℕ} (enc : Γ → List.Vector Bool n) (enc0 : enc default=List.Vector.replicate n false) + (c : TM1.Cfg Γ Λ σ) (hc : c.l∈S.insertNone) : + (TM1to1.trCfg enc enc0 c).l∈(TM1to1.trSupp M S).insertNone := by + rcases c with ⟨l,v,T⟩ + cases l with + | none => simp [TM1to1.trCfg] + | some l => simpa only [TM1to1.trCfg,Option.map_some,Finset.some_mem_insertNone,normal_mem] using hc +end MatchingFPRAS.CoinAlphabet + +namespace MatchingFPRAS.CoinStack +open Turing TM2to1 +open scoped Classical + +variable {K : Type} {Γ : K → Type} {Λ σ : Type} [DecidableEq K] +omit [DecidableEq K] in +lemma normal_not_internal (l : Λ) (q : TM2.Stmt Γ Λ σ) : Λ'.normal l∉trStmts₁ q := by + induction q using stmtStRec with + | run k o q ih => simp_all [trStmts₁_run] + | load f q ih => exact ih + | branch f q r ihq ihr => simp_all [trStmts₁] + | goto f => simp [trStmts₁] + | halt => simp [trStmts₁] +omit [DecidableEq K] in +lemma normal_mem (M : Λ → TM2.Stmt Γ Λ σ) (S : Finset Λ) (l : Λ) : + Λ'.normal l∈trSupp M S ↔ l∈S := by + simp only [trSupp,Finset.mem_biUnion,Finset.mem_insert,Λ'.normal.injEq, + normal_not_internal,or_false] + constructor + · rintro ⟨l',hl',rfl⟩; exact hl' + · intro hl; exact ⟨l,hl,rfl⟩ +omit [DecidableEq K] in +lemma coins_supported (M : Λ → TM2.Stmt Γ Λ σ) (S : Finset Λ) (c : CoinTM1.Coins Λ) + (hc : ∀ l∈S,∀ f,c l=some f→∀ b,f b∈S) : + ∀ l∈trSupp M S,∀ f,coins c l=some f→∀ b,f b∈trSupp M S := by + intro l hl f hf b + cases l with + | normal l => + have hl':= (normal_mem M S l).mp hl + simp only [coins,Option.map_eq_some_iff] at hf + obtain ⟨g,hg,rfl⟩:=hf + exact (normal_mem M S (g b)).mpr (hc l hl' g hg b) + | go k o q => simp [coins] at hf + | ret q => simp [coins] at hf +omit [DecidableEq K] in +lemma cfg_supported (M : Λ → TM2.Stmt Γ Λ σ) (S : Finset Λ) + {c : TM2.Cfg Γ Λ σ} {a : TM1.Cfg (Γ' K Γ) (Λ' K Γ Λ σ) σ} + (hca : TrCfg c a) (hc : c.l∈S.insertNone) : a.l∈(trSupp M S).insertNone := by + rcases hca with ⟨L,hL⟩ + rename_i l v S' + cases l with + | none => simp + | some l => simpa only [Option.map_some,Finset.some_mem_insertNone,normal_mem] using hc +end MatchingFPRAS.CoinStack + +end OAI diff --git a/lean/OAI/Combinatorics/MatchingCount/Tapes/FixedAlphabetCompiler.lean b/lean/OAI/Combinatorics/MatchingCount/Tapes/FixedAlphabetCompiler.lean new file mode 100644 index 0000000000000000000000000000000000000000..aa2a9d6618c998284bb2dfb926437028c94fe4a1 --- /dev/null +++ b/lean/OAI/Combinatorics/MatchingCount/Tapes/FixedAlphabetCompiler.lean @@ -0,0 +1,91 @@ +import Mathlib +import OAI.Combinatorics.MatchingCount.Machines.SupportedCompiler +import OAI.Combinatorics.MatchingCount.Machines.BoolPostCompiler + +namespace OAI + +namespace MatchingFPRAS.FixedAlphabetCompiler +open Turing MachineCost +open scoped Classical + +variable {Γ Λ σ : Type*} [Inhabited Γ] [Fintype Γ] [Inhabited Λ] + [Inhabited σ] [Fintype σ] +variable {w : ℕ} (enc : Γ → List.Vector Bool w) (dec : List.Vector Bool w → Γ) + (enc0 : enc default = List.Vector.replicate w false) + (encdec : ∀ a,dec (enc a)=a) (M : Λ → TM1.Stmt Γ Λ σ) + (S : Finset Λ) (hS : TM1.Supports M S) +def bitsWord (input : List Γ) : List Bool := input.flatMap (fun a=>(enc a).toList) +def word (input : List Γ) : List Symbol := (bitsWord enc input).map BoolPostCompiler.up +omit [Fintype Γ] [Fintype σ] in +lemma initial_block (input : List Γ) : + TM1to1.trCfg enc enc0 (TM1.init (Λ:=Λ) (σ:=σ) input)= + TM1.init (bitsWord enc input) := by + simp only [TM1to1.trCfg,TM1.init,Option.map_some,TM1to1.trTape,TM1to1.trTape', + Tape.mk₁,Tape.mk₂,Tape.mk'_left,Tape.mk'_right₀,ListBlank.flatMap_mk, + List.flatMap_nil,bitsWord] + rfl +omit [Fintype Γ] [Fintype σ] [Inhabited Λ] [Inhabited σ] in +lemma output_block (c : TM1.Cfg Γ Λ σ) (output : List Γ) + (h : c.Tape.right₀=ListBlank.mk output) : + (TM1to1.trCfg enc enc0 c).Tape.right₀=ListBlank.mk (bitsWord enc output) := by + change (TM1to1.trTape enc0 c.Tape).right₀=_ + simp only [TM1to1.trTape,TM1to1.trTape',Tape.mk'_right₀,h,ListBlank.flatMap_mk,bitsWord] +noncomputable def support := TM1to1.trSupp M S +include hS in +omit [Inhabited Γ] [Inhabited σ] [Fintype σ] in +lemma block_support : TM1.Supports (TM1to1.tr enc dec M) (support M S) := + TM1to1.tr_supports enc dec M hS +noncomputable def compiled : RandomMachine := + BoolPostCompiler.compiled (TM1to0.tr (TM1to1.tr enc dec M)) + (TM1to0.trStmts (TM1to1.tr enc dec M) (support M S)) + (TM1to0.tr_supports _ (block_support enc dec M S hS)) +noncomputable def cost : ℕ := + SupportedCompiler.cost (TM1to1.tr enc dec M) (support M S) * + (AlphabetCost.supportedWrites M S+1) +include encdec enc0 + +theorem compiled_words (input output : List Γ) (n t : ℕ) + (hhalt : (MachineCost.run (TM1.step M) n (TM1.init input)).l=none) + (hout : (MachineCost.run (TM1.step M) n (TM1.init input)).Tape.right₀= + ListBlank.mk output) + (ht : cost enc dec M S*n+2 ≤ t) (bits : Fin t → Bool) : + (MatchingFPRAS.run (compiled enc dec M S hS) (word enc input) bits).state=none ∧ + (MatchingFPRAS.run (compiled enc dec M S hS) (word enc input) bits).tape.right₀= + ListBlank.mk (word enc output) := by + have hi : (TM1.init (Λ:=Λ) (σ:=σ) input).l ∈ S.insertNone := + Finset.some_mem_insertNone.mpr hS.1 + obtain ⟨b,hb,he⟩:=AlphabetCost.execution_supported enc dec enc0 encdec M S hS hi n + rw [initial_block] at he + have hS' := block_support enc dec M S hS + have hi' : (TM1.init (Λ:=TM1to1.Λ' Γ Λ σ) (σ:=σ) (bitsWord enc input)).l ∈ + (support M S).insertNone := Finset.some_mem_insertNone.mpr hS'.1 + obtain ⟨k,hk,hke⟩:=SupportedCompiler.post_time (TM1to1.tr enc dec M) (support M S) hS' hi' b + have initpost : TM1to0.trCfg (TM1to1.tr enc dec M) + (TM1.init (bitsWord enc input))=TM0.init (bitsWord enc input) := rfl + rw [initpost,he] at hke + have hh : TM0.step (TM1to0.tr (TM1to1.tr enc dec M)) + (MachineCost.run (TM0.step (TM1to0.tr (TM1to1.tr enc dec M))) k + (TM0.init (bitsWord enc input)))=none := by + rw [hke] + generalize hc:MachineCost.run (TM1.step M) n (TM1.init input)=c at hhalt ⊢ + rcases c with ⟨l,v,T⟩ + change l=none at hhalt + subst l + rfl + have ho : (MachineCost.run (TM0.step (TM1to0.tr (TM1to1.tr enc dec M))) k + (TM0.init (bitsWord enc input))).Tape.right₀=ListBlank.mk (bitsWord enc output) := by + rw [hke] + exact output_block enc enc0 _ output hout + have hkt : k+2 ≤ t := by + apply (Nat.add_le_add_right (hk.trans (Nat.mul_le_mul_left _ hb)) 2).trans + have hp : SupportedCompiler.cost (TM1to1.tr enc dec M) (support M S) * + (n*(AlphabetCost.supportedWrites M S+1))+2 = cost enc dec M S*n+2 := by + unfold cost + ring + rw [hp] + exact ht + exact BoolPostCompiler.compiled_words _ _ _ (bitsWord enc input) (bitsWord enc output) + k t hh ho hkt bits +end MatchingFPRAS.FixedAlphabetCompiler + +end OAI diff --git a/lean/OAI/Combinatorics/MatchingCount/Tapes/FixedEncoding.lean b/lean/OAI/Combinatorics/MatchingCount/Tapes/FixedEncoding.lean new file mode 100644 index 0000000000000000000000000000000000000000..4f0866e9d4b39242ad900f0fb133e84ffaa1d63d --- /dev/null +++ b/lean/OAI/Combinatorics/MatchingCount/Tapes/FixedEncoding.lean @@ -0,0 +1,42 @@ +import Mathlib +import OAI.Combinatorics.MatchingCount.Tapes.FixedAlphabetCompiler + +namespace OAI + +namespace MatchingFPRAS.FixedEncoding +variable (Γ : Type*) [Fintype Γ] [Inhabited Γ] +noncomputable def enc (a : Γ) : List.Vector Bool (Fintype.card Γ) := by + classical + exact List.Vector.ofFn (fun i=>decide (a≠default ∧ Fintype.equivFin Γ a=i)) +lemma blank : enc Γ default=List.Vector.replicate (Fintype.card Γ) false := by + classical + apply List.Vector.ext + intro i + simp [enc] +lemma injective : Function.Injective (enc Γ) := by + classical + intro a b hab + by_cases ha : a=default + · by_cases hb : b=default + · exact ha.trans hb.symm + · have hh:=congrArg (fun v : List.Vector Bool (Fintype.card Γ)=>v.get (Fintype.equivFin Γ b)) hab + simp [enc,ha,hb] at hh + · have hh:=congrArg (fun v : List.Vector Bool (Fintype.card Γ)=>v.get (Fintype.equivFin Γ a)) hab + simp only [enc,List.Vector.get_ofFn] at hh + have ht : decide (b≠default ∧ Fintype.equivFin Γ b=Fintype.equivFin Γ a)=true := by + simpa [ha] using hh.symm + exact ((Fintype.equivFin Γ).injective (of_decide_eq_true ht).2).symm +noncomputable def dec : List.Vector Bool (Fintype.card Γ) → Γ := Function.invFun (enc Γ) +lemma left_inverse (a : Γ) : dec Γ (enc Γ a)=a := + Function.leftInverse_invFun (injective Γ) a +lemma bitsWord_length {Γ : Type*} {w : ℕ} (e : Γ → List.Vector Bool w) (input : List Γ) : + (FixedAlphabetCompiler.bitsWord e input).length=w*input.length := by + induction input with + | nil => simp [FixedAlphabetCompiler.bitsWord] + | cons a input ih => + simp only [FixedAlphabetCompiler.bitsWord,List.flatMap_cons,List.length_append] at ih ⊢ + rw [show (e a).toList.length=w from (e a).2,ih,List.length_cons,Nat.mul_add,Nat.mul_one] + omega +end MatchingFPRAS.FixedEncoding + +end OAI diff --git a/lean/OAI/Combinatorics/MatchingCount/Tapes/GuardBits.lean b/lean/OAI/Combinatorics/MatchingCount/Tapes/GuardBits.lean new file mode 100644 index 0000000000000000000000000000000000000000..b6f8c513888045ed62466bed03882df8c5fd1ba1 --- /dev/null +++ b/lean/OAI/Combinatorics/MatchingCount/Tapes/GuardBits.lean @@ -0,0 +1,121 @@ +import Mathlib +import OAI.Combinatorics.MatchingCount.Algorithm.GuardProbability + +namespace OAI + +namespace MatchingFPRAS.FiniteTrial +open Transport Enlargement Variation Adaptive Amplification Finset +open scoped Classical + +variable {G : GraphInput} [Nontrivial (Fin G.n)] +attribute [local instance] NumberedHierarchy.labelOrder sym2Order bagEdgeOrder bagEdgeFintype +attribute [local instance] UnitRefresh.Computable.allowedDec prodOrder sumOrder +noncomputable local instance (w : Fin G.n → Fin G.n → ℚ) (K : ℕ) : + DecidableEq (SourceLabel (fun x y=>(w x y:ℝ)) K) := Classical.decEq _ +noncomputable local instance (w : Fin G.n → Fin G.n → ℚ) (K : ℕ) : + Fintype (BagEdge (sourceBags (fun x y=>(w x y:ℝ)) K)) := Fintype.ofFinite _ +noncomputable local instance (w : Fin G.n → Fin G.n → ℚ) (K : ℕ) : + Fintype (SourceMarked (fun x y=>(w x y:ℝ)) K) := Fintype.ofFinite _ + +noncomputable def guardBits (p : Trial.Parameters G) : ℕ := 16*oneBits p +noncomputable def ScaleState.drawGuard (p : Trial.Parameters G) (s : ScaleState G p.K) : + (Fin (guardBits p) → Bool) → GuardSamples p s := + (fun b i=>s.drawOne p le_rfl (b i)) ∘ matrixBitsEquiv 16 (oneBits p) +lemma ScaleState.drawGuard_law (p : Trial.Parameters G) (s : ScaleState G p.K) : + imageLaw (s.drawGuard p)=(guardLaw p s).mass := by + unfold ScaleState.drawGuard + erw [imageLaw_comp_equiv,imageLaw_componentwise] + rw [ScaleState.drawOne_law] + rfl +lemma ScaleState.drawGuard_no_certificate (p : Trial.Parameters G) (s : ScaleState G p.K) + (hZ : Z G = 0) (b : Fin (guardBits p) → Bool) : ¬guardPass p s (s.drawGuard p b) := by + dsimp only [guardBits] at b + dsimp only [guardPass, ScaleState.drawGuard, guardBits, Function.comp_apply] + simp only [s.drawOne_certificate_zero p le_rfl hZ, lt_self_iff_false, exists_const, not_false_eq_true] + +noncomputable def guardedBits (p : Trial.Parameters G) : ℕ := p.K*stageBits p+guardBits p +noncomputable def drawGuarded (p : Trial.Parameters G) : + (Fin (guardedBits p) → Bool) → GuardedTrial p := + fun b => + let c := pairBitsEquiv (p.K*stageBits p) (guardBits p) b + let x := drawLayer p p.K le_rfl c.1 + ⟨x,((layers p p.K le_rfl).state x).drawGuard p c.2⟩ +lemma drawGuarded_law (p : Trial.Parameters G) : imageLaw (drawGuarded p)=(guardedLaw p).mass := by + change imageLaw ((fun c : (Fin (p.K*stageBits p) → Bool) × (Fin (guardBits p) → Bool) => + (⟨drawLayer p p.K le_rfl c.1, + ((layers p p.K le_rfl).state (drawLayer p p.K le_rfl c.1)).drawGuard p c.2⟩ : GuardedTrial p)) ∘ + pairBitsEquiv (p.K*stageBits p) (guardBits p)) = _ + erw [imageLaw_comp_equiv] + change imageLaw _ = sigmaLift (layers p p.K le_rfl).law.mass (fun x=>(guardLaw p ((layers p p.K le_rfl).state x)).mass) + rw [imageLaw_sigma_pair (drawLayer p p.K le_rfl) (fun x=>((layers p p.K le_rfl).state x).drawGuard p)] + simp_rw [ScaleState.drawGuard_law] + rw [drawLayer_law] +noncomputable def guardedBitOutput (p : Trial.Parameters G) : (Fin (guardedBits p) → Bool) → ℚ := + guardedOutput p ∘ drawGuarded p +lemma guardedBitOutput_nonneg (p : Trial.Parameters G) (b : Fin (guardedBits p) → Bool) : + 0≤guardedBitOutput p b := guardedOutput_nonneg p _ +theorem guardedBitOutput_zero (p : Trial.Parameters G) (hZ : Z G=0) (b : Fin (guardedBits p) → Bool) : + guardedBitOutput p b=0 := by + unfold guardedBitOutput drawGuarded + simp only [Function.comp_apply, guardedOutput] + exact ite_eq_right (ScaleState.drawGuard_no_certificate p _ hZ _) + +noncomputable def guardedAmplifiedBits (p : Trial.Parameters G) (δ : ℚ) : ℕ := + (2*halfRepetitions δ+1)*guardedBits p +noncomputable def drawGuardedTrials (p : Trial.Parameters G) (δ : ℚ) : + (Fin (guardedAmplifiedBits p δ) → Bool) → Fin (2*halfRepetitions δ+1) → GuardedTrial p := + (fun bits i=>drawGuarded p (bits i)) ∘ matrixBitsEquiv (2*halfRepetitions δ+1) (guardedBits p) +lemma drawGuardedTrials_law (p : Trial.Parameters G) (δ : ℚ) : + imageLaw (drawGuardedTrials p δ)=((guardedLaw p).iid (2*halfRepetitions δ+1)).mass := by + unfold drawGuardedTrials + erw [imageLaw_comp_equiv,imageLaw_componentwise] + rw [drawGuarded_law] + rfl +noncomputable def guardedAmplifiedOutput (p : Trial.Parameters G) (δ : ℚ) + (x : Fin (2*halfRepetitions δ+1) → GuardedTrial p) : ℚ := median (fun i=>guardedOutput p (x i)) +noncomputable def guardedAmplifiedBitOutput (p : Trial.Parameters G) (δ : ℚ) : + (Fin (guardedAmplifiedBits p δ) → Bool) → ℚ := guardedAmplifiedOutput p δ ∘ drawGuardedTrials p δ +lemma guardedAmplifiedBitOutput_nonneg (p : Trial.Parameters G) (δ : ℚ) + (b : Fin (guardedAmplifiedBits p δ) → Bool) : 0≤guardedAmplifiedBitOutput p δ b := + median_nonneg _ (fun _=>guardedOutput_nonneg p _) + +omit [Nontrivial (Fin G.n)] in +lemma median_eq_of_constant {k : ℕ} (x : Fin (2*k+1) → ℚ) (a : ℚ) (hx : ∀ i,x i=a) : median x=a := by + unfold median sortedValue + have hp := List.mergeSort_perm (List.ofFn x) (· ≤ ·) + have hm : (sortedList x)[k]'(by rw [sortedList_length]; omega) ∈ List.ofFn x := + hp.mem_iff.mp (List.getElem_mem _) + obtain ⟨i,hi⟩ := List.mem_ofFn.mp hm + rw [←hi, hx] + +theorem guardedAmplifiedBitOutput_zero (p : Trial.Parameters G) (hZ : Z G=0) (δ : ℚ) + (b : Fin (guardedAmplifiedBits p δ) → Bool) : guardedAmplifiedBitOutput p δ b=0 := by + apply median_eq_of_constant + intro i + exact guardedBitOutput_zero p hZ _ + +noncomputable def guardedAccurateBits (p : Trial.Parameters G) (δ : ℚ) : Finset (Fin (guardedAmplifiedBits p δ) → Bool) := + univ.filter fun b=>Accurate p (guardedAmplifiedBitOutput p δ b) +theorem guardedAmplifiedBitOutput_success (p : Trial.Parameters G) (hZ : 0Accurate p (guardedAmplifiedOutput p δ x)) + rw [Law.total] at hc + have hh : 1-(δ:ℝ) ≤ event ((guardedLaw p).iid (2*halfRepetitions δ+1)).mass + (fun x=>Accurate p (guardedAmplifiedOutput p δ x)) := by + change event _ (fun x=>¬Accurate p (guardedAmplifiedOutput p δ x))≤(δ:ℝ) at hf + linarith only [hc,hf] + rw [←drawGuardedTrials_law,event_imageLaw] at hh + have he : Fintype.card (Fin (guardedAmplifiedBits p δ) → Bool)=2^(guardedAmplifiedBits p δ) := by simp + rw [he] at hh + change 1-(δ:ℝ) ≤ ((guardedAccurateBits p δ).card:ℝ)/(2^(guardedAmplifiedBits p δ):ℕ) at hh + have hr : ((1-δ:ℚ):ℝ) ≤ (((((guardedAccurateBits p δ).card:ℚ)/(2:ℚ)^(guardedAmplifiedBits p δ)):ℚ):ℝ) := by + push_cast + simpa only [Nat.cast_pow,Nat.cast_ofNat] using hh + exact Rat.cast_le.mp hr + +end MatchingFPRAS.FiniteTrial + +end OAI diff --git a/lean/OAI/Combinatorics/MatchingCount/Tapes/Input.lean b/lean/OAI/Combinatorics/MatchingCount/Tapes/Input.lean new file mode 100644 index 0000000000000000000000000000000000000000..80764755f3e9d09baddec80fb9bfb38945576dfb --- /dev/null +++ b/lean/OAI/Combinatorics/MatchingCount/Tapes/Input.lean @@ -0,0 +1,148 @@ +import Mathlib +import OAI.Combinatorics.MatchingCount.Machines.TreeListMore +import OAI.Combinatorics.MatchingCount.Tapes.Parse + +namespace OAI + +namespace MatchingFPRAS.LiteralInput +open TreeTyped TreeFunction Polynomial LiteralParse + +abbrev PairState := (Bool×ℕ)×List (ℕ×ℕ) +def pairStep (x : ℕ×PairState) : PairState := + if x.2.1.1 then ((false,0),(x.1,x.2.1.2)::x.2.2) else ((true,x.1),x.2.2) +def pairStepRealizer : Realizer pairStep := + (choose second.fst.fst + (pair (constant (false,0)) (composition (pair (pair first second.fst.snd) second.snd) listCons)) + (pair (pair (constant true) first) second.snd)).congr (by + intro x;simp only [Function.comp_apply,pairStep]) +lemma polynomial_pairStep : PolynomialTime pairStepRealizer := by + unfold pairStepRealizer + apply polynomial_congr + dsimp only [Realizer.fst,Realizer.snd] + tree_cost +lemma pairStep_weight (n : ℕ) (s : PairState) : weight (pairStep (n,s)) ≤ weight s+weight n+4 := by + rcases s with ⟨⟨b,m⟩,es⟩ + cases b + · change weight ((true,n),es) ≤ weight ((false,m),es)+weight n+4 + simp only [weight_prod] + change 1+(1+3+weight n)+weight es ≤ 1+(1+1+weight m)+weight es+weight n+4 + omega + · change weight ((false,0),(n,m)::es) ≤ weight ((true,m),es)+weight n+4 + simp only [weight_prod,weight_cons] + change 1+(1+1+1)+(1+(1+weight n+weight m)+weight es) ≤ + 1+(1+3+weight m)+weight es+weight n+4 + omega +lemma pairFold_weight (ns : List ℕ) (s : PairState) : + weight (ns.foldl (fun s n=>pairStep (n,s)) s) ≤ weight s+5*weight ns := by + induction ns generalizing s with + | nil => simp + | cons n ns ih => + have h := ih (pairStep (n,s)) + have h' := pairStep_weight n s + simp only [List.foldl_cons,weight_cons] + omega +lemma polynomial_pairFold : PolynomialTime (fold pairStepRealizer) := by + apply polynomial_fold polynomial_pairStep (6*X) + intro as s pre post he + have h := pairFold_weight pre s + have hw : weight pre ≤ weight as := by + have ha := weight_append pre post + have hp := weight_pos post + rw [he] + omega + simp only [Polynomial.eval_mul,Polynomial.eval_ofNat,Polynomial.eval_X,weight_prod] + omega + +def pairs (ns : List ℕ) : List (ℕ×ℕ) := (ns.foldl (fun s n=>pairStep (n,s)) ((false,0),[])).2 +def pairsRealizer : Realizer pairs := + (composition + (composition (pair identity (constant (((false,0),[]) : PairState))) (fold pairStepRealizer)) second).congr (fun _=>rfl) +lemma polynomial_pairs : PolynomialTime pairsRealizer := + polynomial_congr _ (polynomial_composition (polynomial_composition (polynomial_pair polynomial_identity (polynomial_constant _)) + polynomial_pairFold) polynomial_second) +lemma pair_pair (i j : ℕ) (es : List (ℕ×ℕ)) : + pairStep (i,pairStep (j,((false,0),es)))=((false,0),(i,j)::es) := rfl +lemma pairs_reverse (es : List (ℕ×ℕ)) (acc : List (ℕ×ℕ)) : + ((es.flatMap (fun e=>[e.1,e.2])).reverse.foldl (fun s n=>pairStep (n,s)) ((false,0),acc))= + ((false,0),es++acc) := by + induction es generalizing acc with + | nil => rfl + | cons e es ih => + simp only [List.flatMap_cons,List.reverse_append,List.reverse_cons,List.reverse_nil, + List.nil_append,List.singleton_append,List.foldl_append,ih,List.foldl_cons,List.foldl_nil,pair_pair] + rfl + +abbrev Parsed := ℕ×(List (ℕ×ℕ)×(TreeFraction.Fraction×TreeFraction.Fraction)) +def ratTail (ns : List ℕ) : TreeFraction.Fraction×TreeFraction.Fraction := + ((ns.tail.tail.tail.headD 0,ns.tail.tail.headD 0),(ns.tail.headD 0,ns.headD 0)) +def ratTailRealizer : Realizer ratTail := + pair (pair (composition (composition (composition tail tail) tail) (head 0)) + (composition (composition tail tail) (head 0))) + (pair (composition tail (head 0)) (head 0)) +lemma polynomial_ratTail : PolynomialTime ratTailRealizer := by + unfold ratTailRealizer + exact TreeTyped.polynomial_pair + (TreeTyped.polynomial_pair + (polynomial_composition (polynomial_composition (polynomial_composition polynomial_tail polynomial_tail) + polynomial_tail) (polynomial_head _)) + (polynomial_composition (polynomial_composition polynomial_tail polynomial_tail) (polynomial_head _))) + (TreeTyped.polynomial_pair (polynomial_composition polynomial_tail (polynomial_head _)) (polynomial_head _)) + +def fromNumbers (ns : List ℕ) : Parsed := + (ns.headD 0,(pairs ns.tail.tail.reverse.tail.tail.tail.tail,ratTail ns.tail.tail.reverse)) +def reversedTailRealizer : Realizer (fun ns : List ℕ=>ns.tail.tail.reverse) := + composition (composition tail tail) reverse +def fromNumbersRealizer : Realizer fromNumbers := + (pair (head 0) (pair + (composition (composition (composition (composition (composition reversedTailRealizer tail) tail) tail) tail) pairsRealizer) + (composition reversedTailRealizer ratTailRealizer))).congr (fun _=>rfl) +lemma polynomial_reversedTail : PolynomialTime reversedTailRealizer := + polynomial_composition (polynomial_composition polynomial_tail polynomial_tail) polynomial_reverse +lemma polynomial_fromNumbers : PolynomialTime fromNumbersRealizer := by + unfold fromNumbersRealizer + apply polynomial_congr + apply polynomial_pair (polynomial_head _) + apply polynomial_pair + · exact polynomial_composition (polynomial_composition (polynomial_composition + (polynomial_composition (polynomial_composition polynomial_reversedTail polynomial_tail) polynomial_tail) + polynomial_tail) polynomial_tail) polynomial_pairs + · exact polynomial_composition polynomial_reversedTail polynomial_ratTail + +def parseInput (as : List Symbol) : Parsed := fromNumbers (LiteralParse.parse as) +def parseInputRealizer : Realizer parseInput := composition LiteralParse.parseRealizer fromNumbersRealizer +lemma polynomial_parseInput : PolynomialTime parseInputRealizer := + polynomial_composition LiteralParse.polynomial_parse polynomial_fromNumbers + +def edgeNumbers (G : GraphInput) : List (ℕ×ℕ) := + ((G.edges.map toLex.toEmbedding).sort (·≤·)).map (fun e=>((ofLex e).1.val,(ofLex e).2.val)) +lemma edges_fold (es : List (ℕ×ℕ)) (ns : List ℕ) : + (es.flatMap (fun e=>encodeNat e.1++encodeNat e.2)).foldr (fun a ns=>numStep (a,ns)) ns= + es.flatMap (fun e=>[e.1,e.2])++ns := by + induction es with + | nil => rfl + | cons e es ih => + simp only [List.flatMap_cons,List.foldr_append,ih,encodeNat_fold] + rfl +lemma parse_source (G : GraphInput) (ε δ : ℚ) : LiteralParse.parse (encodeInput G ε δ)= + G.n::G.edges.card::(edgeNumbers G).flatMap (fun e=>[e.1,e.2])++[ε.num.natAbs,ε.den,δ.num.natAbs,δ.den] := by + unfold encodeInput LiteralParse.parse + simp only [List.foldr_append,encodeNat_fold,encodeRat_fold] + rw [show (((G.edges.map toLex.toEmbedding).sort (·≤·)).flatMap fun e=>encodeNat (ofLex e).1.val++encodeNat (ofLex e).2.val)= + (edgeNumbers G).flatMap (fun e=>encodeNat e.1++encodeNat e.2) by simp only [edgeNumbers,List.flatMap_map]] + rw [edges_fold] + rfl +lemma parseInput_source (G : GraphInput) (ε δ : ℚ) : + parseInput (encodeInput G ε δ)=(G.n,(edgeNumbers G,(TreeFraction.repr ε,TreeFraction.repr δ))) := by + rw [parseInput,parse_source] + unfold fromNumbers + simp only [List.cons_append,List.headD_cons,List.tail_cons, + List.reverse_append,List.reverse_cons,List.reverse_nil,List.nil_append] + unfold ratTail + simp only [List.headD_cons,List.tail_cons] + unfold pairs + rw [pairs_reverse] + simp only [List.append_nil] + rfl +end MatchingFPRAS.LiteralInput + +end OAI diff --git a/lean/OAI/Combinatorics/MatchingCount/Tapes/Online.lean b/lean/OAI/Combinatorics/MatchingCount/Tapes/Online.lean new file mode 100644 index 0000000000000000000000000000000000000000..635ee2eab6cbe19e56d181f46a7998a66236bfd6 --- /dev/null +++ b/lean/OAI/Combinatorics/MatchingCount/Tapes/Online.lean @@ -0,0 +1,91 @@ +import Mathlib +import OAI.Combinatorics.MatchingCount.Tapes.OnlineStackCompiler + +namespace OAI + +namespace MatchingFPRAS.OnlineStack +open Turing MachineCost PhysicalStream + +variable {K Λ σ α : Type} {Γ : K → Type} [DecidableEq K] + +inductive Executes (M : Λ → TM2.Stmt Γ Λ σ) (coin : CoinTM1.Coins Λ) + (out : α → TM2.Cfg Γ Λ σ) : TM2.Cfg Γ Λ σ → Experiment α → Prop + | done (a) : Executes M coin out (out a) (.done a) + | read (l v S) (f : Bool → Λ) (p : Bool → Experiment α) + (hf : coin l=some f) + (rest : ∀ b,Executes M coin out ⟨some (f b),v,S⟩ (p b)) : + Executes M coin out ⟨some l,v,S⟩ (.read p) + | step (l v S) (p : Experiment α) (safe : coin l=none) + (rest : Executes M coin out (TM2.stepAux (M l) v S) p) : + Executes M coin out ⟨some l,v,S⟩ (.delay 1 p) + +namespace Executes +variable {M : Λ → TM2.Stmt Γ Λ σ} {coin : CoinTM1.Coins Λ} + {out : α → TM2.Cfg Γ Λ σ} {c : TM2.Cfg Γ Λ σ} {p : Experiment α} +lemma bind {β : Type} (h : Executes M coin out c p) (q : α → Experiment β) + (out' : β → TM2.Cfg Γ Λ σ) (hq : ∀ a,Executes M coin out' (out a) (q a)) : + Executes M coin out' c (p.bind q) := by + induction h with + | done a => exact hq a + | read l v S f p hf rest ih => exact .read l v S f _ hf ih + | step l v S p safe rest ih => exact .step l v S _ safe ih + +variable [Fintype K] [∀ k,Fintype (Γ k)] [Inhabited Λ] [Fintype Λ] + [Inhabited σ] [Fintype σ] + +noncomputable def factor (M : Λ → TM2.Stmt Γ Λ σ) (H n : ℕ) : ℕ := + overhead M*(1+2*accesses M*(H+n*accesses M+1))+1 +omit [Inhabited Λ] [Inhabited σ] [Fintype σ] in +lemma factor_mono [Inhabited Λ] [Inhabited σ] [Fintype σ] + (H H' n n' : ℕ) (hH : H≤H') (hn : n≤n') : + factor M H n ≤ factor M H' n' := by unfold factor; gcongr +omit [Inhabited Λ] [Inhabited σ] [Fintype σ] in +lemma factor_shift [Inhabited Λ] [Inhabited σ] [Fintype σ] + (H n : ℕ) : factor M (H+accesses M) n=factor M H (1+n) := by + unfold factor + congr 3; ring + +theorem compile (h : Executes M coin out c p) (H : ℕ) (hH : StackCost.StackBound c.stk H) : + ∃ q : Experiment α, + PhysicalPost.Implements (table M coin) (fun a=>cfg (out a)) (cfg c) q ∧ + (∀ f : α → ℚ,q.mean f=p.mean f) ∧ q.cost ≤ p.cost*factor M H p.cost := by + induction h generalizing H with + | done a => exact ⟨.done a,.done a,fun _=>rfl,by simp [Experiment.cost]⟩ + | read l v S f p hf rest ih => + choose q hq hmean hcost using fun b=>ih b H hH + refine ⟨.read q,.read _ q (fun b=>?_),?_,?_⟩ + · rw [random M coin l v S f hf b] + exact hq b + · intro g + simp only [Experiment.mean,hmean] + · have hn0 : (p false).cost≤1+max (p false).cost (p true).cost := by omega + have hn1 : (p true).cost≤1+max (p false).cost (p true).cost := by omega + have hc0 := (hcost false).trans (Nat.mul_le_mul_left (p false).cost (factor_mono (M:=M) H H _ _ le_rfl hn0)) + have hc1 := (hcost true).trans (Nat.mul_le_mul_left (p true).cost (factor_mono (M:=M) H H _ _ le_rfl hn1)) + have hp : 1≤factor M H (1+max (p false).cost (p true).cost) := by unfold factor; omega + simp only [Experiment.cost] + have hf0 := Nat.mul_le_mul_right (factor M H (1+max (p false).cost (p true).cost)) (le_max_left (p false).cost (p true).cost) + have hf1 := Nat.mul_le_mul_right (factor M H (1+max (p false).cost (p true).cost)) (le_max_right (p false).cost (p true).cost) + calc + 1+max (q false).cost (q true).cost ≤ 1+max (p false).cost (p true).cost*factor M H (1+max (p false).cost (p true).cost) := by omega + _≤ (1+max (p false).cost (p true).cost)*factor M H (1+max (p false).cost (p true).cost) := by nlinarith + | step l v S p safe rest ih => + let c : TM2.Cfg Γ Λ σ:=⟨some l,v,S⟩ + have hs : ∀ u,c.l=some u→coin u=none := by intro u hu; cases hu; exact safe + obtain ⟨k,hk,he⟩:=deterministic M coin c hs H hH + obtain ⟨q,hq,hm,hc⟩:=ih (H+accesses M) (StackCost.advance_bound M _ (accesses_bound M) c H hH) + refine ⟨.delay k q,.delay _ _ k q he hq,hm,?_⟩ + simp only [Experiment.cost] + rw [factor_shift] at hc + have hfac : k≤factor M H (1+p.cost) := by + apply hk.trans + unfold factor + have hh : H+accesses M+1≤H+(1+p.cost)*accesses M+1 := by nlinarith + have hb : overhead M*(1+2*accesses M*(H+accesses M+1))≤ + overhead M*(1+2*accesses M*(H+(1+p.cost)*accesses M+1)) := by gcongr + omega + nlinarith +end Executes +end MatchingFPRAS.OnlineStack + +end OAI diff --git a/lean/OAI/Combinatorics/MatchingCount/Tapes/OnlineComposition.lean b/lean/OAI/Combinatorics/MatchingCount/Tapes/OnlineComposition.lean new file mode 100644 index 0000000000000000000000000000000000000000..87b2380dce03843ce1af689cb85df5fbe1a375ef --- /dev/null +++ b/lean/OAI/Combinatorics/MatchingCount/Tapes/OnlineComposition.lean @@ -0,0 +1,106 @@ +import Mathlib +import OAI.Combinatorics.MatchingCount.Machines.TreeFrame +import OAI.Combinatorics.MatchingCount.Tapes.Online + +namespace OAI + +namespace MatchingFPRAS.OnlineStack +open Turing MachineCost PhysicalStream StackComposition + +variable {K Λ Λ' σ α : Type} {Γ : K → Type} [DecidableEq K] +namespace Executes +lemma relabel {M : Λ → TM2.Stmt Γ Λ σ} {coin : CoinTM1.Coins Λ} + {out : α → TM2.Cfg Γ Λ σ} {c : TM2.Cfg Γ Λ σ} {p : Experiment α} + (h : Executes M coin out c p) (N : Λ' → TM2.Stmt Γ Λ' σ) + (co : CoinTM1.Coins Λ') (f : Λ → Λ') (halt : Option Λ') + (hN : ∀ l,N (f l)=StackComposition.relabel f halt (M l)) + (hco : ∀ l,co (f l)=(coin l).map (fun g=>f ∘ g)) : + Executes N co (fun a=>mapCfg f halt (out a)) (mapCfg f halt c) p := by + induction h with + | done a => exact .done a + | read l v S g p hg rest ih => + apply Executes.read (f l) v S (f ∘ g) p + · rw [hco,hg]; rfl + · exact ih + | step l v S p hs rest ih => + apply Executes.step (f l) v S p + · rw [hco,hs]; rfl + · rw [hN,StackComposition.relabel_eval] + exact ih + +lemma of_run (M : Λ → TM2.Stmt Γ Λ σ) (n : ℕ) (c : TM2.Cfg Γ Λ σ) + (v : σ) (S : ∀ k,List (Γ k)) (he : MachineCost.run (TM2.step M) n c=⟨none,v,S⟩) : + ∃ p : Experiment Unit,Executes M (fun _=>none) (fun _ : Unit=>⟨none,v,S⟩) c p ∧ + (∀ f : Unit → ℚ,p.mean f=f ()) ∧ p.cost≤n := by + induction n generalizing c with + | zero => cases he; exact ⟨.done (),.done (),fun _=>rfl,le_rfl⟩ + | succ n ih => + rcases c with ⟨l,v',S'⟩ + cases l with + | none => + rw [StackComposition.run_halted] at he + cases he + exact ⟨.done (),.done (),fun _=>rfl,Nat.zero_le _⟩ + | some l => + obtain ⟨p,hp,hm,hc⟩:=ih (TM2.stepAux (M l) v' S') he + exact ⟨.delay 1 p,.step l v' S' p rfl hp,hm,by simpa [Experiment.cost,Nat.add_comm] using Nat.succ_le_succ hc⟩ +end Executes +end MatchingFPRAS.OnlineStack + +namespace MatchingFPRAS.OnlineProc +open Turing MachineCost PhysicalStream OnlineStack RegisterProc + +variable {K : Type} [DecidableEq K] + +structure Proc (K : Type) extends RegisterProc.Proc K where + coin : CoinTM1.Coins Label + +def deterministic (P : RegisterProc.Proc K) : Proc K := ⟨P,fun _=>none⟩ +def seq (P Q : Proc K) : Proc K where + toProc := RegisterProc.seq P.toProc Q.toProc + coin := fun l=>match l with + | .inl l => (P.coin l).map (fun f b=>Sum.inl (f b)) + | .inr l => (Q.coin l).map (fun f b=>Sum.inr (f b)) + +def Exec (P : Proc K) (S : Stack K) (p : Experiment (Stack K)) (bound : ℕ) : Prop := + ∃ q : Experiment (Stack K), + Executes P.code P.coin (fun T=>⟨none,none,T⟩) ⟨some default,none,S⟩ q ∧ + (∀ f : Stack K → ℚ,q.mean f=p.mean f) ∧ q.cost≤bound + +lemma exec_deterministic {P : RegisterProc.Proc K} {S T : Stack K} {n : ℕ} + (h : RegisterProc.Exec P S T n) : Exec (deterministic P) S (.done T) n := by + obtain ⟨k,hk,he⟩:=h + obtain ⟨p,hp,hm,hc⟩:=Executes.of_run P.code k ⟨some default,none,S⟩ none T he + refine ⟨p.map (fun _=>T),?_,?_,?_⟩ + · apply hp.bind (fun _=>.done T) (fun T=>⟨none,none,T⟩) + intro _ + exact .done T + · intro f + rw [Experiment.mean_map,hm]; rfl + · rw [Experiment.cost_map] + exact hc.trans hk + +lemma Exec.mono {P : Proc K} {S : Stack K} {p : Experiment (Stack K)} {n m : ℕ} + (h : Exec P S p n) (hn : n ≤ m) : Exec P S p m := by + obtain ⟨q,hq,hm,hc⟩:=h + exact ⟨q,hq,hm,hc.trans hn⟩ + +lemma Exec.seq {P Q : Proc K} {S : Stack K} {p : Experiment (Stack K)} + {q : Stack K → Experiment (Stack K)} {n m : ℕ} + (hP : Exec P S p n) (hQ : ∀ T,Exec Q T (q T) m) : + Exec (OnlineProc.seq P Q) S (p.bind q) (n+m) := by + obtain ⟨p',hp',hpm,hpc⟩:=hP + choose q' hq' hqm hqc using hQ + have hp:=hp'.relabel (OnlineProc.seq P Q).code (OnlineProc.seq P Q).coin Sum.inl (some (Sum.inr default)) + (fun _=>rfl) (fun _=>rfl) + have hq T := (hq' T).relabel (OnlineProc.seq P Q).code (OnlineProc.seq P Q).coin Sum.inr none + (fun _=>rfl) (fun _=>rfl) + refine ⟨p'.bind q',hp.bind q' _ hq,?_,?_⟩ + · intro f + rw [Experiment.mean_bind,Experiment.mean_bind] + simp_rw [hqm] + exact hpm _ + · exact (Experiment.cost_bind_le p' q' m hqc).trans (Nat.add_le_add_right hpc m) +end MatchingFPRAS.OnlineProc + +end OAI diff --git a/lean/OAI/Combinatorics/MatchingCount/Tapes/OnlineStackCompiler.lean b/lean/OAI/Combinatorics/MatchingCount/Tapes/OnlineStackCompiler.lean new file mode 100644 index 0000000000000000000000000000000000000000..6c6cc1b76d255dbc17712f72c125701fefebf164 --- /dev/null +++ b/lean/OAI/Combinatorics/MatchingCount/Tapes/OnlineStackCompiler.lean @@ -0,0 +1,134 @@ +import Mathlib +import OAI.Combinatorics.MatchingCount.Arithmetic.ArithmeticSize +import OAI.Combinatorics.MatchingCount.Machines.CoinTM1Finite +import OAI.Combinatorics.MatchingCount.Tapes.PhysicalAlphabet +import OAI.Combinatorics.MatchingCount.Tapes.CoinSupport + +namespace OAI + +namespace MatchingFPRAS.OnlineStack +open Turing MachineCost PhysicalStream SafeTrace +open scoped Classical + +variable {K Λ σ : Type} {Γ : K → Type} [DecidableEq K] [Fintype K] + [∀ k,Fintype (Γ k)] [Inhabited Λ] [Fintype Λ] [Inhabited σ] [Fintype σ] +abbrev Alpha (K : Type) (Γ : K → Type) := TM2to1.Γ' K Γ +abbrev L1 (K : Type) (Γ : K → Type) (Λ σ : Type) := TM2to1.Λ' K Γ Λ σ +abbrev L2 (K : Type) (Γ : K → Type) (Λ σ : Type) := TM1to1.Λ' (Alpha K Γ) (L1 K Γ Λ σ) σ +abbrev Q (K : Type) (Γ : K → Type) (Λ σ : Type) := CoinTM1.State Bool (L2 K Γ Λ σ) σ + +noncomputable def height (S : ∀ k,List (Γ k)) : ℕ := Finset.univ.sup (fun k=>(S k).length) +omit [DecidableEq K] [∀ k,Fintype (Γ k)] in +lemma height_bound (S : ∀ k,List (Γ k)) : StackCost.StackBound S (height S) := + fun k=>Finset.le_sup (f:=fun k=>(S k).length) (Finset.mem_univ k) +noncomputable def stackCfg (c : TM2.Cfg Γ Λ σ) : TM1.Cfg (Alpha K Γ) (L1 K Γ Λ σ) σ := + ⟨c.l.map TM2to1.Λ'.normal,c.var,Tape.mk₁ (StackWords.word c.stk (height c.stk))⟩ +omit [DecidableEq K] [∀ k,Fintype (Γ k)] [Inhabited Λ] [Fintype Λ] + [Inhabited σ] [Fintype σ] in +lemma stackCfg_spec [DecidableEq K] [∀ k,Fintype (Γ k)] [Inhabited Λ] [Fintype Λ] + [Inhabited σ] [Fintype σ] (c : TM2.Cfg Γ Λ σ) : TM2to1.TrCfg c (stackCfg c) := by + rcases c with ⟨l,v,S⟩ + have h:=TM2to1.TrCfg.mk (Λ:=Λ) (σ:=σ) (q:=l) (v:=v) + (ListBlank.mk (StackWords.rows S (height S))) (StackWords.rows_projection S _ (height_bound S)) + convert h using 1 + simp only [stackCfg,Tape.mk₁,Tape.mk₂,StackWords.word_blank] + rfl +omit [DecidableEq K] [∀ k,Fintype (Γ k)] [Inhabited Λ] [Fintype Λ] + [Inhabited σ] [Fintype σ] in +lemma stackCfg_unique [DecidableEq K] [∀ k,Fintype (Γ k)] [Inhabited Λ] [Fintype Λ] + [Inhabited σ] [Fintype σ] {c : TM2.Cfg Γ Λ σ} + {a : TM1.Cfg (Alpha K Γ) (L1 K Γ Λ σ) σ} (h : TM2to1.TrCfg c a) : a=stackCfg c := by + rcases h with ⟨L,hL⟩ + rename_i l v S + rw [StackWords.unique_rows S (height S) (height_bound S) L hL] + simp only [stackCfg,Tape.mk₁,Tape.mk₂,StackWords.word_blank] + rfl + +variable (M : Λ → TM2.Stmt Γ Λ σ) (coin : CoinTM1.Coins Λ) +noncomputable def program1 := TM2to1.tr M +noncomputable def enc := FixedEncoding.enc (Alpha K Γ) +noncomputable def dec := FixedEncoding.dec (Alpha K Γ) +lemma enc0 : enc (K:=K) (Γ:=Γ) default=List.Vector.replicate (Fintype.card (Alpha K Γ)) false := + FixedEncoding.blank (Alpha K Γ) +lemma encdec (a : Alpha K Γ) : dec (enc a)=a := FixedEncoding.left_inverse _ a +noncomputable def program2 := TM1to1.tr (enc (K:=K) (Γ:=Γ)) dec (program1 M) +noncomputable def support1 := TM2to1.trSupp M Finset.univ +noncomputable def support2 := TM1to1.trSupp (program1 M) (support1 M) +noncomputable def coin2 := CoinAlphabet.coins (Γ:=Alpha K Γ) (σ:=σ) (CoinStack.coins (Γ:=Γ) (σ:=σ) coin) +noncomputable def table := CoinTM1.table (program2 M) (coin2 coin) +noncomputable def states := CoinTM1.states (program2 M) (support2 M) +omit [Fintype K] [∀ k,Fintype (Γ k)] [Inhabited σ] [Fintype σ] in +lemma supports1 [Fintype K] [∀ k,Fintype (Γ k)] [Inhabited σ] [Fintype σ] : + TM1.Supports (program1 M) (support1 M) := + TM2to1.tr_supports M (StackComposition.supports_univ M) +lemma supports2 : TM1.Supports (program2 M) (support2 M) := + TM1to1.tr_supports enc dec (program1 M) (supports1 M) +omit [Inhabited Λ] [Inhabited σ] [Fintype σ] in +lemma coin2_supported [Inhabited Λ] [Inhabited σ] [Fintype σ] : + ∀ l∈support2 M,∀ f,coin2 coin l=some f→∀ b,f b∈support2 M := + CoinAlphabet.coins_supported (program1 M) (support1 M) _ + (CoinStack.coins_supported M Finset.univ coin (fun _ _ _ _ _=>Finset.mem_univ _)) +lemma table_supported : PhysicalPost.Supported (table M coin) (states M) := + CoinTM1.table_supported (program2 M) (support2 M) (supports2 M) (coin2 coin) (coin2_supported M coin) +noncomputable def cfg (c : TM2.Cfg Γ Λ σ) : PhysicalPost.Cfg Bool (Q K Γ Λ σ) := + CoinTM1.trCfg (TM1to1.trCfg enc enc0 (stackCfg c)) + +noncomputable def accesses : ℕ := Finset.univ.sup (fun l=>StackCost.accesses (M l)) +omit [DecidableEq K] [Fintype K] [∀ k,Fintype (Γ k)] [Inhabited Λ] + [Inhabited σ] [Fintype σ] in +lemma accesses_bound (l : Λ) : StackCost.accesses (M l)≤accesses M := + Finset.le_sup (f:=fun l=>StackCost.accesses (M l)) (Finset.mem_univ l) +noncomputable def overhead : ℕ := + (AlphabetCost.supportedWrites (program1 M) (support1 M)+1)* + SupportedCompiler.cost (program2 M) (support2 M) + +theorem deterministic (c : TM2.Cfg Γ Λ σ) (hc : ∀ l,c.l=some l→coin l=none) + (H : ℕ) (hH : StackCost.StackBound c.stk H) : + ∃ k,k≤overhead M*(1+2*accesses M*(H+accesses M+1)) ∧ ∀ b : Stream, + PhysicalPost.execute (table M coin) k (cfg c) b=cfg (advance (TM2.step M) c) := by + obtain ⟨i,a,hi,ha,hpath⟩:=CoinStack.one_step_path M (fun l=>coin l=none) + (accesses M) (accesses_bound M) (stackCfg_spec c) hc H hH + have hc1 : (stackCfg c).l∈(support1 M).insertNone := + CoinStack.cfg_supported M Finset.univ (stackCfg_spec c) (by simp) + obtain ⟨j,hj,hpath2⟩:=CoinAlphabet.path_supported enc dec enc0 encdec (program1 M) + (support1 M) (supports1 M) hpath hc1 + have hc2 : (TM1to1.trCfg enc enc0 (stackCfg c)).l∈(support2 M).insertNone := + CoinAlphabet.cfg_supported (program1 M) (support1 M) enc enc0 (stackCfg c) hc1 + have hh:=hpath2.with_support (supports2 M) (fun l hl=>Finset.some_mem_insertNone.mp (hl ▸ hc2)) + obtain ⟨k,hk,he⟩:=hh.physical (coin2 coin) + (fun l hl=>CoinAlphabet.coins_none (by + cases l with + | normal l => exact CoinStack.coins_none hl.1 + | write a q => trivial)) + (SupportedCompiler.cost (program2 M) (support2 M)) (fun l hl=>SupportedCompiler.cost_le _ _ hl.2) + refine ⟨k,?_,fun b=>?_⟩ + · calc + k≤(i*(AlphabetCost.supportedWrites (program1 M) (support1 M)+1))* + SupportedCompiler.cost (program2 M) (support2 M) := hk.trans (Nat.mul_le_mul_right _ hj) + _=overhead M*i := by unfold overhead; ring + _≤overhead M*(1+2*accesses M*(H+accesses M+1)) := Nat.mul_le_mul_left _ hi + · rw [stackCfg_unique ha] at he + exact he b + +omit [Inhabited Λ] [Fintype Λ] [Inhabited σ] [Fintype σ] in +lemma random [Inhabited Λ] [Fintype Λ] [Inhabited σ] [Fintype σ] + (l : Λ) (v : σ) (S : ∀ k,List (Γ k)) (f : Bool → Λ) (hf : coin l=some f) (b : Bool) : + PhysicalPost.tick (table M coin) (cfg ⟨some l,v,S⟩) b=cfg ⟨some (f b),v,S⟩ := by + apply CoinTM1.coin_tick + simp only [coin2,CoinAlphabet.coins,CoinStack.coins,hf,Option.map_some] + +noncomputable def initialState : Q K Γ Λ σ := + (.inl (.normal (.normal default)),default) +lemma initialState_mem : initialState (K:=K) (Γ:=Γ) (Λ:=Λ) (σ:=σ)∈states M := by + apply CoinTM1.state_mem + apply CoinTM1.node_entry + apply (CoinAlphabet.normal_mem _ _ _).mpr + exact (CoinStack.normal_mem M Finset.univ default).mpr (Finset.mem_univ default) + +noncomputable def machine : RandomMachine := PhysicalPost.restrictedMachine + (PhysicalPost.liftBool (table M coin)) (states M) + (PhysicalPost.liftBool_supported _ _ (table_supported M coin)) + initialState (initialState_mem M) +end MatchingFPRAS.OnlineStack + +end OAI diff --git a/lean/OAI/Combinatorics/MatchingCount/Tapes/OnlineWord.lean b/lean/OAI/Combinatorics/MatchingCount/Tapes/OnlineWord.lean new file mode 100644 index 0000000000000000000000000000000000000000..d3bfa63584e3ad1751dce2c8defa52f0401901a2 --- /dev/null +++ b/lean/OAI/Combinatorics/MatchingCount/Tapes/OnlineWord.lean @@ -0,0 +1,81 @@ +import Mathlib +import OAI.Combinatorics.MatchingCount.Machines.OnlineFold + +namespace OAI + +namespace MatchingFPRAS.OnlineWord +open PhysicalStream TreeData TreeFunction TreeTyped OnlineTree + +def prepend : ℕ → List Bool → Experiment (List Bool) + | 0,acc => .done acc + | n+1,acc => .read (fun b=>prepend n (b::acc)) +lemma mean_prepend (n : ℕ) (acc : List Bool) (f : List Bool → ℚ) : + (prepend n acc).mean f=(Experiment.word n).mean (fun w=>f ((List.ofFn w).reverse++acc)) := by + induction n generalizing acc with + | zero => simp [prepend,Experiment.word,Experiment.mean] + | succ n ih => + simp only [prepend,Experiment.word,Experiment.mean,Experiment.mean_map,ih] + congr 2 <;> congr 1 <;> funext w <;> + simp [List.ofFn_succ,List.reverse_cons,List.append_assoc] + +def reverseBits (n : ℕ) : Bits n ≃ Bits n where + toFun w i:=w i.rev + invFun w i:=w i.rev + left_inv w:=by funext i; simp + right_inv w:=by funext i; simp +lemma ofFn_reverse (n : ℕ) (w : Bits n) : + List.ofFn (reverseBits n w)=(List.ofFn w).reverse := by + apply List.ext_getElem + · simp + · intro i hi hj + simp only [List.length_ofFn] at hi hj + simp only [reverseBits,Equiv.coe_fn_mk,List.getElem_ofFn,List.getElem_reverse,Fin.rev,List.length_ofFn] + congr 1 + apply Fin.ext + change n-(i+1)=n-1-i + omega +lemma average_reverse (n : ℕ) (f : List Bool → ℚ) : + average (fun w : Bits n=>f (List.ofFn w).reverse)=average (fun w : Bits n=>f (List.ofFn w)) := by + unfold average + congr 1 + exact Fintype.sum_equiv (reverseBits n) _ _ (fun w=>by rw [ofFn_reverse]) +lemma mean_prepend_nil (n : ℕ) (f : List Bool → ℚ) : + (prepend n []).mean f=average (fun w : Bits n=>f (List.ofFn w)) := by + rw [mean_prepend,Experiment.mean_word] + simp only [List.append_nil] + exact average_reverse n f + +def step (x : ℕ×List Bool) : Experiment (List Bool) := .read (fun b=>.done (b::x.2)) +noncomputable def stepRealizer : OnlineTree.Realizer step := + (OnlineTree.choose + (OnlineTree.deterministic (TreeTyped.composition (TreeTyped.pair (TreeTyped.constant false) TreeTyped.second) TreeTyped.listCons)) + (OnlineTree.deterministic (TreeTyped.composition (TreeTyped.pair (TreeTyped.constant true) TreeTyped.second) TreeTyped.listCons))).congr + (by intro x f; rfl) +lemma fold_step (as : List ℕ) (acc : List Bool) : + OnlineTree.foldM step as acc=prepend as.length acc := by + induction as generalizing acc with + | nil => rfl + | cons a as ih => simp only [OnlineTree.foldM,step,Experiment.bind,ih,List.length_cons,prepend] + +noncomputable def listRealizer : OnlineTree.Realizer (fun as : List ℕ=>prepend as.length []) := + (OnlineTree.composition + (OnlineTree.deterministic (TreeTyped.pair (TreeTyped.identity (A:=List ℕ)) (TreeTyped.constant ([] : List Bool)))) + (OnlineTree.fold stepRealizer)).congr (by + intro as f + change (OnlineTree.foldM step as []).mean f=(prepend as.length []).mean f + rw [fold_step]) + +noncomputable def naturalRealizer : OnlineTree.Realizer (fun n : ℕ=>prepend n []) := + (OnlineTree.composition (OnlineTree.deterministic TreeTyped.range) listRealizer).congr + (by intro n f; simp only [Experiment.mean_bind,Experiment.mean,List.length_range]) + +lemma all_length (n : ℕ) (acc : List Bool) : + (prepend n acc).All (fun bs=>bs.length=n+acc.length) := by + induction n generalizing acc with + | zero => simp only [prepend,Experiment.All,Nat.zero_add] + | succ n ih => + change (prepend n (false::acc)).All _ ∧ (prepend n (true::acc)).All _ + constructor <;> exact (ih _).mono (fun bs h=>by simp only [List.length_cons] at h; omega) +end MatchingFPRAS.OnlineWord + +end OAI diff --git a/lean/OAI/Combinatorics/MatchingCount/Tapes/Packed.lean b/lean/OAI/Combinatorics/MatchingCount/Tapes/Packed.lean new file mode 100644 index 0000000000000000000000000000000000000000..e266485ae5f396e7d996d31b36f33c8be7c66ed3 --- /dev/null +++ b/lean/OAI/Combinatorics/MatchingCount/Tapes/Packed.lean @@ -0,0 +1,98 @@ +import Mathlib +import OAI.Combinatorics.MatchingCount.Machines.TreeListMore +import OAI.Combinatorics.MatchingCount.Machines.TreePostRealization +import OAI.Combinatorics.MatchingCount.Tapes.Codec + +namespace OAI + +namespace MatchingFPRAS.LiteralPacked +open TreeTyped TreeData TreeFunction TreeMachine TreePost + +abbrev Row := K Reg→Option Bool +def baseRow : Row + | .inl _ => some false + | .inr _ => none +def bitRow (b : Bool) : Row := fun k=>if k=Sum.inl 0 then some b else none +def bottom : Alphabet := (true,baseRow) +def letter (b : Bool) : Alphabet := (false,bitRow b) +lemma rows_eq {A : Type} [Codec A] (a : A) (bs : List Bool) + (hs : (TreeData.encode (TreeTyped.encode a)).reverse=false::bs) : + StackWords.rows (inputStacks a) (weight a)=baseRow::bs.map bitRow := by + have hw : weight a=bs.length+1 := by + have h:=congrArg List.length hs + simpa only [List.length_reverse,List.length_cons,weight,TreeFunction.size] using h + apply List.ext_getElem + · simp only [StackWords.rows,List.length_ofFn,List.length_cons,List.length_map,hw] + · intro i hi hj + simp only [StackWords.rows,List.getElem_ofFn] + funext k + cases k with + | inr k => + cases i <;> simp [inputStacks,encodeEnv,baseRow,bitRow] + | inl r => + by_cases hr:r=0 + · subst r + simp only [inputStacks,encodeEnv,env,ite_true,hs] + cases i <;> simp [baseRow,bitRow] + · have hn : env (TreeTyped.encode a) .nil .nil r=.nil := by simp [env,hr] + simp only [inputStacks,encodeEnv,hn,TreeData.encode,List.reverse_singleton] + cases i <;> simp [baseRow,bitRow,hr] +lemma word_eq {A : Type} [Codec A] (a : A) (bs : List Bool) + (hs : (TreeData.encode (TreeTyped.encode a)).reverse=false::bs) : + StackWords.word (inputStacks a) (weight a)=bottom::bs.map letter := by + rw [StackWords.word,rows_eq a bs hs] + simp only [List.headI_cons,List.tail_cons] + change (true,baseRow)::(bs.map bitRow).map (fun a=>(false,a)) = (true,baseRow)::bs.map LiteralPacked.letter + rw [List.map_map] + rfl + +def symbolBits (a : Symbol) : List Bool := (TreeData.encode (TreeTyped.encode a)).reverse++[true] +lemma symbolBits_length (a : Symbol) : (symbolBits a).length=18 := by + simp only [symbolBits,List.length_append,List.length_reverse,List.length_singleton] + change weight a+1=18 + rw [LiteralCodec.weight_symbol] +lemma list_bits (as : List Symbol) : + (TreeData.encode (TreeTyped.encode as)).reverse=false::as.reverse.flatMap symbolBits := by + induction as with + | nil => rfl + | cons a as ih => + simp only [TreeTyped.encode_list_cons,TreeData.encode,List.reverse_cons,List.reverse_append,ih, + List.flatMap_append,List.flatMap_cons,List.flatMap_nil,List.append_nil,symbolBits, + List.cons_append,List.append_assoc] + +noncomputable def block (a : Alphabet) : List Symbol := + (FixedEncoding.enc Alphabet a).toList.map BoolPostCompiler.up +noncomputable def header : List Symbol := block bottom +noncomputable def chunk (a : Symbol) : List Symbol := (symbolBits a).flatMap (fun b=>block (letter b)) +noncomputable def width : ℕ := Fintype.card Alphabet +lemma map_enc_length {α : Type} [Fintype α] [Inhabited α] (a : α) : + ((FixedEncoding.enc α a).toList.map BoolPostCompiler.up).length=Fintype.card α := by + rw [List.length_map] + exact (FixedEncoding.enc α a).2 +lemma block_length (a : Alphabet) : (block a).length=width := by + unfold width block + exact map_enc_length a +lemma flatMap_uniform_length {α β : Type} (as : List α) (f : α→List β) (w : ℕ) + (h : ∀ a,(f a).length=w) : (as.flatMap f).length=as.length*w := by + induction as with + | nil => simp + | cons a as ih => simp only [List.flatMap_cons,List.length_append,h,ih,List.length_cons,Nat.add_mul,Nat.one_mul];omega +lemma chunk_length (a : Symbol) : (chunk a).length=18*width := by + exact (flatMap_uniform_length (symbolBits a) (fun b=>block (letter b)) width + (fun b=>block_length (letter b))).trans (congrArg (fun n=>n*width) (symbolBits_length a)) + +lemma packed_eq (as : List Symbol) : TreePost.packed as=header++as.reverse.flatMap chunk := by + unfold TreePost.packed StackWords.encoded FixedAlphabetCompiler.word FixedAlphabetCompiler.bitsWord + rw [word_eq as _ (list_bits as)] + simp only [List.flatMap_cons,List.map_append,List.flatMap_map,List.map_flatMap, + List.flatMap_assoc,LiteralPacked.header,LiteralPacked.block] + rfl +lemma block_alphabet (a : Alphabet) (s : Symbol) (hs : s∈block a) : s=0 ∨ s=1 := by + obtain ⟨b,_,rfl⟩:=List.mem_map.mp hs + cases b <;> simp [BoolPostCompiler.up] +lemma chunk_alphabet (a s : Symbol) (hs : s∈chunk a) : s≠6 ∧ s≠7 := by + obtain ⟨b,_,hb⟩:=List.mem_flatMap.mp hs + rcases block_alphabet _ _ hb with rfl|rfl <;> decide +end MatchingFPRAS.LiteralPacked + +end OAI diff --git a/lean/OAI/Combinatorics/MatchingCount/Tapes/PackedExecution.lean b/lean/OAI/Combinatorics/MatchingCount/Tapes/PackedExecution.lean new file mode 100644 index 0000000000000000000000000000000000000000..f576df4b8d7a899c83252c15ff5d57ed68d36d38 --- /dev/null +++ b/lean/OAI/Combinatorics/MatchingCount/Tapes/PackedExecution.lean @@ -0,0 +1,78 @@ +import Mathlib +import OAI.Combinatorics.MatchingCount.Tapes.PackedInverse + +namespace OAI + +namespace MatchingFPRAS.LiteralPacked +open Turing LiteralTape LiteralBlockMap + +noncomputable def packCode := LiteralBlockMap.code 1 (fun b=>chunk (b 0)) header +def singletonBlock (a : Symbol) : Block 1 := fun _=>a +lemma singletonBlock_word (a : Symbol) : List.ofFn (singletonBlock a)=[a] := by simp [singletonBlock,List.ofFn_succ] +lemma pack_exec (as : List Symbol) (ha : ∀ a∈as,a≠0) : + Exec packCode ⟨some .start,(fun _=>0),Tape.mk₁ as⟩ + ⟨none,(fun _=>0),Tape.mk₁ (TreePost.packed as)⟩ + (1+LiteralBlockMap.budget 1 (18*width) as.length 0) := by + have h:=LiteralBlockMap.computes 1 (fun b=>chunk (b 0)) header (by decide) + (as.map singletonBlock) (18*width) ?_ ?_ ?_ + · simpa only [packCode,List.flatMap_map,singletonBlock_word,List.flatMap_singleton,List.flatMap_singleton',List.length_map, + ←List.map_reverse,singletonBlock,←packed_eq] using h + · intro b hb + obtain ⟨a,ha',rfl⟩:=List.mem_map.mp hb + intro he + exact ha a ha' (congrFun he 0) + · intro b _ a had + exact chunk_alphabet _ _ had + · intro b _ + exact (chunk_length _).le +noncomputable def unpackCode := LiteralBlockMap.code (18*width) unchunk [] +lemma unpack_exec (as : List Symbol) (ha : ∀ a∈as,a≠6 ∧ a≠7) : + Exec unpackCode ⟨some .start,(fun _=>0),Tape.mk₁ (as.reverse.flatMap chunk)⟩ + ⟨none,(fun _=>0),Tape.mk₁ as⟩ + (1+LiteralBlockMap.budget (18*width) 1 as.length 0) := by + have h:=LiteralBlockMap.computes (18*width) unchunk [] (Nat.mul_pos (by decide) width_pos) + (as.reverse.map chunkFn) 1 ?_ ?_ ?_ + · simpa only [unpackCode,List.flatMap_map,chunkFn_word,←List.map_reverse,List.reverse_reverse, + unchunk_chunkFn,List.flatMap_singleton,List.flatMap_singleton',List.nil_append,List.length_map,List.length_reverse] using h + · intro b hb + obtain ⟨a,_,rfl⟩:=List.mem_map.mp hb + exact chunkFn_nonzero a + · intro b hb a had + obtain ⟨c,hc,rfl⟩:=List.mem_map.mp hb + rw [unchunk_chunkFn,List.mem_singleton] at had + subst a + exact ha c (List.mem_reverse.mp hc) + · intro b hb + obtain ⟨a,_,rfl⟩:=List.mem_map.mp hb + rw [unchunk_chunkFn];rfl +end MatchingFPRAS.LiteralPacked + +namespace MatchingFPRAS.LiteralTape +open Turing MachineCost + +variable {Γ Λ σ : Type} [Inhabited Γ] +def eraseRight (n : ℕ) (q : TM1.Stmt Γ Λ σ) : TM1.Stmt Γ Λ σ := + Nat.rec q (fun _ tail=>.write (fun _ _=>default) (.move .right tail)) n +lemma eraseRight_step (xs L R : List Γ) (q : TM1.Stmt Γ Λ σ) (v : σ) : + TM1.stepAux (eraseRight xs.length q) v (Tape.mk₂ L (xs++R))= + TM1.stepAux q v (Tape.mk₂ (List.replicate xs.length default++L) R) := by + induction xs generalizing L with + | nil => rfl + | cons a xs ih => + simp only [List.length_cons,eraseRight,TM1.stepAux,List.cons_append,mk₂_write,mk₂_right] + rw [show Nat.rec q (fun _ tail=>TM1.Stmt.write (fun _ _=>default) (.move .right tail)) xs.length=eraseRight xs.length q from rfl,ih] + simp only [List.replicate_succ',List.append_assoc,List.singleton_append] +noncomputable def eraseCode (n : ℕ) : Unit→TM1.Stmt Symbol Unit Unit := fun _=>eraseRight n .halt +lemma erase_exec (xs R : List Symbol) : + Exec (eraseCode xs.length) ⟨some (),(),Tape.mk₁ (xs++R)⟩ ⟨none,(),Tape.mk₁ R⟩ 1 := by + have h:=Exec.step (eraseCode xs.length) () () (Tape.mk₁ (xs++R)) + change Exec _ _ (TM1.stepAux (eraseRight xs.length .halt) () (Tape.mk₂ [] (xs++R))) 1 at h + rw [eraseRight_step] at h + have he : Tape.mk₂ (List.replicate xs.length (0:Symbol)++[]) R=Tape.mk₁ R := by + simp only [List.append_nil,Tape.mk₂,Tape.mk₁] + rw [show (ListBlank.mk (List.replicate xs.length (0:Symbol)))=ListBlank.mk [] from blank_zero xs.length] + change Exec _ _ (TM1.stepAux (.halt : TM1.Stmt Symbol Unit Unit) () (Tape.mk₂ (List.replicate xs.length (0:Symbol)++[]) R)) 1 at h + simpa only [TM1.stepAux,he] using h +end MatchingFPRAS.LiteralTape + +end OAI diff --git a/lean/OAI/Combinatorics/MatchingCount/Tapes/PackedInverse.lean b/lean/OAI/Combinatorics/MatchingCount/Tapes/PackedInverse.lean new file mode 100644 index 0000000000000000000000000000000000000000..fcb23bac0c8fbee1b2b735673017ccd31c720f99 --- /dev/null +++ b/lean/OAI/Combinatorics/MatchingCount/Tapes/PackedInverse.lean @@ -0,0 +1,106 @@ +import Mathlib +import OAI.Combinatorics.MatchingCount.Tapes.TreeEncodingInjective +import OAI.Combinatorics.MatchingCount.Tapes.BlockMap +import OAI.Combinatorics.MatchingCount.Tapes.Packed + +namespace OAI + +namespace MatchingFPRAS.LiteralPacked +open TreeTyped TreeData TreePost + +lemma symbol_encode_injective : Function.Injective (TreeTyped.encode (A:=Symbol)) := by + intro a b h + have hh : TreeTyped.encode (LiteralCodec.parts a)=TreeTyped.encode (LiteralCodec.parts b) := h + have he := (TreeData.Data.cons.inj hh).1 + have hs : (LiteralCodec.parts a).1=(LiteralCodec.parts b).1 := + list_encode_injective (show Function.Injective (TreeTyped.encode (A:=Bool)) from bit_injective) he + apply Fin.ext + simpa only [LiteralCodec.parts,List.length_replicate] using congrArg List.length hs +lemma symbolBits_injective : Function.Injective symbolBits := by + intro a b h + have h1:=List.append_cancel_right (show _++[true]=_++[true] from h) + exact symbol_encode_injective (TreeData.encode_injective (List.reverse_injective h1)) +lemma encoding_injective (Γ : Type) [Fintype Γ] [Inhabited Γ] : + Function.Injective (fun a : Γ=>(FixedEncoding.enc Γ a).toList.map BoolPostCompiler.up) := by + intro a b h + have hb : (FixedEncoding.enc Γ a).toList=(FixedEncoding.enc Γ b).toList := + List.map_injective_iff.mpr (Function.LeftInverse.injective BoolPostCompiler.down_up) h + exact FixedEncoding.injective Γ (Subtype.ext hb) +lemma block_injective : Function.Injective block := encoding_injective Alphabet +lemma flatMap_injective_fixed {A B : Type} (f : A→List B) (w : ℕ) (hw : 0 + intro bs h + cases bs with + | nil => rfl + | cons b bs => have hh:=congrArg List.length h;simp only [List.flatMap_nil,List.flatMap_cons,List.length_nil,List.length_append,hl] at hh;omega + | cons a as ih => + intro bs h + cases bs with + | nil => have hh:=congrArg List.length h;simp only [List.flatMap_nil,List.flatMap_cons,List.length_nil,List.length_append,hl] at hh;omega + | cons b bs => + have h1 := List.append_inj_left h ((hl a).trans (hl b).symm) + have h2 := List.append_inj_right h ((hl a).trans (hl b).symm) + exact congrArg₂ List.cons (hi h1) (ih h2) +lemma width_pos : 0x.2 (Sum.inl 0)) h + simpa only [letter,bitRow,ite_true,Option.some.injEq] using hh +lemma chunk_injective : Function.Injective chunk := by + intro a b h + have hi : Function.Injective (fun b=>block (letter b)) := by + intro b c he + exact letter_injective (block_injective he) + have hh : (symbolBits a).flatMap (fun b=>block (letter b)) = + (symbolBits b).flatMap (fun b=>block (letter b)) := h + exact symbolBits_injective (flatMap_injective_fixed (fun b=>block (letter b)) width width_pos + (fun b=>block_length (letter b)) hi hh) +lemma encoding_blank (Γ : Type) [Fintype Γ] [Inhabited Γ] : + (FixedEncoding.enc Γ default).toList.map BoolPostCompiler.up= + List.replicate (Fintype.card Γ) (0:Symbol) := by + rw [FixedEncoding.blank] + change (List.replicate (Fintype.card Γ) false).map _ = _ + rw [List.map_replicate] + rfl +lemma block_blank : block default=List.replicate width 0 := encoding_blank Alphabet +lemma block_ne_zero (a : Alphabet) (ha : a≠default) : block a≠List.replicate width 0 := by + intro he + exact ha (block_injective (he.trans block_blank.symm)) +lemma chunk_nonzero (a : Symbol) : ∃ s∈chunk a,s≠0 := by + classical + by_contra h + push Not at h + have h1 : ∀ s∈block (letter true),s=(0:Symbol) := by + intro s hs + exact h s (List.mem_flatMap.mpr ⟨true,by simp [symbolBits],hs⟩) + have he : block (letter true)=List.replicate width 0 := by + rw [←block_length (letter true)] + exact List.eq_replicate_of_mem h1 + apply block_ne_zero (letter true) _ he + intro h2 + have hh:=congrArg (fun x : Alphabet=>x.2 (Sum.inl 0)) h2 + change (some true : Option Bool)=none at hh + exact Option.some_ne_none true hh +noncomputable def chunkFn (a : Symbol) : LiteralBlockMap.Block (18*width) := + fun i=>(chunk a)[i.val]'(by rw [chunk_length];exact i.isLt) +lemma chunkFn_word (a : Symbol) : List.ofFn (chunkFn a)=chunk a := by + apply List.ext_getElem + · simp only [List.length_ofFn,chunk_length] + · intro i hi hj; simp only [List.getElem_ofFn,chunkFn] +noncomputable def unchunk (b : LiteralBlockMap.Block (18*width)) : List Symbol := + [Function.invFun chunk (List.ofFn b)] +lemma unchunk_chunkFn (a : Symbol) : unchunk (chunkFn a)=[a] := by + rw [unchunk,chunkFn_word,Function.leftInverse_invFun chunk_injective] +lemma chunkFn_nonzero (a : Symbol) : chunkFn a≠fun _=>0 := by + intro he + have hh:=congrArg List.ofFn he + rw [chunkFn_word,List.ofFn_const] at hh + obtain ⟨s,hs,hn⟩:=chunk_nonzero a + rw [hh] at hs + exact hn (List.eq_of_mem_replicate hs) +end MatchingFPRAS.LiteralPacked + +end OAI diff --git a/lean/OAI/Combinatorics/MatchingCount/Tapes/Parse.lean b/lean/OAI/Combinatorics/MatchingCount/Tapes/Parse.lean new file mode 100644 index 0000000000000000000000000000000000000000..7180efd71a65937a78dfb8e85ab0b2bf8898c552 --- /dev/null +++ b/lean/OAI/Combinatorics/MatchingCount/Tapes/Parse.lean @@ -0,0 +1,123 @@ +import Mathlib +import OAI.Combinatorics.MatchingCount.Algorithm.OnlineScheduleNat +import OAI.Combinatorics.MatchingCount.Tapes.Codec + +namespace OAI + +namespace MatchingFPRAS.LiteralParse +open TreeTyped TreeData TreeFunction Polynomial LiteralCodec + +def numStep (x : Symbol×List ℕ) : List ℕ := + if x.1=3 then 0::x.2 + else if x.1=1 then (2*x.2.headD 0)::x.2.tail + else if x.1=2 then (2*x.2.headD 0+1)::x.2.tail + else x.2 + +def eqSymbol (a : Symbol) : Realizer (fun b : Symbol=>decide (b=a)) := + (composition (pair valRealizer (constant a.val)) natEqual).congr + (fun b=>by simp only [Function.comp_apply,Fin.ext_iff]) +lemma polynomial_eqSymbol (a : Symbol) : PolynomialTime (eqSymbol a) := by + unfold eqSymbol; apply polynomial_congr + exact polynomial_composition (polynomial_pair polynomial_val (polynomial_constant _)) polynomial_natEqual + +def numStepRealizer : Realizer numStep := + (choose (composition first (eqSymbol 3)) + (composition (pair (constant 0) second) listCons) + (choose (composition first (eqSymbol 1)) + (composition (pair ((constant 2).mulNat (composition second (head 0))) (composition second tail)) listCons) + (choose (composition first (eqSymbol 2)) + (composition (pair (((constant 2).mulNat (composition second (head 0))).addNat (constant 1)) (composition second tail)) listCons) + second))).congr (fun x=>by simp only [Function.comp_apply,decide_eq_true_eq,numStep]) +lemma polynomial_numStep : PolynomialTime numStepRealizer := by + unfold numStepRealizer + apply polynomial_congr + have := polynomial_eqSymbol 3 + have := polynomial_eqSymbol 2 + have := polynomial_eqSymbol 1 + have := polynomial_head (0:ℕ) + have := polynomial_tail (A:=ℕ) + simp only [Realizer.mulNat, Realizer.addNat] + tree_cost + +lemma weight_double (n : ℕ) : weight (2*n)≤weight n+2 := by + by_cases hn:n=0 + · subst n; simp only [Nat.mul_zero]; omega + rw [weight_nat,Nat.bit0_bits n hn] + rw [weight_cons] + change 1+1+weight n≤_ + omega +lemma weight_double_one (n : ℕ) : weight (2*n+1)≤weight n+4 := by + rw [weight_nat,Nat.bit1_bits,weight_cons] + change 1+3+weight n≤_ + omega + +lemma numStep_weight (a : Symbol) (ns : List ℕ) : weight (numStep (a,ns))≤weight ns+6 := by + unfold numStep + dsimp only + split_ifs + · rw [weight_cons]; change 1+1+weight ns≤_; omega + · cases ns with + | nil => change 3≤1+6; omega + | cons n ns => + simp only [List.headD_cons,List.tail_cons,weight_cons] + have h:=weight_double n + omega + · cases ns with + | nil => change 7≤7; omega + | cons n ns => + simp only [List.headD_cons,List.tail_cons,weight_cons] + have h:=weight_double_one n + omega + · omega + +lemma fold_weight (as : List Symbol) (ns : List ℕ) : + weight (as.foldl (fun ns a=>numStep (a,ns)) ns)≤weight ns+6*as.length := by + induction as generalizing ns with + | nil => simp + | cons a as ih => + have h:=ih (numStep (a,ns)) + have h':=numStep_weight a ns + simp only [List.foldl_cons,List.length_cons] + omega +lemma polynomial_numFold : PolynomialTime (fold numStepRealizer) := by + apply polynomial_fold polynomial_numStep (7*X) + intro as ns pre post he + have h:=fold_weight pre ns + have hlen : pre.length≤as.length := by rw [he,List.length_append]; omega + have hlen':=list_length_le_weight as + simp only [Polynomial.eval_mul,Polynomial.eval_ofNat,Polynomial.eval_X,weight_prod] + omega + +def parse (as : List Symbol) : List ℕ := as.foldr (fun a ns=>numStep (a,ns)) [] +def parseRealizer : Realizer parse := + (composition (pair reverse (constant [])) (fold numStepRealizer)).congr (fun as=>by + simp only [Function.comp_apply,List.foldl_reverse,parse]) +lemma polynomial_parse : PolynomialTime parseRealizer := by + unfold parseRealizer + apply polynomial_congr + exact polynomial_composition (polynomial_pair polynomial_reverse (polynomial_constant _)) polynomial_numFold + +lemma bits_fold (n : ℕ) (ns : List ℕ) : + (n.bits.map fromBit).foldr (fun a ns=>numStep (a,ns)) (0::ns)=n::ns := by + induction n using Nat.binaryRec' with + | zero => rfl + | bit b n hn ih => + rw [Nat.bits_append_bit n b hn,List.map_cons,List.foldr_cons,ih] + cases b <;> simp [fromBit,numStep,Nat.bit] +lemma encodeNat_fold (n : ℕ) (ns : List ℕ) : + (encodeNat n).foldr (fun a ns=>numStep (a,ns)) ns=n::ns := by + change (n.bits.map fromBit++[3]).foldr _ ns=_ + rw [List.foldr_append] + change (n.bits.map fromBit).foldr (fun a ns=>numStep (a,ns)) (0::ns)=_ + exact bits_fold n ns +lemma encodeInt_fold (z : ℤ) (ns : List ℕ) : + (encodeInt z).foldr (fun a ns=>numStep (a,ns)) ns=z.natAbs::ns := by + unfold encodeInt + rw [List.foldr_append,encodeNat_fold] + split_ifs <;> simp [numStep] +lemma encodeRat_fold (q : ℚ) (ns : List ℕ) : + (encodeRat q).foldr (fun a ns=>numStep (a,ns)) ns=q.num.natAbs::q.den::ns := by + rw [encodeRat,List.foldr_append,encodeNat_fold,encodeInt_fold] +end MatchingFPRAS.LiteralParse + +end OAI diff --git a/lean/OAI/Combinatorics/MatchingCount/Tapes/Physical.lean b/lean/OAI/Combinatorics/MatchingCount/Tapes/Physical.lean new file mode 100644 index 0000000000000000000000000000000000000000..47dfe74c5c974e29e27ab220fcc093ed10a31efa --- /dev/null +++ b/lean/OAI/Combinatorics/MatchingCount/Tapes/Physical.lean @@ -0,0 +1,51 @@ +import Mathlib +import OAI.Combinatorics.MatchingCount.Machines.CoinTM1Finite +import OAI.Combinatorics.MatchingCount.Tapes.TapeTools +import OAI.Combinatorics.MatchingCount.Machines.PhysicalProcess +import OAI.Combinatorics.MatchingCount.Graphs.SafeTrace + +namespace OAI + +namespace MatchingFPRAS.LiteralTape +open Turing MachineCost PhysicalStream + +variable {Γ Λ σ : Type} [Inhabited Γ] [Inhabited Λ] [Fintype Λ] [Fintype σ] [Inhabited σ] +omit [Inhabited Γ] [Fintype σ] [Inhabited σ] in +lemma supports_univ (M : Λ→TM1.Stmt Γ Λ σ) : TM1.Supports M Finset.univ := by + classical + refine ⟨Finset.mem_univ _,fun l _=>?_⟩ + induction M l with + | move d q ih => exact ih + | write f q ih => exact ih + | load f q ih => exact ih + | branch f q r ih jh => exact ⟨ih,jh⟩ + | goto f => exact fun a v=>Finset.mem_univ _ + | halt => trivial +noncomputable def table (M : Λ→TM1.Stmt Γ Λ σ) := CoinTM1.table M (fun _=>none) +noncomputable def states (M : Λ→TM1.Stmt Γ Λ σ) := CoinTM1.states M Finset.univ +omit [Inhabited Γ] [Inhabited σ] in +lemma supported (M : Λ→TM1.Stmt Γ Λ σ) : PhysicalPost.Supported (table M) (states M) := + CoinTM1.table_supported M Finset.univ (supports_univ M) (fun _=>none) (by simp) +omit [Inhabited Γ] [Inhabited Λ] [Inhabited σ] in +lemma entry_mem (M : Λ→TM1.Stmt Γ Λ σ) (l : Λ) (v : σ) : (Sum.inl l,v)∈states M := + CoinTM1.state_mem (CoinTM1.node_entry (Finset.mem_univ _)) +omit [Inhabited Λ] [Fintype σ] [Inhabited σ] in +lemma Exec.physical {M : Λ→TM1.Stmt Γ Λ σ} {c d : TM1.Cfg Γ Λ σ} {t : ℕ} + (h : Exec M c d t) : ∃ k,k≤t*programCost M ∧ ∀ b : Stream, + PhysicalPost.execute (table M) k (CoinTM1.trCfg c) b=CoinTM1.trCfg d := by + obtain ⟨n,hn,he⟩:=h + have hp:=SafeTrace.Path.of_run (safe:=fun _=>True) (M:=M) n c (fun _ _ _ _=>trivial) + rw [he] at hp + obtain ⟨k,hk,hb⟩:=hp.physical (fun _=>none) (fun _ _=>rfl) (programCost M) + (fun l _=>statementCost_le_programCost M l) + exact ⟨k,hk.trans (Nat.mul_le_mul_right _ hn),hb⟩ +omit [Inhabited Λ] [Fintype σ] [Inhabited σ] in +lemma Exec.implements {M : Λ→TM1.Stmt Γ Λ σ} {c d : TM1.Cfg Γ Λ σ} {t : ℕ} + (h : Exec M c d t) : ∃ p : Experiment Unit,p.cost≤t*programCost M ∧ + PhysicalPost.Implements (table M) (fun _=>CoinTM1.trCfg d) (CoinTM1.trCfg c) p ∧ + ∀ f : Unit→ℚ,p.mean f=f () := by + obtain ⟨k,hk,hb⟩:=h.physical + exact ⟨.delay k (.done ()),by simpa only [Experiment.cost,Nat.add_zero] using hk,.delay _ _ k _ hb (.done ()),fun _=>rfl⟩ +end MatchingFPRAS.LiteralTape + +end OAI diff --git a/lean/OAI/Combinatorics/MatchingCount/Tapes/PhysicalAlphabet.lean b/lean/OAI/Combinatorics/MatchingCount/Tapes/PhysicalAlphabet.lean new file mode 100644 index 0000000000000000000000000000000000000000..5ef97452ef5b3e6f20099770a52aca7f65f55dbd --- /dev/null +++ b/lean/OAI/Combinatorics/MatchingCount/Tapes/PhysicalAlphabet.lean @@ -0,0 +1,62 @@ +import Mathlib +import OAI.Combinatorics.MatchingCount.Machines.BoolPostCompiler +import OAI.Combinatorics.MatchingCount.Machines.PhysicalRestriction +import OAI.Combinatorics.MatchingCount.Machines.PhysicalProcess + +namespace OAI + +namespace MatchingFPRAS.PhysicalPost +open Turing PhysicalStream BoolPostCompiler + +variable {Q : Type} + +def liftBool (M : Table Bool Q) : Table Symbol Q := fun q a b=> + (M q (down a) b).map (fun qa=>(qa.1,qa.2.map up)) +def upCfg (c : Cfg Bool Q) : Cfg Symbol Q := ⟨c.state,c.tape.map up⟩ +lemma tick_up (M : Table Bool Q) (c : Cfg Bool Q) (b : Bool) : + tick (liftBool M) (upCfg c) b=upCfg (tick M c b) := by + rcases c with ⟨s,T⟩ + cases s with + | none => rfl + | some q => + simp only [tick,upCfg,liftBool,(show (T.map up).head=up T.head from rfl),down_up] + cases e:M q T.head b with + | none => rfl + | some qa => + rcases qa with ⟨q',act⟩ + cases act with + | move d => simp only [Option.map_some,TM0.Stmt.map,Tape.map_move] + | write a => simp only [Option.map_some,TM0.Stmt.map,Tape.map_write] +lemma execute_up (M : Table Bool Q) (n : ℕ) (c : Cfg Bool Q) (b : Stream) : + execute (liftBool M) n (upCfg c) b=upCfg (execute M n c b) := by + induction n generalizing c b with + | zero => rfl + | succ n ih => rw [execute,tick_up,ih,execute] +lemma liftBool_supported (M : Table Bool Q) (S : Finset Q) (hS : Supported M S) : + Supported (liftBool M) S := by + intro q hq a b q' act he + simp only [liftBool,Option.map_eq_some_iff] at he + obtain ⟨⟨q'',act'⟩,h,e⟩:=he + have hqq : q''=q':=congrArg Prod.fst e + subst q'' + exact hS q hq (down a) b q' act' h +lemma up_init (q : Q) (input : List Bool) : + upCfg (⟨some q,Tape.mk₁ input⟩ : Cfg Bool Q)=⟨some q,Tape.mk₁ (input.map up)⟩ := by + simp only [upCfg,Tape.map_mk₁] +lemma Implements.up {α : Type} {M : Table Bool Q} {out : α → Cfg Bool Q} + {c : Cfg Bool Q} {p : Experiment α} (h : Implements M out c p) : + Implements (liftBool M) (fun a=>upCfg (out a)) (upCfg c) p := by + induction h with + | done a => exact .done a + | read c f h ih => + apply Implements.read + intro b + rw [tick_up] + exact ih b + | delay c d n p hs hr ih => + apply Implements.delay (upCfg c) (upCfg d) n p _ ih + intro b + rw [execute_up,hs] +end MatchingFPRAS.PhysicalPost + +end OAI diff --git a/lean/OAI/Combinatorics/MatchingCount/Tapes/ProductBits.lean b/lean/OAI/Combinatorics/MatchingCount/Tapes/ProductBits.lean new file mode 100644 index 0000000000000000000000000000000000000000..6c3244a63afd54908e6c4e91589b8a16337857ad --- /dev/null +++ b/lean/OAI/Combinatorics/MatchingCount/Tapes/ProductBits.lean @@ -0,0 +1,170 @@ +import Mathlib +import OAI.Combinatorics.MatchingCount.Sampling.MetropolisChoice + +namespace OAI + +namespace MatchingFPRAS.Variation + +open Finset +open scoped Classical + +variable {Ω : Type*} [Fintype Ω] + +omit [Fintype Ω] in +lemma product_nonneg {I : Type*} [Fintype I] [DecidableEq I] (p : I → Ω → ℝ) + (hp : ∀ i x,0≤p i x) (x : I → Ω) : 0≤product p x := + prod_nonneg (fun i _=>hp i (x i)) + +lemma product_sum {I : Type*} [Fintype I] [DecidableEq I] (p : I → Ω → ℝ) + (hp : ∀ i,∑ x,p i x=1) : ∑ x,product p x=1 := by + unfold product + rw [←Fintype.prod_sum] + simp [hp] + +lemma product_fin_tv (n : ℕ) (p q : Fin n → Ω → ℝ) + (hp : ∀ i x,0≤p i x) (hps : ∀ i,∑ x,p i x=1) + (hq : ∀ i x,0≤q i x) (hqs : ∀ i,∑ x,q i x=1) : + tv (product p) (product q)≤∑ i,tv (p i) (q i) := by + induction n with + | zero => simp [tv,product] + | succ n ih => + let e : (Ω×(Fin n → Ω)) ≃ (Fin (n+1) → Ω) := Fin.consEquiv (fun _=>Ω) + have hpE : product p ∘ e=tensor (p 0) (product (fun i : Fin n=>p i.succ)) := by + funext x + simp [product,tensor,e,Fin.prod_univ_succ] + have hqE : product q ∘ e=tensor (q 0) (product (fun i : Fin n=>q i.succ)) := by + funext x + simp [product,tensor,e,Fin.prod_univ_succ] + rw [←tv_equiv e,hpE,hqE] + have ht := tensor_tv (p 0) (q 0) (product (fun i : Fin n=>p i.succ)) + (product (fun i : Fin n=>q i.succ)) (hp 0) (hps 0) + (product_nonneg (fun i : Fin n=>q i.succ) (fun i=>hq i.succ)) + (product_sum (fun i : Fin n=>q i.succ) (fun i=>hqs i.succ)) + rw [Fin.sum_univ_succ] + exact ht.trans (add_le_add_right (ih _ _ (fun i=>hp i.succ) (fun i=>hps i.succ) + (fun i=>hq i.succ) (fun i=>hqs i.succ)) _) + +lemma product_tv {I : Type*} [Fintype I] [DecidableEq I] (p q : I → Ω → ℝ) + (hp : ∀ i x,0≤p i x) (hps : ∀ i,∑ x,p i x=1) + (hq : ∀ i x,0≤q i x) (hqs : ∀ i,∑ x,q i x=1) : + tv (product p) (product q)≤∑ i,tv (p i) (q i) := by + let e:=Fintype.equivFin I + let a : (I → Ω) ≃ (Fin (Fintype.card I) → Ω) := Equiv.arrowCongr e (Equiv.refl Ω) + have he (p : I → Ω → ℝ) : product p ∘ a.symm=product (fun i=>p (e.symm i)) := by + funext x + change (∏ i,p i (x (e i)))=∏ j,p (e.symm j) (x j) + exact Fintype.prod_equiv e _ _ (by simp) + rw [←tv_equiv a.symm,he,he] + have ht:=product_fin_tv _ (fun i=>p (e.symm i)) (fun i=>q (e.symm i)) + (fun i=>hp _) (fun i=>hps _) (fun i=>hq _) (fun i=>hqs _) + rw [e.symm.sum_comp (fun i=>tv (p i) (q i))] at ht + exact ht + +lemma uniform_fun {I A : Type*} [Fintype I] [DecidableEq I] [Fintype A] (x : I → A) : + uniform (I → A) x=∏ i,uniform A (x i) := by + simp [uniform,Nat.cast_pow] + +omit [Fintype Ω] in +lemma imageLaw_componentwise [Fintype Ω] {I A : Type*} [Fintype I] [DecidableEq I] [Fintype A] + (f : I → A → Ω) : imageLaw (fun x : I → A=>fun i=>f i (x i))= + product (fun i=>imageLaw (f i)) := by + funext y + let : DecidableEq (I → Ω) := Classical.decEq _ + have he (x : I → A) : (if (fun i=>f i (x i))=y then uniform (I → A) x else 0)= + ∏ i,if f i (x i)=y i then uniform A (x i) else 0 := by + by_cases h : (fun i=>f i (x i))=y + · rw [ite_eq_left h,uniform_fun] + apply prod_congr rfl + intro i _ + rw [ite_eq_left (congrFun h i)] + · rw [ite_eq_right h] + obtain ⟨i,hi⟩ : ∃ i,f i (x i)≠y i := by + by_contra hn + apply h + funext i + exact Classical.not_not.mp (fun hi=>hn ⟨i,hi⟩) + symm + exact prod_eq_zero (mem_univ i) (ite_eq_right hi) + unfold imageLaw push product + simp_rw [he] + exact (Fintype.prod_sum (fun i a=>if f i a=y i then uniform A a else 0)).symm + +lemma product_restrict {I : Type*} [Fintype I] [DecidableEq I] (S : Finset I) + (p : I → Ω → ℝ) (hs : ∀ i,∑ a,p i a=1) : + push (product p) (fun x=>fun i : S=>x i.val)=product (fun i : S=>p i.val) := by + funext y + let : DecidableEq (S → Ω) := Classical.decEq _ + let q : I → Ω → ℝ := fun i a=>if hi : i∈S then (if a=y ⟨i,hi⟩ then p i a else 0) else p i a + have he (x : I → Ω) : (if (fun i : S=>x i.val)=y then product p x else 0)=∏ i,q i (x i) := by + by_cases h : (fun i : S=>x i.val)=y + · rw [ite_eq_left h] + apply prod_congr rfl + intro i _ + by_cases hi : i∈S + · simp only [q,dite_eq_left hi,congrFun h ⟨i,hi⟩,ite_true] + · simp only [q,dite_eq_right hi] + · rw [ite_eq_right h] + obtain ⟨i,hi⟩ : ∃ i : S,x i.val≠y i := by + by_contra hn + apply h + funext i + exact Classical.not_not.mp (fun hi=>hn ⟨i,hi⟩) + symm + apply prod_eq_zero (mem_univ i.val) + simp only [q,dite_eq_left i.property,ite_eq_right hi] + have hq (i : I) : ∑ a,q i a=if hi : i∈S then p i (y ⟨i,hi⟩) else 1 := by + by_cases hi : i∈S + · simp [q,hi] + · simp [q,hi,hs i] + unfold push + simp_rw [he] + rw [←Fintype.prod_sum] + simp_rw [hq] + change (∏ i,if hi : i∈S then p i (y ⟨i,hi⟩) else 1)=∏ i : S,p i.val (y i) + let g : I → ℝ := fun i=>if hi : i∈S then p i (y ⟨i,hi⟩) else 1 + change (∏ i,g i)=_ + calc + _ = ∏ i∈S,g i := (prod_subset (subset_univ S) (by intro i _ hi;simp [g,hi])).symm + _ = ∏ i∈S.attach,g i.val := (Finset.prod_attach S g).symm + _ = ∏ i : S,p i.val (y i) := by + rw [Finset.univ_eq_attach] + apply prod_congr rfl + intro i _ + simp [g] + +lemma imageLaw_tensor {A B C D : Type*} [Fintype A] [Fintype B] [Fintype C] [Fintype D] + (f : A → C) (g : B → D) : + imageLaw (fun x : A×B=>(f x.1,g x.2))=tensor (imageLaw f) (imageLaw g) := by + funext y + simp only [imageLaw,push,tensor,Fintype.sum_prod_type,uniform_prod,sum_mul,mul_sum] + rw [sum_comm] + apply sum_congr rfl + intro b _ + apply sum_congr rfl + intro a _ + by_cases hf : f a=y.1 <;> by_cases hg : g b=y.2 <;> simp [hf,hg,Prod.ext_iff] + +lemma push_tensor_sigma {A B : Type*} [Fintype A] [Fintype B] {C : A → Type*} + [∀ a,Fintype (C a)] (p : A → ℝ) (r : B → ℝ) (f : ∀ a,B → C a) : + push (tensor p r) (fun x : A×B=>Sigma.mk x.1 (f x.1 x.2))= + sigmaLift p (fun a=>push r (f a)) := by + funext x + obtain ⟨a,c⟩:=x + simp only [push,tensor,sigmaLift,Fintype.sum_prod_type] + have he (x : A) : (∑ b,if (⟨x,f x b⟩ : Sigma C)=⟨a,c⟩ then p x*r b else 0)= + if x=a then p a*(∑ b,if f a b=c then r b else 0) else 0 := by + by_cases h : x=a + · subst x + simp [mul_sum,mul_ite] + · simp only [ite_eq_right h] + apply sum_eq_zero + intro b _ + apply ite_eq_right + intro he + exact h (congrArg Sigma.fst he) + simp_rw [he] + simp + +end MatchingFPRAS.Variation + +end OAI diff --git a/lean/OAI/Combinatorics/MatchingCount/Tapes/RandomReservoir.lean b/lean/OAI/Combinatorics/MatchingCount/Tapes/RandomReservoir.lean new file mode 100644 index 0000000000000000000000000000000000000000..af0eaeacd309b7b813001c691d70b6b9a79f9868 --- /dev/null +++ b/lean/OAI/Combinatorics/MatchingCount/Tapes/RandomReservoir.lean @@ -0,0 +1,67 @@ +import Mathlib +import OAI.Combinatorics.MatchingCount.Tapes.RandomWordLaw + +namespace OAI + +namespace MatchingFPRAS.RandomWord +open Turing BinaryArithmetic + +lemma draw_forward_suffix (xs : List (Bool×Bool)) (L R : List Symbol) : + execute (pairCoins xs) (cfg (some 0) L (List.replicate xs.length 1++3::R))= + cfg (some 0) ((drawnWord xs).reverse++L) (3::R) := by + induction xs generalizing L with + | nil=>rfl + | cons p xs ih=> + simp only [pairCoins,List.flatMap_cons,List.length_cons,List.replicate_succ,List.cons_append] + change execute ([p.1,p.2]++pairCoins xs) (cfg (some 0) L (1::(List.replicate xs.length 1++3::R)))=_ + rw [execute_append,draw_two,ih] + simp [drawnWord,List.reverse_cons,List.append_assoc] +lemma finish_run_suffix (L R : List Symbol) (hL : ∀ b∈L,b≠0) + (xs : List Bool) (hx : xs.length=L.length+3) : + execute xs (cfg (some 0) L (3::R))=cfg none [] (L.reverse++3::R) := by + obtain ⟨ys,b,rfl⟩ : ∃ ys b,xs=ys++[b] := by + have hn : xs.reverse≠[] := by + intro h + have h' : xs.length=0 := by simpa only [List.length_reverse,List.length_nil] using congrArg List.length h + omega + obtain ⟨b,ys,he⟩:=List.exists_cons_of_ne_nil hn + exact ⟨ys.reverse,b,by have h:=congrArg List.reverse he; simpa using h⟩ + have hy : ys.length=L.length+2 := by simpa using hx + have he : execute ys (cfg (some 0) L (3::R))=cfg (some 3) [] (L.reverse++3::R) := by + have hr:=reset_run L R 3 (by decide) hL ys hy + cases ys with + | nil=>simp at hy + | cons c ys=> + rw [execute_cons] at hr ⊢ + have ht : tick machine (cfg (some 0) L (3::R)) c=tick machine (cfg (some 2) L (3::R)) c := by + simp [tick,machine,Tape.mk₂,Tape.mk'] + rw [ht] + exact hr + rw [execute_append,he] + simp [execute,tick,machine,cfg] +lemma execute_word_suffix (xs : List (Bool×Bool)) (tail : List Bool) (R : List Symbol) + (ht : tail.length=xs.length+3) : + execute (pairCoins xs++tail) (cfg (some 0) [] (List.replicate xs.length 1++3::R))= + cfg none [] (drawnWord xs++3::R) := by + rw [execute_append,draw_forward_suffix,List.append_nil] + have hn : ∀ b∈(drawnWord xs).reverse,b≠0 := by + intro b hb + obtain ⟨p,hp,rfl⟩:=List.mem_map.mp (List.mem_reverse.mp hb) + exact bitSymbol_ne_zero _ + simpa using finish_run_suffix (drawnWord xs).reverse R hn tail (by simpa [drawnWord] using ht) +lemma run_word_suffix (m : ℕ) (R : List Symbol) (bits : Fin (m*2+(m+3))→Bool) : + run machine (List.replicate m 1++3::R) bits= + cfg none [] ((List.ofFn (outputCoins m bits)).map bitSymbol++3::R) := by + obtain ⟨⟨x,y⟩,rfl⟩:=(wordTapeEquiv m).symm.surjective bits + change execute (List.ofFn ((wordTapeEquiv m).symm (x,y))) + (cfg (some 0) [] (List.replicate m 1++3::R))=_ + rw [wordTape_list] + have h:=execute_word_suffix (List.ofFn x) (List.ofFn y) R (by simp) + have ho : outputCoins m ((wordTapeEquiv m).symm (x,y))=(fun i=>(x i).1) := by + funext i + simp only [outputCoins,Equiv.apply_symm_apply] + rw [ho] + simpa only [List.length_ofFn,drawnWord,List.map_ofFn,Function.comp_def] using h +end MatchingFPRAS.RandomWord + +end OAI diff --git a/lean/OAI/Combinatorics/MatchingCount/Tapes/RandomWord.lean b/lean/OAI/Combinatorics/MatchingCount/Tapes/RandomWord.lean new file mode 100644 index 0000000000000000000000000000000000000000..a6091e209feb98f5b96ffb5fbd37ac4a355c0506 --- /dev/null +++ b/lean/OAI/Combinatorics/MatchingCount/Tapes/RandomWord.lean @@ -0,0 +1,111 @@ +import Mathlib +import OAI.Combinatorics.MatchingCount.Arithmetic.BinaryIncrement +import OAI.Combinatorics.MatchingCount.Arithmetic.BinaryCopy + +namespace OAI + +namespace MatchingFPRAS.RandomWord +open Turing BinaryArithmetic + +abbrev machine : RandomMachine where + states := 3 + transition s a b := + if s=0 then + if a=3 then some (2,.move .left) else some (1,.write (bitSymbol b)) + else if s=1 then some (0,.move .right) + else if s=2 then + if a=0 then some (3,.move .right) else some (2,.move .left) + else none +abbrev cfg (s : Option (Fin 4)) (L R : List Symbol) : Configuration machine := + ⟨s,Tape.mk₂ L R⟩ +def execute (xs : List Bool) (c : Configuration machine) : Configuration machine := + xs.foldl (tick machine) c +lemma execute_append (xs ys : List Bool) (c : Configuration machine) : + execute (xs++ys) c=execute ys (execute xs c) := List.foldl_append +lemma execute_cons (b : Bool) (xs : List Bool) (c : Configuration machine) : + execute (b::xs) c=execute xs (tick machine c b) := rfl +lemma execute_halted (xs : List Bool) (L R : List Symbol) : + execute xs (cfg none L R)=cfg none L R := by + induction xs with + | nil => rfl + | cons b xs ih => exact ih +lemma draw_two (b c : Bool) (L R : List Symbol) : + execute [b,c] (cfg (some 0) L (1::R))=cfg (some 0) (bitSymbol b::L) R := by + simp [execute,tick,machine,cfg,Tape.mk₂,Tape.mk',Tape.write,Tape.move] +def pairCoins (xs : List (Bool×Bool)) : List Bool := xs.flatMap (fun p=>[p.1,p.2]) +def drawnWord (xs : List (Bool×Bool)) : List Symbol := xs.map (fun p=>bitSymbol p.1) +lemma draw_forward (xs : List (Bool×Bool)) (L : List Symbol) : + execute (pairCoins xs) (cfg (some 0) L (List.replicate xs.length 1++[3]))= + cfg (some 0) ((drawnWord xs).reverse++L) [3] := by + induction xs generalizing L with + | nil => rfl + | cons p xs ih => + simp only [pairCoins,List.flatMap_cons,List.length_cons,List.replicate_succ,List.cons_append] + change execute ([p.1,p.2]++pairCoins xs) (cfg (some 0) L (1::(List.replicate xs.length 1++[3])))=_ + rw [execute_append,draw_two] + rw [ih] + simp [drawnWord,List.reverse_cons,List.append_assoc] +lemma reset_tick (L R : List Symbol) (a : Symbol) (ha : a≠0) (b : Bool) : + tick machine (cfg (some 2) L (a::R)) b= + ⟨some 2,(Tape.mk₂ L (a::R)).move .left⟩ := by + simp [tick,machine,Tape.mk₂,Tape.mk',ha] +lemma reset_run (L R : List Symbol) (a : Symbol) (ha : a≠0) + (hL : ∀ b∈L,b≠0) (xs : List Bool) (hx : xs.length=L.length+2) : + execute xs (cfg (some 2) L (a::R))=cfg (some 3) [] (L.reverse++a::R) := by + induction L generalizing a R xs with + | nil => + obtain ⟨b,c,rfl⟩ : ∃ b c,xs=[b,c] := by + exact List.length_eq_two.mp (by simpa using hx) + rw [execute_cons,reset_tick _ _ _ ha] + simp [execute,tick,machine,cfg,Tape.mk₂,Tape.mk',Tape.move,ListBlank.cons_mk] + apply Quotient.sound + exact Or.inr ⟨1,rfl⟩ + | cons b L ih => + cases xs with + | nil => simp at hx + | cons c xs => + have hb : b≠0:=hL b (by simp) + have hL' : ∀ d∈L,d≠0:=fun d hd=>hL d (by simp [hd]) + rw [execute_cons,reset_tick _ _ _ ha] + have ht : (⟨some 2,(Tape.mk₂ (b::L) (a::R)).move .left⟩ : Configuration machine)= + cfg (some 2) L (b::a::R) := by + simp [cfg,Tape.mk₂,Tape.mk',Tape.move] + rw [ht,ih (a::R) b hb hL' xs (by simpa using hx)] + simp [cfg,List.reverse_cons,List.append_assoc] +lemma finish_run (L : List Symbol) (hL : ∀ b∈L,b≠0) + (xs : List Bool) (hx : xs.length=L.length+3) : + execute xs (cfg (some 0) L [3])=cfg none [] (L.reverse++[3]) := by + obtain ⟨ys,b,rfl⟩ : ∃ ys b,xs=ys++[b] := by + have hn : xs.reverse≠[] := by + intro h + have h' : xs.length=0 := by simpa only [List.length_reverse,List.length_nil] using congrArg List.length h + omega + obtain ⟨b,ys,he⟩:=List.exists_cons_of_ne_nil hn + exact ⟨ys.reverse,b,by have h:=congrArg List.reverse he; simpa using h⟩ + have hy : ys.length=L.length+2 := by simpa using hx + have he : execute ys (cfg (some 0) L [3])=cfg (some 3) [] (L.reverse++[3]) := by + have hr:=reset_run L [] 3 (by decide) hL ys hy + cases ys with + | nil => simp at hy + | cons c ys => + rw [execute_cons] at hr ⊢ + have ht : tick machine (cfg (some 0) L [3]) c=tick machine (cfg (some 2) L [3]) c := by + simp [tick,machine,Tape.mk₂,Tape.mk'] + rw [ht] + exact hr + rw [execute_append,he] + simp [execute,tick,machine,cfg] + +theorem execute_word (xs : List (Bool×Bool)) (tail : List Bool) + (ht : tail.length=xs.length+3) : + execute (pairCoins xs++tail) (cfg (some 0) [] (List.replicate xs.length 1++[3]))= + cfg none [] (drawnWord xs++[3]) := by + rw [execute_append,draw_forward,List.append_nil] + have hn : ∀ b∈(drawnWord xs).reverse,b≠0 := by + intro b hb + obtain ⟨p,hp,rfl⟩:=List.mem_map.mp (List.mem_reverse.mp hb) + exact bitSymbol_ne_zero _ + simpa using finish_run (drawnWord xs).reverse hn tail (by simpa [drawnWord] using ht) +end MatchingFPRAS.RandomWord + +end OAI diff --git a/lean/OAI/Combinatorics/MatchingCount/Tapes/RandomWordLaw.lean b/lean/OAI/Combinatorics/MatchingCount/Tapes/RandomWordLaw.lean new file mode 100644 index 0000000000000000000000000000000000000000..b860856a9b74db162ff480c50cb5c0b22e3456ab --- /dev/null +++ b/lean/OAI/Combinatorics/MatchingCount/Tapes/RandomWordLaw.lean @@ -0,0 +1,93 @@ +import Mathlib +import OAI.Combinatorics.MatchingCount.Tapes.RandomWord + +namespace OAI + +namespace MatchingFPRAS.RandomWord +open Turing BinaryArithmetic + +def splitBits (m n : ℕ) : (Fin (m+n) → Bool) ≃ ((Fin m → Bool) × (Fin n → Bool)) := + (Equiv.arrowCongr finSumFinEquiv.symm (Equiv.refl Bool)).trans + (Equiv.sumArrowEquivProdArrow _ _ _) +def gridBits (m n : ℕ) : (Fin (m*n) → Bool) ≃ (Fin m → Fin n → Bool) := + (Equiv.arrowCongr finProdFinEquiv.symm (Equiv.refl Bool)).trans (Equiv.curry _ _ _) +def wordTapeEquiv (m : ℕ) : (Fin (m*2+(m+3)) → Bool) ≃ + ((Fin m → Bool×Bool) × (Fin (m+3) → Bool)) := + (splitBits (m*2) (m+3)).trans (Equiv.prodCongr + ((gridBits m 2).trans (Equiv.piCongrRight fun _=>finTwoArrowEquiv Bool)) (Equiv.refl _)) +lemma gridBits_apply (m n : ℕ) (b : Fin (m*n) → Bool) (i : Fin m) (j : Fin n) : + gridBits m n b i j=b (finProdFinEquiv (i,j)) := rfl +lemma splitBits_symm (m n : ℕ) (x : Fin m → Bool) (y : Fin n → Bool) : + (splitBits m n).symm (x,y)=Fin.append x y := by + ext i + refine Fin.addCases (fun i=>?_) (fun j=>?_) i <;> simp [splitBits,Fin.append,finSumFinEquiv] +lemma wordTape_list (m : ℕ) (x : Fin m → Bool×Bool) (y : Fin (m+3) → Bool) : + List.ofFn ((wordTapeEquiv m).symm (x,y))=pairCoins (List.ofFn x)++List.ofFn y := by + let rows : Fin m → Fin 2 → Bool:=fun i=>![ (x i).1,(x i).2 ] + let b : Fin (m*2) → Bool:=(gridBits m 2).symm rows + have hb (i : Fin m) (j : Fin 2) : b (finProdFinEquiv (i,j))=rows i j := by + exact congrFun (congrFun ((gridBits m 2).apply_symm_apply rows) i) j + have he : (wordTapeEquiv m).symm (x,y)=Fin.append b y := splitBits_symm _ _ b y + rw [he,List.ofFn_fin_append] + congr 1 + rw [List.ofFn_mul] + have hi (i : Fin m) : (List.ofFn fun j : Fin 2=>b ⟨i*2+j,by omega⟩)=[(x i).1,(x i).2] := by + have he' : (fun j : Fin 2=>b ⟨i*2+j,by omega⟩)=rows i := by + funext j + have hc : finProdFinEquiv (i,j)=(⟨i*2+j,by omega⟩ : Fin (m*2)) := by + apply Fin.ext + change j.val+2*i.val=i.val*2+j.val + omega + exact hc ▸ hb i j + rw [he'] + simp [rows,List.ofFn_succ] + simp_rw [hi] + simp [pairCoins,List.map_ofFn,List.flatMap,Function.comp_def] +lemma wordTape_run (m : ℕ) (x : Fin m → Bool×Bool) (y : Fin (m+3) → Bool) : + MatchingFPRAS.run machine (List.replicate m 1++[3]) ((wordTapeEquiv m).symm (x,y))= + cfg none [] (drawnWord (List.ofFn x)++[3]) := by + change execute (List.ofFn ((wordTapeEquiv m).symm (x,y))) + (cfg (some 0) [] (List.replicate m 1++[3]))=_ + rw [wordTape_list] + convert execute_word (List.ofFn x) (List.ofFn y) (by simp) using 1 + simp + +theorem run_word (m : ℕ) (bits : Fin (m*2+(m+3)) → Bool) : + MatchingFPRAS.run machine (List.replicate m 1++[3]) bits= + cfg none [] (drawnWord (List.ofFn (wordTapeEquiv m bits).1)++[3]) := by + have he:=wordTape_run m (wordTapeEquiv m bits).1 (wordTapeEquiv m bits).2 + simpa only [Prod.mk.eta,Equiv.symm_apply_apply] using he + +def outputCoins (m : ℕ) (bits : Fin (m*2+(m+3)) → Bool) : Fin m → Bool := + fun i=>(wordTapeEquiv m bits).1 i |>.1 + +def outputSplit (m : ℕ) : (Fin (m*2+(m+3)) → Bool) ≃ + ((Fin m → Bool) × ((Fin m → Bool) × (Fin (m+3) → Bool))) := + (wordTapeEquiv m).trans ((Equiv.prodCongr (Equiv.arrowProdEquivProdArrow _ _ _) (Equiv.refl _)).trans + (Equiv.prodAssoc _ _ _)) +lemma outputSplit_fst (m : ℕ) (bits : Fin (m*2+(m+3)) → Bool) : + (outputSplit m bits).1=outputCoins m bits := rfl + +theorem outputCoins_fiber (m : ℕ) (x : Fin m → Bool) : + (Finset.univ.filter (fun b=>outputCoins m b=x)).card=2^(2*m+3) := by + classical + let e : ({b : Fin (m*2+(m+3)) → Bool // outputCoins m b=x}) ≃ + ((Fin m → Bool) × (Fin (m+3) → Bool)) := { + toFun := fun b=>(outputSplit m b.1).2 + invFun := fun y=>⟨(outputSplit m).symm (x,y),by + change (outputSplit m ((outputSplit m).symm (x,y))).1=x + rw [Equiv.apply_symm_apply]⟩ + left_inv b := by + apply Subtype.ext + apply (outputSplit m).injective + rw [Equiv.apply_symm_apply] + exact Prod.ext b.property.symm rfl + right_inv y := by change (outputSplit m ((outputSplit m).symm (x,y))).2=y; rw [Equiv.apply_symm_apply] } + rw [←Fintype.card_subtype] + rw [Fintype.card_congr e] + simp only [Fintype.card_prod,Fintype.card_fun,Fintype.card_fin,Fintype.card_bool,←pow_add] + congr 1 + omega +end MatchingFPRAS.RandomWord + +end OAI diff --git a/lean/OAI/Combinatorics/MatchingCount/Tapes/RunBits.lean b/lean/OAI/Combinatorics/MatchingCount/Tapes/RunBits.lean new file mode 100644 index 0000000000000000000000000000000000000000..d519d5bb4ae334b6eb8f27081b2a7a8d7f087230 --- /dev/null +++ b/lean/OAI/Combinatorics/MatchingCount/Tapes/RunBits.lean @@ -0,0 +1,391 @@ +import Mathlib +import OAI.Combinatorics.MatchingCount.Graphs.Cumulative + +namespace OAI + +namespace MatchingFPRAS.FiniteChoice + +open Finset + +lemma tapeIndex_value (k : ℕ) (bits : Fin k → Bool) : + (tapeIndex k bits).val = ∑ i, (if bits i then 1 else 0)*2^i.val := by + change (finFunctionFinEquiv (fun i => finTwoEquiv.symm (bits i))).val = _ + rw [finFunctionFinEquiv_apply] + apply sum_congr rfl; intro i _ + cases bits i <;> simp [finTwoEquiv] + +lemma tapeLaw_eq {r : ℕ} (p : Fin r → ℚ) (hs : ∑ i, p i = 1) (k : ℕ) : + tapeLaw p hs k = outputLaw p hs (pow_pos (by norm_num : 0 < (2:ℕ)) k) := by + funext i + have hcard : (univ.filter (fun bits : Fin k → Bool => chooseBits p hs k bits=i)).card = + (univ.filter (fun J : Fin (2^k) => choose p hs (pow_pos (by norm_num : 0 < (2:ℕ)) k) J=i)).card := by + calc + _ = ∑ bits : Fin k → Bool, if chooseBits p hs k bits=i then (1:ℕ) else 0 := by simp + _ = ∑ J : Fin (2^k), if choose p hs (pow_pos (by norm_num : 0 < (2:ℕ)) k) J=i then (1:ℕ) else 0 := + by + simp only [chooseBits] + convert (tapeIndex k).sum_comp + (fun J : Fin (2^k) => if choose p hs (pow_pos (by norm_num : 0 < (2:ℕ)) k) J=i then (1:ℕ) else 0) using 1 + congr 3 + _ = _ := by simp + simp only [tapeLaw,outputLaw,hcard,Nat.cast_pow,Nat.cast_ofNat] + +end MatchingFPRAS.FiniteChoice + +namespace MatchingFPRAS.BoundedSimulation + +open Finset + +variable {Ω : Type*} [Fintype Ω] [DecidableEq Ω] + +def runBits {r : ℕ} (z : Ω) (p : ℕ → Ω → Fin r → ℚ) + (hs : ∀ n s, ∑ i, p n s i = 1) (next : ℕ → Ω → Fin r → Ω) (k : ℕ) : + (n : ℕ) → (Fin n → Fin k → Bool) → Ω + | 0, _ => z + | n+1, bits => + let s := runBits z p hs next k n (Fin.init bits) + next n s (MatchingFPRAS.FiniteChoice.chooseBits (p n s) (hs n s) k (bits (Fin.last n))) + +def pointMass (z : Ω) (s : Ω) : ℚ := if z=s then 1 else 0 + +def uniformLaw {A : Type*} [Fintype A] (f : A → Ω) (s : Ω) : ℚ := + (∑ a, if f a=s then (1:ℚ) else 0)/(Fintype.card A:ℚ) + + + + +omit [Fintype Ω] in +lemma uniformLaw_equiv [Fintype Ω] {A B : Type*} [Fintype A] [Fintype B] (e : A ≃ B) + (f : B → Ω) (s : Ω) : uniformLaw (f ∘ e) s=uniformLaw f s := by + unfold uniformLaw + rw [Fintype.card_congr e] + congr 1 + exact e.sum_comp (fun b => if f b=s then (1:ℚ) else 0) + +lemma fiber_sum {A : Type*} [Fintype A] (f : A → Ω) (g : Ω → ℚ) : + (∑ s, (∑ a, if f a=s then (1:ℚ) else 0)*g s) = ∑ a, g (f a) := by + simp_rw [sum_mul,ite_mul,one_mul,zero_mul] + rw [sum_comm] + simp only [sum_ite_eq,mem_univ,ite_true] + +lemma uniformLaw_map {A Ψ : Type*} [Fintype A] [Fintype Ψ] [DecidableEq Ψ] + (f : A → Ω) (g : Ω → Ψ) (t : Ψ) : + uniformLaw (g ∘ f) t = ∑ s, uniformLaw f s*(if g s=t then 1 else 0) := by + unfold uniformLaw + simp only [Function.comp_apply,div_mul_eq_mul_div,← sum_div] + rw [fiber_sum] + +lemma uniformLaw_prod {A B : Type*} [Fintype A] [Fintype B] + (f : A → Ω) (g : Ω → B → Ω) (t : Ω) : + uniformLaw (fun ab : A×B => g (f ab.1) ab.2) t = + ∑ s, uniformLaw f s*uniformLaw (g s) t := by + unfold uniformLaw + simp only [Fintype.card_prod,Nat.cast_mul,div_mul_div_comm,← sum_div,Fintype.sum_prod_type] + rw [fiber_sum] + +lemma uniformLaw_chooseBits {r : ℕ} (p : Fin r → ℚ) (hs : ∑ i, p i=1) (k : ℕ) (i : Fin r) : + uniformLaw (MatchingFPRAS.FiniteChoice.chooseBits p hs k) i = + MatchingFPRAS.FiniteChoice.outputLaw p hs (pow_pos (by norm_num : 0 < (2:ℕ)) k) i := by + rw [← MatchingFPRAS.FiniteChoice.tapeLaw_eq] + simp [uniformLaw,MatchingFPRAS.FiniteChoice.tapeLaw] + + + + +lemma uniformLaw_choice_step {r : ℕ} (p : Fin r → ℚ) (hs : ∑ i, p i=1) (k : ℕ) + (next : Fin r → Ω) (t : Ω) : + uniformLaw (fun bits => next (MatchingFPRAS.FiniteChoice.chooseBits p hs k bits)) t = + ∑ i, if next i=t then MatchingFPRAS.FiniteChoice.outputLaw p hs + (pow_pos (by norm_num : 0 < (2:ℕ)) k) i else 0 := by + have h := uniformLaw_map (MatchingFPRAS.FiniteChoice.chooseBits p hs k) next t + simp only [uniformLaw_chooseBits,mul_ite,mul_one,mul_zero] at h + convert h using 1 + congr 3 + +lemma runBits_law_succ {r : ℕ} (z : Ω) (p : ℕ → Ω → Fin r → ℚ) + (hs : ∀ n s, ∑ i, p n s i=1) (next : ℕ → Ω → Fin r → Ω) (k n : ℕ) (t : Ω) : + uniformLaw (runBits z p hs next k (n+1)) t = + categoricalStep (uniformLaw (runBits z p hs next k n)) + (fun s => MatchingFPRAS.FiniteChoice.outputLaw (p n s) (hs n s) + (pow_pos (by norm_num : 0 < (2:ℕ)) k)) (next n) t := by + let e : ((Fin n → Fin k → Bool) × (Fin k → Bool)) ≃ (Fin (n+1) → Fin k → Bool) := + (Equiv.prodComm _ _).trans (Fin.snocEquiv (fun _ => Fin k → Bool)) + have hh := uniformLaw_equiv e (runBits z p hs next k (n+1)) t + have hc : (runBits z p hs next k (n+1)) ∘ e = + (fun ab : ((Fin n → Fin k → Bool) × (Fin k → Bool)) => + next n (runBits z p hs next k n ab.1) + (MatchingFPRAS.FiniteChoice.chooseBits (p n (runBits z p hs next k n ab.1)) + (hs n (runBits z p hs next k n ab.1)) k ab.2)) := by + funext ab + rcases ab with ⟨pref, last⟩ + change next n (runBits z p hs next k n (Fin.init (Fin.snoc (α := fun _ : Fin (n+1) => Fin k → Bool) pref last))) + (MatchingFPRAS.FiniteChoice.chooseBits + (p n (runBits z p hs next k n (Fin.init (Fin.snoc (α := fun _ : Fin (n+1) => Fin k → Bool) pref last)))) + (hs n (runBits z p hs next k n (Fin.init (Fin.snoc (α := fun _ : Fin (n+1) => Fin k → Bool) pref last)))) k + ((Fin.snoc (α := fun _ : Fin (n+1) => Fin k → Bool) pref last) (Fin.last n))) = _ + simp only [Fin.init_snoc,Fin.snoc_last] + rw [hc] at hh + rw [← hh,uniformLaw_prod (runBits z p hs next k n) + (fun s bits => next n s (MatchingFPRAS.FiniteChoice.chooseBits (p n s) (hs n s) k bits)) t] + simp only [uniformLaw_choice_step,categoricalStep] + +lemma runBits_law {r : ℕ} (z : Ω) (p : ℕ → Ω → Fin r → ℚ) + (hs : ∀ n s, ∑ i, p n s i=1) (next : ℕ → Ω → Fin r → Ω) (k n : ℕ) : + uniformLaw (runBits z p hs next k n) = bitRun (pointMass z) p hs next k n := by + induction n with + | zero => funext s; by_cases h : z=s <;> simp [runBits,bitRun,uniformLaw,pointMass,h] + | succ n ih => funext s; rw [runBits_law_succ,ih]; rfl + +omit [Fintype Ω] in +lemma pointMass_nonneg [Fintype Ω] (z : Ω) (s : Ω) : 0 ≤ pointMass z s := by + unfold pointMass; split_ifs <;> norm_num + +lemma pointMass_sum (z : Ω) : ∑ s, pointMass z s=1 := by simp [pointMass] + +lemma fixed_tape_card (n k : ℕ) : Fintype.card (Fin n → Fin k → Bool)=2^(n*k) := by + simp only [Fintype.card_fun,Fintype.card_bool,Fintype.card_fin,← pow_mul,Nat.mul_comm k n] + + + + +theorem fixed_tape_simulation {r : ℕ} (z : Ω) (p : ℕ → Ω → Fin r → ℚ) + (hp : ∀ n s i, 0 ≤ p n s i) (hs : ∀ n s, ∑ i, p n s i=1) + (next : ℕ → Ω → Fin r → Ω) (k n : ℕ) : + (∑ s, |uniformLaw (runBits z p hs next k n) s-idealRun (pointMass z) p next n s|)/2 ≤ + 2*n*r/(2:ℚ)^k := by + rw [runBits_law] + exact finite_bit_simulation (pointMass z) (pointMass_nonneg z) (pointMass_sum z) p hp hs next k n + +end MatchingFPRAS.BoundedSimulation + +namespace MatchingFPRAS.Counting + +open Finset + +abbrev alpha : ℚ := 1/100000 + +lemma others_nonempty {n : ℕ} (hn : 2 ≤ n) (i : Fin n) : (univ.erase i).Nonempty := by + let j : Fin n := ⟨if i.val=0 then 1 else 0, by split_ifs <;> omega⟩ + refine ⟨j,mem_erase.mpr ⟨?_,mem_univ _⟩⟩ + apply Fin.ne_of_val_ne + dsimp [j]; split_ifs <;> omega + +def rowMaximum {n : ℕ} (hn : 2 ≤ n) (G : Fin n → Fin n → ℚ) (v : Fin n → ℚ) (i : Fin n) : ℚ := + (univ.erase i).sup' (others_nonempty hn i) (fun j => G i j / v j) + +def scaleUpdate {n : ℕ} (hn : 2 ≤ n) (G : Fin n → Fin n → ℚ) (v : Fin n → ℚ) (i : Fin n) : Fin n → ℚ := + Function.update v i (rowMaximum hn G v i) + +def scalingTrace {n : ℕ} (hn : 2 ≤ n) (G : Fin n → Fin n → ℚ) : ℕ → Fin n → ℚ + | 0 => fun _ => 2 + | k+1 => if hk : k G i j/v j) (mem_erase.mpr ⟨hji,mem_univ _⟩) + +lemma rowMaximum_lower (hn : 2 ≤ n) (G : Fin n → Fin n → ℚ) (v : Fin n → ℚ) + (hG : ∀ i j, i≠j → alpha ≤ G i j) (hv : ScaleInvariant G v) (i) : + alpha/2 ≤ rowMaximum hn G v i := by + obtain ⟨j,hj⟩ := others_nonempty hn i + have hji := (mem_erase.mp hj).1 + apply le_trans _ (ratio_le_rowMaximum hn G v i j hji) + apply (le_div_iff₀ (hv.pos j)).mpr + have hGi := hG i j hji.symm + have hvi := hv.upper j + norm_num [alpha] at * + linarith + +lemma scaleUpdate_le (hn : 2 ≤ n) (G : Fin n → Fin n → ℚ) (v : Fin n → ℚ) + (hv : ScaleInvariant G v) (i j) : scaleUpdate hn G v i j ≤ v j := by + by_cases hji : j=i + · subst j; simpa [scaleUpdate] using rowMaximum_le hn G v hv i + · simp [scaleUpdate,Function.update_of_ne hji] + +lemma scaleUpdate_invariant (hn : 2 ≤ n) (G : Fin n → Fin n → ℚ) (v : Fin n → ℚ) + (hsym : ∀ i j, G i j=G j i) (hG : ∀ i j, i≠j → alpha ≤ G i j) + (hv : ScaleInvariant G v) (i) : ScaleInvariant G (scaleUpdate hn G v i) := by + constructor + · intro j + by_cases hji : j=i + · subst j; simpa [scaleUpdate] using rowMaximum_lower hn G v hG hv i + · simpa [scaleUpdate,Function.update_of_ne hji] using hv.lower j + · intro j; exact (scaleUpdate_le hn G v hv i j).trans (hv.upper j) + · intro a b hab + by_cases hai : a=i + · subst a + have hb := (div_le_iff₀ (hv.pos b)).mp (ratio_le_rowMaximum hn G v i b hab.symm) + simpa [scaleUpdate,Function.update_of_ne hab.symm] using hb + · by_cases hbi : b=i + · subst b + have ha := (div_le_iff₀ (hv.pos a)).mp (ratio_le_rowMaximum hn G v i a hai) + simpa [scaleUpdate,Function.update_of_ne hai,hsym i a,mul_comm] using ha + · simpa [scaleUpdate,Function.update_of_ne hai,Function.update_of_ne hbi] using hv.feasible a b hab + +lemma scaleUpdate_tight (hn : 2 ≤ n) (G : Fin n → Fin n → ℚ) (v : Fin n → ℚ) + (hv : ScaleInvariant G v) (i) : + ∃ j, j≠i ∧ scaleUpdate hn G v i i*scaleUpdate hn G v i j=G i j := by + obtain ⟨j,hj,heq⟩ := Finset.exists_mem_eq_sup' (others_nonempty hn i) (fun j => G i j/v j) + have hji := (mem_erase.mp hj).1 + refine ⟨j,hji,?_⟩ + change rowMaximum hn G v i = G i j/v j at heq + simp only [scaleUpdate,Function.update_self,Function.update_of_ne hji] + rw [heq] + exact div_mul_cancel₀ _ (hv.pos j).ne' + +lemma tight_persists (G : Fin n → Fin n → ℚ) (v v' : Fin n → ℚ) + (hv : ScaleInvariant G v) (hv' : ScaleInvariant G v') (hdown : ∀ i, v' i ≤ v i) + (i j) (hji : j≠i) (hij : v i*v j=G i j) : v' i*v' j=G i j := by + apply le_antisymm + · calc + _ ≤ v i*v j := mul_le_mul (hdown i) (hdown j) (hv'.pos j).le (hv.pos i).le + _ = _ := hij + · exact hv'.feasible i j hji.symm + + + + +lemma scalingTrace_invariant (hn : 2 ≤ n) (G : Fin n → Fin n → ℚ) + (hsym : ∀ i j, G i j=G j i) (hG : ∀ i j, i≠j → alpha ≤ G i j ∧ G i j ≤ 3) + (k : ℕ) : ScaleInvariant G (scalingTrace hn G k) ∧ + ∀ i, i.val + constructor + · constructor + · intro i; norm_num [scalingTrace,alpha] + · intro i; simp [scalingTrace] + · intro i j h; have := (hG i j h).2; simp only [scalingTrace]; linarith + · intro i hi; omega + | succ k ih => + by_cases hk : k (hG i j h).1) ih.1 i + have htrace : scalingTrace hn G (k+1)=scaleUpdate hn G (scalingTrace hn G k) i := by + simp [scalingTrace,hk,i] + rw [htrace] + refine ⟨hinv,?_⟩ + intro a ha + by_cases hak : a.val fun h => ?_⟩ + · intro k i + by_cases hk : k ⟨h i,(htrace n).1.upper i⟩,(htrace n).1.feasible,?_⟩ + intro i + exact (htrace n).2 i i.isLt + + + + +def rowPeak {n : ℕ} (hn : 2 ≤ n) (g : Fin n → Fin n → ℚ) (i : Fin n) : ℚ := + (univ.erase i).sup' (others_nonempty hn i) (g i) + +def scaledHoleMatrix {n : ℕ} (g : Fin n → Fin n → ℚ) (v : Fin n → ℚ) (i j : Fin n) : ℚ := + g i j/(v i*v j) + +def BalancedRows {n : ℕ} (hn : 2 ≤ n) (g : Fin n → Fin n → ℚ) : Prop := + ∀ i, (1:ℚ)/4 ≤ rowPeak hn g i ∧ rowPeak hn g i ≤ 1 + + + + +theorem one_pass_restores_balance {n : ℕ} (hn : 2 ≤ n) (g G : Fin n → Fin n → ℚ) + (hGsym : ∀ i j, G i j=G j i) + (hG : ∀ i j, i≠j → alpha ≤ G i j ∧ G i j ≤ 3) + (hpre : ∀ i, (1:ℚ)/8 ≤ rowPeak hn g i) + (haccuracy : ∀ i j, i≠j → g i j ≤ G i j ∧ G i j ≤ g i j+2*alpha) : + (∀ i, (1:ℚ)/16 ≤ scalingTrace hn G n i) ∧ + BalancedRows hn (scaledHoleMatrix g (scalingTrace hn G n)) := by + let v := scalingTrace hn G n + have hv := (scalingTrace_invariant hn G hGsym hG n).1 + have hlow (i : Fin n) : (1:ℚ)/16 ≤ v i := by + obtain ⟨j,hj,heq⟩ := Finset.exists_mem_eq_sup' (others_nonempty hn i) (g i) + have hji := (mem_erase.mp hj).1 + change rowPeak hn g i=g i j at heq + have hgij : (1:ℚ)/8 ≤ g i j := by rw [← heq]; exact hpre i + have hGi := (haccuracy i j hji.symm).1 + have hfeas := hv.feasible i j hji.symm + have hup := mul_le_mul_of_nonneg_left (hv.upper j) (hv.pos i).le + dsimp [v] + linarith + refine ⟨hlow,?_⟩ + intro i + constructor + · obtain ⟨j,hji,heq⟩ := (one_pass_scaling hn G hGsym hG).2.2.2 i + have hprod : (1:ℚ)/256 ≤ v i*v j := by + calc + (1:ℚ)/256 = ((1:ℚ)/16)*((1:ℚ)/16) := by norm_num + _ ≤ v i*v j := mul_le_mul (hlow i) (hlow j) (by norm_num) (hv.pos i).le + have hacc := (haccuracy i j hji.symm).2 + have hg : (1:ℚ)/4 ≤ scaledHoleMatrix g v i j := by + apply (le_div_iff₀ (mul_pos (hv.pos i) (hv.pos j))).mpr + change v i*v j=G i j at heq + norm_num [alpha] at hacc + nlinarith + apply hg.trans + exact Finset.le_sup' (scaledHoleMatrix g v i) (mem_erase.mpr ⟨hji,mem_univ _⟩) + · apply Finset.sup'_le + intro j hj + have hji := (mem_erase.mp hj).1 + apply (div_le_one (mul_pos (hv.pos i) (hv.pos j))).mpr + exact ((haccuracy i j hji.symm).1).trans (hv.feasible i j hji.symm) + + + +def sigma (D K : ℕ) (epsilon : ℚ) : ℚ := min (alpha/(100*D)) (epsilon/(1000*K)) + +def ratioEstimate (abar dbar : ℚ) : ℚ := if 0hl (e.injective h) + simp [Function.update_of_ne hne,Function.update_of_ne hl] + · have hne : j≠e k := fun h'=>h ⟨k,h'.symm⟩ + rw [Function.update_of_ne hne,extend_off e _ _ j h,extend_off e _ _ j h] + +def stmt (e : K ↪ J) : TM2.Stmt (fun _ : K=>α) Λ σ → TM2.Stmt (fun _ : J=>α) Λ (σ×τ) + | .push k a q => .push (e k) (fun v=>a v.1) (stmt e q) + | .peek k a q => .peek (e k) (fun v x=>(a v.1 x,v.2)) (stmt e q) + | .pop k a q => .pop (e k) (fun v x=>(a v.1 x,v.2)) (stmt e q) + | .load a q => .load (fun v=>(a v.1,v.2)) (stmt e q) + | .branch p q r => .branch (fun v=>p v.1) (stmt e q) (stmt e r) + | .goto l => .goto (fun v=>l v.1) + | .halt => .halt +noncomputable def cfg (e : K ↪ J) (R : J → List α) (u : τ) + (c : TM2.Cfg (fun _ : K=>α) Λ σ) : TM2.Cfg (fun _ : J=>α) Λ (σ×τ) := + ⟨c.l,(c.var,u),extend e c.stk R⟩ +lemma stmt_eval (e : K ↪ J) (R : J → List α) (u : τ) + (q : TM2.Stmt (fun _ : K=>α) Λ σ) (v : σ) (S : K → List α) : + TM2.stepAux (stmt e q) (v,u) (extend e S R)=cfg e R u (TM2.stepAux q v S) := by + induction q generalizing v S with + | push k a q ih => simpa only [stmt,TM2.stepAux,extend_on,extend_update] using ih v (Function.update S k (a v::S k)) + | peek k a q ih => simpa only [stmt,TM2.stepAux,extend_on] using ih (a v (S k).head?) S + | pop k a q ih => simpa only [stmt,TM2.stepAux,extend_on,extend_update] using ih (a v (S k).head?) (Function.update S k (S k).tail) + | load a q ih => exact ih (a v) S + | branch p q r ihq ihr => + cases h : p v <;> simp only [stmt,TM2.stepAux,h,Bool.cond_false,Bool.cond_true] <;> first | apply ihr | apply ihq + | goto l => rfl + | halt => rfl +omit [DecidableEq K] [DecidableEq J] in +lemma stmt_accesses (e : K ↪ J) (q : TM2.Stmt (fun _ : K=>α) Λ σ) : + StackCost.accesses (stmt (τ:=τ) e q)=StackCost.accesses q := by + induction q <;> simp_all [stmt,StackCost.accesses] + +def program (e : K ↪ J) (M : Λ → TM2.Stmt (fun _ : K=>α) Λ σ) := + fun l=>stmt (τ:=τ) e (M l) +lemma advance_cfg (e : K ↪ J) (M : Λ → TM2.Stmt (fun _ : K=>α) Λ σ) + (R : J → List α) (u : τ) (c : TM2.Cfg (fun _ : K=>α) Λ σ) : + advance (TM2.step (program e M)) (cfg e R u c)=cfg e R u (advance (TM2.step M) c) := by + rcases c with ⟨l,v,S⟩ + cases l with + | none => rfl + | some l => exact stmt_eval e R u (M l) v S + +theorem run_cfg (e : K ↪ J) (M : Λ → TM2.Stmt (fun _ : K=>α) Λ σ) + (R : J → List α) (u : τ) (n : ℕ) (c : TM2.Cfg (fun _ : K=>α) Λ σ) : + MachineCost.run (TM2.step (program e M)) n (cfg e R u c)= + cfg e R u (MachineCost.run (TM2.step M) n c) := by + induction n generalizing c with + | zero => rfl + | succ n ih => rw [MachineCost.run,advance_cfg,ih,MachineCost.run] +end MatchingFPRAS.StackEmbedding + +end OAI diff --git a/lean/OAI/Combinatorics/MatchingCount/Tapes/StackLens.lean b/lean/OAI/Combinatorics/MatchingCount/Tapes/StackLens.lean new file mode 100644 index 0000000000000000000000000000000000000000..471c28b4101f480c5e0b28dcff4fb669952d6045 --- /dev/null +++ b/lean/OAI/Combinatorics/MatchingCount/Tapes/StackLens.lean @@ -0,0 +1,76 @@ +import Mathlib +import OAI.Combinatorics.MatchingCount.Tapes.StackEmbedding + +namespace OAI + +namespace MatchingFPRAS.StackLens +open Turing MachineCost StackEmbedding + +structure Lens (σ τ : Type*) where + get : τ → σ + put : τ → σ → τ + get_put : ∀ v s,get (put v s)=s + put_get : ∀ v,put v (get v)=v + put_put : ∀ v s t,put (put v s) t=put v t + +def Lens.identity (σ : Type*) : Lens σ σ := + ⟨id,fun _ s=>s,fun _ _=>rfl,fun _=>rfl,fun _ _ _=>rfl⟩ +def Lens.first (σ τ : Type*) : Lens σ (σ×τ) := + ⟨Prod.fst,fun v s=>(s,v.2),fun _ _=>rfl,fun _=>rfl,fun _ _ _=>rfl⟩ +def Lens.second (σ τ : Type*) : Lens τ (σ×τ) := + ⟨Prod.snd,fun v s=>(v.1,s),fun _ _=>rfl,fun _=>rfl,fun _ _ _=>rfl⟩ +variable {K J α Λ σ τ : Type*} [DecidableEq K] [DecidableEq J] + +def stmt (e : K ↪ J) (L : Lens σ τ) : + TM2.Stmt (fun _ : K=>α) Λ σ → TM2.Stmt (fun _ : J=>α) Λ τ + | .push k a q => .push (e k) (fun v=>a (L.get v)) (stmt e L q) + | .peek k a q => .peek (e k) (fun v x=>L.put v (a (L.get v) x)) (stmt e L q) + | .pop k a q => .pop (e k) (fun v x=>L.put v (a (L.get v) x)) (stmt e L q) + | .load a q => .load (fun v=>L.put v (a (L.get v))) (stmt e L q) + | .branch p q r => .branch (fun v=>p (L.get v)) (stmt e L q) (stmt e L r) + | .goto l => .goto (fun v=>l (L.get v)) + | .halt => .halt +noncomputable def cfg (e : K ↪ J) (L : Lens σ τ) (R : J → List α) (u : τ) + (c : TM2.Cfg (fun _ : K=>α) Λ σ) : TM2.Cfg (fun _ : J=>α) Λ τ := + ⟨c.l,L.put u c.var,extend e c.stk R⟩ +lemma stmt_eval (e : K ↪ J) (L : Lens σ τ) (R : J → List α) (u : τ) + (q : TM2.Stmt (fun _ : K=>α) Λ σ) (v : σ) (S : K → List α) : + TM2.stepAux (stmt e L q) (L.put u v) (extend e S R)= + cfg e L R u (TM2.stepAux q v S) := by + induction q generalizing v S with + | push k a q ih => + simpa only [stmt,TM2.stepAux,L.get_put,extend_on,extend_update] using ih v (Function.update S k (a v::S k)) + | peek k a q ih => + simpa only [stmt,TM2.stepAux,L.get_put,L.put_put,extend_on] using ih (a v (S k).head?) S + | pop k a q ih => + simpa only [stmt,TM2.stepAux,L.get_put,L.put_put,extend_on,extend_update] using ih (a v (S k).head?) (Function.update S k (S k).tail) + | load a q ih => simpa only [stmt,TM2.stepAux,L.get_put,L.put_put] using ih (a v) S + | branch p q r ihq ihr => + cases h : p v <;> simp only [stmt,TM2.stepAux,L.get_put,h,Bool.cond_false,Bool.cond_true] <;> + first | apply ihr | apply ihq + | goto l => simp only [stmt,TM2.stepAux,cfg,L.get_put] + | halt => rfl +omit [DecidableEq K] [DecidableEq J] in +lemma accesses (e : K ↪ J) (L : Lens σ τ) (q : TM2.Stmt (fun _ : K=>α) Λ σ) : + StackCost.accesses (stmt e L q)=StackCost.accesses q := by + induction q <;> simp_all [stmt,StackCost.accesses] +def program (e : K ↪ J) (L : Lens σ τ) (M : Λ → TM2.Stmt (fun _ : K=>α) Λ σ) := + fun l=>stmt e L (M l) +lemma advance_cfg (e : K ↪ J) (L : Lens σ τ) (M : Λ → TM2.Stmt (fun _ : K=>α) Λ σ) + (R : J → List α) (u : τ) (c : TM2.Cfg (fun _ : K=>α) Λ σ) : + advance (TM2.step (program e L M)) (cfg e L R u c)=cfg e L R u (advance (TM2.step M) c) := by + rcases c with ⟨l,v,S⟩ + cases l with + | none => rfl + | some l => exact stmt_eval e L R u (M l) v S + +theorem run_cfg (e : K ↪ J) (L : Lens σ τ) (M : Λ → TM2.Stmt (fun _ : K=>α) Λ σ) + (R : J → List α) (u : τ) (n : ℕ) (c : TM2.Cfg (fun _ : K=>α) Λ σ) : + MachineCost.run (TM2.step (program e L M)) n (cfg e L R u c)= + cfg e L R u (MachineCost.run (TM2.step M) n c) := by + induction n generalizing c with + | zero => rfl + | succ n ih => rw [MachineCost.run,advance_cfg,ih,MachineCost.run] +end MatchingFPRAS.StackLens + +end OAI diff --git a/lean/OAI/Combinatorics/MatchingCount/Tapes/StackWords.lean b/lean/OAI/Combinatorics/MatchingCount/Tapes/StackWords.lean new file mode 100644 index 0000000000000000000000000000000000000000..c1f9aff6ac3f84d099955ee55e5d94d93af18179 --- /dev/null +++ b/lean/OAI/Combinatorics/MatchingCount/Tapes/StackWords.lean @@ -0,0 +1,104 @@ +import Mathlib +import OAI.Combinatorics.MatchingCount.Complexity.StackCompilerCost +import OAI.Combinatorics.MatchingCount.Tapes.FixedAlphabetCompiler + +namespace OAI + +namespace MatchingFPRAS.StackWords +open Turing MachineCost + +variable {K : Type*} {Γ : K → Type*} +def rows (S : ∀ k,List (Γ k)) (H : ℕ) : List (∀ k,Option (Γ k)) := + List.ofFn (fun i : Fin H=>fun k=>(S k).reverse[i.val]?) +def word (S : ∀ k,List (Γ k)) (H : ℕ) : List (TM2to1.Γ' K Γ) := + (true,(rows S H).headI)::((rows S H).tail.map (fun a=>(false,a))) +lemma word_length (S : ∀ k,List (Γ k)) (H : ℕ) : (word S H).length ≤ H+1 := by + change ((rows S H).tail.map (fun a=>(false,a))).length+1 ≤ H+1 + rw [List.length_map,List.length_tail] + simp only [rows,List.length_ofFn] + omega +lemma rows_projection (S : ∀ k,List (Γ k)) (H : ℕ) (hS : StackCost.StackBound S H) + (k : K) : (ListBlank.mk (rows S H)).map (proj k)=ListBlank.mk ((S k).map some).reverse := by + apply ListBlank.ext + intro i + rw [ListBlank.nth_map,ListBlank.nth_mk,List.getI_eq_getElem?_getD] + simp only [rows,List.getElem?_ofFn,proj,PointedMap.mk_val] + rw [←List.map_reverse,ListBlank.nth_mk,List.getI_eq_getElem?_getD,List.getElem?_map] + by_cases hi : i rfl + · have hlen : (S k).reverse.length ≤ i := by simpa using (hS k).trans (Nat.le_of_not_gt hi) + simp [hi,List.getElem?_eq_none hlen] +lemma word_blank (S : ∀ k,List (Γ k)) (H : ℕ) : + ListBlank.mk (word S H)=TM2to1.addBottom (ListBlank.mk (rows S H)) := by + simp only [word,TM2to1.addBottom,ListBlank.head_mk,ListBlank.tail_mk, + ListBlank.map_mk] + exact (ListBlank.cons_mk _ _).symm +lemma unique_rows (S : ∀ k,List (Γ k)) (H : ℕ) (hS : StackCost.StackBound S H) + (L : ListBlank (∀ k,Option (Γ k))) + (hL : ∀ k,L.map (proj k)=ListBlank.mk ((S k).map some).reverse) : + L=ListBlank.mk (rows S H) := by + apply ListBlank.ext + intro i + funext k + rw [TM2to1.stk_nth_val i (hL k),TM2to1.stk_nth_val i (rows_projection S H hS k)] +variable {Λ σ : Type*} [Inhabited Λ] [Inhabited σ] +lemma initial (S : ∀ k,List (Γ k)) (H : ℕ) (hS : StackCost.StackBound S H) : + TM2to1.TrCfg (⟨some default,default,S⟩ : TM2.Cfg Γ Λ σ) + (TM1.init (word S H)) := by + have h:=TM2to1.TrCfg.mk (Λ:=Λ) (σ:=σ) (q:=some default) (v:=default) + (ListBlank.mk (rows S H)) (rows_projection S H hS) + convert h using 1 + simp only [TM1.init,Tape.mk₁,Tape.mk₂,word_blank] + rfl +omit [Inhabited Λ] [Inhabited σ] in +lemma output {c : TM2.Cfg Γ Λ σ} {b : TM1.Cfg (TM2to1.Γ' K Γ) (TM2to1.Λ' K Γ Λ σ) σ} + (hcb : TM2to1.TrCfg c b) (H : ℕ) (hS : StackCost.StackBound c.stk H) : + b.l=c.l.map TM2to1.Λ'.normal ∧ b.Tape.right₀=ListBlank.mk (word c.stk H) := by + rcases hcb with ⟨L,hL⟩ + constructor + · rfl + · simp only [Tape.mk'_right₀,word_blank] + rw [unique_rows _ H hS L hL] +variable [DecidableEq K] [Fintype K] [∀ k,Fintype (Γ k)] [Fintype σ] +variable {w : ℕ} (enc : TM2to1.Γ' K Γ → List.Vector Bool w) + (dec : List.Vector Bool w → TM2to1.Γ' K Γ) + (enc0 : enc default=List.Vector.replicate w false) + (encdec : ∀ a,dec (enc a)=a) + (M : Λ → TM2.Stmt Γ Λ σ) (S : Finset Λ) (hs : TM2.Supports M S) +noncomputable def compiled : RandomMachine := + FixedAlphabetCompiler.compiled enc dec (TM2to1.tr M) (TM2to1.trSupp M S) + (TM2to1.tr_supports M hs) +noncomputable def cost : ℕ := + FixedAlphabetCompiler.cost enc dec (TM2to1.tr M) (TM2to1.trSupp M S) +def encoded (S₀ : ∀ k,List (Γ k)) (H : ℕ) : List Symbol := + FixedAlphabetCompiler.word enc (word S₀ H) +include enc0 encdec + +theorem compiled_execution (A : ℕ) (hA : ∀ l,StackCost.accesses (M l)≤A) + (S₀ : ∀ k,List (Γ k)) (H₀ : ℕ) (h₀ : StackCost.StackBound S₀ H₀) + (n H₁ : ℕ) + (hh : (MachineCost.run (TM2.step M) n ⟨some default,default,S₀⟩).l=none) + (ho : StackCost.StackBound (MachineCost.run (TM2.step M) n ⟨some default,default,S₀⟩).stk H₁) + (t : ℕ) (ht : cost enc dec M S*(n*(1+2*A*(H₀+n*A+1)))+2≤t) + (bits : Fin t → Bool) : + (MatchingFPRAS.run (compiled enc dec M S hs) (encoded enc S₀ H₀) bits).state=none ∧ + (MatchingFPRAS.run (compiled enc dec M S hs) (encoded enc S₀ H₀) bits).tape.right₀= + ListBlank.mk (encoded enc (MachineCost.run (TM2.step M) n ⟨some default,default,S₀⟩).stk H₁) := by + obtain ⟨k,b,hk,hb,he⟩:=StackCost.execution_time M A hA (initial (Λ:=Λ) (σ:=σ) S₀ H₀ h₀) H₀ h₀ n + have hb' := output hb H₁ ho + have hhalt : (MachineCost.run (TM1.step (TM2to1.tr M)) k (TM1.init (word S₀ H₀))).l=none := by + rw [he,hb'.1,hh] + rfl + have hout : (MachineCost.run (TM1.step (TM2to1.tr M)) k (TM1.init (word S₀ H₀))).Tape.right₀= + ListBlank.mk (word (MachineCost.run (TM2.step M) n ⟨some default,default,S₀⟩).stk H₁) := by + rw [he,hb'.2] + have htime : FixedAlphabetCompiler.cost enc dec (TM2to1.tr M) (TM2to1.trSupp M S)*k+2≤t := + (Nat.add_le_add_right (Nat.mul_le_mul_left _ hk) 2).trans ht + exact FixedAlphabetCompiler.compiled_words enc dec enc0 encdec (TM2to1.tr M) + (TM2to1.trSupp M S) (TM2to1.tr_supports M hs) (word S₀ H₀) + (word (MachineCost.run (TM2.step M) n ⟨some default,default,S₀⟩).stk H₁) + k t hhalt hout htime bits +end MatchingFPRAS.StackWords + +end OAI diff --git a/lean/OAI/Combinatorics/MatchingCount/Tapes/TapeTools.lean b/lean/OAI/Combinatorics/MatchingCount/Tapes/TapeTools.lean new file mode 100644 index 0000000000000000000000000000000000000000..9d79a1b9d79b7716444a14b5c073d27a78618a3c --- /dev/null +++ b/lean/OAI/Combinatorics/MatchingCount/Tapes/TapeTools.lean @@ -0,0 +1,126 @@ +import Mathlib +import OAI.Combinatorics.MatchingCount.Complexity.GuardMachineBase + +namespace OAI + +namespace MatchingFPRAS.LiteralTape +open Turing MachineCost + +variable {Γ Λ σ : Type} [Inhabited Γ] +@[simp] lemma mk₂_head (a : Γ) (L R : List Γ) : (Tape.mk₂ L (a::R)).head=a := rfl +@[simp] lemma mk₂_right (a : Γ) (L R : List Γ) : + (Tape.mk₂ L (a::R)).move .right=Tape.mk₂ (a::L) R := by + simp [Tape.mk₂,ListBlank.cons_mk] +@[simp] lemma mk₂_left (a : Γ) (L R : List Γ) : + (Tape.mk₂ (a::L) R).move .left=Tape.mk₂ L (a::R) := by + simp [Tape.mk₂,ListBlank.cons_mk] +@[simp] lemma mk₂_write (a b : Γ) (L R : List Γ) : + (Tape.mk₂ L (a::R)).write b=Tape.mk₂ L (b::R) := by + simp [Tape.mk₂,ListBlank.cons_mk] +lemma mk₂_left_nil (R : List Γ) : + (Tape.mk₂ [] R).move .left=Tape.mk₂ [] (default::R) := by + simp [Tape.mk₂,ListBlank.cons_mk,ListBlank.tail_mk,ListBlank.head_mk] +lemma mk₂_right_nil (L : List Γ) : + (Tape.mk₂ L []).move .right=Tape.mk₂ (default::L) [] := by + simp [Tape.mk₂,ListBlank.cons_mk,ListBlank.tail_mk,ListBlank.head_mk] +lemma mk₂_write_nil (L : List Γ) (a : Γ) : + (Tape.mk₂ L []).write a=Tape.mk₂ L [a] := by + simp [Tape.mk₂,ListBlank.cons_mk,ListBlank.tail_mk] +lemma blank_zero (n : ℕ) : (ListBlank.mk (List.replicate n (default : Γ)))=ListBlank.mk [] := by + induction n with + | zero => rfl + | succ n ih => rw [List.replicate_succ,←ListBlank.cons_mk,ih]; exact ListBlank.cons_head_tail (ListBlank.mk []) +lemma blank_append_zero (L : List Γ) (n : ℕ) : + ListBlank.mk (L++List.replicate n default)=ListBlank.mk L := by + induction L with + | nil => exact blank_zero n + | cons a L ih => rw [List.cons_append,←ListBlank.cons_mk,ih,ListBlank.cons_mk] + +def Exec (M : Λ→TM1.Stmt Γ Λ σ) (c d : TM1.Cfg Γ Λ σ) (t : ℕ) : Prop := + ∃ k,k≤t ∧ MachineCost.run (TM1.step M) k c=d +lemma Exec.refl (M : Λ→TM1.Stmt Γ Λ σ) (c : TM1.Cfg Γ Λ σ) : Exec M c c 0 := ⟨0,le_rfl,rfl⟩ +lemma Exec.step (M : Λ→TM1.Stmt Γ Λ σ) (l : Λ) (v : σ) (T : Tape Γ) : + Exec M ⟨some l,v,T⟩ (TM1.stepAux (M l) v T) 1 := ⟨1,le_rfl,rfl⟩ +lemma Exec.trans {M : Λ→TM1.Stmt Γ Λ σ} {c d e : TM1.Cfg Γ Λ σ} {s t : ℕ} + (h : Exec M c d s) (g : Exec M d e t) : Exec M c e (s+t) := by + obtain ⟨i,hi,he⟩:=h + obtain ⟨j,hj,hf⟩:=g + exact ⟨i+j,Nat.add_le_add hi hj,by rw [MachineCost.run_add,he,hf]⟩ +lemma Exec.mono {M : Λ→TM1.Stmt Γ Λ σ} {c d : TM1.Cfg Γ Λ σ} {s t : ℕ} + (h : Exec M c d s) (hst : s≤t) : Exec M c d t := + let ⟨k,hk,he⟩:=h; ⟨k,hk.trans hst,he⟩ + +def select [DecidableEq σ] (vs : List σ) (f : σ→TM1.Stmt Γ Λ σ) + (fallback : TM1.Stmt Γ Λ σ) : TM1.Stmt Γ Λ σ := + vs.foldr (fun v tail=>.branch (fun _ s=>decide (s=v)) (f v) tail) fallback +lemma select_step [DecidableEq σ] (vs : List σ) (f : σ→TM1.Stmt Γ Λ σ) + (fallback : TM1.Stmt Γ Λ σ) (v : σ) (hv : v∈vs) (T : Tape Γ) : + TM1.stepAux (select vs f fallback) v T=TM1.stepAux (f v) v T := by + induction vs with + | nil => simp at hv + | cons a as ih => + simp only [List.mem_cons] at hv + simp only [select,List.foldr_cons,TM1.stepAux] + by_cases h:v=a + · simp only [h,decide_true,Bool.cond_true] + · simp only [h,decide_false,Bool.cond_false] + exact ih (hv.resolve_left h) + +def writeLeft (xs : List Γ) (q : TM1.Stmt Γ Λ σ) : TM1.Stmt Γ Λ σ := + xs.foldr (fun a tail=>.write (fun _ _=>a) (.move .left tail)) q +lemma writeLeft_step (xs : List Γ) (q : TM1.Stmt Γ Λ σ) (v : σ) (R : List Γ) : + TM1.stepAux (writeLeft xs q) v (Tape.mk₂ [] (default::R))= + TM1.stepAux q v (Tape.mk₂ [] (default::xs.reverse++R)) := by + induction xs generalizing R with + | nil => rfl + | cons b bs ih => + simp only [writeLeft,List.foldr_cons,TM1.stepAux,mk₂_write,mk₂_left_nil] + rw [show List.foldr (fun a tail=>TM1.Stmt.write (fun _ _=>a) (.move .left tail)) q bs=writeLeft bs q from rfl,ih] + simp only [List.reverse_cons,List.cons_append,List.append_assoc,List.nil_append] + +def eraseToLeft (n : ℕ) (q : TM1.Stmt Γ Λ σ) : TM1.Stmt Γ Λ σ := + Nat.rec q (fun _ tail=>.move .left (.write (fun _ _=>default) tail)) n +lemma eraseToLeft_step (xs L R : List Γ) (q : TM1.Stmt Γ Λ σ) (v : σ) : + TM1.stepAux (eraseToLeft xs.length q) v (Tape.mk₂ (xs++L) R)= + TM1.stepAux q v (Tape.mk₂ L (List.replicate xs.length default++R)) := by + induction xs generalizing R with + | nil => rfl + | cons a xs ih => + simp only [List.length_cons,eraseToLeft,TM1.stepAux,List.cons_append,mk₂_left,mk₂_write] + rw [show Nat.rec q (fun _ tail=>TM1.Stmt.move .left (.write (fun _ _=>default) tail)) xs.length=eraseToLeft xs.length q from rfl,ih] + simp only [List.replicate_succ',List.append_assoc,List.singleton_append] + +variable {I : Type} [DecidableEq I] +def grab (is : List I) (q : TM1.Stmt Γ Λ (I→Γ)) : TM1.Stmt Γ Λ (I→Γ) := + is.foldr (fun i tail=>.load (fun a v=>Function.update v i a) (.move .right tail)) q +lemma grab_step (is : List I) (f v : I→Γ) (q : TM1.Stmt Γ Λ (I→Γ)) (L R : List Γ) : + TM1.stepAux (grab is q) v (Tape.mk₂ L (is.map f++R))= + TM1.stepAux q (is.foldl (fun v i=>Function.update v i (f i)) v) + (Tape.mk₂ ((is.map f).reverse++L) R) := by + induction is generalizing v L with + | nil => rfl + | cons i is ih => + simp only [grab,List.foldr_cons,List.map_cons,List.cons_append,TM1.stepAux,mk₂_head,mk₂_right,List.foldl_cons] + rw [show List.foldr (fun i tail=>TM1.Stmt.load (fun a v=>Function.update v i a) (.move .right tail)) q is=grab is q from rfl,ih] + simp only [List.reverse_cons,List.append_assoc,List.singleton_append] +omit [Inhabited Γ] in +lemma fold_updates (is : List I) (f v : I→Γ) (i : I) : + (is.foldl (fun v i=>Function.update v i (f i)) v) i=if i∈is then f i else v i := by + induction is generalizing v with + | nil => simp + | cons a is ih => + rw [List.foldl_cons,ih] + by_cases hi:i∈is <;> by_cases ha:i=a <;> simp [hi,ha] +lemma grab_fin (n : ℕ) (f v : Fin n→Γ) (q : TM1.Stmt Γ Λ (Fin n→Γ)) (L R : List Γ) : + TM1.stepAux (grab (List.finRange n) q) v (Tape.mk₂ L (List.ofFn f++R))= + TM1.stepAux q f (Tape.mk₂ ((List.ofFn f).reverse++L) R) := by + have he : (List.finRange n).map f=List.ofFn f := List.ofFn_eq_map.symm + rw [←he,grab_step] + have hf : (List.finRange n).foldl (fun v i=>Function.update v i (f i)) v=f := by + funext i + rw [fold_updates] + simp + rw [hf] +end MatchingFPRAS.LiteralTape + +end OAI diff --git a/lean/OAI/Combinatorics/MatchingCount/Tapes/TreeAddBits.lean b/lean/OAI/Combinatorics/MatchingCount/Tapes/TreeAddBits.lean new file mode 100644 index 0000000000000000000000000000000000000000..3932b46c986c9b9cb08694def60a8a972309dc36 --- /dev/null +++ b/lean/OAI/Combinatorics/MatchingCount/Tapes/TreeAddBits.lean @@ -0,0 +1,50 @@ +import Mathlib +import OAI.Combinatorics.MatchingCount.Arithmetic.TreeNumberOps + +namespace OAI + +namespace MatchingFPRAS.TreeArithmetic +open RegisterProc TreeData TreeMachine Turing + +variable {R : Type} [DecidableEq R] + +theorem add_bits_exec (E : Env R) (i j : R) (hij : i≠j) (A B : List Bool) + (hm : E i=bits A) (hn : E j=bits B) : + Exec (add i j hij) (encodeEnv E) (encodeEnv (putPair E i j (nat (StackAddition.value A+StackAddition.value B)) .nil)) + (9*(A.length+B.length)+20) := by + let S:=StackAddition.addDigits false A B + have h₁:=on_left TreeBits.decodeForward E i j hij (TreeData.encode (bits A)) (TreeData.encode (bits B)) A _ + (TreeBits.decodeForward_exec A []) + have h₂:=on_right TreeBits.decodeForward E i j hij A (TreeData.encode (bits B)) B _ + (TreeBits.decodeForward_exec B []) + have h₃:=on_pair BinaryArithmeticProc.add E i j hij A B S [] _ (BinaryArithmeticProc.add_exec A B) + have h₄:=on_left BinaryNormalize.program E i j hij S [] (BinaryNormalize.normalize S) _ + (BinaryNormalize.exec S []) + have h₅:=on_left TreeBits.encodeForward E i j hij (BinaryNormalize.normalize S) [] + (TreeData.encode (bits (BinaryNormalize.normalize S))) _ (TreeBits.encodeForward_exec _ []) + have h₆ : Exec (atom (.push (.inl j) (fun _=>false) .halt)) + (rawPair E i j (TreeData.encode (bits (BinaryNormalize.normalize S))) []) + (rawPair E i j (TreeData.encode (bits (BinaryNormalize.normalize S))) [false]) 1 := by + apply exec_atom + simp only [TM2.stepAux,rawPair_right] + congr 1 + simp [rawPair] + have hh:=h₁.seq (h₂.seq (h₃.seq (h₄.seq (h₅.seq h₆)))) + have hS : BinaryNormalize.normalize S=(StackAddition.value A+StackAddition.value B).bits := by + rw [BinaryNormalize.normalize_bits,StackAddition.addDigits_value,Bool.toNat_false,Nat.add_zero] + rw [hS] at hh + have hstart : rawPair E i j (TreeData.encode (bits A)) (TreeData.encode (bits B))=encodeEnv E := by + rw [←hm,←hn] + exact rawPair_same E i j + have hend : rawPair E i j (TreeData.encode (bits (StackAddition.value A+StackAddition.value B).bits)) [false]= + encodeEnv (putPair E i j (nat (StackAddition.value A+StackAddition.value B)) .nil) := rawPair_encode E i j (nat (StackAddition.value A+StackAddition.value B)) .nil + rw [hstart,hend] at hh + apply hh.mono + have hl:=StackAddition.addDigits_length A B false + have hl' := BinaryNormalize.normalize_length S + rw [hS] at hl' + dsimp only [S] at hl hl' ⊢ + omega +end MatchingFPRAS.TreeArithmetic + +end OAI diff --git a/lean/OAI/Combinatorics/MatchingCount/Tapes/TreeBits.lean b/lean/OAI/Combinatorics/MatchingCount/Tapes/TreeBits.lean new file mode 100644 index 0000000000000000000000000000000000000000..5d00a9f64b90c7ecddf5234f53e7e70b1e96ccb2 --- /dev/null +++ b/lean/OAI/Combinatorics/MatchingCount/Tapes/TreeBits.lean @@ -0,0 +1,80 @@ +import Mathlib +import OAI.Combinatorics.MatchingCount.Machines.TableLookup + +namespace OAI + +namespace MatchingFPRAS.TreeData + +def bits (A : List Bool) : Data := ofList (A.map bit) +@[simp] lemma bits_nil : bits []=.nil := rfl +@[simp] lemma bits_cons (b : Bool) (A : List Bool) : bits (b::A)=.cons (bit b) (bits A) := rfl +lemma bits_length (A : List Bool) : (encode (bits A)).length≤4*A.length+1 := by + induction A with + | nil => simp [encode] + | cons b A ih => cases b <;> simp only [bits_cons,encode,bit,Bool.false_eq_true,↓reduceIte, + List.length_cons,List.length_append,List.length_nil] <;> omega +end MatchingFPRAS.TreeData + +namespace MatchingFPRAS.TreeBits +open Turing MachineCost RegisterProc TreeData TreeTransfer + +def decodeProgram : Unit→TM2.Stmt (fun _ : Fin 3=>Bool) Unit (Option Bool) := fun _=> + .pop 0 (fun _ x=>x) (.branch (fun x=>x.getD false) + (.pop 0 (fun _ x=>x) (.branch (fun x=>x.getD false) + (.pop 0 (fun v _=>v) (.pop 0 (fun v _=>v) (.push 1 (fun _=>true) (.goto (fun _=>()))))) + (.push 1 (fun _=>false) (.goto (fun _=>()))))) + (.load (fun _=>none) .halt)) +lemma decode_nil (A B C : List Bool) (v : Option Bool) : + advance (TM2.step decodeProgram) (cfg (some ()) (false::A) B C v)=cfg none A B C none := by + simp [advance,TM2.step,decodeProgram,TM2.stepAux,cfg,update_zero] +lemma decode_cons (b : Bool) (bs A B C : List Bool) (v : Option Bool) : + advance (TM2.step decodeProgram) (cfg (some ()) (encode (bits (b::bs))++A) B C v)= + cfg (some ()) (encode (bits bs)++A) (b::B) C (some b) := by + cases b <;> simp [advance,TM2.step,decodeProgram,TM2.stepAux,cfg,update_zero,update_one,encode,bit] +lemma run_decode (bs A B C : List Bool) (v : Option Bool) : + MachineCost.run (TM2.step decodeProgram) (bs.length+1) + (cfg (some ()) (encode (bits bs)++A) B C v)=cfg none A (bs.reverse++B) C none := by + induction bs generalizing B v with + | nil => simpa only [bits_nil,encode,List.singleton_append,List.length_nil,List.reverse_nil,List.nil_append,Nat.zero_add,MachineCost.run] using decode_nil A B C v + | cons b bs ih => + rw [List.length_cons,Nat.add_right_comm,MachineCost.run,decode_cons,ih] + simp only [List.reverse_cons,List.append_assoc,List.singleton_append] +def decodeRaw : Proc (Fin 3) := ⟨Unit,decodeProgram⟩ +lemma decodeRaw_exec (bs A B C : List Bool) : + Exec decodeRaw ![encode (bits bs)++A,B,C] ![A,bs.reverse++B,C] (bs.length+1) := + ⟨_,le_rfl,run_decode bs A B C none⟩ + +def encodeProgram : Unit→TM2.Stmt (fun _ : Fin 3=>Bool) Unit (Option Bool) := fun _=> + .pop 0 (fun _ x=>x) (.branch Option.isNone (.load (fun _=>none) .halt) + (.branch (fun x=>x.getD false) + (.push 1 (fun _=>false) (.push 1 (fun _=>false) (.push 1 (fun _=>true) (.push 1 (fun _=>true) (.goto (fun _=>())))))) + (.push 1 (fun _=>false) (.push 1 (fun _=>true) (.goto (fun _=>())))))) +lemma encode_nil (B C : List Bool) (v : Option Bool) : + advance (TM2.step encodeProgram) (cfg (some ()) [] B C v)=cfg none [] B C none := by + simp [advance,TM2.step,encodeProgram,TM2.stepAux,cfg,update_zero] +lemma encode_cons (b : Bool) (bs C : List Bool) (x : Data) (v : Option Bool) : + advance (TM2.step encodeProgram) (cfg (some ()) (b::bs) (encode x) C v)= + cfg (some ()) bs (encode (.cons (bit b) x)) C (some b) := by + cases b <;> simp [advance,TM2.step,encodeProgram,TM2.stepAux,cfg,update_zero,update_one,encode,bit] +def prepend (bs : List Bool) (x : Data) : Data := bs.foldr (fun b x=>.cons (bit b) x) x +lemma prepend_append (A B : List Bool) (x : Data) : prepend (A++B) x=prepend A (prepend B x) := by + simp [prepend,List.foldr_append] +lemma run_encode (bs C : List Bool) (x : Data) (v : Option Bool) : + MachineCost.run (TM2.step encodeProgram) (bs.length+1) + (cfg (some ()) bs (encode x) C v)=cfg none [] (encode (prepend bs.reverse x)) C none := by + induction bs generalizing x v with + | nil => exact encode_nil (encode x) C v + | cons b bs ih => + rw [List.length_cons,Nat.add_right_comm,MachineCost.run,encode_cons,ih,List.reverse_cons,prepend_append] + rfl +lemma prepend_bits (bs : List Bool) : prepend bs .nil=bits bs := by + induction bs <;> simp_all [prepend,bits,ofList] +def encodeRaw : Proc (Fin 3) := ⟨Unit,encodeProgram⟩ +lemma encodeRaw_exec (bs C : List Bool) : + Exec encodeRaw ![bs.reverse,[false],C] ![[],encode (bits bs),C] (bs.length+1) := by + refine ⟨_,le_rfl,?_⟩ + have h:=run_encode bs.reverse C .nil none + simpa only [List.length_reverse,List.reverse_reverse,prepend_bits,encode,encodeRaw,cfg,stackData] using h +end MatchingFPRAS.TreeBits + +end OAI diff --git a/lean/OAI/Combinatorics/MatchingCount/Tapes/TreeEncodingInjective.lean b/lean/OAI/Combinatorics/MatchingCount/Tapes/TreeEncodingInjective.lean new file mode 100644 index 0000000000000000000000000000000000000000..d827de45bea336c19778e81bbd8c97c1e1f8eb0f --- /dev/null +++ b/lean/OAI/Combinatorics/MatchingCount/Tapes/TreeEncodingInjective.lean @@ -0,0 +1,84 @@ +import Mathlib +import OAI.Combinatorics.MatchingCount.Machines.TreeProgramUnique + +namespace OAI + +namespace MatchingFPRAS.TreeData +lemma encode_prefix_injective (a : Data) : ∀ b xs ys, + encode a++xs=encode b++ys → a=b ∧ xs=ys := by + induction a with + | nil=> + intro b xs ys h + cases b with + | nil=>simpa [encode] using h + | cons b c=>simp [encode] at h + | cons a c ia ic=> + intro b xs ys h + cases b with + | nil=>simp [encode] at h + | cons b d=> + simp only [encode,List.cons_append,List.cons.injEq,true_and,List.append_assoc] at h + obtain ⟨hab,he⟩:=ia b _ _ h + obtain ⟨hcd,hxy⟩:=ic d xs ys he + exact ⟨congrArg₂ Data.cons hab hcd,hxy⟩ +lemma encode_injective : Function.Injective encode := by + intro a b h + exact (encode_prefix_injective a b [] [] (by simpa using h)).1 +lemma ofList_injective : Function.Injective ofList := by + intro a + induction a with + | nil=>intro b h; cases b <;> simp_all [ofList] + | cons a as ih=> + intro b h + cases b with + | nil=>simp [ofList] at h + | cons b bs=> + obtain ⟨rfl,he⟩:=Data.cons.inj h + rw [ih he] +lemma bit_injective : Function.Injective bit := by + intro a b h + cases a <;> cases b <;> simp_all [bit] +lemma nat_injective : Function.Injective nat := by + intro a b h + have hh: a.bits=b.bits:=(List.map_injective_iff.mpr bit_injective) (ofList_injective h) + have := congrArg StackAddition.value hh + simpa only [StackAddition.value_bits] using this +end MatchingFPRAS.TreeData + +namespace MatchingFPRAS.TreePost +open TreeTyped TreeData TreeFunction TreeMachine RegisterProc + +variable {A B C D : Type} [Codec A] [Codec B] [Codec C] [Codec D] +lemma sameProgram_encode {f : A→B} {g : C→D} (F : Realizer f) (G : Realizer g) + (h : F.program=G.program) (a : A) (b : C) (hi : TreeTyped.encode a=TreeTyped.encode b) : + TreeTyped.encode (f a)=TreeTyped.encode (g b) := by + have hf:=F.correct a .nil + have hg:=G.correct b .nil + change Exec F.program (inputStacks a) (inputStacks (f a)) _ at hf + change Exec G.program (inputStacks b) (inputStacks (g b)) _ at hg + rw [h,stacks_eq_of_encode hi] at hf + exact TreeData.encode_injective (congrFun (hf.unique hg) (.inl 0)) +end MatchingFPRAS.TreePost + +namespace MatchingFPRAS.TreeTyped +open TreeData + +lemma list_encode_injective {A : Type} [Codec A] (hf : Function.Injective (encode (A:=A))) : + Function.Injective (encode (A:=List A)) := by + intro a b h + exact (List.map_injective_iff.mpr hf) (ofList_injective h) +lemma nat_encode_injective : Function.Injective (encode (A:=ℕ)) := TreeData.nat_injective +lemma finsetNat_encode_injective : Function.Injective (encode (A:=Finset ℕ)) := by + intro a b h + change encode (a.sort (·≤·))=encode (b.sort (·≤·)) at h + have hh:=list_encode_injective nat_encode_injective h + have := congrArg List.toFinset hh + simpa using this +lemma pair_encode_injective {A B : Type} [Codec A] [Codec B] + (ha : Function.Injective (encode (A:=A))) (hb : Function.Injective (encode (A:=B))) : + Function.Injective (encode (A:=A×B)) := by + intro a b h + exact Prod.ext (ha (TreeData.Data.cons.inj h).1) (hb (TreeData.Data.cons.inj h).2) +end MatchingFPRAS.TreeTyped + +end OAI diff --git a/lean/OAI/Combinatorics/MatchingCount/Tapes/TreeErasure.lean b/lean/OAI/Combinatorics/MatchingCount/Tapes/TreeErasure.lean new file mode 100644 index 0000000000000000000000000000000000000000..a22e7f84cf4ac48d4c4cfd12a8b0c4c693a6359a --- /dev/null +++ b/lean/OAI/Combinatorics/MatchingCount/Tapes/TreeErasure.lean @@ -0,0 +1,47 @@ +import Mathlib +import OAI.Combinatorics.MatchingCount.Sampling.TreeOptions +import OAI.Combinatorics.MatchingCount.Machines.TreeSum + +namespace OAI + +namespace MatchingFPRAS.TreeTyped +open TreeData + +variable {A B : Type} [Codec A] [Codec B] +lemma constantData_program (d : Data) : + (constantData (A:=A) d).program=(constantData (A:=B) d).program := by + induction d with + | nil=>rfl + | cons a b ih ihb=> + change TreeFunction.pair _ _ = TreeFunction.pair _ _ + rw [ih,ihb] +lemma constant_program (a : A) (b : B) (h : encode a=encode b) + {C D : Type} [Codec C] [Codec D] : + (constant (A:=C) a).program=(constant (A:=D) b).program := by + change (constantData (A:=C) (encode a)).program=(constantData (A:=D) (encode b)).program + rw [h] + exact constantData_program _ +lemma encode_empty_finset {E : Type} [Codec E] [LinearOrder E] : + encode (∅ : Finset E)=Data.nil := by + simp only [encode_finset,Finset.sort_empty,encode_list_nil] +lemma head_program (a : A) (b : B) (h : encode a=encode b) : + (head a).program=(head b).program := by + change RegisterStructured.select 0 (constant a).program first.program = + RegisterStructured.select 0 (constant b).program first.program + rw [constant_program a b h (C:=List A) (D:=List B)] + rfl +lemma getDFast_program (a : A) (b : B) (h : encode a=encode b) : + (getDFast a).program=(getDFast b).program := by + change RegisterProc.seq dropFast.program (head a).program = + RegisterProc.seq dropFast.program (head b).program + rw [head_program a b h] + rfl +lemma draw_program (a : A) (b : B) (h : encode a=encode b) : + (ExecutableOptions.drawRealizer a).program=(ExecutableOptions.drawRealizer b).program := by + unfold ExecutableOptions.drawRealizer + dsimp only [Realizer.congr, composition, pair] + rw [getDFast_program a b h] + rfl +end MatchingFPRAS.TreeTyped + +end OAI diff --git a/lean/OAI/Combinatorics/MatchingCount/Tapes/TreeErasurePrimitives.lean b/lean/OAI/Combinatorics/MatchingCount/Tapes/TreeErasurePrimitives.lean new file mode 100644 index 0000000000000000000000000000000000000000..10e397ad5c76a030488bc90e39dd26e67f2fcca9 --- /dev/null +++ b/lean/OAI/Combinatorics/MatchingCount/Tapes/TreeErasurePrimitives.lean @@ -0,0 +1,24 @@ +import Mathlib +import OAI.Combinatorics.MatchingCount.Tapes.TreeErasure + +namespace OAI + +namespace MatchingFPRAS.TreeTyped +variable {A B C D : Type} [Codec A] [Codec B] [Codec C] [Codec D] +lemma program_congr {f g : A→B} (F : Realizer f) (h : ∀ a,f a=g a) : (F.congr h).program=F.program := rfl +lemma program_recode {f : C→D} (F : Realizer f) (i : A→C) (g : A→B) (hi : ∀ a,encode (i a)=encode a) (ho : ∀ a,encode (f (i a))=encode (g a)) : (F.recode i g hi ho).program=F.program := rfl +lemma program_composition {f : A→B} {g : B→C} (F : Realizer f) (G : Realizer g) : + (composition F G).program=RegisterProc.seq F.program G.program := rfl +lemma program_pair {f : A→B} {g : A→C} (F : Realizer f) (G : Realizer g) : + (pair F G).program=TreeFunction.pair F.program G.program := rfl +lemma program_fold {f : A×B→B} (F : Realizer f) : + (fold F).program=RegisterControl.compile (Fold.code F.program) := rfl +lemma program_choose {f : A→Bool} {g h : A→B} (F : Realizer f) (G : Realizer g) (H : Realizer h) : + (choose F G H).program=RegisterProc.seq (TreeFunction.copy 0 1 (by decide)) + (RegisterProc.seq (TreeFunction.cons 1 2 (by decide)) (RegisterProc.seq F.program + (RegisterStructured.select 0 (RegisterProc.seq (TreeFunction.split 0 2 (by decide)) H.program) + (RegisterProc.seq (TreeFunction.split 0 2 (by decide)) G.program)))) := rfl +lemma program_constant (a : B) : (constant (A:=A) a).program=(constantData (A:=TreeData.Data) (encode a)).program := constantData_program _ +end MatchingFPRAS.TreeTyped + +end OAI diff --git a/lean/OAI/Combinatorics/MatchingCount/Tapes/TreeNumberedCodec.lean b/lean/OAI/Combinatorics/MatchingCount/Tapes/TreeNumberedCodec.lean new file mode 100644 index 0000000000000000000000000000000000000000..dca1be37789b15fb9ba295a523dcfb5e09813677 --- /dev/null +++ b/lean/OAI/Combinatorics/MatchingCount/Tapes/TreeNumberedCodec.lean @@ -0,0 +1,36 @@ +import Mathlib +import OAI.Combinatorics.MatchingCount.Machines.TreeSum +import OAI.Combinatorics.MatchingCount.Machines.TreeClosureReindex + +namespace OAI + +namespace MatchingFPRAS.TreeTyped.Numbered +variable {A : Type} [Fintype A] [LinearOrder A] +def index (a : A) : ℕ := ((UnitRefresh.orderedEnum A).symm a).val +instance (priority := 100) codec : Codec A := ⟨fun a=>encode (index a)⟩ +lemma index_injective : Function.Injective (index (A:=A)) := by + intro a b h + exact (UnitRefresh.orderedEnum A).symm.injective (Fin.ext h) +lemma index_le (a b : A) : index a ≤ index b ↔ a ≤ b := by + change (UnitRefresh.orderedEnum A).symm a ≤ (UnitRefresh.orderedEnum A).symm b ↔ _ + rw [←not_lt,←not_lt,←UnitRefresh.orderedEnum_lt] + simp + +def equal : Realizer (fun x : A×A=>decide (x.1=x.2)) := + natEqual.recode (fun x : A×A=>(index x.1,index x.2)) _ (fun _=>rfl) (fun x=>by + simp only [(index_injective (A:=A)).eq_iff]) +def lessEqual : Realizer (fun x : A×A=>decide (x.1≤x.2)) := + leNat.recode (fun x : A×A=>(index x.1,index x.2)) _ (fun _=>rfl) (fun x=>by + simp only [index_le]) +lemma polynomial_equal : PolynomialTime (equal (A:=A)) := + polynomial_recode _ _ _ _ polynomial_natEqual +lemma polynomial_lessEqual : PolynomialTime (lessEqual (A:=A)) := + polynomial_recode _ _ _ _ polynomial_leNat +@[simp] lemma equal_program : (equal (A:=A)).program=natEqual.program := rfl +@[simp] lemma lessEqual_program : (lessEqual (A:=A)).program=leNat.program := rfl + +lemma index_orderedEnum (i : Fin (Fintype.card A)) : + index (UnitRefresh.orderedEnum A i)=i.val := by simp [index] +end MatchingFPRAS.TreeTyped.Numbered + +end OAI diff --git a/lean/OAI/Combinatorics/MatchingCount/Tapes/TreeSparseCertificate.lean b/lean/OAI/Combinatorics/MatchingCount/Tapes/TreeSparseCertificate.lean new file mode 100644 index 0000000000000000000000000000000000000000..adfcf8f35fc60601561eac6b25197b029f4f7417 --- /dev/null +++ b/lean/OAI/Combinatorics/MatchingCount/Tapes/TreeSparseCertificate.lean @@ -0,0 +1,150 @@ +import Mathlib +import OAI.Combinatorics.MatchingCount.Tapes.TreeSparseStage +import OAI.Combinatorics.MatchingCount.Algorithm.TreeGeneratedCertificate +import OAI.Combinatorics.MatchingCount.Algorithm.TreeCertificate + +namespace OAI + +namespace MatchingFPRAS.ExecutableSource +open TreeTyped TreeFraction TreeTyped.Numbered ExecutableBottleneck ExecutableHierarchy ExecutableRefresh Enlargement RealGeometry NumericLadder +open ExecutableLadder UnitRefresh Replica.Ladder Transport NumericMarking ExecutableStatistics ExecutableScaling ExecutableAdaptive + +attribute [local instance] NumberedHierarchy.labelOrder +attribute [local instance] Transport.sym2Order Transport.bagEdgeOrder Transport.bagEdgeFintype +attribute [local instance] UnitRefresh.Computable.allowedDec Transport.prodOrder Transport.sumOrder + +abbrev CertificateMatrixInput := GraphData×Vector +def certificateCellData (x : CertificateMatrixInput) : CellData := ((x.1.2,(0,1)),x.2) +def certificateCellDataRealizer : Realizer certificateCellData := + (TreeTyped.pair (TreeTyped.pair first.snd (constant (0,1))) second).congr (fun _=>rfl) +lemma polynomial_certificateCellData : PolynomialTime certificateCellDataRealizer := by + unfold certificateCellDataRealizer; apply polynomial_congr + dsimp only [Realizer.fst,Realizer.snd] + tree_cost + +def certificateMatrix (x : CertificateMatrixInput) : Matrix := + x.1.1.map (fun i=>stageRow ((certificateCellData x,x.1.1),i)) +def certificateMatrixRealizer : Realizer certificateMatrix := + (composition (TreeTyped.pair (TreeTyped.pair certificateCellDataRealizer first.fst) first.fst) + (mapWith stageRowRealizer)).congr (fun _=>rfl) +lemma polynomial_certificateMatrix : PolynomialTime certificateMatrixRealizer := by + unfold certificateMatrixRealizer; apply polynomial_congr + have := polynomial_certificateCellData + have := polynomial_stageRow + dsimp only [Realizer.fst,Realizer.snd] + tree_cost + +lemma certificateMatrix_source {G : GraphInput} {j : ℕ} (s : FiniteTrial.ScaleState G j) : + certificateMatrix (graphRep G,vectorRep s.scale)=matrixRep s.certificateActivity := by + have hr (i j : Fin G.n) : (0:ℚ)≤ if (min i j,max i j)∈G.edges then 1 else 0 := by + split_ifs <;> norm_num + have hc (i j : Fin G.n) : + rawCell (certificateCellData (graphRep G,vectorRep s.scale),(i.val,j.val))= + TreeFraction.repr (if (min i j,max i j)∈G.edges then (1:ℚ) else 0) := by + unfold rawCell certificateCellData + dsimp only + simp only [edge_mem_graphRep] + split_ifs <;> rfl + unfold certificateMatrix stageRow matrixRep + change (List.range G.n).map _=List.ofFn _ + rw [ExecutableDP.map_range_ofFn] + congr 1 + funext i + change (List.range G.n).map _=List.ofFn _ + rw [ExecutableDP.map_range_ofFn] + congr 1 + funext j + unfold stageCell + rw [hc,show (certificateCellData (graphRep G,vectorRep s.scale)).2=vectorRep s.scale from rfl, + lookup_vectorRep s.scale i,lookup_vectorRep s.scale j,mul_repr (hr i j) (s.positive i).le, + mul_repr (mul_nonneg (hr i j) (s.positive i).le) (s.positive j).le] + rfl + +def sparseCertificateMatrixArg (x : SparseStageData) : CertificateMatrixInput := (x.1.1.1,x.2) +def sparseCertificateMatrixArgRealizer : Realizer sparseCertificateMatrixArg := + (TreeTyped.pair first.fst.fst second).congr (fun _=>rfl) +lemma polynomial_sparseCertificateMatrixArg : PolynomialTime sparseCertificateMatrixArgRealizer := by + unfold sparseCertificateMatrixArgRealizer; apply polynomial_congr + dsimp only [Realizer.fst,Realizer.snd] + tree_cost + +def sparseCertificateData (x : SparseStageData) : GeneratedStageData := + (sparseGeneratedInput x,certificateMatrix (sparseCertificateMatrixArg x)) +def sparseCertificateDataRealizer : Realizer sparseCertificateData := (TreeTyped.pair + sparseGeneratedInputRealizer (composition sparseCertificateMatrixArgRealizer certificateMatrixRealizer)).congr (fun _=>rfl) +lemma polynomial_sparseCertificateData : PolynomialTime sparseCertificateDataRealizer := polynomial_congr _ + (TreeTyped.polynomial_pair polynomial_sparseGeneratedInput + (polynomial_composition polynomial_sparseCertificateMatrixArg polynomial_certificateMatrix)) + +def sparseCertificate (x : SparseStageData×SampleBits) : Fraction := generatedCertificate (sparseCertificateData x.1,x.2) +def sparseCertificateRealizer : Realizer sparseCertificate := (composition + (TreeTyped.pair (composition first sparseCertificateDataRealizer) second) generatedCertificateRealizer).congr (fun _=>rfl) +lemma polynomial_sparseCertificate : PolynomialTime sparseCertificateRealizer := polynomial_congr _ + (polynomial_composition (TreeTyped.polynomial_pair + (polynomial_composition polynomial_first polynomial_sparseCertificateData) polynomial_second) polynomial_generatedCertificate) + +lemma sparseCertificateData_source {G : GraphInput} {j : ℕ} (s : FiniteTrial.ScaleState G j) + (K D : ℕ) (ft fq : List Bool) : + sparseCertificateData (((graphRep G,List.replicate j false), + (((List.replicate (2*K+2) false,List.replicate (2*K) false),D),(ft,fq))),vectorRep s.scale)= + ((((((matrixRep s.activity,List.replicate (2*K+2) false),List.range G.n),List.replicate (2*K) false),D),(ft,fq)), + matrixRep s.certificateActivity) := by + unfold sparseCertificateData sparseGeneratedInput sparseBagInput sparseCurrentMatrix currentActivityArg sparseCertificateMatrixArg + dsimp only + rw [stageMatrix_rep G _ s.scale (fun i=>(s.positive i).le),certificateMatrix_source] + simp only [List.length_replicate] + rfl + +lemma sparseCertificate_source {G : GraphInput} [Nontrivial (Fin G.n)] (hn : 2≤G.n) + (he : Even G.n) {j : ℕ} (s : FiniteTrial.ScaleState G j) (K D : ℕ) (hD : 0(List.ofFn (bits z).1,localBitsRep (bits z).2)), + keys.map (fun e=>(index e,List.ofFn (mb e)))))= + TreeFraction.repr (RationalSource.observableD s.activity s.certificateActivity K + (generatedSourceSample he s.activity s.activity_pos K D hD hu ft fq hq bits mb)) := by + dsimp only + unfold sparseCertificate + rw [sparseCertificateData_source] + have hnonneg : ∀ a b,0 ≤ s.certificateActivity a b := by + intro a b + have h:=s.toReal.certificateActivity_nonneg a b + rw [←s.certificateActivity_cast] at h + change (0:ℝ) ≤ (s.certificateActivity a b:ℝ) at h + exact_mod_cast h + exact generatedCertificate_source hn he s.activity s.certificateActivity s.activity_pos hnonneg K D hD hu ft fq hq bits mb + +lemma sparseCertificate_zero {G : GraphInput} [Nontrivial (Fin G.n)] (hn : 2≤G.n) + (he : Even G.n) {j : ℕ} (s : FiniteTrial.ScaleState G j) (hZ : Z G=0) + (K D : ℕ) (hD : 0(List.ofFn (bits z).1,localBitsRep (bits z).2)), + keys.map (fun e=>(index e,List.ofFn (mb e)))))=TreeFraction.repr 0 := by + dsimp only + rw [sparseCertificate_source hn he s K D hD hu ft fq hq bits mb, + generated_certificate_zero he s hZ K D hD hu ft fq hq bits mb] + +open TreePost Turing + +theorem sparseCertificate_post : ∃ p : Polynomial ℕ,∀ x : SparseStageData×SampleBits,∀ t : ℕ, + p.eval (packed x).length≤t → ∀ coins : Fin t→Bool, + (run (machine sparseCertificateRealizer.program) (packed x) coins).state=none ∧ + (run (machine sparseCertificateRealizer.program) (packed x) coins).tape.right₀= + ListBlank.mk (packed (sparseCertificate x)) := + polynomial_compiles sparseCertificateRealizer polynomial_sparseCertificate +end MatchingFPRAS.ExecutableSource + +end OAI diff --git a/lean/OAI/Combinatorics/MatchingCount/Tapes/TreeSparseComponents.lean b/lean/OAI/Combinatorics/MatchingCount/Tapes/TreeSparseComponents.lean new file mode 100644 index 0000000000000000000000000000000000000000..2bb622d63dead40aec707aeaa7ff9f53e4dc03c6 --- /dev/null +++ b/lean/OAI/Combinatorics/MatchingCount/Tapes/TreeSparseComponents.lean @@ -0,0 +1,130 @@ +import Mathlib +import OAI.Combinatorics.MatchingCount.Machines.TreeReachCorrect + +namespace OAI + +namespace MatchingFPRAS.TreeTyped.SparseProgram +open TreeTyped + +variable {A C : Type} [Codec A] [Codec C] [LinearOrder A] +attribute [local instance] Transport.Sparse.finsetOrder + +variable (p : C×(A×A) → Bool) +def adjacent (x : (C×Finset A)×(A×A)) : Bool := + decide (x.2.1≠x.2.2) && (decide (x.2.1∈x.1.2) && (decide (x.2.2∈x.1.2) && p (x.1.1,x.2))) +variable {p} +def adjacentRealizer (P : Realizer p) (E : Realizer (fun x : A×A=>decide (x.1=x.2))) : + Realizer (adjacent p) := + (composition (pair (composition (composition second E) boolNot) + (composition (pair (composition (pair second.fst first.snd) (finsetMember E)) + (composition (pair (composition (pair second.snd first.snd) (finsetMember E)) + (composition (pair first.fst second) P)) boolAnd)) boolAnd)) boolAnd).congr (by + intro x + change (!decide (x.2.1=x.2.2) && _) = _ + apply Bool.eq_iff_iff.mpr + simp only [adjacent, Function.comp_apply, Bool.and_eq_true, + Bool.not_eq_true', decide_eq_false_iff_not, decide_eq_true_eq]) +lemma polynomial_adjacent {P : Realizer p} {E : Realizer (fun x : A×A=>decide (x.1=x.2))} + (hP : PolynomialTime P) (hE : PolynomialTime E) : PolynomialTime (adjacentRealizer P E) := by + unfold adjacentRealizer Realizer.fst Realizer.snd + tree_poly + +abbrev ComponentInput (C A : Type) := ((C×Finset A)×Finset A)×A + +def component (x : ComponentInput C A) : Finset A := + x.1.2 ∩ FiniteReach.reach (adjacent p) (((x.1.1.1,x.1.2),x.1.1.2),{x.2}) +def componentRealizer (P : Realizer p) + (E : Realizer (fun x : A×A=>decide (x.1=x.2))) + (R : Realizer (fun x : A×A=>decide (x.1≤x.2))) : Realizer (component (p:=p)) := + composition (pair first.snd (composition + (pair (pair (pair first.fst.fst first.snd) first.fst.snd) (composition second finsetSingleton)) + (FiniteReach.reachRealizer (adjacentRealizer P E) E R))) (finsetInter E) +lemma polynomial_component {P : Realizer p} + {E : Realizer (fun x : A×A=>decide (x.1=x.2))} + {R : Realizer (fun x : A×A=>decide (x.1≤x.2))} + (hP : PolynomialTime P) (hE : PolynomialTime E) (hR : PolynomialTime R) : + PolynomialTime (componentRealizer P E R) := by + unfold componentRealizer + have hh:=FiniteReach.polynomial_reach (polynomial_adjacent hP hE) hE hR + apply polynomial_composition _ (polynomial_finsetInter hE) + apply polynomial_pair (polynomial_snd polynomial_first) + apply polynomial_composition _ hh + unfold Realizer.fst Realizer.snd + tree_poly + +def orderedSetEqual (E : Realizer (fun x : A×A=>decide (x.1=x.2))) : + Realizer (fun x : Finset A×Finset A=>@decide (x.1=x.2) (LinearOrder.toDecidableEq x.1 x.2)) := + (finsetEqual E).congr (by intro x; apply Bool.eq_iff_iff.mpr; simp only [decide_eq_true_eq]) +lemma polynomial_orderedSetEqual {E : Realizer (fun x : A×A=>decide (x.1=x.2))} + (hE : PolynomialTime E) : PolynomialTime (orderedSetEqual E) := + polynomial_congr _ (polynomial_finsetEqual hE) + +def allComponents (x : (C×Finset A)×Finset A) : Finset (Finset A) := + x.2.image (fun a=>component (p:=p) (x,a)) +def allComponentsRealizer (P : Realizer p) + (E : Realizer (fun x : A×A=>decide (x.1=x.2))) + (R : Realizer (fun x : A×A=>decide (x.1≤x.2))) : Realizer (allComponents (p:=p)) := + (composition (pair identity second) (finsetImageWith (componentRealizer P E R) (orderedSetEqual E) (colexLe E R))).congr (by + intro x; ext a; simp only [Function.comp_apply,id_eq,allComponents,Finset.mem_image]) +lemma polynomial_allComponents {P : Realizer p} + {E : Realizer (fun x : A×A=>decide (x.1=x.2))} + {R : Realizer (fun x : A×A=>decide (x.1≤x.2))} + (hP : PolynomialTime P) (hE : PolynomialTime E) (hR : PolynomialTime R) : + PolynomialTime (allComponentsRealizer P E R) := by + unfold allComponentsRealizer + apply polynomial_congr + apply polynomial_composition (polynomial_pair polynomial_identity polynomial_second) + exact polynomial_finsetImageWith (polynomial_component hP hE hR) (polynomial_orderedSetEqual hE) (polynomial_colexLe hE hR) + +def discrepancies (x : (C×Finset A)×(Finset A×Finset A)) : Finset (Finset A) := + (allComponents (p:=p) (x.1,x.2.1∪x.2.2)).filter (fun s=>¬s⊆x.2.1∩x.2.2) +def discrepanciesRealizer (P : Realizer p) + (E : Realizer (fun x : A×A=>decide (x.1=x.2))) + (R : Realizer (fun x : A×A=>decide (x.1≤x.2))) : Realizer (discrepancies (p:=p)) := + (composition (pair (composition second (finsetInter E)) + (composition (pair first (composition second (finsetUnion E R))) (allComponentsRealizer P E R))) + (finsetFilterWith (composition (composition (pair second first) (finsetSubset E)) boolNot))).congr (by + intro x + simp only [discrepancies,Function.comp_apply,Bool.not_eq_true',decide_eq_false_iff_not]) +lemma polynomial_discrepancies {P : Realizer p} + {E : Realizer (fun x : A×A=>decide (x.1=x.2))} + {R : Realizer (fun x : A×A=>decide (x.1≤x.2))} + (hP : PolynomialTime P) (hE : PolynomialTime E) (hR : PolynomialTime R) : + PolynomialTime (discrepanciesRealizer P E R) := by + unfold discrepanciesRealizer + have hh:=polynomial_allComponents hP hE hR + apply polynomial_congr + apply polynomial_composition + · apply polynomial_pair + · tree_poly + · apply polynomial_composition _ hh + tree_poly + · tree_poly + +omit [Codec A] [Codec C] +variable [Fintype A] {V : Type} [Fintype V] [DecidableEq V] +variable (ends : A → Sym2 V) (c : C) +variable (hp : ∀ a b,p (c,(a,b))=decide (∃ v,v∈ends a ∧ v∈ends b)) +include hp +omit [Fintype A] in +lemma adjacent_eq (U : Finset A) (a b : A) : + adjacent p ((c,U),(a,b))=decide ((Transport.overlayLineGraph (fun e v=>v∈ends e) U).Adj a b) := by + apply Bool.eq_iff_iff.mpr + simp only [adjacent,Bool.and_eq_true,decide_eq_true_eq,hp] + rfl +lemma component_eq (U : Finset A) (a : A) : + component (p:=p) (((c,Finset.univ),U),a)=Transport.Sparse.component ends U a := by + unfold component Transport.Sparse.component + rw [FiniteReach.reach_closure _ (c,U) (adjacent_eq ends c hp U)] +lemma allComponents_eq (U : Finset A) : + allComponents (p:=p) ((c,Finset.univ),U)=Transport.Sparse.allComponents ends U := by + unfold allComponents Transport.Sparse.allComponents + exact Finset.image_congr (fun a _=>component_eq ends c hp U a) +lemma discrepancies_eq (a b : Transport.PM (fun e v=>v∈ends e)) : + discrepancies (p:=p) ((c,Finset.univ),(a.val,b.val))=Transport.Sparse.discrepancies ends a b := by + unfold discrepancies Transport.Sparse.discrepancies + dsimp only + rw [allComponents_eq ends c hp] +end MatchingFPRAS.TreeTyped.SparseProgram + +end OAI diff --git a/lean/OAI/Combinatorics/MatchingCount/Tapes/TreeSparseNeighbors.lean b/lean/OAI/Combinatorics/MatchingCount/Tapes/TreeSparseNeighbors.lean new file mode 100644 index 0000000000000000000000000000000000000000..c54164e7c09ce431afe1d195c0fca8eb92e02e40 --- /dev/null +++ b/lean/OAI/Combinatorics/MatchingCount/Tapes/TreeSparseNeighbors.lean @@ -0,0 +1,127 @@ +import Mathlib +import OAI.Combinatorics.MatchingCount.Sampling.TreeOptionsMaps +import OAI.Combinatorics.MatchingCount.Machines.TreeCertify +import OAI.Combinatorics.MatchingCount.Machines.TreeColorRaw +import OAI.Combinatorics.MatchingCount.Graphs.TreeSwitchRaw + +namespace OAI + +namespace MatchingFPRAS.TreeTyped.SparseProgram +open TreeTyped ExecutableOptions + +variable {E V C : Type} [Codec E] [Codec V] [Codec C] [LinearOrder E] [LinearOrder V] +attribute [local instance] Transport.Sparse.finsetOrder +abbrev TableInput (C E V : Type) := (C×(Finset V×Finset E))×Finset E + +def colorTable (p : C×(E×V)→Bool) (q : C×(E×E)→Bool) (x : TableInput C E V) : Options (Finset E) := + neighbors ((x.2,(certify p ((x.1.1,x.1.2.1),colorRaw q ((x.1.1,x.1.2.2),x.2))).erase x.2),x.1.2.1.card) +def colorTableRealizer {p : C×(E×V)→Bool} {q : C×(E×E)→Bool} + (P : Realizer p) (Q : Realizer q) + (Eq : Realizer (fun x : E×E=>decide (x.1=x.2))) + (Le : Realizer (fun x : E×E=>decide (x.1≤x.2))) : Realizer (colorTable p q) := + (composition (pair (pair second (composition (pair second (composition + (pair (pair first.fst first.snd.fst) (composition (pair (pair first.fst first.snd.snd) second) + (colorRawRealizer Q Eq Le))) (certifyRealizer P))) (finsetErase (orderedSetEqual Eq)))) + (composition first.snd.fst finsetCard)) neighborsRealizer).congr (by + intro x + apply congrArg neighbors + dsimp only [Function.comp_apply] + congr 2 + ext b + simp only [Finset.mem_erase]) +lemma polynomial_colorTable {p : C×(E×V)→Bool} {q : C×(E×E)→Bool} + {P : Realizer p} {Q : Realizer q} + {Eq : Realizer (fun x : E×E=>decide (x.1=x.2))} + {Le : Realizer (fun x : E×E=>decide (x.1≤x.2))} + (hP : PolynomialTime P) (hQ : PolynomialTime Q) (hE : PolynomialTime Eq) (hL : PolynomialTime Le) : + PolynomialTime (colorTableRealizer P Q Eq Le) := by + unfold colorTableRealizer Realizer.fst Realizer.snd + apply polynomial_congr + have := polynomial_colorRaw hQ hE hL + have := polynomial_certify hP + have := polynomial_orderedSetEqual hE + have := ExecutableOptions.polynomial_neighbors (A:=Finset E) + tree_cost + +def degree (n : ℕ) : ℕ := 8*(n/2).choose 2 +def degreeRealizer : Realizer degree := by + let half : Realizer (fun n : ℕ=>n/2) := composition (pair identity (constant 2)) quotient + let chooseTwo : Realizer (fun n : ℕ=>n.choose 2) := + (composition (pair (composition (pair identity (composition (pair identity (constant 1)) subtract)) multiply) + (constant 2)) quotient).congr (fun n=>Nat.choose_two_right n |>.symm) + exact (composition (pair (constant 8) (composition half chooseTwo)) multiply).congr (fun _=>rfl) +lemma polynomial_degree : PolynomialTime degreeRealizer := by + unfold degreeRealizer + dsimp only + apply polynomial_congr + have := polynomial_quotient + tree_cost + +def switchTable (p : C×(E×V)→Bool) (q : C×(E×(V×V))→Bool) (x : TableInput C E V) : Options (Finset E) := + neighbors ((x.2,(certify p ((x.1.1,x.1.2.1),switchRaw q x)).erase x.2),degree x.1.2.1.card) +def switchTableRealizer {p : C×(E×V)→Bool} {q : C×(E×(V×V))→Bool} + (P : Realizer p) (Q : Realizer q) + (Eq : Realizer (fun x : E×E=>decide (x.1=x.2))) + (Le : Realizer (fun x : E×E=>decide (x.1≤x.2))) + (EqV : Realizer (fun x : V×V=>decide (x.1=x.2))) + (LeV : Realizer (fun x : V×V=>decide (x.1≤x.2))) : Realizer (switchTable p q) := + (composition (pair (pair second (composition (pair second (composition + (pair (pair first.fst first.snd.fst) (switchRawRealizer Q Eq Le EqV LeV)) (certifyRealizer P))) + (finsetErase (orderedSetEqual Eq)))) + (composition (composition first.snd.fst finsetCard) degreeRealizer)) neighborsRealizer).congr (by + intro x + apply congrArg neighbors + dsimp only [Function.comp_apply] + congr 2 + ext b + simp only [Finset.mem_erase]) +lemma polynomial_switchTable {p : C×(E×V)→Bool} {q : C×(E×(V×V))→Bool} + {P : Realizer p} {Q : Realizer q} + {Eq : Realizer (fun x : E×E=>decide (x.1=x.2))} + {Le : Realizer (fun x : E×E=>decide (x.1≤x.2))} + {EqV : Realizer (fun x : V×V=>decide (x.1=x.2))} + {LeV : Realizer (fun x : V×V=>decide (x.1≤x.2))} + (hP : PolynomialTime P) (hQ : PolynomialTime Q) (hE : PolynomialTime Eq) (hL : PolynomialTime Le) + (hV : PolynomialTime EqV) (hlV : PolynomialTime LeV) : + PolynomialTime (switchTableRealizer P Q Eq Le EqV LeV) := by + unfold switchTableRealizer Realizer.fst Realizer.snd + apply polynomial_congr + have := polynomial_switchRaw hQ hE hL hV hlV + have := polynomial_certify hP + have := polynomial_orderedSetEqual hE + have := polynomial_degree + have := ExecutableOptions.polynomial_neighbors (A:=Finset E) + tree_cost + +variable [Fintype E] [Fintype V] (ends : E→Sym2 V) +attribute [local instance] Transport.Sparse.pmOrder +variable (hloop : ∀ e,¬(ends e).IsDiag) (hpar : ∀ e,(Finset.univ.filter (fun f=>ends f=ends e)).card≤2) +omit [Codec E] [Codec V] [Codec C] in +lemma colorTable_eq (p : C×(E×V)→Bool) (q : C×(E×E)→Bool) (c : C) + (hp : ∀ e v,p (c,(e,v))=decide (v∈ends e)) (hq : ∀ e f,q (c,(e,f))=decide (ends e=ends f)) + (a : Transport.PM (fun e v=>v∈ends e)) : + colorTable p q ((c,(Finset.univ,Finset.univ)),a.val)=repr Subtype.val (Transport.Sparse.colorTable ends hloop hpar a) := by + unfold colorTable + have hraw : colorRaw q ((c,Finset.univ),a.val)=Transport.Sparse.colorRaw ends a.val := by + simp only [colorRaw,Transport.Sparse.colorRaw,hq,decide_eq_true_eq] + rw [hraw,certify_eq ends p c hp,Finset.card_univ] + have he:=Finset.map_erase (pmEmbedding ends).toEmbedding (Transport.Sparse.colors ends a) a + have hn:=neighbors_repr_map (pmEmbedding ends) a ((Transport.Sparse.colors ends a).erase a) + (Fintype.card V) (Transport.Sparse.color_degree ends hloop hpar a) + rw [he] at hn + exact hn +omit [Codec E] [Codec V] [Codec C] in +lemma switchTable_eq (p : C×(E×V)→Bool) (q : C×(E×(V×V))→Bool) (c : C) + (hp : ∀ e v,p (c,(e,v))=decide (v∈ends e)) (hq : ∀ e v w,q (c,(e,(v,w)))=decide (ends e=s(v,w))) + (a : Transport.PM (fun e v=>v∈ends e)) : + switchTable p q ((c,(Finset.univ,Finset.univ)),a.val)=repr Subtype.val (Transport.Sparse.switchTable ends hloop hpar a) := by + unfold switchTable + rw [switchRaw_eq ends q c hq,certify_eq ends p c hp,Finset.card_univ] + have he:=Finset.map_erase (pmEmbedding ends).toEmbedding (Transport.Sparse.switches ends a) a + have hn:=neighbors_repr_map (pmEmbedding ends) a ((Transport.Sparse.switches ends a).erase a) + (degree (Fintype.card V)) (Transport.Sparse.switch_degree ends hloop hpar a) + rw [he] at hn + exact hn +end MatchingFPRAS.TreeTyped.SparseProgram + +end OAI diff --git a/lean/OAI/Combinatorics/MatchingCount/Tapes/TreeSparseStage.lean b/lean/OAI/Combinatorics/MatchingCount/Tapes/TreeSparseStage.lean new file mode 100644 index 0000000000000000000000000000000000000000..8ee2991876aac9664662d3070df3a7e627a1551c --- /dev/null +++ b/lean/OAI/Combinatorics/MatchingCount/Tapes/TreeSparseStage.lean @@ -0,0 +1,127 @@ +import Mathlib +import OAI.Combinatorics.MatchingCount.Algorithm.TreeGeneratedUpdate +import OAI.Combinatorics.MatchingCount.Algorithm.TreeStageActivity + +namespace OAI + +namespace MatchingFPRAS.ExecutableSource +open TreeTyped TreeFraction TreeTyped.Numbered ExecutableBottleneck ExecutableHierarchy ExecutableRefresh Enlargement RealGeometry NumericLadder +open ExecutableLadder UnitRefresh Replica.Ladder Transport NumericMarking ExecutableStatistics ExecutableScaling ExecutableAdaptive + +attribute [local instance] NumberedHierarchy.labelOrder +attribute [local instance] Transport.sym2Order Transport.bagEdgeOrder Transport.bagEdgeFintype +attribute [local instance] UnitRefresh.Computable.allowedDec Transport.prodOrder Transport.sumOrder + +abbrev StageControls := ((List Bool×List Bool)×ℕ)×(List Bool×List Bool) +abbrev SparseStageData := ((GraphData×List Bool)×StageControls)×Vector +abbrev SparseStageInput := SparseStageData×List SampleBits + +def currentActivityArg (x : SparseStageData) : ActivityData := (x.1.1,x.2) +def currentActivityArgRealizer : Realizer currentActivityArg := + (TreeTyped.pair (first (A:=(GraphData×List Bool)×StageControls) (B:=Vector)).fst second).congr (fun _=>rfl) +lemma polynomial_currentActivityArg : PolynomialTime currentActivityArgRealizer := + polynomial_congr _ (TreeTyped.polynomial_pair (polynomial_fst polynomial_first) polynomial_second) +def sparseCurrentMatrix (x : SparseStageData) : Matrix := stageMatrix (currentActivityArg x) +def sparseCurrentMatrixRealizer : Realizer sparseCurrentMatrix := + (composition currentActivityArgRealizer stageMatrixRealizer).congr (fun _=>rfl) +lemma polynomial_sparseCurrentMatrix : PolynomialTime sparseCurrentMatrixRealizer := + polynomial_congr _ (polynomial_composition polynomial_currentActivityArg polynomial_stageMatrix) + +def nextActivityArg (x : SparseStageData) : ActivityData := ((x.1.1.1,false::x.1.1.2),x.2) +def nextActivityArgRealizer : Realizer nextActivityArg := (TreeTyped.pair + (TreeTyped.pair first.fst.fst (composition (TreeTyped.pair (constant false) first.fst.snd) listCons)) second).congr (fun _=>rfl) +lemma polynomial_nextActivityArg : PolynomialTime nextActivityArgRealizer := by + unfold nextActivityArgRealizer + apply polynomial_congr + dsimp only [Realizer.fst, Realizer.snd] + tree_cost + +def sparseNextMatrix (x : SparseStageData) : Matrix := stageMatrix (nextActivityArg x) +def sparseNextMatrixRealizer : Realizer sparseNextMatrix := + (composition nextActivityArgRealizer stageMatrixRealizer).congr (fun _=>rfl) +lemma polynomial_sparseNextMatrix : PolynomialTime sparseNextMatrixRealizer := + polynomial_congr _ (polynomial_composition polynomial_nextActivityArg polynomial_stageMatrix) + +def sparseBagInput (x : SparseStageData) : BagBuildInput := + (((sparseCurrentMatrix x,x.1.2.1.1.1),x.1.1.1.1),x.1.2.1.1.2) +def sparseBagInputRealizer : Realizer sparseBagInput := (TreeTyped.pair + (TreeTyped.pair (TreeTyped.pair sparseCurrentMatrixRealizer first.snd.fst.fst.fst) first.fst.fst.fst) + first.snd.fst.fst.snd).congr (fun _=>rfl) +lemma polynomial_sparseBagInput : PolynomialTime sparseBagInputRealizer := by + unfold sparseBagInputRealizer + apply polynomial_congr + dsimp only [Realizer.fst, Realizer.snd] + have := polynomial_sparseCurrentMatrix + tree_cost + +def sparseGeneratedInput (x : SparseStageData) : GeneratedInput := + ((sparseBagInput x,x.1.2.1.2),x.1.2.2) +def sparseGeneratedInputRealizer : Realizer sparseGeneratedInput := (TreeTyped.pair + (TreeTyped.pair sparseBagInputRealizer first.snd.fst.snd) first.snd.snd).congr (fun _=>rfl) +lemma polynomial_sparseGeneratedInput : PolynomialTime sparseGeneratedInputRealizer := by + unfold sparseGeneratedInputRealizer + apply polynomial_congr + dsimp only [Realizer.fst, Realizer.snd] + have := polynomial_sparseBagInput + tree_cost + +def sparseUpdateData (x : SparseStageData) : GeneratedUpdateData := + ((sparseGeneratedInput x,sparseNextMatrix x),x.2) +def sparseUpdateDataRealizer : Realizer sparseUpdateData := + (TreeTyped.pair (TreeTyped.pair sparseGeneratedInputRealizer sparseNextMatrixRealizer) second).congr (fun _=>rfl) +lemma polynomial_sparseUpdateData : PolynomialTime sparseUpdateDataRealizer := + polynomial_congr _ (TreeTyped.polynomial_pair (TreeTyped.polynomial_pair polynomial_sparseGeneratedInput polynomial_sparseNextMatrix) + polynomial_second) + +def sparseStage (x : SparseStageInput) : Fraction×Vector := generatedUpdate (sparseUpdateData x.1,x.2) +def sparseStageRealizer : Realizer sparseStage := (composition + (TreeTyped.pair (composition (first (A:=SparseStageData) (B:=List SampleBits)) sparseUpdateDataRealizer) second) + generatedUpdateRealizer).congr (fun _=>rfl) +lemma polynomial_sparseStage : PolynomialTime sparseStageRealizer := polynomial_congr _ + (polynomial_composition (TreeTyped.polynomial_pair (polynomial_composition polynomial_first polynomial_sparseUpdateData) + polynomial_second) polynomial_generatedUpdate) + +lemma sparseUpdateData_source {G : GraphInput} {j : ℕ} (s : FiniteTrial.ScaleState G j) + (K D : ℕ) (ft fq : List Bool) : + sparseUpdateData (((graphRep G,List.replicate j false), + (((List.replicate (2*K+2) false,List.replicate (2*K) false),D),(ft,fq))),vectorRep s.scale)= + (((((((matrixRep s.activity,List.replicate (2*K+2) false),List.range G.n),List.replicate (2*K) false),D),(ft,fq)), + matrixRep s.nextActivity),vectorRep s.scale) := by + unfold sparseUpdateData sparseGeneratedInput sparseBagInput sparseCurrentMatrix sparseNextMatrix currentActivityArg nextActivityArg + dsimp only + rw [stageMatrix_rep G _ s.scale (fun i=>(s.positive i).le),stageMatrix_rep G _ s.scale (fun i=>(s.positive i).le)] + simp only [List.length_replicate,List.length_cons] + rfl + +lemma sparseStage_source {G : GraphInput} [Nontrivial (Fin G.n)] (hn : 2≤G.n) + (he : Even G.n) {j : ℕ} (s : FiniteTrial.ScaleState G j) (K : ℕ) + (hD : 0generatedSourceSample he s.activity s.activity_pos K + (FiniteTrial.sourceD (G:=G) K) hD hu ft fq hq (bits i) (mb i) + let keys := List.ofFn (orderedEnum (BagEdge (RationalSource.bags s.activity K))) + sparseStage + ((((graphRep G,List.replicate j false), + (((List.replicate (2*K+2) false,List.replicate (2*K) false),FiniteTrial.sourceD (G:=G) K),(ft,fq))),vectorRep s.scale), + List.ofFn (fun i=>(List.ofFn (fun z=>(List.ofFn (bits i z).1,localBitsRep (bits i z).2)), + keys.map (fun e=>(index e,List.ofFn (mb i e))))))= + (TreeFraction.repr (s.ratioEstimate x),vectorRep (s.update hn x).scale) := by + dsimp only + unfold sparseStage + rw [sparseUpdateData_source] + exact generatedUpdate_source hn he s K hD hu ft fq hq bits mb + +open TreePost Turing + +theorem sparseStage_post : ∃ p : Polynomial ℕ,∀ x : SparseStageInput,∀ t : ℕ, + p.eval (packed x).length≤t → ∀ coins : Fin t→Bool, + (run (machine sparseStageRealizer.program) (packed x) coins).state=none ∧ + (run (machine sparseStageRealizer.program) (packed x) coins).tape.right₀= + ListBlank.mk (packed (sparseStage x)) := + polynomial_compiles sparseStageRealizer polynomial_sparseStage +end MatchingFPRAS.ExecutableSource + +end OAI diff --git a/lean/OAI/Combinatorics/MatchingCount/Tapes/WordOps.lean b/lean/OAI/Combinatorics/MatchingCount/Tapes/WordOps.lean new file mode 100644 index 0000000000000000000000000000000000000000..a3088d8388ac87fd118be06a1a52d863b41e7eb3 --- /dev/null +++ b/lean/OAI/Combinatorics/MatchingCount/Tapes/WordOps.lean @@ -0,0 +1,45 @@ +import Mathlib +import OAI.Combinatorics.MatchingCount.Machines.TreeTransfer + +namespace OAI + +namespace MatchingFPRAS.WordOps +open Turing MachineCost TreeTransfer + +def duplicate : Unit → TM2.Stmt (fun _ : Fin 3=>Bool) Unit Store := fun _=> + .pop 0 (fun _ b=>b) (.branch Option.isNone (.load (fun _=>none) .halt) + (.push 1 (fun v=>v.getD false) (.push 2 (fun v=>v.getD false) (.goto (fun _=>()))))) +lemma duplicate_nil (B D : List Bool) (v : Store) : + advance (TM2.step duplicate) (cfg (some ()) [] B D v)=cfg none [] B D none := by + simp [advance,TM2.step,duplicate,TM2.stepAux,cfg,update_zero] +lemma duplicate_cons (b : Bool) (A B D : List Bool) (v : Store) : + advance (TM2.step duplicate) (cfg (some ()) (b::A) B D v)= + cfg (some ()) A (b::B) (b::D) (some b) := by + simp [advance,TM2.step,duplicate,TM2.stepAux,cfg,update_zero,update_one,update_two] +theorem run_duplicate (A B D : List Bool) (v : Store) : + MachineCost.run (TM2.step duplicate) (A.length+1) (cfg (some ()) A B D v)= + cfg none [] (A.reverse++B) (A.reverse++D) none := by + induction A generalizing B D v with + | nil => simpa only [List.length_nil,Nat.zero_add,List.reverse_nil,List.nil_append,MachineCost.run] using duplicate_nil B D v + | cons b A ih => + rw [List.length_cons,Nat.add_right_comm,MachineCost.run,duplicate_cons,ih] + simp only [List.reverse_cons,List.append_assoc,List.singleton_append] +lemma duplicate_accesses (l : Unit) : StackCost.accesses (duplicate l)≤3 := by cases l; decide + +def clear : Unit → TM2.Stmt (fun _ : Fin 3=>Bool) Unit Store := fun _=> + .pop 0 (fun _ b=>b) (.branch Option.isNone (.load (fun _=>none) .halt) (.goto (fun _=>()))) +lemma clear_nil (B D : List Bool) (v : Store) : + advance (TM2.step clear) (cfg (some ()) [] B D v)=cfg none [] B D none := by + simp [advance,TM2.step,clear,TM2.stepAux,cfg,update_zero] +lemma clear_cons (b : Bool) (A B D : List Bool) (v : Store) : + advance (TM2.step clear) (cfg (some ()) (b::A) B D v)=cfg (some ()) A B D (some b) := by + simp [advance,TM2.step,clear,TM2.stepAux,cfg,update_zero] +theorem run_clear (A B D : List Bool) (v : Store) : + MachineCost.run (TM2.step clear) (A.length+1) (cfg (some ()) A B D v)=cfg none [] B D none := by + induction A generalizing v with + | nil => exact clear_nil B D v + | cons b A ih => rw [List.length_cons,Nat.add_right_comm,MachineCost.run,clear_cons,ih] +lemma clear_accesses (l : Unit) : StackCost.accesses (clear l)≤1 := by cases l; decide +end MatchingFPRAS.WordOps + +end OAI diff --git a/lean/OAI/Combinatorics/MatchingEntropy/Basic.lean b/lean/OAI/Combinatorics/MatchingEntropy/Basic.lean new file mode 100644 index 0000000000000000000000000000000000000000..831aba2c140ead1fcec890d137376c5514cecf16 --- /dev/null +++ b/lean/OAI/Combinatorics/MatchingEntropy/Basic.lean @@ -0,0 +1,96 @@ +import OAI.Combinatorics.MatchingEntropy.Coupling + +namespace OAI + +noncomputable section + +open scoped BigOperators Topology +open Filter + +universe uV uE uI uJ uA uB uC uW uF uD uι + +namespace MatchingEntropyBounds.LooplessGraph + +variable {V : Type uV} {E : Type uE} [Fintype V] [Fintype E] [DecidableEq V] [DecidableEq E] + +omit [Fintype V] [Fintype E] [DecidableEq V] in +@[simp] theorem indicator_nonneg (G : LooplessGraph V E) (M : G.Matching) (e : E) : + 0 ≤ G.indicator M e := by + simp only [indicator] + split <;> norm_num + +omit [Fintype V] [Fintype E] [DecidableEq V] in +@[simp] theorem indicator_le_one (G : LooplessGraph V E) (M : G.Matching) (e : E) : + G.indicator M e ≤ 1 := by + simp only [indicator] + split <;> norm_num + +omit [Fintype V] [DecidableEq V] in +theorem continuous_mean (G : LooplessGraph V E) : Continuous G.mean := by + unfold mean + fun_prop + +def meanLinear (G : LooplessGraph V E) : (G.Matching → ℝ) →ₗ[ℝ] (E → ℝ) where + toFun := G.mean + map_add' p q := by + ext e + simp [mean, add_mul, Finset.sum_add_distrib] + map_smul' a p := by + ext e + simp [mean, mul_assoc, Finset.mul_sum] + +omit [Fintype V] [DecidableEq V] in +theorem mean_mem_polytope (G : LooplessGraph V E) {p : G.Matching → ℝ} + (hp : p ∈ probabilitySimplex G.Matching) : G.mean p ∈ G.polytope := by + have h := (convex_convexHull ℝ (Set.range G.indicator)).sum_mem + (fun M _ ↦ hp.1 M) hp.2 (fun M _ ↦ subset_convexHull ℝ _ (Set.mem_range_self M)) + have he : G.mean p = ∑ M, p M • G.indicator M := by + ext e + simp [mean] + rw [he] + exact h + +omit [Fintype V] [DecidableEq V] in +@[simp] theorem mean_single (G : LooplessGraph V E) (M : G.Matching) : + G.mean (Pi.single M 1) = G.indicator M := by + classical + ext e + simp [mean, Pi.single_apply, ite_mul] + +omit [Fintype V] [DecidableEq V] in + +theorem mem_polytope_iff (G : LooplessGraph V E) (y : E → ℝ) : + y ∈ G.polytope ↔ (G.feasibleLaws y).Nonempty := by + classical + constructor + · intro hy + have hc : Convex ℝ (G.mean '' probabilitySimplex G.Matching) := + (convex_probabilitySimplex G.Matching).linear_image G.meanLinear + have hs : Set.range G.indicator ⊆ G.mean '' probabilitySimplex G.Matching := by + rintro _ ⟨M, rfl⟩ + exact ⟨Pi.single M 1, single_mem_probabilitySimplex M, G.mean_single M⟩ + obtain ⟨p, hp, rfl⟩ := convexHull_min hs hc hy + exact ⟨p, hp, rfl⟩ + · rintro ⟨p, hp, rfl⟩ + exact G.mean_mem_polytope hp + +omit [Fintype V] [DecidableEq V] in +theorem compact_feasibleLaws (G : LooplessGraph V E) (y : E → ℝ) : + IsCompact (G.feasibleLaws y) := by + exact (isCompact_probabilitySimplex G.Matching).inter_right + (isClosed_eq G.continuous_mean continuous_const) + +omit [Fintype V] [DecidableEq V] in +theorem compact_polytope (G : LooplessGraph V E) : IsCompact G.polytope := by + have heq : G.polytope = G.mean '' probabilitySimplex G.Matching := by + ext y + rw [G.mem_polytope_iff] + rfl + rw [heq] + exact (isCompact_probabilitySimplex G.Matching).image G.continuous_mean + +end MatchingEntropyBounds.LooplessGraph + +end + +end OAI diff --git a/lean/OAI/Combinatorics/MatchingEntropy/Calculus.lean b/lean/OAI/Combinatorics/MatchingEntropy/Calculus.lean new file mode 100644 index 0000000000000000000000000000000000000000..3d844f91293a46b16004563d4d74d81824b3e412 --- /dev/null +++ b/lean/OAI/Combinatorics/MatchingEntropy/Calculus.lean @@ -0,0 +1,155 @@ +import OAI.Combinatorics.MatchingEntropy.Duality + +namespace OAI + +noncomputable section + +open scoped BigOperators Topology +open Filter + +universe uV uE uI uJ uA uB uC uW uF uD uι + +namespace MatchingEntropyBounds + +variable {V : Type uV} {E : Type uE} [Fintype V] [Fintype E] [DecidableEq V] [DecidableEq E] + +def entropyLineD {ι : Type uι} [Fintype ι] (x v : ι → ℝ) (t : ℝ) : ℝ := + -∑ i, v i * Real.log (x i+t*v i) - ∑ i, v i + +theorem entropy_line_hasDerivAt_at {ι : Type uι} [Fintype ι] (x v : ι → ℝ) + (t : ℝ) (h : ∀ i, x i+t*v i ≠ 0 ∨ v i = 0) : + HasDerivAt (fun t : ℝ => entropy (fun i => x i+t*v i)) (entropyLineD x v t) t := by + have hd : ∀ i, HasDerivAt (fun t : ℝ => Real.negMulLog (x i+t*v i)) + ((-Real.log (x i+t*v i)-1)*v i) t := by + intro i + rcases h i with hi | hi + · simpa only [one_mul, Function.comp_def, id_eq] using + (Real.hasDerivAt_negMulLog hi).comp t + (((hasDerivAt_id t).mul_const (v i)).const_add (x i)) + · simpa only [hi, mul_zero, add_zero] using (hasDerivAt_const t (Real.negMulLog (x i))) + have he : (∑ i, (-Real.log (x i+t*v i)-1)*v i) = entropyLineD x v t := by + simp_rw [sub_mul, one_mul, neg_mul, mul_comm (Real.log (x _+t*v _))] + rw [Finset.sum_sub_distrib, Finset.sum_neg_distrib] + rfl + rw [← he] + simpa only [entropy, Finset.sum_apply] using + (HasDerivAt.fun_sum (u := Finset.univ) (fun i _ => hd i)) + +theorem entropy_line_deriv_eventually {ι : Type uι} [Fintype ι] (x v : ι → ℝ) + (hsupp : ∀ i, x i = 0 → v i = 0) : + deriv (fun t : ℝ => entropy (fun i => x i+t*v i)) =ᶠ[𝓝 0] entropyLineD x v := by + have hh : ∀ᶠ t : ℝ in 𝓝 0, ∀ i, x i+t*v i ≠ 0 ∨ v i = 0 := by + apply Filter.eventually_all.mpr + intro i + by_cases hi : x i = 0 + · exact Filter.Eventually.of_forall (fun t => Or.inr (hsupp i hi)) + · have hc : ContinuousAt (fun t : ℝ => x i+t*v i) 0 := by fun_prop + have hn := hc.eventually_ne (show x i+(0:ℝ)*v i ≠ 0 by simpa using hi) + exact hn.mono (fun t ht => Or.inl ht) + filter_upwards [hh] with t ht + exact (entropy_line_hasDerivAt_at x v t ht).deriv + +theorem entropyLineD_hasDerivAt {ι : Type uι} [Fintype ι] (x v : ι → ℝ) + (hsupp : ∀ i, x i = 0 → v i = 0) : + HasDerivAt (entropyLineD x v) (-∑ i, (v i)^2/x i) 0 := by + have hd : ∀ i, HasDerivAt (fun t : ℝ => v i*Real.log (x i+t*v i)) + ((v i)^2/x i) 0 := by + intro i + by_cases hi : x i = 0 + · simpa only [hi, hsupp i hi, zero_mul, zero_pow (by omega : 2 ≠ 0), zero_div] using + (hasDerivAt_const (0:ℝ) (0:ℝ)) + · have hh := ((((hasDerivAt_id (0:ℝ)).mul_const (v i)).const_add (x i)).log + (by simpa using hi)).const_mul (v i) + simpa only [id_eq, one_mul, zero_mul, add_zero, pow_two, mul_div_assoc] using hh + change HasDerivAt (fun t : ℝ => -(∑ i, v i*Real.log (x i+t*v i)) - ∑ i, v i) + (-∑ i, (v i)^2/x i) 0 + exact (HasDerivAt.fun_sum (u := Finset.univ) (fun i _ => hd i)).neg.sub_const (∑ i, v i) + +theorem entropy_line_second {ι : Type uι} [Fintype ι] (x v : ι → ℝ) + (hsupp : ∀ i, x i = 0 → v i = 0) : + HasDerivAt (deriv (fun t : ℝ => entropy (fun i => x i+t*v i))) + (-∑ i, (v i)^2/x i) 0 := + (entropyLineD_hasDerivAt x v hsupp).congr_of_eventuallyEq + (entropy_line_deriv_eventually x v hsupp) + +theorem second_deriv_quadratic_adjustment {f fD g gD : ℝ → ℝ} {fDD gDD c₀ c₁ v : ℝ} + (hf : ∀ᶠ t in 𝓝 (0:ℝ), HasDerivAt f (fD t) t) + (hg : ∀ᶠ t in 𝓝 (0:ℝ), HasDerivAt g (gD t) t) + (hfD : HasDerivAt fD fDD 0) (hgD : HasDerivAt gD gDD 0) : + HasDerivAt (deriv (fun t => f t+c₀+t*c₁+t^2*v-g t)) + (fDD+2*v-gDD) 0 := by + have hfirst : deriv (fun t => f t+c₀+t*c₁+t^2*v-g t) =ᶠ[𝓝 (0:ℝ)] + (fun t => fD t+c₁+2*t*v-gD t) := by + filter_upwards [hf, hg] with t hft hgt + have hd := (((hft.add_const c₀).fun_add ((hasDerivAt_id t).mul_const c₁)).fun_add + (((hasDerivAt_id t).fun_pow 2).mul_const v)).fun_sub hgt + simpa only [Pi.add_apply, Pi.sub_apply, Pi.pow_apply, id_eq, one_mul, + Nat.cast_ofNat, Nat.reduceSub, pow_one, mul_one] using hd.deriv + have hd := ((hfD.add_const c₁).fun_add + (((hasDerivAt_id (0:ℝ)).const_mul 2).mul_const v)).fun_sub hgD + have hd' : HasDerivAt (fun t => fD t+c₁+2*t*v-gD t) (fDD+2*v-gDD) 0 := by + simpa only [Pi.add_apply, Pi.sub_apply, id_eq, mul_one] using hd + exact hd'.congr_of_eventuallyEq hfirst + +theorem second_deriv_nonpos_of_local_max {f : ℝ → ℝ} {x : ℝ} + (hm : IsLocalMax f x) (hc : ContinuousAt f x) : deriv (deriv f) x ≤ 0 := by + by_contra h + have hp : 0 < deriv (deriv f) x := lt_of_not_ge h + have hmin := isLocalMin_of_deriv_deriv_pos hp hm.deriv_eq_zero hc + have he : f =ᶠ[𝓝 x] (fun _ => f x) := by + filter_upwards [hm, hmin] with y h₁ h₂ + exact le_antisymm h₁ h₂ + have hh := he.deriv.deriv_eq + simp only [deriv_const', deriv_const] at hh + linarith + +theorem entropy_line_eventually_hasDerivAt {ι : Type uι} [Fintype ι] (x v : ι → ℝ) + (hsupp : ∀ i, x i = 0 → v i = 0) : + ∀ᶠ t : ℝ in 𝓝 0, + HasDerivAt (fun t : ℝ => entropy (fun i => x i+t*v i)) (entropyLineD x v t) t := by + have hh : ∀ᶠ t : ℝ in 𝓝 0, ∀ i, x i+t*v i ≠ 0 ∨ v i = 0 := by + apply Filter.eventually_all.mpr + intro i + by_cases hi : x i = 0 + · exact Filter.Eventually.of_forall (fun t => Or.inr (hsupp i hi)) + · have hc : ContinuousAt (fun t : ℝ => x i+t*v i) 0 := by fun_prop + have hn := hc.eventually_ne (show x i+(0:ℝ)*v i ≠ 0 by simpa using hi) + exact hn.mono (fun t ht => Or.inl ht) + exact hh.mono (fun t ht => entropy_line_hasDerivAt_at x v t ht) + +theorem score_law_eventually_simplex {ι : Type uι} [Fintype ι] {p : ι → ℝ} + (hp : p ∈ probabilitySimplex ι) (a : ι → ℝ) (hcenter : ∑ i, p i*a i = 0) : + ∀ᶠ t : ℝ in 𝓝 0, (fun i => p i+t*(p i*a i)) ∈ probabilitySimplex ι := by + have hh : ∀ᶠ t : ℝ in 𝓝 0, ∀ i, 0 < 1+t*a i := by + apply Filter.eventually_all.mpr + intro i + have hc : Continuous (fun t : ℝ => 1+t*a i) := by fun_prop + exact (isOpen_lt continuous_const hc).mem_nhds (by norm_num) + filter_upwards [hh] with t ht + constructor + · intro i + have h := mul_nonneg (hp.1 i) (ht i).le + nlinarith + · rw [Finset.sum_add_distrib, ← Finset.mul_sum, hp.2, hcenter] + ring + +omit [Fintype V] [DecidableEq V] in +theorem mean_score_support (G : LooplessGraph V E) {p : G.Matching → ℝ} + (hp : p ∈ probabilitySimplex G.Matching) (a : G.Matching → ℝ) : + ∀ e, G.mean p e = 0 → G.mean (fun M => p M*a M) e = 0 := by + intro e he + have hterms : ∀ M, p M*G.indicator M e = 0 := by + have hh := (Finset.sum_eq_zero_iff_of_nonneg + (fun M (_ : M ∈ Finset.univ) => mul_nonneg (hp.1 M) (G.indicator_nonneg M e))).mp he + exact fun M => hh M (Finset.mem_univ M) + apply Finset.sum_eq_zero + intro M _ + calc + _ = a M*(p M*G.indicator M e) := by ring + _ = 0 := by rw [hterms, mul_zero] + +end MatchingEntropyBounds + +end + +end OAI diff --git a/lean/OAI/Combinatorics/MatchingEntropy/Components.lean b/lean/OAI/Combinatorics/MatchingEntropy/Components.lean new file mode 100644 index 0000000000000000000000000000000000000000..2ac42e5cc2dd1a4284ee7f6a2dc56010d6cc980c --- /dev/null +++ b/lean/OAI/Combinatorics/MatchingEntropy/Components.lean @@ -0,0 +1,349 @@ +import OAI.Combinatorics.MatchingEntropy.FractionalReduction + +namespace OAI + +noncomputable section + +open scoped BigOperators Topology +open Filter + +universe uV uE uI uJ uA uB uC uW uF uD uι + +namespace MatchingEntropyBounds.Refined + +variable {V : Type uV} {E : Type uE} [Fintype V] [Fintype E] [DecidableEq V] [DecidableEq E] + +def underlyingSimple (G : LooplessGraph V E) : SimpleGraph V where + Adj v w := ∃ e, (G.left e = v ∧ G.right e = w) ∨ (G.left e = w ∧ G.right e = v) + symm := ⟨by + rintro v w ⟨e, h | h⟩ + · exact ⟨e, Or.inr h⟩ + · exact ⟨e, Or.inl h⟩⟩ + loopless := ⟨by + rintro v ⟨e, h | h⟩ <;> exact G.loopless e (h.1.trans h.2.symm)⟩ + +abbrev Component (G : LooplessGraph V E) := (underlyingSimple G).ConnectedComponent +noncomputable instance componentFintype (G : LooplessGraph V E) : Fintype (Component G) := Fintype.ofFinite _ +noncomputable instance componentDecidableEq (G : LooplessGraph V E) : DecidableEq (Component G) := Classical.decEq _ + +def componentOf (G : LooplessGraph V E) (v : V) : Component G := + (underlyingSimple G).connectedComponentMk v + +omit [Fintype V] [Fintype E] [DecidableEq V] [DecidableEq E] in +theorem component_edge_eq (G : LooplessGraph V E) (e : E) : + componentOf G (G.left e) = componentOf G (G.right e) := + SimpleGraph.ConnectedComponent.connectedComponentMk_eq_of_adj ⟨e, Or.inl ⟨rfl,rfl⟩⟩ + +def componentGraph (G : LooplessGraph V E) (c : Component G) : + LooplessGraph {v // componentOf G v = c} {e // componentOf G (G.left e) = c} where + left e := ⟨G.left e.val,e.property⟩ + right e := ⟨G.right e.val,(component_edge_eq G e.val).symm.trans e.property⟩ + loopless e h := G.loopless e.val (congrArg Subtype.val h) + +def componentMean (G : LooplessGraph V E) (x : E → ℝ) (c : Component G) : + {e // componentOf G (G.left e) = c} → ℝ := fun e => x e.val + +def componentOrder (G : LooplessGraph V E) (c : Component G) : ℕ := + Fintype.card {v // componentOf G v = c} / 2 + +section ProductLaws +variable {I : Type uI} [Fintype I] [DecidableEq I] {A : I → Type uA} + [∀ i, Fintype (A i)] [∀ i, DecidableEq (A i)] + +def piLaw (q : ∀ i, A i → ℝ) (a : ∀ i, A i) : ℝ := ∏ i, q i (a i) + +omit [∀ i, DecidableEq (A i)] in +theorem piLaw_simplex {q : ∀ i, A i → ℝ} (hq : ∀ i, q i ∈ probabilitySimplex (A i)) : + piLaw q ∈ probabilitySimplex (∀ i, A i) := by + refine ⟨fun a => Finset.prod_nonneg (fun i _ => (hq i).1 (a i)), ?_⟩ + change (∑ a : ∀ i, A i, ∏ i, q i (a i)) = 1 + rw [← Fintype.prod_sum] + simp_rw [(hq _).2] + simp + +omit [∀ i, DecidableEq (A i)] in +theorem piLaw_expect {q : ∀ i, A i → ℝ} (hq : ∀ i, q i ∈ probabilitySimplex (A i)) + (k : I) (f : A k → ℝ) : + (∑ a : ∀ i, A i, piLaw q a * f (a k)) = ∑ b, q k b * f b := by + let r : ∀ i, A i → ℝ := Function.update q k (fun b => q k b * f b) + have heq (a : ∀ i, A i) : (∏ i, r i (a i)) = piLaw q a * f (a k) := by + rw [Fintype.prod_eq_mul_prod_compl k (fun i => r i (a i)), + piLaw, Fintype.prod_eq_mul_prod_compl k (fun i => q i (a i))] + have hr : r k (a k) = q k (a k) * f (a k) := by simp [r] + rw [hr] + have hprod : (∏ i ∈ ({k}ᶜ : Finset I), r i (a i)) = ∏ i ∈ ({k}ᶜ : Finset I), q i (a i) := by + apply Finset.prod_congr rfl + intro i hi + have hik : i ≠ k := by simpa using hi + simp [r, hik] + rw [hprod] + ring + rw [← show (∑ a : ∀ i, A i, ∏ i, r i (a i)) = _ from Finset.sum_congr rfl (fun a _ => heq a), + ← Fintype.prod_sum, Fintype.prod_eq_mul_prod_compl k] + have hr : (∑ b, r k b) = ∑ b, q k b * f b := by simp [r] + rw [hr] + have hprod : (∏ i ∈ ({k}ᶜ : Finset I), ∑ b, r i b) = 1 := by + apply Finset.prod_eq_one + intro i hi + have hik : i ≠ k := by simpa using hi + simpa [r, hik] using (hq i).2 + rw [hprod, mul_one] + +theorem piLaw_marginal {q : ∀ i, A i → ℝ} (hq : ∀ i, q i ∈ probabilitySimplex (A i)) + (k : I) : fiberMass (piLaw q) (fun a => a k) = q k := by + ext b + have h := piLaw_expect hq k (fun x => if x=b then 1 else 0) + simpa [fiberMass, mul_ite] using h + +theorem piLaw_crossEntropy (p : (∀ i, A i) → ℝ) (q : ∀ i, A i → ℝ) + (hsupp : ∀ a, p a ≠ 0 → ∀ i, q i (a i) ≠ 0) : + -(∑ a, p a * Real.log (piLaw q a)) = + ∑ i, -(∑ b, fiberMass p (fun a => a i) b * Real.log (q i b)) := by + have heq (a : ∀ i, A i) : p a * Real.log (piLaw q a) = ∑ i, p a * Real.log (q i (a i)) := by + by_cases ha : p a = 0 + · simp [ha] + · rw [piLaw, Real.log_prod (fun i _ => hsupp a ha i), Finset.mul_sum] + simp_rw [heq] + rw [Finset.sum_comm, Finset.sum_neg_distrib] + congr 1 + apply Finset.sum_congr rfl + intro i _ + exact (fiberMass_expect p (fun a => a i) (fun b => Real.log (q i b))).symm + +theorem entropy_piLaw {q : ∀ i, A i → ℝ} (hq : ∀ i, q i ∈ probabilitySimplex (A i)) : + entropy (piLaw q) = ∑ i, entropy (q i) := by + rw [entropy_eq, piLaw_crossEntropy] + · simp_rw [piLaw_marginal hq, ← entropy_eq] + · intro a ha i + exact (Finset.prod_ne_zero_iff.mp ha) i (Finset.mem_univ i) + +theorem entropy_le_marginal_sum {p : (∀ i, A i) → ℝ} + (hp : p ∈ probabilitySimplex (∀ i, A i)) : + entropy p ≤ ∑ i, entropy (fiberMass p (fun a => a i)) := by + let q : ∀ i, A i → ℝ := fun i => fiberMass p (fun a => a i) + have hq : ∀ i, q i ∈ probabilitySimplex (A i) := fun i => fiberMass_mem_simplex hp _ + have hs : ∀ a, p a ≠ 0 → ∀ i, q i (a i) ≠ 0 := by + intro a ha i + exact ne_of_gt ((lt_of_le_of_ne (hp.1 a) (Ne.symm ha)).trans_le (le_fiberMass_self hp.1 _ a)) + have h := entropy_le_crossEntropy (piLaw_simplex hq) hp (fun a ha => by + by_contra hpa + exact (Finset.prod_ne_zero_iff.mpr (fun i _ => hs a hpa i)) ha) + rw [piLaw_crossEntropy p q hs] at h + simpa only [q, ← entropy_eq] using h +end ProductLaws + +omit [Fintype V] [Fintype E] [DecidableEq V] [DecidableEq E] in +theorem component_incident_iff (G : LooplessGraph V E) (c : Component G) + (v : {v // componentOf G v = c}) (e : {e // componentOf G (G.left e) = c}) : + (componentGraph G c).Incident v e ↔ G.Incident v.val e.val := by + constructor + · rintro (h | h) + · exact Or.inl (congrArg Subtype.val h) + · exact Or.inr (congrArg Subtype.val h) + · rintro (h | h) + · exact Or.inl (Subtype.ext h) + · exact Or.inr (Subtype.ext h) + +omit [Fintype V] [Fintype E] [DecidableEq V] [DecidableEq E] in +theorem component_eq_of_incident (G : LooplessGraph V E) {v : V} {e : E} (h : G.Incident v e) : + componentOf G (G.left e) = componentOf G v := by + rcases h with h | h + · rw [h] + · rw [component_edge_eq G e, h] + +def componentRestrict (G : LooplessGraph V E) (c : Component G) (M : G.Matching) : + (componentGraph G c).Matching := by + classical + refine ⟨M.val.subtype (fun e => componentOf G (G.left e) = c), ?_⟩ + intro v + obtain ⟨e,he,hu⟩ := M.property v.val + have hc : componentOf G (G.left e) = c := (component_eq_of_incident G he.2).trans v.property + refine ⟨⟨e,hc⟩, ⟨by simpa using he.1,(component_incident_iff G c v _).mpr he.2⟩, ?_⟩ + intro f hf + exact Subtype.ext (hu f.val ⟨by simpa using hf.1,(component_incident_iff G c v f).mp hf.2⟩) + +omit [Fintype V] [Fintype E] [DecidableEq V] [DecidableEq E] in +@[simp] theorem mem_componentRestrict (G : LooplessGraph V E) (c : Component G) (M : G.Matching) + (e : {e // componentOf G (G.left e) = c}) : + e ∈ (componentRestrict G c M).val ↔ e.val ∈ M.val := by + simp [componentRestrict] + +omit [Fintype V] [Fintype E] [DecidableEq V] in +theorem componentRestrict_indicator (G : LooplessGraph V E) (c : Component G) (M : G.Matching) + (e : {e // componentOf G (G.left e) = c}) : + (componentGraph G c).indicator (componentRestrict G c M) e = G.indicator M e.val := by + simp [LooplessGraph.indicator] + +def componentGlue (G : LooplessGraph V E) (M : ∀ c : Component G, (componentGraph G c).Matching) : + G.Matching := by + classical + let N := Finset.univ.filter (fun e => (⟨e,rfl⟩ : {f // componentOf G (G.left f) = componentOf G (G.left e)}) ∈ (M (componentOf G (G.left e))).val) + have hmem (c : Component G) (e : {e // componentOf G (G.left e) = c}) : e.val ∈ N ↔ e ∈ (M c).val := by + obtain ⟨e,he⟩ := e + subst c + simp [N] + refine ⟨N, ?_⟩ + intro v + obtain ⟨e,he,hu⟩ := (M (componentOf G v)).property ⟨v,rfl⟩ + refine ⟨e.val,⟨(hmem _ e).mpr he.1,(component_incident_iff G _ _ e).mp he.2⟩,?_⟩ + intro f hf + have hfc := component_eq_of_incident G hf.2 + exact congrArg Subtype.val (hu ⟨f,hfc⟩ ⟨(hmem _ _).mp hf.1,(component_incident_iff G _ _ _).mpr hf.2⟩) + +omit [Fintype V] [DecidableEq V] in +@[simp] theorem mem_componentGlue (G : LooplessGraph V E) + (M : ∀ c : Component G, (componentGraph G c).Matching) (c : Component G) + (e : {e // componentOf G (G.left e) = c}) : + e.val ∈ (componentGlue G M).val ↔ e ∈ (M c).val := by + obtain ⟨e,he⟩ := e + subst c + simp [componentGlue] + +def componentMatchingEquiv (G : LooplessGraph V E) : + G.Matching ≃ (∀ c : Component G, (componentGraph G c).Matching) where + toFun := fun M c => componentRestrict G c M + invFun := componentGlue G + left_inv M := by + apply Subtype.ext + ext e + exact (mem_componentGlue G _ _ ⟨e,rfl⟩).trans (mem_componentRestrict G _ M ⟨e,rfl⟩) + right_inv M := by + funext c + apply Subtype.ext + ext e + rw [mem_componentRestrict, mem_componentGlue] + +omit [Fintype V] in +omit [DecidableEq V] in +theorem component_mean_marginal (G : LooplessGraph V E) (c : Component G) (p : G.Matching → ℝ) : + (componentGraph G c).mean (fiberMass p (componentRestrict G c)) = componentMean G (G.mean p) c := by + ext e + rw [LooplessGraph.mean, fiberMass_expect] + simp_rw [componentRestrict_indicator] + rfl + +omit [Fintype V] in +omit [DecidableEq V] in +theorem component_feasible (G : LooplessGraph V E) (c : Component G) + {x : E → ℝ} {p : G.Matching → ℝ} (hp : p ∈ G.feasibleLaws x) : + fiberMass p (componentRestrict G c) ∈ (componentGraph G c).feasibleLaws (componentMean G x c) := by + exact ⟨fiberMass_mem_simplex hp.1 _, by rw [component_mean_marginal, hp.2]⟩ + +section FiberComposition +variable {A : Type uA} {B : Type uB} {C : Type uC} [Fintype A] [Fintype B] [Fintype C] [DecidableEq B] [DecidableEq C] +omit [Fintype C] in +theorem fiberMass_comp (p : A → ℝ) (f : A → B) (g : B → C) : + fiberMass (fiberMass p f) g = fiberMass p (g ∘ f) := by + ext c + have h := fiberMass_expect p f (fun b => if g b = c then 1 else 0) + simpa [fiberMass, mul_ite] using h +end FiberComposition + +omit [DecidableEq V] in +theorem component_joint_entropy_bound (G : LooplessGraph V E) + {p : G.Matching → ℝ} (hp : p ∈ probabilitySimplex G.Matching) : + entropy p ≤ ∑ c : Component G, entropy (fiberMass p (componentRestrict G c)) := by + have h := entropy_le_marginal_sum (fiberMass_mem_simplex hp (componentMatchingEquiv G)) + rw [entropy_fiberMass_injective _ _ (componentMatchingEquiv G).injective] at h + simpa only [fiberMass_comp, Function.comp_def, componentMatchingEquiv, Equiv.coe_fn_mk] using h + +omit [DecidableEq V] in +theorem component_product_feasible (G : LooplessGraph V E) {x : E → ℝ} + {q : ∀ c : Component G, (componentGraph G c).Matching → ℝ} + (hq : ∀ c, q c ∈ (componentGraph G c).feasibleLaws (componentMean G x c)) : + fiberMass (piLaw q) (componentMatchingEquiv G).symm ∈ G.feasibleLaws x := by + refine ⟨fiberMass_mem_simplex (piLaw_simplex (fun c => (hq c).1)) _, ?_⟩ + ext e + let c := componentOf G (G.left e) + let f : {e // componentOf G (G.left e) = c} := ⟨e,rfl⟩ + rw [LooplessGraph.mean, fiberMass_expect] + have hi (M : ∀ c : Component G, (componentGraph G c).Matching) : + G.indicator ((componentMatchingEquiv G).symm M) e = (componentGraph G c).indicator (M c) f := by + simp only [LooplessGraph.indicator] + change (if f.val ∈ (componentGlue G M).val then (1:ℝ) else 0) = _ + simp only [mem_componentGlue] + simp_rw [hi] + rw [piLaw_expect (fun c => (hq c).1) c (fun M => (componentGraph G c).indicator M f)] + exact congrFun (hq c).2 f + +omit [DecidableEq V] in +theorem component_maxEntropy (G : LooplessGraph V E) {x : E → ℝ} (hx : x ∈ G.polytope) : + maxMatchingEntropy G x = ∑ c : Component G, maxMatchingEntropy (componentGraph G c) (componentMean G x c) := by + obtain ⟨p,hp,hopt⟩ := maxMatchingEntropy_attained G hx + have hc (c : Component G) : componentMean G x c ∈ (componentGraph G c).polytope := + ((componentGraph G c).mem_polytope_iff _).mpr ⟨_,component_feasible G c hp⟩ + choose q hq hqo using fun c => maxMatchingEntropy_attained (componentGraph G c) (hc c) + apply le_antisymm + · rw [← hopt] + exact (component_joint_entropy_bound G hp.1).trans (Finset.sum_le_sum (fun c _ => + entropy_le_maxMatchingEntropy _ (component_feasible G c hp))) + · have hh := entropy_le_maxMatchingEntropy G (component_product_feasible G hq) + rw [entropy_fiberMass_injective _ _ (componentMatchingEquiv G).symm.injective, + entropy_piLaw (fun c => (hq c).1)] at hh + simpa only [hqo] using hh + +omit [DecidableEq V] [DecidableEq E] in +theorem component_entropy_terms (G : LooplessGraph V E) (x : E → ℝ) : + entropy x = ∑ c : Component G, entropy (componentMean G x c) ∧ + complementEntropy x = ∑ c : Component G, complementEntropy (componentMean G x c) := by + constructor + · exact (Fintype.sum_fiberwise (fun e => componentOf G (G.left e)) (fun e => Real.negMulLog (x e))).symm + · exact (Fintype.sum_fiberwise (fun e => componentOf G (G.left e)) (fun e => Real.negMulLog (1-x e))).symm + +theorem component_additivity (G : LooplessGraph V E) {x : E → ℝ} (hx : x ∈ G.polytope) : + (∀ c : Component G, 0 < componentOrder G c ∧ + Fintype.card {v // componentOf G v = c} = 2 * componentOrder G c ∧ + componentMean G x c ∈ (componentGraph G c).polytope) ∧ + maxMatchingEntropy G x = ∑ c : Component G, maxMatchingEntropy (componentGraph G c) (componentMean G x c) ∧ + entropy x = ∑ c : Component G, entropy (componentMean G x c) ∧ + complementEntropy x = ∑ c : Component G, complementEntropy (componentMean G x c) := by + refine ⟨?_,component_maxEntropy G hx,component_entropy_terms G x⟩ + intro c + obtain ⟨p,hp⟩ := (G.mem_polytope_iff x).mp hx + have hr := (componentGraph G c).mean_mem_polytope (component_feasible G c hp).1 + rw [(component_feasible G c hp).2] at hr + have hev := even_of_mem (componentGraph G c) hr + obtain ⟨v,hv⟩ := c.exists_rep + have hcpos : 0 < Fintype.card {v // componentOf G v = c} := + Fintype.card_pos_iff.mpr ⟨⟨v,hv⟩⟩ + refine ⟨?_,?_,hr⟩ <;> unfold componentOrder <;> obtain ⟨m,hm⟩ := hev <;> omega + +theorem fractional_components (G : LooplessGraph V E) {x : E → ℝ} (hx : x ∈ G.polytope) : + let R := fractionalGraph G x + let z := fractionalMean x + (∀ c : Component R, 0 < componentOrder R c ∧ + Fintype.card {v // componentOf R v = c} = 2 * componentOrder R c ∧ + componentMean R z c ∈ (componentGraph R c).polytope) ∧ + maxMatchingEntropy G x = ∑ c : Component R, maxMatchingEntropy (componentGraph R c) (componentMean R z c) ∧ + entropy x - (∑ c : Component R, (2 - 2 / (componentOrder R c : ℝ)) * + complementEntropy (componentMean R z c)) ≤ maxMatchingEntropy G x ∧ + maxMatchingEntropy G x ≤ entropy x ∧ + (IsEmpty (Component R) → entropy x = 0 ∧ complementEntropy x = 0 ∧ maxMatchingEntropy G x = 0) := by + dsimp only + let R := fractionalGraph G x + let z := fractionalMean x + have hz := fractionalMean_mem G hx + have ⟨ho,hH,hF,hB⟩ := component_additivity R hz + have hHr : maxMatchingEntropy G x = maxMatchingEntropy R z := by + simpa only [fractionalExtension_mean] using fractional_maxEntropy G hx hz + have ⟨hFr,hBr⟩ := fractional_entropy_terms G hx + refine ⟨ho,hHr.trans hH,?_,refined_upper G x hx,?_⟩ + · rw [hHr, hH, ← hFr, hF, ← Finset.sum_sub_distrib] + exact Finset.sum_le_sum (fun c _ => refined_lower (componentGraph R c) (componentOrder R c) + (ho c).1 (ho c).2.1 (componentMean R z c) (ho c).2.2) + · intro hc + have : IsEmpty (Component R) := hc + constructor + · rw [← hFr, hF] + simp + constructor + · rw [← hBr, hB] + simp + · rw [hHr, hH] + simp + +end MatchingEntropyBounds.Refined + +end + +end OAI diff --git a/lean/OAI/Combinatorics/MatchingEntropy/Continuity.lean b/lean/OAI/Combinatorics/MatchingEntropy/Continuity.lean new file mode 100644 index 0000000000000000000000000000000000000000..24cc874b4878c069ff30cf4eab54f08698c24850 --- /dev/null +++ b/lean/OAI/Combinatorics/MatchingEntropy/Continuity.lean @@ -0,0 +1,61 @@ +import OAI.Combinatorics.MatchingEntropy.Covariance + +namespace OAI + +noncomputable section + +open scoped BigOperators Topology +open Filter Matrix + +universe uV uE uI uJ uA uB uC uW uF uD uι + +namespace MatchingEntropyBounds + +variable {V : Type uV} {E : Type uE} [Fintype V] [Fintype E] [DecidableEq V] [DecidableEq E] + +omit [Fintype V] [DecidableEq V] in + +theorem maxMatchingEntropy_mix_ge (G : LooplessGraph V E) {x y : E → ℝ} + (hx : x ∈ G.polytope) (hy : y ∈ G.polytope) {t : ℝ} + (ht : t ∈ Set.Icc (0 : ℝ) 1) : + (1-t)*maxMatchingEntropy G x+t*maxMatchingEntropy G y ≤ + maxMatchingEntropy G ((1-t) • x+t • y) := by + obtain ⟨p,hp,hpe⟩ := maxMatchingEntropy_attained G hx + obtain ⟨q,hq,hqe⟩ := maxMatchingEntropy_attained G hy + rw [← hpe,← hqe] + apply (entropy_mix_ge hp.1.1 hq.1.1 ht).trans + apply entropy_le_maxMatchingEntropy + refine ⟨convex_probabilitySimplex _ hp.1 hq.1 (sub_nonneg.mpr ht.2) ht.1 (by ring),?_⟩ + change G.meanLinear ((1-t) • p+t • q) = _ + rw [map_add,map_smul,map_smul] + change (1-t) • G.mean p+t • G.mean q = _ + rw [hp.2,hq.2] + +theorem maxMatchingEntropy_lowerSemicontinuousOn (G : LooplessGraph V E) + (heven : Even (Fintype.card V)) : + LowerSemicontinuousOn (maxMatchingEntropy G) G.polytope := by + intro x hx r hr + have hn := maxMatchingEntropy_nonneg G hx + have hden : 0 < maxMatchingEntropy G x+1 := by linarith + have ha : 0 < min (1:ℝ) ((maxMatchingEntropy G x-r)/(maxMatchingEntropy G x+1)) := + lt_min (by norm_num) (div_pos (sub_pos.mpr hr) hden) + obtain ⟨t,ht0,htt⟩ := exists_between ha + have ht1 : t<1 := htt.trans_le (min_le_left _ _) + have htb : t*(maxMatchingEntropy G x+1) < maxMatchingEntropy G x-r := + (lt_div_iff₀ hden).mp (htt.trans_le (min_le_right _ _)) + filter_upwards [G.polytope_eventually_expand heven hx ht0] with y hy + have hh := maxMatchingEntropy_mix_ge G hx hy ⟨ht0.le,ht1.le⟩ + have he : (1-t) • x+t • (x+t⁻¹ • (y-x))=y := by + ext e + simp only [Pi.add_apply,Pi.smul_apply,Pi.sub_apply,smul_eq_mul] + field_simp + ring + rw [he] at hh + have hz := mul_nonneg ht0.le (maxMatchingEntropy_nonneg G hy) + nlinarith + +end MatchingEntropyBounds + +end + +end OAI diff --git a/lean/OAI/Combinatorics/MatchingEntropy/Contraction.lean b/lean/OAI/Combinatorics/MatchingEntropy/Contraction.lean new file mode 100644 index 0000000000000000000000000000000000000000..87ade4fa37d0e610f8ab5c4cfa3a4011bd019684 --- /dev/null +++ b/lean/OAI/Combinatorics/MatchingEntropy/Contraction.lean @@ -0,0 +1,421 @@ +import OAI.Combinatorics.MatchingEntropy.OddCuts + +namespace OAI + +noncomputable section + +open scoped BigOperators Topology +open Filter + +universe uV uE uI uJ uA uB uC uW uF uD uι + +namespace MatchingEntropyBounds.LooplessGraph + +variable {V : Type uV} {E : Type uE} [Fintype V] [Fintype E] [DecidableEq V] [DecidableEq E] + +def onSide (G : LooplessGraph V E) (S : Finset V) : + LooplessGraph (Option {v // v ∈ S}) {e // G.left e ∈ S ∨ G.right e ∈ S} where + left e := if h : G.left e.val ∈ S then some ⟨G.left e.val, h⟩ else none + right e := if h : G.right e.val ∈ S then some ⟨G.right e.val, h⟩ else none + loopless e := by + dsimp + split_ifs with hl hr + · intro he + have hv := Option.some.inj he + exact G.loopless e.val (congrArg Subtype.val hv) + · simp + · simp + · rename_i hr + exact (e.property.elim hl hr).elim + +omit [Fintype V] [Fintype E] [DecidableEq E] in +theorem onSide_incident_some (G : LooplessGraph V E) (S : Finset V) + (v : {v // v ∈ S}) (e : {e // G.left e ∈ S ∨ G.right e ∈ S}) : + (G.onSide S).Incident (some v) e ↔ G.Incident v.val e.val := by + have hf : ∀ (w : V), + (if h : w ∈ S then some (⟨w,h⟩ : {v // v ∈ S}) else none) = some v ↔ w=v.val := by + intro w + by_cases hw : w ∈ S + · simp only [hw, ↓reduceDIte, Option.some.injEq] + exact Subtype.ext_iff + · simp only [hw, ↓reduceDIte] + constructor + · intro h + cases h + · intro he + exact (hw (he.symm ▸ v.property)).elim + change ((if h : G.left e.val ∈ S then some ⟨G.left e.val,h⟩ else none) = some v ∨ + (if h : G.right e.val ∈ S then some ⟨G.right e.val,h⟩ else none) = some v) ↔ _ + rw [hf, hf] + rfl + +omit [Fintype V] [Fintype E] [DecidableEq E] in +theorem onSide_incident_none (G : LooplessGraph V E) (S : Finset V) + (e : {e // G.left e ∈ S ∨ G.right e ∈ S}) : + (G.onSide S).Incident none e ↔ G.Crosses S e.val := by + simp only [Incident, onSide, Crosses] + by_cases hl : G.left e.val ∈ S <;> by_cases hr : G.right e.val ∈ S <;> + simp [hl, hr] + exact (e.property.elim hl hr).elim + +def boundaryEdge (G : LooplessGraph V E) (S : Finset V) (M : (G.onSide S).Matching) : + {e // G.left e ∈ S ∨ G.right e ∈ S} := Classical.choose (M.property none) + +omit [Fintype V] [Fintype E] [DecidableEq E] in +theorem boundaryEdge_mem (G : LooplessGraph V E) (S : Finset V) + (M : (G.onSide S).Matching) : G.boundaryEdge S M ∈ M.val := + (Classical.choose_spec (M.property none)).1.1 + +omit [Fintype V] [Fintype E] [DecidableEq E] in +theorem boundaryEdge_crosses (G : LooplessGraph V E) (S : Finset V) + (M : (G.onSide S).Matching) : G.Crosses S (G.boundaryEdge S M).val := + (G.onSide_incident_none S _).mp (Classical.choose_spec (M.property none)).1.2 + +omit [Fintype V] [Fintype E] [DecidableEq E] in +theorem eq_boundaryEdge (G : LooplessGraph V E) (S : Finset V) + (M : (G.onSide S).Matching) {e : {e // G.left e ∈ S ∨ G.right e ∈ S}} + (he : e ∈ M.val) (hc : G.Crosses S e.val) : e = G.boundaryEdge S M := + (Classical.choose_spec (M.property none)).2 e ⟨he, (G.onSide_incident_none S e).mpr hc⟩ + +def liftedEdges (G : LooplessGraph V E) (S : Finset V) (M : (G.onSide S).Matching) : Finset E := + M.val.image Subtype.val + +omit [Fintype V] [Fintype E] in +theorem mem_liftedEdges (G : LooplessGraph V E) (S : Finset V) + (M : (G.onSide S).Matching) (e : {e // G.left e ∈ S ∨ G.right e ∈ S}) : + e.val ∈ G.liftedEdges S M ↔ e ∈ M.val := by + simp only [liftedEdges, Finset.mem_image] + constructor + · rintro ⟨a, ha, he⟩ + have he' : a = e := Subtype.ext he + simpa only [he'] using ha + · intro he + exact ⟨e, he, rfl⟩ + +omit [Fintype V] [Fintype E] in +theorem liftedEdges_keep (G : LooplessGraph V E) (S : Finset V) + (M : (G.onSide S).Matching) {e : E} (he : e ∈ G.liftedEdges S M) : + G.left e ∈ S ∨ G.right e ∈ S := by + rcases Finset.mem_image.mp he with ⟨a, _, rfl⟩ + exact a.property + +omit [Fintype V] [Fintype E] in +theorem lifted_cross_eq_boundary (G : LooplessGraph V E) (S : Finset V) + (M : (G.onSide S).Matching) {e : E} (he : e ∈ G.liftedEdges S M) + (hc : G.Crosses S e) : e = (G.boundaryEdge S M).val := by + let e' : {e // G.left e ∈ S ∨ G.right e ∈ S} := ⟨e, G.liftedEdges_keep S M he⟩ + exact congrArg Subtype.val (G.eq_boundaryEdge S M ((G.mem_liftedEdges S M e').mp he) hc) + +omit [Fintype V] [Fintype E] in +theorem boundary_mem_lifted (G : LooplessGraph V E) (S : Finset V) + (M : (G.onSide S).Matching) : (G.boundaryEdge S M).val ∈ G.liftedEdges S M := + (G.mem_liftedEdges S M _).mpr (G.boundaryEdge_mem S M) + +omit [Fintype E] [DecidableEq E] in +theorem crosses_of_kept_both (G : LooplessGraph V E) (S : Finset V) (e : E) + (h₁ : G.left e ∈ S ∨ G.right e ∈ S) + (h₂ : G.left e ∈ Sᶜ ∨ G.right e ∈ Sᶜ) : G.Crosses S e := by + simp only [Finset.mem_compl] at h₂ + unfold Crosses + tauto + +omit [Fintype E] in + +theorem lifted_other_subset (G : LooplessGraph V E) (S : Finset V) + (M₁ : (G.onSide S).Matching) (M₂ : (G.onSide Sᶜ).Matching) + (heq : (G.boundaryEdge S M₁).val = (G.boundaryEdge Sᶜ M₂).val) + {e : E} (he : e ∈ G.liftedEdges Sᶜ M₂) + (hkeep : G.left e ∈ S ∨ G.right e ∈ S) : e ∈ G.liftedEdges S M₁ := by + have hc := G.crosses_of_kept_both S e hkeep (G.liftedEdges_keep Sᶜ M₂ he) + have hcb : G.Crosses Sᶜ e := (G.crosses_compl S e).mpr hc + rw [G.lifted_cross_eq_boundary Sᶜ M₂ he hcb, ← heq] + exact G.boundary_mem_lifted S M₁ + +omit [Fintype E] in + +theorem mem_glued_left (G : LooplessGraph V E) (S : Finset V) + (M₁ : (G.onSide S).Matching) (M₂ : (G.onSide Sᶜ).Matching) + (heq : (G.boundaryEdge S M₁).val = (G.boundaryEdge Sᶜ M₂).val) + (e : {e // G.left e ∈ S ∨ G.right e ∈ S}) : + e.val ∈ G.liftedEdges S M₁ ∪ G.liftedEdges Sᶜ M₂ ↔ e ∈ M₁.val := by + simp only [Finset.mem_union] + constructor + · rintro (h | h) + · exact (G.mem_liftedEdges S M₁ e).mp h + · exact (G.mem_liftedEdges S M₁ e).mp (G.lifted_other_subset S M₁ M₂ heq h e.property) + · intro h + exact Or.inl ((G.mem_liftedEdges S M₁ e).mpr h) + +omit [Fintype E] in +theorem mem_glued_right (G : LooplessGraph V E) (S : Finset V) + (M₁ : (G.onSide S).Matching) (M₂ : (G.onSide Sᶜ).Matching) + (heq : (G.boundaryEdge S M₁).val = (G.boundaryEdge Sᶜ M₂).val) + (e : {e // G.left e ∈ Sᶜ ∨ G.right e ∈ Sᶜ}) : + e.val ∈ G.liftedEdges S M₁ ∪ G.liftedEdges Sᶜ M₂ ↔ e ∈ M₂.val := by + simp only [Finset.mem_union] + constructor + · rintro (h | h) + · have hc := G.crosses_of_kept_both S e.val (G.liftedEdges_keep S M₁ h) e.property + have he := (G.lifted_cross_eq_boundary S M₁ h hc).trans heq + apply (G.mem_liftedEdges Sᶜ M₂ e).mp + rw [he] + exact G.boundary_mem_lifted Sᶜ M₂ + · exact (G.mem_liftedEdges Sᶜ M₂ e).mp h + · intro h + exact Or.inr ((G.mem_liftedEdges Sᶜ M₂ e).mpr h) + +omit [Fintype E] in +theorem glued_perfect (G : LooplessGraph V E) (S : Finset V) + (M₁ : (G.onSide S).Matching) (M₂ : (G.onSide Sᶜ).Matching) + (heq : (G.boundaryEdge S M₁).val = (G.boundaryEdge Sᶜ M₂).val) : + G.IsPerfectMatching (G.liftedEdges S M₁ ∪ G.liftedEdges Sᶜ M₂) := by + intro v + by_cases hv : v ∈ S + · obtain ⟨e, ⟨he, hev⟩, hu⟩ := M₁.property (some ⟨v,hv⟩) + have hev' := (G.onSide_incident_some S ⟨v,hv⟩ e).mp hev + refine ⟨e.val, ⟨(G.mem_glued_left S M₁ M₂ heq e).mpr he, hev'⟩, ?_⟩ + rintro f ⟨hf, hfv⟩ + have hk : G.left f ∈ S ∨ G.right f ∈ S := by + rcases hfv with h | h + · exact Or.inl (h.symm ▸ hv) + · exact Or.inr (h.symm ▸ hv) + let f' : {e // G.left e ∈ S ∨ G.right e ∈ S} := ⟨f,hk⟩ + have hf' : f' ∈ M₁.val := (G.mem_glued_left S M₁ M₂ heq f').mp hf + exact congrArg Subtype.val (hu f' ⟨hf', (G.onSide_incident_some S ⟨v,hv⟩ f').mpr hfv⟩) + · have hv' := Finset.mem_compl.mpr hv + obtain ⟨e, ⟨he, hev⟩, hu⟩ := M₂.property (some ⟨v,hv'⟩) + have hev' := (G.onSide_incident_some Sᶜ ⟨v,hv'⟩ e).mp hev + refine ⟨e.val, ⟨(G.mem_glued_right S M₁ M₂ heq e).mpr he, hev'⟩, ?_⟩ + rintro f ⟨hf, hfv⟩ + have hk : G.left f ∈ Sᶜ ∨ G.right f ∈ Sᶜ := by + rcases hfv with h | h + · exact Or.inl (h.symm ▸ hv') + · exact Or.inr (h.symm ▸ hv') + let f' : {e // G.left e ∈ Sᶜ ∨ G.right e ∈ Sᶜ} := ⟨f,hk⟩ + have hf' : f' ∈ M₂.val := (G.mem_glued_right S M₁ M₂ heq f').mp hf + exact congrArg Subtype.val (hu f' ⟨hf', (G.onSide_incident_some Sᶜ ⟨v,hv'⟩ f').mpr hfv⟩) + +def glueMatching (G : LooplessGraph V E) (S : Finset V) + (z : {z : (G.onSide S).Matching × (G.onSide Sᶜ).Matching // + (G.boundaryEdge S z.1).val = (G.boundaryEdge Sᶜ z.2).val}) : G.Matching := + ⟨G.liftedEdges S z.val.1 ∪ G.liftedEdges Sᶜ z.val.2, + G.glued_perfect S z.val.1 z.val.2 z.property⟩ + +omit [Fintype E] in +theorem indicator_glue_left (G : LooplessGraph V E) (S : Finset V) + (z : {z : (G.onSide S).Matching × (G.onSide Sᶜ).Matching // + (G.boundaryEdge S z.1).val = (G.boundaryEdge Sᶜ z.2).val}) + (e : {e // G.left e ∈ S ∨ G.right e ∈ S}) : + G.indicator (G.glueMatching S z) e.val = (G.onSide S).indicator z.val.1 e := by + simp only [indicator, glueMatching, G.mem_glued_left S z.val.1 z.val.2 z.property e] + +omit [Fintype E] in +theorem indicator_glue_right (G : LooplessGraph V E) (S : Finset V) + (z : {z : (G.onSide S).Matching × (G.onSide Sᶜ).Matching // + (G.boundaryEdge S z.1).val = (G.boundaryEdge Sᶜ z.2).val}) + (e : {e // G.left e ∈ Sᶜ ∨ G.right e ∈ Sᶜ}) : + G.indicator (G.glueMatching S z) e.val = (G.onSide Sᶜ).indicator z.val.2 e := by + simp only [indicator, glueMatching, G.mem_glued_right S z.val.1 z.val.2 z.property e] + +omit [Fintype V] [Fintype E] [DecidableEq E] in +theorem boundary_eq_iff_mem (G : LooplessGraph V E) (S : Finset V) + (M : (G.onSide S).Matching) (e : {e // G.left e ∈ S ∨ G.right e ∈ S}) + (hc : G.Crosses S e.val) : (G.boundaryEdge S M).val=e.val ↔ e ∈ M.val := by + constructor + · intro h + have he : G.boundaryEdge S M = e := Subtype.ext h + exact he ▸ G.boundaryEdge_mem S M + · intro h + exact (congrArg Subtype.val (G.eq_boundaryEdge S M h hc)).symm + +omit [Fintype V] in +theorem boundary_fiber (G : LooplessGraph V E) (S : Finset V) + (p : (G.onSide S).Matching → ℝ) (e : {e // G.left e ∈ S ∨ G.right e ∈ S}) + (hc : G.Crosses S e.val) : + fiberMass p (fun M => (G.boundaryEdge S M).val) e.val = (G.onSide S).mean p e := by + unfold fiberMass mean + apply Finset.sum_congr rfl + intro M _ + simp only [G.boundary_eq_iff_mem S M e hc, indicator] + split <;> simp + +omit [Fintype V] in +theorem boundary_fiber_zero (G : LooplessGraph V E) (S : Finset V) + (p : (G.onSide S).Matching → ℝ) (e : E) (hc : ¬G.Crosses S e) : + fiberMass p (fun M => (G.boundaryEdge S M).val) e = 0 := by + apply Finset.sum_eq_zero + intro M _ + have he : (G.boundaryEdge S M).val ≠ e := by + intro h + exact hc (h ▸ G.boundaryEdge_crosses S M) + simp [he] + +theorem couple_laws (G : LooplessGraph V E) (S : Finset V) (x : E → ℝ) + {p : (G.onSide S).Matching → ℝ} {q : (G.onSide Sᶜ).Matching → ℝ} + (hp : p ∈ probabilitySimplex (G.onSide S).Matching) + (hq : q ∈ probabilitySimplex (G.onSide Sᶜ).Matching) + (hpx : ∀ e, (G.onSide S).mean p e = x e.val) + (hqx : ∀ e, (G.onSide Sᶜ).mean q e = x e.val) : + ∃ r, r ∈ G.feasibleLaws x := by + let f := fun M : (G.onSide S).Matching => (G.boundaryEdge S M).val + let g := fun M : (G.onSide Sᶜ).Matching => (G.boundaryEdge Sᶜ M).val + have hc : ∀ e, fiberMass p f e = fiberMass q g e := by + intro e + by_cases he : G.Crosses S e + · have hk : G.left e ∈ S ∨ G.right e ∈ S := he.elim (fun h => Or.inl h.1) (fun h => Or.inr h.2) + have he' := (G.crosses_compl S e).mpr he + have hk' : G.left e ∈ Sᶜ ∨ G.right e ∈ Sᶜ := he'.elim (fun h => Or.inl h.1) (fun h => Or.inr h.2) + rw [G.boundary_fiber S p ⟨e,hk⟩ he, G.boundary_fiber Sᶜ q ⟨e,hk'⟩ he', hpx, hqx] + · have he' : ¬G.Crosses Sᶜ e := fun h => he ((G.crosses_compl S e).mp h) + rw [G.boundary_fiber_zero S p e he, G.boundary_fiber_zero Sᶜ q e he'] + let Z := {z : (G.onSide S).Matching × (G.onSide Sᶜ).Matching // f z.1=g z.2} + let w : Z → ℝ := fun z => jointLaw p q f g z.val + have hw : w ∈ probabilitySimplex Z := compatible_jointLaw_mem_simplex hp hq f g hc + refine ⟨fiberMass w (G.glueMatching S), fiberMass_mem_simplex hw _, ?_⟩ + ext e + rw [mean, fiberMass_expect] + by_cases he : G.left e ∈ S ∨ G.right e ∈ S + · have hi : ∀ z : Z, G.indicator (G.glueMatching S z) e = + (G.onSide S).indicator z.val.1 ⟨e,he⟩ := fun z => G.indicator_glue_left S z ⟨e,he⟩ + simp_rw [hi] + exact (compatible_jointLaw_expect_first hp.1 f g hc + (fun M => (G.onSide S).indicator M ⟨e,he⟩)).trans (hpx ⟨e,he⟩) + · have he' : G.left e ∈ Sᶜ ∨ G.right e ∈ Sᶜ := by + simp only [not_or] at he + exact Or.inl (Finset.mem_compl.mpr he.1) + have hi : ∀ z : Z, G.indicator (G.glueMatching S z) e = + (G.onSide Sᶜ).indicator z.val.2 ⟨e,he'⟩ := fun z => G.indicator_glue_right S z ⟨e,he'⟩ + simp_rw [hi] + exact (compatible_jointLaw_expect_second hq.1 f g hc + (fun M => (G.onSide Sᶜ).indicator M ⟨e,he'⟩)).trans (hqx ⟨e,he'⟩) + +def sideMap (S : Finset V) (v : V) : Option {v // v ∈ S} := + if h : v ∈ S then some ⟨v,h⟩ else none + +def liftVertices (S : Finset V) (T : Finset (Option {v // v ∈ S})) : Finset V := + Finset.univ.filter (fun v => sideMap S v ∈ T) + +@[simp] theorem mem_liftVertices (S : Finset V) + (T : Finset (Option {v // v ∈ S})) (v : V) : + v ∈ liftVertices S T ↔ sideMap S v ∈ T := by simp [liftVertices] + +omit [Fintype V] in +@[simp] theorem sideMap_some (S : Finset V) (v : {v // v ∈ S}) : + sideMap S v.val = some v := by + simp [sideMap, v.property] + +theorem liftVertices_card (S : Finset V) (T : Finset (Option {v // v ∈ S})) + (hn : none ∉ T) : (liftVertices S T).card = T.card := by + apply Finset.card_bij (fun v _ => sideMap S v) + · intro v hv + exact (mem_liftVertices S T v).mp hv + · intro v hv w hw he + have hvS : v ∈ S := by + by_contra h + have hmem := (mem_liftVertices S T v).mp hv + simp only [sideMap, h, ↓reduceDIte] at hmem + exact hn hmem + have hwS : w ∈ S := by + by_contra h + have hmem := (mem_liftVertices S T w).mp hw + simp only [sideMap, h, ↓reduceDIte] at hmem + exact hn hmem + simp only [sideMap, hvS, hwS, ↓reduceDIte, Option.some.injEq] at he + exact congrArg Subtype.val he + · intro t ht + cases t with + | none => exact (hn ht).elim + | some v => exact ⟨v.val, by simpa only [mem_liftVertices, sideMap_some] using ht, sideMap_some S v⟩ + +omit [Fintype E] [DecidableEq E] in +theorem onSide_cut_crosses (G : LooplessGraph V E) (S : Finset V) + (T : Finset (Option {v // v ∈ S})) (e : {e // G.left e ∈ S ∨ G.right e ∈ S}) : + (G.onSide S).Crosses T e ↔ G.Crosses (liftVertices S T) e.val := by + simp only [Crosses, mem_liftVertices] + rfl + +omit [Fintype E] [DecidableEq E] in +theorem crosses_lift_kept (G : LooplessGraph V E) (S : Finset V) + (T : Finset (Option {v // v ∈ S})) (e : E) + (he : G.Crosses (liftVertices S T) e) : G.left e ∈ S ∨ G.right e ∈ S := by + by_contra h + simp only [not_or] at h + simp only [Crosses, mem_liftVertices, sideMap, h.1, h.2, ↓reduceDIte] at he + tauto + +omit [DecidableEq E] in +theorem onSide_cutMass (G : LooplessGraph V E) (S : Finset V) + (x : E → ℝ) (T : Finset (Option {v // v ∈ S})) : + (G.onSide S).cutMass (fun e => x e.val) T = G.cutMass x (liftVertices S T) := by + simp only [cutMass, cut, Finset.sum_filter] + simp_rw [G.onSide_cut_crosses S T] + exact sum_subtype_supported (fun e => G.left e ∈ S ∨ G.right e ∈ S) + (fun e => if G.Crosses (liftVertices S T) e then x e else 0) + (by intro e he; rw [ite_eq_right (fun hc => he (G.crosses_lift_kept S T e hc))]) + +omit [Fintype V] [DecidableEq E] in +theorem onSide_degree_some (G : LooplessGraph V E) (S : Finset V) + (x : E → ℝ) (v : {v // v ∈ S}) : + (G.onSide S).degree (fun e => x e.val) (some v) = G.degree x v.val := by + simp only [degree] + simp_rw [G.onSide_incident_some S v] + apply sum_subtype_supported (fun e => G.left e ∈ S ∨ G.right e ∈ S) + (fun e => if G.Incident v.val e then x e else 0) + intro e he + rw [ite_eq_right] + rintro (h | h) + · exact he (Or.inl (h.symm ▸ v.property)) + · exact he (Or.inr (h.symm ▸ v.property)) + +omit [Fintype V] [DecidableEq E] in +theorem onSide_degree_none (G : LooplessGraph V E) (S : Finset V) (x : E → ℝ) : + (G.onSide S).degree (fun e => x e.val) none = G.cutMass x S := by + simp only [degree, cutMass, cut, Finset.sum_filter] + simp_rw [G.onSide_incident_none S] + apply sum_subtype_supported (fun e => G.left e ∈ S ∨ G.right e ∈ S) + (fun e => if G.Crosses S e then x e else 0) + intro e he + rw [ite_eq_right] + rintro (h | h) + · exact he (Or.inl h.1) + · exact he (Or.inr h.2) + +theorem odd_compl_of_even {W : Type uW} [Fintype W] [DecidableEq W] + (hn : Even (Fintype.card W)) {T : Finset W} (hT : Odd T.card) : Odd Tᶜ.card := by + rcases hn with ⟨k,hk⟩ + rcases hT with ⟨l,hl⟩ + have hle := Finset.card_le_univ T + rw [Finset.card_compl] + refine ⟨k-l-1, ?_⟩ + omega + +omit [DecidableEq E] in + +theorem restriction_mem_constraints (G : LooplessGraph V E) {x : E → ℝ} + (hx : x ∈ G.constraintPolytope) (S : Finset V) (hS : Odd S.card) + (htight : G.cutMass x S = 1) : + (fun e : {e // G.left e ∈ S ∨ G.right e ∈ S} => x e.val) ∈ + (G.onSide S).constraintPolytope := by + refine ⟨fun e => hx.1 e.val, ?_, ?_⟩ + · intro v + cases v with + | none => exact (G.onSide_degree_none S x).trans htight + | some v => exact (G.onSide_degree_some S x v).trans (hx.2.1 v.val) + · intro T hT + by_cases hn : none ∈ T + · have hn' : none ∉ Tᶜ := by simpa using hn + have hnEven : Even (Fintype.card (Option {v // v ∈ S})) := by + simp only [Fintype.card_option, Fintype.card_coe] + exact hS.add_odd odd_one + have hTc := odd_compl_of_even hnEven hT + have hh := hx.2.2 (liftVertices S Tᶜ) (by rwa [liftVertices_card S Tᶜ hn']) + rw [← G.onSide_cutMass S x Tᶜ] at hh + simpa only [cutMass, cut_compl] using hh + · rw [G.onSide_cutMass S x T] + exact hx.2.2 _ (by rwa [liftVertices_card S T hn]) + +end MatchingEntropyBounds.LooplessGraph + +end + +end OAI diff --git a/lean/OAI/Combinatorics/MatchingEntropy/Counting.lean b/lean/OAI/Combinatorics/MatchingEntropy/Counting.lean new file mode 100644 index 0000000000000000000000000000000000000000..d989b2ac7d48b0a01cc25fc21edd96ba91d6433c --- /dev/null +++ b/lean/OAI/Combinatorics/MatchingEntropy/Counting.lean @@ -0,0 +1,189 @@ +import OAI.Combinatorics.MatchingEntropy.EntropyUpper + +namespace OAI + +noncomputable section + +open scoped BigOperators Topology +open Filter + +universe uV uE uI uJ uA uB uC uW uF uD uι + +namespace MatchingEntropyBounds + +variable {V : Type uV} {E : Type uE} [Fintype V] [Fintype E] [DecidableEq V] [DecidableEq E] + +theorem separable_entropy_main (G : LooplessGraph V E) + (_hn : 2 ≤ Fintype.card V) (hPM : Nonempty G.Matching) + (x : E → ℝ) (hx : x ∈ G.polytope) : + separableLower x ≤ maxMatchingEntropy G x ∧ + maxMatchingEntropy G x ≤ binaryEntropy x := + ⟨separable_lower G hPM x hx, maxMatchingEntropy_le_binary G x hx⟩ + +omit [Fintype V] [Fintype E] [DecidableEq V] in + +theorem selected_uniform_mean (G : LooplessGraph V E) {k : ℕ} (hk : 1 ≤ k) + (M : Fin k → G.Matching) + (hdisjoint : ∀ i j, i ≠ j → Disjoint (M i).val (M j).val) : + ∃ x ∈ G.polytope, ∀ e, x e=0 ∨ x e=1/(k:ℝ) := by + classical + have hkR : (0:ℝ) (one_div_pos.mpr hkR).le) hsum + (fun i _ => subset_convexHull ℝ _ (Set.mem_range_self (M i))) + · intro e + dsimp only [x] + simp only [Finset.sum_apply,Pi.smul_apply,smul_eq_mul] + by_cases he : ∃ i, e ∈ (M i).val + · obtain ⟨i,hi⟩ := he + right + rw [Finset.sum_eq_single i] + · simp [LooplessGraph.indicator,hi] + · intro j _ hji + have hj : e ∉ (M j).val := fun h => + Finset.disjoint_left.mp (hdisjoint j i hji) h hi + simp [LooplessGraph.indicator,hj] + · simp + · left + apply Finset.sum_eq_zero + intro i _ + have hi : e ∉ (M i).val := fun h => he ⟨i,h⟩ + simp [LooplessGraph.indicator,hi] + +theorem separableLower_uniform (G : LooplessGraph V E) {r k : ℕ} + (hV : Fintype.card V=2*r) (hk : 2 ≤ k) {x : E → ℝ} (hx : x ∈ G.polytope) + (huniform : ∀ e, x e=0 ∨ x e=1/(k:ℝ)) : + separableLower x = (r:ℝ)*(Real.log (k:ℝ)+ + (3*((k-1:ℕ):ℝ))*Real.log (1-1/(k:ℝ))) := by + have hkR : (0:ℝ) 1/(k:ℝ)) ∈ G.polytope := by + have hkR : (0:ℝ) (one_div_pos.mpr hkR).le,?_,?_⟩ + · intro v + unfold LooplessGraph.degree + rw [← Finset.sum_filter] + simp only [Finset.sum_const,nsmul_eq_mul,hregular] + field_simp + · intro S hS + unfold LooplessGraph.cutMass + simp only [Finset.sum_const,nsmul_eq_mul] + have hc : (k:ℝ) ≤ (G.cut S).card := by exact_mod_cast hodd S hS + calc + 1 = (k:ℝ)*(1/(k:ℝ)) := by field_simp + _ ≤ _ := mul_le_mul_of_nonneg_right hc (one_div_pos.mpr hkR).le + +theorem regular_count_main (G : LooplessGraph V E) (r k : ℕ) + (_hr : 0 Or.inr rfl) + +end MatchingEntropyBounds + +end + +end OAI diff --git a/lean/OAI/Combinatorics/MatchingEntropy/Coupling.lean b/lean/OAI/Combinatorics/MatchingEntropy/Coupling.lean new file mode 100644 index 0000000000000000000000000000000000000000..923522e62fa466165d5c821f629c3a5bfca9c1cd --- /dev/null +++ b/lean/OAI/Combinatorics/MatchingEntropy/Coupling.lean @@ -0,0 +1,174 @@ +import OAI.Combinatorics.MatchingEntropy.Polyhedron + +namespace OAI + +noncomputable section + +open scoped BigOperators Topology +open Filter + +universe uV uE uI uJ uA uB uC uW uF uD uι + +namespace MatchingEntropyBounds + +variable {V : Type uV} {E : Type uE} [Fintype V] [Fintype E] [DecidableEq V] [DecidableEq E] + +def fiberMass {A : Type uA} {C : Type uC} [Fintype A] [DecidableEq C] + (p : A → ℝ) (f : A → C) (c : C) : ℝ := ∑ a, if f a = c then p a else 0 + +theorem fiberMass_nonneg {A : Type uA} {C : Type uC} [Fintype A] [DecidableEq C] + {p : A → ℝ} (hp : ∀ a, 0 ≤ p a) (f : A → C) (c : C) : + 0 ≤ fiberMass p f c := by + apply Finset.sum_nonneg + intro a _ + split <;> simp_all + +theorem le_fiberMass_self {A : Type uA} {C : Type uC} [Fintype A] [DecidableEq C] + {p : A → ℝ} (hp : ∀ a, 0 ≤ p a) (f : A → C) (a : A) : + p a ≤ fiberMass p f (f a) := by + have h := Finset.single_le_sum (s := Finset.univ) (a := a) + (f := fun b => if f b = f a then p b else 0) + (by intro b _; split <;> simp_all) (Finset.mem_univ a) + simpa only [fiberMass, ite_true] using h + +def jointLaw {A : Type uA} {B : Type uB} {C : Type uC} [Fintype A] [Fintype B] [DecidableEq C] + (p : A → ℝ) (q : B → ℝ) (f : A → C) (g : B → C) (z : A × B) : ℝ := + if f z.1 = g z.2 then p z.1*q z.2 / fiberMass p f (f z.1) else 0 + +theorem jointLaw_nonneg {A : Type uA} {B : Type uB} {C : Type uC} [Fintype A] [Fintype B] [DecidableEq C] + {p : A → ℝ} {q : B → ℝ} (hp : ∀ a, 0 ≤ p a) (hq : ∀ b, 0 ≤ q b) + (f : A → C) (g : B → C) (z : A × B) : 0 ≤ jointLaw p q f g z := by + unfold jointLaw + split + · exact div_nonneg (mul_nonneg (hp _) (hq _)) (fiberMass_nonneg hp f _) + · rfl + +theorem jointLaw_first {A : Type uA} {B : Type uB} {C : Type uC} [Fintype A] [Fintype B] [DecidableEq C] + {p : A → ℝ} {q : B → ℝ} (hp : ∀ a, 0 ≤ p a) + (f : A → C) (g : B → C) (hcompat : ∀ c, fiberMass p f c = fiberMass q g c) + (a : A) : (∑ b, jointLaw p q f g (a,b)) = p a := by + have heq : ∀ b, jointLaw p q f g (a,b) = + (p a / fiberMass p f (f a)) * (if g b=f a then q b else 0) := by + intro b + by_cases h : f a=g b + · simp only [jointLaw, h, ite_true] + ring + · simp [jointLaw, h, Ne.symm h] + simp_rw [heq] + rw [← Finset.mul_sum] + change p a / fiberMass p f (f a) * fiberMass q g (f a) = p a + rw [← hcompat] + by_cases hz : fiberMass p f (f a) = 0 + · have ha : p a = 0 := le_antisymm (by simpa [hz] using le_fiberMass_self hp f a) (hp a) + simp [ha] + · exact div_mul_cancel₀ _ hz + +theorem jointLaw_second {A : Type uA} {B : Type uB} {C : Type uC} [Fintype A] [Fintype B] [DecidableEq C] + {p : A → ℝ} {q : B → ℝ} (hq : ∀ b, 0 ≤ q b) + (f : A → C) (g : B → C) (hcompat : ∀ c, fiberMass p f c = fiberMass q g c) + (b : B) : (∑ a, jointLaw p q f g (a,b)) = q b := by + have heq : ∀ a, jointLaw p q f g (a,b) = + (q b / fiberMass q g (g b)) * (if f a=g b then p a else 0) := by + intro a + by_cases h : f a=g b + · simp only [jointLaw, h, ite_true, ← hcompat] + ring + · simp [jointLaw, h] + simp_rw [heq] + rw [← Finset.mul_sum] + change q b / fiberMass q g (g b) * fiberMass p f (g b) = q b + rw [hcompat] + by_cases hz : fiberMass q g (g b) = 0 + · have hb : q b = 0 := le_antisymm (by simpa [hz] using le_fiberMass_self hq g b) (hq b) + simp [hb] + · exact div_mul_cancel₀ _ hz + +theorem jointLaw_mem_simplex {A : Type uA} {B : Type uB} {C : Type uC} [Fintype A] [Fintype B] [DecidableEq C] + {p : A → ℝ} {q : B → ℝ} (hp : p ∈ probabilitySimplex A) (hq : q ∈ probabilitySimplex B) + (f : A → C) (g : B → C) (hcompat : ∀ c, fiberMass p f c = fiberMass q g c) : + jointLaw p q f g ∈ probabilitySimplex (A × B) := by + refine ⟨jointLaw_nonneg hp.1 hq.1 f g, ?_⟩ + rw [Fintype.sum_prod_type] + simp_rw [jointLaw_first hp.1 f g hcompat] + exact hp.2 + +theorem sum_subtype_supported {A : Type uA} [Fintype A] (P : A → Prop) [DecidablePred P] + (w : A → ℝ) (hsupp : ∀ a, ¬P a → w a = 0) : + (∑ a : {a // P a}, w a.val) = ∑ a, w a := by + have hh : (∑ a : {a // ¬P a}, w a.val) = 0 := by + apply Finset.sum_eq_zero + intro a _ + exact hsupp a.val a.property + simpa only [hh, add_zero] using (Fintype.sum_subtype_add_sum_subtype P w) + +theorem compatible_jointLaw_mem_simplex {A : Type uA} {B : Type uB} {C : Type uC} [Fintype A] [Fintype B] [DecidableEq C] + {p : A → ℝ} {q : B → ℝ} (hp : p ∈ probabilitySimplex A) (hq : q ∈ probabilitySimplex B) + (f : A → C) (g : B → C) (hcompat : ∀ c, fiberMass p f c = fiberMass q g c) : + (fun z : {z : A × B // f z.1=g z.2} => jointLaw p q f g z.val) ∈ + probabilitySimplex {z : A × B // f z.1=g z.2} := by + refine ⟨fun z => jointLaw_nonneg hp.1 hq.1 f g z.val, ?_⟩ + rw [sum_subtype_supported (fun z : A × B => f z.1=g z.2) (jointLaw p q f g) + (by intro z hz; simp [jointLaw, hz])] + exact (jointLaw_mem_simplex hp hq f g hcompat).2 + +theorem fiberMass_sum {A : Type uA} {C : Type uC} [Fintype A] [Fintype C] [DecidableEq C] + (p : A → ℝ) (f : A → C) : ∑ c, fiberMass p f c = ∑ a, p a := by + unfold fiberMass + rw [Finset.sum_comm] + simp + +theorem fiberMass_expect {A : Type uA} {C : Type uC} [Fintype A] [Fintype C] [DecidableEq C] + (p : A → ℝ) (f : A → C) (h : C → ℝ) : + ∑ c, fiberMass p f c * h c = ∑ a, p a*h (f a) := by + unfold fiberMass + simp_rw [Finset.sum_mul] + rw [Finset.sum_comm] + apply Finset.sum_congr rfl + intro a _ + simp only [ite_mul, zero_mul] + simp + +theorem fiberMass_mem_simplex {A : Type uA} {C : Type uC} [Fintype A] [Fintype C] [DecidableEq C] + {p : A → ℝ} (hp : p ∈ probabilitySimplex A) (f : A → C) : + fiberMass p f ∈ probabilitySimplex C := + ⟨fiberMass_nonneg hp.1 f, (fiberMass_sum p f).trans hp.2⟩ + +theorem jointLaw_expect_first {A : Type uA} {B : Type uB} {C : Type uC} [Fintype A] [Fintype B] [DecidableEq C] + {p : A → ℝ} {q : B → ℝ} (hp : ∀ a, 0 ≤ p a) + (f : A → C) (g : B → C) (hcompat : ∀ c, fiberMass p f c = fiberMass q g c) + (h : A → ℝ) : ∑ z : A × B, jointLaw p q f g z * h z.1 = ∑ a, p a*h a := by + rw [Fintype.sum_prod_type] + simp_rw [← Finset.sum_mul, jointLaw_first hp f g hcompat] + +theorem jointLaw_expect_second {A : Type uA} {B : Type uB} {C : Type uC} [Fintype A] [Fintype B] [DecidableEq C] + {p : A → ℝ} {q : B → ℝ} (hq : ∀ b, 0 ≤ q b) + (f : A → C) (g : B → C) (hcompat : ∀ c, fiberMass p f c = fiberMass q g c) + (h : B → ℝ) : ∑ z : A × B, jointLaw p q f g z * h z.2 = ∑ b, q b*h b := by + rw [Fintype.sum_prod_type, Finset.sum_comm] + simp_rw [← Finset.sum_mul, jointLaw_second hq f g hcompat] + +theorem compatible_jointLaw_expect_first {A : Type uA} {B : Type uB} {C : Type uC} [Fintype A] [Fintype B] [DecidableEq C] + {p : A → ℝ} {q : B → ℝ} (hp : ∀ a, 0 ≤ p a) + (f : A → C) (g : B → C) (hcompat : ∀ c, fiberMass p f c = fiberMass q g c) + (h : A → ℝ) : + ∑ z : {z : A × B // f z.1=g z.2}, jointLaw p q f g z.val * h z.val.1 = ∑ a, p a*h a := by + rw [sum_subtype_supported (fun z : A × B => f z.1=g z.2) + (fun z => jointLaw p q f g z * h z.1) + (by intro z hz; simp [jointLaw, hz])] + exact jointLaw_expect_first hp f g hcompat h + +theorem compatible_jointLaw_expect_second {A : Type uA} {B : Type uB} {C : Type uC} [Fintype A] [Fintype B] [DecidableEq C] + {p : A → ℝ} {q : B → ℝ} (hq : ∀ b, 0 ≤ q b) + (f : A → C) (g : B → C) (hcompat : ∀ c, fiberMass p f c = fiberMass q g c) + (h : B → ℝ) : + ∑ z : {z : A × B // f z.1=g z.2}, jointLaw p q f g z.val * h z.val.2 = ∑ b, q b*h b := by + rw [sum_subtype_supported (fun z : A × B => f z.1=g z.2) + (fun z => jointLaw p q f g z * h z.2) + (by intro z hz; simp [jointLaw, hz])] + exact jointLaw_expect_second hq f g hcompat h + +end MatchingEntropyBounds + +end + +end OAI diff --git a/lean/OAI/Combinatorics/MatchingEntropy/Covariance.lean b/lean/OAI/Combinatorics/MatchingEntropy/Covariance.lean new file mode 100644 index 0000000000000000000000000000000000000000..318e54673b5451807761d1e6dd79612a039a2fe3 --- /dev/null +++ b/lean/OAI/Combinatorics/MatchingEntropy/Covariance.lean @@ -0,0 +1,158 @@ +import OAI.Combinatorics.MatchingEntropy.Calculus + +namespace OAI + +noncomputable section + +open scoped BigOperators Topology +open Filter + +universe uV uE uI uJ uA uB uC uW uF uD uι + +namespace MatchingEntropyBounds + +variable {V : Type uV} {E : Type uE} [Fintype V] [Fintype E] [DecidableEq V] [DecidableEq E] + +open Matrix + +variable {A : Type uA} {I : Type uI} [Fintype A] [Fintype I] [DecidableEq A] [DecidableEq I] + +def weightedColumns (p : A → ℝ) (b : A → I → ℝ) : Matrix I A ℝ := + fun i a => Real.sqrt (p a) * b a i + +def covariance (p : A → ℝ) (b : A → I → ℝ) : Matrix I I ℝ := + weightedColumns p b * (weightedColumns p b)ᵀ + +omit [DecidableEq A] [DecidableEq I] in +theorem covariance_posSemidef (p : A → ℝ) (b : A → I → ℝ) : + (covariance p b).PosSemidef := by + simpa only [covariance, conjTranspose_eq_transpose_of_trivial] using + posSemidef_self_mul_conjTranspose (weightedColumns p b) + +omit [Fintype I] [DecidableEq A] [DecidableEq I] in +theorem covariance_entry {p : A → ℝ} (hp : ∀ a, 0 ≤ p a) (b : A → I → ℝ) (i j : I) : + covariance p b i j = ∑ a, p a*b a i*b a j := by + unfold covariance + rw [Matrix.mul_apply] + apply Finset.sum_congr rfl + intro a _ + simp only [weightedColumns, Matrix.transpose_apply] + calc + _ = (Real.sqrt (p a))^2 * b a i * b a j := by ring + _ = _ := by rw [Real.sq_sqrt (hp a)] + +omit [DecidableEq A] [DecidableEq I] in +theorem covariance_mulVec {p : A → ℝ} (hp : ∀ a, 0 ≤ p a) (b : A → I → ℝ) + (u : I → ℝ) (i : I) : + (covariance p b *ᵥ u) i = ∑ a, p a*b a i*(b a ⬝ᵥ u) := by + simp only [Matrix.mulVec, dotProduct, covariance_entry hp, Finset.sum_mul] + rw [Finset.sum_comm] + apply Finset.sum_congr rfl + intro a _ + rw [Finset.mul_sum] + apply Finset.sum_congr rfl + intro j _ + ring + +omit [DecidableEq A] [DecidableEq I] in +theorem covariance_quadratic {p : A → ℝ} (hp : ∀ a, 0 ≤ p a) (b : A → I → ℝ) + (u : I → ℝ) : u ⬝ᵥ (covariance p b *ᵥ u) = ∑ a, p a*(b a ⬝ᵥ u)^2 := by + rw [dotProduct] + simp_rw [covariance_mulVec hp, Finset.mul_sum] + rw [Finset.sum_comm] + apply Finset.sum_congr rfl + intro a _ + calc + (∑ i, u i*(p a*b a i*(b a ⬝ᵥ u))) = + (∑ i, b a i*u i)*(p a*(b a ⬝ᵥ u)) := by + rw [Finset.sum_mul] + apply Finset.sum_congr rfl + intro i _ + ring + _ = p a*(b a ⬝ᵥ u)^2 := by rw [← dotProduct]; ring + +def weightedDirectionSpace (p : A → ℝ) (b : A → I → ℝ) : Submodule ℝ (I → ℝ) := + Submodule.span ℝ (Set.range fun a : {a // 0 < p a} => b a.val) + +omit [Fintype A] [Fintype I] [DecidableEq A] [DecidableEq I] in +theorem weightedColumns_span {p : A → ℝ} (hp : ∀ a, 0 ≤ p a) (b : A → I → ℝ) : + Submodule.span ℝ (Set.range (weightedColumns p b).col) = weightedDirectionSpace p b := by + apply le_antisymm + · apply Submodule.span_le.mpr + rintro _ ⟨a,rfl⟩ + by_cases ha : 0 < p a + · have hb : b a ∈ weightedDirectionSpace p b := Submodule.subset_span ⟨⟨a,ha⟩,rfl⟩ + exact Submodule.smul_mem _ (Real.sqrt (p a)) hb + · have hz := le_antisymm (le_of_not_gt ha) (hp a) + have he : (weightedColumns p b).col a = 0 := by + ext i + simp [weightedColumns, Matrix.col, hz] + rw [he] + exact (weightedDirectionSpace p b).zero_mem + · apply Submodule.span_le.mpr + rintro _ ⟨a,rfl⟩ + have hb : (weightedColumns p b).col a.val ∈ + Submodule.span ℝ (Set.range (weightedColumns p b).col) := Submodule.subset_span ⟨a.val,rfl⟩ + have hs : Real.sqrt (p a.val) ≠ 0 := ne_of_gt (Real.sqrt_pos.2 a.property) + have hh := Submodule.smul_mem _ (Real.sqrt (p a.val))⁻¹ hb + have he : (Real.sqrt (p a.val))⁻¹ • (weightedColumns p b).col a.val = b a.val := by + ext i + change (Real.sqrt (p a.val))⁻¹ * (Real.sqrt (p a.val) * b a.val i) = _ + rw [← mul_assoc, inv_mul_cancel₀ hs, one_mul] + rw [he] at hh + exact hh + +omit [DecidableEq A] [DecidableEq I] in +theorem covariance_rank {p : A → ℝ} (hp : ∀ a, 0 ≤ p a) (b : A → I → ℝ) : + (covariance p b).rank = Module.finrank ℝ (weightedDirectionSpace p b) := by + rw [covariance, rank_self_mul_transpose, rank_eq_finrank_span_cols, weightedColumns_span hp] + +def normalizedCentered (v : A → I → ℝ) (x : I → ℝ) (a : A) (i : I) : ℝ := + (v a i-x i)/Real.sqrt (x i) + +omit [Fintype I] [DecidableEq A] [DecidableEq I] in +theorem normalizedCentered_mean {p : A → ℝ} (hp : ∑ a, p a = 1) + (v : A → I → ℝ) (x : I → ℝ) (hx : ∀ i, ∑ a, p a*v a i = x i) (i : I) : + ∑ a, p a*normalizedCentered v x a i = 0 := by + simp only [normalizedCentered, ← mul_div_assoc, mul_sub, ← Finset.sum_div, + Finset.sum_sub_distrib, ← Finset.sum_mul, hp, one_mul, hx, sub_self, zero_div] + +omit [Fintype I] [DecidableEq A] [DecidableEq I] in +theorem normalizedCentered_variance {p : A → ℝ} (hp : ∑ a, p a = 1) + (v : A → I → ℝ) (hv : ∀ a i, (v a i)^2=v a i) (x : I → ℝ) + (hx : ∀ i, ∑ a, p a*v a i = x i) (hxp : ∀ i, 0 < x i) (i : I) : + ∑ a, p a*(normalizedCentered v x a i)^2 = 1-x i := by + have heq : ∀ a, p a*(normalizedCentered v x a i)^2 = + (p a*v a i-2*x i*(p a*v a i)+(x i)^2*p a)/x i := by + intro a + rw [normalizedCentered, div_pow, Real.sq_sqrt (hxp i).le, ← mul_div_assoc] + congr 1 + calc + _ = p a*(v a i)^2-2*x i*(p a*v a i)+(x i)^2*p a := by ring + _ = _ := by rw [hv] + simp_rw [heq] + rw [← Finset.sum_div] + simp only [Finset.sum_add_distrib, Finset.sum_sub_distrib, ← Finset.mul_sum, + hx, hp, mul_one] + field_simp [ne_of_gt (hxp i)] + ring + +omit [DecidableEq A] [DecidableEq I] in +theorem normalized_covariance_trace {p : A → ℝ} (hp : p ∈ probabilitySimplex A) + (v : A → I → ℝ) (hv : ∀ a i, (v a i)^2=v a i) (x : I → ℝ) + (hx : ∀ i, ∑ a, p a*v a i = x i) (hxp : ∀ i, 0 < x i) : + (covariance p (normalizedCentered v x)).trace = Fintype.card I - ∑ i, x i := by + unfold Matrix.trace Matrix.diag + simp_rw [covariance_entry hp.1] + have heq : ∀ i, (∑ a, p a*normalizedCentered v x a i*normalizedCentered v x a i) = 1-x i := by + intro i + simpa only [pow_two, mul_assoc] using + normalizedCentered_variance hp.2 v hv x hx hxp i + simp_rw [heq] + simp + +end MatchingEntropyBounds + +end + +end OAI diff --git a/lean/OAI/Combinatorics/MatchingEntropy/Degenerate.lean b/lean/OAI/Combinatorics/MatchingEntropy/Degenerate.lean new file mode 100644 index 0000000000000000000000000000000000000000..c343e604b7d1d5d3649b57efd2251aa5b924e10d --- /dev/null +++ b/lean/OAI/Combinatorics/MatchingEntropy/Degenerate.lean @@ -0,0 +1,127 @@ +import OAI.Combinatorics.MatchingEntropy.Components + +namespace OAI + +noncomputable section + +open scoped BigOperators Topology +open Filter + +universe uV uE uI uJ uA uB uC uW uF uD uι + +namespace MatchingEntropyBounds.Refined + +variable {V : Type uV} {E : Type uE} [Fintype V] [Fintype E] [DecidableEq V] [DecidableEq E] + +theorem empty_conventions (G : LooplessGraph V E) (hV : Fintype.card V = 0) : + Fintype.card E = 0 ∧ Fintype.card G.Matching = 1 ∧ G.polytope = {0} ∧ + (∀ x ∈ G.polytope, entropy x = 0 ∧ complementEntropy x = 0 ∧ maxMatchingEntropy G x = 0) ∧ + (∀ β : E → ℝ, weightedPartition G β = 1 ∧ weightedObjective β 0 = 0) ∧ + (∀ k : ℕ, 1 ≤ k → (Real.exp (-2) * (k : ℝ))^0 = 1) := by + have : IsEmpty V := Fintype.card_eq_zero_iff.mp hV + have : IsEmpty E := ⟨fun e => isEmptyElim (G.left e)⟩ + let M : G.Matching := ⟨∅,fun v => isEmptyElim v⟩ + have : Nonempty G.Matching := ⟨M⟩ + have : Subsingleton G.Matching := inferInstance + have hc : Fintype.card G.Matching = 1 := by + let : Unique G.Matching := ⟨⟨M⟩, fun _ => Subsingleton.elim _ _⟩ + exact Fintype.card_unique + have hi : G.indicator M = 0 := Subsingleton.elim _ _ + have hp : G.polytope = {0} := by + apply Set.Subset.antisymm + · intro x _ + exact Set.mem_singleton_iff.mpr (Subsingleton.elim _ _) + · rintro x rfl + rw [← hi] + exact subset_convexHull ℝ _ (Set.mem_range_self M) + refine ⟨Fintype.card_eq_zero, hc, hp, ?_, ?_, fun _ _ => pow_zero _⟩ + · intro x hx + have hF : entropy x = 0 := by simp [entropy] + have hB : complementEntropy x = 0 := by simp [complementEntropy, entropy] + refine ⟨hF,hB,le_antisymm ?_ (maxMatchingEntropy_nonneg G hx)⟩ + simpa [hF] using refined_upper G x hx + · intro β + constructor + · simp [weightedPartition, hc] + · simp [weightedObjective, entropy] + +theorem no_matching_polytope {V : Type uV} {E : Type uE} + [Fintype V] [Fintype E] [DecidableEq V] [DecidableEq E] (G : LooplessGraph V E) : + IsEmpty G.Matching ↔ G.polytope = ∅ := by + constructor + · intro hm + have : IsEmpty G.Matching := hm + exact Set.eq_empty_iff_forall_notMem.mpr (fun x hx => by + obtain ⟨M⟩ := matching_nonempty_of_mem G hx + exact isEmptyElim M) + · intro hp + exact ⟨fun M => by + have h := subset_convexHull ℝ (Set.range G.indicator) (Set.mem_range_self M) + change G.indicator M ∈ G.polytope at h + rw [hp] at h + exact h⟩ + +theorem zero_selected_bound {V : Type uV} {E : Type uE} + [Fintype V] [Fintype E] [DecidableEq V] [DecidableEq E] (G : LooplessGraph V E) (m : ℕ) (hm : 0 < m) : + (Real.exp (-2) * (0 : ℝ))^m = 0 ∧ (0 : ℝ) ≤ Fintype.card G.Matching := by + simp [zero_pow (Nat.ne_of_gt hm)] + +theorem zero_regular {V : Type uV} {E : Type uE} + [Fintype V] [Fintype E] [DecidableEq V] [DecidableEq E] (G : LooplessGraph V E) (hV : 0 < Fintype.card V) + (hreg : ∀ v, (Finset.univ.filter (G.Incident v)).card = 0) : + Fintype.card E = 0 ∧ IsEmpty G.Matching := by + have he : IsEmpty E := by + refine ⟨fun e => ?_⟩ + have hh := Finset.card_eq_zero.mp (hreg (G.left e)) + have hm : e ∈ Finset.univ.filter (G.Incident (G.left e)) := by + simp [LooplessGraph.Incident] + rw [hh] at hm + exact Finset.notMem_empty e hm + have : IsEmpty E := he + obtain ⟨v⟩ := Fintype.card_pos_iff.mp hV + exact ⟨Fintype.card_eq_zero, ⟨fun M => by obtain ⟨e,_,_⟩ := M.property v; exact isEmptyElim e⟩⟩ + +theorem one_selected_bound {V : Type uV} {E : Type uE} + [Fintype V] [Fintype E] [DecidableEq V] [DecidableEq E] (G : LooplessGraph V E) (M : G.Matching) : + 1 ≤ Fintype.card G.Matching := Fintype.card_pos_iff.mpr ⟨M⟩ + +theorem one_partition_exact {V : Type uV} {E : Type uE} + [Fintype V] [Fintype E] [DecidableEq V] [DecidableEq E] (G : LooplessGraph V E) (M : G.Matching) + (hcover : M.val = Finset.univ) : Fintype.card G.Matching = 1 := by + have hu : ∀ N : G.Matching, N = M := by + intro N + apply Subtype.ext + apply Finset.Subset.antisymm + · rw [hcover] + exact Finset.subset_univ _ + · intro e he + obtain ⟨f,hf,_⟩ := N.property (G.left e) + have hfm : f ∈ M.val := hcover ▸ Finset.mem_univ f + have hfe := (M.property (G.left e)).unique ⟨hfm,hf.2⟩ ⟨he,Or.inl rfl⟩ + exact hfe ▸ hf.1 + have : Subsingleton G.Matching := ⟨fun a b => (hu a).trans (hu b).symm⟩ + exact by + let : Unique G.Matching := ⟨⟨M⟩, fun _ => Subsingleton.elim _ _⟩ + exact Fintype.card_unique + +theorem pointwise_endpoints (G : LooplessGraph V E) (m : ℕ) + (hm : 0 < m) (hV : Fintype.card V = 2 * m) {x : E → ℝ} (hx : x ∈ G.polytope) : + entropy x - 2 * complementEntropy x ≤ maxMatchingEntropy G x ∧ + (m = 1 → maxMatchingEntropy G x = entropy x) := by + have hl := refined_lower G m hm hV x hx + change entropy x - (2 - 2 / (m : ℝ)) * complementEntropy x ≤ maxMatchingEntropy G x at hl + have hB := B_nonneg G hx + have hmR : (0 : ℝ) < m := by exact_mod_cast hm + constructor + · have hpos := mul_nonneg (div_nonneg (by norm_num : (0:ℝ) ≤ 2) hmR.le) hB + nlinarith + · intro hh + subst m + norm_num at hl + exact le_antisymm (refined_upper G x hx) hl + +end MatchingEntropyBounds.Refined + +end + +end OAI diff --git a/lean/OAI/Combinatorics/MatchingEntropy/Duality.lean b/lean/OAI/Combinatorics/MatchingEntropy/Duality.lean new file mode 100644 index 0000000000000000000000000000000000000000..23f4ca17d4ff9cf03da8016746140ecd35880309 --- /dev/null +++ b/lean/OAI/Combinatorics/MatchingEntropy/Duality.lean @@ -0,0 +1,153 @@ +import OAI.Combinatorics.MatchingEntropy.Optimizer + +namespace OAI + +noncomputable section + +open scoped BigOperators Topology +open Filter + +universe uV uE uI uJ uA uB uC uW uF uD uι + +namespace MatchingEntropyBounds + +variable {V : Type uV} {E : Type uE} [Fintype V] [Fintype E] [DecidableEq V] [DecidableEq E] + +def partition {ι : Type uι} [Fintype ι] (p a : ι → ℝ) (t : ℝ) : ℝ := + ∑ i, p i * Real.exp (t*a i) + +def tiltedLaw {ι : Type uι} [Fintype ι] (p a : ι → ℝ) (t : ℝ) (i : ι) : ℝ := + p i * Real.exp (t*a i) / partition p a t + +theorem partition_pos {ι : Type uι} [Fintype ι] {p : ι → ℝ} + (hp : p ∈ probabilitySimplex ι) (a : ι → ℝ) (t : ℝ) : 0 < partition p a t := by + obtain ⟨i, _, hi⟩ := (Finset.sum_pos_iff_of_nonneg (fun i (_ : i ∈ Finset.univ) => hp.1 i)).mp + (show 0 < ∑ i, p i by rw [hp.2]; norm_num) + exact (Finset.sum_pos_iff_of_nonneg (fun i _ => mul_nonneg (hp.1 i) (Real.exp_pos _).le)).mpr + ⟨i, Finset.mem_univ _, mul_pos hi (Real.exp_pos _)⟩ + +@[simp] theorem partition_zero {ι : Type uι} [Fintype ι] {p : ι → ℝ} + (hp : p ∈ probabilitySimplex ι) (a : ι → ℝ) : partition p a 0 = 1 := by + simpa only [partition, zero_mul, Real.exp_zero, mul_one] using hp.2 + +theorem tiltedLaw_mem_simplex {ι : Type uι} [Fintype ι] {p : ι → ℝ} + (hp : p ∈ probabilitySimplex ι) (a : ι → ℝ) (t : ℝ) : + tiltedLaw p a t ∈ probabilitySimplex ι := by + refine ⟨fun i => div_nonneg (mul_nonneg (hp.1 i) (Real.exp_pos _).le) + (partition_pos hp a t).le, ?_⟩ + simp only [tiltedLaw, ← Finset.sum_div] + exact div_self (partition_pos hp a t).ne' + +theorem entropy_partition_bound {ι : Type uι} [Fintype ι] {p q : ι → ℝ} + (hp : p ∈ probabilitySimplex ι) (hq : q ∈ probabilitySimplex ι) + (hsupp : ∀ i, p i = 0 → q i = 0) (a : ι → ℝ) (t : ℝ) : + entropy q ≤ Real.log (partition p a t) - ∑ i, q i*Real.log (p i) - + t * ∑ i, q i*a i := by + have hlog : ∀ i, q i * Real.log (tiltedLaw p a t i) = + q i * Real.log (p i) + t*(q i*a i) - q i*Real.log (partition p a t) := by + intro i + by_cases hi : p i = 0 + · simp [hsupp i hi] + · rw [tiltedLaw, Real.log_div (mul_ne_zero hi (Real.exp_ne_zero _)) + (partition_pos hp a t).ne', Real.log_mul hi (Real.exp_ne_zero _), Real.log_exp] + ring + calc + entropy q ≤ -∑ i, q i*Real.log (tiltedLaw p a t i) := + entropy_le_crossEntropy (tiltedLaw_mem_simplex hp a t) hq (by + intro i hi + have hii : p i = 0 := by + have := (div_eq_zero_iff).mp hi + rcases this with hh | hh + · exact (mul_eq_zero.mp hh).resolve_right (Real.exp_ne_zero _) + · exact ((partition_pos hp a t).ne' hh).elim + exact hsupp i hii) + _ = _ := by + simp_rw [hlog] + rw [Finset.sum_sub_distrib, Finset.sum_add_distrib, ← Finset.mul_sum, + ← Finset.sum_mul, hq.2, one_mul] + ring + +def linearScore (G : LooplessGraph V E) (u : E → ℝ) (c : ℝ) (M : G.Matching) : ℝ := + (∑ e, u e * G.indicator M e) - c + +omit [Fintype V] [DecidableEq V] in +theorem sum_mean_assoc (G : LooplessGraph V E) (p : G.Matching → ℝ) (u : E → ℝ) : + (∑ M, p M * (∑ e, u e * G.indicator M e)) = ∑ e, u e * G.mean p e := by + simp only [LooplessGraph.mean, Finset.mul_sum] + rw [Finset.sum_comm] + apply Finset.sum_congr rfl + intro e _ + apply Finset.sum_congr rfl + intro M _ + ring + +omit [Fintype V] [DecidableEq V] in +theorem linearScore_expectation (G : LooplessGraph V E) (p : G.Matching → ℝ) + (u : E → ℝ) (c : ℝ) : + (∑ M, p M * linearScore G u c M) = + (∑ e, u e * G.mean p e) - c * ∑ M, p M := by + simp only [linearScore, mul_sub, Finset.sum_sub_distrib, ← Finset.sum_mul] + rw [sum_mean_assoc] + ring + +omit [Fintype V] [DecidableEq V] in + +theorem matching_entropy_dual_bound (G : LooplessGraph V E) {y : E → ℝ} + {p : G.Matching → ℝ} (hp : p ∈ G.feasibleLaws y) + (hopt : entropy p = maxMatchingEntropy G y) + {r : G.Matching → ℝ} (hr : r ∈ probabilitySimplex G.Matching) + (hrsupport : ∀ M, p M = 0 → r M = 0) + (u : E → ℝ) (c t : ℝ) : + maxMatchingEntropy G (G.mean r) ≤ + Real.log (partition p (linearScore G u c) t) - ∑ M, r M * Real.log (p M) - + t * ∑ M, r M * linearScore G u c M := by + obtain ⟨q, hq, heq⟩ := maxMatchingEntropy_attained G (G.mean_mem_polytope hr) + have hsuppq := matching_optimizer_face_support G hp hopt hq.1 hr hq.2 hrsupport + have hmean : G.mean (q-r) = 0 := by + change G.meanLinear (q-r) = 0 + rw [map_sub] + change G.mean q-G.mean r = 0 + rw [hq.2, sub_self] + have hsum : ∑ M, (q-r) M = 0 := by + simp only [Pi.sub_apply, Finset.sum_sub_distrib, hq.1.2, hr.2, sub_self] + have hlog := matching_optimizer_log_annihilates G hp hopt (q-r) hsum hmean + (fun M hM => by simp [hsuppq M hM, hrsupport M hM]) + simp only [Pi.sub_apply, sub_mul, Finset.sum_sub_distrib, sub_eq_zero] at hlog + have hscore : (∑ M, q M*linearScore G u c M) = ∑ M, r M*linearScore G u c M := by + rw [linearScore_expectation, linearScore_expectation, hq.2, hq.1.2, hr.2] + rw [← heq] + simpa only [hlog, hscore] using entropy_partition_bound hp.1 hq.1 hsuppq + (linearScore G u c) t + +theorem partition_hasDerivAt {ι : Type uι} [Fintype ι] (p a : ι → ℝ) (t : ℝ) : + HasDerivAt (partition p a) (partition (fun i => p i*a i) a t) t := by + apply HasDerivAt.fun_sum + intro i _ + simpa only [one_mul, id_eq, mul_assoc, mul_comm, mul_left_comm] using + (((hasDerivAt_id t).mul_const (a i)).exp.const_mul (p i)) + +theorem logPartition_hasDerivAt {ι : Type uι} [Fintype ι] {p : ι → ℝ} + (hp : p ∈ probabilitySimplex ι) (a : ι → ℝ) (t : ℝ) : + HasDerivAt (fun t => Real.log (partition p a t)) + (partition (fun i => p i*a i) a t / partition p a t) t := + (partition_hasDerivAt p a t).log (partition_pos hp a t).ne' + +theorem logPartition_second {ι : Type uι} [Fintype ι] {p : ι → ℝ} + (hp : p ∈ probabilitySimplex ι) (a : ι → ℝ) : + HasDerivAt (fun t => partition (fun i => p i*a i) a t / partition p a t) + ((∑ i, p i*(a i)^2) - (∑ i, p i*a i)^2) 0 := by + have hd := (partition_hasDerivAt (fun i => p i*a i) a 0).div + (partition_hasDerivAt p a 0) (partition_pos hp a 0).ne' + refine hd.congr_deriv ?_ + simp only [partition, zero_mul, Real.exp_zero, mul_one, hp.2, one_pow, div_one] + congr 1 + · apply Finset.sum_congr rfl + intro i _ + ring + · ring + +end MatchingEntropyBounds + +end + +end OAI diff --git a/lean/OAI/Combinatorics/MatchingEntropy/EdgeReduction.lean b/lean/OAI/Combinatorics/MatchingEntropy/EdgeReduction.lean new file mode 100644 index 0000000000000000000000000000000000000000..25f67df0d72a9a0e5d3006de706750ceba1dddae --- /dev/null +++ b/lean/OAI/Combinatorics/MatchingEntropy/EdgeReduction.lean @@ -0,0 +1,318 @@ +import OAI.Combinatorics.MatchingEntropy.SeparableCovariance + +namespace OAI + +noncomputable section + +open scoped BigOperators Topology +open Filter + +universe uV uE uI uJ uA uB uC uW uF uD uι + +namespace MatchingEntropyBounds + +namespace LooplessGraph +variable {V : Type uV} {E : Type uE} [Fintype V] [Fintype E] [DecidableEq V] [DecidableEq E] + +def RemainingVertex (G : LooplessGraph V E) (e₀ : E) (v : V) : Prop := + ¬G.Incident v e₀ + +instance remainingVertexDecidable (G : LooplessGraph V E) (e₀ : E) (v : V) : + Decidable (G.RemainingVertex e₀ v) := inferInstanceAs (Decidable (¬G.Incident v e₀)) + +def RemainingEdge (G : LooplessGraph V E) (e₀ e : E) : Prop := + G.RemainingVertex e₀ (G.left e) ∧ G.RemainingVertex e₀ (G.right e) + +instance remainingEdgeDecidable (G : LooplessGraph V E) (e₀ e : E) : + Decidable (G.RemainingEdge e₀ e) := inferInstanceAs + (Decidable (G.RemainingVertex e₀ (G.left e) ∧ G.RemainingVertex e₀ (G.right e))) + +def deleteEndpoints (G : LooplessGraph V E) (e₀ : E) : + LooplessGraph {v // G.RemainingVertex e₀ v} {e // G.RemainingEdge e₀ e} where + left e := ⟨G.left e.val, e.property.1⟩ + right e := ⟨G.right e.val, e.property.2⟩ + loopless e he := G.loopless e.val (congrArg Subtype.val he) + +omit [Fintype V] [Fintype E] [DecidableEq V] [DecidableEq E] in +theorem remainingEdge_ne (G : LooplessGraph V E) (e₀ : E) + {e : E} (he : G.RemainingEdge e₀ e) : e ≠ e₀ := by + rintro rfl + exact he.1 (Or.inl rfl) + +omit [Fintype V] [Fintype E] [DecidableEq V] [DecidableEq E] in +theorem remaining_of_incident (G : LooplessGraph V E) (e₀ : E) + {e : E} (he : G.RemainingEdge e₀ e) {v : V} (hv : G.Incident v e) : + G.RemainingVertex e₀ v := by + rcases hv with h | h + · exact h ▸ he.1 + · exact h ▸ he.2 + +omit [Fintype V] [Fintype E] [DecidableEq V] [DecidableEq E] in +@[simp] theorem deleteEndpoints_incident (G : LooplessGraph V E) (e₀ : E) + (v : {v // G.RemainingVertex e₀ v}) (e : {e // G.RemainingEdge e₀ e}) : + (G.deleteEndpoints e₀).Incident v e ↔ G.Incident v.val e.val := by + simp only [Incident, deleteEndpoints, Subtype.ext_iff] + +omit [Fintype V] [Fintype E] [DecidableEq V] [DecidableEq E] in +theorem matching_common_vertex (G : LooplessGraph V E) (M : G.Matching) + {e f : E} (he : e ∈ M.val) (hf : f ∈ M.val) {v : V} + (hve : G.Incident v e) (hvf : G.Incident v f) : e=f := by + obtain ⟨g, _, hg⟩ := M.property v + exact (hg e ⟨he,hve⟩).trans (hg f ⟨hf,hvf⟩).symm + +omit [Fintype V] [Fintype E] [DecidableEq V] [DecidableEq E] in + +theorem matching_remaining (G : LooplessGraph V E) (e₀ : E) (M : G.Matching) + (h₀ : e₀ ∈ M.val) {e : E} (he : e ∈ M.val) (hne : e ≠ e₀) : + G.RemainingEdge e₀ e := by + constructor + · intro hv + exact hne (G.matching_common_vertex M he h₀ (Or.inl rfl) hv) + · intro hv + exact hne (G.matching_common_vertex M he h₀ (Or.inr rfl) hv) + +def addForced (G : LooplessGraph V E) (e₀ : E) (N : (G.deleteEndpoints e₀).Matching) : + G.Matching := by + refine ⟨insert e₀ (N.val.image Subtype.val), ?_⟩ + intro v + by_cases hv : G.Incident v e₀ + · refine ⟨e₀, ⟨by simp, hv⟩, ?_⟩ + rintro f ⟨hf,hfv⟩ + rcases Finset.mem_insert.mp hf with h | h + · exact h + · obtain ⟨g,_,rfl⟩ := Finset.mem_image.mp h + exact False.elim (G.remaining_of_incident e₀ g.property hfv hv) + · let v' : {v // G.RemainingVertex e₀ v} := ⟨v,hv⟩ + obtain ⟨f,⟨hf,hfv⟩, hu⟩ := N.property v' + refine ⟨f.val, ⟨Finset.mem_insert_of_mem (Finset.mem_image.mpr ⟨f,hf,rfl⟩), + (G.deleteEndpoints_incident e₀ v' f).mp hfv⟩, ?_⟩ + rintro g ⟨hg,hgv⟩ + rcases Finset.mem_insert.mp hg with h | h + · exact False.elim (hv (h ▸ hgv)) + · obtain ⟨g',hg',rfl⟩ := Finset.mem_image.mp h + exact congrArg Subtype.val (hu g' ⟨hg', (G.deleteEndpoints_incident e₀ v' g').mpr hgv⟩) + +omit [Fintype V] [Fintype E] in +@[simp] theorem mem_addForced (G : LooplessGraph V E) (e₀ : E) + (N : (G.deleteEndpoints e₀).Matching) (e : E) : + e ∈ (G.addForced e₀ N).val ↔ e=e₀ ∨ ∃ h : G.RemainingEdge e₀ e, ⟨e,h⟩ ∈ N.val := by + simp only [addForced, Finset.mem_insert, Finset.mem_image] + constructor + · rintro (h | ⟨f,hf,rfl⟩) + · exact Or.inl h + · exact Or.inr ⟨f.property,hf⟩ + · rintro (h | ⟨h,he⟩) + · exact Or.inl h + · exact Or.inr ⟨⟨e,h⟩,he,rfl⟩ + +omit [Fintype V] [Fintype E] in +@[simp] theorem mem_addForced_remaining (G : LooplessGraph V E) (e₀ : E) + (N : (G.deleteEndpoints e₀).Matching) (e : {e // G.RemainingEdge e₀ e}) : + e.val ∈ (G.addForced e₀ N).val ↔ e ∈ N.val := by + rw [mem_addForced] + simp only [G.remainingEdge_ne e₀ e.property, false_or] + exact ⟨fun ⟨_,h⟩ => h, fun h => ⟨e.property,h⟩⟩ + +def removeForced (G : LooplessGraph V E) (e₀ : E) + (M : {M : G.Matching // e₀ ∈ M.val}) : (G.deleteEndpoints e₀).Matching := by + refine ⟨M.val.val.subtype (G.RemainingEdge e₀), ?_⟩ + intro v + obtain ⟨e,⟨he,hev⟩,hu⟩ := M.val.property v.val + have hne : e ≠ e₀ := by rintro rfl; exact v.property hev + have hrem := G.matching_remaining e₀ M.val M.property he hne + refine ⟨⟨e,hrem⟩, ⟨by simpa using he, + (G.deleteEndpoints_incident e₀ v ⟨e,hrem⟩).mpr hev⟩, ?_⟩ + rintro f ⟨hf,hfv⟩ + apply Subtype.ext + exact hu f.val ⟨by simpa using hf, (G.deleteEndpoints_incident e₀ v f).mp hfv⟩ + +omit [Fintype V] [Fintype E] [DecidableEq E] in +@[simp] theorem mem_removeForced (G : LooplessGraph V E) (e₀ : E) + (M : {M : G.Matching // e₀ ∈ M.val}) (e : {e // G.RemainingEdge e₀ e}) : + e ∈ (G.removeForced e₀ M).val ↔ e.val ∈ M.val.val := by + simp [removeForced] + +def forcedMatchingEquiv (G : LooplessGraph V E) (e₀ : E) : + (G.deleteEndpoints e₀).Matching ≃ {M : G.Matching // e₀ ∈ M.val} where + toFun N := ⟨G.addForced e₀ N, (G.mem_addForced e₀ N e₀).mpr (Or.inl rfl)⟩ + invFun M := G.removeForced e₀ M + left_inv N := by + apply Subtype.ext + ext e + exact (G.mem_removeForced e₀ _ e).trans (G.mem_addForced_remaining e₀ N e) + right_inv M := by + apply Subtype.ext + apply Subtype.ext + ext e + rw [mem_addForced] + constructor + · rintro (rfl | ⟨h,he⟩) + · exact M.property + · exact (G.mem_removeForced e₀ M ⟨e,h⟩).mp he + · intro he + by_cases h : e=e₀ + · exact Or.inl h + · exact Or.inr ⟨G.matching_remaining e₀ M.val M.property he h, + (G.mem_removeForced e₀ M _).mpr he⟩ + +omit [Fintype V] [Fintype E] in +theorem addForced_injective (G : LooplessGraph V E) (e₀ : E) : + Function.Injective (G.addForced e₀) := by + intro N N' h + apply (G.forcedMatchingEquiv e₀).injective + exact Subtype.ext h + +omit [Fintype E] [DecidableEq E] in +theorem remaining_vertex_card (G : LooplessGraph V E) (e₀ : E) : + Fintype.card {v // G.RemainingVertex e₀ v} + 2 = Fintype.card V := by + have he : Fintype.card {v // G.Incident v e₀}=2 := by + rw [Fintype.card_subtype] + have hf : Finset.univ.filter (fun v => G.Incident v e₀)={G.left e₀, G.right e₀} := by + ext v + simp [Incident, eq_comm] + rw [hf, Finset.card_pair (G.loopless e₀)] + have h := Fintype.card_subtype_compl (G.Incident · e₀) + have hle := Fintype.card_subtype_le (G.Incident · e₀) + change Fintype.card {v // ¬G.Incident v e₀} + 2 = Fintype.card V + omega + +omit [Fintype V] [Fintype E] in +@[simp] theorem range_addForced (G : LooplessGraph V E) (e₀ : E) (M : G.Matching) : + M ∈ Set.range (G.addForced e₀) ↔ e₀ ∈ M.val := by + constructor + · rintro ⟨N,rfl⟩ + exact (G.mem_addForced e₀ N e₀).mpr (Or.inl rfl) + · intro h + refine ⟨G.removeForced e₀ ⟨M,h⟩, ?_⟩ + exact congrArg Subtype.val ((G.forcedMatchingEquiv e₀).apply_symm_apply ⟨M,h⟩) + +omit [Fintype V] [DecidableEq V] in +theorem law_support_of_mean_one (G : LooplessGraph V E) {p : G.Matching → ℝ} + (hp : p ∈ probabilitySimplex G.Matching) {e₀ : E} (he : G.mean p e₀=1) + (M : G.Matching) (hM : e₀ ∉ M.val) : p M=0 := by + have hz : ∑ N, p N*(1-G.indicator N e₀)=0 := by + simp only [mul_sub, mul_one, Finset.sum_sub_distrib, hp.2] + change 1-G.mean p e₀=0 + rw [he, sub_self] + have hh := (Finset.sum_eq_zero_iff_of_nonneg + (fun N (_ : N ∈ Finset.univ) => + mul_nonneg (hp.1 N) (sub_nonneg.mpr (G.indicator_le_one N e₀)))).mp hz M (by simp) + simpa [indicator,hM] using hh + +omit [Fintype V] in + +theorem forcedLaw_feasible (G : LooplessGraph V E) {x : E → ℝ} + {p : G.Matching → ℝ} (hp : p ∈ G.feasibleLaws x) (e₀ : E) (he : x e₀=1) : + (fun N => p (G.addForced e₀ N)) ∈ (G.deleteEndpoints e₀).feasibleLaws + (fun e => x e.val) := by + have hs : ∀ M, e₀ ∉ M.val → p M=0 := + G.law_support_of_mean_one hp.1 (by rw [hp.2,he]) + refine ⟨⟨fun N => hp.1.1 _, ?_⟩, ?_⟩ + · rw [← hp.1.2] + apply Fintype.sum_of_injective (G.addForced e₀) (G.addForced_injective e₀) + · intro M hM + exact hs M (fun hh => hM ((G.range_addForced e₀ M).mpr hh)) + · intro N + rfl + · funext e + rw [← congrFun hp.2 e.val] + apply Fintype.sum_of_injective (G.addForced e₀) (G.addForced_injective e₀) + · intro M hM + rw [hs M (fun hh => hM ((G.range_addForced e₀ M).mpr hh)),zero_mul] + · intro N + simp only [indicator,mem_addForced_remaining] + +omit [Fintype V] [DecidableEq V] in + +theorem forced_coordinate_zero (G : LooplessGraph V E) {x : E → ℝ} + (hx : x ∈ G.polytope) (e₀ : E) (he : x e₀=1) {e : E} + (hneq : e ≠ e₀) (hrem : ¬G.RemainingEdge e₀ e) : x e=0 := by + obtain ⟨p,hp⟩ := (G.mem_polytope_iff x).mp hx + rw [← congrFun hp.2 e] + apply Finset.sum_eq_zero + intro M _ + by_cases hM : e₀ ∈ M.val + · have hh : e ∉ M.val := fun hh => hrem (G.matching_remaining e₀ M hM hh hneq) + simp [indicator,hh] + · rw [G.law_support_of_mean_one hp.1 (by rw [hp.2,he]) M hM,zero_mul] + +omit [Fintype V] in + +theorem separableLower_forced (G : LooplessGraph V E) {x : E → ℝ} + (hx : x ∈ G.polytope) (e₀ : E) (he : x e₀=1) : + separableLower (fun e : {e // G.RemainingEdge e₀ e} => x e.val)=separableLower x := by + have hz : ∀ e, ¬G.RemainingEdge e₀ e → + Real.negMulLog (x e)=0 ∧ Real.negMulLog (1-x e)=0 := by + intro e h + by_cases hneq : e=e₀ + · simp [hneq,he] + · simp [G.forced_coordinate_zero hx e₀ he hneq h] + unfold separableLower entropy + rw [sum_subtype_supported _ _ (fun e h => (hz e h).1), + sum_subtype_supported _ _ (fun e h => (hz e h).2)] + +end LooplessGraph + +theorem entropy_fiberMass_injective {A : Type uA} {B : Type uB} [Fintype A] [Fintype B] [DecidableEq B] + (p : A → ℝ) (f : A → B) (hf : Function.Injective f) : + entropy (fiberMass p f)=entropy p := by + classical + have hself (a : A) : fiberMass p f (f a)=p a := by + simp [fiberMass,hf.eq_iff] + have hzero (b : B) (hb : b ∉ Set.range f) : fiberMass p f b=0 := by + apply Finset.sum_eq_zero + intro a _ + exact ite_eq_right (fun h => hb ⟨a,h⟩) + symm + apply Fintype.sum_of_injective f hf + · intro b hb + rw [hzero b hb,Real.negMulLog_zero] + · intro a + rw [hself] + +namespace LooplessGraph +variable {V : Type uV} {E : Type uE} [Fintype V] [Fintype E] [DecidableEq V] [DecidableEq E] +omit [Fintype V] in + +theorem liftForced_feasible (G : LooplessGraph V E) {x : E → ℝ} + (hx : x ∈ G.polytope) (e₀ : E) (he : x e₀=1) + {q : (G.deleteEndpoints e₀).Matching → ℝ} + (hq : q ∈ (G.deleteEndpoints e₀).feasibleLaws (fun e => x e.val)) : + fiberMass q (G.addForced e₀) ∈ G.feasibleLaws x := by + refine ⟨fiberMass_mem_simplex hq.1 _, ?_⟩ + funext e + rw [mean,fiberMass_expect] + by_cases heq : e=e₀ + · subst e + simpa [indicator] using hq.1.2.trans he.symm + · by_cases hr : G.RemainingEdge e₀ e + · change (∑ N, q N*G.indicator (G.addForced e₀ N) e)=_ + have hm (N : (G.deleteEndpoints e₀).Matching) : + G.indicator (G.addForced e₀ N) e = (G.deleteEndpoints e₀).indicator N ⟨e,hr⟩ := by + simp only [indicator,G.mem_addForced_remaining e₀ N ⟨e,hr⟩] + simp_rw [hm] + exact congrFun hq.2 ⟨e,hr⟩ + · rw [G.forced_coordinate_zero hx e₀ he heq hr] + apply Finset.sum_eq_zero + intro N _ + simp [indicator,heq,hr] + +omit [Fintype V] in + +theorem maxMatchingEntropy_forced_le (G : LooplessGraph V E) {x : E → ℝ} + (hx : x ∈ G.polytope) (e₀ : E) (he : x e₀=1) : + maxMatchingEntropy (G.deleteEndpoints e₀) (fun e => x e.val) ≤ maxMatchingEntropy G x := by + obtain ⟨p,hp⟩ := (G.mem_polytope_iff x).mp hx + have hr := G.forcedLaw_feasible hp e₀ he + have hx' := ((G.deleteEndpoints e₀).mem_polytope_iff _).mpr ⟨_,hr⟩ + obtain ⟨q,hq,hopt⟩ := maxMatchingEntropy_attained (G.deleteEndpoints e₀) hx' + rw [← hopt,← entropy_fiberMass_injective q _ (G.addForced_injective e₀)] + exact entropy_le_maxMatchingEntropy G (G.liftForced_feasible hx e₀ he hq) + +end LooplessGraph + +end MatchingEntropyBounds + +end + +end OAI diff --git a/lean/OAI/Combinatorics/MatchingEntropy/EightVertex.lean b/lean/OAI/Combinatorics/MatchingEntropy/EightVertex.lean new file mode 100644 index 0000000000000000000000000000000000000000..92623e9006c538271d1eae19324c011783330462 --- /dev/null +++ b/lean/OAI/Combinatorics/MatchingEntropy/EightVertex.lean @@ -0,0 +1,260 @@ +import OAI.Combinatorics.MatchingEntropy.KleeSharpness + +namespace OAI + +noncomputable section + +open scoped BigOperators Topology +open Filter + +universe uV uE uI uJ uA uB uC uW uF uD uι + +namespace MatchingEntropyBounds.Refined + +def obstructionGraph : LooplessGraph (Fin 8) (Fin 12) where + left := ![0,0,0,1,1,2,2,2,3,5,5,6] + right := ![1,3,5,4,6,3,4,7,4,6,7,7] + loopless := by intro e; fin_cases e <;> decide + +def obstructionEdges (i : Fin 5) : Finset (Fin 12) := + ![{0,7,8,9}, {1,4,6,10}, {2,3,5,11}, {1,3,7,9}, {2,4,7,8}] i + +def obstructionUniform : Fin 12 → ℝ := fun _ => 1 / 3 + +def obstructionLaw : obstructionGraph.Matching → ℝ := + fun M => ∑ i : Fin 3, if M.val = obstructionEdges i.castSucc.castSucc then 1 / 3 else 0 + +theorem obstruction_simple : IsSimpleLabelled obstructionGraph := by + unfold IsSimpleLabelled obstructionGraph + decide + +theorem obstruction_matching (i : Fin 5) : obstructionGraph.IsPerfectMatching (obstructionEdges i) := by + unfold LooplessGraph.IsPerfectMatching LooplessGraph.Incident obstructionGraph ExistsUnique + fin_cases i <;> decide + +def obstructionMatching (i : Fin 5) : obstructionGraph.Matching := ⟨obstructionEdges i,obstruction_matching i⟩ + +theorem obstructionEdges_injective : Function.Injective obstructionEdges := by + unfold Function.Injective obstructionEdges + decide + +theorem obstructionMatching_injective : Function.Injective obstructionMatching := by + intro i j h + exact obstructionEdges_injective (congrArg Subtype.val h) + +theorem obstruction_binary_classify (a b c d e f g h i j k l : ℕ) + (h0 : a+b+c=1) (h1 : a+d+e=1) (h2 : f+g+h=1) (h3 : b+f+i=1) + (h4 : d+g+i=1) (h5 : c+j+k=1) (h6 : e+j+l=1) (h7 : h+k+l=1) : + (a=1 ∧ b=0 ∧ c=0 ∧ d=0 ∧ e=0 ∧ f=0 ∧ g=0 ∧ h=1 ∧ i=1 ∧ j=1 ∧ k=0 ∧ l=0) ∨ + (a=0 ∧ b=1 ∧ c=0 ∧ d=0 ∧ e=1 ∧ f=0 ∧ g=1 ∧ h=0 ∧ i=0 ∧ j=0 ∧ k=1 ∧ l=0) ∨ + (a=0 ∧ b=0 ∧ c=1 ∧ d=1 ∧ e=0 ∧ f=1 ∧ g=0 ∧ h=0 ∧ i=0 ∧ j=0 ∧ k=0 ∧ l=1) ∨ + (a=0 ∧ b=1 ∧ c=0 ∧ d=1 ∧ e=0 ∧ f=0 ∧ g=0 ∧ h=1 ∧ i=0 ∧ j=1 ∧ k=0 ∧ l=0) ∨ + (a=0 ∧ b=0 ∧ c=1 ∧ d=0 ∧ e=1 ∧ f=0 ∧ g=0 ∧ h=1 ∧ i=1 ∧ j=0 ∧ k=0 ∧ l=0) := by + rcases (show a = 1 ∨ b = 1 ∨ c = 1 by omega) with ha | hb | hc + · left + omega + · rcases (show d = 0 ∨ d = 1 by omega) with hd | hd + · right; left; omega + · right; right; right; left; omega + · rcases (show d = 0 ∨ d = 1 by omega) with hd | hd + · right; right; right; right; omega + · right; right; left; omega + +theorem obstruction_classify (M : obstructionGraph.Matching) : ∃ i : Fin 5, M = obstructionMatching i := by + let a : Fin 12 → ℕ := fun e => if e ∈ M.val then 1 else 0 + have hadeg (v : Fin 8) : (∑ e : Fin 12, if obstructionGraph.Incident v e then a e else 0) = 1 := by + obtain ⟨e,he,hu⟩ := M.property v + rw [Finset.sum_eq_single e] + · simp [he,a] + · intro f _ hfe + by_cases hf : obstructionGraph.Incident v f + · have hfm : f ∉ M.val := fun h => hfe (hu f ⟨h,hf⟩) + simp [hf,a,hfm] + · simp [hf] + · simp + have h0 := hadeg 0 + have h1 := hadeg 1 + have h2 := hadeg 2 + have h3 := hadeg 3 + have h4 := hadeg 4 + have h5 := hadeg 5 + have h6 := hadeg 6 + have h7 := hadeg 7 + simp +decide [obstructionGraph,LooplessGraph.Incident,Fin.sum_univ_succ] at h0 h1 h2 h3 h4 h5 h6 h7 + have hcases := obstruction_binary_classify (a 0) (a 1) (a 2) (a 3) (a 4) (a 5) + (a 6) (a 7) (a 8) (a 9) (a 10) (a 11) (by omega) (by omega) (by omega) (by omega) + (by omega) (by omega) (by omega) (by omega) + clear hadeg h0 h1 h2 h3 h4 h5 h6 h7 + rcases hcases with hh | hh | hh | hh | hh + all_goals simp [a] at hh + · refine ⟨0,Subtype.ext ?_⟩ + ext e + fin_cases e <;> simp_all +decide + · refine ⟨1,Subtype.ext ?_⟩ + ext e + fin_cases e <;> simp_all +decide + · refine ⟨2,Subtype.ext ?_⟩ + ext e + fin_cases e <;> simp_all +decide + · refine ⟨3,Subtype.ext ?_⟩ + ext e + fin_cases e <;> simp_all +decide + · refine ⟨4,Subtype.ext ?_⟩ + ext e + fin_cases e <;> simp_all +decide + +def obstructionEquiv : Fin 5 ≃ obstructionGraph.Matching := + Equiv.ofBijective obstructionMatching ⟨obstructionMatching_injective, + fun M => by obtain ⟨i,hi⟩ := obstruction_classify M; exact ⟨i,hi.symm⟩⟩ + +def obstructionSelected (i : Fin 3) : obstructionGraph.Matching := + obstructionMatching (i.castSucc.castSucc) + +theorem obstructionSelected_injective : Function.Injective obstructionSelected := by + intro i j h + exact Fin.ext (congrArg (fun k : Fin 5 => k.val) (obstructionMatching_injective h)) + +theorem obstruction_law_eq_fiber : + obstructionLaw = fiberMass (uniformLaw (Fin 3)) obstructionSelected := by + ext M + unfold obstructionLaw fiberMass + apply Finset.sum_congr rfl + intro i _ + have he : obstructionSelected i = M ↔ M.val = obstructionEdges i.castSucc.castSucc := by + rw [Subtype.ext_iff] + exact eq_comm + simp [he,uniformLaw] + +theorem obstruction_law_mean : obstructionGraph.mean obstructionLaw = obstructionUniform := by + ext e + rw [obstruction_law_eq_fiber,LooplessGraph.mean,fiberMass_expect] + fin_cases e <;> simp +decide [obstructionSelected,obstructionMatching,obstructionEdges, + uniformLaw,LooplessGraph.indicator,obstructionUniform,Fin.sum_univ_succ] + +theorem obstruction_law_feasible : obstructionLaw ∈ obstructionGraph.feasibleLaws obstructionUniform := by + refine ⟨?_,obstruction_law_mean⟩ + rw [obstruction_law_eq_fiber] + exact fiberMass_mem_simplex uniformLaw_simplex _ + +theorem obstruction_uniform_mem : obstructionUniform ∈ obstructionGraph.polytope := + (obstructionGraph.mem_polytope_iff _).mpr ⟨_,obstruction_law_feasible⟩ + +theorem obstruction_mean_coordinates (p : obstructionGraph.Matching → ℝ) : + obstructionGraph.mean p = + ![p (obstructionMatching 0), p (obstructionMatching 1) + p (obstructionMatching 3), + p (obstructionMatching 2) + p (obstructionMatching 4), + p (obstructionMatching 2) + p (obstructionMatching 3), + p (obstructionMatching 1) + p (obstructionMatching 4), + p (obstructionMatching 2), p (obstructionMatching 1), + p (obstructionMatching 0) + p (obstructionMatching 3) + p (obstructionMatching 4), + p (obstructionMatching 0) + p (obstructionMatching 4), + p (obstructionMatching 0) + p (obstructionMatching 3), + p (obstructionMatching 1), p (obstructionMatching 2)] := by + ext e + unfold LooplessGraph.mean + rw [← Equiv.sum_comp obstructionEquiv] + change (∑ i : Fin 5, p (obstructionMatching i) * obstructionGraph.indicator (obstructionMatching i) e) = _ + fin_cases e <;> simp +decide [LooplessGraph.indicator,obstructionMatching,obstructionEdges,Fin.sum_univ_succ,add_assoc] + +theorem obstruction_law_values (i : Fin 5) : + obstructionLaw (obstructionMatching i) = ![(1 : ℝ)/3,1/3,1/3,0,0] i := by + fin_cases i <;> simp +decide [obstructionLaw,obstructionMatching,obstructionEdges,Fin.sum_univ_succ] + +theorem obstruction_unique_law : + obstructionGraph.feasibleLaws obstructionUniform = {obstructionLaw} := by + apply Set.Subset.antisymm ?_ (Set.singleton_subset_iff.mpr obstruction_law_feasible) + intro p hp + have hm := hp.2 + rw [obstruction_mean_coordinates] at hm + have h0 := congrFun hm 0 + have h1 := congrFun hm 6 + have h2 := congrFun hm 5 + have h3 := congrFun hm 3 + have h4 := congrFun hm 4 + change p (obstructionMatching 0) = 1/3 at h0 + change p (obstructionMatching 1) = 1/3 at h1 + change p (obstructionMatching 2) = 1/3 at h2 + change p (obstructionMatching 2) + p (obstructionMatching 3) = 1/3 at h3 + change p (obstructionMatching 1) + p (obstructionMatching 4) = 1/3 at h4 + apply Set.mem_singleton_iff.mpr + ext M + obtain ⟨i,rfl⟩ := obstruction_classify M + rw [obstruction_law_values] + fin_cases i + · exact h0 + · exact h1 + · exact h2 + · change p (obstructionMatching 3) = 0 + linarith only [h2,h3] + · change p (obstructionMatching 4) = 0 + linarith only [h1,h4] + +theorem obstruction_entropy_law : entropy obstructionLaw = Real.log 3 := by + rw [obstruction_law_eq_fiber,entropy_fiberMass_injective _ _ obstructionSelected_injective,uniformLaw_entropy] + norm_num + +theorem obstruction_maxEntropy : maxMatchingEntropy obstructionGraph obstructionUniform = Real.log 3 := by + obtain ⟨p,hp,he⟩ := maxMatchingEntropy_attained _ obstruction_uniform_mem + rw [obstruction_unique_law,Set.mem_singleton_iff] at hp + rw [← he,hp,obstruction_entropy_law] + +theorem obstruction_entropy_terms : + entropy obstructionUniform = 4 * Real.log 3 ∧ + complementEntropy obstructionUniform = 8 * Real.log (3/2) := by + have hF : Real.negMulLog (1/3) = Real.log 3 / 3 := by + norm_num [Real.negMulLog,Real.log_div] + ring + have hB : Real.negMulLog (1-1/3) = (2/3) * Real.log (3/2) := by + norm_num [Real.negMulLog,Real.log_div] + ring + constructor + · simp only [entropy,obstructionUniform,hF,Finset.sum_const,Finset.card_univ,Fintype.card_fin,nsmul_eq_mul] + ring + · change (∑ _ : Fin 12, Real.negMulLog (1-1/3)) = _ + simp only [hB,Finset.sum_const,Finset.card_univ,Fintype.card_fin,nsmul_eq_mul] + ring + +theorem obstruction_logarithms : + entropy obstructionUniform - complementEntropy obstructionUniform = 4 * Real.log (4/3) ∧ + entropy obstructionUniform - complementEntropy obstructionUniform - + maxMatchingEntropy obstructionGraph obstructionUniform = Real.log (256/243) := by + have h4 : Real.log 4 = 2 * Real.log 2 := by + convert Real.log_pow (2 : ℝ) 2 using 1 + norm_num + have h256 : Real.log 256 = 8 * Real.log 2 := by + convert Real.log_pow (2 : ℝ) 8 using 1 + norm_num + have h243 : Real.log 243 = 5 * Real.log 3 := by + convert Real.log_pow (3 : ℝ) 5 using 1 + norm_num + rw [obstruction_entropy_terms.1,obstruction_entropy_terms.2,obstruction_maxEntropy] + norm_num [Real.log_div,h4,h256,h243] + constructor <;> ring + +theorem eight_vertex_obstruction : + IsSimpleLabelled obstructionGraph ∧ + (∀ M : obstructionGraph.Matching, ∃! i : Fin 5, M.val = obstructionEdges i) ∧ + (∀ i : Fin 5, obstructionGraph.IsPerfectMatching (obstructionEdges i)) ∧ + Fintype.card obstructionGraph.Matching = 5 ∧ + obstructionUniform ∈ obstructionGraph.polytope ∧ + obstructionGraph.feasibleLaws obstructionUniform = {obstructionLaw} ∧ + maxMatchingEntropy obstructionGraph obstructionUniform = Real.log 3 ∧ + entropy obstructionUniform - complementEntropy obstructionUniform = 4 * Real.log (4 / 3) ∧ + entropy obstructionUniform - complementEntropy obstructionUniform - + maxMatchingEntropy obstructionGraph obstructionUniform = Real.log (256 / 243) ∧ + 0 < Real.log (256 / 243) := by + refine ⟨obstruction_simple,?_,obstruction_matching,?_,obstruction_uniform_mem, + obstruction_unique_law,obstruction_maxEntropy,obstruction_logarithms.1, + obstruction_logarithms.2,Real.log_pos (by norm_num)⟩ + · intro M + obtain ⟨i,rfl⟩ := obstruction_classify M + refine ⟨i,rfl,?_⟩ + intro j hj + exact (obstructionEdges_injective hj).symm + · exact (Fintype.card_congr obstructionEquiv).symm.trans (Fintype.card_fin 5) + +end MatchingEntropyBounds.Refined + +end + +end OAI diff --git a/lean/OAI/Combinatorics/MatchingEntropy/Entropy.lean b/lean/OAI/Combinatorics/MatchingEntropy/Entropy.lean new file mode 100644 index 0000000000000000000000000000000000000000..1fcaa96224cce3269019e1b48119e431e8c40ebf --- /dev/null +++ b/lean/OAI/Combinatorics/MatchingEntropy/Entropy.lean @@ -0,0 +1,164 @@ +import OAI.Combinatorics.MatchingEntropy.Face + +namespace OAI + +noncomputable section + +open scoped BigOperators Topology +open Filter + +universe uV uE uI uJ uA uB uC uW uF uD uι + +namespace MatchingEntropyBounds + +variable {V : Type uV} {E : Type uE} [Fintype V] [Fintype E] [DecidableEq V] [DecidableEq E] + +def marginalEntropy (y : E → ℝ) : ℝ := entropy y + +theorem entropy_eq {ι : Type uι} [Fintype ι] (p : ι → ℝ) : + entropy p = -(∑ i, p i * Real.log (p i)) := by + simp [entropy, Real.negMulLog, Finset.sum_neg_distrib, neg_mul] + +theorem continuous_entropy {ι : Type uι} [Fintype ι] : + Continuous (entropy : (ι → ℝ) → ℝ) := by + unfold entropy + fun_prop + +theorem entropy_nonneg {ι : Type uι} [Fintype ι] {p : ι → ℝ} + (hp : p ∈ probabilitySimplex ι) : 0 ≤ entropy p := by + apply Finset.sum_nonneg + intro i _ + exact Real.negMulLog_nonneg (mem_Icc_of_mem_probabilitySimplex hp i).1 + (mem_Icc_of_mem_probabilitySimplex hp i).2 + +theorem entropy_le_log_card {ι : Type uι} [Fintype ι] {p : ι → ℝ} + (hp : p ∈ probabilitySimplex ι) : entropy p ≤ Real.log (Fintype.card ι) := by + have hn : 0 < Fintype.card ι := by + by_contra h + have hz : Fintype.card ι = 0 := Nat.eq_zero_of_not_pos h + have : IsEmpty ι := Fintype.card_eq_zero_iff.mp hz + simpa using hp.2 + have hnR : (0 : ℝ) < Fintype.card ι := by exact_mod_cast hn + have h := Finset.sum_le_sum (s := Finset.univ) (fun i _ ↦ + Real.negMulLog_le_one_sub_self (mul_nonneg hnR.le (hp.1 i))) + simp_rw [Real.negMulLog_mul] at h + rw [Finset.sum_add_distrib, ← Finset.sum_mul, ← Finset.mul_sum, + hp.2, one_mul, Finset.sum_sub_distrib, ← Finset.mul_sum, hp.2] at h + simp only [Finset.sum_const, Finset.card_univ, nsmul_eq_mul, mul_one, sub_self] at h + change Real.negMulLog (Fintype.card ι) + (Fintype.card ι : ℝ) * entropy p ≤ 0 at h + rw [Real.negMulLog] at h + nlinarith + +namespace LooplessGraph + +omit [Fintype V] [DecidableEq V] in +theorem coordinate_mem_Icc (G : LooplessGraph V E) {y : E → ℝ} + (hy : y ∈ G.polytope) (e : E) : y e ∈ Set.Icc (0 : ℝ) 1 := by + obtain ⟨p, hp, rfl⟩ := (G.mem_polytope_iff y).mp hy + constructor + · exact Finset.sum_nonneg (fun M _ ↦ mul_nonneg (hp.1 M) (G.indicator_nonneg M e)) + · calc + ∑ M, p M * G.indicator M e ≤ ∑ M, p M * 1 := + Finset.sum_le_sum (fun M _ ↦ mul_le_mul_of_nonneg_left (G.indicator_le_one M e) (hp.1 M)) + _ = 1 := by simpa using hp.2 + +omit [Fintype E] [DecidableEq E] in + +theorem incident_vertex_sum (G : LooplessGraph V E) (e : E) : + (∑ v, if G.Incident v e then (1 : ℕ) else 0) = 2 := by + classical + have he (v : V) : (if G.Incident v e then (1 : ℕ) else 0) = + (if G.left e = v then 1 else 0) + (if G.right e = v then 1 else 0) := by + by_cases hl : G.left e = v <;> by_cases hr : G.right e = v + · exact False.elim (G.loopless e (hl.trans hr.symm)) + · simp [Incident, hl, hr] + · simp [Incident, hl, hr] + · simp [Incident, hl, hr] + simp_rw [he, Finset.sum_add_distrib] + simp + +omit [Fintype V] [Fintype E] [DecidableEq E] in +theorem matching_incident_sum (G : LooplessGraph V E) (M : G.Matching) (v : V) : + (∑ e ∈ M.val, if G.Incident v e then (1 : ℕ) else 0) = 1 := by + classical + obtain ⟨e, ⟨he, hv⟩, hu⟩ := M.property v + rw [Finset.sum_eq_single e] + · simp [hv] + · intro e' he' hne + have hn : ¬ G.Incident v e' := fun hv' ↦ hne (hu e' ⟨he', hv'⟩) + simp [hn] + · simp [he] + +omit [Fintype E] [DecidableEq E] in +theorem matching_card_twice (G : LooplessGraph V E) (M : G.Matching) : + 2 * M.val.card = Fintype.card V := by + classical + calc + 2 * M.val.card = ∑ e ∈ M.val, ∑ v, if G.Incident v e then (1 : ℕ) else 0 := by + simp_rw [G.incident_vertex_sum] + simp [Nat.mul_comm] + _ = ∑ v, ∑ e ∈ M.val, if G.Incident v e then (1 : ℕ) else 0 := Finset.sum_comm + _ = Fintype.card V := by + simp_rw [G.matching_incident_sum] + simp + +omit [Fintype E] [DecidableEq E] in +theorem matching_card (G : LooplessGraph V E) {m : ℕ} + (hV : Fintype.card V = 2 * m) (M : G.Matching) : M.val.card = m := by + have h := G.matching_card_twice M + omega + +theorem indicator_sum (G : LooplessGraph V E) {m : ℕ} + (hV : Fintype.card V = 2 * m) (M : G.Matching) : + ∑ e, G.indicator M e = (m : ℝ) := by + simp [indicator, G.matching_card hV M] + +theorem marginal_sum (G : LooplessGraph V E) {m : ℕ} + (hV : Fintype.card V = 2 * m) {y : E → ℝ} (hy : y ∈ G.polytope) : + ∑ e, y e = (m : ℝ) := by + obtain ⟨p, hp, rfl⟩ := (G.mem_polytope_iff y).mp hy + simp_rw [mean] + rw [Finset.sum_comm] + simp_rw [← Finset.mul_sum, G.indicator_sum hV] + rw [← Finset.sum_mul, hp.2, one_mul] + +end LooplessGraph + +omit [Fintype V] [DecidableEq V] in + +theorem maxMatchingEntropy_attained (G : LooplessGraph V E) {y : E → ℝ} + (hy : y ∈ G.polytope) : + ∃ p ∈ G.feasibleLaws y, entropy p = maxMatchingEntropy G y := by + have hc := (G.compact_feasibleLaws y).image continuous_entropy + have hn := ((G.mem_polytope_iff y).mp hy).image entropy + obtain ⟨p, hp, hpe⟩ := hc.sSup_mem hn + exact ⟨p, hp, hpe⟩ + +omit [Fintype V] [DecidableEq V] in +theorem maxMatchingEntropy_nonneg (G : LooplessGraph V E) {y : E → ℝ} + (hy : y ∈ G.polytope) : 0 ≤ maxMatchingEntropy G y := by + obtain ⟨p, hp, he⟩ := maxMatchingEntropy_attained G hy + rw [← he] + exact entropy_nonneg hp.1 + +omit [Fintype V] [DecidableEq V] in +theorem maxMatchingEntropy_le_log_card (G : LooplessGraph V E) {y : E → ℝ} + (hy : y ∈ G.polytope) : + maxMatchingEntropy G y ≤ Real.log (Fintype.card G.Matching) := by + obtain ⟨p, hp, he⟩ := maxMatchingEntropy_attained G hy + rw [← he] + exact entropy_le_log_card hp.1 + +omit [Fintype V] [DecidableEq V] in +theorem entropy_le_maxMatchingEntropy (G : LooplessGraph V E) {y : E → ℝ} + {p : G.Matching → ℝ} (hp : p ∈ G.feasibleLaws y) : + entropy p ≤ maxMatchingEntropy G y := by + apply le_csSup + · exact ((G.compact_feasibleLaws y).image continuous_entropy).bddAbove + · exact ⟨p, hp, rfl⟩ + +end MatchingEntropyBounds + +end + +end OAI diff --git a/lean/OAI/Combinatorics/MatchingEntropy/EntropyUpper.lean b/lean/OAI/Combinatorics/MatchingEntropy/EntropyUpper.lean new file mode 100644 index 0000000000000000000000000000000000000000..82a8110eeec10caa7160623a766c23099262781c --- /dev/null +++ b/lean/OAI/Combinatorics/MatchingEntropy/EntropyUpper.lean @@ -0,0 +1,153 @@ +import OAI.Combinatorics.MatchingEntropy.SeparableBound + +namespace OAI + +noncomputable section + +open scoped BigOperators Topology +open Filter + +universe uV uE uI uJ uA uB uC uW uF uD uι + +namespace MatchingEntropyBounds + +theorem entropy_le_subprob_crossEntropy {I : Type uI} [Fintype I] {p q : I → ℝ} + (hp : ∀ i, 0 ≤ p i) (hpsum : ∑ i, p i ≤ 1) (hq : q ∈ probabilitySimplex I) + (hsupp : ∀ i, p i=0 → q i=0) : + entropy q ≤ -∑ i, q i*Real.log (p i) := by + have hterm : ∀ i, Real.negMulLog (q i) ≤ -(q i*Real.log (p i))+p i-q i := by + intro i + by_cases hi : p i=0 + · simp [hi,hsupp i hi] + · simpa only [neg_mul] using negMulLog_tangent (hq.1 i) + (lt_of_le_of_ne (hp i) (Ne.symm hi)) + have hh := Finset.sum_le_sum (s := Finset.univ) fun i _ => hterm i + simp only [Finset.sum_sub_distrib,Finset.sum_add_distrib,Finset.sum_neg_distrib,hq.2] at hh + change entropy q ≤ -(∑ i, q i*Real.log (p i))+(∑ i,p i)-1 at hh + linarith + +variable {V : Type uV} {E : Type uE} [Fintype V] [Fintype E] [DecidableEq V] [DecidableEq E] + +namespace LooplessGraph + +def matchingBits (G : LooplessGraph V E) (M : G.Matching) : E → Bool := + fun e => decide (e ∈ M.val) + +omit [Fintype V] [Fintype E] [DecidableEq V] in +theorem matchingBits_injective (G : LooplessGraph V E) : Function.Injective G.matchingBits := by + intro M N h + apply Subtype.ext + ext e + have he := congrFun h e + simpa only [matchingBits,decide_eq_decide] using he + +end LooplessGraph + +def productBoolean (x : E → ℝ) (b : E → Bool) : ℝ := + ∏ e, if b e then x e else 1-x e + +omit [Fintype V] [DecidableEq V] [DecidableEq E] in +theorem productBoolean_nonneg {x : E → ℝ} (hx : ∀ e, x e ∈ Set.Icc (0:ℝ) 1) + (b : E → Bool) : 0 ≤ productBoolean x b := by + apply Finset.prod_nonneg + intro e _ + split + · exact (hx e).1 + · exact sub_nonneg.mpr (hx e).2 + +omit [Fintype V] [DecidableEq V] in +theorem productBoolean_sum (x : E → ℝ) : (∑ b : E → Bool, productBoolean x b)=1 := by + unfold productBoolean + rw [← Fintype.prod_sum (fun e (b : Bool) => if b then x e else 1-x e)] + simp + +omit [Fintype V] [DecidableEq V] in +theorem matchingBoolean_sum_le (G : LooplessGraph V E) {x : E → ℝ} + (hx : ∀ e, x e ∈ Set.Icc (0:ℝ) 1) : + (∑ M, productBoolean x (G.matchingBits M)) ≤ 1 := by + rw [← productBoolean_sum x] + classical + calc + _ = ∑ b ∈ Finset.univ.image G.matchingBits, productBoolean x b := by + rw [Finset.sum_image] + intro M _ N _ h + exact G.matchingBits_injective h + _ ≤ _ := Finset.sum_le_sum_of_subset_of_nonneg (Finset.subset_univ _) + (fun b _ _ => productBoolean_nonneg hx b) + +omit [Fintype V] [DecidableEq V] in +theorem matching_boolean_factor_pos (G : LooplessGraph V E) {x : E → ℝ} + {p : G.Matching → ℝ} (hp : p ∈ G.feasibleLaws x) {M : G.Matching} (hM : 0

p N*G.indicator N e) + (s := Finset.univ) (fun N _ => mul_nonneg (hp.1.1 N) (G.indicator_nonneg N e)) + (Finset.mem_univ M) + have hm : G.indicator M e=1 := by simp [LooplessGraph.indicator,he] + rw [hm,mul_one] at hh + change p M ≤ G.mean p e at hh + rw [hp.2] at hh + exact hM.trans_le hh + · simp only [he,decide_false] + have hh := Finset.single_le_sum (f := fun N => p N*(1-G.indicator N e)) + (s := Finset.univ) (fun N _ => mul_nonneg (hp.1.1 N) + (sub_nonneg.mpr (G.indicator_le_one N e))) (Finset.mem_univ M) + have hm : G.indicator M e=0 := by simp [LooplessGraph.indicator,he] + simp only [hm,sub_zero,mul_one,mul_sub,Finset.sum_sub_distrib,hp.1.2] at hh + change p M ≤ 1-G.mean p e at hh + rw [hp.2] at hh + exact hM.trans_le hh + +omit [Fintype V] [DecidableEq V] in + +theorem matching_entropy_le_binary (G : LooplessGraph V E) {x : E → ℝ} + {p : G.Matching → ℝ} (hp : p ∈ G.feasibleLaws x) : entropy p ≤ binaryEntropy x := by + have hx := G.coordinate_mem_Icc ((G.mem_polytope_iff x).mpr ⟨p,hp⟩) + have hprod (M : G.Matching) (hM : 0

matching_boolean_factor_pos G hp hM e) + have hcross := entropy_le_subprob_crossEntropy + (fun M => productBoolean_nonneg hx (G.matchingBits M)) (matchingBoolean_sum_le G hx) hp.1 + (fun M hzero => le_antisymm (le_of_not_gt (fun hM => (ne_of_gt (hprod M hM)) hzero)) (hp.1.1 M)) + have hlog (M : G.Matching) : p M*Real.log (productBoolean x (G.matchingBits M)) = + ∑ e, p M*(G.indicator M e*Real.log (x e)+(1-G.indicator M e)*Real.log (1-x e)) := by + by_cases hzero : p M=0 + · simp [hzero] + · have hpos : 0

ne_of_gt (matching_boolean_factor_pos G hp hpos e)), + Finset.mul_sum] + apply Finset.sum_congr rfl + intro e _ + simp only [LooplessGraph.matchingBits,LooplessGraph.indicator] + by_cases he : e ∈ M.val <;> simp [he] + have heq : -(∑ M, p M*Real.log (productBoolean x (G.matchingBits M)))=binaryEntropy x := by + simp_rw [hlog] + rw [Finset.sum_comm] + have he (e : E) : (∑ M, p M*(G.indicator M e*Real.log (x e)+ + (1-G.indicator M e)*Real.log (1-x e)))= + x e*Real.log (x e)+(1-x e)*Real.log (1-x e) := by + simp_rw [mul_add,← mul_assoc,Finset.sum_add_distrib,← Finset.sum_mul] + have hmean : (∑ M,p M*G.indicator M e)=x e := congrFun hp.2 e + have hbar : (∑ M,p M*(1-G.indicator M e))=1-x e := by + simp_rw [mul_sub,mul_one,Finset.sum_sub_distrib,hp.1.2,hmean] + rw [hmean,hbar] + simp_rw [he] + rw [Finset.sum_add_distrib,neg_add_rev] + dsimp only [binaryEntropy] + rw [entropy_eq,entropy_eq] + ring + rwa [heq] at hcross + +omit [Fintype V] [DecidableEq V] in +theorem maxMatchingEntropy_le_binary (G : LooplessGraph V E) (x : E → ℝ) + (hx : x ∈ G.polytope) : maxMatchingEntropy G x ≤ binaryEntropy x := by + obtain ⟨p,hp,hopt⟩ := maxMatchingEntropy_attained G hx + rw [← hopt] + exact matching_entropy_le_binary G hp + +end MatchingEntropyBounds + +end + +end OAI diff --git a/lean/OAI/Combinatorics/MatchingEntropy/ExpansionSequences.lean b/lean/OAI/Combinatorics/MatchingEntropy/ExpansionSequences.lean new file mode 100644 index 0000000000000000000000000000000000000000..4b0de3427e9055cd264f80e67aa2ffe5caeebea8 --- /dev/null +++ b/lean/OAI/Combinatorics/MatchingEntropy/ExpansionSequences.lean @@ -0,0 +1,185 @@ +import OAI.Combinatorics.MatchingEntropy.EightVertex + +namespace OAI + +noncomputable section + +open scoped BigOperators Topology +open Filter + +universe uV uE uI uJ uA uB uC uW uF uD uι + +namespace MatchingEntropyBounds.Refined + +inductive KleeConstruction : (n : ℕ) → LooplessGraph (KleeV n) (KleeE n) → Prop + | base : KleeConstruction 0 (kleeGraph 0) + | expand {n : ℕ} {G : LooplessGraph (KleeV n) (KleeE n)} + (previous : KleeConstruction n G) (v : KleeV n) : + KleeConstruction (n+1) (triangleExpansion G (kleeColor n) v) + +def coloredLaw {W : Type uW} {D : Type uD} [Fintype D] [DecidableEq W] [DecidableEq D] + (G : LooplessGraph W D) (c : D → Fin 3) : G.Matching → ℝ := + fun M => ∑ i : Fin 3, if M.val = colorEdges c i then 1 / 3 else 0 + +section ColoredLaws +variable {W : Type uW} {D : Type uD} [Fintype W] [Fintype D] [DecidableEq W] [DecidableEq D] + +omit [Fintype W] in +theorem colored_law_eq_fiber (G : LooplessGraph W D) (c : D → Fin 3) (hc : CubicColoring G c) : + coloredLaw G c = fiberMass (uniformLaw (Fin 3)) (colorMatching G c hc) := by + ext M + unfold coloredLaw fiberMass + apply Finset.sum_congr rfl + intro i _ + have he : colorMatching G c hc i = M ↔ M.val = colorEdges c i := by + rw [Subtype.ext_iff] + exact eq_comm + simp [he,uniformLaw] + +omit [Fintype W] in +theorem colored_law_feasible (G : LooplessGraph W D) (c : D → Fin 3) (hc : CubicColoring G c) : + coloredLaw G c ∈ G.feasibleLaws (fun _ => 1/3) := by + rw [colored_law_eq_fiber G c hc] + exact ⟨fiberMass_mem_simplex uniformLaw_simplex _,colored_uniform_mean G c hc⟩ + +omit [Fintype W] in +theorem colored_uniform_mem (G : LooplessGraph W D) (c : D → Fin 3) (hc : CubicColoring G c) : + (fun _ => 1/3) ∈ G.polytope := + (G.mem_polytope_iff _).mpr ⟨_,colored_law_feasible G c hc⟩ + +omit [Fintype W] in +theorem colored_entropy_law (G : LooplessGraph W D) (c : D → Fin 3) (hc : CubicColoring G c) (v : W) : + entropy (coloredLaw G c) = Real.log 3 := by + rw [colored_law_eq_fiber G c hc,entropy_fiberMass_injective _ _ + (colorMatching_injective G c hc v),uniformLaw_entropy] + norm_num + +omit [Fintype W] in +theorem colored_law_expand (G : LooplessGraph W D) (c : D → Fin 3) (hc : CubicColoring G c) (v : W) : + fiberMass (coloredLaw G c) (expandMatching G c v) = + coloredLaw (triangleExpansion G c v) (expandedColor c) := by + rw [colored_law_eq_fiber G c hc, + colored_law_eq_fiber _ _ (cubicColoring_expansion G c hc v),fiberMass_comp] + ext M + unfold fiberMass + apply Finset.sum_congr rfl + intro i _ + rw [Function.comp_apply,expanded_colorMatching G c hc v] + +omit [Fintype W] in +theorem colored_unique_expansion (G : LooplessGraph W D) (c : D → Fin 3) (hc : CubicColoring G c) (v : W) + (hu : G.feasibleLaws (fun _ => 1/3) = {coloredLaw G c}) : + (triangleExpansion G c v).feasibleLaws (fun _ => 1/3) = + {coloredLaw (triangleExpansion G c v) (expandedColor c)} := by + apply Set.Subset.antisymm ?_ (Set.singleton_subset_iff.mpr + (colored_law_feasible _ _ (cubicColoring_expansion G c hc v))) + intro p hp + have he : triangleExtension G c hc v (fun _ => 1/3) = fun _ => 1/3 := by + ext e + cases e <;> rfl + rw [← he] at hp + obtain ⟨hp',hq⟩ := expanded_pull_feasible G c hc v (colored_uniform_mem G c hc) hp + rw [hu,Set.mem_singleton_iff] at hq + rw [hq,colored_law_expand G c hc v] at hp' + exact Set.mem_singleton_iff.mpr hp' + +omit [Fintype W] [Fintype D] [DecidableEq W] [DecidableEq D] in +theorem colored_triangle_expansion (G : LooplessGraph W D) (c : D → Fin 3) (hc : CubicColoring G c) (v : W) : + triangleExtension G c hc v '' convexHull ℝ (Set.range (coloredVector c)) = + convexHull ℝ (Set.range (coloredVector (expandedColor c))) := by + rw [LinearMap.image_convexHull,← Set.range_comp] + congr 1 + apply congrArg Set.range + funext i + exact triangleExtension_colored G c hc v i + +theorem colored_minimal_expansion (G : LooplessGraph W D) (c : D → Fin 3) (hc : CubicColoring G c) (v : W) + (hm : minimalFace G (fun _ => 1/3) = convexHull ℝ (Set.range (coloredVector c))) : + minimalFace (triangleExpansion G c v) (fun _ => 1/3) = + convexHull ℝ (Set.range (coloredVector (expandedColor c))) := by + have hh := ((expansion_face G c hc v).2.2 _ (colored_uniform_mem G c hc)).1 + have he : triangleExtension G c hc v (fun _ => 1/3) = fun _ => 1/3 := by + ext e + cases e <;> rfl + rw [he,hm,colored_triangle_expansion G c hc v] at hh + exact hh +end ColoredLaws + +theorem klee_generated_cubic {n : ℕ} {G : LooplessGraph (KleeV n) (KleeE n)} + (hG : KleeConstruction n G) : CubicColoring G (kleeColor n) := by + induction hG with + | base => exact klee_cubic 0 + | expand _ v ih => exact cubicColoring_expansion _ _ ih v + +theorem klee_generated_minimal {n : ℕ} {G : LooplessGraph (KleeV n) (KleeE n)} + (hG : KleeConstruction n G) : minimalFace G (kleeUniform n) = kleeTriangle n := by + induction hG with + | base => exact klee_minimal 0 + | @expand n G prev v ih => + rw [kleeEDecEq_succ,kleeVDecEq_succ] + exact colored_minimal_expansion G (kleeColor n) (klee_generated_cubic prev) v ih + +theorem klee_generated_unique {n : ℕ} {G : LooplessGraph (KleeV n) (KleeE n)} + (hG : KleeConstruction n G) : G.feasibleLaws (kleeUniform n) = {coloredLaw G (kleeColor n)} := by + induction hG with + | base => exact klee_unique_law 0 + | @expand n G prev v ih => + rw [kleeEDecEq_succ,kleeVDecEq_succ] + exact colored_unique_expansion G (kleeColor n) (klee_generated_cubic prev) v ih + +theorem klee_initial_expansion_simple (v : KleeV 0) : + IsSimpleLabelled (triangleExpansion (kleeGraph 0) (kleeColor 0) v) := by + fin_cases v + · exact klee_simple_one + · intro e f h + rcases e with e | i <;> rcases f with f | j + · fin_cases e <;> fin_cases f <;> + simp_all [kleeGraph,kleeColor,triangleExpansion,reattach,triangleTip,KleeV,KleeE] + · fin_cases e <;> fin_cases j <;> + simp_all [kleeGraph,kleeColor,triangleExpansion,reattach,triangleTip,KleeV,KleeE] + · fin_cases i <;> fin_cases f <;> + simp_all [kleeGraph,kleeColor,triangleExpansion,reattach,triangleTip,KleeV,KleeE] + · fin_cases i <;> fin_cases j <;> + simp_all [kleeGraph,kleeColor,triangleExpansion,reattach,triangleTip,KleeV,KleeE] + +theorem klee_generated_simple {n : ℕ} {G : LooplessGraph (KleeV n) (KleeE n)} + (hG : KleeConstruction n G) (hn : 1 ≤ n) : IsSimpleLabelled G := by + induction hG with + | base => omega + | @expand n G prev v ih => + by_cases hz : n = 0 + · subst n + cases prev + exact klee_initial_expansion_simple v + · exact simplicity_expansion G _ v (ih (by omega)) + +theorem klee_all_expansions (n : ℕ) (G : LooplessGraph (KleeV n) (KleeE n)) + (hG : KleeConstruction n G) : + Fintype.card (KleeV n) = 2 * (n+1) ∧ + Fintype.card (KleeE n) = 3 * (n+1) ∧ + CubicColoring G (kleeColor n) ∧ + (n ≥ 1 → IsSimpleLabelled G) ∧ + kleeUniform n ∈ G.polytope ∧ + minimalFace G (kleeUniform n) = kleeTriangle n ∧ + faceDimension G (kleeUniform n) = 2 ∧ + Fintype.card (KleeE n) - faceDimension G (kleeUniform n) = 3 * (n+1) - 2 ∧ + G.feasibleLaws (kleeUniform n) = {coloredLaw G (kleeColor n)} ∧ + maxMatchingEntropy G (kleeUniform n) = Real.log 3 ∧ + entropy (kleeUniform n) = (n+1) * Real.log 3 ∧ + complementEntropy (kleeUniform n) = 2 * (n+1) * Real.log (3/2) := by + have hc := klee_generated_cubic hG + have hm : kleeUniform n ∈ G.polytope := colored_uniform_mem G (kleeColor n) hc + have hd : faceDimension G (kleeUniform n) = 2 := by + rw [faceDimension,klee_generated_minimal hG,kleeTriangle,affineSpan_convexHull,direction_affineSpan] + exact (coloredVector_linearIndependent G _ hc (kleeRoot n)).affineIndependent.finrank_vectorSpan (by decide) + refine ⟨klee_cardV n,klee_cardE n,hc,klee_generated_simple hG,hm,klee_generated_minimal hG, + hd,by rw [klee_cardE,hd],klee_generated_unique hG,?_,klee_entropy_terms n⟩ + obtain ⟨p,hp,he⟩ := maxMatchingEntropy_attained G hm + rw [klee_generated_unique hG,Set.mem_singleton_iff] at hp + rw [← he,hp,colored_entropy_law G _ hc (kleeRoot n)] + +end MatchingEntropyBounds.Refined + +end + +end OAI diff --git a/lean/OAI/Combinatorics/MatchingEntropy/Face.lean b/lean/OAI/Combinatorics/MatchingEntropy/Face.lean new file mode 100644 index 0000000000000000000000000000000000000000..818a89ab7dc14f869a479445734ebc84067a2876 --- /dev/null +++ b/lean/OAI/Combinatorics/MatchingEntropy/Face.lean @@ -0,0 +1,299 @@ +import OAI.Combinatorics.MatchingEntropy.Polytope + +namespace OAI + +noncomputable section + +open scoped BigOperators Topology +open Filter + +universe uV uE uI uJ uA uB uC uW uF uD uι + +namespace MatchingEntropyBounds.LooplessGraph + +variable {V : Type uV} {E : Type uE} [Fintype V] [Fintype E] [DecidableEq V] [DecidableEq E] + +def positiveExtension (x : E → ℝ) : ({e // 0 if h : 0 simp [h] + map_smul' := by intro a u; ext e; by_cases h : 0 simp [h] } + +omit [Fintype E] [DecidableEq E] in +@[simp] theorem positiveExtension_pos (x : E → ℝ) (u : {e // 0 simp + +def cutLinear (G : LooplessGraph V E) (S : Finset V) : (E → ℝ) →ₗ[ℝ] ℝ where + toFun := fun u => G.cutMass u S + map_add' := by intro u v; simpa using G.cutMass_linear u v 1 1 S + map_smul' := by intro a u; simp [cutMass,Finset.mul_sum] + +def faceSpace (G : LooplessGraph V E) (x : E → ℝ) : Submodule ℝ ({e // 0 positiveExtension_zero x u he) + (congrFun hu.1) hu.2 + +omit [Fintype V] [DecidableEq E] in + theorem faceSpace_of_eventually_line (G : LooplessGraph V E) {x : E → ℝ} + (hx : x ∈ G.constraintPolytope) {u : {e // 0 -t) (𝓝 0) (𝓝 0) := by simpa using continuous_neg.tendsto (0:ℝ) + exact hc.eventually hu + have hh : ∀ᶠ t : ℝ in 𝓝[>] 0, + (x+t • positiveExtension x u ∈ G.constraintPolytope ∧ + x+(-t) • positiveExtension x u ∈ G.constraintPolytope) ∧ 0 x e.val + +def sideRestriction (G : LooplessGraph V E) (x : E → ℝ) (S : Finset V) : + ({e // 0 u ⟨e.val.val,e.property⟩ + map_add' := by intros; rfl + map_smul' := by intros; rfl + +omit [Fintype V] [Fintype E] [DecidableEq V] [DecidableEq E] in + theorem positiveExtension_side (G : LooplessGraph V E) (x : E → ℝ) (S : Finset V) + (u : {e // 0 G.faceSpace_of_side_spaces heven hx S hS ht) + +theorem faceCodimension_strong_aux (n : ℕ) : + ∀ {W : Type uW} {F : Type uF} [Fintype W] [Fintype F] [DecidableEq W] [DecidableEq F] + (G : LooplessGraph W F), Fintype.card W=n → Even n → 4≤n → + ∀ x ∈ G.constraintPolytope, G.faceCodimension x ≤ 2*(n-2) := by + induction n using Nat.strong_induction_on with + | h n ih => + intro W F _ _ _ _ G hcard heven hfour x hx + have heven' : Even (Fintype.card W) := hcard ▸ heven + by_cases hcut : ∃ S : Finset W, Odd S.card ∧ 3≤S.card ∧ 3≤Sᶜ.card ∧ G.cutMass x S=1 + · obtain ⟨S,hS,hlo,hhi,ht⟩ := hcut + have hc := odd_compl_of_even heven' hS + have hlt1 : Fintype.card (Option {v // v ∈ S}) < n := by + simp only [Fintype.card_option,Fintype.card_coe] + have hco := Finset.card_compl S + omega + have hlt2 : Fintype.card (Option {v // v ∈ Sᶜ}) < n := by + simp only [Fintype.card_option,Fintype.card_coe] + have hco := Finset.card_compl S + have hle := Finset.card_le_univ S + omega + have hv1 : Even (Fintype.card (Option {v // v ∈ S})) := by + simpa only [Fintype.card_option,Fintype.card_coe] using hS.add_odd odd_one + have hv2 : Even (Fintype.card (Option {v // v ∈ Sᶜ})) := by + simpa only [Fintype.card_option,Fintype.card_coe] using hc.add_odd odd_one + have hn1 : 4≤Fintype.card (Option {v // v ∈ S}) := by + simp only [Fintype.card_option,Fintype.card_coe]; omega + have hn2 : 4≤Fintype.card (Option {v // v ∈ Sᶜ}) := by + simp only [Fintype.card_option,Fintype.card_coe]; omega + have hx1 := G.restriction_mem_constraints hx S hS ht + have htc : G.cutMass x Sᶜ=1 := by simpa only [cutMass,cut_compl] using ht + have hx2 := G.restriction_mem_constraints hx Sᶜ hc htc + have hb1 := ih _ hlt1 (G.onSide S) rfl hv1 hn1 _ hx1 + have hb2 := ih _ hlt2 (G.onSide Sᶜ) rfl hv2 hn2 _ hx2 + have hb := G.faceCodimension_le_sides heven' hx S hS ht + have hsum : Fintype.card (Option {v // v ∈ S}) + Fintype.card (Option {v // v ∈ Sᶜ})=n+2 := by + simp only [Fintype.card_option,Fintype.card_coe] + have hh := Finset.card_compl_add_card S + omega + change (G.onSide S).faceCodimension (G.sideMarginal x S) ≤ _ at hb1 + change (G.onSide Sᶜ).faceCodimension (G.sideMarginal x Sᶜ) ≤ _ at hb2 + omega + · have hb := G.faceCodimension_no_tight heven' hcut + omega + +theorem faceCodimension_bound (G : LooplessGraph V E) {x : E → ℝ} + (heven : Even (Fintype.card V)) (hx : x ∈ G.polytope) : + G.faceCodimension x ≤ 2*Fintype.card V := by + by_cases hn : 4≤Fintype.card V + · have hb := faceCodimension_strong_aux (Fintype.card V) G rfl heven hn x + (G.polytope_subset_constraintPolytope hx) + omega + · have hnt : ¬ ∃ S : Finset V, Odd S.card ∧ 3≤S.card ∧ 3≤Sᶜ.card ∧ G.cutMass x S=1 := by + rintro ⟨S,_,hlo,hhi,_⟩ + have hh := Finset.card_compl_add_card S + omega + have hb := G.faceCodimension_no_tight heven hnt + omega + +omit [Fintype V] [DecidableEq E] in + theorem degree_add_smul (G : LooplessGraph V E) (x u : E → ℝ) (t : ℝ) (v : V) : + G.degree (x+t • u) v=G.degree x v+t*G.degree u v := by + simpa using G.degree_linear x u 1 t v + +omit [Fintype V] [DecidableEq E] in + theorem cutMass_add_smul (G : LooplessGraph V E) (x u : E → ℝ) (t : ℝ) (S : Finset V) : + G.cutMass (x+t • u) S=G.cutMass x S+t*G.cutMass u S := by + simpa using G.cutMass_linear x u 1 t S + +omit [DecidableEq E] in + +theorem constraint_eventually_expand (G : LooplessGraph V E) {x : E → ℝ} + (hx : x ∈ G.constraintPolytope) {t : ℝ} (ht : 0 (x+t⁻¹ • (y-x)) e) := by fun_prop + have hh : ∀ᶠ y : E → ℝ in 𝓝 x, 0<(x+t⁻¹ • (y-x)) e := + (isOpen_lt continuous_const hc).mem_nhds (by simpa using hp) + exact (hh.filter_mono nhdsWithin_le_nhds).mono fun y hy => hy.le + have hodd : ∀ᶠ y in 𝓝[G.constraintPolytope] x, + ∀ S : Finset V, Odd S.card → 1≤G.cutMass (x+t⁻¹ • (y-x)) S := by + apply Filter.eventually_all.mpr + intro S + by_cases hS : Odd S.card + · by_cases hs : G.cutMass x S=1 + · filter_upwards [eventually_mem_nhdsWithin] with y hy _ + rw [cutMass_add_smul,cutMass_sub,hs] + have hh := mul_nonneg (inv_nonneg.mpr ht.le) (sub_nonneg.mpr (hy.2.2 S hS)) + linarith + · have hp : 1 G.cutMass (x+t⁻¹ • (y-x)) S) := + (G.continuous_cutMass S).comp (by fun_prop) + have hh : ∀ᶠ y : E → ℝ in 𝓝 x, 1 hy.le + · exact Filter.Eventually.of_forall fun _ h => (hS h).elim + filter_upwards [hn,hodd,eventually_mem_nhdsWithin] with y hn hodd hy + refine ⟨hn,?_,hodd⟩ + intro v + rw [degree_add_smul,degree_sub,hx.2.1,hy.2.1] + ring + + theorem polytope_eventually_expand (G : LooplessGraph V E) {x : E → ℝ} + (heven : Even (Fintype.card V)) (hx : x ∈ G.polytope) {t : ℝ} (ht : 0 if h : IsFractional x e then u ⟨e,h⟩ else 0 + map_add' := by intro u v; ext e; by_cases h : IsFractional x e <;> simp [h] + map_smul' := by intro a u; ext e; by_cases h : IsFractional x e <;> simp [h] } + map_vadd' := by intro z u; ext e; by_cases h : IsFractional x e <;> simp [h] + +def fixedFace (G : LooplessGraph V E) (x : E → ℝ) : Set (E → ℝ) := + {y | y ∈ G.polytope ∧ ∀ e, ¬IsFractional x e → y e = x e} + +omit [Fintype E] [DecidableEq E] in +@[simp] theorem fractionalExtension_apply_fractional (x : E → ℝ) + (z : {e // IsFractional x e} → ℝ) (e : {e // IsFractional x e}) : + fractionalExtension x z e.val = z e := by simp [fractionalExtension, e.property] + +omit [Fintype E] [DecidableEq E] in +@[simp] theorem fractionalExtension_apply_fixed (x : E → ℝ) + (z : {e // IsFractional x e} → ℝ) {e : E} (he : ¬IsFractional x e) : + fractionalExtension x z e = x e := by simp [fractionalExtension, he] + +omit [Fintype E] [DecidableEq E] in +@[simp] theorem fractionalExtension_mean (x : E → ℝ) : + fractionalExtension x (fractionalMean x) = x := by + ext e + by_cases he : IsFractional x e <;> simp [fractionalExtension, fractionalMean, he] + +omit [Fintype E] [DecidableEq E] in +theorem fractionalExtension_injective (x : E → ℝ) : + Function.Injective (fractionalExtension x) := by + intro z w h + ext e + simpa using congrFun h e.val + +omit [Fintype E] [DecidableEq E] in +theorem fractionalLinear_injective (x : E → ℝ) : + Function.Injective (fractionalExtension x).linear := by + intro z w h + ext e + have := congrFun h e.val + simpa [fractionalExtension, e.property] using this + +omit [Fintype V] [Fintype E] [DecidableEq V] [DecidableEq E] in +theorem fractional_incident (G : LooplessGraph V E) (x : E → ℝ) + (v : {v // FractionalVertex G x v}) (e : {e // IsFractional x e}) : + (fractionalGraph G x).Incident v e ↔ G.Incident v.val e.val := by + simp only [LooplessGraph.Incident, fractionalGraph, Subtype.ext_iff] + +omit [Fintype V] [DecidableEq V] in +theorem fixed_or_zero (G : LooplessGraph V E) {x : E → ℝ} (hx : x ∈ G.polytope) + {e : E} (he : ¬IsFractional x e) : x e = 0 ∨ x e = 1 := by + have h := G.coordinate_mem_Icc hx e + dsimp [IsFractional] at he + by_cases hz : x e = 0 + · exact Or.inl hz + · exact Or.inr (le_antisymm h.2 (not_lt.mp (fun hh => he ⟨lt_of_le_of_ne h.1 (Ne.symm hz), hh⟩))) + +omit [Fintype V] [DecidableEq V] in +theorem incident_forced_zero (G : LooplessGraph V E) {x : E → ℝ} (hx : x ∈ G.polytope) + {v : V} {e₀ e : E} (h₀ : x e₀ = 1) (hv₀ : G.Incident v e₀) + (hv : G.Incident v e) (hne : e ≠ e₀) : x e = 0 := by + apply G.forced_coordinate_zero hx e₀ h₀ hne + intro hr + rcases hv with h | h + · exact hr.1 (h ▸ hv₀) + · exact hr.2 (h ▸ hv₀) + +omit [Fintype V] [DecidableEq V] in +theorem fractional_no_forced (G : LooplessGraph V E) {x : E → ℝ} (hx : x ∈ G.polytope) + {v : V} (hv : FractionalVertex G x v) {e : E} (he : x e = 1) : ¬G.Incident v e := by + intro hi + obtain ⟨f, hf, hif⟩ := hv + have hne : f ≠ e := by intro h; subst f; exact (ne_of_lt hf.2) he + have hz := incident_forced_zero G hx he hi hif hne + exact (ne_of_gt hf.1) hz + +omit [Fintype V] in +theorem positive_incident (G : LooplessGraph V E) {x : E → ℝ} (hx : x ∈ G.polytope) (v : V) : + ∃ e, G.Incident v e ∧ 0 < x e := by + by_contra! hn + have hc := G.polytope_subset_constraintPolytope hx + have hz : G.degree x v = 0 := by + apply Finset.sum_eq_zero + intro e _ + by_cases hi : G.Incident v e + · simp [hi, le_antisymm (hn e hi) (hc.1 e)] + · simp [hi] + rw [hc.2.1 v] at hz + norm_num at hz + +omit [Fintype V] in +theorem fixed_at_vertex (G : LooplessGraph V E) {x : E → ℝ} (hx : x ∈ G.polytope) + {v : V} (hv : ¬FractionalVertex G x v) : ∃! e, x e = 1 ∧ G.Incident v e := by + obtain ⟨e, hi, he⟩ := positive_incident G hx v + have hnot : ¬IsFractional x e := fun h => hv ⟨e, h, hi⟩ + have hone : x e = 1 := (fixed_or_zero G hx hnot).resolve_left (ne_of_gt he) + refine ⟨e, ⟨hone, hi⟩, ?_⟩ + intro f hf + by_contra hn + have hz := incident_forced_zero G hx hone hi hf.2 hn + linarith [hf.1] + +def fractionalAdd (G : LooplessGraph V E) {x : E → ℝ} (hx : x ∈ G.polytope) + (M : (fractionalGraph G x).Matching) : G.Matching := by + classical + let N := M.val.map (Function.Embedding.subtype (IsFractional x)) ∪ + Finset.univ.filter (fun e => x e = 1) + have hmem (e : E) : e ∈ N ↔ + (∃ he : IsFractional x e, (⟨e,he⟩ : {e // IsFractional x e}) ∈ M.val) ∨ x e = 1 := by + simp only [N, Finset.mem_union, Finset.mem_map, Function.Embedding.coe_subtype, + Finset.mem_filter, Finset.mem_univ, true_and] + constructor + · rintro (⟨f, hf, rfl⟩ | h) + · exact Or.inl ⟨f.property, hf⟩ + · exact Or.inr h + · rintro (⟨he, hm⟩ | h) + · exact Or.inl ⟨⟨e,he⟩, hm, rfl⟩ + · exact Or.inr h + refine ⟨N, ?_⟩ + intro v + by_cases hv : FractionalVertex G x v + · obtain ⟨e, ⟨he, hi⟩, hu⟩ := M.property ⟨v,hv⟩ + refine ⟨e.val, ⟨(hmem e.val).mpr (Or.inl ⟨e.property,he⟩), + (fractional_incident G x _ _).mp hi⟩, ?_⟩ + intro f hf + rcases (hmem f).mp hf.1 with ⟨hfrac, hm⟩ | hone + · exact congrArg Subtype.val (hu ⟨f,hfrac⟩ ⟨hm, (fractional_incident G x _ _).mpr hf.2⟩) + · exact (fractional_no_forced G hx hv hone hf.2).elim + · obtain ⟨e, he, hu⟩ := fixed_at_vertex G hx hv + refine ⟨e, ⟨(hmem e).mpr (Or.inr he.1), he.2⟩, ?_⟩ + intro f hf + rcases (hmem f).mp hf.1 with ⟨hfrac, _⟩ | hone + · exact (hv ⟨f,hfrac,hf.2⟩).elim + · exact hu f ⟨hone,hf.2⟩ + +omit [Fintype V] in +theorem mem_fractionalAdd (G : LooplessGraph V E) {x : E → ℝ} (hx : x ∈ G.polytope) + (M : (fractionalGraph G x).Matching) (e : E) : + e ∈ (fractionalAdd G hx M).val ↔ + (∃ he : IsFractional x e, (⟨e,he⟩ : {e // IsFractional x e}) ∈ M.val) ∨ x e = 1 := by + classical + simp only [fractionalAdd, Finset.mem_union, Finset.mem_map, Function.Embedding.coe_subtype, + Finset.mem_filter, Finset.mem_univ, true_and] + constructor + · rintro (⟨f,hf,rfl⟩ | h) + · exact Or.inl ⟨f.property,hf⟩ + · exact Or.inr h + · rintro (⟨he,hm⟩ | h) + · exact Or.inl ⟨⟨e,he⟩,hm,rfl⟩ + · exact Or.inr h + +omit [Fintype V] in +@[simp] theorem mem_fractionalAdd_fractional (G : LooplessGraph V E) {x : E → ℝ} + (hx : x ∈ G.polytope) (M : (fractionalGraph G x).Matching) (e : {e // IsFractional x e}) : + e.val ∈ (fractionalAdd G hx M).val ↔ e ∈ M.val := by + rw [mem_fractionalAdd] + simp only [exists_prop, Subtype.coe_eta] + constructor + · rintro (⟨_, hm⟩ | h) + · exact hm + · exact ((ne_of_lt e.property.2) h).elim + · intro h + exact Or.inl ⟨e.property,h⟩ + +omit [Fintype V] in +theorem fractionalAdd_injective (G : LooplessGraph V E) {x : E → ℝ} (hx : x ∈ G.polytope) : + Function.Injective (fractionalAdd G hx) := by + intro M N h + apply Subtype.ext + ext e + rw [← mem_fractionalAdd_fractional G hx M e, ← mem_fractionalAdd_fractional G hx N e, h] + +def FixedMatching (G : LooplessGraph V E) (x : E → ℝ) (M : G.Matching) : Prop := + ∀ e, ¬IsFractional x e → (e ∈ M.val ↔ x e = 1) + +def fractionalRemove (G : LooplessGraph V E) {x : E → ℝ} (hx : x ∈ G.polytope) + (M : G.Matching) (hM : FixedMatching G x M) : (fractionalGraph G x).Matching := by + classical + refine ⟨Finset.univ.filter (fun e => e.val ∈ M.val), ?_⟩ + intro v + obtain ⟨e, ⟨he, hi⟩, hu⟩ := M.property v.val + have hefrac : IsFractional x e := by + by_contra hn + exact fractional_no_forced G hx v.property ((hM e hn).mp he) hi + refine ⟨⟨e,hefrac⟩, ⟨by simpa using he, (fractional_incident G x _ _).mpr hi⟩, ?_⟩ + intro f hf + apply Subtype.ext + exact hu f.val ⟨by simpa using hf.1, (fractional_incident G x _ _).mp hf.2⟩ + +omit [Fintype V] in +theorem fractionalAdd_range (G : LooplessGraph V E) {x : E → ℝ} (hx : x ∈ G.polytope) + (M : G.Matching) : M ∈ Set.range (fractionalAdd G hx) ↔ FixedMatching G x M := by + constructor + · rintro ⟨N,rfl⟩ e he + rw [mem_fractionalAdd] + simp [he] + · intro hM + refine ⟨fractionalRemove G hx M hM, ?_⟩ + apply Subtype.ext + ext e + by_cases he : IsFractional x e + · rw [← (show (⟨e,he⟩ : {e // IsFractional x e}).val = e from rfl)] + rw [mem_fractionalAdd_fractional] + simp [fractionalRemove] + · rw [mem_fractionalAdd] + simp [he, hM e he] + +omit [Fintype V] [DecidableEq V] in +theorem law_zero_of_mean_zero (G : LooplessGraph V E) {p : G.Matching → ℝ} + (hp : p ∈ probabilitySimplex G.Matching) {e : E} (he : G.mean p e = 0) + (M : G.Matching) (hM : e ∈ M.val) : p M = 0 := by + have hz := (Finset.sum_eq_zero_iff_of_nonneg (fun N (_ : N ∈ Finset.univ) => + mul_nonneg (hp.1 N) (G.indicator_nonneg N e))).mp he M (by simp) + simpa [LooplessGraph.indicator, hM] using hz + +omit [Fintype V] [DecidableEq V] in +theorem fractional_law_support (G : LooplessGraph V E) {x : E → ℝ} (hx : x ∈ G.polytope) + {z : {e // IsFractional x e} → ℝ} {p : G.Matching → ℝ} + (hp : p ∈ G.feasibleLaws (fractionalExtension x z)) {M : G.Matching} (hM : p M ≠ 0) : + FixedMatching G x M := by + intro e he + have hm : G.mean p e = x e := by rw [hp.2, fractionalExtension_apply_fixed x z he] + rcases fixed_or_zero G hx he with hz | ho + · constructor + · intro h + exact (hM (law_zero_of_mean_zero G hp.1 (hm.trans hz) M h)).elim + · intro h + linarith + · refine ⟨fun _ => ho, fun _ => ?_⟩ + by_contra hn + exact hM (G.law_support_of_mean_one hp.1 (hm.trans ho) M hn) + +theorem fiberMass_injective_apply {A : Type uA} {B : Type uB} [Fintype A] [DecidableEq B] + (p : A → ℝ) (f : A → B) (hf : Function.Injective f) (a : A) : + fiberMass p f (f a) = p a := by + classical + simp [fiberMass, hf.eq_iff] + +theorem fiberMass_outside {A : Type uA} {B : Type uB} [Fintype A] [DecidableEq B] + (p : A → ℝ) (f : A → B) (b : B) (hb : b ∉ Set.range f) : fiberMass p f b = 0 := by + apply Finset.sum_eq_zero + intro a _ + exact ite_eq_right (fun h => hb ⟨a,h⟩) + +theorem fiberMass_pullback {A : Type uA} {B : Type uB} [Fintype A] [DecidableEq B] + (p : B → ℝ) (f : A → B) (hf : Function.Injective f) + (hp : ∀ b, b ∉ Set.range f → p b = 0) : + fiberMass (fun a => p (f a)) f = p := by + ext b + by_cases hb : b ∈ Set.range f + · obtain ⟨a,rfl⟩ := hb + exact fiberMass_injective_apply _ _ hf a + · rw [fiberMass_outside _ _ _ hb, hp b hb] + +theorem simplex_of_fiberMass {A : Type uA} {B : Type uB} [Fintype A] [Fintype B] [DecidableEq B] + (p : A → ℝ) (f : A → B) (hf : Function.Injective f) + (hp : fiberMass p f ∈ probabilitySimplex B) : p ∈ probabilitySimplex A := by + refine ⟨fun a => ?_, ?_⟩ + · simpa only [fiberMass_injective_apply p f hf] using hp.1 (f a) + · rw [← fiberMass_sum p f] + exact hp.2 + +omit [Fintype V] in +theorem fractionalAdd_indicator (G : LooplessGraph V E) {x : E → ℝ} (hx : x ∈ G.polytope) + (M : (fractionalGraph G x).Matching) : + G.indicator (fractionalAdd G hx M) = fractionalExtension x ((fractionalGraph G x).indicator M) := by + ext e + by_cases he : IsFractional x e + · rw [← (show (⟨e,he⟩ : {e // IsFractional x e}).val = e from rfl), + fractionalExtension_apply_fractional] + simp only [LooplessGraph.indicator, mem_fractionalAdd_fractional G hx M ⟨e,he⟩] + · rw [fractionalExtension_apply_fixed x _ he] + simp only [LooplessGraph.indicator, mem_fractionalAdd] + rcases fixed_or_zero G hx he with h | h <;> simp [he,h] + +omit [Fintype V] in +theorem fractional_mean_push (G : LooplessGraph V E) {x : E → ℝ} (hx : x ∈ G.polytope) + {q : (fractionalGraph G x).Matching → ℝ} (hq : q ∈ probabilitySimplex (fractionalGraph G x).Matching) : + G.mean (fiberMass q (fractionalAdd G hx)) = + fractionalExtension x ((fractionalGraph G x).mean q) := by + ext e + rw [LooplessGraph.mean, fiberMass_expect] + simp_rw [fractionalAdd_indicator G hx] + by_cases he : IsFractional x e + · simp only [fractionalExtension, he, ↓reduceDIte, AffineMap.coe_mk] + rfl + · simp only [fractionalExtension_apply_fixed x _ he] + rw [← Finset.sum_mul, hq.2, one_mul] + +omit [Fintype V] in +theorem fractional_pull_feasible (G : LooplessGraph V E) {x : E → ℝ} (hx : x ∈ G.polytope) + {z : {e // IsFractional x e} → ℝ} {p : G.Matching → ℝ} + (hp : p ∈ G.feasibleLaws (fractionalExtension x z)) : + p = fiberMass (fun N => p (fractionalAdd G hx N)) (fractionalAdd G hx) ∧ + (fun N => p (fractionalAdd G hx N)) ∈ (fractionalGraph G x).feasibleLaws z := by + have hinj := fractionalAdd_injective G hx + have hpe : fiberMass (fun N => p (fractionalAdd G hx N)) (fractionalAdd G hx) = p := by + apply fiberMass_pullback _ _ hinj + intro M hM + by_contra hn + exact hM ((fractionalAdd_range G hx M).mpr (fractional_law_support G hx hp hn)) + have hsimplex : (fun N => p (fractionalAdd G hx N)) ∈ probabilitySimplex (fractionalGraph G x).Matching := + simplex_of_fiberMass _ _ hinj (by rw [hpe]; exact hp.1) + refine ⟨hpe.symm, hsimplex, fractionalExtension_injective x ?_⟩ + rw [← fractional_mean_push G hx hsimplex, hpe, hp.2] + +omit [Fintype V] in +theorem fractional_feasible_iff (G : LooplessGraph V E) {x : E → ℝ} (hx : x ∈ G.polytope) + (z : {e // IsFractional x e} → ℝ) (q : (fractionalGraph G x).Matching → ℝ) : + q ∈ (fractionalGraph G x).feasibleLaws z ↔ + fiberMass q (fractionalAdd G hx) ∈ G.feasibleLaws (fractionalExtension x z) := by + constructor + · intro hq + exact ⟨fiberMass_mem_simplex hq.1 _, (fractional_mean_push G hx hq.1).trans (congrArg _ hq.2)⟩ + · intro hp + have hq := (fractional_pull_feasible G hx hp).2 + simpa only [fiberMass_injective_apply q _ (fractionalAdd_injective G hx)] using hq + +omit [Fintype V] in +theorem fractional_image_eq (G : LooplessGraph V E) {x : E → ℝ} (hx : x ∈ G.polytope) : + fractionalExtension x '' (fractionalGraph G x).polytope = fixedFace G x := by + ext y + constructor + · rintro ⟨z,hz,rfl⟩ + obtain ⟨q,hq⟩ := ((fractionalGraph G x).mem_polytope_iff z).mp hz + exact ⟨(G.mem_polytope_iff _).mpr ⟨_, (fractional_feasible_iff G hx z q).mp hq⟩, + fun e he => fractionalExtension_apply_fixed x z he⟩ + · intro hy + let z : {e // IsFractional x e} → ℝ := fun e => y e.val + have hext : fractionalExtension x z = y := by + ext e + by_cases he : IsFractional x e + · simp [fractionalExtension,he,z] + · simp [fractionalExtension,he,hy.2 e he] + obtain ⟨p,hp⟩ := (G.mem_polytope_iff _).mp hy.1 + have hp' : p ∈ G.feasibleLaws (fractionalExtension x z) := hext ▸ hp + exact ⟨z, ((fractionalGraph G x).mem_polytope_iff z).mpr + ⟨_,(fractional_pull_feasible G hx hp').2⟩, hext⟩ + +omit [Fintype V] in +theorem fractionalMean_mem (G : LooplessGraph V E) {x : E → ℝ} (hx : x ∈ G.polytope) : + fractionalMean x ∈ (fractionalGraph G x).polytope := by + have h : x ∈ fixedFace G x := ⟨hx,fun _ _ => rfl⟩ + rw [← fractional_image_eq G hx] at h + obtain ⟨z,hz,he⟩ := h + have : z = fractionalMean x := fractionalExtension_injective x (he.trans (fractionalExtension_mean x).symm) + exact this ▸ hz + +omit [Fintype V] [DecidableEq V] in +theorem fixedFace_extreme (G : LooplessGraph V E) {x : E → ℝ} (hx : x ∈ G.polytope) : + IsExtreme ℝ G.polytope (fixedFace G x) := by + refine ⟨fun _ h => h.1, ?_⟩ + intro y hy z hz w hw hseg + obtain ⟨a,b,ha,hb,hab,rfl⟩ := hseg + refine ⟨hy, ?_⟩ + intro e he + have heq := hw.2 e he + change a * y e + b * z e = x e at heq + have hyb := G.coordinate_mem_Icc hy e + have hzb := G.coordinate_mem_Icc hz e + rcases hyb with ⟨hy0,hy1⟩ + rcases hzb with ⟨hz0,hz1⟩ + rcases fixed_or_zero G hx he with h | h + · rw [h] at heq ⊢ + have := mul_nonneg hb.le hz0 + nlinarith + · rw [h] at heq ⊢ + apply le_antisymm hy1 + by_contra! hn + have hpos := mul_pos ha (sub_pos.mpr hn) + have hnonneg := mul_nonneg hb.le (sub_nonneg.mpr hz1) + nlinarith + +section AffineFaces +variable {A : Type uA} {B : Type uB} [AddCommGroup A] [Module ℝ A] [AddCommGroup B] [Module ℝ B] + +theorem extreme_affine_image (f : A →ᵃ[ℝ] B) (hf : Function.Injective f) + {P Q : Set A} (h : IsExtreme ℝ P Q) : IsExtreme ℝ (f '' P) (f '' Q) := by + refine ⟨Set.image_mono h.subset, ?_⟩ + rintro _ ⟨u,hu,rfl⟩ _ ⟨v,hv,rfl⟩ _ ⟨w,hw,rfl⟩ hseg + rw [← image_openSegment ℝ f] at hseg + obtain ⟨w',hw',he⟩ := hseg + have hww : w' = w := hf he + exact ⟨u, h.left_mem_of_mem_openSegment hu hv hw (hww ▸ hw'), rfl⟩ + +theorem extreme_affine_preimage (f : A →ᵃ[ℝ] B) {P : Set A} {Q R : Set B} + (hPQ : f '' P ⊆ Q) (hQR : IsExtreme ℝ Q R) : + IsExtreme ℝ P (P ∩ f ⁻¹' R) := by + refine ⟨Set.inter_subset_left, ?_⟩ + intro u hu v hv w hw hseg + refine ⟨hu, hQR.left_mem_of_mem_openSegment (hPQ ⟨u,hu,rfl⟩) + (hPQ ⟨v,hv,rfl⟩) hw.2 ?_⟩ + rw [← image_openSegment ℝ f] + exact ⟨w,hseg,rfl⟩ +end AffineFaces + +section FaceMaps +variable {W : Type uW} {D : Type uD} [Fintype W] [Fintype D] [DecidableEq W] [DecidableEq D] + +theorem minimalFace_map (G : LooplessGraph V E) (H : LooplessGraph W D) + (f : (D → ℝ) →ᵃ[ℝ] (E → ℝ)) (hf : Function.Injective f) + (hP : IsExtreme ℝ G.polytope (f '' H.polytope)) + {z : D → ℝ} (hz : z ∈ H.polytope) : + f '' minimalFace H z = minimalFace G (f z) := by + have hfg : f z ∈ G.polytope := hP.subset ⟨z,hz,rfl⟩ + have ⟨hzz, _, hHz, hminH⟩ := minimalFace_spec H hz + have ⟨hfz, _, hGz, hminG⟩ := minimalFace_spec G hfg + apply Set.Subset.antisymm + · have hp := extreme_affine_preimage f hP.subset hGz + have hsub := hminH _ hp ⟨hz,hfz⟩ + rintro _ ⟨u,hu,rfl⟩ + exact (hsub hu).2 + · exact hminG _ (hP.trans (extreme_affine_image f hf hHz)) ⟨z,hzz,rfl⟩ + +theorem faceDimension_map (G : LooplessGraph V E) (H : LooplessGraph W D) + (f : (D → ℝ) →ᵃ[ℝ] (E → ℝ)) (hf : Function.Injective f) + (hP : IsExtreme ℝ G.polytope (f '' H.polytope)) + {z : D → ℝ} (hz : z ∈ H.polytope) : + faceDimension H z = faceDimension G (f z) := by + rw [faceDimension, faceDimension, ← minimalFace_map G H f hf hP hz, + ← AffineSubspace.map_span, AffineSubspace.map_direction] + exact (Submodule.equivMapOfInjective _ (f.linear_injective_iff.mpr hf) _).finrank_eq +end FaceMaps + +theorem fractional_minimalFace (G : LooplessGraph V E) {x : E → ℝ} (hx : x ∈ G.polytope) : + fractionalExtension x '' minimalFace (fractionalGraph G x) (fractionalMean x) = minimalFace G x := by + have hextreme : IsExtreme ℝ G.polytope (fractionalExtension x '' (fractionalGraph G x).polytope) := + (fractional_image_eq G hx).symm ▸ fixedFace_extreme G hx + simpa only [fractionalExtension_mean] using minimalFace_map G (fractionalGraph G x) + (fractionalExtension x) (fractionalExtension_injective x) hextreme (fractionalMean_mem G hx) + +theorem fractional_dimension (G : LooplessGraph V E) {x : E → ℝ} (hx : x ∈ G.polytope) : + faceDimension (fractionalGraph G x) (fractionalMean x) = faceDimension G x := by + have hextreme : IsExtreme ℝ G.polytope (fractionalExtension x '' (fractionalGraph G x).polytope) := + (fractional_image_eq G hx).symm ▸ fixedFace_extreme G hx + simpa only [fractionalExtension_mean] using faceDimension_map G (fractionalGraph G x) + (fractionalExtension x) (fractionalExtension_injective x) hextreme (fractionalMean_mem G hx) + +omit [Fintype V] [DecidableEq V] in +theorem fractional_entropy_terms (G : LooplessGraph V E) {x : E → ℝ} (hx : x ∈ G.polytope) : + entropy (fractionalMean x) = entropy x ∧ + complementEntropy (fractionalMean x) = complementEntropy x := by + constructor + · unfold entropy fractionalMean + apply sum_subtype_supported (IsFractional x) (fun e => Real.negMulLog (x e)) + intro e he + rcases fixed_or_zero G hx he with h | h <;> simp [h] + · unfold complementEntropy + unfold entropy fractionalMean + apply sum_subtype_supported (IsFractional x) (fun e => Real.negMulLog (1-x e)) + intro e he + rcases fixed_or_zero G hx he with h | h <;> simp [h] + +omit [Fintype V] in +theorem fractional_maxEntropy (G : LooplessGraph V E) {x : E → ℝ} (hx : x ∈ G.polytope) + {z : {e // IsFractional x e} → ℝ} (hz : z ∈ (fractionalGraph G x).polytope) : + maxMatchingEntropy G (fractionalExtension x z) = maxMatchingEntropy (fractionalGraph G x) z := by + obtain ⟨q,hq,hqopt⟩ := maxMatchingEntropy_attained (fractionalGraph G x) hz + have hq' := (fractional_feasible_iff G hx z q).mp hq + have hz' := (G.mem_polytope_iff _).mpr ⟨_,hq'⟩ + obtain ⟨p,hp,hpopt⟩ := maxMatchingEntropy_attained G hz' + have ⟨hpe,hp'⟩ := fractional_pull_feasible G hx hp + apply le_antisymm + · rw [← hpopt, hpe, entropy_fiberMass_injective _ _ (fractionalAdd_injective G hx)] + exact entropy_le_maxMatchingEntropy _ hp' + · rw [← hqopt, ← entropy_fiberMass_injective q _ (fractionalAdd_injective G hx)] + exact entropy_le_maxMatchingEntropy _ hq' + +theorem fractional_laws {V : Type uV} {E : Type uE} + [Fintype V] [Fintype E] [DecidableEq V] [DecidableEq E] (G : LooplessGraph V E) {x : E → ℝ} (hx : x ∈ G.polytope) : + ∃ lift : (fractionalGraph G x).Matching → G.Matching, Function.Injective lift ∧ + (∀ z q, q ∈ (fractionalGraph G x).feasibleLaws z ↔ + fiberMass q lift ∈ G.feasibleLaws (fractionalExtension x z)) ∧ + (∀ z p, p ∈ G.feasibleLaws (fractionalExtension x z) → + p = fiberMass (fun N => p (lift N)) lift ∧ + (fun N => p (lift N)) ∈ (fractionalGraph G x).feasibleLaws z) ∧ + (∀ z ∈ (fractionalGraph G x).polytope, + maxMatchingEntropy G (fractionalExtension x z) = maxMatchingEntropy (fractionalGraph G x) z) ∧ + entropy (fractionalMean x) = entropy x ∧ + complementEntropy (fractionalMean x) = complementEntropy x := by + exact ⟨fractionalAdd G hx, fractionalAdd_injective G hx, fractional_feasible_iff G hx, + fun _ _ hp => fractional_pull_feasible G hx hp, fun _ hz => fractional_maxEntropy G hx hz, + fractional_entropy_terms G hx⟩ + +theorem fractional_reduction (G : LooplessGraph V E) {x : E → ℝ} (hx : x ∈ G.polytope) : + IsExtreme ℝ G.polytope (fixedFace G x) ∧ + Function.Injective (fractionalExtension x) ∧ + fractionalExtension x '' (fractionalGraph G x).polytope = fixedFace G x ∧ + fractionalExtension x '' minimalFace (fractionalGraph G x) (fractionalMean x) = minimalFace G x ∧ + faceDimension (fractionalGraph G x) (fractionalMean x) = faceDimension G x ∧ + ∃ m_f : ℕ, Fintype.card {v // FractionalVertex G x v} = 2 * m_f ∧ + (∑ e : {e // IsFractional x e}, x e.val) = (m_f : ℝ) ∧ + (0 < m_f → Fintype.card {e // IsFractional x e} + 2 ≤ faceDimension G x + 3 * m_f) ∧ + (m_f = 0 → ∃ M : G.Matching, G.indicator M = x ∧ faceDimension G x = 0) := by + have hz := fractionalMean_mem G hx + have hd := fractional_dimension G hx + refine ⟨fixedFace_extreme G hx, fractionalExtension_injective x, fractional_image_eq G hx, + fractional_minimalFace G hx, hd, ?_⟩ + obtain ⟨m,hm⟩ := even_of_mem (fractionalGraph G x) hz + have hm' : Fintype.card {v // FractionalVertex G x v} = 2 * m := by omega + refine ⟨m,hm',(fractionalGraph G x).marginal_sum hm' hz,?_,?_⟩ + · intro hm0 + have hr := minimalFace_rank (fractionalGraph G x) m hm0 hm' hz + have hc : Fintype.card {e : {e // IsFractional x e} // 0 < fractionalMean x e} = + Fintype.card {e // IsFractional x e} := + Fintype.card_congr (Equiv.subtypeUnivEquiv (fun e => e.property.1)) + rwa [hc,hd] at hr + · intro hm0 + have hvzero : Fintype.card {v // FractionalVertex G x v} = 0 := by omega + have : IsEmpty {v // FractionalVertex G x v} := Fintype.card_eq_zero_iff.mp hvzero + have : IsEmpty {e // IsFractional x e} := ⟨fun e => isEmptyElim ((fractionalGraph G x).left e)⟩ + obtain ⟨M⟩ := matching_nonempty_of_mem (fractionalGraph G x) hz + refine ⟨fractionalAdd G hx M, ?_, ?_⟩ + · rw [fractionalAdd_indicator G hx] + have hM : (fractionalGraph G x).indicator M = fractionalMean x := Subsingleton.elim _ _ + rw [hM, fractionalExtension_mean] + · rw [← hd, faceDimension] + have hle := (affineSpan ℝ (minimalFace (fractionalGraph G x) (fractionalMean x))).direction.finrank_le + have hzdim : Module.finrank ℝ ({e // IsFractional x e} → ℝ) = 0 := by simp + rw [hzdim] at hle + exact Nat.eq_zero_of_le_zero hle + +end MatchingEntropyBounds.Refined + +end + +end OAI diff --git a/lean/OAI/Combinatorics/MatchingEntropy/KleeSharpness.lean b/lean/OAI/Combinatorics/MatchingEntropy/KleeSharpness.lean new file mode 100644 index 0000000000000000000000000000000000000000..e097775aeed81675d7dd8bdb4682632bc415c66e --- /dev/null +++ b/lean/OAI/Combinatorics/MatchingEntropy/KleeSharpness.lean @@ -0,0 +1,296 @@ +import OAI.Combinatorics.MatchingEntropy.TriangleExpansion + +namespace OAI + +noncomputable section + +open scoped BigOperators Topology +open Filter + +universe uV uE uI uJ uA uB uC uW uF uD uι + +namespace MatchingEntropyBounds.Refined + +section ColoredSupport +variable {V : Type uV} {E : Type uE} [Fintype E] [DecidableEq V] [DecidableEq E] + +omit [DecidableEq V] in +theorem colorMatching_indicator (G : LooplessGraph V E) (c : E → Fin 3) + (hc : CubicColoring G c) (i : Fin 3) : G.indicator (colorMatching G c hc i) = coloredVector c i := by + ext e + simp [LooplessGraph.indicator,colorMatching,colorEdges,coloredVector] + +omit [DecidableEq V] [DecidableEq E] in +theorem colorMatching_injective (G : LooplessGraph V E) (c : E → Fin 3) + (hc : CubicColoring G c) (v : V) : Function.Injective (colorMatching G c hc) := by + intro i j hij + have he : vertexColorEdge G c hc v i ∈ (colorMatching G c hc i).val := by + simp [colorMatching,colorEdges,(vertexColorEdge_spec G c hc v i).2] + rw [hij] at he + have hh : c (vertexColorEdge G c hc v i) = j := by simpa [colorMatching,colorEdges] using he + exact (vertexColorEdge_spec G c hc v i).2.symm.trans hh + +omit [Fintype E] [DecidableEq V] [DecidableEq E] in +theorem coloredVector_linearIndependent (G : LooplessGraph V E) (c : E → Fin 3) + (hc : CubicColoring G c) (v : V) : LinearIndependent ℝ (coloredVector c) := by + rw [linearIndependent_iff'] + intro s w hw i hi + have he := congrFun hw (vertexColorEdge G c hc v i) + simp only [Finset.sum_apply,Pi.smul_apply,smul_eq_mul,Pi.zero_apply,coloredVector, + (vertexColorEdge_spec G c hc v i).2,mul_ite,mul_one,mul_zero] at he + simpa [Finset.sum_ite_eq,hi] using he + +omit [DecidableEq V] in +theorem colored_uniform_mean (G : LooplessGraph V E) (c : E → Fin 3) + (hc : CubicColoring G c) : + G.mean (fiberMass (uniformLaw (Fin 3)) (colorMatching G c hc)) = fun _ => 1/3 := by + ext e + rw [LooplessGraph.mean,fiberMass_expect] + simp_rw [colorMatching_indicator] + simp only [uniformLaw,Fintype.card_fin,coloredVector,mul_ite,mul_one,mul_zero] + simp [Finset.sum_ite_eq] + +omit [DecidableEq E] in +theorem expanded_colorMatching (G : LooplessGraph V E) (c : E → Fin 3) + (hc : CubicColoring G c) (v : V) (i : Fin 3) : + expandMatching G c v (colorMatching G c hc i) = + colorMatching (triangleExpansion G c v) (expandedColor c) (cubicColoring_expansion G c hc v) i := by + have he : c (incidentChoice G (colorMatching G c hc i) v) = i := by + simpa [colorMatching,colorEdges] using (incidentChoice_spec G (colorMatching G c hc i) v).1 + apply Subtype.ext + change (colorEdges c i).disjSum {c (incidentChoice G (colorMatching G c hc i) v)} = + colorEdges (expandedColor c) i + rw [he] + ext e + rcases e with e | j <;> simp! [colorEdges,expandedColor] + +omit [Fintype E] [DecidableEq V] [DecidableEq E] in +theorem triangleExtension_colored (G : LooplessGraph V E) (c : E → Fin 3) + (hc : CubicColoring G c) (v : V) (i : Fin 3) : + triangleExtension G c hc v (coloredVector c i) = coloredVector (expandedColor c) i := by + ext e + rcases e with e | j + · rfl + · simp only [triangleExtension,LinearMap.coe_mk,AddHom.coe_mk,Sum.elim_inr,coloredVector,expandedColor,(vertexColorEdge_spec G c hc v j).2] + rfl + +end ColoredSupport + +theorem kleeEDecEq_succ (n : ℕ) : kleeEDecEq (n+1) = inferInstanceAs (DecidableEq (KleeE n ⊕ Fin 3)) := Subsingleton.elim _ _ +theorem kleeVDecEq_succ (n : ℕ) : kleeVDecEq (n+1) = inferInstanceAs (DecidableEq (KleeV n ⊕ Fin 2)) := Subsingleton.elim _ _ +theorem kleeEDecEq_zero : kleeEDecEq 0 = inferInstanceAs (DecidableEq (Fin 3)) := Subsingleton.elim _ _ + +theorem klee_law_eq_fiber (n : ℕ) : + kleeLaw n = fiberMass (uniformLaw (Fin 3)) (colorMatching (kleeGraph n) (kleeColor n) (klee_cubic n)) := by + ext M + unfold kleeLaw fiberMass + apply Finset.sum_congr rfl + intro i _ + have he : colorMatching (kleeGraph n) (kleeColor n) (klee_cubic n) i = M ↔ + M.val = colorEdges (kleeColor n) i := by + rw [Subtype.ext_iff] + exact eq_comm + simp [he,uniformLaw] + +theorem klee_law_feasible (n : ℕ) : kleeLaw n ∈ (kleeGraph n).feasibleLaws (kleeUniform n) := by + rw [klee_law_eq_fiber] + exact ⟨fiberMass_mem_simplex uniformLaw_simplex _,colored_uniform_mean _ _ (klee_cubic n)⟩ + +theorem klee_uniform_mem (n : ℕ) : kleeUniform n ∈ (kleeGraph n).polytope := + ((kleeGraph n).mem_polytope_iff _).mpr ⟨_,klee_law_feasible n⟩ + +theorem klee_entropy_law (n : ℕ) : entropy (kleeLaw n) = Real.log 3 := by + rw [klee_law_eq_fiber,entropy_fiberMass_injective _ _ (colorMatching_injective _ _ (klee_cubic n) (kleeRoot n)),uniformLaw_entropy] + norm_num + +theorem klee_uniform_extend (n : ℕ) : + triangleExtension (kleeGraph n) (kleeColor n) (klee_cubic n) (kleeRoot n) (kleeUniform n) = kleeUniform (n+1) := by + ext e + rcases e with e | i <;> rfl + +theorem klee_law_expand (n : ℕ) : + fiberMass (kleeLaw n) (expandMatching (kleeGraph n) (kleeColor n) (kleeRoot n)) = kleeLaw (n+1) := by + rw [klee_law_eq_fiber,klee_law_eq_fiber,fiberMass_comp] + ext M + unfold fiberMass + apply Finset.sum_congr rfl + intro i _ + rw [Function.comp_apply,expanded_colorMatching _ _ (klee_cubic n)] + rw [kleeEDecEq_succ] + rfl + +theorem klee_triangle_expand (n : ℕ) : + triangleExtension (kleeGraph n) (kleeColor n) (klee_cubic n) (kleeRoot n) '' kleeTriangle n = kleeTriangle (n+1) := by + rw [kleeTriangle,LinearMap.image_convexHull,← Set.range_comp,kleeTriangle] + congr 1 + apply congrArg Set.range + funext i + exact triangleExtension_colored _ _ (klee_cubic n) _ i + +theorem klee_zero_matching (M : (kleeGraph 0).Matching) : + ∃ i : Fin 3, M = colorMatching (kleeGraph 0) (kleeColor 0) (klee_cubic 0) i := by + obtain ⟨i,hi,hu⟩ := M.property (0 : Fin 2) + refine ⟨i,Subtype.ext ?_⟩ + ext e + have he : (kleeGraph 0).Incident (0 : Fin 2) e := Or.inl rfl + simp only [colorMatching,colorEdges,Finset.mem_filter,Finset.mem_univ,true_and] + change e ∈ M.val ↔ e = i + exact ⟨fun h => hu e ⟨h,he⟩,fun h => h ▸ hi.1⟩ + +theorem klee_zero_polytope : (kleeGraph 0).polytope = kleeTriangle 0 := by + unfold LooplessGraph.polytope kleeTriangle + congr 1 + ext x + constructor + · rintro ⟨M,rfl⟩ + obtain ⟨i,rfl⟩ := klee_zero_matching M + exact ⟨i,(colorMatching_indicator _ _ _ _).symm⟩ + · rintro ⟨i,rfl⟩ + exact ⟨_,colorMatching_indicator _ _ (klee_cubic 0) i⟩ + +theorem klee_zero_minimal : minimalFace (kleeGraph 0) (kleeUniform 0) = (kleeGraph 0).polytope := by + apply Set.Subset.antisymm (fun _ hy => hy.1) + intro y hy + refine ⟨hy,?_,?_⟩ + · intro e he + norm_num [kleeUniform] at he + · intro S hS _ + have hcard : S.card ≤ 2 := by + have hh := Finset.card_le_univ S + change S.card ≤ Fintype.card (Fin 2) at hh + simpa using hh + have h1 : S.card = 1 := by + obtain ⟨k,hk⟩ := hS + omega + obtain ⟨v,rfl⟩ := Finset.card_eq_one.mp h1 + rw [LooplessGraph.cutMass_singleton] + exact ((kleeGraph 0).polytope_subset_constraintPolytope hy).2.1 v + +theorem klee_minimal (n : ℕ) : minimalFace (kleeGraph n) (kleeUniform n) = kleeTriangle n := by + induction n with + | zero => exact klee_zero_minimal.trans klee_zero_polytope + | succ n ih => + have he := ((expansion_face (kleeGraph n) (kleeColor n) (klee_cubic n) (kleeRoot n)).2.2 + (kleeUniform n) (klee_uniform_mem n)).1 + rw [klee_uniform_extend,ih,klee_triangle_expand] at he + rw [kleeEDecEq_succ,kleeVDecEq_succ] + exact he + +theorem klee_dimension (n : ℕ) : faceDimension (kleeGraph n) (kleeUniform n) = 2 := by + rw [faceDimension,klee_minimal,kleeTriangle,affineSpan_convexHull,direction_affineSpan] + exact (coloredVector_linearIndependent _ _ (klee_cubic n) (kleeRoot n)).affineIndependent.finrank_vectorSpan (by decide) + +theorem klee_zero_mean (p : (kleeGraph 0).Matching → ℝ) (i : KleeE 0) : + (kleeGraph 0).mean p i = + p (colorMatching (kleeGraph 0) (kleeColor 0) (klee_cubic 0) (kleeColor 0 i)) := by + classical + unfold LooplessGraph.mean + rw [Finset.sum_eq_single + (colorMatching (kleeGraph 0) (kleeColor 0) (klee_cubic 0) (kleeColor 0 i))] + · rw [colorMatching_indicator] + simp [coloredVector] + · intro M _ hM + obtain ⟨j,rfl⟩ := klee_zero_matching M + rw [colorMatching_indicator] + have hij : kleeColor 0 i ≠ j := fun h => hM (congrArg _ h.symm) + simp [coloredVector,hij] + · simp + +theorem klee_unique_law (n : ℕ) : (kleeGraph n).feasibleLaws (kleeUniform n) = {kleeLaw n} := by + apply Set.Subset.antisymm ?_ (Set.singleton_subset_iff.mpr (klee_law_feasible n)) + induction n with + | zero => + intro p hp + apply Set.mem_singleton_iff.mpr + ext M + obtain ⟨i,rfl⟩ := klee_zero_matching M + have hp' : p (colorMatching (kleeGraph 0) (kleeColor 0) (klee_cubic 0) i) = 1/3 := + (klee_zero_mean p i).symm.trans (congrFun hp.2 i) + rw [hp',klee_law_eq_fiber,fiberMass_injective_apply _ _ + (colorMatching_injective _ _ (klee_cubic 0) (kleeRoot 0))] + norm_num [kleeUniform,uniformLaw] + | succ n ih => + intro p hp + have hp' : p ∈ (triangleExpansion (kleeGraph n) (kleeColor n) (kleeRoot n)).feasibleLaws + (triangleExtension (kleeGraph n) (kleeColor n) (klee_cubic n) (kleeRoot n) (kleeUniform n)) := by + rw [klee_uniform_extend] + rw [kleeEDecEq_succ] at hp + exact hp + obtain ⟨heq,hq⟩ := expanded_pull_feasible _ _ (klee_cubic n) _ (klee_uniform_mem n) hp' + have hh := Set.mem_singleton_iff.mp (ih hq) + rw [hh,klee_law_expand] at heq + exact Set.mem_singleton_iff.mpr heq + +theorem klee_maxEntropy (n : ℕ) : maxMatchingEntropy (kleeGraph n) (kleeUniform n) = Real.log 3 := by + obtain ⟨p,hp,he⟩ := maxMatchingEntropy_attained _ (klee_uniform_mem n) + rw [klee_unique_law,Set.mem_singleton_iff] at hp + rw [← he,hp,klee_entropy_law] + +theorem klee_entropy_terms (n : ℕ) : + entropy (kleeUniform n) = (n + 1) * Real.log 3 ∧ + complementEntropy (kleeUniform n) = 2 * (n + 1) * Real.log (3 / 2) := by + have hF : Real.negMulLog (1/3) = Real.log 3 / 3 := by + norm_num [Real.negMulLog,Real.log_div] + ring + have hB : Real.negMulLog (1-1/3) = (2/3) * Real.log (3/2) := by + norm_num [Real.negMulLog,Real.log_div] + ring + constructor + · simp only [entropy,kleeUniform,hF,Finset.sum_const,Finset.card_univ,klee_cardE,nsmul_eq_mul, + Nat.cast_mul,Nat.cast_add,Nat.cast_one,Nat.cast_ofNat] + ring + · change (∑ _ : KleeE n, Real.negMulLog (1-1/3)) = _ + simp only [hB,Finset.sum_const,Finset.card_univ,klee_cardE,nsmul_eq_mul, + Nat.cast_mul,Nat.cast_add,Nat.cast_one,Nat.cast_ofNat] + ring + +theorem klee_sharp_face (n : ℕ) : + kleeUniform n ∈ (kleeGraph n).polytope ∧ + minimalFace (kleeGraph n) (kleeUniform n) = kleeTriangle n ∧ + faceDimension (kleeGraph n) (kleeUniform n) = 2 ∧ + Fintype.card (KleeE n) - faceDimension (kleeGraph n) (kleeUniform n) = 3 * (n + 1) - 2 ∧ + (kleeGraph n).feasibleLaws (kleeUniform n) = {kleeLaw n} ∧ + maxMatchingEntropy (kleeGraph n) (kleeUniform n) = Real.log 3 ∧ + entropy (kleeUniform n) = (n + 1) * Real.log 3 ∧ + complementEntropy (kleeUniform n) = 2 * (n + 1) * Real.log (3 / 2) := by + exact ⟨klee_uniform_mem n,klee_minimal n,klee_dimension n,by rw [klee_cardE,klee_dimension], + klee_unique_law n,klee_maxEntropy n,klee_entropy_terms n⟩ + +theorem coefficient_obstruction_scalar (c : ℝ) + (hc : ∀ n : ℕ, (n+2)*Real.log 3 - c*(2*(n+2)*Real.log (3/2)) ≤ Real.log 3) : + Real.log 3 / (2 * Real.log (3 / 2)) ≤ c := by + have hB : 0 < 2 * Real.log (3/2) := mul_pos (by norm_num) (Real.log_pos (by norm_num)) + by_contra! hn + have hd : 0 < Real.log 3 - c*(2*Real.log (3/2)) := sub_pos.mpr ((lt_div_iff₀ hB).mp hn) + obtain ⟨n,hn⟩ := exists_nat_gt (Real.log 3 / (Real.log 3 - c*(2*Real.log (3/2)))) + have hh := (div_lt_iff₀ hd).mp hn + have hc' := hc n + nlinarith + +theorem universal_coefficient_obstruction (c : ℝ) + (hc : ∀ (V E : Type) [Fintype V] [Fintype E] [DecidableEq V] [DecidableEq E] + (G : LooplessGraph V E) (x : E → ℝ), x ∈ G.polytope → + entropy x - c * complementEntropy x ≤ maxMatchingEntropy G x) : + Real.log 3 / (2 * Real.log (3 / 2)) ≤ c := by + apply coefficient_obstruction_scalar c + intro n + have h := hc _ _ (kleeGraph (n+1)) (kleeUniform (n+1)) (klee_uniform_mem (n+1)) + rw [(klee_entropy_terms (n+1)).1,(klee_entropy_terms (n+1)).2,klee_maxEntropy] at h + simpa only [Nat.cast_add,Nat.cast_one,add_assoc,one_add_one_eq_two] using h + +theorem simple_coefficient_obstruction (c : ℝ) + (hc : ∀ (V E : Type) [Fintype V] [Fintype E] [DecidableEq V] [DecidableEq E] + (G : LooplessGraph V E), IsSimpleLabelled G → ∀ x : E → ℝ, x ∈ G.polytope → + entropy x - c * complementEntropy x ≤ maxMatchingEntropy G x) : + Real.log 3 / (2 * Real.log (3 / 2)) ≤ c := by + apply coefficient_obstruction_scalar c + intro n + have h := hc _ _ (kleeGraph (n+1)) (klee_simple (n+1) (by omega)) (kleeUniform (n+1)) (klee_uniform_mem (n+1)) + rw [(klee_entropy_terms (n+1)).1,(klee_entropy_terms (n+1)).2,klee_maxEntropy] at h + simpa only [Nat.cast_add,Nat.cast_one,add_assoc,one_add_one_eq_two] using h + +end MatchingEntropyBounds.Refined + +end + +end OAI diff --git a/lean/OAI/Combinatorics/MatchingEntropy/Main.lean b/lean/OAI/Combinatorics/MatchingEntropy/Main.lean new file mode 100644 index 0000000000000000000000000000000000000000..454ca68b88c8165cb428d8090d681fb1ed208f29 --- /dev/null +++ b/lean/OAI/Combinatorics/MatchingEntropy/Main.lean @@ -0,0 +1,16 @@ +import OAI.Combinatorics.MatchingEntropy.ExpansionSequences + +/-! +# Sharp analytic bounds for perfect-matching entropy + +For a finite loopless labelled multigraph on `2m` vertices, with `m ≥ 1` and a perfect +matching, every point of the matching polytope satisfies +`F - (2 - 2 / m) * B ≤ H ≤ F`. Here `F` and `B` are the coordinate entropy and +complement entropy with natural logarithms, and `H` is the attained supremum of entropy +over all perfect-matching laws with the prescribed mean. + +The development includes the odd-cut description of the matching polytope, sharp face +rank bounds, minimal faces, fractional and connected-component reductions, attained +entropy and weighted partition objectives, matching counts, degenerate cases, colored +triangle-expansion families, and concrete coefficient obstructions. +-/ diff --git a/lean/OAI/Combinatorics/MatchingEntropy/MatchingCovariance.lean b/lean/OAI/Combinatorics/MatchingEntropy/MatchingCovariance.lean new file mode 100644 index 0000000000000000000000000000000000000000..0ac606d6ac10aaa2d3769fb3a3b124f9ae36b55e --- /dev/null +++ b/lean/OAI/Combinatorics/MatchingEntropy/MatchingCovariance.lean @@ -0,0 +1,152 @@ +import OAI.Combinatorics.MatchingEntropy.Continuity + +namespace OAI + +noncomputable section + +open scoped BigOperators Topology +open Filter Matrix + +universe uV uE uI uJ uA uB uC uW uF uD uι + +namespace MatchingEntropyBounds + +variable {V : Type uV} {E : Type uE} [Fintype V] [Fintype E] [DecidableEq V] [DecidableEq E] + +def matchingNormalized (G : LooplessGraph V E) (x : E → ℝ) : + G.Matching → {e // 0 < x e} → ℝ := + normalizedCentered (fun M e => G.indicator M e.val) (fun e => x e.val) + +omit [Fintype V] [DecidableEq V] in +theorem matchingNormalized_average (G : LooplessGraph V E) {x y : E → ℝ} + {q : G.Matching → ℝ} (hq : q ∈ G.feasibleLaws y) (e : {e // 0 < x e}) : + (∑ M, q M*matchingNormalized G x M e)=(y e.val-x e.val)/Real.sqrt (x e.val) := by + simp only [matchingNormalized,normalizedCentered,← mul_div_assoc,mul_sub, + ← Finset.sum_div,Finset.sum_sub_distrib,← Finset.sum_mul,hq.1.2,one_mul] + rw [show (∑ M, q M*G.indicator M e.val)=y e.val from congrFun hq.2 e.val] + +omit [Fintype V] [DecidableEq V] in + +theorem midpoint_law_support (G : LooplessGraph V E) {x v : E → ℝ} {a : ℝ} + {p q r : G.Matching → ℝ} (hp : p ∈ G.feasibleLaws x) + (hopt : entropy p=maxMatchingEntropy G x) + (hq : q ∈ G.feasibleLaws (x+a • v)) + (hr : r ∈ G.feasibleLaws (x+(-a) • v)) : + ∀ M, 0 < q M → 0 < p M := by + let w : G.Matching → ℝ := (1/2:ℝ) • q+(1/2:ℝ) • r + have hw : w ∈ G.feasibleLaws x := by + refine ⟨convex_probabilitySimplex _ hq.1 hr.1 (by norm_num) (by norm_num) (by norm_num),?_⟩ + change G.meanLinear ((1/2:ℝ) • q+(1/2:ℝ) • r) = _ + rw [map_add,map_smul,map_smul] + change (1/2:ℝ) • G.mean q+(1/2:ℝ) • G.mean r = _ + rw [hq.2,hr.2] + ext e + simp only [Pi.add_apply,Pi.smul_apply,smul_eq_mul] + ring + intro M hM + apply matching_optimizer_support G hp hw hopt + change 0 < (1/2:ℝ)*q M+(1/2:ℝ)*r M + have hh := hr.1.1 M + linarith + +theorem normalized_face_mem (G : LooplessGraph V E) {x : E → ℝ} + (heven : Even (Fintype.card V)) {p : G.Matching → ℝ} + (hp : p ∈ G.feasibleLaws x) (hopt : entropy p=maxMatchingEntropy G x) + {u : {e // 0 < x e} → ℝ} (hu : u ∈ G.faceSpace x) : + (fun e => u e/Real.sqrt (x e.val)) ∈ weightedDirectionSpace p (matchingNormalized G x) := by + have hx : x ∈ G.polytope := (G.mem_polytope_iff x).mpr ⟨p,hp⟩ + have hev := G.faceSpace_eventually_line (G.polytope_subset_constraintPolytope hx) hu + have hneg : ∀ᶠ t : ℝ in 𝓝 0, x+(-t) • LooplessGraph.positiveExtension x u ∈ G.constraintPolytope := by + have hc : Tendsto (fun t : ℝ => -t) (𝓝 0) (𝓝 0) := by simpa using continuous_neg.tendsto (0:ℝ) + exact hc.eventually hev + have hh : ∀ᶠ t : ℝ in 𝓝[>] 0, + (x+t • LooplessGraph.positiveExtension x u ∈ G.constraintPolytope ∧ + x+(-t) • LooplessGraph.positiveExtension x u ∈ G.constraintPolytope) ∧ 0 < t := + ((hev.and hneg).filter_mono nhdsWithin_le_nhds).and eventually_mem_nhdsWithin + obtain ⟨a,⟨ha,hna⟩,ha0⟩ := hh.exists + rw [← G.polytope_eq_constraints heven] at ha hna + obtain ⟨q,hq⟩ := (G.mem_polytope_iff _).mp ha + obtain ⟨r,hr⟩ := (G.mem_polytope_iff _).mp hna + have hsupp := midpoint_law_support G hp hopt hq hr + have hsum : (∑ M, q M • matchingNormalized G x M) ∈ + weightedDirectionSpace p (matchingNormalized G x) := by + apply Submodule.sum_mem + intro M _ + by_cases hM : 0 < p M + · exact Submodule.smul_mem _ _ (Submodule.subset_span ⟨⟨M,hM⟩,rfl⟩) + · have hq0 : q M=0 := le_antisymm (le_of_not_gt fun hqM => hM (hsupp M hqM)) (hq.1.1 M) + simp only [hq0,zero_smul] + exact Submodule.zero_mem _ + have hin := Submodule.smul_mem _ a⁻¹ hsum + have he : a⁻¹ • (∑ M, q M • matchingNormalized G x M) = + (fun e => u e/Real.sqrt (x e.val)) := by + ext e + simp only [Pi.smul_apply,Finset.sum_apply,smul_eq_mul] + rw [matchingNormalized_average G hq] + simp only [Pi.add_apply,Pi.smul_apply,smul_eq_mul,LooplessGraph.positiveExtension_pos] + field_simp + ring + rwa [he] at hin + +def normalizeLinear (x : E → ℝ) : + ({e // 0 < x e} → ℝ) →ₗ[ℝ] ({e // 0 < x e} → ℝ) where + toFun := fun u e => u e/Real.sqrt (x e.val) + map_add' := by intro u v; ext e; exact add_div _ _ _ + map_smul' := by intro a u; ext e; exact mul_div_assoc _ _ _ + +omit [DecidableEq E] in +theorem sum_positive_support (x f : E → ℝ) (hf : ∀ e, ¬ 0 < x e → f e=0) : + (∑ e, f e) = ∑ e : {e // 0 < x e}, f e.val := by + classical + have hz : (∑ e : {e // ¬ 0 < x e}, f e.val)=0 := + Finset.sum_eq_zero fun e _ => hf e.val e.property + have hh := Fintype.sum_subtype_add_sum_subtype (fun e => 0 < x e) f + rw [hz,add_zero] at hh + exact hh.symm + +def matchingScoreWeights (x : E → ℝ) (u : {e // 0 < x e} → ℝ) : E → ℝ := + LooplessGraph.positiveExtension x (fun e => u e/Real.sqrt (x e.val)) + +omit [Fintype V] [DecidableEq V] in +theorem matchingNormalized_score (G : LooplessGraph V E) (x : E → ℝ) + (u : {e // 0 < x e} → ℝ) (M : G.Matching) : + linearScore G (matchingScoreWeights x u) (∑ e, matchingScoreWeights x u e*x e) M = + matchingNormalized G x M ⬝ᵥ u := by + classical + unfold linearScore + rw [← Finset.sum_sub_distrib] + rw [sum_positive_support x _ (fun e he => by simp [matchingScoreWeights,LooplessGraph.positiveExtension,he])] + rw [dotProduct] + apply Finset.sum_congr rfl + intro e _ + simp only [matchingScoreWeights,LooplessGraph.positiveExtension_pos,matchingNormalized,normalizedCentered] + ring + +omit [Fintype V] [DecidableEq V] in +theorem matchingNormalized_mulVec (G : LooplessGraph V E) {x : E → ℝ} + {p : G.Matching → ℝ} (hp : p ∈ G.feasibleLaws x) + (u : {e // 0 < x e} → ℝ) (e : {e // 0 < x e}) : + (covariance p (matchingNormalized G x) *ᵥ u) e = + G.mean (fun M => p M * linearScore G (matchingScoreWeights x u) + (∑ e, matchingScoreWeights x u e*x e) M) e.val / Real.sqrt (x e.val) := by + let a := linearScore G (matchingScoreWeights x u) (∑ e, matchingScoreWeights x u e*x e) + have hcenter : ∑ M, p M*a M=0 := by + dsimp only [a] + rw [linearScore_expectation,hp.2,hp.1.2,mul_one,sub_self] + calc + _ = ∑ M, (p M*a M*G.indicator M e.val-x e.val*(p M*a M))/Real.sqrt (x e.val) := by + rw [covariance_mulVec hp.1.1] + apply Finset.sum_congr rfl + intro M _ + rw [← matchingNormalized_score G x u M] + change p M*((G.indicator M e.val-x e.val)/Real.sqrt (x e.val))*a M = _ + ring + _ = _ := by + rw [← Finset.sum_div,Finset.sum_sub_distrib,← Finset.mul_sum,hcenter,mul_zero,sub_zero] + rfl + +end MatchingEntropyBounds + +end + +end OAI diff --git a/lean/OAI/Combinatorics/MatchingEntropy/MinimalFace.lean b/lean/OAI/Combinatorics/MatchingEntropy/MinimalFace.lean new file mode 100644 index 0000000000000000000000000000000000000000..fdd0d9d4fe199bec447eb3b88b146e6935ef9c11 --- /dev/null +++ b/lean/OAI/Combinatorics/MatchingEntropy/MinimalFace.lean @@ -0,0 +1,173 @@ +import OAI.Combinatorics.MatchingEntropy.Pointwise + +namespace OAI + +noncomputable section + +open scoped BigOperators Topology +open Filter + +universe uV uE uI uJ uA uB uC uW uF uD uι + +namespace MatchingEntropyBounds.Refined + +variable {V : Type uV} {E : Type uE} [Fintype V] [Fintype E] [DecidableEq V] [DecidableEq E] + +def minimalFace (G : LooplessGraph V E) (x : E → ℝ) : Set (E → ℝ) := + {y | y ∈ G.polytope ∧ (∀ e, x e = 0 → y e = 0) ∧ + ∀ S : Finset V, Odd S.card → G.cutMass x S = 1 → G.cutMass y S = 1} + +def faceDimension (G : LooplessGraph V E) (x : E → ℝ) : ℕ := + Module.finrank ℝ (affineSpan ℝ (minimalFace G x)).direction + +theorem even_of_mem (G : LooplessGraph V E) {x : E → ℝ} (hx : x ∈ G.polytope) : + Even (Fintype.card V) := by + obtain ⟨M⟩ := matching_nonempty_of_mem G hx + rw [← G.matching_card_twice M] + exact even_two_mul _ + +omit [Fintype V] in +theorem self_mem_minimalFace (G : LooplessGraph V E) {x : E → ℝ} (hx : x ∈ G.polytope) : + x ∈ minimalFace G x := ⟨hx, fun _ h => h, fun _ _ h => h⟩ + +omit [Fintype V] in +theorem minimalFace_sub_direction (G : LooplessGraph V E) {x y : E → ℝ} + (hx : x ∈ G.polytope) (hy : y ∈ minimalFace G x) : + y - x ∈ (G.faceSpace x).map (LooplessGraph.positiveExtension x) := by + let u : {e // 0 < x e} → ℝ := fun e => y e.val - x e.val + have hext : LooplessGraph.positiveExtension x u = y - x := by + ext e + by_cases he : 0 < x e + · simp [LooplessGraph.positiveExtension, he, u] + · have hz : x e = 0 := le_antisymm (le_of_not_gt he) ((G.polytope_subset_constraintPolytope hx).1 e) + simp [LooplessGraph.positiveExtension, hz, hy.2.1 e hz] + refine ⟨u, ?_, hext⟩ + rw [LooplessGraph.faceSpace] + change G.degreeLinear (LooplessGraph.positiveExtension x u) = 0 ∧ _ + rw [hext] + constructor + · rw [map_sub] + ext v + change G.degree y v - G.degree x v = 0 + rw [(G.polytope_subset_constraintPolytope hy.1).2.1, + (G.polytope_subset_constraintPolytope hx).2.1, sub_self] + · intro S hS ht + rw [map_sub] + change G.cutMass y S - G.cutMass x S = 0 + rw [hy.2.2 S hS ht, ht, sub_self] + +theorem direction_eventually_minimalFace (G : LooplessGraph V E) {x : E → ℝ} + (hx : x ∈ G.polytope) {u : E → ℝ} + (hu : u ∈ (G.faceSpace x).map (LooplessGraph.positiveExtension x)) : + ∀ᶠ t : ℝ in 𝓝 0, x + t • u ∈ minimalFace G x := by + obtain ⟨v, hv, rfl⟩ := hu + have hline := G.faceSpace_eventually_line (G.polytope_subset_constraintPolytope hx) hv + rw [← G.polytope_eq_constraints (even_of_mem G hx)] at hline + filter_upwards [hline] with t ht + refine ⟨ht, ?_, ?_⟩ + · intro e he + simp [he, LooplessGraph.positiveExtension_zero x v he] + · intro S hS hcut + change G.cutLinear S (x + t • LooplessGraph.positiveExtension x v) = 1 + rw [map_add, map_smul, hv.2 S hS hcut, smul_zero, add_zero] + exact hcut + +theorem minimalFace_spec (G : LooplessGraph V E) {x : E → ℝ} (hx : x ∈ G.polytope) : + x ∈ minimalFace G x ∧ Convex ℝ (minimalFace G x) ∧ + IsExtreme ℝ G.polytope (minimalFace G x) ∧ + ∀ A : Set (E → ℝ), IsExtreme ℝ G.polytope A → x ∈ A → minimalFace G x ⊆ A := by + refine ⟨self_mem_minimalFace G hx, ?_, ?_, ?_⟩ + · intro y hy z hz a b ha hb hab + refine ⟨(convex_convexHull ℝ _ ) hy.1 hz.1 ha hb hab, ?_, ?_⟩ + · intro e he + simp [hy.2.1 e he, hz.2.1 e he] + · intro S hS ht + rw [G.cutMass_linear, hy.2.2 S hS ht, hz.2.2 S hS ht] + simpa using hab + · refine ⟨fun _ h => h.1, ?_⟩ + intro y hy z hz w hw hseg + obtain ⟨a, b, ha, hb, hab, rfl⟩ := hseg + have hyc := G.polytope_subset_constraintPolytope hy + have hzc := G.polytope_subset_constraintPolytope hz + refine ⟨hy, ?_, ?_⟩ + · intro e he + have h := hw.2.1 e he + change a * y e + b * z e = 0 at h + have hn := mul_nonneg hb.le (hzc.1 e) + have hyn := hyc.1 e + nlinarith + · intro S hS ht + have h := hw.2.2 S hS ht + rw [G.cutMass_linear] at h + have hyn := hyc.2.2 S hS + have hzn := hzc.2.2 S hS + nlinarith + · intro A hA hxA y hy + have hline := direction_eventually_minimalFace G hx (minimalFace_sub_direction G hx hy) + have hneg : ∀ᶠ t : ℝ in 𝓝 0, x + (-t) • (y - x) ∈ minimalFace G x := + (show Tendsto (fun t : ℝ => -t) (𝓝 0) (𝓝 0) by + simpa using continuous_neg.tendsto (0 : ℝ)).eventually hline + have hh : ∀ᶠ t : ℝ in 𝓝[>] 0, (x + (-t) • (y-x) ∈ minimalFace G x) ∧ 0 < t := + (hneg.filter_mono nhdsWithin_le_nhds).and eventually_mem_nhdsWithin + obtain ⟨a, ha, ha0⟩ := hh.exists + apply hA.left_mem_of_mem_openSegment hy.1 ha.1 hxA + refine ⟨a / (1+a), 1 / (1+a), div_pos ha0 (by linarith), + div_pos (by norm_num) (by linarith), ?_, ?_⟩ + · field_simp + ring + · ext e + simp only [Pi.add_apply, Pi.smul_apply, Pi.sub_apply, smul_eq_mul] + field_simp + ring + +theorem minimalFace_direction (G : LooplessGraph V E) {x : E → ℝ} (hx : x ∈ G.polytope) : + (affineSpan ℝ (minimalFace G x)).direction = + (G.faceSpace x).map (LooplessGraph.positiveExtension x) := by + apply le_antisymm + · have hle : affineSpan ℝ (minimalFace G x) ≤ + AffineSubspace.mk' x ((G.faceSpace x).map (LooplessGraph.positiveExtension x)) := by + apply affineSpan_le.mpr + intro y hy + exact (AffineSubspace.mem_mk').mpr (minimalFace_sub_direction G hx hy) + simpa using AffineSubspace.direction_le hle + · intro u hu + have he := direction_eventually_minimalFace G hx hu + have hh : ∀ᶠ t : ℝ in 𝓝[>] 0, (x + t • u ∈ minimalFace G x) ∧ 0 < t := + (he.filter_mono nhdsWithin_le_nhds).and eventually_mem_nhdsWithin + obtain ⟨a, ha, ha0⟩ := hh.exists + have hd := AffineSubspace.vsub_mem_direction + (subset_affineSpan ℝ _ ha) (subset_affineSpan ℝ _ (self_mem_minimalFace G hx)) + have hd' : a • u ∈ (affineSpan ℝ (minimalFace G x)).direction := by + simpa using hd + have hh := (affineSpan ℝ (minimalFace G x)).direction.smul_mem a⁻¹ hd' + simpa [smul_smul, ne_of_gt ha0] using hh + +omit [Fintype E] [DecidableEq E] in +theorem positiveExtension_injective (x : E → ℝ) : + Function.Injective (LooplessGraph.positiveExtension x) := by + intro u v h + ext e + simpa using congrFun h e.val + +theorem faceDimension_eq (G : LooplessGraph V E) {x : E → ℝ} (hx : x ∈ G.polytope) : + faceDimension G x = Module.finrank ℝ (G.faceSpace x) := by + rw [faceDimension, minimalFace_direction G hx] + exact (Submodule.equivMapOfInjective _ (positiveExtension_injective x) _).finrank_eq.symm + +theorem minimalFace_rank (G : LooplessGraph V E) (m : ℕ) + (hm : 0 < m) (hV : Fintype.card V = 2 * m) {x : E → ℝ} (hx : x ∈ G.polytope) : + Fintype.card {e // 0 < x e} + 2 ≤ faceDimension G x + 3 * m := by + have hr := sharp_face_rank G m hm hV hx + have hd := (G.faceSpace x).finrank_quotient_add_finrank + rw [Module.finrank_pi] at hd + rw [faceDimension_eq G hx] + dsimp only [LooplessGraph.faceCodimension] at hr + omega + +def IsFractional (x : E → ℝ) (e : E) : Prop := 0 < x e ∧ x e < 1 + +end MatchingEntropyBounds.Refined + +end + +end OAI diff --git a/lean/OAI/Combinatorics/MatchingEntropy/Model.lean b/lean/OAI/Combinatorics/MatchingEntropy/Model.lean new file mode 100644 index 0000000000000000000000000000000000000000..adf0e441ba1411f19b49a0d90c92d7176ab777a6 --- /dev/null +++ b/lean/OAI/Combinatorics/MatchingEntropy/Model.lean @@ -0,0 +1,75 @@ +import Mathlib + +namespace OAI + +noncomputable section + +open scoped BigOperators Topology +open Filter + +universe uV uE uIndex uι + +namespace MatchingEntropyBounds + +structure LooplessGraph (V : Type uV) (E : Type uE) where + left : E → V + right : E → V + loopless : ∀ e, left e ≠ right e + +variable {V : Type uV} {E : Type uE} + [Fintype V] [Fintype E] [DecidableEq V] [DecidableEq E] + +namespace LooplessGraph + +def Incident (G : LooplessGraph V E) (v : V) (e : E) : Prop := + G.left e = v ∨ G.right e = v + +instance incidentDecidable (G : LooplessGraph V E) (v : V) (e : E) : + Decidable (G.Incident v e) := inferInstanceAs (Decidable (G.left e = v ∨ G.right e = v)) + +def IsPerfectMatching (G : LooplessGraph V E) (M : Finset E) : Prop := + ∀ v, ∃! e, e ∈ M ∧ G.Incident v e + +abbrev Matching (G : LooplessGraph V E) := {M : Finset E // G.IsPerfectMatching M} + +instance matchingFintype (G : LooplessGraph V E) : Fintype G.Matching := + Fintype.ofFinite _ + +def indicator (G : LooplessGraph V E) (M : G.Matching) (e : E) : ℝ := + if e ∈ M.val then 1 else 0 + +def polytope (G : LooplessGraph V E) : Set (E → ℝ) := + convexHull ℝ (Set.range G.indicator) + +def mean (G : LooplessGraph V E) (p : G.Matching → ℝ) (e : E) : ℝ := + ∑ M, p M * G.indicator M e + +end LooplessGraph + +def probabilitySimplex (Index : Type uIndex) [Fintype Index] : Set (Index → ℝ) := + {weights | (∀ index, 0 ≤ weights index) ∧ ∑ index, weights index = 1} + +namespace LooplessGraph + +def feasibleLaws (G : LooplessGraph V E) (y : E → ℝ) : Set (G.Matching → ℝ) := + {p | p ∈ probabilitySimplex G.Matching ∧ G.mean p = y} + +end LooplessGraph + +def entropy {ι : Type uι} [Fintype ι] (p : ι → ℝ) : ℝ := + ∑ i, Real.negMulLog (p i) + +def maxMatchingEntropy (G : LooplessGraph V E) (y : E → ℝ) : ℝ := + sSup (entropy '' G.feasibleLaws y) + +namespace Refined + +def complementEntropy (x : E → ℝ) : ℝ := entropy (fun e => 1 - x e) + +end Refined + +end MatchingEntropyBounds + +end + +end OAI diff --git a/lean/OAI/Combinatorics/MatchingEntropy/OddCuts.lean b/lean/OAI/Combinatorics/MatchingEntropy/OddCuts.lean new file mode 100644 index 0000000000000000000000000000000000000000..e6248f844ae7a02ed983f19d5ff49fd9a5f4b8a2 --- /dev/null +++ b/lean/OAI/Combinatorics/MatchingEntropy/OddCuts.lean @@ -0,0 +1,228 @@ +import OAI.Combinatorics.MatchingEntropy.Basic + +namespace OAI + +noncomputable section + +open scoped BigOperators Topology +open Filter + +universe uV uE uI uJ uA uB uC uW uF uD uι + +namespace MatchingEntropyBounds.LooplessGraph + +variable {V : Type uV} {E : Type uE} [Fintype V] [Fintype E] [DecidableEq V] [DecidableEq E] + +def Crosses (G : LooplessGraph V E) (S : Finset V) (e : E) : Prop := + (G.left e ∈ S ∧ G.right e ∉ S) ∨ (G.left e ∉ S ∧ G.right e ∈ S) + +instance crossesDecidable (G : LooplessGraph V E) (S : Finset V) (e : E) : + Decidable (G.Crosses S e) := inferInstanceAs (Decidable + ((G.left e ∈ S ∧ G.right e ∉ S) ∨ (G.left e ∉ S ∧ G.right e ∈ S))) + +def cut (G : LooplessGraph V E) (S : Finset V) : Finset E := + Finset.univ.filter (G.Crosses S) + +def degree (G : LooplessGraph V E) (x : E → ℝ) (v : V) : ℝ := + ∑ e, if G.Incident v e then x e else 0 + +def cutMass (G : LooplessGraph V E) (x : E → ℝ) (S : Finset V) : ℝ := + ∑ e ∈ G.cut S, x e + +def constraintPolytope (G : LooplessGraph V E) : Set (E → ℝ) := + {x | (∀ e, 0 ≤ x e) ∧ (∀ v, G.degree x v = 1) ∧ + (∀ S : Finset V, Odd S.card → 1 ≤ G.cutMass x S)} + +omit [Fintype V] [DecidableEq E] in +@[simp] theorem mem_cut (G : LooplessGraph V E) (S : Finset V) (e : E) : + e ∈ G.cut S ↔ G.Crosses S e := by simp [cut] + +omit [Fintype E] [DecidableEq E] in +theorem crosses_compl (G : LooplessGraph V E) (S : Finset V) (e : E) : + G.Crosses Sᶜ e ↔ G.Crosses S e := by + simp only [Crosses, Finset.mem_compl, not_not] + tauto + +omit [DecidableEq E] in +@[simp] theorem cut_compl (G : LooplessGraph V E) (S : Finset V) : + G.cut Sᶜ = G.cut S := by ext; simp [crosses_compl] + +omit [Fintype V] in +theorem degree_indicator (G : LooplessGraph V E) (M : G.Matching) (v : V) : + G.degree (G.indicator M) v = 1 := by + obtain ⟨e, ⟨he, hev⟩, huniq⟩ := M.property v + rw [degree, Finset.sum_eq_single e] + · simp [hev, indicator, he] + · intro e' _ hne + by_cases hv : G.Incident v e' + · have hh : e' ∉ M.val := by + intro hm + exact hne (huniq e' ⟨hm, hv⟩) + simp [hv, indicator, hh] + · simp [hv] + · simp + +omit [Fintype V] in +theorem degree_mean (G : LooplessGraph V E) (p : G.Matching → ℝ) (v : V) : + G.degree (G.mean p) v = ∑ M, p M := by + classical + have he : ∀ e, (if G.Incident v e then G.mean p e else 0) = + ∑ M, p M*(if G.Incident v e then G.indicator M e else 0) := by + intro e + by_cases h : G.Incident v e <;> simp [h, mean] + unfold degree + simp_rw [he] + rw [Finset.sum_comm] + apply Finset.sum_congr rfl + intro M _ + rw [← Finset.mul_sum] + change p M*G.degree (G.indicator M) v = p M + rw [G.degree_indicator, mul_one] + +omit [Fintype V] [Fintype E] [DecidableEq E] in +theorem incidence_sum (G : LooplessGraph V E) (e : E) (S : Finset V) : + (∑ v ∈ S, if G.Incident v e then (1:ℕ) else 0) = + (if G.left e ∈ S then 1 else 0) + (if G.right e ∈ S then 1 else 0) := by + have hv : ∀ v, (if G.Incident v e then (1:ℕ) else 0) = + (if v = G.left e then 1 else 0) + (if v = G.right e then 1 else 0) := by + intro v + by_cases hl : v = G.left e <;> by_cases hr : v = G.right e + · exact ((G.loopless e) (hl.symm.trans hr)).elim + · simp [Incident, hl, G.loopless e, Ne.symm (G.loopless e)] + · simp [Incident, hr, G.loopless e, Ne.symm (G.loopless e)] + · simp [Incident, Ne.symm hl, Ne.symm hr, hl, hr] + simp_rw [hv, Finset.sum_add_distrib] + simp + +omit [Fintype V] [Fintype E] [DecidableEq E] in +theorem matching_incidence_count (G : LooplessGraph V E) (M : G.Matching) + (S : Finset V) : + (∑ e ∈ M.val, ((if G.left e ∈ S then (1:ℕ) else 0) + + (if G.right e ∈ S then 1 else 0))) = S.card := by + have hsum : ∀ v, (∑ e ∈ M.val, if G.Incident v e then (1:ℕ) else 0) = 1 := by + intro v + obtain ⟨e, ⟨he, hev⟩, hu⟩ := M.property v + rw [Finset.sum_eq_single e] + · simp [hev] + · intro e' he' hh + have hv : ¬G.Incident v e' := fun hv => hh (hu e' ⟨he', hv⟩) + simp [hv] + · simp [he] + calc + _ = ∑ e ∈ M.val, ∑ v ∈ S, if G.Incident v e then (1:ℕ) else 0 := by + simp_rw [incidence_sum] + _ = ∑ v ∈ S, ∑ e ∈ M.val, if G.Incident v e then (1:ℕ) else 0 := Finset.sum_comm + _ = S.card := by simp_rw [hsum]; simp + +omit [Fintype V] [Fintype E] [DecidableEq E] in +theorem matching_crosses_odd (G : LooplessGraph V E) (M : G.Matching) + (S : Finset V) (hS : Odd S.card) : ∃ e ∈ M.val, G.Crosses S e := by + by_contra h + push Not at h + have heq : ∀ e ∈ M.val, ((if G.left e ∈ S then (1:ℕ) else 0) + + (if G.right e ∈ S then 1 else 0)) = 2*(if G.left e ∈ S then 1 else 0) := by + intro e he + have hc := h e he + simp only [Crosses] at hc + by_cases hl : G.left e ∈ S <;> by_cases hr : G.right e ∈ S <;> + simp_all + have hh := G.matching_incidence_count M S + have heqsum := Finset.sum_congr rfl heq + rw [heqsum, ← Finset.mul_sum] at hh + obtain ⟨k, hk⟩ := hS + omega + +omit [Fintype V] [DecidableEq E] in +theorem degree_linear (G : LooplessGraph V E) (x y : E → ℝ) (a b : ℝ) (v : V) : + G.degree (a • x+b • y) v = a*G.degree x v+b*G.degree y v := by + have he : ∀ e, (if G.Incident v e then (a • x+b • y) e else 0) = + a*(if G.Incident v e then x e else 0)+b*(if G.Incident v e then y e else 0) := by + intro e + by_cases h : G.Incident v e <;> simp [h] + simp only [degree, he, Finset.sum_add_distrib, ← Finset.mul_sum] + +omit [Fintype V] [DecidableEq E] in +theorem cutMass_linear (G : LooplessGraph V E) (x y : E → ℝ) (a b : ℝ) (S : Finset V) : + G.cutMass (a • x+b • y) S = a*G.cutMass x S+b*G.cutMass y S := by + simp [cutMass, Finset.sum_add_distrib, Finset.mul_sum] + +omit [Fintype V] [DecidableEq E] in +theorem convex_constraintPolytope (G : LooplessGraph V E) : + Convex ℝ G.constraintPolytope := by + intro x hx y hy a b ha hb hab + refine ⟨fun e => add_nonneg (mul_nonneg ha (hx.1 e)) (mul_nonneg hb (hy.1 e)), ?_, ?_⟩ + · intro v + rw [degree_linear, hx.2.1, hy.2.1, mul_one, mul_one, hab] + · intro S hS + rw [cutMass_linear] + calc + 1 = a*1+b*1 := by linarith + _ ≤ _ := add_le_add (mul_le_mul_of_nonneg_left (hx.2.2 S hS) ha) + (mul_le_mul_of_nonneg_left (hy.2.2 S hS) hb) + +omit [Fintype V] in +theorem indicator_mem_constraintPolytope (G : LooplessGraph V E) (M : G.Matching) : + G.indicator M ∈ G.constraintPolytope := by + refine ⟨?_, G.degree_indicator M, ?_⟩ + · intro e; simp [indicator]; split <;> norm_num + · intro S hS + obtain ⟨e, he, hc⟩ := G.matching_crosses_odd M S hS + have h := Finset.single_le_sum (f := G.indicator M) + (s := G.cut S) (a := e) (by intro e' _; simp [indicator]; split <;> norm_num) + ((G.mem_cut S e).mpr hc) + simpa only [cutMass, indicator, he, ite_true] using h + +omit [Fintype V] in +theorem polytope_subset_constraintPolytope (G : LooplessGraph V E) : + G.polytope ⊆ G.constraintPolytope := by + apply convexHull_min + · rintro x ⟨M, rfl⟩ + exact G.indicator_mem_constraintPolytope M + · exact G.convex_constraintPolytope + +omit [Fintype V] [DecidableEq E] in +theorem constraint_coordinate_le_one (G : LooplessGraph V E) {x : E → ℝ} + (hx : x ∈ G.constraintPolytope) (e : E) : x e ≤ 1 := by + have h := Finset.single_le_sum (f := fun e' => if G.Incident (G.left e) e' then x e' else 0) + (s := Finset.univ) (a := e) (by + intro e' _; split; exact hx.1 e'; rfl) (Finset.mem_univ e) + have he : G.Incident (G.left e) e := Or.inl rfl + change (if G.Incident (G.left e) e then x e else 0) ≤ G.degree x (G.left e) at h + simpa only [he, ite_true, hx.2.1] using h + +omit [Fintype V] [DecidableEq E] in +theorem continuous_degree (G : LooplessGraph V E) (v : V) : + Continuous (fun x : E → ℝ => G.degree x v) := by + unfold degree + apply continuous_finsetSum + intro e _ + split <;> fun_prop + +omit [Fintype V] [DecidableEq E] in +theorem continuous_cutMass (G : LooplessGraph V E) (S : Finset V) : + Continuous (fun x : E → ℝ => G.cutMass x S) := by + unfold cutMass + fun_prop + +omit [Fintype V] [DecidableEq E] in +theorem isClosed_constraintPolytope (G : LooplessGraph V E) : + IsClosed G.constraintPolytope := by + simp only [constraintPolytope, Set.ofPred_and, Set.ofPred_forall] + exact (isClosed_iInter fun e => isClosed_le continuous_const (continuous_apply e)).inter + ((isClosed_iInter fun v => isClosed_eq (G.continuous_degree v) continuous_const).inter + (isClosed_iInter fun S => isClosed_iInter fun _ => + isClosed_le continuous_const (G.continuous_cutMass S))) + +omit [Fintype V] [DecidableEq E] in +theorem isCompact_constraintPolytope (G : LooplessGraph V E) : + IsCompact G.constraintPolytope := by + apply (isCompact_Icc : IsCompact (Set.Icc (0 : E → ℝ) 1)).of_isClosed_subset + G.isClosed_constraintPolytope + intro x hx + exact ⟨hx.1, fun e => G.constraint_coordinate_le_one hx e⟩ + +end MatchingEntropyBounds.LooplessGraph + +end + +end OAI diff --git a/lean/OAI/Combinatorics/MatchingEntropy/Optimizer.lean b/lean/OAI/Combinatorics/MatchingEntropy/Optimizer.lean new file mode 100644 index 0000000000000000000000000000000000000000..1a58d72569ed0067b04a4b6595ed10a7761aab0a --- /dev/null +++ b/lean/OAI/Combinatorics/MatchingEntropy/Optimizer.lean @@ -0,0 +1,226 @@ +import OAI.Combinatorics.MatchingEntropy.Entropy + +namespace OAI + +noncomputable section + +open scoped BigOperators Topology +open Filter + +universe uV uE uI uJ uA uB uC uW uF uD uι + +namespace MatchingEntropyBounds + +variable {V : Type uV} {E : Type uE} [Fintype V] [Fintype E] [DecidableEq V] [DecidableEq E] + +theorem entropy_mix_ge {ι : Type uι} [Fintype ι] {p q : ι → ℝ} + (hp : ∀ i, 0 ≤ p i) (hq : ∀ i, 0 ≤ q i) + {t : ℝ} (ht : t ∈ Set.Icc (0 : ℝ) 1) : + (1-t) * entropy p + t * entropy q ≤ + entropy (fun i => (1-t)*p i + t*q i) := by + unfold entropy + rw [Finset.mul_sum, Finset.mul_sum, ← Finset.sum_add_distrib] + apply Finset.sum_le_sum + intro i _ + simpa only [smul_eq_mul] using Real.concaveOn_negMulLog.2 + (hp i) (hq i) (sub_nonneg.mpr ht.2) ht.1 (by ring : 1-t+t=1) + +theorem entropy_mix_zero_bonus {ι : Type uι} [Fintype ι] {p q : ι → ℝ} + (hp : ∀ i, 0 ≤ p i) (hq : ∀ i, 0 ≤ q i) {j : ι} (hj : p j = 0) + {t : ℝ} (ht : t ∈ Set.Icc (0 : ℝ) 1) : + (1-t) * entropy p + t * entropy q + q j * Real.negMulLog t ≤ + entropy (fun i => (1-t)*p i + t*q i) := by + classical + have hterm : ∀ i, (1-t) * Real.negMulLog (p i) + t * Real.negMulLog (q i) + + (if i=j then q j * Real.negMulLog t else 0) ≤ + Real.negMulLog ((1-t)*p i+t*q i) := by + intro i + by_cases hi : i=j + · subst i + simp only [hj, Real.negMulLog_zero, mul_zero, zero_add, ite_true, + Real.negMulLog_mul] + linarith + · simp only [hi, ↓reduceIte, add_zero] + simpa only [smul_eq_mul] using Real.concaveOn_negMulLog.2 + (hp i) (hq i) (sub_nonneg.mpr ht.2) ht.1 (by ring : 1-t+t=1) + have hh := Finset.sum_le_sum (s := Finset.univ) (fun i _ => hterm i) + simpa only [Finset.sum_add_distrib, ← Finset.mul_sum, + Finset.sum_ite_eq', Finset.mem_univ, ite_true, entropy] using hh + +theorem entropy_maximizer_support {ι : Type uι} [Fintype ι] {p q : ι → ℝ} + (hp : ∀ i, 0 ≤ p i) (hq : ∀ i, 0 ≤ q i) + (hmax : ∀ t ∈ Set.Icc (0 : ℝ) 1, + entropy (fun i => (1-t)*p i+t*q i) ≤ entropy p) {j : ι} (hjq : 0 < q j) : + 0 < p j := by + by_contra hj + have hj0 : p j = 0 := le_antisymm (le_of_not_gt hj) (hp j) + have hqp : entropy q ≤ entropy p := by simpa using hmax 1 (by constructor <;> norm_num) + let c := (entropy p-entropy q)/(q j)+1 + have hc : 0 < c := by dsimp [c]; positivity + let t := Real.exp (-c) + have htp : 0 < t := Real.exp_pos _ + have ht : t ∈ Set.Icc (0 : ℝ) 1 := + ⟨htp.le, Real.exp_le_one_iff.mpr (neg_nonpos.mpr hc.le)⟩ + have hbonus := (entropy_mix_zero_bonus hp hq hj0 ht).trans (hmax t ht) + have hlog : Real.log t = -c := Real.log_exp _ + rw [Real.negMulLog, hlog] at hbonus + have he : q j * c = entropy p-entropy q+q j := by + dsimp [c] + field_simp + nlinarith + +omit [Fintype V] [DecidableEq V] in + +theorem matching_optimizer_support (G : LooplessGraph V E) {y : E → ℝ} + {p q : G.Matching → ℝ} (hp : p ∈ G.feasibleLaws y) + (hq : q ∈ G.feasibleLaws y) (hopt : entropy p = maxMatchingEntropy G y) + {M : G.Matching} (hM : 0 < q M) : 0 < p M := by + apply entropy_maximizer_support hp.1.1 hq.1.1 _ hM + intro t ht + apply le_trans (entropy_le_maxMatchingEntropy (G := G) (y := y) ?_) (le_of_eq hopt.symm) + constructor + · exact convex_probabilitySimplex _ hp.1 hq.1 + (sub_nonneg.mpr ht.2) ht.1 (by ring) + · calc + G.mean (fun i => (1-t)*p i+t*q i) = + (1-t) • G.mean p + t • G.mean q := by + exact (G.meanLinear).map_add ((1-t) • p) (t • q) |>.trans (by + rw [LinearMap.map_smul, LinearMap.map_smul]; rfl) + _ = y := by rw [hp.2, hq.2]; ext e; simp only [Pi.add_apply, Pi.smul_apply, smul_eq_mul]; ring + +theorem negMulLog_tangent {x y : ℝ} (hx : 0 ≤ x) (hy : 0 < y) : + Real.negMulLog x ≤ -x * Real.log y + y-x := by + have h := mul_le_mul_of_nonneg_left + (Real.negMulLog_le_one_sub_self (div_nonneg hx hy.le)) hy.le + have he : Real.negMulLog x = -x * Real.log y + y * Real.negMulLog (x/y) := by + calc + Real.negMulLog x = Real.negMulLog (y * (x/y)) := by congr 1; field_simp + _ = (x/y) * Real.negMulLog y + y * Real.negMulLog (x/y) := Real.negMulLog_mul _ _ + _ = _ := by unfold Real.negMulLog; field_simp + rw [he] + have hdiv : y * (x/y) = x := by field_simp + nlinarith + +theorem entropy_le_crossEntropy {ι : Type uι} [Fintype ι] {p q : ι → ℝ} + (hp : p ∈ probabilitySimplex ι) (hq : q ∈ probabilitySimplex ι) + (hsupp : ∀ i, p i = 0 → q i = 0) : + entropy q ≤ -∑ i, q i * Real.log (p i) := by + have hterm : ∀ i, Real.negMulLog (q i) ≤ + -(q i * Real.log (p i)) + p i-q i := by + intro i + by_cases hi : p i = 0 + · simp [hi, hsupp i hi] + · simpa only [neg_mul] using negMulLog_tangent (hq.1 i) + (lt_of_le_of_ne (hp.1 i) (Ne.symm hi)) + have hh := Finset.sum_le_sum (s := Finset.univ) fun i _ => hterm i + simpa only [Finset.sum_sub_distrib, Finset.sum_add_distrib, + Finset.sum_neg_distrib, hp.2, hq.2, add_sub_cancel_right, entropy] using hh + +theorem entropy_line_hasDerivAt {ι : Type uι} [Fintype ι] (p v : ι → ℝ) + (hsupp : ∀ i, p i = 0 → v i = 0) : + HasDerivAt (fun t : ℝ => entropy (fun i => p i+t*v i)) + (-∑ i, v i * Real.log (p i) - ∑ i, v i) 0 := by + have hd : ∀ i, HasDerivAt (fun t : ℝ => Real.negMulLog (p i+t*v i)) + ((-Real.log (p i)-1)*v i) 0 := by + intro i + by_cases hi : p i = 0 + · simpa only [hi, hsupp i hi, mul_zero, add_zero, Real.negMulLog_zero] using + (hasDerivAt_const (0 : ℝ) (0 : ℝ)) + · have hp : p i+(0 : ℝ)*v i ≠ 0 := by simpa using hi + simpa only [zero_mul, add_zero, one_mul, Function.comp_def, id_eq] using + (Real.hasDerivAt_negMulLog hp).comp 0 + (((hasDerivAt_id (0 : ℝ)).mul_const (v i)).const_add (p i)) + have he : (∑ i, (-Real.log (p i)-1)*v i) = + -∑ i, v i*Real.log (p i) - ∑ i, v i := by + simp_rw [sub_mul, one_mul, neg_mul, mul_comm (Real.log (p _))] + rw [Finset.sum_sub_distrib, Finset.sum_neg_distrib] + rw [← he] + simpa only [entropy, Finset.sum_apply] using (HasDerivAt.fun_sum (u := Finset.univ) (fun i _ => hd i)) + +omit [Fintype V] [DecidableEq V] in + +theorem matching_optimizer_log_annihilates (G : LooplessGraph V E) {y : E → ℝ} + {p : G.Matching → ℝ} (hp : p ∈ G.feasibleLaws y) + (hopt : entropy p = maxMatchingEntropy G y) (v : G.Matching → ℝ) + (hvsum : ∑ M, v M = 0) (hvmean : G.mean v = 0) + (hsupp : ∀ M, p M = 0 → v M = 0) : + ∑ M, v M * Real.log (p M) = 0 := by + have hev : ∀ᶠ t : ℝ in 𝓝 0, ∀ M, 0 ≤ p M+t*v M := by + apply Filter.eventually_all.mpr + intro M + by_cases hM : p M = 0 + · exact Filter.Eventually.of_forall (fun t => by simp [hM, hsupp M hM]) + · have hpos : 0 < p M := lt_of_le_of_ne (hp.1.1 M) (Ne.symm hM) + have hc : Continuous (fun t : ℝ => p M+t*v M) := by fun_prop + have hh : {t : ℝ | 0 < p M+t*v M} ∈ 𝓝 0 := + (isOpen_lt continuous_const hc).mem_nhds (by simpa using hpos) + exact Filter.Eventually.mono hh (fun t ht => ht.le) + have hlocal : IsLocalMax (fun t : ℝ => entropy (fun M => p M+t*v M)) 0 := by + filter_upwards [hev] with t ht + have hmean : G.mean (fun M => p M+t*v M) = y := by + change G.meanLinear (p+t • v) = y + rw [map_add, map_smul] + change G.mean p + t • G.mean v = y + rw [hp.2, hvmean, smul_zero, add_zero] + have hsum : ∑ M, (p M+t*v M) = 1 := by + rw [Finset.sum_add_distrib, ← Finset.mul_sum, hp.1.2, hvsum, mul_zero, add_zero] + have hle := entropy_le_maxMatchingEntropy (G := G) ⟨⟨ht, hsum⟩, hmean⟩ + simpa only [zero_mul, add_zero, ← hopt] using hle + have hh := hlocal.deriv_eq_zero + rw [(entropy_line_hasDerivAt p v hsupp).deriv, hvsum] at hh + linarith + +theorem exists_pos_nonneg_perturb {ι : Type uι} [Fintype ι] (p v : ι → ℝ) + (hp : ∀ i, 0 ≤ p i) (hz : ∀ i, p i = 0 → 0 ≤ v i) : + ∃ t : ℝ, 0 < t ∧ ∀ i, 0 ≤ p i+t*v i := by + have hev : ∀ᶠ t : ℝ in 𝓝 0, ∀ i, p i ≠ 0 → 0 ≤ p i+t*v i := by + apply Filter.eventually_all.mpr + intro i + by_cases hi : p i = 0 + · exact Filter.Eventually.of_forall (fun _ h => (h hi).elim) + · have hc : Continuous (fun t : ℝ => p i+t*v i) := by fun_prop + have hh : {t : ℝ | 0 < p i+t*v i} ∈ 𝓝 0 := + (isOpen_lt continuous_const hc).mem_nhds + (by simpa using lt_of_le_of_ne (hp i) (Ne.symm hi)) + exact Filter.Eventually.mono hh (fun t ht _ => ht.le) + have he' := (hev.filter_mono nhdsWithin_le_nhds).and + (self_mem_nhdsWithin : ∀ᶠ t : ℝ in 𝓝[>] 0, t ∈ Set.Ioi 0) + obtain ⟨t, ht, htp⟩ := he'.exists + refine ⟨t, htp, fun i => ?_⟩ + by_cases hi : p i = 0 + · rw [hi, zero_add] + exact mul_nonneg htp.le (hz i hi) + · exact ht i hi + +omit [Fintype V] [DecidableEq V] in + +theorem matching_optimizer_face_support (G : LooplessGraph V E) {y : E → ℝ} + {p : G.Matching → ℝ} (hp : p ∈ G.feasibleLaws y) + (hopt : entropy p = maxMatchingEntropy G y) + {q r : G.Matching → ℝ} (hq : q ∈ probabilitySimplex G.Matching) + (hr : r ∈ probabilitySimplex G.Matching) (hmean : G.mean q = G.mean r) + (hrsupport : ∀ M, p M = 0 → r M = 0) : + ∀ M, p M = 0 → q M = 0 := by + obtain ⟨t, htp, ht⟩ := exists_pos_nonneg_perturb p (q-r) hp.1.1 + (fun M hM => by simpa [hrsupport M hM] using hq.1 M) + have hsum : ∑ M, (p M+t*(q-r) M) = 1 := by + simp only [Pi.sub_apply, Finset.sum_add_distrib, ← Finset.mul_sum, + Finset.sum_sub_distrib, hp.1.2, hq.2, hr.2] + ring + have hmean' : G.mean (fun M => p M+t*(q-r) M) = y := by + change G.meanLinear (p+t • (q-r)) = y + rw [map_add, map_smul, map_sub] + change G.mean p + t • (G.mean q-G.mean r) = y + rw [hp.2, hmean, sub_self, smul_zero, add_zero] + intro M hM + by_contra hqM + have hqMp : 0 < q M := lt_of_le_of_ne (hq.1 M) (Ne.symm hqM) + have hpM := matching_optimizer_support G hp ⟨⟨ht, hsum⟩, hmean'⟩ hopt + (M := M) (by simpa [hM, hrsupport M hM] using mul_pos htp hqMp) + simp [hM] at hpM + +end MatchingEntropyBounds + +end + +end OAI diff --git a/lean/OAI/Combinatorics/MatchingEntropy/Pointwise.lean b/lean/OAI/Combinatorics/MatchingEntropy/Pointwise.lean new file mode 100644 index 0000000000000000000000000000000000000000..a8de4f01ec70ff3db4f85fb9deff5bf283c85c31 --- /dev/null +++ b/lean/OAI/Combinatorics/MatchingEntropy/Pointwise.lean @@ -0,0 +1,404 @@ +import OAI.Combinatorics.MatchingEntropy.RefinedVariation + +namespace OAI + +noncomputable section + +open scoped BigOperators Topology +open Filter Module Matrix + +universe uV uE uI uJ uA uB uC uW uF uD uι + +namespace MatchingEntropyBounds.Refined + +variable {V : Type uV} {E : Type uE} [Fintype V] [Fintype E] [DecidableEq V] [DecidableEq E] + +open LooplessGraph + +theorem pointwise_entropy (G : LooplessGraph V E) (m : ℕ) + (hm : 0 < m) (hV : Fintype.card V = 2 * m) (hPM : Nonempty G.Matching) + (x : E → ℝ) (hx : x ∈ G.polytope) : + entropy x - (2 - 2 / (m : ℝ)) * complementEntropy x ≤ maxMatchingEntropy G x ∧ + maxMatchingEntropy G x ≤ entropy x := by + obtain ⟨_⟩ := hPM + exact ⟨refined_lower G m hm hV x hx, refined_upper G x hx⟩ + +omit [Fintype V] [DecidableEq V] in +theorem F_nonneg (G : LooplessGraph V E) {x : E → ℝ} (hx : x ∈ G.polytope) : + 0 ≤ entropy x := by + exact Finset.sum_nonneg (fun e _ => Real.negMulLog_nonneg + (G.coordinate_mem_Icc hx e).1 (G.coordinate_mem_Icc hx e).2) + +omit [Fintype V] [DecidableEq V] in +theorem B_nonneg (G : LooplessGraph V E) {x : E → ℝ} (hx : x ∈ G.polytope) : + 0 ≤ complementEntropy x := by + apply Finset.sum_nonneg + intro e _ + exact Real.negMulLog_nonneg (sub_nonneg.mpr (G.coordinate_mem_Icc hx e).2) + (by linarith [(G.coordinate_mem_Icc hx e).1]) + +theorem B_le_order (G : LooplessGraph V E) (m : ℕ) (hV : Fintype.card V = 2 * m) + {x : E → ℝ} (hx : x ∈ G.polytope) : complementEntropy x ≤ m := by + rw [← G.marginal_sum hV hx] + apply Finset.sum_le_sum + intro e _ + simpa only [sub_sub_cancel] using + Real.negMulLog_le_one_sub_self (sub_nonneg.mpr (G.coordinate_mem_Icc hx e).2) + +theorem entropy_defect (G : LooplessGraph V E) (m : ℕ) + (hm : 0 < m) (hV : Fintype.card V = 2 * m) (hPM : Nonempty G.Matching) + (x : E → ℝ) (hx : x ∈ G.polytope) : + 0 ≤ entropy x - maxMatchingEntropy G x ∧ + entropy x - maxMatchingEntropy G x ≤ min (entropy x) (2 * (m : ℝ) - 2) := by + have hb := pointwise_entropy G m hm hV hPM x hx + have hmR : (0 : ℝ) < m := by exact_mod_cast hm + have hm1 : (1 : ℝ) ≤ m := by exact_mod_cast hm + have hc : 0 ≤ 2 - 2 / (m : ℝ) := by + have hd : 2 / (m : ℝ) ≤ 2 := (div_le_iff₀ hmR).mpr (by linarith) + linarith + have heq : (2 - 2 / (m : ℝ)) * m = 2 * (m : ℝ) - 2 := by field_simp + have hB := mul_le_mul_of_nonneg_left (B_le_order G m hV hx) hc + rw [heq] at hB + refine ⟨sub_nonneg.mpr hb.2, le_min ?_ ?_⟩ + · linarith [maxMatchingEntropy_nonneg G hx] + · linarith [hb.1] + +section UniformLaw +variable {I : Type uI} [Fintype I] + +def uniformLaw (I : Type uI) [Fintype I] : I → ℝ := fun _ => (Fintype.card I : ℝ)⁻¹ + +theorem uniformLaw_simplex [Nonempty I] : uniformLaw I ∈ probabilitySimplex I := by + have hN : (Fintype.card I : ℝ) ≠ 0 := by exact_mod_cast Fintype.card_ne_zero + refine ⟨fun _ => inv_nonneg.mpr (Nat.cast_nonneg _), ?_⟩ + simp [uniformLaw, hN] + +theorem uniformLaw_entropy [Nonempty I] : entropy (uniformLaw I) = Real.log (Fintype.card I : ℝ) := by + have hN : (Fintype.card I : ℝ) ≠ 0 := by exact_mod_cast Fintype.card_ne_zero + simp only [entropy, uniformLaw, Real.negMulLog, Real.log_inv, neg_mul_neg, + Finset.sum_const, Finset.card_univ, nsmul_eq_mul] + field_simp +end UniformLaw + +omit [Fintype V] [DecidableEq V] in +theorem uniformMatching_mean (G : LooplessGraph V E) (hPM : Nonempty G.Matching) : + ∃ z ∈ G.polytope, maxMatchingEntropy G z = Real.log (Fintype.card G.Matching : ℝ) := by + let := hPM + have hp := uniformLaw_simplex (I := G.Matching) + have hz : G.mean (uniformLaw G.Matching) ∈ G.polytope := G.mean_mem_polytope hp + refine ⟨_, hz, le_antisymm (maxMatchingEntropy_le_log_card G hz) ?_⟩ + rw [← uniformLaw_entropy (I := G.Matching)] + exact entropy_le_maxMatchingEntropy G ⟨hp, rfl⟩ + +omit [Fintype V] [DecidableEq V] [DecidableEq E] in +theorem continuous_binaryEntropy : Continuous (binaryEntropy (E := E)) := by + exact continuous_entropy.add (continuous_entropy.comp (by fun_prop)) + +theorem optimized_entropy (G : LooplessGraph V E) (m : ℕ) + (hm : 0 < m) (hV : Fintype.card V = 2 * m) (hPM : Nonempty G.Matching) : + ∃ x ∈ G.polytope, ∃ y ∈ G.polytope, + (∀ z ∈ G.polytope, entropy z ≤ entropy x) ∧ + (∀ z ∈ G.polytope, binaryEntropy z ≤ binaryEntropy y) ∧ + Real.log (Fintype.card G.Matching : ℝ) ≤ entropy x ∧ + entropy x ≤ Real.log (Fintype.card G.Matching : ℝ) + 2 * (m : ℝ) - 2 ∧ + Real.log (Fintype.card G.Matching : ℝ) ≤ binaryEntropy y ∧ + binaryEntropy y ≤ Real.log (Fintype.card G.Matching : ℝ) + 3 * (m : ℝ) - 2 := by + obtain ⟨z, hz, heq⟩ := uniformMatching_mean G hPM + have hn : G.polytope.Nonempty := ⟨z, hz⟩ + obtain ⟨x, hx, hmax⟩ := UpperSemicontinuousOn.exists_isMaxOn hn G.compact_polytope + continuous_entropy.continuousOn.upperSemicontinuousOn + obtain ⟨y, hy, hmaxb⟩ := UpperSemicontinuousOn.exists_isMaxOn hn G.compact_polytope + continuous_binaryEntropy.continuousOn.upperSemicontinuousOn + have hxdef := (entropy_defect G m hm hV hPM x hx).2.trans (min_le_right _ _) + have hydef := (entropy_defect G m hm hV hPM y hy).2.trans (min_le_right _ _) + have hxu := maxMatchingEntropy_le_log_card G hx + have hyu := maxMatchingEntropy_le_log_card G hy + have hzu := refined_upper G z hz + have hzB := B_nonneg G hz + have hyB := B_le_order G m hV hy + have hzx : entropy z ≤ entropy x := hmax hz + have hzy := hmaxb hz + change entropy z + complementEntropy z ≤ entropy y + complementEntropy y at hzy + refine ⟨x, hx, y, hy, hmax, hmaxb, ?_, ?_, ?_, ?_⟩ + · linarith + · linarith + · change _ ≤ entropy y + complementEntropy y + linarith + · change entropy y + complementEntropy y ≤ _ + linarith + +def countBound (m k : ℕ) (N : ℝ) : Prop := + (k = 1 → 1 ≤ N) ∧ + (2 ≤ k → (k : ℝ)^m * (1 - 1 / (k : ℝ))^(2 * (m - 1) * (k - 1)) ≤ N ∧ + Real.exp (-2 * ((m : ℝ) - 1)) * (k : ℝ)^m ≤ + (k : ℝ)^m * (1 - 1 / (k : ℝ))^(2 * (m - 1) * (k - 1)) ∧ + (Real.exp (-2) * (k : ℝ))^m ≤ Real.exp (-2 * ((m : ℝ) - 1)) * (k : ℝ)^m) + +omit [Fintype V] [DecidableEq V] in +theorem matching_nonempty_of_mem (G : LooplessGraph V E) {x : E → ℝ} (hx : x ∈ G.polytope) : + Nonempty G.Matching := by + obtain ⟨p, hp⟩ := (G.mem_polytope_iff x).mp hx + by_contra h + have : IsEmpty G.Matching := not_nonempty_iff.mp h + simpa using hp.1.2 + +theorem entropy_uniform (G : LooplessGraph V E) {m k : ℕ} + (hV : Fintype.card V = 2 * m) (hk : 2 ≤ k) {x : E → ℝ} (hx : x ∈ G.polytope) + (hu : ∀ e, x e = 0 ∨ x e = 1 / (k : ℝ)) : + entropy x = (m : ℝ) * Real.log (k : ℝ) ∧ + complementEntropy x = -(m : ℝ) * ((k : ℝ) - 1) * Real.log (1 - 1 / (k : ℝ)) := by + have hkR : (0 : ℝ) < k := by exact_mod_cast (show 0 < k by omega) + have ha (e : E) : Real.negMulLog (x e) = x e * Real.log (k : ℝ) := by + rcases hu e with he | he + · simp [he] + · rw [he, one_div, Real.negMulLog, Real.log_inv]; ring + have hb (e : E) : Real.negMulLog (1 - x e) = + -((k : ℝ) - 1) * x e * Real.log (1 - 1 / (k : ℝ)) := by + rcases hu e with he | he + · simp [he] + · rw [he, Real.negMulLog]; field_simp + constructor + · simp_rw [entropy, ha] + rw [← Finset.sum_mul, G.marginal_sum hV hx] + · simp_rw [complementEntropy, entropy, hb] + rw [← Finset.sum_mul, ← Finset.mul_sum, G.marginal_sum hV hx] + ring + +omit [Fintype V] [Fintype E] [DecidableEq V] [DecidableEq E] in +theorem finiteCount_eq_exp {m k : ℕ} (hm : 0 < m) (hk : 2 ≤ k) : + (k : ℝ)^m * (1 - 1 / (k : ℝ))^(2 * (m - 1) * (k - 1)) = + Real.exp ((m : ℝ) * Real.log (k : ℝ) + + 2 * ((m : ℝ) - 1) * ((k : ℝ) - 1) * Real.log (1 - 1 / (k : ℝ))) := by + have hkR : (1 : ℝ) < k := by exact_mod_cast hk + have ht : 0 < 1 - 1 / (k : ℝ) := sub_pos.mpr ((div_lt_one (by linarith)).mpr hkR) + have hc : 2 * ((m : ℝ) - 1) * ((k : ℝ) - 1) = ((2 * (m - 1) * (k - 1) : ℕ) : ℝ) := by + rw [Nat.cast_mul, Nat.cast_mul, Nat.cast_sub (by omega), Nat.cast_sub (by omega)] + norm_num + rw [hc, Real.exp_add, Real.exp_nat_mul, Real.exp_nat_mul, Real.exp_log (by linarith), Real.exp_log ht] + +omit [Fintype V] [Fintype E] [DecidableEq V] [DecidableEq E] in +theorem log_uniform_loss {k : ℕ} (hk : 2 ≤ k) : + -1 ≤ ((k : ℝ) - 1) * Real.log (1 - 1 / (k : ℝ)) := by + have hkR : (1 : ℝ) < k := by exact_mod_cast hk + have hk0 : (0 : ℝ) < k := by linarith + have ht : 0 < 1 - 1 / (k : ℝ) := sub_pos.mpr ((div_lt_one hk0).mpr hkR) + have hb := Real.log_le_sub_one_of_pos (inv_pos.mpr ht) + rw [Real.log_inv] at hb + have hkm : 0 < (k : ℝ) - 1 := by linarith + have heq : ((1 - 1 / (k : ℝ))⁻¹ - 1) * ((k : ℝ) - 1) = 1 := by + field_simp; ring + have hh := mul_le_mul_of_nonneg_right hb (by linarith : 0 ≤ (k : ℝ) - 1) + rw [heq] at hh + nlinarith + +theorem refined_uniform_count (G : LooplessGraph V E) {m k : ℕ} + (hm : 0 < m) (hV : Fintype.card V = 2 * m) {x : E → ℝ} (hx : x ∈ G.polytope) + (hu : ∀ e, x e = 0 ∨ x e = 1 / (k : ℝ)) : + countBound m k (Fintype.card G.Matching : ℝ) := by + have hPM := matching_nonempty_of_mem G hx + have hN : (0 : ℝ) < Fintype.card G.Matching := by + exact_mod_cast Fintype.card_pos_iff.mpr hPM + refine ⟨fun _ => by exact_mod_cast Fintype.card_pos_iff.mpr hPM, fun hk => ?_⟩ + have hk0 : (0 : ℝ) < k := by exact_mod_cast (show 0 < k by omega) + have hm0 : (0 : ℝ) < m := by exact_mod_cast hm + have hm1 : (1 : ℝ) ≤ m := by exact_mod_cast hm + obtain ⟨hF, hB⟩ := entropy_uniform G hV hk hx hu + have hl := (pointwise_entropy G m hm hV hPM x hx).1.trans (maxMatchingEntropy_le_log_card G hx) + rw [hF, hB] at hl + have hl' : (m : ℝ) * Real.log (k : ℝ) + + 2 * ((m : ℝ) - 1) * ((k : ℝ) - 1) * Real.log (1 - 1 / (k : ℝ)) ≤ + Real.log (Fintype.card G.Matching : ℝ) := by + convert hl using 1 + first | rfl | (field_simp; ring) + refine ⟨?_, ?_, ?_⟩ + · rw [finiteCount_eq_exp hm hk] + simpa only [Real.exp_log hN] using Real.exp_le_exp.mpr hl' + · rw [finiteCount_eq_exp hm hk] + have heq : Real.exp (-2 * ((m : ℝ) - 1)) * (k : ℝ)^m = + Real.exp (-2 * ((m : ℝ) - 1) + (m : ℝ) * Real.log (k : ℝ)) := by + rw [Real.exp_add, Real.exp_nat_mul, Real.exp_log hk0] + rw [heq] + apply Real.exp_le_exp.mpr + have hh := mul_le_mul_of_nonneg_left (log_uniform_loss hk) (by linarith : 0 ≤ 2 * ((m : ℝ) - 1)) + nlinarith + · rw [mul_pow, ← Real.exp_nat_mul] + apply mul_le_mul_of_nonneg_right _ (pow_nonneg hk0.le _) + apply Real.exp_le_exp.mpr + linarith + +theorem structural_count (G : LooplessGraph V E) (m k : ℕ) + (hm : 0 < m) (hV : Fintype.card V = 2 * m) (hk : 1 ≤ k) + (M : Fin k → G.Matching) + (hd : ∀ i j, i ≠ j → Disjoint (M i).val (M j).val) : + countBound m k (Fintype.card G.Matching : ℝ) := by + obtain ⟨x, hx, hu⟩ := selected_uniform_mean G hk M hd + exact refined_uniform_count G hm hV hx hu + +theorem regular_count (G : LooplessGraph V E) (m k : ℕ) + (hm : 0 < m) (hV : Fintype.card V = 2 * m) (hk : 1 ≤ k) + (hregular : ∀ v, (Finset.univ.filter (G.Incident v)).card = k) + (hodd : ∀ S : Finset V, Odd S.card → k ≤ (G.cut S).card) : + countBound m k (Fintype.card G.Matching : ℝ) := by + exact refined_uniform_count G hm hV (regular_uniform_mem G hV hk hregular hodd) (fun _ => Or.inr rfl) + +omit [Fintype V] [DecidableEq E] in + +theorem degree_cut_count (G : LooplessGraph V E) {k : ℕ} + (hreg : ∀ v, (Finset.univ.filter (G.Incident v)).card = k) (S : Finset V) : + S.card * k = 2 * (Finset.univ.filter (fun e => G.left e ∈ S ∧ G.right e ∈ S)).card + + (G.cut S).card := by + classical + have hp (e : E) : ((if G.left e ∈ S then (1 : ℕ) else 0) + + (if G.right e ∈ S then 1 else 0)) = + 2 * (if G.left e ∈ S ∧ G.right e ∈ S then 1 else 0) + + (if G.Crosses S e then 1 else 0) := by + by_cases hl : G.left e ∈ S <;> by_cases hr : G.right e ∈ S <;> simp [Crosses, hl, hr] + calc + S.card * k = ∑ v ∈ S, (∑ e : E, if G.Incident v e then (1 : ℕ) else 0) := by + simp [Finset.sum_boole, hreg, Finset.sum_const] + _ = ∑ e : E, ∑ v ∈ S, if G.Incident v e then (1 : ℕ) else 0 := Finset.sum_comm + _ = _ := by + simp_rw [G.incidence_sum, hp] + rw [Finset.sum_add_distrib, ← Finset.mul_sum] + simp [Finset.sum_boole, cut] + +omit [DecidableEq E] in + +theorem connected_odd_cut (G : LooplessGraph V E) {m k : ℕ} + (hV : Fintype.card V = 2 * m) (hk : 1 ≤ k) + (hregular : ∀ v, (Finset.univ.filter (G.Incident v)).card = k) + (hconn : ∀ S : Finset V, S.Nonempty → S ≠ Finset.univ → k - 1 ≤ (G.cut S).card) + (S : Finset V) (hS : Odd S.card) : k ≤ (G.cut S).card := by + have hsmod := Nat.odd_iff.mp hS + have hn : S.Nonempty := Finset.card_pos.mp (by omega) + have hp : S ≠ Finset.univ := by + intro hh + simp only [hh, Finset.card_univ, hV] at hsmod + omega + have hc := hconn S hn hp + have heq := congrArg (fun a : ℕ => a % 2) (degree_cut_count G hregular S) + rw [Nat.mul_mod S.card k 2, hsmod] at heq + simp only [one_mul, Nat.mod_mod] at heq + omega + +theorem connected_regular_count (G : LooplessGraph V E) (m k : ℕ) + (hm : 0 < m) (hV : Fintype.card V = 2 * m) (hk : 1 ≤ k) + (hregular : ∀ v, (Finset.univ.filter (G.Incident v)).card = k) + (hconn : ∀ S : Finset V, S.Nonempty → S ≠ Finset.univ → k - 1 ≤ (G.cut S).card) : + countBound m k (Fintype.card G.Matching : ℝ) := by + exact regular_count G m k hm hV hk hregular (connected_odd_cut G hV hk hregular hconn) + +def weightedPartition (G : LooplessGraph V E) (β : E → ℝ) : ℝ := + ∑ M : G.Matching, (2 : ℝ) ^ (∑ e, β e * G.indicator M e) +def weightedObjective (β x : E → ℝ) : ℝ := entropy x / Real.log 2 + ∑ e, β e * x e + +def gibbsLaw (G : LooplessGraph V E) (β : E → ℝ) (M : G.Matching) : ℝ := + (2 : ℝ) ^ (∑ e, β e * G.indicator M e) / weightedPartition G β + +omit [Fintype V] [DecidableEq V] in +theorem weightedPartition_pos (G : LooplessGraph V E) (hPM : Nonempty G.Matching) (β : E → ℝ) : + 0 < weightedPartition G β := by + let := hPM + exact Finset.sum_pos (fun M _ => Real.rpow_pos_of_pos (by norm_num) _) Finset.univ_nonempty + +omit [Fintype V] [DecidableEq V] in +theorem gibbsLaw_pos (G : LooplessGraph V E) (hPM : Nonempty G.Matching) (β : E → ℝ) (M : G.Matching) : + 0 < gibbsLaw G β M := + div_pos (Real.rpow_pos_of_pos (by norm_num) _) (weightedPartition_pos G hPM β) + +omit [Fintype V] [DecidableEq V] in +theorem gibbsLaw_simplex (G : LooplessGraph V E) (hPM : Nonempty G.Matching) (β : E → ℝ) : + gibbsLaw G β ∈ probabilitySimplex G.Matching := by + refine ⟨fun M => (gibbsLaw_pos G hPM β M).le, ?_⟩ + simp only [gibbsLaw, ← Finset.sum_div] + exact div_self (weightedPartition_pos G hPM β).ne' + +omit [Fintype V] [DecidableEq V] in +theorem gibbs_cross_entropy (G : LooplessGraph V E) (hPM : Nonempty G.Matching) (β : E → ℝ) + {p : G.Matching → ℝ} (hp : p ∈ probabilitySimplex G.Matching) : + -(∑ M, p M * Real.log (gibbsLaw G β M)) = + Real.log (weightedPartition G β) - Real.log 2 * (∑ e, β e * G.mean p e) := by + have hl (M : G.Matching) : Real.log (gibbsLaw G β M) = + (∑ e, β e * G.indicator M e) * Real.log 2 - Real.log (weightedPartition G β) := by + rw [gibbsLaw, Real.log_div (ne_of_gt (Real.rpow_pos_of_pos (by norm_num) _)) + (weightedPartition_pos G hPM β).ne', Real.log_rpow (by norm_num)] + simp_rw [hl, mul_sub, ← mul_assoc] + rw [Finset.sum_sub_distrib, ← Finset.sum_mul, ← Finset.sum_mul, hp.2, one_mul, sum_mean_assoc] + ring + +omit [Fintype V] [DecidableEq V] in +theorem gibbs_law_bound (G : LooplessGraph V E) (hPM : Nonempty G.Matching) (β : E → ℝ) + {p : G.Matching → ℝ} (hp : p ∈ probabilitySimplex G.Matching) : + entropy p / Real.log 2 + (∑ e, β e * G.mean p e) ≤ + Real.log (weightedPartition G β) / Real.log 2 := by + have h := entropy_le_crossEntropy (gibbsLaw_simplex G hPM β) hp + (fun M hzero => ((gibbsLaw_pos G hPM β M).ne' hzero).elim) + rw [gibbs_cross_entropy G hPM β hp] at h + have hlog : 0 < Real.log 2 := Real.log_pos (by norm_num) + apply (le_div_iff₀ hlog).mpr + rw [add_mul, div_mul_cancel₀ _ hlog.ne'] + nlinarith + +omit [Fintype V] [DecidableEq V] in +theorem gibbs_law_equality (G : LooplessGraph V E) (hPM : Nonempty G.Matching) (β : E → ℝ) : + entropy (gibbsLaw G β) / Real.log 2 + (∑ e, β e * G.mean (gibbsLaw G β) e) = + Real.log (weightedPartition G β) / Real.log 2 := by + have h := gibbs_cross_entropy G hPM β (gibbsLaw_simplex G hPM β) + rw [← entropy_eq] at h + rw [h] + have hlog : Real.log 2 ≠ 0 := (Real.log_pos (by norm_num : (1 : ℝ) < 2)).ne' + field_simp + ring + +omit [Fintype V] [DecidableEq V] in + +theorem gibbs_variational (G : LooplessGraph V E) (hPM : Nonempty G.Matching) (β : E → ℝ) : + gibbsLaw G β ∈ probabilitySimplex G.Matching ∧ + maxMatchingEntropy G (G.mean (gibbsLaw G β)) / Real.log 2 + + (∑ e, β e * G.mean (gibbsLaw G β) e) = Real.log (weightedPartition G β) / Real.log 2 ∧ + ∀ x ∈ G.polytope, maxMatchingEntropy G x / Real.log 2 + (∑ e, β e * x e) ≤ + Real.log (weightedPartition G β) / Real.log 2 := by + have hp := gibbsLaw_simplex G hPM β + have hx := G.mean_mem_polytope hp + have hu : ∀ x ∈ G.polytope, maxMatchingEntropy G x / Real.log 2 + (∑ e, β e * x e) ≤ + Real.log (weightedPartition G β) / Real.log 2 := by + intro x hx + obtain ⟨p, hp, hopt⟩ := maxMatchingEntropy_attained G hx + rw [← hopt, ← hp.2] + exact gibbs_law_bound G hPM β hp.1 + refine ⟨hp, le_antisymm (hu _ hx) ?_, hu⟩ + rw [← gibbs_law_equality G hPM β] + exact add_le_add (div_le_div_of_nonneg_right (entropy_le_maxMatchingEntropy G ⟨hp, rfl⟩) + (Real.log_pos (by norm_num)).le) le_rfl + +theorem weighted_count (G : LooplessGraph V E) (m : ℕ) + (hm : 0 < m) (hV : Fintype.card V = 2 * m) (hPM : Nonempty G.Matching) + (β : E → ℝ) : + ∃ x ∈ G.polytope, (∀ y ∈ G.polytope, weightedObjective β y ≤ weightedObjective β x) ∧ + weightedObjective β x - (2 * (m : ℝ) - 2) / Real.log 2 ≤ + Real.log (weightedPartition G β) / Real.log 2 ∧ + Real.log (weightedPartition G β) / Real.log 2 ≤ weightedObjective β x := by + obtain ⟨hp, heq, hu⟩ := gibbs_variational G hPM β + have hz := G.mean_mem_polytope hp + have hcont : Continuous (weightedObjective β) := by + unfold weightedObjective + exact (continuous_entropy.div_const _).add (by fun_prop) + obtain ⟨x, hx, hmax⟩ := UpperSemicontinuousOn.exists_isMaxOn ⟨_, hz⟩ G.compact_polytope + hcont.continuousOn.upperSemicontinuousOn + have hlog : 0 < Real.log 2 := Real.log_pos (by norm_num) + refine ⟨x, hx, hmax, ?_, ?_⟩ + · have hd := (entropy_defect G m hm hV hPM x hx).2.trans (min_le_right _ _) + have hd' := div_le_div_of_nonneg_right hd hlog.le + have huu := hu x hx + dsimp only [weightedObjective] + rw [sub_div] at hd' + linarith + · rw [← heq] + apply le_trans _ (hmax hz) + exact add_le_add (div_le_div_of_nonneg_right (refined_upper G _ hz) hlog.le) le_rfl + +end MatchingEntropyBounds.Refined + +end + +end OAI diff --git a/lean/OAI/Combinatorics/MatchingEntropy/Polyhedron.lean b/lean/OAI/Combinatorics/MatchingEntropy/Polyhedron.lean new file mode 100644 index 0000000000000000000000000000000000000000..5caac6e5a8e6edaf371cea1d3e638737de55490e --- /dev/null +++ b/lean/OAI/Combinatorics/MatchingEntropy/Polyhedron.lean @@ -0,0 +1,116 @@ +import OAI.Combinatorics.MatchingEntropy.Simplex + +namespace OAI + +noncomputable section + +open scoped BigOperators Topology +open Filter + +universe uV uE uI uJ uA uB uC uW uF uD uι + +namespace MatchingEntropyBounds + +section PolyhedralPrelude +variable {I : Type uI} {J : Type uJ} [Fintype I] [Fintype J] + +def finitePolyhedron (L : I → (J → ℝ) →ₗ[ℝ] ℝ) (b : I → ℝ) : Set (J → ℝ) := + {x | ∀ i, L i x ≤ b i} + +theorem finitePolyhedron_eventually_line (L : I → (J → ℝ) →ₗ[ℝ] ℝ) (b : I → ℝ) + {x : J → ℝ} (hx : x ∈ finitePolyhedron L b) (u : J → ℝ) + (hu : ∀ i, L i x = b i → L i u = 0) : + ∀ᶠ t : ℝ in 𝓝 0, x+t • u ∈ finitePolyhedron L b := by + apply Filter.eventually_all.mpr + intro i + by_cases hi : L i x=b i + · apply Filter.Eventually.of_forall + intro t + rw [map_add, map_smul, hu i hi, smul_zero, add_zero, hi] + · have hlt : L i x < b i := lt_of_le_of_ne (hx i) hi + have hc : Continuous (fun t : ℝ => L i (x+t • u)) := + (L i).continuous_of_finiteDimensional.comp (by fun_prop) + have hh : ∀ᶠ t : ℝ in 𝓝 0, L i (x+t • u) < b i := + (isOpen_lt hc continuous_const).mem_nhds (by simpa using hlt : L i (x+(0:ℝ) • u) < b i) + exact hh.mono fun t ht => le_of_lt ht + +theorem finitePolyhedron_eventually_expand (L : I → (J → ℝ) →ₗ[ℝ] ℝ) (b : I → ℝ) + {x : J → ℝ} (hx : x ∈ finitePolyhedron L b) {t : ℝ} (ht : 0 < t) : + ∀ᶠ y in 𝓝[finitePolyhedron L b] x, x+t⁻¹ • (y-x) ∈ finitePolyhedron L b := by + apply Filter.eventually_all.mpr + intro i + by_cases hi : L i x=b i + · filter_upwards [eventually_mem_nhdsWithin] with y hy + rw [map_add, map_smul, map_sub, hi] + change b i+t⁻¹ * (L i y-b i) ≤ b i + have hh := mul_nonpos_of_nonneg_of_nonpos (inv_nonneg.mpr ht.le) (sub_nonpos.mpr (hy i)) + linarith + · have hlt : L i x < b i := lt_of_le_of_ne (hx i) hi + have hc : Continuous (fun y : J → ℝ => L i (x+t⁻¹ • (y-x))) := + (L i).continuous_of_finiteDimensional.comp (by fun_prop) + have hh : ∀ᶠ y : J → ℝ in 𝓝 x, L i (x+t⁻¹ • (y-x)) < b i := + (isOpen_lt hc continuous_const).mem_nhds (by simpa using hlt : L i (x+t⁻¹ • (x-x)) < b i) + exact (hh.filter_mono nhdsWithin_le_nhds).mono fun y hy => le_of_lt hy + +omit [Fintype J] in +theorem extreme_point_direction_zero (P : Set (J → ℝ)) {x : J → ℝ} + (hx : x ∈ Set.extremePoints ℝ P) (u : J → ℝ) + (hu : ∀ᶠ t : ℝ in 𝓝 0, x+t • u ∈ P) : u=0 := by + have hu' : ∀ᶠ t : ℝ in 𝓝 0, x+(-t) • u ∈ P := by + have hc : Tendsto (fun t : ℝ => -t) (𝓝 0) (𝓝 0) := by simpa using (continuous_neg.tendsto (0:ℝ)) + exact hc.eventually hu + + have hh : ∀ᶠ t : ℝ in 𝓝[>] 0, (x+t • u ∈ P ∧ x+(-t) • u ∈ P) ∧ 0.1 + ext j + have hj := congrFun he j + change x j+a*u j=x j at hj + change u j=0 + exact (mul_eq_zero.mp (by linarith : a*u j=0)).resolve_left (ne_of_gt ha0) + +section LinearHelper +open Module +variable {A : Type uA} {B : Type uB} {C : Type uC} [AddCommGroup A] [AddCommGroup B] [AddCommGroup C] + [Module ℝ A] [Module ℝ B] [Module ℝ C] + [FiniteDimensional ℝ A] [FiniteDimensional ℝ B] [FiniteDimensional ℝ C] + +theorem quotient_finrank_le_of_ker_le (U : Submodule ℝ A) (f : A →ₗ[ℝ] B) + (h : f.ker ≤ U) : finrank ℝ (A ⧸ U) ≤ finrank ℝ B := by + have h1 := U.finrank_quotient_add_finrank + have h2 := f.finrank_range_add_finrank_ker + have h3 := Submodule.finrank_mono h + have h4 : finrank ℝ f.range ≤ finrank ℝ B := Submodule.finrank_le _ + omega + +theorem quotient_finrank_le_pair (U : Submodule ℝ A) (W : Submodule ℝ B) (Z : Submodule ℝ C) + (f : A →ₗ[ℝ] B) (g : A →ₗ[ℝ] C) + (h : ∀ u, f u ∈ W → g u ∈ Z → u ∈ U) : + finrank ℝ (A ⧸ U) ≤ finrank ℝ (B ⧸ W)+finrank ℝ (C ⧸ Z) := by + let F := (W.mkQ.comp f).prod (Z.mkQ.comp g) + have hk : F.ker ≤ U := by + intro u hu + have hh : (W.mkQ (f u), Z.mkQ (g u))=0 := hu + have hW : f u ∈ W := by + have hq := congrArg Prod.fst hh + simpa using hq + have hZ : g u ∈ Z := by + have hq := congrArg Prod.snd hh + simpa using hq + exact h u hW hZ + simpa using quotient_finrank_le_of_ker_le U F hk + +end LinearHelper +end PolyhedralPrelude + +end MatchingEntropyBounds + +end + +end OAI diff --git a/lean/OAI/Combinatorics/MatchingEntropy/Polytope.lean b/lean/OAI/Combinatorics/MatchingEntropy/Polytope.lean new file mode 100644 index 0000000000000000000000000000000000000000..f3fe6bd05014b73abd7963ceca7afd7c92cdab7c --- /dev/null +++ b/lean/OAI/Combinatorics/MatchingEntropy/Polytope.lean @@ -0,0 +1,381 @@ +import OAI.Combinatorics.MatchingEntropy.Contraction + +namespace OAI + +noncomputable section + +open scoped BigOperators Topology +open Filter + +universe uV uE uI uJ uA uB uC uW uF uD uι + +namespace MatchingEntropyBounds.LooplessGraph + +variable {V : Type uV} {E : Type uE} [Fintype V] [Fintype E] [DecidableEq V] [DecidableEq E] + +def supportSimple (G : LooplessGraph V E) (x : E → ℝ) : SimpleGraph V where + Adj v w := ∃ e, 0 < x e ∧ ((G.left e=v ∧ G.right e=w) ∨ (G.left e=w ∧ G.right e=v)) + symm := ⟨by intro v w; rintro ⟨e,hx,h⟩; exact ⟨e,hx,h.symm⟩⟩ + loopless := ⟨by + intro v + rintro ⟨e,_,(⟨hl,hr⟩ | ⟨hl,hr⟩)⟩ <;> exact G.loopless e (hl.trans hr.symm)⟩ + +omit [Fintype V] [Fintype E] [DecidableEq V] [DecidableEq E] in + theorem supportSimple_edge (G : LooplessGraph V E) {x : E → ℝ} {e : E} (he : 0 < x e) : + (G.supportSimple x).Adj (G.left e) (G.right e) := ⟨e,he,Or.inl ⟨rfl,rfl⟩⟩ + +theorem sum_pred_le_one {C : Type uC} [Fintype C] (P : C → Prop) [DecidablePred P] + (huniq : ∀ a b, P a → P b → a=b) : (∑ c, if P c then (1 : ℝ) else 0) ≤ 1 := by + by_cases h : ∃ a, P a + · obtain ⟨a,ha⟩ := h + rw [Finset.sum_eq_single a] + · simp [ha] + · intro b _ hb + rw [ite_eq_right] + intro hPb + exact hb (huniq b a hPb ha) + · simp + · simp only [not_exists] at h + simp [h] + +omit [Fintype V] [DecidableEq E] in + +theorem odd_family_bound (G : LooplessGraph V E) {x : E → ℝ} + (hx : x ∈ G.constraintPolytope) {C : Type uC} [Fintype C] [DecidableEq C] + (U : Finset V) (T : C → Finset V) + (hodd : ∀ c, Odd (T c).card) + (hdisj : ∀ c v, v ∈ T c → v ∉ U) + (huniq : ∀ a b v, v ∈ T a → v ∈ T b → a=b) + (hclosed : ∀ e, 0 < x e → G.left e ∉ U → G.right e ∉ U → + ∀ c, G.left e ∈ T c ↔ G.right e ∈ T c) : + Fintype.card C ≤ U.card := by + have hcuts : (Fintype.card C : ℝ) ≤ ∑ c, G.cutMass x (T c) := by + calc + _ = ∑ c : C, (1 : ℝ) := by simp + _ ≤ _ := Finset.sum_le_sum fun c _ => hx.2.2 (T c) (hodd c) + have hedges : ∀ e, (∑ c, if G.Crosses (T c) e then x e else 0) ≤ + (if G.left e ∈ U then x e else 0) + (if G.right e ∈ U then x e else 0) := by + intro e + by_cases hz : x e=0 + · simp [hz] + have hp : 0 < x e := lt_of_le_of_ne (hx.1 e) (Ne.symm hz) + by_cases hl : G.left e ∈ U <;> by_cases hr : G.right e ∈ U + · have hzero : ∀ c, ¬G.Crosses (T c) e := by + intro c hc + rcases hc with h | h + · exact hdisj c _ h.1 hl + · exact hdisj c _ h.2 hr + simp [hzero, hl, hr, hx.1 e] + · have heq : ∀ c, G.Crosses (T c) e ↔ G.right e ∈ T c := by + intro c + have hn : G.left e ∉ T c := fun h => hdisj c _ h hl + simp [Crosses, hn] + simp_rw [heq] + have hcount := sum_pred_le_one (fun c => G.right e ∈ T c) + (fun a b => huniq a b (G.right e)) + have heq' : (∑ c, if G.right e ∈ T c then x e else 0) = + (∑ c, if G.right e ∈ T c then (1 : ℝ) else 0) * x e := by + rw [Finset.sum_mul] + apply Finset.sum_congr rfl + intro c _ + split <;> simp + rw [heq'] + simpa [hl, hr] using mul_le_mul_of_nonneg_right hcount (hx.1 e) + · have heq : ∀ c, G.Crosses (T c) e ↔ G.left e ∈ T c := by + intro c + have hn : G.right e ∉ T c := fun h => hdisj c _ h hr + simp [Crosses, hn] + simp_rw [heq] + have hcount := sum_pred_le_one (fun c => G.left e ∈ T c) + (fun a b => huniq a b (G.left e)) + have heq' : (∑ c, if G.left e ∈ T c then x e else 0) = + (∑ c, if G.left e ∈ T c then (1 : ℝ) else 0) * x e := by + rw [Finset.sum_mul] + apply Finset.sum_congr rfl + intro c _ + split <;> simp + rw [heq'] + simpa [hl, hr] using mul_le_mul_of_nonneg_right hcount (hx.1 e) + · have hzero : ∀ c, ¬G.Crosses (T c) e := by + intro c hc + have hiff := hclosed e hp hl hr c + unfold Crosses at hc + tauto + simp [hzero, hl, hr] + have hdegree : ∑ v ∈ U, G.degree x v = (U.card : ℝ) := by + simp_rw [hx.2.1] + simp + have hsum : (∑ e : E, ((if G.left e ∈ U then x e else 0) + + (if G.right e ∈ U then x e else 0))) = ∑ v ∈ U, G.degree x v := by + simp only [degree] + rw [Finset.sum_comm] + apply Finset.sum_congr rfl + intro e _ + have hf : ∀ v, (if G.Incident v e then x e else 0) = + (if G.left e = v then x e else 0) + (if G.right e = v then x e else 0) := by + intro v + by_cases hl : G.left e=v <;> by_cases hr : G.right e=v + · exact (G.loopless e (hl.trans hr.symm)).elim + all_goals simp [Incident, hl, hr] + simp_rw [hf] + rw [Finset.sum_add_distrib] + simp + have hbound := (Finset.sum_le_sum (fun e (_ : e ∈ Finset.univ) => hedges e)) + rw [hsum, hdegree] at hbound + have hcutEq : (∑ c, G.cutMass x (T c)) = ∑ e, ∑ c, if G.Crosses (T c) e then x e else 0 := by + simp only [cutMass, cut, Finset.sum_filter] + exact Finset.sum_comm + exact_mod_cast hcuts.trans (hcutEq ▸ hbound) + +omit [DecidableEq E] in +theorem supportSimple_has_perfectMatching (G : LooplessGraph V E) {x : E → ℝ} + (hx : x ∈ G.constraintPolytope) : + ∃ M : (G.supportSimple x).Subgraph, M.IsPerfectMatching := by + classical + apply SimpleGraph.tutte.mpr + intro U + let H := (⊤ : (G.supportSimple x).Subgraph).deleteVerts U + let C := H.coe.oddComponents + let : Fintype C := Fintype.ofFinite C + let T : C → Finset V := fun c => (Subtype.val '' c.val.supp).toFinset + have hnot : ∀ v : H.verts, v.val ∉ U := by + intro v + have hv := v.property + simpa [H] using hv + have hT : ∀ c : C, ∀ v : V, v ∈ T c ↔ ∃ w : H.verts, w ∈ c.val.supp ∧ w.val=v := by + intro c v + simp [T] + have hodd : ∀ c : C, Odd (T c).card := by + intro c + have hc := c.property + change Odd c.val.supp.ncard at hc + change Odd ((Subtype.val '' c.val.supp).toFinset.card) + rw [← Set.ncard_eq_toFinset_card', Set.ncard_image_of_injective _ Subtype.val_injective] + exact hc + have hdisj : ∀ c v, v ∈ T c → v ∉ U.toFinset := by + intro c v hv + obtain ⟨w,_,rfl⟩ := (hT c v).mp hv + simpa using hnot w + have huniq : ∀ a b v, v ∈ T a → v ∈ T b → a=b := by + intro a b v ha hb + obtain ⟨wa,hwa,rfl⟩ := (hT a v).mp ha + obtain ⟨wb,hwb,he⟩ := (hT b wa.val).mp hb + have hw : wb=wa := Subtype.ext he + subst wb + exact Subtype.ext (SimpleGraph.ConnectedComponent.eq_of_common_vertex hwa hwb) + have hclosed : ∀ e, 0 SimpleGraph.ConnectedComponent.mem_coe_supp_of_adj h hr' ha, + fun h => SimpleGraph.ConnectedComponent.mem_coe_supp_of_adj h hl' ha.symm⟩ + have hb := G.odd_family_bound hx U.toFinset T hodd hdisj huniq hclosed + change ¬ U.ncard < H.coe.oddComponents.ncard + have hcard : Fintype.card C = H.coe.oddComponents.ncard := by + simp [C, ← Nat.card_eq_fintype_card, Nat.card_coe_set_eq] + rw [hcard] at hb + exact not_lt_of_ge (by simpa only [← Set.ncard_eq_toFinset_card'] using hb) + +theorem exists_supported_matching (G : LooplessGraph V E) {x : E → ℝ} + (hx : x ∈ G.constraintPolytope) : + ∃ M : G.Matching, ∀ e ∈ M.val, 0 < x e := by + classical + obtain ⟨M,hM⟩ := G.supportSimple_has_perfectMatching hx + have he : ∀ q ∈ M.edgeSet, ∃ e, 0 + intro hq + obtain ⟨e,he,hor⟩ := (SimpleGraph.Subgraph.mem_edgeSet.mp hq).adj_sub + refine ⟨e,he,Sym2.eq_iff.mpr hor⟩ + let f : M.edgeSet → E := fun q => (he q.val q.property).choose + have hf : ∀ q, 0 (he q.val q.property).choose_spec + let F : Finset E := Finset.univ.image f + have hF : G.IsPerfectMatching F := by + intro v + obtain ⟨w,hw,hu⟩ := SimpleGraph.Subgraph.isPerfectMatching_iff.mp hM v + let q : M.edgeSet := ⟨s(v,w),SimpleGraph.Subgraph.mem_edgeSet.mpr hw⟩ + refine ⟨f q,⟨Finset.mem_image.mpr ⟨q,Finset.mem_univ _,rfl⟩,?_⟩,?_⟩ + · rcases Sym2.eq_iff.mp (hf q).2 with h | h + · exact Or.inl h.1 + · exact Or.inr h.2 + · intro e he' + obtain ⟨q',_,rfl⟩ := Finset.mem_image.mp he'.1 + have hq : q'=q := by + apply Subtype.ext + rcases he'.2 with hl | hr + · have hval : q'.val=s(v,G.right (f q')) := by rw [← (hf q').2, hl] + have hAdj : M.Adj v (G.right (f q')) := + SimpleGraph.Subgraph.mem_edgeSet.mp (hval ▸ q'.property) + rw [hval, hu _ hAdj] + · have hval : q'.val=s(v,G.left (f q')) := by + rw [← (hf q').2, hr, Sym2.eq_swap] + have hAdj : M.Adj v (G.left (f q')) := + SimpleGraph.Subgraph.mem_edgeSet.mp (hval ▸ q'.property) + rw [hval, hu _ hAdj] + exact congrArg f hq + refine ⟨⟨F,hF⟩,?_⟩ + intro e he' + obtain ⟨q,_,rfl⟩ := Finset.mem_image.mp he' + exact (hf q).1 + +omit [Fintype V] [Fintype E] [DecidableEq E] in +@[simp] theorem crosses_singleton (G : LooplessGraph V E) (v : V) (e : E) : + G.Crosses {v} e ↔ G.Incident v e := by + have hh := G.loopless e + simp only [Crosses, Finset.mem_singleton, Incident] + have hn : ¬ (G.left e=v ∧ G.right e=v) := fun h => hh (h.1.trans h.2.symm) + tauto + +omit [Fintype V] [DecidableEq E] in +@[simp] theorem cutMass_singleton (G : LooplessGraph V E) (x : E → ℝ) (v : V) : + G.cutMass x {v} = G.degree x v := by + simp [cutMass,cut,Finset.sum_filter,degree] + +omit [DecidableEq E] in + +theorem constraint_eventually_line (G : LooplessGraph V E) {x : E → ℝ} + (hx : x ∈ G.constraintPolytope) (u : E → ℝ) + (hzero : ∀ e, x e=0 → u e=0) (hdeg : ∀ v, G.degree u v=0) + (hcut : ∀ S, Odd S.card → G.cutMass x S=1 → G.cutMass u S=0) : + ∀ᶠ t : ℝ in 𝓝 0, x+t • u ∈ G.constraintPolytope := by + have hn : ∀ᶠ t : ℝ in 𝓝 0, ∀ e, 0≤(x+t • u) e := by + apply Filter.eventually_all.mpr + intro e + by_cases he : x e=0 + · exact Filter.Eventually.of_forall (by intro t; simp [he,hzero e he]) + · have hp : 0 (x+t • u) e) := by fun_prop + have hh : ∀ᶠ t : ℝ in 𝓝 0, 0<(x+t • u) e := (isOpen_lt continuous_const hc).mem_nhds + (by simpa using hp : 0<(x+(0:ℝ) • u) e) + exact hh.mono fun t ht => ht.le + have hodd : ∀ᶠ t : ℝ in 𝓝 0, ∀ S : Finset V, Odd S.card → 1≤G.cutMass (x+t • u) S := by + apply Filter.eventually_all.mpr + intro S + by_cases hS : Odd S.card + · by_cases ht : G.cutMass x S=1 + · exact Filter.Eventually.of_forall (by + intro t _ + have he := G.cutMass_linear x u 1 t S + simp only [one_smul, one_mul, hcut S hS ht, mul_zero, add_zero, ht] at he + exact he.ge) + · have hp : 1 G.cutMass (x+t • u) S) := + (G.continuous_cutMass S).comp (by fun_prop) + have hh : ∀ᶠ t : ℝ in 𝓝 0, 1 ht.le + · exact Filter.Eventually.of_forall fun _ h => (hS h).elim + filter_upwards [hn,hodd] with t hn hodd + refine ⟨hn,?_,hodd⟩ + intro v + have he := G.degree_linear x u 1 t v + simpa only [one_smul, one_mul, hdeg, mul_zero, add_zero, hx.2.1] using he + +omit [Fintype V] [DecidableEq E] in + theorem degree_sub (G : LooplessGraph V E) (x y : E → ℝ) (v : V) : + G.degree (x-y) v = G.degree x v-G.degree y v := by + have h := G.degree_linear x y 1 (-1) v + simpa [sub_eq_add_neg] using h + +omit [Fintype V] [DecidableEq E] in + theorem cutMass_sub (G : LooplessGraph V E) (x y : E → ℝ) (S : Finset V) : + G.cutMass (x-y) S = G.cutMass x S-G.cutMass y S := by + have h := G.cutMass_linear x y 1 (-1) S + simpa [sub_eq_add_neg] using h + +omit [DecidableEq E] in + +theorem trivial_tight_cut_preserved (G : LooplessGraph V E) {x : E → ℝ} + (heven : Even (Fintype.card V)) + (hnt : ¬∃ S : Finset V, Odd S.card ∧ 3≤S.card ∧ 3≤Sᶜ.card ∧ G.cutMass x S=1) + (u : E → ℝ) (hdeg : ∀ v, G.degree u v=0) : + ∀ S, Odd S.card → G.cutMass x S=1 → G.cutMass u S=0 := by + intro S hS ht + have hc := odd_compl_of_even heven hS + have hsmall : S.card=1 ∨ Sᶜ.card=1 := by + have hn : ¬ (3≤S.card ∧ 3≤Sᶜ.card) := fun h => hnt ⟨S,hS,h.1,h.2,ht⟩ + rcases hS with ⟨k,hk⟩ + rcases hc with ⟨l,hl⟩ + omega + rcases hsmall with hs | hs + · obtain ⟨v,rfl⟩ := Finset.card_eq_one.mp hs + simpa using hdeg v + · obtain ⟨v,hv⟩ := Finset.card_eq_one.mp hs + have hh : G.cutMass u Sᶜ=0 := by rw [hv,cutMass_singleton,hdeg] + simpa only [cutMass,cut_compl] using hh + + theorem extreme_no_tight_integral (G : LooplessGraph V E) {x : E → ℝ} + (heven : Even (Fintype.card V)) (hx : x ∈ Set.extremePoints ℝ G.constraintPolytope) + (hnt : ¬∃ S : Finset V, Odd S.card ∧ 3≤S.card ∧ 3≤Sᶜ.card ∧ G.cutMass x S=1) : + ∃ M : G.Matching, G.indicator M=x := by + have hxQ := (mem_extremePoints.mp hx).1 + obtain ⟨M,hM⟩ := G.exists_supported_matching hxQ + have hd : ∀ v, G.degree (G.indicator M-x) v=0 := by + intro v + rw [degree_sub,degree_indicator,hxQ.2.1,sub_self] + have hz : ∀ e, x e=0 → (G.indicator M-x) e=0 := by + intro e he + have hn : e ∉ M.val := fun h => (hM e h).ne' he + simp [indicator,hn,he] + have hu := G.constraint_eventually_line hxQ (G.indicator M-x) hz hd + (G.trivial_tight_cut_preserved heven hnt _ hd) + have he := extreme_point_direction_zero G.constraintPolytope hx _ hu + exact ⟨M,sub_eq_zero.mp he⟩ + +theorem constraint_subset_polytope_aux (n : ℕ) : + ∀ {W : Type uW} {F : Type uF} [Fintype W] [Fintype F] [DecidableEq W] [DecidableEq F] + (G : LooplessGraph W F), Fintype.card W=n → Even n → + G.constraintPolytope ⊆ G.polytope := by + induction n using Nat.strong_induction_on with + | h n ih => + intro W F _ _ _ _ G hcard heven + have heven' : Even (Fintype.card W) := hcard ▸ heven + have hex : Set.extremePoints ℝ G.constraintPolytope ⊆ G.polytope := by + intro x hx + have hxQ := (mem_extremePoints.mp hx).1 + by_cases hcut : ∃ S : Finset W, Odd S.card ∧ 3≤S.card ∧ 3≤Sᶜ.card ∧ G.cutMass x S=1 + · obtain ⟨S,hS,hlo,hhi,ht⟩ := hcut + have hc := odd_compl_of_even heven' hS + have hlt1 : Fintype.card (Option {v // v ∈ S}) < n := by + simp only [Fintype.card_option,Fintype.card_coe] + have hco := Finset.card_compl S + omega + have hlt2 : Fintype.card (Option {v // v ∈ Sᶜ}) < n := by + simp only [Fintype.card_option,Fintype.card_coe] + have hco := Finset.card_compl S + have hle := Finset.card_le_univ S + omega + have hv1 : Even (Fintype.card (Option {v // v ∈ S})) := by + simpa only [Fintype.card_option,Fintype.card_coe] using hS.add_odd odd_one + have hv2 : Even (Fintype.card (Option {v // v ∈ Sᶜ})) := by + simpa only [Fintype.card_option,Fintype.card_coe] using hc.add_odd odd_one + have hx1 := ih _ hlt1 (G.onSide S) rfl hv1 (G.restriction_mem_constraints hxQ S hS ht) + have htc : G.cutMass x Sᶜ=1 := by simpa only [cutMass,cut_compl] using ht + have hx2 := ih _ hlt2 (G.onSide Sᶜ) rfl hv2 (G.restriction_mem_constraints hxQ Sᶜ hc htc) + obtain ⟨p,hp,hpx⟩ := ((G.onSide S).mem_polytope_iff _).mp hx1 + obtain ⟨q,hq,hqx⟩ := ((G.onSide Sᶜ).mem_polytope_iff _).mp hx2 + exact (G.mem_polytope_iff x).mpr (G.couple_laws S x hp hq (congrFun hpx) (congrFun hqx)) + · obtain ⟨M,rfl⟩ := G.extreme_no_tight_integral heven' hx hcut + exact subset_convexHull ℝ _ (Set.mem_range_self M) + rw [← closure_convexHull_extremePoints G.isCompact_constraintPolytope G.convex_constraintPolytope] + exact closure_minimal (convexHull_min hex (convex_convexHull ℝ _)) G.compact_polytope.isClosed + +theorem polytope_eq_constraints (G : LooplessGraph V E) (heven : Even (Fintype.card V)) : + G.polytope = G.constraintPolytope := by + exact Set.Subset.antisymm G.polytope_subset_constraintPolytope + (constraint_subset_polytope_aux (Fintype.card V) G rfl heven) + +end MatchingEntropyBounds.LooplessGraph + +end + +end OAI diff --git a/lean/OAI/Combinatorics/MatchingEntropy/RefinedVariation.lean b/lean/OAI/Combinatorics/MatchingEntropy/RefinedVariation.lean new file mode 100644 index 0000000000000000000000000000000000000000..c48f18b4ae87dc46ce9a5f9cdd2a9e12f1e1b64b --- /dev/null +++ b/lean/OAI/Combinatorics/MatchingEntropy/RefinedVariation.lean @@ -0,0 +1,491 @@ +import OAI.Combinatorics.MatchingEntropy.SharpRank + +namespace OAI + +noncomputable section + +open scoped BigOperators Topology +open Filter Module + +universe uV uE uI uJ uA uB uC uW uF uD uι + +namespace MatchingEntropyBounds.Refined + +variable {V : Type uV} {E : Type uE} [Fintype V] [Fintype E] [DecidableEq V] [DecidableEq E] + +open LooplessGraph + +omit [Fintype V] [DecidableEq V] [DecidableEq E] in +theorem continuous_lowerObjective (κ : ℝ) : Continuous (lowerObjective (E := E) κ) := by + exact continuous_entropy.sub (continuous_const.mul (continuous_entropy.comp (by fun_prop))) + +def objectiveLineD (κ : ℝ) (x v : E → ℝ) (t : ℝ) : ℝ := + entropyLineD x v t - κ * entropyLineD (fun e => 1-x e) (fun e => -v e) t + +omit [Fintype V] [DecidableEq V] [DecidableEq E] in +theorem objective_line_eventually_hasDerivAt (κ : ℝ) (x v : E → ℝ) + (hzero : ∀ e, x e = 0 → v e = 0) (hone : ∀ e, x e = 1 → v e = 0) : + ∀ᶠ t : ℝ in 𝓝 0, + HasDerivAt (fun t => lowerObjective κ (fun e => x e+t*v e)) + (objectiveLineD κ x v t) t := by + have hbar : ∀ e, 1-x e=0 → -v e=0 := by + intro e he + rw [hone e (by linarith), neg_zero] + filter_upwards [entropy_line_eventually_hasDerivAt x v hzero, + entropy_line_eventually_hasDerivAt (fun e => 1-x e) (fun e => -v e) hbar] + with t ht hb + have he : (fun t => lowerObjective κ (fun e => x e+t*v e)) = + (fun t => entropy (fun e => x e+t*v e) - + κ * entropy (fun e => (1-x e)+t*(-v e))) := by + funext t + unfold lowerObjective complementEntropy + congr 2 + congr 1 + funext e + ring + rw [he] + exact ht.sub (hb.const_mul κ) + +omit [Fintype V] [DecidableEq V] [DecidableEq E] in +theorem objectiveLineD_hasDerivAt (κ : ℝ) (x v : E → ℝ) + (hzero : ∀ e, x e = 0 → v e = 0) (hone : ∀ e, x e = 1 → v e = 0) : + HasDerivAt (objectiveLineD κ x v) + (-(∑ e, (v e)^2/x e) + κ*(∑ e, (v e)^2/(1-x e))) 0 := by + have hbar : ∀ e, 1-x e=0 → -v e=0 := by + intro e he + rw [hone e (by linarith), neg_zero] + have hd := (entropyLineD_hasDerivAt x v hzero).sub + ((entropyLineD_hasDerivAt (fun e => 1-x e) (fun e => -v e) hbar).const_mul κ) + exact hd.congr_deriv (by simp only [neg_sq]; ring) + +omit [Fintype V] [DecidableEq V] [DecidableEq E] in +theorem objective_second_variation (κ : ℝ) {A : Type uA} [Fintype A] + (x v : E → ℝ) (hzero : ∀ e, x e=0 → v e=0) (hone : ∀ e, x e=1 → v e=0) + {p : A → ℝ} (hp : p ∈ probabilitySimplex A) (a : A → ℝ) + (hcenter : ∑ i, p i*a i=0) (c₀ c₁ : ℝ) + (hlocal : IsLocalMax (fun t => lowerObjective κ (fun e => x e+t*v e) + + c₀+t*c₁+t^2*(∑ i, p i*(a i)^2)-Real.log (partition p a t)) 0) : + -(∑ e, (v e)^2/x e) + κ*(∑ e, (v e)^2/(1-x e)) + + (∑ i, p i*(a i)^2) ≤ 0 := by + have hf := objective_line_eventually_hasDerivAt κ x v hzero hone + have hg : ∀ᶠ t : ℝ in 𝓝 0, HasDerivAt (fun t => Real.log (partition p a t)) + (partition (fun i => p i*a i) a t / partition p a t) t := + Filter.Eventually.of_forall (logPartition_hasDerivAt hp a) + have hd := second_deriv_quadratic_adjustment (c₀ := c₀) (c₁ := c₁) + (v := ∑ i, p i*(a i)^2) hf hg (objectiveLineD_hasDerivAt κ x v hzero hone) + (logPartition_second hp a) + have hc : ContinuousAt (fun t => lowerObjective κ (fun e => x e+t*v e) + + c₀+t*c₁+t^2*(∑ i, p i*(a i)^2)-Real.log (partition p a t)) 0 := by + apply ContinuousAt.sub + · apply ContinuousAt.add + · apply ContinuousAt.add + · exact hf.self_of_nhds.continuousAt.add_const c₀ + · fun_prop + · fun_prop + · exact hg.self_of_nhds.continuousAt + have hh := second_deriv_nonpos_of_local_max hlocal hc + rw [hd.deriv, hcenter] at hh + nlinarith + +omit [Fintype V] [DecidableEq V] in + +theorem matching_objective_second_variation (κ : ℝ) (G : LooplessGraph V E) {x : E → ℝ} + {p : G.Matching → ℝ} (hp : p ∈ G.feasibleLaws x) + (hopt : entropy p=maxMatchingEntropy G x) + (hmax : ∀ y ∈ G.polytope, lowerObjective κ y-maxMatchingEntropy G y ≤ + lowerObjective κ x-maxMatchingEntropy G x) + (u : E → ℝ) (c : ℝ) (hcenter : ∑ M, p M*linearScore G u c M=0) : + -(∑ e, (G.mean (fun M => p M*linearScore G u c M) e)^2/x e) + + κ*(∑ e, (G.mean (fun M => p M*linearScore G u c M) e)^2/(1-x e)) + + (∑ M, p M*(linearScore G u c M)^2) ≤ 0 := by + let a := linearScore G u c + let v := G.mean (fun M => p M*a M) + let c₀ := ∑ M, p M*Real.log (p M) + let c₁ := ∑ M, (p M*a M)*Real.log (p M) + have hzero : ∀ e, x e=0 → v e=0 := by + rw [← hp.2] + exact mean_score_support G hp.1 a + have hone : ∀ e, x e=1 → v e=0 := by + rw [← hp.2] + exact mean_score_one G hp.1 a hcenter + apply objective_second_variation κ x v hzero hone hp.1 a hcenter c₀ c₁ + filter_upwards [score_law_eventually_simplex hp.1 a hcenter] with t ht + let r := fun M => p M+t*(p M*a M) + have hr : r ∈ probabilitySimplex G.Matching := ht + have hrmean : G.mean r=fun e => x e+t*v e := by + change G.meanLinear (p+t • (fun M => p M*a M)) = _ + rw [map_add, map_smul] + change G.mean p+t • v = _ + rw [hp.2] + rfl + have hdual := matching_entropy_dual_bound G hp hopt hr + (fun M hM => by dsimp [r]; simp [hM]) u c t + have hscore : (∑ M, r M*a M)=t*(∑ M, p M*(a M)^2) := by + dsimp [r] + simp_rw [add_mul, mul_assoc t, Finset.sum_add_distrib, ← Finset.mul_sum] + rw [hcenter, zero_add] + congr 1 + apply Finset.sum_congr rfl + intro M _ + ring + have hlog : (∑ M, r M*Real.log (p M))=c₀+t*c₁ := by + dsimp [r, c₀, c₁] + simp_rw [add_mul, mul_assoc t, Finset.sum_add_distrib, ← Finset.mul_sum] + change maxMatchingEntropy G (G.mean r) ≤ + Real.log (partition p a t) - (∑ M, r M*Real.log (p M)) - t*(∑ M, r M*a M) at hdual + rw [hlog, hscore] at hdual + have hmaxr := hmax (G.mean r) (G.mean_mem_polytope hr) + have hpart := partition_zero hp.1 a + simp only [zero_mul, zero_pow (by omega : 2 ≠ 0), add_zero, hpart, + Real.log_one, sub_zero] + rw [← hopt, entropy_eq p] at hmaxr + rw [← hrmean] + dsimp only [c₀] at * + nlinarith + +theorem objectiveDefect_attains_max (κ : ℝ) (G : LooplessGraph V E) + (heven : Even (Fintype.card V)) (hPM : Nonempty G.Matching) : + ∃ x ∈ G.polytope, ∀ y ∈ G.polytope, + lowerObjective κ y-maxMatchingEntropy G y ≤ lowerObjective κ x-maxMatchingEntropy G x := by + have hs : UpperSemicontinuousOn (fun y => lowerObjective κ y-maxMatchingEntropy G y) + G.polytope := by + simpa only [sub_eq_add_neg, Pi.neg_apply] using + (continuous_lowerObjective κ).continuousOn.upperSemicontinuousOn.add + (maxMatchingEntropy_lowerSemicontinuousOn G heven).neg + have hn : G.polytope.Nonempty := by + obtain ⟨M⟩ := hPM + exact ⟨G.indicator M,subset_convexHull ℝ _ (Set.mem_range_self M)⟩ + exact UpperSemicontinuousOn.exists_isMaxOn hn G.compact_polytope hs + +open Matrix +omit [Fintype V] [DecidableEq V] in + +theorem matching_objective_covariance (κ : ℝ) (G : LooplessGraph V E) {x : E → ℝ} + {p : G.Matching → ℝ} (hp : p ∈ G.feasibleLaws x) + (hopt : entropy p=maxMatchingEntropy G x) + (hmax : ∀ y ∈ G.polytope, lowerObjective κ y-maxMatchingEntropy G y ≤ + lowerObjective κ x-maxMatchingEntropy G x) + (u : {e // 0 < x e} → ℝ) : + u ⬝ᵥ (covariance p (matchingNormalized G x) *ᵥ u) ≤ + ∑ e, (1-κ*x e.val/(1-x e.val))*((covariance p (matchingNormalized G x) *ᵥ u) e)^2 := by + let w := matchingScoreWeights x u + let c := ∑ e, w e*x e + let a := linearScore G w c + let v := G.mean (fun M => p M*a M) + have hx : x ∈ G.polytope := (G.mem_polytope_iff x).mpr ⟨p,hp⟩ + have hcenter : ∑ M, p M*a M=0 := by + dsimp only [a,c] + rw [linearScore_expectation,hp.2,hp.1.2,mul_one,sub_self] + have hh := matching_objective_second_variation κ G hp hopt hmax w c hcenter + have hzero : ∀ e, ¬0 < x e → v e=0 := by + intro e he + have he0 : x e=0 := le_antisymm (le_of_not_gt he) (G.coordinate_mem_Icc hx e).1 + exact mean_score_support G hp.1 a e (by rw [hp.2,he0]) + have hnorm : (∑ e, (v e)^2/x e) = + ∑ e, ((covariance p (matchingNormalized G x) *ᵥ u) e)^2 := by + rw [sum_positive_support x _ (fun e he => by rw [hzero e he]; simp)] + apply Finset.sum_congr rfl + intro e _ + rw [matchingNormalized_mulVec G hp,div_pow,Real.sq_sqrt e.property.le] + have hbar : (∑ e, (v e)^2/(1-x e)) = + ∑ e, x e.val/(1-x e.val)*((covariance p (matchingNormalized G x) *ᵥ u) e)^2 := by + rw [sum_positive_support x _ (fun e he => by rw [hzero e he]; simp)] + apply Finset.sum_congr rfl + intro e _ + rw [matchingNormalized_mulVec G hp,div_pow,Real.sq_sqrt e.property.le] + change (v e.val)^2/(1-x e.val)=x e.val/(1-x e.val)*((v e.val)^2/x e.val) + field_simp [ne_of_gt e.property] + have hquad : (∑ M, p M*(a M)^2)=u ⬝ᵥ (covariance p (matchingNormalized G x) *ᵥ u) := by + rw [covariance_quadratic hp.1.1] + apply Finset.sum_congr rfl + intro M _ + rw [← matchingNormalized_score G x u M] + change -(∑ e, (v e)^2/x e)+κ*(∑ e, (v e)^2/(1-x e))+(∑ M,p M*(a M)^2) ≤ 0 at hh + rw [hnorm,hbar,hquad] at hh + have heq : (∑ e, (1-κ*x e.val/(1-x e.val))*((covariance p (matchingNormalized G x) *ᵥ u) e)^2) = + (∑ e, ((covariance p (matchingNormalized G x) *ᵥ u) e)^2)- + κ*(∑ e, x e.val/(1-x e.val)*((covariance p (matchingNormalized G x) *ᵥ u) e)^2) := by + simp_rw [sub_mul,one_mul,Finset.sum_sub_distrib,Finset.mul_sum] + congr 1 + apply Finset.sum_congr rfl + intro e _ + ring + rw [heq] + linarith + +omit [Fintype V] in + +theorem lowerObjective_forced (κ : ℝ) (G : LooplessGraph V E) {x : E → ℝ} + (hx : x ∈ G.polytope) (e₀ : E) (he : x e₀=1) : + lowerObjective κ (fun e : {e // G.RemainingEdge e₀ e} => x e.val)=lowerObjective κ x := by + have hz : ∀ e, ¬G.RemainingEdge e₀ e → + Real.negMulLog (x e)=0 ∧ Real.negMulLog (1-x e)=0 := by + intro e h + by_cases hneq : e=e₀ + · simp [hneq,he] + · simp [G.forced_coordinate_zero hx e₀ he hneq h] + unfold lowerObjective complementEntropy entropy + rw [sum_subtype_supported _ _ (fun e h => (hz e h).1), + sum_subtype_supported _ _ (fun e h => (hz e h).2)] + +theorem objective_max_has_forced (κ : ℝ) (G : LooplessGraph V E) {x : E → ℝ} + (heven : Even (Fintype.card V)) (hn : 0 < Fintype.card V) (hx : x ∈ G.polytope) + (hκ : (2 - κ) * (Fintype.card V : ℝ) < 4) + (hmax : ∀ y ∈ G.polytope, lowerObjective κ y - maxMatchingEntropy G y ≤ + lowerObjective κ x - maxMatchingEntropy G x) : ∃ e, x e = 1 := by + by_contra hforced + push Not at hforced + obtain ⟨m, hm⟩ := heven + have hV : Fintype.card V = 2 * m := by omega + have hmpos : 0 < m := by omega + have heven : Even (Fintype.card V) := ⟨m, hm⟩ + obtain ⟨p, hp, hopt⟩ := maxMatchingEntropy_attained G hx + have hsecond := covariance_weighted_rank (covariance_posSemidef p (matchingNormalized G x)) + (fun e => 1 - κ * x e.val / (1 - x e.val)) (matching_objective_covariance κ G hp hopt hmax) + have htrace : (∑ e : {e // 0 < x e}, (1 - κ * x e.val / (1 - x e.val)) * + covariance p (matchingNormalized G x) e e) = + Fintype.card {e // 0 < x e} - (κ + 1) * (m : ℝ) := by + have he (e : {e // 0 < x e}) : (1 - κ * x e.val / (1 - x e.val)) * + covariance p (matchingNormalized G x) e e = 1 - (κ + 1) * x e.val := by + rw [matching_covariance_diagonal G hp] + have hh : 1 - x e.val ≠ 0 := sub_ne_zero.mpr (Ne.symm (hforced e.val)) + field_simp + ring + simp_rw [he] + rw [Finset.sum_sub_distrib, ← Finset.mul_sum] + have hs : (∑ e : {e // 0 < x e}, x e.val) = (m : ℝ) := by + rw [← G.marginal_sum hV hx] + exact (sum_positive_support x x (fun e he => + le_antisymm (le_of_not_gt he) (G.coordinate_mem_Icc hx e).1)).symm + rw [hs] + simp + rw [htrace] at hsecond + have hrank := matching_covariance_rank_face G heven hp hopt + have hsharp := sharp_face_rank G m hmpos hV hx + have hrankR : (Fintype.card {e // 0 < x e} : ℝ) ≤ G.faceCodimension x + + (covariance p (matchingNormalized G x)).rank := by exact_mod_cast hrank + have hsharpR : (G.faceCodimension x : ℝ) + 2 ≤ 3 * (m : ℝ) := by exact_mod_cast hsharp + rw [hV, Nat.cast_mul, Nat.cast_ofNat] at hκ + nlinarith + +theorem coefficient_down (κ : ℝ) {n k : ℕ} (hk : k ≤ n) + (hn : (2 - κ) * (n : ℝ) < 4) : (2 - κ) * (k : ℝ) < 4 := by + by_cases hc : 0 ≤ 2 - κ + · exact lt_of_le_of_lt (mul_le_mul_of_nonneg_left (by exact_mod_cast hk) hc) hn + · have hneg := mul_nonpos_of_nonpos_of_nonneg (le_of_not_ge hc) (Nat.cast_nonneg k : (0:ℝ) ≤ k) + linarith + +theorem strict_lower_aux (κ : ℝ) (n : ℕ) : + ∀ {V : Type uV} {E : Type uE} [Fintype V] [Fintype E] [DecidableEq V] [DecidableEq E] + (G : LooplessGraph V E), Fintype.card V = n → Even n → + (2 - κ) * (n : ℝ) < 4 → + ∀ x ∈ G.polytope, lowerObjective κ x ≤ maxMatchingEntropy G x := by + induction n using Nat.strong_induction_on with + | h n ih => + intro V E _ _ _ _ G hcard heven hκ y hy + by_cases hn : n = 0 + · have : IsEmpty V := Fintype.card_eq_zero_iff.mp (hcard.trans hn) + have : IsEmpty E := ⟨fun e => isEmptyElim (G.left e)⟩ + simpa [lowerObjective, complementEntropy, entropy] using maxMatchingEntropy_nonneg G hy + · have heven' : Even (Fintype.card V) := hcard ▸ heven + have hPM : Nonempty G.Matching := by + obtain ⟨p,hp⟩ := (G.mem_polytope_iff y).mp hy + by_contra h + have : IsEmpty G.Matching := not_nonempty_iff.mp h + simpa using hp.1.2 + obtain ⟨x, hx, hmax⟩ := objectiveDefect_attains_max κ G heven' hPM + obtain ⟨e₀, he₀⟩ := objective_max_has_forced κ G heven' (by omega) hx (hcard ▸ hκ) hmax + have hc := G.remaining_vertex_card e₀ + have hlt : Fintype.card {v // G.RemainingVertex e₀ v} < n := by omega + have hev : Even (Fintype.card {v // G.RemainingVertex e₀ v}) := by + obtain ⟨r,hr⟩ := heven + refine ⟨r-1,?_⟩ + omega + obtain ⟨p,hp⟩ := (G.mem_polytope_iff x).mp hx + have hs := G.forcedLaw_feasible hp e₀ he₀ + have hxr := ((G.deleteEndpoints e₀).mem_polytope_iff _).mpr ⟨_,hs⟩ + have hsmall := ih _ hlt (G.deleteEndpoints e₀) rfl hev (coefficient_down κ hlt.le hκ) _ hxr + rw [lowerObjective_forced κ G hx e₀ he₀] at hsmall + have hxbound := hsmall.trans (G.maxMatchingEntropy_forced_le hx e₀ he₀) + have hcompare := hmax y hy + linarith + +theorem refined_lower (G : LooplessGraph V E) (m : ℕ) + (hm : 0 < m) (hV : Fintype.card V = 2 * m) (x : E → ℝ) (hx : x ∈ G.polytope) : + lowerObjective (2 - 2 / (m : ℝ)) x ≤ maxMatchingEntropy G x := by + let c : ℝ := 2 - 2 / (m : ℝ) + have hcont : Continuous (fun κ : ℝ => lowerObjective κ x) := by + unfold lowerObjective + fun_prop + apply le_of_tendsto (hcont.continuousAt.tendsto.mono_left nhdsWithin_le_nhds : + Tendsto (fun κ : ℝ => lowerObjective κ x) (𝓝[>] c) (𝓝 (lowerObjective c x))) + filter_upwards [self_mem_nhdsWithin] with κ hκ + have hκc : c < κ := hκ + have hmR : (0 : ℝ) < m := by exact_mod_cast hm + have hc : (2 - c) * (2 * (m : ℝ)) = 4 := by + dsimp [c] + field_simp + ring + have hstrict : (2 - κ) * (Fintype.card V : ℝ) < 4 := by + rw [hV, Nat.cast_mul, Nat.cast_ofNat] + nlinarith [mul_lt_mul_of_pos_right hκc (by positivity : 0 < 2 * (m : ℝ))] + exact strict_lower_aux κ (Fintype.card V) G rfl (by rw [hV]; exact even_two_mul m) hstrict x hx + +def matchingProduct (G : LooplessGraph V E) (x : E → ℝ) (M : G.Matching) : ℝ := + ∏ e ∈ M.val, x e + +omit [Fintype V] [Fintype E] [DecidableEq V] [DecidableEq E] in +theorem matchingProduct_nonneg (G : LooplessGraph V E) {x : E → ℝ} + (hx : ∀ e, 0 ≤ x e) (M : G.Matching) : 0 ≤ matchingProduct G x M := + Finset.prod_nonneg (fun e _ => hx e) + +omit [Fintype V] [Fintype E] in +theorem matchingProduct_addForced (G : LooplessGraph V E) (x : E → ℝ) (e₀ : E) + (N : (G.deleteEndpoints e₀).Matching) : + matchingProduct G x (G.addForced e₀ N) = + x e₀ * matchingProduct (G.deleteEndpoints e₀) (fun e => x e.val) N := by + have hnot : e₀ ∉ N.val.image Subtype.val := by + rintro h + obtain ⟨e, _, he⟩ := Finset.mem_image.mp h + exact G.remainingEdge_ne e₀ e.property he + change (∏ e ∈ insert e₀ (N.val.image Subtype.val), x e) = _ + rw [Finset.prod_insert hnot, Finset.prod_image (fun _ _ _ _ h => Subtype.ext h)] + rfl + +omit [Fintype V] in +theorem sum_matching_incident (G : LooplessGraph V E) (w : G.Matching → ℝ) (v : V) : + (∑ M, w M) = ∑ e, if G.Incident v e then ∑ M : {M : G.Matching // e ∈ M.val}, w M.val else 0 := by + have hone (M : G.Matching) : (∑ e, if G.Incident v e ∧ e ∈ M.val then w M else 0) = w M := by + obtain ⟨e, ⟨he, hev⟩, huniq⟩ := M.property v + rw [Finset.sum_eq_single e] + · simp [he, hev] + · intro f _ hne + have hf : ¬ (G.Incident v f ∧ f ∈ M.val) := by + rintro ⟨hfv, hfM⟩ + exact hne (huniq f ⟨hfM, hfv⟩) + simp [hf] + · simp + calc + _ = ∑ M, ∑ e, if G.Incident v e ∧ e ∈ M.val then w M else 0 := by simp_rw [hone] + _ = _ := by + rw [Finset.sum_comm] + apply Finset.sum_congr rfl + intro e _ + by_cases he : G.Incident v e + · simp only [he, true_and, ite_true] + have hh := (sum_subtype_supported (fun M : G.Matching => e ∈ M.val) + (fun M => if e ∈ M.val then w M else 0) (by intro M h; simp [h])).symm + apply hh.trans + apply Finset.sum_congr rfl + intro M _ + exact ite_eq_left M.property + · simp [he] + +omit [Fintype V] in +theorem matchingProduct_recursion (G : LooplessGraph V E) (x : E → ℝ) (v : V) : + (∑ M, matchingProduct G x M) = + ∑ e, if G.Incident v e then x e * + ∑ N, matchingProduct (G.deleteEndpoints e) (fun f => x f.val) N else 0 := by + rw [sum_matching_incident G _ v] + apply Finset.sum_congr rfl + intro e _ + by_cases he : G.Incident v e + · simp only [he, ite_true] + rw [← (G.forcedMatchingEquiv e).sum_comp (fun M => matchingProduct G x M.val)] + change (∑ N, matchingProduct G x (G.addForced e N)) = _ + simp_rw [matchingProduct_addForced] + rw [Finset.mul_sum] + · simp [he] + +omit [Fintype V] [DecidableEq E] in +theorem degree_deleteEndpoints_le (G : LooplessGraph V E) {x : E → ℝ} + (hx : ∀ e, 0 ≤ x e) (e₀ : E) (v : {v // G.RemainingVertex e₀ v}) : + (G.deleteEndpoints e₀).degree (fun e => x e.val) v ≤ G.degree x v.val := by + simp only [degree, deleteEndpoints_incident] + rw [← Finset.sum_subtype (Finset.univ.filter (G.RemainingEdge e₀)) (by simp) + (fun e => if G.Incident v.val e then x e else 0)] + apply Finset.sum_le_sum_of_subset_of_nonneg (Finset.filter_subset _ _) + intro e _ _ + split + · exact hx e + · exact le_rfl + +theorem matchingProduct_sum_le_aux (n : ℕ) : + ∀ {V : Type uV} {E : Type uE} [Fintype V] [Fintype E] [DecidableEq V] [DecidableEq E] + (G : LooplessGraph V E), Fintype.card V = n → + ∀ x : E → ℝ, (∀ e, 0 ≤ x e) → (∀ v, G.degree x v ≤ 1) → + (∑ M, matchingProduct G x M) ≤ 1 := by + induction n using Nat.strong_induction_on with + | h n ih => + intro V E _ _ _ _ G hcard x hx hd + by_cases hn : n = 0 + · have : IsEmpty V := Fintype.card_eq_zero_iff.mp (hcard.trans hn) + have : IsEmpty E := ⟨fun e => isEmptyElim (G.left e)⟩ + have hM : Fintype.card G.Matching ≤ 1 := Fintype.card_le_one_iff_subsingleton.mpr inferInstance + have heach (M : G.Matching) : matchingProduct G x M = 1 := by + rw [matchingProduct, Finset.eq_empty_of_isEmpty M.val, Finset.prod_empty] + simp_rw [heach] + simpa using (show (Fintype.card G.Matching : ℝ) ≤ 1 by exact_mod_cast hM) + · have : Nonempty V := Fintype.card_pos_iff.mp (by omega) + obtain ⟨v⟩ := this + rw [matchingProduct_recursion G x v] + calc + _ ≤ ∑ e, if G.Incident v e then x e else 0 := by + apply Finset.sum_le_sum + intro e _ + split + · have hc := G.remaining_vertex_card e + have hlt : Fintype.card {v // G.RemainingVertex e v} < n := by omega + have hb := ih _ hlt (G.deleteEndpoints e) rfl (fun f => x f.val) + (fun f => hx f.val) (fun v => (degree_deleteEndpoints_le G hx e v).trans (hd v.val)) + simpa only [mul_one] using mul_le_mul_of_nonneg_left hb (hx e) + · exact le_rfl + _ ≤ 1 := hd v + +theorem matchingProduct_sum_le (G : LooplessGraph V E) {x : E → ℝ} (hx : x ∈ G.polytope) : + (∑ M, matchingProduct G x M) ≤ 1 := by + have hc := G.polytope_subset_constraintPolytope hx + exact matchingProduct_sum_le_aux (Fintype.card V) G rfl x hc.1 (fun v => (hc.2.1 v).le) + +theorem matching_entropy_le_F (G : LooplessGraph V E) {x : E → ℝ} + {p : G.Matching → ℝ} (hp : p ∈ G.feasibleLaws x) : entropy p ≤ entropy x := by + have hx : x ∈ G.polytope := (G.mem_polytope_iff x).mpr ⟨p, hp⟩ + have hfactor (M : G.Matching) (hM : 0 < p M) (e : E) (he : e ∈ M.val) : 0 < x e := by + simpa [LooplessGraph.matchingBits, he] using matching_boolean_factor_pos G hp hM e + have hprod (M : G.Matching) (hM : 0 < p M) : 0 < matchingProduct G x M := + Finset.prod_pos (fun e he => hfactor M hM e he) + have hcross := entropy_le_subprob_crossEntropy + (fun M => matchingProduct_nonneg G (fun e => (G.coordinate_mem_Icc hx e).1) M) + (matchingProduct_sum_le G hx) hp.1 + (fun M hzero => le_antisymm (le_of_not_gt (fun hM => (ne_of_gt (hprod M hM)) hzero)) (hp.1.1 M)) + have hlog (M : G.Matching) : p M * Real.log (matchingProduct G x M) = + ∑ e, (p M * G.indicator M e) * Real.log (x e) := by + by_cases hzero : p M = 0 + · simp [hzero] + · have hpos : 0 < p M := lt_of_le_of_ne (hp.1.1 M) (Ne.symm hzero) + rw [matchingProduct, Real.log_prod (fun e he => ne_of_gt (hfactor M hpos e he)), Finset.mul_sum] + simp only [LooplessGraph.indicator, mul_ite, mul_one, mul_zero, ite_mul, zero_mul] + rw [← Finset.sum_filter] + simp + have heq : -(∑ M, p M * Real.log (matchingProduct G x M)) = entropy x := by + simp_rw [hlog] + rw [Finset.sum_comm, entropy_eq] + congr 1 + apply Finset.sum_congr rfl + intro e _ + rw [← Finset.sum_mul] + have he : (∑ M, p M * G.indicator M e) = x e := congrFun hp.2 e + rw [he] + rwa [heq] at hcross + +theorem refined_upper (G : LooplessGraph V E) (x : E → ℝ) (hx : x ∈ G.polytope) : + maxMatchingEntropy G x ≤ entropy x := by + obtain ⟨p, hp, hopt⟩ := maxMatchingEntropy_attained G hx + rw [← hopt] + exact matching_entropy_le_F G hp + +end MatchingEntropyBounds.Refined + +end + +end OAI diff --git a/lean/OAI/Combinatorics/MatchingEntropy/SeparableBound.lean b/lean/OAI/Combinatorics/MatchingEntropy/SeparableBound.lean new file mode 100644 index 0000000000000000000000000000000000000000..8ee9e3dfdf8b5618d910223967c98f2efd635a15 --- /dev/null +++ b/lean/OAI/Combinatorics/MatchingEntropy/SeparableBound.lean @@ -0,0 +1,60 @@ +import OAI.Combinatorics.MatchingEntropy.EdgeReduction + +namespace OAI + +noncomputable section + +open scoped BigOperators Topology +open Filter + +universe uV uE uI uJ uA uB uC uW uF uD uι + +namespace MatchingEntropyBounds + +theorem separable_lower_aux (n : ℕ) : + ∀ {V : Type uV} {E : Type uE} [Fintype V] [Fintype E] [DecidableEq V] [DecidableEq E] + (G : LooplessGraph V E), Fintype.card V=n → Even n → + ∀ x ∈ G.polytope, separableLower x ≤ maxMatchingEntropy G x := by + induction n using Nat.strong_induction_on with + | h n ih => + intro V E _ _ _ _ G hcard heven y hy + by_cases hn : n=0 + · have : IsEmpty V := Fintype.card_eq_zero_iff.mp (hcard.trans hn) + have : IsEmpty E := ⟨fun e => isEmptyElim (G.left e)⟩ + simpa [separableLower,entropy] using maxMatchingEntropy_nonneg G hy + · have heven' : Even (Fintype.card V) := hcard ▸ heven + have hPM : Nonempty G.Matching := by + obtain ⟨p,hp⟩ := (G.mem_polytope_iff y).mp hy + by_contra h + have : IsEmpty G.Matching := not_nonempty_iff.mp h + simpa using hp.1.2 + obtain ⟨x,hx,hmax⟩ := separableDefect_attains_max G heven' hPM + obtain ⟨e₀,he₀⟩ := separable_max_has_forced G heven' (by omega) hx hmax + have hc := G.remaining_vertex_card e₀ + have hlt : Fintype.card {v // G.RemainingVertex e₀ v} separableLower y-maxMatchingEntropy G y) + G.polytope := by + simpa only [sub_eq_add_neg, Pi.neg_apply] using + continuous_separableLower.continuousOn.upperSemicontinuousOn.add + (maxMatchingEntropy_lowerSemicontinuousOn G heven).neg + have hn : G.polytope.Nonempty := by + obtain ⟨M⟩ := hPM + exact ⟨G.indicator M,subset_convexHull ℝ _ (Set.mem_range_self M)⟩ + exact UpperSemicontinuousOn.exists_isMaxOn hn G.compact_polytope hs + +theorem matching_covariance_rank_face (G : LooplessGraph V E) {x : E → ℝ} + (heven : Even (Fintype.card V)) {p : G.Matching → ℝ} + (hp : p ∈ G.feasibleLaws x) (hopt : entropy p=maxMatchingEntropy G x) : + Fintype.card {e // 0 < x e} ≤ G.faceCodimension x+ + (covariance p (matchingNormalized G x)).rank := by + let W := weightedDirectionSpace p (matchingNormalized G x) + let L : G.faceSpace x →ₗ[ℝ] W := + ((normalizeLinear x).comp (G.faceSpace x).subtype).codRestrict W + (fun u => normalized_face_mem G heven hp hopt u.property) + have hi : Function.Injective L := by + intro u v huv + apply Subtype.ext + funext e + have hh := congrFun (congrArg Subtype.val huv) e + change u.val e/Real.sqrt (x e.val)=v.val e/Real.sqrt (x e.val) at hh + exact (div_left_inj' (ne_of_gt (Real.sqrt_pos.mpr e.property))).mp hh + have hdim := LinearMap.finrank_le_finrank_of_injective hi + have hq := (G.faceSpace x).finrank_quotient_add_finrank + rw [covariance_rank hp.1.1] + have hq' : G.faceCodimension x+Module.finrank ℝ (G.faceSpace x)=Fintype.card {e // 0 < x e} := by + simpa only [LooplessGraph.faceCodimension,Module.finrank_pi,Module.finrank_self,Finset.sum_const, + Finset.card_univ,smul_eq_mul,mul_one] using hq + change Module.finrank ℝ (G.faceSpace x) ≤ Module.finrank ℝ W at hdim + dsimp only [W] at hdim + omega + +theorem faceCodimension_strict (G : LooplessGraph V E) {x : E → ℝ} + (heven : Even (Fintype.card V)) (hn : 0 < Fintype.card V) (hx : x ∈ G.polytope) : + G.faceCodimension x < 2*Fintype.card V := by + by_cases hn4 : 4 ≤ Fintype.card V + · have hb := LooplessGraph.faceCodimension_strong_aux (Fintype.card V) G rfl heven hn4 x + (G.polytope_subset_constraintPolytope hx) + omega + · have hnt : ¬∃ S : Finset V, Odd S.card ∧ 3≤S.card ∧ 3≤Sᶜ.card ∧ G.cutMass x S=1 := by + rintro ⟨S,_,hlo,hhi,_⟩ + have hh := Finset.card_compl_add_card S + omega + have hb := G.faceCodimension_no_tight heven hnt + omega + +omit [Fintype V] [DecidableEq V] in + +theorem matching_separable_covariance (G : LooplessGraph V E) {x : E → ℝ} + {p : G.Matching → ℝ} (hp : p ∈ G.feasibleLaws x) + (hopt : entropy p=maxMatchingEntropy G x) + (hmax : ∀ y ∈ G.polytope, separableLower y-maxMatchingEntropy G y ≤ + separableLower x-maxMatchingEntropy G x) + (u : {e // 0 < x e} → ℝ) : + u ⬝ᵥ (covariance p (matchingNormalized G x) *ᵥ u) ≤ + ∑ e, (1-3*x e.val/(1-x e.val))*((covariance p (matchingNormalized G x) *ᵥ u) e)^2 := by + let w := matchingScoreWeights x u + let c := ∑ e, w e*x e + let a := linearScore G w c + let v := G.mean (fun M => p M*a M) + have hx : x ∈ G.polytope := (G.mem_polytope_iff x).mpr ⟨p,hp⟩ + have hcenter : ∑ M, p M*a M=0 := by + dsimp only [a,c] + rw [linearScore_expectation,hp.2,hp.1.2,mul_one,sub_self] + have hh := matching_separable_second_variation G hp hopt hmax w c hcenter + have hzero : ∀ e, ¬0 < x e → v e=0 := by + intro e he + have he0 : x e=0 := le_antisymm (le_of_not_gt he) (G.coordinate_mem_Icc hx e).1 + exact mean_score_support G hp.1 a e (by rw [hp.2,he0]) + have hnorm : (∑ e, (v e)^2/x e) = + ∑ e, ((covariance p (matchingNormalized G x) *ᵥ u) e)^2 := by + rw [sum_positive_support x _ (fun e he => by rw [hzero e he]; simp)] + apply Finset.sum_congr rfl + intro e _ + rw [matchingNormalized_mulVec G hp,div_pow,Real.sq_sqrt e.property.le] + have hbar : (∑ e, (v e)^2/(1-x e)) = + ∑ e, x e.val/(1-x e.val)*((covariance p (matchingNormalized G x) *ᵥ u) e)^2 := by + rw [sum_positive_support x _ (fun e he => by rw [hzero e he]; simp)] + apply Finset.sum_congr rfl + intro e _ + rw [matchingNormalized_mulVec G hp,div_pow,Real.sq_sqrt e.property.le] + change (v e.val)^2/(1-x e.val)=x e.val/(1-x e.val)*((v e.val)^2/x e.val) + field_simp [ne_of_gt e.property] + have hquad : (∑ M, p M*(a M)^2)=u ⬝ᵥ (covariance p (matchingNormalized G x) *ᵥ u) := by + rw [covariance_quadratic hp.1.1] + apply Finset.sum_congr rfl + intro M _ + rw [← matchingNormalized_score G x u M] + change -(∑ e, (v e)^2/x e)+3*(∑ e, (v e)^2/(1-x e))+(∑ M,p M*(a M)^2) ≤ 0 at hh + rw [hnorm,hbar,hquad] at hh + have heq : (∑ e, (1-3*x e.val/(1-x e.val))*((covariance p (matchingNormalized G x) *ᵥ u) e)^2) = + (∑ e, ((covariance p (matchingNormalized G x) *ᵥ u) e)^2)- + 3*(∑ e, x e.val/(1-x e.val)*((covariance p (matchingNormalized G x) *ᵥ u) e)^2) := by + simp_rw [sub_mul,one_mul,Finset.sum_sub_distrib,Finset.mul_sum] + congr 1 + apply Finset.sum_congr rfl + intro e _ + ring + rw [heq] + linarith + +omit [Fintype V] [DecidableEq V] in +theorem matching_covariance_diagonal (G : LooplessGraph V E) {x : E → ℝ} + {p : G.Matching → ℝ} (hp : p ∈ G.feasibleLaws x) (e : {e // 0 G.indicator M e.val) + (by intro M e; simp only [LooplessGraph.indicator]; split <;> norm_num) + (fun e => x e.val) (fun e => congrFun hp.2 e.val) (fun e => e.property) e + convert hh using 1 + apply Finset.sum_congr rfl + intro M _ + change p M*matchingNormalized G x M e*matchingNormalized G x M e= + p M*(matchingNormalized G x M e)^2 + ring + +theorem separable_max_has_forced (G : LooplessGraph V E) {x : E → ℝ} + (heven : Even (Fintype.card V)) (hn : 0 < Fintype.card V) (hx : x ∈ G.polytope) + (hmax : ∀ y ∈ G.polytope, separableLower y-maxMatchingEntropy G y ≤ + separableLower x-maxMatchingEntropy G x) : ∃ e, x e=1 := by + by_contra hforced + push Not at hforced + obtain ⟨p,hp,hopt⟩ := maxMatchingEntropy_attained G hx + have hsecond := covariance_weighted_rank (covariance_posSemidef p (matchingNormalized G x)) + (fun e => 1-3*x e.val/(1-x e.val)) (matching_separable_covariance G hp hopt hmax) + have htrace : (∑ e : {e // 0 + le_antisymm (le_of_not_gt he) (G.coordinate_mem_Icc hx e).1)).symm + rw [hs,hv] + simp only [Finset.sum_const,Finset.card_univ,nsmul_eq_mul,mul_one,Nat.cast_mul,Nat.cast_ofNat] + ring + rw [htrace] at hsecond + have hrank := matching_covariance_rank_face G heven hp hopt + have hstrict := faceCodimension_strict G heven hn hx + have hrankR : (Fintype.card {e // 0 1 - x e) + +def separableLower (x : E → ℝ) : ℝ := entropy x - 3 * entropy (fun e => 1 - x e) + +def structuralBase (k : ℕ) : ℝ := + if k = 1 then 1 else (k : ℝ) * (1 - 1 / (k : ℝ)) ^ (3 * (k - 1)) + +omit [Fintype V] [DecidableEq V] [DecidableEq E] in +theorem continuous_separableLower : Continuous (separableLower (E := E)) := by + exact continuous_entropy.sub (continuous_const.mul (continuous_entropy.comp (by fun_prop))) + +def separableLineD (x v : E → ℝ) (t : ℝ) : ℝ := + entropyLineD x v t - 3 * entropyLineD (fun e => 1-x e) (fun e => -v e) t + +omit [Fintype V] [DecidableEq V] [DecidableEq E] in +theorem separable_line_eventually_hasDerivAt (x v : E → ℝ) + (hzero : ∀ e, x e = 0 → v e = 0) (hone : ∀ e, x e = 1 → v e = 0) : + ∀ᶠ t : ℝ in 𝓝 0, + HasDerivAt (fun t => separableLower (fun e => x e+t*v e)) + (separableLineD x v t) t := by + have hbar : ∀ e, 1-x e=0 → -v e=0 := by + intro e he + rw [hone e (by linarith), neg_zero] + filter_upwards [entropy_line_eventually_hasDerivAt x v hzero, + entropy_line_eventually_hasDerivAt (fun e => 1-x e) (fun e => -v e) hbar] + with t ht hb + have he : (fun t => separableLower (fun e => x e+t*v e)) = + (fun t => entropy (fun e => x e+t*v e) - + 3 * entropy (fun e => (1-x e)+t*(-v e))) := by + funext t + unfold separableLower + congr 2 + congr 1 + funext e + ring + rw [he] + exact ht.sub (hb.const_mul 3) + +omit [Fintype V] [DecidableEq V] [DecidableEq E] in +theorem separableLineD_hasDerivAt (x v : E → ℝ) + (hzero : ∀ e, x e = 0 → v e = 0) (hone : ∀ e, x e = 1 → v e = 0) : + HasDerivAt (separableLineD x v) + (-(∑ e, (v e)^2/x e) + 3*(∑ e, (v e)^2/(1-x e))) 0 := by + have hbar : ∀ e, 1-x e=0 → -v e=0 := by + intro e he + rw [hone e (by linarith), neg_zero] + have hd := (entropyLineD_hasDerivAt x v hzero).sub + ((entropyLineD_hasDerivAt (fun e => 1-x e) (fun e => -v e) hbar).const_mul 3) + exact hd.congr_deriv (by simp only [neg_sq]; ring) + +omit [Fintype V] [DecidableEq V] [DecidableEq E] in +theorem separable_second_variation {A : Type uA} [Fintype A] + (x v : E → ℝ) (hzero : ∀ e, x e=0 → v e=0) (hone : ∀ e, x e=1 → v e=0) + {p : A → ℝ} (hp : p ∈ probabilitySimplex A) (a : A → ℝ) + (hcenter : ∑ i, p i*a i=0) (c₀ c₁ : ℝ) + (hlocal : IsLocalMax (fun t => separableLower (fun e => x e+t*v e) + + c₀+t*c₁+t^2*(∑ i, p i*(a i)^2)-Real.log (partition p a t)) 0) : + -(∑ e, (v e)^2/x e) + 3*(∑ e, (v e)^2/(1-x e)) + + (∑ i, p i*(a i)^2) ≤ 0 := by + have hf := separable_line_eventually_hasDerivAt x v hzero hone + have hg : ∀ᶠ t : ℝ in 𝓝 0, HasDerivAt (fun t => Real.log (partition p a t)) + (partition (fun i => p i*a i) a t / partition p a t) t := + Filter.Eventually.of_forall (logPartition_hasDerivAt hp a) + have hd := second_deriv_quadratic_adjustment (c₀ := c₀) (c₁ := c₁) + (v := ∑ i, p i*(a i)^2) hf hg (separableLineD_hasDerivAt x v hzero hone) + (logPartition_second hp a) + have hc : ContinuousAt (fun t => separableLower (fun e => x e+t*v e) + + c₀+t*c₁+t^2*(∑ i, p i*(a i)^2)-Real.log (partition p a t)) 0 := by + apply ContinuousAt.sub + · apply ContinuousAt.add + · apply ContinuousAt.add + · exact hf.self_of_nhds.continuousAt.add_const c₀ + · fun_prop + · fun_prop + · exact hg.self_of_nhds.continuousAt + have hh := second_deriv_nonpos_of_local_max hlocal hc + rw [hd.deriv, hcenter] at hh + nlinarith + +omit [Fintype V] [DecidableEq V] in +theorem mean_score_one (G : LooplessGraph V E) {p : G.Matching → ℝ} + (hp : p ∈ probabilitySimplex G.Matching) (a : G.Matching → ℝ) + (hcenter : ∑ M, p M*a M=0) : + ∀ e, G.mean p e=1 → G.mean (fun M => p M*a M) e=0 := by + intro e he + have hz : ∑ M, p M*(1-G.indicator M e)=0 := by + simp only [mul_sub, mul_one, Finset.sum_sub_distrib, hp.2] + change 1-G.mean p e=0 + rw [he, sub_self] + have hterms : ∀ M, p M*(1-G.indicator M e)=0 := by + exact fun M => (Finset.sum_eq_zero_iff_of_nonneg + (fun M (_ : M ∈ Finset.univ) => + mul_nonneg (hp.1 M) (sub_nonneg.mpr (G.indicator_le_one M e)))).mp hz M (by simp) + calc + _ = ∑ M, p M*a M := by + apply Finset.sum_congr rfl + intro M _ + have hh := hterms M + have hh' : a M*(p M*(1-G.indicator M e))=0 := by rw [hh, mul_zero] + nlinarith [hh'] + _ = 0 := hcenter + +omit [Fintype V] [DecidableEq V] in + +theorem matching_separable_second_variation (G : LooplessGraph V E) {x : E → ℝ} + {p : G.Matching → ℝ} (hp : p ∈ G.feasibleLaws x) + (hopt : entropy p=maxMatchingEntropy G x) + (hmax : ∀ y ∈ G.polytope, separableLower y-maxMatchingEntropy G y ≤ + separableLower x-maxMatchingEntropy G x) + (u : E → ℝ) (c : ℝ) (hcenter : ∑ M, p M*linearScore G u c M=0) : + -(∑ e, (G.mean (fun M => p M*linearScore G u c M) e)^2/x e) + + 3*(∑ e, (G.mean (fun M => p M*linearScore G u c M) e)^2/(1-x e)) + + (∑ M, p M*(linearScore G u c M)^2) ≤ 0 := by + let a := linearScore G u c + let v := G.mean (fun M => p M*a M) + let c₀ := ∑ M, p M*Real.log (p M) + let c₁ := ∑ M, (p M*a M)*Real.log (p M) + have hzero : ∀ e, x e=0 → v e=0 := by + rw [← hp.2] + exact mean_score_support G hp.1 a + have hone : ∀ e, x e=1 → v e=0 := by + rw [← hp.2] + exact mean_score_one G hp.1 a hcenter + apply separable_second_variation x v hzero hone hp.1 a hcenter c₀ c₁ + filter_upwards [score_law_eventually_simplex hp.1 a hcenter] with t ht + let r := fun M => p M+t*(p M*a M) + have hr : r ∈ probabilitySimplex G.Matching := ht + have hrmean : G.mean r=fun e => x e+t*v e := by + change G.meanLinear (p+t • (fun M => p M*a M)) = _ + rw [map_add, map_smul] + change G.mean p+t • v = _ + rw [hp.2] + rfl + have hdual := matching_entropy_dual_bound G hp hopt hr + (fun M hM => by dsimp [r]; simp [hM]) u c t + have hscore : (∑ M, r M*a M)=t*(∑ M, p M*(a M)^2) := by + dsimp [r] + simp_rw [add_mul, mul_assoc t, Finset.sum_add_distrib, ← Finset.mul_sum] + rw [hcenter, zero_add] + congr 1 + apply Finset.sum_congr rfl + intro M _ + ring + have hlog : (∑ M, r M*Real.log (p M))=c₀+t*c₁ := by + dsimp [r, c₀, c₁] + simp_rw [add_mul, mul_assoc t, Finset.sum_add_distrib, ← Finset.mul_sum] + change maxMatchingEntropy G (G.mean r) ≤ + Real.log (partition p a t) - (∑ M, r M*Real.log (p M)) - t*(∑ M, r M*a M) at hdual + rw [hlog, hscore] at hdual + have hmaxr := hmax (G.mean r) (G.mean_mem_polytope hr) + have hpart := partition_zero hp.1 a + simp only [zero_mul, zero_pow (by omega : 2 ≠ 0), add_zero, hpart, + Real.log_one, sub_zero] + rw [← hopt, entropy_eq p] at hmaxr + rw [← hrmean] + dsimp only [c₀] at * + nlinarith + +end MatchingEntropyBounds + +end + +end OAI diff --git a/lean/OAI/Combinatorics/MatchingEntropy/SharpRank.lean b/lean/OAI/Combinatorics/MatchingEntropy/SharpRank.lean new file mode 100644 index 0000000000000000000000000000000000000000..cc3c518c77b5d7c54d1a44542934ee9e1b5422ed --- /dev/null +++ b/lean/OAI/Combinatorics/MatchingEntropy/SharpRank.lean @@ -0,0 +1,204 @@ +import OAI.Combinatorics.MatchingEntropy.Counting + +namespace OAI + +noncomputable section + +open scoped BigOperators Topology +open Filter Module + +universe uV uE uI uJ uA uB uC uW uF uD uι + +namespace MatchingEntropyBounds.Refined + +section SharedEquation +variable {A : Type uA} {B : Type uB} {C : Type uC} [AddCommGroup A] [AddCommGroup B] [AddCommGroup C] + [Module ℝ A] [Module ℝ B] [Module ℝ C] + [FiniteDimensional ℝ A] [FiniteDimensional ℝ B] [FiniteDimensional ℝ C] + +theorem quotient_finrank_shared (U : Submodule ℝ A) (W : Submodule ℝ B) (Z : Submodule ℝ C) + (f : A →ₗ[ℝ] B) (g : A →ₗ[ℝ] C) + (h : ∀ u, f u ∈ W → g u ∈ Z → u ∈ U) + (l : B →ₗ[ℝ] ℝ) (r : C →ₗ[ℝ] ℝ) (hl : W ≤ l.ker) (hr : Z ≤ r.ker) + (heq : ∀ u, l (f u) = r (g u)) (b : B) (hb : l b ≠ 0) : + finrank ℝ (A ⧸ U) + 1 ≤ finrank ℝ (B ⧸ W) + finrank ℝ (C ⧸ Z) := by + let F := (W.mkQ.comp f).prod (Z.mkQ.comp g) + let L : ((B ⧸ W) × (C ⧸ Z)) →ₗ[ℝ] ℝ := + (W.liftQ l hl).comp (LinearMap.fst ℝ _ _) - + (Z.liftQ r hr).comp (LinearMap.snd ℝ _ _) + have hk : F.ker ≤ U := by + intro u hu + have hh : (W.mkQ (f u), Z.mkQ (g u)) = 0 := hu + apply h u + · simpa using congrArg Prod.fst hh + · simpa using congrArg Prod.snd hh + have hL : ∀ u, F u ∈ L.ker := by + intro u + change l (f u) - r (g u) = 0 + exact sub_eq_zero.mpr (heq u) + let F' := F.codRestrict L.ker hL + have hk' : F'.ker ≤ U := by + intro u hu + apply hk + have hh := congrArg Subtype.val (show F' u = 0 from hu) + exact hh + have hdim := quotient_finrank_le_of_ker_le U F' hk' + have hsum := L.finrank_range_add_finrank_ker + have hpos : 1 ≤ finrank ℝ L.range := by + apply Submodule.one_le_finrank_iff.mpr + intro hh + have hm : L (W.mkQ b, 0) ∈ L.range := ⟨_, rfl⟩ + rw [hh] at hm + have hz : L (W.mkQ b, 0) = 0 := hm + apply hb + simpa [L] using hz + rw [Module.finrank_prod] at hsum + omega +end SharedEquation + +variable {V : Type uV} {E : Type uE} [Fintype V] [Fintype E] [DecidableEq V] [DecidableEq E] + +def lowerObjective (c : ℝ) (x : E → ℝ) : ℝ := entropy x - c * complementEntropy x + +open LooplessGraph + +omit [Fintype V] [Fintype E] [DecidableEq V] [DecidableEq E] in +theorem positiveExtension_self {x : E → ℝ} (hx : ∀ e, 0 ≤ x e) : + positiveExtension x (fun e => x e.val) = x := by + funext e + by_cases he : 0 < x e + · simp [positiveExtension, he] + · simp [positiveExtension, le_antisymm (le_of_not_gt he) (hx e)] + +def boundaryLinear (G : LooplessGraph V E) (x : E → ℝ) (S : Finset V) : + ({e // 0 < G.sideMarginal x S e} → ℝ) →ₗ[ℝ] ℝ := + (LinearMap.proj none).comp + ((G.onSide S).degreeLinear.comp (positiveExtension (G.sideMarginal x S))) + +omit [Fintype V] [DecidableEq E] in +theorem boundaryLinear_restriction (G : LooplessGraph V E) (x : E → ℝ) (S : Finset V) + (u : {e // 0 < x e} → ℝ) : + boundaryLinear G x S (G.sideRestriction x S u) = G.cutMass (positiveExtension x u) S := by + change (G.onSide S).degree (fun e => positiveExtension x u e.val) none = _ + exact G.onSide_degree_none S _ + +omit [Fintype V] [DecidableEq E] in +theorem boundaryLinear_face (G : LooplessGraph V E) (x : E → ℝ) (S : Finset V) : + (G.onSide S).faceSpace (G.sideMarginal x S) ≤ (boundaryLinear G x S).ker := by + intro u hu + exact congrFun hu.1 none + +theorem faceCodimension_le_sides_shared (G : LooplessGraph V E) {x : E → ℝ} + (heven : Even (Fintype.card V)) (hx : x ∈ G.constraintPolytope) + (S : Finset V) (hS : Odd S.card) (ht : G.cutMass x S = 1) : + G.faceCodimension x + 1 ≤ (G.onSide S).faceCodimension (G.sideMarginal x S) + + (G.onSide Sᶜ).faceCodimension (G.sideMarginal x Sᶜ) := by + classical + apply quotient_finrank_shared (G.faceSpace x) + ((G.onSide S).faceSpace (G.sideMarginal x S)) + ((G.onSide Sᶜ).faceSpace (G.sideMarginal x Sᶜ)) + (G.sideRestriction x S) (G.sideRestriction x Sᶜ) + (fun _ => G.faceSpace_of_side_spaces heven hx S hS ht) + (boundaryLinear G x S) (boundaryLinear G x Sᶜ) + (boundaryLinear_face G x S) (boundaryLinear_face G x Sᶜ) + (fun u => by simp only [boundaryLinear_restriction, cutMass, cut_compl]) + (fun e => G.sideMarginal x S e.val) + have hext := positiveExtension_self (x := G.sideMarginal x S) (fun e => hx.1 e.val) + change (G.onSide S).degree + (positiveExtension (G.sideMarginal x S) (fun e => G.sideMarginal x S e.val)) none ≠ 0 + rw [hext, G.onSide_degree_none, ht] + norm_num + +omit [Fintype E] [DecidableEq E] in + +theorem incident_of_card_two (G : LooplessGraph V E) (hV : Fintype.card V = 2) + (v : V) (e : E) : G.Incident v e := by + have hp : ({G.left e, G.right e} : Finset V) = Finset.univ := by + apply Finset.eq_of_subset_of_card_le (Finset.subset_univ _) + simp [hV, G.loopless e] + have hv : v ∈ ({G.left e, G.right e} : Finset V) := hp ▸ Finset.mem_univ v + simpa only [Finset.mem_insert, Finset.mem_singleton, eq_comm, Incident] using hv + +omit [DecidableEq E] in + +theorem faceCodimension_two (G : LooplessGraph V E) (hV : Fintype.card V = 2) + (x : E → ℝ) : G.faceCodimension x ≤ 1 := by + classical + let L : ({e // 0 < x e} → ℝ) →ₗ[ℝ] ℝ := + (Finset.univ.sum (fun e : E => LinearMap.proj e)).comp (positiveExtension x) + have heven : Even (Fintype.card V) := by simp [hV] + have hnt : ¬ ∃ S : Finset V, Odd S.card ∧ 3 ≤ S.card ∧ 3 ≤ Sᶜ.card ∧ G.cutMass x S = 1 := by + rintro ⟨S, _, hlo, _, _⟩ + have hc := Finset.card_le_univ S + omega + have hker : L.ker ≤ G.faceSpace x := by + intro u hu + have hz : ∑ e, positiveExtension x u e = 0 := by simpa [L] using hu + have hd : ∀ v, G.degree (positiveExtension x u) v = 0 := by + intro v + simpa only [degree, incident_of_card_two G hV v, ite_true] using hz + refine ⟨funext hd, ?_⟩ + exact G.trivial_tight_cut_preserved heven hnt _ hd + simpa [faceCodimension] using quotient_finrank_le_of_ker_le (G.faceSpace x) L hker + +theorem sharp_face_rank_aux (n : ℕ) : + ∀ {W : Type uW} {F : Type uF} [Fintype W] [Fintype F] [DecidableEq W] [DecidableEq F] + (G : LooplessGraph W F), Fintype.card W=n → Even n → 4≤n → + ∀ x ∈ G.constraintPolytope, 2 * (G.faceCodimension x + 2) ≤ 3 * n := by + induction n using Nat.strong_induction_on with + | h n ih => + intro W F _ _ _ _ G hcard heven hfour x hx + have heven' : Even (Fintype.card W) := hcard ▸ heven + by_cases hcut : ∃ S : Finset W, Odd S.card ∧ 3≤S.card ∧ 3≤Sᶜ.card ∧ G.cutMass x S=1 + · obtain ⟨S,hS,hlo,hhi,ht⟩ := hcut + have hc := odd_compl_of_even heven' hS + have hlt1 : Fintype.card (Option {v // v ∈ S}) < n := by + simp only [Fintype.card_option,Fintype.card_coe] + have hco := Finset.card_compl S + omega + have hlt2 : Fintype.card (Option {v // v ∈ Sᶜ}) < n := by + simp only [Fintype.card_option,Fintype.card_coe] + have hco := Finset.card_compl S + have hle := Finset.card_le_univ S + omega + have hv1 : Even (Fintype.card (Option {v // v ∈ S})) := by + simpa only [Fintype.card_option,Fintype.card_coe] using hS.add_odd odd_one + have hv2 : Even (Fintype.card (Option {v // v ∈ Sᶜ})) := by + simpa only [Fintype.card_option,Fintype.card_coe] using hc.add_odd odd_one + have hn1 : 4≤Fintype.card (Option {v // v ∈ S}) := by + simp only [Fintype.card_option,Fintype.card_coe]; omega + have hn2 : 4≤Fintype.card (Option {v // v ∈ Sᶜ}) := by + simp only [Fintype.card_option,Fintype.card_coe]; omega + have hx1 := G.restriction_mem_constraints hx S hS ht + have htc : G.cutMass x Sᶜ=1 := by simpa only [cutMass,cut_compl] using ht + have hx2 := G.restriction_mem_constraints hx Sᶜ hc htc + have hb1 := ih _ hlt1 (G.onSide S) rfl hv1 hn1 _ hx1 + have hb2 := ih _ hlt2 (G.onSide Sᶜ) rfl hv2 hn2 _ hx2 + have hb := faceCodimension_le_sides_shared G heven' hx S hS ht + have hsum : Fintype.card (Option {v // v ∈ S}) + Fintype.card (Option {v // v ∈ Sᶜ})=n+2 := by + simp only [Fintype.card_option,Fintype.card_coe] + have hh := Finset.card_compl_add_card S + omega + change 2 * ((G.onSide S).faceCodimension (G.sideMarginal x S) + 2) ≤ _ at hb1 + change 2 * ((G.onSide Sᶜ).faceCodimension (G.sideMarginal x Sᶜ) + 2) ≤ _ at hb2 + omega + · have hb := G.faceCodimension_no_tight heven' hcut + omega + +theorem sharp_face_rank (G : LooplessGraph V E) (m : ℕ) + (hm : 0 < m) (hV : Fintype.card V = 2 * m) {x : E → ℝ} + (hx : x ∈ G.polytope) : G.faceCodimension x + 2 ≤ 3 * m := by + by_cases hm1 : m = 1 + · have htwo : Fintype.card V = 2 := by omega + have hb := faceCodimension_two G htwo x + omega + · have heven : Even (Fintype.card V) := by rw [hV]; exact even_two_mul m + have hb := sharp_face_rank_aux (Fintype.card V) G rfl heven (by omega) x + (G.polytope_subset_constraintPolytope hx) + omega + +end MatchingEntropyBounds.Refined + +end + +end OAI diff --git a/lean/OAI/Combinatorics/MatchingEntropy/Simplex.lean b/lean/OAI/Combinatorics/MatchingEntropy/Simplex.lean new file mode 100644 index 0000000000000000000000000000000000000000..70100e20db1dc2da0e3af2dfcb5f112a6d0f1f7b --- /dev/null +++ b/lean/OAI/Combinatorics/MatchingEntropy/Simplex.lean @@ -0,0 +1,56 @@ +import OAI.Combinatorics.MatchingEntropy.Model + +namespace OAI + +noncomputable section + +open scoped BigOperators + +universe uIndex + +namespace MatchingEntropyBounds + +theorem probabilitySimplex_eq_range (Index : Type uIndex) [Fintype Index] : + probabilitySimplex Index = + Set.range (fun simplex : Convexity.StdSimplex ℝ Index ↦ ⇑simplex.weights) := by + rw [Convexity.StdSimplex.range_toFun_comp_weights] + ext weights + simp [probabilitySimplex] + +theorem convex_probabilitySimplex (Index : Type uIndex) [Fintype Index] : + Convex ℝ (probabilitySimplex Index) := by + intro leftWeights leftMem rightWeights rightMem leftScale rightScale + leftNonneg rightNonneg total + constructor + · intro index + exact add_nonneg (mul_nonneg leftNonneg (leftMem.1 index)) + (mul_nonneg rightNonneg (rightMem.1 index)) + · simp only [Pi.add_apply, Pi.smul_apply, smul_eq_mul, Finset.sum_add_distrib, + ← Finset.mul_sum, leftMem.2, rightMem.2, mul_one, total] + +theorem single_mem_probabilitySimplex {Index : Type uIndex} [Fintype Index] + [DecidableEq Index] (index : Index) : Pi.single index 1 ∈ probabilitySimplex Index := by + constructor + · intro other + simp only [Pi.single_apply] + split <;> norm_num + · simp + +theorem mem_Icc_of_mem_probabilitySimplex {Index : Type uIndex} [Fintype Index] + {weights : Index → ℝ} (mem : weights ∈ probabilitySimplex Index) (index : Index) : + weights index ∈ Set.Icc (0 : ℝ) 1 := by + refine ⟨mem.1 index, ?_⟩ + rw [← mem.2] + exact Finset.single_le_sum (fun other _ ↦ mem.1 other) (Finset.mem_univ index) + +theorem isCompact_probabilitySimplex (Index : Type uIndex) [Fintype Index] : + IsCompact (probabilitySimplex Index) := by + rw [probabilitySimplex_eq_range] + exact isCompact_range + (Convexity.StdSimplex.isEmbedding_toFun_comp_weights ℝ Index).continuous + +end MatchingEntropyBounds + +end + +end OAI diff --git a/lean/OAI/Combinatorics/MatchingEntropy/TriangleExpansion.lean b/lean/OAI/Combinatorics/MatchingEntropy/TriangleExpansion.lean new file mode 100644 index 0000000000000000000000000000000000000000..0c57b0cd38c2ac5d9f6855cd8fbe1bcf3e5476cd --- /dev/null +++ b/lean/OAI/Combinatorics/MatchingEntropy/TriangleExpansion.lean @@ -0,0 +1,698 @@ +import OAI.Combinatorics.MatchingEntropy.Degenerate + +namespace OAI + +noncomputable section + +open scoped BigOperators Topology +open Filter + +universe uV uE uI uJ uA uB uC uW uF uD uι + +namespace MatchingEntropyBounds.Refined + +section TriangleExpansion +variable {V : Type uV} {E : Type uE} [Fintype V] [Fintype E] [DecidableEq V] [DecidableEq E] + +def CubicColoring (G : LooplessGraph V E) (c : E → Fin 3) : Prop := + ∀ v i, ∃! e, G.Incident v e ∧ c e = i + +def colorEdges (c : E → Fin 3) (i : Fin 3) : Finset E := Finset.univ.filter (fun e => c e = i) + +def triangleTip (v : V) (i : Fin 3) : V ⊕ Fin 2 := ![Sum.inl v, Sum.inr 0, Sum.inr 1] i + +def triangleCollapse (v : V) : V ⊕ Fin 2 → V := Sum.elim id (fun _ => v) + +def reattach (v : V) (i : Fin 3) (w : V) : V ⊕ Fin 2 := + if w = v then triangleTip v i else Sum.inl w + +omit [Fintype V] [Fintype E] [DecidableEq E] in +theorem collapse_reattach (v : V) (i : Fin 3) (w : V) : + triangleCollapse v (reattach v i w) = w := by + by_cases h : w = v + · subst w + fin_cases i <;> simp [reattach,triangleTip,triangleCollapse] + · simp [reattach,h,triangleCollapse] + +def triangleExpansion (G : LooplessGraph V E) (c : E → Fin 3) (v : V) : + LooplessGraph (V ⊕ Fin 2) (E ⊕ Fin 3) where + left := Sum.elim (fun e => reattach v (c e) (G.left e)) (fun i => triangleTip v (i + 1)) + right := Sum.elim (fun e => reattach v (c e) (G.right e)) (fun i => triangleTip v (i + 2)) + loopless := by + intro e h + rcases e with e | i + · have hh := congrArg (triangleCollapse v) h + exact G.loopless e ((collapse_reattach v (c e) (G.left e)).symm.trans + (hh.trans (collapse_reattach v (c e) (G.right e)))) + · fin_cases i <;> simp [triangleTip] at h + +def expandedColor (c : E → Fin 3) : E ⊕ Fin 3 → Fin 3 := Sum.elim c id + +def triangleVertices (v : V) : Finset (V ⊕ Fin 2) := Finset.univ.image (triangleTip v) + +def vertexColorEdge (G : LooplessGraph V E) (c : E → Fin 3) (hc : CubicColoring G c) + (v : V) (i : Fin 3) : E := Classical.choose (hc v i) + +def triangleExtension (G : LooplessGraph V E) (c : E → Fin 3) (hc : CubicColoring G c) + (v : V) : (E → ℝ) →ₗ[ℝ] (E ⊕ Fin 3 → ℝ) where + toFun x := Sum.elim x (fun i => x (vertexColorEdge G c hc v i)) + map_add' x y := by ext e; cases e <;> rfl + map_smul' a x := by ext e; cases e <;> rfl + +def IsSimpleLabelled (G : LooplessGraph V E) : Prop := + ∀ e f, ((G.left e = G.left f ∧ G.right e = G.right f) ∨ + (G.left e = G.right f ∧ G.right e = G.left f)) → e = f + +end TriangleExpansion + +def KleeV : ℕ → Type + | 0 => Fin 2 + | n + 1 => KleeV n ⊕ Fin 2 + +def KleeE : ℕ → Type + | 0 => Fin 3 + | n + 1 => KleeE n ⊕ Fin 3 + +noncomputable instance kleeVFintype (n : ℕ) : Fintype (KleeV n) := by + induction n with + | zero => exact inferInstanceAs (Fintype (Fin 2)) + | succ n ih => + let : Fintype (KleeV n) := ih + exact inferInstanceAs (Fintype (KleeV n ⊕ Fin 2)) +noncomputable instance kleeEFintype (n : ℕ) : Fintype (KleeE n) := by + induction n with + | zero => exact inferInstanceAs (Fintype (Fin 3)) + | succ n ih => + let : Fintype (KleeE n) := ih + exact inferInstanceAs (Fintype (KleeE n ⊕ Fin 3)) +noncomputable instance kleeVDecEq (n : ℕ) : DecidableEq (KleeV n) := Classical.decEq _ +noncomputable instance kleeEDecEq (n : ℕ) : DecidableEq (KleeE n) := Classical.decEq _ + +def kleeRoot : (n : ℕ) → KleeV n + | 0 => (0 : Fin 2) + | n + 1 => Sum.inl (kleeRoot n) + +def kleeColor : (n : ℕ) → KleeE n → Fin 3 + | 0 => id + | n + 1 => expandedColor (kleeColor n) + +def kleeGraph : (n : ℕ) → LooplessGraph (KleeV n) (KleeE n) + | 0 => ⟨fun _ => (0 : Fin 2), fun _ => (1 : Fin 2), fun _ => by exact (by norm_num : (0 : Fin 2) ≠ 1)⟩ + | n + 1 => triangleExpansion (kleeGraph n) (kleeColor n) (kleeRoot n) + +def kleeUniform (n : ℕ) : KleeE n → ℝ := fun _ => 1 / 3 + +def coloredVector {E : Type uE} (c : E → Fin 3) (i : Fin 3) : E → ℝ := + fun e => if c e = i then 1 else 0 + +def kleeTriangle (n : ℕ) : Set (KleeE n → ℝ) := + convexHull ℝ (Set.range (coloredVector (kleeColor n))) + +def kleeLaw (n : ℕ) : (kleeGraph n).Matching → ℝ := + fun M => ∑ i : Fin 3, if M.val = colorEdges (kleeColor n) i then 1 / 3 else 0 + +section ExpansionSupport +variable {V : Type uV} {E : Type uE} [Fintype V] [Fintype E] [DecidableEq V] [DecidableEq E] + +omit [Fintype V] [Fintype E] [DecidableEq V] [DecidableEq E] in +theorem triangleTip_injective (v : V) : Function.Injective (triangleTip v) := by + intro i j h + fin_cases i <;> fin_cases j <;> simp_all [triangleTip] + +omit [Fintype V] [Fintype E] [DecidableEq E] in +theorem reattach_eq_tip (v w : V) (i j : Fin 3) : + reattach v i w = triangleTip v j ↔ w = v ∧ i = j := by + by_cases h : w = v + · simp [reattach,h,(triangleTip_injective v).eq_iff] + · fin_cases j <;> simp [reattach,h,triangleTip] + +omit [Fintype V] [Fintype E] [DecidableEq E] in +theorem reattach_eq_inl (v w z : V) (hz : z ≠ v) (i : Fin 3) : + reattach v i w = Sum.inl z ↔ w = z := by + by_cases h : w = v + · subst w + fin_cases i <;> simp [reattach,triangleTip,hz.symm] + · simp [reattach,h] + +omit [Fintype V] [Fintype E] [DecidableEq E] in +theorem expanded_incident_old_tip (G : LooplessGraph V E) (c : E → Fin 3) (v : V) + (e : E) (j : Fin 3) : + (triangleExpansion G c v).Incident (triangleTip v j) (Sum.inl e) ↔ + G.Incident v e ∧ c e = j := by + simp only [LooplessGraph.Incident,triangleExpansion,Sum.elim_inl,reattach_eq_tip] + tauto + +omit [Fintype V] [Fintype E] [DecidableEq E] in +theorem expanded_incident_old_inl (G : LooplessGraph V E) (c : E → Fin 3) (v w : V) + (hw : w ≠ v) (e : E) : + (triangleExpansion G c v).Incident (Sum.inl w) (Sum.inl e) ↔ G.Incident w e := by + simp only [LooplessGraph.Incident,triangleExpansion,Sum.elim_inl,reattach_eq_inl v _ w hw] + +omit [Fintype V] [Fintype E] [DecidableEq E] in +theorem expanded_incident_new_tip (G : LooplessGraph V E) (c : E → Fin 3) (v : V) + (i j : Fin 3) : + (triangleExpansion G c v).Incident (triangleTip v j) (Sum.inr i) ↔ i ≠ j := by + simp only [LooplessGraph.Incident,triangleExpansion,Sum.elim_inr, + (triangleTip_injective v).eq_iff] + fin_cases i <;> fin_cases j <;> decide + +omit [Fintype V] [Fintype E] [DecidableEq E] in +theorem expanded_incident_new_inl (G : LooplessGraph V E) (c : E → Fin 3) (v w : V) + (hw : w ≠ v) (i : Fin 3) : + ¬(triangleExpansion G c v).Incident (Sum.inl w) (Sum.inr i) := by + fin_cases i <;> simp [LooplessGraph.Incident,triangleExpansion,triangleTip,hw.symm] + +omit [Fintype V] [Fintype E] [DecidableEq V] [DecidableEq E] in +theorem vertexColorEdge_spec (G : LooplessGraph V E) (c : E → Fin 3) (hc : CubicColoring G c) + (v : V) (i : Fin 3) : + G.Incident v (vertexColorEdge G c hc v i) ∧ c (vertexColorEdge G c hc v i) = i := + (Classical.choose_spec (hc v i)).1 + +omit [Fintype V] [Fintype E] [DecidableEq V] [DecidableEq E] in +theorem eq_vertexColorEdge (G : LooplessGraph V E) (c : E → Fin 3) (hc : CubicColoring G c) + (v : V) {e : E} {i : Fin 3} (he : G.Incident v e) (hi : c e = i) : + e = vertexColorEdge G c hc v i := (Classical.choose_spec (hc v i)).2 e ⟨he,hi⟩ + +omit [Fintype V] [DecidableEq V] [DecidableEq E] in +theorem colorEdges_matching (G : LooplessGraph V E) (c : E → Fin 3) (hc : CubicColoring G c) + (i : Fin 3) : G.IsPerfectMatching (colorEdges c i) := by + intro v + obtain ⟨e, he, hu⟩ := hc v i + refine ⟨e,⟨by simp [colorEdges,he.2],he.1⟩,?_⟩ + intro f hf + exact hu f ⟨hf.2,by simpa [colorEdges] using hf.1⟩ + +omit [Fintype V] [DecidableEq V] in +def colorMatching (G : LooplessGraph V E) (c : E → Fin 3) (hc : CubicColoring G c) + (i : Fin 3) : G.Matching := ⟨colorEdges c i,colorEdges_matching G c hc i⟩ + +omit [Fintype V] [Fintype E] [DecidableEq E] in +theorem cubicColoring_expansion (G : LooplessGraph V E) (c : E → Fin 3) + (hc : CubicColoring G c) (v : V) : CubicColoring (triangleExpansion G c v) (expandedColor c) := by + intro w i + have htip (j : Fin 3) : ∃! e, (triangleExpansion G c v).Incident (triangleTip v j) e ∧ expandedColor c e = i := by + by_cases hij : i = j + · subst j + refine ⟨Sum.inl (vertexColorEdge G c hc v i), ⟨?_,(vertexColorEdge_spec G c hc v i).2⟩, ?_⟩ + · exact (expanded_incident_old_tip G c v _ _).mpr (vertexColorEdge_spec G c hc v i) + · intro e he + rcases e with e | e + · apply congrArg Sum.inl + exact eq_vertexColorEdge G c hc v ((expanded_incident_old_tip G c v e i).mp he.1).1 he.2 + · exact ((expanded_incident_new_tip G c v e i).mp he.1 he.2).elim + · refine ⟨Sum.inr i,⟨(expanded_incident_new_tip G c v i j).mpr hij,rfl⟩,?_⟩ + intro e he + rcases e with e | e + · have hej := ((expanded_incident_old_tip G c v e j).mp he.1).2 + exact (hij (he.2.symm.trans hej)).elim + · exact congrArg Sum.inr he.2 + rcases w with w | w + · by_cases hw : w = v + · subst w + exact htip 0 + · obtain ⟨e,he,hu⟩ := hc w i + refine ⟨Sum.inl e,⟨(expanded_incident_old_inl G c v w hw e).mpr he.1,he.2⟩,?_⟩ + intro f hf + rcases f with f | f + · exact congrArg Sum.inl (hu f ⟨(expanded_incident_old_inl G c v w hw f).mp hf.1,hf.2⟩) + · exact (expanded_incident_new_inl G c v w hw f hf.1).elim + · fin_cases w + · exact htip 1 + · exact htip 2 + +omit [Fintype V] [Fintype E] [DecidableEq E] in +theorem triangleVertices_eq (v : V) : + triangleVertices v = {Sum.inl v, Sum.inr 0, Sum.inr 1} := by + simp [triangleVertices,Fin.univ_succ,triangleTip] + +omit [Fintype V] [Fintype E] [DecidableEq E] in +theorem mem_triangleVertices_tip (v : V) (i : Fin 3) : triangleTip v i ∈ triangleVertices v := + Finset.mem_image.mpr ⟨i,Finset.mem_univ i,rfl⟩ + +omit [Fintype V] [Fintype E] [DecidableEq E] in +theorem reattach_mem_triangle (v w : V) (i : Fin 3) : + reattach v i w ∈ triangleVertices v ↔ w = v := by + by_cases h : w = v + · simp [reattach,h,mem_triangleVertices_tip] + · simp [reattach,h,triangleVertices_eq] + +omit [Fintype V] [Fintype E] [DecidableEq E] in +theorem expanded_crosses_old (G : LooplessGraph V E) (c : E → Fin 3) (v : V) (e : E) : + (triangleExpansion G c v).Crosses (triangleVertices v) (Sum.inl e) ↔ G.Incident v e := by + have hl := G.loopless e + simp only [LooplessGraph.Crosses,triangleExpansion,Sum.elim_inl,reattach_mem_triangle, + LooplessGraph.Incident] + constructor + · tauto + · rintro (h | h) + · exact Or.inl ⟨h,fun hh => hl (h.trans hh.symm)⟩ + · exact Or.inr ⟨fun hh => hl (hh.trans h.symm),h⟩ + +omit [Fintype V] [Fintype E] [DecidableEq E] in +theorem expanded_crosses_new (G : LooplessGraph V E) (c : E → Fin 3) (v : V) (i : Fin 3) : + ¬(triangleExpansion G c v).Crosses (triangleVertices v) (Sum.inr i) := by + simp [LooplessGraph.Crosses,triangleExpansion,mem_triangleVertices_tip] + +omit [Fintype V] [Fintype E] [DecidableEq E] in +theorem triangleVertices_odd (v : V) : Odd (triangleVertices v).card := by + have hcard : (triangleVertices v).card = 3 := by + rw [triangleVertices,Finset.card_image_of_injective _ (triangleTip_injective v)] + simp + rw [hcard] + norm_num + +omit [Fintype V] [DecidableEq E] in +theorem expanded_cutMass (G : LooplessGraph V E) (c : E → Fin 3) (v : V) (y : E ⊕ Fin 3 → ℝ) : + (triangleExpansion G c v).cutMass y (triangleVertices v) = G.degree (fun e => y (Sum.inl e)) v := by + simp only [LooplessGraph.cutMass,LooplessGraph.cut,Finset.sum_filter,Fintype.sum_sum_type, + expanded_crosses_old,expanded_crosses_new,ite_false,Finset.sum_const_zero,add_zero, + LooplessGraph.degree] + +omit [Fintype V] [Fintype E] [DecidableEq V] [DecidableEq E] in +def incidentChoice (G : LooplessGraph V E) (M : G.Matching) (v : V) : E := + Classical.choose (M.property v) + +omit [Fintype V] [Fintype E] [DecidableEq V] [DecidableEq E] in +theorem incidentChoice_spec (G : LooplessGraph V E) (M : G.Matching) (v : V) : + incidentChoice G M v ∈ M.val ∧ G.Incident v (incidentChoice G M v) := + (Classical.choose_spec (M.property v)).1 + +omit [Fintype V] [Fintype E] [DecidableEq V] [DecidableEq E] in +theorem eq_incidentChoice (G : LooplessGraph V E) (M : G.Matching) (v : V) {e : E} + (he : e ∈ M.val) (hv : G.Incident v e) : e = incidentChoice G M v := + (Classical.choose_spec (M.property v)).2 e ⟨he,hv⟩ + +omit [Fintype V] [Fintype E] [DecidableEq V] [DecidableEq E] in +def expandEdges (G : LooplessGraph V E) (c : E → Fin 3) (v : V) (M : G.Matching) : + Finset (E ⊕ Fin 3) := M.val.disjSum {c (incidentChoice G M v)} + +omit [Fintype V] [Fintype E] [DecidableEq E] in +theorem expandEdges_matching (G : LooplessGraph V E) (c : E → Fin 3) (v : V) (M : G.Matching) : + (triangleExpansion G c v).IsPerfectMatching (expandEdges G c v M) := by + let e := incidentChoice G M v + have he := incidentChoice_spec G M v + have htip (j : Fin 3) : ∃! f, f ∈ expandEdges G c v M ∧ + (triangleExpansion G c v).Incident (triangleTip v j) f := by + by_cases hj : c e = j + · refine ⟨Sum.inl e,⟨by simp [expandEdges,he.1,e], + (expanded_incident_old_tip G c v e j).mpr ⟨he.2,hj⟩⟩,?_⟩ + intro f hf + rcases f with f | f + · have hfm : f ∈ M.val := by simpa [expandEdges] using hf.1 + exact congrArg Sum.inl (eq_incidentChoice G M v hfm + ((expanded_incident_old_tip G c v f j).mp hf.2).1) + · have hfcol : f = c e := by simpa [expandEdges,e] using hf.1 + exact ((expanded_incident_new_tip G c v f j).mp hf.2 (hfcol.trans hj)).elim + · refine ⟨Sum.inr (c e),⟨by simp [expandEdges,e], + (expanded_incident_new_tip G c v (c e) j).mpr hj⟩,?_⟩ + intro f hf + rcases f with f | f + · have hfm : f ∈ M.val := by simpa [expandEdges] using hf.1 + have hfv := (expanded_incident_old_tip G c v f j).mp hf.2 + have hfe : f = e := eq_incidentChoice G M v hfm hfv.1 + exact (hj (hfe ▸ hfv.2)).elim + · exact congrArg Sum.inr (by simpa [expandEdges,e] using hf.1) + intro w + rcases w with w | w + · by_cases hw : w = v + · subst w + exact htip 0 + · obtain ⟨f,hf,hu⟩ := M.property w + refine ⟨Sum.inl f,⟨by simpa [expandEdges] using hf.1, + (expanded_incident_old_inl G c v w hw f).mpr hf.2⟩,?_⟩ + intro g hg + rcases g with g | g + · exact congrArg Sum.inl (hu g ⟨by simpa [expandEdges] using hg.1, + (expanded_incident_old_inl G c v w hw g).mp hg.2⟩) + · exact (expanded_incident_new_inl G c v w hw g hg.2).elim + · fin_cases w + · exact htip 1 + · exact htip 2 + +omit [Fintype V] [Fintype E] [DecidableEq E] in +def expandMatching (G : LooplessGraph V E) (c : E → Fin 3) (v : V) (M : G.Matching) : + (triangleExpansion G c v).Matching := ⟨expandEdges G c v M,expandEdges_matching G c v M⟩ + +omit [Fintype V] [Fintype E] [DecidableEq E] in +theorem expandMatching_injective (G : LooplessGraph V E) (c : E → Fin 3) (v : V) : + Function.Injective (expandMatching G c v) := by + intro M N h + apply Subtype.ext + ext e + have hh := congrArg (fun K : (triangleExpansion G c v).Matching => Sum.inl e ∈ K.val) h + simpa [expandMatching,expandEdges] using hh + +omit [Fintype V] [Fintype E] in +theorem expandMatching_indicator (G : LooplessGraph V E) (c : E → Fin 3) + (hc : CubicColoring G c) (v : V) (M : G.Matching) : + (triangleExpansion G c v).indicator (expandMatching G c v M) = triangleExtension G c hc v (G.indicator M) := by + ext e + rcases e with e | i + · simp [LooplessGraph.indicator,expandMatching,expandEdges,triangleExtension] + · have hh : c (incidentChoice G M v) = i ↔ vertexColorEdge G c hc v i ∈ M.val := by + constructor + · intro h + rw [← eq_vertexColorEdge G c hc v (incidentChoice_spec G M v).2 h] + exact (incidentChoice_spec G M v).1 + · intro h + rw [← eq_incidentChoice G M v h (vertexColorEdge_spec G c hc v i).1] + exact (vertexColorEdge_spec G c hc v i).2 + simp only [LooplessGraph.indicator,expandMatching,expandEdges,Finset.inr_mem_disjSum, + Finset.mem_singleton,triangleExtension,LinearMap.coe_mk,AddHom.coe_mk,Sum.elim_inr] + simp only [eq_comm (a := i) (b := c (incidentChoice G M v)),hh] + +def CrossOnce (G : LooplessGraph V E) (c : E → Fin 3) (v : V) + (N : (triangleExpansion G c v).Matching) : Prop := + ∃! e, Sum.inl e ∈ N.val ∧ G.Incident v e + +omit [Fintype V] in +theorem cutMass_indicator_card (G : LooplessGraph V E) (M : G.Matching) (S : Finset V) : + G.cutMass (G.indicator M) S = ((M.val.filter (G.Crosses S)).card : ℝ) := by + simp only [LooplessGraph.cutMass,LooplessGraph.indicator,Finset.sum_boole] + congr 2 + ext e + simp [LooplessGraph.cut,and_comm] + +omit [Fintype V] in +theorem crossOnce_of_cut_eq_one (G : LooplessGraph V E) (c : E → Fin 3) (v : V) + (N : (triangleExpansion G c v).Matching) + (hN : (triangleExpansion G c v).cutMass ((triangleExpansion G c v).indicator N) (triangleVertices v) = 1) : + CrossOnce G c v N := by + rw [cutMass_indicator_card] at hN + have hn : (N.val.filter ((triangleExpansion G c v).Crosses (triangleVertices v))).card = 1 := by + exact_mod_cast hN + obtain ⟨f,hf⟩ := Finset.card_eq_one.mp hn + have hfm : f ∈ N.val ∧ (triangleExpansion G c v).Crosses (triangleVertices v) f := by + have hh : f ∈ N.val.filter ((triangleExpansion G c v).Crosses (triangleVertices v)) := by rw [hf]; simp + exact Finset.mem_filter.mp hh + rcases f with e | i + · refine ⟨e,⟨hfm.1,(expanded_crosses_old G c v e).mp hfm.2⟩,?_⟩ + intro f hfg + have hh : Sum.inl f ∈ N.val.filter ((triangleExpansion G c v).Crosses (triangleVertices v)) := + Finset.mem_filter.mpr ⟨hfg.1,(expanded_crosses_old G c v f).mpr hfg.2⟩ + rw [hf,Finset.mem_singleton] at hh + exact Sum.inl.inj hh + · exact (expanded_crosses_new G c v i hfm.2).elim + +def contractEdges (G : LooplessGraph V E) (c : E → Fin 3) (v : V) + (N : (triangleExpansion G c v).Matching) : Finset E := + Finset.univ.filter (fun e => Sum.inl e ∈ N.val) + +omit [Fintype V] in +theorem contractEdges_matching (G : LooplessGraph V E) (c : E → Fin 3) (v : V) + (N : (triangleExpansion G c v).Matching) (hN : CrossOnce G c v N) : + G.IsPerfectMatching (contractEdges G c v N) := by + intro w + by_cases hw : w = v + · subst w + simpa only [CrossOnce,contractEdges,Finset.mem_filter,Finset.mem_univ,true_and] using hN + · obtain ⟨f,hf,hu⟩ := N.property (Sum.inl w) + rcases f with f | f + · refine ⟨f,⟨by simpa [contractEdges] using hf.1, + (expanded_incident_old_inl G c v w hw f).mp hf.2⟩,?_⟩ + intro g hg + apply Sum.inl.inj + exact hu (Sum.inl g) ⟨by simpa [contractEdges] using hg.1, + (expanded_incident_old_inl G c v w hw g).mpr hg.2⟩ + · exact (expanded_incident_new_inl G c v w hw f hf.2).elim + +def contractMatching (G : LooplessGraph V E) (c : E → Fin 3) (v : V) + (N : (triangleExpansion G c v).Matching) (hN : CrossOnce G c v N) : G.Matching := + ⟨contractEdges G c v N,contractEdges_matching G c v N hN⟩ + +omit [Fintype V] [Fintype E] [DecidableEq V] [DecidableEq E] in +theorem fin3_add_one_ne (i : Fin 3) : i + 1 ≠ i := by fin_cases i <;> decide + +omit [Fintype V] in +theorem expand_contract (G : LooplessGraph V E) (c : E → Fin 3) (v : V) + (N : (triangleExpansion G c v).Matching) (hN : CrossOnce G c v N) : + expandMatching G c v (contractMatching G c v N hN) = N := by + let M := contractMatching G c v N hN + let e := incidentChoice G M v + have he : Sum.inl e ∈ N.val ∧ G.Incident v e := by + simpa [e,M,contractMatching,contractEdges] using incidentChoice_spec G M v + have hcol : ∀ i : Fin 3, Sum.inr i ∈ N.val → i = c e := by + intro i hi + by_contra hn + have hh := (N.property (triangleTip v (c e))).unique + ⟨hi,(expanded_incident_new_tip G c v i (c e)).mpr hn⟩ + ⟨he.1,(expanded_incident_old_tip G c v e (c e)).mpr ⟨he.2,rfl⟩⟩ + cases hh + have hmem : Sum.inr (c e) ∈ N.val := by + obtain ⟨f,hf,_⟩ := N.property (triangleTip v (c e + 1)) + rcases f with f | i + · have hfv := (expanded_incident_old_tip G c v f (c e + 1)).mp hf.2 + have hfe : f = e := hN.unique ⟨hf.1,hfv.1⟩ he + have hh : c e = c e + 1 := hfe ▸ hfv.2 + exact (fin3_add_one_ne (c e) hh.symm).elim + · exact hcol i hf.1 ▸ hf.1 + apply Subtype.ext + ext f + rcases f with f | i + · simp [expandMatching,expandEdges,contractMatching,contractEdges] + · simp only [expandMatching,expandEdges,Finset.inr_mem_disjSum,Finset.mem_singleton] + change i = c e ↔ Sum.inr i ∈ N.val + exact ⟨fun hi => hi ▸ hmem,hcol i⟩ + +omit [Fintype V] in +theorem range_expandMatching_of_crossOnce (G : LooplessGraph V E) (c : E → Fin 3) (v : V) + (N : (triangleExpansion G c v).Matching) (hN : CrossOnce G c v N) : + N ∈ Set.range (expandMatching G c v) := ⟨contractMatching G c v N hN,expand_contract G c v N hN⟩ + +omit [Fintype V] in +theorem cutMass_mean (G : LooplessGraph V E) (p : G.Matching → ℝ) (S : Finset V) : + G.cutMass (G.mean p) S = ∑ M, p M * G.cutMass (G.indicator M) S := by + simp only [LooplessGraph.cutMass,LooplessGraph.mean,Finset.mul_sum] + exact Finset.sum_comm + +omit [Fintype V] in +theorem positive_law_tight_cut (G : LooplessGraph V E) {p : G.Matching → ℝ} + (hp : p ∈ probabilitySimplex G.Matching) (S : Finset V) (hS : Odd S.card) + (ht : G.cutMass (G.mean p) S = 1) {M : G.Matching} (hM : p M ≠ 0) : + G.cutMass (G.indicator M) S = 1 := by + have hl (N : G.Matching) : 0 ≤ G.cutMass (G.indicator N) S - 1 := + sub_nonneg.mpr ((G.indicator_mem_constraintPolytope N).2.2 S hS) + have heq : ∑ N, p N * (G.cutMass (G.indicator N) S - 1) = 0 := by + simp only [mul_sub,mul_one,Finset.sum_sub_distrib,← cutMass_mean,ht,hp.2,sub_self] + have hz : p M * (G.cutMass (G.indicator M) S - 1) = 0 := + (Finset.sum_eq_zero_iff_of_nonneg (fun N _ => mul_nonneg (hp.1 N) (hl N))).mp heq M (Finset.mem_univ M) + exact sub_eq_zero.mp ((mul_eq_zero.mp hz).resolve_left hM) + +omit [Fintype V] in +theorem expanded_push_mean (G : LooplessGraph V E) (c : E → Fin 3) + (hc : CubicColoring G c) (v : V) (q : G.Matching → ℝ) : + (triangleExpansion G c v).mean (fiberMass q (expandMatching G c v)) = + triangleExtension G c hc v (G.mean q) := by + ext e + rw [LooplessGraph.mean,fiberMass_expect] + simp_rw [expandMatching_indicator G c hc v] + rcases e with e | i <;> rfl + +omit [Fintype V] [Fintype E] [DecidableEq V] [DecidableEq E] in +theorem triangleExtension_injective (G : LooplessGraph V E) (c : E → Fin 3) + (hc : CubicColoring G c) (v : V) : Function.Injective (triangleExtension G c hc v) := by + intro x y h + ext e + exact congrFun h (Sum.inl e) + +omit [Fintype V] in +theorem expanded_push_feasible (G : LooplessGraph V E) (c : E → Fin 3) + (hc : CubicColoring G c) (v : V) {x : E → ℝ} {q : G.Matching → ℝ} + (hq : q ∈ G.feasibleLaws x) : + fiberMass q (expandMatching G c v) ∈ (triangleExpansion G c v).feasibleLaws (triangleExtension G c hc v x) := by + exact ⟨fiberMass_mem_simplex hq.1 _,by rw [expanded_push_mean G c hc v,hq.2]⟩ + +omit [Fintype V] in +theorem expanded_pull_simplex (G : LooplessGraph V E) (c : E → Fin 3) (v : V) + {p : (triangleExpansion G c v).Matching → ℝ} + (hp : p ∈ probabilitySimplex (triangleExpansion G c v).Matching) + (ht : (triangleExpansion G c v).cutMass ((triangleExpansion G c v).mean p) (triangleVertices v) = 1) : + p = fiberMass (fun M => p (expandMatching G c v M)) (expandMatching G c v) ∧ + (fun M => p (expandMatching G c v M)) ∈ probabilitySimplex G.Matching := by + have heq : fiberMass (fun M => p (expandMatching G c v M)) (expandMatching G c v) = p := by + apply fiberMass_pullback _ _ (expandMatching_injective G c v) + intro N hN + by_contra hn + exact hN (range_expandMatching_of_crossOnce G c v N (crossOnce_of_cut_eq_one G c v N + (positive_law_tight_cut _ hp _ (triangleVertices_odd v) ht hn))) + refine ⟨heq.symm,simplex_of_fiberMass _ _ (expandMatching_injective G c v) ?_⟩ + exact heq.symm ▸ hp + +omit [Fintype V] in +theorem expanded_pull_feasible (G : LooplessGraph V E) (c : E → Fin 3) + (hc : CubicColoring G c) (v : V) {x : E → ℝ} (hx : x ∈ G.polytope) + {p : (triangleExpansion G c v).Matching → ℝ} + (hp : p ∈ (triangleExpansion G c v).feasibleLaws (triangleExtension G c hc v x)) : + p = fiberMass (fun M => p (expandMatching G c v M)) (expandMatching G c v) ∧ + (fun M => p (expandMatching G c v M)) ∈ G.feasibleLaws x := by + have ht : (triangleExpansion G c v).cutMass ((triangleExpansion G c v).mean p) (triangleVertices v) = 1 := by + rw [hp.2,expanded_cutMass] + exact (G.polytope_subset_constraintPolytope hx).2.1 v + obtain ⟨heq,hq⟩ := expanded_pull_simplex G c v hp.1 ht + refine ⟨heq,hq,triangleExtension_injective G c hc v ?_⟩ + rw [← expanded_push_mean,← heq,hp.2] + +omit [Fintype V] in +theorem expansion_image_eq (G : LooplessGraph V E) (c : E → Fin 3) + (hc : CubicColoring G c) (v : V) : + triangleExtension G c hc v '' G.polytope = + {y | y ∈ (triangleExpansion G c v).polytope ∧ + (triangleExpansion G c v).cutMass y (triangleVertices v) = 1} := by + ext y + constructor + · rintro ⟨x,hx,rfl⟩ + obtain ⟨q,hq⟩ := (G.mem_polytope_iff x).mp hx + refine ⟨((triangleExpansion G c v).mem_polytope_iff _).mpr + ⟨_,expanded_push_feasible G c hc v hq⟩,?_⟩ + rw [expanded_cutMass] + exact (G.polytope_subset_constraintPolytope hx).2.1 v + · rintro ⟨hy,ht⟩ + obtain ⟨p,hp⟩ := ((triangleExpansion G c v).mem_polytope_iff y).mp hy + have ht' : (triangleExpansion G c v).cutMass ((triangleExpansion G c v).mean p) (triangleVertices v) = 1 := hp.2.symm ▸ ht + obtain ⟨heq,hq⟩ := expanded_pull_simplex G c v hp.1 ht' + refine ⟨_,G.mean_mem_polytope hq,?_⟩ + rw [← expanded_push_mean,← heq,hp.2] + +omit [Fintype V] in +theorem expansion_image_extreme (G : LooplessGraph V E) (c : E → Fin 3) + (hc : CubicColoring G c) (v : V) : + IsExtreme ℝ (triangleExpansion G c v).polytope (triangleExtension G c hc v '' G.polytope) := by + rw [expansion_image_eq] + refine ⟨fun _ h => h.1, ?_⟩ + intro y hy z hz w hw hseg + obtain ⟨a,b,ha,hb,hab,rfl⟩ := hseg + refine ⟨hy,?_⟩ + have heq := hw.2 + rw [LooplessGraph.cutMass_linear] at heq + have hyl := ((triangleExpansion G c v).polytope_subset_constraintPolytope hy).2.2 _ (triangleVertices_odd v) + have hzl := ((triangleExpansion G c v).polytope_subset_constraintPolytope hz).2.2 _ (triangleVertices_odd v) + apply le_antisymm _ hyl + by_contra! hn + have hpos := mul_pos ha (sub_pos.mpr hn) + have hnonneg := mul_nonneg hb.le (sub_nonneg.mpr hzl) + nlinarith + +omit [Fintype V] in +theorem expansion_entropy (G : LooplessGraph V E) (c : E → Fin 3) + (hc : CubicColoring G c) (v : V) {x : E → ℝ} (hx : x ∈ G.polytope) : + maxMatchingEntropy (triangleExpansion G c v) (triangleExtension G c hc v x) = maxMatchingEntropy G x := by + have hxe : triangleExtension G c hc v x ∈ (triangleExpansion G c v).polytope := + (expansion_image_extreme G c hc v).subset ⟨x,hx,rfl⟩ + apply le_antisymm + · obtain ⟨p,hp,hopt⟩ := maxMatchingEntropy_attained _ hxe + obtain ⟨heq,hq⟩ := expanded_pull_feasible G c hc v hx hp + rw [← hopt,heq,entropy_fiberMass_injective _ _ (expandMatching_injective G c v)] + exact entropy_le_maxMatchingEntropy G hq + · obtain ⟨q,hq,hopt⟩ := maxMatchingEntropy_attained G hx + rw [← hopt,← entropy_fiberMass_injective q _ (expandMatching_injective G c v)] + exact entropy_le_maxMatchingEntropy (triangleExpansion G c v) (expanded_push_feasible G c hc v hq) + +theorem expansion_face (G : LooplessGraph V E) (c : E → Fin 3) (hc : CubicColoring G c) (v : V) : + let H := triangleExpansion G c v + let f := triangleExtension G c hc v + f '' G.polytope = {y | y ∈ H.polytope ∧ H.cutMass y (triangleVertices v) = 1} ∧ + IsExtreme ℝ H.polytope (f '' G.polytope) ∧ + ∀ x ∈ G.polytope, + minimalFace H (f x) = f '' minimalFace G x ∧ + faceDimension H (f x) = faceDimension G x ∧ + maxMatchingEntropy H (f x) = maxMatchingEntropy G x := by + refine ⟨expansion_image_eq G c hc v,expansion_image_extreme G c hc v,?_⟩ + intro x hx + exact ⟨(minimalFace_map _ G (triangleExtension G c hc v).toAffineMap + (triangleExtension_injective G c hc v) (expansion_image_extreme G c hc v) hx).symm, + (faceDimension_map _ G (triangleExtension G c hc v).toAffineMap + (triangleExtension_injective G c hc v) (expansion_image_extreme G c hc v) hx).symm, + expansion_entropy G c hc v hx⟩ + +omit [Fintype V] [Fintype E] [DecidableEq E] in +theorem simplicity_expansion (G : LooplessGraph V E) (c : E → Fin 3) (v : V) + (hG : IsSimpleLabelled G) : IsSimpleLabelled (triangleExpansion G c v) := by + intro e f h + rcases e with e | i <;> rcases f with f | j + · apply congrArg Sum.inl + apply hG e f + rcases h with ⟨hl,hr⟩ | ⟨hl,hr⟩ + · exact Or.inl ⟨by simpa [triangleExpansion,collapse_reattach] using congrArg (triangleCollapse v) hl, + by simpa [triangleExpansion,collapse_reattach] using congrArg (triangleCollapse v) hr⟩ + · exact Or.inr ⟨by simpa [triangleExpansion,collapse_reattach] using congrArg (triangleCollapse v) hl, + by simpa [triangleExpansion,collapse_reattach] using congrArg (triangleCollapse v) hr⟩ + · exfalso + rcases h with ⟨hl,hr⟩ | ⟨hl,hr⟩ <;> + simp only [triangleExpansion,Sum.elim_inl,Sum.elim_inr,reattach_eq_tip] at hl hr <;> + exact G.loopless e (hl.1.trans hr.1.symm) + · exfalso + rcases h with ⟨hl,hr⟩ | ⟨hl,hr⟩ + · simp only [triangleExpansion,Sum.elim_inl,Sum.elim_inr] at hl hr + have hl' := (reattach_eq_tip v _ _ _).mp hl.symm + have hr' := (reattach_eq_tip v _ _ _).mp hr.symm + exact G.loopless f (hl'.1.trans hr'.1.symm) + · simp only [triangleExpansion,Sum.elim_inl,Sum.elim_inr] at hl hr + have hl' := (reattach_eq_tip v _ _ _).mp hl.symm + have hr' := (reattach_eq_tip v _ _ _).mp hr.symm + exact G.loopless f (hr'.1.trans hl'.1.symm) + · fin_cases i <;> fin_cases j <;> simp_all [triangleExpansion,triangleTip] + +end ExpansionSupport +theorem klee_cubic (n : ℕ) : CubicColoring (kleeGraph n) (kleeColor n) := by + induction n with + | zero => + intro v i + refine ⟨i,⟨?_,rfl⟩,?_⟩ + · fin_cases v <;> simp [LooplessGraph.Incident,kleeGraph,KleeV] + · intro e he + exact he.2 + | succ n ih => exact cubicColoring_expansion _ _ ih _ + +theorem klee_cardV (n : ℕ) : Fintype.card (KleeV n) = 2 * (n + 1) := by + induction n with + | zero => rfl + | succ n ih => + change Fintype.card (KleeV n ⊕ Fin 2) = _ + rw [Fintype.card_sum,Fintype.card_fin,ih] + omega + +theorem klee_cardE (n : ℕ) : Fintype.card (KleeE n) = 3 * (n + 1) := by + induction n with + | zero => rfl + | succ n ih => + change Fintype.card (KleeE n ⊕ Fin 3) = _ + rw [Fintype.card_sum,Fintype.card_fin,ih] + omega + +theorem klee_simple_one : IsSimpleLabelled (kleeGraph 1) := by + intro e f h + rcases e with e | i <;> rcases f with f | j + · fin_cases e <;> fin_cases f <;> + simp_all [kleeGraph,kleeColor,kleeRoot,triangleExpansion,reattach,triangleTip,KleeV,KleeE] + · fin_cases e <;> fin_cases j <;> + simp_all [kleeGraph,kleeColor,kleeRoot,triangleExpansion,reattach,triangleTip,KleeV,KleeE] + · fin_cases i <;> fin_cases f <;> + simp_all [kleeGraph,kleeColor,kleeRoot,triangleExpansion,reattach,triangleTip,KleeV,KleeE] + · fin_cases i <;> fin_cases j <;> + simp_all [kleeGraph,kleeColor,kleeRoot,triangleExpansion,reattach,triangleTip,KleeV,KleeE] + +theorem klee_simple (n : ℕ) (hn : 0 < n) : IsSimpleLabelled (kleeGraph n) := by + induction n with + | zero => omega + | succ n ih => + cases n with + | zero => exact klee_simple_one + | succ n => exact simplicity_expansion _ _ _ (ih (by omega)) + +theorem klee_graph_properties (n : ℕ) : + Fintype.card (KleeV n) = 2 * (n + 1) ∧ Fintype.card (KleeE n) = 3 * (n + 1) ∧ + CubicColoring (kleeGraph n) (kleeColor n) ∧ + (∀ i, (kleeGraph n).IsPerfectMatching (colorEdges (kleeColor n) i)) ∧ + (∀ e, ∃! i, e ∈ colorEdges (kleeColor n) i) ∧ + (0 < n → IsSimpleLabelled (kleeGraph n)) := by + refine ⟨klee_cardV n,klee_cardE n,klee_cubic n,fun i => colorEdges_matching _ _ (klee_cubic n) i,?_,klee_simple n⟩ + intro e + refine ⟨kleeColor n e,by simp [colorEdges],?_⟩ + intro i hi + exact (by simpa [colorEdges] using hi : kleeColor n e = i).symm + +end MatchingEntropyBounds.Refined + +end + +end OAI diff --git a/lean/OAI/Combinatorics/MatchingEntropy/WeightedSpectrum.lean b/lean/OAI/Combinatorics/MatchingEntropy/WeightedSpectrum.lean new file mode 100644 index 0000000000000000000000000000000000000000..24fe22ef3fc303a0ce5542c26dd016e7aef775d5 --- /dev/null +++ b/lean/OAI/Combinatorics/MatchingEntropy/WeightedSpectrum.lean @@ -0,0 +1,79 @@ +import OAI.Combinatorics.MatchingEntropy.SeparableVariation + +namespace OAI + +noncomputable section + +open scoped BigOperators Topology +open Matrix + +universe uV uE uI uJ uA uB uC uW uF uD uι + +namespace MatchingEntropyBounds + +theorem spectral_diagonal {I : Type uI} [Fintype I] [DecidableEq I] + {C : Matrix I I ℝ} (hC : C.IsHermitian) (e : I) : + C e e = ∑ i, hC.eigenvalues i * (hC.eigenvectorBasis i e)^2 := by + have hh := congrArg (fun A : Matrix I I ℝ => A e e) hC.spectral_theorem + rw [Unitary.conjStarAlgAut_apply] at hh + simpa only [mul_apply, diagonal_apply, star_eq_conjTranspose, conjTranspose_apply, + star_trivial, Function.comp_apply, RCLike.ofReal_real_eq_id, id_eq, + mul_ite, ite_mul, mul_zero, zero_mul, Finset.sum_ite_eq', Finset.mem_univ, ite_true, + Matrix.IsHermitian.eigenvectorUnitary_apply, pow_two, mul_comm, mul_left_comm, + mul_assoc] using hh + +theorem covariance_weighted_rank {I : Type uI} [Fintype I] [DecidableEq I] + {C : Matrix I I ℝ} (hC : C.PosSemidef) (w : I → ℝ) + (hsecond : ∀ u : I → ℝ, + u ⬝ᵥ (C *ᵥ u) ≤ ∑ e, w e * ((C *ᵥ u) e)^2) : + (C.rank : ℝ) ≤ ∑ e, w e * C e e := by + let eig := hC.isHermitian.eigenvalues + let b := hC.isHermitian.eigenvectorBasis + have heig : ∀ i, 0 ≤ eig i := hC.eigenvalues_nonneg + have hone : ∀ i, eig i ≠ 0 → 1 ≤ eig i * (∑ e, w e * (b i e)^2) := by + intro i hi + let v : I → ℝ := b i + have hv : v ⬝ᵥ v=1 := by + have hn := b.orthonormal.1 i + have hb : inner ℝ (b i) (b i)=1 := by + rw [real_inner_self_eq_norm_sq, hn] + norm_num + simpa only [EuclideanSpace.inner_eq_star_dotProduct, star_trivial] using hb + have he : C *ᵥ v=eig i • v := hC.isHermitian.mulVec_eigenvectorBasis i + have hs := hsecond v + rw [he] at hs + simp only [dotProduct_smul, smul_eq_mul, hv, mul_one, Pi.smul_apply] at hs + have heq : (∑ e, w e*(eig i * v e)^2) = + (eig i)^2 * (∑ e, w e*(v e)^2) := by + rw [Finset.mul_sum] + apply Finset.sum_congr rfl + intro e _ + ring + rw [heq] at hs + have hp : 0 < eig i := lt_of_le_of_ne (heig i) (Ne.symm hi) + nlinarith + rw [hC.isHermitian.rank_eq_card_non_zero_eigs] + calc + (Fintype.card {i // eig i ≠ 0} : ℝ) = ∑ i : {i // eig i ≠ 0}, (1:ℝ) := by simp + _ ≤ ∑ i : {i // eig i ≠ 0}, eig i * (∑ e, w e*(b i e)^2) := + Finset.sum_le_sum fun i _ => hone i i.property + _ = ∑ i, eig i * (∑ e, w e*(b i e)^2) := by + exact sum_subtype_supported (fun i => eig i ≠ 0) + (fun i => eig i * (∑ e, w e*(b i e)^2)) + (by intro i hi; rw [not_ne_iff.mp hi, zero_mul]) + _ = ∑ e, w e * C e e := by + simp_rw [Finset.mul_sum] + rw [Finset.sum_comm] + apply Finset.sum_congr rfl + intro e _ + rw [spectral_diagonal hC.isHermitian e, Finset.mul_sum] + apply Finset.sum_congr rfl + intro i _ + dsimp [eig, b] + ring + +end MatchingEntropyBounds + +end + +end OAI diff --git a/lean/OAI/Combinatorics/MatchingPSD/AdmissiblePoints.lean b/lean/OAI/Combinatorics/MatchingPSD/AdmissiblePoints.lean new file mode 100644 index 0000000000000000000000000000000000000000..5eeb79db7080158b6e50e66f016d12b747d0932e --- /dev/null +++ b/lean/OAI/Combinatorics/MatchingPSD/AdmissiblePoints.lean @@ -0,0 +1,54 @@ +import OAI.Combinatorics.MatchingPSD.CrossSelection + +namespace OAI + +namespace MatchingSmoothing +open scoped BigOperators +attribute [local instance] Classical.propDecidable + +lemma triple_pairing_five {s : ℕ} (hs : 1 ≤ s) (j : Fin 5) : + ∃ M : Pairing (TripleVertices s), crossVector tripleColor M = + (![![1,0,0], ![0,1,1], ![3,0,0], ![1,2,0], ![1,0,2]] j : Fin 3 → ℝ) := by + have hex (E : Fin 6 → ℕ) (he : endpointSizes E = ![2*s+1,2*s+1,2*s]) : + ∃ M : Pairing (TripleVertices s), crossVector tripleColor M = + (fun i => (![E 1,E 2,E 4] i : ℝ)) := by + obtain ⟨M,hM⟩ := exists_pairing_of_endpoints tripleColor E (by rw [tripleColor_histogram, he]) + exact ⟨M,funext hM⟩ + fin_cases j + · obtain ⟨M,hM⟩ := hex ![s,1,0,s,0,s] (by ext i; fin_cases i <;> simp [endpointSizes]; omega) + exact ⟨M,by rw [hM]; ext i; fin_cases i <;> simp⟩ + · obtain ⟨M,hM⟩ := hex ![s,0,1,s,1,s-1] (by ext i; fin_cases i <;> simp [endpointSizes]; omega) + exact ⟨M,by rw [hM]; ext i; fin_cases i <;> simp⟩ + · obtain ⟨M,hM⟩ := hex ![s-1,3,0,s-1,0,s] (by ext i; fin_cases i <;> simp [endpointSizes] <;> omega) + exact ⟨M,by rw [hM]; ext i; fin_cases i <;> simp⟩ + · obtain ⟨M,hM⟩ := hex ![s-1,1,2,s,0,s-1] (by ext i; fin_cases i <;> simp [endpointSizes] <;> omega) + exact ⟨M,by rw [hM]; ext i; fin_cases i <;> simp⟩ + · obtain ⟨M,hM⟩ := hex ![s,1,0,s-1,2,s-1] (by ext i; fin_cases i <;> simp [endpointSizes] <;> omega) + exact ⟨M,by rw [hM]; ext i; fin_cases i <;> simp⟩ + +lemma triple_pairing_grid {s l d : ℕ} (hs : 2*l*d ≤ s) (k : Fin 3 → Fin (d+1)) : + ∃ M : Pairing (TripleVertices s), crossVector tripleColor M = + (fun a => (![1,0,0] a : ℝ) + (2*l:ℝ)*(k a:ℝ)) := by + let E : Fin 6 → ℕ := ![s-l*((k 0:ℕ)+k 1), 1+2*l*k 0, 2*l*k 1, + s-l*((k 0:ℕ)+k 2), 2*l*k 2, s-l*((k 1:ℕ)+k 2)] + have hk (a : Fin 3) : (k a : ℕ) ≤ d := Nat.le_of_lt_succ (k a).isLt + have hle (a b : Fin 3) : l*((k a:ℕ)+k b) ≤ s := by + calc + _ ≤ l*(d+d) := Nat.mul_le_mul_left l (Nat.add_le_add (hk a) (hk b)) + _ = 2*l*d := by ring + _ ≤ s := hs + have he : endpointSizes E = ![2*s+1,2*s+1,2*s] := by + ext i + fin_cases i <;> simp [endpointSizes, E] + · have h := Nat.sub_add_cancel (hle 0 1); nlinarith + · have h := Nat.sub_add_cancel (hle 0 2); nlinarith + · have h := Nat.sub_add_cancel (hle 1 2); nlinarith + obtain ⟨M,hM⟩ := exists_pairing_of_endpoints tripleColor E (by rw [tripleColor_histogram, he]) + refine ⟨M,?_⟩ + funext i + rw [crossVector, hM] + fin_cases i <;> simp [E, Nat.cast_add, Nat.cast_mul] + +end MatchingSmoothing + +end OAI diff --git a/lean/OAI/Combinatorics/MatchingPSD/AdmissibleTables.lean b/lean/OAI/Combinatorics/MatchingPSD/AdmissibleTables.lean new file mode 100644 index 0000000000000000000000000000000000000000..1f73682eaeb1d7fc78a713f632e8f1f7330beb42 --- /dev/null +++ b/lean/OAI/Combinatorics/MatchingPSD/AdmissibleTables.lean @@ -0,0 +1,85 @@ +import OAI.Combinatorics.MatchingPSD.GlobalGeometry + +namespace OAI + +universe u_1 u_2 u_3 u_4 + +namespace MatchingSmoothing +open scoped BigOperators +attribute [local instance] Classical.propDecidable + +section ColorTransport +variable {A : Type u_1} {B : Type u_2} {C : Type u_3} [Fintype A] [Fintype B] [Fintype C] [DecidableEq C] +noncomputable def colorEquiv (f : A → C) (g : B → C) (h : histogram f = histogram g) : A ≃ B := + (Equiv.sigmaFiberEquiv f).symm.trans + ((Equiv.sigmaCongrRight (fun c => Fintype.equivOfCardEq (congrFun h c))).trans + (Equiv.sigmaFiberEquiv g)) + +omit [Fintype C] in +lemma colorEquiv_spec (f : A → C) (g : B → C) (h : histogram f = histogram g) (a : A) : + g (colorEquiv f g h a) = f a := by + exact (Fintype.equivOfCardEq (congrFun h (f a)) ⟨a,rfl⟩).property +end ColorTransport + +def typePair : Fin 6 → Fin 3 × Fin 3 := ![(0,0),(0,1),(0,2),(1,1),(1,2),(2,2)] +abbrev TypedEdges (E : Fin 6 → ℕ) := (t : Fin 6) × Fin (E t) +def edgeColor (E : Fin 6 → ℕ) : TypedEdges E × Bool → Fin 3 := + fun v => if v.2 then (typePair v.1.1).2 else (typePair v.1.1).1 + +def endpointSizes (E : Fin 6 → ℕ) : Fin 3 → ℕ := + ![2*E 0+E 1+E 2, E 1+2*E 3+E 4, E 2+E 4+2*E 5] + +lemma edgeColor_histogram (E : Fin 6 → ℕ) : histogram (edgeColor E) = endpointSizes E := by + funext c + apply Nat.cast_injective (R := ℝ) + rw [histogram_cast_sum] + simp only [Fintype.sum_prod_type, Fintype.sum_sigma, Fintype.sum_bool] + fin_cases c <;> simp [edgeColor, endpointSizes, typePair, Fin.sum_univ_succ] <;> ring + +lemma edgeColor_cross (E : Fin 6 → ℕ) (i : Fin 3) : + crossCoordinate (edgeColor E) i (standardPairing (H := TypedEdges E)) = + (![E 1,E 2,E 4] i : ℝ) := by + simp only [crossCoordinate, tableCoordinate, Fintype.sum_prod_type, + Fintype.sum_sigma, Fintype.sum_bool] + fin_cases i <;> simp [crossPair, standardPairing, edgeColor, typePair, Fin.sum_univ_succ] + +lemma exists_pairing_of_endpoints {V : Type u_4} [Fintype V] + (z : V → Fin 3) (E : Fin 6 → ℕ) (hz : histogram z = endpointSizes E) : + ∃ M : Pairing V, ∀ i : Fin 3, crossCoordinate z i M = (![E 1,E 2,E 4] i : ℝ) := by + let e := colorEquiv (edgeColor E) z ((edgeColor_histogram E).trans hz.symm) + have he : z ∘ e = edgeColor E := funext (colorEquiv_spec _ _ _) + refine ⟨Pairing.transport e standardPairing, ?_⟩ + intro i + rw [crossCoordinate, tableCoordinate_transport, he] + exact edgeColor_cross E i + +abbrev TripleVertices (s : ℕ) := (Fin (2*s+1) ⊕ Fin (2*s+1)) ⊕ (Fin s × Bool) +def tripleColor {s : ℕ} : TripleVertices s → Fin 3 := + Sum.elim (Sum.elim (fun _ => 0) (fun _ => 1)) (fun _ => 2) + +lemma tripleColor_histogram (s : ℕ) : + histogram (@tripleColor s) = ![2*s+1,2*s+1,2*s] := by + funext c + apply Nat.cast_injective (R := ℝ) + rw [histogram_cast_sum] + fin_cases c <;> simp [tripleColor, Fintype.sum_sum_type, Nat.cast_add, Nat.cast_mul]; ring + +lemma triple_card (s : ℕ) : Fintype.card (TripleVertices s) = 2*(3*s+1) := by + simp only [TripleVertices, Fintype.card_sum, Fintype.card_fin, Fintype.card_prod, + Fintype.card_bool] + omega + +noncomputable def tripleEquiv (s : ℕ) : TripleVertices s ≃ Vertices (3*s+1) := + Fintype.equivOfCardEq (by + change Fintype.card (TripleVertices s) = Fintype.card (Fin (3*s+1) × Bool) + rw [triple_card, Fintype.card_prod, Fintype.card_fin, Fintype.card_bool] + omega) + +lemma triple_histogram_pos {s : ℕ} (hs : 0 < s) (i : Fin 3) : + 0 < histogram (@tripleColor s) i := by + rw [tripleColor_histogram] + fin_cases i <;> simp; omega + +end MatchingSmoothing + +end OAI diff --git a/lean/OAI/Combinatorics/MatchingPSD/AffineCertificate.lean b/lean/OAI/Combinatorics/MatchingPSD/AffineCertificate.lean new file mode 100644 index 0000000000000000000000000000000000000000..3d2f4f7ad939f35110ea73b2529eed718164923f --- /dev/null +++ b/lean/OAI/Combinatorics/MatchingPSD/AffineCertificate.lean @@ -0,0 +1,53 @@ +import Mathlib +import OAI.Combinatorics.MatchingPSD.PSDDuality +import OAI.Combinatorics.MatchingPSD.AffineSums + +namespace OAI + +namespace AffinePSD +open Matrix Finset +open scoped BigOperators +variable {I R : Type*} [Fintype I] [Fintype R] [DecidableEq R] + +lemma affine_slack_certificate (L : AffineSubspace ℝ (Matrix R R ℝ)) + (B : I → Matrix R R ℝ) (hB : ∀ i, (B i).PosSemidef) (hBL : ∀ i, B i ∈ L) + (f : Matrix R R ℝ →ᵃ[ℝ] ℝ) + (hn : ∀ X ∈ L, X.PosSemidef → 0 ≤ f X) + (i₀ : I) (hz : f (B i₀) = 0) : + ∃ A : Matrix R R ℝ, A.PosSemidef ∧ ∀ i, (A * B i).trace = f (B i) := by + classical + suffices ∃ A : Matrix R R ℝ, A.PosSemidef ∧ evaluation B A = fun i => f (B i) by + obtain ⟨A, hA, he⟩ := this + exact ⟨A, hA, fun i => congrFun he i⟩ + apply exists_psd_evaluation B hB + intro c hc + let s : ℝ := ∑ i, c i + let t : ℝ := |s| + 1 + let q : ℝ := s + t + have ht : 0 ≤ t := by dsimp [t]; positivity + have hq : 0 < q := by dsimp [q, t]; linarith [neg_abs_le s] + let w : I → ℝ := fun i => (c i + if i = i₀ then t else 0) / q + have hw : ∑ i, w i = 1 := by + simp only [w, ← Finset.sum_div, Finset.sum_add_distrib] + simpa only [Finset.sum_ite_eq', Finset.mem_univ, ite_true, q, s] using div_self hq.ne' + have hmatrix : ∑ i, w i • B i = q⁻¹ • ((∑ i, c i • B i) + t • B i₀) := by + simp only [w, div_eq_inv_mul, mul_smul, ← Finset.smul_sum, add_smul, + Finset.sum_add_distrib] + congr 1 + simp + have hpos : (∑ i, w i • B i).PosSemidef := by + rw [hmatrix] + exact (hc.add ((hB i₀).smul ht)).smul (inv_nonneg.mpr hq.le) + have hnonneg := hn _ (affine_sum_mem L B hBL w hw) hpos + rw [affine_sum_apply f B w hw] at hnonneg + have hvalue : ∑ i, w i • f (B i) = (∑ i, c i * f (B i)) / q := by + simp only [w, smul_eq_mul, add_div, add_mul, Finset.sum_add_distrib, + div_mul_eq_mul_div, ← Finset.sum_div] + simp [hz] + rw [hvalue] at hnonneg + have hh := (le_div_iff₀ hq).mp hnonneg + simpa using hh + +end AffinePSD + +end OAI diff --git a/lean/OAI/Combinatorics/MatchingPSD/AffineFactorization.lean b/lean/OAI/Combinatorics/MatchingPSD/AffineFactorization.lean new file mode 100644 index 0000000000000000000000000000000000000000..9ea579a2b9c680634ae5823a5b4dff7e419f19a6 --- /dev/null +++ b/lean/OAI/Combinatorics/MatchingPSD/AffineFactorization.lean @@ -0,0 +1,59 @@ +import Mathlib +import OAI.Combinatorics.MatchingPSD.AffineCertificate +import OAI.Combinatorics.MatchingPSD.AffineSlacks +import OAI.Combinatorics.MatchingPSD.TightMatchings +import OAI.Combinatorics.MatchingPSD.NormalizedFactors + +namespace OAI + +namespace PerfectMatchingPSD +open MatchingSmoothing Finset Matrix +open scoped BigOperators + +theorem affineLift_hasFactorization {n r : ℕ} (hn : 4 ≤ n) (he : Even n) + (h : HasAffineLift n r) : HasFactorization n r := by + classical + obtain ⟨L, T, hT⟩ := h + have hvertex (M : PerfectMatching n) : ∃ X : Matrix (Fin r) (Fin r) ℝ, + X ∈ L ∧ X.PosSemidef ∧ T X = matchingPoint M := by + have hm : matchingPoint M ∈ matchingPolytope n := + subset_convexHull ℝ _ (Set.mem_range_self M) + rw [← hT] at hm + obtain ⟨X, hX, heq⟩ := hm + exact ⟨X, hX.1, hX.2, heq⟩ + choose B hBL hB hBT using hvertex + have hrow (i : Row n) : ∃ A : Matrix (Fin r) (Fin r) ℝ, + A.PosSemidef ∧ ∀ M, (A * B M).trace = slack i M := by + obtain ⟨M₀, hzero⟩ := row_has_tight_matching hn he i + have hnonneg (X : Matrix (Fin r) (Fin r) ℝ) (hXL : X ∈ L) + (hXP : X.PosSemidef) : 0 ≤ ((slackAffine i).comp T) X := by + apply slackAffine_nonneg + rw [← hT] + exact ⟨X, ⟨hXL, hXP⟩, rfl⟩ + have hz : ((slackAffine i).comp T) (B M₀) = 0 := by + simpa only [AffineMap.comp_apply, hBT, slackAffine_vertex] using hzero + obtain ⟨A, hA, hAB⟩ := AffinePSD.affine_slack_certificate L B hB hBL + ((slackAffine i).comp T) hnonneg M₀ hz + refine ⟨A, hA, fun M => ?_⟩ + simpa only [AffineMap.comp_apply, hBT, slackAffine_vertex] using hAB M + choose A hA hAB using hrow + exact ⟨A, B, hA, hB, fun i M => (hAB i M).symm⟩ + +lemma factorization_order_pos {n r : ℕ} (hn : 1 ≤ n) (he : Even n) + (h : HasFactorization n r) : 0 < r := by + classical + by_contra hr + have hr0 : r = 0 := by omega + subst r + obtain ⟨M⟩ := perfectMatching_nonempty he + let v : Fin n := ⟨0, by omega⟩ + have hc := M.2 v + obtain ⟨e, heq⟩ := Finset.card_eq_one.mp hc + have heM : e ∈ M.1 := (Finset.mem_filter.mp (heq.symm ▸ Finset.mem_singleton_self e)).1 + obtain ⟨A, B, hA, hB, hf⟩ := h + have hz := hf (Sum.inl e) M + simp [slack, heM, Matrix.trace] at hz + +end PerfectMatchingPSD + +end OAI diff --git a/lean/OAI/Combinatorics/MatchingPSD/AffineLift.lean b/lean/OAI/Combinatorics/MatchingPSD/AffineLift.lean new file mode 100644 index 0000000000000000000000000000000000000000..b7d2bde728912655ba2dde4eda5c576d3eb4ac01 --- /dev/null +++ b/lean/OAI/Combinatorics/MatchingPSD/AffineLift.lean @@ -0,0 +1,26 @@ +import Mathlib +import OAI.Combinatorics.MatchingPSD.AffineFactorization +import OAI.Combinatorics.MatchingPSD.Main + +namespace OAI + +namespace PerfectMatchingPSD +open MatchingSmoothing Finset Matrix +open scoped BigOperators + +theorem affine_lift_lower_bound : + ∀ C : ℝ, 0 < C → ∃ n₀ : ℕ, 4 ≤ n₀ ∧ + ∀ n : ℕ, n₀ ≤ n → Even n → ∀ r : ℕ, + HasAffineLift n r → (n : ℝ) ^ C < (r : ℝ) := by + intro C hC + obtain ⟨n₀, hn₀, hmain⟩ := main C hC + refine ⟨n₀, hn₀, ?_⟩ + intro n hn he r h + have hn4 : 4 ≤ n := hn₀.trans hn + have hf := affineLift_hasFactorization hn4 he h + have hr := factorization_order_pos (by omega) he hf + exact (hmain n hn he).trans_le (by exact_mod_cast psdRank_le hr hf) + +end PerfectMatchingPSD + +end OAI diff --git a/lean/OAI/Combinatorics/MatchingPSD/AffineModel.lean b/lean/OAI/Combinatorics/MatchingPSD/AffineModel.lean new file mode 100644 index 0000000000000000000000000000000000000000..b430adde00c2940e015d368128ae8993a5b23328 --- /dev/null +++ b/lean/OAI/Combinatorics/MatchingPSD/AffineModel.lean @@ -0,0 +1,22 @@ +import Mathlib +import OAI.Combinatorics.MatchingPSD.Model + +namespace OAI + +namespace PerfectMatchingPSD + +noncomputable def matchingPoint {n : ℕ} (M : PerfectMatching n) : Edge n → ℝ := by + classical + exact fun e => if e ∈ M.1 then 1 else 0 + +noncomputable def matchingPolytope (n : ℕ) : Set (Edge n → ℝ) := + convexHull ℝ (Set.range (matchingPoint (n := n))) + +def HasAffineLift (n r : ℕ) : Prop := + ∃ (L : AffineSubspace ℝ (Matrix (Fin r) (Fin r) ℝ)) + (T : Matrix (Fin r) (Fin r) ℝ →ᵃ[ℝ] (Edge n → ℝ)), + T '' {X | X ∈ L ∧ X.PosSemidef} = matchingPolytope n + +end PerfectMatchingPSD + +end OAI diff --git a/lean/OAI/Combinatorics/MatchingPSD/AffineSlacks.lean b/lean/OAI/Combinatorics/MatchingPSD/AffineSlacks.lean new file mode 100644 index 0000000000000000000000000000000000000000..b118e8178f30f7c9372a81f01a50a913c7ce319f --- /dev/null +++ b/lean/OAI/Combinatorics/MatchingPSD/AffineSlacks.lean @@ -0,0 +1,51 @@ +import Mathlib +import OAI.Combinatorics.MatchingPSD.AffineModel +import OAI.Combinatorics.MatchingPSD.FiniteFactorization + +namespace OAI + +namespace PerfectMatchingPSD +open MatchingSmoothing Finset Matrix +open scoped BigOperators + +noncomputable def slackAffine {n : ℕ} (i : Row n) : (Edge n → ℝ) →ᵃ[ℝ] ℝ := by + classical + cases i with + | inl e => exact (LinearMap.proj e).toAffineMap + | inr U => + exact (∑ e : Edge n, if Crosses U.1 e then LinearMap.proj e else 0).toAffineMap - + AffineMap.const ℝ (Edge n → ℝ) 1 + +lemma slackAffine_vertex {n : ℕ} (i : Row n) (M : PerfectMatching n) : + slackAffine i (matchingPoint M) = slack i M := by + classical + cases i with + | inl e => rfl + | inr U => + simp only [slackAffine, AffineMap.coe_sub, Pi.sub_apply, AffineMap.const_apply, + LinearMap.coe_toAffineMap, slack] + congr 1 + rw [LinearMap.sum_apply] + calc + _ = ∑ e : Edge n, if Crosses U.1 e ∧ e ∈ M.1 then (1 : ℝ) else 0 := by + apply Finset.sum_congr rfl + intro e _ + by_cases h : Crosses U.1 e <;> simp [h, matchingPoint] + _ = _ := by + simp only [Finset.sum_boole, crossingCount] + apply congrArg (fun s : Finset (Edge n) => (s.card : ℝ)) + ext e + simp [and_comm] + +lemma slackAffine_nonneg {n : ℕ} (i : Row n) {x : Edge n → ℝ} + (hx : x ∈ matchingPolytope n) : 0 ≤ slackAffine i x := by + have hc : Convex ℝ {x : Edge n → ℝ | 0 ≤ slackAffine i x} := by + exact (convex_Ici (0 : ℝ)).affine_preimage (slackAffine i) + apply convexHull_min _ hc hx + rintro _ ⟨M, rfl⟩ + rw [Set.mem_ofPred_eq, slackAffine_vertex] + exact slack_nonneg i M + +end PerfectMatchingPSD + +end OAI diff --git a/lean/OAI/Combinatorics/MatchingPSD/AffineSums.lean b/lean/OAI/Combinatorics/MatchingPSD/AffineSums.lean new file mode 100644 index 0000000000000000000000000000000000000000..0277250880d0e42c80c99ee7f004c0ba088688ba --- /dev/null +++ b/lean/OAI/Combinatorics/MatchingPSD/AffineSums.lean @@ -0,0 +1,28 @@ +import Mathlib + +namespace OAI + +namespace AffinePSD +open Matrix Finset +open scoped BigOperators +variable {I R : Type*} [Fintype I] [Fintype R] [DecidableEq R] + +lemma affine_sum_mem {V : Type*} [AddCommGroup V] [Module ℝ V] + (L : AffineSubspace ℝ V) (p : I → V) (hp : ∀ i, p i ∈ L) + (w : I → ℝ) (hw : ∑ i, w i = 1) : ∑ i, w i • p i ∈ L := by + rw [← Finset.affineCombination_eq_linear_combination univ p w hw] + exact (affineSpan_le.mpr (Set.range_subset_iff.mpr hp)) + (affineCombination_mem_affineSpan hw p) + +lemma affine_sum_apply {V W : Type*} [AddCommGroup V] [Module ℝ V] + [AddCommGroup W] [Module ℝ W] (f : V →ᵃ[ℝ] W) (p : I → V) + (w : I → ℝ) (hw : ∑ i, w i = 1) : + f (∑ i, w i • p i) = ∑ i, w i • f (p i) := by + rw [← Finset.affineCombination_eq_linear_combination univ p w hw, + Finset.map_affineCombination _ _ _ hw f, + Finset.affineCombination_eq_linear_combination _ _ _ hw] + rfl + +end AffinePSD + +end OAI diff --git a/lean/OAI/Combinatorics/MatchingPSD/BitTests.lean b/lean/OAI/Combinatorics/MatchingPSD/BitTests.lean new file mode 100644 index 0000000000000000000000000000000000000000..522e1bfdd3df135228279d0fb4590b19d303a7d8 --- /dev/null +++ b/lean/OAI/Combinatorics/MatchingPSD/BitTests.lean @@ -0,0 +1,84 @@ +import OAI.Combinatorics.MatchingPSD.SequentialTests + +namespace OAI + +universe u_1 + +namespace PerfectMatchingPSD +open Matrix +open scoped MatrixOrder +variable {R : Type u_1} [Fintype R] [DecidableEq R] + +lemma two_div_success {μ ε : ℝ} (hμ : 2 ≤ μ) (hε : 0 ≤ ε) (hub : μ ≤ 2+ε) : + 1-ε ≤ 2/μ := by + rw [le_div_iff₀ (by linarith : 0 < μ)] + have hh : ε ≤ ε*μ := by nlinarith + nlinarith + +lemma normalized_gauge_pair (G Q T : Matrix R R ℝ) (hu : IsUnit G) : + (G*Q*G*(G⁻¹*T*G⁻¹)).trace = (Q*T).trace := by + have hunit := (Matrix.isUnit_iff_isUnit_det G).mp hu + have hl : G⁻¹*G=1 := Matrix.nonsing_inv_mul G hunit + have hr : G*G⁻¹=1 := Matrix.mul_nonsing_inv G hunit + have he : G*Q*G*(G⁻¹*T*G⁻¹) = G*(Q*T)*G⁻¹ := by + calc + _ = G*Q*(G*G⁻¹)*T*G⁻¹ := by simp only [mul_assoc] + _ = _ := by rw [hr, mul_one]; simp only [mul_assoc] + rw [he, Matrix.trace_mul_cycle, hl, one_mul] + +lemma inverse_sqrt_congruence (D : Matrix R R ℝ) (hD : D.PosDef) : + (CFC.sqrt D)⁻¹ * D * (CFC.sqrt D)⁻¹ = 1 := by + let G := CFC.sqrt D + have hGG : G*G=D := CFC.sqrt_mul_sqrt_self D hD.posSemidef.nonneg + have hu : IsUnit G := (IsUnit.mul_iff.mp (hGG ▸ hD.isUnit)).1 + have hl : G⁻¹*G=1 := Matrix.nonsing_inv_mul G ((Matrix.isUnit_iff_isUnit_det G).mp hu) + have hr : G*G⁻¹=1 := Matrix.mul_nonsing_inv G ((Matrix.isUnit_iff_isUnit_det G).mp hu) + change G⁻¹*D*G⁻¹=1 + rw [← hGG, ← mul_assoc, hl, one_mul, hr] + +lemma states_of_domination {q : ℕ} + (Q : (Fin q → Bool) → Matrix R R ℝ) (T : Fin q → Bool → Matrix R R ℝ) + (D : Matrix R R ℝ) (hD : D.PosDef) + (hQ : ∀ y, (Q y).PosSemidef) (hT : ∀ i b, (T i b).PosSemidef) + (hdom : ∀ i, T i false + T i true ≤ D) + (ε : ℝ) (hε : 0 ≤ ε) + (htr : ∀ y, 2 ≤ (Q y*D).trace ∧ (Q y*D).trace ≤ 2+ε) + (hbit : ∀ y i, (Q y * T i (y i)).trace = 2) : + ∃ (ρ : (Fin q → Bool) → Matrix R R ℝ) (F : Fin q → Bool → Matrix R R ℝ), + (∀ y, (ρ y).PosSemidef) ∧ (∀ y, (ρ y).trace = 1) ∧ + (∀ i b, 0 ≤ F i b) ∧ (∀ i, F i false + F i true ≤ 1) ∧ + ∀ y i, 1-ε ≤ (ρ y*F i (y i)).trace := by + let G := CFC.sqrt D + have hG : G.PosSemidef := (CFC.sqrt_nonneg D).posSemidef + have hGG : G*G=D := CFC.sqrt_mul_sqrt_self D hD.posSemidef.nonneg + have hu : IsUnit G := (IsUnit.mul_iff.mp (hGG ▸ hD.isUnit)).1 + have hGi : G⁻¹.PosSemidef := hG.inv + let μ := fun y => (Q y*D).trace + have hμ (y : Fin q → Bool) : 0 < μ y := lt_of_lt_of_le (by norm_num) (htr y).1 + refine ⟨fun y => (μ y)⁻¹ • (G*Q y*G), fun i b => G⁻¹*T i b*G⁻¹, + ?_, ?_, ?_, ?_, ?_⟩ + · intro y + apply Matrix.PosSemidef.smul _ (le_of_lt (inv_pos.mpr (hμ y))) + simpa only [hG.isHermitian.eq] using (hQ y).conjTranspose_mul_mul_same G + · intro y + rw [Matrix.trace_smul, Matrix.trace_mul_cycle, hGG, Matrix.trace_mul_comm] + change (μ y)⁻¹ * μ y = 1 + exact inv_mul_cancel₀ (ne_of_gt (hμ y)) + · intro i b + apply Matrix.PosSemidef.nonneg + simpa only [hGi.isHermitian.eq] using (hT i b).conjTranspose_mul_mul_same G⁻¹ + · intro i + have hg := congruence_mono (hdom i) G⁻¹ + have hGit : (G⁻¹)ᵀ=G⁻¹ := hGi.isHermitian.eq + rw [hGit, inverse_sqrt_congruence D hD, mul_add, add_mul] at hg + exact hg + · intro y i + rw [smul_mul_assoc, Matrix.trace_smul, normalized_gauge_pair G (Q y) (T i (y i)) hu, + hbit y i] + change 1-ε ≤ (μ y)⁻¹*2 + rw [mul_comm, ← div_eq_mul_inv] + exact two_div_success (htr y).1 hε (htr y).2 + +end PerfectMatchingPSD + +end OAI diff --git a/lean/OAI/Combinatorics/MatchingPSD/CellAverages.lean b/lean/OAI/Combinatorics/MatchingPSD/CellAverages.lean new file mode 100644 index 0000000000000000000000000000000000000000..ee58c42d1e7418c7bd71423cf5bc5fb5cf22310d --- /dev/null +++ b/lean/OAI/Combinatorics/MatchingPSD/CellAverages.lean @@ -0,0 +1,74 @@ +import OAI.Combinatorics.MatchingPSD.CutGeometry + +namespace OAI + +universe u_1 u_2 u_3 u_4 u_5 u_6 + +namespace MatchingSmoothing +open scoped BigOperators +attribute [local instance] Classical.propDecidable +section CellAverages +variable {A : Type u_1} {B : Type u_2} {C : Type u_3} {I : Type u_4} [Fintype A] [Fintype B] [Fintype C] [Fintype I] [DecidableEq I] + +noncomputable def extensionAverage (i : I) (f : Pairing ((A ⊕ B) ⊕ (I × C)) → ℝ) + (M : Pairing ((A ⊕ B) ⊕ C)) : ℝ := + 𝔼 N : {j : I // j ≠ i} → Pairing C, f (extendLocal i M N) + +noncomputable def cellAverage (i : I) (f : Pairing ((A ⊕ B) ⊕ (I × C)) → ℝ) + (x : Fin 3 → ℝ) : ℝ := + predicateAverage (fun M => crossVector threeColor M = x) (extensionAverage i f) + +omit [Fintype A] [Fintype B] in +lemma extensionAverage_relabel (i : I) (p : Equiv.Perm ((A ⊕ B) ⊕ C)) + (f : Pairing ((A ⊕ B) ⊕ (I × C)) → ℝ) (M : Pairing ((A ⊕ B) ⊕ C)) : + extensionAverage i f (Pairing.relabel p M) = + extensionAverage i (fun N => f (Pairing.relabel (liftLocal i p) N)) M := by + simp only [extensionAverage, extendLocal_relabel] + +lemma expect_pair_product {X : Type u_5} {Y : Type u_6} [Fintype X] [Fintype Y] (f : X × Y → ℝ) : + (𝔼 p : X × Y, f p) = 𝔼 x : X, 𝔼 y : Y, f (x,y) := by + rw [← Finset.univ_product_univ, Finset.expect_product] + +lemma cellAverage_star (i : I) (f : Pairing ((A ⊕ B) ⊕ (I × C)) → ℝ) (x : ℝ) : + cellAverage i f ![x,0,0] = + 𝔼 M : {M : Pairing (A ⊕ B) // tableCoordinate abColor (0,1) M = x}, + 𝔼 N : I → Pairing C, f (Pairing.sum M.1 (Pairing.cellwise N)) := by + classical + rw [cellAverage, predicateAverage_eq_expect] + have he := Fintype.expect_equiv (starFiberEquiv (A := A) (B := B) (C := C) x) + (fun p => extensionAverage i f (Pairing.sum p.1.1 p.2)) + (fun p => extensionAverage i f p.1) (fun _ => rfl) + calc + _ = 𝔼 p : {M : Pairing (A ⊕ B) // tableCoordinate abColor (0,1) M = x} × Pairing C, + extensionAverage i f (Pairing.sum p.1.1 p.2) := by + convert he.symm using 1 + congr 1 + ext; simp + _ = _ := ?_ + rw [expect_pair_product] + apply Finset.expect_congr rfl + intro M _ + simp only [extensionAverage] + calc + _ = 𝔼 p : Pairing C × ({j : I // j ≠ i} → Pairing C), + f (extendLocal i (Pairing.sum M.1 p.1) p.2) := by + convert (expect_pair_product (fun p : Pairing C × ({j : I // j ≠ i} → Pairing C) => + f (extendLocal i (Pairing.sum M.1 p.1) p.2))).symm using 1 + _ = _ := (Fintype.expect_equiv (Equiv.piSplitAt i (fun _ : I => Pairing C)) + (fun N => f (Pairing.sum M.1 (Pairing.cellwise N))) + (fun p => f (extendLocal i (Pairing.sum M.1 p.1) p.2)) + (fun N => by rw [Equiv.piSplitAt_apply, extendLocal_sum])).symm + +lemma cellAverage_const (i : I) (f : Pairing ((A ⊕ B) ⊕ (I × C)) → ℝ) + (x : Fin 3 → ℝ) (c : ℝ) (hM : ∃ M : Pairing ((A ⊕ B) ⊕ C), crossVector threeColor M = x) + [Nonempty (Pairing C)] + (hf : ∀ M, crossVector threeColor M = x → ∀ N, f (extendLocal i M N) = c) : + cellAverage i f x = c := by + apply predicateAverage_of_constant _ _ hM + intro M hM + simp only [extensionAverage, hf M hM, Finset.expect_const, Finset.univ_nonempty] + +end CellAverages +end MatchingSmoothing + +end OAI diff --git a/lean/OAI/Combinatorics/MatchingPSD/CellDecoder.lean b/lean/OAI/Combinatorics/MatchingPSD/CellDecoder.lean new file mode 100644 index 0000000000000000000000000000000000000000..27162cfd387bcc77832a05067ae498c9af120e1e --- /dev/null +++ b/lean/OAI/Combinatorics/MatchingPSD/CellDecoder.lean @@ -0,0 +1,113 @@ +import OAI.Combinatorics.MatchingPSD.DominationDecoder + +namespace OAI + +namespace MatchingInterpolation +open MatchingSmoothing PerfectMatchingPSD Matrix +open scoped BigOperators MatrixOrder +attribute [local instance] Classical.propDecidable + +noncomputable def cutValue (b : Bool) (x : Point) : ℝ := x 0+x (if b then 2 else 1)-1 + +lemma cell_trace_value {s q r : ℕ} + (Q : (Fin q → Bool) → Matrix (Fin r) (Fin r) ℝ) + (B : Pairing (GlobalVertices s q) → Matrix (Fin r) (Fin r) ℝ) + (hpair : ∀ y M, (Q y*B M).trace = tableCoordinate (globalCutColor y) (true,false) M-1) + (y : Fin q → Bool) (i : Fin q) (x : Point) + (hx : ∃ M : Pairing (TripleVertices s), crossVector threeColor M=x) : + (Q y*cellMatrix i B x).trace = cutValue (y i) x := by + have : Nonempty (Pairing (Fin s × Bool)) := ⟨standardPairing⟩ + rw [trace_cellMatrix] + apply cellAverage_const i _ x _ hx + intro M hM N + rw [hpair, extendLocal_cut, hM] + rfl + +lemma cutValue_p (b : Bool) : cutValue b (origin+dirP) = 0 := by + cases b <;> norm_num [cutValue, origin, dirP, Matrix.cons_val_two, Matrix.vecHead, Matrix.vecTail] +lemma cutValue_star (b : Bool) : cutValue b (origin+dirStar) = 2 := by + cases b <;> norm_num [cutValue, origin, dirStar, Matrix.cons_val_two, Matrix.vecHead, Matrix.vecTail] +lemma cutValue_bit (b : Bool) : cutValue b (if b then origin+dirB else origin+dirA) = 2 := by + cases b <;> norm_num [cutValue, origin, dirA, dirB, Matrix.cons_val_two, Matrix.vecHead, Matrix.vecTail] + +lemma cutValue_grid {d : ℕ} {L : ℝ} (hL : 0 ≤ L) (g : GridIndex d) (b : Bool) : + cutValue b (scaledNode L g) ≤ 2*(d:ℝ)*L := by + have hk (a : Fin 3) : (g a : ℝ) ≤ (d:ℝ) := by exact_mod_cast (Nat.le_of_lt_succ (g a).isLt) + have h0 := mul_le_mul_of_nonneg_left (hk 0) hL + have h1 := mul_le_mul_of_nonneg_left (hk 1) hL + have h2 := mul_le_mul_of_nonneg_left (hk 2) hL + cases b <;> norm_num [cutValue, scaledNode, origin, Matrix.cons_val_two, Matrix.vecHead, Matrix.vecTail] <;> nlinarith + +lemma origin_star_eq : origin+dirStar = (![3,0,0] : Point) := by + ext a + fin_cases a <;> norm_num [origin, dirStar] + +lemma weightMass_bound (d : ℕ) : ∃ c : ℝ, 0 < c ∧ ∀ L : ℝ, 1 ≤ L → + weightMass d L ≤ c/L^2 := by + obtain ⟨c,hc,hbound⟩ := weights_bound d + refine ⟨(Fintype.card (GridIndex d) : ℝ)*c, mul_pos (by positivity) hc, ?_⟩ + intro L hL + have he := Finset.sum_le_sum (s := Finset.univ) (fun g _ => hbound L hL g) + simpa only [weightMass, Finset.sum_const, Finset.card_univ, nsmul_eq_mul, mul_div_assoc] using he + +lemma cell_decoder {s q l r d : ℕ} (hs : 1 ≤ s) (hq : 1 ≤ q) (hsl : 2*l*d ≤ s) + (Q : (Fin q → Bool) → Matrix (Fin r) (Fin r) ℝ) + (B : Pairing (GlobalVertices s q) → Matrix (Fin r) (Fin r) ℝ) + (hQ : ∀ y, (Q y).PosSemidef) (hB : ∀ M, (B M).PosSemidef) + (hpair : ∀ y M, (Q y*B M).trace = tableCoordinate (globalCutColor y) (true,false) M-1) + (P : Fin q → Fin r → Fin r → Point → ℝ) + (hP : ∀ i u v, P i u v ∈ lowDegree coord d) + {η m δ : ℝ} (hη : 0 ≤ η) (hδ : 0 < δ) (hl : 0 < l) + (hm : ∀ y, (Q y).trace ≤ m) + (happrox : ∀ i u v t, |cellMatrix i B (samplePoint d (2*l) t) u v- + P i u v (samplePoint d (2*l) t)| ≤ η) + (hε : 0 ≤ (q:ℝ)*(weightMass d (2*l)*(2*d*(2*l))+ + (r:ℝ)*(6+weightMass d (2*l))*η*m)+δ*m) + (hsmall : (q:ℝ)*Real.sqrt ((q:ℝ)*(weightMass d (2*l)*(2*d*(2*l))+ + (r:ℝ)*(6+weightMass d (2*l))*η*m)+δ*m) ≤ 1/4) : + (2:ℝ)^q/2 ≤ r := by + let L : ℝ := 2*l + have hL : 0 < L := by dsimp [L]; positivity + let C := fun i => cellMatrix i B + have hC (i : Fin q) (x : Point) : (C i x).PosSemidef := cellMatrix_psd i B hB x + have hsamp (y : Fin q → Bool) (i : Fin q) (t : SampleIndex d) : + (Q y*C i (samplePoint d L t)).trace = cutValue (y i) (samplePoint d L t) := + cell_trace_value Q B hpair y i _ (sample_witness hs hsl t) + have hfive (y : Fin q → Bool) (i : Fin q) (j : Fin 5) : + (Q y*C i (specialPoint j)).trace = cutValue (y i) (specialPoint j) := hsamp y i (.inl j) + have hp (y : Fin q → Bool) (i : Fin q) : (Q y*C i (origin+dirP)).trace=0 := + (hfive y i 1).trans (cutValue_p _) + have hstar (y : Fin q → Bool) (i : Fin q) : (Q y*C i (origin+dirStar)).trace=2 := + (hfive y i 2).trans (cutValue_star _) + have hgrid (y : Fin q → Bool) (i : Fin q) (g : GridIndex d) : + (Q y*C i (scaledNode L g)).trace ≤ 2*(d:ℝ)*L := + (hsamp y i (.inr g)).le.trans (cutValue_grid hL.le g (y i)) + have hEex (i : Fin q) := interpolation_matrix_domination d (C i) (hC i) (P i) (hP i) + hL.ne' hη (fun j u v => happrox i u v (.inl j)) (fun g u v => happrox i u v (.inr g)) + choose E hE hdom hEb using hEex + let i₀ : Fin q := ⟨0,by omega⟩ + let S := C i₀ (origin+dirStar) + have hcommon (i : Fin q) : C i (origin+dirStar)=S := by + dsimp only [S,C] + rw [origin_star_eq] + exact cellMatrix_star i i₀ B 3 + let T := fun i (b : Bool) => if b then C i (origin+dirB) else C i (origin+dirA) + have hT (i : Fin q) (b : Bool) : (T i b).PosSemidef := by + cases b <;> exact hC i _ + have hTdom (i : Fin q) : T i false+T i true ≤ S+(2:ℝ) • C i (origin+dirP)+E i := by + change C i (origin+dirA)+C i (origin+dirB) ≤ S+(2:ℝ) • C i (origin+dirP)+E i + rw [← hcommon i] + exact hdom i + have hbit (y : Fin q → Bool) (i : Fin q) : (Q y*T i (y i)).trace=2 := by + cases hy : y i + · exact (hfive y i 3).trans (by rw [hy]; exact cutValue_bit false) + · exact (hfive y i 4).trans (by rw [hy]; exact cutValue_bit true) + have he (y : Fin q → Bool) (i : Fin q) : (Q y*E i).trace ≤ + weightMass d L*(2*(d:ℝ)*L)+(r:ℝ)*(6+weightMass d L)*η*m := by + simpa only [Fintype.card_fin] using hEb i (Q y) m (2*(d:ℝ)*L) (hm y) (hgrid y i) + simpa only [Fintype.card_fin] using domination_decoder Q T (fun i => C i (origin+dirP)) E S hQ hT + (fun i => hC i _) hE (hC i₀ _) hTdom hp (fun y => hstar y i₀) hbit hδ hm he hε hsmall + +end MatchingInterpolation + +end OAI diff --git a/lean/OAI/Combinatorics/MatchingPSD/CellLowerBound.lean b/lean/OAI/Combinatorics/MatchingPSD/CellLowerBound.lean new file mode 100644 index 0000000000000000000000000000000000000000..9f12e76f17140c82203aa7ae150461ae5c5d4db6 --- /dev/null +++ b/lean/OAI/Combinatorics/MatchingPSD/CellLowerBound.lean @@ -0,0 +1,91 @@ +import OAI.Combinatorics.MatchingPSD.CellDecoder + +namespace OAI + +namespace MatchingInterpolation +open MatchingSmoothing PerfectMatchingPSD Matrix +open scoped BigOperators MatrixOrder + +lemma interpolation_trace_error_bound (d : ℕ) {c L r η m : ℝ} + (hc : 0 ≤ c) (hL : 1 ≤ L) + (hw : weightMass d L ≤ c/L^2) (hnorm : r*η*m ≤ 1/L) : + weightMass d L*(2*(d:ℝ)*L)+r*(6+weightMass d L)*η*m ≤ + ((2*(d:ℝ)+1)*c+6)/L := by + have hLp : 0 < L := by linarith + have hwc : weightMass d L ≤ c := by + apply hw.trans + exact (div_le_self hc (by nlinarith : 1 ≤ L^2)) + have h1 := mul_le_mul_of_nonneg_right hw (show 0 ≤ 2*(d:ℝ)*L by positivity) + have h2 := mul_le_mul_of_nonneg_left hnorm (show 0 ≤ 6+weightMass d L by linarith [weightMass_nonneg d L]) + have h3 := mul_le_mul_of_nonneg_right (show 6+weightMass d L ≤ 6+c by linarith) (show 0 ≤ 1/L by positivity) + calc + _ = weightMass d L*(2*(d:ℝ)*L)+(6+weightMass d L)*(r*η*m) := by ring + _ ≤ (c/L^2)*(2*(d:ℝ)*L)+(6+c)*(1/L) := add_le_add h1 (h2.trans h3) + _ = _ := by field_simp; ring + +lemma sqrt_error_small {q D L ε : ℝ} (hq : 0 ≤ q) (hL : 0 < L) (hε : 0 ≤ ε) + (he : ε ≤ (q*D+1)/L) (hn : 16*q^2*(q*D+1) ≤ L) : + q*Real.sqrt ε ≤ 1/4 := by + have heL : ε*L ≤ q*D+1 := (le_div_iff₀ hL).mp he + have hmult := mul_le_mul_of_nonneg_left heL (show 0 ≤ 16*q^2 by positivity) + have h16 : 16*q^2*ε ≤ 1 := by + apply (mul_le_mul_iff_of_pos_right hL).mp + nlinarith [hmult.trans hn] + have hsq : (q*Real.sqrt ε)^2 = q^2*ε := by rw [mul_pow, Real.sq_sqrt hε] + have hn0 : 0 ≤ q*Real.sqrt ε := mul_nonneg hq (Real.sqrt_nonneg _) + nlinarith + +lemma normalized_eta {r m L : ℝ} (hr : 0 < r) (hm : 0 < m) (hL : 0 < L) : + r*(1/(r*m*L))*m = 1/L := by + field_simp [hr.ne', hm.ne', hL.ne'] + +lemma conditional_cell_lower_bound (K : ℕ) : + ∃ d H : ℕ, 0 < d ∧ ∃ D : ℝ, 0 < D ∧ + ∀ s q l r : ℕ, H ≤ 3*s+1 → 1 ≤ s → 1 ≤ q → 2*l*d ≤ s → 1 ≤ l → 0 < r → + ∀ m : ℝ, 0 < m → + ∀ (Q : Equiv.Perm (GlobalVertices s q) → (Fin q → Bool) → Matrix (Fin r) (Fin r) ℝ) + (B : Pairing (GlobalVertices s q) → Matrix (Fin r) (Fin r) ℝ), + (∀ a y, (Q a y).PosSemidef) → (∀ M, (B M).PosSemidef) → + (∀ a y, (Q a y).trace ≤ m) → (∀ M, (B M).trace ≤ (r:ℝ)) → + (∀ a y M, (Q a y*B (Pairing.relabel a M)).trace = + tableCoordinate (globalCutColor y) (true,false) M-1) → + (q:ℝ)*r^4*(Fintype.card (SampleIndex d))*((2*(3*s+1):ℝ)^(2*K))⁻¹ ≤ + (1/((r:ℝ)*m*(2*l)))^2 → + 16*(q:ℝ)^2*((q:ℝ)*D+1) ≤ 2*l → + (2:ℝ)^q/2 ≤ r := by + obtain ⟨d,H,hd,hgood⟩ := good_cell_polynomials K + obtain ⟨c,hc,hw⟩ := weightMass_bound d + let D := (2*(d:ℝ)+1)*c+6 + have hD : 0 < D := by dsimp [D]; positivity + refine ⟨d,H,hd,D,hD,?_⟩ + intro s q l r hH hs hq hsl hl hr m hm Q B hQ hB htrQ htrB hpair hnum hn + let L : ℝ := 2*l + have hL : 1 ≤ L := by dsimp [L]; exact_mod_cast (by omega : 1 ≤ 2*l) + have hLp : 0 < L := by linarith + have hrp : 0 < (r:ℝ) := by exact_mod_cast hr + let η := 1/((r:ℝ)*m*L) + let δ := 1/(L*m) + have hη : 0 ≤ η := by dsimp [η]; positivity + have hδ : 0 < δ := by dsimp [δ]; positivity + obtain ⟨a,P,hP,happrox⟩ := hgood s q l r hH hs hsl B hB htrB η hη hnum + let e := weightMass d L*(2*(d:ℝ)*L)+(r:ℝ)*(6+weightMass d L)*η*m + have hw0 := weightMass_nonneg d L + have he0 : 0 ≤ e := by dsimp [e]; positivity + have he : e ≤ D/L := interpolation_trace_error_bound d hc.le hL + (hw L hL) (le_of_eq (normalized_eta hrp hm hLp)) + have hδm : δ*m=1/L := by dsimp [δ]; field_simp [hLp.ne', hm.ne'] + have hε : 0 ≤ (q:ℝ)*e+δ*m := by positivity + have heps : (q:ℝ)*e+δ*m ≤ ((q:ℝ)*D+1)/L := by + have heq := mul_le_mul_of_nonneg_left he (Nat.cast_nonneg q) + rw [hδm] + calc + _ ≤ (q:ℝ)*(D/L)+1/L := add_le_add heq (le_refl (1/L)) + _ = _ := by ring + have hsmall := sqrt_error_small (Nat.cast_nonneg q) hLp hε heps hn + exact cell_decoder hs hq hsl (Q a) (fun M => B (Pairing.relabel a M)) + (hQ a) (fun M => hB _) (hpair a) P hP hη hδ (by omega) + (htrQ a) happrox hε hsmall + +end MatchingInterpolation + +end OAI diff --git a/lean/OAI/Combinatorics/MatchingPSD/ColorPolynomials.lean b/lean/OAI/Combinatorics/MatchingPSD/ColorPolynomials.lean new file mode 100644 index 0000000000000000000000000000000000000000..9854ec1b74ed9d925ddd9f2115492548ccc03e15 --- /dev/null +++ b/lean/OAI/Combinatorics/MatchingPSD/ColorPolynomials.lean @@ -0,0 +1,140 @@ +import OAI.Combinatorics.MatchingPSD.PartialColorings + +namespace OAI + +universe u_1 u_2 u_3 u_4 u_5 u_6 + +namespace MatchingSmoothing +attribute [local instance] Classical.propDecidable +section ColorPolynomials +variable {V : Type u_1} {C : Type u_2} [Fintype V] + +lemma colorAverage_recurrence (z : V → C) (l : List (V × V)) (e : V × V) + (he : e ∈ candidateEdges z (Pairing.edgeSupport l) (z e.1,z e.2)) + (M₀ : Pairing V) (h₀ : Pairing.ContainsList M₀ l) : + ((candidateEdges z (Pairing.edgeSupport l) (z e.1,z e.2)).card : ℝ) • + colorAverage z (Pairing.edgeMonomial (e::l)) = + (tableCoordinate z (z e.1,z e.2) - + (∑ v ∈ Pairing.edgeSupport l, + if z v = z e.1 ∧ z (M₀.1 v) = z e.2 then (1:ℝ) else 0) • 1) * + colorAverage z (Pairing.edgeMonomial l) := by + let S := candidateEdges z (Pairing.edgeSupport l) (z e.1,z e.2) + have hsum : (∑ f ∈ S, colorAverage z (Pairing.edgeMonomial (f::l))) = + ((S.card : ℕ) : ℝ) • colorAverage z (Pairing.edgeMonomial (e::l)) := by + calc + _ = ∑ _f ∈ S, colorAverage z (Pairing.edgeMonomial (e::l)) := by + apply Finset.sum_congr rfl + intro f hf + exact candidate_average_eq z l _ f e hf he + _ = _ := by + funext M + simp [Pi.smul_apply] + have hm : (∑ f ∈ S, Pairing.edgeMonomial (f::l)) = + Pairing.edgeMonomial l * ∑ f ∈ S, Pairing.edgeCoord f := by + simp only [Pairing.edgeMonomial_cons, ← Finset.sum_mul, mul_comm] + rw [← hsum, ← map_sum, hm, monomial_candidate_identity z l _ M₀ h₀, mul_comm] + apply colorAverage_mul_invariant + intro p + rw [map_sub, tableCoordinate_invariant, map_smul] + rfl + +lemma colorAverage_monomial_mem (z : V → C) (l : List (V × V)) : + colorAverage z (Pairing.edgeMonomial l) ∈ lowDegree (tableCoordinate z) l.length := by + induction l with + | nil => + simpa only [Pairing.edgeMonomial, List.map_nil, List.prod_nil, colorAverage_one, + List.length_nil] using one_mem_lowDegree (tableCoordinate z) 0 + | cons e l ih => + by_cases hc : ∃ M : Pairing V, Pairing.ContainsList M (e::l) + · obtain ⟨M₀, hm⟩ := hc + have h₀ : Pairing.ContainsList M₀ l := fun f hf => hm f (List.mem_cons_of_mem _ hf) + have hEdge : M₀.1 e.1 = e.2 := hm e (List.mem_cons_self) + by_cases hv : e.1 ∈ Pairing.edgeSupport l ∨ e.2 ∈ Pairing.edgeSupport l + · rw [Pairing.redundant_edgeMonomial hEdge h₀ hv] + exact lowDegree_mono _ (by simp) ih + · have he : e ∈ candidateEdges z (Pairing.edgeSupport l) (z e.1,z e.2) := by + apply (mem_candidateEdges _ _ _ _).mpr + refine ⟨fun h => hv (Or.inl h), fun h => hv (Or.inr h), ?_, rfl, rfl⟩ + intro heq + exact M₀.partner_ne e.1 (hEdge.trans heq.symm) + let D := ((candidateEdges z (Pairing.edgeSupport l) (z e.1,z e.2)).card : ℝ) + have hD : D ≠ 0 := by + apply Nat.cast_ne_zero.mpr + exact Finset.card_ne_zero.mpr ⟨e, he⟩ + have hr := colorAverage_recurrence z l e he M₀ h₀ + have hlin : tableCoordinate z (z e.1,z e.2) - + (∑ v ∈ Pairing.edgeSupport l, + if z v = z e.1 ∧ z (M₀.1 v) = z e.2 then (1:ℝ) else 0) • 1 ∈ + lowDegree (tableCoordinate z) 1 := + (lowDegree (tableCoordinate z) 1).sub_mem (coord_mem_lowDegree _ _) + ((lowDegree (tableCoordinate z) 1).smul_mem _ (one_mem_lowDegree _ _)) + have hmem := mul_mem_lowDegree (tableCoordinate z) hlin ih + rw [← hr] at hmem + change D • colorAverage z (Pairing.edgeMonomial (e::l)) ∈ + lowDegree (tableCoordinate z) (1+l.length) at hmem + have hh := (lowDegree (tableCoordinate z) (1+l.length)).smul_mem D⁻¹ hmem + simpa only [smul_smul, inv_mul_cancel₀ hD, one_smul, Nat.add_comm, + List.length_cons] using hh + · rw [Pairing.edgeMonomial_zero_of_unsatisfiable _ hc, map_zero] + exact Submodule.zero_mem _ + +lemma colorAverage_lowDegree (z : V → C) (d : ℕ) + (f : Pairing V → ℝ) (hf : f ∈ lowDegree Pairing.edgeCoord d) : + colorAverage z f ∈ lowDegree (tableCoordinate z) d := by + apply Submodule.span_induction (p := fun f _ => colorAverage z f ∈ + lowDegree (tableCoordinate z) d) _ _ _ _ hf + · rintro f ⟨l, hl, rfl⟩ + exact lowDegree_mono _ hl (colorAverage_monomial_mem z l) + · simp + · intro f g _ _ hf hg + simpa only [map_add] using (lowDegree (tableCoordinate z) d).add_mem hf hg + · intro c f _ hf + simpa only [map_smul] using (lowDegree (tableCoordinate z) d).smul_mem c hf + +end ColorPolynomials + +section Substitution +variable {E : Type u_3} {I : Type u_4} {X : Type u_5} {Y : Type u_6} + +lemma list_prod_mem_lowDegree (x : E → X → ℝ) (l : List I) (y : I → X → ℝ) + (hy : ∀ i, y i ∈ lowDegree x 1) : (l.map y).prod ∈ lowDegree x l.length := by + induction l with + | nil => exact one_mem_lowDegree x 0 + | cons i l ih => + simpa only [List.map_cons, List.prod_cons, List.length_cons, Nat.add_comm] using + mul_mem_lowDegree x (hy i) ih + +lemma lowDegree_substitute (x : E → X → ℝ) (y : I → X → ℝ) + (hy : ∀ i, y i ∈ lowDegree x 1) (d : ℕ) : lowDegree y d ≤ lowDegree x d := by + apply Submodule.span_le.mpr + rintro f ⟨l, hl, rfl⟩ + exact lowDegree_mono x hl (list_prod_mem_lowDegree x l y hy) + +lemma lowDegree_lift (x : E → X → ℝ) (d : ℕ) (f : X → ℝ) + (hf : f ∈ lowDegree x d) : + ∃ P ∈ lowDegree (fun e (v : E → ℝ) => v e) d, + ∀ a, f a = P (fun e => x e a) := by + induction hf using Submodule.span_induction with + | mem f hf => + obtain ⟨l, hl, rfl⟩ := hf + refine ⟨(l.map (fun e (v : E → ℝ) => v e)).prod, + Submodule.subset_span ⟨l, hl, rfl⟩, ?_⟩ + intro a + induction l with + | nil => rfl + | cons e l ih => + simp only [List.map_cons, List.prod_cons, Pi.mul_apply] + rw [ih (by simpa only [List.length_cons] using Nat.le_trans (Nat.le_succ _) hl)] + | zero => exact ⟨0, Submodule.zero_mem _, by simp⟩ + | add f g _ _ hf hg => + obtain ⟨P, hP, hp⟩ := hf + obtain ⟨Q, hQ, hq⟩ := hg + exact ⟨P+Q, Submodule.add_mem _ hP hQ, fun a => by simp [hp a, hq a]⟩ + | smul c f _ hf => + obtain ⟨P, hP, hp⟩ := hf + exact ⟨c • P, Submodule.smul_mem _ c hP, fun a => by simp [hp a]⟩ + +end Substitution +end MatchingSmoothing + +end OAI diff --git a/lean/OAI/Combinatorics/MatchingPSD/ColoringCounts.lean b/lean/OAI/Combinatorics/MatchingPSD/ColoringCounts.lean new file mode 100644 index 0000000000000000000000000000000000000000..a112afab918470834f7518e4dc9b260d7120459f --- /dev/null +++ b/lean/OAI/Combinatorics/MatchingPSD/ColoringCounts.lean @@ -0,0 +1,340 @@ +import OAI.Combinatorics.MatchingPSD.RepresentationDimension + +namespace OAI + +universe u_1 u_2 u_3 u_4 u_5 u_6 u_7 u_8 + +namespace MatchingSmoothing + +variable {α : Type u_1} {β : Type u_2} [Fintype α] [DecidableEq β] + +noncomputable def histogram (f : α → β) (b : β) : ℕ := + Fintype.card {a // f a = b} + +lemma sum_histogram [Fintype β] (f : α → β) : ∑ b, histogram f b = Fintype.card α := by + classical + simp only [histogram] + rw [← Fintype.card_sigma] + exact Fintype.card_congr (Equiv.sigmaFiberEquiv f) + +abbrev Colorings (α : Type u_3) (β : Type u_4) [Fintype α] [DecidableEq β] (s : β → ℕ) := + {f : α → β // histogram f = s} + +noncomputable instance coloringsFintype [Fintype β] (s : β → ℕ) : + Fintype (Colorings α β s) := Fintype.ofFinite _ + +noncomputable def fiberEquivOfHistogram {f g : α → β} (h : histogram f = histogram g) + (b : β) : {a // f a = b} ≃ {a // g a = b} := + Fintype.equivOfCardEq (congrFun h b) + +noncomputable def permOfHistogram {f g : α → β} (h : histogram f = histogram g) : + Equiv.Perm α := + (Equiv.sigmaFiberEquiv f).symm.trans + ((Equiv.sigmaCongrRight (fiberEquivOfHistogram h)).trans (Equiv.sigmaFiberEquiv g)) + +lemma permOfHistogram_spec {f g : α → β} (h : histogram f = histogram g) + (a : α) : g (permOfHistogram h a) = f a := by + exact (fiberEquivOfHistogram h (f a) ⟨a, rfl⟩).property + +lemma histogram_comp_perm (f : α → β) (σ : Equiv.Perm α) : + histogram (f ∘ σ) = histogram f := by + funext b + apply Fintype.card_congr + exact { toFun := fun x => ⟨σ x, x.property⟩ + invFun := fun y => ⟨σ.symm y, by simpa using y.property⟩ + left_inv := by intro x; ext; simp + right_inv := by intro x; ext; simp } + +noncomputable def fiberPermEquiv (f g : α → β) : + {σ : Equiv.Perm α // f ∘ σ = g} ≃ + (∀ b, {a // g a = b} ≃ {a // f a = b}) where + toFun σ b := + { toFun := fun x => ⟨σ.1 x, (congrFun σ.2 x).trans x.property⟩ + invFun := fun y => ⟨σ.1.symm y, by + exact (congrFun σ.2 (σ.1.symm y)).symm.trans (by simpa using y.property)⟩ + left_inv := by intro x; ext; simp + right_inv := by intro x; ext; simp } + invFun e := ⟨Equiv.ofFiberEquiv e, by + funext a; exact Equiv.ofFiberEquiv_map e a⟩ + left_inv σ := by apply Subtype.ext; ext a; rfl + right_inv e := by + funext b + apply Equiv.ext + rintro ⟨a, ha⟩ + subst b + rfl + +lemma card_colorings_mul_factorials [Fintype β] (f : α → β) : + Fintype.card (Colorings α β (histogram f)) * + (∏ b, (histogram f b).factorial) = (Fintype.card α).factorial := by + classical + let F : Equiv.Perm α → Colorings α β (histogram f) := + fun σ => ⟨f ∘ σ, histogram_comp_perm f σ⟩ + have hf (g : Colorings α β (histogram f)) : + Fintype.card {σ // F σ = g} = ∏ b, (histogram f b).factorial := by + let e₁ : {σ // F σ = g} ≃ {σ : Equiv.Perm α // f ∘ σ = g.1} := + Equiv.subtypeEquivRight (fun σ => Subtype.ext_iff) + rw [Fintype.card_congr e₁, Fintype.card_congr (fiberPermEquiv f g.1), + Fintype.card_pi] + apply Finset.prod_congr rfl + intro b _ + rw [Fintype.card_equiv (fiberEquivOfHistogram g.2 b)] + exact congrArg Nat.factorial (congrFun g.2 b) + have he := Fintype.card_congr (Equiv.sigmaFiberEquiv F) + rw [Fintype.card_sigma, Fintype.card_perm] at he + simpa only [hf, Finset.sum_const, Finset.card_univ, smul_eq_mul] using he + +lemma card_colorings_eq_multinomial [Fintype β] (f : α → β) : + Fintype.card (Colorings α β (histogram f)) = + Nat.multinomial Finset.univ (histogram f) := by + have h := card_colorings_mul_factorials f + rw [Nat.multinomial, sum_histogram f, ← h, Nat.mul_div_cancel] + exact Finset.prod_pos (by intro b _; exact Nat.factorial_pos _) + +lemma card_perm_color_fiber [DecidableEq α] [Fintype β] (f : α → β) (g : Colorings α β (histogram f)) : + Fintype.card {σ : Equiv.Perm α // f ∘ σ = g.1} = + ∏ b, (histogram f b).factorial := by + classical + rw [Fintype.card_congr (fiberPermEquiv f g.1), Fintype.card_pi] + apply Finset.prod_congr rfl + intro b _ + rw [Fintype.card_equiv (fiberEquivOfHistogram g.2 b)] + exact congrArg Nat.factorial (congrFun g.2 b) + +lemma sum_perm_comp [DecidableEq α] [Fintype β] (f : α → β) (φ : (α → β) → ℝ) : + ∑ σ : Equiv.Perm α, φ (f ∘ σ) = + (∏ b, ((histogram f b).factorial : ℝ)) * + ∑ g : Colorings α β (histogram f), φ g.1 := by + classical + let F : Equiv.Perm α → Colorings α β (histogram f) := + fun σ => ⟨f ∘ σ, histogram_comp_perm f σ⟩ + rw [← Fintype.sum_fiberwise F (fun σ => φ (f ∘ σ)), Finset.mul_sum] + apply Finset.sum_congr rfl + intro g _ + have he : ∀ σ : {σ // F σ = g}, φ (f ∘ σ.1) = φ g.1 := by + intro σ + exact congrArg φ (congrArg Subtype.val σ.2) + simp_rw [he, Finset.sum_const, Finset.card_univ, nsmul_eq_mul] + congr 1 + let e : {σ // F σ = g} ≃ {σ : Equiv.Perm α // f ∘ σ = g.1} := + Equiv.subtypeEquivRight (fun σ => Subtype.ext_iff) + rw [Fintype.card_congr e, card_perm_color_fiber] + simp + +lemma mean_perm_comp [DecidableEq α] [Fintype β] (f : α → β) (φ : (α → β) → ℝ) : + (Fintype.card (Colorings α β (histogram f)) : ℝ) * + (∑ σ : Equiv.Perm α, φ (f ∘ σ)) = + (Fintype.card (Equiv.Perm α) : ℝ) * + ∑ g : Colorings α β (histogram f), φ g.1 := by + rw [sum_perm_comp, ← mul_assoc] + congr 1 + have h := card_colorings_mul_factorials f + rw [Fintype.card_perm] + exact_mod_cast h + +variable {H : Type u_5} [Fintype H] [DecidableEq H] + +def pairConstant (f : H × Bool → β) : Prop := ∀ i, f (i, false) = f (i, true) + +instance pairConstantDecidable (f : H × Bool → β) : Decidable (pairConstant f) := + inferInstanceAs (Decidable (∀ i, f (i, false) = f (i, true))) + +def duplicateColoring (k : H → β) : H × Bool → β := fun v => k v.1 + +noncomputable def pairConstantEquiv : {f : H × Bool → β // pairConstant f} ≃ (H → β) where + toFun f i := f.1 (i, false) + invFun k := ⟨duplicateColoring k, by intro i; rfl⟩ + left_inv f := by + apply Subtype.ext + funext ⟨i, b⟩ + cases b + · rfl + · exact f.2 i + right_inv k := rfl + +def spliceColoring (k l : H → β) : H × Bool → β := + fun v => if v.2 then l v.1 else k v.1 + +omit [DecidableEq H] in +lemma histogram_spliceColoring (k l : H → β) : + histogram (spliceColoring k l) = histogram k + histogram l := by + funext b + change Fintype.card {v : H × Bool // spliceColoring k l v = b} = _ + let e : {v : H × Bool // spliceColoring k l v = b} ≃ + ({i // k i = b} ⊕ {i // l i = b}) := + { toFun := fun v => if h : v.1.2 = true then + Sum.inr ⟨v.1.1, by simpa [spliceColoring, h] using v.2⟩ else + Sum.inl ⟨v.1.1, by simpa [spliceColoring, h] using v.2⟩ + invFun := Sum.elim (fun i => ⟨(i.1, false), i.2⟩) (fun i => ⟨(i.1, true), i.2⟩) + left_inv := by + rintro ⟨⟨i, b⟩, h⟩ + cases b <;> rfl + right_inv := by intro v; cases v <;> rfl } + rw [Fintype.card_congr e, Fintype.card_sum] + rfl + +omit [DecidableEq H] in +lemma histogram_duplicateColoring (k : H → β) : + histogram (duplicateColoring k) = fun b => 2 * histogram k b := by + have he : duplicateColoring k = spliceColoring k k := by + funext ⟨i, b⟩; cases b <;> rfl + rw [he, histogram_spliceColoring] + funext b + simp [two_mul] + +omit [DecidableEq H] in +lemma card_colorings_double_ge_square [Fintype β] (s : β → ℕ) : + Fintype.card (Colorings H β s) ^ 2 ≤ + Fintype.card (Colorings (H × Bool) β (fun b => 2 * s b)) := by + classical + let e : Colorings H β s × Colorings H β s → + Colorings (H × Bool) β (fun b => 2 * s b) := fun kl => + ⟨spliceColoring kl.1.1 kl.2.1, by + rw [histogram_spliceColoring, kl.1.2, kl.2.2] + funext b; simp [two_mul]⟩ + have hi : Function.Injective e := by + intro kl mn h + apply Prod.ext + · apply Subtype.ext + funext i + exact congrFun (congrArg Subtype.val h) (i, false) + · apply Subtype.ext + funext i + exact congrFun (congrArg Subtype.val h) (i, true) + simpa only [Fintype.card_prod, pow_two] using Fintype.card_le_of_injective e hi + +noncomputable def constantColoringsEquiv (s : β → ℕ) : + {g : Colorings (H × Bool) β (fun b => 2 * s b) // pairConstant g.1} ≃ + Colorings H β s where + toFun g := ⟨fun i => g.1.1 (i, false), by + have he : duplicateColoring (fun i => g.1.1 (i, false)) = g.1.1 := by + funext ⟨i, b⟩ + cases b + · rfl + · exact g.2 i + have hh := congrArg histogram he + rw [histogram_duplicateColoring, g.1.2] at hh + funext b + exact Nat.eq_of_mul_eq_mul_left (by decide : 0 < 2) (congrFun hh b)⟩ + invFun k := ⟨⟨duplicateColoring k.1, by rw [histogram_duplicateColoring, k.2]⟩, + by intro i; rfl⟩ + left_inv g := by + apply Subtype.ext + apply Subtype.ext + funext ⟨i, b⟩ + cases b + · rfl + · exact g.2 i + right_inv k := by apply Subtype.ext; rfl + +lemma sum_indicator_card {X : Type u_6} [Fintype X] (p : X → Prop) [DecidablePred p] : + (∑ x, if p x then (1 : ℝ) else 0) = (Fintype.card {x // p x} : ℝ) := by + simp only [Fintype.card_subtype, Finset.card_filter, Nat.cast_sum] + apply Finset.sum_congr rfl + intro x _ + split_ifs <;> norm_num + +lemma sum_pairConstant (F : (H × Bool → β) → ℝ) [Fintype β] : + (∑ f, if pairConstant f then F f else 0) = ∑ k : H → β, F (duplicateColoring k) := by + classical + rw [← Finset.sum_filter, ← Finset.sum_subtype_eq_sum_filter] + simp only [Finset.subtype_univ] + exact Fintype.sum_equiv pairConstantEquiv _ _ (by + intro f + congr 1 + exact (congrArg Subtype.val (pairConstantEquiv.symm_apply_apply f)).symm) + +lemma pairConstant_perm_sum_bound [Fintype β] (k : H → β) : + (Fintype.card (Colorings H β (histogram k)) : ℝ) * + (∑ σ : Equiv.Perm (H × Bool), + if pairConstant (duplicateColoring k ∘ σ) then (1 : ℝ) else 0) ≤ + Fintype.card (Equiv.Perm (H × Bool)) := by + classical + let A := Fintype.card (Colorings H β (histogram k)) + let B := Fintype.card (Colorings (H × Bool) β (fun b => 2 * histogram k b)) + let S := ∑ σ : Equiv.Perm (H × Bool), + if pairConstant (duplicateColoring k ∘ σ) then (1 : ℝ) else 0 + have hA : (0 : ℝ) < A := by + exact_mod_cast (Fintype.card_pos_iff.mpr ⟨⟨k, rfl⟩⟩ : 0 < A) + have hS : 0 ≤ S := Finset.sum_nonneg (fun _ _ => by split_ifs <;> norm_num) + have hB : (A : ℝ) ^ 2 ≤ B := by exact_mod_cast card_colorings_double_ge_square (histogram k) + have he := mean_perm_comp (duplicateColoring k) + (fun g => if pairConstant g then (1 : ℝ) else 0) + rw [histogram_duplicateColoring] at he + conv_rhs at he => + arg 2 + rw [sum_indicator_card, Fintype.card_congr (constantColoringsEquiv (histogram k))] + change (B : ℝ) * S = _ at he + change (A : ℝ) * S ≤ _ + nlinarith [mul_le_mul_of_nonneg_right hB hS] + +lemma sum_le_card_mul_of_fiber_bound {X : Type u_7} {J : Type u_8} [Fintype X] [Fintype J] + [DecidableEq J] (g : X → J) (a : X → ℝ) (P : ℝ) (hP : 0 ≤ P) + (ha : ∀ x, (Fintype.card {y // g y = g x} : ℝ) * a x ≤ P) : + ∑ x, a x ≤ (Fintype.card J : ℝ) * P := by + rw [← Fintype.sum_fiberwise g a] + calc + _ ≤ ∑ _j : J, P := by + apply Finset.sum_le_sum + intro j _ + by_cases hn : Nonempty {y // g y = j} + · have hc : (0 : ℝ) < Fintype.card {y // g y = j} := by + exact_mod_cast Fintype.card_pos_iff.mpr hn + apply (mul_le_mul_iff_right₀ hc).mp + rw [Finset.mul_sum] + calc + _ ≤ ∑ _y : {y // g y = j}, P := by + apply Finset.sum_le_sum + intro y _ + simpa only [y.2] using ha y.1 + _ = _ := by simp + · have : IsEmpty {y // g y = j} := ⟨fun y => hn ⟨y⟩⟩ + simpa using hP + _ = _ := by simp + +noncomputable def boundedHistogram (f : H → β) : β → Fin (Fintype.card H + 1) := + fun b => ⟨histogram f b, Nat.lt_succ_of_le + (Fintype.card_le_of_injective (fun a : {a // f a = b} => a.1) Subtype.val_injective)⟩ + +omit [DecidableEq H] in +lemma boundedHistogram_eq_iff (f g : H → β) : + boundedHistogram f = boundedHistogram g ↔ histogram f = histogram g := by + constructor + · intro h; funext b; exact congrArg Fin.val (congrFun h b) + · intro h; funext b; apply Fin.ext; exact congrFun h b + +lemma common_pairColorings_moment [Fintype β] : + (∑ σ : Equiv.Perm (H × Bool), + (Fintype.card {f : H × Bool → β // pairConstant f ∧ pairConstant (f ∘ σ)} : ℝ)) ≤ + (Fintype.card (Equiv.Perm (H × Bool)) : ℝ) * + (Fintype.card H + 1 : ℝ) ^ Fintype.card β := by + classical + conv_lhs => + arg 2 + ext σ + rw [← sum_indicator_card] + rw [Finset.sum_comm] + have he (f : H × Bool → β) : + ∑ σ : Equiv.Perm (H × Bool), + (if pairConstant f ∧ pairConstant (f ∘ σ) then (1 : ℝ) else 0) = + if pairConstant f then ∑ σ : Equiv.Perm (H × Bool), + (if pairConstant (f ∘ σ) then (1 : ℝ) else 0) else 0 := by + split_ifs with hf <;> simp [hf] + simp_rw [he] + rw [sum_pairConstant] + have hb := sum_le_card_mul_of_fiber_bound (boundedHistogram (H := H) (β := β)) + (fun k => ∑ σ : Equiv.Perm (H × Bool), + if pairConstant (duplicateColoring k ∘ σ) then (1 : ℝ) else 0) + (Fintype.card (Equiv.Perm (H × Bool)) : ℝ) (by positivity) (by + intro k + let e : {l : H → β // boundedHistogram l = boundedHistogram k} ≃ + Colorings H β (histogram k) := + Equiv.subtypeEquivRight (fun l => boundedHistogram_eq_iff l k) + rw [Fintype.card_congr e] + exact pairConstant_perm_sum_bound k) + simpa only [Fintype.card_fun, Fintype.card_fin, Nat.cast_pow, Nat.cast_add, + Nat.cast_one, mul_comm] using hb + +end MatchingSmoothing + +end OAI diff --git a/lean/OAI/Combinatorics/MatchingPSD/CommonSelection.lean b/lean/OAI/Combinatorics/MatchingPSD/CommonSelection.lean new file mode 100644 index 0000000000000000000000000000000000000000..5ebfb8590477ccc28100e3f30dac5cd921ac2846 --- /dev/null +++ b/lean/OAI/Combinatorics/MatchingPSD/CommonSelection.lean @@ -0,0 +1,43 @@ +import OAI.Combinatorics.MatchingPSD.PermutationSmoothing + +namespace OAI + +universe u_1 u_2 u_3 + +namespace MatchingSmoothing +open scoped BigOperators + +section GroupAveraging +variable {G : Type u_1} {I : Type u_2} [Fintype G] [Group G] [Fintype I] + {P : I → Type u_3} [∀ i, Fintype (P i)] [∀ i, Nonempty (P i)] + +lemma mean_right_translate (g : G) (f : G → ℝ) : + (𝔼 a : G, f (a*g)) = 𝔼 a : G, f a := by + exact Fintype.expect_equiv (Equiv.mulRight g) _ _ (fun _ => rfl) + +omit [Fintype I] in +lemma mean_le_of_local_means (lift : (i : I) → P i → G) + (err : I → G → ℝ) (b : I → ℝ) + (hb : ∀ i a, (𝔼 p : P i, err i (a * lift i p)) ≤ b i) (i : I) : + (𝔼 a : G, err i a) ≤ b i := by + have hh : (𝔼 a : G, 𝔼 p : P i, err i (a * lift i p)) ≤ b i := + Finset.expect_le Finset.univ_nonempty (fun a _ => hb i a) + rw [Finset.expect_comm] at hh + simpa only [mean_right_translate, Fintype.expect_const] using hh + +lemma exists_total_le_of_local_means (lift : (i : I) → P i → G) + (err : I → G → ℝ) (b : I → ℝ) + (hb : ∀ i a, (𝔼 p : P i, err i (a * lift i p)) ≤ b i) : + ∃ a : G, (∑ i, err i a) ≤ ∑ i, b i := by + have he (i : I) : (𝔼 a : G, err i a) ≤ b i := + mean_le_of_local_means lift err b hb i + have htotal : (𝔼 a : G, ∑ i, err i a) ≤ ∑ i, b i := by + rw [Finset.expect_sum_comm] + exact Finset.sum_le_sum (fun i _ => he i) + obtain ⟨a, _, ha⟩ := Finset.exists_le_of_expect_le Finset.univ_nonempty htotal + exact ⟨a,ha⟩ + +end GroupAveraging +end MatchingSmoothing + +end OAI diff --git a/lean/OAI/Combinatorics/MatchingPSD/CrossSelection.lean b/lean/OAI/Combinatorics/MatchingPSD/CrossSelection.lean new file mode 100644 index 0000000000000000000000000000000000000000..023ea6a3c9fc7db59df8c21451b0f274bfbff551 --- /dev/null +++ b/lean/OAI/Combinatorics/MatchingPSD/CrossSelection.lean @@ -0,0 +1,71 @@ +import OAI.Combinatorics.MatchingPSD.TableGeometry + +namespace OAI + +namespace MatchingSmoothing +open scoped BigOperators +attribute [local instance] Classical.propDecidable + +lemma simultaneous_cross_approximation (K : ℕ) : + ∃ d H : ℕ, 0 < d ∧ ∀ h : ℕ, H ≤ h → + ∀ (V G I T : Type) [Fintype V] [Fintype G] [Group G] [Fintype I] [Fintype T] + (_e : V ≃ Vertices h) (z : I → V → Fin 3), (∀ i c, 0 < histogram (z i) c) → + ∀ (M : I → T → Pairing V) + (lift : I → Equiv.Perm V → G) + (g : I → G → Pairing V → ℝ), + (∀ i a p, g i (a * lift i p) = fun N => g i a (Pairing.relabel p N)) → + ∀ B : ℝ, (∀ i a N, (g i a N)^2 ≤ B^2) → + ∃ a : G, ∃ P : I → (Fin 3 → ℝ) → ℝ, + (∀ i, P i ∈ lowDegree (fun c (v : Fin 3 → ℝ) => v c) d) ∧ + (∑ i, ∑ t : T, + (predicateAverage (fun N => crossVector (z i) N = crossVector (z i) (M i t)) (g i a) - + P i (crossVector (z i) (M i t)))^2) + ≤ (Fintype.card I : ℝ) * Fintype.card T * ((2*h : ℝ)^(2*K))⁻¹ * B^2 := by + classical + obtain ⟨d,H,hd,hmain⟩ := simultaneous_table_approximation K + refine ⟨d,H,hd,?_⟩ + intro h hh V G I T _ _ _ _ _ e z hz M lift g hcov B hB + let ev := Pairing.transportEquiv e.symm + let z' := fun i => z i ∘ e.symm + let M' := fun i t => Pairing.transport e (M i t) + let lift' := fun i (p : Equiv.Perm (Vertices h)) => lift i (e.trans (p.trans e.symm)) + let g' := fun i a N => g i a (ev N) + have hc (i : I) (a : G) (p : Equiv.Perm (Vertices h)) : + g' i (a * lift' i p) = fun N => g' i a (Pairing.relabel p N) := by + funext N + change g i (a * lift' i p) (ev N) = _ + rw [hcov] + change g i a (Pairing.relabel (e.trans (p.trans e.symm)) (Pairing.transport e.symm N)) = + g i a (Pairing.transport e.symm (Pairing.relabel p N)) + rw [Pairing.transport_relabel] + rfl + obtain ⟨a,P,hP,hbound⟩ := hmain h hh G I T z' + (fun i c => by + have he : histogram (z' i) = histogram (z i) := histogram_comp_equiv (z i) e.symm + rw [he] + exact hz i c) + M' lift' g' hc B (fun i a N => hB i a (ev N)) + refine ⟨a,P,hP,?_⟩ + have hvec (i : I) (t : T) : crossVector (z' i) (M' i t) = crossVector (z i) (M i t) := by + rw [crossVector_transport] + have he : z' i ∘ e = z i := by funext v; simp [z'] + rw [he] + have hav (i : I) (t : T) : + predicateAverage (fun N => N.table (z' i) = (M' i t).table (z' i)) (g' i a) = + predicateAverage (fun N => crossVector (z i) N = crossVector (z i) (M i t)) (g i a) := by + apply predicateAverage_equiv ev + intro N + rw [table_eq_iff_cross, hvec] + change _ ↔ crossVector (z i) (Pairing.transport e.symm N) = _ + rw [crossVector_transport] + have htvec (i : I) (t : T) : + (fun c => ((M' i t).table (z' i) (threeEdgeType (crossPair c)) : ℝ)) = + crossVector (z i) (M i t) := by + rw [← hvec] + funext c + exact (crossCoordinate_eq_table _ _ _).symm + simpa only [hav, htvec] using hbound + +end MatchingSmoothing + +end OAI diff --git a/lean/OAI/Combinatorics/MatchingPSD/CutGeometry.lean b/lean/OAI/Combinatorics/MatchingPSD/CutGeometry.lean new file mode 100644 index 0000000000000000000000000000000000000000..76a64dc1465f33d55330a9f18c9f3ec9c407cd77 --- /dev/null +++ b/lean/OAI/Combinatorics/MatchingPSD/CutGeometry.lean @@ -0,0 +1,103 @@ +import OAI.Combinatorics.MatchingPSD.AdmissiblePoints + +namespace OAI + +universe u_1 u_2 u_3 u_4 u_5 u_6 u_7 u_8 u_9 u_10 u_11 u_12 u_13 u_14 u_15 + +namespace MatchingSmoothing +open scoped BigOperators +attribute [local instance] Classical.propDecidable + +abbrev GlobalVertices (s q : ℕ) := + (Fin (2*s+1) ⊕ Fin (2*s+1)) ⊕ (Fin q × (Fin s × Bool)) + +def localCutColor (b : Bool) : Fin 3 → Bool := ![true,false,b] +def globalCutColor {A : Type u_1} {B : Type u_2} {C : Type u_3} {I : Type u_4} (y : I → Bool) : (A ⊕ B) ⊕ (I × C) → Bool := + Sum.elim (Sum.elim (fun _ => true) (fun _ => false)) (fun v => y v.1) + +lemma tableCoordinate_localcut {V : Type u_5} [Fintype V] (z : V → Fin 3) + (M : Pairing V) (b : Bool) : + tableCoordinate (localCutColor b ∘ z) (true,false) M = + crossVector z M 0 + crossVector z M (if b then 2 else 1) := by + cases b + · change _ = tableCoordinate z (0,1) M + tableCoordinate z (0,2) M + simp only [tableCoordinate, ← Finset.sum_add_distrib] + apply Finset.sum_congr rfl + intro v _ + rcases (show z v=0 ∨ z v=1 ∨ z v=2 by omega) with hv | hv | hv <;> + rcases (show z (M.1 v)=0 ∨ z (M.1 v)=1 ∨ z (M.1 v)=2 by omega) with hw | hw | hw <;> + simp [Function.comp_apply, hv, hw, localCutColor] + · change _ = tableCoordinate z (0,1) M + tableCoordinate z (1,2) M + rw [tableCoordinate_symm z 1 2] + simp only [tableCoordinate, ← Finset.sum_add_distrib] + apply Finset.sum_congr rfl + intro v _ + rcases (show z v=0 ∨ z v=1 ∨ z v=2 by omega) with hv | hv | hv <;> + rcases (show z (M.1 v)=0 ∨ z (M.1 v)=1 ∨ z (M.1 v)=2 by omega) with hw | hw | hw <;> + simp [Function.comp_apply, hv, hw, localCutColor] + +lemma tableCoordinate_cellwise_cut {I : Type u_6} {C : Type u_7} [Fintype I] [Fintype C] + (y : I → Bool) (N : I → Pairing C) : + tableCoordinate (fun v : I × C => y v.1) (true,false) (Pairing.cellwise N) = 0 := by + apply (tableCoordinate_eq_zero_iff _ _ _).mpr + rintro ⟨j,c⟩ ⟨h1,h2⟩ + have he : (true : Bool) = false := h1.symm.trans h2 + cases he + +lemma localSplit_cut {A : Type u_8} {B : Type u_9} {C : Type u_10} {I : Type u_11} [DecidableEq I] + (y : I → Bool) (i : I) : + globalCutColor (A := A) (B := B) (C := C) y ∘ localSplitEquiv i = + Sum.elim (localCutColor (y i) ∘ threeColor) + (fun v : {j : I // j ≠ i} × C => y v.1.1) := by + funext v + rcases v with (a | c) | ⟨j,c⟩ + · cases a <;> rfl + · rfl + · rfl + +lemma extendLocal_cut {A : Type u_12} {B : Type u_13} {C : Type u_14} {I : Type u_15} [Fintype A] [Fintype B] [Fintype C] + [Fintype I] [DecidableEq I] (y : I → Bool) (i : I) + (M : Pairing ((A ⊕ B) ⊕ C)) (N : {j : I // j ≠ i} → Pairing C) : + tableCoordinate (globalCutColor y) (true,false) (extendLocal i M N) = + crossVector threeColor M 0 + crossVector threeColor M (if y i then 2 else 1) := by + rw [extendLocal, tableCoordinate_transport, localSplit_cut, tableCoordinate_sum, + tableCoordinate_cellwise_cut (fun j : {j : I // j ≠ i} => y j.1), + add_zero, tableCoordinate_localcut] + +lemma globalCutColor_card (s q : ℕ) (y : Fin q → Bool) : + Fintype.card {v : GlobalVertices s q // globalCutColor y v = true} = + 2*s+1 + Fintype.card {i : Fin q // y i = true} * (2*s) := by + classical + have hc (V : Type) [Fintype V] (f : V → Bool) : + Fintype.card {v // f v = true} = histogram f true := by + simp only [Fintype.card_subtype, histogram] + rw [hc, hc] + apply Nat.cast_injective (R := ℝ) + simp only [Nat.cast_add, Nat.cast_mul, Nat.cast_ofNat, Nat.cast_one, + histogram_cast_sum] + simp only [Fintype.sum_sum_type, Fintype.sum_prod_type, globalCutColor, + Sum.elim_inl, Sum.elim_inr, Fintype.sum_bool, ite_true, Bool.false_eq_true, + ite_false, Finset.sum_const, Finset.card_univ, Fintype.card_fin, nsmul_eq_mul, + mul_one, mul_zero, add_zero, Finset.sum_add_distrib, Finset.sum_mul, + Nat.cast_add, Nat.cast_mul, Nat.cast_ofNat, Nat.cast_one] + congr 1 + rw [← Finset.sum_add_distrib] + apply Finset.sum_congr rfl + intro i _ + by_cases h : y i = true <;> simp [h] + ring + +lemma globalCutColor_odd (s q : ℕ) (y : Fin q → Bool) : + Odd (Fintype.card {v : GlobalVertices s q // globalCutColor y v = true}) := by + rw [globalCutColor_card] + exact ⟨s+Fintype.card {i : Fin q // y i = true}*s, by ring⟩ + +lemma globalVertices_card (s q : ℕ) : + Fintype.card (GlobalVertices s q) = 2*s*(q+2)+2 := by + simp only [GlobalVertices, Fintype.card_sum, Fintype.card_prod, Fintype.card_fin, + Fintype.card_bool] + ring + +end MatchingSmoothing + +end OAI diff --git a/lean/OAI/Combinatorics/MatchingPSD/DeterminantNormalization.lean b/lean/OAI/Combinatorics/MatchingPSD/DeterminantNormalization.lean new file mode 100644 index 0000000000000000000000000000000000000000..3ef7acca1d25314884a857fb6db36209b3125745 --- /dev/null +++ b/lean/OAI/Combinatorics/MatchingPSD/DeterminantNormalization.lean @@ -0,0 +1,189 @@ +import OAI.Combinatorics.MatchingPSD.CellAverages + +namespace OAI + +universe u_1 u_2 u_3 + +namespace PerfectMatchingPSD +open Matrix Set +variable {R : Type u_1} {I : Type u_2} {J : Type u_3} [Fintype R] [DecidableEq R] + +omit [Fintype R] [DecidableEq R] in +lemma convex_posSemidef : Convex ℝ {A : Matrix R R ℝ | A.PosSemidef} := by + intro A hA B hB a b ha hb _ + exact (hA.smul ha).add (hB.smul hb) + +lemma hasDerivAt_det_one_add (A : Matrix R R ℝ) : + HasDerivAt (fun t : ℝ => (1 + t • A).det) A.trace 0 := by + let p : Polynomial ℝ := (1 + (Polynomial.X : Polynomial ℝ) • A.map Polynomial.C).det + have h := p.hasDerivAt 0 + rw [show p.derivative.eval 0 = A.trace from Matrix.derivative_det_one_add_X_smul A] at h + have he : (fun t : ℝ => (1 + t • A).det) = (fun t => p.eval t) := by + funext t + change _ = (Polynomial.evalRingHom t) p + rw [RingHom.map_det] + congr 1 + ext i j + change (if i = j then 1 else 0) + t * A i j = + Polynomial.eval t ((if i = j then 1 else 0) + + Polynomial.X * Polynomial.C (A i j)) + rw [Polynomial.eval_add, Polynomial.eval_mul, Polynomial.eval_X, Polynomial.eval_C] + split_ifs <;> simp only [Polynomial.eval_one, Polynomial.eval_zero] + rwa [he] + +lemma hasDerivAt_det_add (D E : Matrix R R ℝ) (hD : IsUnit D) : + HasDerivAt (fun t : ℝ => (D + t • E).det) + (D.det * (D⁻¹ * E).trace) 0 := by + have h := (hasDerivAt_det_one_add (D⁻¹ * E)).const_mul D.det + have he : (fun t : ℝ => (D + t • E).det) = + (fun t => D.det * (1 + t • (D⁻¹ * E)).det) := by + funext t + rw [← Matrix.det_mul] + congr 1 + rw [mul_add, mul_one, mul_smul_comm, ← mul_assoc, + Matrix.mul_nonsing_inv D ((Matrix.isUnit_iff_isUnit_det D).mp hD), one_mul] + rwa [he] + +lemma derivative_nonpos_at_right_max {f : ℝ → ℝ} {c : ℝ} + (h : HasDerivAt f c 0) (hm : ∀ t ∈ Set.Icc (0 : ℝ) 1, f t ≤ f 0) : c ≤ 0 := by + have he : IsLocalMaxOn f (Set.Icc (0 : ℝ) 1) 0 := + (show IsMaxOn f (Set.Icc (0 : ℝ) 1) 0 from hm).isLocalMaxOn + have ht : (1 : ℝ) ∈ posTangentConeAt (Set.Icc (0 : ℝ) 1) 0 := by + apply mem_posTangentConeAt_of_segment_subset + simp [segment_eq_Icc] + simpa using he.hasFDerivWithinAt_nonpos h.hasFDerivAt.hasFDerivWithinAt ht + +lemma trace_inv_mul_le_of_det_max (D B : Matrix R R ℝ) (hD : D.PosDef) + (hm : ∀ t ∈ Set.Icc (0 : ℝ) 1, (D + t • (B - D)).det ≤ D.det) : + (D⁻¹ * B).trace ≤ (Fintype.card R : ℝ) := by + have hd : 0 < D.det := hD.det_pos + have he := derivative_nonpos_at_right_max (hasDerivAt_det_add D (B - D) hD.isUnit) + (by simpa using hm) + have ht : (D⁻¹ * (B - D)).trace ≤ 0 := by nlinarith + rw [mul_sub, Matrix.trace_sub, Matrix.nonsing_inv_mul D ((Matrix.isUnit_iff_isUnit_det D).mp hD.isUnit), Matrix.trace_one] at ht + linarith + +lemma exists_regularized_det_max [Fintype I] [Nonempty I] + (B : I → Matrix R R ℝ) (hB : ∀ i, (B i).PosSemidef) + (ε : ℝ) (hε : 0 < ε) : + ∃ D : Matrix R R ℝ, D.PosDef ∧ + D ∈ (fun A => ε • (1 : Matrix R R ℝ) + A) '' convexHull ℝ (Set.range B) ∧ + ∀ i, (D⁻¹ * B i).trace ≤ (Fintype.card R : ℝ) := by + let S := convexHull ℝ (Set.range B) + let f : Matrix R R ℝ → Matrix R R ℝ := fun A => ε • (1 : Matrix R R ℝ) + A + have hc : IsCompact S := (Set.finite_range B).isCompact_convexHull ℝ + have hn : S.Nonempty := (Set.range_nonempty B).mono (subset_convexHull ℝ _) + have hf : Continuous f := by fun_prop + have hp : ∀ A ∈ S, A.PosSemidef := + convexHull_min (Set.range_subset_iff.mpr hB) convex_posSemidef + have hpd : ∀ D ∈ f '' S, D.PosDef := by + rintro _ ⟨A, hA, rfl⟩ + exact (Matrix.PosDef.one.smul hε).add_posSemidef (hp A hA) + obtain ⟨D, hDs, hmax⟩ := (hc.image hf).exists_isMaxOn (hn.image f) + (by fun_prop : ContinuousOn Matrix.det (f '' S)) + refine ⟨D, hpd D hDs, hDs, ?_⟩ + intro i + have hi : f (B i) ∈ f '' S := ⟨B i, subset_convexHull ℝ _ (Set.mem_range_self i), rfl⟩ + have hs : Convex ℝ (f '' S) := by + exact (convex_convexHull ℝ (Set.range B)).translate (ε • (1 : Matrix R R ℝ)) + have hm := trace_inv_mul_le_of_det_max D (f (B i)) (hpd D hDs) (by + intro t ht + apply hmax + have he : D + t • (f (B i) - D) = (1 - t) • D + t • f (B i) := by module + rw [he] + exact hs hDs hi (sub_nonneg.mpr ht.2) ht.1 (by ring)) + have htr : 0 ≤ (D⁻¹).trace := (hpd D hDs).inv.posSemidef.trace_nonneg + have he : (D⁻¹ * f (B i)).trace = ε * (D⁻¹).trace + (D⁻¹ * B i).trace := by + simp [f, mul_add, Matrix.trace_add, Matrix.trace_smul] + rw [he] at hm + nlinarith + +open scoped MatrixOrder + +lemma trace_mul_nonneg {A B : Matrix R R ℝ} (hA : A.PosSemidef) (hB : B.PosSemidef) : + 0 ≤ (A * B).trace := by + let G := CFC.sqrt B + have hG : G.PosSemidef := (CFC.sqrt_nonneg B).posSemidef + have hGG : G * G = B := CFC.sqrt_mul_sqrt_self B hB.nonneg + have h := (hA.conjTranspose_mul_mul_same G).trace_nonneg + rw [hG.isHermitian.eq, Matrix.trace_mul_cycle, hGG] at h + simpa only [Matrix.trace_mul_comm B A] using h + +lemma trace_mul_le_of_le {A B D : Matrix R R ℝ} (hA : A.PosSemidef) (hBD : B ≤ D) : + (A * B).trace ≤ (A * D).trace := by + have h := trace_mul_nonneg hA hBD + rwa [mul_sub, Matrix.trace_sub, sub_nonneg] at h + +lemma trace_mul_convexHull_le [Fintype I] (A : Matrix R R ℝ) + (B : I → Matrix R R ℝ) (m : ℝ) (hB : ∀ i, (A * B i).trace ≤ m) + {D : Matrix R R ℝ} (hD : D ∈ convexHull ℝ (Set.range B)) : + (A * D).trace ≤ m := by + have hc : Convex ℝ {D : Matrix R R ℝ | (A * D).trace ≤ m} := by + intro X hX Y hY a b ha hb hab + change (A * (a • X + b • Y)).trace ≤ m + rw [mul_add, mul_smul_comm, mul_smul_comm, Matrix.trace_add, + Matrix.trace_smul, Matrix.trace_smul] + change a * (A * X).trace + b * (A * Y).trace ≤ m + calc + _ ≤ a * m + b * m := add_le_add + (mul_le_mul_of_nonneg_left hX ha) (mul_le_mul_of_nonneg_left hY hb) + _ = m := by rw [← add_mul, hab, one_mul] + exact convexHull_min (Set.range_subset_iff.mpr hB) hc hD + +lemma exists_normalized_factors [Fintype I] [Nonempty I] [Fintype J] + (A : J → Matrix R R ℝ) (B : I → Matrix R R ℝ) + (hA : ∀ j, (A j).PosSemidef) (hB : ∀ i, (B i).PosSemidef) + (m : ℝ) (hpair : ∀ j i, (A j * B i).trace ≤ m) : + ∃ (A' : J → Matrix R R ℝ) (B' : I → Matrix R R ℝ), + (∀ j, (A' j).PosSemidef) ∧ (∀ i, (B' i).PosSemidef) ∧ + (∀ j i, (A' j * B' i).trace = (A j * B i).trace) ∧ + (∀ j, (A' j).trace ≤ m + 1) ∧ + (∀ i, (B' i).trace ≤ (Fintype.card R : ℝ)) := by + classical + let S : ℝ := ∑ j, (A j).trace + have hS : 0 ≤ S := Finset.sum_nonneg (fun j _ => (hA j).trace_nonneg) + let ε : ℝ := 1 / (1 + S) + have hε : 0 < ε := one_div_pos.mpr (by linarith) + have hεA (j : J) : ε * (A j).trace ≤ 1 := by + have hj : (A j).trace ≤ S := Finset.single_le_sum + (fun j _ => (hA j).trace_nonneg) (Finset.mem_univ j) + change 1 / (1 + S) * (A j).trace ≤ 1 + rw [one_div_mul_eq_div] + exact (div_le_one (by linarith : 0 < 1 + S)).mpr (by linarith) + obtain ⟨D, hD, ⟨D₀, hD₀, hDeq⟩, htr⟩ := exists_regularized_det_max B hB ε hε + let G := CFC.sqrt D + have hG : G.PosSemidef := (CFC.sqrt_nonneg D).posSemidef + have hGG : G * G = D := CFC.sqrt_mul_sqrt_self D hD.posSemidef.nonneg + have huG : IsUnit G := (IsUnit.mul_iff.mp (hGG ▸ hD.isUnit)).1 + have hunit := (Matrix.isUnit_iff_isUnit_det G).mp huG + have hGinv : G⁻¹.PosSemidef := hG.inv + have hleft : G⁻¹ * G = 1 := Matrix.nonsing_inv_mul G hunit + have hright : G * G⁻¹ = 1 := Matrix.mul_nonsing_inv G hunit + have hinv : G⁻¹ * G⁻¹ = D⁻¹ := by + rw [← hGG, Matrix.mul_inv_rev] + refine ⟨fun j => G * A j * G, fun i => G⁻¹ * B i * G⁻¹, + ?_, ?_, ?_, ?_, ?_⟩ + · intro j + simpa only [hG.isHermitian.eq] using (hA j).conjTranspose_mul_mul_same G + · intro i + simpa only [hGinv.isHermitian.eq] using (hB i).conjTranspose_mul_mul_same G⁻¹ + · intro j i + change (G * A j * G * (G⁻¹ * B i * G⁻¹)).trace = _ + have he : G * A j * G * (G⁻¹ * B i * G⁻¹) = G * (A j * B i) * G⁻¹ := by + calc + _ = G * A j * (G * G⁻¹) * B i * G⁻¹ := by simp only [mul_assoc] + _ = _ := by rw [hright, mul_one]; simp only [mul_assoc] + rw [he, Matrix.trace_mul_cycle, hleft, one_mul] + · intro j + rw [Matrix.trace_mul_cycle, hGG, Matrix.trace_mul_comm, ← hDeq, mul_add, Matrix.trace_add, + mul_smul_comm, Matrix.trace_smul, mul_one] + change ε * (A j).trace + (A j * D₀).trace ≤ m + 1 + have hl := trace_mul_convexHull_le (A j) B m (hpair j) hD₀ + linarith [hεA j] + · intro i + rw [Matrix.trace_mul_cycle, hinv] + exact htr i + +end PerfectMatchingPSD + +end OAI diff --git a/lean/OAI/Combinatorics/MatchingPSD/DiagonalCone.lean b/lean/OAI/Combinatorics/MatchingPSD/DiagonalCone.lean new file mode 100644 index 0000000000000000000000000000000000000000..9fe21d2f3bcb212c19dd728c7bbcf7f2be1a00a7 --- /dev/null +++ b/lean/OAI/Combinatorics/MatchingPSD/DiagonalCone.lean @@ -0,0 +1,54 @@ +import Mathlib +import OAI.Combinatorics.MatchingPSD.PSDCompression +import OAI.Combinatorics.MatchingPSD.PSDTopology +import OAI.Combinatorics.MatchingPSD.MatrixBounds + +namespace OAI + +namespace AffinePSD +open Matrix Finset +open scoped BigOperators +variable {I R : Type*} [Fintype I] [Fintype R] [DecidableEq R] + +lemma evaluationCone_isClosed_of_diagonal (B : I → Matrix R R ℝ) + (hB : ∀ i, (B i).PosSemidef) (d : R → ℝ) + (hs : ∑ i, B i = diagonal d) : IsClosed (evaluationCone B) := by + classical + apply IsSeqClosed.isClosed + intro u y hu hy + choose A hA heA using hu + have hc (k : ℕ) := diagonal_compression B hB d hs (A k) (hA k) + choose C hC heC hzC using hc + have heval (k : ℕ) : evaluation B (C k) = u k := (heC k).trans (heA k) + have hsum : Filter.Tendsto (fun k => ∑ i, u k i) Filter.atTop (nhds (∑ i, y i)) := + tendsto_finsetSum _ (fun i _ => (tendsto_pi_nhds.mp hy) i) + obtain ⟨b, hb⟩ := hsum.bddAbove_range + have hbound (k : ℕ) : ∑ i, u k i ≤ b := hb (Set.mem_range_self k) + let a : ℝ := ∑ j, (d j)⁻¹ + have ha : 0 ≤ a := Finset.sum_nonneg (fun j _ => + inv_nonneg.mpr (sum_diagonal_nonneg B hB d hs j)) + have htr (k : ℕ) : (C k).trace ≤ a * b := by + refine (diagonal_trace_bound B hB d hs (C k) (hC k) (hzC k)).trans ?_ + rw [heval] + exact mul_le_mul_of_nonneg_left (hbound k) ha + let lo : R → R → ℝ := fun _ _ => -(a * b) + let hi : R → R → ℝ := fun _ _ => a * b + have hm (k : ℕ) : C k ∈ Set.Icc lo hi := by + constructor <;> intro i j + · exact (abs_le.mp ((PerfectMatchingPSD.posSemidef_entry_abs_le_trace (hC k) i j).trans + (htr k))).1 + · exact (abs_le.mp ((PerfectMatchingPSD.posSemidef_entry_abs_le_trace (hC k) i j).trans + (htr k))).2 + obtain ⟨L, hL, φ, hφ, ht⟩ := IsCompact.tendsto_subseq (X := R → R → ℝ) (isCompact_Icc : IsCompact (Set.Icc lo hi)) hm + have hpsd : Matrix.PosSemidef L := psd_isClosed.mem_of_tendsto ht + (Filter.Eventually.of_forall (fun k => hC (φ k))) + refine ⟨L, hpsd, ?_⟩ + have hlim := (evaluation_continuous B).continuousAt.tendsto.comp ht + have hlim' := hy.comp hφ.tendsto_atTop + have hEq : evaluation B ∘ (C ∘ φ) = u ∘ φ := by ext k i; exact congrFun (heval (φ k)) i + have hlim := hlim.congr (fun k => congrFun hEq k) + exact tendsto_nhds_unique hlim hlim' + +end AffinePSD + +end OAI diff --git a/lean/OAI/Combinatorics/MatchingPSD/DominationDecoder.lean b/lean/OAI/Combinatorics/MatchingPSD/DominationDecoder.lean new file mode 100644 index 0000000000000000000000000000000000000000..b532d047aa453ef5b7edd80e5618ddbbb7367def --- /dev/null +++ b/lean/OAI/Combinatorics/MatchingPSD/DominationDecoder.lean @@ -0,0 +1,66 @@ +import OAI.Combinatorics.MatchingPSD.GoodCells + +namespace OAI + +universe u_1 + +namespace PerfectMatchingPSD +open Matrix +open scoped BigOperators MatrixOrder +attribute [local instance] Classical.propDecidable + +lemma domination_decoder {R : Type u_1} [Fintype R] [DecidableEq R] {q : ℕ} + (Q : (Fin q → Bool) → Matrix R R ℝ) + (T : Fin q → Bool → Matrix R R ℝ) (P E : Fin q → Matrix R R ℝ) + (S : Matrix R R ℝ) + (hQ : ∀ y, (Q y).PosSemidef) (hT : ∀ i b, (T i b).PosSemidef) + (hP : ∀ i, (P i).PosSemidef) (hE : ∀ i, (E i).PosSemidef) (hS : S.PosSemidef) + (hdom : ∀ i, T i false + T i true ≤ S+(2:ℝ) • P i+E i) + (hzero : ∀ y i, (Q y*P i).trace=0) (hstar : ∀ y, (Q y*S).trace=2) + (hbit : ∀ y i, (Q y*T i (y i)).trace=2) + {m e δ : ℝ} (hδ : 0 < δ) (hm : ∀ y, (Q y).trace ≤ m) + (he : ∀ y i, (Q y*E i).trace ≤ e) + (hε : 0 ≤ (q:ℝ)*e+δ*m) + (hsmall : (q:ℝ)*Real.sqrt ((q:ℝ)*e+δ*m) ≤ 1/4) : + (2:ℝ)^q/2 ≤ Fintype.card R := by + let F := fun i => (2:ℝ) • P i+E i + have hF (i : Fin q) : (F i).PosSemidef := (hP i).smul (by norm_num) |>.add (hE i) + let D := S+(∑ i, F i)+δ • (1 : Matrix R R ℝ) + have hsum : (∑ i, F i).PosSemidef := matrix_sum_psd _ _ (fun i _ => hF i) + have hdelt : (δ • (1 : Matrix R R ℝ)).PosDef := Matrix.PosDef.one.smul hδ + have hD : D.PosDef := by + simpa only [D, add_comm] using hdelt.add_posSemidef (hS.add hsum) + have hleS : S ≤ D := by + have he := add_nonneg hsum.nonneg hdelt.posSemidef.nonneg + dsimp [D] + simpa only [add_assoc] using le_add_of_nonneg_right he + have hdomD (i : Fin q) : T i false+T i true ≤ D := by + apply (hdom i).trans + have hi : F i ≤ ∑ j, F j := Finset.single_le_sum (fun j _ => (hF j).nonneg) (Finset.mem_univ i) + calc + S+(2:ℝ) • P i+E i = S+F i := by dsimp [F]; abel + _ ≤ S+(∑ j, F j) := by simpa only [add_comm] using add_le_add_left hi S + _ ≤ D := le_add_of_nonneg_right hdelt.posSemidef.nonneg + have htr (y : Fin q → Bool) : 2 ≤ (Q y*D).trace ∧ (Q y*D).trace ≤ 2+((q:ℝ)*e+δ*m) := by + constructor + · rw [← hstar y] + exact trace_mul_le_of_le (hQ y) hleS + · dsimp [D] + rw [mul_add, mul_add, Matrix.trace_add, Matrix.trace_add, hstar, + Finset.mul_sum, Matrix.trace_sum, mul_smul_comm, Matrix.trace_smul, mul_one] + have hsumtr : (∑ i, (Q y*F i).trace) ≤ (q:ℝ)*e := by + have hh := Finset.sum_le_sum (s := Finset.univ) (fun i _ => he y i) + have hFi (i : Fin q) : (Q y*F i).trace = (Q y*E i).trace := by + simp only [F, mul_add, Matrix.trace_add, mul_smul_comm, Matrix.trace_smul, + hzero, smul_zero, zero_add] + simpa only [hFi, Finset.sum_const, Finset.card_univ, Fintype.card_fin, nsmul_eq_mul] using hh + have hδm := mul_le_mul_of_nonneg_left (hm y) hδ.le + change _ + δ*(Q y).trace ≤ _ + linarith + obtain ⟨ρ,H,hρ,htρ,hH,hpair,hbit'⟩ := states_of_domination Q T D hD hQ hT hdomD + ((q:ℝ)*e+δ*m) hε htr hbit + exact nearly_perfect_bit_tests ρ H hρ htρ hH hpair _ hε hsmall hbit' + +end PerfectMatchingPSD + +end OAI diff --git a/lean/OAI/Combinatorics/MatchingPSD/EdgeMonomials.lean b/lean/OAI/Combinatorics/MatchingPSD/EdgeMonomials.lean new file mode 100644 index 0000000000000000000000000000000000000000..6c32d73c549c13ac956a304f94a13e6f263b86dc --- /dev/null +++ b/lean/OAI/Combinatorics/MatchingPSD/EdgeMonomials.lean @@ -0,0 +1,141 @@ +import OAI.Combinatorics.MatchingPSD.ScalarSmoothing + +namespace OAI + +universe u_1 u_2 u_3 + +namespace MatchingSmoothing +attribute [local instance] Classical.propDecidable +namespace Pairing +variable {V : Type u_1} + +noncomputable def edgeMonomial (l : List (V × V)) : Pairing V → ℝ := + (l.map edgeCoord).prod + +def ContainsList (M : Pairing V) (l : List (V × V)) : Prop := + ∀ e ∈ l, M.1 e.1 = e.2 + +noncomputable def edgeSupport (l : List (V × V)) : Finset V := + l.toFinset.image Prod.fst ∪ l.toFinset.image Prod.snd + +lemma mem_edgeSupport (l : List (V × V)) (v : V) : + v ∈ edgeSupport l ↔ ∃ e ∈ l, v = e.1 ∨ v = e.2 := by + simp only [edgeSupport, Finset.mem_union, Finset.mem_image, List.mem_toFinset] + constructor + · rintro (⟨e, he, rfl⟩ | ⟨e, he, rfl⟩) + · exact ⟨e, he, Or.inl rfl⟩ + · exact ⟨e, he, Or.inr rfl⟩ + · rintro ⟨e, he, h | h⟩ + · exact Or.inl ⟨e, he, h.symm⟩ + · exact Or.inr ⟨e, he, h.symm⟩ + +lemma edgeMonomial_eq_indicator (l : List (V × V)) (M : Pairing V) : + edgeMonomial l M = if ContainsList M l then 1 else 0 := by + induction l with + | nil => simp [edgeMonomial, ContainsList] + | cons e l ih => + simp only [edgeMonomial, List.map_cons, List.prod_cons, Pi.mul_apply] at ih ⊢ + rw [ih] + simp only [ContainsList, List.mem_cons, forall_eq_or_imp, edgeCoord] + split_ifs <;> simp_all + +lemma edgeMonomial_cons (e : V × V) (l : List (V × V)) : + edgeMonomial (e::l) = edgeCoord e * edgeMonomial l := by + simp [edgeMonomial] + +lemma contains_partner_support {M : Pairing V} {l : List (V × V)} + (hm : ContainsList M l) {v : V} (hv : v ∈ edgeSupport l) : + M.1 v ∈ edgeSupport l := by + obtain ⟨e, he, rfl | rfl⟩ := (mem_edgeSupport l v).mp hv + · rw [hm e he] + exact (mem_edgeSupport l e.2).mpr ⟨e, he, Or.inr rfl⟩ + · rw [(partner_eq_iff M e.1 e.2).mp (hm e he)] + exact (mem_edgeSupport l e.1).mpr ⟨e, he, Or.inl rfl⟩ + +lemma contains_agree_support {M N : Pairing V} {l : List (V × V)} + (hm : ContainsList M l) (hn : ContainsList N l) {v : V} + (hv : v ∈ edgeSupport l) : M.1 v = N.1 v := by + obtain ⟨e, he, rfl | rfl⟩ := (mem_edgeSupport l v).mp hv + · rw [hm e he, hn e he] + · rw [(partner_eq_iff M e.1 e.2).mp (hm e he), + (partner_eq_iff N e.1 e.2).mp (hn e he)] + +lemma redundant_edgeMonomial {M : Pairing V} {e : V × V} {l : List (V × V)} + (he : M.1 e.1 = e.2) (hm : ContainsList M l) + (hv : e.1 ∈ edgeSupport l ∨ e.2 ∈ edgeSupport l) : + edgeMonomial (e::l) = edgeMonomial l := by + funext N + simp only [edgeMonomial_eq_indicator] + congr 1 + simp only [ContainsList, List.mem_cons, forall_eq_or_imp] + apply propext + refine and_iff_right_of_imp ?_ + intro hn + change ContainsList N l at hn + rcases hv with hv | hv + · exact (contains_agree_support hn hm hv).trans he + · apply (partner_eq_iff N e.1 e.2).mpr + exact (contains_agree_support hn hm hv).trans ((partner_eq_iff M e.1 e.2).mp he) + +lemma edgeMonomial_zero_of_unsatisfiable (l : List (V × V)) + (h : ¬ ∃ M : Pairing V, ContainsList M l) : edgeMonomial l = 0 := by + funext M + rw [edgeMonomial_eq_indicator, ite_eq_right (fun hm => h ⟨M, hm⟩)] + rfl + +lemma edgeMonomial_act_fix (l : List (V × V)) (p : Equiv.Perm V) + (hp : ∀ v ∈ edgeSupport l, p v = v) : act p (edgeMonomial l) = edgeMonomial l := by + funext M + simp only [act_apply, edgeMonomial_eq_indicator] + congr 1 + apply propext + apply forall₂_congr + intro e he + have h₁ := hp e.1 ((mem_edgeSupport l e.1).mpr ⟨e, he, Or.inl rfl⟩) + have h₂ := hp e.2 ((mem_edgeSupport l e.2).mpr ⟨e, he, Or.inr rfl⟩) + simp only [relabel_apply, inv_inv] + rw [h₁, Equiv.Perm.inv_def, p.symm_apply_eq, h₂] + +end Pairing + +section ColorAverage +variable {V : Type u_2} {C : Type u_3} [Fintype V] + +def colorStabilizer (z : V → C) : Subgroup (Equiv.Perm V) where + carrier := {p | ∀ v, z (p v) = z v} + one_mem' := fun _ => rfl + mul_mem' := by intro p q hp hq v; exact (hp (q v)).trans (hq v) + inv_mem' := by intro p hp v; simpa using (hp (p⁻¹ v)).symm + +noncomputable def colorAverage (z : V → C) : Module.End ℝ (Pairing V → ℝ) := + (Fintype.card (colorStabilizer z) : ℝ)⁻¹ • + ∑ p : colorStabilizer z, (Pairing.act p.1).toLinearMap + +lemma colorAverage_apply (z : V → C) (f : Pairing V → ℝ) (M : Pairing V) : + colorAverage z f M = + (∑ p : colorStabilizer z, Pairing.act p.1 f M) / Fintype.card (colorStabilizer z) := by + simp [colorAverage, div_eq_mul_inv, mul_comm] + +lemma colorAverage_act (z : V → C) (q : colorStabilizer z) (f : Pairing V → ℝ) : + colorAverage z (Pairing.act q.1 f) = colorAverage z f := by + funext M + simp only [colorAverage_apply, ← Pairing.act_mul] + congr 1 + exact Equiv.sum_comp (Equiv.mulRight q) (fun p : colorStabilizer z => Pairing.act p.1 f M) + +lemma colorAverage_one (z : V → C) : colorAverage z (1 : Pairing V → ℝ) = 1 := by + funext M + simp [colorAverage_apply, Pairing.act_apply, Fintype.card_ne_zero] + +lemma colorAverage_mul_invariant (z : V → C) (f g : Pairing V → ℝ) + (hf : ∀ p : colorStabilizer z, Pairing.act p.1 f = f) : + colorAverage z (f*g) = f * colorAverage z g := by + funext M + simp only [colorAverage_apply, Pi.mul_apply, Pairing.act_apply] + have h (p : colorStabilizer z) : f (Pairing.relabel p.1⁻¹ M) = f M := congrFun (hf p) M + simp_rw [h, ← Finset.mul_sum, mul_div_assoc] + +end ColorAverage +end MatchingSmoothing + +end OAI diff --git a/lean/OAI/Combinatorics/MatchingPSD/EdgeProducts.lean b/lean/OAI/Combinatorics/MatchingPSD/EdgeProducts.lean new file mode 100644 index 0000000000000000000000000000000000000000..b5cd36ce9f558fbc3e60f9519fc6dbe970676f14 --- /dev/null +++ b/lean/OAI/Combinatorics/MatchingPSD/EdgeProducts.lean @@ -0,0 +1,96 @@ +import OAI.Combinatorics.MatchingPSD.Involutions + +namespace OAI + +universe u_1 u_2 u_3 u_4 + +namespace MatchingSmoothing +variable {E : Type u_1} {X : Type u_2} + +def lowDegree (x : E → X → ℝ) (d : ℕ) : Submodule ℝ (X → ℝ) := + Submodule.span ℝ {f | ∃ l : List E, l.length ≤ d ∧ f = (l.map x).prod} + +lemma lowDegree_mono (x : E → X → ℝ) {d e : ℕ} (h : d ≤ e) : + lowDegree x d ≤ lowDegree x e := by + apply Submodule.span_mono + rintro f ⟨l, hl, hf⟩ + exact ⟨l, hl.trans h, hf⟩ + +lemma one_mem_lowDegree (x : E → X → ℝ) (d : ℕ) : (1 : X → ℝ) ∈ lowDegree x d := + Submodule.subset_span ⟨[], Nat.zero_le _, rfl⟩ + +lemma coord_mem_lowDegree (x : E → X → ℝ) (e : E) : x e ∈ lowDegree x 1 := by + apply Submodule.subset_span + exact ⟨[e], by simp, by simp⟩ + +lemma mul_mem_lowDegree (x : E → X → ℝ) {d e : ℕ} {f g : X → ℝ} + (hf : f ∈ lowDegree x d) (hg : g ∈ lowDegree x e) : + f * g ∈ lowDegree x (d + e) := by + refine Submodule.span_induction₂ + (p := fun f g _ _ => f * g ∈ lowDegree x (d + e)) ?_ ?_ ?_ ?_ ?_ ?_ ?_ hf hg + · rintro f g ⟨l, hl, rfl⟩ ⟨m, hm, rfl⟩ + apply Submodule.subset_span + exact ⟨l ++ m, by simpa using Nat.add_le_add hl hm, by simp⟩ + · intro g _; simp + · intro f _; simp + · intro f g h _ _ _ hf hg + simpa only [add_mul] using (lowDegree x (d + e)).add_mem hf hg + · intro f g h _ _ _ hg hh + simpa only [mul_add] using (lowDegree x (d + e)).add_mem hg hh + · intro r f g _ _ h + simpa only [smul_mul_assoc] using (lowDegree x (d + e)).smul_mem r h + · intro r f g _ _ h + simpa only [mul_smul_comm] using (lowDegree x (d + e)).smul_mem r h + +lemma prod_mem_lowDegree {ι : Type u_3} (x : E → X → ℝ) (s : Finset ι) + (f : ι → X → ℝ) (hf : ∀ i ∈ s, f i ∈ lowDegree x 1) : + (∏ i ∈ s, f i) ∈ lowDegree x s.card := by + classical + induction s using Finset.induction_on with + | empty => simpa using one_mem_lowDegree x 0 + | @insert i s his ih => + rw [Finset.prod_insert his, Finset.card_insert_of_notMem his] + have hi := hf i (Finset.mem_insert_self i s) + have hs := ih (fun j hj => hf j (Finset.mem_insert_of_mem hj)) + simpa only [Nat.add_comm] using mul_mem_lowDegree x hi hs + +lemma boolean_pattern_mem_lowDegree [DecidableEq E] + (x : E → X → ℝ) (s t : Finset E) : + (∏ e ∈ s, if e ∈ t then x e else 1 - x e) ∈ lowDegree x s.card := by + apply prod_mem_lowDegree + intro e _ + split_ifs + · exact coord_mem_lowDegree x e + · exact (lowDegree x 1).sub_mem (one_mem_lowDegree x 1) (coord_mem_lowDegree x e) + +lemma mem_of_fiber_indicators {I : Type u_4} [Fintype I] [DecidableEq I] + (θ : X → I) (f : X → ℝ) (S : Submodule ℝ (X → ℝ)) + (hf : ∀ a b, θ a = θ b → f a = f b) + (hind : ∀ a, (fun b => if θ b = θ a then (1 : ℝ) else 0) ∈ S) : f ∈ S := by + classical + let g (i : I) : ℝ := if h : ∃ a, θ a = i then f h.choose else 0 + let b (i : I) : X → ℝ := fun a => if θ a = i then 1 else 0 + have hm (i : I) : g i • b i ∈ S := by + by_cases hi : ∃ a, θ a = i + · have hb : b i = b (θ hi.choose) := by rw [hi.choose_spec] + rw [hb] + exact S.smul_mem _ (hind hi.choose) + · have hb : b i = 0 := by + ext a + have hn : θ a ≠ i := by intro h; exact hi ⟨a, h⟩ + simp [b, hn] + simp [hb] + have he : ∑ i, g i • b i = f := by + ext a + simp only [Finset.sum_apply, Pi.smul_apply, b, smul_eq_mul, mul_ite, mul_one, mul_zero] + simp only [Finset.sum_ite_eq, Finset.mem_univ, ite_true] + have ha : ∃ c, θ c = θ a := ⟨a, rfl⟩ + dsimp [g] + rw [dite_eq_left ha] + exact hf ha.choose a ha.choose_spec + rw [← he] + exact S.sum_mem (fun i _ => hm i) + +end MatchingSmoothing + +end OAI diff --git a/lean/OAI/Combinatorics/MatchingPSD/EquivariantCompression.lean b/lean/OAI/Combinatorics/MatchingPSD/EquivariantCompression.lean new file mode 100644 index 0000000000000000000000000000000000000000..c070d6c37b58eb3299701f4ff6abed4a58df216c --- /dev/null +++ b/lean/OAI/Combinatorics/MatchingPSD/EquivariantCompression.lean @@ -0,0 +1,128 @@ +import OAI.Combinatorics.MatchingPSD.SpectralContraction + +namespace OAI + +universe u_1 u_2 u_3 + +namespace MatchingSmoothing +namespace Pairing +variable {V : Type u_1} + +lemma act_pointwise_mul (p : Equiv.Perm V) (f g : Pairing V → ℝ) : + act p (f * g) = act p f * act p g := rfl + +lemma act_pointwise_one (p : Equiv.Perm V) : act p (1 : Pairing V → ℝ) = 1 := rfl + +lemma act_edgeCoord (p : Equiv.Perm V) (e : V × V) : + act p (edgeCoord e) = edgeCoord (p e.1, p e.2) := by + classical + ext M + simp only [act_apply, edgeCoord, relabel_apply, inv_inv] + congr 1 + exact propext p.symm_apply_eq + +lemma lowDegree_invariant (p : Equiv.Perm V) (d : ℕ) + (f : Pairing V → ℝ) (hf : f ∈ lowDegree edgeCoord d) : + act p f ∈ lowDegree edgeCoord d := by + apply Submodule.span_induction (p := fun f _ => act p f ∈ lowDegree edgeCoord d) + _ _ _ _ hf + · rintro f ⟨l, hl, rfl⟩ + have hprod : act p ((l.map edgeCoord).prod) = + ((l.map (fun e => (p e.1, p e.2))).map edgeCoord).prod := by + clear hl + induction l with + | nil => exact act_pointwise_one p + | cons e l ih => + simp only [List.map_cons, List.prod_cons, act_pointwise_mul, + act_edgeCoord, ih] + rw [hprod] + exact Submodule.subset_span ⟨_, by simpa, rfl⟩ + · simp + · intro f g _ _ hf hg + simpa only [map_add] using (lowDegree edgeCoord d).add_mem hf hg + · intro c f _ hf + simpa only [map_smul] using (lowDegree edgeCoord d).smul_mem c hf + +end Pairing + +open scoped RealInnerProductSpace +section EuclideanPermutations +variable {X : Type u_2} [Fintype X] + +noncomputable def permIso (e : Equiv.Perm X) : + EuclideanSpace ℝ X ≃ₗᵢ[ℝ] EuclideanSpace ℝ X := + LinearIsometryEquiv.piLpCongrLeft 2 ℝ ℝ e + +@[simp] lemma permIso_apply (e : Equiv.Perm X) (v : EuclideanSpace ℝ X) (x : X) : + permIso e v x = v (e.symm x) := rfl + +lemma matrix_equivariant [DecidableEq X] (A : Matrix X X ℝ) (e : Equiv.Perm X) + (hA : ∀ x y, A (e x) (e y) = A x y) (v : EuclideanSpace ℝ X) : + A.toEuclideanLin (permIso e v) = permIso e (A.toEuclideanLin v) := by + ext x + change (∑ y, A x y * v (e.symm y)) = ∑ y, A (e.symm x) y * v y + rw [← Equiv.sum_comp e (fun y => A x y * v (e.symm y))] + apply Finset.sum_congr rfl + intro y _ + rw [e.symm_apply_apply, ← hA (e.symm x) y, e.apply_symm_apply] + +lemma matrix_trace_square [DecidableEq X] (A : Matrix X X ℝ) : + LinearMap.trace ℝ (EuclideanSpace ℝ X) (A.toEuclideanLin * A.toEuclideanLin) = + Matrix.trace (A * A) := by + simp only [Matrix.toLpLin_eq_toLin, Module.End.mul_eq_comp, + ← Matrix.toLin_mul, Matrix.trace_toLin_eq] + +end EuclideanPermutations + +section CompressionEquivariance +variable {E : Type u_3} [NormedAddCommGroup E] [InnerProductSpace ℝ E] + [FiniteDimensional ℝ E] + +omit [FiniteDimensional ℝ E] in +lemma invariant_map_eq (W : Submodule ℝ E) (e : E ≃ₗᵢ[ℝ] E) + (h : ∀ x, x ∈ W → e x ∈ W) (hi : ∀ x, x ∈ W → e.symm x ∈ W) : + W.map e.toLinearEquiv.toLinearMap = W := by + apply le_antisymm + · rintro _ ⟨x, hx, rfl⟩ + exact h x hx + · intro x hx + exact ⟨e.symm x, hi x hx, e.apply_symm_apply x⟩ + +omit [FiniteDimensional ℝ E] in +lemma invariant_orthogonal (W : Submodule ℝ E) (e : E ≃ₗᵢ[ℝ] E) + (hi : ∀ x, x ∈ W → e.symm x ∈ W) (x : E) (hx : x ∈ Wᗮ) : + e x ∈ Wᗮ := by + rw [Submodule.mem_orthogonal] at hx ⊢ + intro y hy + rw [← e.apply_symm_apply y, e.inner_map_map] + exact hx (e.symm y) (hi y hy) + +lemma starProjection_equivariant (W : Submodule ℝ E) (e : E ≃ₗᵢ[ℝ] E) + (h : ∀ x, x ∈ W → e x ∈ W) (hi : ∀ x, x ∈ W → e.symm x ∈ W) + (x : E) : e (W.starProjection x) = W.starProjection (e x) := by + symm + apply Submodule.eq_starProjection_of_mem_of_inner_eq_zero + · exact h _ (W.orthogonalProjectionOnto x).property + · intro y hy + rw [← e.apply_symm_apply y, ← e.map_sub, e.inner_map_map] + exact W.starProjection_inner_eq_zero x (e.symm y) (hi y hy) + +lemma compression_eigenspace_invariant (A : Module.End ℝ E) (W : Submodule ℝ E) + (e : E ≃ₗᵢ[ℝ] E) (h : ∀ x, x ∈ W → e x ∈ W) + (hi : ∀ x, x ∈ W → e.symm x ∈ W) + (hA : ∀ x, A (e x) = e (A x)) (c : ℝ) (x : E) + (hx : x ∈ (Module.End.eigenspace (compression A W) c).map W.subtype) : + e x ∈ (Module.End.eigenspace (compression A W) c).map W.subtype := by + rcases hx with ⟨x, hx, rfl⟩ + refine ⟨⟨e x, h x x.2⟩, ?_, rfl⟩ + simp only [SetLike.mem_coe, Module.End.mem_eigenspace_iff] at hx ⊢ + apply Subtype.ext + have he := congrArg (fun y : W => (y : E)) hx + change W.starProjection (A x) = c • (x : E) at he + change W.starProjection (A (e (x : E))) = c • e (x : E) + rw [hA, ← starProjection_equivariant W e h hi, he, map_smul] + +end CompressionEquivariance +end MatchingSmoothing + +end OAI diff --git a/lean/OAI/Combinatorics/MatchingPSD/FiberAverages.lean b/lean/OAI/Combinatorics/MatchingPSD/FiberAverages.lean new file mode 100644 index 0000000000000000000000000000000000000000..220b679cf5da76f681fcf505bd2564ac9cc58024 --- /dev/null +++ b/lean/OAI/Combinatorics/MatchingPSD/FiberAverages.lean @@ -0,0 +1,125 @@ +import OAI.Combinatorics.MatchingPSD.PolynomialSpaces + +namespace OAI + +universe u_1 u_2 u_3 + +namespace MatchingSmoothing +open Matrix +attribute [local instance] Classical.propDecidable +section FiberAverages +variable {X : Type u_1} {Z : Type u_2} [Fintype X] [Fintype Z] + +noncomputable def fiberAverage (P : X → Z → Prop) (f : X → ℝ) (z : Z) : ℝ := + conditionalAverage P (Fintype.card {x // P x z}) f z + +lemma cardinal_fibers_balance (P : X → Z → Prop) (D E : ℕ) + (hD : ∀ x, Fintype.card {z // P x z} = D) + (hE : ∀ z, Fintype.card {x // P x z} = E) : + Fintype.card X * D = Fintype.card Z * E := by + classical + calc + _ = ∑ x : X, Fintype.card {z // P x z} := by simp [hD] + _ = ∑ z : Z, Fintype.card {x // P x z} := by + simp only [Fintype.card_subtype, Finset.card_filter] + exact Finset.sum_comm + _ = _ := by simp [hE] + +end FiberAverages + +section TableFibers +variable {H : Type u_3} [Fintype H] [DecidableEq H] + +lemma table_row_card (f₀ : H × Bool → Fin 3) (hH : 0 < Fintype.card H) + (M : Pairing (H × Bool)) : + Fintype.card {z // tableRelation f₀ M z} = + Fintype.card {f : H × Bool → Fin 3 // threeTable f = threeTable f₀} := by + classical + obtain ⟨p, rfl⟩ := Pairing.exists_relabel (standardPairing (H := H)) M + apply Fintype.card_congr + refine ((coloringPerm (histogram f₀) p).subtypeEquiv + (q := tableRelation f₀ standardPairing) (fun z => ?_)).trans ?_ + · change ((Pairing.relabel p standardPairing).table z.1 = _) ↔ + (standardPairing.table (z.1 ∘ p) = _) + rw [Pairing.table_relabel] + · refine { toFun := fun z => ⟨z.1.1, ?_⟩ + invFun := fun f => ⟨⟨f.1, threeTable_histogram_eq hH f.2⟩, ?_⟩ + left_inv := fun _ => rfl + right_inv := fun _ => rfl } + · simpa only [tableRelation, standardPairing_table] using z.2 + · simpa only [tableRelation, standardPairing_table] using f.2 + +omit [DecidableEq H] in +lemma table_col_card (f₀ : H × Bool → Fin 3) + (z w : Colorings (H × Bool) (Fin 3) (histogram f₀)) : + Fintype.card {M // tableRelation f₀ M z} = + Fintype.card {M // tableRelation f₀ M w} := by + classical + let p := permOfHistogram (z.2.trans w.2.symm) + have hp : w.1 ∘ p = z.1 := funext (permOfHistogram_spec _) + apply Fintype.card_congr + apply (Pairing.relabelEquiv p).subtypeEquiv + intro M + change (M.table z.1 = _) ↔ ((Pairing.relabel p M).table w.1 = _) + rw [Pairing.table_relabel, hp] + +lemma table_fiber_size (f₀ : H × Bool → Fin 3) (hH : 0 < Fintype.card H) + (z : Colorings (H × Bool) (Fin 3) (histogram f₀)) : + (Fintype.card {M // tableRelation f₀ M z} : ℝ) = + (Fintype.card (Pairing (H × Bool)) : ℝ) * + Fintype.card {f : H × Bool → Fin 3 // threeTable f = threeTable f₀} / + Fintype.card (Colorings (H × Bool) (Fin 3) (histogram f₀)) := by + classical + have : Nonempty (Colorings (H × Bool) (Fin 3) (histogram f₀)) := ⟨⟨f₀, rfl⟩⟩ + have he := cardinal_fibers_balance (tableRelation f₀) _ _ + (table_row_card f₀ hH) (fun w => table_col_card f₀ w z) + apply (eq_div_iff (Nat.cast_ne_zero.mpr Fintype.card_ne_zero)).mpr + have hr : (Fintype.card (Pairing (H × Bool)) : ℝ) * + Fintype.card {f : H × Bool → Fin 3 // threeTable f = threeTable f₀} = + Fintype.card (Colorings (H × Bool) (Fin 3) (histogram f₀)) * + Fintype.card {M // tableRelation f₀ M z} := by exact_mod_cast he + rw [mul_comm] + exact hr.symm + +end TableFibers + +open scoped RealInnerProductSpace +lemma table_smoothing_bound {h : ℕ} (k : ℕ) (hk : 4*k < h) + (f₀ : Vertices h → Fin 3) (hf₀ : ∀ i, 0 < histogram f₀ i) + (a : ℝ) (ha : 0 ≤ a) (hHa : (h+1 : ℝ)^33 ≤ (h.choose k : ℝ) * a^2) + (f : MatchingSpace h) (hf : f ∈ (polynomialSpace h ((4*k)*(4*k)))ᗮ) : + (∑ z, fiberAverage (tableRelation f₀) (matchingEquiv h f) z ^ 2) / + Fintype.card (Colorings (Vertices h) (Fin 3) (histogram f₀)) ≤ + a * ((∑ M, (f M)^2) / Fintype.card (Pairing (Vertices h))) := by + classical + have hH : 0 < Fintype.card (Fin h) := by simpa using (show 0 < h by omega) + have : Nonempty (Pairing (Vertices h)) := ⟨standardPairing⟩ + have : Nonempty (Colorings (Vertices h) (Fin 3) (histogram f₀)) := ⟨⟨f₀, rfl⟩⟩ + let D : ℝ := Fintype.card {f : Vertices h → Fin 3 // threeTable f = threeTable f₀} + have hD : D ≠ 0 := by + have : Nonempty {f : Vertices h → Fin 3 // threeTable f = threeTable f₀} := ⟨⟨f₀, rfl⟩⟩ + exact Nat.cast_ne_zero.mpr Fintype.card_ne_zero + have he : (∑ z, fiberAverage (tableRelation f₀) (matchingEquiv h f) z ^ 2) / + Fintype.card (Colorings (Vertices h) (Fin 3) (histogram f₀)) = + (∑ M, f M * (incidenceOperator (tableRelation f₀) D *ᵥ (matchingEquiv h f)) M) / + Fintype.card (Pairing (Vertices h)) := by + simp only [fiberAverage, table_fiber_size f₀ hH] + exact conditionalAverage_energy _ D hD _ + rw [he] + have hb := symmetric_matching_smoothing k hk (incidenceOperator (tableRelation f₀) D) + (incidenceOperator_posSemidef _ _).isHermitian + (fun p M N => by + simp only [incidenceOperator, incidenceKernel, commonIncidence_table_relabel]) + ((h+1)^33) a ha (by simpa using matching_table_trace_square f₀ hH hf₀) hHa f hf + rw [EuclideanSpace.real_norm_sq_eq] at hb + have hinner : ⟪f, (incidenceOperator (tableRelation f₀) D).toEuclideanLin f⟫ = + ∑ M, f M * (incidenceOperator (tableRelation f₀) D *ᵥ (matchingEquiv h f)) M := by + simp only [EuclideanSpace.inner_eq_star_dotProduct, star_trivial] + exact dotProduct_comm _ _ + rw [hinner] at hb + simpa only [mul_div_assoc] using div_le_div_of_nonneg_right hb + (show (0 : ℝ) ≤ Fintype.card (Pairing (Vertices h)) by positivity) + +end MatchingSmoothing + +end OAI diff --git a/lean/OAI/Combinatorics/MatchingPSD/FiniteFactorization.lean b/lean/OAI/Combinatorics/MatchingPSD/FiniteFactorization.lean new file mode 100644 index 0000000000000000000000000000000000000000..06652f62df57d6c161335202281198b36cc26e02 --- /dev/null +++ b/lean/OAI/Combinatorics/MatchingPSD/FiniteFactorization.lean @@ -0,0 +1,120 @@ +import OAI.Combinatorics.MatchingPSD.CellLowerBound + +namespace OAI + +universe u_1 u_2 + +namespace PerfectMatchingPSD + +lemma endpoint_count {n : ℕ} (U : Finset (Fin n)) (M : PerfectMatching n) : + (∑ e ∈ M.1, ((if e.1.1 ∈ U then 1 else 0) + + (if e.1.2 ∈ U then 1 else 0) : ℕ)) = U.card := by + classical + have pair_count (e : Edge n) : + (∑ v ∈ U, (if e.1.1 = v ∨ e.1.2 = v then 1 else 0 : ℕ)) = + (if e.1.1 ∈ U then 1 else 0) + (if e.1.2 ∈ U then 1 else 0) := by + have pointwise (v : Fin n) : + (if e.1.1 = v ∨ e.1.2 = v then 1 else 0 : ℕ) = + (if e.1.1 = v then 1 else 0) + (if e.1.2 = v then 1 else 0) := by + have hne : e.1.1 ≠ e.1.2 := ne_of_lt e.2 + by_cases h₁ : e.1.1 = v <;> by_cases h₂ : e.1.2 = v <;> simp_all + simp_rw [pointwise] + simp [Finset.sum_add_distrib] + calc + _ = ∑ e ∈ M.1, ∑ v ∈ U, + (if e.1.1 = v ∨ e.1.2 = v then 1 else 0 : ℕ) := by + apply Finset.sum_congr rfl + intro e _ + exact (pair_count e).symm + _ = ∑ v ∈ U, ∑ e ∈ M.1, + (if e.1.1 = v ∨ e.1.2 = v then 1 else 0 : ℕ) := Finset.sum_comm + _ = ∑ v ∈ U, (M.1.filter fun e => e.1.1 = v ∨ e.1.2 = v).card := by + simp only [Finset.sum_boole, Nat.cast_id] + _ = U.card := by + have hm : ∀ v : Fin n, + (M.1.filter fun e => e.1.1 = v ∨ e.1.2 = v).card = 1 := M.2 + simp [hm] + +lemma cut_degree_identity {n : ℕ} (U : Finset (Fin n)) (M : PerfectMatching n) : + U.card = 2 * (M.1.filter fun e => e.1.1 ∈ U ∧ e.1.2 ∈ U).card + + crossingCount U M := by + classical + rw [← endpoint_count U M] + have term (e : Edge n) : + ((if e.1.1 ∈ U then 1 else 0) + (if e.1.2 ∈ U then 1 else 0) : ℕ) = + 2 * (if e.1.1 ∈ U ∧ e.1.2 ∈ U then 1 else 0) + + (if Crosses U e then 1 else 0) := by + by_cases h₁ : e.1.1 ∈ U <;> by_cases h₂ : e.1.2 ∈ U <;> + simp [h₁, h₂, Crosses] + simp_rw [term] + rw [Finset.sum_add_distrib, ← Finset.mul_sum] + simp only [Finset.sum_boole, Nat.cast_id, crossingCount] + +lemma crossingCount_pos {n : ℕ} (U : OddCut n) (M : PerfectMatching n) : + 0 < crossingCount U.1 M := by + obtain ⟨k, hk⟩ := U.2 + have h := cut_degree_identity U.1 M + omega + +lemma slack_nonneg {n : ℕ} (i : Row n) (M : PerfectMatching n) : + 0 ≤ slack i M := by + classical + rcases i with e | U + · simp only [slack] + split_ifs <;> norm_num + · have h : 1 ≤ crossingCount U.1 M := crossingCount_pos U M + have hr : (1 : ℝ) ≤ (crossingCount U.1 M : ℝ) := by exact_mod_cast h + simpa only [slack, sub_nonneg] using hr + +lemma exists_diagonal_factorization {I : Type u_1} {J : Type u_2} [Finite J] + (S : I → J → ℝ) (hS : ∀ i j, 0 ≤ S i j) : + ∃ r : ℕ, 0 < r ∧ + ∃ (A : I → Matrix (Fin r) (Fin r) ℝ) + (B : J → Matrix (Fin r) (Fin r) ℝ), + (∀ i, (A i).PosSemidef) ∧ (∀ j, (B j).PosSemidef) ∧ + ∀ i j, S i j = Matrix.trace (A i * B j) := by + classical + let : Fintype J := Fintype.ofFinite J + let e := Fintype.equivFin (Option J) + let a (i : I) (k : Option J) : ℝ := k.elim 0 (S i) + let b (j : J) (k : Option J) : ℝ := if k = some j then 1 else 0 + refine ⟨Fintype.card (Option J), by simp, + (fun i => (Matrix.diagonal (a i)).submatrix e.symm e.symm), + (fun j => (Matrix.diagonal (b j)).submatrix e.symm e.symm), ?_, ?_, ?_⟩ + · intro i + apply Matrix.PosSemidef.submatrix + apply Matrix.PosSemidef.diagonal + intro k + cases k with + | none => exact le_rfl + | some j => exact hS i j + · intro j + apply Matrix.PosSemidef.submatrix + apply Matrix.PosSemidef.diagonal + intro k + dsimp [b] + split_ifs <;> norm_num + · intro i j + rw [Matrix.submatrix_mul_equiv, Matrix.diagonal_mul_diagonal, + Matrix.submatrix_diagonal _ _ e.symm.injective, Matrix.trace_diagonal] + dsimp only [Function.comp_def] + rw [e.symm.sum_comp (fun k => a i k * b j k)] + simp [a, b] + +lemma factor_orders_nonempty (n : ℕ) : + {r : ℕ | 0 < r ∧ HasFactorization n r}.Nonempty := by + obtain ⟨r, hr, h⟩ := exists_diagonal_factorization (@slack n) slack_nonneg + exact ⟨r, hr, h⟩ + +lemma psdRank_pos (n : ℕ) : 0 < psdRank n := + (Nat.sInf_mem (factor_orders_nonempty n)).1 + +lemma hasFactorization_psdRank (n : ℕ) : HasFactorization n (psdRank n) := + (Nat.sInf_mem (factor_orders_nonempty n)).2 + +lemma psdRank_le {n r : ℕ} (hr : 0 < r) (h : HasFactorization n r) : + psdRank n ≤ r := Nat.sInf_le ⟨hr, h⟩ + +end PerfectMatchingPSD + +end OAI diff --git a/lean/OAI/Combinatorics/MatchingPSD/GlobalGeometry.lean b/lean/OAI/Combinatorics/MatchingPSD/GlobalGeometry.lean new file mode 100644 index 0000000000000000000000000000000000000000..01635bf7fc9b47c3e58fbca56e430643a9de48bb --- /dev/null +++ b/lean/OAI/Combinatorics/MatchingPSD/GlobalGeometry.lean @@ -0,0 +1,115 @@ +import OAI.Combinatorics.MatchingPSD.MatchingFibers + +namespace OAI + +universe u_1 u_2 u_3 u_4 u_5 u_6 u_7 + +namespace MatchingSmoothing +open scoped BigOperators +attribute [local instance] Classical.propDecidable + +section ThreeCellGeometry +variable {A : Type u_1} {B : Type u_2} {C : Type u_3} [Fintype A] [Fintype B] [Fintype C] + +def abColor : A ⊕ B → Fin 3 := Sum.elim (fun _ => 0) (fun _ => 1) +def threeColor : (A ⊕ B) ⊕ C → Fin 3 := Sum.elim abColor (fun _ => 2) +noncomputable def crossVector {V : Type u_4} [Fintype V] (z : V → Fin 3) + (M : Pairing V) : Fin 3 → ℝ := fun i => crossCoordinate z i M + +lemma crossVector_sum (M : Pairing (A ⊕ B)) (N : Pairing C) : + crossVector threeColor (Pairing.sum M N) = ![tableCoordinate abColor (0,1) M,0,0] := by + have h02 : tableCoordinate (abColor : A ⊕ B → Fin 3) (0,2) M = 0 := by + apply (tableCoordinate_eq_zero_iff _ _ _).mpr + intro v hv + have hh := hv.2 + cases he : M.1 v <;> simp [he, abColor] at hh + have h12 : tableCoordinate (abColor : A ⊕ B → Fin 3) (1,2) M = 0 := by + apply (tableCoordinate_eq_zero_iff _ _ _).mpr + intro v hv + have hh := hv.2 + cases he : M.1 v <;> simp [he, abColor] at hh + funext i + fin_cases i <;> + simp [crossVector, crossCoordinate, crossPair, threeColor, + tableCoordinate_sum, tableCoordinate_constant, h02, h12] + +lemma threeColor_closed (M : Pairing ((A ⊕ B) ⊕ C)) + (h1 : crossCoordinate threeColor 1 M = 0) (h2 : crossCoordinate threeColor 2 M = 0) : + ∀ a : A ⊕ B, ∃ a' : A ⊕ B, M.1 (.inl a) = .inl a' := by + have h1' := (tableCoordinate_eq_zero_iff _ _ _).mp h1 + have h2' := (tableCoordinate_eq_zero_iff _ _ _).mp h2 + intro a + cases hm : M.1 (.inl a) with + | inl a' => exact ⟨a',rfl⟩ + | inr c => + cases a with + | inl a => exact False.elim (h1' (.inl (.inl a)) ⟨rfl, by rw [hm]; rfl⟩) + | inr b => exact False.elim (h2' (.inl (.inr b)) ⟨rfl, by rw [hm]; rfl⟩) + +noncomputable def starFiberEquiv (x : ℝ) : + {M : Pairing (A ⊕ B) // tableCoordinate abColor (0,1) M = x} × Pairing C ≃ + {M : Pairing ((A ⊕ B) ⊕ C) // crossVector threeColor M = ![x,0,0]} := + Pairing.sumFiberEquiv _ _ + (fun M N => by rw [crossVector_sum]; simp) + (fun M hM => threeColor_closed M + (by have := congrFun hM 1; exact this) + (by have := congrFun hM 2; exact this)) + +end ThreeCellGeometry + +section GlobalExtension +variable {D : Type u_5} {C : Type u_6} {I : Type u_7} [DecidableEq I] + +def insertCellEquiv (i : I) : C ⊕ ({j : I // j ≠ i} × C) ≃ I × C where + toFun v := v.elim (fun c => (i,c)) (fun jc => (jc.1.1,jc.2)) + invFun v := if h : v.1 = i then .inl v.2 else .inr (⟨v.1,h⟩,v.2) + left_inv v := by + cases v with + | inl c => simp + | inr jc => simp [jc.1.2] + right_inv v := by + rcases v with ⟨j,c⟩ + by_cases h : j = i <;> simp_all + +def localSplitEquiv (i : I) : (D ⊕ C) ⊕ ({j : I // j ≠ i} × C) ≃ D ⊕ (I × C) := + (Equiv.sumAssoc D C _).trans (Equiv.sumCongr (Equiv.refl D) (insertCellEquiv i)) + +def extendLocal (i : I) (M : Pairing (D ⊕ C)) (N : {j : I // j ≠ i} → Pairing C) : + Pairing (D ⊕ (I × C)) := + Pairing.transport (localSplitEquiv i) (Pairing.sum M (Pairing.cellwise N)) + +def liftLocal (i : I) (p : Equiv.Perm (D ⊕ C)) : Equiv.Perm (D ⊕ (I × C)) := + (localSplitEquiv i).symm.trans + ((Equiv.sumCongr p (Equiv.refl _)).trans (localSplitEquiv i)) + +lemma extendLocal_relabel (i : I) (p : Equiv.Perm (D ⊕ C)) + (M : Pairing (D ⊕ C)) (N : {j : I // j ≠ i} → Pairing C) : + extendLocal i (Pairing.relabel p M) N = Pairing.relabel (liftLocal i p) (extendLocal i M N) := by + rw [extendLocal, Pairing.sum_relabel_left, Pairing.transport_relabel] + rfl + +lemma localSplit_inl (i : I) (d : D) : + localSplitEquiv (C := C) i (.inl (.inl d)) = .inl d := rfl +lemma localSplit_cell (i : I) (c : C) : + localSplitEquiv (D := D) i (.inl (.inr c)) = .inr (i,c) := rfl +lemma localSplit_outside (i : I) (v : {j : I // j ≠ i} × C) : + localSplitEquiv (D := D) i (.inr v) = .inr (v.1.1,v.2) := rfl + +lemma extendLocal_sum (i : I) (M : Pairing D) (N : I → Pairing C) : + extendLocal i (Pairing.sum M (N i)) (fun j => N j.1) = + Pairing.sum M (Pairing.cellwise N) := by + apply Pairing.ext + intro v + obtain ⟨v,rfl⟩ := (localSplitEquiv (D := D) (C := C) i).surjective v + simp only [extendLocal, Pairing.transport_apply, Equiv.symm_apply_apply] + cases v with + | inl v => + cases v with + | inl d => rfl + | inr c => rfl + | inr jc => rfl + +end GlobalExtension +end MatchingSmoothing + +end OAI diff --git a/lean/OAI/Combinatorics/MatchingPSD/GoodCells.lean b/lean/OAI/Combinatorics/MatchingPSD/GoodCells.lean new file mode 100644 index 0000000000000000000000000000000000000000..0772eff7148aa54ad3fa33283a5210ba5d81e149 --- /dev/null +++ b/lean/OAI/Combinatorics/MatchingPSD/GoodCells.lean @@ -0,0 +1,89 @@ +import OAI.Combinatorics.MatchingPSD.MatrixInterpolation + +namespace OAI + +namespace MatchingInterpolation +open MatchingSmoothing PerfectMatchingPSD Matrix +open scoped BigOperators +attribute [local instance] Classical.propDecidable + +abbrev SampleIndex (d : ℕ) := Fin 5 ⊕ GridIndex d +noncomputable def samplePoint (d : ℕ) (L : ℝ) : SampleIndex d → Point := + Sum.elim specialPoint (scaledNode L) + +lemma specialPoint_explicit (j : Fin 5) : + specialPoint j = (![![1,0,0], ![0,1,1], ![3,0,0], ![1,2,0], ![1,0,2]] j : Point) := by + fin_cases j <;> ext a <;> fin_cases a <;> norm_num [specialPoint, origin, dirP, dirStar, dirA, dirB] + +lemma sample_witness {s l d : ℕ} (hs : 1 ≤ s) (hsl : 2*l*d ≤ s) (t : SampleIndex d) : + ∃ M : Pairing (TripleVertices s), crossVector threeColor M = samplePoint d (2*l) t := by + rcases t with j | g + · rw [samplePoint, Sum.elim_inl, specialPoint_explicit] + exact triple_pairing_five hs j + · exact triple_pairing_grid hsl g + +lemma good_cell_polynomials (K : ℕ) : + ∃ d H : ℕ, 0 < d ∧ ∀ s q l r : ℕ, H ≤ 3*s+1 → 1 ≤ s → 2*l*d ≤ s → + ∀ (B : Pairing (GlobalVertices s q) → Matrix (Fin r) (Fin r) ℝ), + (∀ M, (B M).PosSemidef) → (∀ M, (B M).trace ≤ (r:ℝ)) → + ∀ η : ℝ, 0 ≤ η → + (q:ℝ)*r^4*(Fintype.card (SampleIndex d))*((2*(3*s+1):ℝ)^(2*K))⁻¹ ≤ η^2 → + ∃ a : Equiv.Perm (GlobalVertices s q), + ∃ P : Fin q → Fin r → Fin r → Point → ℝ, + (∀ i u v, P i u v ∈ lowDegree coord d) ∧ + ∀ i u v t, |cellMatrix i (fun M => B (Pairing.relabel a M)) + (samplePoint d (2*l) t) u v-P i u v (samplePoint d (2*l) t)| ≤ η := by + classical + obtain ⟨d,H,hd,hmain⟩ := simultaneous_cross_approximation K + refine ⟨d,H,hd,?_⟩ + intro s q l r hH hs hsl B hB htr η hη hnum + let J := Fin q × (Fin r × Fin r) + let T := SampleIndex d + let M : T → Pairing (TripleVertices s) := fun t => (sample_witness hs hsl t).choose + have hM (t : T) : crossVector threeColor (M t) = samplePoint d (2*l) t := + (sample_witness hs hsl t).choose_spec + let g (j : J) (a : Equiv.Perm (GlobalVertices s q)) (N : Pairing (TripleVertices s)) : ℝ := + extensionAverage j.1 (fun Z => B (Pairing.relabel a Z) j.2.1 j.2.2) N + have hg (j : J) (a : Equiv.Perm (GlobalVertices s q)) (p : Equiv.Perm (TripleVertices s)) : + g j (a * liftLocal j.1 p) = fun N => g j a (Pairing.relabel p N) := by + funext N + dsimp only [g] + rw [extensionAverage_relabel] + simp only [Pairing.relabel_mul] + have hgb (j : J) (a : Equiv.Perm (GlobalVertices s q)) (N : Pairing (TripleVertices s)) : + (g j a N)^2 ≤ (r:ℝ)^2 := + extensionAverage_sq_bound j.1 _ (fun Z => hB _) (Nat.cast_nonneg r) + (fun Z => htr _) j.2.1 j.2.2 N + obtain ⟨a,P,hP,hbound⟩ := hmain (3*s+1) hH (TripleVertices s) + (Equiv.Perm (GlobalVertices s q)) J T (tripleEquiv s) (fun _ => threeColor) + (fun _ c => triple_histogram_pos (by omega) c) (fun _ => M) + (fun j => liftLocal j.1) g hg (r:ℝ) hgb + refine ⟨a,fun i u v => P (i,u,v),fun i u v => hP (i,u,v),?_⟩ + intro i u v t + let E (j : J) (t : T) := + predicateAverage (fun N => crossVector threeColor N = crossVector threeColor (M t)) (g j a) - + P j (crossVector threeColor (M t)) + have hjt : (E (i,u,v) t)^2 ≤ ∑ j, ∑ t, (E j t)^2 := by + exact (Finset.single_le_sum (fun z _ => sq_nonneg (E (i,u,v) z)) (Finset.mem_univ t)).trans + (Finset.single_le_sum (fun j _ => Finset.sum_nonneg (fun z _ => sq_nonneg (E j z))) + (Finset.mem_univ (i,u,v))) + have hb : (∑ j, ∑ t, (E j t)^2) ≤ η^2 := by + apply hbound.trans + have heq : (Fintype.card J : ℝ)*(Fintype.card T)*((2*(3*s+1:ℕ):ℝ)^(2*K))⁻¹*(r:ℝ)^2 = + (q:ℝ)*r^4*(Fintype.card (SampleIndex d))*((2*(3*s+1):ℝ)^(2*K))⁻¹ := by + simp only [J, T, Fintype.card_prod, Fintype.card_fin, Nat.cast_mul, Nat.cast_add, Nat.cast_ofNat] + ring + rw [heq] + exact hnum + have hab : |E (i,u,v) t| ≤ η := (sq_le_sq₀ (abs_nonneg _) hη).mp + (by simpa only [sq_abs] using hjt.trans hb) + have he : E (i,u,v) t = cellMatrix i (fun Z => B (Pairing.relabel a Z)) + (samplePoint d (2*l) t) u v-P (i,u,v) (samplePoint d (2*l) t) := by + rw [cellMatrix_apply] + dsimp only [E, cellAverage, g] + rw [hM] + rwa [he] at hab + +end MatchingInterpolation + +end OAI diff --git a/lean/OAI/Combinatorics/MatchingPSD/IncidenceKernels.lean b/lean/OAI/Combinatorics/MatchingPSD/IncidenceKernels.lean new file mode 100644 index 0000000000000000000000000000000000000000..8d112e77fb0d39a5c41f4a454a2a7d8d6b53c168 --- /dev/null +++ b/lean/OAI/Combinatorics/MatchingPSD/IncidenceKernels.lean @@ -0,0 +1,171 @@ +import OAI.Combinatorics.MatchingPSD.TableMoments + +namespace OAI + +universe u_1 u_2 u_3 u_4 u_5 u_6 + +namespace MatchingSmoothing +open Matrix + +section FiniteSums +variable {G : Type u_1} {X : Type u_2} [Fintype G] [Group G] [Fintype X] [MulAction G X] + +omit [Fintype G] in +lemma sum_smul_eq (g : G) (f : X → ℝ) : ∑ x, f (g • x) = ∑ x, f x := + Equiv.sum_comp (MulAction.toPerm g) f + +omit [Fintype X] in +lemma sum_group_smul_eq (x₀ : X) (ht : ∀ x, ∃ g : G, g • x₀ = x) + (f : X → ℝ) (x : X) : ∑ g : G, f (g • x) = ∑ g : G, f (g • x₀) := by + obtain ⟨h, rfl⟩ := ht x + simp_rw [← mul_smul] + exact Equiv.sum_comp (Equiv.mulRight h) (fun g => f (g • x₀)) + +lemma group_smul_sum_card (x₀ : X) (ht : ∀ x, ∃ g : G, g • x₀ = x) + (f : X → ℝ) : + (Fintype.card G : ℝ) * ∑ x, f x = + (Fintype.card X : ℝ) * ∑ g : G, f (g • x₀) := by + calc + _ = ∑ g : G, ∑ x, f (g • x) := by simp only [sum_smul_eq, Finset.sum_const, + Finset.card_univ, nsmul_eq_mul] + _ = ∑ x, ∑ g : G, f (g • x) := Finset.sum_comm + _ = _ := by simp_rw [sum_group_smul_eq x₀ ht, Finset.sum_const, + Finset.card_univ, nsmul_eq_mul] + +omit [Fintype G] in +lemma invariant_kernel_sum (x₀ : X) (ht : ∀ x, ∃ g : G, g • x₀ = x) + (K : X → X → ℝ) (hK : ∀ (g : G) x y, K (g • x) (g • y) = K x y) : + (∑ x, ∑ y, K x y) = (Fintype.card X : ℝ) * ∑ y, K x₀ y := by + have he (x : X) : ∑ y, K x y = ∑ y, K x₀ y := by + obtain ⟨g, rfl⟩ := ht x + rw [← sum_smul_eq g (fun y => K (g • x₀) y)] + simp_rw [hK] + simp_rw [he, Finset.sum_const, Finset.card_univ, nsmul_eq_mul] + +lemma invariant_kernel_double_sum_group (x₀ : X) + (ht : ∀ x, ∃ g : G, g • x₀ = x) + (K : X → X → ℝ) (hK : ∀ (g : G) x y, K (g • x) (g • y) = K x y) : + (Fintype.card G : ℝ) * (∑ x, ∑ y, K x y) = + (Fintype.card X : ℝ) ^ 2 * ∑ g : G, K x₀ (g • x₀) := by + rw [invariant_kernel_sum x₀ ht K hK] + have h := group_smul_sum_card x₀ ht (K x₀) + nlinarith [h] + +end FiniteSums + +section KernelTrace +variable {G : Type u_3} {X : Type u_4} [Fintype G] [Group G] [Fintype X] [DecidableEq X] + [MulAction G X] + +omit [DecidableEq X] in +lemma trace_normalized_kernel_sq (K : Matrix X X ℝ) (hs : ∀ x y, K x y = K y x) : + Matrix.trace ((Matrix.of fun x y => K x y / Fintype.card X) * + (Matrix.of fun x y => K x y / Fintype.card X)) = + (∑ x, ∑ y, K x y ^ 2) / (Fintype.card X : ℝ) ^ 2 := by + simp only [Matrix.trace, Matrix.diag, Matrix.mul_apply, Matrix.of_apply, Finset.sum_div] + apply Finset.sum_congr rfl + intro x _ + apply Finset.sum_congr rfl + intro y _ + rw [hs y x] + ring + +omit [DecidableEq X] in +lemma trace_normalized_invariant_kernel_sq (x₀ : X) + (ht : ∀ x, ∃ g : G, g • x₀ = x) + (K : Matrix X X ℝ) (hs : ∀ x y, K x y = K y x) + (hi : ∀ (g : G) x y, K (g • x) (g • y) = K x y) : + Matrix.trace ((Matrix.of fun x y => K x y / Fintype.card X) * + (Matrix.of fun x y => K x y / Fintype.card X)) = + (∑ g : G, K x₀ (g • x₀) ^ 2) / (Fintype.card G : ℝ) := by + have : Nonempty X := ⟨x₀⟩ + rw [trace_normalized_kernel_sq K hs] + have h := invariant_kernel_double_sum_group x₀ ht + (fun x y => K x y ^ 2) (fun g x y => congrArg (fun a : ℝ => a ^ 2) (hi g x y)) + have hx : (Fintype.card X : ℝ) ≠ 0 := Nat.cast_ne_zero.mpr Fintype.card_ne_zero + have hg : (Fintype.card G : ℝ) ≠ 0 := Nat.cast_ne_zero.mpr Fintype.card_ne_zero + apply (div_eq_div_iff (pow_ne_zero _ hx) hg).mpr + nlinarith [h] + +end KernelTrace + +section Incidence +variable {X : Type u_5} {Z : Type u_6} [Fintype X] [Fintype Z] [DecidableEq X] [DecidableEq Z] + +noncomputable def incidence (P : X → Z → Prop) : Matrix Z X ℝ := + by classical exact fun z x => if P x z then 1 else 0 + +noncomputable def commonIncidence (P : X → Z → Prop) (x y : X) : ℝ := + by classical exact (Fintype.card {z // P x z ∧ P y z} : ℝ) + +omit [Fintype X] [DecidableEq X] [DecidableEq Z] in +lemma commonIncidence_eq (P : X → Z → Prop) (x y : X) : + commonIncidence P x y = ∑ z, incidence P z x * incidence P z y := by + classical + simp only [commonIncidence, Fintype.card_subtype, Finset.card_filter, Nat.cast_sum] + apply Finset.sum_congr rfl + intro z _ + by_cases hx : P x z <;> by_cases hy : P y z <;> simp [incidence, hx, hy] + +omit [Fintype X] [DecidableEq X] [DecidableEq Z] in +lemma commonIncidence_symm (P : X → Z → Prop) (x y : X) : + commonIncidence P x y = commonIncidence P y x := by + simp only [commonIncidence_eq, mul_comm] + +noncomputable def incidenceKernel (P : X → Z → Prop) (D : ℝ) : Matrix X X ℝ := + fun x y => (Fintype.card Z : ℝ) / D ^ 2 * commonIncidence P x y + +noncomputable def incidenceOperator (P : X → Z → Prop) (D : ℝ) : Matrix X X ℝ := + fun x y => incidenceKernel P D x y / Fintype.card X + +omit [Fintype X] [DecidableEq X] [DecidableEq Z] in +lemma incidenceKernel_symm (P : X → Z → Prop) (D : ℝ) (x y : X) : + incidenceKernel P D x y = incidenceKernel P D y x := by + unfold incidenceKernel + rw [commonIncidence_symm P x y] + +omit [DecidableEq X] [DecidableEq Z] in +lemma incidenceOperator_eq (P : X → Z → Prop) (D : ℝ) : + incidenceOperator P D = + ((Fintype.card Z : ℝ) / (D ^ 2 * Fintype.card X)) • + ((incidence P).transpose * incidence P) := by + ext x y + simp only [incidenceOperator, incidenceKernel, commonIncidence_eq, Matrix.smul_apply, + smul_eq_mul, Matrix.mul_apply, Matrix.transpose_apply] + ring + +omit [DecidableEq X] [DecidableEq Z] in +lemma incidenceOperator_posSemidef (P : X → Z → Prop) (D : ℝ) : + (incidenceOperator P D).PosSemidef := by + rw [incidenceOperator_eq] + apply Matrix.PosSemidef.smul + · simpa only [Matrix.conjTranspose_eq_transpose_of_trivial] using + Matrix.posSemidef_conjTranspose_mul_self (incidence P) + · positivity + +noncomputable def conditionalAverage (P : X → Z → Prop) (E : ℝ) (f : X → ℝ) (z : Z) : ℝ := + (∑ x, incidence P z x * f x) / E + +omit [DecidableEq X] [DecidableEq Z] in +lemma conditionalAverage_energy [Nonempty X] [Nonempty Z] + (P : X → Z → Prop) (D : ℝ) (hD : D ≠ 0) (f : X → ℝ) : + (∑ z, conditionalAverage P ((Fintype.card X : ℝ) * D / Fintype.card Z) f z ^ 2) / + Fintype.card Z = + (∑ x, f x * (incidenceOperator P D *ᵥ f) x) / Fintype.card X := by + have hx : (Fintype.card X : ℝ) ≠ 0 := Nat.cast_ne_zero.mpr Fintype.card_ne_zero + have hz : (Fintype.card Z : ℝ) ≠ 0 := Nat.cast_ne_zero.mpr Fintype.card_ne_zero + change _ = (f ⬝ᵥ (incidenceOperator P D *ᵥ f)) / Fintype.card X + rw [incidenceOperator_eq, Matrix.smul_mulVec, dotProduct_smul, + ← Matrix.mulVec_mulVec, Matrix.dotProduct_mulVec, Matrix.vecMul_transpose] + simp only [conditionalAverage, div_pow, ← Finset.sum_div, smul_eq_mul] + change (∑ z, ((incidence P *ᵥ f) z) ^ 2) / + (((Fintype.card X : ℝ) * D) ^ 2 / (Fintype.card Z : ℝ) ^ 2) / Fintype.card Z = + ((Fintype.card Z : ℝ) / (D ^ 2 * Fintype.card X)) * + (∑ z, (incidence P *ᵥ f) z * (incidence P *ᵥ f) z) / Fintype.card X + simp only [← pow_two] + field_simp + +end Incidence +end MatchingSmoothing + +end OAI diff --git a/lean/OAI/Combinatorics/MatchingPSD/Involutions.lean b/lean/OAI/Combinatorics/MatchingPSD/Involutions.lean new file mode 100644 index 0000000000000000000000000000000000000000..e0fc90ee98658e87f3d7a035e4aea536ab3fd0c4 --- /dev/null +++ b/lean/OAI/Combinatorics/MatchingPSD/Involutions.lean @@ -0,0 +1,193 @@ +import OAI.Combinatorics.MatchingPSD.Model + +namespace OAI + +universe u_1 u_2 u_3 + +namespace MatchingSmoothing + +section CommutingInvolutions + +variable {ι : Type u_1} {V : Type u_2} [AddCommGroup V] [Module ℝ V] + +lemma eigen_add_commuting (A B : Module.End ℝ V) (hAB : Commute A B) + (v : V) (c : ℝ) (hv : A v = c • v) : + A (v + B v) = c • (v + B v) := by + have hc : A (B v) = B (A v) := congrArg (fun f : Module.End ℝ V => f v) hAB.eq + rw [map_add, hv, hc, hv, map_smul, smul_add] + +lemma eigen_sub_commuting (A B : Module.End ℝ V) (hAB : Commute A B) + (v : V) (c : ℝ) (hv : A v = c • v) : + A (v - B v) = c • (v - B v) := by + have hc : A (B v) = B (A v) := congrArg (fun f : Module.End ℝ V => f v) hAB.eq + rw [map_sub, hv, hc, hv, map_smul, smul_sub] + +lemma simultaneous_sign_eigenvector_on (A : ι → Module.End ℝ V) + (hcomm : ∀ i j, Commute (A i) (A j)) + (hinv : ∀ i v, A i (A i v) = v) + (W : Submodule ℝ V) (hstable : ∀ i v, v ∈ W → A i v ∈ W) + (hne : ∃ v ∈ W, v ≠ 0) (s : Finset ι) : + ∃ (χ : ι → ℝ) (v : V), v ∈ W ∧ v ≠ 0 ∧ + ∀ i ∈ s, (χ i = 1 ∨ χ i = -1) ∧ A i v = χ i • v := by + classical + induction s using Finset.induction_on with + | empty => + obtain ⟨v, hv, hv0⟩ := hne + exact ⟨fun _ => 1, v, hv, hv0, by simp⟩ + | @insert i s his ih => + obtain ⟨χ, v, hv, hv0, heig⟩ := ih + by_cases hp : v + A i v = 0 + · have hm : v - A i v ≠ 0 := by + intro hm + have htwo : (2 : ℝ) • v = 0 := by + rw [two_smul] + linear_combination (norm := abel) hp + hm + exact hv0 ((smul_eq_zero.mp htwo).resolve_left (by norm_num)) + refine ⟨Function.update χ i (-1), v - A i v, + W.sub_mem hv (hstable i v hv), hm, ?_⟩ + intro j hj + rcases Finset.mem_insert.mp hj with rfl | hj + · simp only [Function.update_self, neg_smul, one_smul] + refine ⟨by simp, ?_⟩ + rw [map_sub, hinv] + abel + · have hji : j ≠ i := by intro h; subst j; exact his hj + rw [Function.update_of_ne hji] + exact ⟨(heig j hj).1, eigen_sub_commuting (A j) (A i) (hcomm j i) + v (χ j) (heig j hj).2⟩ + · refine ⟨Function.update χ i 1, v + A i v, + W.add_mem hv (hstable i v hv), hp, ?_⟩ + intro j hj + rcases Finset.mem_insert.mp hj with rfl | hj + · simp only [Function.update_self, one_smul] + refine ⟨by simp, ?_⟩ + rw [map_add, hinv, add_comm] + · have hji : j ≠ i := by intro h; subst j; exact his hj + rw [Function.update_of_ne hji] + exact ⟨(heig j hj).1, eigen_add_commuting (A j) (A i) (hcomm j i) + v (χ j) (heig j hj).2⟩ + +lemma simultaneous_sign_eigenvector [Fintype ι] (A : ι → Module.End ℝ V) + (hcomm : ∀ i j, Commute (A i) (A j)) + (hinv : ∀ i v, A i (A i v) = v) + (W : Submodule ℝ V) (hstable : ∀ i v, v ∈ W → A i v ∈ W) + (hne : ∃ v ∈ W, v ≠ 0) : + ∃ (χ : ι → ℝ) (v : V), v ∈ W ∧ v ≠ 0 ∧ + ∀ i, (χ i = 1 ∨ χ i = -1) ∧ A i v = χ i • v := by + simpa using simultaneous_sign_eigenvector_on A hcomm hinv W hstable hne Finset.univ + +lemma simultaneous_sign_eigenvector_preserving [Fintype ι] + (A : ι → Module.End ℝ V) (hcomm : ∀ i j, Commute (A i) (A j)) + (hinv : ∀ i v, A i (A i v) = v) + (W : Submodule ℝ V) (hstable : ∀ i v, v ∈ W → A i v ∈ W) + (s : Finset ι) (χ : ι → ℝ) + (v : V) (hv : v ∈ W) (hv0 : v ≠ 0) (he : ∀ i ∈ s, A i v = χ i • v) : + ∃ (ψ : ι → ℝ) (w : V), w ∈ W ∧ w ≠ 0 ∧ + (∀ i, (ψ i = 1 ∨ ψ i = -1) ∧ A i w = ψ i • w) ∧ + ∀ i ∈ s, ψ i = χ i := by + let U : Submodule ℝ V := + { carrier := {w | w ∈ W ∧ ∀ i ∈ s, A i w = χ i • w} + zero_mem' := by simp + add_mem' := by + rintro a b ⟨ha, hea⟩ ⟨hb, heb⟩ + exact ⟨W.add_mem ha hb, fun i hi => by rw [map_add, hea i hi, heb i hi, smul_add]⟩ + smul_mem' := by + rintro c a ⟨ha, hea⟩ + exact ⟨W.smul_mem c ha, fun i hi => by rw [map_smul, hea i hi, smul_comm]⟩ } + have hU (j : ι) (w : V) (hw : w ∈ U) : A j w ∈ U := by + refine ⟨hstable j w hw.1, ?_⟩ + intro i hi + have hc := congrArg (fun f : Module.End ℝ V => f w) (hcomm i j).eq + change A i (A j w) = A j (A i w) at hc + rw [hc, hw.2 i hi, map_smul] + obtain ⟨ψ, w, hw, hw0, hew⟩ := simultaneous_sign_eigenvector A hcomm hinv U hU + ⟨v, ⟨hv, he⟩, hv0⟩ + refine ⟨ψ, w, hw.1, hw0, hew, ?_⟩ + intro i hi + exact smul_left_injective ℝ hw0 ((hew i).2.symm.trans (hw.2 i hi)) + +lemma independent_eigenprofiles {κ : Type u_3} (A : ι → Module.End ℝ V) + (hcomm : ∀ i j, Commute (A i) (A j)) (χ : κ → ι → ℝ) + (hinj : Function.Injective χ) (v : κ → V) (hv : ∀ k, v k ≠ 0) + (heig : ∀ k i, A i (v k) = χ k i • v k) : LinearIndependent ℝ v := by + have hi := Module.End.independent_iInf_maxGenEigenspace_of_forall_mapsTo A + (fun i j c => Module.End.mapsTo_maxGenEigenspace_of_comm (hcomm j i) c) + apply (hi.comp hinj).linearIndependent _ _ hv + intro k + change v k ∈ ⨅ i, (A i).maxGenEigenspace (χ k i) + rw [Submodule.mem_iInf] + intro i + exact Module.End.eigenspace_le_maxGenEigenspace + (Module.End.mem_eigenspace_iff.mpr (heig k i)) + +lemma binomial_le_finrank_of_eigenvector [Fintype ι] [DecidableEq ι] [FiniteDimensional ℝ V] + (A : ι → Module.End ℝ V) (hcomm : ∀ i j, Commute (A i) (A j)) + (P : Equiv.Perm ι → V ≃ₗ[ℝ] V) + (hconj : ∀ p i v, A (p i) (P p v) = P p (A i v)) + (s : Finset ι) (v : V) (hv : v ≠ 0) + (heig : ∀ i, A i v = (if i ∈ s then (-1 : ℝ) else 1) • v) : + (Fintype.card ι).choose s.card ≤ Module.finrank ℝ V := by + classical + let T := ↥((Finset.univ : Finset ι).powersetCard s.card) + have hp (t : T) : ∃ p : Equiv.Perm ι, s.map p.toEmbedding = t.1 := + Equiv.Perm.exists_map_finset_eq s t.1 + (Finset.mem_powersetCard.mp t.2).2.symm + choose p hp using hp + let χ (t : T) (i : ι) : ℝ := if i ∈ t.1 then -1 else 1 + have hχ : Function.Injective χ := by + intro t u h + apply Subtype.ext + ext i + have hh := congrFun h i + dsimp [χ] at hh + by_cases ht : i ∈ t.1 <;> by_cases hu : i ∈ u.1 <;> simp_all <;> norm_num at hh + have hprof (t : T) (i : ι) : A i (P (p t) v) = χ t i • P (p t) v := by + have hi : (p t).symm i ∈ s ↔ i ∈ t.1 := by + rw [← hp t] + simp + by_cases hii : i ∈ t.1 <;> + simpa [heig, χ, hi, hii] using hconj (p t) ((p t).symm i) v + have hli := independent_eigenprofiles A hcomm χ hχ + (fun t => P (p t) v) (fun t => by simpa using hv) hprof + have hc := hli.fintype_card_le_finrank + simpa only [T, Fintype.card_coe, Finset.card_powersetCard, Finset.card_univ] using hc + +lemma binomial_le_finrank_of_eigenvector_mem [Fintype ι] [DecidableEq ι] [FiniteDimensional ℝ V] + (A : ι → Module.End ℝ V) (hcomm : ∀ i j, Commute (A i) (A j)) + (P : Equiv.Perm ι → V ≃ₗ[ℝ] V) + (hconj : ∀ p i v, A (p i) (P p v) = P p (A i v)) + (W : Submodule ℝ V) (hW : ∀ p v, v ∈ W → P p v ∈ W) + (s : Finset ι) (v : V) (hvW : v ∈ W) (hv : v ≠ 0) + (heig : ∀ i, A i v = (if i ∈ s then (-1 : ℝ) else 1) • v) : + (Fintype.card ι).choose s.card ≤ Module.finrank ℝ W := by + classical + let T := ↥((Finset.univ : Finset ι).powersetCard s.card) + have hp (t : T) : ∃ p : Equiv.Perm ι, s.map p.toEmbedding = t.1 := + Equiv.Perm.exists_map_finset_eq s t.1 + (Finset.mem_powersetCard.mp t.2).2.symm + choose p hp using hp + let χ (t : T) (i : ι) : ℝ := if i ∈ t.1 then -1 else 1 + have hχ : Function.Injective χ := by + intro t u h + apply Subtype.ext + ext i + have hh := congrFun h i + dsimp [χ] at hh + by_cases ht : i ∈ t.1 <;> by_cases hu : i ∈ u.1 <;> simp_all <;> norm_num at hh + have hprof (t : T) (i : ι) : A i (P (p t) v) = χ t i • P (p t) v := by + have hi : (p t).symm i ∈ s ↔ i ∈ t.1 := by + rw [← hp t] + simp + by_cases hii : i ∈ t.1 <;> + simpa [heig, χ, hi, hii] using hconj (p t) ((p t).symm i) v + have hli := independent_eigenprofiles A hcomm χ hχ + (fun t => P (p t) v) (fun t => by simpa using hv) hprof + let vw (t : T) : W := ⟨P (p t) v, hW (p t) v hvW⟩ + have hliw : LinearIndependent ℝ vw := LinearIndependent.of_comp W.subtype hli + have hc := hliw.fintype_card_le_finrank + simpa only [T, Fintype.card_coe, Finset.card_powersetCard, Finset.card_univ] using hc + +end CommutingInvolutions +end MatchingSmoothing + +end OAI diff --git a/lean/OAI/Combinatorics/MatchingPSD/Main.lean b/lean/OAI/Combinatorics/MatchingPSD/Main.lean new file mode 100644 index 0000000000000000000000000000000000000000..8b876ebcb629b1aa3b67879c512f086446382336 --- /dev/null +++ b/lean/OAI/Combinatorics/MatchingPSD/Main.lean @@ -0,0 +1,65 @@ +import OAI.Combinatorics.MatchingPSD.NumericalBounds + +namespace OAI + +namespace PerfectMatchingPSD +open MatchingSmoothing MatchingInterpolation Matrix Filter Asymptotics +open scoped BigOperators MatrixOrder + +lemma main_nat (p : ℕ) : ∃ n₀ : ℕ, 4 ≤ n₀ ∧ + ∀ n : ℕ, n₀ ≤ n → Even n → (n:ℝ)^p < (psdRank n:ℝ) := by + classical + obtain ⟨d,H,hd,D,hD,hdecode⟩ := conditional_cell_lower_bound (10*(p+1)) + obtain ⟨Te,hTe⟩ := eventually_atTop.mp (eventually_pow_lt_half_exp (6*p)) + let T := 2+H+1024*(d+1)+Fintype.card (SampleIndex d)+⌈8*(D+1)⌉₊+Te + refine ⟨vertexSize d T+4, by omega, ?_⟩ + intro n hn hneven + obtain ⟨t,ht,hleft,hright⟩ := bracket_vertexSize d T n (by omega) + dsimp only [T] at ht + have ht2 : 2 ≤ t := by omega + have ht1 : 1 ≤ t := by omega + have hHt : H ≤ t := by omega + have hdt : 1024*(d+1) ≤ t := by omega + have hTt : Fintype.card (SampleIndex d) ≤ t := by omega + have hDt : 8*(D+1) ≤ (t:ℝ) := + (Nat.le_ceil (8*(D+1))).trans (by exact_mod_cast (show ⌈8*(D+1)⌉₊ ≤ t by omega)) + have htet : Te ≤ t := by omega + have hn6 : n ≤ t^6 := hright.le.trans (vertexSize_succ_le_pow6 d t ht1 hdt) + have hl : 1 ≤ t^4 := one_le_pow₀ ht1 + have hs : 1 ≤ blockSize d t := hl.trans (blockSize_ge d t) + have hH : H ≤ 3*blockSize d t+1 := by + have hts : t ≤ blockSize d t := (Nat.le_pow (by decide : 0 < 4)).trans (blockSize_ge d t) + omega + by_contra hnot + have hrn : (psdRank n:ℝ) ≤ (n:ℝ)^p := le_of_not_gt hnot + obtain ⟨k,⟨e⟩⟩ := exists_padded_global_equiv hneven hleft + obtain ⟨Q,B,hQ,hB,htrQ,htrB,hpair⟩ := global_factors_of_factorization + hneven (by omega : 1 ≤ n) (hasFactorization_psdRank n) e (standardPairing (H := Fin k)) + have hsel : (t:ℝ)*(psdRank n)^4*(Fintype.card (SampleIndex d))* + ((2*(3*(blockSize d t:ℝ)+1))^(2*(10*(p+1))))⁻¹ ≤ + (1/((psdRank n:ℝ)*((n:ℝ)+1)*(2*(t^4:ℕ))))^2 := by + simpa only [Nat.cast_pow] using numerical_selection p d t (psdRank n) n + (Fintype.card (SampleIndex d)) ht2 (psdRank_pos n) hn6 hTt hrn + have hsmall : 16*(t:ℝ)^2*((t:ℝ)*D+1) ≤ 2*(t^4:ℕ) := by + simpa only [Nat.cast_pow] using numerical_smallness D t ht1 hDt + have hlower : (2:ℝ)^t/2 ≤ (psdRank n:ℝ) := + hdecode (blockSize d t) t (t^4) (psdRank n) hH hs ht1 (blockSize_grid d t) hl + (psdRank_pos n) ((n:ℝ)+1) (by positivity) Q B hQ hB htrQ htrB hpair hsel hsmall + have hn6r : (n:ℝ) ≤ (t:ℝ)^6 := by exact_mod_cast hn6 + have hpow : (n:ℝ)^p ≤ (t:ℝ)^(6*p) := by + simpa only [pow_mul] using pow_le_pow_left₀ (Nat.cast_nonneg n) hn6r p + exact (not_lt_of_ge hlower) ((hrn.trans hpow).trans_lt (hTe t htet)) + +theorem main : MainClaim := by + intro C _hC + obtain ⟨n₀,hn₀,hmain⟩ := main_nat ⌈C⌉₊ + refine ⟨n₀,hn₀,?_⟩ + intro n hn heven + have hn1 : (1:ℝ) ≤ n := by exact_mod_cast (show 1 ≤ n by omega) + have hpow := Real.rpow_le_rpow_of_exponent_le hn1 (Nat.le_ceil C) + rw [Real.rpow_natCast] at hpow + exact hpow.trans_lt (hmain n hn heven) + +end PerfectMatchingPSD + +end OAI diff --git a/lean/OAI/Combinatorics/MatchingPSD/MatchingConversion.lean b/lean/OAI/Combinatorics/MatchingPSD/MatchingConversion.lean new file mode 100644 index 0000000000000000000000000000000000000000..d2a6be4ac0226339a0b5b195be1d7ec4cad86816 --- /dev/null +++ b/lean/OAI/Combinatorics/MatchingPSD/MatchingConversion.lean @@ -0,0 +1,112 @@ +import OAI.Combinatorics.MatchingPSD.FiniteFactorization + +namespace OAI + +namespace PerfectMatchingPSD +open MatchingSmoothing +attribute [local instance] Classical.propDecidable + +noncomputable def pairingEdge {n : ℕ} (M : Pairing (Fin n)) (v : Fin n) : Edge n := + if h : v < M.1 v then ⟨(v,M.1 v),h⟩ else + ⟨(M.1 v,v),lt_of_le_of_ne (le_of_not_gt h) (M.partner_ne v)⟩ + +lemma pairingEdge_partner {n : ℕ} (M : Pairing (Fin n)) (v : Fin n) : + pairingEdge M (M.1 v) = pairingEdge M v := by + by_cases h : v < M.1 v + · simp [pairingEdge, h, M.partner_partner, not_lt.mpr h.le] + · have h' : M.1 v < v := lt_of_le_of_ne (le_of_not_gt h) (M.partner_ne v) + simp [pairingEdge, h, h', M.partner_partner] + +lemma pairingEdge_incident {n : ℕ} (M : Pairing (Fin n)) (v : Fin n) : + (pairingEdge M v).1.1 = v ∨ (pairingEdge M v).1.2 = v := by + unfold pairingEdge + split_ifs <;> simp + +lemma pairingEdge_mem {n : ℕ} (M : Pairing (Fin n)) (v : Fin n) : + M.1 (pairingEdge M v).1.1 = (pairingEdge M v).1.2 := by + unfold pairingEdge + split_ifs <;> simp + +lemma eq_pairingEdge {n : ℕ} (M : Pairing (Fin n)) (e : Edge n) (hM : M.1 e.1.1 = e.1.2) + (v : Fin n) (hv : e.1.1 = v ∨ e.1.2 = v) : e = pairingEdge M v := by + have he : e = pairingEdge M e.1.1 := by + simp only [pairingEdge, hM, e.2, dite_true] + rcases hv with rfl | rfl + · exact he + · rw [← hM, pairingEdge_partner] + exact he + +noncomputable def fromPairing {n : ℕ} (M : Pairing (Fin n)) : PerfectMatching n := + ⟨Finset.univ.filter (fun e : Edge n => M.1 e.1.1 = e.1.2), by + intro v + apply Finset.card_eq_one.mpr + refine ⟨pairingEdge M v, ?_⟩ + ext e + simp only [Finset.mem_filter, Finset.mem_univ, true_and, Finset.mem_singleton] + constructor + · rintro ⟨hM,hv⟩ + exact eq_pairingEdge M e hM v hv + · rintro rfl + exact ⟨pairingEdge_mem M v, pairingEdge_incident M v⟩⟩ + +@[simp] lemma mem_fromPairing {n : ℕ} (M : Pairing (Fin n)) (e : Edge n) : + e ∈ (fromPairing M).1 ↔ M.1 e.1.1 = e.1.2 := by + simp [fromPairing] + +lemma pairingEdge_cross {n : ℕ} (M : Pairing (Fin n)) (U : Finset (Fin n)) + (v : Fin n) (hv : v ∈ U) (hp : M.1 v ∉ U) : Crosses U (pairingEdge M v) := by + unfold pairingEdge + split_ifs <;> simp [Crosses, hv, hp] + +lemma cross_edge_inside {n : ℕ} (M : Pairing (Fin n)) (U : Finset (Fin n)) + (e : Edge n) (he : e ∈ (fromPairing M).1) (hc : Crosses U e) : + ∃ v : Fin n, (v ∈ U ∧ M.1 v ∉ U) ∧ pairingEdge M v = e := by + have hm := (mem_fromPairing M e).mp he + rcases hc with hc | hc + · refine ⟨e.1.1,⟨hc.1,?_⟩,(eq_pairingEdge M e hm _ (Or.inl rfl)).symm⟩ + simpa only [hm] using hc.2 + · refine ⟨e.1.2,⟨hc.2,?_⟩,(eq_pairingEdge M e hm _ (Or.inr rfl)).symm⟩ + simpa only [← hm, M.partner_partner] using hc.1 + +lemma pairingEdge_inside_injective {n : ℕ} (M : Pairing (Fin n)) (U : Finset (Fin n)) : + Function.Injective (fun v : {v : Fin n // v ∈ U ∧ M.1 v ∉ U} => pairingEdge M v.1) := by + intro v w h + apply Subtype.ext + have hv := pairingEdge_incident M v.1 + have hw := pairingEdge_incident M w.1 + change pairingEdge M v.1 = pairingEdge M w.1 at h + rw [← h] at hw + rcases hv with hv | hv <;> rcases hw with hw | hw + · exact hv.symm.trans hw + · have hm := pairingEdge_mem M v.1 + rw [hv,hw] at hm + exact False.elim (v.2.2 (hm ▸ w.2.1)) + · have hm := pairingEdge_mem M v.1 + rw [hw,hv] at hm + exact False.elim (w.2.2 (hm ▸ v.2.1)) + · exact hv.symm.trans hw + +lemma crossingCount_fromPairing {n : ℕ} (M : Pairing (Fin n)) (U : Finset (Fin n)) : + crossingCount U (fromPairing M) = Fintype.card {v : Fin n // v ∈ U ∧ M.1 v ∉ U} := by + classical + rw [crossingCount, ← Fintype.card_coe] + symm + apply Fintype.card_of_bijective (f := fun v : {v : Fin n // v ∈ U ∧ M.1 v ∉ U} => + (⟨pairingEdge M v.1,by simp [pairingEdge_mem, pairingEdge_cross M U v.1 v.2.1 v.2.2]⟩ : + {e // e ∈ (fromPairing M).1.filter (Crosses U)})) + constructor + · intro v w h + exact pairingEdge_inside_injective M U (congrArg Subtype.val h) + · intro e + obtain ⟨v,hv,he⟩ := cross_edge_inside M U e.1 (Finset.mem_filter.mp e.2).1 (Finset.mem_filter.mp e.2).2 + exact ⟨⟨v,hv⟩,Subtype.ext he⟩ + +lemma crossingCount_tableCoordinate {n : ℕ} (M : Pairing (Fin n)) (U : Finset (Fin n)) : + (crossingCount U (fromPairing M) : ℝ) = + tableCoordinate (fun v => decide (v ∈ U)) (true,false) M := by + rw [crossingCount_fromPairing] + simp [tableCoordinate, Fintype.card_subtype, Finset.sum_boole] + +end PerfectMatchingPSD + +end OAI diff --git a/lean/OAI/Combinatorics/MatchingPSD/MatchingFibers.lean b/lean/OAI/Combinatorics/MatchingPSD/MatchingFibers.lean new file mode 100644 index 0000000000000000000000000000000000000000..af6f010dadfc4698400ac6ecf7f6e2486ea6c819 --- /dev/null +++ b/lean/OAI/Combinatorics/MatchingPSD/MatchingFibers.lean @@ -0,0 +1,187 @@ +import OAI.Combinatorics.MatchingPSD.SimultaneousSmoothing + +namespace OAI + +universe u_1 u_2 u_3 u_4 u_5 u_6 u_7 u_8 u_9 u_10 + +namespace MatchingSmoothing +namespace Pairing +variable {A : Type u_1} {B : Type u_2} {C : Type u_3} + +def transport (e : A ≃ B) (M : Pairing A) : Pairing B := + ⟨e.symm.trans (M.1.trans e), by + constructor + · intro b + simp + · intro b hb + apply M.partner_ne (e.symm b) + simpa using congrArg e.symm hb⟩ + +@[simp] lemma transport_apply (e : A ≃ B) (M : Pairing A) (b : B) : + (transport e M).1 b = e (M.1 (e.symm b)) := rfl + +@[simp] lemma transport_refl (M : Pairing A) : transport (Equiv.refl A) M = M := by + ext a + rfl + +@[simp] lemma transport_trans (e : A ≃ B) (f : B ≃ C) (M : Pairing A) : + transport (e.trans f) M = transport f (transport e M) := by + ext c + rfl + +@[simp] lemma transport_symm (e : A ≃ B) (M : Pairing A) : + transport e.symm (transport e M) = M := by + ext a + simp + +def transportEquiv (e : A ≃ B) : Pairing A ≃ Pairing B where + toFun := transport e + invFun := transport e.symm + left_inv := transport_symm e + right_inv := transport_symm e.symm + +lemma transport_perm (p : Equiv.Perm A) (M : Pairing A) : transport p M = relabel p M := rfl + +def sum (M : Pairing A) (N : Pairing B) : Pairing (A ⊕ B) := + ⟨Equiv.sumCongr M.1 N.1, by + constructor + · intro v + cases v <;> simp + · intro v hv + cases v with + | inl a => exact M.partner_ne a (Sum.inl.inj hv) + | inr b => exact N.partner_ne b (Sum.inr.inj hv)⟩ + +@[simp] lemma sum_inl (M : Pairing A) (N : Pairing B) (a : A) : + (sum M N).1 (.inl a) = .inl (M.1 a) := rfl +@[simp] lemma sum_inr (M : Pairing A) (N : Pairing B) (b : B) : + (sum M N).1 (.inr b) = .inr (N.1 b) := rfl + +lemma sum_relabel_left (p : Equiv.Perm A) (M : Pairing A) (N : Pairing B) : + sum (relabel p M) N = relabel (Equiv.sumCongr p (Equiv.refl B)) (sum M N) := by + ext v + cases v <;> rfl + +lemma transport_relabel (e : A ≃ B) (p : Equiv.Perm A) (M : Pairing A) : + transport e (relabel p M) = relabel (e.symm.trans (p.trans e)) (transport e M) := by + ext b + simp only [transport_apply, relabel_apply, Equiv.Perm.inv_def, + Equiv.symm_trans_apply, Equiv.trans_apply, Equiv.symm_symm, + Equiv.symm_apply_apply] + +def cellwise {I : Type u_4} (M : I → Pairing A) : Pairing (I × A) := + ⟨{ toFun := fun v => (v.1,(M v.1).1 v.2) + invFun := fun v => (v.1,(M v.1).1 v.2) + left_inv := by intro v; simp + right_inv := by intro v; simp }, by + constructor + · intro v; simp + · intro v hv + exact (M v.1).partner_ne v.2 (congrArg Prod.snd hv)⟩ + +@[simp] lemma cellwise_apply {I : Type u_5} (M : I → Pairing A) (i : I) (a : A) : + (cellwise M).1 (i,a) = (i,(M i).1 a) := rfl + +end Pairing + +section Coordinates +variable {A : Type u_6} {B : Type u_7} {C : Type u_8} [Fintype A] [Fintype B] +attribute [local instance] Classical.propDecidable + +lemma tableCoordinate_transport (e : A ≃ B) (z : B → C) (c : C × C) (M : Pairing A) : + tableCoordinate z c (Pairing.transport e M) = tableCoordinate (z ∘ e) c M := by + unfold tableCoordinate + rw [← e.sum_comp (fun b => if z b = c.1 ∧ z ((Pairing.transport e M).1 b) = c.2 then (1:ℝ) else 0)] + simp only [Pairing.transport_apply, Equiv.symm_apply_apply, Function.comp_apply] + +lemma tableCoordinate_sum (z : A → C) (w : B → C) (c : C × C) + (M : Pairing A) (N : Pairing B) : + tableCoordinate (Sum.elim z w) c (Pairing.sum M N) = + tableCoordinate z c M + tableCoordinate w c N := by + simp only [tableCoordinate, Fintype.sum_sum_type, Pairing.sum_inl, Pairing.sum_inr, + Sum.elim_inl, Sum.elim_inr] + rfl + +lemma tableCoordinate_nonneg (z : A → C) (c : C × C) (M : Pairing A) : + 0 ≤ tableCoordinate z c M := by + unfold tableCoordinate + exact Finset.sum_nonneg (fun _ _ => by split_ifs <;> norm_num) + +lemma tableCoordinate_eq_zero_iff (z : A → C) (c : C × C) (M : Pairing A) : + tableCoordinate z c M = 0 ↔ ∀ a, ¬ (z a = c.1 ∧ z (M.1 a) = c.2) := by + unfold tableCoordinate + rw [Finset.sum_eq_zero_iff_of_nonneg (fun _ _ => by split_ifs <;> norm_num)] + simp + +lemma tableCoordinate_constant (z : C) (c : C × C) (M : Pairing A) : + tableCoordinate (fun _ : A => z) c M = + if z=c.1 ∧ z=c.2 then (Fintype.card A : ℝ) else 0 := by + simp only [tableCoordinate] + split_ifs <;> simp_all + +end Coordinates +end MatchingSmoothing + +namespace MatchingSmoothing.Pairing +variable {A : Type u_9} {B : Type u_10} + +lemma sum_injective : Function.Injective (fun p : Pairing A × Pairing B => sum p.1 p.2) := by + intro p q hpq + apply Prod.ext + · ext a + exact Sum.inl.inj (congrArg (fun M : Pairing (A ⊕ B) => M.1 (.inl a)) hpq) + · ext b + exact Sum.inr.inj (congrArg (fun M : Pairing (A ⊕ B) => M.1 (.inr b)) hpq) + +lemma exists_sum (M : Pairing (A ⊕ B)) + (hl : ∀ a : A, ∃ a' : A, M.1 (.inl a) = .inl a') : + ∃ L : Pairing A, ∃ R : Pairing B, M = sum L R := by + classical + have hr (b : B) : ∃ b' : B, M.1 (.inr b) = .inr b' := by + cases he : M.1 (.inr b) with + | inl a => + obtain ⟨a',ha⟩ := hl a + have hh := M.partner_partner (.inr b) + rw [he, ha] at hh + cases hh + | inr b' => exact ⟨b',rfl⟩ + choose f hf using hl + choose g hg using hr + have hff : Function.Involutive f := by + intro a + apply Sum.inl_injective (β := B) + rw [← hf, ← hf, M.partner_partner] + have hgg : Function.Involutive g := by + intro b + apply Sum.inr_injective (α := A) + rw [← hg, ← hg, M.partner_partner] + let L : Pairing A := ⟨⟨f,f,hff,hff⟩,hff,fun a ha => + M.partner_ne (.inl a) ((hf a).trans (congrArg Sum.inl ha))⟩ + let R : Pairing B := ⟨⟨g,g,hgg,hgg⟩,hgg,fun b hb => + M.partner_ne (.inr b) ((hg b).trans (congrArg Sum.inr hb))⟩ + refine ⟨L,R,?_⟩ + ext v + cases v with + | inl a => exact hf a + | inr b => exact hg b + +noncomputable def sumFiberEquiv (P : Pairing (A ⊕ B) → Prop) (Q : Pairing A → Prop) + (hs : ∀ L R, P (sum L R) ↔ Q L) + (hc : ∀ M, P M → ∀ a : A, ∃ a' : A, M.1 (.inl a) = .inl a') : + {L : Pairing A // Q L} × Pairing B ≃ {M : Pairing (A ⊕ B) // P M} := + Equiv.ofBijective (fun p => ⟨sum p.1.1 p.2, (hs _ _).mpr p.1.2⟩) (by + constructor + · intro p q he + have hh : (p.1.1,p.2) = (q.1.1,q.2) := + sum_injective (congrArg Subtype.val he) + apply Prod.ext + · exact Subtype.ext (congrArg (fun x : Pairing A × Pairing B => x.1) hh) + · exact congrArg (fun x : Pairing A × Pairing B => x.2) hh + · intro M + obtain ⟨L,R,hM⟩ := exists_sum M.1 (hc M.1 M.2) + refine ⟨(⟨L,(hs L R).mp (hM ▸ M.2)⟩,R),?_⟩ + exact Subtype.ext hM.symm) + +end MatchingSmoothing.Pairing + +end OAI diff --git a/lean/OAI/Combinatorics/MatchingPSD/MatchingIncidence.lean b/lean/OAI/Combinatorics/MatchingPSD/MatchingIncidence.lean new file mode 100644 index 0000000000000000000000000000000000000000..6e4161edb9d99cb958749f066a2fb760e1636d34 --- /dev/null +++ b/lean/OAI/Combinatorics/MatchingPSD/MatchingIncidence.lean @@ -0,0 +1,149 @@ +import OAI.Combinatorics.MatchingPSD.SpectralMultiplicity + +namespace OAI + +universe u_1 u_2 u_3 + +namespace MatchingSmoothing + +namespace Pairing +variable {V : Type u_1} [Fintype V] [DecidableEq V] + +noncomputable instance : Fintype (Pairing V) := Fintype.ofFinite _ + +instance relabelMulAction : MulAction (Equiv.Perm V) (Pairing V) where + smul := relabel + one_smul := relabel_one + mul_smul := relabel_mul + +omit [Fintype V] [DecidableEq V] in +lemma smul_eq_relabel (p : Equiv.Perm V) (M : Pairing V) : p • M = relabel p M := rfl + +noncomputable def table (M : Pairing V) (f : V → Fin 3) (t : Fin 6) : ℕ := + histogram (fun v => threeEdgeType (f v, f (M.1 v))) t / 2 + +omit [DecidableEq V] in +lemma table_relabel (p : Equiv.Perm V) (M : Pairing V) (f : V → Fin 3) : + (relabel p M).table f = M.table (f ∘ p) := by + funext t + unfold table + congr 1 + have he : (fun v => threeEdgeType (f v, f ((relabel p M).1 v))) ∘ p = + (fun v => threeEdgeType ((f ∘ p) v, (f ∘ p) (M.1 v))) := by + funext v + simp only [Function.comp_apply, relabel_apply] + rw [Equiv.Perm.inv_def, p.symm_apply_apply] + rw [← he, histogram_comp_perm] + +end Pairing + +section StandardTable +variable {H : Type u_2} [Fintype H] [DecidableEq H] + +def standardPairing : Pairing (H × Bool) := + ⟨Equiv.prodCongr (Equiv.refl H) Equiv.boolNot, + by rintro ⟨i,b⟩; cases b <;> rfl, + by rintro ⟨i,b⟩ h; have he := congrArg Prod.snd h; cases b <;> contradiction⟩ + +omit [DecidableEq H] in +lemma standardPairing_table (f : H × Bool → Fin 3) : + (standardPairing (H := H)).table f = threeTable f := by + funext t + have he : histogram (fun v => threeEdgeType (f v, f ((standardPairing (H := H)).1 v))) t = + 2 * threeTable f t := by + have hr : (histogram (fun v => threeEdgeType (f v, + f ((standardPairing (H := H)).1 v))) t : ℝ) = 2 * threeTable f t := by + simp only [histogram_cast_sum, Fintype.sum_prod_type, Fintype.sum_bool, + standardPairing, Equiv.prodCongr_apply] + change (∑ i, ((if threeEdgeType (f (i,true),f (i,false)) = t then (1 : ℝ) else 0) + + (if threeEdgeType (f (i,false),f (i,true)) = t then 1 else 0))) = _ + simp_rw [threeEdgeType_symm (f (_,true)) (f (_,false))] + rw [Finset.sum_add_distrib] + change (∑ i, if threeEdgeType (f (i,false),f (i,true)) = t then (1 : ℝ) else 0) + + (∑ i, if threeEdgeType (f (i,false),f (i,true)) = t then (1 : ℝ) else 0) = _ + rw [show (threeTable f t : ℝ) = + ∑ i, if threeEdgeType (f (i,false),f (i,true)) = t then 1 else 0 from + histogram_cast_sum (threeEdgeType ∘ pairColorEquiv f) t] + ring + exact_mod_cast hr + change _ / 2 = _ + rw [he, Nat.mul_div_right _ (by decide : 0 < 2)] + +end StandardTable + +section MatchingIncidence +variable {H : Type u_3} [Fintype H] [DecidableEq H] + +noncomputable def tableRelation (f₀ : H × Bool → Fin 3) : + Pairing (H × Bool) → Colorings (H × Bool) (Fin 3) (histogram f₀) → Prop := + fun M z => M.table z.1 = threeTable f₀ + +noncomputable def coloringPerm (s : Fin 3 → ℕ) (p : Equiv.Perm (H × Bool)) : + Equiv.Perm (Colorings (H × Bool) (Fin 3) s) where + toFun z := ⟨z.1 ∘ p, (histogram_comp_perm z.1 p).trans z.2⟩ + invFun z := ⟨z.1 ∘ p.symm, (histogram_comp_perm z.1 p.symm).trans z.2⟩ + left_inv z := by apply Subtype.ext; funext v; simp + right_inv z := by apply Subtype.ext; funext v; simp + +omit [DecidableEq H] in +lemma commonIncidence_table_relabel (f₀ : H × Bool → Fin 3) + (p : Equiv.Perm (H × Bool)) (M N : Pairing (H × Bool)) : + commonIncidence (tableRelation f₀) (Pairing.relabel p M) (Pairing.relabel p N) = + commonIncidence (tableRelation f₀) M N := by + classical + unfold commonIncidence + congr 1 + apply Fintype.card_congr + apply (coloringPerm (histogram f₀) p).subtypeEquiv + intro z + change ((Pairing.relabel p M).table z.1 = _ ∧ (Pairing.relabel p N).table z.1 = _) ↔ + (M.table (z.1 ∘ p) = _ ∧ N.table (z.1 ∘ p) = _) + simp only [Pairing.table_relabel] + +lemma commonIncidence_standard (f₀ : H × Bool → Fin 3) (hH : 0 < Fintype.card H) + (p : Equiv.Perm (H × Bool)) : + commonIncidence (tableRelation f₀) standardPairing (Pairing.relabel p standardPairing) = + (Fintype.card {f : H × Bool → Fin 3 // + threeTable f = threeTable f₀ ∧ threeTable (f ∘ p) = threeTable f₀} : ℝ) := by + classical + unfold commonIncidence + congr 1 + apply Fintype.card_congr + refine { toFun := fun z => ⟨z.1.1, ?_⟩ + invFun := fun f => ⟨⟨f.1, threeTable_histogram_eq hH f.2.1⟩, ?_⟩ + left_inv := fun _ => rfl + right_inv := fun _ => rfl } + · simpa only [tableRelation, Pairing.table_relabel, standardPairing_table] using z.2 + · simpa only [tableRelation, Pairing.table_relabel, standardPairing_table] using f.2 + +lemma matching_table_trace_square (f₀ : H × Bool → Fin 3) (hH : 0 < Fintype.card H) + (hf₀ : ∀ i, 0 < histogram f₀ i) : + let D : ℝ := Fintype.card {f : H × Bool → Fin 3 // threeTable f = threeTable f₀} + Matrix.trace (incidenceOperator (tableRelation f₀) D * + incidenceOperator (tableRelation f₀) D) ≤ (Fintype.card H + 1 : ℝ) ^ 33 := by + classical + dsimp only + let D : ℝ := Fintype.card {f : H × Bool → Fin 3 // threeTable f = threeTable f₀} + change Matrix.trace (incidenceOperator (tableRelation f₀) D * + incidenceOperator (tableRelation f₀) D) ≤ _ + have he := trace_normalized_invariant_kernel_sq (G := Equiv.Perm (H × Bool)) + (standardPairing (H := H)) (fun M => Pairing.exists_relabel _ M) + (incidenceKernel (tableRelation f₀) D) + (incidenceKernel_symm (tableRelation f₀) D) + (fun p M N => by + change (Fintype.card _ : ℝ) / D ^ 2 * commonIncidence _ (Pairing.relabel p M) + (Pairing.relabel p N) = (Fintype.card _ : ℝ) / D ^ 2 * commonIncidence _ M N + rw [commonIncidence_table_relabel]) + change Matrix.trace (incidenceOperator (tableRelation f₀) D * + incidenceOperator (tableRelation f₀) D) = _ at he + rw [he] + have hp : (0 : ℝ) < Fintype.card (Equiv.Perm (H × Bool)) := Nat.cast_pos.mpr Fintype.card_pos + apply (div_le_iff₀ hp).mpr + simp only [incidenceKernel, Pairing.smul_eq_relabel, + commonIncidence_standard f₀ hH] + exact (three_table_kernel_moment f₀ hH hf₀).trans_eq (mul_comm _ _) + +end MatchingIncidence +end MatchingSmoothing + +end OAI diff --git a/lean/OAI/Combinatorics/MatchingPSD/MatrixAverages.lean b/lean/OAI/Combinatorics/MatchingPSD/MatrixAverages.lean new file mode 100644 index 0000000000000000000000000000000000000000..26ff774f38425b2c9b09855c68dc09efe1055f27 --- /dev/null +++ b/lean/OAI/Combinatorics/MatchingPSD/MatrixAverages.lean @@ -0,0 +1,118 @@ +import OAI.Combinatorics.MatchingPSD.MatrixBounds + +namespace OAI + +universe u_1 u_2 u_3 u_4 u_5 u_6 + +namespace PerfectMatchingPSD +open Matrix MatchingSmoothing +open scoped BigOperators MatrixOrder +attribute [local instance] Classical.propDecidable +variable {R : Type u_1} {X : Type u_2} [Fintype R] [DecidableEq R] [Fintype X] + +omit [Fintype R] [DecidableEq R] in +lemma matrix_expect_eq (f : X → Matrix R R ℝ) : + (𝔼 x, f x) = ((Fintype.card X : ℝ)⁻¹) • (∑ x, f x) := by + ext i j + simp [Finset.expect, NNRat.smul_def] + +omit [Fintype R] [DecidableEq R] in +lemma matrix_expect_apply (f : X → Matrix R R ℝ) (u v : R) : + (𝔼 x, f x) u v = 𝔼 x, f x u v := by + rw [matrix_expect_eq, Fintype.expect_eq_sum_div_card] + simp only [Matrix.smul_apply, Matrix.sum_apply, smul_eq_mul, div_eq_inv_mul] + +omit [Fintype R] [DecidableEq R] in +lemma matrix_expect_psd (f : X → Matrix R R ℝ) (hf : ∀ x, (f x).PosSemidef) : + (𝔼 x, f x).PosSemidef := by + rw [matrix_expect_eq] + exact (matrix_sum_psd Finset.univ f (fun x _ => hf x)).smul + (inv_nonneg.mpr (Nat.cast_nonneg _)) + +lemma trace_mul_expect (Q : Matrix R R ℝ) (f : X → Matrix R R ℝ) : + (Q * (𝔼 x, f x)).trace = 𝔼 x, (Q*f x).trace := by + rw [matrix_expect_eq, mul_smul_comm, Matrix.trace_smul, + Finset.mul_sum, Matrix.trace_sum, Fintype.expect_eq_sum_div_card] + change (Fintype.card X : ℝ)⁻¹ * _ = _ / Fintype.card X + rw [div_eq_inv_mul] + +lemma expect_abs_bound (f : X → ℝ) {b : ℝ} (hb : 0 ≤ b) (hf : ∀ x, |f x| ≤ b) : + |𝔼 x, f x| ≤ b := by + by_cases hX : Nonempty X + · let := hX + have h0 (x : X) : -b ≤ f x := (abs_le.mp (hf x)).1 + have h1 (x : X) : f x ≤ b := (abs_le.mp (hf x)).2 + apply abs_le.mpr + constructor + · simpa using Finset.expect_le_expect (s := Finset.univ) (fun x _ => h0 x) + · simpa using Finset.expect_le_expect (s := Finset.univ) (fun x _ => h1 x) + · have : IsEmpty X := not_nonempty_iff.mp hX + simpa using hb + +section CellMatrices +variable {A : Type u_3} {B : Type u_4} {C : Type u_5} {I : Type u_6} [Fintype A] [Fintype B] [Fintype C] [Fintype I] [DecidableEq I] + +noncomputable def extensionMatrix (i : I) + (Bf : Pairing ((A ⊕ B) ⊕ (I × C)) → Matrix R R ℝ) + (M : Pairing ((A ⊕ B) ⊕ C)) : Matrix R R ℝ := + 𝔼 N : {j : I // j ≠ i} → Pairing C, Bf (extendLocal i M N) + +noncomputable def cellMatrix (i : I) + (Bf : Pairing ((A ⊕ B) ⊕ (I × C)) → Matrix R R ℝ) + (x : Fin 3 → ℝ) : Matrix R R ℝ := + 𝔼 M : {M : Pairing ((A ⊕ B) ⊕ C) // crossVector threeColor M = x}, extensionMatrix i Bf M.1 + +omit [Fintype R] [DecidableEq R] in +lemma cellMatrix_apply (i : I) (Bf : Pairing ((A ⊕ B) ⊕ (I × C)) → Matrix R R ℝ) + (x : Fin 3 → ℝ) (u v : R) : + cellMatrix i Bf x u v = cellAverage i (fun M => Bf M u v) x := by + rw [cellAverage, predicateAverage_eq_expect] + simp only [cellMatrix, extensionMatrix, extensionAverage, matrix_expect_apply] + apply Finset.expect_congr (by ext; simp) + intro M _ + rfl + +omit [Fintype R] [DecidableEq R] in +lemma cellMatrix_psd (i : I) (Bf : Pairing ((A ⊕ B) ⊕ (I × C)) → Matrix R R ℝ) + (hB : ∀ M, (Bf M).PosSemidef) (x : Fin 3 → ℝ) : + (cellMatrix i Bf x).PosSemidef := by + apply matrix_expect_psd + intro M + apply matrix_expect_psd + intro N + exact hB _ + +omit [Fintype R] [DecidableEq R] in +lemma cellMatrix_star (i j : I) (Bf : Pairing ((A ⊕ B) ⊕ (I × C)) → Matrix R R ℝ) + (x : ℝ) : cellMatrix i Bf ![x,0,0] = cellMatrix j Bf ![x,0,0] := by + ext u v + simp only [cellMatrix_apply, cellAverage_star] + +lemma trace_cellMatrix (i : I) (Bf : Pairing ((A ⊕ B) ⊕ (I × C)) → Matrix R R ℝ) + (Q : Matrix R R ℝ) (x : Fin 3 → ℝ) : + (Q*cellMatrix i Bf x).trace = cellAverage i (fun M => (Q*Bf M).trace) x := by + rw [cellAverage, predicateAverage_eq_expect, cellMatrix, trace_mul_expect] + apply Finset.expect_congr (by ext; simp) + intro M _ + exact trace_mul_expect Q _ + +omit [Fintype A] [Fintype B] in +lemma extensionAverage_sq_bound (i : I) + (Bf : Pairing ((A ⊕ B) ⊕ (I × C)) → Matrix R R ℝ) + (hB : ∀ M, (Bf M).PosSemidef) {b : ℝ} (hb : 0 ≤ b) + (htr : ∀ M, (Bf M).trace ≤ b) (u v : R) (M : Pairing ((A ⊕ B) ⊕ C)) : + (extensionAverage i (fun N => Bf N u v) M)^2 ≤ b^2 := by + have he := expect_abs_bound (fun N => Bf (extendLocal i M N) u v) hb + (fun N => (posSemidef_entry_abs_le_trace (hB _) u v).trans (htr _)) + have hex : extensionAverage i (fun N => Bf N u v) M = + 𝔼 N : {j : I // j ≠ i} → Pairing C, Bf (extendLocal i M N) u v := by + apply Finset.expect_congr (by ext; simp) + intro N _ + rfl + rw [hex] + simpa only [sq_abs] using (sq_le_sq₀ (abs_nonneg _) hb).mpr he + +end CellMatrices +end PerfectMatchingPSD + +end OAI diff --git a/lean/OAI/Combinatorics/MatchingPSD/MatrixBounds.lean b/lean/OAI/Combinatorics/MatchingPSD/MatrixBounds.lean new file mode 100644 index 0000000000000000000000000000000000000000..f29cdf19ae4a84f6d2230e7854067dcc520a7758 --- /dev/null +++ b/lean/OAI/Combinatorics/MatchingPSD/MatrixBounds.lean @@ -0,0 +1,88 @@ +import OAI.Combinatorics.MatchingPSD.BitTests + +namespace OAI + +universe u_1 u_2 + +namespace PerfectMatchingPSD +open Matrix +open scoped MatrixOrder +variable {R : Type u_1} [Fintype R] [DecidableEq R] + +lemma entry_product_bound {a x y b : ℝ} (hb : 0 ≤ b) (ha : |a| ≤ b) : + x*a*y ≤ b*(x^2+y^2)/2 := by + have hxy : 2 * |x| * |y| ≤ x^2+y^2 := by + nlinarith [sq_nonneg (|x|-|y|), sq_abs x, sq_abs y] + have he : x*a*y ≤ b*(|x| * |y|) := by + calc + _ ≤ |x*a*y| := le_abs_self _ + _ = |a| *(|x| * |y|) := by rw [abs_mul, abs_mul]; ring + _ ≤ _ := mul_le_mul_of_nonneg_right ha (mul_nonneg (abs_nonneg _) (abs_nonneg _)) + nlinarith [mul_le_mul_of_nonneg_left hxy hb] + +lemma le_card_entry_bound {E : Matrix R R ℝ} (hE : E.IsHermitian) + {b : ℝ} (hb : 0 ≤ b) (hbound : ∀ i j, |E i j| ≤ b) : + E ≤ ((Fintype.card R : ℝ)*b) • (1 : Matrix R R ℝ) := by + apply sub_nonneg.mp + apply Matrix.PosSemidef.nonneg + apply Matrix.PosSemidef.of_dotProduct_mulVec_nonneg + · exact (isHermitian_one.smul (.of_nonneg (mul_nonneg (Nat.cast_nonneg _) hb))).sub hE + · intro x + have hsum : (∑ i, ∑ j, x i*E i j*x j) ≤ + (Fintype.card R : ℝ)*b*(∑ i, (x i)^2) := by + calc + _ ≤ ∑ i, ∑ j, (b/2*(x i)^2 + b/2*(x j)^2) := by + apply Finset.sum_le_sum + intro i _ + apply Finset.sum_le_sum + intro j _ + have he := entry_product_bound (x := x i) (y := x j) hb (hbound i j) + linarith + _ = _ := by + simp only [Finset.sum_add_distrib, Finset.sum_const, Finset.card_univ, + nsmul_eq_mul, ← Finset.mul_sum] + ring + simp only [Matrix.sub_mulVec, Matrix.smul_mulVec, Matrix.one_mulVec, + dotProduct_sub, dotProduct_smul, star_trivial] + rw [sub_nonneg] + simpa only [dotProduct, Matrix.mulVec, Finset.mul_sum, pow_two, smul_eq_mul, mul_assoc] using hsum + +lemma posSemidef_entry_abs_le_trace {A : Matrix R R ℝ} (hA : A.PosSemidef) (i j : R) : + |A i j| ≤ A.trace := by + have hi : 0 ≤ A i i := by + have he := hA.dotProduct_mulVec_nonneg (Pi.single i 1) + simpa using he + have hj : 0 ≤ A j j := by + have he := hA.dotProduct_mulVec_nonneg (Pi.single j 1) + simpa using he + have hsym : A j i = A i j := by + simpa using congrArg (fun M : Matrix R R ℝ => M i j) hA.isHermitian.eq + have hplus : -(A i i + A j j)/2 ≤ A i j := by + have he := hA.dotProduct_mulVec_nonneg (Pi.single i 1 + Pi.single j 1) + simp only [star_trivial, Matrix.mulVec_add, dotProduct_add, + add_dotProduct, Matrix.mulVec_single_one, single_dotProduct, one_mul, Matrix.col_apply] at he + rw [hsym] at he + linarith + have hminus : A i j ≤ (A i i + A j j)/2 := by + have he := hA.dotProduct_mulVec_nonneg (Pi.single i 1 - Pi.single j 1) + simp only [star_trivial, Matrix.mulVec_sub, dotProduct_sub, + sub_dotProduct, Matrix.mulVec_single_one, single_dotProduct, one_mul, Matrix.col_apply] at he + rw [hsym] at he + linarith + have hdiag (k : R) : A k k ≤ A.trace := by + change A k k ≤ ∑ l, A l l + apply Finset.single_le_sum (f := fun l => A l l) + · intro l _ + have he := hA.dotProduct_mulVec_nonneg (Pi.single l 1) + simpa using he + · exact Finset.mem_univ k + exact (abs_le.mpr ⟨by linarith, hminus⟩).trans (by linarith [hdiag i, hdiag j]) + +omit [Fintype R] [DecidableEq R] in +lemma matrix_sum_psd {X : Type u_2} (s : Finset X) (f : X → Matrix R R ℝ) + (hf : ∀ x ∈ s, (f x).PosSemidef) : (∑ x ∈ s, f x).PosSemidef := + (Finset.sum_nonneg (fun x hx => (hf x hx).nonneg)).posSemidef + +end PerfectMatchingPSD + +end OAI diff --git a/lean/OAI/Combinatorics/MatchingPSD/MatrixInterpolation.lean b/lean/OAI/Combinatorics/MatchingPSD/MatrixInterpolation.lean new file mode 100644 index 0000000000000000000000000000000000000000..4536a9f9a8f1ea818e573080f8541225270e0e2e --- /dev/null +++ b/lean/OAI/Combinatorics/MatchingPSD/MatrixInterpolation.lean @@ -0,0 +1,130 @@ +import OAI.Combinatorics.MatchingPSD.PolynomialInterpolation + +namespace OAI + +universe u_1 u_2 + +namespace MatchingInterpolation +open MatchingSmoothing Matrix PerfectMatchingPSD +open scoped BigOperators MatrixOrder +attribute [local instance] Classical.propDecidable + +noncomputable def specialPoint : Fin 5 → Point := + ![origin, origin+dirP, origin+dirStar, origin+dirA, origin+dirB] +def specialCoeff : Fin 5 → ℝ := ![1,-2,-1,1,1] +noncomputable def scaledNode {d : ℕ} (L : ℝ) (g : GridIndex d) : Point := + fun a => origin a+L*(g a:ℝ) +noncomputable def weightMass (d : ℕ) (L : ℝ) : ℝ := ∑ g, |weight d L g| + +lemma weightMass_nonneg (d : ℕ) (L : ℝ) : 0 ≤ weightMass d L := + Finset.sum_nonneg (fun _ _ => abs_nonneg _) + +lemma sum_abs_specialCoeff : (∑ j, |specialCoeff j|) = 6 := by + norm_num [specialCoeff, Fin.sum_univ_succ] + +lemma five_interpolation {d : ℕ} (P : Point → ℝ) (hP : P ∈ lowDegree coord d) + {L : ℝ} (hL : L ≠ 0) : + (∑ j, specialCoeff j * P (specialPoint j)) = ∑ g, weight d L g * P (scaledNode L g) := by + have h := weighted_interpolation d P hP L hL + simp only [specialCoeff, specialPoint, Fin.sum_univ_succ, Matrix.cons_val_zero, + Matrix.cons_val_succ, one_mul, neg_mul, Fin.sum_univ_zero, add_zero] at * + change _ = ∑ g, weight d L g * P (fun a => origin a+L*(g a:ℝ)) + linarith + +lemma finite_weighted_error {X : Type u_1} [Fintype X] + (c e : X → ℝ) {η : ℝ} (he : ∀ x, |e x| ≤ η) : + |∑ x, c x*e x| ≤ (∑ x, |c x|)*η := by + calc + _ ≤ ∑ x, |c x*e x| := Finset.abs_sum_le_sum_abs _ _ + _ ≤ ∑ x, |c x| *η := by + apply Finset.sum_le_sum + intro x _ + rw [abs_mul] + exact mul_le_mul_of_nonneg_left (he x) (abs_nonneg _) + _ = _ := (Finset.sum_mul _ _ _).symm + +lemma interpolation_error {d : ℕ} (F P : Point → ℝ) + (hP : P ∈ lowDegree coord d) {L η : ℝ} (hL : L ≠ 0) + (hs : ∀ j, |F (specialPoint j)-P (specialPoint j)| ≤ η) + (hg : ∀ g : GridIndex d, |F (scaledNode L g)-P (scaledNode L g)| ≤ η) : + |(∑ j, specialCoeff j*F (specialPoint j)) - + ∑ g, weight d L g*F (scaledNode L g)| ≤ (6+weightMass d L)*η := by + have hidentity : (∑ j, specialCoeff j*F (specialPoint j)) - + ∑ g, weight d L g*F (scaledNode L g) = + (∑ j, specialCoeff j*(F (specialPoint j)-P (specialPoint j))) - + ∑ g, weight d L g*(F (scaledNode L g)-P (scaledNode L g)) := by + simp only [mul_sub, Finset.sum_sub_distrib, five_interpolation P hP hL] + ring + rw [hidentity] + have h1 := finite_weighted_error specialCoeff (fun j => F (specialPoint j)-P (specialPoint j)) hs + have h2 := finite_weighted_error (weight d L) (fun g => F (scaledNode L g)-P (scaledNode L g)) hg + rw [sum_abs_specialCoeff] at h1 + calc + _ ≤ |∑ j, specialCoeff j*(F (specialPoint j)-P (specialPoint j))| + + |∑ g, weight d L g*(F (scaledNode L g)-P (scaledNode L g))| := abs_sub _ _ + _ ≤ 6*η + weightMass d L*η := add_le_add h1 h2 + _ = _ := by ring + +section Matrices +variable {R : Type u_2} [Fintype R] [DecidableEq R] + +lemma interpolation_matrix_domination (d : ℕ) + (B : Point → Matrix R R ℝ) (hB : ∀ x, (B x).PosSemidef) + (P : R → R → Point → ℝ) (hP : ∀ u v, P u v ∈ lowDegree coord d) + {L η : ℝ} (hL : L ≠ 0) (hη : 0 ≤ η) + (hs : ∀ j u v, |B (specialPoint j) u v-P u v (specialPoint j)| ≤ η) + (hg : ∀ g : GridIndex d, ∀ u v, |B (scaledNode L g) u v-P u v (scaledNode L g)| ≤ η) : + ∃ E : Matrix R R ℝ, E.PosSemidef ∧ + B (origin+dirA)+B (origin+dirB) ≤ B (origin+dirStar)+(2:ℝ) • B (origin+dirP)+E ∧ + ∀ (Q : Matrix R R ℝ) (m k : ℝ), Q.trace ≤ m → + (∀ g : GridIndex d, (Q*B (scaledNode L g)).trace ≤ k) → + (Q*E).trace ≤ weightMass d L*k + + (Fintype.card R : ℝ)*(6+weightMass d L)*η*m := by + let H := (∑ j, specialCoeff j • B (specialPoint j)) - + ∑ g, weight d L g • B (scaledNode L g) + let b := (6+weightMass d L)*η + let c := (Fintype.card R : ℝ)*b + let W := ∑ g, |weight d L g| • B (scaledNode L g) + have hb : 0 ≤ b := mul_nonneg (by linarith [weightMass_nonneg d L]) hη + have hc : 0 ≤ c := mul_nonneg (Nat.cast_nonneg _) hb + have hH : H.IsHermitian := by + have hh (x : Point) := (hB x).isHermitian.eq + simp only [H, Matrix.IsHermitian, Matrix.conjTranspose_sub, Matrix.conjTranspose_sum, + Matrix.conjTranspose_smul, star_trivial, hh] + have hentry (u v : R) : |H u v| ≤ b := by + simpa only [H, Matrix.sub_apply, Matrix.sum_apply, Matrix.smul_apply, smul_eq_mul] using + interpolation_error (fun x => B x u v) (P u v) (hP u v) hL (fun j => hs j u v) (fun g => hg g u v) + have hbound : H ≤ c • (1 : Matrix R R ℝ) := le_card_entry_bound hH hb hentry + have hW : W.PosSemidef := matrix_sum_psd _ _ (fun g _ => (hB _).smul (abs_nonneg _)) + let E := W+c • (1 : Matrix R R ℝ) + have hE : E.PosSemidef := hW.add (Matrix.PosSemidef.one.smul hc) + refine ⟨E,hE,?_,?_⟩ + · apply sub_nonneg.mp + apply Matrix.PosSemidef.nonneg + have hdiff : (∑ g : GridIndex d, (|weight d L g|-weight d L g) • B (scaledNode L g)).PosSemidef := + matrix_sum_psd _ _ (fun g _ => (hB _).smul (sub_nonneg.mpr (le_abs_self _))) + convert ((sub_nonneg.mpr hbound).posSemidef.add (hB origin)).add hdiff using 1 + dsimp [E,W,H] + simp only [sub_smul, Finset.sum_sub_distrib, specialPoint, specialCoeff, Fin.sum_univ_succ, + Matrix.cons_val_zero, Matrix.cons_val_succ, one_smul, neg_smul, + Fin.sum_univ_zero, add_zero] + module + · intro Q m k hm hk + change (Q*(W+c • (1 : Matrix R R ℝ))).trace ≤ _ + rw [mul_add, Matrix.trace_add, mul_smul_comm, Matrix.trace_smul, mul_one] + have hWt : (Q*W).trace ≤ weightMass d L*k := by + dsimp [W,weightMass] + rw [Finset.mul_sum, Matrix.trace_sum, Finset.sum_mul] + apply Finset.sum_le_sum + intro g _ + rw [mul_smul_comm, Matrix.trace_smul] + exact mul_le_mul_of_nonneg_left (hk g) (abs_nonneg _) + have he := add_le_add hWt (mul_le_mul_of_nonneg_left hm hc) + calc + _ ≤ weightMass d L*k + c*m := he + _ = _ := by dsimp [c,b]; ring + +end Matrices +end MatchingInterpolation + +end OAI diff --git a/lean/OAI/Combinatorics/MatchingPSD/Model.lean b/lean/OAI/Combinatorics/MatchingPSD/Model.lean new file mode 100644 index 0000000000000000000000000000000000000000..0f774147fff4c88ba5ca52c33c9cbd79385fda88 --- /dev/null +++ b/lean/OAI/Combinatorics/MatchingPSD/Model.lean @@ -0,0 +1,52 @@ +import Mathlib + +namespace OAI + +namespace PerfectMatchingPSD + +abbrev Edge (n : ℕ) := {p : Fin n × Fin n // p.1 < p.2} + +def IsPerfectMatching {n : ℕ} (M : Finset (Edge n)) : Prop := + ∀ v : Fin n, (M.filter fun e => e.1.1 = v ∨ e.1.2 = v).card = 1 + +abbrev PerfectMatching (n : ℕ) := + {M : Finset (Edge n) // IsPerfectMatching M} + +abbrev OddCut (n : ℕ) := {U : Finset (Fin n) // Odd U.card} + +abbrev Row (n : ℕ) := Edge n ⊕ OddCut n + +def Crosses {n : ℕ} (U : Finset (Fin n)) (e : Edge n) : Prop := + (e.1.1 ∈ U ∧ e.1.2 ∉ U) ∨ (e.1.1 ∉ U ∧ e.1.2 ∈ U) + +noncomputable def crossingCount {n : ℕ} (U : Finset (Fin n)) + (M : PerfectMatching n) : ℕ := by + classical + exact (M.1.filter (Crosses U)).card + +noncomputable def slack {n : ℕ} (i : Row n) (M : PerfectMatching n) : ℝ := by + classical + exact match i with + | Sum.inl e => if e ∈ M.1 then 1 else 0 + | Sum.inr U => (crossingCount U.1 M : ℝ) - 1 + +/-- Real PSD factors of order `r`, without equivariance or rank-one restrictions. -/ +def HasFactorization (n r : ℕ) : Prop := + ∃ (A : Row n → Matrix (Fin r) (Fin r) ℝ) + (B : PerfectMatching n → Matrix (Fin r) (Fin r) ℝ), + (∀ i, (A i).PosSemidef) ∧ (∀ M, (B M).PosSemidef) ∧ + ∀ i M, slack i M = Matrix.trace (A i * B M) + +/-- The least positive order of a real PSD factorization. -/ +noncomputable def psdRank (n : ℕ) : ℕ := + sInf {r : ℕ | 0 < r ∧ HasFactorization n r} + +/-- Every positive real power is eventually smaller than the PSD rank, +uniformly over all even vertex counts. The exponentiation is real `rpow`. -/ +def MainClaim : Prop := + ∀ C : ℝ, 0 < C → ∃ n₀ : ℕ, 4 ≤ n₀ ∧ + ∀ n : ℕ, n₀ ≤ n → Even n → (n : ℝ) ^ C < (psdRank n : ℝ) + +end PerfectMatchingPSD + +end OAI diff --git a/lean/OAI/Combinatorics/MatchingPSD/NormalizedFactors.lean b/lean/OAI/Combinatorics/MatchingPSD/NormalizedFactors.lean new file mode 100644 index 0000000000000000000000000000000000000000..be47fd04dfe14c4e81a873df6c28e17878b6facb --- /dev/null +++ b/lean/OAI/Combinatorics/MatchingPSD/NormalizedFactors.lean @@ -0,0 +1,49 @@ +import OAI.Combinatorics.MatchingPSD.MatchingConversion + +namespace OAI + +namespace PerfectMatchingPSD +open MatchingSmoothing Matrix +open scoped BigOperators +attribute [local instance] Classical.propDecidable + +lemma perfectMatching_nonempty {n : ℕ} (hn : Even n) : Nonempty (PerfectMatching n) := by + classical + obtain ⟨k,hk⟩ := hn + let e : (Fin k × Bool) ≃ Fin n := Fintype.equivOfCardEq (by + simp only [Fintype.card_prod, Fintype.card_fin, Fintype.card_bool] + omega) + exact ⟨fromPairing (Pairing.transport e standardPairing)⟩ + +lemma slack_le_vertices {n : ℕ} (hn : 1 ≤ n) (i : Row n) (M : PerfectMatching n) : + slack i M ≤ (n:ℝ) := by + rcases i with e | U + · simp only [slack] + split_ifs + · exact_mod_cast hn + · positivity + · have hd := cut_degree_identity U.1 M + have hcard : U.1.card ≤ n := by simpa using Finset.card_le_univ U.1 + have hc : crossingCount U.1 M ≤ n := by omega + have hc' : (crossingCount U.1 M : ℝ) ≤ n := by exact_mod_cast hc + change (crossingCount U.1 M : ℝ)-1 ≤ (n:ℝ) + linarith + +lemma normalized_factorization {n r : ℕ} (hn : Even n) (hnpos : 1 ≤ n) + (hfac : HasFactorization n r) : + ∃ (A : Row n → Matrix (Fin r) (Fin r) ℝ) + (B : PerfectMatching n → Matrix (Fin r) (Fin r) ℝ), + (∀ i, (A i).PosSemidef) ∧ (∀ M, (B M).PosSemidef) ∧ + (∀ i M, (A i*B M).trace = slack i M) ∧ + (∀ i, (A i).trace ≤ (n:ℝ)+1) ∧ (∀ M, (B M).trace ≤ (r:ℝ)) := by + classical + have := perfectMatching_nonempty hn + rcases hfac with ⟨A,B,hA,hB,hpair⟩ + obtain ⟨A',B',hA',hB',hpair',htrA,htrB⟩ := exists_normalized_factors A B hA hB (n:ℝ) + (fun i M => by rw [← hpair]; exact slack_le_vertices hnpos i M) + exact ⟨A',B',hA',hB',fun i M => (hpair' i M).trans (hpair i M).symm, + htrA,by simpa using htrB⟩ + +end PerfectMatchingPSD + +end OAI diff --git a/lean/OAI/Combinatorics/MatchingPSD/NumericalBounds.lean b/lean/OAI/Combinatorics/MatchingPSD/NumericalBounds.lean new file mode 100644 index 0000000000000000000000000000000000000000..da1db97a5969109dea713460f6cdddec95cc6b00 --- /dev/null +++ b/lean/OAI/Combinatorics/MatchingPSD/NumericalBounds.lean @@ -0,0 +1,80 @@ +import OAI.Combinatorics.MatchingPSD.Parameters + +namespace OAI + +namespace PerfectMatchingPSD +open MatchingSmoothing MatchingInterpolation Matrix +open scoped BigOperators MatrixOrder + +lemma blockSize_ge (d t : ℕ) : t^4 ≤ blockSize d t := by + dsimp [blockSize] + simpa only [one_mul] using Nat.mul_le_mul_right (t^4) (show 1 ≤ 4*(d+1) by omega) + +lemma blockSize_grid (d t : ℕ) : 2*t^4*d ≤ blockSize d t := by + dsimp [blockSize] + calc + 2*t^4*d = (2*d)*t^4 := by ring + _ ≤ 4*(d+1)*t^4 := Nat.mul_le_mul_right _ (by omega) + +lemma selection_of_cleared {q r T m L b : ℝ} (hb : 0 < b) (hc : 0 < r*m*L) + (hnum : q*r^6*T*m^2*L^2 ≤ b) : + q*r^4*T*b⁻¹ ≤ (1/(r*m*L))^2 := by + rw [← div_eq_mul_inv, div_pow, one_pow] + apply (div_le_div_iff₀ hb (sq_pos_of_pos hc)).mpr + calc + _ = q*r^6*T*m^2*L^2 := by ring + _ ≤ b := hnum + _ = _ := by ring + +lemma numerical_selection (p d t r n T : ℕ) (ht : 2 ≤ t) (hr : 0 < r) + (hn : n ≤ t^6) (hT : T ≤ t) (hrn : (r:ℝ) ≤ (n:ℝ)^p) : + (t:ℝ)*r^4*T*((2*(3*(blockSize d t:ℝ)+1))^(2*(10*(p+1))))⁻¹ ≤ + (1/((r:ℝ)*((n:ℝ)+1)*(2*(t:ℝ)^4)))^2 := by + have ht2 : (2:ℝ) ≤ t := by exact_mod_cast ht + have ht1 : (1:ℝ) ≤ t := by linarith + have ht0 : (0:ℝ) ≤ t := Nat.cast_nonneg t + have hr0 : (0:ℝ) ≤ r := Nat.cast_nonneg r + have hn6 : (n:ℝ) ≤ (t:ℝ)^6 := by exact_mod_cast hn + have hrp : (r:ℝ) ≤ (t:ℝ)^(6*p) := by + simpa only [pow_mul] using hrn.trans (pow_le_pow_left₀ (Nat.cast_nonneg n) hn6 p) + have hm : (n:ℝ)+1 ≤ (t:ℝ)^7 := by + have h6 : (1:ℝ) ≤ (t:ℝ)^6 := one_le_pow₀ ht1 + calc + _ ≤ (t:ℝ)^6+(t:ℝ)^6 := add_le_add hn6 h6 + _ = 2*(t:ℝ)^6 := by ring + _ ≤ (t:ℝ)*(t:ℝ)^6 := mul_le_mul_of_nonneg_right ht2 (pow_nonneg ht0 _) + _ = _ := by ring + have hL : 2*(t:ℝ)^4 ≤ (t:ℝ)^5 := by + calc + _ ≤ (t:ℝ)*(t:ℝ)^4 := mul_le_mul_of_nonneg_right ht2 (pow_nonneg ht0 _) + _ = _ := by ring + have hTr : (T:ℝ) ≤ t := by exact_mod_cast hT + have hbase : (t:ℝ)^4 ≤ 2*(3*(blockSize d t:ℝ)+1) := by + have hs : (t:ℝ)^4 ≤ (blockSize d t:ℝ) := by exact_mod_cast blockSize_ge d t + have hs0 : (0:ℝ) ≤ (blockSize d t:ℝ) := Nat.cast_nonneg _ + linarith + have hb : 0 < (2*(3*(blockSize d t:ℝ)+1))^(2*(10*(p+1))) := by positivity + apply selection_of_cleared hb (by positivity) + calc + _ ≤ (t:ℝ)*((t:ℝ)^(6*p))^6*(t:ℝ)*((t:ℝ)^7)^2*((t:ℝ)^5)^2 := by gcongr + _ = (t:ℝ)^(36*p+26) := by + have he : 36*p+26 = 1+(6*p)*6+1+7*2+5*2 := by omega + rw [he] + simp only [pow_add, pow_mul, pow_one] + _ ≤ (t:ℝ)^(8*(10*(p+1))) := pow_le_pow_right₀ ht1 (by omega) + _ = ((t:ℝ)^4)^(2*(10*(p+1))) := by rw [← pow_mul]; congr 1; omega + _ ≤ _ := pow_le_pow_left₀ (pow_nonneg ht0 _) hbase _ + +lemma numerical_smallness (D : ℝ) (t : ℕ) (ht : 1 ≤ t) (hD : 8*(D+1) ≤ (t:ℝ)) : + 16*(t:ℝ)^2*((t:ℝ)*D+1) ≤ 2*(t:ℝ)^4 := by + have ht1 : (1:ℝ) ≤ t := by exact_mod_cast ht + have ht0 : (0:ℝ) ≤ t := Nat.cast_nonneg t + calc + _ ≤ 16*(t:ℝ)^2*((t:ℝ)*(D+1)) := by gcongr; linarith + _ = 2*(t:ℝ)^3*(8*(D+1)) := by ring + _ ≤ 2*(t:ℝ)^3*(t:ℝ) := mul_le_mul_of_nonneg_left hD (by positivity) + _ = _ := by ring + +end PerfectMatchingPSD + +end OAI diff --git a/lean/OAI/Combinatorics/MatchingPSD/OrthogonalCone.lean b/lean/OAI/Combinatorics/MatchingPSD/OrthogonalCone.lean new file mode 100644 index 0000000000000000000000000000000000000000..8809d618f4142e0c7b21394d5428850f495fe115 --- /dev/null +++ b/lean/OAI/Combinatorics/MatchingPSD/OrthogonalCone.lean @@ -0,0 +1,63 @@ +import Mathlib +import OAI.Combinatorics.MatchingPSD.DiagonalCone + +namespace OAI + +namespace AffinePSD +open Matrix Finset +open scoped BigOperators +variable {I R : Type*} [Fintype I] [Fintype R] [DecidableEq R] + +lemma trace_orthogonal_congruence (U A D : Matrix R R ℝ) + (hU : U * Uᵀ = 1) : + ((Uᵀ * A * U) * (Uᵀ * D * U)).trace = (A * D).trace := by + have he : (Uᵀ * A * U) * (Uᵀ * D * U) = Uᵀ * (A * D) * U := by + simp only [Matrix.mul_assoc] + rw [← Matrix.mul_assoc U Uᵀ, hU, Matrix.one_mul] + rw [he, Matrix.trace_mul_cycle, hU, Matrix.one_mul] + +omit [Fintype I] in +lemma evaluationCone_orthogonal (B : I → Matrix R R ℝ) + (U : Matrix R R ℝ) (hU' : U * Uᵀ = 1) : + evaluationCone (fun i => Uᵀ * B i * U) = evaluationCone B := by + ext y + constructor + · rintro ⟨A, hA, rfl⟩ + refine ⟨U * A * Uᵀ, ?_, ?_⟩ + · simpa using hA.mul_mul_conjTranspose_same U + · ext i + change (U * A * Uᵀ * B i).trace = (A * (Uᵀ * B i * U)).trace + rw [Matrix.mul_assoc U A Uᵀ, Matrix.mul_assoc U (A * Uᵀ) (B i), + Matrix.trace_mul_comm U] + simp only [Matrix.mul_assoc] + · rintro ⟨A, hA, rfl⟩ + refine ⟨Uᵀ * A * U, ?_, ?_⟩ + · simpa using hA.conjTranspose_mul_mul_same U + · ext i + exact trace_orthogonal_congruence U A (B i) hU' + +lemma evaluationCone_isClosed (B : I → Matrix R R ℝ) + (hB : ∀ i, (B i).PosSemidef) : IsClosed (evaluationCone B) := by + classical + have hS : (∑ i, B i).PosSemidef := Matrix.posSemidef_sum _ (fun i _ => hB i) + let U : Matrix R R ℝ := hS.isHermitian.eigenvectorUnitary + let d : R → ℝ := hS.isHermitian.eigenvalues + have hU : Uᵀ * U = 1 := by + simpa only [U, Matrix.star_eq_conjTranspose, Matrix.conjTranspose_eq_transpose_of_trivial] + using hS.isHermitian.eigenvectorUnitary.property.1 + have hU' : U * Uᵀ = 1 := by + simpa only [U, Matrix.star_eq_conjTranspose, Matrix.conjTranspose_eq_transpose_of_trivial] + using hS.isHermitian.eigenvectorUnitary.property.2 + have hspec : ∑ i, B i = U * diagonal d * Uᵀ := by + simpa [Unitary.conjStarAlgAut_apply, Matrix.star_eq_conjTranspose, + Matrix.conjTranspose_eq_transpose_of_trivial, U, d] using hS.isHermitian.spectral_theorem + rw [← evaluationCone_orthogonal B U hU'] + refine evaluationCone_isClosed_of_diagonal _ (fun i => ?_) d ?_ + · simpa using (hB i).conjTranspose_mul_mul_same U + · rw [← Matrix.sum_mul, ← Matrix.mul_sum, hspec] + simp only [← Matrix.mul_assoc, hU, Matrix.one_mul] + rw [Matrix.mul_assoc, hU, Matrix.mul_one] + +end AffinePSD + +end OAI diff --git a/lean/OAI/Combinatorics/MatchingPSD/PSDCompression.lean b/lean/OAI/Combinatorics/MatchingPSD/PSDCompression.lean new file mode 100644 index 0000000000000000000000000000000000000000..ee6236049750fbcd10879bebf1e17c607ac5f00d --- /dev/null +++ b/lean/OAI/Combinatorics/MatchingPSD/PSDCompression.lean @@ -0,0 +1,102 @@ +import Mathlib +import OAI.Combinatorics.MatchingPSD.PSDEvaluation + +namespace OAI + +namespace AffinePSD +open Matrix Finset +open scoped BigOperators +variable {I R : Type*} [Fintype I] [Fintype R] [DecidableEq R] + +lemma zero_col_of_diag_zero {A : Matrix R R ℝ} (hA : A.PosSemidef) + (i : R) (hi : A i i = 0) (j : R) : A j i = 0 := by + have h := (hA.dotProduct_mulVec_zero_iff (x := Pi.single i 1)).mp (by simpa using hi) + simpa using congrFun h j + +lemma zero_row_of_diag_zero {A : Matrix R R ℝ} (hA : A.PosSemidef) + (i : R) (hi : A i i = 0) (j : R) : A i j = 0 := by + have hs : A i j = A j i := by + simpa using congrArg (fun M : Matrix R R ℝ => M j i) hA.isHermitian.eq + rw [hs] + exact zero_col_of_diag_zero hA i hi j + +lemma diagonal_compression (B : I → Matrix R R ℝ) (hB : ∀ i, (B i).PosSemidef) + (d : R → ℝ) (hs : ∑ i, B i = diagonal d) (A : Matrix R R ℝ) + (hA : A.PosSemidef) : + ∃ A' : Matrix R R ℝ, A'.PosSemidef ∧ evaluation B A' = evaluation B A ∧ + (∀ j, d j = 0 → A' j j = 0) := by + classical + let p : R → ℝ := fun j => if d j = 0 then 0 else 1 + let P := diagonal p + have hdiag (i : I) (j : R) (hj : d j = 0) : B i j j = 0 := by + have hle : B i j j ≤ ∑ k, B k j j := + Finset.single_le_sum (fun k _ => (hB k).diag_nonneg) (Finset.mem_univ i) + have he : ∑ k, B k j j = d j := by + simpa only [Matrix.sum_apply, Matrix.diagonal_apply_eq] using + congrArg (fun M : Matrix R R ℝ => M j j) hs + have hn := (hB i).diag_nonneg (i := j) + rw [he, hj] at hle + exact le_antisymm hle hn + have hpB (i : I) : P * B i = B i := by + ext j k + simp only [P, Matrix.diagonal_mul, p] + split_ifs with hj + · simp [zero_row_of_diag_zero (hB i) j (hdiag i j hj) k] + · simp + have hBp (i : I) : B i * P = B i := by + ext j k + simp only [P, Matrix.mul_diagonal, p] + split_ifs with hk + · simp [zero_col_of_diag_zero (hB i) k (hdiag i k hk) j] + · simp + refine ⟨P * A * P, ?_, ?_, ?_⟩ + · simpa only [Matrix.conjTranspose_eq_transpose_of_trivial, P, Matrix.diagonal_transpose] + using hA.conjTranspose_mul_mul_same P + · ext i + change (P * A * P * B i).trace = (A * B i).trace + rw [Matrix.mul_assoc P A P, Matrix.mul_assoc P (A * P) (B i), + Matrix.trace_mul_comm P, Matrix.mul_assoc A P (B i), hpB, + Matrix.mul_assoc A (B i) P, hBp] + · intro j hj + simp [P, Matrix.mul_diagonal, Matrix.diagonal_mul, p, hj] + +omit [Fintype R] in +lemma sum_diagonal_nonneg (B : I → Matrix R R ℝ) (hB : ∀ i, (B i).PosSemidef) + (d : R → ℝ) (hs : ∑ i, B i = diagonal d) : ∀ j, 0 ≤ d j := by + intro j + have he : ∑ i, B i j j = d j := by + simpa only [Matrix.sum_apply, Matrix.diagonal_apply_eq] using + congrArg (fun M : Matrix R R ℝ => M j j) hs + rw [← he] + exact Finset.sum_nonneg (fun i _ => (hB i).diag_nonneg) + +lemma evaluation_sum_eq (B : I → Matrix R R ℝ) (d : R → ℝ) + (hs : ∑ i, B i = diagonal d) (A : Matrix R R ℝ) : + ∑ i, evaluation B A i = ∑ j, A j j * d j := by + simp only [evaluation_apply] + rw [← Matrix.trace_sum, ← Matrix.mul_sum, hs] + simp [Matrix.trace, Matrix.diag, Matrix.mul_diagonal] + +lemma diagonal_trace_bound (B : I → Matrix R R ℝ) (hB : ∀ i, (B i).PosSemidef) + (d : R → ℝ) (hs : ∑ i, B i = diagonal d) (A : Matrix R R ℝ) + (hA : A.PosSemidef) (hz : ∀ j, d j = 0 → A j j = 0) : + A.trace ≤ (∑ j, (d j)⁻¹) * ∑ i, evaluation B A i := by + have hd := sum_diagonal_nonneg B hB d hs + have he := evaluation_sum_eq B d hs A + rw [he] + change (∑ j, A j j) ≤ _ + rw [Finset.sum_mul] + apply Finset.sum_le_sum + intro j _ + by_cases hj : d j = 0 + · simp [hj, hz j hj] + · have hp : 0 < d j := lt_of_le_of_ne (hd j) (Ne.symm hj) + have hle : A j j * d j ≤ ∑ k, A k k * d k := + Finset.single_le_sum (fun k _ => mul_nonneg (hA.diag_nonneg (i := k)) (hd k)) (Finset.mem_univ j) + calc + A j j = (d j)⁻¹ * (A j j * d j) := by field_simp + _ ≤ (d j)⁻¹ * ∑ k, A k k * d k := mul_le_mul_of_nonneg_left hle (inv_nonneg.mpr hp.le) + +end AffinePSD + +end OAI diff --git a/lean/OAI/Combinatorics/MatchingPSD/PSDDuality.lean b/lean/OAI/Combinatorics/MatchingPSD/PSDDuality.lean new file mode 100644 index 0000000000000000000000000000000000000000..7e845f2ce13b7fb8932085b38757a0d2f747e7ab --- /dev/null +++ b/lean/OAI/Combinatorics/MatchingPSD/PSDDuality.lean @@ -0,0 +1,80 @@ +import Mathlib +import OAI.Combinatorics.MatchingPSD.OrthogonalCone +import OAI.Combinatorics.MatchingPSD.DeterminantNormalization + +namespace OAI + +namespace AffinePSD +open Matrix Finset +open scoped BigOperators +variable {I R : Type*} [Fintype I] [Fintype R] [DecidableEq R] + +omit [Fintype I] in +lemma evaluationCone_convex (B : I → Matrix R R ℝ) : Convex ℝ (evaluationCone B) := + PerfectMatchingPSD.convex_posSemidef.linear_image (evaluation B) + +omit [Fintype I] in +lemma evaluationCone_zero (B : I → Matrix R R ℝ) : 0 ∈ evaluationCone B := + ⟨0, Matrix.PosSemidef.zero, map_zero _⟩ + +omit [Fintype I] in +lemma evaluationCone_smul (B : I → Matrix R R ℝ) {y : I → ℝ} + (hy : y ∈ evaluationCone B) {t : ℝ} (ht : 0 ≤ t) : + t • y ∈ evaluationCone B := by + obtain ⟨A, hA, rfl⟩ := hy + exact ⟨t • A, hA.smul ht, map_smul _ _ _⟩ + +lemma trace_evaluation_duality (B : I → Matrix R R ℝ) (c : I → ℝ) + (A : Matrix R R ℝ) : + (A * ∑ i, c i • B i).trace = ∑ i, c i * evaluation B A i := by + simp [evaluation, Matrix.mul_sum, Matrix.trace_sum, Matrix.trace_smul] + +omit [Fintype I] [DecidableEq R] in +lemma psd_of_trace_nonneg {D : Matrix R R ℝ} (hD : D.IsHermitian) + (h : ∀ A : Matrix R R ℝ, A.PosSemidef → 0 ≤ (A * D).trace) : D.PosSemidef := by + apply Matrix.PosSemidef.of_dotProduct_mulVec_nonneg hD + intro x + have hx : (Matrix.vecMulVec x x).PosSemidef := by + simpa using Matrix.posSemidef_vecMulVec_self_star x + have ht := h _ hx + rw [Matrix.trace_mul_comm, Matrix.mul_vecMulVec, Matrix.trace_vecMulVec, + dotProduct_comm] at ht + simpa only [star_trivial] using ht + +lemma exists_psd_evaluation (B : I → Matrix R R ℝ) (hB : ∀ i, (B i).PosSemidef) + (y : I → ℝ) + (hy : ∀ c : I → ℝ, (∑ i, c i • B i).PosSemidef → 0 ≤ ∑ i, c i * y i) : + ∃ A : Matrix R R ℝ, A.PosSemidef ∧ evaluation B A = y := by + classical + change y ∈ evaluationCone B + by_contra hn + obtain ⟨f, u, hfy, hu⟩ := geometric_hahn_banach_point_closed + (evaluationCone_convex B) (evaluationCone_isClosed B hB) hn + have hu0 : u < 0 := by simpa using hu 0 (evaluationCone_zero B) + have hfn (z : I → ℝ) (hz : z ∈ evaluationCone B) : 0 ≤ f z := by + by_contra hneg + have hnz : f z < 0 := lt_of_not_ge hneg + have hratio : 0 < u / f z := div_pos_of_neg_of_neg hu0 hnz + have ht := hu ((u / f z + 1) • z) + (evaluationCone_smul B hz (by linarith : 0 ≤ u / f z + 1)) + rw [map_smul, smul_eq_mul] at ht + have he : (u / f z + 1) * f z = u + f z := by + field_simp [ne_of_lt hnz] + rw [he] at ht + linarith + let c : I → ℝ := fun i => f (fun j => if i = j then 1 else 0) + have hf (z : I → ℝ) : f z = ∑ i, c i * z i := by + simpa only [ContinuousLinearMap.coe_coe, c, smul_eq_mul, mul_comm] using f.toLinearMap.pi_apply_eq_sum_univ z + have hD : (∑ i, c i • B i).PosSemidef := by + apply psd_of_trace_nonneg + · exact isSelfAdjoint_sum univ (fun i _ => (hB i).isHermitian.smul (by simp [IsSelfAdjoint])) + · intro A hA + rw [trace_evaluation_duality, ← hf] + exact hfn _ ⟨A, hA, rfl⟩ + have h := hy c hD + rw [← hf] at h + linarith + +end AffinePSD + +end OAI diff --git a/lean/OAI/Combinatorics/MatchingPSD/PSDEvaluation.lean b/lean/OAI/Combinatorics/MatchingPSD/PSDEvaluation.lean new file mode 100644 index 0000000000000000000000000000000000000000..847077bbd3f71df5582623c01e25272747d358ab --- /dev/null +++ b/lean/OAI/Combinatorics/MatchingPSD/PSDEvaluation.lean @@ -0,0 +1,24 @@ +import Mathlib + +namespace OAI + +namespace AffinePSD +open Matrix Finset +open scoped BigOperators +variable {I R : Type*} [Fintype I] [Fintype R] [DecidableEq R] + +noncomputable def evaluation (B : I → Matrix R R ℝ) : Matrix R R ℝ →ₗ[ℝ] (I → ℝ) where + toFun A := fun i => (A * B i).trace + map_add' A C := by ext i; simp [add_mul, Matrix.trace_add] + map_smul' t A := by ext i; simp [Matrix.trace_smul] + +omit [Fintype I] in +@[simp] lemma evaluation_apply (B : I → Matrix R R ℝ) (A : Matrix R R ℝ) (i : I) : + evaluation B A i = (A * B i).trace := rfl + +noncomputable def evaluationCone (B : I → Matrix R R ℝ) : Set (I → ℝ) := + evaluation B '' {A | A.PosSemidef} + +end AffinePSD + +end OAI diff --git a/lean/OAI/Combinatorics/MatchingPSD/PSDTopology.lean b/lean/OAI/Combinatorics/MatchingPSD/PSDTopology.lean new file mode 100644 index 0000000000000000000000000000000000000000..a9b74271b08eed86c4c43c814676e1f074ea5090 --- /dev/null +++ b/lean/OAI/Combinatorics/MatchingPSD/PSDTopology.lean @@ -0,0 +1,35 @@ +import Mathlib +import OAI.Combinatorics.MatchingPSD.PSDEvaluation + +namespace OAI + +namespace AffinePSD +open Matrix Finset +open scoped BigOperators +variable {I R : Type*} [Fintype I] [Fintype R] [DecidableEq R] + +omit [Fintype I] [DecidableEq R] in +lemma psd_isClosed : IsClosed {A : Matrix R R ℝ | A.PosSemidef} := by + have he : {A : Matrix R R ℝ | A.PosSemidef} = + {A : Matrix R R ℝ | Aᵀ = A} ∩ + ⋂ x : R → ℝ, {A : Matrix R R ℝ | 0 ≤ x ⬝ᵥ (A *ᵥ x)} := by + ext A + simp only [Set.mem_ofPred_eq, Set.mem_inter_iff, Set.mem_iInter, + Matrix.posSemidef_iff_dotProduct_mulVec, star_trivial] + rfl + rw [he] + apply IsClosed.inter + · exact isClosed_eq (by fun_prop) continuous_id + · apply isClosed_iInter + intro x + apply isClosed_le continuous_const + simp only [dotProduct, Matrix.mulVec] + fun_prop + +omit [Fintype I] in +lemma evaluation_continuous (B : I → Matrix R R ℝ) : Continuous (evaluation B) := + (evaluation B).continuous_of_finiteDimensional + +end AffinePSD + +end OAI diff --git a/lean/OAI/Combinatorics/MatchingPSD/Padding.lean b/lean/OAI/Combinatorics/MatchingPSD/Padding.lean new file mode 100644 index 0000000000000000000000000000000000000000..d7a5fc2046a7b7290a713c557cd360a973e49752 --- /dev/null +++ b/lean/OAI/Combinatorics/MatchingPSD/Padding.lean @@ -0,0 +1,92 @@ +import OAI.Combinatorics.MatchingPSD.NormalizedFactors + +namespace OAI + +universe u_1 u_2 u_3 u_4 u_5 u_6 u_7 + +namespace PerfectMatchingPSD +open MatchingSmoothing Matrix +open scoped BigOperators +attribute [local instance] Classical.propDecidable + +noncomputable def colorCut {n : ℕ} {V : Type u_1} [Fintype V] + (e : V ≃ Fin n) (z : V → Bool) (hz : Odd (Fintype.card {v // z v = true})) : OddCut n := by + classical + refine ⟨Finset.univ.filter (fun v => z (e.symm v) = true), ?_⟩ + have he := Fintype.card_congr (Equiv.subtypeEquivOfSubtype' (p := fun v => z v = true) e) + have ho : Odd (Fintype.card {v : Fin n // z (e.symm v) = true}) := by + rw [← he] + exact hz + simpa only [Fintype.card_subtype] using ho + +lemma colorCut_slack {n : ℕ} {V : Type u_2} [Fintype V] + (e : V ≃ Fin n) (z : V → Bool) (hz : Odd (Fintype.card {v // z v = true})) + (M : Pairing V) : + slack (Sum.inr (colorCut e z hz)) (fromPairing (Pairing.transport e M)) = + tableCoordinate z (true,false) M - 1 := by + classical + rw [slack, crossingCount_tableCoordinate, tableCoordinate_transport] + congr 2 + funext v + simp [colorCut] + +lemma true_card_comp_equiv {V : Type u_3} {W : Type u_4} [Fintype V] [Fintype W] + (z : V → Bool) (e : W ≃ V) : + Fintype.card {w // z (e w) = true} = Fintype.card {v // z v = true} := + Fintype.card_congr (Equiv.subtypeEquiv e (fun _ => Iff.rfl)) + +lemma true_card_sum_false {V : Type u_5} {W : Type u_6} [Fintype V] [Fintype W] (z : V → Bool) : + Fintype.card {v : V ⊕ W // Sum.elim z (fun _ => false) v = true} = + Fintype.card {v : V // z v = true} := by + classical + let e : {v : V ⊕ W // Sum.elim z (fun _ => false) v = true} ≃ {v : V // z v = true} := + { toFun := fun v => match v with + | ⟨Sum.inl a,h⟩ => ⟨a,h⟩ + | ⟨Sum.inr _,h⟩ => nomatch h + invFun := fun v => ⟨Sum.inl v.1,v.2⟩ + left_inv := by + rintro ⟨v,h⟩ + cases v with + | inl v => rfl + | inr v => exact False.elim (Bool.false_ne_true h) + right_inv := by intro v; rfl } + exact Fintype.card_congr e + +lemma tableCoordinate_false {V : Type u_7} [Fintype V] (M : Pairing V) : + tableCoordinate (fun _ : V => false) (true,false) M = 0 := by + simp [tableCoordinate] + +lemma global_factors_of_factorization {n r s q : ℕ} (hn : Even n) (hnpos : 1 ≤ n) + (hfac : HasFactorization n r) {W : Type} [Fintype W] + (e : (GlobalVertices s q ⊕ W) ≃ Fin n) (MW : Pairing W) : + ∃ (Q : Equiv.Perm (GlobalVertices s q) → (Fin q → Bool) → Matrix (Fin r) (Fin r) ℝ) + (B : Pairing (GlobalVertices s q) → Matrix (Fin r) (Fin r) ℝ), + (∀ a y, (Q a y).PosSemidef) ∧ (∀ M, (B M).PosSemidef) ∧ + (∀ a y, (Q a y).trace ≤ (n:ℝ)+1) ∧ (∀ M, (B M).trace ≤ (r:ℝ)) ∧ + ∀ a y M, (Q a y * B (Pairing.relabel a M)).trace = + tableCoordinate (globalCutColor y) (true,false) M - 1 := by + classical + obtain ⟨A,B,hA,hB,hpair,htrA,htrB⟩ := normalized_factorization hn hnpos hfac + let z (a : Equiv.Perm (GlobalVertices s q)) (y : Fin q → Bool) : GlobalVertices s q ⊕ W → Bool := + Sum.elim (globalCutColor y ∘ a.symm) (fun _ => false) + have hz (a : Equiv.Perm (GlobalVertices s q)) (y : Fin q → Bool) : + Odd (Fintype.card {v // z a y v = true}) := by + rw [true_card_sum_false] + change Odd (Fintype.card {v // globalCutColor y (a.symm v) = true}) + rw [true_card_comp_equiv] + exact globalCutColor_odd s q y + let U (a : Equiv.Perm (GlobalVertices s q)) (y : Fin q → Bool) := colorCut e (z a y) (hz a y) + refine ⟨fun a y => A (Sum.inr (U a y)), + fun M => B (fromPairing (Pairing.transport e (Pairing.sum M MW))), + fun a y => hA _, fun M => hB _, fun a y => htrA _, fun M => htrB _, ?_⟩ + intro a y M + rw [hpair, colorCut_slack, tableCoordinate_sum, tableCoordinate_false, add_zero] + congr 1 + rw [← Pairing.transport_perm, tableCoordinate_transport] + congr 1 + ext v + simp + +end PerfectMatchingPSD + +end OAI diff --git a/lean/OAI/Combinatorics/MatchingPSD/Pairings.lean b/lean/OAI/Combinatorics/MatchingPSD/Pairings.lean new file mode 100644 index 0000000000000000000000000000000000000000..2afc95833958decf37f293e28d68dca15b3dad17 --- /dev/null +++ b/lean/OAI/Combinatorics/MatchingPSD/Pairings.lean @@ -0,0 +1,415 @@ +import OAI.Combinatorics.MatchingPSD.EdgeProducts + +namespace OAI + +universe u_1 u_2 + +namespace MatchingSmoothing +abbrev Pairing (α : Type u_1) := + {M : Equiv.Perm α // Function.Involutive M ∧ ∀ a, M a ≠ a} + +namespace Pairing +variable {α : Type u_2} + +@[ext] lemma ext {M N : Pairing α} (h : ∀ a, M.1 a = N.1 a) : M = N := + Subtype.ext (Equiv.ext h) + +@[simp] lemma partner_partner (M : Pairing α) (a : α) : M.1 (M.1 a) = a := M.2.1 a + +lemma partner_ne (M : Pairing α) (a : α) : M.1 a ≠ a := M.2.2 a + +@[simp] lemma partner_eq_iff (M : Pairing α) (a b : α) : M.1 a = b ↔ M.1 b = a := by + constructor <;> intro h <;> rw [← h, partner_partner] + +def relabel (p : Equiv.Perm α) (M : Pairing α) : Pairing α := + ⟨p * M.1 * p⁻¹, by + constructor + · intro a + simp [Equiv.Perm.mul_apply] + · intro a h + apply M.partner_ne (p⁻¹ a) + simpa using + congrArg (fun b => p⁻¹ b) h⟩ + +@[simp] lemma relabel_apply (p : Equiv.Perm α) (M : Pairing α) (a : α) : + (relabel p M).1 a = p (M.1 (p⁻¹ a)) := rfl + +@[simp] lemma relabel_one (M : Pairing α) : relabel 1 M = M := by ext a; simp + +@[simp] lemma relabel_mul (p q : Equiv.Perm α) (M : Pairing α) : + relabel (p * q) M = relabel p (relabel q M) := by + ext a + simp [Equiv.Perm.mul_apply] + +def relabelEquiv (p : Equiv.Perm α) : Equiv.Perm (Pairing α) where + toFun := relabel p + invFun := relabel p⁻¹ + left_inv M := by rw [← relabel_mul, inv_mul_cancel, relabel_one] + right_inv M := by rw [← relabel_mul, mul_inv_cancel, relabel_one] + +def act (p : Equiv.Perm α) : (Pairing α → ℝ) ≃ₗ[ℝ] (Pairing α → ℝ) where + toFun f M := f (relabel p⁻¹ M) + invFun f M := f (relabel p M) + left_inv f := by ext M; simp [← relabel_mul] + right_inv f := by ext M; simp [← relabel_mul] + map_add' f g := rfl + map_smul' c f := rfl + +@[simp] lemma act_apply (p : Equiv.Perm α) (f : Pairing α → ℝ) (M : Pairing α) : + act p f M = f (relabel p⁻¹ M) := rfl + +@[simp] lemma act_mul (p q : Equiv.Perm α) (f : Pairing α → ℝ) : + act (p * q) f = act p (act q f) := by + ext M + simp [← relabel_mul] + +@[simp] lemma act_one (f : Pairing α → ℝ) : act 1 f = f := by ext M; simp + +@[simp] lemma partner_sq (M : Pairing α) : M.1 ^ 2 = 1 := by + ext a + simp [pow_two, Equiv.Perm.mul_apply] + +lemma cycleType_eq [Fintype α] [DecidableEq α] (M N : Pairing α) : + M.1.cycleType = N.1.cycleType := by + have hm := Equiv.Perm.cycleType_of_pow_prime_eq_one M.partner_sq + have hn := Equiv.Perm.cycleType_of_pow_prime_eq_one N.partner_sq + have hsum (P : Pairing α) : P.1.cycleType.sum = Fintype.card α := by + rw [Equiv.Perm.sum_cycleType] + have hs : P.1.support = Finset.univ := by + ext a + simp [Equiv.Perm.mem_support, P.partner_ne] + rw [hs, Finset.card_univ] + have hc : M.1.cycleType.card = N.1.cycleType.card := by + have he := (hsum M).trans (hsum N).symm + rw [hm, hn] at he + simp only [Multiset.sum_replicate, nsmul_eq_mul, Nat.cast_id] at he + omega + rw [hm, hn, hc] + +lemma exists_relabel [Fintype α] [DecidableEq α] (M N : Pairing α) : + ∃ p : Equiv.Perm α, relabel p M = N := by + have h := Equiv.Perm.isConj_iff_cycleType_eq.mpr (cycleType_eq M N) + rcases isConj_iff.mp h with ⟨p, hp⟩ + refine ⟨p, Subtype.ext ?_⟩ + exact hp + +@[simp] lemma relabel_swap_partner [DecidableEq α] (M : Pairing α) (a : α) : + relabel (Equiv.swap a (M.1 a)) M = M := by + apply Subtype.ext + change Equiv.swap a (M.1 a) * M.1 * (Equiv.swap a (M.1 a))⁻¹ = M.1 + have hc : M.1 * Equiv.swap a (M.1 a) = Equiv.swap a (M.1 a) * M.1 := by + rw [Equiv.mul_swap_eq_swap_mul, partner_partner, Equiv.swap_comm] + rw [← hc, mul_inv_cancel_right] + +lemma exists_internal_edge_compl [Fintype α] [DecidableEq α] + (M : Pairing α) (U : Finset α) (hU : 2 * U.card < Fintype.card α) : + ∃ a, a ∉ U ∧ M.1 a ∉ U := by + by_contra! h + have hinj : Set.InjOn M.1 (↑Uᶜ : Set α) := M.1.injective.injOn + have hmaps : ∀ a ∈ Uᶜ, M.1 a ∈ U := by simpa using h + have hc := Finset.card_le_card_of_injOn M.1 hmaps hinj + rw [Finset.card_compl] at hc + have hu := Finset.card_le_univ U + omega + +lemma no_sign_on_complement [Fintype α] [DecidableEq α] + (U : Finset α) (hU : 2 * U.card < Fintype.card α) + (f : Pairing α → ℝ) + (hf : ∀ a ∉ U, ∀ b ∉ U, a ≠ b → act (Equiv.swap a b) f = -f) : f = 0 := by + ext M + obtain ⟨a, ha, hma⟩ := exists_internal_edge_compl M U hU + have he := congrFun (hf a ha (M.1 a) hma (M.partner_ne a).symm) M + simp only [act_apply, Equiv.swap_inv, relabel_swap_partner, Pi.neg_apply] at he + dsimp + linarith + +def SameInternal (U : Finset α) (M N : Pairing α) : Prop := + ∀ a ∈ U, ∀ b ∈ U, M.1 a = b ↔ N.1 a = b + +lemma align_partners [Fintype α] [DecidableEq α] + (U : Finset α) (M N : Pairing α) (hMN : SameInternal U M N) : + ∃ p : Equiv.Perm α, (∀ a ∈ U, p a = a) ∧ + ∀ a ∈ U, (relabel p M).1 a = N.1 a := by + classical + let S := {a : α // a ∈ U ∧ M.1 a ∉ U} + have hnout (a : S) : N.1 a.1 ∉ U := by + intro hn + have he := (hMN a.1 a.2.1 (N.1 a.1) hn).mpr rfl + exact a.2.2 (he.symm ▸ hn) + let f : U ⊕ S → α := Sum.elim (fun a => a.1) (fun a => M.1 a.1) + let g : U ⊕ S → α := Sum.elim (fun a => a.1) (fun a => N.1 a.1) + have hf : Function.Injective f := by + intro x y h + cases x with + | inl a => + cases y with + | inl b => exact congrArg Sum.inl (Subtype.ext h) + | inr b => + change a.1 = M.1 b.1 at h + exact False.elim (b.2.2 (h ▸ a.2)) + | inr a => + cases y with + | inl b => + change M.1 a.1 = b.1 at h + exact False.elim (a.2.2 (h.symm ▸ b.2)) + | inr b => exact congrArg Sum.inr (Subtype.ext (M.1.injective h)) + have hg : Function.Injective g := by + intro x y h + cases x with + | inl a => + cases y with + | inl b => exact congrArg Sum.inl (Subtype.ext h) + | inr b => + change a.1 = N.1 b.1 at h + exact False.elim (hnout b (h ▸ a.2)) + | inr a => + cases y with + | inl b => + change N.1 a.1 = b.1 at h + exact False.elim (hnout a (h.symm ▸ b.2)) + | inr b => exact congrArg Sum.inr (Subtype.ext (N.1.injective h)) + obtain ⟨p, hp⟩ := Equiv.Perm.exists_extending_pair f g hf hg + have hfix (a : α) (ha : a ∈ U) : p a = a := hp (Sum.inl ⟨a, ha⟩) + have hpart (a : α) (ha : a ∈ U) : p (M.1 a) = N.1 a := by + by_cases hm : M.1 a ∈ U + · rw [hfix _ hm] + exact ((hMN a ha (M.1 a) hm).mp rfl).symm + · exact hp (Sum.inr ⟨a, ha, hm⟩) + refine ⟨p, hfix, ?_⟩ + intro a ha + have hi : p⁻¹ a = a := by + calc + p⁻¹ a = p⁻¹ (p a) := congrArg (fun b => p⁻¹ b) (hfix a ha).symm + _ = a := by simp + simp only [relabel_apply, hi, hpart a ha] + +def restrict (M : Pairing α) (S : Finset α) + (hS : ∀ a, M.1 a ∈ S ↔ a ∈ S) : Pairing S := + ⟨M.1.subtypePerm hS, by + constructor + · intro a; apply Subtype.ext; exact M.partner_partner a.1 + · intro a h; exact M.partner_ne a.1 (congrArg Subtype.val h)⟩ + +@[simp] lemma restrict_apply (M : Pairing α) (S : Finset α) + (hS : ∀ a, M.1 a ∈ S ↔ a ∈ S) (a : S) : + ((restrict M S hS).1 a).1 = M.1 a.1 := rfl + +def closure [DecidableEq α] (M : Pairing α) (U : Finset α) : Finset α := + U ∪ U.image M.1 + +lemma mem_closure [DecidableEq α] (M : Pairing α) (U : Finset α) (a : α) : + a ∈ closure M U ↔ a ∈ U ∨ M.1 a ∈ U := by + simp only [closure, Finset.mem_union, Finset.mem_image] + constructor + · rintro (h | ⟨b, hb, rfl⟩) + · exact Or.inl h + · exact Or.inr (by simpa using hb) + · rintro (h | h) + · exact Or.inl h + · exact Or.inr ⟨M.1 a, h, M.partner_partner a⟩ + +lemma stable_closure [DecidableEq α] (M : Pairing α) (U : Finset α) (a : α) : + M.1 a ∈ closure M U ↔ a ∈ closure M U := by + simp only [mem_closure, partner_partner, or_comm] + +lemma agree_on_closure [DecidableEq α] (U : Finset α) (M N : Pairing α) + (h : ∀ a ∈ U, M.1 a = N.1 a) : + ∀ a ∈ closure N U, M.1 a = N.1 a := by + intro a ha + rcases (mem_closure N U a).mp ha with ha | ha + · exact h a ha + · apply (M.partner_eq_iff a (N.1 a)).mpr + rw [h _ ha, partner_partner] + +lemma align_remaining [Fintype α] [DecidableEq α] + (U : Finset α) (M N : Pairing α) + (hMN : ∀ a ∈ U, M.1 a = N.1 a) : + ∃ p : Equiv.Perm α, (∀ a ∈ U, p a = a) ∧ relabel p M = N := by + classical + let S := (closure N U)ᶜ + have hagree := agree_on_closure U M N hMN + have hcM : ∀ a ∈ closure N U, M.1 a ∈ closure N U := by + intro a ha + rw [hagree a ha] + exact (stable_closure N U a).mpr ha + have hcMi (a : α) : M.1 a ∈ closure N U ↔ a ∈ closure N U := by + constructor + · intro ha + simpa using hcM (M.1 a) ha + · exact hcM a + have hM (a : α) : M.1 a ∈ S ↔ a ∈ S := by + simp only [S, Finset.mem_compl, hcMi] + have hN (a : α) : N.1 a ∈ S ↔ a ∈ S := by + simp only [S, Finset.mem_compl, stable_closure] + obtain ⟨q, hq⟩ := exists_relabel (restrict M S hM) (restrict N S hN) + let p := q.extendDomain (Equiv.refl S) + have hpin (a : α) (ha : a ∈ S) : p a = (q ⟨a, ha⟩).1 := by + simpa [p] using Equiv.Perm.extendDomain_apply_subtype q (Equiv.refl S) ha + have hpout (a : α) (ha : a ∉ S) : p a = a := by + exact Equiv.Perm.extendDomain_apply_not_subtype q (Equiv.refl S) ha + have hinter (a : α) : p (M.1 a) = N.1 (p a) := by + by_cases ha : a ∈ S + · have hh := congrArg (fun P : Pairing S => (P.1 (q ⟨a, ha⟩)).1) hq + rw [hpin _ ((hM a).mpr ha), hpin a ha] + simpa [restrict] using hh + · have hma : M.1 a ∉ S := by simpa only [hM] using ha + rw [hpout _ hma, hpout _ ha] + exact hagree a (by simpa only [S, Finset.mem_compl, not_not] using ha) + refine ⟨p, ?_, ?_⟩ + · intro a ha + apply hpout + simp only [S, Finset.mem_compl, not_not] + exact (mem_closure N U a).mpr (Or.inl ha) + · ext a + obtain ⟨b, rfl⟩ := p.surjective a + simpa using hinter b + +lemma exists_relabel_fixing [Fintype α] [DecidableEq α] + (U : Finset α) (M N : Pairing α) (hMN : SameInternal U M N) : + ∃ p : Equiv.Perm α, (∀ a ∈ U, p a = a) ∧ relabel p M = N := by + obtain ⟨p, hp, hpM⟩ := align_partners U M N hMN + obtain ⟨q, hq, hqM⟩ := align_remaining U (relabel p M) N hpM + refine ⟨q * p, ?_, ?_⟩ + · intro a ha + simp only [Equiv.Perm.mul_apply, hp a ha, hq a ha] + · rw [relabel_mul, hqM] + +lemma extend_swap [DecidableEq α] (S : Finset α) (x y : S) : + (Equiv.swap x y).extendDomain (Equiv.refl S) = Equiv.swap x.1 y.1 := by + ext a + by_cases ha : a ∈ S + · rw [Equiv.Perm.extendDomain_apply_subtype _ _ ha] + by_cases hx : a = x.1 <;> by_cases hy : a = y.1 <;> + simp [Equiv.swap_apply_def, Subtype.ext_iff, hx, hy] + · rw [Equiv.Perm.extendDomain_apply_not_subtype _ _ ha] + have hx : a ≠ x.1 := by rintro rfl; exact ha x.2 + have hy : a ≠ y.1 := by rintro rfl; exact ha y.2 + simp [Equiv.swap_apply_def, hx, hy] + +lemma invariant_of_swap_invariant [Fintype α] [DecidableEq α] + (U : Finset α) (f : Pairing α → ℝ) + (hf : ∀ a ∉ U, ∀ b ∉ U, a ≠ b → act (Equiv.swap a b) f = f) + (p : Equiv.Perm α) (hp : ∀ a ∈ U, p a = a) : act p f = f := by + classical + let S := Uᶜ + have hU (a : α) : p a ∈ U ↔ a ∈ U := by + constructor + · intro h + have he : p a = a := p.injective (hp (p a) h) + simpa [he] using h + · intro h; simpa [hp a h] using h + have hS (a : α) : p a ∈ S ↔ a ∈ S := by simp only [S, Finset.mem_compl, hU] + have hind (q : Equiv.Perm S) : act (q.extendDomain (Equiv.refl S)) f = f := by + induction q using Equiv.Perm.swap_induction_on with + | one => simp + | swap_mul q x y hxy ih => + rw [← Equiv.Perm.extendDomain_mul, act_mul, ih, extend_swap] + apply hf x.1 (by simpa only [S, Finset.mem_compl] using x.2) + y.1 (by simpa only [S, Finset.mem_compl] using y.2) + exact fun h => hxy (Subtype.ext h) + have he : (p.subtypePerm hS).extendDomain (Equiv.refl S) = p := by + ext a + by_cases ha : a ∈ S + · rw [Equiv.Perm.extendDomain_apply_subtype _ _ ha] + rfl + · rw [Equiv.Perm.extendDomain_apply_not_subtype _ _ ha] + exact (hp a (by simpa only [S, Finset.mem_compl, not_not] using ha)).symm + rw [← he] + exact hind _ + +lemma sameInternal_value_of_invariant [Fintype α] [DecidableEq α] + (U : Finset α) (f : Pairing α → ℝ) + (hf : ∀ a ∉ U, ∀ b ∉ U, a ≠ b → act (Equiv.swap a b) f = f) + (M N : Pairing α) (hMN : SameInternal U M N) : f M = f N := by + obtain ⟨p, hp, hpM⟩ := exists_relabel_fixing U M N hMN + have he := congrFun (invariant_of_swap_invariant U f hf p hp) N + rw [act_apply, ← hpM, ← relabel_mul, inv_mul_cancel, relabel_one] at he + simpa only [hpM] using he + +noncomputable def edgeCoord (e : α × α) (M : Pairing α) : ℝ := by + classical + exact if M.1 e.1 = e.2 then 1 else 0 + +noncomputable def internalPattern [DecidableEq α] (U : Finset α) + (M : Pairing α) : Finset (α × α) := + (U ×ˢ U).filter fun e => M.1 e.1 = e.2 + +lemma internalPattern_eq_iff [DecidableEq α] (U : Finset α) (M N : Pairing α) : + internalPattern U M = internalPattern U N ↔ SameInternal U M N := by + constructor + · intro h a ha b hb + have he := Finset.ext_iff.mp h (a,b) + simpa [internalPattern, ha, hb] using he + · intro h + ext ⟨a,b⟩ + simp only [internalPattern, Finset.mem_filter, Finset.mem_product] + by_cases ha : a ∈ U <;> by_cases hb : b ∈ U <;> simp_all [SameInternal] + +lemma internal_indicator_mem_lowDegree [Fintype α] [DecidableEq α] + (U : Finset α) (M : Pairing α) : + (fun N => if internalPattern U N = internalPattern U M then (1 : ℝ) else 0) + ∈ lowDegree edgeCoord (U.card * U.card) := by + classical + have h := boolean_pattern_mem_lowDegree edgeCoord (U ×ˢ U) (internalPattern U M) + rw [Finset.card_product] at h + convert h using 1 + ext N + rw [Finset.prod_apply] + have hf (e : α × α) (he : e ∈ U ×ˢ U) : + (if e ∈ internalPattern U M then edgeCoord e else 1 - edgeCoord e) N = + (if (N.1 e.1 = e.2 ↔ M.1 e.1 = e.2) then (1 : ℝ) else 0) := by + by_cases hm : M.1 e.1 = e.2 <;> by_cases hn : N.1 e.1 = e.2 <;> + simp [internalPattern, he, hm, hn, edgeCoord] + rw [Finset.prod_congr rfl hf, Finset.prod_boole] + congr 1 + rw [internalPattern_eq_iff] + simp only [SameInternal, Finset.mem_product, Prod.forall] + aesop + +lemma mem_lowDegree_of_swap_invariant [Fintype α] [DecidableEq α] + (U : Finset α) (f : Pairing α → ℝ) + (hf : ∀ a ∉ U, ∀ b ∉ U, a ≠ b → act (Equiv.swap a b) f = f) : + f ∈ lowDegree edgeCoord (U.card * U.card) := by + apply mem_of_fiber_indicators (internalPattern U) f + · intro M N hMN + exact sameInternal_value_of_invariant U f hf M N + ((internalPattern_eq_iff U M N).mp hMN) + · exact internal_indicator_mem_lowDegree U + +lemma exists_perm_fixing_pair [Fintype α] [DecidableEq α] + (U : Finset α) {a b c d : α} (ha : a ∉ U) (hb : b ∉ U) + (hc : c ∉ U) (hd : d ∉ U) (hab : a ≠ b) (hcd : c ≠ d) : + ∃ p : Equiv.Perm α, (∀ u ∈ U, p u = u) ∧ p a = c ∧ p b = d := by + let f : U ⊕ Bool → α := Sum.elim Subtype.val (fun i => cond i b a) + let g : U ⊕ Bool → α := Sum.elim Subtype.val (fun i => cond i d c) + have hi {x y : α} (hx : x ∉ U) (hy : y ∉ U) (hxy : x ≠ y) : + Function.Injective (Sum.elim (Subtype.val : U → α) (fun i : Bool => cond i y x)) := by + rw [Sum.elim_injective] + refine ⟨Subtype.val_injective, ?_, ?_⟩ + · intro i j h + cases i <;> cases j <;> simp_all + · intro u i + cases i <;> simp only [Bool.cond_false, Bool.cond_true] + · intro h; exact hx (h ▸ u.2) + · intro h; exact hy (h ▸ u.2) + obtain ⟨p, hp⟩ := Equiv.Perm.exists_extending_pair f g (hi ha hb hab) (hi hc hd hcd) + exact ⟨p, fun u hu => hp (Sum.inl ⟨u, hu⟩), hp (Sum.inr false), hp (Sum.inr true)⟩ + +lemma act_swap_involution [DecidableEq α] (a b : α) (f : Pairing α → ℝ) : + act (Equiv.swap a b) (act (Equiv.swap a b) f) = f := by + rw [← act_mul, Equiv.swap_mul_self, act_one] + +lemma act_swap_conj [DecidableEq α] (p : Equiv.Perm α) (a b : α) + (f : Pairing α → ℝ) : + act (Equiv.swap (p a) (p b)) (act p f) = act p (act (Equiv.swap a b) f) := by + rw [← act_mul, ← act_mul, Equiv.mul_swap_eq_swap_mul] + +lemma act_commute_of_swap_fixed [DecidableEq α] (p : Equiv.Perm α) (a b : α) + (ha : p a = a) (hb : p b = b) (f : Pairing α → ℝ) : + act (Equiv.swap a b) (act p f) = act p (act (Equiv.swap a b) f) := by + simpa only [ha, hb] using act_swap_conj p a b f + +end Pairing +end MatchingSmoothing + +end OAI diff --git a/lean/OAI/Combinatorics/MatchingPSD/Parameters.lean b/lean/OAI/Combinatorics/MatchingPSD/Parameters.lean new file mode 100644 index 0000000000000000000000000000000000000000..2ba2f7c888d7f0f9497e0ceebc12bdb68bafa974 --- /dev/null +++ b/lean/OAI/Combinatorics/MatchingPSD/Parameters.lean @@ -0,0 +1,77 @@ +import OAI.Combinatorics.MatchingPSD.Padding + +namespace OAI + +namespace PerfectMatchingPSD +open MatchingSmoothing MatchingInterpolation Matrix Filter Asymptotics +open scoped BigOperators MatrixOrder + +def blockSize (d t : ℕ) : ℕ := 4*(d+1)*t^4 +def vertexSize (d t : ℕ) : ℕ := 2*blockSize d t*(t+2)+2 + +lemma index_le_vertexSize (d t : ℕ) : t ≤ vertexSize d t := by + have ht : t ≤ t^4 := Nat.le_pow (by decide) + have hc : 1 ≤ 8*(d+1)*(t+2) := by + have : 0 < 8*(d+1)*(t+2) := by positivity + omega + calc + t ≤ t^4 := ht + _ ≤ (8*(d+1)*(t+2))*t^4 := by simpa only [one_mul] using Nat.mul_le_mul_right (t^4) hc + _ ≤ vertexSize d t := by dsimp [vertexSize, blockSize]; nlinarith + +lemma vertexSize_succ_bound (d t : ℕ) (ht : 1 ≤ t) : + vertexSize d (t+1) ≤ 1024*(d+1)*t^5 := by + have hp : 1 ≤ (d+1)*t^5 := by + have : 0 < (d+1)*t^5 := by positivity + omega + calc + _ = 8*(d+1)*(t+1)^4*(t+3)+2 := by dsimp [vertexSize, blockSize]; ring + _ ≤ 8*(d+1)*(2*t)^4*(4*t)+2 := by gcongr <;> omega + _ = 512*(d+1)*t^5+2 := by ring + _ ≤ _ := by nlinarith + +lemma vertexSize_succ_le_pow6 (d t : ℕ) (ht : 1 ≤ t) (hd : 1024*(d+1) ≤ t) : + vertexSize d (t+1) ≤ t^6 := by + calc + _ ≤ 1024*(d+1)*t^5 := vertexSize_succ_bound d t ht + _ ≤ t*t^5 := Nat.mul_le_mul_right _ hd + _ = _ := by ring + +lemma bracket_vertexSize (d T n : ℕ) (hn : vertexSize d T ≤ n) : + ∃ t : ℕ, T ≤ t ∧ vertexSize d t ≤ n ∧ n < vertexSize d (t+1) := by + classical + let P := fun t => vertexSize d t ≤ n + let t := Nat.findGreatest P n + have hT : T ≤ n := (index_le_vertexSize d T).trans hn + refine ⟨t, Nat.le_findGreatest (P := P) hT hn, Nat.findGreatest_spec (P := P) hT hn, ?_⟩ + by_contra h + have hnext : P (t+1) := le_of_not_gt h + have htn : t+1 ≤ n := (index_le_vertexSize d (t+1)).trans hnext + exact (Nat.findGreatest_eq_iff.mp (show Nat.findGreatest P n=t from rfl)).2.2 + (Nat.lt_succ_self t) htn hnext + +lemma exists_padded_global_equiv {n s q : ℕ} (hn : Even n) (hle : 2*s*(q+2)+2 ≤ n) : + ∃ k : ℕ, Nonempty ((GlobalVertices s q ⊕ (Fin k × Bool)) ≃ Fin n) := by + have hg : Even (2*s*(q+2)+2) := ⟨s*(q+2)+1, by ring⟩ + have hd : Even (n-(2*s*(q+2)+2)) := (Nat.even_sub hle).mpr ⟨fun _ => hg, fun _ => hn⟩ + obtain ⟨k,hk⟩ := hd + refine ⟨k, ⟨Fintype.equivOfCardEq ?_⟩⟩ + rw [Fintype.card_sum, globalVertices_card] + simp only [Fintype.card_prod, Fintype.card_fin, Fintype.card_bool] + omega + +lemma eventually_pow_lt_half_exp (p : ℕ) : + ∀ᶠ t : ℕ in atTop, (t:ℝ)^p < (2:ℝ)^t/2 := by + have ho := isLittleO_pow_const_const_pow_of_one_lt (R := ℝ) p (by norm_num : 1 < (2:ℝ)) + have hb := ho.bound (by norm_num : (0:ℝ) < 1/4) + filter_upwards [hb] with t ht + have ht' : (t:ℝ)^p ≤ (1/4)*(2:ℝ)^t := by + simpa only [Real.norm_eq_abs, abs_of_nonneg (show (0:ℝ) ≤ (t:ℝ)^p by positivity), + abs_of_pos (pow_pos (by norm_num : (0:ℝ)<2) _)] using ht + calc + _ ≤ (1/4)*(2:ℝ)^t := ht' + _ < _ := by nlinarith [pow_pos (by norm_num : (0:ℝ)<2) t] + +end PerfectMatchingPSD + +end OAI diff --git a/lean/OAI/Combinatorics/MatchingPSD/PartialColorings.lean b/lean/OAI/Combinatorics/MatchingPSD/PartialColorings.lean new file mode 100644 index 0000000000000000000000000000000000000000..042144def37b03c3716cfea944773247f3a01dd8 --- /dev/null +++ b/lean/OAI/Combinatorics/MatchingPSD/PartialColorings.lean @@ -0,0 +1,147 @@ +import OAI.Combinatorics.MatchingPSD.EdgeMonomials + +namespace OAI + +universe u_1 u_2 + +namespace MatchingSmoothing +attribute [local instance] Classical.propDecidable +section ColorCounting +variable {V : Type u_1} {C : Type u_2} [Fintype V] + +omit [Fintype V] in +lemma swap_preserves_color (z : V → C) {a b : V} (hab : z a = z b) (v : V) : + z (Equiv.swap a b v) = z v := by + by_cases hva : v = a + · subst v; simpa using hab.symm + by_cases hvb : v = b + · subst v; simpa using hab + rw [Equiv.swap_apply_of_ne_of_ne hva hvb] + +omit [Fintype V] in +lemma swap_fixes_finset (U : Finset V) {a b : V} (ha : a ∉ U) (hb : b ∉ U) + (v : V) (hv : v ∈ U) : Equiv.swap a b v = v := + Equiv.swap_apply_of_ne_of_ne (fun h => ha (h ▸ hv)) (fun h => hb (h ▸ hv)) + +omit [Fintype V] in +lemma exists_color_perm_fixing_pair (z : V → C) (U : Finset V) + {a b c d : V} (ha : a ∉ U) (hb : b ∉ U) (hc : c ∉ U) (hd : d ∉ U) + (hab : a ≠ b) (hcd : c ≠ d) (hzac : z a = z c) (hzbd : z b = z d) : + ∃ p : colorStabilizer z, (∀ v ∈ U, p.1 v = v) ∧ p.1 a = c ∧ p.1 b = d := by + let q := Equiv.swap a c + have hq : ∀ v, z (q v) = z v := swap_preserves_color z hzac + have hqfix : ∀ v ∈ U, q v = v := swap_fixes_finset U ha hc + have hqb : q b ∉ U := by + intro h + have hh := hqfix (q b) h + have : b = q b := by simpa only [q, Equiv.swap_apply_self] using hh + exact hb (this ▸ h) + let p := Equiv.swap (q b) d * q + have hp : p ∈ colorStabilizer z := by + intro v + change z (Equiv.swap (q b) d (q v)) = z v + rw [swap_preserves_color z ((hq b).trans hzbd), hq] + refine ⟨⟨p, hp⟩, ?_, ?_, ?_⟩ + · intro v hv + change Equiv.swap (q b) d (q v) = v + rw [hqfix v hv, swap_fixes_finset U hqb hd v hv] + · change Equiv.swap (q b) d (q a) = c + have hqbc : q b ≠ c := by + change Equiv.swap a c b ≠ c + intro h + have hh := congrArg (Equiv.swap a c) h + have : b = a := by simpa using hh + exact hab this.symm + rw [show q a = c by simp [q]] + exact Equiv.swap_apply_of_ne_of_ne hqbc.symm hcd + · change Equiv.swap (q b) d (q b) = d + simp + +noncomputable def tableCoordinate (z : V → C) (c : C × C) (M : Pairing V) : ℝ := + ∑ v, if z v = c.1 ∧ z (M.1 v) = c.2 then 1 else 0 + +lemma tableCoordinate_invariant (z : V → C) (c : C × C) (p : colorStabilizer z) : + Pairing.act p.1 (tableCoordinate z c) = tableCoordinate z c := by + funext M + simp only [Pairing.act_apply, tableCoordinate, Pairing.relabel_apply, inv_inv] + have hi (v : V) : z (p.1⁻¹ v) = z v := (p⁻¹).property v + simp_rw [hi] + rw [← Equiv.sum_comp p.1 (fun v => if z v = c.1 ∧ z (M.1 v) = c.2 then (1:ℝ) else 0)] + apply Finset.sum_congr rfl + intro v _ + rw [p.property] + +noncomputable def candidateEdges (z : V → C) (U : Finset V) (c : C × C) : Finset (V × V) := + Finset.univ.filter fun e => e.1 ∉ U ∧ e.2 ∉ U ∧ e.1 ≠ e.2 ∧ z e.1 = c.1 ∧ z e.2 = c.2 + +lemma mem_candidateEdges (z : V → C) (U : Finset V) (c : C × C) (e : V × V) : + e ∈ candidateEdges z U c ↔ + e.1 ∉ U ∧ e.2 ∉ U ∧ e.1 ≠ e.2 ∧ z e.1 = c.1 ∧ z e.2 = c.2 := by + simp [candidateEdges] + +lemma candidate_average_eq (z : V → C) (l : List (V × V)) (c : C × C) + (e f : V × V) (he : e ∈ candidateEdges z (Pairing.edgeSupport l) c) + (hf : f ∈ candidateEdges z (Pairing.edgeSupport l) c) : + colorAverage z (Pairing.edgeMonomial (e::l)) = + colorAverage z (Pairing.edgeMonomial (f::l)) := by + obtain ⟨ha, hb, hab, hza, hzb⟩ := (mem_candidateEdges _ _ _ _).mp he + obtain ⟨hc, hd, hcd, hzc, hzd⟩ := (mem_candidateEdges _ _ _ _).mp hf + obtain ⟨p, hp, hpa, hpb⟩ := exists_color_perm_fixing_pair z (Pairing.edgeSupport l) + ha hb hc hd hab hcd (hza.trans hzc.symm) (hzb.trans hzd.symm) + rw [← colorAverage_act z p (Pairing.edgeMonomial (e::l)), Pairing.edgeMonomial_cons] + have hact : Pairing.act p.1 (Pairing.edgeCoord e * Pairing.edgeMonomial l) = + Pairing.edgeCoord f * Pairing.edgeMonomial l := by + rw [Pairing.act_pointwise_mul, Pairing.edgeMonomial_act_fix l p.1 hp, + Pairing.act_edgeCoord, hpa, hpb] + rw [hact, Pairing.edgeMonomial_cons] + +lemma candidate_sum (z : V → C) (U : Finset V) (c : C × C) (M : Pairing V) + (hU : ∀ v, M.1 v ∈ U ↔ v ∈ U) : + ∑ e ∈ candidateEdges z U c, Pairing.edgeCoord e M = + ∑ v ∈ (Finset.univ \ U), if z v = c.1 ∧ z (M.1 v) = c.2 then (1:ℝ) else 0 := by + rw [candidateEdges, Finset.sum_filter] + change (∑ e : V × V, if e.1 ∉ U ∧ e.2 ∉ U ∧ e.1 ≠ e.2 ∧ + z e.1 = c.1 ∧ z e.2 = c.2 then Pairing.edgeCoord e M else 0) = _ + rw [Fintype.sum_prod_type, Finset.sum_sdiff_eq_sub (Finset.subset_univ U)] + have hpoint (v : V) : + (∑ w : V, if v ∉ U ∧ w ∉ U ∧ v ≠ w ∧ z v = c.1 ∧ z w = c.2 + then Pairing.edgeCoord (v,w) M else 0) = + if v ∉ U then (if z v = c.1 ∧ z (M.1 v) = c.2 then 1 else 0) else 0 := by + rw [Finset.sum_eq_single (M.1 v)] + · by_cases hv : v ∈ U <;> by_cases ha : z v = c.1 <;> + by_cases hb : z (M.1 v) = c.2 <;> + simp [Pairing.edgeCoord, hU v, (M.partner_ne v).symm, hv, ha, hb] + · intro w _ hw + simp [Pairing.edgeCoord, Ne.symm hw] + · simp + simp_rw [hpoint] + rw [← Finset.sum_filter] + have hfilter : Finset.univ.filter (fun v => v ∉ U) = Finset.univ \ U := by ext; simp + rw [hfilter, Finset.sum_sdiff_eq_sub (Finset.subset_univ U)] + +lemma monomial_candidate_identity (z : V → C) (l : List (V × V)) (c : C × C) + (M₀ : Pairing V) (h₀ : Pairing.ContainsList M₀ l) : + Pairing.edgeMonomial l * (∑ e ∈ candidateEdges z (Pairing.edgeSupport l) c, + Pairing.edgeCoord e) = + Pairing.edgeMonomial l * (tableCoordinate z c - + (∑ v ∈ Pairing.edgeSupport l, + if z v = c.1 ∧ z (M₀.1 v) = c.2 then (1:ℝ) else 0) • 1) := by + funext M + by_cases hm : Pairing.ContainsList M l + · simp only [Pi.mul_apply, Pairing.edgeMonomial_eq_indicator, ite_eq_left hm, one_mul, + Finset.sum_apply, Pi.sub_apply, Pi.smul_apply, Pi.one_apply, smul_eq_mul, mul_one] + rw [candidate_sum z (Pairing.edgeSupport l) c M (fun v => ⟨ + fun hv => by simpa using Pairing.contains_partner_support hm hv, + fun hv => Pairing.contains_partner_support hm hv⟩)] + rw [Finset.sum_sdiff_eq_sub (Finset.subset_univ _)] + unfold tableCoordinate + congr 1 + apply Finset.sum_congr rfl + intro v hv + rw [Pairing.contains_agree_support hm h₀ hv] + · simp [Pi.mul_apply, Pairing.edgeMonomial_eq_indicator, hm] + +end ColorCounting +end MatchingSmoothing + +end OAI diff --git a/lean/OAI/Combinatorics/MatchingPSD/PermutationSmoothing.lean b/lean/OAI/Combinatorics/MatchingPSD/PermutationSmoothing.lean new file mode 100644 index 0000000000000000000000000000000000000000..c24103d366ba0d2287dc65dcf40a528b821c3b19 --- /dev/null +++ b/lean/OAI/Combinatorics/MatchingPSD/PermutationSmoothing.lean @@ -0,0 +1,129 @@ +import OAI.Combinatorics.MatchingPSD.TablePolynomials + +namespace OAI + +universe u_1 u_2 u_3 u_4 u_5 u_6 u_7 u_8 u_9 + +namespace MatchingSmoothing +open scoped BigOperators +attribute [local instance] Classical.propDecidable + +section Averages +variable {X : Type u_1} {Y : Type u_2} [Fintype X] [Fintype Y] +lemma predicateAverage_equiv (e : X ≃ Y) (P : X → Prop) (Q : Y → Prop) + (he : ∀ x, P x ↔ Q (e x)) (f : Y → ℝ) : + predicateAverage P (f ∘ e) = predicateAverage Q f := by + classical + have hc : Fintype.card {x // P x} = Fintype.card {y // Q y} := + Fintype.card_congr (e.subtypeEquiv he) + rw [predicateAverage_apply, predicateAverage_apply, hc] + congr 1 + exact Fintype.sum_equiv e _ _ (fun x => by simp only [Function.comp_apply, he]) + +lemma predicateAverage_eq_expect (P : X → Prop) (f : X → ℝ) : + predicateAverage P f = 𝔼 x : {x // P x}, f x.1 := by + rw [predicateAverage_apply, Fintype.expect_eq_sum_div_card] + congr 1 + rw [← Finset.sum_filter] + exact Finset.sum_subtype (Finset.univ.filter P) (by simp) f + +end Averages + +noncomputable def lowProjection (h d : ℕ) : Module.End ℝ (Pairing (Vertices h) → ℝ) := + (matchingEquiv h).toLinearMap ∘ₗ (polynomialSpace h d).starProjection.toLinearMap ∘ₗ + (matchingEquiv h).symm.toLinearMap + +lemma lowProjection_mem (h d : ℕ) (f : Pairing (Vertices h) → ℝ) : + lowProjection h d f ∈ lowDegree Pairing.edgeCoord d := by + exact ((polynomialSpace h d).orthogonalProjectionOnto ((matchingEquiv h).symm f)).property + +lemma lowProjection_equivariant (h d : ℕ) (p : Equiv.Perm (Vertices h)) + (f : Pairing (Vertices h) → ℝ) : + lowProjection h d (Pairing.act p f) = Pairing.act p (lowProjection h d f) := by + have he := starProjection_equivariant (polynomialSpace h d) (relabelIso p) + (polynomialSpace_invariant p) (by simpa only [relabelIso_symm] using + (polynomialSpace_invariant (d := d) p⁻¹)) ((matchingEquiv h).symm f) + exact congrArg (matchingEquiv h) he.symm + +lemma predicateAverage_relabel {V : Type u_3} [Fintype V] [DecidableEq V] + (z : V → Fin 3) (t : Fin 6 → ℕ) (p : Equiv.Perm V) (f : Pairing V → ℝ) : + predicateAverage (fun M => M.table z = t) (fun M => f (Pairing.relabel p M)) = + predicateAverage (fun M => M.table (z ∘ p.symm) = t) f := by + apply predicateAverage_equiv (Pairing.relabelEquiv p) + intro M + change M.table z = t ↔ (Pairing.relabel p M).table (z ∘ p.symm) = t + rw [Pairing.table_relabel] + have hz : (z ∘ p.symm) ∘ p = z := by funext a; simp + rw [hz] + +lemma expect_perm_colorings {V : Type u_4} {C : Type u_5} [Fintype V] [DecidableEq V] + [Fintype C] [DecidableEq C] (z : V → C) (φ : (V → C) → ℝ) : + (𝔼 p : Equiv.Perm V, φ (z ∘ p)) = + 𝔼 w : Colorings V C (histogram z), φ w.1 := by + have : Nonempty (Colorings V C (histogram z)) := ⟨⟨z,rfl⟩⟩ + rw [Fintype.expect_eq_sum_div_card, Fintype.expect_eq_sum_div_card] + apply (div_eq_div_iff (Nat.cast_ne_zero.mpr Fintype.card_ne_zero) + (Nat.cast_ne_zero.mpr Fintype.card_ne_zero)).mpr + simpa only [mul_comm] using mean_perm_comp z φ + +noncomputable def tableEnergy {V : Type u_6} [Fintype V] (s : Fin 3 → ℕ) + (t : Fin 6 → ℕ) (f : Pairing V → ℝ) : ℝ := + 𝔼 z : Colorings V (Fin 3) s, (predicateAverage (fun M => M.table z.1 = t) f)^2 + +lemma fiberAverage_eq_predicateAverage {X : Type u_7} {Z : Type u_8} [Fintype X] [Fintype Z] + (P : X → Z → Prop) (f : X → ℝ) (z : Z) : + fiberAverage P f z = predicateAverage (fun x => P x z) f := by + simp only [fiberAverage, conditionalAverage, incidence, predicateAverage_apply, + ite_mul, one_mul, zero_mul] + +lemma fiberEnergy_eq {h : ℕ} (f₀ : Vertices h → Fin 3) + (f : Pairing (Vertices h) → ℝ) : + (∑ z, fiberAverage (tableRelation f₀) f z ^ 2) / + Fintype.card (Colorings (Vertices h) (Fin 3) (histogram f₀)) = + tableEnergy (histogram f₀) (threeTable f₀) f := by + simp_rw [fiberAverage_eq_predicateAverage] + rw [tableEnergy, Fintype.expect_eq_sum_div_card] + rfl + +lemma permutation_energy_eq {V : Type u_9} [Fintype V] [DecidableEq V] + (z : V → Fin 3) (t : Fin 6 → ℕ) (f : Pairing V → ℝ) : + (𝔼 p : Equiv.Perm V, (predicateAverage (fun M => M.table z = t) + (fun M => f (Pairing.relabel p M)))^2) = tableEnergy (histogram z) t f := by + simp_rw [predicateAverage_relabel] + calc + _ = 𝔼 p : Equiv.Perm V, + (predicateAverage (fun M => M.table (z ∘ p) = t) f)^2 := by + apply Fintype.expect_equiv (Equiv.inv (Equiv.Perm V)) + intro p + rfl + _ = _ := expect_perm_colorings z (fun w => + (predicateAverage (fun M => M.table w = t) f)^2) + +lemma uniform_permutation_smoothing (K : ℕ) : + ∃ d H : ℕ, 0 < d ∧ ∀ h : ℕ, H ≤ h → + ∀ (z : Vertices h → Fin 3), (∀ i, 0 < histogram z i) → + ∀ (M₀ : Pairing (Vertices h)) (f : Pairing (Vertices h) → ℝ), + (𝔼 p : Equiv.Perm (Vertices h), + (predicateAverage (fun M => M.table z = M₀.table z) + (fun M => (f - lowProjection h d f) (Pairing.relabel p M)))^2) ≤ + ((2*h : ℝ)^(2*K))⁻¹ * (𝔼 M, (f M)^2) := by + obtain ⟨d,H,hd,hbound⟩ := uniform_table_smoothing K + refine ⟨d,H,hd,?_⟩ + intro h hh z hz M₀ f + obtain ⟨p₀, hp₀⟩ := Pairing.exists_relabel (standardPairing (H := Fin h)) M₀ + let f₀ := z ∘ p₀ + have hhist : histogram f₀ = histogram z := histogram_comp_perm z p₀ + have ht : threeTable f₀ = M₀.table z := by + rw [← hp₀, Pairing.table_relabel, standardPairing_table] + have hb := hbound h hh f₀ (by simpa only [hhist] using hz) ((matchingEquiv h).symm f) + have heg : matchingEquiv h ((matchingEquiv h).symm f - + polynomialProjection h d ((matchingEquiv h).symm f)) = f - lowProjection h d f := by + simp only [map_sub, LinearEquiv.apply_symm_apply] + rfl + rw [fiberEnergy_eq, heg, ht, hhist] at hb + rw [permutation_energy_eq, Fintype.expect_eq_sum_div_card] + exact hb + +end MatchingSmoothing + +end OAI diff --git a/lean/OAI/Combinatorics/MatchingPSD/PolynomialInterpolation.lean b/lean/OAI/Combinatorics/MatchingPSD/PolynomialInterpolation.lean new file mode 100644 index 0000000000000000000000000000000000000000..67ba3bfe876836c137960c9322c9bb52e69a3f26 --- /dev/null +++ b/lean/OAI/Combinatorics/MatchingPSD/PolynomialInterpolation.lean @@ -0,0 +1,212 @@ +import OAI.Combinatorics.MatchingPSD.MatrixAverages + +namespace OAI + +namespace MatchingInterpolation +open Polynomial +open MatchingSmoothing + +abbrev Point := Fin 3 → ℝ +abbrev GridIndex (d : ℕ) := Fin 3 → Fin (d+1) +def coord (i : Fin 3) (x : Point) : ℝ := x i +noncomputable def lagrange (d : ℕ) (k : Fin (d+1)) : ℝ[X] := + Lagrange.basis Finset.univ (fun j : Fin (d+1) => (j:ℝ)) k +noncomputable def tensorBasis (d : ℕ) (g : GridIndex d) (x : Point) : ℝ := + ∏ a, (lagrange d (g a)).eval (x a) +def gridNode {d : ℕ} (g : GridIndex d) : Point := fun a => (g a:ℝ) + +lemma power_interpolation (d k : ℕ) (hk : k ≤ d) (x : ℝ) : + x^k = ∑ j : Fin (d+1), (j:ℝ)^k * (lagrange d j).eval x := by + have hinj : Set.InjOn (fun j : Fin (d+1) => (j:ℝ)) (Finset.univ : Finset (Fin (d+1))) := by + intro i _ j _ h + apply Fin.ext + change (i.val:ℝ) = (j.val:ℝ) at h + exact Nat.cast_inj.mp h + have hdeg : (Polynomial.X^k : ℝ[X]).degree < (Finset.univ : Finset (Fin (d+1))).card := by + simp only [Polynomial.degree_X_pow, Finset.card_univ, Fintype.card_fin] + exact_mod_cast Nat.lt_succ_of_le hk + have he := congrArg (Polynomial.eval x) (Lagrange.eq_interpolate hinj hdeg) + simpa [Lagrange.interpolate_apply, lagrange, Polynomial.eval_finsetSum] using he + +lemma list_product_counts (l : List (Fin 3)) (x : Point) : + (l.map x).prod = ∏ a, x a ^ l.count a := by + rw [Finset.prod_list_map_count] + apply Finset.prod_subset (Finset.subset_univ _) + intro a _ ha + have hn : a ∉ l := fun hx => ha (List.mem_toFinset.mpr hx) + simp [List.count_eq_zero_of_not_mem hn] + +lemma monomial_interpolation (d : ℕ) (l : List (Fin 3)) (hl : l.length ≤ d) (x : Point) : + (l.map x).prod = ∑ g : GridIndex d, tensorBasis d g x * (l.map (gridNode g)).prod := by + rw [list_product_counts] + have hp (a : Fin 3) := power_interpolation d (l.count a) + (List.count_le_length.trans hl) (x a) + simp_rw [hp] + rw [Fintype.prod_sum] + apply Finset.sum_congr rfl + intro g _ + rw [Finset.prod_mul_distrib, list_product_counts, mul_comm] + rfl + +lemma lowDegree_interpolation (d : ℕ) (P : Point → ℝ) (hP : P ∈ lowDegree coord d) + (x : Point) : P x = ∑ g : GridIndex d, tensorBasis d g x * P (gridNode g) := by + induction hP using Submodule.span_induction with + | mem P hP => + obtain ⟨l, hl, rfl⟩ := hP + have he (v : Point) : (l.map coord).prod v = (l.map v).prod := by + induction l with + | nil => rfl + | cons a l ih => simpa [coord] using congrArg (fun t => v a*t) (ih (by simpa only [List.length_cons] using Nat.le_trans (Nat.le_succ l.length) hl)) + simp_rw [he] + exact monomial_interpolation d l hl x + | zero => simp + | add f g _ _ hf hg => simp only [Pi.add_apply, mul_add, Finset.sum_add_distrib, hf, hg] + | smul c f _ hf => + simp only [Pi.smul_apply, smul_eq_mul, ← mul_assoc, mul_comm _ c, Finset.mul_sum, hf] + +noncomputable def linePolynomial (d : ℕ) (g : GridIndex d) (v : Point) : ℝ[X] := + ∏ a, (lagrange d (g a)).comp (Polynomial.C (v a) * Polynomial.X) + +lemma linePolynomial_eval (d : ℕ) (g : GridIndex d) (v : Point) (t : ℝ) : + (linePolynomial d g v).eval t = tensorBasis d g (fun a => t * v a) := by + simp only [linePolynomial, tensorBasis, Polynomial.eval_prod, Polynomial.eval_comp, + Polynomial.eval_mul, Polynomial.eval_C, Polynomial.eval_X] + apply Finset.prod_congr rfl + intro a _ + rw [mul_comm] + +lemma linePolynomial_zero (d : ℕ) (g : GridIndex d) (v : Point) : + (linePolynomial d g v).coeff 0 = ∏ a, (lagrange d (g a)).eval 0 := by + rw [Polynomial.coeff_zero_eq_eval_zero, linePolynomial_eval] + simp [tensorBasis] + +lemma linePolynomial_one (d : ℕ) (g : GridIndex d) (v : Point) : + (linePolynomial d g v).coeff 1 = + ∑ a, v a * ((∏ b ∈ Finset.univ.erase a, (lagrange d (g b)).eval 0) * + (lagrange d (g a)).derivative.eval 0) := by + have he (P : ℝ[X]) : P.coeff 1 = P.derivative.eval 0 := by + simp [← Polynomial.coeff_zero_eq_eval_zero, Polynomial.coeff_derivative] + rw [he, linePolynomial, Polynomial.derivative_prod_finset, Polynomial.eval_finsetSum] + apply Finset.sum_congr rfl + intro a _ + simp only [Polynomial.derivative_comp, Polynomial.derivative_mul, Polynomial.derivative_C, + Polynomial.derivative_X, zero_mul, mul_one, zero_add, Polynomial.eval_mul, + Polynomial.eval_comp, Polynomial.eval_prod, Polynomial.eval_C, Polynomial.eval_X, + mul_zero] + ring + +def origin : Point := ![1,0,0] +def dirA : Point := ![0,2,0] +def dirB : Point := ![0,0,2] +def dirStar : Point := ![2,0,0] +def dirP : Point := ![-1,1,1] +noncomputable def weightPolynomial (d : ℕ) (g : GridIndex d) : ℝ[X] := + linePolynomial d g dirA + linePolynomial d g dirB - linePolynomial d g dirStar - + (2:ℝ) • linePolynomial d g dirP + linePolynomial d g 0 + +lemma weightPolynomial_zero (d : ℕ) (g : GridIndex d) : + (weightPolynomial d g).coeff 0 = 0 := by + simp only [weightPolynomial, Polynomial.coeff_add, Polynomial.coeff_sub, + Polynomial.coeff_smul, smul_eq_mul, linePolynomial_zero] + ring + +lemma weightPolynomial_one (d : ℕ) (g : GridIndex d) : + (weightPolynomial d g).coeff 1 = 0 := by + simp only [weightPolynomial, Polynomial.coeff_add, Polynomial.coeff_sub, + Polynomial.coeff_smul, smul_eq_mul, linePolynomial_one, Pi.zero_apply, zero_mul, + Finset.sum_const_zero, add_zero] + rw [← Finset.sum_add_distrib, ← Finset.sum_sub_distrib, Finset.mul_sum, + ← Finset.sum_sub_distrib] + apply Finset.sum_eq_zero + intro a _ + fin_cases a <;> simp [dirA, dirB, dirStar, dirP] + +lemma weightPolynomial_bound (d : ℕ) (g : GridIndex d) : + ∃ c : ℝ, 0 ≤ c ∧ ∀ t ∈ Set.Icc (0:ℝ) 1, + |(weightPolynomial d g).eval t| ≤ c * t^2 := by + have hd : (Polynomial.X^2 : ℝ[X]) ∣ weightPolynomial d g := by + apply Polynomial.X_pow_dvd_iff.mpr + intro k hk + interval_cases k + · exact weightPolynomial_zero d g + · exact weightPolynomial_one d g + obtain ⟨P, hP⟩ := hd + obtain ⟨b, hb⟩ := (isCompact_Icc : IsCompact (Set.Icc (0:ℝ) 1)).exists_bound_of_continuousOn + P.continuous.continuousOn + refine ⟨max b 0, le_max_right _ _, ?_⟩ + intro t ht + rw [hP, Polynomial.eval_mul, Polynomial.eval_pow, Polynomial.eval_X, abs_mul, + abs_of_nonneg (sq_nonneg t), mul_comm] + have htbound : |P.eval t| ≤ b := by simpa only [Real.norm_eq_abs] using hb t ht + exact mul_le_mul_of_nonneg_right (htbound.trans (le_max_left b 0)) (sq_nonneg t) + +noncomputable def weight (d : ℕ) (L : ℝ) (g : GridIndex d) : ℝ := + (weightPolynomial d g).eval L⁻¹ + +lemma weights_bound (d : ℕ) : ∃ c : ℝ, 0 < c ∧ ∀ L : ℝ, 1 ≤ L → + ∀ g : GridIndex d, |weight d L g| ≤ c / L^2 := by + classical + choose c hc hb using weightPolynomial_bound d + refine ⟨1 + ∑ g, c g, by have hsum := Finset.sum_nonneg (fun g (_ : g ∈ Finset.univ) => hc g); linarith, ?_⟩ + intro L hL g + have hLp : 0 < L := lt_of_lt_of_le zero_lt_one hL + have ht : L⁻¹ ∈ Set.Icc (0:ℝ) 1 := ⟨inv_nonneg.mpr hLp.le, + (inv_le_one₀ hLp).mpr hL⟩ + calc + |weight d L g| ≤ c g * (L⁻¹)^2 := hb g L⁻¹ ht + _ ≤ (1+∑ a, c a) * (L⁻¹)^2 := by + apply mul_le_mul_of_nonneg_right _ (sq_nonneg _) + have hh := Finset.single_le_sum (fun a (_ : a ∈ Finset.univ) => hc a) + (Finset.mem_univ g) + linarith + _ = (1+∑ a, c a)/L^2 := by simp [div_eq_mul_inv] + +lemma lowDegree_affine_pullback (d : ℕ) (P : Point → ℝ) + (hP : P ∈ lowDegree coord d) (b : Point) (L : ℝ) : + (fun x : Point => P (fun a => b a + L*x a)) ∈ lowDegree coord d := by + have hcoord (a : Fin 3) : (fun x : Point => b a + L*x a) ∈ lowDegree coord 1 := by + have hc := (lowDegree coord 1).smul_mem (b a) (one_mem_lowDegree coord 1) + have hx := (lowDegree coord 1).smul_mem L (coord_mem_lowDegree coord a) + convert (lowDegree coord 1).add_mem hc hx using 1 + ext x + simp [coord] + induction hP using Submodule.span_induction with + | mem P hP => + obtain ⟨l, hl, rfl⟩ := hP + apply lowDegree_mono coord hl + clear hl + induction l with + | nil => exact one_mem_lowDegree coord 0 + | cons a l ih => + convert mul_mem_lowDegree coord (hcoord a) ih using 1 + · simp only [List.length_cons, Nat.add_comm] + · rfl + | zero => exact (lowDegree coord d).zero_mem + | add f g _ _ hf hg => exact (lowDegree coord d).add_mem hf hg + | smul c f _ hf => exact (lowDegree coord d).smul_mem c hf + +lemma weighted_interpolation (d : ℕ) (P : Point → ℝ) (hP : P ∈ lowDegree coord d) + (L : ℝ) (hL : L ≠ 0) : + P (origin + dirA) + P (origin + dirB) - P (origin + dirStar) - + 2 * P (origin + dirP) + P origin = + ∑ g : GridIndex d, weight d L g * P (fun a => origin a + L*(g a:ℝ)) := by + let Q : Point → ℝ := fun x => P (fun a => origin a + L*x a) + have hQ : Q ∈ lowDegree coord d := lowDegree_affine_pullback d P hP origin L + have he (v : Point) : P (origin + v) = + ∑ g : GridIndex d, (linePolynomial d g v).eval L⁻¹ * + P (fun a => origin a + L*(g a:ℝ)) := by + have hi := lowDegree_interpolation d Q hQ (fun a => L⁻¹*v a) + have hx : (fun a => origin a + L*(L⁻¹*v a)) = origin + v := by + funext a + simp [hL] + simpa only [Q, hx, ← linePolynomial_eval, gridNode] using hi + have he0 := he 0 + rw [add_zero] at he0 + rw [he dirA, he dirB, he dirStar, he dirP, he0] + simp only [weight, weightPolynomial, Polynomial.eval_add, Polynomial.eval_sub, + Polynomial.eval_smul, smul_eq_mul, Finset.sum_add_distrib, Finset.sum_sub_distrib, + add_mul, sub_mul, mul_assoc, ← Finset.mul_sum] + +end MatchingInterpolation + +end OAI diff --git a/lean/OAI/Combinatorics/MatchingPSD/PolynomialSpaces.lean b/lean/OAI/Combinatorics/MatchingPSD/PolynomialSpaces.lean new file mode 100644 index 0000000000000000000000000000000000000000..06c38b99635aa09a997fb52f34f3d90c276b4722 --- /dev/null +++ b/lean/OAI/Combinatorics/MatchingPSD/PolynomialSpaces.lean @@ -0,0 +1,122 @@ +import OAI.Combinatorics.MatchingPSD.EquivariantCompression + +namespace OAI + +namespace MatchingSmoothing +open scoped RealInnerProductSpace + +abbrev MatchingSpace (h : ℕ) := EuclideanSpace ℝ (Pairing (Vertices h)) + +noncomputable def matchingEquiv (h : ℕ) : + MatchingSpace h ≃ₗ[ℝ] (Pairing (Vertices h) → ℝ) := + WithLp.linearEquiv 2 ℝ _ + +noncomputable def polynomialSpace (h d : ℕ) : Submodule ℝ (MatchingSpace h) := + (lowDegree Pairing.edgeCoord d).comap (matchingEquiv h).toLinearMap + +noncomputable def relabelIso {h : ℕ} (p : Equiv.Perm (Vertices h)) : + MatchingSpace h ≃ₗᵢ[ℝ] MatchingSpace h := permIso (Pairing.relabelEquiv p) + +lemma matchingEquiv_relabel {h : ℕ} (p : Equiv.Perm (Vertices h)) (f : MatchingSpace h) : + matchingEquiv h (relabelIso p f) = Pairing.act p (matchingEquiv h f) := rfl + +lemma relabelIso_symm {h : ℕ} (p : Equiv.Perm (Vertices h)) : + (relabelIso p).symm = relabelIso p⁻¹ := by + simp only [relabelIso, permIso, LinearIsometryEquiv.piLpCongrLeft_symm] + congr 1 + +lemma polynomialSpace_invariant {h d : ℕ} (p : Equiv.Perm (Vertices h)) + (f : MatchingSpace h) (hf : f ∈ polynomialSpace h d) : + relabelIso p f ∈ polynomialSpace h d := + Pairing.lowDegree_invariant p d _ hf + +lemma highSpace_invariant {h d : ℕ} (p : Equiv.Perm (Vertices h)) + (f : MatchingSpace h) (hf : f ∈ (polynomialSpace h d)ᗮ) : + relabelIso p f ∈ (polynomialSpace h d)ᗮ := by + apply invariant_orthogonal (polynomialSpace h d) (relabelIso p) _ f hf + intro x hx + rw [relabelIso_symm] + exact polynomialSpace_invariant p⁻¹ x hx + +lemma euclidean_high_degree_dimension {h : ℕ} (k : ℕ) (hk : 4*k < h) + (W : Submodule ℝ (MatchingSpace h)) + (hW : ∀ p f, f ∈ W → relabelIso p f ∈ W) + (hle : W ≤ (polynomialSpace h ((4*k)*(4*k)))ᗮ) + (hne : ∃ f ∈ W, f ≠ 0) : h.choose k ≤ Module.finrank ℝ W := by + let l := matchingEquiv h + have he := invariant_high_degree_dimension k hk (W.map l.toLinearMap) + have hinv (p : Equiv.Perm (Vertices h)) (f : Pairing (Vertices h) → ℝ) + (hf : f ∈ W.map l.toLinearMap) : Pairing.act p f ∈ W.map l.toLinearMap := by + rcases hf with ⟨x, hx, rfl⟩ + exact ⟨relabelIso p x, hW p x hx, matchingEquiv_relabel p x⟩ + have hdis : Disjoint (W.map l.toLinearMap) + (lowDegree Pairing.edgeCoord ((4*k)*(4*k))) := by + rw [Submodule.disjoint_def] + rintro f ⟨x, hx, rfl⟩ hp + have hp' : x ∈ polynomialSpace h ((4*k)*(4*k)) := hp + have hx0 := Submodule.disjoint_def.mp + (polynomialSpace h ((4*k)*(4*k))).orthogonal_disjoint.symm x (hle hx) hp' + rw [hx0, map_zero] + have hn : ∃ f ∈ W.map l.toLinearMap, f ≠ 0 := by + obtain ⟨x, hx, hx0⟩ := hne + refine ⟨l x, ⟨x, hx, rfl⟩, ?_⟩ + simpa using hx0 + simpa only [LinearEquiv.finrank_map_eq] using he hinv hdis hn + +lemma matching_compression_multiplicity {h : ℕ} (k : ℕ) (hk : 4*k < h) + (A : Module.End ℝ (MatchingSpace h)) + (hA : ∀ p x, A (relabelIso p x) = relabelIso p (A x)) + (c : ℝ) (hc : Module.End.HasEigenvalue + (compression A (polynomialSpace h ((4*k)*(4*k)))ᗮ) c) : + h.choose k ≤ Module.finrank ℝ (Module.End.eigenspace + (compression A (polynomialSpace h ((4*k)*(4*k)))ᗮ) c) := by + let W := (polynomialSpace h ((4*k)*(4*k)))ᗮ + let U := (Module.End.eigenspace (compression A W) c).map W.subtype + have hinv : ∀ p x, x ∈ U → relabelIso p x ∈ U := by + intro p x hx + apply compression_eigenspace_invariant A W (relabelIso p) + (highSpace_invariant p) _ (hA p) c x hx + intro y hy + rw [relabelIso_symm] + exact highSpace_invariant p⁻¹ y hy + have hle : U ≤ W := by + rintro x ⟨x, _, rfl⟩ + exact x.2 + have hne : ∃ x ∈ U, x ≠ 0 := by + obtain ⟨x, hx, hx0⟩ := hc.exists_hasEigenvector + refine ⟨x, ⟨x, hx, rfl⟩, ?_⟩ + intro he + exact hx0 (Subtype.ext he) + have hd := euclidean_high_degree_dimension k hk U hinv hle hne + simpa only [U, Submodule.finrank_map_subtype_eq] using hd + +lemma symmetric_matching_smoothing {h : ℕ} (k : ℕ) (hk : 4*k < h) + (A : Matrix (Pairing (Vertices h)) (Pairing (Vertices h)) ℝ) + (hA : A.IsHermitian) + (heq : ∀ p M N, A (Pairing.relabel p M) (Pairing.relabel p N) = A M N) + (H a : ℝ) (ha : 0 ≤ a) + (htrace : Matrix.trace (A * A) ≤ H) + (hHa : H ≤ (h.choose k : ℝ) * a ^ 2) + (f : MatchingSpace h) (hf : f ∈ (polynomialSpace h ((4*k)*(4*k)))ᗮ) : + ⟪f, A.toEuclideanLin f⟫ ≤ a * ‖f‖ ^ 2 := by + classical + let W := (polynomialSpace h ((4*k)*(4*k)))ᗮ + have hm : (0 : ℝ) < h.choose k := Nat.cast_pos.mpr (Nat.choose_pos (by omega)) + have hs : A.toEuclideanLin.IsSymmetric := Matrix.isSymmetric_toEuclideanLin_iff.mpr hA + have hd (c : ℝ) (_hc : c ≠ 0) + (he : Module.End.HasEigenvalue (compression A.toEuclideanLin W) c) : + (h.choose k : ℝ) ≤ Module.finrank ℝ + (Module.End.eigenspace (compression A.toEuclideanLin W) c) := by + exact_mod_cast matching_compression_multiplicity k hk A.toEuclideanLin + (fun p x => matrix_equivariant A (Pairing.relabelEquiv p) (heq p) x) c he + have ht : LinearMap.trace ℝ W (compression A.toEuclideanLin W * + compression A.toEuclideanLin W) ≤ H := by + apply (trace_square_compression_le A.toEuclideanLin hs W).trans + rwa [matrix_trace_square] + have hh := quadratic_form_le_of_multiplicity (compression A.toEuclideanLin W) + (compression_symmetric A.toEuclideanLin hs W) (h.choose k) H a hm ha hd ht hHa ⟨f, hf⟩ + simpa only [compression_inner, ← Submodule.norm_coe] using hh + +end MatchingSmoothing + +end OAI diff --git a/lean/OAI/Combinatorics/MatchingPSD/RepresentationDimension.lean b/lean/OAI/Combinatorics/MatchingPSD/RepresentationDimension.lean new file mode 100644 index 0000000000000000000000000000000000000000..7064241ca81bde733091b383d8ad9d50960006e1 --- /dev/null +++ b/lean/OAI/Combinatorics/MatchingPSD/RepresentationDimension.lean @@ -0,0 +1,255 @@ +import OAI.Combinatorics.MatchingPSD.Pairings + +namespace OAI + +universe u_1 + +namespace MatchingSmoothing +section StandardPairs + +abbrev Vertices (h : ℕ) := Fin h × Bool + +variable {h : ℕ} + +def firstVertices (h t : ℕ) : Finset (Vertices h) := + (Finset.univ.filter fun i : Fin h => i.val < t) ×ˢ Finset.univ + +@[simp] lemma mem_firstVertices (t : ℕ) (v : Vertices h) : + v ∈ firstVertices h t ↔ v.1.val < t := by simp [firstVertices] + +lemma card_firstVertices {t : ℕ} (ht : t ≤ h) : + (firstVertices h t).card = 2 * t := by + simp [firstVertices, Fin.card_filter_val_lt, min_eq_right ht, Nat.mul_comm] + +def pairSwap (i : Fin h) : Equiv.Perm (Vertices h) := + Equiv.swap (i, false) (i, true) + +lemma pairSwap_commute (i j : Fin h) : Commute (pairSwap i) (pairSwap j) := by + by_cases hij : i = j + · subst j; exact Commute.refl _ + · change Equiv.swap (i,false) (i,true) * Equiv.swap (j,false) (j,true) = + Equiv.swap (j,false) (j,true) * Equiv.swap (i,false) (i,true) + rw [Equiv.mul_swap_eq_swap_mul] + simp [Equiv.swap_apply_def, Ne.symm hij] + +lemma act_pairSwap_commute (i j : Fin h) : + Commute (Pairing.act (pairSwap i)).toLinearMap (Pairing.act (pairSwap j)).toLinearMap := by + apply LinearMap.ext + intro f + change Pairing.act (pairSwap i) (Pairing.act (pairSwap j) f) = _ + rw [← Pairing.act_mul, (pairSwap_commute i j).eq, Pairing.act_mul] + rfl + +lemma pairSwap_fixed_outside {i : Fin h} {a b : Vertices h} + (ha : a.1 ≠ i) (hb : b.1 ≠ i) : + Equiv.swap a b (i,false) = (i,false) ∧ Equiv.swap a b (i,true) = (i,true) := by + simp [Equiv.swap_apply_def, Prod.ext_iff, Ne.symm ha, Ne.symm hb] + +lemma eigen_weighted_projection {V : Type u_1} [AddCommGroup V] [Module ℝ V] + (A : Module.End ℝ V) (hinv : ∀ v, A (A v) = v) + (c : ℝ) (hc : c = 1 ∨ c = -1) (v : V) : + A (v + c • A v) = c • (v + c • A v) := by + rcases hc with rfl | rfl + · simp [hinv, add_comm] + · simp [hinv, add_comm] + +lemma next_prescribed_sign (W : Submodule ℝ (Pairing (Vertices h) → ℝ)) + (hW : ∀ p f, f ∈ W → Pairing.act p f ∈ W) + {t : ℕ} (ht : t < h) (χ : Fin h → ℝ) (c : ℝ) (hc : c = 1 ∨ c = -1) + (f : Pairing (Vertices h) → ℝ) (hf : f ∈ W) + (heig : ∀ i : Fin h, i.val < t → Pairing.act (pairSwap i) f = χ i • f) + (hex : ∃ a, a ∉ firstVertices h t ∧ ∃ b, b ∉ firstVertices h t ∧ a ≠ b ∧ + f + c • Pairing.act (Equiv.swap a b) f ≠ 0) : + ∃ g ∈ W, g ≠ 0 ∧ Pairing.act (pairSwap ⟨t, ht⟩) g = c • g ∧ + ∀ i : Fin h, i.val < t → Pairing.act (pairSwap i) g = χ i • g := by + obtain ⟨a, ha, b, hb, hab, h0⟩ := hex + let i : Fin h := ⟨t, ht⟩ + obtain ⟨p, hp, hpa, hpb⟩ := Pairing.exists_perm_fixing_pair (firstVertices h t) + ha hb (c := (i,false)) (d := (i,true)) (by simp [i]) (by simp [i]) hab (by simp) + let v := f + c • Pairing.act (Equiv.swap a b) f + have hv : v ∈ W := W.add_mem hf (W.smul_mem c (hW _ _ hf)) + refine ⟨Pairing.act p v, hW _ _ hv, ?_, ?_, ?_⟩ + · intro hz + apply h0 + change v = 0 + exact (Pairing.act p).injective (hz.trans (map_zero _).symm) + · change Pairing.act (Equiv.swap (i,false) (i,true)) (Pairing.act p v) = _ + rw [← hpa, ← hpb, Pairing.act_swap_conj] + have hvsign := eigen_weighted_projection (Pairing.act (Equiv.swap a b)).toLinearMap + (Pairing.act_swap_involution a b) c hc f + change Pairing.act (Equiv.swap a b) v = c • v at hvsign + rw [hvsign, map_smul] + · intro j hj + have hpj (b : Bool) : p (j,b) = (j,b) := hp _ (by simpa using hj) + change Pairing.act (Equiv.swap (j,false) (j,true)) (Pairing.act p v) = _ + rw [Pairing.act_commute_of_swap_fixed p _ _ (hpj false) (hpj true)] + have haj : a.1 ≠ j := by + intro he + apply ha + simpa only [mem_firstVertices, he] using hj + have hbj : b.1 ≠ j := by + intro he + apply hb + simpa only [mem_firstVertices, he] using hj + obtain ⟨hfix₁, hfix₂⟩ := pairSwap_fixed_outside haj hbj + have hpast : Pairing.act (pairSwap j) v = χ j • v := by + change Pairing.act (Equiv.swap (j,false) (j,true)) + (f + c • Pairing.act (Equiv.swap a b) f) = _ + rw [map_add, map_smul, Pairing.act_commute_of_swap_fixed _ _ _ hfix₁ hfix₂] + change Pairing.act (pairSwap j) f + + c • Pairing.act (Equiv.swap a b) (Pairing.act (pairSwap j) f) = _ + rw [heig j hj, map_smul] + change χ j • f + c • (χ j • Pairing.act (Equiv.swap a b) f) = + χ j • (f + c • Pairing.act (Equiv.swap a b) f) + rw [smul_add, smul_comm c (χ j)] + change Pairing.act p (Pairing.act (pairSwap j) v) = _ + rw [hpast, map_smul] + +lemma exists_negative_projection {α : Type u_1} [Fintype α] [DecidableEq α] + (U : Finset α) (f : Pairing α → ℝ) + (hf : f ∉ lowDegree Pairing.edgeCoord (U.card * U.card)) : + ∃ a, a ∉ U ∧ ∃ b, b ∉ U ∧ a ≠ b ∧ f + (-1 : ℝ) • Pairing.act (Equiv.swap a b) f ≠ 0 := by + by_contra! hall + apply hf + apply Pairing.mem_lowDegree_of_swap_invariant U f + intro a ha b hb hab + have he := hall a ha b hb hab + have hz : f - Pairing.act (Equiv.swap a b) f = 0 := by + simpa only [neg_smul, one_smul, sub_eq_add_neg] using he + exact (sub_eq_zero.mp hz).symm + +lemma exists_positive_projection {α : Type u_1} [Fintype α] [DecidableEq α] + (U : Finset α) (hU : 2 * U.card < Fintype.card α) + (f : Pairing α → ℝ) (hf : f ≠ 0) : + ∃ a, a ∉ U ∧ ∃ b, b ∉ U ∧ a ≠ b ∧ f + (1 : ℝ) • Pairing.act (Equiv.swap a b) f ≠ 0 := by + by_contra! hall + apply hf + apply Pairing.no_sign_on_complement U hU f + intro a ha b hb hab + have he := hall a ha b hb hab + exact eq_neg_of_add_eq_zero_left (by simpa only [one_smul, add_comm] using he) + +lemma prescribed_sign_vector (k : ℕ) (hk : 4 * k < h) + (W : Submodule ℝ (Pairing (Vertices h) → ℝ)) + (hW : ∀ p f, f ∈ W → Pairing.act p f ∈ W) + (hdis : Disjoint W (lowDegree Pairing.edgeCoord ((4 * k) * (4 * k)))) + (hne : ∃ f ∈ W, f ≠ 0) : + ∃ f ∈ W, f ≠ 0 ∧ ∀ i : Fin h, i.val < 2 * k → + Pairing.act (pairSwap i) f = (if i.val < k then (-1 : ℝ) else 1) • f := by + let χ (i : Fin h) : ℝ := if i.val < k then -1 else 1 + have hind : ∀ t : ℕ, t ≤ 2 * k → ∃ f ∈ W, f ≠ 0 ∧ + ∀ i : Fin h, i.val < t → Pairing.act (pairSwap i) f = χ i • f := by + intro t + induction t with + | zero => + intro _ + obtain ⟨f, hf, hf0⟩ := hne + exact ⟨f, hf, hf0, by simp⟩ + | succ t ih => + intro ht + obtain ⟨f, hf, hf0, he⟩ := ih (by omega) + have hth : t < h := by omega + let c : ℝ := if t < k then -1 else 1 + have hc : c = 1 ∨ c = -1 := by dsimp [c]; split_ifs <;> simp + have hex : ∃ a, a ∉ firstVertices h t ∧ ∃ b, b ∉ firstVertices h t ∧ a ≠ b ∧ + f + c • Pairing.act (Equiv.swap a b) f ≠ 0 := by + by_cases htk : t < k + · dsimp [c]; rw [ite_eq_left htk] + apply exists_negative_projection + intro hlow + have hd : (firstVertices h t).card * (firstVertices h t).card ≤ (4*k) * (4*k) := by + rw [card_firstVertices hth.le] + apply Nat.mul_self_le_mul_self + omega + exact hf0 ((Submodule.disjoint_def.mp hdis) f hf (lowDegree_mono _ hd hlow)) + · dsimp [c]; rw [ite_eq_right htk] + apply exists_positive_projection _ _ f hf0 + rw [card_firstVertices hth.le] + simp only [Vertices, Fintype.card_prod, Fintype.card_fin, Fintype.card_bool] + omega + obtain ⟨g, hg, hg0, hnew, hold⟩ := next_prescribed_sign W hW hth χ c hc f hf he hex + refine ⟨g, hg, hg0, ?_⟩ + intro i hi + by_cases hit : i.val < t + · exact hold i hit + · have hie : i = ⟨t, hth⟩ := Fin.ext (by change i.val = t; omega) + subst i + exact hnew + exact hind (2*k) le_rfl + +lemma choose_le_choose_of_le_of_le_compl {n k w : ℕ} + (hkw : k ≤ w) (hw : w ≤ n - k) : n.choose k ≤ n.choose w := by + have hmon : ∀ a b : ℕ, a ≤ b → b ≤ n / 2 → n.choose a ≤ n.choose b := by + intro a b hab + induction b, hab using Nat.le_induction with + | base => intro _; rfl + | succ b hab ih => + intro hb + exact (ih (by omega)).trans (Nat.choose_le_succ_of_lt_half_left (by omega)) + by_cases hhalf : w ≤ n / 2 + · exact hmon k w hkw hhalf + · have hwn : w ≤ n := hw.trans (Nat.sub_le _ _) + rw [← Nat.choose_symm hwn] + apply hmon k (n-w) <;> omega + +lemma invariant_high_degree_dimension (k : ℕ) (hk : 4 * k < h) + (W : Submodule ℝ (Pairing (Vertices h) → ℝ)) + (hW : ∀ p f, f ∈ W → Pairing.act p f ∈ W) + (hdis : Disjoint W (lowDegree Pairing.edgeCoord ((4 * k) * (4 * k)))) + (hne : ∃ f ∈ W, f ≠ 0) : h.choose k ≤ Module.finrank ℝ W := by + classical + obtain ⟨v, hv, hv0, he⟩ := prescribed_sign_vector k hk W hW hdis hne + let A (i : Fin h) := (Pairing.act (pairSwap i)).toLinearMap + let s₀ := Finset.univ.filter fun i : Fin h => i.val < 2*k + obtain ⟨ψ, w, hw, hw0, hew, hp⟩ := simultaneous_sign_eigenvector_preserving A + act_pairSwap_commute (fun i => Pairing.act_swap_involution (i,false) (i,true)) + W (fun i => hW (pairSwap i)) s₀ (fun i => if i.val < k then -1 else 1) + v hv hv0 (by simpa [A, s₀] using he) + have hpres (i : Fin h) (hi : i.val < 2*k) : ψ i = if i.val < k then -1 else 1 := + hp i (by simpa only [s₀, Finset.mem_filter, Finset.mem_univ, true_and] using hi) + let s := Finset.univ.filter fun i => ψ i = -1 + have hlow : k ≤ s.card := by + let e (i : Fin k) : s := ⟨⟨i.val, by omega⟩, by + simp only [s, Finset.mem_filter, Finset.mem_univ, true_and] + rw [hpres _ (by dsimp; omega)] + exact ite_eq_left i.isLt⟩ + have hinj : Function.Injective e := by + intro i j hij + exact Fin.ext (congrArg (fun x : s => x.1.val) hij) + simpa only [Fintype.card_fin, Fintype.card_coe] using Fintype.card_le_of_injective e hinj + have hhigh : k ≤ sᶜ.card := by + let e (i : Fin k) : ↥(sᶜ) := ⟨⟨k+i.val, by omega⟩, by + simp only [Finset.mem_compl, s, Finset.mem_filter, Finset.mem_univ, true_and] + rw [hpres _ (by dsimp; omega), ite_eq_right (by dsimp; omega)] + norm_num⟩ + have hinj : Function.Injective e := by + intro i j hij + have heq := congrArg (fun x : ↥(sᶜ) => x.1.val) hij + apply Fin.ext + dsimp [e] at heq + omega + simpa only [Fintype.card_fin, Fintype.card_coe] using Fintype.card_le_of_injective e hinj + have hsc : s.card ≤ h := Finset.card_le_univ s |>.trans_eq (Fintype.card_fin h) + rw [Finset.card_compl, Fintype.card_fin] at hhigh + have hchoose := choose_le_choose_of_le_of_le_compl hlow (by omega : s.card ≤ h-k) + apply hchoose.trans + let P (p : Equiv.Perm (Fin h)) := Pairing.act (Equiv.prodCongr p (Equiv.refl Bool)) + have hconj (p : Equiv.Perm (Fin h)) (i : Fin h) (f : Pairing (Vertices h) → ℝ) : + A (p i) (P p f) = P p (A i f) := + Pairing.act_swap_conj (Equiv.prodCongr p (Equiv.refl Bool)) (i,false) (i,true) f + have hsigne (i : Fin h) : A i w = (if i ∈ s then (-1 : ℝ) else 1) • w := by + have hi := hew i + rw [hi.2] + congr 1 + by_cases his : ψ i = -1 + · simp [s, his] + · have hie : ψ i = 1 := hi.1.resolve_right his + simp [s, hie] + simpa only [Fintype.card_fin] using + binomial_le_finrank_of_eigenvector_mem A act_pairSwap_commute P hconj W + (fun p => hW _) s w hw hw0 hsigne + +end StandardPairs +end MatchingSmoothing + +end OAI diff --git a/lean/OAI/Combinatorics/MatchingPSD/ScalarSmoothing.lean b/lean/OAI/Combinatorics/MatchingPSD/ScalarSmoothing.lean new file mode 100644 index 0000000000000000000000000000000000000000..5a25c195c21b1bbca7a0e16cb2a82a6137db44ff --- /dev/null +++ b/lean/OAI/Combinatorics/MatchingPSD/ScalarSmoothing.lean @@ -0,0 +1,74 @@ +import OAI.Combinatorics.MatchingPSD.FiberAverages + +namespace OAI + +namespace MatchingSmoothing +open Filter Asymptotics + +lemma eventually_power_le_choose (m k : ℕ) (hm : m < k) (c : ℝ) : + ∀ᶠ h : ℕ in atTop, c * (h : ℝ)^m ≤ (h.choose k : ℝ) := by + have ho : (fun h : ℕ => (h : ℝ)^m) =o[atTop] (fun h : ℕ => (h : ℝ)^k) := + (isLittleO_pow_pow_atTop_of_lt hm).comp_tendsto tendsto_natCast_atTop_atTop + have hb := ((ho.const_mul_left c).trans_isBigO (isTheta_choose k).symm.isBigO).bound + (by norm_num : (0 : ℝ) < 1) + filter_upwards [hb] with h hh + exact (le_abs_self _).trans (by simpa only [Real.norm_eq_abs, abs_of_nonneg (show (0 : ℝ) ≤ h.choose k by positivity), one_mul] using hh) + +lemma eventually_table_moment_small (K : ℕ) : + ∀ᶠ h : ℕ in atTop, 4*(4*K+34) < h ∧ + (h+1 : ℝ)^33 ≤ (h.choose (4*K+34) : ℝ) * ((2*h : ℝ)^(2*K))⁻¹^2 := by + have hb := eventually_power_le_choose (33+4*K) (4*K+34) (by omega) + ((2 : ℝ)^(33+4*K)) + filter_upwards [hb, eventually_gt_atTop (4*(4*K+34))] with h hh hk + refine ⟨hk, ?_⟩ + have hp : (0 : ℝ) < 2*h := by + have : 0 < h := by omega + positivity + have h1 : (1 : ℝ) ≤ h := by exact_mod_cast (show 1 ≤ h by omega) + rw [inv_pow, le_mul_inv_iff₀ (pow_pos (pow_pos hp _) _)] + calc + (h+1 : ℝ)^33 * ((2*h : ℝ)^(2*K))^2 ≤ + (2*h : ℝ)^33 * ((2*h : ℝ)^(2*K))^2 := by gcongr; linarith + _ = (2*h : ℝ)^(33+4*K) := by + rw [← pow_mul, ← pow_add] + congr 1 + omega + _ ≤ (h.choose (4*K+34) : ℝ) := by simpa only [mul_pow] using hh + +noncomputable def polynomialProjection (h d : ℕ) (f : MatchingSpace h) : MatchingSpace h := + (polynomialSpace h d).starProjection f + +lemma residual_mem_high (h d : ℕ) (f : MatchingSpace h) : + f - polynomialProjection h d f ∈ (polynomialSpace h d)ᗮ := by + exact (polynomialSpace h d).sub_starProjection_mem_orthogonal f + +lemma residual_norm_le (h d : ℕ) (f : MatchingSpace h) : + ‖f - polynomialProjection h d f‖ ≤ ‖f‖ := by + rw [polynomialProjection, ← Submodule.starProjection_orthogonal_val] + exact (polynomialSpace h d)ᗮ.norm_starProjection_apply_le f + +lemma uniform_table_smoothing (K : ℕ) : + ∃ d H : ℕ, 0 < d ∧ ∀ h : ℕ, H ≤ h → + ∀ (f₀ : Vertices h → Fin 3), (∀ i, 0 < histogram f₀ i) → + ∀ f : MatchingSpace h, + (∑ z, fiberAverage (tableRelation f₀) + (matchingEquiv h (f - polynomialProjection h d f)) z ^ 2) / + Fintype.card (Colorings (Vertices h) (Fin 3) (histogram f₀)) ≤ + ((2*h : ℝ)^(2*K))⁻¹ * + ((∑ M, (f M)^2) / Fintype.card (Pairing (Vertices h))) := by + obtain ⟨H, hH⟩ := eventually_atTop.mp (eventually_table_moment_small K) + let k := 4*K+34 + let d := (4*k)*(4*k) + refine ⟨d, H, by dsimp [d, k]; positivity, ?_⟩ + intro h hh f₀ hf₀ f + obtain ⟨hk, hb⟩ := hH h hh + apply (table_smoothing_bound k hk f₀ hf₀ _ (by positivity) hb + _ (residual_mem_high h d f)).trans + apply mul_le_mul_of_nonneg_left _ (by positivity) + apply div_le_div_of_nonneg_right _ (by positivity) + rw [← EuclideanSpace.real_norm_sq_eq, ← EuclideanSpace.real_norm_sq_eq] + exact pow_le_pow_left₀ (norm_nonneg _) (residual_norm_le h d f) _ + +end MatchingSmoothing + +end OAI diff --git a/lean/OAI/Combinatorics/MatchingPSD/SequentialTests.lean b/lean/OAI/Combinatorics/MatchingPSD/SequentialTests.lean new file mode 100644 index 0000000000000000000000000000000000000000..d271f9dda5686b4a4179880045c716d6e9a0fa42 --- /dev/null +++ b/lean/OAI/Combinatorics/MatchingPSD/SequentialTests.lean @@ -0,0 +1,161 @@ +import OAI.Combinatorics.MatchingPSD.SquareRootDisturbance + +namespace OAI + +universe u_1 u_2 + +namespace PerfectMatchingPSD +open Matrix +open scoped MatrixOrder Matrix.Norms.Frobenius +variable {R : Type u_1} [Fintype R] [DecidableEq R] + +omit [DecidableEq R] in +lemma congruence_mono {A B : Matrix R R ℝ} (h : A ≤ B) (X : Matrix R R ℝ) : + Xᵀ * A * X ≤ Xᵀ * B * X := by + change (Xᵀ * B * X - Xᵀ * A * X).PosSemidef + simpa only [Matrix.conjTranspose_eq_transpose_of_trivial, mul_sub, sub_mul] + using h.conjTranspose_mul_mul_same X + +omit [Fintype R] in +lemma effect_le_one (F : Bool → Matrix R R ℝ) (hF : ∀ b, 0 ≤ F b) + (hs : F false + F true ≤ 1) (b : Bool) : F b ≤ 1 := by + cases b + · exact (le_add_of_nonneg_right (hF true)).trans hs + · exact (le_add_of_nonneg_left (hF false)).trans hs + +lemma effects_square_sum_le (F : Bool → Matrix R R ℝ) (hF : ∀ b, 0 ≤ F b) + (hs : F false + F true ≤ 1) : + (F false)ᵀ * F false + (F true)ᵀ * F true ≤ 1 := by + have h0 : (F false)ᵀ = F false := (hF false).posSemidef.isHermitian.eq + have h1 : (F true)ᵀ = F true := (hF true).posSemidef.isHermitian.eq + rw [h0, h1, ← pow_two, ← pow_two] + exact (add_le_add (square_le_self (hF false) (effect_le_one F hF hs false)) + (square_le_self (hF true) (effect_le_one F hF hs true))).trans hs + +def sequentialProduct : {q : ℕ} → (Fin q → Bool → Matrix R R ℝ) → + (Fin q → Bool) → Matrix R R ℝ + | 0, _, _ => 1 + | _+1, F, y => F 0 (y 0) * sequentialProduct (Fin.tail F) (Fin.tail y) + +lemma sum_function_succ {q : ℕ} {A : Type u_2} [AddCommMonoid A] + (f : (Fin (q+1) → Bool) → A) : + ∑ y, f y = ∑ z : Fin q → Bool, (f (Fin.cons false z) + f (Fin.cons true z)) := by + rw [← (Fin.consEquiv (fun _ : Fin (q+1) => Bool)).sum_comp f, + Fintype.sum_prod_type, Finset.sum_comm] + simp [Fin.consEquiv, add_comm] + +lemma sequentialProduct_sum_le {q : ℕ} (F : Fin q → Bool → Matrix R R ℝ) + (hF : ∀ i b, 0 ≤ F i b) (hs : ∀ i, F i false + F i true ≤ 1) : + ∑ y, (sequentialProduct F y)ᵀ * sequentialProduct F y ≤ 1 := by + induction q with + | zero => simp [sequentialProduct] + | succ q ih => + rw [sum_function_succ] + apply le_trans _ (ih (Fin.tail F) (fun i => hF i.succ) (fun i => hs i.succ)) + apply Finset.sum_le_sum + intro z _ + simp only [sequentialProduct, Fin.cons_zero, Fin.tail_cons, Matrix.transpose_mul] + have h := congruence_mono (effects_square_sum_le (F 0) (hF 0) (hs 0)) + (sequentialProduct (Fin.tail F) z) + simpa only [mul_add, add_mul, mul_one, mul_assoc] using h + +lemma sequentialProduct_error {q : ℕ} (F : Fin q → Bool → Matrix R R ℝ) + (y : Fin q → Bool) (G : Matrix R R ℝ) (δ : ℝ) + (hF : ∀ i b, (F i b)ᵀ * F i b ≤ 1) + (herr : ∀ i, ‖(F i (y i)-1)*G‖ ≤ δ) : + ‖(sequentialProduct F y-1)*G‖ ≤ (q:ℝ)*δ := by + induction q with + | zero => simp [sequentialProduct] + | succ q ih => + have ht := ih (Fin.tail F) (Fin.tail y) + (fun i b => hF i.succ b) (fun i => herr i.succ) + have hid : (sequentialProduct F y-1)*G = + F 0 (y 0) * ((sequentialProduct (Fin.tail F) (Fin.tail y)-1)*G) + + (F 0 (y 0)-1)*G := by + simp only [sequentialProduct] + noncomm_ring + rw [hid] + calc + _ ≤ ‖F 0 (y 0) * ((sequentialProduct (Fin.tail F) (Fin.tail y)-1)*G)‖ + + ‖(F 0 (y 0)-1)*G‖ := norm_add_le _ _ + _ ≤ (q:ℝ)*δ + δ := add_le_add + ((frobenius_mul_contraction (hF 0 (y 0)) _).trans ht) (herr 0) + _ = _ := by push_cast; ring + +lemma norm_sqrt_trace_one {ρ : Matrix R R ℝ} (hρ : ρ.PosSemidef) (htρ : ρ.trace = 1) : + ‖CFC.sqrt ρ‖ = 1 := by + have hG : (CFC.sqrt ρ).PosSemidef := (CFC.sqrt_nonneg ρ).posSemidef + have hGt : (CFC.sqrt ρ)ᵀ = CFC.sqrt ρ := hG.isHermitian.eq + have hsq : ‖CFC.sqrt ρ‖^2 = 1 := by + rw [frobenius_sq_trace, hGt, CFC.sqrt_mul_sqrt_self ρ hρ.nonneg, htρ] + nlinarith [norm_nonneg (CFC.sqrt ρ)] + +lemma norm_mul_sqrt_sq {ρ : Matrix R R ℝ} (hρ : ρ.PosSemidef) + (V : Matrix R R ℝ) : ‖V*CFC.sqrt ρ‖^2 = (ρ*(Vᵀ*V)).trace := by + let G := CFC.sqrt ρ + have hGt : Gᵀ = G := (CFC.sqrt_nonneg ρ).posSemidef.isHermitian.eq + have hGG : G*G = ρ := CFC.sqrt_mul_sqrt_self ρ hρ.nonneg + change ‖V*G‖^2 = _ + rw [frobenius_sq_trace, Matrix.transpose_mul, hGt] + have hid : G*Vᵀ*(V*G) = G*(Vᵀ*V)*G := by simp only [mul_assoc] + rw [hid, Matrix.trace_mul_cycle, hGG] + +lemma norm_mul_sq_lower (G V : Matrix R R ℝ) (hG : ‖G‖ = 1) + (δ : ℝ) (hδ : δ ≤ 1/4) (he : ‖(V-1)*G‖ ≤ δ) : + 1/2 ≤ ‖V*G‖^2 := by + have hh := norm_sub_le (V*G) ((V-1)*G) + have hid : V*G - (V-1)*G = G := by rw [sub_mul, one_mul, sub_sub_cancel] + rw [hid, hG] at hh + nlinarith [sq_nonneg (‖V*G‖-3/4)] + +lemma trace_product_upper {ρ : Matrix R R ℝ} (hρ : ρ.PosSemidef) + (htρ : ρ.trace = 1) (V : Matrix R R ℝ) : + (ρ*(Vᵀ*V)).trace ≤ (Vᵀ*V).trace := by + have hρle : ρ ≤ 1 := by simpa only [htρ, one_smul] using posSemidef_le_trace hρ + have hp : (Vᵀ*V).PosSemidef := by + simpa only [Matrix.conjTranspose_eq_transpose_of_trivial] + using Matrix.posSemidef_conjTranspose_mul_self V + have hub := trace_mul_le_of_le hp hρle + rwa [Matrix.trace_mul_comm (Vᵀ*V) ρ, mul_one] at hub + +lemma sequentialProduct_trace_lower {q : ℕ} + (ρ : Matrix R R ℝ) (F : Fin q → Bool → Matrix R R ℝ) (y : Fin q → Bool) + (hρ : ρ.PosSemidef) (htρ : ρ.trace = 1) + (hF : ∀ i b, 0 ≤ F i b) (hpair : ∀ i, F i false + F i true ≤ 1) + (ε : ℝ) (hε : 0 ≤ ε) (hsmall : (q:ℝ)*Real.sqrt ε ≤ 1/4) + (hsuccess : ∀ i, 1-ε ≤ (ρ * F i (y i)).trace) : + 1/2 ≤ ((sequentialProduct F y)ᵀ * sequentialProduct F y).trace := by + have heffect (i : Fin q) (b : Bool) : F i b ≤ 1 := + effect_le_one (F i) (hF i) (hpair i) b + have hlocal (i : Fin q) : ‖(F i (y i)-1)*CFC.sqrt ρ‖ ≤ Real.sqrt ε := + test_error hρ htρ (hF i (y i)) (heffect i (y i)) ε hε (hsuccess i) + have he := sequentialProduct_error F y (CFC.sqrt ρ) (Real.sqrt ε) + (fun i b => transpose_mul_self_le_one (hF i b) (heffect i b)) hlocal + have hsq := norm_mul_sq_lower (CFC.sqrt ρ) (sequentialProduct F y) + (norm_sqrt_trace_one hρ htρ) _ hsmall he + rw [norm_mul_sqrt_sq hρ] at hsq + exact hsq.trans (trace_product_upper hρ htρ _) + +lemma nearly_perfect_bit_tests {q : ℕ} + (ρ : (Fin q → Bool) → Matrix R R ℝ) (F : Fin q → Bool → Matrix R R ℝ) + (hρ : ∀ y, (ρ y).PosSemidef) (htρ : ∀ y, (ρ y).trace = 1) + (hF : ∀ i b, 0 ≤ F i b) (hpair : ∀ i, F i false + F i true ≤ 1) + (ε : ℝ) (hε : 0 ≤ ε) (hsmall : (q:ℝ)*Real.sqrt ε ≤ 1/4) + (hsuccess : ∀ y i, 1-ε ≤ (ρ y * F i (y i)).trace) : + (2:ℝ)^q / 2 ≤ Fintype.card R := by + classical + have hper (y : Fin q → Bool) : + 1/2 ≤ ((sequentialProduct F y)ᵀ * sequentialProduct F y).trace := + sequentialProduct_trace_lower (ρ y) F y (hρ y) (htρ y) hF hpair ε hε hsmall + (hsuccess y) + have hsum := Finset.sum_le_sum (fun y (_ : y ∈ Finset.univ) => hper y) + have hupper := trace_mono_matrix (sequentialProduct_sum_le F hF hpair) + rw [Matrix.trace_sum, Matrix.trace_one] at hupper + have hcard : (∑ _y : Fin q → Bool, (1/2:ℝ)) = (2:ℝ)^q/2 := by + simp [Fintype.card_bool, Fintype.card_fin, div_eq_mul_inv] + rw [hcard] at hsum + exact hsum.trans hupper + +end PerfectMatchingPSD + +end OAI diff --git a/lean/OAI/Combinatorics/MatchingPSD/SimultaneousSmoothing.lean b/lean/OAI/Combinatorics/MatchingPSD/SimultaneousSmoothing.lean new file mode 100644 index 0000000000000000000000000000000000000000..1f75bec095bf5ca9a4e5ce2d800c782b1e270fb2 --- /dev/null +++ b/lean/OAI/Combinatorics/MatchingPSD/SimultaneousSmoothing.lean @@ -0,0 +1,72 @@ +import OAI.Combinatorics.MatchingPSD.CommonSelection + +namespace OAI + +namespace MatchingSmoothing +open scoped BigOperators + +lemma lowProjection_comp (h d : ℕ) (p : Equiv.Perm (Vertices h)) + (f : Pairing (Vertices h) → ℝ) : + lowProjection h d (fun M => f (Pairing.relabel p M)) = + fun M => lowProjection h d f (Pairing.relabel p M) := by + have he := lowProjection_equivariant h d p⁻¹ f + have hc (f : Pairing (Vertices h) → ℝ) : + Pairing.act p⁻¹ f = fun M => f (Pairing.relabel p M) := by + ext M + simp only [Pairing.act_apply, inv_inv] + rw [hc, hc] at he + exact he + +lemma simultaneous_table_approximation (K : ℕ) : + ∃ d H : ℕ, 0 < d ∧ ∀ h : ℕ, H ≤ h → + ∀ (G I T : Type) [Fintype G] [Group G] [Fintype I] [Fintype T] + (z : I → Vertices h → Fin 3), (∀ i c, 0 < histogram (z i) c) → + ∀ (M : I → T → Pairing (Vertices h)) + (lift : I → Equiv.Perm (Vertices h) → G) + (g : I → G → Pairing (Vertices h) → ℝ), + (∀ i a p, g i (a * lift i p) = fun N => g i a (Pairing.relabel p N)) → + ∀ B : ℝ, (∀ i a N, (g i a N)^2 ≤ B^2) → + ∃ a : G, ∃ P : I → (Fin 3 → ℝ) → ℝ, + (∀ i, P i ∈ lowDegree (fun c (v : Fin 3 → ℝ) => v c) d) ∧ + (∑ i, ∑ t : T, + (predicateAverage (fun N => N.table (z i) = (M i t).table (z i)) (g i a) - + P i (fun c => ((M i t).table (z i) (threeEdgeType (crossPair c)) : ℝ)))^2) + ≤ (Fintype.card I : ℝ) * Fintype.card T * ((2*h : ℝ)^(2*K))⁻¹ * B^2 := by + classical + obtain ⟨d,H,hd,hsm⟩ := uniform_permutation_smoothing K + refine ⟨d,H,hd,?_⟩ + intro h hh G I T _ _ _ _ z hz M lift g hcov B hB + let : Nonempty (Pairing (Vertices h)) := ⟨standardPairing⟩ + let err : I → G → ℝ := fun i a => ∑ t : T, + (predicateAverage (fun N => N.table (z i) = (M i t).table (z i)) + (g i a - lowProjection h d (g i a)))^2 + let b : ℝ := (Fintype.card T : ℝ) * ((2*h : ℝ)^(2*K))⁻¹ * B^2 + have hlocal (i : I) (a : G) : (𝔼 p : Equiv.Perm (Vertices h), err i (a*lift i p)) ≤ b := by + have hres (p : Equiv.Perm (Vertices h)) : + g i (a*lift i p) - lowProjection h d (g i (a*lift i p)) = + fun N => (g i a - lowProjection h d (g i a)) (Pairing.relabel p N) := by + rw [hcov, lowProjection_comp] + rfl + simp only [err, hres] + rw [Finset.expect_sum_comm] + have hmean : (𝔼 N : Pairing (Vertices h), (g i a N)^2) ≤ B^2 := + Finset.expect_le Finset.univ_nonempty (fun N _ => hB i a N) + calc + _ ≤ ∑ _t : T, ((2*h : ℝ)^(2*K))⁻¹ * B^2 := by + apply Finset.sum_le_sum + intro t _ + exact (hsm h hh (z i) (hz i) (M i t) (g i a)).trans + (mul_le_mul_of_nonneg_left hmean (by positivity)) + _ = b := by simp [b, mul_assoc] + obtain ⟨a,ha⟩ := exists_total_le_of_local_means lift err (fun _ => b) hlocal + have hex (i : I) := table_average_polynomial (z i) d (lowProjection h d (g i a)) + (lowProjection_mem h d (g i a)) + choose P hP he using hex + refine ⟨a,P,hP,?_⟩ + have ht (i : I) (t : T) := he i ((M i t).table (z i)) ⟨M i t, rfl⟩ + simp only [err, map_sub, ht, Finset.sum_const, Finset.card_univ, nsmul_eq_mul] at ha + simpa only [b, mul_assoc] using ha + +end MatchingSmoothing + +end OAI diff --git a/lean/OAI/Combinatorics/MatchingPSD/SpectralContraction.lean b/lean/OAI/Combinatorics/MatchingPSD/SpectralContraction.lean new file mode 100644 index 0000000000000000000000000000000000000000..26054c0793baeee0fa1d6d3eb887a1f269e025c5 --- /dev/null +++ b/lean/OAI/Combinatorics/MatchingPSD/SpectralContraction.lean @@ -0,0 +1,69 @@ +import OAI.Combinatorics.MatchingPSD.MatchingIncidence + +namespace OAI + +universe u_1 u_2 + +namespace MatchingSmoothing +open scoped RealInnerProductSpace +variable {E : Type u_1} [NormedAddCommGroup E] [InnerProductSpace ℝ E] + [FiniteDimensional ℝ E] + +noncomputable def compression (A : Module.End ℝ E) (W : Submodule ℝ E) : + Module.End ℝ W := W.orthogonalProjectionOnto.toLinearMap.comp (A.comp W.subtype) + +lemma compression_symmetric (A : Module.End ℝ E) (hA : A.IsSymmetric) + (W : Submodule ℝ E) : (compression A W).IsSymmetric := by + intro x y + change ⟪W.orthogonalProjectionOnto (A x), y⟫ = + ⟪x, W.orthogonalProjectionOnto (A y)⟫ + simpa only [Submodule.inner_orthogonalProjectionOnto_eq_of_mem_left, + Submodule.inner_orthogonalProjectionOnto_eq_of_mem_right] using hA x y + +lemma compression_inner (A : Module.End ℝ E) (W : Submodule ℝ E) (x y : W) : + ⟪x, compression A W y⟫ = ⟪(x : E), A y⟫ := + Submodule.inner_orthogonalProjectionOnto_eq_of_mem_left _ _ + +omit [FiniteDimensional ℝ E] in +lemma trace_square_eq_sum_norm_sq (A : Module.End ℝ E) (hA : A.IsSymmetric) + {ι : Type u_2} [Fintype ι] (b : OrthonormalBasis ι ℝ E) : + LinearMap.trace ℝ E (A * A) = ∑ i, ‖A (b i)‖ ^ 2 := by + rw [LinearMap.trace_eq_sum_inner _ b] + apply Finset.sum_congr rfl + intro i _ + rw [Module.End.mul_apply, ← hA, real_inner_self_eq_norm_sq] + +lemma trace_square_compression_le (A : Module.End ℝ E) (hA : A.IsSymmetric) + (W : Submodule ℝ E) : + LinearMap.trace ℝ W (compression A W * compression A W) ≤ + LinearMap.trace ℝ E (A * A) := by + classical + let b := stdOrthonormalBasis ℝ W + let e := stdOrthonormalBasis ℝ E + rw [trace_square_eq_sum_norm_sq _ (compression_symmetric A hA W) b, + trace_square_eq_sum_norm_sq A hA e] + calc + ∑ i, ‖compression A W (b i)‖ ^ 2 ≤ ∑ i, ‖A (b i)‖ ^ 2 := by + apply Finset.sum_le_sum + intro i _ + exact sq_le_sq₀ (norm_nonneg _) (norm_nonneg _) |>.mpr + (W.norm_orthogonalProjectionOnto_apply_le _) + _ = ∑ i, ∑ j, ⟪e j, A (b i)⟫ ^ 2 := by + simp_rw [e.sum_sq_inner_right] + _ = ∑ j, ∑ i, ⟪(b i : E), A (e j)⟫ ^ 2 := by + rw [Finset.sum_comm] + apply Finset.sum_congr rfl + intro j _ + apply Finset.sum_congr rfl + intro i _ + rw [← hA, real_inner_comm] + _ ≤ ∑ j, ‖A (e j)‖ ^ 2 := by + apply Finset.sum_le_sum + intro j _ + have hb := b.orthonormal.comp_linearIsometry W.subtypeₗᵢ + have hh := hb.sum_inner_products_le (A (e j)) (s := Finset.univ) + simpa only [Function.comp_apply, Submodule.coe_subtypeₗᵢ, Submodule.coe_subtype, Real.norm_eq_abs, sq_abs] using hh + +end MatchingSmoothing + +end OAI diff --git a/lean/OAI/Combinatorics/MatchingPSD/SpectralMultiplicity.lean b/lean/OAI/Combinatorics/MatchingPSD/SpectralMultiplicity.lean new file mode 100644 index 0000000000000000000000000000000000000000..bfebfa7e74a4f529cd5b0463748e99206bc07b69 --- /dev/null +++ b/lean/OAI/Combinatorics/MatchingPSD/SpectralMultiplicity.lean @@ -0,0 +1,76 @@ +import OAI.Combinatorics.MatchingPSD.IncidenceKernels + +namespace OAI + +universe u_1 + +namespace MatchingSmoothing + +open scoped RealInnerProductSpace + +variable {E : Type u_1} [NormedAddCommGroup E] [InnerProductSpace ℝ E] + [FiniteDimensional ℝ E] + +lemma trace_square_eq_sum_eigenvalue_sq (B : Module.End ℝ E) (hB : B.IsSymmetric) : + LinearMap.trace ℝ E (B * B) = + ∑ i, (hB.eigenvalues (n := Module.finrank ℝ E) rfl i) ^ 2 := by + rw [LinearMap.trace_eq_sum_inner _ (hB.eigenvectorBasis rfl)] + apply Finset.sum_congr rfl + intro i _ + simp only [Module.End.mul_apply, hB.apply_eigenvectorBasis rfl, map_smul, + real_inner_smul_right, OrthonormalBasis.inner_eq_one, mul_one] + simp [pow_two] + +lemma eigenspace_dim_mul_sq_le_trace_square (B : Module.End ℝ E) (hB : B.IsSymmetric) + (c : ℝ) : + (Module.finrank ℝ (Module.End.eigenspace B c) : ℝ) * c ^ 2 ≤ + LinearMap.trace ℝ E (B * B) := by + classical + let ev := hB.eigenvalues (n := Module.finrank ℝ E) rfl + let s := Finset.univ.filter fun i => ev i = c + have hcard : s.card = Module.finrank ℝ (Module.End.eigenspace B c) := + hB.card_filter_eigenvalues_eq rfl c + have he : ∑ i ∈ s, ev i ^ 2 = (s.card : ℝ) * c ^ 2 := by + calc + ∑ i ∈ s, ev i ^ 2 = ∑ _i ∈ s, c ^ 2 := by + apply Finset.sum_congr rfl + intro i hi + rw [(Finset.mem_filter.mp hi).2] + _ = _ := by simp + rw [trace_square_eq_sum_eigenvalue_sq B hB, ← hcard, ← he] + exact Finset.sum_le_sum_of_subset_of_nonneg (Finset.subset_univ s) + (fun _ _ _ => sq_nonneg _) + +lemma quadratic_form_le_of_eigenvalues_le (B : Module.End ℝ E) (hB : B.IsSymmetric) + (a : ℝ) (ha : ∀ i, hB.eigenvalues (n := Module.finrank ℝ E) rfl i ≤ a) + (x : E) : ⟪x, B x⟫ ≤ a * ‖x‖ ^ 2 := by + let b := hB.eigenvectorBasis (n := Module.finrank ℝ E) rfl + rw [← b.sum_inner_mul_inner x (B x), ← b.sum_sq_inner_right x, Finset.mul_sum] + apply Finset.sum_le_sum + intro i _ + have he : B (b i) = (hB.eigenvalues rfl i) • b i := hB.apply_eigenvectorBasis rfl i + rw [← hB (b i) x, he, real_inner_smul_left, real_inner_comm x (b i)] + nlinarith [sq_nonneg (inner ℝ (b i) x), ha i] + +lemma quadratic_form_le_of_multiplicity (B : Module.End ℝ E) (hB : B.IsSymmetric) + (m H a : ℝ) (hm : 0 < m) (ha : 0 ≤ a) + (hdim : ∀ c : ℝ, c ≠ 0 → Module.End.HasEigenvalue B c → + m ≤ Module.finrank ℝ (Module.End.eigenspace B c)) + (htrace : LinearMap.trace ℝ E (B * B) ≤ H) + (hHa : H ≤ m * a ^ 2) (x : E) : ⟪x, B x⟫ ≤ a * ‖x‖ ^ 2 := by + apply quadratic_form_le_of_eigenvalues_le B hB a _ x + intro i + let c := hB.eigenvalues (n := Module.finrank ℝ E) rfl i + by_cases hc : c = 0 + · simpa only [← show c = hB.eigenvalues rfl i from rfl, hc] using ha + · have hd := hdim c hc (hB.hasEigenvalue_eigenvalues rfl i) + have he := eigenspace_dim_mul_sq_le_trace_square B hB c + have hsq : m * c ^ 2 ≤ m * a ^ 2 := + (mul_le_mul_of_nonneg_right hd (sq_nonneg c)).trans (he.trans (htrace.trans hHa)) + have hle : c ^ 2 ≤ a ^ 2 := (mul_le_mul_iff_right₀ hm).mp hsq + change c ≤ a + nlinarith + +end MatchingSmoothing + +end OAI diff --git a/lean/OAI/Combinatorics/MatchingPSD/SquareRootDisturbance.lean b/lean/OAI/Combinatorics/MatchingPSD/SquareRootDisturbance.lean new file mode 100644 index 0000000000000000000000000000000000000000..d1c8e364de9fdb61c36db32946fae7fb1930e65a --- /dev/null +++ b/lean/OAI/Combinatorics/MatchingPSD/SquareRootDisturbance.lean @@ -0,0 +1,96 @@ +import OAI.Combinatorics.MatchingPSD.DeterminantNormalization + +namespace OAI + +universe u_1 + +namespace PerfectMatchingPSD +open Matrix +open scoped MatrixOrder Matrix.Norms.Frobenius +variable {R : Type u_1} [Fintype R] [DecidableEq R] + +omit [DecidableEq R] in +lemma trace_mono_matrix {A B : Matrix R R ℝ} (h : A ≤ B) : A.trace ≤ B.trace := + (Matrix.tracePositiveLinearMap R ℝ ℝ).monotone h + +lemma frobenius_sq (A : Matrix R R ℝ) : + ‖A‖^2 = ∑ i, ∑ j, (A i j)^2 := by + rw [Matrix.frobenius_norm_def, ← Real.sqrt_eq_rpow, Real.sq_sqrt] + · simp + · positivity + +lemma frobenius_sq_trace (A : Matrix R R ℝ) : ‖A‖^2 = (Aᵀ * A).trace := by + rw [frobenius_sq] + simp only [Matrix.trace, Matrix.diag, Matrix.mul_apply, Matrix.transpose_apply, ← pow_two] + exact Finset.sum_comm + +lemma square_le_self {A : Matrix R R ℝ} (hA : 0 ≤ A) (hA₁ : A ≤ 1) : A^2 ≤ A := by + have hc : Commute A (1-A) := (Commute.one_right A).sub_right (Commute.refl A) + have hh := Commute.mul_nonneg hA (sub_nonneg.mpr hA₁) hc + simpa only [mul_sub, mul_one, ← pow_two, sub_nonneg] using hh + +lemma transpose_mul_self_le_one {A : Matrix R R ℝ} (hA : 0 ≤ A) (hA₁ : A ≤ 1) : + Aᵀ * A ≤ 1 := by + have hh : Aᵀ = A := hA.posSemidef.isHermitian.eq + rw [hh, ← pow_two] + exact (square_le_self hA hA₁).trans hA₁ + +lemma frobenius_mul_contraction {A : Matrix R R ℝ} (hA : Aᵀ * A ≤ 1) + (B : Matrix R R ℝ) : ‖A*B‖ ≤ ‖B‖ := by + have h := hA.conjTranspose_mul_mul_same B + have ht := h.trace_nonneg + have hid : Bᴴ * (1 - Aᵀ * A) * B = Bᵀ * B - (A*B)ᵀ * (A*B) := by + simp only [Matrix.conjTranspose_eq_transpose_of_trivial, mul_sub, sub_mul, mul_one, + Matrix.transpose_mul, mul_assoc] + rw [hid, Matrix.trace_sub, ← frobenius_sq_trace, ← frobenius_sq_trace] at ht + nlinarith [norm_nonneg (A*B), norm_nonneg B] + +lemma one_sub_square_le {A : Matrix R R ℝ} (hA : 0 ≤ A) (hA₁ : A ≤ 1) : + (1-A)^2 ≤ 1-A := square_le_self (sub_nonneg.mpr hA₁) (by simpa using hA) + +lemma test_error {ρ F : Matrix R R ℝ} (hρ : ρ.PosSemidef) (htρ : ρ.trace = 1) + (hF : 0 ≤ F) (hF₁ : F ≤ 1) (ε : ℝ) (hε : 0 ≤ ε) + (hs : 1-ε ≤ (ρ*F).trace) : + ‖(F-1)*CFC.sqrt ρ‖ ≤ Real.sqrt ε := by + let G := CFC.sqrt ρ + have hG : G.PosSemidef := (CFC.sqrt_nonneg ρ).posSemidef + have hGG : G*G = ρ := CFC.sqrt_mul_sqrt_self ρ hρ.nonneg + have he : ((F-1)*G)ᵀ * ((F-1)*G) = G*(1-F)^2*G := by + have hFt : Fᵀ = F := hF.posSemidef.isHermitian.eq + have hGt : Gᵀ = G := hG.isHermitian.eq + rw [Matrix.transpose_mul, Matrix.transpose_sub, hFt, Matrix.transpose_one, hGt] + noncomm_ring + have hb := trace_mul_le_of_le hρ (one_sub_square_le hF hF₁) + have hnorm : ‖(F-1)*G‖^2 ≤ ε := by + rw [frobenius_sq_trace, he, Matrix.trace_mul_cycle, hGG] + have hc : (ρ*(1-F)).trace = 1-(ρ*F).trace := by + rw [mul_sub, mul_one, Matrix.trace_sub, htρ] + rw [hc] at hb + linarith + change ‖(F-1)*G‖ ≤ Real.sqrt ε + nlinarith [Real.sq_sqrt hε, Real.sqrt_nonneg ε, norm_nonneg ((F-1)*G)] + +lemma posSemidef_le_trace {A : Matrix R R ℝ} (hA : A.PosSemidef) : + A ≤ A.trace • (1 : Matrix R R ℝ) := by + classical + have he (i : R) : hA.isHermitian.eigenvalues i ≤ A.trace := by + rw [hA.isHermitian.trace_eq_sum_eigenvalues] + exact Finset.single_le_sum (fun j _ => hA.eigenvalues_nonneg j) (Finset.mem_univ i) + have hd : (A.trace • (1 : Matrix R R ℝ) - + Matrix.diagonal hA.isHermitian.eigenvalues).PosSemidef := by + rw [Matrix.smul_one_eq_diagonal, Matrix.diagonal_sub] + exact Matrix.PosSemidef.diagonal (fun i => sub_nonneg.mpr (he i)) + let U : Matrix R R ℝ := hA.isHermitian.eigenvectorUnitary + have hu : U * Uᴴ = 1 := Unitary.coe_mul_star_self _ + have hs : A = U * Matrix.diagonal hA.isHermitian.eigenvalues * Uᴴ := by + simpa [Unitary.conjStarAlgAut_apply, Matrix.star_eq_conjTranspose, U] using hA.isHermitian.spectral_theorem + have hc := hd.conjTranspose_mul_mul_same Uᴴ + have hc' : (A.trace • (1 : Matrix R R ℝ) - + U * Matrix.diagonal hA.isHermitian.eigenvalues * Uᴴ).PosSemidef := by + simpa only [Matrix.conjTranspose_conjTranspose, mul_sub, sub_mul, + mul_smul_comm, smul_mul_assoc, mul_one, hu] using hc + rwa [← hs] at hc' + +end PerfectMatchingPSD + +end OAI diff --git a/lean/OAI/Combinatorics/MatchingPSD/TableCoordinates.lean b/lean/OAI/Combinatorics/MatchingPSD/TableCoordinates.lean new file mode 100644 index 0000000000000000000000000000000000000000..deaa0a59db9143728568d9aaf2846122cf9f3e7a --- /dev/null +++ b/lean/OAI/Combinatorics/MatchingPSD/TableCoordinates.lean @@ -0,0 +1,149 @@ +import OAI.Combinatorics.MatchingPSD.ColorPolynomials + +namespace OAI + +universe u_1 u_2 u_3 u_4 + +namespace MatchingSmoothing +attribute [local instance] Classical.propDecidable +section TableCoordinates +variable {V : Type u_1} {C : Type u_2} [Fintype V] + +lemma tableCoordinate_symm (z : V → C) (a b : C) : + tableCoordinate z (a,b) = tableCoordinate z (b,a) := by + funext M + unfold tableCoordinate + rw [← Equiv.sum_comp M.1 (fun v => if z v = b ∧ z (M.1 v) = a then (1:ℝ) else 0)] + apply Finset.sum_congr rfl + intro v _ + simp [M.partner_partner, and_comm] + +lemma tableCoordinate_row_sum [Fintype C] (z : V → C) (a : C) : + ∑ b, tableCoordinate z (a,b) = (histogram z a : ℝ) • 1 := by + classical + funext M + simp only [Finset.sum_apply, tableCoordinate, Pi.smul_apply, Pi.one_apply, + smul_eq_mul, mul_one] + rw [Finset.sum_comm, histogram_cast_sum] + apply Finset.sum_congr rfl + intro v _ + by_cases ha : z v = a + · simp [ha] + · simp [ha] + +lemma tableCoordinate_diagonal [Fintype C] (z : V → C) (a : C) : + tableCoordinate z (a,a) = (histogram z a : ℝ) • 1 - + ∑ b ∈ Finset.univ.erase a, tableCoordinate z (a,b) := by + classical + rw [← tableCoordinate_row_sum] + rw [eq_sub_iff_add_eq, add_comm] + exact Finset.sum_erase_add _ _ (Finset.mem_univ a) + +end TableCoordinates + +section ThreeCoordinates +variable {V : Type u_3} [Fintype V] + +def crossPair : Fin 3 → Fin 3 × Fin 3 := ![(0,1), (0,2), (1,2)] +noncomputable def crossCoordinate (z : V → Fin 3) (i : Fin 3) : Pairing V → ℝ := + tableCoordinate z (crossPair i) + +lemma tableCoordinate_offdiag_low (z : V → Fin 3) (a b : Fin 3) (hab : a ≠ b) : + tableCoordinate z (a,b) ∈ lowDegree (crossCoordinate z) 1 := by + have h01 : tableCoordinate z (0,1) ∈ lowDegree (crossCoordinate z) 1 := + coord_mem_lowDegree (crossCoordinate z) 0 + have h02 : tableCoordinate z (0,2) ∈ lowDegree (crossCoordinate z) 1 := + coord_mem_lowDegree (crossCoordinate z) 1 + have h12 : tableCoordinate z (1,2) ∈ lowDegree (crossCoordinate z) 1 := + coord_mem_lowDegree (crossCoordinate z) 2 + fin_cases a <;> fin_cases b + all_goals first | exact (hab rfl).elim | exact h01 | exact h02 | exact h12 | + rwa [tableCoordinate_symm] + +lemma tableCoordinate_three_affine (z : V → Fin 3) (c : Fin 3 × Fin 3) : + tableCoordinate z c ∈ lowDegree (crossCoordinate z) 1 := by + classical + obtain ⟨a,b⟩ := c + by_cases hab : a = b + · subst b + rw [tableCoordinate_diagonal] + apply Submodule.sub_mem + · exact Submodule.smul_mem _ _ (one_mem_lowDegree _ _) + · apply Submodule.sum_mem + intro b hb + simp only [Finset.mem_erase] at hb + exact tableCoordinate_offdiag_low z a b hb.1.symm + · exact tableCoordinate_offdiag_low z a b hab + +lemma colorAverage_cross_lowDegree (z : V → Fin 3) (d : ℕ) + (f : Pairing V → ℝ) (hf : f ∈ lowDegree Pairing.edgeCoord d) : + colorAverage z f ∈ lowDegree (crossCoordinate z) d := + lowDegree_substitute (crossCoordinate z) (tableCoordinate z) + (tableCoordinate_three_affine z) d (colorAverage_lowDegree z d f hf) + +lemma colorAverage_polynomial (z : V → Fin 3) (d : ℕ) + (f : Pairing V → ℝ) (hf : f ∈ lowDegree Pairing.edgeCoord d) : + ∃ P ∈ lowDegree (fun i (v : Fin 3 → ℝ) => v i) d, + ∀ M, colorAverage z f M = P (fun i => crossCoordinate z i M) := + lowDegree_lift _ _ _ (colorAverage_cross_lowDegree z d f hf) + +end ThreeCoordinates + +section TableRelation +variable {H : Type u_4} [Fintype H] + +lemma tableCoordinate_relabel (z : H × Bool → Fin 3) (c : Fin 3 × Fin 3) + (p : Equiv.Perm (H × Bool)) (M : Pairing (H × Bool)) : + tableCoordinate z c (Pairing.relabel p M) = tableCoordinate (z ∘ p) c M := by + classical + unfold tableCoordinate + apply Fintype.sum_equiv p.symm + intro v + split_ifs <;> simp_all [Function.comp_apply, Pairing.relabel_apply] + +lemma three_order_indicator (a b x y : Fin 3) : + (if x=a ∧ y=b then (1:ℝ) else 0) + (if y=a ∧ x=b then (1:ℝ) else 0) = + (if a=b then 2 else 1) * + (if threeEdgeType (x,y) = threeEdgeType (a,b) then (1:ℝ) else 0) := by + fin_cases a <;> fin_cases b <;> fin_cases x <;> fin_cases y <;> + norm_num [threeEdgeType, Fin.ext_iff] + +lemma standard_tableCoordinate (z : H × Bool → Fin 3) (a b : Fin 3) : + tableCoordinate z (a,b) standardPairing = + (if a=b then (2:ℝ) else 1) * (threeTable z (threeEdgeType (a,b)) : ℝ) := by + classical + simp only [tableCoordinate, Fintype.sum_prod_type, Fintype.sum_bool, + standardPairing, Equiv.prodCongr_apply] + change (∑ i, ((if z (i,true)=a ∧ z (i,false)=b then (1:ℝ) else 0) + + (if z (i,false)=a ∧ z (i,true)=b then (1:ℝ) else 0))) = _ + calc + _ = ∑ i, (if a=b then (2:ℝ) else 1) * + (if threeEdgeType (z (i,false),z (i,true)) = threeEdgeType (a,b) then 1 else 0) := by + apply Finset.sum_congr rfl + intro i _ + simpa only [add_comm] using three_order_indicator a b (z (i,false)) (z (i,true)) + _ = _ := by + rw [← Finset.mul_sum] + congr 1 + exact (histogram_cast_sum (threeEdgeType ∘ pairColorEquiv z) _).symm + +lemma tableCoordinate_eq_table [DecidableEq H] (z : H × Bool → Fin 3) + (M : Pairing (H × Bool)) (a b : Fin 3) : + tableCoordinate z (a,b) M = + (if a=b then (2:ℝ) else 1) * (M.table z (threeEdgeType (a,b)) : ℝ) := by + classical + obtain ⟨p, rfl⟩ := Pairing.exists_relabel (standardPairing (H := H)) M + rw [tableCoordinate_relabel, Pairing.table_relabel, standardPairing_table, + standard_tableCoordinate] + +lemma crossCoordinate_eq_table [DecidableEq H] (z : H × Bool → Fin 3) + (M : Pairing (H × Bool)) (i : Fin 3) : + crossCoordinate z i M = (M.table z (threeEdgeType (crossPair i)) : ℝ) := by + rw [crossCoordinate, tableCoordinate_eq_table] + have hne : (crossPair i).1 ≠ (crossPair i).2 := by fin_cases i <;> decide + rw [ite_eq_right hne, one_mul] + +end TableRelation +end MatchingSmoothing + +end OAI diff --git a/lean/OAI/Combinatorics/MatchingPSD/TableGeometry.lean b/lean/OAI/Combinatorics/MatchingPSD/TableGeometry.lean new file mode 100644 index 0000000000000000000000000000000000000000..6f1294e8da925e52b719dc33394e1d40191ba888 --- /dev/null +++ b/lean/OAI/Combinatorics/MatchingPSD/TableGeometry.lean @@ -0,0 +1,78 @@ +import OAI.Combinatorics.MatchingPSD.AdmissibleTables + +namespace OAI + +universe u_1 u_2 u_3 u_4 u_5 u_6 u_7 u_8 u_9 + +namespace MatchingSmoothing +open scoped BigOperators +attribute [local instance] Classical.propDecidable + +lemma predicateAverage_fiberEquiv {X : Type u_1} {Y : Type u_2} [Fintype X] [Fintype Y] + (P : X → Prop) (Q : Y → Prop) (e : {x // P x} ≃ {y // Q y}) + (f : X → ℝ) (g : Y → ℝ) (h : ∀ x, f x.1 = g (e x).1) : + predicateAverage P f = predicateAverage Q g := by + rw [predicateAverage_eq_expect, predicateAverage_eq_expect] + apply Fintype.expect_equiv e + exact h + +lemma coordinates_eq_of_cross_eq {V : Type u_3} [Fintype V] + (z : V → Fin 3) (M N : Pairing V) + (h : crossVector z M = crossVector z N) : ∀ a b, tableCoordinate z (a,b) M = tableCoordinate z (a,b) N := by + have hb (a b : Fin 3) (hab : a ≠ b) : tableCoordinate z (a,b) M = tableCoordinate z (a,b) N := by + have h0 := congrFun h 0 + have h1 := congrFun h 1 + have h2 := congrFun h 2 + fin_cases a <;> fin_cases b + all_goals first | exact (hab rfl).elim | exact h0 | exact h1 | exact h2 | + rwa [tableCoordinate_symm] + intro a b + by_cases hab : a = b + · subst b + rw [tableCoordinate_diagonal] + simp only [Pi.sub_apply, Pi.smul_apply, Pi.one_apply, smul_eq_mul, mul_one, + Finset.sum_apply] + congr 1 + apply Finset.sum_congr rfl + intro b hb' + simp only [Finset.mem_erase, Finset.mem_univ, and_true] at hb' + exact hb a b hb'.symm + · exact hb a b hab + +lemma table_eq_iff_cross {H : Type u_4} [Fintype H] [DecidableEq H] + (z : H × Bool → Fin 3) (M N : Pairing (H × Bool)) : + M.table z = N.table z ↔ crossVector z M = crossVector z N := by + constructor + · intro h + funext i + simp only [crossVector, crossCoordinate_eq_table, h] + · intro h + have hh := coordinates_eq_of_cross_eq z M N h + have get (a b : Fin 3) : M.table z (threeEdgeType (a,b)) = N.table z (threeEdgeType (a,b)) := by + have he := hh a b + rw [tableCoordinate_eq_table, tableCoordinate_eq_table] at he + split_ifs at he <;> exact_mod_cast (by linarith : (M.table z (threeEdgeType (a,b)) : ℝ) = N.table z (threeEdgeType (a,b))) + funext i + fin_cases i + · exact get 0 0 + · exact get 0 1 + · exact get 0 2 + · exact get 1 1 + · exact get 1 2 + · exact get 2 2 + +lemma crossVector_transport {V : Type u_5} {W : Type u_6} [Fintype V] [Fintype W] + (e : V ≃ W) (z : W → Fin 3) (M : Pairing V) : + crossVector z (Pairing.transport e M) = crossVector (z ∘ e) M := by + funext i + exact tableCoordinate_transport e z (crossPair i) M + +lemma histogram_comp_equiv {V : Type u_7} {W : Type u_8} {C : Type u_9} [Fintype V] [Fintype W] [DecidableEq C] + (z : W → C) (e : V ≃ W) : histogram (z ∘ e) = histogram z := by + funext c + apply Fintype.card_congr + exact e.subtypeEquiv (fun _ => Iff.rfl) + +end MatchingSmoothing + +end OAI diff --git a/lean/OAI/Combinatorics/MatchingPSD/TableMoments.lean b/lean/OAI/Combinatorics/MatchingPSD/TableMoments.lean new file mode 100644 index 0000000000000000000000000000000000000000..27fec9abfee80eaae7d5c1f4193b32ceb7ae942b --- /dev/null +++ b/lean/OAI/Combinatorics/MatchingPSD/TableMoments.lean @@ -0,0 +1,362 @@ +import OAI.Combinatorics.MatchingPSD.TypeProbabilities + +namespace OAI + +universe u_1 u_2 u_3 u_4 u_5 u_6 u_7 u_8 u_9 u_10 + +namespace MatchingSmoothing +open Matrix +section TableKernel +variable {H : Type u_1} {C : Type u_2} [Fintype H] [Fintype C] [DecidableEq H] [DecidableEq C] + +omit [DecidableEq C] in + +lemma weighted_common_fiber_bound (A : Matrix C C ℝ) + (hA : ∀ i j, 0 ≤ A i j) (P : (H × Bool → C) → Prop) [DecidablePred P] + (w : ℝ) (hw : ∀ f, P f → pairWeight A f = w) + (σ : Equiv.Perm (H × Bool)) : + (Fintype.card {f : H × Bool → C // P f ∧ P (f ∘ σ)} : ℝ) * w ^ 2 ≤ + ∑ f : H × Bool → C, pairWeight A f * pairWeight A (f ∘ σ) := by + classical + calc + _ = ∑ f : H × Bool → C, if P f ∧ P (f ∘ σ) then w ^ 2 else 0 := by + rw [← sum_indicator_card] + rw [Finset.sum_mul] + apply Finset.sum_congr rfl + intro f _ + split_ifs <;> simp + _ ≤ _ := by + apply Finset.sum_le_sum + intro f _ + split_ifs with hf + · rw [hw f hf.1, hw (f ∘ σ) hf.2, pow_two] + · exact mul_nonneg (pairWeight_nonneg A hA f) (pairWeight_nonneg A hA (f ∘ σ)) + +omit [DecidableEq C] in +lemma weighted_table_kernel_bound (A : Matrix C C ℝ) + (hA : ∀ i j, 0 ≤ A i j) (P : (H × Bool → C) → Prop) [DecidablePred P] + (w Z D L : ℝ) (hw : ∀ f, P f → pairWeight A f = w) + (hD : 0 < D) (hL : 0 ≤ L) (hz : Z ≤ D ^ 2 * w ^ 2 * L) + (σ : Equiv.Perm (H × Bool)) : + Z / D ^ 2 * Fintype.card {f : H × Bool → C // P f ∧ P (f ∘ σ)} ≤ + L * ∑ f : H × Bool → C, pairWeight A f * pairWeight A (f ∘ σ) := by + have hc := weighted_common_fiber_bound A hA P w hw σ + have hd : 0 < D ^ 2 := sq_pos_of_pos hD + have hz' : Z / D ^ 2 ≤ w ^ 2 * L := (div_le_iff₀ hd).mpr (by nlinarith [hz]) + calc + _ ≤ (w ^ 2 * L) * Fintype.card {f : H × Bool → C // P f ∧ P (f ∘ σ)} := + mul_le_mul_of_nonneg_right hz' (Nat.cast_nonneg _) + _ = L * ((Fintype.card {f : H × Bool → C // P f ∧ P (f ∘ σ)} : ℝ) * w ^ 2) := by ring + _ ≤ _ := mul_le_mul_of_nonneg_left hc hL + +lemma weighted_table_kernel_moment (A : Matrix C C ℝ) + (hs : A.IsHermitian) (hA : ∀ i j, 0 ≤ A i j) + (v : C → ℝ) (hv : ∀ i, 0 < v i) (hAv : A *ᵥ v = v) + (P : (H × Bool → C) → Prop) [DecidablePred P] + (w Z D L : ℝ) (hw : ∀ f, P f → pairWeight A f = w) + (hZ : 0 ≤ Z) (hD : 0 < D) (hL : 0 ≤ L) (hz : Z ≤ D ^ 2 * w ^ 2 * L) : + (∑ σ : Equiv.Perm (H × Bool), + (Z / D ^ 2 * Fintype.card {f : H × Bool → C // P f ∧ P (f ∘ σ)}) ^ 2) ≤ + Fintype.card (Equiv.Perm (H × Bool)) * L ^ 2 * + (Fintype.card H + 1 : ℝ) ^ (Fintype.card C ^ 2) := by + calc + _ ≤ ∑ σ : Equiv.Perm (H × Bool), + (L * ∑ f : H × Bool → C, pairWeight A f * pairWeight A (f ∘ σ)) ^ 2 := by + apply Finset.sum_le_sum + intro σ _ + apply pow_le_pow_left₀ (by positivity) + exact weighted_table_kernel_bound A hA P w Z D L hw hD hL hz σ + _ = L ^ 2 * ∑ σ : Equiv.Perm (H × Bool), + (∑ f : H × Bool → C, pairWeight A f * pairWeight A (f ∘ σ)) ^ 2 := by + simp_rw [mul_pow] + rw [Finset.mul_sum] + _ ≤ L ^ 2 * (Fintype.card (Equiv.Perm (H × Bool)) * + (Fintype.card H + 1 : ℝ) ^ (Fintype.card C ^ 2)) := + mul_le_mul_of_nonneg_left (pairWeight_overlap_square_moment A hs hA v hv hAv) (sq_nonneg L) + _ = _ := by ring + +end TableKernel +end MatchingSmoothing + +namespace MatchingSmoothing +open Matrix + +def threeEdgeType (p : Fin 3 × Fin 3) : Fin 6 := + (![![0, 1, 2], ![1, 3, 4], ![2, 4, 5]] : Fin 3 → Fin 3 → Fin 6) p.1 p.2 + +def typeMultiplicity : Fin 6 → ℕ := ![1, 2, 2, 1, 2, 1] + +lemma threeEdgeType_surjective : Function.Surjective threeEdgeType := by decide + +lemma card_threeEdgeType_fiber (t : Fin 6) : + Fintype.card {a : Fin 3 × Fin 3 // threeEdgeType a = t} = typeMultiplicity t := by + fin_cases t <;> decide + +lemma threeEdgeType_symm (a b : Fin 3) : threeEdgeType (a,b) = threeEdgeType (b,a) := by + fin_cases a <;> fin_cases b <;> rfl + +lemma typeMultiplicity_pos (t : Fin 6) : 0 < typeMultiplicity t := by + fin_cases t <;> decide + +lemma endpoint_type_identity (a b i : Fin 3) : + (∑ j : Fin 3, (if threeEdgeType (a,b) = threeEdgeType (i,j) then (1 : ℝ) else 0) / + typeMultiplicity (threeEdgeType (i,j))) = + ((if a = i then (1 : ℝ) else 0) + (if b = i then 1 else 0)) / 2 := by + have h0 : typeMultiplicity 0 = 1 := by decide + have h1 : typeMultiplicity 1 = 2 := by decide + have h2 : typeMultiplicity 2 = 2 := by decide + have h3 : typeMultiplicity 3 = 1 := by decide + have h4 : typeMultiplicity 4 = 2 := by decide + have h5 : typeMultiplicity 5 = 1 := by decide + fin_cases a <;> fin_cases b <;> fin_cases i <;> + norm_num [threeEdgeType, Fin.sum_univ_succ, Fin.ext_iff, h0, h1, h2, h3, h4, h5] + +section ThreeTables +variable {H : Type u_3} [Fintype H] [DecidableEq H] + +noncomputable def pairColorEquiv : (H × Bool → Fin 3) ≃ (H → Fin 3 × Fin 3) where + toFun f i := (f (i,false), f (i,true)) + invFun k v := if v.2 then (k v.1).2 else (k v.1).1 + left_inv f := by funext ⟨i,b⟩; cases b <;> rfl + right_inv k := by funext i; rfl + +noncomputable def threeTable (f : H × Bool → Fin 3) : Fin 6 → ℕ := + histogram (threeEdgeType ∘ pairColorEquiv f) + +noncomputable def tableGamma (f : H × Bool → Fin 3) : Matrix (Fin 3) (Fin 3) ℝ := + fun i j => ((threeTable f (threeEdgeType (i,j)) : ℝ) / Fintype.card H) / + typeMultiplicity (threeEdgeType (i,j)) + +noncomputable def tablePi (f : H × Bool → Fin 3) : Fin 3 → ℝ := + fun i => (histogram f i : ℝ) / (2 * Fintype.card H) + +omit [DecidableEq H] in +lemma histogram_cast_sum {V : Type u_4} {T : Type u_5} [Fintype V] [DecidableEq T] (f : V → T) (t : T) : + (histogram f t : ℝ) = ∑ i, if f i = t then 1 else 0 := by + classical + simp only [histogram, Fintype.card_subtype, Finset.card_filter, Nat.cast_sum] + apply Finset.sum_congr rfl + intro i _ + split_ifs <;> norm_num + +omit [DecidableEq H] in +lemma tableGamma_hermitian (f : H × Bool → Fin 3) : (tableGamma f).IsHermitian := by + rw [Matrix.IsHermitian.ext_iff] + intro i j + simp only [star_trivial, tableGamma, threeEdgeType_symm j i] + +omit [DecidableEq H] in +lemma tableGamma_nonneg (f : H × Bool → Fin 3) : ∀ i j, 0 ≤ tableGamma f i j := by + intro i j + unfold tableGamma + positivity + +omit [DecidableEq H] in +lemma tableGamma_rowsum (f : H × Bool → Fin 3) (i : Fin 3) : + ∑ j, tableGamma f i j = tablePi f i := by + have he (j : Fin 3) : tableGamma f i j = + (∑ v : H, (if threeEdgeType (f (v,false),f (v,true)) = threeEdgeType (i,j) + then (1 : ℝ) else 0) / typeMultiplicity (threeEdgeType (i,j))) / Fintype.card H := by + simp only [tableGamma, threeTable, histogram_cast_sum, Function.comp_apply, + pairColorEquiv, Equiv.coe_fn_mk, ← Finset.sum_div] + ring + simp_rw [he] + rw [← Finset.sum_div, Finset.sum_comm] + simp_rw [endpoint_type_identity] + rw [← Finset.sum_div, div_div] + congr 1 + simp only [histogram_cast_sum, Fintype.sum_prod_type, Fintype.sum_bool, + Finset.sum_add_distrib] + ring + +omit [DecidableEq H] in +lemma tablePi_pos (f : H × Bool → Fin 3) (hH : 0 < Fintype.card H) + (hf : ∀ i, 0 < histogram f i) : ∀ i, 0 < tablePi f i := by + intro i + exact div_pos (Nat.cast_pos.mpr (hf i)) (by positivity) + +omit [DecidableEq H] in +lemma tablePi_sum (f : H × Bool → Fin 3) (hH : 0 < Fintype.card H) : + ∑ i, tablePi f i = 1 := by + simp only [tablePi, ← Finset.sum_div, ← Nat.cast_sum, sum_histogram, + Fintype.card_prod, Fintype.card_bool, Nat.cast_mul, Nat.cast_ofNat] + field_simp + +omit [DecidableEq H] in +lemma pairWeight_tableGamma_eq (f₀ f : H × Bool → Fin 3) : + pairWeight (tableGamma f₀) f = + ∏ t : Fin 6, (((threeTable f₀ t : ℝ) / Fintype.card H) / typeMultiplicity t) ^ threeTable f t := by + exact prod_eq_prod_histogram (threeEdgeType ∘ pairColorEquiv f) + (fun t => ((threeTable f₀ t : ℝ) / Fintype.card H) / typeMultiplicity t) + +omit [DecidableEq H] in +lemma pairWeight_tableGamma_constant (f₀ f : H × Bool → Fin 3) + (hf : threeTable f = threeTable f₀) : + pairWeight (tableGamma f₀) f = pairWeight (tableGamma f₀) f₀ := by + rw [pairWeight_tableGamma_eq, pairWeight_tableGamma_eq, hf] + +lemma tableGamma_integer_mean_lower (f₀ : H × Bool → Fin 3) (hH : 0 < Fintype.card H) : + 1 ≤ (Fintype.card H + 1 : ℝ) ^ 6 * + ((Fintype.card {f : H × Bool → Fin 3 // threeTable f = threeTable f₀} : ℝ) * + pairWeight (tableGamma f₀) f₀) := by + classical + have hl := integer_mean_type_probability_lower threeEdgeType threeEdgeType_surjective + (threeEdgeType ∘ pairColorEquiv f₀) hH + simp only [Fintype.card_fin, card_threeEdgeType_fiber] at hl + have he : (∑ f : H × Bool → Fin 3, + (if threeTable f = threeTable f₀ then (1 : ℝ) else 0) * pairWeight (tableGamma f₀) f) = + ∑ k : H → Fin 3 × Fin 3, + (if histogram (threeEdgeType ∘ k) = threeTable f₀ then (1 : ℝ) else 0) * + ∏ i, ((threeTable f₀ (threeEdgeType (k i)) : ℝ) / Fintype.card H) / + typeMultiplicity (threeEdgeType (k i)) := by + exact Fintype.sum_equiv pairColorEquiv _ _ (fun f => rfl) + change 1 ≤ (Fintype.card H + 1 : ℝ) ^ 6 * + (∑ k : H → Fin 3 × Fin 3, + (if histogram (threeEdgeType ∘ k) = threeTable f₀ then (1 : ℝ) else 0) * + ∏ i, ((threeTable f₀ (threeEdgeType (k i)) : ℝ) / Fintype.card H) / + typeMultiplicity (threeEdgeType (k i))) at hl + rw [← he] at hl + have hc (f : H × Bool → Fin 3) : + (if threeTable f = threeTable f₀ then (1 : ℝ) else 0) * pairWeight (tableGamma f₀) f = + (if threeTable f = threeTable f₀ then (1 : ℝ) else 0) * pairWeight (tableGamma f₀) f₀ := by + split_ifs with hf + · rw [pairWeight_tableGamma_constant f₀ f hf] + · simp + simp_rw [hc] at hl + rw [← Finset.sum_mul, sum_indicator_card] at hl + exact hl + +omit [DecidableEq H] in +lemma threeTable_histogram_eq {f g : H × Bool → Fin 3} (hH : 0 < Fintype.card H) + (h : threeTable f = threeTable g) : histogram f = histogram g := by + have hγ : tableGamma f = tableGamma g := by + unfold tableGamma + rw [h] + funext i + have he := (tableGamma_rowsum f i).symm.trans + ((congrArg (fun A : Matrix (Fin 3) (Fin 3) ℝ => ∑ j, A i j) hγ).trans + (tableGamma_rowsum g i)) + change (histogram f i : ℝ) / (2 * Fintype.card H) = + (histogram g i : ℝ) / (2 * Fintype.card H) at he + have hn : (2 * Fintype.card H : ℝ) ≠ 0 := by positivity + exact_mod_cast (div_left_inj' hn).mp he + +end ThreeTables + +section Probability +variable {V : Type u_6} {C : Type u_7} [Fintype V] [Fintype C] [DecidableEq V] [DecidableEq C] + +lemma histogram_product_mass_le_one (π : C → ℝ) (hn : ∀ i, 0 ≤ π i) + (hs : ∑ i, π i = 1) (f₀ : V → C) : + (Fintype.card (Colorings V C (histogram f₀)) : ℝ) * (∏ v, π (f₀ v)) ≤ 1 := by + classical + calc + _ = ∑ f : V → C, if histogram f = histogram f₀ then ∏ v, π (f v) else 0 := by + have he (f : V → C) : + (if histogram f = histogram f₀ then ∏ v, π (f v) else 0) = + (if histogram f = histogram f₀ then (1 : ℝ) else 0) * ∏ v, π (f₀ v) := by + split_ifs with hf + · rw [one_mul, prod_eq_prod_histogram f, prod_eq_prod_histogram f₀, hf] + · simp + simp_rw [he] + rw [← Finset.sum_mul, sum_indicator_card] + congr 1 + exact congrArg Nat.cast (@Fintype.card_congr + (Colorings V C (histogram f₀)) {f : V → C // histogram f = histogram f₀} + (coloringsFintype _) (Subtype.fintype _) (Equiv.refl _)) + _ ≤ ∑ f : V → C, ∏ v, π (f v) := by + apply Finset.sum_le_sum + intro f _ + split_ifs + · rfl + · exact Finset.prod_nonneg (fun v _ => hn (f v)) + _ = ∏ _v : V, ∑ i, π i := Fintype.prod_sum (fun (_v : V) i => π i) |>.symm + _ = 1 := by simp only [hs, Finset.prod_const_one] + +omit [DecidableEq V] [Fintype C] [DecidableEq C] in +lemma vertexSqrtWeight_sq (π : C → ℝ) (hn : ∀ i, 0 ≤ π i) (f : V → C) : + (∏ v, Real.sqrt (π (f v))) ^ 2 = ∏ v, π (f v) := by + rw [← Finset.prod_pow] + exact Finset.prod_congr rfl (fun v _ => Real.sq_sqrt (hn (f v))) + +end Probability + +section TableNormalization +variable {H : Type u_8} {C : Type u_9} [Fintype H] [Fintype C] [DecidableEq H] [DecidableEq C] + +omit [DecidableEq H] [Fintype C] [DecidableEq C] in +lemma pairWeight_normalized (γ : Matrix C C ℝ) (π : C → ℝ) (f : H × Bool → C) : + pairWeight (normalizedPairMatrix γ π) f = + pairWeight γ f / (∏ v : H × Bool, Real.sqrt (π (f v))) := by + simp only [pairWeight, normalizedPairMatrix, Finset.prod_div_distrib, + Fintype.prod_prod_type, Fintype.prod_bool] + congr 1 + exact Finset.prod_congr rfl (fun i _ => mul_comm _ _) + +end TableNormalization + +section ThreeTableMoment +variable {H : Type u_10} [Fintype H] [DecidableEq H] + +lemma three_table_kernel_moment (f₀ : H × Bool → Fin 3) (hH : 0 < Fintype.card H) + (hf₀ : ∀ i, 0 < histogram f₀ i) : + (∑ σ : Equiv.Perm (H × Bool), + ((Fintype.card (Colorings (H × Bool) (Fin 3) (histogram f₀)) : ℝ) / + (Fintype.card {f : H × Bool → Fin 3 // threeTable f = threeTable f₀} : ℝ) ^ 2 * + Fintype.card {f : H × Bool → Fin 3 // + threeTable f = threeTable f₀ ∧ threeTable (f ∘ σ) = threeTable f₀}) ^ 2) ≤ + Fintype.card (Equiv.Perm (H × Bool)) * (Fintype.card H + 1 : ℝ) ^ 33 := by + classical + let γ := tableGamma f₀ + let π := tablePi f₀ + let A := normalizedPairMatrix γ π + let Z : ℝ := Fintype.card (Colorings (H × Bool) (Fin 3) (histogram f₀)) + let D : ℝ := Fintype.card {f : H × Bool → Fin 3 // threeTable f = threeTable f₀} + let Q := pairWeight γ f₀ + let S := ∏ v : H × Bool, Real.sqrt (π (f₀ v)) + have hπ : ∀ i, 0 < π i := tablePi_pos f₀ hH hf₀ + have hS : 0 < S := Finset.prod_pos (fun v _ => Real.sqrt_pos.mpr (hπ (f₀ v))) + have hD : 0 < D := by + change (0 : ℝ) < (Fintype.card {f : H × Bool → Fin 3 // threeTable f = threeTable f₀} : ℝ) + exact Nat.cast_pos.mpr (Fintype.card_pos_iff.mpr ⟨⟨f₀, rfl⟩⟩) + have hQ : 0 ≤ Q := pairWeight_nonneg γ (tableGamma_nonneg f₀) f₀ + have hw (f : H × Bool → Fin 3) (ht : threeTable f = threeTable f₀) : + pairWeight A f = Q / S := by + rw [pairWeight_normalized, pairWeight_tableGamma_constant f₀ f ht] + congr 1 + change (∏ v, (fun i => Real.sqrt (π i)) (f v)) = + ∏ v, (fun i => Real.sqrt (π i)) (f₀ v) + rw [prod_eq_prod_histogram f (fun i => Real.sqrt (π i)), + prod_eq_prod_histogram f₀ (fun i => Real.sqrt (π i)), threeTable_histogram_eq hH ht] + have hprob : Z * S ^ 2 ≤ 1 := by + rw [show S ^ 2 = _ from vertexSqrtWeight_sq π (fun i => (hπ i).le) f₀] + exact histogram_product_mass_le_one π (fun i => (hπ i).le) (tablePi_sum f₀ hH) f₀ + have hmean : 1 ≤ (Fintype.card H + 1 : ℝ) ^ 6 * (D * Q) := + tableGamma_integer_mean_lower f₀ hH + have hb : (1 : ℝ) ≤ D ^ 2 * Q ^ 2 * (Fintype.card H + 1 : ℝ) ^ 12 := by + have h := pow_le_pow_left₀ (by norm_num : (0 : ℝ) ≤ 1) hmean 2 + calc + (1 : ℝ) = 1 ^ 2 := by norm_num + _ ≤ ((Fintype.card H + 1 : ℝ) ^ 6 * (D * Q)) ^ 2 := h + _ = _ := by ring + have hz : Z ≤ D ^ 2 * (Q / S) ^ 2 * (Fintype.card H + 1 : ℝ) ^ 12 := by + apply (mul_le_mul_iff_left₀ (sq_pos_of_pos hS)).mp + have he : (D ^ 2 * (Q / S) ^ 2 * (Fintype.card H + 1 : ℝ) ^ 12) * S ^ 2 = + D ^ 2 * Q ^ 2 * (Fintype.card H + 1 : ℝ) ^ 12 := by field_simp + rw [he] + linarith + have hg := weighted_table_kernel_moment A + (normalizedPairMatrix_hermitian γ π (tableGamma_hermitian f₀)) + (normalizedPairMatrix_nonneg γ π (tableGamma_nonneg f₀)) + (fun i => Real.sqrt (π i)) (fun i => Real.sqrt_pos.mpr (hπ i)) + (normalizedPairMatrix_fixed γ π hπ (tableGamma_rowsum f₀)) + (fun f => threeTable f = threeTable f₀) (Q / S) Z D + ((Fintype.card H + 1 : ℝ) ^ 12) hw (Nat.cast_nonneg _) hD (by positivity) hz + convert hg using 1 + norm_num [Fintype.card_fin] + ring + +end ThreeTableMoment +end MatchingSmoothing + +end OAI diff --git a/lean/OAI/Combinatorics/MatchingPSD/TablePolynomials.lean b/lean/OAI/Combinatorics/MatchingPSD/TablePolynomials.lean new file mode 100644 index 0000000000000000000000000000000000000000..b49ee31f74431d971991cab559c7072842ce655a --- /dev/null +++ b/lean/OAI/Combinatorics/MatchingPSD/TablePolynomials.lean @@ -0,0 +1,105 @@ +import OAI.Combinatorics.MatchingPSD.TableCoordinates + +namespace OAI + +universe u_1 u_2 u_3 u_4 + +namespace MatchingSmoothing +attribute [local instance] Classical.propDecidable +section PredicateAverage +variable {X : Type u_1} [Fintype X] + +noncomputable def predicateAverage (P : X → Prop) : (X → ℝ) →ₗ[ℝ] ℝ := + (Fintype.card {x // P x} : ℝ)⁻¹ • + ∑ x, if P x then LinearMap.proj x else 0 + +lemma predicateAverage_apply (P : X → Prop) (f : X → ℝ) : + predicateAverage P f = (∑ x, if P x then f x else 0) / Fintype.card {x // P x} := by + simp only [predicateAverage, LinearMap.smul_apply, LinearMap.sum_apply, smul_eq_mul, + div_eq_mul_inv] + rw [mul_comm] + congr 1 + apply Finset.sum_congr rfl + intro x _ + by_cases hx : P x <;> simp [hx] + +lemma predicateAverage_comp (P : X → Prop) (e : X ≃ X) + (he : ∀ x, P (e x) ↔ P x) (f : X → ℝ) : + predicateAverage P (f ∘ e) = predicateAverage P f := by + rw [predicateAverage_apply, predicateAverage_apply] + congr 1 + calc + _ = ∑ x, if P (e x) then f (e x) else 0 := by simp only [he, Function.comp_apply] + _ = _ := by + apply Fintype.sum_equiv e + intro x + rfl + +lemma predicateAverage_of_constant (P : X → Prop) (c : ℝ) (hP : ∃ x, P x) + (f : X → ℝ) (hf : ∀ x, P x → f x = c) : predicateAverage P f = c := by + classical + have : Nonempty {x // P x} := ⟨⟨hP.choose, hP.choose_spec⟩⟩ + rw [predicateAverage_apply] + have hs : (∑ x, if P x then f x else 0) = Fintype.card {x // P x} * c := by + calc + _ = ∑ x ∈ Finset.univ.filter P, f x := (Finset.sum_filter _ _).symm + _ = ∑ _x ∈ Finset.univ.filter P, c := by + apply Finset.sum_congr rfl + intro x hx + exact hf x (Finset.mem_filter.mp hx).2 + _ = _ := by simp [Fintype.card_subtype] + rw [hs] + exact mul_div_cancel_left₀ c (Nat.cast_ne_zero.mpr Fintype.card_ne_zero) + +end PredicateAverage +end MatchingSmoothing + +namespace MatchingSmoothing +attribute [local instance] Classical.propDecidable +section ReynoldsAverage +variable {V : Type u_2} {C : Type u_3} [Fintype V] + +lemma predicateAverage_colorAverage (z : V → C) (P : Pairing V → Prop) + (hP : ∀ (p : colorStabilizer z) M, P (Pairing.relabel p.1 M) ↔ P M) + (f : Pairing V → ℝ) : + predicateAverage P (colorAverage z f) = predicateAverage P f := by + classical + have hp (p : colorStabilizer z) : + predicateAverage P (Pairing.act p.1 f) = predicateAverage P f := by + exact predicateAverage_comp P (Pairing.relabelEquiv p.1⁻¹) (hP p⁻¹) f + simp only [colorAverage, LinearMap.smul_apply, LinearMap.sum_apply, + LinearEquiv.coe_coe, map_smul, map_sum] + simp_rw [hp] + simp [nsmul_eq_mul, Fintype.card_ne_zero] + +end ReynoldsAverage + +section TablePolynomial +variable {H : Type u_4} [Fintype H] [DecidableEq H] + +lemma table_average_polynomial (z : H × Bool → Fin 3) (d : ℕ) + (f : Pairing (H × Bool) → ℝ) (hf : f ∈ lowDegree Pairing.edgeCoord d) : + ∃ P ∈ lowDegree (fun i (v : Fin 3 → ℝ) => v i) d, + ∀ t : Fin 6 → ℕ, (∃ M : Pairing (H × Bool), M.table z = t) → + predicateAverage (fun M => M.table z = t) f = + P (fun i => (t (threeEdgeType (crossPair i)) : ℝ)) := by + obtain ⟨P, hP, hp⟩ := colorAverage_polynomial z d f hf + refine ⟨P, hP, ?_⟩ + intro t ht + have hInv (p : colorStabilizer z) (M : Pairing (H × Bool)) : + (Pairing.relabel p.1 M).table z = t ↔ M.table z = t := by + rw [Pairing.table_relabel] + have hz : z ∘ p.1 = z := funext p.property + rw [hz] + rw [← predicateAverage_colorAverage z _ hInv] + apply predicateAverage_of_constant _ _ ht + intro M hM + rw [hp] + congr 1 + funext i + rw [crossCoordinate_eq_table, hM] + +end TablePolynomial +end MatchingSmoothing + +end OAI diff --git a/lean/OAI/Combinatorics/MatchingPSD/TensorBounds.lean b/lean/OAI/Combinatorics/MatchingPSD/TensorBounds.lean new file mode 100644 index 0000000000000000000000000000000000000000..083ccdc954bd447764a1ffa88298fec657b231c2 --- /dev/null +++ b/lean/OAI/Combinatorics/MatchingPSD/TensorBounds.lean @@ -0,0 +1,167 @@ +import OAI.Combinatorics.MatchingPSD.TransitionMatrices + +namespace OAI + +universe u_1 u_2 u_3 + +namespace MatchingSmoothing +open Matrix + +variable {C : Type u_1} [Fintype C] [DecidableEq C] + +lemma abs_eigenvalue_le_one_stochastic (W : Matrix C C ℝ) + (hn : ∀ i j, 0 ≤ W i j) (hs : ∀ i, ∑ j, W i j = 1) + (c : ℝ) (hc : Module.End.HasEigenvalue (Matrix.toLin' W) c) : |c| ≤ 1 := by + obtain ⟨i, hi⟩ := eigenvalue_mem_ball hc + rw [mem_closedBall_iff_norm] at hi + simp only [Real.norm_eq_abs, abs_of_nonneg (hn _ _)] at hi + have he := Finset.sum_erase_add (Finset.univ : Finset C) (fun j => W i j) + (Finset.mem_univ i) + rw [hs] at he + calc + |c| = |(c - W i i) + W i i| := by congr 1; ring + _ ≤ |c - W i i| + |W i i| := abs_add_le _ _ + _ ≤ 1 := by rw [abs_of_nonneg (hn _ _)]; linarith + +lemma abs_eigenvalue_le_one_positive_fixed (A : Matrix C C ℝ) + (hn : ∀ i j, 0 ≤ A i j) (v : C → ℝ) (hv : ∀ i, 0 < v i) + (hf : A *ᵥ v = v) (c : ℝ) + (hc : Module.End.HasEigenvalue (Matrix.toLin' A) c) : |c| ≤ 1 := by + let W : Matrix C C ℝ := fun i j => A i j * v j / v i + apply abs_eigenvalue_le_one_stochastic W + · intro i j; exact div_nonneg (mul_nonneg (hn i j) (hv j).le) (hv i).le + · intro i + change ∑ j, A i j * v j / v i = 1 + rw [← Finset.sum_div] + change (A *ᵥ v) i / v i = 1 + rw [hf, div_self (ne_of_gt (hv i))] + · obtain ⟨x, hx, hnx⟩ := hc.exists_hasEigenvector + let y : C → ℝ := fun i => x i / v i + have hy : y ≠ 0 := by + intro h + apply hnx + ext i + have he := congrFun h i + change x i / v i = 0 at he + exact (div_eq_zero_iff.mp he).resolve_right (ne_of_gt (hv i)) + apply Module.End.hasEigenvalue_of_hasEigenvector + refine ⟨?_, hy⟩ + rw [Module.End.mem_eigenspace_iff] + ext i + change ∑ j, (A i j * v j / v i) * (x j / v j) = c * (x i / v i) + have hh (j : C) : A i j * v j / v i * (x j / v j) = A i j * x j / v i := by + field_simp [ne_of_gt (hv j), ne_of_gt (hv i)] + simp_rw [hh] + rw [← Finset.sum_div] + have hhx := congrFun (Module.End.mem_eigenspace_iff.mp hx) i + change ∑ j, A i j * x j = c * x i at hhx + rw [hhx] + ring + +lemma exists_orthogonal_diagonalization_bounded (A : Matrix C C ℝ) + (hA : A.IsHermitian) (hn : ∀ i j, 0 ≤ A i j) + (v : C → ℝ) (hv : ∀ i, 0 < v i) (hf : A *ᵥ v = v) : + ∃ U : Matrix C C ℝ, ∃ d : C → ℝ, + U.transpose * U = 1 ∧ (∀ i, |d i| ≤ 1) ∧ A = U * diagonal d * U.transpose := by + refine ⟨hA.eigenvectorUnitary, hA.eigenvalues, ?_, ?_, ?_⟩ + · simpa only [Matrix.star_eq_conjTranspose, Matrix.conjTranspose_eq_transpose_of_trivial] + using hA.eigenvectorUnitary.property.1 + · intro i + apply abs_eigenvalue_le_one_positive_fixed A hn v hv hf + apply Module.End.hasEigenvalue_of_hasEigenvector + refine ⟨?_, ?_⟩ + · rw [Module.End.mem_eigenspace_iff] + exact hA.mulVec_eigenvectorBasis i + · intro h + have he : hA.eigenvectorBasis i = 0 := by + exact PiLp.ext (fun j => congrFun h j) + exact (hA.eigenvectorBasis.orthonormal.ne_zero i) he + · simpa [Unitary.conjStarAlgAut_apply, Matrix.star_eq_conjTranspose, Matrix.conjTranspose_eq_transpose_of_trivial] + using hA.spectral_theorem + +end MatchingSmoothing + +namespace MatchingSmoothing +open Matrix +variable {H : Type u_2} {C : Type u_3} [Fintype H] [Fintype C] [DecidableEq H] [DecidableEq C] + +noncomputable def commonColoringsProdEquiv (σ : Equiv.Perm (H × Bool)) : + ({f : H × Bool → C // pairConstant f ∧ pairConstant (f ∘ σ)} × + {f : H × Bool → C // pairConstant f ∧ pairConstant (f ∘ σ)}) ≃ + {f : H × Bool → C × C // pairConstant f ∧ pairConstant (f ∘ σ)} where + toFun fg := ⟨fun v => (fg.1.1 v, fg.2.1 v), + ⟨fun i => Prod.ext (fg.1.2.1 i) (fg.2.2.1 i), + fun i => Prod.ext (fg.1.2.2 i) (fg.2.2.2 i)⟩⟩ + invFun f := (⟨fun v => (f.1 v).1, ⟨fun i => congrArg Prod.fst (f.2.1 i), + fun i => congrArg Prod.fst (f.2.2 i)⟩⟩, + ⟨fun v => (f.1 v).2, ⟨fun i => congrArg Prod.snd (f.2.1 i), + fun i => congrArg Prod.snd (f.2.2 i)⟩⟩) + left_inv _ := rfl + right_inv _ := rfl + +lemma commonColorings_square (σ : Equiv.Perm (H × Bool)) : + (Fintype.card {f : H × Bool → C // pairConstant f ∧ pairConstant (f ∘ σ)}) ^ 2 = + Fintype.card {f : H × Bool → C × C // pairConstant f ∧ pairConstant (f ∘ σ)} := by + rw [pow_two, ← Fintype.card_prod] + exact Fintype.card_congr (commonColoringsProdEquiv σ) + +omit [Fintype C] [DecidableEq H] [DecidableEq C] in +lemma pairWeight_nonneg (A : Matrix C C ℝ) (hn : ∀ i j, 0 ≤ A i j) + (f : H × Bool → C) : 0 ≤ pairWeight A f := by + exact Finset.prod_nonneg (fun _ _ => hn _ _) + +lemma pairWeight_overlap_square_moment (A : Matrix C C ℝ) + (hA : A.IsHermitian) (hn : ∀ i j, 0 ≤ A i j) + (v : C → ℝ) (hv : ∀ i, 0 < v i) (hf : A *ᵥ v = v) : + (∑ σ : Equiv.Perm (H × Bool), + (∑ f : H × Bool → C, pairWeight A f * pairWeight A (f ∘ σ)) ^ 2) ≤ + (Fintype.card (Equiv.Perm (H × Bool)) : ℝ) * + (Fintype.card H + 1 : ℝ) ^ (Fintype.card C) ^ 2 := by + obtain ⟨U, d, hU, hd, he⟩ := exists_orthogonal_diagonalization_bounded A hA hn v hv hf + have hp (σ : Equiv.Perm (H × Bool)) : + (∑ f : H × Bool → C, pairWeight A f * pairWeight A (f ∘ σ)) ^ 2 ≤ + (Fintype.card {f : H × Bool → C × C // pairConstant f ∧ pairConstant (f ∘ σ)} : ℝ) := by + rw [← commonColorings_square, Nat.cast_pow] + apply pow_le_pow_left₀ + · exact Finset.sum_nonneg (fun f _ => mul_nonneg (pairWeight_nonneg A hn f) + (pairWeight_nonneg A hn (f ∘ σ))) + · rw [he] + exact pairWeight_overlap_le U d hU hd σ + have h := (Finset.sum_le_sum (fun σ (_ : σ ∈ Finset.univ) => hp σ)).trans + (common_pairColorings_moment (H := H) (β := C × C)) + simpa only [Fintype.card_prod, pow_two] using h + +noncomputable def normalizedPairMatrix (γ : Matrix C C ℝ) (π : C → ℝ) : Matrix C C ℝ := + fun i j => γ i j / (Real.sqrt (π i) * Real.sqrt (π j)) + +omit [Fintype C] [DecidableEq C] in +lemma normalizedPairMatrix_nonneg (γ : Matrix C C ℝ) (π : C → ℝ) + (hn : ∀ i j, 0 ≤ γ i j) : ∀ i j, 0 ≤ normalizedPairMatrix γ π i j := by + intro i j + exact div_nonneg (hn i j) (mul_nonneg (Real.sqrt_nonneg _) (Real.sqrt_nonneg _)) + +omit [Fintype C] [DecidableEq C] in +lemma normalizedPairMatrix_hermitian (γ : Matrix C C ℝ) (π : C → ℝ) + (hs : γ.IsHermitian) : (normalizedPairMatrix γ π).IsHermitian := by + rw [Matrix.IsHermitian.ext_iff] at hs ⊢ + intro i j + simp only [star_trivial] at hs ⊢ + simp only [normalizedPairMatrix, hs j i, mul_comm] + +omit [DecidableEq C] in +lemma normalizedPairMatrix_fixed (γ : Matrix C C ℝ) (π : C → ℝ) + (hp : ∀ i, 0 < π i) (hs : ∀ i, ∑ j, γ i j = π i) : + normalizedPairMatrix γ π *ᵥ (fun i => Real.sqrt (π i)) = fun i => Real.sqrt (π i) := by + ext i + have he (j : C) : γ i j / (Real.sqrt (π i) * Real.sqrt (π j)) * Real.sqrt (π j) = + γ i j / Real.sqrt (π i) := by + field_simp [ne_of_gt (Real.sqrt_pos.mpr (hp j)), ne_of_gt (Real.sqrt_pos.mpr (hp i))] + change ∑ j, γ i j / (Real.sqrt (π i) * Real.sqrt (π j)) * Real.sqrt (π j) = _ + simp_rw [he] + rw [← Finset.sum_div, hs] + exact (div_eq_iff (ne_of_gt (Real.sqrt_pos.mpr (hp i)))).mpr + (Real.mul_self_sqrt (hp i).le).symm + +end MatchingSmoothing + +end OAI diff --git a/lean/OAI/Combinatorics/MatchingPSD/TightMatchings.lean b/lean/OAI/Combinatorics/MatchingPSD/TightMatchings.lean new file mode 100644 index 0000000000000000000000000000000000000000..73f133bd5f76c0aff4864e8a7cefa2f51a8d5c56 --- /dev/null +++ b/lean/OAI/Combinatorics/MatchingPSD/TightMatchings.lean @@ -0,0 +1,78 @@ +import Mathlib +import OAI.Combinatorics.MatchingPSD.AdmissibleTables +import OAI.Combinatorics.MatchingPSD.MatchingConversion +import OAI.Combinatorics.MatchingPSD.MatchingIncidence + +namespace OAI + +namespace PerfectMatchingPSD +open MatchingSmoothing Finset Matrix +open scoped BigOperators + +lemma oddCut_has_tight_matching {n : ℕ} (he : Even n) (U : OddCut n) : + ∃ M : PerfectMatching n, slack (Sum.inr U) M = 0 := by + classical + have hu := U.2 + obtain ⟨a, ha⟩ := hu + have hcomp : Odd (n - U.1.card) := by + have hle : U.1.card ≤ n := by simpa using Finset.card_le_univ U.1 + rw [Nat.odd_iff] + obtain ⟨k, hk⟩ := he + omega + obtain ⟨b, hb⟩ := hcomp + let z : Fin n → Fin 3 := fun v => if v ∈ U.1 then 0 else 1 + let E : Fin 6 → ℕ := ![a, 1, 0, b, 0, 0] + have hh : histogram z = endpointSizes E := by + ext c + fin_cases c + · simp [histogram, z, endpointSizes, E, ← ha] + · have hc : U.1ᶜ.card = n - U.1.card := by simp [Finset.card_compl] + simp only [histogram, z, endpointSizes, E, Matrix.cons_val_one, + Matrix.cons_val_zero] + simp + omega + · simp [histogram, z, endpointSizes, E, ite_eq_iff] + obtain ⟨M, hM⟩ := exists_pairing_of_endpoints z E hh + refine ⟨fromPairing M, ?_⟩ + have hcross := hM 0 + have heq : (crossingCount U.1 (fromPairing M) : ℝ) = crossCoordinate z 0 M := by + rw [crossingCount_fromPairing] + simp [crossCoordinate, crossPair, tableCoordinate, z, Fintype.card_subtype, + Finset.sum_boole] + change (crossingCount U.1 (fromPairing M) : ℝ) - 1 = 0 + rw [heq, hcross] + simp [E] + +lemma edge_has_tight_matching {n : ℕ} (hn : 4 ≤ n) (he : Even n) (e : Edge n) : + ∃ M : PerfectMatching n, slack (Sum.inl e) M = 0 := by + classical + obtain ⟨k, hk⟩ := he + let f : (Fin k × Bool) ≃ Fin n := Fintype.equivOfCardEq (by + simp only [Fintype.card_prod, Fintype.card_fin, Fintype.card_bool] + omega) + let P : Pairing (Fin n) := Pairing.transport f standardPairing + by_cases hP : P.1 e.1.1 = e.1.2 + · have hcard : ({e.1.1, e.1.2} : Finset (Fin n)).card < + (Finset.univ : Finset (Fin n)).card := by + have hh := Finset.card_le_two (a := e.1.1) (b := e.1.2) + simpa using lt_of_le_of_lt hh (show 2 < n by omega) + obtain ⟨c, _, hc⟩ := Finset.exists_mem_notMem_of_card_lt_card hcard + have hca : c ≠ e.1.1 := by simpa using (not_or.mp (by simpa using hc)).1 + have hcb : c ≠ e.1.2 := by simpa using (not_or.mp (by simpa using hc)).2 + let Q := Pairing.relabel (Equiv.swap e.1.2 c) P + have hQ : Q.1 e.1.1 = c := by + simp [Q, Equiv.swap_apply_of_ne_of_ne (ne_of_lt e.2) hca.symm, hP] + refine ⟨fromPairing Q, ?_⟩ + simp [slack, mem_fromPairing, hQ, hcb] + · refine ⟨fromPairing P, ?_⟩ + simp [slack, mem_fromPairing, hP] + +lemma row_has_tight_matching {n : ℕ} (hn : 4 ≤ n) (he : Even n) (i : Row n) : + ∃ M : PerfectMatching n, slack i M = 0 := by + cases i with + | inl e => exact edge_has_tight_matching hn he e + | inr U => exact oddCut_has_tight_matching he U + +end PerfectMatchingPSD + +end OAI diff --git a/lean/OAI/Combinatorics/MatchingPSD/TransitionMatrices.lean b/lean/OAI/Combinatorics/MatchingPSD/TransitionMatrices.lean new file mode 100644 index 0000000000000000000000000000000000000000..405a787a7f9c05320ee689a8a518463b09520d6a --- /dev/null +++ b/lean/OAI/Combinatorics/MatchingPSD/TransitionMatrices.lean @@ -0,0 +1,151 @@ +import OAI.Combinatorics.MatchingPSD.ColoringCounts + +namespace OAI + +universe u_1 u_2 u_3 + +namespace MatchingSmoothing +open Matrix + +variable {V : Type u_1} {C : Type u_2} [Fintype V] [Fintype C] [DecidableEq V] [DecidableEq C] + +noncomputable def tensorKernel (U : Matrix C C ℝ) : Matrix (V → C) (V → C) ℝ := + fun f g => ∏ v, U (f v) (g v) + +omit [DecidableEq C] in +lemma tensorKernel_mul (U W : Matrix C C ℝ) : + tensorKernel (V := V) (U * W) = tensorKernel (V := V) U * tensorKernel W := by + classical + ext f g + simp only [tensorKernel, Matrix.mul_apply] + rw [Fintype.prod_sum] + apply Finset.sum_congr rfl + intro h _ + exact Finset.prod_mul_distrib + +omit [Fintype C] [DecidableEq V] [DecidableEq C] in +lemma tensorKernel_transpose (U : Matrix C C ℝ) : + tensorKernel (V := V) U.transpose = (tensorKernel U).transpose := rfl + +omit [Fintype C] [DecidableEq V] in +lemma tensorKernel_one : + tensorKernel (V := V) (1 : Matrix C C ℝ) = 1 := by + classical + ext f g + by_cases h : f = g + · subst g; simp [tensorKernel] + · have he : ∃ v, f v ≠ g v := Function.ne_iff.mp h + obtain ⟨v, hv⟩ := he + simp only [tensorKernel, Matrix.one_apply, ite_eq_right h] + apply Finset.prod_eq_zero (Finset.mem_univ v) + simp [hv] + +lemma tensorKernel_orthogonal (U : Matrix C C ℝ) + (hU : U.transpose * U = 1) : + (tensorKernel (V := V) U).transpose * tensorKernel (V := V) U = 1 := by + rw [← tensorKernel_transpose, ← tensorKernel_mul, hU, tensorKernel_one] + +lemma tensorKernel_overlap (U : Matrix C C ℝ) + (hU : U.transpose * U = 1) (x y : (V → C) → ℝ) : + (tensorKernel U *ᵥ x) ⬝ᵥ (tensorKernel U *ᵥ y) = x ⬝ᵥ y := by + rw [Matrix.dotProduct_mulVec, Matrix.vecMul_mulVec, tensorKernel_orthogonal U hU, + Matrix.vecMul_one] + +omit [Fintype C] [DecidableEq V] [DecidableEq C] in +lemma tensorKernel_relabel (U : Matrix C C ℝ) (σ : Equiv.Perm V) (f g : V → C) : + tensorKernel U (f ∘ σ) (g ∘ σ) = tensorKernel U f g := by + exact Equiv.prod_comp σ (fun v => U (f v) (g v)) + +omit [DecidableEq C] in +lemma tensorKernel_mulVec_relabel (U : Matrix C C ℝ) (σ : Equiv.Perm V) + (x : (V → C) → ℝ) (f : V → C) : + (tensorKernel U *ᵥ (fun g => x (g ∘ σ))) f = + (tensorKernel U *ᵥ x) (f ∘ σ) := by + classical + let e : (V → C) ≃ (V → C) := Equiv.arrowCongr σ (Equiv.refl C) + change ∑ g, tensorKernel U f g * x (g ∘ σ) = + ∑ g, tensorKernel U (f ∘ σ) g * x g + refine Fintype.sum_equiv e.symm _ _ ?_ + intro g + have he : e.symm g = g ∘ σ := rfl + rw [he, tensorKernel_relabel] + +variable {H : Type u_3} [Fintype H] [DecidableEq H] + +noncomputable def pairDiagonal (d : C → ℝ) (f : H × Bool → C) : ℝ := + if pairConstant f then ∏ i, d (f (i, false)) else 0 + +noncomputable def pairWeight (A : Matrix C C ℝ) (f : H × Bool → C) : ℝ := + ∏ i, A (f (i, false)) (f (i, true)) + +lemma tensorKernel_mulVec_pairDiagonal (U : Matrix C C ℝ) (d : C → ℝ) + (f : H × Bool → C) : + (tensorKernel U *ᵥ pairDiagonal d) f = + pairWeight (U * diagonal d * U.transpose) f := by + classical + change ∑ g, (∏ v, U (f v) (g v)) * + (if pairConstant g then ∏ i, d (g (i, false)) else 0) = _ + simp only [mul_ite, mul_zero] + rw [sum_pairConstant] + simp only [duplicateColoring, Fintype.prod_prod_type, Fintype.prod_bool] + have hm (a b : C) : (U * diagonal d * U.transpose) a b = + ∑ c, U a c * d c * U b c := by + rw [Matrix.mul_apply] + simp only [Matrix.mul_diagonal, Matrix.transpose_apply] + simp only [pairWeight, hm] + rw [Fintype.prod_sum] + apply Finset.sum_congr rfl + intro g _ + rw [← Finset.prod_mul_distrib] + apply Finset.prod_congr rfl + intro i _ + ring + +lemma pairWeight_overlap (U : Matrix C C ℝ) (d : C → ℝ) + (hU : U.transpose * U = 1) (σ : Equiv.Perm (H × Bool)) : + (∑ f : H × Bool → C, pairWeight (U * diagonal d * U.transpose) f * + pairWeight (U * diagonal d * U.transpose) (f ∘ σ)) = + ∑ f : H × Bool → C, pairDiagonal d f * pairDiagonal d (f ∘ σ) := by + simp_rw [← tensorKernel_mulVec_pairDiagonal, + ← tensorKernel_mulVec_relabel U σ (pairDiagonal d)] + exact tensorKernel_overlap U hU _ _ + +omit [Fintype C] [DecidableEq H] in +lemma pairDiagonal_abs_le (d : C → ℝ) (hd : ∀ c, |d c| ≤ 1) (f : H × Bool → C) : + |pairDiagonal d f| ≤ 1 := by + classical + unfold pairDiagonal + split_ifs + · rw [Finset.abs_prod] + exact Finset.prod_le_one₀ (fun _ _ => abs_nonneg _) (fun _ _ => hd _) + · simp + +lemma pairWeight_overlap_le (U : Matrix C C ℝ) (d : C → ℝ) + (hU : U.transpose * U = 1) (hd : ∀ c, |d c| ≤ 1) + (σ : Equiv.Perm (H × Bool)) : + (∑ f : H × Bool → C, pairWeight (U * diagonal d * U.transpose) f * + pairWeight (U * diagonal d * U.transpose) (f ∘ σ)) ≤ + (Fintype.card {f : H × Bool → C // pairConstant f ∧ pairConstant (f ∘ σ)} : ℝ) := by + classical + rw [pairWeight_overlap U d hU σ] + have he : (Fintype.card {f : H × Bool → C // pairConstant f ∧ pairConstant (f ∘ σ)} : ℝ) = + ∑ f : H × Bool → C, if pairConstant f ∧ pairConstant (f ∘ σ) then (1 : ℝ) else 0 := by + simp only [Fintype.card_subtype, Finset.card_filter, Nat.cast_sum] + apply Finset.sum_congr rfl + intro f _ + split_ifs <;> norm_num + rw [he] + apply Finset.sum_le_sum + intro f _ + by_cases hf : pairConstant f ∧ pairConstant (f ∘ σ) + · rw [ite_eq_left hf] + exact (le_abs_self _).trans (by + rw [abs_mul] + exact (mul_le_mul (pairDiagonal_abs_le d hd f) + (pairDiagonal_abs_le d hd (f ∘ σ)) (abs_nonneg _) zero_le_one).trans_eq (mul_one _)) + · rw [ite_eq_right hf] + rcases not_and_or.mp hf with hf | hf <;> simp [pairDiagonal, hf] + +end MatchingSmoothing + +end OAI diff --git a/lean/OAI/Combinatorics/MatchingPSD/TypeProbabilities.lean b/lean/OAI/Combinatorics/MatchingPSD/TypeProbabilities.lean new file mode 100644 index 0000000000000000000000000000000000000000..1455eae0c0d9b760635660f8be784fb9e52ed9ad --- /dev/null +++ b/lean/OAI/Combinatorics/MatchingPSD/TypeProbabilities.lean @@ -0,0 +1,197 @@ +import OAI.Combinatorics.MatchingPSD.TensorBounds + +namespace OAI + +universe u_1 u_2 u_3 u_4 u_5 u_6 u_7 + +namespace MatchingSmoothing + +lemma pow_mul_factorial_le_mode (t j : ℕ) : + t ^ j * t.factorial ≤ t ^ t * j.factorial := by + rcases le_total j t with hj | ht + · have he : t.factorial = j.factorial * t.descFactorial (t - j) := by + simpa only [Nat.sub_sub_self hj] using + (Nat.factorial_mul_descFactorial (Nat.sub_le t j)).symm + calc + t ^ j * t.factorial = t ^ j * (j.factorial * t.descFactorial (t - j)) := by rw [he] + _ ≤ t ^ j * (j.factorial * t ^ (t - j)) := by + gcongr; exact Nat.descFactorial_le_pow _ _ + _ = t ^ t * j.factorial := by + rw [mul_comm j.factorial (t ^ (t - j)), ← mul_assoc, ← pow_add, Nat.add_sub_of_le hj] + · have he : j.factorial = t.factorial * (t + 1).ascFactorial (j - t) := by + simpa only [Nat.add_sub_of_le ht] using (Nat.factorial_mul_ascFactorial t (j - t)).symm + have hp : t ^ (j - t) ≤ (t + 1).ascFactorial (j - t) := + (Nat.pow_le_pow_left (Nat.le_succ t) _).trans (Nat.pow_succ_le_ascFactorial _ _) + calc + t ^ j * t.factorial = t ^ t * (t.factorial * t ^ (j - t)) := by + rw [mul_comm t.factorial (t ^ (j - t)), ← mul_assoc, ← pow_add, Nat.add_sub_of_le ht] + _ ≤ t ^ t * (t.factorial * (t + 1).ascFactorial (j - t)) := by gcongr + _ = t ^ t * j.factorial := by rw [he] + +lemma poisson_mass_le_integer_mode (t j : ℕ) : + (t : ℝ) ^ j / j.factorial ≤ (t : ℝ) ^ t / t.factorial := by + apply (div_le_div_iff₀ (by positivity : (0 : ℝ) < j.factorial) + (by positivity : (0 : ℝ) < t.factorial)).mpr + exact_mod_cast pow_mul_factorial_le_mode t j + +lemma multinomial_term_eq {ι : Type u_1} (s : Finset ι) (k : ι → ℕ) (a : ι → ℝ) : + (Nat.multinomial s k : ℝ) * ∏ i ∈ s, a i ^ k i = + ((∑ i ∈ s, k i).factorial : ℝ) * ∏ i ∈ s, (a i ^ k i / (k i).factorial) := by + rw [Finset.prod_div_distrib] + have he : (∏ i ∈ s, ((k i).factorial : ℝ)) * Nat.multinomial s k = + ((∑ i ∈ s, k i).factorial : ℝ) := by exact_mod_cast Nat.multinomial_spec s k + rw [← he] + have hn : ∏ i ∈ s, ((k i).factorial : ℝ) ≠ 0 := + Finset.prod_ne_zero_iff.mpr (by intro i _; positivity) + field_simp + +lemma multinomial_term_le_mode {ι : Type u_2} (s : Finset ι) (t k : ι → ℕ) + (hk : ∑ i ∈ s, k i = ∑ i ∈ s, t i) : + (Nat.multinomial s k : ℝ) * ∏ i ∈ s, (t i : ℝ) ^ k i ≤ + (Nat.multinomial s t : ℝ) * ∏ i ∈ s, (t i : ℝ) ^ t i := by + rw [multinomial_term_eq, multinomial_term_eq, hk] + apply mul_le_mul_of_nonneg_left _ (by positivity) + apply Finset.prod_le_prod₀ + · intro i _; positivity + · intro i _; exact poisson_mass_le_integer_mode _ _ + +lemma card_piAntidiag_univ_le {ι : Type u_3} [Fintype ι] [DecidableEq ι] (n : ℕ) : + (Finset.piAntidiag (Finset.univ : Finset ι) n).card ≤ + (n + 1) ^ Fintype.card ι := by + classical + let s := Finset.piAntidiag (Finset.univ : Finset ι) n + have hn (k : s) (i : ι) : k.1 i ≤ n := by + have he := (Finset.mem_piAntidiag.mp k.2).1 + rw [← he] + exact Finset.single_le_sum (fun _ _ => Nat.zero_le _) (Finset.mem_univ i) + let e : s → (ι → Fin (n + 1)) := fun k i => ⟨k.1 i, Nat.lt_succ_of_le (hn k i)⟩ + have hi : Function.Injective e := by + intro k l h + apply Subtype.ext + funext i + exact congrArg Fin.val (congrFun h i) + simpa only [Fintype.card_coe, Fintype.card_fun, Fintype.card_fin] using + Fintype.card_le_of_injective e hi + +lemma multinomial_mode_lower {ι : Type u_4} [Fintype ι] [DecidableEq ι] + (t : ι → ℕ) (n : ℕ) (ht : ∑ i, t i = n) : + (n : ℝ) ^ n ≤ (n + 1 : ℝ) ^ Fintype.card ι * + ((Nat.multinomial Finset.univ t : ℝ) * ∏ i, (t i : ℝ) ^ t i) := by + have hs : ∑ i, (t i : ℝ) = n := by exact_mod_cast ht + conv_lhs => rw [← hs, Finset.sum_pow_eq_sum_piAntidiag] + calc + _ ≤ ∑ _k ∈ Finset.piAntidiag Finset.univ n, + (Nat.multinomial Finset.univ t : ℝ) * ∏ i, (t i : ℝ) ^ t i := by + apply Finset.sum_le_sum + intro k hk + apply multinomial_term_le_mode + exact (Finset.mem_piAntidiag.mp hk).1.trans ht.symm + _ = ((Finset.piAntidiag (Finset.univ : Finset ι) n).card : ℝ) * + ((Nat.multinomial Finset.univ t : ℝ) * ∏ i, (t i : ℝ) ^ t i) := by simp + _ ≤ _ := by + apply mul_le_mul_of_nonneg_right _ (by positivity) + exact_mod_cast card_piAntidiag_univ_le (ι := ι) n + +section ProductTypes +variable {H : Type u_5} {A : Type u_6} {T : Type u_7} [Fintype H] [DecidableEq H] [Fintype A] [Fintype T] + [DecidableEq A] [DecidableEq T] + +noncomputable def functionFiberEquiv (η : A → T) (k : H → T) : + {f : H → A // η ∘ f = k} ≃ ((i : H) → {a : A // η a = k i}) where + toFun f i := ⟨f.1 i, congrFun f.2 i⟩ + invFun g := ⟨fun i => (g i).1, funext (fun i => (g i).2)⟩ + left_inv _ := rfl + right_inv _ := rfl + +omit [Fintype T] [DecidableEq A] in +lemma card_functionFiber (η : A → T) (k : H → T) : + Fintype.card {f : H → A // η ∘ f = k} = + ∏ i, Fintype.card {a : A // η a = k i} := by + rw [Fintype.card_congr (functionFiberEquiv η k), Fintype.card_pi] + +omit [DecidableEq H] in +lemma prod_eq_prod_histogram (f : H → T) (w : T → ℝ) : + (∏ i, w (f i)) = ∏ t, w t ^ histogram f t := by + rw [← Fintype.prod_fiberwise f] + apply Finset.prod_congr rfl + intro t _ + have he (i : {i // f i = t}) : w (f i.1) = w t := congrArg w i.2 + simp only [he, Finset.prod_const, Finset.card_univ, histogram] + +omit [DecidableEq A] in +lemma sum_product_of_types (η : A → T) (q : T → ℝ) (F : (H → T) → ℝ) : + (∑ f : H → A, F (η ∘ f) * ∏ i, q (η (f i))) = + ∑ k : H → T, F k * ∏ i, ((Fintype.card {a : A // η a = k i} : ℝ) * q (k i)) := by + classical + rw [← Fintype.sum_fiberwise (fun f : H → A => η ∘ f)] + apply Finset.sum_congr rfl + intro k _ + have he (f : {f : H → A // η ∘ f = k}) : + F (η ∘ f.1) * ∏ i, q (η (f.1 i)) = F k * ∏ i, q (k i) := by + rw [f.2] + congr 1 + exact Finset.prod_congr rfl (fun i _ => congrArg q (congrFun f.2 i)) + simp_rw [he, Finset.sum_const, Finset.card_univ, nsmul_eq_mul] + rw [card_functionFiber, Nat.cast_prod, Finset.prod_mul_distrib] + ring + +omit [DecidableEq A] in +lemma sum_product_of_type_probabilities (η : A → T) (hη : Function.Surjective η) + (p : T → ℝ) (F : (H → T) → ℝ) : + (∑ f : H → A, F (η ∘ f) * + ∏ i, p (η (f i)) / Fintype.card {a : A // η a = η (f i)}) = + ∑ k : H → T, F k * ∏ i, p (k i) := by + rw [sum_product_of_types η + (fun t => p t / Fintype.card {a : A // η a = t}) F] + apply Finset.sum_congr rfl + intro k _ + congr 1 + apply Finset.prod_congr rfl + intro i _ + have hn : (Fintype.card {a : A // η a = k i} : ℝ) ≠ 0 := by + obtain ⟨a, ha⟩ := hη (k i) + exact_mod_cast ne_of_gt ((Fintype.card_pos_iff (α := {a : A // η a = k i})).mpr ⟨⟨a, ha⟩⟩) + field_simp + +omit [DecidableEq A] in +lemma sum_type_probability_eq_multinomial (η : A → T) (hη : Function.Surjective η) + (k₀ : H → T) (p : T → ℝ) : + (∑ f : H → A, (if histogram (η ∘ f) = histogram k₀ then (1 : ℝ) else 0) * + ∏ i, p (η (f i)) / Fintype.card {a : A // η a = η (f i)}) = + (Nat.multinomial Finset.univ (histogram k₀) : ℝ) * + ∏ t, p t ^ histogram k₀ t := by + classical + rw [sum_product_of_type_probabilities η hη p + (fun k => if histogram k = histogram k₀ then 1 else 0)] + simp only [ite_mul, one_mul, zero_mul] + rw [← Finset.sum_filter, ← Finset.sum_subtype_eq_sum_filter] + simp only [Finset.subtype_univ] + have he (k : Colorings H T (histogram k₀)) : + (∏ i, p (k.1 i)) = ∏ t, p t ^ histogram k₀ t := by + rw [prod_eq_prod_histogram, k.2] + simp_rw [he, Finset.sum_const, Finset.card_univ, nsmul_eq_mul, + card_colorings_eq_multinomial] + +omit [DecidableEq A] in +lemma integer_mean_type_probability_lower (η : A → T) (hη : Function.Surjective η) + (k₀ : H → T) (hH : 0 < Fintype.card H) : + 1 ≤ (Fintype.card H + 1 : ℝ) ^ Fintype.card T * + (∑ f : H → A, (if histogram (η ∘ f) = histogram k₀ then (1 : ℝ) else 0) * + ∏ i, ((histogram k₀ (η (f i)) : ℝ) / Fintype.card H) / + Fintype.card {a : A // η a = η (f i)}) := by + classical + rw [sum_type_probability_eq_multinomial η hη k₀ + (fun t => (histogram k₀ t : ℝ) / Fintype.card H)] + have hl := multinomial_mode_lower (histogram k₀) (Fintype.card H) (sum_histogram k₀) + simp_rw [div_pow] + rw [Finset.prod_div_distrib, Finset.prod_pow_eq_pow_sum, sum_histogram] + have hp : (0 : ℝ) < (Fintype.card H : ℝ) ^ Fintype.card H := by positivity + apply (mul_le_mul_iff_left₀ hp).mp + field_simp + nlinarith + +end ProductTypes + +end MatchingSmoothing + +end OAI diff --git a/lean/OAI/Combinatorics/MatrixRemoval/AnchorFrames.lean b/lean/OAI/Combinatorics/MatrixRemoval/AnchorFrames.lean new file mode 100644 index 0000000000000000000000000000000000000000..1a37cb069c482f5a7278ca1c4f0c1a18e6c6d05a --- /dev/null +++ b/lean/OAI/Combinatorics/MatrixRemoval/AnchorFrames.lean @@ -0,0 +1,153 @@ +import Mathlib + +namespace OAI + +/-! +Full row and column orders extending the variable order. +The raw carrier is the anchor / variable / dummy sum. +-/ + +universe uM uV uO + +namespace Problem348.AnchorFrames + +abbrev Raw (M : Type uM) (V : Type uV) (O : Type uO) := (M × Fin 64 × O) ⊕ (V ⊕ O) +abbrev AnchorOrder (M : Type uM) (O : Type uO) := M ×ₗ Fin 64 ×ₗ O +abbrev RowOrder (M : Type uM) (V : Type uV) (O : Type uO) := AnchorOrder M O ⊕ₗ (V ⊕ₗ O) +abbrev ColOrder (M : Type uM) (V : Type uV) (O : Type uO) := AnchorOrder M O ⊕ₗ (O ⊕ₗ V) + +/-- Coordinates for the row order: anchors, variables, dummy. -/ +def rowKey {M : Type uM} {V : Type uV} {O : Type uO} : Raw M V O → RowOrder M V O + | .inl (t, u, x) => .inlₗ (toLex (t, toLex (u, x))) + | .inr (.inl v) => .inrₗ (.inlₗ v) + | .inr (.inr x) => .inrₗ (.inrₗ x) + +/-- Coordinates for the column order: anchors, dummy, variables. -/ +def colKey {M : Type uM} {V : Type uV} {O : Type uO} : Raw M V O → ColOrder M V O + | .inl (t, u, x) => .inlₗ (toLex (t, toLex (u, x))) + | .inr (.inl v) => .inrₗ (.inrₗ v) + | .inr (.inr x) => .inrₗ (.inlₗ x) + +def rowEquiv (M : Type uM) (V : Type uV) (O : Type uO) : Raw M V O ≃ RowOrder M V O where + toFun := rowKey + invFun x := match ofLex x with + | .inl a => .inl ((ofLex a).1, (ofLex (ofLex a).2).1, (ofLex (ofLex a).2).2) + | .inr b => .inr (ofLex b) + left_inv := by rintro (⟨t,u,x⟩ | (v | x)) <;> rfl + right_inv := by rintro (⟨t,u,x⟩ | (v | x)) <;> rfl + +def colEquiv (M : Type uM) (V : Type uV) (O : Type uO) : Raw M V O ≃ ColOrder M V O where + toFun := colKey + invFun x := match ofLex x with + | .inl a => .inl ((ofLex a).1, (ofLex (ofLex a).2).1, (ofLex (ofLex a).2).2) + | .inr b => match ofLex b with + | .inl x => .inr (.inr x) + | .inr v => .inr (.inl v) + left_inv := by rintro (⟨t,u,x⟩ | (v | x)) <;> rfl + right_inv := by rintro (⟨t,u,x⟩ | (x | v)) <;> rfl + +section Orders +variable {M : Type uM} {V : Type uV} {O : Type uO} [LinearOrder M] [LinearOrder V] [LinearOrder O] + +/-- The full raw row order, suitable for local instance installation. -/ +abbrev rowOrder : LinearOrder (Raw M V O) := LinearOrder.lift' rowKey (rowEquiv M V O).injective + +/-- The full raw column order, suitable for local instance installation. -/ +abbrev colOrder : LinearOrder (Raw M V O) := LinearOrder.lift' colKey (colEquiv M V O).injective + +/-- Arbitrary offsets in successive groups give increasing selected anchors. -/ +theorem row_anchor_strictMono (t : M) (a : Fin 64 → O) : + StrictMono (fun u => rowKey (M := M) (V := V) (.inl (t, u, a u))) := by + intro u v huv + change Sum.Lex _ _ _ _ + apply Sum.Lex.inl + apply Prod.Lex.right + exact Prod.Lex.left _ _ huv + +theorem col_anchor_strictMono (t : M) (a : Fin 64 → O) : + StrictMono (fun u => colKey (M := M) (V := V) (.inl (t, u, a u))) := by + intro u v huv + change Sum.Lex _ _ _ _ + apply Sum.Lex.inl + apply Prod.Lex.right + exact Prod.Lex.left _ _ huv + +theorem row_anchor_lt_nonanchor (t : M) (u : Fin 64) (a : O) (x : V ⊕ O) : + rowKey (.inl (t,u,a)) < rowKey (.inr x) := by + cases x <;> exact Sum.Lex.sep _ _ + +theorem col_anchor_lt_nonanchor (t : M) (u : Fin 64) (a : O) (x : V ⊕ O) : + colKey (.inl (t,u,a)) < colKey (.inr x) := by + cases x <;> exact Sum.Lex.sep _ _ + +theorem row_variable_lt_dummy (v : V) (x : O) : + rowKey (M := M) (.inr (.inl v)) < rowKey (.inr (.inr x)) := + Sum.Lex.inr (Sum.Lex.sep _ _) + +theorem col_dummy_lt_variable (v : V) (x : O) : + colKey (M := M) (.inr (.inr x)) < colKey (.inr (.inl v)) := + Sum.Lex.inr (Sum.Lex.sep _ _) + +@[simp] theorem row_variable_lt_variable (v w : V) : + rowKey (M := M) (O := O) (.inr (.inl v)) < rowKey (.inr (.inl w)) ↔ v < w := by + simp [rowKey] + +@[simp] theorem col_variable_lt_variable (v w : V) : + colKey (M := M) (O := O) (.inr (.inl v)) < colKey (.inr (.inl w)) ↔ v < w := by + simp [colKey] + +/-- The anchor region is an initial segment of the complete row axis. -/ +theorem row_not_nonanchor_lt_anchor (t : M) (u : Fin 64) (a : O) (x : V ⊕ O) : + ¬ rowKey (.inr x) < rowKey (.inl (t,u,a)) := + not_lt_of_gt (row_anchor_lt_nonanchor t u a x) + +/-- The anchor region is also an initial segment of the complete column axis. -/ +theorem col_not_nonanchor_lt_anchor (t : M) (u : Fin 64) (a : O) (x : V ⊕ O) : + ¬ colKey (.inr x) < colKey (.inl (t,u,a)) := + not_lt_of_gt (col_anchor_lt_nonanchor t u a x) + +/-- Within one mode, increasing selected anchors have nondecreasing group labels. -/ +theorem row_group_le_of_lt (t : M) (u v : Fin 64) (a b : O) + (hab : rowKey (V := V) (.inl (t,u,a)) < rowKey (.inl (t,v,b))) : u ≤ v := by + have h : toLex (u,a) < toLex (v,b) := by + simpa [rowKey, Prod.Lex.lt_iff] using hab + exact (Prod.Lex.monotone_fst_ofLex h.le) + +theorem col_group_le_of_lt (t : M) (u v : Fin 64) (a b : O) + (hab : colKey (V := V) (.inl (t,u,a)) < colKey (.inl (t,v,b))) : u ≤ v := by + have h : toLex (u,a) < toLex (v,b) := by + simpa [colKey, Prod.Lex.lt_iff] using hab + exact (Prod.Lex.monotone_fst_ofLex h.le) + +/-- Selected anchor rows after the full axis has been enumerated by `Fin n`. -/ +def selectedRows {n : ℕ} (e : Fin n ≃o RowOrder M V O) + (t : M) (a : Fin 64 → O) : Fin 64 → Fin n := + fun u => e.symm (rowKey (.inl (t, u, a u))) + +/-- Selected anchor columns after the full axis has been enumerated by `Fin n`. -/ +def selectedCols {n : ℕ} (e : Fin n ≃o ColOrder M V O) + (t : M) (a : Fin 64 → O) : Fin 64 → Fin n := + fun u => e.symm (colKey (.inl (t, u, a u))) + +theorem selectedRows_strictMono {n : ℕ} (e : Fin n ≃o RowOrder M V O) + (t : M) (a : Fin 64 → O) : StrictMono (selectedRows e t a) := + e.symm.strictMono.comp (row_anchor_strictMono t a) + +theorem selectedCols_strictMono {n : ℕ} (e : Fin n ≃o ColOrder M V O) + (t : M) (a : Fin 64 → O) : StrictMono (selectedCols e t a) := + e.symm.strictMono.comp (col_anchor_strictMono t a) + +theorem selectedRows_lt_nonanchor {n : ℕ} (e : Fin n ≃o RowOrder M V O) + (t : M) (a : Fin 64 → O) (u : Fin 64) (x : V ⊕ O) : + selectedRows e t a u < e.symm (rowKey (.inr x)) := + e.symm.strictMono (row_anchor_lt_nonanchor t u (a u) x) + +theorem selectedCols_lt_nonanchor {n : ℕ} (e : Fin n ≃o ColOrder M V O) + (t : M) (a : Fin 64 → O) (u : Fin 64) (x : V ⊕ O) : + selectedCols e t a u < e.symm (colKey (.inr x)) := + e.symm.strictMono (col_anchor_lt_nonanchor t u (a u) x) + +end Orders +end Problem348.AnchorFrames + +end OAI diff --git a/lean/OAI/Combinatorics/MatrixRemoval/AnchorGroups.lean b/lean/OAI/Combinatorics/MatrixRemoval/AnchorGroups.lean new file mode 100644 index 0000000000000000000000000000000000000000..08e3024ad5704ec12819e2f7cb8184e6377412b1 --- /dev/null +++ b/lean/OAI/Combinatorics/MatrixRemoval/AnchorGroups.lean @@ -0,0 +1,175 @@ +import Mathlib + +namespace OAI + +/-! +# Ordered exhaustion of anchor groups + +Once one mode is known, identical host rows within each group and distinct +pattern rows prevent repeated groups. The group order then forces the +selected group map to be the identity. +-/ + +universe uI uJ uR uC uG uL uT + +namespace Problem348.AnchorGroups + +/-- Distinct pattern rows force distinct selected group labels whenever equal +labels give identical rows against the selected columns. -/ +theorem labels_injective {I : Type uI} {J : Type uJ} {R : Type uR} {C : Type uC} {G : Type uG} + (S : I → J → Bool) (A : R → C → Bool) + (r : I → R) (c : J → C) (g : I → G) + (hrows : Function.Injective S) + (hcopy : ∀ i j, A (r i) (c j) = S i j) + (htwin : ∀ i i', g i = g i' → ∀ j, + A (r i) (c j) = A (r i') (c j)) : + Function.Injective g := by + intro i i' h + apply hrows + funext j + rw [← hcopy i j, ← hcopy i' j] + exact htwin i i' h j + +/-- Equal host rows belonging to a fixed twin class cannot both be selected +by a pattern with distinct rows. This applies both to anchor groups and to the +dummy block, even before a common mode has been established. -/ +theorem same_twin_class_index_eq {I : Type uI} {J : Type uJ} {R : Type uR} {C : Type uC} + (S : I → J → Bool) (A : R → C → Bool) + (r : I → R) (c : J → C) (P : R → Prop) + (hrows : Function.Injective S) + (hcopy : ∀ i j, A (r i) (c j) = S i j) + (htwin : ∀ x y, P x → P y → ∀ z, A x z = A y z) + {i i' : I} (hi : P (r i)) (hi' : P (r i')) : i = i' := by + apply hrows + funext j + rw [← hcopy i j, ← hcopy i' j] + exact htwin (r i) (r i') hi hi' (c j) + +/-- Before all selected positions are pinned, the partial anchor label is +already injective on the selected anchor positions. Nonanchor labels are not +required to be injective. -/ +theorem partial_labels_injOn {I : Type uI} {J : Type uJ} {R : Type uR} {C : Type uC} {L : Type uL} + (S : I → J → Bool) (A : R → C → Bool) + (r : I → R) (c : J → C) (label : R → Option L) + (hrows : Function.Injective S) + (hcopy : ∀ i j, A (r i) (c j) = S i j) + (htwin : ∀ x y l, label x = some l → label y = some l → + ∀ z, A x z = A y z) : + Set.InjOn (fun i => label (r i)) {i | ∃ l, label (r i) = some l} := by + intro i hi i' _ heq + obtain ⟨l, hl⟩ := hi + have hl' : label (r i') = some l := heq.symm.trans hl + apply hrows + funext j + rw [← hcopy i j, ← hcopy i' j] + exact htwin (r i) (r i') l hl hl' (c j) + +/-- At most one selected position belongs to any host row twin class. -/ +theorem selected_twin_class_card_le_one {I : Type uI} {J : Type uJ} {R : Type uR} {C : Type uC} [Fintype I] + (S : I → J → Bool) (A : R → C → Bool) + (r : I → R) (c : J → C) (P : R → Prop) [DecidablePred P] + (hrows : Function.Injective S) + (hcopy : ∀ i j, A (r i) (c j) = S i j) + (htwin : ∀ x y, P x → P y → ∀ z, A x z = A y z) : + (Finset.univ.filter (fun i => P (r i))).card ≤ 1 := by + apply Finset.card_le_one.mpr + intro i hi i' hi' + exact same_twin_class_index_eq S A r c P hrows hcopy htwin + (Finset.mem_filter.mp hi).2 (Finset.mem_filter.mp hi').2 + +/-- Unit-vector incidences contribute at most one true entry per participating +mode after selected anchor groups have been shown distinct. This is the +counting bridge from the concrete mode-support bound to rigidity's sparsity +hypothesis. -/ +theorem true_entries_le_supported_modes {I : Type uI} {T : Type uT} {G : Type uG} + (selected : Finset I) (mode : I → T) (group : I → G) + (entry : I → Bool) (support : Finset T) + (hgroups : Set.InjOn (fun i => (mode i, group i)) (↑selected : Set I)) + (hunit : ∀ i ∈ selected, ∀ j ∈ selected, + entry i = true → entry j = true → mode i = mode j → group i = group j) + (hsupport : ∀ i ∈ selected, entry i = true → mode i ∈ support) : + (selected.filter (fun i => entry i = true)).card ≤ support.card := by + classical + apply Finset.card_le_card_of_injOn mode + · intro i hi + obtain ⟨his, hie⟩ := Finset.mem_filter.mp hi + exact hsupport i his hie + · intro i hi j hj hij + obtain ⟨his, hie⟩ := Finset.mem_filter.mp hi + obtain ⟨hjs, hje⟩ := Finset.mem_filter.mp hj + apply hgroups his hjs + exact Prod.ext hij (hunit i his j hjs hie hje hij) + +/-- An increasing injective enumeration of a finite ordered set is its +prescribed enumeration. -/ +theorem monotone_injective_eq_id {I : Type uI} [LinearOrder I] [Finite I] + (g : I → I) (hmono : Monotone g) (hinj : Function.Injective g) : + ∀ i, g i = i := by + let f : I →o I := ⟨g, hmono⟩ + have hf : f = OrderHom.id := OrderHom.eq_id_of_injective f hinj + intro i + exact congrArg (fun q : I →o I => q i) hf + +/-- Ordered group exhaustion for a copied pattern with distinct rows. -/ +theorem group_eq_index {I : Type uI} {J : Type uJ} {R : Type uR} {C : Type uC} [LinearOrder I] [Finite I] + (S : I → J → Bool) (A : R → C → Bool) + (r : I → R) (c : J → C) (g : I → I) + (hrows : Function.Injective S) + (hcopy : ∀ i j, A (r i) (c j) = S i j) + (htwin : ∀ i i', g i = g i' → ∀ j, + A (r i) (c j) = A (r i') (c j)) + (hmono : Monotone g) : ∀ i, g i = i := + monotone_injective_eq_id g hmono + (labels_injective S A r c g hrows hcopy htwin) + +/-- Host-facing formulation: anchor labels record a mode and a group. Once +all selected rows are anchors of one mode, their group labels equal their +pattern indices. The column version follows by transposition. -/ +theorem row_labels_eq {k : ℕ} {J : Type uJ} {R : Type uR} {C : Type uC} {T : Type uT} [LinearOrder R] + (S : Fin k → J → Bool) (A : R → C → Bool) + (label : R → Option (T × Fin k)) + (r : Fin k → R) (c : J → C) (t : T) + (hr : StrictMono r) + (hrows : Function.Injective S) + (hcopy : ∀ i j, A (r i) (c j) = S i j) + (hmode : ∀ i, ∃ u, label (r i) = some (t, u)) + (htwin : ∀ x y u, label x = some (t, u) → + label y = some (t, u) → ∀ z, A x z = A y z) + (horder : ∀ x y u v, x < y → label x = some (t, u) → + label y = some (t, v) → u ≤ v) : + ∀ i, label (r i) = some (t, i) := by + classical + choose g hg using hmode + have hmono : Monotone g := by + intro i j hij + rcases eq_or_lt_of_le hij with h | h + · subst j + exact le_rfl + · exact horder (r i) (r j) (g i) (g j) (hr h) (hg i) (hg j) + have heq : ∀ i, g i = i := group_eq_index S A r c g hrows hcopy + (by + intro i j hij z + exact htwin (r i) (r j) (g i) (hg i) (hij ▸ hg j) (c z)) hmono + intro i + simpa only [heq i] using hg i + +/-- Transposed host-facing formulation for the selected columns. -/ +theorem column_labels_eq {k : ℕ} {I : Type uI} {R : Type uR} {C : Type uC} {T : Type uT} [LinearOrder C] + (S : I → Fin k → Bool) (A : R → C → Bool) + (label : C → Option (T × Fin k)) + (r : I → R) (c : Fin k → C) (t : T) + (hc : StrictMono c) + (hcols : Function.Injective (fun j i => S i j)) + (hcopy : ∀ i j, A (r i) (c j) = S i j) + (hmode : ∀ j, ∃ v, label (c j) = some (t, v)) + (htwin : ∀ x y v, label x = some (t, v) → + label y = some (t, v) → ∀ z, A z x = A z y) + (horder : ∀ x y u v, x < y → label x = some (t, u) → + label y = some (t, v) → u ≤ v) : + ∀ j, label (c j) = some (t, j) := by + exact row_labels_eq (fun j i => S i j) (fun y x => A x y) + label c r t hc hcols (fun j i => hcopy i j) hmode htwin horder + +end Problem348.AnchorGroups + +end OAI diff --git a/lean/OAI/Combinatorics/MatrixRemoval/AnchorPatternBridge.lean b/lean/OAI/Combinatorics/MatrixRemoval/AnchorPatternBridge.lean new file mode 100644 index 0000000000000000000000000000000000000000..8f63912182c1f669000932e436c5e2a2450778cb --- /dev/null +++ b/lean/OAI/Combinatorics/MatrixRemoval/AnchorPatternBridge.lean @@ -0,0 +1,153 @@ +import Mathlib + +namespace OAI + +/-! +# Structural bridges for anchor pinning + +Group uniqueness and no-shattering give pinning criteria independent of +the host construction. +-/ + +universe uI uJ uR uC uG + +namespace Problem348.AnchorBridge + +/-- Distinct pattern rows prevent a copy from repeating any host row class +whose members have identical entries. -/ +theorem row_labels_injective {I : Type uI} {J : Type uJ} {R : Type uR} {C : Type uC} {G : Type uG} + (H : I → J → Bool) (A : R → C → Bool) + (row : I → R) (col : J → C) (label : R → G) + (hcopy : ∀ i j, A (row i) (col j) = H i j) + (hrows : Function.Injective H) + (hlabel : ∀ r s, label r = label s → A r = A s) : + Function.Injective (fun i => label (row i)) := by + intro i j hij + apply hrows + funext c + rw [← hcopy, ← hcopy] + exact congrFun (hlabel (row i) (row j) hij) (col c) + +/-- The column version of `row_labels_injective`. -/ +theorem col_labels_injective {I : Type uI} {J : Type uJ} {R : Type uR} {C : Type uC} {G : Type uG} + (H : I → J → Bool) (A : R → C → Bool) + (row : I → R) (col : J → C) (label : C → G) + (hcopy : ∀ i j, A (row i) (col j) = H i j) + (hcols : Function.Injective (fun j => fun i => H i j)) + (hlabel : ∀ c d, label c = label d → ∀ r, A r c = A r d) : + Function.Injective (fun j => label (col j)) := by + intro i j hij + apply hcols + funext r + change H r i = H r j + rw [← hcopy, ← hcopy] + exact hlabel (col i) (col j) hij (row r) + +/-- The 32 rows carrying all binary words in the fixed anchor. -/ +def wordRow (a : Fin 32) : Fin 64 := ⟨32 + a.val, by omega⟩ + +/-- The five columns carrying the word coordinates in the fixed anchor. -/ +def wordCol (b : Fin 5) : Fin 64 := ⟨59 + b.val, by omega⟩ + +@[simp] theorem wordCol_injective : Function.Injective wordCol := by + intro a b hab + apply Fin.ext + have := congrArg Fin.val hab + simp only [wordCol] at this + omega + +/-- If both axes had at most 32 initial anchor positions, the complete-word +submatrix would shatter five non-anchor columns. Thus the position at index +32 is an anchor on at least one axis. -/ +theorem anchor_at_32_or_anchor_at_32 {R : Type uR} {C : Type uC} + (H : Fin 64 → Fin 64 → Bool) (A : R → C → Bool) + (row : Fin 64 → R) (col : Fin 64 → C) + (anchorR : R → Prop) (anchorC : C → Prop) + (hcopy : ∀ i j, A (row i) (col j) = H i j) + (hcol : Function.Injective col) + (hprefixR : ∀ i j, i ≤ j → anchorR (row j) → anchorR (row i)) + (hprefixC : ∀ i j, i ≤ j → anchorC (col j) → anchorC (col i)) + (hwords : ∀ w : Fin 5 → Bool, ∃ a : Fin 32, + ∀ b : Fin 5, H (wordRow a) (wordCol b) = w b) + (hnoshatter : ∀ cs : Fin 5 → C, Function.Injective cs → + (∀ b, ¬ anchorC (cs b)) → ∃ w : Fin 5 → Bool, + ∀ r, ¬ anchorR r → ∃ b, A r (cs b) ≠ w b) : + anchorR (row ⟨32, by decide⟩) ∨ anchorC (col ⟨32, by decide⟩) := by + classical + by_contra h + push Not at h + have hr : ∀ a : Fin 32, ¬ anchorR (row (wordRow a)) := by + intro a ha + apply h.1 + exact hprefixR _ _ (by simp only [wordRow, Fin.le_iff_val_le_val]; omega) ha + have hc : ∀ b : Fin 5, ¬ anchorC (col (wordCol b)) := by + intro b hb + apply h.2 + exact hprefixC _ _ (by simp only [wordCol, Fin.le_iff_val_le_val]; omega) hb + obtain ⟨w, hw⟩ := hnoshatter (fun b => col (wordCol b)) + (hcol.comp wordCol_injective) hc + obtain ⟨a, ha⟩ := hwords w + obtain ⟨b, hb⟩ := hw (row (wordRow a)) (hr a) + exact hb ((hcopy _ _).trans (ha b)) + +/-- A downward-closed predicate holding at index `m` holds at at least +`m+1` indices. -/ +theorem prefix_card_lower_bound {n : ℕ} (P : Fin n → Prop) [DecidablePred P] + (m : Fin n) (hprefix : ∀ i j, i ≤ j → P j → P i) (hm : P m) : + m.val + 1 ≤ (Finset.univ.filter P).card := by + classical + calc + m.val + 1 = (Finset.Iic m).card := by simp + _ ≤ (Finset.univ.filter P).card := by + apply Finset.card_le_card + intro i hi + exact Finset.mem_filter.mpr ⟨Finset.mem_univ i, + hprefix i m (Finset.mem_Iic.mp hi) hm⟩ + +/-- An increasing self-map of a finite ordered interval uses every label +in the prescribed order. -/ +theorem increasing_labels_eq_id {n : ℕ} (f : Fin n → Fin n) + (hf : StrictMono f) : f = id := by + funext i + exact le_antisymm (hf.le_id i) (hf.id_le i) + +/-- Any class of host rows with identical entries is used at most once +in a copy with distinct pattern rows. In particular this applies to the +dummy row class. -/ +theorem card_selected_row_class_le_one {I : Type uI} {J : Type uJ} {R : Type uR} {C : Type uC} + [Fintype I] (H : I → J → Bool) (A : R → C → Bool) + (row : I → R) (col : J → C) (P : R → Prop) [DecidablePred P] + (hcopy : ∀ i j, A (row i) (col j) = H i j) + (hrows : Function.Injective H) + (hclass : ∀ r s, P r → P s → A r = A s) : + (Finset.univ.filter (fun i => P (row i))).card ≤ 1 := by + classical + apply Finset.card_le_one.mpr + intro i hi j hj + apply hrows + funext c + rw [← hcopy, ← hcopy] + exact congrFun (hclass (row i) (row j) + (Finset.mem_filter.mp hi).2 (Finset.mem_filter.mp hj).2) (col c) + +/-- Column version of the single-use class bound. -/ +theorem card_selected_col_class_le_one {I : Type uI} {J : Type uJ} {R : Type uR} {C : Type uC} + [Fintype J] (H : I → J → Bool) (A : R → C → Bool) + (row : I → R) (col : J → C) (P : C → Prop) [DecidablePred P] + (hcopy : ∀ i j, A (row i) (col j) = H i j) + (hcols : Function.Injective (fun j => fun i => H i j)) + (hclass : ∀ c d, P c → P d → ∀ r, A r c = A r d) : + (Finset.univ.filter (fun j => P (col j))).card ≤ 1 := by + classical + apply Finset.card_le_one.mpr + intro i hi j hj + apply hcols + funext r + change H r i = H r j + rw [← hcopy, ← hcopy] + exact hclass (col i) (col j) + (Finset.mem_filter.mp hi).2 (Finset.mem_filter.mp hj).2 (row r) + +end Problem348.AnchorBridge + +end OAI diff --git a/lean/OAI/Combinatorics/MatrixRemoval/AnchorPatternFixed.lean b/lean/OAI/Combinatorics/MatrixRemoval/AnchorPatternFixed.lean new file mode 100644 index 0000000000000000000000000000000000000000..60dba321db7d32a5690c8f9c2f2a048faf680b70 --- /dev/null +++ b/lean/OAI/Combinatorics/MatrixRemoval/AnchorPatternFixed.lean @@ -0,0 +1,68 @@ +import OAI.Combinatorics.MatrixRemoval.AnchorPatternBridge +import OAI.Combinatorics.MatrixRemoval.AnchorProperties + +namespace OAI + +/-! +# Structural anchor bridges for the fixed pattern + +The generic bridges are specialized to the explicit `anchor64` definition. +-/ + +universe uR uC + +namespace Problem348.AnchorBridge + +/-- The exact anchor realizes every five-bit word on the specified suffix. -/ +theorem anchor64_word_block_complete (w : Fin 5 → Bool) : + ∃ a : Fin 32, ∀ b : Fin 5, + anchor64 (wordRow a) (wordCol b) = w b := by + obtain ⟨a, ha⟩ := anchorWord_bijective.2 w + refine ⟨a, fun b => ?_⟩ + have hb := congrFun ha b + simpa only [anchorWord, wordRow, wordCol, Nat.add_comm] using hb + +/-- An exact anchor copy has at least 33 anchors on one of its two axes, +provided anchors form prefixes and non-anchor rows do not shatter five +non-anchor columns. -/ +theorem anchor64_anchor_majority {R : Type uR} {C : Type uC} + (A : R → C → Bool) (row : Fin 64 → R) (col : Fin 64 → C) + (anchorR : R → Prop) (anchorC : C → Prop) + [DecidablePred anchorR] [DecidablePred anchorC] + (hcopy : ∀ i j, A (row i) (col j) = anchor64 i j) + (hcol : Function.Injective col) + (hprefixR : ∀ i j, i ≤ j → anchorR (row j) → anchorR (row i)) + (hprefixC : ∀ i j, i ≤ j → anchorC (col j) → anchorC (col i)) + (hnoshatter : ∀ cs : Fin 5 → C, Function.Injective cs → + (∀ b, ¬ anchorC (cs b)) → ∃ w : Fin 5 → Bool, + ∀ r, ¬ anchorR r → ∃ b, A r (cs b) ≠ w b) : + 33 ≤ (Finset.univ.filter (fun i => anchorR (row i))).card ∨ + 33 ≤ (Finset.univ.filter (fun j => anchorC (col j))).card := by + rcases anchor_at_32_or_anchor_at_32 anchor64 A row col anchorR anchorC + hcopy hcol hprefixR hprefixC anchor64_word_block_complete hnoshatter with hr | hc + · exact Or.inl (prefix_card_lower_bound _ ⟨32, by decide⟩ hprefixR hr) + · exact Or.inr (prefix_card_lower_bound _ ⟨32, by decide⟩ hprefixC hc) + +/-- A row class of equal host rows occurs at most once in an anchor copy. -/ +theorem anchor64_row_class_single_use {R : Type uR} {C : Type uC} + (A : R → C → Bool) (row : Fin 64 → R) (col : Fin 64 → C) + (P : R → Prop) [DecidablePred P] + (hcopy : ∀ i j, A (row i) (col j) = anchor64 i j) + (hclass : ∀ r s, P r → P s → A r = A s) : + (Finset.univ.filter (fun i => P (row i))).card ≤ 1 := + card_selected_row_class_le_one anchor64 A row col P hcopy + anchor64_rows_injective hclass + +/-- A column class of equal host columns occurs at most once in an anchor copy. -/ +theorem anchor64_col_class_single_use {R : Type uR} {C : Type uC} + (A : R → C → Bool) (row : Fin 64 → R) (col : Fin 64 → C) + (P : C → Prop) [DecidablePred P] + (hcopy : ∀ i j, A (row i) (col j) = anchor64 i j) + (hclass : ∀ c d, P c → P d → ∀ r, A r c = A r d) : + (Finset.univ.filter (fun j => P (col j))).card ≤ 1 := + card_selected_col_class_le_one anchor64 A row col P hcopy + anchor64_columns_injective hclass + +end Problem348.AnchorBridge + +end OAI diff --git a/lean/OAI/Combinatorics/MatrixRemoval/AnchorProperties.lean b/lean/OAI/Combinatorics/MatrixRemoval/AnchorProperties.lean new file mode 100644 index 0000000000000000000000000000000000000000..2d1e977ae945a236d1663e25833dd445a5647bb4 --- /dev/null +++ b/lean/OAI/Combinatorics/MatrixRemoval/AnchorProperties.lean @@ -0,0 +1,116 @@ +import OAI.Combinatorics.MatrixRemoval.Model + +namespace OAI + +namespace Problem348 + +/-- The anchor is off-diagonal one outside its modified bit rectangle. -/ +theorem anchor64_eq_decide_ne (u v : Fin 64) + (h : u.val < 32 ∨ v.val < 59) : + anchor64 u v = decide (u.val ≠ v.val) := by + unfold anchor64 + split_ifs with hmod + · rcases h with h | h <;> omega + · rfl + +/-- In the dense prefix, every column has at most one zero. -/ +theorem anchor64_first32_zero_iff (u v : Fin 64) (hu : u.val < 32) : + anchor64 u v = false ↔ u = v := by + rw [anchor64_eq_decide_ne u v (Or.inl hu)] + simp [Fin.ext_iff] + +/-- In the dense prefix, every row has at most one zero. -/ +theorem anchor64_first32_column_zero_iff (u v : Fin 64) (hv : v.val < 32) : + anchor64 u v = false ↔ u = v := by + rw [anchor64_eq_decide_ne u v (Or.inr (by omega))] + simp [Fin.ext_iff] + +/-- Every anchor row contains at least 58 ones. -/ +theorem anchor64_row_ones : ∀ u : Fin 64, + 58 ≤ (Finset.univ.filter (fun v => anchor64 u v = true)).card := by + decide + +/-- Every anchor column contains at least 48 ones. -/ +theorem anchor64_column_ones : ∀ v : Fin 64, + 48 ≤ (Finset.univ.filter (fun u => anchor64 u v = true)).card := by + decide + +/-- The five bit-coordinate columns of the anchor. -/ +def anchorLastCol (b : Fin 5) : Fin 64 := ⟨b.val + 59, by omega⟩ + +/-- Distinct rows have distinct complete anchor words. -/ +theorem anchor64_rows_injective : Function.Injective anchor64 := by + intro u v huv + by_cases hu : u.val < 59 + · have h := congrFun huv u + rw [anchor64_eq_decide_ne u u (Or.inr hu), + anchor64_eq_decide_ne v u (Or.inr hu)] at h + apply Fin.ext + have hvu : v.val = u.val := by simpa using h + exact hvu.symm + by_cases hv : v.val < 59 + · have h := congrFun huv v + rw [anchor64_eq_decide_ne u v (Or.inr hv), + anchor64_eq_decide_ne v v (Or.inr hv)] at h + simpa [Fin.ext_iff] using h + have hlast : ∀ a b : Fin 64, 59 ≤ a.val → 59 ≤ b.val → + (∀ j : Fin 5, anchor64 a (anchorLastCol j) = + anchor64 b (anchorLastCol j)) → a = b := by + decide + exact hlast u v (by omega) (by omega) (fun j => congrFun huv _) + +/-- Distinct columns have distinct complete anchor words. -/ +theorem anchor64_columns_injective : + Function.Injective (fun v : Fin 64 => fun u : Fin 64 => anchor64 u v) := by + decide + +/-- All five-bit words, in the order used by the replacement rectangle. -/ +def anchorWord (a : Fin 32) (b : Fin 5) : Bool := + anchor64 ⟨a.val + 32, by omega⟩ ⟨b.val + 59, by omega⟩ + +/-- The 32 lower anchor rows realize all binary words on the last five columns. -/ +theorem anchorWord_bijective : Function.Bijective anchorWord := by + decide + +/-- Inclusion of the dense 32-position prefix. -/ +def anchorFirst32 (i : Fin 32) : Fin 64 := ⟨i.val, by omega⟩ + +/-- First-prefix column density, used to exclude variable columns. -/ +theorem anchor64_first32_column_ones : ∀ v : Fin 64, + 31 ≤ (Finset.univ.filter (fun u : Fin 32 => + anchor64 (anchorFirst32 u) v = true)).card := by + decide + +/-- First-prefix row density, used to exclude variable rows. -/ +theorem anchor64_first32_row_ones : ∀ u : Fin 64, + 31 ≤ (Finset.univ.filter (fun v : Fin 32 => + anchor64 u (anchorFirst32 v) = true)).card := by + decide + +/-- Any two columns share a one in the first 32 rows. -/ +theorem anchor64_columns_common_one : ∀ v w : Fin 64, + ∃ u : Fin 32, anchor64 (anchorFirst32 u) v = true ∧ + anchor64 (anchorFirst32 u) w = true := by + intro v w + by_cases h0 : v.val ≠ 0 ∧ w.val ≠ 0 + · exact ⟨0, by simpa [anchorFirst32, anchor64, ne_comm] using h0⟩ + by_cases h1 : v.val ≠ 1 ∧ w.val ≠ 1 + · exact ⟨1, by simpa [anchorFirst32, anchor64, ne_comm] using h1⟩ + have h2 : v.val ≠ 2 ∧ w.val ≠ 2 := by omega + exact ⟨2, by simpa [anchorFirst32, anchor64, ne_comm] using h2⟩ + +/-- Any two rows share a one in the first 32 columns. -/ +theorem anchor64_rows_common_one : ∀ u w : Fin 64, + ∃ v : Fin 32, anchor64 u (anchorFirst32 v) = true ∧ + anchor64 w (anchorFirst32 v) = true := by + intro u w + by_cases h0 : u.val ≠ 0 ∧ w.val ≠ 0 + · exact ⟨0, by simpa [anchorFirst32, anchor64] using h0⟩ + by_cases h1 : u.val ≠ 1 ∧ w.val ≠ 1 + · exact ⟨1, by simpa [anchorFirst32, anchor64] using h1⟩ + have h2 : u.val ≠ 2 ∧ w.val ≠ 2 := by omega + exact ⟨2, by simp [anchorFirst32, anchor64, h2.1, h2.2]⟩ + +end Problem348 + +end OAI diff --git a/lean/OAI/Combinatorics/MatrixRemoval/AnchorRigidity.lean b/lean/OAI/Combinatorics/MatrixRemoval/AnchorRigidity.lean new file mode 100644 index 0000000000000000000000000000000000000000..74be85686fccc60de258f3ab0355656c9e8b2283 --- /dev/null +++ b/lean/OAI/Combinatorics/MatrixRemoval/AnchorRigidity.lean @@ -0,0 +1,177 @@ +import Mathlib + +namespace OAI + +/-! +Finite combinatorial anchor rigidity under explicit density, sparsity, +and mode-incidence hypotheses. +-/ + +universe uI uJ uT + +namespace Problem348.AnchorRigidity + +/-- At most one zero leaves all but at most one position equal to one. -/ +theorem card_le_true_card_add_one {I : Type uI} [DecidableEq I] + (s : Finset I) (f : I → Bool) + (hz : (s.filter fun i => f i = false).card ≤ 1) : + s.card ≤ (s.filter fun i => f i = true).card + 1 := by + classical + have hp := Finset.card_filter_add_card_filter_not (s := s) + (p := fun i => f i = true) + have hn : (s.filter fun i => ¬ f i = true).card ≤ 1 := by + simpa only [Bool.not_eq_true] using hz + omega + +/-- Two columns with at most one zero share a one on any core of size at least three. -/ +theorem exists_common_true {I : Type uI} [DecidableEq I] + (s : Finset I) (f g : I → Bool) (hs : 3 ≤ s.card) + (hf : (s.filter fun i => f i = false).card ≤ 1) + (hg : (s.filter fun i => g i = false).card ≤ 1) : + ∃ i ∈ s, f i = true ∧ g i = true := by + classical + by_contra h + have hsub : (s.filter fun i => f i = true) ⊆ + (s.filter fun i => g i = false) := by + intro i hi + obtain ⟨his, hif⟩ := Finset.mem_filter.mp hi + apply Finset.mem_filter.mpr + refine ⟨his, ?_⟩ + cases hgi : g i with + | false => rfl + | true => exact False.elim (h ⟨i, his, hif, hgi⟩) + have hcard := Finset.card_le_card hsub + have hpos := card_le_true_card_add_one s f hf + omega + +/-- One-sided rigidity. A dense anchor core on the row axis forces both axes +into one mode. The dummy predicate is only needed to permit one exceptional +non-anchor column before the common mode has been identified. -/ +theorem one_sided + {I : Type uI} {J : Type uJ} {T : Type uT} [Fintype I] [Fintype J] + (B : I → J → Bool) (rowMode : I → Option T) (colMode : J → Option T) + (dummyCol : J → Prop) (core : Finset I) + (hcore : 6 ≤ core.card) + (core_anchor : ∀ i ∈ core, ∃ t, rowMode i = some t) + (core_zeros : ∀ j, (core.filter fun i => B i j = false).card ≤ 1) + (variable_sparse : ∀ j, colMode j = none → ¬ dummyCol j → + (core.filter fun i => B i j = true).card ≤ 4) + (dummy_unique : ∀ j k, dummyCol j → dummyCol k → j = k) + (cross_mode : ∀ i j t u, rowMode i = some t → colMode j = some u → + B i j = true → t = u) + (nonanchor_row_unit : ∀ i, rowMode i = none → ∀ j k t, + colMode j = some t → colMode k = some t → + B i j = true → B i k = true → j = k) + (nonanchor_col_unit : ∀ j, colMode j = none → ∀ i k t, + rowMode i = some t → rowMode k = some t → + B i j = true → B k j = true → i = k) + (row_dense : ∀ i, 2 ≤ (Finset.univ.filter fun j => B i j = true).card) : + ∃ t, (∀ i, rowMode i = some t) ∧ (∀ j, colMode j = some t) := by + classical + have core_positive (j : J) : 5 ≤ (core.filter fun i => B i j = true).card := by + have h := card_le_true_card_add_one core (fun i => B i j) (core_zeros j) + omega + have nonanchor_dummy (j : J) (hj : colMode j = none) : dummyCol j := by + by_contra hd + have hs := variable_sparse j hj hd + have hp := core_positive j + omega + have nonanchor_unique (j k : J) (hj : colMode j = none) + (hk : colMode k = none) : j = k := + dummy_unique j k (nonanchor_dummy j hj) (nonanchor_dummy k hk) + have two_ones (i : I) : ∃ j k, B i j = true ∧ B i k = true ∧ j ≠ k := by + have hd := row_dense i + obtain ⟨j, hj, k, hk, hne⟩ := Finset.one_lt_card.mp (show + 1 < (Finset.univ.filter fun j => B i j = true).card by omega) + exact ⟨j, k, (Finset.mem_filter.mp hj).2, (Finset.mem_filter.mp hk).2, hne⟩ + have row_anchor_one (i : I) : ∃ j t, colMode j = some t ∧ B i j = true := by + obtain ⟨j, k, hj, hk, hne⟩ := two_ones i + cases hmj : colMode j with + | some t => exact ⟨j, t, hmj, hj⟩ + | none => + cases hmk : colMode k with + | some t => exact ⟨k, t, hmk, hk⟩ + | none => exact False.elim (hne (nonanchor_unique j k hmj hmk)) + obtain ⟨i₀, hi₀⟩ := Finset.card_pos.mp (show 0 < core.card by omega) + obtain ⟨j₀, t, hj₀, _⟩ := row_anchor_one i₀ + have anchor_columns (j : J) (u : T) (hj : colMode j = some u) : u = t := by + obtain ⟨i, hi, hij, hij₀⟩ := exists_common_true core + (fun i => B i j) (fun i => B i j₀) (by omega) (core_zeros j) (core_zeros j₀) + obtain ⟨v, hiv⟩ := core_anchor i hi + exact (cross_mode i j v u hiv hj hij).symm.trans + (cross_mode i j₀ v t hiv hj₀ hij₀) + have anchor_rows (i : I) (u : T) (hi : rowMode i = some u) : u = t := by + obtain ⟨j, v, hj, hij⟩ := row_anchor_one i + exact (cross_mode i j u v hi hj hij).trans (anchor_columns j v hj) + have core_same (i : I) (hi : i ∈ core) : rowMode i = some t := by + obtain ⟨u, hu⟩ := core_anchor i hi + simpa only [anchor_rows i u hu] using hu + have all_columns (j : J) : colMode j = some t := by + cases hj : colMode j with + | some u => simp only [anchor_columns j u hj] + | none => + have hs : (core.filter fun i => B i j = true).card ≤ 1 := by + apply Finset.card_le_one.mpr + intro i hi k hk + obtain ⟨hic, hij⟩ := Finset.mem_filter.mp hi + obtain ⟨hkc, hkj⟩ := Finset.mem_filter.mp hk + exact nonanchor_col_unit j hj i k t (core_same i hic) (core_same k hkc) hij hkj + have hp := core_positive j + omega + refine ⟨t, ?_, all_columns⟩ + intro i + cases hi : rowMode i with + | some u => simp only [anchor_rows i u hi] + | none => + obtain ⟨j, k, hj, hk, hne⟩ := two_ones i + exact False.elim (hne (nonanchor_row_unit i hi j k t + (all_columns j) (all_columns k) hj hk)) + +/-- A dense core consists of at least six selected anchor positions. Every +opposite position has at most one zero on it, while a variable opposite +position would have at most four ones. -/ +def DenseAnchorCore {I : Type uI} {J : Type uJ} {T : Type uT} + (B : I → J → Bool) (rowMode : I → Option T) (colMode : J → Option T) + (dummyCol : J → Prop) : Prop := + ∃ core : Finset I, 6 ≤ core.card ∧ + (∀ i ∈ core, ∃ t, rowMode i = some t) ∧ + (∀ j, (core.filter fun i => B i j = false).card ≤ 1) ∧ + (∀ j, colMode j = none → ¬ dummyCol j → + (core.filter fun i => B i j = true).card ≤ 4) + +/-- Symmetric form of anchor rigidity: a dense anchor core on either axis +suffices. The no-shattering/order argument supplies this disjunction in the +application to the 64 by 64 pattern. -/ +theorem rigidity + {I : Type uI} {J : Type uJ} {T : Type uT} [Fintype I] [Fintype J] + (B : I → J → Bool) (rowMode : I → Option T) (colMode : J → Option T) + (dummyRow : I → Prop) (dummyCol : J → Prop) + (hcore : DenseAnchorCore B rowMode colMode dummyCol ∨ + DenseAnchorCore (fun j i => B i j) colMode rowMode dummyRow) + (dummy_row_unique : ∀ i k, dummyRow i → dummyRow k → i = k) + (dummy_col_unique : ∀ j k, dummyCol j → dummyCol k → j = k) + (cross_mode : ∀ i j t u, rowMode i = some t → colMode j = some u → + B i j = true → t = u) + (nonanchor_row_unit : ∀ i, rowMode i = none → ∀ j k t, + colMode j = some t → colMode k = some t → + B i j = true → B i k = true → j = k) + (nonanchor_col_unit : ∀ j, colMode j = none → ∀ i k t, + rowMode i = some t → rowMode k = some t → + B i j = true → B k j = true → i = k) + (row_dense : ∀ i, 2 ≤ (Finset.univ.filter fun j => B i j = true).card) + (col_dense : ∀ j, 2 ≤ (Finset.univ.filter fun i => B i j = true).card) : + ∃ t, (∀ i, rowMode i = some t) ∧ (∀ j, colMode j = some t) := by + rcases hcore with hcore | hcore + · obtain ⟨core, hc, ha, hz, hs⟩ := hcore + exact one_sided B rowMode colMode dummyCol core hc ha hz hs + dummy_col_unique cross_mode nonanchor_row_unit nonanchor_col_unit row_dense + · obtain ⟨core, hc, ha, hz, hs⟩ := hcore + obtain ⟨t, hcol, hrow⟩ := one_sided (fun j i => B i j) colMode rowMode + dummyRow core hc ha hz hs dummy_row_unique + (fun j i u t hj hi hb => (cross_mode i j t u hi hj hb).symm) + nonanchor_col_unit nonanchor_row_unit col_dense + exact ⟨t, hrow, hcol⟩ + +end Problem348.AnchorRigidity + +end OAI diff --git a/lean/OAI/Combinatorics/MatrixRemoval/AnchorRigidityFixed.lean b/lean/OAI/Combinatorics/MatrixRemoval/AnchorRigidityFixed.lean new file mode 100644 index 0000000000000000000000000000000000000000..53b921032346ee9201257e95d0d69eb05c5179a1 --- /dev/null +++ b/lean/OAI/Combinatorics/MatrixRemoval/AnchorRigidityFixed.lean @@ -0,0 +1,118 @@ +import OAI.Combinatorics.MatrixRemoval.AnchorProperties +import OAI.Combinatorics.MatrixRemoval.AnchorRigidity + +namespace OAI + +universe uT + +namespace Problem348.AnchorRigidity + +/-- The actual first 32 positions of the fixed anchor. -/ +def firstCore : Finset (Fin 64) := Finset.univ.filter fun i => i.val < 32 + +@[simp] theorem mem_firstCore (i : Fin 64) : i ∈ firstCore ↔ i.val < 32 := by + simp [firstCore] + +theorem firstCore_card : firstCore.card = 32 := by decide + +theorem firstCore_column_zeros (j : Fin 64) : + (firstCore.filter fun i => anchor64 i j = false).card ≤ 1 := by + apply Finset.card_le_one.mpr + intro i hi k hk + obtain ⟨hic, hij⟩ := Finset.mem_filter.mp hi + obtain ⟨hkc, hkj⟩ := Finset.mem_filter.mp hk + exact ((anchor64_first32_zero_iff i j ((mem_firstCore i).mp hic)).mp hij).trans + ((anchor64_first32_zero_iff k j ((mem_firstCore k).mp hkc)).mp hkj).symm + +theorem firstCore_row_zeros (i : Fin 64) : + (firstCore.filter fun j => anchor64 i j = false).card ≤ 1 := by + apply Finset.card_le_one.mpr + intro j hj k hk + obtain ⟨hjc, hij⟩ := Finset.mem_filter.mp hj + obtain ⟨hkc, hik⟩ := Finset.mem_filter.mp hk + exact ((anchor64_first32_column_zero_iff i j ((mem_firstCore j).mp hjc)).mp hij).symm.trans + ((anchor64_first32_column_zero_iff i k ((mem_firstCore k).mp hkc)).mp hik) + +/-- A majority of anchor labels in an initial segment contains the dense prefix. +This is the small order/cardinality bridge from the no-shattering majority +argument to the finite rigidity theorem. -/ +theorem prefix_of_majority {T : Type uT} (mode : Fin 64 → Option T) + (initial : ∀ i j, i ≤ j → mode j ≠ none → mode i ≠ none) + (majority : 32 < (Finset.univ.filter fun i => (mode i).isSome).card) : + ∀ i : Fin 64, i.val < 32 → ∃ t, mode i = some t := by + intro i hi + cases hmi : mode i with + | some t => exact ⟨t, rfl⟩ + | none => + have hsub : (Finset.univ.filter fun j => (mode j).isSome) ⊆ Finset.Iio i := by + intro j hj + have hjs := (Finset.mem_filter.mp hj).2 + have hjn : mode j ≠ none := by + intro hnone + simp [hnone] at hjs + apply Finset.mem_Iio.mpr + by_contra hnot + exact initial i j (le_of_not_gt hnot) hjn hmi + have hcard := Finset.card_le_card hsub + rw [Fin.card_Iio] at hcard + omega + +/-- The majority conclusion on either axis provides the prefix alternative +required by `anchor64_rigidity_of_prefix`. -/ +theorem prefix_alternative_of_majority {T : Type uT} + (rowMode colMode : Fin 64 → Option T) + (row_initial : ∀ i j, i ≤ j → rowMode j ≠ none → rowMode i ≠ none) + (col_initial : ∀ i j, i ≤ j → colMode j ≠ none → colMode i ≠ none) + (majority : 32 < (Finset.univ.filter fun i => (rowMode i).isSome).card ∨ + 32 < (Finset.univ.filter fun j => (colMode j).isSome).card) : + (∀ i : Fin 64, i.val < 32 → ∃ t, rowMode i = some t) ∨ + (∀ j : Fin 64, j.val < 32 → ∃ t, colMode j = some t) := by + exact majority.imp (prefix_of_majority rowMode row_initial) + (prefix_of_majority colMode col_initial) + +/-- Same-mode conclusion for the exact anchor after prefix pinning. -/ +theorem anchor64_rigidity_of_prefix {T : Type uT} + (rowMode colMode : Fin 64 → Option T) + (dummyRow dummyCol : Fin 64 → Prop) + (hprefix : (∀ i : Fin 64, i.val < 32 → ∃ t, rowMode i = some t) ∨ + (∀ j : Fin 64, j.val < 32 → ∃ t, colMode j = some t)) + (variable_col_sparse : ∀ j, colMode j = none → ¬ dummyCol j → + (∀ i ∈ firstCore, ∃ t, rowMode i = some t) → + (firstCore.filter fun i => anchor64 i j = true).card ≤ 4) + (variable_row_sparse : ∀ i, rowMode i = none → ¬ dummyRow i → + (∀ j ∈ firstCore, ∃ t, colMode j = some t) → + (firstCore.filter fun j => anchor64 i j = true).card ≤ 4) + (dummy_row_unique : ∀ i k, dummyRow i → dummyRow k → i = k) + (dummy_col_unique : ∀ j k, dummyCol j → dummyCol k → j = k) + (cross_mode : ∀ i j t u, rowMode i = some t → colMode j = some u → + anchor64 i j = true → t = u) + (nonanchor_row_unit : ∀ i, rowMode i = none → ∀ j k t, + colMode j = some t → colMode k = some t → + anchor64 i j = true → anchor64 i k = true → j = k) + (nonanchor_col_unit : ∀ j, colMode j = none → ∀ i k t, + rowMode i = some t → rowMode k = some t → + anchor64 i j = true → anchor64 k j = true → i = k) : + ∃ t, (∀ i, rowMode i = some t) ∧ (∀ j, colMode j = some t) := by + apply rigidity anchor64 rowMode colMode dummyRow dummyCol + (dummy_row_unique := dummy_row_unique) (dummy_col_unique := dummy_col_unique) + (cross_mode := cross_mode) (nonanchor_row_unit := nonanchor_row_unit) + (nonanchor_col_unit := nonanchor_col_unit) + · rcases hprefix with hr | hc + · left + have ha : ∀ i ∈ firstCore, ∃ t, rowMode i = some t := + fun i hi => hr i ((mem_firstCore i).mp hi) + exact ⟨firstCore, by rw [firstCore_card]; omega, ha, + firstCore_column_zeros, fun j hj hd => variable_col_sparse j hj hd ha⟩ + · right + have ha : ∀ j ∈ firstCore, ∃ t, colMode j = some t := + fun j hj => hc j ((mem_firstCore j).mp hj) + exact ⟨firstCore, by rw [firstCore_card]; omega, ha, + firstCore_row_zeros, fun i hi hd => variable_row_sparse i hi hd ha⟩ + · intro i + exact (by omega : 2 ≤ 58).trans (anchor64_row_ones i) + · intro j + exact (by omega : 2 ≤ 48).trans (anchor64_column_ones j) + +end Problem348.AnchorRigidity + +end OAI diff --git a/lean/OAI/Combinatorics/MatrixRemoval/Asymptotics.lean b/lean/OAI/Combinatorics/MatrixRemoval/Asymptotics.lean new file mode 100644 index 0000000000000000000000000000000000000000..014027af399158ed7102a80ca05ee50721949310 --- /dev/null +++ b/lean/OAI/Combinatorics/MatrixRemoval/Asymptotics.lean @@ -0,0 +1,69 @@ +import Mathlib + +namespace OAI + +/-! +Analytic conclusion of the ordered-matrix construction. +The polynomial/geometric comparison uses +`tendsto_pow_const_div_const_pow_of_one_lt`. +-/ + +noncomputable section + +namespace Problem348 + +open Filter +open scoped Topology + + +/-- Exponential decay beats the inverse-polynomial distance parameter. -/ +theorem exists_depth_polynomial_decay (c C : ℝ) (hc : 0 < c) : + ∃ h : ℕ, 1 ≤ h ∧ + (1 / ((386 * (h : ℝ) + 2) ^ 2)) * (1 / ((2 : ℝ) ^ h)) < + c * Real.rpow (1 / ((386 * (h : ℝ) + 2) ^ 2)) C := by + obtain ⟨k, hk⟩ := exists_nat_ge C + have ht := (tendsto_pow_const_div_const_pow_of_one_lt (2 * k) + (by norm_num : (1 : ℝ) < 2)).const_mul ((388 : ℝ) ^ (2 * k)) + have hev : ∀ᶠ h : ℕ in atTop, + (388 : ℝ) ^ (2 * k) * ((h : ℝ) ^ (2 * k) / (2 : ℝ) ^ h) < c := by + exact ht.eventually (gt_mem_nhds (by simpa using hc)) + obtain ⟨h, hh, hsmall⟩ := (eventually_ge_atTop 1 |>.and hev).exists + refine ⟨h, hh, ?_⟩ + have hhR : (1 : ℝ) ≤ h := by exact_mod_cast hh + have hd : 0 < 386 * (h : ℝ) + 2 := by positivity + have hd1 : (1 : ℝ) < 386 * (h : ℝ) + 2 := by linarith + have htwo : 0 < (2 : ℝ) ^ h := by positivity + have hpoly : (386 * (h : ℝ) + 2) ^ (2 * k) ≤ + (388 : ℝ) ^ (2 * k) * (h : ℝ) ^ (2 * k) := by + rw [← mul_pow] + exact pow_le_pow_left₀ hd.le (by linarith) _ + have hratio : (386 * (h : ℝ) + 2) ^ (2 * k) / (2 : ℝ) ^ h < c := by + calc + _ ≤ ((388 : ℝ) ^ (2 * k) * (h : ℝ) ^ (2 * k)) / (2 : ℝ) ^ h := + div_le_div_of_nonneg_right hpoly htwo.le + _ = (388 : ℝ) ^ (2 * k) * ((h : ℝ) ^ (2 * k) / (2 : ℝ) ^ h) := by ring + _ < c := hsmall + have hepspos : 0 < 1 / ((386 * (h : ℝ) + 2) ^ 2) := by positivity + have hepsle : 1 / ((386 * (h : ℝ) + 2) ^ 2) ≤ 1 := by + apply (div_le_one (by positivity)).2 + nlinarith + have hexponent : (1 / ((386 * (h : ℝ) + 2) ^ 2)) ^ k ≤ + Real.rpow (1 / ((386 * (h : ℝ) + 2) ^ 2)) C := by + simpa using Real.rpow_le_rpow_of_exponent_ge hepspos hepsle hk + have hsmall' : 1 / ((2 : ℝ) ^ h) < + c * (1 / ((386 * (h : ℝ) + 2) ^ 2)) ^ k := by + rw [div_pow, one_pow, ← pow_mul, mul_one_div] + apply (lt_div_iff₀ (pow_pos hd (2 * k))).2 + simpa [div_eq_mul_inv, mul_comm] using hratio + calc + _ ≤ 1 / ((2 : ℝ) ^ h) := by + exact mul_le_of_le_one_left (by positivity) hepsle + _ < c * (1 / ((386 * (h : ℝ) + 2) ^ 2)) ^ k := hsmall' + _ ≤ c * Real.rpow (1 / ((386 * (h : ℝ) + 2) ^ 2)) C := + mul_le_mul_of_nonneg_left hexponent hc.le + +end Problem348 + +end + +end OAI diff --git a/lean/OAI/Combinatorics/MatrixRemoval/BodyExtension.lean b/lean/OAI/Combinatorics/MatrixRemoval/BodyExtension.lean new file mode 100644 index 0000000000000000000000000000000000000000..f5dce7384b2ecc353f9b22271e754fe782a66ca9 --- /dev/null +++ b/lean/OAI/Combinatorics/MatrixRemoval/BodyExtension.lean @@ -0,0 +1,117 @@ +import OAI.Combinatorics.MatrixRemoval.Model + +namespace OAI + +/-! +The anchor/body extension step for arbitrary repairs. +The finite-order gluing lemma is independent of the host construction. +-/ + +universe uAlpha + +noncomputable section + +namespace Problem348 + +/-- Append two values to a function on a finite initial segment. -/ +def appendTwo {α : Type uAlpha} {k : ℕ} (f : Fin k → α) (a b : α) : + Fin (k + 2) → α := fun i => + if hi : i.val < k then f ⟨i.val, hi⟩ else if i.val = k then a else b + +@[simp] theorem appendTwo_initial {α : Type uAlpha} {k : ℕ} + (f : Fin k → α) (a b : α) (i : Fin k) : + appendTwo f a b ⟨i.val, by omega⟩ = f i := by + simp [appendTwo, i.isLt] + +@[simp] theorem appendTwo_first {α : Type uAlpha} {k : ℕ} + (f : Fin k → α) (a b : α) : + appendTwo f a b ⟨k, by omega⟩ = a := by + simp [appendTwo] + +@[simp] theorem appendTwo_second {α : Type uAlpha} {k : ℕ} + (f : Fin k → α) (a b : α) : + appendTwo f a b ⟨k + 1, by omega⟩ = b := by + simp [appendTwo] + +theorem strictMono_appendTwo {α : Type uAlpha} [Preorder α] {k : ℕ} + (f : Fin k → α) (a b : α) (hf : StrictMono f) + (ha : ∀ i, f i < a) (hab : a < b) : + StrictMono (appendTwo f a b) := by + intro i j hij + have hij' : i.val < j.val := hij + by_cases hi : i.val < k + · by_cases hj : j.val < k + · simpa [appendTwo, hi, hj] using + hf (show (⟨i.val, hi⟩ : Fin k) < ⟨j.val, hj⟩ from hij') + · by_cases hjk : j.val = k + · simpa [appendTwo, hi, hj, hjk] using ha ⟨i.val, hi⟩ + · simpa [appendTwo, hi, hj, hjk] using lt_trans (ha ⟨i.val, hi⟩) hab + · have hik : i.val = k := by omega + have hjk : j.val = k + 1 := by omega + simpa [appendTwo, hik, hjk] using hab + +/-- The increasing map obtained by appending two positions after an anchor. -/ +def appendTwoIncreasing {k n : ℕ} (r : IncreasingMap k n) + (a b : Fin n) (ha : ∀ i, r.val i < a) (hab : a < b) : + IncreasingMap (k + 2) n := + ⟨appendTwo r.val a b, strictMono_appendTwo r.val a b r.property ha hab⟩ + +/-- An anchor and the four body entries reproduce every entry of the fixed pattern. -/ +theorem appendTwo_matches_fixedH {n : ℕ} (B : BinaryMatrix n) + (r c : IncreasingMap 64 n) (r₀ r₁ c₀ c₁ : Fin n) + (hanchor : ∀ u v, B (r.val u) (c.val v) = anchor64 u v) + (hrow₀ : ∀ v, B r₀ (c.val v) = decide (v.val = 0)) + (hrow₁ : ∀ v, B r₁ (c.val v) = decide (v.val = 1)) + (hcol₀ : ∀ u, B (r.val u) c₀ = decide (u.val = 0)) + (hcol₁ : ∀ u, B (r.val u) c₁ = decide (u.val = 1)) + (h₀₀ : B r₀ c₀ = true) (h₀₁ : B r₀ c₁ = false) + (h₁₀ : B r₁ c₀ = true) (h₁₁ : B r₁ c₁ = true) : + ∀ i j : Fin 66, + B (appendTwo r.val r₀ r₁ i) (appendTwo c.val c₀ c₁ j) = fixedH i j := by + intro i j + by_cases hi : i.val < 64 + · by_cases hj : j.val < 64 + · simpa [appendTwo, fixedH, hi, hj] using + hanchor ⟨i.val, hi⟩ ⟨j.val, hj⟩ + · have hjcases : j.val = 64 ∨ j.val = 65 := by omega + rcases hjcases with hj₀ | hj₁ + · simpa [appendTwo, fixedH, hi, hj, hj₀] using hcol₀ ⟨i.val, hi⟩ + · simpa [appendTwo, fixedH, hi, hj, hj₁] using hcol₁ ⟨i.val, hi⟩ + · have hicases : i.val = 64 ∨ i.val = 65 := by omega + by_cases hj : j.val < 64 + · rcases hicases with hi₀ | hi₁ + · simpa [appendTwo, fixedH, hi, hj, hi₀] using hrow₀ ⟨j.val, hj⟩ + · simpa [appendTwo, fixedH, hi, hj, hi₁] using hrow₁ ⟨j.val, hj⟩ + · have hjcases : j.val = 64 ∨ j.val = 65 := by omega + rcases hicases with hi₀ | hi₁ <;> rcases hjcases with hj₀ | hj₁ <;> + simp [appendTwo, fixedH, *] + +/-- The exact anchor-extension bridge needed by arbitrary-repair propagation. -/ +theorem not_HFree_of_anchor_body {n : ℕ} (B : BinaryMatrix n) + (r c : IncreasingMap 64 n) (r₀ r₁ c₀ c₁ : Fin n) + (hr : ∀ i, r.val i < r₀) (hr₀₁ : r₀ < r₁) + (hc : ∀ j, c.val j < c₀) (hc₀₁ : c₀ < c₁) + (hanchor : ∀ u v, B (r.val u) (c.val v) = anchor64 u v) + (hrow₀ : ∀ v, B r₀ (c.val v) = decide (v.val = 0)) + (hrow₁ : ∀ v, B r₁ (c.val v) = decide (v.val = 1)) + (hcol₀ : ∀ u, B (r.val u) c₀ = decide (u.val = 0)) + (hcol₁ : ∀ u, B (r.val u) c₁ = decide (u.val = 1)) + (h₀₀ : B r₀ c₀ = true) (h₀₁ : B r₀ c₁ = false) + (h₁₀ : B r₁ c₀ = true) (h₁₁ : B r₁ c₁ = true) : + ¬ HFree fixedH B := by + classical + let rr := appendTwoIncreasing r r₀ r₁ hr hr₀₁ + let cc := appendTwoIncreasing c c₀ c₁ hc hc₀₁ + have hmem : (rr, cc) ∈ orderedCopies fixedH B := by + simp only [orderedCopies, Finset.mem_filter, Finset.mem_univ, true_and] + exact appendTwo_matches_fixedH B r c r₀ r₁ c₀ c₁ hanchor hrow₀ hrow₁ + hcol₀ hcol₁ h₀₀ h₀₁ h₁₀ h₁₁ + have hpos : 0 < copyCount fixedH B := + Finset.card_pos.mpr ⟨(rr, cc), hmem⟩ + exact Nat.ne_of_gt hpos + +end Problem348 + +end + +end OAI diff --git a/lean/OAI/Combinatorics/MatrixRemoval/BodyRoles.lean b/lean/OAI/Combinatorics/MatrixRemoval/BodyRoles.lean new file mode 100644 index 0000000000000000000000000000000000000000..fe4ed112c5e8b8cbd6086d77c02d109f99293b6d --- /dev/null +++ b/lean/OAI/Combinatorics/MatrixRemoval/BodyRoles.lean @@ -0,0 +1,75 @@ +import OAI.Combinatorics.MatrixRemoval.Model + +namespace OAI + +/-! +# Exact body signatures and extraction of body roles + +All signatures refer to `fixedH`, including its zero entries. +-/ + +namespace Problem348.BodySignatures52 + +def anchorIndex (u : Fin 64) : Fin 66 := ⟨u.val, by omega⟩ + +def bodyIndex (b : Fin 2) : Fin 66 := ⟨64 + b.val, by omega⟩ + +theorem fixedH_anchor_anchor (u v : Fin 64) : + fixedH (anchorIndex u) (anchorIndex v) = anchor64 u v := by + simp [fixedH, anchorIndex, u.isLt, v.isLt] + +theorem fixedH_body_anchor (b : Fin 2) (v : Fin 64) : + fixedH (bodyIndex b) (anchorIndex v) = decide (v.val = b.val) := by + fin_cases b <;> simp [fixedH, bodyIndex, anchorIndex, v.isLt] + +theorem fixedH_anchor_body (u : Fin 64) (b : Fin 2) : + fixedH (anchorIndex u) (bodyIndex b) = decide (u.val = b.val) := by + fin_cases b <;> simp [fixedH, bodyIndex, anchorIndex, u.isLt] + +theorem fixedH_body_body (b c : Fin 2) : + fixedH (bodyIndex b) (bodyIndex c) = decide (b.val = 1 ∨ c.val = 0) := by + fin_cases b <;> fin_cases c <;> rfl + +/-- No anchor row has either of the two body-row signatures. -/ +theorem anchor64_row_ne_body_signature (u : Fin 64) (b : Fin 2) : + (fun v => anchor64 u v) ≠ (fun v : Fin 64 => decide (v.val = b.val)) := by + intro h + have h2 := congrFun h (2 : Fin 64) + have h3 := congrFun h (3 : Fin 64) + fin_cases b <;> simp [anchor64] at h2 h3 <;> omega + +/-- No anchor column has either of the two body-column signatures. -/ +theorem anchor64_col_ne_body_signature (v : Fin 64) (b : Fin 2) : + (fun u => anchor64 u v) ≠ (fun u : Fin 64 => decide (u.val = b.val)) := by + intro h + have h2 := congrFun h (2 : Fin 64) + have h3 := congrFun h (3 : Fin 64) + fin_cases b <;> simp [anchor64] at h2 h3 <;> omega + +theorem zero_ne_body_signature (b : Fin 2) : + (fun _ : Fin 64 => false) ≠ (fun v : Fin 64 => decide (v.val = b.val)) := by + intro h + have hb := congrFun h (⟨b.val, by omega⟩ : Fin 64) + simp at hb + +theorem copy_body_row_signature {n : ℕ} {A : BinaryMatrix n} + {rc : IncreasingMap 66 n × IncreasingMap 66 n} + (hcopy : rc ∈ orderedCopies fixedH A) (b : Fin 2) (v : Fin 64) : + A (rc.1.val (bodyIndex b)) (rc.2.val (anchorIndex v)) = + decide (v.val = b.val) := by + classical + have hm := (Finset.mem_filter.mp hcopy).2 (bodyIndex b) (anchorIndex v) + exact hm.trans (fixedH_body_anchor b v) + +theorem copy_body_col_signature {n : ℕ} {A : BinaryMatrix n} + {rc : IncreasingMap 66 n × IncreasingMap 66 n} + (hcopy : rc ∈ orderedCopies fixedH A) (b : Fin 2) (u : Fin 64) : + A (rc.1.val (anchorIndex u)) (rc.2.val (bodyIndex b)) = + decide (u.val = b.val) := by + classical + have hm := (Finset.mem_filter.mp hcopy).2 (anchorIndex u) (bodyIndex b) + exact hm.trans (fixedH_anchor_body u b) + +end Problem348.BodySignatures52 + +end OAI diff --git a/lean/OAI/Combinatorics/MatrixRemoval/CanonicalCopyBound.lean b/lean/OAI/Combinatorics/MatrixRemoval/CanonicalCopyBound.lean new file mode 100644 index 0000000000000000000000000000000000000000..65c6602d806dda2b8efca11ec27b7fd70a2db9be --- /dev/null +++ b/lean/OAI/Combinatorics/MatrixRemoval/CanonicalCopyBound.lean @@ -0,0 +1,41 @@ +import OAI.Combinatorics.MatrixRemoval.OrderedAnchorRigidity +import OAI.Combinatorics.MatrixRemoval.OrderedHostCopy + +namespace OAI + +/-! +# Unconditional copy bound for the canonical host + +Concrete anchor rigidity and six-mode body localization imply the integer +copy bound and its normalized form. +-/ + +namespace Problem348.OrderedHost + +open Construction + +theorem anchor64Pinned (h : ℕ) : + Anchor64Pinned (rowIndex h) (columnIndex h) := + HostAnchorRigidity.representatives_of_indices + +theorem matching_copy_leaf (h : ℕ) (r c : Fin 66 → Position h) + (hr : StrictMono (fun i => rowIndex h (r i))) + (hc : StrictMono (fun j => columnIndex h (c j))) + (hmatch : ∀ i j, host (r i) (c j) = fixedH i j) : + ∃ z, r 64 = countedLeaf z ∧ c 64 = countedLeaf z := + matching_copy_leaf_of_pinning h (anchor64Pinned h) r c hr hc hmatch + +theorem canonical_copyCount_le (h : ℕ) : + copyCount fixedH (hostMatrix (rowIndex h) (columnIndex h)) ≤ + 2 ^ h * (size h) ^ 130 := + copyCount_le_of_pinning h (anchor64Pinned h) + +theorem canonical_copyDensity_le (h : ℕ) : + (copyCount fixedH (hostMatrix (rowIndex h) (columnIndex h)) : ℝ) / + ((size h : ℝ) ^ 132) ≤ + (1 / (((386 * h + 2 : ℕ) : ℝ) ^ 2)) * (1 / ((2 : ℝ) ^ h)) := + copyDensity_le_of_pinning h (anchor64Pinned h) + +end Problem348.OrderedHost + +end OAI diff --git a/lean/OAI/Combinatorics/MatrixRemoval/CanonicalHorizontal.lean b/lean/OAI/Combinatorics/MatrixRemoval/CanonicalHorizontal.lean new file mode 100644 index 0000000000000000000000000000000000000000..c5bf43598234416f7a8f938ade3a25176bdd9bfd --- /dev/null +++ b/lean/OAI/Combinatorics/MatrixRemoval/CanonicalHorizontal.lean @@ -0,0 +1,42 @@ +import OAI.Combinatorics.MatrixRemoval.CanonicalModeEntries +import OAI.Combinatorics.MatrixRemoval.ModeLocalization + +namespace OAI + +/-! Horizontal body localization for the canonical host entry table. -/ +namespace Problem348.Construction +open ModeLocalization + +theorem horizontal_plus_entries_impossible {h i : ℕ} {r c₀ c₁ : VariablePosition h} + (hr : AtLevel (i + 1) true r) (hc₀ : AtLevel i true c₀) + (hc₁ : AtLevel (i + 1) true c₁) + (horder : node c₀ ≤ node c₁ / 2) (hparity : node r % 2 = node c₁ % 2) + (h₀ : variableEntry r c₀ = true) (h₁ : variableEntry r c₁ = false) : False := by + apply wPlus_not_isP (node r) (node c₁) (node c₀) horder hparity + exact ⟨by simpa only [variableEntry_child_parent_plus hr hc₀] using h₀, + by simpa only [variableEntry_same_plus hr hc₁] using h₁, rfl, rfl⟩ + +/-- A W- body forces the shared leaf diagonal, as literal variable positions. -/ +theorem horizontal_minus_entries_localize {h i : ℕ} {r c₀ c₁ : VariablePosition h} + (hr : AtLevel (i + 1) false r) (hc₀ : AtLevel (i + 1) false c₀) + (hc₁ : AtLevel i false c₁) + (horder : node c₀ / 2 ≤ node c₁) (hparity : node r % 2 = node c₀ % 2) + (h₀ : variableEntry r c₀ = true) (h₁ : variableEntry r c₁ = false) : + i + 1 = h ∧ ∃ z : Fin (2 ^ h), + r = (Fin.last (2 * h), z) ∧ c₀ = (Fin.last (2 * h), z) := by + have hb : IsP + (if i + 1 = h then decide (node r ≤ node c₀) else decide (node r < node c₀)) + (decide (node r / 2 < node c₁)) true true := by + exact ⟨by simpa only [variableEntry_same_minus hr hc₀] using h₀, + by simpa only [variableEntry_child_parent_minus hr hc₁] using h₁, rfl, rfl⟩ + obtain ⟨hi, heq⟩ := wMinus_isP_implies_leaf_diagonal h (i + 1) (node r) (node c₀) (node c₁) horder hparity hb + have hrd : depth r = h := hr.1.trans hi + have hcd : depth c₀ = h := hc₀.1.trans hi + have hz : r.2 = c₀.2 := by + apply Fin.ext + simpa only [node_eq_index_of_depth_eq hrd, node_eq_index_of_depth_eq hcd] using heq + exact ⟨hi, r.2, eq_leaf_of_depth_eq hrd, by simpa only [hz] using eq_leaf_of_depth_eq hcd⟩ + +end Problem348.Construction + +end OAI diff --git a/lean/OAI/Combinatorics/MatrixRemoval/CanonicalModeEntries.lean b/lean/OAI/Combinatorics/MatrixRemoval/CanonicalModeEntries.lean new file mode 100644 index 0000000000000000000000000000000000000000..2517a11538a8d28e469dbe76307b2b6806be25f7 --- /dev/null +++ b/lean/OAI/Combinatorics/MatrixRemoval/CanonicalModeEntries.lean @@ -0,0 +1,61 @@ +import OAI.Combinatorics.MatrixRemoval.Host + +namespace OAI + +/-! Exact level-based entry formulas for the canonical flat-class host. -/ +namespace Problem348.Construction + +theorem variableEntry_same_plus {h i : ℕ} {r c : VariablePosition h} + (hr : AtLevel i true r) (hc : AtLevel i true c) : + variableEntry r c = decide (node r ≤ node c) := by + by_cases hi : i = h + · simp [variableEntry, hr.1, hc.1, hi] + · have hpr := hr.2.resolve_left hi + have hpc := hc.2.resolve_left hi + simp [variableEntry, hr.1, hc.1, hi, hpr, hpc] + +theorem variableEntry_same_minus {h i : ℕ} {r c : VariablePosition h} + (hr : AtLevel i false r) (hc : AtLevel i false c) : + variableEntry r c = + if i = h then decide (node r ≤ node c) else decide (node r < node c) := by + by_cases hi : i = h + · simp [variableEntry, hr.1, hc.1, hi] + · have hpr := hr.2.resolve_left hi + have hpc := hc.2.resolve_left hi + simp [variableEntry, hr.1, hc.1, hi, hpr, hpc] + +theorem variableEntry_child_parent_plus {h i : ℕ} {r c : VariablePosition h} + (hr : AtLevel (i + 1) true r) (hc : AtLevel i true c) : + variableEntry r c = decide (node r / 2 ≤ node c) := by + have hi : i < h := by have := depth_le r; have hrd := hr.1; omega + have hpc := hc.2.resolve_left (Nat.ne_of_lt hi) + simp [variableEntry, hr.1, hc.1, hi, hpc, hr.2] + +theorem variableEntry_child_parent_minus {h i : ℕ} {r c : VariablePosition h} + (hr : AtLevel (i + 1) false r) (hc : AtLevel i false c) : + variableEntry r c = decide (node r / 2 < node c) := by + have hi : i < h := by have := depth_le r; have hrd := hr.1; omega + have hpc := hc.2.resolve_left (Nat.ne_of_lt hi) + simp [variableEntry, hr.1, hc.1, hi, hpc, hr.2] + +/-- Maximal depth is exactly the shared leaf class. -/ +theorem class_eq_leaf_of_depth_eq {h : ℕ} {v : VariablePosition h} + (hv : depth v = h) : v.1 = Fin.last (2 * h) := by + apply Fin.ext + have := v.1.isLt + simp only [Fin.val_last] + unfold depth at hv + omega + +/-- At leaf depth a node labels a unique position, since its block has size one. -/ +theorem node_eq_index_of_depth_eq {h : ℕ} {v : VariablePosition h} + (hv : depth v = h) : node v = v.2.val := by + simp [node, hv] + +theorem eq_leaf_of_depth_eq {h : ℕ} {v : VariablePosition h} + (hv : depth v = h) : v = (Fin.last (2 * h), v.2) := by + exact Prod.ext (class_eq_leaf_of_depth_eq hv) rfl + +end Problem348.Construction + +end OAI diff --git a/lean/OAI/Combinatorics/MatrixRemoval/Consequence.lean b/lean/OAI/Combinatorics/MatrixRemoval/Consequence.lean new file mode 100644 index 0000000000000000000000000000000000000000..39a39245057edb87ffe31dc29bdae9b5705f5a86 --- /dev/null +++ b/lean/OAI/Combinatorics/MatrixRemoval/Consequence.lean @@ -0,0 +1,53 @@ +import OAI.Combinatorics.MatrixRemoval.Model +import OAI.Combinatorics.MatrixRemoval.Asymptotics + +namespace OAI + +/-! +The sequence of matrix counterexamples rules out every polynomial +removal bound. +-/ + +noncomputable section + +namespace Problem348 + +/-- Exponential decay of the copy density rules out polynomial removal bounds. -/ +theorem no_polynomial_removal_bound_of_sequence + (hseq : ∀ h : ℕ, 1 ≤ h → + let d : ℕ := 386 * h + 2 + let n : ℕ := d * 2 ^ h + ∃ A : BinaryMatrix n, + fixedDistance A ≥ 1 / ((d : ℝ) ^ 2) ∧ + (copyCount fixedH A : ℝ) / ((n : ℝ) ^ 132) ≤ + (1 / ((d : ℝ) ^ 2)) * (1 / ((2 : ℝ) ^ h))) : + ∀ c C : ℝ, 0 < c → 0 < C → + ∃ n : ℕ, 1 ≤ n ∧ + ∃ ε : ℝ, 0 < ε ∧ ε < 1 ∧ + ∃ A : BinaryMatrix n, + fixedDistance A ≥ ε ∧ + (copyCount fixedH A : ℝ) < + c * Real.rpow ε C * ((n : ℝ) ^ 132) := by + intro c C hc _hC + obtain ⟨h, hh, hdecay⟩ := exists_depth_polynomial_decay c C hc + let d : ℕ := 386 * h + 2 + let n : ℕ := d * 2 ^ h + have hd : 1 < d := by dsimp [d]; omega + have hdR : (1 : ℝ) < d := by exact_mod_cast hd + have hdpos : (0 : ℝ) < d := by linarith + have hn : 0 < n := Nat.mul_pos (by omega) (pow_pos (by decide) _) + have hnR : (0 : ℝ) < n := by exact_mod_cast hn + obtain ⟨A, hdist, hcopies⟩ := hseq h hh + refine ⟨n, hn, 1 / ((d : ℝ) ^ 2), by positivity, ?_, A, hdist, ?_⟩ + · apply (div_lt_one (by positivity)).2 + nlinarith + · have hdecay' : (1 / ((d : ℝ) ^ 2)) * (1 / ((2 : ℝ) ^ h)) < + c * Real.rpow (1 / ((d : ℝ) ^ 2)) C := by + simpa [d] using hdecay + exact (div_lt_iff₀ (pow_pos hnR 132)).mp (hcopies.trans_lt hdecay') + +end Problem348 + +end + +end OAI diff --git a/lean/OAI/Combinatorics/MatrixRemoval/CopyBound.lean b/lean/OAI/Combinatorics/MatrixRemoval/CopyBound.lean new file mode 100644 index 0000000000000000000000000000000000000000..a2d9fde3a0349ad1079d146b881d8503645617dc --- /dev/null +++ b/lean/OAI/Combinatorics/MatrixRemoval/CopyBound.lean @@ -0,0 +1,70 @@ +import Mathlib + +namespace OAI + +/-! +# Counting ordered matrix copies through a constrained cell + +The counting injection is independent of the host construction. +-/ + +namespace Problem348.CopyBound + +/-- If one specified row-column pair in every member of a finite family belongs + to `L`, the family is encoded by that cell and all remaining coordinates. -/ +theorem card_le_card_mul_pow {k n : ℕ} + (S : Finset + ({f : Fin (k + 1) → Fin n // StrictMono f} × + {f : Fin (k + 1) → Fin n // StrictMono f})) + (i j : Fin (k + 1)) (L : Finset (Fin n × Fin n)) + (hL : ∀ rc ∈ S, (rc.1.val i, rc.2.val j) ∈ L) : + S.card ≤ L.card * n ^ (2 * k) := by + classical + let encode : S → L × ((Fin k → Fin n) × (Fin k → Fin n)) := + fun rc => + (⟨(rc.val.1.val i, rc.val.2.val j), hL rc.val rc.property⟩, + (fun a => rc.val.1.val (i.succAbove a), + fun b => rc.val.2.val (j.succAbove b))) + have hinj : Function.Injective encode := by + intro x y hxy + apply Subtype.ext + apply Prod.ext + · apply Subtype.ext + funext a + rcases Fin.eq_self_or_eq_succAbove i a with ha | ⟨b, hb⟩ + · subst a + exact congrArg (fun z => z.1.val.1) hxy + · subst a + exact congrArg (fun z => z.2.1 b) hxy + · apply Subtype.ext + funext a + rcases Fin.eq_self_or_eq_succAbove j a with ha | ⟨b, hb⟩ + · subst a + exact congrArg (fun z => z.1.val.2) hxy + · subst a + exact congrArg (fun z => z.2.2 b) hxy + have hc := Fintype.card_le_of_injective encode hinj + simpa only [Fintype.card_coe, Fintype.card_prod, Fintype.card_fun, + Fintype.card_fin, two_mul, pow_add, mul_assoc] using hc + +/-- Normalize the integer count bound from the leaf-diagonal argument. -/ +theorem normalized_count_le {count d m : ℕ} (hd : 0 < d) (hm : 0 < m) + (hcount : count ≤ m * (d * m) ^ 130) : + (count : ℝ) / (((d * m : ℕ) : ℝ) ^ 132) ≤ + (1 / ((d : ℝ) ^ 2)) * (1 / (m : ℝ)) := by + have hd0 : (d : ℝ) ≠ 0 := by exact_mod_cast Nat.ne_of_gt hd + have hm0 : (m : ℝ) ≠ 0 := by exact_mod_cast Nat.ne_of_gt hm + have hcount' : (count : ℝ) ≤ (m : ℝ) * ((d : ℝ) * (m : ℝ)) ^ 130 := by + exact_mod_cast hcount + push_cast + calc + (count : ℝ) / ((d : ℝ) * (m : ℝ)) ^ 132 ≤ + ((m : ℝ) * ((d : ℝ) * (m : ℝ)) ^ 130) / + ((d : ℝ) * (m : ℝ)) ^ 132 := + div_le_div_of_nonneg_right hcount' (by positivity) + _ = (1 / ((d : ℝ) ^ 2)) * (1 / (m : ℝ)) := by + field_simp + +end Problem348.CopyBound + +end OAI diff --git a/lean/OAI/Combinatorics/MatrixRemoval/CopyBoundFixed.lean b/lean/OAI/Combinatorics/MatrixRemoval/CopyBoundFixed.lean new file mode 100644 index 0000000000000000000000000000000000000000..06066c02a0f39f907abc467335787dc0df36dc7d --- /dev/null +++ b/lean/OAI/Combinatorics/MatrixRemoval/CopyBoundFixed.lean @@ -0,0 +1,69 @@ +import OAI.Combinatorics.MatrixRemoval.Model +import OAI.Combinatorics.MatrixRemoval.CopyBound + +namespace OAI + +namespace Problem348 + +/-- Ordered-copy specialization of the generic constrained-cell bound. -/ +theorem copyCount_le_of_cell_mem {k n : ℕ} + (H : BinaryMatrix (k + 1)) (A : BinaryMatrix n) + (i j : Fin (k + 1)) (L : Finset (Fin n × Fin n)) + (hL : ∀ rc ∈ orderedCopies H A, (rc.1.val i, rc.2.val j) ∈ L) : + copyCount H A ≤ L.card * n ^ (2 * k) := + CopyBound.card_le_card_mul_pow (orderedCopies H A) i j L hL + +/-- Locate the top-left body entry (zero-based index 64) to count fixed-H copies. -/ +theorem fixedCopyCount_le_of_body_cell_mem {n : ℕ} + (A : BinaryMatrix n) (L : Finset (Fin n × Fin n)) + (hL : ∀ rc ∈ orderedCopies fixedH A, (rc.1.val 64, rc.2.val 64) ∈ L) : + copyCount fixedH A ≤ L.card * n ^ 130 := + copyCount_le_of_cell_mem fixedH A 64 64 L hL + +/-- The copy bound reduced to concrete leaf localization. -/ +theorem fixedCopyDensity_le_of_body_cell_mem {d m : ℕ} + (hd : 0 < d) (hm : 0 < m) (A : BinaryMatrix (d * m)) + (L : Finset (Fin (d * m) × Fin (d * m))) (hcard : L.card ≤ m) + (hL : ∀ rc ∈ orderedCopies fixedH A, (rc.1.val 64, rc.2.val 64) ∈ L) : + (copyCount fixedH A : ℝ) / (((d * m : ℕ) : ℝ) ^ 132) ≤ + (1 / ((d : ℝ) ^ 2)) * (1 / (m : ℝ)) := by + apply CopyBound.normalized_count_le hd hm + exact (fixedCopyCount_le_of_body_cell_mem A L hL).trans + (Nat.mul_le_mul_right _ hcard) + +/-- The exact numerical upper bound appearing in counterexample_sequence. -/ +theorem sequenceCopyDensity_le_of_body_cell_mem (h : ℕ) + (A : BinaryMatrix ((386 * h + 2) * 2 ^ h)) + (L : Finset + (Fin ((386 * h + 2) * 2 ^ h) × Fin ((386 * h + 2) * 2 ^ h))) + (hcard : L.card ≤ 2 ^ h) + (hL : ∀ rc ∈ orderedCopies fixedH A, (rc.1.val 64, rc.2.val 64) ∈ L) : + (copyCount fixedH A : ℝ) / ((((386 * h + 2) * 2 ^ h : ℕ) : ℝ) ^ 132) ≤ + (1 / (((386 * h + 2 : ℕ) : ℝ) ^ 2)) * (1 / ((2 : ℝ) ^ h)) := by + simpa only [Nat.cast_pow, Nat.cast_ofNat] using + fixedCopyDensity_le_of_body_cell_mem (by omega : 0 < 386 * h + 2) + (by positivity : 0 < 2 ^ h) A L hcard hL + +/-- A localization witness is enough; no separate leaf-cell set or injectivity +proof is required for the upper bound. Images can only decrease cardinality. -/ +theorem sequenceCopyDensity_le_of_leaf_witness (h : ℕ) + (A : BinaryMatrix ((386 * h + 2) * 2 ^ h)) + (rowLeaf colLeaf : Fin (2 ^ h) → Fin ((386 * h + 2) * 2 ^ h)) + (hloc : ∀ r c : IncreasingMap 66 ((386 * h + 2) * 2 ^ h), + (∀ i j, A (r.val i) (c.val j) = fixedH i j) → + ∃ z, r.val 64 = rowLeaf z ∧ c.val 64 = colLeaf z) : + (copyCount fixedH A : ℝ) / ((((386 * h + 2) * 2 ^ h : ℕ) : ℝ) ^ 132) ≤ + (1 / (((386 * h + 2 : ℕ) : ℝ) ^ 2)) * (1 / ((2 : ℝ) ^ h)) := by + classical + let L := Finset.univ.image (fun z => (rowLeaf z, colLeaf z)) + apply sequenceCopyDensity_le_of_body_cell_mem h A L + · exact Finset.card_image_le.trans (by simp) + · intro rc hrc + have hentries : ∀ i j, A (rc.1.val i) (rc.2.val j) = fixedH i j := + (Finset.mem_filter.mp hrc).2 + obtain ⟨z, hrow, hcol⟩ := hloc rc.1 rc.2 hentries + exact Finset.mem_image.mpr ⟨z, Finset.mem_univ _, by simp [hrow, hcol]⟩ + +end Problem348 + +end OAI diff --git a/lean/OAI/Combinatorics/MatrixRemoval/DirectNonshattering.lean b/lean/OAI/Combinatorics/MatrixRemoval/DirectNonshattering.lean new file mode 100644 index 0000000000000000000000000000000000000000..cbda3acc3867f21b6a3e8a76173245aaddc7754c --- /dev/null +++ b/lean/OAI/Combinatorics/MatrixRemoval/DirectNonshattering.lean @@ -0,0 +1,270 @@ +import Mathlib + +namespace OAI + +/-! +A direct qualitative proof of the non-anchor trace obstruction. +No enumeration of suffix generators is needed. + +If all binary words occur, any two selected columns in the same class can be +separated by a singleton word, contradicting their suffix monotonicity. +Thus all five classes are distinct. The word 11110 then uses four classes, +while a variable row uses at most three and a dummy row is all ones. +-/ + +universe uR uC uK uL uRho uBeta + +namespace Problem348.DirectNonshattering + +open Finset + +/-- A surjective family of class-monotone words separates the column classes. -/ +theorem class_injective_of_surjective + {R : Type uR} {C : Type uC} {K : Type uK} [DecidableEq C] [LinearOrder K] + {L : Type uL} (classOf : C → L) (key : C → K) (A : R → C → Bool) + (hmono : ∀ r i j, classOf i = classOf j → key i ≤ key j → + A r i = true → A r j = true) + (hsurj : Function.Surjective A) : Function.Injective classOf := by + intro i j hij + by_contra hne + rcases le_total (key i) (key j) with hle | hle + · obtain ⟨r, hr⟩ := hsurj (fun x => decide (x = i)) + have hi : A r i = true := by rw [hr]; simp + have hj : A r j = true := hmono r i j hij hle hi + rw [hr] at hj + simp [Ne.symm hne] at hj + · obtain ⟨r, hr⟩ := hsurj (fun x => decide (x = j)) + have hj : A r j = true := by rw [hr]; simp + have hi : A r i = true := hmono r j i hij.symm hle hj + rw [hr] at hi + simp [hne] at hi + +/-- General form: `q + 2` columns cannot be shattered by classwise suffix +rows supported on at most `q` classes, together with all-one rows. -/ +theorem not_surjective_of_card + {R : Type uR} {C : Type uC} {L : Type uL} {K : Type uK} [Fintype C] [DecidableEq C] [DecidableEq L] + [LinearOrder K] (q : ℕ) (hcard : q + 2 ≤ Fintype.card C) + (classOf : C → L) (key : C → K) (A : R → C → Bool) + (hmono : ∀ r i j, classOf i = classOf j → key i ≤ key j → + A r i = true → A r j = true) + (hsupport : ∀ r, + ((univ.filter (fun i => A r i = true)).image classOf).card ≤ q ∨ + (∀ i, A r i = true)) : + ¬ Function.Surjective A := by + classical + intro hsurj + have hinj := class_injective_of_surjective classOf key A hmono hsurj + have : Nonempty C := Fintype.card_pos_iff.mp (by omega) + let j : C := Classical.arbitrary C + obtain ⟨r, hr⟩ := hsurj (fun i => decide (i ≠ j)) + rcases hsupport r with hs | hd + · rw [hr, card_image_of_injective _ hinj] at hs + change (univ.filter (fun i : C => decide (i ≠ j) = true)).card ≤ q at hs + have hfilter : (univ.filter (fun i : C => decide (i ≠ j) = true)) = + univ.erase j := by + ext i + simp + rw [hfilter, card_erase_of_mem (mem_univ j), card_univ] at hs + omega + · have hj := hd j + rw [hr] at hj + simp at hj + +/-- No family with suffixes in at most three classes, plus all-one rows, +realizes every binary word on five columns. -/ +theorem not_surjective_five + {R : Type uR} {L : Type uL} {K : Type uK} [DecidableEq L] [LinearOrder K] + (classOf : Fin 5 → L) (key : Fin 5 → K) (A : R → Fin 5 → Bool) + (hmono : ∀ r i j, classOf i = classOf j → key i ≤ key j → + A r i = true → A r j = true) + (hsupport : ∀ r, + ((univ.filter (fun i => A r i = true)).image classOf).card ≤ 3 ∨ + (∀ i, A r i = true)) : + ¬ Function.Surjective A := + not_surjective_of_card 3 (by simp) classOf key A hmono hsupport + +/-- The conclusion in a form convenient for a five-column shattering test. -/ +theorem exists_missing_word + {R : Type uR} {L : Type uL} {K : Type uK} [DecidableEq L] [LinearOrder K] + (classOf : Fin 5 → L) (key : Fin 5 → K) (A : R → Fin 5 → Bool) + (hmono : ∀ r i j, classOf i = classOf j → key i ≤ key j → + A r i = true → A r j = true) + (hsupport : ∀ r, + ((univ.filter (fun i => A r i = true)).image classOf).card ≤ 3 ∨ + (∀ i, A r i = true)) : + ∃ w : Fin 5 → Bool, ∀ r, A r ≠ w := by + simpa only [Function.Surjective, not_forall, not_exists] using + not_surjective_five classOf key A hmono hsupport + +/-- A column equal to one in every row also rules out shattering immediately. -/ +theorem not_surjective_of_constant_column + {R : Type uR} {C : Type uC} (A : R → C → Bool) (j : C) + (hj : ∀ r, A r j = true) : ¬ Function.Surjective A := by + intro hsurj + obtain ⟨r, hr⟩ := hsurj (fun _ => false) + have h := hj r + rw [hr] at h + cases h + +/-- Whole-host version. Dummy columns are all ones, and every non-dummy row +has at most three active classes among the non-dummy columns. The chosen five +columns need not be ordered or even assumed distinct. -/ +theorem not_surjective_selected_columns + {R : Type uR} {C : Type uC} {L : Type uL} {K : Type uK} [Fintype C] [DecidableEq C] [DecidableEq L] + [LinearOrder K] + (A : R → C → Bool) (dummyRow : R → Prop) (dummyColumn : C → Prop) + [DecidablePred dummyColumn] + (classOf : C → L) (key : C → K) + (hrow : ∀ r, dummyRow r → ∀ c, A r c = true) + (hcolumn : ∀ c, dummyColumn c → ∀ r, A r c = true) + (hmono : ∀ r, ¬ dummyRow r → ∀ c d, + ¬ dummyColumn c → ¬ dummyColumn d → classOf c = classOf d → + key c ≤ key d → A r c = true → A r d = true) + (hsupport : ∀ r, ¬ dummyRow r → + ((univ.filter (fun c => ¬ dummyColumn c ∧ A r c = true)).image classOf).card ≤ 3) + (selected : Fin 5 → C) : + ¬ Function.Surjective (fun r i => A r (selected i)) := by + classical + by_cases hdummy : ∃ i, dummyColumn (selected i) + · obtain ⟨i, hi⟩ := hdummy + exact not_surjective_of_constant_column (fun r j => A r (selected j)) i + (hcolumn (selected i) hi) + · have hnondummy : ∀ i, ¬ dummyColumn (selected i) := by + simpa only [not_exists] using hdummy + apply not_surjective_five (classOf ∘ selected) (key ∘ selected) + (fun r i => A r (selected i)) + · intro r i j hij hle hi + by_cases hr : dummyRow r + · exact hrow r hr (selected j) + · exact hmono r hr (selected i) (selected j) + (hnondummy i) (hnondummy j) hij hle hi + · intro r + by_cases hr : dummyRow r + · exact Or.inr (fun i => hrow r hr (selected i)) + · left + refine (card_le_card (show + (univ.filter (fun i => A r (selected i) = true)).image (classOf ∘ selected) ⊆ + (univ.filter (fun c => ¬ dummyColumn c ∧ A r c = true)).image classOf + from ?_)).trans (hsupport r hr) + intro l hl + obtain ⟨i, hi, rfl⟩ := mem_image.mp hl + exact mem_image.mpr ⟨selected i, + mem_filter.mpr ⟨mem_univ _, hnondummy i, (mem_filter.mp hi).2⟩, rfl⟩ + + +/-- On `k+2` coordinates, classwise monotone traces with at most `k` +active classes, allowing also the constant-one trace, omit a Boolean word. +The rank need not be injective within a class. -/ +theorem exists_missing_word_with_zero {ρ : Type uRho} {β : Type uBeta} [DecidableEq β] (k : ℕ) + (cls : Fin (k + 2) → β) (key : Fin (k + 2) → ℕ) + (trace : ρ → Fin (k + 2) → Bool) + (hup : ∀ r a b, cls a = cls b → key a ≤ key b → + trace r a = true → trace r b = true) + (hsupport : ∀ r, (∀ j, trace r j = true) ∨ + ((Finset.univ.filter (fun j => trace r j = true)).image cls).card ≤ k) : + ∃ word : Fin (k + 2) → Bool, + (∃ j, word j = false) ∧ ∀ r, trace r ≠ word := by + classical + by_cases hinj : Function.Injective cls + · let word : Fin (k + 2) → Bool := fun j => decide (j ≠ 0) + refine ⟨word, ⟨0, by simp [word]⟩, ?_⟩ + intro r heq + rcases hsupport r with hall | hsmall + · have hzero := hall 0 + rw [heq] at hzero + simp [word] at hzero + · rw [heq] at hsmall + rw [Finset.card_image_of_injective _ hinj] at hsmall + have hset : Finset.univ.filter (fun j : Fin (k + 2) => word j = true) = + Finset.univ.erase 0 := by + ext j + simp [word] + rw [hset] at hsmall + simp at hsmall + · obtain ⟨a, b, hab, hne⟩ := Function.not_injective_iff.mp hinj + have hp : ∃ a b : Fin (k + 2), + a ≠ b ∧ cls a = cls b ∧ key a ≤ key b := by + rcases le_total (key a) (key b) with h | h + · exact ⟨a, b, hne, hab, h⟩ + · exact ⟨b, a, hne.symm, hab.symm, h⟩ + obtain ⟨a, b, hne, hab, hkey⟩ := hp + let word : Fin (k + 2) → Bool := fun j => decide (j = a) + refine ⟨word, ⟨b, by simp [word, hne.symm]⟩, ?_⟩ + intro r heq + have ha : trace r a = true := by simp [heq, word] + have hb := hup r a b hab hkey ha + simp [heq, word, hne.symm] at hb + +/-- Coordinatewise form of the missing-word theorem. -/ +theorem exists_missing_word_pointwise {ρ : Type uRho} {β : Type uBeta} [DecidableEq β] (k : ℕ) + (cls : Fin (k + 2) → β) (key : Fin (k + 2) → ℕ) + (trace : ρ → Fin (k + 2) → Bool) + (hup : ∀ r a b, cls a = cls b → key a ≤ key b → + trace r a = true → trace r b = true) + (hsupport : ∀ r, (∀ j, trace r j = true) ∨ + ((Finset.univ.filter (fun j => trace r j = true)).image cls).card ≤ k) : + ∃ word : Fin (k + 2) → Bool, ∀ r, ∃ j, trace r j ≠ word j := by + classical + obtain ⟨word, _, hw⟩ := exists_missing_word_with_zero k cls key trace hup hsupport + refine ⟨word, fun r => ?_⟩ + by_contra h + push Not at h + exact hw r (funext h) + +/-- Matrix-facing form, handling both dummy columns and dummy rows. +No injectivity assumption on the selected columns is needed. -/ +theorem matrix_missing_word {R : Type uR} {C : Type uC} {β : Type uBeta} [DecidableEq β] (k : ℕ) + (A : R → C → Bool) (cols : Fin (k + 2) → C) + (cls : C → β) (key : C → ℕ) (dummyRow : R → Prop) (dummyCol : C → Prop) + (hdummyRow : ∀ r, dummyRow r → ∀ c, A r c = true) + (hdummyCol : ∀ c, dummyCol c → ∀ r, A r c = true) + (hup : ∀ r, ¬ dummyRow r → ∀ a b, + ¬ dummyCol a → ¬ dummyCol b → cls a = cls b → key a ≤ key b → + A r a = true → A r b = true) + (hsupport : ∀ r, ¬ dummyRow r → + (∀ j, ¬ dummyCol (cols j)) → + ((Finset.univ.filter (fun j => A r (cols j) = true)).image + (cls ∘ cols)).card ≤ k) : + ∃ word : Fin (k + 2) → Bool, ∀ r, ∃ j, A r (cols j) ≠ word j := by + classical + by_cases hd : ∃ j, dummyCol (cols j) + · obtain ⟨j, hj⟩ := hd + refine ⟨fun _ => false, fun r => ⟨j, ?_⟩⟩ + simp [hdummyCol (cols j) hj r] + · push Not at hd + apply exists_missing_word_pointwise k (cls ∘ cols) (key ∘ cols) + (fun r j => A r (cols j)) + · intro r a b hab hkey ha + by_cases hr : dummyRow r + · exact hdummyRow r hr (cols b) + · exact hup r hr (cols a) (cols b) (hd a) (hd b) hab hkey ha + · intro r + by_cases hr : dummyRow r + · exact Or.inl (fun j => hdummyRow r hr (cols j)) + · exact Or.inr (hsupport r hr hd) + +/-- An explicit cover by at most `k` column classes is enough for the +support premise. This form avoids cardinal computations on selected columns. -/ +theorem matrix_missing_word_of_class_cover {R : Type uR} {C : Type uC} {β : Type uBeta} [DecidableEq β] (k : ℕ) + (A : R → C → Bool) (cols : Fin (k + 2) → C) + (cls : C → β) (key : C → ℕ) (dummyRow : R → Prop) (dummyCol : C → Prop) + (hdummyRow : ∀ r, dummyRow r → ∀ c, A r c = true) + (hdummyCol : ∀ c, dummyCol c → ∀ r, A r c = true) + (hup : ∀ r, ¬ dummyRow r → ∀ a b, + ¬ dummyCol a → ¬ dummyCol b → cls a = cls b → key a ≤ key b → + A r a = true → A r b = true) + (hcover : ∀ r, ¬ dummyRow r → ∃ S : Finset β, S.card ≤ k ∧ + ∀ c, ¬ dummyCol c → A r c = true → cls c ∈ S) : + ∃ word : Fin (k + 2) → Bool, ∀ r, ∃ j, A r (cols j) ≠ word j := by + classical + apply matrix_missing_word k A cols cls key dummyRow dummyCol hdummyRow hdummyCol hup + intro r hr hcols + obtain ⟨S, hS, hmem⟩ := hcover r hr + apply le_trans (Finset.card_le_card ?_) hS + intro c hc + obtain ⟨j, hj, rfl⟩ := Finset.mem_image.mp hc + exact hmem (cols j) (hcols j) (Finset.mem_filter.mp hj).2 + +end Problem348.DirectNonshattering + +end OAI diff --git a/lean/OAI/Combinatorics/MatrixRemoval/GuardContainment.lean b/lean/OAI/Combinatorics/MatrixRemoval/GuardContainment.lean new file mode 100644 index 0000000000000000000000000000000000000000..bc1378f819703438c48f4bec1c90f67ea9c9f6dd --- /dev/null +++ b/lean/OAI/Combinatorics/MatrixRemoval/GuardContainment.lean @@ -0,0 +1,141 @@ +import OAI.Combinatorics.MatrixRemoval.HostSampling +import OAI.Combinatorics.MatrixRemoval.GuardedPath + +namespace OAI + +/-! +Containment of guarded-path cells in the protected sampling set. +The geometric validity of a selection and the cellwise counting bound +are separate requirements. +-/ + +namespace Problem348.Construction.HostSampling + +open Problem348.TreeSampling Problem348.GuardedPath + +variable {h n : ℕ} + +/-- A selected row after the independent row reindexing. -/ +def RowChosen (row : Position h ≃ Fin n) (s : Seeds (2 ^ h)) (r : Fin n) : Prop := + coordinate s.1 s.2.1 (row.symm r) = offset (row.symm r) + +/-- A selected column after the independent column reindexing. -/ +def ColChosen (col : Position h ≃ Fin n) (s : Seeds (2 ^ h)) (c : Fin n) : Prop := + coordinate s.1 s.2.2 (col.symm c) = offset (col.symm c) + +/-- The exact cell predicate needed by `transported_guard_frequency`. -/ +def GoodCell (row col : Position h ≃ Fin n) (s : Seeds (2 ^ h)) + (rc : Fin n × Fin n) : Prop := + Protected (row.symm rc.1) (col.symm rc.2) ∧ + Selected s (row.symm rc.1) (col.symm rc.2) + + theorem goodCell_of_chosen {row col : Position h ≃ Fin n} {s : Seeds (2 ^ h)} + {r c : Fin n} (hp : Protected (row.symm r) (col.symm c)) + (hr : RowChosen row s r) (hc : ColChosen col s c) : + GoodCell row col s (r, c) := + ⟨hp, Prod.ext hr hc⟩ + +/-- A selected anchor frame, considered only as a family of protected positions. -/ +structure FrameChosen (row col : Position h ≃ Fin n) (s : Seeds (2 ^ h)) + (F : AnchorFrame n) : Prop where + row_independent : ∀ u, sampleDepth (row.symm (F.rows.val u)) = none + col_independent : ∀ v, sampleDepth (col.symm (F.cols.val v)) = none + row_chosen : ∀ u, RowChosen row s (F.rows.val u) + col_chosen : ∀ v, ColChosen col s (F.cols.val v) + +/-- All anchor and signature cells of a chosen frame are protected and selected. -/ +theorem FrameChosen.cell_good {row col : Position h ≃ Fin n} {s : Seeds (2 ^ h)} + {F : AnchorFrame n} (hF : FrameChosen row col s F) + {r₀ r₁ c₀ c₁ : Fin n} + (hr₀ : RowChosen row s r₀) (hr₁ : RowChosen row s r₁) + (hc₀ : ColChosen col s c₀) (hc₁ : ColChosen col s c₁) + {rc : Fin n × Fin n} (hcell : F.Cell r₀ r₁ c₀ c₁ rc) : + GoodCell row col s rc := by + rcases hcell with ⟨u, v, rfl⟩ | ⟨v, rfl | rfl⟩ | ⟨u, rfl | rfl⟩ + · exact goodCell_of_chosen (Or.inl (hF.row_independent u)) + (hF.row_chosen u) (hF.col_chosen v) + · exact goodCell_of_chosen (Or.inr (Or.inl (hF.col_independent v))) + hr₀ (hF.col_chosen v) + · exact goodCell_of_chosen (Or.inr (Or.inl (hF.col_independent v))) + hr₁ (hF.col_chosen v) + · exact goodCell_of_chosen (Or.inl (hF.row_independent u)) + (hF.row_chosen u) hc₀ + · exact goodCell_of_chosen (Or.inl (hF.row_independent u)) + (hF.row_chosen u) hc₁ + +/-- Purely geometric sampling facts, separate from the host's matrix values. -/ +structure PathChosen (row col : Position h ≃ Fin n) (s : Seeds (2 ^ h)) + (P : Selection n) : Prop where + xp_chosen : ∀ i, i ≤ h → RowChosen row s (P.xp i) + xm_chosen : ∀ i, i ≤ h → RowChosen row s (P.xm i) + yp_chosen : ∀ i, i ≤ h → ColChosen col s (P.yp i) + ym_chosen : ∀ i, i ≤ h → ColChosen col s (P.ym i) + xd_chosen : RowChosen row s P.xd + yd_chosen : ColChosen col s P.yd + xd_independent : sampleDepth (row.symm P.xd) = none + yd_independent : sampleDepth (col.symm P.yd) = none + root_plus : Protected (row.symm (P.xp 0)) (col.symm (P.yp 0)) + root_minus : Protected (row.symm (P.xm 0)) (col.symm (P.ym 0)) + vertical_plus : ∀ i, i < h → FrameChosen row col s (P.vPlus i) + vertical_minus : ∀ i, i < h → FrameChosen row col s (P.vMinus i) + horizontal_plus : ∀ i, i < h → FrameChosen row col s (P.wPlus i) + horizontal_minus : ∀ i, i < h → FrameChosen row col s (P.wMinus i) + + theorem PathChosen.core_good {row col : Position h ≃ Fin n} {s : Seeds (2 ^ h)} + {P : Selection n} (hP : PathChosen row col s P) + {rc : Fin n × Fin n} (hc : P.CoreCell h rc) : GoodCell row col s rc := by + rcases hc with rfl | rfl | ⟨i, hi, rfl | rfl | rfl | rfl⟩ + · exact goodCell_of_chosen hP.root_plus + (hP.xp_chosen 0 (Nat.zero_le _)) (hP.yp_chosen 0 (Nat.zero_le _)) + · exact goodCell_of_chosen hP.root_minus + (hP.xm_chosen 0 (Nat.zero_le _)) (hP.ym_chosen 0 (Nat.zero_le _)) + · exact goodCell_of_chosen (Or.inr (Or.inl hP.yd_independent)) + (hP.xp_chosen i hi) hP.yd_chosen + · exact goodCell_of_chosen (Or.inr (Or.inl hP.yd_independent)) + (hP.xm_chosen i hi) hP.yd_chosen + · exact goodCell_of_chosen (Or.inl hP.xd_independent) + hP.xd_chosen (hP.yp_chosen i hi) + · exact goodCell_of_chosen (Or.inl hP.xd_independent) + hP.xd_chosen (hP.ym_chosen i hi) + + theorem PathChosen.edge_good {row col : Position h ≃ Fin n} {s : Seeds (2 ^ h)} + {P : Selection n} (hP : PathChosen row col s P) {i : ℕ} (hi : i < h) + {rc : Fin n × Fin n} (hc : P.EdgeCell i rc) : GoodCell row col s rc := by + have hil : i ≤ h := Nat.le_of_lt hi + have his : i + 1 ≤ h := hi + rcases hc with hc | hc | hc | hc + · exact (hP.vertical_plus i hi).cell_good + (hP.xp_chosen (i + 1) his) (hP.xp_chosen i hil) + hP.yd_chosen (hP.yp_chosen i hil) hc + · exact (hP.vertical_minus i hi).cell_good + (hP.xm_chosen i hil) (hP.xm_chosen (i + 1) his) + hP.yd_chosen (hP.ym_chosen i hil) hc + · exact (hP.horizontal_plus i hi).cell_good + (hP.xp_chosen (i + 1) his) hP.xd_chosen + (hP.yp_chosen i hil) (hP.yp_chosen (i + 1) his) hc + · exact (hP.horizontal_minus i hi).cell_good + (hP.xm_chosen (i + 1) his) hP.xd_chosen + (hP.ym_chosen (i + 1) his) (hP.ym_chosen i hil) hc + +/-- Every actual guarded-path cell is in the protected selected-cell event. -/ +theorem PathChosen.guard_good {row col : Position h ≃ Fin n} {s : Seeds (2 ^ h)} + {P : Selection n} (hP : PathChosen row col s P) + {rc : Fin n × Fin n} (hc : rc ∈ P.guards h) : GoodCell row col s rc := by + rw [Selection.mem_guards] at hc + rcases hc with hc | ⟨i, hi, hc⟩ + · exact hP.core_good hc + · exact hP.edge_good hi hc + +/-- The frequency bound for any concretely chosen family of paths. -/ +theorem path_guard_frequency (row col : Position h ≃ Fin n) + (P : Seeds (2 ^ h) → Selection n) + (hP : ∀ s, PathChosen row col s (P s)) (rc : Fin n × Fin n) : + (Finset.univ.filter fun s => rc ∈ (P s).guards h).card * (2 ^ h) ^ 2 ≤ + Fintype.card (Seeds (2 ^ h)) := by + classical + exact transported_guard_frequency row col (fun s => (P s).guards h) + (fun s _ hc => (hP s).guard_good hc) rc + +end Problem348.Construction.HostSampling + +end OAI diff --git a/lean/OAI/Combinatorics/MatrixRemoval/GuardedFrame.lean b/lean/OAI/Combinatorics/MatrixRemoval/GuardedFrame.lean new file mode 100644 index 0000000000000000000000000000000000000000..06407187670d58969731615a6048b39dca82c8f1 --- /dev/null +++ b/lean/OAI/Combinatorics/MatrixRemoval/GuardedFrame.lean @@ -0,0 +1,71 @@ +import OAI.Combinatorics.MatrixRemoval.BodyExtension +import OAI.Combinatorics.MatrixRemoval.PathPropagation + +namespace OAI + +/-! Exact selected-anchor frames and their protected cells. +The frame does not constrain any of the four body entries. -/ + +noncomputable section +namespace Problem348.GuardedPath + +structure AnchorFrame (n : ℕ) where + rows : IncreasingMap 64 n + cols : IncreasingMap 64 n + +namespace AnchorFrame + +variable {n : ℕ} + +/-- All data needed to extend a body, except the body entries themselves. -/ +structure Valid (F : AnchorFrame n) (A : BinaryMatrix n) + (r₀ r₁ c₀ c₁ : Fin n) : Prop where + row_before : ∀ u, F.rows.val u < r₀ + row_lt : r₀ < r₁ + col_before : ∀ v, F.cols.val v < c₀ + col_lt : c₀ < c₁ + anchor : ∀ u v, A (F.rows.val u) (F.cols.val v) = anchor64 u v + row_zero : ∀ v, A r₀ (F.cols.val v) = decide (v.val = 0) + row_one : ∀ v, A r₁ (F.cols.val v) = decide (v.val = 1) + col_zero : ∀ u, A (F.rows.val u) c₀ = decide (u.val = 0) + col_one : ∀ u, A (F.rows.val u) c₁ = decide (u.val = 1) + +/-- Precisely the anchor and signature cells of one selected frame. -/ +def Cell (F : AnchorFrame n) (r₀ r₁ c₀ c₁ : Fin n) + (rc : Fin n × Fin n) : Prop := + (∃ u v, rc = (F.rows.val u, F.cols.val v)) ∨ + (∃ v, rc = (r₀, F.cols.val v) ∨ rc = (r₁, F.cols.val v)) ∨ + (∃ u, rc = (F.rows.val u, c₀) ∨ rc = (F.rows.val u, c₁)) + +/-- Agreement only on frame cells preserves anchor and signature validity. -/ +theorem Valid.transfer {F : AnchorFrame n} {A B : BinaryMatrix n} + {r₀ r₁ c₀ c₁ : Fin n} (hF : F.Valid A r₀ r₁ c₀ c₁) + (hag : ∀ rc, F.Cell r₀ r₁ c₀ c₁ rc → A rc.1 rc.2 = B rc.1 rc.2) : + F.Valid B r₀ r₁ c₀ c₁ := by + refine ⟨hF.row_before, hF.row_lt, hF.col_before, hF.col_lt, ?_, ?_, ?_, ?_, ?_⟩ + · intro u v + exact (hag _ (Or.inl ⟨u, v, rfl⟩)).symm.trans (hF.anchor u v) + · intro v + exact (hag _ (Or.inr (Or.inl ⟨v, Or.inl rfl⟩))).symm.trans (hF.row_zero v) + · intro v + exact (hag _ (Or.inr (Or.inl ⟨v, Or.inr rfl⟩))).symm.trans (hF.row_one v) + · intro u + exact (hag _ (Or.inr (Or.inr ⟨u, Or.inl rfl⟩))).symm.trans (hF.col_zero u) + · intro u + exact (hag _ (Or.inr (Or.inr ⟨u, Or.inr rfl⟩))).symm.trans (hF.col_one u) + +/-- A valid frame and the body give a genuine ordered copy of the fixed H. -/ +theorem Valid.not_HFree {F : AnchorFrame n} {B : BinaryMatrix n} + {r₀ r₁ c₀ c₁ : Fin n} (hF : F.Valid B r₀ r₁ c₀ c₁) + (hbody : PathPropagation.Body B r₀ r₁ c₀ c₁) : ¬ HFree fixedH B := by + exact not_HFree_of_anchor_body B F.rows F.cols r₀ r₁ c₀ c₁ + hF.row_before hF.row_lt hF.col_before hF.col_lt + hF.anchor hF.row_zero hF.row_one hF.col_zero hF.col_one + hbody.1 hbody.2.1 hbody.2.2.1 hbody.2.2.2 + +end AnchorFrame +end Problem348.GuardedPath + +end + +end OAI diff --git a/lean/OAI/Combinatorics/MatrixRemoval/GuardedPath.lean b/lean/OAI/Combinatorics/MatrixRemoval/GuardedPath.lean new file mode 100644 index 0000000000000000000000000000000000000000..34185ed38a03e4264e452dc86bfcb24090c3667b --- /dev/null +++ b/lean/OAI/Combinatorics/MatrixRemoval/GuardedPath.lean @@ -0,0 +1,148 @@ +import OAI.Combinatorics.MatrixRemoval.GuardedFrame + +namespace OAI + +/-! +A deterministic arbitrary-repair obstruction for the fixed binary pattern. +A selection records one common tree path, dummy positions, and four selected +anchor frames per edge. Its guards contain only root, dummy, anchor, and +anchor/body signature cells -- never the unconstrained variable body cells. +-/ + +noncomputable section +namespace Problem348.GuardedPath + +/-- Selected positions; no host construction or matching assumptions are hidden +in this data structure. Values past the chosen depth are irrelevant. -/ +structure Selection (n : ℕ) where + xp : ℕ → Fin n + xm : ℕ → Fin n + yp : ℕ → Fin n + ym : ℕ → Fin n + xd : Fin n + yd : Fin n + vPlus : ℕ → AnchorFrame n + vMinus : ℕ → AnchorFrame n + wPlus : ℕ → AnchorFrame n + wMinus : ℕ → AnchorFrame n + +namespace Selection +variable {n : ℕ} + +/-- Root and dummy cells needed for Boolean propagation. -/ +def CoreCell (P : Selection n) (h : ℕ) (rc : Fin n × Fin n) : Prop := + rc = (P.xp 0, P.yp 0) ∨ rc = (P.xm 0, P.ym 0) ∨ + ∃ i, i ≤ h ∧ (rc = (P.xp i, P.yd) ∨ rc = (P.xm i, P.yd) ∨ + rc = (P.xd, P.yp i) ∨ rc = (P.xd, P.ym i)) + +/-- Anchor and signature cells for the four modes at one edge. -/ +def EdgeCell (P : Selection n) (i : ℕ) (rc : Fin n × Fin n) : Prop := + (P.vPlus i).Cell (P.xp (i + 1)) (P.xp i) P.yd (P.yp i) rc ∨ + (P.vMinus i).Cell (P.xm i) (P.xm (i + 1)) P.yd (P.ym i) rc ∨ + (P.wPlus i).Cell (P.xp (i + 1)) P.xd (P.yp i) (P.yp (i + 1)) rc ∨ + (P.wMinus i).Cell (P.xm (i + 1)) P.xd (P.ym (i + 1)) (P.ym i) rc + +/-- The protected cells of the whole selected path. -/ +def GuardCell (P : Selection n) (h : ℕ) (rc : Fin n × Fin n) : Prop := + P.CoreCell h rc ∨ ∃ i, i < h ∧ P.EdgeCell i rc + +def guards (P : Selection n) (h : ℕ) : Finset (Fin n × Fin n) := by + classical + exact Finset.univ.filter (P.GuardCell h) + +@[simp] theorem mem_guards (P : Selection n) (h : ℕ) (rc : Fin n × Fin n) : + rc ∈ P.guards h ↔ P.GuardCell h rc := by + classical + simp [guards] + +/-- Explicit original-matrix conditions on a selected path. The frame validity +contains all required order comparisons and all 64-anchor signatures. -/ +structure Valid (P : Selection n) (A : BinaryMatrix n) (h : ℕ) : Prop where + root_plus : A (P.xp 0) (P.yp 0) = true + root_minus : A (P.xm 0) (P.ym 0) = false + dummy_col : ∀ i, i ≤ h → A (P.xp i) P.yd = true ∧ A (P.xm i) P.yd = true + dummy_row : ∀ i, i ≤ h → A P.xd (P.yp i) = true ∧ A P.xd (P.ym i) = true + leaf_row : P.xp h = P.xm h + leaf_col : P.yp h = P.ym h + vertical_plus : ∀ i, i < h → + (P.vPlus i).Valid A (P.xp (i + 1)) (P.xp i) P.yd (P.yp i) + vertical_minus : ∀ i, i < h → + (P.vMinus i).Valid A (P.xm i) (P.xm (i + 1)) P.yd (P.ym i) + horizontal_plus : ∀ i, i < h → + (P.wPlus i).Valid A (P.xp (i + 1)) P.xd (P.yp i) (P.yp (i + 1)) + horizontal_minus : ∀ i, i < h → + (P.wMinus i).Valid A (P.xm (i + 1)) P.xd (P.ym (i + 1)) (P.ym i) + +/-- If no guard cell was edited, every condition needed for path propagation +and exact anchor completion survives. -/ +theorem Valid.transfer {P : Selection n} {A B : BinaryMatrix n} {h : ℕ} + (hv : P.Valid A h) + (hag : ∀ rc ∈ P.guards h, A rc.1 rc.2 = B rc.1 rc.2) : + P.Valid B h := by + have hc : ∀ rc, P.CoreCell h rc → A rc.1 rc.2 = B rc.1 rc.2 := by + intro rc hrc + exact hag rc ((mem_guards P h rc).mpr (Or.inl hrc)) + have he : ∀ i, i < h → ∀ rc, P.EdgeCell i rc → A rc.1 rc.2 = B rc.1 rc.2 := by + intro i hi rc hrc + exact hag rc ((mem_guards P h rc).mpr (Or.inr ⟨i, hi, hrc⟩)) + refine ⟨?_, ?_, ?_, ?_, hv.leaf_row, hv.leaf_col, ?_, ?_, ?_, ?_⟩ + · exact (hc _ (Or.inl rfl)).symm.trans hv.root_plus + · exact (hc _ (Or.inr (Or.inl rfl))).symm.trans hv.root_minus + · intro i hi + constructor + · exact (hc _ (Or.inr (Or.inr ⟨i, hi, Or.inl rfl⟩))).symm.trans + (hv.dummy_col i hi).1 + · exact (hc _ (Or.inr (Or.inr ⟨i, hi, Or.inr (Or.inl rfl)⟩))).symm.trans + (hv.dummy_col i hi).2 + · intro i hi + constructor + · exact (hc _ (Or.inr (Or.inr ⟨i, hi, Or.inr (Or.inr (Or.inl rfl))⟩))).symm.trans + (hv.dummy_row i hi).1 + · exact (hc _ (Or.inr (Or.inr ⟨i, hi, Or.inr (Or.inr (Or.inr rfl))⟩))).symm.trans + (hv.dummy_row i hi).2 + · intro i hi + exact (hv.vertical_plus i hi).transfer (fun rc hrc => he i hi rc (Or.inl hrc)) + · intro i hi + exact (hv.vertical_minus i hi).transfer + (fun rc hrc => he i hi rc (Or.inr (Or.inl hrc))) + · intro i hi + exact (hv.horizontal_plus i hi).transfer + (fun rc hrc => he i hi rc (Or.inr (Or.inr (Or.inl hrc)))) + · intro i hi + exact (hv.horizontal_minus i hi).transfer + (fun rc hrc => he i hi rc (Or.inr (Or.inr (Or.inr hrc)))) + +/-- Every valid selected path gives a copy of the exact fixed H. -/ +theorem Valid.not_HFree {P : Selection n} {B : BinaryMatrix n} {h : ℕ} + (hv : P.Valid B h) : ¬ HFree fixedH B := by + obtain ⟨i, hi, hb⟩ := PathPropagation.exists_modeBody hv.root_plus hv.root_minus + hv.dummy_col hv.dummy_row hv.leaf_row hv.leaf_col + rcases hb with hb | hb | hb | hb + · exact (hv.vertical_plus i hi).not_HFree hb + · exact (hv.vertical_minus i hi).not_HFree hb + · exact (hv.horizontal_plus i hi).not_HFree hb + · exact (hv.horizontal_minus i hi).not_HFree hb + +/-- Arbitrary edits outside the finite guard set cannot destroy all copies. -/ +theorem not_HFree_of_agree {P : Selection n} {A B : BinaryMatrix n} {h : ℕ} + (hv : P.Valid A h) + (hag : ∀ rc ∈ P.guards h, A rc.1 rc.2 = B rc.1 rc.2) : + ¬ HFree fixedH B := + (hv.transfer hag).not_HFree + +/-- Every H-free repair must hit the guard set of each valid selected path. +This is a statement about all repairs, not just destroying original copies. -/ +theorem repair_hits_guards {P : Selection n} {A B : BinaryMatrix n} {h : ℕ} + (hv : P.Valid A h) (hfree : HFree fixedH B) : + ∃ rc ∈ P.guards h, A rc.1 rc.2 ≠ B rc.1 rc.2 := by + classical + by_contra hn + push Not at hn + exact not_HFree_of_agree hv hn hfree + +end Selection +end Problem348.GuardedPath + +end + +end OAI diff --git a/lean/OAI/Combinatorics/MatrixRemoval/Host.lean b/lean/OAI/Combinatorics/MatrixRemoval/Host.lean new file mode 100644 index 0000000000000000000000000000000000000000..b83fb35a62024683ca696071c7b8e6fbff5f3f2c --- /dev/null +++ b/lean/OAI/Combinatorics/MatrixRemoval/Host.lean @@ -0,0 +1,155 @@ +import OAI.Combinatorics.MatrixRemoval.Model + +namespace OAI + +/-! +The raw finite host; row and column orders are supplied separately. +The second coordinate in a variable class is uniform on `Fin (2^h)`; +its quotient by the block size is the node index. +-/ +noncomputable section +namespace Problem348.Construction + +abbrev VariablePosition (h : ℕ) := Fin (2 * h + 1) × Fin (2 ^ h) +abbrev AnchorPosition (h : ℕ) := Fin (6 * h) × Fin 64 × Fin (2 ^ h) +abbrev Position (h : ℕ) := AnchorPosition h ⊕ (VariablePosition h ⊕ Fin (2 ^ h)) +abbrev Mode (h : ℕ) := Fin (6 * h) + +def depth {h : ℕ} (x : VariablePosition h) : ℕ := x.1.val / 2 +def node {h : ℕ} (x : VariablePosition h) : ℕ := x.2.val / 2 ^ (h - depth x) +def plus {h : ℕ} (x : VariablePosition h) : Bool := decide (x.1.val % 2 = 0) +def level {h : ℕ} (t : Mode h) : ℕ := t.val / 6 + 1 +def kind {h : ℕ} (t : Mode h) : ℕ := t.val % 6 + +def AtLevel {h : ℕ} (i : ℕ) (s : Bool) (x : VariablePosition h) : Prop := + depth x = i ∧ (i = h ∨ plus x = s) + +def rowRole {h : ℕ} (t : Mode h) (j : Fin 2) (x : Position h) : Prop := + match x with + | Sum.inl _ => False + | Sum.inr (Sum.inr _) => 2 ≤ kind t ∧ j.val = 1 + | Sum.inr (Sum.inl v) => + if kind t = 0 then + AtLevel (if j.val = 0 then level t else level t - 1) true v + else if kind t = 1 then + AtLevel (if j.val = 0 then level t - 1 else level t) false v + else + j.val = 0 ∧ AtLevel (level t) (decide (kind t < 4)) v ∧ + node v % 2 = (kind t % 2) + +def colRole {h : ℕ} (t : Mode h) (j : Fin 2) (x : Position h) : Prop := + match x with + | Sum.inl _ => False + | Sum.inr (Sum.inr _) => kind t < 2 ∧ j.val = 0 + | Sum.inr (Sum.inl v) => + if kind t < 2 then + j.val = 1 ∧ AtLevel (level t - 1) (decide (kind t = 0)) v + else if kind t < 4 then + if j.val = 0 then AtLevel (level t - 1) true v + else AtLevel (level t) true v ∧ node v % 2 = kind t % 2 + else + if j.val = 0 then AtLevel (level t) false v ∧ node v % 2 = kind t % 2 + else AtLevel (level t - 1) false v + +instance {h : ℕ} (i : ℕ) (s : Bool) (v : VariablePosition h) : + Decidable (AtLevel i s v) := inferInstanceAs (Decidable (_ ∧ _)) +instance {h : ℕ} (t : Mode h) (j : Fin 2) (x : Position h) : + Decidable (rowRole t j x) := by unfold rowRole; split <;> infer_instance +instance {h : ℕ} (t : Mode h) (j : Fin 2) (x : Position h) : + Decidable (colRole t j x) := by unfold colRole; split <;> infer_instance + +def variableEntry {h : ℕ} (r c : VariablePosition h) : Bool := + if depth r = depth c then + if depth r = h then decide (node r ≤ node c) + else if plus r = plus c then + if plus r then decide (node r ≤ node c) else decide (node r < node c) + else false + else if depth r = depth c + 1 ∧ depth c < h ∧ + (depth r = h ∨ plus r = plus c) then + if plus c then decide (node r / 2 ≤ node c) else decide (node r / 2 < node c) + else false + +def host {h : ℕ} (r c : Position h) : Bool := + match r, c with + | Sum.inl (t, u, _), Sum.inl (t', v, _) => + if t = t' then Problem348.anchor64 u v else false + | Sum.inl (t, u, _), Sum.inr _ => + decide ((u.val = 0 ∧ colRole t 0 c) ∨ (u.val = 1 ∧ colRole t 1 c)) + | Sum.inr _, Sum.inl (t, v, _) => + decide ((v.val = 0 ∧ rowRole t 0 r) ∨ (v.val = 1 ∧ rowRole t 1 r)) + | Sum.inr (Sum.inl v), Sum.inr (Sum.inl w) => variableEntry v w + | Sum.inr _, Sum.inr _ => true + +theorem depth_le {h : ℕ} (x : VariablePosition h) : depth x ≤ h := by + have hx := x.1.isLt + unfold depth + omega + +theorem level_pos {h : ℕ} (t : Mode h) : 1 ≤ level t := by + unfold level + omega + +theorem level_le {h : ℕ} (t : Mode h) : level t ≤ h := by + have ht := t.isLt + unfold level + omega + +theorem kind_lt {h : ℕ} (t : Mode h) : kind t < 6 := by + exact Nat.mod_lt _ (by decide) + +theorem card_variablePosition (h : ℕ) : + Fintype.card (VariablePosition h) = (2 * h + 1) * 2 ^ h := by + simp [VariablePosition] + +theorem card_position (h : ℕ) : + Fintype.card (Position h) = (386 * h + 2) * 2 ^ h := by + simp only [Position, AnchorPosition, VariablePosition, Fintype.card_sum, + Fintype.card_prod, Fintype.card_fin] + ring + +@[simp] theorem host_anchor_same {h : ℕ} (t : Mode h) (u v : Fin 64) + (x y : Fin (2 ^ h)) : + host (Sum.inl (t, u, x)) (Sum.inl (t, v, y)) = anchor64 u v := by + simp [host] + +@[simp] theorem host_anchor_different {h : ℕ} (t t' : Mode h) (ht : t ≠ t') + (u v : Fin 64) (x y : Fin (2 ^ h)) : + host (Sum.inl (t, u, x)) (Sum.inl (t', v, y)) = false := by + simp [host, ht] + +@[simp] theorem host_variable_variable {h : ℕ} (v w : VariablePosition h) : + host (Sum.inr (Sum.inl v)) (Sum.inr (Sum.inl w)) = variableEntry v w := rfl + +@[simp] theorem host_dummy_variable {h : ℕ} (x : Fin (2 ^ h)) + (v : VariablePosition h) : + host (Sum.inr (Sum.inr x)) (Sum.inr (Sum.inl v)) = true := rfl + +@[simp] theorem host_variable_dummy {h : ℕ} (x : Fin (2 ^ h)) + (v : VariablePosition h) : + host (Sum.inr (Sum.inl v)) (Sum.inr (Sum.inr x)) = true := rfl + +theorem rowRole_disjoint {h : ℕ} (t : Mode h) (x : Position h) : + ¬ (rowRole t 0 x ∧ rowRole t 1 x) := by + have hp := level_pos t + have hk := kind_lt t + rcases x with a | (v | d) + · simp [rowRole] + · interval_cases e : kind t <;> + simp [rowRole, e, AtLevel] <;> omega + · simp [rowRole] + +theorem colRole_disjoint {h : ℕ} (t : Mode h) (x : Position h) : + ¬ (colRole t 0 x ∧ colRole t 1 x) := by + have hp := level_pos t + have hk := kind_lt t + rcases x with a | (v | d) + · simp [colRole] + · interval_cases e : kind t <;> + simp [colRole, e, AtLevel] <;> omega + · simp [colRole] + +end Problem348.Construction + +end + +end OAI diff --git a/lean/OAI/Combinatorics/MatrixRemoval/HostAnchorFrames.lean b/lean/OAI/Combinatorics/MatrixRemoval/HostAnchorFrames.lean new file mode 100644 index 0000000000000000000000000000000000000000..c007b9f009adeec51c74cb34de595f573d770a68 --- /dev/null +++ b/lean/OAI/Combinatorics/MatrixRemoval/HostAnchorFrames.lean @@ -0,0 +1,102 @@ +import OAI.Combinatorics.MatrixRemoval.Host +import OAI.Combinatorics.MatrixRemoval.AnchorFrames +import OAI.Combinatorics.MatrixRemoval.GuardedFrame + +namespace OAI + +/-! +Concrete selected-anchor frames for the canonical host. +The frame signatures follow from the actual host entry definition. +-/ + +noncomputable section +namespace Problem348.Construction + +/-- A true first row role gives the exact first unit signature. -/ +theorem host_row_role_zero {h : ℕ} (t : Mode h) (r : Position h) + (hr : rowRole t 0 r) (v : Fin 64) (y : Fin (2 ^ h)) : + host r (.inl (t,v,y)) = decide (v.val = 0) := by + have hn : ¬ rowRole t 1 r := fun h₁ => rowRole_disjoint t r ⟨hr,h₁⟩ + cases r with + | inl a => simp [rowRole] at hr + | inr r => simp [host, hr, hn] + +/-- A true second row role gives the exact second unit signature. -/ +theorem host_row_role_one {h : ℕ} (t : Mode h) (r : Position h) + (hr : rowRole t 1 r) (v : Fin 64) (y : Fin (2 ^ h)) : + host r (.inl (t,v,y)) = decide (v.val = 1) := by + have hn : ¬ rowRole t 0 r := fun h₀ => rowRole_disjoint t r ⟨h₀,hr⟩ + cases r with + | inl a => simp [rowRole] at hr + | inr r => simp [host, hr, hn] + +/-- A true first column role gives the exact first unit signature. -/ +theorem host_col_role_zero {h : ℕ} (t : Mode h) (c : Position h) + (hc : colRole t 0 c) (u : Fin 64) (x : Fin (2 ^ h)) : + host (.inl (t,u,x)) c = decide (u.val = 0) := by + have hn : ¬ colRole t 1 c := fun h₁ => colRole_disjoint t c ⟨hc,h₁⟩ + cases c with + | inl a => simp [colRole] at hc + | inr c => simp [host, hc, hn] + +/-- A true second column role gives the exact second unit signature. -/ +theorem host_col_role_one {h : ℕ} (t : Mode h) (c : Position h) + (hc : colRole t 1 c) (u : Fin 64) (x : Fin (2 ^ h)) : + host (.inl (t,u,x)) c = decide (u.val = 1) := by + have hn : ¬ colRole t 0 c := fun h₀ => colRole_disjoint t c ⟨h₀,hc⟩ + cases c with + | inl a => simp [colRole] at hc + | inr c => simp [host, hc, hn] + +namespace SelectedAnchor + +/-- Independent reindexings of the exact canonical raw host. -/ +def matrix {h n : ℕ} (er ec : Position h ≃ Fin n) : BinaryMatrix n := + fun r c => host (er.symm r) (ec.symm c) + +@[simp] theorem matrix_apply {h n : ℕ} (er ec : Position h ≃ Fin n) + (r c : Position h) : matrix er ec (er r) (ec c) = host r c := by + simp [matrix] + +/-- One selected representative from each anchor group of a fixed mode. -/ +def frame {h n : ℕ} (er ec : Position h ≃ Fin n) (t : Mode h) + (a b : Fin 64 → Fin (2 ^ h)) + (hr : StrictMono (fun u => er (.inl (t,u,a u)))) + (hc : StrictMono (fun v => ec (.inl (t,v,b v)))) : + GuardedPath.AnchorFrame n where + rows := ⟨fun u => er (.inl (t,u,a u)), hr⟩ + cols := ⟨fun v => ec (.inl (t,v,b v)), hc⟩ + +/-- The actual host roles and the row/column order comparisons give a valid +selected frame. No body entry is required or constrained. -/ +theorem frame_valid {h n : ℕ} (er ec : Position h ≃ Fin n) (t : Mode h) + (a b : Fin 64 → Fin (2 ^ h)) + (hr : StrictMono (fun u => er (.inl (t,u,a u)))) + (hc : StrictMono (fun v => ec (.inl (t,v,b v)))) + (r₀ r₁ c₀ c₁ : Position h) + (hr₀ : rowRole t 0 r₀) (hr₁ : rowRole t 1 r₁) + (hc₀ : colRole t 0 c₀) (hc₁ : colRole t 1 c₁) + (hbeforeR : ∀ u, er (.inl (t,u,a u)) < er r₀) + (hrows : er r₀ < er r₁) + (hbeforeC : ∀ v, ec (.inl (t,v,b v)) < ec c₀) + (hcols : ec c₀ < ec c₁) : + (frame er ec t a b hr hc).Valid (matrix er ec) + (er r₀) (er r₁) (ec c₀) (ec c₁) := by + refine ⟨hbeforeR, hrows, hbeforeC, hcols, ?_, ?_, ?_, ?_, ?_⟩ + · intro u v + exact (matrix_apply er ec _ _).trans (host_anchor_same t u v (a u) (b v)) + · intro v + exact (matrix_apply er ec _ _).trans (host_row_role_zero t r₀ hr₀ v (b v)) + · intro v + exact (matrix_apply er ec _ _).trans (host_row_role_one t r₁ hr₁ v (b v)) + · intro u + exact (matrix_apply er ec _ _).trans (host_col_role_zero t c₀ hc₀ u (a u)) + · intro u + exact (matrix_apply er ec _ _).trans (host_col_role_one t c₁ hc₁ u (a u)) + +end SelectedAnchor +end Problem348.Construction + +end + +end OAI diff --git a/lean/OAI/Combinatorics/MatrixRemoval/HostAnchorGroups.lean b/lean/OAI/Combinatorics/MatrixRemoval/HostAnchorGroups.lean new file mode 100644 index 0000000000000000000000000000000000000000..3202934f031eedb8d5e5c4474d2f2b51af2db8e2 --- /dev/null +++ b/lean/OAI/Combinatorics/MatrixRemoval/HostAnchorGroups.lean @@ -0,0 +1,101 @@ +import OAI.Combinatorics.MatrixRemoval.AnchorGroups +import OAI.Combinatorics.MatrixRemoval.AnchorProperties +import OAI.Combinatorics.MatrixRemoval.HostTwins + +namespace OAI + +/-! +# Group coordinates of a canonical host anchor copy + +One-mode anchor rigidity, the entries of `Construction.host`, and distinct +rows and columns of `anchor64` force exhaustion of the anchor groups. +The two axes use independent key functions, with no global order instance +on the raw carrier. +-/ + +universe uK uKR uKC + +namespace Problem348.Construction.AnchorGroups + +/-- The row groups of a one-mode anchor copy are exactly their pattern indices. +Only the within-mode comparison property of the chosen row order is needed. -/ +theorem row_representatives {h : ℕ} {K : Type uK} [LinearOrder K] + (key : Position h → K) (r c : Fin 64 → Position h) (t : Mode h) + (hr : StrictMono (fun i => key (r i))) + (hcopy : ∀ i j, host (r i) (c j) = anchor64 i j) + (hmode : ∀ i, ∃ u x, r i = Sum.inl (t, u, x)) + (horder : ∀ u v : Fin 64, ∀ x y : Fin (2 ^ h), + key (Sum.inl (t,u,x)) < key (Sum.inl (t,v,y)) → u ≤ v) : + ∃ x : Fin 64 → Fin (2 ^ h), ∀ i, r i = Sum.inl (t,i,x i) := by + classical + choose g x hx using hmode + have hmono : Monotone g := by + intro i j hij + rcases eq_or_lt_of_le hij with e | hij + · subst j + exact le_rfl + · apply horder (g i) (g j) (x i) (x j) + simpa only [hx i, hx j] using hr hij + have heq : ∀ i, g i = i := + Problem348.AnchorGroups.group_eq_index anchor64 host r c g + anchor64_rows_injective hcopy + (by + intro i j hij z + rw [hx i, hx j, ← hij] + exact host_anchor_row_twin t (g i) (x i) (x j) (c z)) hmono + refine ⟨x, fun i => ?_⟩ + simpa only [heq i] using hx i + +/-- The analogous conclusion for the independently ordered column axis. -/ +theorem column_representatives {h : ℕ} {K : Type uK} [LinearOrder K] + (key : Position h → K) (r c : Fin 64 → Position h) (t : Mode h) + (hc : StrictMono (fun j => key (c j))) + (hcopy : ∀ i j, host (r i) (c j) = anchor64 i j) + (hmode : ∀ j, ∃ v y, c j = Sum.inl (t, v, y)) + (horder : ∀ u v : Fin 64, ∀ x y : Fin (2 ^ h), + key (Sum.inl (t,u,x)) < key (Sum.inl (t,v,y)) → u ≤ v) : + ∃ y : Fin 64 → Fin (2 ^ h), ∀ j, c j = Sum.inl (t,j,y j) := by + classical + choose g y hy using hmode + have hmono : Monotone g := by + intro i j hij + rcases eq_or_lt_of_le hij with e | hij + · subst j + exact le_rfl + · apply horder (g i) (g j) (y i) (y j) + simpa only [hy i, hy j] using hc hij + have heq : ∀ j, g j = j := + Problem348.AnchorGroups.group_eq_index (fun j i => anchor64 i j) + (fun b a => host a b) c r g anchor64_columns_injective + (fun j i => hcopy i j) + (by + intro i j hij z + rw [hy i, hy j, ← hij] + exact host_anchor_column_twin t (g i) (y i) (y j) (r z)) hmono + refine ⟨y, fun j => ?_⟩ + simpa only [heq j] using hy j + +/-- Both axes of the canonical anchor copy use every group in its prescribed +order, with independent choices of the within-group offsets. -/ +theorem representatives {h : ℕ} {KR : Type uKR} {KC : Type uKC} + [LinearOrder KR] [LinearOrder KC] + (rowKey : Position h → KR) (colKey : Position h → KC) + (r c : Fin 64 → Position h) (t : Mode h) + (hr : StrictMono (fun i => rowKey (r i))) + (hc : StrictMono (fun j => colKey (c j))) + (hcopy : ∀ i j, host (r i) (c j) = anchor64 i j) + (hrowmode : ∀ i, ∃ u x, r i = Sum.inl (t,u,x)) + (hcolmode : ∀ j, ∃ v y, c j = Sum.inl (t,v,y)) + (hroworder : ∀ u v : Fin 64, ∀ x y : Fin (2 ^ h), + rowKey (Sum.inl (t,u,x)) < rowKey (Sum.inl (t,v,y)) → u ≤ v) + (hcolorder : ∀ u v : Fin 64, ∀ x y : Fin (2 ^ h), + colKey (Sum.inl (t,u,x)) < colKey (Sum.inl (t,v,y)) → u ≤ v) : + ∃ x y : Fin 64 → Fin (2 ^ h), + (∀ i, r i = Sum.inl (t,i,x i)) ∧ (∀ j, c j = Sum.inl (t,j,y j)) := by + obtain ⟨x, hx⟩ := row_representatives rowKey r c t hr hcopy hrowmode hroworder + obtain ⟨y, hy⟩ := column_representatives colKey r c t hc hcopy hcolmode hcolorder + exact ⟨x, y, hx, hy⟩ + +end Problem348.Construction.AnchorGroups + +end OAI diff --git a/lean/OAI/Combinatorics/MatrixRemoval/HostAnchorPinning.lean b/lean/OAI/Combinatorics/MatrixRemoval/HostAnchorPinning.lean new file mode 100644 index 0000000000000000000000000000000000000000..a47fd2daa2ec8f9218588fd8abdf92becb730d13 --- /dev/null +++ b/lean/OAI/Combinatorics/MatrixRemoval/HostAnchorPinning.lean @@ -0,0 +1,186 @@ +import OAI.Combinatorics.MatrixRemoval.HostAnchorRigidity +import OAI.Combinatorics.MatrixRemoval.AnchorRigidityFixed +import OAI.Combinatorics.MatrixRemoval.AnchorPatternFixed +import OAI.Combinatorics.MatrixRemoval.HostNonshattering + +namespace OAI + +/-! Assembly of the exact anchor-majority and concrete-host rigidity steps. -/ +namespace Problem348.HostAnchorRigidity + +open Construction AnchorRigidity + +/-- An exact anchor copy is automatically injective on the column axis. -/ +theorem selected_columns_injective {h : ℕ} (r c : Fin 64 → Position h) + (hcopy : ∀ i j, host (r i) (c j) = anchor64 i j) : Function.Injective c := by + intro j k hjk + apply anchor64_columns_injective + funext i + change anchor64 i j = anchor64 i k + rw [← hcopy i j, ← hcopy i k, hjk] + +/-- An exact anchor copy is automatically injective on the row axis. -/ +theorem selected_rows_injective {h : ℕ} (r c : Fin 64 → Position h) + (hcopy : ∀ i j, host (r i) (c j) = anchor64 i j) : Function.Injective r := by + intro i k hik + apply anchor64_rows_injective + funext j + rw [← hcopy i j, ← hcopy k j, hik] + +/-- Variable-column sparseness on a selected prefix. -/ +def ColumnSparse {h : ℕ} (r c : Fin 64 → Position h) : Prop := + ∀ j, modeLabel (c j) = none → ¬ Dummy (c j) → + (∀ i ∈ firstCore, ∃ t, modeLabel (r i) = some t) → + (firstCore.filter fun i => anchor64 i j = true).card ≤ 4 + +/-- Variable-row sparseness on a selected prefix. -/ +def RowSparse {h : ℕ} (r c : Fin 64 → Position h) : Prop := + ∀ i, modeLabel (r i) = none → ¬ Dummy (r i) → + (∀ j ∈ firstCore, ∃ t, modeLabel (c j) = some t) → + (firstCore.filter fun j => anchor64 i j = true).card ≤ 4 + +/-- Prefix anchoring plus actual variable sparseness pins all positions to one mode. -/ +theorem mode_constant_of_prefix {h : ℕ} (r c : Fin 64 → Position h) + (hcopy : ∀ i j, host (r i) (c j) = anchor64 i j) + (hprefix : (∀ i : Fin 64, i.val < 32 → ∃ t, modeLabel (r i) = some t) ∨ + (∀ j : Fin 64, j.val < 32 → ∃ t, modeLabel (c j) = some t)) + (hcs : ColumnSparse r c) (hrs : RowSparse r c) : + ∃ t : Mode h, (∀ i, modeLabel (r i) = some t) ∧ + (∀ j, modeLabel (c j) = some t) := by + apply anchor64_rigidity_of_prefix (modeLabel ∘ r) (modeLabel ∘ c) + (Dummy ∘ r) (Dummy ∘ c) hprefix hcs hrs + · intro i k hi hk + exact selected_dummy_rows_unique r c hcopy hi hk + · intro j k hj hk + exact selected_dummy_columns_unique r c hcopy hj hk + · exact selected_cross_mode r c hcopy + · exact selected_nonanchor_row_unit r c hcopy + · exact selected_nonanchor_column_unit r c hcopy + +/-- No five-column shattering and the anchor-before-nonanchor order give a +majority; prefix rigidity then yields one common mode. -/ +theorem mode_constant_of_no_shattering {h : ℕ} (r c : Fin 64 → Position h) + (hcopy : ∀ i j, host (r i) (c j) = anchor64 i j) + (row_initial : ∀ i j, i ≤ j → modeLabel (r j) ≠ none → modeLabel (r i) ≠ none) + (col_initial : ∀ i j, i ≤ j → modeLabel (c j) ≠ none → modeLabel (c i) ≠ none) + (hnoshatter : ∀ cs : Fin 5 → Position h, Function.Injective cs → + (∀ b, modeLabel (cs b) = none) → ∃ w : Fin 5 → Bool, + ∀ x, modeLabel x = none → ∃ b, host x (cs b) ≠ w b) + (hcs : ColumnSparse r c) (hrs : RowSparse r c) : + ∃ t : Mode h, (∀ i, modeLabel (r i) = some t) ∧ + (∀ j, modeLabel (c j) = some t) := by + classical + have hm := AnchorBridge.anchor64_anchor_majority host r c + (fun x => modeLabel x ≠ none) (fun x => modeLabel x ≠ none) + hcopy (selected_columns_injective r c hcopy) row_initial col_initial + (by + intro cs hcs hnone + obtain ⟨w, hw⟩ := hnoshatter cs hcs (fun b => not_not.mp (hnone b)) + exact ⟨w, fun x hx => hw x (not_not.mp hx)⟩) + have hm' : + 32 < (Finset.univ.filter fun i => (modeLabel (r i)).isSome).card ∨ + 32 < (Finset.univ.filter fun j => (modeLabel (c j)).isSome).card := by + simpa only [Option.isSome_iff_ne_none, Nat.lt_iff_add_one_le] using hm + have hp := prefix_alternative_of_majority (modeLabel ∘ r) (modeLabel ∘ c) + row_initial col_initial hm' + exact mode_constant_of_prefix r c hcopy hp hcs hrs + +/-- The within-mode group order enjoyed by an increasingly selected axis. -/ +def GroupsMonotone {h : ℕ} (r : Fin 64 → Position h) : Prop := + ∀ (i j : Fin 64), i ≤ j → ∀ (t : Mode h) (u v : Fin 64) + (x y : Fin (2 ^ h)), r i = Sum.inl (t, u, x) → + r j = Sum.inl (t, v, y) → u ≤ v + +/-- Once one common mode is known, group uniqueness and the actual group +order identify its representatives in the exact pattern order. -/ +theorem representatives_of_mode_constant {h : ℕ} (r c : Fin 64 → Position h) + (hcopy : ∀ i j, host (r i) (c j) = anchor64 i j) + (hrow : GroupsMonotone r) (hcol : GroupsMonotone c) + {t : Mode h} (hmr : ∀ i, modeLabel (r i) = some t) + (hmc : ∀ j, modeLabel (c j) = some t) : + ∃ a b : Fin 64 → Fin (2 ^ h), + (∀ i, r i = Sum.inl (t, i, a i)) ∧ + (∀ j, c j = Sum.inl (t, j, b j)) := by + classical + choose u a ha using fun i => exists_anchor_of_mode (hmr i) + choose v b hb using fun j => exists_anchor_of_mode (hmc j) + have hu : Monotone u := by + intro i j hij + exact hrow i j hij t (u i) (u j) (a i) (a j) (ha i) (ha j) + have hv : Monotone v := by + intro i j hij + exact hcol i j hij t (v i) (v j) (b i) (b j) (hb i) (hb j) + have hui : Function.Injective u := by + intro i j hij + apply selected_anchor_rows_unique r c hcopy (ha i) + simpa only [hij] using ha j + have hvi : Function.Injective v := by + intro i j hij + apply selected_anchor_columns_unique r c hcopy (hb i) + simpa only [hij] using hb j + have hu_id : ∀ i, u i = i := by + intro i + have hs := hu.strictMono_of_injective hui + exact le_antisymm (hs.le_id i) (hs.id_le i) + have hv_id : ∀ i, v i = i := by + intro i + have hs := hv.strictMono_of_injective hvi + exact le_antisymm (hs.le_id i) (hs.id_le i) + refine ⟨a, b, ?_, ?_⟩ + · intro i + simpa only [hu_id i] using ha i + · intro j + simpa only [hv_id j] using hb j + +/-- Full anchor representative conclusion assuming initial anchor segments, +nonshattering, variable sparseness, and within-mode group order. -/ +theorem representatives_of_no_shattering {h : ℕ} (r c : Fin 64 → Position h) + (hcopy : ∀ i j, host (r i) (c j) = anchor64 i j) + (row_initial : ∀ i j, i ≤ j → modeLabel (r j) ≠ none → modeLabel (r i) ≠ none) + (col_initial : ∀ i j, i ≤ j → modeLabel (c j) ≠ none → modeLabel (c i) ≠ none) + (hnoshatter : ∀ cs : Fin 5 → Position h, Function.Injective cs → + (∀ b, modeLabel (cs b) = none) → ∃ w : Fin 5 → Bool, + ∀ x, modeLabel x = none → ∃ b, host x (cs b) ≠ w b) + (hcs : ColumnSparse r c) (hrs : RowSparse r c) + (hrow : GroupsMonotone r) (hcol : GroupsMonotone c) : + ∃ (t : Mode h) (a b : Fin 64 → Fin (2 ^ h)), + (∀ i, r i = Sum.inl (t, i, a i)) ∧ + (∀ j, c j = Sum.inl (t, j, b j)) := by + obtain ⟨t, hmr, hmc⟩ := mode_constant_of_no_shattering r c hcopy + row_initial col_initial hnoshatter hcs hrs + obtain ⟨a, b, ha, hb⟩ := representatives_of_mode_constant r c hcopy hrow hcol hmr hmc + exact ⟨t, a, b, ha, hb⟩ + +/-- The concrete canonical host supplies the missing-word hypothesis, +without any ordering or injectivity condition on the five columns. -/ +theorem actual_nonshattering {h : ℕ} (cs : Fin 5 → Position h) + (hcs : ∀ b, modeLabel (cs b) = none) : + ∃ w : Fin 5 → Bool, ∀ x, modeLabel x = none → + ∃ b, host x (cs b) ≠ w b := by + classical + obtain ⟨w, hw⟩ := host_nonanchor_missing_word cs + (fun b => exists_nonanchor_of_mode_none (hcs b)) + refine ⟨w, ?_⟩ + intro x hx + have hne := hw x (exists_nonanchor_of_mode_none hx) + by_contra heq + push Not at heq + exact hne (funext heq) + +/-- Concrete-host anchor pinning assuming axis-order and sparse-core +conditions; nonshattering follows from the host entries. -/ +theorem representatives_of_sparse {h : ℕ} (r c : Fin 64 → Position h) + (hcopy : ∀ i j, host (r i) (c j) = anchor64 i j) + (row_initial : ∀ i j, i ≤ j → modeLabel (r j) ≠ none → modeLabel (r i) ≠ none) + (col_initial : ∀ i j, i ≤ j → modeLabel (c j) ≠ none → modeLabel (c i) ≠ none) + (hcs : ColumnSparse r c) (hrs : RowSparse r c) + (hrow : GroupsMonotone r) (hcol : GroupsMonotone c) : + ∃ (t : Mode h) (a b : Fin 64 → Fin (2 ^ h)), + (∀ i, r i = Sum.inl (t, i, a i)) ∧ + (∀ j, c j = Sum.inl (t, j, b j)) := by + exact representatives_of_no_shattering r c hcopy row_initial col_initial + (fun cs _ hin => actual_nonshattering cs hin) hcs hrs hrow hcol + +end Problem348.HostAnchorRigidity + +end OAI diff --git a/lean/OAI/Combinatorics/MatrixRemoval/HostAnchorRigidity.lean b/lean/OAI/Combinatorics/MatrixRemoval/HostAnchorRigidity.lean new file mode 100644 index 0000000000000000000000000000000000000000..198b7ceb676f0a49be9502ea38dbe9443b42030f --- /dev/null +++ b/lean/OAI/Combinatorics/MatrixRemoval/HostAnchorRigidity.lean @@ -0,0 +1,292 @@ +import OAI.Combinatorics.MatrixRemoval.Host +import OAI.Combinatorics.MatrixRemoval.AnchorRigidityFixed +import OAI.Combinatorics.MatrixRemoval.HostTwins +import OAI.Combinatorics.MatrixRemoval.AnchorProperties +import OAI.Combinatorics.MatrixRemoval.AnchorRigidity + +namespace OAI + + +/-! Concrete cross-mode and single-mode incidence facts for the canonical host. +These discharge the corresponding premises of abstract anchor rigidity once +an anchor copy has distinct selected anchor groups. -/ +universe uI uJ + +namespace Problem348.AnchorRigidity + +open Construction + +/-- The mode label of a raw anchor position, and `none` off the anchors. -/ +def positionMode {h : ℕ} : Position h → Option (Mode h) + | Sum.inl (t, _, _) => some t + | Sum.inr _ => none + +/-- Group label, ignoring the within-group coordinate. -/ +def positionGroup {h : ℕ} : Position h → Option (Mode h × Fin 64) + | Sum.inl (t, u, _) => some (t, u) + | Sum.inr _ => none + +/-- A selected family uses each anchor group at most once. -/ +def DistinctAnchorGroups {h : ℕ} {I : Type uI} (r : I → Position h) : Prop := + ∀ i j g, positionGroup (r i) = some g → positionGroup (r j) = some g → i = j + +/-- A true entry between anchors forces their modes to agree. -/ +theorem host_cross_mode {h : ℕ} (r c : Position h) (t u : Mode h) + (hr : positionMode r = some t) (hc : positionMode c = some u) + (hb : host r c = true) : t = u := by + rcases r with ⟨tr, ur, xr⟩ | r + · rcases c with ⟨tc, vc, yc⟩ | c + · simp only [positionMode, Option.some.injEq] at hr hc + subst tr + subst tc + by_contra hne + simp [host, hne] at hb + · simp [positionMode] at hc + · simp [positionMode] at hr + +/-- On the columns of one mode, a nonanchor row has ones in only one group. -/ +theorem host_nonanchor_row_one_group {h : ℕ} + (r : VariablePosition h ⊕ Fin (2 ^ h)) (t : Mode h) + (u v : Fin 64) (x y : Fin (2 ^ h)) + (hu : host (Sum.inr r) (Sum.inl (t, u, x)) = true) + (hv : host (Sum.inr r) (Sum.inl (t, v, y)) = true) : u = v := by + change decide ((u.val = 0 ∧ rowRole t 0 (Sum.inr r)) ∨ + (u.val = 1 ∧ rowRole t 1 (Sum.inr r))) = true at hu + change decide ((v.val = 0 ∧ rowRole t 0 (Sum.inr r)) ∨ + (v.val = 1 ∧ rowRole t 1 (Sum.inr r))) = true at hv + have hu' := of_decide_eq_true hu + have hv' := of_decide_eq_true hv + rcases hu' with ⟨hu0, hr0⟩ | ⟨hu1, hr1⟩ + · rcases hv' with ⟨hv0, _⟩ | ⟨_, hr1⟩ + · exact Fin.ext (hu0.trans hv0.symm) + · exact False.elim (rowRole_disjoint t (Sum.inr r) ⟨hr0, hr1⟩) + · rcases hv' with ⟨_, hr0⟩ | ⟨hv1, _⟩ + · exact False.elim (rowRole_disjoint t (Sum.inr r) ⟨hr0, hr1⟩) + · exact Fin.ext (hu1.trans hv1.symm) + +/-- On the rows of one mode, a nonanchor column has ones in only one group. -/ +theorem host_nonanchor_col_one_group {h : ℕ} + (c : VariablePosition h ⊕ Fin (2 ^ h)) (t : Mode h) + (u v : Fin 64) (x y : Fin (2 ^ h)) + (hu : host (Sum.inl (t, u, x)) (Sum.inr c) = true) + (hv : host (Sum.inl (t, v, y)) (Sum.inr c) = true) : u = v := by + change decide ((u.val = 0 ∧ colRole t 0 (Sum.inr c)) ∨ + (u.val = 1 ∧ colRole t 1 (Sum.inr c))) = true at hu + change decide ((v.val = 0 ∧ colRole t 0 (Sum.inr c)) ∨ + (v.val = 1 ∧ colRole t 1 (Sum.inr c))) = true at hv + have hu' := of_decide_eq_true hu + have hv' := of_decide_eq_true hv + rcases hu' with ⟨hu0, hc0⟩ | ⟨hu1, hc1⟩ + · rcases hv' with ⟨hv0, _⟩ | ⟨_, hc1⟩ + · exact Fin.ext (hu0.trans hv0.symm) + · exact False.elim (colRole_disjoint t (Sum.inr c) ⟨hc0, hc1⟩) + · rcases hv' with ⟨_, hc0⟩ | ⟨hv1, _⟩ + · exact False.elim (colRole_disjoint t (Sum.inr c) ⟨hc0, hc1⟩) + · exact Fin.ext (hu1.trans hv1.symm) + +/-- Unit-incidence premise for a selected family of columns with no repeated group. -/ +theorem host_nonanchor_row_unit {h : ℕ} {J : Type uJ} + (r : Position h) (c : J → Position h) (hcgroup : DistinctAnchorGroups c) + (hr : positionMode r = none) (j k : J) (t : Mode h) + (hj : positionMode (c j) = some t) (hk : positionMode (c k) = some t) + (hbj : host r (c j) = true) (hbk : host r (c k) = true) : j = k := by + rcases r with a | r + · simp [positionMode] at hr + rcases hjc : c j with ⟨tj, uj, xj⟩ | cj + · rcases hkc : c k with ⟨tk, uk, xk⟩ | ck + · simp only [hjc, hkc, positionMode, Option.some.injEq] at hj hk + subst tj + subst tk + rw [hjc] at hbj + rw [hkc] at hbk + have hu := host_nonanchor_row_one_group r t uj uk xj xk hbj hbk + apply hcgroup j k (t, uj) + · simp [hjc, positionGroup] + · simp [hkc, positionGroup, hu] + · simp [hkc, positionMode] at hk + · simp [hjc, positionMode] at hj + +/-- Unit-incidence premise for a selected family of rows with no repeated group. -/ +theorem host_nonanchor_col_unit {h : ℕ} {I : Type uI} + (r : I → Position h) (c : Position h) (hrgroup : DistinctAnchorGroups r) + (hc : positionMode c = none) (i k : I) (t : Mode h) + (hi : positionMode (r i) = some t) (hk : positionMode (r k) = some t) + (hbi : host (r i) c = true) (hbk : host (r k) c = true) : i = k := by + rcases c with a | c + · simp [positionMode] at hc + rcases hir : r i with ⟨ti, ui, xi⟩ | ri + · rcases hkr : r k with ⟨tk, uk, xk⟩ | rk + · simp only [hir, hkr, positionMode, Option.some.injEq] at hi hk + subst ti + subst tk + rw [hir] at hbi + rw [hkr] at hbk + have hu := host_nonanchor_col_one_group c t ui uk xi xk hbi hbk + apply hrgroup i k (t, ui) + · simp [hir, positionGroup] + · simp [hkr, positionGroup, hu] + · simp [hkr, positionMode] at hk + · simp [hir, positionMode] at hi + +end Problem348.AnchorRigidity + + +/-! +# Concrete canonical-host specialization of anchor rigidity + +For `Construction.host`, a dense core forces one common anchor mode. +The twin, signature, density, and cross-mode properties follow from the +canonical entry table. +-/ + +namespace Problem348.HostAnchorRigidity + +open Construction + +/-- The mode label of an anchor, and `none` for a non-anchor. -/ +def modeLabel {h : ℕ} : Position h → Option (Mode h) + | Sum.inl (t, _, _) => some t + | Sum.inr _ => none + +/-- The actual dummy positions on either raw axis. -/ +def Dummy {h : ℕ} (x : Position h) : Prop := + ∃ z, x = Sum.inr (Sum.inr z) + +theorem exists_anchor_of_mode {h : ℕ} {x : Position h} {t : Mode h} + (hx : modeLabel x = some t) : + ∃ u z, x = Sum.inl (t, u, z) := by + rcases x with ⟨t', u, z⟩ | a + · simp only [modeLabel, Option.some.injEq] at hx + subst t' + exact ⟨u, z, rfl⟩ + · simp [modeLabel] at hx + +theorem exists_nonanchor_of_mode_none {h : ℕ} {x : Position h} + (hx : modeLabel x = none) : + ∃ a, x = Sum.inr a := by + rcases x with a | a + · simp [modeLabel] at hx + · exact ⟨a, rfl⟩ + +theorem exists_dummy_of_dummy {h : ℕ} {x : Position h} (hx : Dummy x) : + ∃ z, x = Sum.inr (Sum.inr z) := hx + +/-- Distinct selected anchor rows cannot have the same mode and group. -/ +theorem selected_anchor_rows_unique {h : ℕ} + (r c : Fin 64 → Position h) + (hcopy : ∀ i j, host (r i) (c j) = anchor64 i j) + {i k : Fin 64} {t : Mode h} {u : Fin 64} {x y : Fin (2 ^ h)} + (hi : r i = Sum.inl (t, u, x)) + (hk : r k = Sum.inl (t, u, y)) : i = k := by + apply anchor64_rows_injective + funext j + rw [← hcopy i j, ← hcopy k j, hi, hk] + exact host_anchor_row_twin t u x y (c j) + +/-- Distinct selected anchor columns cannot have the same mode and group. -/ +theorem selected_anchor_columns_unique {h : ℕ} + (r c : Fin 64 → Position h) + (hcopy : ∀ i j, host (r i) (c j) = anchor64 i j) + {j k : Fin 64} {t : Mode h} {v : Fin 64} {x y : Fin (2 ^ h)} + (hj : c j = Sum.inl (t, v, x)) + (hk : c k = Sum.inl (t, v, y)) : j = k := by + apply anchor64_columns_injective + funext i + change anchor64 i j = anchor64 i k + rw [← hcopy i j, ← hcopy i k, hj, hk] + exact host_anchor_column_twin t v x y (r i) + +/-- At most one selected row can be dummy, because all dummy rows are twins. -/ +theorem selected_dummy_rows_unique {h : ℕ} + (r c : Fin 64 → Position h) + (hcopy : ∀ i j, host (r i) (c j) = anchor64 i j) + {i k : Fin 64} (hi : Dummy (r i)) (hk : Dummy (r k)) : i = k := by + obtain ⟨x, hx⟩ := exists_dummy_of_dummy hi + obtain ⟨y, hy⟩ := exists_dummy_of_dummy hk + apply anchor64_rows_injective + funext j + rw [← hcopy i j, ← hcopy k j, hx, hy] + exact host_dummy_row_twin x y (c j) + +/-- At most one selected column can be dummy. -/ +theorem selected_dummy_columns_unique {h : ℕ} + (r c : Fin 64 → Position h) + (hcopy : ∀ i j, host (r i) (c j) = anchor64 i j) + {j k : Fin 64} (hj : Dummy (c j)) (hk : Dummy (c k)) : j = k := by + obtain ⟨x, hx⟩ := exists_dummy_of_dummy hj + obtain ⟨y, hy⟩ := exists_dummy_of_dummy hk + apply anchor64_columns_injective + funext i + change anchor64 i j = anchor64 i k + rw [← hcopy i j, ← hcopy i k, hx, hy] + exact host_dummy_column_twin x y (r i) + +/-- A one between two anchors forces their modes to coincide. -/ +theorem selected_cross_mode {h : ℕ} (r c : Fin 64 → Position h) + (hcopy : ∀ i j, host (r i) (c j) = anchor64 i j) + (i j : Fin 64) (t u : Mode h) + (hi : modeLabel (r i) = some t) (hj : modeLabel (c j) = some u) + (hij : anchor64 i j = true) : t = u := by + obtain ⟨v, x, hx⟩ := exists_anchor_of_mode hi + obtain ⟨w, y, hy⟩ := exists_anchor_of_mode hj + rw [← hcopy i j, hx, hy] at hij + by_contra hne + simp [host, hne] at hij + +/-- On the selected anchors of a fixed mode a non-anchor row has at most one one. -/ +theorem selected_nonanchor_row_unit {h : ℕ} (r c : Fin 64 → Position h) + (hcopy : ∀ i j, host (r i) (c j) = anchor64 i j) + (i : Fin 64) (hi : modeLabel (r i) = none) (j k : Fin 64) (t : Mode h) + (hj : modeLabel (c j) = some t) (hk : modeLabel (c k) = some t) + (hij : anchor64 i j = true) (hik : anchor64 i k = true) : j = k := by + obtain ⟨a, hx⟩ := exists_nonanchor_of_mode_none hi + obtain ⟨v, y, hy⟩ := exists_anchor_of_mode hj + obtain ⟨w, z, hz⟩ := exists_anchor_of_mode hk + rw [← hcopy i j, hx, hy] at hij + rw [← hcopy i k, hx, hz] at hik + have hvw : v = w := nonanchor_row_one_group_unique a t v w y z hij hik + subst w + exact selected_anchor_columns_unique r c hcopy hy hz + +/-- On the selected anchors of a fixed mode a non-anchor column has at most one one. -/ +theorem selected_nonanchor_column_unit {h : ℕ} (r c : Fin 64 → Position h) + (hcopy : ∀ i j, host (r i) (c j) = anchor64 i j) + (j : Fin 64) (hj : modeLabel (c j) = none) (i k : Fin 64) (t : Mode h) + (hi : modeLabel (r i) = some t) (hk : modeLabel (r k) = some t) + (hij : anchor64 i j = true) (hkj : anchor64 k j = true) : i = k := by + obtain ⟨a, hx⟩ := exists_nonanchor_of_mode_none hj + obtain ⟨u, y, hy⟩ := exists_anchor_of_mode hi + obtain ⟨v, z, hz⟩ := exists_anchor_of_mode hk + rw [← hcopy i j, hy, hx] at hij + rw [← hcopy k j, hz, hx] at hkj + have huv : u = v := nonanchor_column_one_group_unique a t u v y z hij hkj + subst v + exact selected_anchor_rows_unique r c hcopy hy hz + +/-- Concrete host rigidity assuming a dense core, with twin, signature, +density, and cross-mode properties following from the host entries. -/ +theorem mode_constant_of_dense_core {h : ℕ} (r c : Fin 64 → Position h) + (hcopy : ∀ i j, host (r i) (c j) = anchor64 i j) + (hcore : + AnchorRigidity.DenseAnchorCore anchor64 (modeLabel ∘ r) (modeLabel ∘ c) (Dummy ∘ c) ∨ + AnchorRigidity.DenseAnchorCore (fun j i => anchor64 i j) + (modeLabel ∘ c) (modeLabel ∘ r) (Dummy ∘ r)) : + ∃ t : Mode h, (∀ i, modeLabel (r i) = some t) ∧ + (∀ j, modeLabel (c j) = some t) := by + apply AnchorRigidity.rigidity anchor64 (modeLabel ∘ r) (modeLabel ∘ c) + (Dummy ∘ r) (Dummy ∘ c) hcore + · intro i k hi hk + exact selected_dummy_rows_unique r c hcopy hi hk + · intro j k hj hk + exact selected_dummy_columns_unique r c hcopy hj hk + · exact selected_cross_mode r c hcopy + · exact selected_nonanchor_row_unit r c hcopy + · exact selected_nonanchor_column_unit r c hcopy + · intro i + exact (by decide : 2 ≤ 58).trans (anchor64_row_ones i) + · intro j + exact (by decide : 2 ≤ 48).trans (anchor64_column_ones j) + +end Problem348.HostAnchorRigidity + +end OAI diff --git a/lean/OAI/Combinatorics/MatrixRemoval/HostBodyModes.lean b/lean/OAI/Combinatorics/MatrixRemoval/HostBodyModes.lean new file mode 100644 index 0000000000000000000000000000000000000000..18c0108cc848c1235ce7ae33da91326dd9fcc82a --- /dev/null +++ b/lean/OAI/Combinatorics/MatrixRemoval/HostBodyModes.lean @@ -0,0 +1,114 @@ +import OAI.Combinatorics.MatrixRemoval.CanonicalHorizontal +import OAI.Combinatorics.MatrixRemoval.HostVerticalLocalization + +namespace OAI + +/-! +# Exhaustive localization of bodies in canonical host modes + +All entry and role hypotheses refer to the actual canonical host. The numerical +order premise is exactly the four parent comparisons supplied by the two tree +orders. +-/ +namespace Problem348.Construction +open ModeLocalization + +/-- The necessary parent comparison for an ordered body in each of the six modes. -/ +def BodyNodeOrder {h : ℕ} (t : Mode h) (r₀ r₁ c₀ c₁ : Position h) : Prop := + if kind t = 0 then positionNode r₀ / 2 ≤ positionNode r₁ + else if kind t = 1 then positionNode r₀ ≤ positionNode r₁ / 2 + else if kind t < 4 then positionNode c₀ ≤ positionNode c₁ / 2 + else positionNode c₀ / 2 ≤ positionNode c₁ + +theorem rowRole_first_variable {h : ℕ} {t : Mode h} {x : Position h} + (hx : rowRole t 0 x) : ∃ v : VariablePosition h, x = Sum.inr (Sum.inl v) := by + rcases x with a | (v | d) + · simp [rowRole] at hx + · exact ⟨v, rfl⟩ + · simp [rowRole] at hx + +theorem colRole_horizontal_variable {h : ℕ} {t : Mode h} {j : Fin 2} + {x : Position h} (hk : 2 ≤ kind t) (hx : colRole t j x) : + ∃ v : VariablePosition h, x = Sum.inr (Sum.inl v) := by + rcases x with a | (v | d) + · simp [colRole] at hx + · exact ⟨v, rfl⟩ + · simp [colRole] at hx + omega + +/-- The horizontal plus roles cannot realize the body's top row. -/ +theorem host_horizontal_plus_not_body {h : ℕ} {t : Mode h} + (hklo : 2 ≤ kind t) (hkhi : kind t < 4) {r₀ r₁ c₀ c₁ : Position h} + (hr₀ : rowRole t 0 r₀) (hc₀ : colRole t 0 c₀) (hc₁ : colRole t 1 c₁) + (horder : positionNode c₀ ≤ positionNode c₁ / 2) : + ¬ IsP (host r₀ c₀) (host r₀ c₁) (host r₁ c₀) (host r₁ c₁) := by + obtain ⟨r, rfl⟩ := rowRole_first_variable hr₀ + obtain ⟨c, rfl⟩ := colRole_horizontal_variable hklo hc₀ + obtain ⟨d, rfl⟩ := colRole_horizontal_variable hklo hc₁ + have hk0 : kind t ≠ 0 := by omega + have hk1 : kind t ≠ 1 := by omega + have hk2 : ¬ kind t < 2 := by omega + have hr : AtLevel (level t) true r ∧ node r % 2 = kind t % 2 := by + simpa [rowRole, hk0, hk1, hkhi] using hr₀ + have hc : AtLevel (level t - 1) true c := by + simpa [colRole, hk2, hkhi] using hc₀ + have hd : AtLevel (level t) true d ∧ node d % 2 = kind t % 2 := by + simpa [colRole, hk2, hkhi] using hc₁ + have hl : level t - 1 + 1 = level t := by have := level_pos t; omega + intro hb + exact horizontal_plus_entries_impossible (hl ▸ hr.1) hc (hl ▸ hd.1) + horder (hr.2.trans hd.2.symm) hb.1 hb.2.1 + +/-- The horizontal minus roles force the body's top-left entry onto a shared leaf. -/ +theorem host_horizontal_minus_leaf_diagonal {h : ℕ} {t : Mode h} + (hklo : 4 ≤ kind t) {r₀ r₁ c₀ c₁ : Position h} + (hr₀ : rowRole t 0 r₀) (hc₀ : colRole t 0 c₀) (hc₁ : colRole t 1 c₁) + (horder : positionNode c₀ / 2 ≤ positionNode c₁) + (hb : IsP (host r₀ c₀) (host r₀ c₁) (host r₁ c₀) (host r₁ c₁)) : + ∃ z : Fin (2 ^ h), + r₀ = Sum.inr (Sum.inl (Fin.last (2 * h), z)) ∧ + c₀ = Sum.inr (Sum.inl (Fin.last (2 * h), z)) := by + obtain ⟨r, rfl⟩ := rowRole_first_variable hr₀ + obtain ⟨c, rfl⟩ := colRole_horizontal_variable (by omega) hc₀ + obtain ⟨d, rfl⟩ := colRole_horizontal_variable (by omega) hc₁ + have hk0 : kind t ≠ 0 := by omega + have hk1 : kind t ≠ 1 := by omega + have hk2 : ¬ kind t < 2 := by omega + have hk4 : ¬ kind t < 4 := by omega + have hr : AtLevel (level t) false r ∧ node r % 2 = kind t % 2 := by + simpa [rowRole, hk0, hk1, hk4] using hr₀ + have hc : AtLevel (level t) false c ∧ node c % 2 = kind t % 2 := by + simpa [colRole, hk2, hk4] using hc₀ + have hd : AtLevel (level t - 1) false d := by + simpa [colRole, hk2, hk4] using hc₁ + have hl : level t - 1 + 1 = level t := by have := level_pos t; omega + obtain ⟨_, z, hz, hcz⟩ := horizontal_minus_entries_localize + (hl ▸ hr.1) (hl ▸ hc.1) hd horder (hr.2.trans hc.2.symm) hb.1 hb.2.1 + exact ⟨z, congrArg (fun v => Sum.inr (Sum.inl v)) hz, + congrArg (fun v => Sum.inr (Sum.inl v)) hcz⟩ + +/-- Under `BodyNodeOrder`, every ordered body in any canonical mode has its +top-left cell on the shared leaf diagonal. -/ +theorem host_body_leaf_diagonal {h : ℕ} {t : Mode h} {r₀ r₁ c₀ c₁ : Position h} + (hr₀ : rowRole t 0 r₀) (hr₁ : rowRole t 1 r₁) + (hc₀ : colRole t 0 c₀) (hc₁ : colRole t 1 c₁) + (horder : BodyNodeOrder t r₀ r₁ c₀ c₁) + (hb : IsP (host r₀ c₀) (host r₀ c₁) (host r₁ c₀) (host r₁ c₁)) : + ∃ z : Fin (2 ^ h), + r₀ = Sum.inr (Sum.inl (Fin.last (2 * h), z)) ∧ + c₀ = Sum.inr (Sum.inl (Fin.last (2 * h), z)) := by + by_cases hk0 : kind t = 0 + · exact False.elim (host_vertical_plus_not_body hk0 hr₀ hr₁ hc₀ hc₁ + (by simpa [BodyNodeOrder, hk0] using horder) hb) + by_cases hk1 : kind t = 1 + · exact False.elim (host_vertical_minus_not_body hk1 hr₀ hr₁ hc₀ hc₁ + (by simpa [BodyNodeOrder, hk0, hk1] using horder) hb) + by_cases hk4 : kind t < 4 + · exact False.elim (host_horizontal_plus_not_body (by omega) hk4 hr₀ hc₀ hc₁ + (by simpa [BodyNodeOrder, hk0, hk1, hk4] using horder) hb) + · exact host_horizontal_minus_leaf_diagonal (by omega) hr₀ hc₀ hc₁ + (by simpa [BodyNodeOrder, hk0, hk1, hk4] using horder) hb + +end Problem348.Construction + +end OAI diff --git a/lean/OAI/Combinatorics/MatrixRemoval/HostBodyOrder.lean b/lean/OAI/Combinatorics/MatrixRemoval/HostBodyOrder.lean new file mode 100644 index 0000000000000000000000000000000000000000..d0ed6d156f34104e6eac3c9fdc716b85fd1c5343 --- /dev/null +++ b/lean/OAI/Combinatorics/MatrixRemoval/HostBodyOrder.lean @@ -0,0 +1,143 @@ +import OAI.Combinatorics.MatrixRemoval.HostBodyModes +import OAI.Combinatorics.MatrixRemoval.HostTreeOrder + +namespace OAI + +/-! +# From increasing body positions to the four node-order inequalities + +These lemmas use the actual host roles and tree keys. Each independent +coordinate map reflects the corresponding tree-key order on variable +positions; no mode-specific ordering is assumed. +-/ + +universe uAlpha uR uC + +namespace Problem348.Construction + +theorem vertical_plus_node_order {h : ℕ} {α : Type uAlpha} [Preorder α] + (rowIndex : Position h → α) + (hkey : ∀ v w : VariablePosition h, + rowIndex (Sum.inr (Sum.inl v)) < rowIndex (Sum.inr (Sum.inl w)) → + TreePositions.rowKey h v < TreePositions.rowKey h w) + {t : Mode h} (hk : kind t = 0) {r₀ r₁ : Position h} + (hr₀ : rowRole t 0 r₀) (hr₁ : rowRole t 1 r₁) + (hrow : rowIndex r₀ < rowIndex r₁) : + positionNode r₀ / 2 ≤ positionNode r₁ := by + have hkt : kind t < 2 := by omega + obtain ⟨x, rfl⟩ := rowRole_vertical_variable hkt hr₀ + obtain ⟨y, rfl⟩ := rowRole_vertical_variable hkt hr₁ + have hx : AtLevel (level t) true x := by simpa [rowRole, hk] using hr₀ + have hy : AtLevel (level t - 1) true y := by simpa [rowRole, hk] using hr₁ + have hl : level t - 1 + 1 = level t := by have := level_pos t; omega + exact (row_plus_lt_iff (hl ▸ hx) hy).mp (hkey x y hrow) + +theorem vertical_minus_node_order {h : ℕ} {α : Type uAlpha} [Preorder α] + (rowIndex : Position h → α) + (hkey : ∀ v w : VariablePosition h, + rowIndex (Sum.inr (Sum.inl v)) < rowIndex (Sum.inr (Sum.inl w)) → + TreePositions.rowKey h v < TreePositions.rowKey h w) + {t : Mode h} (hk : kind t = 1) {r₀ r₁ : Position h} + (hr₀ : rowRole t 0 r₀) (hr₁ : rowRole t 1 r₁) + (hrow : rowIndex r₀ < rowIndex r₁) : + positionNode r₀ ≤ positionNode r₁ / 2 := by + have hkt : kind t < 2 := by omega + obtain ⟨x, rfl⟩ := rowRole_vertical_variable hkt hr₀ + obtain ⟨y, rfl⟩ := rowRole_vertical_variable hkt hr₁ + have hx : AtLevel (level t - 1) false x := by simpa [rowRole, hk] using hr₀ + have hy : AtLevel (level t) false y := by simpa [rowRole, hk] using hr₁ + have hl : level t - 1 + 1 = level t := by have := level_pos t; omega + exact (row_minus_lt_iff (hl ▸ hy) hx).mp (hkey x y hrow) + +theorem horizontal_plus_node_order {h : ℕ} {α : Type uAlpha} [Preorder α] + (colIndex : Position h → α) + (hkey : ∀ v w : VariablePosition h, + colIndex (Sum.inr (Sum.inl v)) < colIndex (Sum.inr (Sum.inl w)) → + TreePositions.columnKey h v < TreePositions.columnKey h w) + {t : Mode h} (hklo : 2 ≤ kind t) (hkhi : kind t < 4) + {c₀ c₁ : Position h} (hc₀ : colRole t 0 c₀) (hc₁ : colRole t 1 c₁) + (hcol : colIndex c₀ < colIndex c₁) : + positionNode c₀ ≤ positionNode c₁ / 2 := by + obtain ⟨x, rfl⟩ := colRole_horizontal_variable hklo hc₀ + obtain ⟨y, rfl⟩ := colRole_horizontal_variable hklo hc₁ + have hkn : ¬ kind t < 2 := by omega + have hx : AtLevel (level t - 1) true x := by + simpa [colRole, hkn, hkhi] using hc₀ + have hy : AtLevel (level t) true y := by + have hy' : AtLevel (level t) true y ∧ node y % 2 = kind t % 2 := by + simpa [colRole, hkn, hkhi] using hc₁ + exact hy'.1 + have hl : level t - 1 + 1 = level t := by have := level_pos t; omega + exact (column_plus_lt_iff (hl ▸ hy) hx).mp (hkey x y hcol) + +theorem horizontal_minus_node_order {h : ℕ} {α : Type uAlpha} [Preorder α] + (colIndex : Position h → α) + (hkey : ∀ v w : VariablePosition h, + colIndex (Sum.inr (Sum.inl v)) < colIndex (Sum.inr (Sum.inl w)) → + TreePositions.columnKey h v < TreePositions.columnKey h w) + {t : Mode h} (hk : 4 ≤ kind t) + {c₀ c₁ : Position h} (hc₀ : colRole t 0 c₀) (hc₁ : colRole t 1 c₁) + (hcol : colIndex c₀ < colIndex c₁) : + positionNode c₀ / 2 ≤ positionNode c₁ := by + have hklo : 2 ≤ kind t := by omega + obtain ⟨x, rfl⟩ := colRole_horizontal_variable hklo hc₀ + obtain ⟨y, rfl⟩ := colRole_horizontal_variable hklo hc₁ + have hkn : ¬ kind t < 2 := by omega + have hkhi : ¬ kind t < 4 := by omega + have hx : AtLevel (level t) false x := by + have hx' : AtLevel (level t) false x ∧ node x % 2 = kind t % 2 := by + simpa [colRole, hkn, hkhi] using hc₀ + exact hx'.1 + have hy : AtLevel (level t - 1) false y := by + simpa [colRole, hkn, hkhi] using hc₁ + have hl : level t - 1 + 1 = level t := by have := level_pos t; omega + exact (column_minus_lt_iff (hl ▸ hx) hy).mp (hkey x y hcol) + +/-- Increasing positions in the actual two tree orders satisfy precisely the +node-order premise of the exhaustive six-mode localization theorem. -/ +theorem bodyNodeOrder_of_ordered {h : ℕ} {R : Type uR} {C : Type uC} [Preorder R] [Preorder C] + (rowIndex : Position h → R) (colIndex : Position h → C) + (hrowKey : ∀ v w : VariablePosition h, + rowIndex (Sum.inr (Sum.inl v)) < rowIndex (Sum.inr (Sum.inl w)) → + TreePositions.rowKey h v < TreePositions.rowKey h w) + (hcolKey : ∀ v w : VariablePosition h, + colIndex (Sum.inr (Sum.inl v)) < colIndex (Sum.inr (Sum.inl w)) → + TreePositions.columnKey h v < TreePositions.columnKey h w) + {t : Mode h} {r₀ r₁ c₀ c₁ : Position h} + (hr₀ : rowRole t 0 r₀) (hr₁ : rowRole t 1 r₁) + (hc₀ : colRole t 0 c₀) (hc₁ : colRole t 1 c₁) + (hrow : rowIndex r₀ < rowIndex r₁) (hcol : colIndex c₀ < colIndex c₁) : + BodyNodeOrder t r₀ r₁ c₀ c₁ := by + unfold BodyNodeOrder + split_ifs with hk₀ hk₁ hk₄ + · exact vertical_plus_node_order rowIndex hrowKey hk₀ hr₀ hr₁ hrow + · exact vertical_minus_node_order rowIndex hrowKey hk₁ hr₀ hr₁ hrow + · exact horizontal_plus_node_order colIndex hcolKey (by omega) hk₄ hc₀ hc₁ hcol + · exact horizontal_minus_node_order colIndex hcolKey (by omega) hc₀ hc₁ hcol + +/-- The concrete host localization conclusion, with the numerical mode-order +certificate discharged by the constructed key orders and increasing coordinates. -/ +theorem host_ordered_body_leaf_diagonal {h : ℕ} {R : Type uR} {C : Type uC} + [Preorder R] [Preorder C] + (rowIndex : Position h → R) (colIndex : Position h → C) + (hrowKey : ∀ v w : VariablePosition h, + rowIndex (Sum.inr (Sum.inl v)) < rowIndex (Sum.inr (Sum.inl w)) → + TreePositions.rowKey h v < TreePositions.rowKey h w) + (hcolKey : ∀ v w : VariablePosition h, + colIndex (Sum.inr (Sum.inl v)) < colIndex (Sum.inr (Sum.inl w)) → + TreePositions.columnKey h v < TreePositions.columnKey h w) + {t : Mode h} {r₀ r₁ c₀ c₁ : Position h} + (hr₀ : rowRole t 0 r₀) (hr₁ : rowRole t 1 r₁) + (hc₀ : colRole t 0 c₀) (hc₁ : colRole t 1 c₁) + (hrow : rowIndex r₀ < rowIndex r₁) (hcol : colIndex c₀ < colIndex c₁) + (hb : ModeLocalization.IsP (host r₀ c₀) (host r₀ c₁) + (host r₁ c₀) (host r₁ c₁)) : + ∃ z : Fin (2 ^ h), + r₀ = Sum.inr (Sum.inl (Fin.last (2 * h), z)) ∧ + c₀ = Sum.inr (Sum.inl (Fin.last (2 * h), z)) := by + exact host_body_leaf_diagonal hr₀ hr₁ hc₀ hc₁ + (bodyNodeOrder_of_ordered rowIndex colIndex hrowKey hcolKey hr₀ hr₁ hc₀ hc₁ hrow hcol) hb + +end Problem348.Construction + +end OAI diff --git a/lean/OAI/Combinatorics/MatrixRemoval/HostCopyBound.lean b/lean/OAI/Combinatorics/MatrixRemoval/HostCopyBound.lean new file mode 100644 index 0000000000000000000000000000000000000000..d9c7a10273d238cbd873f9811756f12a1fbd01bc --- /dev/null +++ b/lean/OAI/Combinatorics/MatrixRemoval/HostCopyBound.lean @@ -0,0 +1,105 @@ +import OAI.Combinatorics.MatrixRemoval.Host +import OAI.Combinatorics.MatrixRemoval.CopyBoundFixed + +namespace OAI + +/-! +# Transfer raw-host copy localization to the fixed counting target + +The row and column enumerations are independent. This adapter does not assume +that either enumeration preserves an ambient order on the sum type: the raw +localization hypothesis uses exactly the two induced finite orders. +-/ + +noncomputable section +namespace Problem348.Construction + +/-- The canonical host viewed through independent row/column enumerations. -/ +def hostMatrix {h n : ℕ} (er ec : Position h ≃ Fin n) : BinaryMatrix n := + fun i j => host (er.symm i) (ec.symm j) + +/-- A raw leaf is shared by the plus and minus names on both axes. -/ +def countedLeaf {h : ℕ} (z : Fin (2 ^ h)) : Position h := + Sum.inr (Sum.inl (Fin.last (2 * h), z)) + +/-- The depth/node conclusion of the mode analysis is exactly a leaf-diagonal +witness in the raw-position type, including the shared leaf class. -/ +theorem exists_countedLeaf_of_depth_node {h : ℕ} (r c : VariablePosition h) + (hr : depth r = h) (hc : depth c = h) (hnode : node r = node c) : + ∃ z, (Sum.inr (Sum.inl r) : Position h) = countedLeaf z ∧ + (Sum.inr (Sum.inl c) : Position h) = countedLeaf z := by + have hrclass : r.1 = Fin.last (2 * h) := by + apply Fin.ext + have hb := r.1.isLt + have hr' : r.1.val / 2 = h := hr + simp only [Fin.val_last] + omega + have hcclass : c.1 = Fin.last (2 * h) := by + apply Fin.ext + have hb := c.1.isLt + have hc' : c.1.val / 2 = h := hc + simp only [Fin.val_last] + omega + have hoffset : r.2 = c.2 := by + apply Fin.ext + simpa [node, hr, hc] using hnode + refine ⟨r.2, ?_, ?_⟩ + · simp only [countedLeaf, Sum.inr.injEq, Sum.inl.injEq] + exact Prod.ext hrclass rfl + · simp only [countedLeaf, Sum.inr.injEq, Sum.inl.injEq] + exact Prod.ext hcclass hoffset.symm + +/-- Exact localization of a raw copy transports without any count-equivalence +machinery. The increasing-map hypotheses refer to the supplied enumerations. -/ +theorem localization_on_fin {h n : ℕ} (er ec : Position h ≃ Fin n) + (hloc : ∀ r c : Fin 66 → Position h, + StrictMono (fun i => er (r i)) → StrictMono (fun j => ec (c j)) → + (∀ i j, host (r i) (c j) = fixedH i j) → + ∃ z, r 64 = countedLeaf z ∧ c 64 = countedLeaf z) + (r c : IncreasingMap 66 n) + (hentries : ∀ i j, hostMatrix er ec (r.val i) (c.val j) = fixedH i j) : + ∃ z, r.val 64 = er (countedLeaf z) ∧ c.val 64 = ec (countedLeaf z) := by + obtain ⟨z, hr, hc⟩ := hloc (fun i => er.symm (r.val i)) + (fun j => ec.symm (c.val j)) (by simpa using r.property) + (by simpa using c.property) hentries + refine ⟨z, ?_, ?_⟩ + · simpa using congrArg er hr + · simpa using congrArg ec hc + +/-- Integer bound used by the sequence assembly, from raw-host localization. -/ +theorem host_copyCount_le {h n : ℕ} (er ec : Position h ≃ Fin n) + (hloc : ∀ r c : Fin 66 → Position h, + StrictMono (fun i => er (r i)) → StrictMono (fun j => ec (c j)) → + (∀ i j, host (r i) (c j) = fixedH i j) → + ∃ z, r 64 = countedLeaf z ∧ c 64 = countedLeaf z) : + copyCount fixedH (hostMatrix er ec) ≤ 2 ^ h * n ^ 130 := by + classical + let L := Finset.univ.image (fun z : Fin (2 ^ h) => + (er (countedLeaf z), ec (countedLeaf z))) + have hcard : L.card ≤ 2 ^ h := Finset.card_image_le.trans (by simp) + apply (fixedCopyCount_le_of_body_cell_mem (hostMatrix er ec) L ?_).trans + (Nat.mul_le_mul_right _ hcard) + intro rc hrc + obtain ⟨z, hr, hc⟩ := localization_on_fin er ec hloc rc.1 rc.2 + (Finset.mem_filter.mp hrc).2 + exact Finset.mem_image.mpr ⟨z, Finset.mem_univ _, by simp [hr, hc]⟩ + +/-- The exact density upper bound of counterexample_sequence for this raw host. -/ +theorem host_copyDensity_le (h : ℕ) + (er ec : Position h ≃ Fin ((386 * h + 2) * 2 ^ h)) + (hloc : ∀ r c : Fin 66 → Position h, + StrictMono (fun i => er (r i)) → StrictMono (fun j => ec (c j)) → + (∀ i j, host (r i) (c j) = fixedH i j) → + ∃ z, r 64 = countedLeaf z ∧ c 64 = countedLeaf z) : + (copyCount fixedH (hostMatrix er ec) : ℝ) / + ((((386 * h + 2) * 2 ^ h : ℕ) : ℝ) ^ 132) ≤ + (1 / (((386 * h + 2 : ℕ) : ℝ) ^ 2)) * (1 / ((2 : ℝ) ^ h)) := by + apply sequenceCopyDensity_le_of_leaf_witness h (hostMatrix er ec) + (fun z => er (countedLeaf z)) (fun z => ec (countedLeaf z)) + exact localization_on_fin er ec hloc + +end Problem348.Construction + +end + +end OAI diff --git a/lean/OAI/Combinatorics/MatrixRemoval/HostModeIncidence.lean b/lean/OAI/Combinatorics/MatrixRemoval/HostModeIncidence.lean new file mode 100644 index 0000000000000000000000000000000000000000..33b9a2b79f28df0974440f47f83cd10f81c3e847 --- /dev/null +++ b/lean/OAI/Combinatorics/MatrixRemoval/HostModeIncidence.lean @@ -0,0 +1,175 @@ +import OAI.Combinatorics.MatrixRemoval.Host +import OAI.Combinatorics.MatrixRemoval.ModeIncidence + +namespace OAI + +/-! +The mode-incidence count bounds sparse anchor traces for the actual +finite host. +-/ + +universe uAlpha + +namespace Problem348.Construction + +private def incidenceKind (k : ℕ) : ModeIncidence.Kind := + if k < 2 then .vertical (decide (k = 0)) + else .horizontal (decide (k < 4)) (decide (k % 2 = 1)) + +/-- Decode the canonical six-mode enumeration into the incidence labels. -/ +def incidenceMode {h : ℕ} (t : Mode h) : ModeIncidence.Mode := + (level t, incidenceKind (kind t)) + +/-- Boolean parity, in the convention used by ModeIncidence. -/ +def nodeParity {h : ℕ} (v : VariablePosition h) : Bool := + decide (node v % 2 = 1) + +private theorem incidenceKind_injective {a b : ℕ} (ha : a < 6) (hb : b < 6) + (hab : incidenceKind a = incidenceKind b) : a = b := by + interval_cases a <;> interval_cases b <;> simp_all [incidenceKind] + + theorem incidenceMode_injective (h : ℕ) : + Function.Injective (@incidenceMode h) := by + intro t u htu + have hl : level t = level u := congrArg Prod.fst htu + have hk := incidenceKind_injective (kind_lt t) (kind_lt u) + (congrArg Prod.snd htu) + apply Fin.ext + dsimp [level] at hl + dsimp [kind] at hk + omega + + theorem rowRole_incident {h : ℕ} (t : Mode h) (j : Fin 2) + (v : VariablePosition h) (hv : rowRole t j (.inr (.inl v))) : + ModeIncidence.rowIncident h (depth v) (plus v) (nodeParity v) + (incidenceMode t) := by + have hp := level_pos t + have hl := level_le t + have hk := kind_lt t + interval_cases e : kind t <;> fin_cases j <;> + simp_all [rowRole, incidenceMode, incidenceKind, ModeIncidence.rowIncident, + ModeIncidence.hasSign, AtLevel, nodeParity] + + theorem colRole_incident {h : ℕ} (t : Mode h) (j : Fin 2) + (v : VariablePosition h) (hv : colRole t j (.inr (.inl v))) : + ModeIncidence.colIncident h (depth v) (plus v) (nodeParity v) + (incidenceMode t) := by + have hp := level_pos t + have hl := level_le t + have hk := kind_lt t + interval_cases e : kind t <;> fin_cases j <;> + simp_all [colRole, incidenceMode, incidenceKind, ModeIncidence.colIncident, + ModeIncidence.hasSign, AtLevel, nodeParity] + +/-- The actual canonical variable row meets at most four modes. -/ +theorem card_rowRole_modes_le_four {h : ℕ} (v : VariablePosition h) + (s : Finset (Mode h)) + (hs : ∀ t ∈ s, ∃ j, rowRole t j (.inr (.inl v))) : s.card ≤ 4 := by + rw [← Finset.card_image_of_injective s (incidenceMode_injective h)] + apply ModeIncidence.card_row_incident_le_four (depth_le v) + intro t ht + obtain ⟨u, hu, rfl⟩ := Finset.mem_image.mp ht + obtain ⟨j, hj⟩ := hs u hu + exact rowRole_incident u j v hj + +/-- The actual canonical variable column meets at most four modes. -/ +theorem card_colRole_modes_le_four {h : ℕ} (v : VariablePosition h) + (s : Finset (Mode h)) + (hs : ∀ t ∈ s, ∃ j, colRole t j (.inr (.inl v))) : s.card ≤ 4 := by + rw [← Finset.card_image_of_injective s (incidenceMode_injective h)] + apply ModeIncidence.card_col_incident_le_four (depth_le v) + intro t ht + obtain ⟨u, hu, rfl⟩ := Finset.mem_image.mp ht + obtain ⟨j, hj⟩ := hs u hu + exact colRole_incident u j v hj + +/-- A nonanchor row has at most one one-bearing anchor group in each mode. -/ +theorem row_anchor_ones_unique_group {h : ℕ} + (x : VariablePosition h ⊕ Fin (2 ^ h)) + (a b : AnchorPosition h) + (ha : host (.inr x) (.inl a) = true) + (hb : host (.inr x) (.inl b) = true) + (hm : a.1 = b.1) : a.2.1 = b.2.1 := by + rcases a with ⟨t, u, ax⟩ + rcases b with ⟨t', v, bx⟩ + dsimp at hm ⊢ + subst t' + simp only [host, decide_eq_true_eq] at ha hb + rcases ha with ⟨hu, hr⟩ | ⟨hu, hr⟩ <;> + rcases hb with ⟨hv, hs⟩ | ⟨hv, hs⟩ + · exact Fin.ext (by omega) + · exact False.elim (rowRole_disjoint t (.inr x) ⟨hr, hs⟩) + · exact False.elim (rowRole_disjoint t (.inr x) ⟨hs, hr⟩) + · exact Fin.ext (by omega) + +/-- The corresponding unit-signature fact for a nonanchor column. -/ +theorem col_anchor_ones_unique_group {h : ℕ} + (x : VariablePosition h ⊕ Fin (2 ^ h)) + (a b : AnchorPosition h) + (ha : host (.inl a) (.inr x) = true) + (hb : host (.inl b) (.inr x) = true) + (hm : a.1 = b.1) : a.2.1 = b.2.1 := by + rcases a with ⟨t, u, ax⟩ + rcases b with ⟨t', v, bx⟩ + dsimp at hm ⊢ + subst t' + simp only [host, decide_eq_true_eq] at ha hb + rcases ha with ⟨hu, hr⟩ | ⟨hu, hr⟩ <;> + rcases hb with ⟨hv, hs⟩ | ⟨hv, hs⟩ + · exact Fin.ext (by omega) + · exact False.elim (colRole_disjoint t (.inr x) ⟨hr, hs⟩) + · exact False.elim (colRole_disjoint t (.inr x) ⟨hs, hr⟩) + · exact Fin.ext (by omega) + +/-- The concrete sparse-anchor-trace conclusion for arbitrary indexed anchor +representatives: no group is represented twice among the selected indices. -/ +theorem card_variable_row_anchor_ones_le_four {h : ℕ} {α : Type uAlpha} + [DecidableEq α] (v : VariablePosition h) (s : Finset α) + (a : α → AnchorPosition h) + (hgroups : Set.InjOn (fun x => ((a x).1, (a x).2.1)) (s : Set α)) : + (s.filter (fun x => host (.inr (.inl v)) (.inl (a x)) = true)).card ≤ 4 := by + classical + apply ModeIncidence.card_row_ones_le_four + (sign := plus v) (parity := nodeParity v) (depth_le v) s + (fun x => incidenceMode (a x).1) + (fun x => host (.inr (.inl v)) (.inl (a x))) + · intro x hx hentry + have hrole : ((a x).2.1.val = 0 ∧ rowRole (a x).1 0 (.inr (.inl v))) ∨ + ((a x).2.1.val = 1 ∧ rowRole (a x).1 1 (.inr (.inl v))) := by + simpa only [host, decide_eq_true_eq] using hentry + rcases hrole with ⟨_, hr⟩ | ⟨_, hr⟩ + · exact rowRole_incident (a x).1 0 v hr + · exact rowRole_incident (a x).1 1 v hr + · intro x hx y hy hxe hye hm + have hm' : (a x).1 = (a y).1 := incidenceMode_injective h hm + have hg : (a x).2.1 = (a y).2.1 := + row_anchor_ones_unique_group (.inl v) (a x) (a y) hxe hye hm' + exact hgroups hx hy (Prod.ext hm' hg) + +/-- The concrete sparse-anchor-trace conclusion for a variable column. -/ +theorem card_variable_col_anchor_ones_le_four {h : ℕ} {α : Type uAlpha} + [DecidableEq α] (v : VariablePosition h) (s : Finset α) + (a : α → AnchorPosition h) + (hgroups : Set.InjOn (fun x => ((a x).1, (a x).2.1)) (s : Set α)) : + (s.filter (fun x => host (.inl (a x)) (.inr (.inl v)) = true)).card ≤ 4 := by + classical + apply ModeIncidence.card_col_ones_le_four + (sign := plus v) (parity := nodeParity v) (depth_le v) s + (fun x => incidenceMode (a x).1) + (fun x => host (.inl (a x)) (.inr (.inl v))) + · intro x hx hentry + have hrole : ((a x).2.1.val = 0 ∧ colRole (a x).1 0 (.inr (.inl v))) ∨ + ((a x).2.1.val = 1 ∧ colRole (a x).1 1 (.inr (.inl v))) := by + simpa only [host, decide_eq_true_eq] using hentry + rcases hrole with ⟨_, hr⟩ | ⟨_, hr⟩ + · exact colRole_incident (a x).1 0 v hr + · exact colRole_incident (a x).1 1 v hr + · intro x hx y hy hxe hye hm + have hm' : (a x).1 = (a y).1 := incidenceMode_injective h hm + have hg : (a x).2.1 = (a y).2.1 := + col_anchor_ones_unique_group (.inl v) (a x) (a y) hxe hye hm' + exact hgroups hx hy (Prod.ext hm' hg) + +end Problem348.Construction + +end OAI diff --git a/lean/OAI/Combinatorics/MatrixRemoval/HostNonshattering.lean b/lean/OAI/Combinatorics/MatrixRemoval/HostNonshattering.lean new file mode 100644 index 0000000000000000000000000000000000000000..fd91c5052d0566029e9cf14385ceea21cdb2fe14 --- /dev/null +++ b/lean/OAI/Combinatorics/MatrixRemoval/HostNonshattering.lean @@ -0,0 +1,170 @@ +import OAI.Combinatorics.MatrixRemoval.Host +import OAI.Combinatorics.MatrixRemoval.DirectNonshattering + +namespace OAI + +/-! +# Nonshattering for the concrete canonical host + +This is a direct application of the qualitative five-column obstruction to +`Problem348.Construction.host`. It needs no axis order and no injectivity +assumption on the five selected non-anchor columns. +-/ + +universe uR + +namespace Problem348.Construction + +open Finset + +noncomputable section + +/-- The two kinds of non-anchor positions, without their outer sum tag. -/ +abbrev NonanchorPosition (h : ℕ) := VariablePosition h ⊕ Fin (2 ^ h) + +/-- Column-class labels for the non-anchor induced submatrix. The dummy label +is irrelevant because dummy columns are treated separately. -/ +def nonanchorClass {h : ℕ} : NonanchorPosition h → ℕ + | Sum.inl v => v.1.val + | Sum.inr _ => 0 + +def nonanchorKey {h : ℕ} : NonanchorPosition h → ℕ + | Sum.inl v => node v + | Sum.inr _ => 0 + +def nonanchorDummy {h : ℕ} : NonanchorPosition h → Prop + | Sum.inl _ => False + | Sum.inr _ => True + +instance {h : ℕ} (x : NonanchorPosition h) : Decidable (nonanchorDummy x) := by + cases x <;> simp only [nonanchorDummy] <;> infer_instance + +/-- The three class labels that can contain ones in a variable row. -/ +def variableSupportLabels {h : ℕ} (r : VariablePosition h) : Finset ℕ := + {r.1.val, 2 * (depth r - 1), 2 * (depth r - 1) + 1} + +theorem variableSupportLabels_card_le {h : ℕ} (r : VariablePosition h) : + (variableSupportLabels r).card ≤ 3 := by + exact Finset.card_le_three + +/-- The constant-class suffix property, stated for the actual host kernel. -/ +theorem variableEntry_mono_class {h : ℕ} (r c d : VariablePosition h) + (hclass : c.1.val = d.1.val) (hnode : node c ≤ node d) + (hc : variableEntry r c = true) : variableEntry r d = true := by + have hd : depth c = depth d := by simp only [depth, hclass] + have hp : plus c = plus d := by simp only [plus, hclass] + unfold variableEntry at hc ⊢ + simp only [hd, hp] at hc + split_ifs at hc ⊢ <;> simp_all <;> omega + +/-- A true variable entry has one of the three possible column-class labels. -/ +theorem variableEntry_mem_support {h : ℕ} (r c : VariablePosition h) + (hc : variableEntry r c = true) : c.1.val ∈ variableSupportLabels r := by + have hr := r.1.isLt + have hcv := c.1.isLt + simp only [variableSupportLabels, Finset.mem_insert, Finset.mem_singleton] + unfold variableEntry at hc + simp only [depth, plus, decide_eq_true_eq] at hc ⊢ + split_ifs at hc <;> simp_all <;> omega + +/-- The induced matrix on all non-anchor positions misses a five-bit word. -/ +theorem nonanchor_host_not_surjective (h : ℕ) + (selected : Fin 5 → NonanchorPosition h) : + ¬ Function.Surjective + (fun r : NonanchorPosition h => + fun i => host (Sum.inr r) (Sum.inr (selected i))) := by + apply DirectNonshattering.not_surjective_selected_columns + (fun r c : NonanchorPosition h => host (Sum.inr r) (Sum.inr c)) + nonanchorDummy nonanchorDummy nonanchorClass nonanchorKey + · intro r hr c + cases r with + | inl r => exact False.elim hr + | inr r => cases c <;> rfl + · intro c hc r + cases c with + | inl c => exact False.elim hc + | inr c => cases r <;> rfl + · intro r hr c d hc hd hclass hnode he + cases r with + | inr r => exact False.elim (hr trivial) + | inl r => + cases c with + | inr c => exact False.elim (hc trivial) + | inl c => + cases d with + | inr d => exact False.elim (hd trivial) + | inl d => exact variableEntry_mono_class r c d hclass hnode he + · intro r hr + cases r with + | inr r => exact False.elim (hr trivial) + | inl r => + apply (Finset.card_le_card ?_).trans (variableSupportLabels_card_le r) + intro a ha + obtain ⟨c, hc, rfl⟩ := Finset.mem_image.mp ha + obtain ⟨_, hnd, he⟩ := Finset.mem_filter.mp hc + cases c with + | inr c => exact False.elim (hnd trivial) + | inl c => exact variableEntry_mem_support r c he + +/-- The actual host, stated using its outer position type. This avoids any +choice of a separate non-anchor enumeration in anchor-rigidity applications. -/ +theorem host_nonanchor_missing_word {h : ℕ} (columns : Fin 5 → Position h) + (hcolumns : ∀ i, ∃ c : NonanchorPosition h, columns i = Sum.inr c) : + ∃ w : Fin 5 → Bool, ∀ r : Position h, + (∃ a : NonanchorPosition h, r = Sum.inr a) → + (fun i => host r (columns i)) ≠ w := by + classical + choose selected hselected using hcolumns + obtain ⟨w, hw⟩ : ∃ w : Fin 5 → Bool, ∀ r : NonanchorPosition h, + (fun i => host (Sum.inr r) (Sum.inr (selected i))) ≠ w := by + simpa only [Function.Surjective, not_forall, not_exists] using + nonanchor_host_not_surjective h selected + refine ⟨w, ?_⟩ + rintro r ⟨a, rfl⟩ + simpa only [hselected] using hw a + +/-- Restricting to any collection of non-anchor rows still misses a word. +This is the form used for the final 32 rows of an alleged anchor copy. -/ +theorem host_nonanchor_submatrix_not_surjective {h : ℕ} {R : Type uR} + (rows : R → Position h) (columns : Fin 5 → Position h) + (hrows : ∀ r, ∃ a : NonanchorPosition h, rows r = Sum.inr a) + (hcolumns : ∀ i, ∃ c : NonanchorPosition h, columns i = Sum.inr c) : + ¬ Function.Surjective (fun r i => host (rows r) (columns i)) := by + obtain ⟨w, hw⟩ := host_nonanchor_missing_word columns hcolumns + intro hsurj + obtain ⟨r, hr⟩ := hsurj w + exact hw (rows r) (hrows r) hr + +/-- The outer sum tag gives a convenient intrinsic non-anchor predicate. -/ +@[simp] theorem exists_nonanchor_iff_not_isLeft {h : ℕ} (x : Position h) : + (∃ a : NonanchorPosition h, x = Sum.inr a) ↔ ¬ x.isLeft := by + cases x <;> simp + +/-- Pointwise missing-word property for concrete anchor rigidity. -/ +theorem host_nonanchor_missing_entry {h : ℕ} (columns : Fin 5 → Position h) + (hcolumns : ∀ i, ¬ (columns i).isLeft) : + ∃ w : Fin 5 → Bool, ∀ r : Position h, ¬ r.isLeft → + ∃ i, host r (columns i) ≠ w i := by + obtain ⟨w, hw⟩ := host_nonanchor_missing_word columns + (fun i => (exists_nonanchor_iff_not_isLeft (columns i)).mpr (hcolumns i)) + refine ⟨w, ?_⟩ + intro r hr + have hne := hw r ((exists_nonanchor_iff_not_isLeft r).mpr hr) + exact not_forall.mp (fun he => hne (funext he)) + +/-- The subtype formulation also avoids making any non-anchor choices. -/ +theorem host_nonanchor_subtype_not_surjective {h : ℕ} + (columns : Fin 5 → Position h) (hcolumns : ∀ i, ¬ (columns i).isLeft) : + ¬ Function.Surjective + (fun r : {x : Position h // ¬ x.isLeft} => fun i => host r.val (columns i)) := by + apply host_nonanchor_submatrix_not_surjective + (fun r : {x : Position h // ¬ x.isLeft} => r.val) columns + · intro r + exact (exists_nonanchor_iff_not_isLeft r.val).mpr r.property + · intro i + exact (exists_nonanchor_iff_not_isLeft (columns i)).mpr (hcolumns i) + +end +end Problem348.Construction + +end OAI diff --git a/lean/OAI/Combinatorics/MatrixRemoval/HostRepairDistance.lean b/lean/OAI/Combinatorics/MatrixRemoval/HostRepairDistance.lean new file mode 100644 index 0000000000000000000000000000000000000000..64ad70c2880e7c018301d74974a160e01052329f --- /dev/null +++ b/lean/OAI/Combinatorics/MatrixRemoval/HostRepairDistance.lean @@ -0,0 +1,104 @@ +import OAI.Combinatorics.MatrixRemoval.HostSampledSelection +import OAI.Combinatorics.MatrixRemoval.HostSamplingCompatibility + +namespace OAI + +/-! +# Arbitrary-repair lower bound for the actual canonical host + +The concrete common-leaf selection satisfies both independent certificates: +its guarded path is valid, and its chosen coordinates bound each guard cell's +sampling multiplicity. +Together these prove the integer repair lower bound. No assumption +about preservation of arbitrary variable-variable cells is made. +-/ + +noncomputable section +namespace Problem348.Construction.SampledSelection + +open HostSampledPath HostSampling TreeSampling + +/-- The actual constant-offset anchor frame is chosen by its row/column seeds. -/ +theorem frame_chosen {h n : ℕ} (er ec : Position h ≃ Fin n) + (ha : AxisConditions er ec) (s : Seeds (2 ^ h)) (t : Mode h) : + FrameChosen er ec s (frame er ec ha t s.2.1 s.2.2) := by + constructor + · intro u + simp [frame, SelectedAnchor.frame, sampleDepth] + · intro v + simp [frame, SelectedAnchor.frame, sampleDepth] + · intro u + exact rowChosen_path_anchor er s t u + · intro v + exact colChosen_path_anchor ec s t v + +/-- Every actual path point and anchor frame obeys the uniform sampler's +coordinate equations. This is separate from all matrix-entry claims. -/ +theorem selection_chosen {h n : ℕ} (hh : 1 ≤ h) (er ec : Position h ≃ Fin n) + (ha : AxisConditions er ec) (s : Seeds (2 ^ h)) : + PathChosen er ec s (selection hh er ec ha s.1 s.2.1 s.2.2) := by + constructor + · intro i hi + simpa only [selection, path_of_le hi] using rowChosen_path er i hi true s + · intro i hi + simpa only [selection, path_of_le hi] using rowChosen_path er i hi false s + · intro i hi + simpa only [selection, path_of_le hi] using colChosen_path ec i hi true s + · intro i hi + simpa only [selection, path_of_le hi] using colChosen_path ec i hi false s + · exact rowChosen_path_dummy er s + · exact colChosen_path_dummy ec s + · simp [selection, HostSampledPath.dummy, sampleDepth] + · simp [selection, HostSampledPath.dummy, sampleDepth] + · simpa only [selection, Equiv.symm_apply_apply, path_of_le (Nat.zero_le h)] using + protected_path_roots h true true s.1 s.2.1 s.2.2 + · simpa only [selection, Equiv.symm_apply_apply, path_of_le (Nat.zero_le h)] using + protected_path_roots h false false s.1 s.2.1 s.2.2 + · intro i hi + exact frame_chosen er ec ha s _ + · intro i hi + exact frame_chosen er ec ha s _ + · intro i hi + exact frame_chosen er ec ha s _ + · intro i hi + exact frame_chosen er ec ha s _ + +/-- Each fixed guarded cell occupies at most the prescribed `1/m²` fraction +of the three-seed sample space, for the actual selected paths. -/ +theorem selection_guard_frequency {h n : ℕ} (hh : 1 ≤ h) + (er ec : Position h ≃ Fin n) (ha : AxisConditions er ec) + (rc : Fin n × Fin n) : + (Finset.univ.filter fun s : Seeds (2 ^ h) => + rc ∈ (selection hh er ec ha s.1 s.2.1 s.2.2).guards h).card * (2 ^ h) ^ 2 ≤ + Fintype.card (Seeds (2 ^ h)) := + path_guard_frequency er ec + (fun s => selection hh er ec ha s.1 s.2.1 s.2.2) + (fun s => selection_chosen hh er ec ha s) rc + +/-- The arbitrary-repair lower bound for the literal canonical host. +The independent axis enumerations satisfy `AxisConditions`: increasing anchor +groups precede all nonanchors, variable rows precede dummy rows, dummy columns +precede variable columns, and sampled parent/child pairs obey the four signed +tree-order inequalities. No entry-preservation condition is imposed on repairs. -/ +theorem hammingDistance_ge {h n : ℕ} (hh : 1 ≤ h) + (er ec : Position h ≃ Fin n) (ha : AxisConditions er ec) + (B : BinaryMatrix n) (hfree : HFree fixedH B) : + (2 ^ h) ^ 2 ≤ hammingDistance (SelectedAnchor.matrix er ec) B := by + classical + apply Sampling.hammingDistance_ge_of_guard_sampling fixedH + (SelectedAnchor.matrix er ec) B + (fun s : Seeds (2 ^ h) => (selection hh er ec ha s.1 s.2.1 s.2.2).guards h) + (2 ^ h) + · rw [card_seeds] + positivity + · exact selection_guard_frequency hh er ec ha + · intro s hag + exact GuardedPath.Selection.not_HFree_of_agree + (selection_valid hh er ec ha s.1 s.2.1 s.2.2) hag + · exact hfree + +end Problem348.Construction.SampledSelection + +end + +end OAI diff --git a/lean/OAI/Combinatorics/MatrixRemoval/HostRoleExtraction.lean b/lean/OAI/Combinatorics/MatrixRemoval/HostRoleExtraction.lean new file mode 100644 index 0000000000000000000000000000000000000000..3a50359eefaf8ed5630bf969a342cd761bde85a6 --- /dev/null +++ b/lean/OAI/Combinatorics/MatrixRemoval/HostRoleExtraction.lean @@ -0,0 +1,153 @@ +import OAI.Combinatorics.MatrixRemoval.Host +import OAI.Combinatorics.MatrixRemoval.BodyRoles + +namespace OAI + +/-! +# Body-role extraction for the canonical host + +Anchor traces determine body roles in the actual `Construction.host` table. +-/ + +namespace Problem348.Construction + +theorem rowRole_of_anchor_trace {h : ℕ} (t : Mode h) (r : Position h) + (z : Fin 64 → Fin (2 ^ h)) (b : Fin 2) + (hsig : ∀ v : Fin 64, + host r (Sum.inl (t, v, z v)) = decide (v.val = b.val)) : + rowRole t b r := by + rcases r with ⟨t', u, a⟩ | r + · by_cases ht : t' = t + · subst t' + have heq : (fun v => anchor64 u v) = + (fun v : Fin 64 => decide (v.val = b.val)) := by + funext v + simpa [host] using hsig v + exact False.elim (BodySignatures52.anchor64_row_ne_body_signature u b heq) + · have heq : (fun _ : Fin 64 => false) = + (fun v : Fin 64 => decide (v.val = b.val)) := by + funext v + simpa [host, ht] using hsig v + exact False.elim (BodySignatures52.zero_ne_body_signature b heq) + · fin_cases b + · have hv := hsig (0 : Fin 64) + simpa [host] using hv + · have hv := hsig (1 : Fin 64) + simpa [host] using hv + +theorem colRole_of_anchor_trace {h : ℕ} (t : Mode h) (c : Position h) + (z : Fin 64 → Fin (2 ^ h)) (b : Fin 2) + (hsig : ∀ u : Fin 64, + host (Sum.inl (t, u, z u)) c = decide (u.val = b.val)) : + colRole t b c := by + rcases c with ⟨t', v, a⟩ | c + · by_cases ht : t = t' + · subst t' + have heq : (fun u => anchor64 u v) = + (fun u : Fin 64 => decide (u.val = b.val)) := by + funext u + simpa [host] using hsig u + exact False.elim (BodySignatures52.anchor64_col_ne_body_signature v b heq) + · have heq : (fun _ : Fin 64 => false) = + (fun u : Fin 64 => decide (u.val = b.val)) := by + funext u + simpa [host, ht] using hsig u + exact False.elim (BodySignatures52.zero_ne_body_signature b heq) + · fin_cases b + · have hu := hsig (0 : Fin 64) + simpa [host] using hu + · have hu := hsig (1 : Fin 64) + simpa [host] using hu + +/-- Exact converse, useful also when constructing a guarded anchor frame. -/ +theorem anchor_trace_of_rowRole {h : ℕ} (t : Mode h) (r : Position h) + (z : Fin 64 → Fin (2 ^ h)) (b : Fin 2) (hr : rowRole t b r) : + ∀ v : Fin 64, host r (Sum.inl (t, v, z v)) = decide (v.val = b.val) := by + have hd := rowRole_disjoint t r + rcases r with a | r + · simp [rowRole] at hr + · fin_cases b + · have hn : ¬ rowRole t 1 (Sum.inr r) := fun h1 => hd ⟨hr, h1⟩ + intro v + simp [host, hn] + exact fun _ => hr + · have hn : ¬ rowRole t 0 (Sum.inr r) := fun h0 => hd ⟨h0, hr⟩ + intro v + simp [host, hn] + exact fun _ => hr + +theorem anchor_trace_of_colRole {h : ℕ} (t : Mode h) (c : Position h) + (z : Fin 64 → Fin (2 ^ h)) (b : Fin 2) (hc : colRole t b c) : + ∀ u : Fin 64, host (Sum.inl (t, u, z u)) c = decide (u.val = b.val) := by + have hd := colRole_disjoint t c + rcases c with a | c + · simp [colRole] at hc + · fin_cases b + · have hn : ¬ colRole t 1 (Sum.inr c) := fun h1 => hd ⟨hc, h1⟩ + intro u + simp [host, hn] + exact fun _ => hc + · have hn : ¬ colRole t 0 (Sum.inr c) := fun h0 => hd ⟨h0, hc⟩ + intro u + simp [host, hn] + exact fun _ => hc + +/-- Raw matching version, independent of any enumeration or order on the axes. -/ +theorem host_body_roles_of_matching {h : ℕ} + (r c : Fin 66 → Position h) + (hmatch : ∀ i j, host (r i) (c j) = fixedH i j) + (t : Mode h) (zr zc : Fin 64 → Fin (2 ^ h)) + (hrows : ∀ u, r (BodySignatures52.anchorIndex u) = Sum.inl (t, u, zr u)) + (hcols : ∀ v, c (BodySignatures52.anchorIndex v) = Sum.inl (t, v, zc v)) + (b : Fin 2) : + rowRole t b (r (BodySignatures52.bodyIndex b)) ∧ + colRole t b (c (BodySignatures52.bodyIndex b)) := by + constructor + · apply rowRole_of_anchor_trace t _ zc b + intro v + rw [← hcols v] + exact (hmatch _ _).trans (BodySignatures52.fixedH_body_anchor b v) + · apply colRole_of_anchor_trace t _ zr b + intro u + rw [← hrows u] + exact (hmatch _ _).trans (BodySignatures52.fixedH_anchor_body u b) + +/-- The lower-right four cells of any raw matching copy form exactly P. -/ +theorem host_body_entries_of_matching {h : ℕ} + (r c : Fin 66 → Position h) + (hmatch : ∀ i j, host (r i) (c j) = fixedH i j) : + host (r (BodySignatures52.bodyIndex 0)) (c (BodySignatures52.bodyIndex 0)) = true ∧ + host (r (BodySignatures52.bodyIndex 0)) (c (BodySignatures52.bodyIndex 1)) = false ∧ + host (r (BodySignatures52.bodyIndex 1)) (c (BodySignatures52.bodyIndex 0)) = true ∧ + host (r (BodySignatures52.bodyIndex 1)) (c (BodySignatures52.bodyIndex 1)) = true := by + simp only [hmatch, BodySignatures52.fixedH_body_body] + decide + +/-- An actual ordered copy in a transported canonical host has the +two prescribed body roles, once anchor rigidity pins its prefix. -/ +theorem host_body_roles_of_copy {h n : ℕ} {A : BinaryMatrix n} + (row col : Fin n → Position h) + (hA : ∀ i j, A i j = host (row i) (col j)) + {rc : IncreasingMap 66 n × IncreasingMap 66 n} + (hcopy : rc ∈ orderedCopies fixedH A) + (t : Mode h) (zr zc : Fin 64 → Fin (2 ^ h)) + (hrows : ∀ u, row (rc.1.val (BodySignatures52.anchorIndex u)) = + Sum.inl (t, u, zr u)) + (hcols : ∀ v, col (rc.2.val (BodySignatures52.anchorIndex v)) = + Sum.inl (t, v, zc v)) + (b : Fin 2) : + rowRole t b (row (rc.1.val (BodySignatures52.bodyIndex b))) ∧ + colRole t b (col (rc.2.val (BodySignatures52.bodyIndex b))) := by + constructor + · apply rowRole_of_anchor_trace t _ zc b + intro v + rw [← hcols v, ← hA] + exact BodySignatures52.copy_body_row_signature hcopy b v + · apply colRole_of_anchor_trace t _ zr b + intro u + rw [← hrows u, ← hA] + exact BodySignatures52.copy_body_col_signature hcopy b u + +end Problem348.Construction + +end OAI diff --git a/lean/OAI/Combinatorics/MatrixRemoval/HostRootLeaf.lean b/lean/OAI/Combinatorics/MatrixRemoval/HostRootLeaf.lean new file mode 100644 index 0000000000000000000000000000000000000000..4ed012b84aeb76df94a51899f40d180810d232fe --- /dev/null +++ b/lean/OAI/Combinatorics/MatrixRemoval/HostRootLeaf.lean @@ -0,0 +1,121 @@ +import OAI.Combinatorics.MatrixRemoval.Host + +namespace OAI + +/-! Root bits and shared-leaf entries of the exact canonical construction. -/ + +namespace Problem348.Construction + +/-- At the root, all uniform coordinates name node zero. -/ +theorem node_eq_zero_of_depth_zero {h : ℕ} (v : VariablePosition h) + (hv : depth v = 0) : node v = 0 := by + unfold node + rw [hv, Nat.sub_zero] + exact Nat.div_eq_of_lt v.2.isLt + +/-- The even class zero is the plus root. -/ +@[simp] theorem depth_root_plus {h : ℕ} (x : Fin (2 ^ h)) : + depth ((0 : Fin (2 * h + 1)), x) = 0 := by + simp [depth] + +@[simp] theorem plus_root_plus {h : ℕ} (x : Fin (2 ^ h)) : + plus ((0 : Fin (2 * h + 1)), x) = true := by + simp [plus] + +/-- All entries between the two plus-root blocks are one. -/ +theorem variableEntry_root_plus {h : ℕ} (x y : Fin (2 ^ h)) : + variableEntry ((0 : Fin (2 * h + 1)), x) + ((0 : Fin (2 * h + 1)), y) = true := by + have hx := node_eq_zero_of_depth_zero ((0 : Fin (2 * h + 1)), x) + (depth_root_plus x) + have hy := node_eq_zero_of_depth_zero ((0 : Fin (2 * h + 1)), y) + (depth_root_plus y) + simp [variableEntry, hx, hy] + +/-- Class one is the minus root when the tree has positive height. -/ +@[simp] theorem depth_root_minus {h : ℕ} (hh : 1 ≤ h) (x : Fin (2 ^ h)) : + depth ((⟨1, by omega⟩ : Fin (2 * h + 1)), x) = 0 := by + simp [depth] + +@[simp] theorem plus_root_minus {h : ℕ} (hh : 1 ≤ h) (x : Fin (2 ^ h)) : + plus ((⟨1, by omega⟩ : Fin (2 * h + 1)), x) = false := by + simp [plus] + +/-- All entries between the minus-root blocks are zero. -/ +theorem variableEntry_root_minus {h : ℕ} (hh : 1 ≤ h) (x y : Fin (2 ^ h)) : + variableEntry ((⟨1, by omega⟩ : Fin (2 * h + 1)), x) + ((⟨1, by omega⟩ : Fin (2 * h + 1)), y) = false := by + have hx := node_eq_zero_of_depth_zero + ((⟨1, by omega⟩ : Fin (2 * h + 1)), x) (depth_root_minus hh x) + have hy := node_eq_zero_of_depth_zero + ((⟨1, by omega⟩ : Fin (2 * h + 1)), y) (depth_root_minus hh y) + simp [variableEntry, depth, plus, hx, hy, show 0 ≠ h by omega] + +/-- The last class is the single shared leaf class. -/ +@[simp] theorem depth_shared_leaf {h : ℕ} (x : Fin (2 ^ h)) : + depth (Fin.last (2 * h), x) = h := by + simp [depth] + +@[simp] theorem node_shared_leaf {h : ℕ} (x : Fin (2 ^ h)) : + node (Fin.last (2 * h), x) = x.val := by + simp [node] + +/-- Entry values at shared leaves, including the minus diagonal. -/ +theorem variableEntry_shared_leaf {h : ℕ} (x y : Fin (2 ^ h)) : + variableEntry (Fin.last (2 * h), x) (Fin.last (2 * h), y) = + decide (x.val ≤ y.val) := by + simp [variableEntry] + +/-- Exact unchanged plus root bit on the full host. -/ +theorem host_root_plus {h : ℕ} (x y : Fin (2 ^ h)) : + host (Sum.inr (Sum.inl ((0 : Fin (2 * h + 1)), x))) + (Sum.inr (Sum.inl ((0 : Fin (2 * h + 1)), y))) = true := + variableEntry_root_plus x y + +/-- Exact unchanged minus root bit on the full host. -/ +theorem host_root_minus {h : ℕ} (hh : 1 ≤ h) (x y : Fin (2 ^ h)) : + host (Sum.inr (Sum.inl ((⟨1, by omega⟩ : Fin (2 * h + 1)), x))) + (Sum.inr (Sum.inl ((⟨1, by omega⟩ : Fin (2 * h + 1)), y))) = false := + variableEntry_root_minus hh x y + +/-- The shared-leaf diagonal consists of ones. -/ +theorem host_shared_leaf_diagonal {h : ℕ} (x : Fin (2 ^ h)) : + host (Sum.inr (Sum.inl (Fin.last (2 * h), x))) + (Sum.inr (Sum.inl (Fin.last (2 * h), x))) = true := by + simp [host, variableEntry_shared_leaf] + +/-- Constructor-free form of the positive root entry. -/ +theorem variableEntry_root_plus_of_atLevel {h : ℕ} (hh : 1 ≤ h) + (r c : VariablePosition h) (hr : AtLevel 0 true r) (hc : AtLevel 0 true c) : + variableEntry r c = true := by + have hrp : plus r = true := hr.2.resolve_left (by omega) + have hcp : plus c = true := hc.2.resolve_left (by omega) + have hrn := node_eq_zero_of_depth_zero r hr.1 + have hcn := node_eq_zero_of_depth_zero c hc.1 + simp [variableEntry, hr.1, hc.1, hrp, hcp, hrn, hcn] + +/-- Constructor-free form of the negative root entry. -/ +theorem variableEntry_root_minus_of_atLevel {h : ℕ} (hh : 1 ≤ h) + (r c : VariablePosition h) (hr : AtLevel 0 false r) (hc : AtLevel 0 false c) : + variableEntry r c = false := by + have hrp : plus r = false := hr.2.resolve_left (by omega) + have hcp : plus c = false := hc.2.resolve_left (by omega) + have hrn := node_eq_zero_of_depth_zero r hr.1 + have hcn := node_eq_zero_of_depth_zero c hc.1 + simp [variableEntry, hr.1, hc.1, hrp, hcp, hrn, hcn, show 0 ≠ h by omega] + +/-- Every shared-leaf node is its coordinate. -/ +theorem node_eq_coordinate_of_leaf {h : ℕ} (r : VariablePosition h) + (hr : depth r = h) : node r = r.2.val := by + simp [node, hr] + +/-- Constructor-free shared-leaf threshold formula. -/ +theorem variableEntry_leaf_of_depth {h : ℕ} (r c : VariablePosition h) + (hr : depth r = h) (hc : depth c = h) : + variableEntry r c = decide (r.2.val ≤ c.2.val) := by + simp [variableEntry, hr, hc, node_eq_coordinate_of_leaf r hr, + node_eq_coordinate_of_leaf c hc] + +end Problem348.Construction + +end OAI diff --git a/lean/OAI/Combinatorics/MatrixRemoval/HostSampledPath.lean b/lean/OAI/Combinatorics/MatrixRemoval/HostSampledPath.lean new file mode 100644 index 0000000000000000000000000000000000000000..38326621f6e0476110c196339e7a7d47940e4b04 --- /dev/null +++ b/lean/OAI/Combinatorics/MatrixRemoval/HostSampledPath.lean @@ -0,0 +1,153 @@ +import OAI.Combinatorics.MatrixRemoval.Host +import OAI.Combinatorics.MatrixRemoval.SampledPath + +namespace OAI + +/-! +Concrete sampled-path role membership for the canonical host. +The input is one common leaf seed and arbitrary within-class offset seeds. +-/ +namespace Problem348.HostSampledPath + +open SampledPath + +/-- The variable-position sample, injected into the full host axis. -/ +def position (h i : ℕ) (hi : i ≤ h) (plus : Bool) + (z u : Fin (2 ^ h)) : Construction.Position h := + Sum.inr (Sum.inl (sample h i hi plus z u)) + +/-- A sampled dummy position. -/ +def dummy (h : ℕ) (u : Fin (2 ^ h)) : Construction.Position h := + Sum.inr (Sum.inr u) + +@[simp] theorem sample_atLevel (h i : ℕ) (hi : i ≤ h) (s : Bool) + (z u : Fin (2 ^ h)) : Construction.AtLevel i s (sample h i hi s z u) := by + constructor + · exact sample_depth h i hi s z u + · by_cases heq : i = h + · exact Or.inl heq + · right + cases s <;> + simp [Construction.plus, sample, classAt, heq] + +@[simp] theorem sample_hostNode (h i : ℕ) (hi : i ≤ h) (s : Bool) + (z u : Fin (2 ^ h)) : + Construction.node (sample h i hi s z u) = z.val / blockSize h i := + sample_node h i hi s z u + +@[simp] theorem position_shared_leaf (h : ℕ) (s t : Bool) + (z u v : Fin (2 ^ h)) : + position h h le_rfl s z u = position h h le_rfl t z v := by + exact congrArg (fun p : Construction.VariablePosition h => + (Sum.inr (Sum.inl p) : Construction.Position h)) + (sample_shared_leaf h s t z u v) + +/-- Encode the mode at the edge from depth `i` to depth `i+1`. -/ +def mode {h : ℕ} (i : Fin h) (k : Fin 6) : Construction.Mode h := + ⟨6 * i.val + k.val, by have := i.isLt; have := k.isLt; omega⟩ + +@[simp] theorem mode_level {h : ℕ} (i : Fin h) (k : Fin 6) : + Construction.level (mode i k) = i.val + 1 := by + have := k.isLt + unfold Construction.level mode + dsimp + omega + +@[simp] theorem mode_kind {h : ℕ} (i : Fin h) (k : Fin 6) : + Construction.kind (mode i k) = k.val := by + have := k.isLt + unfold Construction.kind mode + dsimp + omega + +def verticalKind : Bool → Fin 6 + | true => 0 + | false => 1 + +def horizontalKind : Bool → Bool → Fin 6 + | true, false => 2 + | true, true => 3 + | false, false => 4 + | false, true => 5 + +def vertical {h : ℕ} (i : Fin h) (s : Bool) : Construction.Mode h := + mode i (verticalKind s) +def horizontal {h : ℕ} (i : Fin h) (s d : Bool) : Construction.Mode h := + mode i (horizontalKind s d) + +def parity (n : ℕ) : Bool := decide (n % 2 = 1) + +@[simp] theorem parity_eq_false (n : ℕ) : parity n = false ↔ n % 2 = 0 := by + simp only [parity, decide_eq_false_iff_not] + omega + +@[simp] theorem parity_eq_true (n : ℕ) : parity n = true ↔ n % 2 = 1 := by + simp [parity] + + theorem vertical_plus_row_first {h : ℕ} (i : Fin h) (z u : Fin (2 ^ h)) : + Construction.rowRole (vertical i true) 0 + (position h (i.val + 1) (by omega) true z u) := by + simp [vertical, verticalKind, Construction.rowRole, position] + + theorem vertical_plus_row_second {h : ℕ} (i : Fin h) (z u : Fin (2 ^ h)) : + Construction.rowRole (vertical i true) 1 + (position h i.val (by omega) true z u) := by + simp [vertical, verticalKind, Construction.rowRole, position] + + theorem vertical_minus_row_first {h : ℕ} (i : Fin h) (z u : Fin (2 ^ h)) : + Construction.rowRole (vertical i false) 0 + (position h i.val (by omega) false z u) := by + simp [vertical, verticalKind, Construction.rowRole, position] + + theorem vertical_minus_row_second {h : ℕ} (i : Fin h) (z u : Fin (2 ^ h)) : + Construction.rowRole (vertical i false) 1 + (position h (i.val + 1) (by omega) false z u) := by + simp [vertical, verticalKind, Construction.rowRole, position] + + theorem vertical_col_first {h : ℕ} (i : Fin h) (s : Bool) (u : Fin (2 ^ h)) : + Construction.colRole (vertical i s) 0 (dummy h u) := by + cases s <;> simp [vertical, verticalKind, Construction.colRole, dummy] + + theorem vertical_col_second {h : ℕ} (i : Fin h) (s : Bool) (z u : Fin (2 ^ h)) : + Construction.colRole (vertical i s) 1 (position h i.val (by omega) s z u) := by + cases s <;> simp [vertical, verticalKind, Construction.colRole, position] + + theorem horizontal_row_second {h : ℕ} (i : Fin h) (s d : Bool) + (u : Fin (2 ^ h)) : Construction.rowRole (horizontal i s d) 1 (dummy h u) := by + cases s <;> cases d <;> simp [horizontal, horizontalKind, Construction.rowRole, dummy] + + theorem horizontal_row_first {h : ℕ} (i : Fin h) (s : Bool) + (z u : Fin (2 ^ h)) : + Construction.rowRole (horizontal i s (parity (z.val / blockSize h (i.val + 1)))) 0 + (position h (i.val + 1) (by omega) s z u) := by + have hp := Nat.mod_lt (z.val / blockSize h (i.val + 1)) (by decide : 0 < 2) + cases s <;> by_cases hd : (z.val / blockSize h (i.val + 1)) % 2 = 1 <;> + simp_all [horizontal, horizontalKind, Construction.rowRole, position, parity] + + theorem horizontal_plus_col_first {h : ℕ} (i : Fin h) (d : Bool) + (z u : Fin (2 ^ h)) : + Construction.colRole (horizontal i true d) 0 (position h i.val (by omega) true z u) := by + cases d <;> simp [horizontal, horizontalKind, Construction.colRole, position] + + theorem horizontal_plus_col_second {h : ℕ} (i : Fin h) (z u : Fin (2 ^ h)) : + Construction.colRole (horizontal i true (parity (z.val / blockSize h (i.val + 1)))) 1 + (position h (i.val + 1) (by omega) true z u) := by + have hp := Nat.mod_lt (z.val / blockSize h (i.val + 1)) (by decide : 0 < 2) + by_cases hd : (z.val / blockSize h (i.val + 1)) % 2 = 1 <;> + simp_all [horizontal, horizontalKind, Construction.colRole, position, parity] + + theorem horizontal_minus_col_first {h : ℕ} (i : Fin h) (z u : Fin (2 ^ h)) : + Construction.colRole (horizontal i false (parity (z.val / blockSize h (i.val + 1)))) 0 + (position h (i.val + 1) (by omega) false z u) := by + have hp := Nat.mod_lt (z.val / blockSize h (i.val + 1)) (by decide : 0 < 2) + by_cases hd : (z.val / blockSize h (i.val + 1)) % 2 = 1 <;> + simp_all [horizontal, horizontalKind, Construction.colRole, position, parity] + + theorem horizontal_minus_col_second {h : ℕ} (i : Fin h) (d : Bool) + (z u : Fin (2 ^ h)) : + Construction.colRole (horizontal i false d) 1 (position h i.val (by omega) false z u) := by + cases d <;> simp [horizontal, horizontalKind, Construction.colRole, position] + +end Problem348.HostSampledPath + +end OAI diff --git a/lean/OAI/Combinatorics/MatrixRemoval/HostSampledSelection.lean b/lean/OAI/Combinatorics/MatrixRemoval/HostSampledSelection.lean new file mode 100644 index 0000000000000000000000000000000000000000..9084d3ebb6c9da259b538ff070ff73f841cecd6f --- /dev/null +++ b/lean/OAI/Combinatorics/MatrixRemoval/HostSampledSelection.lean @@ -0,0 +1,226 @@ +import OAI.Combinatorics.MatrixRemoval.HostAnchorFrames +import OAI.Combinatorics.MatrixRemoval.HostSampledPath +import OAI.Combinatorics.MatrixRemoval.HostRootLeaf +import OAI.Combinatorics.MatrixRemoval.GuardedPath +import OAI.Combinatorics.MatrixRemoval.SamplingDistance + +namespace OAI + +/-! +# The concrete common-leaf selection in the canonical host + +The row/column enumerations are independent. `AxisConditions` records only the +order properties required of those enumerations; entries, role memberships, +root values, shared leaves, and the resulting guarded-path validity are proved +from the actual canonical host and the concrete sampled positions. +-/ + +noncomputable section +namespace Problem348.Construction.SampledSelection + +open HostSampledPath + +/-- The ten order facts used by the sampled-path construction. These are +separate from matrix entries and can be supplied by any correct enumeration +of the two recursively ordered axes. -/ +structure AxisConditions {h n : ℕ} (er ec : Position h ≃ Fin n) : Prop where + anchor_rows : ∀ (t : Mode h) (a : Fin (2 ^ h)), + StrictMono (fun u : Fin 64 => er (.inl (t, u, a))) + anchor_cols : ∀ (t : Mode h) (a : Fin (2 ^ h)), + StrictMono (fun u : Fin 64 => ec (.inl (t, u, a))) + anchor_before_rows : ∀ (t : Mode h) (u : Fin 64) (a : Fin (2 ^ h)) + (x : VariablePosition h ⊕ Fin (2 ^ h)), er (.inl (t, u, a)) < er (.inr x) + anchor_before_cols : ∀ (t : Mode h) (u : Fin 64) (a : Fin (2 ^ h)) + (x : VariablePosition h ⊕ Fin (2 ^ h)), ec (.inl (t, u, a)) < ec (.inr x) + variable_before_dummy : ∀ (x : VariablePosition h) (a : Fin (2 ^ h)), + er (.inr (.inl x)) < er (dummy h a) + dummy_before_variable : ∀ (x : VariablePosition h) (a : Fin (2 ^ h)), + ec (dummy h a) < ec (.inr (.inl x)) + row_plus : ∀ (i : Fin h) (z u : Fin (2 ^ h)), + er (position h (i.val + 1) (by omega) true z u) < + er (position h i.val (by omega) true z u) + row_minus : ∀ (i : Fin h) (z u : Fin (2 ^ h)), + er (position h i.val (by omega) false z u) < + er (position h (i.val + 1) (by omega) false z u) + col_plus : ∀ (i : Fin h) (z u : Fin (2 ^ h)), + ec (position h i.val (by omega) true z u) < + ec (position h (i.val + 1) (by omega) true z u) + col_minus : ∀ (i : Fin h) (z u : Fin (2 ^ h)), + ec (position h (i.val + 1) (by omega) false z u) < + ec (position h i.val (by omega) false z u) + +/-- A total path; indices beyond the tree depth repeat the common leaf. -/ +def path (h i : ℕ) (s : Bool) (z u : Fin (2 ^ h)) : Position h := + position h (min i h) (Nat.min_le_right i h) s z u + +@[simp] theorem path_of_le {h i : ℕ} (hi : i ≤ h) (s : Bool) + (z u : Fin (2 ^ h)) : path h i s z u = position h i hi s z u := by + simp [path, Nat.min_eq_left hi] + +/-- A harmless total extension of the edge index; it equals `i` for `i u) (fun _ => v) + (ha.anchor_rows t u) (ha.anchor_cols t v) + +/-- The actual selected path and four anchor frames at each edge. -/ +def selection {h n : ℕ} (hh : 1 ≤ h) (er ec : Position h ≃ Fin n) + (ha : AxisConditions er ec) (z u v : Fin (2 ^ h)) : GuardedPath.Selection n where + xp i := er (path h i true z u) + xm i := er (path h i false z u) + yp i := ec (path h i true z v) + ym i := ec (path h i false z v) + xd := er (dummy h u) + yd := ec (dummy h v) + vPlus i := frame er ec ha (vertical (edge hh i) true) u v + vMinus i := frame er ec ha (vertical (edge hh i) false) u v + wPlus i := frame er ec ha (horizontalMode hh z i true) u v + wMinus i := frame er ec ha (horizontalMode hh z i false) u v + +/-- For named body roles, all anchor/signature data follow from the host; +only the two body order inequalities need to be supplied. -/ +theorem frame_valid {h n : ℕ} (er ec : Position h ≃ Fin n) + (ha : AxisConditions er ec) (t : Mode h) (u v : Fin (2 ^ h)) + (r₀ r₁ c₀ c₁ : Position h) + (hr₀ : rowRole t 0 r₀) (hr₁ : rowRole t 1 r₁) + (hc₀ : colRole t 0 c₀) (hc₁ : colRole t 1 c₁) + (hrs : er r₀ < er r₁) (hcs : ec c₀ < ec c₁) : + (frame er ec ha t u v).Valid (SelectedAnchor.matrix er ec) + (er r₀) (er r₁) (ec c₀) (ec c₁) := by + apply SelectedAnchor.frame_valid er ec t (fun _ => u) (fun _ => v) + (ha.anchor_rows t u) (ha.anchor_cols t v) r₀ r₁ c₀ c₁ hr₀ hr₁ hc₀ hc₁ + · intro j + cases r₀ with + | inl a => simp [rowRole] at hr₀ + | inr x => exact ha.anchor_before_rows t j u x + · exact hrs + · intro j + cases c₀ with + | inl a => simp [colRole] at hc₀ + | inr x => exact ha.anchor_before_cols t j v x + · exact hcs + +theorem vertical_plus_valid {h n : ℕ} (er ec : Position h ≃ Fin n) + (ha : AxisConditions er ec) (i : Fin h) (z u v : Fin (2 ^ h)) : + (frame er ec ha (vertical i true) u v).Valid (SelectedAnchor.matrix er ec) + (er (position h (i.val + 1) (by omega) true z u)) + (er (position h i.val (by omega) true z u)) + (ec (dummy h v)) (ec (position h i.val (by omega) true z v)) := by + apply frame_valid er ec ha + · exact vertical_plus_row_first i z u + · exact vertical_plus_row_second i z u + · exact vertical_col_first i true v + · exact vertical_col_second i true z v + · exact ha.row_plus i z u + · exact ha.dummy_before_variable _ v + +theorem vertical_minus_valid {h n : ℕ} (er ec : Position h ≃ Fin n) + (ha : AxisConditions er ec) (i : Fin h) (z u v : Fin (2 ^ h)) : + (frame er ec ha (vertical i false) u v).Valid (SelectedAnchor.matrix er ec) + (er (position h i.val (by omega) false z u)) + (er (position h (i.val + 1) (by omega) false z u)) + (ec (dummy h v)) (ec (position h i.val (by omega) false z v)) := by + apply frame_valid er ec ha + · exact vertical_minus_row_first i z u + · exact vertical_minus_row_second i z u + · exact vertical_col_first i false v + · exact vertical_col_second i false z v + · exact ha.row_minus i z u + · exact ha.dummy_before_variable _ v + +theorem horizontal_plus_valid {h n : ℕ} (er ec : Position h ≃ Fin n) + (ha : AxisConditions er ec) (i : Fin h) (z u v : Fin (2 ^ h)) : + (frame er ec ha + (horizontal i true (parity (z.val / SampledPath.blockSize h (i.val + 1)))) u v).Valid + (SelectedAnchor.matrix er ec) + (er (position h (i.val + 1) (by omega) true z u)) (er (dummy h u)) + (ec (position h i.val (by omega) true z v)) + (ec (position h (i.val + 1) (by omega) true z v)) := by + apply frame_valid er ec ha + · exact horizontal_row_first i true z u + · exact horizontal_row_second i true _ u + · exact horizontal_plus_col_first i _ z v + · exact horizontal_plus_col_second i z v + · exact ha.variable_before_dummy _ u + · exact ha.col_plus i z v + +theorem horizontal_minus_valid {h n : ℕ} (er ec : Position h ≃ Fin n) + (ha : AxisConditions er ec) (i : Fin h) (z u v : Fin (2 ^ h)) : + (frame er ec ha + (horizontal i false (parity (z.val / SampledPath.blockSize h (i.val + 1)))) u v).Valid + (SelectedAnchor.matrix er ec) + (er (position h (i.val + 1) (by omega) false z u)) (er (dummy h u)) + (ec (position h (i.val + 1) (by omega) false z v)) + (ec (position h i.val (by omega) false z v)) := by + apply frame_valid er ec ha + · exact horizontal_row_first i false z u + · exact horizontal_row_second i false _ u + · exact horizontal_minus_col_first i z v + · exact horizontal_minus_col_second i _ z v + · exact ha.variable_before_dummy _ u + · exact ha.col_minus i z v + +/-- Every concrete three-seed selection satisfies all guarded-path hypotheses. +Only the axis order laws were assumed; the entire original-matrix certificate +is derived from the exact host entries and the sampled common-leaf path. -/ +theorem selection_valid {h n : ℕ} (hh : 1 ≤ h) (er ec : Position h ≃ Fin n) + (ha : AxisConditions er ec) (z u v : Fin (2 ^ h)) : + (selection hh er ec ha z u v).Valid (SelectedAnchor.matrix er ec) h := by + constructor + · simp only [selection, SelectedAnchor.matrix_apply, + path_of_le (Nat.zero_le h)] + exact variableEntry_root_plus_of_atLevel hh _ _ + (sample_atLevel h 0 (Nat.zero_le h) true z u) + (sample_atLevel h 0 (Nat.zero_le h) true z v) + · simp only [selection, SelectedAnchor.matrix_apply, + path_of_le (Nat.zero_le h)] + exact variableEntry_root_minus_of_atLevel hh _ _ + (sample_atLevel h 0 (Nat.zero_le h) false z u) + (sample_atLevel h 0 (Nat.zero_le h) false z v) + · intro i hi + simp [selection, SelectedAnchor.matrix_apply, path, position, dummy, host] + · intro i hi + simp [selection, SelectedAnchor.matrix_apply, path, position, dummy, host] + · simp only [selection, path_of_le (Nat.le_refl h)] + exact congrArg er (position_shared_leaf h true false z u u) + · simp only [selection, path_of_le (Nat.le_refl h)] + exact congrArg ec (position_shared_leaf h true false z v v) + · intro i hi + simpa only [selection, edge_of_lt hh hi, path_of_le hi.le, + path_of_le (show i + 1 ≤ h by omega)] using + vertical_plus_valid er ec ha ⟨i, hi⟩ z u v + · intro i hi + simpa only [selection, edge_of_lt hh hi, path_of_le hi.le, + path_of_le (show i + 1 ≤ h by omega)] using + vertical_minus_valid er ec ha ⟨i, hi⟩ z u v + · intro i hi + simpa only [selection, horizontalMode, edge_of_lt hh hi, path_of_le hi.le, + path_of_le (show i + 1 ≤ h by omega)] using + horizontal_plus_valid er ec ha ⟨i, hi⟩ z u v + · intro i hi + simpa only [selection, horizontalMode, edge_of_lt hh hi, path_of_le hi.le, + path_of_le (show i + 1 ≤ h by omega)] using + horizontal_minus_valid er ec ha ⟨i, hi⟩ z u v + +end Problem348.Construction.SampledSelection + +end + +end OAI diff --git a/lean/OAI/Combinatorics/MatrixRemoval/HostSampling.lean b/lean/OAI/Combinatorics/MatrixRemoval/HostSampling.lean new file mode 100644 index 0000000000000000000000000000000000000000..50a3cc3d94405af29de69a20541a20eef2acb796 --- /dev/null +++ b/lean/OAI/Combinatorics/MatrixRemoval/HostSampling.lean @@ -0,0 +1,158 @@ +import OAI.Combinatorics.MatrixRemoval.Host +import OAI.Combinatorics.MatrixRemoval.ThreeSeedSampling + +namespace OAI + +/-! +The canonical host projections and protected-cell sampling bridge. +Three seeds give the cellwise sampling bound. +-/ + +namespace Problem348.Construction.HostSampling + +open Problem348.TreeSampling + +/-- Anchor and dummy positions use their independent axis seed. -/ +def sampleDepth {h : ℕ} : Position h → Option (Fin (h + 1)) + | Sum.inl _ => none + | Sum.inr (Sum.inl v) => some ⟨depth v, Nat.lt_succ_of_le (depth_le v)⟩ + | Sum.inr (Sum.inr _) => none + +/-- The coordinate within the size-`2^h` class of a raw host position. -/ +def offset {h : ℕ} : Position h → Fin (2 ^ h) + | Sum.inl (_, _, x) => x + | Sum.inr (Sum.inl v) => v.2 + | Sum.inr (Sum.inr x) => x + +/-- The selected coordinate in the class containing a given position. -/ +def coordinate {h : ℕ} (z u : Fin (2 ^ h)) : Position h → Fin (2 ^ h) + | Sum.inl _ => u + | Sum.inr (Sum.inl v) => atLevel h (depth v) (depth_le v) z u + | Sum.inr (Sum.inr _) => u + +/-- Whether both positions of a fixed raw cell are selected. -/ +def Selected {h : ℕ} (s : Seeds (2 ^ h)) (r c : Position h) : Prop := + (coordinate s.1 s.2.1 r, coordinate s.1 s.2.2 c) = (offset r, offset c) + +instance {h : ℕ} (s : Seeds (2 ^ h)) (r c : Position h) : + Decidable (Selected s r c) := inferInstanceAs (Decidable (_ = _)) + +/-- Protected cells: at least one anchor/dummy position, or two root positions. -/ +def Protected {h : ℕ} (r c : Position h) : Prop := + sampleDepth r = none ∨ sampleDepth c = none ∨ + sampleDepth r = some ⟨0, by omega⟩ ∧ sampleDepth c = some ⟨0, by omega⟩ + +@[simp] theorem protected_anchor_left {h : ℕ} (a : AnchorPosition h) + (c : Position h) : Protected (Sum.inl a) c := by + simp [Protected, sampleDepth] + +@[simp] theorem protected_anchor_right {h : ℕ} (r : Position h) + (a : AnchorPosition h) : Protected r (Sum.inl a) := by + simp [Protected, sampleDepth] + +@[simp] theorem protected_dummy_left {h : ℕ} (x : Fin (2 ^ h)) + (c : Position h) : Protected (Sum.inr (Sum.inr x)) c := by + simp [Protected, sampleDepth] + +@[simp] theorem protected_dummy_right {h : ℕ} (r : Position h) + (x : Fin (2 ^ h)) : Protected r (Sum.inr (Sum.inr x)) := by + simp [Protected, sampleDepth] + + theorem protected_roots {h : ℕ} (v w : VariablePosition h) + (hv : depth v = 0) (hw : depth w = 0) : + Protected (Sum.inr (Sum.inl v)) (Sum.inr (Sum.inl w)) := by + simp [Protected, sampleDepth, hv, hw] + +/-- Concrete host protected-cell events all have exactly `2^h` seed preimages. -/ +theorem selected_fiber_card {h : ℕ} (r c : Position h) (hp : Protected r c) : + Fintype.card {s : Seeds (2 ^ h) // Selected s r c} = 2 ^ h := by + rcases r with ⟨t, u, x⟩ | (v | x) <;> + rcases c with ⟨t', u', y⟩ | (w | y) + · exact card_both_fiber x y + · exact card_atLevel_column_fiber h (depth w) (depth_le w) x w.2 + · exact card_both_fiber x y + · exact card_atLevel_row_fiber h (depth v) (depth_le v) v.2 y + · have hd : depth v = 0 ∧ depth w = 0 := by + simpa [Protected, sampleDepth, Fin.ext_iff] using hp + have he : ∀ s : Seeds (2 ^ h), Selected s (Sum.inr (Sum.inl v)) + (Sum.inr (Sum.inl w)) ↔ s.2 = (v.2, w.2) := by + intro s + simp [Selected, coordinate, offset, hd.1, hd.2] + calc + _ = Fintype.card {s : Seeds (2 ^ h) // s.2 = (v.2, w.2)} := + Fintype.card_congr (Equiv.subtypeEquivRight he) + _ = _ := card_both_fiber v.2 w.2 + · exact card_atLevel_row_fiber h (depth v) (depth_le v) v.2 y + · exact card_both_fiber x y + · exact card_atLevel_column_fiber h (depth w) (depth_le w) x w.2 + · exact card_both_fiber x y + +/-- Fraction-free marginal equality, directly consumable by finite avoidance. -/ +theorem selected_fiber_card_mul {h : ℕ} (r c : Position h) (hp : Protected r c) : + Fintype.card {s : Seeds (2 ^ h) // Selected s r c} * (2 ^ h) ^ 2 = + Fintype.card (Seeds (2 ^ h)) := by + rw [selected_fiber_card r c hp, card_seeds] + ring + +/-- The same marginal in the `Finset.filter` form used by the union bound. -/ +theorem selected_filter_card {h : ℕ} (r c : Position h) (hp : Protected r c) : + (Finset.univ.filter fun s : Seeds (2 ^ h) => Selected s r c).card = 2 ^ h := by + simpa only [Fintype.card_subtype] using selected_fiber_card r c hp + +/-- A subset of the protected event has at most the same frequency. -/ +theorem protected_event_card_le {h : ℕ} (r c : Position h) + (event : Finset (Seeds (2 ^ h))) + (hevent : ∀ s ∈ event, Protected r c ∧ Selected s r c) : + event.card ≤ 2 ^ h := by + classical + rcases event.eq_empty_or_nonempty with hempty | ⟨s, hs⟩ + · simp [hempty] + · have hp := (hevent s hs).1 + calc + event.card ≤ (Finset.univ.filter fun s => Selected s r c).card := by + apply Finset.card_le_card + intro t ht + simp only [Finset.mem_filter, Finset.mem_univ, true_and] + exact (hevent t ht).2 + _ = _ := selected_filter_card r c hp + +/-- Guard-cell containment in the protected selected-cell event implies +the union-bound frequency estimate for each fixed raw cell. -/ +theorem guard_frequency {h : ℕ} + (guards : Seeds (2 ^ h) → Finset (Position h × Position h)) + (hguards : ∀ s rc, rc ∈ guards s → + Protected rc.1 rc.2 ∧ Selected s rc.1 rc.2) + (rc : Position h × Position h) : + (Finset.univ.filter fun s => rc ∈ guards s).card * (2 ^ h) ^ 2 ≤ + Fintype.card (Seeds (2 ^ h)) := by + classical + have hb := protected_event_card_le rc.1 rc.2 + (Finset.univ.filter fun s => rc ∈ guards s) + (fun s hs => hguards s rc (Finset.mem_filter.mp hs).2) + rw [card_seeds] + calc + _ ≤ 2 ^ h * (2 ^ h) ^ 2 := Nat.mul_le_mul_right _ hb + _ = (2 ^ h) ^ 3 := by ring + +/-- Independent row and column reindexings preserve the protected-cell bound. -/ +theorem transported_guard_frequency {h n : ℕ} + (row col : Position h ≃ Fin n) + (guards : Seeds (2 ^ h) → Finset (Fin n × Fin n)) + (hguards : ∀ s rc, rc ∈ guards s → + Protected (row.symm rc.1) (col.symm rc.2) ∧ + Selected s (row.symm rc.1) (col.symm rc.2)) + (rc : Fin n × Fin n) : + (Finset.univ.filter fun s => rc ∈ guards s).card * (2 ^ h) ^ 2 ≤ + Fintype.card (Seeds (2 ^ h)) := by + classical + have hb := protected_event_card_le (row.symm rc.1) (col.symm rc.2) + (Finset.univ.filter fun s => rc ∈ guards s) + (fun s hs => hguards s rc (Finset.mem_filter.mp hs).2) + rw [card_seeds] + calc + _ ≤ 2 ^ h * (2 ^ h) ^ 2 := Nat.mul_le_mul_right _ hb + _ = (2 ^ h) ^ 3 := by ring + +end Problem348.Construction.HostSampling + +end OAI diff --git a/lean/OAI/Combinatorics/MatrixRemoval/HostSamplingCompatibility.lean b/lean/OAI/Combinatorics/MatrixRemoval/HostSamplingCompatibility.lean new file mode 100644 index 0000000000000000000000000000000000000000..497e4dd47d72eb33911f72e8513fc692cd893941 --- /dev/null +++ b/lean/OAI/Combinatorics/MatrixRemoval/HostSamplingCompatibility.lean @@ -0,0 +1,126 @@ +import OAI.Combinatorics.MatrixRemoval.HostSampling +import OAI.Combinatorics.MatrixRemoval.HostSampledPath +import OAI.Combinatorics.MatrixRemoval.GuardContainment + +namespace OAI + +/-! +# Compatibility of the path sampler and protected-cell sampler + +The quotient/remainder formula and `finProdFinEquiv` select the same +coordinate, identifying path samples with the uniform-fiber sampler. +-/ + +namespace Problem348.TreeSampling + +/-- The equivalence-based and arithmetic mixers select identical coordinates. -/ +theorem atLevel_eq_mixFin (h i : ℕ) (hi : i ≤ h) (z u : Fin (2 ^ h)) : + atLevel h i hi z u = SampledPath.mixFin h i hi z u := by + apply Fin.ext + change u.val % (2 ^ (h - i)) + (2 ^ (h - i)) * (z.val / (2 ^ (h - i))) = + z.val / (2 ^ (h - i)) * (2 ^ (h - i)) + u.val % (2 ^ (h - i)) + ac_rfl + +end Problem348.TreeSampling + +namespace Problem348.Construction.HostSampling + +/-- An actual sampled variable path point is selected by the marginal sampler. -/ +theorem coordinate_path_position (h i : ℕ) (hi : i ≤ h) (sign : Bool) + (z u : Fin (2 ^ h)) : + coordinate z u (HostSampledPath.position h i hi sign z u) = + offset (HostSampledPath.position h i hi sign z u) := by + change TreeSampling.atLevel h (depth (SampledPath.sample h i hi sign z u)) + (depth_le _) z u = + (SampledPath.sample h i hi sign z u).2 + have hd : depth (SampledPath.sample h i hi sign z u) = i := + (HostSampledPath.sample_atLevel h i hi sign z u).1 + simp only [hd] + exact TreeSampling.atLevel_eq_mixFin h i hi z u + +/-- Anchor representatives use the corresponding independent axis seed. -/ +@[simp] theorem coordinate_anchor (h : ℕ) (t : Mode h) (v : Fin 64) + (z u : Fin (2 ^ h)) : + coordinate z u (Sum.inl (t, v, u)) = offset (Sum.inl (t, v, u)) := rfl + +/-- The selected dummy position uses the same independent axis seed. -/ +@[simp] theorem coordinate_path_dummy (h : ℕ) (z u : Fin (2 ^ h)) : + coordinate z u (HostSampledPath.dummy h u) = + offset (HostSampledPath.dummy h u) := rfl + +/-- Every pair of path samples, not just the protected pairs, is selected. +The two axes use different offset seeds but the same leaf seed. -/ +theorem selected_path_positions (h i j : ℕ) (hi : i ≤ h) (hj : j ≤ h) + (s t : Bool) (z u v : Fin (2 ^ h)) : + Selected (z, u, v) (HostSampledPath.position h i hi s z u) + (HostSampledPath.position h j hj t z v) := by + exact Prod.ext (coordinate_path_position h i hi s z u) + (coordinate_path_position h j hj t z v) + +/-- A path-row / selected-anchor-column pair is a selected protected cell. -/ +theorem protected_selected_path_anchor (h i : ℕ) (hi : i ≤ h) (sign : Bool) + (t : Mode h) (a : Fin 64) (z u v : Fin (2 ^ h)) : + Protected (HostSampledPath.position h i hi sign z u) (Sum.inl (t, a, v)) ∧ + Selected (z, u, v) (HostSampledPath.position h i hi sign z u) + (Sum.inl (t, a, v)) := by + exact ⟨protected_anchor_right _ _, + Prod.ext (coordinate_path_position h i hi sign z u) rfl⟩ + +/-- A selected-anchor-row / path-column pair is a selected protected cell. -/ +theorem protected_selected_anchor_path (h i : ℕ) (hi : i ≤ h) (sign : Bool) + (t : Mode h) (a : Fin 64) (z u v : Fin (2 ^ h)) : + Protected (Sum.inl (t, a, u)) (HostSampledPath.position h i hi sign z v) ∧ + Selected (z, u, v) (Sum.inl (t, a, u)) + (HostSampledPath.position h i hi sign z v) := by + exact ⟨protected_anchor_left _ _, + Prod.ext rfl (coordinate_path_position h i hi sign z v)⟩ + +/-- Direct row-field adapter for the geometric guarded-path certificate. -/ +theorem rowChosen_path {h n : ℕ} (er : Position h ≃ Fin n) + (i : ℕ) (hi : i ≤ h) (sign : Bool) (s : TreeSampling.Seeds (2 ^ h)) : + RowChosen er s (er (HostSampledPath.position h i hi sign s.1 s.2.1)) := by + simp only [RowChosen, Equiv.symm_apply_apply] + exact coordinate_path_position h i hi sign s.1 s.2.1 + +/-- Direct column-field adapter for the geometric guarded-path certificate. -/ +theorem colChosen_path {h n : ℕ} (ec : Position h ≃ Fin n) + (i : ℕ) (hi : i ≤ h) (sign : Bool) (s : TreeSampling.Seeds (2 ^ h)) : + ColChosen ec s (ec (HostSampledPath.position h i hi sign s.1 s.2.2)) := by + simp only [ColChosen, Equiv.symm_apply_apply] + exact coordinate_path_position h i hi sign s.1 s.2.2 + +@[simp] theorem rowChosen_path_dummy {h n : ℕ} (er : Position h ≃ Fin n) + (s : TreeSampling.Seeds (2 ^ h)) : + RowChosen er s (er (HostSampledPath.dummy h s.2.1)) := by + simp only [RowChosen, Equiv.symm_apply_apply] + rfl + +@[simp] theorem colChosen_path_dummy {h n : ℕ} (ec : Position h ≃ Fin n) + (s : TreeSampling.Seeds (2 ^ h)) : + ColChosen ec s (ec (HostSampledPath.dummy h s.2.2)) := by + simp only [ColChosen, Equiv.symm_apply_apply] + rfl + +@[simp] theorem rowChosen_path_anchor {h n : ℕ} (er : Position h ≃ Fin n) + (s : TreeSampling.Seeds (2 ^ h)) (t : Mode h) (a : Fin 64) : + RowChosen er s (er (Sum.inl (t, a, s.2.1))) := by + simp only [RowChosen, Equiv.symm_apply_apply] + rfl + +@[simp] theorem colChosen_path_anchor {h n : ℕ} (ec : Position h ≃ Fin n) + (s : TreeSampling.Seeds (2 ^ h)) (t : Mode h) (a : Fin 64) : + ColChosen ec s (ec (Sum.inl (t, a, s.2.2))) := by + simp only [ColChosen, Equiv.symm_apply_apply] + rfl + +/-- Both sampled roots belong to protected classes, regardless of sign. -/ +theorem protected_path_roots (h : ℕ) (s t : Bool) (z u v : Fin (2 ^ h)) : + Protected (HostSampledPath.position h 0 (Nat.zero_le h) s z u) + (HostSampledPath.position h 0 (Nat.zero_le h) t z v) := by + apply protected_roots + · exact (HostSampledPath.sample_atLevel h 0 (Nat.zero_le h) s z u).1 + · exact (HostSampledPath.sample_atLevel h 0 (Nat.zero_le h) t z v).1 + +end Problem348.Construction.HostSampling + +end OAI diff --git a/lean/OAI/Combinatorics/MatrixRemoval/HostTreeOrder.lean b/lean/OAI/Combinatorics/MatrixRemoval/HostTreeOrder.lean new file mode 100644 index 0000000000000000000000000000000000000000..5b3144ed23658ba7d7c209142daa303547948624 --- /dev/null +++ b/lean/OAI/Combinatorics/MatrixRemoval/HostTreeOrder.lean @@ -0,0 +1,97 @@ +import OAI.Combinatorics.MatrixRemoval.Host +import OAI.Combinatorics.MatrixRemoval.TreePositions + +namespace OAI + +/-! +Comparison lemmas for the concrete depth-first tree orders used in +mode localization. +-/ + +namespace Problem348.Construction + +open TreePositions + +theorem eq_plusPos_of_atLevel {h i : ℕ} {v : VariablePosition h} + (hv : AtLevel i true v) : + v = TreePositions.plusPos i (hv.1 ▸ depth_le v) v.2 := by + apply Prod.ext + · apply Fin.ext + have hc := v.1.isLt + obtain ⟨hd, hs⟩ := hv + simp only [depth] at hd + change v.1.val = 2 * i + rcases hs with hi | hs + · omega + · simp only [plus, decide_eq_true_eq] at hs + omega + · rfl + +theorem eq_minusPos_of_atLevel {h i : ℕ} {v : VariablePosition h} + (hv : AtLevel i false v) : + v = TreePositions.minusPos i (hv.1 ▸ depth_le v) v.2 := by + apply Prod.ext + · apply Fin.ext + have hc := v.1.isLt + obtain ⟨hd, hs⟩ := hv + simp only [depth] at hd + change v.1.val = if i = h then 2 * h else 2 * i + 1 + split_ifs with hi + · omega + · rcases hs with hs | hs + · exact (hi hs).elim + · simp only [plus, decide_eq_false_iff_not] at hs + omega + · rfl + +theorem node_eq_level_node {h i : ℕ} {v : VariablePosition h} + (hv : depth v = i) : node v = TreePositions.node i v.2 := by + simp [node, TreePositions.node, hv] + +/-- Row plus child precedes row plus parent exactly for the stated parent-node inequality. -/ +theorem row_plus_lt_iff {h i : ℕ} {child parent : VariablePosition h} + (hc : AtLevel (i + 1) true child) (hp : AtLevel i true parent) : + TreePositions.rowKey h child < TreePositions.rowKey h parent ↔ + node child / 2 ≤ node parent := by + have hi : i < h := by have := hc.1 ▸ depth_le child; omega + have hn₁ := node_eq_level_node hc.1 + have hn₂ := node_eq_level_node hp.1 + rw [hn₁, hn₂, eq_plusPos_of_atLevel hc, eq_plusPos_of_atLevel hp] + exact TreePositions.row_plus_child_lt_parent hi child.2 parent.2 + +/-- Row minus parent precedes row minus child exactly for the parent-node inequality. -/ +theorem row_minus_lt_iff {h i : ℕ} {child parent : VariablePosition h} + (hc : AtLevel (i + 1) false child) (hp : AtLevel i false parent) : + TreePositions.rowKey h parent < TreePositions.rowKey h child ↔ + node parent ≤ node child / 2 := by + have hi : i < h := by have := hc.1 ▸ depth_le child; omega + have hn₁ := node_eq_level_node hc.1 + have hn₂ := node_eq_level_node hp.1 + rw [hn₁, hn₂, eq_minusPos_of_atLevel hc, eq_minusPos_of_atLevel hp] + exact TreePositions.row_minus_parent_lt_child hi child.2 parent.2 + +/-- Column plus parent precedes column plus child exactly for the parent-node inequality. -/ +theorem column_plus_lt_iff {h i : ℕ} {child parent : VariablePosition h} + (hc : AtLevel (i + 1) true child) (hp : AtLevel i true parent) : + TreePositions.columnKey h parent < TreePositions.columnKey h child ↔ + node parent ≤ node child / 2 := by + have hi : i < h := by have := hc.1 ▸ depth_le child; omega + have hn₁ := node_eq_level_node hc.1 + have hn₂ := node_eq_level_node hp.1 + rw [hn₁, hn₂, eq_plusPos_of_atLevel hc, eq_plusPos_of_atLevel hp] + exact TreePositions.column_plus_parent_lt_child hi child.2 parent.2 + +/-- Column minus child precedes column minus parent exactly for the parent-node inequality. -/ +theorem column_minus_lt_iff {h i : ℕ} {child parent : VariablePosition h} + (hc : AtLevel (i + 1) false child) (hp : AtLevel i false parent) : + TreePositions.columnKey h child < TreePositions.columnKey h parent ↔ + node child / 2 ≤ node parent := by + have hi : i < h := by have := hc.1 ▸ depth_le child; omega + have hn₁ := node_eq_level_node hc.1 + have hn₂ := node_eq_level_node hp.1 + rw [hn₁, hn₂, eq_minusPos_of_atLevel hc, eq_minusPos_of_atLevel hp] + exact TreePositions.column_minus_child_lt_parent hi child.2 parent.2 + +end Problem348.Construction + +end OAI diff --git a/lean/OAI/Combinatorics/MatrixRemoval/HostTwins.lean b/lean/OAI/Combinatorics/MatrixRemoval/HostTwins.lean new file mode 100644 index 0000000000000000000000000000000000000000..be06931781e94eb0848b9a4e5680f5ae9d207cae --- /dev/null +++ b/lean/OAI/Combinatorics/MatrixRemoval/HostTwins.lean @@ -0,0 +1,113 @@ +import OAI.Combinatorics.MatrixRemoval.Host + +namespace OAI + +/-! +Concrete twin-position facts for anchor rigidity in the flat-class host. +-/ + +namespace Problem348.Construction + +/-- Changing the representative inside an anchor row group changes no entry. -/ +theorem host_anchor_row_twin {h : ℕ} (t : Mode h) (u : Fin 64) + (x y : Fin (2 ^ h)) (c : Position h) : + host (Sum.inl (t,u,x)) c = host (Sum.inl (t,u,y)) c := by + rcases c with a | (v | d) <;> rfl + +/-- Changing the representative inside an anchor column group changes no entry. -/ +theorem host_anchor_column_twin {h : ℕ} (t : Mode h) (v : Fin 64) + (x y : Fin (2 ^ h)) (r : Position h) : + host r (Sum.inl (t,v,x)) = host r (Sum.inl (t,v,y)) := by + rcases r with a | (v | d) <;> rfl + +/-- All dummy rows, including their anchor incidences, have equal signatures. -/ +theorem host_dummy_row_twin {h : ℕ} (x y : Fin (2 ^ h)) (c : Position h) : + host (Sum.inr (Sum.inr x)) c = host (Sum.inr (Sum.inr y)) c := by + rcases c with a | (v | d) <;> rfl + +/-- All dummy columns, including their anchor incidences, have equal signatures. -/ +theorem host_dummy_column_twin {h : ℕ} (x y : Fin (2 ^ h)) (r : Position h) : + host r (Sum.inr (Sum.inr x)) = host r (Sum.inr (Sum.inr y)) := by + rcases r with a | (v | d) <;> rfl + +/-- The anchor-group label forgets only the coordinate within a group. -/ +def anchorGroup {h : ℕ} : Position h → Option (Mode h × Fin 64) + | Sum.inl (t,u,_) => some (t,u) + | Sum.inr _ => none + +/-- A group-label equality is enough to prove that two full row signatures agree. -/ +theorem host_rows_eq_of_anchorGroup {h : ℕ} {r r' : Position h} + {t : Mode h} {u : Fin 64} + (hr : anchorGroup r = some (t,u)) (hr' : anchorGroup r' = some (t,u)) : + ∀ c, host r c = host r' c := by + rcases r with ⟨t₁,u₁,x⟩ | r + · rcases r' with ⟨t₂,u₂,y⟩ | r' + · simp only [anchorGroup, Option.some.injEq, Prod.mk.injEq] at hr hr' + rcases hr with ⟨rfl,rfl⟩ + rcases hr' with ⟨rfl,rfl⟩ + exact host_anchor_row_twin _ _ x y + · simp [anchorGroup] at hr' + · simp [anchorGroup] at hr + +/-- The same group-label criterion on the column axis. -/ +theorem host_columns_eq_of_anchorGroup {h : ℕ} {c c' : Position h} + {t : Mode h} {u : Fin 64} + (hc : anchorGroup c = some (t,u)) (hc' : anchorGroup c' = some (t,u)) : + ∀ r, host r c = host r c' := by + rcases c with ⟨t₁,u₁,x⟩ | c + · rcases c' with ⟨t₂,u₂,y⟩ | c' + · simp only [anchorGroup, Option.some.injEq, Prod.mk.injEq] at hc hc' + rcases hc with ⟨rfl,rfl⟩ + rcases hc' with ⟨rfl,rfl⟩ + exact host_anchor_column_twin _ _ x y + · simp [anchorGroup] at hc' + · simp [anchorGroup] at hc + +/-- A true anchor--anchor entry forces the two modes to coincide. -/ +theorem mode_eq_of_host_anchor_true {h : ℕ} {t t' : Mode h} + {u v : Fin 64} {x y : Fin (2 ^ h)} + (he : host (Sum.inl (t,u,x)) (Sum.inl (t',v,y)) = true) : t = t' := by + by_contra hne + simp [host, hne] at he + +/-- In any one mode a non-anchor row can be one in at most one anchor group. -/ +theorem nonanchor_row_one_group_unique {h : ℕ} + (r : VariablePosition h ⊕ Fin (2 ^ h)) (t : Mode h) + (u v : Fin 64) (x y : Fin (2 ^ h)) + (hu : host (Sum.inr r) (Sum.inl (t,u,x)) = true) + (hv : host (Sum.inr r) (Sum.inl (t,v,y)) = true) : u = v := by + have hu' : (u.val = 0 ∧ rowRole t 0 (Sum.inr r)) ∨ + (u.val = 1 ∧ rowRole t 1 (Sum.inr r)) := by + simpa only [host, decide_eq_true_eq] using hu + have hv' : (v.val = 0 ∧ rowRole t 0 (Sum.inr r)) ∨ + (v.val = 1 ∧ rowRole t 1 (Sum.inr r)) := by + simpa only [host, decide_eq_true_eq] using hv + rcases hu' with ⟨hu₀, hr₀⟩ | ⟨hu₁, hr₁⟩ <;> + rcases hv' with ⟨hv₀, hs₀⟩ | ⟨hv₁, hs₁⟩ + · exact Fin.ext (hu₀.trans hv₀.symm) + · exact False.elim (rowRole_disjoint t (Sum.inr r) ⟨hr₀, hs₁⟩) + · exact False.elim (rowRole_disjoint t (Sum.inr r) ⟨hs₀, hr₁⟩) + · exact Fin.ext (hu₁.trans hv₁.symm) + +/-- In any one mode a non-anchor column can be one in at most one anchor group. -/ +theorem nonanchor_column_one_group_unique {h : ℕ} + (c : VariablePosition h ⊕ Fin (2 ^ h)) (t : Mode h) + (u v : Fin 64) (x y : Fin (2 ^ h)) + (hu : host (Sum.inl (t,u,x)) (Sum.inr c) = true) + (hv : host (Sum.inl (t,v,y)) (Sum.inr c) = true) : u = v := by + have hu' : (u.val = 0 ∧ colRole t 0 (Sum.inr c)) ∨ + (u.val = 1 ∧ colRole t 1 (Sum.inr c)) := by + simpa only [host, decide_eq_true_eq] using hu + have hv' : (v.val = 0 ∧ colRole t 0 (Sum.inr c)) ∨ + (v.val = 1 ∧ colRole t 1 (Sum.inr c)) := by + simpa only [host, decide_eq_true_eq] using hv + rcases hu' with ⟨hu₀, hr₀⟩ | ⟨hu₁, hr₁⟩ <;> + rcases hv' with ⟨hv₀, hs₀⟩ | ⟨hv₁, hs₁⟩ + · exact Fin.ext (hu₀.trans hv₀.symm) + · exact False.elim (colRole_disjoint t (Sum.inr c) ⟨hr₀, hs₁⟩) + · exact False.elim (colRole_disjoint t (Sum.inr c) ⟨hs₀, hr₁⟩) + · exact Fin.ext (hu₁.trans hv₁.symm) + +end Problem348.Construction + +end OAI diff --git a/lean/OAI/Combinatorics/MatrixRemoval/HostVerticalLocalization.lean b/lean/OAI/Combinatorics/MatrixRemoval/HostVerticalLocalization.lean new file mode 100644 index 0000000000000000000000000000000000000000..891ec2ac949e16d045fd98b3ab586f15b157e27f --- /dev/null +++ b/lean/OAI/Combinatorics/MatrixRemoval/HostVerticalLocalization.lean @@ -0,0 +1,127 @@ +import OAI.Combinatorics.MatrixRemoval.Host +import OAI.Combinatorics.MatrixRemoval.ModeLocalization + +namespace OAI + +/-! +# Vertical-mode localization for the concrete host + +The only additional input to the exclusion theorems is the node inequality +provided by the tree order. All entry values and role memberships follow +from the host definitions. +-/ + +namespace Problem348.Construction + +/-- Extend the variable node index to all positions. -/ +def positionNode {h : ℕ} : Position h → ℕ + | Sum.inr (Sum.inl v) => node v + | _ => 0 + +@[simp] theorem positionNode_variable {h : ℕ} (v : VariablePosition h) : + positionNode (Sum.inr (Sum.inl v)) = node v := rfl + +theorem variableEntry_same_level {h i : ℕ} {r c : VariablePosition h} + (s : Bool) (hr : AtLevel i s r) (hc : AtLevel i s c) : + variableEntry r c = + if i = h then decide (node r ≤ node c) + else if s then decide (node r ≤ node c) else decide (node r < node c) := by + rcases hr with ⟨hrd, hrs⟩ + rcases hc with ⟨hcd, hcs⟩ + by_cases hi : i = h + · simp [variableEntry, hrd, hcd, hi] + · have hrp : plus r = s := hrs.resolve_left hi + have hcp : plus c = s := hcs.resolve_left hi + simp [variableEntry, hrd, hcd, hi, hrp, hcp] + +theorem variableEntry_child_parent {h i : ℕ} {r c : VariablePosition h} + (s : Bool) (hr : AtLevel (i + 1) s r) (hc : AtLevel i s c) : + variableEntry r c = + if s then decide (node r / 2 ≤ node c) else decide (node r / 2 < node c) := by + rcases hr with ⟨hrd, hrs⟩ + rcases hc with ⟨hcd, hcs⟩ + have hih : i < h := by have := depth_le r; omega + have hcp : plus c = s := hcs.resolve_left (by omega) + have hsign : i + 1 = h ∨ plus r = s := hrs + simp [variableEntry, hrd, hcd, hih, hcp, hsign] + +theorem rowRole_vertical_variable {h : ℕ} {t : Mode h} {j : Fin 2} + {x : Position h} (hk : kind t < 2) (hx : rowRole t j x) : + ∃ v : VariablePosition h, x = Sum.inr (Sum.inl v) := by + rcases x with a | (v | d) + · simp [rowRole] at hx + · exact ⟨v, rfl⟩ + · simp [rowRole] at hx + omega + +theorem colRole_vertical_first_dummy {h : ℕ} {t : Mode h} + {x : Position h} (hk : kind t < 2) (hx : colRole t 0 x) : + ∃ d : Fin (2 ^ h), x = Sum.inr (Sum.inr d) := by + rcases x with a | (v | d) + · simp [colRole] at hx + · simp [colRole, hk] at hx + · exact ⟨d, rfl⟩ + +theorem colRole_vertical_second_variable {h : ℕ} {t : Mode h} + {x : Position h} (_hk : kind t < 2) (hx : colRole t 1 x) : + ∃ v : VariablePosition h, x = Sum.inr (Sum.inl v) := by + rcases x with a | (v | d) + · simp [colRole] at hx + · exact ⟨v, rfl⟩ + · simp [colRole] at hx + +/-- An actual vertical plus mode of the host cannot contain the body. -/ +theorem host_vertical_plus_not_body {h : ℕ} {t : Mode h} + (hk : kind t = 0) {r₀ r₁ c₀ c₁ : Position h} + (hr₀ : rowRole t 0 r₀) (hr₁ : rowRole t 1 r₁) + (hc₀ : colRole t 0 c₀) (hc₁ : colRole t 1 c₁) + (horder : positionNode r₀ / 2 ≤ positionNode r₁) : + ¬ ModeLocalization.IsP (host r₀ c₀) (host r₀ c₁) + (host r₁ c₀) (host r₁ c₁) := by + have hkt : kind t < 2 := by omega + obtain ⟨x, rfl⟩ := rowRole_vertical_variable hkt hr₀ + obtain ⟨y, rfl⟩ := rowRole_vertical_variable hkt hr₁ + obtain ⟨d, rfl⟩ := colRole_vertical_first_dummy hkt hc₀ + obtain ⟨z, rfl⟩ := colRole_vertical_second_variable hkt hc₁ + have hx : AtLevel (level t) true x := by simpa [rowRole, hk] using hr₀ + have hy : AtLevel (level t - 1) true y := by simpa [rowRole, hk] using hr₁ + have hz : AtLevel (level t - 1) true z := by simpa [colRole, hk] using hc₁ + have hl : level t - 1 + 1 = level t := by have := level_pos t; omega + have hparent := variableEntry_child_parent true (hl ▸ hx) hz + have hsame := variableEntry_same_level true hy hz + have hnotleaf : level t - 1 ≠ h := by + have := level_le t + have := level_pos t + omega + simpa [host, hparent, hsame, hnotleaf, positionNode] using + ModeLocalization.vPlus_not_isP (node x) (node y) (node z) horder + +/-- An actual vertical minus mode of the host cannot contain the body. -/ +theorem host_vertical_minus_not_body {h : ℕ} {t : Mode h} + (hk : kind t = 1) {r₀ r₁ c₀ c₁ : Position h} + (hr₀ : rowRole t 0 r₀) (hr₁ : rowRole t 1 r₁) + (hc₀ : colRole t 0 c₀) (hc₁ : colRole t 1 c₁) + (horder : positionNode r₀ ≤ positionNode r₁ / 2) : + ¬ ModeLocalization.IsP (host r₀ c₀) (host r₀ c₁) + (host r₁ c₀) (host r₁ c₁) := by + have hkt : kind t < 2 := by omega + obtain ⟨x, rfl⟩ := rowRole_vertical_variable hkt hr₀ + obtain ⟨y, rfl⟩ := rowRole_vertical_variable hkt hr₁ + obtain ⟨d, rfl⟩ := colRole_vertical_first_dummy hkt hc₀ + obtain ⟨z, rfl⟩ := colRole_vertical_second_variable hkt hc₁ + have hx : AtLevel (level t - 1) false x := by simpa [rowRole, hk] using hr₀ + have hy : AtLevel (level t) false y := by simpa [rowRole, hk] using hr₁ + have hz : AtLevel (level t - 1) false z := by simpa [colRole, hk] using hc₁ + have hl : level t - 1 + 1 = level t := by have := level_pos t; omega + have hparent := variableEntry_child_parent false (hl ▸ hy) hz + have hsame := variableEntry_same_level false hx hz + have hnotleaf : level t - 1 ≠ h := by + have := level_le t + have := level_pos t + omega + simpa [host, hparent, hsame, hnotleaf, positionNode] using + ModeLocalization.vMinus_not_isP (node y) (node x) (node z) horder + +end Problem348.Construction + +end OAI diff --git a/lean/OAI/Combinatorics/MatrixRemoval/Main.lean b/lean/OAI/Combinatorics/MatrixRemoval/Main.lean new file mode 100644 index 0000000000000000000000000000000000000000..7d8191a1cf2eb484501aad10c67e63d3975dcacc --- /dev/null +++ b/lean/OAI/Combinatorics/MatrixRemoval/Main.lean @@ -0,0 +1,40 @@ +import OAI.Combinatorics.MatrixRemoval.CanonicalCopyBound +import OAI.Combinatorics.MatrixRemoval.OrderedRepairDistance +import OAI.Combinatorics.MatrixRemoval.SequenceAssembly +import OAI.Combinatorics.MatrixRemoval.Consequence + +namespace OAI + +noncomputable section +namespace Problem348 + +theorem counterexample_sequence : + ∀ h : ℕ, 1 ≤ h → + let d : ℕ := 386 * h + 2 + let n : ℕ := d * 2 ^ h + ∃ A : BinaryMatrix n, + fixedDistance A ≥ 1 / ((d : ℝ) ^ 2) ∧ + (copyCount fixedH A : ℝ) / ((n : ℝ) ^ 132) ≤ + (1 / ((d : ℝ) ^ 2)) * (1 / ((2 : ℝ) ^ h)) := by + apply SequenceAssembly.counterexample_sequence_of_integer_bounds + intro h hh + refine ⟨Construction.hostMatrix (OrderedHost.rowIndex h) (OrderedHost.columnIndex h), ?_, + OrderedHost.canonical_copyCount_le h⟩ + intro B hfree + exact OrderedHost.hammingDistance_ge hh B hfree + +theorem no_polynomial_removal_bound : + ∀ c C : ℝ, 0 < c → 0 < C → + ∃ n : ℕ, 1 ≤ n ∧ + ∃ ε : ℝ, 0 < ε ∧ ε < 1 ∧ + ∃ A : BinaryMatrix n, + fixedDistance A ≥ ε ∧ + (copyCount fixedH A : ℝ) < + c * Real.rpow ε C * ((n : ℝ) ^ 132) := by + exact no_polynomial_removal_bound_of_sequence counterexample_sequence + +end Problem348 + +end + +end OAI diff --git a/lean/OAI/Combinatorics/MatrixRemoval/ModeIncidence.lean b/lean/OAI/Combinatorics/MatrixRemoval/ModeIncidence.lean new file mode 100644 index 0000000000000000000000000000000000000000..3475e70dcd8a2f877051b6d9cf4b0bc169ea91d2 --- /dev/null +++ b/lean/OAI/Combinatorics/MatrixRemoval/ModeIncidence.lean @@ -0,0 +1,232 @@ +import Mathlib + +namespace OAI + +/-! +Mode-incidence bounds. Active modes have levels 1 through h, while +variable positions have levels 0 through h. At level h the plus and minus +blocks coincide. +-/ + +universe uAlpha + +namespace Problem348.ModeIncidence + +inductive Kind where + | vertical (sign : Bool) + | horizontal (sign parity : Bool) + deriving DecidableEq, Fintype + +abbrev Mode := ℕ × Kind + +/-- Leaf positions have both sign names; other positions have their own sign. -/ +def hasSign (h depth : ℕ) (own requested : Bool) : Prop := + depth = h ∨ own = requested + +/-- Incidence with either row role of a mode. -/ +def rowIncident (h depth : ℕ) (sign parity : Bool) (t : Mode) : Prop := + 1 ≤ t.1 ∧ t.1 ≤ h ∧ + match t.2 with + | .vertical s => (depth = t.1 ∨ depth + 1 = t.1) ∧ hasSign h depth sign s + | .horizontal s p => depth = t.1 ∧ hasSign h depth sign s ∧ parity = p + +/-- Incidence with either column role of a mode. -/ +def colIncident (h depth : ℕ) (sign parity : Bool) (t : Mode) : Prop := + 1 ≤ t.1 ∧ t.1 ≤ h ∧ + match t.2 with + | .vertical s => depth + 1 = t.1 ∧ hasSign h depth sign s + | .horizontal s p => hasSign h depth sign s ∧ + (depth + 1 = t.1 ∨ (depth = t.1 ∧ parity = p)) + +/-- Three possible modes for an internal variable row. Boundary levels may +remove some of these modes. -/ +def internalRowModes (depth : ℕ) (sign parity : Bool) : Finset Mode := + {(depth, .vertical sign), (depth + 1, .vertical sign), + (depth, .horizontal sign parity)} + +/-- The four possible modes for a shared leaf row. -/ +def leafRowModes (h : ℕ) (parity : Bool) : Finset Mode := + {(h, .vertical false), (h, .vertical true), + (h, .horizontal false parity), (h, .horizontal true parity)} + +/-- Four possible modes for an internal variable column. -/ +def internalColModes (depth : ℕ) (sign parity : Bool) : Finset Mode := + {(depth + 1, .vertical sign), (depth + 1, .horizontal sign false), + (depth + 1, .horizontal sign true), (depth, .horizontal sign parity)} + +/-- The two possible modes for a shared leaf column. -/ +def leafColModes (h : ℕ) (parity : Bool) : Finset Mode := + {(h, .horizontal false parity), (h, .horizontal true parity)} + +theorem rowIncident_internal {h depth : ℕ} {sign parity : Bool} {t : Mode} + (hd : depth < h) (ht : rowIncident h depth sign parity t) : + t ∈ internalRowModes depth sign parity := by + rcases t with ⟨level, kind⟩ + rcases kind with s | ⟨s, p⟩ <;> dsimp [rowIncident] at ht + · rcases ht with ⟨_, _, hlevel, hsign⟩ + have hs : sign = s := hsign.resolve_left (Nat.ne_of_lt hd) + subst s + rcases hlevel with rfl | rfl <;> simp [internalRowModes] + · rcases ht with ⟨_, _, hlevel, hsign, hp⟩ + have hs : sign = s := hsign.resolve_left (Nat.ne_of_lt hd) + subst s + subst p + subst level + simp [internalRowModes] + +theorem rowIncident_leaf {h : ℕ} {sign parity : Bool} {t : Mode} + (ht : rowIncident h h sign parity t) : t ∈ leafRowModes h parity := by + rcases t with ⟨level, kind⟩ + rcases kind with s | ⟨s, p⟩ <;> dsimp [rowIncident] at ht + · rcases ht with ⟨_, hbound, hlevel, _⟩ + have heq : level = h := by omega + subst level + cases s <;> simp [leafRowModes] + · rcases ht with ⟨_, _, hlevel, _, hp⟩ + subst level + subst p + cases s <;> simp [leafRowModes] + +theorem colIncident_internal {h depth : ℕ} {sign parity : Bool} {t : Mode} + (hd : depth < h) (ht : colIncident h depth sign parity t) : + t ∈ internalColModes depth sign parity := by + rcases t with ⟨level, kind⟩ + rcases kind with s | ⟨s, p⟩ <;> dsimp [colIncident] at ht + · rcases ht with ⟨_, _, hlevel, hsign⟩ + have hs : sign = s := hsign.resolve_left (Nat.ne_of_lt hd) + subst s + subst level + simp [internalColModes] + · rcases ht with ⟨_, _, hsign, hlevel⟩ + have hs : sign = s := hsign.resolve_left (Nat.ne_of_lt hd) + subst s + rcases hlevel with hlevel | ⟨hlevel, hp⟩ + · subst level + cases p <;> simp [internalColModes] + · subst level + subst p + simp [internalColModes] + +theorem colIncident_leaf {h : ℕ} {sign parity : Bool} {t : Mode} + (ht : colIncident h h sign parity t) : t ∈ leafColModes h parity := by + rcases t with ⟨level, kind⟩ + rcases kind with s | ⟨s, p⟩ <;> dsimp [colIncident] at ht + · rcases ht with ⟨_, hbound, hlevel, _⟩ + omega + · rcases ht with ⟨_, hbound, _, hlevel⟩ + rcases hlevel with hbad | ⟨heq, hp⟩ + · omega + · subst level + subst p + cases s <;> simp [leafColModes] + +/-- An internal row participates in at most three modes. -/ +theorem card_internalRowModes_le (depth : ℕ) (sign parity : Bool) : + (internalRowModes depth sign parity).card ≤ 3 := by + simp only [internalRowModes] + exact Finset.card_insert_le _ _ |>.trans (Nat.succ_le_succ + (Finset.card_insert_le _ _ |>.trans (by simp))) + +/-- A leaf row participates in at most four modes. -/ +theorem card_leafRowModes_le (h : ℕ) (parity : Bool) : + (leafRowModes h parity).card ≤ 4 := by + simp [leafRowModes] + +/-- A variable column below the leaf level participates in at most four modes. -/ +theorem card_internalColModes_le (depth : ℕ) (sign parity : Bool) : + (internalColModes depth sign parity).card ≤ 4 := by + unfold internalColModes + exact Finset.card_insert_le _ _ |>.trans (Nat.succ_le_succ + (Finset.card_insert_le _ _ |>.trans (Nat.succ_le_succ + (Finset.card_insert_le _ _ |>.trans (by simp))))) + +/-- A leaf column participates in at most two modes. -/ +theorem card_leafColModes_le (h : ℕ) (parity : Bool) : + (leafColModes h parity).card ≤ 2 := by + simp [leafColModes] + +/-- Formulation independent of the particular finite enumeration of valid modes. -/ +theorem card_row_incident_le_four {h depth : ℕ} {sign parity : Bool} + (hd : depth ≤ h) (modes : Finset Mode) + (hmodes : ∀ t ∈ modes, rowIncident h depth sign parity t) : + modes.card ≤ 4 := by + rcases lt_or_eq_of_le hd with hd | rfl + · have hsub : modes ⊆ internalRowModes depth sign parity := by + intro t ht + exact rowIncident_internal hd (hmodes t ht) + exact (Finset.card_le_card hsub).trans + ((card_internalRowModes_le depth sign parity).trans (by decide)) + · have hsub : modes ⊆ leafRowModes depth parity := by + intro t ht + exact rowIncident_leaf (hmodes t ht) + exact (Finset.card_le_card hsub).trans (card_leafRowModes_le depth parity) + +/-- Formulation independent of the particular finite enumeration of valid modes. -/ +theorem card_col_incident_le_four {h depth : ℕ} {sign parity : Bool} + (hd : depth ≤ h) (modes : Finset Mode) + (hmodes : ∀ t ∈ modes, colIncident h depth sign parity t) : + modes.card ≤ 4 := by + rcases lt_or_eq_of_le hd with hd | rfl + · have hsub : modes ⊆ internalColModes depth sign parity := by + intro t ht + exact colIncident_internal hd (hmodes t ht) + exact (Finset.card_le_card hsub).trans (card_internalColModes_le depth sign parity) + · have hsub : modes ⊆ leafColModes depth parity := by + intro t ht + exact colIncident_leaf (hmodes t ht) + exact (Finset.card_le_card hsub).trans + ((card_leafColModes_le depth parity).trans (by decide)) + +/-- A generic sparse-trace transfer: at most one chosen one-entry per mode. -/ +theorem card_ones_le_of_mode_bound {α : Type uAlpha} [DecidableEq α] + (positions : Finset α) (mode : α → Mode) (entry : α → Bool) + (incident : Mode → Prop) (bound : ℕ) + (hbound : ∀ modes : Finset Mode, + (∀ t ∈ modes, incident t) → modes.card ≤ bound) + (hincident : ∀ x ∈ positions, entry x = true → incident (mode x)) + (hunique : ∀ x ∈ positions, ∀ y ∈ positions, + entry x = true → entry y = true → mode x = mode y → x = y) : + (positions.filter (fun x => entry x = true)).card ≤ bound := by + have hinjective : Set.InjOn mode + (↑(positions.filter (fun x => entry x = true)) : Set α) := by + intro x hx y hy heq + obtain ⟨hx, hxe⟩ := Finset.mem_filter.mp hx + obtain ⟨hy, hye⟩ := Finset.mem_filter.mp hy + exact hunique x hx y hy hxe hye heq + rw [← Finset.card_image_of_injOn hinjective] + apply hbound + intro t ht + obtain ⟨x, hx, rfl⟩ := Finset.mem_image.mp ht + obtain ⟨hx, hxe⟩ := Finset.mem_filter.mp hx + exact hincident x hx hxe + +/-- Against anchor representatives, a variable row has at most four ones, +provided one-entries in the same mode use the same representative. -/ +theorem card_row_ones_le_four {α : Type uAlpha} [DecidableEq α] + {h depth : ℕ} {sign parity : Bool} (hd : depth ≤ h) + (positions : Finset α) (mode : α → Mode) (entry : α → Bool) + (hincident : ∀ x ∈ positions, entry x = true → + rowIncident h depth sign parity (mode x)) + (hunique : ∀ x ∈ positions, ∀ y ∈ positions, + entry x = true → entry y = true → mode x = mode y → x = y) : + (positions.filter (fun x => entry x = true)).card ≤ 4 := + card_ones_le_of_mode_bound positions mode entry + (rowIncident h depth sign parity) 4 + (card_row_incident_le_four hd) hincident hunique + +/-- The symmetric sparse-trace statement for variable columns. -/ +theorem card_col_ones_le_four {α : Type uAlpha} [DecidableEq α] + {h depth : ℕ} {sign parity : Bool} (hd : depth ≤ h) + (positions : Finset α) (mode : α → Mode) (entry : α → Bool) + (hincident : ∀ x ∈ positions, entry x = true → + colIncident h depth sign parity (mode x)) + (hunique : ∀ x ∈ positions, ∀ y ∈ positions, + entry x = true → entry y = true → mode x = mode y → x = y) : + (positions.filter (fun x => entry x = true)).card ≤ 4 := + card_ones_le_of_mode_bound positions mode entry + (colIncident h depth sign parity) 4 + (card_col_incident_le_four hd) hincident hunique + +end Problem348.ModeIncidence + +end OAI diff --git a/lean/OAI/Combinatorics/MatrixRemoval/ModeLocalization.lean b/lean/OAI/Combinatorics/MatrixRemoval/ModeLocalization.lean new file mode 100644 index 0000000000000000000000000000000000000000..d6797293b0b4b6c2c6da8314254918155fb9ad46 --- /dev/null +++ b/lean/OAI/Combinatorics/MatrixRemoval/ModeLocalization.lean @@ -0,0 +1,72 @@ +import Mathlib + +namespace OAI + +/-! +# Localization of the four body modes + +The arithmetic case analysis assumes the stated order inequalities and entry +values, independently of the host-position encoding. +-/ + +namespace Problem348.ModeLocalization + +/-- The four entries of the body pattern, in row-major order. -/ +def IsP (a b c d : Bool) : Prop := + a = true ∧ b = false ∧ c = true ∧ d = true + +/-- Within either parity class, taking the parent preserves and reflects order. -/ +theorem le_iff_parent_le_of_same_parity {p q : ℕ} + (hparity : p % 2 = q % 2) : + p ≤ q ↔ p / 2 ≤ q / 2 := by + omega + +theorem eq_of_parent_eq_of_same_parity {p q : ℕ} + (hparity : p % 2 = q % 2) (hparent : p / 2 = q / 2) : p = q := by + omega + +/-- A `V_i^+` body cannot match `P`: its row order forces the zero to be one. -/ +theorem vPlus_not_isP (p a b : ℕ) (horder : p / 2 ≤ a) : + ¬ IsP true (decide (p / 2 ≤ b)) true (decide (a ≤ b)) := by + simp only [IsP, true_and, decide_eq_false_iff_not, decide_eq_true_eq] + omega + +/-- A `V_i^-` body cannot match `P`: its row order forces the last one to be zero. -/ +theorem vMinus_not_isP (p a b : ℕ) (horder : a ≤ p / 2) : + ¬ IsP true (decide (a < b)) true (decide (p / 2 < b)) := by + simp only [IsP, true_and, decide_eq_false_iff_not, decide_eq_true_eq] + omega + +/-- A `W_{i,d}^+` body cannot match `P`, including at the shared leaf level. -/ +theorem wPlus_not_isP (p q b : ℕ) (horder : b ≤ q / 2) + (hparity : p % 2 = q % 2) : + ¬ IsP (decide (p / 2 ≤ b)) (decide (p ≤ q)) true true := by + simp only [IsP, and_true, decide_eq_false_iff_not, decide_eq_true_eq] + omega + +/-- In a minus `W` mode, a body match can occur only on a shared leaf diagonal. -/ +theorem wMinus_isP_implies_leaf_diagonal + (h i p q b : ℕ) (horder : q / 2 ≤ b) + (hparity : p % 2 = q % 2) + (hbody : IsP (if i = h then decide (p ≤ q) else decide (p < q)) + (decide (p / 2 < b)) true true) : + i = h ∧ p = q := by + by_cases hleaf : i = h + · simp only [hleaf, ite_true, IsP, and_true, + decide_eq_false_iff_not, decide_eq_true_eq] at hbody + constructor + · exact hleaf + · omega + · simp only [hleaf, ite_false, IsP, and_true, + decide_eq_false_iff_not, decide_eq_true_eq] at hbody + omega + +/-- Conversely, the diagonal leaf choice with its parent column gives `P`. -/ +theorem wMinus_leaf_diagonal_isP (h p : ℕ) : + IsP (if h = h then decide (p ≤ p) else decide (p < p)) + (decide (p / 2 < p / 2)) true true := by + simp [IsP] + +end Problem348.ModeLocalization + +end OAI diff --git a/lean/OAI/Combinatorics/MatrixRemoval/Model.lean b/lean/OAI/Combinatorics/MatrixRemoval/Model.lean new file mode 100644 index 0000000000000000000000000000000000000000..fb4ba75ad49c1bfe2f8735de2cef7d677c677ab1 --- /dev/null +++ b/lean/OAI/Combinatorics/MatrixRemoval/Model.lean @@ -0,0 +1,69 @@ +import Mathlib + +namespace OAI + +noncomputable section + + + +namespace Problem348 + +abbrev BinaryMatrix (n : ℕ) := Fin n → Fin n → Bool + +abbrev IncreasingMap (k n : ℕ) := {f : Fin k → Fin n // StrictMono f} + +def orderedCopies {k n : ℕ} (H : BinaryMatrix k) (A : BinaryMatrix n) : + Finset (IncreasingMap k n × IncreasingMap k n) := by + classical + exact Finset.univ.filter (fun rc => + ∀ i j, A ((rc.1).val i) ((rc.2).val j) = H i j) + +def copyCount {k n : ℕ} (H : BinaryMatrix k) (A : BinaryMatrix n) : ℕ := + (orderedCopies H A).card + +def HFree {k n : ℕ} (H : BinaryMatrix k) (A : BinaryMatrix n) : Prop := + copyCount H A = 0 + +def hammingDistance {n : ℕ} (A B : BinaryMatrix n) : ℕ := by + classical + exact (Finset.univ.filter (fun rc : Fin n × Fin n => + A rc.1 rc.2 ≠ B rc.1 rc.2)).card + +def etaBit (a b : ℕ) : Bool := + decide (((a / (2 ^ (5 - b))) % 2) = 1) + +def anchor64 (u v : Fin 64) : Bool := + if 32 ≤ u.val ∧ 59 ≤ v.val then + etaBit (u.val - 32) (v.val - 58) + else + decide (u.val ≠ v.val) + +def fixedH : BinaryMatrix 66 := fun u v => + if hu : u.val < 64 then + if hv : v.val < 64 then + anchor64 ⟨u.val, hu⟩ ⟨v.val, hv⟩ + else + decide ((v.val = 64 ∧ u.val = 0) ∨ + (v.val = 65 ∧ u.val = 1)) + else + if v.val < 64 then + decide ((u.val = 64 ∧ v.val = 0) ∨ + (u.val = 65 ∧ v.val = 1)) + else + decide (u.val = 65 ∨ v.val = 64) + +def fixedMinEdits {n : ℕ} (A : BinaryMatrix n) : ℕ := by + classical + exact + (Finset.univ.image (fun B : BinaryMatrix n => + if HFree fixedH B then hammingDistance A B else n * n + 1)).min' + (by simp) + +def fixedDistance {n : ℕ} (A : BinaryMatrix n) : ℝ := + (fixedMinEdits A : ℝ) / ((n : ℝ) ^ 2) + +end Problem348 + +end + +end OAI diff --git a/lean/OAI/Combinatorics/MatrixRemoval/OrderedAnchorGroups.lean b/lean/OAI/Combinatorics/MatrixRemoval/OrderedAnchorGroups.lean new file mode 100644 index 0000000000000000000000000000000000000000..67cf3731858e5f75dcb695a181620e7d9bc1506e --- /dev/null +++ b/lean/OAI/Combinatorics/MatrixRemoval/OrderedAnchorGroups.lean @@ -0,0 +1,68 @@ +import OAI.Combinatorics.MatrixRemoval.OrderedHost +import OAI.Combinatorics.MatrixRemoval.HostAnchorGroups + +namespace OAI + +/-! +# Prescribed anchor coordinates in the actual ordered host + +The independent enumerations satisfy `OrderedHost.row_anchor_strictMono` +and `column_anchor_strictMono`, giving the order premises of one-mode group +exhaustion without a default order instance on the raw Position sum type. +-/ + +universe uI uO uK + +namespace Problem348.OrderedHost + +open Construction + +private theorem group_le_of_ordered_representatives + {I : Type uI} {O : Type uO} {K : Type uK} [LinearOrder I] [LinearOrder K] + (key : I → O → K) + (hmono : ∀ f : I → O, StrictMono (fun i => key i (f i))) + (u v : I) (x y : O) (hxy : key u x < key v y) : u ≤ v := by + by_contra hnot + have hvu : v < u := lt_of_not_ge hnot + have hne : u ≠ v := ne_of_gt hvu + have hback := hmono (fun i => if i = v then y else x) hvu + simp only [ite_eq_right hne] at hback + exact lt_asymm hxy hback + +/-- Increasing rows in one mode have nondecreasing anchor group indices. -/ +theorem row_anchor_group_le {h : ℕ} (t : Mode h) (u v : Fin 64) + (x y : Fin (2 ^ h)) + (hxy : rowIndex h (Sum.inl (t,u,x)) < rowIndex h (Sum.inl (t,v,y))) : + u ≤ v := + group_le_of_ordered_representatives + (fun i a => rowIndex h (Sum.inl (t,i,a))) + (row_anchor_strictMono t) u v x y hxy + +/-- The analogous group-order implication for the actual column enumeration. -/ +theorem column_anchor_group_le {h : ℕ} (t : Mode h) (u v : Fin 64) + (x y : Fin (2 ^ h)) + (hxy : columnIndex h (Sum.inl (t,u,x)) < columnIndex h (Sum.inl (t,v,y))) : + u ≤ v := + group_le_of_ordered_representatives + (fun i a => columnIndex h (Sum.inl (t,i,a))) + (column_anchor_strictMono t) u v x y hxy + +/-- Mode rigidity locates the prefix in one mode, forcing its exact group +coordinates in the concrete ordered host. No additional group, twin, density, +or order hypotheses are required. -/ +theorem anchor_representatives_of_one_mode {h : ℕ} + (r c : Fin 64 → Position h) (t : Mode h) + (hr : StrictMono (fun i => rowIndex h (r i))) + (hc : StrictMono (fun j => columnIndex h (c j))) + (hcopy : ∀ i j, host (r i) (c j) = anchor64 i j) + (hrowmode : ∀ i, ∃ u x, r i = Sum.inl (t,u,x)) + (hcolmode : ∀ j, ∃ v y, c j = Sum.inl (t,v,y)) : + ∃ x y : Fin 64 → Fin (2 ^ h), + (∀ i, r i = Sum.inl (t,i,x i)) ∧ (∀ j, c j = Sum.inl (t,j,y j)) := by + exact Construction.AnchorGroups.representatives (rowIndex h) (columnIndex h) + r c t hr hc hcopy hrowmode hcolmode + (row_anchor_group_le t) (column_anchor_group_le t) + +end Problem348.OrderedHost + +end OAI diff --git a/lean/OAI/Combinatorics/MatrixRemoval/OrderedAnchorRigidity.lean b/lean/OAI/Combinatorics/MatrixRemoval/OrderedAnchorRigidity.lean new file mode 100644 index 0000000000000000000000000000000000000000..9665e10f5da79dfd155866cdec34d958136e5478 --- /dev/null +++ b/lean/OAI/Combinatorics/MatrixRemoval/OrderedAnchorRigidity.lean @@ -0,0 +1,115 @@ +import OAI.Combinatorics.MatrixRemoval.HostAnchorPinning +import OAI.Combinatorics.MatrixRemoval.SelectedAnchorSparsity +import OAI.Combinatorics.MatrixRemoval.OrderedAnchorGroups + +namespace OAI + +/-! +# Anchor rigidity for the ordered canonical host + +No-shattering, sparse anchor traces, twin classes, and the two independent +axis orders determine all anchor representatives. +-/ +namespace Problem348.HostAnchorRigidity +open Construction AnchorRigidity + +theorem modeLabel_eq_selectedMode {h : ℕ} (x : Position h) : + modeLabel x = SelectedAnchors.mode x := by + rcases x with ⟨t,u,z⟩ | a <;> rfl + +theorem selected_rows_groupInjective {h : ℕ} (r c : Fin 64 → Position h) + (hcopy : ∀ i j, host (r i) (c j) = anchor64 i j) : + SelectedAnchors.GroupInjective r := by + intro i j a b hi hj hm hg + rcases a with ⟨t,u,x⟩ + rcases b with ⟨s,v,y⟩ + dsimp at hm hg + subst s + subst v + exact selected_anchor_rows_unique r c hcopy hi hj + +theorem selected_columns_groupInjective {h : ℕ} (r c : Fin 64 → Position h) + (hcopy : ∀ i j, host (r i) (c j) = anchor64 i j) : + SelectedAnchors.GroupInjective c := by + intro i j a b hi hj hm hg + rcases a with ⟨t,u,x⟩ + rcases b with ⟨s,v,y⟩ + dsimp at hm hg + subst s + subst v + exact selected_anchor_columns_unique r c hcopy hi hj + +/-- The sparse-column requirement follows from the actual host incidence bound. -/ +theorem actual_columnSparse {h : ℕ} (r c : Fin 64 → Position h) + (hcopy : ∀ i j, host (r i) (c j) = anchor64 i j) : ColumnSparse r c := by + intro j hm hd ha + have hb := SelectedAnchors.sparse_column_of_mode_none r firstCore (c j) + (by + intro i hi + obtain ⟨t, ht⟩ := ha i hi + obtain ⟨u,x,hx⟩ := exists_anchor_of_mode ht + exact ⟨(t,u,x),hx⟩) + (selected_rows_groupInjective r c hcopy) + (by simpa only [modeLabel_eq_selectedMode] using hm) hd + simpa only [hcopy] using hb + +/-- The transpose sparse-row requirement, with no assumptions left over. -/ +theorem actual_rowSparse {h : ℕ} (r c : Fin 64 → Position h) + (hcopy : ∀ i j, host (r i) (c j) = anchor64 i j) : RowSparse r c := by + intro i hm hd ha + have hb := SelectedAnchors.sparse_row_of_mode_none c firstCore (r i) + (by + intro j hj + obtain ⟨t, ht⟩ := ha j hj + obtain ⟨u,x,hx⟩ := exists_anchor_of_mode ht + exact ⟨(t,u,x),hx⟩) + (selected_columns_groupInjective r c hcopy) + (by simpa only [modeLabel_eq_selectedMode] using hm) hd + simpa only [hcopy] using hb + +private theorem mode_nonempty_iff_anchor {h : ℕ} (x : Position h) : + modeLabel x ≠ none ↔ ∃ a, x = Sum.inl a := by + rcases x with ⟨t,u,z⟩ | a <;> simp [modeLabel] + +theorem row_initial_of_indices {h : ℕ} (r : Fin 64 → Position h) + (hr : StrictMono (fun i => OrderedHost.rowIndex h (r i))) : + ∀ i j, i ≤ j → modeLabel (r j) ≠ none → modeLabel (r i) ≠ none := by + intro i j hij hj + rcases eq_or_lt_of_le hij with he | hlt + · simpa only [he] using hj + · apply (mode_nonempty_iff_anchor (r i)).mpr + exact OrderedHost.row_anchor_initial (hr hlt) + ((mode_nonempty_iff_anchor (r j)).mp hj) + +theorem col_initial_of_indices {h : ℕ} (c : Fin 64 → Position h) + (hc : StrictMono (fun i => OrderedHost.columnIndex h (c i))) : + ∀ i j, i ≤ j → modeLabel (c j) ≠ none → modeLabel (c i) ≠ none := by + intro i j hij hj + rcases eq_or_lt_of_le hij with he | hlt + · simpa only [he] using hj + · apply (mode_nonempty_iff_anchor (c i)).mpr + exact OrderedHost.column_anchor_initial (hc hlt) + ((mode_nonempty_iff_anchor (c j)).mp hj) + +/-- Every ordered copy of the fixed 64-by-64 anchor in the canonical host +uses precisely one mode, with its groups in the prescribed order. There are +no sparsity, majority, nonshattering, twin, or abstract-order premises. -/ +theorem representatives_of_indices {h : ℕ} (r c : Fin 64 → Position h) + (hr : StrictMono (fun i => OrderedHost.rowIndex h (r i))) + (hc : StrictMono (fun j => OrderedHost.columnIndex h (c j))) + (hcopy : ∀ i j, host (r i) (c j) = anchor64 i j) : + ∃ (t : Mode h) (a b : Fin 64 → Fin (2 ^ h)), + (∀ i, r i = Sum.inl (t,i,a i)) ∧ + (∀ j, c j = Sum.inl (t,j,b j)) := by + obtain ⟨t, hmr, hmc⟩ := mode_constant_of_no_shattering r c hcopy + (row_initial_of_indices r hr) (col_initial_of_indices c hc) + (fun cs _ hnone => actual_nonshattering cs hnone) + (actual_columnSparse r c hcopy) (actual_rowSparse r c hcopy) + obtain ⟨a,b,ha,hb⟩ := OrderedHost.anchor_representatives_of_one_mode + r c t hr hc hcopy (fun i => exists_anchor_of_mode (hmr i)) + (fun j => exists_anchor_of_mode (hmc j)) + exact ⟨t,a,b,ha,hb⟩ + +end Problem348.HostAnchorRigidity + +end OAI diff --git a/lean/OAI/Combinatorics/MatrixRemoval/OrderedBodyLocalization.lean b/lean/OAI/Combinatorics/MatrixRemoval/OrderedBodyLocalization.lean new file mode 100644 index 0000000000000000000000000000000000000000..4c8163fc550073f2d53133de3b0bff8f28b1c480 --- /dev/null +++ b/lean/OAI/Combinatorics/MatrixRemoval/OrderedBodyLocalization.lean @@ -0,0 +1,59 @@ +import OAI.Combinatorics.MatrixRemoval.OrderedHost +import OAI.Combinatorics.MatrixRemoval.HostBodyOrder + +namespace OAI + +/-! +# Body localization for the independent host enumerations + +The canonical full-axis enumeration gives exhaustive body-mode localization. +All comparisons use the actual row and column indices; no order-reflection +certificate remains as an assumption. +-/ + +namespace Problem348.OrderedHost + +open Construction + +theorem rowIndex_reflects_variable_order {h : ℕ} (v w : VariablePosition h) + (hvw : rowIndex h (.inr (.inl v)) < rowIndex h (.inr (.inl w))) : + TreePositions.rowKey h v < TreePositions.rowKey h w := + (rowIndex_variable_lt_iff v w).mp hvw + +theorem columnIndex_reflects_variable_order {h : ℕ} (v w : VariablePosition h) + (hvw : columnIndex h (.inr (.inl v)) < columnIndex h (.inr (.inl w))) : + TreePositions.columnKey h v < TreePositions.columnKey h w := + (columnIndex_variable_lt_iff v w).mp hvw + +/-- The actual independent enumerations discharge all four numerical mode orders. -/ +theorem bodyNodeOrder_of_indices {h : ℕ} {t : Mode h} + {r₀ r₁ c₀ c₁ : Position h} + (hr₀ : rowRole t 0 r₀) (hr₁ : rowRole t 1 r₁) + (hc₀ : colRole t 0 c₀) (hc₁ : colRole t 1 c₁) + (hrow : rowIndex h r₀ < rowIndex h r₁) + (hcol : columnIndex h c₀ < columnIndex h c₁) : + BodyNodeOrder t r₀ r₁ c₀ c₁ := + bodyNodeOrder_of_ordered (rowIndex h) (columnIndex h) + rowIndex_reflects_variable_order columnIndex_reflects_variable_order + hr₀ hr₁ hc₀ hc₁ hrow hcol + +/-- Every correctly assigned ordered body in the canonical host has its +top-left cell on the shared leaf diagonal. -/ +theorem body_leaf_diagonal {h : ℕ} {t : Mode h} + {r₀ r₁ c₀ c₁ : Position h} + (hr₀ : rowRole t 0 r₀) (hr₁ : rowRole t 1 r₁) + (hc₀ : colRole t 0 c₀) (hc₁ : colRole t 1 c₁) + (hrow : rowIndex h r₀ < rowIndex h r₁) + (hcol : columnIndex h c₀ < columnIndex h c₁) + (hb : ModeLocalization.IsP (host r₀ c₀) (host r₀ c₁) + (host r₁ c₀) (host r₁ c₁)) : + ∃ z : Fin (2 ^ h), + r₀ = Sum.inr (Sum.inl (Fin.last (2 * h), z)) ∧ + c₀ = Sum.inr (Sum.inl (Fin.last (2 * h), z)) := + host_ordered_body_leaf_diagonal (rowIndex h) (columnIndex h) + rowIndex_reflects_variable_order columnIndex_reflects_variable_order + hr₀ hr₁ hc₀ hc₁ hrow hcol hb + +end Problem348.OrderedHost + +end OAI diff --git a/lean/OAI/Combinatorics/MatrixRemoval/OrderedHost.lean b/lean/OAI/Combinatorics/MatrixRemoval/OrderedHost.lean new file mode 100644 index 0000000000000000000000000000000000000000..a7ee57f7281b5d57c85ac3efb68cb4de9dcc4cc1 --- /dev/null +++ b/lean/OAI/Combinatorics/MatrixRemoval/OrderedHost.lean @@ -0,0 +1,174 @@ +import OAI.Combinatorics.MatrixRemoval.Host +import OAI.Combinatorics.MatrixRemoval.TreePositions +import OAI.Combinatorics.MatrixRemoval.AnchorFrames + +namespace OAI + +/-! +# The canonical host with both full-axis orders + +The raw host, variable depth-first orders, and anchor/dummy order extension +give two orders. They are not global instances on the same carrier. Their +increasing enumerations are independent equivalences to the matrix size. +-/ + +noncomputable section + +namespace Problem348.OrderedHost + +open Construction + +abbrev size (h : ℕ) := (386 * h + 2) * 2 ^ h + +/-- Rows: anchors first, then the minus/subtree/plus tree order, then dummy. -/ +abbrev rowOrder (h : ℕ) : LinearOrder (Position h) := by + exact @AnchorFrames.rowOrder (Mode h) (VariablePosition h) (Fin (2 ^ h)) + inferInstance (TreePositions.positionOrder false h) inferInstance + +/-- Columns: anchors first, then dummy, then the plus/subtree/minus tree order. -/ +abbrev columnOrder (h : ℕ) : LinearOrder (Position h) := by + exact @AnchorFrames.colOrder (Mode h) (VariablePosition h) (Fin (2 ^ h)) + inferInstance (TreePositions.positionOrder true h) inferInstance + +/-- The increasing row enumeration, from raw positions to actual indices. -/ +def rowIndex (h : ℕ) : Position h ≃ Fin (size h) := by + letI := rowOrder h + exact (monoEquivOfFin (Position h) (card_position h)).toEquiv.symm + +/-- The increasing column enumeration, independent of the row enumeration. -/ +def columnIndex (h : ℕ) : Position h ≃ Fin (size h) := by + letI := columnOrder h + exact (monoEquivOfFin (Position h) (card_position h)).toEquiv.symm + +theorem rowIndex_lt_iff (h : ℕ) (r s : Position h) : + rowIndex h r < rowIndex h s ↔ @LT.lt _ (rowOrder h).toLT r s := by + let := rowOrder h + exact @OrderIso.lt_iff_lt _ _ (rowOrder h).toPreorder inferInstance + (@OrderIso.symm _ _ inferInstance (rowOrder h).toLE + (monoEquivOfFin (Position h) (card_position h))) r s + +theorem columnIndex_lt_iff (h : ℕ) (r s : Position h) : + columnIndex h r < columnIndex h s ↔ @LT.lt _ (columnOrder h).toLT r s := by + let := columnOrder h + exact @OrderIso.lt_iff_lt _ _ (columnOrder h).toPreorder inferInstance + (@OrderIso.symm _ _ inferInstance (columnOrder h).toLE + (monoEquivOfFin (Position h) (card_position h))) r s + +/-- On variable positions the full row enumeration has exactly the tree-key order. -/ +theorem rowIndex_variable_lt_iff {h : ℕ} (v w : VariablePosition h) : + rowIndex h (Sum.inr (Sum.inl v)) < rowIndex h (Sum.inr (Sum.inl w)) ↔ + TreePositions.rowKey h v < TreePositions.rowKey h w := by + rw [rowIndex_lt_iff] + exact @AnchorFrames.row_variable_lt_variable (Mode h) (VariablePosition h) + (Fin (2 ^ h)) inferInstance (TreePositions.positionOrder false h) inferInstance v w + +/-- On variable positions the full column enumeration has exactly the tree-key order. -/ +theorem columnIndex_variable_lt_iff {h : ℕ} (v w : VariablePosition h) : + columnIndex h (Sum.inr (Sum.inl v)) < columnIndex h (Sum.inr (Sum.inl w)) ↔ + TreePositions.columnKey h v < TreePositions.columnKey h w := by + rw [columnIndex_lt_iff] + exact @AnchorFrames.col_variable_lt_variable (Mode h) (VariablePosition h) + (Fin (2 ^ h)) inferInstance (TreePositions.positionOrder true h) inferInstance v w + +/-- Any representatives of the 64 successive anchor groups are increasing rows. -/ +theorem row_anchor_strictMono {h : ℕ} (t : Mode h) + (a : Fin 64 → Fin (2 ^ h)) : + StrictMono (fun u => rowIndex h (Sum.inl (t, u, a u))) := by + intro u v huv + rw [rowIndex_lt_iff] + exact @AnchorFrames.row_anchor_strictMono (Mode h) (VariablePosition h) + (Fin (2 ^ h)) inferInstance (TreePositions.positionOrder false h) inferInstance + t a u v huv + +/-- The analogous anchor representatives are increasing columns. -/ +theorem column_anchor_strictMono {h : ℕ} (t : Mode h) + (a : Fin 64 → Fin (2 ^ h)) : + StrictMono (fun u => columnIndex h (Sum.inl (t, u, a u))) := by + intro u v huv + rw [columnIndex_lt_iff] + exact @AnchorFrames.col_anchor_strictMono (Mode h) (VariablePosition h) + (Fin (2 ^ h)) inferInstance (TreePositions.positionOrder true h) inferInstance + t a u v huv + +theorem row_anchor_lt_nonanchor {h : ℕ} (t : Mode h) (u : Fin 64) + (a : Fin (2 ^ h)) (x : VariablePosition h ⊕ Fin (2 ^ h)) : + rowIndex h (Sum.inl (t, u, a)) < rowIndex h (Sum.inr x) := by + rw [rowIndex_lt_iff] + exact @AnchorFrames.row_anchor_lt_nonanchor (Mode h) (VariablePosition h) + (Fin (2 ^ h)) inferInstance (TreePositions.positionOrder false h) inferInstance + t u a x + +theorem column_anchor_lt_nonanchor {h : ℕ} (t : Mode h) (u : Fin 64) + (a : Fin (2 ^ h)) (x : VariablePosition h ⊕ Fin (2 ^ h)) : + columnIndex h (Sum.inl (t, u, a)) < columnIndex h (Sum.inr x) := by + rw [columnIndex_lt_iff] + exact @AnchorFrames.col_anchor_lt_nonanchor (Mode h) (VariablePosition h) + (Fin (2 ^ h)) inferInstance (TreePositions.positionOrder true h) inferInstance + t u a x + +theorem row_variable_lt_dummy {h : ℕ} (v : VariablePosition h) (x : Fin (2 ^ h)) : + rowIndex h (Sum.inr (Sum.inl v)) < rowIndex h (Sum.inr (Sum.inr x)) := by + rw [rowIndex_lt_iff] + exact @AnchorFrames.row_variable_lt_dummy (Mode h) (VariablePosition h) + (Fin (2 ^ h)) inferInstance (TreePositions.positionOrder false h) inferInstance v x + +theorem column_dummy_lt_variable {h : ℕ} (v : VariablePosition h) (x : Fin (2 ^ h)) : + columnIndex h (Sum.inr (Sum.inr x)) < columnIndex h (Sum.inr (Sum.inl v)) := by + rw [columnIndex_lt_iff] + exact @AnchorFrames.col_dummy_lt_variable (Mode h) (VariablePosition h) + (Fin (2 ^ h)) inferInstance (TreePositions.positionOrder true h) inferInstance v x + +/-- Initial-segment property for anchors, stated without an extra host predicate. -/ +theorem row_anchor_initial {h : ℕ} {r s : Position h} + (hrs : rowIndex h r < rowIndex h s) (hs : ∃ a, s = Sum.inl a) : + ∃ a, r = Sum.inl a := by + obtain ⟨⟨t, u, x⟩, rfl⟩ := hs + rcases r with a | v + · exact ⟨a, rfl⟩ + · exact False.elim (lt_asymm hrs (row_anchor_lt_nonanchor t u x v)) + +theorem column_anchor_initial {h : ℕ} {r s : Position h} + (hrs : columnIndex h r < columnIndex h s) (hs : ∃ a, s = Sum.inl a) : + ∃ a, r = Sum.inl a := by + obtain ⟨⟨t, u, x⟩, rfl⟩ := hs + rcases r with a | v + · exact ⟨a, rfl⟩ + · exact False.elim (lt_asymm hrs (column_anchor_lt_nonanchor t u x v)) + +/-- First tree-order equivalence, now for the actual row indices. -/ +theorem row_plus_child_lt_parent {h i : ℕ} (hi : i < h) (x y : Fin (2 ^ h)) : + rowIndex h (.inr (.inl (TreePositions.plusPos (i + 1) (by omega) x))) < + rowIndex h (.inr (.inl (TreePositions.plusPos i (by omega) y))) ↔ + TreePositions.node (i + 1) x / 2 ≤ TreePositions.node i y := by + rw [rowIndex_variable_lt_iff] + exact TreePositions.row_plus_child_lt_parent hi x y + +/-- Second tree-order equivalence, now for the actual row indices. -/ +theorem row_minus_parent_lt_child {h i : ℕ} (hi : i < h) (x y : Fin (2 ^ h)) : + rowIndex h (.inr (.inl (TreePositions.minusPos i (by omega) y))) < + rowIndex h (.inr (.inl (TreePositions.minusPos (i + 1) (by omega) x))) ↔ + TreePositions.node i y ≤ TreePositions.node (i + 1) x / 2 := by + rw [rowIndex_variable_lt_iff] + exact TreePositions.row_minus_parent_lt_child hi x y + +/-- Third tree-order equivalence, now for the actual column indices. -/ +theorem column_plus_parent_lt_child {h i : ℕ} (hi : i < h) (x y : Fin (2 ^ h)) : + columnIndex h (.inr (.inl (TreePositions.plusPos i (by omega) y))) < + columnIndex h (.inr (.inl (TreePositions.plusPos (i + 1) (by omega) x))) ↔ + TreePositions.node i y ≤ TreePositions.node (i + 1) x / 2 := by + rw [columnIndex_variable_lt_iff] + exact TreePositions.column_plus_parent_lt_child hi x y + +/-- Fourth tree-order equivalence, now for the actual column indices. -/ +theorem column_minus_child_lt_parent {h i : ℕ} (hi : i < h) (x y : Fin (2 ^ h)) : + columnIndex h (.inr (.inl (TreePositions.minusPos (i + 1) (by omega) x))) < + columnIndex h (.inr (.inl (TreePositions.minusPos i (by omega) y))) ↔ + TreePositions.node (i + 1) x / 2 ≤ TreePositions.node i y := by + rw [columnIndex_variable_lt_iff] + exact TreePositions.column_minus_child_lt_parent hi x y + +end Problem348.OrderedHost + +end + +end OAI diff --git a/lean/OAI/Combinatorics/MatrixRemoval/OrderedHostCopy.lean b/lean/OAI/Combinatorics/MatrixRemoval/OrderedHostCopy.lean new file mode 100644 index 0000000000000000000000000000000000000000..a49147cc04edf75eaabf0c350b8f1b45d96ba4b6 --- /dev/null +++ b/lean/OAI/Combinatorics/MatrixRemoval/OrderedHostCopy.lean @@ -0,0 +1,53 @@ +import OAI.Combinatorics.MatrixRemoval.OrderedBodyLocalization +import OAI.Combinatorics.MatrixRemoval.PinnedHostCopy + +namespace OAI + +/-! +# Ordered-copy localization and counting + +The six-mode body theorem places the distinguished cell at a shared leaf. +The count needs only anchor pinning, not a further order certificate. +-/ + +namespace Problem348.OrderedHost + +open Construction + +/-- The six-mode theorem supplies the exact body-localization counting input. -/ +theorem orderedBodyLocalizes (h : ℕ) : + OrderedBodyLocalizes (rowIndex h) (columnIndex h) := by + intro t r₀ r₁ c₀ c₁ hr₀ hr₁ hc₀ hc₁ hrow hcol hb + exact body_leaf_diagonal hr₀ hr₁ hc₀ hc₁ hrow hcol hb + +/-- Every matching ordered copy has its top-left body cell at a shared leaf. -/ +theorem matching_copy_leaf_of_pinning (h : ℕ) + (hpin : Anchor64Pinned (rowIndex h) (columnIndex h)) + (r c : Fin 66 → Position h) + (hr : StrictMono (fun i => rowIndex h (r i))) + (hc : StrictMono (fun j => columnIndex h (c j))) + (hmatch : ∀ i j, host (r i) (c j) = fixedH i j) : + ∃ z, r 64 = countedLeaf z ∧ c 64 = countedLeaf z := + host_raw_localization_of_anchor_pinning (rowIndex h) (columnIndex h) + hpin (orderedBodyLocalizes h) r c hr hc hmatch + +/-- Integer copy bound for the actual two-axis enumeration. -/ +theorem copyCount_le_of_pinning (h : ℕ) + (hpin : Anchor64Pinned (rowIndex h) (columnIndex h)) : + copyCount fixedH (hostMatrix (rowIndex h) (columnIndex h)) ≤ + 2 ^ h * (size h) ^ 130 := + host_copyCount_le_of_pinning (rowIndex h) (columnIndex h) + hpin (orderedBodyLocalizes h) + +/-- The normalized copy bound, conditional only on anchor pinning. -/ +theorem copyDensity_le_of_pinning (h : ℕ) + (hpin : Anchor64Pinned (rowIndex h) (columnIndex h)) : + (copyCount fixedH (hostMatrix (rowIndex h) (columnIndex h)) : ℝ) / + ((size h : ℝ) ^ 132) ≤ + (1 / (((386 * h + 2 : ℕ) : ℝ) ^ 2)) * (1 / ((2 : ℝ) ^ h)) := + host_copyDensity_le_of_pinning h (rowIndex h) (columnIndex h) + hpin (orderedBodyLocalizes h) + +end Problem348.OrderedHost + +end OAI diff --git a/lean/OAI/Combinatorics/MatrixRemoval/OrderedRepairDistance.lean b/lean/OAI/Combinatorics/MatrixRemoval/OrderedRepairDistance.lean new file mode 100644 index 0000000000000000000000000000000000000000..ce4d7a0a8216af6a437a0ed7fa8cd278337c154c --- /dev/null +++ b/lean/OAI/Combinatorics/MatrixRemoval/OrderedRepairDistance.lean @@ -0,0 +1,40 @@ +import OAI.Combinatorics.MatrixRemoval.OrderedSampledSelection +import OAI.Combinatorics.MatrixRemoval.HostRepairDistance + +namespace OAI + +/-! +# Unconditional repair lower bound for the ordered canonical host + +The sampler order certificate follows from the independent increasing +row and column enumerations, giving the arbitrary-repair lower bound. +-/ + +noncomputable section +namespace Problem348.OrderedHost + +open Construction + +/-- Every fixedH-free repair of the actual ordered host changes at least m² +cells. In particular no pinning premise or preservation condition is assumed. -/ +theorem hammingDistance_ge {h : ℕ} (hh : 1 ≤ h) + (B : BinaryMatrix (size h)) (hfree : HFree fixedH B) : + (2 ^ h) ^ 2 ≤ + hammingDistance (SelectedAnchor.matrix (rowIndex h) (columnIndex h)) B := + SampledSelection.hammingDistance_ge hh (rowIndex h) (columnIndex h) + (sampledAxisConditions h) B hfree + +/-- The concrete three-seed sampler has the exact uniform guard bound. -/ +theorem sampledSelection_guard_frequency {h : ℕ} (hh : 1 ≤ h) + (rc : Fin (size h) × Fin (size h)) : + (Finset.univ.filter fun s : TreeSampling.Seeds (2 ^ h) => + rc ∈ (sampledSelection hh s.1 s.2.1 s.2.2).guards h).card * (2 ^ h) ^ 2 ≤ + Fintype.card (TreeSampling.Seeds (2 ^ h)) := + SampledSelection.selection_guard_frequency hh (rowIndex h) (columnIndex h) + (sampledAxisConditions h) rc + +end Problem348.OrderedHost + +end + +end OAI diff --git a/lean/OAI/Combinatorics/MatrixRemoval/OrderedSampledSelection.lean b/lean/OAI/Combinatorics/MatrixRemoval/OrderedSampledSelection.lean new file mode 100644 index 0000000000000000000000000000000000000000..cd8ac9ca5560c54bdfce318b563eb6ed5b61a401 --- /dev/null +++ b/lean/OAI/Combinatorics/MatrixRemoval/OrderedSampledSelection.lean @@ -0,0 +1,62 @@ +import OAI.Combinatorics.MatrixRemoval.OrderedHost +import OAI.Combinatorics.MatrixRemoval.HostSampledSelection +import OAI.Combinatorics.MatrixRemoval.SampledPathOrder + +namespace OAI + +/-! +# The sampled selection on increasing host enumerations + +The ten order assumptions of the concrete sampler follow from the independent +row and column enumerations. No order or entry certificate remains as a +hypothesis of `sampledSelection_valid`. +-/ + +noncomputable section +namespace Problem348.OrderedHost + +open Construction + +/-- The actual row and column enumerations meet every sampler order condition. -/ +theorem sampledAxisConditions (h : ℕ) : + SampledSelection.AxisConditions (rowIndex h) (columnIndex h) := by + constructor + · intro t a + exact row_anchor_strictMono t (fun _ => a) + · intro t a + exact column_anchor_strictMono t (fun _ => a) + · exact row_anchor_lt_nonanchor + · exact column_anchor_lt_nonanchor + · exact row_variable_lt_dummy + · exact column_dummy_lt_variable + · intro i z u + exact HostSampledPath.row_plus_sample_order (rowIndex h) + (fun p q hpq => (rowIndex_variable_lt_iff p q).mpr hpq) i z u u + · intro i z u + exact HostSampledPath.row_minus_sample_order (rowIndex h) + (fun p q hpq => (rowIndex_variable_lt_iff p q).mpr hpq) i z u u + · intro i z u + exact HostSampledPath.column_plus_sample_order (columnIndex h) + (fun p q hpq => (columnIndex_variable_lt_iff p q).mpr hpq) i z u u + · intro i z u + exact HostSampledPath.column_minus_sample_order (columnIndex h) + (fun p q hpq => (columnIndex_variable_lt_iff p q).mpr hpq) i z u u + +/-- The three-seed selection in the concrete matrix of the prescribed size. -/ +def sampledSelection {h : ℕ} (hh : 1 ≤ h) (z u v : Fin (2 ^ h)) : + GuardedPath.Selection (size h) := + SampledSelection.selection hh (rowIndex h) (columnIndex h) + (sampledAxisConditions h) z u v + +/-- The actual sampled path and anchor frames are valid without extra inputs. -/ +theorem sampledSelection_valid {h : ℕ} (hh : 1 ≤ h) (z u v : Fin (2 ^ h)) : + (sampledSelection hh z u v).Valid + (SelectedAnchor.matrix (rowIndex h) (columnIndex h)) h := + SampledSelection.selection_valid hh (rowIndex h) (columnIndex h) + (sampledAxisConditions h) z u v + +end Problem348.OrderedHost + +end + +end OAI diff --git a/lean/OAI/Combinatorics/MatrixRemoval/PathPropagation.lean b/lean/OAI/Combinatorics/MatrixRemoval/PathPropagation.lean new file mode 100644 index 0000000000000000000000000000000000000000..e9d4657c137e958defdf3830b201af640c879dd2 --- /dev/null +++ b/lean/OAI/Combinatorics/MatrixRemoval/PathPropagation.lean @@ -0,0 +1,119 @@ +import Mathlib + +namespace OAI + +/-! +Boolean propagation independent of the host construction. +No entry between variable positions is assumed to remain unchanged. Only +the dummy incidences, root bits, and identification of the two leaves +are hypotheses. +-/ + +universe uR uC + +namespace Problem348.PathPropagation + +variable {R : Type uR} {C : Type uC} + +/-- The lower-right two-by-two pattern of the fixed matrix `fixedH`. -/ +def Body (B : R → C → Bool) (r₁ r₂ : R) (c₁ c₂ : C) : Prop := + B r₁ c₁ = true ∧ B r₁ c₂ = false ∧ + B r₂ c₁ = true ∧ B r₂ c₂ = true + +/-- Avoiding the body propagates a one upwards across a column of dummy ones. -/ +theorem vertical_plus {B : R → C → Bool} {r₁ r₂ : R} {c₁ c₂ : C} + (havoid : ¬ Body B r₁ r₂ c₁ c₂) + (h₁ : B r₁ c₁ = true) (h₂ : B r₂ c₁ = true) + (h₃ : B r₂ c₂ = true) : B r₁ c₂ = true := by + apply Bool.eq_true_of_not_eq_false + intro h + exact havoid ⟨h₁, h, h₂, h₃⟩ + +/-- Avoiding the body propagates a zero downwards across dummy ones. -/ +theorem vertical_minus {B : R → C → Bool} {r₁ r₂ : R} {c₁ c₂ : C} + (havoid : ¬ Body B r₁ r₂ c₁ c₂) + (h₁ : B r₁ c₁ = true) (h₂ : B r₂ c₁ = true) + (h₃ : B r₁ c₂ = false) : B r₂ c₂ = false := by + apply Bool.eq_false_of_not_eq_true + intro h + exact havoid ⟨h₁, h₃, h₂, h⟩ + +/-- Avoiding the body propagates a one rightwards above a dummy row. -/ +theorem horizontal_plus {B : R → C → Bool} {r₁ r₂ : R} {c₁ c₂ : C} + (havoid : ¬ Body B r₁ r₂ c₁ c₂) + (h₁ : B r₁ c₁ = true) (h₂ : B r₂ c₁ = true) + (h₃ : B r₂ c₂ = true) : B r₁ c₂ = true := + vertical_plus havoid h₁ h₂ h₃ + +/-- Avoiding the body propagates a zero leftwards above a dummy row. -/ +theorem horizontal_minus {B : R → C → Bool} {r₁ r₂ : R} {c₁ c₂ : C} + (havoid : ¬ Body B r₁ r₂ c₁ c₂) + (h₁ : B r₁ c₂ = false) (h₂ : B r₂ c₁ = true) + (h₃ : B r₂ c₂ = true) : B r₁ c₁ = false := by + apply Bool.eq_false_of_not_eq_true + intro h + exact havoid ⟨h, h₁, h₂, h₃⟩ + +/-- One of the four mode bodies encountered at the edge from level `i` +to level `i + 1` of the selected path. -/ +def ModeBody (B : R → C → Bool) + (xp xm : ℕ → R) (yp ym : ℕ → C) (xd : R) (yd : C) (i : ℕ) : Prop := + Body B (xp (i + 1)) (xp i) yd (yp i) ∨ + Body B (xm i) (xm (i + 1)) yd (ym i) ∨ + Body B (xp (i + 1)) xd (yp i) (yp (i + 1)) ∨ + Body B (xm (i + 1)) xd (ym (i + 1)) (ym i) + +/-- The induction invariant: absence of all four mode bodies preserves the +opposite plus and minus bits at every level of the selected path. -/ +theorem propagate {B : R → C → Bool} + {xp xm : ℕ → R} {yp ym : ℕ → C} {xd : R} {yd : C} {h : ℕ} + (hrootp : B (xp 0) (yp 0) = true) + (hrootm : B (xm 0) (ym 0) = false) + (hdcol : ∀ i, i ≤ h → B (xp i) yd = true ∧ B (xm i) yd = true) + (hdrow : ∀ i, i ≤ h → B xd (yp i) = true ∧ B xd (ym i) = true) + (havoid : ∀ i, i < h → ¬ ModeBody B xp xm yp ym xd yd i) : + ∀ i, i ≤ h → B (xp i) (yp i) = true ∧ B (xm i) (ym i) = false := by + intro i + induction i with + | zero => exact fun _ => ⟨hrootp, hrootm⟩ + | succ i ih => + intro hi + have hil : i ≤ h := by omega + have hit : i < h := by omega + obtain ⟨hp, hm⟩ := ih hil + have hvp : ¬ Body B (xp (i + 1)) (xp i) yd (yp i) := + fun hb => havoid i hit (Or.inl hb) + have hvm : ¬ Body B (xm i) (xm (i + 1)) yd (ym i) := + fun hb => havoid i hit (Or.inr (Or.inl hb)) + have hwp : ¬ Body B (xp (i + 1)) xd (yp i) (yp (i + 1)) := + fun hb => havoid i hit (Or.inr (Or.inr (Or.inl hb))) + have hwm : ¬ Body B (xm (i + 1)) xd (ym (i + 1)) (ym i) := + fun hb => havoid i hit (Or.inr (Or.inr (Or.inr hb))) + have hcrossp : B (xp (i + 1)) (yp i) = true := + vertical_plus hvp (hdcol (i + 1) hi).1 (hdcol i hil).1 hp + have hcrossm : B (xm (i + 1)) (ym i) = false := + vertical_minus hvm (hdcol i hil).2 (hdcol (i + 1) hi).2 hm + exact ⟨horizontal_plus hwp hcrossp (hdrow i hil).1 (hdrow (i + 1) hi).1, + horizontal_minus hwm hcrossm (hdrow (i + 1) hi).2 (hdrow i hil).2⟩ + +/-- Opposite root entries and shared leaves force some mode body. Arbitrary +changes to every other variable-variable entry are explicitly allowed. -/ +theorem exists_modeBody {B : R → C → Bool} + {xp xm : ℕ → R} {yp ym : ℕ → C} {xd : R} {yd : C} {h : ℕ} + (hrootp : B (xp 0) (yp 0) = true) + (hrootm : B (xm 0) (ym 0) = false) + (hdcol : ∀ i, i ≤ h → B (xp i) yd = true ∧ B (xm i) yd = true) + (hdrow : ∀ i, i ≤ h → B xd (yp i) = true ∧ B xd (ym i) = true) + (hleafr : xp h = xm h) (hleafc : yp h = ym h) : + ∃ i, i < h ∧ ModeBody B xp xm yp ym xd yd i := by + by_contra hnone + have havoid : ∀ i, i < h → ¬ ModeBody B xp xm yp ym xd yd i := by + intro i hi hb + exact hnone ⟨i, hi, hb⟩ + obtain ⟨hp, hm⟩ := propagate hrootp hrootm hdcol hdrow havoid h le_rfl + rw [hleafr, hleafc, hm] at hp + cases hp + +end Problem348.PathPropagation + +end OAI diff --git a/lean/OAI/Combinatorics/MatrixRemoval/PinnedHostCopy.lean b/lean/OAI/Combinatorics/MatrixRemoval/PinnedHostCopy.lean new file mode 100644 index 0000000000000000000000000000000000000000..f124bf129c13ceb8b381d0196c424b6707e6ab33 --- /dev/null +++ b/lean/OAI/Combinatorics/MatrixRemoval/PinnedHostCopy.lean @@ -0,0 +1,99 @@ +import OAI.Combinatorics.MatrixRemoval.HostRoleExtraction +import OAI.Combinatorics.MatrixRemoval.HostCopyBound +import OAI.Combinatorics.MatrixRemoval.ModeLocalization + +namespace OAI + +/-! +# From anchor rigidity and body localization to the copy-count bound + +The independent row and column orders are represented by `er` and `ec`. +The geometric hypotheses are rigidity of every ordered `anchor64` copy and +localization of ordered bodies in their actual host roles. +-/ + +namespace Problem348.Construction + +/-- The precise form of anchor rigidity needed for counting: every ordered +anchor copy contains one representative of each group of one common mode. -/ +def Anchor64Pinned {h n : ℕ} (er ec : Position h ≃ Fin n) : Prop := + ∀ r c : Fin 64 → Position h, + StrictMono (fun u => er (r u)) → StrictMono (fun v => ec (c v)) → + (∀ u v, host (r u) (c v) = anchor64 u v) → + ∃ (t : Mode h) (zr zc : Fin 64 → Fin (2 ^ h)), + (∀ u, r u = Sum.inl (t, u, zr u)) ∧ + (∀ v, c v = Sum.inl (t, v, zc v)) + +/-- Localization of bodies in the six actual host modes, using the two +orders induced by the chosen enumerations. -/ +def OrderedBodyLocalizes {h n : ℕ} (er ec : Position h ≃ Fin n) : Prop := + ∀ (t : Mode h) (r₀ r₁ c₀ c₁ : Position h), + rowRole t 0 r₀ → rowRole t 1 r₁ → + colRole t 0 c₀ → colRole t 1 c₁ → + er r₀ < er r₁ → ec c₀ < ec c₁ → + ModeLocalization.IsP (host r₀ c₀) (host r₀ c₁) + (host r₁ c₀) (host r₁ c₁) → + ∃ z : Fin (2 ^ h), r₀ = countedLeaf z ∧ c₀ = countedLeaf z + +/-- The anchor coordinates form an increasing initial segment of the pattern. -/ +theorem strictMono_anchorIndex52 : StrictMono BodySignatures52.anchorIndex := by + intro u v huv + exact huv + +/-- Once the prefix of a particular matching copy has been pinned, its body +roles and the exact four entries supply the leaf witness. -/ +theorem pinned_matching_copy_leaf {h n : ℕ} (er ec : Position h ≃ Fin n) + (hbody : OrderedBodyLocalizes er ec) + (r c : Fin 66 → Position h) + (hr : StrictMono (fun i => er (r i))) + (hc : StrictMono (fun j => ec (c j))) + (hmatch : ∀ i j, host (r i) (c j) = fixedH i j) + (t : Mode h) (zr zc : Fin 64 → Fin (2 ^ h)) + (hrows : ∀ u, r (BodySignatures52.anchorIndex u) = Sum.inl (t, u, zr u)) + (hcols : ∀ v, c (BodySignatures52.anchorIndex v) = Sum.inl (t, v, zc v)) : + ∃ z, r 64 = countedLeaf z ∧ c 64 = countedLeaf z := by + have hroles₀ := host_body_roles_of_matching r c hmatch t zr zc hrows hcols 0 + have hroles₁ := host_body_roles_of_matching r c hmatch t zr zc hrows hcols 1 + have hentries := host_body_entries_of_matching r c hmatch + have hindex : BodySignatures52.bodyIndex 0 < BodySignatures52.bodyIndex 1 := by + decide + exact hbody t _ _ _ _ hroles₀.1 hroles₁.1 hroles₀.2 hroles₁.2 + (hr hindex) (hc hindex) hentries + +/-- Restrict a fixed-H copy to its genuine anchor64 prefix, apply rigidity, +and then use body localization. This is the raw localization premise consumed +by `host_copyCount_le`, with no counting or order-transplant assumptions lost. -/ +theorem host_raw_localization_of_anchor_pinning {h n : ℕ} + (er ec : Position h ≃ Fin n) + (hpin : Anchor64Pinned er ec) (hbody : OrderedBodyLocalizes er ec) + (r c : Fin 66 → Position h) + (hr : StrictMono (fun i => er (r i))) + (hc : StrictMono (fun j => ec (c j))) + (hmatch : ∀ i j, host (r i) (c j) = fixedH i j) : + ∃ z, r 64 = countedLeaf z ∧ c 64 = countedLeaf z := by + obtain ⟨t, zr, zc, hrows, hcols⟩ := hpin + (fun u => r (BodySignatures52.anchorIndex u)) + (fun v => c (BodySignatures52.anchorIndex v)) + (hr.comp strictMono_anchorIndex52) (hc.comp strictMono_anchorIndex52) + (fun u v => (hmatch _ _).trans (BodySignatures52.fixedH_anchor_anchor u v)) + exact pinned_matching_copy_leaf er ec hbody r c hr hc hmatch t zr zc hrows hcols + +/-- Anchor rigidity and body localization imply the integer copy bound. -/ +theorem host_copyCount_le_of_pinning {h n : ℕ} + (er ec : Position h ≃ Fin n) + (hpin : Anchor64Pinned er ec) (hbody : OrderedBodyLocalizes er ec) : + copyCount fixedH (hostMatrix er ec) ≤ 2 ^ h * n ^ 130 := + host_copyCount_le er ec (host_raw_localization_of_anchor_pinning er ec hpin hbody) + +/-- The normalized upper bound for the counterexample sequence. -/ +theorem host_copyDensity_le_of_pinning (h : ℕ) + (er ec : Position h ≃ Fin ((386 * h + 2) * 2 ^ h)) + (hpin : Anchor64Pinned er ec) (hbody : OrderedBodyLocalizes er ec) : + (copyCount fixedH (hostMatrix er ec) : ℝ) / + ((((386 * h + 2) * 2 ^ h : ℕ) : ℝ) ^ 132) ≤ + (1 / (((386 * h + 2 : ℕ) : ℝ) ^ 2)) * (1 / ((2 : ℝ) ^ h)) := + host_copyDensity_le h er ec (host_raw_localization_of_anchor_pinning er ec hpin hbody) + +end Problem348.Construction + +end OAI diff --git a/lean/OAI/Combinatorics/MatrixRemoval/SampledPath.lean b/lean/OAI/Combinatorics/MatrixRemoval/SampledPath.lean new file mode 100644 index 0000000000000000000000000000000000000000..19835a12f017bab401e4e4be33a9fd3bbd0cec1f --- /dev/null +++ b/lean/OAI/Combinatorics/MatrixRemoval/SampledPath.lean @@ -0,0 +1,175 @@ +import Mathlib + +namespace OAI + +/-! +Concrete common-leaf path positions. +The variable-position type is `Fin (2*h+1) × Fin (2^h)`: even classes are +plus, odd classes are minus, and class `2*h` is the shared leaf class. +-/ + +namespace Problem348.SampledPath + +abbrev VariablePosition (h : ℕ) := Fin (2 * h + 1) × Fin (2 ^ h) + +def blockSize (h i : ℕ) : ℕ := 2 ^ (h - i) + +theorem blockSize_pos (h i : ℕ) : 0 < blockSize h i := by + exact pow_pos (by decide) _ + +theorem blockSize_mul_nodes {h i : ℕ} (hi : i ≤ h) : + blockSize h i * 2 ^ i = 2 ^ h := + Nat.pow_sub_mul_pow 2 hi + +/-- Retain the sampled leaf's node but choose the within-node offset from `u`. -/ +def mix (b z u : ℕ) : ℕ := z / b * b + u % b + +theorem mix_lt {b n z u : ℕ} (hb : 0 < b) (hz : z < n * b) : + mix b z u < n * b := by + have hq : z / b < n := (Nat.div_lt_iff_lt_mul hb).2 hz + have hr : u % b < b := Nat.mod_lt u hb + unfold mix + nlinarith + +theorem mix_div {b : ℕ} (hb : 0 < b) (z u : ℕ) : + mix b z u / b = z / b := by + unfold mix + rw [Nat.mul_comm (z / b) b, Nat.mul_add_div hb] + simp [Nat.div_eq_of_lt (Nat.mod_lt u hb)] + +theorem mix_mod {b : ℕ} (hb : 0 < b) (z u : ℕ) : + mix b z u % b = u % b := by + calc + mix b z u % b = (u % b) % b := by simp [mix, Nat.add_mod] + _ = u % b := Nat.mod_eq_of_lt (Nat.mod_lt u hb) + +def mixFin (h i : ℕ) (hi : i ≤ h) (z u : Fin (2 ^ h)) : Fin (2 ^ h) := + ⟨mix (blockSize h i) z.val u.val, by + have hm : 2 ^ h = 2 ^ i * blockSize h i := by + rw [Nat.mul_comm, blockSize_mul_nodes hi] + calc + mix (blockSize h i) z.val u.val < 2 ^ i * blockSize h i := + mix_lt (blockSize_pos h i) (lt_of_lt_of_eq z.isLt hm) + _ = 2 ^ h := hm.symm⟩ + +@[simp] theorem mixFin_node (h i : ℕ) (hi : i ≤ h) (z u : Fin (2 ^ h)) : + (mixFin h i hi z u).val / blockSize h i = z.val / blockSize h i := + mix_div (blockSize_pos h i) z.val u.val + +@[simp] theorem mixFin_root (h : ℕ) (z u : Fin (2 ^ h)) : + mixFin h 0 (Nat.zero_le h) z u = u := by + apply Fin.ext + simp [mixFin, mix, blockSize, Nat.div_eq_of_lt z.isLt, Nat.mod_eq_of_lt u.isLt] + +@[simp] theorem mixFin_leaf (h : ℕ) (z u : Fin (2 ^ h)) : + mixFin h h le_rfl z u = z := by + apply Fin.ext + simp [mixFin, mix, blockSize, Nat.mod_one] + +/-- The plus and minus names coincide precisely at the leaf level. -/ +def classAt (h i : ℕ) (hi : i ≤ h) (plus : Bool) : Fin (2 * h + 1) := + ⟨if i = h then 2 * h else 2 * i + (!plus).toNat, by + split_ifs with heq + · omega + · cases plus <;> simp <;> omega⟩ + +@[simp] theorem classAt_depth (h i : ℕ) (hi : i ≤ h) (plus : Bool) : + (classAt h i hi plus).val / 2 = i := by + unfold classAt + split_ifs with heq + · subst i + change 2 * h / 2 = h + omega + · cases plus <;> simp; omega + +@[simp] theorem classAt_leaf (h : ℕ) (plus : Bool) : + (classAt h h le_rfl plus).val = 2 * h := by + simp [classAt] + +theorem classAt_internal (h i : ℕ) (hi : i < h) (plus : Bool) : + (classAt h i hi.le plus).val = 2 * i + (!plus).toNat := by + simp [classAt, Nat.ne_of_lt hi] + +theorem classAt_leaf_iff (h i : ℕ) (hi : i ≤ h) (plus : Bool) : + (classAt h i hi plus).val = 2 * h ↔ i = h := by + constructor + · intro heq + have hd := classAt_depth h i hi plus + rw [heq] at hd + omega + · rintro rfl + simp + +theorem classAt_signs_eq_iff (h i : ℕ) (hi : i ≤ h) : + classAt h i hi true = classAt h i hi false ↔ i = h := by + by_cases heq : i = h + · subst i + simp [classAt] + · simp [classAt, heq, Fin.ext_iff] + +def sample (h i : ℕ) (hi : i ≤ h) (plus : Bool) + (z u : Fin (2 ^ h)) : VariablePosition h := + (classAt h i hi plus, mixFin h i hi z u) + +def depth {h : ℕ} (p : VariablePosition h) : ℕ := p.1.val / 2 + +def node {h : ℕ} (p : VariablePosition h) : ℕ := + p.2.val / blockSize h (depth p) + +@[simp] theorem sample_depth (h i : ℕ) (hi : i ≤ h) (plus : Bool) + (z u : Fin (2 ^ h)) : depth (sample h i hi plus z u) = i := + classAt_depth h i hi plus + +@[simp] theorem sample_node (h i : ℕ) (hi : i ≤ h) (plus : Bool) + (z u : Fin (2 ^ h)) : + node (sample h i hi plus z u) = z.val / blockSize h i := by + unfold node + rw [sample_depth] + exact mixFin_node h i hi z u + +theorem sample_node_lt (h i : ℕ) (hi : i ≤ h) (plus : Bool) + (z u : Fin (2 ^ h)) : node (sample h i hi plus z u) < 2 ^ i := by + rw [sample_node] + apply (Nat.div_lt_iff_lt_mul (blockSize_pos h i)).2 + rw [Nat.mul_comm, blockSize_mul_nodes hi] + exact z.isLt + +/-- The two axes may use different offset seeds and still follow one common path. -/ +theorem sample_nodes_eq (h i : ℕ) (hi : i ≤ h) (s t : Bool) + (z u v : Fin (2 ^ h)) : + node (sample h i hi s z u) = node (sample h i hi t z v) := by + simp + +theorem ancestor_parent (h i z : ℕ) (hi : i + 1 ≤ h) : + z / blockSize h (i + 1) / 2 = z / blockSize h i := by + have he : h - i = h - (i + 1) + 1 := by omega + simp only [blockSize, Nat.div_div_eq_div_mul] + rw [he, pow_succ] + +theorem sample_parent (h i : ℕ) (hi : i + 1 ≤ h) (s t : Bool) + (z u v : Fin (2 ^ h)) : + node (sample h (i + 1) hi s z u) / 2 = + node (sample h i (by omega) t z v) := by + simp only [sample_node] + exact ancestor_parent h i z.val hi + +@[simp] theorem sample_shared_leaf (h : ℕ) (s t : Bool) + (z u v : Fin (2 ^ h)) : + sample h h le_rfl s z u = sample h h le_rfl t z v := by + simp [sample, classAt] + +@[simp] theorem sample_leaf_offset (h : ℕ) (s : Bool) (z u : Fin (2 ^ h)) : + (sample h h le_rfl s z u).2 = z := by + simp [sample] + +@[simp] theorem sample_root_offset (h : ℕ) (s : Bool) (z u : Fin (2 ^ h)) : + (sample h 0 (Nat.zero_le h) s z u).2 = u := by + simp [sample] + +@[simp] theorem sample_root_node (h : ℕ) (s : Bool) (z u : Fin (2 ^ h)) : + node (sample h 0 (Nat.zero_le h) s z u) = 0 := by + simp [blockSize, Nat.div_eq_of_lt z.isLt] + +end Problem348.SampledPath + +end OAI diff --git a/lean/OAI/Combinatorics/MatrixRemoval/SampledPathOrder.lean b/lean/OAI/Combinatorics/MatrixRemoval/SampledPathOrder.lean new file mode 100644 index 0000000000000000000000000000000000000000..93e2f9cb9e28c6b6af61756fc1d33ffa4805e983 --- /dev/null +++ b/lean/OAI/Combinatorics/MatrixRemoval/SampledPathOrder.lean @@ -0,0 +1,108 @@ +import OAI.Combinatorics.MatrixRemoval.HostSampledPath +import OAI.Combinatorics.MatrixRemoval.TreePositions + +namespace OAI + +/-! The four sampled body orders, including the shared-leaf edge. -/ +universe uR uC + +namespace Problem348.HostSampledPath + +open SampledPath + + theorem sample_plus_eq (h i : ℕ) (hi : i ≤ h) (z u : Fin (2 ^ h)) : + sample h i hi true z u = TreePositions.plusPos i hi (mixFin h i hi z u) := by + apply Prod.ext + · apply Fin.ext + simp [sample, classAt, TreePositions.plusPos] + omega + · rfl + + theorem sample_minus_eq (h i : ℕ) (hi : i ≤ h) (z u : Fin (2 ^ h)) : + sample h i hi false z u = TreePositions.minusPos i hi (mixFin h i hi z u) := by + simp [sample, classAt, TreePositions.minusPos] + +@[simp] theorem treeNode_mixFin (h i : ℕ) (hi : i ≤ h) (z u : Fin (2 ^ h)) : + TreePositions.node i (mixFin h i hi z u) = z.val / blockSize h i := + mixFin_node h i hi z u + + theorem row_plus_sample_child_lt_parent {h : ℕ} (i : Fin h) + (z u v : Fin (2 ^ h)) : + TreePositions.rowKey h (sample h (i.val + 1) (by omega) true z u) < + TreePositions.rowKey h (sample h i.val (by omega) true z v) := by + rw [sample_plus_eq, sample_plus_eq, + TreePositions.row_plus_child_lt_parent i.isLt] + simp only [treeNode_mixFin] + rw [ancestor_parent h i.val z.val (by omega)] + + theorem row_minus_sample_parent_lt_child {h : ℕ} (i : Fin h) + (z u v : Fin (2 ^ h)) : + TreePositions.rowKey h (sample h i.val (by omega) false z v) < + TreePositions.rowKey h (sample h (i.val + 1) (by omega) false z u) := by + rw [sample_minus_eq, sample_minus_eq, + TreePositions.row_minus_parent_lt_child i.isLt] + simp only [treeNode_mixFin] + rw [ancestor_parent h i.val z.val (by omega)] + + theorem column_plus_sample_parent_lt_child {h : ℕ} (i : Fin h) + (z u v : Fin (2 ^ h)) : + TreePositions.columnKey h (sample h i.val (by omega) true z v) < + TreePositions.columnKey h (sample h (i.val + 1) (by omega) true z u) := by + rw [sample_plus_eq, sample_plus_eq, + TreePositions.column_plus_parent_lt_child i.isLt] + simp only [treeNode_mixFin] + rw [ancestor_parent h i.val z.val (by omega)] + + theorem column_minus_sample_child_lt_parent {h : ℕ} (i : Fin h) + (z u v : Fin (2 ^ h)) : + TreePositions.columnKey h (sample h (i.val + 1) (by omega) false z u) < + TreePositions.columnKey h (sample h i.val (by omega) false z v) := by + rw [sample_minus_eq, sample_minus_eq, + TreePositions.column_minus_child_lt_parent i.isLt] + simp only [treeNode_mixFin] + rw [ancestor_parent h i.val z.val (by omega)] + +/-- Consequence after transporting the canonical row key into any ordered axis. -/ +theorem row_plus_sample_order {h : ℕ} {R : Type uR} [Preorder R] + (r : Construction.Position h → R) + (hr : ∀ p q : Construction.VariablePosition h, + TreePositions.rowKey h p < TreePositions.rowKey h q → + r (Sum.inr (Sum.inl p)) < r (Sum.inr (Sum.inl q))) + (i : Fin h) (z u v : Fin (2 ^ h)) : + r (position h (i.val + 1) (by omega) true z u) < + r (position h i.val (by omega) true z v) := + hr _ _ (row_plus_sample_child_lt_parent i z u v) + + theorem row_minus_sample_order {h : ℕ} {R : Type uR} [Preorder R] + (r : Construction.Position h → R) + (hr : ∀ p q : Construction.VariablePosition h, + TreePositions.rowKey h p < TreePositions.rowKey h q → + r (Sum.inr (Sum.inl p)) < r (Sum.inr (Sum.inl q))) + (i : Fin h) (z u v : Fin (2 ^ h)) : + r (position h i.val (by omega) false z v) < + r (position h (i.val + 1) (by omega) false z u) := + hr _ _ (row_minus_sample_parent_lt_child i z u v) + + theorem column_plus_sample_order {h : ℕ} {C : Type uC} [Preorder C] + (c : Construction.Position h → C) + (hc : ∀ p q : Construction.VariablePosition h, + TreePositions.columnKey h p < TreePositions.columnKey h q → + c (Sum.inr (Sum.inl p)) < c (Sum.inr (Sum.inl q))) + (i : Fin h) (z u v : Fin (2 ^ h)) : + c (position h i.val (by omega) true z v) < + c (position h (i.val + 1) (by omega) true z u) := + hc _ _ (column_plus_sample_parent_lt_child i z u v) + + theorem column_minus_sample_order {h : ℕ} {C : Type uC} [Preorder C] + (c : Construction.Position h → C) + (hc : ∀ p q : Construction.VariablePosition h, + TreePositions.columnKey h p < TreePositions.columnKey h q → + c (Sum.inr (Sum.inl p)) < c (Sum.inr (Sum.inl q))) + (i : Fin h) (z u v : Fin (2 ^ h)) : + c (position h (i.val + 1) (by omega) false z u) < + c (position h i.val (by omega) false z v) := + hc _ _ (column_minus_sample_child_lt_parent i z u v) + +end Problem348.HostSampledPath + +end OAI diff --git a/lean/OAI/Combinatorics/MatrixRemoval/SamplingAvoidance.lean b/lean/OAI/Combinatorics/MatrixRemoval/SamplingAvoidance.lean new file mode 100644 index 0000000000000000000000000000000000000000..e175b3fed93e2c4033e2191d4b298588c6809329 --- /dev/null +++ b/lean/OAI/Combinatorics/MatrixRemoval/SamplingAvoidance.lean @@ -0,0 +1,157 @@ +import Mathlib + +namespace OAI + + +/-! +# Avoiding a finite family of events by counting + +The cardinality of a finite union is bounded by the sum of the individual +cardinalities. A strict bound below the size of the ambient finite type +therefore supplies an element outside every event. The rational corollary +uses normalized cardinalities and requires no independence assumption. +-/ + +universe uOmega uI uCell uValue + +namespace Problem348.Sampling + +open scoped BigOperators + +/-- A family of finite bad events whose summed cardinality is smaller than the +ambient finite type has an element avoiding every event in the family. -/ +theorem exists_avoiding_of_sum_card_lt {Ω : Type uOmega} {I : Type uI} [Fintype Ω] + (events : Finset I) (bad : I → Finset Ω) + (hsmall : (∑ i ∈ events, (bad i).card) < Fintype.card Ω) : + ∃ ω, ∀ i ∈ events, ω ∉ bad i := by + classical + have hUnion : (events.biUnion bad).card < (Finset.univ : Finset Ω).card := by + rw [Finset.card_univ] + exact lt_of_le_of_lt Finset.card_biUnion_le hsmall + obtain ⟨ω, _, hω⟩ := Finset.exists_mem_notMem_of_card_lt_card hUnion + refine ⟨ω, ?_⟩ + intro i hi hbad + exact hω (Finset.mem_biUnion.mpr ⟨i, hi, hbad⟩) + +/-- Uniform rational bounds on the normalized bad-event cardinalities give an +avoiding element when the number of events times the bound is less than one. +The events may overlap arbitrarily. -/ +theorem exists_avoiding_of_uniform_ratio_lt {Ω : Type uOmega} {I : Type uI} [Fintype Ω] + (events : Finset I) (bad : I → Finset Ω) (r : ℚ) + (hΩ : 0 < Fintype.card Ω) + (hbound : ∀ i ∈ events, ((bad i).card : ℚ) / (Fintype.card Ω : ℚ) ≤ r) + (hsmall : (events.card : ℚ) * r < 1) : + ∃ ω, ∀ i ∈ events, ω ∉ bad i := by + have hpos : (0 : ℚ) < (Fintype.card Ω : ℚ) := Nat.cast_pos.mpr hΩ + have hsum : (∑ i ∈ events, ((bad i).card : ℚ)) < (Fintype.card Ω : ℚ) := by + calc + (∑ i ∈ events, ((bad i).card : ℚ)) + ≤ ∑ i ∈ events, r * (Fintype.card Ω : ℚ) := + Finset.sum_le_sum fun i hi => (div_le_iff₀ hpos).mp (hbound i hi) + _ = (events.card : ℚ) * r * (Fintype.card Ω : ℚ) := by + simp only [Finset.sum_const, nsmul_eq_mul, mul_assoc] + _ < 1 * (Fintype.card Ω : ℚ) := mul_lt_mul_of_pos_right hsmall hpos + _ = (Fintype.card Ω : ℚ) := one_mul _ + apply exists_avoiding_of_sum_card_lt events bad + apply (Nat.cast_lt (α := ℚ)).mp + simpa only [Nat.cast_sum] using hsum + +/-- A fraction-free uniform union bound. Every bad event occupies at most +`1 / q` of the finite sample space; fewer than `q` bad events can be avoided. +No independence between the bad events is required. -/ +theorem exists_avoiding_of_card_mul_le {Ω : Type uOmega} {I : Type uI} [Fintype Ω] + (events : Finset I) (bad : I → Finset Ω) (q : ℕ) + (hΩ : 0 < Fintype.card Ω) + (hbound : ∀ i ∈ events, (bad i).card * q ≤ Fintype.card Ω) + (hsmall : events.card < q) : + ∃ ω, ∀ i ∈ events, ω ∉ bad i := by + have hq : 0 < q := lt_of_le_of_lt (Nat.zero_le _) hsmall + apply exists_avoiding_of_sum_card_lt events bad + apply (Nat.mul_lt_mul_right hq).mp + calc + (∑ i ∈ events, (bad i).card) * q + = ∑ i ∈ events, (bad i).card * q := Finset.sum_mul _ _ _ + _ ≤ ∑ _i ∈ events, Fintype.card Ω := Finset.sum_le_sum hbound + _ = events.card * Fintype.card Ω := by simp + _ < q * Fintype.card Ω := Nat.mul_lt_mul_of_pos_right hsmall hΩ + _ = Fintype.card Ω * q := Nat.mul_comm _ _ + +/-- The cellwise counting form of sampling avoidance. +The relation `selected ω e` means that sample `ω` uses the relevant cell `e`. +The budget is the square of the common size of the axis classes. -/ +theorem exists_selection_avoiding {Ω : Type uOmega} {Cell : Type uCell} [Fintype Ω] + (changed : Finset Cell) (selected : Ω → Cell → Prop) (m : ℕ) + [DecidableRel selected] + (hΩ : 0 < Fintype.card Ω) + (hbound : ∀ e ∈ changed, + (Finset.univ.filter (fun ω => selected ω e)).card * m ^ 2 ≤ Fintype.card Ω) + (hsmall : changed.card < m ^ 2) : + ∃ ω, ∀ e ∈ changed, ¬ selected ω e := by + obtain ⟨ω, hω⟩ := exists_avoiding_of_card_mul_le changed + (fun e => Finset.univ.filter (fun ω => selected ω e)) (m ^ 2) hΩ hbound hsmall + exact ⟨ω, fun e he hs => hω e he (Finset.mem_filter.mpr ⟨Finset.mem_univ _, hs⟩)⟩ + +/-- Agreement on every protected selected cell follows from the cellwise +sampling estimate. Unprotected cells are allowed to change arbitrarily. -/ +theorem exists_agreement_of_changed_card_lt + {Ω : Type uOmega} {Cell : Type uCell} {Value : Type uValue} [Fintype Ω] [Fintype Cell] [DecidableEq Value] + (A B : Cell → Value) (selected : Ω → Cell → Prop) + (relevant : Cell → Prop) [DecidableRel selected] [DecidablePred relevant] + (m : ℕ) (hΩ : 0 < Fintype.card Ω) + (hbound : ∀ e, relevant e → + (Finset.univ.filter (fun ω => selected ω e)).card * m ^ 2 ≤ Fintype.card Ω) + (hsmall : (Finset.univ.filter (fun e => A e ≠ B e)).card < m ^ 2) : + ∃ ω, ∀ e, relevant e → selected ω e → A e = B e := by + classical + let changed := Finset.univ.filter (fun e => A e ≠ B e) + let events := changed.filter relevant + have hsmall' : events.card < m ^ 2 := + lt_of_le_of_lt (Finset.card_filter_le _ _) hsmall + obtain ⟨ω, hω⟩ := exists_selection_avoiding events selected m hΩ + (fun e he => hbound e (Finset.mem_filter.mp he).2) hsmall' + refine ⟨ω, ?_⟩ + intro e he hs + by_contra hne + exact hω e (by simp [events, changed, he, hne]) hs + +/-- Version for the three-seed sample space used in the tree construction. +There are `m³` samples, and a protected cell occurs in at most `m` of them. -/ +theorem exists_agreement_three_seed + {Cell : Type uCell} {Value : Type uValue} [Fintype Cell] [DecidableEq Value] + (m : ℕ) (hm : 0 < m) (A B : Cell → Value) + (selected : (Fin m × Fin m × Fin m) → Cell → Prop) + (relevant : Cell → Prop) [DecidableRel selected] [DecidablePred relevant] + (hbound : ∀ e, relevant e → + (Finset.univ.filter (fun ω => selected ω e)).card ≤ m) + (hsmall : (Finset.univ.filter (fun e => A e ≠ B e)).card < m ^ 2) : + ∃ ω, ∀ e, relevant e → selected ω e → A e = B e := by + apply exists_agreement_of_changed_card_lt A B selected relevant m + · simpa using Nat.mul_pos hm (Nat.mul_pos hm hm) + · intro e he + calc + (Finset.univ.filter (fun ω => selected ω e)).card * m ^ 2 + ≤ m * m ^ 2 := Nat.mul_le_mul_right _ (hbound e he) + _ = Fintype.card (Fin m × Fin m × Fin m) := by + simp [pow_two] + · exact hsmall + +/-- Contrapositive form: if every sample forces a changed protected cell, +then at least `m²` entries have changed. -/ +theorem sq_le_changed_card_of_forcing + {Ω : Type uOmega} {Cell : Type uCell} {Value : Type uValue} [Fintype Ω] [Fintype Cell] [DecidableEq Value] + (A B : Cell → Value) (selected : Ω → Cell → Prop) + (relevant : Cell → Prop) [DecidableRel selected] [DecidablePred relevant] + (m : ℕ) (hΩ : 0 < Fintype.card Ω) + (hbound : ∀ e, relevant e → + (Finset.univ.filter (fun ω => selected ω e)).card * m ^ 2 ≤ Fintype.card Ω) + (hforcing : ∀ ω, ∃ e, relevant e ∧ selected ω e ∧ A e ≠ B e) : + m ^ 2 ≤ (Finset.univ.filter (fun e => A e ≠ B e)).card := by + by_contra h + obtain ⟨ω, hω⟩ := exists_agreement_of_changed_card_lt A B selected relevant m + hΩ hbound (Nat.lt_of_not_ge h) + obtain ⟨e, he, hs, hne⟩ := hforcing ω + exact hne (hω e he hs) + +end Problem348.Sampling + +end OAI diff --git a/lean/OAI/Combinatorics/MatrixRemoval/SamplingDistance.lean b/lean/OAI/Combinatorics/MatrixRemoval/SamplingDistance.lean new file mode 100644 index 0000000000000000000000000000000000000000..98927fb0fe1d495b91e45293f56cfa3121209997 --- /dev/null +++ b/lean/OAI/Combinatorics/MatrixRemoval/SamplingDistance.lean @@ -0,0 +1,84 @@ +import OAI.Combinatorics.MatrixRemoval.Model +import OAI.Combinatorics.MatrixRemoval.SamplingAvoidance + +namespace OAI + +/-! +# From sampled protected cells to arbitrary-repair distance + +The guard sets comprise only cells that the path proof requires to stay +unchanged. The hypotheses do not require preservation of every +variable-variable entry or of an original copy of the pattern. +-/ + +universe uOmega uCell + +noncomputable section + +namespace Problem348.Sampling + +/-- A sparse family of guards with a deterministic obstruction forces a lower +bound on every repair to an `H`-free matrix. The pattern may be arbitrary. -/ +theorem hammingDistance_ge_of_guard_sampling + {k n : ℕ} {Ω : Type uOmega} [Fintype Ω] + (H : BinaryMatrix k) (A B : BinaryMatrix n) + (guard : Ω → Finset (Fin n × Fin n)) (m : ℕ) + (hΩ : 0 < Fintype.card Ω) + (hbound : ∀ e, + (Finset.univ.filter (fun ω => e ∈ guard ω)).card * m ^ 2 ≤ Fintype.card Ω) + (hforce : ∀ ω, + (∀ e ∈ guard ω, A e.1 e.2 = B e.1 e.2) → ¬ HFree H B) + (hfree : HFree H B) : m ^ 2 ≤ hammingDistance A B := by + classical + by_contra h + have hsmall : + (Finset.univ.filter (fun e : Fin n × Fin n => A e.1 e.2 ≠ B e.1 e.2)).card + < m ^ 2 := by + simpa only [hammingDistance] using Nat.lt_of_not_ge h + obtain ⟨ω, hω⟩ := exists_agreement_of_changed_card_lt + (fun e : Fin n × Fin n => A e.1 e.2) + (fun e : Fin n × Fin n => B e.1 e.2) + (fun ω e => e ∈ guard ω) (fun _ => True) m hΩ + (fun e _ => hbound e) hsmall + exact hforce ω (fun e he => hω e True.intro he) hfree + +/-- The three-seed specialization: a guard uses each cell in at most `m` +of the `m³` samples. Therefore no `H`-free repair changes fewer than `m²` +entries. -/ +theorem hammingDistance_ge_of_three_seed_guards + {k n : ℕ} (m : ℕ) (hm : 0 < m) + (H : BinaryMatrix k) (A B : BinaryMatrix n) + (guard : (Fin m × Fin m × Fin m) → Finset (Fin n × Fin n)) + (hbound : ∀ e, (Finset.univ.filter (fun ω => e ∈ guard ω)).card ≤ m) + (hforce : ∀ ω, + (∀ e ∈ guard ω, A e.1 e.2 = B e.1 e.2) → ¬ HFree H B) + (hfree : HFree H B) : m ^ 2 ≤ hammingDistance A B := by + apply hammingDistance_ge_of_guard_sampling H A B guard m + · simpa using Nat.mul_pos hm (Nat.mul_pos hm hm) + · intro e + calc + (Finset.univ.filter (fun ω => e ∈ guard ω)).card * m ^ 2 + ≤ m * m ^ 2 := Nat.mul_le_mul_right _ (hbound e) + _ = Fintype.card (Fin m × Fin m × Fin m) := by simp [pow_two] + · exact hforce + · exact hfree + +/-- A guard-frequency estimate can be obtained from a larger set of protected +selected cells. This is useful when the deterministic path proof uses just a +subset of all selected anchor, dummy, and root incidences. -/ +theorem guard_frequency_le {Ω : Type uOmega} {Cell : Type uCell} [Fintype Ω] [DecidableEq Cell] + (guard : Ω → Finset Cell) (selected : Ω → Cell → Prop) + [DecidableRel selected] + (hsub : ∀ ω e, e ∈ guard ω → selected ω e) (e : Cell) : + (Finset.univ.filter (fun ω => e ∈ guard ω)).card ≤ + (Finset.univ.filter (fun ω => selected ω e)).card := by + classical + apply Finset.card_le_card + intro ω hω + exact Finset.mem_filter.mpr ⟨Finset.mem_univ _, hsub ω e (Finset.mem_filter.mp hω).2⟩ + +end Problem348.Sampling + +end + +end OAI diff --git a/lean/OAI/Combinatorics/MatrixRemoval/SelectedAnchorSparsity.lean b/lean/OAI/Combinatorics/MatrixRemoval/SelectedAnchorSparsity.lean new file mode 100644 index 0000000000000000000000000000000000000000..9b2b4da6dd1cd7bf826b0b3a3c207bffc291d32c --- /dev/null +++ b/lean/OAI/Combinatorics/MatrixRemoval/SelectedAnchorSparsity.lean @@ -0,0 +1,196 @@ +import OAI.Combinatorics.MatrixRemoval.HostModeIncidence + +namespace OAI + +/-! +Sparsity for arbitrary selected raw host positions. +Only the selected core is assumed to consist of anchors; outside it the +selection may include variable and dummy positions. +-/ +universe uI + +noncomputable section +namespace Problem348.Construction.SelectedAnchors + +/-- Anchor mode and group, forgetting the irrelevant within-group offset. -/ +def label {h : ℕ} : Position h → Option (Mode h × Fin 64) + | .inl a => some (a.1, a.2.1) + | .inr _ => none + +/-- The mode classifier used by the abstract rigidity theorem. -/ +def mode {h : ℕ} : Position h → Option (Mode h) + | .inl a => some a.1 + | .inr _ => none + +/-- Group uniqueness only concerns anchors, so it permits many nonanchors. -/ +def GroupInjective {I : Type uI} {h : ℕ} (f : I → Position h) : Prop := + ∀ i j a b, f i = .inl a → f j = .inl b → + a.1 = b.1 → a.2.1 = b.2.1 → i = j + +/-- Restrict the actual sparse-row theorem to an arbitrary selected anchor core. -/ +theorem variable_row_core_card_le_four {I : Type uI} [DecidableEq I] {h : ℕ} + (f : I → Position h) (S : Finset I) (v : VariablePosition h) + (hanchor : ∀ i ∈ S, ∃ a, f i = .inl a) + (hgroups : Set.InjOn (fun i => label (f i)) (S : Set I)) : + (S.filter (fun i => host (.inr (.inl v)) (f i) = true)).card ≤ 4 := by + classical + let a : S → AnchorPosition h := fun i => Classical.choose (hanchor i i.property) + have ha (i : S) : f i = .inl (a i) := Classical.choose_spec (hanchor i i.property) + have hg : Set.InjOn (fun i : S => ((a i).1, (a i).2.1)) S.attach := by + intro i hi j hj hij + apply Subtype.ext + apply hgroups i.property j.property + simp only [ha, label] + exact congrArg some hij + have hb := card_variable_row_anchor_ones_le_four v S.attach a hg + simp only [← ha] at hb + have he := congrArg Finset.card + (Finset.filter_attach (fun i : I => host (.inr (.inl v)) (f i) = true) S) + simp only [Finset.card_map, Finset.card_attach] at he + exact he ▸ hb + +/-- The transpose restriction to a selected anchor core. -/ +theorem variable_col_core_card_le_four {I : Type uI} [DecidableEq I] {h : ℕ} + (f : I → Position h) (S : Finset I) (v : VariablePosition h) + (hanchor : ∀ i ∈ S, ∃ a, f i = .inl a) + (hgroups : Set.InjOn (fun i => label (f i)) (S : Set I)) : + (S.filter (fun i => host (f i) (.inr (.inl v)) = true)).card ≤ 4 := by + classical + let a : S → AnchorPosition h := fun i => Classical.choose (hanchor i i.property) + have ha (i : S) : f i = .inl (a i) := Classical.choose_spec (hanchor i i.property) + have hg : Set.InjOn (fun i : S => ((a i).1, (a i).2.1)) S.attach := by + intro i hi j hj hij + apply Subtype.ext + apply hgroups i.property j.property + simp only [ha, label] + exact congrArg some hij + have hb := card_variable_col_anchor_ones_le_four v S.attach a hg + simp only [← ha] at hb + have he := congrArg Finset.card + (Finset.filter_attach (fun i : I => host (f i) (.inr (.inl v)) = true) S) + simp only [Finset.card_map, Finset.card_attach] at he + exact he ▸ hb + +/-- The structural group-uniqueness property gives label injectivity on a core. -/ +theorem GroupInjective.injOn {I : Type uI} {h : ℕ} {f : I → Position h} + (hf : GroupInjective f) (S : Set I) + (hanchor : ∀ i ∈ S, ∃ a, f i = .inl a) : + Set.InjOn (fun i => label (f i)) S := by + intro i hi j hj hij + obtain ⟨a, ha⟩ := hanchor i hi + obtain ⟨b, hb⟩ := hanchor j hj + have hab : (a.1, a.2.1) = (b.1, b.2.1) := by + simpa only [ha, hb, label, Option.some.injEq] using hij + exact hf i j a b ha hb (congrArg (fun x : Mode h × Fin 64 => x.1) hab) + (congrArg (fun x : Mode h × Fin 64 => x.2) hab) + +/-- Exact nonanchor-row unit hypothesis of the abstract rigidity theorem. -/ +theorem nonanchor_row_unit {I : Type uI} {h : ℕ} + (f : I → Position h) (hf : GroupInjective f) + (r : VariablePosition h ⊕ Fin (2 ^ h)) (i j : I) (t : Mode h) + (hi : mode (f i) = some t) (hj : mode (f j) = some t) + (hri : host (.inr r) (f i) = true) + (hrj : host (.inr r) (f j) = true) : i = j := by + cases hfi : f i with + | inr x => simp [hfi, mode] at hi + | inl a => + cases hfj : f j with + | inr x => simp [hfj, mode] at hj + | inl b => + have hm : a.1 = b.1 := by simpa [hfi, hfj, mode] using hi.trans hj.symm + have hg : a.2.1 = b.2.1 := row_anchor_ones_unique_group r a b + (by simpa [hfi] using hri) (by simpa [hfj] using hrj) hm + exact hf i j a b hfi hfj hm hg + +/-- Exact nonanchor-column unit hypothesis of the abstract rigidity theorem. -/ +theorem nonanchor_col_unit {I : Type uI} {h : ℕ} + (f : I → Position h) (hf : GroupInjective f) + (c : VariablePosition h ⊕ Fin (2 ^ h)) (i j : I) (t : Mode h) + (hi : mode (f i) = some t) (hj : mode (f j) = some t) + (hci : host (f i) (.inr c) = true) + (hcj : host (f j) (.inr c) = true) : i = j := by + cases hfi : f i with + | inr x => simp [hfi, mode] at hi + | inl a => + cases hfj : f j with + | inr x => simp [hfj, mode] at hj + | inl b => + have hm : a.1 = b.1 := by simpa [hfi, hfj, mode] using hi.trans hj.symm + have hg : a.2.1 = b.2.1 := col_anchor_ones_unique_group c a b + (by simpa [hfi] using hci) (by simpa [hfj] using hcj) hm + exact hf i j a b hfi hfj hm hg + +/-- The raw dummy-position predicate. -/ +def IsDummy {h : ℕ} (p : Position h) : Prop := + ∃ d, p = .inr (.inr d) + +/-- A mode-free non-dummy position is a variable position. -/ +theorem variable_of_mode_none_not_dummy {h : ℕ} (p : Position h) + (hm : mode p = none) (hd : ¬ IsDummy p) : + ∃ v, p = .inr (.inl v) := by + rcases p with a | (v | d) + · simp [mode] at hm + · exact ⟨v, rfl⟩ + · exact False.elim (hd ⟨d, rfl⟩) + +/-- The exact variable-column sparsity input of one-sided anchor rigidity. -/ +theorem sparse_column_of_mode_none {I : Type uI} [DecidableEq I] {h : ℕ} + (f : I → Position h) (S : Finset I) (p : Position h) + (hanchor : ∀ i ∈ S, ∃ a, f i = .inl a) + (hgroups : GroupInjective f) + (hm : mode p = none) (hd : ¬ IsDummy p) : + (S.filter (fun i => host (f i) p = true)).card ≤ 4 := by + obtain ⟨v, rfl⟩ := variable_of_mode_none_not_dummy p hm hd + exact variable_col_core_card_le_four f S v hanchor + (hgroups.injOn S hanchor) + +/-- The axis-transposed sparsity input. -/ +theorem sparse_row_of_mode_none {I : Type uI} [DecidableEq I] {h : ℕ} + (f : I → Position h) (S : Finset I) (p : Position h) + (hanchor : ∀ i ∈ S, ∃ a, f i = .inl a) + (hgroups : GroupInjective f) + (hm : mode p = none) (hd : ¬ IsDummy p) : + (S.filter (fun i => host p (f i) = true)).card ≤ 4 := by + obtain ⟨v, rfl⟩ := variable_of_mode_none_not_dummy p hm hd + exact variable_row_core_card_le_four f S v hanchor + (hgroups.injOn S hanchor) + +/-- An anchor-anchor one forces equality of the two mode labels. -/ +theorem cross_mode {h : ℕ} (r c : Position h) (t u : Mode h) + (hr : mode r = some t) (hc : mode c = some u) + (hentry : host r c = true) : t = u := by + rcases r with a | r + · rcases c with b | c + · have hat : a.1 = t := by simpa [mode] using hr + have hbu : b.1 = u := by simpa [mode] using hc + by_contra htu + have hab : a.1 ≠ b.1 := by simpa [hat, hbu] using htu + simp [host, hab] at hentry + · simp [mode] at hc + · simp [mode] at hr + +/-- Raw-position form matching the abstract nonanchor-row unit hypothesis. -/ +theorem nonanchor_row_unit_of_mode_none {I : Type uI} {h : ℕ} + (f : I → Position h) (hf : GroupInjective f) (r : Position h) + (hr : mode r = none) (i j : I) (t : Mode h) + (hi : mode (f i) = some t) (hj : mode (f j) = some t) + (hri : host r (f i) = true) (hrj : host r (f j) = true) : i = j := by + rcases r with a | r + · simp [mode] at hr + · exact nonanchor_row_unit f hf r i j t hi hj hri hrj + +/-- Raw-position form matching the abstract nonanchor-column unit hypothesis. -/ +theorem nonanchor_col_unit_of_mode_none {I : Type uI} {h : ℕ} + (f : I → Position h) (hf : GroupInjective f) (c : Position h) + (hc : mode c = none) (i j : I) (t : Mode h) + (hi : mode (f i) = some t) (hj : mode (f j) = some t) + (hci : host (f i) c = true) (hcj : host (f j) c = true) : i = j := by + rcases c with a | c + · simp [mode] at hc + · exact nonanchor_col_unit f hf c i j t hi hj hci hcj + +end Problem348.Construction.SelectedAnchors + +end + +end OAI diff --git a/lean/OAI/Combinatorics/MatrixRemoval/SequenceAssembly.lean b/lean/OAI/Combinatorics/MatrixRemoval/SequenceAssembly.lean new file mode 100644 index 0000000000000000000000000000000000000000..35044043e4bee4ce0fce38cba00e48ec479be1dd --- /dev/null +++ b/lean/OAI/Combinatorics/MatrixRemoval/SequenceAssembly.lean @@ -0,0 +1,94 @@ +import OAI.Combinatorics.MatrixRemoval.Model + +namespace OAI + +/-! +Assembly of the counterexample sequence from two integer bounds. +The existence of a host satisfying both bounds is an explicit hypothesis. +-/ + +noncomputable section + +namespace Problem348.SequenceAssembly + +/-- Integer certificates for one candidate host. This does not assert existence. -/ +def HostBounds {n : ℕ} (A : BinaryMatrix n) (m : ℕ) : Prop := + (∀ B : BinaryMatrix n, HFree fixedH B → m ^ 2 ≤ hammingDistance A B) ∧ + copyCount fixedH A ≤ m * n ^ 130 + +/-- The sentinel value in `fixedMinEdits` respects every lower bound at most n². -/ +theorem fixedMinEdits_ge_of_repairs {n q : ℕ} (A : BinaryMatrix n) + (hq : q ≤ n * n) + (hrep : ∀ B : BinaryMatrix n, HFree fixedH B → q ≤ hammingDistance A B) : + q ≤ fixedMinEdits A := by + classical + unfold fixedMinEdits + apply Finset.le_min' + intro k hk + obtain ⟨B, _, rfl⟩ := Finset.mem_image.mp hk + split_ifs with hB + · exact hrep B hB + · omega + +/-- Normalize an arbitrary-repair certificate at order n=d*m. -/ +theorem fixedDistance_ge_of_integer_bound {d m : ℕ} + (hd : 0 < d) (hm : 0 < m) (A : BinaryMatrix (d * m)) + (hrep : ∀ B : BinaryMatrix (d * m), HFree fixedH B → + m ^ 2 ≤ hammingDistance A B) : + 1 / ((d : ℝ) ^ 2) ≤ fixedDistance A := by + have hmn : m ≤ d * m := by nlinarith + have hq : m ^ 2 ≤ (d * m) * (d * m) := by nlinarith + have hmin := fixedMinEdits_ge_of_repairs A hq hrep + have hdR : (0 : ℝ) < d := by exact_mod_cast hd + have hmR : (0 : ℝ) < m := by exact_mod_cast hm + have hminR : (m : ℝ) ^ 2 ≤ (fixedMinEdits A : ℝ) := by exact_mod_cast hmin + unfold fixedDistance + push_cast + apply (le_div_iff₀ (by positivity : (0 : ℝ) < ((d : ℝ) * m) ^ 2)).2 + calc + 1 / ((d : ℝ) ^ 2) * ((d : ℝ) * m) ^ 2 = (m : ℝ) ^ 2 := by + field_simp + _ ≤ (fixedMinEdits A : ℝ) := hminR + +/-- Normalize the localized-copy integer estimate at order n=d*m. -/ +theorem copyDensity_le_of_integer_bound {d m : ℕ} + (hd : 0 < d) (hm : 0 < m) (A : BinaryMatrix (d * m)) + (hcount : copyCount fixedH A ≤ m * (d * m) ^ 130) : + (copyCount fixedH A : ℝ) / (((d * m : ℕ) : ℝ) ^ 132) ≤ + (1 / ((d : ℝ) ^ 2)) * (1 / (m : ℝ)) := by + have hdR : (0 : ℝ) < d := by exact_mod_cast hd + have hmR : (0 : ℝ) < m := by exact_mod_cast hm + have hcountR : (copyCount fixedH A : ℝ) ≤ + (m : ℝ) * ((d : ℝ) * m) ^ 130 := by exact_mod_cast hcount + push_cast + apply (div_le_iff₀ (by positivity : (0 : ℝ) < ((d : ℝ) * m) ^ 132)).2 + calc + (copyCount fixedH A : ℝ) ≤ (m : ℝ) * ((d : ℝ) * m) ^ 130 := hcountR + _ = (1 / ((d : ℝ) ^ 2)) * (1 / (m : ℝ)) * ((d : ℝ) * m) ^ 132 := by + field_simp + +/-- The counterexample sequence follows from the integer bounds. -/ +theorem counterexample_sequence_of_integer_bounds + (hcert : ∀ h : ℕ, 1 ≤ h → + let d : ℕ := 386 * h + 2 + let n : ℕ := d * 2 ^ h + ∃ A : BinaryMatrix n, HostBounds A (2 ^ h)) : + ∀ h : ℕ, 1 ≤ h → + let d : ℕ := 386 * h + 2 + let n : ℕ := d * 2 ^ h + ∃ A : BinaryMatrix n, + fixedDistance A ≥ 1 / ((d : ℝ) ^ 2) ∧ + (copyCount fixedH A : ℝ) / ((n : ℝ) ^ 132) ≤ + (1 / ((d : ℝ) ^ 2)) * (1 / ((2 : ℝ) ^ h)) := by + intro h hh + obtain ⟨A, hrep, hcount⟩ := hcert h hh + refine ⟨A, fixedDistance_ge_of_integer_bound (by omega) + (pow_pos (by decide) _) A hrep, ?_⟩ + simpa using copyDensity_le_of_integer_bound (by omega) + (pow_pos (by decide) _) A hcount + +end Problem348.SequenceAssembly + +end + +end OAI diff --git a/lean/OAI/Combinatorics/MatrixRemoval/ThreeSeedSampling.lean b/lean/OAI/Combinatorics/MatrixRemoval/ThreeSeedSampling.lean new file mode 100644 index 0000000000000000000000000000000000000000..97c001b3acb4e7dd5528dafa84938bf303bd5224 --- /dev/null +++ b/lean/OAI/Combinatorics/MatrixRemoval/ThreeSeedSampling.lean @@ -0,0 +1,219 @@ +import Mathlib + +namespace OAI + +/-! +# Three-seed sampling for the tree-matrix repair argument + +Choices in different groups on the same axis need not be independent. +Three uniform seeds suffice: a common leaf, a row seed and a column seed. +The equal-fiber calculation gives uniform marginals. +-/ + +universe uX uY uZ + +namespace Problem348.TreeSampling + +/-- Replace the within-block coordinate of a leaf by that of a second seed. -/ +def mix {a b : ℕ} (z u : Fin (a * b)) : Fin (a * b) := + finProdFinEquiv ((finProdFinEquiv.symm z).1, + (finProdFinEquiv.symm u).2) + +@[simp] theorem mix_div {a b : ℕ} (z u : Fin (a * b)) : + (finProdFinEquiv.symm (mix z u)).1 = + (finProdFinEquiv.symm z).1 := by + simp [mix] + +@[simp] theorem mix_mod {a b : ℕ} (z u : Fin (a * b)) : + (finProdFinEquiv.symm (mix z u)).2 = + (finProdFinEquiv.symm u).2 := by + simp [mix] + +/-- The output of the mixer and the two unused coordinates determine both seeds. -/ +def splitMix {a b : ℕ} : + (Fin (a * b) × Fin (a * b)) ≃ + (Fin (a * b) × (Fin b × Fin a)) where + toFun p := (mix p.1 p.2, + ((finProdFinEquiv.symm p.1).2, (finProdFinEquiv.symm p.2).1)) + invFun p := + (finProdFinEquiv ((finProdFinEquiv.symm p.1).1, p.2.1), + finProdFinEquiv (p.2.2, (finProdFinEquiv.symm p.1).2)) + left_inv p := by + rcases p with ⟨z,u⟩ + simp only [mix, Equiv.symm_apply_apply] + exact Prod.ext (finProdFinEquiv.apply_symm_apply z) + (finProdFinEquiv.apply_symm_apply u) + right_inv p := by + rcases p with ⟨x,r,s⟩ + simp only [mix, Equiv.symm_apply_apply] + exact Prod.ext (finProdFinEquiv.apply_symm_apply x) rfl + +/-- A first-coordinate fiber of a product decomposition is the second factor. -/ +def fiberOfEquiv {X : Type uX} {Y : Type uY} {Z : Type uZ} (e : X ≃ Y × Z) (y : Y) : + {x : X // (e x).1 = y} ≃ Z where + toFun x := (e x.1).2 + invFun z := ⟨e.symm (y, z), by simp⟩ + left_inv x := by + apply Subtype.ext + apply e.injective + simp only [Equiv.apply_symm_apply] + exact Prod.ext x.property.symm rfl + right_inv z := by simp + +/-- Every level-class position occurs equally often in the pair of seeds. -/ +theorem card_mix_fiber {a b : ℕ} (x : Fin (a * b)) : + Fintype.card {p : Fin (a * b) × Fin (a * b) // mix p.1 p.2 = x} = + a * b := by + classical + calc + _ = Fintype.card (Fin b × Fin a) := + Fintype.card_congr (fiberOfEquiv (splitMix (a := a) (b := b)) x) + _ = _ := by simp [Nat.mul_comm] + +/-- The three seeds are the common leaf, an axis-one seed and an axis-two seed. -/ +abbrev Seeds (m : ℕ) := Fin m × (Fin m × Fin m) + +/-- A variable row and an anchor/dummy column, together with unused coordinates. -/ +def splitRow {a b : ℕ} : + Seeds (a * b) ≃ (Fin (a * b) × Fin (a * b)) × (Fin b × Fin a) where + toFun s := ((mix s.1 s.2.1, s.2.2), + ((finProdFinEquiv.symm s.1).2, (finProdFinEquiv.symm s.2.1).1)) + invFun p := (finProdFinEquiv ((finProdFinEquiv.symm p.1.1).1, p.2.1), + (finProdFinEquiv (p.2.2, (finProdFinEquiv.symm p.1.1).2), p.1.2)) + left_inv s := by + rcases s with ⟨z,u,v⟩ + simp only [mix, Equiv.symm_apply_apply] + exact Prod.ext (finProdFinEquiv.apply_symm_apply z) + (Prod.ext (finProdFinEquiv.apply_symm_apply u) rfl) + right_inv p := by + rcases p with ⟨⟨x,y⟩,r,t⟩ + simp only [mix, Equiv.symm_apply_apply] + exact Prod.ext (Prod.ext (finProdFinEquiv.apply_symm_apply x) rfl) rfl + +/-- An anchor/dummy row and a variable column, with the unused coordinates. -/ +def splitColumn {a b : ℕ} : + Seeds (a * b) ≃ (Fin (a * b) × Fin (a * b)) × (Fin b × Fin a) where + toFun s := ((s.2.1, mix s.1 s.2.2), + ((finProdFinEquiv.symm s.1).2, (finProdFinEquiv.symm s.2.2).1)) + invFun p := (finProdFinEquiv ((finProdFinEquiv.symm p.1.2).1, p.2.1), + (p.1.1, finProdFinEquiv (p.2.2, (finProdFinEquiv.symm p.1.2).2))) + left_inv s := by + rcases s with ⟨z,u,v⟩ + simp only [mix, Equiv.symm_apply_apply] + exact Prod.ext (finProdFinEquiv.apply_symm_apply z) + (Prod.ext rfl (finProdFinEquiv.apply_symm_apply v)) + right_inv p := by + rcases p with ⟨⟨x,y⟩,r,t⟩ + simp only [mix, Equiv.symm_apply_apply] + exact Prod.ext (Prod.ext rfl (finProdFinEquiv.apply_symm_apply y)) rfl + +/-- Two independent axis seeds, with the common-leaf coordinate unused. -/ +def splitBoth {m : ℕ} : Seeds m ≃ (Fin m × Fin m) × Fin m where + toFun s := (s.2, s.1) + invFun p := (p.2, p.1) + left_inv _ := rfl + right_inv _ := rfl + +/-- Exact protected-cell multiplicity when the row is variable. -/ +theorem card_row_fiber {a b : ℕ} (x y : Fin (a * b)) : + Fintype.card {s : Seeds (a * b) // (mix s.1 s.2.1, s.2.2) = (x,y)} = + a * b := by + classical + calc + _ = Fintype.card (Fin b × Fin a) := + Fintype.card_congr (fiberOfEquiv (splitRow (a := a) (b := b)) (x,y)) + _ = _ := by simp [Nat.mul_comm] + +/-- Exact protected-cell multiplicity when the column is variable. -/ +theorem card_column_fiber {a b : ℕ} (x y : Fin (a * b)) : + Fintype.card {s : Seeds (a * b) // (s.2.1, mix s.1 s.2.2) = (x,y)} = + a * b := by + classical + calc + _ = Fintype.card (Fin b × Fin a) := + Fintype.card_congr (fiberOfEquiv (splitColumn (a := a) (b := b)) (x,y)) + _ = _ := by simp [Nat.mul_comm] + +/-- Exact multiplicity for two anchor/dummy positions or two root positions. -/ +theorem card_both_fiber {m : ℕ} (x y : Fin m) : + Fintype.card {s : Seeds m // s.2 = (x,y)} = m := by + classical + calc + _ = Fintype.card (Fin m) := + Fintype.card_congr (fiberOfEquiv (splitBoth (m := m)) (x,y)) + _ = _ := Fintype.card_fin m + +@[simp] theorem card_seeds (m : ℕ) : Fintype.card (Seeds m) = m ^ 3 := by + simp [Seeds, pow_succ, Nat.mul_assoc] + +@[simp] theorem mix_val {a b : ℕ} (z u : Fin (a * b)) : + (mix z u).val = u.val % b + b * (z.val / b) := rfl + +/-- The two coordinates of a depth-i level class multiply to the leaf count. -/ +theorem level_factor {h i : ℕ} (hi : i ≤ h) : + 2 ^ i * 2 ^ (h-i) = 2 ^ h := by + rw [← pow_add, Nat.add_sub_of_le hi] + +/-- Transport the mixer to a size presented by an equality rather than a product. -/ +def mixCast {a b m : ℕ} (hm : a * b = m) (z u : Fin m) : Fin m := + Fin.cast hm (mix (Fin.cast hm.symm z) (Fin.cast hm.symm u)) + +@[simp] theorem card_mixCast_row_fiber {a b m : ℕ} (hm : a*b=m) (x y : Fin m) : + Fintype.card {s : Seeds m // (mixCast hm s.1 s.2.1, s.2.2) = (x,y)} = m := by + subst m + exact card_row_fiber x y + +@[simp] theorem card_mixCast_column_fiber {a b m : ℕ} (hm : a*b=m) (x y : Fin m) : + Fintype.card {s : Seeds m // (s.2.1, mixCast hm s.1 s.2.2) = (x,y)} = m := by + subst m + exact card_column_fiber x y + +/-- The class-coordinate selected at depth i by a common leaf and an axis seed. -/ +def atLevel (h i : ℕ) (hi : i ≤ h) (z u : Fin (2 ^ h)) : Fin (2 ^ h) := + mixCast (level_factor hi) z u + +@[simp] theorem atLevel_val (h i : ℕ) (hi : i ≤ h) (z u : Fin (2 ^ h)) : + (atLevel h i hi z u).val = + u.val % (2 ^ (h-i)) + (2 ^ (h-i)) * (z.val / (2 ^ (h-i))) := rfl + +/-- Root selections depend only on the corresponding axis seed. -/ +@[simp] theorem atLevel_root (h : ℕ) (z u : Fin (2 ^ h)) : + atLevel h 0 (Nat.zero_le h) z u = u := by + apply Fin.ext + simp [Nat.mod_eq_of_lt u.isLt, Nat.div_eq_of_lt z.isLt] + +/-- Both signs at the leaf select the same common leaf, regardless of axis seed. -/ +@[simp] theorem atLevel_leaf (h : ℕ) (z u : Fin (2 ^ h)) : + atLevel h h le_rfl z u = z := by + apply Fin.ext + simp [Nat.mod_one] + +/-- Every selected position lies in the ancestor block of the common leaf. -/ +theorem atLevel_node (h i : ℕ) (hi : i ≤ h) (z u : Fin (2 ^ h)) : + (atLevel h i hi z u).val / (2 ^ (h-i)) = z.val / (2 ^ (h-i)) := by + rw [atLevel_val, Nat.add_mul_div_left _ _ (by positivity)] + rw [Nat.div_eq_of_lt (Nat.mod_lt _ (by positivity)), Nat.zero_add] + +/-- The sampler's node at a child level has the prescribed parent. -/ +theorem ancestor_parent (h i z : ℕ) (hi : i < h) : + (z / 2 ^ (h - (i+1))) / 2 = z / 2 ^ (h-i) := by + rw [Nat.div_div_eq_div_mul] + congr 1 + have he : h-i = (h-(i+1))+1 := by omega + rw [he, pow_succ] + +/-- Every variable-row / anchor-column cell has exactly m seed preimages. -/ +theorem card_atLevel_row_fiber (h i : ℕ) (hi : i ≤ h) (x y : Fin (2^h)) : + Fintype.card {s : Seeds (2^h) // + (atLevel h i hi s.1 s.2.1, s.2.2) = (x,y)} = 2^h := + card_mixCast_row_fiber (level_factor hi) x y + +/-- Every anchor-row / variable-column cell has exactly m seed preimages. -/ +theorem card_atLevel_column_fiber (h i : ℕ) (hi : i ≤ h) (x y : Fin (2^h)) : + Fintype.card {s : Seeds (2^h) // + (s.2.1, atLevel h i hi s.1 s.2.2) = (x,y)} = 2^h := + card_mixCast_column_fiber (level_factor hi) x y + +end Problem348.TreeSampling + +end OAI diff --git a/lean/OAI/Combinatorics/MatrixRemoval/TreePositions.lean b/lean/OAI/Combinatorics/MatrixRemoval/TreePositions.lean new file mode 100644 index 0000000000000000000000000000000000000000..70ee853de89427ce27102b3402039911d3bf648e --- /dev/null +++ b/lean/OAI/Combinatorics/MatrixRemoval/TreePositions.lean @@ -0,0 +1,266 @@ +import Mathlib + +namespace OAI + +/-! +Concrete depth-first orders for variable positions. +Each class has 2^h positions. Classes 2*i and 2*i+1 are respectively +plus and minus at i simp_all [leafKey, earlyKey, lateKey] + +@[simp] theorem keyCoordinate_orderKey (column : Bool) (h : ℕ) + (p : VariablePosition h) : keyCoordinate (orderKey column h p) = p.2.val := by + simp only [orderKey] + split_ifs <;> rfl + +theorem orderKey_injective (column : Bool) (h : ℕ) : + Function.Injective (orderKey column h) := by + intro p q hpq + apply Prod.ext + · apply Fin.ext + simpa using congrArg keyClass hpq + · apply Fin.ext + simpa using congrArg keyCoordinate hpq + +/-- Explicit order structures, not global instances: the same raw positions +carry different row and column orders. -/ +abbrev positionOrder (column : Bool) (h : ℕ) : LinearOrder (VariablePosition h) := + LinearOrder.lift' (orderKey column h) (orderKey_injective column h) + +@[simp] theorem card_variablePosition (h : ℕ) : + Fintype.card (VariablePosition h) = (2 * h + 1) * 2 ^ h := by + simp [VariablePosition] + +end Problem348.TreePositions + +namespace Problem348.TreePositions + +theorem key_lt_iff_endpoint_le_of_tie_lt + (a b phase t u cls₁ cls₂ x y : ℕ) (htu : t < u) : + key a phase t cls₁ x < key b phase u cls₂ y ↔ a ≤ b := by + simp [key, Prod.Lex.lt_iff, htu, ne_of_lt htu, le_iff_lt_or_eq] + +theorem lateKey_child_lt_parent (b r p a cls₁ cls₂ x y : ℕ) (hb : 0 < b) : + lateKey r b p cls₁ x < lateKey (r + 1) (2 * b) a cls₂ y ↔ p / 2 ≤ a := by + rw [lateKey, lateKey, key_lt_iff_endpoint_le_of_tie_lt _ _ _ _ _ _ _ _ _ + (Nat.lt_succ_self r)] + have heq : 2 * (a + 1) * (2 * b) = (2 * (2 * a + 2)) * b := by ring + rw [heq, mul_le_mul_iff_left₀ hb] + omega + +theorem earlyKey_parent_lt_child (b i p a cls₁ cls₂ x y : ℕ) (hb : 0 < b) : + earlyKey i (2 * b) a cls₁ x < earlyKey (i + 1) b p cls₂ y ↔ a ≤ p / 2 := by + rw [earlyKey, earlyKey, key_lt_iff_endpoint_le_of_tie_lt _ _ _ _ _ _ _ _ _ + (Nat.lt_succ_self i)] + have heq : 2 * a * (2 * b) = (4 * a) * b := by ring + rw [heq, mul_le_mul_iff_left₀ hb] + omega + +end Problem348.TreePositions + +namespace Problem348.TreePositions + +theorem leafKey_lt_lateKey_parent (h r p a cls y : ℕ) : + leafKey h p < lateKey r 2 a cls y ↔ p / 2 ≤ a := by + simp [leafKey, lateKey, key, Prod.Lex.lt_iff] + omega + +theorem earlyKey_parent_lt_leafKey (h i p a cls x : ℕ) : + earlyKey i 2 a cls x < leafKey h p ↔ a ≤ p / 2 := by + simp only [earlyKey, leafKey, key, Prod.Lex.lt_iff, ofLex_toLex, + ] + omega + +/-- The plus class; at depth h this is the shared leaf class. -/ +def plusPos {h : ℕ} (i : ℕ) (hi : i ≤ h) (x : Fin (2 ^ h)) : VariablePosition h := + (⟨2 * i, by omega⟩, x) + +/-- The minus class, identified with the plus class exactly at the leaf. -/ +def minusPos {h : ℕ} (i : ℕ) (hi : i ≤ h) (x : Fin (2 ^ h)) : VariablePosition h := + (⟨if i = h then 2 * h else 2 * i + 1, by split_ifs <;> omega⟩, x) + +def node {h : ℕ} (i : ℕ) (x : Fin (2 ^ h)) : ℕ := x.val / 2 ^ (h - i) + +@[simp] theorem minusPos_leaf (h : ℕ) (x : Fin (2 ^ h)) : + minusPos h le_rfl x = plusPos h le_rfl x := by + simp [minusPos, plusPos] + +@[simp] theorem orderKey_leaf (column : Bool) (h : ℕ) (x : Fin (2 ^ h)) : + orderKey column h (plusPos h le_rfl x) = leafKey h x.val := by + simp [orderKey, plusPos] + +@[simp] theorem rowKey_leaf (h : ℕ) (x : Fin (2 ^ h)) : + rowKey h (plusPos h le_rfl x) = leafKey h x.val := + orderKey_leaf false h x + +@[simp] theorem columnKey_leaf (h : ℕ) (x : Fin (2 ^ h)) : + columnKey h (plusPos h le_rfl x) = leafKey h x.val := + orderKey_leaf true h x + +theorem rowKey_plus_internal {h i : ℕ} (hi : i < h) (x : Fin (2 ^ h)) : + rowKey h (plusPos i (Nat.le_of_lt hi) x) = + lateKey (h - i) (2 ^ (h - i)) (node i x) (2 * i) x.val := by + have hh : 2 * i ≠ 2 * h := by omega + simp [rowKey, orderKey, plusPos, hh, node] + +theorem columnKey_plus_internal {h i : ℕ} (hi : i < h) (x : Fin (2 ^ h)) : + columnKey h (plusPos i (Nat.le_of_lt hi) x) = + earlyKey i (2 ^ (h - i)) (node i x) (2 * i) x.val := by + have hh : 2 * i ≠ 2 * h := by omega + simp [columnKey, orderKey, plusPos, hh, node] + +theorem rowKey_minus_internal {h i : ℕ} (hi : i < h) (x : Fin (2 ^ h)) : + rowKey h (minusPos i (Nat.le_of_lt hi) x) = + earlyKey i (2 ^ (h - i)) (node i x) (2 * i + 1) x.val := by + have hh : 2 * i + 1 ≠ 2 * h := by omega + have hd : (2 * i + 1) / 2 = i := by omega + simp [rowKey, orderKey, minusPos, hh, hd, Nat.ne_of_lt hi, node] + +theorem columnKey_minus_internal {h i : ℕ} (hi : i < h) (x : Fin (2 ^ h)) : + columnKey h (minusPos i (Nat.le_of_lt hi) x) = + lateKey (h - i) (2 ^ (h - i)) (node i x) (2 * i + 1) x.val := by + have hh : 2 * i + 1 ≠ 2 * h := by omega + have hd : (2 * i + 1) / 2 = i := by omega + simp [columnKey, orderKey, minusPos, hh, hd, Nat.ne_of_lt hi, node] + +end Problem348.TreePositions + +namespace Problem348.TreePositions + +/-- The plus row-order equivalence, including shared leaves. -/ +theorem row_plus_child_lt_parent {h i : ℕ} (hi : i < h) + (x y : Fin (2 ^ h)) : + rowKey h (plusPos (i + 1) (by omega) x) < + rowKey h (plusPos i (Nat.le_of_lt hi) y) ↔ + node (i + 1) x / 2 ≤ node i y := by + by_cases he : i + 1 = h + · subst h + rw [rowKey_leaf, rowKey_plus_internal hi] + have hs : i + 1 - i = 1 := by omega + simp only [hs, pow_one] + simpa [node] using leafKey_lt_lateKey_parent (i + 1) 1 x.val + (node i y) (2 * i) y.val + · have hic : i + 1 < h := by omega + rw [rowKey_plus_internal hic, rowKey_plus_internal hi] + have hr : h - i = h - (i + 1) + 1 := by omega + have hb : 2 ^ (h - i) = 2 * 2 ^ (h - (i + 1)) := by + rw [hr, pow_succ] + omega + rw [hb, hr] + exact lateKey_child_lt_parent _ _ _ _ _ _ _ _ (by positivity) + +/-- The minus row-order equivalence, including shared leaves. -/ +theorem row_minus_parent_lt_child {h i : ℕ} (hi : i < h) + (x y : Fin (2 ^ h)) : + rowKey h (minusPos i (Nat.le_of_lt hi) y) < + rowKey h (minusPos (i + 1) (by omega) x) ↔ + node i y ≤ node (i + 1) x / 2 := by + by_cases he : i + 1 = h + · subst h + rw [minusPos_leaf, rowKey_leaf, rowKey_minus_internal hi] + have hs : i + 1 - i = 1 := by omega + simp only [hs, pow_one] + simpa [node] using earlyKey_parent_lt_leafKey (i + 1) i x.val + (node i y) (2 * i + 1) y.val + · have hic : i + 1 < h := by omega + rw [rowKey_minus_internal hic, rowKey_minus_internal hi] + have hr : h - i = h - (i + 1) + 1 := by omega + have hb : 2 ^ (h - i) = 2 * 2 ^ (h - (i + 1)) := by + rw [hr, pow_succ] + omega + rw [hb] + exact earlyKey_parent_lt_child _ _ _ _ _ _ _ _ (by positivity) + +/-- The plus column-order equivalence, including shared leaves. -/ +theorem column_plus_parent_lt_child {h i : ℕ} (hi : i < h) + (x y : Fin (2 ^ h)) : + columnKey h (plusPos i (Nat.le_of_lt hi) y) < + columnKey h (plusPos (i + 1) (by omega) x) ↔ + node i y ≤ node (i + 1) x / 2 := by + by_cases he : i + 1 = h + · subst h + rw [columnKey_leaf, columnKey_plus_internal hi] + have hs : i + 1 - i = 1 := by omega + simp only [hs, pow_one] + simpa [node] using earlyKey_parent_lt_leafKey (i + 1) i x.val + (node i y) (2 * i) y.val + · have hic : i + 1 < h := by omega + rw [columnKey_plus_internal hic, columnKey_plus_internal hi] + have hr : h - i = h - (i + 1) + 1 := by omega + have hb : 2 ^ (h - i) = 2 * 2 ^ (h - (i + 1)) := by + rw [hr, pow_succ] + omega + rw [hb] + exact earlyKey_parent_lt_child _ _ _ _ _ _ _ _ (by positivity) + +/-- The minus column-order equivalence, including shared leaves. -/ +theorem column_minus_child_lt_parent {h i : ℕ} (hi : i < h) + (x y : Fin (2 ^ h)) : + columnKey h (minusPos (i + 1) (by omega) x) < + columnKey h (minusPos i (Nat.le_of_lt hi) y) ↔ + node (i + 1) x / 2 ≤ node i y := by + by_cases he : i + 1 = h + · subst h + rw [minusPos_leaf, columnKey_leaf, columnKey_minus_internal hi] + have hs : i + 1 - i = 1 := by omega + simp only [hs, pow_one] + simpa [node] using leafKey_lt_lateKey_parent (i + 1) 1 x.val + (node i y) (2 * i + 1) y.val + · have hic : i + 1 < h := by omega + rw [columnKey_minus_internal hic, columnKey_minus_internal hi] + have hr : h - i = h - (i + 1) + 1 := by omega + have hb : 2 ^ (h - i) = 2 * 2 ^ (h - (i + 1)) := by + rw [hr, pow_succ] + omega + rw [hb, hr] + exact lateKey_child_lt_parent _ _ _ _ _ _ _ _ (by positivity) + +end Problem348.TreePositions + +end OAI diff --git a/lean/OAI/Combinatorics/MatroidCounting/CommonBases.lean b/lean/OAI/Combinatorics/MatroidCounting/CommonBases.lean new file mode 100644 index 0000000000000000000000000000000000000000..83e7e510797b85b7ef65b93d5983303245c3246b --- /dev/null +++ b/lean/OAI/Combinatorics/MatroidCounting/CommonBases.lean @@ -0,0 +1,26126 @@ +import Mathlib + +namespace OAI + +namespace CommonBasesFPRAS + +section + +abbrev IndependenceOracle (n : ℕ) := Bool → (Fin n → Bool) → Bool + +def ExactOracles {n : ℕ} (M₁ M₂ : Matroid (Fin n)) + (O : IndependenceOracle n) : Prop := + ∀ (which : Bool) (A : Fin n → Bool), + O which A = true ↔ (if which then M₂ else M₁).Indep {i | A i = true} + +noncomputable def commonBaseCount {n : ℕ} (M₁ M₂ : Matroid (Fin n)) : ℕ := + Nat.card {A : Finset (Fin n) // M₁.IsBase (A : Set (Fin n)) ∧ + M₂.IsBase (A : Set (Fin n))} + +inductive Instruction (k s : ℕ) where + | push (register : Fin (k + 8)) (bit : Bool) (next : Fin (s + 1)) + | pop (register : Fin (k + 8)) (empty zero one : Fin (s + 1)) + | coin (zero one : Fin (s + 1)) + | query (which : Bool) (register : Fin (k + 8)) (no yes : Fin (s + 1)) + | halt + +def Program (k s : ℕ) := Fin (s + 1) → Instruction k s + +def binaryValue : List Bool → ℕ + | [] => 0 + | b :: l => (if b then 1 else 0) + 2 * binaryValue l + +structure MachineConfig (k s : ℕ) where + registers : Fin (k + 8) → List Bool + control : Fin (s + 1) + output : Option ℚ := none + oracleCalls : ℕ := 0 + bitOperations : ℕ := 0 + +def inputLength (n r : ℕ) (ε δ : ℚ) : ℕ := + 6 + n.bits.length + r.bits.length + ε.num.natAbs.bits.length + ε.den.bits.length + + δ.num.natAbs.bits.length + δ.den.bits.length + +def initialConfig (k s n r : ℕ) (ε δ : ℚ) : MachineConfig k s where + registers := fun i => match i.val with + | 0 => n.bits + | 1 => r.bits + | 2 => ε.num.natAbs.bits + | 3 => ε.den.bits + | 4 => δ.num.natAbs.bits + | 5 => δ.den.bits + | _ => [] + control := 0 + +def machineStep {k s n : ℕ} (P : Program k s) (O : IndependenceOracle n) + (randomBit : Bool) (c : MachineConfig k s) : MachineConfig k s := + if c.output.isSome then c else + match P c.control with + | .push i b next => + { c with + registers := Function.update c.registers i (b :: c.registers i) + control := next + bitOperations := c.bitOperations + 1 } + | .pop i empty zero one => + match c.registers i with + | [] => { c with + control := empty + bitOperations := c.bitOperations + 1 } + | b :: l => + { c with + registers := Function.update c.registers i l + control := if b then one else zero + bitOperations := c.bitOperations + 1 } + | .coin zero one => + { c with + control := if randomBit then one else zero + bitOperations := c.bitOperations + 1 } + | .query which i no yes => + if (c.registers i).length = n then + { c with + control := if O which (fun j => (c.registers i)[j.val]?.getD false) + then yes else no + oracleCalls := c.oracleCalls + 1 + bitOperations := c.bitOperations + (c.registers i).length + n + 1 } + else + { c with + output := some 0 + bitOperations := c.bitOperations + (c.registers i).length + n + 1 } + | .halt => + { c with + output := some ((binaryValue (c.registers ⟨6, by omega⟩) : ℚ) / + (binaryValue (c.registers ⟨7, by omega⟩) : ℚ)) + bitOperations := c.bitOperations + (c.registers ⟨6, by omega⟩).length + + (c.registers ⟨7, by omega⟩).length + 1 } + +def execution {k s n : ℕ} (P : Program k s) (O : IndependenceOracle n) + (c : MachineConfig k s) (bits : ℕ → Bool) : ℕ → MachineConfig k s + | 0 => c + | t + 1 => machineStep P O (bits t) (execution P O c bits t) + +def finiteBits {B : ℕ} (bits : Fin B → Bool) (t : ℕ) : Bool := + if h : t < B then bits ⟨t, h⟩ else false + +def relativeAccuracy (ε : ℚ) (Z : ℕ) (z : ℚ) : Prop := + (1-ε)*(Z:ℚ)≤z ∧ z≤(1+ε)*(Z:ℚ) + +def resourceBound (C d n r : ℕ) (ε δ : ℚ) : ℕ := + C * (1 + n + inputLength n r ε δ + ⌈ε⁻¹⌉₊ + Nat.clog 2 ⌈δ⁻¹⌉₊) ^ d + +def MainTheorem : Prop := + ∃ (k s : ℕ) (P : Program k s) (C d : ℕ), 0 < C ∧ + ∀ (n r : ℕ) (M₁ M₂ : Matroid (Fin n)) (O : IndependenceOracle n) + (ε δ : ℚ), + M₁.E = Set.univ → M₂.E = Set.univ → + M₁.eRank = (r : ℕ∞) → M₂.eRank = (r : ℕ∞) → + ExactOracles M₁ M₂ O → 0 < ε → ε < 1 → 0 < δ → δ < 1 → + let B := resourceBound C d n r ε δ + let Z := commonBaseCount M₁ M₂ + (∀ bits : ℕ → Bool, + let out := execution P O (initialConfig k s n r ε δ) bits B + out.output.isSome ∧ out.oracleCalls ≤ B ∧ out.bitOperations ≤ B ∧ + ∀ z, out.output = some z → 0 ≤ z ∧ (Z = 0 → z = 0)) ∧ + (1 - δ) * (2 : ℚ) ^ B ≤ + (Nat.card {bits : Fin B → Bool // + ∃ z, (execution P O (initialConfig k s n r ε δ) (finiteBits bits) B).output + = some z ∧ relativeAccuracy ε Z z} : ℚ) + +section +open scoped RealInnerProductSpace BigOperators Matrix + +variable {V : Type*} [AddCommGroup V] [Module ℝ V] + +def OnePositive (B : LinearMap.BilinForm ℝ V) : Prop := + ∀ e, 0 < B e e → ∀ v, B v e = 0 → B v v ≤ 0 + +theorem onePositive_of_nonpositive_kernel (B : LinearMap.BilinForm ℝ V) + (hsymm : B.IsSymm) (L : V →ₗ[ℝ] ℝ) + (hker : ∀ v, L v = 0 → B v v ≤ 0) : OnePositive B := by + intro e he v hve + by_contra hv + have hvpos : 0 < B v v := lt_of_not_ge hv + have hLe : L e ≠ 0 := by + intro h + exact (not_le_of_gt he) (hker e h) + have hev : B e v = 0 := by rw [hsymm.eq e v, hve] + have hz : L ((L e) • v - (L v) • e) = 0 := by + simp only [map_sub, map_smul, smul_eq_mul] + ring + have hq := hker ((L e) • v - (L v) • e) hz + simp only [map_sub, map_smul, LinearMap.sub_apply, LinearMap.smul_apply, + smul_eq_mul, hve, hev, mul_zero, sub_zero] at hq + have hLe2 : 0 < (L e)^2 := sq_pos_of_ne_zero hLe + have hn : 0 ≤ (L v)^2 * B e e := mul_nonneg (sq_nonneg _) (le_of_lt he) + have hp : 0 < (L e)^2 * B v v := mul_pos hLe2 hvpos + nlinarith + +section Spectral +variable {E : Type*} [NormedAddCommGroup E] [InnerProductSpace ℝ E] + [FiniteDimensional ℝ E] + +theorem spectral_kernel_nonpositive (T : E →ₗ[ℝ] E) (hT : T.IsSymmetric) (w : E) + (hlocal : ∀ v, ⟪v, T v⟫ ≤ ⟪T v, T v⟫) + (hcon : ∀ v, ⟪v, T v⟫ ≤ ⟪v, v⟫) + (heq : ∀ v, ⟪v, T v⟫ = ⟪v, v⟫ → ∃ a : ℝ, v = a • w) + (v : E) (hv : ⟪w,v⟫ = 0) : ⟪v, T v⟫ ≤ 0 := by + let b := hT.eigenvectorBasis (rfl : Module.finrank ℝ E = Module.finrank ℝ E) + let ev := hT.eigenvalues (rfl : Module.finrank ℝ E = Module.finrank ℝ E) + have heigen : ∀ i, T (b i) = ev i • b i := hT.apply_eigenvectorBasis rfl + have hunit : ∀ i, ⟪b i, b i⟫ = 1 := by + intro i + rw [real_inner_self_eq_norm_sq, b.orthonormal.1 i] + norm_num + have hpos : ∀ i, 0 < ev i → b.repr v i = 0 := by + intro i hi + have hl := hlocal (b i) + have hc := hcon (b i) + rw [heigen i] at hl hc + simp only [inner_smul_left, inner_smul_right, hunit, conj_trivial, mul_one] at hl hc + have he : ev i = 1 := by nlinarith + have he' : ⟪b i, T (b i)⟫ = ⟪b i, b i⟫ := by rw [heigen i, he, one_smul] + obtain ⟨a, ha⟩ := heq (b i) he' + rw [b.repr_apply_apply, ha, inner_smul_left, hv] + simp + rw [← b.repr.inner_map_map v (T v)] + simp only [PiLp.inner_apply, RCLike.inner_apply, conj_trivial] + apply Finset.sum_nonpos + intro i _ + have ht : b.repr (T v) i = ev i * b.repr v i := + hT.eigenvectorBasis_apply_self_apply rfl v i + rw [ht] + by_cases h : 0 < ev i + · simp [hpos i h] + · have hn : ev i ≤ 0 := le_of_not_gt h + nlinarith [sq_nonneg (b.repr v i)] + +end Spectral +section PositiveMatrix +variable {ι : Type*} [Fintype ι] [sectionInstance7 : DecidableEq ι] + +theorem matrix_bilin_symm (A : Matrix ι ι ℝ) (hA : ∀ i j, A i j = A j i) : + A.toBilin'.IsSymm := by + constructor + intro x y + simp only [Matrix.toBilin'_apply] + rw [Finset.sum_comm] + apply Finset.sum_congr rfl + intro i _ + apply Finset.sum_congr rfl + intro j _ + rw [hA j i] + ring + +def weightedSumLinear (a : ι → ℝ) : (ι → ℝ) →ₗ[ℝ] ℝ where + toFun v := ∑ i, a i * v i + map_add' x y := by simp [mul_add, Finset.sum_add_distrib] + map_smul' c x := by simp [Finset.mul_sum, mul_left_comm] + +omit sectionInstance7 in +lemma dirichlet_identity [DecidableEq ι] (A : Matrix ι ι ℝ) (hA : ∀ i j, A i j = A j i) + (r : ι → ℝ) : + (∑ i, ∑ j, A i j * (r i-r j)^2) = + 2*(∑ i, (∑ j, A i j)*(r i)^2) - 2*(∑ i, ∑ j, r i*A i j*r j) := by + have hfirst : (∑ i, ∑ j, A i j*(r i)^2) = ∑ i, (∑ j, A i j)*(r i)^2 := by + simp only [Finset.sum_mul] + have hsecond : (∑ i, ∑ j, A i j*(r j)^2) = ∑ i, (∑ j, A i j)*(r i)^2 := by + rw [Finset.sum_comm] + simp_rw [hA] + exact hfirst + calc + _ = ∑ i, ∑ j, (A i j*(r i)^2 + A i j*(r j)^2 - 2*(r i*A i j*r j)) := by + apply Finset.sum_congr rfl + intro i _ + apply Finset.sum_congr rfl + intro j _ + ring + _ = _ := by + simp only [Finset.sum_sub_distrib, Finset.sum_add_distrib, ← Finset.mul_sum] + rw [hfirst, hsecond] + ring + +lemma eigen_dirichlet (A : Matrix ι ι ℝ) (hA : ∀ i j, A i j = A j i) + (w v : ι → ℝ) (hw : ∀ i, 0 < w i) (he : A *ᵥ w = w) : + (∑ i, ∑ j, A i j*w i*w j*(v i/w i-v j/w j)^2) = + 2 * ((∑ i, (v i)^2) - A.toBilin' v v) := by + have hs : ∀ i j, A i j*w i*w j = A j i*w j*w i := by + intro i j; rw [hA i j]; ring + rw [dirichlet_identity (fun i j => A i j*w i*w j) hs (fun i => v i/w i)] + have hrows : ∀ i, (∑ j, A i j*w i*w j)*(v i/w i)^2 = (v i)^2 := by + intro i + have he' : (∑ j, A i j*w j) = w i := congr_fun he i + have hsum : (∑ j, A i j*w i*w j) = w i*(∑ j, A i j*w j) := by + rw [Finset.mul_sum] + apply Finset.sum_congr rfl + intro j _ + ring + rw [hsum, he'] + field_simp [ne_of_gt (hw i)] + have hquad : (∑ i, ∑ j, (v i/w i)*(A i j*w i*w j)*(v j/w j)) = A.toBilin' v v := by + rw [Matrix.toBilin'_apply] + apply Finset.sum_congr rfl + intro i _ + apply Finset.sum_congr rfl + intro j _ + field_simp [ne_of_gt (hw i), ne_of_gt (hw j)] + simp_rw [hrows] + rw [hquad] + ring + +lemma positive_eigen_contraction (A : Matrix ι ι ℝ) + (hA : ∀ i j, A i j = A j i) (hpos : ∀ i j, 0 ≤ A i j) + (w v : ι → ℝ) (hw : ∀ i, 0 < w i) (he : A *ᵥ w = w) : + A.toBilin' v v ≤ ∑ i, (v i)^2 := by + have hd := eigen_dirichlet A hA w v hw he + have hn : 0 ≤ ∑ i, ∑ j, A i j*w i*w j*(v i/w i-v j/w j)^2 := + Finset.sum_nonneg fun i _ => Finset.sum_nonneg fun j _ => + mul_nonneg (mul_nonneg (mul_nonneg (hpos i j) (hw i).le) (hw j).le) (sq_nonneg _) + linarith + +lemma positive_eigen_equality [Nonempty ι] (A : Matrix ι ι ℝ) + (hA : ∀ i j, A i j = A j i) (hnonneg : ∀ i j, 0 ≤ A i j) + (hpos : ∀ i j, i ≠ j → 0 < A i j) + (w v : ι → ℝ) (hw : ∀ i, 0 < w i) (he : A *ᵥ w = w) + (heq : A.toBilin' v v = ∑ i, (v i)^2) : ∃ a : ℝ, v = a • w := by + classical + let k : ι := Classical.choice ‹Nonempty ι› + have hd := eigen_dirichlet A hA w v hw he + rw [heq, sub_self, mul_zero] at hd + have hn : ∀ i j, 0 ≤ A i j*w i*w j*(v i/w i-v j/w j)^2 := by + intro i j + exact mul_nonneg (mul_nonneg (mul_nonneg (hnonneg i j) (hw i).le) (hw j).le) (sq_nonneg _) + have h0 : ∀ i j, A i j*w i*w j*(v i/w i-v j/w j)^2 = 0 := by + have hrow := (Finset.sum_eq_zero_iff_of_nonneg + (fun i (_ : i ∈ Finset.univ) => Finset.sum_nonneg fun j _ => hn i j)).mp hd + intro i j + exact (Finset.sum_eq_zero_iff_of_nonneg (fun j _ => hn i j)).mp + (hrow i (Finset.mem_univ i)) j (Finset.mem_univ j) + refine ⟨v k/w k, ?_⟩ + ext i + simp only [Pi.smul_apply, smul_eq_mul] + by_cases hik : i = k + · subst i + field_simp [ne_of_gt (hw k)] + · have hm : A i k*w i*w k ≠ 0 := ne_of_gt (mul_pos (mul_pos (hpos i k hik) (hw i)) (hw k)) + have hz : (v i/w i-v k/w k)^2 = 0 := (mul_eq_zero.mp (h0 i k)).resolve_left hm + have hh : v i/w i = v k/w k := sub_eq_zero.mp (sq_eq_zero_iff.mp hz) + exact (div_eq_iff (ne_of_gt (hw i))).mp hh + +lemma euclidean_inner_matrix (A : Matrix ι ι ℝ) (v w : EuclideanSpace ℝ ι) : + ⟪v, A.toEuclideanLin w⟫ = A.toBilin' (WithLp.ofLp v) (WithLp.ofLp w) := by + simp only [PiLp.inner_apply, RCLike.inner_apply, conj_trivial, + Matrix.toLpLin_apply, Matrix.mulVec, dotProduct, + Matrix.toBilin'_apply, Finset.sum_mul] + apply Finset.sum_congr rfl + intro i _ + apply Finset.sum_congr rfl + intro j _ + ring + +omit sectionInstance7 in +lemma euclidean_normsq [DecidableEq ι] (v : EuclideanSpace ℝ ι) : + ⟪v,v⟫ = ∑ i, (WithLp.ofLp v i)^2 := by + simp only [PiLp.inner_apply, RCLike.inner_apply, conj_trivial, pow_two] + +theorem matrix_signature_of_squared [Nonempty ι] (A : Matrix ι ι ℝ) + (hA : ∀ i j, A i j = A j i) (hnonneg : ∀ i j, 0 ≤ A i j) + (hpos : ∀ i j, i ≠ j → 0 < A i j) + (w : ι → ℝ) (hw : ∀ i, 0 < w i) (he : A *ᵥ w = w) + (hlocal : ∀ v, A.toBilin' v v ≤ ∑ i, ((A *ᵥ v) i)^2) : + OnePositive A.toBilin' := by + have hsym : A.toEuclideanLin.IsSymmetric := by + apply Matrix.isSymmetric_toEuclideanLin_iff.mpr + ext i j + simpa using hA j i + refine onePositive_of_nonpositive_kernel _ (matrix_bilin_symm A hA) + (weightedSumLinear w) ?_ + intro v hv + change (∑ i, w i * v i) = 0 at hv + have hn := spectral_kernel_nonpositive A.toEuclideanLin hsym (WithLp.toLp 2 w) + (fun v => ?_) (fun v => ?_) (fun v hv => ?_) (WithLp.toLp 2 v) ?_ + · simpa only [euclidean_inner_matrix, WithLp.ofLp_toLp] using hn + · rw [euclidean_inner_matrix, euclidean_normsq] + exact hlocal _ + · rw [euclidean_inner_matrix, euclidean_normsq] + exact positive_eigen_contraction A hA hnonneg w _ hw he + · rw [euclidean_inner_matrix, euclidean_normsq] at hv + obtain ⟨a, ha⟩ := positive_eigen_equality A hA hnonneg hpos w _ hw he hv + refine ⟨a, ?_⟩ + exact WithLp.ofLp_injective 2 ha + · simpa [PiLp.inner_apply, RCLike.inner_apply, mul_comm] using hv + +def diagonalScale (A : Matrix ι ι ℝ) (s : ι → ℝ) : Matrix ι ι ℝ := + fun i j => s i * A i j * s j + +lemma diagonalScale_bilin (A : Matrix ι ι ℝ) (s u v : ι → ℝ) : + (diagonalScale A s).toBilin' u v = + A.toBilin' (fun i => s i*u i) (fun i => s i*v i) := by + simp only [Matrix.toBilin'_apply, diagonalScale] + apply Finset.sum_congr rfl + intro i _ + apply Finset.sum_congr rfl + intro j _ + ring + +omit sectionInstance7 in +lemma diagonalScale_mulVec [DecidableEq ι] (A : Matrix ι ι ℝ) (s v : ι → ℝ) (i : ι) : + (diagonalScale A s *ᵥ v) i = s i * (A *ᵥ (fun j => s j*v j)) i := by + simp only [Matrix.mulVec, dotProduct, diagonalScale, Finset.mul_sum] + apply Finset.sum_congr rfl + intro j _ + ring + +lemma onePositive_unscale (A : Matrix ι ι ℝ) (s : ι → ℝ) (hs : ∀ i, s i ≠ 0) + (h : OnePositive (diagonalScale A s).toBilin') : OnePositive A.toBilin' := by + have hf : ∀ v : ι → ℝ, (fun i => s i * (v i / s i)) = v := by + intro v; ext i; field_simp [hs i] + intro e he v hv + have hep : 0 < (diagonalScale A s).toBilin' (fun i => e i/s i) (fun i => e i/s i) := by + simpa [diagonalScale_bilin, hf] using he + have hvp : (diagonalScale A s).toBilin' (fun i => v i/s i) (fun i => e i/s i) = 0 := by + simpa [diagonalScale_bilin, hf] using hv + simpa [diagonalScale_bilin, hf] using h _ hep _ hvp + +theorem signature_of_local_bound [Nonempty ι] (A : Matrix ι ι ℝ) + (hA : ∀ i j, A i j = A j i) (hnonneg : ∀ i j, 0 ≤ A i j) + (hpos : ∀ i j, i ≠ j → 0 < A i j) + (x s : ι → ℝ) (hx : ∀ i, 0 < x i) (hs : ∀ i, 0 < s i) + (hsx : ∀ i, (s i)^2*(A*ᵥx) i = x i) + (hlocal : ∀ v, A.toBilin' v v ≤ ∑ i, (s i)^2*((A *ᵥ v) i)^2) : + OnePositive A.toBilin' := by + let B := diagonalScale A s + have hB : ∀ i j, B i j = B j i := by + intro i j; dsimp [B, diagonalScale]; rw [hA i j]; ring + have hBn : ∀ i j, 0 ≤ B i j := by + intro i j; exact mul_nonneg (mul_nonneg (hs i).le (hnonneg i j)) (hs j).le + have hBp : ∀ i j, i ≠ j → 0 < B i j := by + intro i j hij; exact mul_pos (mul_pos (hs i) (hpos i j hij)) (hs j) + let w : ι → ℝ := fun i => x i/s i + have hw : ∀ i, 0 < w i := fun i => div_pos (hx i) (hs i) + have hsw : (fun j => s j * w j) = x := by + ext j; dsimp [w]; field_simp [ne_of_gt (hs j)] + have he : B *ᵥ w = w := by + ext i + rw [diagonalScale_mulVec, hsw] + dsimp [w] + apply (eq_div_iff (ne_of_gt (hs i))).mpr + nlinarith [hsx i] + have hl : ∀ v, B.toBilin' v v ≤ ∑ i, ((B *ᵥ v) i)^2 := by + intro v + change (diagonalScale A s).toBilin' v v ≤ _ + dsimp only [B] + rw [diagonalScale_bilin] + simp_rw [diagonalScale_mulVec, mul_pow] + exact hlocal _ + exact onePositive_unscale A s (fun i => ne_of_gt (hs i)) + (matrix_signature_of_squared B hB hBn hBp w hw he hl) + +lemma onePositive_quadratic_bound {V : Type*} [AddCommGroup V] [Module ℝ V] + (B : LinearMap.BilinForm ℝ V) (hB : OnePositive B) (hS : B.IsSymm) + (e v : V) (he : 0 < B e e) : B v v ≤ (B v e)^2 / B e e := by + have hz : B ((B e e) • v - (B v e) • e) e = 0 := by + simp only [map_sub, map_smul, LinearMap.sub_apply, LinearMap.smul_apply, smul_eq_mul] + ring + have hn := hB e he ((B e e) • v - (B v e) • e) hz + have hev : B e v = B v e := hS.eq e v + simp only [map_sub, map_smul, LinearMap.sub_apply, LinearMap.smul_apply, + smul_eq_mul, hev] at hn + apply (le_div_iff₀ he).mpr + have hf : B e e * (B v v * B e e - (B v e)^2) ≤ 0 := by nlinarith [hn] + have hle : B v v * B e e - (B v e)^2 ≤ 0 := + nonpos_of_mul_nonpos_right hf he + linarith + +def cubicContraction (C : ι → Matrix ι ι ℝ) (x : ι → ℝ) : Matrix ι ι ℝ := + fun j k => ∑ i, x i*C i j k + +omit sectionInstance7 in +lemma cubicContraction_symm [DecidableEq ι] (C : ι → Matrix ι ι ℝ) + (hC : ∀ i j k, C i j k = C i k j) (x : ι → ℝ) : + ∀ j k, cubicContraction C x j k = cubicContraction C x k j := by + intro j k + simp only [cubicContraction, hC] + +lemma cubicContraction_bilin (C : ι → Matrix ι ι ℝ) (x v : ι → ℝ) : + (cubicContraction C x).toBilin' v v = ∑ i, x i*(C i).toBilin' v v := by + calc + _ = ∑ j, ∑ k, ∑ i, v j * x i * C i j k * v k := by + simp only [Matrix.toBilin'_apply, cubicContraction, Finset.mul_sum, Finset.sum_mul] + apply Finset.sum_congr rfl + intro j _ + apply Finset.sum_congr rfl + intro k _ + apply Finset.sum_congr rfl + intro i _ + ring + _ = ∑ j, ∑ i, ∑ k, v j * x i * C i j k * v k := + Finset.sum_congr rfl fun _ _ => Finset.sum_comm + _ = ∑ i, ∑ j, ∑ k, v j * x i * C i j k * v k := Finset.sum_comm + _ = _ := by + simp only [Matrix.toBilin'_apply, Finset.mul_sum] + apply Finset.sum_congr rfl + intro i _ + apply Finset.sum_congr rfl + intro j _ + apply Finset.sum_congr rfl + intro k _ + ring + +lemma cubicContraction_row (C : ι → Matrix ι ι ℝ) + (hC : ∀ i j k, C i j k = C j i k) (x v : ι → ℝ) (i : ι) : + (C i).toBilin' x v = (cubicContraction C x *ᵥ v) i := by + simp only [Matrix.toBilin'_apply, Matrix.mulVec, dotProduct, cubicContraction, + Finset.sum_mul] + rw [Finset.sum_comm] + apply Finset.sum_congr rfl + intro j _ + apply Finset.sum_congr rfl + intro k _ + rw [hC i k j] + +theorem cubic_local_estimate (C : ι → Matrix ι ι ℝ) + (hCs : ∀ i j k, C i j k = C i k j) + (hCt : ∀ i j k, C i j k = C j i k) + (hC : ∀ i, OnePositive (C i).toBilin') + (x : ι → ℝ) (hx : ∀ i, 0 ≤ x i) + (hCx : ∀ i, 0 < (C i).toBilin' x x) (v : ι → ℝ) : + (cubicContraction C x).toBilin' v v ≤ + ∑ i, x i * ((cubicContraction C x *ᵥv) i)^2 / (cubicContraction C x *ᵥx) i := by + rw [cubicContraction_bilin] + apply Finset.sum_le_sum + intro i _ + have hS := matrix_bilin_symm (C i) (hCs i) + have hl := mul_le_mul_of_nonneg_left + (onePositive_quadratic_bound (C i).toBilin' (hC i) hS x v (hCx i)) (hx i) + rw [hS.eq v x, cubicContraction_row C hCt x v i, + cubicContraction_row C hCt x x i, ← mul_div_assoc] at hl + exact hl + +theorem cubic_signature [Nonempty ι] (C : ι → Matrix ι ι ℝ) + (hCs : ∀ i j k, C i j k = C i k j) + (hCt : ∀ i j k, C i j k = C j i k) + (hC : ∀ i, OnePositive (C i).toBilin') + (x : ι → ℝ) (hx : ∀ i, 0 < x i) + (hCx : ∀ i, 0 < (C i).toBilin' x x) + (hCn : ∀ j k, 0 ≤ cubicContraction C x j k) + (hCp : ∀ j k, j ≠ k → 0 < cubicContraction C x j k) : + OnePositive (cubicContraction C x).toBilin' := by + let A := cubicContraction C x + have hy : ∀ i, 0 < (A*ᵥx) i := by + intro i + rw [← cubicContraction_row C hCt x x i] + exact hCx i + let s : ι → ℝ := fun i => Real.sqrt (x i/(A*ᵥx) i) + have hs : ∀ i, 0 < s i := fun i => Real.sqrt_pos.2 (div_pos (hx i) (hy i)) + have hs2 : ∀ i, (s i)^2 = x i/(A*ᵥx) i := fun i => + Real.sq_sqrt (le_of_lt (div_pos (hx i) (hy i))) + apply signature_of_local_bound A (cubicContraction_symm C hCs x) hCn hCp x s hx hs + · intro i + rw [hs2] + field_simp [ne_of_gt (hy i)] + intro v + have hl := cubic_local_estimate C hCs hCt hC x (fun i => (hx i).le) hCx v + refine hl.trans_eq ?_ + apply Finset.sum_congr rfl + intro i _ + rw [hs2] + ring + +end PositiveMatrix + +section RawSignature +open scoped BigOperators Classical +variable {ι : Type*} [sectionInstance8 : Fintype ι] [sectionInstance9 : DecidableEq ι] + +noncomputable def rankWeight (M : Matroid ι) (q : ℝ) (A : Set ι) : ℝ := + (q⁻¹) ^ (M.eRk A).toNat + +noncomputable def rawHessian (M : Matroid ι) (q : ℝ) : Matrix ι ι ℝ := + fun i j => if i = j then 0 else rankWeight M q {i,j} + +omit sectionInstance8 sectionInstance9 in +lemma eRk_insert_of_mem_closure' [Fintype ι] [DecidableEq ι] (M : Matroid ι) (i : ι) (X : Set ι) + (hi : i ∈ M.closure X) : M.eRk (insert i X) = M.eRk X := by + rw [← M.eRk_insert_closure_eq, Set.insert_eq_of_mem hi, M.eRk_closure_eq] + +lemma pair_rank_of_loop (M : Matroid ι) (i j : ι) (hi : M.IsLoop i) : + M.eRk {i,j} = M.eRk {j} := + eRk_insert_of_mem_closure' M i {j} (hi.mem_closure _) + +lemma pair_rank_parallel (M : Matroid ι) (i j : ι) (hi : M.IsNonloop i) (hj : M.IsNonloop j) + (hc : M.closure {i} = M.closure {j}) : M.eRk {i,j} = 1 := by + rw [eRk_insert_of_mem_closure' M i {j}, hj.eRk_eq] + rw [← hc] + exact M.mem_closure_self i hi.mem_ground + +omit sectionInstance8 sectionInstance9 in +lemma pair_rank_nonparallel [Fintype ι] [DecidableEq ι] (M : Matroid ι) (i j : ι) (hi : M.IsNonloop i) + (hj : M.IsNonloop j) (hc : M.closure {i} ≠ M.closure {j}) : + M.eRk {i,j} = 2 := by + have hn : i ∉ M.closure {j} := fun h => hc (hi.closure_eq_of_mem_closure h) + rw [M.eRk_insert_eq_add_one ⟨hi.mem_ground, hn⟩, hj.eRk_eq] + norm_num + +noncomputable def rawPositive (M : Matroid ι) (q : ℝ) (i : ι) : ℝ := + if M.IsNonloop i then q⁻¹ else 1 + +noncomputable def parallelIndicator (M : Matroid ι) (C : Set ι) (i : ι) : ℝ := + if M.IsNonloop i ∧ M.closure {i} = C then 1 else 0 + +omit sectionInstance9 in +lemma parallel_gram [DecidableEq ι] (M : Matroid ι) (i j : ι) : + (∑ C : Set ι, parallelIndicator M C i * parallelIndicator M C j) = + if M.IsNonloop i ∧ M.IsNonloop j ∧ M.closure {i} = M.closure {j} + then 1 else 0 := by + classical + by_cases hi : M.IsNonloop i <;> by_cases hj : M.IsNonloop j + · simp [parallelIndicator, hi, hj, Finset.sum_ite_eq', eq_comm] + · simp [parallelIndicator, hi, hj] + · simp [parallelIndicator, hi, hj] + · simp [parallelIndicator, hi, hj] + +lemma rawHessian_decomposition (M : Matroid ι) (hE : M.E = Set.univ) + (q : ℝ) (i j : ι) : + rawHessian M q i j = rawPositive M q i * rawPositive M q j - + (if i = j then rawPositive M q i else 0) - + (q⁻¹^2-q⁻¹) * ∑ C : Set ι, parallelIndicator M C i * parallelIndicator M C j := by + classical + have hground : ∀ i, i ∈ M.E := by simp [hE] + rw [parallel_gram] + by_cases hij : i = j + · subst j + by_cases hi : M.IsNonloop i <;> simp [rawHessian, rawPositive, hi] ; ring + · have hij' : j ≠ i := Ne.symm hij + simp only [rawHessian, ite_eq_right hij] + by_cases hi : M.IsNonloop i <;> by_cases hj : M.IsNonloop j + · by_cases hc : M.closure {i} = M.closure {j} + · rw [rankWeight, pair_rank_parallel M i j hi hj hc] + simp [rawPositive, hi, hj, hc] + ring + · rw [rankWeight, pair_rank_nonparallel M i j hi hj hc] + simp [rawPositive, hi, hj, hc] + ring + · have hloop : M.IsLoop j := (M.not_isNonloop_iff (hground j)).mp hj + rw [rankWeight, Set.pair_comm i j, pair_rank_of_loop M j i hloop, hi.eRk_eq] + simp [rawPositive, hi, hj] + · have hloop : M.IsLoop i := (M.not_isNonloop_iff (hground i)).mp hi + rw [rankWeight, pair_rank_of_loop M i j hloop, hj.eRk_eq] + simp [rawPositive, hi, hj] + · have hli : M.IsLoop i := (M.not_isNonloop_iff (hground i)).mp hi + have hlj : M.IsLoop j := (M.not_isNonloop_iff (hground j)).mp hj + rw [rankWeight, pair_rank_of_loop M i j hli, hlj.eRk_eq] + simp [rawPositive, hi, hj] + +omit sectionInstance9 in +lemma sum_rankone [DecidableEq ι] (a v : ι → ℝ) : + (∑ i, ∑ j, v i * (a i * a j) * v j) = (∑ i, a i * v i)^2 := by + rw [pow_two, Finset.sum_mul_sum] + apply Finset.sum_congr rfl + intro i _ + apply Finset.sum_congr rfl + intro j _ + ring + +lemma sum_diagonal (a v : ι → ℝ) : + (∑ i, ∑ j, v i * (if i = j then a i else 0) * v j) = + ∑ i, a i * (v i)^2 := by + simp only [mul_ite, ite_mul, mul_zero, zero_mul, Finset.sum_ite_eq, Finset.mem_univ, ite_true] + apply Finset.sum_congr rfl + intro i _ + ring + +lemma sum_gram {κ : Type*} [Fintype κ] (p : κ → ι → ℝ) (v : ι → ℝ) : + (∑ i, ∑ j, v i * (∑ c, p c i * p c j) * v j) = + ∑ c, (∑ i, p c i * v i)^2 := by + calc + _ = ∑ i, ∑ j, ∑ c, v i * (p c i * p c j) * v j := by + simp only [Finset.mul_sum, Finset.sum_mul] + _ = ∑ i, ∑ c, ∑ j, v i * (p c i * p c j) * v j := + Finset.sum_congr rfl fun _ _ => Finset.sum_comm + _ = ∑ c, ∑ i, ∑ j, v i * (p c i * p c j) * v j := Finset.sum_comm + _ = _ := Finset.sum_congr rfl fun c _ => sum_rankone (p c) v + +lemma rawHessian_eval (M : Matroid ι) (hE : M.E = Set.univ) (q : ℝ) (v : ι → ℝ) : + (rawHessian M q).toBilin' v v = + (∑ i, rawPositive M q i * v i)^2 - + (∑ i, rawPositive M q i * (v i)^2) - + (q⁻¹^2-q⁻¹) * ∑ C : Set ι, (∑ i, parallelIndicator M C i * v i)^2 := by + simp only [Matrix.toBilin'_apply, rawHessian_decomposition M hE] + generalize hc : q⁻¹^2-q⁻¹ = c + simp only [mul_sub, sub_mul, Finset.sum_sub_distrib] + rw [sum_rankone, sum_diagonal] + congr 1 + rw [← sum_gram] + simp only [Finset.mul_sum] + apply Finset.sum_congr rfl + intro i _ + apply Finset.sum_congr rfl + intro j _ + simp only [Finset.sum_mul, Finset.mul_sum] + apply Finset.sum_congr rfl + intro C _ + ring + +theorem raw_matroid_signature (M : Matroid ι) (hE : M.E = Set.univ) + (q : ℝ) (hq : 0 < q) (hq1 : q ≤ 1) : OnePositive (rawHessian M q).toBilin' := by + refine onePositive_of_nonpositive_kernel _ ?_ (weightedSumLinear (rawPositive M q)) ?_ + · apply matrix_bilin_symm + intro i j + by_cases hij : i = j + · subst j; rfl + · simp [rawHessian, hij, Ne.symm hij, Set.pair_comm i j] + intro v hv + change (∑ i, rawPositive M q i * v i) = 0 at hv + rw [rawHessian_eval M hE q v, hv, zero_pow (by decide), zero_sub] + have hp : ∀ i, 0 ≤ rawPositive M q i := by + intro i + simp only [rawPositive] + split_ifs <;> positivity + have hd : 0 ≤ ∑ i, rawPositive M q i * (v i)^2 := + Finset.sum_nonneg fun i _ => mul_nonneg (hp i) (sq_nonneg _) + have hi : 1 ≤ q⁻¹ := (one_le_inv₀ hq).mpr hq1 + have hc : 0 ≤ q⁻¹^2-q⁻¹ := by nlinarith + have hg : 0 ≤ (q⁻¹^2-q⁻¹) * ∑ C : Set ι, (∑ i, parallelIndicator M C i * v i)^2 := + mul_nonneg hc (Finset.sum_nonneg fun _ _ => sq_nonneg _) + linarith + +end RawSignature +section MatroidFaces +open scoped Matroid BigOperators Classical +variable {ι : Type*} [sectionInstance10 : Fintype ι] [sectionInstance11 : DecidableEq ι] + +omit sectionInstance10 sectionInstance11 in +lemma contract_eRk_add [Fintype ι] [DecidableEq ι] (M : Matroid ι) (A X : Set ι) + (hA : A ⊆ M.E) (hX : X ⊆ (M / A).E) : + (M / A).eRk X + M.eRk A = M.eRk (X ∪ A) := by + obtain ⟨I, hI⟩ := M.exists_isBasis A hA + obtain ⟨J, hJ⟩ := (M / A).exists_isBasis X hX + have hJ' : (M / I).IsBasis J X := by + rw [hI.contract_eq_contract_delete] at hJ + exact (Matroid.delete_isBasis_iff.mp hJ).1 + have hU := hI.indep.union_isBasis_union_of_contract_isBasis hJ' + have hd : Disjoint J I := (hI.indep.contract_indep_iff.mp hJ'.indep).1 + calc + _ = J.encard + I.encard := by rw [hJ.eRk_eq_encard, hI.eRk_eq_encard] + _ = (J ∪ I).encard := (Set.encard_union_eq hd).symm + _ = M.eRk (X ∪ I) := hU.encard_eq_eRk + _ = M.eRk (X ∪ A) := by + simpa [Set.union_comm] using hI.eRk_eq_eRk_union X + +noncomputable def faceHessian (f : Set ι → ℝ) (A : Set ι) : + Matrix {i // i ∉ A} {i // i ∉ A} ℝ := + fun i j => if i = j then 0 else f (A ∪ {i.val,j.val}) + +noncomputable def faceMatroid (M : Matroid ι) (A : Set ι) : Matroid {i // i ∉ A} := + (M / A).comap Subtype.val + +omit sectionInstance10 sectionInstance11 in +lemma faceMatroid_ground [Fintype ι] [DecidableEq ι] (M : Matroid ι) (hE : M.E = Set.univ) (A : Set ι) : + (faceMatroid M A).E = Set.univ := by + ext i + simp [faceMatroid, hE, i.property] + +lemma faceMatroid_rank (M : Matroid ι) (hE : M.E = Set.univ) + (A : Set ι) (i j : {i // i ∉ A}) : + (faceMatroid M A).eRk {i,j} + M.eRk A = M.eRk (A ∪ {i.val,j.val}) := by + have hA : A ⊆ M.E := by simp [hE] + have hX : ({i.val,j.val} : Set ι) ⊆ (M / A).E := by + simp only [Matroid.contract_ground, hE] + intro k hk + rcases hk with rfl | rfl + · exact ⟨Set.mem_univ _, i.property⟩ + · exact ⟨Set.mem_univ _, j.property⟩ + simpa [faceMatroid, Matroid.eRk_comap, Set.image_pair, Set.union_comm] using + contract_eRk_add M A {i.val,j.val} hA hX + +lemma faceHessian_rankWeight (M : Matroid ι) (hE : M.E = Set.univ) + (q : ℝ) (A : Set ι) : + faceHessian (rankWeight M q) A = rankWeight M q A • rawHessian (faceMatroid M A) q := by + ext i j + by_cases hij : i = j + · simp [faceHessian, rawHessian, hij] + simp only [faceHessian, rawHessian, ite_eq_right hij, Matrix.smul_apply, smul_eq_mul, + rankWeight] + have hr := faceMatroid_rank M hE A i j + rw [← hr, ENat.toNat_add (by simp) (by simp), pow_add, mul_comm] + +lemma onePositive_pos_smul {V : Type*} [AddCommGroup V] [Module ℝ V] + (B : LinearMap.BilinForm ℝ V) (hB : OnePositive B) (c : ℝ) (hc : 0 < c) : + OnePositive (c • B) := by + intro e he v hv + simp only [LinearMap.smul_apply, smul_eq_mul] at he hv ⊢ + have he' : 0 < B e e := pos_of_mul_pos_right he hc.le + have hv' : B v e = 0 := (mul_eq_zero.mp hv).resolve_left (ne_of_gt hc) + exact mul_nonpos_of_nonneg_of_nonpos hc.le (hB e he' v hv') + +theorem rankWeight_face_signature (M : Matroid ι) (hE : M.E = Set.univ) + (q : ℝ) (hq : 0 < q) (hq1 : q ≤ 1) (A : Set ι) : + OnePositive (faceHessian (rankWeight M q) A).toBilin' := by + rw [faceHessian_rankWeight M hE q A, map_smul] + exact onePositive_pos_smul _ + (raw_matroid_signature (faceMatroid M A) (faceMatroid_ground M hE A) q hq hq1) + _ (by dsimp [rankWeight]; positivity) + +end MatroidFaces + +section DerivativeClosure +open scoped BigOperators Classical Matrix +variable {ι : Type*} [sectionInstance12 : Fintype ι] [sectionInstance13 : DecidableEq ι] +noncomputable def coeffDeriv (a : ι → ℝ) (f : Set ι → ℝ) (A : Set ι) : ℝ := + ∑ i, if i ∈ A then 0 else a i * f (insert i A) + +noncomputable def coeffDerivs : List (ι → ℝ) → (Set ι → ℝ) → Set ι → ℝ + | [], f => f + | a :: as, f => coeffDeriv a (coeffDerivs as f) + +omit sectionInstance13 in +lemma card_outside [DecidableEq ι] (A : Set ι) : Fintype.card {i // i ∉ A} + A.ncard = Fintype.card ι := by + change Fintype.card (Aᶜ : Set ι) + A.ncard = Fintype.card ι + rw [Set.fintypeCard_eq_ncard] + simpa [Nat.card_eq_fintype_card, add_comm] using A.ncard_add_ncard_compl + +omit sectionInstance13 in +lemma ncard_insert_eq [DecidableEq ι] (A : Set ι) (i : ι) (hi : i ∉ A) : + (insert i A).ncard = A.ncard + 1 := Set.ncard_insert_of_notMem hi + +omit sectionInstance13 in +lemma exists_outside_of_ncard_lt [DecidableEq ι] (A : Set ι) (h : A.ncard < Fintype.card ι) : + ∃ i, i ∉ A := by + by_contra hn + have hA : A = Set.univ := by ext i; simp only [Set.mem_univ, iff_true]; exact of_not_not (not_exists.mp hn i) + simp [hA] at h + +def FullPositive (f : Set ι → ℝ) (k : ℕ) : Prop := + (∀ A, A.ncard + k ≤ Fintype.card ι → 0 < f A) ∧ + (∀ A, Fintype.card ι < A.ncard + k → f A = 0) + +omit sectionInstance13 in +lemma FullPositive.nonneg [DecidableEq ι] {f : Set ι → ℝ} {k : ℕ} (h : FullPositive f k) + (A : Set ι) : 0 ≤ f A := by + by_cases ha : A.ncard + k ≤ Fintype.card ι + · exact (h.1 A ha).le + · rw [h.2 A (lt_of_not_ge ha)] + +lemma FullPositive.deriv {f : Set ι → ℝ} {k : ℕ} (h : FullPositive f k) + (a : ι → ℝ) (ha : ∀ i, 0 < a i) : FullPositive (coeffDeriv a f) (k+1) := by + constructor + · intro A hA + obtain ⟨i, hi⟩ := exists_outside_of_ncard_lt A (by omega) + apply Finset.sum_pos' + · intro j _ + split_ifs + · exact le_rfl + · exact mul_nonneg (ha j).le (h.nonneg _) + · refine ⟨i, Finset.mem_univ _, ?_⟩ + rw [ite_eq_right hi] + apply mul_pos (ha i) + apply h.1 + rw [ncard_insert_eq A i hi] + omega + · intro A hA + apply Finset.sum_eq_zero + intro i _ + split_ifs with hi + · rfl + · rw [h.2 (insert i A) (by rw [ncard_insert_eq A i hi]; omega), mul_zero] + +lemma onePositive_comap {V W : Type*} [AddCommGroup V] [Module ℝ V] + [AddCommGroup W] [Module ℝ W] (B : LinearMap.BilinForm ℝ V) + (hB : OnePositive B) (L : W →ₗ[ℝ] V) : OnePositive (B.compl₁₂ L L) := by + intro e he v hv + exact hB (L e) he (L v) hv + +noncomputable def padMatrix (p : ι → Prop) [DecidablePred p] + (B : Matrix {i // p i} {i // p i} ℝ) : Matrix ι ι ℝ := + fun i j => if hi : p i then if hj : p j then B ⟨i,hi⟩ ⟨j,hj⟩ else 0 else 0 + +lemma padMatrix_bilin (p : ι → Prop) [DecidablePred p] + (B : Matrix {i // p i} {i // p i} ℝ) (v w : ι → ℝ) : + (padMatrix p B).toBilin' v w = B.toBilin' (fun i => v i.val) (fun i => w i.val) := by + simp only [Matrix.toBilin'_apply] + rw [← Fintype.sum_subtype_add_sum_subtype p + (fun i => ∑ j, v i * padMatrix p B i j * w j)] + have hn : (∑ i : {i // ¬p i}, ∑ j, v i.val * padMatrix p B i.val j * w j) = 0 := by + apply Finset.sum_eq_zero + intro i _ + apply Finset.sum_eq_zero + intro j _ + simp [padMatrix, i.property] + rw [hn, add_zero] + apply Finset.sum_congr rfl + intro i _ + rw [← Fintype.sum_subtype_add_sum_subtype p + (fun j => v i.val * padMatrix p B i.val j * w j)] + have hn' : (∑ j : {j // ¬p j}, v i.val * padMatrix p B i.val j.val * w j.val) = 0 := by + apply Finset.sum_eq_zero + intro j _ + simp [padMatrix, i.property, j.property] + rw [hn', add_zero] + apply Finset.sum_congr rfl + intro j _ + simp [padMatrix, i.property, j.property] + +lemma onePositive_padMatrix (p : ι → Prop) [DecidablePred p] + (B : Matrix {i // p i} {i // p i} ℝ) (hB : OnePositive B.toBilin') : + OnePositive (padMatrix p B).toBilin' := by + intro e he v hv + rw [padMatrix_bilin] at he hv ⊢ + exact hB _ he _ hv + +lemma matrix_reindex_bilin {κ : Type*} [Fintype κ] (e : ι ≃ κ) + (B : Matrix κ κ ℝ) (v w : ι → ℝ) : + (B.submatrix e e).toBilin' v w = + B.toBilin' (fun j => v (e.symm j)) (fun j => w (e.symm j)) := by + simp only [Matrix.toBilin'_apply, Matrix.submatrix_apply] + apply Fintype.sum_equiv e + intro i + apply Fintype.sum_equiv e + intro j + simp + +lemma onePositive_reindex {κ : Type*} [Fintype κ] (e : ι ≃ κ) + (B : Matrix κ κ ℝ) (hB : OnePositive B.toBilin') : + OnePositive (B.submatrix e e).toBilin' := by + intro x hx v hv + rw [matrix_reindex_bilin] at hx hv ⊢ + exact hB _ hx _ hv + +noncomputable def faceEraseEquiv (A : Set ι) (i : {i // i ∉ A}) : + {j : {j // j ∉ A} // j ≠ i} ≃ {j // j ∉ insert i.val A} where + toFun j := ⟨j.val.val, by + simp only [Set.mem_insert_iff, not_or] + exact ⟨fun h => j.property (Subtype.ext h), j.val.property⟩⟩ + invFun j := ⟨⟨j.val, fun h => j.property (Set.mem_insert_of_mem _ h)⟩, + fun h => j.property (Or.inl (congrArg Subtype.val h))⟩ + left_inv j := rfl + right_inv j := rfl + +noncomputable def faceCubic (f : Set ι → ℝ) (A : Set ι) : + {i // i ∉ A} → Matrix {i // i ∉ A} {i // i ∉ A} ℝ := + fun i j k => if i = j ∨ i = k ∨ j = k then 0 else f (insert i.val (A ∪ {j.val,k.val})) + +omit sectionInstance12 in +lemma faceCubic_symm [Fintype ι] (f : Set ι → ℝ) (A : Set ι) (i j k : {i // i ∉ A}) : + faceCubic f A i j k = faceCubic f A i k j := by + unfold faceCubic + have hc : (i = j ∨ i = k ∨ j = k) ↔ (i = k ∨ i = j ∨ k = j) := by aesop + simp only [← hc] + have hs : ({j.val,k.val} : Set ι) = {k.val,j.val} := Set.pair_comm _ _ + rw [hs] + +omit sectionInstance12 in +lemma faceCubic_transpose [Fintype ι] (f : Set ι → ℝ) (A : Set ι) (i j k : {i // i ∉ A}) : + faceCubic f A i j k = faceCubic f A j i k := by + unfold faceCubic + have hc : (i = j ∨ i = k ∨ j = k) ↔ (j = i ∨ j = k ∨ i = k) := by aesop + simp only [← hc] + have hs : insert i.val (A ∪ {j.val,k.val}) = insert j.val (A ∪ {i.val,k.val}) := by + ext x; simp; tauto + rw [hs] + +omit sectionInstance12 in +lemma faceCubic_pad [Fintype ι] (f : Set ι → ℝ) (A : Set ι) (i : {i // i ∉ A}) : + faceCubic f A i = padMatrix (fun j => j ≠ i) + ((faceHessian f (insert i.val A)).submatrix (faceEraseEquiv A i) (faceEraseEquiv A i)) := by + ext j k + simp only [faceCubic, padMatrix] + by_cases hji : j = i + · subst j; simp + by_cases hki : k = i + · subst k; simp + rw [dite_eq_left hji, dite_eq_left hki] + simp only [Matrix.submatrix_apply, faceHessian] + by_cases hjk : j = k + · subst k; simp + have hi : i ≠ j := Ne.symm hji + have hk : i ≠ k := Ne.symm hki + have hne : faceEraseEquiv A i ⟨j,hji⟩ ≠ faceEraseEquiv A i ⟨k,hki⟩ := by + intro h + exact hjk (congrArg Subtype.val ((faceEraseEquiv A i).injective h)) + simp only [hi, hk, hjk, false_or, ite_false, hne] + congr 1 + ext x + simp [faceEraseEquiv] + tauto + +lemma faceCubic_onePositive (f : Set ι → ℝ) + (hf : ∀ A, OnePositive (faceHessian f A).toBilin') + (A : Set ι) (i : {i // i ∉ A}) : OnePositive (faceCubic f A i).toBilin' := by + classical + rw [faceCubic_pad] + apply onePositive_padMatrix + apply onePositive_reindex + convert hf (insert i.val A) using 1 + congr 2 <;> exact Subsingleton.elim _ _ + +omit sectionInstance13 in +lemma ncard_union_pair [DecidableEq ι] (A : Set ι) (i j : {i // i ∉ A}) (hij : i ≠ j) : + (A ∪ {i.val,j.val}).ncard = A.ncard + 2 := by + have he : A ∪ {i.val,j.val} = insert i.val (insert j.val A) := by ext x; simp + have hne : i.val ≠ j.val := fun h => hij (Subtype.ext h) + rw [he, Set.ncard_insert_of_notMem (by simpa using And.intro hne i.property), + Set.ncard_insert_of_notMem j.property] + +lemma ncard_insert_union_pair (A : Set ι) (i j k : {i // i ∉ A}) + (hij : i ≠ j) (hik : i ≠ k) (hjk : j ≠ k) : + (insert i.val (A ∪ {j.val,k.val})).ncard = A.ncard + 3 := by + have hi : i.val ∉ A ∪ {j.val,k.val} := by + simp only [Set.mem_union, Set.mem_insert_iff, Set.mem_singleton_iff, not_or] + exact ⟨i.property, fun h => hij (Subtype.ext h), fun h => hik (Subtype.ext h)⟩ + rw [Set.ncard_insert_of_notMem hi, ncard_union_pair A j k hjk] + +lemma faceCubic_contraction (f : Set ι → ℝ) (a : ι → ℝ) (A : Set ι) + (j k : {i // i ∉ A}) : + faceHessian (coeffDeriv a f) A j k = + ∑ i : {i // i ∉ A}, a i.val * faceCubic f A i j k := by + classical + by_cases hjk : j = k + · subst k; simp [faceHessian, faceCubic] + change (if j = k then 0 else coeffDeriv a f (A ∪ {j.val,k.val})) = _ + rw [ite_eq_right hjk] + unfold coeffDeriv + let g : ι → ℝ := fun i => @ite ℝ (i ∈ A ∪ {j.val,k.val}) + (Classical.propDecidable _) 0 (a i * f (insert i (A ∪ {j.val,k.val}))) + change (∑ i, g i) = _ + rw [← Fintype.sum_subtype_add_sum_subtype (fun i => i ∉ A) g] + have hz : (∑ i : {i // ¬i ∉ A}, g i.val) = 0 := by + apply Finset.sum_eq_zero + intro i _ + dsimp [g] + rw [ite_eq_left (Set.mem_union_left _ (not_not.mp i.property))] + rw [hz, add_zero] + apply Finset.sum_congr rfl + intro i _ + dsimp only [g] + by_cases hij : i = j + · subst j; simp [faceCubic] + by_cases hik : i = k + · subst k; simp [faceCubic] + have hni : i.val ∉ A ∪ {j.val,k.val} := by + simp only [Set.mem_union, Set.mem_insert_iff, Set.mem_singleton_iff, not_or] + exact ⟨i.property, fun h => hij (Subtype.ext h), fun h => hik (Subtype.ext h)⟩ + simp only [ite_eq_right hni, faceCubic, hij, hik, hjk, false_or, ite_false] + +omit sectionInstance12 in +lemma faceCubic_nonneg [Fintype ι] (f : Set ι → ℝ) (hf : ∀ A, 0 ≤ f A) (A : Set ι) + (i j k : {i // i ∉ A}) : 0 ≤ faceCubic f A i j k := by + unfold faceCubic + split_ifs + · exact le_rfl + · exact hf _ + +lemma FullPositive.faceCubic_pos {f : Set ι → ℝ} {m : ℕ} (hf : FullPositive f m) + (A : Set ι) (hA : A.ncard + m + 3 ≤ Fintype.card ι) + (i j k : {i // i ∉ A}) (hij : i ≠ j) (hik : i ≠ k) (hjk : j ≠ k) : + 0 < faceCubic f A i j k := by + simp only [faceCubic, hij, hik, hjk, false_or, ite_false] + apply hf.1 + rw [ncard_insert_union_pair A i j k hij hik hjk] + omega + +lemma FullPositive.faceCubic_zero {f : Set ι → ℝ} {m : ℕ} (hf : FullPositive f m) + (A : Set ι) (hA : Fintype.card ι < A.ncard + m + 3) + (i j k : {i // i ∉ A}) : faceCubic f A i j k = 0 := by + unfold faceCubic + split_ifs with hc + · rfl + · obtain ⟨hij,hik,hjk⟩ : i ≠ j ∧ i ≠ k ∧ j ≠ k := by tauto + apply hf.2 + rw [ncard_insert_union_pair A i j k hij hik hjk] + omega + +theorem derivative_face_signature {f : Set ι → ℝ} {m : ℕ} + (hf : FullPositive f m) (hfs : ∀ A, OnePositive (faceHessian f A).toBilin') + (a : ι → ℝ) (ha : ∀ i, 0 < a i) (A : Set ι) : + OnePositive (faceHessian (coeffDeriv a f) A).toBilin' := by + classical + have heq : faceHessian (coeffDeriv a f) A = + cubicContraction (faceCubic f A) (fun i => a i.val) := by + ext j k + exact faceCubic_contraction f a A j k + rw [heq] + by_cases hA : A.ncard + m + 3 ≤ Fintype.card ι + · obtain ⟨i, hi⟩ := exists_outside_of_ncard_lt A (by omega) + let : Nonempty {i // i ∉ A} := ⟨⟨i,hi⟩⟩ + have hn : ∀ j k, 0 ≤ cubicContraction (faceCubic f A) (fun i => a i.val) j k := by + intro j k + apply Finset.sum_nonneg + intro i _ + exact mul_nonneg (ha _).le (faceCubic_nonneg f hf.nonneg A i j k) + have hp : ∀ j k, j ≠ k → + 0 < cubicContraction (faceCubic f A) (fun i => a i.val) j k := by + intro j k hjk + obtain ⟨l,hl⟩ := exists_outside_of_ncard_lt (A ∪ {j.val,k.val}) + (by rw [ncard_union_pair A j k hjk]; omega) + have hlA : l ∉ A := fun h => hl (Or.inl h) + let l' : {i // i ∉ A} := ⟨l,hlA⟩ + have hlj : l' ≠ j := by intro h; exact hl (Or.inr (Or.inl (congrArg Subtype.val h))) + have hlk : l' ≠ k := by intro h; exact hl (Or.inr (Or.inr (congrArg Subtype.val h))) + apply Finset.sum_pos' + · intro i _ + exact mul_nonneg (ha _).le (faceCubic_nonneg f hf.nonneg A i j k) + · exact ⟨l', Finset.mem_univ _, mul_pos (ha l) (hf.faceCubic_pos A hA l' j k hlj hlk hjk)⟩ + apply cubic_signature (faceCubic f A) (faceCubic_symm f A) (faceCubic_transpose f A) + (faceCubic_onePositive f hfs A) (fun i => a i.val) (fun i => ha i.val) _ hn hp + intro j + rw [cubicContraction_row _ (faceCubic_transpose f A)] + change 0 < ∑ k, cubicContraction (faceCubic f A) (fun i => a i.val) j k * a k.val + obtain ⟨k,hk⟩ := exists_outside_of_ncard_lt (insert j.val A) + (by rw [ncard_insert_eq A j.val j.property]; omega) + have hkA : k ∉ A := fun h => hk (Or.inr h) + let k' : {i // i ∉ A} := ⟨k,hkA⟩ + have hjk : j ≠ k' := by intro h; exact hk (Or.inl (congrArg Subtype.val h).symm) + apply Finset.sum_pos' + · intro k _; exact mul_nonneg (hn j k) (ha _).le + · exact ⟨k', Finset.mem_univ _, mul_pos (hp j k' hjk) (ha k)⟩ + · have hz : cubicContraction (faceCubic f A) (fun i => a i.val) = 0 := by + ext j k + simp [cubicContraction, hf.faceCubic_zero A (lt_of_not_ge hA)] + rw [hz] + intro e he + simp + +omit sectionInstance13 in +lemma rankWeight_fullPositive [DecidableEq ι] (M : Matroid ι) (q : ℝ) (hq : 0 < q) : + FullPositive (rankWeight M q) 0 := by + constructor + · intro A _; unfold rankWeight; positivity + · intro A hA + have hbound : A.ncard ≤ Fintype.card ι := by simpa using Set.ncard_le_card A + omega + +theorem rankWeight_positive_directions (M : Matroid ι) (hE : M.E = Set.univ) + (q : ℝ) (hq : 0 < q) (hq1 : q ≤ 1) (ds : List (ι → ℝ)) + (hds : ∀ a ∈ ds, ∀ i, 0 < a i) : + FullPositive (coeffDerivs ds (rankWeight M q)) ds.length ∧ + ∀ A, OnePositive (faceHessian (coeffDerivs ds (rankWeight M q)) A).toBilin' := by + induction ds with + | nil => + exact ⟨rankWeight_fullPositive M q hq, rankWeight_face_signature M hE q hq hq1⟩ + | cons a ds ih => + have ha := hds a (List.mem_cons_self ..) + obtain ⟨hpos,hsig⟩ := ih (fun b hb => hds b (List.mem_cons_of_mem _ hb)) + exact ⟨hpos.deriv a ha, derivative_face_signature hpos hsig a ha⟩ + +lemma matrix_bilin_tendsto {κ : Type*} {l : Filter κ} + (F : κ → Matrix ι ι ℝ) (B : Matrix ι ι ℝ) + (hF : ∀ i j, Filter.Tendsto (fun t => F t i j) l (nhds (B i j))) + (v w : ι → ℝ) : + Filter.Tendsto (fun t => (F t).toBilin' v w) l (nhds (B.toBilin' v w)) := by + simp only [Matrix.toBilin'_apply] + apply tendsto_finsetSum + intro i _ + apply tendsto_finsetSum + intro j _ + exact ((tendsto_const_nhds.mul (hF i j)).mul tendsto_const_nhds) + +lemma onePositive_of_tendsto {κ : Type*} {l : Filter κ} [l.NeBot] + (F : κ → Matrix ι ι ℝ) (B : Matrix ι ι ℝ) + (hF : ∀ i j, Filter.Tendsto (fun t => F t i j) l (nhds (B i j))) + (hS : ∀ t i j, F t i j = F t j i) + (hP : ∀ᶠ t in l, OnePositive (F t).toBilin') : OnePositive B.toBilin' := by + intro e he v hv + have hee := matrix_bilin_tendsto F B hF e e + have hvv := matrix_bilin_tendsto F B hF v v + have hve := matrix_bilin_tendsto F B hF v e + have hp : ∀ᶠ t in l, (F t).toBilin' v v * (F t).toBilin' e e ≤ + ((F t).toBilin' v e)^2 := by + filter_upwards [hP, hee.eventually (eventually_gt_nhds he)] with t ht hte + exact (le_div_iff₀ hte).mp + (onePositive_quadratic_bound _ ht (matrix_bilin_symm _ (hS t)) e v hte) + have hh := le_of_tendsto_of_tendsto (hvv.mul hee) (hve.pow 2) hp + rw [hv, zero_pow (by decide : 2 ≠ 0)] at hh + exact nonpos_of_mul_nonpos_right (by simpa [mul_comm] using hh) he + +omit sectionInstance12 in +lemma faceHessian_symm [Fintype ι] (f : Set ι → ℝ) (A : Set ι) : + ∀ i j, faceHessian f A i j = faceHessian f A j i := by + intro i j + simp only [faceHessian] + by_cases hij : i = j + · subst j; rfl + · rw [ite_eq_right hij, ite_eq_right (Ne.symm hij), Set.pair_comm] + +omit sectionInstance13 in +lemma continuous_coeffDerivs_perturb [DecidableEq ι] (ds : List (ι → ℝ)) (f : Set ι → ℝ) (A : Set ι) : + Continuous (fun t : ℝ => coeffDerivs (ds.map (fun a i => a i + t)) f A) := by + induction ds generalizing A with + | nil => exact continuous_const + | cons a ds ih => + simp only [List.map_cons, coeffDerivs, coeffDeriv] + apply continuous_finsetSum + intro i _ + by_cases hi : i ∈ A + · simp only [ite_eq_left hi]; exact continuous_const + · simp only [ite_eq_right hi] + exact (continuous_const.add continuous_id).mul (ih _) + +theorem rankWeight_nonnegative_directions (M : Matroid ι) (hE : M.E = Set.univ) + (q : ℝ) (hq : 0 < q) (hq1 : q ≤ 1) (ds : List (ι → ℝ)) + (hds : ∀ a ∈ ds, ∀ i, 0 ≤ a i) (A : Set ι) : + OnePositive (faceHessian (coeffDerivs ds (rankWeight M q)) A).toBilin' := by + classical + let F : ℝ → Matrix {i // i ∉ A} {i // i ∉ A} ℝ := fun t => + faceHessian (coeffDerivs (ds.map (fun a i => a i + t)) (rankWeight M q)) A + have hzero : F 0 = faceHessian (coeffDerivs ds (rankWeight M q)) A := by + simp [F] + rw [← hzero] + let l := nhdsWithin (0 : ℝ) (Set.Ioi 0) + have : l.NeBot := nhdsWithin_Ioi_neBot (le_refl (0 : ℝ)) + apply onePositive_of_tendsto (l := l) F (F 0) + · intro i j + have hc : Continuous (fun t => F t i j) := by + dsimp [F, faceHessian] + by_cases hij : i = j + · simp only [ite_eq_left hij]; exact continuous_const + · simp only [ite_eq_right hij] + exact continuous_coeffDerivs_perturb ds (rankWeight M q) _ + exact hc.continuousAt.tendsto.mono_left nhdsWithin_le_nhds + · exact fun t => faceHessian_symm _ A + · have hpos : ∀ᶠ t in l, 0 < t := self_mem_nhdsWithin + filter_upwards [hpos] with t ht + apply (rankWeight_positive_directions M hE q hq hq1 _ _).2 A + intro b hb i + obtain ⟨a,ha,rfl⟩ := List.mem_map.mp hb + exact add_pos_of_nonneg_of_pos (hds a ha i) ht + +lemma onePositive_matrix_substitution {κ : Type*} [Fintype κ] [DecidableEq κ] + (B : Matrix ι ι ℝ) (hB : OnePositive B.toBilin') (L : Matrix ι κ ℝ) : + OnePositive (L.transpose * B * L).toBilin' := by + rw [← Matrix.toBilin'_comp] + intro e he v hv + exact hB (L.toLin' e) he (L.toLin' v) hv + +noncomputable def slotDirection (E : Finset ι) (i : ι) : ℝ := if i ∈ E then 1 else 0 + +omit sectionInstance12 in +lemma slotDirection_nonneg [Fintype ι] (E : Finset ι) (i : ι) : 0 ≤ slotDirection E i := by + unfold slotDirection + split_ifs <;> norm_num + +lemma coeffDeriv_slot (E : Finset ι) (f : Set ι → ℝ) (A : Set ι) : + coeffDeriv (slotDirection E) f A = + ∑ i ∈ E, if i ∈ A then 0 else f (insert i A) := by + classical + unfold coeffDeriv slotDirection + rw [← Finset.sum_subset (Finset.subset_univ E)] + · apply Finset.sum_congr rfl + intro i hi + simp [hi] + · intro i _ hi + simp [hi] + +lemma coeffDeriv_pair (a b : ι) (hab : a ≠ b) (f : Set ι → ℝ) (A : Set ι) + (ha : a ∉ A) (hb : b ∉ A) : + coeffDeriv (slotDirection {a,b}) f A = f (insert a A) + f (insert b A) := by + rw [coeffDeriv_slot] + simp [hab, ha, hb] + +theorem matroid_slot_signature {κ : Type*} [Fintype κ] [DecidableEq κ] + (M : Matroid ι) (hE : M.E = Set.univ) (q : ℝ) (hq : 0 < q) (hq1 : q ≤ 1) + (slots : List (Finset ι)) (A : Set ι) + (L : Matrix {i // i ∉ A} κ ℝ) : + OnePositive (L.transpose * + faceHessian (coeffDerivs (slots.map slotDirection) (rankWeight M q)) A * L).toBilin' := by + apply onePositive_matrix_substitution + apply rankWeight_nonnegative_directions M hE q hq hq1 + intro a ha i + obtain ⟨E,_,rfl⟩ := List.mem_map.mp ha + exact slotDirection_nonneg E i + +omit sectionInstance12 sectionInstance13 in +lemma onePositive_smul [Fintype ι] [DecidableEq ι] (B : LinearMap.BilinForm ℝ (ι → ℝ)) + (hB : OnePositive B) (c : ℝ) (hc : 0 < c) : OnePositive (c • B) := by + intro e he v hv + change 0 < c * B e e at he + change c * B v e = 0 at hv + change c * B v v ≤ 0 + have he' : 0 < B e e := (mul_pos_iff_of_pos_left hc).mp he + have hv' : B v e = 0 := (mul_eq_zero.mp hv).resolve_left (ne_of_gt hc) + exact mul_nonpos_of_nonneg_of_nonpos hc.le (hB e he' v hv') + +lemma onePositive_submatrix {κ : Type*} [Fintype κ] [DecidableEq κ] + (B : Matrix ι ι ℝ) (hB : OnePositive B.toBilin') (e : κ → ι) : + OnePositive (B.submatrix e e).toBilin' := by + classical + let L : Matrix ι κ ℝ := fun i j => if i = e j then 1 else 0 + have heq : L.transpose * B * L = B.submatrix e e := by + ext i j + change (∑ k, (∑ l, (if l = e i then (1 : ℝ) else 0) * B l k) * + (if k = e j then (1 : ℝ) else 0)) = B (e i) (e j) + simp + rw [← heq] + exact onePositive_matrix_substitution B hB L + +end DerivativeClosure + +theorem quadratic_split_bound (B : LinearMap.BilinForm ℝ V) + (hB : OnePositive B) (hsymm : B.IsSymm) + (e h d : V) (u X : ℝ) (hu : 0 < u) + (hee : 0 < B e e) (hhe : B h e = 0) (hde : B d e = 0) + (hhd : B h d = -2 * X) (hdd : B d d = -2 * u) : + 2 * X ^ 2 / u ≤ -B h h := by + have hor : B (h - (X / u) • d) e = 0 := by + simp [map_sub, map_smul, hhe, hde] + have hn := hB e hee (h - (X / u) • d) hor + have hdh : B d h = -2 * X := by rw [hsymm.eq d h, hhd] + simp only [map_sub, map_smul, LinearMap.sub_apply, LinearMap.smul_apply, + smul_eq_mul, hhd, hdh, hdd] at hn + have hu0 : u ≠ 0 := ne_of_gt hu + field_simp at hn ⊢ + nlinarith + +section MatrixSplit + +open scoped BigOperators +variable {ι : Type*} [Fintype ι] [sectionInstance15 : DecidableEq ι] + +def splitMatrix (V : Matrix ι ι ℝ) (sa sb : ι → ℝ) (u : ℝ) : + Matrix (ι ⊕ Bool) (ι ⊕ Bool) ℝ + | .inl i, .inl j => V i j + | .inl i, .inr false => sb i + | .inl i, .inr true => sa i + | .inr false, .inl i => sb i + | .inr true, .inl i => sa i + | .inr a, .inr b => if a = b then 0 else u + +def oldVector (h : ι → ℝ) : (ι ⊕ Bool) → ℝ + | .inl i => h i + | .inr _ => 0 + +def splitPositive : (ι ⊕ Bool) → ℝ + | .inl _ => 0 + | .inr _ => 1 + +def splitDifference : (ι ⊕ Bool) → ℝ + | .inl _ => 0 + | .inr false => 1 + | .inr true => -1 + +theorem splitMatrix_symm (V : Matrix ι ι ℝ) (sa sb : ι → ℝ) (u : ℝ) + (hV : ∀ i j, V i j = V j i) : (splitMatrix V sa sb u).toBilin'.IsSymm := by + apply matrix_bilin_symm + intro i j + cases i with + | inl i => cases j with + | inl j => exact hV i j + | inr b => cases b <;> rfl + | inr a => cases a <;> cases j with + | inl j => rfl + | inr b => cases b <;> rfl + +theorem split_bound (V : Matrix ι ι ℝ) (sa sb h : ι → ℝ) (u : ℝ) + (hu : 0 < u) (hV : ∀ i j, V i j = V j i) + (hA : OnePositive (splitMatrix V sa sb u).toBilin') + (hbal : ∑ i, (sa i + sb i) * h i = 0) : + 2 * (∑ i, h i * sa i)^2 / u ≤ - V.toBilin' h h := by + have bal : (∑ i, h i * sb i) = -(∑ i, h i * sa i) := by + simp_rw [add_mul, Finset.sum_add_distrib] at hbal + have hs : ∀ f : ι → ℝ, (∑ i, f i * h i) = ∑ i, h i * f i := by + intro f + apply Finset.sum_congr rfl + intro i _ + ring + rw [hs sa, hs sb] at hbal + linarith + have hh : (splitMatrix V sa sb u).toBilin' (oldVector h) (oldVector h) = + V.toBilin' h h := by + simp [Matrix.toBilin'_apply, Fintype.sum_sum_type, + splitMatrix, oldVector] + rw [← hh] + apply quadratic_split_bound (splitMatrix V sa sb u).toBilin' hA + (splitMatrix_symm V sa sb u hV) splitPositive (oldVector h) splitDifference + u (∑ i, h i * sa i) hu + · simpa [Matrix.toBilin'_apply, Fintype.sum_sum_type, Fintype.sum_bool, + splitMatrix, splitPositive] using (show 0 < u + u by linarith) + · simp [Matrix.toBilin'_apply, Fintype.sum_sum_type, + splitMatrix, splitPositive, oldVector, Finset.sum_add_distrib, bal] + · simp [Matrix.toBilin'_apply, Fintype.sum_sum_type, + splitMatrix, splitPositive, splitDifference] + · simp [Matrix.toBilin'_apply, Fintype.sum_sum_type, + splitMatrix, splitDifference, oldVector, Finset.sum_add_distrib, + bal] + ring + · simp [Matrix.toBilin'_apply, Fintype.sum_sum_type, + splitMatrix, splitDifference] + ring + +def futureChild (V : Matrix ι ι ℝ) (c : ι → ℝ) : Matrix (Option ι) (Option ι) ℝ + | some i, some j => V i j + | some i, none => c i + | none, some j => c j + | none, none => 0 + +def extendVector (h : ι → ℝ) (a : ℝ) : Option ι → ℝ + | some i => h i + | none => a + +theorem future_conservation (Va Vb : Matrix ι ι ℝ) (c h : ι → ℝ) (a : ℝ) : + (futureChild Va c).toBilin' (extendVector h a) (extendVector h a) + + (futureChild Vb c).toBilin' (extendVector h (-a)) (extendVector h (-a)) = + (Va + Vb).toBilin' h h := by + simp only [Matrix.toBilin'_apply, Fintype.sum_option, futureChild, extendVector, + mul_zero, zero_mul, Matrix.add_apply, mul_add, add_mul, + Finset.sum_add_distrib, mul_neg, neg_mul, Finset.sum_neg_distrib] + ring + +omit sectionInstance15 in +theorem child_balance [DecidableEq ι] (s h : ι → ℝ) (u : ℝ) (hu : u ≠ 0) : + ∑ i : Option ι, extendVector s u i * + extendVector h (-(∑ j, h j * s j) / u) i = 0 := by + simp only [Fintype.sum_option, extendVector] + have hcomm : (∑ j, s j * h j) = ∑ j, h j * s j := by + apply Finset.sum_congr rfl + intro i _ + ring + rw [hcomm] + field_simp + ring + +omit sectionInstance15 in +theorem demand_conservation [DecidableEq ι] (ga gb h : ι → ℝ) (g a : ℝ) : + (∑ i : Option ι, extendVector h a i * extendVector ga g i) + + (∑ i : Option ι, extendVector h (-a) i * extendVector gb g i) = + ∑ i, h i * (ga i + gb i) := by + simp only [Fintype.sum_option, extendVector, mul_add, neg_mul, Finset.sum_add_distrib] + ring + +omit sectionInstance15 in +theorem potential_increment [DecidableEq ι] (sa sb h W : ι → ℝ) (u wt X : ℝ) + (hu : u ≠ 0) (hw : wt ≠ 0) : + (∑ i : Option ι, extendVector sa u i * + (extendVector h (-X/u) i)^2 / extendVector W wt i) + + (∑ i : Option ι, extendVector sb u i * + (extendVector h (X/u) i)^2 / extendVector W wt i) = + (∑ i, (sa i + sb i) * (h i)^2 / W i) + 2*X^2/(u*wt) := by + simp only [Fintype.sum_option, extendVector, add_mul, add_div, Finset.sum_add_distrib] + field_simp + ring + +omit sectionInstance15 in +theorem leaf_clique_bound [DecidableEq ι] (s W h H : ι → ℝ) (hub : ι) + (hs : ∀ i, 0 < s i) (hW : ∀ i, 0 < W i) + (hbal : ∑ i, s i * h i = 0) : + 2 * (∑ i, s i * h i * H i) ≤ + (∑ i, s i * (h i)^2 / W i) + + ∑ i, W i * s i * (H i - H hub)^2 := by + have hterm : ∀ i, 2*(s i*h i*(H i-H hub)) ≤ + s i*(h i)^2/W i + W i*s i*(H i-H hub)^2 := by + intro i + have hsq := mul_nonneg (div_nonneg (le_of_lt (hs i)) (le_of_lt (hW i))) + (sq_nonneg (h i-W i*(H i-H hub))) + have heq : s i*(h i)^2/W i + W i*s i*(H i-H hub)^2 - + 2*(s i*h i*(H i-H hub)) = + (s i/W i)*(h i-W i*(H i-H hub))^2 := by + field_simp [ne_of_gt (hW i)] + ; ring + linarith + have hsum := Finset.sum_le_sum (s := Finset.univ) (fun i _ => hterm i) + have hz : (∑ i, s i * h i * H hub) = 0 := by + rw [← Finset.sum_mul, hbal, zero_mul] + simpa only [mul_sub, Finset.sum_sub_distrib, Finset.sum_add_distrib, + ← Finset.mul_sum, hz, mul_zero, sub_zero] using hsum + +end MatrixSplit + +section RecursiveTransport +open scoped BigOperators Classical Matrix +variable {Γ : Type*} [sectionInstance16 : Fintype Γ] [sectionInstance17 : DecidableEq Γ] + +noncomputable def pairDirection (p : Γ × Γ) : Γ → ℝ := slotDirection {p.1,p.2} + +noncomputable def slotTotal (ps : List (Γ × Γ)) (f : Set Γ → ℝ) : Set Γ → ℝ := + coeffDerivs (ps.map pairDirection) f + +lemma slotTotal_nil (f : Set Γ → ℝ) (A : Set Γ) : slotTotal [] f A = f A := rfl + +lemma slotTotal_cons (p : Γ × Γ) (ps : List (Γ × Γ)) (f : Set Γ → ℝ) + (A : Set Γ) (hp : p.1 ≠ p.2) (ha : p.1 ∉ A) (hb : p.2 ∉ A) : + slotTotal (p::ps) f A = slotTotal ps f (insert p.1 A) + + slotTotal ps f (insert p.2 A) := by + exact coeffDeriv_pair p.1 p.2 hp (slotTotal ps f) A ha hb + +def SlotsFresh : List (Γ × Γ) → Set Γ → Prop + | [], _ => True + | p::ps, B => p.1 ≠ p.2 ∧ p.1 ∉ B ∧ p.2 ∉ B ∧ + SlotsFresh ps (insert p.1 (insert p.2 B)) + +omit sectionInstance16 sectionInstance17 in +lemma SlotsFresh.mono [Fintype Γ] [DecidableEq Γ] {ps : List (Γ × Γ)} {A B : Set Γ} + (h : SlotsFresh ps B) (hAB : A ⊆ B) : SlotsFresh ps A := by + induction ps generalizing A B with + | nil => trivial + | cons p ps ih => + obtain ⟨hp,ha,hb,ht⟩ := h + exact ⟨hp, fun hx => ha (hAB hx), fun hx => hb (hAB hx), + ih ht (Set.insert_subset_insert (Set.insert_subset_insert hAB))⟩ + +lemma slotTotal_pos (ps : List (Γ × Γ)) (f : Set Γ → ℝ) + (hf : ∀ A, 0 < f A) (A : Set Γ) (hps : SlotsFresh ps A) : + 0 < slotTotal ps f A := by + induction ps generalizing A with + | nil => exact hf A + | cons p ps ih => + obtain ⟨hp,ha,hb,ht⟩ := hps + rw [slotTotal_cons p ps f A hp ha hb] + apply add_pos + · apply ih _ (ht.mono _) + intro x hx + rcases hx with rfl | hx + · exact Set.mem_insert _ _ + · exact Set.mem_insert_of_mem _ (Set.mem_insert_of_mem _ hx) + · apply ih _ (ht.mono _) + intro x hx + exact Set.mem_insert_of_mem _ hx + +def appendPoint {ι : Type*} (e : ι → Γ) (a : Γ) : Option ι → Γ + | none => a + | some i => e i + +omit sectionInstance16 sectionInstance17 in +lemma range_appendPoint [Fintype Γ] [DecidableEq Γ] {ι : Type*} (e : ι → Γ) (a : Γ) : + Set.range (appendPoint e a) = insert a (Set.range e) := by + ext x + constructor + · rintro ⟨i,rfl⟩ + cases i with + | none => exact Or.inl rfl + | some i => exact Or.inr ⟨i,rfl⟩ + · rintro (rfl | ⟨i,rfl⟩) + · exact ⟨none,rfl⟩ + · exact ⟨some i,rfl⟩ + +omit sectionInstance16 sectionInstance17 in +lemma appendPoint_injective [Fintype Γ] [DecidableEq Γ] {ι : Type*} (e : ι → Γ) (a : Γ) + (he : Function.Injective e) (ha : a ∉ Set.range e) : + Function.Injective (appendPoint e a) := by + intro i j h + cases i <;> cases j + · rfl + · exact False.elim (ha ⟨_,h.symm⟩) + · exact False.elim (ha ⟨_,h⟩) + · exact congrArg some (he h) + +lemma slotsFresh_child {ι : Type*} (e : ι → Γ) (A : Set Γ) (p : Γ × Γ) + (ps : List (Γ × Γ)) (h : SlotsFresh (p::ps) (A ∪ Set.range e)) : + SlotsFresh ps (insert p.2 A ∪ Set.range (appendPoint e p.1)) ∧ + SlotsFresh ps (insert p.1 A ∪ Set.range (appendPoint e p.2)) := by + obtain ⟨_,_,_,ht⟩ := h + rw [range_appendPoint, range_appendPoint] + constructor + · convert ht using 1 ; ext x ; simp ; tauto + · convert ht using 1 ; ext x ; simp ; tauto + +omit sectionInstance16 sectionInstance17 in +lemma appendPoint_fresh [Fintype Γ] [DecidableEq Γ] {ι : Type*} (e : ι → Γ) (A : Set Γ) (a b : Γ) + (he : ∀ i, e i ∉ A) (hab : a ≠ b) (ha : a ∉ A) + (hb : b ∉ Set.range e) : ∀ i, appendPoint e a i ∉ insert b A := by + intro i + cases i with + | none => exact fun h => h.elim hab ha + | some i => + intro h + rcases h with h | h + · exact hb ⟨i,h⟩ + · exact he i h + +noncomputable def pairMatrix {ι : Type*} [DecidableEq ι] + (f : Set Γ → ℝ) (A : Set Γ) (e : ι → Γ) : Matrix ι ι ℝ := + fun i j => if i = j then 0 else f (insert (e i) (insert (e j) A)) + +omit sectionInstance16 sectionInstance17 in +lemma pairMatrix_symm [Fintype Γ] [DecidableEq Γ] {ι : Type*} [DecidableEq ι] + (f : Set Γ → ℝ) (A : Set Γ) (e : ι → Γ) : + ∀ i j, pairMatrix f A e i j = pairMatrix f A e j i := by + intro i j + by_cases hij : i = j + · subst j; rfl + · simp only [pairMatrix, hij, Ne.symm hij, ite_false, Set.insert_comm] + +def HasSlotSignature (f : Set Γ → ℝ) : Prop := + ∀ (ps : List (Γ × Γ)) (A : Set Γ), + OnePositive (faceHessian (slotTotal ps f) A).toBilin' + +lemma rankWeight_hasSlotSignature (M : Matroid Γ) (hE : M.E = Set.univ) + (q : ℝ) (hq : 0 < q) (hq1 : q ≤ 1) : HasSlotSignature (rankWeight M q) := by + intro ps A + apply rankWeight_nonnegative_directions M hE q hq hq1 + intro a ha i + obtain ⟨p,_,rfl⟩ := List.mem_map.mp ha + exact slotDirection_nonneg _ i + +lemma pairMatrix_signature {ι : Type*} [Fintype ι] [DecidableEq ι] + (f : Set Γ → ℝ) (hSig : HasSlotSignature f) + (ps : List (Γ × Γ)) (A : Set Γ) (e : ι → Γ) + (he : Function.Injective e) (heA : ∀ i, e i ∉ A) : + OnePositive (pairMatrix (slotTotal ps f) A e).toBilin' := by + let e' : ι → {i // i ∉ A} := fun i => ⟨e i,heA i⟩ + have hEq : pairMatrix (slotTotal ps f) A e = + (faceHessian (slotTotal ps f) A).submatrix e' e' := by + ext i j + by_cases hij : i = j + · subst j; simp [pairMatrix,faceHessian] + · have hne : e' i ≠ e' j := fun h => hij (he (congrArg Subtype.val h)) + simp only [pairMatrix, hij, ite_false, Matrix.submatrix_apply, faceHessian, hne] + congr 1 + ext x + simp [e'] + rw [hEq] + exact onePositive_submatrix _ (hSig ps A) e' + +section Clique +variable {ι : Type*} [Fintype ι] [sectionInstance19 : DecidableEq ι] + +lemma star_le_half_clique (E : ι → ι → ℝ) + (hE : ∀ i j, 0 ≤ E i j) (hS : ∀ i j, E i j = E j i) + (hD : ∀ i, E i i = 0) (hub : ι) : + (∑ i, E i hub) ≤ (∑ i, ∑ j, E i j) / 2 := by + have hrest : (∑ i ∈ Finset.univ.erase hub, E i hub) ≤ + ∑ i ∈ Finset.univ.erase hub, ∑ j, E i j := by + apply Finset.sum_le_sum + intro i _ + exact Finset.single_le_sum (fun j _ => hE i j) (Finset.mem_univ hub) + rw [Finset.sum_erase (f := fun i => E i hub) _ (hD hub)] at hrest + have ht := Finset.sum_erase_add Finset.univ (fun i => ∑ j, E i j) + (Finset.mem_univ hub) + have hrow : (∑ j, E hub j) = ∑ j, E j hub := by simp_rw [hS hub] + rw [hrow] at ht + linarith + +noncomputable def cliqueEnergy (s W H : ι → ℝ) : ℝ := + (∑ i, ∑ j, min (W i*s i) (W j*s j) * (H i-H j)^2) / 2 + +omit sectionInstance19 in +lemma cliqueEnergy_nonneg [DecidableEq ι] (s W H : ι → ℝ) + (hs : ∀ i, 0 ≤ s i) (hW : ∀ i, 0 ≤ W i) : 0 ≤ cliqueEnergy s W H := by + unfold cliqueEnergy + apply div_nonneg _ (by norm_num) + apply Finset.sum_nonneg + intro i _ + apply Finset.sum_nonneg + intro j _ + exact mul_nonneg (le_min (mul_nonneg (hW i) (hs i)) (mul_nonneg (hW j) (hs j))) + (sq_nonneg _) + +lemma clique_linear_bound [Nonempty ι] (s W h H : ι → ℝ) + (hs : ∀ i, 0 < s i) (hW : ∀ i, 0 < W i) + (hbal : ∑ i, s i*h i = 0) : + 2*(∑ i, s i*h i*H i) ≤ (∑ i, s i*(h i)^2/W i) + cliqueEnergy s W H := by + obtain ⟨hub,_,hhub⟩ := Finset.exists_max_image Finset.univ (fun i => W i*s i) + Finset.univ_nonempty + have hl := leaf_clique_bound s W h H hub hs hW hbal + have he := star_le_half_clique (fun i j => min (W i*s i) (W j*s j)*(H i-H j)^2) + (fun i j => mul_nonneg (le_min (mul_pos (hW i) (hs i)).le + (mul_pos (hW j) (hs j)).le) (sq_nonneg _)) + (by intro i j; rw [min_comm]; ring) (by intro i; simp) hub + simp_rw [min_eq_left (hhub _ (Finset.mem_univ _))] at he + unfold cliqueEnergy + linarith + +end Clique + +variable {ι : Type*} [sectionInstance20 : Fintype ι] [sectionInstance21 : DecidableEq ι] + +def splitEmbedding (e : ι → Γ) (a b : Γ) : (ι ⊕ Bool) → Γ + | .inl i => e i + | .inr false => a + | .inr true => b + +omit sectionInstance16 sectionInstance17 sectionInstance20 sectionInstance21 in +lemma splitEmbedding_injective [Fintype Γ] [DecidableEq Γ] [Fintype ι] [DecidableEq ι] (e : ι → Γ) (a b : Γ) + (he : Function.Injective e) (hab : a ≠ b) + (ha : a ∉ Set.range e) (hb : b ∉ Set.range e) : + Function.Injective (splitEmbedding e a b) := by + intro i j hij + cases i with + | inl i => + cases j with + | inl j => exact congrArg Sum.inl (he hij) + | inr x => + cases x with + | false => exact False.elim (ha ⟨i,hij⟩) + | true => exact False.elim (hb ⟨i,hij⟩) + | inr x => + cases j with + | inl j => + cases x with + | false => exact False.elim (ha ⟨j,hij.symm⟩) + | true => exact False.elim (hb ⟨j,hij.symm⟩) + | inr y => + cases x <;> cases y + · rfl + · exact False.elim (hab hij) + · exact False.elim (hab hij.symm) + · rfl + +omit sectionInstance16 sectionInstance17 sectionInstance20 in +lemma pairMatrix_split [Fintype Γ] [DecidableEq Γ] [Fintype ι] (f : Set Γ → ℝ) (A : Set Γ) (e : ι → Γ) (a b : Γ) : + pairMatrix f A (splitEmbedding e a b) = + splitMatrix (pairMatrix f A e) + (fun i => f (insert (e i) (insert b A))) + (fun i => f (insert (e i) (insert a A))) + (f (insert a (insert b A))) := by + ext i j + cases i with + | inl i => + cases j with + | inl j => simp [pairMatrix, splitMatrix, splitEmbedding] + | inr x => cases x <;> simp [pairMatrix, splitMatrix, splitEmbedding] + | inr x => + cases j with + | inl j => cases x <;> simp [pairMatrix, splitMatrix, splitEmbedding, Set.insert_comm] + | inr y => cases x <;> cases y <;> + simp [pairMatrix, splitMatrix, splitEmbedding, Set.insert_comm] + +lemma slot_split_signature (f : Set Γ → ℝ) (hSig : HasSlotSignature f) + (ps : List (Γ × Γ)) (A : Set Γ) (e : ι → Γ) (a b : Γ) + (he : Function.Injective e) (heA : ∀ i, e i ∉ A) (hab : a ≠ b) + (ha : a ∉ A ∪ Set.range e) (hb : b ∉ A ∪ Set.range e) : + OnePositive (splitMatrix (pairMatrix (slotTotal ps f) A e) + (fun i => slotTotal ps f (insert (e i) (insert b A))) + (fun i => slotTotal ps f (insert (e i) (insert a A))) + (slotTotal ps f (insert a (insert b A)))).toBilin' := by + rw [← pairMatrix_split] + apply pairMatrix_signature f hSig ps A _ + (splitEmbedding_injective e a b he hab (fun h => ha (Or.inr h)) (fun h => hb (Or.inr h))) + intro i + cases i with + | inl i => exact heA i + | inr x => + cases x with + | false => exact fun h => ha (Or.inl h) + | true => exact fun h => hb (Or.inl h) + +omit sectionInstance16 sectionInstance17 sectionInstance20 in +lemma pairMatrix_append [Fintype Γ] [DecidableEq Γ] [Fintype ι] (f : Set Γ → ℝ) (A : Set Γ) (e : ι → Γ) (a b : Γ) : + pairMatrix f (insert b A) (appendPoint e a) = + futureChild (pairMatrix f (insert b A) e) + (fun i => f (insert (e i) (insert a (insert b A)))) := by + ext i j + cases i <;> cases j <;> simp [pairMatrix, appendPoint, futureChild, Set.insert_comm] + +omit sectionInstance20 sectionInstance21 in +lemma slotTotal_parent [Fintype ι] [DecidableEq ι] (ps : List (Γ × Γ)) (f : Set Γ → ℝ) (A : Set Γ) + (e : ι → Γ) (p : Γ × Γ) + (hp : p.1 ≠ p.2) (ha : p.1 ∉ A ∪ Set.range e) (hb : p.2 ∉ A ∪ Set.range e) : + ∀ i, slotTotal (p::ps) f (insert (e i) A) = + slotTotal ps f (insert (e i) (insert p.2 A)) + + slotTotal ps f (insert (e i) (insert p.1 A)) := by + intro i + rw [slotTotal_cons p ps f _ hp] + · rw [Set.insert_comm p.1, Set.insert_comm p.2, add_comm] + · intro h + exact h.elim (fun h => ha (Or.inr ⟨i,h.symm⟩)) (fun h => ha (Or.inl h)) + · intro h + exact h.elim (fun h => hb (Or.inr ⟨i,h.symm⟩)) (fun h => hb (Or.inl h)) + +omit sectionInstance20 in +lemma pairMatrix_parent [Fintype ι] (ps : List (Γ × Γ)) (f : Set Γ → ℝ) (A : Set Γ) + (e : ι → Γ) (p : Γ × Γ) + (hp : p.1 ≠ p.2) (ha : p.1 ∉ A ∪ Set.range e) (hb : p.2 ∉ A ∪ Set.range e) : + pairMatrix (slotTotal (p::ps) f) A e = + pairMatrix (slotTotal ps f) (insert p.2 A) e + + pairMatrix (slotTotal ps f) (insert p.1 A) e := by + ext i j + by_cases hij : i = j + · subst j; simp [pairMatrix] + simp only [pairMatrix, hij, ite_false, Matrix.add_apply] + rw [slotTotal_cons p ps f _ hp] + · rw [Set.insert_comm p.1 (e i), Set.insert_comm p.1 (e j), + Set.insert_comm p.2 (e i), Set.insert_comm p.2 (e j), add_comm] + · intro h + rcases h with h | h | h + · exact ha (Or.inr ⟨i,h.symm⟩) + · exact ha (Or.inr ⟨j,h.symm⟩) + · exact ha (Or.inl h) + · intro h + rcases h with h | h | h + · exact hb (Or.inr ⟨i,h.symm⟩) + · exact hb (Or.inr ⟨j,h.symm⟩) + · exact hb (Or.inl h) + +lemma slot_future_conservation (ps : List (Γ × Γ)) (f : Set Γ → ℝ) (A : Set Γ) + (e : ι → Γ) (p : Γ × Γ) (h : ι → ℝ) (c : ℝ) + (hp : p.1 ≠ p.2) (ha : p.1 ∉ A ∪ Set.range e) (hb : p.2 ∉ A ∪ Set.range e) : + (pairMatrix (slotTotal ps f) (insert p.2 A) (appendPoint e p.1)).toBilin' + (extendVector h c) (extendVector h c) + + (pairMatrix (slotTotal ps f) (insert p.1 A) (appendPoint e p.2)).toBilin' + (extendVector h (-c)) (extendVector h (-c)) = + (pairMatrix (slotTotal (p::ps) f) A e).toBilin' h h := by + rw [pairMatrix_append, pairMatrix_append, pairMatrix_parent ps f A e p hp ha hb] + have heq : (fun i => slotTotal ps f (insert (e i) (insert p.2 (insert p.1 A)))) = + (fun i => slotTotal ps f (insert (e i) (insert p.1 (insert p.2 A)))) := by + simp only [Set.insert_comm p.2 p.1] + rw [heq] + exact future_conservation _ _ _ h c + +noncomputable def transportDemand (ps : List (Γ × Γ)) (f H : Set Γ → ℝ) + (A : Set Γ) (e : ι → Γ) (h : ι → ℝ) : ℝ := + ∑ i, h i * slotTotal ps (fun S => f S*H S) (insert (e i) A) + +noncomputable def transportPotential (ps : List (Γ × Γ)) (f : Set Γ → ℝ) + (A : Set Γ) (e : ι → Γ) (h : ι → ℝ) (W : Γ → ℝ) : ℝ := + ∑ i, slotTotal ps f (insert (e i) A) * (h i)^2 / W (e i) + +def slotPunctures : List (Γ × Γ) → List ((Γ × Γ) × List (Γ × Γ)) + | [] => [] + | p::ps => (p,ps) :: (slotPunctures ps).map (fun x => (x.1,p::x.2)) + +noncomputable def transportCorrection (ps : List (Γ × Γ)) (f : Set Γ → ℝ) + (A : Set Γ) (e : ι → Γ) (h : ι → ℝ) (W : Γ → ℝ) : ℝ := + ((slotPunctures ps).map (fun x => + (pairMatrix (slotTotal x.2 f) A e).toBilin' h h / W x.1.1)).sum + +noncomputable def transportEnergy {ι : Type*} [Fintype ι] (ps : List (Γ × Γ)) + (f H : Set Γ → ℝ) (A : Set Γ) (e : ι → Γ) (W : Γ → ℝ) : ℝ := + match ps with + | [] => cliqueEnergy (fun i => f (insert (e i) A)) (fun i => W (e i)) + (fun i => H (insert (e i) A)) + | p::ps => transportEnergy ps f H (insert p.2 A) (appendPoint e p.1) W + + transportEnergy ps f H (insert p.1 A) (appendPoint e p.2) W +termination_by ps.length + +omit sectionInstance16 sectionInstance17 in +lemma transportEnergy_nil [Fintype Γ] [DecidableEq Γ] {ι : Type*} [Fintype ι] + (f H : Set Γ → ℝ) (A : Set Γ) (e : ι → Γ) (W : Γ → ℝ) : + transportEnergy [] f H A e W = + cliqueEnergy (fun i => f (insert (e i) A)) (fun i => W (e i)) + (fun i => H (insert (e i) A)) := by rw [transportEnergy] + +omit sectionInstance16 sectionInstance17 in +lemma transportEnergy_cons [Fintype Γ] [DecidableEq Γ] {ι : Type*} [Fintype ι] + (p : Γ × Γ) (ps : List (Γ × Γ)) (f H : Set Γ → ℝ) + (A : Set Γ) (e : ι → Γ) (W : Γ → ℝ) : + transportEnergy (p::ps) f H A e W = + transportEnergy ps f H (insert p.2 A) (appendPoint e p.1) W + + transportEnergy ps f H (insert p.1 A) (appendPoint e p.2) W := by rw [transportEnergy] + +lemma transportDemand_split (ps : List (Γ × Γ)) (f H : Set Γ → ℝ) + (A : Set Γ) (e : ι → Γ) (p : Γ × Γ) (h : ι → ℝ) (c : ℝ) + (hp : p.1 ≠ p.2) (ha : p.1 ∉ A ∪ Set.range e) (hb : p.2 ∉ A ∪ Set.range e) : + transportDemand ps f H (insert p.2 A) (appendPoint e p.1) (extendVector h c) + + transportDemand ps f H (insert p.1 A) (appendPoint e p.2) (extendVector h (-c)) = + transportDemand (p::ps) f H A e h := by + unfold transportDemand + simp only [Fintype.sum_option, extendVector, appendPoint] + rw [Set.insert_comm p.2 p.1] + simp_rw [slotTotal_parent ps (fun S => f S*H S) A e p hp ha hb] + simp only [mul_add, Finset.sum_add_distrib, neg_mul] + ring + +lemma transportCorrection_split (ps : List (Γ × Γ)) (f : Set Γ → ℝ) + (A : Set Γ) (e : ι → Γ) (p : Γ × Γ) (h : ι → ℝ) (c : ℝ) (W : Γ → ℝ) + (hp : p.1 ≠ p.2) (ha : p.1 ∉ A ∪ Set.range e) (hb : p.2 ∉ A ∪ Set.range e) : + transportCorrection (p::ps) f A e h W = + (pairMatrix (slotTotal ps f) A e).toBilin' h h / W p.1 + + (transportCorrection ps f (insert p.2 A) (appendPoint e p.1) (extendVector h c) W + + transportCorrection ps f (insert p.1 A) (appendPoint e p.2) (extendVector h (-c)) W) := by + simp only [transportCorrection, slotPunctures, List.map_cons, List.map_map, List.sum_cons] + rw [← List.sum_map_add] + congr 1 + apply congrArg List.sum + apply List.map_congr_left + intro x _ + dsimp + rw [← add_div, slot_future_conservation x.2 f A e p h c hp ha hb] + +lemma transportPotential_split (ps : List (Γ × Γ)) (f : Set Γ → ℝ) + (A : Set Γ) (e : ι → Γ) (p : Γ × Γ) (h : ι → ℝ) (X u : ℝ) (W : Γ → ℝ) + (hp : p.1 ≠ p.2) (ha : p.1 ∉ A ∪ Set.range e) (hb : p.2 ∉ A ∪ Set.range e) + (hu : u = slotTotal ps f (insert p.1 (insert p.2 A))) (hu0 : u ≠ 0) + (hw : W p.1 = W p.2) (hw0 : W p.1 ≠ 0) : + transportPotential ps f (insert p.2 A) (appendPoint e p.1) (extendVector h (-X/u)) W + + transportPotential ps f (insert p.1 A) (appendPoint e p.2) (extendVector h (X/u)) W = + transportPotential (p::ps) f A e h W + 2*X^2/(u*W p.1) := by + unfold transportPotential + simp only [Fintype.sum_option, extendVector, appendPoint] + rw [Set.insert_comm p.2 p.1, ← hu, ← hw] + simp_rw [slotTotal_parent ps f A e p hp ha hb] + simp only [add_mul, add_div, Finset.sum_add_distrib] + field_simp + ring + +theorem transport_linear_bound (ps : List (Γ × Γ)) : + ∀ {κ : Type*} [Fintype κ] [DecidableEq κ] [Nonempty κ] + (f H : Set Γ → ℝ) (A : Set Γ) (e : κ → Γ) (h : κ → ℝ) (W : Γ → ℝ), + (∀ S, 0 < f S) → HasSlotSignature f → Function.Injective e → + (∀ i, e i ∉ A) → SlotsFresh ps (A ∪ Set.range e) → + (∀ i, 0 < W i) → (∀ p ∈ ps, W p.1 = W p.2) → + (∑ i, slotTotal ps f (insert (e i) A)*h i = 0) → + 2*transportDemand ps f H A e h ≤ + transportPotential ps f A e h W - transportCorrection ps f A e h W + + transportEnergy ps f H A e W := by + induction ps with + | nil => + intro κ _ _ _ f H A e h W hf _ _ _ _ hW _ hbal + have hb : ∑ i, f (insert (e i) A)*h i = 0 := hbal + have hl := clique_linear_bound (fun i => f (insert (e i) A)) (fun i => W (e i)) h + (fun i => H (insert (e i) A)) (fun i => hf _) (fun i => hW _) hb + simpa [transportDemand, transportPotential, transportCorrection, slotPunctures, + slotTotal, coeffDerivs, transportEnergy_nil, mul_comm, mul_left_comm, mul_assoc] using hl + | cons p ps ih => + intro κ _ _ _ f H A e h W hf hSig he heA hFresh hW hw hbal + obtain ⟨hab,ha,hb,ht⟩ := hFresh + have hFresh' : SlotsFresh (p::ps) (A ∪ Set.range e) := ⟨hab,ha,hb,ht⟩ + obtain ⟨hfa,hfb⟩ := slotsFresh_child e A p ps hFresh' + let sa : κ → ℝ := fun i => slotTotal ps f (insert (e i) (insert p.2 A)) + let sb : κ → ℝ := fun i => slotTotal ps f (insert (e i) (insert p.1 A)) + let u : ℝ := slotTotal ps f (insert p.1 (insert p.2 A)) + let X : ℝ := ∑ i, h i*sa i + let c : ℝ := -X/u + have hu : 0 < u := slotTotal_pos ps f hf _ + (ht.mono (Set.insert_subset_insert (Set.insert_subset_insert Set.subset_union_left))) + have hb0 : (∑ i, (sa i+sb i)*h i) = 0 := by + simpa only [slotTotal_parent ps f A e p hab ha hb] using hbal + have hXb : (∑ i, h i*sb i) = -X := by + simp only [add_mul, Finset.sum_add_distrib] at hb0 + have ha' : (∑ i, sa i*h i) = X := by dsimp [X]; apply Finset.sum_congr rfl; intro i _; ring + have hb' : (∑ i, sb i*h i) = ∑ i, h i*sb i := by apply Finset.sum_congr rfl; intro i _; ring + rw [ha',hb'] at hb0 + linarith + have hcB : -c = -(∑ i, h i*sb i)/u := by rw [hXb]; dsimp [c]; ring + have hba : ∑ i, slotTotal ps f (insert (appendPoint e p.1 i) (insert p.2 A)) * + extendVector h c i = 0 := by + have hc := child_balance sa h u (ne_of_gt hu) + simp only [Fintype.sum_option, extendVector] at hc + simpa only [Fintype.sum_option, extendVector, appendPoint, sa, u, c, X] using hc + have hbb : ∑ i, slotTotal ps f (insert (appendPoint e p.2 i) (insert p.1 A)) * + extendVector h (-c) i = 0 := by + rw [hcB] + have hc := child_balance sb h u (ne_of_gt hu) + simp only [Fintype.sum_option, extendVector] at hc + simpa only [Fintype.sum_option, extendVector, appendPoint, u, sb, Set.insert_comm p.2 p.1] using hc + have hwa := hw p (List.mem_cons_self ..) + have hwt : ∀ p ∈ ps, W p.1 = W p.2 := fun q hq => hw q (List.mem_cons_of_mem _ hq) + have hla := ih f H (insert p.2 A) (appendPoint e p.1) (extendVector h c) W + hf hSig (appendPoint_injective e p.1 he (fun h => ha (Or.inr h))) + (appendPoint_fresh e A p.1 p.2 heA hab (fun h => ha (Or.inl h)) + (fun h => hb (Or.inr h))) hfa hW hwt hba + have hlb := ih f H (insert p.1 A) (appendPoint e p.2) (extendVector h (-c)) W + hf hSig (appendPoint_injective e p.2 he (fun h => hb (Or.inr h))) + (appendPoint_fresh e A p.2 p.1 heA hab.symm (fun h => hb (Or.inl h)) + (fun h => ha (Or.inr h))) hfb hW hwt hbb + have hsplit := split_bound (pairMatrix (slotTotal ps f) A e) sa sb h u hu + (pairMatrix_symm _ A e) (slot_split_signature f hSig ps A e p.1 p.2 he heA hab ha hb) hb0 + have hcost : 2*X^2/(u*W p.1) ≤ + -(pairMatrix (slotTotal ps f) A e).toBilin' h h / W p.1 := by + simpa only [X, div_div] using div_le_div_of_nonneg_right hsplit (hW p.1).le + have hpot := transportPotential_split ps f A e p h X u W hab ha hb rfl + (ne_of_gt hu) hwa (ne_of_gt (hW p.1)) + have hcN : X/u = -c := by dsimp [c]; ring + rw [hcN] at hpot + change transportPotential ps f (insert p.2 A) (appendPoint e p.1) (extendVector h c) W + + transportPotential ps f (insert p.1 A) (appendPoint e p.2) (extendVector h (-c)) W = _ at hpot + rw [← transportDemand_split ps f H A e p h c hab ha hb, + transportEnergy_cons, transportCorrection_split ps f A e p h c W hab ha hb] + rw [neg_div] at hcost + linarith + +end RecursiveTransport + +section TransportRoot +open scoped BigOperators Classical Matrix +variable {Γ ι : Type*} [sectionInstance22 : Fintype Γ] [sectionInstance23 : DecidableEq Γ] + [Fintype ι] [sectionInstance25 : DecidableEq ι] + +omit sectionInstance25 in +lemma transportDemand_smul [DecidableEq ι] (ps : List (Γ × Γ)) (f H : Set Γ → ℝ) + (A : Set Γ) (e : ι → Γ) (h : ι → ℝ) (c : ℝ) : + transportDemand ps f H A e (c • h) = c * transportDemand ps f H A e h := by + simp [transportDemand, Pi.smul_apply, smul_eq_mul, mul_assoc, Finset.mul_sum] + +omit sectionInstance25 in +lemma transportPotential_smul [DecidableEq ι] (ps : List (Γ × Γ)) (f : Set Γ → ℝ) + (A : Set Γ) (e : ι → Γ) (h : ι → ℝ) (W : Γ → ℝ) (c : ℝ) : + transportPotential ps f A e (c • h) W = c^2 * transportPotential ps f A e h W := by + unfold transportPotential + rw [Finset.mul_sum] + apply Finset.sum_congr rfl + intro i _ + simp only [Pi.smul_apply, smul_eq_mul] + ring + +lemma transportCorrection_smul (ps : List (Γ × Γ)) (f : Set Γ → ℝ) + (A : Set Γ) (e : ι → Γ) (h : ι → ℝ) (W : Γ → ℝ) (c : ℝ) : + transportCorrection ps f A e (c • h) W = c^2 * transportCorrection ps f A e h W := by + unfold transportCorrection + rw [← List.sum_map_mul_left] + apply congrArg List.sum + apply List.map_congr_left + intro x _ + simp only [map_smul, LinearMap.smul_apply, smul_eq_mul] + ring + +lemma squared_le_of_linear_scalings (D C E : ℝ) (hC : 0 < C) + (h : ∀ t : ℝ, 2*t*D ≤ t^2*C + E) : D^2 ≤ C*E := by + have ht := h (D/C) + have ht' := (mul_le_mul_of_nonneg_right ht hC.le) + field_simp at ht' + nlinarith + +theorem transport_squared_bound [Nonempty ι] (ps : List (Γ × Γ)) + (f H : Set Γ → ℝ) (A : Set Γ) (e : ι → Γ) (h : ι → ℝ) (W : Γ → ℝ) + (hf : ∀ S, 0 < f S) (hSig : HasSlotSignature f) (he : Function.Injective e) + (heA : ∀ i, e i ∉ A) (hps : SlotsFresh ps (A ∪ Set.range e)) + (hW : ∀ i, 0 < W i) (hw : ∀ p ∈ ps, W p.1 = W p.2) + (hbal : ∑ i, slotTotal ps f (insert (e i) A)*h i = 0) + (hC : 0 < transportPotential ps f A e h W - transportCorrection ps f A e h W) : + (transportDemand ps f H A e h)^2 ≤ + (transportPotential ps f A e h W - transportCorrection ps f A e h W) * + transportEnergy ps f H A e W := by + apply squared_le_of_linear_scalings _ _ _ hC + intro t + have hbal' : ∑ i, slotTotal ps f (insert (e i) A)*(t • h) i = 0 := by + simp only [Pi.smul_apply, smul_eq_mul] + simp_rw [mul_left_comm _ t, ← Finset.mul_sum, hbal, mul_zero] + have ht := transport_linear_bound ps f H A e (t • h) W hf hSig he heA hps hW hw hbal' + rw [transportDemand_smul,transportPotential_smul,transportCorrection_smul] at ht + nlinarith + +lemma slotTotal_nonneg (ps : List (Γ × Γ)) (f : Set Γ → ℝ) + (hf : ∀ S, 0 ≤ f S) (A : Set Γ) : 0 ≤ slotTotal ps f A := by + induction ps generalizing A with + | nil => exact hf A + | cons p ps ih => + change 0 ≤ coeffDeriv (pairDirection p) (slotTotal ps f) A + apply Finset.sum_nonneg + intro i _ + split_ifs + · exact le_rfl + · exact mul_nonneg (slotDirection_nonneg _ i) (ih _) + +def rootEmbedding (p d : Γ) : Bool → Γ := fun b => if b then d else p + +omit sectionInstance22 sectionInstance23 in +lemma rootEmbedding_injective [Fintype Γ] [DecidableEq Γ] (p d : Γ) (hpd : p ≠ d) : + Function.Injective (rootEmbedding p d) := by + intro i j h + cases i <;> cases j <;> simp_all [rootEmbedding] + +noncomputable def rootDemand (sp sd : ℝ) : Bool → ℝ := + fun b => if b then -(1/sd) else 1/sp + +noncomputable def rootCoefficient (ps : List (Γ × Γ)) (f : Set Γ → ℝ) + (A : Set Γ) (p d : Γ) (W : Γ → ℝ) : ℝ := + let sp := slotTotal ps f (insert p A) + let sd := slotTotal ps f (insert d A) + 1/(sp*W p) + 1/(sd*W d) + 2/(sp*sd)* + ((slotPunctures ps).map (fun x => slotTotal x.2 f (insert p (insert d A))/W x.1.1)).sum + +lemma rootPotential (ps : List (Γ × Γ)) (f : Set Γ → ℝ) + (A : Set Γ) (p d : Γ) (W : Γ → ℝ) + (hsp : slotTotal ps f (insert p A) ≠ 0) (hsd : slotTotal ps f (insert d A) ≠ 0) : + transportPotential ps f A (rootEmbedding p d) + (rootDemand (slotTotal ps f (insert p A)) (slotTotal ps f (insert d A))) W = + 1/(slotTotal ps f (insert p A)*W p) + 1/(slotTotal ps f (insert d A)*W d) := by + simp only [transportPotential, Fintype.sum_bool, rootEmbedding, rootDemand, + Bool.false_eq_true, ite_false, ite_true] + field_simp + ; ring + +lemma rootCorrection (ps : List (Γ × Γ)) (f : Set Γ → ℝ) + (A : Set Γ) (p d : Γ) (W : Γ → ℝ) (sp sd : ℝ) : + transportCorrection ps f A (rootEmbedding p d) (rootDemand sp sd) W = + -(2/(sp*sd)*((slotPunctures ps).map + (fun x => slotTotal x.2 f (insert p (insert d A))/W x.1.1)).sum) := by + unfold transportCorrection + rw [← neg_mul, ← List.sum_map_mul_left] + apply congrArg List.sum + apply List.map_congr_left + intro x _ + simp only [Matrix.toBilin'_apply, Fintype.sum_bool, pairMatrix, rootEmbedding, + rootDemand, Bool.false_eq_true, Bool.true_eq_false, ite_false, ite_true, + Set.insert_comm d p] + ring + +lemma rootCoefficient_pos (ps : List (Γ × Γ)) (f : Set Γ → ℝ) + (hf : ∀ S, 0 < f S) (A : Set Γ) (p d : Γ) (W : Γ → ℝ) + (hps : SlotsFresh ps (A ∪ Set.range (rootEmbedding p d))) (hW : ∀ i, 0 < W i) : + 0 < rootCoefficient ps f A p d W := by + have hfp : SlotsFresh ps (insert p A) := hps.mono (by + intro x hx + rcases hx with rfl | hx + · exact Or.inr ⟨false,rfl⟩ + · exact Or.inl hx) + have hfd : SlotsFresh ps (insert d A) := hps.mono (by + intro x hx + rcases hx with rfl | hx + · exact Or.inr ⟨true,rfl⟩ + · exact Or.inl hx) + have hp := slotTotal_pos ps f hf _ hfp + have hd := slotTotal_pos ps f hf _ hfd + unfold rootCoefficient + apply add_pos_of_pos_of_nonneg + · exact add_pos (one_div_pos.mpr (mul_pos hp (hW p))) + (one_div_pos.mpr (mul_pos hd (hW d))) + · apply mul_nonneg (div_nonneg (by norm_num) (mul_pos hp hd).le) + apply List.sum_nonneg + intro x hx + obtain ⟨y,_,rfl⟩ := List.mem_map.mp hx + exact div_nonneg (slotTotal_nonneg _ f (fun S => (hf S).le) _) (hW _).le + +theorem transport_root_bound (ps : List (Γ × Γ)) (f H : Set Γ → ℝ) + (A : Set Γ) (p d : Γ) (W : Γ → ℝ) + (hf : ∀ S, 0 < f S) (hSig : HasSlotSignature f) + (hpd : p ≠ d) (hpA : p ∉ A) (hdA : d ∉ A) + (hps : SlotsFresh ps (A ∪ Set.range (rootEmbedding p d))) + (hW : ∀ i, 0 < W i) (hw : ∀ p ∈ ps, W p.1 = W p.2) : + (slotTotal ps (fun S => f S*H S) (insert p A) / slotTotal ps f (insert p A) - + slotTotal ps (fun S => f S*H S) (insert d A) / slotTotal ps f (insert d A))^2 ≤ + rootCoefficient ps f A p d W * transportEnergy ps f H A (rootEmbedding p d) W := by + have heA : ∀ i, rootEmbedding p d i ∉ A := by + intro i; cases i <;> assumption + have hfresh : ∀ i, SlotsFresh ps (insert (rootEmbedding p d i) A) := by + intro i + apply hps.mono + intro x hx + rcases hx with rfl | hx + · exact Or.inr ⟨i,rfl⟩ + · exact Or.inl hx + have hsp := slotTotal_pos ps f hf _ (hfresh false) + have hsd := slotTotal_pos ps f hf _ (hfresh true) + change 0 < slotTotal ps f (insert p A) at hsp + change 0 < slotTotal ps f (insert d A) at hsd + let h := rootDemand (slotTotal ps f (insert p A)) (slotTotal ps f (insert d A)) + have hbal : ∑ i, slotTotal ps f (insert (rootEmbedding p d i) A)*h i = 0 := by + simp [h,rootDemand,rootEmbedding, ne_of_gt hsp, ne_of_gt hsd] + have hcoef : transportPotential ps f A (rootEmbedding p d) h W - + transportCorrection ps f A (rootEmbedding p d) h W = rootCoefficient ps f A p d W := by + dsimp [h] + rw [rootPotential ps f A p d W (ne_of_gt hsp) (ne_of_gt hsd), rootCorrection] + simp only [rootCoefficient, sub_neg_eq_add] + have ht := transport_squared_bound ps f H A (rootEmbedding p d) h W hf hSig + (rootEmbedding_injective p d hpd) heA hps hW hw hbal + (by rw [hcoef]; exact rootCoefficient_pos ps f hf A p d W hps hW) + rw [hcoef] at ht + simpa [transportDemand,h,rootDemand,rootEmbedding,Fintype.sum_bool,div_eq_mul_inv, + mul_comm,sub_eq_add_neg,add_comm] using ht + +end TransportRoot + +section TransportGraph +open scoped BigOperators Classical +variable {Γ : Type*} [sectionInstance26 : Fintype Γ] [sectionInstance27 : DecidableEq Γ] + +def ExchangeAdjacent (S T : Set Γ) : Prop := + ∃ (A : Set Γ) (a b : Γ), a ≠ b ∧ a ∉ A ∧ b ∉ A ∧ + S = insert a A ∧ T = insert b A + +noncomputable def slotVertices {ι : Type*} [Fintype ι] + (ps : List (Γ × Γ)) (A : Set Γ) (e : ι → Γ) : Finset (Set Γ) := + match ps with + | [] => Finset.univ.image (fun i => insert (e i) A) + | p::ps => slotVertices ps (insert p.2 A) (appendPoint e p.1) ∪ + slotVertices ps (insert p.1 A) (appendPoint e p.2) +termination_by ps.length + +noncomputable def transportEdges {ι : Type*} [Fintype ι] [DecidableEq ι] + (ps : List (Γ × Γ)) (A : Set Γ) (e : ι → Γ) : Finset (Set Γ × Set Γ) := + match ps with + | [] => (Finset.univ.filter (fun ij : ι × ι => ij.1 ≠ ij.2)).image + (fun ij => (insert (e ij.1) A, insert (e ij.2) A)) + | p::ps => transportEdges ps (insert p.2 A) (appendPoint e p.1) ∪ + transportEdges ps (insert p.1 A) (appendPoint e p.2) +termination_by ps.length + +noncomputable def missingMultiplier {ι : Type*} [Fintype ι] + (ps : List (Γ × Γ)) (e : ι → Γ) (W : Γ → ℝ) (S : Set Γ) : ℝ := + (∑ i, if e i ∈ S then W (e i) else 0) + + (ps.map (fun p => if p.1 ∈ S ∧ p.2 ∈ S then W p.1 else 0)).sum + +omit sectionInstance26 sectionInstance27 in +lemma transportEdges_fixed [Fintype Γ] [DecidableEq Γ] (ps : List (Γ × Γ)) : + ∀ {ι : Type*} [Fintype ι] [DecidableEq ι] (A : Set Γ) (e : ι → Γ) + (ST : Set Γ × Set Γ), ST ∈ transportEdges ps A e → + A ⊆ ST.1 ∩ ST.2 := by + induction ps with + | nil => + intro ι _ _ A e ST h + rw [transportEdges] at h + obtain ⟨ij,_,rfl⟩ := Finset.mem_image.mp h + exact Set.subset_inter (Set.subset_insert _ _) (Set.subset_insert _ _) + | cons p ps ih => + intro ι _ _ A e ST h + rw [transportEdges] at h + rcases Finset.mem_union.mp h with h | h + · exact (Set.subset_insert p.2 A).trans (ih _ _ _ h) + · exact (Set.subset_insert p.1 A).trans (ih _ _ _ h) + +lemma transportEdges_not_holes (ps : List (Γ × Γ)) : + ∀ {ι : Type*} [Fintype ι] [DecidableEq ι] (A : Set Γ) (e : ι → Γ), + Function.Injective e → (∀ i, e i ∉ A) → SlotsFresh ps (A ∪ Set.range e) → + ∀ ST ∈ transportEdges ps A e, ∀ i, e i ∉ ST.1 ∩ ST.2 := by + induction ps with + | nil => + intro ι _ _ A e he heA _ ST h i + rw [transportEdges] at h + obtain ⟨ij,hij,rfl⟩ := Finset.mem_image.mp h + have hij' := (Finset.mem_filter.mp hij).2 + intro ⟨hi,hj⟩ + have hi' : e i = e ij.1 := hi.resolve_right (heA i) + have hj' : e i = e ij.2 := hj.resolve_right (heA i) + exact hij' ((he hi').symm.trans (he hj')) + | cons p ps ih => + intro ι _ _ A e he heA hps ST h i + obtain ⟨hab,ha,hb,ht⟩ := hps + have hps' : SlotsFresh (p::ps) (A ∪ Set.range e) := ⟨hab,ha,hb,ht⟩ + obtain ⟨hfa,hfb⟩ := slotsFresh_child e A p ps hps' + rw [transportEdges] at h + rcases Finset.mem_union.mp h with h | h + · exact ih (insert p.2 A) (appendPoint e p.1) + (appendPoint_injective e p.1 he (fun h => ha (Or.inr h))) + (appendPoint_fresh e A p.1 p.2 heA hab (fun h => ha (Or.inl h)) + (fun h => hb (Or.inr h))) hfa ST h (some i) + · exact ih (insert p.1 A) (appendPoint e p.2) + (appendPoint_injective e p.2 he (fun h => hb (Or.inr h))) + (appendPoint_fresh e A p.2 p.1 heA hab.symm (fun h => hb (Or.inl h)) + (fun h => ha (Or.inr h))) hfb ST h (some i) + +lemma transportEdges_disjoint {ι : Type*} [Fintype ι] [DecidableEq ι] + (ps : List (Γ × Γ)) (A : Set Γ) (e : ι → Γ) (p : Γ × Γ) + (he : Function.Injective e) (heA : ∀ i, e i ∉ A) + (hps : SlotsFresh (p::ps) (A ∪ Set.range e)) : + Disjoint (transportEdges ps (insert p.2 A) (appendPoint e p.1)) + (transportEdges ps (insert p.1 A) (appendPoint e p.2)) := by + apply Finset.disjoint_left.mpr + intro ST ha hb + have hfix := transportEdges_fixed ps (insert p.2 A) (appendPoint e p.1) ST ha + obtain ⟨hab,hpa,hpb,ht⟩ := hps + have hps' : SlotsFresh (p::ps) (A ∪ Set.range e) := ⟨hab,hpa,hpb,ht⟩ + have hn := transportEdges_not_holes ps (insert p.1 A) (appendPoint e p.2) + (appendPoint_injective e p.2 he (fun h => hpb (Or.inr h))) + (appendPoint_fresh e A p.2 p.1 heA hab.symm (fun h => hpb (Or.inl h)) + (fun h => hpa (Or.inr h))) (slotsFresh_child e A p ps hps').2 ST hb none + exact hn (hfix (Set.mem_insert _ _)) + +omit sectionInstance26 sectionInstance27 in +lemma missingMultiplier_child_left [Fintype Γ] [DecidableEq Γ] {ι : Type*} [Fintype ι] + (ps : List (Γ × Γ)) (p : Γ × Γ) (e : ι → Γ) (W : Γ → ℝ) + (S : Set Γ) (hb : p.2 ∈ S) : + missingMultiplier (p::ps) e W S = missingMultiplier ps (appendPoint e p.1) W S := by + simp only [missingMultiplier, List.map_cons, List.sum_cons, Fintype.sum_option, appendPoint] + simp only [hb, and_true] + ac_rfl + +omit sectionInstance26 sectionInstance27 in +lemma missingMultiplier_child_right [Fintype Γ] [DecidableEq Γ] {ι : Type*} [Fintype ι] + (ps : List (Γ × Γ)) (p : Γ × Γ) (e : ι → Γ) (W : Γ → ℝ) + (S : Set Γ) (ha : p.1 ∈ S) (hw : W p.1 = W p.2) : + missingMultiplier (p::ps) e W S = missingMultiplier ps (appendPoint e p.2) W S := by + simp only [missingMultiplier, List.map_cons, List.sum_cons, Fintype.sum_option, appendPoint] + simp only [ha, true_and, hw] + ac_rfl + +omit sectionInstance26 in +lemma missingMultiplier_leaf [Fintype Γ] {ι : Type*} [Fintype ι] [DecidableEq ι] + (A : Set Γ) (e : ι → Γ) (W : Γ → ℝ) (he : Function.Injective e) + (heA : ∀ i, e i ∉ A) (i : ι) : + missingMultiplier [] e W (insert (e i) A) = W (e i) := by + simp [missingMultiplier, Set.mem_insert_iff, he.eq_iff, heA] + +omit sectionInstance26 sectionInstance27 in +lemma insert_embedding_injective [Fintype Γ] [DecidableEq Γ] {ι : Type*} (A : Set Γ) (e : ι → Γ) + (he : Function.Injective e) (heA : ∀ i, e i ∉ A) : + Function.Injective (fun i => insert (e i) A) := by + intro i j hij + apply he + have hi : e i ∈ insert (e j) A := (Set.ext_iff.mp hij (e i)).mp (Set.mem_insert _ _) + exact hi.resolve_right (heA i) + +noncomputable def slotEdgeEnergy {ι : Type*} [Fintype ι] + (ps : List (Γ × Γ)) (e : ι → Γ) (W : Γ → ℝ) + (f H : Set Γ → ℝ) (ST : Set Γ × Set Γ) : ℝ := + min (missingMultiplier ps e W ST.1 * f ST.1) + (missingMultiplier ps e W ST.2 * f ST.2) * (H ST.1-H ST.2)^2 + +lemma offdiag_sum {ι : Type*} [Fintype ι] [DecidableEq ι] + (E : ι → ι → ℝ) (hE : ∀ i, E i i = 0) : + ∑ ij ∈ Finset.univ.filter (fun ij : ι × ι => ij.1 ≠ ij.2), E ij.1 ij.2 = + ∑ i, ∑ j, E i j := by + rw [Finset.sum_filter, Fintype.sum_prod_type] + apply Finset.sum_congr rfl + intro i _ + apply Finset.sum_congr rfl + intro j _ + by_cases hij : i = j + · subst j; simp [hE] + · simp [hij] + +lemma transportEnergy_leaf_eq_sum {ι : Type*} [Fintype ι] [DecidableEq ι] + (f H : Set Γ → ℝ) (A : Set Γ) (e : ι → Γ) (W : Γ → ℝ) + (he : Function.Injective e) (heA : ∀ i, e i ∉ A) : + transportEnergy [] f H A e W = + (∑ ST ∈ transportEdges [] A e, slotEdgeEnergy [] e W f H ST)/2 := by + have hi := insert_embedding_injective A e he heA + have hp : Function.Injective (fun ij : ι × ι => (insert (e ij.1) A, insert (e ij.2) A)) := by + intro ij kl h + exact Prod.ext (hi (congrArg Prod.fst h)) (hi (congrArg Prod.snd h)) + rw [transportEnergy_nil, transportEdges, Finset.sum_image (fun _ _ _ _ h => hp h)] + simp only [slotEdgeEnergy, missingMultiplier_leaf A e W he heA] + rw [offdiag_sum (fun i j => min (W (e i)*f (insert (e i) A)) + (W (e j)*f (insert (e j) A)) * (H (insert (e i) A)-H (insert (e j) A))^2) + (fun i => by simp)] + rfl + +lemma transportEnergy_eq_sum (ps : List (Γ × Γ)) : + ∀ {ι : Type*} [Fintype ι] [DecidableEq ι] (f H : Set Γ → ℝ) + (A : Set Γ) (e : ι → Γ) (W : Γ → ℝ), + Function.Injective e → (∀ i, e i ∉ A) → SlotsFresh ps (A ∪ Set.range e) → + (∀ p ∈ ps, W p.1 = W p.2) → + transportEnergy ps f H A e W = + (∑ ST ∈ transportEdges ps A e, slotEdgeEnergy ps e W f H ST)/2 := by + induction ps with + | nil => + intro ι _ _ f H A e W he heA _ _ + exact transportEnergy_leaf_eq_sum f H A e W he heA + | cons p ps ih => + intro ι _ _ f H A e W he heA hps hw + obtain ⟨hab,ha,hb,ht⟩ := hps + have hps' : SlotsFresh (p::ps) (A ∪ Set.range e) := ⟨hab,ha,hb,ht⟩ + obtain ⟨hfa,hfb⟩ := slotsFresh_child e A p ps hps' + have hwt : ∀ p ∈ ps, W p.1 = W p.2 := fun q hq => hw q (List.mem_cons_of_mem _ hq) + rw [transportEnergy_cons, + ih f H (insert p.2 A) (appendPoint e p.1) W + (appendPoint_injective e p.1 he (fun h => ha (Or.inr h))) + (appendPoint_fresh e A p.1 p.2 heA hab (fun h => ha (Or.inl h)) + (fun h => hb (Or.inr h))) hfa hwt, + ih f H (insert p.1 A) (appendPoint e p.2) W + (appendPoint_injective e p.2 he (fun h => hb (Or.inr h))) + (appendPoint_fresh e A p.2 p.1 heA hab.symm (fun h => hb (Or.inl h)) + (fun h => ha (Or.inr h))) hfb hwt, + transportEdges, Finset.sum_union (transportEdges_disjoint ps A e p he heA hps'), ← add_div] + congr 1 + apply congrArg₂ (· + ·) + · apply Finset.sum_congr rfl + intro ST hST + have hfix := transportEdges_fixed ps (insert p.2 A) (appendPoint e p.1) ST hST + have hm := hfix (Set.mem_insert _ _) + simp only [slotEdgeEnergy, missingMultiplier_child_left ps p e W ST.1 hm.1, + missingMultiplier_child_left ps p e W ST.2 hm.2] + · apply Finset.sum_congr rfl + intro ST hST + have hfix := transportEdges_fixed ps (insert p.1 A) (appendPoint e p.2) ST hST + have hm := hfix (Set.mem_insert _ _) + simp only [slotEdgeEnergy, missingMultiplier_child_right ps p e W ST.1 hm.1 + (hw p (List.mem_cons_self ..)), + missingMultiplier_child_right ps p e W ST.2 hm.2 (hw p (List.mem_cons_self ..))] + +omit sectionInstance26 sectionInstance27 in +lemma transportEdges_states [Fintype Γ] [DecidableEq Γ] (ps : List (Γ × Γ)) : + ∀ {ι : Type*} [Fintype ι] [DecidableEq ι] (A : Set Γ) (e : ι → Γ) + (ST : Set Γ × Set Γ), ST ∈ transportEdges ps A e → + ST.1 ∈ slotVertices ps A e ∧ ST.2 ∈ slotVertices ps A e := by + induction ps with + | nil => + intro ι _ _ A e ST h + rw [transportEdges] at h + obtain ⟨ij,_,rfl⟩ := Finset.mem_image.mp h + rw [slotVertices] + exact ⟨Finset.mem_image.mpr ⟨ij.1,Finset.mem_univ _,rfl⟩, + Finset.mem_image.mpr ⟨ij.2,Finset.mem_univ _,rfl⟩⟩ + | cons p ps ih => + intro ι _ _ A e ST h + rw [transportEdges] at h + rw [slotVertices] + rcases Finset.mem_union.mp h with h | h + · have hh := ih _ _ _ h + exact ⟨Finset.mem_union_left _ hh.1,Finset.mem_union_left _ hh.2⟩ + · have hh := ih _ _ _ h + exact ⟨Finset.mem_union_right _ hh.1,Finset.mem_union_right _ hh.2⟩ + +lemma transportEdges_adjacent (ps : List (Γ × Γ)) : + ∀ {ι : Type*} [Fintype ι] [DecidableEq ι] (A : Set Γ) (e : ι → Γ), + Function.Injective e → (∀ i, e i ∉ A) → SlotsFresh ps (A ∪ Set.range e) → + ∀ ST ∈ transportEdges ps A e, ExchangeAdjacent ST.1 ST.2 := by + induction ps with + | nil => + intro ι _ _ A e he heA _ ST h + rw [transportEdges] at h + obtain ⟨ij,hij,rfl⟩ := Finset.mem_image.mp h + exact ⟨A,e ij.1,e ij.2,fun h => (Finset.mem_filter.mp hij).2 (he h), + heA _,heA _,rfl,rfl⟩ + | cons p ps ih => + intro ι _ _ A e he heA hps ST h + obtain ⟨hab,ha,hb,ht⟩ := hps + have hps' : SlotsFresh (p::ps) (A ∪ Set.range e) := ⟨hab,ha,hb,ht⟩ + obtain ⟨hfa,hfb⟩ := slotsFresh_child e A p ps hps' + rw [transportEdges] at h + rcases Finset.mem_union.mp h with h | h + · exact ih (insert p.2 A) (appendPoint e p.1) + (appendPoint_injective e p.1 he (fun h => ha (Or.inr h))) + (appendPoint_fresh e A p.1 p.2 heA hab (fun h => ha (Or.inl h)) + (fun h => hb (Or.inr h))) hfa ST h + · exact ih (insert p.1 A) (appendPoint e p.2) + (appendPoint_injective e p.2 he (fun h => hb (Or.inr h))) + (appendPoint_fresh e A p.2 p.1 heA hab.symm (fun h => hb (Or.inl h)) + (fun h => ha (Or.inr h))) hfb ST h + +noncomputable def slotGraphEdges {ι : Type*} [Fintype ι] + (ps : List (Γ × Γ)) (A : Set Γ) (e : ι → Γ) : Finset (Set Γ × Set Γ) := + ((slotVertices ps A e).product (slotVertices ps A e)).filter + (fun ST => ExchangeAdjacent ST.1 ST.2) + +noncomputable def slotGraphEnergy {ι : Type*} [Fintype ι] + (ps : List (Γ × Γ)) (f H : Set Γ → ℝ) (A : Set Γ) (e : ι → Γ) (W : Γ → ℝ) : ℝ := + (∑ ST ∈ slotGraphEdges ps A e, slotEdgeEnergy ps e W f H ST)/2 + +omit sectionInstance26 sectionInstance27 in +lemma missingMultiplier_nonneg [Fintype Γ] [DecidableEq Γ] {ι : Type*} [Fintype ι] + (ps : List (Γ × Γ)) (e : ι → Γ) (W : Γ → ℝ) (hW : ∀ i, 0 ≤ W i) (S : Set Γ) : + 0 ≤ missingMultiplier ps e W S := by + apply add_nonneg + · exact Finset.sum_nonneg (fun i _ => by split_ifs <;> simp_all) + · apply List.sum_nonneg + intro x hx + obtain ⟨p,_,rfl⟩ := List.mem_map.mp hx + split_ifs <;> simp_all + +lemma transportEnergy_le_graphEnergy {ι : Type*} [Fintype ι] [DecidableEq ι] + (ps : List (Γ × Γ)) (f H : Set Γ → ℝ) (A : Set Γ) (e : ι → Γ) (W : Γ → ℝ) + (he : Function.Injective e) (heA : ∀ i, e i ∉ A) + (hps : SlotsFresh ps (A ∪ Set.range e)) (hw : ∀ p ∈ ps, W p.1 = W p.2) + (hf : ∀ S, 0 ≤ f S) (hW : ∀ i, 0 ≤ W i) : + transportEnergy ps f H A e W ≤ slotGraphEnergy ps f H A e W := by + rw [transportEnergy_eq_sum ps f H A e W he heA hps hw] + apply div_le_div_of_nonneg_right _ (by norm_num) + apply Finset.sum_le_sum_of_subset_of_nonneg + · intro ST hST + apply Finset.mem_filter.mpr + exact ⟨Finset.mem_product.mpr (transportEdges_states ps A e ST hST), + transportEdges_adjacent ps A e he heA hps ST hST⟩ + · intro ST _ _ + apply mul_nonneg _ (sq_nonneg _) + exact le_min (mul_nonneg (missingMultiplier_nonneg ps e W hW ST.1) (hf _)) + (mul_nonneg (missingMultiplier_nonneg ps e W hW ST.2) (hf _)) + +theorem transport_graph_bound (ps : List (Γ × Γ)) (f H : Set Γ → ℝ) + (A : Set Γ) (p d : Γ) (W : Γ → ℝ) + (hf : ∀ S, 0 < f S) (hSig : HasSlotSignature f) + (hpd : p ≠ d) (hpA : p ∉ A) (hdA : d ∉ A) + (hps : SlotsFresh ps (A ∪ Set.range (rootEmbedding p d))) + (hW : ∀ i, 0 < W i) (hw : ∀ p ∈ ps, W p.1 = W p.2) : + (slotTotal ps (fun S => f S*H S) (insert p A) / slotTotal ps f (insert p A) - + slotTotal ps (fun S => f S*H S) (insert d A) / slotTotal ps f (insert d A))^2 ≤ + rootCoefficient ps f A p d W * slotGraphEnergy ps f H A (rootEmbedding p d) W := by + apply (transport_root_bound ps f H A p d W hf hSig hpd hpA hdA hps hW hw).trans + apply mul_le_mul_of_nonneg_left _ (rootCoefficient_pos ps f hf A p d W hps hW).le + apply transportEnergy_le_graphEnergy ps f H A (rootEmbedding p d) W + (rootEmbedding_injective p d hpd) _ hps hw (fun S => (hf S).le) (fun i => (hW i).le) + intro i + cases i <;> assumption + +end TransportGraph + +section CoefficientInequalities +open scoped BigOperators Classical Matrix +variable {ι : Type*} [sectionInstance28 : Fintype ι] [sectionInstance29 : DecidableEq ι] + +omit sectionInstance29 in +lemma coeffDeriv_eq_sum_outside [DecidableEq ι] (a : ι → ℝ) (f : Set ι → ℝ) (A : Set ι) : + coeffDeriv a f A = ∑ i : {i // i ∉ A}, a i.val * f (insert i.val A) := by + classical + unfold coeffDeriv + let g : ι → ℝ := fun i => if i ∈ A then 0 else a i * f (insert i A) + change (∑ i, g i) = _ + rw [← Fintype.sum_subtype_add_sum_subtype (fun i => i ∉ A) g] + have hz : (∑ i : {i // ¬i ∉ A}, g i.val) = 0 := by + apply Finset.sum_eq_zero + intro i _ + simp only [g, ite_eq_left (not_not.mp i.property)] + rw [hz,add_zero] + apply Finset.sum_congr rfl + intro i _ + simp only [g, ite_eq_right i.property] + +lemma faceHessian_bilin_derivatives (f : Set ι → ℝ) (a b : ι → ℝ) (A : Set ι) : + (faceHessian f A).toBilin' (fun i => a i.val) (fun i => b i.val) = + coeffDeriv a (coeffDeriv b f) A := by + classical + rw [coeffDeriv_eq_sum_outside] + simp only [Matrix.toBilin'_apply, faceHessian] + apply Finset.sum_congr rfl + intro i _ + unfold coeffDeriv + let g : ι → ℝ := fun j => @ite ℝ (j ∈ insert i.val A) + (Classical.propDecidable _) 0 (b j * f (insert j (insert i.val A))) + change _ = a i.val * ∑ j, g j + have heq : (∑ j, g j) = ∑ j : {j // j ∉ A}, g j.val := by + rw [← Fintype.sum_subtype_add_sum_subtype (fun j => j ∉ A) g] + have hz : (∑ j : {j // ¬j ∉ A}, g j.val) = 0 := by + apply Finset.sum_eq_zero + intro j _ + simp only [g, ite_eq_left (Set.mem_insert_of_mem _ (not_not.mp j.property))] + rw [hz,add_zero] + rw [heq, Finset.mul_sum] + apply Finset.sum_congr rfl + intro j _ + dsimp only [g] + by_cases hij : i = j + · subst j; simp [] + · have hji : j.val ∉ insert i.val A := by + simp only [Set.mem_insert_iff, not_or] + exact ⟨fun h => hij (Subtype.ext h.symm),j.property⟩ + rw [ite_eq_right hji] + simp only [hij, ite_false] + have hset : A ∪ {i.val,j.val} = insert j.val (insert i.val A) := by + ext x; simp; tauto + rw [hset] + ring + +lemma onePositive_pair_bound {V : Type*} [AddCommGroup V] [Module ℝ V] + (B : LinearMap.BilinForm ℝ V) (hB : OnePositive B) (hS : B.IsSymm) + (u v : V) (hu : 0 < B u u) : B u u * B v v ≤ (B u v)^2 := by + have h := (le_div_iff₀ hu).mp (onePositive_quadratic_bound B hB hS u v hu) + rw [hS.eq v u] at h + nlinarith + +lemma onePositive_triple_bound {V : Type*} [AddCommGroup V] [Module ℝ V] + (B : LinearMap.BilinForm ℝ V) (hB : OnePositive B) (hS : B.IsSymm) + (u e v : V) (he : 0 < B e e) (hue : 0 < B u e) (hve : 0 < B v e) + (hu : 0 ≤ B u u) (hv : 0 ≤ B v v) : + B u v * B e e ≤ 2 * B u e * B v e := by + have h := (le_div_iff₀ he).mp + (onePositive_quadratic_bound B hB hS e ((B v e) • u + (B u e) • v) he) + have hvu : B v u = B u v := hS.eq v u + simp only [map_add, map_smul, LinearMap.add_apply, LinearMap.smul_apply, + smul_eq_mul, hvu] at h + have hn₁ := mul_nonneg (mul_nonneg (sq_nonneg (B v e)) hu) he.le + have hn₂ := mul_nonneg (mul_nonneg (sq_nonneg (B u e)) hv) he.le + have hh : (2 * B u e * B v e) * (B u v * B e e) ≤ + (2 * B u e * B v e) * (2 * B u e * B v e) := by nlinarith [h,hn₁,hn₂] + exact (mul_le_mul_iff_right₀ (mul_pos (mul_pos (by norm_num) hue) hve)).mp hh + +lemma coeffDeriv_comm (a b : ι → ℝ) (f : Set ι → ℝ) (A : Set ι) : + coeffDeriv a (coeffDeriv b f) A = coeffDeriv b (coeffDeriv a f) A := by + rw [← faceHessian_bilin_derivatives, ← faceHessian_bilin_derivatives] + exact (matrix_bilin_symm _ (faceHessian_symm f A)).eq _ _ + +lemma coeffDeriv_pair_twice (p : ι × ι) (f : Set ι → ℝ) (A : Set ι) + (hp : p.1 ≠ p.2) (ha : p.1 ∉ A) (hb : p.2 ∉ A) : + coeffDeriv (pairDirection p) (coeffDeriv (pairDirection p) f) A = + 2 * f (insert p.1 (insert p.2 A)) := by + unfold pairDirection + rw [coeffDeriv_pair p.1 p.2 hp _ A ha hb] + simp only [coeffDeriv_slot] + simp [hp, hp.symm, ha, hb, Set.insert_comm, two_mul] + +lemma faceHessian_nonnegative_vectors (f : Set ι → ℝ) (hf : ∀ S, 0 ≤ f S) + (A : Set ι) (a b : ι → ℝ) (ha : ∀ i, 0 ≤ a i) (hb : ∀ i, 0 ≤ b i) : + 0 ≤ (faceHessian f A).toBilin' (fun i => a i.val) (fun i => b i.val) := by + simp only [Matrix.toBilin'_apply] + apply Finset.sum_nonneg + intro i _ + apply Finset.sum_nonneg + intro j _ + apply mul_nonneg _ (hb _) + apply mul_nonneg (ha _) + unfold faceHessian + split_ifs + · exact le_rfl + · exact hf _ + +theorem coefficient_pair (ps : List (ι × ι)) (f : Set ι → ℝ) + (hf : ∀ S, 0 < f S) (hsig : HasSlotSignature f) + (A : Set ι) (p r : ι × ι) + (hpr : SlotsFresh (p::r::ps) A) : + 4 * slotTotal ps f (insert p.1 (insert p.2 A)) * + slotTotal ps f (insert r.1 (insert r.2 A)) ≤ + (slotTotal (p::r::ps) f A)^2 := by + obtain ⟨hp,hpa,hpb,hr,hra,hrb,hps⟩ := hpr + have hra' : r.1 ∉ A := fun h => hra (Or.inr (Or.inr h)) + have hrb' : r.2 ∉ A := fun h => hrb (Or.inr (Or.inr h)) + let B := (faceHessian (slotTotal ps f) A).toBilin' + let u : {i // i ∉ A} → ℝ := fun i => pairDirection p i.val + let v : {i // i ∉ A} → ℝ := fun i => pairDirection r i.val + have huu : B u u = 2 * slotTotal ps f (insert p.1 (insert p.2 A)) := by + rw [faceHessian_bilin_derivatives] + exact coeffDeriv_pair_twice p _ A hp hpa hpb + have hvv : B v v = 2 * slotTotal ps f (insert r.1 (insert r.2 A)) := by + rw [faceHessian_bilin_derivatives] + exact coeffDeriv_pair_twice r _ A hr hra' hrb' + have huv : B u v = slotTotal (p::r::ps) f A := by + exact faceHessian_bilin_derivatives _ _ _ _ + have hpos : 0 < B u u := by + rw [huu] + apply mul_pos (by norm_num) + apply slotTotal_pos ps f hf _ (hps.mono _) + intro x hx + simp only [Set.mem_insert_iff] at hx ⊢ + tauto + have h := onePositive_pair_bound B (hsig ps A) + (matrix_bilin_symm _ (faceHessian_symm _ _)) u v hpos + rw [huu,hvv,huv] at h + nlinarith + +lemma SlotsFresh.tail {ps : List (ι × ι)} {p : ι × ι} {A : Set ι} + (h : SlotsFresh (p::ps) A) : SlotsFresh ps A := + h.2.2.2.mono (by intro x hx; exact Or.inr (Or.inr hx)) + +omit sectionInstance28 sectionInstance29 in +lemma SlotsFresh.swap [Fintype ι] [DecidableEq ι] {ps : List (ι × ι)} {p r : ι × ι} {A : Set ι} + (h : SlotsFresh (p::r::ps) A) : SlotsFresh (r::p::ps) A := by + obtain ⟨hp,hpa,hpb,hr,hra,hrb,hps⟩ := h + refine ⟨hr,?_,?_,hp,?_,?_,?_⟩ + · exact fun hx => hra (Or.inr (Or.inr hx)) + · exact fun hx => hrb (Or.inr (Or.inr hx)) + · simp only [Set.mem_insert_iff, not_or] at hra hrb ⊢ + exact ⟨Ne.symm hra.1,Ne.symm hrb.1,hpa⟩ + · simp only [Set.mem_insert_iff, not_or] at hra hrb ⊢ + exact ⟨Ne.symm hra.2.1,Ne.symm hrb.2.1,hpb⟩ + · convert hps using 1 ; ext x ; simp ; tauto + +lemma coeffDeriv_pair_repeated (p r : ι × ι) (f : Set ι → ℝ) (A : Set ι) + (hp : p.1 ≠ p.2) (ha : p.1 ∉ A) (hb : p.2 ∉ A) : + coeffDeriv (pairDirection r) (coeffDeriv (pairDirection p) + (coeffDeriv (pairDirection p) f)) A = + 2 * coeffDeriv (pairDirection r) f (insert p.1 (insert p.2 A)) := by + rw [coeffDeriv_comm (pairDirection r) (pairDirection p)] + have h : coeffDeriv (pairDirection r) (coeffDeriv (pairDirection p) f) = + coeffDeriv (pairDirection p) (coeffDeriv (pairDirection r) f) := by + funext S + exact coeffDeriv_comm _ _ _ _ + rw [h, coeffDeriv_pair_twice p _ A hp ha hb] + +theorem coefficient_triple (ps : List (ι × ι)) (f : Set ι → ℝ) + (hf : ∀ S, 0 < f S) (hsig : HasSlotSignature f) + (A : Set ι) (p r t : ι × ι) + (hprt : SlotsFresh (p::r::t::ps) A) : + slotTotal (t::ps) f (insert r.1 (insert r.2 A)) * + slotTotal (p::ps) f (insert t.1 (insert t.2 A)) ≤ + slotTotal (p::r::t::ps) f A * + slotTotal (r::ps) f (insert t.1 (insert t.2 A)) := by + have hrt := hprt.tail + have ht := hrt.tail + have hr := hrt.1 + have hra := hrt.2.1 + have hrb := hrt.2.2.1 + have htr : SlotsFresh (r::ps) (insert t.1 (insert t.2 A)) := hrt.swap.2.2.2 + let g := slotTotal ps f + let B := (faceHessian (coeffDeriv (pairDirection t) g) A).toBilin' + let u : {i // i ∉ A} → ℝ := fun i => pairDirection p i.val + let e : {i // i ∉ A} → ℝ := fun i => pairDirection r i.val + let v : {i // i ∉ A} → ℝ := fun i => pairDirection t i.val + have hee : B e e = 2 * slotTotal (t::ps) f (insert r.1 (insert r.2 A)) := by + rw [faceHessian_bilin_derivatives] + exact coeffDeriv_pair_twice r _ A hr hra hrb + have hue : B u e = slotTotal (p::r::t::ps) f A := + faceHessian_bilin_derivatives _ _ _ _ + have hve : B v e = 2 * slotTotal (r::ps) f (insert t.1 (insert t.2 A)) := by + rw [faceHessian_bilin_derivatives, coeffDeriv_comm (pairDirection t) (pairDirection r)] + exact coeffDeriv_pair_repeated t r _ A ht.1 ht.2.1 ht.2.2.1 + have huv : B u v = 2 * slotTotal (p::ps) f (insert t.1 (insert t.2 A)) := by + rw [faceHessian_bilin_derivatives] + exact coeffDeriv_pair_repeated t p _ A ht.1 ht.2.1 ht.2.2.1 + have hepos : 0 < B e e := by + rw [hee] + exact mul_pos (by norm_num) (slotTotal_pos _ f hf _ hrt.2.2.2) + have huepos : 0 < B u e := by + rw [hue] + exact slotTotal_pos _ f hf _ hprt + have hvepos : 0 < B v e := by + rw [hve] + exact mul_pos (by norm_num) (slotTotal_pos _ f hf _ htr) + have hn : ∀ S, 0 ≤ coeffDeriv (pairDirection t) g S := + slotTotal_nonneg (t::ps) f (fun S => (hf S).le) + have h := onePositive_triple_bound B (hsig (t::ps) A) + (matrix_bilin_symm _ (faceHessian_symm _ _)) u e v hepos huepos hvepos + (faceHessian_nonnegative_vectors _ hn A _ _ (slotDirection_nonneg _) (slotDirection_nonneg _)) + (faceHessian_nonnegative_vectors _ hn A _ _ (slotDirection_nonneg _) (slotDirection_nonneg _)) + rw [huv,hee,hue,hve] at h + nlinarith + +theorem scores_have_sink [Nonempty ι] (a : ι → ι → ℝ) + (hpair : ∀ i j, i ≠ j → a i j * a j i ≤ 1/16) + (htriple : ∀ i j k, i ≠ j → j ≠ k → i ≠ k → a i j * a j k ≤ a i k) : + ∃ k, ∀ t, k ≠ t → a k t ≤ 1 := by + classical + let out : ι → Finset ι := fun i => Finset.univ.filter (fun j => i ≠ j ∧ 1 < a i j) + obtain ⟨k,_,hk⟩ := Finset.exists_min_image Finset.univ (fun i => (out i).card) + Finset.univ_nonempty + refine ⟨k,?_⟩ + intro t hkt + by_contra hkt' + have hat : 1 < a k t := lt_of_not_ge hkt' + have hnocycle : ∀ i j, i ≠ j → 1 < a i j → ¬ 1 < a j i := by + intro i j hij ha hb + have hm : 1 < a i j * a j i := by + nlinarith [mul_pos (sub_pos.mpr ha) (sub_pos.mpr hb)] + have hp := hpair i j hij + linarith + have hsub : out t ⊆ out k := by + intro j hj + obtain ⟨htj,haj⟩ := (Finset.mem_filter.mp hj).2 + have hkj : k ≠ j := by + intro heq + subst j + exact hnocycle k t hkt hat haj + apply Finset.mem_filter.mpr + refine ⟨Finset.mem_univ _,hkj,?_⟩ + have hm : 1 < a k t * a t j := by + nlinarith [mul_pos (sub_pos.mpr hat) (sub_pos.mpr haj)] + exact hm.trans_le (htriple k t j hkt htj hkj) + have ht : t ∈ out k := Finset.mem_filter.mpr ⟨Finset.mem_univ _,hkt,hat⟩ + have htt : t ∉ out t := by simp [out] + have hss : out t ⊂ out k := Finset.ssubset_iff_subset_ne.mpr ⟨hsub,fun heq => htt (heq ▸ ht)⟩ + exact (not_lt_of_ge (hk t (Finset.mem_univ _))) (Finset.card_lt_card hss) + +end CoefficientInequalities + +section MatroidWeights +open scoped BigOperators Classical Matrix +variable {ι : Type*} [sectionInstance30 : Fintype ι] [sectionInstance31 : DecidableEq ι] + +omit sectionInstance31 in +lemma coeffDeriv_scale [DecidableEq ι] (a : ι → ℝ) (f : Set ι → ℝ) (c : ℝ) (A : Set ι) : + coeffDeriv a (fun S => c * f S) A = c * coeffDeriv a f A := by + simp only [coeffDeriv, Finset.mul_sum] + apply Finset.sum_congr rfl + intro i _ + split_ifs <;> ring + +lemma coeffDerivs_scale (as : List (ι → ℝ)) (f : Set ι → ℝ) (c : ℝ) (A : Set ι) : + coeffDerivs as (fun S => c * f S) A = c * coeffDerivs as f A := by + induction as generalizing A with + | nil => rfl + | cons a as ih => + change coeffDeriv a (coeffDerivs as (fun S => c * f S)) A = _ + have h : coeffDerivs as (fun S => c * f S) = fun S => c * coeffDerivs as f S := by + funext S; exact ih S + rw [h,coeffDeriv_scale] + rfl + +lemma HasSlotSignature.scale {f : Set ι → ℝ} (hf : HasSlotSignature f) + (c : ℝ) (hc : 0 < c) : HasSlotSignature (fun S => c * f S) := by + intro ps A + have heq : faceHessian (slotTotal ps (fun S => c * f S)) A = + c • faceHessian (slotTotal ps f) A := by + ext i j + simp only [faceHessian, Matrix.smul_apply, smul_eq_mul] + split_ifs + · simp + · exact coeffDerivs_scale _ _ _ _ + rw [heq,map_smul] + exact onePositive_smul _ (hf ps A) c hc + +noncomputable def matroidWeight (M : Matroid ι) (n : ℕ) (q : ℝ) (S : Set ι) : ℝ := + q ^ (n - (M.eRk S).toNat) + +omit sectionInstance30 sectionInstance31 in +lemma matroidWeight_eq_scaled [Fintype ι] [DecidableEq ι] (M : Matroid ι) (n : ℕ) (hR : M.eRank = (n : ℕ∞)) + (q : ℝ) (hq : 0 < q) (S : Set ι) : + matroidWeight M n q S = q^n * rankWeight M q S := by + have hr : (M.eRk S).toNat ≤ n := by + have h := M.eRk_le_eRank S + rw [hR] at h + exact ENat.toNat_le_of_le_natCast h + unfold matroidWeight rankWeight + rw [inv_pow, ← div_eq_mul_inv] + exact (eq_div_iff (ne_of_gt (pow_pos hq _))).mpr (by + rw [← pow_add, Nat.sub_add_cancel hr]) + +omit sectionInstance30 sectionInstance31 in +lemma matroidWeight_pos [Fintype ι] [DecidableEq ι] (M : Matroid ι) (n : ℕ) (q : ℝ) (hq : 0 < q) (S : Set ι) : + 0 < matroidWeight M n q S := pow_pos hq _ + +lemma matroidWeight_signature (M : Matroid ι) (hE : M.E = Set.univ) + (n : ℕ) (hR : M.eRank = (n : ℕ∞)) (q : ℝ) (hq : 0 < q) (hq1 : q ≤ 1) : + HasSlotSignature (matroidWeight M n q) := by + have heq : matroidWeight M n q = fun S => q^n * rankWeight M q S := by + funext S; exact matroidWeight_eq_scaled M n hR q hq S + rw [heq] + exact (rankWeight_hasSlotSignature M hE q hq hq1).scale _ (pow_pos hq _) + +omit sectionInstance31 in +lemma dual_rank_equal_complement [DecidableEq ι] (M : Matroid ι) (hE : M.E = Set.univ) + (n : ℕ) (hR : M.eRank = (n : ℕ∞)) (S : Set ι) (hS : S.ncard = n) : + M✶.eRk S = M.eRk Sᶜ := by + have he := M.eRk_dual_add_eRank S (by simp [hE]) + have hencard : S.encard = (n : ℕ∞) := by + rw [← Set.coe_ncard_eq_encard S, hS] + rw [hE, ← Set.compl_eq_univ_sdiff, hR, hencard] at he + exact ENat.add_left_injective_of_ne_top (by simp) he + +omit sectionInstance31 in +lemma dual_eRank_half [DecidableEq ι] (M : Matroid ι) (hE : M.E = Set.univ) + (n : ℕ) (hR : M.eRank = (n : ℕ∞)) (hcard : Fintype.card ι = 2*n) : + M✶.eRank = (n : ℕ∞) := by + have h := M.eRank_add_eRank_dual + rw [hE, Set.encard_univ, hR, ENat.card_eq_coe_fintype_card, hcard] at h + have h' : (n : ℕ∞) + M✶.eRank = (n : ℕ∞) + n := by + simpa [Nat.cast_mul, two_mul] using h + exact ENat.add_right_injective_of_ne_top (by simp) h' + +lemma matroidWeight_dual_complement (M : Matroid ι) (hE : M.E = Set.univ) + (n : ℕ) (hR : M.eRank = (n : ℕ∞)) (q : ℝ) (S : Set ι) (hS : S.ncard = n) : + matroidWeight M✶ n q S = matroidWeight M n q Sᶜ := by + unfold matroidWeight + rw [dual_rank_equal_complement M hE n hR S hS] + +theorem paired_matroid_weight_signatures (M : Matroid ι) (hE : M.E = Set.univ) + (n : ℕ) (hR : M.eRank = (n : ℕ∞)) (hcard : Fintype.card ι = 2*n) + (q : ℝ) (hq : 0 < q) (hq1 : q ≤ 1) : + HasSlotSignature (matroidWeight M n q) ∧ HasSlotSignature (matroidWeight M✶ n q) := by + exact ⟨matroidWeight_signature M hE n hR q hq hq1, + matroidWeight_signature M✶ (by simpa) n (dual_eRank_half M hE n hR hcard) q hq hq1⟩ + +end MatroidWeights + +section IndexedSlotCoefficients +open scoped BigOperators Classical +variable {ι : Type*} [sectionInstance32 : Fintype ι] [DecidableEq ι] + +lemma SlotsFresh.perm {ps qs : List (ι × ι)} (hperm : ps.Perm qs) (A : Set ι) : + SlotsFresh ps A ↔ SlotsFresh qs A := by + induction hperm generalizing A with + | nil => rfl + | cons p h ih => + change (_ ∧ _ ∧ _ ∧ SlotsFresh _ _) ↔ (_ ∧ _ ∧ _ ∧ SlotsFresh _ _) + rw [ih] + | swap p r ps => exact ⟨SlotsFresh.swap,SlotsFresh.swap⟩ + | trans h₁ h₂ ih₁ ih₂ => exact (ih₁ A).trans (ih₂ A) + +lemma slotTotal_perm {ps qs : List (ι × ι)} (hperm : ps.Perm qs) + (f : Set ι → ℝ) : slotTotal ps f = slotTotal qs f := by + induction hperm with + | nil => rfl + | cons p h ih => + change coeffDeriv _ (slotTotal _ f) = coeffDeriv _ (slotTotal _ f) + rw [ih] + | swap p r ps => + funext A + exact coeffDeriv_comm _ _ _ _ + | trans h₁ h₂ ih₁ ih₂ => exact ih₁.trans ih₂ + +noncomputable def slotDefect (ps : List (ι × ι)) (f : Set ι → ℝ) + (A : Set ι) (p r : ι × ι) : ℝ := + slotTotal ((ps.erase p).erase r) f (insert r.1 (insert r.2 A)) + +omit sectionInstance32 in +lemma slots_perm_two [Fintype ι] {ps : List (ι × ι)} {p r : ι × ι} + (hp : p ∈ ps) (hr : r ∈ ps) (hpr : p ≠ r) : + ps.Perm (p::r::(ps.erase p).erase r) := by + exact (List.perm_cons_erase hp).trans + ((List.perm_cons_erase ((List.mem_erase_of_ne hpr.symm).mpr hr)).cons p) + +lemma slotDefect_perm {ps qs : List (ι × ι)} (hperm : ps.Perm qs) + (f : Set ι → ℝ) (A : Set ι) (p r : ι × ι) : + slotDefect ps f A p r = slotDefect qs f A p r := by + unfold slotDefect + rw [slotTotal_perm ((hperm.erase p).erase r)] + +lemma slotDefect_pos (ps : List (ι × ι)) (f : Set ι → ℝ) + (hf : ∀ S, 0 < f S) (A : Set ι) (hps : SlotsFresh ps A) + (p r : ι × ι) (hp : p ∈ ps) (hr : r ∈ ps) (hpr : p ≠ r) : + 0 < slotDefect ps f A p r := by + have hh := (SlotsFresh.perm (slots_perm_two hp hr hpr) A).mp hps + apply slotTotal_pos _ f hf _ (hh.2.2.2.2.2.2.mono _) + intro x hx + simp only [Set.mem_insert_iff] at hx ⊢ + tauto + +lemma slotDefect_pair_bound (ps : List (ι × ι)) (f : Set ι → ℝ) + (hf : ∀ S, 0 < f S) (hsig : HasSlotSignature f) + (A : Set ι) (hps : SlotsFresh ps A) (p r : ι × ι) + (hp : p ∈ ps) (hr : r ∈ ps) (hpr : p ≠ r) : + 4 * slotDefect ps f A p r * slotDefect ps f A r p ≤ (slotTotal ps f A)^2 := by + have hperm := slots_perm_two hp hr hpr + have h := coefficient_pair ((ps.erase p).erase r) f hf hsig A p r + ((SlotsFresh.perm hperm A).mp hps) + rw [← slotTotal_perm hperm f] at h + unfold slotDefect + rw [List.erase_comm r p] + nlinarith + +lemma slots_perm_three {ps : List (ι × ι)} {p r t : ι × ι} + (hp : p ∈ ps) (hr : r ∈ ps) (ht : t ∈ ps) + (hpr : p ≠ r) (hrt : r ≠ t) (hpt : p ≠ t) : + ps.Perm (p::r::t::((ps.erase p).erase r).erase t) := by + have ht' : t ∈ (ps.erase p).erase r := + (List.mem_erase_of_ne hrt.symm).mpr ((List.mem_erase_of_ne hpt.symm).mpr ht) + exact (slots_perm_two hp hr hpr).trans ((List.perm_cons_erase ht').cons r |>.cons p) + +lemma slotDefect_triple_bound (ps : List (ι × ι)) (f : Set ι → ℝ) + (hf : ∀ S, 0 < f S) (hsig : HasSlotSignature f) + (A : Set ι) (hps : SlotsFresh ps A) (p r t : ι × ι) + (hp : p ∈ ps) (hr : r ∈ ps) (ht : t ∈ ps) + (hpr : p ≠ r) (hrt : r ≠ t) (hpt : p ≠ t) : + slotDefect ps f A p r * slotDefect ps f A r t ≤ + slotTotal ps f A * slotDefect ps f A p t := by + have hperm := slots_perm_three hp hr ht hpr hrt hpt + have h := coefficient_triple (((ps.erase p).erase r).erase t) f hf hsig A p r t + ((SlotsFresh.perm hperm A).mp hps) + rw [slotDefect_perm hperm, slotDefect_perm hperm, slotDefect_perm hperm, + slotTotal_perm hperm] + simpa [slotDefect, hpr, hpr.symm, hrt, hrt.symm, hpt, hpt.symm] using h + +lemma coefficient_scores_sink {J : Type*} [Fintype J] [DecidableEq J] [Nonempty J] + (c d : J → J → ℝ) (z v : ℝ) (hz : 0 < z) (hv : 0 < v) + (hc : ∀ i j, i ≠ j → 0 ≤ c i j) (hd : ∀ i j, i ≠ j → 0 ≤ d i j) + (hcp : ∀ i j, i ≠ j → 4*c i j*c j i ≤ z^2) + (hdp : ∀ i j, i ≠ j → 4*d i j*d j i ≤ v^2) + (hct : ∀ i j k, i ≠ j → j ≠ k → i ≠ k → c i j*c j k ≤ z*c i k) + (hdt : ∀ i j k, i ≠ j → j ≠ k → i ≠ k → d i j*d j k ≤ v*d i k) : + ∃ i, ∀ j, i ≠ j → c i j*d j i ≤ z*v := by + let a : J → J → ℝ := fun i j => (c i j * d j i)/(z*v) + have hzv : 0 < z*v := mul_pos hz hv + have hp : ∀ i j, i ≠ j → a i j*a j i ≤ 1/16 := by + intro i j hij + dsimp [a] + rw [div_mul_div_comm] + apply (div_le_iff₀ (mul_pos hzv hzv)).mpr + have h := mul_le_mul (hcp i j hij) (hdp j i hij.symm) + (mul_nonneg (mul_nonneg (by norm_num) (hd j i hij.symm)) (hd i j hij)) + (sq_nonneg z) + nlinarith + have ht : ∀ i j k, i ≠ j → j ≠ k → i ≠ k → a i j*a j k ≤ a i k := by + intro i j k hij hjk hik + dsimp [a] + rw [div_mul_div_comm] + apply (div_le_iff₀ (mul_pos hzv hzv)).mpr + have h := mul_le_mul (hct i j k hij hjk hik) (hdt k j i hjk.symm hij.symm hik.symm) + (mul_nonneg (hd k j hjk.symm) (hd j i hij.symm)) + (mul_nonneg hz.le (hc i k hik)) + have heq : c i k*d k i/(z*v)*(z*v*(z*v)) = z*c i k*(v*d k i) := by + field_simp + + rw [heq] + nlinarith + obtain ⟨i,hi⟩ := scores_have_sink a hp ht + refine ⟨i,fun j hij => ?_⟩ + exact (div_le_iff₀ hzv).mp (hi j hij) |>.trans_eq (one_mul _) + +theorem slot_scores_have_sink_forward (ps gs : List (ι × ι)) (f : Set ι → ℝ) + (hf : ∀ S, 0 < f S) (hsig : HasSlotSignature f) + (A B : Set ι) (hps : SlotsFresh ps A) (hgs : SlotsFresh gs B) + (hsub : ∀ p ∈ ps, p ∈ gs) (hne : ps ≠ []) : + ∃ p ∈ ps, ∀ r ∈ ps, p ≠ r → + slotDefect ps f A p r * slotDefect gs f B r p ≤ + slotTotal ps f A * slotTotal gs f B := by + classical + let J := {p : ι × ι // p ∈ ps} + have : Nonempty J := by + obtain ⟨p,hp⟩ := List.exists_mem_of_ne_nil ps hne + exact ⟨⟨p,hp⟩⟩ + have hne' : ∀ p r : J, p ≠ r → p.val ≠ r.val := fun p r h he => h (Subtype.ext he) + obtain ⟨p,hp⟩ := coefficient_scores_sink + (fun p r : J => slotDefect ps f A p.val r.val) + (fun p r : J => slotDefect gs f B p.val r.val) + (slotTotal ps f A) (slotTotal gs f B) + (slotTotal_pos ps f hf A hps) (slotTotal_pos gs f hf B hgs) + (fun p r h => (slotDefect_pos ps f hf A hps p r p.property r.property (hne' p r h)).le) + (fun p r h => (slotDefect_pos gs f hf B hgs p r (hsub p p.property) + (hsub r r.property) (hne' p r h)).le) + (fun p r h => slotDefect_pair_bound ps f hf hsig A hps p r p.property r.property (hne' p r h)) + (fun p r h => slotDefect_pair_bound gs f hf hsig B hgs p r (hsub p p.property) + (hsub r r.property) (hne' p r h)) + (fun p r t h₁ h₂ h₃ => slotDefect_triple_bound ps f hf hsig A hps p r t + p.property r.property t.property (hne' p r h₁) (hne' r t h₂) (hne' p t h₃)) + (fun p r t h₁ h₂ h₃ => slotDefect_triple_bound gs f hf hsig B hgs p r t + (hsub p p.property) (hsub r r.property) (hsub t t.property) + (hne' p r h₁) (hne' r t h₂) (hne' p t h₃)) + refine ⟨p.val,p.property,?_⟩ + intro r hr hpr + exact hp ⟨r,hr⟩ (fun h => hpr (congrArg Subtype.val h)) + +theorem slot_scores_have_sink (ps gs : List (ι × ι)) (f : Set ι → ℝ) + (hf : ∀ S, 0 < f S) (hsig : HasSlotSignature f) + (A B : Set ι) (hps : SlotsFresh ps A) (hgs : SlotsFresh gs B) + (hsub : ∀ p ∈ ps, p ∈ gs) (hne : ps ≠ []) : + ∃ p ∈ ps, ∀ r ∈ ps, p ≠ r → + slotDefect ps f A r p * slotDefect gs f B p r ≤ + slotTotal ps f A * slotTotal gs f B := by + classical + let J := {p : ι × ι // p ∈ ps} + have : Nonempty J := by + obtain ⟨p,hp⟩ := List.exists_mem_of_ne_nil ps hne + exact ⟨⟨p,hp⟩⟩ + have hne' : ∀ p r : J, p ≠ r → p.val ≠ r.val := fun p r h he => h (Subtype.ext he) + obtain ⟨p,hp⟩ := coefficient_scores_sink + (fun p r : J => slotDefect ps f A r.val p.val) + (fun p r : J => slotDefect gs f B r.val p.val) + (slotTotal ps f A) (slotTotal gs f B) + (slotTotal_pos ps f hf A hps) (slotTotal_pos gs f hf B hgs) + (fun p r h => (slotDefect_pos ps f hf A hps r p r.property p.property (hne' r p h.symm)).le) + (fun p r h => (slotDefect_pos gs f hf B hgs r p (hsub r r.property) + (hsub p p.property) (hne' r p h.symm)).le) + (fun p r h => slotDefect_pair_bound ps f hf hsig A hps r p r.property p.property (hne' r p h.symm)) + (fun p r h => slotDefect_pair_bound gs f hf hsig B hgs r p (hsub r r.property) + (hsub p p.property) (hne' r p h.symm)) + (fun p r t h₁ h₂ h₃ => by + simpa only [mul_comm] using slotDefect_triple_bound ps f hf hsig A hps t r p + t.property r.property p.property (hne' t r h₂.symm) (hne' r p h₁.symm) (hne' t p h₃.symm)) + (fun p r t h₁ h₂ h₃ => by + simpa only [mul_comm] using slotDefect_triple_bound gs f hf hsig B hgs t r p + (hsub t t.property) (hsub r r.property) (hsub p p.property) + (hne' t r h₂.symm) (hne' r p h₁.symm) (hne' t p h₃.symm)) + refine ⟨p.val,p.property,?_⟩ + intro r hr hpr + exact hp ⟨r,hr⟩ (fun h => hpr (congrArg Subtype.val h)) + +end IndexedSlotCoefficients + +section VarianceTree +open scoped BigOperators Classical +variable {ι : Type*} [sectionInstance34 : Fintype ι] [sectionInstance35 : DecidableEq ι] + +noncomputable def slotVariance (ps : List (ι × ι)) (f H : Set ι → ℝ) (A : Set ι) : ℝ := + slotTotal ps (fun S => f S*(H S)^2) A - + (slotTotal ps (fun S => f S*H S) A)^2 / slotTotal ps f A + +lemma slotVariance_nil (f H : Set ι → ℝ) (A : Set ι) (_ : f A ≠ 0) : + slotVariance [] f H A = 0 := by + unfold slotVariance + simp only [slotTotal_nil] + field_simp + ; ring + +lemma slotVariance_perm {ps qs : List (ι × ι)} (h : ps.Perm qs) + (f H : Set ι → ℝ) (A : Set ι) : + slotVariance ps f H A = slotVariance qs f H A := by + unfold slotVariance + rw [slotTotal_perm h, slotTotal_perm h, slotTotal_perm h] + +lemma variance_split_algebra (a b x y u v : ℝ) (ha : 0 < a) (hb : 0 < b) : + x+y-(u+v)^2/(a+b) = + (x-u^2/a) + (y-v^2/b) + a*b/(a+b)*(u/a-v/b)^2 := by + have hab : a+b ≠ 0 := ne_of_gt (add_pos ha hb) + field_simp + ; ring + +lemma slotVariance_split (ps : List (ι × ι)) (f H : Set ι → ℝ) + (hf : ∀ S, 0 < f S) (A : Set ι) (p : ι × ι) (hps : SlotsFresh (p::ps) A) : + slotVariance (p::ps) f H A = + slotVariance ps f H (insert p.1 A) + slotVariance ps f H (insert p.2 A) + + (slotTotal ps f (insert p.1 A)*slotTotal ps f (insert p.2 A) / slotTotal (p::ps) f A)* + (slotTotal ps (fun S => f S*H S) (insert p.1 A)/slotTotal ps f (insert p.1 A) - + slotTotal ps (fun S => f S*H S) (insert p.2 A)/slotTotal ps f (insert p.2 A))^2 := by + unfold slotVariance + simp only [slotTotal_cons p ps _ A hps.1 hps.2.1 hps.2.2.1] + apply variance_split_algebra + · exact slotTotal_pos ps f hf _ (hps.2.2.2.mono (by intro x hx; simp only [Set.mem_insert_iff] at hx ⊢; tauto)) + · exact slotTotal_pos ps f hf _ (hps.2.2.2.mono (Set.subset_insert _ _)) + +lemma slotVariance_nonneg (ps : List (ι × ι)) (f H : Set ι → ℝ) + (hf : ∀ S, 0 < f S) (A : Set ι) (hps : SlotsFresh ps A) : + 0 ≤ slotVariance ps f H A := by + induction ps generalizing A with + | nil => rw [slotVariance_nil f H A (ne_of_gt (hf A))] + | cons p ps ih => + have h₁ : SlotsFresh ps (insert p.1 A) := hps.2.2.2.mono (by + intro x hx; simp only [Set.mem_insert_iff] at hx ⊢; tauto) + have h₂ : SlotsFresh ps (insert p.2 A) := hps.2.2.2.mono (Set.subset_insert _ _) + rw [slotVariance_split ps f H hf A p hps] + exact add_nonneg (add_nonneg (ih _ h₁) (ih _ h₂)) + (mul_nonneg (div_nonneg (mul_nonneg (slotTotal_pos ps f hf _ h₁).le + (slotTotal_pos ps f hf _ h₂).le) (slotTotal_pos _ f hf _ hps).le) (sq_nonneg _)) + +omit sectionInstance34 sectionInstance35 in +lemma slotPunctures_length [Fintype ι] [DecidableEq ι] (ps : List (ι × ι)) : (slotPunctures ps).length = ps.length := by + induction ps with + | nil => rfl + | cons p ps ih => simp only [slotPunctures, List.length_cons,List.length_map,ih] + +lemma list_sum_map_le_const {β : Type*} (l : List β) (g : β → ℝ) (C : ℝ) + (h : ∀ x ∈ l, g x ≤ C) : (l.map g).sum ≤ (l.length : ℝ)*C := by + induction l with + | nil => simp + | cons x l ih => + simp only [List.map_cons,List.sum_cons,List.length_cons,Nat.cast_add,Nat.cast_one] + have hh := ih (fun y hy => h y (List.mem_cons_of_mem _ hy)) + have hx := h x (List.mem_cons_self) + linarith + +theorem transport_node_variance (ps : List (ι × ι)) (f H : Set ι → ℝ) + (A : Set ι) (p d : ι) (W : ι → ℝ) + (hf : ∀ S, 0 < f S) (hSig : HasSlotSignature f) + (hpd : p ≠ d) (hpA : p ∉ A) (hdA : d ∉ A) + (hps : SlotsFresh ps (A ∪ Set.range (rootEmbedding p d))) + (hW : ∀ i, 0 < W i) (hw : ∀ p ∈ ps, W p.1 = W p.2) + (hWp : W p = 1) (hWd : W d = 1) + (hsink : ∀ x ∈ slotPunctures ps, + slotTotal x.2 f (insert p (insert d A))/W x.1.1 ≤ + 4*(slotTotal ps f (insert p A)+slotTotal ps f (insert d A))) : + let sp := slotTotal ps f (insert p A) + let sd := slotTotal ps f (insert d A) + sp*sd/(sp+sd) * + (slotTotal ps (fun S => f S*H S) (insert p A)/sp - + slotTotal ps (fun S => f S*H S) (insert d A)/sd)^2 ≤ + (1+8*(ps.length : ℝ))*slotGraphEnergy ps f H A (rootEmbedding p d) W := by + let sp := slotTotal ps f (insert p A) + let sd := slotTotal ps f (insert d A) + have hp : 0 < sp := slotTotal_pos ps f hf _ (hps.mono (by + intro x hx; rcases hx with rfl | hx + · exact Or.inr ⟨false,rfl⟩ + · exact Or.inl hx)) + have hd : 0 < sd := slotTotal_pos ps f hf _ (hps.mono (by + intro x hx; rcases hx with rfl | hx + · exact Or.inr ⟨true,rfl⟩ + · exact Or.inl hx)) + have hpd' : 0 < sp*sd/(sp+sd) := div_pos (mul_pos hp hd) (add_pos hp hd) + have hsum := list_sum_map_le_const (slotPunctures ps) + (fun x => slotTotal x.2 f (insert p (insert d A))/W x.1.1) (4*(sp+sd)) hsink + rw [slotPunctures_length] at hsum + have hcoef : sp*sd/(sp+sd)*rootCoefficient ps f A p d W ≤ 1+8*(ps.length : ℝ) := by + unfold rootCoefficient + change sp*sd/(sp+sd)*(1/(sp*W p)+1/(sd*W d)+2/(sp*sd)*_) ≤ _ + rw [hWp,hWd,mul_one,mul_one] + have heq (s : ℝ) : sp*sd/(sp+sd)*(1/sp+1/sd+2/(sp*sd)*s) = 1+2/(sp+sd)*s := by + field_simp + ; ring + rw [heq] + have hh := mul_le_mul_of_nonneg_left hsum (show 0 ≤ 2/(sp+sd) by positivity) + have heq' : 2/(sp+sd)*((ps.length : ℝ)*(4*(sp+sd))) = 8*(ps.length : ℝ) := by + field_simp + ; ring + rw [heq'] at hh + linarith + have hE : 0 ≤ slotGraphEnergy ps f H A (rootEmbedding p d) W := by + unfold slotGraphEnergy + apply div_nonneg _ (by norm_num) + apply Finset.sum_nonneg + intro ST hST + unfold slotEdgeEnergy + apply mul_nonneg _ (sq_nonneg _) + apply le_min + · exact mul_nonneg (missingMultiplier_nonneg ps _ W (fun i => (hW i).le) _ ) (hf _).le + · exact mul_nonneg (missingMultiplier_nonneg ps _ W (fun i => (hW i).le) _ ) (hf _).le + have ht := mul_le_mul_of_nonneg_left + (transport_graph_bound ps f H A p d W hf hSig hpd hpA hdA hps hW hw) hpd'.le + dsimp only + exact ht.trans (by rw [← mul_assoc]; exact mul_le_mul_of_nonneg_right hcoef hE) + +end VarianceTree + +section StateGeometry +open scoped BigOperators Classical +variable {Γ : Type*} [sectionInstance36 : Fintype Γ] [sectionInstance37 : DecidableEq Γ] + +def PairSingle (p : Γ × Γ) (S : Set Γ) : Prop := + (p.1 ∈ S ∧ p.2 ∉ S) ∨ (p.2 ∈ S ∧ p.1 ∉ S) +def PairFull (p : Γ × Γ) (S : Set Γ) : Prop := p.1 ∈ S ∧ p.2 ∈ S +def PairEmpty (p : Γ × Γ) (S : Set Γ) : Prop := p.1 ∉ S ∧ p.2 ∉ S + +omit sectionInstance36 sectionInstance37 in +lemma PairSingle.not_full [Fintype Γ] [DecidableEq Γ] {p : Γ × Γ} {S : Set Γ} (h : PairSingle p S) : ¬ PairFull p S := by + unfold PairSingle PairFull at * + tauto +omit sectionInstance36 sectionInstance37 in +lemma PairSingle.not_empty [Fintype Γ] [DecidableEq Γ] {p : Γ × Γ} {S : Set Γ} (h : PairSingle p S) : ¬ PairEmpty p S := by + unfold PairSingle PairEmpty at * + tauto +omit sectionInstance36 sectionInstance37 in +lemma PairFull.not_empty [Fintype Γ] [DecidableEq Γ] {p : Γ × Γ} {S : Set Γ} (h : PairFull p S) : ¬ PairEmpty p S := by + unfold PairFull PairEmpty at * + tauto + +def PlainState (gs : List (Γ × Γ)) (S : Set Γ) : Prop := ∀ p ∈ gs, PairSingle p S +def DefectState (gs : List (Γ × Γ)) (p r : Γ × Γ) (S : Set Γ) : Prop := + p ∈ gs ∧ r ∈ gs ∧ p ≠ r ∧ PairEmpty p S ∧ PairFull r S ∧ + ∀ t ∈ gs, t ≠ p → t ≠ r → PairSingle t S + +lemma DefectState.not_plain {gs : List (Γ × Γ)} {p r : Γ × Γ} {S : Set Γ} + (h : DefectState gs p r S) : ¬ PlainState gs S := by + intro hs + exact (hs p h.1).not_empty h.2.2.2.1 + +lemma DefectState.unique {gs : List (Γ × Γ)} {p r p' r' : Γ × Γ} {S : Set Γ} + (h : DefectState gs p r S) (h' : DefectState gs p' r' S) : p = p' ∧ r = r' := by + obtain ⟨hp,hr,hpr,hep,hfr,hs⟩ := h + obtain ⟨hp',hr',hpr',hep',hfr',hs'⟩ := h' + have hpp : p = p' := by + by_contra hne + by_cases hpr' : p = r' + · subst r'; exact hfr'.not_empty hep + · exact (hs' p hp hne hpr').not_empty hep + subst p' + refine ⟨rfl,?_⟩ + by_contra hne + exact (hs' r hr hpr.symm hne).not_full hfr + +omit sectionInstance36 sectionInstance37 in +lemma SlotsFresh.elements_fresh [Fintype Γ] [DecidableEq Γ] {ps : List (Γ × Γ)} {A : Set Γ} + (h : SlotsFresh ps A) (p : Γ × Γ) (hp : p ∈ ps) : p.1 ∉ A ∧ p.2 ∉ A := by + induction ps generalizing A with + | nil => simp at hp + | cons q ps ih => + rcases List.mem_cons.mp hp with rfl | hp + · exact ⟨h.2.1,h.2.2.1⟩ + · have hh := ih h.2.2.2 hp + exact ⟨fun hx => hh.1 (Or.inr (Or.inr hx)), fun hx => hh.2 (Or.inr (Or.inr hx))⟩ + +lemma SlotsFresh.pair_ne_of_mem {ps : List (Γ × Γ)} {A : Set Γ} {p : Γ × Γ} + (h : SlotsFresh (p::ps) A) {r : Γ × Γ} (hr : r ∈ ps) : p ≠ r := by + intro heq + subst r + exact (h.2.2.2.elements_fresh p hr).1 (Set.mem_insert _ _) + +lemma SlotsFresh.nodup {ps : List (Γ × Γ)} {A : Set Γ} (h : SlotsFresh ps A) : ps.Nodup := by + induction ps generalizing A with + | nil => exact List.nodup_nil + | cons p ps ih => + exact List.nodup_cons.mpr ⟨fun hp => (h.pair_ne_of_mem hp) rfl,ih h.2.2.2⟩ + +omit sectionInstance36 sectionInstance37 in +lemma slotVertices_fixed [Fintype Γ] [DecidableEq Γ] (ps : List (Γ × Γ)) : + ∀ {J : Type*} [Fintype J] (A : Set Γ) (e : J → Γ) (S : Set Γ), + S ∈ slotVertices ps A e → A ⊆ S := by + induction ps with + | nil => + intro J _ A e S h + rw [slotVertices] at h + obtain ⟨j,_,rfl⟩ := Finset.mem_image.mp h + exact Set.subset_insert _ _ + | cons p ps ih => + intro J _ A e S h + rw [slotVertices] at h + rcases Finset.mem_union.mp h with h | h + · exact (Set.subset_insert _ _).trans (ih _ _ _ h) + · exact (Set.subset_insert _ _).trans (ih _ _ _ h) + +lemma slotVertices_classify (ps : List (Γ × Γ)) : + ∀ {J : Type*} [Fintype J] [DecidableEq J] (A : Set Γ) (e : J → Γ), + Function.Injective e → (∀ j, e j ∉ A) → SlotsFresh ps (A ∪ Set.range e) → + ∀ S ∈ slotVertices ps A e, + (∃ j, (∀ i, e i ∈ S ↔ i = j) ∧ ∀ p ∈ ps, PairSingle p S) ∨ + (∃ p ∈ ps, (∀ i, e i ∉ S) ∧ PairFull p S ∧ + ∀ r ∈ ps, r ≠ p → PairSingle r S) := by + induction ps with + | nil => + intro J _ _ A e he heA _ S h + rw [slotVertices] at h + obtain ⟨j,_,rfl⟩ := Finset.mem_image.mp h + left + refine ⟨j,fun i => ?_,by simp⟩ + simp only [Set.mem_insert_iff, heA i, or_false] + exact he.eq_iff + | cons p ps ih => + intro J _ _ A e he heA hps S h + have hab := hps.1 + have ha := hps.2.1 + have hb := hps.2.2.1 + obtain ⟨hfa,hfb⟩ := slotsFresh_child e A p ps hps + have branch (a b : Γ) (hab : a ≠ b) (haA : a ∉ A) (hbE : b ∉ Set.range e) + (haE : a ∉ Set.range e) + (hf : SlotsFresh ps (insert b A ∪ Set.range (appendPoint e a))) + (hm : S ∈ slotVertices ps (insert b A) (appendPoint e a)) : + (∃ j, (∀ i, e i ∈ S ↔ i = j) ∧ + PairSingle (a,b) S ∧ ∀ r ∈ ps, PairSingle r S) ∨ + ((∀ i, e i ∉ S) ∧ PairFull (a,b) S ∧ ∀ r ∈ ps, PairSingle r S) ∨ + (∃ r ∈ ps, (∀ i, e i ∉ S) ∧ PairFull r S ∧ PairSingle (a,b) S ∧ + ∀ t ∈ ps, t ≠ r → PairSingle t S) := by + have hbS : b ∈ S := slotVertices_fixed ps _ _ S hm (Set.mem_insert _ _) + have hh := ih (insert b A) (appendPoint e a) + (appendPoint_injective e a he haE) + (appendPoint_fresh e A a b heA hab haA hbE) hf S hm + rcases hh with ⟨j,hj,hr⟩ | ⟨r,hr,he',hfull,hrest⟩ + · cases j with + | none => + right; left + refine ⟨fun i hi => ?_,⟨?_,hbS⟩,hr⟩ + · exact Option.some_ne_none i ((hj (some i)).mp hi) + · exact (hj none).mpr rfl + | some j => + left + refine ⟨j,fun i => ?_,Or.inr ⟨hbS,?_⟩,hr⟩ + · simpa only [appendPoint, Option.some.injEq] using hj (some i) + · intro haS; exact Option.some_ne_none j (((hj none).mp haS).symm) + · right; right + exact ⟨r,hr,fun i => he' (some i),hfull,Or.inr ⟨hbS,he' none⟩,hrest⟩ + rw [slotVertices] at h + rcases Finset.mem_union.mp h with h | h + · have hh := branch p.1 p.2 hab (fun h => ha (Or.inl h)) + (fun h => hb (Or.inr h)) (fun h => ha (Or.inr h)) hfa h + rcases hh with ⟨j,hj,hp,hr⟩ | ⟨hi,hp,hr⟩ | ⟨r,hr,hi,hfull,hp,hrest⟩ + · left; exact ⟨j,hj,fun r hr' => (List.mem_cons.mp hr').elim (fun heq => heq ▸ hp) (hr r)⟩ + · right + refine ⟨p,List.mem_cons_self,hi,hp,?_⟩ + intro r hr' hne + exact hr r ((List.mem_cons.mp hr').resolve_left hne) + · right + refine ⟨r,List.mem_cons_of_mem _ hr,hi,hfull,?_⟩ + intro t ht hne + rcases List.mem_cons.mp ht with rfl | ht + · exact hp + · exact hrest t ht hne + · have hh := branch p.2 p.1 hab.symm (fun h => hb (Or.inl h)) + (fun h => ha (Or.inr h)) (fun h => hb (Or.inr h)) hfb h + have hsingle : PairSingle (p.2,p.1) S → PairSingle p S := fun h => h.elim Or.inr Or.inl + have hfull : PairFull (p.2,p.1) S → PairFull p S := And.symm + rcases hh with ⟨j,hj,hp,hr⟩ | ⟨hi,hp,hr⟩ | ⟨r,hr,hi,hfr,hp,hrest⟩ + · left; exact ⟨j,hj,fun r hr' => (List.mem_cons.mp hr').elim (fun heq => heq ▸ hsingle hp) (hr r)⟩ + · right + refine ⟨p,List.mem_cons_self,hi,hfull hp,?_⟩ + intro r hr' hne + exact hr r ((List.mem_cons.mp hr').resolve_left hne) + · right + refine ⟨r,List.mem_cons_of_mem _ hr,hi,hfr,?_⟩ + intro t ht hne + rcases List.mem_cons.mp ht with rfl | ht + · exact hsingle hp + · exact hrest t ht hne + +end StateGeometry + +section RestrictedEnergy +open scoped BigOperators Classical +variable {Γ : Type*} [sectionInstance38 : Fintype Γ] [sectionInstance39 : DecidableEq Γ] + +def Respects (A B S : Set Γ) : Prop := A ⊆ S ∧ Disjoint B S + +def EdgeRespects (A B : Set Γ) (ST : Set Γ × Set Γ) : Prop := + Respects A B ST.1 ∧ Respects A B ST.2 + +noncomputable def restrictedEnergy (E : Finset (Set Γ × Set Γ)) + (c : (Set Γ × Set Γ) → ℝ) (H : Set Γ → ℝ) (A B : Set Γ) : ℝ := + (∑ ST ∈ E, if EdgeRespects A B ST then c ST*(H ST.1-H ST.2)^2 else 0)/2 + +omit sectionInstance38 sectionInstance39 in +lemma Respects.parent [Fintype Γ] [DecidableEq Γ] {A B S : Set Γ} {a b : Γ} + (h : Respects (insert a A) (insert b B) S) : Respects A B S := + ⟨(Set.subset_insert _ _).trans h.1, h.2.mono_left (Set.subset_insert _ _)⟩ + +omit sectionInstance38 sectionInstance39 in +lemma Respects.child_disjoint [Fintype Γ] [DecidableEq Γ] {A B S : Set Γ} {a b : Γ} + (h : Respects (insert a A) (insert b B) S) : + ¬ Respects (insert b A) (insert a B) S := by + intro h' + exact Set.disjoint_left.mp h'.2 (Set.mem_insert _ _) (h.1 (Set.mem_insert _ _)) + +omit sectionInstance38 sectionInstance39 in +lemma restrictedEnergy_nonneg [Fintype Γ] [DecidableEq Γ] (E : Finset (Set Γ × Set Γ)) + (c : (Set Γ × Set Γ) → ℝ) (H : Set Γ → ℝ) (A B : Set Γ) + (hc : ∀ ST ∈ E, 0 ≤ c ST) : 0 ≤ restrictedEnergy E c H A B := by + apply div_nonneg _ (by norm_num) + apply Finset.sum_nonneg + intro ST hST + split_ifs + · exact mul_nonneg (hc ST hST) (sq_nonneg _) + · rfl + +lemma restrictedEnergy_children (E : Finset (Set Γ × Set Γ)) + (c : (Set Γ × Set Γ) → ℝ) (H : Set Γ → ℝ) (A B : Set Γ) (a b : Γ) + (hc : ∀ ST ∈ E, 0 ≤ c ST) : + restrictedEnergy E c H (insert a A) (insert b B) + + restrictedEnergy E c H (insert b A) (insert a B) ≤ restrictedEnergy E c H A B := by + unfold restrictedEnergy + rw [← add_div, ← Finset.sum_add_distrib] + apply div_le_div_of_nonneg_right _ (by norm_num) + apply Finset.sum_le_sum + intro ST hST + have hw : 0 ≤ c ST*(H ST.1-H ST.2)^2 := mul_nonneg (hc ST hST) (sq_nonneg _) + by_cases h₁ : EdgeRespects (insert a A) (insert b B) ST + · have hp : EdgeRespects A B ST := ⟨h₁.1.parent,h₁.2.parent⟩ + have hn : ¬ EdgeRespects (insert b A) (insert a B) ST := fun h₂ => h₁.1.child_disjoint h₂.1 + simp only [ite_eq_left h₁,ite_eq_right hn,ite_eq_left hp,add_zero,le_refl] + · by_cases h₂ : EdgeRespects (insert b A) (insert a B) ST + · have hp : EdgeRespects A B ST := ⟨h₂.1.parent,h₂.2.parent⟩ + simp only [ite_eq_right h₁,ite_eq_left h₂,ite_eq_left hp,zero_add,le_refl] + · simp only [ite_eq_right h₁,ite_eq_right h₂,zero_add] + split_ifs <;> positivity + +theorem adaptive_variance_bound (f H : Set Γ → ℝ) (hf : ∀ S, 0 < f S) + (E : Finset (Set Γ × Set Γ)) (c : (Set Γ × Set Γ) → ℝ) + (hc : ∀ ST ∈ E, 0 ≤ c ST) (C : ℝ) (hC : 0 ≤ C) + (P : List (Γ × Γ) → Set Γ → Set Γ → Prop) + (hchoose : ∀ ps A B, P ps A B → ps ≠ [] → + ∃ p qs, ps.Perm (p::qs) ∧ SlotsFresh (p::qs) A ∧ + P qs (insert p.1 A) (insert p.2 B) ∧ P qs (insert p.2 A) (insert p.1 B) ∧ + slotVariance (p::qs) f H A - slotVariance qs f H (insert p.1 A) - + slotVariance qs f H (insert p.2 A) ≤ C*restrictedEnergy E c H A B) : + ∀ ps A B, P ps A B → slotVariance ps f H A ≤ + (ps.length : ℝ)*C*restrictedEnergy E c H A B := by + intro ps + induction hn : ps.length using Nat.strong_induction_on generalizing ps with + | h n ih => + intro A B hP + by_cases hnil : ps = [] + · subst ps + have hn0 : n = 0 := hn.symm + subst n + simp only [slotVariance_nil f H A (ne_of_gt (hf A)),List.length_nil,Nat.cast_zero,zero_mul,le_refl] + · obtain ⟨p,qs,hperm,hfresh,hP₁,hP₂,hnode⟩ := hchoose ps A B hP hnil + have hpq : ps.length = qs.length+1 := by simpa using hperm.length_eq + have hq : qs.length < n := by omega + have ha := ih qs.length hq qs rfl (insert p.1 A) (insert p.2 B) hP₁ + have hb := ih qs.length hq qs rfl (insert p.2 A) (insert p.1 B) hP₂ + have he := restrictedEnergy_children E c H A B p.1 p.2 hc + have hmul := mul_le_mul_of_nonneg_left he (mul_nonneg (Nat.cast_nonneg qs.length) hC) + rw [← hn, slotVariance_perm hperm f H A,hpq,Nat.cast_add,Nat.cast_one] + nlinarith + +end RestrictedEnergy + +section ChainIdentification +open scoped BigOperators Classical +variable {Γ : Type*} [sectionInstance40 : Fintype Γ] [sectionInstance41 : DecidableEq Γ] + +omit sectionInstance40 sectionInstance41 in +lemma slotVertices_excluded [Fintype Γ] [DecidableEq Γ] (ps : List (Γ × Γ)) : + ∀ {J : Type*} [Fintype J] (A B : Set Γ) (e : J → Γ), + Disjoint A B → (∀ j, e j ∉ B) → (∀ p ∈ ps, p.1 ∉ B ∧ p.2 ∉ B) → + ∀ S ∈ slotVertices ps A e, Disjoint B S := by + induction ps with + | nil => + intro J _ A B e hAB he _ S hS + rw [slotVertices] at hS + obtain ⟨j,_,rfl⟩ := Finset.mem_image.mp hS + exact Set.disjoint_insert_right.mpr ⟨he j,hAB.symm⟩ + | cons p ps ih => + intro J _ A B e hAB he hp S hS + obtain ⟨hp₁,hp₂⟩ := hp p List.mem_cons_self + have hrest := fun r hr => hp r (List.mem_cons_of_mem _ hr) + rw [slotVertices] at hS + rcases Finset.mem_union.mp hS with hS | hS + · apply ih (insert p.2 A) B (appendPoint e p.1) + (Set.disjoint_insert_left.mpr ⟨hp₂,hAB⟩) _ hrest S hS + intro j; cases j <;> first | exact hp₁ | exact he _ + · apply ih (insert p.1 A) B (appendPoint e p.2) + (Set.disjoint_insert_left.mpr ⟨hp₁,hAB⟩) _ hrest S hS + intro j; cases j <;> first | exact hp₂ | exact he _ + +def FixedOutside (gs ps : List (Γ × Γ)) (A B : Set Γ) : Prop := + ∀ r ∈ gs, r ∉ ps → (r.1 ∈ A ∧ r.2 ∈ B) ∨ (r.2 ∈ A ∧ r.1 ∈ B) + +omit sectionInstance40 sectionInstance41 in +lemma FixedOutside.single [Fintype Γ] [DecidableEq Γ] {gs ps : List (Γ × Γ)} {A B S : Set Γ} + (h : FixedOutside gs ps A B) (hS : Respects A B S) + (r : Γ × Γ) (hr : r ∈ gs) (hn : r ∉ ps) : PairSingle r S := by + rcases h r hr hn with h | h + · exact Or.inl ⟨hS.1 h.1,fun hx => Set.disjoint_left.mp hS.2 h.2 hx⟩ + · exact Or.inr ⟨hS.1 h.1,fun hx => Set.disjoint_left.mp hS.2 h.2 hx⟩ + +noncomputable def chainMultiplier (gs : List (Γ × Γ)) + (w : (Γ × Γ) → (Γ × Γ) → ℝ) (S : Set Γ) : ℝ := + if h : ∃ p r, DefectState gs p r S then w h.choose h.choose_spec.choose else 1 + +lemma chainMultiplier_plain (gs : List (Γ × Γ)) (w : (Γ × Γ) → (Γ × Γ) → ℝ) + (S : Set Γ) (h : PlainState gs S) : chainMultiplier gs w S = 1 := by + unfold chainMultiplier + rw [dite_eq_right] + rintro ⟨p,r,hpr⟩ + exact hpr.not_plain h + +lemma chainMultiplier_defect (gs : List (Γ × Γ)) (w : (Γ × Γ) → (Γ × Γ) → ℝ) + (S : Set Γ) {p r : Γ × Γ} (h : DefectState gs p r S) : + chainMultiplier gs w S = w p r := by + have he : ∃ p r, DefectState gs p r S := ⟨p,r,h⟩ + unfold chainMultiplier + rw [dite_eq_left he] + have hh := he.choose_spec.choose_spec.unique h + exact congrArg₂ w hh.1 hh.2 + +omit sectionInstance41 in +lemma chainMultiplier_pos [DecidableEq Γ] (gs : List (Γ × Γ)) (w : (Γ × Γ) → (Γ × Γ) → ℝ) + (hw : ∀ p r, 0 < w p r) (S : Set Γ) : 0 < chainMultiplier gs w S := by + unfold chainMultiplier + split_ifs <;> first | exact hw _ _ | norm_num + +def ChainState (gs : List (Γ × Γ)) (S : Set Γ) : Prop := + PlainState gs S ∨ ∃ p r, DefectState gs p r S + +noncomputable def chainEdges (gs : List (Γ × Γ)) : Finset (Set Γ × Set Γ) := + Finset.univ.filter (fun ST => ChainState gs ST.1 ∧ ChainState gs ST.2 ∧ + ExchangeAdjacent ST.1 ST.2) + +noncomputable def chainConductance (gs : List (Γ × Γ)) + (w : (Γ × Γ) → (Γ × Γ) → ℝ) (f : Set Γ → ℝ) (ST : Set Γ × Set Γ) : ℝ := + min (chainMultiplier gs w ST.1*f ST.1) (chainMultiplier gs w ST.2*f ST.2) + +lemma list_sum_single {β : Type*} [DecidableEq β] (ps : List β) (hn : ps.Nodup) + (p : β) (hp : p ∈ ps) (g : β → ℝ) (hg : ∀ r ∈ ps, r ≠ p → g r = 0) : + (ps.map g).sum = g p := by + rw [← List.sum_toFinset _ hn] + exact Finset.sum_eq_single p (fun b hb hbp => hg b (List.mem_toFinset.mp hb) hbp) + (fun hn => False.elim (hn (List.mem_toFinset.mpr hp))) + +lemma missingMultiplier_old {J : Type*} [Fintype J] [DecidableEq J] + (ps : List (Γ × Γ)) (e : J → Γ) (W : Γ → ℝ) (S : Set Γ) (j : J) + (hj : ∀ i, e i ∈ S ↔ i = j) (hp : ∀ p ∈ ps, PairSingle p S) : + missingMultiplier ps e W S = W (e j) := by + unfold missingMultiplier + have hz : (ps.map (fun p => if p.1 ∈ S ∧ p.2 ∈ S then W p.1 else 0)).sum = 0 := by + apply List.sum_eq_zero + intro x hx + obtain ⟨p,hp',rfl⟩ := List.mem_map.mp hx + exact ite_eq_right (hp p hp').not_full + rw [hz,add_zero] + simp only [hj] + simp + +lemma missingMultiplier_new {J : Type*} [Fintype J] + (ps : List (Γ × Γ)) (hn : ps.Nodup) (e : J → Γ) (W : Γ → ℝ) (S : Set Γ) + (p : Γ × Γ) (hp : p ∈ ps) (he : ∀ i, e i ∉ S) (hf : PairFull p S) + (hr : ∀ r ∈ ps, r ≠ p → PairSingle r S) : + missingMultiplier ps e W S = W p.1 := by + unfold missingMultiplier + simp only [he,ite_false,Finset.sum_const_zero,zero_add] + have hh := list_sum_single ps hn p hp + (fun r => if r.1 ∈ S ∧ r.2 ∈ S then W r.1 else 0) + (fun r hr' hne => ite_eq_right (hr r hr' hne).not_full) + exact hh.trans (ite_eq_left hf) + +lemma SlotsFresh.pair_contains_unique {ps : List (Γ × Γ)} {A : Set Γ} + (h : SlotsFresh ps A) {p r : Γ × Γ} (hp : p ∈ ps) (hr : r ∈ ps) + {x : Γ} (hxp : x = p.1 ∨ x = p.2) (hxr : x = r.1 ∨ x = r.2) : p = r := by + by_contra hne + have hh := (SlotsFresh.perm (slots_perm_two hp hr hne) A).mp h + have hr₁ := hh.2.2.2.2.1 + have hr₂ := hh.2.2.2.2.2.1 + rcases hxp with rfl | rfl <;> rcases hxr with heq | heq + · exact hr₁ (Or.inl heq.symm) + · exact hr₂ (Or.inl heq.symm) + · exact hr₁ (Or.inr (Or.inl heq.symm)) + · exact hr₂ (Or.inr (Or.inl heq.symm)) + +noncomputable def pairMultiplier (ps : List (Γ × Γ)) (w : (Γ × Γ) → ℝ) (x : Γ) : ℝ := + if h : ∃ p ∈ ps, x = p.1 ∨ x = p.2 then w h.choose else 1 + +omit sectionInstance40 in +lemma pairMultiplier_pos [Fintype Γ] (ps : List (Γ × Γ)) (w : (Γ × Γ) → ℝ) + (hw : ∀ p, 0 < w p) (x : Γ) : 0 < pairMultiplier ps w x := by + unfold pairMultiplier + split_ifs <;> first | exact hw _ | norm_num + +lemma pairMultiplier_on {ps : List (Γ × Γ)} {A : Set Γ} (hps : SlotsFresh ps A) + (w : (Γ × Γ) → ℝ) (p : Γ × Γ) (hp : p ∈ ps) (x : Γ) + (hx : x = p.1 ∨ x = p.2) : pairMultiplier ps w x = w p := by + have he : ∃ p ∈ ps, x = p.1 ∨ x = p.2 := ⟨p,hp,hx⟩ + unfold pairMultiplier + rw [dite_eq_left he] + rw [hps.pair_contains_unique he.choose_spec.1 hp he.choose_spec.2 hx] + +lemma pairMultiplier_fresh {ps : List (Γ × Γ)} {A : Set Γ} (hps : SlotsFresh ps A) + (w : (Γ × Γ) → ℝ) (x : Γ) (hx : x ∈ A) : pairMultiplier ps w x = 1 := by + unfold pairMultiplier + rw [dite_eq_right] + rintro ⟨p,hp,h⟩ + rcases h with rfl | rfl + · exact (hps.elements_fresh p hp).1 hx + · exact (hps.elements_fresh p hp).2 hx + +lemma variance_vertex_identification (gs ps : List (Γ × Γ)) (A B : Set Γ) (p : Γ × Γ) + (w : (Γ × Γ) → (Γ × Γ) → ℝ) + (hsub : ∀ r ∈ p::ps, r ∈ gs) (hAB : Disjoint A B) + (hfresh : SlotsFresh (p::ps) (A ∪ B)) (hout : FixedOutside gs (p::ps) A B) + (S : Set Γ) (hS : S ∈ slotVertices ps A (rootEmbedding p.1 p.2)) : + ChainState gs S ∧ Respects A B S ∧ + missingMultiplier ps (rootEmbedding p.1 p.2) (pairMultiplier ps (w p)) S = + chainMultiplier gs w S := by + have hps : SlotsFresh ps (A ∪ Set.range (rootEmbedding p.1 p.2)) := + hfresh.2.2.2.mono (by + intro x hx + rcases hx with hx | ⟨i,rfl⟩ + · exact Or.inr (Or.inr (Or.inl hx)) + · cases i <;> simp [rootEmbedding]) + have heA : ∀ j, rootEmbedding p.1 p.2 j ∉ A := by + intro j; cases j <;> first | exact fun h => hfresh.2.1 (Or.inl h) | exact fun h => hfresh.2.2.1 (Or.inl h) + have heB : ∀ j, rootEmbedding p.1 p.2 j ∉ B := by + intro j; cases j <;> first | exact fun h => hfresh.2.1 (Or.inr h) | exact fun h => hfresh.2.2.1 (Or.inr h) + have hSB : Disjoint B S := slotVertices_excluded ps A B _ hAB heB + (fun r hr => let hh := hfresh.elements_fresh r (List.mem_cons_of_mem _ hr) + ⟨fun h => hh.1 (Or.inr h),fun h => hh.2 (Or.inr h)⟩) S hS + have hrespect : Respects A B S := ⟨slotVertices_fixed ps A _ S hS,hSB⟩ + have hclass := slotVertices_classify ps A _ (rootEmbedding_injective _ _ hfresh.1) heA hps S hS + rcases hclass with ⟨j,hj,hrest⟩ | ⟨r,hr,he,hfull,hrest⟩ + · have hp : PairSingle p S := by + cases j + · exact Or.inl ⟨(hj false).mpr rfl,fun h => Bool.noConfusion ((hj true).mp h)⟩ + · exact Or.inr ⟨(hj true).mpr rfl,fun h => Bool.noConfusion ((hj false).mp h)⟩ + have hplain : PlainState gs S := by + intro r hr + by_cases hm : r ∈ p::ps + · rcases List.mem_cons.mp hm with rfl | hm + · exact hp + · exact hrest r hm + · exact hout.single hrespect r hr hm + refine ⟨Or.inl hplain,hrespect,?_⟩ + rw [chainMultiplier_plain gs w S hplain,missingMultiplier_old ps _ _ S j hj hrest] + exact pairMultiplier_fresh hps _ _ (Or.inr ⟨j,rfl⟩) + · have hdef : DefectState gs p r S := by + refine ⟨hsub p List.mem_cons_self,hsub r (List.mem_cons_of_mem _ hr), + hfresh.pair_ne_of_mem hr,⟨he false,he true⟩,hfull,?_⟩ + intro t ht htp htr + by_cases hm : t ∈ p::ps + · exact hrest t ((List.mem_cons.mp hm).resolve_left htp) htr + · exact hout.single hrespect t ht hm + refine ⟨Or.inr ⟨p,r,hdef⟩,hrespect,?_⟩ + rw [chainMultiplier_defect gs w S hdef, + missingMultiplier_new ps hps.nodup _ _ S r hr he hfull hrest] + exact pairMultiplier_on hps _ r hr r.1 (Or.inl rfl) + +lemma variance_energy_identification (gs ps : List (Γ × Γ)) (A B : Set Γ) (p : Γ × Γ) + (w : (Γ × Γ) → (Γ × Γ) → ℝ) (f H : Set Γ → ℝ) + (hw : ∀ p r, 0 < w p r) (hf : ∀ S, 0 < f S) + (hsub : ∀ r ∈ p::ps, r ∈ gs) (hAB : Disjoint A B) + (hfresh : SlotsFresh (p::ps) (A ∪ B)) (hout : FixedOutside gs (p::ps) A B) : + slotGraphEnergy ps f H A (rootEmbedding p.1 p.2) (pairMultiplier ps (w p)) ≤ + restrictedEnergy (chainEdges gs) (chainConductance gs w f) H A B := by + have hvertex := variance_vertex_identification gs ps A B p w hsub hAB hfresh hout + unfold slotGraphEnergy restrictedEnergy + apply div_le_div_of_nonneg_right _ (by norm_num) + let D := slotGraphEdges ps A (rootEmbedding p.1 p.2) + have hE : D ⊆ chainEdges gs := by + intro ST hST + obtain ⟨hprod,hadj⟩ := Finset.mem_filter.mp hST + obtain ⟨hs,ht⟩ := Finset.mem_product.mp hprod + exact Finset.mem_filter.mpr ⟨Finset.mem_univ _,(hvertex ST.1 hs).1,(hvertex ST.2 ht).1,hadj⟩ + calc + _ = ∑ ST ∈ D, if EdgeRespects A B ST then + chainConductance gs w f ST*(H ST.1-H ST.2)^2 else 0 := by + apply Finset.sum_congr rfl + intro ST hST + obtain ⟨hs,ht⟩ := Finset.mem_product.mp (Finset.mem_filter.mp hST).1 + have hs' := hvertex ST.1 hs + have ht' := hvertex ST.2 ht + rw [ite_eq_left (show EdgeRespects A B ST from ⟨hs'.2.1,ht'.2.1⟩)] + simp only [slotEdgeEnergy,hs'.2.2,ht'.2.2,chainConductance] + _ ≤ _ := by + apply Finset.sum_le_sum_of_subset_of_nonneg hE + intro ST hST _ + split_ifs + · exact mul_nonneg (le_min + (mul_nonneg (chainMultiplier_pos gs w hw _).le (hf _).le) + (mul_nonneg (chainMultiplier_pos gs w hw _).le (hf _).le)) (sq_nonneg _) + · rfl + +end ChainIdentification + +section TransversalVariance +open scoped BigOperators Classical +variable {Γ : Type*} [sectionInstance42 : Fintype Γ] [sectionInstance43 : DecidableEq Γ] + +omit sectionInstance42 sectionInstance43 in +lemma slotPunctures_perm [Fintype Γ] [DecidableEq Γ] (ps : List (Γ × Γ)) (x : (Γ × Γ) × List (Γ × Γ)) + (hx : x ∈ slotPunctures ps) : ps.Perm (x.1::x.2) := by + induction ps generalizing x with + | nil => simp [slotPunctures] at hx + | cons p ps ih => + rw [slotPunctures,List.mem_cons] at hx + rcases hx with rfl | hx + · exact List.Perm.refl _ + · obtain ⟨y,hy,rfl⟩ := List.mem_map.mp hx + exact ((ih y hy).cons p).trans (List.Perm.swap _ _ _) + +lemma slotDefect_puncture (ps : List (Γ × Γ)) (p : Γ × Γ) (A : Set Γ) + (f : Set Γ → ℝ) (hps : SlotsFresh (p::ps) A) + (x : (Γ × Γ) × List (Γ × Γ)) (hx : x ∈ slotPunctures ps) : + slotDefect (p::ps) f A x.1 p = slotTotal x.2 f (insert p.1 (insert p.2 A)) := by + have hperm := slotPunctures_perm ps x hx + have hm : x.1 ∈ ps := hperm.mem_iff.mpr List.mem_cons_self + rw [slotDefect_perm (hperm.cons p)] + simp [slotDefect,hps.pair_ne_of_mem hm] + +def VarianceNode (gs ps : List (Γ × Γ)) (A B : Set Γ) : Prop := + Disjoint A B ∧ SlotsFresh ps (A ∪ B) ∧ (∀ p ∈ ps, p ∈ gs) ∧ FixedOutside gs ps A B + +lemma VarianceNode.perm {gs ps qs : List (Γ × Γ)} {A B : Set Γ} + (h : VarianceNode gs ps A B) (hp : ps.Perm qs) : VarianceNode gs qs A B := by + refine ⟨h.1,(SlotsFresh.perm hp _).mp h.2.1,fun r hr => h.2.2.1 r (hp.mem_iff.mpr hr),?_⟩ + intro r hr hn + exact h.2.2.2 r hr (fun hm => hn (hp.mem_iff.mp hm)) + +lemma VarianceNode.children {gs ps : List (Γ × Γ)} {A B : Set Γ} {p : Γ × Γ} + (h : VarianceNode gs (p::ps) A B) : + VarianceNode gs ps (insert p.1 A) (insert p.2 B) ∧ + VarianceNode gs ps (insert p.2 A) (insert p.1 B) := by + obtain ⟨hAB,hfresh,hsub,hout⟩ := h + have hab := hfresh.1 + have haA : p.1 ∉ A := fun hx => hfresh.2.1 (Or.inl hx) + have haB : p.1 ∉ B := fun hx => hfresh.2.1 (Or.inr hx) + have hbA : p.2 ∉ A := fun hx => hfresh.2.2.1 (Or.inl hx) + have hbB : p.2 ∉ B := fun hx => hfresh.2.2.1 (Or.inr hx) + have ho (a b : Γ) (hp : (a,b) = p ∨ (a,b) = (p.2,p.1)) : + FixedOutside gs ps (insert a A) (insert b B) := by + intro r hr hn + by_cases hrp : r = p + · subst r + rcases hp with hp | hp + · have h₁ := congrArg Prod.fst hp + have h₂ := congrArg Prod.snd hp + exact Or.inl ⟨Or.inl h₁.symm,Or.inl h₂.symm⟩ + · have h₁ := congrArg Prod.fst hp + have h₂ := congrArg Prod.snd hp + exact Or.inr ⟨Or.inl h₁.symm,Or.inl h₂.symm⟩ + · rcases hout r hr (by simp [hrp,hn]) with hh | hh + · exact Or.inl ⟨Or.inr hh.1,Or.inr hh.2⟩ + · exact Or.inr ⟨Or.inr hh.1,Or.inr hh.2⟩ + constructor + · refine ⟨?_,hfresh.2.2.2.mono ?_,fun r hr => hsub r (List.mem_cons_of_mem _ hr),ho _ _ (Or.inl rfl)⟩ + · simp only [Set.disjoint_insert_left,Set.mem_insert_iff,not_or,Set.disjoint_insert_right] + tauto + · intro x hx + simp only [Set.mem_union,Set.mem_insert_iff] at hx ⊢ + tauto + · refine ⟨?_,hfresh.2.2.2.mono ?_,fun r hr => hsub r (List.mem_cons_of_mem _ hr),ho _ _ (Or.inr rfl)⟩ + · simp only [Set.disjoint_insert_left,Set.mem_insert_iff,not_or,Set.disjoint_insert_right] + tauto + · intro x hx + simp only [Set.mem_union,Set.mem_insert_iff] at hx ⊢ + tauto + +lemma variance_node_bound (gs ps : List (Γ × Γ)) (f H : Set Γ → ℝ) + (w : (Γ × Γ) → (Γ × Γ) → ℝ) (hf : ∀ S, 0 < f S) + (hsig : HasSlotSignature f) (hgs : SlotsFresh gs ∅) + (hw : ∀ p r, 0 < w p r) + (hgood : ∀ p ∈ gs, ∀ r ∈ gs, p ≠ r → + slotTotal gs f ∅ / (4*slotDefect gs f ∅ p r) ≤ w p r) + (A B : Set Γ) (hnode : VarianceNode gs ps A B) (hne : ps ≠ []) : + ∃ p qs, ps.Perm (p::qs) ∧ SlotsFresh (p::qs) A ∧ + VarianceNode gs qs (insert p.1 A) (insert p.2 B) ∧ + VarianceNode gs qs (insert p.2 A) (insert p.1 B) ∧ + slotVariance (p::qs) f H A - slotVariance qs f H (insert p.1 A) - + slotVariance qs f H (insert p.2 A) ≤ + (1+8*(gs.length : ℝ))*restrictedEnergy (chainEdges gs) (chainConductance gs w f) H A B := by + obtain ⟨p,hp,hsink⟩ := slot_scores_have_sink ps gs f hf hsig A ∅ + (hnode.2.1.mono Set.subset_union_left) hgs hnode.2.2.1 hne + let qs := ps.erase p + have hperm : ps.Perm (p::qs) := List.perm_cons_erase hp + have hnode' := hnode.perm hperm + have hfr := hnode'.2.1 + have hfrA : SlotsFresh (p::qs) A := hfr.mono Set.subset_union_left + have hps : SlotsFresh qs (A ∪ Set.range (rootEmbedding p.1 p.2)) := + hfrA.2.2.2.mono (by + intro x hx + rcases hx with hx | ⟨i,rfl⟩ + · exact Or.inr (Or.inr hx) + · cases i <;> simp [rootEmbedding]) + let W := pairMultiplier qs (w p) + have hW : ∀ x, 0 < W x := pairMultiplier_pos qs (w p) (hw p) + have hws : ∀ r ∈ qs, W r.1 = W r.2 := by + intro r hr + dsimp only [W] + rw [pairMultiplier_on hps _ r hr r.1 (Or.inl rfl), + pairMultiplier_on hps _ r hr r.2 (Or.inr rfl)] + have hWp : W p.1 = 1 := pairMultiplier_fresh hps _ _ (Or.inr ⟨false,rfl⟩) + have hWd : W p.2 = 1 := pairMultiplier_fresh hps _ _ (Or.inr ⟨true,rfl⟩) + have hsink' : ∀ x ∈ slotPunctures qs, + slotTotal x.2 f (insert p.1 (insert p.2 A))/W x.1.1 ≤ + 4*(slotTotal qs f (insert p.1 A)+slotTotal qs f (insert p.2 A)) := by + intro x hx + have hxq : x.1 ∈ qs := (slotPunctures_perm qs x hx).mem_iff.mpr List.mem_cons_self + have hxp : p ≠ x.1 := hfr.pair_ne_of_mem hxq + have hxps : x.1 ∈ ps := hperm.mem_iff.mpr (List.mem_cons_of_mem _ hxq) + have hpG := hnode.2.2.1 p hp + have hxG := hnode.2.2.1 x.1 hxps + have hcpos := slotDefect_pos gs f hf ∅ hgs p x.1 hpG hxG hxp + have hzpos := slotTotal_pos ps f hf A (hnode.2.1.mono Set.subset_union_left) + have hs := hsink x.1 hxps hxp + rw [slotDefect_perm hperm,slotDefect_puncture qs p A f hfrA x hx] at hs + have hg := (div_le_iff₀ (mul_pos (by norm_num : (0:ℝ)<4) hcpos)).mp (hgood p hpG x.1 hxG hxp) + have hgz := mul_le_mul_of_nonneg_left hg hzpos.le + have hbound : slotTotal x.2 f (insert p.1 (insert p.2 A)) ≤ + 4*slotTotal ps f A*w p x.1 := by + apply (mul_le_mul_iff_of_pos_right hcpos).mp + nlinarith + change slotTotal x.2 f (insert p.1 (insert p.2 A))/pairMultiplier qs (w p) x.1.1 ≤ _ + rw [pairMultiplier_on hps _ x.1 hxq x.1.1 (Or.inl rfl)] + apply (div_le_iff₀ (hw p x.1)).mpr + rw [slotTotal_perm hperm f,slotTotal_cons p qs f A hfrA.1 hfrA.2.1 hfrA.2.2.1] at hbound + exact hbound + have ht := transport_node_variance qs f H A p.1 p.2 W hf hsig hfrA.1 hfrA.2.1 hfrA.2.2.1 + hps hW hws hWp hWd hsink' + have he := variance_energy_identification gs qs A B p w f H hw hf + hnode'.2.2.1 hnode'.1 hfr hnode'.2.2.2 + have hqle : qs.length ≤ gs.length := by + have hnodup := (hnode.2.1.nodup).erase p + exact List.Subperm.length_le (List.subperm_of_subset hnodup (fun r hr => hnode'.2.2.1 r (List.mem_cons_of_mem _ hr))) + have hqleR : (qs.length : ℝ) ≤ gs.length := by exact_mod_cast hqle + have hepos : 0 ≤ restrictedEnergy (chainEdges gs) (chainConductance gs w f) H A B := by + apply restrictedEnergy_nonneg + intro ST _ + exact le_min (mul_nonneg (chainMultiplier_pos gs w hw _).le (hf _).le) + (mul_nonneg (chainMultiplier_pos gs w hw _).le (hf _).le) + have hfinal := ht.trans ((mul_le_mul_of_nonneg_left he (by positivity : (0:ℝ) ≤ 1+8*(qs.length : ℝ))).trans + (mul_le_mul_of_nonneg_right (by linarith : (1:ℝ)+8*(qs.length:ℝ) ≤ 1+8*(gs.length:ℝ)) hepos)) + refine ⟨p,qs,hperm,hfrA,hnode'.children.1,hnode'.children.2,?_⟩ + rw [slotVariance_split qs f H hf A p hfrA,slotTotal_cons p qs f A hfrA.1 hfrA.2.1 hfrA.2.2.1] + linarith + +theorem transversal_variance_bound (gs : List (Γ × Γ)) (f H : Set Γ → ℝ) + (w : (Γ × Γ) → (Γ × Γ) → ℝ) (hf : ∀ S, 0 < f S) + (hsig : HasSlotSignature f) (hgs : SlotsFresh gs ∅) + (hw : ∀ p r, 0 < w p r) + (hgood : ∀ p ∈ gs, ∀ r ∈ gs, p ≠ r → + slotTotal gs f ∅ / (4*slotDefect gs f ∅ p r) ≤ w p r) : + slotVariance gs f H ∅ ≤ (gs.length : ℝ)*(1+8*(gs.length : ℝ))* + restrictedEnergy (chainEdges gs) (chainConductance gs w f) H ∅ ∅ := by + apply adaptive_variance_bound f H hf (chainEdges gs) (chainConductance gs w f) + (fun ST _ => le_min (mul_nonneg (chainMultiplier_pos gs w hw _).le (hf _).le) + (mul_nonneg (chainMultiplier_pos gs w hw _).le (hf _).le)) + (1+8*(gs.length:ℝ)) (by positivity) (VarianceNode gs) + (fun ps A B hnode hne => variance_node_bound gs ps f H w hf hsig hgs hw hgood A B hnode hne) + exact ⟨by simp,by simpa using hgs,fun _ => id,fun r hr hn => False.elim (hn hr)⟩ + +end TransversalVariance + +section ChoiceEnumeration +open scoped BigOperators Classical +variable {Γ : Type*} [sectionInstance44 : Fintype Γ] [sectionInstance45 : DecidableEq Γ] + +def pairSupport (ps : List (Γ × Γ)) : Set Γ := + {x | ∃ p ∈ ps, x = p.1 ∨ x = p.2} + +omit sectionInstance44 sectionInstance45 in +@[simp] lemma pairSupport_nil [Fintype Γ] [DecidableEq Γ] : pairSupport ([] : List (Γ × Γ)) = ∅ := by ext; simp [pairSupport] +omit sectionInstance44 sectionInstance45 in +lemma pairSupport_cons [Fintype Γ] [DecidableEq Γ] (p : Γ × Γ) (ps : List (Γ × Γ)) : + pairSupport (p::ps) = insert p.1 (insert p.2 (pairSupport ps)) := by + ext x + simp only [pairSupport,Set.mem_ofPred_eq,List.mem_cons,Set.mem_insert_iff] + aesop + +noncomputable def choiceVertices (ps : List (Γ × Γ)) (A : Set Γ) : Finset (Set Γ) := + match ps with + | [] => {A} + | p::ps => choiceVertices ps (insert p.1 A) ∪ choiceVertices ps (insert p.2 A) + +omit sectionInstance44 sectionInstance45 in +lemma choiceVertices_fixed [Fintype Γ] [DecidableEq Γ] (ps : List (Γ × Γ)) (A S : Set Γ) + (hS : S ∈ choiceVertices ps A) : A ⊆ S := by + induction ps generalizing A with + | nil => + rw [choiceVertices,Finset.mem_singleton] at hS + exact hS ▸ Set.Subset.rfl + | cons p ps ih => + rw [choiceVertices] at hS + rcases Finset.mem_union.mp hS with hS | hS + · exact (Set.subset_insert _ _).trans (ih _ hS) + · exact (Set.subset_insert _ _).trans (ih _ hS) + +omit sectionInstance44 sectionInstance45 in +lemma choiceVertices_excluded [Fintype Γ] [DecidableEq Γ] (ps : List (Γ × Γ)) (A B S : Set Γ) + (hAB : Disjoint A B) (hps : ∀ p ∈ ps, p.1 ∉ B ∧ p.2 ∉ B) + (hS : S ∈ choiceVertices ps A) : Disjoint B S := by + induction ps generalizing A with + | nil => + rw [choiceVertices,Finset.mem_singleton] at hS + exact hS ▸ hAB.symm + | cons p ps ih => + obtain ⟨ha,hb⟩ := hps p List.mem_cons_self + have hrest := fun r hr => hps r (List.mem_cons_of_mem _ hr) + rw [choiceVertices] at hS + rcases Finset.mem_union.mp hS with hS | hS + · exact ih _ (Set.disjoint_insert_left.mpr ⟨ha,hAB⟩) hrest hS + · exact ih _ (Set.disjoint_insert_left.mpr ⟨hb,hAB⟩) hrest hS + +lemma choiceVertices_disjoint (ps : List (Γ × Γ)) (A : Set Γ) (p : Γ × Γ) + (hps : SlotsFresh (p::ps) A) : + Disjoint (choiceVertices ps (insert p.1 A)) (choiceVertices ps (insert p.2 A)) := by + apply Finset.disjoint_left.mpr + intro S h₁ h₂ + have hp₁ : p.1 ∈ S := choiceVertices_fixed ps (insert p.1 A) S h₁ (Set.mem_insert _ _) + have hp₂ : Disjoint {p.1} S := choiceVertices_excluded ps (insert p.2 A) {p.1} S + (by simp only [Set.disjoint_singleton_right,Set.mem_insert_iff,not_or]; exact ⟨hps.1,hps.2.1⟩) + (by + intro r hr + have hh := hps.2.2.2.elements_fresh r hr + exact ⟨fun heq => hh.1 (Or.inl heq),fun heq => hh.2 (Or.inl heq)⟩) h₂ + exact Set.disjoint_left.mp hp₂ rfl hp₁ + +lemma slotTotal_eq_choice_sum (ps : List (Γ × Γ)) (A : Set Γ) (f : Set Γ → ℝ) + (hps : SlotsFresh ps A) : slotTotal ps f A = ∑ S ∈ choiceVertices ps A, f S := by + induction ps generalizing A with + | nil => simp [choiceVertices,slotTotal_nil] + | cons p ps ih => + rw [slotTotal_cons p ps f A hps.1 hps.2.1 hps.2.2.1,choiceVertices, + Finset.sum_union (choiceVertices_disjoint ps A p hps)] + congr 1 + · exact ih _ (hps.2.2.2.mono (by intro x hx; simp only [Set.mem_insert_iff] at hx ⊢; tauto)) + · exact ih _ (hps.2.2.2.mono (Set.subset_insert _ _)) + +lemma choiceVertices_card (ps : List (Γ × Γ)) (A : Set Γ) (hps : SlotsFresh ps A) : + (choiceVertices ps A).card = 2^ps.length := by + induction ps generalizing A with + | nil => simp [choiceVertices] + | cons p ps ih => + rw [choiceVertices,Finset.card_union_of_disjoint (choiceVertices_disjoint ps A p hps), + ih _ (hps.2.2.2.mono (by intro x hx; simp only [Set.mem_insert_iff] at hx ⊢; tauto)), + ih _ (hps.2.2.2.mono (Set.subset_insert _ _)),List.length_cons,pow_succ] + omega + +lemma mem_choiceVertices_iff (ps : List (Γ × Γ)) (A S : Set Γ) (hps : SlotsFresh ps A) : + S ∈ choiceVertices ps A ↔ + A ⊆ S ∧ S ⊆ A ∪ pairSupport ps ∧ PlainState ps S := by + induction ps generalizing A with + | nil => simp [choiceVertices,pairSupport_nil,PlainState,Set.Subset.antisymm_iff,and_comm] + | cons p ps ih => + have hf₁ : SlotsFresh ps (insert p.1 A) := hps.2.2.2.mono (by + intro x hx; simp only [Set.mem_insert_iff] at hx ⊢; tauto) + have hf₂ : SlotsFresh ps (insert p.2 A) := hps.2.2.2.mono (Set.subset_insert _ _) + rw [choiceVertices,Finset.mem_union,ih _ hf₁,ih _ hf₂] + have hnot₁ : p.1 ∉ pairSupport ps := by + rintro ⟨r,hr,h⟩ + have hh := hps.2.2.2.elements_fresh r hr + rcases h with he | he + · exact hh.1 (Or.inl he.symm) + · exact hh.2 (Or.inl he.symm) + have hnot₂ : p.2 ∉ pairSupport ps := by + rintro ⟨r,hr,h⟩ + have hh := hps.2.2.2.elements_fresh r hr + rcases h with he | he + · exact hh.1 (Or.inr (Or.inl he.symm)) + · exact hh.2 (Or.inr (Or.inl he.symm)) + constructor + · rintro (⟨hfix,hsupp,hsing⟩ | ⟨hfix,hsupp,hsing⟩) + · refine ⟨(Set.subset_insert _ _).trans hfix,?_,?_⟩ + · intro x hx + have hh := hsupp hx + rw [pairSupport_cons] + simp only [Set.mem_union,Set.mem_insert_iff] at hh ⊢ + tauto + · intro r hr + rcases List.mem_cons.mp hr with rfl | hr + · left + refine ⟨hfix (Set.mem_insert _ _),?_⟩ + intro hbad + have hh := hsupp hbad + rcases hh with hh | hh + · rcases hh with hh | hh + · exact hps.1 hh.symm + · exact hps.2.2.1 hh + · exact hnot₂ hh + · exact hsing r hr + · refine ⟨(Set.subset_insert _ _).trans hfix,?_,?_⟩ + · intro x hx + have hh := hsupp hx + rw [pairSupport_cons] + simp only [Set.mem_union,Set.mem_insert_iff] at hh ⊢ + tauto + · intro r hr + rcases List.mem_cons.mp hr with rfl | hr + · right + refine ⟨hfix (Set.mem_insert _ _),?_⟩ + intro hbad + have hh := hsupp hbad + rcases hh with hh | hh + · rcases hh with hh | hh + · exact hps.1 hh + · exact hps.2.1 hh + · exact hnot₁ hh + · exact hsing r hr + · rintro ⟨hfix,hsupp,hsing⟩ + have hp := hsing p List.mem_cons_self + have hrest : PlainState ps S := fun r hr => hsing r (List.mem_cons_of_mem _ hr) + rcases hp with hp | hp + · left + refine ⟨Set.insert_subset hp.1 hfix,?_,hrest⟩ + intro x hx + have hh := hsupp hx + rw [pairSupport_cons] at hh + simp only [Set.mem_union,Set.mem_insert_iff] at hh ⊢ + rcases hh with hh | rfl | rfl | hh + · exact Or.inl (Or.inr hh) + · exact Or.inl (Or.inl rfl) + · exact False.elim (hp.2 hx) + · exact Or.inr hh + · right + refine ⟨Set.insert_subset hp.1 hfix,?_,hrest⟩ + intro x hx + have hh := hsupp hx + rw [pairSupport_cons] at hh + simp only [Set.mem_union,Set.mem_insert_iff] at hh ⊢ + rcases hh with hh | rfl | rfl | hh + · exact Or.inl (Or.inr hh) + · exact False.elim (hp.2 hx) + · exact Or.inl (Or.inl rfl) + · exact Or.inr hh + +lemma choiceVertices_plain (gs : List (Γ × Γ)) (hgs : SlotsFresh gs ∅) + (hcover : pairSupport gs = Set.univ) : + choiceVertices gs ∅ = Finset.univ.filter (PlainState gs) := by + ext S + rw [mem_choiceVertices_iff gs ∅ S hgs] + simp [hcover] + +lemma slotTotal_eq_plain_sum (gs : List (Γ × Γ)) (hgs : SlotsFresh gs ∅) + (hcover : pairSupport gs = Set.univ) (f : Set Γ → ℝ) : + slotTotal gs f ∅ = ∑ S ∈ Finset.univ.filter (PlainState gs), f S := by + rw [slotTotal_eq_choice_sum gs ∅ f hgs,choiceVertices_plain gs hgs hcover] + +lemma slotVariance_eq_plain_variance (gs : List (Γ × Γ)) (hgs : SlotsFresh gs ∅) + (hcover : pairSupport gs = Set.univ) (f H : Set Γ → ℝ) : + slotVariance gs f H ∅ = + (∑ S ∈ Finset.univ.filter (PlainState gs), f S*(H S)^2) - + (∑ S ∈ Finset.univ.filter (PlainState gs), f S*H S)^2 / + (∑ S ∈ Finset.univ.filter (PlainState gs), f S) := by + unfold slotVariance + rw [slotTotal_eq_plain_sum gs hgs hcover,slotTotal_eq_plain_sum gs hgs hcover, + slotTotal_eq_plain_sum gs hgs hcover] + +end ChoiceEnumeration + +section DefectEnumeration +open scoped BigOperators Classical +variable {Γ : Type*} [sectionInstance46 : Fintype Γ] [sectionInstance47 : DecidableEq Γ] + +omit sectionInstance46 sectionInstance47 in +lemma pairSupport_perm [Fintype Γ] [DecidableEq Γ] {ps qs : List (Γ × Γ)} (hp : ps.Perm qs) : pairSupport ps = pairSupport qs := by + ext x + simp only [pairSupport,Set.mem_ofPred_eq,hp.mem_iff] + +lemma SlotsFresh.support_disjoint {ps : List (Γ × Γ)} {A : Set Γ} (h : SlotsFresh ps A) : + Disjoint (pairSupport ps) A := by + apply Set.disjoint_left.mpr + rintro x ⟨p,hp,hx⟩ hxA + rcases hx with rfl | rfl + · exact (h.elements_fresh p hp).1 hxA + · exact (h.elements_fresh p hp).2 hxA + +omit sectionInstance46 sectionInstance47 in +lemma PlainState.perm [Fintype Γ] [DecidableEq Γ] {ps qs : List (Γ × Γ)} {S : Set Γ} (h : PlainState ps S) + (hp : ps.Perm qs) : PlainState qs S := fun p hm => h p (hp.mem_iff.mpr hm) + +omit sectionInstance46 sectionInstance47 in +lemma DefectState.perm [Fintype Γ] [DecidableEq Γ] {ps qs : List (Γ × Γ)} {p r : Γ × Γ} {S : Set Γ} + (h : DefectState ps p r S) (hp : ps.Perm qs) : DefectState qs p r S := by + exact ⟨hp.mem_iff.mp h.1,hp.mem_iff.mp h.2.1,h.2.2.1,h.2.2.2.1,h.2.2.2.2.1, + fun t ht => h.2.2.2.2.2 t (hp.mem_iff.mpr ht)⟩ + +lemma choiceVertices_defect (gs : List (Γ × Γ)) (hgs : SlotsFresh gs ∅) + (hcover : pairSupport gs = Set.univ) (p r : Γ × Γ) + (hp : p ∈ gs) (hr : r ∈ gs) (hpr : p ≠ r) : + choiceVertices ((gs.erase p).erase r) {r.1,r.2} = + Finset.univ.filter (DefectState gs p r) := by + let ps := (gs.erase p).erase r + have hperm : gs.Perm (p::r::ps) := slots_perm_two hp hr hpr + have hslots := (SlotsFresh.perm hperm ∅).mp hgs + have htail : SlotsFresh ps {r.1,r.2} := hslots.2.2.2.2.2.2.mono (by + intro x hx + simp only [Set.mem_insert_iff,Set.mem_singleton_iff,Set.mem_empty_iff_false,or_false] at hx ⊢ + tauto) + have hno : p.1 ∉ pairSupport (r::ps) ∧ p.2 ∉ pairSupport (r::ps) := by + exact ⟨fun hx => Set.disjoint_left.mp hslots.2.2.2.support_disjoint hx (Or.inl rfl), + fun hx => Set.disjoint_left.mp hslots.2.2.2.support_disjoint hx (Or.inr (Or.inl rfl))⟩ + have htailSupport : ({r.1,r.2} : Set Γ) ∪ pairSupport ps = pairSupport (r::ps) := by + rw [pairSupport_cons] + ext x + simp only [Set.mem_union,Set.mem_insert_iff,Set.mem_singleton_iff] + tauto + have hcover' : pairSupport (p::r::ps) = Set.univ := (pairSupport_perm hperm).symm.trans hcover + ext S + rw [mem_choiceVertices_iff _ _ _ htail,Finset.mem_filter] + simp only [Finset.mem_univ,true_and] + constructor + · rintro ⟨hfix,hsupp,hsing⟩ + refine ⟨hp,hr,hpr,⟨?_,?_⟩,⟨hfix (Or.inl rfl),hfix (Or.inr rfl)⟩,?_⟩ + · intro hx; exact hno.1 (htailSupport ▸ hsupp hx) + · intro hx; exact hno.2 (htailSupport ▸ hsupp hx) + · intro t ht htp htr + have ht' : t ∈ p::r::ps := hperm.mem_iff.mp ht + simp only [List.mem_cons] at ht' + exact hsing t (ht'.resolve_left htp |>.resolve_left htr) + · intro hdef + refine ⟨?_,?_,?_⟩ + · intro x hx + rcases hx with rfl | hx + · exact hdef.2.2.2.2.1.1 + · exact hx ▸ hdef.2.2.2.2.1.2 + · intro x hx + have hh : x ∈ pairSupport (p::r::ps) := hcover' ▸ Set.mem_univ x + rw [pairSupport_cons] at hh + rcases hh with rfl | rfl | hh + · exact False.elim (hdef.2.2.2.1.1 hx) + · exact False.elim (hdef.2.2.2.1.2 hx) + · exact htailSupport ▸ hh + · intro t ht + exact hdef.2.2.2.2.2 t (hperm.mem_iff.mpr (List.mem_cons_of_mem _ (List.mem_cons_of_mem _ ht))) + (hslots.pair_ne_of_mem (List.mem_cons_of_mem _ ht)).symm + (hslots.2.2.2.pair_ne_of_mem ht).symm + +lemma slotDefect_eq_defect_sum (gs : List (Γ × Γ)) (hgs : SlotsFresh gs ∅) + (hcover : pairSupport gs = Set.univ) (f : Set Γ → ℝ) (p r : Γ × Γ) + (hp : p ∈ gs) (hr : r ∈ gs) (hpr : p ≠ r) : + slotDefect gs f ∅ p r = ∑ S ∈ Finset.univ.filter (DefectState gs p r), f S := by + have hslots := (SlotsFresh.perm (slots_perm_two hp hr hpr) ∅).mp hgs + have htail : SlotsFresh ((gs.erase p).erase r) {r.1,r.2} := hslots.2.2.2.2.2.2.mono (by + intro x hx + simp only [Set.mem_insert_iff,Set.mem_singleton_iff,Set.mem_empty_iff_false,or_false] at hx ⊢ + tauto) + unfold slotDefect + simp only [insert_empty_eq] + rw [slotTotal_eq_choice_sum _ _ f htail,choiceVertices_defect gs hgs hcover p r hp hr hpr] + +lemma choiceVertices_alternatives (ps : List (Γ × Γ)) (A : Set Γ) (p : Γ × Γ) + (hps : SlotsFresh (p::ps) A) : + slotTotal (p::ps) (fun _ => (1:ℝ)) A = 2^(ps.length+1) := by + rw [slotTotal_eq_choice_sum _ _ _ hps] + simp [choiceVertices_card _ _ hps] + +end DefectEnumeration + +section DefectTransport +open scoped BigOperators Classical +variable {Γ : Type*} [sectionInstance48 : Fintype Γ] [sectionInstance49 : DecidableEq Γ] + +def SamePair (p q : Γ × Γ) : Prop := q = p ∨ q = p.swap + +omit sectionInstance48 sectionInstance49 in +lemma SamePair.full [Fintype Γ] [DecidableEq Γ] {p q : Γ × Γ} (h : SamePair p q) (S : Set Γ) : + PairFull q S ↔ PairFull p S := by + rcases h with rfl | rfl <;> simp [PairFull,and_comm] +omit sectionInstance48 sectionInstance49 in +lemma SamePair.empty [Fintype Γ] [DecidableEq Γ] {p q : Γ × Γ} (h : SamePair p q) (S : Set Γ) : + PairEmpty q S ↔ PairEmpty p S := by + rcases h with rfl | rfl <;> simp [PairEmpty,and_comm] +omit sectionInstance48 sectionInstance49 in +lemma SamePair.single [Fintype Γ] [DecidableEq Γ] {p q : Γ × Γ} (h : SamePair p q) (S : Set Γ) : + PairSingle q S ↔ PairSingle p S := by + rcases h with rfl | rfl <;> simp [PairSingle,or_comm] +omit sectionInstance48 sectionInstance49 in +lemma SamePair.set [Fintype Γ] [DecidableEq Γ] {p q : Γ × Γ} (h : SamePair p q) : + ({q.1,q.2} : Set Γ) = {p.1,p.2} := by + rcases h with rfl | rfl <;> simp [Set.pair_comm] +omit sectionInstance48 sectionInstance49 in +lemma SamePair.insert [Fintype Γ] [DecidableEq Γ] {p q : Γ × Γ} (h : SamePair p q) (A : Set Γ) : + insert q.1 (insert q.2 A) = insert p.1 (insert p.2 A) := by + rcases h with rfl | rfl <;> simp [Set.insert_comm] +omit sectionInstance48 sectionInstance49 in +lemma SamePair.fresh [Fintype Γ] [DecidableEq Γ] {p q : Γ × Γ} (h : SamePair p q) (ps : List (Γ × Γ)) (A : Set Γ) : + SlotsFresh (q::ps) A ↔ SlotsFresh (p::ps) A := by + rcases h with rfl | rfl + · rfl + · simp only [SlotsFresh,Prod.fst_swap,Prod.snd_swap,ne_eq] + rw [Set.insert_comm] + tauto + +lemma slot_energy_le_chain (gs ps : List (Γ × Γ)) (A : Set Γ) (p d : Γ) + (W : Γ → ℝ) (w : (Γ × Γ) → (Γ × Γ) → ℝ) (f H : Set Γ → ℝ) + (hw : ∀ p r, 0 < w p r) (hf : ∀ S, 0 < f S) + (hv : ∀ S ∈ slotVertices ps A (rootEmbedding p d), + ChainState gs S ∧ missingMultiplier ps (rootEmbedding p d) W S = chainMultiplier gs w S) : + slotGraphEnergy ps f H A (rootEmbedding p d) W ≤ + restrictedEnergy (chainEdges gs) (chainConductance gs w f) H ∅ ∅ := by + unfold slotGraphEnergy restrictedEnergy + simp only [EdgeRespects,Respects,Set.empty_subset,Set.empty_disjoint,true_and,ite_true] + apply div_le_div_of_nonneg_right _ (by norm_num) + have hE : slotGraphEdges ps A (rootEmbedding p d) ⊆ chainEdges gs := by + intro ST hST + obtain ⟨hp,ha⟩ := Finset.mem_filter.mp hST + obtain ⟨hs,ht⟩ := Finset.mem_product.mp hp + exact Finset.mem_filter.mpr ⟨Finset.mem_univ _,(hv _ hs).1,(hv _ ht).1,ha⟩ + calc + _ = ∑ ST ∈ slotGraphEdges ps A (rootEmbedding p d), + chainConductance gs w f ST*(H ST.1-H ST.2)^2 := by + apply Finset.sum_congr rfl + intro ST hST + obtain ⟨hs,ht⟩ := Finset.mem_product.mp (Finset.mem_filter.mp hST).1 + simp only [slotEdgeEnergy,(hv _ hs).2,(hv _ ht).2,chainConductance] + _ ≤ _ := by + apply Finset.sum_le_sum_of_subset_of_nonneg hE + intro ST _ _ + exact mul_nonneg (le_min + (mul_nonneg (chainMultiplier_pos gs w hw _).le (hf _).le) + (mul_nonneg (chainMultiplier_pos gs w hw _).le (hf _).le)) (sq_nonneg _) + +lemma defect_vertex_identification (gs ps : List (Γ × Γ)) (p r u v : Γ × Γ) + (hperm : gs.Perm (p::r::ps)) (hgs : SlotsFresh gs ∅) + (hu : SamePair p u) (hv : SamePair r v) + (w : (Γ × Γ) → (Γ × Γ) → ℝ) + (S : Set Γ) (hS : S ∈ slotVertices ps {v.2} (rootEmbedding v.1 u.1)) : + ChainState gs S ∧ missingMultiplier ps (rootEmbedding v.1 u.1) + (pairMultiplier (r::ps) (w p)) S = chainMultiplier gs w S := by + have hslots := (SlotsFresh.perm hperm ∅).mp hgs + have horient : SlotsFresh (u::v::ps) ∅ := by + apply (hu.fresh _ _).mpr + change _ ∧ _ ∧ _ ∧ SlotsFresh (v::ps) (insert p.1 (insert p.2 ∅)) + exact ⟨hslots.1,hslots.2.1,hslots.2.2.1,(hv.fresh _ _).mpr hslots.2.2.2⟩ + have hfull : insert u.1 (insert u.2 (insert v.1 (insert v.2 (∅ : Set Γ)))) = + insert v.1 (insert v.2 (insert u.1 (insert u.2 ∅))) := by + ext x; simp only [Set.mem_insert_iff]; tauto + have htail := horient.2.2.2.2.2.2 + have hbase : SlotsFresh ps ({v.2} ∪ Set.range (rootEmbedding v.1 u.1)) := + htail.mono (by + intro x hx + rcases hx with hx | ⟨i,rfl⟩ + · simp only [Set.mem_singleton_iff] at hx; subst x; simp + · cases i <;> simp [rootEmbedding]) + have hne : v.1 ≠ u.1 := by + intro he; exact horient.2.2.2.2.1 (Or.inl he) + have hvu : v.2 ≠ u.1 := by + intro he; exact horient.2.2.2.2.2.1 (Or.inl he) + have heA : ∀ j, rootEmbedding v.1 u.1 j ∉ ({v.2} : Set Γ) := by + intro j; cases j + · exact horient.2.2.2.1 + · exact hvu.symm + have hinc : v.2 ∈ S := slotVertices_fixed ps {v.2} _ S hS rfl + have heB : ∀ j, rootEmbedding v.1 u.1 j ∉ ({u.2} : Set Γ) := by + intro j; cases j + · exact fun he => horient.2.2.2.2.1 (Or.inr (Or.inl he)) + · exact horient.1 + have hexc : u.2 ∉ S := by + have hh := slotVertices_excluded ps {v.2} {u.2} (rootEmbedding v.1 u.1) + (by simpa only [Set.disjoint_singleton] using (show v.2 ≠ u.2 from fun he => + horient.2.2.2.2.2.1 (Or.inr (Or.inl he)))) heB + (fun t ht => let hh := htail.elements_fresh t ht + ⟨fun he => hh.1 (Or.inr (Or.inr (Or.inr (Or.inl he)))), + fun he => hh.2 (Or.inr (Or.inr (Or.inr (Or.inl he))))⟩) S hS + exact fun hx => Set.disjoint_left.mp hh rfl hx + have hmem (t : Γ × Γ) (ht : t ∈ gs) (hp : t ≠ p) (hr : t ≠ r) : t ∈ ps := + ((List.mem_cons.mp (hperm.mem_iff.mp ht)).resolve_left hp |> List.mem_cons.mp).resolve_left hr + have hp : p ∈ gs := hperm.mem_iff.mpr List.mem_cons_self + have hr : r ∈ gs := hperm.mem_iff.mpr (List.mem_cons_of_mem _ List.mem_cons_self) + have hpr : p ≠ r := hslots.pair_ne_of_mem List.mem_cons_self + have hcl := slotVertices_classify ps {v.2} _ (rootEmbedding_injective _ _ hne) heA hbase S hS + rcases hcl with ⟨j,hj,hrest⟩ | ⟨t,ht,he,hfull,hrest⟩ + · cases j + · have hdef : DefectState gs p r S := by + refine ⟨hp,hr,hpr,(hu.empty S).mp ⟨?_,hexc⟩,(hv.full S).mp ⟨?_,hinc⟩,?_⟩ + · exact fun hh => Bool.noConfusion ((hj true).mp hh) + · exact (hj false).mpr rfl + · intro t ht htp htr; exact hrest t (hmem t ht htp htr) + refine ⟨Or.inr ⟨p,r,hdef⟩,?_⟩ + rw [chainMultiplier_defect gs w S hdef,missingMultiplier_old ps _ _ S false hj hrest] + apply pairMultiplier_on hslots.2.2.2 _ r List.mem_cons_self v.1 + rcases hv with rfl | rfl <;> simp + · have hplain : PlainState gs S := by + intro t ht + by_cases ht₁ : t = p + · subst t; apply (hu.single S).mp; exact Or.inl ⟨(hj true).mpr rfl,hexc⟩ + by_cases ht₂ : t = r + · subst t; apply (hv.single S).mp + exact Or.inr ⟨hinc,fun hh => Bool.noConfusion ((hj false).mp hh)⟩ + exact hrest t (hmem t ht ht₁ ht₂) + refine ⟨Or.inl hplain,?_⟩ + rw [chainMultiplier_plain gs w S hplain,missingMultiplier_old ps _ _ S true hj hrest] + apply pairMultiplier_fresh hslots.2.2.2 + rcases hu with rfl | rfl <;> simp [rootEmbedding] + · have hdef : DefectState gs p t S := by + refine ⟨hp,hperm.mem_iff.mpr (List.mem_cons_of_mem _ (List.mem_cons_of_mem _ ht)), + hslots.pair_ne_of_mem (List.mem_cons_of_mem _ ht),(hu.empty S).mp ⟨he true,hexc⟩,hfull,?_⟩ + intro z hz hzp hzt + by_cases hzr : z = r + · subst z; exact (hv.single S).mp (Or.inr ⟨hinc,he false⟩) + · exact hrest z (hmem z hz hzp hzr) hzt + refine ⟨Or.inr ⟨p,t,hdef⟩,?_⟩ + rw [chainMultiplier_defect gs w S hdef, + missingMultiplier_new ps htail.nodup _ _ S t ht he hfull hrest] + exact pairMultiplier_on hslots.2.2.2 _ t (List.mem_cons_of_mem _ ht) t.1 (Or.inl rfl) + +lemma SamePair.fresh_two {p r u v : Γ × Γ} (hu : SamePair p u) (hv : SamePair r v) + (ps : List (Γ × Γ)) (A : Set Γ) (h : SlotsFresh (p::r::ps) A) : + SlotsFresh (u::v::ps) A := by + apply (hu.fresh _ _).mpr + exact ⟨h.1,h.2.1,h.2.2.1,(hv.fresh _ _).mpr h.2.2.2⟩ + +lemma slotDefect_rest (gs ps : List (Γ × Γ)) (p r : Γ × Γ) + (hperm : gs.Perm (p::r::ps)) (f : Set Γ → ℝ) : + slotDefect gs f ∅ p r = slotTotal ps f {r.1,r.2} := by + rw [slotDefect_perm hperm] + simp [slotDefect] + +lemma defect_puncture_le (gs ps : List (Γ × Γ)) (p r u v : Γ × Γ) + (hperm : gs.Perm (p::r::ps)) (hgs : SlotsFresh gs ∅) + (hu : SamePair p u) (hv : SamePair r v) (f : Set Γ → ℝ) (hf : ∀ S, 0 < f S) + (x : (Γ × Γ) × List (Γ × Γ)) (hx : x ∈ slotPunctures ps) : + slotTotal x.2 f (insert v.1 (insert u.1 {v.2})) ≤ slotDefect gs f ∅ x.1 r := by + have hxp := slotPunctures_perm ps x hx + have hxmem : x.1 ∈ ps := hxp.mem_iff.mpr List.mem_cons_self + have hslots := (SlotsFresh.perm hperm ∅).mp hgs + have hpt := hslots.pair_ne_of_mem (List.mem_cons_of_mem _ hxmem) + have hrt := hslots.2.2.2.pair_ne_of_mem hxmem + have hpr := hslots.pair_ne_of_mem List.mem_cons_self + have heq : insert v.1 (insert u.1 ({v.2} : Set Γ)) = insert u.1 {r.1,r.2} := by + rw [Set.insert_comm v.1 u.1,hv.set] + rw [heq,slotDefect_perm (hperm.trans ((hxp.cons r).cons p))] + simp only [slotDefect] + simp [hpt,hrt,hpr,insert_empty_eq] + have hp₁ : p.1 ∉ ({r.1,r.2} : Set Γ) := by + rintro (he | he) + · exact hslots.2.2.2.2.1 (Or.inl he.symm) + · exact hslots.2.2.2.2.2.1 (Or.inl he.symm) + have hp₂ : p.2 ∉ ({r.1,r.2} : Set Γ) := by + rintro (he | he) + · exact hslots.2.2.2.2.1 (Or.inr (Or.inl he.symm)) + · exact hslots.2.2.2.2.2.1 (Or.inr (Or.inl he.symm)) + rw [slotTotal_cons p x.2 f {r.1,r.2} hslots.1 hp₁ hp₂] + rcases hu with rfl | rfl + · exact le_add_of_nonneg_right (slotTotal_nonneg _ f (fun S => (hf S).le) _) + · exact le_add_of_nonneg_left (slotTotal_nonneg _ f (fun S => (hf S).le) _) + +theorem defect_conditional_transport (gs ps : List (Γ × Γ)) (p r u v : Γ × Γ) + (hperm : gs.Perm (p::r::ps)) (hgs : SlotsFresh gs ∅) + (hu : SamePair p u) (hv : SamePair r v) + (f H : Set Γ → ℝ) (hf : ∀ S, 0 < f S) (hsig : HasSlotSignature f) + (w : (Γ × Γ) → (Γ × Γ) → ℝ) (hw : ∀ p r, 0 < w p r) + (hgood : ∀ p ∈ gs, ∀ r ∈ gs, p ≠ r → slotTotal gs f ∅/(4*slotDefect gs f ∅ p r) ≤ w p r) : + let z := slotTotal gs f ∅ + let sp := slotDefect gs f ∅ p r + let sd := slotTotal ps f {u.1,v.2} + sd*(slotDefect gs (fun S => f S*H S) ∅ p r/sp - + slotTotal ps (fun S => f S*H S) {u.1,v.2}/sd)^2 ≤ + (4*sd/z+1+8*(ps.length:ℝ))* + restrictedEnergy (chainEdges gs) (chainConductance gs w f) H ∅ ∅ := by + let z := slotTotal gs f ∅ + let sp := slotDefect gs f ∅ p r + let sd := slotTotal ps f {u.1,v.2} + let W := pairMultiplier (r::ps) (w p) + let D := restrictedEnergy (chainEdges gs) (chainConductance gs w f) H ∅ ∅ + have hslots := (SlotsFresh.perm hperm ∅).mp hgs + have horient := hu.fresh_two hv ps ∅ hslots + have hp : p ∈ gs := hperm.mem_iff.mpr List.mem_cons_self + have hr : r ∈ gs := hperm.mem_iff.mpr (List.mem_cons_of_mem _ List.mem_cons_self) + have hpr := hslots.pair_ne_of_mem List.mem_cons_self + have hz : 0 < z := slotTotal_pos gs f hf ∅ hgs + have hsp : 0 < sp := slotDefect_pos gs f hf ∅ hgs p r hp hr hpr + have hsd : 0 < sd := slotTotal_pos ps f hf _ (horient.2.2.2.2.2.2.mono (by + intro x hx + simp only [Set.mem_insert_iff,Set.mem_singleton_iff] at hx ⊢ + rcases hx with rfl | rfl <;> simp)) + have hbase : SlotsFresh ps ({v.2} ∪ Set.range (rootEmbedding v.1 u.1)) := + horient.2.2.2.2.2.2.mono (by + intro x hx + rcases hx with hx | ⟨i,rfl⟩ + · simp only [Set.mem_singleton_iff] at hx; subst x; simp + · cases i <;> simp [rootEmbedding]) + have hne : v.1 ≠ u.1 := fun he => horient.2.2.2.2.1 (Or.inl he) + have hpA : v.1 ∉ ({v.2} : Set Γ) := horient.2.2.2.1 + have hdA : u.1 ∉ ({v.2} : Set Γ) := fun he => horient.2.2.2.2.2.1 (Or.inl he.symm) + have hW : ∀ x, 0 < W x := pairMultiplier_pos _ _ (hw p) + have hws : ∀ t ∈ ps, W t.1 = W t.2 := by + intro t ht + dsimp [W] + rw [pairMultiplier_on hslots.2.2.2 _ t (List.mem_cons_of_mem _ ht) t.1 (Or.inl rfl), + pairMultiplier_on hslots.2.2.2 _ t (List.mem_cons_of_mem _ ht) t.2 (Or.inr rfl)] + have hWp : W v.1 = w p r := by + apply pairMultiplier_on hslots.2.2.2 _ r List.mem_cons_self v.1 + rcases hv with rfl | rfl <;> simp + have hWd : W u.1 = 1 := by + apply pairMultiplier_fresh hslots.2.2.2 + rcases hu with rfl | rfl <;> simp + have heqsp (g : Set Γ → ℝ) : slotTotal ps g (insert v.1 {v.2}) = slotDefect gs g ∅ p r := by + rw [hv.set,slotDefect_rest gs ps p r hperm g] + have hgoodpr : z ≤ 4*sp*w p r := by + have hh := (div_le_iff₀ (by positivity : 0 < 4*sp)).mp (hgood p hp r hr hpr) + dsimp [z,sp] at *; nlinarith + have hfirst : 1/(sp*w p r) ≤ 4/z := by + apply (div_le_div_iff₀ (mul_pos hsp (hw p r)) hz).mpr + nlinarith + have hsink : ∀ x ∈ slotPunctures ps, + slotTotal x.2 f (insert v.1 (insert u.1 {v.2}))/W x.1.1 ≤ 4*sp := by + intro x hx + have hxmem : x.1 ∈ ps := (slotPunctures_perm ps x hx).mem_iff.mpr List.mem_cons_self + have hxg : x.1 ∈ gs := hperm.mem_iff.mpr (List.mem_cons_of_mem _ (List.mem_cons_of_mem _ hxmem)) + have hpt := hslots.pair_ne_of_mem (List.mem_cons_of_mem _ hxmem) + have hrt := hslots.2.2.2.pair_ne_of_mem hxmem + have hcx := slotDefect_pos gs f hf ∅ hgs p x.1 hp hxg hpt + have htriple := slotDefect_triple_bound gs f hf hsig ∅ hgs p x.1 r hp hxg hr hpt hrt.symm hpr + have hvle := defect_puncture_le gs ps p r u v hperm hgs hu hv f hf x hx + have hg := (div_le_iff₀ (by positivity : 0 < 4*slotDefect gs f ∅ p x.1)).mp + (hgood p hp x.1 hxg hpt) + have hg' := mul_le_mul_of_nonneg_left hg hsp.le + have hv' := mul_le_mul_of_nonneg_left hvle hcx.le + have hb : slotTotal x.2 f (insert v.1 (insert u.1 {v.2})) ≤ 4*sp*w p x.1 := by + apply (mul_le_mul_iff_of_pos_right hcx).mp + dsimp [z,sp] at * + nlinarith + dsimp [W] + rw [pairMultiplier_on hslots.2.2.2 _ x.1 (List.mem_cons_of_mem _ hxmem) x.1.1 (Or.inl rfl)] + exact (div_le_iff₀ (hw p x.1)).mpr hb + have hsum := list_sum_map_le_const (slotPunctures ps) + (fun x => slotTotal x.2 f (insert v.1 (insert u.1 {v.2}))/W x.1.1) (4*sp) hsink + rw [slotPunctures_length] at hsum + have hcoef : sd*rootCoefficient ps f {v.2} v.1 u.1 W ≤ 4*sd/z+1+8*(ps.length:ℝ) := by + unfold rootCoefficient + rw [heqsp f,hWp,hWd] + dsimp only + rw [mul_one] + change sd*(1/(sp*w p r)+1/sd+2/(sp*sd)*_) ≤ _ + have h₁ := mul_le_mul_of_nonneg_left hfirst hsd.le + have h₂ := mul_le_mul_of_nonneg_left hsum (show 0 ≤ 2/sp by positivity) + have heq (a b : ℝ) : sd*(a+1/sd+2/(sp*sd)*b) = sd*a+1+(2/sp)*b := by + field_simp + + rw [heq] + have heq' : 2/sp*((ps.length:ℝ)*(4*sp)) = 8*(ps.length:ℝ) := by + field_simp + ; ring + rw [heq'] at h₂ + calc + _ ≤ sd*(4/z)+1+8*(ps.length:ℝ) := by linarith only [h₁,h₂] + _ = _ := by ring + have he := slot_energy_le_chain gs ps {v.2} v.1 u.1 W w f H hw hf + (defect_vertex_identification gs ps p r u v hperm hgs hu hv w) + have ht := transport_graph_bound ps f H {v.2} v.1 u.1 W hf hsig hne hpA hdA hbase hW hws + have hcp := rootCoefficient_pos ps f hf {v.2} v.1 u.1 W hbase hW + have hD : 0 ≤ D := restrictedEnergy_nonneg _ _ _ _ _ (by + intro ST _ + exact le_min (mul_nonneg (chainMultiplier_pos gs w hw _).le (hf _).le) + (mul_nonneg (chainMultiplier_pos gs w hw _).le (hf _).le)) + have htnew := mul_le_mul_of_nonneg_left ht hsd.le + rw [← mul_assoc] at htnew + have hb := htnew.trans + ((mul_le_mul_of_nonneg_left he (mul_nonneg hsd.le hcp.le)).trans + (mul_le_mul_of_nonneg_right hcoef hD)) + simpa only [heqsp f,heqsp (fun S => f S*H S),← mul_assoc] using hb + +end DefectTransport + +section DefectMeans +open scoped BigOperators Classical +variable {Γ : Type*} [sectionInstance50 : Fintype Γ] [sectionInstance51 : DecidableEq Γ] + +def orientPair (p : Γ × Γ) (b : Bool) : Γ × Γ := if b then p.swap else p +omit sectionInstance50 sectionInstance51 in +lemma orientPair_same [Fintype Γ] [DecidableEq Γ] (p : Γ × Γ) (b : Bool) : SamePair p (orientPair p b) := by + cases b <;> simp [orientPair,SamePair] + +lemma slotTotal_four (gs ps : List (Γ × Γ)) (p r : Γ × Γ) + (hperm : gs.Perm (p::r::ps)) (hgs : SlotsFresh gs ∅) (f : Set Γ → ℝ) : + ∑ o : Bool × Bool, slotTotal ps f {(orientPair p o.1).1,(orientPair r o.2).2} = + slotTotal gs f ∅ := by + have hslots := (SlotsFresh.perm hperm ∅).mp hgs + have hr₁ : r.1 ∉ (insert p.1 (∅ : Set Γ)) := fun hx => hslots.2.2.2.2.1 (by + simp only [Set.mem_insert_iff] at hx ⊢; tauto) + have hr₂ : r.2 ∉ (insert p.1 (∅ : Set Γ)) := fun hx => hslots.2.2.2.2.2.1 (by + simp only [Set.mem_insert_iff] at hx ⊢; tauto) + have hr₃ : r.1 ∉ (insert p.2 (∅ : Set Γ)) := fun hx => hslots.2.2.2.2.1 (Or.inr hx) + have hr₄ : r.2 ∉ (insert p.2 (∅ : Set Γ)) := fun hx => hslots.2.2.2.2.2.1 (Or.inr hx) + rw [slotTotal_perm hperm f,slotTotal_cons p (r::ps) f ∅ hslots.1 hslots.2.1 hslots.2.2.1, + slotTotal_cons r ps f _ hslots.2.2.2.1 hr₁ hr₂, + slotTotal_cons r ps f _ hslots.2.2.2.1 hr₃ hr₄] + simp only [Fintype.sum_prod_type,Fintype.sum_bool,orientPair,Bool.false_eq_true, + ite_false,ite_true,Prod.fst_swap,Prod.snd_swap,insert_empty_eq] + rw [Set.pair_comm r.1 p.1,Set.pair_comm r.2 p.1,Set.pair_comm r.1 p.2,Set.pair_comm r.2 p.2] + ring + +lemma weighted_square_mean {J : Type*} [Fintype J] (w x : J → ℝ) (hw : ∀ j, 0 < w j) : + (∑ j, w j*x j)^2/(∑ j, w j) ≤ ∑ j, w j*(x j)^2 := by + have h := Finset.sq_sum_div_le_sum_sq_div Finset.univ (fun j => w j*x j) (fun j _ => hw j) + have heq : (∑ j, (w j*x j)^2/w j) = ∑ j, w j*(x j)^2 := by + apply Finset.sum_congr rfl + intro j _ + field_simp [ne_of_gt (hw j)] + + rw [heq] at h + exact h + +theorem defect_mean_bound (gs : List (Γ × Γ)) (p r : Γ × Γ) + (hgs : SlotsFresh gs ∅) (hp : p ∈ gs) (hr : r ∈ gs) (hpr : p ≠ r) + (f H : Set Γ → ℝ) (hf : ∀ S, 0 < f S) (hsig : HasSlotSignature f) + (w : (Γ × Γ) → (Γ × Γ) → ℝ) (hw : ∀ p r, 0 < w p r) + (hgood : ∀ p ∈ gs, ∀ r ∈ gs, p ≠ r → slotTotal gs f ∅/(4*slotDefect gs f ∅ p r) ≤ w p r) : + slotTotal gs f ∅ * + (slotDefect gs (fun S => f S*H S) ∅ p r/slotDefect gs f ∅ p r - + slotTotal gs (fun S => f S*H S) ∅/slotTotal gs f ∅)^2 ≤ + (8+32*(gs.length:ℝ))*restrictedEnergy (chainEdges gs) (chainConductance gs w f) H ∅ ∅ := by + let ps := (gs.erase p).erase r + have hperm : gs.Perm (p::r::ps) := slots_perm_two hp hr hpr + let z := slotTotal gs f ∅ + let m := slotDefect gs (fun S => f S*H S) ∅ p r/slotDefect gs f ∅ p r + let s : Bool × Bool → ℝ := fun o => slotTotal ps f {(orientPair p o.1).1,(orientPair r o.2).2} + let a : Bool × Bool → ℝ := fun o => slotTotal ps (fun S => f S*H S) + {(orientPair p o.1).1,(orientPair r o.2).2} + let D := restrictedEnergy (chainEdges gs) (chainConductance gs w f) H ∅ ∅ + have hz : 0 < z := slotTotal_pos gs f hf ∅ hgs + have hs : ∀ o, 0 < s o := by + intro o + have hh := (orientPair_same p o.1).fresh_two (orientPair_same r o.2) ps ∅ + ((SlotsFresh.perm hperm ∅).mp hgs) + apply slotTotal_pos ps f hf _ (hh.2.2.2.2.2.2.mono _) + intro x hx + simp only [Set.mem_insert_iff,Set.mem_singleton_iff] at hx ⊢ + rcases hx with rfl | rfl <;> simp + have hsum : ∑ o, s o = z := slotTotal_four gs ps p r hperm hgs f + have hsumA : ∑ o, a o = slotTotal gs (fun S => f S*H S) ∅ := + slotTotal_four gs ps p r hperm hgs _ + have ha (o : Bool × Bool) : s o*(m-a o/s o) = s o*m-a o := by + field_simp [ne_of_gt (hs o)] + + have hmean := weighted_square_mean s (fun o => m-a o/s o) hs + simp_rw [ha] at hmean + rw [Finset.sum_sub_distrib,← Finset.sum_mul,hsum,hsumA] at hmean + have heq : (z*m-slotTotal gs (fun S => f S*H S) ∅)^2/z = + z*(m-slotTotal gs (fun S => f S*H S) ∅/z)^2 := by + field_simp + + rw [heq] at hmean + have hc (o : Bool × Bool) : s o*(m-a o/s o)^2 ≤ + (4*s o/z+1+8*(ps.length:ℝ))*D := + defect_conditional_transport gs ps p r (orientPair p o.1) (orientPair r o.2) + hperm hgs (orientPair_same p o.1) (orientPair_same r o.2) f H hf hsig w hw hgood + have hsumc := Finset.sum_le_sum (fun o (_ : o ∈ (Finset.univ : Finset (Bool × Bool))) => hc o) + have hsumcoef : (∑ o : Bool × Bool, (4*s o/z+1+8*(ps.length:ℝ))*D) = + (8+32*(ps.length:ℝ))*D := by + rw [← Finset.sum_mul] + congr 1 + simp only [Finset.sum_add_distrib,← Finset.sum_div,← Finset.mul_sum,hsum] + simp [ne_of_gt hz] + ; ring + rw [hsumcoef] at hsumc + have hD : 0 ≤ D := restrictedEnergy_nonneg _ _ _ _ _ (by + intro ST _ + exact le_min (mul_nonneg (chainMultiplier_pos gs w hw _).le (hf _).le) + (mul_nonneg (chainMultiplier_pos gs w hw _).le (hf _).le)) + have hlen : (ps.length:ℝ) ≤ gs.length := by + have hh := hperm.length_eq + simp only [List.length_cons] at hh + exact_mod_cast (show ps.length ≤ gs.length by omega) + exact (hmean.trans hsumc).trans (mul_le_mul_of_nonneg_right (by linarith) hD) + +end DefectMeans + +section Observable +open scoped BigOperators Classical +variable {Γ : Type*} [sectionInstance52 : Fintype Γ] [DecidableEq Γ] + +noncomputable def chainStates (gs : List (Γ × Γ)) : Finset (Set Γ) := + Finset.univ.filter (ChainState gs) +noncomputable def defectTypes (gs : List (Γ × Γ)) : Finset ((Γ × Γ) × (Γ × Γ)) := + gs.toFinset.offDiag +noncomputable def chainWeight (gs : List (Γ × Γ)) + (w : (Γ × Γ) → (Γ × Γ) → ℝ) (f : Set Γ → ℝ) (S : Set Γ) : ℝ := + chainMultiplier gs w S * f S +noncomputable def chainTotal (gs : List (Γ × Γ)) + (w : (Γ × Γ) → (Γ × Γ) → ℝ) (f : Set Γ → ℝ) : ℝ := + ∑ S ∈ chainStates gs, chainWeight gs w f S +noncomputable def plainMean (gs : List (Γ × Γ)) (f H : Set Γ → ℝ) : ℝ := + slotTotal gs (fun S => f S*H S) ∅/slotTotal gs f ∅ +noncomputable def defectMean (gs : List (Γ × Γ)) (f H : Set Γ → ℝ) (p r : Γ × Γ) : ℝ := + slotDefect gs (fun S => f S*H S) ∅ p r/slotDefect gs f ∅ p r +noncomputable def observableProjection (gs : List (Γ × Γ)) (f H : Set Γ → ℝ) (S : Set Γ) : ℝ := + if h : ∃ p r, DefectState gs p r S then defectMean gs f H h.choose h.choose_spec.choose else H S + +lemma observableProjection_plain (gs : List (Γ × Γ)) (f H : Set Γ → ℝ) (S : Set Γ) + (h : PlainState gs S) : observableProjection gs f H S = H S := by + unfold observableProjection + rw [dite_eq_right] + rintro ⟨p,r,hpr⟩ + exact hpr.not_plain h +lemma observableProjection_defect (gs : List (Γ × Γ)) (f H : Set Γ → ℝ) (S : Set Γ) + {p r : Γ × Γ} (h : DefectState gs p r S) : observableProjection gs f H S = defectMean gs f H p r := by + have he : ∃ p r, DefectState gs p r S := ⟨p,r,h⟩ + unfold observableProjection + rw [dite_eq_left he] + have hh := he.choose_spec.choose_spec.unique h + exact congrArg₂ (defectMean gs f H) hh.1 hh.2 + +omit sectionInstance52 in +lemma mem_defectTypes [Fintype Γ] (gs : List (Γ × Γ)) (pr : (Γ × Γ) × (Γ × Γ)) : + pr ∈ defectTypes gs ↔ pr.1 ∈ gs ∧ pr.2 ∈ gs ∧ pr.1 ≠ pr.2 := by + simp [defectTypes,Finset.mem_offDiag] + +lemma chain_sum_decomposition (gs : List (Γ × Γ)) (w : (Γ × Γ) → (Γ × Γ) → ℝ) + (g : Set Γ → ℝ) : + (∑ S ∈ chainStates gs, chainMultiplier gs w S*g S) = + (∑ S ∈ Finset.univ.filter (PlainState gs),g S) + + ∑ pr ∈ defectTypes gs, w pr.1 pr.2 * + ∑ S ∈ Finset.univ.filter (DefectState gs pr.1 pr.2),g S := by + simp only [chainStates,Finset.sum_filter,Finset.mul_sum] + rw [Finset.sum_comm,← Finset.sum_add_distrib] + apply Finset.sum_congr rfl + intro S _ + by_cases hp : PlainState gs S + · have hd : ∀ p r, ¬ DefectState gs p r S := fun p r hh => hh.not_plain hp + simp [hp,ChainState,chainMultiplier_plain gs w S hp,hd] + · by_cases hd : ∃ p r, DefectState gs p r S + · obtain ⟨p,r,hpr⟩ := hd + have hmem : (p,r) ∈ defectTypes gs := (mem_defectTypes gs _).mpr ⟨hpr.1,hpr.2.1,hpr.2.2.1⟩ + have hu : ∀ pr ∈ defectTypes gs, pr ≠ (p,r) → ¬ DefectState gs pr.1 pr.2 S := by + intro pr _ hn hh + have he := hh.unique hpr + exact hn (Prod.ext he.1 he.2) + rw [ite_eq_left (show ChainState gs S from Or.inr ⟨p,r,hpr⟩),ite_eq_right hp,zero_add, + Finset.sum_eq_single (p,r)] + · simp [hpr,chainMultiplier_defect gs w S hpr] + · intro pr hm hn + simp [hu pr hm hn] + · exact fun hn => False.elim (hn hmem) + · have hd' : ∀ p r, ¬ DefectState gs p r S := fun p r hh => hd ⟨p,r,hh⟩ + simp [ChainState,hp,hd'] + +lemma chainTotal_eq (gs : List (Γ × Γ)) (hgs : SlotsFresh gs ∅) + (hcover : pairSupport gs = Set.univ) (w : (Γ × Γ) → (Γ × Γ) → ℝ) (f : Set Γ → ℝ) : + chainTotal gs w f = slotTotal gs f ∅ + + ∑ pr ∈ defectTypes gs, w pr.1 pr.2*slotDefect gs f ∅ pr.1 pr.2 := by + unfold chainTotal chainWeight + rw [chain_sum_decomposition,← slotTotal_eq_plain_sum gs hgs hcover f] + congr 1 + apply Finset.sum_congr rfl + intro pr hm + obtain ⟨hp,hr,hpr⟩ := (mem_defectTypes gs pr).mp hm + rw [slotDefect_eq_defect_sum gs hgs hcover f pr.1 pr.2 hp hr hpr] + +lemma chainTotal_ge_plain (gs : List (Γ × Γ)) (hgs : SlotsFresh gs ∅) + (hcover : pairSupport gs = Set.univ) (w : (Γ × Γ) → (Γ × Γ) → ℝ) + (f : Set Γ → ℝ) (hf : ∀ S, 0 < f S) (hw : ∀ p r, 0 < w p r) : + slotTotal gs f ∅ ≤ chainTotal gs w f := by + rw [chainTotal_eq gs hgs hcover w f] + apply le_add_of_nonneg_right + apply Finset.sum_nonneg + intro pr hm + obtain ⟨hp,hr,hpr⟩ := (mem_defectTypes gs pr).mp hm + exact mul_nonneg (hw _ _).le (slotDefect_pos gs f hf ∅ hgs pr.1 pr.2 hp hr hpr).le + +lemma chainTotal_pos (gs : List (Γ × Γ)) (hgs : SlotsFresh gs ∅) + (hcover : pairSupport gs = Set.univ) (w : (Γ × Γ) → (Γ × Γ) → ℝ) + (f : Set Γ → ℝ) (hf : ∀ S, 0 < f S) (hw : ∀ p r, 0 < w p r) : + 0 < chainTotal gs w f := + (slotTotal_pos gs f hf ∅ hgs).trans_le (chainTotal_ge_plain gs hgs hcover w f hf hw) + +omit sectionInstance52 in +lemma defectTypes_card_le [Fintype Γ] (gs : List (Γ × Γ)) : + (defectTypes gs).card ≤ gs.length*gs.length := by + calc + _ ≤ gs.toFinset.card*gs.toFinset.card := by simp [defectTypes,Finset.offDiag_card] + _ ≤ _ := Nat.mul_le_mul (List.toFinset_card_le _) (List.toFinset_card_le _) + +lemma chainTotal_le (gs : List (Γ × Γ)) (hgs : SlotsFresh gs ∅) (hne : gs ≠ []) + (hcover : pairSupport gs = Set.univ) (w : (Γ × Γ) → (Γ × Γ) → ℝ) + (f : Set Γ → ℝ) (hf : ∀ S, 0 < f S) + (hupper : ∀ p ∈ gs, ∀ r ∈ gs, p ≠ r → w p r ≤ 4*slotTotal gs f ∅/slotDefect gs f ∅ p r) : + chainTotal gs w f ≤ 5*(gs.length:ℝ)^2*slotTotal gs f ∅ := by + rw [chainTotal_eq gs hgs hcover w f] + have hz := slotTotal_pos gs f hf ∅ hgs + have hc : (∑ pr ∈ defectTypes gs, w pr.1 pr.2*slotDefect gs f ∅ pr.1 pr.2) ≤ + (defectTypes gs).card*(4*slotTotal gs f ∅) := by + calc + _ ≤ ∑ _pr ∈ defectTypes gs, 4*slotTotal gs f ∅ := by + apply Finset.sum_le_sum + intro pr hm + obtain ⟨hp,hr,hpr⟩ := (mem_defectTypes gs pr).mp hm + exact (le_div_iff₀ (slotDefect_pos gs f hf ∅ hgs pr.1 pr.2 hp hr hpr)).mp + (hupper pr.1 hp pr.2 hr hpr) + _ = _ := by simp + have hcard : ((defectTypes gs).card:ℝ) ≤ (gs.length:ℝ)^2 := by + exact_mod_cast (show (defectTypes gs).card ≤ gs.length^2 by simpa [pow_two] using defectTypes_card_le gs) + have hn : 1 ≤ (gs.length:ℝ) := by exact_mod_cast List.length_pos_iff.mpr hne + have hn2 : 1 ≤ (gs.length:ℝ)^2 := by nlinarith + nlinarith [mul_le_mul_of_nonneg_right hcard (show 0 ≤ 4*slotTotal gs f ∅ by positivity)] + +lemma finite_center_sum {X : Type*} (s : Finset X) (w H : X → ℝ) (a : ℝ) : + (∑ x ∈ s, w x*(H x-a)^2) = (∑ x ∈ s, w x*(H x)^2) - + 2*a*(∑ x ∈ s,w x*H x)+a^2*(∑ x ∈ s,w x) := by + have he (x : X) : w x*(H x-a)^2 = w x*(H x)^2 - 2*a*(w x*H x)+a^2*w x := by ring + simp_rw [he] + rw [Finset.sum_add_distrib,Finset.sum_sub_distrib,← Finset.mul_sum,← Finset.mul_sum] + +lemma finite_center_at_mean {X : Type*} (s : Finset X) (w H : X → ℝ) + (hz : (∑ x ∈ s,w x) ≠ 0) : + (∑ x ∈ s, w x*(H x-(∑ y ∈ s,w y*H y)/(∑ y ∈ s,w y))^2) = + (∑ x ∈ s,w x*(H x)^2) - (∑ x ∈ s,w x*H x)^2/(∑ x ∈ s,w x) := by + rw [finite_center_sum] + field_simp + ; ring + +lemma finite_center_min {X : Type*} (s : Finset X) (w H : X → ℝ) (a : ℝ) + (hz : 0 < ∑ x ∈ s,w x) : + (∑ x ∈ s, w x*(H x-(∑ y ∈ s,w y*H y)/(∑ y ∈ s,w y))^2) ≤ + ∑ x ∈ s,w x*(H x-a)^2 := by + rw [finite_center_at_mean s w H (ne_of_gt hz),finite_center_sum] + have hsq : 0 ≤ ((∑ x ∈ s,w x*H x)-a*(∑ x ∈ s,w x))^2 := sq_nonneg _ + apply (mul_le_mul_iff_left₀ hz).mp + field_simp + nlinarith + +lemma plain_center_eq_variance (gs : List (Γ × Γ)) (hgs : SlotsFresh gs ∅) + (hcover : pairSupport gs = Set.univ) (f H : Set Γ → ℝ) (hf : ∀ S, 0 < f S) : + (∑ S ∈ Finset.univ.filter (PlainState gs), f S*(H S-plainMean gs f H)^2) = + slotVariance gs f H ∅ := by + have hz := slotTotal_pos gs f hf ∅ hgs + rw [slotTotal_eq_plain_sum gs hgs hcover] at hz + unfold plainMean + rw [slotTotal_eq_plain_sum gs hgs hcover,slotTotal_eq_plain_sum gs hgs hcover, + finite_center_at_mean _ _ _ (ne_of_gt hz),slotVariance_eq_plain_variance gs hgs hcover] + +lemma projection_center_decomposition (gs : List (Γ × Γ)) (hgs : SlotsFresh gs ∅) + (hcover : pairSupport gs = Set.univ) (w : (Γ × Γ) → (Γ × Γ) → ℝ) + (f H : Set Γ → ℝ) (hf : ∀ S, 0 < f S) : + (∑ S ∈ chainStates gs, chainWeight gs w f S* + (observableProjection gs f H S-plainMean gs f H)^2) = slotVariance gs f H ∅ + + ∑ pr ∈ defectTypes gs, w pr.1 pr.2*slotDefect gs f ∅ pr.1 pr.2* + (defectMean gs f H pr.1 pr.2-plainMean gs f H)^2 := by + simp only [chainWeight,mul_assoc] + rw [chain_sum_decomposition] + congr 1 + · rw [← plain_center_eq_variance gs hgs hcover f H hf] + apply Finset.sum_congr rfl + intro S hS + rw [observableProjection_plain gs f H S (Finset.mem_filter.mp hS).2] + · apply Finset.sum_congr rfl + intro pr hm + obtain ⟨hp,hr,hpr⟩ := (mem_defectTypes gs pr).mp hm + rw [slotDefect_eq_defect_sum gs hgs hcover f pr.1 pr.2 hp hr hpr,Finset.sum_mul] + congr 1 + apply Finset.sum_congr rfl + intro S hS + rw [observableProjection_defect gs f H S (Finset.mem_filter.mp hS).2] + +noncomputable def chainMean (gs : List (Γ × Γ)) (w : (Γ × Γ) → (Γ × Γ) → ℝ) + (f H : Set Γ → ℝ) : ℝ := + (∑ S ∈ chainStates gs,chainWeight gs w f S*H S)/chainTotal gs w f +noncomputable def chainVariance (gs : List (Γ × Γ)) (w : (Γ × Γ) → (Γ × Γ) → ℝ) + (f H : Set Γ → ℝ) : ℝ := + (∑ S ∈ chainStates gs,chainWeight gs w f S*(H S-chainMean gs w f H)^2)/chainTotal gs w f +noncomputable def chainDirichlet (gs : List (Γ × Γ)) (w : (Γ × Γ) → (Γ × Γ) → ℝ) + (f H : Set Γ → ℝ) : ℝ := + restrictedEnergy (chainEdges gs) (chainConductance gs w f) H ∅ ∅/ + (2*(gs.length:ℝ)^2*chainTotal gs w f) + +lemma projection_center_bound (gs : List (Γ × Γ)) (hgs : SlotsFresh gs ∅) + (hcover : pairSupport gs = Set.univ) (w : (Γ × Γ) → (Γ × Γ) → ℝ) + (hw : ∀ p r, 0 < w p r) (f H : Set Γ → ℝ) (hf : ∀ S, 0 < f S) + (hsig : HasSlotSignature f) + (hlower : ∀ p ∈ gs, ∀ r ∈ gs, p ≠ r → slotTotal gs f ∅/(4*slotDefect gs f ∅ p r) ≤ w p r) + (hupper : ∀ p ∈ gs, ∀ r ∈ gs, p ≠ r → w p r ≤ 4*slotTotal gs f ∅/slotDefect gs f ∅ p r) : + (∑ S ∈ chainStates gs, chainWeight gs w f S* + (observableProjection gs f H S-plainMean gs f H)^2) ≤ + ((gs.length:ℝ)*(1+8*(gs.length:ℝ))+4*((defectTypes gs).card:ℝ)*(8+32*(gs.length:ℝ)))* + restrictedEnergy (chainEdges gs) (chainConductance gs w f) H ∅ ∅ := by + rw [projection_center_decomposition gs hgs hcover w f H hf] + have hp := transversal_variance_bound gs f H w hf hsig hgs hw hlower + let D := restrictedEnergy (chainEdges gs) (chainConductance gs w f) H ∅ ∅ + have hd : ∀ pr ∈ defectTypes gs, + w pr.1 pr.2*slotDefect gs f ∅ pr.1 pr.2*(defectMean gs f H pr.1 pr.2-plainMean gs f H)^2 ≤ + 4*(8+32*(gs.length:ℝ))*D := by + intro pr hm + obtain ⟨hp,hr,hpr⟩ := (mem_defectTypes gs pr).mp hm + have hu := (le_div_iff₀ (slotDefect_pos gs f hf ∅ hgs pr.1 pr.2 hp hr hpr)).mp + (hupper pr.1 hp pr.2 hr hpr) + have ht := defect_mean_bound gs pr.1 pr.2 hgs hp hr hpr f H hf hsig w hw hlower + change slotTotal gs f ∅*(defectMean gs f H pr.1 pr.2-plainMean gs f H)^2 ≤ _ at ht + have hh := mul_le_mul_of_nonneg_right hu + (sq_nonneg (defectMean gs f H pr.1 pr.2-plainMean gs f H)) + dsimp only [D] + linarith + have hs := Finset.sum_le_sum (fun pr hpr => hd pr hpr) + simp only [Finset.sum_const,nsmul_eq_mul] at hs + dsimp only [D] at hs + nlinarith + +theorem observable_poincare (gs : List (Γ × Γ)) (hgs : SlotsFresh gs ∅) (hne : gs ≠ []) + (hcover : pairSupport gs = Set.univ) (w : (Γ × Γ) → (Γ × Γ) → ℝ) + (hw : ∀ p r, 0 < w p r) (f H : Set Γ → ℝ) (hf : ∀ S, 0 < f S) + (hsig : HasSlotSignature f) + (hlower : ∀ p ∈ gs, ∀ r ∈ gs, p ≠ r → slotTotal gs f ∅/(4*slotDefect gs f ∅ p r) ≤ w p r) + (hupper : ∀ p ∈ gs, ∀ r ∈ gs, p ≠ r → w p r ≤ 4*slotTotal gs f ∅/slotDefect gs f ∅ p r) : + chainVariance gs w f (observableProjection gs f H) ≤ + 2000*(gs.length:ℝ)^6*chainDirichlet gs w f H := by + have hΛ := chainTotal_pos gs hgs hcover w f hf hw + have hm := finite_center_min (chainStates gs) (chainWeight gs w f) + (observableProjection gs f H) (plainMean gs f H) hΛ + have hb := projection_center_bound gs hgs hcover w hw f H hf hsig hlower hupper + let n : ℝ := gs.length + let D := restrictedEnergy (chainEdges gs) (chainConductance gs w f) H ∅ ∅ + have hD : 0 ≤ D := restrictedEnergy_nonneg _ _ _ _ _ (by + intro ST _ + exact le_min (mul_nonneg (chainMultiplier_pos gs w hw _).le (hf _).le) + (mul_nonneg (chainMultiplier_pos gs w hw _).le (hf _).le)) + have hn : 1 ≤ n := by + dsimp only [n] + exact_mod_cast List.length_pos_iff.mpr hne + have hn0 : 0 < n := lt_of_lt_of_le zero_lt_one hn + have hcard : ((defectTypes gs).card:ℝ) ≤ n^2 := by + dsimp only [n] + exact_mod_cast (show (defectTypes gs).card ≤ gs.length^2 by simpa [pow_two] using defectTypes_card_le gs) + have hc : n*(1+8*n)+4*((defectTypes gs).card:ℝ)*(8+32*n) ≤ 1000*n^4 := by + have hn2 : n ≤ n^2 := by nlinarith + have hn3 : n^2 ≤ n^3 := by nlinarith [mul_le_mul_of_nonneg_left hn2 hn0.le] + have hn4 : n^3 ≤ n^4 := by nlinarith [mul_le_mul_of_nonneg_left hn3 hn0.le] + have hh := mul_le_mul_of_nonneg_right hcard (show 0 ≤ 4*(8+32*n) by positivity) + nlinarith + have hbound := (hm.trans hb).trans (mul_le_mul_of_nonneg_right hc hD) + change chainVariance gs w f (observableProjection gs f H) ≤ 2000*n^6*(D/(2*n^2*chainTotal gs w f)) + unfold chainVariance chainMean + apply (div_le_iff₀ hΛ).mpr + have he : 2000*n^6*(D/(2*n^2*chainTotal gs w f))*chainTotal gs w f = 1000*n^4*D := by + field_simp + ; ring + rw [he] + exact hbound + +end Observable + +section ChainGeometry +open scoped BigOperators Classical +variable {Γ : Type*} [sectionInstance54 : Fintype Γ] [sectionInstance55 : DecidableEq Γ] + +lemma pairSupport_ncard (ps : List (Γ × Γ)) (A : Set Γ) (hps : SlotsFresh ps A) : + (A ∪ pairSupport ps).ncard = A.ncard+2*ps.length := by + induction ps generalizing A with + | nil => simp + | cons p ps ih => + have he : A ∪ pairSupport (p::ps) = (insert p.1 (insert p.2 A)) ∪ pairSupport ps := by + rw [pairSupport_cons] + ext x + simp only [Set.mem_union,Set.mem_insert_iff] + tauto + rw [he,ih _ hps.2.2.2,Set.ncard_insert_of_notMem (by + simpa only [Set.mem_insert_iff,not_or] using And.intro hps.1 hps.2.1), + Set.ncard_insert_of_notMem hps.2.2.1,List.length_cons] + omega + +lemma slots_ground_card (gs : List (Γ × Γ)) (hgs : SlotsFresh gs ∅) + (hcover : pairSupport gs = Set.univ) : Fintype.card Γ = 2*gs.length := by + have h := pairSupport_ncard gs ∅ hgs + simpa [hcover,Set.ncard_univ,Nat.card_eq_fintype_card] using h + +lemma choiceVertices_ncard (ps : List (Γ × Γ)) (A S : Set Γ) (hps : SlotsFresh ps A) + (hS : S ∈ choiceVertices ps A) : S.ncard = A.ncard+ps.length := by + induction ps generalizing A with + | nil => + simp only [choiceVertices,Finset.mem_singleton] at hS + subst S + simp + | cons p ps ih => + rw [choiceVertices,Finset.mem_union] at hS + rcases hS with hS | hS + · have ht : SlotsFresh ps (insert p.1 A) := hps.2.2.2.mono (by + intro x hx + simp only [Set.mem_insert_iff] at hx ⊢ + tauto) + rw [ih _ ht hS,Set.ncard_insert_of_notMem hps.2.1,List.length_cons] + omega + · have ht : SlotsFresh ps (insert p.2 A) := hps.2.2.2.mono (Set.subset_insert _ _) + rw [ih _ ht hS,Set.ncard_insert_of_notMem hps.2.2.1,List.length_cons] + omega + +lemma PlainState.ncard {gs : List (Γ × Γ)} (hgs : SlotsFresh gs ∅) + (hcover : pairSupport gs = Set.univ) {S : Set Γ} (hS : PlainState gs S) : S.ncard = gs.length := by + have hm : S ∈ choiceVertices gs ∅ := by rw [choiceVertices_plain gs hgs hcover]; simp [hS] + simpa using choiceVertices_ncard gs ∅ S hgs hm + +lemma DefectState.ncard {gs : List (Γ × Γ)} (hgs : SlotsFresh gs ∅) + (hcover : pairSupport gs = Set.univ) {p r : Γ × Γ} {S : Set Γ} (hS : DefectState gs p r S) : + S.ncard = gs.length := by + let ps := (gs.erase p).erase r + have hperm : gs.Perm (p::r::ps) := slots_perm_two hS.1 hS.2.1 hS.2.2.1 + have hs := (SlotsFresh.perm hperm ∅).mp hgs + have ht : SlotsFresh ps {r.1,r.2} := hs.2.2.2.2.2.2.mono (by + intro x hx + simp only [Set.mem_insert_iff,Set.mem_singleton_iff,Set.mem_empty_iff_false,or_false] at hx ⊢ + tauto) + have hm : S ∈ choiceVertices ps {r.1,r.2} := by + rw [choiceVertices_defect gs hgs hcover p r hS.1 hS.2.1 hS.2.2.1] + simp [hS] + have hc := choiceVertices_ncard ps {r.1,r.2} S ht hm + have hpair : ({r.1,r.2} : Set Γ).ncard = 2 := Set.ncard_pair hs.2.2.2.1 + rw [hpair] at hc + have hl := hperm.length_eq + simp only [List.length_cons] at hl + omega + +lemma ChainState.ncard {gs : List (Γ × Γ)} (hgs : SlotsFresh gs ∅) + (hcover : pairSupport gs = Set.univ) {S : Set Γ} (hS : ChainState gs S) : S.ncard = gs.length := by + rcases hS with hS | ⟨p,r,hS⟩ + · exact hS.ncard hgs hcover + · exact hS.ncard hgs hcover + +omit sectionInstance54 sectionInstance55 in +lemma ExchangeAdjacent.symm [Fintype Γ] [DecidableEq Γ] {S T : Set Γ} (h : ExchangeAdjacent S T) : ExchangeAdjacent T S := by + obtain ⟨A,a,b,hab,ha,hb,hS,hT⟩ := h + exact ⟨A,b,a,hab.symm,hb,ha,hT,hS⟩ +omit sectionInstance54 sectionInstance55 in +lemma ExchangeAdjacent.ne [Fintype Γ] [DecidableEq Γ] {S T : Set Γ} (h : ExchangeAdjacent S T) : S ≠ T := by + obtain ⟨A,a,b,hab,ha,hb,rfl,rfl⟩ := h + intro he + have hh : a ∈ insert b A := he ▸ Set.mem_insert a A + exact (Set.mem_insert_iff.mp hh).elim hab ha + +omit sectionInstance54 sectionInstance55 in +lemma ExchangeAdjacent.move [Fintype Γ] [DecidableEq Γ] {S T : Set Γ} (h : ExchangeAdjacent S T) : + ∃ a ∈ S, ∃ b ∈ Sᶜ, T = insert b (S\{a}) := by + obtain ⟨A,a,b,hab,ha,hb,rfl,rfl⟩ := h + refine ⟨a,Set.mem_insert _ _,b,?_,?_⟩ + · simpa only [Set.mem_compl_iff,Set.mem_insert_iff,not_or] using And.intro hab.symm hb + · congr 1 + ext x + simp only [Set.mem_sdiff,Set.mem_insert_iff,Set.mem_singleton_iff] + constructor + · intro hx + exact ⟨Or.inr hx,fun he => ha (he ▸ hx)⟩ + · rintro ⟨hh,hn⟩ + exact hh.resolve_left hn + +lemma exchange_neighbors_card (S : Set Γ) : + (Finset.univ.filter (ExchangeAdjacent S)).card ≤ S.ncard*Sᶜ.ncard := by + have hsub : Finset.univ.filter (ExchangeAdjacent S) ⊆ + (S.toFinset ×ˢ Sᶜ.toFinset).image (fun ab => insert ab.2 (S\{ab.1})) := by + intro T hT + obtain ⟨a,ha,b,hb,rfl⟩ := (Finset.mem_filter.mp hT).2.move + exact Finset.mem_image.mpr ⟨(a,b),by simpa only [Finset.mem_product,Set.mem_toFinset] using And.intro ha hb,rfl⟩ + calc + _ ≤ ((S.toFinset ×ˢ Sᶜ.toFinset).image (fun ab => insert ab.2 (S\{ab.1}))).card := Finset.card_le_card hsub + _ ≤ (S.toFinset ×ˢ Sᶜ.toFinset).card := Finset.card_image_le + _ = _ := by rw [Finset.card_product,← Set.ncard_eq_toFinset_card',← Set.ncard_eq_toFinset_card'] + +abbrev ChainIndex (gs : List (Γ × Γ)) := {S : Set Γ // ChainState gs S} + +lemma chain_neighbors_card (gs : List (Γ × Γ)) (hgs : SlotsFresh gs ∅) + (hcover : pairSupport gs = Set.univ) (S : ChainIndex gs) : + (Finset.univ.filter (fun T : ChainIndex gs => ExchangeAdjacent S.val T.val)).card ≤ gs.length^2 := by + let e : ChainIndex gs → Set Γ := Subtype.val + have he : Function.Injective e := Subtype.val_injective + have hsub : (Finset.univ.filter (fun T : ChainIndex gs => ExchangeAdjacent S.val T.val)).image e ⊆ + Finset.univ.filter (ExchangeAdjacent S.val) := by + intro T hT + obtain ⟨U,hU,hUT⟩ := Finset.mem_image.mp hT + subst T + exact Finset.mem_filter.mpr ⟨Finset.mem_univ _,(Finset.mem_filter.mp hU).2⟩ + have hcompl : S.valᶜ.ncard = gs.length := by + have hc := S.val.ncard_add_ncard_compl + rw [Nat.card_eq_fintype_card,slots_ground_card gs hgs hcover,S.property.ncard hgs hcover] at hc + omega + calc + _ = ((Finset.univ.filter (fun T : ChainIndex gs => ExchangeAdjacent S.val T.val)).image e).card := + (Finset.card_image_of_injective _ he).symm + _ ≤ (Finset.univ.filter (ExchangeAdjacent S.val)).card := Finset.card_le_card hsub + _ ≤ S.val.ncard*S.valᶜ.ncard := exchange_neighbors_card _ + _ = gs.length^2 := by rw [S.property.ncard hgs hcover,hcompl,pow_two] + +end ChainGeometry + +open scoped BigOperators Classical + +structure FiniteChain (X : Type*) [Fintype X] where + P : X → X → ℝ + π : X → ℝ + positive : ∀ x, 0 < π x + normalized : ∑ x, π x = 1 + nonnegative : ∀ x y, 0 ≤ P x y + stochastic : ∀ x, ∑ y, P x y = 1 + reversible : ∀ x y, π x*P x y = π y*P y x + lazy : ∀ x, 1/2 ≤ P x x + +namespace FiniteChain +variable {X : Type*} [sectionInstance56 : Fintype X] (C : FiniteChain X) + +noncomputable def inner (f g : X → ℝ) : ℝ := ∑ x, C.π x*f x*g x +noncomputable def apply (f : X → ℝ) (x : X) : ℝ := ∑ y, C.P x y*f y +noncomputable def energy (f : X → ℝ) : ℝ := C.inner f (fun x => f x-C.apply f x) +noncomputable def iterate (k : ℕ) (f : X → ℝ) : X → ℝ := Nat.iterate C.apply k f + +lemma inner_symm (f g : X → ℝ) : C.inner f g = C.inner g f := by + unfold inner + apply Finset.sum_congr rfl + intro x _ + ring +lemma inner_add_right (f g h : X → ℝ) : C.inner f (fun x => g x+h x) = C.inner f g+C.inner f h := by + simp [inner,mul_add,Finset.sum_add_distrib] +lemma inner_sub_right (f g h : X → ℝ) : C.inner f (fun x => g x-h x) = C.inner f g-C.inner f h := by + simp [inner,mul_sub,Finset.sum_sub_distrib] +lemma inner_add_left (f g h : X → ℝ) : C.inner (fun x => f x+g x) h = C.inner f h+C.inner g h := by + rw [inner_symm,inner_add_right,inner_symm C h f,inner_symm C h g] +lemma inner_sum_right {J : Type*} (s : Finset J) (f : X → ℝ) (g : J → X → ℝ) : + C.inner f (fun x => ∑ j ∈ s,g j x) = ∑ j ∈ s,C.inner f (g j) := by + simp only [inner,Finset.mul_sum] + exact Finset.sum_comm +lemma inner_sum_left {J : Type*} (s : Finset J) (f : J → X → ℝ) (g : X → ℝ) : + C.inner (fun x => ∑ j ∈ s,f j x) g = ∑ j ∈ s,C.inner (f j) g := by + rw [inner_symm,inner_sum_right] + apply Finset.sum_congr rfl + intro j _ + exact C.inner_symm _ _ +lemma inner_nonneg (f : X → ℝ) : 0 ≤ C.inner f f := by + apply Finset.sum_nonneg + intro x _ + nlinarith [C.positive x,sq_nonneg (f x)] +lemma apply_add (f g : X → ℝ) : C.apply (fun x => f x+g x) = fun x => C.apply f x+C.apply g x := by + funext x + simp [apply,mul_add,Finset.sum_add_distrib] +lemma apply_sum {J : Type*} (s : Finset J) (f : J → X → ℝ) : + C.apply (fun x => ∑ j ∈ s,f j x) = fun x => ∑ j ∈ s,C.apply (f j) x := by + funext x + simp only [apply,Finset.mul_sum] + exact Finset.sum_comm +lemma apply_const (a : ℝ) : C.apply (fun _ => a) = fun _ => a := by + funext x + simp [apply,← Finset.sum_mul,C.stochastic] + +lemma stationary (y : X) : ∑ x, C.π x*C.P x y = C.π y := by + simp_rw [C.reversible] + rw [← Finset.mul_sum,C.stochastic,mul_one] +lemma apply_selfAdjoint (f g : X → ℝ) : C.inner f (C.apply g) = C.inner (C.apply f) g := by + unfold inner apply + simp only [Finset.mul_sum,Finset.sum_mul] + rw [Finset.sum_comm] + apply Finset.sum_congr rfl + intro y _ + apply Finset.sum_congr rfl + intro x _ + have h := C.reversible x y + calc + _ = (C.π x*C.P x y)*(f x*g y) := by ring + _ = (C.π y*C.P y x)*(f x*g y) := by rw [h] + _ = _ := by ring + +lemma energy_eq (f : X → ℝ) : C.energy f = + (∑ x, ∑ y, C.π x*C.P x y*(f x-f y)^2)/2 := by + have h₁ : (∑ x,∑ y,C.π x*C.P x y*(f x)^2) = C.inner f f := by + simp_rw [mul_assoc,← Finset.mul_sum,← Finset.sum_mul,C.stochastic,one_mul] + unfold inner + apply Finset.sum_congr rfl + intro x _ + ring + have h₂ : (∑ x,∑ y,C.π x*C.P x y*(f y)^2) = C.inner f f := by + rw [Finset.sum_comm] + simp_rw [← Finset.sum_mul,C.stationary] + unfold inner + apply Finset.sum_congr rfl + intro x _ + ring + have h₃ : (∑ x,∑ y,C.π x*C.P x y*(f x*f y)) = C.inner f (C.apply f) := by + unfold inner apply + simp only [Finset.mul_sum] + apply Finset.sum_congr rfl + intro x _ + apply Finset.sum_congr rfl + intro y _ + ring + have he (x y : X) : C.π x*C.P x y*(f x-f y)^2 = + C.π x*C.P x y*(f x)^2+C.π x*C.P x y*(f y)^2-2*(C.π x*C.P x y*(f x*f y)) := by ring + simp_rw [he,Finset.sum_sub_distrib,Finset.sum_add_distrib,← Finset.mul_sum] + rw [h₁,h₂,h₃,energy,inner_sub_right] + ring + +lemma energy_nonneg (f : X → ℝ) : 0 ≤ C.energy f := by + rw [C.energy_eq] + apply div_nonneg _ (by norm_num) + apply Finset.sum_nonneg + intro x _ + apply Finset.sum_nonneg + intro y _ + exact mul_nonneg (mul_nonneg (C.positive x).le (C.nonnegative x y)) (sq_nonneg _) + +lemma energy_le_inner (f : X → ℝ) : C.energy f ≤ C.inner f f := by + classical + have ho (x : X) : ∑ y ∈ Finset.univ.erase x,C.P x y ≤ 1/2 := by + have h := Finset.sum_erase_add Finset.univ (fun y => C.P x y) (Finset.mem_univ x) + rw [C.stochastic] at h + linarith [C.lazy x] + have hbound : (∑ x,∑ y,C.π x*C.P x y*(f x-f y)^2) ≤ + ∑ x,∑ y ∈ Finset.univ.erase x,2*(C.π x*C.P x y*(f x)^2+C.π x*C.P x y*(f y)^2) := by + apply Finset.sum_le_sum + intro x _ + rw [← Finset.sum_erase_add _ _ (Finset.mem_univ x)] + simp only [sub_self,zero_pow (by decide : 2 ≠ 0),mul_zero,add_zero] + apply Finset.sum_le_sum + intro y _ + have h := mul_le_mul_of_nonneg_left (show (f x-f y)^2 ≤ 2*((f x)^2+(f y)^2) by nlinarith [sq_nonneg (f x+f y)]) + (mul_nonneg (C.positive x).le (C.nonnegative x y)) + nlinarith + have hs (x : X) : (∑ y ∈ Finset.univ.erase x,C.π x*C.P x y*(f x)^2) ≤ (C.π x*(f x)^2)/2 := by + calc + _ = (C.π x*(f x)^2)*(∑ y ∈ Finset.univ.erase x,C.P x y) := by + rw [Finset.mul_sum] + apply Finset.sum_congr rfl + intro y _ + ring + _ ≤ _ := by nlinarith [mul_le_mul_of_nonneg_left (ho x) (mul_nonneg (C.positive x).le (sq_nonneg (f x)))] + have hswap : (∑ x,∑ y ∈ Finset.univ.erase x,C.π x*C.P x y*(f y)^2) = + ∑ x,∑ y ∈ Finset.univ.erase x,C.π x*C.P x y*(f x)^2 := by + simp only [Finset.sum_erase_eq_sub (Finset.mem_univ _)] + rw [Finset.sum_sub_distrib,Finset.sum_sub_distrib] + congr 1 + rw [Finset.sum_comm] + apply Finset.sum_congr rfl + intro x _ + apply Finset.sum_congr rfl + intro y _ + rw [C.reversible] + have hsum := Finset.sum_le_sum (fun x (_ : x ∈ Finset.univ) => hs x) + have heq : (∑ x,C.π x*(f x)^2/2) = C.inner f f/2 := by + rw [← Finset.sum_div] + congr 1 + unfold inner + apply Finset.sum_congr rfl + intro x _ + ring + rw [heq] at hsum + simp_rw [← Finset.mul_sum,Finset.sum_add_distrib] at hbound + rw [hswap] at hbound + rw [C.energy_eq] + linarith + +lemma apply_positive (f : X → ℝ) : 0 ≤ C.inner f (C.apply f) := by + have h := C.energy_le_inner f + rw [energy,inner_sub_right] at h + linarith + +@[simp] lemma iterate_zero (f : X → ℝ) : C.iterate 0 f = f := rfl +lemma iterate_succ (k : ℕ) (f : X → ℝ) : C.iterate (k+1) f = C.apply (C.iterate k f) := by + exact Function.iterate_succ_apply' C.apply k f +lemma iterate_add (k l : ℕ) (f : X → ℝ) : C.iterate (k+l) f = C.iterate k (C.iterate l f) := by + exact Function.iterate_add_apply C.apply k l f +lemma iterate_selfAdjoint (k : ℕ) (f g : X → ℝ) : C.inner f (C.iterate k g) = C.inner (C.iterate k f) g := by + induction k generalizing f g with + | zero => rfl + | succ k ih => + rw [C.iterate_succ,C.apply_selfAdjoint,ih] + change C.inner (C.iterate k (C.iterate 1 f)) g = _ + rw [← C.iterate_add] + +lemma covariance_nonneg (k : ℕ) (f : X → ℝ) : 0 ≤ C.inner f (C.iterate k f) := by + have hk : k = k/2+k/2 ∨ k = k/2+(k/2+1) := by + have := Nat.mod_add_div k 2 + have := Nat.mod_lt k (by decide : 0 < 2) + omega + rcases hk with hk | hk + · nth_rw 1 [hk] + rw [C.iterate_add,C.iterate_selfAdjoint] + exact C.inner_nonneg _ + · nth_rw 1 [hk] + rw [C.iterate_add,C.iterate_selfAdjoint,C.iterate_succ] + exact C.apply_positive _ + +noncomputable def partialResolvent (N : ℕ) (f : X → ℝ) (x : X) : ℝ := + ∑ k ∈ Finset.range N,C.iterate k f x +lemma partialResolvent_zero (f : X → ℝ) : C.partialResolvent 0 f = fun _ => 0 := by + funext x + simp [partialResolvent] +lemma partialResolvent_succ (N : ℕ) (f : X → ℝ) : + C.partialResolvent (N+1) f = fun x => C.partialResolvent N f x+C.iterate N f x := by + funext x + exact Finset.sum_range_succ _ _ + +lemma partialResolvent_residual (N : ℕ) (f : X → ℝ) : + (fun x => C.partialResolvent N f x-C.apply (C.partialResolvent N f) x) = + fun x => f x-C.iterate N f x := by + induction N with + | zero => rw [C.partialResolvent_zero,C.apply_const]; simp + | succ N ih => + rw [C.partialResolvent_succ,C.apply_add,C.iterate_succ] + funext x + have hh := congrFun ih x + dsimp only at hh ⊢ + linarith + +lemma partialResolvent_inner (N : ℕ) (f : X → ℝ) : + C.inner f (C.partialResolvent N f) = ∑ k ∈ Finset.range N,C.inner f (C.iterate k f) := by + exact C.inner_sum_right _ _ _ + +lemma partialResolvent_energy_le (N : ℕ) (f : X → ℝ) : + C.energy (C.partialResolvent N f) ≤ C.inner f (C.partialResolvent N f) := by + rw [energy,C.partialResolvent_residual,C.inner_sub_right,C.inner_symm (C.partialResolvent N f) f] + have hh : 0 ≤ C.inner (C.partialResolvent N f) (C.iterate N f) := by + change 0 ≤ C.inner (fun x => ∑ k ∈ Finset.range N,C.iterate k f x) (C.iterate N f) + rw [C.inner_sum_left] + apply Finset.sum_nonneg + intro k _ + rw [← C.iterate_selfAdjoint,← C.iterate_add] + exact C.covariance_nonneg _ f + linarith + +theorem covariance_sum_bound (g : X → ℝ) (K : ℝ) (hK : 0 ≤ K) + (hdual : ∀ H, (C.inner g H)^2 ≤ K*C.inner g g*C.energy H) (N : ℕ) : + (∑ k ∈ Finset.range N,C.inner g (C.iterate k g)) ≤ K*C.inner g g := by + rw [← C.partialResolvent_inner] + have h := hdual (C.partialResolvent N g) + have he := C.partialResolvent_energy_le N g + have hnon : 0 ≤ K*C.inner g g := mul_nonneg hK (C.inner_nonneg g) + have hb := mul_le_mul_of_nonneg_left he hnon + nlinarith + +noncomputable def pathExpectation : ℕ → X → (List X → ℝ) → ℝ + | 0,x,F => F [x] + | N+1,x,F => ∑ y,C.P x y*pathExpectation N y (fun l => F (x::l)) + +lemma pathExpectation_nonneg (N : ℕ) (x : X) (F : List X → ℝ) (hF : ∀ l,0 ≤ F l) : + 0 ≤ C.pathExpectation N x F := by + induction N generalizing x F with + | zero => exact hF _ + | succ N ih => + apply Finset.sum_nonneg + intro y _ + exact mul_nonneg (C.nonnegative x y) (ih y _ (fun l => hF _)) +lemma pathExpectation_add (N : ℕ) (x : X) (F G : List X → ℝ) : + C.pathExpectation N x (fun l => F l+G l) = C.pathExpectation N x F+C.pathExpectation N x G := by + induction N generalizing x F G with + | zero => rfl + | succ N ih => simp [pathExpectation,ih,mul_add,Finset.sum_add_distrib] +lemma pathExpectation_mul (N : ℕ) (x : X) (a : ℝ) (F : List X → ℝ) : + C.pathExpectation N x (fun l => a*F l) = a*C.pathExpectation N x F := by + induction N generalizing x F with + | zero => rfl + | succ N ih => simp [pathExpectation,ih,Finset.mul_sum,mul_left_comm] +lemma pathExpectation_const (N : ℕ) (x : X) (a : ℝ) : C.pathExpectation N x (fun _ => a) = a := by + induction N generalizing x with + | zero => rfl + | succ N ih => simp [pathExpectation,ih,← Finset.sum_mul,C.stochastic] +lemma pathExpectation_congr (N : ℕ) (x : X) (F G : List X → ℝ) (hFG : ∀ l,F l=G l) : + C.pathExpectation N x F = C.pathExpectation N x G := by + congr 1 + funext l + exact hFG l + +noncomputable def pathSum (g : X → ℝ) (l : List X) : ℝ := (l.map g).sum +noncomputable def squareMoment (g : X → ℝ) (N : ℕ) (x : X) : ℝ := + if N=0 then 0 else C.pathExpectation (N-1) x (fun l => (pathSum g l)^2) + +omit sectionInstance56 in +lemma pathSum_cons [Fintype X] (g : X → ℝ) (x : X) (l : List X) : pathSum g (x::l) = g x+pathSum g l := rfl +lemma pathExpectation_sum (g : X → ℝ) (N : ℕ) (x : X) : + C.pathExpectation N x (pathSum g) = C.partialResolvent (N+1) g x := by + induction N generalizing x with + | zero => simp [pathExpectation,pathSum,partialResolvent] + | succ N ih => + have hc (y : X) : C.pathExpectation N y (fun l => pathSum g (x::l)) = + g x+C.partialResolvent (N+1) g y := by + simp only [pathSum_cons] + rw [C.pathExpectation_add,C.pathExpectation_const,ih] + simp only [pathExpectation,hc,mul_add,Finset.sum_add_distrib,← Finset.sum_mul,C.stochastic,one_mul] + have hh := congrFun (C.partialResolvent_residual (N+1) g) x + change g x+C.apply (C.partialResolvent (N+1) g) x = _ + rw [C.partialResolvent_succ (N+1)] + dsimp only at hh ⊢ + linarith + +lemma squareMoment_zero (g : X → ℝ) (x : X) : C.squareMoment g 0 x = 0 := rfl +lemma squareMoment_succ (g : X → ℝ) (N : ℕ) (x : X) : + C.squareMoment g (N+1) x = (g x)^2 + + 2*g x*C.apply (C.partialResolvent N g) x+C.apply (C.squareMoment g N) x := by + cases N with + | zero => simp [squareMoment,pathExpectation,pathSum,partialResolvent,apply] + | succ N => + simp only [squareMoment,Nat.succ_ne_zero,ite_false, + Nat.add_sub_cancel,pathExpectation] + have he (y : X) : C.pathExpectation N y (fun l => (pathSum g (x::l))^2) = + (g x)^2+2*g x*C.partialResolvent (N+1) g y+ + C.pathExpectation N y (fun l => (pathSum g l)^2) := by + calc + _ = C.pathExpectation N y (fun l => (g x)^2+2*g x*pathSum g l+(pathSum g l)^2) := by + apply C.pathExpectation_congr + intro l + rw [pathSum_cons] + ring + _ = _ := by rw [C.pathExpectation_add,C.pathExpectation_add,C.pathExpectation_const, + C.pathExpectation_mul,C.pathExpectation_sum] + simp only [he,mul_add,Finset.sum_add_distrib,← Finset.sum_mul,C.stochastic,one_mul] + unfold apply + congr 1 + rw [Finset.mul_sum] + congr 1 + apply Finset.sum_congr rfl + intro y _ + ring + +lemma squareMoment_nonneg (g : X → ℝ) (N : ℕ) (x : X) : 0 ≤ C.squareMoment g N x := by + unfold squareMoment + split_ifs + · exact le_rfl + · exact C.pathExpectation_nonneg _ x _ (fun l => sq_nonneg _) + +lemma stationary_apply (f : X → ℝ) : ∑ x,C.π x*C.apply f x = ∑ x,C.π x*f x := by + unfold apply + simp only [Finset.mul_sum] + rw [Finset.sum_comm] + apply Finset.sum_congr rfl + intro y _ + simp_rw [← mul_assoc,← Finset.sum_mul,C.stationary] + +lemma stationary_squareMoment_succ (g : X → ℝ) (N : ℕ) : + (∑ x,C.π x*C.squareMoment g (N+1) x) = (∑ x,C.π x*C.squareMoment g N x)+ + C.inner g g+2*∑ k ∈ Finset.range N,C.inner g (C.iterate (k+1) g) := by + simp_rw [C.squareMoment_succ,mul_add,Finset.sum_add_distrib] + rw [C.stationary_apply] + have h₁ : (∑ x,C.π x*(g x)^2) = C.inner g g := by + unfold inner + apply Finset.sum_congr rfl + intro x _ + ring + have h₂ : (∑ x,C.π x*(2*g x*C.apply (C.partialResolvent N g) x)) = + 2*C.inner g (C.apply (C.partialResolvent N g)) := by + unfold inner + rw [Finset.mul_sum] + apply Finset.sum_congr rfl + intro x _ + ring + rw [h₁,h₂] + have hh : C.apply (C.partialResolvent N g) = fun x => ∑ k ∈ Finset.range N,C.iterate (k+1) g x := by + change C.apply (fun x => ∑ k ∈ Finset.range N,C.iterate k g x) = _ + rw [C.apply_sum] + simp_rw [C.iterate_succ] + rw [hh,C.inner_sum_right] + ring + +theorem stationary_squareMoment_bound (g : X → ℝ) (K : ℝ) (hK : 0 ≤ K) + (hdual : ∀ H, (C.inner g H)^2 ≤ K*C.inner g g*C.energy H) (N : ℕ) : + (∑ x,C.π x*C.squareMoment g N x) ≤ 2*N*K*C.inner g g := by + induction N with + | zero => simp [squareMoment] + | succ N ih => + rw [C.stationary_squareMoment_succ] + have hc := C.covariance_sum_bound g K hK hdual (N+1) + have hh : (∑ k ∈ Finset.range (N+1),C.inner g (C.iterate k g)) = C.inner g g+ + ∑ k ∈ Finset.range N,C.inner g (C.iterate (k+1) g) := by + rw [Finset.sum_range_succ'] + simp [add_comm] + rw [hh] at hc + have hg := C.inner_nonneg g + push_cast + nlinarith + +theorem warm_squareMoment_bound (g : X → ℝ) (K U : ℝ) (hK : 0 ≤ K) (hU : 0 ≤ U) + (hdual : ∀ H, (C.inner g H)^2 ≤ K*C.inner g g*C.energy H) + (ν : X → ℝ) (hwarm : ∀ x,ν x ≤ U*C.π x) (N : ℕ) (hN : 0 < N) : + (∑ x,ν x*C.squareMoment g N x)/(N:ℝ)^2 ≤ 2*U*K*C.inner g g/N := by + have hs : (∑ x,ν x*C.squareMoment g N x) ≤ U*∑ x,C.π x*C.squareMoment g N x := by + rw [Finset.mul_sum] + apply Finset.sum_le_sum + intro x _ + simpa only [mul_assoc] using mul_le_mul_of_nonneg_right (hwarm x) (C.squareMoment_nonneg g N x) + have hb := mul_le_mul_of_nonneg_left (C.stationary_squareMoment_bound g K hK hdual N) hU + have hn : (0:ℝ) < N := by exact_mod_cast hN + apply (div_le_iff₀ (sq_pos_of_pos hn)).mpr + have he : 2*U*K*C.inner g g/(N:ℝ)*(N:ℝ)^2 = U*(2*(N:ℝ)*K*C.inner g g) := by + field_simp + + rw [he] + exact hs.trans hb + +variable [DecidableEq X] + +noncomputable def ofMoves (π : X → ℝ) (m : X → X → ℝ) + (hπ : ∀ x,0 < π x) (hπsum : ∑ x,π x = 1) + (hm : ∀ x y,0 ≤ m x y) (hrow : ∀ x,∑ y,m x y ≤ 1/2) + (hrev : ∀ x y,π x*m x y = π y*m y x) : FiniteChain X where + P x y := m x y+if x=y then 1-∑ z,m x z else 0 + π := π + positive := hπ + normalized := hπsum + nonnegative x y := by + split_ifs + · linarith [hm x y,hrow x] + · simpa using hm x y + stochastic x := by simp [Finset.sum_add_distrib] + reversible x y := by + by_cases h : x=y + · subst y; rfl + · simp [h,Ne.symm h,hrev] + lazy x := by simp only [ite_true]; linarith [hm x x,hrow x] + +lemma ofMoves_energy (π : X → ℝ) (m : X → X → ℝ) + (hπ : ∀ x,0 < π x) (hπsum : ∑ x,π x = 1) + (hm : ∀ x y,0 ≤ m x y) (hrow : ∀ x,∑ y,m x y ≤ 1/2) + (hrev : ∀ x y,π x*m x y = π y*m y x) (f : X → ℝ) : + (ofMoves π m hπ hπsum hm hrow hrev).energy f = + (∑ x,∑ y,π x*m x y*(f x-f y)^2)/2 := by + rw [energy_eq] + congr 1 + apply Finset.sum_congr rfl + intro x _ + apply Finset.sum_congr rfl + intro y _ + change π x*(m x y+if x=y then _ else _)*(f x-f y)^2 = _ + by_cases h : x=y + · subst y; simp + · simp [h] + +end FiniteChain +section Metropolis +open scoped BigOperators Classical +variable {Γ : Type*} [Fintype Γ] [sectionInstance59 : DecidableEq Γ] + +lemma chainWeight_pos (gs : List (Γ × Γ)) (w : (Γ × Γ) → (Γ × Γ) → ℝ) + (f : Set Γ → ℝ) (hw : ∀ p r,0 < w p r) (hf : ∀ S,0 < f S) (S : Set Γ) : + 0 < chainWeight gs w f S := mul_pos (chainMultiplier_pos gs w hw S) (hf S) + +omit sectionInstance59 in +lemma chain_sum_subtype [DecidableEq Γ] (gs : List (Γ × Γ)) (g : Set Γ → ℝ) : + (∑ S ∈ chainStates gs,g S) = ∑ S : ChainIndex gs,g S.val := by + exact Finset.sum_subtype _ (by intro S; simp [chainStates]) g + +noncomputable def metropolisMove (gs : List (Γ × Γ)) + (w : (Γ × Γ) → (Γ × Γ) → ℝ) (f : Set Γ → ℝ) (S T : ChainIndex gs) : ℝ := + if ExchangeAdjacent S.val T.val then + min (chainWeight gs w f S.val) (chainWeight gs w f T.val)/ + (2*(gs.length:ℝ)^2*chainWeight gs w f S.val) else 0 + +lemma metropolisMove_nonneg (gs : List (Γ × Γ)) + (w : (Γ × Γ) → (Γ × Γ) → ℝ) (f : Set Γ → ℝ) + (hw : ∀ p r,0 < w p r) (hf : ∀ S,0 < f S) (S T : ChainIndex gs) : + 0 ≤ metropolisMove gs w f S T := by + have hS := chainWeight_pos gs w f hw hf S.val + unfold metropolisMove + split_ifs + · exact div_nonneg (le_min (chainWeight_pos gs w f hw hf _).le (chainWeight_pos gs w f hw hf _).le) + (by positivity) + · rfl + +lemma metropolisMove_row (gs : List (Γ × Γ)) (hgs : SlotsFresh gs ∅) (hne : gs ≠ []) + (hcover : pairSupport gs = Set.univ) (w : (Γ × Γ) → (Γ × Γ) → ℝ) + (f : Set Γ → ℝ) (hw : ∀ p r,0 < w p r) (hf : ∀ S,0 < f S) (S : ChainIndex gs) : + ∑ T,metropolisMove gs w f S T ≤ 1/2 := by + have hS := chainWeight_pos gs w f hw hf S.val + have hn : (0:ℝ) < gs.length := by exact_mod_cast List.length_pos_iff.mpr hne + have hinc (T : ChainIndex gs) : metropolisMove gs w f S T ≤ + if ExchangeAdjacent S.val T.val then 1/(2*(gs.length:ℝ)^2) else 0 := by + unfold metropolisMove + split_ifs + · apply (div_le_iff₀ (by positivity : 0 < 2*(gs.length:ℝ)^2*chainWeight gs w f S.val)).mpr + have he : 1/(2*(gs.length:ℝ)^2)*(2*(gs.length:ℝ)^2*chainWeight gs w f S.val) = chainWeight gs w f S.val := by + field_simp + rw [he] + exact min_le_left _ _ + · rfl + have hs := Finset.sum_le_sum (fun T (_ : T ∈ Finset.univ) => hinc T) + have hc : ((Finset.univ.filter (fun T : ChainIndex gs => ExchangeAdjacent S.val T.val)).card:ℝ) ≤ (gs.length:ℝ)^2 := by + exact_mod_cast chain_neighbors_card gs hgs hcover S + have he : (gs.length:ℝ)^2*(1/(2*(gs.length:ℝ)^2)) = 1/2 := by field_simp + calc + _ ≤ _ := hs + _ = ((Finset.univ.filter (fun T : ChainIndex gs => ExchangeAdjacent S.val T.val)).card:ℝ)*(1/(2*(gs.length:ℝ)^2)) := by + rw [← Finset.sum_filter]; simp + _ ≤ (gs.length:ℝ)^2*(1/(2*(gs.length:ℝ)^2)) := mul_le_mul_of_nonneg_right hc (by positivity) + _ = _ := he + +lemma metropolisMove_balanced (gs : List (Γ × Γ)) (w : (Γ × Γ) → (Γ × Γ) → ℝ) + (f : Set Γ → ℝ) (hw : ∀ p r,0 < w p r) (hf : ∀ S,0 < f S) (S T : ChainIndex gs) : + (chainWeight gs w f S.val/chainTotal gs w f)*metropolisMove gs w f S T = + (chainWeight gs w f T.val/chainTotal gs w f)*metropolisMove gs w f T S := by + have hs := (chainWeight_pos gs w f hw hf S.val).ne' + have ht := (chainWeight_pos gs w f hw hf T.val).ne' + by_cases h : ExchangeAdjacent S.val T.val + · simp only [metropolisMove,ite_eq_left h,ite_eq_left h.symm] + rw [min_comm (chainWeight gs w f T.val)] + field_simp + · have hh : ¬ ExchangeAdjacent T.val S.val := fun hh => h hh.symm + simp [metropolisMove,h,hh] + +noncomputable def metropolisChain (gs : List (Γ × Γ)) (hgs : SlotsFresh gs ∅) (hne : gs ≠ []) + (hcover : pairSupport gs = Set.univ) (w : (Γ × Γ) → (Γ × Γ) → ℝ) + (f : Set Γ → ℝ) (hw : ∀ p r,0 < w p r) (hf : ∀ S,0 < f S) : FiniteChain (ChainIndex gs) := + FiniteChain.ofMoves (fun S => chainWeight gs w f S.val/chainTotal gs w f) (metropolisMove gs w f) + (fun S => div_pos (chainWeight_pos gs w f hw hf S.val) (chainTotal_pos gs hgs hcover w f hf hw)) + (by rw [← Finset.sum_div,← chain_sum_subtype]; exact div_self (chainTotal_pos gs hgs hcover w f hf hw).ne') + (metropolisMove_nonneg gs w f hw hf) + (metropolisMove_row gs hgs hne hcover w f hw hf) + (metropolisMove_balanced gs w f hw hf) + +lemma chainEdges_sum (gs : List (Γ × Γ)) (g : (Set Γ × Set Γ) → ℝ) : + (∑ ST ∈ chainEdges gs,g ST) = + ∑ S : ChainIndex gs,∑ T : ChainIndex gs, + if ExchangeAdjacent S.val T.val then g (S.val,T.val) else 0 := by + calc + _ = ∑ S ∈ chainStates gs,∑ T ∈ chainStates gs, + if ExchangeAdjacent S T then g (S,T) else 0 := by + simp only [chainEdges,chainStates,Finset.sum_filter,Fintype.sum_prod_type] + apply Finset.sum_congr rfl + intro S _ + by_cases hs : ChainState gs S + · simp only [hs,true_and,ite_true] + apply Finset.sum_congr rfl + intro T _ + by_cases ht : ChainState gs T <;> simp [ht] + · simp [hs] + _ = _ := by + rw [chain_sum_subtype] + apply Finset.sum_congr rfl + intro S _ + exact chain_sum_subtype gs _ + +lemma restrictedEnergy_chain_eq (gs : List (Γ × Γ)) + (w : (Γ × Γ) → (Γ × Γ) → ℝ) (f H : Set Γ → ℝ) : + restrictedEnergy (chainEdges gs) (chainConductance gs w f) H ∅ ∅ = + (∑ S : ChainIndex gs, ∑ T : ChainIndex gs, + if ExchangeAdjacent S.val T.val then + min (chainWeight gs w f S.val) (chainWeight gs w f T.val)*(H S.val-H T.val)^2 else 0)/2 := by + unfold restrictedEnergy + simp only [EdgeRespects,Respects,Set.empty_subset,Set.empty_disjoint,and_self,ite_true] + rw [chainEdges_sum] + rfl + +theorem metropolisChain_energy (gs : List (Γ × Γ)) (hgs : SlotsFresh gs ∅) (hne : gs ≠ []) + (hcover : pairSupport gs = Set.univ) (w : (Γ × Γ) → (Γ × Γ) → ℝ) + (f H : Set Γ → ℝ) (hw : ∀ p r,0 < w p r) (hf : ∀ S,0 < f S) : + (metropolisChain gs hgs hne hcover w f hw hf).energy (fun S => H S.val) = chainDirichlet gs w f H := by + unfold metropolisChain + rw [FiniteChain.ofMoves_energy] + have he (S T : ChainIndex gs) : + (chainWeight gs w f S.val/chainTotal gs w f)*metropolisMove gs w f S T*(H S.val-H T.val)^2 = + (if ExchangeAdjacent S.val T.val then + min (chainWeight gs w f S.val) (chainWeight gs w f T.val)*(H S.val-H T.val)^2 else 0)/ + (2*(gs.length:ℝ)^2*chainTotal gs w f) := by + have hs := (chainWeight_pos gs w f hw hf S.val).ne' + unfold metropolisMove + split_ifs + · field_simp + · simp + simp_rw [he,← Finset.sum_div] + rw [chainDirichlet,restrictedEnergy_chain_eq] + ring + +end Metropolis + +namespace FiniteChain +variable {X : Type*} [Fintype X] (C : FiniteChain X) + +lemma inner_cauchy (f g : X → ℝ) : (C.inner f g)^2 ≤ C.inner f f*C.inner g g := by + have he (f g : X → ℝ) : (∑ x,(Real.sqrt (C.π x)*f x)*(Real.sqrt (C.π x)*g x)) = C.inner f g := by + unfold inner + apply Finset.sum_congr rfl + intro x _ + have hs := Real.sq_sqrt (C.positive x).le + calc + _ = (Real.sqrt (C.π x))^2*f x*g x := by ring + _ = _ := by rw [hs] + have hf (f : X → ℝ) : (∑ x,(Real.sqrt (C.π x)*f x)^2) = C.inner f f := by + simpa only [pow_two] using he f f + have h := Finset.sum_mul_sq_le_sq_mul_sq Finset.univ + (fun x => Real.sqrt (C.π x)*f x) (fun x => Real.sqrt (C.π x)*g x) + rwa [he,hf,hf] at h + +noncomputable def mean (f : X → ℝ) : ℝ := ∑ x,C.π x*f x +noncomputable def variance (f : X → ℝ) : ℝ := C.inner (fun x => f x-C.mean f) (fun x => f x-C.mean f) + +lemma centered_mean (f : X → ℝ) : C.mean (fun x => f x-C.mean f) = 0 := by + unfold mean + simp [mul_sub,Finset.sum_sub_distrib,← Finset.sum_mul,C.normalized] + +lemma inner_center_right (f g : X → ℝ) (hf : C.mean f = 0) (a : ℝ) : + C.inner f (fun x => g x-a) = C.inner f g := by + rw [C.inner_sub_right] + have hz : C.inner f (fun _ => a) = 0 := by + change (∑ x,C.π x*f x*a) = 0 + rw [← Finset.sum_mul] + change C.mean f*a = 0 + rw [hf,zero_mul] + rw [hz,sub_zero] + +end FiniteChain +section ProjectionBridge +open scoped BigOperators Classical +variable {Γ : Type*} [sectionInstance61 : Fintype Γ] [sectionInstance62 : DecidableEq Γ] + +def ClassObservable (gs : List (Γ × Γ)) (G : Set Γ → ℝ) : Prop := + ∀ p r S T, DefectState gs p r S → DefectState gs p r T → G S = G T + +lemma projection_classObservable (gs : List (Γ × Γ)) (f G : Set Γ → ℝ) : + ClassObservable gs (observableProjection gs f G) := by + intro p r S T hS hT + rw [observableProjection_defect gs f G S hS,observableProjection_defect gs f G T hT] + +omit sectionInstance61 sectionInstance62 in +lemma ClassObservable.sub_const [Fintype Γ] [DecidableEq Γ] {gs : List (Γ × Γ)} {G : Set Γ → ℝ} + (hG : ClassObservable gs G) (a : ℝ) : ClassObservable gs (fun S => G S-a) := by + intro p r S T hS hT + dsimp only + rw [hG p r S T hS hT] + +lemma defect_pairing_projection (gs : List (Γ × Γ)) (hgs : SlotsFresh gs ∅) + (hcover : pairSupport gs = Set.univ) (f G H : Set Γ → ℝ) + (hf : ∀ S,0 < f S) (hG : ClassObservable gs G) + (p r : Γ × Γ) (hp : p ∈ gs) (hr : r ∈ gs) (hpr : p ≠ r) : + (∑ S ∈ Finset.univ.filter (DefectState gs p r), f S*G S*H S) = + ∑ S ∈ Finset.univ.filter (DefectState gs p r), f S*G S*observableProjection gs f H S := by + let t := Finset.univ.filter (DefectState gs p r) + have hz := slotDefect_pos gs f hf ∅ hgs p r hp hr hpr + rw [slotDefect_eq_defect_sum gs hgs hcover f p r hp hr hpr] at hz + have ht : t.Nonempty := by + by_contra h + have he : t = ∅ := Finset.not_nonempty_iff_eq_empty.mp h + change 0 < ∑ S ∈ t,f S at hz + rw [he,Finset.sum_empty] at hz + exact lt_irrefl _ hz + obtain ⟨T,hT⟩ := ht + have hTp : DefectState gs p r T := (Finset.mem_filter.mp hT).2 + have hc (S : Set Γ) (hS : S ∈ t) : G S = G T := + hG p r S T (Finset.mem_filter.mp hS).2 hTp + change (∑ S ∈ t,f S*G S*H S) = ∑ S ∈ t,f S*G S*observableProjection gs f H S + calc + _ = G T*(∑ S ∈ t,f S*H S) := by + rw [Finset.mul_sum] + apply Finset.sum_congr rfl + intro S hS + rw [hc S hS]; ring + _ = G T*((∑ S ∈ t,f S)*defectMean gs f H p r) := by + congr 1 + unfold defectMean + rw [slotDefect_eq_defect_sum gs hgs hcover f p r hp hr hpr, + slotDefect_eq_defect_sum gs hgs hcover (fun S => f S*H S) p r hp hr hpr] + change _ = (∑ S ∈ t,f S)*((∑ S ∈ t,f S*H S)/(∑ S ∈ t,f S)) + have hzt : (∑ S ∈ t,f S) ≠ 0 := hz.ne' + field_simp [hzt] + _ = _ := by + rw [Finset.sum_mul,Finset.mul_sum] + apply Finset.sum_congr rfl + intro S hS + rw [hc S hS,observableProjection_defect gs f H S (Finset.mem_filter.mp hS).2] + ring + +lemma chain_pairing_projection (gs : List (Γ × Γ)) (hgs : SlotsFresh gs ∅) + (hcover : pairSupport gs = Set.univ) (w : (Γ × Γ) → (Γ × Γ) → ℝ) + (f G H : Set Γ → ℝ) (hf : ∀ S,0 < f S) (hG : ClassObservable gs G) : + (∑ S ∈ chainStates gs,chainWeight gs w f S*G S*H S) = + ∑ S ∈ chainStates gs,chainWeight gs w f S*G S*observableProjection gs f H S := by + simp only [chainWeight,mul_assoc] + rw [chain_sum_decomposition,chain_sum_decomposition] + congr 1 + · apply Finset.sum_congr rfl + intro S hS + rw [observableProjection_plain gs f H S (Finset.mem_filter.mp hS).2] + · apply Finset.sum_congr rfl + intro pr hpr + obtain ⟨hp,hr,hpr⟩ := (mem_defectTypes gs pr).mp hpr + congr 1 + simpa only [mul_assoc] using defect_pairing_projection gs hgs hcover f G H hf hG pr.1 pr.2 hp hr hpr + +noncomputable def extendChainFun (gs : List (Γ × Γ)) (H : ChainIndex gs → ℝ) (S : Set Γ) : ℝ := + if h : ChainState gs S then H ⟨S,h⟩ else 0 +omit sectionInstance61 sectionInstance62 in +lemma extendChainFun_apply [Fintype Γ] [DecidableEq Γ] (gs : List (Γ × Γ)) (H : ChainIndex gs → ℝ) (S : ChainIndex gs) : + extendChainFun gs H S.val = H S := by simp [extendChainFun,S.property] + +end ProjectionBridge + +section ObservableMSE +open scoped BigOperators Classical +variable {Γ : Type*} [Fintype Γ] [DecidableEq Γ] + +lemma metropolisChain_inner (gs : List (Γ × Γ)) (hgs : SlotsFresh gs ∅) (hne : gs ≠ []) + (hcover : pairSupport gs = Set.univ) (w : (Γ × Γ) → (Γ × Γ) → ℝ) + (f G H : Set Γ → ℝ) (hw : ∀ p r,0 < w p r) (hf : ∀ S,0 < f S) : + (metropolisChain gs hgs hne hcover w f hw hf).inner (fun S => G S.val) (fun S => H S.val) = + (∑ S ∈ chainStates gs,chainWeight gs w f S*G S*H S)/chainTotal gs w f := by + change (∑ S : ChainIndex gs,(chainWeight gs w f S.val/chainTotal gs w f)*G S.val*H S.val) = _ + simp_rw [div_mul_eq_mul_div] + rw [← Finset.sum_div,chain_sum_subtype] + +lemma metropolisChain_mean (gs : List (Γ × Γ)) (hgs : SlotsFresh gs ∅) (hne : gs ≠ []) + (hcover : pairSupport gs = Set.univ) (w : (Γ × Γ) → (Γ × Γ) → ℝ) + (f G : Set Γ → ℝ) (hw : ∀ p r,0 < w p r) (hf : ∀ S,0 < f S) : + (metropolisChain gs hgs hne hcover w f hw hf).mean (fun S => G S.val) = chainMean gs w f G := by + change (∑ S : ChainIndex gs,(chainWeight gs w f S.val/chainTotal gs w f)*G S.val) = _ + simp_rw [div_mul_eq_mul_div] + unfold chainMean + rw [← Finset.sum_div,chain_sum_subtype] + +lemma metropolisChain_variance (gs : List (Γ × Γ)) (hgs : SlotsFresh gs ∅) (hne : gs ≠ []) + (hcover : pairSupport gs = Set.univ) (w : (Γ × Γ) → (Γ × Γ) → ℝ) + (f G : Set Γ → ℝ) (hw : ∀ p r,0 < w p r) (hf : ∀ S,0 < f S) : + (metropolisChain gs hgs hne hcover w f hw hf).variance (fun S => G S.val) = chainVariance gs w f G := by + rw [FiniteChain.variance,metropolisChain_mean] + rw [metropolisChain_inner gs hgs hne hcover w f (fun S => G S-chainMean gs w f G) (fun S => G S-chainMean gs w f G) hw hf] + unfold chainVariance + congr 1 + apply Finset.sum_congr rfl + intro S _ + ring + +theorem metropolisChain_dual (gs : List (Γ × Γ)) (hgs : SlotsFresh gs ∅) (hne : gs ≠ []) + (hcover : pairSupport gs = Set.univ) (w : (Γ × Γ) → (Γ × Γ) → ℝ) + (f G : Set Γ → ℝ) (hw : ∀ p r,0 < w p r) (hf : ∀ S,0 < f S) + (hsig : HasSlotSignature f) (hG : ClassObservable gs G) + (hlower : ∀ p ∈ gs, ∀ r ∈ gs, p ≠ r → slotTotal gs f ∅/(4*slotDefect gs f ∅ p r) ≤ w p r) + (hupper : ∀ p ∈ gs, ∀ r ∈ gs, p ≠ r → w p r ≤ 4*slotTotal gs f ∅/slotDefect gs f ∅ p r) + (H : ChainIndex gs → ℝ) : + let C := metropolisChain gs hgs hne hcover w f hw hf + let g := fun S : ChainIndex gs => G S.val-chainMean gs w f G + (C.inner g H)^2 ≤ (2000*(gs.length:ℝ)^6)*C.inner g g*C.energy H := by + let C := metropolisChain gs hgs hne hcover w f hw hf + let a := chainMean gs w f G + let g := fun S : ChainIndex gs => G S.val-a + let H' := extendChainFun gs H + let QH := fun S : ChainIndex gs => observableProjection gs f H' S.val + have hext : (fun S : ChainIndex gs => H' S.val) = H := by + funext S + exact extendChainFun_apply gs H S + have hmean : C.mean g = 0 := by + have hm := metropolisChain_mean gs hgs hne hcover w f G hw hf + change C.mean (fun S => G S.val-a) = 0 + change C.mean (fun S : ChainIndex gs => G S.val) = a at hm + rw [← hm] + exact C.centered_mean _ + have hpair : C.inner g H = C.inner g QH := by + rw [← hext] + change C.inner (fun S => (G S.val-a)) (fun S => H' S.val) = + C.inner (fun S => (G S.val-a)) (fun S => observableProjection gs f H' S.val) + dsimp only [C] + rw [metropolisChain_inner gs hgs hne hcover w f (fun S => G S-a) H' hw hf, + metropolisChain_inner gs hgs hne hcover w f (fun S => G S-a) (observableProjection gs f H') hw hf] + exact congrArg (fun t => t/chainTotal gs w f) + (chain_pairing_projection gs hgs hcover w f (fun S => G S-a) H' hf (hG.sub_const a)) + have hbound : C.variance QH ≤ (2000*(gs.length:ℝ)^6)*C.energy H := by + change (metropolisChain gs hgs hne hcover w f hw hf).variance + (fun S => observableProjection gs f H' S.val) ≤ _ + rw [metropolisChain_variance] + have hb := observable_poincare gs hgs hne hcover w hw f H' hf hsig hlower hupper + rw [← metropolisChain_energy gs hgs hne hcover w f H' hw hf,hext] at hb + exact hb + change (C.inner g H)^2 ≤ (2000*(gs.length:ℝ)^6)*C.inner g g*C.energy H + rw [hpair,← C.inner_center_right g QH hmean (C.mean QH)] + calc + _ ≤ C.inner g g*C.variance QH := C.inner_cauchy _ _ + _ ≤ C.inner g g*((2000*(gs.length:ℝ)^6)*C.energy H) := + mul_le_mul_of_nonneg_left hbound (C.inner_nonneg g) + _ = _ := by ring + +theorem metropolisChain_timeAverage (gs : List (Γ × Γ)) (hgs : SlotsFresh gs ∅) (hne : gs ≠ []) + (hcover : pairSupport gs = Set.univ) (w : (Γ × Γ) → (Γ × Γ) → ℝ) + (f G : Set Γ → ℝ) (hw : ∀ p r,0 < w p r) (hf : ∀ S,0 < f S) + (hsig : HasSlotSignature f) (hG : ClassObservable gs G) + (hlower : ∀ p ∈ gs, ∀ r ∈ gs, p ≠ r → slotTotal gs f ∅/(4*slotDefect gs f ∅ p r) ≤ w p r) + (hupper : ∀ p ∈ gs, ∀ r ∈ gs, p ≠ r → w p r ≤ 4*slotTotal gs f ∅/slotDefect gs f ∅ p r) + (U : ℝ) (hU : 0 ≤ U) (ν : ChainIndex gs → ℝ) + (hwarm : ∀ S,ν S ≤ U*chainWeight gs w f S.val/chainTotal gs w f) + (N : ℕ) (hN : 0 < N) : + let C := metropolisChain gs hgs hne hcover w f hw hf + let g := fun S : ChainIndex gs => G S.val-chainMean gs w f G + (∑ S,ν S*C.squareMoment g N S)/(N:ℝ)^2 ≤ + 2*U*(2000*(gs.length:ℝ)^6)*chainVariance gs w f G/N := by + let C := metropolisChain gs hgs hne hcover w f hw hf + let g := fun S : ChainIndex gs => G S.val-chainMean gs w f G + have hi : C.inner g g = chainVariance gs w f G := by + rw [← metropolisChain_variance gs hgs hne hcover w f G hw hf] + unfold FiniteChain.variance + rw [metropolisChain_mean] + have h := C.warm_squareMoment_bound g (2000*(gs.length:ℝ)^6) U (by positivity) hU + (metropolisChain_dual gs hgs hne hcover w f G hw hf hsig hG hlower hupper) ν + (by intro S; simpa only [C,metropolisChain,FiniteChain.ofMoves,mul_div_assoc] using hwarm S) N hN + rw [hi] at h + exact h + +end ObservableMSE + +structure KilledKernel (B : Type*) [Fintype B] where + Q : B → B → ℝ + r : ℝ + nonnegative : ∀ x y,0 ≤ Q x y + rnonneg : 0 ≤ r + rlt : r < 1 + rowbound : ∀ x,∑ y,Q x y ≤ r + +namespace KilledKernel +open scoped BigOperators Classical +open Filter +variable {B : Type*} [Fintype B] (Q : KilledKernel B) +noncomputable def apply (f : B → ℝ) (x : B) : ℝ := ∑ y,Q.Q x y*f y +noncomputable def iterate (k : ℕ) (f : B → ℝ) : B → ℝ := Nat.iterate Q.apply k f +@[simp] lemma iterate_zero (f : B → ℝ) : Q.iterate 0 f = f := rfl +lemma iterate_succ (k : ℕ) (f : B → ℝ) : Q.iterate (k+1) f = Q.apply (Q.iterate k f) := + Function.iterate_succ_apply' Q.apply k f +lemma iterate_succ' (k : ℕ) (f : B → ℝ) : Q.iterate (k+1) f = Q.iterate k (Q.apply f) := + Function.iterate_succ_apply Q.apply k f +lemma apply_add (f g : B → ℝ) : Q.apply (fun x => f x+g x) = fun x => Q.apply f x+Q.apply g x := by + funext x + simp [apply,mul_add,Finset.sum_add_distrib] +lemma apply_sub (f g : B → ℝ) : Q.apply (fun x => f x-g x) = fun x => Q.apply f x-Q.apply g x := by + funext x + simp [apply,mul_sub,Finset.sum_sub_distrib] +lemma apply_sum {J : Type*} (s : Finset J) (f : J → B → ℝ) : + Q.apply (fun x => ∑ j ∈ s,f j x) = fun x => ∑ j ∈ s,Q.apply (f j) x := by + funext x + simp only [apply,Finset.mul_sum] + exact Finset.sum_comm +lemma apply_mul (a : ℝ) (f : B → ℝ) : Q.apply (fun x => a*f x) = fun x => a*Q.apply f x := by + funext x + simp only [apply,Finset.mul_sum] + apply Finset.sum_congr rfl + intro y _ + ring +lemma apply_nonneg (f : B → ℝ) (hf : ∀ x,0 ≤ f x) (x : B) : 0 ≤ Q.apply f x := + Finset.sum_nonneg (fun y _ => mul_nonneg (Q.nonnegative x y) (hf y)) +lemma iterate_nonneg (k : ℕ) (f : B → ℝ) (hf : ∀ x,0 ≤ f x) (x : B) : 0 ≤ Q.iterate k f x := by + induction k generalizing x with + | zero => exact hf x + | succ k ih => + rw [Q.iterate_succ] + exact Q.apply_nonneg _ ih x + +lemma apply_abs_bound (f : B → ℝ) (M : ℝ) (hM : 0 ≤ M) (hf : ∀ x,|f x| ≤ M) (x : B) : + |Q.apply f x| ≤ Q.r*M := by + calc + _ ≤ ∑ y,|Q.Q x y*f y| := Finset.abs_sum_le_sum_abs _ _ + _ = ∑ y,Q.Q x y*|f y| := by simp_rw [abs_mul,abs_of_nonneg (Q.nonnegative x _) ] + _ ≤ ∑ y,Q.Q x y*M := Finset.sum_le_sum (fun y _ => mul_le_mul_of_nonneg_left (hf y) (Q.nonnegative x y)) + _ = (∑ y,Q.Q x y)*M := (Finset.sum_mul _ _ _).symm + _ ≤ Q.r*M := mul_le_mul_of_nonneg_right (Q.rowbound x) hM + +lemma iterate_abs_bound (k : ℕ) (f : B → ℝ) (M : ℝ) (hM : 0 ≤ M) (hf : ∀ x,|f x| ≤ M) (x : B) : + |Q.iterate k f x| ≤ Q.r^k*M := by + induction k generalizing x with + | zero => simpa using hf x + | succ k ih => + rw [Q.iterate_succ,pow_succ'] + simpa only [mul_assoc] using Q.apply_abs_bound (Q.iterate k f) (Q.r^k*M) + (mul_nonneg (pow_nonneg Q.rnonneg _) hM) ih x + +lemma summable_iterate (f : B → ℝ) (x : B) : Summable (fun k => Q.iterate k f x) := by + let M := ∑ y,|f y| + have hM : 0 ≤ M := Finset.sum_nonneg (fun y _ => abs_nonneg _) + have hf : ∀ y,|f y| ≤ M := fun y => Finset.single_le_sum (f := fun z => |f z|) (fun z _ => abs_nonneg _) (Finset.mem_univ y) + exact (Summable.of_nonneg_of_le (fun k => abs_nonneg _) (fun k => Q.iterate_abs_bound k f M hM hf x) + ((summable_geometric_of_lt_one Q.rnonneg Q.rlt).mul_right M)).of_abs + +lemma iterate_tendsto_zero (f : B → ℝ) (x : B) : Tendsto (fun k => Q.iterate k f x) atTop (nhds 0) := by + let M := ∑ y,|f y| + have hM : 0 ≤ M := Finset.sum_nonneg (fun y _ => abs_nonneg _) + have hf : ∀ y,|f y| ≤ M := fun y => Finset.single_le_sum (f := fun z => |f z|) (fun z _ => abs_nonneg _) (Finset.mem_univ y) + have ht : Tendsto (fun k => Q.r^k*M) atTop (nhds 0) := by + simpa using (tendsto_pow_atTop_nhds_zero_of_lt_one Q.rnonneg Q.rlt).mul_const M + exact (tendsto_zero_iff_abs_tendsto_zero _).mpr (squeeze_zero (fun k => abs_nonneg _) + (fun k => Q.iterate_abs_bound k f M hM hf x) ht) + +noncomputable def green (f : B → ℝ) (x : B) : ℝ := ∑' k,Q.iterate k f x +lemma green_nonneg (f : B → ℝ) (hf : ∀ x,0 ≤ f x) (x : B) : 0 ≤ Q.green f x := + tsum_nonneg (fun k => Q.iterate_nonneg k f hf x) + +lemma green_firstStep (f : B → ℝ) (x : B) : Q.green f x = f x+Q.apply (Q.green f) x := by + unfold green + rw [(Q.summable_iterate f x).tsum_eq_zero_add] + simp only [Q.iterate_zero,Q.iterate_succ,apply] + congr 1 + rw [Summable.tsum_finsetSum (fun y (_ : y ∈ Finset.univ) => (Q.summable_iterate f y).mul_left (Q.Q x y))] + simp_rw [tsum_mul_left] + +lemma iterate_sub (k : ℕ) (f g : B → ℝ) : + Q.iterate k (fun x => f x-g x) = fun x => Q.iterate k f x-Q.iterate k g x := by + induction k with + | zero => rfl + | succ k ih => rw [Q.iterate_succ,ih,Q.apply_sub,← Q.iterate_succ,← Q.iterate_succ] +lemma iterate_sum {J : Type*} (s : Finset J) (f : J → B → ℝ) (k : ℕ) : + Q.iterate k (fun x => ∑ j ∈ s,f j x) = fun x => ∑ j ∈ s,Q.iterate k (f j) x := by + induction k with + | zero => rfl + | succ k ih => rw [Q.iterate_succ,ih,Q.apply_sum]; simp_rw [← Q.iterate_succ] +lemma iterate_mul (a : ℝ) (f : B → ℝ) (k : ℕ) : + Q.iterate k (fun x => a*f x) = fun x => a*Q.iterate k f x := by + induction k with + | zero => rfl + | succ k ih => rw [Q.iterate_succ,ih,Q.apply_mul,← Q.iterate_succ] + +lemma green_sum {J : Type*} (s : Finset J) (f : J → B → ℝ) (x : B) : + Q.green (fun x => ∑ j ∈ s,f j x) x = ∑ j ∈ s,Q.green (f j) x := by + unfold green + simp_rw [Q.iterate_sum] + exact Summable.tsum_finsetSum (fun j _ => Q.summable_iterate (f j) x) +lemma green_mul (a : ℝ) (f : B → ℝ) (x : B) : Q.green (fun x => a*f x) x = a*Q.green f x := by + unfold green + simp_rw [Q.iterate_mul] + exact tsum_mul_left + +lemma iterate_residual_sum (f : B → ℝ) (N : ℕ) (x : B) : + (∑ k ∈ Finset.range N,Q.iterate k (fun y => f y-Q.apply f y) x) = f x-Q.iterate N f x := by + induction N with + | zero => simp + | succ N ih => + rw [Finset.sum_range_succ,ih,Q.iterate_sub,← Q.iterate_succ'] + simp only + ring + +lemma green_residual (f : B → ℝ) (x : B) : Q.green (fun y => f y-Q.apply f y) x = f x := by + have hs := (Q.summable_iterate (fun y => f y-Q.apply f y) x).tendsto_sum_tsum_nat + simp_rw [Q.iterate_residual_sum] at hs + have ht : Tendsto (fun N => f x-Q.iterate N f x) atTop (nhds (f x)) := by + simpa using tendsto_const_nhds.sub (Q.iterate_tendsto_zero f x) + exact tendsto_nhds_unique hs ht + +end KilledKernel +namespace FiniteChain + +section +open scoped BigOperators Classical +variable {X : Type*} [sectionInstance66 : Fintype X] (C : FiniteChain X) (A : X → Prop) + +abbrev Inside := {x : X // A x} +abbrev Outside := {x : X // ¬ A x} + +noncomputable def mergeFun (h : Inside A → ℝ) (b : Outside A → ℝ) (x : X) : ℝ := + if hx : A x then h ⟨x,hx⟩ else b ⟨x,hx⟩ +omit sectionInstance66 in +@[simp] lemma mergeFun_inside [Fintype X] (h : Inside A → ℝ) (b : Outside A → ℝ) (x : Inside A) : + mergeFun A h b x.val = h x := by simp [mergeFun,x.property] +omit sectionInstance66 in +@[simp] lemma mergeFun_outside [Fintype X] (h : Inside A → ℝ) (b : Outside A → ℝ) (x : Outside A) : + mergeFun A h b x.val = b x := by simp [mergeFun,x.property] + +variable (Q : KilledKernel (Outside A)) (hQ : ∀ x y : Outside A,Q.Q x y = C.P x.val y.val) + +noncomputable def hitKernel (x : Outside A) (y : Inside A) : ℝ := + Q.green (fun z => C.P z.val y.val) x +lemma hitKernel_nonneg (x : Outside A) (y : Inside A) : 0 ≤ C.hitKernel A Q x y := + Q.green_nonneg _ (fun z => C.nonnegative z.val y.val) x + +include hQ in +lemma exitRow (x : Outside A) : (∑ y : Inside A,C.P x.val y.val) = 1-Q.apply (fun _ => 1) x := by + have hh := Fintype.sum_subtype_add_sum_subtype A (fun y => C.P x.val y) + rw [C.stochastic] at hh + have he : Q.apply (fun _ => 1) x = ∑ y : Outside A,C.P x.val y.val := by + simp [KilledKernel.apply,hQ] + rw [he] + linarith + +include hQ in +lemma hitKernel_row (x : Outside A) : ∑ y : Inside A,C.hitKernel A Q x y = 1 := by + unfold hitKernel + rw [← Q.green_sum Finset.univ] + have he : (fun z : Outside A => ∑ y : Inside A,C.P z.val y.val) = + fun z => 1-Q.apply (fun _ => 1) z := by + funext z + exact C.exitRow A Q hQ z + rw [he,Q.green_residual] + +include hQ in +lemma hitKernel_firstStep (x : Outside A) (y : Inside A) : + C.hitKernel A Q x y = C.P x.val y.val+∑ z : Outside A,C.P x.val z.val*C.hitKernel A Q z y := by + unfold hitKernel + rw [Q.green_firstStep] + simp only [KilledKernel.apply,hQ] + +noncomputable def traceMatrix (x y : Inside A) : ℝ := + C.P x.val y.val+∑ z : Outside A,C.P x.val z.val*C.hitKernel A Q z y +noncomputable def traceApply (h : Inside A → ℝ) (x : Inside A) : ℝ := + ∑ y,C.traceMatrix A Q x y*h y + +lemma traceMatrix_nonneg (x y : Inside A) : 0 ≤ C.traceMatrix A Q x y := + add_nonneg (C.nonnegative _ _) (Finset.sum_nonneg (fun z _ => mul_nonneg + (C.nonnegative _ _) (C.hitKernel_nonneg A Q z y))) +lemma traceMatrix_lazy (x : Inside A) : 1/2 ≤ C.traceMatrix A Q x x := by + exact (C.lazy x.val).trans (le_add_of_nonneg_right (Finset.sum_nonneg (fun z _ => + mul_nonneg (C.nonnegative _ _) (C.hitKernel_nonneg A Q z x)))) +include hQ in +lemma traceMatrix_stochastic (x : Inside A) : ∑ y,C.traceMatrix A Q x y = 1 := by + unfold traceMatrix + rw [Finset.sum_add_distrib,Finset.sum_comm] + simp_rw [← Finset.mul_sum,C.hitKernel_row A Q hQ,mul_one] + rw [Fintype.sum_subtype_add_sum_subtype A,C.stochastic] + +noncomputable def offExtension (h : Inside A → ℝ) (x : Outside A) : ℝ := + ∑ y : Inside A,C.hitKernel A Q x y*h y +noncomputable def harmonicExtension (h : Inside A → ℝ) : X → ℝ := mergeFun A h (C.offExtension A Q h) +@[simp] lemma harmonicExtension_inside (h : Inside A → ℝ) (x : Inside A) : + C.harmonicExtension A Q h x.val = h x := mergeFun_inside _ _ _ _ +@[simp] lemma harmonicExtension_outside (h : Inside A → ℝ) (x : Outside A) : + C.harmonicExtension A Q h x.val = C.offExtension A Q h x := mergeFun_outside _ _ _ _ + +include hQ in +lemma offExtension_firstStep (h : Inside A → ℝ) (x : Outside A) : + C.offExtension A Q h x = (∑ y : Inside A,C.P x.val y.val*h y)+ + ∑ z : Outside A,C.P x.val z.val*C.offExtension A Q h z := by + unfold offExtension + calc + _ = ∑ y : Inside A,(C.P x.val y.val+∑ z : Outside A,C.P x.val z.val*C.hitKernel A Q z y)*h y := by + apply Finset.sum_congr rfl + intro y _ + rw [C.hitKernel_firstStep A Q hQ] + _ = _ := ?_ + simp only [add_mul,Finset.sum_mul,Finset.sum_add_distrib] + congr 1 + rw [Finset.sum_comm] + apply Finset.sum_congr rfl + intro z _ + simp_rw [mul_assoc,← Finset.mul_sum] + +include hQ in +lemma harmonicExtension_harmonic (h : Inside A → ℝ) (x : Outside A) : + C.apply (C.harmonicExtension A Q h) x.val = C.harmonicExtension A Q h x.val := by + unfold apply + rw [← Fintype.sum_subtype_add_sum_subtype A] + simp only [C.harmonicExtension_inside,C.harmonicExtension_outside] + exact (C.offExtension_firstStep A Q hQ h x).symm + +lemma apply_harmonicExtension_inside (h : Inside A → ℝ) (x : Inside A) : + C.apply (C.harmonicExtension A Q h) x.val = C.traceApply A Q h x := by + unfold apply + rw [← Fintype.sum_subtype_add_sum_subtype A] + simp only [C.harmonicExtension_inside,C.harmonicExtension_outside] + unfold traceApply traceMatrix offExtension + simp_rw [add_mul,Finset.sum_mul,Finset.sum_add_distrib,Finset.mul_sum] + congr 1 + rw [Finset.sum_comm] + apply Finset.sum_congr rfl + intro y _ + apply Finset.sum_congr rfl + intro z _ + ring + +include hQ in +lemma harmonic_inner_residual (h g : Inside A → ℝ) : + C.inner (C.harmonicExtension A Q h) + (fun x => C.harmonicExtension A Q g x-C.apply (C.harmonicExtension A Q g) x) = + ∑ x : Inside A,C.π x.val*h x*(g x-C.traceApply A Q g x) := by + unfold inner + rw [← Fintype.sum_subtype_add_sum_subtype A] + simp only [C.harmonicExtension_inside,C.apply_harmonicExtension_inside, + C.harmonicExtension_harmonic A Q hQ,sub_self,mul_zero,Finset.sum_const_zero,add_zero] + +end +section +open scoped BigOperators Classical +variable {X : Type*} [Fintype X] (C : FiniteChain X) (A : X → Prop) +variable (Q : KilledKernel (Outside A)) (hQ : ∀ x y : Outside A,Q.Q x y = C.P x.val y.val) + +lemma residual_symmetric (f g : X → ℝ) : + C.inner f (fun x => g x-C.apply g x) = C.inner g (fun x => f x-C.apply f x) := by + rw [C.inner_sub_right,C.inner_sub_right,C.apply_selfAdjoint,C.inner_symm f g, + C.inner_symm (C.apply f) g] + +include hQ in +lemma traceMatrix_reversible (x y : Inside A) : + C.π x.val*C.traceMatrix A Q x y = C.π y.val*C.traceMatrix A Q y x := by + by_cases hxy : x = y + · subst y; rfl + have h := C.residual_symmetric (C.harmonicExtension A Q (fun z => if z=x then 1 else 0)) + (C.harmonicExtension A Q (fun z => if z=y then 1 else 0)) + rw [C.harmonic_inner_residual A Q hQ,C.harmonic_inner_residual A Q hQ] at h + simp [traceApply,hxy,Ne.symm hxy] at h + linarith + +noncomputable def insideMass : ℝ := ∑ x : Inside A,C.π x.val +lemma insideMass_pos [Nonempty (Inside A)] : 0 < C.insideMass A := by + apply Finset.sum_pos + · intro x _; exact C.positive _ + · exact Finset.univ_nonempty + +noncomputable def traceChain [Nonempty (Inside A)] : FiniteChain (Inside A) where + P := C.traceMatrix A Q + π := fun x => C.π x.val/C.insideMass A + positive := fun x => div_pos (C.positive _) (C.insideMass_pos A) + normalized := by rw [← Finset.sum_div]; exact div_self (C.insideMass_pos A).ne' + nonnegative := C.traceMatrix_nonneg A Q + stochastic := C.traceMatrix_stochastic A Q hQ + reversible := by + intro x y + rw [div_mul_eq_mul_div,div_mul_eq_mul_div,C.traceMatrix_reversible A Q hQ] + lazy := C.traceMatrix_lazy A Q + +lemma traceChain_energy [Nonempty (Inside A)] (h : Inside A → ℝ) : + C.energy (C.harmonicExtension A Q h) = + C.insideMass A*(C.traceChain A Q hQ).energy h := by + rw [energy,C.harmonic_inner_residual A Q hQ] + change _ = C.insideMass A*(∑ x : Inside A, + (C.π x.val/C.insideMass A)*h x*(h x-C.traceApply A Q h x)) + rw [Finset.mul_sum] + apply Finset.sum_congr rfl + intro x _ + field_simp [(C.insideMass_pos A).ne'] + +lemma mean_apply (f : X → ℝ) : C.mean (C.apply f) = C.mean f := by + unfold mean apply + simp_rw [Finset.mul_sum] + rw [Finset.sum_comm] + simp_rw [← mul_assoc,← Finset.sum_mul,C.stationary] +lemma mean_residual (f : X → ℝ) : C.mean (fun x => f x-C.apply f x) = 0 := by + unfold mean + simp_rw [mul_sub,Finset.sum_sub_distrib] + change C.mean f-C.mean (C.apply f) = 0 + rw [C.mean_apply,sub_self] + +noncomputable def duration (x : Outside A) : ℝ := Q.green (fun _ => 1) x +noncomputable def returnCost (x : Inside A) : ℝ := + 1+∑ y : Outside A,C.P x.val y.val*duration A Q y +lemma duration_nonneg (x : Outside A) : 0 ≤ duration A Q x := + Q.green_nonneg _ (by intro; norm_num) x +lemma returnCost_nonneg (x : Inside A) : 0 ≤ C.returnCost A Q x := + add_nonneg (by norm_num) (Finset.sum_nonneg (fun y _ => + mul_nonneg (C.nonnegative _ _) (duration_nonneg A Q y))) + +include hQ in +lemma expected_returnCost : (∑ x : Inside A,C.π x.val*C.returnCost A Q x) = 1 := by + let l : X → ℝ := mergeFun A (fun _ => 0) (duration A Q) + have hi (x : Inside A) : l x.val = 0 := by simp [l] + have ho (x : Outside A) : l x.val = duration A Q x := by simp [l] + have hai (x : Inside A) : C.apply l x.val = ∑ y : Outside A,C.P x.val y.val*duration A Q y := by + unfold apply + rw [← Fintype.sum_subtype_add_sum_subtype A] + simp only [hi,ho,mul_zero,Finset.sum_const_zero,zero_add] + have hao (x : Outside A) : C.apply l x.val = Q.apply (duration A Q) x := by + unfold apply + rw [← Fintype.sum_subtype_add_sum_subtype A] + simp only [hi,ho,mul_zero,Finset.sum_const_zero,zero_add,KilledKernel.apply,hQ] + have hr (x : Outside A) : l x.val-C.apply l x.val = 1 := by + rw [ho,hao] + have hg := Q.green_firstStep (fun _ => (1:ℝ)) x + change duration A Q x = 1+Q.apply (duration A Q) x at hg + linarith + have hm := C.mean_residual l + unfold mean at hm + rw [← Fintype.sum_subtype_add_sum_subtype A] at hm + simp only [hi,hai,hr,zero_sub,mul_neg,Finset.sum_neg_distrib,mul_one] at hm + have hmass := Fintype.sum_subtype_add_sum_subtype A C.π + rw [C.normalized] at hmass + unfold returnCost + simp only [mul_add,mul_one,Finset.sum_add_distrib] + linarith + +lemma traceChain_returnCost [Nonempty (Inside A)] : + (C.traceChain A Q hQ).mean (C.returnCost A Q) = 1/C.insideMass A := by + change (∑ x : Inside A,(C.π x.val/C.insideMass A)*C.returnCost A Q x) = _ + simp_rw [div_mul_eq_mul_div] + rw [← Finset.sum_div,C.expected_returnCost A Q hQ] + +lemma warm_returnCost [Nonempty (Inside A)] (ν : Inside A → ℝ) (U : ℝ) + (hν : ∀ x,ν x ≤ U*(C.traceChain A Q hQ).π x) : + (∑ x,ν x*C.returnCost A Q x) ≤ U/C.insideMass A := by + calc + _ ≤ ∑ x,U*(C.traceChain A Q hQ).π x*C.returnCost A Q x := + Finset.sum_le_sum (fun x _ => mul_le_mul_of_nonneg_right (hν x) (C.returnCost_nonneg A Q x)) + _ = U*(C.traceChain A Q hQ).mean (C.returnCost A Q) := by simp [mean,Finset.mul_sum,mul_assoc] + _ = _ := by rw [C.traceChain_returnCost A Q hQ]; ring +end +section +open scoped BigOperators Classical +variable {X : Type*} [Fintype X] (C : FiniteChain X) (A : X → Prop) +variable (hExit : ∀ x : Outside A,∃ y : Inside A,0 < C.P x.val y.val) +noncomputable def exitProbability (x : Outside A) : ℝ := ∑ y : Inside A,C.P x.val y.val +lemma exitProbability_nonneg (x : Outside A) : 0 ≤ C.exitProbability A x := + Finset.sum_nonneg (fun y _ => C.nonnegative x.val y.val) +include hExit in +lemma exitProbability_pos (x : Outside A) : 0 < C.exitProbability A x := by + obtain ⟨y,hy⟩ := hExit x + exact hy.trans_le (Finset.single_le_sum (fun z _ => C.nonnegative _ _) (Finset.mem_univ y)) +lemma exitProbability_le_one (x : Outside A) : C.exitProbability A x ≤ 1 := by + have h := Fintype.sum_subtype_add_sum_subtype A (fun y => C.P x.val y) + rw [C.stochastic] at h + have hn : 0 ≤ ∑ y : Outside A,C.P x.val y.val := Finset.sum_nonneg (fun y _ => C.nonnegative _ _) + change (∑ y : Inside A,C.P x.val y.val) ≤ 1 + linarith +noncomputable def killedChain : KilledKernel (Outside A) where + Q := fun x y => C.P x.val y.val + r := 1-∏ x : Outside A,C.exitProbability A x + nonnegative := fun x y => C.nonnegative _ _ + rnonneg := sub_nonneg.mpr (Finset.prod_le_one₀ (fun x _ => C.exitProbability_nonneg A x) + (fun x _ => C.exitProbability_le_one A x)) + rlt := by + have h : 0 < ∏ x : Outside A,C.exitProbability A x := Finset.prod_pos (fun x _ => C.exitProbability_pos A hExit x) + linarith + rowbound := by + intro x + have hprod : (∏ z : Outside A,C.exitProbability A z) ≤ C.exitProbability A x := by + have h := Finset.prod_le_prod_of_subset_of_le_one₀ (Finset.singleton_subset_iff.mpr (Finset.mem_univ x)) + (fun z (_ : z ∈ Finset.univ) => C.exitProbability_nonneg A z) + (fun z _ _ => C.exitProbability_le_one A z) + simpa only [Finset.prod_singleton] using h + have hs := Fintype.sum_subtype_add_sum_subtype A (fun y => C.P x.val y) + rw [C.stochastic] at hs + change (∑ y : Inside A,C.P x.val y.val)+(∑ y : Outside A,C.P x.val y.val) = 1 at hs + unfold exitProbability at hprod ⊢ + linarith +end +open scoped Classical BigOperators +variable {X : Type*} [Fintype X] (C : FiniteChain X) + +lemma apply_cauchy (f g : X → ℝ) : + (C.inner f (C.apply g))^2 ≤ C.inner f (C.apply f)*C.inner g (C.apply g) := by + let B : LinearMap.BilinForm ℝ (X → ℝ) := Matrix.toBilin' (fun x y => C.π x*C.P x y) + have he (u v : X → ℝ) : B u v = C.inner u (C.apply v) := by + simp only [B,inner,apply,Finset.mul_sum] + apply Finset.sum_congr rfl + intro x _ + apply Finset.sum_congr rfl + intro y _ + change v y*(u x*(C.π x*C.P x y))=C.π x*u x*(C.P x y*v y) + ring + have hs : LinearMap.IsSymm B := by + constructor + intro u v + simp only [he,RingHom.id_apply] + rw [C.apply_selfAdjoint,C.inner_symm] + simpa only [he] using B.apply_sq_le_of_symm (fun u => by rw [he]; exact C.apply_positive u) hs f g + +lemma inner_sub_left (f g h : X → ℝ) : + C.inner (fun x => f x-g x) h = C.inner f h-C.inner g h := by + rw [C.inner_symm,C.inner_sub_right,C.inner_symm h f,C.inner_symm h g] +lemma apply_sub (f g : X → ℝ) : C.apply (fun x => f x-g x) = fun x => C.apply f x-C.apply g x := by + funext x + simp [apply,mul_sub,Finset.sum_sub_distrib] +lemma mean_const (a : ℝ) : C.mean (fun _ => a) = a := by + simp [mean,← Finset.sum_mul,C.normalized] +lemma mean_sub (f g : X → ℝ) : C.mean (fun x => f x-g x) = C.mean f-C.mean g := by + simp [mean,mul_sub,Finset.sum_sub_distrib] +lemma variance_eq_inner (f : X → ℝ) (hf : C.mean f = 0) : C.variance f = C.inner f f := by + simp [variance,hf] + +lemma apply_contraction (r : ℝ) (hr : 0 ≤ r) + (hgap : ∀ f : X → ℝ,C.mean f = 0 → C.inner f (C.apply f) ≤ r*C.inner f f) + (f : X → ℝ) (hf : C.mean f = 0) : + C.inner (C.apply f) (C.apply f) ≤ r^2*C.inner f f := by + have hg : C.mean (C.apply f) = 0 := by rw [C.mean_apply,hf] + have hcs := C.apply_cauchy (C.apply f) f + have h₁ := hgap f hf + have h₂ := hgap (C.apply f) hg + have hp₁ := C.apply_positive f + have hp₂ := C.apply_positive (C.apply f) + have hn := C.inner_nonneg (C.apply f) + have hm := C.inner_nonneg f + have hb := mul_le_mul h₂ h₁ hp₁ (mul_nonneg hr hn) + by_cases hz : C.inner (C.apply f) (C.apply f) = 0 + · rw [hz]; positivity + · have hpos : 0 < C.inner (C.apply f) (C.apply f) := lt_of_le_of_ne hn (Ne.symm hz) + nlinarith + +lemma iterate_mean (k : ℕ) (f : X → ℝ) : C.mean (C.iterate k f) = C.mean f := by + induction k with + | zero => rfl + | succ k ih => rw [C.iterate_succ,C.mean_apply,ih] +lemma iterate_contraction (r : ℝ) (hr : 0 ≤ r) + (hgap : ∀ f : X → ℝ,C.mean f = 0 → C.inner f (C.apply f) ≤ r*C.inner f f) + (k : ℕ) (f : X → ℝ) (hf : C.mean f = 0) : + C.inner (C.iterate k f) (C.iterate k f) ≤ r^(2*k)*C.inner f f := by + induction k with + | zero => simp + | succ k ih => + rw [C.iterate_succ] + calc + _ ≤ r^2*C.inner (C.iterate k f) (C.iterate k f) := + C.apply_contraction r hr hgap _ (by rw [C.iterate_mean,hf]) + _ ≤ r^2*(r^(2*k)*C.inner f f) := mul_le_mul_of_nonneg_left ih (sq_nonneg r) + _ = _ := by rw [show 2*(k+1)=2+2*k by omega,pow_add]; ring + +noncomputable def pointDensity (x : X) (y : X) : ℝ := if y=x then 1/C.π x else 0 +noncomputable def centeredPoint (x : X) (y : X) : ℝ := C.pointDensity x y-1 +lemma pointDensity_mean (x : X) : C.mean (C.pointDensity x) = 1 := by + simp [mean,pointDensity,(C.positive x).ne'] +lemma centeredPoint_mean (x : X) : C.mean (C.centeredPoint x) = 0 := by + change C.mean (fun z => C.pointDensity x z-1) = 0 + rw [C.mean_sub,C.pointDensity_mean,C.mean_const,sub_self] +lemma pointDensity_inner (x : X) (f : X → ℝ) : C.inner (C.pointDensity x) f = f x := by + simp [inner,pointDensity,(C.positive x).ne'] +lemma centeredPoint_norm (x : X) : C.inner (C.centeredPoint x) (C.centeredPoint x) ≤ 1/C.π x := by + unfold centeredPoint + rw [C.inner_sub_left,C.inner_sub_right,C.inner_sub_right,C.pointDensity_inner, + C.pointDensity_inner,C.inner_symm (fun _ => 1),C.pointDensity_inner] + have h₁ : C.inner (fun _ => 1) (fun _ => 1) = 1 := by simp [inner,C.normalized] + rw [h₁] + simp only [pointDensity,ite_true] + linarith + +lemma iterate_const (k : ℕ) (a : ℝ) : C.iterate k (fun _ => a) = fun _ => a := by + induction k with + | zero => rfl + | succ k ih => rw [C.iterate_succ,ih,C.apply_const] +lemma iterate_sub (k : ℕ) (f g : X → ℝ) : + C.iterate k (fun x => f x-g x) = fun x => C.iterate k f x-C.iterate k g x := by + induction k with + | zero => rfl + | succ k ih => rw [C.iterate_succ,ih,C.apply_sub,C.iterate_succ,C.iterate_succ] + +lemma point_mixing_squared (r : ℝ) (hr : 0 ≤ r) + (hgap : ∀ f : X → ℝ,C.mean f = 0 → C.inner f (C.apply f) ≤ r*C.inner f f) + (k : ℕ) (x y : X) : + (C.iterate k (C.pointDensity y) x-1)^2 ≤ r^(2*k)/(C.π x*C.π y) := by + have he : C.inner (C.centeredPoint x) (C.iterate k (C.centeredPoint y)) = + C.iterate k (C.pointDensity y) x-1 := by + change C.inner (fun z => C.pointDensity x z-1) (C.iterate k (C.centeredPoint y)) = _ + rw [C.inner_sub_left,C.pointDensity_inner] + have hm : C.inner (fun _ => 1) (C.iterate k (C.centeredPoint y)) = 0 := by + have hz := C.iterate_mean k (C.centeredPoint y) + rw [C.centeredPoint_mean] at hz + simpa only [inner,mean,mul_one] using hz + rw [hm,sub_zero] + change C.iterate k (fun z => C.pointDensity y z-1) x = _ + rw [C.iterate_sub,C.iterate_const] + have hcs := C.inner_cauchy (C.centeredPoint x) (C.iterate k (C.centeredPoint y)) + rw [he] at hcs + have hcon := C.iterate_contraction r hr hgap k (C.centeredPoint y) (C.centeredPoint_mean y) + have hny := C.centeredPoint_norm y + have hnx := C.centeredPoint_norm x + have hb := mul_le_mul hnx (hcon.trans (mul_le_mul_of_nonneg_left hny (pow_nonneg hr _))) + (C.inner_nonneg _) (div_nonneg (by norm_num) (C.positive x).le) + calc + _ ≤ _ := hcs.trans hb + _ = _ := by field_simp +lemma variance_formula (f : X → ℝ) : C.variance f = C.inner f f-(C.mean f)^2 := by + rw [variance,C.inner_sub_left,C.inner_sub_right,C.inner_sub_right] + have h₁ : C.inner f (fun _ => C.mean f) = (C.mean f)^2 := by + unfold inner + rw [← Finset.sum_mul] + change C.mean f*C.mean f = (C.mean f)^2 + ring + have h₂ : C.inner (fun _ => C.mean f) (fun _ => C.mean f) = (C.mean f)^2 := by + simp only [inner,← Finset.sum_mul,C.normalized,one_mul,pow_two] + rw [h₁,C.inner_symm (fun _ => C.mean f) f,h₁,h₂] + ring + +lemma poincare_rayleigh (K : ℝ) (hK : 0 < K) + (hp : ∀ f : X → ℝ,C.variance f ≤ K*C.energy f) + (f : X → ℝ) (hf : C.mean f = 0) : + C.inner f (C.apply f) ≤ (1-1/K)*C.inner f f := by + have h := hp f + rw [C.variance_eq_inner f hf,energy,C.inner_sub_right] at h + apply (mul_le_mul_iff_right₀ hK).mp + field_simp + nlinarith + +lemma point_mixing (r m : ℝ) (hr : 0 ≤ r) (hm : 0 < m) (hπ : ∀ x,m ≤ C.π x) + (hgap : ∀ f : X → ℝ,C.mean f = 0 → C.inner f (C.apply f) ≤ r*C.inner f f) + (k : ℕ) (x y : X) : + |C.iterate k (C.pointDensity y) x-1| ≤ r^k/m := by + have hs := C.point_mixing_squared r hr hgap k x y + have hd : m^2 ≤ C.π x*C.π y := by simpa only [pow_two] using mul_le_mul (hπ x) (hπ y) hm.le (C.positive x).le + have hb : r^(2*k)/(C.π x*C.π y) ≤ (r^k/m)^2 := by + calc + _ ≤ r^(2*k)/m^2 := div_le_div_of_nonneg_left (pow_nonneg hr _) (sq_pos_of_pos hm) hd + _ = _ := by rw [mul_comm 2 k,pow_mul,div_pow] + have ha : (|C.iterate k (C.pointDensity y) x-1|)^2 ≤ (r^k/m)^2 := by + rw [sq_abs] + exact hs.trans hb + exact (sq_le_sq₀ (abs_nonneg _) (div_nonneg (pow_nonneg hr _) hm.le)).mp ha + +lemma point_mixing_exp (K m : ℝ) (hK : 1 ≤ K) (hm : 0 < m) (hπ : ∀ x,m ≤ C.π x) + (hp : ∀ f : X → ℝ,C.variance f ≤ K*C.energy f) + (k : ℕ) (x y : X) : + |C.iterate k (C.pointDensity y) x-1| ≤ Real.exp (-(k:ℝ)/K)/m := by + have hKp : 0 < K := lt_of_lt_of_le (by norm_num) hK + have hr : 0 ≤ 1-1/K := sub_nonneg.mpr ((div_le_one hKp).mpr hK) + have hpow : (1-1/K)^k ≤ Real.exp (-(k:ℝ)/K) := by + have hle : 1-1/K ≤ Real.exp (-1/K) := by + have hh := Real.add_one_le_exp (-1/K) + convert hh using 1 ; ring + calc + _ ≤ (Real.exp (-1/K))^k := pow_le_pow_left₀ hr hle k + _ = Real.exp ((k:ℝ)*(-1/K)) := (Real.exp_nat_mul _ _).symm + _ = _ := by congr 1; ring + exact (C.point_mixing _ m hr hm hπ (C.poincare_rayleigh K hKp hp) k x y).trans + (div_le_div_of_nonneg_right hpow hm.le) +end FiniteChain +section TraceGeometry +open scoped Classical BigOperators +variable {Γ : Type*} [Fintype Γ] [sectionInstance71 : DecidableEq Γ] + +lemma SlotsFresh.cross_ne {gs : List (Γ × Γ)} {A : Set Γ} (hgs : SlotsFresh gs A) + {p r : Γ × Γ} (hp : p ∈ gs) (hr : r ∈ gs) (hpr : p ≠ r) + {x y : Γ} (hx : x=p.1 ∨ x=p.2) (hy : y=r.1 ∨ y=r.2) : x ≠ y := by + intro hxy + have := hgs.pair_contains_unique hp hr hx (hxy ▸ hy) + exact hpr this + +lemma DefectState.plain_neighbor {gs : List (Γ × Γ)} (hgs : SlotsFresh gs ∅) + {p r : Γ × Γ} {S : Set Γ} (hS : DefectState gs p r S) : + ∃ T,PlainState gs T ∧ ExchangeAdjacent S T := by + obtain ⟨hp,hr,hpr,he,hf,ht⟩ := hS + let T := insert p.1 (S\{r.1}) + have hpne : p.1 ≠ p.2 := ((SlotsFresh.perm (List.perm_cons_erase hp) ∅).mp hgs).1 + have hrne : r.1 ≠ r.2 := ((SlotsFresh.perm (List.perm_cons_erase hr) ∅).mp hgs).1 + have hpr11 : p.1 ≠ r.1 := hgs.cross_ne hp hr hpr (Or.inl rfl) (Or.inl rfl) + have hpr21 : p.2 ≠ r.1 := hgs.cross_ne hp hr hpr (Or.inr rfl) (Or.inl rfl) + have hpr12 : p.1 ≠ r.2 := hgs.cross_ne hp hr hpr (Or.inl rfl) (Or.inr rfl) + refine ⟨T,?_,?_⟩ + · intro t htm + by_cases htp : t=p + · subst t + simp [PairSingle,T,hpne.symm,he.1,he.2] + by_cases htr : t=r + · subst t + simp [PairSingle,T,hpr11.symm,hpr12.symm,hrne.symm,hf.2] + have h₁ : t.1 ≠ p.1 := hgs.cross_ne htm hp htp (Or.inl rfl) (Or.inl rfl) + have h₂ : t.2 ≠ p.1 := hgs.cross_ne htm hp htp (Or.inr rfl) (Or.inl rfl) + have h₃ : t.1 ≠ r.1 := hgs.cross_ne htm hr htr (Or.inl rfl) (Or.inl rfl) + have h₄ : t.2 ≠ r.1 := hgs.cross_ne htm hr htr (Or.inr rfl) (Or.inl rfl) + simpa only [PairSingle,T,Set.mem_insert_iff,Set.mem_sdiff,Set.mem_singleton_iff, + h₁,h₂,h₃,h₄,false_or,not_false_eq_true,and_true] using ht t htm htp htr + · refine ⟨S\{r.1},r.1,p.1,hpr11.symm,by simp,?_,?_,rfl⟩ + · exact fun h => he.1 h.1 + · ext x + simp only [Set.mem_insert_iff,Set.mem_sdiff,Set.mem_singleton_iff] + constructor + · intro hx + by_cases h : x=r.1 + · exact Or.inl h + · exact Or.inr ⟨hx,h⟩ + · rintro (rfl|⟨hx,_⟩) + · exact hf.1 + · exact hx + +abbrev PlainIndex (gs : List (Γ × Γ)) := + FiniteChain.Inside (fun S : ChainIndex gs => PlainState gs S.val) + +omit sectionInstance71 in +lemma plainIndex_sum [DecidableEq Γ] (gs : List (Γ × Γ)) (g : Set Γ → ℝ) : + (∑ S : PlainIndex gs,g S.val.val) = ∑ S ∈ Finset.univ.filter (PlainState gs),g S := by + let e : PlainIndex gs ≃ {S : Set Γ // PlainState gs S} := + { toFun := fun S => ⟨S.val.val,S.property⟩ + invFun := fun S => ⟨⟨S.val,Or.inl S.property⟩,S.property⟩ + left_inv := by intro; rfl + right_inv := by intro; rfl } + calc + _ = ∑ S : {S : Set Γ // PlainState gs S},g S.val := + Fintype.sum_equiv e _ _ (by intro S; rfl) + _ = _ := (Finset.sum_subtype _ (by intro S; simp) g).symm + +lemma plainIndex_nonempty (gs : List (Γ × Γ)) (hgs : SlotsFresh gs ∅) + (hcover : pairSupport gs = Set.univ) : Nonempty (PlainIndex gs) := by + have hz := slotTotal_pos gs (fun _ => (1:ℝ)) (by intro; norm_num) ∅ hgs + rw [slotTotal_eq_plain_sum gs hgs hcover,← plainIndex_sum] at hz + by_contra h + have : IsEmpty (PlainIndex gs) := not_nonempty_iff.mp h + simp at hz + +lemma metropolis_plain_exit (gs : List (Γ × Γ)) (hgs : SlotsFresh gs ∅) (hne : gs ≠ []) + (hcover : pairSupport gs = Set.univ) (w : (Γ × Γ) → (Γ × Γ) → ℝ) + (f : Set Γ → ℝ) (hw : ∀ p r,0 < w p r) (hf : ∀ S,0 < f S) + (S : FiniteChain.Outside (fun S : ChainIndex gs => PlainState gs S.val)) : + ∃ T : PlainIndex gs,0 < (metropolisChain gs hgs hne hcover w f hw hf).P S.val T.val := by + obtain ⟨p,r,hS⟩ := S.val.property.resolve_left S.property + obtain ⟨T,hT,hST⟩ := hS.plain_neighbor hgs + let t : PlainIndex gs := ⟨⟨T,Or.inl hT⟩,hT⟩ + refine ⟨t,?_⟩ + have hneST : S.val ≠ t.val := by intro h; exact hST.ne (congrArg Subtype.val h) + change 0 < metropolisMove gs w f S.val t.val+if S.val=t.val then _ else _ + rw [ite_eq_right hneST,add_zero] + unfold metropolisMove + rw [ite_eq_left hST] + have hn : (0:ℝ) < gs.length := by exact_mod_cast List.length_pos_iff.mpr hne + exact div_pos (lt_min (chainWeight_pos gs w f hw hf _) (chainWeight_pos gs w f hw hf _)) + (mul_pos (mul_pos (by norm_num) (sq_pos_of_pos hn)) (chainWeight_pos gs w f hw hf _)) +end TraceGeometry +section TracePoincare +open scoped Classical BigOperators +variable {Γ : Type*} [Fintype Γ] [DecidableEq Γ] +variable (gs : List (Γ × Γ)) (hgs : SlotsFresh gs ∅) (hne : gs ≠ []) + (hcover : pairSupport gs = Set.univ) (w : (Γ × Γ) → (Γ × Γ) → ℝ) + (f : Set Γ → ℝ) (hw : ∀ p r,0 < w p r) (hf : ∀ S,0 < f S) + +abbrev plainPredicate (gs : List (Γ × Γ)) (S : ChainIndex gs) := PlainState gs S.val +noncomputable def metropolisKilled : KilledKernel (FiniteChain.Outside (plainPredicate gs)) := + (metropolisChain gs hgs hne hcover w f hw hf).killedChain (plainPredicate gs) + (metropolis_plain_exit gs hgs hne hcover w f hw hf) + +noncomputable def metropolisTrace : FiniteChain (PlainIndex gs) := by + letI := plainIndex_nonempty gs hgs hcover + exact (metropolisChain gs hgs hne hcover w f hw hf).traceChain (plainPredicate gs) + (metropolisKilled gs hgs hne hcover w f hw hf) (by intro _ _; rfl) + +lemma metropolis_insideMass : + (metropolisChain gs hgs hne hcover w f hw hf).insideMass (plainPredicate gs) = + slotTotal gs f ∅/chainTotal gs w f := by + change (∑ S : PlainIndex gs,chainWeight gs w f S.val.val/chainTotal gs w f) = _ + have he (S : PlainIndex gs) : chainWeight gs w f S.val.val = f S.val.val := by + rw [chainWeight,chainMultiplier_plain gs w S.val.val S.property,one_mul] + simp_rw [he] + rw [← Finset.sum_div,plainIndex_sum,slotTotal_eq_plain_sum gs hgs hcover] + +lemma metropolisTrace_pi (S : PlainIndex gs) : + (metropolisTrace gs hgs hne hcover w f hw hf).π S = f S.val.val/slotTotal gs f ∅ := by + change (chainWeight gs w f S.val.val/chainTotal gs w f)/ + (metropolisChain gs hgs hne hcover w f hw hf).insideMass (plainPredicate gs) = _ + rw [metropolis_insideMass gs hgs hne hcover w f hw hf,chainWeight, + chainMultiplier_plain gs w S.val.val S.property,one_mul] + field_simp [(chainTotal_pos gs hgs hcover w f hf hw).ne'] + +lemma metropolisTrace_variance (H : Set Γ → ℝ) : + (metropolisTrace gs hgs hne hcover w f hw hf).variance (fun S => H S.val.val) = + slotVariance gs f H ∅/slotTotal gs f ∅ := by + rw [FiniteChain.variance_formula] + unfold FiniteChain.inner FiniteChain.mean + simp_rw [metropolisTrace_pi,div_mul_eq_mul_div,← Finset.sum_div] + rw [plainIndex_sum gs (fun S => f S*H S*H S),plainIndex_sum gs (fun S => f S*H S), + slotVariance_eq_plain_variance gs hgs hcover,slotTotal_eq_plain_sum gs hgs hcover] + have he : (∑ S with PlainState gs S,f S*H S*H S) = ∑ S with PlainState gs S,f S*(H S)^2 := by + apply Finset.sum_congr rfl; intro S _; ring + rw [he] + have hz := (slotTotal_pos gs f hf ∅ hgs).ne' + rw [slotTotal_eq_plain_sum gs hgs hcover] at hz + field_simp + +theorem metropolisTrace_poincare (hsig : HasSlotSignature f) + (hgood : ∀ p ∈ gs,∀ r ∈ gs,p ≠ r → slotTotal gs f ∅/(4*slotDefect gs f ∅ p r) ≤ w p r) + (h : PlainIndex gs → ℝ) : + (metropolisTrace gs hgs hne hcover w f hw hf).variance h ≤ + 18*(gs.length:ℝ)^4*(metropolisTrace gs hgs hne hcover w f hw hf).energy h := by + let := plainIndex_nonempty gs hgs hcover + let C := metropolisChain gs hgs hne hcover w f hw hf + let Q := metropolisKilled gs hgs hne hcover w f hw hf + let H := C.harmonicExtension (plainPredicate gs) Q h + let F := extendChainFun gs H + have hF (S : ChainIndex gs) : F S.val = H S := extendChainFun_apply gs H S + have hh (S : PlainIndex gs) : F S.val.val = h S := by + rw [hF]; exact C.harmonicExtension_inside (plainPredicate gs) Q h S + have hvar := metropolisTrace_variance gs hgs hne hcover w f hw hf F + have hefun : (fun S : PlainIndex gs => F S.val.val) = h := funext hh + rw [hefun] at hvar + have hv := transversal_variance_bound gs f F w hf hsig hgs hw hgood + have hz := slotTotal_pos gs f hf ∅ hgs + have hΛ := chainTotal_pos gs hgs hcover w f hf hw + have hn : (1:ℝ) ≤ gs.length := by exact_mod_cast List.length_pos_iff.mpr hne + have henergy : restrictedEnergy (chainEdges gs) (chainConductance gs w f) F ∅ ∅ = + (2*(gs.length:ℝ)^2*slotTotal gs f ∅)*(metropolisTrace gs hgs hne hcover w f hw hf).energy h := by + have hc := metropolisChain_energy gs hgs hne hcover w f F hw hf + have hfFn : (fun S : ChainIndex gs => F S.val) = H := funext hF + rw [hfFn] at hc + change C.energy (C.harmonicExtension (plainPredicate gs) Q h) = _ at hc + rw [C.traceChain_energy (plainPredicate gs) Q (by intro _ _; rfl)] at hc + change C.insideMass (plainPredicate gs)*(metropolisTrace gs hgs hne hcover w f hw hf).energy h = _ at hc + rw [metropolis_insideMass gs hgs hne hcover w f hw hf] at hc + unfold chainDirichlet at hc + field_simp at hc + nlinarith + rw [henergy] at hv + rw [hvar] + have hE := (metropolisTrace gs hgs hne hcover w f hw hf).energy_nonneg h + apply (div_le_iff₀ hz).mpr + have hconst : (gs.length:ℝ)*(1+8*(gs.length:ℝ))*(2*(gs.length:ℝ)^2) ≤ 18*(gs.length:ℝ)^4 := by + nlinarith [sq_nonneg ((gs.length:ℝ)-1),sq_nonneg (gs.length:ℝ)] + have hb := mul_le_mul_of_nonneg_right hconst (mul_nonneg hz.le hE) + nlinarith +end TracePoincare + +namespace KilledKernel +open scoped BigOperators Classical +variable {B : Type*} [Fintype B] (Q : KilledKernel B) +lemma apply_mono {f g : B → ℝ} (h : ∀ x,f x ≤ g x) (x : B) : Q.apply f x ≤ Q.apply g x := + Finset.sum_le_sum (fun y _ => mul_le_mul_of_nonneg_left (h y) (Q.nonnegative x y)) +lemma iterate_mono {f g : B → ℝ} (h : ∀ x,f x ≤ g x) (k : ℕ) (x : B) : + Q.iterate k f x ≤ Q.iterate k g x := by + induction k generalizing x with + | zero => exact h x + | succ k ih => rw [Q.iterate_succ,Q.iterate_succ]; exact Q.apply_mono ih x +lemma survival_antitone (x : B) : Antitone (fun k => Q.iterate k (fun _ => 1) x) := by + apply antitone_nat_of_succ_le + intro k + rw [Q.iterate_succ'] + apply Q.iterate_mono + intro y + simpa only [apply,mul_one] using (Q.rowbound y).trans Q.rlt.le +lemma duration_tail (N : ℕ) (x : B) : + (N:ℝ)*Q.iterate N (fun _ => 1) x ≤ Q.green (fun _ => 1) x := by + calc + _ = ∑ k ∈ Finset.range N,Q.iterate N (fun _ => 1) x := by simp + _ ≤ ∑ k ∈ Finset.range N,Q.iterate k (fun _ => 1) x := + Finset.sum_le_sum (fun k hk => Q.survival_antitone x (Finset.mem_range.mp hk).le) + _ ≤ _ := (Q.summable_iterate (fun _ => 1) x).sum_le_tsum (Finset.range N) + (fun k _ => Q.iterate_nonneg k _ (by intro; norm_num) x) +noncomputable def partialGreen (N : ℕ) (f : B → ℝ) (x : B) : ℝ := + ∑ k ∈ Finset.range N,Q.iterate k f x +lemma partialGreen_nonneg (N : ℕ) (f : B → ℝ) (hf : ∀ x,0 ≤ f x) (x : B) : + 0 ≤ Q.partialGreen N f x := Finset.sum_nonneg (fun k _ => Q.iterate_nonneg k f hf x) +lemma partialGreen_le (N : ℕ) (f : B → ℝ) (hf : ∀ x,0 ≤ f x) (x : B) : + Q.partialGreen N f x ≤ Q.green f x := + (Q.summable_iterate f x).sum_le_tsum (Finset.range N) (fun k _ => Q.iterate_nonneg k f hf x) +lemma partialGreen_sum {J : Type*} (s : Finset J) (f : J → B → ℝ) (N : ℕ) (x : B) : + Q.partialGreen N (fun y => ∑ j ∈ s,f j y) x = ∑ j ∈ s,Q.partialGreen N (f j) x := by + unfold partialGreen + simp_rw [Q.iterate_sum] + exact Finset.sum_comm +end KilledKernel + +namespace FiniteChain +open scoped BigOperators Classical +variable {X : Type*} [Fintype X] (C : FiniteChain X) (A : X → Prop) + (Q : KilledKernel (Outside A)) (hQ : ∀ x y,Q.Q x y=C.P x.val y.val) + +noncomputable def cappedTrace (N : ℕ) (x y : Inside A) : ℝ := + C.P x.val y.val + ∑ z : Outside A,C.P x.val z.val* + Q.partialGreen N (fun t => C.P t.val y.val) z +lemma cappedTrace_nonneg (N : ℕ) (x y : Inside A) : 0 ≤ C.cappedTrace A Q N x y := by + apply add_nonneg (C.nonnegative _ _) + exact Finset.sum_nonneg (fun z _ => mul_nonneg (C.nonnegative _ _) + (Q.partialGreen_nonneg N _ (fun t => C.nonnegative _ _) z)) +lemma cappedTrace_le (N : ℕ) (x y : Inside A) : C.cappedTrace A Q N x y ≤ C.traceMatrix A Q x y := by + unfold cappedTrace traceMatrix + apply add_le_add_right + apply Finset.sum_le_sum + intro z _ + exact mul_le_mul_of_nonneg_left (Q.partialGreen_le N _ (fun t => C.nonnegative _ _) z) (C.nonnegative _ _) +include hQ in +lemma cappedTrace_mass (N : ℕ) (x : Inside A) : + ∑ y,C.cappedTrace A Q N x y = 1-∑ z : Outside A,C.P x.val z.val*Q.iterate N (fun _ => 1) z := by + unfold cappedTrace + rw [Finset.sum_add_distrib,Finset.sum_comm] + simp_rw [← Finset.mul_sum,← Q.partialGreen_sum] + have he : (fun t : Outside A => ∑ y : Inside A,C.P t.val y.val) = + fun t => 1-Q.apply (fun _ => 1) t := by + funext t + exact C.exitRow A Q hQ t + rw [he] + simp_rw [KilledKernel.partialGreen,Q.iterate_residual_sum,mul_sub,mul_one,Finset.sum_sub_distrib] + have hs := Fintype.sum_subtype_add_sum_subtype A (fun y => C.P x.val y) + rw [C.stochastic] at hs + linarith + +include hQ in +lemma cappedTrace_loss (N : ℕ) (x : Inside A) : + (N:ℝ)*(1-∑ y,C.cappedTrace A Q N x y) ≤ C.returnCost A Q x := by + rw [C.cappedTrace_mass A Q hQ] + simp only [sub_sub_cancel] + calc + _ = ∑ z : Outside A,C.P x.val z.val*((N:ℝ)*Q.iterate N (fun _ => 1) z) := by + rw [Finset.mul_sum]; apply Finset.sum_congr rfl; intro z _; ring + _ ≤ ∑ z : Outside A,C.P x.val z.val*duration A Q z := + Finset.sum_le_sum (fun z _ => mul_le_mul_of_nonneg_left (Q.duration_tail N z) (C.nonnegative _ _)) + _ ≤ _ := by unfold returnCost; linarith + +include hQ in +lemma cappedTrace_substochastic (N : ℕ) (x : Inside A) : ∑ y,C.cappedTrace A Q N x y ≤ 1 := by + calc + _ ≤ ∑ y,C.traceMatrix A Q x y := Finset.sum_le_sum (fun y _ => C.cappedTrace_le A Q N x y) + _ = 1 := C.traceMatrix_stochastic A Q hQ x + +lemma cappedTrace_warm_loss [Nonempty (Inside A)] (N : ℕ) (U : ℝ) (ν : Inside A → ℝ) + (hν : ∀ x,0 ≤ ν x) (hwarm : ∀ x,ν x ≤ U*(C.traceChain A Q hQ).π x) : + (N:ℝ)*(∑ x,ν x*(1-∑ y,C.cappedTrace A Q N x y)) ≤ U/C.insideMass A := by + calc + _ = ∑ x,ν x*((N:ℝ)*(1-∑ y,C.cappedTrace A Q N x y)) := by + rw [Finset.mul_sum]; apply Finset.sum_congr rfl; intro x _; ring + _ ≤ ∑ x,ν x*C.returnCost A Q x := Finset.sum_le_sum (fun x _ => + mul_le_mul_of_nonneg_left (C.cappedTrace_loss A Q hQ N x) (hν x)) + _ ≤ _ := C.warm_returnCost A Q hQ ν U hwarm +end FiniteChain + +structure FiniteKernel (X Y : Type*) [Fintype Y] where + P : X → Y → ℝ + nonnegative : ∀ x y,0 ≤ P x y + substochastic : ∀ x,∑ y,P x y ≤ 1 +namespace FiniteKernel +open scoped BigOperators Classical +variable {X Y Z : Type*} [Fintype X] [Fintype Y] [Fintype Z] +noncomputable def identity : FiniteKernel X X where + P x y := if x=y then 1 else 0 + nonnegative := by intros; split_ifs <;> norm_num + substochastic := by intro x; simp +noncomputable def comp (K : FiniteKernel X Y) (L : FiniteKernel Y Z) : FiniteKernel X Z where + P x z := ∑ y,K.P x y*L.P y z + nonnegative := by intros; exact Finset.sum_nonneg (fun y _ => mul_nonneg (K.nonnegative _ _) (L.nonnegative _ _)) + substochastic := by + intro x + rw [Finset.sum_comm] + simp_rw [← Finset.mul_sum] + calc + _ ≤ ∑ y,K.P x y*1 := Finset.sum_le_sum (fun y _ => mul_le_mul_of_nonneg_left (L.substochastic y) (K.nonnegative x y)) + _ ≤ 1 := by simp only [mul_one]; exact K.substochastic x +noncomputable def push (K : FiniteKernel X Y) (ν : X → ℝ) (y : Y) := ∑ x,ν x*K.P x y +lemma push_nonneg (K : FiniteKernel X Y) (ν : X → ℝ) (hν : ∀ x,0 ≤ ν x) (y : Y) : + 0 ≤ K.push ν y := Finset.sum_nonneg (fun x _ => mul_nonneg (hν x) (K.nonnegative x y)) +lemma push_mono (K : FiniteKernel X Y) {ν ν' : X → ℝ} (h : ∀ x,ν x ≤ ν' x) (y : Y) : + K.push ν y ≤ K.push ν' y := Finset.sum_le_sum (fun x _ => mul_le_mul_of_nonneg_right (h x) (K.nonnegative x y)) +lemma push_comp (K : FiniteKernel X Y) (L : FiniteKernel Y Z) (ν : X → ℝ) : + (K.comp L).push ν = L.push (K.push ν) := by + funext z + simp only [push,comp,Finset.mul_sum,Finset.sum_mul,mul_assoc] + exact Finset.sum_comm +lemma push_identity (ν : X → ℝ) : (identity : FiniteKernel X X).push ν = ν := by + funext x; simp [push,identity] +lemma push_mass (K : FiniteKernel X Y) (ν : X → ℝ) : + ∑ y,K.push ν y = ∑ x,ν x*(∑ y,K.P x y) := by + unfold push; rw [Finset.sum_comm]; simp_rw [← Finset.mul_sum] +lemma push_mass_le (K : FiniteKernel X Y) (ν : X → ℝ) (hν : ∀ x,0 ≤ ν x) : + ∑ y,K.push ν y ≤ ∑ x,ν x := by + rw [K.push_mass] + exact Finset.sum_le_sum (fun x _ => by simpa using mul_le_mul_of_nonneg_left (K.substochastic x) (hν x)) +noncomputable def power (K : FiniteKernel X X) : ℕ → FiniteKernel X X + | 0 => identity + | n+1 => (K.power n).comp K +lemma power_push_succ (K : FiniteKernel X X) (n : ℕ) (ν : X → ℝ) : + (K.power (n+1)).push ν = K.push ((K.power n).push ν) := (K.power n).push_comp K ν +lemma push_domination (K L : FiniteKernel X Y) (hKL : ∀ x y,K.P x y ≤ L.P x y) + (ν : X → ℝ) (hν : ∀ x,0 ≤ ν x) (y : Y) : K.push ν y ≤ L.push ν y := + Finset.sum_le_sum (fun x _ => mul_le_mul_of_nonneg_left (hKL x y) (hν x)) +lemma power_domination (K L : FiniteKernel X X) (hKL : ∀ x y,K.P x y ≤ L.P x y) + (n : ℕ) (ν : X → ℝ) (hν : ∀ x,0 ≤ ν x) (y : X) : + (K.power n).push ν y ≤ (L.power n).push ν y := by + induction n generalizing y with + | zero => exact le_rfl + | succ n ih => + rw [K.power_push_succ,L.power_push_succ] + exact (K.push_mono (fun y => ih y) y).trans + (K.push_domination L hKL _ ((L.power n).push_nonneg ν hν) y) + +lemma one_step_defect (K L : FiniteKernel X Y) (hL : ∀ x,∑ y,L.P x y=1) + (a b : X → ℝ) (_ : ∀ x,0 ≤ a x) (hab : ∀ x,a x ≤ b x) : + (∑ y,L.push b y)-(∑ y,K.push a y) ≤ + (∑ x,b x)-(∑ x,a x)+∑ x,b x*(1-∑ y,K.P x y) := by + rw [L.push_mass,K.push_mass] + simp_rw [hL,mul_one] + have hh : ∑ x,a x*(1-∑ y,K.P x y) ≤ ∑ x,b x*(1-∑ y,K.P x y) := + Finset.sum_le_sum (fun x _ => mul_le_mul_of_nonneg_right (hab x) (sub_nonneg.mpr (K.substochastic x))) + simp_rw [mul_sub,mul_one,Finset.sum_sub_distrib] at hh ⊢ + linarith +end FiniteKernel + +namespace FiniteChain + +section +open scoped BigOperators Classical +variable {X : Type*} [Fintype X] (C : FiniteChain X) +noncomputable def kernel : FiniteKernel X X where + P := C.P + nonnegative := C.nonnegative + substochastic := fun x => (C.stochastic x).le +lemma kernel_stationary : C.kernel.push C.π = C.π := by + funext y; exact C.stationary y +lemma push_warm (ν : X → ℝ) (U : ℝ) (hν : ∀ x,ν x ≤ U*C.π x) (y : X) : + C.kernel.push ν y ≤ U*C.π y := by + calc + _ ≤ ∑ x,U*C.π x*C.P x y := C.kernel.push_mono hν y + _ = U*C.π y := by simp only [mul_assoc,← Finset.mul_sum,C.stationary] +lemma power_warm (n : ℕ) (ν : X → ℝ) (U : ℝ) (hν : ∀ x,ν x ≤ U*C.π x) (y : X) : + (C.kernel.power n).push ν y ≤ U*C.π y := by + induction n generalizing y with + | zero => simpa [FiniteKernel.power,FiniteKernel.push_identity] using hν y + | succ n ih => rw [FiniteKernel.power_push_succ]; exact C.push_warm _ U (fun y => ih y) y +lemma kernel_power_stochastic (n : ℕ) (x : X) : ∑ y,(C.kernel.power n).P x y=1 := by + induction n with + | zero => simp [FiniteKernel.power,FiniteKernel.identity] + | succ n ih => + change (∑ y,∑ z,(C.kernel.power n).P x z*C.P z y) = 1 + rw [Finset.sum_comm] + simp_rw [← Finset.mul_sum,C.stochastic,mul_one] + exact ih +lemma power_push_mass (n : ℕ) (ν : X → ℝ) : ∑ y,(C.kernel.power n).push ν y = ∑ x,ν x := by + rw [FiniteKernel.push_mass] + simp_rw [C.kernel_power_stochastic,mul_one] + +lemma capped_power_mass (K : FiniteKernel X X) (hK : ∀ x y,K.P x y≤C.P x y) + (ν : X → ℝ) (hν : ∀ x,0≤ν x) (hnorm : ∑ x,ν x=1) + (U e : ℝ) (hwarm : ∀ x,ν x≤U*C.π x) + (hloss : ∀ a : X → ℝ,(∀ x,0≤a x) → (∀ x,a x≤U*C.π x) → + (∑ x,a x*(1-∑ y,K.P x y))≤e) (T : ℕ) : + 1-(∑ x,(K.power T).push ν x)≤(T:ℝ)*e := by + have hdom := fun n x => K.power_domination C.kernel hK n ν hν x + induction T with + | zero => simp [FiniteKernel.power,FiniteKernel.push_identity,hnorm] + | succ T ih => + have h := K.one_step_defect C.kernel C.stochastic + ((K.power T).push ν) ((C.kernel.power T).push ν) + ((K.power T).push_nonneg ν hν) (hdom T) + have hl := hloss ((C.kernel.power T).push ν) + ((C.kernel.power T).push_nonneg ν hν) (C.power_warm T ν U hwarm) + have hm := C.power_push_mass T ν + have hm' := C.power_push_mass (T+1) ν + rw [FiniteKernel.power_push_succ] at hm' + rw [FiniteKernel.power_push_succ] + simp only [hnorm] at hm hm' + rw [hm,hm'] at h + push_cast + linarith + +variable (A : X → Prop) (Q : KilledKernel (Outside A)) (hQ : ∀ x y,Q.Q x y=C.P x.val y.val) +noncomputable def cappedTraceKernel (N : ℕ) : FiniteKernel (Inside A) (Inside A) where + P := C.cappedTrace A Q N + nonnegative := C.cappedTrace_nonneg A Q N + substochastic := C.cappedTrace_substochastic A Q hQ N +lemma cappedTrace_power_mass [Nonempty (Inside A)] (N T : ℕ) (hN : 0 exact h _ + | succ N ih => + apply Finset.sum_le_sum + intro y _ + exact mul_le_mul_of_nonneg_left (ih y _ _ (fun l => h _)) (C.nonnegative x y) +lemma pathExpectation_finsum {J : Type*} (s : Finset J) (N : ℕ) (x : X) (F : J → List X → ℝ) : + C.pathExpectation N x (fun l => ∑ j ∈ s,F j l) = ∑ j ∈ s,C.pathExpectation N x (F j) := by + induction s using Finset.induction_on with + | empty => simp [C.pathExpectation_const] + | @insert j s hj ih => simp [Finset.sum_insert,hj,C.pathExpectation_add,ih] +lemma pathExpectation_congr_length (N : ℕ) (x : X) (F G : List X → ℝ) + (h : ∀ l,l.length=N+1 → F l=G l) : C.pathExpectation N x F=C.pathExpectation N x G := by + induction N generalizing x F G with + | zero => exact h [x] rfl + | succ N ih => + apply Finset.sum_congr rfl + intro y _ + congr 1 + apply ih + intro l hl + exact h (x::l) (by simp [hl]) +omit sectionInstance81 in +lemma pathSum_center [Fintype X] (G : X → ℝ) (m : ℝ) (l : List X) : + pathSum (fun x => G x-m) l = pathSum G l-(l.length:ℝ)*m := by + induction l with + | nil => simp [pathSum] + | cons x l ih => simp only [pathSum_cons,List.length_cons,Nat.cast_add,Nat.cast_one]; rw [ih]; ring + +noncomputable def pathProbability (ν : X → ℝ) (N : ℕ) (E : List X → Prop) : ℝ := + ∑ x,ν x*C.pathExpectation N x (fun l => if E l then 1 else 0) +lemma pathProbability_nonneg (ν : X → ℝ) (hν : ∀ x,0≤ν x) (N : ℕ) (E : List X → Prop) : + 0≤C.pathProbability ν N E := Finset.sum_nonneg (fun x _ => mul_nonneg (hν x) + (C.pathExpectation_nonneg N x _ (by intro l; split_ifs <;> norm_num))) +lemma pathProbability_mono (ν : X → ℝ) (hν : ∀ x,0≤ν x) (N : ℕ) (E F : List X → Prop) + (h : ∀ l,E l → F l) : C.pathProbability ν N E≤C.pathProbability ν N F := by + apply Finset.sum_le_sum + intro x _ + apply mul_le_mul_of_nonneg_left _ (hν x) + apply C.pathExpectation_mono + intro l + by_cases he : E l + · simp [he,h l he] + · simp [he]; split_ifs <;> norm_num +lemma pathProbability_union {J : Type*} [Fintype J] (ν : X → ℝ) (hν : ∀ x,0≤ν x) + (N : ℕ) (E : J → List X → Prop) : + C.pathProbability ν N (fun l => ∃ j,E j l) ≤ ∑ j,C.pathProbability ν N (E j) := by + classical + have h : ∀ l,(if ∃ j,E j l then (1:ℝ) else 0)≤∑ j,if E j l then 1 else 0 := by + intro l + by_cases he : ∃ j,E j l + · obtain ⟨j,hj⟩ := he + rw [ite_eq_left ⟨j,hj⟩] + calc + (1:ℝ) = (if E j l then 1 else 0) := by simp [hj] + _ ≤ ∑ j,if E j l then 1 else 0 := Finset.single_le_sum (f := fun j => if E j l then (1:ℝ) else 0) + (fun j _ => by split_ifs <;> norm_num) (Finset.mem_univ j) + · simp [show ∀ j,¬E j l from fun j hj => he ⟨j,hj⟩] + unfold pathProbability + calc + _ = ∑ x,ν x*C.pathExpectation N x (fun l => if ∃ j,E j l then 1 else 0) := by + apply Finset.sum_congr rfl + intro x _ + congr 1 + apply C.pathExpectation_congr + intro l + split_ifs <;> rfl + _ ≤ ∑ x,ν x*C.pathExpectation N x (fun l => ∑ j,if E j l then 1 else 0) := + Finset.sum_le_sum (fun x _ => mul_le_mul_of_nonneg_left (C.pathExpectation_mono N x _ _ h) (hν x)) + _ = _ := by simp_rw [C.pathExpectation_finsum,Finset.mul_sum]; exact Finset.sum_comm + +lemma pathProbability_average_error (ν : X → ℝ) (hν : ∀ x,0≤ν x) (G : X → ℝ) + (m t : ℝ) (ht : 0 t < |pathSum G l/(N:ℝ)-m|) ≤ + ((∑ x,ν x*C.squareMoment (fun x => G x-m) N x)/(N:ℝ)^2)/t^2 := by + have hn : (0:ℝ) + mul_le_mul_of_nonneg_left (C.pathExpectation_mono (N-1) x _ _ hpoint) (hν x)) + change C.pathProbability ν (N-1) _ ≤ _ at h + have he : ∀ x,C.pathExpectation (N-1) x (fun l => (pathSum G l/(N:ℝ)-m)^2/t^2) = + C.squareMoment (fun x => G x-m) N x/(N:ℝ)^2/t^2 := by + intro x + rw [squareMoment,ite_eq_right (Nat.ne_of_gt hN)] + have hh : C.pathExpectation (N-1) x (fun l => (pathSum G l/(N:ℝ)-m)^2/t^2) = + C.pathExpectation (N-1) x (fun l => (1/(N:ℝ)^2/t^2)*(pathSum (fun x => G x-m) l)^2) := by + apply C.pathExpectation_congr_length + intro l hl + have hl' : l.length=N := by omega + rw [pathSum_center,hl'] + field_simp + + rw [hh,C.pathExpectation_mul] + ring + simp_rw [he] at h + simpa only [← mul_div_assoc,← Finset.sum_div] using h +end + +open scoped BigOperators Classical +variable {X : Type*} [Fintype X] (C : FiniteChain X) +lemma variance_le_one (G : X → ℝ) (hG : ∀ x,0≤G x ∧ G x≤1) : C.variance G≤1 := by + rw [C.variance_formula] + have h : C.inner G G≤1 := by + calc + _ ≤ ∑ x,C.π x*1 := Finset.sum_le_sum (fun x _ => by + have hx := hG x + have hh : G x*G x≤1 := by nlinarith + simpa only [mul_assoc] using mul_le_mul_of_nonneg_left hh (C.positive x).le) + _ = 1 := by simpa using C.normalized + nlinarith [sq_nonneg (C.mean G)] + +lemma relative_union_bound {J : Type*} [Fintype J] + (ν : X → ℝ) (hν : ∀ x,0≤ν x) (G : J → X → ℝ) + (m η v : ℝ) (hm : 0 < m) (hη : 0<η) (hv : 0≤v) + (hmean : ∀ j,m≤C.mean (G j)) (N : ℕ) (hN : 0 G j x-C.mean (G j)) N x)/(N:ℝ)^2≤v) : + C.pathProbability ν (N-1) (fun l => ∃ j,η*C.mean (G j) < + |pathSum (G j) l/(N:ℝ)-C.mean (G j)|) ≤ (Fintype.card J:ℝ)*v/(η*m)^2 := by + calc + _ ≤ ∑ j,C.pathProbability ν (N-1) (fun l => η*C.mean (G j) < + |pathSum (G j) l/(N:ℝ)-C.mean (G j)|) := C.pathProbability_union ν hν (N-1) _ + _ ≤ ∑ j,v/(η*m)^2 := by + apply Finset.sum_le_sum + intro j _ + have hj : 0 G S.val-C.mean (fun S => G S.val)) N S)/(N:ℝ)^2 ≤ + 40000*(gs.length:ℝ)^8/N := by + have h := metropolisChain_timeAverage gs hgs hne hcover w f G hw hf hsig hG + hlower hupper (10*(gs.length:ℝ)^2) (by positivity) ν hwarm N hN + have hv := (metropolisChain gs hgs hne hcover w f hw hf).variance_le_one + (fun S => G S.val) (fun S => hbounded S.val S.property) + rw [metropolisChain_variance] at hv + dsimp only + rw [metropolisChain_mean] + calc + _ ≤ _ := h + _ ≤ 2*(10*(gs.length:ℝ)^2)*(2000*(gs.length:ℝ)^6)*1/N := + div_le_div_of_nonneg_right (mul_le_mul_of_nonneg_left hv (by positivity)) (by positivity) + _ = _ := by ring + +lemma phase_error_arithmetic (n L J N : ℕ) (hn : 0 f S*g S) ∅/chainTotal gs w f := by + unfold chainMean + congr 1 + simp only [chainWeight,mul_assoc] + rw [chain_sum_decomposition,slotTotal_eq_plain_sum gs hgs hcover] + have hplain : (∑ S with PlainState gs S,f S*plainObservable gs g S)= + ∑ S with PlainState gs S,f S*g S := by + apply Finset.sum_congr rfl + intro S hS + simp [plainObservable,(Finset.mem_filter.mp hS).2] + rw [hplain] + have hdef : ∀ pr ∈ defectTypes gs,(∑ S with DefectState gs pr.1 pr.2 S,f S*plainObservable gs g S)=0 := by + intro pr hpr + apply Finset.sum_eq_zero + intro S hS + simp [plainObservable,((Finset.mem_filter.mp hS).2).not_plain] + rw [add_eq_left] + apply Finset.sum_eq_zero + intro pr hpr + rw [hdef pr hpr,mul_zero] +lemma defectIndicator_mean (gs : List (Γ × Γ)) (hgs : SlotsFresh gs ∅) + (hcover : pairSupport gs=Set.univ) (w : (Γ × Γ) → (Γ × Γ) → ℝ) + (f : Set Γ → ℝ) (p r : Γ × Γ) (hp : p∈gs) (hr : r∈gs) (hpr : p≠r) : + chainMean gs w f (defectIndicator gs p r) = + w p r*slotDefect gs f ∅ p r/chainTotal gs w f := by + unfold chainMean + congr 1 + simp only [chainWeight,mul_assoc] + rw [chain_sum_decomposition,slotDefect_eq_defect_sum gs hgs hcover f p r hp hr hpr] + have hplain : (∑ S with PlainState gs S,f S*defectIndicator gs p r S)=0 := by + apply Finset.sum_eq_zero + intro S hS + have hh : ¬DefectState gs p r S := fun h => h.not_plain (Finset.mem_filter.mp hS).2 + simp [defectIndicator,hh] + rw [hplain,zero_add] + rw [Finset.sum_eq_single (p,r)] + · congr 1 + apply Finset.sum_congr rfl + intro S hS + simp [defectIndicator,(Finset.mem_filter.mp hS).2] + · intro pr hm hne + have he : ∀ S,DefectState gs pr.1 pr.2 S → ¬DefectState gs p r S := by + intro S hS h + exact hne (Prod.ext (hS.unique h).1 (hS.unique h).2) + have hz : (∑ S with DefectState gs pr.1 pr.2 S,f S*defectIndicator gs p r S)=0 := by + apply Finset.sum_eq_zero + intro S hS + simp [defectIndicator,he S (Finset.mem_filter.mp hS).2] + rw [hz,mul_zero] + · intro h + exact (h ((mem_defectTypes gs (p,r)).mpr ⟨hp,hr,hpr⟩)).elim +lemma plain_mass_lower (gs : List (Γ × Γ)) (hgs : SlotsFresh gs ∅) (hne : gs≠[]) + (hcover : pairSupport gs=Set.univ) (w : (Γ × Γ) → (Γ × Γ) → ℝ) + (f : Set Γ → ℝ) (hw : ∀ p r,0 < w p r) (hf : ∀ S,0 < f S) + (hupper : ∀ p∈gs,∀ r∈gs,p≠r → w p r ≤ 4*slotTotal gs f ∅/slotDefect gs f ∅ p r) : + 1/(5*(gs.length:ℝ)^2) ≤ slotTotal gs f ∅/chainTotal gs w f := by + have hz := slotTotal_pos gs f hf ∅ hgs + have hΛ := chainTotal_pos gs hgs hcover w f hf hw + have hn : (0:ℝ) < gs.length := by exact_mod_cast List.length_pos_iff.mpr hne + apply (div_le_div_iff₀ (by positivity) hΛ).mpr + simpa only [one_mul,mul_one,mul_comm] using chainTotal_le gs hgs hne hcover w f hf hupper +lemma defect_mass_lower (gs : List (Γ × Γ)) (hgs : SlotsFresh gs ∅) (hne : gs≠[]) + (hcover : pairSupport gs=Set.univ) (w : (Γ × Γ) → (Γ × Γ) → ℝ) + (f : Set Γ → ℝ) (hw : ∀ p r,0 < w p r) (hf : ∀ S,0 < f S) + (hlower : ∀ p∈gs,∀ r∈gs,p≠r → slotTotal gs f ∅/(4*slotDefect gs f ∅ p r) ≤ w p r) + (hupper : ∀ p∈gs,∀ r∈gs,p≠r → w p r ≤ 4*slotTotal gs f ∅/slotDefect gs f ∅ p r) + (p r : Γ × Γ) (hp : p∈gs) (hr : r∈gs) (hpr : p≠r) : + 1/(20*(gs.length:ℝ)^2) ≤ chainMean gs w f (defectIndicator gs p r) := by + rw [defectIndicator_mean gs hgs hcover w f p r hp hr hpr] + have hc := slotDefect_pos gs f hf ∅ hgs p r hp hr hpr + have hΛ := chainTotal_pos gs hgs hcover w f hf hw + have hwc : slotTotal gs f ∅/4 ≤ w p r*slotDefect gs f ∅ p r := by + have h := (div_le_iff₀ (show 0 < 4*slotDefect gs f ∅ p r by positivity)).mp (hlower p hp r hr hpr) + linarith + calc + _ = (1/(5*(gs.length:ℝ)^2))/4 := by ring + _ ≤ (slotTotal gs f ∅/chainTotal gs w f)/4 := + div_le_div_of_nonneg_right (plain_mass_lower gs hgs hne hcover w f hw hf hupper) (by norm_num) + _ = (slotTotal gs f ∅/4)/chainTotal gs w f := by ring + _ ≤ _ := div_le_div_of_nonneg_right hwc hΛ.le +lemma chainMean_mono (gs : List (Γ × Γ)) (hgs : SlotsFresh gs ∅) + (hcover : pairSupport gs=Set.univ) (w : (Γ × Γ) → (Γ × Γ) → ℝ) + (f G H : Set Γ → ℝ) (hw : ∀ p r,0 < w p r) (hf : ∀ S,0 < f S) + (h : ∀ S,ChainState gs S → G S ≤ H S) : chainMean gs w f G ≤ chainMean gs w f H := by + apply div_le_div_of_nonneg_right _ (chainTotal_pos gs hgs hcover w f hf hw).le + apply Finset.sum_le_sum + intro S hS + exact mul_le_mul_of_nonneg_left (h S (Finset.mem_filter.mp hS).2) + (mul_nonneg (chainMultiplier_pos gs w hw S).le (hf S).le) +lemma plainObservable_mass_lower (gs : List (Γ × Γ)) (hgs : SlotsFresh gs ∅) (hne : gs≠[]) + (hcover : pairSupport gs=Set.univ) (w : (Γ × Γ) → (Γ × Γ) → ℝ) + (f g : Set Γ → ℝ) (hw : ∀ p r,0 < w p r) (hf : ∀ S,0 < f S) + (hg : ∀ S,PlainState gs S → 1/2 ≤ g S) + (hupper : ∀ p∈gs,∀ r∈gs,p≠r → w p r ≤ 4*slotTotal gs f ∅/slotDefect gs f ∅ p r) : + 1/(20*(gs.length:ℝ)^2) ≤ chainMean gs w f (plainObservable gs g) := by + have hm := chainMean_mono gs hgs hcover w f (plainObservable gs (fun _ => 1/2)) + (plainObservable gs g) hw hf (by intro S hS; unfold plainObservable; split_ifs with hp; exact hg S hp; rfl) + rw [plainObservable_mean gs hgs hcover] at hm + have he : slotTotal gs (fun S => f S*(1/2)) ∅ = (1/2)*slotTotal gs f ∅ := by + have hfun : (fun S => f S*(1/2)) = fun S => (1/2)*f S := by funext S; ring + rw [hfun] + exact coeffDerivs_scale _ _ _ _ + rw [he] at hm + have hl := plain_mass_lower gs hgs hne hcover w f hw hf hupper + have hn : (0:ℝ) < gs.length := by exact_mod_cast List.length_pos_iff.mpr hne + have hp : 0 ≤ 1/(5*(gs.length:ℝ)^2) := by positivity + calc + _ ≤ (1/(5*(gs.length:ℝ)^2))/2 := by field_simp; norm_num + _ ≤ (slotTotal gs f ∅/chainTotal gs w f)/2 := div_le_div_of_nonneg_right hl (by norm_num) + _ ≤ _ := by convert hm using 1 ; ring + +abbrev PhaseObservables (gs : List (Γ × Γ)) := Option {pr // pr∈defectTypes gs} ⊕ Unit +lemma phaseObservables_card (gs : List (Γ × Γ)) (hgs : SlotsFresh gs ∅) (hne : gs≠[]) : + Fintype.card (PhaseObservables gs) ≤ 2*gs.length^2 := by + have hn := List.length_pos_iff.mpr hne + have hc : (defectTypes gs).card=gs.length*gs.length-gs.length := by + rw [defectTypes,Finset.offDiag_card,List.toFinset_card_of_nodup hgs.nodup] + simp only [PhaseObservables,Fintype.card_sum,Fintype.card_option,Fintype.card_coe,Fintype.card_unit,hc] + have hh : gs.length ≤ gs.length*gs.length := by nlinarith + rw [pow_two] + omega +noncomputable def phaseObservable (gs : List (Γ × Γ)) (g : Set Γ → ℝ) : + PhaseObservables gs → Set Γ → ℝ + | .inl none => plainObservable gs (fun _ => 1) + | .inl (some pr) => defectIndicator gs pr.val.1 pr.val.2 + | .inr _ => plainObservable gs g +lemma phaseObservable_class (gs : List (Γ × Γ)) (g : Set Γ → ℝ) (j : PhaseObservables gs) : + ClassObservable gs (phaseObservable gs g j) := by + rcases j with (_ | pr) | u + · exact plainObservable_class gs _ + · exact defectIndicator_class gs _ _ + · exact plainObservable_class gs _ +omit sectionInstance85 in +lemma phaseObservable_bounded [Fintype Γ] (gs : List (Γ × Γ)) (g : Set Γ → ℝ) + (hg : ∀ S,PlainState gs S → 0 ≤ g S ∧ g S ≤ 1) + (j : PhaseObservables gs) (S : Set Γ) : + 0 ≤ phaseObservable gs g j S ∧ phaseObservable gs g j S ≤ 1 := by + rcases j with (_ | pr) | u + · simp only [phaseObservable,plainObservable]; split_ifs <;> norm_num + · simp only [phaseObservable,defectIndicator]; split_ifs <;> norm_num + · simp only [phaseObservable,plainObservable]; split_ifs with h + · exact hg S h + · norm_num +lemma phaseObservable_mean_lower (gs : List (Γ × Γ)) (hgs : SlotsFresh gs ∅) (hne : gs≠[]) + (hcover : pairSupport gs=Set.univ) (w : (Γ × Γ) → (Γ × Γ) → ℝ) + (f g : Set Γ → ℝ) (hw : ∀ p r,0 < w p r) (hf : ∀ S,0 < f S) + (hg : ∀ S,PlainState gs S → 1/2 ≤ g S) + (hlower : ∀ p∈gs,∀ r∈gs,p≠r → slotTotal gs f ∅/(4*slotDefect gs f ∅ p r) ≤ w p r) + (hupper : ∀ p∈gs,∀ r∈gs,p≠r → w p r ≤ 4*slotTotal gs f ∅/slotDefect gs f ∅ p r) + (j : PhaseObservables gs) : + 1/(20*(gs.length:ℝ)^2) ≤ chainMean gs w f (phaseObservable gs g j) := by + rcases j with (_ | pr) | u + · exact plainObservable_mass_lower gs hgs hne hcover w f _ hw hf (by intros; norm_num) hupper + · obtain ⟨hp,hr,hpr⟩ := (mem_defectTypes gs pr.val).mp pr.property + exact defect_mass_lower gs hgs hne hcover w f hw hf hlower hupper _ _ hp hr hpr + · exact plainObservable_mass_lower gs hgs hne hcover w f g hw hf hg hupper + +theorem metropolis_phase_failure (gs : List (Γ × Γ)) (hgs : SlotsFresh gs ∅) (hne : gs≠[]) + (hcover : pairSupport gs=Set.univ) (w : (Γ × Γ) → (Γ × Γ) → ℝ) + (f g : Set Γ → ℝ) (hw : ∀ p r,0 < w p r) (hf : ∀ S,0 < f S) + (hsig : HasSlotSignature f) (hg : ∀ S,PlainState gs S → 1/2 ≤ g S ∧ g S ≤ 1) + (hlower : ∀ p∈gs,∀ r∈gs,p≠r → slotTotal gs f ∅/(4*slotDefect gs f ∅ p r) ≤ w p r) + (hupper : ∀ p∈gs,∀ r∈gs,p≠r → w p r ≤ 4*slotTotal gs f ∅/slotDefect gs f ∅ p r) + (ν : ChainIndex gs → ℝ) (hν : ∀ S,0 ≤ ν S) + (hwarm : ∀ S,ν S ≤ (10*(gs.length:ℝ)^2)*chainWeight gs w f S.val/chainTotal gs w f) + (L N : ℕ) (η : ℝ) (hη : 0 < η) + (hN : (10:ℝ)^10*(L+1)*gs.length^14/η^2 ≤ N) : + let C := metropolisChain gs hgs hne hcover w f hw hf + C.pathProbability ν (N-1) (fun l => ∃ j : PhaseObservables gs, + η*C.mean (fun S => phaseObservable gs g j S.val) < + |FiniteChain.pathSum (fun S => phaseObservable gs g j S.val) l/(N:ℝ)- + C.mean (fun S => phaseObservable gs g j S.val)|) ≤ 1/(32*(L+1:ℝ)) := by + let C := metropolisChain gs hgs hne hcover w f hw hf + have hn : 0 < gs.length := List.length_pos_iff.mpr hne + have hn' : (0:ℝ) < gs.length := by exact_mod_cast hn + have hN' : (0:ℝ) < N := lt_of_lt_of_le (by positivity) hN + have hNm : 0 < N := by exact_mod_cast hN' + have hμ : ∀ j,1/(20*(gs.length:ℝ)^2) ≤ C.mean (fun S => phaseObservable gs g j S.val) := by + intro j + rw [metropolisChain_mean] + exact phaseObservable_mean_lower gs hgs hne hcover w f g hw hf (fun S hS => (hg S hS).1) + hlower hupper j + have hb := C.relative_union_bound ν hν (fun j S => phaseObservable gs g j S.val) + (1/(20*(gs.length:ℝ)^2)) η (40000*(gs.length:ℝ)^8/N) (by positivity) hη (by positivity) + hμ N hNm (fun j => metropolisChain_bounded_MSE gs hgs hne hcover w f + (phaseObservable gs g j) hw hf hsig (phaseObservable_class gs g j) + (fun S _ => phaseObservable_bounded gs g (fun S hS => ⟨by linarith [(hg S hS).1],(hg S hS).2⟩) j S) + hlower hupper ν hwarm N hNm) + exact hb.trans (phase_error_arithmetic gs.length L (Fintype.card (PhaseObservables gs)) N hn + (phaseObservables_card gs hgs hne) η hη hN) +end SamplingObservables + +open Set + +section PairedReduction +variable {α β : Type*} + +lemma sum_eRank (M : Matroid α) (N : Matroid β) : + (M.sum N).eRank = M.eRank + N.eRank := by + obtain ⟨B,hB⟩ := M.exists_isBase + obtain ⟨C,hC⟩ := N.exists_isBase + have hBC : (M.sum N).IsBase (Sum.inl '' B ∪ Sum.inr '' C) := by + rw [Matroid.sum_isBase_iff] + simpa [Set.preimage_image_eq _ Sum.inl_injective, + Set.preimage_image_eq _ Sum.inr_injective] using And.intro hB hC + rw [← hBC.encard_eq_eRank, Set.encard_union_eq, + Set.InjOn.encard_image, Set.InjOn.encard_image, + hB.encard_eq_eRank, hC.encard_eq_eRank] + · exact Sum.inr_injective.injOn + · exact Sum.inl_injective.injOn + · exact Set.disjoint_image_inl_image_inr + +def pairedMatroid (M₁ M₂ : Matroid α) : Matroid (α ⊕ α) := M₁.sum M₂✶ + +def transversal (A : Set α) : Set (α ⊕ α) := Sum.inl '' A ∪ Sum.inr '' Aᶜ + +@[simp] lemma preimage_inl_transversal (A : Set α) : + Sum.inl ⁻¹' transversal A = A := by + simp [transversal, Set.preimage_image_eq _ Sum.inl_injective] + +@[simp] lemma preimage_inr_transversal (A : Set α) : + Sum.inr ⁻¹' transversal A = Aᶜ := by + simp [transversal, + Set.preimage_image_eq _ Sum.inr_injective] + +lemma transversal_injective : Function.Injective (@transversal α) := by + intro A B h + have := congrArg (fun S => Sum.inl ⁻¹' S) h + simpa using this + +lemma paired_ground (M₁ M₂ : Matroid α) (h₁ : M₁.E = Set.univ) + (h₂ : M₂.E = Set.univ) : (pairedMatroid M₁ M₂).E = Set.univ := by + ext x + cases x <;> simp [pairedMatroid, h₁, h₂] + +lemma transversal_isBase_iff (M₁ M₂ : Matroid α) (h₂ : M₂.E = Set.univ) + (A : Set α) : + (pairedMatroid M₁ M₂).IsBase (transversal A) ↔ M₁.IsBase A ∧ M₂.IsBase A := by + simp only [pairedMatroid, Matroid.sum_isBase_iff, preimage_inl_transversal, + preimage_inr_transversal, Matroid.dual_isBase_iff', h₂, + ← Set.compl_eq_univ_sdiff, compl_compl, Set.subset_univ, and_true] + +lemma paired_eRank [Fintype α] (M₁ M₂ : Matroid α) (h₂ : M₂.E = Set.univ) + (hr : M₁.eRank = M₂.eRank) : + (pairedMatroid M₁ M₂).eRank = (Fintype.card α : ℕ∞) := by + rw [pairedMatroid, sum_eRank,hr, M₂.eRank_add_eRank_dual,h₂, + Set.encard_univ, ENat.card_eq_coe_fintype_card] + +lemma transversal_encard [Fintype α] (A : Set α) : + (transversal A).encard = (Fintype.card α : ℕ∞) := by + rw [transversal, Set.encard_union_eq, + Set.InjOn.encard_image, Set.InjOn.encard_image, + ← Set.encard_union_eq disjoint_compl_right, union_compl_self, Set.encard_univ, + ENat.card_eq_coe_fintype_card] + · exact Sum.inr_injective.injOn + · exact Sum.inl_injective.injOn + · exact Set.disjoint_image_inl_image_inr + +lemma transversal_ncard [Fintype α] (A : Set α) : + (transversal A).ncard = Fintype.card α := by + exact_mod_cast (Set.coe_ncard_eq_encard (transversal A)).trans (transversal_encard A) + +end PairedReduction + +open scoped BigOperators Classical + +noncomputable def annealRho (n : ℕ) : ℝ := 1 - 1 / (2 * (n : ℝ)) +def annealLength (n b : ℕ) : ℕ := 2*n*(n+b) +noncomputable def annealTolerance (ε : ℝ) (L : ℕ) : ℝ := ε/(32*((L:ℝ)+1)) + +lemma annealRho_bounds (n : ℕ) (hn : 0 pow_pos hq _) Finset.univ_nonempty +lemma coefficient_step (d : X → ℕ) (n : ℕ) (hn : 0 by + have := mul_le_mul_of_nonneg_left (annealStep_bounds n (d x) hn (hd x)).1 (pow_nonneg hq (d x)) + linarith) + · exact Finset.sum_le_sum (fun x _ => by + simpa using mul_le_mul_of_nonneg_left (annealStep_bounds n (d x) hn (hd x)).2 (pow_nonneg hq _)) +lemma normalized_drift [Nonempty X] (d : X → ℕ) (n : ℕ) (hn : 0 linarith + +lemma product_ratios (c : ℕ → ℝ) (hc : ∀ j,0 < c j) (L : ℕ) : + (∏ j ∈ Finset.range L,c (j+1)/c j) = c L/c 0 := by + induction L with + | zero => simp [ne_of_gt (hc 0)] + | succ L ih => + rw [Finset.prod_range_succ,ih] + field_simp [ne_of_gt (hc L),ne_of_gt (hc 0)] + +lemma relative_product_lower (a : ℕ → ℝ) (L : ℕ) (η : ℝ) (hη0 : 0≤η) (hη1 : η≤1/2) + (ha : ∀ j (ha j hj).1) + have hap : ∀ j (a j)⁻¹) L η hη0.le (by linarith) hainv + rw [Finset.prod_inv_distrib] at hinv + have hp : 0 < ∏ j ∈ Finset.range L,a j := Finset.prod_pos (fun j hj => hap j (Finset.mem_range.mp hj)) + have hlow : 1-ε/16 ≤ (∏ j ∈ Finset.range L,a j)⁻¹ := by linarith + have hmul := (le_div_iff₀ hp).mp (show 1-ε/16 ≤ 1/(∏ j ∈ Finset.range L,a j) by simpa only [one_div] using hlow) + constructor + · linarith + · nlinarith [mul_nonneg (show 0≤ε by linarith) (show 0≤1-ε by linarith)] + +lemma final_estimate_accuracy (ε Z C Zhat : ℝ) (hε0 : 0<ε) (hε1 : ε<1) (hZ : 0≤Z) + (hC : Z≤C ∧ C≤(1+ε/10)*Z) + (hhat : (1-ε/4)*C≤Zhat ∧ Zhat≤(1+ε/4)*C) : + (1-ε)*Z≤Zhat ∧ Zhat≤(1+ε)*Z := by + have hl := mul_le_mul_of_nonneg_left hC.1 (show 0≤1-ε/4 by linarith) + have hu := mul_le_mul_of_nonneg_left hC.2 (show 0≤1+ε/4 by linarith) + have he : (1+ε/4)*(1+ε/10)≤1+ε := by nlinarith [sq_nonneg ε] + have he' := mul_le_mul_of_nonneg_right he hZ + constructor <;> nlinarith [mul_nonneg hε0.le hZ] + +section Contamination +variable {X : Type*} [Fintype X] +noncomputable def zeroDeficiencyCount (d : X → ℕ) : ℕ := (Finset.univ.filter (fun x => d x=0)).card +lemma partition_contamination (d : X → ℕ) (q : ℝ) (hq0 : 0≤q) (hq1 : q≤1) : + (zeroDeficiencyCount d:ℝ) ≤ deficiencyPartition d q ∧ + deficiencyPartition d q ≤ (zeroDeficiencyCount d:ℝ)+(Fintype.card X:ℝ)*q := by + have hcount : (zeroDeficiencyCount d:ℝ) = ∑ x,if d x=0 then (1:ℝ) else 0 := by + simp [zeroDeficiencyCount,Finset.sum_boole] + rw [hcount] + constructor + · apply Finset.sum_le_sum + intro x _ + by_cases h : d x=0 + · simp [h] + · simp [h,pow_nonneg hq0] + · have hs : ∀ x,q^(d x) ≤ (if d x=0 then 1 else 0)+q := by + intro x + by_cases h : d x=0 + · simp [h,hq0] + · simp only [h,ite_false,zero_add] + have hd : 1≤d x := Nat.one_le_iff_ne_zero.mpr h + simpa using pow_le_pow_of_le_one hq0 hq1 hd + have hh := Finset.sum_le_sum (s := Finset.univ) (fun x _ => hs x) + simpa [deficiencyPartition,Finset.sum_add_distrib] using hh +end Contamination + +namespace FiniteExperiment +open scoped BigOperators Classical +variable {X : Type*} [sectionInstance89 : Fintype X] + +noncomputable def expect (K : List X → X → ℝ) : ℕ → List X → (List X → ℝ) → ℝ + | 0,h,φ => φ h + | t+1,h,φ => ∑ x,K h x*expect K t (h++[x]) φ +noncomputable def mass (K : List X → X → ℝ) (t : ℕ) (h : List X) : ℝ := + expect K t h (fun _ => 1) +lemma expect_nonneg (K : List X → X → ℝ) (hK : ∀ h x,0 ≤ K h x) + (φ : List X → ℝ) (hφ : ∀ h,0 ≤ φ h) (t : ℕ) (h : List X) : + 0 ≤ expect K t h φ := by + induction t generalizing h with + | zero => exact hφ h + | succ t ih => exact Finset.sum_nonneg (fun x _ => mul_nonneg (hK h x) (ih _)) +lemma expect_mono (K : List X → X → ℝ) (hK : ∀ h x,0 ≤ K h x) + (φ ψ : List X → ℝ) (hh : ∀ h,φ h ≤ ψ h) (t : ℕ) (h : List X) : + expect K t h φ ≤ expect K t h ψ := by + induction t generalizing h with + | zero => exact hh h + | succ t ih => exact Finset.sum_le_sum (fun x _ => mul_le_mul_of_nonneg_left (ih _) (hK h x)) +lemma expect_kernel_mono (K P : List X → X → ℝ) (hK : ∀ h x,0 ≤ K h x) + (hKP : ∀ h x,K h x ≤ P h x) (φ : List X → ℝ) (hφ : ∀ h,0 ≤ φ h) + (t : ℕ) (h : List X) : expect K t h φ ≤ expect P t h φ := by + have hP : ∀ h x,0 ≤ P h x := fun h x => (hK h x).trans (hKP h x) + induction t generalizing h with + | zero => rfl + | succ t ih => + exact Finset.sum_le_sum (fun x _ => mul_le_mul (hKP h x) (ih _) + (expect_nonneg K hK φ hφ t _) (hP h x)) +lemma mass_nonneg (K : List X → X → ℝ) (hK : ∀ h x,0 ≤ K h x) (t : ℕ) (h : List X) : + 0 ≤ mass K t h := expect_nonneg K hK _ (by intros; norm_num) t h +lemma mass_le_one (K : List X → X → ℝ) (hK : ∀ h x,0 ≤ K h x) + (hrow : ∀ h,∑ x,K h x ≤ 1) (t : ℕ) (h : List X) : mass K t h ≤ 1 := by + induction t generalizing h with + | zero => rfl + | succ t ih => + change (∑ x,K h x*mass K t (h++[x])) ≤ 1 + calc + _ ≤ ∑ x,K h x*1 := Finset.sum_le_sum (fun x _ => mul_le_mul_of_nonneg_left (ih _) (hK h x)) + _ ≤ 1 := by simpa using hrow h + +theorem adaptive_success (K : List X → X → ℝ) (Good : List X → Prop) + (hK : ∀ h x,0 ≤ K h x) (hrow : ∀ h,∑ x,K h x ≤ 1) + (hsupport : ∀ h,Good h → ∀ x,0 simp [mass,expect] + | succ t ih => + have hlocal : ∀ x,K h x*(1-(t:ℝ)*e) ≤ K h x*mass K t (h++[x]) := by + intro x + by_cases hz : K h x=0 + · simp [hz] + · exact mul_le_mul_of_nonneg_left (ih _ (hsupport h hh x (lt_of_le_of_ne (hK h x) (Ne.symm hz)))) (hK h x) + change 1-((t+1:ℕ):ℝ)*e ≤ ∑ x,K h x*mass K t (h++[x]) + have hs := Finset.sum_le_sum (fun x (_ : x∈Finset.univ) => hlocal x) + rw [← Finset.sum_mul] at hs + have hm := hloss h hh + have hu := hrow h + have ht : 0 ≤ (t:ℝ)*e := mul_nonneg (Nat.cast_nonneg _) he + push_cast + nlinarith [mul_nonneg ht (sub_nonneg.mpr hu)] + +noncomputable def restrict (P : List X → X → ℝ) (Good : List X → Prop) (h : List X) (x : X) : ℝ := + if Good (h++[x]) then P h x else 0 +omit sectionInstance89 in +lemma restrict_nonneg [Fintype X] (P : List X → X → ℝ) (Good : List X → Prop) (hP : ∀ h x,0 ≤ P h x) + (h : List X) (x : X) : 0 ≤ restrict P Good h x := by + unfold restrict; split_ifs; exact hP _ _; rfl +omit sectionInstance89 in +lemma restrict_le [Fintype X] (P : List X → X → ℝ) (Good : List X → Prop) (hP : ∀ h x,0 ≤ P h x) + (h : List X) (x : X) : restrict P Good h x ≤ P h x := by + unfold restrict; split_ifs; rfl; exact hP _ _ +omit sectionInstance89 in +lemma restrict_support [Fintype X] (P : List X → X → ℝ) (Good : List X → Prop) + (h : List X) (x : X) (hx : 0 if Good l then 1 else 0) := by + induction t generalizing h with + | zero => simp [mass,expect,hh] + | succ t ih => + change (∑ x,restrict P Good h x*mass (restrict P Good) t (h++[x])) ≤ _ + apply Finset.sum_le_sum + intro x _ + by_cases hg : Good (h++[x]) + · simpa only [restrict,ite_eq_left hg] using mul_le_mul_of_nonneg_left (ih _ hg) (hP h x) + · have hr : restrict P Good h x=0 := by simp [restrict,hg] + rw [hr,zero_mul] + exact mul_nonneg (hP h x) (expect_nonneg P hP _ (by intro l; split_ifs <;> norm_num) t _) + +theorem good_probability (P : List X → X → ℝ) (Good : List X → Prop) + (hP : ∀ h x,0 ≤ P h x) (hrow : ∀ h,∑ x,P h x ≤ 1) + (e : ℝ) (he : 0 ≤ e) + (hstep : ∀ h,Good h → 1-e ≤ ∑ x,restrict P Good h x) + (t : ℕ) (h : List X) (hh : Good h) : + 1-(t:ℝ)*e ≤ expect P t h (fun l => if Good l then 1 else 0) := by + have hb := adaptive_success (restrict P Good) Good (restrict_nonneg P Good hP) + (fun h => (Finset.sum_le_sum (fun x _ => restrict_le P Good hP h x)).trans (hrow h)) + (fun h _ x hx => restrict_support P Good h x hx) e he hstep t h hh + exact hb.trans (mass_le_good_probability P Good hP t h hh) +end FiniteExperiment +section PairedSlots +open scoped BigOperators Classical +variable {α : Type*} [sectionInstance90 : Fintype α] [sectionInstance91 : DecidableEq α] +def slotPair (i : α) : (α ⊕ α) × (α ⊕ α) := (Sum.inl i,Sum.inr i) +def pairedSlots (n : ℕ) : List ((Fin n ⊕ Fin n) × (Fin n ⊕ Fin n)) := + (List.finRange n).map slotPair +omit sectionInstance90 sectionInstance91 in +lemma slotPairList_fresh [Fintype α] [DecidableEq α] (l : List α) (hl : l.Nodup) (B : Set (α ⊕ α)) + (hB : ∀ i ∈ l,Sum.inl i ∉ B ∧ Sum.inr i ∉ B) : SlotsFresh (l.map slotPair) B := by + induction l generalizing B with + | nil => trivial + | cons a l ih => + obtain ⟨ha,hl⟩ := List.nodup_cons.mp hl + refine ⟨by simp [slotPair],(hB a (by simp)).1,(hB a (by simp)).2,?_⟩ + apply ih hl + intro i hi + have hn : i ≠ a := fun he => ha (he ▸ hi) + have hb := hB i (by simp [hi]) + simpa [slotPair,hn] using hb +lemma pairedSlots_fresh (n : ℕ) : SlotsFresh (pairedSlots n) ∅ := + slotPairList_fresh _ (List.nodup_finRange n) ∅ (by intros; simp) +@[simp] lemma pairedSlots_length (n : ℕ) : (pairedSlots n).length = n := by simp [pairedSlots] +lemma pairedSlots_ne_nil (n : ℕ) (hn : 0 exact ⟨slotPair i,by simp [pairedSlots],Or.inl rfl⟩ + | inr i => exact ⟨slotPair i,by simp [pairedSlots],Or.inr rfl⟩ +lemma pairedSlots_plain (n : ℕ) (S : Set (Fin n ⊕ Fin n)) : + PlainState (pairedSlots n) S ↔ ∀ i, (Sum.inl i ∈ S ↔ Sum.inr i ∉ S) := by + simp only [PlainState,pairedSlots,List.mem_map,forall_exists_index,and_imp] + constructor + · intro h i + have hh := h (slotPair i) i (by simp) rfl + simp only [PairSingle,slotPair] at hh + tauto + · intro h p i hi he + subst p + have hh := h i + simp only [PairSingle,slotPair] + tauto +lemma transversal_plain (n : ℕ) (A : Set (Fin n)) : PlainState (pairedSlots n) (transversal A) := by + rw [pairedSlots_plain] + intro i + have hl : Sum.inl i ∈ transversal A ↔ i ∈ A := by + change i ∈ Sum.inl ⁻¹' transversal A ↔ _ + rw [preimage_inl_transversal] + have hr : Sum.inr i ∈ transversal A ↔ i ∉ A := by + change i ∈ Sum.inr ⁻¹' transversal A ↔ _ + rw [preimage_inr_transversal]; rfl + rw [hl,hr,not_not] +lemma plain_eq_transversal (n : ℕ) (S : Set (Fin n ⊕ Fin n)) (hS : PlainState (pairedSlots n) S) : + S = transversal (Sum.inl ⁻¹' S) := by + rw [pairedSlots_plain] at hS + ext x + cases x with + | inl i => + change i ∈ Sum.inl ⁻¹' S ↔ i ∈ Sum.inl ⁻¹' transversal (Sum.inl ⁻¹' S) + rw [preimage_inl_transversal] + | inr i => + change Sum.inr i ∈ S ↔ i ∈ Sum.inr ⁻¹' transversal (Sum.inl ⁻¹' S) + rw [preimage_inr_transversal] + change Sum.inr i ∈ S ↔ Sum.inl i ∉ S + have hh := hS i + tauto +noncomputable def plainEquivSubsets (n : ℕ) : + {S : Set (Fin n ⊕ Fin n) // PlainState (pairedSlots n) S} ≃ Set (Fin n) where + toFun S := Sum.inl ⁻¹' S.val + invFun A := ⟨transversal A,transversal_plain n A⟩ + left_inv S := Subtype.ext (plain_eq_transversal n S.val S.property).symm + right_inv A := preimage_inl_transversal A +lemma pairedPlain_card (n : ℕ) : Fintype.card {S : Set (Fin n ⊕ Fin n) // PlainState (pairedSlots n) S} = 2^n := by + rw [Fintype.card_congr (plainEquivSubsets n),Fintype.card_set,Fintype.card_fin] +end PairedSlots +open scoped BigOperators Classical +noncomputable def subsetDeficiency {n : ℕ} (M₁ M₂ : Matroid (Fin n)) (A : Set (Fin n)) : ℕ := + n-((pairedMatroid M₁ M₂).eRk (transversal A)).toNat +lemma subsetDeficiency_zero {n : ℕ} (M₁ M₂ : Matroid (Fin n)) + (hE₂ : M₂.E=Set.univ) (hr : M₁.eRank=M₂.eRank) (A : Set (Fin n)) : + subsetDeficiency M₁ M₂ A=0 ↔ M₁.IsBase A ∧ M₂.IsBase A := by + have hR : (pairedMatroid M₁ M₂).eRank=(n:ℕ∞) := by simpa using paired_eRank M₁ M₂ hE₂ hr + have hk : ((pairedMatroid M₁ M₂).eRk (transversal A)).toNat≤n := + ENat.toNat_le_of_le_natCast (by rw [← hR]; exact Matroid.eRk_le_eRank _ _) + rw [← transversal_isBase_iff M₁ M₂ hE₂ A] + constructor + · intro hd + have hn : ((pairedMatroid M₁ M₂).eRk (transversal A)).toNat=n := by unfold subsetDeficiency at hd; omega + have he : (pairedMatroid M₁ M₂).eRk (transversal A)=(n:ℕ∞) := by + calc + _ = (((pairedMatroid M₁ M₂).eRk (transversal A)).toNat:ℕ∞) := + (ENat.natCast_toNat (Matroid.isRkFinite_set _ _).eRk_lt_top.ne).symm + _ = _ := congrArg (fun k : ℕ => (k:ℕ∞)) hn + have hi : (pairedMatroid M₁ M₂).Indep (transversal A) := by + apply (Matroid.indep_iff_eRk_eq_encard_of_finite (Set.toFinite _)).mpr + rw [he,transversal_encard,Fintype.card_fin] + exact hi.isBase_of_eRk_ge (Set.toFinite _) (by rw [he,hR]) + · intro h + unfold subsetDeficiency + rw [h.eRk_eq_eRank,hR,ENat.toNat_natCast,Nat.sub_self] + +noncomputable def commonSetFinsetEquiv {n : ℕ} (M₁ M₂ : Matroid (Fin n)) : + {A : Set (Fin n) // M₁.IsBase A ∧ M₂.IsBase A} ≃ + {A : Finset (Fin n) // M₁.IsBase (A:Set (Fin n)) ∧ M₂.IsBase (A:Set (Fin n))} where + toFun A := ⟨A.val.toFinset,by simpa only [Set.coe_toFinset] using A.property⟩ + invFun A := ⟨(A.val:Set (Fin n)),A.property⟩ + left_inv A := by apply Subtype.ext; exact Set.coe_toFinset _ + right_inv A := by apply Subtype.ext; simp +lemma zeroDeficiency_eq_commonBaseCount {n : ℕ} (M₁ M₂ : Matroid (Fin n)) + (hE₂ : M₂.E=Set.univ) (hr : M₁.eRank=M₂.eRank) : + zeroDeficiencyCount (subsetDeficiency M₁ M₂)=commonBaseCount M₁ M₂ := by + have hp : (fun A => subsetDeficiency M₁ M₂ A=0) = (fun A => M₁.IsBase A ∧ M₂.IsBase A) := + funext (fun A => propext (subsetDeficiency_zero M₁ M₂ hE₂ hr A)) + unfold zeroDeficiencyCount commonBaseCount + rw [← Fintype.card_subtype,← Nat.card_eq_fintype_card] + calc + _ = Nat.card {A : Set (Fin n) // M₁.IsBase A ∧ M₂.IsBase A} := + Nat.card_congr (Equiv.subtypeEquivRight (fun A => subsetDeficiency_zero M₁ M₂ hE₂ hr A)) + _ = _ := Nat.card_congr (commonSetFinsetEquiv M₁ M₂) + +lemma plainPartition_eq_subsets {n : ℕ} (M₁ M₂ : Matroid (Fin n)) (q : ℝ) : + slotTotal (pairedSlots n) (matroidWeight (pairedMatroid M₁ M₂) n q) ∅ = + deficiencyPartition (subsetDeficiency M₁ M₂) q := by + rw [slotTotal_eq_plain_sum (pairedSlots n) (pairedSlots_fresh n) (pairedSlots_cover n)] + rw [Finset.sum_subtype (p := PlainState (pairedSlots n)) _ (by intro S; simp)] + unfold deficiencyPartition + apply Fintype.sum_equiv (plainEquivSubsets n) + intro S + change q^(n-((pairedMatroid M₁ M₂).eRk S.val).toNat)= + q^(n-((pairedMatroid M₁ M₂).eRk (transversal (Sum.inl ⁻¹' S.val))).toNat) + rw [← plain_eq_transversal n S.val S.property] + +theorem paired_partition_contamination {n : ℕ} (M₁ M₂ : Matroid (Fin n)) + (hE₂ : M₂.E=Set.univ) (hr : M₁.eRank=M₂.eRank) (q : ℝ) (hq0 : 0≤q) (hq1 : q≤1) : + (commonBaseCount M₁ M₂:ℝ) ≤ slotTotal (pairedSlots n) (matroidWeight (pairedMatroid M₁ M₂) n q) ∅ ∧ + slotTotal (pairedSlots n) (matroidWeight (pairedMatroid M₁ M₂) n q) ∅ ≤ + (commonBaseCount M₁ M₂:ℝ)+(2:ℝ)^n*q := by + have h := partition_contamination (subsetDeficiency M₁ M₂) q hq0 hq1 + rw [zeroDeficiency_eq_commonBaseCount M₁ M₂ hE₂ hr,Fintype.card_set,Fintype.card_fin] at h + rw [plainPartition_eq_subsets] + exact_mod_cast h +open scoped BigOperators Classical +lemma annealRho_pow_upper (n : ℕ) (hn : 0 pow_le_one₀ hq0 hq1) + _ = _ := by simp + +lemma anneal_minimum_mass {X : Type*} [Fintype X] [Nonempty X] + (n L j : ℕ) (hn : 0 simp [FiniteKernel.power,FiniteKernel.identity] + | succ k ih => + change (∑ y,(∑ z,(C.kernel.power k).P x z*C.P z y)*f y)=_ + simp_rw [Finset.sum_mul,mul_assoc] + rw [Finset.sum_comm] + simp_rw [← Finset.mul_sum] + change (∑ z,(C.kernel.power k).P x z*C.apply f z)=_ + rw [ih] + exact congrFun (Function.iterate_succ_apply C.apply k f).symm x +lemma kernel_power_density (k : ℕ) (x y : X) : + (C.kernel.power k).P x y/C.π y=C.iterate k (C.pointDensity y) x := by + rw [← C.kernel_power_action] + simp [pointDensity,div_eq_mul_inv] +lemma kernel_point_mixing (K m : ℝ) (hK : 1≤K) (hm : 0 < m) (hπ : ∀ x,m≤C.π x) + (hp : ∀ f : X → ℝ,C.variance f≤K*C.energy f) (k : ℕ) (x y : X) : + |(C.kernel.power k).P x y/C.π y-1|≤Real.exp (-(k:ℝ)/K)/m := by + rw [C.kernel_power_density] + exact C.point_mixing_exp K m hK hm hπ hp k x y + +lemma kernel_power_warm_any (K m e : ℝ) (hK : 1≤K) (hm : 0 < m) + (hπ : ∀ x,m≤C.π x) (hp : ∀ f : X → ℝ,C.variance f≤K*C.energy f) + (k : ℕ) (he : Real.exp (-(k:ℝ)/K)/m≤e) (he' : 0≤1+e) + (ν : X → ℝ) (hν : ∀ x,0≤ν x) (hnorm : ∑ x,ν x≤1) (y : X) : + (C.kernel.power k).push ν y≤(1+e)*C.π y := by + have hrow : ∀ x,(C.kernel.power k).P x y≤(1+e)*C.π y := by + intro x + have h := (le_abs_self _).trans ((C.kernel_point_mixing K m hK hm hπ hp k x y).trans he) + apply (div_le_iff₀ (C.positive y)).mp + linarith + calc + _ ≤ ∑ x,ν x*((1+e)*C.π y) := Finset.sum_le_sum (fun x _ => mul_le_mul_of_nonneg_left (hrow x) (hν x)) + _ = (∑ x,ν x)*((1+e)*C.π y) := by rw [Finset.sum_mul] + _ ≤ _ := by simpa using mul_le_mul_of_nonneg_right hnorm (mul_nonneg he' (C.positive y).le) +end FiniteChain + +namespace Annealing + +lemma restart_exponential (n L : ℕ) (hn : 0 exact h A + | cons p ps ih => + change coeffDeriv (pairDirection p) (slotTotal ps f) A ≤ coeffDeriv (pairDirection p) (slotTotal ps g) A + unfold coeffDeriv + apply Finset.sum_le_sum + intro i _ + split_ifs + · rfl + · exact mul_le_mul_of_nonneg_left (ih _) (slotDirection_nonneg _ _) +lemma slotTotal_scale (ps : List (Γ × Γ)) (f : Set Γ → ℝ) (c : ℝ) (A : Set Γ) : + slotTotal ps (fun S => c*f S) A=c*slotTotal ps f A := coeffDerivs_scale _ _ _ _ +noncomputable def annealWeight (M : Matroid Γ) (n j : ℕ) : Set Γ → ℝ := + matroidWeight M n (annealRho n^j) +lemma annealWeight_pos (M : Matroid Γ) (n j : ℕ) (hn : 0 (annealWeight_drift M n j hn S).1) _ + · exact slotTotal_mono _ _ _ (fun S => (annealWeight_drift M n j hn S).2) _ +lemma anneal_ideal_drift (ps : List (Γ × Γ)) (hps : SlotsFresh ps ∅) + (M : Matroid Γ) (n j : ℕ) (hn : 0 annealRho n^(n-(M.eRk S).toNat))) = + slotTotal gs (annealWeight M n (j+1)) ∅/chainTotal gs w (annealWeight M n j) := by + rw [plainObservable_mean gs hgs hcover] + congr 2 + funext S + exact (annealWeight_step M n j hn S).symm +lemma plain_probability_mean (gs : List (Γ × Γ)) (hgs : SlotsFresh gs ∅) + (hcover : pairSupport gs=Set.univ) (f : Set Γ → ℝ) + (w : (Γ × Γ) → (Γ × Γ) → ℝ) : + chainMean gs w f (plainObservable gs (fun _ => 1))=slotTotal gs f ∅/chainTotal gs w f := by + rw [plainObservable_mean gs hgs hcover] + simp +lemma weight_mean_identity (gs : List (Γ × Γ)) (hgs : SlotsFresh gs ∅) + (hcover : pairSupport gs=Set.univ) (f : Set Γ → ℝ) (hf : ∀ S,0 1))/ + chainMean gs w f (defectIndicator gs p r))=slotTotal gs f ∅/slotDefect gs f ∅ p r := by + rw [plain_probability_mean gs hgs hcover,defectIndicator_mean gs hgs hcover _ _ p r hp hr hpr] + field_simp [(chainTotal_pos gs hgs hcover w f hf hw).ne',(hw p r).ne'] + +lemma plainIndex_card (n : ℕ) : Fintype.card (PlainIndex (pairedSlots n))=2^n := by + let e : PlainIndex (pairedSlots n) ≃ {S : Set (Fin n ⊕ Fin n) // PlainState (pairedSlots n) S} := + { toFun := fun S => ⟨S.val.val,S.property⟩ + invFun := fun S => ⟨⟨S.val,Or.inl S.property⟩,S.property⟩ + left_inv := by intro S; rfl + right_inv := by intro S; rfl } + rw [Fintype.card_congr e,pairedPlain_card] +lemma anneal_plainPartition (gs : List (Γ × Γ)) (hgs : SlotsFresh gs ∅) + (hcover : pairSupport gs=Set.univ) (M : Matroid Γ) (n j : ℕ) : + slotTotal gs (annealWeight M n j) ∅= + deficiencyPartition (fun S : PlainIndex gs => n-(M.eRk S.val.val).toNat) (annealRho n^j) := by + rw [slotTotal_eq_plain_sum gs hgs hcover] + symm + exact plainIndex_sum gs (annealWeight M n j) +lemma actual_trace_minimum (n L j : ℕ) (hn : 0 n-(M.eRk S.val.val).toNat) (fun _ => Nat.sub_le _ _) S +lemma slotTotal_one (ps : List (Γ × Γ)) (A : Set Γ) (hps : SlotsFresh ps A) : + slotTotal ps (fun _ => 1) A=(2:ℝ)^ps.length := by + induction ps generalizing A with + | nil => rfl + | cons p ps ih => + rw [slotTotal_cons p ps _ A hps.1 hps.2.1 hps.2.2.1] + have hleft : SlotsFresh ps (insert p.1 A) := hps.2.2.2.mono (by intro i hi; simp only [Set.mem_insert_iff] at hi ⊢; tauto) + have hright : SlotsFresh ps (insert p.2 A) := hps.2.2.2.mono (by intro i hi; simp only [Set.mem_insert_iff] at hi ⊢; tauto) + rw [ih _ hleft,ih _ hright,List.length_cons,pow_succ] + ring +lemma initial_ideal (gs : List (Γ × Γ)) (hgs : SlotsFresh gs ∅) (p r : Γ × Γ) + (hp : p∈gs) (hr : r∈gs) (hpr : p≠r) : + slotTotal gs (fun _ => 1) ∅/slotDefect gs (fun _ => 1) ∅ p r=4 := by + have hperm := slots_perm_two hp hr hpr + have hh := (SlotsFresh.perm hperm ∅).mp hgs + have hrest : SlotsFresh ((gs.erase p).erase r) (insert r.1 (insert r.2 ∅)) := + hh.2.2.2.2.2.2.mono (by intro i hi; simp only [Set.mem_insert_iff] at hi ⊢; tauto) + have hlen := List.Perm.length_eq hperm + simp only [List.length_cons] at hlen + rw [slotTotal_one _ _ hgs,slotDefect,slotTotal_one _ _ hrest,hlen,pow_succ,pow_succ] + have hp : (2:ℝ)^((gs.erase p).erase r).length≠0 := by positivity + field_simp + ; ring +lemma initial_good (gs : List (Γ × Γ)) (hgs : SlotsFresh gs ∅) (M : Matroid Γ) (n : ℕ) : + GoodMultipliers gs (annealWeight M n 0) (fun _ _ => 4) := by + have he : annealWeight M n 0=(fun _ => 1) := by funext S; simp [annealWeight,matroidWeight] + rw [he] + refine ⟨by intros; norm_num,?_,?_⟩ + · intro p hp r hr hpr + rw [mul_comm (4:ℝ),← div_div,initial_ideal gs hgs p r hp hr hpr] + norm_num + · intro p hp r hr hpr + rw [mul_div_assoc,initial_ideal gs hgs p r hp hr hpr] + norm_num + +noncomputable def empirical (H : Set Γ → ℝ) (l : List (Set Γ)) : ℝ := + (l.map H).sum/(l.length:ℝ) +noncomputable def learnedMultipliers (gs : List (Γ × Γ)) + (w : (Γ × Γ) → (Γ × Γ) → ℝ) (l : List (Set Γ)) (p r : Γ × Γ) : ℝ := + if p∈gs ∧ r∈gs ∧ p≠r then + w p r*(empirical (plainObservable gs (fun _ => 1)) l/empirical (defectIndicator gs p r) l) + else w p r +noncomputable def empiricalRatio (gs : List (Γ × Γ)) (g : Set Γ → ℝ) (l : List (Set Γ)) : ℝ := + empirical (plainObservable gs g) l/empirical (plainObservable gs (fun _ => 1)) l + +def AccuratePhase (gs : List (Γ × Γ)) (w : (Γ × Γ) → (Γ × Γ) → ℝ) + (f g : Set Γ → ℝ) (η : ℝ) (l : List (Set Γ)) : Prop := + ∀ j : PhaseObservables gs, + |empirical (phaseObservable gs g j) l-chainMean gs w f (phaseObservable gs g j)| ≤ + η*chainMean gs w f (phaseObservable gs g j) +lemma relative_error_bounds (x m η : ℝ) (h : |x-m| ≤ η*m) : + (1-η)*m ≤ x ∧ x ≤ (1+η)*m := by + obtain ⟨h1,h2⟩ := abs_le.mp h + constructor <;> nlinarith +lemma accurate_plain (gs : List (Γ × Γ)) (w : (Γ × Γ) → (Γ × Γ) → ℝ) + (f g : Set Γ → ℝ) (η : ℝ) (l : List (Set Γ)) (h : AccuratePhase gs w f g η l) : + (1-η)*chainMean gs w f (plainObservable gs (fun _ => 1)) ≤ empirical (plainObservable gs (fun _ => 1)) l ∧ + empirical (plainObservable gs (fun _ => 1)) l ≤ (1+η)*chainMean gs w f (plainObservable gs (fun _ => 1)) := + relative_error_bounds _ _ _ (h (.inl none)) +lemma accurate_defect (gs : List (Γ × Γ)) (w : (Γ × Γ) → (Γ × Γ) → ℝ) + (f g : Set Γ → ℝ) (η : ℝ) (l : List (Set Γ)) (h : AccuratePhase gs w f g η l) + (p r : Γ × Γ) (hp : p∈gs) (hr : r∈gs) (hpr : p≠r) : + (1-η)*chainMean gs w f (defectIndicator gs p r) ≤ empirical (defectIndicator gs p r) l ∧ + empirical (defectIndicator gs p r) l ≤ (1+η)*chainMean gs w f (defectIndicator gs p r) := + relative_error_bounds _ _ _ (h (.inl (some ⟨(p,r),(mem_defectTypes gs (p,r)).mpr ⟨hp,hr,hpr⟩⟩))) + +theorem successful_phase_learns (gs : List (Γ × Γ)) (hgs : SlotsFresh gs ∅) + (hcover : pairSupport gs=Set.univ) (M : Matroid Γ) (n j : ℕ) (hn : 0 annealRho n^(n-(M.eRk S).toNat)) η l) : + GoodMultipliers gs (annealWeight M n (j+1)) (learnedMultipliers gs w l) := by + let f := annealWeight M n j + let g := fun S => annealRho n^(n-(M.eRk S).toNat) + have hf := annealWeight_pos M n j hn + have hΛ := chainTotal_pos gs hgs hcover w f hf hw + have hp0 : 0 1)) := by + rw [plain_probability_mean gs hgs hcover] + exact div_pos (slotTotal_pos gs f hf ∅ hgs) hΛ + have hp0h := accurate_plain gs w f g η l hacc + have hp0hp : 0 1)) l := + lt_of_lt_of_le (mul_pos (by linarith) hp0) hp0h.1 + have hpt : ∀ p∈gs,∀ r∈gs,p≠r → 0 annealRho n^(n-(M.eRk S).toNat)) η l) : + (1-η)/(1+η) ≤ empiricalRatio gs (fun S => annealRho n^(n-(M.eRk S).toNat)) l/ + (slotTotal gs (annealWeight M n (j+1)) ∅/slotTotal gs (annealWeight M n j) ∅) ∧ + empiricalRatio gs (fun S => annealRho n^(n-(M.eRk S).toNat)) l/ + (slotTotal gs (annealWeight M n (j+1)) ∅/slotTotal gs (annealWeight M n j) ∅) ≤ (1+η)/(1-η) := by + let f := annealWeight M n j + let g := fun S => annealRho n^(n-(M.eRk S).toNat) + have hΛ := chainTotal_pos gs hgs hcover w f (annealWeight_pos M n j hn) hw + have hp0 : 0 1)) := by + rw [plain_probability_mean gs hgs hcover] + exact div_pos (slotTotal_pos gs f (annealWeight_pos M n j hn) ∅ hgs) hΛ + have hu : 0 1)) = + slotTotal gs (annealWeight M n (j+1)) ∅/slotTotal gs (annealWeight M n j) ∅ := by + rw [anneal_ratio_mean gs hgs hcover M n j hn,plain_probability_mean gs hgs hcover] + dsimp only [f] at hΛ ⊢ + field_simp [hΛ.ne'] + have h := estimated_ratio_bounds η _ _ _ _ hη0 hη1 hp0 hu + (accurate_plain gs w f g η l hacc) (relative_error_bounds _ _ _ (hacc (.inr ()))) + rw [he] at h + exact h.2 +end ActualAnnealing +namespace FiniteChain +open scoped BigOperators Classical +variable {X : Type*} [Fintype X] (C : FiniteChain X) +lemma capped_power_submass (K : FiniteKernel X X) (hK : ∀ x y,K.P x y ≤ C.P x y) + (ν : X → ℝ) (hν : ∀ x,0 ≤ ν x) (U e : ℝ) (hwarm : ∀ x,ν x ≤ U*C.π x) + (hloss : ∀ a : X → ℝ,(∀ x,0 ≤ a x) → (∀ x,a x ≤ U*C.π x) → + (∑ x,a x*(1-∑ y,K.P x y)) ≤ e) (T : ℕ) : + (∑ x,ν x)-(∑ x,(K.power T).push ν x) ≤ (T:ℝ)*e := by + have hdom := fun n x => K.power_domination C.kernel hK n ν hν x + induction T with + | zero => simp [FiniteKernel.power,FiniteKernel.push_identity] + | succ T ih => + have h := K.one_step_defect C.kernel C.stochastic + ((K.power T).push ν) ((C.kernel.power T).push ν) + ((K.power T).push_nonneg ν hν) (hdom T) + have hl := hloss ((C.kernel.power T).push ν) + ((C.kernel.power T).push_nonneg ν hν) (C.power_warm T ν U hwarm) + have hm := C.power_push_mass T ν + have hm' := C.power_push_mass (T+1) ν + rw [FiniteKernel.power_push_succ] at hm' + rw [FiniteKernel.power_push_succ] + rw [hm,hm'] at h + push_cast + linarith +variable (A : X → Prop) (Q : KilledKernel (Outside A)) (hQ : ∀ x y,Q.Q x y=C.P x.val y.val) +lemma cappedTrace_power_submass [Nonempty (Inside A)] (N T : ℕ) (hN : 0 pairedSlots n +local notation "W" => (((Fin n ⊕ Fin n) × (Fin n ⊕ Fin n)) → ((Fin n ⊕ Fin n) × (Fin n ⊕ Fin n)) → ℝ) +noncomputable def actualTrace (j : ℕ) (w : W) (hw : ∀ p r,0 pairedSlots n +local notation "W" => (((Fin n ⊕ Fin n) × (Fin n ⊕ Fin n)) → ((Fin n ⊕ Fin n) × (Fin n ⊕ Fin n)) → ℝ) +noncomputable def actualCappedTrace (j : ℕ) (w : W) (hw : ∀ p r,0 1) := by funext S; simp [annealWeight,matroidWeight] + rw [he,slotTotal_one GS ∅ (pairedSlots_fresh n),pairedSlots_length] + rfl +noncomputable def restartLaw (L cap : ℕ) (w : ℕ → W) (hw : ∀ j p r,0 uniformPlain n + | j+1 => ((actualCappedTrace n hn M (j+1) (w (j+1)) (hw (j+1)) cap).power + (20*n^4*(n*(L+1)+2))).push (restartLaw L cap w hw j) +lemma restartLaw_nonneg (L cap : ℕ) (w : ℕ → W) (hw : ∀ j p r,0 simp only [restartLaw,uniformPlain]; positivity + | succ j ih => exact FiniteKernel.push_nonneg _ _ ih x +lemma restartLaw_mass_le (L cap : ℕ) (w : ℕ → W) (hw : ∀ j p r,0 exact (uniformPlain_mass n).le + | succ j ih => exact (FiniteKernel.push_mass_le _ _ (restartLaw_nonneg n hn M L cap w hw j)).trans ih +lemma restartLaw_warm (hE : M.E=Set.univ) (hR : M.eRank=(n:ℕ∞)) + (L cap : ℕ) (w : ℕ → W) (hw : ∀ j p r,0 + rw [restartLaw,uniformPlain_pi n hn M (w 0) (hw 0)] + have h := (actualTrace n hn M 0 (w 0) (hw 0)).positive x + linarith + | succ j => + have h := actual_capped_mixing n hn M hE hR L (j+1) hj (w (j+1)) hgood cap + (restartLaw n hn M L cap w hw j) (restartLaw_nonneg n hn M L cap w hw j) + (restartLaw_mass_le n hn M L cap w hw j) x + change _ ≤ 2*(actualTrace n hn M (j+1) (w (j+1)) (hw (j+1))).π x + have hp := (actualTrace n hn M (j+1) (w (j+1)) (hw (j+1))).positive x + exact h.trans (by linarith) +lemma restartLaw_missing_mass (hE : M.E=Set.univ) (hR : M.eRank=(n:ℕ∞)) + (L cap : ℕ) (hcap : 0 simp [restartLaw,uniformPlain_mass] + | succ j ih => + have hj' : j ≤ L := by omega + have hb := ih hj' (fun a ha => hgood a (by omega)) + have hwarm : ∀ x,restartLaw n hn M L cap w hw j x ≤ 4*(actualTrace n hn M (j+1) (w (j+1)) (hw (j+1))).π x := by + intro x + have h1 := restartLaw_warm n hn M hE hR L cap w hw j hj' (hgood j (by omega)) x + have h2 := actual_mu_drift n hn M j (w j) (w (j+1)) (hw j) (hw (j+1)) x + linarith + have h := actual_capped_loss n hn M (j+1) (w (j+1)) (hgood (j+1) le_rfl) cap + (20*n^4*(n*(L+1)+2)) hcap (restartLaw n hn M L cap w hw j) + (restartLaw_nonneg n hn M L cap w hw j) hwarm + change 1-(∑ x,(_ : FiniteKernel _ _).push _ x) ≤ _ + simp only [Nat.cast_add,Nat.cast_one] + nlinarith +end ActualRestart +namespace FiniteChain +open scoped BigOperators Classical +variable {X : Type*} [Fintype X] (C : FiniteChain X) +lemma pathProbability_congr_length (ν : X → ℝ) (N : ℕ) (E F : List X → Prop) + (h : ∀ l,l.length=N+1 → (E l ↔ F l)) : + C.pathProbability ν N E=C.pathProbability ν N F := by + unfold pathProbability + apply Finset.sum_congr rfl + intro x _ + congr 1 + apply C.pathExpectation_congr_length + intro l hl + simp only [h l hl] +lemma pathProbability_compl (ν : X → ℝ) (N : ℕ) (E : List X → Prop) : + C.pathProbability ν N E+C.pathProbability ν N (fun l => ¬E l)=∑ x,ν x := by + unfold pathProbability + rw [← Finset.sum_add_distrib] + apply Finset.sum_congr rfl + intro x _ + rw [← mul_add,← C.pathExpectation_add] + calc + _ = ν x*C.pathExpectation N x (fun _ => 1) := by + congr 1 + apply C.pathExpectation_congr + intro l + by_cases h : E l <;> simp [h] + _ = ν x := by rw [C.pathExpectation_const,mul_one] +lemma pathProbability_le_mass (ν : X → ℝ) (hν : ∀ x,0 ≤ ν x) (N : ℕ) (E : List X → Prop) : + C.pathProbability ν N E ≤ ∑ x,ν x := by + have h := C.pathProbability_compl ν N E + have hn := C.pathProbability_nonneg ν hν N (fun l => ¬E l) + linarith +end FiniteChain +section PhaseBridge +open scoped BigOperators Classical +variable {Γ : Type*} [sectionInstance97 : Fintype Γ] [sectionInstance98 : DecidableEq Γ] +omit sectionInstance97 sectionInstance98 in +lemma empirical_trajectory [Fintype Γ] [DecidableEq Γ] (gs : List (Γ × Γ)) (H : Set Γ → ℝ) (l : List (ChainIndex gs)) : + empirical H (l.map Subtype.val)=FiniteChain.pathSum (fun S => H S.val) l/(l.length:ℝ) := by + simp [empirical,FiniteChain.pathSum,] + +theorem accurate_phase_probability (gs : List (Γ × Γ)) (hgs : SlotsFresh gs ∅) (hne : gs≠[]) + (hcover : pairSupport gs=Set.univ) (w : (Γ × Γ) → (Γ × Γ) → ℝ) + (f g : Set Γ → ℝ) (hw : GoodMultipliers gs f w) (hf : ∀ S,0 AccuratePhase gs w f g η (l.map Subtype.val)) := by + let C := metropolisChain gs hgs hne hcover w f hw.positive hf + have hn : 0 ∃ j : PhaseObservables gs,η*C.mean (fun S => phaseObservable gs g j S.val)< + |FiniteChain.pathSum (fun S => phaseObservable gs g j S.val) l/(N:ℝ)-C.mean (fun S => phaseObservable gs g j S.val)|) + (fun l => ¬AccuratePhase gs w f g η (l.map Subtype.val)) (by + intro l hl + have hl' : l.length=N := by omega + simp only [AccuratePhase,empirical_trajectory,hl',not_forall,not_le] + simp only [C,metropolisChain_mean]) + rw [he] at h + have hc := C.pathProbability_compl ν (N-1) (fun l => AccuratePhase gs w f g η (l.map Subtype.val)) + dsimp only + linarith +end PhaseBridge +section EstimatorBridge +open scoped BigOperators Classical +variable {Γ : Type*} [Fintype Γ] [DecidableEq Γ] +lemma product_ratios_telescope (a : ℕ → ℝ) (ha : ∀ j,a j≠0) (L : ℕ) : + (∏ j ∈ Finset.range L,a (j+1)/a j)=a L/a 0 := by + induction L with + | zero => simp [ha] + | succ L ih => rw [Finset.prod_range_succ,ih]; field_simp [ha L,ha 0] +lemma accurate_phases_product (gs : List (Γ × Γ)) (hgs : SlotsFresh gs ∅) + (hcover : pairSupport gs=Set.univ) (M : Matroid Γ) (n : ℕ) (hn : 0 annealRho n^(n-(M.eRk S).toNat)) (annealTolerance ε L) (ls j)) : + let Zhat := (2:ℝ)^gs.length * ∏ j ∈ Finset.range L, + empiricalRatio gs (fun S => annealRho n^(n-(M.eRk S).toNat)) (ls j) + (1-ε/4)*slotTotal gs (annealWeight M n L) ∅ ≤ Zhat ∧ + Zhat ≤ (1+ε/4)*slotTotal gs (annealWeight M n L) ∅ := by + let c := fun j => slotTotal gs (annealWeight M n j) ∅ + let R := fun j => empiricalRatio gs (fun S => annealRho n^(n-(M.eRk S).toNat)) (ls j) + have hc : ∀ j,0 slotTotal_pos gs _ (annealWeight_pos M n j hn) ∅ hgs + have ht := product_ratios_telescope c (fun j => (hc j).ne') L + have he : c 0=(2:ℝ)^gs.length := by + have hf : annealWeight M n 0=(fun _ => 1) := by funext S; simp [annealWeight,matroidWeight] + dsimp only [c]; rw [hf,slotTotal_one gs ∅ hgs] + have hη : 0 R j/(c (j+1)/c j)) ε L hε0 hε1 + (fun j hj => successful_phase_ratio gs hgs hcover M n j hn (w j) (hw j) + (annealTolerance ε L) hη.1.le (by linarith [hη.2]) (ls j) (hacc j hj)) + have hidentity : (∏ j ∈ Finset.range L,R j/(c (j+1)/c j)) = + ((2:ℝ)^gs.length*(∏ j ∈ Finset.range L,R j))/c L := by + rw [Finset.prod_div_distrib,ht,he] + field_simp + rw [hidentity] at hp + constructor + · exact (le_div_iff₀ (hc L)).mp hp.1 + · exact (div_le_iff₀ (hc L)).mp hp.2 + +theorem actual_estimator_accuracy {n : ℕ} (hn : 0 annealRho n^(n-((pairedMatroid M₁ M₂).eRk S).toNat)) + (annealTolerance ε (annealLength n b)) (ls j)) : + let Zhat := (2:ℝ)^n * ∏ j ∈ Finset.range (annealLength n b), + empiricalRatio (pairedSlots n) (fun S => annealRho n^(n-((pairedMatroid M₁ M₂).eRk S).toNat)) (ls j) + (1-ε)*(commonBaseCount M₁ M₂:ℝ) ≤ Zhat ∧ Zhat ≤ (1+ε)*(commonBaseCount M₁ M₂:ℝ) := by + have hp := accurate_phases_product (pairedSlots n) (pairedSlots_fresh n) (pairedSlots_cover n) + (pairedMatroid M₁ M₂) n hn ε hε0 hε1 (annealLength n b) w hw ls hacc + simp only [pairedSlots_length] at hp + have hrho := annealRho_bounds n hn + have hq0 : 0 ≤ annealRho n^annealLength n b := pow_nonneg (le_trans (by norm_num) hrho.1) _ + have hq1 : annealRho n^annealLength n b ≤ 1 := pow_le_one₀ (le_trans (by norm_num) hrho.1) hrho.2.le + have hc := paired_partition_contamination M₁ M₂ hE₂ hr _ hq0 hq1 + have hcont := anneal_final_contamination n b hn ε hb + have hZ' : (1:ℝ) ≤ commonBaseCount M₁ M₂ := by exact_mod_cast hZ + apply final_estimate_accuracy ε _ _ _ hε0 hε1 (by positivity) ⟨hc.1,?_⟩ hp + have hm := mul_le_mul_of_nonneg_left hZ' (show 0 ≤ ε/10 by positivity) + nlinarith [hc.2] +end EstimatorBridge +namespace FiniteChain +open scoped BigOperators Classical +variable {X : Type*} [sectionInstance101 : Fintype X] +universe u + +def Sample (X : Type u) : ℕ → Type u + | 0 => X + | k+1 => X × Sample X k +instance sampleFintype (k : ℕ) : Fintype (Sample X k) := by + induction k with + | zero => exact inferInstanceAs (Fintype X) + | succ k ih => + letI : Fintype (Sample X k) := ih + exact inferInstanceAs (Fintype (X × Sample X k)) +def Sample.toList : {k : ℕ} → Sample X k → List X + | 0,x => [x] + | _+1,(x,v) => x::v.toList +omit sectionInstance101 in +lemma Sample.toList_length [Fintype X] {k : ℕ} (v : Sample X k) : v.toList.length=k+1 := by + induction k with + | zero => rfl + | succ k ih => exact congrArg Nat.succ (ih v.2) +variable (C : FiniteChain X) +noncomputable def sampleMass (C : FiniteChain X) (ν : X → ℝ) : {k : ℕ} → Sample X k → ℝ + | 0,x => ν x + | _+1,(x,v) => ν x*sampleMass C (C.P x) v +lemma sampleMass_nonneg (ν : X → ℝ) (hν : ∀ x,0 ≤ ν x) {k : ℕ} (v : Sample X k) : + 0 ≤ C.sampleMass ν v := by + induction k generalizing ν with + | zero => exact hν v + | succ k ih => exact mul_nonneg (hν _) (ih _ (C.nonnegative _) v.2) +lemma sampleMass_expect (ν : X → ℝ) (k : ℕ) (F : List X → ℝ) : + (∑ v : Sample X k,C.sampleMass ν v*F v.toList)= + ∑ x,ν x*C.pathExpectation k x F := by + induction k generalizing ν F with + | zero => rfl + | succ k ih => + change (∑ v : X × Sample X k,_)=_ + rw [Fintype.sum_prod_type] + apply Finset.sum_congr rfl + intro x _ + simp only [sampleMass,Sample.toList,mul_assoc,← Finset.mul_sum] + rw [ih (C.P x) (fun l => F (x::l))] + rfl +lemma sampleMass_total (ν : X → ℝ) (k : ℕ) : + (∑ v : Sample X k,C.sampleMass ν v)=∑ x,ν x := by + have h := C.sampleMass_expect ν k (fun _ => 1) + simpa only [mul_one,C.pathExpectation_const] using h +lemma sampleMass_event (ν : X → ℝ) (k : ℕ) (E : List X → Prop) : + (∑ v : Sample X k,if E v.toList then C.sampleMass ν v else 0)=C.pathProbability ν k E := by + unfold pathProbability + rw [← C.sampleMass_expect] + apply Finset.sum_congr rfl + intro v _ + split_ifs <;> simp +end FiniteChain +section WarmLift +open scoped BigOperators Classical +variable {Γ : Type*} [sectionInstance102 : Fintype Γ] [sectionInstance103 : DecidableEq Γ] +noncomputable def plainLift (gs : List (Γ × Γ)) (ν : PlainIndex gs → ℝ) (S : ChainIndex gs) : ℝ := + if h : PlainState gs S.val then ν ⟨S,h⟩ else 0 +omit sectionInstance102 sectionInstance103 in +lemma plainLift_nonneg [Fintype Γ] [DecidableEq Γ] (gs : List (Γ × Γ)) (ν : PlainIndex gs → ℝ) (hν : ∀ x,0 ≤ ν x) (S : ChainIndex gs) : + 0 ≤ plainLift gs ν S := by unfold plainLift; split_ifs; exact hν _; rfl +omit sectionInstance103 in +lemma plainLift_mass [DecidableEq Γ] (gs : List (Γ × Γ)) (ν : PlainIndex gs → ℝ) : + (∑ S,plainLift gs ν S)=∑ S : PlainIndex gs,ν S := by + have h := Fintype.sum_subtype_add_sum_subtype (plainPredicate gs) (fun S => plainLift gs ν S) + have ht : ∀ S : PlainIndex gs,plainLift gs ν S.val=ν S := by + intro S; exact dite_eq_left S.property + have hf : ∀ S : {S : ChainIndex gs // ¬plainPredicate gs S},plainLift gs ν S.val=0 := by + intro S; exact dite_eq_right S.property + simp_rw [ht,hf,Finset.sum_const_zero,add_zero] at h + exact h.symm +lemma plainLift_warm (gs : List (Γ × Γ)) (hgs : SlotsFresh gs ∅) (hne : gs≠[]) + (hcover : pairSupport gs=Set.univ) (w : (Γ × Γ) → (Γ × Γ) → ℝ) + (f : Set Γ → ℝ) (hf : ∀ S,0 simp [mass,expect] + | succ t ih => + have hlocal : ∀ x,K h x*(1-(t:ℝ)*e) ≤ K h x*mass K t (h++[x]) := by + intro x + by_cases hz : K h x=0 + · simp [hz] + · exact mul_le_mul_of_nonneg_left (ih _ (hsupport h hh x (lt_of_le_of_ne (hK h x) (Ne.symm hz))) (by simp only [List.length_append,List.length_singleton]; omega)) (hK h x) + change 1-((t+1:ℕ):ℝ)*e ≤ ∑ x,K h x*mass K t (h++[x]) + have hs := Finset.sum_le_sum (fun x (_ : x∈Finset.univ) => hlocal x) + rw [← Finset.sum_mul] at hs + have hm := hloss h hh (by omega) + have hu := hrow h + have ht : 0 ≤ (t:ℝ)*e := mul_nonneg (Nat.cast_nonneg _) he + push_cast + nlinarith [mul_nonneg ht (sub_nonneg.mpr hu)] +theorem good_probability_bounded (P : List X → X → ℝ) (Good : List X → Prop) + (hP : ∀ h x,0 ≤ P h x) (hrow : ∀ h,∑ x,P h x ≤ 1) + (L : ℕ) (e : ℝ) (he : 0 ≤ e) + (hstep : ∀ h,Good h → h.length if Good l then 1 else 0) := by + intro hh + have hb := adaptive_success_bounded (restrict P Good) Good (restrict_nonneg P Good hP) + (fun h => (Finset.sum_le_sum (fun x _ => restrict_le P Good hP h x)).trans (hrow h)) + (fun h _ x hx => restrict_support P Good h x hx) L e he hstep L [] hh (by simp) + exact hb.trans (mass_le_good_probability P Good hP L [] hh) +end FiniteExperiment +section ActualHistory +open scoped BigOperators Classical +variable {Γ : Type*} [sectionInstance105 : Fintype Γ] [DecidableEq Γ] +variable (gs : List (Γ × Γ)) +noncomputable def historyWeights {X : Type*} (sample : X → List (Set Γ)) (h : List X) : + (Γ × Γ) → (Γ × Γ) → ℝ := + h.foldl (fun w x => learnedMultipliers gs w (sample x)) (fun _ _ => 4) +omit sectionInstance105 in +lemma historyWeights_nil [Fintype Γ] {X : Type*} (sample : X → List (Set Γ)) : historyWeights gs sample []=(fun _ _ => 4) := rfl +omit sectionInstance105 in +lemma historyWeights_snoc [Fintype Γ] {X : Type*} (sample : X → List (Set Γ)) (h : List X) (x : X) : + historyWeights gs sample (h++[x])=learnedMultipliers gs (historyWeights gs sample h) (sample x) := by + simp [historyWeights,List.foldl_append] +variable (M : Matroid Γ) (n : ℕ) (η : ℝ) +inductive SuccessfulHistory {X : Type*} (sample : X → List (Set Γ)) : List X → Prop + | nil : SuccessfulHistory sample [] + | snoc (h : List X) (x : X) (hh : SuccessfulHistory sample h) + (hx : AccuratePhase gs (historyWeights gs sample h) (annealWeight M n h.length) + (fun S => annealRho n^(n-(M.eRk S).toNat)) η (sample x)) : SuccessfulHistory sample (h++[x]) +lemma successfulHistory_take {X : Type*} (sample : X → List (Set Γ)) (h : List X) + (hh : SuccessfulHistory gs M n η sample h) (a : ℕ) : + SuccessfulHistory gs M n η sample (h.take a) := by + induction hh with + | nil => simpa using SuccessfulHistory.nil (gs := gs) (M := M) (n := n) (η := η) (sample := sample) + | snoc h x hh hx ih => + by_cases ha : a ≤ h.length + · rw [List.take_append_of_le_length ha] + exact ih + · have he : a ≥ (h++[x]).length := by simp; omega + rw [List.take_of_length_le he] + exact SuccessfulHistory.snoc h x hh hx +lemma successfulHistory_good {X : Type*} (sample : X → List (Set Γ)) + (hgs : SlotsFresh gs ∅) (hcover : pairSupport gs=Set.univ) (hn : 0 exact initial_good gs hgs M n + | snoc h x hh hx ih => + rw [historyWeights_snoc,List.length_append,List.length_singleton] + exact successful_phase_learns gs hgs hcover M n h.length hn (historyWeights gs sample h) + ih.positive η hη0 hη1 (sample x) hx +lemma successfulHistory_snoc_iff {X : Type*} (sample : X → List (Set Γ)) (h : List X) (x : X) + (hh : SuccessfulHistory gs M n η sample h) : + SuccessfulHistory gs M n η sample (h++[x]) ↔ + AccuratePhase gs (historyWeights gs sample h) (annealWeight M n h.length) + (fun S => annealRho n^(n-(M.eRk S).toNat)) η (sample x) := by + constructor + · intro hs + have aux : ∀ l,SuccessfulHistory gs M n η sample l → ∀ h x,l=h++[x] → + AccuratePhase gs (historyWeights gs sample h) (annealWeight M n h.length) + (fun S => annealRho n^(n-(M.eRk S).toNat)) η (sample x) := by + intro l hl h x he + cases hl with + | nil => simp at he + | snoc l y hl hy => + have hlen := congrArg List.length he + simp only [List.length_append,List.length_singleton] at hlen + have hex := List.append_inj he (by omega : l.length=h.length) + obtain ⟨rfl,hyx⟩ := hex + have : y=x := by simpa using hyx + subst y + exact hy + exact aux _ hs h x rfl + · exact SuccessfulHistory.snoc h x hh +end ActualHistory +section ActualPhase +open scoped BigOperators Classical +variable (n : ℕ) (hn : 0 pairedSlots n +local notation "W" => (((Fin n ⊕ Fin n) × (Fin n ⊕ Fin n)) → ((Fin n ⊕ Fin n) × (Fin n ⊕ Fin n)) → ℝ) +def restartCap (n L : ℕ) : ℕ := 2000*(L+1)^2*n^2*(20*n^4*(n*(L+1)+2)) +include hn in +lemma restartCap_pos (L : ℕ) : 0 pairedSlots n +variable (N L : ℕ) (η : ℝ) (hη0 : 0<η) (hη1 : η ≤ 1/3) +include hE hR hη0 hη1 in +lemma phaseStart_warm (h : List (PhaseSample n N)) + (hh : SuccessfulHistory GS M n η (observedSets n N) h) (hj : h.length ≤ L) : + let hp := successfulHistory_positive n hn M N η hη0.le hη1 h hh + ∀ S,phaseStart n hn M N L h hp S ≤ + (10*(n:ℝ)^2)*chainWeight GS (storedWeights n N h h.length) + (annealWeight M n h.length) S.val / + chainTotal GS (storedWeights n N h h.length) (annealWeight M n h.length) := by + intro hp S + let good := successfulHistory_stored_good n hn M N η hη0.le hη1 h hh h.length le_rfl + have hw := restartLaw_warm n hn M hE hR L (restartCap n L) (storedWeights n N h) + (historyPositive_all n N h hp) h.length hj good + simpa only [phaseStart,pairedSlots_length] using plainLift_warm GS (pairedSlots_fresh n) + (pairedSlots_ne_nil n hn) (pairedSlots_cover n) (storedWeights n N h h.length) + (annealWeight M n h.length) (annealWeight_pos M n h.length hn) good _ hw S +include hE hR hη0 hη1 in +lemma phaseStart_mass_lower (h : List (PhaseSample n N)) + (hh : SuccessfulHistory GS M n η (observedSets n N) h) (hj : h.length ≤ L) : + let hp := successfulHistory_positive n hn M N η hη0.le hη1 h hh + 1-1/(100*(L+1:ℝ)) ≤ ∑ S,phaseStart n hn M N L h hp S := by + intro hp + have hm := restartLaw_missing_mass n hn M hE hR L (restartCap n L) (restartCap_pos n hn L) + (storedWeights n N h) (historyPositive_all n N h hp) h.length hj + (fun a ha => successfulHistory_stored_good n hn M N η hη0.le hη1 h hh a ha) + have he := restartCap_loss n hn L h.length hj + simp only [phaseStart,plainLift_mass] + linarith +include hE hR hη0 hη1 in +lemma phaseKernel_good_mass + (hN : (10:ℝ)^10*(L+1)*n^14/η^2 ≤ N) + (h : List (PhaseSample n N)) (hh : SuccessfulHistory GS M n η (observedSets n N) h) + (hj : h.length ≤ L) : + 1-1/(20*(L+1:ℝ)) ≤ ∑ v,FiniteExperiment.restrict (phaseKernel n hn M N L) + (SuccessfulHistory GS M n η (observedSets n N)) h v := by + let hp := successfulHistory_positive n hn M N η hη0.le hη1 h hh + let good := successfulHistory_stored_good n hn M N η hη0.le hη1 h hh h.length le_rfl + have hrho := annealRho_bounds n hn + have hρ : 0 annealRho n^(n-(M.eRk S).toNat)) good (annealWeight_pos M n h.length hn) + hsig hg (phaseStart n hn M N L h hp) (phaseStart_nonneg n hn M N L h hp) + (by simpa only [pairedSlots_length] using phaseStart_warm n hn M hE hR N L η hη0 hη1 h hh hj) + L N η hη0 (by simpa only [pairedSlots_length] using hN) + have he : (∑ v,FiniteExperiment.restrict (phaseKernel n hn M N L) + (SuccessfulHistory GS M n η (observedSets n N)) h v) = + (phaseChain n hn M N h hp).pathProbability (phaseStart n hn M N L h hp) (N-1) + (fun l => AccuratePhase GS (storedWeights n N h h.length) (annealWeight M n h.length) + (fun S => annealRho n^(n-(M.eRk S).toNat)) η (l.map Subtype.val)) := by + rw [← FiniteChain.sampleMass_event] + apply Finset.sum_congr rfl + intro v _ + simp only [FiniteExperiment.restrict,successfulHistory_snoc_iff GS M n η (observedSets n N) h v hh, + phaseKernel,dite_eq_left hp,storedWeights_current,observedSets] + rw [he] + change (∑ S,phaseStart n hn M N L h hp S)-1/(32*(L+1:ℝ)) ≤ + (phaseChain n hn M N h hp).pathProbability _ _ _ at ha + have hm := phaseStart_mass_lower n hn M hE hR N L η hη0 hη1 h hh hj + have he' : 1/(100*(L+1:ℝ))+1/(32*(L+1:ℝ)) ≤ 1/(20*(L+1:ℝ)) := by + have hl : 0<(L:ℝ)+1 := by positivity + field_simp + nlinarith + linarith +include hE hR hη0 hη1 in + +theorem actual_history_success + (hN : (10:ℝ)^10*(L+1)*n^14/η^2 ≤ N) : + 19/20 ≤ FiniteExperiment.expect (phaseKernel n hn M N L) L [] + (fun h => if SuccessfulHistory GS M n η (observedSets n N) h then 1 else 0) := by + have h := FiniteExperiment.good_probability_bounded (phaseKernel n hn M N L) + (SuccessfulHistory GS M n η (observedSets n N)) (phaseKernel_nonneg n hn M N L) + (phaseKernel_mass_le n hn M N L) L (1/(20*(L+1:ℝ))) (by positivity) + (fun h hh hj => phaseKernel_good_mass n hn M hE hR N L η hη0 hη1 hN h hh hj.le) + SuccessfulHistory.nil + apply le_trans _ h + have hl : 0<(L:ℝ)+1 := by positivity + apply (le_sub_iff_add_le).mpr + field_simp + nlinarith +end PhaseSuccess +section HistoryEstimate +open scoped BigOperators Classical +variable {Γ : Type*} [sectionInstance107 : Fintype Γ] [sectionInstance108 : DecidableEq Γ] +variable {X : Type*} (sample : X → List (Set Γ)) +def historySample (h : List X) (j : ℕ) : List (Set Γ) := (h[j]?.map sample).getD [] +omit sectionInstance107 sectionInstance108 in +lemma historySample_getElem [Fintype Γ] [DecidableEq Γ] (h : List X) (j : ℕ) (hj : j annealRho n^(n-(M.eRk S).toNat)) η (historySample sample h j) := by + have ht := successfulHistory_take gs M n η sample h hh j + have hs := successfulHistory_take gs M n η sample h hh (j+1) + rw [List.take_succ_eq_append_getElem hj] at hs + have ha := (successfulHistory_snoc_iff gs M n η sample (h.take j) h[j] ht).mp hs + simpa only [List.length_take,Nat.min_eq_left hj.le,historySample_getElem sample h j hj] using ha +end HistoryEstimate +section ActualHistoryEstimate +open scoped BigOperators Classical +variable (n : ℕ) (N L : ℕ) (M : Matroid (Fin n ⊕ Fin n)) +noncomputable def historyEstimate (h : List (PhaseSample n N)) : ℝ := + (2:ℝ)^n * ∏ j ∈ Finset.range L, + empiricalRatio (pairedSlots n) (fun S => annealRho n^(n-(M.eRk S).toNat)) + (historySample (observedSets n N) h j) +lemma historyEstimate_accuracy (hn : 0 successfulHistory_accurate (observedSets n N) (pairedSlots n) (pairedMatroid M₁ M₂) + n (annealTolerance ε (annealLength n b)) h hh j (by omega)) +lemma empirical_nonneg {Γ : Type*} (H : Set Γ → ℝ) (hH : ∀ S,0 ≤ H S) (l : List (Set Γ)) : + 0 ≤ empirical H l := by + unfold empirical + apply div_nonneg _ (Nat.cast_nonneg _) + exact List.sum_nonneg (fun x hx => by obtain ⟨S,hS,rfl⟩ := List.mem_map.mp hx; exact hH S) +lemma empiricalRatio_nonneg {Γ : Type*} [Fintype Γ] [DecidableEq Γ] + (gs : List (Γ × Γ)) (g : Set Γ → ℝ) (hg : ∀ S,0 ≤ g S) (l : List (Set Γ)) : + 0 ≤ empiricalRatio gs g l := by + unfold empiricalRatio + apply div_nonneg + · apply empirical_nonneg; intro S; unfold plainObservable; split_ifs; exact hg S; rfl + · apply empirical_nonneg; intro S; unfold plainObservable; split_ifs <;> norm_num +lemma historyEstimate_nonneg (hn : 0 pow_nonneg (le_trans (by norm_num) (annealRho_bounds n hn).1) _) _ +end ActualHistoryEstimate +section WitnessRestart +open scoped BigOperators Classical +variable (n : ℕ) (hn : 0 pairedMatroid M₁ M₂ +local notation "GS" => pairedSlots n +local notation "W" => (((Fin n ⊕ Fin n) × (Fin n ⊕ Fin n)) → ((Fin n ⊕ Fin n) × (Fin n ⊕ Fin n)) → ℝ) +def Witnessed (x : PlainIndex GS) : Prop := n-((K).eRk x.val.val).toNat=0 +lemma witnessed_iff_common_base (hE₂ : M₂.E=Set.univ) (hr : M₁.eRank=M₂.eRank) (x : PlainIndex GS) : + Witnessed n M₁ M₂ x ↔ M₁.IsBase (Sum.inl ⁻¹' x.val.val) ∧ M₂.IsBase (Sum.inl ⁻¹' x.val.val) := by + unfold Witnessed + rw [plain_eq_transversal n x.val.val x.property] + simpa only [preimage_inl_transversal,subsetDeficiency] using subsetDeficiency_zero M₁ M₂ hE₂ hr (Sum.inl ⁻¹' x.val.val) +lemma witnessed_count_pos (hE₂ : M₂.E=Set.univ) (hr : M₁.eRank=M₂.eRank) (x : PlainIndex GS) + (hx : Witnessed n M₁ M₂ x) : 0 hlocal x) + simp only [Finset.sum_const,Finset.card_univ,nsmul_eq_mul,plainIndex_card,Nat.cast_pow,Nat.cast_ofNat] at hs + have he := anneal_final_contamination n b hn ε hb + dsimp only [q] at hs + linarith +variable (N : ℕ) +noncomputable def witnessKernel (L : ℕ) (h : List (PhaseSample n N)) (x : PlainIndex GS) : ℝ := + if hp : HistoryPositive n N h then + restartLaw n hn K L (restartCap n L) (storedWeights n N h) (historyPositive_all n N h hp) h.length x + else 0 +lemma witnessKernel_nonneg (L : ℕ) (h : List (PhaseSample n N)) (x : PlainIndex GS) : + 0 ≤ witnessKernel n hn M₁ M₂ N L h x := by + unfold witnessKernel + split_ifs with hp + · exact restartLaw_nonneg n hn K L _ _ _ _ x + · rfl +lemma witnessKernel_mass_le (L : ℕ) (h : List (PhaseSample n N)) : + (∑ x,witnessKernel n hn M₁ M₂ N L h x) ≤ 1 := by + unfold witnessKernel + split_ifs with hp + · exact restartLaw_mass_le n hn K L _ _ _ _ + · simp +include hn in +lemma witnessKernel_good_mass (hE₁ : M₁.E=Set.univ) (hE₂ : M₂.E=Set.univ) (hr : M₁.eRank=M₂.eRank) + (ε : ℝ) (hε0 : 0<ε) (hε1 : ε<1) (b : ℕ) (hb : (1/2:ℝ)^b ≤ ε/10) + (hZ : 0 simp + have hsmall : 1/(100*(L+1:ℝ)) ≤ 1/100 := by + apply (div_le_iff₀ (by positivity : (0:ℝ)<100*(L+1:ℝ))).mpr + nlinarith [Nat.cast_nonneg (α := ℝ) L] + have hm' : 99/100 ≤ ∑ x,witnessKernel n hn M₁ M₂ N L h x := by + simp only [witnessKernel,dite_eq_left hp] + linarith + change 79/100 ≤ ∑ x,if Witnessed n M₁ M₂ x then witnessKernel n hn M₁ M₂ N L h x else 0 + linarith +end WitnessRestart +namespace FiniteExperiment +open scoped BigOperators Classical +variable {X : Type*} [Fintype X] +lemma expect_mul_left (K : List X → X → ℝ) (r : ℝ) (φ : List X → ℝ) (t : ℕ) (h : List X) : + expect K t h (fun l => r*φ l)=r*expect K t h φ := by + induction t generalizing h with + | zero => rfl + | succ t ih => + simp only [expect,ih] + rw [Finset.mul_sum] + apply Finset.sum_congr rfl + intro x _ + ring +lemma expect_mono_length (K : List X → X → ℝ) (hK : ∀ h x,0 ≤ K h x) + (φ ψ : List X → ℝ) (t : ℕ) (h : List X) + (hh : ∀ l,l.length=h.length+t → φ l ≤ ψ l) : + expect K t h φ ≤ expect K t h ψ := by + induction t generalizing h with + | zero => exact hh h (by simp) + | succ t ih => + apply Finset.sum_le_sum + intro x _ + apply mul_le_mul_of_nonneg_left _ (hK h x) + apply ih + intro l hl + apply hh l + simp only [List.length_append,List.length_singleton] at hl + omega +end FiniteExperiment +open scoped BigOperators Classical +variable (n : ℕ) (hn : 0 pairedMatroid M₁ M₂ +local notation "GS" => pairedSlots n +noncomputable def guardedEstimate (h : List (PhaseSample n N)) (x : PlainIndex GS) : ℝ := + if Witnessed n M₁ M₂ x then historyEstimate n N L K h else 0 +include hn in +lemma guardedEstimate_nonneg (h : List (PhaseSample n N)) (x : PlainIndex GS) : + 0 ≤ guardedEstimate n M₁ M₂ N L h x := by + unfold guardedEstimate + split_ifs + · exact historyEstimate_nonneg n N L K hn h + · rfl +lemma guardedEstimate_zero (hE₂ : M₂.E=Set.univ) (hr : M₁.eRank=M₂.eRank) + (hZ : commonBaseCount M₁ M₂=0) (h : List (PhaseSample n N)) (x : PlainIndex GS) : + guardedEstimate n M₁ M₂ N L h x=0 := by + unfold guardedEstimate + apply ite_eq_right + intro hx + have hp := witnessed_count_pos n M₁ M₂ hE₂ hr x hx + omega +noncomputable def actualRealSuccess (ε : ℝ) : ℝ := + FiniteExperiment.expect (phaseKernel n hn K N L) L [] (fun h => + ∑ x,if (1-ε)*(commonBaseCount M₁ M₂:ℝ) ≤ guardedEstimate n M₁ M₂ N L h x ∧ + guardedEstimate n M₁ M₂ N L h x ≤ (1+ε)*(commonBaseCount M₁ M₂:ℝ) + then witnessKernel n hn M₁ M₂ N L h x else 0) + +theorem real_annealing_success (hE₁ : M₁.E=Set.univ) (hE₂ : M₂.E=Set.univ) + (hr : M₁.eRank=M₂.eRank) (ε : ℝ) (hε0 : 0<ε) (hε1 : ε<1) + (b : ℕ) (hb : (1/2:ℝ)^b ≤ ε/10) (hZ : 0 (79/100)*(if Good h then 1 else 0)) + (fun h => ∑ x,if (1-ε)*(commonBaseCount M₁ M₂:ℝ) ≤ guardedEstimate n M₁ M₂ N L h x ∧ + guardedEstimate n M₁ M₂ N L h x ≤ (1+ε)*(commonBaseCount M₁ M₂:ℝ) + then witnessKernel n hn M₁ M₂ N L h x else 0) L [] (by + intro h hlen + have hlen' : h.length=L := by simpa using hlen + by_cases hh : Good h + · simp only [ite_eq_left hh,mul_one] + have he := historyEstimate_accuracy n N hn M₁ M₂ hE₂ hr ε hε0 hε1 b hb hZ h hlen' hh + apply (witnessKernel_good_mass n hn M₁ M₂ N hE₁ hE₂ hr ε hε0 hε1 b hb hZ h hlen' hh).trans + apply Finset.sum_le_sum + intro x _ + by_cases hx : Witnessed n M₁ M₂ x + · simp only [guardedEstimate,ite_eq_left hx] + rw [ite_eq_left he] + · simp only [ite_eq_right hx] + split_ifs + · exact witnessKernel_nonneg n hn M₁ M₂ N L h x + · rfl + · simp only [ite_eq_right hh,mul_zero] + exact Finset.sum_nonneg (fun x _ => by + split_ifs + · exact witnessKernel_nonneg n hn M₁ M₂ N L h x + · rfl)) + rw [FiniteExperiment.expect_mul_left] at hmono + change 3/4 ≤ actualRealSuccess n hn M₁ M₂ N L ε + apply le_trans _ hmono + have h := mul_le_mul_of_nonneg_left hmain (by norm_num : (0:ℝ) ≤ 79/100) + norm_num at h ⊢ + exact le_trans (by norm_num) h + +end + +section + +open scoped BigOperators Classical +abbrev BitWord (h : ℕ) := Fin h → Bool + +def wordEquiv : (h : ℕ) → BitWord h ≃ Fin (2^h) + | 0 => { toFun := fun _ => 0 + invFun := fun _ => Fin.elim0 + left_inv := fun _ => Subsingleton.elim _ _ + right_inv := by + intro i + apply Fin.ext + have hi : i.val < 1 := by exact i.isLt + change 0=i.val + omega } + | h+1 => (Fin.consEquiv (fun _ : Fin (h+1) => Bool)).symm |>.trans + ((Equiv.prodCongr finTwoEquiv.symm (wordEquiv h)).trans + (finProdFinEquiv.trans (finCongr (by rw [pow_succ]; omega : 2*2^h=2^(h+1))))) +noncomputable def uniformAverage {X : Type*} [Fintype X] (f : X → ℝ) : ℝ := + (∑ x,f x)/(Fintype.card X:ℝ) +lemma uniformAverage_equiv {X Y : Type*} [Fintype X] [Fintype Y] + (e : X ≃ Y) (f : Y → ℝ) : uniformAverage (fun x => f (e x))=uniformAverage f := by + rw [uniformAverage,uniformAverage,e.sum_comp,Fintype.card_congr e] +lemma uniformAverage_const {X : Type*} [Fintype X] [Nonempty X] (r : ℝ) : + uniformAverage (fun _ : X => r)=r := by + have h : (Fintype.card X:ℝ)≠0 := by exact_mod_cast ne_of_gt (Fintype.card_pos) + simp [uniformAverage,h] +lemma uniformAverage_add {X : Type*} [Fintype X] (f g : X → ℝ) : + uniformAverage (fun x => f x+g x)=uniformAverage f+uniformAverage g := by + simp [uniformAverage,Finset.sum_add_distrib,add_div] +lemma uniformAverage_mul_left {X : Type*} [Fintype X] (r : ℝ) (f : X → ℝ) : + uniformAverage (fun x => r*f x)=r*uniformAverage f := by + simp [uniformAverage,← Finset.mul_sum,mul_div_assoc] +lemma uniformAverage_prod {X Y : Type*} [Fintype X] [Fintype Y] (f : X × Y → ℝ) : + uniformAverage f=uniformAverage (fun x => uniformAverage (fun y => f (x,y))) := by + simp only [uniformAverage,Fintype.sum_prod_type,Fintype.card_prod,Nat.cast_mul] + rw [← Finset.sum_div] + ring +lemma uniformAverage_fin_succ {X : Type*} [Fintype X] (D : ℕ) + (f : (Fin (D+1) → X) → ℝ) : + uniformAverage f=uniformAverage (fun x => uniformAverage (fun rest => f (Fin.cons x rest))) := by + rw [← uniformAverage_equiv (Fin.consEquiv (fun _ : Fin (D+1) => X)) f,uniformAverage_prod] + rfl + +def boundedUniform (v h : ℕ) : (D : ℕ) → (Fin D → BitWord h) → Option (Fin v) + | 0,_ => none + | D+1,bits => + let x := wordEquiv h (bits 0) + if hx : x.val < v then some ⟨x.val,hx⟩ else boundedUniform v h D (Fin.tail bits) +noncomputable def rejectionRate (v h : ℕ) : ℝ := (2^h-v:ℕ)/(2:ℝ)^h +lemma acceptedCard (v T : ℕ) (hv : v≤T) : + Fintype.card {x : Fin T // x.val < v}=v := by + let e : {x : Fin T // x.val < v} ≃ Fin v := + { toFun := fun x => ⟨x.val.val,x.property⟩ + invFun := fun x => ⟨⟨x.val,lt_of_lt_of_le x.isLt hv⟩,x.isLt⟩ + left_inv := by intro x; rfl + right_inv := by intro x; rfl } + simpa using Fintype.card_congr e +lemma rejectedCard (v T : ℕ) (hv : v≤T) : + Fintype.card {x : Fin T // ¬x.val < v}=T-v := by + rw [Fintype.card_subtype_compl,acceptedCard v T hv,Fintype.card_fin] +lemma sum_ite_count {X : Type*} [Fintype X] (p : X → Prop) [DecidablePred p] (r : ℝ) : + (∑ x,if p x then r else 0)=(Fintype.card {x // p x}:ℝ)*r := by + rw [← Finset.sum_filter] + simp only [Finset.sum_const,nsmul_eq_mul] + congr 1 + exact_mod_cast (Fintype.card_subtype p).symm +lemma one_trial_none (v h : ℕ) (hv : v≤2^h) (r : ℝ) : + uniformAverage (fun bits : BitWord h => if (wordEquiv h bits).val < v then 0 else r)= + rejectionRate v h*r := by + rw [uniformAverage_equiv (wordEquiv h) (fun x => if x.val simp [hx] + _ = _ := by rw [sum_ite_count,rejectedCard _ _ hv] + rw [he,Fintype.card_fin,Nat.cast_pow,Nat.cast_ofNat] + ring +lemma one_trial_some (v h : ℕ) (hv : v≤2^h) (a : Fin v) (r : ℝ) : + uniformAverage (fun bits : BitWord h => + if hx : (wordEquiv h bits).val + if hx : (wordEquiv h bits).val (if wordEquiv h bits=aT then 1 else 0)+ + (if (wordEquiv h bits).val if x=aT then 1 else 0)] + simp [uniformAverage,aT] +lemma boundedUniform_failure (v h D : ℕ) (hv : v≤2^h) : + uniformAverage (fun bits => if boundedUniform v h D bits=none then (1:ℝ) else 0)= + rejectionRate v h^D := by + induction D with + | zero => simp [boundedUniform,uniformAverage_const] + | succ D ih => + rw [uniformAverage_fin_succ] + have he : (fun x : BitWord h => uniformAverage (fun rest : Fin D → BitWord h => + if boundedUniform v h (D+1) (Fin.cons x rest)=none then (1:ℝ) else 0)) = + fun x => if (wordEquiv h x).val if boundedUniform v h D bits=none then (1:ℝ) else 0)≤(1/2:ℝ)^D := by + rw [boundedUniform_failure v h D hv] + exact pow_le_pow_left₀ (rejectionRate_bounds v h hv hhalf).1 + (rejectionRate_bounds v h hv hhalf).2 D +lemma clog_trial_size (v : ℕ) (hv : 0 if boundedUniform v h D bits=some a then (1:ℝ) else 0)= + (1-rejectionRate v h^D)/(v:ℝ) := by + have hv' : (v:ℝ)≠0 := by exact_mod_cast ne_of_gt hv0 + have hT : (2:ℝ)^h≠0 := by positivity + induction D with + | zero => simp [boundedUniform,uniformAverage_const] + | succ D ih => + rw [uniformAverage_fin_succ] + have he : (fun x : BitWord h => uniformAverage (fun rest : Fin D → BitWord h => + if boundedUniform v h (D+1) (Fin.cons x rest)=some a then (1:ℝ) else 0)) = + fun x => if hx : (wordEquiv h x).val ∑ j,f j x)=∑ j,uniformAverage (f j) := by + unfold uniformAverage + rw [Finset.sum_comm,Finset.sum_div] + +lemma boundedUniform_law (v h D : ℕ) (hv : v ≤ 2^h) (hv0 : 0 < v) (φ : Option (Fin v) → ℝ) : + uniformAverage (fun bits => φ (boundedUniform v h D bits)) = + rejectionRate v h^D*φ none + (1-rejectionRate v h^D)*uniformAverage (fun a => φ (some a)) := by + have he : (fun bits => φ (boundedUniform v h D bits)) = fun bits => + φ none*(if boundedUniform v h D bits=none then 1 else 0) + + ∑ a : Fin v,φ (some a)*(if boundedUniform v h D bits=some a then 1 else 0) := by + funext bits + cases e : boundedUniform v h D bits with + | none => simp + | some a => simp + rw [he,uniformAverage_add,uniformAverage_mul_left,boundedUniform_failure v h D hv, + uniformAverage_sum] + simp_rw [uniformAverage_mul_left,boundedUniform_probability v h D hv hv0] + rw [← Finset.sum_mul] + unfold uniformAverage + rw [Fintype.card_fin] + ring + +lemma uniformAverage_nonneg {X : Type*} [Fintype X] (f : X → ℝ) + (hf : ∀ x,0≤f x) : 0≤uniformAverage f := by + exact div_nonneg (Finset.sum_nonneg (fun x _ => hf x)) (Nat.cast_nonneg _) +lemma uniformAverage_mono {X : Type*} [Fintype X] (f g : X → ℝ) + (hfg : ∀ x,f x≤g x) : uniformAverage f≤uniformAverage g := by + exact div_le_div_of_nonneg_right (Finset.sum_le_sum (fun x _ => hfg x)) (Nat.cast_nonneg _) +lemma uniformAverage_sub_const {X : Type*} [Fintype X] [Nonempty X] (f : X → ℝ) (r : ℝ) : + uniformAverage (fun x => f x-r)=uniformAverage f-r := by + unfold uniformAverage + rw [Finset.sum_sub_distrib,sub_div] + simp only [Finset.sum_const,Finset.card_univ,nsmul_eq_mul] + have h : (Fintype.card X:ℝ)≠0 := by exact_mod_cast ne_of_gt (Fintype.card_pos) + field_simp + +def bitPrefix (h H : ℕ) (hh : h≤H) (w : BitWord H) : BitWord h := + fun i => w ⟨i.val,lt_of_lt_of_le i.isLt hh⟩ +lemma uniformAverage_bitPrefix (h H : ℕ) (hh : h≤H) (φ : BitWord h → ℝ) : + uniformAverage (fun w => φ (bitPrefix h H hh w))=uniformAverage φ := by + obtain ⟨t,rfl⟩ := Nat.exists_eq_add_of_le hh + rw [← uniformAverage_equiv (Fin.appendEquiv h t) (fun w => φ (bitPrefix h (h+t) hh w)),uniformAverage_prod] + have he : ∀ a : BitWord h,∀ b : BitWord t,bitPrefix h (h+t) hh ((Fin.appendEquiv h t) (a,b))=a := by + intro a b + funext i + change Fin.append a b (Fin.castAdd t i)=a i + simp + simp_rw [he,uniformAverage_const] +lemma uniformAverage_prefixTrials (h H D : ℕ) (hh : h≤H) + (φ : (Fin D → BitWord h) → ℝ) : + uniformAverage (fun w : Fin D → BitWord H => φ (fun d => bitPrefix h H hh (w d)))=uniformAverage φ := by + induction D with + | zero => + have he : ∀ w : Fin 0 → BitWord H,(fun d => bitPrefix h H hh (w d))=(fun d : Fin 0 => Fin.elim0 d) := by + intro w; funext d; exact Fin.elim0 d + have hf : ∀ w : Fin 0 → BitWord h,w=(fun d : Fin 0 => Fin.elim0 d) := by + intro w; funext d; exact Fin.elim0 d + simp_rw [he] + rw [uniformAverage_const] + conv_rhs => arg 1; ext w; rw [hf w] + rw [uniformAverage_const] + | succ D ih => + rw [uniformAverage_fin_succ,uniformAverage_fin_succ] + have he : ∀ x : BitWord H,∀ xs : Fin D → BitWord H, + (fun d : Fin (D+1) => bitPrefix h H hh ((Fin.cons x xs : Fin (D+1) → BitWord H) d))= + Fin.cons (bitPrefix h H hh x) (fun d => bitPrefix h H hh (xs d)) := by + intro x xs; funext d; refine Fin.cases ?_ (fun i => ?_) d <;> rfl + simp_rw [he] + have hhφ : ∀ x : BitWord H, + uniformAverage (fun xs : Fin D → BitWord H => φ (Fin.cons (bitPrefix h H hh x) (fun d => bitPrefix h H hh (xs d))))= + uniformAverage (fun xs : Fin D → BitWord h => φ (Fin.cons (bitPrefix h H hh x) xs)) := by + intro x + exact ih (fun xs => φ (Fin.cons (bitPrefix h H hh x) xs)) + simp_rw [hhφ] + exact uniformAverage_bitPrefix h H hh (fun x => uniformAverage (fun xs => φ (Fin.cons x xs))) + +inductive DrawTree (A : Type*) where + | leaf (a : A) + | draw (v : ℕ) (next : Fin (v+1) → DrawTree A) +namespace DrawTree + +section +open scoped BigOperators Classical +variable {A : Type*} +noncomputable def expectation (φ : A → ℝ) : DrawTree A → ℝ + | .leaf a => φ a + | .draw _ k => uniformAverage (fun i => expectation φ (k i)) +lemma expectation_nonneg (φ : A → ℝ) (hφ : ∀ a,0≤φ a) (t : DrawTree A) : + 0≤t.expectation φ := by + induction t with + | leaf a => exact hφ a + | draw v k ih => exact uniformAverage_nonneg _ ih +lemma expectation_le_one (φ : A → ℝ) (hφ : ∀ a,φ a≤1) (t : DrawTree A) : + t.expectation φ≤1 := by + induction t with + | leaf a => exact hφ a + | draw v k ih => + have h := uniformAverage_mono _ (fun _ : Fin (v+1) => 1) ih + simpa only [expectation,uniformAverage_const] using h + +def Fits (H : ℕ) : ℕ → DrawTree A → Prop + | _,.leaf _ => True + | 0,.draw _ _ => False + | M+1,.draw v k => Nat.clog 2 (v+1)≤H ∧ ∀ i,Fits H M (k i) + +def run (H D : ℕ) : (M : ℕ) → DrawTree A → (Fin M → Fin D → BitWord H) → Option A + | _,.leaf a,_ => some a + | 0,.draw _ _,_ => none + | M+1,.draw v k,bits => + if hh : Nat.clog 2 (v+1)≤H then + match boundedUniform (v+1) (Nat.clog 2 (v+1)) D + (fun d => bitPrefix _ H hh (bits 0 d)) with + | none => none + | some a => run H D M (k a) (Fin.tail bits) + else none + +def optionValue (φ : A → ℝ) : Option A → ℝ + | none => 0 + | some a => φ a +lemma run_draw_average (H D M v : ℕ) (k : Fin (v+1) → DrawTree A) + (hh : Nat.clog 2 (v+1)≤H) (φ : A → ℝ) : + uniformAverage (fun bits => optionValue φ (run H D (M+1) (.draw v k) bits))= + (1-rejectionRate (v+1) (Nat.clog 2 (v+1))^D)* + uniformAverage (fun a : Fin (v+1) => uniformAverage + (fun rest => optionValue φ (run H D M (k a) rest))) := by + rw [uniformAverage_fin_succ] + simp only [run,dite_eq_left hh,Fin.cons_zero,Fin.tail_cons] + let ψ : Option (Fin (v+1)) → ℝ := fun z => match z with + | none => 0 + | some a => uniformAverage (fun rest => optionValue φ (run H D M (k a) rest)) + have he : (fun x : Fin D → BitWord H => uniformAverage + (fun rest : Fin M → Fin D → BitWord H => optionValue φ + (match boundedUniform (v+1) (Nat.clog 2 (v+1)) D + (fun d => bitPrefix _ H hh (x d)) with + | none => none + | some a => run H D M (k a) rest))) = + fun x => ψ (boundedUniform (v+1) (Nat.clog 2 (v+1)) D + (fun d => bitPrefix _ H hh (x d))) := by + funext x + cases hz : boundedUniform (v+1) (Nat.clog 2 (v+1)) D + (fun d => bitPrefix _ H hh (x d)) with + | none => exact uniformAverage_const 0 + | some a => rfl + rw [he,uniformAverage_prefixTrials _ _ D hh (fun w => ψ (boundedUniform (v+1) (Nat.clog 2 (v+1)) D w))] + rw [boundedUniform_law _ _ _ (clog_trial_size _ (by omega)).1 (by omega)] + simp only [ψ,mul_zero,zero_add] + +theorem run_lower (H D M : ℕ) (t : DrawTree A) (ht : Fits H M t) + (φ : A → ℝ) (_ : ∀ a,0≤φ a) (hφ1 : ∀ a,φ a≤1) : + t.expectation φ-(M:ℝ)*(1/2:ℝ)^D ≤ + uniformAverage (fun bits => optionValue φ (run H D M t bits)) := by + induction M generalizing t with + | zero => + cases t with + | leaf a => simp [run,optionValue,expectation,uniformAverage_const] + | draw v k => exact False.elim ht + | succ M ih => + cases t with + | leaf a => + simp only [expectation,run,optionValue,uniformAverage_const] + have h : 0 ≤ ((M+1:ℕ):ℝ)*(1/2:ℝ)^D := by positivity + linarith + | draw v k => + obtain ⟨hh,hk⟩ := ht + rw [run_draw_average H D M v k hh φ] + have hlocal := uniformAverage_mono + (fun a => (k a).expectation φ-(M:ℝ)*(1/2:ℝ)^D) + (fun a => uniformAverage (fun bits => optionValue φ (run H D M (k a) bits))) + (fun a => ih (k a) (hk a)) + rw [uniformAverage_sub_const] at hlocal + let r := rejectionRate (v+1) (Nat.clog 2 (v+1))^D + have hb := rejectionRate_bounds (v+1) (Nat.clog 2 (v+1)) + (clog_trial_size _ (by omega)).1 (clog_trial_size _ (by omega)).2 + have hr0 : 0≤r := pow_nonneg hb.1 D + have hr : r≤(1/2:ℝ)^D := pow_le_pow_left₀ hb.1 hb.2 D + have hr1 : r≤1 := hr.trans (pow_le_one₀ (by norm_num) (by norm_num)) + have hE : uniformAverage (fun a => (k a).expectation φ)≤1 := + expectation_le_one φ hφ1 (.draw v k) + have hmul := mul_le_mul_of_nonneg_left hlocal (sub_nonneg.mpr hr1) + have hz : 0≤(M:ℝ)*(1/2:ℝ)^D := by positivity + change _ ≤ (1-r)*_ + change uniformAverage (fun a => (k a).expectation φ)-((M+1:ℕ):ℝ)*(1/2:ℝ)^D ≤ _ + push_cast + nlinarith [mul_nonneg hr0 hz,mul_nonneg hr0 (sub_nonneg.mpr hE)] +end +open scoped BigOperators Classical +variable {A B : Type*} +def bind : DrawTree A → (A → DrawTree B) → DrawTree B + | .leaf a,k => k a + | .draw v f,k => .draw v (fun i => (f i).bind k) +def map (f : A → B) (t : DrawTree A) : DrawTree B := t.bind (fun a => .leaf (f a)) +lemma expectation_bind (t : DrawTree A) (k : A → DrawTree B) (φ : B → ℝ) : + (t.bind k).expectation φ=t.expectation (fun a => (k a).expectation φ) := by + induction t with + | leaf a => rfl + | draw v f ih => simp only [bind,expectation,ih] +lemma expectation_map (t : DrawTree A) (f : A → B) (φ : B → ℝ) : + (t.map f).expectation φ=t.expectation (fun a => φ (f a)) := by + rw [map,expectation_bind]; rfl +lemma fits_mono_steps (H M M' : ℕ) (hM : M≤M') (t : DrawTree A) (ht : Fits H M t) : + Fits H M' t := by + induction M generalizing M' t with + | zero => cases t <;> simp_all [Fits] + | succ M ih => + cases t with + | leaf a => simp [Fits] + | draw v f => + cases M' with + | zero => omega + | succ M' => exact ⟨ht.1,fun i => ih M' (by omega) (f i) (ht.2 i)⟩ +lemma fits_bind (H M N : ℕ) (t : DrawTree A) (k : A → DrawTree B) + (ht : Fits H M t) (hk : ∀ a,Fits H N (k a)) : Fits H (M+N) (t.bind k) := by + induction M generalizing t with + | zero => cases t with + | leaf a => simpa only [bind,Nat.zero_add] using hk a + | draw v f => exact False.elim ht + | succ M ih => + cases t with + | leaf a => exact fits_mono_steps H N (M+1+N) (by omega) (k a) (hk a) + | draw v f => + have he : M+1+N=(M+N)+1 := by omega + rw [he] + exact ⟨ht.1,fun i => ih (f i) (ht.2 i)⟩ + +def rationalCoin (a v : ℕ) : DrawTree Bool := + .draw v (fun i => .leaf (decide (i.val φ (decide (i.val φ (decide (i.val φ false+if i.val simp [h] + rw [he,uniformAverage_add,uniformAverage_const] + unfold uniformAverage + rw [sum_ite_count,acceptedCard a (v+1) ha,Fintype.card_fin] + have hv : ((v+1:ℕ):ℝ)≠0 := by positivity + field_simp + ; ring +lemma rationalCoin_fits (a v H : ℕ) (hh : Nat.clog 2 (v+1)≤H) : + Fits H 1 (rationalCoin a v) := ⟨hh,fun _ => trivial⟩ +def bernoulli (p : ℚ) : DrawTree Bool := rationalCoin p.num.natAbs (p.den-1) +lemma bernoulli_expectation (p : ℚ) (hp0 : 0≤p) (hp1 : p≤1) (φ : Bool → ℝ) : + (bernoulli p).expectation φ=(p:ℝ)*φ true+(1-(p:ℝ))*φ false := by + have hd : p.den-1+1=p.den := by have h := p.den_pos; omega + have hn : (p.num.natAbs:ℤ)=p.num := Int.natAbs_of_nonneg (Rat.num_nonneg.mpr hp0) + have hnr : (p.num.natAbs:ℝ)=(p.num:ℝ) := by simpa only [Int.cast_natCast] using congrArg (fun z : ℤ => (z:ℝ)) hn + have he : (p.num.natAbs:ℝ)/(p.den:ℝ)=(p:ℝ) := by rw [hnr,Rat.cast_def] + have ha : p.num.natAbs≤p.den := by + have hd' : (0:ℝ) hn rfl⟩ + intro he + exact a.2.property (he ▸ a.1.property) +omit sectionInstance110 sectionInstance111 in +lemma exchangedSet_right_difference [Fintype Γ] [DecidableEq Γ] (S : Set Γ) (a : ExchangeChoice S) : + exchangedSet S a\S={a.2.val} := by + ext x + simp only [exchangedSet,Set.mem_sdiff,Set.mem_insert_iff,Set.mem_singleton_iff] + constructor + · rintro ⟨hh,hn⟩ + exact hh.resolve_right (fun h => hn h.1) + · intro he; subst x + exact ⟨Or.inl rfl,a.2.property⟩ +lemma exchangedSet_injective (S : Set Γ) : Function.Injective (exchangedSet S) := by + intro a b he + apply Prod.ext + · apply Subtype.ext + have h := congrArg (fun T => S\T) he + rw [exchangedSet_left_difference,exchangedSet_left_difference] at h + exact Set.singleton_injective h + · apply Subtype.ext + have h := congrArg (fun T => T\S) he + rw [exchangedSet_right_difference,exchangedSet_right_difference] at h + exact Set.singleton_injective h +lemma exchangedSet_exists_iff (S T : Set Γ) : + (∃ a : ExchangeChoice S,exchangedSet S a=T) ↔ ExchangeAdjacent S T := by + constructor + · rintro ⟨a,rfl⟩; exact exchangedSet_adjacent S a + · intro h + obtain ⟨a,ha,b,hb,he⟩ := h.move + exact ⟨(⟨a,ha⟩,⟨b,hb⟩),he.symm⟩ +lemma sum_exchangedSet_indicator (S T : Set Γ) (r : ℝ) : + (∑ a : ExchangeChoice S,if exchangedSet S a=T then r else 0)= + if ExchangeAdjacent S T then r else 0 := by + by_cases h : ExchangeAdjacent S T + · obtain ⟨a,ha⟩ := (exchangedSet_exists_iff S T).mpr h + have he : ∀ b : ExchangeChoice S,exchangedSet S b=T ↔ b=a := by + intro b; rw [←ha]; exact (exchangedSet_injective S).eq_iff + simp [he,h] + · have he : ∀ a : ExchangeChoice S, exchangedSet S a≠T := by + intro a ha; exact h ((exchangedSet_exists_iff S T).mp ⟨a,ha⟩) + simp [he,h] +lemma exchangeChoice_card (gs : List (Γ × Γ)) (hgs : SlotsFresh gs ∅) + (hcover : pairSupport gs=Set.univ) (S : ChainIndex gs) : + Fintype.card (ExchangeChoice S.val)=gs.length^2 := by + rw [Fintype.card_prod] + have hs : Fintype.card S.val=S.val.ncard := by rw [Set.ncard_eq_toFinset_card',Set.toFinset_card] + have hc : Fintype.card ↥(S.valᶜ)=S.valᶜ.ncard := by rw [Set.ncard_eq_toFinset_card',Set.toFinset_card] + rw [hs,hc] + have ht := S.val.ncard_add_ncard_compl + rw [Nat.card_eq_fintype_card,slots_ground_card gs hgs hcover,S.property.ncard hgs hcover] at ht + have hh : S.valᶜ.ncard=gs.length := by omega + rw [S.property.ncard hgs hcover,hh,pow_two] + +noncomputable def metropolisAcceptance (gs : List (Γ × Γ)) + (w : (Γ × Γ) → (Γ × Γ) → ℝ) (f : Set Γ → ℝ) (S T : ChainIndex gs) : ℝ := + min 1 (chainWeight gs w f T.val/chainWeight gs w f S.val) +noncomputable def exchangeOffer (gs : List (Γ × Γ)) + (w : (Γ × Γ) → (Γ × Γ) → ℝ) (f : Set Γ → ℝ) (S : ChainIndex gs) + (a : ExchangeChoice S.val) (φ : ChainIndex gs → ℝ) : ℝ := + if ht : ChainState gs (exchangedSet S.val a) then + let T : ChainIndex gs := ⟨exchangedSet S.val a,ht⟩ + metropolisAcceptance gs w f S T*φ T+(1-metropolisAcceptance gs w f S T)*φ S + else φ S +omit sectionInstance111 in +lemma exchangeOffer_expansion [DecidableEq Γ] (gs : List (Γ × Γ)) + (w : (Γ × Γ) → (Γ × Γ) → ℝ) (f : Set Γ → ℝ) (S : ChainIndex gs) + (a : ExchangeChoice S.val) (φ : ChainIndex gs → ℝ) : + exchangeOffer gs w f S a φ=φ S+∑ T : ChainIndex gs, + if exchangedSet S.val a=T.val then metropolisAcceptance gs w f S T*(φ T-φ S) else 0 := by + unfold exchangeOffer + split_ifs with ht + · let T : ChainIndex gs := ⟨exchangedSet S.val a,ht⟩ + have he : ∀ U : ChainIndex gs,exchangedSet S.val a=U.val ↔ U=T := by + intro U + constructor + · intro he; exact Subtype.ext he.symm + · intro he; subst U; rfl + simp only [he,Finset.sum_ite_eq',Finset.mem_univ,ite_true] + change _=φ S+metropolisAcceptance gs w f S T*(φ T-φ S) + ring + · have he : ∀ T : ChainIndex gs,exchangedSet S.val a≠T.val := by + intro T he; exact ht (he ▸ T.property) + simp [he] +lemma metropolisAcceptance_min (gs : List (Γ × Γ)) + (w : (Γ × Γ) → (Γ × Γ) → ℝ) (f : Set Γ → ℝ) + (hw : ∀ p r,0 exchangeOffer gs w f S a φ))/2= + (metropolisChain gs hgs hne hcover w f hw hf).apply φ S := by + have hn : (gs.length:ℝ)≠0 := by exact_mod_cast ne_of_gt (List.length_pos_iff.mpr hne) + have hc : (Fintype.card (ExchangeChoice S.val):ℝ)=(gs.length:ℝ)^2 := by + rw [exchangeChoice_card gs hgs hcover S,Nat.cast_pow] + have hex : uniformAverage (fun a => exchangeOffer gs w f S a φ)= + φ S+(∑ T : ChainIndex gs,if ExchangeAdjacent S.val T.val then + metropolisAcceptance gs w f S T*(φ T-φ S) else 0)/(gs.length:ℝ)^2 := by + simp_rw [exchangeOffer_expansion] + rw [uniformAverage_add] + have hnon : Nonempty (ExchangeChoice S.val) := Fintype.card_pos_iff.mp (by + rw [exchangeChoice_card gs hgs hcover S] + exact pow_pos (List.length_pos_iff.mpr hne) _) + let := hnon + rw [uniformAverage_const] + congr 1 + unfold uniformAverage + rw [hc,Finset.sum_comm] + simp_rw [sum_exchangedSet_indicator] + rw [hex] + change _=∑ T,(metropolisMove gs w f S T+if S=T then 1-∑ U,metropolisMove gs w f S U else 0)*φ T + simp_rw [add_mul,ite_mul,zero_mul] + rw [Finset.sum_add_distrib] + simp only [Finset.sum_ite_eq,Finset.mem_univ,ite_true] + have he : (∑ T : ChainIndex gs,if ExchangeAdjacent S.val T.val then + metropolisAcceptance gs w f S T*(φ T-φ S) else 0)/(gs.length:ℝ)^2/2= + ∑ T : ChainIndex gs,metropolisMove gs w f S T*(φ T-φ S) := by + rw [Finset.sum_div,Finset.sum_div] + apply Finset.sum_congr rfl + intro T _ + by_cases ht : ExchangeAdjacent S.val T.val + · simp only [metropolisMove,ite_eq_left ht,metropolisAcceptance_min gs w f hw hf] + field_simp + + · simp [metropolisMove,ht] + have hsum : (∑ T : ChainIndex gs,metropolisMove gs w f S T*(φ T-φ S))= + (∑ T : ChainIndex gs,metropolisMove gs w f S T*φ T)- + (∑ T : ChainIndex gs,metropolisMove gs w f S T)*φ S := by + simp [mul_sub,Finset.sum_sub_distrib,Finset.sum_mul] + linarith +end MetropolisSampling +section RationalSampling +open scoped BigOperators Classical +variable {Γ : Type*} [sectionInstance112 : Fintype Γ] [sectionInstance113 : DecidableEq Γ] +noncomputable def rationalMultiplier (gs : List (Γ × Γ)) + (w : (Γ × Γ) → (Γ × Γ) → ℚ) (S : Set Γ) : ℚ := + if h : ∃ p r,DefectState gs p r S then w h.choose h.choose_spec.choose else 1 +noncomputable def rationalWeight (gs : List (Γ × Γ)) + (w : (Γ × Γ) → (Γ × Γ) → ℚ) (f : Set Γ → ℚ) (S : Set Γ) : ℚ := + rationalMultiplier gs w S*f S +omit sectionInstance113 in +lemma rationalMultiplier_cast [DecidableEq Γ] (gs : List (Γ × Γ)) + (w : (Γ × Γ) → (Γ × Γ) → ℚ) (S : Set Γ) : + (rationalMultiplier gs w S:ℝ)=chainMultiplier gs (fun p r => (w p r:ℝ)) S := by + unfold rationalMultiplier chainMultiplier + split_ifs <;> simp +lemma rationalWeight_cast (gs : List (Γ × Γ)) + (w : (Γ × Γ) → (Γ × Γ) → ℚ) (f : Set Γ → ℚ) (S : Set Γ) : + (rationalWeight gs w f S:ℝ)=chainWeight gs (fun p r => (w p r:ℝ)) (fun S => (f S:ℝ)) S := by + simp [rationalWeight,chainWeight,rationalMultiplier_cast] +noncomputable def rationalEmpirical (H : Set Γ → ℚ) (l : List (Set Γ)) : ℚ := + (l.map H).sum/(l.length:ℚ) +omit sectionInstance112 sectionInstance113 in +lemma rationalEmpirical_cast [Fintype Γ] [DecidableEq Γ] (H : Set Γ → ℚ) (l : List (Set Γ)) : + (rationalEmpirical H l:ℝ)=empirical (fun S => (H S:ℝ)) l := by + simp [rationalEmpirical,empirical,Rat.cast_list_sum,List.map_map,Function.comp_def] +noncomputable def rationalPlain (gs : List (Γ × Γ)) (g : Set Γ → ℚ) (S : Set Γ) : ℚ := + if PlainState gs S then g S else 0 +omit sectionInstance112 sectionInstance113 in +lemma rationalPlain_cast [Fintype Γ] [DecidableEq Γ] (gs : List (Γ × Γ)) (g : Set Γ → ℚ) (S : Set Γ) : + (rationalPlain gs g S:ℝ)=plainObservable gs (fun S => (g S:ℝ)) S := by + unfold rationalPlain plainObservable; split_ifs <;> simp +noncomputable def rationalDefect (gs : List (Γ × Γ)) (p r : Γ × Γ) (S : Set Γ) : ℚ := + if DefectState gs p r S then 1 else 0 +omit sectionInstance112 sectionInstance113 in +lemma rationalDefect_cast [Fintype Γ] [DecidableEq Γ] (gs : List (Γ × Γ)) (p r : Γ × Γ) (S : Set Γ) : + (rationalDefect gs p r S:ℝ)=defectIndicator gs p r S := by + unfold rationalDefect defectIndicator; split_ifs <;> simp +noncomputable def rationalLearn (gs : List (Γ × Γ)) + (w : (Γ × Γ) → (Γ × Γ) → ℚ) (l : List (Set Γ)) (p r : Γ × Γ) : ℚ := + if p∈gs ∧ r∈gs ∧ p≠r then + w p r*(rationalEmpirical (rationalPlain gs (fun _ => 1)) l/rationalEmpirical (rationalDefect gs p r) l) + else w p r +lemma rationalLearn_cast (gs : List (Γ × Γ)) + (w : (Γ × Γ) → (Γ × Γ) → ℚ) (l : List (Set Γ)) (p r : Γ × Γ) : + (rationalLearn gs w l p r:ℝ)=learnedMultipliers gs (fun p r => (w p r:ℝ)) l p r := by + unfold rationalLearn learnedMultipliers + split_ifs <;> simp [rationalEmpirical_cast,rationalPlain_cast,rationalDefect_cast] +noncomputable def rationalHistory {X : Type*} (gs : List (Γ × Γ)) + (sample : X → List (Set Γ)) (h : List X) : (Γ × Γ) → (Γ × Γ) → ℚ := + h.foldl (fun w x => rationalLearn gs w (sample x)) (fun _ _ => 4) +lemma rationalHistory_cast {X : Type*} (gs : List (Γ × Γ)) + (sample : X → List (Set Γ)) (h : List X) (p r : Γ × Γ) : + (rationalHistory gs sample h p r:ℝ)=historyWeights gs sample h p r := by + induction h using List.reverseRecOn generalizing p r with + | nil => norm_num [rationalHistory,historyWeights] + | append_singleton h x ih => + simp only [rationalHistory,List.foldl_append,List.foldl_cons,List.foldl_nil,historyWeights_snoc] + rw [rationalLearn_cast] + have he : (fun p r => ((h.foldl (fun w x => rationalLearn gs w (sample x)) (fun _ _ => 4)) p r:ℝ))= + historyWeights gs sample h := by funext p r; exact ih p r + rw [he] + +def rationalRho (n : ℕ) : ℚ := 1-1/(2*(n:ℚ)) +lemma rationalRho_cast (n : ℕ) : (rationalRho n:ℝ)=annealRho n := by simp [rationalRho,annealRho] +noncomputable def rationalAnneal (M : Matroid Γ) (n j : ℕ) (S : Set Γ) : ℚ := + (rationalRho n^j)^(n-(M.eRk S).toNat) +omit sectionInstance112 sectionInstance113 in +lemma rationalAnneal_cast [Fintype Γ] [DecidableEq Γ] (M : Matroid Γ) (n j : ℕ) (S : Set Γ) : + (rationalAnneal M n j S:ℝ)=annealWeight M n j S := by simp [rationalAnneal,annealWeight,matroidWeight,rationalRho_cast] +noncomputable def rationalRatio (gs : List (Γ × Γ)) (g : Set Γ → ℚ) (l : List (Set Γ)) : ℚ := + rationalEmpirical (rationalPlain gs g) l / rationalEmpirical (rationalPlain gs (fun _ => 1)) l +lemma rationalRatio_cast (gs : List (Γ × Γ)) (g : Set Γ → ℚ) (l : List (Set Γ)) : + (rationalRatio gs g l:ℝ)=empiricalRatio gs (fun S => (g S:ℝ)) l := by + simp [rationalRatio,empiricalRatio,rationalEmpirical_cast,rationalPlain_cast] +end RationalSampling + +namespace DrawTree +open scoped BigOperators Classical +noncomputable def uniformChoice (A : Type*) [Fintype A] [Nonempty A] : DrawTree A := + let h : Fintype.card A-1+1=Fintype.card A := by have hh := Fintype.card_pos (α := A); omega + .draw (Fintype.card A-1) (fun i => .leaf ((Fintype.equivFin A).symm (Fin.cast h i))) +lemma uniformChoice_expectation (A : Type*) [Fintype A] [Nonempty A] (φ : A → ℝ) : + (uniformChoice A).expectation φ=uniformAverage φ := by + unfold uniformChoice + change uniformAverage (fun i => φ ((Fintype.equivFin A).symm (Fin.cast _ i)))=_ + exact uniformAverage_equiv ((finCongr (by have hh := Fintype.card_pos (α := A); omega)).trans (Fintype.equivFin A).symm) φ +lemma uniformChoice_fits (A : Type*) [Fintype A] [Nonempty A] (H : ℕ) + (h : Nat.clog 2 (Fintype.card A)≤H) : Fits H 1 (uniformChoice A) := by + unfold uniformChoice + refine ⟨?_,fun _ => trivial⟩ + have he : Fintype.card A-1+1=Fintype.card A := by have hh := Fintype.card_pos (α := A); omega + simpa only [he] using h +end DrawTree + +section RationalMetropolis +open scoped BigOperators Classical +variable {Γ : Type*} [Fintype Γ] [sectionInstance115 : DecidableEq Γ] +variable (gs : List (Γ × Γ)) +noncomputable def rationalAcceptance (w : (Γ × Γ) → (Γ × Γ) → ℚ) (f : Set Γ → ℚ) + (S T : ChainIndex gs) : ℚ := min 1 (rationalWeight gs w f T.val/rationalWeight gs w f S.val) +lemma rationalAcceptance_cast (w : (Γ × Γ) → (Γ × Γ) → ℚ) (f : Set Γ → ℚ) (S T : ChainIndex gs) : + (rationalAcceptance gs w f S T:ℝ)=metropolisAcceptance gs (fun p r => (w p r:ℝ)) (fun S => (f S:ℝ)) S T := by + simp [rationalAcceptance,metropolisAcceptance,rationalWeight_cast] +omit sectionInstance115 in +lemma rationalAcceptance_bounds [DecidableEq Γ] (w : (Γ × Γ) → (Γ × Γ) → ℚ) (f : Set Γ → ℚ) + (hw : ∀ p r,00 := by + intro S + unfold rationalWeight rationalMultiplier + apply mul_pos _ (hf S) + split_ifs <;> first | exact hw _ _ | norm_num + exact ⟨le_min (by norm_num) (div_nonneg (hpos _).le (hpos _).le),min_le_left _ _⟩ +noncomputable def rationalExchange (w : (Γ × Γ) → (Γ × Γ) → ℚ) (f : Set Γ → ℚ) + (S : ChainIndex gs) (a : ExchangeChoice S.val) : DrawTree (ChainIndex gs) := + if ht : ChainState gs (exchangedSet S.val a) then + let T : ChainIndex gs := ⟨exchangedSet S.val a,ht⟩ + (DrawTree.bernoulli (rationalAcceptance gs w f S T)).map (fun accept => if accept then T else S) + else .leaf S +lemma rationalExchange_expectation (w : (Γ × Γ) → (Γ × Γ) → ℚ) (f : Set Γ → ℚ) + (hw : ∀ p r,0 (w p r:ℝ)) (fun S => (f S:ℝ)) S a φ := by + unfold rationalExchange exchangeOffer + split_ifs with ht + · rw [DrawTree.expectation_map,DrawTree.bernoulli_expectation _ + (rationalAcceptance_bounds gs w f hw hf S _).1 (rationalAcceptance_bounds gs w f hw hf S _).2] + simp only [ite_true,Bool.false_eq_true,ite_false,rationalAcceptance_cast] + · rfl +noncomputable def rationalMetropolis (hgs : SlotsFresh gs ∅) (hne : gs≠[]) + (hcover : pairSupport gs=Set.univ) (w : (Γ × Γ) → (Γ × Γ) → ℚ) (f : Set Γ → ℚ) + (S : ChainIndex gs) : DrawTree (ChainIndex gs) := + letI : Nonempty (ExchangeChoice S.val) := Fintype.card_pos_iff.mp (by + rw [exchangeChoice_card gs hgs hcover S]; exact pow_pos (List.length_pos_iff.mpr hne) _) + (DrawTree.bernoulli (1/2)).bind (fun lazy => if lazy then .leaf S else + (DrawTree.uniformChoice (ExchangeChoice S.val)).bind (rationalExchange gs w f S)) +lemma rationalMetropolis_expectation (hgs : SlotsFresh gs ∅) (hne : gs≠[]) + (hcover : pairSupport gs=Set.univ) (w : (Γ × Γ) → (Γ × Γ) → ℚ) (f : Set Γ → ℚ) + (hw : ∀ p r,0 (w p r:ℝ)) (fun S => (f S:ℝ)) + (by intro p r; exact_mod_cast hw p r) (by intro S; exact_mod_cast hf S)).apply φ S := by + unfold rationalMetropolis + rw [DrawTree.expectation_bind,DrawTree.bernoulli_expectation _ (by norm_num) (by norm_num)] + simp only [ite_true,Bool.false_eq_true,ite_false,DrawTree.expectation, + DrawTree.expectation_bind,DrawTree.uniformChoice_expectation, + rationalExchange_expectation gs w f hw hf] + have he := lazy_exchange_expectation gs hgs hne hcover (fun p r => (w p r:ℝ)) (fun S => (f S:ℝ)) + (by intro p r; exact_mod_cast hw p r) (by intro S; exact_mod_cast hf S) S φ + rw [←he] + norm_num + ring +end RationalMetropolis +namespace DrawTree +open scoped BigOperators Classical +variable {A B D : Type*} +def optionBind (t : DrawTree (Option A)) (k : A → DrawTree (Option B)) : DrawTree (Option B) := + t.bind (fun z => match z with | none => .leaf none | some a => k a) +def pureSome (a : A) : DrawTree (Option A) := .leaf (some a) +lemma expectation_zero (t : DrawTree A) : t.expectation (fun _ => (0:ℝ))=0 := by + induction t with + | leaf a => rfl + | draw v f ih => simp only [expectation,ih,uniformAverage_const] +lemma expectation_add (t : DrawTree A) (φ ψ : A → ℝ) : + t.expectation (fun a => φ a+ψ a)=t.expectation φ+t.expectation ψ := by + induction t with + | leaf a => rfl + | draw v f ih => simp only [expectation,ih,uniformAverage_add] +lemma expectation_mul_left (t : DrawTree A) (c : ℝ) (φ : A → ℝ) : + t.expectation (fun a => c*φ a)=c*t.expectation φ := by + induction t with + | leaf a => rfl + | draw v f ih => simp only [expectation,ih,uniformAverage_mul_left] +lemma expectation_sum (t : DrawTree A) {J : Type*} (s : Finset J) (φ : J → A → ℝ) : + t.expectation (fun a => ∑ j ∈ s,φ j a)=∑ j ∈ s,t.expectation (φ j) := by + induction s using Finset.induction_on with + | empty => simp only [Finset.sum_empty,expectation_zero] + | @insert j s hj ih => simp only [Finset.sum_insert hj,expectation_add,ih] +lemma expectation_mono (t : DrawTree A) (φ ψ : A → ℝ) (h : ∀ a,φ a≤ψ a) : + t.expectation φ≤t.expectation ψ := by + induction t with + | leaf a => exact h a + | draw v f ih => exact uniformAverage_mono _ _ ih +lemma expectation_optionBind (t : DrawTree (Option A)) (k : A → DrawTree (Option B)) (φ : B → ℝ) : + (t.optionBind k).expectation (optionValue φ)= + t.expectation (optionValue (fun a => (k a).expectation (optionValue φ))) := by + rw [optionBind,expectation_bind] + congr 1; funext a; cases a <;> rfl +lemma optionBind_fits (t : DrawTree (Option A)) (k : A → DrawTree (Option B)) + (H M N : ℕ) (ht : Fits H M t) (hk : ∀ a,Fits H N (k a)) : + Fits H (M+N) (t.optionBind k) := by + apply fits_bind H M N t _ ht + intro a; cases a with + | none => cases N <;> trivial + | some a => exact hk a + +def Matches [Fintype B] (t : A → DrawTree (Option B)) (P : A → B → ℝ) : Prop := + ∀ a φ,(t a).expectation (optionValue φ)=∑ b,P a b*φ b +lemma matches_comp [Fintype A] [Fintype B] [Fintype D] + (t : A → DrawTree (Option B)) (u : B → DrawTree (Option D)) + (P : A → B → ℝ) (Q : B → D → ℝ) (ht : Matches t P) (hu : Matches u Q) : + Matches (fun a => (t a).optionBind u) (fun a d => ∑ b,P a b*Q b d) := by + intro a φ + rw [expectation_optionBind,ht] + simp_rw [show ∀ b,(u b).expectation (optionValue φ)=∑ d,Q b d*φ d from fun b => hu b φ] + simp only [Finset.mul_sum,Finset.sum_mul,mul_assoc] + exact Finset.sum_comm + +def iterate (t : A → DrawTree (Option A)) : ℕ → A → DrawTree (Option A) + | 0,a => pureSome a + | k+1,a => (iterate t k a).optionBind t +lemma iterate_matches [Fintype A] (t : A → DrawTree (Option A)) (K : FiniteKernel A A) + (ht : Matches t K.P) (k : ℕ) : Matches (iterate t k) (K.power k).P := by + induction k with + | zero => + intro a φ + change φ a=∑ b,(if a=b then (1:ℝ) else 0)*φ b + simp + | succ k ih => + have h := matches_comp (iterate t k) t (K.power k).P K.P ih ht + simpa only [iterate,FiniteKernel.power,FiniteKernel.comp] using h +lemma iterate_fits (t : A → DrawTree (Option A)) (H M k : ℕ) + (ht : ∀ a,Fits H M (t a)) : ∀ a,Fits H (M*k) (iterate t k a) := by + induction k with + | zero => intro a; trivial + | succ k ih => + intro a + have h := optionBind_fits (iterate t k a) t H (M*k) M (ih a) ht + simpa only [iterate,Nat.mul_succ] using h +end DrawTree + +section DrawHitting +open scoped BigOperators Classical +variable {X : Type*} [sectionInstance116 : Fintype X] +variable (step : X → DrawTree X) (A : X → Prop) +noncomputable def hittingTree : ℕ → X → DrawTree (Option (FiniteChain.Inside A)) + | 0,_ => .leaf none + | k+1,x => (step x).bind (fun y => if hy : A y then .leaf (some ⟨y,hy⟩) else hittingTree k y) +omit sectionInstance116 in +lemma hittingTree_fits [Fintype X] (H M k : ℕ) (hs : ∀ x,DrawTree.Fits H M (step x)) : + ∀ x,DrawTree.Fits H (M*k) (hittingTree step A k x) := by + induction k with + | zero => intro x; trivial + | succ k ih => + intro x + unfold hittingTree + have h := DrawTree.fits_bind H M (M*k) (step x) + (fun y => if hy : A y then DrawTree.leaf (some (⟨y,hy⟩ : FiniteChain.Inside A)) else hittingTree step A k y) + (hs x) (by intro y; split_ifs; exacts [by cases M*k <;> trivial,ih y]) + simpa only [Nat.mul_succ,Nat.add_comm] using h +variable (C : FiniteChain X) (Q : KilledKernel (FiniteChain.Outside A)) + (hQ : ∀ x y,Q.Q x y=C.P x.val y.val) + (hstep : ∀ x φ,(step x).expectation φ=C.apply φ x) +lemma partialGreen_succ_apply (k : ℕ) (f : FiniteChain.Outside A → ℝ) (x : FiniteChain.Outside A) : + Q.partialGreen (k+1) f x=f x+Q.apply (Q.partialGreen k f) x := by + unfold KilledKernel.partialGreen + rw [Finset.sum_range_succ'] + simp only [KilledKernel.iterate_succ,KilledKernel.iterate_zero] + rw [KilledKernel.apply_sum] + ring +include hQ hstep in +lemma hittingTree_outside (k : ℕ) (φ : FiniteChain.Inside A → ℝ) (x : FiniteChain.Outside A) : + (hittingTree step A k x.val).expectation (DrawTree.optionValue φ)= + Q.partialGreen k (fun z => ∑ y : FiniteChain.Inside A,C.P z.val y.val*φ y) x := by + induction k generalizing x with + | zero => simp [hittingTree,DrawTree.expectation,DrawTree.optionValue,KilledKernel.partialGreen] + | succ k ih => + rw [hittingTree,DrawTree.expectation_bind,hstep,FiniteChain.apply] + rw [←Fintype.sum_subtype_add_sum_subtype A] + have hin : (∑ y : FiniteChain.Inside A,C.P x.val y.val* + (if hy : A y.val then DrawTree.leaf (some (⟨y.val,hy⟩ : FiniteChain.Inside A)) else hittingTree step A k y.val).expectation (DrawTree.optionValue φ))= + ∑ y : FiniteChain.Inside A,C.P x.val y.val*φ y := by + apply Finset.sum_congr rfl; intro y _ + simp only [dite_eq_left y.property,DrawTree.expectation,DrawTree.optionValue] + have hout : (∑ y : FiniteChain.Outside A,C.P x.val y.val* + (if hy : A y.val then DrawTree.leaf (some (⟨y.val,hy⟩ : FiniteChain.Inside A)) else hittingTree step A k y.val).expectation (DrawTree.optionValue φ))= + Q.apply (Q.partialGreen k (fun z => ∑ y : FiniteChain.Inside A,C.P z.val y.val*φ y)) x := by + unfold KilledKernel.apply + apply Finset.sum_congr rfl; intro y _ + rw [dite_eq_right y.property,ih,hQ] + rw [hin,hout,partialGreen_succ_apply] +include hQ hstep in +lemma hittingTree_inside (k : ℕ) (x : FiniteChain.Inside A) (φ : FiniteChain.Inside A → ℝ) : + (hittingTree step A (k+1) x.val).expectation (DrawTree.optionValue φ)= + ∑ y : FiniteChain.Inside A,C.cappedTrace A Q k x y*φ y := by + rw [hittingTree,DrawTree.expectation_bind,hstep,FiniteChain.apply] + rw [←Fintype.sum_subtype_add_sum_subtype A] + have hin : (∑ y : FiniteChain.Inside A,C.P x.val y.val* + (if hy : A y.val then DrawTree.leaf (some (⟨y.val,hy⟩ : FiniteChain.Inside A)) else hittingTree step A k y.val).expectation (DrawTree.optionValue φ))= + ∑ y : FiniteChain.Inside A,C.P x.val y.val*φ y := by + apply Finset.sum_congr rfl; intro y _ + simp only [dite_eq_left y.property,DrawTree.expectation,DrawTree.optionValue] + have hout : (∑ y : FiniteChain.Outside A,C.P x.val y.val* + (if hy : A y.val then DrawTree.leaf (some (⟨y.val,hy⟩ : FiniteChain.Inside A)) else hittingTree step A k y.val).expectation (DrawTree.optionValue φ))= + ∑ z : FiniteChain.Outside A,C.P x.val z.val* + Q.partialGreen k (fun t => ∑ y : FiniteChain.Inside A,C.P t.val y.val*φ y) z := by + apply Finset.sum_congr rfl; intro y _ + rw [dite_eq_right y.property,hittingTree_outside step A C Q hQ hstep] + rw [hin,hout] + simp only [FiniteChain.cappedTrace,add_mul,Finset.sum_add_distrib] + congr 1 + simp only [Finset.sum_mul] + rw [Finset.sum_comm] + apply Finset.sum_congr rfl; intro z _ + simp only [mul_assoc] + rw [←Finset.mul_sum,KilledKernel.partialGreen_sum] + congr 1 + apply Finset.sum_congr rfl; intro y _ + unfold KilledKernel.partialGreen + simp_rw [show (fun t : FiniteChain.Outside A => C.P t.val y.val*φ y)=fun t => φ y*C.P t.val y.val by funext t; ring] + simp only [KilledKernel.iterate_mul,←Finset.mul_sum] + ring +end DrawHitting +namespace DrawTree +open scoped BigOperators Classical +variable {X Y : Type*} [sectionInstance117 : Fintype X] +omit sectionInstance117 in +lemma map_fits [Fintype X] (t : DrawTree X) (f : X → Y) (H M : ℕ) (ht : Fits H M t) : + Fits H M (t.map f) := by + have h := fits_bind H M 0 t (fun x => .leaf (f x)) ht (fun _ => trivial) + simpa only [map,Nat.add_zero] using h +def sample (step : X → DrawTree X) : (k : ℕ) → X → DrawTree (FiniteChain.Sample X k) + | 0,x => .leaf x + | k+1,x => (step x).bind (fun y => (sample step k y).map (fun v => (x,v))) +lemma sampleMass_delta (C : FiniteChain X) (ν : X → ℝ) (k : ℕ) (v : FiniteChain.Sample X k) : + (∑ x,ν x*C.sampleMass (fun y => if x=y then 1 else 0) v)=C.sampleMass ν v := by + cases k with + | zero => + dsimp only [FiniteChain.Sample] at v + change (∑ x : X,ν x*(if x=v then 1 else 0))=ν v + simp + | succ k => + change (∑ x,ν x*((if x=v.1 then 1 else 0)*C.sampleMass (C.P v.1) v.2))=_ + change (∑ x : X,ν x*((if x=v.1 then 1 else 0)*C.sampleMass (C.P v.1) v.2))=ν v.1*C.sampleMass (C.P v.1) v.2 + simp +lemma sample_expectation (step : X → DrawTree X) (C : FiniteChain X) + (hs : ∀ x φ,(step x).expectation φ=C.apply φ x) (k : ℕ) (x : X) + (F : FiniteChain.Sample X k → ℝ) : + (sample step k x).expectation F=∑ v : FiniteChain.Sample X k,C.sampleMass (fun y => if x=y then 1 else 0) v*F v := by + induction k generalizing x with + | zero => + dsimp only [FiniteChain.Sample,FiniteChain.sampleFintype] at F ⊢ + change F x=∑ v : X,(if x=v then (1:ℝ) else 0)*F v + simp + | succ k ih => + dsimp only [FiniteChain.Sample,FiniteChain.sampleFintype] at F ⊢ + change ((step x).bind (fun y => (sample step k y).map (fun v : FiniteChain.Sample X k => (x,v)))).expectation F=∑ v : X × FiniteChain.Sample X k,_ + rw [expectation_bind] + simp_rw [expectation_map,ih] + rw [hs,FiniteChain.apply,Fintype.sum_prod_type] + simp only [FiniteChain.sampleMass,ite_mul,one_mul,zero_mul] + simp only [Finset.sum_ite_irrel,Finset.sum_const_zero,Finset.sum_ite_eq,Finset.mem_univ,ite_true] + simp only [Finset.mul_sum] + rw [Finset.sum_comm] + apply Finset.sum_congr rfl; intro v _ + simp only [←mul_assoc] + rw [←Finset.sum_mul,sampleMass_delta] +lemma sample_start_expectation (start : DrawTree (Option X)) (step : X → DrawTree X) + (ν : X → ℝ) (C : FiniteChain X) + (hstart : ∀ φ,start.expectation (optionValue φ)=∑ x,ν x*φ x) + (hs : ∀ x φ,(step x).expectation φ=C.apply φ x) (k : ℕ) + (F : FiniteChain.Sample X k → ℝ) : + (start.optionBind (fun x => (sample step k x).map some)).expectation (optionValue F)= + ∑ v : FiniteChain.Sample X k,C.sampleMass ν v*F v := by + rw [expectation_optionBind,hstart] + simp_rw [expectation_map] + simp only [optionValue] + simp_rw [sample_expectation step C hs,Finset.mul_sum] + rw [Finset.sum_comm] + apply Finset.sum_congr rfl; intro v _ + simp only [←mul_assoc] + rw [←Finset.sum_mul] + congr 1 + exact sampleMass_delta C ν k v +lemma sample_fits (step : X → DrawTree X) (H M k : ℕ) + (hs : ∀ x,Fits H M (step x)) (x : X) : Fits H (M*k) (sample step k x) := by + induction k generalizing x with + | zero => trivial + | succ k ih => + unfold sample + have h := fits_bind H M (M*k) (step x) + (fun y => (sample step k y).map (fun v : FiniteChain.Sample X k => (x,v))) + (hs x) (by intro y; exact map_fits _ _ H (M*k) (ih y)) + simpa only [FiniteChain.Sample,sample,Nat.mul_succ,Nat.add_comm] using h + +def history (K : List X → DrawTree (Option X)) : ℕ → List X → DrawTree (Option (List X)) + | 0,h => pureSome h + | k+1,h => (K h).optionBind (fun x => history K k (h++[x])) +lemma history_expectation (K : List X → DrawTree (Option X)) (P : List X → X → ℝ) + (hK : Matches K P) (k : ℕ) (h : List X) (F : List X → ℝ) : + (history K k h).expectation (optionValue F)=FiniteExperiment.expect P k h F := by + induction k generalizing h with + | zero => rfl + | succ k ih => + rw [history,expectation_optionBind,hK] + simp_rw [ih] + rfl +omit sectionInstance117 in +lemma history_fits [Fintype X] (K : List X → DrawTree (Option X)) (H M k : ℕ) + (hK : ∀ h,Fits H M (K h)) (h : List X) : Fits H (M*k) (history K k h) := by + induction k generalizing h with + | zero => trivial + | succ k ih => + unfold history + have hh := optionBind_fits (K h) (fun x => history K k (h++[x])) H M (M*k) (hK h) (fun x => ih (h++[x])) + simpa only [FiniteChain.Sample,sample,Nat.mul_succ,Nat.add_comm] using hh +end DrawTree +section DrawActual +open scoped BigOperators Classical +variable (n : ℕ) (hn : 0 pairedSlots n +noncomputable def rationalStored (h : List (PhaseSample n N)) (j : ℕ) := + rationalHistory GS (observedSets n N) (h.take j) +lemma rationalStored_cast (h : List (PhaseSample n N)) (j : ℕ) (p r) : + (rationalStored n N h j p r:ℝ)=storedWeights n N h j p r := by + exact rationalHistory_cast GS (observedSets n N) (h.take j) p r +lemma rationalStored_pos (h : List (PhaseSample n N)) (hp : HistoryPositive n N h) + (j : ℕ) (p r) : 0 hittingTree (actualStepTree n hn M N h j) (plainPredicate GS) (cap+1) x.val +lemma actualTraceTree_matches (h : List (PhaseSample n N)) (hp : HistoryPositive n N h) (j cap : ℕ) : + DrawTree.Matches (actualTraceTree n hn M N h j cap) + (actualCappedTrace n hn M j (storedWeights n N h j) (historyPositive_all n N h hp j) cap).P := by + intro x φ + exact hittingTree_inside (actualStepTree n hn M N h j) (plainPredicate GS) + (metropolisChain GS (pairedSlots_fresh n) (pairedSlots_ne_nil n hn) (pairedSlots_cover n) + (storedWeights n N h j) (annealWeight M n j) (historyPositive_all n N h hp j) + (annealWeight_pos M n j hn)) + (metropolisKilled GS (pairedSlots_fresh n) (pairedSlots_ne_nil n hn) (pairedSlots_cover n) + (storedWeights n N h j) (annealWeight M n j) (historyPositive_all n N h hp j) + (annealWeight_pos M n j hn)) (by intros; rfl) + (actualStepTree_expectation n hn M N h hp j) cap x φ +noncomputable def actualRestartTree (h : List (PhaseSample n N)) (cap : ℕ) : ℕ → DrawTree (Option (PlainIndex GS)) + | 0 => + letI := plainIndex_nonempty GS (pairedSlots_fresh n) (pairedSlots_cover n) + (DrawTree.uniformChoice (PlainIndex GS)).map some + | j+1 => (actualRestartTree h cap j).optionBind + (DrawTree.iterate (actualTraceTree n hn M N h (j+1) cap) (20*n^4*(n*(L+1)+2))) +lemma actualRestartTree_expectation (h : List (PhaseSample n N)) (hp : HistoryPositive n N h) + (cap j : ℕ) (φ : PlainIndex GS → ℝ) : + (actualRestartTree n hn M N L h cap j).expectation (DrawTree.optionValue φ)= + ∑ x,restartLaw n hn M L cap (storedWeights n N h) (historyPositive_all n N h hp) j x*φ x := by + induction j generalizing φ with + | zero => + rw [actualRestartTree,DrawTree.expectation_map,DrawTree.uniformChoice_expectation] + simp only [DrawTree.optionValue,uniformAverage,restartLaw,uniformPlain,plainIndex_card,Nat.cast_pow,Nat.cast_ofNat] + rw [Finset.sum_div] + apply Finset.sum_congr rfl; intro x _; ring + | succ j ih => + rw [actualRestartTree,DrawTree.expectation_optionBind,ih] + have hi := DrawTree.iterate_matches _ _ (actualTraceTree_matches n hn M N h hp (j+1) cap) (20*n^4*(n*(L+1)+2)) + unfold DrawTree.Matches at hi + simp_rw [hi] + simp only [Finset.mul_sum] + simp only [restartLaw,FiniteKernel.push,Finset.sum_mul,mul_assoc] + rw [Finset.sum_comm] +noncomputable def actualStartTree (h : List (PhaseSample n N)) : DrawTree (Option (ChainIndex GS)) := + (actualRestartTree n hn M N L h (restartCap n L) h.length).map (Option.map Subtype.val) +lemma actualStartTree_expectation (h : List (PhaseSample n N)) (hp : HistoryPositive n N h) + (φ : ChainIndex GS → ℝ) : + (actualStartTree n hn M N L h).expectation (DrawTree.optionValue φ)=∑ x,phaseStart n hn M N L h hp x*φ x := by + rw [actualStartTree,DrawTree.expectation_map] + have hf : (fun a : Option (PlainIndex GS) => DrawTree.optionValue φ (Option.map Subtype.val a))= + DrawTree.optionValue (fun a => φ a.val) := by funext a; cases a <;> rfl + rw [hf,actualRestartTree_expectation n hn M N L h hp] + rw [←Fintype.sum_subtype_add_sum_subtype (plainPredicate GS)] + simp only [phaseStart,plainLift] + have hin : (∑ x : PlainIndex GS,(if hx : PlainState GS x.val.val then + restartLaw n hn M L (restartCap n L) (storedWeights n N h) (historyPositive_all n N h hp) h.length ⟨x.val,hx⟩ else 0)*φ x.val)= + ∑ x : PlainIndex GS,restartLaw n hn M L (restartCap n L) (storedWeights n N h) (historyPositive_all n N h hp) h.length x*φ x.val := by + apply Finset.sum_congr rfl; intro x _; rw [dite_eq_left x.property] + rw [hin] + have hout : (∑ x : FiniteChain.Outside (plainPredicate GS), + (if hx : PlainState GS x.val.val then + restartLaw n hn M L (restartCap n L) (storedWeights n N h) (historyPositive_all n N h hp) h.length ⟨x.val,hx⟩ else 0)*φ x.val)=0 := by + apply Finset.sum_eq_zero; intro x _; rw [dite_eq_right x.property,zero_mul] + rw [hout,add_zero] +noncomputable def actualPhaseTree (h : List (PhaseSample n N)) : DrawTree (Option (PhaseSample n N)) := + if HistoryPositive n N h then + (actualStartTree n hn M N L h).optionBind + (fun x => (DrawTree.sample (actualStepTree n hn M N h h.length) (N-1) x).map some) + else .leaf none +lemma actualPhaseTree_matches : DrawTree.Matches (actualPhaseTree n hn M N L) (phaseKernel n hn M N L) := by + intro h φ + unfold actualPhaseTree phaseKernel + split_ifs with hp + · exact DrawTree.sample_start_expectation _ _ _ _ + (actualStartTree_expectation n hn M N L h hp) + (actualStepTree_expectation n hn M N h hp h.length) (N-1) φ + · simp [DrawTree.expectation,DrawTree.optionValue] +end DrawActual +open scoped BigOperators Classical +variable (n : ℕ) (hn : 0 pairedMatroid M₁ M₂ +local notation "GS" => pairedSlots n +noncomputable def rationalEstimate (h : List (PhaseSample n N)) : ℚ := + (2:ℚ)^n * ∏ j ∈ Finset.range L, + rationalRatio GS (fun S => rationalRho n^(n-((K).eRk S).toNat)) + (historySample (observedSets n N) h j) +lemma rationalEstimate_cast (h : List (PhaseSample n N)) : + (rationalEstimate n M₁ M₂ N L h:ℝ)=historyEstimate n N L K h := by + simp only [rationalEstimate,Rat.cast_mul,Rat.cast_pow,Rat.cast_ofNat,Rat.cast_prod,rationalRatio_cast, + rationalRho_cast,historyEstimate] +noncomputable def rationalGuard (h : List (PhaseSample n N)) (x : PlainIndex GS) : ℚ := + if Witnessed n M₁ M₂ x then rationalEstimate n M₁ M₂ N L h else 0 +lemma rationalGuard_cast (h : List (PhaseSample n N)) (x : PlainIndex GS) : + (rationalGuard n M₁ M₂ N L h x:ℝ)=guardedEstimate n M₁ M₂ N L h x := by + unfold rationalGuard guardedEstimate + split_ifs <;> simp [rationalEstimate_cast] +include hn in +lemma rationalGuard_nonneg (h : List (PhaseSample n N)) (x : PlainIndex GS) : + 0≤rationalGuard n M₁ M₂ N L h x := by + have hh := guardedEstimate_nonneg n hn M₁ M₂ N L h x + rw [←rationalGuard_cast] at hh + exact_mod_cast hh +lemma rationalGuard_zero (hE₂ : M₂.E=Set.univ) (hr : M₁.eRank=M₂.eRank) + (hZ : commonBaseCount M₁ M₂=0) (h : List (PhaseSample n N)) (x : PlainIndex GS) : + rationalGuard n M₁ M₂ N L h x=0 := by + have hh := guardedEstimate_zero n M₁ M₂ N L hE₂ hr hZ h x + rw [←rationalGuard_cast] at hh + exact_mod_cast hh +noncomputable def rationalWitnessTree (h : List (PhaseSample n N)) : DrawTree (Option (PlainIndex GS)) := + if HistoryPositive n N h then actualRestartTree n hn K N L h (restartCap n L) h.length else .leaf none +lemma rationalWitnessTree_expectation (h : List (PhaseSample n N)) (φ : PlainIndex GS → ℝ) : + (rationalWitnessTree n hn M₁ M₂ N L h).expectation (DrawTree.optionValue φ)= + ∑ x,witnessKernel n hn M₁ M₂ N L h x*φ x := by + unfold rationalWitnessTree witnessKernel + split_ifs with hp + · exact actualRestartTree_expectation n hn K N L h hp (restartCap n L) h.length φ + · simp [DrawTree.expectation,DrawTree.optionValue] +noncomputable def rationalAlgorithmTree : DrawTree (Option ℚ) := + (DrawTree.history (actualPhaseTree n hn K N L) L []).optionBind (fun h => + (rationalWitnessTree n hn M₁ M₂ N L h).map (Option.map (rationalGuard n M₁ M₂ N L h))) +lemma rationalAlgorithmTree_expectation (F : ℚ → ℝ) : + (rationalAlgorithmTree n hn M₁ M₂ N L).expectation (DrawTree.optionValue F)= + FiniteExperiment.expect (phaseKernel n hn K N L) L [] + (fun h => ∑ x,witnessKernel n hn M₁ M₂ N L h x*F (rationalGuard n M₁ M₂ N L h x)) := by + rw [rationalAlgorithmTree,DrawTree.expectation_optionBind,DrawTree.history_expectation _ _ (actualPhaseTree_matches n hn K N L)] + congr 1; funext h + rw [DrawTree.expectation_map] + have hf : (fun a : Option (PlainIndex GS) => DrawTree.optionValue F + (Option.map (rationalGuard n M₁ M₂ N L h) a))= + DrawTree.optionValue (fun x => F (rationalGuard n M₁ M₂ N L h x)) := by + funext a; cases a <;> rfl + rw [hf,rationalWitnessTree_expectation] +lemma rationalAlgorithmTree_success_eq (ε : ℚ) : + (rationalAlgorithmTree n hn M₁ M₂ N L).expectation + (DrawTree.optionValue (fun z => if relativeAccuracy ε (commonBaseCount M₁ M₂) z then 1 else 0))= + actualRealSuccess n hn M₁ M₂ N L (ε:ℝ) := by + rw [rationalAlgorithmTree_expectation] + unfold actualRealSuccess + congr 1; funext h + apply Finset.sum_congr rfl; intro x _ + have he : relativeAccuracy ε (commonBaseCount M₁ M₂) (rationalGuard n M₁ M₂ N L h x) ↔ + (1-(ε:ℝ))*(commonBaseCount M₁ M₂:ℝ)≤guardedEstimate n M₁ M₂ N L h x ∧ + guardedEstimate n M₁ M₂ N L h x≤(1+(ε:ℝ))*(commonBaseCount M₁ M₂:ℝ) := by + rw [←rationalGuard_cast] + unfold relativeAccuracy + constructor <;> intro hh <;> exact_mod_cast hh + simp only [he,mul_ite,mul_one,mul_zero] +include hn in +theorem rational_algorithm_success (hE₁ : M₁.E=Set.univ) (hE₂ : M₂.E=Set.univ) + (hr : M₁.eRank=M₂.eRank) (ε : ℚ) (hε0 : 0<ε) (hε1 : ε<1) + (b : ℕ) (hb : (1/2:ℝ)^b ≤ (ε:ℝ)/10) (hZ : 0 if relativeAccuracy ε (commonBaseCount M₁ M₂) z then 1 else 0)) := by + rw [rationalAlgorithmTree_success_eq] + exact real_annealing_success n hn M₁ M₂ N hE₁ hE₂ hr (ε:ℝ) + (by exact_mod_cast hε0) (by exact_mod_cast hε1) b hb hZ hN + +end + +open scoped BigOperators Classical + +def RatBound (q : ℚ) (B : ℕ) : Prop := + ∃ a b : ℕ,a≤B ∧ b≤B ∧ 0 simpa using one 1 (by decide) + | succ k ih => simpa only [pow_succ] using ih.mul hq +lemma min_one (hq : RatBound q B) : RatBound (min 1 q) B := by + by_cases h : 1≤q + · rw [min_eq_left h]; exact one B hq.one_le + · rw [min_eq_right (le_of_not_ge h)]; exact hq +lemma den_le (hq : RatBound q B) : q.den≤B := by + obtain ⟨a,b,ha,hb,hpos,rfl⟩ := hq + have he : ((a:ℚ)/(b:ℚ))=Rat.divInt (a:ℤ) (b:ℤ) := by simp [Rat.divInt_eq_div] + rw [he] + have hd := Rat.den_dvd (a:ℤ) (b:ℤ) + exact (Nat.le_of_dvd hpos (Int.natCast_dvd_natCast.mp hd)).trans hb +lemma num_le (hq : RatBound q B) : q.num.natAbs≤B := by + obtain ⟨a,b,ha,hb,hpos,rfl⟩ := hq + have he : ((a:ℚ)/(b:ℚ))=Rat.divInt (a:ℤ) (b:ℤ) := by simp [Rat.divInt_eq_div] + rw [he,Rat.num_divInt] + have hs : (b:ℤ).sign=1 := Int.sign_eq_one_of_pos (by exact_mod_cast hpos) + rw [hs,one_mul] + rw [Int.natAbs_ediv,Int.natAbs_natCast,Int.natAbs_natCast] + exact (Nat.div_le_self _ _).trans ha +end RatBound + +section ActualSize +open scoped BigOperators Classical +lemma RatBound.nat_div (a b B : ℕ) (ha : a≤B) (hb : b≤B) (hB : 0 if P x then (1:ℚ) else 0)).sum=(l.countP (fun x => decide (P x)):ℚ) := by + induction l with + | nil => simp + | cons x l ih => by_cases hx : P x <;> simp [hx,ih,add_comm] +variable {Γ : Type*} [sectionInstance118 : Fintype Γ] [sectionInstance119 : DecidableEq Γ] +omit sectionInstance118 sectionInstance119 in +lemma rationalTypeRatio [Fintype Γ] [DecidableEq Γ] (gs : List (Γ × Γ)) (l : List (Set Γ)) (p r : Γ × Γ) : + rationalEmpirical (rationalPlain gs (fun _ => 1)) l / + rationalEmpirical (rationalDefect gs p r) l = + (l.countP (fun S => decide (PlainState gs S)):ℚ)/ + (l.countP (fun S => decide (DefectState gs p r S)):ℚ) := by + unfold rationalEmpirical rationalPlain rationalDefect + rw [indicator_list_sum,indicator_list_sum] + by_cases hz : l.length=0 + · have he : l=[] := List.length_eq_zero_iff.mp hz + simp [he] + · exact div_div_div_cancel_right₀ (by exact_mod_cast hz : (l.length:ℚ)≠0) _ _ +lemma rationalLearn_bound (gs : List (Γ × Γ)) (w : (Γ × Γ) → (Γ × Γ) → ℚ) + (l : List (Set Γ)) (B N : ℕ) (hN : 0 simpa [rationalHistory] using RatBound.nat 4 4 (by omega) (by omega) + | append_singleton h x ih => + have he : rationalHistory gs sample (h++[x])=rationalLearn gs (rationalHistory gs sample h) (sample x) := by + funext p r; simp [rationalHistory,List.foldl_append] + rw [he] + have hh := rationalLearn_bound gs (rationalHistory gs sample h) (sample x) (4*N^h.length) N hN (hs x) ih p r + simpa only [List.length_append,List.length_singleton,pow_succ,Nat.mul_assoc] using hh +omit sectionInstance119 in +lemma rationalMultiplier_bound [DecidableEq Γ] (gs : List (Γ × Γ)) (w : (Γ × Γ) → (Γ × Γ) → ℚ) + (B : ℕ) (hB : 0 (observedSets_length n N hN x).le) (h.take j) p r + apply hd.mono + apply Nat.mul_le_mul_left + apply Nat.pow_le_pow_right hN + rw [List.length_take] + exact (Nat.min_le_right _ _).trans hlen +lemma rationalWeight_bound (hn : 0 pairedSlots n +local notation "H" => drawWordBound n N L +include hN in +lemma actualStepTree_fits (h : List (PhaseSample n N)) (hlen : h.length≤L) (j : ℕ) (hj : j≤L) + (x : ChainIndex GS) : DrawTree.Fits H 3 (actualStepTree n hn M N h j x) := by + let : Nonempty (ExchangeChoice x.val) := Fintype.card_pos_iff.mp (by + rw [exchangeChoice_card GS (pairedSlots_fresh n) (pairedSlots_cover n),pairedSlots_length]; positivity) + unfold actualStepTree rationalMetropolis + apply DrawTree.fits_bind H 1 2 _ _ + · apply DrawTree.bernoulli_fits + norm_num + exact drawWordBound_ge_one n N L + · intro lazy + cases lazy with + | true => trivial + | false => + simp only [Bool.false_eq_true,ite_false] + apply DrawTree.fits_bind H 1 1 _ _ + · apply DrawTree.uniformChoice_fits + rw [exchangeChoice_card GS (pairedSlots_fresh n) (pairedSlots_cover n),pairedSlots_length] + exact drawWordBound_exchange n N L + · intro a + unfold rationalExchange + split_ifs + · apply DrawTree.map_fits + apply DrawTree.bernoulli_fits + apply Nat.clog_le_of_le_pow + exact (rationalAcceptance_bound n N L hN hn M h hlen j hj x _).den_le.trans + (acceptance_word_bound n N L) + · trivial +include hN in +lemma actualTraceTree_fits (h : List (PhaseSample n N)) (hlen : h.length≤L) (j cap : ℕ) (hj : j≤L) + (x : PlainIndex GS) : DrawTree.Fits H (3*(cap+1)) (actualTraceTree n hn M N h j cap x) := by + exact hittingTree_fits _ _ H 3 (cap+1) (actualStepTree_fits n hn M N L hN h hlen j hj) x.val +include hN in +lemma actualRestartTree_fits (h : List (PhaseSample n N)) (hlen : h.length≤L) (cap j : ℕ) (hj : j≤L) : + DrawTree.Fits H (1+3*j*(cap+1)*(20*n^4*(n*(L+1)+2))) (actualRestartTree n hn M N L h cap j) := by + let := plainIndex_nonempty GS (pairedSlots_fresh n) (pairedSlots_cover n) + induction j with + | zero => + rw [actualRestartTree] + simp only [Nat.mul_zero,Nat.zero_mul,Nat.add_zero] + apply DrawTree.map_fits + apply DrawTree.uniformChoice_fits + rw [plainIndex_card,Nat.clog_pow 2 n (by omega)] + exact drawWordBound_ge_n n N L + | succ j ih => + rw [actualRestartTree] + have hh := DrawTree.optionBind_fits (actualRestartTree n hn M N L h cap j) + (DrawTree.iterate (actualTraceTree n hn M N h (j+1) cap) (20*n^4*(n*(L+1)+2))) H + (1+3*j*(cap+1)*(20*n^4*(n*(L+1)+2))) (3*(cap+1)*(20*n^4*(n*(L+1)+2))) + (ih (by omega)) + (DrawTree.iterate_fits _ H (3*(cap+1)) _ (actualTraceTree_fits n hn M N L hN h hlen (j+1) cap hj)) + convert hh using 1 ; ring + +def phaseDrawBound (n N L : ℕ) : ℕ := 1+3*L*(restartCap n L+1)*(20*n^4*(n*(L+1)+2))+3*N +include hN in +lemma actualPhaseTree_fits (h : List (PhaseSample n N)) (hlen : h.length≤L) : + DrawTree.Fits H (phaseDrawBound n N L) (actualPhaseTree n hn M N L h) := by + unfold actualPhaseTree + split_ifs + · have hstart : DrawTree.Fits H (1+3*L*(restartCap n L+1)*(20*n^4*(n*(L+1)+2))) (actualStartTree n hn M N L h) := by + apply DrawTree.map_fits + apply DrawTree.fits_mono_steps H _ _ _ _ + (actualRestartTree_fits n hn M N L hN h hlen (restartCap n L) h.length hlen) + gcongr + apply DrawTree.optionBind_fits _ _ H _ (3*N) hstart + intro x + apply DrawTree.map_fits + apply DrawTree.fits_mono_steps H (3*(N-1)) (3*N) (by omega) + exact DrawTree.sample_fits _ H 3 (N-1) (actualStepTree_fits n hn M N L hN h hlen h.length hlen) x + · cases phaseDrawBound n N L <;> trivial +end ActualFits + +namespace DrawTree +variable {A B C : Type*} +lemma bind_assoc (t : DrawTree A) (f : A → DrawTree B) (g : B → DrawTree C) : + (t.bind f).bind g=t.bind (fun a => (f a).bind g) := by + induction t with + | leaf a => rfl + | draw v k ih => simp only [bind,ih] +lemma optionBind_assoc (t : DrawTree (Option A)) (f : A → DrawTree (Option B)) (g : B → DrawTree (Option C)) : + (t.optionBind f).optionBind g=t.optionBind (fun a => (f a).optionBind g) := by + simp only [optionBind,bind_assoc] + congr 1; funext a; cases a <;> rfl +lemma leaf_fits (H M : ℕ) (a : A) : Fits H M (.leaf a) := by cases M <;> trivial +end DrawTree +section AlgorithmFits +open scoped BigOperators Classical +variable (n : ℕ) (hn : 0 pairedMatroid M₁ M₂ +local notation "H" => drawWordBound n N L +local notation "B" => phaseDrawBound n N L +include hN in +lemma rationalWitnessTree_fits (h : List (PhaseSample n N)) (hlen : h.length≤L) : + DrawTree.Fits H B (rationalWitnessTree n hn M₁ M₂ N L h) := by + unfold rationalWitnessTree + split_ifs + · apply DrawTree.fits_mono_steps H _ B _ _ + (actualRestartTree_fits n hn K N L hN h hlen (restartCap n L) h.length hlen) + unfold phaseDrawBound + have hh : 3*h.length*(restartCap n L+1)*(20*n^4*(n*(L+1)+2))≤ + 3*L*(restartCap n L+1)*(20*n^4*(n*(L+1)+2)) := by gcongr + omega + · exact DrawTree.leaf_fits H B none +include hN in +lemma rational_history_finish_fits (h : List (PhaseSample n N)) (k : ℕ) (hlen : h.length+k≤L) : + DrawTree.Fits H (B*(k+1)) + ((DrawTree.history (actualPhaseTree n hn K N L) k h).optionBind (fun h => + (rationalWitnessTree n hn M₁ M₂ N L h).map (Option.map (rationalGuard n M₁ M₂ N L h)))) := by + induction k generalizing h with + | zero => + simp only [DrawTree.history,DrawTree.pureSome,DrawTree.optionBind,DrawTree.bind,Nat.zero_add,Nat.mul_one] + exact DrawTree.map_fits _ _ H B (rationalWitnessTree_fits n hn M₁ M₂ N L hN h (by omega)) + | succ k ih => + rw [DrawTree.history,DrawTree.optionBind_assoc] + have hh := DrawTree.optionBind_fits + (actualPhaseTree n hn K N L h) + (fun x => (DrawTree.history (actualPhaseTree n hn K N L) k (h++[x])).optionBind (fun h => + (rationalWitnessTree n hn M₁ M₂ N L h).map (Option.map (rationalGuard n M₁ M₂ N L h)))) + H B (B*(k+1)) (actualPhaseTree_fits n hn K N L hN h (by omega)) (by + intro x; apply ih; simp only [List.length_append,List.length_singleton]; omega) + convert hh using 1 ; ring +def algorithmDrawBound (n N L : ℕ) : ℕ := phaseDrawBound n N L*(L+1) +include hN in +lemma rationalAlgorithmTree_fits : DrawTree.Fits H (algorithmDrawBound n N L) (rationalAlgorithmTree n hn M₁ M₂ N L) := + rational_history_finish_fits n hn M₁ M₂ N L hN [] L (by simp) +end AlgorithmFits + +namespace DrawTree +variable {A B : Type*} +def All (p : A → Prop) : DrawTree A → Prop + | .leaf a => p a + | .draw _ k => ∀ i,All p (k i) +lemma all_bind (t : DrawTree A) (f : A → DrawTree B) (p : B → Prop) + (hf : ∀ a,All p (f a)) : All p (t.bind f) := by + induction t with + | leaf a => exact hf a + | draw v k ih => exact ih +lemma all_map (t : DrawTree A) (f : A → B) (p : B → Prop) (hf : ∀ a,p (f a)) : All p (t.map f) := + all_bind t _ p hf +lemma run_all (H D M : ℕ) (t : DrawTree A) (p : A → Prop) (ht : All p t) (bits) (a : A) + (ha : run H D M t bits=some a) : p a := by + induction M generalizing t with + | zero => + cases t with + | leaf x => simp only [run,Option.some.injEq] at ha; exact ha ▸ ht + | draw v k => simp [run] at ha + | succ M ih => + cases t with + | leaf x => simp only [run,Option.some.injEq] at ha; exact ha ▸ ht + | draw v k => + simp only [run] at ha + split_ifs at ha with h + · split at ha + · simp at ha + · exact ih _ (ht _) _ ha +end DrawTree +section AlgorithmAll +open scoped Classical +variable (n : ℕ) (hn : 0 ∀ z,a=some z → 0≤z ∧ + (M₂.E=Set.univ → M₁.eRank=M₂.eRank → commonBaseCount M₁ M₂=0 → z=0)) + (rationalAlgorithmTree n hn M₁ M₂ N L) := by + unfold rationalAlgorithmTree DrawTree.optionBind + apply DrawTree.all_bind + intro a + cases a with + | none => intro z; simp + | some h => + apply DrawTree.all_map + intro a + cases a with + | none => intro z; simp + | some x => + intro z hz + simp only [Option.map_some,Option.some.injEq] at hz + subst z + exact ⟨rationalGuard_nonneg n hn M₁ M₂ N L h x, + fun hE hr hZ => rationalGuard_zero n M₁ M₂ N L hE hr hZ h x⟩ +end AlgorithmAll +open scoped BigOperators Classical +lemma uniformAverage_one_sub {X : Type*} [Fintype X] [Nonempty X] (f : X → ℝ) : + uniformAverage (fun x => 1-f x)=1-uniformAverage f := by + unfold uniformAverage + simp only [Finset.sum_sub_distrib,Finset.sum_const,Finset.card_univ,nsmul_eq_mul,mul_one] + rw [sub_div,div_self (by exact_mod_cast ne_of_gt (Fintype.card_pos))] +lemma rejectionBudget (M : ℕ) : (M:ℝ)*(1/2:ℝ)^(M+6)≤1/64 := by + have hM : (M:ℝ)≤(2:ℝ)^M := by exact_mod_cast (Nat.lt_two_pow_self (n:=M)).le + have h := mul_le_mul_of_nonneg_right hM (by positivity : 0≤(1/2:ℝ)^(M+6)) + apply h.trans + rw [pow_add,←mul_assoc,←mul_pow] + norm_num +abbrev FairBank (n N L : ℕ) := + Fin (algorithmDrawBound n N L) → Fin (algorithmDrawBound n N L+6) → BitWord (drawWordBound n N L) +noncomputable def fairOutput (n : ℕ) (hn : 0 simp + | some a => + cases a with + | none => simp + | some z => + simp only [Option.join_some,Option.getD_some] + exact (DrawTree.run_all _ _ _ _ _ (rationalAlgorithmTree_all n hn M₁ M₂ N L) bits (some z) he z rfl).1 +lemma fairOutput_zero (n : ℕ) (hn : 0 simp + | some a => + cases a with + | none => simp + | some z => + simp only [Option.join_some,Option.getD_some] + exact (DrawTree.run_all _ _ _ _ _ (rationalAlgorithmTree_all n hn M₁ M₂ N L) bits (some z) he z rfl).2 hE₂ hr hZ + +theorem fair_single_success (n : ℕ) (hn : 0 + if relativeAccuracy ε (commonBaseCount M₁ M₂) (fairOutput n hn M₁ M₂ N (annealLength n b) bits) then (1:ℝ) else 0) := by + by_cases hZ : commonBaseCount M₁ M₂=0 + · simp only [fairOutput_zero n hn M₁ M₂ N _ hE₂ hr hZ,hZ,relativeAccuracy,Nat.cast_zero,mul_zero,le_refl,and_self,ite_true,uniformAverage_const] + norm_num + have hN0 : 0 if relativeAccuracy ε (commonBaseCount M₁ M₂) z then 1 else 0 + have hs := rational_algorithm_success n hn M₁ M₂ N hE₁ hE₂ hr ε hε0 hε1 b hb (Nat.pos_of_ne_zero hZ) hN + have hrun := DrawTree.run_lower (drawWordBound n N L) (algorithmDrawBound n N L+6) (algorithmDrawBound n N L) + (rationalAlgorithmTree n hn M₁ M₂ N L) (rationalAlgorithmTree_fits n hn M₁ M₂ N L hN0) + (DrawTree.optionValue φ) (by intro a; cases a with + | none => norm_num [DrawTree.optionValue] + | some z => dsimp [DrawTree.optionValue,φ]; split_ifs <;> norm_num) + (by intro a; cases a with + | none => norm_num [DrawTree.optionValue] + | some z => dsimp [DrawTree.optionValue,φ]; split_ifs <;> norm_num) + have hm : uniformAverage (fun bits : FairBank n N L => DrawTree.optionValue (DrawTree.optionValue φ) + (DrawTree.run (drawWordBound n N L) (algorithmDrawBound n N L+6) (algorithmDrawBound n N L) + (rationalAlgorithmTree n hn M₁ M₂ N L) bits)) ≤ + uniformAverage (fun bits : FairBank n N L => φ (fairOutput n hn M₁ M₂ N L bits)) := by + apply uniformAverage_mono + intro bits + unfold fairOutput + generalize DrawTree.run _ _ _ _ bits=a + cases a with + | none => dsimp [DrawTree.optionValue,φ]; split_ifs <;> norm_num + | some a => cases a <;> dsimp [DrawTree.optionValue,φ] <;> split_ifs <;> norm_num + have hbudget := rejectionBudget (algorithmDrawBound n N L) + change 11/16≤uniformAverage (fun bits : FairBank n N L => φ (fairOutput n hn M₁ M₂ N L bits)) + change 3/4≤(rationalAlgorithmTree n hn M₁ M₂ N L).expectation (DrawTree.optionValue φ) at hs + linarith +open scoped BigOperators Classical + +def rationalMedian (l : List ℚ) : ℚ := (l.mergeSort (· ≤ ·)).getD (l.length/2) 0 + +def outsideInterval (a b x : ℚ) : Bool := decide (¬(a≤x ∧ x≤b)) +lemma median_bad_count (l : List ℚ) (hl : 0 hbad ⟨ha,hh⟩) + have htail : (s.drop (l.length/2)).countP (outsideInterval a b)=(s.drop (l.length/2)).length := by + apply List.countP_eq_length.mpr + intro x hx + obtain ⟨i,hi,rfl⟩ := List.getElem_of_mem hx + rw [List.getElem_drop] + apply decide_eq_true + intro hh + have hm := hs.getElem_le_getElem_of_le (i := l.length/2) (j := l.length/2+i) (hi := hk) (hj := by simp only [List.length_drop] at hi; omega) (by omega) + exact (not_le_of_gt (hb.trans_le hm)) hh.2 + have hdecomp := List.countP_append (p := outsideInterval a b) + (l₁ := s.take (l.length/2)) (l₂ := s.drop (l.length/2)) + rw [List.take_append_drop,htail,hc,List.length_drop,hlen] at hdecomp + omega + · have hfront : (s.take (l.length/2+1)).countP (outsideInterval a b)=(s.take (l.length/2+1)).length := by + apply List.countP_eq_length.mpr + intro x hx + obtain ⟨i,hi,rfl⟩ := List.getElem_of_mem hx + rw [List.getElem_take] + apply decide_eq_true + intro hh + have hi' : i≤l.length/2 := by simp only [List.length_take] at hi; omega + have hm := hs.getElem_le_getElem_of_le (i := i) (j := l.length/2) (hi := by simp only [List.length_take] at hi; omega) (hj := hk) hi' + exact ha (hh.1.trans hm) + have hdecomp := List.countP_append (p := outsideInterval a b) + (l₁ := s.take (l.length/2+1)) (l₂ := s.drop (l.length/2+1)) + rw [List.take_append_drop,hfront,hc,List.length_take,hlen] at hdecomp + omega + +lemma uniformAverage_mul_const {X : Type*} [Fintype X] (f : X → ℝ) (c : ℝ) : + uniformAverage (fun x => f x*c)=uniformAverage f*c := by + unfold uniformAverage + rw [← Finset.sum_mul] + ring + +lemma countP_ofFn_cons {X : Type*} (p : X → Bool) (x : X) {R : ℕ} (xs : Fin R → X) : + (List.ofFn (Fin.cons x xs)).countP p=(if p x then 1 else 0)+(List.ofFn xs).countP p := by + rw [List.ofFn_succ] + simp only [Fin.cons_zero,Fin.cons_succ,List.countP_cons] + change (List.ofFn xs).countP p+(if p x then 1 else 0)=(if p x then 1 else 0)+(List.ofFn xs).countP p + omega + +lemma independent_bad_moment {X : Type*} [Fintype X] [Nonempty X] + (bad : X → Bool) (R : ℕ) : + uniformAverage (fun xs : Fin R → X => (4:ℝ)^((List.ofFn xs).countP bad))= + (1+3*uniformAverage (fun x => if bad x then (1:ℝ) else 0))^R := by + induction R with + | zero => simp [List.ofFn_zero,uniformAverage_const] + | succ R ih => + rw [uniformAverage_fin_succ] + simp_rw [countP_ofFn_cons,pow_add,uniformAverage_mul_left,ih] + rw [uniformAverage_mul_const] + have he : (fun x : X => (4:ℝ)^(if bad x then 1 else 0:ℕ))= + fun x => 1+3*(if bad x then (1:ℝ) else 0) := by + funext x; cases bad x <;> norm_num + rw [he,uniformAverage_add,uniformAverage_const,uniformAverage_mul_left,pow_succ] + ring + +lemma countP_map {X Y : Type*} (l : List X) (f : X → Y) (p : Y → Bool) : + (l.map f).countP p=l.countP (fun x => p (f x)) := by + induction l with + | nil => rfl + | cons x xs ih => simp only [List.map_cons,List.countP_cons,ih] + +theorem median_failure_bound {X : Type*} [Fintype X] [Nonempty X] + (output : X → ℚ) (a b : ℚ) (R : ℕ) (hR : 0 if outsideInterval a b (output x) then (1:ℝ) else 0)≤5/16) : + uniformAverage (fun xs : Fin R → X => + if outsideInterval a b (rationalMedian (List.ofFn (fun i => output (xs i)))) + then (1:ℝ) else 0) ≤ (31/32:ℝ)^R := by + let bad : X → Bool := fun x => outsideInterval a b (output x) + have hx : ∀ xs : Fin R → X, + (if outsideInterval a b (rationalMedian (List.ofFn (fun i => output (xs i)))) then (1:ℝ) else 0) + ≤ (4:ℝ)^((List.ofFn xs).countP bad)/(2:ℝ)^R := by + intro xs + by_cases he : outsideInterval a b (rationalMedian (List.ofFn (fun i => output (xs i))))=true + · rw [ite_eq_left he] + have hc := median_bad_count (List.ofFn (fun i => output (xs i))) (by simpa using hR) a b (by + simpa only [outsideInterval,decide_eq_true_eq] using he) + have hmap : List.ofFn (fun i => output (xs i))=(List.ofFn xs).map output := by rw [List.map_ofFn]; rfl + rw [hmap,countP_map,List.length_map,List.length_ofFn] at hc + have hp : (2:ℝ)^R≤4^((List.ofFn xs).countP bad) := by + calc + (2:ℝ)^R ≤ 2^(2*((List.ofFn xs).countP bad)) := pow_le_pow_right₀ (by norm_num) hc + _ = _ := by rw [pow_mul]; norm_num + exact (le_div_iff₀ (by positivity)).mpr (by simpa using hp) + · rw [ite_eq_right he]; positivity + have hm := uniformAverage_mono _ _ hx + have hrw : uniformAverage (fun xs : Fin R → X => (4:ℝ)^((List.ofFn xs).countP bad)/(2:ℝ)^R)= + (1+3*uniformAverage (fun x => if bad x then (1:ℝ) else 0))^R/(2:ℝ)^R := by + simp_rw [div_eq_mul_inv] + rw [uniformAverage_mul_const,independent_bad_moment] + rw [hrw] at hm + apply hm.trans + rw [←div_pow] + apply pow_le_pow_left₀ (by + apply div_nonneg _ (by norm_num) + have hz := uniformAverage_nonneg (fun x => if bad x then (1:ℝ) else 0) (by intro x; split_ifs <;> norm_num) + linarith) + dsimp [bad] at * + linarith + +def repetitionCount (δ : ℚ) : ℕ := 64*(δ.den.bits.length+1) +lemma repetitionCount_pos (δ : ℚ) : 0 if outsideInterval a b (output x) then (1:ℝ) else 0)≤5/16) : + 1-(δ:ℝ) ≤ uniformAverage (fun xs : Fin (repetitionCount δ) → X => + if a≤rationalMedian (List.ofFn (fun i => output (xs i))) ∧ + rationalMedian (List.ofFn (fun i => output (xs i)))≤b then (1:ℝ) else 0) := by + have h := (median_failure_bound output a b (repetitionCount δ) (repetitionCount_pos δ) hbad).trans + (confidence_decay δ hδ) + have he : (fun xs : Fin (repetitionCount δ) → X => + if outsideInterval a b (rationalMedian (List.ofFn (fun i => output (xs i)))) then (1:ℝ) else 0)= + fun xs => 1-(if a≤rationalMedian (List.ofFn (fun i => output (xs i))) ∧ + rationalMedian (List.ofFn (fun i => output (xs i)))≤b then (1:ℝ) else 0) := by + funext xs + simp only [outsideInterval,decide_eq_true_eq] + split_ifs <;> simp_all + rw [he] at h + have hei : uniformAverage (fun xs : Fin (repetitionCount δ) → X => + 1-(if a≤rationalMedian (List.ofFn (fun i => output (xs i))) ∧ + rationalMedian (List.ofFn (fun i => output (xs i)))≤b then (1:ℝ) else 0))= + 1-uniformAverage (fun xs : Fin (repetitionCount δ) → X => + if a≤rationalMedian (List.ofFn (fun i => output (xs i))) ∧ + rationalMedian (List.ofFn (fun i => output (xs i)))≤b then (1:ℝ) else 0) := by + unfold uniformAverage + simp only [Finset.sum_sub_distrib,Finset.sum_const,Finset.card_univ,nsmul_eq_mul,mul_one] + rw [sub_div,div_self (by exact_mod_cast ne_of_gt (Fintype.card_pos))] + rw [hei] at h + linarith + +open scoped BigOperators Classical +lemma rationalMedian_all (p : ℚ → Prop) (l : List ℚ) (h0 : p 0) (hl : ∀ z∈l,p z) : p (rationalMedian l) := by + unfold rationalMedian + by_cases h : l.length/2<(l.mergeSort (· ≤ ·)).length + · rw [List.getD_eq_getElem _ _ h] + apply hl + exact (List.mem_mergeSort).mp (List.getElem_mem h) + · have hl0 : l.length=0 := by simp only [List.length_mergeSort] at h; omega + have he : l=[] := List.length_eq_zero_iff.mp hl0 + simpa [he] using h0 + +def accuracyExponent (ε : ℚ) : ℕ := ε.den.bits.length+5 +lemma accuracyExponent_spec (ε : ℚ) (hε : 0<ε) : (1/2:ℝ)^(accuracyExponent ε)≤(ε:ℝ)/10 := by + have h := rational_binary_accuracy ε hε + have he : (0:ℝ)<ε := by exact_mod_cast hε + unfold accuracyExponent + rw [show ε.den.bits.length+5=(ε.den.bits.length+1)+4 by omega,pow_add] + norm_num + nlinarith + +def sampleCount (n L : ℕ) (ε : ℚ) : ℕ := 10^14*(L+1)^3*n^14*⌈ε⁻¹⌉₊^2+1 +lemma sampleCount_pos (n L : ℕ) (ε : ℚ) : 0 fairOutput n hn M₁ M₂ N L (bits i))) +lemma amplifiedOutput_nonneg (n : ℕ) (hn : 0 0≤z) _ (by norm_num) + intro z hz + obtain ⟨i,rfl⟩ := List.mem_ofFn.mp hz + exact fairOutput_nonneg n hn M₁ M₂ N L (bits i) +lemma amplifiedOutput_zero (n : ℕ) (hn : 0 z=0) _ rfl + intro z hz + obtain ⟨i,rfl⟩ := List.mem_ofFn.mp hz + exact fairOutput_zero n hn M₁ M₂ N L hE₂ hr hZ (bits i) + +theorem amplified_success (n : ℕ) (hn : 0 + if relativeAccuracy ε (commonBaseCount M₁ M₂) (amplifiedOutput n hn M₁ M₂ N (annealLength n b) δ bits) + then (1:ℝ) else 0) := by + have hbad : uniformAverage (fun bits : FairBank n N (annealLength n b) => + if outsideInterval ((1-ε)*(commonBaseCount M₁ M₂:ℚ)) ((1+ε)*(commonBaseCount M₁ M₂:ℚ)) + (fairOutput n hn M₁ M₂ N (annealLength n b) bits) then (1:ℝ) else 0)≤5/16 := by + have hs := fair_single_success n hn M₁ M₂ N hE₁ hE₂ hr ε hε0 hε1 b hb hN + have he : (fun bits : FairBank n N (annealLength n b) => + if outsideInterval ((1-ε)*(commonBaseCount M₁ M₂:ℚ)) ((1+ε)*(commonBaseCount M₁ M₂:ℚ)) + (fairOutput n hn M₁ M₂ N (annealLength n b) bits) then (1:ℝ) else 0)= + fun bits => 1-(if relativeAccuracy ε (commonBaseCount M₁ M₂) + (fairOutput n hn M₁ M₂ N (annealLength n b) bits) then (1:ℝ) else 0) := by + funext bits + by_cases hh : relativeAccuracy ε (commonBaseCount M₁ M₂) + (fairOutput n hn M₁ M₂ N (annealLength n b) bits) + · simp only [hh,ite_true,sub_self] + simp only [relativeAccuracy] at hh + simp [outsideInterval,hh] + · simp only [hh,ite_false,sub_zero] + simp only [relativeAccuracy] at hh + simp [outsideInterval,hh] + rw [he,uniformAverage_one_sub] + linarith + have hm := median_confidence (fairOutput n hn M₁ M₂ N (annealLength n b)) + ((1-ε)*(commonBaseCount M₁ M₂:ℚ)) ((1+ε)*(commonBaseCount M₁ M₂:ℚ)) δ hδ hbad + convert hm using 1 + congr 1 + funext bits + unfold relativeAccuracy amplifiedOutput + split_ifs <;> rfl + +abbrev FPRASBank (n : ℕ) (ε δ : ℚ) := Fin (repetitionCount δ) → + FairBank n (sampleCount n (annealLength n (accuracyExponent ε)) ε) (annealLength n (accuracyExponent ε)) +noncomputable def boundedFPRASOutput (n : ℕ) (hn : 0 + if relativeAccuracy ε (commonBaseCount M₁ M₂) (boundedFPRASOutput n hn M₁ M₂ ε δ bits) then (1:ℝ) else 0) := by + constructor + · intro bits + exact ⟨amplifiedOutput_nonneg n hn M₁ M₂ _ _ δ bits, + fun hZ => amplifiedOutput_zero n hn M₁ M₂ _ _ δ hE₂ hr hZ bits⟩ + · exact amplified_success n hn M₁ M₂ _ hE₁ hE₂ hr ε δ hε0 hε1 hδ + (accuracyExponent ε) (accuracyExponent_spec ε hε0) + (sampleCount_spec n _ ε hε0) + +section GreedyOracle +variable {α : Type*} [sectionInstance120 : DecidableEq α] + +def greedyOracle (O : Finset α → Bool) : List α → Finset α + | [] => ∅ + | a::l => let I := greedyOracle O l + if O (insert a I) then insert a I else I +lemma greedyOracle_correct (M : Matroid α) (O : Finset α → Bool) + (hO : ∀ I,O I = true ↔ M.Indep (I : Set α)) (l : List α) + (hE : ∀ a ∈ l,a ∈ M.E) : M.IsBasis (greedyOracle O l : Set α) (l.toFinset : Set α) := by + induction l with + | nil => simp [greedyOracle] + | cons a l ih => + have hi := ih (fun x hx => hE x (by simp [hx])) + have ha := hE a (by simp) + simp only [greedyOracle] + split_ifs with h + · have hind := (hO _).mp h + apply hind.isBasis_of_subset_of_subset_closure + · simpa only [List.toFinset_cons,Finset.coe_insert] using Set.insert_subset_insert hi.subset + · simp only [List.toFinset_cons,Finset.coe_insert] + apply Set.insert_subset + · simpa only [Finset.coe_insert] using M.subset_closure _ hind.subset_ground (Finset.mem_insert_self a _) + · exact hi.subset_closure.trans (M.closure_mono (by simp)) + · apply hi.indep.isBasis_of_subset_of_subset_closure + · exact hi.subset.trans (by simp) + · simp only [List.toFinset_cons,Finset.coe_insert] + apply Set.insert_subset + · apply hi.indep.mem_closure_iff'.mpr + refine ⟨ha,?_⟩ + intro hind + exfalso + exact h ((hO _).mpr (by simpa using hind)) + · exact hi.subset_closure + +def greedyQueryCount : List α → ℕ + | [] => 0 + | _::l => greedyQueryCount l+1 +omit sectionInstance120 in +lemma greedyQueryCount_eq [DecidableEq α] (l : List α) : greedyQueryCount l = l.length := by + induction l <;> simp_all [greedyQueryCount] + +lemma greedyOracle_rank (M : Matroid α) (O : Finset α → Bool) + (hO : ∀ I,O I = true ↔ M.Indep (I : Set α)) (l : List α) + (hE : ∀ a ∈ l,a ∈ M.E) : + (greedyOracle O l).card = (M.eRk (l.toFinset : Set α)).toNat := by + have h := (greedyOracle_correct M O hO l hE).encard_eq_eRk + simpa using congrArg ENat.toNat h +end GreedyOracle + +open scoped Classical + +def queryFinset {n : ℕ} (O : IndependenceOracle n) (which : Bool) (I : Finset (Fin n)) : Bool := + O which (fun i => decide (i ∈ I)) +def rankOracle {n : ℕ} (O : IndependenceOracle n) (which : Bool) (S : Finset (Fin n)) : ℕ := + (greedyOracle (queryFinset O which) ((List.finRange n).filter (fun i => decide (i ∈ S)))).card +lemma queryFinset_exact {n : ℕ} (M₁ M₂ : Matroid (Fin n)) (O : IndependenceOracle n) + (hO : ExactOracles M₁ M₂ O) (which : Bool) (I : Finset (Fin n)) : + queryFinset O which I = true ↔ (if which then M₂ else M₁).Indep (I : Set (Fin n)) := by + have h := hO which (fun i => decide (i ∈ I)) + have he : {i : Fin n | decide (i ∈ I) = true} = (I : Set (Fin n)) := by ext i; simp + rw [he] at h + exact h +lemma rankOracle_correct {n : ℕ} (M₁ M₂ : Matroid (Fin n)) (O : IndependenceOracle n) + (hO : ExactOracles M₁ M₂ O) (hE₁ : M₁.E=Set.univ) (hE₂ : M₂.E=Set.univ) + (which : Bool) (S : Finset (Fin n)) : + rankOracle O which S = ((if which then M₂ else M₁).eRk (S : Set (Fin n))).toNat := by + have hE : (if which then M₂ else M₁).E = Set.univ := by cases which <;> simpa + have h := greedyOracle_rank (if which then M₂ else M₁) (queryFinset O which) + (queryFinset_exact M₁ M₂ O hO which) ((List.finRange n).filter (fun i => decide (i ∈ S))) + (by intro i _; simp [hE]) + have hs : (((List.finRange n).filter (fun i => decide (i ∈ S))).toFinset : Set (Fin n)) = S := by + ext i; simp + rw [hs] at h + exact h +lemma rankOracle_query_bound {n : ℕ} (S : Finset (Fin n)) : + greedyQueryCount ((List.finRange n).filter (fun i => decide (i ∈ S))) ≤ n := by + rw [greedyQueryCount_eq] + exact (List.length_filter_le _ _).trans_eq (List.length_finRange (n := n)) + +section SumRank +open Set +variable {α β : Type*} [sectionInstance121 : Fintype α] [sectionInstance122 : Fintype β] +omit sectionInstance121 sectionInstance122 in +lemma sum_eRk [Fintype α] [Fintype β] (M : Matroid α) (N : Matroid β) (S : Set (α ⊕ β)) : + (M.sum N).eRk S = M.eRk (Sum.inl ⁻¹' S) + N.eRk (Sum.inr ⁻¹' S) := by + obtain ⟨I,hI⟩ := M.exists_isBasis' (Sum.inl ⁻¹' S) + obtain ⟨J,hJ⟩ := N.exists_isBasis' (Sum.inr ⁻¹' S) + have hb : (M.sum N).IsBasis' (Sum.inl '' I ∪ Sum.inr '' J) S := by + rw [Matroid.isBasis'_iff_isBasis_inter_ground,Matroid.sum_isBasis_iff] + constructor + · simpa [Set.preimage_image_eq _ Sum.inl_injective,Set.preimage_image_eq _ Sum.inr_injective] + using hI.isBasis_inter_ground + · simpa [Set.preimage_image_eq _ Sum.inl_injective,Set.preimage_image_eq _ Sum.inr_injective] + using hJ.isBasis_inter_ground + rw [hb.eRk_eq_encard,Set.encard_union_eq (Set.disjoint_image_inl_image_inr), + Set.InjOn.encard_image Sum.inl_injective.injOn, + Set.InjOn.encard_image Sum.inr_injective.injOn,hI.encard_eq_eRk,hJ.encard_eq_eRk] + +lemma dual_rank_nat (M : Matroid α) (hE : M.E=Set.univ) (S : Set α) : + (M✶.eRk S).toNat+M.eRank.toNat = S.ncard+(M.eRk Sᶜ).toNat := by + have h := M.eRk_dual_add_eRank S (by simp [hE]) + rw [hE,← Set.compl_eq_univ_sdiff] at h + have hh := congrArg ENat.toNat h + rw [ENat.toNat_add (M✶.isRkFinite_set S).eRk_lt_top.ne + ((M.eRank_ne_top_iff).mpr inferInstance), + ENat.toNat_add (M.isRkFinite_set Sᶜ).eRk_lt_top.ne + (Set.encard_ne_top_iff.mpr (Set.toFinite S))] at hh + simpa only [Set.ncard,add_comm] using hh +end SumRank + +open scoped Classical + +def pairedDeficiencyOracle {n : ℕ} (r : ℕ) (O : IndependenceOracle n) + (Sx Sy : Finset (Fin n)) : ℕ := + n+r-(rankOracle O false Sx+Sy.card+rankOracle O true Syᶜ) +lemma paired_rank_nat {n r : ℕ} (M₁ M₂ : Matroid (Fin n)) + (hE₂ : M₂.E=Set.univ) (hr₂ : M₂.eRank=(r:ℕ∞)) (S : Set (Fin n ⊕ Fin n)) : + ((pairedMatroid M₁ M₂).eRk S).toNat+r = + (M₁.eRk (Sum.inl ⁻¹' S)).toNat+(Sum.inr ⁻¹' S).ncard+ + (M₂.eRk (Sum.inr ⁻¹' S)ᶜ).toNat := by + rw [pairedMatroid,sum_eRk,ENat.toNat_add + (M₁.isRkFinite_set _).eRk_lt_top.ne (M₂✶.isRkFinite_set _).eRk_lt_top.ne] + have h := dual_rank_nat M₂ hE₂ (Sum.inr ⁻¹' S) + rw [hr₂,ENat.toNat_natCast] at h + omega +lemma pairedDeficiencyOracle_correct {n r : ℕ} (M₁ M₂ : Matroid (Fin n)) + (O : IndependenceOracle n) (hO : ExactOracles M₁ M₂ O) + (hE₁ : M₁.E=Set.univ) (hE₂ : M₂.E=Set.univ) + (_ : M₁.eRank=(r:ℕ∞)) (hr₂ : M₂.eRank=(r:ℕ∞)) (S : Set (Fin n ⊕ Fin n)) : + pairedDeficiencyOracle r O (Sum.inl ⁻¹' S).toFinset (Sum.inr ⁻¹' S).toFinset = + n-((pairedMatroid M₁ M₂).eRk S).toNat := by + have h := paired_rank_nat M₁ M₂ hE₂ hr₂ S + unfold pairedDeficiencyOracle + rw [rankOracle_correct M₁ M₂ O hO hE₁ hE₂,rankOracle_correct M₁ M₂ O hO hE₁ hE₂] + simp only [Bool.false_eq_true,ite_false,ite_true,Set.coe_toFinset,Finset.coe_compl, + Set.toFinset_card,Set.fintypeCard_eq_ncard] + omega + +def verifyCommonBase {n : ℕ} (r : ℕ) (O : IndependenceOracle n) (A : Finset (Fin n)) : Bool := + decide (A.card=r) && queryFinset O false A && queryFinset O true A +lemma verifyCommonBase_correct {n r : ℕ} (M₁ M₂ : Matroid (Fin n)) + (O : IndependenceOracle n) (hO : ExactOracles M₁ M₂ O) + (hr₁ : M₁.eRank=(r:ℕ∞)) (hr₂ : M₂.eRank=(r:ℕ∞)) (A : Finset (Fin n)) : + verifyCommonBase r O A = true ↔ M₁.IsBase (A:Set (Fin n)) ∧ M₂.IsBase (A:Set (Fin n)) := by + simp only [verifyCommonBase,Bool.and_eq_true,decide_eq_true_eq, + queryFinset_exact M₁ M₂ O hO,Bool.false_eq_true,ite_false,ite_true] + constructor + · rintro ⟨⟨hc,h₁⟩,h₂⟩ + have he : (A:Set (Fin n)).encard=(r:ℕ∞) := by simp [hc] + constructor + · apply h₁.isBase_of_eRk_ge A.finite_toSet + rw [h₁.eRk_eq_encard,he,hr₁] + · apply h₂.isBase_of_eRk_ge A.finite_toSet + rw [h₂.eRk_eq_encard,he,hr₂] + · rintro ⟨h₁,h₂⟩ + refine ⟨⟨?_,h₁.indep⟩,h₂.indep⟩ + have h := h₁.encard_eq_eRank + rw [hr₁] at h + simpa using h +lemma verified_count_positive {n r : ℕ} (M₁ M₂ : Matroid (Fin n)) + (O : IndependenceOracle n) (hO : ExactOracles M₁ M₂ O) + (hr₁ : M₁.eRank=(r:ℕ∞)) (hr₂ : M₂.eRank=(r:ℕ∞)) (A : Finset (Fin n)) + (hA : verifyCommonBase r O A=true) : 0 pairedSlots n +noncomputable def oracleDeficiency (S : Set (Fin n ⊕ Fin n)) : ℕ := + pairedDeficiencyOracle r O (Sum.inl ⁻¹' S).toFinset (Sum.inr ⁻¹' S).toFinset +noncomputable def oracleAnneal (j : ℕ) (S : Set (Fin n ⊕ Fin n)) : ℚ := + (rationalRho n^j)^(oracleDeficiency n r O S) +def rationalHistoryPositive (h : List (PhaseSample n N)) : Prop := + ∀ j ≤ h.length,∀ p q,0 intro hh j hj p q + · have hs := hh j hj p q + rw [←rationalStored_cast] + exact_mod_cast hs + · have hs := hh j hj p q + rw [←rationalStored_cast] at hs + exact_mod_cast hs +noncomputable def oracleStepTree (h : List (PhaseSample n N)) (j : ℕ) : ChainIndex GS → DrawTree (ChainIndex GS) := + rationalMetropolis GS (pairedSlots_fresh n) (pairedSlots_ne_nil n hn) (pairedSlots_cover n) + (rationalStored n N h j) (oracleAnneal n r O j) +noncomputable def oracleTraceTree (h : List (PhaseSample n N)) (j cap : ℕ) : + PlainIndex GS → DrawTree (Option (PlainIndex GS)) := + fun x => hittingTree (oracleStepTree n hn r O N h j) (plainPredicate GS) (cap+1) x.val +noncomputable def oracleRestartTree (h : List (PhaseSample n N)) (cap : ℕ) : ℕ → DrawTree (Option (PlainIndex GS)) + | 0 => + letI := plainIndex_nonempty GS (pairedSlots_fresh n) (pairedSlots_cover n) + (DrawTree.uniformChoice (PlainIndex GS)).map some + | j+1 => (oracleRestartTree h cap j).optionBind + (DrawTree.iterate (oracleTraceTree n hn r O N h (j+1) cap) (20*n^4*(n*(L+1)+2))) +noncomputable def oracleStartTree (h : List (PhaseSample n N)) : DrawTree (Option (ChainIndex GS)) := + (oracleRestartTree n hn r O N L h (restartCap n L) h.length).map (Option.map Subtype.val) +noncomputable def oraclePhaseTree (h : List (PhaseSample n N)) : DrawTree (Option (PhaseSample n N)) := + if rationalHistoryPositive n N h then + (oracleStartTree n hn r O N L h).optionBind + (fun x => (DrawTree.sample (oracleStepTree n hn r O N h h.length) (N-1) x).map some) + else .leaf none +noncomputable def oracleEstimate (h : List (PhaseSample n N)) : ℚ := + (2:ℚ)^n * ∏ j ∈ Finset.range L, + rationalRatio GS (fun S => rationalRho n^(oracleDeficiency n r O S)) + (historySample (observedSets n N) h j) +noncomputable def oracleGuard (h : List (PhaseSample n N)) (x : PlainIndex GS) : ℚ := + if oracleDeficiency n r O x.val.val=0 then oracleEstimate n r O N L h else 0 +noncomputable def oracleWitnessTree (h : List (PhaseSample n N)) : DrawTree (Option (PlainIndex GS)) := + if rationalHistoryPositive n N h then oracleRestartTree n hn r O N L h (restartCap n L) h.length else .leaf none + +noncomputable def oracleAlgorithmTree : DrawTree (Option ℚ) := + (DrawTree.history (oraclePhaseTree n hn r O N L) L []).optionBind (fun h => + (oracleWitnessTree n hn r O N L h).map (Option.map (oracleGuard n r O N L h))) +variable (M₁ M₂ : Matroid (Fin n)) (hO : ExactOracles M₁ M₂ O) +variable (hE₁ : M₁.E=Set.univ) (hE₂ : M₂.E=Set.univ) +variable (hr₁ : M₁.eRank=(r:ℕ∞)) (hr₂ : M₂.eRank=(r:ℕ∞)) +include hO hE₁ hE₂ hr₁ hr₂ +lemma oracleDeficiency_eq (S : Set (Fin n ⊕ Fin n)) : + oracleDeficiency n r O S=n-((pairedMatroid M₁ M₂).eRk S).toNat := + pairedDeficiencyOracle_correct M₁ M₂ O hO hE₁ hE₂ hr₁ hr₂ S +lemma oracleAnneal_eq (j : ℕ) : oracleAnneal n r O j = rationalAnneal (pairedMatroid M₁ M₂) n j := by + funext S + simp only [oracleAnneal,rationalAnneal,oracleDeficiency_eq n r O M₁ M₂ hO hE₁ hE₂ hr₁ hr₂] +lemma oracleStepTree_eq (h : List (PhaseSample n N)) (j : ℕ) : + oracleStepTree n hn r O N h j=actualStepTree n hn (pairedMatroid M₁ M₂) N h j := by + unfold oracleStepTree actualStepTree + rw [oracleAnneal_eq n r O M₁ M₂ hO hE₁ hE₂ hr₁ hr₂] +lemma oracleTraceTree_eq (h : List (PhaseSample n N)) (j cap : ℕ) : + oracleTraceTree n hn r O N h j cap=actualTraceTree n hn (pairedMatroid M₁ M₂) N h j cap := by + unfold oracleTraceTree actualTraceTree + rw [oracleStepTree_eq n hn r O N M₁ M₂ hO hE₁ hE₂ hr₁ hr₂] +lemma oracleRestartTree_eq (h : List (PhaseSample n N)) (cap j : ℕ) : + oracleRestartTree n hn r O N L h cap j = actualRestartTree n hn (pairedMatroid M₁ M₂) N L h cap j := by + induction j with + | zero => rfl + | succ j ih => + simp only [oracleRestartTree,actualRestartTree,ih, + oracleTraceTree_eq n hn r O N M₁ M₂ hO hE₁ hE₂ hr₁ hr₂] +lemma oracleStartTree_eq (h : List (PhaseSample n N)) : + oracleStartTree n hn r O N L h=actualStartTree n hn (pairedMatroid M₁ M₂) N L h := by + unfold oracleStartTree actualStartTree + rw [oracleRestartTree_eq n hn r O N L M₁ M₂ hO hE₁ hE₂ hr₁ hr₂] +lemma oraclePhaseTree_eq : oraclePhaseTree n hn r O N L=actualPhaseTree n hn (pairedMatroid M₁ M₂) N L := by + funext h + simp only [oraclePhaseTree,actualPhaseTree,rationalHistoryPositive_iff, + oracleStartTree_eq n hn r O N L M₁ M₂ hO hE₁ hE₂ hr₁ hr₂, + oracleStepTree_eq n hn r O N M₁ M₂ hO hE₁ hE₂ hr₁ hr₂] +lemma oracleEstimate_eq (h : List (PhaseSample n N)) : + oracleEstimate n r O N L h=rationalEstimate n M₁ M₂ N L h := by + simp only [oracleEstimate,rationalEstimate, + oracleDeficiency_eq n r O M₁ M₂ hO hE₁ hE₂ hr₁ hr₂] +lemma oracleGuard_eq (h : List (PhaseSample n N)) : + oracleGuard n r O N L h=rationalGuard n M₁ M₂ N L h := by + funext x + simp only [oracleGuard,rationalGuard,Witnessed, + oracleDeficiency_eq n r O M₁ M₂ hO hE₁ hE₂ hr₁ hr₂, + oracleEstimate_eq n r O N L M₁ M₂ hO hE₁ hE₂ hr₁ hr₂] + split_ifs <;> simp_all +lemma oracleWitnessTree_eq (h : List (PhaseSample n N)) : + oracleWitnessTree n hn r O N L h=rationalWitnessTree n hn M₁ M₂ N L h := by + simp only [oracleWitnessTree,rationalWitnessTree,rationalHistoryPositive_iff, + oracleRestartTree_eq n hn r O N L M₁ M₂ hO hE₁ hE₂ hr₁ hr₂] +theorem oracleAlgorithmTree_eq : oracleAlgorithmTree n hn r O N L=rationalAlgorithmTree n hn M₁ M₂ N L := by + simp only [oracleAlgorithmTree,rationalAlgorithmTree, + oraclePhaseTree_eq n hn r O N L M₁ M₂ hO hE₁ hE₂ hr₁ hr₂, + oracleWitnessTree_eq n hn r O N L M₁ M₂ hO hE₁ hE₂ hr₁ hr₂, + oracleGuard_eq n r O N L M₁ M₂ hO hE₁ hE₂ hr₁ hr₂] + +end + +section +open scoped BigOperators Classical +lemma RatBound.add {q r : ℚ} {B D : ℕ} (hq : RatBound q B) (hr : RatBound r D) : + RatBound (q+r) (2*B*D) := by + obtain ⟨a,b,ha,hb,hb0,rfl⟩ := hq + obtain ⟨c,d,hc,hd,hd0,rfl⟩ := hr + refine ⟨a*d+c*b,b*d,?_,?_,Nat.mul_pos hb0 hd0,?_⟩ + · nlinarith [Nat.mul_le_mul ha hd,Nat.mul_le_mul hc hb] + · nlinarith [Nat.mul_le_mul hb hd] + · push_cast + have hbq : (b:ℚ)≠0 := by exact_mod_cast Nat.ne_of_gt hb0 + have hdq : (d:ℚ)≠0 := by exact_mod_cast Nat.ne_of_gt hd0 + field_simp +lemma RatBound.bits {q : ℚ} {H : ℕ} (hq : RatBound q (2^H)) : + q.num.natAbs.bits.length ≤ H+1 ∧ q.den.bits.length ≤ H+1 := by + constructor + · rw [Nat.size_eq_bits_len] + exact (Nat.size_le_size hq.num_le).trans_eq (Nat.size_pow (n := H)) + · rw [Nat.size_eq_bits_len] + exact (Nat.size_le_size hq.den_le).trans_eq (Nat.size_pow (n := H)) +lemma RatBound.binary_add {q r : ℚ} {H J : ℕ} (hq : RatBound q (2^H)) (hr : RatBound r (2^J)) : + RatBound (q+r) (2^(H+J+1)) := by + convert hq.add hr using 1 + simp only [pow_add,pow_one] + ring +lemma RatBound.binary_mul {q r : ℚ} {H J : ℕ} (hq : RatBound q (2^H)) (hr : RatBound r (2^J)) : + RatBound (q*r) (2^(H+J)) := by simpa only [pow_add] using hq.mul hr +lemma RatBound.binary_div {q r : ℚ} {H J : ℕ} (hq : RatBound q (2^H)) (hr : RatBound r (2^J)) : + RatBound (q/r) (2^(H+J)) := by simpa only [pow_add] using hq.div hr +lemma RatBound.binary_list_sum {X : Type*} (f : X → ℚ) (l : List X) (H : ℕ) + (h : ∀ x∈l,RatBound (f x) (2^H)) : + RatBound ((l.map f).sum) (2^((H+1)*l.length)) := by + induction l with + | nil => simpa using RatBound.zero 1 (by decide) + | cons x l ih => + have hx := h x (by simp) + have ht := ih (fun y hy => h y (by simp [hy])) + simpa only [List.map_cons,List.sum_cons,List.length_cons,Nat.mul_add,Nat.mul_one, + show H + (H+1)*l.length+1=(H+1)*l.length+(H+1) by omega] using hx.binary_add ht +lemma RatBound.binary_prod {X : Type*} (s : Finset X) (f : X → ℚ) (H : ℕ) + (h : ∀ x∈s,RatBound (f x) (2^H)) : RatBound (∏ x∈s,f x) (2^(H*s.card)) := by + induction s using Finset.induction_on with + | empty => simpa using RatBound.one 1 (by decide) + | @insert x s hx ih => + have hh := (h x (by simp)).binary_mul (ih (fun y hy => h y (by simp [hy]))) + simpa only [Finset.prod_insert hx,Finset.card_insert_of_notMem hx,Nat.mul_add,Nat.mul_one, + add_comm H (H*s.card)] using hh +lemma rationalEmpirical_binary_bound {Γ : Type*} (f : Set Γ → ℚ) (l : List (Set Γ)) (N H : ℕ) + (hlen : l.length≤N) (hf : ∀ S∈l,RatBound (f S) (2^H)) : + RatBound (rationalEmpirical f l) (2^((H+2)*N)) := by + have hs := RatBound.binary_list_sum f l H hf + have hnat : RatBound (l.length:ℚ) (2^N) := RatBound.nat _ _ + (hlen.trans (Nat.le_of_lt (Nat.lt_two_pow_self))) (by positivity) + apply (hs.binary_div hnat).mono + apply Nat.pow_le_pow_right (by decide : 0<2) + nlinarith +lemma rho_observable_binary (n : ℕ) (hn : 0 1) S) (2^0) := by + intro S hS; unfold rationalPlain; split_ifs + · exact RatBound.one 1 (by decide) + · exact RatBound.zero 1 (by decide) + have hh := (rationalEmpirical_binary_bound _ l N H hlen hf').binary_div + (rationalEmpirical_binary_bound _ l N 0 hlen hi) + unfold rationalRatio + apply hh.mono + apply Nat.pow_le_pow_right (by decide : 0<2) + nlinarith +variable (n : ℕ) (hn : 0 simp + | some x => simpa only [Option.map_some,Option.getD_some] using (observedSets_length n N hN x).le + +def outputWordBound (n N L : ℕ) : ℕ := n+(2*n*n+5)*N*L +include hn hN in +lemma rationalEstimate_binary_bound (h : List (PhaseSample n N)) : + RatBound (rationalEstimate n M₁ M₂ N L h) (2^(outputWordBound n N L)) := by + have hp : RatBound ((2:ℚ)^n) (2^n) := by exact_mod_cast (RatBound.nat (2^n) (2^n) le_rfl (by positivity)) + have hh := RatBound.binary_prod (Finset.range L) + (fun j => rationalRatio (pairedSlots n) + (fun S => rationalRho n^(n-((pairedMatroid M₁ M₂).eRk S).toNat)) + (historySample (observedSets n N) h j)) ((2*n*n+5)*N) (by + intro j hj + exact rationalRatio_binary_bound _ _ _ N (2*n*n) (historySample_length_le n N hN h j) + (fun S => rho_observable_binary n hn _ (Nat.sub_le n _))) + simpa only [rationalEstimate,Finset.card_range,outputWordBound] using hp.binary_mul hh +include hn hN in +lemma rationalGuard_binary_bound (h : List (PhaseSample n N)) (x : PlainIndex (pairedSlots n)) : + RatBound (rationalGuard n M₁ M₂ N L h x) (2^(outputWordBound n N L)) := by + unfold rationalGuard + split_ifs + · exact rationalEstimate_binary_bound n hn M₁ M₂ N L hN h + · exact RatBound.zero _ (by positivity) + +end + +def bitResourceParameter (n : ℕ) (ε δ : ℚ) : ℕ := + 1+n+ε.den.bits.length+δ.den.bits.length+⌈ε⁻¹⌉₊ +def fairBitCount (n : ℕ) (ε δ : ℚ) : ℕ := + let L := annealLength n (accuracyExponent ε) + let N := sampleCount n L ε + repetitionCount δ * drawWordBound n N L * (algorithmDrawBound n N L+6) * algorithmDrawBound n N L +lemma polynomial_recipe_bounds (n e f E T : ℕ) (hT : 0 oracleFairOutput n hn r O N L (bits i))) +noncomputable def oracleBoundedOutput (n r : ℕ) (O : IndependenceOracle n) + (ε δ : ℚ) (bits : FPRASBank n ε δ) : ℚ := + if hn : 0 + if relativeAccuracy ε (commonBaseCount M₁ M₂) (oracleBoundedOutput n r O ε δ bits) then (1:ℝ) else 0) := by + by_cases hn : 0 linarith + simpa only [ho,commonBaseCount_empty,relativeAccuracy,Nat.cast_one,mul_one,ite_eq_left hac, + uniformAverage_const] using (sub_le_self (1:ℝ) (by exact_mod_cast hδ.le : (0:ℝ)≤δ)) + +open scoped BigOperators Classical + +noncomputable def wordPlainEquiv (n : ℕ) : BitWord n ≃ PlainIndex (pairedSlots n) where + toFun b := ⟨⟨transversal {i | b i=true},Or.inl (transversal_plain n _)⟩,transversal_plain n _⟩ + invFun S := fun i => decide (Sum.inl i∈S.val.val) + left_inv b := by + funext i + change decide (Sum.inl i∈transversal {i | b i=true})=b i + change decide (i∈Sum.inl ⁻¹' transversal {i | b i=true})=b i + rw [preimage_inl_transversal] + cases h : b i <;> simp [h] + right_inv S := by + apply Subtype.ext + apply Subtype.ext + change transversal {i | decide (Sum.inl i∈S.val.val)=true}=S.val.val + have he : {i | decide (Sum.inl i∈S.val.val)=true}=Sum.inl ⁻¹' S.val.val := by + ext i + simp + rw [he] + exact (plain_eq_transversal n S.val.val S.property).symm + +noncomputable def sortedMemberEquiv {Γ : Type*} [Fintype Γ] [LinearOrder Γ] (S : Set Γ) : + Fin (Fintype.card S) ≃ S := by + let c : ↥S.toFinset ≃ S := + { toFun := fun a => ⟨a.val,Set.mem_toFinset.mp a.property⟩ + invFun := fun a => ⟨a.val,Set.mem_toFinset.mpr a.property⟩ + left_inv := by intro a; rfl + right_inv := by intro a; rfl } + let e := (S.toFinset.orderIsoOfFin rfl).toEquiv.trans c + have he : Fintype.card S=S.toFinset.card := by + simpa only [Fintype.card_fin] using (Fintype.card_congr e).symm + exact (finCongr he).trans e +noncomputable def canonicalPlainEnumeration (n : ℕ) : + Fin (Fintype.card (PlainIndex (pairedSlots n))) ≃ PlainIndex (pairedSlots n) := + (finCongr (plainIndex_card n)).trans ((wordEquiv n).symm.trans (wordPlainEquiv n)) +noncomputable def canonicalExchangeEnumeration (n : ℕ) (S : Set (Fin n ⊕ Fin n)) : + Fin (Fintype.card (ExchangeChoice S)) ≃ ExchangeChoice S := by + letI : LinearOrder (Fin n ⊕ Fin n) := LinearOrder.lift' (finSumFinEquiv : Fin n ⊕ Fin n ≃ Fin (n+n)) (Equiv.injective _) + let e := finProdFinEquiv.symm.trans ((sortedMemberEquiv S).prodCongr (sortedMemberEquiv Sᶜ)) + have he : Fintype.card (ExchangeChoice S)=_ := (Fintype.card_congr e).symm + exact (finCongr (by simpa only [Fintype.card_fin] using he)).trans e + +section +namespace DrawTree +open scoped BigOperators Classical +variable {A B : Type*} + +inductive Reindexed : DrawTree A → DrawTree A → Prop + | leaf (a : A) : Reindexed (.leaf a) (.leaf a) + | draw (v : ℕ) (k l : Fin (v+1) → DrawTree A) (e : Fin (v+1) ≃ Fin (v+1)) + (h : ∀ i,Reindexed (k i) (l (e i))) : Reindexed (.draw v k) (.draw v l) +lemma Reindexed.refl (t : DrawTree A) : Reindexed t t := by + induction t with + | leaf a => exact .leaf a + | draw v k ih => exact .draw v k k (Equiv.refl _) ih +lemma Reindexed.symm {t u : DrawTree A} (h : Reindexed t u) : Reindexed u t := by + induction h with + | leaf a => exact .leaf a + | draw v k l e h ih => + apply Reindexed.draw v l k e.symm + intro i + simpa using ih (e.symm i) +lemma Reindexed.bind {t u : DrawTree A} {k l : A → DrawTree B} + (ht : Reindexed t u) (hk : ∀ a,Reindexed (k a) (l a)) : + Reindexed (t.bind k) (u.bind l) := by + induction ht with + | leaf a => exact hk a + | draw v a b e h ih => exact .draw v _ _ e ih +lemma Reindexed.map {t u : DrawTree A} (h : Reindexed t u) (f : A → B) : + Reindexed (t.map f) (u.map f) := h.bind (fun a => .leaf (f a)) +lemma Reindexed.expectation {t u : DrawTree A} (h : Reindexed t u) (φ : A → ℝ) : + t.expectation φ=u.expectation φ := by + induction h with + | leaf a => rfl + | draw v k l e h ih => + change uniformAverage (fun i => (k i).expectation φ)=uniformAverage (fun i => (l i).expectation φ) + simp_rw [ih] + exact uniformAverage_equiv e (fun i => (l i).expectation φ) +noncomputable def uniformVia (A : Type*) [Fintype A] [Nonempty A] + (e : Fin (Fintype.card A) ≃ A) : DrawTree A := + let h : Fintype.card A-1+1=Fintype.card A := by have hh := Fintype.card_pos (α := A); omega + .draw (Fintype.card A-1) (fun i => .leaf (e (Fin.cast h i))) +lemma uniformVia_reindexed (A : Type*) [Fintype A] [Nonempty A] + (e : Fin (Fintype.card A) ≃ A) : Reindexed (uniformVia A e) (uniformChoice A) := by + let h : Fintype.card A-1+1=Fintype.card A := by have hh := Fintype.card_pos (α := A); omega + let c := finCongr h + let p := c.trans (e.trans ((Fintype.equivFin A).trans c.symm)) + apply Reindexed.draw _ _ _ p + intro i + have he : (Fintype.equivFin A).symm (Fin.cast h (p i))=e (Fin.cast h i) := by simp [p,c] + simpa only [he] using Reindexed.leaf (e (Fin.cast h i)) +lemma Reindexed.fits {t u : DrawTree A} (h : Reindexed t u) (H M : ℕ) + (ht : Fits H M t) : Fits H M u := by + induction h generalizing M with + | leaf a => trivial + | draw v k l e h ih => + cases M with + | zero => exact False.elim ht + | succ M => + refine ⟨ht.1,fun i => ?_⟩ + simpa using ih (e.symm i) M (ht.2 (e.symm i)) +lemma Reindexed.all {t u : DrawTree A} (h : Reindexed t u) (P : A → Prop) + (ht : All P t) : All P u := by + induction h with + | leaf a => exact ht + | draw v k l e h ih => + intro i + simpa using ih (e.symm i) (ht (e.symm i)) +lemma Reindexed.run_expectation {t u : DrawTree A} (h : Reindexed t u) (H D M : ℕ) + (ht : Fits H M t) (φ : A → ℝ) : + uniformAverage (fun bits => optionValue φ (run H D M t bits))= + uniformAverage (fun bits => optionValue φ (run H D M u bits)) := by + induction h generalizing M with + | leaf a => rfl + | draw v k l e h ih => + cases M with + | zero => exact False.elim ht + | succ M => + rw [run_draw_average H D M v k ht.1 φ,run_draw_average H D M v l ht.1 φ] + congr 1 + have he : ∀ i,uniformAverage (fun bits => optionValue φ (run H D M (k i) bits))= + uniformAverage (fun bits => optionValue φ (run H D M (l (e i)) bits)) := + fun i => ih i M (ht.2 i) + simp_rw [he] + exact uniformAverage_equiv e (fun i => uniformAverage (fun bits => optionValue φ (run H D M (l i) bits))) +lemma Reindexed.run_observable {t u : DrawTree A} (h : Reindexed t u) (H D M : ℕ) + (ht : Fits H M t) (φ : Option A → ℝ) : + uniformAverage (fun bits => φ (run H D M t bits))= + uniformAverage (fun bits => φ (run H D M u bits)) := by + have hf : ∀ x : Option A,φ x=optionValue (fun a => φ (some a)-φ none) x+φ none := by + intro x; cases x <;> simp [optionValue] + have he (v : DrawTree A) : + (fun bits => φ (run H D M v bits))= + (fun bits => optionValue (fun a => φ (some a)-φ none) (run H D M v bits)+φ none) := + funext (fun bits => hf _) + rw [he t,he u,uniformAverage_add,uniformAverage_add,h.run_expectation H D M ht] +lemma Reindexed.optionBind {t u : DrawTree (Option A)} {k l : A → DrawTree (Option B)} + (ht : Reindexed t u) (hk : ∀ a,Reindexed (k a) (l a)) : + Reindexed (t.optionBind k) (u.optionBind l) := by + apply ht.bind + intro a; cases a with + | none => exact .leaf none + | some a => exact hk a +lemma Reindexed.iterate {t u : A → DrawTree (Option A)} (h : ∀ a,Reindexed (t a) (u a)) + (k : ℕ) (a : A) : Reindexed (iterate t k a) (iterate u k a) := by + induction k with + | zero => exact .leaf (some a) + | succ k ih => exact ih.optionBind h +lemma Reindexed.sample [Fintype A] {t u : A → DrawTree A} (h : ∀ a,Reindexed (t a) (u a)) + (k : ℕ) (a : A) : Reindexed (sample t k a) (sample u k a) := by + induction k generalizing a with + | zero => exact .leaf a + | succ k ih => exact (h a).bind (fun x => (ih x).map (fun v => (a,v))) +lemma Reindexed.history {K L : List A → DrawTree (Option A)} + (h : ∀ a,Reindexed (K a) (L a)) (k : ℕ) (a : List A) : + Reindexed (history K k a) (history L k a) := by + induction k generalizing a with + | zero => exact .leaf (some a) + | succ k ih => exact (h a).optionBind (fun x => ih (a++[x])) +end DrawTree +lemma hittingTree_reindexed {X : Type*} [Fintype X] {t u : X → DrawTree X} + (h : ∀ x,DrawTree.Reindexed (t x) (u x)) (A : X → Prop) (k : ℕ) (x : X) : + DrawTree.Reindexed (hittingTree t A k x) (hittingTree u A k x) := by + classical + induction k generalizing x with + | zero => exact .leaf none + | succ k ih => + apply (h x).bind + intro y + by_cases hy : A y + · simp only [dite_eq_left hy]; exact .leaf _ + · simp only [dite_eq_right hy]; exact ih y + +open scoped BigOperators Classical +variable (n : ℕ) (hn : 0 pairedSlots n +noncomputable def canonicalMetropolis (w : ((Fin n ⊕ Fin n) × (Fin n ⊕ Fin n)) → + ((Fin n ⊕ Fin n) × (Fin n ⊕ Fin n)) → ℚ) (f : Set (Fin n ⊕ Fin n) → ℚ) + (S : ChainIndex GS) : DrawTree (ChainIndex GS) := + letI : Nonempty (ExchangeChoice S.val) := Fintype.card_pos_iff.mp (by + rw [exchangeChoice_card GS (pairedSlots_fresh n) (pairedSlots_cover n),pairedSlots_length]; positivity) + (DrawTree.bernoulli (1/2)).bind (fun lazy => if lazy then .leaf S else + (DrawTree.uniformVia (ExchangeChoice S.val) (canonicalExchangeEnumeration n S.val)).bind + (rationalExchange GS w f S)) +lemma canonicalMetropolis_reindexed (w : ((Fin n ⊕ Fin n) × (Fin n ⊕ Fin n)) → + ((Fin n ⊕ Fin n) × (Fin n ⊕ Fin n)) → ℚ) (f : Set (Fin n ⊕ Fin n) → ℚ) + (S : ChainIndex GS) : DrawTree.Reindexed (canonicalMetropolis n hn w f S) + (rationalMetropolis GS (pairedSlots_fresh n) (pairedSlots_ne_nil n hn) (pairedSlots_cover n) w f S) := by + let : Nonempty (ExchangeChoice S.val) := Fintype.card_pos_iff.mp (by + rw [exchangeChoice_card GS (pairedSlots_fresh n) (pairedSlots_cover n),pairedSlots_length]; positivity) + apply (DrawTree.Reindexed.refl (DrawTree.bernoulli (1/2))).bind + intro lazy + cases lazy with + | true => exact .leaf S + | false => + apply (DrawTree.uniformVia_reindexed _ (canonicalExchangeEnumeration n S.val)).bind + intro a; exact .refl _ +noncomputable def canonicalStepTree (h : List (PhaseSample n N)) (j : ℕ) : ChainIndex GS → DrawTree (ChainIndex GS) := + canonicalMetropolis n hn (rationalStored n N h j) (oracleAnneal n r O j) +noncomputable def canonicalTraceTree (h : List (PhaseSample n N)) (j cap : ℕ) : + PlainIndex GS → DrawTree (Option (PlainIndex GS)) := + fun x => hittingTree (canonicalStepTree n hn r O N h j) (plainPredicate GS) (cap+1) x.val +noncomputable def canonicalRestartTree (h : List (PhaseSample n N)) (cap : ℕ) : ℕ → DrawTree (Option (PlainIndex GS)) + | 0 => + letI := plainIndex_nonempty GS (pairedSlots_fresh n) (pairedSlots_cover n) + (DrawTree.uniformVia (PlainIndex GS) (canonicalPlainEnumeration n)).map some + | j+1 => (canonicalRestartTree h cap j).optionBind + (DrawTree.iterate (canonicalTraceTree n hn r O N h (j+1) cap) (20*n^4*(n*(L+1)+2))) +noncomputable def canonicalStartTree (h : List (PhaseSample n N)) : DrawTree (Option (ChainIndex GS)) := + (canonicalRestartTree n hn r O N L h (restartCap n L) h.length).map (Option.map Subtype.val) +noncomputable def canonicalPhaseTree (h : List (PhaseSample n N)) : DrawTree (Option (PhaseSample n N)) := + if rationalHistoryPositive n N h then + (canonicalStartTree n hn r O N L h).optionBind + (fun x => (DrawTree.sample (canonicalStepTree n hn r O N h h.length) (N-1) x).map some) + else .leaf none +noncomputable def canonicalWitnessTree (h : List (PhaseSample n N)) : DrawTree (Option (PlainIndex GS)) := + if rationalHistoryPositive n N h then canonicalRestartTree n hn r O N L h (restartCap n L) h.length else .leaf none +noncomputable def canonicalAlgorithmTree : DrawTree (Option ℚ) := + (DrawTree.history (canonicalPhaseTree n hn r O N L) L []).optionBind (fun h => + (canonicalWitnessTree n hn r O N L h).map (Option.map (oracleGuard n r O N L h))) +lemma canonicalStepTree_reindexed (h : List (PhaseSample n N)) (j : ℕ) (S : ChainIndex GS) : + DrawTree.Reindexed (canonicalStepTree n hn r O N h j S) (oracleStepTree n hn r O N h j S) := + canonicalMetropolis_reindexed n hn _ _ S +lemma canonicalTraceTree_reindexed (h : List (PhaseSample n N)) (j cap : ℕ) (S : PlainIndex GS) : + DrawTree.Reindexed (canonicalTraceTree n hn r O N h j cap S) (oracleTraceTree n hn r O N h j cap S) := + hittingTree_reindexed (canonicalStepTree_reindexed n hn r O N h j) _ _ _ +lemma canonicalRestartTree_reindexed (h : List (PhaseSample n N)) (cap j : ℕ) : + DrawTree.Reindexed (canonicalRestartTree n hn r O N L h cap j) (oracleRestartTree n hn r O N L h cap j) := by + let := plainIndex_nonempty GS (pairedSlots_fresh n) (pairedSlots_cover n) + induction j with + | zero => exact (DrawTree.uniformVia_reindexed _ (canonicalPlainEnumeration n)).map some + | succ j ih => exact ih.optionBind (fun S => DrawTree.Reindexed.iterate (canonicalTraceTree_reindexed n hn r O N h (j+1) cap) _ S) +lemma canonicalStartTree_reindexed (h : List (PhaseSample n N)) : + DrawTree.Reindexed (canonicalStartTree n hn r O N L h) (oracleStartTree n hn r O N L h) := + (canonicalRestartTree_reindexed n hn r O N L h _ _).map _ +lemma canonicalPhaseTree_reindexed (h : List (PhaseSample n N)) : + DrawTree.Reindexed (canonicalPhaseTree n hn r O N L h) (oraclePhaseTree n hn r O N L h) := by + unfold canonicalPhaseTree oraclePhaseTree + split_ifs + · exact (canonicalStartTree_reindexed n hn r O N L h).optionBind (fun S => + (DrawTree.Reindexed.sample (canonicalStepTree_reindexed n hn r O N h h.length) _ S).map some) + · exact .leaf none +lemma canonicalWitnessTree_reindexed (h : List (PhaseSample n N)) : + DrawTree.Reindexed (canonicalWitnessTree n hn r O N L h) (oracleWitnessTree n hn r O N L h) := by + unfold canonicalWitnessTree oracleWitnessTree + split_ifs + · exact canonicalRestartTree_reindexed n hn r O N L h _ _ + · exact .leaf none +lemma canonicalAlgorithmTree_reindexed : + DrawTree.Reindexed (canonicalAlgorithmTree n hn r O N L) (oracleAlgorithmTree n hn r O N L) := + (DrawTree.Reindexed.history (canonicalPhaseTree_reindexed n hn r O N L) L []).optionBind + (fun h => (canonicalWitnessTree_reindexed n hn r O N L h).map _) + +end + +section CanonicalFair +open scoped BigOperators Classical +lemma uniformAverage_independent_eq {X Y Z : Type*} [Fintype X] [Fintype Y] + (f : X → Z) (g : Y → Z) + (h : ∀ φ : Z → ℝ,uniformAverage (fun x => φ (f x))=uniformAverage (fun y => φ (g y))) + (k : ℕ) (F : (Fin k → Z) → ℝ) : + uniformAverage (fun xs : Fin k → X => F (fun i => f (xs i)))= + uniformAverage (fun ys : Fin k → Y => F (fun i => g (ys i))) := by + induction k with + | zero => + have hf : ∀ xs : Fin 0 → X,(fun i => f (xs i))=(fun i : Fin 0 => Fin.elim0 i) := by + intro xs; funext i; exact Fin.elim0 i + have hg : ∀ ys : Fin 0 → Y,(fun i => g (ys i))=(fun i : Fin 0 => Fin.elim0 i) := by + intro ys; funext i; exact Fin.elim0 i + simp_rw [hf,hg,uniformAverage_const] + | succ k ih => + have hf (x : X) (xs : Fin k → X) : + (fun i : Fin (k+1) => f ((Fin.cons x xs : Fin (k+1) → X) i))=Fin.cons (f x) (fun i => f (xs i)) := by + funext i; refine Fin.cases ?_ (fun j => ?_) i <;> rfl + have hg (y : Y) (ys : Fin k → Y) : + (fun i : Fin (k+1) => g ((Fin.cons y ys : Fin (k+1) → Y) i))=Fin.cons (g y) (fun i => g (ys i)) := by + funext i; refine Fin.cases ?_ (fun j => ?_) i <;> rfl + rw [uniformAverage_fin_succ,uniformAverage_fin_succ] + simp_rw [hf,hg] + have hi (x : X) := ih (fun zs => F (Fin.cons (f x) zs)) + simp_rw [hi] + exact h (fun z => uniformAverage (fun ys : Fin k → Y => F (Fin.cons z (fun i => g (ys i))))) +noncomputable def canonicalFairOutput (n : ℕ) (hn : 0 canonicalFairOutput n hn r O N L (bits i))) +noncomputable def canonicalBoundedOutput (n r : ℕ) (O : IndependenceOracle n) + (ε δ : ℚ) (bits : FPRASBank n ε δ) : ℚ := + if hn : 0 simp + | some a => + cases a with + | none => simp + | some z => + simp only [Option.join_some,Option.getD_some] + have hz := DrawTree.run_all _ _ _ _ _ ht bits (some z) he z rfl + exact ⟨hz.1,hz.2 hE₂ (hr₁.trans hr₂.symm)⟩ +include hO hE₁ hE₂ hr₁ hr₂ in +lemma canonicalFairOutput_law (hN : 0 φ (canonicalFairOutput n hn r O N L bits))= + uniformAverage (fun bits : FairBank n N L => φ (fairOutput n hn M₁ M₂ N L bits)) := + (canonicalAlgorithmTree_to_rational n hn r O N L M₁ M₂ hO hE₁ hE₂ hr₁ hr₂).run_observable _ _ _ + (canonicalAlgorithmTree_fits n hn r O N L M₁ M₂ hO hE₁ hE₂ hr₁ hr₂ hN) + (fun a : Option (Option ℚ) => φ (a.join.getD 0)) +include hO hE₁ hE₂ hr₁ hr₂ in +lemma canonicalAmplifiedOutput_law (hN : 0 φ (canonicalAmplifiedOutput n hn r O N L δ bits))= + uniformAverage (fun bits => φ (amplifiedOutput n hn M₁ M₂ N L δ bits)) := + uniformAverage_independent_eq (canonicalFairOutput n hn r O N L) (fairOutput n hn M₁ M₂ N L) + (canonicalFairOutput_law n hn r O N L M₁ M₂ hO hE₁ hE₂ hr₁ hr₂ hN) _ + (fun z => φ (rationalMedian (List.ofFn z))) +include hO hE₁ hE₂ hr₁ hr₂ in +lemma canonicalAmplifiedOutput_all (δ : ℚ) (bits : Fin (repetitionCount δ) → FairBank n N L) : + 0≤canonicalAmplifiedOutput n hn r O N L δ bits ∧ + (commonBaseCount M₁ M₂=0 → canonicalAmplifiedOutput n hn r O N L δ bits=0) := by + constructor + · apply rationalMedian_all (fun z => 0≤z) _ (by norm_num) + intro z hz + obtain ⟨i,rfl⟩ := List.mem_ofFn.mp hz + exact (canonicalFairOutput_all n hn r O N L M₁ M₂ hO hE₁ hE₂ hr₁ hr₂ (bits i)).1 + · intro hZ + apply rationalMedian_all (fun z => z=0) _ rfl + intro z hz + obtain ⟨i,rfl⟩ := List.mem_ofFn.mp hz + exact (canonicalFairOutput_all n hn r O N L M₁ M₂ hO hE₁ hE₂ hr₁ hr₂ (bits i)).2 hZ +end CanonicalFair + +open scoped BigOperators Classical + +theorem canonical_bounded_fair_experiment (n r : ℕ) (O : IndependenceOracle n) + (M₁ M₂ : Matroid (Fin n)) (hO : ExactOracles M₁ M₂ O) + (hE₁ : M₁.E=Set.univ) (hE₂ : M₂.E=Set.univ) + (hr₁ : M₁.eRank=(r:ℕ∞)) (hr₂ : M₂.eRank=(r:ℕ∞)) + (ε δ : ℚ) (hε0 : 0<ε) (hε1 : ε<1) (hδ : 0<δ) : + (∀ bits : FPRASBank n ε δ,0≤canonicalBoundedOutput n r O ε δ bits ∧ + (commonBaseCount M₁ M₂=0 → canonicalBoundedOutput n r O ε δ bits=0)) ∧ + 1-(δ:ℝ)≤uniformAverage (fun bits : FPRASBank n ε δ => + if relativeAccuracy ε (commonBaseCount M₁ M₂) (canonicalBoundedOutput n r O ε δ bits) then (1:ℝ) else 0) := by + by_cases hn : 0 if relativeAccuracy ε (commonBaseCount M₁ M₂) z then (1:ℝ) else 0) + rw [hlaw] + exact (bounded_fair_experiment n hn M₁ M₂ hE₁ hE₂ (hr₁.trans hr₂.symm) ε δ hε0 hε1 hδ).2 + · have hn0 : n=0 := by omega + subst n + have ho : ∀ bits : FPRASBank 0 ε δ,canonicalBoundedOutput 0 r O ε δ bits=1 := by intro bits; simp [canonicalBoundedOutput] + constructor + · intro bits + rw [ho bits,commonBaseCount_empty] + norm_num + · have hac : 1-ε≤(1:ℚ) ∧ (1:ℚ)≤1+ε := by constructor <;> linarith + simpa only [ho,commonBaseCount_empty,relativeAccuracy,Nat.cast_one,mul_one,ite_eq_left hac, + uniformAverage_const] using (sub_le_self (1:ℝ) (by exact_mod_cast hδ.le : (0:ℝ)≤δ)) + +open scoped BigOperators Classical + +def bitMatrixEquiv (a b : ℕ) : BitWord (a*b) ≃ (Fin a → BitWord b) := + (Equiv.arrowCongr finProdFinEquiv.symm (Equiv.refl Bool)).trans + (Equiv.curry (Fin a) (Fin b) Bool) +def fourBitEquiv (a b c d : ℕ) : BitWord (a*(b*(c*d))) ≃ + (Fin a → Fin b → Fin c → BitWord d) := + (bitMatrixEquiv a (b*(c*d))).trans + (Equiv.piCongrRight (fun _ => (bitMatrixEquiv b (c*d)).trans + (Equiv.piCongrRight (fun _ => bitMatrixEquiv c d)))) +def bankWordEquiv (n : ℕ) (ε δ : ℚ) : BitWord (fairBitCount n ε δ) ≃ FPRASBank n ε δ := by + let L := annealLength n (accuracyExponent ε) + let N := sampleCount n L ε + let M := algorithmDrawBound n N L + let H := drawWordBound n N L + let R := repetitionCount δ + have h : fairBitCount n ε δ=R*(M*((M+6)*H)) := by + dsimp [fairBitCount,R,M,H,N,L]; ring + exact (Equiv.arrowCongr (finCongr h) (Equiv.refl Bool)).trans + (fourBitEquiv R M (M+6) H) +noncomputable def flatFPRASOutput (n r : ℕ) (O : IndependenceOracle n) (ε δ : ℚ) + (bits : BitWord (fairBitCount n ε δ)) : ℚ := + canonicalBoundedOutput n r O ε δ (bankWordEquiv n ε δ bits) +noncomputable def paddedFPRASOutput (n r : ℕ) (O : IndependenceOracle n) (ε δ : ℚ) + (B : ℕ) (hB : fairBitCount n ε δ≤B) (bits : BitWord B) : ℚ := + flatFPRASOutput n r O ε δ (bitPrefix _ B hB bits) +lemma paddedFPRASOutput_law (n r : ℕ) (O : IndependenceOracle n) (ε δ : ℚ) + (B : ℕ) (hB : fairBitCount n ε δ≤B) (φ : ℚ → ℝ) : + uniformAverage (fun bits => φ (paddedFPRASOutput n r O ε δ B hB bits))= + uniformAverage (fun bits => φ (canonicalBoundedOutput n r O ε δ bits)) := by + unfold paddedFPRASOutput + rw [uniformAverage_bitPrefix _ B hB (fun w => φ (flatFPRASOutput n r O ε δ w))] + unfold flatFPRASOutput + exact uniformAverage_equiv (bankWordEquiv n ε δ) + (fun w : FPRASBank n ε δ => φ (canonicalBoundedOutput n r O ε δ w)) +lemma uniformAverage_indicator_card {X : Type*} [Fintype X] (P : X → Prop) : + uniformAverage (fun x => if P x then (1:ℝ) else 0)= + (Nat.card {x // P x}:ℝ)/(Fintype.card X:ℝ) := by + simp [uniformAverage,Nat.card_eq_fintype_card,Fintype.card_subtype] + +theorem padded_fair_experiment (n r : ℕ) (O : IndependenceOracle n) + (M₁ M₂ : Matroid (Fin n)) (hO : ExactOracles M₁ M₂ O) + (hE₁ : M₁.E=Set.univ) (hE₂ : M₂.E=Set.univ) + (hr₁ : M₁.eRank=(r:ℕ∞)) (hr₂ : M₂.eRank=(r:ℕ∞)) + (ε δ : ℚ) (hε0 : 0<ε) (hε1 : ε<1) (hδ : 0<δ) + (B : ℕ) (hB : fairBitCount n ε δ≤B) : + (∀ bits : BitWord B,0≤paddedFPRASOutput n r O ε δ B hB bits ∧ + (commonBaseCount M₁ M₂=0 → paddedFPRASOutput n r O ε δ B hB bits=0)) ∧ + (1-δ)*(2:ℚ)^B≤(Nat.card {bits : BitWord B // + relativeAccuracy ε (commonBaseCount M₁ M₂) (paddedFPRASOutput n r O ε δ B hB bits)}:ℚ) := by + have hfull := canonical_bounded_fair_experiment n r O M₁ M₂ hO hE₁ hE₂ hr₁ hr₂ ε δ hε0 hε1 hδ + constructor + · intro bits + exact hfull.1 _ + · have h := hfull.2 + rw [←paddedFPRASOutput_law n r O ε δ B hB + (fun z => if relativeAccuracy ε (commonBaseCount M₁ M₂) z then (1:ℝ) else 0)] at h + rw [uniformAverage_indicator_card] at h + have hcard : Fintype.card (BitWord B)=2^B := by simp [BitWord] + rw [hcard,Nat.cast_pow,Nat.cast_ofNat] at h + have hh := (le_div_iff₀ (by positivity : (0:ℝ)<2^B)).mp h + exact_mod_cast hh + +section + +inductive OracleDraw (n : ℕ) (A : Type) where + | pure : A → OracleDraw n A + | query : Bool → (Fin n → Bool) → (Bool → OracleDraw n A) → OracleDraw n A + | draw : (v : ℕ) → (Fin (v+1) → OracleDraw n A) → OracleDraw n A +namespace OracleDraw +variable {n : ℕ} {A B : Type} +def bind : OracleDraw n A → (A → OracleDraw n B) → OracleDraw n B + | .pure a,f => f a + | .query w S k,f => .query w S (fun b => (k b).bind f) + | .draw v k,f => .draw v (fun i => (k i).bind f) +def map (t : OracleDraw n A) (f : A → B) : OracleDraw n B := t.bind (fun a => .pure (f a)) +def lift : DrawTree A → OracleDraw n A + | .leaf a => .pure a + | .draw v k => .draw v (fun i => lift (k i)) +def resolve (O : IndependenceOracle n) : OracleDraw n A → DrawTree A + | .pure a => .leaf a + | .query w S k => resolve O (k (O w S)) + | .draw v k => .draw v (fun i => resolve O (k i)) +lemma resolve_bind (O : IndependenceOracle n) (t : OracleDraw n A) (f : A → OracleDraw n B) : + resolve O (t.bind f)=(resolve O t).bind (fun a => resolve O (f a)) := by + induction t with + | pure a => rfl + | query w S k ih => exact ih (O w S) + | draw v k ih => simp only [bind,resolve,DrawTree.bind]; congr; funext i; exact ih i +lemma resolve_map (O : IndependenceOracle n) (t : OracleDraw n A) (f : A → B) : + resolve O (t.map f)=(resolve O t).map f := resolve_bind O t _ +lemma resolve_lift (O : IndependenceOracle n) (t : DrawTree A) : resolve O (lift t)=t := by + induction t with + | leaf a => rfl + | draw v k ih => simp only [lift,resolve]; congr; funext i; exact ih i + +def Queries : ℕ → OracleDraw n A → Prop + | _,.pure _ => True + | Q,.query _ _ k => 0 ∀ i,Queries Q (k i) +lemma queries_mono (t : OracleDraw n A) {Q R : ℕ} (h : Queries Q t) (hle : Q≤R) : Queries R t := by + induction t generalizing Q R with + | pure a => trivial + | query w S k ih => + have hq := h.1 + exact ⟨by omega,fun b => ih b (h.2 b) (by omega)⟩ + | draw v k ih => exact fun i => ih i (h i) hle +lemma queries_bind (t : OracleDraw n A) (f : A → OracleDraw n B) (Q R : ℕ) + (ht : Queries Q t) (hf : ∀ a,Queries R (f a)) : Queries (Q+R) (t.bind f) := by + induction t generalizing Q with + | pure a => exact queries_mono (f a) (hf a) (by omega) + | query w S k ih => + have hq := ht.1 + refine ⟨by omega,?_⟩ + intro b + have he : Q+R-1=(Q-1)+R := by have hq := ht.1; omega + rw [he]; exact ih b (Q-1) (ht.2 b) + | draw v k ih => exact fun i => ih i Q (ht i) +lemma queries_map (t : OracleDraw n A) (f : A → B) (Q : ℕ) (ht : Queries Q t) : Queries Q (t.map f) := by + exact queries_bind t (fun a => .pure (f a)) Q 0 ht (fun _ => trivial) +lemma queries_lift (t : DrawTree A) : Queries 0 (lift t : OracleDraw n A) := by + induction t with + | leaf a => trivial + | draw v k ih => exact ih + +def run (O : IndependenceOracle n) (H D : ℕ) : + OracleDraw n A → (M : ℕ) → (Fin M → Fin D → BitWord H) → Option A × ℕ + | .pure a,_,_ => (some a,0) + | .query w S k,M,bits => + let out := run O H D (k (O w S)) M bits + (out.1,out.2+1) + | .draw _ _,0,_ => (none,0) + | .draw v k,M+1,bits => + if hh : Nat.clog 2 (v+1)≤H then + match boundedUniform (v+1) (Nat.clog 2 (v+1)) D (fun d => bitPrefix _ H hh (bits 0 d)) with + | none => (none,0) + | some i => run O H D (k i) M (Fin.tail bits) + else (none,0) +lemma run_resolve (O : IndependenceOracle n) (H D : ℕ) (t : OracleDraw n A) + (M : ℕ) (bits : Fin M → Fin D → BitWord H) : + (run O H D t M bits).1=DrawTree.run H D M (resolve O t) bits := by + induction t generalizing M with + | pure a => simp [run,resolve,DrawTree.run] + | query w S k ih => exact ih (O w S) M bits + | draw v k ih => + cases M with + | zero => rfl + | succ M => + simp only [run,resolve,DrawTree.run] + split_ifs + · split <;> rename_i he + · simp only [] + · simpa only [he] using ih _ M (Fin.tail bits) + · rfl +lemma run_queries (O : IndependenceOracle n) (H D : ℕ) (t : OracleDraw n A) + (Q M : ℕ) (ht : Queries Q t) (bits : Fin M → Fin D → BitWord H) : + (run O H D t M bits).2≤Q := by + induction t generalizing Q M with + | pure a => simp [run] + | query w S k ih => + have hq := ht.1 + have h := ih (O w S) (Q-1) M (ht.2 _) bits + change (run O H D (k (O w S)) M bits).2+1≤Q + omega + | draw v k ih => + cases M with + | zero => simp [run] + | succ M => + simp only [run] + split_ifs + · split + · simp + · exact ih _ Q M (ht _) _ + · simp +end OracleDraw +open scoped Classical +variable {n : ℕ} +def greedyEffect (which : Bool) : List (Fin n) → OracleDraw n (Finset (Fin n)) + | [] => .pure ∅ + | a::l => (greedyEffect which l).bind (fun I => + .query which (fun i => decide (i ∈ insert a I)) (fun b => .pure (if b then insert a I else I))) +lemma greedyEffect_resolve (O : IndependenceOracle n) (which : Bool) (l : List (Fin n)) : + OracleDraw.resolve O (greedyEffect which l)=.leaf (greedyOracle (queryFinset O which) l) := by + induction l with + | nil => rfl + | cons a l ih => simp [greedyEffect,OracleDraw.resolve_bind,ih,DrawTree.bind,OracleDraw.resolve,greedyOracle,queryFinset] +lemma greedyEffect_queries (which : Bool) (l : List (Fin n)) : + OracleDraw.Queries l.length (greedyEffect which l) := by + induction l with + | nil => trivial + | cons a l ih => + exact OracleDraw.queries_bind _ _ l.length 1 ih (fun I => ⟨by omega,fun b => trivial⟩) +def rankEffect (which : Bool) (S : Finset (Fin n)) : OracleDraw n ℕ := + (greedyEffect which ((List.finRange n).filter (fun i => decide (i ∈ S)))).map Finset.card +lemma rankEffect_resolve (O : IndependenceOracle n) (which : Bool) (S : Finset (Fin n)) : + OracleDraw.resolve O (rankEffect which S)=.leaf (rankOracle O which S) := by + simp [rankEffect,OracleDraw.resolve_map,greedyEffect_resolve,DrawTree.map,DrawTree.bind,rankOracle] +lemma rankEffect_queries (which : Bool) (S : Finset (Fin n)) : + OracleDraw.Queries n (rankEffect which S) := by + apply OracleDraw.queries_mono _ (OracleDraw.queries_map _ _ _ (greedyEffect_queries which _)) + exact (List.length_filter_le _ _).trans_eq (List.length_finRange (n := n)) +noncomputable def deficiencyEffect (r : ℕ) (S : Set (Fin n ⊕ Fin n)) : OracleDraw n ℕ := + (rankEffect false (Sum.inl ⁻¹' S).toFinset).bind (fun rx => + (rankEffect true (Sum.inr ⁻¹' S).toFinsetᶜ).map (fun rc => n+r-(rx+(Sum.inr ⁻¹' S).toFinset.card+rc))) +lemma deficiencyEffect_resolve (O : IndependenceOracle n) (r : ℕ) (S : Set (Fin n ⊕ Fin n)) : + OracleDraw.resolve O (deficiencyEffect r S)=.leaf (oracleDeficiency n r O S) := by + simp [deficiencyEffect,OracleDraw.resolve_bind,OracleDraw.resolve_map,rankEffect_resolve, + DrawTree.map,DrawTree.bind,oracleDeficiency,pairedDeficiencyOracle] +lemma deficiencyEffect_queries (r : ℕ) (S : Set (Fin n ⊕ Fin n)) : + OracleDraw.Queries (2*n) (deficiencyEffect r S) := by + simpa only [two_mul,deficiencyEffect] using OracleDraw.queries_bind _ _ n n (rankEffect_queries false _) + (fun rx => OracleDraw.queries_map _ _ n (rankEffect_queries true _)) + +end + +section +namespace OracleDraw +open scoped Classical +variable {n : ℕ} {A B : Type} +def optionBind (t : OracleDraw n (Option A)) (f : A → OracleDraw n (Option B)) : OracleDraw n (Option B) := + t.bind (fun a => match a with | none => .pure none | some a => f a) +lemma resolve_optionBind (O : IndependenceOracle n) (t : OracleDraw n (Option A)) (f : A → OracleDraw n (Option B)) : + resolve O (t.optionBind f)=(resolve O t).optionBind (fun a => resolve O (f a)) := by + rw [optionBind,resolve_bind,DrawTree.optionBind]; congr; funext a; cases a <;> rfl +lemma queries_optionBind (t : OracleDraw n (Option A)) (f : A → OracleDraw n (Option B)) + (Q R : ℕ) (ht : Queries Q t) (hf : ∀ a,Queries R (f a)) : Queries (Q+R) (t.optionBind f) := by + apply queries_bind _ _ Q R ht + intro a; cases a with + | none => trivial + | some a => exact hf a +def iterate (t : A → OracleDraw n (Option A)) : ℕ → A → OracleDraw n (Option A) + | 0,a => .pure (some a) + | k+1,a => (iterate t k a).optionBind t +lemma resolve_iterate (O : IndependenceOracle n) (t : A → OracleDraw n (Option A)) (k : ℕ) (a : A) : + resolve O (iterate t k a)=DrawTree.iterate (fun a => resolve O (t a)) k a := by + induction k with + | zero => rfl + | succ k ih => simp [iterate,resolve_optionBind,ih,DrawTree.iterate] +lemma queries_iterate (t : A → OracleDraw n (Option A)) (Q k : ℕ) (ht : ∀ a,Queries Q (t a)) (a : A) : + Queries (Q*k) (iterate t k a) := by + induction k with + | zero => trivial + | succ k ih => simpa only [iterate,Nat.mul_succ] using queries_optionBind _ t (Q*k) Q ih ht +def sample (step : A → OracleDraw n A) : (k : ℕ) → A → OracleDraw n (FiniteChain.Sample A k) + | 0,a => .pure a + | k+1,a => (step a).bind (fun b => (sample step k b).map (fun v => (a,v))) +lemma resolve_sample (O : IndependenceOracle n) (step : A → OracleDraw n A) (k : ℕ) (a : A) : + resolve O (sample step k a)=DrawTree.sample (fun a => resolve O (step a)) k a := by + induction k generalizing a with + | zero => rfl + | succ k ih => + simp only [sample,resolve_bind,DrawTree.sample] + congr; funext b + exact (resolve_map O (sample step k b) (fun v => (a,v))).trans (by rw [ih]; rfl) +lemma queries_sample (step : A → OracleDraw n A) (Q k : ℕ) (hs : ∀ a,Queries Q (step a)) (a : A) : + Queries (Q*k) (sample step k a) := by + induction k generalizing a with + | zero => trivial + | succ k ih => + simpa only [sample,Nat.mul_succ,Nat.add_comm] using queries_bind (step a) _ Q (Q*k) (hs a) + (fun b => queries_map _ _ _ (ih b)) +noncomputable def hitting (step : A → OracleDraw n A) (p : A → Prop) : ℕ → A → OracleDraw n (Option {a // p a}) + | 0,_ => .pure none + | k+1,a => (step a).bind (fun b => if hb : p b then .pure (some ⟨b,hb⟩) else hitting step p k b) +lemma resolve_hitting [Fintype A] (O : IndependenceOracle n) (step : A → OracleDraw n A) (p : A → Prop) (k : ℕ) (a : A) : + resolve O (hitting step p k a)=hittingTree (fun a => resolve O (step a)) p k a := by + induction k generalizing a with + | zero => rfl + | succ k ih => + simp only [hitting,resolve_bind,hittingTree] + congr; funext b; split_ifs <;> first | rfl | exact ih b +lemma queries_hitting (step : A → OracleDraw n A) (p : A → Prop) (Q k : ℕ) + (hs : ∀ a,Queries Q (step a)) (a : A) : Queries (Q*k) (hitting step p k a) := by + induction k generalizing a with + | zero => trivial + | succ k ih => + have h := queries_bind (step a) (fun b => if hb : p b then .pure (some ⟨b,hb⟩) else hitting step p k b) + Q (Q*k) (hs a) (by intro b; split_ifs; exacts [trivial,ih b]) + simpa only [hitting,Nat.mul_succ,Nat.add_comm] using h +noncomputable def traverse (f : A → OracleDraw n B) : List A → OracleDraw n (List B) + | [] => .pure [] + | a::l => (f a).bind (fun b => (traverse f l).map (fun xs => b::xs)) +lemma traverse_resolve (O : IndependenceOracle n) (f : A → OracleDraw n B) (g : A → B) + (hf : ∀ a,resolve O (f a)=.leaf (g a)) (l : List A) : resolve O (traverse f l)=.leaf (l.map g) := by + induction l with + | nil => rfl + | cons a l ih => simp [traverse,resolve_bind,resolve_map,hf,ih,DrawTree.bind,DrawTree.map] +lemma traverse_queries (f : A → OracleDraw n B) (Q : ℕ) (hf : ∀ a,Queries Q (f a)) (l : List A) : + Queries (Q*l.length) (traverse f l) := by + induction l with + | nil => trivial + | cons a l ih => + simpa only [traverse,List.length_cons,Nat.mul_succ,Nat.add_comm] using queries_bind (f a) _ Q (Q*l.length) (hf a) + (fun b => queries_map _ _ _ ih) +end OracleDraw +open scoped BigOperators Classical +variable (n : ℕ) (hn : 0 pairedSlots n +noncomputable def exchangeEffect (w : ((Fin n ⊕ Fin n) × (Fin n ⊕ Fin n)) → + ((Fin n ⊕ Fin n) × (Fin n ⊕ Fin n)) → ℚ) (j : ℕ) + (S : ChainIndex GS) (a : ExchangeChoice S.val) : OracleDraw n (ChainIndex GS) := + if ht : ChainState GS (exchangedSet S.val a) then + let T : ChainIndex GS := ⟨exchangedSet S.val a,ht⟩ + (deficiencyEffect r S.val).bind (fun ds => (deficiencyEffect r T.val).bind (fun dt => + OracleDraw.lift ((DrawTree.bernoulli (min 1 + ((rationalMultiplier GS w T.val*(rationalRho n^j)^dt)/ + (rationalMultiplier GS w S.val*(rationalRho n^j)^ds)))).map (fun accept => if accept then T else S)))) + else .pure S +lemma exchangeEffect_resolve (O : IndependenceOracle n) (w) (j : ℕ) (S : ChainIndex GS) (a : ExchangeChoice S.val) : + OracleDraw.resolve O (exchangeEffect n r w j S a)=rationalExchange GS w (oracleAnneal n r O j) S a := by + unfold exchangeEffect rationalExchange + split_ifs + · simp only [OracleDraw.resolve_bind,deficiencyEffect_resolve,DrawTree.bind,OracleDraw.resolve_lift] + rfl + · rfl +lemma exchangeEffect_queries (w) (j : ℕ) (S : ChainIndex GS) (a : ExchangeChoice S.val) : + OracleDraw.Queries (4*n) (exchangeEffect n r w j S a) := by + unfold exchangeEffect + split_ifs + · rw [show 4*n=2*n+2*n by omega] + apply OracleDraw.queries_bind _ _ (2*n) (2*n) (deficiencyEffect_queries r _) + intro ds + exact OracleDraw.queries_bind _ _ (2*n) 0 (deficiencyEffect_queries r _) + (fun dt => OracleDraw.queries_lift _) + · trivial +noncomputable def stepEffect (h : List (PhaseSample n N)) (j : ℕ) (S : ChainIndex GS) : OracleDraw n (ChainIndex GS) := + letI : Nonempty (ExchangeChoice S.val) := Fintype.card_pos_iff.mp (by + rw [exchangeChoice_card GS (pairedSlots_fresh n) (pairedSlots_cover n),pairedSlots_length]; positivity) + (OracleDraw.lift (DrawTree.bernoulli (1/2))).bind (fun lazy => if lazy then .pure S else + (OracleDraw.lift (DrawTree.uniformVia (ExchangeChoice S.val) (canonicalExchangeEnumeration n S.val))).bind + (exchangeEffect n r (rationalStored n N h j) j S)) +lemma stepEffect_resolve (O : IndependenceOracle n) (h : List (PhaseSample n N)) (j : ℕ) (S : ChainIndex GS) : + OracleDraw.resolve O (stepEffect n hn r N h j S)=canonicalStepTree n hn r O N h j S := by + unfold stepEffect canonicalStepTree canonicalMetropolis + simp only [OracleDraw.resolve_bind,OracleDraw.resolve_lift] + congr; funext a; cases a + · simp only [Bool.false_eq_true,ite_false,OracleDraw.resolve_bind,OracleDraw.resolve_lift] + congr; funext b; exact exchangeEffect_resolve n r O _ _ _ _ + · rfl +lemma stepEffect_queries (h : List (PhaseSample n N)) (j : ℕ) (S : ChainIndex GS) : + OracleDraw.Queries (4*n) (stepEffect n hn r N h j S) := by + let : Nonempty (ExchangeChoice S.val) := Fintype.card_pos_iff.mp (by + rw [exchangeChoice_card GS (pairedSlots_fresh n) (pairedSlots_cover n),pairedSlots_length]; positivity) + have hp : OracleDraw.Queries (0+4*n) (stepEffect n hn r N h j S) := by + unfold stepEffect + apply OracleDraw.queries_bind _ _ 0 (4*n) (OracleDraw.queries_lift _) + intro a; cases a + · simp only [Bool.false_eq_true,ite_false] + have hq : OracleDraw.Queries (0+4*n) + ((OracleDraw.lift (DrawTree.uniformVia (ExchangeChoice S.val) + (canonicalExchangeEnumeration n S.val))).bind + (exchangeEffect n r (rationalStored n N h j) j S)) := + OracleDraw.queries_bind _ _ 0 (4*n) (OracleDraw.queries_lift _) + (fun b => exchangeEffect_queries n r _ _ _ b) + simpa only [Nat.zero_add] using hq + · trivial + simpa only [Nat.zero_add] using hp +noncomputable def traceEffect (h : List (PhaseSample n N)) (j cap : ℕ) (x : PlainIndex GS) : + OracleDraw n (Option (PlainIndex GS)) := + OracleDraw.hitting (stepEffect n hn r N h j) (plainPredicate GS) (cap+1) x.val +lemma traceEffect_resolve (O : IndependenceOracle n) (h : List (PhaseSample n N)) (j cap : ℕ) (x : PlainIndex GS) : + OracleDraw.resolve O (traceEffect n hn r N h j cap x)=canonicalTraceTree n hn r O N h j cap x := by + simp only [traceEffect,OracleDraw.resolve_hitting,stepEffect_resolve,canonicalTraceTree] +lemma traceEffect_queries (h : List (PhaseSample n N)) (j cap : ℕ) (x : PlainIndex GS) : + OracleDraw.Queries (4*n*(cap+1)) (traceEffect n hn r N h j cap x) := + OracleDraw.queries_hitting _ _ _ _ (stepEffect_queries n hn r N h j) _ +noncomputable def restartEffect (h : List (PhaseSample n N)) (cap : ℕ) : ℕ → OracleDraw n (Option (PlainIndex GS)) + | 0 => + letI := plainIndex_nonempty GS (pairedSlots_fresh n) (pairedSlots_cover n) + OracleDraw.lift ((DrawTree.uniformVia (PlainIndex GS) (canonicalPlainEnumeration n)).map some) + | j+1 => (restartEffect h cap j).optionBind + (OracleDraw.iterate (traceEffect n hn r N h (j+1) cap) (20*n^4*(n*(L+1)+2))) +lemma restartEffect_resolve (O : IndependenceOracle n) (h : List (PhaseSample n N)) (cap j : ℕ) : + OracleDraw.resolve O (restartEffect n hn r N L h cap j)=canonicalRestartTree n hn r O N L h cap j := by + induction j with + | zero => exact OracleDraw.resolve_lift O _ + | succ j ih => simp only [restartEffect,canonicalRestartTree,OracleDraw.resolve_optionBind, + OracleDraw.resolve_iterate,traceEffect_resolve,ih] +lemma restartEffect_queries (h : List (PhaseSample n N)) (cap j : ℕ) : + OracleDraw.Queries (4*n*(cap+1)*(20*n^4*(n*(L+1)+2))*j) (restartEffect n hn r N L h cap j) := by + induction j with + | zero => exact OracleDraw.queries_lift _ + | succ j ih => + simpa only [restartEffect,Nat.mul_succ] using OracleDraw.queries_optionBind _ _ _ _ ih + (OracleDraw.queries_iterate _ _ _ (traceEffect_queries n hn r N h (j+1) cap)) +noncomputable def startEffect (h : List (PhaseSample n N)) : OracleDraw n (Option (ChainIndex GS)) := + (restartEffect n hn r N L h (restartCap n L) h.length).map (Option.map Subtype.val) +noncomputable def phaseEffect (h : List (PhaseSample n N)) : OracleDraw n (Option (PhaseSample n N)) := + if rationalHistoryPositive n N h then + (startEffect n hn r N L h).optionBind + (fun x => (OracleDraw.sample (stepEffect n hn r N h h.length) (N-1) x).map some) + else .pure none +lemma phaseEffect_resolve (O : IndependenceOracle n) (h : List (PhaseSample n N)) : + OracleDraw.resolve O (phaseEffect n hn r N L h)=canonicalPhaseTree n hn r O N L h := by + unfold phaseEffect canonicalPhaseTree + split_ifs + · simp only [OracleDraw.resolve_optionBind,startEffect,OracleDraw.resolve_map,restartEffect_resolve, + canonicalStartTree,OracleDraw.resolve_sample,stepEffect_resolve] + · rfl +noncomputable def witnessEffect (h : List (PhaseSample n N)) : OracleDraw n (Option (PlainIndex GS)) := + if rationalHistoryPositive n N h then restartEffect n hn r N L h (restartCap n L) h.length else .pure none +lemma witnessEffect_resolve (O : IndependenceOracle n) (h : List (PhaseSample n N)) : + OracleDraw.resolve O (witnessEffect n hn r N L h)=canonicalWitnessTree n hn r O N L h := by + unfold witnessEffect canonicalWitnessTree + split_ifs + · exact restartEffect_resolve n hn r N L O h _ _ + · rfl + +end + +section +open scoped BigOperators Classical +variable (n : ℕ) (hn : 0 pairedSlots n +noncomputable def ratioEffect (l : List (Set (Fin n ⊕ Fin n))) : OracleDraw n ℚ := + (OracleDraw.traverse (fun S => (deficiencyEffect r S).map + (fun d => rationalPlain GS (fun _ => rationalRho n ^ d) S)) l).map + (fun vs => (vs.sum/(l.length:ℚ))/rationalEmpirical (rationalPlain GS (fun _ => 1)) l) +lemma ratioEffect_resolve (O : IndependenceOracle n) (l : List (Set (Fin n ⊕ Fin n))) : + OracleDraw.resolve O (ratioEffect n r l)=.leaf + (rationalRatio GS (fun S => rationalRho n ^ oracleDeficiency n r O S) l) := by + unfold ratioEffect + rw [OracleDraw.resolve_map,OracleDraw.traverse_resolve O _ + (fun S => rationalPlain GS (fun _ => rationalRho n ^ oracleDeficiency n r O S) S)] + · simp only [DrawTree.map,DrawTree.bind,rationalRatio,rationalEmpirical] + congr 3 + · intro S; simp only [OracleDraw.resolve_map,deficiencyEffect_resolve,DrawTree.map,DrawTree.bind] +lemma ratioEffect_queries (l : List (Set (Fin n ⊕ Fin n))) : + OracleDraw.Queries (2*n*l.length) (ratioEffect n r l) := by + apply OracleDraw.queries_map + exact OracleDraw.traverse_queries _ (2*n) + (fun S => OracleDraw.queries_map _ _ _ (deficiencyEffect_queries r S)) l +lemma historySample_length_bound (h : List (PhaseSample n N)) (j : ℕ) : + (historySample (observedSets n N) h j).length≤N+1 := by + unfold historySample + by_cases hj : j .pure 1 + | j+1 => (estimateProductEffect h j).bind (fun z => + (ratioEffect n r (historySample (observedSets n N) h j)).map (fun q => z*q)) +lemma estimateProductEffect_resolve (O : IndependenceOracle n) (h : List (PhaseSample n N)) (j : ℕ) : + OracleDraw.resolve O (estimateProductEffect n r N h j)=.leaf + (∏ i ∈ Finset.range j,rationalRatio GS (fun S => rationalRho n ^ oracleDeficiency n r O S) + (historySample (observedSets n N) h i)) := by + induction j with + | zero => simp [estimateProductEffect,OracleDraw.resolve] + | succ j ih => simp only [estimateProductEffect,OracleDraw.resolve_bind,ih,DrawTree.bind, + OracleDraw.resolve_map,ratioEffect_resolve,DrawTree.map,Finset.prod_range_succ] +lemma estimateProductEffect_queries (h : List (PhaseSample n N)) (j : ℕ) : + OracleDraw.Queries (2*n*(N+1)*j) (estimateProductEffect n r N h j) := by + induction j with + | zero => trivial + | succ j ih => + rw [Nat.mul_succ] + apply OracleDraw.queries_bind _ _ _ _ ih + intro z + apply OracleDraw.queries_map + exact OracleDraw.queries_mono _ (ratioEffect_queries n r _) (by + have hh := historySample_length_bound n N h j + gcongr) +noncomputable def estimateEffect (h : List (PhaseSample n N)) : OracleDraw n ℚ := + (estimateProductEffect n r N h L).map (fun z => (2:ℚ)^n*z) +lemma estimateEffect_resolve (O : IndependenceOracle n) (h : List (PhaseSample n N)) : + OracleDraw.resolve O (estimateEffect n r N L h)=.leaf (oracleEstimate n r O N L h) := by + simp only [estimateEffect,OracleDraw.resolve_map,estimateProductEffect_resolve,DrawTree.map,DrawTree.bind,oracleEstimate] +lemma estimateEffect_queries (h : List (PhaseSample n N)) : + OracleDraw.Queries (2*n*(N+1)*L) (estimateEffect n r N L h) := + OracleDraw.queries_map _ _ _ (estimateProductEffect_queries n r N h L) +noncomputable def guardEffect (h : List (PhaseSample n N)) (x : PlainIndex GS) : OracleDraw n ℚ := + (deficiencyEffect r x.val.val).bind (fun d => if d=0 then estimateEffect n r N L h else .pure 0) +lemma guardEffect_resolve (O : IndependenceOracle n) (h : List (PhaseSample n N)) (x : PlainIndex GS) : + OracleDraw.resolve O (guardEffect n r N L h x)=.leaf (oracleGuard n r O N L h x) := by + simp only [guardEffect,OracleDraw.resolve_bind,deficiencyEffect_resolve,DrawTree.bind,oracleGuard] + split_ifs + · exact estimateEffect_resolve n r N L O h + · rfl +lemma guardEffect_queries (h : List (PhaseSample n N)) (x : PlainIndex GS) : + OracleDraw.Queries (2*n+2*n*(N+1)*L) (guardEffect n r N L h x) := by + apply OracleDraw.queries_bind _ _ _ _ (deficiencyEffect_queries r _) + intro d; split_ifs + · exact estimateEffect_queries n r N L h + · trivial +noncomputable def finishEffect (h : List (PhaseSample n N)) : OracleDraw n (Option ℚ) := + (witnessEffect n hn r N L h).optionBind (fun x => (guardEffect n r N L h x).map some) +lemma finishEffect_resolve (O : IndependenceOracle n) (h : List (PhaseSample n N)) : + OracleDraw.resolve O (finishEffect n hn r N L h)= + (canonicalWitnessTree n hn r O N L h).map (Option.map (oracleGuard n r O N L h)) := by + rw [finishEffect,OracleDraw.resolve_optionBind,witnessEffect_resolve] + simp only [OracleDraw.resolve_map,guardEffect_resolve,DrawTree.map,DrawTree.bind,DrawTree.optionBind] + congr; funext a; cases a <;> rfl +noncomputable def historyFinishEffect : List (PhaseSample n N) → ℕ → OracleDraw n (Option ℚ) + | h,0 => finishEffect n hn r N L h + | h,k+1 => (phaseEffect n hn r N L h).optionBind (fun x => historyFinishEffect (h++[x]) k) +lemma historyFinishEffect_resolve (O : IndependenceOracle n) (h : List (PhaseSample n N)) (k : ℕ) : + OracleDraw.resolve O (historyFinishEffect n hn r N L h k)= + (DrawTree.history (canonicalPhaseTree n hn r O N L) k h).optionBind (fun h => + (canonicalWitnessTree n hn r O N L h).map (Option.map (oracleGuard n r O N L h))) := by + induction k generalizing h with + | zero => exact finishEffect_resolve n hn r N L O h + | succ k ih => simp only [historyFinishEffect,OracleDraw.resolve_optionBind,phaseEffect_resolve,ih, + DrawTree.history,DrawTree.optionBind_assoc] +noncomputable def queryAlgorithm : OracleDraw n (Option ℚ) := historyFinishEffect n hn r N L [] L +lemma queryAlgorithm_resolve (O : IndependenceOracle n) : + OracleDraw.resolve O (queryAlgorithm n hn r N L)=canonicalAlgorithmTree n hn r O N L := + historyFinishEffect_resolve n hn r N L O [] L + +end + +section +open scoped Classical +variable (n : ℕ) (hn : 0 OracleDraw.queries_map _ _ _ (guardEffect_queries n r N L h x)) + apply OracleDraw.queries_mono _ hp + unfold phaseQueryBound + have h1 : 4*n*(restartCap n L+1)*(20*n^4*(n*(L+1)+2))*h.length≤ + 4*n*(restartCap n L+1)*(20*n^4*(n*(L+1)+2))*L := by gcongr + omega +lemma historyFinishEffect_queries (h : List (PhaseSample n N)) (k : ℕ) (hk : h.length+k≤L) : + OracleDraw.Queries (phaseQueryBound n N L*(k+1)) (historyFinishEffect n hn r N L h k) := by + induction k generalizing h with + | zero => simpa only [historyFinishEffect,Nat.zero_add,Nat.mul_one] using finishEffect_queries n hn r N L h (by omega) + | succ k ih => + rw [show phaseQueryBound n N L*(k+1+1)=phaseQueryBound n N L+phaseQueryBound n N L*(k+1) by ring] + apply OracleDraw.queries_optionBind _ _ _ _ (phaseEffect_queries n hn r N L h (by omega)) + intro x; apply ih + simp only [List.length_append,List.length_singleton]; omega +def oracleQueryBound (n N L : ℕ) : ℕ := phaseQueryBound n N L*(L+1) +lemma queryAlgorithm_queries : OracleDraw.Queries (oracleQueryBound n N L) (queryAlgorithm n hn r N L) := + historyFinishEffect_queries n hn r N L [] L (by simp) +lemma capped_queryAlgorithm (O : IndependenceOracle n) (H D M : ℕ) + (bits : Fin M → Fin D → BitWord H) : + (OracleDraw.run O H D (queryAlgorithm n hn r N L) M bits).1= + DrawTree.run H D M (canonicalAlgorithmTree n hn r O N L) bits ∧ + (OracleDraw.run O H D (queryAlgorithm n hn r N L) M bits).2≤oracleQueryBound n N L := by + exact ⟨by rw [OracleDraw.run_resolve,queryAlgorithm_resolve], + OracleDraw.run_queries O H D _ _ M (queryAlgorithm_queries n hn r N L) bits⟩ + +lemma oracleQueryBound_le (n N L : ℕ) : + oracleQueryBound n N L≤4*n*(algorithmDrawBound n N L)+(2*n+2*n*(N+1)*L)*(L+1) := by + have hp : 4*n*(restartCap n L+1)*(20*n^4*(n*(L+1)+2))*L+4*n*N≤4*n*phaseDrawBound n N L := by + calc + _ = 4*n*(L*(restartCap n L+1)*(20*n^4*(n*(L+1)+2))+N) := by ring + _ ≤ 4*n*(1+3*(L*(restartCap n L+1)*(20*n^4*(n*(L+1)+2)))+3*N) := by gcongr <;> omega + _ = _ := by unfold phaseDrawBound; ring + calc + _ ≤ (4*n*phaseDrawBound n N L+(2*n+2*n*(N+1)*L))*(L+1) := by + unfold oracleQueryBound phaseQueryBound + apply Nat.mul_le_mul_right + omega + _ = _ := by unfold algorithmDrawBound; ring + +theorem allQueries_polynomial (n : ℕ) (ε δ : ℚ) : + repetitionCount δ*oracleQueryBound n (sampleCount n (annealLength n (accuracyExponent ε)) ε) + (annealLength n (accuracyExponent ε))≤10^31*(bitResourceParameter n ε δ)^30 := by + let T := bitResourceParameter n ε δ + have hT : 0 queryFairOutput n hn r O N L (bits i) + (rationalMedian (List.ofFn (fun i => (outs i).1)),∑ i,(outs i).2) +lemma queryAmplifiedOutput_value (n : ℕ) (hn : 0 queryFairOutput_queries n hn r O N L (bits i))) + simp +noncomputable def queryBoundedOutput (n r : ℕ) (O : IndependenceOracle n) + (ε δ : ℚ) (bits : FPRASBank n ε δ) : ℚ × ℕ := + if hn : 0 bits (t+i)) u := by + induction u with + | zero => rfl + | succ u ih => + change machineStep P O (bits (t+u)) (execution P O c bits (t+u))= + machineStep P O (bits (t+u)) (execution P O (execution P O c bits t) (fun i => bits (t+i)) u) + rw [ih] +def incrementProgram (a b : Fin (k+8)) : Program k 5 := fun pc => + match pc.val with + | 0 => .pop a 1 1 2 + | 1 => .push a true 3 + | 2 => .push b false 0 + | 3 => .pop b 5 4 4 + | 4 => .push a false 3 + | _ => .halt +def leadingOnes : List Bool → ℕ + | [] => 0 + | false::_ => 0 + | true::xs => leadingOnes xs+1 +def carryTail : List Bool → List Bool + | [] => [true] + | false::xs => true::xs + | true::xs => carryTail xs +lemma leadingOnes_le (xs : List Bool) : leadingOnes xs≤xs.length := by + induction xs with + | nil => simp [leadingOnes] + | cons b xs ih => cases b <;> simp [leadingOnes,List.length_cons] ; omega +lemma replicate_append_false (m : ℕ) (xs : List Bool) : + List.replicate m false ++ false::xs=List.replicate (m+1) false++xs := by + rw [List.replicate_succ']; simp +lemma increment_carry (a b : Fin (k+8)) (hab : a≠b) (O : IndependenceOracle n) + (R : Fin (k+8) → List Bool) (xs ys : List Bool) (q c : ℕ) (bits : ℕ → Bool) : + execution (incrementProgram a b) O (workConfig (pairRegisters R a b xs ys) 0 q c) bits + (2*leadingOnes xs+2)= + workConfig (pairRegisters R a b (carryTail xs) (List.replicate (leadingOnes xs) false++ys)) + 3 q (c+2*leadingOnes xs+2) := by + induction xs generalizing ys c bits with + | nil => + simp [leadingOnes,carryTail,execution,machineStep,incrementProgram,workConfig, + pairRegisters_a _ _ _ hab,pairRegisters_update_a _ _ _ hab] + | cons x xs ih => + cases x with + | false => + simp [leadingOnes,carryTail,execution,machineStep,incrementProgram,workConfig, + pairRegisters_a _ _ _ hab,pairRegisters_update_a _ _ _ hab] + | true => + have ht : execution (incrementProgram a b) O (workConfig (pairRegisters R a b (true::xs) ys) 0 q c) bits 2 = + workConfig (pairRegisters R a b xs (false::ys)) 0 q (c+2) := by + simp [execution,machineStep,incrementProgram,workConfig, + pairRegisters_a _ _ _ hab,pairRegisters_b,pairRegisters_update_a _ _ _ hab,pairRegisters_update_b] + rw [leadingOnes,show 2*(leadingOnes xs+1)+2=2+(2*leadingOnes xs+2) by omega,execution_add,ht,ih] + simp only [carryTail,replicate_append_false] + congr 1 ; omega +lemma increment_restore (a b : Fin (k+8)) (hab : a≠b) (O : IndependenceOracle n) + (R : Fin (k+8) → List Bool) (m : ℕ) (xs : List Bool) (q c : ℕ) (bits : ℕ → Bool) : + execution (incrementProgram a b) O (workConfig (pairRegisters R a b xs (List.replicate m false)) 3 q c) bits + (2*m+1)=workConfig (pairRegisters R a b (List.replicate m false++xs) []) 5 q (c+2*m+1) := by + induction m generalizing xs c bits with + | zero => + simp [execution,machineStep,incrementProgram,workConfig,pairRegisters_b] + | succ m ih => + have ht : execution (incrementProgram a b) O + (workConfig (pairRegisters R a b xs (List.replicate (m+1) false)) 3 q c) bits 2 = + workConfig (pairRegisters R a b (false::xs) (List.replicate m false)) 3 q (c+2) := by + simp [execution,machineStep,incrementProgram,workConfig,List.replicate_succ, + pairRegisters_b,pairRegisters_a _ _ _ hab,pairRegisters_update_b,pairRegisters_update_a _ _ _ hab] + rw [show 2*(m+1)+1=2+(2*m+1) by omega,execution_add,ht,ih,replicate_append_false] + congr 1 ; omega +def incrementBits (xs : List Bool) : List Bool := List.replicate (leadingOnes xs) false ++ carryTail xs +lemma incrementBits_correct (xs : List Bool) : binaryValue (incrementBits xs)=binaryValue xs+1 := by + induction xs with + | nil => simp [incrementBits,leadingOnes,carryTail,binaryValue] + | cons x xs ih => + cases x with + | false => simp [incrementBits,leadingOnes,carryTail,binaryValue,Nat.add_comm] + | true => + have he : incrementBits (true::xs)=false::incrementBits xs := by simp [incrementBits,leadingOnes,carryTail,List.replicate_succ] + rw [he,binaryValue,binaryValue,ih] + simp; omega + +theorem increment_block (a b : Fin (k+8)) (hab : a≠b) (O : IndependenceOracle n) + (R : Fin (k+8) → List Bool) (xs : List Bool) (q c : ℕ) (bits : ℕ → Bool) : + execution (incrementProgram a b) O (workConfig (pairRegisters R a b xs []) 0 q c) bits + (4*leadingOnes xs+3)= + workConfig (pairRegisters R a b (incrementBits xs) []) 5 q (c+4*leadingOnes xs+3) ∧ + 4*leadingOnes xs+3≤4*xs.length+3 ∧ binaryValue (incrementBits xs)=binaryValue xs+1 := by + refine ⟨?_,by have h := leadingOnes_le xs; omega,incrementBits_correct xs⟩ + rw [show 4*leadingOnes xs+3=(2*leadingOnes xs+2)+(2*leadingOnes xs+1) by omega,execution_add, + increment_carry a b hab] + simp only [List.append_nil] + rw [increment_restore a b hab] + simp only [incrementBits] + congr 1 ; omega + +end + +section + +variable {k s t n : ℕ} +def Instruction.relabel (e : Fin (s+1) → Fin (t+1)) : Instruction k s → Instruction k t + | .push i b j => .push i b (e j) + | .pop i x y z => .pop i (e x) (e y) (e z) + | .coin x y => .coin (e x) (e y) + | .query w i x y => .query w i (e x) (e y) + | .halt => .halt +def relabelConfig (e : Fin (s+1) → Fin (t+1)) (c : MachineConfig k s) : MachineConfig k t := + ⟨c.registers,e c.control,c.output,c.oracleCalls,c.bitOperations⟩ +lemma machineStep_relabel (P : Program k s) (Q : Program k t) (e : Fin (s+1) → Fin (t+1)) + (O : IndependenceOracle n) (b : Bool) (c : MachineConfig k s) + (h : Q (e c.control)=(P c.control).relabel e) : + machineStep Q O b (relabelConfig e c)=relabelConfig e (machineStep P O b c) := by + cases hc : c.output with + | some z => simp [machineStep,relabelConfig,hc] + | none => + cases hp : P c.control with + | push i b j => simp [machineStep,relabelConfig,hc,h,hp,Instruction.relabel] + | pop i x y z => + cases hl : c.registers i with + | nil => simp [machineStep,relabelConfig,hc,h,hp,Instruction.relabel,hl] + | cons a l => cases a <;> simp [machineStep,relabelConfig,hc,h,hp,Instruction.relabel,hl] + | coin x y => cases b <;> simp [machineStep,relabelConfig,hc,h,hp,Instruction.relabel] + | query w i x y => + by_cases hl : (c.registers i).length=n + · simp [machineStep,relabelConfig,hc,h,hp,Instruction.relabel,hl,apply_ite] + · simp [machineStep,relabelConfig,hc,h,hp,Instruction.relabel,hl] + | halt => simp [machineStep,relabelConfig,hc,h,hp,Instruction.relabel] +lemma machineStep_none_pre (P : Program k s) (O : IndependenceOracle n) (b : Bool) (c : MachineConfig k s) + (h : (machineStep P O b c).output=none) : c.output=none := by + cases hc : c.output with + | none => rfl + | some z => simp [machineStep,hc] at h +lemma machineStep_none_not_halt (P : Program k s) (O : IndependenceOracle n) (b : Bool) (c : MachineConfig k s) + (h : (machineStep P O b c).output=none) : P c.control≠.halt := by + have hc := machineStep_none_pre P O b c h + intro hh + simp [machineStep,hc,hh] at h +lemma execution_relabel (P : Program k s) (Q : Program k t) (e : Fin (s+1) → Fin (t+1)) + (h : ∀ i,Q (e i)=(P i).relabel e) (O : IndependenceOracle n) + (c : MachineConfig k s) (bits : ℕ → Bool) (u : ℕ) : + execution Q O (relabelConfig e c) bits u=relabelConfig e (execution P O c bits u) := by + induction u with + | zero => rfl + | succ u ih => + simp only [execution,ih] + exact machineStep_relabel P Q e O _ _ (h _) +lemma execution_relabel_before_halt (P : Program k s) (Q : Program k t) + (e : Fin (s+1) → Fin (t+1)) (exit : Fin (s+1)) (hexit : P exit=.halt) + (h : ∀ i,i≠exit → Q (e i)=(P i).relabel e) (O : IndependenceOracle n) + (c : MachineConfig k s) (bits : ℕ → Bool) (u : ℕ) + (hu : (execution P O c bits u).output=none) : + execution Q O (relabelConfig e c) bits u=relabelConfig e (execution P O c bits u) := by + induction u with + | zero => rfl + | succ u ih => + have hn := machineStep_none_pre P O (bits u) (execution P O c bits u) hu + have hh := machineStep_none_not_halt P O (bits u) (execution P O c bits u) hu + have he : (execution P O c bits u).control≠exit := by intro he; rw [he,hexit] at hh; exact hh rfl + simp only [execution,ih hn] + exact machineStep_relabel P Q e O _ _ (h _ he) +def firstLabel (s t : ℕ) (i : Fin (s+1)) : Fin (s+t+1) := ⟨i.val,by omega⟩ +def secondLabel (s t : ℕ) (i : Fin (t+1)) : Fin (s+t+1) := ⟨s+i.val,by omega⟩ +def lastLabel (s : ℕ) : Fin (s+1) := ⟨s,by omega⟩ + +def concatProgram (P : Program k s) (Q : Program k t) : Program k (s+t) := fun i => + if hi : i.val bits (u+i)) v) := by + rw [execution_add,concat_first_run P Q hexit O c bits u hu,link_exit _ hc, + concat_second_run] + +end + +section +variable {k n : ℕ} +def tripleRegisters (R : Fin (k+8) → List Bool) (a b d : Fin (k+8)) (xs ys zs : List Bool) := + Function.update (pairRegisters R a b xs ys) d zs +lemma tripleRegisters_a (R : Fin (k+8) → List Bool) (a b d : Fin (k+8)) + (hab : a≠b) (had : a≠d) (xs ys zs : List Bool) : tripleRegisters R a b d xs ys zs a=xs := by + simp [tripleRegisters,pairRegisters,hab,had] +lemma tripleRegisters_b (R : Fin (k+8) → List Bool) (a b d : Fin (k+8)) + (hbd : b≠d) (xs ys zs : List Bool) : tripleRegisters R a b d xs ys zs b=ys := by + simp [tripleRegisters,pairRegisters,hbd] +lemma tripleRegisters_d (R : Fin (k+8) → List Bool) (a b d : Fin (k+8)) + (xs ys zs : List Bool) : tripleRegisters R a b d xs ys zs d=zs := by + simp [tripleRegisters] +lemma tripleRegisters_update_a (R : Fin (k+8) → List Bool) (a b d : Fin (k+8)) + (hab : a≠b) (had : a≠d) (xs ys zs ws : List Bool) : + Function.update (tripleRegisters R a b d xs ys zs) a ws=tripleRegisters R a b d ws ys zs := by + funext i + by_cases ha : i=a + · subst i; simp [tripleRegisters,pairRegisters,hab,had] + · by_cases hb : i=b + · subst i; by_cases hbd : b=d <;> simp [tripleRegisters,pairRegisters,ha,hbd,Ne.symm had] + · by_cases hd : i=d + · subst i; simp [tripleRegisters,pairRegisters,ha] + · simp [tripleRegisters,pairRegisters,ha,hb,hd] +lemma tripleRegisters_update_b (R : Fin (k+8) → List Bool) (a b d : Fin (k+8)) + (hbd : b≠d) (xs ys zs ws : List Bool) : + Function.update (tripleRegisters R a b d xs ys zs) b ws=tripleRegisters R a b d xs ws zs := by + funext i + by_cases hb : i=b + · subst i; simp [tripleRegisters,pairRegisters,hbd] + · by_cases hd : i=d + · subst i; simp [tripleRegisters,pairRegisters,hb] + · simp [tripleRegisters,pairRegisters,hb,hd] +lemma tripleRegisters_update_d (R : Fin (k+8) → List Bool) (a b d : Fin (k+8)) + (xs ys zs ws : List Bool) : + Function.update (tripleRegisters R a b d xs ys zs) d ws=tripleRegisters R a b d xs ys ws := by + simp [tripleRegisters] +def copyConfig (R : Fin (k+8) → List Bool) (pc : Fin 9) (q c : ℕ) : MachineConfig k 8 := + ⟨R,pc,none,q,c⟩ +def copyProgram (a b d : Fin (k+8)) : Program k 8 := fun pc => + match pc.val with + | 0 => .pop a 3 1 2 + | 1 => .push b false 0 + | 2 => .push b true 0 + | 3 => .pop b 8 4 5 + | 4 => .push a false 6 + | 5 => .push a true 7 + | 6 => .push d false 3 + | 7 => .push d true 3 + | _ => .halt +lemma copy_scan (a b d : Fin (k+8)) (hab : a≠b) (had : a≠d) (hbd : b≠d) + (O : IndependenceOracle n) (R : Fin (k+8) → List Bool) (xs ys zs : List Bool) + (q c : ℕ) (bits : ℕ → Bool) : + execution (copyProgram a b d) O (copyConfig (tripleRegisters R a b d xs ys zs) 0 q c) bits + (2*xs.length+1)=copyConfig (tripleRegisters R a b d [] (xs.reverse++ys) zs) 3 q (c+2*xs.length+1) := by + induction xs generalizing ys c bits with + | nil => simp [execution,machineStep,copyProgram,copyConfig,tripleRegisters_a _ _ _ _ hab had] + | cons x xs ih => + have ht : execution (copyProgram a b d) O (copyConfig (tripleRegisters R a b d (x::xs) ys zs) 0 q c) bits 2= + copyConfig (tripleRegisters R a b d xs (x::ys) zs) 0 q (c+2) := by + cases x <;> simp [execution,machineStep,copyProgram,copyConfig,tripleRegisters_a _ _ _ _ hab had, + tripleRegisters_b _ _ _ _ hbd,tripleRegisters_update_a _ _ _ _ hab had,tripleRegisters_update_b _ _ _ _ hbd] + rw [List.length_cons,show 2*(xs.length+1)+1=2+(2*xs.length+1) by omega,execution_add,ht,ih] + simp only [List.reverse_cons,List.append_assoc,List.singleton_append] + congr 1 ; omega +lemma copy_restore (a b d : Fin (k+8)) (hab : a≠b) (had : a≠d) (hbd : b≠d) + (O : IndependenceOracle n) (R : Fin (k+8) → List Bool) (xs ys zs : List Bool) + (q c : ℕ) (bits : ℕ → Bool) : + execution (copyProgram a b d) O (copyConfig (tripleRegisters R a b d xs ys zs) 3 q c) bits + (3*ys.length+1)=copyConfig (tripleRegisters R a b d (ys.reverse++xs) [] (ys.reverse++zs)) 8 q (c+3*ys.length+1) := by + induction ys generalizing xs zs c bits with + | nil => simp [execution,machineStep,copyProgram,copyConfig,tripleRegisters_b _ _ _ _ hbd] + | cons y ys ih => + have ht : execution (copyProgram a b d) O (copyConfig (tripleRegisters R a b d xs (y::ys) zs) 3 q c) bits 3= + copyConfig (tripleRegisters R a b d (y::xs) ys (y::zs)) 3 q (c+3) := by + cases y <;> simp [execution,machineStep,copyProgram,copyConfig,tripleRegisters_a _ _ _ _ hab had, + tripleRegisters_b _ _ _ _ hbd,tripleRegisters_d,tripleRegisters_update_a _ _ _ _ hab had, + tripleRegisters_update_b _ _ _ _ hbd,tripleRegisters_update_d] + rw [List.length_cons,show 3*(ys.length+1)+1=3+(3*ys.length+1) by omega,execution_add,ht,ih] + simp only [List.reverse_cons,List.append_assoc,List.singleton_append] + congr 1 ; omega + +theorem copy_block (a b d : Fin (k+8)) (hab : a≠b) (had : a≠d) (hbd : b≠d) + (O : IndependenceOracle n) (R : Fin (k+8) → List Bool) (xs zs : List Bool) + (q c : ℕ) (bits : ℕ → Bool) : + execution (copyProgram a b d) O (copyConfig (tripleRegisters R a b d xs [] zs) 0 q c) bits + (5*xs.length+2)=copyConfig (tripleRegisters R a b d xs [] (xs++zs)) 8 q (c+5*xs.length+2) := by + rw [show 5*xs.length+2=(2*xs.length+1)+(3*xs.length+1) by omega,execution_add, + copy_scan a b d hab had hbd] + simp only [List.append_nil] + rw [←List.length_reverse (as:=xs),copy_restore a b d hab had hbd] + simp only [List.reverse_reverse,List.length_reverse,List.append_nil] + congr 1 ; omega + +def sumDigit (x y c : Bool) : Bool := xor (xor x y) c +def sumCarry (x y c : Bool) : Bool := (x && y) || (x && c) || (y && c) +def addDigits (c : Bool) (xs ys : List Bool) : List Bool := + match xs,ys with + | [],[] => if c then [true] else [] + | x::xs,[] => sumDigit x false c :: addDigits (sumCarry x false c) xs [] + | [],y::ys => sumDigit false y c :: addDigits (sumCarry false y c) [] ys + | x::xs,y::ys => sumDigit x y c :: addDigits (sumCarry x y c) xs ys +termination_by xs.length+ys.length +def addCost (c : Bool) (xs ys : List Bool) : ℕ := + match xs,ys with + | [],[] => if c then 3 else 2 + | x::xs,[] => 3+addCost (sumCarry x false c) xs [] + | [],y::ys => 3+addCost (sumCarry false y c) [] ys + | x::xs,y::ys => 3+addCost (sumCarry x y c) xs ys +termination_by xs.length+ys.length +lemma addDigits_value (c : Bool) (xs ys : List Bool) : + binaryValue (addDigits c xs ys)=binaryValue xs+binaryValue ys+(if c then 1 else 0) := by + induction xs generalizing ys c with + | nil => + induction ys generalizing c with + | nil => cases c <;> simp [addDigits,binaryValue] + | cons y ys ih => + simp only [addDigits,binaryValue,ih] + cases y <;> cases c <;> simp [sumDigit,sumCarry] <;> omega + | cons x xs ih => + cases ys with + | nil => + simp only [addDigits,binaryValue,ih] + cases x <;> cases c <;> simp [sumDigit,sumCarry] <;> omega + | cons y ys => + simp only [addDigits,binaryValue,ih] + cases x <;> cases y <;> cases c <;> simp [sumDigit,sumCarry] <;> omega +lemma addDigits_length_cost (c : Bool) (xs ys : List Bool) : + (addDigits c xs ys).length≤xs.length+ys.length+1 ∧ + addCost c xs ys≤3*(xs.length+ys.length)+3 := by + induction xs generalizing ys c with + | nil => + induction ys generalizing c with + | nil => cases c <;> simp [addDigits,addCost] + | cons y ys ih => + have hi := ih (sumCarry false y c) + simp only [addDigits,addCost,List.length_cons,List.length_nil] at * + constructor <;> omega + | cons x xs ih => + cases ys with + | nil => + have hi := ih (sumCarry x false c) [] + simp only [addDigits,addCost,List.length_cons,List.length_nil] at * + constructor <;> omega + | cons y ys => + have hi := ih (sumCarry x y c) ys + simp only [addDigits,addCost,List.length_cons] at * + constructor <;> omega + +def addConfig (R : Fin (k+8) → List Bool) (pc : Fin 17) (q c : ℕ) : MachineConfig k 16 := + ⟨R,pc,none,q,c⟩ +def addProgram (a b d : Fin (k+8)) : Program k 16 := fun pc => + match pc.val with + | 0 => .pop a 2 3 4 + | 1 => .pop a 5 6 7 + | 2 => .pop b 12 8 9 + | 3 => .pop b 8 8 9 + | 4 => .pop b 9 9 10 + | 5 => .pop b 13 9 10 + | 6 => .pop b 9 9 10 + | 7 => .pop b 10 10 11 + | 8 => .push d false 0 + | 9 => .push d true 0 + | 10 => .push d false 1 + | 11 => .push d true 1 + | 12 => .pop d 16 14 15 + | 13 => .push d true 12 + | 14 => .push a false 12 + | 15 => .push a true 12 + | _ => .halt +lemma add_build (a b d : Fin (k+8)) (hab : a≠b) (had : a≠d) (hbd : b≠d) + (O : IndependenceOracle n) (R : Fin (k+8) → List Bool) (xs ys zs : List Bool) + (carry : Bool) (q c : ℕ) (bits : ℕ → Bool) : + execution (addProgram a b d) O + (addConfig (tripleRegisters R a b d xs ys zs) (if carry then 1 else 0) q c) bits + (addCost carry xs ys)=addConfig + (tripleRegisters R a b d [] [] ((addDigits carry xs ys).reverse++zs)) 12 q (c+addCost carry xs ys) := by + induction xs generalizing ys zs carry c bits with + | nil => + induction ys generalizing zs carry c bits with + | nil => + cases carry <;> simp [addCost,addDigits,execution,machineStep,addProgram,addConfig, + tripleRegisters_a _ _ _ _ hab had,tripleRegisters_b _ _ _ _ hbd,tripleRegisters_d, + tripleRegisters_update_d] + | cons y ys ih => + have ht : execution (addProgram a b d) O + (addConfig (tripleRegisters R a b d [] (y::ys) zs) (if carry then 1 else 0) q c) bits 3= + addConfig (tripleRegisters R a b d [] ys (sumDigit false y carry::zs)) + (if sumCarry false y carry then 1 else 0) q (c+3) := by + cases y <;> cases carry <;> simp [execution,machineStep,addProgram,addConfig,sumDigit,sumCarry, + tripleRegisters_a _ _ _ _ hab had,tripleRegisters_b _ _ _ _ hbd,tripleRegisters_d, + tripleRegisters_update_b _ _ _ _ hbd,tripleRegisters_update_d] + rw [addCost,execution_add,ht,ih] + simp only [addDigits,List.reverse_cons,List.append_assoc,List.singleton_append] + congr 1 ; omega + | cons x xs ih => + cases ys with + | nil => + have ht : execution (addProgram a b d) O + (addConfig (tripleRegisters R a b d (x::xs) [] zs) (if carry then 1 else 0) q c) bits 3= + addConfig (tripleRegisters R a b d xs [] (sumDigit x false carry::zs)) + (if sumCarry x false carry then 1 else 0) q (c+3) := by + cases x <;> cases carry <;> simp [execution,machineStep,addProgram,addConfig,sumDigit,sumCarry, + tripleRegisters_a _ _ _ _ hab had,tripleRegisters_b _ _ _ _ hbd,tripleRegisters_d, + tripleRegisters_update_a _ _ _ _ hab had,tripleRegisters_update_d] + rw [addCost,execution_add,ht,ih] + simp only [addDigits,List.reverse_cons,List.append_assoc,List.singleton_append] + congr 1 ; omega + | cons y ys => + have ht : execution (addProgram a b d) O + (addConfig (tripleRegisters R a b d (x::xs) (y::ys) zs) (if carry then 1 else 0) q c) bits 3= + addConfig (tripleRegisters R a b d xs ys (sumDigit x y carry::zs)) + (if sumCarry x y carry then 1 else 0) q (c+3) := by + cases x <;> cases y <;> cases carry <;> simp [execution,machineStep,addProgram,addConfig,sumDigit,sumCarry, + tripleRegisters_a _ _ _ _ hab had,tripleRegisters_b _ _ _ _ hbd,tripleRegisters_d, + tripleRegisters_update_a _ _ _ _ hab had,tripleRegisters_update_b _ _ _ _ hbd, + tripleRegisters_update_d] + rw [addCost,execution_add,ht,ih] + simp only [addDigits,List.reverse_cons,List.append_assoc,List.singleton_append] + congr 1 ; omega +lemma add_restore (a b d : Fin (k+8)) (hab : a≠b) (had : a≠d) (_ : b≠d) + (O : IndependenceOracle n) (R : Fin (k+8) → List Bool) (xs ys zs : List Bool) + (q c : ℕ) (bits : ℕ → Bool) : + execution (addProgram a b d) O (addConfig (tripleRegisters R a b d xs ys zs) 12 q c) bits + (2*zs.length+1)=addConfig (tripleRegisters R a b d (zs.reverse++xs) ys []) 16 q (c+2*zs.length+1) := by + induction zs generalizing xs c bits with + | nil => simp [execution,machineStep,addProgram,addConfig,tripleRegisters_d] + | cons z zs ih => + have ht : execution (addProgram a b d) O (addConfig (tripleRegisters R a b d xs ys (z::zs)) 12 q c) bits 2= + addConfig (tripleRegisters R a b d (z::xs) ys zs) 12 q (c+2) := by + cases z <;> simp [execution,machineStep,addProgram,addConfig,tripleRegisters_a _ _ _ _ hab had, + tripleRegisters_d,tripleRegisters_update_a _ _ _ _ hab had,tripleRegisters_update_d] + rw [List.length_cons,show 2*(zs.length+1)+1=2+(2*zs.length+1) by omega,execution_add,ht,ih] + simp only [List.reverse_cons,List.append_assoc,List.singleton_append] + congr 1 ; omega + +theorem addition_block (a b d : Fin (k+8)) (hab : a≠b) (had : a≠d) (hbd : b≠d) + (O : IndependenceOracle n) (R : Fin (k+8) → List Bool) (xs ys : List Bool) + (q c : ℕ) (bits : ℕ → Bool) : + let z := addDigits false xs ys + let t := addCost false xs ys+2*z.length+1 + binaryValue z=binaryValue xs+binaryValue ys ∧ t≤5*(xs.length+ys.length)+6 ∧ + execution (addProgram a b d) O (addConfig (tripleRegisters R a b d xs ys []) 0 q c) bits t= + addConfig (tripleRegisters R a b d z [] []) 16 q (c+t) := by + dsimp only + refine ⟨by simpa using addDigits_value false xs ys,?_,?_⟩ + · have h := addDigits_length_cost false xs ys + omega + · rw [show addCost false xs ys+2*(addDigits false xs ys).length+1= + addCost false xs ys+(2*(addDigits false xs ys).length+1) by omega,execution_add] + rw [show (0 : Fin 17)=(if false then 1 else 0) by rfl,add_build a b d hab had hbd] + simp only [List.append_nil] + rw [←List.length_reverse (as:=addDigits false xs ys),add_restore a b d hab had hbd] + simp only [List.reverse_reverse,List.length_reverse,List.append_nil] + congr 1 ; omega + +lemma addDigits_length_max (c : Bool) (xs ys : List Bool) : + (addDigits c xs ys).length≤ max xs.length ys.length+1 := by + induction xs generalizing c ys with + | nil => + induction ys generalizing c with + | nil => cases c <;> simp [addDigits] + | cons y ys ih => + have h := ih (sumCarry false y c) + simp only [addDigits,List.length_cons,List.length_nil,Nat.zero_max] at * + omega + | cons x xs ih => + cases ys with + | nil => + have h := ih (sumCarry x false c) [] + simp only [addDigits,List.length_cons,List.length_nil,Nat.max_zero] at * + omega + | cons y ys => + have h := ih (sumCarry x y c) ys + simp only [addDigits,List.length_cons] at * + omega + +lemma workReg_ne {a b : ℕ} (ha : a if i=0 then xs else if i=1 then ys else if i=2 then zs + else if i=3 then [] else if i=4 then ws else R i +lemma mulRegisters_copy_in (R : Fin (k+8) → List Bool) (xs ys zs : List Bool) : + tripleRegisters (mulRegisters R xs ys zs []) 0 3 4 xs [] []=mulRegisters R xs ys zs [] := by + funext i + by_cases h0 : i=0 <;> by_cases h3 : i=3 <;> by_cases h4 : i=4 <;> + simp_all [tripleRegisters,pairRegisters,mulRegisters] +lemma mulRegisters_copy_out (R : Fin (k+8) → List Bool) (xs ys zs : List Bool) : + tripleRegisters (mulRegisters R xs ys zs []) 0 3 4 xs [] xs=mulRegisters R xs ys zs xs := by + funext i + by_cases h0 : i=0 <;> by_cases h3 : i=3 <;> by_cases h4 : i=4 <;> + simp_all [tripleRegisters,pairRegisters,mulRegisters] +lemma mulRegisters_add_in (R : Fin (k+8) → List Bool) (xs ys zs : List Bool) : + tripleRegisters (mulRegisters R xs ys zs xs) 2 4 3 zs xs []=mulRegisters R xs ys zs xs := by + funext i + by_cases h2 : i=2 <;> by_cases h3 : i=3 <;> by_cases h4 : i=4 <;> + simp_all [tripleRegisters,pairRegisters,mulRegisters] +lemma mulRegisters_add_out (R : Fin (k+8) → List Bool) (xs ys zs us : List Bool) : + tripleRegisters (mulRegisters R xs ys zs xs) 2 4 3 us [] []=mulRegisters R xs ys us [] := by + funext i + by_cases h2 : i=2 <;> by_cases h3 : i=3 <;> by_cases h4 : i=4 <;> + simp_all [tripleRegisters,pairRegisters,mulRegisters] +lemma mulRegisters_update0 (R : Fin (k+8) → List Bool) (xs ys zs ws us : List Bool) : + Function.update (mulRegisters R xs ys zs ws) 0 us=mulRegisters R us ys zs ws := by + funext i + by_cases h0 : i=0 <;> simp [mulRegisters,h0] +lemma mulRegisters_update1 (R : Fin (k+8) → List Bool) (xs ys zs ws us : List Bool) : + Function.update (mulRegisters R xs ys zs ws) 1 us=mulRegisters R xs us zs ws := by + funext i + by_cases h0 : i=0 <;> by_cases h1 : i=1 <;> simp_all [mulRegisters] + +def mulBody : Program k 24 := concatProgram (copyProgram 0 3 4) (addProgram 2 4 3) +def mulBodyConfig (R : Fin (k+8) → List Bool) (pc : Fin 25) (q c : ℕ) : MachineConfig k 24 := + ⟨R,pc,none,q,c⟩ +def mulBodyCost (xs zs : List Bool) : ℕ := + (5*xs.length+2)+(addCost false zs xs+2*(addDigits false zs xs).length+1) +lemma mulBody_exit : (mulBody : Program k 24) (lastLabel 24)=.halt := by + simp [mulBody,concatProgram,lastLabel,addProgram,Instruction.relabel] +lemma mulBody_run (O : IndependenceOracle n) (R : Fin (k+8) → List Bool) + (xs ys zs : List Bool) (q c : ℕ) (bits : ℕ → Bool) : + execution mulBody O (mulBodyConfig (mulRegisters R xs ys zs []) 0 q c) bits (mulBodyCost xs zs)= + mulBodyConfig (mulRegisters R xs ys (addDigits false zs xs) []) 24 q (c+mulBodyCost xs zs) := by + have hc := copy_block (k:=k) (0 : Fin (k+8)) 3 4 (by simp) (by simp) (by simp) + O (mulRegisters R xs ys zs []) xs [] q c bits + simp only [List.append_nil,mulRegisters_copy_in,mulRegisters_copy_out] at hc + have ha := (addition_block (k:=k) (2 : Fin (k+8)) 4 3 (by simp) (by simp) (by simp) + O (mulRegisters R xs ys zs xs) zs xs q (c+(5*xs.length+2)) + (fun i => bits (5*xs.length+2+i))).2.2 + simp only [mulRegisters_add_in,mulRegisters_add_out] at ha + have hh := concat_run (copyProgram (k:=k) 0 3 4) (addProgram 2 4 3) + (by rfl) O (copyConfig (mulRegisters R xs ys zs []) 0 q c) bits (5*xs.length+2) + (addCost false zs xs+2*(addDigits false zs xs).length+1) + (by rw [hc]; rfl) (by rw [hc]; rfl) + rw [hc] at hh + have hre : restartControl (copyConfig (mulRegisters R xs ys zs xs) 8 q (c+5*xs.length+2)) + (0 : Fin 17)=addConfig (mulRegisters R xs ys zs xs) 0 q (c+(5*xs.length+2)) := by + simp [restartControl,copyConfig,addConfig,Nat.add_assoc] + rw [hre,ha] at hh + simpa [mulBody,mulBodyCost,mulBodyConfig,copyConfig,addConfig,relabelConfig,firstLabel,secondLabel, + Nat.add_assoc] using hh +lemma mulBodyCost_bound (xs zs : List Bool) : + mulBodyCost xs zs≤15*max xs.length zs.length+8 := by + have h := addDigits_length_cost false zs xs + unfold mulBodyCost + have hx : xs.length≤ max xs.length zs.length := Nat.le_max_left _ _ + have hz : zs.length≤ max xs.length zs.length := Nat.le_max_right _ _ + omega + +def mulBodyLabel (i : Fin 25) : Fin 27 := ⟨i.val+1,by omega⟩ +def mulProgram : Program k 26 := fun i => + if hi : i.val=0 then .pop 1 26 25 1 + else if hj : i.val<25 then + ((mulBody : Program k 24) ⟨i.val-1,by omega⟩).relabel mulBodyLabel + else if i.val=25 then .push 0 false 0 else .halt +def mulConfig (R : Fin (k+8) → List Bool) (pc : Fin 27) (q c : ℕ) : MachineConfig k 26 := + ⟨R,pc,none,q,c⟩ +lemma mulProgram_body (i : Fin 25) (hi : i≠lastLabel 24) : + (mulProgram : Program k 26) (mulBodyLabel i)=((mulBody : Program k 24) i).relabel mulBodyLabel := by + have h : i.val<24 := by + have hh : i.val≠24 := by intro hh; apply hi; exact Fin.ext hh + omega + simp [mulProgram,mulBodyLabel,show i.val+1<25 by omega] +lemma mulProgram_body_run (O : IndependenceOracle n) (R : Fin (k+8) → List Bool) + (xs ys zs : List Bool) (q c : ℕ) (bits : ℕ → Bool) : + execution mulProgram O (mulConfig (mulRegisters R xs ys zs []) 1 q c) bits (mulBodyCost xs zs)= + mulConfig (mulRegisters R xs ys (addDigits false zs xs) []) 25 q (c+mulBodyCost xs zs) := by + have h := execution_relabel_before_halt (mulBody : Program k 24) mulProgram mulBodyLabel + (lastLabel 24) mulBody_exit mulProgram_body O + (mulBodyConfig (mulRegisters R xs ys zs []) 0 q c) bits (mulBodyCost xs zs) + (by rw [mulBody_run]; rfl) + rw [mulBody_run] at h + simpa [relabelConfig,mulBodyConfig,mulConfig,mulBodyLabel] using h + +def mulDigits (xs ys zs : List Bool) : List Bool := + match ys with + | [] => zs + | bit::ys => mulDigits (false::xs) ys (if bit then addDigits false zs xs else zs) +def mulCost (xs ys zs : List Bool) : ℕ := + match ys with + | [] => 1 + | bit::ys => 2+(if bit then mulBodyCost xs zs else 0)+ + mulCost (false::xs) ys (if bit then addDigits false zs xs else zs) +lemma mulDigits_value (xs ys zs : List Bool) : + binaryValue (mulDigits xs ys zs)=binaryValue zs+binaryValue xs*binaryValue ys := by + induction ys generalizing xs zs with + | nil => simp [mulDigits,binaryValue] + | cons bit ys ih => + simp only [mulDigits,ih] + cases bit <;> simp [binaryValue,addDigits_value] <;> ring +lemma mulDigits_length (xs ys zs : List Bool) : + (mulDigits xs ys zs).length≤ max xs.length zs.length+ys.length := by + induction ys generalizing xs zs with + | nil => simp [mulDigits] + | cons bit ys ih => + have h1 := ih (false::xs) (if bit then addDigits false zs xs else zs) + have h2 := addDigits_length_max false zs xs + cases bit <;> simp only [mulDigits,Bool.false_eq_true,ite_false,ite_true,List.length_cons] at * <;> omega +lemma mulCost_bound (xs ys zs : List Bool) : + mulCost xs ys zs≤(15*(max xs.length zs.length+ys.length)+10)*ys.length+1 := by + induction ys generalizing xs zs with + | nil => simp [mulCost] + | cons bit ys ih => + have h1 := ih (false::xs) (if bit then addDigits false zs xs else zs) + have h2 := addDigits_length_max false zs xs + have h3 := mulBodyCost_bound xs zs + have hz : (if bit then addDigits false zs xs else zs).length≤ max xs.length zs.length+1 := by + cases bit <;> simp only [Bool.false_eq_true,ite_false,ite_true] <;> omega + have hh : max (false::xs).length (if bit then addDigits false zs xs else zs).length≤ + max xs.length zs.length+1 := by simp only [List.length_cons]; omega + have hm : (15*(max (false::xs).length (if bit then addDigits false zs xs else zs).length+ys.length)+10)*ys.length≤ + (15*(max xs.length zs.length+1+ys.length)+10)*ys.length := + Nat.mul_le_mul_right _ (by omega) + cases bit <;> simp only [mulCost,Bool.false_eq_true,ite_false,ite_true,List.length_cons] at * <;> nlinarith +lemma mul_run (O : IndependenceOracle n) (R : Fin (k+8) → List Bool) + (xs ys zs : List Bool) (q c : ℕ) (bits : ℕ → Bool) : + execution mulProgram O (mulConfig (mulRegisters R xs ys zs []) 0 q c) bits (mulCost xs ys zs)= + mulConfig (mulRegisters R (List.replicate ys.length false++xs) [] (mulDigits xs ys zs) []) + 26 q (c+mulCost xs ys zs) := by + induction ys generalizing xs zs c bits with + | nil => simp [mulCost,mulDigits,execution,machineStep,mulProgram,mulConfig,mulRegisters] + | cons bit ys ih => + have hpop : execution mulProgram O (mulConfig (mulRegisters R xs (bit::ys) zs []) 0 q c) bits 1= + mulConfig (mulRegisters R xs ys zs []) (if bit then 1 else 25) q (c+1) := by + cases bit <;> simp [execution,machineStep,mulProgram,mulConfig,mulRegisters_update1,mulRegisters] + have hshift (us : List Bool) (c' : ℕ) (bits' : ℕ → Bool) : + execution mulProgram O (mulConfig (mulRegisters R xs ys us []) 25 q c') bits' 1= + mulConfig (mulRegisters R (false::xs) ys us []) 0 q (c'+1) := by + simp [execution,machineStep,mulProgram,mulConfig,mulRegisters_update0,mulRegisters] + have hbody : execution mulProgram O (mulConfig (mulRegisters R xs (bit::ys) zs []) 0 q c) bits + (2+(if bit then mulBodyCost xs zs else 0))= + mulConfig (mulRegisters R (false::xs) ys (if bit then addDigits false zs xs else zs) []) 0 q + (c+(2+(if bit then mulBodyCost xs zs else 0))) := by + cases bit with + | false => + simp only [Bool.false_eq_true,ite_false,Nat.add_zero] + rw [show 2=1+1 by rfl,execution_add,hpop] + simp only [Bool.false_eq_true,ite_false] + rw [hshift] + | true => + simp only [ite_true] + rw [show 2+mulBodyCost xs zs=1+(mulBodyCost xs zs+1) by omega, + execution_add,hpop] + simp only [ite_true] + rw [execution_add,mulProgram_body_run,hshift] + try (congr 1 ; omega) + rw [mulCost,execution_add,hbody,ih] + simp only [mulDigits,List.length_cons,List.replicate_add,List.replicate_one,List.append_assoc,List.singleton_append] + congr 1 ; omega + +theorem multiplication_block (O : IndependenceOracle n) (R : Fin (k+8) → List Bool) + (xs ys : List Bool) (q c : ℕ) (bits : ℕ → Bool) : + let z := mulDigits xs ys [] + let t := mulCost xs ys [] + binaryValue z=binaryValue xs*binaryValue ys ∧ + t≤(15*(xs.length+ys.length)+10)*ys.length+1 ∧ + execution mulProgram O (mulConfig (mulRegisters R xs ys [] []) 0 q c) bits t= + mulConfig (mulRegisters R (List.replicate ys.length false++xs) [] z []) 26 q (c+t) := by + refine ⟨by simp [mulDigits_value,binaryValue],?_,mul_run O R xs ys [] q c bits⟩ + simpa using mulCost_bound xs ys [] + +def coinWord : ℕ → (ℕ → Bool) → List Bool + | 0,_ => [] + | m+1,bits => bits 1::coinWord m (fun i => bits (3+i)) +lemma coinWord_length (m : ℕ) (bits : ℕ → Bool) : (coinWord m bits).length=m := by + induction m generalizing bits with + | zero => rfl + | succ m ih => simp [coinWord,ih] +lemma coinWord_ofFn (m : ℕ) (bits : ℕ → Bool) : + coinWord m bits=List.ofFn (fun i : Fin m => bits (3*i.val+1)) := by + induction m generalizing bits with + | zero => simp [coinWord] + | succ m ih => + rw [coinWord,ih,List.ofFn_succ] + simp only [Fin.val_zero,Nat.mul_zero,Nat.zero_add,Fin.val_succ] + congr 2 + funext i + congr 1 ; omega + +def randomConfig (R : Fin (k+8) → List Bool) (pc : Fin 5) (q c : ℕ) : MachineConfig k 4 := + ⟨R,pc,none,q,c⟩ +def randomProgram (counter dest : Fin (k+8)) : Program k 4 := fun pc => + match pc.val with + | 0 => .pop counter 4 1 1 + | 1 => .coin 2 3 + | 2 => .push dest false 0 + | 3 => .push dest true 0 + | _ => .halt + +theorem random_bank_block (a b : Fin (k+8)) (hab : a≠b) (O : IndependenceOracle n) + (R : Fin (k+8) → List Bool) (xs ys : List Bool) (q c : ℕ) (bits : ℕ → Bool) : + execution (randomProgram a b) O (randomConfig (pairRegisters R a b xs ys) 0 q c) bits (3*xs.length+1)= + randomConfig (pairRegisters R a b [] ((coinWord xs.length bits).reverse++ys)) 4 q (c+3*xs.length+1) := by + induction xs generalizing ys c bits with + | nil => simp [execution,machineStep,randomProgram,randomConfig,pairRegisters_a _ _ _ hab,coinWord] + | cons x xs ih => + have ht : execution (randomProgram a b) O (randomConfig (pairRegisters R a b (x::xs) ys) 0 q c) bits 3= + randomConfig (pairRegisters R a b xs (bits 1::ys)) 0 q (c+3) := by + cases x <;> cases hb : bits 1 <;> + simp [execution,machineStep,randomProgram,randomConfig,pairRegisters_a _ _ _ hab, + pairRegisters_b,pairRegisters_update_a _ _ _ hab,pairRegisters_update_b,hb] + rw [List.length_cons,show 3*(xs.length+1)+1=3+(3*xs.length+1) by omega,execution_add,ht,ih] + simp only [coinWord,List.reverse_cons,List.append_assoc,List.singleton_append] + congr 1 ; omega + +end + +lemma bitResourceParameter_le_target (n r : ℕ) (ε δ : ℚ) : + bitResourceParameter n ε δ≤1+n+inputLength n r ε δ+⌈ε⁻¹⌉₊+Nat.clog 2 ⌈δ⁻¹⌉₊ := by + unfold bitResourceParameter inputLength + omega +lemma fairBitCount_le_target (n r : ℕ) (ε δ : ℚ) : + fairBitCount n ε δ≤resourceBound (10^66) 73 n r ε δ := by + have h := fairBitCount_polynomial n ε δ + exact h.trans (Nat.mul_le_mul_left _ (Nat.pow_le_pow_left (bitResourceParameter_le_target n r ε δ) _)) +lemma queryCount_le_target (n r : ℕ) (ε δ : ℚ) : + 10^31*(bitResourceParameter n ε δ)^30≤resourceBound (10^66) 73 n r ε δ := by + have ha := bitResourceParameter_le_target n r ε δ + have hb : 1≤1+n+inputLength n r ε δ+⌈ε⁻¹⌉₊+Nat.clog 2 ⌈δ⁻¹⌉₊ := by omega + unfold resourceBound + apply Nat.mul_le_mul (by norm_num : (10:ℕ)^31≤10^66) + exact (Nat.pow_le_pow_left ha 30).trans (Nat.pow_le_pow_right hb (by decide : 30≤73)) + +theorem query_experiment_target_scale (n r : ℕ) (O : IndependenceOracle n) + (M₁ M₂ : Matroid (Fin n)) (hO : ExactOracles M₁ M₂ O) + (hE₁ : M₁.E=Set.univ) (hE₂ : M₂.E=Set.univ) + (hr₁ : M₁.eRank=(r:ℕ∞)) (hr₂ : M₂.eRank=(r:ℕ∞)) + (ε δ : ℚ) (hε0 : 0<ε) (hε1 : ε<1) (hδ : 0<δ) : + let B := resourceBound (10^66) 73 n r ε δ + let out := paddedQueryOutput n r O ε δ B (fairBitCount_le_target n r ε δ) + (∀ bits,0≤(out bits).1 ∧ (commonBaseCount M₁ M₂=0 → (out bits).1=0) ∧ (out bits).2≤B) ∧ + (1-δ)*(2:ℚ)^B≤(Nat.card {bits : BitWord B // + relativeAccuracy ε (commonBaseCount M₁ M₂) (out bits).1}:ℚ) := by + dsimp only + have h := query_fair_experiment n r O M₁ M₂ hO hE₁ hE₂ hr₁ hr₂ ε δ hε0 hε1 hδ + (resourceBound (10^66) 73 n r ε δ) (fairBitCount_le_target n r ε δ) + refine ⟨?_,h.2⟩ + intro bits + exact ⟨(h.1 bits).1,(h.1 bits).2.1,(h.1 bits).2.2.trans (queryCount_le_target n r ε δ)⟩ + +open scoped Classical +lemma uniformAverage_bitEmbedding (m B : ℕ) (f : Fin m → Fin B) + (hf : Function.Injective f) (φ : BitWord m → ℝ) : + uniformAverage (fun w : BitWord B => φ (fun i => w (f i)))=uniformAverage φ := by + have hm : m≤B := by simpa using Fintype.card_le_of_injective f hf + let g : Fin m → Fin B := fun i => ⟨i.val,lt_of_lt_of_le i.isLt hm⟩ + have hg : Function.Injective g := by + intro i j h + apply Fin.ext + exact congrArg (fun x : Fin B => x.val) h + obtain ⟨σ,hσ⟩ := Equiv.Perm.exists_extending_pair g f hg hf + let e : BitWord B ≃ BitWord B := Equiv.arrowCongr σ.symm (Equiv.refl Bool) + have he (w : BitWord B) : (fun i => w (f i))=bitPrefix m B hm (e w) := by + funext i + change w (f i)=w (σ (g i)) + rw [hσ] + simp_rw [he] + rw [uniformAverage_equiv e (fun w => φ (bitPrefix m B hm w))] + exact uniformAverage_bitPrefix m B hm φ + +def clockPosition (start m B : ℕ) (h : start+3*m+1≤B) (i : Fin m) : Fin B := + ⟨start+3*i.val+1,by have hi:=i.isLt; omega⟩ +lemma clockPosition_injective (start m B : ℕ) (h : start+3*m+1≤B) : + Function.Injective (clockPosition start m B h) := by + intro i j hij + have hh := congrArg Fin.val hij + dsimp only [clockPosition] at hh + apply Fin.ext + omega +def clockWord (start m B : ℕ) (h : start+3*m+1≤B) (w : BitWord B) : BitWord m := + fun i => w (clockPosition start m B h i) +lemma clockWord_law (start m B : ℕ) (h : start+3*m+1≤B) (φ : BitWord m → ℝ) : + uniformAverage (fun w : BitWord B => φ (clockWord start m B h w))=uniformAverage φ := + uniformAverage_bitEmbedding m B _ (clockPosition_injective start m B h) φ +noncomputable def clockQueryOutput (n r : ℕ) (O : IndependenceOracle n) (ε δ : ℚ) + (start B : ℕ) (h : start+3*fairBitCount n ε δ+1≤B) (w : BitWord B) : ℚ × ℕ := + queryBoundedOutput n r O ε δ (bankWordEquiv n ε δ (clockWord start _ B h w)) +lemma clockQueryOutput_value (n r : ℕ) (O : IndependenceOracle n) (ε δ : ℚ) + (start B : ℕ) (h : start+3*fairBitCount n ε δ+1≤B) (w : BitWord B) : + (clockQueryOutput n r O ε δ start B h w).1= + flatFPRASOutput n r O ε δ (clockWord start _ B h w) := + queryBoundedOutput_value n r O ε δ _ +lemma clockQueryOutput_law (n r : ℕ) (O : IndependenceOracle n) (ε δ : ℚ) + (start B : ℕ) (h : start+3*fairBitCount n ε δ+1≤B) (φ : ℚ → ℝ) : + uniformAverage (fun w : BitWord B => φ (clockQueryOutput n r O ε δ start B h w).1)= + uniformAverage (fun w : FPRASBank n ε δ => φ (canonicalBoundedOutput n r O ε δ w)) := by + simp_rw [clockQueryOutput_value] + rw [clockWord_law start _ B h (fun w => φ (flatFPRASOutput n r O ε δ w))] + exact uniformAverage_equiv (bankWordEquiv n ε δ) + (fun w : FPRASBank n ε δ => φ (canonicalBoundedOutput n r O ε δ w)) + +theorem clock_query_experiment (n r : ℕ) (O : IndependenceOracle n) + (M₁ M₂ : Matroid (Fin n)) (hO : ExactOracles M₁ M₂ O) + (hE₁ : M₁.E=Set.univ) (hE₂ : M₂.E=Set.univ) + (hr₁ : M₁.eRank=(r:ℕ∞)) (hr₂ : M₂.eRank=(r:ℕ∞)) + (ε δ : ℚ) (hε0 : 0<ε) (hε1 : ε<1) (hδ : 0<δ) + (start B : ℕ) (hB : start+3*fairBitCount n ε δ+1≤B) : + (∀ bits : BitWord B, + let out := clockQueryOutput n r O ε δ start B hB bits + 0≤out.1 ∧ (commonBaseCount M₁ M₂=0 → out.1=0) ∧ + out.2≤10^31*(bitResourceParameter n ε δ)^30) ∧ + (1-δ)*(2:ℚ)^B≤(Nat.card {bits : BitWord B // + relativeAccuracy ε (commonBaseCount M₁ M₂) (clockQueryOutput n r O ε δ start B hB bits).1}:ℚ) := by + have hf := canonical_bounded_fair_experiment n r O M₁ M₂ hO hE₁ hE₂ hr₁ hr₂ ε δ hε0 hε1 hδ + constructor + · intro bits + refine ⟨?_,?_,queryBoundedOutput_queries n r O ε δ _⟩ + · exact (hf.1 _).1.trans_eq (queryBoundedOutput_value n r O ε δ _).symm + · intro hZ + exact (queryBoundedOutput_value n r O ε δ _).trans ((hf.1 _).2 hZ) + · have h := hf.2 + rw [←clockQueryOutput_law n r O ε δ start B hB + (fun z => if relativeAccuracy ε (commonBaseCount M₁ M₂) z then (1:ℝ) else 0)] at h + rw [uniformAverage_indicator_card] at h + have hcard : Fintype.card (BitWord B)=2^B := by simp [BitWord] + rw [hcard,Nat.cast_pow,Nat.cast_ofNat] at h + have hh := (le_div_iff₀ (by positivity : (0:ℝ)<2^B)).mp h + exact_mod_cast hh + +section + +variable {k n : ℕ} +def wordOracle (which : Bool) (O : IndependenceOracle n) (l : List Bool) : Bool := + O which (fun i => l[i.val]?.getD false) +def wordGreedy (W : List Bool → Bool) : List Bool → List Bool → List Bool + | [],ps => ps + | b::xs,ps => wordGreedy W xs ((b && W (List.replicate xs.length false++true::ps))::ps) +def greedyTime (n : ℕ) : List Bool → ℕ + | [] => 1 + | b::xs => (if b then 6*n+5 else 3)+greedyTime n xs +def greedyWork (n : ℕ) : List Bool → ℕ + | [] => 1 + | b::xs => (if b then 8*n+5 else 3)+greedyWork n xs +def greedyCalls : List Bool → ℕ + | [] => 0 + | b::xs => (if b then 1 else 0)+greedyCalls xs +lemma greedyTime_bound (n : ℕ) (xs : List Bool) : greedyTime n xs≤(6*n+5)*xs.length+1 := by + induction xs with + | nil => simp [greedyTime] + | cons b xs ih => cases b <;> simp only [greedyTime,List.length_cons,Bool.false_eq_true,ite_false,ite_true] <;> nlinarith +lemma greedyWork_bound (n : ℕ) (xs : List Bool) : greedyWork n xs≤(8*n+5)*xs.length+1 := by + induction xs with + | nil => simp [greedyWork] + | cons b xs ih => cases b <;> simp only [greedyWork,List.length_cons,Bool.false_eq_true,ite_false,ite_true] <;> nlinarith +lemma greedyCalls_bound (xs : List Bool) : greedyCalls xs≤xs.length := by + induction xs with + | nil => simp [greedyCalls] + | cons b xs ih => cases b <;> simp_all [greedyCalls] <;> omega +lemma wordGreedy_length (W : List Bool → Bool) (xs ps : List Bool) : + (wordGreedy W xs ps).length=xs.length+ps.length := by + induction xs generalizing ps with + | nil => simp [wordGreedy] + | cons b xs ih => simp [wordGreedy,ih,Nat.add_comm,Nat.add_left_comm] + +def greedyRegisters (R : Fin (k+8) → List Bool) (xs zs ps qs : List Bool) : Fin (k+8) → List Bool := + fun i => if i=0 then xs else if i=1 then zs else if i=2 then ps else if i=3 then [] else if i=4 then qs else R i +lemma greedyRegisters_update0 (R : Fin (k+8) → List Bool) (xs zs ps qs us : List Bool) : + Function.update (greedyRegisters R xs zs ps qs) 0 us=greedyRegisters R us zs ps qs := by + funext i; by_cases h : i=0 <;> simp_all [greedyRegisters] +lemma greedyRegisters_update1 (R : Fin (k+8) → List Bool) (xs zs ps qs us : List Bool) : + Function.update (greedyRegisters R xs zs ps qs) 1 us=greedyRegisters R xs us ps qs := by + funext i; by_cases h : i=1 <;> simp_all [greedyRegisters] +lemma greedyRegisters_update2 (R : Fin (k+8) → List Bool) (xs zs ps qs us : List Bool) : + Function.update (greedyRegisters R xs zs ps qs) 2 us=greedyRegisters R xs zs us qs := by + funext i; by_cases h : i=2 <;> simp_all [greedyRegisters] +lemma greedyRegisters_update4 (R : Fin (k+8) → List Bool) (xs zs ps qs us : List Bool) : + Function.update (greedyRegisters R xs zs ps qs) 4 us=greedyRegisters R xs zs ps us := by + funext i; by_cases h : i=4 <;> simp_all [greedyRegisters] +def greedyConfig (R : Fin (k+8) → List Bool) (pc : Fin 27) (q c : ℕ) : MachineConfig k 26 := + ⟨R,pc,none,q,c⟩ +def greedyCopy₁ (i : Fin 9) : Fin 27 := ⟨i.val+4,by omega⟩ +def greedyCopy₂ (i : Fin 9) : Fin 27 := ⟨i.val+13,by omega⟩ +def greedyProgram (which : Bool) : Program k 26 := fun pc => + if h₁ : 4≤pc.val ∧ pc.val<12 then + ((copyProgram 2 3 4) ⟨pc.val-4,by omega⟩).relabel greedyCopy₁ + else if h₂ : 13≤pc.val ∧ pc.val<21 then + ((copyProgram 1 3 4) ⟨pc.val-13,by omega⟩).relabel greedyCopy₂ + else match pc.val with + | 0 => .pop 0 26 1 2 + | 1 => .pop 1 3 3 3 + | 2 => .pop 1 4 4 4 + | 3 => .push 2 false 0 + | 12 => .push 4 true 13 + | 21 => .query which 4 22 23 + | 22 => .pop 4 24 22 22 + | 23 => .pop 4 25 23 23 + | 24 => .push 2 false 0 + | 25 => .push 2 true 0 + | _ => .halt +lemma greedy_copy₁ (which : Bool) (i : Fin 9) (hi : i≠8) : + greedyProgram (k:=k) which (greedyCopy₁ i)=(copyProgram 2 3 4 i).relabel greedyCopy₁ := by + have hh : i.val<8 := by + have hb := i.isLt + have hn : i.val≠8 := by intro h; exact hi (Fin.ext h) + omega + simp [greedyProgram,greedyCopy₁,hh,show 4≤ i.val+4 by omega] +lemma greedy_copy₂ (which : Bool) (i : Fin 9) (hi : i≠8) : + greedyProgram (k:=k) which (greedyCopy₂ i)=(copyProgram 1 3 4 i).relabel greedyCopy₂ := by + have hh : i.val<8 := by + have hb := i.isLt + have hn : i.val≠8 := by intro h; exact hi (Fin.ext h) + omega + simp [greedyProgram,greedyCopy₂,hh,show 13≤ i.val+13 by omega,show ¬i.val+13<12 by omega] +lemma greedyRegisters_copy₁ (R : Fin (k+8) → List Bool) (xs zs ps qs : List Bool) : + tripleRegisters (greedyRegisters R xs zs ps qs) 2 3 4 ps [] qs=greedyRegisters R xs zs ps qs := by + funext i + by_cases h2 : i=2 <;> by_cases h3 : i=3 <;> by_cases h4 : i=4 <;> + simp_all [tripleRegisters,pairRegisters,greedyRegisters] +lemma greedyRegisters_copy₁_out (R : Fin (k+8) → List Bool) (xs zs ps qs : List Bool) : + tripleRegisters (greedyRegisters R xs zs ps qs) 2 3 4 ps [] (ps++qs)=greedyRegisters R xs zs ps (ps++qs) := by + funext i + by_cases h2 : i=2 <;> by_cases h3 : i=3 <;> by_cases h4 : i=4 <;> + simp_all [tripleRegisters,pairRegisters,greedyRegisters] +lemma greedyRegisters_copy₂ (R : Fin (k+8) → List Bool) (xs zs ps qs : List Bool) : + tripleRegisters (greedyRegisters R xs zs ps qs) 1 3 4 zs [] qs=greedyRegisters R xs zs ps qs := by + funext i + by_cases h1 : i=1 <;> by_cases h3 : i=3 <;> by_cases h4 : i=4 <;> + simp_all [tripleRegisters,pairRegisters,greedyRegisters] +lemma greedyRegisters_copy₂_out (R : Fin (k+8) → List Bool) (xs zs ps qs : List Bool) : + tripleRegisters (greedyRegisters R xs zs ps qs) 1 3 4 zs [] (zs++qs)=greedyRegisters R xs zs ps (zs++qs) := by + funext i + by_cases h1 : i=1 <;> by_cases h3 : i=3 <;> by_cases h4 : i=4 <;> + simp_all [tripleRegisters,pairRegisters,greedyRegisters] +lemma greedy_copy₁_run (which : Bool) (O : IndependenceOracle n) (R : Fin (k+8) → List Bool) + (xs zs ps qs : List Bool) (q c : ℕ) (bits : ℕ → Bool) : + execution (greedyProgram which) O (greedyConfig (greedyRegisters R xs zs ps qs) 4 q c) bits (5*ps.length+2)= + greedyConfig (greedyRegisters R xs zs ps (ps++qs)) 12 q (c+5*ps.length+2) := by + have hc := copy_block (k:=k) (2 : Fin (k+8)) 3 4 (by simp) (by simp) (by simp) + O (greedyRegisters R xs zs ps qs) ps qs q c bits + simp only [greedyRegisters_copy₁,greedyRegisters_copy₁_out] at hc + have h := execution_relabel_before_halt (copyProgram (k:=k) 2 3 4) (greedyProgram which) greedyCopy₁ + 8 (by rfl) (greedy_copy₁ which) O (copyConfig (greedyRegisters R xs zs ps qs) 0 q c) bits (5*ps.length+2) + (by rw [hc]; rfl) + rw [hc] at h + simpa [relabelConfig,copyConfig,greedyConfig,greedyCopy₁] using h +lemma greedy_copy₂_run (which : Bool) (O : IndependenceOracle n) (R : Fin (k+8) → List Bool) + (xs zs ps qs : List Bool) (q c : ℕ) (bits : ℕ → Bool) : + execution (greedyProgram which) O (greedyConfig (greedyRegisters R xs zs ps qs) 13 q c) bits (5*zs.length+2)= + greedyConfig (greedyRegisters R xs zs ps (zs++qs)) 21 q (c+5*zs.length+2) := by + have hc := copy_block (k:=k) (1 : Fin (k+8)) 3 4 (by simp) (by simp) (by simp) + O (greedyRegisters R xs zs ps qs) zs qs q c bits + simp only [greedyRegisters_copy₂,greedyRegisters_copy₂_out] at hc + have h := execution_relabel_before_halt (copyProgram (k:=k) 1 3 4) (greedyProgram which) greedyCopy₂ + 8 (by rfl) (greedy_copy₂ which) O (copyConfig (greedyRegisters R xs zs ps qs) 0 q c) bits (5*zs.length+2) + (by rw [hc]; rfl) + rw [hc] at h + simpa [relabelConfig,copyConfig,greedyConfig,greedyCopy₂] using h +lemma greedy_clear (which b : Bool) (O : IndependenceOracle n) (R : Fin (k+8) → List Bool) + (xs zs ps qs : List Bool) (q c : ℕ) (bits : ℕ → Bool) : + execution (greedyProgram which) O (greedyConfig (greedyRegisters R xs zs ps qs) (if b then 23 else 22) q c) + bits (qs.length+1)=greedyConfig (greedyRegisters R xs zs ps []) (if b then 25 else 24) q (c+qs.length+1) := by + induction qs generalizing c bits with + | nil => cases b <;> simp [execution,machineStep,greedyProgram,greedyConfig,greedyRegisters] + | cons a qs ih => + have ht : execution (greedyProgram which) O (greedyConfig (greedyRegisters R xs zs ps (a::qs)) + (if b then 23 else 22) q c) bits 1= + greedyConfig (greedyRegisters R xs zs ps qs) (if b then 23 else 22) q (c+1) := by + cases b <;> cases a <;> simp [execution,machineStep,greedyProgram,greedyConfig,greedyRegisters,greedyRegisters_update4] + rw [List.length_cons,show qs.length+1+1=1+(qs.length+1) by omega,execution_add,ht,ih] + congr 1 ; omega +lemma greedy_query_run (which : Bool) (O : IndependenceOracle n) (R : Fin (k+8) → List Bool) + (xs zs ps qs : List Bool) (hn : qs.length=n) (q c : ℕ) (bits : ℕ → Bool) : + execution (greedyProgram which) O (greedyConfig (greedyRegisters R xs zs ps qs) 21 q c) bits (n+3)= + greedyConfig (greedyRegisters R xs zs (wordOracle which O qs::ps) []) 0 (q+1) (c+3*n+3) := by + have ht : execution (greedyProgram which) O (greedyConfig (greedyRegisters R xs zs ps qs) 21 q c) bits 1= + greedyConfig (greedyRegisters R xs zs ps qs) (if wordOracle which O qs then 23 else 22) (q+1) (c+2*n+1) := by + simp [execution,machineStep,greedyProgram,greedyConfig,greedyRegisters,wordOracle,hn,two_mul,Nat.add_assoc] + have hp (b : Bool) (c' : ℕ) (bits' : ℕ → Bool) : + execution (greedyProgram which) O (greedyConfig (greedyRegisters R xs zs ps []) (if b then 25 else 24) (q+1) c') bits' 1= + greedyConfig (greedyRegisters R xs zs (b::ps) []) 0 (q+1) (c'+1) := by + cases b <;> simp [execution,machineStep,greedyProgram,greedyConfig,greedyRegisters_update2,greedyRegisters] + rw [show n+3=1+((qs.length+1)+1) by omega,execution_add,ht,execution_add,greedy_clear,hp] + congr 1 ; omega +lemma greedy_true_body (which : Bool) (O : IndependenceOracle n) (R : Fin (k+8) → List Bool) + (xs ps : List Bool) (hn : xs.length+ps.length+1=n) (q c : ℕ) (bits : ℕ → Bool) : + execution (greedyProgram which) O + (greedyConfig (greedyRegisters R (true::xs) (List.replicate (xs.length+1) false) ps []) 0 q c) bits (6*n+5)= + greedyConfig (greedyRegisters R xs (List.replicate xs.length false) + (wordOracle which O (List.replicate xs.length false++true::ps)::ps) []) 0 (q+1) (c+8*n+5) := by + let zs := List.replicate xs.length false + have hpop : execution (greedyProgram which) O + (greedyConfig (greedyRegisters R (true::xs) (List.replicate (xs.length+1) false) ps []) 0 q c) bits 2= + greedyConfig (greedyRegisters R xs zs ps []) 4 q (c+2) := by + simp [execution,machineStep,greedyProgram,greedyConfig,greedyRegisters_update0,greedyRegisters_update1, + greedyRegisters,List.replicate_succ,zs] + have hpush (c' : ℕ) (bits' : ℕ → Bool) : + execution (greedyProgram which) O (greedyConfig (greedyRegisters R xs zs ps ps) 12 q c') bits' 1= + greedyConfig (greedyRegisters R xs zs ps (true::ps)) 13 q (c'+1) := by + simp [execution,machineStep,greedyProgram,greedyConfig,greedyRegisters_update4,greedyRegisters] + have hlen : (zs++true::ps).length=n := by simp only [List.length_append,List.length_cons,List.length_replicate,zs]; omega + rw [show 6*n+5=2+((5*ps.length+2)+(1+((5*zs.length+2)+(n+3)))) by simp only [zs,List.length_replicate]; omega, + execution_add,hpop,execution_add,greedy_copy₁_run] + simp only [List.append_nil] + rw [execution_add,hpush,execution_add,greedy_copy₂_run,greedy_query_run _ _ _ _ _ _ _ hlen] + congr 1 ; simp only [zs,List.length_replicate] ; omega +lemma greedy_false_body (which : Bool) (O : IndependenceOracle n) (R : Fin (k+8) → List Bool) + (xs ps : List Bool) (q c : ℕ) (bits : ℕ → Bool) : + execution (greedyProgram which) O + (greedyConfig (greedyRegisters R (false::xs) (List.replicate (xs.length+1) false) ps []) 0 q c) bits 3= + greedyConfig (greedyRegisters R xs (List.replicate xs.length false) (false::ps) []) 0 q (c+3) := by + simp [execution,machineStep,greedyProgram,greedyConfig,greedyRegisters_update0,greedyRegisters_update1, + greedyRegisters_update2,greedyRegisters,List.replicate_succ] + +theorem greedy_machine_run (which : Bool) (O : IndependenceOracle n) (R : Fin (k+8) → List Bool) + (xs ps : List Bool) (hn : xs.length+ps.length=n) (q c : ℕ) (bits : ℕ → Bool) : + execution (greedyProgram which) O + (greedyConfig (greedyRegisters R xs (List.replicate xs.length false) ps []) 0 q c) bits (greedyTime n xs)= + greedyConfig (greedyRegisters R [] [] (wordGreedy (wordOracle which O) xs ps) []) 26 + (q+greedyCalls xs) (c+greedyWork n xs) := by + induction xs generalizing ps q c bits with + | nil => simp [greedyTime,greedyWork,greedyCalls,wordGreedy,execution,machineStep,greedyProgram,greedyConfig,greedyRegisters] + | cons b xs ih => + have hn' : xs.length+ps.length+1=n := by simp only [List.length_cons] at hn; omega + cases b with + | false => + simp only [greedyTime,greedyWork,greedyCalls,wordGreedy,Bool.false_and,Bool.false_eq_true,ite_false,Nat.zero_add] + rw [List.length_cons,execution_add,greedy_false_body,ih] + · congr 1 ; omega + · simp only [List.length_cons]; omega + | true => + simp only [greedyTime,greedyWork,greedyCalls,wordGreedy,Bool.true_and,ite_true] + rw [List.length_cons,execution_add,greedy_true_body _ _ _ _ _ hn',ih] + · congr 1 <;> omega + · simp only [List.length_cons]; omega + +end + +section + +variable {n : ℕ} +def wordSet (n : ℕ) (l : List Bool) : Set (Fin n) := {i | l[i.val]?.getD false=true} +lemma wordSet_zero_succ (m : ℕ) (ps : List Bool) : + wordSet n (List.replicate (m+1) false++ps)=wordSet n (List.replicate m false++false::ps) := by + congr 1 + rw [List.replicate_add,List.replicate_one,List.append_assoc,List.singleton_append] +lemma wordSet_bit (as ps : List Bool) (h : as.length simp + +theorem wordGreedy_basis (M : Matroid (Fin n)) (hE : M.E=Set.univ) + (W : List Bool → Bool) (hW : ∀l,l.length=n → (W l=true ↔ M.Indep (wordSet n l))) + (xs ps : List Bool) (hn : xs.length+ps.length=n) + (hI : M.Indep (wordSet n (List.replicate xs.length false++ps))) : + M.IsBasis (wordSet n (wordGreedy W xs ps)) (wordSet n (xs.reverse++ps)) := by + induction xs generalizing ps with + | nil => simpa [wordGreedy] using hI.isBasis_self + | cons b xs ih => + have hlen : xs.length+(b::ps).length=n := by simp only [List.length_cons] at *; omega + have ha : xs.length simpa [wordGreedy,List.reverse_cons,List.append_assoc] using ih (false::ps) hlen hI' + | true => + cases hq : W (List.replicate xs.length false++true::ps) with + | true => + have hJ := (hW _ hqueryLen).mp hq + simpa [wordGreedy,hq,List.reverse_cons,List.append_assoc] using ih (true::ps) hlen hJ + | false => + have hJ := ih (false::ps) (by simpa using hlen) hI' + have han : ¬M.Indep (insert a (wordSet n (List.replicate xs.length false++false::ps))) := by + rw [←hbit] + intro h + have := (hW _ hqueryLen).mpr h + simp [hq] at this + have hac : a ∈ M.closure (wordSet n (List.replicate xs.length false++false::ps)) := + hI'.mem_closure_iff'.mpr ⟨by simp [hE],fun h => (han h).elim⟩ + have hsub : wordSet n (List.replicate xs.length false++false::ps) ⊆ wordSet n (xs.reverse++false::ps) := by + simpa using wordSet_zero_subset (n:=n) xs.reverse (false::ps) + have hac' : a ∈ M.closure (wordSet n (wordGreedy W xs (false::ps))) := by + rw [hJ.closure_eq_closure] + exact M.closure_mono hsub hac + have hB := hJ.indep.isBasis_of_subset_of_subset_closure + (hJ.subset.trans (Set.subset_insert a _)) (Set.insert_subset hac' hJ.subset_closure) + simpa [wordGreedy,hq,List.reverse_cons,List.append_assoc,hbit'] using hB + +end + +section + +variable {k n : ℕ} +lemma incrementBits_length (ys : List Bool) : (incrementBits ys).length≤ys.length+1 := by + induction ys with + | nil => simp [incrementBits,leadingOnes,carryTail] + | cons b ys ih => + cases b <;> simp only [incrementBits,leadingOnes,carryTail,List.length_append,List.length_replicate, + List.length_cons] at * <;> omega + +def popcountBits : List Bool → List Bool → List Bool + | [],ys => ys + | b::xs,ys => popcountBits xs (if b then incrementBits ys else ys) +def popcountTime : List Bool → List Bool → ℕ + | [],_ => 1 + | b::xs,ys => 1+(if b then 4*leadingOnes ys+3 else 0)+popcountTime xs (if b then incrementBits ys else ys) +lemma popcount_value (xs ys : List Bool) : + binaryValue (popcountBits xs ys)=binaryValue ys+xs.count true := by + induction xs generalizing ys with + | nil => simp [popcountBits] + | cons b xs ih => cases b <;> simp [popcountBits,ih,incrementBits_correct,_root_.Nat.add_comm,_root_.Nat.add_assoc] +lemma popcountTime_bound (xs ys : List Bool) : + popcountTime xs ys≤(4*(xs.length+ys.length)+4)*xs.length+1 := by + induction xs generalizing ys with + | nil => simp [popcountTime] + | cons b xs ih => + have hi := ih (if b then incrementBits ys else ys) + have hl : (if b then incrementBits ys else ys).length≤ys.length+1 := by + cases b <;> simp only [Bool.false_eq_true,ite_false,ite_true]; exacts [by omega,incrementBits_length ys] + have hh := Nat.mul_le_mul_right xs.length (show 4*(xs.length+(if b then incrementBits ys else ys).length)+4≤ + 4*(xs.length+ys.length+1)+4 by omega) + have ho := leadingOnes_le ys + cases b <;> simp only [popcountTime,List.length_cons,Bool.false_eq_true,ite_false,ite_true] at * <;> nlinarith + +def popcountConfig (R : Fin (k+8) → List Bool) (pc : Fin 7) (q c : ℕ) : MachineConfig k 6 := + ⟨R,pc,none,q,c⟩ +def popcountLabel (i : Fin 6) : Fin 7 := if i.val<5 then ⟨i.val+1,by omega⟩ else 0 +def popcountProgram : Program k 6 := fun pc => + if h0 : pc.val=0 then .pop 2 6 0 1 + else if h1 : pc.val<6 then + ((incrementProgram 0 3) ⟨pc.val-1,by omega⟩).relabel popcountLabel + else .halt +lemma popcount_increment (i : Fin 6) (hi : i≠5) : + (popcountProgram : Program k 6) (popcountLabel i)=(incrementProgram 0 3 i).relabel popcountLabel := by + have hh : i.val<5 := by + have hb := i.isLt + have hn : i.val≠5 := by intro h; exact hi (Fin.ext h) + omega + simp [popcountProgram,popcountLabel,hh,show i.val+1<6 by omega] +lemma greedyRegisters_increment_in (R : Fin (k+8) → List Bool) (xs ys : List Bool) : + pairRegisters (greedyRegisters R ys [] xs []) 0 3 ys []=greedyRegisters R ys [] xs [] := by + funext i + by_cases h0 : i=0 <;> by_cases h3 : i=3 <;> simp_all [pairRegisters,greedyRegisters] +lemma greedyRegisters_increment_out (R : Fin (k+8) → List Bool) (xs ys : List Bool) : + pairRegisters (greedyRegisters R ys [] xs []) 0 3 (incrementBits ys) []= + greedyRegisters R (incrementBits ys) [] xs [] := by + funext i + by_cases h0 : i=0 <;> by_cases h3 : i=3 <;> simp_all [pairRegisters,greedyRegisters] +lemma popcount_increment_run (O : IndependenceOracle n) (R : Fin (k+8) → List Bool) + (xs ys : List Bool) (q c : ℕ) (bits : ℕ → Bool) : + execution popcountProgram O (popcountConfig (greedyRegisters R ys [] xs []) 1 q c) bits (4*leadingOnes ys+3)= + popcountConfig (greedyRegisters R (incrementBits ys) [] xs []) 0 q (c+4*leadingOnes ys+3) := by + have hi := (increment_block (k:=k) (0 : Fin (k+8)) 3 (by simp) O (greedyRegisters R ys [] xs []) ys q c bits).1 + simp only [greedyRegisters_increment_in,greedyRegisters_increment_out] at hi + have h := execution_relabel_before_halt (incrementProgram (k:=k) 0 3) popcountProgram popcountLabel + 5 (by rfl) popcount_increment O (workConfig (greedyRegisters R ys [] xs []) 0 q c) bits (4*leadingOnes ys+3) + (by rw [hi]; rfl) + rw [hi] at h + simpa [relabelConfig,workConfig,popcountConfig,popcountLabel] using h + +theorem popcount_run (O : IndependenceOracle n) (R : Fin (k+8) → List Bool) + (xs ys : List Bool) (q c : ℕ) (bits : ℕ → Bool) : + execution popcountProgram O (popcountConfig (greedyRegisters R ys [] xs []) 0 q c) bits (popcountTime xs ys)= + popcountConfig (greedyRegisters R (popcountBits xs ys) [] [] []) 6 q (c+popcountTime xs ys) := by + induction xs generalizing ys c bits with + | nil => simp [popcountTime,popcountBits,execution,machineStep,popcountProgram,popcountConfig,greedyRegisters] + | cons b xs ih => + have hp : execution popcountProgram O (popcountConfig (greedyRegisters R ys [] (b::xs) []) 0 q c) bits 1= + popcountConfig (greedyRegisters R ys [] xs []) (if b then 1 else 0) q (c+1) := by + cases b <;> simp [execution,machineStep,popcountProgram,popcountConfig,greedyRegisters,greedyRegisters_update2] + cases b with + | false => + simp only [popcountTime,popcountBits,Bool.false_eq_true,ite_false,Nat.add_zero] + rw [execution_add,hp] + simp only [Bool.false_eq_true,ite_false] + rw [ih] + congr 1 ; omega + | true => + simp only [popcountTime,popcountBits,ite_true] + rw [show 1+(4*leadingOnes ys+3)+popcountTime xs (incrementBits ys)= + 1+((4*leadingOnes ys+3)+popcountTime xs (incrementBits ys)) by omega,execution_add,hp] + simp only [ite_true] + rw [execution_add,popcount_increment_run,ih] + congr 1 ; omega + +end + +section +open scoped BigOperators Classical +variable {k n : ℕ} +lemma count_ofFn (n : ℕ) (f : Fin n → Bool) : + (List.ofFn f).count true=∑i,if f i then 1 else 0 := by + induction n with + | zero => simp + | succ n ih => + rw [List.ofFn_succ,Fin.sum_univ_succ] + cases hf : f 0 <;> simp [ih,Nat.add_comm] +lemma wordSet_card (xs : List Bool) (hn : xs.length=n) : + Fintype.card (wordSet n xs)=xs.count true := by + subst n + let f : Fin xs.length → Bool := fun i => xs[i.val] + have hf : List.ofFn f=xs := List.ofFn_getElem + have hs : wordSet xs.length xs=wordSet xs.length (List.ofFn f) := congrArg (wordSet xs.length) hf.symm + rw [hs,wordSet_ofFn,Fintype.card_subtype,Finset.card_filter] + have hc := count_ofFn xs.length f + rw [hf] at hc + exact hc.symm +lemma wordGreedy_rank (M : Matroid (Fin n)) (hE : M.E=Set.univ) + (W : List Bool → Bool) (hW : ∀l,l.length=n → (W l=true ↔ M.Indep (wordSet n l))) + (xs : List Bool) (hn : xs.length=n) : + (wordGreedy W xs []).count true=(M.eRk (wordSet n xs.reverse)).toNat := by + have h := wordGreedy_basis M hE W hW xs [] (by simpa using hn) + (by simp [wordSet_zeros]) + simp only [List.append_nil] at h + have hh := h.encard_eq_eRk + rw [Set.encard_eq_coe_toFinset_card] at hh + have hc : (wordSet n (wordGreedy W xs [])).toFinset.card=(wordGreedy W xs []).count true := by + rw [Set.toFinset_card] + exact wordSet_card _ (by simpa [wordGreedy_length] using hn) + rw [hc] at hh + simpa using congrArg ENat.toNat hh + +def rankProgram (which : Bool) : Program k 32 := concatProgram (greedyProgram which) popcountProgram +def rankConfig (R : Fin (k+8) → List Bool) (pc : Fin 33) (q c : ℕ) : MachineConfig k 32 := + ⟨R,pc,none,q,c⟩ +def rankBits (which : Bool) (O : IndependenceOracle n) (xs : List Bool) : List Bool := + popcountBits (wordGreedy (wordOracle which O) xs []) [] +def rankTime (which : Bool) (O : IndependenceOracle n) (xs : List Bool) : ℕ := + greedyTime n xs+popcountTime (wordGreedy (wordOracle which O) xs []) [] +def rankWork (which : Bool) (O : IndependenceOracle n) (xs : List Bool) : ℕ := + greedyWork n xs+popcountTime (wordGreedy (wordOracle which O) xs []) [] +lemma rankTime_bound (which : Bool) (O : IndependenceOracle n) (xs : List Bool) (hn : xs.length=n) : + rankTime which O xs≤(10*n+9)*n+2 := by + have hg := greedyTime_bound n xs + have hp := popcountTime_bound (wordGreedy (wordOracle which O) xs []) [] + simp only [wordGreedy_length,List.length_nil,Nat.add_zero,hn] at * + unfold rankTime + nlinarith +lemma rankWork_bound (which : Bool) (O : IndependenceOracle n) (xs : List Bool) (hn : xs.length=n) : + rankWork which O xs≤(12*n+9)*n+2 := by + have hg := greedyWork_bound n xs + have hp := popcountTime_bound (wordGreedy (wordOracle which O) xs []) [] + simp only [wordGreedy_length,List.length_nil,Nat.add_zero,hn] at * + unfold rankWork + nlinarith +lemma rank_run (which : Bool) (O : IndependenceOracle n) (R : Fin (k+8) → List Bool) + (xs : List Bool) (hn : xs.length=n) (q c : ℕ) (bits : ℕ → Bool) : + execution (rankProgram which) O + (rankConfig (greedyRegisters R xs (List.replicate n false) [] []) 0 q c) bits (rankTime which O xs)= + rankConfig (greedyRegisters R (rankBits which O xs) [] [] []) 32 + (q+greedyCalls xs) (c+rankWork which O xs) := by + have hg := greedy_machine_run which O R xs [] (by simpa using hn) q c bits + have hp := popcount_run O R (wordGreedy (wordOracle which O) xs []) [] (q+greedyCalls xs) + (c+greedyWork n xs) (fun i => bits (greedyTime n xs+i)) + have h := concat_run (greedyProgram (k:=k) which) popcountProgram (by rfl) O + (greedyConfig (greedyRegisters R xs (List.replicate xs.length false) [] []) 0 q c) bits + (greedyTime n xs) (popcountTime (wordGreedy (wordOracle which O) xs []) []) + (by rw [hg]; rfl) (by rw [hg]; rfl) + rw [hg] at h + have hre : restartControl (greedyConfig (greedyRegisters R [] [] (wordGreedy (wordOracle which O) xs []) []) + 26 (q+greedyCalls xs) (c+greedyWork n xs)) (0 : Fin 7)= + popcountConfig (greedyRegisters R [] [] (wordGreedy (wordOracle which O) xs []) []) 0 (q+greedyCalls xs) (c+greedyWork n xs) := rfl + rw [hre,hp] at h + simpa [rankProgram,rankConfig,rankTime,rankWork,rankBits,relabelConfig,greedyConfig,popcountConfig, + firstLabel,secondLabel,hn,Nat.add_assoc] using h + +theorem matroid_rank_machine (M₁ M₂ : Matroid (Fin n)) (O : IndependenceOracle n) + (hO : ExactOracles M₁ M₂ O) (hE₁ : M₁.E=Set.univ) (hE₂ : M₂.E=Set.univ) + (which : Bool) (S : Fin n → Bool) (R : Fin (k+8) → List Bool) (q c : ℕ) (bits : ℕ → Bool) : + let xs := (List.ofFn S).reverse + let z := rankBits which O xs + let t := rankTime which O xs + let w := rankWork which O xs + binaryValue z=((if which then M₂ else M₁).eRk {i | S i=true}).toNat ∧ + t≤(10*n+9)*n+2 ∧ w≤(12*n+9)*n+2 ∧ greedyCalls xs≤n ∧ + execution (rankProgram which) O + (rankConfig (greedyRegisters R xs (List.replicate n false) [] []) 0 q c) bits t= + rankConfig (greedyRegisters R z [] [] []) 32 (q+greedyCalls xs) (c+w) := by + have hn : (List.ofFn S).reverse.length=n := by simp + refine ⟨?_,rankTime_bound which O _ hn,rankWork_bound which O _ hn,?_,rank_run which O R _ hn q c bits⟩ + · simp only [rankBits,popcount_value,binaryValue,Nat.zero_add] + have hr := wordGreedy_rank (if which then M₂ else M₁) (by cases which <;> assumption) + (wordOracle which O) (fun l _ => hO which (fun i => l[i.val]?.getD false)) (List.ofFn S).reverse hn + simpa only [List.reverse_reverse,wordSet_ofFn] using hr + · simpa using greedyCalls_bound (List.ofFn S).reverse + +end + +section + +variable {k n : ℕ} +def compareBits : Bool → List Bool → List Bool → Bool + | b,[],[] => b + | b,[],y::ys => compareBits (if y then true else b) [] ys + | b,x::xs,[] => compareBits (if x then false else b) xs [] + | b,x::xs,y::ys => compareBits (if x=y then b else y) xs ys +lemma compareBits_correct (b : Bool) (xs ys : List Bool) : + compareBits b xs ys=true ↔ binaryValue xs + induction ys generalizing b with + | nil => simp [compareBits,binaryValue] + | cons y ys ih => + rw [compareBits,ih] + cases b <;> cases y <;> simp [binaryValue] <;> omega + | cons x xs ih => + cases ys with + | nil => + rw [compareBits,ih] + cases b <;> cases x <;> simp [binaryValue] + | cons y ys => + rw [compareBits,ih] + cases b <;> cases x <;> cases y <;> simp [binaryValue] <;> omega +lemma compareBits_lt (xs ys : List Bool) : compareBits false xs ys=true ↔ binaryValue xs + match pc.val with + | 0 => .pop a 1 2 3 + | 1 => .pop b 8 0 4 + | 2 => .pop b 0 0 4 + | 3 => .pop b 0 0 0 + | 4 => .pop a 5 6 7 + | 5 => .pop b 9 4 4 + | 6 => .pop b 4 4 4 + | 7 => .pop b 0 0 4 + | _ => .halt + +theorem comparison_run (a b : Fin (k+8)) (hab : a≠b) (O : IndependenceOracle n) + (R : Fin (k+8) → List Bool) (xs ys : List Bool) (lt : Bool) (q c : ℕ) (bits : ℕ → Bool) : + execution (compareProgram a b) O (compareConfig (pairRegisters R a b xs ys) (if lt then 4 else 0) q c) bits + (2*max xs.length ys.length+2)= + compareConfig (pairRegisters R a b [] []) (if compareBits lt xs ys then 9 else 8) q + (c+(2*max xs.length ys.length+2)) := by + induction xs generalizing lt ys c bits with + | nil => + induction ys generalizing lt c bits with + | nil => cases lt <;> simp [execution,machineStep,compareProgram,compareConfig,pairRegisters_a _ _ _ hab,pairRegisters_b,compareBits] + | cons y ys ih => + have hstep : execution (compareProgram a b) O (compareConfig (pairRegisters R a b [] (y::ys)) + (if lt then 4 else 0) q c) bits 2= + compareConfig (pairRegisters R a b [] ys) (if (if y then true else lt) then 4 else 0) q (c+2) := by + cases lt <;> cases y <;> simp [execution,machineStep,compareProgram,compareConfig, + pairRegisters_a _ _ _ hab,pairRegisters_b,pairRegisters_update_b] + simp only [List.length_nil,List.length_cons,Nat.zero_max] + rw [show 2*(ys.length+1)+2=2+(2*ys.length+2) by omega,execution_add,hstep] + simpa [compareBits,Nat.add_assoc] using ih (if y then true else lt) (c+2) (fun i => bits (2+i)) + | cons x xs ih => + cases ys with + | nil => + have hstep : execution (compareProgram a b) O (compareConfig (pairRegisters R a b (x::xs) []) + (if lt then 4 else 0) q c) bits 2= + compareConfig (pairRegisters R a b xs []) (if (if x then false else lt) then 4 else 0) q (c+2) := by + cases lt <;> cases x <;> simp [execution,machineStep,compareProgram,compareConfig, + pairRegisters_a _ _ _ hab,pairRegisters_b,pairRegisters_update_a _ _ _ hab] + simp only [List.length_nil,List.length_cons,Nat.max_zero] + rw [show 2*(xs.length+1)+2=2+(2*xs.length+2) by omega,execution_add,hstep] + simpa [compareBits,Nat.add_assoc] using ih [] (if x then false else lt) (c+2) (fun i => bits (2+i)) + | cons y ys => + have hstep : execution (compareProgram a b) O (compareConfig (pairRegisters R a b (x::xs) (y::ys)) + (if lt then 4 else 0) q c) bits 2= + compareConfig (pairRegisters R a b xs ys) (if (if x=y then lt else y) then 4 else 0) q (c+2) := by + cases lt <;> cases x <;> cases y <;> simp [execution,machineStep,compareProgram,compareConfig, + pairRegisters_a _ _ _ hab,pairRegisters_b,pairRegisters_update_a _ _ _ hab,pairRegisters_update_b] + simp only [List.length_cons,max_add_add_right] + rw [show 2*(max xs.length ys.length+1)+2=2+(2*max xs.length ys.length+2) by omega,execution_add,hstep] + simpa [compareBits,Nat.add_assoc] using ih ys (if x=y then lt else y) (c+2) (fun i => bits (2+i)) + +theorem comparison_block (a b : Fin (k+8)) (hab : a≠b) (O : IndependenceOracle n) + (R : Fin (k+8) → List Bool) (xs ys : List Bool) (q c : ℕ) (bits : ℕ → Bool) : + let t := 2*max xs.length ys.length+2 + execution (compareProgram a b) O (compareConfig (pairRegisters R a b xs ys) 0 q c) bits t= + compareConfig (pairRegisters R a b [] []) (if binaryValue xs [] + | x::xs,[] => sumDigit x false c :: subDigits (subBorrow x false c) xs [] + | [],y::ys => sumDigit false y c :: subDigits (subBorrow false y c) [] ys + | x::xs,y::ys => sumDigit x y c :: subDigits (subBorrow x y c) xs ys +termination_by xs.length+ys.length +def subCost (c : Bool) (xs ys : List Bool) : ℕ := + match xs,ys with + | [],[] => 2 + | x::xs,[] => 3+subCost (subBorrow x false c) xs [] + | [],y::ys => 3+subCost (subBorrow false y c) [] ys + | x::xs,y::ys => 3+subCost (subBorrow x y c) xs ys +termination_by xs.length+ys.length +lemma subDigits_value (c : Bool) (xs ys : List Bool) + (h : binaryValue ys+(if c then 1 else 0)≤binaryValue xs) : + binaryValue (subDigits c xs ys)+binaryValue ys+(if c then 1 else 0)=binaryValue xs := by + induction xs generalizing ys c with + | nil => + induction ys generalizing c with + | nil => cases c <;> simp_all [subDigits,binaryValue] + | cons y ys ih => + cases y <;> cases c <;> simp_all [binaryValue,subDigits,subBorrow,sumDigit] + | cons x xs ih => + cases ys with + | nil => + have ht : binaryValue []+(if subBorrow x false c then 1 else 0)≤binaryValue xs := by + cases x <;> cases c <;> simp_all [binaryValue,subBorrow] ; omega + have hi := ih (subBorrow x false c) [] ht + simp only [subDigits,binaryValue] + cases x <;> cases c <;> simp [subBorrow,sumDigit,binaryValue] at hi h ⊢ <;> omega + | cons y ys => + have ht : binaryValue ys+(if subBorrow x y c then 1 else 0)≤binaryValue xs := by + cases x <;> cases y <;> cases c <;> simp_all [binaryValue,subBorrow] <;> omega + have hi := ih (subBorrow x y c) ys ht + simp only [subDigits,binaryValue] + cases x <;> cases y <;> cases c <;> simp [subBorrow,sumDigit,binaryValue] at hi h ⊢ <;> omega +lemma subDigits_length_cost (c : Bool) (xs ys : List Bool) : + (subDigits c xs ys).length≤xs.length+ys.length+1 ∧ + subCost c xs ys≤3*(xs.length+ys.length)+3 := by + induction xs generalizing ys c with + | nil => + induction ys generalizing c with + | nil => cases c <;> simp [subDigits,subCost] + | cons y ys ih => + have hi := ih (subBorrow false y c) + simp only [subDigits,subCost,List.length_cons,List.length_nil] at * + constructor <;> omega + | cons x xs ih => + cases ys with + | nil => + have hi := ih (subBorrow x false c) [] + simp only [subDigits,subCost,List.length_cons,List.length_nil] at * + constructor <;> omega + | cons y ys => + have hi := ih (subBorrow x y c) ys + simp only [subDigits,subCost,List.length_cons] at * + constructor <;> omega + +def subConfig (R : Fin (k+8) → List Bool) (pc : Fin 17) (q c : ℕ) : MachineConfig k 16 := + ⟨R,pc,none,q,c⟩ +def subProgram (a b d : Fin (k+8)) : Program k 16 := fun pc => + match pc.val with + | 0 => .pop a 2 3 4 + | 1 => .pop a 5 6 7 + | 2 => .pop b 12 8 11 + | 3 => .pop b 8 8 11 + | 4 => .pop b 9 9 8 + | 5 => .pop b 12 11 10 + | 6 => .pop b 11 11 10 + | 7 => .pop b 8 8 11 + | 8 => .push d false 0 + | 9 => .push d true 0 + | 10 => .push d false 1 + | 11 => .push d true 1 + | 12 => .pop d 16 14 15 + | 13 => .halt + | 14 => .push a false 12 + | 15 => .push a true 12 + | _ => .halt +lemma sub_build (a b d : Fin (k+8)) (hab : a≠b) (had : a≠d) (hbd : b≠d) + (O : IndependenceOracle n) (R : Fin (k+8) → List Bool) (xs ys zs : List Bool) + (carry : Bool) (q c : ℕ) (bits : ℕ → Bool) : + execution (subProgram a b d) O + (subConfig (tripleRegisters R a b d xs ys zs) (if carry then 1 else 0) q c) bits + (subCost carry xs ys)=subConfig + (tripleRegisters R a b d [] [] ((subDigits carry xs ys).reverse++zs)) 12 q (c+subCost carry xs ys) := by + induction xs generalizing ys zs carry c bits with + | nil => + induction ys generalizing zs carry c bits with + | nil => + cases carry <;> simp [subCost,subDigits,execution,machineStep,subProgram,subConfig, + tripleRegisters_a _ _ _ _ hab had,tripleRegisters_b _ _ _ _ hbd,] + | cons y ys ih => + have ht : execution (subProgram a b d) O + (subConfig (tripleRegisters R a b d [] (y::ys) zs) (if carry then 1 else 0) q c) bits 3= + subConfig (tripleRegisters R a b d [] ys (sumDigit false y carry::zs)) + (if subBorrow false y carry then 1 else 0) q (c+3) := by + cases y <;> cases carry <;> simp [execution,machineStep,subProgram,subConfig,sumDigit,subBorrow, + tripleRegisters_a _ _ _ _ hab had,tripleRegisters_b _ _ _ _ hbd,tripleRegisters_d, + tripleRegisters_update_b _ _ _ _ hbd,tripleRegisters_update_d] + rw [subCost,execution_add,ht,ih] + simp only [subDigits,List.reverse_cons,List.append_assoc,List.singleton_append] + congr 1 ; omega + | cons x xs ih => + cases ys with + | nil => + have ht : execution (subProgram a b d) O + (subConfig (tripleRegisters R a b d (x::xs) [] zs) (if carry then 1 else 0) q c) bits 3= + subConfig (tripleRegisters R a b d xs [] (sumDigit x false carry::zs)) + (if subBorrow x false carry then 1 else 0) q (c+3) := by + cases x <;> cases carry <;> simp [execution,machineStep,subProgram,subConfig,sumDigit,subBorrow, + tripleRegisters_a _ _ _ _ hab had,tripleRegisters_b _ _ _ _ hbd,tripleRegisters_d, + tripleRegisters_update_a _ _ _ _ hab had,tripleRegisters_update_d] + rw [subCost,execution_add,ht,ih] + simp only [subDigits,List.reverse_cons,List.append_assoc,List.singleton_append] + congr 1 ; omega + | cons y ys => + have ht : execution (subProgram a b d) O + (subConfig (tripleRegisters R a b d (x::xs) (y::ys) zs) (if carry then 1 else 0) q c) bits 3= + subConfig (tripleRegisters R a b d xs ys (sumDigit x y carry::zs)) + (if subBorrow x y carry then 1 else 0) q (c+3) := by + cases x <;> cases y <;> cases carry <;> simp [execution,machineStep,subProgram,subConfig,sumDigit,subBorrow, + tripleRegisters_a _ _ _ _ hab had,tripleRegisters_b _ _ _ _ hbd,tripleRegisters_d, + tripleRegisters_update_a _ _ _ _ hab had,tripleRegisters_update_b _ _ _ _ hbd, + tripleRegisters_update_d] + rw [subCost,execution_add,ht,ih] + simp only [subDigits,List.reverse_cons,List.append_assoc,List.singleton_append] + congr 1 ; omega +lemma sub_restore (a b d : Fin (k+8)) (hab : a≠b) (had : a≠d) (_ : b≠d) + (O : IndependenceOracle n) (R : Fin (k+8) → List Bool) (xs ys zs : List Bool) + (q c : ℕ) (bits : ℕ → Bool) : + execution (subProgram a b d) O (subConfig (tripleRegisters R a b d xs ys zs) 12 q c) bits + (2*zs.length+1)=subConfig (tripleRegisters R a b d (zs.reverse++xs) ys []) 16 q (c+2*zs.length+1) := by + induction zs generalizing xs c bits with + | nil => simp [execution,machineStep,subProgram,subConfig,tripleRegisters_d] + | cons z zs ih => + have ht : execution (subProgram a b d) O (subConfig (tripleRegisters R a b d xs ys (z::zs)) 12 q c) bits 2= + subConfig (tripleRegisters R a b d (z::xs) ys zs) 12 q (c+2) := by + cases z <;> simp [execution,machineStep,subProgram,subConfig,tripleRegisters_a _ _ _ _ hab had, + tripleRegisters_d,tripleRegisters_update_a _ _ _ _ hab had,tripleRegisters_update_d] + rw [List.length_cons,show 2*(zs.length+1)+1=2+(2*zs.length+1) by omega,execution_add,ht,ih] + simp only [List.reverse_cons,List.append_assoc,List.singleton_append] + congr 1 ; omega + +theorem subtraction_block (a b d : Fin (k+8)) (hab : a≠b) (had : a≠d) (hbd : b≠d) + (O : IndependenceOracle n) (R : Fin (k+8) → List Bool) (xs ys : List Bool) + (hxy : binaryValue ys≤binaryValue xs) (q c : ℕ) (bits : ℕ → Bool) : + let z := subDigits false xs ys + let t := subCost false xs ys+2*z.length+1 + binaryValue z=binaryValue xs-binaryValue ys ∧ t≤5*(xs.length+ys.length)+6 ∧ + execution (subProgram a b d) O (subConfig (tripleRegisters R a b d xs ys []) 0 q c) bits t= + subConfig (tripleRegisters R a b d z [] []) 16 q (c+t) := by + dsimp only + refine ⟨?_,?_,?_⟩ + · have h := subDigits_value false xs ys (by simpa using hxy) + simp only [Bool.false_eq_true,ite_false,Nat.add_zero] at h + omega + · have h := subDigits_length_cost false xs ys + omega + · rw [show subCost false xs ys+2*(subDigits false xs ys).length+1= + subCost false xs ys+(2*(subDigits false xs ys).length+1) by omega,execution_add] + rw [show (0 : Fin 17)=(if false then 1 else 0) by rfl,sub_build a b d hab had hbd] + simp only [List.append_nil] + rw [←List.length_reverse (as:=subDigits false xs ys),sub_restore a b d hab had hbd] + simp only [List.reverse_reverse,List.length_reverse,List.append_nil] + congr 1 ; omega + +end + +section + +variable {k s t n : ℕ} +lemma execution_relabel_before_any_halt (P : Program k s) (Q : Program k t) + (e : Fin (s+1) → Fin (t+1)) + (h : ∀ i,P i≠.halt → Q (e i)=(P i).relabel e) (O : IndependenceOracle n) + (c : MachineConfig k s) (bits : ℕ → Bool) (u : ℕ) + (hu : (execution P O c bits u).output=none) : + execution Q O (relabelConfig e c) bits u=relabelConfig e (execution P O c bits u) := by + induction u with + | zero => rfl + | succ u ih => + have hn := machineStep_none_pre P O (bits u) (execution P O c bits u) hu + have hh := machineStep_none_not_halt P O (bits u) (execution P O c bits u) hu + simp only [execution,ih hn] + exact machineStep_relabel P Q e O _ _ (h _ hh) + +lemma execution_of_output (P : Program k s) (O : IndependenceOracle n) + (c : MachineConfig k s) (bits : ℕ → Bool) (u : ℕ) (h : c.output.isSome) : + execution P O c bits u=c := by + induction u with + | zero => rfl + | succ u ih => simp [execution,ih,machineStep,h] +lemma execution_extend_output (P : Program k s) (O : IndependenceOracle n) + (c : MachineConfig k s) (bits : ℕ → Bool) (u B : ℕ) (hu : u≤B) + (h : (execution P O c bits u).output.isSome) : + execution P O c bits B=execution P O c bits u := by + rw [show B=u+(B-u) by omega,execution_add] + exact execution_of_output P O _ _ _ h + +end + +section + +variable {k n : ℕ} +@[simp] lemma workReg_ne05 : (0 : Fin (k+8))≠5 := workReg_ne (a:=0) (b:=5) (by omega) (by omega) (by omega) +@[simp] lemma workReg_ne06 : (0 : Fin (k+8))≠6 := workReg_ne (a:=0) (b:=6) (by omega) (by omega) (by omega) +@[simp] lemma workReg_ne15 : (1 : Fin (k+8))≠5 := workReg_ne (a:=1) (b:=5) (by omega) (by omega) (by omega) +@[simp] lemma workReg_ne16 : (1 : Fin (k+8))≠6 := workReg_ne (a:=1) (b:=6) (by omega) (by omega) (by omega) +@[simp] lemma workReg_ne25 : (2 : Fin (k+8))≠5 := workReg_ne (a:=2) (b:=5) (by omega) (by omega) (by omega) +@[simp] lemma workReg_ne26 : (2 : Fin (k+8))≠6 := workReg_ne (a:=2) (b:=6) (by omega) (by omega) (by omega) +@[simp] lemma workReg_ne35 : (3 : Fin (k+8))≠5 := workReg_ne (a:=3) (b:=5) (by omega) (by omega) (by omega) +@[simp] lemma workReg_ne36 : (3 : Fin (k+8))≠6 := workReg_ne (a:=3) (b:=6) (by omega) (by omega) (by omega) +@[simp] lemma workReg_ne45 : (4 : Fin (k+8))≠5 := workReg_ne (a:=4) (b:=5) (by omega) (by omega) (by omega) +@[simp] lemma workReg_ne46 : (4 : Fin (k+8))≠6 := workReg_ne (a:=4) (b:=6) (by omega) (by omega) (by omega) +@[simp] lemma workReg_ne50 : (5 : Fin (k+8))≠0 := workReg_ne (a:=5) (b:=0) (by omega) (by omega) (by omega) +@[simp] lemma workReg_ne51 : (5 : Fin (k+8))≠1 := workReg_ne (a:=5) (b:=1) (by omega) (by omega) (by omega) +@[simp] lemma workReg_ne52 : (5 : Fin (k+8))≠2 := workReg_ne (a:=5) (b:=2) (by omega) (by omega) (by omega) +@[simp] lemma workReg_ne53 : (5 : Fin (k+8))≠3 := workReg_ne (a:=5) (b:=3) (by omega) (by omega) (by omega) +@[simp] lemma workReg_ne54 : (5 : Fin (k+8))≠4 := workReg_ne (a:=5) (b:=4) (by omega) (by omega) (by omega) +@[simp] lemma workReg_ne56 : (5 : Fin (k+8))≠6 := workReg_ne (a:=5) (b:=6) (by omega) (by omega) (by omega) +@[simp] lemma workReg_ne60 : (6 : Fin (k+8))≠0 := workReg_ne (a:=6) (b:=0) (by omega) (by omega) (by omega) +@[simp] lemma workReg_ne61 : (6 : Fin (k+8))≠1 := workReg_ne (a:=6) (b:=1) (by omega) (by omega) (by omega) +@[simp] lemma workReg_ne62 : (6 : Fin (k+8))≠2 := workReg_ne (a:=6) (b:=2) (by omega) (by omega) (by omega) +@[simp] lemma workReg_ne63 : (6 : Fin (k+8))≠3 := workReg_ne (a:=6) (b:=3) (by omega) (by omega) (by omega) +@[simp] lemma workReg_ne64 : (6 : Fin (k+8))≠4 := workReg_ne (a:=6) (b:=4) (by omega) (by omega) (by omega) +@[simp] lemma workReg_ne65 : (6 : Fin (k+8))≠5 := workReg_ne (a:=6) (b:=5) (by omega) (by omega) (by omega) +def divRegisters (R : Fin (k+8) → List Bool) (xs ys zs ws as bs : List Bool) : Fin (k+8) → List Bool := + fun i => if i=0 then xs else if i=1 then ys else if i=2 then zs else if i=3 then ws + else if i=4 then [] else if i=5 then as else if i=6 then bs else R i +lemma divRegisters_copyR_in (R : Fin (k+8) → List Bool) (xs ys zs ws as bs : List Bool) : + tripleRegisters (divRegisters R xs ys zs ws as bs) 2 4 5 zs [] as=divRegisters R xs ys zs ws as bs := by + funext i + by_cases h0 : i=0 <;> by_cases h1 : i=1 <;> by_cases h2 : i=2 <;> by_cases h3 : i=3 <;> by_cases h4 : i=4 <;> by_cases h5 : i=5 <;> by_cases h6 : i=6 <;> + simp_all [divRegisters,tripleRegisters,pairRegisters] +lemma divRegisters_copyR_out (R : Fin (k+8) → List Bool) (xs ys zs ws bs : List Bool) : + tripleRegisters (divRegisters R xs ys zs ws [] bs) 2 4 5 zs [] zs=divRegisters R xs ys zs ws zs bs := by + funext i + by_cases h0 : i=0 <;> by_cases h1 : i=1 <;> by_cases h2 : i=2 <;> by_cases h3 : i=3 <;> by_cases h4 : i=4 <;> by_cases h5 : i=5 <;> by_cases h6 : i=6 <;> + simp_all [divRegisters,tripleRegisters,pairRegisters] +lemma divRegisters_copyD_in (R : Fin (k+8) → List Bool) (xs ys zs ws as bs : List Bool) : + tripleRegisters (divRegisters R xs ys zs ws as bs) 1 4 6 ys [] bs=divRegisters R xs ys zs ws as bs := by + funext i + by_cases h0 : i=0 <;> by_cases h1 : i=1 <;> by_cases h2 : i=2 <;> by_cases h3 : i=3 <;> by_cases h4 : i=4 <;> by_cases h5 : i=5 <;> by_cases h6 : i=6 <;> + simp_all [divRegisters,tripleRegisters,pairRegisters] +lemma divRegisters_copyD_out (R : Fin (k+8) → List Bool) (xs ys zs ws as : List Bool) : + tripleRegisters (divRegisters R xs ys zs ws as []) 1 4 6 ys [] ys=divRegisters R xs ys zs ws as ys := by + funext i + by_cases h0 : i=0 <;> by_cases h1 : i=1 <;> by_cases h2 : i=2 <;> by_cases h3 : i=3 <;> by_cases h4 : i=4 <;> by_cases h5 : i=5 <;> by_cases h6 : i=6 <;> + simp_all [divRegisters,tripleRegisters,pairRegisters] +lemma divRegisters_compare_in (R : Fin (k+8) → List Bool) (xs ys zs ws as bs : List Bool) : + pairRegisters (divRegisters R xs ys zs ws as bs) 5 6 as bs=divRegisters R xs ys zs ws as bs := by + funext i + by_cases h0 : i=0 <;> by_cases h1 : i=1 <;> by_cases h2 : i=2 <;> by_cases h3 : i=3 <;> by_cases h4 : i=4 <;> by_cases h5 : i=5 <;> by_cases h6 : i=6 <;> + simp_all [divRegisters,pairRegisters] +lemma divRegisters_compare_out (R : Fin (k+8) → List Bool) (xs ys zs ws as bs : List Bool) : + pairRegisters (divRegisters R xs ys zs ws as bs) 5 6 [] []=divRegisters R xs ys zs ws [] [] := by + funext i + by_cases h0 : i=0 <;> by_cases h1 : i=1 <;> by_cases h2 : i=2 <;> by_cases h3 : i=3 <;> by_cases h4 : i=4 <;> by_cases h5 : i=5 <;> by_cases h6 : i=6 <;> + simp_all [divRegisters,pairRegisters] +lemma divRegisters_copyS_in (R : Fin (k+8) → List Bool) (xs ys zs ws as bs : List Bool) : + tripleRegisters (divRegisters R xs ys zs ws as bs) 1 4 5 ys [] as=divRegisters R xs ys zs ws as bs := by + funext i + by_cases h0 : i=0 <;> by_cases h1 : i=1 <;> by_cases h2 : i=2 <;> by_cases h3 : i=3 <;> by_cases h4 : i=4 <;> by_cases h5 : i=5 <;> by_cases h6 : i=6 <;> + simp_all [divRegisters,tripleRegisters,pairRegisters] +lemma divRegisters_copyS_out (R : Fin (k+8) → List Bool) (xs ys zs ws bs : List Bool) : + tripleRegisters (divRegisters R xs ys zs ws [] bs) 1 4 5 ys [] ys=divRegisters R xs ys zs ws ys bs := by + funext i + by_cases h0 : i=0 <;> by_cases h1 : i=1 <;> by_cases h2 : i=2 <;> by_cases h3 : i=3 <;> by_cases h4 : i=4 <;> by_cases h5 : i=5 <;> by_cases h6 : i=6 <;> + simp_all [divRegisters,tripleRegisters,pairRegisters] +lemma divRegisters_sub_in (R : Fin (k+8) → List Bool) (xs ys zs ws as bs : List Bool) : + tripleRegisters (divRegisters R xs ys zs ws as bs) 2 5 4 zs as []=divRegisters R xs ys zs ws as bs := by + funext i + by_cases h0 : i=0 <;> by_cases h1 : i=1 <;> by_cases h2 : i=2 <;> by_cases h3 : i=3 <;> by_cases h4 : i=4 <;> by_cases h5 : i=5 <;> by_cases h6 : i=6 <;> + simp_all [divRegisters,tripleRegisters,pairRegisters] +lemma divRegisters_sub_out (R : Fin (k+8) → List Bool) (xs ys zs ws as bs : List Bool) (us : List Bool) : + tripleRegisters (divRegisters R xs ys zs ws as bs) 2 5 4 us [] []=divRegisters R xs ys us ws [] bs := by + funext i + by_cases h0 : i=0 <;> by_cases h1 : i=1 <;> by_cases h2 : i=2 <;> by_cases h3 : i=3 <;> by_cases h4 : i=4 <;> by_cases h5 : i=5 <;> by_cases h6 : i=6 <;> + simp_all [divRegisters,tripleRegisters,pairRegisters] +lemma divRegisters_update0 (R : Fin (k+8) → List Bool) (xs ys zs ws as bs : List Bool) (us : List Bool) : + Function.update (divRegisters R xs ys zs ws as bs) 0 us=divRegisters R us ys zs ws as bs := by + funext i + by_cases h0 : i=0 <;> by_cases h1 : i=1 <;> by_cases h2 : i=2 <;> by_cases h3 : i=3 <;> by_cases h4 : i=4 <;> by_cases h5 : i=5 <;> by_cases h6 : i=6 <;> + simp_all [divRegisters,] +lemma divRegisters_update2 (R : Fin (k+8) → List Bool) (xs ys zs ws as bs : List Bool) (us : List Bool) : + Function.update (divRegisters R xs ys zs ws as bs) 2 us=divRegisters R xs ys us ws as bs := by + funext i + by_cases h0 : i=0 <;> by_cases h1 : i=1 <;> by_cases h2 : i=2 <;> by_cases h3 : i=3 <;> by_cases h4 : i=4 <;> by_cases h5 : i=5 <;> by_cases h6 : i=6 <;> + simp_all [divRegisters,] +lemma divRegisters_update3 (R : Fin (k+8) → List Bool) (xs ys zs ws as bs : List Bool) (us : List Bool) : + Function.update (divRegisters R xs ys zs ws as bs) 3 us=divRegisters R xs ys zs us as bs := by + funext i + by_cases h0 : i=0 <;> by_cases h1 : i=1 <;> by_cases h2 : i=2 <;> by_cases h3 : i=3 <;> by_cases h4 : i=4 <;> by_cases h5 : i=5 <;> by_cases h6 : i=6 <;> + simp_all [divRegisters,] +def divCopies : Program k 16 := concatProgram (copyProgram 2 4 5) (copyProgram 1 4 6) +def divCheck : Program k 25 := concatProgram divCopies (compareProgram 5 6) +def divSubtract : Program k 24 := concatProgram (copyProgram 1 4 5) (subProgram 2 5 4) +def divCopiesConfig (R : Fin (k+8) → List Bool) (pc : Fin 17) (q c : ℕ) : MachineConfig k 16 := ⟨R,pc,none,q,c⟩ +def divCheckConfig (R : Fin (k+8) → List Bool) (pc : Fin 26) (q c : ℕ) : MachineConfig k 25 := ⟨R,pc,none,q,c⟩ +def divSubtractConfig (R : Fin (k+8) → List Bool) (pc : Fin 25) (q c : ℕ) : MachineConfig k 24 := ⟨R,pc,none,q,c⟩ +lemma divCopies_exit : (divCopies : Program k 16) (lastLabel 16)=.halt := by + simp [divCopies,concatProgram,lastLabel,copyProgram,Instruction.relabel] +lemma divSubtract_exit : (divSubtract : Program k 24) (lastLabel 24)=.halt := by + simp [divSubtract,concatProgram,lastLabel,subProgram,Instruction.relabel] +lemma divCopies_run (O : IndependenceOracle n) (R : Fin (k+8) → List Bool) + (xs ys zs ws : List Bool) (q c : ℕ) (bits : ℕ → Bool) : + execution divCopies O (divCopiesConfig (divRegisters R xs ys zs ws [] []) 0 q c) bits + ((5*zs.length+2)+(5*ys.length+2))= + divCopiesConfig (divRegisters R xs ys zs ws zs ys) 16 q (c+((5*zs.length+2)+(5*ys.length+2))) := by + have hc := copy_block (k:=k) (2 : Fin (k+8)) 4 5 (by simp) (by simp) (by simp) + O (divRegisters R xs ys zs ws [] []) zs [] q c bits + simp only [List.append_nil,divRegisters_copyR_in,divRegisters_copyR_out] at hc + have hd := copy_block (k:=k) (1 : Fin (k+8)) 4 6 (by simp) (by simp) (by simp) + O (divRegisters R xs ys zs ws zs []) ys [] q (c+(5*zs.length+2)) (fun i => bits (5*zs.length+2+i)) + simp only [List.append_nil,divRegisters_copyD_in,divRegisters_copyD_out] at hd + have hh := concat_run (copyProgram (k:=k) 2 4 5) (copyProgram 1 4 6) (by rfl) O + (copyConfig (divRegisters R xs ys zs ws [] []) 0 q c) bits (5*zs.length+2) (5*ys.length+2) + (by rw [hc]; rfl) (by rw [hc]; rfl) + rw [hc] at hh + have hre : restartControl (copyConfig (divRegisters R xs ys zs ws zs []) 8 q (c+5*zs.length+2)) + (0 : Fin 9)=copyConfig (divRegisters R xs ys zs ws zs []) 0 q (c+(5*zs.length+2)) := by + simp [restartControl,copyConfig,Nat.add_assoc] + rw [hre,hd] at hh + simpa [divCopies,divCopiesConfig,copyConfig,relabelConfig,firstLabel,secondLabel,Nat.add_assoc] using hh + +def divCheckCost (ys zs : List Bool) : ℕ := (5*zs.length+2)+(5*ys.length+2)+(2*max zs.length ys.length+2) +lemma divCheck_run (O : IndependenceOracle n) (R : Fin (k+8) → List Bool) + (xs ys zs ws : List Bool) (q c : ℕ) (bits : ℕ → Bool) : + execution divCheck O (divCheckConfig (divRegisters R xs ys zs ws [] []) 0 q c) bits + (divCheckCost ys zs)= + divCheckConfig (divRegisters R xs ys zs ws [] []) (if binaryValue zs bits ((5*zs.length+2)+(5*ys.length+2)+i)) + dsimp only at hd + simp only [divRegisters_compare_in,divRegisters_compare_out] at hd + have hh := concat_run (divCopies : Program k 16) (compareProgram 5 6) divCopies_exit O + (divCopiesConfig (divRegisters R xs ys zs ws [] []) 0 q c) bits + ((5*zs.length+2)+(5*ys.length+2)) (2*max zs.length ys.length+2) + (by rw [hc]; rfl) (by rw [hc]; rfl) + rw [hc] at hh + have hre : restartControl (divCopiesConfig (divRegisters R xs ys zs ws zs ys) 16 q (c+((5*zs.length+2)+(5*ys.length+2)))) + (0 : Fin 10)=compareConfig (divRegisters R xs ys zs ws zs ys) 0 q (c+((5*zs.length+2)+(5*ys.length+2))) := rfl + rw [hre,hd] at hh + split_ifs at hh ⊢ <;> simpa [divCheck,divCheckCost,divCopiesConfig,divCheckConfig,compareConfig,relabelConfig,firstLabel,secondLabel,Nat.add_assoc] using hh + +def divSubtractCost (ys zs : List Bool) : ℕ := (5*ys.length+2)+(subCost false zs ys+2*(subDigits false zs ys).length+1) +lemma divSubtract_run (O : IndependenceOracle n) (R : Fin (k+8) → List Bool) + (xs ys zs ws : List Bool) (hzy : binaryValue ys≤binaryValue zs) (q c : ℕ) (bits : ℕ → Bool) : + execution divSubtract O (divSubtractConfig (divRegisters R xs ys zs ws [] []) 0 q c) bits + (divSubtractCost ys zs)= + divSubtractConfig (divRegisters R xs ys (subDigits false zs ys) ws [] []) 24 q (c+divSubtractCost ys zs) := by + have hc := copy_block (k:=k) (1 : Fin (k+8)) 4 5 (by simp) (by simp) (by simp) + O (divRegisters R xs ys zs ws [] []) ys [] q c bits + simp only [List.append_nil,divRegisters_copyS_in,divRegisters_copyS_out] at hc + have hd := (subtraction_block (k:=k) (2 : Fin (k+8)) 5 4 (by simp) (by simp) (by simp) + O (divRegisters R xs ys zs ws ys []) zs ys hzy q (c+(5*ys.length+2)) + (fun i => bits (5*ys.length+2+i))).2.2 + simp only [divRegisters_sub_in,divRegisters_sub_out] at hd + have hh := concat_run (copyProgram (k:=k) 1 4 5) (subProgram 2 5 4) (by rfl) O + (copyConfig (divRegisters R xs ys zs ws [] []) 0 q c) bits (5*ys.length+2) + (subCost false zs ys+2*(subDigits false zs ys).length+1) + (by rw [hc]; rfl) (by rw [hc]; rfl) + rw [hc] at hh + have hre : restartControl (copyConfig (divRegisters R xs ys zs ws ys []) 8 q (c+5*ys.length+2)) + (0 : Fin 17)=subConfig (divRegisters R xs ys zs ws ys []) 0 q (c+(5*ys.length+2)) := by + simp [restartControl,copyConfig,subConfig,Nat.add_assoc] + rw [hre,hd] at hh + simpa [divSubtract,divSubtractCost,divSubtractConfig,copyConfig,subConfig,relabelConfig,firstLabel,secondLabel,Nat.add_assoc] using hh + +def divisionCheckLabel (i : Fin 26) : Fin 54 := + if h : i.val<24 then ⟨3+i.val,by omega⟩ else if i.val=24 then 27 else 52 +def divisionSubLabel (i : Fin 25) : Fin 54 := ⟨27+i.val,by omega⟩ +def divisionProgram : Program k 53 := fun i => + if i.val=0 then .pop 0 53 1 2 + else if i.val=1 then .push 2 false 3 + else if i.val=2 then .push 2 true 3 + else if h : i.val<27 then + ((divCheck : Program k 25) ⟨i.val-3,by omega⟩).relabel divisionCheckLabel + else if h : i.val<51 then + ((divSubtract : Program k 24) ⟨i.val-27,by omega⟩).relabel divisionSubLabel + else if i.val=51 then .push 3 true 0 + else if i.val=52 then .push 3 false 0 + else .halt +def divisionConfig (R : Fin (k+8) → List Bool) (pc : Fin 54) (q c : ℕ) : MachineConfig k 53 := + ⟨R,pc,none,q,c⟩ +lemma division_check_table (i : Fin 26) (hi : (divCheck : Program k 25) i≠.halt) : + (divisionProgram : Program k 53) (divisionCheckLabel i)= + ((divCheck : Program k 25) i).relabel divisionCheckLabel := by + have hil : i.val<24 := by + by_contra hh + have he : i=24 ∨ i=25 := by + have hl := i.isLt + rcases (show i.val=24 ∨ i.val=25 by omega) with h|h + · exact Or.inl (Fin.ext h) + · exact Or.inr (Fin.ext h) + rcases he with rfl|rfl <;> exact hi rfl + simp [divisionCheckLabel,hil,divisionProgram, + show ¬3+i.val=1 by omega,show ¬3+i.val=2 by omega,show 3+i.val<27 by omega] +lemma division_sub_table (i : Fin 25) (hi : i≠lastLabel 24) : + (divisionProgram : Program k 53) (divisionSubLabel i)= + ((divSubtract : Program k 24) i).relabel divisionSubLabel := by + have hil : i.val<24 := by + have hn : i.val≠24 := by intro h; exact hi (Fin.ext h) + omega + simp [divisionSubLabel,divisionProgram, + show ¬27+i.val=1 by omega,show ¬27+i.val=2 by omega, + show ¬27+i.val<27 by omega,show 27+i.val<51 by omega] +lemma division_check_run (O : IndependenceOracle n) (R : Fin (k+8) → List Bool) + (xs ys zs ws : List Bool) (q c : ℕ) (bits : ℕ → Bool) : + execution divisionProgram O (divisionConfig (divRegisters R xs ys zs ws [] []) 3 q c) bits + (divCheckCost ys zs)=divisionConfig (divRegisters R xs ys zs ws [] []) + (if binaryValue zs simpa [relabelConfig,divCheckConfig,divisionConfig,divisionCheckLabel] using h +lemma division_sub_run (O : IndependenceOracle n) (R : Fin (k+8) → List Bool) + (xs ys zs ws : List Bool) (hzy : binaryValue ys≤binaryValue zs) (q c : ℕ) (bits : ℕ → Bool) : + execution divisionProgram O (divisionConfig (divRegisters R xs ys zs ws [] []) 27 q c) bits + (divSubtractCost ys zs)=divisionConfig (divRegisters R xs ys (subDigits false zs ys) ws [] []) + 51 q (c+divSubtractCost ys zs) := by + have h := execution_relabel_before_halt (divSubtract : Program k 24) divisionProgram divisionSubLabel + (lastLabel 24) divSubtract_exit division_sub_table O + (divSubtractConfig (divRegisters R xs ys zs ws [] []) 0 q c) bits (divSubtractCost ys zs) + (by rw [divSubtract_run O R xs ys zs ws hzy]; rfl) + rw [divSubtract_run O R xs ys zs ws hzy] at h + simpa [relabelConfig,divSubtractConfig,divisionConfig,divisionSubLabel] using h + +def divisionRemainder (ys zs : List Bool) : List Bool := + if binaryValue zs simp [execution,machineStep,divisionProgram,divisionConfig, + divRegisters_update0,divRegisters_update2,divRegisters] + unfold divisionDigitCost + rw [show 2+divCheckCost ys (x::zs)+(if binaryValue (x::zs) (zs,ws) + | x::xs,ys,zs,ws => divisionWords xs ys (divisionRemainder ys (x::zs)) (divisionDigit ys (x::zs)::ws) +def divisionCost : List Bool → List Bool → List Bool → ℕ + | [],_,_ => 1 + | x::xs,ys,zs => divisionDigitCost ys (x::zs)+divisionCost xs ys (divisionRemainder ys (x::zs)) + +theorem division_machine_run (O : IndependenceOracle n) (R : Fin (k+8) → List Bool) + (xs ys zs ws : List Bool) (q c : ℕ) (bits : ℕ → Bool) : + execution divisionProgram O (divisionConfig (divRegisters R xs ys zs ws [] []) 0 q c) bits + (divisionCost xs ys zs)=divisionConfig + (divRegisters R [] ys (divisionWords xs ys zs ws).1 (divisionWords xs ys zs ws).2 [] []) + 53 q (c+divisionCost xs ys zs) := by + induction xs generalizing zs ws c bits with + | nil => simp [divisionCost,divisionWords,execution,machineStep,divisionProgram,divisionConfig,divRegisters] + | cons x xs ih => + rw [divisionCost,execution_add,division_digit_run,ih] + simp only [divisionWords,Nat.add_assoc] + +lemma binaryValue_append (xs ys : List Bool) : + binaryValue (xs++ys)=binaryValue xs+2^xs.length*binaryValue ys := by + induction xs with + | nil => simp [binaryValue] + | cons x xs ih => + simp only [List.cons_append,binaryValue,ih,List.length_cons,pow_succ] + ring + +def streamValue : List Bool → ℕ → ℕ + | [],a => a + | x::xs,a => streamValue xs (2*a+(if x then 1 else 0)) +lemma streamValue_eq (xs : List Bool) (a : ℕ) : + streamValue xs a=binaryValue xs.reverse+2^xs.length*a := by + induction xs generalizing a with + | nil => simp [streamValue,binaryValue] + | cons x xs ih => + simp only [streamValue,ih,List.reverse_cons,binaryValue_append,List.length_reverse, + List.length_cons,pow_succ,binaryValue] + ring +lemma division_step_math (x : Bool) (ys zs : List Bool) (hr : binaryValue zs simp [binaryValue] at hv <;> omega +lemma divisionWords_invariant (xs ys zs ws : List Bool) (hr : binaryValue zs exact ⟨rfl,hr⟩ + | cons x xs ih => + have hd := division_step_math x ys zs hr + have hi := ih (divisionRemainder ys (x::zs)) (divisionDigit ys (x::zs)::ws) hd.1 + simp only [divisionWords] + refine ⟨?_,hi.2⟩ + rw [hi.1,streamValue] + congr 1 + simp only [binaryValue] + have hv := hd.2 + simp only [binaryValue] at hv + nlinarith + +theorem divisionWords_correct (xs ys : List Bool) (hy : 0 + induction ys generalizing c with + | nil => simp [subDigits] + | cons y ys ih => simp [subDigits,ih] + | cons x xs ih => + cases ys with + | nil => simp [subDigits,ih] + | cons y ys => simp [subDigits,ih,max_add_add_right] +lemma divisionRemainder_length (ys zs : List Bool) : + (divisionRemainder ys zs).length ≤ max zs.length ys.length := by + unfold divisionRemainder + split_ifs + · exact Nat.le_max_left _ _ + · exact (subDigits_length false zs ys).le +lemma divCheckCost_bound (ys zs : List Bool) : + divCheckCost ys zs≤12*max ys.length zs.length+6 := by + have hy := Nat.le_max_left ys.length zs.length + have hz := Nat.le_max_right ys.length zs.length + unfold divCheckCost + rw [Nat.max_comm zs.length ys.length] + omega +lemma divSubtractCost_bound (ys zs : List Bool) : + divSubtractCost ys zs≤13*max ys.length zs.length+6 := by + have hy := Nat.le_max_left ys.length zs.length + have hz := Nat.le_max_right ys.length zs.length + have h := (subDigits_length_cost false zs ys).2 + unfold divSubtractCost + rw [subDigits_length,Nat.max_comm zs.length ys.length] + omega +lemma divisionDigitCost_bound (ys zs : List Bool) : + divisionDigitCost ys zs≤25*max ys.length zs.length+15 := by + have hc := divCheckCost_bound ys zs + have hs := divSubtractCost_bound ys zs + unfold divisionDigitCost + split_ifs <;> omega +lemma divisionCost_bound (xs ys zs : List Bool) (K : ℕ) (hy : ys.length≤K) (hz : zs.length≤K) : + divisionCost xs ys zs≤40*xs.length*(K+xs.length+1)+1 := by + induction xs generalizing zs K with + | nil => simp [divisionCost] + | cons x xs ih => + have hl : max ys.length (x::zs).length≤K+1 := by simp only [List.length_cons]; omega + have hr : (divisionRemainder ys (x::zs)).length≤K+1 := by + have hh := divisionRemainder_length ys (x::zs) + rw [Nat.max_comm] at hh + exact hh.trans hl + have hc := (divisionDigitCost_bound ys (x::zs)).trans (Nat.add_le_add_right (Nat.mul_le_mul_left 25 hl) 15) + have ht := ih (divisionRemainder ys (x::zs)) (K+1) (by omega) hr + simp only [divisionCost,List.length_cons] + nlinarith + +theorem division_block (O : IndependenceOracle n) (R : Fin (k+8) → List Bool) + (xs ys : List Bool) (hy : 0 .push (e i) b j + | .pop i a b c => .pop (e i) a b c + | .coin a b => .coin a b + | .query w i a b => .query w (e i) a b + | .halt => .halt +def renameProgram (e : Equiv.Perm (Fin (k+8))) (P : Program k s) : Program k s := + fun i => (P i).renameRegisters e +def renameConfig (e : Equiv.Perm (Fin (k+8))) (c : MachineConfig k s) : MachineConfig k s := + ⟨fun i => c.registers (e.symm i),c.control,c.output,c.oracleCalls,c.bitOperations⟩ +lemma rename_update (e : Equiv.Perm (Fin (k+8))) (R : Fin (k+8) → List Bool) (j : Fin (k+8)) (z : List Bool) : + Function.update (fun i => R (e.symm i)) (e j) z=(fun i => Function.update R j z (e.symm i)) := by + funext i + by_cases hi : i=e j + · subst i; simp + · have hj : e.symm i≠j := by intro h; apply hi; simpa using congrArg e h + simp [Function.update,hi,hj] +lemma machineStep_rename (e : Equiv.Perm (Fin (k+8))) (P : Program k s) + (O : IndependenceOracle n) (b : Bool) (c : MachineConfig k s) (h : P c.control≠.halt) : + machineStep (renameProgram e P) O b (renameConfig e c)=renameConfig e (machineStep P O b c) := by + cases hc : c.output with + | some z => simp [machineStep,renameConfig,hc] + | none => + cases hp : P c.control with + | push i b j => simp [machineStep,renameConfig,hc,renameProgram,hp,Instruction.renameRegisters,rename_update] + | pop i x y z => + cases hl : c.registers i with + | nil => simp [machineStep,renameConfig,hc,renameProgram,hp,Instruction.renameRegisters,hl] + | cons a l => cases a <;> simp [machineStep,renameConfig,hc,renameProgram,hp,Instruction.renameRegisters,hl,rename_update] + | coin x y => cases b <;> simp [machineStep,renameConfig,hc,renameProgram,hp,Instruction.renameRegisters] + | query w i x y => + by_cases hl : (c.registers i).length=n + · simp [machineStep,renameConfig,hc,renameProgram,hp,Instruction.renameRegisters,hl] + · simp [machineStep,renameConfig,hc,renameProgram,hp,Instruction.renameRegisters,hl] + | halt => exact (h hp).elim + +theorem execution_rename_before_halt (e : Equiv.Perm (Fin (k+8))) (P : Program k s) + (O : IndependenceOracle n) (c : MachineConfig k s) (bits : ℕ → Bool) (u : ℕ) + (hu : (execution P O c bits u).output=none) : + execution (renameProgram e P) O (renameConfig e c) bits u=renameConfig e (execution P O c bits u) := by + induction u with + | zero => rfl + | succ u ih => + have hn := machineStep_none_pre P O (bits u) (execution P O c bits u) hu + have hh := machineStep_none_not_halt P O (bits u) (execution P O c bits u) hu + simp only [execution,ih hn] + exact machineStep_rename e P O _ _ hh + +end + +variable {k n : ℕ} +def bitFrame : List Bool → List Bool + | [] => [true] + | b::bs => false::b::bitFrame bs +lemma bitFrame_length (bs : List Bool) : (bitFrame bs).length=2*bs.length+1 := by + induction bs with + | nil => rfl + | cons b bs ih => simp [bitFrame,ih]; omega +lemma bitFrame_append (xs ys : List Bool) : + bitFrame (xs++ys)=(xs.flatMap (fun b => [false,b]))++bitFrame ys := by + induction xs with + | nil => rfl + | cons x xs ih => simp [bitFrame,ih] +lemma bitFrame_reverse_cons (b : Bool) (bs : List Bool) : + bitFrame (b::bs).reverse=(bs.reverse.flatMap (fun x => [false,x]))++[false,b,true] := by + rw [List.reverse_cons,bitFrame_append] + rfl + +def framePackProgram (a d : Fin (k+8)) : Program k 5 := fun pc => + match pc.val with + | 0 => .push d true 1 + | 1 => .pop a 5 2 3 + | 2 => .push d false 4 + | 3 => .push d true 4 + | 4 => .push d false 1 + | _ => .halt +def frameConfig (R : Fin (k+8) → List Bool) (pc : Fin 6) (q c : ℕ) : MachineConfig k 5 := + ⟨R,pc,none,q,c⟩ +lemma frame_pack_scan (a d : Fin (k+8)) (had : a≠d) (O : IndependenceOracle n) + (R : Fin (k+8) → List Bool) (xs ts : List Bool) (q c : ℕ) (bits : ℕ → Bool) : + execution (framePackProgram a d) O (frameConfig (pairRegisters R a d xs ts) 1 q c) bits + (3*xs.length+1)=frameConfig (pairRegisters R a d [] + ((xs.reverse.flatMap (fun b => [false,b]))++ts)) 5 q (c+3*xs.length+1) := by + induction xs generalizing ts c bits with + | nil => simp [execution,machineStep,framePackProgram,frameConfig,pairRegisters_a _ _ _ had] + | cons x xs ih => + have ht : execution (framePackProgram a d) O (frameConfig (pairRegisters R a d (x::xs) ts) 1 q c) bits 3= + frameConfig (pairRegisters R a d xs (false::x::ts)) 1 q (c+3) := by + cases x <;> simp [execution,machineStep,framePackProgram,frameConfig, + pairRegisters_a _ _ _ had,pairRegisters_b,pairRegisters_update_a _ _ _ had,pairRegisters_update_b] + rw [List.length_cons,show 3*(xs.length+1)+1=3+(3*xs.length+1) by omega,execution_add,ht,ih] + simp only [List.reverse_cons,List.flatMap_append,List.flatMap_singleton,List.append_assoc,List.cons_append,List.nil_append] + congr 1 ; omega + +theorem frame_pack_block (a d : Fin (k+8)) (had : a≠d) (O : IndependenceOracle n) + (R : Fin (k+8) → List Bool) (xs ts : List Bool) (q c : ℕ) (bits : ℕ → Bool) : + execution (framePackProgram a d) O (frameConfig (pairRegisters R a d xs ts) 0 q c) bits + (3*xs.length+2)=frameConfig (pairRegisters R a d [] (bitFrame xs.reverse++ts)) 5 q (c+3*xs.length+2) := by + have ht : execution (framePackProgram a d) O (frameConfig (pairRegisters R a d xs ts) 0 q c) bits 1= + frameConfig (pairRegisters R a d xs (true::ts)) 1 q (c+1) := by + simp [execution,machineStep,framePackProgram,frameConfig,pairRegisters_b,pairRegisters_update_b] + rw [show 3*xs.length+2=1+(3*xs.length+1) by omega,execution_add,ht,frame_pack_scan a d had] + have hf : bitFrame xs.reverse=(xs.reverse.flatMap (fun b => [false,b]))++[true] := by + simpa [bitFrame] using bitFrame_append xs.reverse [] + simp only [hf,List.append_assoc,List.singleton_append] + congr 1 ; omega + +def frameUnpackProgram (a d : Fin (k+8)) : Program k 5 := fun pc => + match pc.val with + | 0 => .pop a 5 1 4 + | 1 => .pop a 5 2 3 + | 2 => .push d false 0 + | 3 => .push d true 0 + | _ => .halt + +theorem frame_unpack_block (a d : Fin (k+8)) (had : a≠d) (O : IndependenceOracle n) + (R : Fin (k+8) → List Bool) (xs ts zs : List Bool) (q c : ℕ) (bits : ℕ → Bool) : + execution (frameUnpackProgram a d) O + (frameConfig (pairRegisters R a d (bitFrame xs++ts) zs) 0 q c) bits (3*xs.length+1)= + frameConfig (pairRegisters R a d ts (xs.reverse++zs)) 4 q (c+3*xs.length+1) := by + induction xs generalizing zs c bits with + | nil => simp [bitFrame,execution,machineStep,frameUnpackProgram,frameConfig, + pairRegisters_a _ _ _ had,pairRegisters_update_a _ _ _ had] + | cons x xs ih => + have ht : execution (frameUnpackProgram a d) O + (frameConfig (pairRegisters R a d (bitFrame (x::xs)++ts) zs) 0 q c) bits 3= + frameConfig (pairRegisters R a d (bitFrame xs++ts) (x::zs)) 0 q (c+3) := by + cases x <;> simp [bitFrame,execution,machineStep,frameUnpackProgram,frameConfig, + pairRegisters_a _ _ _ had,pairRegisters_b,pairRegisters_update_a _ _ _ had,pairRegisters_update_b] + rw [List.length_cons,show 3*(xs.length+1)+1=3+(3*xs.length+1) by omega,execution_add,ht,ih] + simp only [List.reverse_cons,List.append_assoc,List.singleton_append] + congr 1 ; omega + +theorem frame_unpack_packed (a d : Fin (k+8)) (had : a≠d) (O : IndependenceOracle n) + (R : Fin (k+8) → List Bool) (xs ts : List Bool) (q c : ℕ) (bits : ℕ → Bool) : + execution (frameUnpackProgram a d) O + (frameConfig (pairRegisters R a d (bitFrame xs.reverse++ts) []) 0 q c) bits (3*xs.length+1)= + frameConfig (pairRegisters R a d ts xs) 4 q (c+3*xs.length+1) := by + simpa using frame_unpack_block a d had O R xs.reverse ts [] q c bits + +end + +namespace MachineCode +abbrev Registers (k : ℕ) := Fin (k+8) → List Bool +structure Block (k : ℕ) where + size : ℕ + code : Program k size + exit_halt : code (lastLabel size) = .halt + +def state {k s : ℕ} (R : Registers k) (pc : Fin (s+1)) (q w : ℕ) : MachineConfig k s := + ⟨R,pc,none,q,w⟩ + +def Runs {k n : ℕ} (p : Block k) (O : IndependenceOracle n) (bits : ℕ → Bool) + (R R' : Registers k) (t q w : ℕ) : Prop := + ∀ q₀ w₀, execution p.code O (state R 0 q₀ w₀) bits t = + state R' (lastLabel p.size) (q₀+q) (w₀+w) + +def skip (k : ℕ) : Block k := ⟨0,fun _ => .halt,rfl⟩ +lemma runs_skip {k n : ℕ} (O : IndependenceOracle n) (bits : ℕ → Bool) (R : Registers k) : + Runs (skip k) O bits R R 0 0 0 := by + intro q w + rfl + +def seq {k : ℕ} (p q : Block k) : Block k where + size := p.size+q.size + code := concatProgram p.code q.code + exit_halt := by + have he : lastLabel (p.size+q.size)=secondLabel p.size q.size (lastLabel q.size) := by + apply Fin.ext; rfl + rw [he,concatProgram_second,q.exit_halt] + rfl +lemma runs_seq {k n : ℕ} {p q : Block k} (O : IndependenceOracle n) (bits : ℕ → Bool) + {R S T : Registers k} {u v a b c d : ℕ} + (hp : Runs p O bits R S u a b) + (hq : Runs q O (fun i => bits (u+i)) S T v c d) : + Runs (seq p q) O bits R T (u+v) (a+c) (b+d) := by + intro q₀ w₀ + have ep := hp q₀ w₀ + have en : (execution p.code O (state R 0 q₀ w₀) bits u).output=none := by rw [ep]; rfl + have ec : (execution p.code O (state R 0 q₀ w₀) bits u).control=lastLabel p.size := by rw [ep]; rfl + have h := concat_run p.code q.code p.exit_halt O (state R 0 q₀ w₀) bits u v en ec + rw [ep] at h + have eh := hq (q₀+a) (w₀+b) + change execution q.code O (restartControl (state S (lastLabel p.size) (q₀+a) (w₀+b)) 0) + (fun i => bits (u+i)) v = _ at eh + rw [eh] at h + change execution (concatProgram p.code q.code) O (state R 0 q₀ w₀) bits (u+v) = + state T (lastLabel (p.size+q.size)) (q₀+(a+c)) (w₀+(b+d)) + simpa [state,relabelConfig,firstLabel,secondLabel,lastLabel,Nat.add_assoc] using h + +def push {k : ℕ} (a : Fin (k+8)) (b : Bool) : Block k where + size := 1 + code := fun pc => if pc=0 then .push a b 1 else .halt + exit_halt := by simp [lastLabel] +lemma runs_push {k n : ℕ} (O : IndependenceOracle n) (bits : ℕ → Bool) + (R : Registers k) (a : Fin (k+8)) (b : Bool) : + Runs (push a b) O bits R (Function.update R a (b::R a)) 1 0 1 := by + intro q w + rfl + +inductive Test (k : ℕ) where + | pop (a : Fin (k+8)) (empty zero one : Bool) + | query (which : Bool) (a : Fin (k+8)) + | coin + +def Test.instruction {k s : ℕ} (test : Test k) (no yes : Fin (s+1)) : Instruction k s := + match test with + | .pop a e z o => .pop a (if e then yes else no) (if z then yes else no) (if o then yes else no) + | .query which a => .query which a no yes + | .coin => .coin no yes + +def Test.result {k n : ℕ} (test : Test k) (O : IndependenceOracle n) (bit : Bool) + (R : Registers k) : Option (Bool × Registers k) := + match test with + | .pop a e z o => match R a with + | [] => some (e,R) + | b::xs => some ((if b then o else z),Function.update R a xs) + | .query which a => if (R a).length=n then + some (O which (fun i => (R a)[i.val]?.getD false),R) else none + | .coin => some (bit,R) + +def Test.queries {k : ℕ} : Test k → ℕ + | .query _ _ => 1 + | _ => 0 + +def Test.work {k : ℕ} (test : Test k) (n : ℕ) (R : Registers k) : ℕ := + match test with + | .query _ a => (R a).length+n+1 + | _ => 1 + +lemma test_step {k s n : ℕ} (test : Test k) (O : IndependenceOracle n) (bit : Bool) + (P : Program k s) (pc no yes : Fin (s+1)) (hP : P pc=test.instruction no yes) + (R R' : Registers k) (b : Bool) (h : test.result O bit R=some (b,R')) (q w : ℕ) : + machineStep P O bit (state R pc q w)= + state R' (if b then yes else no) (q+test.queries) (w+test.work n R) := by + cases test with + | pop a e z o => + cases ha : R a with + | nil => + simp only [Test.result,ha,Option.some.injEq,Prod.mk.injEq] at h + rcases h with ⟨rfl,rfl⟩ + simp [machineStep,state,hP,Test.instruction,ha,Test.queries,Test.work] + | cons x xs => + simp only [Test.result,ha,Option.some.injEq,Prod.mk.injEq] at h + rcases h with ⟨rfl,rfl⟩ + cases x <;> simp [machineStep,state,hP,Test.instruction,ha,Test.queries,Test.work] + | query which a => + simp only [Test.result] at h + split_ifs at h with hn + · simp only [Option.some.injEq,Prod.mk.injEq] at h + rcases h with ⟨rfl,rfl⟩ + simp [machineStep,state,hP,Test.instruction,hn,Test.queries,Test.work,Nat.add_assoc] + | coin => + simp only [Test.result,Option.some.injEq,Prod.mk.injEq] at h + rcases h with ⟨rfl,rfl⟩ + simp [machineStep,state,hP,Test.instruction,Test.queries,Test.work] + +def noLabel (s t : ℕ) (i : Fin (s+1)) : Fin (s+t+2) := + if i.val=s then lastLabel (s+t+1) else ⟨i.val+1,by omega⟩ +def yesLabel (s t : ℕ) (i : Fin (t+1)) : Fin (s+t+2) := + if i.val=t then lastLabel (s+t+1) else ⟨s+i.val+1,by omega⟩ +lemma noLabel_exit (s t : ℕ) : noLabel s t (lastLabel s)=lastLabel (s+t+1) := by + simp [noLabel,lastLabel] +lemma yesLabel_exit (s t : ℕ) : yesLabel s t (lastLabel t)=lastLabel (s+t+1) := by + simp [yesLabel,lastLabel] + +def fork {k : ℕ} (test : Test k) (p q : Block k) : Block k where + size := p.size+q.size+1 + code := fun pc => + if pc.val=0 then test.instruction (noLabel p.size q.size 0) (yesLabel p.size q.size 0) + else if h : pc.val≤p.size then + (p.code ⟨pc.val-1,by omega⟩).relabel (noLabel p.size q.size) + else if h : pc.val≤p.size+q.size then + (q.code ⟨pc.val-p.size-1,by omega⟩).relabel (yesLabel p.size q.size) + else .halt + exit_halt := by simp [lastLabel,show ¬p.size+q.size+1≤p.size by omega] +lemma fork_head {k : ℕ} (test : Test k) (p q : Block k) : + (fork test p q).code 0=test.instruction (noLabel p.size q.size 0) (yesLabel p.size q.size 0) := by + simp [fork] +lemma fork_no {k : ℕ} (test : Test k) (p q : Block k) (i : Fin (p.size+1)) (hi : i≠lastLabel p.size) : + (fork test p q).code (noLabel p.size q.size i)=(p.code i).relabel (noLabel p.size q.size) := by + have hv : i.val≠p.size := by intro h; exact hi (Fin.ext h) + have hv' : i.val+1≤p.size := by omega + simp [fork,noLabel,hv,hv'] +lemma fork_yes {k : ℕ} (test : Test k) (p q : Block k) (i : Fin (q.size+1)) (hi : i≠lastLabel q.size) : + (fork test p q).code (yesLabel p.size q.size i)=(q.code i).relabel (yesLabel p.size q.size) := by + have hv : i.val≠q.size := by intro h; exact hi (Fin.ext h) + have hv' : p.size+i.val+1≤p.size+q.size := by omega + simp [fork,yesLabel,hv,show ¬p.size+i.val+1≤p.size by omega,hv',show p.size+i.val+1-p.size-1=i.val by omega] + +lemma fork_run_no {k n : ℕ} (test : Test k) (p q : Block k) (O : IndependenceOracle n) + (bits : ℕ → Bool) {R S T : Registers k} {t a b : ℕ} + (ht : test.result O (bits 0) R=some (false,S)) + (hp : Runs p O (fun i => bits (1+i)) S T t a b) : + Runs (fork test p q) O bits R T (1+t) (test.queries+a) (test.work n R+b) := by + intro q₀ w₀ + have first := test_step test O (bits 0) (fork test p q).code 0 _ _ (fork_head test p q) R S false ht q₀ w₀ + have er := hp (q₀+test.queries) (w₀+test.work n R) + have en : (execution p.code O (state S 0 (q₀+test.queries) (w₀+test.work n R)) + (fun i => bits (1+i)) t).output=none := by rw [er]; rfl + have rel := execution_relabel_before_halt p.code (fork test p q).code (noLabel p.size q.size) + (lastLabel p.size) p.exit_halt (fork_no test p q) O _ (fun i => bits (1+i)) t en + rw [er] at rel + rw [execution_add] + change execution (fork test p q).code O + (machineStep (fork test p q).code O (bits 0) (state R 0 q₀ w₀)) (fun i => bits (1+i)) t = _ + rw [first] + change execution (fork test p q).code O + (relabelConfig (noLabel p.size q.size) (state S 0 (q₀+test.queries) (w₀+test.work n R))) + (fun i => bits (1+i)) t = _ + rw [rel] + simp only [state,relabelConfig,noLabel_exit,Nat.add_assoc] + rfl +lemma fork_run_yes {k n : ℕ} (test : Test k) (p q : Block k) (O : IndependenceOracle n) + (bits : ℕ → Bool) {R S T : Registers k} {t a b : ℕ} + (ht : test.result O (bits 0) R=some (true,S)) + (hq : Runs q O (fun i => bits (1+i)) S T t a b) : + Runs (fork test p q) O bits R T (1+t) (test.queries+a) (test.work n R+b) := by + intro q₀ w₀ + have first := test_step test O (bits 0) (fork test p q).code 0 _ _ (fork_head test p q) R S true ht q₀ w₀ + have er := hq (q₀+test.queries) (w₀+test.work n R) + have en : (execution q.code O (state S 0 (q₀+test.queries) (w₀+test.work n R)) + (fun i => bits (1+i)) t).output=none := by rw [er]; rfl + have rel := execution_relabel_before_halt q.code (fork test p q).code (yesLabel p.size q.size) + (lastLabel q.size) q.exit_halt (fork_yes test p q) O _ (fun i => bits (1+i)) t en + rw [er] at rel + rw [execution_add] + change execution (fork test p q).code O + (machineStep (fork test p q).code O (bits 0) (state R 0 q₀ w₀)) (fun i => bits (1+i)) t = _ + rw [first] + change execution (fork test p q).code O + (relabelConfig (yesLabel p.size q.size) (state S 0 (q₀+test.queries) (w₀+test.work n R))) + (fun i => bits (1+i)) t = _ + rw [rel] + simp only [state,relabelConfig,yesLabel_exit,Nat.add_assoc] + rfl + +end MachineCode + +section MachineLoops +variable {k s n : ℕ} +def loopLabel (s : ℕ) (i : Fin (s+1)) : Fin (s+2) := + if h : i.val=s then 0 else ⟨i.val+1,by omega⟩ +def repeatProgram (P : Program k s) (a : Fin (k+8)) : Program k (s+1) := fun pc => + if pc.val=0 then .pop a (lastLabel (s+1)) (loopLabel s 0) (loopLabel s 0) + else if h : pc.val≤ s then (P ⟨pc.val-1,by omega⟩).relabel (loopLabel s) + else .halt +lemma repeatProgram_body (P : Program k s) (a : Fin (k+8)) (i : Fin (s+1)) + (hi : i≠lastLabel s) : repeatProgram P a (loopLabel s i)=(P i).relabel (loopLabel s) := by + have hiv : i.val≠s := by intro h; apply hi; exact Fin.ext h + simp [repeatProgram,loopLabel,hiv,show i.val+1≤ s by omega] +lemma loopLabel_last (s : ℕ) : loopLabel s (lastLabel s)=0 := by simp [loopLabel,lastLabel] +def loopConfig (R : Fin (k+8) → List Bool) (pc : Fin (s+1)) (q c : ℕ) : MachineConfig k s := + ⟨R,pc,none,q,c⟩ +lemma repeatProgram_pop (P : Program k s) (a : Fin (k+8)) (O : IndependenceOracle n) + (R : Fin (k+8) → List Bool) (x : Bool) (xs : List Bool) (q c : ℕ) (bits : ℕ → Bool) : + execution (repeatProgram P a) O (loopConfig (Function.update R a (x::xs)) 0 q c) bits 1= + relabelConfig (loopLabel s) (loopConfig (Function.update R a xs) 0 q (c+1)) := by + cases x <;> simp [execution,machineStep,repeatProgram,loopConfig,relabelConfig] +lemma repeatProgram_empty (P : Program k s) (a : Fin (k+8)) (O : IndependenceOracle n) + (R : Fin (k+8) → List Bool) (q c : ℕ) (bits : ℕ → Bool) : + execution (repeatProgram P a) O (loopConfig (Function.update R a []) 0 q c) bits 1= + loopConfig (Function.update R a []) (lastLabel (s+1)) q (c+1) := by + simp [execution,machineStep,repeatProgram,loopConfig] +def loopState {A : Type*} (f : A → A) : ℕ → A → A + | 0,x => x + | m+1,x => loopState f m (f x) +def loopSum {A : Type*} (f : A → A) (g : A → ℕ) : ℕ → A → ℕ + | 0,_ => 0 + | m+1,x => g x+loopSum f g m (f x) + +theorem repeat_block {A : Type*} (P : Program k s) (a : Fin (k+8)) + (hexit : P (lastLabel s)=.halt) (O : IndependenceOracle n) + (encode : A → Fin (k+8) → List Bool) (f : A → A) (ticks queries work : A → ℕ) + (body : ∀ (v : A) (xs : List Bool) (q c : ℕ) (bits : ℕ → Bool), + execution P O (loopConfig (Function.update (encode v) a xs) 0 q c) bits (ticks v)= + loopConfig (Function.update (encode (f v)) a xs) (lastLabel s) (q+queries v) (c+work v)) + (v : A) (xs : List Bool) (q c : ℕ) (bits : ℕ → Bool) : + execution (repeatProgram P a) O (loopConfig (Function.update (encode v) a xs) 0 q c) bits + (loopSum f (fun v => ticks v+1) xs.length v+1)= + loopConfig (Function.update (encode (loopState f xs.length v)) a []) (lastLabel (s+1)) + (q+loopSum f queries xs.length v) (c+loopSum f (fun v => work v+1) xs.length v+1) := by + induction xs generalizing v q c bits with + | nil => simpa [loopSum,loopState] using repeatProgram_empty P a O (encode v) q c bits + | cons x xs ih => + have hb := body v xs q (c+1) (fun i => bits (1+i)) + have hnone : (execution P O (loopConfig (Function.update (encode v) a xs) 0 q (c+1)) + (fun i => bits (1+i)) (ticks v)).output=none := by rw [hb]; rfl + have hl := execution_relabel_before_halt P (repeatProgram P a) (loopLabel s) (lastLabel s) + hexit (repeatProgram_body P a) O _ (fun i => bits (1+i)) (ticks v) hnone + have hfirst : execution (repeatProgram P a) O + (loopConfig (Function.update (encode v) a (x::xs)) 0 q c) bits (1+ticks v)= + loopConfig (Function.update (encode (f v)) a xs) 0 (q+queries v) (c+1+work v) := by + rw [execution_add,repeatProgram_pop,hl,hb] + simp [relabelConfig,loopConfig,loopLabel_last] + simp only [List.length_cons,loopSum,loopState] + rw [show ticks v+1+loopSum f (fun v => ticks v+1) xs.length (f v)+1= + (1+ticks v)+(loopSum f (fun v => ticks v+1) xs.length (f v)+1) by omega, + execution_add,hfirst,ih] + congr 1 <;> omega +lemma loopSum_le {A : Type*} (f : A → A) (g : A → ℕ) (B : ℕ) (hg : ∀ x,g x≤B) + (m : ℕ) (x : A) : loopSum f g m x≤ m*B := by + induction m generalizing x with + | zero => simp [loopSum] + | succ m ih => simpa [loopSum,Nat.succ_mul,Nat.add_comm] using Nat.add_le_add (hg x) (ih (f x)) +end MachineLoops + +section MachineMove +variable {k n : ℕ} +def reverseProgram (a d : Fin (k+8)) : Program k 3 := fun pc => + match pc.val with + | 0 => .pop a 3 1 2 + | 1 => .push d false 0 + | 2 => .push d true 0 + | _ => .halt +def reverseConfig (R : Fin (k+8) → List Bool) (pc : Fin 4) (q c : ℕ) : MachineConfig k 3 := + ⟨R,pc,none,q,c⟩ +theorem reverse_block (a d : Fin (k+8)) (had : a≠d) (O : IndependenceOracle n) + (R : Fin (k+8) → List Bool) (xs ys : List Bool) (q c : ℕ) (bits : ℕ → Bool) : + execution (reverseProgram a d) O (reverseConfig (pairRegisters R a d xs ys) 0 q c) bits (2*xs.length+1)= + reverseConfig (pairRegisters R a d [] (xs.reverse++ys)) 3 q (c+2*xs.length+1) := by + induction xs generalizing ys c bits with + | nil => simp [execution,machineStep,reverseProgram,reverseConfig,pairRegisters_a _ _ _ had] + | cons x xs ih => + have ht : execution (reverseProgram a d) O (reverseConfig (pairRegisters R a d (x::xs) ys) 0 q c) bits 2= + reverseConfig (pairRegisters R a d xs (x::ys)) 0 q (c+2) := by + cases x <;> simp [execution,machineStep,reverseProgram,reverseConfig,pairRegisters_a _ _ _ had,pairRegisters_b, + pairRegisters_update_a _ _ _ had,pairRegisters_update_b] + rw [List.length_cons,show 2*(xs.length+1)+1=2+(2*xs.length+1) by omega,execution_add,ht,ih] + simp only [List.reverse_cons,List.append_assoc,List.singleton_append] + congr 1; omega +def clearProgram (a : Fin (k+8)) : Program k 1 := fun pc => if pc.val=0 then .pop a 1 0 0 else .halt +def clearConfig (R : Fin (k+8) → List Bool) (pc : Fin 2) (q c : ℕ) : MachineConfig k 1 := + ⟨R,pc,none,q,c⟩ +theorem clear_block (a : Fin (k+8)) (O : IndependenceOracle n) + (R : Fin (k+8) → List Bool) (xs : List Bool) (q c : ℕ) (bits : ℕ → Bool) : + execution (clearProgram a) O (clearConfig (Function.update R a xs) 0 q c) bits (xs.length+1)= + clearConfig (Function.update R a []) 1 q (c+xs.length+1) := by + induction xs generalizing c bits with + | nil => simp [execution,machineStep,clearProgram,clearConfig] + | cons x xs ih => + have ht : execution (clearProgram a) O (clearConfig (Function.update R a (x::xs)) 0 q c) bits 1= + clearConfig (Function.update R a xs) 0 q (c+1) := by + cases x <;> simp [execution,machineStep,clearProgram,clearConfig] + rw [List.length_cons,show xs.length+1+1=1+(xs.length+1) by omega,execution_add,ht,ih] + congr 1; omega +def moveProgram (a b d : Fin (k+8)) : Program k 6 := concatProgram (reverseProgram a b) (reverseProgram b d) +def moveConfig (R : Fin (k+8) → List Bool) (pc : Fin 7) (q c : ℕ) : MachineConfig k 6 := + ⟨R,pc,none,q,c⟩ +lemma triple_pair_ab (R : Fin (k+8) → List Bool) (a b d : Fin (k+8)) + (hab : a≠b) (had : a≠d) (hbd : b≠d) (xs ys zs us vs : List Bool) : + pairRegisters (tripleRegisters R a b d xs ys zs) a b us vs=tripleRegisters R a b d us vs zs := by + simp only [pairRegisters,tripleRegisters_update_a _ _ _ _ hab had,tripleRegisters_update_b _ _ _ _ hbd] +lemma triple_pair_bd (R : Fin (k+8) → List Bool) (a b d : Fin (k+8)) + (hbd : b≠d) (xs ys zs us vs : List Bool) : + pairRegisters (tripleRegisters R a b d xs ys zs) b d us vs=tripleRegisters R a b d xs us vs := by + simp only [pairRegisters,tripleRegisters_update_b _ _ _ _ hbd,tripleRegisters_update_d] +theorem move_block (a b d : Fin (k+8)) (hab : a≠b) (had : a≠d) (hbd : b≠d) + (O : IndependenceOracle n) (R : Fin (k+8) → List Bool) (xs ys : List Bool) + (q c : ℕ) (bits : ℕ → Bool) : + execution (moveProgram a b d) O (moveConfig (tripleRegisters R a b d xs [] ys) 0 q c) bits (4*xs.length+2)= + moveConfig (tripleRegisters R a b d [] [] (xs++ys)) 6 q (c+4*xs.length+2) := by + have h1 := reverse_block a b hab O (tripleRegisters R a b d xs [] ys) xs [] q c bits + simp only [triple_pair_ab _ _ _ _ hab had hbd,List.append_nil] at h1 + have h2 := reverse_block b d hbd O (tripleRegisters R a b d [] xs.reverse ys) xs.reverse ys q + (c+2*xs.length+1) (fun i => bits (2*xs.length+1+i)) + simp only [triple_pair_bd _ _ _ _ hbd,List.reverse_reverse,List.length_reverse] at h2 + have h := concat_run (reverseProgram a b) (reverseProgram b d) (by rfl) O + (reverseConfig (tripleRegisters R a b d xs [] ys) 0 q c) bits (2*xs.length+1) (2*xs.length+1) + (by rw [h1]; rfl) (by rw [h1]; rfl) + rw [h1] at h + change execution (moveProgram a b d) O (moveConfig (tripleRegisters R a b d xs [] ys) 0 q c) bits + ((2*xs.length+1)+(2*xs.length+1))=relabelConfig (secondLabel 3 3) + (execution (reverseProgram b d) O (reverseConfig (tripleRegisters R a b d [] xs.reverse ys) 0 q (c+2*xs.length+1)) + (fun i => bits (2*xs.length+1+i)) (2*xs.length+1)) at h + rw [h2] at h + convert h using 1 <;> simp only [relabelConfig,reverseConfig,moveConfig,secondLabel, + show 2*xs.length+1+(2*xs.length+1)=4*xs.length+2 by omega, + show c+2*xs.length+1+2*xs.length+1=c+4*xs.length+2 by omega] + rfl +end MachineMove + +namespace MachineCode + +def reverse {k : ℕ} (a d : Fin (k+8)) : Block k := + ⟨3,reverseProgram a d,rfl⟩ +def clear {k : ℕ} (a : Fin (k+8)) : Block k := + ⟨1,clearProgram a,rfl⟩ +def move {k : ℕ} (a b d : Fin (k+8)) : Block k := + ⟨6,moveProgram a b d,rfl⟩ +def pack {k : ℕ} (a d : Fin (k+8)) : Block k := + ⟨5,framePackProgram a d,rfl⟩ +def unpack {k : ℕ} (a d : Fin (k+8)) : Block k where + size := 4 + code := fun pc => match pc.val with + | 0 => .pop a 4 1 4 + | 1 => .pop a 4 2 3 + | 2 => .push d false 0 + | 3 => .push d true 0 + | _ => .halt + exit_halt := rfl + +lemma runs_reverse {k n : ℕ} (a d : Fin (k+8)) (had : a≠d) (O : IndependenceOracle n) + (R : Registers k) (xs ys : List Bool) (bits : ℕ → Bool) : + Runs (reverse a d) O bits (pairRegisters R a d xs ys) + (pairRegisters R a d [] (xs.reverse++ys)) (2*xs.length+1) 0 (2*xs.length+1) := by + intro q w + convert reverse_block a d had O R xs ys q w bits using 1 <;> simp [reverse,state,reverseConfig,lastLabel,Nat.add_assoc] + rfl +lemma runs_clear {k n : ℕ} (a : Fin (k+8)) (O : IndependenceOracle n) + (R : Registers k) (xs : List Bool) (bits : ℕ → Bool) : + Runs (clear a) O bits (Function.update R a xs) + (Function.update R a []) (xs.length+1) 0 (xs.length+1) := by + intro q w + convert clear_block a O R xs q w bits using 1 <;> simp [clear,state,clearConfig,lastLabel,Nat.add_assoc] + rfl +lemma runs_move {k n : ℕ} (a b d : Fin (k+8)) (hab : a≠b) (had : a≠d) (hbd : b≠d) + (O : IndependenceOracle n) (R : Registers k) (xs ys : List Bool) (bits : ℕ → Bool) : + Runs (move a b d) O bits (tripleRegisters R a b d xs [] ys) + (tripleRegisters R a b d [] [] (xs++ys)) (4*xs.length+2) 0 (4*xs.length+2) := by + intro q w + convert move_block a b d hab had hbd O R xs ys q w bits using 1 <;> simp [move,state,moveConfig,lastLabel,Nat.add_assoc] + rfl +lemma runs_pack {k n : ℕ} (a d : Fin (k+8)) (had : a≠d) (O : IndependenceOracle n) + (R : Registers k) (xs ts : List Bool) (bits : ℕ → Bool) : + Runs (pack a d) O bits (pairRegisters R a d xs ts) + (pairRegisters R a d [] (bitFrame xs.reverse++ts)) (3*xs.length+2) 0 (3*xs.length+2) := by + intro q w + convert frame_pack_block a d had O R xs ts q w bits using 1 <;> simp [pack,state,frameConfig,lastLabel,Nat.add_assoc] + rfl +lemma runs_unpack {k n : ℕ} (a d : Fin (k+8)) (had : a≠d) (O : IndependenceOracle n) + (R : Registers k) (xs ts zs : List Bool) (bits : ℕ → Bool) : + Runs (unpack a d) O bits (pairRegisters R a d (bitFrame xs++ts) zs) + (pairRegisters R a d ts (xs.reverse++zs)) (3*xs.length+1) 0 (3*xs.length+1) := by + intro q w + let f : Fin 6 → Fin 5 := fun i => ⟨min i.val 4,by omega⟩ + have h := frame_unpack_block a d had O R xs ts zs q w bits + have hn : (execution (frameUnpackProgram a d) O + (frameConfig (pairRegisters R a d (bitFrame xs++ts) zs) 0 q w) bits (3*xs.length+1)).output=none := by + rw [h]; rfl + have rel := execution_relabel_before_halt (frameUnpackProgram a d) (unpack a d).code f 4 rfl + (by intro i hi; fin_cases i <;> rfl) O _ bits (3*xs.length+1) hn + rw [h] at rel + convert rel using 1 <;> simp [state,relabelConfig,frameConfig,f,unpack,lastLabel,Nat.add_assoc] + rfl +lemma runs_unpack_packed {k n : ℕ} (a d : Fin (k+8)) (had : a≠d) (O : IndependenceOracle n) + (R : Registers k) (xs ts : List Bool) (bits : ℕ → Bool) : + Runs (unpack a d) O bits (pairRegisters R a d (bitFrame xs.reverse++ts) []) + (pairRegisters R a d ts xs) (3*xs.length+1) 0 (3*xs.length+1) := by + simpa only [List.length_reverse,List.reverse_reverse,List.append_nil] using + runs_unpack a d had O R xs.reverse ts [] bits + +def repeatBlock {k : ℕ} (p : Block k) (a : Fin (k+8)) : Block k where + size := p.size+1 + code := repeatProgram p.code a + exit_halt := by simp [repeatProgram,lastLabel] + +abbrev Word := List Bool + +def regs (x y z saved : Word) : Registers 1 := fun i => + if i=0 then x else if i=1 then y else if i=2 then z else if i=8 then saved else [] +@[simp] lemma regs_zero (x y z s : Word) : regs x y z s 0=x := by simp [regs] +@[simp] lemma regs_one (x y z s : Word) : regs x y z s 1=y := by simp [regs] +@[simp] lemma regs_two (x y z s : Word) : regs x y z s 2=z := by simp [regs] +@[simp] lemma regs_eight (x y z s : Word) : regs x y z s 8=s := by simp [regs] +@[simp] lemma update_regs_zero (x y z s u : Word) : Function.update (regs x y z s) 0 u=regs u y z s := by + funext i; fin_cases i <;> simp [regs] +@[simp] lemma update_regs_one (x y z s u : Word) : Function.update (regs x y z s) 1 u=regs x u z s := by + funext i; fin_cases i <;> simp [regs] +@[simp] lemma update_regs_two (x y z s u : Word) : Function.update (regs x y z s) 2 u=regs x y u s := by + funext i; fin_cases i <;> simp [regs] +@[simp] lemma update_regs_eight (x y z s u : Word) : Function.update (regs x y z s) 8 u=regs x y z u := by + funext i; fin_cases i <;> simp [regs] + +def pair (x y : Word) : Word := bitFrame x.reverse++y +@[simp] lemma pair_length (x y : Word) : (pair x y).length=2*x.length+1+y.length := by + simp [pair,bitFrame_length] + +def Computes {n : ℕ} (p : Block 1) (O : IndependenceOracle n) + (x y : Word) (t q w : ℕ) : Prop := + ∀ saved bits, Runs p O bits (regs x [] [] saved) (regs y [] [] saved) t q w + +def Bounded {n : ℕ} (p : Block 1) (O : IndependenceOracle n) (x y : Word) (B : ℕ) : Prop := + ∃ t q w, t≤B ∧ q≤B ∧ w≤B ∧ Computes p O x y t q w + +lemma computes_skip {n : ℕ} (O : IndependenceOracle n) (x : Word) : + Computes (skip 1) O x x 0 0 0 := fun s bits => runs_skip O bits (regs x [] [] s) +lemma computes_seq {n : ℕ} {p q : Block 1} {O : IndependenceOracle n} {x y z : Word} + {t₁ q₁ w₁ t₂ q₂ w₂ : ℕ} (hp : Computes p O x y t₁ q₁ w₁) (hq : Computes q O y z t₂ q₂ w₂) : + Computes (seq p q) O x z (t₁+t₂) (q₁+q₂) (w₁+w₂) := by + intro s bits + exact runs_seq O bits (hp s bits) (hq s (fun i => bits (t₁+i))) +lemma bounded_seq {n : ℕ} {p q : Block 1} {O : IndependenceOracle n} {x y z : Word} + {B C : ℕ} (hp : Bounded p O x y B) (hq : Bounded q O y z C) : + Bounded (seq p q) O x z (B+C) := by + obtain ⟨t₁,q₁,w₁,ht₁,hq₁,hw₁,hp⟩ := hp + obtain ⟨t₂,q₂,w₂,ht₂,hq₂,hw₂,hq⟩ := hq + exact ⟨_,_,_,Nat.add_le_add ht₁ ht₂,Nat.add_le_add hq₁ hq₂,Nat.add_le_add hw₁ hw₂,computes_seq hp hq⟩ +lemma bounded_mono {n : ℕ} {p : Block 1} {O : IndependenceOracle n} {x y : Word} + {B C : ℕ} (h : Bounded p O x y B) (hBC : B≤C) : Bounded p O x y C := by + obtain ⟨t,q,w,ht,hq,hw,hp⟩ := h + exact ⟨t,q,w,ht.trans hBC,hq.trans hBC,hw.trans hBC,hp⟩ + +def copy {k : ℕ} (a b d : Fin (k+8)) : Block k := ⟨8,copyProgram a b d,rfl⟩ +lemma runs_copy {k n : ℕ} (a b d : Fin (k+8)) (hab : a≠b) (had : a≠d) (hbd : b≠d) + (O : IndependenceOracle n) (R : Registers k) (xs ys : Word) (bits : ℕ → Bool) : + Runs (copy a b d) O bits (tripleRegisters R a b d xs [] ys) + (tripleRegisters R a b d xs [] (xs++ys)) (5*xs.length+2) 0 (5*xs.length+2) := by + intro q w + convert copy_block a b d hab had hbd O R xs ys q w bits using 1 <;> + simp [copy,state,copyConfig,lastLabel,Nat.add_assoc] + rfl + +def duplicate : Block 1 := seq (copy 0 2 1) (pack 1 0) +lemma computes_duplicate {n : ℕ} (O : IndependenceOracle n) (x : Word) : + Computes duplicate O x (pair x x) (8*x.length+4) 0 (8*x.length+4) := by + intro s bits + have hc := runs_copy (k:=1) 0 2 1 (by decide) (by decide) (by decide) O (regs x [] [] s) x [] bits + simp only [tripleRegisters,pairRegisters,update_regs_zero,update_regs_two,update_regs_one,List.append_nil] at hc + have hp := runs_pack (k:=1) 1 0 (by decide) O (regs x x [] s) x x (fun i => bits (5*x.length+2+i)) + simp only [pairRegisters,update_regs_one,update_regs_zero] at hp + simpa only [duplicate,pair,show 5*x.length+2+(3*x.length+2)=8*x.length+4 by omega,Nat.zero_add] using + runs_seq O bits hc hp + +lemma split_pair {n : ℕ} (O : IndependenceOracle n) (x y z s : Word) (bits : ℕ → Bool) : + Runs (unpack 0 1) O bits (regs (pair x y) z [] s) (regs y (x++z) [] s) + (3*x.length+1) 0 (3*x.length+1) := by + have h := runs_unpack (k:=1) 0 1 (by decide) O (regs [] [] [] s) x.reverse y z bits + simpa only [pair,pairRegisters,update_regs_zero,update_regs_one,List.length_reverse,List.reverse_reverse] using h +lemma make_pair {n : ℕ} (O : IndependenceOracle n) (x y z s : Word) (bits : ℕ → Bool) : + Runs (pack 1 0) O bits (regs y x z s) (regs (pair x y) [] z s) + (3*x.length+2) 0 (3*x.length+2) := by + simpa only [pair,pairRegisters,update_regs_zero,update_regs_one] using + runs_pack (k:=1) 1 0 (by decide) O (regs [] [] z s) x y bits +lemma move_one_zero {n : ℕ} (O : IndependenceOracle n) (x y s : Word) (bits : ℕ → Bool) : + Runs (move 1 2 0) O bits (regs y x [] s) (regs (x++y) [] [] s) + (4*x.length+2) 0 (4*x.length+2) := by + simpa only [tripleRegisters,pairRegisters,update_regs_zero,update_regs_one,update_regs_two] using + runs_move (k:=1) 1 2 0 (by decide) (by decide) (by decide) O (regs [] [] [] s) x y bits + +def first : Block 1 := seq (unpack 0 1) (seq (clear 0) (move 1 2 0)) +def second : Block 1 := seq (unpack 0 1) (clear 1) +lemma computes_first {n : ℕ} (O : IndependenceOracle n) (x y : Word) : + Computes first O (pair x y) x (7*x.length+y.length+4) 0 (7*x.length+y.length+4) := by + intro s bits + have hu := split_pair O x y [] s bits + have hc := runs_clear (k:=1) 0 O (regs y x [] s) y (fun i => bits (3*x.length+1+i)) + simp only [update_regs_zero] at hc + have hm := move_one_zero O x [] s (fun i => bits (3*x.length+1+(y.length+1+i))) + simp only [List.append_nil] at hu hm + have ht := runs_seq O bits hu (runs_seq O (fun i => bits (3*x.length+1+i)) hc hm) + simpa only [first,show 3*x.length+1+(y.length+1+(4*x.length+2))=7*x.length+y.length+4 by omega,Nat.zero_add] using ht +lemma computes_second {n : ℕ} (O : IndependenceOracle n) (x y : Word) : + Computes second O (pair x y) y (4*x.length+2) 0 (4*x.length+2) := by + intro s bits + have hu := split_pair O x y [] s bits + simp only [List.append_nil] at hu + have hc := runs_clear (k:=1) 1 O (regs y x [] s) x (fun i => bits (3*x.length+1+i)) + simp only [update_regs_one] at hc + simpa only [second,show 3*x.length+1+(x.length+1)=4*x.length+2 by omega,Nat.zero_add] using runs_seq O bits hu hc + +lemma save_zero {n : ℕ} (O : IndependenceOracle n) (x y s : Word) (bits : ℕ → Bool) : + Runs (pack 0 8) O bits (regs x y [] s) (regs [] y [] (pair x s)) + (3*x.length+2) 0 (3*x.length+2) := by + simpa only [pair,pairRegisters,update_regs_zero,update_regs_eight] using + runs_pack (k:=1) 0 8 (by decide) O (regs [] y [] []) x s bits +lemma restore_one {n : ℕ} (O : IndependenceOracle n) (x y s : Word) (bits : ℕ → Bool) : + Runs (unpack 8 1) O bits (regs x [] [] (pair y s)) (regs x y [] s) + (3*y.length+1) 0 (3*y.length+1) := by + simpa only [pair,pairRegisters,update_regs_one,update_regs_eight] using + runs_unpack_packed (k:=1) 8 1 (by decide) O (regs x [] [] []) y s bits +lemma pack_zero_one {n : ℕ} (O : IndependenceOracle n) (x y s : Word) (bits : ℕ → Bool) : + Runs (pack 0 1) O bits (regs x y [] s) (regs [] (pair x y) [] s) + (3*x.length+2) 0 (3*x.length+2) := by + simpa only [pair,pairRegisters,update_regs_zero,update_regs_one] using + runs_pack (k:=1) 0 1 (by decide) O (regs [] [] [] s) x y bits + +def swap : Block 1 := seq (unpack 0 1) (seq (pack 0 1) (move 1 2 0)) +lemma computes_swap {n : ℕ} (O : IndependenceOracle n) (x y : Word) : + Computes swap O (pair x y) (pair y x) (7*x.length+11*y.length+9) 0 (7*x.length+11*y.length+9) := by + intro s bits + have hu := split_pair O x y [] s bits + simp only [List.append_nil] at hu + have hp := pack_zero_one O y x s (fun i => bits (3*x.length+1+i)) + have hm := move_one_zero O (pair y x) [] s (fun i => bits (3*x.length+1+(3*y.length+2+i))) + simp only [List.append_nil] at hm + have ht := runs_seq O bits hu (runs_seq O (fun i => bits (3*x.length+1+i)) hp hm) + have he : 3*x.length+1+(3*y.length+2+(4*(pair y x).length+2))=7*x.length+11*y.length+9 := by + rw [pair_length]; omega + simpa only [swap,he,Nat.zero_add] using ht + +def left (p : Block 1) : Block 1 := + seq (unpack 0 1) (seq (pack 0 8) (seq (move 1 2 0) + (seq p (seq (unpack 8 1) (seq (pack 0 1) (move 1 2 0)))))) +lemma computes_left {n : ℕ} {O : IndependenceOracle n} {p : Block 1} {x u : Word} + {t q w : ℕ} (h : Computes p O x u t q w) (y : Word) : + Computes (left p) O (pair x y) (pair u y) + (7*x.length+10*y.length+11*u.length+14+t) q (7*x.length+10*y.length+11*u.length+14+w) := by + intro s bits + have hu := split_pair O x y [] s bits + simp only [List.append_nil] at hu + have hs := save_zero O y x s (fun i => bits (3*x.length+1+i)) + have hm := move_one_zero O x [] (pair y s) (fun i => bits (3*x.length+1+(3*y.length+2+i))) + simp only [List.append_nil] at hm + have hp := h (pair y s) (fun i => bits (3*x.length+1+(3*y.length+2+(4*x.length+2+i)))) + have hr := restore_one O u y s (fun i => bits (3*x.length+1+(3*y.length+2+(4*x.length+2+(t+i))))) + have hf := pack_zero_one O u y s (fun i => bits (3*x.length+1+(3*y.length+2+(4*x.length+2+(t+(3*y.length+1+i)))))) + have he := move_one_zero O (pair u y) [] s + (fun i => bits (3*x.length+1+(3*y.length+2+(4*x.length+2+(t+(3*y.length+1+(3*u.length+2+i))))))) + simp only [List.append_nil] at he + have ht := runs_seq O bits hu (runs_seq O _ hs (runs_seq O _ hm + (runs_seq O _ hp (runs_seq O _ hr (runs_seq O _ hf he))))) + have cost (v : ℕ) : 3*x.length+1+(3*y.length+2+(4*x.length+2+(v+(3*y.length+1+(3*u.length+2+(4*(pair u y).length+2))))))= + 7*x.length+10*y.length+11*u.length+14+v := by rw [pair_length]; omega + simpa only [left,cost,Nat.zero_add,Nat.add_zero] using ht + +def right (p : Block 1) : Block 1 := seq swap (seq (left p) swap) +lemma computes_right {n : ℕ} {O : IndependenceOracle n} {p : Block 1} {x u : Word} + {t q w : ℕ} (h : Computes p O x u t q w) (y : Word) : + Computes (right p) O (pair y x) (pair y u) + (28*y.length+18*x.length+18*u.length+32+t) q (28*y.length+18*x.length+18*u.length+32+w) := by + have ht := computes_seq (computes_swap O y x) (computes_seq (computes_left h y) (computes_swap O u y)) + convert ht using 1 <;> first | rfl | omega + +def parallel (p q : Block 1) : Block 1 := seq (left p) (right q) +def fanout (p q : Block 1) : Block 1 := seq duplicate (parallel p q) + +def stripZeros : Word → Word + | [] => [] + | false::xs => stripZeros xs + | true::xs => true::xs +def stripCost : Word → ℕ + | [] => 1 + | false::xs => 1+stripCost xs + | true::_ => 2 +lemma strip_length (x : Word) : (stripZeros x).length≤x.length := by + induction x with + | nil => rfl + | cons b xs ih => cases b <;> simp only [stripZeros,List.length_cons] <;> omega +lemma strip_cost_le (x : Word) : stripCost x≤x.length+2 := by + induction x with + | nil => decide + | cons b xs ih => cases b <;> simp only [stripCost,List.length_cons] <;> omega +lemma strip_append (x y : Word) : stripZeros (x++y)=if stripZeros x=[] then stripZeros y else stripZeros x++y := by + induction x with + | nil => simp [stripZeros] + | cons b xs ih => + cases b <;> simp [stripZeros,ih] + rfl + +def normalWord (x : Word) : Word := (stripZeros x.reverse).reverse +lemma normal_length (x : Word) : (normalWord x).length≤x.length := by + simpa only [normalWord,List.length_reverse] using strip_length x.reverse +lemma normalWord_cons (b : Bool) (xs : Word) : + normalWord (b::xs)=if normalWord xs=[] then (if b then [true] else []) else b::normalWord xs := by + simp only [normalWord,List.reverse_cons,strip_append] + by_cases h : stripZeros xs.reverse=[] + · simp [h]; cases b <;> rfl + · simp [h,List.reverse_eq_nil_iff] + +lemma binaryValue_bits (n : ℕ) : binaryValue n.bits=n := by + induction n using Nat.binaryRec' with + | zero => rfl + | bit b n hn ih => + rw [Nat.bits_append_bit n b hn] + cases b <;> simp [binaryValue,ih,Nat.bit] + omega +lemma normalWord_eq_bits (xs : Word) : normalWord xs=(binaryValue xs).bits := by + induction xs with + | nil => rfl + | cons b xs ih => + rw [normalWord_cons,ih] + by_cases hz : binaryValue xs=0 + · cases b <;> simp [binaryValue,hz] + · have hb : (binaryValue xs).bits≠[] := by + intro h + have he := binaryValue_bits (binaryValue xs) + rw [h] at he + exact hz he.symm + cases b with + | false => simp [binaryValue,hb,Nat.bit0_bits _ hz] + | true => + simp only [ite_true,ite_eq_right hb,binaryValue] + rw [Nat.add_comm 1, Nat.bit1_bits] +lemma normalWord_value (xs : Word) : binaryValue (normalWord xs)=binaryValue xs := by + rw [normalWord_eq_bits,binaryValue_bits] +@[simp] lemma normalWord_bits (n : ℕ) : normalWord n.bits=n.bits := by + rw [normalWord_eq_bits,binaryValue_bits] + +def stripCode {k : ℕ} (a : Fin (k+8)) : Block k where + size := 2 + code := fun pc => match pc.val with + | 0 => .pop a 2 0 1 + | 1 => .push a true 2 + | _ => .halt + exit_halt := rfl +lemma runs_strip {k n : ℕ} (a : Fin (k+8)) (O : IndependenceOracle n) (R : Registers k) + (x : Word) (bits : ℕ → Bool) : + Runs (stripCode a) O bits (Function.update R a x) (Function.update R a (stripZeros x)) + (stripCost x) 0 (stripCost x) := by + intro q w + induction x generalizing w bits with + | nil => simp [stripCode,stripCost,stripZeros,execution,machineStep,state,lastLabel] + | cons b xs ih => + cases b with + | false => + have hf : execution (stripCode a).code O (state (Function.update R a (false::xs)) 0 q w) bits 1= + state (Function.update R a xs) 0 q (w+1) := by + simp [stripCode,state,execution,machineStep] + rfl + rw [stripCost,execution_add,hf,ih] + simp [stripZeros,Nat.add_assoc] + | true => simp [stripCode,stripCost,stripZeros,execution,machineStep,state,lastLabel,Nat.add_assoc] + +def normalCode : Block 1 := seq (reverse 0 1) (seq (stripCode 1) (reverse 1 0)) +def normalCost (x : Word) : ℕ := 2*x.length+1+(stripCost x.reverse+(2*(stripZeros x.reverse).length+1)) +lemma normalCost_le (x : Word) : normalCost x≤5*x.length+4 := by + have h₁:=strip_cost_le x.reverse + have h₂:=strip_length x.reverse + simp only [List.length_reverse] at h₁ h₂ + unfold normalCost + omega +lemma computes_normalCode {n : ℕ} (O : IndependenceOracle n) (x : Word) : + Computes normalCode O x (normalWord x) (normalCost x) 0 (normalCost x) := by + intro s bits + have h₁ := runs_reverse (k:=1) 0 1 (by decide) O (regs [] [] [] s) x [] bits + simp only [pairRegisters,update_regs_zero,update_regs_one,List.append_nil] at h₁ + have h₂ := runs_strip (k:=1) 1 O (regs [] [] [] s) x.reverse (fun i => bits (2*x.length+1+i)) + simp only [update_regs_one] at h₂ + have h₃ := runs_reverse (k:=1) 1 0 (by decide) O (regs [] [] [] s) (stripZeros x.reverse) [] + (fun i => bits (2*x.length+1+(stripCost x.reverse+i))) + simp only [pairRegisters,update_regs_zero,update_regs_one,List.append_nil] at h₃ + simpa only [normalCode,normalCost,normalWord,Nat.zero_add] using runs_seq O bits h₁ (runs_seq O _ h₂ h₃) +lemma bounded_normalCode {n : ℕ} (O : IndependenceOracle n) (x : Word) : + Bounded normalCode O x (binaryValue x).bits (5*x.length+4) := by + refine ⟨normalCost x,0,normalCost x,normalCost_le x,Nat.zero_le _,normalCost_le x,?_⟩ + rw [←normalWord_eq_bits] + exact computes_normalCode O x + +def addBlock : Block 1 := ⟨16,addProgram 0 1 2,rfl⟩ +def addTime (x y : Word) : ℕ := addCost false x y+2*(addDigits false x y).length+1 +lemma runs_add {n : ℕ} (O : IndependenceOracle n) (x y s : Word) (bits : ℕ → Bool) : + Runs addBlock O bits (regs x y [] s) (regs (addDigits false x y) [] [] s) + (addTime x y) 0 (addTime x y) := by + dsimp only [Runs,addBlock] + intro q w + have h := (addition_block (k:=1) 0 1 2 (by decide) (by decide) (by decide) O (regs [] [] [] s) x y q w bits).2.2 + convert h using 1 <;> simp only [addTime,addConfig,state,tripleRegisters,pairRegisters,update_regs_zero, + update_regs_one,update_regs_two,lastLabel,Nat.add_zero] + rfl +lemma addTime_le (x y : Word) : addTime x y ≤ 5*(x.length+y.length)+6 := by + have h := addDigits_length_cost false x y + unfold addTime + omega + +def addCode : Block 1 := seq (unpack 0 1) (seq addBlock normalCode) +lemma computes_add {n : ℕ} (O : IndependenceOracle n) (x y : Word) : + Computes addCode O (pair x y) (binaryValue x+binaryValue y).bits + (3*x.length+1+addTime y x+normalCost (addDigits false y x)) 0 + (3*x.length+1+addTime y x+normalCost (addDigits false y x)) := by + have hv : binaryValue (addDigits false y x)=binaryValue x+binaryValue y := by + simpa [Nat.add_comm] using addDigits_value false y x + intro s bits + have hs := split_pair O x y [] s bits + simp only [List.append_nil] at hs + have ha := runs_add O y x s (fun i => bits (3*x.length+1+i)) + have hn := computes_normalCode O (addDigits false y x) s (fun i => bits (3*x.length+1+(addTime y x+i))) + rw [normalWord_eq_bits,hv] at hn + have ht := runs_seq O bits hs (runs_seq O _ ha hn) + simpa only [addCode,Nat.zero_add,Nat.add_assoc] using ht +lemma bounded_add {n : ℕ} (O : IndependenceOracle n) (x y : Word) : + Bounded addCode O (pair x y) (binaryValue x+binaryValue y).bits (20*(x.length+y.length+1)) := by + have h₁ := addTime_le y x + have h₂ := normalCost_le (addDigits false y x) + have h₃ := (addDigits_length_cost false y x).1 + refine ⟨_,0,_,?_,Nat.zero_le _,?_,computes_add O x y⟩ <;> omega + +def mulBlock : Block 1 := ⟨26,mulProgram,rfl⟩ +lemma mulRegisters_regs (x y z s : Word) : mulRegisters (regs [] [] [] s) x y z []=regs x y z s := by + funext i; fin_cases i <;> simp [mulRegisters,regs] +lemma runs_mul {n : ℕ} (O : IndependenceOracle n) (x y s : Word) (bits : ℕ → Bool) : + Runs mulBlock O bits (regs x y [] s) + (regs (List.replicate y.length false++x) [] (mulDigits x y []) s) + (mulCost x y []) 0 (mulCost x y []) := by + dsimp only [Runs,mulBlock] + intro q w + have h := (multiplication_block (k:=1) O (regs [] [] [] s) x y q w bits).2.2 + convert h using 1 <;> simp only [mulConfig,state,mulRegisters_regs,lastLabel,Nat.add_zero] + rfl +lemma clear_zero {n : ℕ} (O : IndependenceOracle n) (x y z s : Word) (bits : ℕ → Bool) : + Runs (clear 0) O bits (regs x y z s) (regs [] y z s) (x.length+1) 0 (x.length+1) := by + simpa only [update_regs_zero] using runs_clear (k:=1) 0 O (regs [] y z s) x bits +lemma move_two_zero {n : ℕ} (O : IndependenceOracle n) (x s : Word) (bits : ℕ → Bool) : + Runs (move 2 1 0) O bits (regs [] [] x s) (regs x [] [] s) (4*x.length+2) 0 (4*x.length+2) := by + simpa only [tripleRegisters,pairRegisters,update_regs_zero,update_regs_one,update_regs_two,List.append_nil] using + runs_move (k:=1) 2 1 0 (by decide) (by decide) (by decide) O (regs [] [] [] s) x [] bits + +def mulCode : Block 1 := seq (unpack 0 1) (seq mulBlock (seq (clear 0) (seq (move 2 1 0) normalCode))) +def mulTime (x y : Word) : ℕ := + 3*x.length+1+mulCost y x []+(x.length+y.length+1)+(4*(mulDigits y x []).length+2)+normalCost (mulDigits y x []) +lemma computes_mul {n : ℕ} (O : IndependenceOracle n) (x y : Word) : + Computes mulCode O (pair x y) (binaryValue x*binaryValue y).bits (mulTime x y) 0 (mulTime x y) := by + have hv : binaryValue (mulDigits y x [])=binaryValue x*binaryValue y := by + simp [mulDigits_value,binaryValue,Nat.mul_comm] + intro s bits + have h₁ := split_pair O x y [] s bits + simp only [List.append_nil] at h₁ + have h₂ := runs_mul O y x s (fun i => bits (3*x.length+1+i)) + have h₃ := clear_zero O (List.replicate x.length false++y) [] (mulDigits y x []) s + (fun i => bits (3*x.length+1+(mulCost y x []+i))) + simp only [List.length_append,List.length_replicate] at h₃ + have h₄ := move_two_zero O (mulDigits y x []) s + (fun i => bits (3*x.length+1+(mulCost y x []+(x.length+y.length+1+i)))) + have h₅ := computes_normalCode O (mulDigits y x []) s + (fun i => bits (3*x.length+1+(mulCost y x []+(x.length+y.length+1+(4*(mulDigits y x []).length+2+i))))) + rw [normalWord_eq_bits,hv] at h₅ + have ht := runs_seq O bits h₁ (runs_seq O _ h₂ (runs_seq O _ h₃ (runs_seq O _ h₄ h₅))) + simpa only [mulCode,mulTime,Nat.zero_add,Nat.add_assoc] using ht +lemma mulTime_le (x y : Word) : mulTime x y ≤ 60*(x.length+y.length+1)^2 := by + have h₁ := mulCost_bound y x [] + have h₂ := mulDigits_length y x [] + have h₃ := normalCost_le (mulDigits y x []) + simp only [List.length_nil,Nat.max_zero] at h₁ h₂ + unfold mulTime + nlinarith [sq_nonneg (x.length:ℤ),sq_nonneg (y.length:ℤ)] +lemma bounded_mul {n : ℕ} (O : IndependenceOracle n) (x y : Word) : + Bounded mulCode O (pair x y) (binaryValue x*binaryValue y).bits (60*(x.length+y.length+1)^2) := + ⟨_,0,_,mulTime_le x y,Nat.zero_le _,mulTime_le x y,computes_mul O x y⟩ + +lemma computes_parallel {n : ℕ} {O : IndependenceOracle n} {p q : Block 1} {x y u v : Word} + {t₁ q₁ w₁ t₂ q₂ w₂ : ℕ} (hp : Computes p O x u t₁ q₁ w₁) (hq : Computes q O y v t₂ q₂ w₂) : + Computes (parallel p q) O (pair x y) (pair u v) + (7*x.length+28*y.length+39*u.length+18*v.length+46+t₁+t₂) (q₁+q₂) + (7*x.length+28*y.length+39*u.length+18*v.length+46+w₁+w₂) := by + have ht := computes_seq (computes_left hp y) (computes_right hq u) + convert ht using 1 <;> first | rfl | omega +lemma computes_fanout {n : ℕ} {O : IndependenceOracle n} {p q : Block 1} {x u v : Word} + {t₁ q₁ w₁ t₂ q₂ w₂ : ℕ} (hp : Computes p O x u t₁ q₁ w₁) (hq : Computes q O x v t₂ q₂ w₂) : + Computes (fanout p q) O x (pair u v) + (43*x.length+39*u.length+18*v.length+50+t₁+t₂) (q₁+q₂) + (43*x.length+39*u.length+18*v.length+50+w₁+w₂) := by + have ht := computes_seq (computes_duplicate O x) (computes_parallel hp hq) + convert ht using 1 <;> first | rfl | omega + +def prependCode : Word → Block 1 + | [] => skip 1 + | b::xs => seq (prependCode xs) (push 0 b) +lemma computes_prepend {n : ℕ} (O : IndependenceOracle n) (x y : Word) : + Computes (prependCode x) O y (x++y) x.length 0 x.length := by + induction x with + | nil => exact computes_skip O y + | cons b xs ih => + have hp : Computes (push 0 b) O (xs++y) (b::(xs++y)) 1 0 1 := by + intro s bits + simpa only [regs_zero,update_regs_zero] using runs_push O bits (regs (xs++y) [] [] s) 0 b + have ht := computes_seq ih hp + simpa only [prependCode,List.cons_append,List.length_cons,Nat.zero_add] using ht + +def constCode (x : Word) : Block 1 := seq (clear 0) (prependCode x) +lemma computes_const {n : ℕ} (O : IndependenceOracle n) (x y : Word) : + Computes (constCode y) O x y (x.length+y.length+1) 0 (x.length+y.length+1) := by + have hc : Computes (clear 0) O x [] (x.length+1) 0 (x.length+1) := + fun s bits => clear_zero O x [] [] s bits + have ht := computes_seq hc (computes_prepend O y []) + simpa only [constCode,List.append_nil,Nat.zero_add,show x.length+1+y.length=x.length+y.length+1 by omega] using ht + +def selectCode (p q : Block 1) : Block 1 := seq (unpack 0 1) (fork (.pop 1 false false true) p q) +lemma computes_select {n : ℕ} {O : IndependenceOracle n} (p q : Block 1) (b : Bool) {x y : Word} + {t a w : ℕ} (h : Computes (if b then q else p) O x y t a w) : + Computes (selectCode p q) O (pair [b] x) y (5+t) a (5+w) := by + intro s bits + have hu := split_pair O [b] x [] s bits + simp only [List.append_nil,List.length_singleton,show 3*1+1=4 by omega] at hu + have hf : Runs (fork (.pop 1 false false true) p q) O (fun i => bits (4+i)) + (regs x [b] [] s) (regs y [] [] s) (1+t) a (1+w) := by + cases b with + | false => + have hp := h s (fun i => bits (4+(1+i))) + have hh := fork_run_no (.pop 1 false false true) p q O (fun i => bits (4+i)) + (R:=regs x [false] [] s) (by simp [Test.result]) hp + simpa only [Test.queries,Test.work,Nat.zero_add] using hh + | true => + have hp := h s (fun i => bits (4+(1+i))) + have hh := fork_run_yes (.pop 1 false false true) p q O (fun i => bits (4+i)) + (R:=regs x [true] [] s) (by simp [Test.result]) hp + simpa only [Test.queries,Test.work,Nat.zero_add] using hh + have ht := runs_seq O bits hu hf + simpa only [selectCode,Nat.zero_add,show 4+(1+t)=5+t by omega,show 4+(1+w)=5+w by omega] using ht + +def queryCode (which : Bool) : Block 1 := fork (.query which 0) (constCode [false]) (constCode [true]) +lemma computes_query {n : ℕ} (O : IndependenceOracle n) (which : Bool) (x : Word) (hx : x.length=n) : + Computes (queryCode which) O x [O which (fun i => x[i.val]?.getD false)] (n+3) 1 (3*n+3) := by + intro s bits + have hp (b : Bool) := computes_const O x [b] s (fun i => bits (1+i)) + have hres : (Test.query which 0).result O (bits 0) (regs x [] [] s)= + some (O which (fun i => x[i.val]?.getD false),regs x [] [] s) := by simp [Test.result,hx] + cases hb : O which (fun i => x[i.val]?.getD false) with + | false => + rw [hb] at hres + have ht := fork_run_no (.query which 0) (constCode [false]) (constCode [true]) O bits hres (hp false) + simp only [Test.queries,Test.work,regs_zero,hx,List.length_singleton] at ht + convert ht using 1 <;> first | rfl | omega + | true => + rw [hb] at hres + have ht := fork_run_yes (.query which 0) (constCode [false]) (constCode [true]) O bits hres (hp true) + simp only [Test.queries,Test.work,regs_zero,hx,List.length_singleton] at ht + convert ht using 1 <;> first | rfl | omega + +def quadRegs (x y z u s : Word) : Registers 1 := Function.update (regs x y z s) 3 u +@[simp] lemma quadRegs_zero (x y z u s : Word) : quadRegs x y z u s 0=x := by simp [quadRegs] +@[simp] lemma quadRegs_one (x y z u s : Word) : quadRegs x y z u s 1=y := by simp [quadRegs] +@[simp] lemma quadRegs_two (x y z u s : Word) : quadRegs x y z u s 2=z := by simp [quadRegs] +@[simp] lemma quadRegs_three (x y z u s : Word) : quadRegs x y z u s 3=u := by simp [quadRegs] +@[simp] lemma quadRegs_nil (x y z s : Word) : quadRegs x y z [] s=regs x y z s := by + funext i; fin_cases i <;> simp [quadRegs,regs] +@[simp] lemma update_quad_zero (x y z u s v : Word) : Function.update (quadRegs x y z u s) 0 v=quadRegs v y z u s := by + funext i; fin_cases i <;> simp [quadRegs,regs] +@[simp] lemma update_quad_one (x y z u s v : Word) : Function.update (quadRegs x y z u s) 1 v=quadRegs x v z u s := by + funext i; fin_cases i <;> simp [quadRegs,regs] +@[simp] lemma update_quad_two (x y z u s v : Word) : Function.update (quadRegs x y z u s) 2 v=quadRegs x y v u s := by + funext i; fin_cases i <;> simp [quadRegs,regs] +@[simp] lemma update_quad_three (x y z u s v : Word) : Function.update (quadRegs x y z u s) 3 v=quadRegs x y z v s := by + simp [quadRegs] +lemma divRegisters_quad (x y z u s : Word) : divRegisters (regs [] [] [] s) x y z u [] []=quadRegs x y z u s := by + funext i; fin_cases i <;> simp [divRegisters,quadRegs,regs] + +def divBlock : Block 1 := ⟨53,divisionProgram,rfl⟩ +lemma runs_div {n : ℕ} (O : IndependenceOracle n) (x y s : Word) (bits : ℕ → Bool) : + Runs divBlock O bits (regs x y [] s) + (quadRegs [] y (divisionWords x y [] []).1 (divisionWords x y [] []).2 s) + (divisionCost x y []) 0 (divisionCost x y []) := by + dsimp only [Runs,divBlock] + intro q w + have h := division_machine_run (k:=1) O (regs [] [] [] s) x y [] [] q w bits + convert h using 1 <;> simp only [divisionConfig,state,divRegisters_quad,quadRegs_nil,lastLabel,Nat.add_zero] + rfl + +lemma div_prepare {n : ℕ} (O : IndependenceOracle n) (x y s : Word) (bits : ℕ → Bool) : + Runs (seq (reverse 0 2) (move 2 3 0)) O bits (regs x y [] s) (regs x.reverse y [] s) + (6*x.length+3) 0 (6*x.length+3) := by + have hr := runs_reverse (k:=1) 0 2 (by decide) O (regs [] y [] s) x [] bits + simp only [pairRegisters,update_regs_zero,update_regs_two,List.append_nil] at hr + have hm := runs_move (k:=1) 2 3 0 (by decide) (by decide) (by decide) O + (quadRegs [] y [] [] s) x.reverse [] (fun i => bits (2*x.length+1+i)) + simp only [tripleRegisters,pairRegisters,update_quad_zero,update_quad_two,update_quad_three, + List.append_nil,List.length_reverse] at hm + simp only [quadRegs_nil] at hm + have ht := runs_seq O bits hr hm + convert ht using 1 <;> first | rfl | omega + +lemma div_finish {n : ℕ} (O : IndependenceOracle n) (x r q s : Word) (bits : ℕ → Bool) : + Runs (seq (clear 1) (seq (pack 2 3) (move 3 1 0))) O bits (quadRegs [] x r q s) + (regs (pair r q) [] [] s) (x.length+11*r.length+4*q.length+9) 0 + (x.length+11*r.length+4*q.length+9) := by + have h₁ := runs_clear (k:=1) 1 O (quadRegs [] [] r q s) x bits + simp only [update_quad_one] at h₁ + have h₂ := runs_pack (k:=1) 2 3 (by decide) O (quadRegs [] [] [] [] s) r q + (fun i => bits (x.length+1+i)) + simp only [pairRegisters,update_quad_two,update_quad_three] at h₂ + change Runs (pack 2 3) O _ (quadRegs [] [] r q s) (quadRegs [] [] [] (pair r q) s) _ _ _ at h₂ + have h₃ := runs_move (k:=1) 3 1 0 (by decide) (by decide) (by decide) O (quadRegs [] [] [] [] s) + (pair r q) [] (fun i => bits (x.length+1+(3*r.length+2+i))) + simp only [tripleRegisters,pairRegisters,update_quad_zero,update_quad_one,update_quad_three, + List.append_nil] at h₃ + simp only [quadRegs_nil] at h₃ + have ht := runs_seq O bits h₁ (runs_seq O _ h₂ h₃) + convert ht using 1 <;> first | rfl | simp only [pair_length]; omega + +def rawDivCode : Block 1 := seq (unpack 0 1) + (seq (seq (reverse 0 2) (move 2 3 0)) (seq divBlock + (seq (clear 1) (seq (pack 2 3) (move 3 1 0))))) +def divResult (x y : Word) : Word × Word := divisionWords y.reverse x [] [] +def rawDivTime (x y : Word) : ℕ := + 4*x.length+6*y.length+11*(divResult x y).1.length+4*(divResult x y).2.length+13+divisionCost y.reverse x [] +lemma computes_rawDiv {n : ℕ} (O : IndependenceOracle n) (x y : Word) : + Computes rawDivCode O (pair x y) (pair (divResult x y).1 (divResult x y).2) + (rawDivTime x y) 0 (rawDivTime x y) := by + intro s bits + have h₁ := split_pair O x y [] s bits + simp only [List.append_nil] at h₁ + have h₂ := div_prepare O y x s (fun i => bits (3*x.length+1+i)) + have h₃ := runs_div O y.reverse x s (fun i => bits (3*x.length+1+(6*y.length+3+i))) + have h₄ := div_finish O x (divResult x y).1 (divResult x y).2 s + (fun i => bits (3*x.length+1+(6*y.length+3+(divisionCost y.reverse x []+i)))) + have ht := runs_seq O bits h₁ (runs_seq O _ h₂ (runs_seq O _ h₃ h₄)) + convert ht using 1 <;> first | rfl | unfold rawDivTime; omega + +lemma divisionWords_length (xs ys zs ws : Word) : + (divisionWords xs ys zs ws).1.length ≤ max ys.length zs.length+xs.length ∧ + (divisionWords xs ys zs ws).2.length = xs.length+ws.length := by + induction xs generalizing zs ws with + | nil => simp only [divisionWords,List.length_nil,Nat.add_zero,Nat.zero_add]; exact ⟨Nat.le_max_right _ _,True.intro⟩ + | cons x xs ih => + have hh := ih (divisionRemainder ys (x::zs)) (divisionDigit ys (x::zs)::ws) + have hr := divisionRemainder_length ys (x::zs) + simp only [divisionWords,List.length_cons] at * + constructor <;> omega +lemma divResult_length (x y : Word) : (divResult x y).1.length ≤ x.length+y.length ∧ + (divResult x y).2.length=y.length := by + simpa only [divResult,List.length_reverse,List.length_nil,Nat.max_zero,Nat.add_zero] using divisionWords_length y.reverse x [] [] +lemma rawDivTime_le (x y : Word) : rawDivTime x y ≤ 100*(x.length+y.length+1)^2 := by + have hd := divisionCost_bound y.reverse x [] x.length le_rfl (by simp) + have hl := divResult_length x y + simp only [List.length_reverse] at hd + unfold rawDivTime + nlinarith + +def divCode : Block 1 := seq rawDivCode (parallel normalCode normalCode) +def normalizedResult (x y : Word) : Word := pair (binaryValue (divResult x y).1).bits (binaryValue (divResult x y).2).bits +lemma bounded_div {n : ℕ} (O : IndependenceOracle n) (x y : Word) : + Bounded divCode O (pair x y) (normalizedResult x y) (300*(x.length+y.length+1)^2) := by + have h₁ := computes_rawDiv O x y + have h₂ := computes_parallel (computes_normalCode O (divResult x y).1) (computes_normalCode O (divResult x y).2) + have ht := computes_seq h₁ h₂ + simp only [normalWord_eq_bits] at ht + have hl := divResult_length x y + have hr := rawDivTime_le x y + have hn₁ := normal_length (divResult x y).1 + have hn₂ := normal_length (divResult x y).2 + have hc₁ := normalCost_le (divResult x y).1 + have hc₂ := normalCost_le (divResult x y).2 + rw [normalWord_eq_bits] at hn₁ hn₂ + refine ⟨_,0,_,?_,Nat.zero_le _,?_,ht⟩ <;> nlinarith +lemma normalizedResult_pos (x y : Word) (hx : 0 < binaryValue x) : + normalizedResult x y=pair (binaryValue y%binaryValue x).bits (binaryValue y/binaryValue x).bits := by + have hh := divisionWords_correct y.reverse x hx + simpa only [normalizedResult,divResult,List.reverse_reverse] using congrArg₂ (fun a b : ℕ => pair a.bits b.bits) hh.1 hh.2 + +def cmpLabel (i : Fin 10) : Fin 11 := ⟨i.val,by omega⟩ +def cmpBlock : Block 1 where + size := 10 + code := fun pc => if h : pc.val < 8 then + (compareProgram (1 : Fin 9) 0 ⟨pc.val,by omega⟩).relabel cmpLabel + else if pc.val=8 then .push 0 false 10 + else if pc.val=9 then .push 0 true 10 else .halt + exit_halt := rfl +lemma cmpBlock_body (i : Fin 10) (h : compareProgram (1 : Fin 9) 0 i ≠ .halt) : + cmpBlock.code (cmpLabel i)=(compareProgram (1 : Fin 9) 0 i).relabel cmpLabel := by + have hi : i.val<8 := by + by_contra hn + have hiv := i.isLt + have : i.val=8 ∨ i.val=9 := by omega + rcases this with hi|hi <;> simp [compareProgram,hi] at h + simp [cmpBlock,cmpLabel,hi] +lemma runs_cmp {n : ℕ} (O : IndependenceOracle n) (x y s : Word) (bits : ℕ → Bool) : + Runs cmpBlock O bits (regs y x [] s) (regs [decide (binaryValue x + simp [h,relabelConfig,cmpLabel,compareConfig,state,execution,machineStep,cmpBlock,lastLabel,Nat.add_assoc] + +def cmpCode : Block 1 := seq (unpack 0 1) cmpBlock +lemma computes_cmp {n : ℕ} (O : IndependenceOracle n) (x y : Word) : + Computes cmpCode O (pair x y) [decide (binaryValue x bits (3*x.length+1+i)) + have hh := runs_seq O bits hu hr + convert hh using 1 <;> first | rfl | omega +lemma bounded_cmp {n : ℕ} (O : IndependenceOracle n) (x y : Word) : + Bounded cmpCode O (pair x y) [decide (binaryValue x omega + +def loopAccum {A : Type*} (f : A → A) (g : A → ℕ → ℕ) : ℕ → A → ℕ + | 0,_ => 0 + | m+1,x => g x m+loopAccum f g m (f x) + +theorem runs_repeat {k n : ℕ} {A : Type*} (p : Block k) (a : Fin (k+8)) + (O : IndependenceOracle n) (encode : A → Registers k) (f : A → A) + (ticks queries work : A → ℕ → ℕ) + (body : ∀ v xs bits, Runs p O bits (Function.update (encode v) a xs) + (Function.update (encode (f v)) a xs) (ticks v xs.length) (queries v xs.length) (work v xs.length)) + (v : A) (xs : Word) (bits : ℕ → Bool) : + Runs (repeatBlock p a) O bits (Function.update (encode v) a xs) + (Function.update (encode (loopState f xs.length v)) a []) + (xs.length+loopAccum f ticks xs.length v+1) (loopAccum f queries xs.length v) + (xs.length+loopAccum f work xs.length v+1) := by + dsimp only [Runs, repeatBlock] + intro q c + induction xs generalizing v q c bits with + | nil => + have h := repeatProgram_empty p.code a O (encode v) q c bits + simpa [Runs,repeatBlock,state,loopConfig,loopAccum,loopState] using h + | cons x xs ih => + have hb := body v xs (fun i => bits (1+i)) q (c+1) + have hnone : (execution p.code O (state (Function.update (encode v) a xs) 0 q (c+1)) + (fun i => bits (1+i)) (ticks v xs.length)).output=none := by rw [hb]; rfl + have hl := execution_relabel_before_halt p.code (repeatProgram p.code a) (loopLabel p.size) + (lastLabel p.size) p.exit_halt (repeatProgram_body p.code a) O _ (fun i => bits (1+i)) + (ticks v xs.length) hnone + have hfirst : execution (repeatProgram p.code a) O + (state (Function.update (encode v) a (x::xs)) 0 q c) bits (1+ticks v xs.length)= + state (Function.update (encode (f v)) a xs) 0 (q+queries v xs.length) (c+1+work v xs.length) := by + rw [execution_add] + change execution _ O (execution (repeatProgram p.code a) O + (loopConfig (Function.update (encode v) a (x::xs)) 0 q c) bits 1) _ _ = _ + rw [repeatProgram_pop] + change execution _ O (relabelConfig _ (state (Function.update (encode v) a xs) 0 q (c+1))) _ _ = _ + rw [hl,hb] + simp [relabelConfig,state,loopLabel_last] + simp only [List.length_cons,loopAccum,loopState] + rw [show xs.length+1+(ticks v xs.length+loopAccum f ticks xs.length (f v))+1= + (1+ticks v xs.length)+(xs.length+loopAccum f ticks xs.length (f v)+1) by omega, + execution_add,hfirst] + have hi := ih (f v) (fun i => bits (1+ticks v xs.length+i)) + (q+queries v xs.length) (c+1+work v xs.length) + change execution (repeatProgram p.code a) O _ _ _ = _ at hi + rw [hi] + congr 1 <;> omega + +lemma loopAccum_le {A : Type*} (f : A → A) (g : A → ℕ → ℕ) (m B : ℕ) + (h : ∀ x i, i < m → g x i ≤ B) (x : A) : loopAccum f g m x ≤ m * B := by + induction m generalizing x with + | zero => simp [loopAccum] + | succ m ih => + have h₁ := h x m (by omega) + have h₂ := ih (fun x i hi => h x i (by omega)) (f x) + simpa only [loopAccum,Nat.succ_mul] using Nat.add_le_add h₁ h₂ |>.trans (by omega) + +lemma save_one {n : ℕ} (O : IndependenceOracle n) (x y s : Word) (bits : ℕ → Bool) : + Runs (pack 1 8) O bits (regs x y [] s) (regs x [] [] (pair y s)) + (3*y.length+2) 0 (3*y.length+2) := by + simpa only [pair,pairRegisters,update_regs_one,update_regs_eight] using + runs_pack (k:=1) 1 8 (by decide) O (regs x [] [] []) y s bits + +def iterationBody (p : Block 1) : Block 1 := seq (pack 1 8) (seq p (unpack 8 1)) +lemma iteration_body {n : ℕ} {O : IndependenceOracle n} {p : Block 1} {x y : Word} + {t q w : ℕ} (h : Computes p O x y t q w) (counter saved : Word) (bits : ℕ → Bool) : + Runs (iterationBody p) O bits (regs x counter [] saved) (regs y counter [] saved) + (6*counter.length+3+t) q (6*counter.length+3+w) := by + have hs := save_one O x counter saved bits + have hp := h (pair counter saved) (fun i => bits (3*counter.length+2+i)) + have hr := restore_one O y counter saved (fun i => bits (3*counter.length+2+(t+i))) + have ht := runs_seq O bits hs (runs_seq O _ hp hr) + convert ht using 1 <;> first | rfl | omega + +def iterateCode (p : Block 1) : Block 1 := seq (unpack 0 1) (repeatBlock (iterationBody p) 1) +lemma computes_iterate {n : ℕ} {A : Type*} (O : IndependenceOracle n) (p : Block 1) + (encode : A → Word) (f : A → A) (t q w : A → ℕ) + (h : ∀ x, Computes p O (encode x) (encode (f x)) (t x) (q x) (w x)) (x : A) (counter : Word) : + Computes (iterateCode p) O (pair counter (encode x)) (encode (loopState f counter.length x)) + (4*counter.length+loopAccum f (fun x i => 6*i+3+t x) counter.length x+2) + (loopAccum f (fun x _ => q x) counter.length x) + (4*counter.length+loopAccum f (fun x i => 6*i+3+w x) counter.length x+2) := by + intro saved bits + have hs := split_pair O counter (encode x) [] saved bits + simp only [List.append_nil] at hs + have hr := runs_repeat (iterationBody p) 1 O (fun x => regs (encode x) [] [] saved) f + (fun x i => 6*i+3+t x) (fun x _ => q x) (fun x i => 6*i+3+w x) + (by intro x xs bits; simpa only [update_regs_one] using iteration_body (h x) xs saved bits) + x counter (fun i => bits (3*counter.length+1+i)) + simp only [update_regs_one] at hr + have ht := runs_seq O bits hs hr + convert ht using 1 <;> first | rfl | omega + +lemma bounded_iterate {n : ℕ} {A : Type*} (O : IndependenceOracle n) (p : Block 1) + (encode : A → Word) (f : A → A) (B : ℕ) + (h : ∀x,Bounded p O (encode x) (encode (f x)) B) (x : A) (counter : Word) : + Bounded (iterateCode p) O (pair counter (encode x)) (encode (loopState f counter.length x)) + (counter.length*(6*counter.length+B+7)+2) := by + classical + choose t q w ht hq hw hc using h + have hc' := computes_iterate O p encode f t q w hc x counter + have ht' := loopAccum_le f (fun x i => 6*i+3+t x) counter.length (6*counter.length+3+B) + (by intro x i hi; have := ht x; omega) x + have hw' := loopAccum_le f (fun x i => 6*i+3+w x) counter.length (6*counter.length+3+B) + (by intro x i hi; have := hw x; omega) x + have hq' := loopAccum_le f (fun x _ => q x) counter.length B (by intro x _ _; exact hq x) x + refine ⟨_,_,_,?_,?_,?_,hc'⟩ <;> nlinarith + +def words : List Word → Word + | [] => [] + | x::xs => true :: pair x (words xs) +lemma words_length (xs : List Word) : (words xs).length = 2*(xs.map List.length).sum+2*xs.length := by + induction xs with + | nil => rfl + | cons x xs ih => simp only [words,List.length_cons,pair_length,List.map_cons,List.sum_cons,ih]; omega + +def foldWords {A X : Type*} (f : X → A → A) : List X → A → A + | [],s => s + | x::xs,s => foldWords f xs (f x s) +def foldCharge {A X : Type*} (f : X → A → A) (g : X → List X → A → ℕ) : List X → A → ℕ + | [],_ => 0 + | x::xs,s => g x xs s+foldCharge f g xs (f x s) + +lemma runs_repeat_cons {k n : ℕ} {p : Block k} {a : Fin (k+8)} {O : IndependenceOracle n} + {bits : ℕ → Bool} {R R' R'' : Registers k} {b : Bool} {xs : Word} + {t q w u v z : ℕ} + (hp : Runs p O (fun i => bits (1+i)) (Function.update R a xs) R' t q w) + (hi : Runs (repeatBlock p a) O (fun i => bits (1+t+i)) R' R'' u v z) : + Runs (repeatBlock p a) O bits (Function.update R a (b::xs)) R'' + (1+t+u) (q+v) (1+w+z) := by + dsimp only [Runs, repeatBlock] at * + intro q₀ w₀ + have hb := hp q₀ (w₀+1) + have hnone : (execution p.code O (state (Function.update R a xs) 0 q₀ (w₀+1)) + (fun i => bits (1+i)) t).output=none := by rw [hb]; rfl + have hl := execution_relabel_before_halt p.code (repeatProgram p.code a) (loopLabel p.size) + (lastLabel p.size) p.exit_halt (repeatProgram_body p.code a) O _ (fun i => bits (1+i)) t hnone + rw [execution_add,execution_add] + change execution _ O (execution _ O (execution (repeatProgram p.code a) O + (loopConfig (Function.update R a (b::xs)) 0 q₀ w₀) bits 1) _ _) _ _ = _ + rw [repeatProgram_pop] + change execution _ O (execution _ O (relabelConfig _ (state (Function.update R a xs) 0 q₀ (w₀+1))) _ _) _ _ = _ + rw [hl,hb] + simp only [relabelConfig,state,loopLabel_last] + have hh := hi (q₀+q) (w₀+1+w) + simpa [state,Nat.add_assoc] using hh + +lemma unpack_one_two {n : ℕ} (O : IndependenceOracle n) (a x tail s : Word) (bits : ℕ → Bool) : + Runs (unpack 1 2) O bits (regs a (pair x tail) [] s) (regs a tail x s) + (3*x.length+1) 0 (3*x.length+1) := by + simpa only [pair,pairRegisters,update_regs_one,update_regs_two] using + runs_unpack_packed (k:=1) 1 2 (by decide) O (regs a [] [] s) x tail bits +lemma pack_two_zero {n : ℕ} (O : IndependenceOracle n) (a x s : Word) (bits : ℕ → Bool) : + Runs (pack 2 0) O bits (regs a [] x s) (regs (pair x a) [] [] s) + (3*x.length+2) 0 (3*x.length+2) := by + simpa only [pair,pairRegisters,update_regs_zero,update_regs_two] using + runs_pack (k:=1) 2 0 (by decide) O (regs [] [] [] s) x a bits +lemma save_one_with_two {n : ℕ} (O : IndependenceOracle n) (a y x s : Word) (bits : ℕ → Bool) : + Runs (pack 1 8) O bits (regs a y x s) (regs a [] x (pair y s)) + (3*y.length+2) 0 (3*y.length+2) := by + simpa only [pair,pairRegisters,update_regs_one,update_regs_eight] using + runs_pack (k:=1) 1 8 (by decide) O (regs a [] x []) y s bits + +def listBody (p : Block 1) : Block 1 := + seq (unpack 1 2) (seq (pack 1 8) (seq (pack 2 0) (seq p (unpack 8 1)))) +lemma list_body {n : ℕ} {O : IndependenceOracle n} {p : Block 1} {x a b : Word} + {t q w : ℕ} (h : Computes p O (pair x a) b t q w) (tail saved : Word) (bits : ℕ → Bool) : + Runs (listBody p) O bits (regs a (pair x tail) [] saved) (regs b tail [] saved) + (6*x.length+6*tail.length+6+t) q (6*x.length+6*tail.length+6+w) := by + have h₁ := unpack_one_two O a x tail saved bits + have h₂ := save_one_with_two O a tail x saved (fun i => bits (3*x.length+1+i)) + have h₃ := pack_two_zero O a x (pair tail saved) (fun i => bits (3*x.length+1+(3*tail.length+2+i))) + have h₄ := h (pair tail saved) (fun i => bits (3*x.length+1+(3*tail.length+2+(3*x.length+2+i)))) + have h₅ := restore_one O b tail saved (fun i => bits (3*x.length+1+(3*tail.length+2+(3*x.length+2+(t+i))))) + have ht := runs_seq O bits h₁ (runs_seq O _ h₂ (runs_seq O _ h₃ (runs_seq O _ h₄ h₅))) + convert ht using 1 <;> first | rfl | omega + +lemma list_loop {n : ℕ} {A X : Type*} (O : IndependenceOracle n) (p : Block 1) + (encode : A → Word) (encX : X → Word) (f : X → A → A) (t q w : X → A → ℕ) + (h : ∀ x a, Computes p O (pair (encX x) (encode a)) (encode (f x a)) (t x a) (q x a) (w x a)) + (xs : List X) (a : A) (saved : Word) (bits : ℕ → Bool) : + Runs (repeatBlock (listBody p) 1) O bits (regs (encode a) (words (xs.map encX)) [] saved) + (regs (encode (foldWords f xs a)) [] [] saved) + (1+foldCharge f (fun x tail a => 7+6*(encX x).length+6*(words (tail.map encX)).length+t x a) xs a) + (foldCharge f (fun x _ a => q x a) xs a) + (1+foldCharge f (fun x tail a => 7+6*(encX x).length+6*(words (tail.map encX)).length+w x a) xs a) := by + induction xs generalizing a bits with + | nil => + dsimp only [Runs, repeatBlock] + intro q₀ w₀ + simpa only [repeatBlock,state,loopConfig,words,List.map_nil,foldWords,foldCharge,Nat.add_zero, + update_regs_one] using repeatProgram_empty (listBody p).code 1 O (regs (encode a) [] [] saved) q₀ w₀ bits + | cons x xs ih => + have hb := list_body (h x a) (words (xs.map encX)) saved (fun i => bits (1+i)) + have hr := runs_repeat_cons (R:=regs (encode a) [] [] saved) (b:=true) + (by simpa only [update_regs_one] using hb) + (ih (f x a) (fun i => bits (1+(6*(encX x).length+6*(words (xs.map encX)).length+6+t x a)+i))) + simp only [update_regs_one] at hr + convert hr using 1 <;> first | rfl | simp only [foldCharge]; omega + +def foldCode (p : Block 1) : Block 1 := seq (unpack 0 1) (repeatBlock (listBody p) 1) +lemma computes_fold {n : ℕ} {A X : Type*} (O : IndependenceOracle n) (p : Block 1) + (encode : A → Word) (encX : X → Word) (f : X → A → A) (t q w : X → A → ℕ) + (h : ∀ x a, Computes p O (pair (encX x) (encode a)) (encode (f x a)) (t x a) (q x a) (w x a)) + (xs : List X) (a : A) : + Computes (foldCode p) O (pair (words (xs.map encX)) (encode a)) (encode (foldWords f xs a)) + (3*(words (xs.map encX)).length+2+foldCharge f (fun x tail a => 7+6*(encX x).length+6*(words (tail.map encX)).length+t x a) xs a) + (foldCharge f (fun x _ a => q x a) xs a) + (3*(words (xs.map encX)).length+2+foldCharge f (fun x tail a => 7+6*(encX x).length+6*(words (tail.map encX)).length+w x a) xs a) := by + intro saved bits + have hs := split_pair O (words (xs.map encX)) (encode a) [] saved bits + simp only [List.append_nil] at hs + have hl := list_loop O p encode encX f t q w h xs a saved (fun i => bits (3*(words (xs.map encX)).length+1+i)) + have ht := runs_seq O bits hs hl + convert ht using 1 <;> first | rfl | omega + +def reverseCode : Block 1 := seq (reverse 0 1) (move 1 2 0) +lemma computes_reverse {n : ℕ} (O : IndependenceOracle n) (x : Word) : + Computes reverseCode O x x.reverse (6*x.length+3) 0 (6*x.length+3) := by + intro s bits + have hr := runs_reverse (k:=1) 0 1 (by decide) O (regs [] [] [] s) x [] bits + simp only [pairRegisters,update_regs_zero,update_regs_one,List.append_nil] at hr + have hm := move_one_zero O x.reverse [] s (fun i => bits (2*x.length+1+i)) + have ht := runs_seq O bits hr hm + simpa only [reverseCode,List.append_nil,List.length_reverse,Nat.zero_add, + show 2*x.length+1+(4*x.length+2)=6*x.length+3 by omega] using ht + +def boolListBlock : Block 1 where + size := 7 + code := fun pc => match pc.val with + | 0 => .pop 1 7 1 2 + | 1 => .push 0 true 3 + | 2 => .push 0 true 4 + | 3 => .push 0 false 5 + | 4 => .push 0 true 5 + | 5 => .push 0 false 6 + | 6 => .push 0 true 0 + | _ => .halt + exit_halt := rfl +lemma boolList_push (b : Bool) (s : Word) : true::false::b::true::s=true::pair [b] s := rfl +lemma runs_boolList {n : ℕ} (O : IndependenceOracle n) (x y s : Word) (bits : ℕ → Bool) : + Runs boolListBlock O bits (regs (words (y.map (fun b => [b]))) x [] s) + (regs (words ((x.reverse++y).map (fun b => [b]))) [] [] s) (5*x.length+1) 0 (5*x.length+1) := by + intro q w + induction x generalizing y w bits with + | nil => simp [execution,machineStep,boolListBlock,state,lastLabel] + | cons b xs ih => + have hh : execution boolListBlock.code O + (state (regs (words (y.map (fun b => [b]))) (b::xs) [] s) 0 q w) bits 5= + state (regs (words ((b::y).map (fun b => [b]))) xs [] s) 0 q (w+5) := by + cases b <;> simp [execution,machineStep,boolListBlock,state,words,pair,bitFrame,Nat.add_assoc] <;> rfl + rw [List.length_cons,show 5*(xs.length+1)+1=5+(5*xs.length+1) by omega,execution_add,hh,ih] + simp only [List.reverse_cons,List.append_assoc,List.singleton_append] + congr 1; omega + +def boolListCode : Block 1 := seq (reverse 0 1) boolListBlock +lemma computes_boolList {n : ℕ} (O : IndependenceOracle n) (x : Word) : + Computes boolListCode O x (words (x.map (fun b => [b]))) (7*x.length+2) 0 (7*x.length+2) := by + intro s bits + have hr := runs_reverse (k:=1) 0 1 (by decide) O (regs [] [] [] s) x [] bits + simp only [pairRegisters,update_regs_zero,update_regs_one,List.append_nil] at hr + have hb := runs_boolList O x.reverse [] s (fun i => bits (2*x.length+1+i)) + simp only [List.map_nil,words,List.reverse_reverse,List.append_nil,List.length_reverse] at hb + have ht := runs_seq O bits hr hb + convert ht using 1 <;> first | rfl | omega + +def consWordCode : Block 1 := seq (unpack 0 1) + (fork (.pop 1 false false true) (push 0 false) (push 0 true)) +lemma computes_consWord {n : ℕ} (O : IndependenceOracle n) (b : Bool) (x : Word) : + Computes consWordCode O (pair [b] x) (b::x) 6 0 6 := by + have h (b : Bool) : Computes (push 0 b) O x (b::x) 1 0 1 := by + intro s bits + simpa only [regs_zero,update_regs_zero] using runs_push O bits (regs x [] [] s) 0 b + have ht := computes_select (push 0 false) (push 0 true) b (x:=x) (y:=b::x) (by cases b <;> exact h _) + exact ht + +def consListCode : Block 1 := push 0 true +lemma computes_consList {n : ℕ} (O : IndependenceOracle n) (x : Word) (xs : List Word) : + Computes consListCode O (pair x (words xs)) (words (x::xs)) 1 0 1 := by + intro s bits + simpa only [regs_zero,update_regs_zero,consListCode,words] using runs_push O bits (regs (pair x (words xs)) [] [] s) 0 true + +def appendCode : Block 1 := seq (unpack 0 1) (move 1 2 0) +lemma computes_append {n : ℕ} (O : IndependenceOracle n) (x y : Word) : + Computes appendCode O (pair x y) (x++y) (7*x.length+3) 0 (7*x.length+3) := by + intro s bits + have hs := split_pair O x y [] s bits + simp only [List.append_nil] at hs + have hm := move_one_zero O x y s (fun i => bits (3*x.length+1+i)) + simpa only [appendCode,Nat.zero_add,show 3*x.length+1+(4*x.length+2)=7*x.length+3 by omega] using + runs_seq O bits hs hm + +def subBlock : Block 1 := ⟨16,subProgram 1 0 2,rfl⟩ +def subTime (x y : Word) : ℕ := subCost false x y+2*(subDigits false x y).length+1 +lemma runs_sub {n : ℕ} (O : IndependenceOracle n) (x y s : Word) + (hxy : binaryValue y≤binaryValue x) (bits : ℕ → Bool) : + Runs subBlock O bits (regs y x [] s) (regs [] (subDigits false x y) [] s) + (subTime x y) 0 (subTime x y) := by + dsimp only [Runs,subBlock] + intro q w + have h := (subtraction_block (k:=1) 1 0 2 (by decide) (by decide) (by decide) O + (regs [] [] [] s) x y hxy q w bits).2.2 + convert h using 1 <;> simp only [subTime,subConfig,state,tripleRegisters,pairRegisters,update_regs_zero, + update_regs_one,update_regs_two,lastLabel,Nat.add_zero] + rfl + +def subCode : Block 1 := seq (unpack 0 1) (seq subBlock (seq (move 1 2 0) normalCode)) +lemma computes_sub {n : ℕ} (O : IndependenceOracle n) (x y : Word) + (hxy : binaryValue y≤binaryValue x) : + Computes subCode O (pair x y) (binaryValue x-binaryValue y).bits + (3*x.length+1+subTime x y+4*(subDigits false x y).length+2+normalCost (subDigits false x y)) 0 + (3*x.length+1+subTime x y+4*(subDigits false x y).length+2+normalCost (subDigits false x y)) := by + have hv := (subtraction_block (k:=1) 1 0 2 (by decide) (by decide) (by decide) O + (regs [] [] [] []) x y hxy 0 0 (fun _ => false)).1 + intro s bits + have hs := split_pair O x y [] s bits + simp only [List.append_nil] at hs + have hd := runs_sub O x y s hxy (fun i => bits (3*x.length+1+i)) + have hm := move_one_zero O (subDigits false x y) [] s (fun i => bits (3*x.length+1+(subTime x y+i))) + simp only [List.append_nil] at hm + have hn := computes_normalCode O (subDigits false x y) s + (fun i => bits (3*x.length+1+(subTime x y+(4*(subDigits false x y).length+2+i)))) + rw [normalWord_eq_bits,hv] at hn + have hh := runs_seq O bits hs (runs_seq O _ hd (runs_seq O _ hm hn)) + convert hh using 1 <;> first | rfl | omega +lemma bounded_sub {n : ℕ} (O : IndependenceOracle n) (x y : Word) + (hxy : binaryValue y≤binaryValue x) : + Bounded subCode O (pair x y) (binaryValue x-binaryValue y).bits (30*(x.length+y.length+1)) := by + have h₁ := subDigits_length_cost false x y + have h₂ := normalCost_le (subDigits false x y) + refine ⟨_,0,_,?_,Nat.zero_le _,?_,computes_sub O x y hxy⟩ <;> dsimp only [subTime] <;> omega + +def rankPrep : Block 1 where + size := 5 + code := fun pc => match pc.val with + | 0 => .pop 0 5 1 3 + | 1 => .push 2 false 2 + | 2 => .push 1 false 0 + | 3 => .push 2 true 4 + | 4 => .push 1 false 0 + | _ => .halt + exit_halt := rfl +lemma runs_rankPrep {n : ℕ} (O : IndependenceOracle n) (x y z s : Word) (bits : ℕ → Bool) : + Runs rankPrep O bits (regs x y z s) + (regs [] (List.replicate x.length false++y) (x.reverse++z) s) (3*x.length+1) 0 (3*x.length+1) := by + dsimp only [Runs] + intro q w + induction x generalizing y z w bits with + | nil => simp [execution,machineStep,rankPrep,state,lastLabel] + | cons b xs ih => + have h : execution rankPrep.code O (state (regs (b::xs) y z s) 0 q w) bits 3= + state (regs xs (false::y) (b::z) s) 0 q (w+3) := by + cases b <;> simp [execution,machineStep,rankPrep,state,Nat.add_assoc] <;> rfl + rw [List.length_cons,show 3*(xs.length+1)+1=3+(3*xs.length+1) by omega,execution_add,h,ih] + simp only [List.reverse_cons,List.append_assoc,List.singleton_append,Nat.add_zero] + congr 1 + · simp [List.replicate_add,List.append_assoc] + · omega + +lemma update_regs_three_empty (x y z s : Word) : Function.update (regs x y z s) 3 []=regs x y z s := by + funext i; fin_cases i <;> simp [regs] +lemma greedyRegisters_regs (x y z s : Word) : greedyRegisters (regs [] [] [] s) x y z []=regs x y z s := by + funext i; fin_cases i <;> simp [greedyRegisters,regs] + +def readyRank (which : Bool) : Block 1 := ⟨32,rankProgram which,rfl⟩ +def rankCode (which : Bool) : Block 1 := seq rankPrep (seq (move 2 3 0) (seq (readyRank which) normalCode)) +def rankWord {n : ℕ} (O : IndependenceOracle n) (which : Bool) (x : Word) : ℕ := + binaryValue (rankBits which O x.reverse) +lemma popcountBits_length (xs ys : Word) : (popcountBits xs ys).length≤xs.length+ys.length := by + induction xs generalizing ys with + | nil => simp [popcountBits] + | cons b xs ih => + cases b with + | false => simpa only [popcountBits,Bool.false_eq_true,ite_false,List.length_cons] using + (ih ys).trans (by omega) + | true => + have h := ih (incrementBits ys) + have hi := incrementBits_length ys + simp only [popcountBits,ite_true,List.length_cons] + omega +lemma rankBits_length {n : ℕ} (O : IndependenceOracle n) (which : Bool) (x : Word) : + (rankBits which O x).length≤x.length := by + simpa only [rankBits,wordGreedy_length,List.length_nil,Nat.add_zero] using + popcountBits_length (wordGreedy (wordOracle which O) x []) [] +lemma computes_rank {n : ℕ} (O : IndependenceOracle n) (which : Bool) (x : Word) (hx : x.length=n) : + Computes (rankCode which) O x (rankWord O which x).bits + (7*n+3+rankTime which O x.reverse+normalCost (rankBits which O x.reverse)) + (greedyCalls x.reverse) + (7*n+3+rankWork which O x.reverse+normalCost (rankBits which O x.reverse)) := by + intro s bits + have hp := runs_rankPrep O x [] [] s bits + simp only [hx,List.append_nil] at hp + have hm := runs_move (k:=1) 2 3 0 (by decide) (by decide) (by decide) O + (regs [] (List.replicate n false) [] s) x.reverse [] (fun i => bits (3*n+1+i)) + simp only [tripleRegisters,pairRegisters,update_regs_zero,update_regs_two,update_regs_three_empty, + List.append_nil,List.length_reverse,hx] at hm + have hr : Runs (readyRank which) O (fun i => bits (3*n+1+(4*n+2+i))) + (regs x.reverse (List.replicate n false) [] s) (regs (rankBits which O x.reverse) [] [] s) + (rankTime which O x.reverse) (greedyCalls x.reverse) (rankWork which O x.reverse) := by + intro q w + convert rank_run which O (regs [] [] [] s) x.reverse (by simpa only [List.length_reverse] using hx) q w (fun i => bits (3*n+1+(4*n+2+i))) using 1 <;> + (try simp only [readyRank,state,rankConfig,greedyRegisters_regs,lastLabel]) <;> rfl + have hn := computes_normalCode O (rankBits which O x.reverse) s + (fun i => bits (3*n+1+(4*n+2+(rankTime which O x.reverse+i)))) + rw [normalWord_eq_bits] at hn + have hh := runs_seq O bits hp (runs_seq O _ hm (runs_seq O _ hr hn)) + convert hh using 1 <;> first | rfl | omega +lemma bounded_rank {n : ℕ} (O : IndependenceOracle n) (which : Bool) (x : Word) (hx : x.length=n) : + Bounded (rankCode which) O x (rankWord O which x).bits (100*(n+1)^2) := by + have hr : x.reverse.length=n := by simpa only [List.length_reverse] using hx + have ht := rankTime_bound which O x.reverse hr + have hw := rankWork_bound which O x.reverse hr + have hl := rankBits_length O which x.reverse + have hn := normalCost_le (rankBits which O x.reverse) + have hq := greedyCalls_bound x.reverse + simp only [List.length_reverse,hx] at hl hq + refine ⟨_,_,_,?_,?_,?_,computes_rank O which x hx⟩ <;> nlinarith + +lemma rankWord_correct {n : ℕ} (M₁ M₂ : Matroid (Fin n)) (O : IndependenceOracle n) + (hO : ExactOracles M₁ M₂ O) (hE₁ : M₁.E=Set.univ) (hE₂ : M₂.E=Set.univ) + (which : Bool) (x : Word) (hx : x.length=n) : + rankWord O which x=((if which then M₂ else M₁).eRk (wordSet n x)).toNat := by + simp only [rankWord,rankBits,popcount_value,binaryValue,Nat.zero_add] + have hr := wordGreedy_rank (if which then M₂ else M₁) (by cases which <;> assumption) + (wordOracle which O) (fun l _ => hO which (fun i => l[i.val]?.getD false)) x.reverse + (by simpa only [List.length_reverse] using hx) + simpa only [List.reverse_reverse] using hr +open scoped Classical in +lemma rankWord_eq_rankOracle {n : ℕ} (M₁ M₂ : Matroid (Fin n)) (O : IndependenceOracle n) + (hO : ExactOracles M₁ M₂ O) (hE₁ : M₁.E=Set.univ) (hE₂ : M₂.E=Set.univ) + (which : Bool) (x : Word) (hx : x.length=n) : + rankWord O which x=rankOracle O which (wordSet n x).toFinset := by + classical + rw [rankWord_correct M₁ M₂ O hO hE₁ hE₂ which x hx, + rankOracle_correct M₁ M₂ O hO hE₁ hE₂ which,Set.coe_toFinset] + +inductive DataType where + | unit | bool | nat | word + | prod : DataType → DataType → DataType + | list : DataType → DataType + +@[reducible] def Value : DataType → Type + | .unit => Unit + | .bool => Bool + | .nat => ℕ + | .word => Word + | .prod a b => Value a × Value b + | .list a => List (Value a) + +def encode : {a : DataType} → Value a → Word + | .unit,_ => [] + | .bool,b => [b] + | .nat,m => m.bits + | .word,w => w + | .prod _ _,(x,y) => pair (encode x) (encode y) + | .list _,xs => words (xs.map encode) + +def width {a : DataType} (x : Value a) : ℕ := (encode x).length + +inductive Expression : DataType → DataType → Type where + | ident {a} : Expression a a + | constant {a b} : Value b → Expression a b + | compose {a b c} : Expression a b → Expression b c → Expression a c + | both {a b c} : Expression a b → Expression a c → Expression a (.prod b c) + | fst {a b} : Expression (.prod a b) a + | snd {a b} : Expression (.prod a b) b + | branch {a b} : Expression a b → Expression a b → Expression (.prod .bool a) b + | fold {a b} : Expression (.prod a b) b → Expression (.prod (.list a) b) b + | cons {a} : Expression (.prod a (.list a)) (.list a) + | consBit : Expression (.prod .bool .word) .word + | append : Expression (.prod .word .word) .word + | reverse : Expression .word .word + | toList : Expression .word (.list .bool) + | toBits : Expression .nat .word + | toNat : Expression .word .nat + | add : Expression (.prod .nat .nat) .nat + | sub : Expression (.prod .nat .nat) .nat + | rank : Bool → Expression .word .nat + | mul : Expression (.prod .nat .nat) .nat + | less : Expression (.prod .nat .nat) .bool + | divRem : Expression (.prod .nat .nat) (.prod .nat .nat) + | query : Bool → Expression .word .bool + +def compile : {a b : DataType} → Expression a b → Block 1 + | _,_,.ident => skip 1 + | _,_,.constant x => constCode (encode x) + | _,_,.compose p q => seq (compile p) (compile q) + | _,_,.both p q => fanout (compile p) (compile q) + | _,_,.fst => first + | _,_,.snd => second + | _,_,.branch p q => selectCode (compile p) (compile q) + | _,_,.fold p => foldCode (compile p) + | _,_,.cons => consListCode + | _,_,.consBit => consWordCode + | _,_,.append => appendCode + | _,_,.reverse => reverseCode + | _,_,.toList => boolListCode + | _,_,.toBits => skip 1 + | _,_,.toNat => normalCode + | _,_,.add => addCode + | _,_,.sub => subCode + | _,_,.rank b => rankCode b + | _,_,.mul => mulCode + | _,_,.less => cmpCode + | _,_,.divRem => divCode + | _,_,.query b => queryCode b + +def evalFold {a b : DataType} (step : Value (.prod a b) → Option (Value b × ℕ)) : + List (Value a) → Value b → Option (Value b × ℕ) + | [],z => some (z,0) + | x::xs,z => do + let (z',c) ← step (x,z) + let (y,d) ← evalFold step xs z' + pure (y,7+6*width x+6*width (a:=.list a) xs+c+d) + +def evaluate {n : ℕ} (O : IndependenceOracle n) : {a b : DataType} → Expression a b → + Value a → Option (Value b × ℕ) + | _,_,.ident,x => some (x,0) + | _,_,.constant y,x => some (y,width x+width y+1) + | _,_,.compose p q,x => do + let (y,c) ← evaluate O p x + let (z,d) ← evaluate O q y + pure (z,c+d) + | _,_,.both p q,x => do + let (y,c) ← evaluate O p x + let (z,d) ← evaluate O q x + pure ((y,z),43*width x+39*width y+18*width z+50+c+d) + | _,_,.fst,(x,y) => some (x,7*width x+width y+4) + | _,_,.snd,(x,y) => some (y,4*width x+2) + | _,_,.branch p q,(b,x) => do + let (y,c) ← (if b then evaluate O q x else evaluate O p x) + pure (y,5+c) + | _,_,.fold p,(xs,z) => do + let (y,c) ← evalFold (evaluate O p) xs z + pure (y,3*width xs+2+c) + | _,_,.cons,(x,xs) => some (x::xs,1) + | _,_,.consBit,(b,xs) => some (b::xs,6) + | _,_,.append,(x,y) => some (x++y,7*x.length+3) + | _,_,.reverse,x => some (x.reverse,6*x.length+3) + | _,_,.toList,x => some (x,7*x.length+2) + | _,_,.toBits,x => some (x.bits,0) + | _,_,.toNat,x => some (binaryValue x,5*x.length+4) + | _,_,.add,(x,y) => some (x+y,20*(x.bits.length+y.bits.length+1)) + | _,_,.sub,(x,y) => if y≤x then some (x-y,30*(x.bits.length+y.bits.length+1)) else none + | _,_,.rank b,x => if x.length=n then some (rankWord O b x,100*(n+1)^2) else none + | _,_,.mul,(x,y) => some (x*y,60*(x.bits.length+y.bits.length+1)^2) + | _,_,.less,(x,y) => some (decide (x if x=0 then none else + some ((y%x,y/x),300*(x.bits.length+y.bits.length+1)^2) + | _,_,.query b,x => if x.length=n then + some (O b (fun i => x[i.val]?.getD false),3*n+3) else none + +lemma bounded_fanout {n : ℕ} {O : IndependenceOracle n} {p q : Block 1} {x y z : Word} {B C : ℕ} + (h : Bounded p O x y B) (g : Bounded q O x z C) : + Bounded (fanout p q) O x (pair y z) (43*x.length+39*y.length+18*z.length+50+B+C) := by + obtain ⟨t,a,w,ht,ha,hw,hp⟩ := h + obtain ⟨u,b,v,hu,hb,hv,hq⟩ := g + refine ⟨_,_,_,?_,?_,?_,computes_fanout hp hq⟩ <;> omega +lemma bounded_select {n : ℕ} {O : IndependenceOracle n} (p q : Block 1) (b : Bool) {x y : Word} {B : ℕ} + (h : Bounded (if b then q else p) O x y B) : + Bounded (selectCode p q) O (pair [b] x) y (5+B) := by + obtain ⟨t,a,w,ht,ha,hw,hp⟩ := h + refine ⟨_,_,_,?_,?_,?_,computes_select p q b hp⟩ <;> omega + +lemma computes_bounded {n : ℕ} {O : IndependenceOracle n} {p : Block 1} {x y : Word} {c : ℕ} + (h : Computes p O x y c 0 c) : Bounded p O x y c := + ⟨c,0,c,le_rfl,Nat.zero_le _,le_rfl,h⟩ + +lemma evalFold_loop {n : ℕ} {O : IndependenceOracle n} {a b : DataType} + (p : Block 1) (f : Value (.prod a b) → Option (Value b × ℕ)) + (hf : ∀ x y c, f x=some (y,c) → Bounded p O (encode x) (encode y) c) + (xs : List (Value a)) (z y : Value b) (c : ℕ) (h : evalFold f xs z=some (y,c)) : + ∃ t q w, t≤1+c ∧ q≤c ∧ w≤1+c ∧ ∀ s bits, + Runs (repeatBlock (listBody p) 1) O bits (regs (encode z) (encode (a:=.list a) xs) [] s) + (regs (encode y) [] [] s) t q w := by + induction xs generalizing z y c with + | nil => + simp only [evalFold,Option.some.injEq,Prod.mk.injEq] at h + rcases h with ⟨rfl,rfl⟩ + refine ⟨1,0,1,by omega,by omega,by omega,?_⟩ + intro s bits + dsimp only [Runs, repeatBlock] + intro q w + simpa only [repeatBlock,state,loopConfig,encode,List.map_nil,words,Nat.add_zero,update_regs_one] using + repeatProgram_empty (listBody p).code 1 O (regs (encode z) [] [] s) q w bits + | cons x xs ih => + cases h₁ : f (x,z) with + | none => simp [evalFold,h₁] at h + | some r => + rcases r with ⟨z',c₁⟩ + cases h₂ : evalFold f xs z' with + | none => simp [evalFold,h₁,h₂] at h + | some r => + rcases r with ⟨y',c₂⟩ + simp [evalFold,h₁,h₂] at h + rcases h with ⟨rfl,rfl⟩ + obtain ⟨t₁,q₁,w₁,ht₁,hq₁,hw₁,hp⟩ := hf _ _ _ h₁ + obtain ⟨t₂,q₂,w₂,ht₂,hq₂,hw₂,hr⟩ := ih z' y' c₂ h₂ + refine ⟨7+6*width x+6*width (a:=.list a) xs+t₁+t₂,q₁+q₂, + 7+6*width x+6*width (a:=.list a) xs+w₁+w₂,by omega,by omega,by omega,?_⟩ + intro s bits + have hb := list_body hp (encode (a:=.list a) xs) s (fun i => bits (1+i)) + have hh := runs_repeat_cons (R:=regs (encode z) [] [] s) (b:=true) + (by simpa only [update_regs_one] using hb) + (hr s (fun i => bits (1+(6*(encode x).length+6*(encode (a:=.list a) xs).length+6+t₁)+i))) + simp only [update_regs_one] at hh + convert hh using 1 <;> first | rfl | (dsimp only [width]; omega) + +lemma evalFold_bounded {n : ℕ} {O : IndependenceOracle n} {a b : DataType} + (p : Block 1) (f : Value (.prod a b) → Option (Value b × ℕ)) + (hf : ∀ x y c, f x=some (y,c) → Bounded p O (encode x) (encode y) c) + (xs : List (Value a)) (z y : Value b) (c : ℕ) (h : evalFold f xs z=some (y,c)) : + Bounded (foldCode p) O (encode (a:=.prod (.list a) b) (xs,z)) (encode y) (3*width (a:=.list a) xs+2+c) := by + obtain ⟨t,q,w,ht,hq,hw,hl⟩ := evalFold_loop p f hf xs z y c h + refine ⟨3*width (a:=.list a) xs+1+t,q,3*width (a:=.list a) xs+1+w,by omega,by omega,by omega,?_⟩ + intro s bits + have hs := split_pair O (encode (a:=.list a) xs) (encode z) [] s bits + simp only [List.append_nil] at hs + simpa only [Nat.zero_add, foldCode, encode, width] using runs_seq O bits hs (hl s (fun i => bits (3*width (a:=.list a) xs+1+i))) + +theorem compile_correct {n : ℕ} (O : IndependenceOracle n) {a b : DataType} + (e : Expression a b) : ∀ x y c, evaluate O e x=some (y,c) → + Bounded (compile e) O (encode x) (encode y) c := by + induction e with + | ident => + intro x y c h + simp only [evaluate,Option.some.injEq,Prod.mk.injEq] at h + rcases h with ⟨rfl,rfl⟩ + exact computes_bounded (computes_skip O _) + | constant v => + intro x y c h + simp only [evaluate,Option.some.injEq,Prod.mk.injEq] at h + rcases h with ⟨rfl,rfl⟩ + exact computes_bounded (computes_const O _ _) + | compose p q ihp ihq => + intro x y c h + cases hp : evaluate O p x with + | none => simp [evaluate,hp] at h + | some r => + rcases r with ⟨z,d⟩ + cases hq : evaluate O q z with + | none => simp [evaluate,hp,hq] at h + | some r => + rcases r with ⟨v,f⟩ + simp [evaluate,hp,hq] at h + rcases h with ⟨rfl,rfl⟩ + exact bounded_seq (ihp _ _ _ hp) (ihq _ _ _ hq) + | both p q ihp ihq => + intro x y c h + cases hp : evaluate O p x with + | none => simp [evaluate,hp] at h + | some r => + rcases r with ⟨z,d⟩ + cases hq : evaluate O q x with + | none => simp [evaluate,hp,hq] at h + | some r => + rcases r with ⟨v,f⟩ + simp [evaluate,hp,hq] at h + rcases h with ⟨rfl,rfl⟩ + exact bounded_fanout (ihp _ _ _ hp) (ihq _ _ _ hq) + | fst => + intro ⟨x,z⟩ y c h + simp only [evaluate,Option.some.injEq,Prod.mk.injEq] at h + rcases h with ⟨rfl,rfl⟩ + exact computes_bounded (computes_first O _ _) + | snd => + intro ⟨x,z⟩ y c h + simp only [evaluate,Option.some.injEq,Prod.mk.injEq] at h + rcases h with ⟨rfl,rfl⟩ + exact computes_bounded (computes_second O _ _) + | branch p q ihp ihq => + intro ⟨b,x⟩ y c h + have he : (if b then evaluate O q x else evaluate O p x)=evaluate O (if b then q else p) x := by cases b <;> rfl + cases hp : evaluate O (if b then q else p) x with + | none => simp [evaluate,he,hp] at h + | some r => + rcases r with ⟨z,d⟩ + simp [evaluate,he,hp] at h + rcases h with ⟨rfl,rfl⟩ + apply bounded_select + cases b with + | false => exact ihp _ _ _ hp + | true => exact ihq _ _ _ hp + | fold p ih => + intro ⟨xs,z⟩ y c h + cases hp : evalFold (evaluate O p) xs z with + | none => simp [evaluate,hp] at h + | some r => + rcases r with ⟨v,d⟩ + simp [evaluate,hp] at h + rcases h with ⟨rfl,rfl⟩ + exact evalFold_bounded (compile p) (evaluate O p) ih xs z v d hp + | cons => + intro ⟨x,xs⟩ y c h + simp only [evaluate,Option.some.injEq,Prod.mk.injEq] at h + rcases h with ⟨rfl,rfl⟩ + exact computes_bounded (computes_consList O _ _) + | consBit => + intro ⟨b,x⟩ y c h + simp only [evaluate,Option.some.injEq,Prod.mk.injEq] at h + rcases h with ⟨rfl,rfl⟩ + exact computes_bounded (computes_consWord O _ _) + | append => + intro ⟨x,z⟩ y c h + simp only [evaluate,Option.some.injEq,Prod.mk.injEq] at h + rcases h with ⟨rfl,rfl⟩ + exact computes_bounded (computes_append O _ _) + | reverse => + intro x y c h + simp only [evaluate,Option.some.injEq,Prod.mk.injEq] at h + rcases h with ⟨rfl,rfl⟩ + exact computes_bounded (computes_reverse O _) + | toList => + intro x y c h + simp only [evaluate,Option.some.injEq,Prod.mk.injEq] at h + rcases h with ⟨rfl,rfl⟩ + exact computes_bounded (computes_boolList O _) + | toBits => + intro x y c h + simp only [evaluate,Option.some.injEq,Prod.mk.injEq] at h + rcases h with ⟨rfl,rfl⟩ + exact computes_bounded (computes_skip O _) + | toNat => + intro x y c h + simp only [evaluate,Option.some.injEq,Prod.mk.injEq] at h + rcases h with ⟨rfl,rfl⟩ + have hh := computes_bounded (computes_normalCode O x) + rw [normalWord_eq_bits] at hh + exact bounded_mono hh (normalCost_le x) + | add => + intro ⟨x,z⟩ y c h + simp only [evaluate,Option.some.injEq,Prod.mk.injEq] at h + rcases h with ⟨rfl,rfl⟩ + simpa only [compile, encode, binaryValue_bits] using bounded_add O x.bits z.bits + | sub => + intro ⟨x,z⟩ y c h + simp only [evaluate] at h + by_cases hx : z≤x + · simp only [ite_eq_left hx,Option.some.injEq,Prod.mk.injEq] at h + rcases h with ⟨rfl,rfl⟩ + simpa only [compile,encode,binaryValue_bits] using bounded_sub O x.bits z.bits + (by simpa only [binaryValue_bits] using hx) + · simp [hx] at h + | rank b => + intro x y c h + simp only [evaluate] at h + by_cases hx : x.length=n + · simp only [ite_eq_left hx,Option.some.injEq,Prod.mk.injEq] at h + rcases h with ⟨rfl,rfl⟩ + exact bounded_rank O b x hx + · simp [hx] at h + | mul => + intro ⟨x,z⟩ y c h + simp only [evaluate,Option.some.injEq,Prod.mk.injEq] at h + rcases h with ⟨rfl,rfl⟩ + simpa only [compile, encode, binaryValue_bits] using bounded_mul O x.bits z.bits + | less => + intro ⟨x,z⟩ y c h + simp only [evaluate,Option.some.injEq,Prod.mk.injEq] at h + rcases h with ⟨rfl,rfl⟩ + simpa only [compile, encode, binaryValue_bits] using bounded_cmp O x.bits z.bits + | divRem => + intro ⟨x,z⟩ y c h + simp only [evaluate] at h + by_cases hx : x=0 + · simp [hx] at h + · simp only [ite_eq_right hx] at h + simp only [Option.some.injEq,Prod.mk.injEq] at h + rcases h with ⟨rfl,rfl⟩ + have hh := bounded_div O x.bits z.bits + rw [normalizedResult_pos _ _ (by simpa only [binaryValue_bits] using Nat.pos_of_ne_zero hx)] at hh + simpa only [compile, encode, binaryValue_bits] using hh + | query b => + intro x y c h + simp only [evaluate] at h + by_cases hx : x.length=n + · simp only [ite_eq_left hx] at h + simp only [Option.some.injEq,Prod.mk.injEq] at h + rcases h with ⟨rfl,rfl⟩ + exact ⟨n+3,1,3*n+3,by omega,by omega,le_rfl,computes_query O b x hx⟩ + · simp [hx] at h + +def foldValue {A B : Type*} (step : A × B → Option B) : List A → B → Option B + | [],z => some z + | x::xs,z => (step (x,z)).bind (foldValue step xs) + +def run {n : ℕ} (O : IndependenceOracle n) : {a b : DataType} → Expression a b → Value a → Option (Value b) + | _,_,.ident,x => some x + | _,_,.constant y,_ => some y + | _,_,.compose p q,x => (run O p x).bind (run O q) + | _,_,.both p q,x => do let y ← run O p x; let z ← run O q x; pure (y,z) + | _,_,.fst,(x,_) => some x + | _,_,.snd,(_,y) => some y + | _,_,.branch p q,(b,x) => if b then run O q x else run O p x + | _,_,.fold p,(xs,z) => foldValue (run O p) xs z + | _,_,.cons,(x,xs) => some (x::xs) + | _,_,.consBit,(b,xs) => some (b::xs) + | _,_,.append,(x,y) => some (x++y) + | _,_,.reverse,x => some x.reverse + | _,_,.toList,x => some x + | _,_,.toBits,x => some x.bits + | _,_,.toNat,x => some (binaryValue x) + | _,_,.add,(x,y) => some (x+y) + | _,_,.sub,(x,y) => if y≤x then some (x-y) else none + | _,_,.mul,(x,y) => some (x*y) + | _,_,.less,(x,y) => some (decide (x if x=0 then none else some (y%x,y/x) + | _,_,.query b,x => if x.length=n then some (O b (fun i => x[i.val]?.getD false)) else none + | _,_,.rank b,x => if x.length=n then some (rankWord O b x) else none + +lemma evalFold_forget {a b : DataType} (f : Value (.prod a b) → Option (Value b × ℕ)) + (g : Value (.prod a b) → Option (Value b)) (hfg : ∀ x,(f x).map Prod.fst=g x) + (xs : List (Value a)) (z : Value b) : (evalFold f xs z).map Prod.fst=foldValue g xs z := by + induction xs generalizing z with + | nil => rfl + | cons x xs ih => + rw [evalFold,foldValue,←hfg] + cases hf : f (x,z) with + | none => rfl + | some r => + rcases r with ⟨z',c⟩ + simp only [Option.map_some,Option.bind_some] + rw [←ih] + cases hh : evalFold f xs z' <;> simp [hh] +lemma evaluate_forget {n : ℕ} (O : IndependenceOracle n) {a b : DataType} (e : Expression a b) + (x : Value a) : (evaluate O e x).map Prod.fst=run O e x := by + induction e with + | compose p q ihp ihq => + simp only [evaluate,run,←ihp] + cases hp : evaluate O p x with + | none => rfl + | some r => + rcases r with ⟨y,c⟩ + simp only [Option.map_some,Option.bind_some] + rw [←ihq] + cases hh : evaluate O q y <;> simp [hh] + | both p q ihp ihq => + simp only [evaluate,run,←ihp,←ihq] + cases evaluate O p x <;> cases evaluate O q x <;> rfl + | branch p q ihp ihq => + rcases x with ⟨b,x⟩ + cases b <;> simp only [evaluate,run,Bool.false_eq_true,ite_false,ite_true,←ihp,←ihq] <;> + first | (cases evaluate O p x <;> rfl) | (cases evaluate O q x <;> rfl) + | fold p ih => + rcases x with ⟨xs,z⟩ + simp only [evaluate,run,←evalFold_forget (evaluate O p) (run O p) ih xs z] + cases evalFold (evaluate O p) xs z <;> rfl + | divRem => rcases x with ⟨x,y⟩; simp only [evaluate,run]; split_ifs <;> rfl + | sub => rcases x with ⟨x,y⟩; simp only [evaluate,run]; split_ifs <;> rfl + | query b => simp only [evaluate,run]; split_ifs <;> rfl + | rank b => simp only [evaluate,run]; split_ifs <;> rfl + | _ => rfl + +lemma compile_run {n : ℕ} (O : IndependenceOracle n) {a b : DataType} + (e : Expression a b) (x : Value a) (y : Value b) (h : run O e x=some y) : + ∃ B, Bounded (compile e) O (encode x) (encode y) B := by + rw [←evaluate_forget] at h + cases he : evaluate O e x with + | none => simp [he] at h + | some r => + rcases r with ⟨y',c⟩ + simp only [he,Option.map_some,Option.some.injEq] at h + subst y' + exact ⟨c,compile_correct O e x y c he⟩ + +namespace Expression +infixr:80 " >>> " => compose + +def onLeft {a b c} (p : Expression a b) : Expression (.prod a c) (.prod b c) := + both (fst >>> p) snd +def onRight {a b c} (p : Expression a b) : Expression (.prod c a) (.prod c b) := + both fst (snd >>> p) +def swap {a b} : Expression (.prod a b) (.prod b a) := both snd fst +def letIn {a b c} (p : Expression a b) (q : Expression (.prod a b) c) : Expression a c := + both ident p >>> q +def applyIf {a b} (test : Expression a .bool) (no yes : Expression a b) : Expression a b := + both test ident >>> branch no yes + +def boolNot : Expression .bool .bool := both ident ident >>> branch (constant true) (constant false) +def boolAnd : Expression (.prod .bool .bool) .bool := branch (constant false) ident +def natEqZero : Expression .nat .bool := both ident (constant 1) >>> less +def natSub : Expression (.prod .nat .nat) .nat := applyIf less sub (constant 0) +def natDivRem : Expression (.prod .nat .nat) (.prod .nat .nat) := + applyIf (fst >>> natEqZero) divRem (both snd (constant 0)) +def natDiv : Expression (.prod .nat .nat) .nat := natDivRem >>> snd +def natMod : Expression (.prod .nat .nat) .nat := natDivRem >>> fst + +def listReverse {a} : Expression (.list a) (.list a) := both ident (constant []) >>> fold cons + +def mapStep {a b c} (p : Expression (.prod a c) b) : Expression (.prod a (.prod (.list b) c)) (.prod (.list b) c) := + both + (both (both fst (snd >>> snd) >>> p) (snd >>> fst) >>> cons) + (snd >>> snd) +def mapWith {a b c} (p : Expression (.prod a c) b) : Expression (.prod (.list a) c) (.list b) := + both fst (both (constant []) snd) >>> fold (mapStep p) >>> fst >>> listReverse + +def listLength {a} : Expression (.list a) .nat := + both ident (constant 0) >>> fold (both snd (constant 1) >>> add) +def wordLength : Expression .word .nat := toList >>> listLength + +def wordRepeatStep : Expression (.prod .bool .word) .word := + letIn (snd >>> both ident ident >>> append) + (both fst snd >>> both (fst >>> fst) snd >>> branch ident (both (constant false) ident >>> consBit)) + +def unary : Expression .nat .word := + both (toBits >>> reverse >>> toList) (constant []) >>> fold wordRepeatStep + +end Expression + +lemma foldValue_eq_foldl {a b : DataType} (f : Value (.prod a b) → Option (Value b)) + (g : Value b → Value a → Value b) (hf : ∀ x z, f (x,z)=some (g z x)) + (xs : List (Value a)) (z : Value b) : foldValue f xs z=some (xs.foldl g z) := by + induction xs generalizing z with + | nil => rfl + | cons x xs ih => simp [foldValue,hf,ih] + +namespace Expression +variable {n : ℕ} (O : IndependenceOracle n) +@[simp] lemma run_boolNot (b : Bool) : run O boolNot b=some (!b) := by + cases b <;> rfl +@[simp] lemma run_boolAnd (b c : Bool) : run O boolAnd (b,c)=some (b && c) := by + cases b <;> rfl +@[simp] lemma run_natEqZero (m : ℕ) : run O natEqZero m=some (decide (m=0)) := by + simp [natEqZero,run] +@[simp] lemma run_natSub (x y : ℕ) : run O natSub (x,y)=some (x-y) := by + simp only [natSub,applyIf,run] + by_cases h : x simp [h] +@[simp] lemma run_natDiv (x y : ℕ) : run O natDiv (x,y)=some (y/x) := by + change ((run O natDivRem (x,y)).bind fun p => some p.2)=some (y/x) + rw [run_natDivRem]; rfl +@[simp] lemma run_natMod (x y : ℕ) : run O natMod (x,y)=some (y%x) := by + change ((run O natDivRem (x,y)).bind fun p => some p.1)=some (y%x) + rw [run_natDivRem]; rfl +lemma run_listReverse {a : DataType} (xs : List (Value a)) : + run O listReverse xs=some xs.reverse := by + simp only [listReverse,run] + have h := foldValue_eq_foldl (fun p : Value (.prod a (.list a)) => some (p.1::p.2)) + (fun zs x => x::zs) (fun _ _ => rfl) xs [] + simpa using h +lemma run_mapStep {a b c : DataType} (p : Expression (.prod a c) b) + (f : Value a → Value c → Value b) (hp : ∀ x z, run O p (x,z)=some (f x z)) + (x : Value a) (xs : List (Value b)) (z : Value c) : + run O (mapStep p) (x,(xs,z))=some (f x z::xs,z) := by + simp [mapStep,run,hp] +lemma run_mapWith {a b c : DataType} (p : Expression (.prod a c) b) + (f : Value a → Value c → Value b) (hp : ∀ x z, run O p (x,z)=some (f x z)) + (xs : List (Value a)) (z : Value c) : + run O (mapWith p) (xs,z)=some (xs.map (fun x => f x z)) := by + have hf : ∀ (ys : List (Value a)) (acc : List (Value b)), + foldValue (run O (mapStep p)) ys (acc,z)=some ((ys.map (fun x => f x z)).reverse++acc,z) := by + intro ys + induction ys with + | nil => intro acc; rfl + | cons x ys ih => intro acc; simp [foldValue,run_mapStep O p f hp,ih,List.append_assoc] + simp [mapWith,run,hf,run_listReverse] +lemma run_listLength {a : DataType} (xs : List (Value a)) : + run O listLength xs=some xs.length := by + have hf : ∀ (ys : List (Value a)) (z : ℕ), + foldValue (fun p : Value (.prod a .nat) => some (p.2+1)) ys z=some (z+ys.length) := by + intro ys + induction ys with + | nil => intro z; simp [foldValue] + | cons x ys ih => intro z; simpa [foldValue,ih] using congrArg some (by omega : z+1+ys.length=z+(ys.length+1)) + simp [listLength,run,hf] +lemma run_wordLength (xs : Word) : run O wordLength xs=some xs.length := by + simp [wordLength,run,run_listLength] +lemma run_wordRepeatStep (b : Bool) (w : Word) : + run O wordRepeatStep (b,w)=some (if b then false::(w++w) else w++w) := by + cases b <;> rfl +lemma unary_value (xs : List Bool) (w : Word) : + ∃ out, foldValue (run O wordRepeatStep) xs.reverse w=some out ∧ + out.length=2^xs.length*w.length+binaryValue xs := by + induction xs generalizing w with + | nil => exact ⟨w,rfl,by simp [binaryValue]⟩ + | cons b xs ih => + obtain ⟨u,hu,hl⟩ := ih w + have happ : ∀ (ys zs : List Bool) v, + foldValue (run O wordRepeatStep) (ys++zs) v= + (foldValue (run O wordRepeatStep) ys v).bind (foldValue (run O wordRepeatStep) zs) := by + intro ys + induction ys with + | nil => intros; rfl + | cons y ys ih => intros; simp [foldValue,ih,Option.bind_assoc] + refine ⟨(if b then false::(u++u) else u++u),?_,?_⟩ + · rw [List.reverse_cons,happ,hu] + simp only [Option.bind_some,foldValue] + rw [run_wordRepeatStep]; rfl + · cases b <;> simp [List.length_append,hl,binaryValue,Nat.pow_succ] <;> ring +lemma run_unary (m : ℕ) : ∃ w,run O unary m=some w ∧ w.length=m := by + obtain ⟨w,hw,hlen⟩ := unary_value O m.bits [] + refine ⟨w,?_,?_⟩ + · simpa [unary,run] using hw + · simpa [binaryValue_bits] using hlen +end Expression + +@[simp] lemma width_pair {a b : DataType} (x : Value a) (y : Value b) : + width (a:=.prod a b) (x,y)=2*width x+1+width y := by simp [width,encode] +@[simp] lemma width_nil {a : DataType} : width (a:=.list a) []=0 := rfl +@[simp] lemma width_cons {a : DataType} (x : Value a) (xs : List (Value a)) : + width (a:=.list a) (x::xs)=2*width x+2+width (a:=.list a) xs := by + simp [width,encode,words]; omega +lemma list_length_le_width {a : DataType} (xs : List (Value a)) : + xs.length≤width (a:=.list a) xs := by + induction xs with + | nil => rfl + | cons x xs ih => simp only [List.length_cons,width_cons]; omega + +def FoldSafe {A B : Type*} (ok : A×B → Prop) (f : A×B → Option B) : List A → B → Prop + | [],_ => True + | x::xs,z => ok (x,z) ∧ ∀ y,f (x,z)=some y → FoldSafe ok f xs y + +def Safe {n : ℕ} (O : IndependenceOracle n) (S : ℕ) : {a b : DataType} → + Expression a b → Value a → Prop + | _,_,e,x => width x≤S ∧ (∀ y,run O e x=some y → width y≤S) ∧ + match e,x with + | .compose p q,x => Safe O S p x ∧ ∀ y,run O p x=some y → Safe O S q y + | .both p q,x => Safe O S p x ∧ Safe O S q x + | .branch p q,(b,x) => if b then Safe O S q x else Safe O S p x + | .fold p,(xs,z) => FoldSafe (Safe O S p) (run O p) xs z + | _,_ => True + +lemma safe_input {n S : ℕ} {O : IndependenceOracle n} {a b : DataType} + {p : Expression a b} {x : Value a} (h : Safe O S p x) : width x≤S := by + cases p <;> exact h.1 +lemma safe_output {n S : ℕ} {O : IndependenceOracle n} {a b : DataType} + {p : Expression a b} {x : Value a} (h : Safe O S p x) {y : Value b} + (hr : run O p x=some y) : width y≤S := by + cases p <;> exact h.2.1 y hr + +def chargeBound : {a b : DataType} → Expression a b → ℕ → ℕ + | _,_,.compose p q,T => 10000*(T+1)^2+chargeBound p T+chargeBound q T + | _,_,.both p q,T => 10000*(T+1)^2+chargeBound p T+chargeBound q T + | _,_,.branch p q,T => 10000*(T+1)^2+chargeBound p T+chargeBound q T + | _,_,.fold p,T => 10000*(T+1)^2+(T+1)*(10000*(T+1)^2+chargeBound p T) + | _,_,_,T => 10000*(T+1)^2 + +lemma evalFold_charge {n : ℕ} (O : IndependenceOracle n) {a b : DataType} + (p : Expression (.prod a b) b) (S E : ℕ) + (hp : ∀ x y c,Safe O S p x → evaluate O p x=some (y,c) → c≤E) + (xs : List (Value a)) (z y : Value b) (c : ℕ) + (hs : FoldSafe (Safe O S p) (run O p) xs z) (hw : width (a:=.list a) xs≤S) + (he : evalFold (evaluate O p) xs z=some (y,c)) : + c≤xs.length*(7+12*S+E) := by + induction xs generalizing z y c with + | nil => simp [evalFold] at he; rcases he with ⟨rfl,rfl⟩; simp + | cons x xs ih => + rw [evalFold] at he + cases hh : evaluate O p (x,z) with + | none => simp [hh] at he + | some u => + rcases u with ⟨z',d⟩ + have hrun : run O p (x,z)=some z' := by rw [←evaluate_forget,hh]; rfl + have hd := hp (x,z) z' d hs.1 hh + have hw' : width (a:=.list a) xs≤S := by rw [width_cons] at hw; omega + have hx : width x≤S := by rw [width_cons] at hw; omega + cases ht : evalFold (evaluate O p) xs z' with + | none => simp [hh,ht] at he + | some u => + rcases u with ⟨y',e⟩ + simp [hh,ht] at he + rcases he with ⟨rfl,rfl⟩ + have hh := ih z' y' e (hs.2 z' hrun) hw' ht + simp only [List.length_cons,Nat.add_mul,Nat.one_mul] + omega + +lemma charge_primitive (T : ℕ) : 300*(2*T+1)^2+100*T+100≤10000*(T+1)^2 := by nlinarith + +lemma evaluate_charge {n : ℕ} (O : IndependenceOracle n) {a b : DataType} (p : Expression a b) + (S : ℕ) (x : Value a) (y : Value b) (c : ℕ) (hs : Safe O S p x) + (he : evaluate O p x=some (y,c)) : c≤chargeBound p (S+n) := by + induction p generalizing S c with + | compose p q ihp ihq => + rcases hs with ⟨hx,hy,hp,hq⟩ + simp only [evaluate] at he + cases hpv : evaluate O p x with + | none => simp [hpv] at he + | some u => + rcases u with ⟨z,d⟩ + have hr : run O p x=some z := by rw [←evaluate_forget,hpv]; rfl + have hd := ihp S x z d hp hpv + cases hqv : evaluate O q z with + | none => simp [hpv,hqv] at he + | some u => + rcases u with ⟨y',e⟩ + simp [hpv,hqv] at he + rcases he with ⟨rfl,rfl⟩ + have hh := ihq S z y' e (hq z hr) hqv + simp only [chargeBound]; omega + | both p q ihp ihq => + rcases hs with ⟨hx,hy,hp,hq⟩ + simp only [evaluate] at he + cases hpv : evaluate O p x with + | none => simp [hpv] at he + | some u => + rcases u with ⟨z,d⟩ + have hr : run O p x=some z := by rw [←evaluate_forget,hpv]; rfl + have hz := safe_output hp hr + have hd := ihp S x z d hp hpv + cases hqv : evaluate O q x with + | none => simp [hpv,hqv] at he + | some u => + rcases u with ⟨z',e⟩ + have hr' : run O q x=some z' := by rw [←evaluate_forget,hqv]; rfl + have hz' := safe_output hq hr' + simp [hpv,hqv] at he + rcases he with ⟨rfl,rfl⟩ + have hh := ihq S x z' e hq hqv + have hb := charge_primitive (S+n) + simp only [chargeBound]; nlinarith + | branch p q ihp ihq => + rcases x with ⟨b,x⟩ + rcases hs with ⟨hx,hy,hh⟩ + cases b <;> simp only [Bool.false_eq_true,ite_false,ite_true] at hh <;> + simp only [evaluate,Bool.false_eq_true,ite_false,ite_true] at he + · cases hv : evaluate O p x with + | none => simp [hv] at he + | some u => + rcases u with ⟨y',d⟩ + simp [hv] at he + rcases he with ⟨rfl,rfl⟩ + have hd := ihp S x y' d hh hv + have hb := charge_primitive (S+n) + simp only [chargeBound]; omega + · cases hv : evaluate O q x with + | none => simp [hv] at he + | some u => + rcases u with ⟨y',d⟩ + simp [hv] at he + rcases he with ⟨rfl,rfl⟩ + have hd := ihq S x y' d hh hv + have hb := charge_primitive (S+n) + simp only [chargeBound]; omega + | fold p ih => + rcases x with ⟨xs,z⟩ + rcases hs with ⟨hx,hy,hh⟩ + have hw : width (a:=.list _) xs≤S := by rw [width_pair] at hx; omega + have hlen := list_length_le_width xs + simp only [evaluate] at he + cases hv : evalFold (evaluate O p) xs z with + | none => simp [hv] at he + | some u => + rcases u with ⟨y',d⟩ + simp [hv] at he + rcases he with ⟨rfl,rfl⟩ + have hd := evalFold_charge O p S (chargeBound p (S+n)) (fun x y c => ih S x y c) xs z y' d hh hw hv + have hb := charge_primitive (S+n) + have hmul : xs.length*(7+12*S+chargeBound p (S+n))≤(S+n+1)*(10000*(S+n+1)^2+chargeBound p (S+n)) := + Nat.mul_le_mul (by omega) (by omega) + simp only [chargeBound]; omega + | ident => simp only [evaluate,Option.some.injEq,Prod.mk.injEq] at he; rcases he with ⟨rfl,rfl⟩; exact Nat.zero_le _ + | constant z => + have hx := safe_input hs + have hz := safe_output hs (y:=z) rfl + simp only [evaluate,Option.some.injEq,Prod.mk.injEq] at he + rcases he with ⟨rfl,rfl⟩ + have hb := charge_primitive (S+n) + simp only [chargeBound]; omega + | fst => + rcases x with ⟨u,v⟩ + have hx := safe_input hs + rw [width_pair] at hx + simp only [evaluate,Option.some.injEq,Prod.mk.injEq] at he + rcases he with ⟨rfl,rfl⟩ + have hb := charge_primitive (S+n) + simp only [chargeBound]; omega + | snd => + rcases x with ⟨u,v⟩ + have hx := safe_input hs + rw [width_pair] at hx + simp only [evaluate,Option.some.injEq,Prod.mk.injEq] at he + rcases he with ⟨rfl,rfl⟩ + have hb := charge_primitive (S+n) + simp only [chargeBound]; omega + | cons | consBit | append | add | sub | mul | less | divRem => + rcases x with ⟨x,y⟩ + have hx := safe_input hs + have hb := charge_primitive (S+n) + try simp only [width_pair] at hx + simp only [evaluate] at he + try split_ifs at he + all_goals + simp only [Option.some.injEq,Prod.mk.injEq] at he + try contradiction + rcases he with ⟨rfl,rfl⟩ + simp only [chargeBound,width,encode,pair_length] at hx ⊢ + nlinarith + | reverse | toList | toBits | toNat | rank | query => + have hx := safe_input hs + have hb := charge_primitive (S+n) + simp only [evaluate] at he + try split_ifs at he + all_goals + simp only [Option.some.injEq,Prod.mk.injEq] at he + try contradiction + rcases he with ⟨rfl,rfl⟩ + simp only [chargeBound,width,encode] at hx ⊢ + nlinarith + +def chargeDegree : {a b : DataType} → Expression a b → ℕ + | _,_,.compose p q => chargeDegree p+chargeDegree q+3 + | _,_,.both p q => chargeDegree p+chargeDegree q+3 + | _,_,.branch p q => chargeDegree p+chargeDegree q+3 + | _,_,.fold p => chargeDegree p+3 + | _,_,_ => 2 + +def chargeCoefficient : {a b : DataType} → Expression a b → ℕ + | _,_,.compose p q => 10000+chargeCoefficient p+chargeCoefficient q + | _,_,.both p q => 10000+chargeCoefficient p+chargeCoefficient q + | _,_,.branch p q => 10000+chargeCoefficient p+chargeCoefficient q + | _,_,.fold p => 20000+chargeCoefficient p + | _,_,_ => 10000 + +lemma monomial_add_bound (T C D e f x y : ℕ) (hx : x≤C*(T+1)^e) (hy : y≤D*(T+1)^f) : + 10000*(T+1)^2+x+y≤(10000+C+D)*(T+1)^(e+f+3) := by + have hbase : 1≤T+1 := by omega + have hp : (T+1)^2≤(T+1)^(e+f+3) := Nat.pow_le_pow_right hbase (by omega) + have he : (T+1)^e≤(T+1)^(e+f+3) := Nat.pow_le_pow_right hbase (by omega) + have hf : (T+1)^f≤(T+1)^(e+f+3) := Nat.pow_le_pow_right hbase (by omega) + have hx' := hx.trans (Nat.mul_le_mul_left C he) + have hy' := hy.trans (Nat.mul_le_mul_left D hf) + calc + _ ≤ 10000*(T+1)^(e+f+3)+C*(T+1)^(e+f+3)+D*(T+1)^(e+f+3) := by omega + _ = _ := by ring +lemma monomial_fold_bound (T C e x : ℕ) (hx : x≤C*(T+1)^e) : + 10000*(T+1)^2+(T+1)*(10000*(T+1)^2+x)≤(20000+C)*(T+1)^(e+3) := by + have hbase : 1≤T+1 := by omega + have hp : (T+1)^2≤(T+1)^(e+3) := Nat.pow_le_pow_right hbase (by omega) + have hq : (T+1)^3≤(T+1)^(e+3) := Nat.pow_le_pow_right hbase (by omega) + have he : (T+1)^(e+1)≤(T+1)^(e+3) := Nat.pow_le_pow_right hbase (by omega) + calc + _ ≤ 10000*(T+1)^2+(T+1)*(10000*(T+1)^2+C*(T+1)^e) := by gcongr + _ = 10000*(T+1)^2+10000*(T+1)^3+C*(T+1)^(e+1) := by ring + _ ≤ 10000*(T+1)^(e+3)+10000*(T+1)^(e+3)+C*(T+1)^(e+3) := by gcongr + _ = _ := by ring + +lemma chargeBound_polynomial {a b : DataType} (p : Expression a b) (T : ℕ) : + chargeBound p T≤chargeCoefficient p*(T+1)^chargeDegree p := by + induction p with + | compose p q ihp ihq | both p q ihp ihq | branch p q ihp ihq => + exact monomial_add_bound T _ _ _ _ _ _ ihp ihq + | fold p ih => exact monomial_fold_bound T _ _ _ ih + | ident | constant | fst | snd | cons | consBit | append | reverse | toList | toBits | toNat | + add | sub | mul | less | divRem | query | rank => exact Nat.le_refl _ + +lemma evaluate_polynomial {n : ℕ} (O : IndependenceOracle n) {a b : DataType} (p : Expression a b) + (S : ℕ) (x : Value a) (y : Value b) (c : ℕ) (hs : Safe O S p x) + (he : evaluate O p x=some (y,c)) : + c≤chargeCoefficient p*(S+n+1)^chargeDegree p := + (evaluate_charge O p S x y c hs he).trans (chargeBound_polynomial p (S+n)) + +lemma foldSafe_mono {A B : Type*} (p q : A×B → Prop) (f : A×B → Option B) + (hpq : ∀ x,p x → q x) (xs : List A) (z : B) (h : FoldSafe p f xs z) : + FoldSafe q f xs z := by + induction xs generalizing z with + | nil => trivial + | cons x xs ih => exact ⟨hpq _ h.1,fun y hy => ih y (h.2 y hy)⟩ +lemma safe_mono {n S T : ℕ} {O : IndependenceOracle n} {a b : DataType} + (p : Expression a b) (x : Value a) (h : Safe O S p x) (hST : S≤T) : Safe O T p x := by + induction p with + | compose p q ihp ihq => + exact ⟨h.1.trans hST,fun y hy => (h.2.1 y hy).trans hST, + ihp _ h.2.2.1,fun y hy => ihq _ (h.2.2.2 y hy)⟩ + | both p q ihp ihq => + exact ⟨h.1.trans hST,fun y hy => (h.2.1 y hy).trans hST,ihp _ h.2.2.1,ihq _ h.2.2.2⟩ + | branch p q ihp ihq => + refine ⟨h.1.trans hST,fun y hy => (h.2.1 y hy).trans hST,?_⟩ + rcases x with ⟨v,x⟩ + cases v <;> simp only [Bool.false_eq_true,ite_false,ite_true] at * + · exact ihp _ h.2.2 + · exact ihq _ h.2.2 + | fold p ih => + exact ⟨h.1.trans hST,fun y hy => (h.2.1 y hy).trans hST, + foldSafe_mono _ _ _ (fun x hx => ih x hx) _ _ h.2.2⟩ + | _ => exact ⟨h.1.trans hST,fun y hy => (h.2.1 y hy).trans hST,trivial⟩ + +lemma safe_compose {n S : ℕ} (O : IndependenceOracle n) {a b c : DataType} + (p : Expression a b) (q : Expression b c) (x : Value a) + (hp : Safe O S p x) (hq : ∀ y,run O p x=some y → Safe O S q y) : + Safe O S (.compose p q) x := by + refine ⟨safe_input hp,?_,hp,hq⟩ + intro z hz + simp only [run] at hz + cases he : run O p x with + | none => simp [he] at hz + | some y => + simp only [he,Option.bind_some] at hz + exact safe_output (hq y he) hz +lemma safe_both {n S : ℕ} (O : IndependenceOracle n) {a b c : DataType} + (p : Expression a b) (q : Expression a c) (x : Value a) + (hp : Safe O S p x) (hq : Safe O S q x) : + Safe O (3*S+1) (.both p q) x := by + have hS : S≤3*S+1 := by omega + refine ⟨(safe_input hp).trans hS,?_,safe_mono p x hp hS,safe_mono q x hq hS⟩ + intro z hz + simp only [run] at hz + cases he : run O p x with + | none => simp [he] at hz + | some y => + simp only [he] at hz + cases hf : run O q x with + | none => simp [hf] at hz + | some w => + simp only [hf,] at hz + have hh : (y,w)=z := Option.some.inj hz + cases hh + have hy := safe_output hp he + have hw := safe_output hq hf + rw [width_pair] + omega +lemma foldSafe_invariant {A B : Type*} (ok : A×B → Prop) (f : A×B → Option B) + (P : B → Prop) (xs : List A) (z : B) (hz : P z) + (hstep : ∀ x∈xs,∀ y,P y → ok (x,y) ∧ ∀ y',f (x,y)=some y' → P y') : + FoldSafe ok f xs z := by + induction xs generalizing z with + | nil => trivial + | cons x xs ih => + obtain ⟨hgood,hnext⟩ := hstep x (by simp) z hz + exact ⟨hgood,fun y hy => ih y (hnext y hy) (fun v hv => hstep v (by simp [hv]))⟩ +lemma foldValue_invariant {A B : Type*} (f : A×B → Option B) (P : B → Prop) + (xs : List A) (z : B) (hz : P z) + (hstep : ∀ x∈xs,∀ y,P y → ∀ y',f (x,y)=some y' → P y') + (y : B) (hy : foldValue f xs z=some y) : P y := by + induction xs generalizing z with + | nil => cases hy; exact hz + | cons x xs ih => + simp only [foldValue] at hy + cases he : f (x,z) with + | none => simp [he] at hy + | some w => + simp only [he,Option.bind_some] at hy + exact ih w (hstep x (by simp) z hz w he) (fun v hv => hstep v (by simp [hv])) hy +lemma safe_fold_invariant {n S : ℕ} (O : IndependenceOracle n) {a b : DataType} + (p : Expression (.prod a b) b) (xs : List (Value a)) (z : Value b) (P : Value b → Prop) + (hz : P z) (hw : width (a:=.prod (.list a) b) (xs,z)≤S) + (hwidth : ∀ y,P y → width y≤S) + (hstep : ∀ x∈xs,∀ y,P y → Safe O S p (x,y) ∧ ∀ y',run O p (x,y)=some y' → P y') : + Safe O S (.fold p) (xs,z) := by + refine ⟨hw,?_,foldSafe_invariant _ _ P xs z hz hstep⟩ + intro y hy + exact hwidth y (foldValue_invariant _ P xs z hz (fun x hx v hv => (hstep x hx v hv).2) y hy) + +inductive SizePolynomial where + | constant : ℕ → SizePolynomial + | input : SizePolynomial + | add : SizePolynomial → SizePolynomial → SizePolynomial + | mul : SizePolynomial → SizePolynomial → SizePolynomial +namespace SizePolynomial +def eval : SizePolynomial → ℕ → ℕ + | .constant c,_ => c + | .input,x => x + | .add p q,x => p.eval x+q.eval x + | .mul p q,x => p.eval x*q.eval x +def degree : SizePolynomial → ℕ + | .constant _ => 0 + | .input => 1 + | .add p q | .mul p q => p.degree+q.degree +def coefficient : SizePolynomial → ℕ + | .constant c => c + | .input => 1 + | .add p q => p.coefficient+q.coefficient + | .mul p q => p.coefficient*q.coefficient +lemma monotone (p : SizePolynomial) : Monotone p.eval := by + intro x y h + induction p with + | constant c => rfl + | input => exact h + | add p q ihp ihq => exact Nat.add_le_add ihp ihq + | mul p q ihp ihq => exact Nat.mul_le_mul ihp ihq +lemma bound (p : SizePolynomial) (x : ℕ) : p.eval x≤p.coefficient*(x+1)^p.degree := by + induction p with + | constant c => simp [eval,coefficient,degree] + | input => simp [eval,coefficient,degree] + | add p q ihp ihq => + have hp := Nat.pow_le_pow_right (by omega : 1≤x+1) (Nat.le_add_right p.degree q.degree) + have hq := Nat.pow_le_pow_right (by omega : 1≤x+1) (Nat.le_add_left q.degree p.degree) + dsimp only [eval,coefficient,degree] + calc + _ ≤ p.coefficient*(x+1)^(p.degree+q.degree)+q.coefficient*(x+1)^(p.degree+q.degree) := + Nat.add_le_add (ihp.trans (Nat.mul_le_mul_left _ hp)) (ihq.trans (Nat.mul_le_mul_left _ hq)) + _ = _ := by ring + | mul p q ihp ihq => + dsimp only [eval,coefficient,degree] + calc + _ ≤ (p.coefficient*(x+1)^p.degree)*(q.coefficient*(x+1)^q.degree) := Nat.mul_le_mul ihp ihq + _ = _ := by rw [pow_add]; ring +def subst : SizePolynomial → SizePolynomial → SizePolynomial + | .constant c,_ => .constant c + | .input,q => q + | .add p r,q => .add (p.subst q) (r.subst q) + | .mul p r,q => .mul (p.subst q) (r.subst q) +lemma eval_subst (p q : SizePolynomial) (x : ℕ) : (p.subst q).eval x=p.eval (q.eval x) := by + induction p <;> simp_all [subst,eval] +end SizePolynomial + +def Controlled {a b : DataType} (p : Expression a b) : Prop := + ∃ f : SizePolynomial,∀ {n : ℕ} (O : IndependenceOracle n) (x : Value a),Safe O (f.eval (width x)) p x +lemma controlled_input {a b : DataType} {p : Expression a b} (hp : Controlled p) : + ∃ C d : ℕ,∀ {n : ℕ} (O : IndependenceOracle n) (S : ℕ) (x : Value a), + width x≤S → Safe O (C*(S+1)^d) p x := by + obtain ⟨f,hf⟩ := hp + exact ⟨f.coefficient,f.degree,fun O S x hx => safe_mono p x (hf O x) + ((f.monotone hx).trans (f.bound S))⟩ +lemma controlled_compose {a b c : DataType} (p : Expression a b) (q : Expression b c) + (hp : Controlled p) (hq : Controlled q) : Controlled (.compose p q) := by + obtain ⟨f,hf⟩ := hp + obtain ⟨g,hg⟩ := hq + refine ⟨.add f (g.subst f),fun O x => ?_⟩ + apply safe_compose O p q x + · exact safe_mono p x (hf O x) (by simp only [SizePolynomial.eval]; omega) + · intro y hy + have h := safe_output (hf O x) hy + apply safe_mono q y (hg O y) + rw [SizePolynomial.eval,SizePolynomial.eval_subst] + exact (g.monotone h).trans (Nat.le_add_left _ _) +lemma controlled_both {a b c : DataType} (p : Expression a b) (q : Expression a c) + (hp : Controlled p) (hq : Controlled q) : Controlled (.both p q) := by + obtain ⟨f,hf⟩ := hp + obtain ⟨g,hg⟩ := hq + refine ⟨.add (.mul (.constant 3) (.add f g)) (.constant 1),fun O x => ?_⟩ + apply safe_both O p q x + · exact safe_mono p x (hf O x) (Nat.le_add_right _ _) + · exact safe_mono q x (hg O x) (Nat.le_add_left _ _) +lemma controlled_branch {a b : DataType} (p q : Expression a b) + (hp : Controlled p) (hq : Controlled q) : Controlled (.branch p q) := by + obtain ⟨f,hf⟩ := hp + obtain ⟨g,hg⟩ := hq + refine ⟨.add .input (.add f g),fun O x => ?_⟩ + rcases x with ⟨v,x⟩ + have hw : width x≤width (a:=.prod .bool a) (v,x) := by rw [width_pair]; omega + have hp' : Safe O (width (a:=.prod .bool a) (v,x)+ + (f.eval (width (a:=.prod .bool a) (v,x))+g.eval (width (a:=.prod .bool a) (v,x)))) p x := + safe_mono p x (hf O x) ((f.monotone hw).trans (by omega)) + have hq' : Safe O (width (a:=.prod .bool a) (v,x)+ + (f.eval (width (a:=.prod .bool a) (v,x))+g.eval (width (a:=.prod .bool a) (v,x)))) q x := + safe_mono q x (hg O x) ((g.monotone hw).trans (by omega)) + refine ⟨by simp only [SizePolynomial.eval]; omega,?_,?_⟩ + · intro y hy + cases v + · exact safe_output hp' hy + · exact safe_output hq' hy + · cases v + · exact hp' + · exact hq' + +@[simp] lemma width_nat (x : ℕ) : width (a:=.nat) x=x.bits.length := rfl +@[simp] lemma width_word (x : Word) : width (a:=.word) x=x.length := rfl +@[simp] lemma width_bool (x : Bool) : width (a:=.bool) x=1 := rfl +@[simp] lemma width_unit (x : Unit) : width (a:=.unit) x=0 := rfl +lemma bits_length_mono {a b : ℕ} (h : a≤b) : a.bits.length≤b.bits.length := by + simpa only [Nat.size_eq_bits_len] using Nat.size_le_size h +lemma bits_length_le_value (a : ℕ) : a.bits.length≤a := by + rw [Nat.size_eq_bits_len] + exact Nat.size_le.mpr a.lt_two_pow_self +lemma bits_length_add (a b : ℕ) : (a+b).bits.length≤a.bits.length+b.bits.length+1 := by + simp only [Nat.size_eq_bits_len] + apply Nat.size_le.mpr + have ha := Nat.lt_size_self a + have hb := Nat.lt_size_self b + have hpa : 1≤2^a.size := Nat.one_le_pow _ _ (by decide) + have hpb : 1≤2^b.size := Nat.one_le_pow _ _ (by decide) + rw [pow_succ,pow_add] + nlinarith +lemma bits_length_mul (a b : ℕ) : (a*b).bits.length≤a.bits.length+b.bits.length := by + simp only [Nat.size_eq_bits_len] + apply Nat.size_le.mpr + rw [pow_add] + calc + a*b≤(2^a.size)*b := Nat.mul_le_mul_right _ (Nat.lt_size_self a).le + _ < (2^a.size)*(2^b.size) := Nat.mul_lt_mul_of_pos_left (Nat.lt_size_self b) (by positivity) +lemma bits_length_binaryValue (x : Word) : (binaryValue x).bits.length≤x.length := by + rw [←normalWord_eq_bits] + exact normal_length x +lemma width_list_bool (x : Word) : width (a:=.list .bool) x=4*x.length := by + induction x with + | nil => rfl + | cons b xs ih => + rw [width_cons (a:=.bool),width_bool,ih,List.length_cons] + omega +lemma width_list_append {a : DataType} (x y : List (Value a)) : + width (a:=.list a) (x++y)=width (a:=.list a) x+width (a:=.list a) y := by + induction x with + | nil => simp + | cons z x ih => simp only [List.cons_append,width_cons,ih]; omega +lemma width_list_reverse {a : DataType} (x : List (Value a)) : + width (a:=.list a) x.reverse=width (a:=.list a) x := by + induction x with + | nil => rfl + | cons z x ih => simp only [List.reverse_cons,width_list_append,width_cons,width_nil,ih]; omega +lemma width_list_member {a : DataType} (x : Value a) (xs : List (Value a)) (h : x∈xs) : + width x≤width (a:=.list a) xs := by + induction xs with + | nil => cases h + | cons z zs ih => + simp only [List.mem_cons] at h + cases h with + | inl h => subst x; rw [width_cons]; omega + | inr h => have hi := ih h; rw [width_cons]; omega + +def Atomic : {a b : DataType} → Expression a b → Prop + | _,_,.compose _ _ | _,_,.both _ _ | _,_,.branch _ _ | _,_,.fold _ => False + | _,_,_ => True + +def constantWidth : {a b : DataType} → Expression a b → ℕ + | _,_,.constant x => width x + | _,_,_ => 0 +lemma safe_atomic {n S : ℕ} (O : IndependenceOracle n) {a b : DataType} + (p : Expression a b) (x : Value a) (ha : Atomic p) (hx : width x≤S) + (hy : ∀ y,run O p x=some y → width y≤S) : Safe O S p x := by + cases p <;> first | contradiction | exact ⟨hx,hy,trivial⟩ +lemma atomic_width {n : ℕ} (O : IndependenceOracle n) {a b : DataType} + (p : Expression a b) (x : Value a) (ha : Atomic p) (y : Value b) (hy : run O p x=some y) : + width y≤8*(width x+constantWidth p+1) := by + cases p with + | compose | both | branch | fold => contradiction + | ident => cases hy; simp only [constantWidth]; omega + | constant z => cases hy; simp only [constantWidth]; omega + | fst => + rcases x with ⟨u,v⟩ + cases hy + simp only [width_pair,constantWidth]; omega + | snd => + rcases x with ⟨u,v⟩ + cases hy + simp only [width_pair,constantWidth]; omega + | @cons a => + rcases x with ⟨u,v⟩ + cases hy + rw [width_pair (a := a) (b := .list a)] + simp only [width_cons,constantWidth]; omega + | consBit => + rcases x with ⟨u,v⟩ + cases hy + rw [width_pair (a := .bool) (b := .word)] + simp only [width_word,List.length_cons,width_bool,constantWidth]; omega + | append => + rcases x with ⟨u,v⟩ + cases hy + rw [width_pair (a := .word) (b := .word)] + simp only [width_word,List.length_append,constantWidth]; omega + | reverse => + cases hy + simp only [width_word,List.length_reverse,constantWidth]; omega + | toList => + cases hy + rw [width_list_bool] + simp only [width_word,constantWidth]; omega + | toBits => + cases hy + simp only [width_word,width_nat,constantWidth]; omega + | toNat => + cases hy + have h := bits_length_binaryValue x + simp only [width_word,width_nat,constantWidth]; omega + | add => + rcases x with ⟨u,v⟩ + cases hy + have h := bits_length_add u v + rw [width_pair (a := .nat) (b := .nat)] + simp only [width_nat,constantWidth]; omega + | mul => + rcases x with ⟨u,v⟩ + cases hy + have h := bits_length_mul u v + rw [width_pair (a := .nat) (b := .nat)] + simp only [width_nat,constantWidth]; omega + | sub => + rcases x with ⟨u,v⟩ + simp only [run] at hy + split_ifs at hy with hv + · cases hy + have h := bits_length_mono (Nat.sub_le u v) + rw [width_pair (a := .nat) (b := .nat)] + simp only [width_nat,constantWidth]; omega + | less => + simp only [width_bool,constantWidth]; omega + | divRem => + rcases x with ⟨u,v⟩ + simp only [run] at hy + split_ifs at hy with hv + · cases hy + have h₁ := bits_length_mono (Nat.mod_le v u) + have h₂ := bits_length_mono (Nat.div_le_self v u) + simp only [width_pair (a := .nat) (b := .nat),width_nat,constantWidth]; omega + | query b => simp only [width_bool,constantWidth]; omega + | rank b => + simp only [run] at hy + split_ifs at hy with hx + · cases hy + have h₁ := bits_length_binaryValue (rankBits b O x.reverse) + have h₂ := rankBits_length O b x.reverse + simp only [List.length_reverse] at h₂ + simp only [width_nat,width_word,constantWidth,rankWord]; omega +lemma controlled_atomic {a b : DataType} (p : Expression a b) (ha : Atomic p) : Controlled p := by + refine ⟨.mul (.constant 8) (.add (.add .input (.constant (constantWidth p))) (.constant 1)),fun O x => ?_⟩ + apply safe_atomic O p x ha + · dsimp [SizePolynomial.eval]; omega + · exact fun y hy => atomic_width O p x ha y hy + +lemma foldSafe_prefix {A B : Type*} (ok : A×B → Prop) (f : A×B → Option B) + (xs : List A) (z : B) + (h : ∀ pre x post,xs=pre++x::post → ∀ y,foldValue f pre z=some y → ok (x,y)) : + FoldSafe ok f xs z := by + induction xs generalizing z with + | nil => trivial + | cons x xs ih => + refine ⟨h [] x xs rfl z rfl,?_⟩ + intro y hy + apply ih y + intro pre a post he w hw + apply h (x::pre) a post (by simpa using congrArg (List.cons x) he) w + simp only [foldValue,hy,Option.bind_some] + exact hw + +lemma controlled_fold {a b : DataType} (p : Expression (.prod a b) b) + (hp : Controlled p) (g : SizePolynomial) + (hg : ∀ {n : ℕ} (O : IndependenceOracle n) (xs : List (Value a)) (z : Value b) + (pre post : List (Value a)),xs=pre++post → ∀ y,foldValue (run O p) pre z=some y → + width y≤g.eval (width (a:=.prod (.list a) b) (xs,z))) : + Controlled (.fold p) := by + obtain ⟨f,hf⟩ := hp + let vP : SizePolynomial := .add (.add (.mul (.constant 2) .input) (.constant 1)) g + let h : SizePolynomial := .add (.add .input g) (f.subst vP) + refine ⟨h,fun O x => ?_⟩ + rcases x with ⟨xs,z⟩ + have hS : width (a:=.prod (.list a) b) (xs,z)≤h.eval (width (a:=.prod (.list a) b) (xs,z)) := by + dsimp [h,SizePolynomial.eval]; omega + have hgS : g.eval (width (a:=.prod (.list a) b) (xs,z))≤h.eval (width (a:=.prod (.list a) b) (xs,z)) := by + dsimp [h,SizePolynomial.eval]; omega + refine ⟨hS,?_,?_⟩ + · intro y hy + exact (hg O xs z xs [] (by simp) y hy).trans hgS + · apply foldSafe_prefix + intro pre v post he y hy + have hay : width y≤g.eval (width (a:=.prod (.list a) b) (xs,z)) := hg O xs z pre (v::post) he y hy + have ha : width (a:=a) v≤width (a:=.prod (.list a) b) (xs,z) := by + have hm : v∈xs := by rw [he]; simp + have ha := width_list_member v xs hm + rw [width_pair]; omega + have hinput : width (a:=.prod a b) (v,y)≤vP.eval (width (a:=.prod (.list a) b) (xs,z)) := by + rw [width_pair] + dsimp [vP,SizePolynomial.eval] + omega + apply safe_mono p (v,y) (hf O (v,y)) + exact (f.monotone hinput).trans (by + dsimp only [h,SizePolynomial.eval] + rw [SizePolynomial.eval_subst] + omega) + +lemma mod_double_lt (a b : ℕ) (hb : 0 p + | k+1,p => gcdSteps k (gcdStep p) +lemma gcdSteps_zero (k a : ℕ) : gcdSteps k (a,0)=(a,0) := by + induction k with + | zero => rfl + | succ k ih => simpa [gcdSteps,gcdStep] using ih +lemma gcdSteps_done (k a b : ℕ) (hba : b≤a) (hk : a.size+b.size≤k) : + gcdSteps k (a,b)=(Nat.gcd a b,0) := by + induction k generalizing a b with + | zero => + have ha : a=0 := Nat.size_eq_zero.mp (by omega) + have hb : b=0 := Nat.size_eq_zero.mp (by omega) + simp [ha,hb,gcdSteps] + | succ k ih => + by_cases hb : b=0 + · subst b; simp [gcdSteps_zero] + · have hb' := Nat.pos_of_ne_zero hb + have hl := mod_size_lt a b hb' hba + have hs := Nat.size_le_size hba + have hh := ih b (a%b) (Nat.le_of_lt (Nat.mod_lt a hb')) (by omega) + simp only [gcdSteps,gcdStep,hb,ite_false] + rw [hh,Nat.gcd_comm b (a%b),←Nat.gcd_rec,Nat.gcd_comm b a] + +namespace Expression +abbrev NN := DataType.prod .nat .nat + +def sortPair : Expression NN NN := applyIf less ident swap +def gcdStepCode : Expression NN NN := + applyIf (snd >>> natEqZero) (both snd (swap >>> natMod)) ident + +def gcdCode : Expression NN .nat := + sortPair >>> both + (both (fst >>> toBits) (snd >>> toBits) >>> append >>> toList) + ident >>> fold (snd >>> gcdStepCode) >>> fst +lemma run_sortPair {n : ℕ} (O : IndependenceOracle n) (a b : ℕ) : + run O sortPair (a,b)=some (if a simp [h] +lemma run_gcdStepCode {n : ℕ} (O : IndependenceOracle n) (a b : ℕ) : + run O gcdStepCode (a,b)=some (gcdStep (a,b)) := by + by_cases hb : b=0 <;> + simp [gcdStepCode,applyIf,run,swap,natEqZero,natMod,natDivRem,gcdStep,hb] +lemma fold_gcdStepCode {n : ℕ} (O : IndependenceOracle n) (xs : List Bool) (p : ℕ × ℕ) : + foldValue (run O (snd (a:=.bool) >>> gcdStepCode)) xs p=some (gcdSteps xs.length p) := by + induction xs generalizing p with + | nil => rfl + | cons b xs ih => + rcases p with ⟨a,c⟩ + change ((run O gcdStepCode (a,c)).bind fun p => + foldValue (run O (snd (a:=.bool) >>> gcdStepCode)) xs p)=_ + rw [run_gcdStepCode,Option.bind_some,ih] + rfl +lemma run_gcdCode {n : ℕ} (O : IndependenceOracle n) (a b : ℕ) : + run O gcdCode (a,b)=some (Nat.gcd a b) := by + unfold gcdCode + have hs := run_sortPair O a b + simp only [run] + rw [hs] + simp only [Option.bind_some] + by_cases hab : a>> gcdStepCode)) (b.bits++a.bits) (b,a)).bind + fun p => some p.1)=some (Nat.gcd a b) + rw [fold_gcdStepCode] + simp only [List.length_append,Nat.size_eq_bits_len] + rw [gcdSteps_done _ _ _ (Nat.le_of_lt hab) (by rfl)] + simp [Nat.gcd_comm] + · simp only [hab,ite_false] + change ((foldValue (run O (snd (a:=.bool) >>> gcdStepCode)) (a.bits++b.bits) (a,b)).bind + fun p => some p.1)=some (Nat.gcd a b) + rw [fold_gcdStepCode] + simp only [List.length_append,Nat.size_eq_bits_len] + rw [gcdSteps_done _ _ _ (Nat.le_of_not_gt hab) (by rfl)] + rfl +end Expression + +open Expression +syntax "control" : tactic +macro_rules +| `(tactic| control) => `(tactic| + first + | assumption + | apply controlled_compose <;> control + | apply controlled_both <;> control + | apply controlled_branch <;> control + | exact controlled_atomic _ trivial) +lemma controlled_onLeft {a b c : DataType} (p : Expression a b) (hp : Controlled p) : + Controlled (onLeft (c:=c) p) := by unfold onLeft; control +lemma controlled_onRight {a b c : DataType} (p : Expression a b) (hp : Controlled p) : + Controlled (onRight (c:=c) p) := by unfold onRight; control +lemma controlled_swap {a b : DataType} : Controlled (Expression.swap (a:=a) (b:=b)) := by unfold Expression.swap; control +lemma controlled_letIn {a b c : DataType} (p : Expression a b) (q : Expression (.prod a b) c) + (hp : Controlled p) (hq : Controlled q) : Controlled (letIn p q) := by unfold letIn; control +lemma controlled_applyIf {a b : DataType} (p : Expression a .bool) (q r : Expression a b) + (hp : Controlled p) (hq : Controlled q) (hr : Controlled r) : Controlled (applyIf p q r) := by + unfold applyIf; control +lemma controlled_boolNot : Controlled boolNot := by unfold boolNot; control +lemma controlled_boolAnd : Controlled boolAnd := by unfold boolAnd; control +lemma controlled_natEqZero : Controlled natEqZero := by unfold natEqZero; control +lemma controlled_natSub : Controlled natSub := by unfold natSub; control +lemma controlled_natDivRem : Controlled natDivRem := by unfold natDivRem; control +lemma controlled_natDiv : Controlled natDiv := by unfold natDiv; control +lemma controlled_natMod : Controlled natMod := by unfold natMod; control +lemma controlled_listReverse {a : DataType} : Controlled (listReverse (a:=a)) := by + unfold listReverse + apply controlled_compose + · control + · apply controlled_fold _ (controlled_atomic (cons (a:=a)) trivial) (.mul (.constant 2) .input) + intro n O xs z pre post he y hy + have hh := foldValue_eq_foldl (run O (cons (a:=a))) (fun z x => x::z) (fun _ _ => rfl) pre z + rw [hh] at hy + cases hy + rw [List.foldl_flip_cons_eq_append',width_list_append,width_list_reverse] + have hp : width (a:=.list a) pre≤width (a:=.list a) xs := by rw [he,width_list_append]; omega + rw [width_pair (a:=.list a) (b:=.list a)] + dsimp [SizePolynomial.eval] + omega +lemma foldl_succ {A : Type*} (l : List A) (z : ℕ) : l.foldl (fun z _ => z+1) z=z+l.length := by + induction l generalizing z with + | nil => simp + | cons x xs ih => simp only [List.foldl_cons,ih,List.length_cons]; omega +lemma controlled_listLength {a : DataType} : Controlled (listLength (a:=a)) := by + unfold listLength + apply controlled_compose + · control + · apply controlled_fold _ (by control) (.mul (.constant 2) .input) + intro n O xs z pre post he y hy + have hh := foldValue_eq_foldl (run O (both (snd (a:=a)) (constant 1) >>> Expression.add)) (fun z (_ : Value a) => z+1) (fun _ _ => rfl) pre z + rw [hh] at hy + cases hy + have hv := foldl_succ pre z + rw [hv,width_nat] + have hbits := bits_length_add z pre.length + have hlen := bits_length_le_value pre.length + have hx := list_length_le_width xs + have hp : pre.length≤xs.length := by rw [he,List.length_append]; omega + rw [width_pair (a:=.list a) (b:=.nat),width_nat] + dsimp [SizePolynomial.eval] + omega +lemma controlled_wordLength : Controlled wordLength := by + exact controlled_compose _ _ (controlled_atomic _ trivial) controlled_listLength +lemma gcdSteps_max (k a b : ℕ) : (gcdSteps k (a,b)).1≤ max a b ∧ (gcdSteps k (a,b)).2≤ max a b := by + induction k generalizing a b with + | zero => exact ⟨Nat.le_max_left _ _,Nat.le_max_right _ _⟩ + | succ k ih => + by_cases hb : b=0 + · simpa [hb,gcdStep,gcdSteps] using ih a 0 + · have hi := ih b (a%b) + have hle : max b (a%b)≤ max a b := max_le (Nat.le_max_right _ _) ((Nat.mod_le _ _).trans (Nat.le_max_left _ _)) + simpa [gcdSteps,gcdStep,hb] using And.intro (hi.1.trans hle) (hi.2.trans hle) +lemma controlled_gcdStep : Controlled gcdStepCode := by unfold gcdStepCode; control +lemma controlled_gcd : Controlled gcdCode := by + unfold gcdCode + apply controlled_compose + · control + · apply controlled_compose + · control + · apply controlled_compose + · apply controlled_fold _ (by control) (.mul (.constant 4) .input) + intro n O xs z pre post he y hy + rcases z with ⟨a,b⟩ + rw [fold_gcdStepCode] at hy + cases hy + have hh := gcdSteps_max pre.length a b + have h₁ := bits_length_mono hh.1 + have h₂ := bits_length_mono hh.2 + have hm : (max a b).bits.length≤a.bits.length+b.bits.length := by + rcases le_total a b with h|h + · rw [max_eq_right h]; omega + · rw [max_eq_left h]; omega + rw [width_pair (a:=.nat) (b:=.nat),width_pair (a:=.list .bool) (b:=.prod .nat .nat), + width_pair (a:=.nat) (b:=.nat)] + simp only [width_nat,SizePolynomial.eval] + omega + · control + +open Expression + +def PolySafe {a b : DataType} (p : Expression a b) (R : ℕ → Value a → Prop) : Prop := + ∃ f : SizePolynomial,∀ {n : ℕ} (O : IndependenceOracle n) (S : ℕ) (x : Value a), + R S x → Safe O (f.eval S) p x +lemma polySafe_of_controlled {a b : DataType} (p : Expression a b) (hp : Controlled p) + (R : ℕ → Value a → Prop) (g : SizePolynomial) (hg : ∀ S x,R S x → width x≤g.eval S) : + PolySafe p R := by + obtain ⟨f,hf⟩ := hp + refine ⟨f.subst g,fun O S x hx => ?_⟩ + apply safe_mono p x (hf O x) + rw [SizePolynomial.eval_subst] + exact f.monotone (hg S x hx) +lemma polySafe_mono {a b : DataType} (p : Expression a b) {R Q : ℕ → Value a → Prop} + (hp : PolySafe p Q) (h : ∀ S x,R S x → Q S x) : PolySafe p R := by + obtain ⟨f,hf⟩ := hp + exact ⟨f,fun O S x hx => hf O S x (h S x hx)⟩ +lemma polySafe_compose {a b c : DataType} (p : Expression a b) (q : Expression b c) + (R : ℕ → Value a → Prop) (Q : ℕ → Value b → Prop) + (hp : PolySafe p R) (hq : PolySafe q Q) + (h : ∀ {n : ℕ} (O : IndependenceOracle n) S x,R S x → ∀ y,run O p x=some y → Q S y) : + PolySafe (p >>> q) R := by + obtain ⟨f,hf⟩ := hp + obtain ⟨g,hg⟩ := hq + refine ⟨.add f g,fun O S x hx => ?_⟩ + apply safe_compose O p q x + · exact safe_mono p x (hf O S x hx) (Nat.le_add_right _ _) + · intro y hy + exact safe_mono q y (hg O S y (h O S x hx y hy)) (Nat.le_add_left _ _) +lemma polySafe_both {a b c : DataType} (p : Expression a b) (q : Expression a c) + (R : ℕ → Value a → Prop) (hp : PolySafe p R) (hq : PolySafe q R) : + PolySafe (.both p q) R := by + obtain ⟨f,hf⟩ := hp + obtain ⟨g,hg⟩ := hq + refine ⟨.add (.mul (.constant 3) (.add f g)) (.constant 1),fun O S x hx => ?_⟩ + apply safe_both O p q x + · exact safe_mono p x (hf O S x hx) (Nat.le_add_right _ _) + · exact safe_mono q x (hg O S x hx) (Nat.le_add_left _ _) +lemma polySafe_fold {a b : DataType} (p : Expression (.prod a b) b) + (R : ℕ → Value (.prod (.list a) b) → Prop) (Q : ℕ → Value (.prod a b) → Prop) + (hp : PolySafe p Q) (g : SizePolynomial) + (hinput : ∀ S x,R S x → width x≤g.eval S) + (hacc : ∀ {n : ℕ} (O : IndependenceOracle n) S xs z,R S (xs,z) → + ∀ pre post,xs=pre++post → ∀ y,foldValue (run O p) pre z=some y → width y≤g.eval S) + (hstep : ∀ {n : ℕ} (O : IndependenceOracle n) S xs z,R S (xs,z) → + ∀ pre x post,xs=pre++x::post → ∀ y,foldValue (run O p) pre z=some y → Q S (x,y)) : + PolySafe (.fold p) R := by + obtain ⟨f,hf⟩ := hp + refine ⟨.add f g,fun O S x hx => ?_⟩ + obtain ⟨xs,z⟩ := x + refine ⟨(hinput S (xs,z) hx).trans (Nat.le_add_left _ _),?_,?_⟩ + · intro y hy + exact (hacc O S xs z hx xs [] (by simp) y hy).trans (Nat.le_add_left _ _) + · apply foldSafe_prefix + intro pre x post he y hy + exact safe_mono p (x,y) (hf O S (x,y) (hstep O S xs z hx pre x post he y hy)) + (Nat.le_add_right _ _) +lemma polySafe_controlled {a b : DataType} (p : Expression a b) + (hp : PolySafe p (fun S x => width x≤S)) : Controlled p := by + obtain ⟨f,hf⟩ := hp + exact ⟨f,fun O x => hf O (width x) x le_rfl⟩ + +lemma run_mapStep_partial {n : ℕ} (O : IndependenceOracle n) {a b c : DataType} + (p : Expression (.prod a c) b) (x : Value a) (zs : List (Value b)) (ctx : Value c) : + run O (mapStep p) (x,(zs,ctx))=(run O p (x,ctx)).map (fun v => (v::zs,ctx)) := by + simp only [mapStep,run,bind_pure_comp,Option.bind_some] + cases he : run O p (x,ctx) <;> simp [he] +lemma fold_mapStep_bound {n : ℕ} (O : IndependenceOracle n) {a b c : DataType} + (p : Expression (.prod a c) b) (xs : List (Value a)) (zs : List (Value b)) (ctx : Value c) + (U : ℕ) (hu : ∀ x∈xs,∀ v,run O p (x,ctx)=some v → width v≤U) + (y : Value (.prod (.list b) c)) (hy : foldValue (run O (mapStep p)) xs (zs,ctx)=some y) : + width (a:=.list b) y.1≤width (a:=.list b) zs+xs.length*(2*U+2) ∧ y.2=ctx := by + induction xs generalizing zs with + | nil => cases hy; simp + | cons x xs ih => + rw [foldValue,run_mapStep_partial] at hy + cases he : run O p (x,ctx) with + | none => simp [he] at hy + | some v => + simp only [he,Option.map_some,Option.bind_some] at hy + have hv := hu x (by simp) v he + have hh := ih (v::zs) (fun x hx => hu x (by simp [hx])) hy + rw [width_cons] at hh + refine ⟨?_,hh.2⟩ + simp only [List.length_cons,Nat.add_mul,Nat.one_mul] + omega +lemma controlled_mapStep {a b c : DataType} (p : Expression (.prod a c) b) (hp : Controlled p) : + Controlled (mapStep p) := by unfold mapStep; control +lemma controlled_mapFold {a b c : DataType} (p : Expression (.prod a c) b) (hp : Controlled p) : + Controlled (.fold (mapStep p)) := by + obtain ⟨f,hf⟩ := hp + let s : SizePolynomial := .add (.mul (.constant 3) .input) (.constant 1) + let g : SizePolynomial := .mul (.add (.mul (.constant 4) .input) (.constant 3)) + (.add (.mul (.constant 2) (f.subst s)) (.constant 3)) + apply controlled_fold _ (controlled_mapStep p ⟨f,hf⟩) g + intro n O xs z pre post he y hy + rcases z with ⟨zs,ctx⟩ + let W := width (a:=.prod (.list a) (.prod (.list b) c)) (xs,(zs,ctx)) + have hx : width (a:=.list a) xs≤W := by dsimp [W]; rw [width_pair (a:=.list a) (b:=.prod (.list b) c)]; omega + have hzs : width (a:=.list b) zs≤W := by dsimp [W]; rw [width_pair (a:=.list a) (b:=.prod (.list b) c),width_pair (a:=.list b) (b:=c)]; omega + have hc : width ctx≤W := by dsimp [W]; rw [width_pair (a:=.list a) (b:=.prod (.list b) c),width_pair (a:=.list b) (b:=c)]; omega + have hl : pre.length≤W := by + have hh := list_length_le_width xs + have he' := congrArg List.length he + simp only [List.length_append] at he' + omega + let U := f.eval (3*W+1) + have hh := fold_mapStep_bound O p pre zs ctx U (by + intro x hxp v hv + have hxx : x∈xs := by rw [he]; exact List.mem_append_left post hxp + have hxb := (width_list_member x xs hxx).trans hx + apply (safe_output (hf O (x,ctx)) hv).trans + apply f.monotone + rw [width_pair (a:=a) (b:=c)] + omega) y hy + have hm := Nat.mul_le_mul_right (2*U+2) hl + have hy' : width (a:=.list b) y.1≤W+W*(2*U+2) := by omega + change width y≤g.eval W + have hw : width y=2*width (a:=.list b) y.1+1+width ctx := by + obtain ⟨ys,vctx⟩ := y + change width (a:=.prod (.list b) c) (ys,vctx)=2*width (a:=.list b) ys+1+width ctx + rw [width_pair,show vctx=ctx from hh.2] + rw [hw] + simp only [g,SizePolynomial.eval,SizePolynomial.eval_subst] + change _≤(4*W+3)*(2*U+3) + nlinarith +lemma controlled_mapWith {a b c : DataType} (p : Expression (.prod a c) b) (hp : Controlled p) : + Controlled (mapWith p) := by + unfold mapWith + apply controlled_compose + · control + · apply controlled_compose + · exact controlled_mapFold p hp + · apply controlled_compose + · control + · exact controlled_listReverse + +def rationalPair (q : ℚ) : ℕ × ℕ := (q.num.natAbs,q.den) +def normalizePair (a b : ℕ) : ℕ × ℕ := + if b=0 then (0,1) else (a/Nat.gcd a b,b/Nat.gcd a b) +lemma rationalPair_div (a b : ℕ) : rationalPair ((a:ℚ)/(b:ℚ))=normalizePair a b := by + have he : (a:ℚ)/(b:ℚ)=mkRat (a:ℤ) b := by + simp only [Rat.mkRat_eq_divInt,Rat.divInt_eq_div,Int.cast_natCast] + rw [he] + by_cases hb : b=0 <;> + simp [rationalPair,normalizePair,Rat.num_mkRat,Rat.den_mkRat,hb,Nat.gcd_comm,Int.natAbs_ediv_of_nonneg] +lemma rationalPair_value {q : ℚ} (hq : 0≤q) : + ((rationalPair q).1:ℚ)/((rationalPair q).2:ℚ)=q := by + dsimp [rationalPair] + have hnum : 0≤q.num := Rat.num_nonneg.mpr hq + have he : (q.num.natAbs:ℚ)=(q.num:ℚ) := by + have hnat : (q.num.natAbs:ℤ)=q.num := Int.natAbs_of_nonneg hnum + simpa only [Int.cast_natCast] using congrArg (fun z : ℤ => (z:ℚ)) hnat + rw [he] + exact Rat.num_div_den q +lemma rationalPair_den (q : ℚ) : 0<(rationalPair q).2 := q.den_pos + +namespace Expression +lemma run_applyIf {n : ℕ} (O : IndependenceOracle n) {a b : DataType} + (p : Expression a .bool) (q r : Expression a b) (x : Value a) : + run O (applyIf p q r) x=(run O p x).bind (fun t => if t then run O r x else run O q x) := by + simp [applyIf,run,Option.bind_assoc] +lemma run_letIn {n : ℕ} (O : IndependenceOracle n) {a b c : DataType} + (p : Expression a b) (q : Expression (.prod a b) c) (x : Value a) : + run O (letIn p q) x=(run O p x).bind (fun y => run O q (x,y)) := by + simp [letIn,run,Option.bind_assoc] + +def normalizeRat : Expression NN NN := applyIf (snd >>> natEqZero) + (letIn gcdCode (both + (both snd (fst >>> fst) >>> natDiv) + (both snd (fst >>> snd) >>> natDiv))) + (constant (0,1)) + +def ratCross : Expression (.prod NN NN) NN := both + (both (fst >>> fst) (snd >>> snd) >>> mul) + (both (snd >>> fst) (fst >>> snd) >>> mul) +def ratAdd : Expression (.prod NN NN) NN := + both (ratCross >>> add) (both (fst >>> snd) (snd >>> snd) >>> mul) >>> normalizeRat +def ratMul : Expression (.prod NN NN) NN := + both (both (fst >>> fst) (snd >>> fst) >>> mul) + (both (fst >>> snd) (snd >>> snd) >>> mul) >>> normalizeRat +def ratDiv : Expression (.prod NN NN) NN := ratCross >>> normalizeRat +def ratLess : Expression (.prod NN NN) .bool := ratCross >>> less + +def ratMinOne : Expression NN NN := applyIf (swap >>> less) ident (constant (1,1)) + +lemma run_normalizeRat {n : ℕ} (O : IndependenceOracle n) (a b : ℕ) : + run O normalizeRat (a,b)=some (normalizePair a b) := by + rw [normalizeRat,run_applyIf] + change ((run O natEqZero b).bind fun t => if t then some (0,1) else _)=_ + rw [run_natEqZero] + by_cases hb : b=0 + · simp [hb,normalizePair] + · simp only [hb,decide_false,Option.bind_some,Bool.false_eq_true,ite_false] + rw [run_letIn,run_gcdCode] + change (do + let x ← run O natDiv (Nat.gcd a b,a) + let y ← run O natDiv (Nat.gcd a b,b) + pure (x,y))=some (normalizePair a b) + rw [run_natDiv O _ _,run_natDiv O _ _] + simp [normalizePair,hb] +lemma run_normalizeRat_pair {n : ℕ} (O : IndependenceOracle n) (a b : ℕ) : + run O normalizeRat (a,b)=some (rationalPair ((a:ℚ)/(b:ℚ))) := by + rw [rationalPair_div] + exact run_normalizeRat O a b +lemma run_ratCross {n : ℕ} (O : IndependenceOracle n) (a b c d : ℕ) : + run O ratCross ((a,b),(c,d))=some (a*d,c*b) := rfl +lemma run_ratAdd_raw {n : ℕ} (O : IndependenceOracle n) (a b c d : ℕ) : + run O ratAdd ((a,b),(c,d))=some (normalizePair (a*d+c*b) (b*d)) := by + change run O normalizeRat (a*d+c*b,b*d)=_ + exact run_normalizeRat O _ _ +lemma run_ratMul_raw {n : ℕ} (O : IndependenceOracle n) (a b c d : ℕ) : + run O ratMul ((a,b),(c,d))=some (normalizePair (a*c) (b*d)) := by + change run O normalizeRat (a*c,b*d)=_ + exact run_normalizeRat O _ _ +lemma run_ratDiv_raw {n : ℕ} (O : IndependenceOracle n) (a b c d : ℕ) : + run O ratDiv ((a,b),(c,d))=some (normalizePair (a*d) (c*b)) := by + change run O normalizeRat (a*d,c*b)=_ + exact run_normalizeRat O _ _ +lemma run_ratAdd {n : ℕ} (O : IndependenceOracle n) (q r : ℚ) (hq : 0≤q) (hr : 0≤r) : + run O ratAdd (rationalPair q,rationalPair r)=some (rationalPair (q+r)) := by + rw [run_ratAdd_raw,←rationalPair_div] + congr 2 + conv_rhs => rw [←rationalPair_value hq,←rationalPair_value hr] + push_cast + have hb : (rationalPair q).2 ≠ 0 := (rationalPair_den q).ne' + have hd : (rationalPair r).2 ≠ 0 := (rationalPair_den r).ne' + field_simp +lemma run_ratMul {n : ℕ} (O : IndependenceOracle n) (q r : ℚ) (hq : 0≤q) (hr : 0≤r) : + run O ratMul (rationalPair q,rationalPair r)=some (rationalPair (q*r)) := by + rw [run_ratMul_raw,←rationalPair_div] + congr 2 + conv_rhs => rw [←rationalPair_value hq,←rationalPair_value hr] + push_cast + ring +lemma run_ratDiv {n : ℕ} (O : IndependenceOracle n) (q r : ℚ) (hq : 0≤q) (hr : 0≤r) : + run O ratDiv (rationalPair q,rationalPair r)=some (rationalPair (q/r)) := by + rw [run_ratDiv_raw,←rationalPair_div] + congr 2 + conv_rhs => rw [←rationalPair_value hq,←rationalPair_value hr] + push_cast + simp only [div_eq_mul_inv,mul_inv_rev,inv_inv] + ring +lemma run_ratLess {n : ℕ} (O : IndependenceOracle n) (q r : ℚ) (hq : 0≤q) (hr : 0≤r) : + run O ratLess (rationalPair q,rationalPair r)=some (decide (q rw [←rationalPair_value hq,←rationalPair_value hr] + have hb : (0:ℚ)<(rationalPair q).2 := by exact_mod_cast rationalPair_den q + have hd : (0:ℚ)<(rationalPair r).2 := by exact_mod_cast rationalPair_den r + rw [div_lt_div_iff₀ hb hd] + norm_cast +lemma run_ratMinOne {n : ℕ} (O : IndependenceOracle n) (q : ℚ) (hq : 0≤q) : + run O ratMinOne (rationalPair q)=some (rationalPair (min 1 q)) := by + have hv := rationalPair_value hq + have hd : (0:ℚ)<(rationalPair q).2 := by exact_mod_cast rationalPair_den q + have hcmp : (rationalPair q).2<(rationalPair q).1 ↔ (1:ℚ) rw [←hv,lt_div_iff₀ hd,one_mul] + norm_cast + by_cases h : 1>> fold (snd >>> p) +def iterateNat {a : DataType} (p : Expression a a) : Expression (.prod .nat a) a := + onLeft unary >>> iterateWord p + +def fromList : Expression (.list .bool) .word := + both (listReverse) (constant []) >>> fold consBit + +lemma foldValue_iterate {n : ℕ} (O : IndependenceOracle n) {a : DataType} (p : Expression a a) + (f : Value a → Value a) (hp : ∀ x,run O p x=some (f x)) (xs : List Bool) (z : Value a) : + foldValue (run O (snd (a:=.bool) >>> p)) xs z=some ((f^[xs.length]) z) := by + induction xs generalizing z with + | nil => rfl + | cons b xs ih => + change ((run O p z).bind fun y => foldValue (run O (snd (a:=.bool) >>> p)) xs y)=_ + rw [hp,Option.bind_some,ih] + rfl +lemma run_iterateWord {n : ℕ} (O : IndependenceOracle n) {a : DataType} (p : Expression a a) + (f : Value a → Value a) (hp : ∀ x,run O p x=some (f x)) (w : Word) (z : Value a) : + run O (iterateWord p) (w,z)=some ((f^[w.length]) z) := by + change foldValue (run O (snd (a:=.bool) >>> p)) w z=_ + exact foldValue_iterate O p f hp w z +lemma run_iterateNat {n : ℕ} (O : IndependenceOracle n) {a : DataType} (p : Expression a a) + (f : Value a → Value a) (hp : ∀ x,run O p x=some (f x)) (k : ℕ) (z : Value a) : + run O (iterateNat p) (k,z)=some ((f^[k]) z) := by + obtain ⟨w,hw,hlen⟩ := run_unary O k + simp only [iterateNat,onLeft,run,Option.bind_some] + rw [hw] + change run O (iterateWord p) (w,z)=_ + rw [run_iterateWord O p f hp,hlen] +lemma run_fromList {n : ℕ} (O : IndependenceOracle n) (xs : List Bool) : + run O fromList xs=some xs := by + simp only [fromList,run] + rw [run_listReverse] + change foldValue (run O consBit) xs.reverse []=some xs + have hh := foldValue_eq_foldl (run O consBit) (fun z x => x::z) (fun _ _ => rfl) xs.reverse [] + simpa using hh + +def rangeStepCode : Expression (.prod .nat (.list .nat)) (.prod .nat (.list .nat)) := + both (both fst (constant 1) >>> add) (both fst snd >>> cons) +def rangeCode : Expression .nat (.list .nat) := + both ident (constant (0,[])) >>> iterateNat rangeStepCode >>> snd >>> listReverse + +def rangeStep (p : ℕ × List ℕ) : ℕ × List ℕ := (p.1+1,p.1::p.2) +lemma rangeStep_iterate (k : ℕ) : (rangeStep^[k]) (0,[])=(k,(List.range k).reverse) := by + induction k with + | zero => rfl + | succ k ih => rw [Function.iterate_succ_apply',ih]; simp [rangeStep,List.range_succ] +lemma run_rangeCode {n : ℕ} (O : IndependenceOracle n) (k : ℕ) : + run O rangeCode k=some (List.range k) := by + have hh := run_iterateNat O rangeStepCode rangeStep (fun _ => rfl) k (0,[]) + change ((run O (iterateNat rangeStepCode) (k,(0,[]))).bind fun p => run O listReverse p.2)=_ + rw [hh,rangeStep_iterate,Option.bind_some,run_listReverse,List.reverse_reverse] + +abbrev SplitState (a : DataType) := DataType.prod .nat (.prod (.list a) (.list a)) +def splitStep {a : DataType} : Expression (.prod a (SplitState a)) (SplitState a) := + applyIf (snd >>> fst >>> natEqZero) + (both (both (snd >>> fst) (constant 1) >>> natSub) + (both (both fst (snd >>> snd >>> fst) >>> cons) (snd >>> snd >>> snd))) + (both (snd >>> fst) + (both (snd >>> snd >>> fst) (both fst (snd >>> snd >>> snd) >>> cons))) +def splitAtCode {a : DataType} : Expression (.prod (.list a) .nat) (.prod (.list a) (.list a)) := + both fst (both snd (constant ([],[]))) >>> fold splitStep >>> snd >>> + both (fst >>> listReverse) (snd >>> listReverse) +def takeCode {a : DataType} : Expression (.prod (.list a) .nat) (.list a) := splitAtCode >>> fst +def dropCode {a : DataType} : Expression (.prod (.list a) .nat) (.list a) := splitAtCode >>> snd + +def splitStepValue {a : DataType} (p : Value a × (ℕ × (List (Value a) × List (Value a)))) := + if p.2.1=0 then (0,(p.2.2.1,p.1::p.2.2.2)) else (p.2.1-1,(p.1::p.2.2.1,p.2.2.2)) +lemma run_splitStep {n : ℕ} (O : IndependenceOracle n) {a : DataType} (x : Value a) + (k : ℕ) (u v : List (Value a)) : run O splitStep (x,(k,(u,v)))=some (splitStepValue (x,(k,(u,v)))) := by + rw [splitStep,run_applyIf] + change ((run O natEqZero k).bind fun t => if t then _ else _)=_ + rw [run_natEqZero] + by_cases hk : k=0 + · subst k; rfl + · simp only [hk,decide_false,Option.bind_some,Bool.false_eq_true,ite_false] + change ((run O natSub (k,1)).bind fun j => some (j,(x::u,v)))=_ + rw [run_natSub] + simp [splitStepValue,hk] +lemma fold_splitStep {n : ℕ} (O : IndependenceOracle n) {a : DataType} (xs : List (Value a)) + (k : ℕ) (u v : List (Value a)) : + foldValue (run O splitStep) xs (k,(u,v))= + some (k-xs.length,((xs.take k).reverse++u,(xs.drop k).reverse++v)) := by + induction xs generalizing k u v with + | nil => simp [foldValue] + | cons x xs ih => + rw [foldValue,run_splitStep] + cases k with + | zero => simpa [splitStepValue,List.append_assoc] using ih 0 u (x::v) + | succ k => simpa [splitStepValue,List.append_assoc] using ih k (x::u) v +lemma run_splitAtCode {n : ℕ} (O : IndependenceOracle n) {a : DataType} (xs : List (Value a)) (k : ℕ) : + run O splitAtCode (xs,k)=some (xs.take k,xs.drop k) := by + change ((foldValue (run O splitStep) xs (k,([],[]))).bind fun p => do + let x ← run O listReverse p.2.1 + let y ← run O listReverse p.2.2 + pure (x,y))=_ + rw [fold_splitStep] + simp only [List.append_nil,Option.bind_some] + rw [run_listReverse,run_listReverse] + simp +lemma run_takeCode {n : ℕ} (O : IndependenceOracle n) {a : DataType} (xs : List (Value a)) (k : ℕ) : + run O takeCode (xs,k)=some (xs.take k) := by + change ((run O splitAtCode (xs,k)).bind fun p => some p.1)=_ + rw [run_splitAtCode]; rfl +lemma run_dropCode {n : ℕ} (O : IndependenceOracle n) {a : DataType} (xs : List (Value a)) (k : ℕ) : + run O dropCode (xs,k)=some (xs.drop k) := by + change ((run O splitAtCode (xs,k)).bind fun p => some p.2)=_ + rw [run_splitAtCode]; rfl + +lemma run_compose {n : ℕ} (O : IndependenceOracle n) {a b c : DataType} + (p : Expression a b) (q : Expression b c) (x : Value a) : + run O (p >>> q) x=(run O p x).bind (run O q) := rfl +lemma run_both {n : ℕ} (O : IndependenceOracle n) {a b c : DataType} + (p : Expression a b) (q : Expression a c) (x : Value a) : + run O (both p q) x=(run O p x).bind (fun y => (run O q x).map (fun z => (y,z))) := by + simp only [run] + congr 1 + funext y + cases run O q x <;> rfl + +def headD {a} : Expression (.prod (.list a) a) a := onLeft listReverse >>> fold fst +def getDCode {a} : Expression (.prod (.prod (.list a) .nat) a) a := + both (fst >>> dropCode) snd >>> headD + +def boolOr : Expression (.prod .bool .bool) .bool := branch ident (constant true) +def natEqual : Expression NN .bool := both less (swap >>> less) >>> boolOr >>> boolNot + +def listAll : Expression (.list .bool) .bool := both ident (constant true) >>> fold boolAnd + +def filterStep {a b} (p : Expression (.prod a b) .bool) : + Expression (.prod a (.prod (.list a) b)) (.prod (.list a) b) := + both (applyIf (both fst (snd >>> snd) >>> p) (snd >>> fst) + (both fst (snd >>> fst) >>> cons)) (snd >>> snd) +def filterWith {a b} (p : Expression (.prod a b) .bool) : + Expression (.prod (.list a) b) (.list a) := + both fst (both (constant []) snd) >>> fold (filterStep p) >>> fst >>> listReverse + +def foldLast {A : Type*} : List A → A → A + | [],d => d + | x::xs,_ => foldLast xs x +lemma foldLast_append {A : Type*} (xs ys : List A) (d : A) : + foldLast (xs++ys) d=foldLast ys (foldLast xs d) := by + induction xs generalizing d with + | nil => rfl + | cons x xs ih => exact ih x +lemma foldLast_reverse {A : Type*} (xs : List A) (d : A) : + foldLast xs.reverse d=xs.headD d := by + cases xs with + | nil => rfl + | cons x xs => simp [List.reverse_cons,foldLast_append,foldLast] +lemma run_headD {n : ℕ} (O : IndependenceOracle n) {a} (xs : List (Value a)) (d : Value a) : + run O headD (xs,d)=some (xs.headD d) := by + have hf : ∀ (ys : List (Value a)) (z : Value a), + foldValue (run O (fst (b:=a))) ys z=some (foldLast ys z) := by + intro ys + induction ys with + | nil => intro z; rfl + | cons y ys ih => intro z; exact ih y + simp only [headD,onLeft,run,run_listReverse] + change foldValue (run O (fst (b:=a))) xs.reverse d=_ + rw [hf,foldLast_reverse] +lemma run_getDCode {n : ℕ} (O : IndependenceOracle n) {a} (xs : List (Value a)) (k : ℕ) (d : Value a) : + run O getDCode ((xs,k),d)=some (xs.getD k d) := by + simp [getDCode,run] + rw [run_dropCode O xs k] + change run O headD (xs.drop k,d)=_ + rw [run_headD] + congr 1 + induction k generalizing xs with + | zero => cases xs <;> rfl + | succ k ih => cases xs with + | nil => rfl + | cons x xs => exact ih xs +lemma run_boolOr {n : ℕ} (O : IndependenceOracle n) (x y : Bool) : + run O boolOr (x,y)=some (x||y) := by cases x <;> rfl +lemma run_natEqual {n : ℕ} (O : IndependenceOracle n) (x y : ℕ) : + run O natEqual (x,y)=some (decide (x=y)) := by + simp [natEqual,run,swap] + rw [run_boolOr] + simp only [Option.bind_some] + congr 1 + by_cases h : x=y + · subst y; simp + · have hn : x simp [h,hh] +lemma run_listAll {n : ℕ} (O : IndependenceOracle n) (xs : List Bool) : + run O listAll xs=some (xs.all id) := by + have hf : ∀ (ys : List Bool) (z : Bool), + foldValue (run O boolAnd) ys z=some (z && ys.all id) := by + intro ys + induction ys with + | nil => intro z; cases z <;> rfl + | cons y ys ih => + intro z + change ((run O boolAnd (y,z)).bind (foldValue (run O boolAnd) ys))=_ + rw [run_boolAnd,Option.bind_some,ih] + cases z <;> cases y <;> simp + change foldValue (run O boolAnd) xs true=_ + simpa using hf xs true +lemma run_filterStep {n : ℕ} (O : IndependenceOracle n) {a b} (p : Expression (.prod a b) .bool) + (f : Value a → Value b → Bool) (hp : ∀ x z,run O p (x,z)=some (f x z)) + (x : Value a) (ys : List (Value a)) (z : Value b) : + run O (filterStep p) (x,(ys,z))=some ((if f x z then x::ys else ys),z) := by + simp only [filterStep,run_both,run_applyIf] + change ((run O p (x,z)).bind fun t => if t then some (x::ys) else some ys).bind + (fun v => (some z).map (fun w => (v,w)))=_ + rw [hp] + cases f x z <;> rfl +lemma run_filterWith {n : ℕ} (O : IndependenceOracle n) {a b} (p : Expression (.prod a b) .bool) + (f : Value a → Value b → Bool) (hp : ∀ x z,run O p (x,z)=some (f x z)) + (xs : List (Value a)) (z : Value b) : + run O (filterWith p) (xs,z)=some (xs.filter (fun x => f x z)) := by + have hf : ∀ (ys acc : List (Value a)), + foldValue (run O (filterStep p)) ys (acc,z)=some ((ys.filter (fun x => f x z)).reverse++acc,z) := by + intro ys + induction ys with + | nil => intro acc; rfl + | cons y ys ih => + intro acc + rw [foldValue,run_filterStep O p f hp,Option.bind_some] + cases h : f y z <;> simp [h,ih,List.append_assoc] + change ((foldValue (run O (filterStep p)) xs ([],z)).bind fun yz => run O listReverse yz.1)=_ + rw [hf] + change run O listReverse ((xs.filter (fun x => f x z)).reverse++[])=_ + rw [List.append_nil,run_listReverse,List.reverse_reverse] + +def powStepCode : Expression (.prod .nat .nat) (.prod .nat .nat) := both fst mul +def powCode : Expression NN .nat := + both snd (both fst (constant 1)) >>> iterateNat powStepCode >>> snd +lemma run_powCode {n : ℕ} (O : IndependenceOracle n) (a k : ℕ) : + run O powCode (a,k)=some (a^k) := by + let f : ℕ×ℕ → ℕ×ℕ := fun z => (z.1,z.1*z.2) + have hi : ∀ j v,(f^[j]) (a,v)=(a,a^j*v) := by + intro j + induction j with + | zero => intro v; simp [f] + | succ j ih => intro v; rw [Function.iterate_succ_apply',ih]; simp [f,pow_succ]; ring + have hh := run_iterateNat O powStepCode f (fun _ => rfl) k (a,1) + simp [powCode,run,hh,hi] + +def ratPowCode : Expression (.prod NN .nat) NN := + both (both (fst >>> fst) snd >>> powCode) (both (fst >>> snd) snd >>> powCode) >>> normalizeRat +lemma run_ratPowCode {n : ℕ} (O : IndependenceOracle n) (q : ℚ) (hq : 0≤q) (k : ℕ) : + run O ratPowCode (rationalPair q,k)=some (rationalPair (q^k)) := by + simp [ratPowCode,run] + rw [run_powCode O _ _,run_powCode O _ _] + change run O normalizeRat ((rationalPair q).1^k,(rationalPair q).2^k)=_ + rw [run_normalizeRat_pair] + congr 2 + conv_rhs => rw [←rationalPair_value hq] + push_cast + rw [div_pow] +end Expression + +open Expression +lemma width_take {a : DataType} (xs : List (Value a)) (k : ℕ) : + width (a:=.list a) (xs.take k)≤width (a:=.list a) xs := by + have hh := width_list_append (xs.take k) (xs.drop k) + rw [List.take_append_drop] at hh + omega +lemma width_drop {a : DataType} (xs : List (Value a)) (k : ℕ) : + width (a:=.list a) (xs.drop k)≤width (a:=.list a) xs := by + have hh := width_list_append (xs.take k) (xs.drop k) + rw [List.take_append_drop] at hh + omega +lemma controlled_fromList : Controlled fromList := by + unfold fromList + apply controlled_compose + · exact controlled_both _ _ controlled_listReverse (controlled_atomic _ trivial) + · apply controlled_fold consBit (controlled_atomic _ trivial) (.mul (.constant 2) .input) + intro n O xs z pre post he y hy + have hh := foldValue_eq_foldl (run O consBit) (fun z x => x::z) (fun _ _ => rfl) pre z + rw [hh] at hy + cases hy + rw [List.foldl_flip_cons_eq_append',width_word,List.length_append,List.length_reverse] + have hp : pre.length≤xs.length := by rw [he,List.length_append]; omega + rw [width_pair (a:=.list .bool) (b:=.word),width_list_bool,width_word] + dsimp [SizePolynomial.eval] + omega +lemma controlled_splitStep {a : DataType} : Controlled (splitStep (a:=a)) := by unfold splitStep; control +lemma controlled_splitFold {a : DataType} : Controlled (.fold (splitStep (a:=a))) := by + apply controlled_fold splitStep controlled_splitStep (.mul (.constant 8) .input) + intro n O xs z pre post he y hy + rcases z with ⟨k,u,v⟩ + rw [fold_splitStep] at hy + cases hy + have hpre : width (a:=.list a) pre≤width (a:=.list a) xs := by rw [he,width_list_append]; omega + have ht := width_take (a:=a) pre k + have hd := width_drop (a:=a) pre k + have hk := bits_length_mono (Nat.sub_le k pre.length) + simp only [width_pair (a:=.nat) (b:=.prod (.list a) (.list a)), + width_pair (a:=.list a) (b:=.list a),width_nat,width_list_append,width_list_reverse, + width_pair (a:=.list a) (b:=SplitState a),SizePolynomial.eval] + omega +lemma controlled_splitAt {a : DataType} : Controlled (splitAtCode (a:=a)) := by + have hf := controlled_splitFold (a:=a) + have hr := controlled_listReverse (a:=a) + unfold splitAtCode + control +lemma controlled_take {a : DataType} : Controlled (takeCode (a:=a)) := + controlled_compose _ _ controlled_splitAt (controlled_atomic _ trivial) +lemma controlled_drop {a : DataType} : Controlled (dropCode (a:=a)) := + controlled_compose _ _ controlled_splitAt (controlled_atomic _ trivial) +lemma fold_fst_mem {A : Type*} (xs : List A) (z y : A) + (hy : foldValue (fun p : A×A => some p.1) xs z=some y) : y=z ∨ y∈xs := by + induction xs generalizing z with + | nil => cases hy; exact Or.inl rfl + | cons x xs ih => + change foldValue (fun p : A×A => some p.1) xs x=some y at hy + rcases ih x hy with h|h + · exact Or.inr (by simp [h]) + · exact Or.inr (by simp [h]) +lemma controlled_headD {a : DataType} : Controlled (headD (a:=a)) := by + unfold headD + apply controlled_compose + · exact controlled_onLeft _ controlled_listReverse + · apply controlled_fold (Expression.fst (a:=a) (b:=a)) (controlled_atomic _ trivial) (.mul (.constant 2) .input) + intro n O xs z pre post he y hy + have hh := fold_fst_mem pre z y hy + have hw : width y≤width z+width (a:=.list a) xs := by + rcases hh with hh|hh + · subst y; omega + · have hm : y∈xs := by rw [he]; exact List.mem_append_left post hh + have hb := width_list_member y xs hm + omega + rw [width_pair (a:=.list a) (b:=a)] + dsimp [SizePolynomial.eval] + omega +lemma controlled_getD {a : DataType} : Controlled (getDCode (a:=a)) := by + have hd := controlled_drop (a:=a) + have hh := controlled_headD (a:=a) + unfold getDCode + control +lemma controlled_boolOr : Controlled boolOr := by unfold boolOr; control +lemma controlled_natEqual : Controlled natEqual := by unfold natEqual; control +lemma controlled_listAll : Controlled listAll := by + unfold listAll + apply controlled_compose + · control + · apply controlled_fold boolAnd controlled_boolAnd (.add .input (.constant 1)) + intro n O xs z pre post he y hy + simp only [width_bool,SizePolynomial.eval] + omega + +open Expression +def wordDouble (w : Word) (b : Bool) : Word := if b then false::(w++w) else w++w +lemma wordDouble_length_le (w : Word) (b : Bool) : w.length≤(wordDouble w b).length := by + cases b <;> simp [wordDouble,List.length_append] ; omega +lemma wordDouble_fold_length_le (xs : List Bool) (z : Word) : z.length≤(xs.foldl wordDouble z).length := by + induction xs generalizing z with + | nil => rfl + | cons b xs ih => exact (wordDouble_length_le z b).trans (ih (wordDouble z b)) +lemma wordDouble_prefix_length_le (pre post : List Bool) (z : Word) : + (pre.foldl wordDouble z).length≤((pre++post).foldl wordDouble z).length := by + rw [List.foldl_append] + exact wordDouble_fold_length_le post _ +lemma fold_wordDouble {n : ℕ} (O : IndependenceOracle n) (xs : List Bool) (z : Word) : + foldValue (run O wordRepeatStep) xs z=some (xs.foldl wordDouble z) := by + apply foldValue_eq_foldl + intro b w + exact run_wordRepeatStep O b w +lemma controlled_wordRepeatStep : Controlled wordRepeatStep := by unfold wordRepeatStep; control +lemma polySafe_wordRepeatFold : PolySafe (.fold wordRepeatStep) + (fun S x => x.1.length≤S ∧ (x.1.foldl wordDouble x.2).length≤S) := by + apply polySafe_fold wordRepeatStep _ (fun S x => width x≤5*S+4) + (polySafe_of_controlled wordRepeatStep controlled_wordRepeatStep _ + (.add (.mul (.constant 5) .input) (.constant 4)) (by intros; assumption)) + (.add (.mul (.constant 10) .input) (.constant 4)) + · intro S x hx + obtain ⟨xs,z⟩ := x + dsimp only [Prod.fst,Prod.snd] at hx + have hh := wordDouble_fold_length_le xs z + rw [width_pair (a:=.list .bool) (b:=.word),width_list_bool,width_word] + dsimp [SizePolynomial.eval] + omega + · intro n O S xs z hx pre post he y hy + dsimp only [Prod.fst,Prod.snd] at hx + rw [fold_wordDouble] at hy + cases hy + have hh := wordDouble_prefix_length_le pre post z + rw [←he] at hh + rw [width_word] + dsimp [SizePolynomial.eval] + omega + · intro n O S xs z hx pre b post he y hy + dsimp only [Prod.fst,Prod.snd] at hx + rw [fold_wordDouble] at hy + cases hy + have hh := wordDouble_prefix_length_le pre (b::post) z + rw [←he] at hh + rw [width_pair (a:=.bool) (b:=.word),width_bool,width_word] + omega +lemma polySafe_unary : PolySafe unary (fun S x => x≤S) := by + unfold unary + apply polySafe_compose _ _ _ _ + (polySafe_of_controlled _ (by control) _ .input (by + intro S x hx + exact (bits_length_le_value x).trans hx)) polySafe_wordRepeatFold + intro n O S x hx y hy + cases hy + obtain ⟨w,hw,hlen⟩ := unary_value O x.bits [] + rw [fold_wordDouble] at hw + have hwe : (x.bits.reverse.foldl wordDouble [])=w := Option.some.inj hw + refine ⟨?_,?_⟩ + · simpa only [List.length_reverse] using (bits_length_le_value x).trans hx + · rw [hwe,hlen] + simpa only [List.length_nil,mul_zero,zero_add,binaryValue_bits] using hx + +abbrev StateData := DataType.prod .word .word + +def representedState (n : ℕ) (p : Word×Word) : Set (Fin n⊕Fin n) := + {i | Sum.elim (fun j => j∈wordSet n p.1) (fun j => j∈wordSet n p.2) i} +@[simp] lemma representedState_inl (n : ℕ) (p : Word×Word) (i : Fin n) : + Sum.inl i∈representedState n p ↔ p.1[i.val]?.getD false=true := Iff.rfl +@[simp] lemma representedState_inr (n : ℕ) (p : Word×Word) (i : Fin n) : + Sum.inr i∈representedState n p ↔ p.2[i.val]?.getD false=true := Iff.rfl +@[simp] lemma representedState_preinl (n : ℕ) (p : Word×Word) : + Sum.inl ⁻¹' representedState n p=wordSet n p.1 := rfl +@[simp] lemma representedState_preinr (n : ℕ) (p : Word×Word) : + Sum.inr ⁻¹' representedState n p=wordSet n p.2 := rfl +lemma wordSet_not {n : ℕ} (x : Word) (hx : x.length=n) : + wordSet n (x.map Bool.not)=(wordSet n x)ᶜ := by + ext i + simp only [wordSet,Set.mem_ofPred_eq,Set.mem_compl_iff] + have hi : i.val simp + +namespace Expression + +def wordGet : Expression (.prod .word .nat) .bool := + both (both (fst >>> toList) snd) (constant false) >>> getDCode +def wordNot : Expression .word .word := + toList >>> both ident (constant (b:=.unit) ()) >>> mapWith (c:=.unit) (fst >>> boolNot) >>> fromList +def wordCountStep : Expression (.prod .bool .nat) .nat := branch ident (both ident (constant 1) >>> add) +def wordCount : Expression .word .nat := toList >>> both ident (constant 0) >>> fold wordCountStep + +lemma run_wordGet {n : ℕ} (O : IndependenceOracle n) (x : Word) (j : ℕ) : + run O wordGet (x,j)=some (x[j]?.getD false) := by + change run O (getDCode (a:=.bool)) ((x,j),false)=_ + exact run_getDCode O (a:=.bool) x j false +lemma run_wordNot {n : ℕ} (O : IndependenceOracle n) (x : Word) : + run O wordNot x=some (x.map Bool.not) := by + change ((run O (mapWith (c:=.unit) (fst >>> boolNot)) (x,())).bind (run O fromList))=_ + rw [run_mapWith O _ (fun b (_ : Unit) => !b) (by intro b z; exact run_boolNot O b)] + change run O fromList (x.map Bool.not)=_ + exact run_fromList O _ +lemma run_wordCount {n : ℕ} (O : IndependenceOracle n) (x : Word) : + run O wordCount x=some (x.count true) := by + have hf : ∀ (xs : Word) k,foldValue (run O wordCountStep) xs k=some (k+xs.count true) := by + intro xs + induction xs with + | nil => intro k; simp [foldValue] + | cons b xs ih => + intro k + cases b with + | false => + change foldValue (run O wordCountStep) xs k=some (k+(false::xs).count true) + rw [ih]; simp + | true => + change foldValue (run O wordCountStep) xs (k+1)=some (k+(true::xs).count true) + rw [ih]; simp [Nat.add_comm,Nat.add_left_comm] + change foldValue (run O wordCountStep) x 0=_ + simpa using hf x 0 + +def deficiencyCode : Expression (.prod .nat StateData) .nat := + both (both (snd >>> fst >>> wordLength) fst >>> add) + (both (both (snd >>> fst >>> rank false) (snd >>> snd >>> wordCount) >>> add) + (snd >>> snd >>> wordNot >>> rank true) >>> add) >>> natSub +lemma run_deficiencyCode {n : ℕ} (O : IndependenceOracle n) (r : ℕ) (x y : Word) + (hx : x.length=n) (hy : y.length=n) : + run O deficiencyCode (r,(x,y))= + some (n+r-(rankWord O false x+y.count true+rankWord O true (y.map Bool.not))) := by + simp only [deficiencyCode,run_compose,run_both] + simp [run,run_wordLength,run_wordCount,run_wordNot,hx,hy] + rw [run_natSub] +end Expression + +open scoped Classical in +lemma deficiencyCode_source {n : ℕ} (M₁ M₂ : Matroid (Fin n)) (O : IndependenceOracle n) + (hO : ExactOracles M₁ M₂ O) (hE₁ : M₁.E=Set.univ) (hE₂ : M₂.E=Set.univ) + (r : ℕ) (x y : Word) (hx : x.length=n) (hy : y.length=n) : + run O Expression.deficiencyCode (r,(x,y))=some (oracleDeficiency n r O (representedState n (x,y))) := by + rw [Expression.run_deficiencyCode O r x y hx hy] + unfold oracleDeficiency pairedDeficiencyOracle + rw [representedState_preinl,representedState_preinr, + rankWord_eq_rankOracle M₁ M₂ O hO hE₁ hE₂ false x hx, + rankWord_eq_rankOracle M₁ M₂ O hO hE₁ hE₂ true (y.map Bool.not) (by simpa using hy), + wordSet_not y hy] + rw [Set.toFinset_compl] + have hc : (wordSet n y).toFinset.card=y.count true := by + simpa using wordSet_card y hy + simp only [hc] + +abbrev Optional (a : DataType) := DataType.prod .bool a +abbrev RandomRows := DataType.list .word + +def optionData {a : DataType} (d : Value a) : Option (Value a) → Value (Optional a) + | none => (false,d) + | some x => (true,x) +lemma foldValue_append {A B : Type*} (f : A×B → Option B) (xs ys : List A) (z : B) : + foldValue f (xs++ys) z=(foldValue f xs z).bind (foldValue f ys) := by + induction xs generalizing z with + | nil => rfl + | cons x xs ih => + simp only [List.cons_append,foldValue,ih,Option.bind_assoc] + +namespace Expression +@[simp] lemma run_ident {n : ℕ} (O : IndependenceOracle n) {a : DataType} (x : Value a) : + run O (ident (a:=a)) x=some x := rfl +@[simp] lemma run_fst {n : ℕ} (O : IndependenceOracle n) {a b : DataType} : + run O (fst (a:=a) (b:=b))=(fun x => some x.1) := rfl +@[simp] lemma run_snd {n : ℕ} (O : IndependenceOracle n) {a b : DataType} : + run O (snd (a:=a) (b:=b))=(fun x => some x.2) := rfl +@[simp] lemma run_constant {n : ℕ} (O : IndependenceOracle n) {a b : DataType} (x : Value a) (y : Value b) : + run O (constant (a:=a) (b:=b) y) x=some y := rfl +@[simp] lemma run_reverse {n : ℕ} (O : IndependenceOracle n) (x : Word) : + run O reverse x=some x.reverse := rfl +@[simp] lemma run_toNat {n : ℕ} (O : IndependenceOracle n) (x : Word) : + run O toNat x=some (binaryValue x) := rfl +@[simp] lemma run_less {n : ℕ} (O : IndependenceOracle n) (x y : ℕ) : + run O less (x,y)=some (decide (x>> takeCode >>> fromList +def wordDrop : Expression (.prod .word .nat) .word := onLeft toList >>> dropCode >>> fromList +lemma run_wordTake {n : ℕ} (O : IndependenceOracle n) (x : Word) (k : ℕ) : + run O wordTake (x,k)=some (x.take k) := by + change ((run O (takeCode (a:=.bool)) (x,k)).bind (run O fromList))=_ + rw [run_takeCode]; exact run_fromList O _ +lemma run_wordDrop {n : ℕ} (O : IndependenceOracle n) (x : Word) (k : ℕ) : + run O wordDrop (x,k)=some (x.drop k) := by + change ((run O (dropCode (a:=.bool)) (x,k)).bind (run O fromList))=_ + rw [run_dropCode]; exact run_fromList O _ + +abbrev RejectState := DataType.prod NN (Optional .nat) +def rejectStep : Expression (.prod .word RejectState) RejectState := + both (snd >>> fst) + (letIn (both fst (snd >>> fst >>> snd) >>> wordTake >>> reverse >>> toNat) + (applyIf (both snd (fst >>> snd >>> fst >>> fst) >>> less) + (fst >>> snd >>> snd) (both (constant true) snd))) +def rejectCode : Expression (.prod RandomRows NN) (Optional .nat) := + both (fst >>> listReverse) (both snd (constant (false,0))) >>> fold rejectStep >>> snd + +def rejectValue (v k : ℕ) : List Word → Option ℕ + | [] => none + | x::xs => let z := binaryValue (x.take k).reverse + if z simp [run,h] +lemma fold_reject {n : ℕ} (O : IndependenceOracle n) (v k : ℕ) (xs : List Word) (z : Bool×ℕ) : + foldValue (run O rejectStep) xs.reverse ((v,k),z)= + some ((v,k),match rejectValue v k xs with | none => z | some y => (true,y)) := by + induction xs with + | nil => rfl + | cons x xs ih => + rw [List.reverse_cons,foldValue_append,ih] + simp only [Option.bind_some,foldValue] + rw [run_rejectStep] + simp only [Option.bind_some] + change _=some ((v,k),match rejectValue v k (x::xs) with | none => z | some y => (true,y)) + simp only [rejectValue] + split_ifs <;> rfl +lemma run_rejectCode {n : ℕ} (O : IndependenceOracle n) (xs : List Word) (v k : ℕ) : + run O rejectCode (xs,(v,k))=some (optionData 0 (rejectValue v k xs)) := by + simp only [rejectCode,run_compose,run_both,run_fst,run_snd,run_constant,Option.bind_some, + run_listReverse,Option.map_some] + change ((foldValue (run O rejectStep) xs.reverse ((v,k),(false,0))).bind fun z => some z.2)=_ + rw [fold_reject] + cases rejectValue v k xs <;> rfl +end Expression + +lemma binaryValue_ofFn_reverse (h : ℕ) (bits : BitWord h) : + binaryValue (List.ofFn bits).reverse=(wordEquiv h bits).val := by + induction h with + | zero => simp [wordEquiv,binaryValue] + | succ h ih => + rw [List.ofFn_succ,List.reverse_cons,binaryValue_append] + simp only [List.length_reverse,List.length_ofFn,ih,binaryValue] + simp [wordEquiv,Equiv.trans_apply,Fin.consEquiv,finProdFinEquiv,finTwoEquiv] + cases bits 0 <;> simp <;> rfl + +lemma ofFn_bitPrefix (h H : ℕ) (hh : h≤H) (bits : BitWord H) : + List.ofFn (bitPrefix h H hh bits)=(List.ofFn bits).take h := by + apply List.ext_getElem + · simp; omega + · intro i hi hj + simp [bitPrefix] + +lemma rejectValue_ofFn (v h D : ℕ) (bits : Fin D → BitWord h) : + Expression.rejectValue v h (List.ofFn (fun i => List.ofFn (bits i)))= + (boundedUniform v h D bits).map Fin.val := by + induction D with + | zero => rfl + | succ D ih => + rw [List.ofFn_succ] + simp only [Expression.rejectValue] + rw [List.take_of_length_le (by simp),binaryValue_ofFn_reverse] + simp only [boundedUniform] + split_ifs <;> first | rfl | exact ih (Fin.tail bits) + +lemma rejectValue_prefix (v h H D : ℕ) (hh : h≤H) (bits : Fin D → BitWord H) : + Expression.rejectValue v h (List.ofFn (fun i => List.ofFn (bits i)))= + (boundedUniform v h D (fun i => bitPrefix h H hh (bits i))).map Fin.val := by + induction D with + | zero => rfl + | succ D ih => + rw [List.ofFn_succ] + simp only [Expression.rejectValue,←ofFn_bitPrefix h H hh,binaryValue_ofFn_reverse,boundedUniform] + split_ifs <;> first | rfl | exact ih (Fin.tail bits) + +abbrev BankData := DataType.list RandomRows +abbrev Bank := List (List Word) +lemma rejectValue_lt (v h : ℕ) (xs : List Word) {i : ℕ} + (hi : Expression.rejectValue v h xs=some i) : i cases hi + | cons x xs ih => + simp only [Expression.rejectValue] at hi + split_ifs at hi with hx + · cases hi; exact hx + · exact ih hi + +def bankEval {A : Type*} : DrawTree A → Bank → Option A × Bank + | .leaf a,bank => (some a,bank) + | .draw _ _,[] => (none,[]) + | .draw v k,rows::bank => + match hi : Expression.rejectValue (v+1) (Nat.clog 2 (v+1)) rows with + | none => (none,bank) + | some i => bankEval (k ⟨i,rejectValue_lt _ _ _ hi⟩) bank + +lemma bankEval_bind {A B : Type*} (t : DrawTree A) (f : A → DrawTree B) (bank : Bank) : + bankEval (t.bind f) bank= + match bankEval t bank with + | (none,rest) => (none,rest) + | (some a,rest) => bankEval (f a) rest := by + induction t generalizing bank with + | leaf a => rfl + | draw v k ih => + cases bank with + | nil => rfl + | cons rows bank => + simp only [DrawTree.bind,bankEval] + split <;> first | rfl | exact ih _ bank +lemma bankEval_map {A B : Type*} (t : DrawTree A) (f : A → B) (bank : Bank) : + bankEval (t.map f) bank=((bankEval t bank).1.map f,(bankEval t bank).2) := by + rw [DrawTree.map,bankEval_bind] + cases bankEval t bank with + | mk o rest => cases o <;> rfl + +def bankEncode {H D M : ℕ} (bits : Fin M → Fin D → BitWord H) : Bank := + List.ofFn (fun m => List.ofFn (fun d => List.ofFn (bits m d))) +lemma bankEncode_succ {H D M : ℕ} (bits : Fin (M+1) → Fin D → BitWord H) : + bankEncode bits=List.ofFn (fun d => List.ofFn (bits 0 d))::bankEncode (Fin.tail bits) := by + exact List.ofFn_succ +lemma bankEval_run {A : Type*} (H D M : ℕ) (t : DrawTree A) (ht : DrawTree.Fits H M t) + (bits : Fin M → Fin D → BitWord H) : + (bankEval t (bankEncode bits)).1=DrawTree.run H D M t bits := by + induction t generalizing M with + | leaf a => cases M <;> rfl + | draw v k ih => + cases M with + | zero => exact False.elim ht + | succ M => + rw [bankEncode_succ] + simp only [bankEval,DrawTree.run,dite_eq_left ht.1] + have he := rejectValue_prefix (v+1) (Nat.clog 2 (v+1)) H D ht.1 (bits 0) + cases hu : boundedUniform (v+1) (Nat.clog 2 (v+1)) D + (fun i => bitPrefix _ H ht.1 (bits 0 i)) with + | none => + simp only [hu,Option.map_none] at he + split + · rfl + · rename_i i hi + have hh := he.symm.trans hi + cases hh + | some i => + simp only [hu,Option.map_some] at he + split + · rename_i hi + have hh := he.symm.trans hi + cases hh + · rename_i j hj + have hh := Option.some.inj (he.symm.trans hj) + subst j + exact ih i M (ht.2 i) (Fin.tail bits) + +open Expression + +def zeroValue : (a : DataType) → Value a + | .unit => () + | .bool => false + | .nat => 0 + | .word => [] + | .prod a b => (zeroValue a,zeroValue b) + | .list _ => [] +def optionalValue (a : DataType) : Option (Value a) → Value (Optional a) := optionData (zeroValue a) +def decodeOptional {a : DataType} (x : Value (Optional a)) : Option (Value a) := if x.1 then some x.2 else none +@[simp] lemma decode_optionalValue (a : DataType) (x : Option (Value a)) : + decodeOptional (optionalValue a x)=x := by cases x <;> rfl + +abbrev Effect (a b : DataType) := Expression (.prod a BankData) (.prod (Optional b) BankData) +namespace Expression +lemma clog_two_size_pred (v : ℕ) : Nat.clog 2 v=(v-1).size := by + apply Nat.le_antisymm + · apply (Nat.clog_le_iff_le_pow (by norm_num)).mpr + have h := Nat.lt_size_self (v-1) + omega + · apply Nat.size_le.mpr + have h := Nat.le_pow_clog (by norm_num : 1<2) v + have hp : 0<2^(Nat.clog 2 v) := by positivity + omega + +def clogCode : Expression .nat .nat := both ident (constant 1) >>> natSub >>> toBits >>> wordLength +lemma run_clogCode {n : ℕ} (O : IndependenceOracle n) (v : ℕ) : + run O clogCode v=some (Nat.clog 2 v) := by + simp only [clogCode,run_compose,run_both,run_ident,run_constant,Option.bind_some,Option.map_some] + rw [run_natSub] + change run O wordLength (v-1).bits=_ + rw [run_wordLength,Nat.size_eq_bits_len,clog_two_size_pred] + +end Expression +open Expression +namespace Effect + +def pure {a b} (p : Expression a b) : Effect a b := both (both (constant true) (fst >>> p)) snd +def fail {a b} : Effect a b := both (constant (optionalValue b none)) snd + +def bind {a b c} (p : Effect a b) (q : Effect b c) : Effect a c := + p >>> applyIf (fst >>> fst) + (both (constant (optionalValue c none)) snd) + (both (fst >>> snd) snd >>> q) + +def keep {a b} (p : Effect a b) : Effect a (.prod a b) := + letIn p (both + (applyIf (snd >>> fst >>> fst) (constant (optionalValue (.prod a b) none)) + (both (constant true) (both (fst >>> fst) (snd >>> fst >>> snd)))) + (snd >>> snd)) + +def letIn {a b c} (p : Effect a b) (q : Effect (.prod a b) c) : Effect a c := + bind (keep p) q + +def draw : Effect .nat .nat := + both + (both (snd >>> both ident (constant []) >>> headD) (both fst (fst >>> clogCode)) >>> rejectCode) + (snd >>> both ident (constant 1) >>> dropCode) + +lemma run_pure {n : ℕ} (O : IndependenceOracle n) {a b} (p : Expression a b) + (x : Value a) (y : Value b) (bank : Bank) (hp : run O p x=some y) : + run O (pure p) (x,bank)=some (optionalValue b (some y),bank) := by + simp only [pure,run_both,run_compose,run_fst,run_snd,run_constant, + Option.bind_some,hp,Option.map_some] + rfl +lemma run_fail {n : ℕ} (O : IndependenceOracle n) {a b} (x : Value a) (bank : Bank) : + run O (fail (a:=a) (b:=b)) (x,bank)=some (optionalValue b none,bank) := rfl +lemma run_bind {n : ℕ} (O : IndependenceOracle n) {a b c} (p : Effect a b) (q : Effect b c) + (x : Value a) (bank rest : Bank) (y : Option (Value b)) + (hp : run O p (x,bank)=some (optionalValue b y,rest)) : + run O (bind p q) (x,bank)= + match y with + | none => some (optionalValue c none,rest) + | some z => run O q (z,rest) := by + cases y <;> dsimp only <;> rw [bind,run_compose,hp,Option.bind_some,run_applyIf] <;> rfl +lemma run_keep {n : ℕ} (O : IndependenceOracle n) {a b} (p : Effect a b) + (x : Value a) (bank rest : Bank) (y : Value b) + (hp : run O p (x,bank)=some (optionalValue b (some y),rest)) : + run O (keep p) (x,bank)=some (optionalValue (.prod a b) (some (x,y)),rest) := by + rw [keep,run_letIn,hp] + rfl +lemma run_draw {n : ℕ} (O : IndependenceOracle n) (v : ℕ) (bank : Bank) : + run O draw (v,bank)=some (optionData 0 + (Expression.rejectValue v (Nat.clog 2 v) (bank.headD [])),bank.drop 1) := by + simp only [draw,run_both,run_compose,run_fst,run_snd,run_ident,run_constant,Option.bind_some,Option.map_some] + rw [run_headD,run_clogCode,run_dropCode] + simp only [Option.bind_some,Option.map_some] + rw [run_rejectCode] + rfl + +def Realizes {n : ℕ} (O : IndependenceOracle n) {A : Type*} {a b : DataType} + (p : Effect a b) (encode : A → Value b) (x : Value a) (t : DrawTree A) : Prop := + ∀ bank, run O p (x,bank)=some + (optionalValue b ((bankEval t bank).1.map encode),(bankEval t bank).2) + +lemma realizes_pure {n : ℕ} (O : IndependenceOracle n) {A : Type*} {a b : DataType} + (p : Expression a b) (encode : A → Value b) (x : Value a) (y : A) + (hp : run O p x=some (encode y)) : Realizes O (pure p) encode x (.leaf y) := by + intro bank + exact run_pure O p x (encode y) bank hp + +lemma realizes_bind {n : ℕ} (O : IndependenceOracle n) {A B : Type*} {a b c : DataType} + (p : Effect a b) (q : Effect b c) (ea : A → Value b) (eb : B → Value c) + (x : Value a) (t : DrawTree A) (f : A → DrawTree B) + (hp : Realizes O p ea x t) (hq : ∀ y,Realizes O q eb (ea y) (f y)) : + Realizes O (bind p q) eb x (t.bind f) := by + intro bank + rw [bankEval_bind] + cases ht : bankEval t bank with + | mk out rest => + have hh := hp bank + rw [ht] at hh + cases out with + | none => exact run_bind O p q x bank rest none hh + | some y => + rw [run_bind O p q x bank rest (some (ea y)) hh] + exact hq y rest + +lemma realizes_keep {n : ℕ} (O : IndependenceOracle n) {A : Type*} {a b : DataType} + (p : Effect a b) (ea : A → Value b) (x : Value a) (t : DrawTree A) + (hp : Realizes O p ea x t) : + Realizes O (keep p) (fun y => (x,ea y)) x t := by + intro bank + have hh := hp bank + cases ht : bankEval t bank with + | mk out rest => + rw [ht] at hh + cases out with + | none => rw [keep,run_letIn,hh]; rfl + | some y => exact run_keep O p x bank rest (ea y) hh + +lemma realizes_letIn {n : ℕ} (O : IndependenceOracle n) {A B : Type*} {a b c : DataType} + (p : Effect a b) (q : Effect (.prod a b) c) (ea : A → Value b) (eb : B → Value c) + (x : Value a) (t : DrawTree A) (f : A → DrawTree B) + (hp : Realizes O p ea x t) (hq : ∀ y,Realizes O q eb (x,ea y) (f y)) : + Realizes O (letIn p q) eb x (t.bind f) := + realizes_bind O (keep p) q _ eb x t f (realizes_keep O p ea x t hp) hq + +lemma realizes_draw {n : ℕ} (O : IndependenceOracle n) (v : ℕ) : + Realizes O draw Fin.val (v+1) (.draw v DrawTree.leaf) := by + intro bank + rw [run_draw] + cases bank with + | nil => rfl + | cons rows bank => + simp only [bankEval] + split + · rename_i hi + simp only [List.headD_cons,List.drop_succ_cons,List.drop_zero,hi,Option.map_none] + rfl + · rename_i i hi + simp only [List.headD_cons,List.drop_succ_cons,List.drop_zero,hi,Option.map_some] + rfl + +def map {a b c} (p : Effect a b) (q : Expression b c) : Effect a c := bind p (pure q) +def precompose {a b c} (p : Expression a b) (q : Effect b c) : Effect a c := onLeft p >>> q + +def choose {a b} (test : Expression a .bool) (p q : Effect a b) : Effect a b := + applyIf (fst >>> test) p q + +lemma run_precompose {n : ℕ} (O : IndependenceOracle n) {a b c} (p : Expression a b) + (q : Effect b c) (x : Value a) (y : Value b) (bank : Bank) + (hp : run O p x=some y) : run O (precompose p q) (x,bank)=run O q (y,bank) := by + simp only [precompose,onLeft,run_compose,run_both,run_fst,run_snd,Option.bind_some,hp,Option.map_some] + +lemma realizes_precompose {n : ℕ} (O : IndependenceOracle n) {A : Type*} {a b c} + (p : Expression a b) (q : Effect b c) (ea : A → Value c) (x : Value a) (y : Value b) + (t : DrawTree A) (hp : run O p x=some y) (hq : Realizes O q ea y t) : + Realizes O (precompose p q) ea x t := by + intro bank + rw [run_precompose O p q x y bank hp] + exact hq bank + +lemma run_choose {n : ℕ} (O : IndependenceOracle n) {a b} (test : Expression a .bool) + (p q : Effect a b) (x : Value a) (bank : Bank) (v : Bool) + (ht : run O test x=some v) : + run O (choose test p q) (x,bank)=if v then run O q (x,bank) else run O p (x,bank) := by + rw [choose,run_applyIf] + change ((run O test x).bind fun v => if v then _ else _)=_ + rw [ht,Option.bind_some] + +lemma realizes_map {n : ℕ} (O : IndependenceOracle n) {A B : Type*} {a b c} + (p : Effect a b) (q : Expression b c) (ea : A → Value b) (eb : B → Value c) + (x : Value a) (t : DrawTree A) (f : A → B) + (hp : Realizes O p ea x t) (hq : ∀ y,run O q (ea y)=some (eb (f y))) : + Realizes O (map p q) eb x (t.map f) := + realizes_bind O p (pure q) ea eb x t (fun y => .leaf (f y)) hp + (fun y => realizes_pure O q eb (ea y) (f y) (hq y)) +end Effect + +def iterateM {A : Type*} (f : A → Option A) : ℕ → A → Option A + | 0,x => some x + | k+1,x => (f x).bind (iterateM f k) +lemma iterateM_some {A : Type*} (f : A → Option A) (x : A) (h : f x=some x) (k : ℕ) : + iterateM f k x=some x := by + induction k with + | zero => rfl + | succ k ih => rw [iterateM,h,Option.bind_some,ih] +namespace Expression +lemma run_iterateNatM {n : ℕ} (O : IndependenceOracle n) {a : DataType} + (p : Expression a a) (k : ℕ) (x : Value a) : + run O (iterateNat p) (k,x)=iterateM (run O p) k x := by + have hf : ∀ (w : Word) (z : Value a), + foldValue (run O (snd (a:=.bool) >>> p)) w z=iterateM (run O p) w.length z := by + intro w + induction w with + | nil => intro z; rfl + | cons b w ih => + intro z + change ((run O p z).bind (foldValue (run O (snd (a:=.bool) >>> p)) w))=_ + simp only [List.length_cons,iterateM] + congr 1 + funext v + exact ih v + obtain ⟨w,hw,hlen⟩ := run_unary O k + simp only [iterateNat,onLeft,run_compose,run_both,run_fst,run_snd,Option.bind_some,Option.map_some] + rw [hw] + change foldValue (run O (snd (a:=.bool) >>> p)) w x=_ + rw [hf,hlen] +end Expression +namespace Effect + +def loopStep {a} (p : Effect a a) : Expression (.prod (Optional a) BankData) (.prod (Optional a) BankData) := + applyIf (fst >>> fst) ident (both (fst >>> snd) snd >>> p) +def repeatCode {a} (p : Effect a a) : Effect (.prod .nat a) a := + both (fst >>> fst) (both (both (constant (b:=.bool) true) (fst >>> snd)) snd) >>> iterateNat (loopStep p) +lemma run_loopStep_none {n : ℕ} (O : IndependenceOracle n) {a} (p : Effect a a) (bank : Bank) : + run O (loopStep p) (optionalValue a none,bank)=some (optionalValue a none,bank) := rfl +lemma run_loopStep_some {n : ℕ} (O : IndependenceOracle n) {a} (p : Effect a a) + (x : Value a) (bank : Bank) : + run O (loopStep p) (optionalValue a (some x),bank)=run O p (x,bank) := rfl +lemma run_repeat {n : ℕ} (O : IndependenceOracle n) {a} (p : Effect a a) + (k : ℕ) (x : Value a) (bank : Bank) : + run O (repeatCode p) ((k,x),bank)=iterateM (run O (loopStep p)) k (optionalValue a (some x),bank) := by + change run O (iterateNat (loopStep p)) (k,(optionalValue a (some x),bank))=_ + exact run_iterateNatM O _ _ _ + +def treeRepeat {A : Type*} (f : A → DrawTree A) : ℕ → A → DrawTree A + | 0,x => .leaf x + | k+1,x => (f x).bind (treeRepeat f k) +lemma realizes_repeat {n : ℕ} (O : IndependenceOracle n) {A : Type*} {a} + (p : Effect a a) (ea : A → Value a) (f : A → DrawTree A) + (hp : ∀ x,Realizes O p ea (ea x) (f x)) (k : ℕ) (x : A) : + Realizes O (repeatCode p) ea (k,ea x) (treeRepeat f k x) := by + intro bank + rw [run_repeat] + induction k generalizing x bank with + | zero => rfl + | succ k ih => + rw [iterateM,run_loopStep_some,hp x bank,Option.bind_some,treeRepeat,bankEval_bind] + cases ht : bankEval (f x) bank with + | mk out rest => + cases out with + | none => + simpa only [Option.map_none] using iterateM_some (run O (loopStep p)) + (optionalValue a none,rest) (run_loopStep_none O p rest) k + | some y => exact ih y rest + +end Effect +end MachineCode + +namespace DrawTree +variable {A B : Type*} +lemma Reindexed.trans {t u v : DrawTree A} (h : Reindexed t u) (g : Reindexed u v) : + Reindexed t v := by + induction h generalizing v with + | leaf a => cases g; exact .leaf a + | draw m k l e h ih => + cases g with + | draw _ _ z f gz => + exact .draw m k z (e.trans f) (fun i => ih i (gz (e i))) +lemma uniformVia_reindexed_via (A : Type*) [Fintype A] [Nonempty A] + (e f : Fin (Fintype.card A) ≃ A) : Reindexed (uniformVia A e) (uniformVia A f) := + (uniformVia_reindexed A e).trans (uniformVia_reindexed A f).symm +end DrawTree +namespace MachineCode +open Expression +namespace Effect + +def RealizesLaw {n : ℕ} (O : IndependenceOracle n) {A : Type*} {a b : DataType} + (p : Effect a b) (encode : A → Value b) (x : Value a) (t : DrawTree A) : Prop := + ∃ u, DrawTree.Reindexed t u ∧ Realizes O p encode x u +lemma Realizes.law {n : ℕ} {O : IndependenceOracle n} {A : Type*} {a b} {p : Effect a b} + {e : A → Value b} {x : Value a} {t : DrawTree A} (h : Realizes O p e x t) : + RealizesLaw O p e x t := ⟨t,.refl t,h⟩ +lemma RealizesLaw.reindex {n : ℕ} {O : IndependenceOracle n} {A : Type*} {a b} + {p : Effect a b} {e : A → Value b} {x : Value a} {t u : DrawTree A} + (h : RealizesLaw O p e x u) (ht : DrawTree.Reindexed t u) : RealizesLaw O p e x t := by + rcases h with ⟨v,hv,hp⟩ + exact ⟨v,ht.trans hv,hp⟩ +lemma law_bind {n : ℕ} (O : IndependenceOracle n) {A B : Type*} {a b c} + (p : Effect a b) (q : Effect b c) (ea : A → Value b) (eb : B → Value c) + (x : Value a) (t : DrawTree A) (f : A → DrawTree B) + (hp : RealizesLaw O p ea x t) (hq : ∀ y,RealizesLaw O q eb (ea y) (f y)) : + RealizesLaw O (bind p q) eb x (t.bind f) := by + classical + rcases hp with ⟨u,hu,hp⟩ + choose g hg hq using hq + exact ⟨u.bind g,hu.bind hg,realizes_bind O p q ea eb x u g hp hq⟩ +lemma law_letIn {n : ℕ} (O : IndependenceOracle n) {A B : Type*} {a b c} + (p : Effect a b) (q : Effect (.prod a b) c) (ea : A → Value b) (eb : B → Value c) + (x : Value a) (t : DrawTree A) (f : A → DrawTree B) + (hp : RealizesLaw O p ea x t) (hq : ∀ y,RealizesLaw O q eb (x,ea y) (f y)) : + RealizesLaw O (letIn p q) eb x (t.bind f) := by + classical + rcases hp with ⟨u,hu,hp⟩ + choose g hg hq using hq + exact ⟨u.bind g,hu.bind hg,realizes_letIn O p q ea eb x u g hp hq⟩ +lemma law_precompose {n : ℕ} (O : IndependenceOracle n) {A : Type*} {a b c} + (p : Expression a b) (q : Effect b c) (ea : A → Value c) (x : Value a) (y : Value b) + (t : DrawTree A) (hp : run O p x=some y) (hq : RealizesLaw O q ea y t) : + RealizesLaw O (precompose p q) ea x t := by + rcases hq with ⟨u,hu,hq⟩ + exact ⟨u,hu,realizes_precompose O p q ea x y u hp hq⟩ +lemma law_map {n : ℕ} (O : IndependenceOracle n) {A B : Type*} {a b c} + (p : Effect a b) (q : Expression b c) (ea : A → Value b) (eb : B → Value c) + (x : Value a) (t : DrawTree A) (f : A → B) + (hp : RealizesLaw O p ea x t) (hq : ∀ y,run O q (ea y)=some (eb (f y))) : + RealizesLaw O (map p q) eb x (t.map f) := by + rcases hp with ⟨u,hu,hp⟩ + exact ⟨u.map f,hu.map f,realizes_map O p q ea eb x u f hp hq⟩ +lemma law_choose {n : ℕ} (O : IndependenceOracle n) {A : Type*} {a b} + (test : Expression a .bool) (p q : Effect a b) (ea : A → Value b) + (x : Value a) (t : DrawTree A) (v : Bool) (ht : run O test x=some v) + (h : RealizesLaw O (if v then q else p) ea x t) : + RealizesLaw O (choose test p q) ea x t := by + rcases h with ⟨u,hu,hp⟩ + refine ⟨u,hu,fun bank => ?_⟩ + rw [run_choose O test p q x bank v ht] + cases v <;> exact hp bank +end Effect +end MachineCode + +namespace DrawTree +variable {A B C : Type*} +lemma bind_leaf (t : DrawTree A) : t.bind leaf=t := by + induction t with + | leaf a => rfl + | draw v f ih => simp only [bind,ih] +lemma map_bind (t : DrawTree A) (f : A → B) (g : B → DrawTree C) : + (t.map f).bind g=t.bind (fun a => g (f a)) := by + rw [DrawTree.map,bind_assoc] + rfl +lemma bind_map (t : DrawTree A) (f : A → DrawTree B) (g : B → C) : + (t.bind f).map g=t.bind (fun a => (f a).map g) := bind_assoc t f _ +lemma map_map (t : DrawTree A) (f : A → B) (g : B → C) : + (t.map f).map g=t.map (g ∘ f) := map_bind t f _ +end DrawTree +namespace MachineCode + +open Expression + +def optionEncode {A : Type*} {a} (e : A → Value a) (x : Option A) : Value (Optional a) := + optionalValue a (x.map e) +@[simp] lemma optionEncode_none {A : Type*} {a} (e : A → Value a) : + optionEncode e none=(false,zeroValue a) := rfl +@[simp] lemma optionEncode_some {A : Type*} {a} (e : A → Value a) (x : A) : + optionEncode e (some x)=(true,e x) := rfl +namespace Effect + +def someCode {a b} (p : Effect a b) : Effect a (Optional b) := + map p (both (constant true) ident) +def noneCode {a b} : Effect a (Optional b) := pure (constant (optionalValue b none)) +def optionContinue {a b} (q : Effect a (Optional b)) : Effect (Optional a) (Optional b) := + choose fst noneCode (precompose snd q) +def optionBind {a b c} (p : Effect a (Optional b)) (q : Effect b (Optional c)) : Effect a (Optional c) := + bind p (optionContinue q) + +lemma law_some {n : ℕ} (O : IndependenceOracle n) {A : Type*} {a b} (p : Effect a b) + (ea : A → Value b) (x : Value a) (t : DrawTree A) (h : RealizesLaw O p ea x t) : + RealizesLaw O (someCode p) (optionEncode ea) x (t.map some) := + law_map O p _ ea (optionEncode ea) x t some h (fun _ => rfl) +lemma law_none {n : ℕ} (O : IndependenceOracle n) {A : Type*} {a b} (ea : A → Value b) (x : Value a) : + RealizesLaw O (noneCode (a:=a) (b:=b)) (optionEncode ea) x (.leaf none) := + (realizes_pure O _ _ _ none rfl).law +lemma law_optionContinue {n : ℕ} (O : IndependenceOracle n) {A B : Type*} {a b} + (q : Effect a (Optional b)) (ea : A → Value a) (eb : B → Value b) + (f : A → DrawTree (Option B)) (x : Option A) + (hq : ∀ y,RealizesLaw O q (optionEncode eb) (ea y) (f y)) : + RealizesLaw O (optionContinue q) (optionEncode eb) (optionEncode ea x) + (match x with | none => .leaf none | some y => f y) := by + unfold optionContinue + cases x with + | none => exact law_choose O _ _ _ _ _ _ false rfl (law_none O eb _) + | some y => + exact law_choose O _ _ _ _ _ _ true rfl + (law_precompose O snd q _ _ _ _ rfl (hq y)) +lemma law_optionBind {n : ℕ} (O : IndependenceOracle n) {A B : Type*} {a b c} + (p : Effect a (Optional b)) (q : Effect b (Optional c)) + (ea : A → Value b) (eb : B → Value c) (x : Value a) + (t : DrawTree (Option A)) (f : A → DrawTree (Option B)) + (hp : RealizesLaw O p (optionEncode ea) x t) + (hq : ∀ y,RealizesLaw O q (optionEncode eb) (ea y) (f y)) : + RealizesLaw O (optionBind p q) (optionEncode eb) x (t.optionBind f) := + law_bind O p (optionContinue q) (optionEncode ea) (optionEncode eb) x t _ hp + (fun y => law_optionContinue O q ea eb f y hq) + +lemma law_repeat {n : ℕ} (O : IndependenceOracle n) {A : Type*} {a} + (p : Effect a a) (ea : A → Value a) (f : A → DrawTree A) + (hp : ∀ x,RealizesLaw O p ea (ea x) (f x)) (k : ℕ) (x : A) : + RealizesLaw O (repeatCode p) ea (k,ea x) (treeRepeat f k x) := by + classical + choose g hg hp using hp + have hh : ∀ k x, DrawTree.Reindexed (treeRepeat f k x) (treeRepeat g k x) := by + intro k + induction k with + | zero => intro x; exact .leaf x + | succ k ih => intro x; exact (hg x).bind ih + exact ⟨treeRepeat g k x,hh k x,realizes_repeat O p ea g hp k x⟩ +lemma treeRepeat_succ_last {A : Type*} (f : A → DrawTree A) (k : ℕ) (x : A) : + treeRepeat f (k+1) x=(treeRepeat f k x).bind f := by + induction k generalizing x with + | zero => exact DrawTree.bind_leaf (f x) + | succ k ih => + change (f x).bind (treeRepeat f (k+1))=((f x).bind (treeRepeat f k)).bind f + rw [DrawTree.bind_assoc] + congr 1 + funext y + exact ih y +lemma treeRepeat_option {A : Type*} (f : A → DrawTree (Option A)) (k : ℕ) (x : A) : + treeRepeat (fun u => match u with | none => .leaf none | some a => f a) k (some x)= + DrawTree.iterate f k x := by + induction k with + | zero => rfl + | succ k ih => rw [treeRepeat_succ_last,ih]; rfl + +def iterateCode {a} (p : Effect a (Optional a)) : Effect (.prod .nat a) (Optional a) := + precompose (both fst (both (constant true) snd)) (repeatCode (optionContinue p)) +lemma law_iterate {n : ℕ} (O : IndependenceOracle n) {A : Type*} {a} + (p : Effect a (Optional a)) (ea : A → Value a) (f : A → DrawTree (Option A)) + (hp : ∀ x,RealizesLaw O p (optionEncode ea) (ea x) (f x)) (k : ℕ) (x : A) : + RealizesLaw O (iterateCode p) (optionEncode ea) (k,ea x) (DrawTree.iterate f k x) := by + unfold iterateCode + apply law_precompose O _ _ _ _ (k,optionEncode ea (some x)) _ rfl + rw [←treeRepeat_option] + apply law_repeat + intro u + exact law_optionContinue O p ea ea f u hp +end Effect + +lemma polySafe_reparam {a b : DataType} (p : Expression a b) (R : ℕ → Value a → Prop) + (hp : PolySafe p R) (g : SizePolynomial) : PolySafe p (fun S x => R (g.eval S) x) := by + obtain ⟨f,hf⟩ := hp + exact ⟨f.subst g,fun O S x hx => by rw [SizePolynomial.eval_subst]; exact hf O _ x hx⟩ +lemma polySafe_post {a b c : DataType} (p : Expression a b) (q : Expression b c) + (R : ℕ → Value a → Prop) (hp : PolySafe p R) (hq : Controlled q) : PolySafe (p >>> q) R := by + obtain ⟨f,hf⟩ := hp + apply polySafe_compose p q R (fun S y => width y≤f.eval S) ⟨f,hf⟩ + (polySafe_of_controlled q hq _ f (by intros; assumption)) + intro n O S x hx y hy + exact safe_output (hf O S x hx) hy +lemma foldValue_iterateM {n : ℕ} (O : IndependenceOracle n) {a : DataType} + (p : Expression a a) (xs : List Bool) (z : Value a) : + foldValue (run O (Expression.snd (a:=.bool) >>> p)) xs z=iterateM (run O p) xs.length z := by + induction xs generalizing z with + | nil => rfl + | cons b xs ih => simp only [foldValue,run_compose,run_snd,Option.bind_some,List.length_cons,iterateM]; simp_rw [ih] + +lemma polySafe_iterateNat {a : DataType} (p : Expression a a) + (R : ℕ → Value (.prod .nat a) → Prop) (Q : ℕ → Value a → Prop) + (hp : PolySafe p Q) (g : SizePolynomial) + (hinput : ∀ S k z,R S (k,z) → k+width (a:=a) z≤g.eval S) + (hacc : ∀ {n : ℕ} (O : IndependenceOracle n) S k z,R S (k,z) → + ∀ j,j≤k → ∀ y,iterateM (run O p) j z=some y → width (a:=a) y≤g.eval S) + (hbody : ∀ {n : ℕ} (O : IndependenceOracle n) S k z,R S (k,z) → + ∀ j,j k≤g.eval S) + (polySafe_of_controlled Expression.fst (by control) R T hnatwidth) + (polySafe_reparam unary (fun S k => k≤S) polySafe_unary g) + intro n O S x hx y hy + obtain ⟨k,z⟩ := x + simp only [run_fst, Option.some.injEq] at hy + subst y + have hh : k+width (a:=a) z≤g.eval S := hinput S k z hx + exact (Nat.le_add_right k (width (a:=a) z)).trans hh + · exact polySafe_of_controlled Expression.snd (by control) R T hnatwidth + let Rw : ℕ → Value (.prod .word a) → Prop := fun S x => R S (x.1.length,x.2) + let Rl : ℕ → Value (.prod (.list .bool) a) → Prop := fun S x => R S (x.1.length,x.2) + have hw : ∀ S x,Rw S x → width x≤T.eval S := by + intro S x hx + obtain ⟨w,z⟩ := x + have hh : w.length+width (a:=a) z≤g.eval S := hinput S w.length z hx + rw [width_pair (a:=.word) (b:=a),width_word] + dsimp [T,SizePolynomial.eval] + omega + have hfold : PolySafe (.fold (snd >>> p)) Rl := by + refine polySafe_fold (Expression.snd (a:=.bool) >>> p) Rl + (fun S x => width x≤T.eval S ∧ Q S x.2) ?_ T ?_ ?_ ?_ + · apply polySafe_compose _ _ _ Q + (polySafe_of_controlled Expression.snd (by control) _ T (by intro S x hx; exact hx.1)) hp + intro n O S x hx y hy + cases hy + exact hx.2 + · intro S x hx + obtain ⟨xs,z⟩ := x + have hh : xs.length+width (a:=a) z≤g.eval S := hinput S xs.length z hx + rw [width_pair (a:=.list .bool) (b:=a),width_list_bool] + dsimp [T,SizePolynomial.eval] + omega + · intro n O S xs z hx pre post he y hy + rw [foldValue_iterateM] at hy + have hj : pre.length≤xs.length := by rw [he,List.length_append]; omega + have hh := hacc O S xs.length z hx pre.length hj y hy + dsimp [T,SizePolynomial.eval] + omega + · intro n O S xs z hx pre b post he y hy + rw [foldValue_iterateM] at hy + have hj : pre.length rfl + | succ k ih => rw [iterateM,hp,Option.bind_some,ih,Function.iterate_succ_apply] +lemma width_list_le {a : DataType} (xs : List (Value a)) (S : ℕ) + (hs : ∀ x∈xs,width (a:=a) x≤S) : width (a:=.list a) xs≤xs.length*(2*S+2) := by + induction xs with + | nil => simp + | cons x xs ih => + have hx := hs x (by simp) + have hh := ih (fun y hy => hs y (by simp [hy])) + rw [width_cons (a:=a),List.length_cons,Nat.add_mul,Nat.one_mul] + omega +lemma width_range (k : ℕ) : width (a:=.list .nat) (List.range k)≤k*(2*k+2) := by + simpa only [List.length_range] using width_list_le (a:=.nat) (List.range k) k (by + intro x hx + exact (bits_length_le_value x).trans (List.mem_range.mp hx).le) +lemma width_rangeState (k : ℕ) : width (a:=.prod .nat (.list .nat)) (k,(List.range k).reverse)≤4*(k+1)^2 := by + rw [width_pair (a:=.nat) (b:=.list .nat),width_nat,width_list_reverse (a:=.nat)] + have h := width_range k + have h' := bits_length_le_value k + nlinarith +lemma controlled_rangeStep : Controlled rangeStepCode := by unfold rangeStepCode; control +lemma polySafe_rangeCode : PolySafe rangeCode (fun S k => k≤S) := by + let g : SizePolynomial := .mul (.constant 10) (.mul (.add .input (.constant 1)) (.add .input (.constant 1))) + have hg (S : ℕ) : g.eval S=10*(S+1)^2 := by simp [g,SizePolynomial.eval,pow_two] + let R : ℕ → Value (.prod .nat (.prod .nat (.list .nat))) → Prop := fun S x => x.1≤S ∧ x.2=(0,[]) + have hi : PolySafe (iterateNat rangeStepCode) R := by + refine polySafe_iterateNat rangeStepCode R (fun S z => width z≤g.eval S) + (polySafe_of_controlled _ controlled_rangeStep _ g (by intros; assumption)) g ?_ ?_ ?_ + · intro S k z hx + dsimp [R] at hx + rcases hx with ⟨hk,rfl⟩ + rw [hg] + change k+1≤10*(S+1)^2 + exact (Nat.add_le_add_right hk 1).trans (by nlinarith) + · intro n O S k z hx j hj y hy + dsimp [R] at hx + rcases hx with ⟨hk,rfl⟩ + rw [iterateM_total (run O rangeStepCode) rangeStep (fun _ => rfl),rangeStep_iterate] at hy + cases hy + apply (width_rangeState j).trans + rw [hg] + have hjk : Nat.le j S := hj.trans hk + exact (Nat.mul_le_mul_left 4 (Nat.pow_le_pow_left (Nat.add_le_add_right hjk 1) 2)).trans + (Nat.mul_le_mul_right _ (by decide : 4≤10)) + · intro n O S k z hx j hj y hy + dsimp [R] at hx + rcases hx with ⟨hk,rfl⟩ + rw [iterateM_total (run O rangeStepCode) rangeStep (fun _ => rfl),rangeStep_iterate] at hy + cases hy + apply (width_rangeState j).trans + rw [hg] + have hjk : Nat.le j S := hj.le.trans hk + exact (Nat.mul_le_mul_left 4 (Nat.pow_le_pow_left (Nat.add_le_add_right hjk 1) 2)).trans + (Nat.mul_le_mul_right _ (by decide : 4≤10)) + unfold rangeCode + apply polySafe_compose _ _ _ R + (polySafe_of_controlled _ (by control) _ .input (by + intro S k hk + exact (bits_length_le_value k).trans hk)) + (polySafe_post _ _ R hi (controlled_compose _ _ (by control) controlled_listReverse)) + intro n O S x hx y hy + cases hy + exact ⟨hx,rfl⟩ +lemma controlled_wordRange : Controlled (wordLength >>> rangeCode) := by + apply polySafe_controlled + apply polySafe_compose _ _ _ (fun S k => k≤S) + (polySafe_of_controlled _ controlled_wordLength _ .input (by intros; assumption)) polySafe_rangeCode + intro n O S x hx y hy + rw [run_wordLength] at hy + cases hy + exact hx + +lemma run_filterStep_partial {n : ℕ} (O : IndependenceOracle n) {a b : DataType} + (p : Expression (.prod a b) .bool) (x : Value a) (ys : List (Value a)) (z : Value b) : + run O (filterStep p) (x,(ys,z))=(run O p (x,z)).map (fun t => ((if t then x::ys else ys),z)) := by + simp only [filterStep,run_both,run_applyIf,run_compose,run_fst,run_snd,Option.bind_some,Option.map_some] + cases he : run O p (x,z) with + | none => rfl + | some t => cases t <;> rfl +lemma fold_filterStep_bound {n : ℕ} (O : IndependenceOracle n) {a b : DataType} + (p : Expression (.prod a b) .bool) (xs ys : List (Value a)) (z : Value b) + (v : Value (.prod (.list a) b)) (hv : foldValue (run O (filterStep p)) xs (ys,z)=some v) : + width (a:=.list a) v.1≤width (a:=.list a) xs+width (a:=.list a) ys ∧ v.2=z := by + induction xs generalizing ys with + | nil => cases hv; simp + | cons x xs ih => + rw [foldValue,run_filterStep_partial] at hv + cases he : run O p (x,z) with + | none => simp [he] at hv + | some t => + simp only [he,Option.map_some,Option.bind_some] at hv + cases t with + | false => + have hh := ih ys hv + rw [width_cons (a:=a)] + exact ⟨by omega,hh.2⟩ + | true => + have hh := ih (x::ys) hv + rw [width_cons (a:=a)] at hh ⊢ + exact ⟨by omega,hh.2⟩ +lemma controlled_filterStep {a b : DataType} (p : Expression (.prod a b) .bool) (hp : Controlled p) : + Controlled (filterStep p) := by unfold filterStep; control +lemma controlled_filterFold {a b : DataType} (p : Expression (.prod a b) .bool) (hp : Controlled p) : + Controlled (.fold (filterStep p)) := by + apply controlled_fold _ (controlled_filterStep p hp) (.mul (.constant 3) .input) + intro n O xs z pre post he y hy + obtain ⟨ys,ctx⟩ := z + have hh := fold_filterStep_bound O p pre ys ctx y hy + have hpre : width (a:=.list a) pre≤width (a:=.list a) xs := by rw [he,width_list_append]; omega + obtain ⟨out,outctx⟩ := y + dsimp only [Prod.fst,Prod.snd] at hh + rw [width_pair (a:=.list a) (b:=b),width_pair (a:=.list a) (b:=.prod (.list a) b), + width_pair (a:=.list a) (b:=b),hh.2] + dsimp [SizePolynomial.eval] + omega +lemma controlled_filterWith {a b : DataType} (p : Expression (.prod a b) .bool) (hp : Controlled p) : + Controlled (filterWith p) := by + unfold filterWith + have hf := controlled_filterFold p hp + have hr := controlled_listReverse (a:=a) + control + +open scoped Classical +noncomputable def stateEncode {n : ℕ} (S : Set (Fin n⊕Fin n)) : Value StateData := + (List.ofFn (fun i => decide (Sum.inl i∈S)),List.ofFn (fun i => decide (Sum.inr i∈S))) +@[simp] lemma stateEncode_left_length {n : ℕ} (S : Set (Fin n⊕Fin n)) : + (stateEncode S).1.length=n := List.length_ofFn +@[simp] lemma stateEncode_right_length {n : ℕ} (S : Set (Fin n⊕Fin n)) : + (stateEncode S).2.length=n := List.length_ofFn +@[simp] lemma stateEncode_repr {n : ℕ} (S : Set (Fin n⊕Fin n)) : + representedState n (stateEncode S)=S := by + ext i + cases i <;> simp [representedState,stateEncode,wordSet] +lemma stateEncode_get_left {n : ℕ} (S : Set (Fin n⊕Fin n)) (i : Fin n) : + (stateEncode S).1[i.val]?.getD false=decide (Sum.inl i∈S) := by simp [stateEncode] +lemma stateEncode_get_right {n : ℕ} (S : Set (Fin n⊕Fin n)) (i : Fin n) : + (stateEncode S).2[i.val]?.getD false=decide (Sum.inr i∈S) := by simp [stateEncode] + +namespace Expression + +def boolXor : Expression (.prod .bool .bool) .bool := branch ident boolNot +lemma run_boolXor {n : ℕ} (O : IndependenceOracle n) (a b : Bool) : + run O boolXor (a,b)=some (xor a b) := by cases a <;> cases b <;> rfl + +def singleAt : Expression (.prod .nat StateData) .bool := + both (both (snd >>> fst) fst >>> wordGet) (both (snd >>> snd) fst >>> wordGet) >>> boolXor +def fullAt : Expression (.prod .nat StateData) .bool := + both (both (snd >>> fst) fst >>> wordGet) (both (snd >>> snd) fst >>> wordGet) >>> boolAnd +def emptyAt : Expression (.prod .nat StateData) .bool := + both (both (snd >>> fst) fst >>> wordGet) (both (snd >>> snd) fst >>> wordGet) >>> boolOr >>> boolNot + +def singleValue (i : ℕ) (S : Word×Word) : Bool := xor (S.1[i]?.getD false) (S.2[i]?.getD false) +def fullValue (i : ℕ) (S : Word×Word) : Bool := (S.1[i]?.getD false) && (S.2[i]?.getD false) +def emptyValue (i : ℕ) (S : Word×Word) : Bool := !(S.1[i]?.getD false || S.2[i]?.getD false) +lemma run_singleAt {n : ℕ} (O : IndependenceOracle n) (i : ℕ) (S : Word×Word) : + run O singleAt (i,S)=some (singleValue i S) := by + simp only [singleAt,run_compose,run_both,run_fst,run_snd,Option.bind_some,Option.map_some] + rw [run_wordGet,run_wordGet] + exact run_boolXor O _ _ +lemma run_fullAt {n : ℕ} (O : IndependenceOracle n) (i : ℕ) (S : Word×Word) : + run O fullAt (i,S)=some (fullValue i S) := by + simp only [fullAt,run_compose,run_both,run_fst,run_snd,Option.bind_some,Option.map_some] + rw [run_wordGet,run_wordGet] + exact run_boolAnd O _ _ +lemma run_emptyAt {n : ℕ} (O : IndependenceOracle n) (i : ℕ) (S : Word×Word) : + run O emptyAt (i,S)=some (emptyValue i S) := by + simp only [emptyAt,run_compose,run_both,run_fst,run_snd,Option.bind_some,Option.map_some] + rw [run_wordGet,run_wordGet] + change ((run O boolOr _).bind (run O boolNot))=_ + rw [run_boolOr]; exact run_boolNot O _ + +def plainValue (S : Word×Word) : Bool := ((List.range S.1.length).map (fun i => singleValue i S)).all id +def plainCode : Expression StateData .bool := + both (fst >>> wordLength >>> rangeCode) ident >>> mapWith singleAt >>> listAll +lemma run_plainCode {n : ℕ} (O : IndependenceOracle n) (S : Word×Word) : + run O plainCode S=some (plainValue S) := by + simp only [plainCode,run_compose,run_both,run_fst,run_ident,Option.bind_some,Option.map_some] + rw [run_wordLength,Option.bind_some,run_rangeCode] + change ((run O (mapWith singleAt) (List.range S.1.length,S)).bind (run O listAll))=_ + rw [run_mapWith O singleAt singleValue (run_singleAt O)] + exact run_listAll O _ +end Expression + +lemma singleValue_source {n : ℕ} (S : Set (Fin n⊕Fin n)) (i : Fin n) : + Expression.singleValue i.val (stateEncode S)=decide (PairSingle (slotPair i) S) := by + rw [Expression.singleValue,stateEncode_get_left,stateEncode_get_right] + unfold PairSingle slotPair + by_cases ha : Sum.inl i∈S <;> by_cases hb : Sum.inr i∈S <;> simp [ha,hb] +lemma fullValue_source {n : ℕ} (S : Set (Fin n⊕Fin n)) (i : Fin n) : + Expression.fullValue i.val (stateEncode S)=decide (PairFull (slotPair i) S) := by + rw [Expression.fullValue,stateEncode_get_left,stateEncode_get_right] + unfold PairFull slotPair + by_cases ha : Sum.inl i∈S <;> by_cases hb : Sum.inr i∈S <;> simp [ha,hb] +lemma emptyValue_source {n : ℕ} (S : Set (Fin n⊕Fin n)) (i : Fin n) : + Expression.emptyValue i.val (stateEncode S)=decide (PairEmpty (slotPair i) S) := by + rw [Expression.emptyValue,stateEncode_get_left,stateEncode_get_right] + unfold PairEmpty slotPair + by_cases ha : Sum.inl i∈S <;> by_cases hb : Sum.inr i∈S <;> simp [ha,hb] + +lemma plainValue_source {n : ℕ} (S : Set (Fin n⊕Fin n)) : + Expression.plainValue (stateEncode S)=decide (PlainState (pairedSlots n) S) := by + apply Bool.eq_iff_iff.mpr + simp only [Expression.plainValue,List.all_map,List.all_eq_true,Function.comp_apply,id_eq, + stateEncode_left_length,List.mem_range,decide_eq_true_eq] + constructor + · intro h p hp + obtain ⟨i,hi,rfl⟩ := List.mem_map.mp hp + have hh := h i.val i.isLt + rw [singleValue_source] at hh + exact of_decide_eq_true hh + · intro h i hi + rw [singleValue_source S ⟨i,hi⟩] + exact decide_eq_true (h _ (by simp [pairedSlots])) + +lemma plainCode_source {n : ℕ} (O : IndependenceOracle n) (S : Set (Fin n⊕Fin n)) : + run O Expression.plainCode (stateEncode S)=some (decide (PlainState (pairedSlots n) S)) := by + rw [Expression.run_plainCode,plainValue_source] + +abbrev DefectInput := DataType.prod Expression.NN StateData +namespace Expression + +def defectAt : Expression (.prod .nat DefectInput) .bool := + applyIf (both fst (snd >>> fst >>> fst) >>> natEqual) + (applyIf (both fst (snd >>> fst >>> snd) >>> natEqual) + (both fst (snd >>> snd) >>> singleAt) (both fst (snd >>> snd) >>> fullAt)) + (both fst (snd >>> snd) >>> emptyAt) +def defectAtValue (i : ℕ) (p : (ℕ×ℕ)×(Word×Word)) : Bool := + if i=p.1.1 then emptyValue i p.2 else if i=p.1.2 then fullValue i p.2 else singleValue i p.2 +lemma run_defectAt {n : ℕ} (O : IndependenceOracle n) (i p r : ℕ) (S : Word×Word) : + run O defectAt (i,((p,r),S))=some (defectAtValue i ((p,r),S)) := by + simp only [defectAt,run_applyIf,run_compose,run_both,run_fst,run_snd,Option.bind_some,Option.map_some] + rw [run_natEqual] + by_cases hi : i=p + · subst i; simp only [decide_true,Option.bind_some,ite_true]; simpa only [defectAtValue,ite_true] using run_emptyAt O p S + · simp only [hi,decide_false,Option.bind_some,Bool.false_eq_true,ite_false] + rw [run_natEqual] + by_cases hr : i=r + · subst i; simp only [decide_true,Option.bind_some,ite_true] + simpa only [defectAtValue,hi,ite_false,ite_true] using run_fullAt O r S + · simp only [hr,decide_false,Option.bind_some,Bool.false_eq_true,ite_false] + simpa only [defectAtValue,hi,hr,ite_false] using run_singleAt O i S + +def defectValue (p r : ℕ) (S : Word×Word) : Bool := + decide (p≠r) && ((List.range S.1.length).map (fun i => defectAtValue i ((p,r),S))).all id +def defectCode : Expression DefectInput .bool := + both (fst >>> natEqual >>> boolNot) + (both (snd >>> fst >>> wordLength >>> rangeCode) ident >>> mapWith defectAt >>> listAll) >>> boolAnd +lemma run_defectCode {n : ℕ} (O : IndependenceOracle n) (p r : ℕ) (S : Word×Word) : + run O defectCode ((p,r),S)=some (defectValue p r S) := by + simp only [defectCode,run_compose,run_both,run_fst,run_snd,run_ident,Option.bind_some,Option.map_some] + rw [run_natEqual,run_wordLength] + simp only [Option.bind_some] + rw [run_rangeCode] + simp only [Option.bind_some,run_boolNot,run_compose] + rw [run_mapWith O defectAt defectAtValue (by intro i v; rcases v with ⟨⟨p,r⟩,S⟩; exact run_defectAt O i p r S)] + simp only [Option.bind_some,run_listAll,Option.map_some] + rw [run_boolAnd] + congr 1 + simp only [defectValue,decide_not] +end Expression + +lemma slotPair_inj {α : Type*} (i j : α) : slotPair i=slotPair j ↔ i=j := by simp [slotPair] +lemma slotPair_mem {n : ℕ} (i : Fin n) : slotPair i∈pairedSlots n := by simp [pairedSlots] +lemma defect_paired_iff {n : ℕ} (p r : Fin n) (S : Set (Fin n⊕Fin n)) : + DefectState (pairedSlots n) (slotPair p) (slotPair r) S ↔ + p≠r ∧ PairEmpty (slotPair p) S ∧ PairFull (slotPair r) S ∧ + ∀ i, i≠p → i≠r → PairSingle (slotPair i) S := by + constructor + · intro h + refine ⟨fun hp => h.2.2.1 (congrArg slotPair hp),h.2.2.2.1,h.2.2.2.2.1,?_⟩ + intro i hip hir + exact h.2.2.2.2.2 (slotPair i) (slotPair_mem i) (fun he => hip ((slotPair_inj i p).mp he)) (fun he => hir ((slotPair_inj i r).mp he)) + · rintro ⟨hpr,hp,hr,h⟩ + refine ⟨slotPair_mem p,slotPair_mem r,fun he => hpr ((slotPair_inj p r).mp he),hp,hr,?_⟩ + intro t ht htp htr + obtain ⟨i,hi,rfl⟩ := List.mem_map.mp ht + exact h i (fun he => htp (congrArg slotPair he)) (fun he => htr (congrArg slotPair he)) + +lemma defectValue_source {n : ℕ} (S : Set (Fin n⊕Fin n)) (p r : Fin n) : + Expression.defectValue p.val r.val (stateEncode S)= + decide (DefectState (pairedSlots n) (slotPair p) (slotPair r) S) := by + apply Bool.eq_iff_iff.mpr + simp only [Expression.defectValue,Bool.and_eq_true,decide_eq_true_eq,List.all_map,List.all_eq_true, + Function.comp_apply,id_eq,stateEncode_left_length,List.mem_range] + rw [defect_paired_iff] + constructor + · rintro ⟨hne,h⟩ + have hpr : p≠r := fun he => hne (congrArg Fin.val he) + refine ⟨hpr,?_,?_,?_⟩ + · have hh := h p.val p.isLt + simpa only [Expression.defectAtValue,ite_true,emptyValue_source,decide_eq_true_eq] using hh + · have hh := h r.val r.isLt + have hrp : r.val≠p.val := Ne.symm hne + simpa only [Expression.defectAtValue,hrp,ite_false,ite_true,fullValue_source,decide_eq_true_eq] using hh + · intro i hip hir + have hh := h i.val i.isLt + have hip' : i.val≠p.val := fun he => hip (Fin.ext he) + have hir' : i.val≠r.val := fun he => hir (Fin.ext he) + simpa only [Expression.defectAtValue,hip',hir',ite_false,singleValue_source,decide_eq_true_eq] using hh + · rintro ⟨hpr,hp,hr,h⟩ + refine ⟨fun he => hpr (Fin.ext he),?_⟩ + intro i hi + let j : Fin n := ⟨i,hi⟩ + change Expression.defectAtValue j.val ((p.val,r.val),stateEncode S)=true + by_cases hjp : j=p + · subst p + simpa only [Expression.defectAtValue,ite_true,emptyValue_source,decide_eq_true_eq] using hp + · by_cases hjr : j=r + · subst r + have hne : j.val≠p.val := fun he => hjp (Fin.ext he) + simpa only [Expression.defectAtValue,hne,ite_false,ite_true,fullValue_source,decide_eq_true_eq] using hr + · have hip : j.val≠p.val := fun he => hjp (Fin.ext he) + have hir : j.val≠r.val := fun he => hjr (Fin.ext he) + simpa only [Expression.defectAtValue,hip,hir,ite_false,singleValue_source,decide_eq_true_eq] using h j hjp hjr + +lemma defectCode_source {n : ℕ} (O : IndependenceOracle n) (S : Set (Fin n⊕Fin n)) (p r : Fin n) : + run O Expression.defectCode ((p.val,r.val),stateEncode S)= + some (decide (DefectState (pairedSlots n) (slotPair p) (slotPair r) S)) := by + rw [Expression.run_defectCode,defectValue_source] + +abbrev SampleData := DataType.list StateData +abbrev HistoryData := DataType.list SampleData +namespace Expression + +def countWith {a b} (p : Expression (.prod a b) .bool) : Expression (.prod (.list a) b) .nat := + filterWith p >>> listLength +lemma run_countWith {n : ℕ} (O : IndependenceOracle n) {a b} (p : Expression (.prod a b) .bool) + (f : Value a → Value b → Bool) (hp : ∀ x z,run O p (x,z)=some (f x z)) + (xs : List (Value a)) (z : Value b) : + run O (countWith p) (xs,z)=some (xs.countP (fun x => f x z)) := by + rw [countWith,run_compose,run_filterWith O p f hp,Option.bind_some,run_listLength] + simp only [List.countP_eq_length_filter] + +def countPlainCode : Expression SampleData .nat := + both ident (constant (b:=.unit) ()) >>> countWith (fst >>> plainCode) +def countDefectCode : Expression (.prod SampleData NN) .nat := countWith (swap >>> defectCode) +def countPlainValue (xs : List (Word×Word)) : ℕ := xs.countP plainValue +def countDefectValue (xs : List (Word×Word)) (p r : ℕ) : ℕ := xs.countP (fun S => defectValue p r S) +lemma run_countPlainCode {n : ℕ} (O : IndependenceOracle n) (xs : List (Word×Word)) : + run O countPlainCode xs=some (countPlainValue xs) := by + change run O (countWith (fst (b:=.unit) >>> plainCode)) (xs,())=_ + exact run_countWith (a:=StateData) (b:=.unit) O _ (fun x (_ : Unit) => plainValue x) (fun x _ => run_plainCode O x) xs () +lemma run_countDefectCode {n : ℕ} (O : IndependenceOracle n) (xs : List (Word×Word)) (p r : ℕ) : + run O countDefectCode (xs,(p,r))=some (countDefectValue xs p r) := by + exact run_countWith (a:=StateData) (b:=NN) O _ (fun S u => defectValue u.1 u.2 S) + (fun S u => run_defectCode O u.1 u.2 S) xs (p,r) + +def learningRatioCode : Expression (.prod SampleData NN) NN := + both (fst >>> countPlainCode) countDefectCode >>> normalizeRat +def learningRatio (xs : List (Word×Word)) (p r : ℕ) : ℚ := (countPlainValue xs:ℚ)/countDefectValue xs p r +lemma learningRatio_nonneg (xs : List (Word×Word)) (p r : ℕ) : 0≤learningRatio xs p r := by + unfold learningRatio; positivity +lemma run_learningRatio {n : ℕ} (O : IndependenceOracle n) (xs : List (Word×Word)) (p r : ℕ) : + run O learningRatioCode (xs,(p,r))=some (rationalPair (learningRatio xs p r)) := by + simp only [learningRatioCode,run_compose,run_both,run_fst,Option.bind_some] + rw [run_countPlainCode,run_countDefectCode] + exact run_normalizeRat_pair O _ _ + +def weightStep : Expression (.prod SampleData (.prod NN NN)) (.prod NN NN) := + both (snd >>> fst) + (applyIf (snd >>> fst >>> natEqual) + (both (snd >>> snd) (both fst (snd >>> fst) >>> learningRatioCode) >>> ratMul) + (snd >>> snd)) +def weightUpdate (p r : ℕ) (xs : List (Word×Word)) (q : ℚ) : ℚ := + if p=r then q else q*learningRatio xs p r +lemma weightUpdate_nonneg (p r : ℕ) (xs : List (Word×Word)) (q : ℚ) (hq : 0≤q) : + 0≤weightUpdate p r xs q := by + unfold weightUpdate + split_ifs + · exact hq + · exact mul_nonneg hq (learningRatio_nonneg xs p r) +lemma run_weightStep {n : ℕ} (O : IndependenceOracle n) (p r : ℕ) (xs : List (Word×Word)) (q : ℚ) (hq : 0≤q) : + run O weightStep (xs,((p,r),rationalPair q))=some ((p,r),rationalPair (weightUpdate p r xs q)) := by + simp only [weightStep,run_both,run_compose,run_fst,run_snd,Option.bind_some,run_applyIf] + rw [run_natEqual] + by_cases hpr : p=r + · subst p; simp only [decide_true,Option.bind_some,ite_true,Option.map_some,weightUpdate] + · simp only [hpr,decide_false,Option.bind_some,Option.map_some,Bool.false_eq_true,ite_false] + rw [run_learningRatio] + simp only [Option.bind_some,Option.map_some] + rw [run_ratMul O q _ hq (learningRatio_nonneg xs p r)] + simp only [Option.map_some,weightUpdate,hpr,ite_false] + +def historyWeightValue (p r : ℕ) (h : List (List (Word×Word))) : ℚ := + h.foldl (fun q xs => weightUpdate p r xs q) 4 +def historyWeightCode : Expression (.prod HistoryData NN) NN := + both fst (both snd (constant (b:=NN) (4,1))) >>> fold weightStep >>> snd +lemma fold_weightStep {n : ℕ} (O : IndependenceOracle n) (p r : ℕ) (h : List (List (Word×Word))) + (q : ℚ) (hq : 0≤q) : + foldValue (run O weightStep) h ((p,r),rationalPair q)=some + ((p,r),rationalPair (h.foldl (fun q xs => weightUpdate p r xs q) q)) := by + induction h generalizing q with + | nil => rfl + | cons xs h ih => + rw [foldValue,run_weightStep O p r xs q hq,Option.bind_some] + exact ih _ (weightUpdate_nonneg p r xs q hq) +lemma run_historyWeightCode {n : ℕ} (O : IndependenceOracle n) (p r : ℕ) (h : List (List (Word×Word))) : + run O historyWeightCode (h,(p,r))=some (rationalPair (historyWeightValue p r h)) := by + change ((foldValue (run O weightStep) h ((p,r),rationalPair 4)).bind fun z => some z.2)=_ + rw [fold_weightStep O p r h 4 (by norm_num)] + rfl +end Expression + +noncomputable def sampleEncode {n : ℕ} (xs : List (Set (Fin n⊕Fin n))) : Value SampleData := xs.map stateEncode +noncomputable def historyEncode {n : ℕ} (h : List (List (Set (Fin n⊕Fin n)))) : Value HistoryData := h.map sampleEncode +lemma countPlainValue_source {n : ℕ} (xs : List (Set (Fin n⊕Fin n))) : + Expression.countPlainValue (sampleEncode xs)=xs.countP (fun S => decide (PlainState (pairedSlots n) S)) := by + simp only [Expression.countPlainValue,sampleEncode,List.countP_map,plainValue_source,Function.comp_def] +lemma countDefectValue_source {n : ℕ} (xs : List (Set (Fin n⊕Fin n))) (p r : Fin n) : + Expression.countDefectValue (sampleEncode xs) p.val r.val= + xs.countP (fun S => decide (DefectState (pairedSlots n) (slotPair p) (slotPair r) S)) := by + simp only [Expression.countDefectValue,sampleEncode,List.countP_map,defectValue_source,Function.comp_def] + +lemma weightUpdate_source {n : ℕ} (xs : List (Set (Fin n⊕Fin n))) (p r : Fin n) + (w : ((Fin n⊕Fin n)×(Fin n⊕Fin n)) → ((Fin n⊕Fin n)×(Fin n⊕Fin n)) → ℚ) : + Expression.weightUpdate p.val r.val (sampleEncode xs) (w (slotPair p) (slotPair r))= + rationalLearn (pairedSlots n) w xs (slotPair p) (slotPair r) := by + unfold Expression.weightUpdate rationalLearn + by_cases hpr : p=r + · subst p; simp + · have hv : p.val≠r.val := fun he => hpr (Fin.ext he) + have hs : slotPair p≠slotPair r := fun he => hpr ((slotPair_inj p r).mp he) + rw [ite_eq_right hv,ite_eq_left ⟨slotPair_mem p,slotPair_mem r,hs⟩,rationalTypeRatio] + rw [Expression.learningRatio,countPlainValue_source,countDefectValue_source] + +lemma historyWeight_source {n : ℕ} (h : List (List (Set (Fin n⊕Fin n)))) (p r : Fin n) : + Expression.historyWeightValue p.val r.val (historyEncode h)= + rationalHistory (pairedSlots n) id h (slotPair p) (slotPair r) := by + have hf : ∀ (l : List (List (Set (Fin n⊕Fin n)))) + (w : ((Fin n⊕Fin n)×(Fin n⊕Fin n)) → ((Fin n⊕Fin n)×(Fin n⊕Fin n)) → ℚ), + (historyEncode l).foldl (fun q xs => Expression.weightUpdate p.val r.val xs q) (w (slotPair p) (slotPair r))= + (l.foldl (fun w xs => rationalLearn (pairedSlots n) w xs) w) (slotPair p) (slotPair r) := by + intro l + induction l with + | nil => intro w; rfl + | cons xs l ih => + intro w + change (historyEncode l).foldl _ (Expression.weightUpdate p.val r.val (sampleEncode xs) (w (slotPair p) (slotPair r)))=_ + rw [weightUpdate_source] + exact ih _ + exact hf h (fun _ _ => 4) + +lemma historyWeightCode_source {n : ℕ} (O : IndependenceOracle n) + (h : List (List (Set (Fin n⊕Fin n)))) (p r : Fin n) : + run O Expression.historyWeightCode (historyEncode h,(p.val,r.val))= + some (rationalPair (rationalHistory (pairedSlots n) id h (slotPair p) (slotPair r))) := by + rw [Expression.run_historyWeightCode,historyWeight_source] + +namespace Expression + +def listAppend {a} : Expression (.prod (.list a) (.list a)) (.list a) := + onLeft listReverse >>> fold cons +lemma run_listAppend {n : ℕ} (O : IndependenceOracle n) {a} (xs ys : List (Value a)) : + run O listAppend (xs,ys)=some (xs++ys) := by + have hf : ∀ (us vs : List (Value a)),foldValue (run O cons) us vs=some (us.reverse++vs) := by + intro us + induction us with + | nil => intro vs; rfl + | cons u us ih => intro vs; simpa [foldValue,run,List.reverse_cons,List.append_assoc] using ih (u::vs) + simp only [listAppend,onLeft,run_compose,run_both,run_fst,run_snd,Option.bind_some] + rw [run_listReverse] + simp only [Option.bind_some,Option.map_some] + change foldValue (run O cons) xs.reverse ys=_ + rw [hf,List.reverse_reverse] + +def productStep {a b} : Expression (.prod a (.prod (.list (.prod a b)) (.list b))) + (.prod (.list (.prod a b)) (.list b)) := + both (both (snd >>> fst) (both (snd >>> snd) fst >>> mapWith swap) >>> listAppend) (snd >>> snd) +def productCode {a b} : Expression (.prod (.list a) (.list b)) (.list (.prod a b)) := + both fst (both (constant []) snd) >>> fold productStep >>> fst +lemma run_productStep {n : ℕ} (O : IndependenceOracle n) {a b} + (x : Value a) (zs : List (Value a × Value b)) (ys : List (Value b)) : + run O productStep (x,(zs,ys))=some (zs++ys.map (fun y => (x,y)),ys) := by + simp only [productStep,run_both,run_compose,run_fst,run_snd,Option.bind_some,Option.map_some] + rw [run_mapWith O swap (fun y x => (x,y)) (fun _ _ => rfl)] + simp only [Option.map_some,Option.bind_some] + rw [run_listAppend] + rfl +lemma run_productCode {n : ℕ} (O : IndependenceOracle n) {a b} + (xs : List (Value a)) (ys : List (Value b)) : + run O productCode (xs,ys)=some ((xs ×ˢ ys)) := by + have hf : ∀ (us : List (Value a)) (acc : List (Value a × Value b)), + foldValue (run O productStep) us (acc,ys)=some (acc++(us ×ˢ ys),ys) := by + intro us + induction us with + | nil => intro acc; simp [foldValue] + | cons u us ih => + intro acc + rw [foldValue,run_productStep,Option.bind_some,ih] + simp [List.product_cons,List.append_assoc] + change ((foldValue (run O productStep) xs ([],ys)).bind fun z => some z.1)=_ + rw [hf] + rfl + +def indexPairs : Expression .nat (.list NN) := both rangeCode rangeCode >>> productCode +lemma run_indexPairs {n : ℕ} (O : IndependenceOracle n) (k : ℕ) : + run O indexPairs k=some ((List.range k) ×ˢ (List.range k)) := by + simp only [indexPairs,run_compose,run_both] + rw [run_rangeCode] + simp only [Option.bind_some,Option.map_some] + exact run_productCode O _ _ +end Expression + +open Expression +lemma controlled_listAppend {a : DataType} : Controlled (listAppend (a:=a)) := by + unfold listAppend + apply controlled_compose + · exact controlled_onLeft _ controlled_listReverse + · apply controlled_fold (Expression.cons (a:=a)) (controlled_atomic _ trivial) (.mul (.constant 2) .input) + intro n O xs z pre post he y hy + have hh := foldValue_eq_foldl (run O (cons (a:=a))) (fun z x => x::z) (fun _ _ => rfl) pre z + rw [hh] at hy + cases hy + rw [List.foldl_flip_cons_eq_append',width_list_append,width_list_reverse] + have hp : width (a:=.list a) pre≤width (a:=.list a) xs := by rw [he,width_list_append]; omega + rw [width_pair (a:=.list a) (b:=.list a)] + dsimp [SizePolynomial.eval] + omega +lemma width_list_map_pair {a b : DataType} (x : Value a) (ys : List (Value b)) : + width (a:=.list (.prod a b)) (ys.map (fun y => (x,y)))≤ + 4*(width x+1)*(width (a:=.list b) ys+1) := by + have he : width (a:=.list (.prod a b)) (ys.map (fun y => (x,y)))= + (4*width x+2)*ys.length+width (a:=.list b) ys := by + induction ys with + | nil => rfl + | cons y ys ih => + simp only [List.map_cons,width_cons (a:=.prod a b),width_pair (a:=a) (b:=b),ih, + List.length_cons,width_cons (a:=b)] + ring + rw [he] + have hl := list_length_le_width ys + nlinarith +lemma width_list_product {a b : DataType} (xs : List (Value a)) (ys : List (Value b)) : + width (a:=.list (.prod a b)) (xs ×ˢ ys)≤ + 8*(width (a:=.list a) xs+1)*(width (a:=.list b) ys+1) := by + have hh : width (a:=.list (.prod a b)) (xs ×ˢ ys)≤ + 4*width (a:=.list a) xs*(width (a:=.list b) ys+1) := by + induction xs with + | nil => simp only [List.nil_product,width_nil (a:=.prod a b)]; omega + | cons x xs ih => + rw [List.product_cons,width_list_append (a:=.prod a b)] + have hx := width_list_map_pair x ys + rw [width_cons (a:=a)] + nlinarith + nlinarith +lemma controlled_productStep {a b : DataType} : Controlled (productStep (a:=a) (b:=b)) := by + have hm := controlled_mapWith (Expression.swap (a:=b) (b:=a)) controlled_swap + have ha := controlled_listAppend (a:=.prod a b) + unfold productStep + control +lemma fold_productStep {n : ℕ} (O : IndependenceOracle n) {a b : DataType} + (xs : List (Value a)) (zs : List (Value a×Value b)) (ys : List (Value b)) : + foldValue (run O (productStep (a:=a) (b:=b))) xs (zs,ys)=some (zs++(xs ×ˢ ys),ys) := by + induction xs generalizing zs with + | nil => simp [foldValue] + | cons x xs ih => + rw [foldValue,run_productStep,Option.bind_some,ih] + simp [List.product_cons,List.append_assoc] +lemma controlled_productCode {a b : DataType} : Controlled (productCode (a:=a) (b:=b)) := by + unfold productCode + apply controlled_compose + · control + · apply controlled_compose + · apply controlled_fold productStep controlled_productStep + (.mul (.constant 32) (.mul (.add .input (.constant 1)) (.add .input (.constant 1)))) + intro n O xs z pre post he y hy + rcases z with ⟨zs,ys⟩ + rw [fold_productStep] at hy + cases hy + have hp : width (a:=.list a) pre≤width (a:=.list a) xs := by rw [he,width_list_append]; omega + have hb := width_list_product pre ys + rw [width_pair (a:=.list (.prod a b)) (b:=.list b),width_list_append, + width_pair (a:=.list a) (b:=.prod (.list (.prod a b)) (.list b)), + width_pair (a:=.list (.prod a b)) (b:=.list b)] + dsimp [SizePolynomial.eval] + nlinarith + · control +lemma controlled_wordGet : Controlled wordGet := by + have hg := controlled_getD (a:=.bool) + unfold wordGet + control +lemma controlled_wordNot : Controlled wordNot := by + have hm := controlled_mapWith (c:=.unit) (fst >>> boolNot) (by + apply controlled_compose; exact controlled_atomic _ trivial; exact controlled_boolNot) + have hf := controlled_fromList + unfold wordNot + control +lemma controlled_wordCountStep : Controlled wordCountStep := by unfold wordCountStep; control +lemma fold_wordCount_bound {n : ℕ} (O : IndependenceOracle n) (xs : List Bool) (z y : ℕ) + (hy : foldValue (run O wordCountStep) xs z=some y) : y≤z+xs.length := by + induction xs generalizing z with + | nil => cases hy; simp + | cons b xs ih => + cases b with + | false => have hh := ih z hy; simp only [List.length_cons]; omega + | true => have hh := ih (z+1) hy; simp only [List.length_cons]; omega +lemma controlled_wordCount : Controlled wordCount := by + unfold wordCount + apply controlled_compose + · control + · apply controlled_compose + · control + · apply controlled_fold wordCountStep controlled_wordCountStep (.mul (.constant 2) .input) + intro n O xs z pre post he y hy + have hh := bits_length_mono (fold_wordCount_bound O pre z y hy) + have ha := bits_length_add z pre.length + have hp : pre.length≤xs.length := by rw [he,List.length_append]; omega + have hl := bits_length_le_value pre.length + rw [width_nat,width_pair (a:=.list .bool) (b:=.nat),width_nat,width_list_bool] + dsimp [SizePolynomial.eval] + omega +lemma controlled_deficiency : Controlled deficiencyCode := by + have hl := controlled_wordLength + have hc := controlled_wordCount + have hn := controlled_wordNot + have hs := controlled_natSub + unfold deficiencyCode + control + +open Expression +lemma controlled_normalizeRat : Controlled normalizeRat := by + have hg := controlled_gcd + unfold normalizeRat + control +lemma controlled_ratCross : Controlled ratCross := by unfold ratCross; control +lemma controlled_ratAdd : Controlled ratAdd := by + have hg := controlled_normalizeRat + unfold ratAdd + control +lemma controlled_ratMul : Controlled ratMul := by + have hg := controlled_normalizeRat + unfold ratMul + control +lemma controlled_ratDiv : Controlled ratDiv := by + have hg := controlled_normalizeRat + unfold ratDiv + control +lemma controlled_ratLess : Controlled ratLess := by unfold ratLess; control +lemma controlled_ratMinOne : Controlled ratMinOne := by unfold ratMinOne; control + +lemma iterateM_succ_last {A : Type*} (f : A → Option A) (k : ℕ) (x : A) : + iterateM f (k+1) x=(iterateM f k x).bind f := by + induction k generalizing x with + | zero => simp [iterateM] + | succ k ih => + simp only [iterateM,Option.bind_assoc] + congr 1 + funext y + exact ih y +open Expression +open scoped Classical +namespace Effect +lemma realizes_repeat_succ_last {n : ℕ} (O : IndependenceOracle n) {A B : Type*} {a} + (p : Effect a a) (ea : A → Value a) (eb : B → Value a) (k : ℕ) (x : Value a) + (t : DrawTree A) (f : A → DrawTree B) + (hp : Realizes O (repeatCode p) ea (k,x) t) + (hq : ∀ y,Realizes O p eb (ea y) (f y)) : + Realizes O (repeatCode p) eb (k+1,x) (t.bind f) := by + intro bank + rw [run_repeat,iterateM_succ_last,←run_repeat,hp,Option.bind_some,bankEval_bind] + cases ht : bankEval t bank with + | mk out rest => + cases out with + | none => rfl + | some y => exact hq y rest +lemma law_repeat_succ_last {n : ℕ} (O : IndependenceOracle n) {A B : Type*} {a} + (p : Effect a a) (ea : A → Value a) (eb : B → Value a) (k : ℕ) (x : Value a) + (t : DrawTree A) (f : A → DrawTree B) + (hp : RealizesLaw O (repeatCode p) ea (k,x) t) + (hq : ∀ y,RealizesLaw O p eb (ea y) (f y)) : + RealizesLaw O (repeatCode p) eb (k+1,x) (t.bind f) := by + classical + rcases hp with ⟨u,hu,hp⟩ + choose g hg hq using hq + exact ⟨u.bind g,hu.bind hg,realizes_repeat_succ_last O p ea eb k x u g hp hq⟩ + +def phaseRepeat {A : Type*} (f : ℕ → A → DrawTree (Option A)) : ℕ → A → DrawTree (Option A) + | 0,x => .leaf (some x) + | k+1,x => (phaseRepeat f k x).optionBind (f (k+1)) +lemma phaseRepeat_bind {A B : Type*} (f : ℕ → A → DrawTree (Option A)) (t : DrawTree B) + (g : B → A) (k : ℕ) : + (t.bind (fun x => phaseRepeat f (k+1) (g x)))= + (t.bind (fun x => phaseRepeat f k (g x))).optionBind (f (k+1)) := by + simp only [phaseRepeat,DrawTree.optionBind,DrawTree.bind_assoc] +lemma law_phaseRepeat {n : ℕ} (O : IndependenceOracle n) {A : Type*} {a} + (p : Effect a (Optional a)) (e : ℕ → A → Value a) + (f : ℕ → A → DrawTree (Option A)) + (hp : ∀ j x,RealizesLaw O p (optionEncode (e (j+1))) (e j x) (f (j+1) x)) + (k : ℕ) (x : A) : + RealizesLaw O (repeatCode (optionContinue p)) (optionEncode (e k)) + (k,optionEncode (e 0) (some x)) (phaseRepeat f k x) := by + induction k with + | zero => exact ⟨.leaf (some x),.leaf (some x),fun _ => rfl⟩ + | succ k ih => + apply law_repeat_succ_last O (optionContinue p) (optionEncode (e k)) _ k _ _ _ ih + intro y + exact law_optionContinue O p (e k) (e (k+1)) (f (k+1)) y (hp k) + +def hitStepCode {a} (step : Effect a a) (test : Expression a .bool) : Effect (.prod a .bool) (.prod a .bool) := + choose snd (map (precompose fst step) (both ident test)) (pure ident) +def hitFinish {a} : Expression (.prod a .bool) (Optional a) := + applyIf snd (constant (optionalValue a none)) (both (constant true) fst) +def hittingCode {a} (step : Effect a a) (test : Expression a .bool) : Effect (.prod .nat a) (Optional a) := + precompose (both fst (both snd (constant false))) (map (repeatCode (hitStepCode step test)) hitFinish) + +abbrev SearchState (X : Type*) (P : X → Prop) := X ⊕ FiniteChain.Inside P +noncomputable def searchStep {X : Type*} (step : X → DrawTree X) (P : X → Prop) : + SearchState X P → DrawTree (SearchState X P) + | .inl x => (step x).map (fun y => if hy : P y then .inr ⟨y,hy⟩ else .inl y) + | .inr y => .leaf (.inr y) +def searchFinish {X : Type*} {P : X → Prop} : SearchState X P → Option (FiniteChain.Inside P) + | .inl _ => none + | .inr y => some y +def searchEncode {X : Type*} {P : X → Prop} {a} (e : X → Value a) : SearchState X P → Value (.prod a .bool) + | .inl x => (e x,false) + | .inr y => (e y.val,true) + +lemma searchRepeat_done {X : Type*} (step : X → DrawTree X) (P : X → Prop) (k : ℕ) (y : FiniteChain.Inside P) : + treeRepeat (searchStep step P) k (.inr y)=.leaf (.inr y) := by + induction k with + | zero => rfl + | succ k ih => exact ih +lemma searchRepeat_finish {X : Type*} [Fintype X] (step : X → DrawTree X) (P : X → Prop) (k : ℕ) (x : X) : + (treeRepeat (searchStep step P) k (.inl x)).map searchFinish=hittingTree step P k x := by + induction k generalizing x with + | zero => rfl + | succ k ih => + simp only [treeRepeat,searchStep,DrawTree.map_bind,DrawTree.bind_map,hittingTree] + congr 1 + funext y + by_cases hy : P y + · rw [dite_eq_left hy,searchRepeat_done,dite_eq_left hy]; rfl + · rw [dite_eq_right hy,ih,dite_eq_right hy] + +lemma law_hitStep {n : ℕ} (O : IndependenceOracle n) {X : Type*} {a} + (step : Effect a a) (test : Expression a .bool) (e : X → Value a) + (f : X → DrawTree X) (P : X → Prop) + (hs : ∀ x,RealizesLaw O step e (e x) (f x)) + (ht : ∀ x,run O test (e x)=some (decide (P x))) (u : SearchState X P) : + RealizesLaw O (hitStepCode step test) (searchEncode e) (searchEncode e u) (searchStep f P u) := by + unfold hitStepCode + cases u with + | inl x => + apply law_choose O _ _ _ _ _ _ false rfl + change RealizesLaw O (map (precompose fst step) (both ident test)) _ _ _ + apply law_map O _ _ e _ _ _ _ + · exact law_precompose O fst step _ _ _ _ rfl (hs x) + · intro y + rw [run_both,run_ident,Option.bind_some,ht] + by_cases hy : P y + · simp only [hy,dite_eq_left,decide_true,Option.map_some]; rfl + · simp only [hy,decide_false,Option.map_some]; rfl + | inr y => + apply law_choose O _ _ _ _ _ _ true rfl + change RealizesLaw O (pure ident) (searchEncode e) _ (.leaf (.inr y)) + exact (realizes_pure O ident (searchEncode e) _ (Sum.inr y) rfl).law + +lemma law_hitting {n : ℕ} (O : IndependenceOracle n) {X : Type*} [Fintype X] {a} + (step : Effect a a) (test : Expression a .bool) (e : X → Value a) + (f : X → DrawTree X) (P : X → Prop) + (hs : ∀ x,RealizesLaw O step e (e x) (f x)) + (ht : ∀ x,run O test (e x)=some (decide (P x))) (k : ℕ) (x : X) : + RealizesLaw O (hittingCode step test) (optionEncode (fun y : FiniteChain.Inside P => e y.val)) + (k,e x) (hittingTree f P k x) := by + unfold hittingCode + apply law_precompose O _ _ _ _ (k,searchEncode e (.inl x : SearchState X P)) _ rfl + rw [←searchRepeat_finish] + apply law_map O _ _ (searchEncode e) _ _ _ searchFinish + · exact law_repeat O _ _ _ (law_hitStep O step test e f P hs ht) k (.inl x) + · intro u + cases u <;> rfl +end Effect + +open Expression +namespace Expression + +def optionMapCode {a b} (p : Expression a b) : Expression (Optional a) (Optional b) := + applyIf fst (constant (optionalValue b none)) (both (constant true) (snd >>> p)) +lemma run_optionMapCode {n : ℕ} (O : IndependenceOracle n) {a b} (p : Expression a b) + (f : Value a → Value b) (hp : ∀ x,run O p x=some (f x)) (x : Option (Value a)) : + run O (optionMapCode p) (optionalValue a x)=some (optionalValue b (x.map f)) := by + cases x with + | none => rfl + | some x => + change ((run O p x).bind fun y => some (true,y))=_ + rw [hp]; rfl +end Expression +namespace Effect +lemma law_recode {n : ℕ} (O : IndependenceOracle n) {A : Type*} {a b c} + (p : Effect a b) (q : Expression b c) (ea : A → Value b) (eb : A → Value c) + (x : Value a) (t : DrawTree A) (hp : RealizesLaw O p ea x t) + (hq : ∀ y,run O q (ea y)=some (eb y)) : RealizesLaw O (map p q) eb x t := by + have hh := law_map O p q ea eb x t id hp hq + simpa only [DrawTree.map,id_eq,DrawTree.bind_leaf] using hh + +def withContext {a b c} (p : Effect (.prod c a) b) : Effect (.prod c a) (.prod c b) := + letIn p (pure (both (fst >>> fst) snd)) +lemma law_withContext {n : ℕ} (O : IndependenceOracle n) {A : Type*} {a b c} + (p : Effect (.prod c a) b) (e : A → Value b) (ctx : Value c) (x : Value a) + (t : DrawTree A) (hp : RealizesLaw O p e (ctx,x) t) : + RealizesLaw O (withContext p) (fun y => (ctx,e y)) (ctx,x) t := by + unfold withContext + rw [←DrawTree.bind_leaf t] + apply law_letIn O p _ e _ _ t DrawTree.leaf hp + intro y + exact (realizes_pure O _ _ _ y rfl).law + +lemma law_optionMap {n : ℕ} (O : IndependenceOracle n) {A B : Type*} {a b c} + (p : Effect a (Optional b)) (q : Expression b c) (ea : A → Value b) (eb : B → Value c) + (x : Value a) (t : DrawTree (Option A)) (f : A → B) + (hp : RealizesLaw O p (optionEncode ea) x t) + (hq : ∀ y,run O q (ea y)=some (eb (f y))) : + RealizesLaw O (map p (optionMapCode q)) (optionEncode eb) x (t.map (Option.map f)) := by + apply law_map O p _ (optionEncode ea) (optionEncode eb) x t _ hp + intro y + cases y with + | none => rfl + | some y => + change ((run O q (ea y)).bind fun z => some (true,z))=_ + rw [hq]; rfl + +lemma law_optionRecode {n : ℕ} (O : IndependenceOracle n) {A : Type*} {a b c} + (p : Effect a (Optional b)) (q : Expression b c) (ea : A → Value b) (eb : A → Value c) + (x : Value a) (t : DrawTree (Option A)) + (hp : RealizesLaw O p (optionEncode ea) x t) + (hq : ∀ y,run O q (ea y)=some (eb y)) : + RealizesLaw O (map p (optionMapCode q)) (optionEncode eb) x t := by + apply law_recode O p _ (optionEncode ea) (optionEncode eb) x t hp + intro y + cases y with + | none => rfl + | some y => + change ((run O q (ea y)).bind fun z => some (true,z))=_ + rw [hq]; rfl +end Effect + +open scoped Classical +namespace Expression + +def defectPairsValue (S : Word×Word) : List (ℕ×ℕ) := + ((List.range S.1.length) ×ˢ (List.range S.1.length)).filter (fun pr => defectValue pr.1 pr.2 S) +def defectPairsCode : Expression StateData (.list NN) := + both (fst >>> wordLength >>> indexPairs) ident >>> filterWith defectCode +lemma run_defectPairsCode {n : ℕ} (O : IndependenceOracle n) (S : Word×Word) : + run O defectPairsCode S=some (defectPairsValue S) := by + simp only [defectPairsCode,run_compose,run_both,run_fst,run_ident,Option.bind_some] + rw [run_wordLength,Option.bind_some,run_indexPairs] + simp only [Option.bind_some,Option.map_some] + exact run_filterWith (a:=NN) (b:=StateData) O defectCode (fun pr S => defectValue pr.1 pr.2 S) + (fun pr S => run_defectCode O pr.1 pr.2 S) _ S + +def chainValue (S : Word×Word) : Bool := plainValue S || decide ((defectPairsValue S).length≠0) +def chainCode : Expression StateData .bool := + both plainCode (defectPairsCode >>> listLength >>> natEqZero >>> boolNot) >>> boolOr +lemma run_chainCode {n : ℕ} (O : IndependenceOracle n) (S : Word×Word) : + run O chainCode S=some (chainValue S) := by + simp only [chainCode,run_compose,run_both] + rw [run_plainCode,run_defectPairsCode] + simp only [Option.bind_some,run_compose,run_listLength,run_natEqZero,run_boolNot,Option.map_some] + rw [run_boolOr] + simp only [chainValue,decide_not] + +def multiplierValue (h : List (List (Word×Word))) (S : Word×Word) : ℚ := + if (defectPairsValue S).length=0 then 1 else + historyWeightValue ((defectPairsValue S).headD (0,0)).1 ((defectPairsValue S).headD (0,0)).2 h +def multiplierCode : Expression (.prod HistoryData StateData) NN := + letIn (snd >>> defectPairsCode) + (applyIf (snd >>> listLength >>> natEqZero) + (both (fst >>> fst) (both snd (constant (0,0)) >>> headD) >>> historyWeightCode) + (constant (1,1))) +lemma run_multiplierCode {n : ℕ} (O : IndependenceOracle n) (h : List (List (Word×Word))) (S : Word×Word) : + run O multiplierCode (h,S)=some (rationalPair (multiplierValue h S)) := by + simp only [multiplierCode,run_letIn,run_compose,run_snd,Option.bind_some] + rw [run_defectPairsCode] + simp only [Option.bind_some,run_applyIf,run_compose,run_snd,run_listLength,run_natEqZero] + by_cases he : (defectPairsValue S).length=0 + · simp only [he,decide_true,ite_true,multiplierValue,run_constant] + rfl + · simp only [he,decide_false,Option.bind_some,Bool.false_eq_true,ite_false,multiplierValue, + run_compose,run_both,run_fst,run_snd,run_constant,Option.map_some] + rw [run_headD] + simp only [Option.map_some,Option.bind_some] + exact run_historyWeightCode O _ _ h +end Expression + +lemma mem_defectPairsValue {n : ℕ} (S : Set (Fin n⊕Fin n)) (p r : ℕ) : + (p,r)∈Expression.defectPairsValue (stateEncode S) ↔ + ∃ (hp : p exact False.elim (hl hh) + | cons a l => simp + obtain ⟨hp,hr,hd⟩ := (mem_defectPairsValue S (l.headD (0,0)).1 (l.headD (0,0)).2).mp hm + have hex : ∃ p r,DefectState (pairedSlots n) p r S := ⟨_,_,hd⟩ + rw [ite_eq_right he,dite_eq_left hex,historyWeight_source h ⟨_,hp⟩ ⟨_,hr⟩] + have hh := hex.choose_spec.choose_spec.unique hd + exact congrArg₂ (rationalHistory (pairedSlots n) id h) hh.1.symm hh.2.symm + +namespace Expression + +@[simp] lemma run_append {n : ℕ} (O : IndependenceOracle n) (S : Word×Word) : + run O append S=some (S.1++S.2) := rfl + +def updateAt : Expression (.prod .nat (.prod .word (.prod .nat .bool))) .bool := + applyIf (both fst (snd >>> snd >>> fst) >>> natEqual) + (both (snd >>> fst) fst >>> wordGet) (snd >>> snd >>> snd) +def updateWord : Expression (.prod .word (.prod .nat .bool)) .word := + both (fst >>> wordLength >>> rangeCode) ident >>> mapWith updateAt >>> fromList +lemma run_updateAt {n : ℕ} (O : IndependenceOracle n) (i : ℕ) (w : Word) (j : ℕ) (b : Bool) : + run O updateAt (i,(w,(j,b)))=some (if i=j then b else w[i]?.getD false) := by + simp only [updateAt,run_applyIf,run_compose,run_both,run_fst,run_snd,Option.bind_some,Option.map_some] + rw [run_natEqual,run_wordGet] + by_cases h : i=j <;> simp [h] +lemma run_updateWord {n : ℕ} (O : IndependenceOracle n) (w : Word) (j : ℕ) (b : Bool) : + run O updateWord (w,(j,b))=some (w.set j b) := by + simp only [updateWord,run_compose,run_both,run_fst,run_ident,Option.bind_some] + rw [run_wordLength,Option.bind_some,run_rangeCode] + simp only [Option.bind_some,Option.map_some,run_compose] + rw [run_mapWith (a:=.nat) (b:=.bool) (c:=.prod .word (.prod .nat .bool)) O updateAt + (fun i z => if i=z.2.1 then z.2.2 else z.1[i]?.getD false) + (fun i z => run_updateAt O i z.1 z.2.1 z.2.2)] + simp only [Option.bind_some] + rw [run_fromList] + congr 1 + apply List.ext_getElem + · simp + · intro i hi hj + simp only [List.getElem_map,List.getElem_range,List.getElem_set] + rw [List.getElem?_eq_getElem (by simpa using hi)] + simp only [Option.getD_some] + by_cases he : i=j + · simp [he] + · simp [he,Ne.symm he] + +def splitWord : Expression (.prod .word .nat) StateData := + onLeft toList >>> splitAtCode >>> both (fst >>> fromList) (snd >>> fromList) +lemma run_splitWord {n : ℕ} (O : IndependenceOracle n) (w : Word) (k : ℕ) : + run O splitWord (w,k)=some (w.take k,w.drop k) := by + change ((run O (splitAtCode (a:=.bool)) (w,k)).bind (run O (both (fst >>> fromList) (snd >>> fromList))))=_ + rw [run_splitAtCode] + simp only [Option.bind_some,run_both,run_compose,run_fst,run_snd] + rw [run_fromList,run_fromList] + rfl + +def exchangeWord : Expression (.prod .word NN) .word := + letIn (both fst (both (snd >>> fst) (constant false)) >>> updateWord) + (both snd (both (fst >>> snd >>> snd) (constant true)) >>> updateWord) +lemma run_exchangeWord {n : ℕ} (O : IndependenceOracle n) (w : Word) (a b : ℕ) : + run O exchangeWord (w,(a,b))=some ((w.set a false).set b true) := by + simp only [exchangeWord,run_letIn,run_compose,run_both,run_fst,run_snd,run_constant, + Option.bind_some,Option.map_some] + rw [run_updateWord] + simp only [Option.bind_some] + exact run_updateWord O _ _ _ + +def exchangeSetCode : Expression (.prod StateData NN) StateData := + both (both (fst >>> append) snd >>> exchangeWord) (fst >>> fst >>> wordLength) >>> splitWord +lemma run_exchangeSetCode {n : ℕ} (O : IndependenceOracle n) (S : Word×Word) (a b : ℕ) : + run O exchangeSetCode (S,(a,b))=some + ((((S.1++S.2).set a false).set b true).take S.1.length, + (((S.1++S.2).set a false).set b true).drop S.1.length) := by + simp only [exchangeSetCode,run_compose,run_both,run_fst,run_snd,run_append,Option.bind_some,Option.map_some] + rw [run_exchangeWord,run_wordLength] + simp only [Option.bind_some,Option.map_some] + exact run_splitWord O _ _ +end Expression + +open scoped Classical +noncomputable def combinedEncode {n : ℕ} (S : Set (Fin n⊕Fin n)) : Word := (stateEncode S).1++(stateEncode S).2 +def position {n : ℕ} (i : Fin n⊕Fin n) : ℕ := (finSumFinEquiv i).val +lemma position_lt {n : ℕ} (i : Fin n⊕Fin n) : position i finSumFinEquiv.injective (Fin.ext h),fun h => congrArg position h⟩ +@[simp] lemma combinedEncode_length {n : ℕ} (S : Set (Fin n⊕Fin n)) : (combinedEncode S).length=n+n := by + simp [combinedEncode] +lemma combinedEncode_get {n : ℕ} (S : Set (Fin n⊕Fin n)) (i : Fin n⊕Fin n) : + (combinedEncode S)[position i]?.getD false=decide (i∈S) := by + cases i with + | inl i => + simp only [combinedEncode,position,finSumFinEquiv,Equiv.coe_fn_mk] + rw [List.getElem?_append_left (by simp)] + exact stateEncode_get_left S i + | inr i => simp [combinedEncode,stateEncode,position,finSumFinEquiv,i.isLt] + +lemma combinedEncode_update {n : ℕ} (S : Set (Fin n⊕Fin n)) (i : Fin n⊕Fin n) (b : Bool) : + (combinedEncode S).set (position i) b=combinedEncode (if b then insert i S else S\{i}) := by + apply List.ext_getElem + · simp + · intro k hk hk' + let j : Fin n⊕Fin n := finSumFinEquiv.symm ⟨k,by simpa using hk'⟩ + have hj : position j=k := by simp [position,j] + have ha := combinedEncode_get S j + have hb := combinedEncode_get (if b then insert i S else S\{i}) j + rw [hj,List.getElem?_eq_getElem (by simpa using hk),Option.getD_some] at ha + rw [hj,List.getElem?_eq_getElem hk',Option.getD_some] at hb + rw [List.getElem_set,ha,hb] + have he : position i=k ↔ i=j := by rw [←hj,position_inj] + simp only [he] + cases b <;> by_cases hij : i=j <;> simp [hij,eq_comm] + +lemma exchangeSetCode_source {n : ℕ} (O : IndependenceOracle n) (S : Set (Fin n⊕Fin n)) (a : ExchangeChoice S) : + run O Expression.exchangeSetCode (stateEncode S,(position a.1.val,position a.2.val))= + some (stateEncode (exchangedSet S a)) := by + rw [Expression.run_exchangeSetCode,stateEncode_left_length] + change some (((combinedEncode S).set (position a.1.val) false |>.set (position a.2.val) true).take n, + ((combinedEncode S).set (position a.1.val) false |>.set (position a.2.val) true).drop n)=_ + rw [combinedEncode_update] + simp only [Bool.false_eq_true,ite_false] + rw [combinedEncode_update] + simp only [ite_true] + change some ((combinedEncode (exchangedSet S a)).take n,(combinedEncode (exchangedSet S a)).drop n)=_ + have hh (x y : Word) : some ((x++y).take x.length,(x++y).drop x.length)=some (x,y) := by simp + simpa only [combinedEncode, stateEncode_left_length, Prod.eta] using hh (stateEncode (exchangedSet S a)).1 (stateEncode (exchangedSet S a)).2 + +open scoped Classical +namespace Expression +lemma historyWeightValue_nonneg (p r : ℕ) (h : List (List (Word×Word))) : + 0≤historyWeightValue p r h := by + have hf : ∀ (l : List (List (Word×Word))) (q : ℚ),0≤q → + 0≤l.foldl (fun q xs => weightUpdate p r xs q) q := by + intro l + induction l with + | nil => intro q hq; exact hq + | cons xs l ih => intro q hq; exact ih _ (weightUpdate_nonneg p r xs q hq) + exact hf h 4 (by norm_num) +lemma multiplierValue_nonneg (h : List (List (Word×Word))) (S : Word×Word) : + 0 ≤ multiplierValue h S := by + unfold multiplierValue + split_ifs + · norm_num + · exact historyWeightValue_nonneg _ _ h + +def rhoCode : Expression .nat NN := applyIf natEqZero + (letIn (both ident (constant 2) >>> mul) + (both (both snd (constant 1) >>> natSub) snd >>> normalizeRat)) + (constant (1,1)) +lemma rationalRho_nonneg (n : ℕ) : 0≤rationalRho n := by + cases n with + | zero => norm_num [rationalRho] + | succ n => + unfold rationalRho + have hh : (1:ℚ) ≤ 2*((n+1:ℕ):ℚ) := by push_cast; linarith [Nat.cast_nonneg (α:=ℚ) n] + exact sub_nonneg.mpr ((div_le_one (by positivity : (0:ℚ)<2*((n+1:ℕ):ℚ))).mpr hh) +lemma run_rhoCode {n : ℕ} (O : IndependenceOracle n) (m : ℕ) : + run O rhoCode m=some (rationalPair (rationalRho m)) := by + simp only [rhoCode,run_applyIf,run_natEqZero] + by_cases hm : m=0 + · subst m; simp only [decide_true,Option.bind_some,ite_true,run_constant] + norm_num [rationalPair,rationalRho] + · simp only [hm,decide_false,Option.bind_some,Bool.false_eq_true,ite_false] + change run O (both (both (snd (a:=.nat) (b:=.nat)) (constant 1) >>> natSub) snd >>> normalizeRat) (m,m*2)=_ + simp only [run_compose,run_both,run_snd,run_constant,Option.bind_some,Option.map_some] + rw [run_natSub] + simp only [Option.bind_some] + rw [run_normalizeRat_pair] + congr 2 + have hp : 1 ≤ m*2 := by omega + have hz : (m:ℚ)≠0 := by exact_mod_cast hm + rw [Nat.cast_sub hp,Nat.cast_mul,Nat.cast_ofNat,Nat.cast_one] + unfold rationalRho + field_simp + +abbrev WeightContext := DataType.prod NN HistoryData +abbrev WeightInput := DataType.prod WeightContext StateData + +def annealCode : Expression WeightInput NN := + both (both (snd >>> fst >>> wordLength >>> rhoCode) (fst >>> fst >>> snd) >>> ratPowCode) + (both (fst >>> fst >>> fst) snd >>> deficiencyCode) >>> ratPowCode +def weightCode : Expression WeightInput NN := + both (both (fst >>> snd) snd >>> multiplierCode) annealCode >>> ratMul +end Expression + +lemma rationalHistory_nonnegative {n : ℕ} (h : List (List (Set (Fin n⊕Fin n)))) (p r : (Fin n⊕Fin n)×(Fin n⊕Fin n)) : + 0≤rationalHistory (pairedSlots n) id h p r := by + have hf : ∀ (l : List (List (Set (Fin n⊕Fin n)))) + (w : ((Fin n⊕Fin n)×(Fin n⊕Fin n)) → ((Fin n⊕Fin n)×(Fin n⊕Fin n)) → ℚ), + (∀ p r,0≤w p r) → ∀ p r,0≤(l.foldl (fun w xs => rationalLearn (pairedSlots n) w xs) w) p r := by + intro l + induction l with + | nil => intro w hw p r; exact hw p r + | cons xs l ih => + intro w hw p r + apply ih + intro a b + dsimp only [rationalLearn] + split_ifs + · rw [rationalTypeRatio] + exact mul_nonneg (hw _ _) (div_nonneg (Nat.cast_nonneg _) (Nat.cast_nonneg _)) + · exact hw _ _ + exact hf h (fun _ _ => 4) (by intros; norm_num) p r + +lemma annealCode_source {n : ℕ} (M₁ M₂ : Matroid (Fin n)) (O : IndependenceOracle n) + (hO : ExactOracles M₁ M₂ O) (hE₁ : M₁.E=Set.univ) (hE₂ : M₂.E=Set.univ) + (r j : ℕ) (h : List (List (Set (Fin n⊕Fin n)))) (S : Set (Fin n⊕Fin n)) : + run O Expression.annealCode (((r,j),historyEncode h),stateEncode S)= + some (rationalPair ((rationalRho n^j)^(oracleDeficiency n r O S))) := by + simp only [Expression.annealCode,Expression.run_compose,Expression.run_both, + Expression.run_fst,Expression.run_snd,Option.bind_some,Option.map_some] + rw [Expression.run_wordLength,stateEncode_left_length] + simp only [Option.bind_some] + rw [Expression.run_rhoCode] + simp only [Option.bind_some] + rw [Expression.run_ratPowCode O _ (Expression.rationalRho_nonneg n)] + simp only [Option.bind_some] + rw [deficiencyCode_source M₁ M₂ O hO hE₁ hE₂ r _ _ (stateEncode_left_length S) (stateEncode_right_length S),stateEncode_repr] + simp only [Option.bind_some,Option.map_some] + exact Expression.run_ratPowCode O _ (pow_nonneg (Expression.rationalRho_nonneg n) _) _ + +lemma weightCode_source {n : ℕ} (M₁ M₂ : Matroid (Fin n)) (O : IndependenceOracle n) + (hO : ExactOracles M₁ M₂ O) (hE₁ : M₁.E=Set.univ) (hE₂ : M₂.E=Set.univ) + (r j : ℕ) (h : List (List (Set (Fin n⊕Fin n)))) (S : Set (Fin n⊕Fin n)) : + run O Expression.weightCode (((r,j),historyEncode h),stateEncode S)=some + (rationalPair (rationalMultiplier (pairedSlots n) (rationalHistory (pairedSlots n) id h) S* + (rationalRho n^j)^(oracleDeficiency n r O S))) := by + simp only [Expression.weightCode,Expression.run_compose,Expression.run_both, + Expression.run_fst,Expression.run_snd,Option.bind_some,Option.map_some] + rw [Expression.run_multiplierCode,multiplierValue_source,annealCode_source M₁ M₂ O hO hE₁ hE₂] + simp only [Option.bind_some,Option.map_some] + apply Expression.run_ratMul + · rw [←multiplierValue_source] + exact Expression.multiplierValue_nonneg _ _ + · exact pow_nonneg (pow_nonneg (Expression.rationalRho_nonneg n) j) _ + +open Expression +namespace Effect + +def bernoulliCode : Effect NN .bool := + letIn (precompose snd draw) (pure (both snd (fst >>> fst) >>> less)) +lemma bernoulliCode_source {n : ℕ} (O : IndependenceOracle n) (q : ℚ) : + Realizes O bernoulliCode id (rationalPair q) (DrawTree.bernoulli q) := by + have hd : q.den-1+1=q.den := by have hh := q.den_pos; omega + have hh : Realizes O draw Fin.val q.den (.draw (q.den-1) DrawTree.leaf) := by + simpa only [hd] using realizes_draw O (q.den-1) + have hp : Realizes O (precompose (snd (a:=.nat)) draw) Fin.val (rationalPair q) + (.draw (q.den-1) DrawTree.leaf) := + realizes_precompose (a:=NN) (b:=.nat) (c:=.nat) O snd draw Fin.val (rationalPair q) q.den _ rfl hh + change Realizes O (letIn (precompose snd draw) (pure (both snd (fst >>> fst) >>> less))) id + (rationalPair q) _ + have hr := realizes_letIn O (precompose (snd (a:=.nat)) draw) + (pure (both snd (fst >>> fst) >>> less)) Fin.val id (rationalPair q) + (.draw (q.den-1) DrawTree.leaf) (fun (i : Fin (q.den-1+1)) => .leaf (decide (i.val realizes_pure O _ id _ _ rfl) + exact hr +end Effect + +open Expression +open scoped Classical +namespace Expression +abbrev AcceptanceInput := DataType.prod WeightContext (.prod StateData StateData) +def acceptanceCode : Expression AcceptanceInput NN := + both (both fst (snd >>> snd) >>> weightCode) (both fst (snd >>> fst) >>> weightCode) >>> + ratDiv >>> ratMinOne +end Expression + +lemma acceptanceCode_source {n : ℕ} (M₁ M₂ : Matroid (Fin n)) (O : IndependenceOracle n) + (hO : ExactOracles M₁ M₂ O) (hE₁ : M₁.E=Set.univ) (hE₂ : M₂.E=Set.univ) + (r j : ℕ) (h : List (List (Set (Fin n⊕Fin n)))) (S T : ChainIndex (pairedSlots n)) : + run O acceptanceCode (((r,j),historyEncode h),(stateEncode S.val,stateEncode T.val))=some + (rationalPair (rationalAcceptance (pairedSlots n) (rationalHistory (pairedSlots n) id h) + (oracleAnneal n r O j) S T)) := by + have hn (U : Set (Fin n⊕Fin n)) : 0 ≤ rationalWeight (pairedSlots n) + (rationalHistory (pairedSlots n) id h) (oracleAnneal n r O j) U := by + unfold rationalWeight + apply mul_nonneg + · rw [←multiplierValue_source]; exact multiplierValue_nonneg _ _ + · exact pow_nonneg (pow_nonneg (rationalRho_nonneg n) j) _ + simp only [acceptanceCode,run_compose,run_both,run_fst,run_snd,Option.bind_some,Option.map_some] + rw [weightCode_source M₁ M₂ O hO hE₁ hE₂,weightCode_source M₁ M₂ O hO hE₁ hE₂] + simp only [Option.bind_some,Option.map_some] + change ((run O ratDiv (rationalPair (rationalWeight (pairedSlots n) (rationalHistory (pairedSlots n) id h) + (oracleAnneal n r O j) T.val),rationalPair (rationalWeight (pairedSlots n) (rationalHistory (pairedSlots n) id h) + (oracleAnneal n r O j) S.val))).bind (run O ratMinOne))=_ + rw [run_ratDiv O _ _ (hn _) (hn _),Option.bind_some] + exact run_ratMinOne O _ (div_nonneg (hn _) (hn _)) + +open scoped Classical +namespace Expression + +def memberPositions (w : Word) : List ℕ := (List.range w.length).filter (fun i => w[i]?.getD false) +def membersCode : Expression .word (.list .nat) := + both (wordLength >>> rangeCode) ident >>> filterWith (swap >>> wordGet) +lemma run_membersCode {n : ℕ} (O : IndependenceOracle n) (w : Word) : + run O membersCode w=some (memberPositions w) := by + simp only [membersCode,run_compose,run_both,run_ident,run_wordLength,Option.bind_some,Option.map_some] + rw [run_rangeCode] + simp only [Option.bind_some] + apply run_filterWith + intro i w + exact run_wordGet O w i +lemma memberPositions_nodup (w : Word) : (memberPositions w).Nodup := + List.nodup_range.filter _ +end Expression + +lemma mem_memberPositions_source {n : ℕ} (S : Set (Fin n⊕Fin n)) (i : Fin n⊕Fin n) : + position i∈Expression.memberPositions (combinedEncode S) ↔ i∈S := by + simp only [Expression.memberPositions,List.mem_filter,List.mem_range,combinedEncode_length, + combinedEncode_get,decide_eq_true_eq] + exact and_iff_right (finSumFinEquiv i).isLt + +noncomputable def memberPositionEquiv {n : ℕ} (S : Set (Fin n⊕Fin n)) : + {i : ℕ // i∈Expression.memberPositions (combinedEncode S)} ≃ S where + toFun i := by + have hi : i.val>> getDCode)) + +lemma uniformVia_size {A : Type*} [Fintype A] [Nonempty A] (m : ℕ) (e : Fin m ≃ A) + (h : m=Fintype.card A) (hc : m-1+1=m) : + (DrawTree.draw (m-1) (fun i => .leaf (e (Fin.cast hc i))))= + DrawTree.uniformVia A ((finCongr h.symm).trans e) := by + subst m + rfl + +lemma realizes_uniformList {n : ℕ} (O : IndependenceOracle n) {A : Type*} [Fintype A] [Nonempty A] + {a} (encode : A → Value a) (l : List (Value a)) (e : Fin l.length ≃ A) + (he : ∀ i,l.get i=encode (e i)) : + RealizesLaw O uniformList encode l (DrawTree.uniformChoice A) := by + have hlen : l.length=Fintype.card A := by simpa using Fintype.card_congr e + have hp : 0 .leaf (e (Fin.cast hc i))) + have ht : t=DrawTree.uniformVia A ee := uniformVia_size l.length e hlen hc + apply RealizesLaw.reindex (u:=t) + · apply Realizes.law + change Realizes O (letIn (precompose listLength draw) (pure _)) encode l + ((DrawTree.draw (l.length-1) DrawTree.leaf).bind (fun i => .leaf (e (Fin.cast hc i)))) + apply realizes_letIn O (a:=.list a) (b:=.nat) (c:=a) _ _ + (fun i : Fin (l.length-1+1) => i.val) encode l _ _ + · apply realizes_precompose O (a:=.list a) (b:=.nat) (c:=.nat) listLength draw + (fun i : Fin (l.length-1+1) => i.val) l l.length _ (run_listLength O l) + simpa only [hc] using realizes_draw O (l.length-1) + · intro i + apply realizes_pure + simp only [run_compose,run_both,run_fst,run_snd,run_constant,Option.bind_some,Option.map_some] + rw [run_getDCode] + rw [List.getD_eq_getElem (l:=l) (d:=zeroValue a) (n:=i.val) (by omega)] + exact congrArg some (he (Fin.cast hc i)) + · rw [ht] + exact (DrawTree.uniformVia_reindexed A ee).symm +end Effect + +open scoped Classical +open Expression +lemma combinedEncode_compl {n : ℕ} (S : Set (Fin n⊕Fin n)) : + combinedEncode Sᶜ=(combinedEncode S).map Bool.not := by + simp [combinedEncode,stateEncode,List.map_append,List.map_ofFn,Function.comp_def] + +def exchangePositions (S : Word×Word) : List (ℕ×ℕ) := + memberPositions (S.1++S.2) ×ˢ memberPositions ((S.1++S.2).map Bool.not) +def Expression.exchangePositionsCode : Expression StateData (.list NN) := + append >>> both membersCode (wordNot >>> membersCode) >>> productCode +lemma run_exchangePositionsCode {n : ℕ} (O : IndependenceOracle n) (S : Word×Word) : + run O exchangePositionsCode S=some (exchangePositions S) := by + simp only [exchangePositionsCode,run_compose,run_both,run_append,Option.bind_some,run_membersCode, + run_wordNot,Option.map_some] + exact run_productCode O (a:=.nat) (b:=.nat) _ _ +lemma exchangePositions_nodup (S : Word×Word) : (exchangePositions S).Nodup := by + exact List.Nodup.product (memberPositions_nodup _) (memberPositions_nodup _) + +lemma memberPositionEquiv_val {n : ℕ} (S : Set (Fin n⊕Fin n)) + (i : {i : ℕ // i∈memberPositions (combinedEncode S)}) : + position (memberPositionEquiv S i).val=i.val := by simp [memberPositionEquiv,position] + +noncomputable def exchangePositionEquiv {n : ℕ} (S : Set (Fin n⊕Fin n)) : + {p : ℕ×ℕ // p∈exchangePositions (stateEncode S)} ≃ ExchangeChoice S where + toFun p := + let hp : p.val∈memberPositions (combinedEncode S) ×ˢ memberPositions (combinedEncode Sᶜ) := by + rw [combinedEncode_compl] + exact p.property + (memberPositionEquiv S ⟨p.val.1,(List.mem_product.mp hp).1⟩, + memberPositionEquiv Sᶜ ⟨p.val.2,(List.mem_product.mp hp).2⟩) + invFun p := ⟨(position p.1.val,position p.2.val),by + change (position p.1.val, position p.2.val)∈ + memberPositions (combinedEncode S) ×ˢ memberPositions ((combinedEncode S).map Bool.not) + rw [←combinedEncode_compl] + exact List.mem_product.mpr ⟨(mem_memberPositions_source S _).mpr p.1.property, + (mem_memberPositions_source Sᶜ _).mpr p.2.property⟩⟩ + left_inv p := by apply Subtype.ext; simp [memberPositionEquiv_val] + right_inv p := by + apply Prod.ext <;> apply Subtype.ext <;> simp [memberPositionEquiv,position] + +noncomputable def exchangeListEquiv {n : ℕ} (S : Set (Fin n⊕Fin n)) : + Fin (exchangePositions (stateEncode S)).length ≃ ExchangeChoice S := + (exchangePositions_nodup (stateEncode S)).getEquiv.trans (exchangePositionEquiv S) +lemma exchangeListEquiv_val {n : ℕ} (S : Set (Fin n⊕Fin n)) + (i : Fin (exchangePositions (stateEncode S)).length) : + (position (exchangeListEquiv S i).1.val,position (exchangeListEquiv S i).2.val)= + (exchangePositions (stateEncode S)).get i := by + simp [exchangeListEquiv,exchangePositionEquiv,memberPositionEquiv_val,List.Nodup.getEquiv] + +namespace Effect + +def proposal : Effect StateData NN := precompose exchangePositionsCode uniformList +lemma proposal_source {n : ℕ} (O : IndependenceOracle n) (S : Set (Fin n⊕Fin n)) + [Nonempty (ExchangeChoice S)] : + RealizesLaw O proposal (fun a : ExchangeChoice S => (position a.1.val,position a.2.val)) + (stateEncode S) (DrawTree.uniformChoice (ExchangeChoice S)) := by + apply law_precompose O _ _ _ _ _ _ (run_exchangePositionsCode O _) + exact realizes_uniformList O _ _ (exchangeListEquiv S) (fun i => (exchangeListEquiv_val S i).symm) +end Effect + +section +open Expression +open scoped Classical +namespace Effect +abbrev OfferInput := DataType.prod WeightInput StateData + +def acceptancePrep : Expression OfferInput AcceptanceInput := + both (fst >>> fst) (both (fst >>> snd) snd) +def offerCore : Effect OfferInput StateData := + choose (snd >>> chainCode) (pure (fst >>> snd)) + (letIn (precompose (acceptancePrep >>> acceptanceCode) bernoulliCode) + (pure (applyIf snd (fst >>> fst >>> snd) (fst >>> snd)))) +def offerCode : Effect (.prod WeightInput NN) StateData := + precompose (both fst (both (fst >>> snd) snd >>> exchangeSetCode)) offerCore + +def activeStepCode : Effect WeightInput StateData := + letIn (precompose snd proposal) offerCode + +def stepCode : Effect WeightInput StateData := + letIn (precompose (constant (1,2)) bernoulliCode) + (choose snd (precompose fst activeStepCode) (pure (fst >>> snd))) +end Effect + +variable {n : ℕ} (M₁ M₂ : Matroid (Fin n)) (O : IndependenceOracle n) + (hO : ExactOracles M₁ M₂ O) (hE₁ : M₁.E=Set.univ) (hE₂ : M₂.E=Set.univ) + (r j : ℕ) (h : List (List (Set (Fin n⊕Fin n)))) +local notation "GS" => pairedSlots n +local notation "ctx" => (((r,j),historyEncode h) : Value WeightContext) +local notation "W" => rationalHistory GS id h +local notation "F" => oracleAnneal n r O j +open Effect +include M₁ M₂ hO hE₁ hE₂ + +lemma offerCore_source (S : ChainIndex GS) (U : Set (Fin n⊕Fin n)) : + RealizesLaw O offerCore (fun T : ChainIndex GS => stateEncode T.val) + ((ctx,stateEncode S.val),stateEncode U) + (if hu : ChainState GS U then + (DrawTree.bernoulli (rationalAcceptance GS W F S ⟨U,hu⟩)).map + (fun b => if b then ⟨U,hu⟩ else S) + else .leaf S) := by + have ht : run O ((snd (a:=WeightInput) (b:=StateData)) >>> chainCode) ((ctx,stateEncode S.val),stateEncode U)=some (decide (ChainState GS U)) := by + change run O chainCode (stateEncode U)=_ + rw [run_chainCode,chainValue_source] + unfold offerCore + apply law_choose O _ _ _ _ _ _ _ ht + by_cases hu : ChainState GS U + · simp only [hu,decide_true,ite_true,dite_eq_left] + change RealizesLaw O (letIn (precompose _ bernoulliCode) (pure _)) _ _ + ((DrawTree.bernoulli (rationalAcceptance GS W F S ⟨U,hu⟩)).bind (fun b => .leaf (if b then ⟨U,hu⟩ else S))) + apply law_letIn O (a:=OfferInput) (b:=.bool) (c:=StateData) _ _ id _ _ _ _ + · apply Realizes.law + apply realizes_precompose O _ _ _ _ (rationalPair (rationalAcceptance GS W F S ⟨U,hu⟩)) + · exact acceptanceCode_source M₁ M₂ O hO hE₁ hE₂ r j h S ⟨U,hu⟩ + · exact bernoulliCode_source O _ + · intro b + apply Realizes.law + apply realizes_pure + cases b <;> rfl + · simp only [hu,decide_false,Bool.false_eq_true,ite_false] + exact (realizes_pure O _ _ _ S rfl).law + +lemma offerCode_source (S : ChainIndex GS) (a : ExchangeChoice S.val) : + RealizesLaw O offerCode (fun T : ChainIndex GS => stateEncode T.val) + ((ctx,stateEncode S.val),(position a.1.val,position a.2.val)) + (rationalExchange GS W F S a) := by + unfold offerCode + apply law_precompose O _ _ _ _ ((ctx,stateEncode S.val),stateEncode (exchangedSet S.val a)) + · simp only [run_both,run_compose,run_fst,run_snd,Option.bind_some,Option.map_some] + rw [exchangeSetCode_source] + rfl + · exact offerCore_source M₁ M₂ O hO hE₁ hE₂ r j h S _ + +lemma activeStepCode_source (S : ChainIndex GS) [Nonempty (ExchangeChoice S.val)] : + RealizesLaw O activeStepCode (fun T : ChainIndex GS => stateEncode T.val) (ctx,stateEncode S.val) + ((DrawTree.uniformChoice (ExchangeChoice S.val)).bind (rationalExchange GS W F S)) := by + unfold activeStepCode + apply law_letIn O (a:=WeightInput) (b:=NN) (c:=StateData) _ _ + (fun a : ExchangeChoice S.val => (position a.1.val,position a.2.val)) _ _ _ _ + · exact law_precompose O snd proposal _ _ _ _ rfl (proposal_source O S.val) + · exact offerCode_source M₁ M₂ O hO hE₁ hE₂ r j h S + +lemma stepCode_source (hn : 0 stateEncode T.val) (ctx,stateEncode S.val) + (rationalMetropolis GS (pairedSlots_fresh n) (pairedSlots_ne_nil n hn) (pairedSlots_cover n) W F S) := by + let : Nonempty (ExchangeChoice S.val) := Fintype.card_pos_iff.mp (by + rw [exchangeChoice_card GS (pairedSlots_fresh n) (pairedSlots_cover n),pairedSlots_length]; positivity) + unfold stepCode rationalMetropolis + apply law_letIn O (a:=WeightInput) (b:=.bool) (c:=StateData) _ _ id _ _ _ _ + · apply Realizes.law + exact realizes_precompose O _ bernoulliCode id _ (rationalPair (1/2)) _ (by norm_num [run_constant,rationalPair]) (bernoulliCode_source O _) + · intro b + apply law_choose O _ _ _ _ _ _ b rfl + cases b with + | false => + exact law_precompose O fst activeStepCode _ _ _ _ rfl (activeStepCode_source M₁ M₂ O hO hE₁ hE₂ r j h S) + | true => exact (realizes_pure O _ _ _ S rfl).law +end + +section +open Expression +open scoped Classical + +lemma binaryValue_injective_length (x y : Word) (hlen : x.length=y.length) + (hv : binaryValue x=binaryValue y) : x=y := by + induction x generalizing y with + | nil => cases y <;> simp_all + | cons b x ih => + cases y with + | nil => simp at hlen + | cons c y => + simp only [List.length_cons,Nat.add_right_cancel_iff] at hlen + have hbc : b=c := by cases b <;> cases c <;> simp_all [binaryValue] <;> omega + subst c + have hxy : binaryValue x=binaryValue y := by cases b <;> simp_all [binaryValue] + rw [ih y hlen hxy] + +lemma binaryValue_replicate_false (k : ℕ) : binaryValue (List.replicate k false)=0 := by + induction k with + | zero => rfl + | succ k ih => simp [List.replicate_succ,binaryValue,ih] + +lemma padded_range (w : Word) (k : ℕ) (hk : w.length≤k) : + (List.range k).map (fun i => w[i]?.getD false)=w++List.replicate (k-w.length) false := by + apply List.ext_getElem + · simp; omega + · intro i hi hj + simp only [List.getElem_map,List.getElem_range] + by_cases h : i>> rangeCode) (snd >>> toBits) >>> mapWith (swap >>> wordGet) >>> fromList >>> reverse +lemma run_paddedBitsCode {n : ℕ} (O : IndependenceOracle n) (k v : ℕ) (hv : v<2^k) : + run O paddedBitsCode (k,v)=some (List.ofFn ((wordEquiv k).symm ⟨v,hv⟩)) := by + have hk : v.bits.length≤k := by rw [Nat.size_eq_bits_len]; exact Nat.size_le.mpr hv + have hr : (List.range k).map (fun i => v.bits[i]?.getD false)=v.bits++List.replicate (k-v.bits.length) false := padded_range _ _ hk + have he : ((List.range k).map (fun i => v.bits[i]?.getD false)).reverse= + List.ofFn ((wordEquiv k).symm ⟨v,hv⟩) := by + apply List.reverse_inj.mp + simp only [List.reverse_reverse] + apply binaryValue_injective_length + · simp + · rw [hr,binaryValue_append,binaryValue_replicate_false,binaryValue_bits,binaryValue_ofFn_reverse] + simp + simp only [paddedBitsCode,run_compose,run_both,run_fst,run_snd,Option.bind_some] + rw [run_rangeCode] + change ((run O (mapWith (c:=.word) (Expression.swap >>> wordGet)) (List.range k,v.bits)).bind fun l => + (run O fromList l).bind (run O reverse))=_ + rw [run_mapWith O (c:=.word) (Expression.swap >>> wordGet) (fun i w => w[i]?.getD false) (fun i w => run_wordGet O w i)] + simp only [Option.bind_some] + rw [run_fromList] + exact congrArg some he + +def plainDecodeCode : Expression NN StateData := paddedBitsCode >>> both ident wordNot +lemma plainDecodeCode_source {n : ℕ} (O : IndependenceOracle n) (v : Fin (2^n)) : + run O plainDecodeCode (n,v.val)=some (stateEncode (wordPlainEquiv n ((wordEquiv n).symm v)).val.val) := by + rw [plainDecodeCode,run_compose,run_paddedBitsCode O n v.val v.isLt,Option.bind_some,run_both,run_ident,Option.bind_some,run_wordNot] + simp only [Option.map_some] + congr 1 + change (List.ofFn _,(List.ofFn _).map Bool.not)=_ + unfold stateEncode wordPlainEquiv + simp only [] + apply Prod.ext + · apply List.ext_getElem <;> simp [transversal] + · apply List.ext_getElem <;> simp [transversal] +end Expression +namespace Effect +noncomputable local instance {n : ℕ} : Nonempty (PlainIndex (pairedSlots n)) := + plainIndex_nonempty _ (pairedSlots_fresh n) (pairedSlots_cover n) + +def plainCode : Effect .nat StateData := + letIn (precompose (both (constant 2) ident >>> powCode) draw) (pure plainDecodeCode) +lemma plainCode_source {n : ℕ} (O : IndependenceOracle n) : + RealizesLaw O plainCode (fun S : PlainIndex (pairedSlots n) => stateEncode S.val.val) n + (DrawTree.uniformVia _ (canonicalPlainEnumeration n)) := by + have hp : 0<2^n := by positivity + let hc : 2^n-1+1=2^n := by omega + let e : Fin (2^n) ≃ PlainIndex (pairedSlots n) := (wordEquiv n).symm.trans (wordPlainEquiv n) + let t : DrawTree (PlainIndex (pairedSlots n)) := .draw (2^n-1) (fun i => .leaf (e (Fin.cast hc i))) + have ht : t=DrawTree.uniformVia _ (canonicalPlainEnumeration n) := by + exact uniformVia_size (2^n) e (plainIndex_card n).symm hc + rw [←ht] + apply Realizes.law + change Realizes O (letIn (a:=.nat) (b:=.nat) (c:=StateData) _ _) _ n + ((DrawTree.draw (2^n-1) DrawTree.leaf).bind (fun i => .leaf (e (Fin.cast hc i)))) + apply realizes_letIn O (a:=.nat) (b:=.nat) (c:=StateData) _ _ + (fun i : Fin (2^n-1+1) => i.val) _ n _ _ + · apply realizes_precompose O _ draw _ _ (2^n) + · change run O powCode (2,n)=_; exact run_powCode O 2 n + · simpa only [hc] using realizes_draw O (2^n-1) + · intro i + apply realizes_pure + exact plainDecodeCode_source O (Fin.cast hc i) + +def storedStepPrep : Expression WeightInput WeightInput := + both (both (fst >>> fst) (both (fst >>> snd) (fst >>> fst >>> snd) >>> takeCode)) snd + +def storedStepCode : Effect WeightInput StateData := precompose storedStepPrep stepCode + +def traceCode : Effect (.prod .nat WeightInput) (Optional StateData) := + map (hittingCode (withContext storedStepCode) (snd >>> Expression.plainCode)) (optionMapCode snd) +end Effect + +lemma rationalHistory_map {X : Type*} {n : ℕ} (f : X → List (Set (Fin n⊕Fin n))) (h : List X) : + rationalHistory (pairedSlots n) id (h.map f)=rationalHistory (pairedSlots n) f h := by + simp only [rationalHistory,List.foldl_map,id_eq] +lemma historyEncode_take {n : ℕ} (h : List (List (Set (Fin n⊕Fin n)))) (j : ℕ) : + (historyEncode h).take j=historyEncode (h.take j) := by simp only [historyEncode,List.map_take] + +variable {n : ℕ} (M₁ M₂ : Matroid (Fin n)) (O : IndependenceOracle n) + (hO : ExactOracles M₁ M₂ O) (hE₁ : M₁.E=Set.univ) (hE₂ : M₂.E=Set.univ) + (r N : ℕ) (h : List (PhaseSample n N)) (j : ℕ) (hn : 0 pairedSlots n +local notation "ctx" => (((r,j),historyEncode (h.map (observedSets n N))) : Value WeightContext) +open Effect +include M₁ M₂ hO hE₁ hE₂ + +lemma storedStepCode_source (S : ChainIndex GS) : + RealizesLaw O storedStepCode (fun T : ChainIndex GS => stateEncode T.val) (ctx,stateEncode S.val) + (canonicalStepTree n hn r O N h j S) := by + unfold storedStepCode + apply law_precompose O storedStepPrep stepCode _ _ + (((r,j),historyEncode ((h.map (observedSets n N)).take j)),stateEncode S.val) + · simp only [storedStepPrep,run_both,run_compose,run_fst,run_snd,Option.bind_some,Option.map_some] + rw [run_takeCode,historyEncode_take]; rfl + · have hp := stepCode_source M₁ M₂ O hO hE₁ hE₂ r j + ((h.map (observedSets n N)).take j) hn S + have he : rationalHistory GS id ((h.map (observedSets n N)).take j)=rationalStored n N h j := by + rw [←List.map_take,rationalHistory_map]; rfl + rw [he] at hp + exact hp.reindex (canonicalMetropolis_reindexed n hn _ _ S) + +lemma traceCode_source (cap : ℕ) (S : PlainIndex GS) : + RealizesLaw O traceCode (optionEncode (fun T : PlainIndex GS => stateEncode T.val.val)) + (cap+1,(ctx,stateEncode S.val.val)) (canonicalTraceTree n hn r O N h j cap S) := by + unfold traceCode canonicalTraceTree + apply law_optionRecode O _ snd + (fun y : PlainIndex GS => (ctx,stateEncode y.val.val)) _ _ _ + · exact law_hitting O (withContext storedStepCode) (snd >>> Expression.plainCode) + (fun T : ChainIndex GS => (ctx,stateEncode T.val)) (canonicalStepTree n hn r O N h j) + (plainPredicate GS) + (fun T => law_withContext O storedStepCode _ ctx _ _ + (storedStepCode_source M₁ M₂ O hO hE₁ hE₂ r N h j hn T)) + (fun T => plainCode_source O T.val) (cap+1) S.val + · intro T; rfl +end + +section +open Expression +namespace Effect + +def withOptionContext {a b c} (p : Effect (.prod c a) (Optional b)) : Effect (.prod c a) (Optional (.prod c b)) := + letIn p (pure (applyIf (snd >>> fst) (constant (optionalValue (.prod c b) none)) + (both (constant true) (both (fst >>> fst) (snd >>> snd))))) +lemma law_withOptionContext {n : ℕ} (O : IndependenceOracle n) {A : Type*} {a b c} + (p : Effect (.prod c a) (Optional b)) (e : A → Value b) (ctx : Value c) (x : Value a) + (t : DrawTree (Option A)) (hp : RealizesLaw O p (optionEncode e) (ctx,x) t) : + RealizesLaw O (withOptionContext p) (optionEncode (fun y => (ctx,e y))) (ctx,x) t := by + unfold withOptionContext + rw [←DrawTree.bind_leaf t] + apply law_letIn O p _ (optionEncode e) _ _ t DrawTree.leaf hp + intro y + apply Realizes.law + apply realizes_pure + cases y <;> rfl +end Effect + +open Expression +open scoped Classical +abbrev RestartContext : DataType := .prod (.prod .nat HistoryData) (.prod .nat .nat) +abbrev RestartState : DataType := .prod (.prod RestartContext .nat) StateData +abbrev RestartInput : DataType := .prod .nat (.prod .nat RestartContext) +namespace Effect + +def traceAtPrep : Expression RestartState (.prod .nat WeightInput) := + both (fst >>> fst >>> snd >>> fst >>> (both ident (constant 1) >>> add)) + (both (both (both (fst >>> fst >>> fst >>> fst) (fst >>> snd)) + (fst >>> fst >>> fst >>> snd)) snd) +def traceAtCode : Effect RestartState (Optional StateData) := precompose traceAtPrep traceCode + +def restartTickPrep : Expression RestartState (.prod .nat RestartState) := + both (fst >>> fst >>> snd >>> snd) + (both (both (fst >>> fst) (fst >>> snd >>> (both ident (constant 1) >>> add))) snd) +def restartTick : Effect RestartState (Optional RestartState) := + precompose restartTickPrep (iterateCode (withOptionContext traceAtCode)) + +def restartPrep : Expression (.prod RestartInput StateData) (.prod .nat (Optional RestartState)) := + both (fst >>> snd >>> fst) (both (constant true) + (both (both (fst >>> snd >>> snd) (constant 0)) snd)) +def restartCode : Effect RestartInput (Optional StateData) := + map (letIn (precompose fst plainCode) + (precompose restartPrep (repeatCode (optionContinue restartTick)))) (optionMapCode snd) +end Effect +section Correct +variable {n : ℕ} (M₁ M₂ : Matroid (Fin n)) (O : IndependenceOracle n) + (hO : ExactOracles M₁ M₂ O) (hE₁ : M₁.E=Set.univ) (hE₂ : M₂.E=Set.univ) + (r N L : ℕ) (h : List (PhaseSample n N)) (hn : 0 pairedSlots n +local notation "tau" => 20*n^4*(n*(L+1)+2) +local notation "ctx" => (((r,historyEncode (h.map (observedSets n N))),(cap,tau)) : Value RestartContext) +local notation "enc" => (fun j (x : PlainIndex GS) => ((ctx,j),stateEncode (Subtype.val (Subtype.val x)))) +open Effect +include M₁ M₂ hO hE₁ hE₂ +lemma traceAtCode_source (j : ℕ) (x : PlainIndex GS) : + RealizesLaw O traceAtCode (optionEncode (fun y : PlainIndex GS => stateEncode y.val.val)) + (enc j x) (canonicalTraceTree n hn r O N h j cap x) := by + apply law_precompose O traceAtPrep traceCode _ _ _ _ + · rfl + · exact traceCode_source M₁ M₂ O hO hE₁ hE₂ r N h j hn cap x +lemma restartTick_source (j : ℕ) (x : PlainIndex GS) : + RealizesLaw O restartTick (optionEncode (enc (j+1))) (enc j x) + (DrawTree.iterate (canonicalTraceTree n hn r O N h (j+1) cap) tau x) := by + apply law_precompose O restartTickPrep _ _ _ _ _ + · rfl + · apply law_iterate O (withOptionContext traceAtCode) (enc (j+1)) _ _ tau x + intro y + apply law_withOptionContext + exact traceAtCode_source M₁ M₂ O hO hE₁ hE₂ r N L h hn cap (j+1) y +end Correct + +open Effect +lemma canonicalRestart_phaseRepeat {n : ℕ} (hn : 0 phaseRepeat (fun j => DrawTree.iterate (canonicalTraceTree n hn r O N h j cap) + (20*n^4*(n*(L+1)+2))) k x)) := by + let := plainIndex_nonempty (pairedSlots n) (pairedSlots_fresh n) (pairedSlots_cover n) + induction k with + | zero => rfl + | succ k ih => rw [canonicalRestartTree,ih,Effect.phaseRepeat_bind] + +variable {n : ℕ} (M₁ M₂ : Matroid (Fin n)) (O : IndependenceOracle n) + (hO : ExactOracles M₁ M₂ O) (hE₁ : M₁.E=Set.univ) (hE₂ : M₂.E=Set.univ) + (r N L : ℕ) (h : List (PhaseSample n N)) (hn : 0 pairedSlots n +local notation "tau" => 20*n^4*(n*(L+1)+2) +local notation "ctx" => (((r,historyEncode (h.map (observedSets n N))),(cap,tau)) : Value RestartContext) +local notation "enc" => (fun j (x : PlainIndex GS) => ((ctx,j),stateEncode (Subtype.val (Subtype.val x)))) +open Effect +include M₁ M₂ hO hE₁ hE₂ +lemma restartCode_source : + RealizesLaw O restartCode (optionEncode (fun x : PlainIndex GS => stateEncode x.val.val)) + (n,(k,ctx)) (canonicalRestartTree n hn r O N L h cap k) := by + rw [canonicalRestart_phaseRepeat] + unfold restartCode + apply law_optionRecode O _ snd (enc k) _ _ _ + · apply law_letIn O _ _ (fun x : PlainIndex GS => stateEncode x.val.val) _ _ _ _ + · exact law_precompose O fst plainCode _ _ n _ rfl (Effect.plainCode_source O) + · intro x + apply law_precompose O restartPrep _ _ _ _ _ + · rfl + · exact law_phaseRepeat O restartTick enc _ + (restartTick_source M₁ M₂ O hO hE₁ hE₂ r N L h hn cap) k x + · intro x; rfl +end + +open Expression +open scoped Classical +namespace Expression + +def allRange {a} (p : Expression (.prod .nat a) .bool) : Expression (.prod .nat a) .bool := + both (fst >>> rangeCode) snd >>> mapWith p >>> listAll +lemma run_allRange {n : ℕ} (O : IndependenceOracle n) {a} (p : Expression (.prod .nat a) .bool) + (f : ℕ → Value a → Bool) (hp : ∀ i x,run O p (i,x)=some (f i x)) (m : ℕ) (x : Value a) : + run O (allRange p) (m,x)=some (decide (∀ i < m,f i x=true)) := by + simp only [allRange,run_compose,run_both,run_fst,run_snd,Option.bind_some,Option.map_some] + rw [run_rangeCode] + simp only [Option.bind_some,run_compose] + rw [run_mapWith O p f hp,Option.bind_some,run_listAll] + congr 1 + apply Bool.eq_iff_iff.mpr + simp +end Expression +lemma rationalPair_pos {q : ℚ} (hq : 0 ≤ q) : 0 < (rationalPair q).1 ↔ 0 < q := by + have hd : (0:ℚ) < (rationalPair q).2 := by exact_mod_cast rationalPair_den q + conv_rhs => rw [←rationalPair_value hq] + rw [div_pos_iff_of_pos_right hd] + exact_mod_cast (Iff.rfl : 0 < (rationalPair q).1 ↔ 0 < (rationalPair q).1) +namespace Expression + +def pairPositiveCode : Expression (.prod HistoryData NN) .bool := + historyWeightCode >>> fst >>> natEqZero >>> boolNot +lemma run_pairPositiveCode {n : ℕ} (O : IndependenceOracle n) (h : List (List (Word×Word))) (p q : ℕ) : + run O pairPositiveCode (h,(p,q))=some (decide (0 < historyWeightValue p q h)) := by + simp only [pairPositiveCode,run_compose] + rw [run_historyWeightCode] + simp only [Option.bind_some,run_compose,run_fst] + rw [run_natEqZero] + simp only [Option.bind_some,run_boolNot] + congr 1 + apply Bool.eq_iff_iff.mpr + simp only [Bool.not_eq_true',decide_eq_false_iff_not,decide_eq_true_eq] + exact (Nat.pos_iff_ne_zero.symm).trans (rationalPair_pos (historyWeightValue_nonneg p q h)) + +def slotRowCode : Expression (.prod .nat (.prod .nat HistoryData)) .bool := + both (snd >>> fst) (both fst (snd >>> snd)) >>> + allRange (both (snd >>> snd) (both (snd >>> fst) fst) >>> pairPositiveCode) +def slotsPositiveCode : Expression (.prod .nat HistoryData) .bool := + both fst ident >>> allRange slotRowCode +def prefixPositiveCode : Expression (.prod .nat (.prod .nat HistoryData)) .bool := + both (snd >>> fst) (both (snd >>> snd) fst >>> takeCode) >>> slotsPositiveCode +def historyPositiveCode : Expression (.prod .nat HistoryData) .bool := + both (snd >>> listLength >>> (both ident (constant 1) >>> add)) ident >>> allRange prefixPositiveCode + +lemma run_slotRowCode {n : ℕ} (O : IndependenceOracle n) (p m : ℕ) (h : List (List (Word×Word))) : + run O slotRowCode (p,(m,h))=some (decide (∀ q < m,0 < historyWeightValue p q h)) := by + change run O (allRange (a:=.prod .nat HistoryData) _) (m,(p,h))=_ + rw [run_allRange (a:=.prod .nat HistoryData) O _ (fun q u => decide (0 < historyWeightValue u.1 q u.2))] + · simp + · intro q u; exact run_pairPositiveCode O u.2 u.1 q +lemma run_slotsPositiveCode {n : ℕ} (O : IndependenceOracle n) (m : ℕ) (h : List (List (Word×Word))) : + run O slotsPositiveCode (m,h)=some (decide (∀ p < m,∀ q < m,0 < historyWeightValue p q h)) := by + change run O (allRange slotRowCode) (m,(m,h))=_ + rw [run_allRange (a:=.prod .nat HistoryData) O _ (fun p u => decide (∀ q < u.1,0 < historyWeightValue p q u.2)) + (fun p u => run_slotRowCode O p u.1 u.2)] + simp +lemma run_prefixPositiveCode {n : ℕ} (O : IndependenceOracle n) (j m : ℕ) (h : List (List (Word×Word))) : + run O prefixPositiveCode (j,(m,h))=some (decide (∀ p < m,∀ q < m,0 < historyWeightValue p q (h.take j))) := by + simp only [prefixPositiveCode,run_compose,run_both,run_fst,run_snd,Option.bind_some,Option.map_some] + rw [run_takeCode] + exact run_slotsPositiveCode O m (h.take j) +lemma run_historyPositiveCode {n : ℕ} (O : IndependenceOracle n) (m : ℕ) (h : List (List (Word×Word))) : + run O historyPositiveCode (m,h)=some (decide (∀ j ≤ h.length,∀ p < m,∀ q < m,0 < historyWeightValue p q (h.take j))) := by + simp only [historyPositiveCode,run_compose,run_both,run_snd,run_ident,run_constant,Option.bind_some,Option.map_some] + rw [run_listLength] + change run O (allRange prefixPositiveCode) (h.length+1,(m,h))=_ + rw [run_allRange (a:=.prod .nat HistoryData) O _ (fun j u => decide (∀ p < u.1,∀ q < u.1,0 < historyWeightValue p q (u.2.take j))) + (fun j u => run_prefixPositiveCode O j u.1 u.2)] + simp only [decide_eq_true_eq,Nat.lt_add_one_iff] +end Expression + +lemma rationalHistory_inactive {Γ X : Type*} [DecidableEq Γ] (gs : List (Γ×Γ)) (s : X → List (Set Γ)) + (h : List X) (p q : Γ×Γ) (hp : ¬(p∈gs ∧ q∈gs ∧ p≠q)) : rationalHistory gs s h p q=4 := by + have hh : ∀ (l : List X) (w : (Γ×Γ) → (Γ×Γ) → ℚ), + (l.foldl (fun w x => rationalLearn gs w (s x)) w) p q=w p q := by + intro l + induction l with + | nil => intro w; rfl + | cons x l ih => intro w; rw [List.foldl_cons,ih]; simp [rationalLearn,hp] + exact hh h _ +lemma rationalHistoryPositive_slots {n N : ℕ} (h : List (PhaseSample n N)) : + rationalHistoryPositive n N h ↔ ∀ j ≤ h.length,∀ p q : Fin n,0 < rationalStored n N h j (slotPair p) (slotPair q) := by + constructor + · intro hh j hj p q; exact hh j hj _ _ + · intro hh j hj p q + by_cases hpq : p∈pairedSlots n ∧ q∈pairedSlots n ∧ p≠q + · obtain ⟨a,ha,rfl⟩ := List.mem_map.mp hpq.1 + obtain ⟨b,hb,rfl⟩ := List.mem_map.mp hpq.2.1 + exact hh j hj a b + · change 0 < rationalHistory _ _ _ p q + have hz := rationalHistory_inactive (pairedSlots n) (observedSets n N) (h.take j) p q hpq + rw [hz]; norm_num +lemma historyPositiveCode_source {n N : ℕ} (O : IndependenceOracle n) (h : List (PhaseSample n N)) : + run O Expression.historyPositiveCode (n,historyEncode (h.map (observedSets n N)))= + some (decide (rationalHistoryPositive n N h)) := by + rw [Expression.run_historyPositiveCode] + congr 1 + apply Bool.eq_iff_iff.mpr + simp only [decide_eq_true_eq] + rw [rationalHistoryPositive_slots] + have hlen : (historyEncode (h.map (observedSets n N))).length=h.length := by simp [historyEncode] + rw [hlen] + constructor + · intro hp j hj p q + have hh := hp j hj p.val p.isLt q.val q.isLt + rw [historyEncode_take,historyWeight_source,←List.map_take,rationalHistory_map] at hh + exact hh + · intro hp j hj p hp' q hq' + rw [historyEncode_take,historyWeight_source (p:=⟨p,hp'⟩) (r:=⟨q,hq'⟩),←List.map_take,rationalHistory_map] + exact hp j hj ⟨p,hp'⟩ ⟨q,hq'⟩ +end MachineCode + +namespace DrawTree +lemma Reindexed.lift_map {A B : Type*} (f : A → B) (t : DrawTree A) (u : DrawTree B) + (h : Reindexed (t.map f) u) : ∃ v, Reindexed t v ∧ v.map f=u := by + classical + induction t generalizing u with + | leaf a => + cases h + exact ⟨.leaf a,.leaf a,rfl⟩ + | draw w k ih => + cases h with + | draw _ _ l e hh => + choose v hv he using fun i => ih i (l (e i)) (hh i) + refine ⟨.draw w (fun i => v (e.symm i)),.draw w k _ e (by intro i; simpa using hv i),?_⟩ + simp only [DrawTree.map,DrawTree.bind] at he ⊢ + congr 1 + funext i + simpa using he (e.symm i) +end DrawTree +namespace MachineCode + +open Expression +namespace Effect +lemma law_unmap {n : ℕ} (O : IndependenceOracle n) {A B : Type*} {a b} + (p : Effect a b) (e : B → Value b) (x : Value a) (t : DrawTree A) (f : A → B) + (h : RealizesLaw O p e x (t.map f)) : RealizesLaw O p (e ∘ f) x t := by + rcases h with ⟨u,hu,hp⟩ + obtain ⟨v,hv,rfl⟩ := hu.lift_map f t u + refine ⟨v,hv,fun bank => ?_⟩ + simpa only [bankEval_map,Option.map_map,Function.comp_def] using hp bank + +def sampleTick {a} (p : Effect a a) : Effect (.prod (.list a) a) (.prod (.list a) a) := + letIn (precompose snd p) (pure (both (both (fst >>> snd) (fst >>> fst) >>> cons) snd)) +def sampleFinish {a} : Expression (.prod (.list a) a) (.list a) := + both (fst >>> listReverse) (both snd (constant []) >>> cons) >>> listAppend +def sampleCode {a} (p : Effect a a) : Effect (.prod .nat a) (.list a) := + precompose (both fst (both (constant []) snd)) (map (repeatCode (sampleTick p)) sampleFinish) + +def sampleTickTree {X : Type*} (f : X → DrawTree X) (s : List X × X) : DrawTree (List X × X) := + (f s.2).map (fun y => (s.2::s.1,y)) +lemma sampleRepeat_finish {X : Type*} (f : X → DrawTree X) (k : ℕ) (acc : List X) (x : X) : + (treeRepeat (sampleTickTree f) k (acc,x)).map (fun s => s.1.reverse++[s.2])= + (DrawTree.sample f k x).map (fun v => acc.reverse++v.toList) := by + induction k generalizing acc x with + | zero => rfl + | succ k ih => + simp only [treeRepeat,sampleTickTree,DrawTree.map_bind,DrawTree.bind_map,DrawTree.sample] + congr 1 + funext y + rw [ih] + change (DrawTree.sample f k y).map (fun v => (x::acc).reverse++v.toList)= + ((DrawTree.sample f k y).map (fun v => (x,v))).map (fun v : X × FiniteChain.Sample X k => acc.reverse++v.1::v.2.toList) + rw [DrawTree.map_map] + congr 1 + funext v + simp [List.reverse_cons,List.append_assoc] + +lemma law_sampleTick {n : ℕ} (O : IndependenceOracle n) {X : Type*} {a} + (p : Effect a a) (e : X → Value a) (f : X → DrawTree X) + (hp : ∀ x,RealizesLaw O p e (e x) (f x)) (s : List X × X) : + RealizesLaw O (sampleTick p) (fun u => (u.1.map e,e u.2)) (s.1.map e,e s.2) (sampleTickTree f s) := by + unfold sampleTick sampleTickTree DrawTree.map + apply law_letIn O (a:=.prod (.list a) a) (b:=a) (c:=.prod (.list a) a) _ _ e _ _ _ _ + · exact law_precompose O snd p _ _ _ _ rfl (hp s.2) + · intro y + exact (realizes_pure O _ _ _ (s.2::s.1,y) rfl).law + +lemma law_sample {n : ℕ} (O : IndependenceOracle n) {X : Type*} {a} + (p : Effect a a) (e : X → Value a) (f : X → DrawTree X) + (hp : ∀ x,RealizesLaw O p e (e x) (f x)) (k : ℕ) (x : X) : + RealizesLaw O (sampleCode p) (fun v => v.toList.map e) (k,e x) (DrawTree.sample f k x) := by + apply law_unmap O (a:=.prod .nat a) (b:=.list a) (sampleCode p) + (fun l : List X => l.map e) (k,e x) (DrawTree.sample f k x) (fun v => v.toList) + unfold sampleCode + apply law_precompose O _ _ _ _ (k,(([] : List (Value a)),e x)) _ rfl + have he := sampleRepeat_finish f k [] x + simp only [List.reverse_nil,List.nil_append] at he + rw [←he] + apply law_map O _ _ (fun u : List X × X => (u.1.map e,e u.2)) _ _ _ _ + · exact law_repeat O (sampleTick p) _ _ (law_sampleTick O p e f hp) k ([],x) + · intro u + simp only [sampleFinish,run_compose,run_both,run_fst,run_snd,run_constant,Option.bind_some,Option.map_some] + rw [run_listReverse] + change run O listAppend ((u.1.map e).reverse,[e u.2])=_ + rw [run_listAppend] + simp +end Effect + +section +open Expression +open scoped Classical +abbrev AlgorithmParams : DataType := .prod NN (.prod NN NN) +abbrev PhaseInput : DataType := .prod AlgorithmParams HistoryData +def params (n r N L : ℕ) : Value AlgorithmParams := + ((n,r),((N,L),(restartCap n L,20*n^4*(n*(L+1)+2)))) +namespace Expression +def mapEach {a b} (p : Expression a b) : Expression (.list a) (.list b) := + both ident (constant (b:=.unit) ()) >>> mapWith (fst >>> p) +lemma run_mapEach {n : ℕ} (O : IndependenceOracle n) {a b} (p : Expression a b) + (f : Value a → Value b) (hp : ∀ x,run O p x=some (f x)) (xs : List (Value a)) : + run O (mapEach p) xs=some (xs.map f) := by + change run O (mapWith (c:=.unit) (fst >>> p)) (xs,())=_ + exact run_mapWith (c:=.unit) O _ (fun x _ => f x) (fun x _ => hp x) xs () +end Expression +namespace Effect +def retainOption {a b} (p : Effect a (Optional b)) : Effect a (Optional (.prod a b)) := + letIn p (pure (applyIf (snd >>> fst) (constant (optionalValue (.prod a b) none)) + (both (constant true) (both fst (snd >>> snd))))) +lemma law_retainOption {n : ℕ} (O : IndependenceOracle n) {A : Type*} {a b} + (p : Effect a (Optional b)) (e : A → Value b) (x : Value a) + (t : DrawTree (Option A)) (hp : RealizesLaw O p (optionEncode e) x t) : + RealizesLaw O (retainOption p) (optionEncode (fun y => (x,e y))) x t := by + unfold retainOption + rw [←DrawTree.bind_leaf t] + apply law_letIn O p _ (optionEncode e) _ _ t DrawTree.leaf hp + intro y + apply Realizes.law + apply realizes_pure + cases y <;> rfl + +def phaseRestartPrep : Expression PhaseInput RestartInput := + both (fst >>> fst >>> fst) (both (snd >>> listLength) + (both (both (fst >>> fst >>> snd) snd) (fst >>> snd >>> snd))) +def phaseRestartCode : Effect PhaseInput (Optional StateData) := precompose phaseRestartPrep restartCode +def startCode : Effect PhaseInput (Optional StateData) := map phaseRestartCode (optionMapCode ident) +def phaseStepPrep : Expression (.prod PhaseInput StateData) WeightInput := + both (both (both (fst >>> fst >>> fst >>> snd) (fst >>> snd >>> listLength)) (fst >>> snd)) snd +def phaseStepCode : Effect (.prod PhaseInput StateData) StateData := precompose phaseStepPrep storedStepCode + +def phaseSamplePrep : Expression (.prod PhaseInput StateData) (.prod .nat (.prod PhaseInput StateData)) := + both (both (fst >>> fst >>> snd >>> fst >>> fst) (constant 1) >>> natSub) ident +def phaseSampleCode : Effect (.prod PhaseInput StateData) SampleData := + precompose phaseSamplePrep (map (sampleCode (withContext phaseStepCode)) (mapEach snd)) +def positiveTest : Expression PhaseInput .bool := both (fst >>> fst >>> fst) snd >>> historyPositiveCode +def phaseCode : Effect PhaseInput (Optional SampleData) := + choose positiveTest noneCode (optionBind (retainOption startCode) (someCode phaseSampleCode)) +def witnessCode : Effect PhaseInput (Optional StateData) := choose positiveTest noneCode phaseRestartCode +end Effect +variable {n : ℕ} (M₁ M₂ : Matroid (Fin n)) (O : IndependenceOracle n) + (hO : ExactOracles M₁ M₂ O) (hE₁ : M₁.E=Set.univ) (hE₂ : M₂.E=Set.univ) + (r N L : ℕ) (h : List (PhaseSample n N)) (hn : 0 pairedSlots n +local notation "ctx" => ((params n r N L,historyEncode (h.map (observedSets n N))) : Value PhaseInput) +open Effect +include M₁ M₂ hO hE₁ hE₂ +lemma phaseRestartCode_source : + RealizesLaw O phaseRestartCode (optionEncode (fun x : PlainIndex GS => stateEncode x.val.val)) ctx + (canonicalRestartTree n hn r O N L h (restartCap n L) h.length) := by + apply law_precompose O phaseRestartPrep restartCode _ ctx _ _ + · simp only [phaseRestartPrep,params,run_both,run_compose,run_fst,run_snd,Option.bind_some,Option.map_some] + rw [run_listLength] + simp only [historyEncode,List.length_map] + rfl + · exact restartCode_source M₁ M₂ O hO hE₁ hE₂ r N L h hn _ _ +lemma startCode_source : + RealizesLaw O startCode (optionEncode (fun x : ChainIndex GS => stateEncode x.val)) ctx + (canonicalStartTree n hn r O N L h) := by + apply law_optionMap O phaseRestartCode ident (fun x : PlainIndex GS => stateEncode x.val.val) _ ctx _ Subtype.val + · exact phaseRestartCode_source M₁ M₂ O hO hE₁ hE₂ r N L h hn + · intro x; rfl +lemma phaseStepCode_source (x : ChainIndex GS) : + RealizesLaw O phaseStepCode (fun y : ChainIndex GS => stateEncode y.val) (ctx,stateEncode x.val) + (canonicalStepTree n hn r O N h h.length x) := by + apply law_precompose O phaseStepPrep storedStepCode _ _ _ _ + · simp only [phaseStepPrep,params,run_both,run_compose,run_fst,run_snd,Option.bind_some,Option.map_some] + rw [run_listLength] + simp only [historyEncode,List.length_map] + rfl + · exact storedStepCode_source M₁ M₂ O hO hE₁ hE₂ r N h h.length hn x +lemma phaseSampleCode_source (x : ChainIndex GS) : + RealizesLaw O phaseSampleCode (fun v : PhaseSample n N => sampleEncode (observedSets n N v)) + (ctx,stateEncode x.val) (DrawTree.sample (canonicalStepTree n hn r O N h h.length) (N-1) x) := by + apply law_precompose O phaseSamplePrep _ _ _ _ _ + · simp only [phaseSamplePrep,params,run_both,run_compose,run_fst,run_snd,run_ident,run_constant,Option.bind_some,Option.map_some] + rw [run_natSub] + rfl + · apply law_recode O _ (mapEach snd) (fun v : PhaseSample n N => v.toList.map (fun y => (ctx,stateEncode y.val))) _ _ _ + · exact law_sample O (withContext phaseStepCode) (fun y : ChainIndex GS => (ctx,stateEncode y.val)) _ + (fun y => law_withContext O phaseStepCode _ ctx _ _ + (phaseStepCode_source M₁ M₂ O hO hE₁ hE₂ r N L h hn y)) (N-1) x + · intro v + rw [run_mapEach O snd Prod.snd (fun _ => rfl)] + simp only [sampleEncode,observedSets,List.map_map] + rfl +omit M₁ M₂ hO hE₁ hE₂ in +lemma positiveTest_source : run O positiveTest ctx=some (decide (rationalHistoryPositive n N h)) := + historyPositiveCode_source O h +lemma phaseCode_source : + RealizesLaw O phaseCode (optionEncode (fun v : PhaseSample n N => sampleEncode (observedSets n N v))) ctx + (canonicalPhaseTree n hn r O N L h) := by + unfold phaseCode canonicalPhaseTree + apply law_choose O positiveTest _ _ _ ctx _ (decide (rationalHistoryPositive n N h)) (positiveTest_source O r N L h) + by_cases hh : rationalHistoryPositive n N h + · simp only [hh,decide_true,ite_true] + apply law_optionBind O (retainOption startCode) (someCode phaseSampleCode) + (fun x : ChainIndex GS => (ctx,stateEncode x.val)) _ ctx _ _ + · exact law_retainOption O startCode _ ctx _ (startCode_source M₁ M₂ O hO hE₁ hE₂ r N L h hn) + · intro x + exact law_some O phaseSampleCode _ _ _ (phaseSampleCode_source M₁ M₂ O hO hE₁ hE₂ r N L h hn x) + · simp only [hh,decide_false,Bool.false_eq_true,ite_false] + exact law_none (a:=PhaseInput) O _ ctx +lemma witnessCode_source : + RealizesLaw O witnessCode (optionEncode (fun x : PlainIndex GS => stateEncode x.val.val)) ctx + (canonicalWitnessTree n hn r O N L h) := by + unfold witnessCode canonicalWitnessTree + apply law_choose O positiveTest _ _ _ ctx _ (decide (rationalHistoryPositive n N h)) (positiveTest_source O r N L h) + by_cases hh : rationalHistoryPositive n N h + · simp only [hh,decide_true,ite_true] + exact phaseRestartCode_source M₁ M₂ O hO hE₁ hE₂ r N L h hn + · simp only [hh,decide_false,Bool.false_eq_true,ite_false] + exact law_none (a:=PhaseInput) O _ ctx +end + +open Expression +namespace Expression +lemma run_mapWith_source {n : ℕ} (O : IndependenceOracle n) {X : Type*} {a b c} + (p : Expression (.prod a c) b) (e : X → Value a) (f : X → Value b) (ctx : Value c) + (hp : ∀ x,run O p (e x,ctx)=some (f x)) (xs : List X) : + run O (mapWith p) (xs.map e,ctx)=some (xs.map f) := by + have hs : ∀ x (acc : List (Value b)),run O (mapStep p) (e x,(acc,ctx))=some (f x::acc,ctx) := by + intro x acc + simp only [mapStep,run_both,run_compose,run_fst,run_snd,Option.bind_some,Option.map_some] + rw [hp] + rfl + have hf : ∀ (ys : List X) (acc : List (Value b)), + foldValue (run O (mapStep p)) (ys.map e) (acc,ctx)=some ((ys.map f).reverse++acc,ctx) := by + intro ys + induction ys with + | nil => intro acc; rfl + | cons x ys ih => intro acc; simp [foldValue,hs,ih,List.append_assoc] + simp only [mapWith,run_both,run_compose,run_fst,run_snd,run_constant,Option.bind_some,Option.map_some] + change (foldValue (run O (mapStep p)) (xs.map e) ([],ctx)).bind (fun z => run O listReverse z.1)=_ + rw [hf,Option.bind_some,run_listReverse] + simp + +def ratSumCode : Expression (.list NN) NN := both ident (constant (b:=NN) (0,1)) >>> fold ratAdd +def ratProductCode : Expression (.list NN) NN := both ident (constant (b:=NN) (1,1)) >>> fold ratMul +lemma run_ratSumCode {n : ℕ} (O : IndependenceOracle n) (xs : List ℚ) (hx : ∀ q∈xs,0≤q) : + run O ratSumCode (xs.map rationalPair)=some (rationalPair xs.sum) := by + have hf : ∀ (ys : List ℚ), (∀ q∈ys,0≤q) → ∀ q,0≤q → + foldValue (run O ratAdd) (ys.map rationalPair) (rationalPair q)=some (rationalPair (q+ys.sum)) := by + intro ys + induction ys with + | nil => intro hy q hq; simp [foldValue] + | cons y ys ih => + intro hy q hq + rw [List.map_cons,foldValue,run_ratAdd O y q (hy y (by simp)) hq,Option.bind_some] + rw [ih (fun z hz => hy z (by simp [hz])) (y+q) (add_nonneg (hy y (by simp)) hq)] + simp [add_left_comm,add_assoc] + change foldValue (run O ratAdd) (xs.map rationalPair) (rationalPair 0)=_ + simpa using hf xs hx 0 (le_refl 0) +lemma run_ratProductCode {n : ℕ} (O : IndependenceOracle n) (xs : List ℚ) (hx : ∀ q∈xs,0≤q) : + run O ratProductCode (xs.map rationalPair)=some (rationalPair xs.prod) := by + have hf : ∀ (ys : List ℚ), (∀ q∈ys,0≤q) → ∀ q,0≤q → + foldValue (run O ratMul) (ys.map rationalPair) (rationalPair q)=some (rationalPair (q*ys.prod)) := by + intro ys + induction ys with + | nil => intro hy q hq; simp [foldValue] + | cons y ys ih => + intro hy q hq + rw [List.map_cons,foldValue,run_ratMul O y q (hy y (by simp)) hq,Option.bind_some] + rw [ih (fun z hz => hy z (by simp [hz])) (y*q) (mul_nonneg (hy y (by simp)) hq)] + simp [mul_left_comm,mul_assoc] + change foldValue (run O ratMul) (xs.map rationalPair) (rationalPair 1)=_ + simpa using hf xs hx 1 (by norm_num) + +def natRatCode : Expression .nat NN := both ident (constant 1) >>> normalizeRat +lemma run_natRatCode {n : ℕ} (O : IndependenceOracle n) (k : ℕ) : + run O natRatCode k=some (rationalPair (k:ℚ)) := by + change run O normalizeRat (k,1)=_ + simpa using run_normalizeRat_pair O k 1 +end Expression + +lemma bits_length_add_max (a b : ℕ) : (a+b).bits.length≤ max a.bits.length b.bits.length+1 := by + simp only [Nat.size_eq_bits_len] + apply Nat.size_le.mpr + have ha := (Nat.lt_size_self a).trans_le (Nat.pow_le_pow_right (by decide : 1≤2) (Nat.le_max_left a.size b.size)) + have hb := (Nat.lt_size_self b).trans_le (Nat.pow_le_pow_right (by decide : 1≤2) (Nat.le_max_right a.size b.size)) + rw [pow_succ] + omega + +def pairHeight (p : ℕ × ℕ) : ℕ := max 1 (max p.1.bits.length p.2.bits.length) +lemma pairHeight_pos (p : ℕ × ℕ) : 1≤pairHeight p := Nat.le_max_left _ _ +lemma pairHeight_fst (p : ℕ × ℕ) : p.1.bits.length≤pairHeight p := (Nat.le_max_left _ _).trans (Nat.le_max_right _ _) +lemma pairHeight_snd (p : ℕ × ℕ) : p.2.bits.length≤pairHeight p := (Nat.le_max_right _ _).trans (Nat.le_max_right _ _) +lemma width_le_pairHeight (p : ℕ × ℕ) : width (a:=NN) p≤4*pairHeight p := by + obtain ⟨a,b⟩ := p + have h₀ := pairHeight_pos (a,b) + have h₁ := pairHeight_fst (a,b) + have h₂ := pairHeight_snd (a,b) + dsimp only [Prod.fst,Prod.snd] at h₁ h₂ + rw [width_pair (a:=.nat) (b:=.nat),width_nat,width_nat] + omega +lemma pairHeight_le_width (p : ℕ × ℕ) : pairHeight p≤width (a:=NN) p := by + obtain ⟨a,b⟩ := p + simp only [pairHeight,width_pair (a:=.nat) (b:=.nat),width_nat] + omega +lemma pairHeight_normalize (a b : ℕ) : pairHeight (normalizePair a b)≤pairHeight (a,b) := by + by_cases hb : b=0 + · subst b + simp [normalizePair,pairHeight] + · rw [normalizePair,ite_eq_right hb] + have h₁ := bits_length_mono (Nat.div_le_self a (Nat.gcd a b)) + have h₂ := bits_length_mono (Nat.div_le_self b (Nat.gcd a b)) + dsimp [pairHeight] + omega +lemma pairHeight_ratAdd_raw (a b c d : ℕ) : + pairHeight (normalizePair (a*d+c*b) (b*d))≤pairHeight (a,b)+pairHeight (c,d)+1 := by + apply (pairHeight_normalize _ _).trans + have h₁ := bits_length_mul a d + have h₂ := bits_length_mul c b + have h₃ := bits_length_mul b d + have h₄ := bits_length_add_max (a*d) (c*b) + have ha := pairHeight_fst (a,b) + have hb := pairHeight_snd (a,b) + have hc := pairHeight_fst (c,d) + have hd := pairHeight_snd (c,d) + dsimp only [pairHeight] at * + omega +lemma pairHeight_ratMul_raw (a b c d : ℕ) : + pairHeight (normalizePair (a*c) (b*d))≤pairHeight (a,b)+pairHeight (c,d) := by + apply (pairHeight_normalize _ _).trans + have h₁ := bits_length_mul a c + have h₂ := bits_length_mul b d + have ha := pairHeight_fst (a,b) + have hb := pairHeight_snd (a,b) + have hc := pairHeight_fst (c,d) + have hd := pairHeight_snd (c,d) + have hp := pairHeight_pos (a,b) + dsimp only [pairHeight] at * + omega +lemma run_ratAdd_height {n : ℕ} (O : IndependenceOracle n) (p q y : ℕ×ℕ) + (hy : run O ratAdd (p,q)=some y) : pairHeight y≤ pairHeight p+pairHeight q+1 := by + obtain ⟨a,b⟩ := p + obtain ⟨c,d⟩ := q + rw [run_ratAdd_raw] at hy + cases hy + exact pairHeight_ratAdd_raw _ _ _ _ +lemma run_ratMul_height {n : ℕ} (O : IndependenceOracle n) (p q y : ℕ×ℕ) + (hy : run O ratMul (p,q)=some y) : pairHeight y≤ pairHeight p+pairHeight q+1 := by + obtain ⟨a,b⟩ := p + obtain ⟨c,d⟩ := q + rw [run_ratMul_raw] at hy + cases hy + have hh := pairHeight_ratMul_raw a b c d + omega +lemma fold_pairHeight {n : ℕ} (O : IndependenceOracle n) (p : Expression (.prod NN NN) NN) + (hp : ∀ x z y,run O p (x,z)=some y → pairHeight y≤pairHeight x+pairHeight z+1) + (xs : List (ℕ×ℕ)) (z y : ℕ×ℕ) (hy : foldValue (run O p) xs z=some y) : + pairHeight y≤pairHeight z+width (a:=.list NN) xs := by + induction xs generalizing z with + | nil => cases hy; simp + | cons x xs ih => + rw [foldValue] at hy + cases he : run O p (x,z) with + | none => simp [he] at hy + | some w => + simp only [he,Option.bind_some] at hy + have hw := hp x z w he + have hh := ih w hy + have hx := pairHeight_le_width x + rw [width_cons (a:=NN)] + omega +lemma controlled_pairFold (p : Expression (.prod NN NN) NN) (hp : Controlled p) + (hg : ∀ {n : ℕ} (O : IndependenceOracle n) (x z y : ℕ×ℕ), + run O p (x,z)=some y → pairHeight y≤pairHeight x+pairHeight z+1) : Controlled (.fold p) := by + apply controlled_fold p hp (.mul (.constant 4) .input) + intro n O xs z pre post he y hy + have hh := fold_pairHeight O p (hg O) pre z y hy + have hb := width_le_pairHeight y + have hz := pairHeight_le_width z + have hpre : width (a:=.list NN) pre≤width (a:=.list NN) xs := by rw [he,width_list_append]; omega + simp only [SizePolynomial.eval,width_pair (a:=.list NN) (b:=NN)] + omega +lemma controlled_ratSum : Controlled ratSumCode := by + unfold ratSumCode + apply controlled_compose + · control + · exact controlled_pairFold ratAdd controlled_ratAdd run_ratAdd_height +lemma controlled_ratProduct : Controlled ratProductCode := by + unfold ratProductCode + apply controlled_compose + · control + · exact controlled_pairFold ratMul controlled_ratMul run_ratMul_height + +syntax "cc" : tactic +macro_rules +| `(tactic| cc) => `(tactic| + first + | assumption + | exact controlled_wordRange + | exact controlled_boolNot + | exact controlled_boolAnd + | exact controlled_boolOr + | exact controlled_natEqual + | exact controlled_natEqZero + | exact controlled_natSub + | exact controlled_natDiv + | exact controlled_natMod + | exact controlled_natDivRem + | exact controlled_swap + | exact controlled_listLength + | exact controlled_wordLength + | exact controlled_fromList + | exact controlled_listReverse + | exact controlled_listAppend + | exact controlled_productCode + | exact controlled_wordGet + | exact controlled_wordNot + | exact controlled_wordCount + | exact controlled_deficiency + | exact controlled_listAll + | exact controlled_splitAt + | exact controlled_take + | exact controlled_drop + | exact controlled_headD + | exact controlled_getD + | exact controlled_normalizeRat + | exact controlled_ratAdd + | exact controlled_ratMul + | exact controlled_ratDiv + | exact controlled_ratLess + | exact controlled_ratMinOne + | exact controlled_ratSum + | exact controlled_ratProduct + | apply controlled_mapWith <;> cc + | apply controlled_filterWith <;> cc + | apply controlled_onLeft <;> cc + | apply controlled_onRight <;> cc + | apply controlled_letIn <;> cc + | apply controlled_applyIf <;> cc + | apply controlled_compose <;> cc + | apply controlled_both <;> cc + | apply controlled_branch <;> cc + | exact controlled_atomic _ trivial) + +lemma controlled_boolXor : Controlled boolXor := by unfold boolXor; cc +lemma controlled_singleAt : Controlled singleAt := by unfold singleAt boolXor; cc +lemma controlled_fullAt : Controlled fullAt := by unfold fullAt; cc +lemma controlled_emptyAt : Controlled emptyAt := by unfold emptyAt; cc +lemma controlled_plainCode : Controlled plainCode := by + have hs := controlled_singleAt + unfold plainCode + cc +lemma controlled_defectAt : Controlled defectAt := by + have h₁ := controlled_singleAt + have h₂ := controlled_fullAt + have h₃ := controlled_emptyAt + unfold defectAt + cc +lemma controlled_defectCode : Controlled defectCode := by + have hd := controlled_defectAt + unfold defectCode + cc +lemma controlled_countWith {a b : DataType} (p : Expression (.prod a b) .bool) (hp : Controlled p) : + Controlled (countWith p) := by unfold countWith; cc +lemma controlled_countPlain : Controlled countPlainCode := by + have hp := controlled_plainCode + unfold countPlainCode + apply controlled_compose + · cc + · apply controlled_countWith; cc +lemma controlled_countDefect : Controlled countDefectCode := by + have hp := controlled_defectCode + unfold countDefectCode + apply controlled_countWith + cc +lemma controlled_learningRatio : Controlled learningRatioCode := by + have h₁ := controlled_countPlain + have h₂ := controlled_countDefect + unfold learningRatioCode + cc +lemma controlled_weightStep : Controlled weightStep := by + have h := controlled_learningRatio + unfold weightStep + cc +lemma polySafe_indexPairs : PolySafe indexPairs (fun S x => x≤S) := by + unfold indexPairs + exact polySafe_post _ _ _ (polySafe_both _ _ _ polySafe_rangeCode polySafe_rangeCode) controlled_productCode +lemma controlled_wordIndexPairs : Controlled (wordLength >>> indexPairs) := by + apply polySafe_controlled + apply polySafe_compose _ _ _ (fun S k => k≤S) + (polySafe_of_controlled _ controlled_wordLength _ .input (by intros; assumption)) polySafe_indexPairs + intro n O S x hx y hy + rw [run_wordLength] at hy + cases hy + exact hx +lemma controlled_defectPairs : Controlled defectPairsCode := by + have h := controlled_wordIndexPairs + have hd := controlled_defectCode + unfold defectPairsCode + cc +lemma controlled_chainCode : Controlled chainCode := by + have h₁ := controlled_plainCode + have h₂ := controlled_defectPairs + unfold chainCode + cc +lemma controlled_updateAt : Controlled updateAt := by unfold updateAt; cc +lemma controlled_updateWord : Controlled updateWord := by + have h := controlled_updateAt + unfold updateWord + cc +lemma controlled_splitWord : Controlled splitWord := by unfold splitWord; cc +lemma controlled_exchangeWord : Controlled exchangeWord := by + have h := controlled_updateWord + unfold exchangeWord + cc +lemma controlled_exchangeSet : Controlled exchangeSetCode := by + have h₁ := controlled_exchangeWord + have h₂ := controlled_splitWord + unfold exchangeSetCode + cc +lemma controlled_membersCode : Controlled membersCode := by unfold membersCode; cc +lemma controlled_exchangePositions : Controlled exchangePositionsCode := by + have h := controlled_membersCode + unfold exchangePositionsCode + cc + +lemma controlled_wordTake : Controlled wordTake := by unfold wordTake; cc +lemma controlled_wordDrop : Controlled wordDrop := by unfold wordDrop; cc +lemma controlled_clog : Controlled clogCode := by unfold clogCode; cc +lemma controlled_rejectStep : Controlled rejectStep := by + have h := controlled_wordTake + unfold rejectStep + cc +lemma fold_reject_width {n : ℕ} (O : IndependenceOracle n) (xs : List Word) + (v k : ℕ) (z : Bool×ℕ) (y : Value RejectState) + (hy : foldValue (run O rejectStep) xs ((v,k),z)=some y) : + y.1=(v,k) ∧ y.2.2.bits.length ≤ max z.2.bits.length v.bits.length := by + induction xs generalizing z with + | nil => cases hy; exact ⟨rfl,Nat.le_max_left _ _⟩ + | cons x xs ih => + rw [foldValue,run_rejectStep] at hy + simp only [Option.bind_some] at hy + split_ifs at hy with hh + · have hi := ih _ hy + refine ⟨hi.1,hi.2.trans ?_⟩ + have hb := bits_length_mono hh.le + dsimp only [Prod.snd] + exact max_le (hb.trans (Nat.le_max_right _ _)) (Nat.le_max_right _ _) + · exact ih z hy +lemma controlled_rejectFold : Controlled (.fold rejectStep) := by + apply controlled_fold rejectStep controlled_rejectStep (.mul (.constant 3) .input) + intro n O xs z pre post he y hy + obtain ⟨⟨v,k⟩,⟨b,u⟩⟩ := z + change ℕ at v k u + obtain ⟨⟨v',k'⟩,⟨b',u'⟩⟩ := y + change ℕ at v' k' u' + have hh := fold_reject_width O pre v k (b,u) ((v',k'),(b',u')) hy + dsimp only [Prod.fst,Prod.snd] at hh + rw [width_pair (a:=NN) (b:=Optional .nat),hh.1,width_pair (a:=.bool) (b:=.nat),width_bool,width_nat] + simp only [SizePolynomial.eval,width_pair (a:=.list .word) (b:=RejectState), + width_pair (a:=NN) (b:=Optional .nat),width_pair (a:=.bool) (b:=.nat), + width_pair (a:=.nat) (b:=.nat),width_nat,width_bool] at * + omega +lemma controlled_reject : Controlled rejectCode := by + have h := controlled_rejectFold + unfold rejectCode + cc +namespace Effect +lemma controlled_pure {a b : DataType} (p : Expression a b) (hp : Controlled p) : Controlled (pure p) := by + unfold pure; cc +lemma controlled_fail {a b : DataType} : Controlled (fail (a:=a) (b:=b)) := by unfold fail; cc +lemma controlled_bind {a b c : DataType} (p : Effect a b) (q : Effect b c) + (hp : Controlled p) (hq : Controlled q) : Controlled (bind p q) := by unfold bind; cc +lemma controlled_keep {a b : DataType} (p : Effect a b) (hp : Controlled p) : Controlled (keep p) := by + unfold keep; cc +lemma controlled_letIn {a b c : DataType} (p : Effect a b) (q : Effect (.prod a b) c) + (hp : Controlled p) (hq : Controlled q) : Controlled (letIn p q) := + controlled_bind _ _ (controlled_keep _ hp) hq +lemma controlled_draw : Controlled draw := by + have h₁ := controlled_reject + have h₂ := controlled_clog + unfold draw + cc +end Effect + +lemma controlled_optionMap {a b : DataType} (p : Expression a b) (hp : Controlled p) : Controlled (optionMapCode p) := by + unfold optionMapCode; cc +lemma controlled_mapEach {a b : DataType} (p : Expression a b) (hp : Controlled p) : Controlled (mapEach p) := by + unfold mapEach; cc +namespace Effect +lemma controlled_precompose {a b c : DataType} (p : Expression a b) (q : Effect b c) + (hp : Controlled p) (hq : Controlled q) : Controlled (precompose p q) := by + unfold precompose; cc +lemma controlled_map {a b c : DataType} (p : Effect a b) (q : Expression b c) + (hp : Controlled p) (hq : Controlled q) : Controlled (map p q) := + controlled_bind p (pure q) hp (controlled_pure q hq) +lemma controlled_choose {a b : DataType} (test : Expression a .bool) (p q : Effect a b) + (ht : Controlled test) (hp : Controlled p) (hq : Controlled q) : Controlled (choose test p q) := by + unfold choose; cc +lemma controlled_withContext {a b c : DataType} (p : Effect (.prod c a) b) (hp : Controlled p) : + Controlled (withContext p) := by + unfold withContext + apply controlled_letIn _ _ hp + apply controlled_pure; cc +lemma controlled_retainOption {a b : DataType} (p : Effect a (Optional b)) (hp : Controlled p) : + Controlled (retainOption p) := by + unfold retainOption + apply controlled_letIn _ _ hp + apply controlled_pure; cc +syntax "ec" : tactic +macro_rules +| `(tactic| ec) => `(tactic| + first + | assumption + | exact Effect.controlled_draw + | apply Effect.controlled_precompose <;> ec + | apply Effect.controlled_map <;> ec + | apply Effect.controlled_bind <;> ec + | apply Effect.controlled_letIn <;> ec + | apply Effect.controlled_pure <;> cc + | apply Effect.controlled_keep <;> ec + | apply Effect.controlled_choose <;> ec + | apply Effect.controlled_withContext <;> ec + | apply Effect.controlled_retainOption <;> ec + | apply controlled_optionMap <;> cc + | apply controlled_mapEach <;> cc + | cc) +lemma controlled_bernoulli : Controlled bernoulliCode := by unfold bernoulliCode; ec +lemma controlled_uniformList {a : DataType} : Controlled (uniformList (a:=a)) := by unfold uniformList; ec +lemma controlled_proposal : Controlled proposal := by + have h₁ := controlled_exchangePositions + have h₂ := controlled_uniformList (a:=NN) + unfold proposal; ec +lemma controlled_someCode {a b : DataType} (p : Effect a b) (hp : Controlled p) : Controlled (someCode p) := by + unfold someCode; ec +lemma controlled_noneCode {a b : DataType} : Controlled (noneCode (a:=a) (b:=b)) := by unfold noneCode; ec +lemma controlled_optionBind {a b c : DataType} (p : Effect a (Optional b)) (q : Effect b (Optional c)) + (hp : Controlled p) (hq : Controlled q) : Controlled (optionBind p q) := by unfold optionBind; ec +end Effect + +lemma bits_length_pow (a k : ℕ) : (a^k).bits.length≤k*a.bits.length+1 := by + induction k with + | zero => simp + | succ k ih => + rw [pow_succ] + have h := bits_length_mul (a^k) a + rw [Nat.add_mul,Nat.one_mul] + omega +lemma powStep_iterate (a k : ℕ) : ((fun z : ℕ×ℕ => (z.1,z.1*z.2))^[k]) (a,1)=(a,a^k) := by + induction k with + | zero => simp + | succ k ih => rw [Function.iterate_succ_apply',ih,pow_succ]; simp [mul_comm] +lemma controlled_powStep : Controlled powStepCode := by unfold powStepCode; control +lemma polySafe_powCode : PolySafe powCode (fun S x => x.1.bits.length≤S ∧ x.2≤S) := by + let g : SizePolynomial := .mul (.constant 10) (.mul (.add .input (.constant 1)) (.add .input (.constant 1))) + have hg (S : ℕ) : g.eval S=10*(S+1)^2 := by simp [g,SizePolynomial.eval,pow_two] + let R : ℕ → Value (.prod .nat NN) → Prop := fun S x => x.1≤S ∧ x.2.1.bits.length≤S ∧ x.2.2=1 + have hi : PolySafe (iterateNat powStepCode) R := by + refine polySafe_iterateNat powStepCode R (fun S z => width z≤g.eval S) + (polySafe_of_controlled _ controlled_powStep _ g (by intros; assumption)) g ?_ ?_ ?_ + · intro S k z hx + obtain ⟨a,v⟩ := z + dsimp [R] at hx + rcases hx with ⟨hk,ha,rfl⟩ + rw [hg,width_pair (a:=.nat) (b:=.nat),width_nat,width_nat] + have h1 : (1:ℕ).bits.length=1 := rfl + rw [h1] + calc + _ ≤ S+(2*S+1+1) := Nat.add_le_add hk (Nat.add_le_add_right (Nat.add_le_add_right (Nat.mul_le_mul_left 2 ha) 1) 1) + _ ≤ _ := by nlinarith + · intro n O S k z hx j hj y hy + obtain ⟨a,v⟩ := z + dsimp [R] at hx + rcases hx with ⟨hk,ha,rfl⟩ + rw [iterateM_total (run O powStepCode) (fun z : ℕ×ℕ => (z.1,z.1*z.2)) (fun _ => rfl),powStep_iterate] at hy + cases hy + rw [width_pair (a:=.nat) (b:=.nat),width_nat,width_nat,hg] + have hh := bits_length_pow a j + have hm : j*a.bits.length≤S*S := Nat.mul_le_mul (hj.trans hk) ha + have hb := hh.trans (Nat.add_le_add_right hm 1) + calc + _ ≤ 2*S+1+(S*S+1) := Nat.add_le_add (Nat.add_le_add_right (Nat.mul_le_mul_left 2 ha) 1) hb + _ ≤ _ := by nlinarith + · intro n O S k z hx j hj y hy + obtain ⟨a,v⟩ := z + dsimp [R] at hx + rcases hx with ⟨hk,ha,rfl⟩ + rw [iterateM_total (run O powStepCode) (fun z : ℕ×ℕ => (z.1,z.1*z.2)) (fun _ => rfl),powStep_iterate] at hy + cases hy + rw [width_pair (a:=.nat) (b:=.nat),width_nat,width_nat,hg] + have hh := bits_length_pow a j + have hm : j*a.bits.length≤S*S := Nat.mul_le_mul (hj.le.trans hk) ha + have hb := hh.trans (Nat.add_le_add_right hm 1) + calc + _ ≤ 2*S+1+(S*S+1) := Nat.add_le_add (Nat.add_le_add_right (Nat.mul_le_mul_left 2 ha) 1) hb + _ ≤ _ := by nlinarith + unfold powCode + apply polySafe_compose _ _ _ R + (polySafe_of_controlled _ (by control) _ (.add (.mul (.constant 3) .input) (.constant 1)) (by + intro S x hx + obtain ⟨a,k⟩ := x + dsimp only [Prod.fst,Prod.snd] at hx + rw [width_pair (a:=.nat) (b:=.nat),width_nat,width_nat] + have hk : k.bits.length≤S := (bits_length_le_value k).trans hx.2 + dsimp [SizePolynomial.eval] + omega)) (polySafe_post _ _ R hi (by control)) + intro n O S x hx y hy + cases hy + exact ⟨hx.2,hx.1,rfl⟩ +lemma polySafe_ratPowCode : PolySafe ratPowCode (fun S x => width x.1≤S ∧ x.2≤S) := by + have hwidth : ∀ S x,(width (a:=NN) x.1≤S ∧ x.2≤S) → + width (a:=.prod NN .nat) x≤3*S+1 := by + intro S x hx + obtain ⟨q,k⟩ := x + dsimp only [Prod.fst,Prod.snd] at hx + rw [width_pair (a:=NN) (b:=.nat),width_nat] + have hk : k.bits.length≤S := (bits_length_le_value k).trans hx.2 + omega + unfold ratPowCode + apply polySafe_post _ _ _ _ controlled_normalizeRat + apply polySafe_both + · apply polySafe_compose _ _ _ _ + (polySafe_of_controlled _ (by control) _ (.add (.mul (.constant 3) .input) (.constant 1)) hwidth) polySafe_powCode + intro n O S x hx y hy + cases hy + refine ⟨?_,hx.2⟩ + obtain ⟨⟨a,b⟩,k⟩ := x + dsimp only [Prod.fst,Prod.snd] at hx ⊢ + rw [width_pair (a:=.nat) (b:=.nat),width_nat,width_nat] at hx + omega + · apply polySafe_compose _ _ _ _ + (polySafe_of_controlled _ (by control) _ (.add (.mul (.constant 3) .input) (.constant 1)) hwidth) polySafe_powCode + intro n O S x hx y hy + cases hy + refine ⟨?_,hx.2⟩ + obtain ⟨⟨a,b⟩,k⟩ := x + dsimp only [Prod.fst,Prod.snd] at hx ⊢ + rw [width_pair (a:=.nat) (b:=.nat),width_nat,width_nat] at hx + omega + +lemma run_both_parts {n : ℕ} (O : IndependenceOracle n) {a b c : DataType} + (p : Expression a b) (q : Expression a c) (x : Value a) (z : Value (.prod b c)) + (hz : run O (both p q) x=some z) : run O p x=some z.1 ∧ run O q x=some z.2 := by + rw [run_both] at hz + cases hp : run O p x with + | none => simp [hp] at hz + | some y => + simp only [hp,Option.bind_some] at hz + cases hq : run O q x with + | none => simp [hq] at hz + | some w => + simp only [hq,Option.map_some,Option.some.injEq] at hz + subst z + exact ⟨rfl,rfl⟩ +lemma width_fst {a b : DataType} (x : Value (.prod a b)) : width x.1≤width x := by + obtain ⟨p,q⟩ := x; simp only [width_pair]; omega +lemma width_snd {a b : DataType} (x : Value (.prod a b)) : width x.2≤width x := by + obtain ⟨p,q⟩ := x; simp only [width_pair]; omega +lemma polySafe_ratPowerAfter {a : DataType} (p : Expression a (.prod NN .nat)) + (R : ℕ → Value a → Prop) (hp : PolySafe p R) (g : SizePolynomial) + (hg : ∀ {n : ℕ} (O : IndependenceOracle n) S x,R S x → ∀ y,run O p x=some y → y.2≤g.eval S) : + PolySafe (p >>> ratPowCode) R := by + obtain ⟨f,hf⟩ := hp + let t : SizePolynomial := .add f g + apply polySafe_compose p ratPowCode R (fun S y => width y.1≤t.eval S ∧ y.2≤t.eval S) + ⟨f,hf⟩ (polySafe_reparam _ _ polySafe_ratPowCode t) + intro n O S x hx y hy + have hh := (width_fst y).trans (safe_output (hf O S x hx) hy) + exact ⟨hh.trans (Nat.le_add_right _ _),(hg O S x hx y hy).trans (Nat.le_add_left _ _)⟩ +lemma polySafe_preControlled {a b c : DataType} (p : Expression a b) (q : Expression b c) + (R : ℕ → Value a → Prop) (Q : ℕ → Value b → Prop) (hp : Controlled p) + (g : SizePolynomial) (hw : ∀ S x,R S x → width x≤g.eval S) + (hq : PolySafe q Q) + (hh : ∀ {n : ℕ} (O : IndependenceOracle n) S x,R S x → ∀ y,run O p x=some y → Q S y) : + PolySafe (p >>> q) R := + polySafe_compose _ _ _ _ (polySafe_of_controlled p hp R g hw) hq hh + +lemma bankEval_rest_suffix {A : Type*} (t : DrawTree A) (bank : Bank) : + ∃ pre,bank=pre++(bankEval t bank).2 := by + induction t generalizing bank with + | leaf a => exact ⟨[],rfl⟩ + | draw v k ih => + cases bank with + | nil => exact ⟨[],rfl⟩ + | cons row bank => + simp only [bankEval] + split + · exact ⟨[row],rfl⟩ + · rename_i i hi + obtain ⟨pre,hpre⟩ := ih ⟨i,rejectValue_lt _ _ _ hi⟩ bank + exact ⟨row::pre,congrArg (List.cons row) hpre⟩ +lemma bankEval_rest_width {A : Type*} (t : DrawTree A) (bank : Bank) : + width (a:=BankData) (bankEval t bank).2≤width (a:=BankData) bank := by + obtain ⟨pre,hpre⟩ := bankEval_rest_suffix t bank + calc + width (a:=BankData) (bankEval t bank).2 ≤ width (a:=BankData) (pre ++ (bankEval t bank).2) := by + rw [width_list_append (a:=RandomRows)]; exact Nat.le_add_left _ _ + _ = width (a:=BankData) bank := congrArg (width (a:=BankData)) hpre.symm +namespace Effect +lemma RealizesLaw.outputs {n : ℕ} {O : IndependenceOracle n} {A : Type*} {a b : DataType} + {p : Effect a b} {e : A → Value b} {x : Value a} {t : DrawTree A} + (h : RealizesLaw O p e x t) (bank : Bank) : + ∃ y : Option A,∃ rest : Bank, + run O p (x,bank)=some (optionalValue b (y.map e),rest) ∧ width (a:=BankData) rest≤width (a:=BankData) bank := by + obtain ⟨u,hu,hp⟩ := h + exact ⟨(bankEval u bank).1,(bankEval u bank).2,hp bank,bankEval_rest_width u bank⟩ +end Effect +lemma width_optionalValue {a : DataType} (x : Option (Value a)) (W : ℕ) + (h : ∀ y,x=some y → width y≤W) : width (a:=Optional a) (optionalValue a x)≤width (zeroValue a)+W+3 := by + cases x with + | none => simp only [optionalValue,optionData,width_pair (a:=.bool) (b:=a),width_bool]; omega + | some y => + have hh := h y rfl + simp only [optionalValue,optionData,width_pair (a:=.bool) (b:=a),width_bool] + omega +lemma width_optionEncode {A : Type*} {a : DataType} (e : A → Value a) (x : Option A) (W : ℕ) + (h : ∀ y,width (e y)≤W) : width (optionEncode e x)≤width (zeroValue a)+W+3 := by + apply width_optionalValue (x.map e) W + intro y hy + obtain ⟨z,hz,he⟩ := Option.map_eq_some_iff.mp hy + subst y + exact h z + +open Expression +lemma learningRatio_height (xs : List (Word×Word)) (p r : ℕ) : + pairHeight (rationalPair (learningRatio xs p r))≤width (a:=SampleData) xs+1 := by + rw [learningRatio,rationalPair_div] + apply (pairHeight_normalize _ _).trans + have ha := bits_length_le_value (countPlainValue xs) + have hb := bits_length_le_value (countDefectValue xs p r) + have hc : countPlainValue xs≤xs.length := List.countP_le_length + have hd : countDefectValue xs p r≤xs.length := List.countP_le_length + have he := list_length_le_width (a:=StateData) xs + dsimp only [pairHeight] + omega +lemma run_weightStep_raw {n : ℕ} (O : IndependenceOracle n) (p r a b : ℕ) (xs : List (Word×Word)) : + run O weightStep (xs,((p,r),(a,b)))=some ((p,r), + if p=r then (a,b) else + normalizePair (a*(rationalPair (learningRatio xs p r)).1) + (b*(rationalPair (learningRatio xs p r)).2)) := by + simp only [weightStep,run_both,run_compose,run_fst,run_snd,Option.bind_some,run_applyIf] + rw [run_natEqual] + by_cases h : p=r + · simp [h] + · simp only [h,decide_false,Option.bind_some,Bool.false_eq_true,ite_false,Option.map_some] + rw [run_learningRatio] + simp only [Option.bind_some,Option.map_some] + rw [run_ratMul_raw]; rfl +lemma weightStep_height {n : ℕ} (O : IndependenceOracle n) (xs : Value SampleData) + (z y : Value (.prod NN NN)) (hy : run O weightStep (xs,z)=some y) : + y.1=z.1 ∧ pairHeight y.2≤pairHeight z.2+width xs+1 := by + obtain ⟨⟨p,r⟩,⟨a,b⟩⟩ := z + rw [run_weightStep_raw] at hy + cases hy + refine ⟨rfl,?_⟩ + split_ifs with h + · omega + · have hh := pairHeight_ratMul_raw a b (rationalPair (learningRatio xs p r)).1 + (rationalPair (learningRatio xs p r)).2 + have hl := learningRatio_height xs p r + simpa only [Prod.eta,Prod.snd,Nat.add_assoc] using hh.trans (Nat.add_le_add_left hl (pairHeight (a,b))) +lemma fold_weight_height {n : ℕ} (O : IndependenceOracle n) (xs : Value HistoryData) + (z y : Value (.prod NN NN)) (hy : foldValue (run O weightStep) xs z=some y) : + y.1=z.1 ∧ pairHeight y.2≤pairHeight z.2+width xs := by + induction xs generalizing z with + | nil => cases hy; exact ⟨rfl,by simp⟩ + | cons x xs ih => + rw [foldValue] at hy + cases he : run O weightStep (x,z) with + | none => simp [he] at hy + | some w => + simp only [he,Option.bind_some] at hy + have h₁ := weightStep_height O x z w he + have h₂ := ih w hy + refine ⟨h₂.1.trans h₁.1,?_⟩ + rw [width_cons (a:=SampleData)] + omega +lemma controlled_weightFold : Controlled (.fold weightStep) := by + apply controlled_fold weightStep controlled_weightStep (.mul (.constant 6) .input) + intro n O xs z pre post he y hy + have hh := fold_weight_height O pre z y hy + have hp : width (a:=HistoryData) pre≤width (a:=HistoryData) xs := by rw [he,width_list_append]; omega + have hw := width_le_pairHeight y.2 + have hz := pairHeight_le_width z.2 + rw [width_pair (a:=NN) (b:=NN),hh.1] + simp only [SizePolynomial.eval,width_pair (a:=HistoryData) (b:=.prod NN NN),width_pair (a:=NN) (b:=NN)] + omega +lemma controlled_historyWeight : Controlled historyWeightCode := by + have h := controlled_weightFold + unfold historyWeightCode + cc +lemma controlled_multiplier : Controlled multiplierCode := by + have h₁ := controlled_historyWeight + have h₂ := controlled_defectPairs + have h₃ := controlled_plainCode + unfold multiplierCode + cc + +open Expression +lemma controlled_rho : Controlled rhoCode := by unfold rhoCode; cc +lemma run_deficiency_le {n : ℕ} (O : IndependenceOracle n) (r : ℕ) (x y : Word) (z : ℕ) + (hz : run O deficiencyCode (r,(x,y))=some z) : z≤x.length+r := by + simp only [deficiencyCode,run_compose,run_both,run_fst,run_snd,Option.bind_some,Option.map_some] at hz + rw [run_wordLength,run_wordCount,run_wordNot] at hz + simp only [run,Option.bind_some,Option.map_some] at hz + split_ifs at hz <;> simp_all only [Option.bind_none,Option.map_none,Option.bind_some,Option.map_some] <;> try contradiction + rw [run_natSub] at hz + cases hz + exact Nat.sub_le _ _ +def weightSmall (S : ℕ) (x : Value WeightInput) : Prop := + width x≤S ∧ x.1.1.1≤S ∧ x.1.1.2≤S +lemma polySafe_anneal : PolySafe annealCode weightSmall := by + have hrho := controlled_rho + have hi : PolySafe + (both (snd >>> fst >>> wordLength >>> rhoCode) (fst >>> fst >>> snd) >>> ratPowCode) weightSmall := by + apply polySafe_ratPowerAfter _ _ + (polySafe_of_controlled _ (by cc) _ .input (by intro S x hx; exact hx.1)) .input + intro n O S x hx y hy + have hh := (run_both_parts O _ _ x y hy).2 + change some x.1.1.2=some y.2 at hh + exact (Option.some.inj hh) ▸ hx.2.2 + unfold annealCode + apply polySafe_ratPowerAfter _ _ + (polySafe_both _ _ _ hi (polySafe_of_controlled _ (by cc) _ .input (by intro S x hx; exact hx.1))) + (.mul (.constant 2) .input) + intro n O S x hx y hy + have hh := (run_both_parts O _ _ x y hy).2 + change run O deficiencyCode (x.1.1.1,x.2)=some y.2 at hh + have hb := run_deficiency_le O x.1.1.1 x.2.1 x.2.2 y.2 hh + have hw : x.2.1.length≤S := (width_fst (a:=.word) (b:=.word) x.2).trans ((width_snd x).trans hx.1) + dsimp only [SizePolynomial.eval] + exact hb.trans ((Nat.add_le_add hw hx.2.1).trans_eq (by omega)) +lemma polySafe_weight : PolySafe weightCode weightSmall := by + have hm := controlled_multiplier + unfold weightCode + exact polySafe_post _ _ _ (polySafe_both _ _ _ + (polySafe_of_controlled _ (by cc) _ .input (by intro S x hx; exact hx.1)) polySafe_anneal) controlled_ratMul + +abbrev OraclePredicate (a : DataType) := (n : ℕ) → IndependenceOracle n → ℕ → Value a → Prop + +def OracleSafe {a b : DataType} (p : Expression a b) (R : OraclePredicate a) : Prop := + ∃ f : SizePolynomial,∀ {n : ℕ} (O : IndependenceOracle n) S x,R n O S x → Safe O (f.eval S) p x +lemma oracleSafe_lift {a b : DataType} (p : Expression a b) (R : ℕ → Value a → Prop) + (h : PolySafe p R) : OracleSafe p (fun _ _ => R) := h +lemma oracleSafe_controlled {a b : DataType} (p : Expression a b) (hp : Controlled p) + (R : OraclePredicate a) (g : SizePolynomial) + (hg : ∀ n O S x,R n O S x → width x≤g.eval S) : OracleSafe p R := by + obtain ⟨f,hf⟩ := hp + refine ⟨f.subst g,fun O S x hx => ?_⟩ + apply safe_mono p x (hf O x) + rw [SizePolynomial.eval_subst] + exact f.monotone (hg _ O S x hx) +lemma oracleSafe_mono {a b : DataType} (p : Expression a b) {R Q : OraclePredicate a} + (hp : OracleSafe p Q) (h : ∀ n O S x,R n O S x → Q n O S x) : OracleSafe p R := by + obtain ⟨f,hf⟩ := hp + exact ⟨f,fun O S x hx => hf O S x (h _ O S x hx)⟩ +lemma oracleSafe_reparam {a b : DataType} (p : Expression a b) (R : OraclePredicate a) + (hp : OracleSafe p R) (g : SizePolynomial) : OracleSafe p (fun n O S x => R n O (g.eval S) x) := by + obtain ⟨f,hf⟩ := hp + exact ⟨f.subst g,fun O S x hx => by rw [SizePolynomial.eval_subst]; exact hf O _ x hx⟩ +lemma oracleSafe_compose {a b c : DataType} (p : Expression a b) (q : Expression b c) + (R : OraclePredicate a) (Q : OraclePredicate b) (hp : OracleSafe p R) (hq : OracleSafe q Q) + (h : ∀ n O S x,R n O S x → ∀ y,run O p x=some y → Q n O S y) : OracleSafe (p >>> q) R := by + obtain ⟨f,hf⟩ := hp + obtain ⟨g,hg⟩ := hq + refine ⟨.add f g,fun O S x hx => ?_⟩ + apply safe_compose O p q x + · exact safe_mono p x (hf O S x hx) (Nat.le_add_right _ _) + · intro y hy + exact safe_mono q y (hg O S y (h _ O S x hx y hy)) (Nat.le_add_left _ _) +lemma oracleSafe_both {a b c : DataType} (p : Expression a b) (q : Expression a c) + (R : OraclePredicate a) (hp : OracleSafe p R) (hq : OracleSafe q R) : OracleSafe (both p q) R := by + obtain ⟨f,hf⟩ := hp + obtain ⟨g,hg⟩ := hq + refine ⟨.add (.mul (.constant 3) (.add f g)) (.constant 1),fun O S x hx => ?_⟩ + apply safe_both O p q x + · exact safe_mono p x (hf O S x hx) (Nat.le_add_right _ _) + · exact safe_mono q x (hg O S x hx) (Nat.le_add_left _ _) +lemma oracleSafe_post {a b c : DataType} (p : Expression a b) (q : Expression b c) + (R : OraclePredicate a) (hp : OracleSafe p R) (hq : Controlled q) : OracleSafe (p >>> q) R := by + obtain ⟨f,hf⟩ := hp + apply oracleSafe_compose p q R (fun _ _ S y => width y≤f.eval S) ⟨f,hf⟩ + (oracleSafe_controlled q hq _ f (by intros; assumption)) + intro n O S x hx y hy + exact safe_output (hf O S x hx) hy +lemma oracleSafe_pull {a b c : DataType} (p : Expression a b) (q : Expression b c) + (R : OraclePredicate a) (Q : OraclePredicate b) (hp : Controlled p) + (g : SizePolynomial) (hw : ∀ n O S x,R n O S x → width x≤g.eval S) + (hq : OracleSafe q Q) + (hh : ∀ n O S x,R n O S x → ∀ y,run O p x=some y → Q n O S y) : OracleSafe (p >>> q) R := + oracleSafe_compose p q R Q (oracleSafe_controlled p hp R g hw) hq hh +lemma oracleSafe_input_bound {a b : DataType} (p : Expression a b) (R : OraclePredicate a) + (hp : OracleSafe p R) : ∃ f : SizePolynomial,∀ n O S x,R n O S x → width x≤f.eval S := by + obtain ⟨f,hf⟩ := hp + exact ⟨f,fun _ O S x hx => safe_input (hf O S x hx)⟩ +lemma oracleSafe_applyIf {a b : DataType} (t : Expression a .bool) (p q : Expression a b) + (R : OraclePredicate a) (ht : OracleSafe t R) + (hp : OracleSafe p (fun n O S x => R n O S x ∧ run O t x=some false)) + (hq : OracleSafe q (fun n O S x => R n O S x ∧ run O t x=some true)) : + OracleSafe (applyIf t p q) R := by + have hid : OracleSafe (ident (a:=a)) R := by + obtain ⟨f,hf⟩ := oracleSafe_input_bound t R ht + exact oracleSafe_controlled _ (by cc) R f hf + have hboth := oracleSafe_both t ident R ht hid + obtain ⟨f,hf⟩ := hboth + obtain ⟨g,hg⟩ := hp + obtain ⟨k,hk⟩ := hq + unfold applyIf + apply oracleSafe_compose (both t ident) (branch p q) R + (fun n O S z => width z≤f.eval S ∧ R n O S z.2 ∧ run O t z.2=some z.1) ⟨f,hf⟩ + · refine ⟨.add f (.add g k),fun O S z hz => ?_⟩ + obtain ⟨v,x⟩ := z + refine ⟨hz.1.trans (Nat.le_add_right _ _),?_,?_⟩ + · intro y hy + cases v + · exact (safe_output (hg O S x ⟨hz.2.1,hz.2.2⟩) hy).trans (by dsimp [SizePolynomial.eval]; omega) + · exact (safe_output (hk O S x ⟨hz.2.1,hz.2.2⟩) hy).trans (by dsimp [SizePolynomial.eval]; omega) + · cases v + · exact safe_mono p x (hg O S x ⟨hz.2.1,hz.2.2⟩) (by dsimp [SizePolynomial.eval]; omega) + · exact safe_mono q x (hk O S x ⟨hz.2.1,hz.2.2⟩) (by dsimp [SizePolynomial.eval]; omega) + · intro n O S x hx z hz + have hh := run_both_parts O t ident x z hz + have he : x=z.2 := Option.some.inj hh.2 + exact ⟨safe_output (hf O S x hx) hz,he ▸ hx,he ▸ hh.1⟩ + +lemma oracleSafe_fold {a b : DataType} (p : Expression (.prod a b) b) + (R : OraclePredicate (.prod (.list a) b)) (Q : OraclePredicate (.prod a b)) + (hp : OracleSafe p Q) (g : SizePolynomial) + (hinput : ∀ {n : ℕ} (O : IndependenceOracle n) S x,R n O S x → width x≤g.eval S) + (hacc : ∀ {n : ℕ} (O : IndependenceOracle n) S xs z,R n O S (xs,z) → + ∀ pre post,xs=pre++post → ∀ y,foldValue (run O p) pre z=some y → width y≤g.eval S) + (hstep : ∀ {n : ℕ} (O : IndependenceOracle n) S xs z,R n O S (xs,z) → + ∀ pre x post,xs=pre++x::post → ∀ y,foldValue (run O p) pre z=some y → Q n O S (x,y)) : + OracleSafe (.fold p) R := by + obtain ⟨f,hf⟩ := hp + refine ⟨.add f g,fun O S x hx => ?_⟩ + obtain ⟨xs,z⟩ := x + refine ⟨(hinput O S (xs,z) hx).trans (Nat.le_add_left _ _),?_,?_⟩ + · intro y hy + exact (hacc O S xs z hx xs [] (by simp) y hy).trans (Nat.le_add_left _ _) + · apply foldSafe_prefix + intro pre x post he y hy + exact safe_mono p (x,y) (hf O S (x,y) (hstep O S xs z hx pre x post he y hy)) + (Nat.le_add_right _ _) + +lemma oracleSafe_iterateNat {a : DataType} (p : Expression a a) + (R : OraclePredicate (.prod .nat a)) (Q : OraclePredicate a) + (hp : OracleSafe p Q) (g : SizePolynomial) + (hinput : ∀ {n : ℕ} (O : IndependenceOracle n) S k z,R n O S (k,z) → k+width (a:=a) z≤g.eval S) + (hacc : ∀ {n : ℕ} (O : IndependenceOracle n) S k z,R n O S (k,z) → + ∀ j,j≤k → ∀ y,iterateM (run O p) j z=some y → width (a:=a) y≤g.eval S) + (hbody : ∀ {n : ℕ} (O : IndependenceOracle n) S k z,R n O S (k,z) → + ∀ j,j k≤g.eval S) + (oracleSafe_controlled Expression.fst (by control) R T (fun n O => hnatwidth O)) + (oracleSafe_reparam unary (fun _ _ S k => k≤S) (oracleSafe_lift _ _ polySafe_unary) g) + intro n O S x hx y hy + obtain ⟨k,z⟩ := x + simp only [run_fst, Option.some.injEq] at hy + subst y + have hh : k+width (a:=a) z≤g.eval S := hinput O S k z hx + exact (Nat.le_add_right k (width (a:=a) z)).trans hh + · exact oracleSafe_controlled Expression.snd (by control) R T (fun n O => hnatwidth O) + let Rw : OraclePredicate (.prod .word a) := fun n O S x => R n O S (x.1.length,x.2) + let Rl : OraclePredicate (.prod (.list .bool) a) := fun n O S x => R n O S (x.1.length,x.2) + have hw : ∀ {n : ℕ} (O : IndependenceOracle n) S x,Rw n O S x → width x≤T.eval S := by + intro n O S x hx + obtain ⟨w,z⟩ := x + have hh : w.length+width (a:=a) z≤g.eval S := hinput O S w.length z hx + rw [width_pair (a:=.word) (b:=a),width_word] + dsimp [T,SizePolynomial.eval] + omega + have hfold : OracleSafe (.fold (snd >>> p)) Rl := by + refine oracleSafe_fold (Expression.snd (a:=.bool) >>> p) Rl + (fun n O S x => width x≤T.eval S ∧ Q n O S x.2) ?_ T ?_ ?_ ?_ + · apply oracleSafe_compose _ _ _ Q + (oracleSafe_controlled Expression.snd (by control) _ T (by intro n O S x hx; exact hx.1)) hp + intro n O S x hx y hy + cases hy + exact hx.2 + · intro n O S x hx + obtain ⟨xs,z⟩ := x + have hh : xs.length+width (a:=a) z≤g.eval S := hinput O S xs.length z hx + rw [width_pair (a:=.list .bool) (b:=a),width_list_bool] + dsimp [T,SizePolynomial.eval] + omega + · intro n O S xs z hx pre post he y hy + rw [foldValue_iterateM] at hy + have hj : pre.length≤xs.length := by rw [he,List.length_append]; omega + have hh := hacc O S xs.length z hx pre.length hj y hy + dsimp [T,SizePolynomial.eval] + omega + · intro n O S xs z hx pre b post he y hy + rw [foldValue_iterateM] at hy + have hj : pre.length hw O)) hfold + intro n O S x hx y hy + cases hy + exact hx + · intro n O S x hx y hy + obtain ⟨k,z⟩ := x + obtain ⟨w,hw,hk⟩ := run_unary O k + simp only [onLeft,run_both,run_compose,run_fst,run_snd,Option.bind_some,hw,Option.map_some] at hy + cases hy + change R n O S (w.length,z) + rwa [hk] + +namespace Effect +def bankScope {a : DataType} (R : OraclePredicate a) : OraclePredicate (.prod a BankData) := + fun n O S x => R n O S x.1 ∧ width (a:=BankData) x.2≤S +lemma scope_width {a b : DataType} (p : Expression a b) (R : OraclePredicate a) + (hp : OracleSafe p R) : ∃ f : SizePolynomial,∀ n O S x,bankScope R n O S x → width x≤f.eval S := by + obtain ⟨f,hf⟩ := oracleSafe_input_bound p R hp + refine ⟨.add (.mul (.constant 2) f) (.add .input (.constant 1)),?_⟩ + intro n O S x hx + have hh := hf n O S x.1 hx.1 + have hb : width (a:=BankData) x.2≤S := hx.2 + rw [width_pair (a:=a) (b:=BankData)] + dsimp only [SizePolynomial.eval] + omega +lemma safe_scope_fst {a b : DataType} (p : Expression a b) (R : OraclePredicate a) + (hp : OracleSafe p R) : OracleSafe (fst (b:=BankData) >>> p) (bankScope R) := by + obtain ⟨f,hf⟩ := scope_width p R hp + apply oracleSafe_pull _ _ _ R (by cc) f hf hp + intro n O S x hx y hy + cases hy + exact hx.1 +lemma safe_scope_controlled {a b c : DataType} (p : Expression a b) (q : Expression (.prod a BankData) c) + (R : OraclePredicate a) (hp : OracleSafe p R) (hq : Controlled q) : OracleSafe q (bankScope R) := by + obtain ⟨f,hf⟩ := scope_width p R hp + exact oracleSafe_controlled q hq _ f hf +lemma oracleSafe_pure {a b : DataType} (p : Expression a b) (R : OraclePredicate a) + (hp : OracleSafe p R) : OracleSafe (pure p) (bankScope R) := by + unfold pure + apply oracleSafe_both + · apply oracleSafe_both + · exact safe_scope_controlled p _ R hp (by cc) + · exact safe_scope_fst p R hp + · exact safe_scope_controlled p _ R hp (by cc) +lemma oracleSafe_precompose {a b c : DataType} (p : Expression a b) (q : Effect b c) + (R : OraclePredicate a) (Q : OraclePredicate b) (hp : OracleSafe p R) + (hq : OracleSafe q (bankScope Q)) + (h : ∀ n O S x,R n O S x → ∀ y,run O p x=some y → Q n O S y) : + OracleSafe (precompose p q) (bankScope R) := by + unfold precompose onLeft + apply oracleSafe_compose _ _ _ (bankScope Q) + (oracleSafe_both _ _ _ (safe_scope_fst p R hp) (safe_scope_controlled p _ R hp (by cc))) hq + intro n O S x hx y hy + have hh := run_both_parts O (fst >>> p) snd x y hy + have hp' : run O p x.1=some y.1 := hh.1 + + have hb : x.2=y.2 := Option.some.inj hh.2 + exact ⟨h n O S x.1 hx.1 y.1 hp',hb ▸ hx.2⟩ +lemma oracleSafe_keep {a b : DataType} (p : Effect a b) (R : OraclePredicate (.prod a BankData)) + (hp : OracleSafe p R) : OracleSafe (keep p) R := by + obtain ⟨f,hf⟩ := oracleSafe_input_bound p R hp + unfold keep Expression.letIn + apply oracleSafe_post + · exact oracleSafe_both _ _ _ (oracleSafe_controlled _ (by cc) R f hf) hp + · cc +lemma oracleSafe_bind {a b c : DataType} (p : Effect a b) (q : Effect b c) + (R : OraclePredicate a) (Q : OraclePredicate b) + (hp : OracleSafe p (bankScope R)) (hq : OracleSafe q (bankScope Q)) + (h : ∀ n O S x bank,R n O S x → width (a:=BankData) bank≤S → ∀ y rest, + run O p (x,bank)=some ((true,y),rest) → Q n O S y ∧ width (a:=BankData) rest≤S) : + OracleSafe (bind p q) (bankScope R) := by + obtain ⟨f,hf⟩ := hp + let T : OraclePredicate (.prod (Optional b) BankData) := fun n O S z => + ∃ x bank,bankScope R n O S (x,bank) ∧ run O p (x,bank)=some z + have hw : ∀ n O S z,T n O S z → width z≤f.eval S := by + intro n O S z hz + obtain ⟨x,bank,hx,he⟩ := hz + exact safe_output (hf O S (x,bank) hx) he + unfold bind + apply oracleSafe_compose p _ (bankScope R) T ⟨f,hf⟩ + · apply oracleSafe_applyIf _ _ _ T + · exact oracleSafe_controlled _ (by cc) T f hw + · exact oracleSafe_controlled _ (by cc) _ f (by intro n O S z hz; exact hw n O S z hz.1) + · apply oracleSafe_pull _ q _ (bankScope Q) (by cc) f + (by intro n O S z hz; exact hw n O S z hz.1) hq + intro n O S z hz y hy + obtain ⟨⟨flag,v⟩,rest⟩ := z + have hv : flag=true := Option.some.inj hz.2 + subst flag + have hy' : (v,rest)=y := Option.some.inj hy + subst y + obtain ⟨x,bank,hx,he⟩ := hz.1 + exact h n O S x bank hx.1 hx.2 v rest he + · intro n O S x hx z hz + exact ⟨x.1,x.2,hx,hz⟩ +lemma RealizesLaw.output_some {n : ℕ} {O : IndependenceOracle n} {A : Type*} {a b : DataType} + {p : Effect a b} {e : A → Value b} {x : Value a} {t : DrawTree A} + (h : RealizesLaw O p e x t) (bank : Bank) (y : Value b) (rest : Bank) + (hy : run O p (x,bank)=some ((true,y),rest)) : ∃ v,y=e v ∧ width (a:=BankData) rest≤width (a:=BankData) bank := by + obtain ⟨v,r,he,hw⟩ := h.outputs bank + rw [hy] at he + have he' := Option.some.inj he + cases v with + | none => cases (congrArg (fun z => z.1.1) he') + | some v => + have hry : rest=r := congrArg Prod.snd he' + have hyy : y=e v := congrArg (fun z => z.1.2) he' + exact ⟨v,hyy,hry ▸ hw⟩ +end Effect +end MachineCode + +namespace DrawTree +lemma All.mono {A : Type*} {t : DrawTree A} {P Q : A → Prop} + (h : All P t) (hq : ∀ x,P x → Q x) : All Q t := by + induction t with + | leaf x => exact hq x h + | draw v k ih => exact fun i => ih i (h i) +lemma all_bind_of_all {A B : Type*} (t : DrawTree A) (f : A → DrawTree B) + (P : A → Prop) (Q : B → Prop) (ht : All P t) + (hf : ∀ x,P x → All Q (f x)) : All Q (t.bind f) := by + induction t with + | leaf x => exact hf x ht + | draw v k ih => exact fun i => ih i (ht i) +lemma all_map_of_all {A B : Type*} (t : DrawTree A) (f : A → B) + (P : A → Prop) (Q : B → Prop) (ht : All P t) + (hf : ∀ x,P x → Q (f x)) : All Q (t.map f) := + all_bind_of_all t _ P Q ht hf +end DrawTree +namespace MachineCode + +lemma bankEval_all {A : Type*} (t : DrawTree A) (P : A → Prop) + (ht : DrawTree.All P t) (bank : Bank) (x : A) + (hx : (bankEval t bank).1=some x) : P x := by + induction t generalizing bank with + | leaf a => + have he : a=x := Option.some.inj hx + exact he ▸ ht + | draw v k ih => + cases bank with + | nil => cases hx + | cons row bank => + simp only [bankEval] at hx + split at hx + · cases hx + · exact ih _ (ht _) bank hx +open Expression +namespace Effect +lemma RealizesLaw.outputs_all {n : ℕ} {O : IndependenceOracle n} + {A : Type*} {a b : DataType} {p : Effect a b} {e : A → Value b} + {x : Value a} {t : DrawTree A} (h : RealizesLaw O p e x t) + (P : A → Prop) (ht : DrawTree.All P t) (bank : Bank) : + ∃ y : Option A,∃ rest : Bank, + run O p (x,bank)=some (optionalValue b (y.map e),rest) ∧ + width (a:=BankData) rest≤width (a:=BankData) bank ∧ + ∀ v,y=some v → P v := by + obtain ⟨u,hu,hp⟩ := h + refine ⟨(bankEval u bank).1,(bankEval u bank).2,hp bank,bankEval_rest_width u bank,?_⟩ + intro v hv + exact bankEval_all u P (hu.all P ht) bank v hv +lemma RealizesLaw.output_some_all {n : ℕ} {O : IndependenceOracle n} + {A : Type*} {a b : DataType} {p : Effect a b} {e : A → Value b} + {x : Value a} {t : DrawTree A} (h : RealizesLaw O p e x t) + (P : A → Prop) (ht : DrawTree.All P t) (bank : Bank) + (y : Value b) (rest : Bank) (hy : run O p (x,bank)=some ((true,y),rest)) : + ∃ v,y=e v ∧ P v ∧ width (a:=BankData) rest≤width (a:=BankData) bank := by + obtain ⟨v,r,he,hw,hv⟩ := h.outputs_all P ht bank + rw [hy] at he + have hh := Option.some.inj he + cases v with + | none => cases (congrArg (fun z => z.1.1) hh) + | some v => + have hry : rest=r := congrArg Prod.snd hh + have hyy : y=e v := congrArg (fun z => z.1.2) hh + exact ⟨v,hyy,hv v rfl,hry ▸ hw⟩ +lemma RealizesLaw.run_bound {n : ℕ} {O : IndependenceOracle n} + {A : Type*} {a b : DataType} {p : Effect a b} {e : A → Value b} + {x : Value a} {t : DrawTree A} (h : RealizesLaw O p e x t) + (W : ℕ) (R : Value b → Prop) + (ht : DrawTree.All (fun v => width (e v)≤W ∧ R (e v)) t) + (bank : Bank) (y : Value (.prod (Optional b) BankData)) + (hy : run O p (x,bank)=some y) : + width y≤2*(width (zeroValue b)+W+3)+1+width (a:=BankData) bank ∧ + (y.1.1=true → R y.1.2) := by + obtain ⟨v,rest,he,hrest,hv⟩ := h.outputs_all _ ht bank + have he' : y=(optionalValue b (v.map e),rest) := Option.some.inj (hy.symm.trans he) + subst y + constructor + · have hw : width (optionalValue b (v.map e))≤width (zeroValue b)+W+3 := by + apply width_optionalValue + intro z hz + obtain ⟨u,hu,hz⟩ := Option.map_eq_some_iff.mp hz + subst z + exact (hv u hu).1 + rw [width_pair (a:=Optional b) (b:=BankData)] + omega + · cases v with + | none => intro h; cases h + | some z => intro _; exact (hv z rfl).2 +lemma RealizesLaw.rest_width {n : ℕ} {O : IndependenceOracle n} + {A : Type*} {a b : DataType} {p : Effect a b} {e : A → Value b} + {x : Value a} {t : DrawTree A} (h : RealizesLaw O p e x t) + (bank : Bank) (y : Value (.prod (Optional b) BankData)) + (hy : run O p (x,bank)=some y) : width (a:=BankData) y.2≤width (a:=BankData) bank := by + obtain ⟨v,rest,he,hrest⟩ := h.outputs bank + have he' : y=(optionalValue b (v.map e),rest) := Option.some.inj (hy.symm.trans he) + exact he' ▸ hrest + +def BankMonotone {a b : DataType} (p : Effect a b) : Prop := + ∀ {n : ℕ} (O : IndependenceOracle n) (x : Value a) (bank : Bank) z, + run O p (x,bank)=some z → width (a:=BankData) z.2≤width (a:=BankData) bank +lemma bank_pure {a b : DataType} (p : Expression a b) : BankMonotone (pure p) := by + intro n O x bank z hz + have hh := (run_both_parts (a:=.prod a BankData) (b:=Optional b) (c:=BankData) O (both (constant (b:=.bool) true) (fst >>> p)) snd (x,bank) z hz).2 + have he : bank=z.2 := Option.some.inj hh + exact he ▸ le_rfl +lemma bank_fail {a b : DataType} : BankMonotone (fail (a:=a) (b:=b)) := by + intro n O x bank z hz + cases hz + exact le_rfl +lemma bank_bind {a b c : DataType} (p : Effect a b) (q : Effect b c) + (hp : BankMonotone p) (hq : BankMonotone q) : BankMonotone (bind p q) := by + intro n O x bank z hz + rw [bind,run_compose] at hz + cases he : run O p (x,bank) with + | none => simp [he] at hz + | some y => + simp only [he,Option.bind_some] at hz + obtain ⟨⟨v,y⟩,rest⟩ := y + have hb := hp O x bank ((v,y),rest) he + cases v + · cases hz; exact hb + · exact (hq O y rest z hz).trans hb +lemma run_keep_value {n : ℕ} (O : IndependenceOracle n) {a b : DataType} + (p : Effect a b) (x : Value a) (bank : Bank) (v : Value (.prod (Optional b) BankData)) + (hp : run O p (x,bank)=some v) : + run O (keep p) (x,bank)=some + ((if v.1.1 then optionalValue (.prod a b) (some (x,v.1.2)) else optionalValue (.prod a b) none),v.2) := by + rw [keep,run_letIn,hp] + obtain ⟨⟨flag,y⟩,rest⟩ := v + cases flag <;> rfl +lemma run_keep_some {n : ℕ} (O : IndependenceOracle n) {a b : DataType} + (p : Effect a b) (x : Value a) (bank : Bank) (x' : Value a) (y : Value b) (rest : Bank) + (h : run O (keep p) (x,bank)=some ((true,(x',y)),rest)) : + x'=x ∧ run O p (x,bank)=some ((true,y),rest) := by + cases he : run O p (x,bank) with + | none => simp only [keep,run_letIn,he,Option.bind_none] at h; contradiction + | some v => + rw [run_keep_value O p x bank v he] at h + obtain ⟨⟨flag,y'⟩,r⟩ := v + cases flag + · cases h + · cases h + exact ⟨rfl,rfl⟩ +lemma bank_keep {a b : DataType} (p : Effect a b) (hp : BankMonotone p) : BankMonotone (keep p) := by + intro n O x bank z hz + cases he : run O p (x,bank) with + | none => simp only [keep,run_letIn,he,Option.bind_none] at hz; contradiction + | some v => + rw [run_keep_value O p x bank v he] at hz + cases hz + exact hp O x bank v he +lemma bank_letIn {a b c : DataType} (p : Effect a b) (q : Effect (.prod a b) c) + (hp : BankMonotone p) (hq : BankMonotone q) : BankMonotone (letIn p q) := + bank_bind _ _ (bank_keep p hp) hq +lemma bank_precompose {a b c : DataType} (p : Expression a b) (q : Effect b c) + (hq : BankMonotone q) : BankMonotone (precompose p q) := by + intro n O x bank z hz + cases he : run O p x with + | none => simp only [precompose,onLeft,run_compose,run_both,run_fst,run_snd,Option.bind_some,he,Option.bind_none] at hz; contradiction + | some y => + rw [run_precompose O p q x y bank he] at hz + exact hq O y bank z hz +lemma bank_map {a b c : DataType} (p : Effect a b) (q : Expression b c) + (hp : BankMonotone p) : BankMonotone (map p q) := bank_bind _ _ hp (bank_pure q) +lemma bank_choose {a b : DataType} (t : Expression a .bool) (p q : Effect a b) + (hp : BankMonotone p) (hq : BankMonotone q) : BankMonotone (choose t p q) := by + intro n O x bank z hz + cases he : run O t x with + | none => simp only [choose,run_applyIf,run_compose,run_fst,Option.bind_some,he,Option.bind_none] at hz; contradiction + | some flag => + rw [run_choose O t p q x bank flag he] at hz + cases flag + · exact hp O x bank z hz + · exact hq O x bank z hz +lemma bank_draw : BankMonotone draw := by + intro n O v bank z hz + rw [run_draw] at hz + cases hz + exact width_drop (a:=RandomRows) bank 1 +end Effect + +open Expression +abbrev Attribute (a : DataType) := ℕ → Value a → Prop +def Attribute.Mono {a : DataType} (R : Attribute a) : Prop := + ∀ S T,S≤T → ∀ x,R S x → R T x +def AttrSafe {a b : DataType} (p : Expression a b) (R : Attribute a) : Prop := + PolySafe p (fun S x => width x≤S ∧ R S x) +lemma attrSafe_controlled {a b : DataType} (p : Expression a b) (hp : Controlled p) + (R : Attribute a) : AttrSafe p R := + polySafe_of_controlled p hp _ .input (by intro S x hx; exact hx.1) +lemma attrSafe_mono {a b : DataType} (p : Expression a b) {R Q : Attribute a} + (hp : AttrSafe p Q) (h : ∀ S x,R S x → Q S x) : AttrSafe p R := + polySafe_mono p hp (by intro S x hx; exact ⟨hx.1,h S x hx.2⟩) +lemma attrSafe_compose {a b c : DataType} (p : Expression a b) (q : Expression b c) + (R : Attribute a) (Q : Attribute b) (hp : AttrSafe p R) (hq : AttrSafe q Q) + (hm : Q.Mono) + (h : ∀ {n : ℕ} (O : IndependenceOracle n) S x,R S x → ∀ y,run O p x=some y → Q S y) : + AttrSafe (p >>> q) R := by + obtain ⟨f,hf⟩ := hp + let g : SizePolynomial := .add f .input + apply polySafe_compose p q _ (fun S y => width y≤g.eval S ∧ Q (g.eval S) y) ⟨f,hf⟩ + (polySafe_reparam q _ hq g) + intro n O S x hx y hy + exact ⟨(safe_output (hf O S x hx) hy).trans (Nat.le_add_right _ _), + hm S _ (Nat.le_add_left _ _) y (h O S x hx.2 y hy)⟩ +lemma attrSafe_both {a b c : DataType} (p : Expression a b) (q : Expression a c) + (R : Attribute a) (hp : AttrSafe p R) (hq : AttrSafe q R) : AttrSafe (both p q) R := + polySafe_both p q _ hp hq +lemma attrSafe_post {a b c : DataType} (p : Expression a b) (q : Expression b c) + (R : Attribute a) (hp : AttrSafe p R) (hq : Controlled q) : AttrSafe (p >>> q) R := + polySafe_post p q _ hp hq +lemma attrSafe_pull {a b c : DataType} (p : Expression a b) (q : Expression b c) + (R : Attribute a) (Q : Attribute b) (hp : Controlled p) (hq : AttrSafe q Q) + (hm : Q.Mono) + (h : ∀ {n : ℕ} (O : IndependenceOracle n) S x,R S x → ∀ y,run O p x=some y → Q S y) : + AttrSafe (p >>> q) R := + attrSafe_compose p q R Q (attrSafe_controlled p hp R) hq hm h +lemma attrSafe_branch {a b : DataType} (p q : Expression a b) (R : Attribute a) + (hp : AttrSafe p R) (hq : AttrSafe q R) : AttrSafe (branch p q) (fun S x => R S x.2) := by + obtain ⟨f,hf⟩ := hp + obtain ⟨g,hg⟩ := hq + refine ⟨.add .input (.add f g),fun O S z hz => ?_⟩ + obtain ⟨v,x⟩ := z + have hw : width x≤S := (width_snd (a:=.bool) (b:=a) (v,x)).trans hz.1 + have hpf := safe_mono p x (hf O S x ⟨hw,hz.2⟩) (show f.eval S≤S+(f.eval S+g.eval S) by omega) + have hqf := safe_mono q x (hg O S x ⟨hw,hz.2⟩) (show g.eval S≤S+(f.eval S+g.eval S) by omega) + refine ⟨hz.1.trans (Nat.le_add_right _ _),?_,?_⟩ + · intro y hy + cases v + · exact safe_output hpf hy + · exact safe_output hqf hy + · cases v + · exact hpf + · exact hqf +lemma attrSafe_applyIf {a b : DataType} (t : Expression a .bool) (p q : Expression a b) + (R : Attribute a) (hm : R.Mono) (ht : AttrSafe t R) (hp : AttrSafe p R) (hq : AttrSafe q R) : + AttrSafe (applyIf t p q) R := by + unfold applyIf + apply attrSafe_compose _ _ R (fun S (z : Value (.prod .bool a)) => R S z.2) + (attrSafe_both t ident R ht (attrSafe_controlled ident (by cc) R)) (attrSafe_branch p q R hp hq) + · intro S T h z hz; exact hm S T h z.2 hz + · intro n O S x hx z hz + have he : x=z.2 := Option.some.inj (run_both_parts O t ident x z hz).2 + exact he ▸ hx +namespace Effect +abbrev EffectSafe {a b : DataType} (p : Effect a b) (R : Attribute a) := + AttrSafe p (fun S x => R S x.1) +lemma attr_pure {a b : DataType} (p : Expression a b) (R : Attribute a) (hm : R.Mono) + (hp : AttrSafe p R) : EffectSafe (pure p) R := by + unfold pure + apply attrSafe_both + · apply attrSafe_both + · exact attrSafe_controlled _ (by cc) _ + · apply attrSafe_pull _ p _ R (by cc) hp hm + intro n O S x hx y hy + cases hy; exact hx + · exact attrSafe_controlled _ (by cc) _ +lemma attr_precompose {a b c : DataType} (p : Expression a b) (q : Effect b c) + (R : Attribute a) (Q : Attribute b) (hp : AttrSafe p R) (hq : EffectSafe q Q) + (hmR : R.Mono) (hmQ : Q.Mono) + (h : ∀ {n : ℕ} (O : IndependenceOracle n) S x,R S x → ∀ y,run O p x=some y → Q S y) : + EffectSafe (precompose p q) R := by + unfold precompose onLeft + apply attrSafe_compose _ q _ _ ?_ hq + · intro S T h z hz; exact hmQ S T h z.1 hz + · intro n O S x hx y hy + exact h O S x.1 hx y.1 (run_both_parts O _ _ x y hy).1 + · apply attrSafe_both + · apply attrSafe_pull _ p _ R (by cc) hp hmR + intro n O S x hx y hy + cases hy; exact hx + · exact attrSafe_controlled _ (by cc) _ +lemma attr_keep {a b : DataType} (p : Effect a b) (R : Attribute a) + (hp : EffectSafe p R) : EffectSafe (keep p) R := by + unfold keep Expression.letIn + apply attrSafe_post + · exact attrSafe_both _ _ _ (attrSafe_controlled _ (by cc) _) hp + · cc +lemma attr_bind {a b c : DataType} (p : Effect a b) (q : Effect b c) + (R : Attribute a) (Q : Attribute b) (hmQ : Q.Mono) + (hp : EffectSafe p R) (hq : EffectSafe q Q) + (h : ∀ {n : ℕ} (O : IndependenceOracle n) S x bank,R S x → ∀ y rest, + run O p (x,bank)=some ((true,y),rest) → Q S y) : EffectSafe (bind p q) R := by + let T : Attribute (.prod (Optional b) BankData) := fun S z => z.1.1=true → Q S z.1.2 + have hmT : T.Mono := by intro S U h z hz hf; exact hmQ S U h z.1.2 (hz hf) + have hq' : AttrSafe (applyIf (fst >>> fst) (both (constant (optionalValue c none)) snd) + (both (fst >>> snd) snd >>> q)) T := by + + apply (show OracleSafe _ (fun _ _ S x => width x≤S ∧ T S x) from ?_) + apply oracleSafe_applyIf _ _ _ (fun _ _ S x => width x≤S ∧ T S x) + · exact oracleSafe_controlled _ (by cc) _ .input (by intro n O S x hx; exact hx.1) + · exact oracleSafe_controlled _ (by cc) _ .input (by intro n O S x hx; exact hx.1.1) + · apply oracleSafe_pull _ q _ (fun _ _ S x => width x≤S ∧ Q S x.1) (by cc) + (.mul (.constant 2) .input) + (by intro n O S x hx; exact hx.1.1.trans (by dsimp [SizePolynomial.eval]; omega)) + · exact oracleSafe_lift q _ hq + · intro n O S x hx y hy + have hv : x.1.1=true := Option.some.inj hx.2 + cases hy + refine ⟨?_,hx.1.2 hv⟩ + have hb := width_fst (a:=Optional b) (b:=BankData) x + have hs := width_snd (a:=.bool) (b:=b) x.1 + rw [width_pair (a:=b) (b:=BankData)] + have hi := hx.1.1 + rw [width_pair (a:=Optional b) (b:=BankData),width_pair (a:=.bool) (b:=b),width_bool] at hi + omega + unfold bind + apply attrSafe_compose p _ _ T hp hq' hmT + intro n O S x hx z hz hv + obtain ⟨⟨flag,y⟩,rest⟩ := z + dsimp only [Prod.fst] at hv + subst flag + exact h O S x.1 x.2 hx y rest hz +lemma attr_letIn {a b c : DataType} (p : Effect a b) (q : Effect (.prod a b) c) + (R : Attribute a) (Q : Attribute (.prod a b)) (hmQ : Q.Mono) + (hp : EffectSafe p R) (hq : EffectSafe q Q) + (h : ∀ S x y,R S x → Q S (x,y)) : EffectSafe (letIn p q) R := by + apply attr_bind (keep p) q R Q hmQ (attr_keep p R hp) hq + intro n O S x bank hx z rest hz + obtain ⟨x',y⟩ := z + have he := (run_keep_some O p x bank x' y rest hz).1 + subst x' + exact h S x y hx + +lemma attr_controlled {a b : DataType} (p : Effect a b) (hp : Controlled p) (R : Attribute a) : + EffectSafe p R := attrSafe_controlled p hp _ +lemma attr_choose {a b : DataType} (t : Expression a .bool) (p q : Effect a b) + (R : Attribute a) (hm : R.Mono) (ht : Controlled t) (hp : EffectSafe p R) (hq : EffectSafe q R) : + EffectSafe (choose t p q) R := by + apply attrSafe_applyIf _ _ _ (fun S (x : Value (.prod a BankData)) => R S x.1) (fun S T h x hx => hm S T h x.1 hx) _ hp hq + exact attrSafe_controlled _ (by cc) _ +lemma attr_letControlled {a b c : DataType} (p : Effect a b) (q : Effect (.prod a b) c) + (R : Attribute a) (hp : EffectSafe p R) (hq : Controlled q) : EffectSafe (letIn p q) R := + attr_letIn p q R (fun _ _ => True) (by unfold Attribute.Mono; intros; trivial) hp (attr_controlled q hq _) (by intros; trivial) +lemma attr_mapControlled {a b c : DataType} (p : Effect a b) (q : Expression b c) + (R : Attribute a) (hp : EffectSafe p R) (hq : Controlled q) : EffectSafe (map p q) R := + attr_bind p (pure q) R (fun _ _ => True) (by unfold Attribute.Mono; intros; trivial) hp + (attr_controlled _ (controlled_pure q hq) _) (by intros; trivial) +lemma attr_preControlled {a b c : DataType} (p : Expression a b) (q : Effect b c) + (R : Attribute a) (hm : R.Mono) (hp : AttrSafe p R) (hq : Controlled q) : EffectSafe (precompose p q) R := + attr_precompose p q R (fun _ _ => True) hp (attr_controlled q hq _) hm (by unfold Attribute.Mono; intros; trivial) (by intros; trivial) +lemma attr_withContext {a b c : DataType} (p : Effect (.prod c a) b) (R : Attribute (.prod c a)) + (hp : EffectSafe p R) : EffectSafe (withContext p) R := by + unfold withContext + exact attr_letControlled _ _ R hp (by ec) +lemma attr_retainOption {a b : DataType} (p : Effect a (Optional b)) (R : Attribute a) + (hp : EffectSafe p R) : EffectSafe (retainOption p) R := by + unfold retainOption + exact attr_letControlled _ _ R hp (by ec) +lemma attr_some {a b : DataType} (p : Effect a b) (R : Attribute a) + (hp : EffectSafe p R) : EffectSafe (someCode p) R := by + unfold someCode + exact attr_mapControlled _ _ R hp (by cc) + +lemma oracleSafe_loopStep {a : DataType} (p : Effect a a) + (R : OraclePredicate a) (hp : OracleSafe p (bankScope R)) + (g : SizePolynomial) : + OracleSafe (loopStep p) (fun n O S x => width x≤g.eval S ∧ + (x.1.1=true → R n O S x.1.2 ∧ width (a:=BankData) x.2≤S)) := by + unfold loopStep + apply oracleSafe_applyIf + · exact oracleSafe_controlled _ (by cc) _ g (by intro n O S x hx; exact hx.1) + · exact oracleSafe_controlled _ (by cc) _ g (by intro n O S x hx; exact hx.1.1) + · apply oracleSafe_pull _ p _ (bankScope R) (by cc) g + (by intro n O S x hx; exact hx.1.1) hp + intro n O S x hx y hy + have hv : x.1.1=true := Option.some.inj hx.2 + cases hy + exact hx.1.2 hv + +lemma oracleSafe_repeat_scoped {a : DataType} (p : Effect a a) + (R : OraclePredicate (.prod .nat a)) (Q : OraclePredicate a) + (hp : OracleSafe p (bankScope Q)) (g : SizePolynomial) + (hinput : ∀ n O S k x,R n O S (k,x) → k+width (a:=a) x≤g.eval S) + (hprefix : ∀ n O S k x bank,R n O S (k,x) → width (a:=BankData) bank≤S → + ∀ j,j≤k → ∀ y,iterateM (run O (loopStep p)) j (optionalValue a (some x),bank)=some y → + width (a:=.prod (Optional a) BankData) y≤g.eval S ∧ + (y.1.1=true → Q n O S y.1.2 ∧ width (a:=BankData) y.2≤S)) : + OracleSafe (repeatCode p) (bankScope R) := by + let T : OraclePredicate (.prod .nat (.prod (Optional a) BankData)) := fun n O S z => + ∃ k x bank,R n O S (k,x) ∧ width (a:=BankData) bank≤S ∧ z=(k,(optionalValue a (some x),bank)) + let W : SizePolynomial := .add (.mul (.constant 20) g) (.add (.mul (.constant 2) .input) (.constant 20)) + have htwidth : ∀ n O S x,bankScope R n O S x → width x≤W.eval S := by + intro n O S x hx + obtain ⟨⟨k,z⟩,bank⟩ := x + have hi : k+width (a:=a) z≤g.eval S := hinput n O S k z hx.1 + have h₁ := Nat.mul_le_mul_left 4 hi + have hb : width (a:=BankData) bank≤S := hx.2 + have hk := bits_length_le_value k + rw [width_pair (a:=.prod .nat a) (b:=BankData),width_pair (a:=.nat) (b:=a),width_nat] + dsimp [W,SizePolynomial.eval] + omega + unfold repeatCode + apply oracleSafe_pull _ _ (bankScope R) T (by cc) W htwidth + · apply oracleSafe_iterateNat _ T _ (oracleSafe_loopStep p Q hp g) W + · intro n O S k z hz + obtain ⟨k',x,bank,hx,hb,he⟩ := hz + cases he + have hi : k+width (a:=a) x≤g.eval S := hinput n O S k x hx + have h₁ := Nat.mul_le_mul_left 2 hi + rw [width_pair (a:=Optional a) (b:=BankData),width_pair (a:=.bool) (b:=a),width_bool] + change k+(2*(2*1+1+width (a:=a) x)+1+width (a:=BankData) bank)≤_ + have harith : ∀ (k v b G S : ℕ),k+v≤G → b≤S → + k+(2*(2*1+1+v)+1+b)≤20*G+(2*S+20) := by + intros; omega + exact harith k (width (a:=a) x) (width (a:=BankData) bank) (g.eval S) S hi hb + · intro n O S k z hz j hj y hy + obtain ⟨k',x,bank,hx,hb,he⟩ := hz + cases he + have hh := (hprefix n O S k x bank hx hb j hj y hy).1 + dsimp [W,SizePolynomial.eval] + omega + · intro n O S k z hz j hj y hy + obtain ⟨k',x,bank,hx,hb,he⟩ := hz + cases he + exact hprefix n O S k x bank hx hb j hj.le y hy + · intro n O S x hx y hy + cases hy + exact ⟨x.1.1,x.1.2,x.2,hx.1,hx.2,rfl⟩ + +lemma oracleSafe_repeat_law {a : DataType} (p : Effect a a) + (R : OraclePredicate (.prod .nat a)) (Q : OraclePredicate a) + (hp : OracleSafe p (bankScope Q)) (g : SizePolynomial) + (hinput : ∀ n O S k x,R n O S (k,x) → k+width (a:=a) x≤g.eval S) + (hlaw : ∀ n O S k x,R n O S (k,x) → ∀ j,j≤k → + ∃ (A : Type) (e : A → Value a) (t : DrawTree A), + RealizesLaw O (repeatCode p) e (j,x) t ∧ + DrawTree.All (fun v => width (e v)≤g.eval S ∧ Q n O S (e v)) t) : + OracleSafe (repeatCode p) (bankScope R) := by + let W : SizePolynomial := .add (.mul (.constant 2) g) + (.add .input (.constant (2*(width (zeroValue a)+3)+1))) + apply oracleSafe_repeat_scoped p R Q hp W + · intro n O S k x hx + have hh : k+width (a:=a) x≤g.eval S := hinput n O S k x hx + exact hh.trans (by omega : + g.eval S≤2*g.eval S+(S+(2*(width (zeroValue a)+3)+1))) + · intro n O S k x bank hx hb j hj y hy + obtain ⟨A,e,t,ht,he⟩ := hlaw n O S k x hx j hj + have hyr : run O (repeatCode p) ((j,x),bank)=some y := by rw [run_repeat]; exact hy + have hh := ht.run_bound (g.eval S) (Q n O S) he bank y hyr + have hr := ht.rest_width bank y hyr + refine ⟨?_,fun hv => ⟨hh.2 hv,hr.trans hb⟩⟩ + dsimp [W,SizePolynomial.eval] + omega + +lemma oracleSafe_mapControlled {a b c : DataType} (p : Effect a b) (q : Expression b c) + (R : OraclePredicate (.prod a BankData)) (hp : OracleSafe p R) (hq : Controlled q) : + OracleSafe (map p q) R := by + unfold map bind + apply oracleSafe_post _ _ R hp + have hh := controlled_pure q hq + cc +lemma oracleSafe_letControlled {a b c : DataType} (p : Effect a b) (q : Effect (.prod a b) c) + (R : OraclePredicate (.prod a BankData)) (hp : OracleSafe p R) (hq : Controlled q) : + OracleSafe (letIn p q) R := by + unfold letIn bind + apply oracleSafe_post _ _ R (oracleSafe_keep p R hp) + cc +lemma oracleSafe_withContext {a b c : DataType} (p : Effect (.prod c a) b) + (R : OraclePredicate (.prod (.prod c a) BankData)) (hp : OracleSafe p R) : + OracleSafe (withContext p) R := by + unfold withContext + exact oracleSafe_letControlled _ _ R hp (by ec) +lemma oracleSafe_retainOption {a b : DataType} (p : Effect a (Optional b)) + (R : OraclePredicate (.prod a BankData)) (hp : OracleSafe p R) : + OracleSafe (retainOption p) R := by + unfold retainOption + exact oracleSafe_letControlled _ _ R hp (by ec) +lemma oracleSafe_withOptionContext {a b c : DataType} (p : Effect (.prod c a) (Optional b)) + (R : OraclePredicate (.prod (.prod c a) BankData)) (hp : OracleSafe p R) : + OracleSafe (withOptionContext p) R := by + unfold withOptionContext + exact oracleSafe_letControlled _ _ R hp (by ec) +end Effect + +lemma oracleSafe_attr {a b : DataType} (p : Expression a b) (A : Attribute a) + (hA : A.Mono) (hp : AttrSafe p A) (R : OraclePredicate a) (g : SizePolynomial) + (hw : ∀ n O S x,R n O S x → width x≤g.eval S) + (ha : ∀ n O S x,R n O S x → A S x) : OracleSafe p R := by + let W : SizePolynomial := .add g .input + apply oracleSafe_mono p (oracleSafe_reparam p _ (oracleSafe_lift p _ hp) W) + intro n O S x hx + exact ⟨(hw n O S x hx).trans (Nat.le_add_right _ _), + hA S _ (Nat.le_add_left _ _) x (ha n O S x hx)⟩ +namespace Effect +lemma oracleSafe_effectAttr {a b : DataType} (p : Effect a b) (A : Attribute a) + (hA : A.Mono) (hp : EffectSafe p A) (R : OraclePredicate a) (g : SizePolynomial) + (hw : ∀ n O S x,R n O S x → width x≤g.eval S) + (ha : ∀ n O S x,R n O S x → A S x) : OracleSafe p (bankScope R) := by + apply oracleSafe_attr p (fun S x => A S x.1) (fun S T h x hx => hA S T h x.1 hx) hp _ + (.add (.mul (.constant 2) g) (.add .input (.constant 1))) + · intro n O S x hx + have hw' := hw n O S x.1 hx.1 + have hb := hx.2 + rw [width_pair (a:=a) (b:=BankData)] + dsimp [SizePolynomial.eval] + omega + · intro n O S x hx; exact ha n O S x.1 hx.1 +lemma oracleSafe_choose {a b : DataType} (test : Expression a .bool) (p q : Effect a b) + (R : OraclePredicate (.prod a BankData)) (ht : Controlled test) + (hp : OracleSafe p R) (hq : OracleSafe q R) : OracleSafe (choose test p q) R := by + obtain ⟨f,hf⟩ := oracleSafe_input_bound p R hp + apply oracleSafe_applyIf _ _ _ R + · exact oracleSafe_controlled _ (by cc) R f hf + · exact oracleSafe_mono p hp (by intro n O S x hx; exact hx.1) + · exact oracleSafe_mono q hq (by intro n O S x hx; exact hx.1) +lemma oracleSafe_letIn {a b c : DataType} (p : Effect a b) (q : Effect (.prod a b) c) + (R : OraclePredicate a) (Q : OraclePredicate (.prod a b)) + (hp : OracleSafe p (bankScope R)) (hq : OracleSafe q (bankScope Q)) + (h : ∀ n O S x bank,R n O S x → width (a:=BankData) bank≤S → ∀ y rest, + run O p (x,bank)=some ((true,y),rest) → Q n O S (x,y) ∧ width (a:=BankData) rest≤S) : + OracleSafe (letIn p q) (bankScope R) := by + apply oracleSafe_bind (keep p) q R Q (oracleSafe_keep p _ hp) hq + intro n O S x bank hx hb z rest hz + obtain ⟨x',y⟩ := z + have he := run_keep_some O p x bank x' y rest hz + rw [he.1] + exact h n O S x bank hx hb y rest he.2 + +def optionScope {a : DataType} (R : OraclePredicate a) : OraclePredicate (Optional a) := + fun n O S x => x=optionalValue a none ∨ x.1=true ∧ R n O S x.2 +lemma optionScope_encode {A : Type*} {a : DataType} (R : OraclePredicate a) + {n : ℕ} (O : IndependenceOracle n) (S : ℕ) (e : A → Value a) + (he : ∀ z,R n O S (e z)) (v : Option A) : optionScope R n O S (optionEncode e v) := by + cases v with + | none => exact Or.inl rfl + | some z => exact Or.inr ⟨rfl,he z⟩ +lemma optionScope_width {a : DataType} (R : OraclePredicate a) (g : SizePolynomial) + (hw : ∀ n O S x,R n O S x → width x≤g.eval S) : + ∀ n O S x,optionScope R n O S x → width x≤ + (.add g (.constant (width (zeroValue a)+3)) : SizePolynomial).eval S := by + intro n O S x hx + rcases hx with rfl | ⟨hflag,hx⟩ + · rw [width_pair (a:=.bool) (b:=a),width_bool] + change 2*1+1+width (zeroValue a)≤_ + dsimp [SizePolynomial.eval] + omega + · have hh := hw n O S x.2 hx + rw [width_pair (a:=.bool) (b:=a),width_bool] + dsimp [SizePolynomial.eval] + omega +lemma oracleSafe_optionContinue {a b : DataType} (p : Effect a (Optional b)) + (R : OraclePredicate a) (hp : OracleSafe p (bankScope R)) : + OracleSafe (optionContinue p) (bankScope (optionScope R)) := by + obtain ⟨f,hf⟩ := oracleSafe_input_bound p (bankScope R) hp + have hu : ∀ n O S x,R n O S x → width (a:=a) x≤f.eval S := by + intro n O S x hx + exact (width_fst (a:=a) (b:=BankData) (x,([] : Bank))).trans (hf n O S (x,[]) ⟨hx,by exact Nat.zero_le S⟩) + let W : SizePolynomial := .add (.mul (.constant 2) + (.add f (.constant (width (zeroValue a)+3)))) (.add .input (.constant 1)) + have hw : ∀ n O S x,bankScope (optionScope R) n O S x → width x≤W.eval S := by + intro n O S x hx + have hh := optionScope_width R f hu n O S x.1 hx.1 + have hb := hx.2 + rw [width_pair (a:=Optional a) (b:=BankData)] + dsimp [W,SizePolynomial.eval] at * + omega + unfold optionContinue choose + apply oracleSafe_applyIf _ _ _ _ + · exact oracleSafe_controlled _ (by cc) _ W hw + · exact oracleSafe_controlled _ (by ec) _ W (by intro n O S x hx; exact hw n O S x hx.1) + · unfold precompose onLeft + apply oracleSafe_pull _ p _ (bankScope R) (by cc) W + (by intro n O S x hx; exact hw n O S x hx.1) hp + intro n O S x hx y hy + have hv : x.1.1=true := Option.some.inj hx.2 + have he : (x.1.2,x.2)=y := Option.some.inj hy + subst y + refine ⟨?_,hx.1.2⟩ + rcases hx.1.1 with hnone | ⟨_,hh⟩ + · rw [hnone] at hv; cases hv + · exact hh +lemma oracleSafe_optionBind {a b c : DataType} (p : Effect a (Optional b)) + (q : Effect b (Optional c)) (R : OraclePredicate a) (Q : OraclePredicate b) + (hp : OracleSafe p (bankScope R)) (hq : OracleSafe q (bankScope Q)) + (h : ∀ n O S x bank,R n O S x → width (a:=BankData) bank≤S → ∀ y rest, + run O p (x,bank)=some ((true,y),rest) → optionScope Q n O S y ∧ width (a:=BankData) rest≤S) : + OracleSafe (optionBind p q) (bankScope R) := + oracleSafe_bind p _ R _ hp (oracleSafe_optionContinue q Q hq) h +end Effect + +def contextAttr (S : ℕ) (x : Value WeightContext) : Prop := x.1.1≤S ∧ x.1.2≤S +def weightAttr (S : ℕ) (x : Value WeightInput) : Prop := contextAttr S x.1 +lemma contextAttr_mono : Attribute.Mono (a:=WeightContext) contextAttr := by intro S T h x hx; exact ⟨hx.1.trans h,hx.2.trans h⟩ +lemma weightAttr_mono : Attribute.Mono (a:=WeightInput) weightAttr := by intro S T h x hx; exact contextAttr_mono S T h x.1 hx +lemma attr_weight : AttrSafe weightCode weightAttr := + polySafe_mono weightCode polySafe_weight (by intro S x hx; exact ⟨hx.1,hx.2.1,hx.2.2⟩) +def acceptanceAttr (S : ℕ) (x : Value AcceptanceInput) : Prop := contextAttr S x.1 +lemma acceptanceAttr_mono : Attribute.Mono (a:=AcceptanceInput) acceptanceAttr := by intro S T h x hx; exact contextAttr_mono S T h x.1 hx +lemma attr_acceptance : AttrSafe acceptanceCode acceptanceAttr := by + unfold acceptanceCode + apply attrSafe_post + · apply attrSafe_both + · apply attrSafe_pull _ weightCode acceptanceAttr weightAttr (by cc) attr_weight weightAttr_mono + intro n O S x hx y hy + cases hy + exact hx + · apply attrSafe_pull _ weightCode acceptanceAttr weightAttr (by cc) attr_weight weightAttr_mono + intro n O S x hx y hy + cases hy + exact hx + · cc +namespace Effect +def offerAttr (S : ℕ) (x : Value OfferInput) : Prop := weightAttr S x.1 +lemma offerAttr_mono : Attribute.Mono (a:=OfferInput) offerAttr := by intro S T h x hx; exact weightAttr_mono S T h x.1 hx +lemma attr_offerCore : EffectSafe offerCore offerAttr := by + unfold offerCore + apply attr_choose _ _ _ offerAttr offerAttr_mono (by have h := controlled_chainCode; cc) + · exact attr_controlled _ (by ec) _ + · apply attr_letControlled + · apply attr_preControlled _ bernoulliCode offerAttr offerAttr_mono _ controlled_bernoulli + apply attrSafe_pull acceptancePrep acceptanceCode offerAttr acceptanceAttr (by unfold acceptancePrep; cc) + attr_acceptance acceptanceAttr_mono + intro n O S x hx y hy + cases hy + exact hx + · ec +def pairOfferAttr (S : ℕ) (x : Value (.prod WeightInput NN)) : Prop := weightAttr S x.1 +lemma pairOfferAttr_mono : Attribute.Mono (a:=(.prod WeightInput NN)) pairOfferAttr := by intro S T h x hx; exact weightAttr_mono S T h x.1 hx +lemma attr_offer : EffectSafe offerCode pairOfferAttr := by + have he := controlled_exchangeSet + unfold offerCode + apply attr_precompose _ _ pairOfferAttr offerAttr + (attrSafe_controlled _ (by cc) _) attr_offerCore pairOfferAttr_mono offerAttr_mono + intro n O S x hx y hy + have hh : x.1=y.1 := Option.some.inj (run_both_parts O _ _ x y hy).1 + change weightAttr S y.1 + rw [←hh] + exact hx +lemma attr_activeStep : EffectSafe activeStepCode weightAttr := by + unfold activeStepCode + apply attr_letIn _ _ weightAttr pairOfferAttr pairOfferAttr_mono + (attr_controlled _ (by have h := controlled_proposal; ec) _) attr_offer + intro S x y hx + exact hx +lemma attr_step : EffectSafe stepCode weightAttr := by + unfold stepCode + apply attr_letIn _ _ weightAttr (fun S x => weightAttr S x.1) + (fun S T h (x : Value (.prod WeightInput .bool)) hx => weightAttr_mono S T h x.1 hx) + (attr_controlled _ (by have h := controlled_bernoulli; ec) _) + · apply attr_choose _ _ _ _ (fun S T h (x : Value (.prod WeightInput .bool)) hx => weightAttr_mono S T h x.1 hx) (by cc) + · apply attr_precompose _ _ _ weightAttr (attrSafe_controlled _ (by cc) _) attr_activeStep + (fun S T h (x : Value (.prod WeightInput .bool)) hx => weightAttr_mono S T h x.1 hx) weightAttr_mono + intro n O S x hx y hy + cases hy; exact hx + · exact attr_controlled _ (by ec) _ + · intro S x y hx; exact hx +end Effect + +open scoped Classical +lemma width_stateEncode {n : ℕ} (T : Set (Fin n⊕Fin n)) : width (a:=StateData) (stateEncode T)=3*n+1 := by + rw [width_pair (a:=.word) (b:=.word),width_word,width_word,stateEncode_left_length,stateEncode_right_length] + omega +lemma width_sampleEncode {n : ℕ} (xs : List (Set (Fin n⊕Fin n))) : + width (a:=SampleData) (sampleEncode xs)=xs.length*(6*n+4) := by + induction xs with + | nil => change width (a:=.list StateData) []=0*(6*n+4); rw [width_nil,Nat.zero_mul] + | cons x xs ih => + change width (a:=.list StateData) (stateEncode x::sampleEncode xs)=_ + rw [width_cons (a:=StateData),width_stateEncode,ih,List.length_cons,Nat.add_mul,Nat.one_mul] + omega +lemma width_observation {n N : ℕ} (v : PhaseSample n N) : + width (a:=SampleData) (sampleEncode (observedSets n N v))≤(N+1)*(6*n+4) := by + rw [width_sampleEncode] + have hl : (observedSets n N v).length=N-1+1 := by + simp only [observedSets,List.length_map] + exact FiniteChain.Sample.toList_length v + rw [hl] + exact Nat.mul_le_mul_right _ (by omega) +lemma width_history_observed {n N : ℕ} (h : List (PhaseSample n N)) : + width (a:=HistoryData) (historyEncode (h.map (observedSets n N)))≤h.length*(2*((N+1)*(6*n+4))+2) := by + unfold historyEncode + apply (width_list_le _ _ ?_).trans + · simp only [List.length_map]; rfl + · intro x hx + obtain ⟨v,hv,rfl⟩ := List.mem_map.mp hx + obtain ⟨u,hu,rfl⟩ := List.mem_map.mp hv + exact width_observation u + +open Expression +open Effect +open scoped Classical + +structure SamplerModel (n : ℕ) (O : IndependenceOracle n) where + M₁ : Matroid (Fin n) + M₂ : Matroid (Fin n) + exact : ExactOracles M₁ M₂ O + ground₁ : M₁.E=Set.univ + ground₂ : M₂.E=Set.univ + positive : 0 + ∃ (m : SamplerModel n O),m.Bounded S ∧ ∃ h : m.Hist,h.length≤S ∧ + ∃ j,j≤S ∧ ∃ x : ChainIndex (pairedSlots n),z=m.weightValue h j x +lemma weightScope_width : ∀ n O S z,weightScope n O S z → width z≤(sourceWidthPoly 100).eval S := by + intro n O S z hz + obtain ⟨m,hm,h,hh,j,hj,x,rfl⟩ := hz + rw [eval_sourceWidthPoly] + exact m.width_weightValue S hm h hh j hj x +namespace Effect +lemma safe_step : OracleSafe stepCode (bankScope weightScope) := by + apply oracleSafe_effectAttr stepCode weightAttr weightAttr_mono attr_step weightScope + (sourceWidthPoly 100) weightScope_width + intro n O S z hz + obtain ⟨m,hm,h,hh,j,hj,x,rfl⟩ := hz + exact ⟨hm.2.1,hj⟩ +lemma attr_storedStep : EffectSafe storedStepCode weightAttr := by + unfold storedStepCode + apply attr_precompose storedStepPrep stepCode weightAttr weightAttr + (attrSafe_controlled _ (by unfold storedStepPrep; cc) _) attr_step weightAttr_mono weightAttr_mono + intro n O S x hx y hy + unfold storedStepPrep at hy + have he := run_both_parts O _ _ x y hy + have hc := run_both_parts O _ _ x y.1 he.1 + have hp : x.1.1=y.1.1 := Option.some.inj hc.1 + change x.1.1.1≤S ∧ x.1.1.2≤S at hx + change y.1.1.1≤S ∧ y.1.1.2≤S + rw [←hp]; exact hx +lemma safe_storedStep : OracleSafe storedStepCode (bankScope weightScope) := by + apply oracleSafe_effectAttr storedStepCode weightAttr weightAttr_mono attr_storedStep weightScope + (sourceWidthPoly 100) weightScope_width + intro n O S z hz + obtain ⟨m,hm,h,hh,j,hj,x,rfl⟩ := hz + exact ⟨hm.2.1,hj⟩ +end Effect +end MachineCode + +namespace DrawTree +lemma all_of_forall {A : Type*} (t : DrawTree A) (P : A → Prop) (h : ∀ x,P x) : All P t := by + induction t with + | leaf x => exact h x + | draw n k ih => exact ih +end DrawTree +namespace MachineCode + +open Expression +open scoped Classical +namespace Effect +lemma oracleSafe_hitStep {a : DataType} (step : Effect a a) (test : Expression a .bool) + (Q : OraclePredicate a) (hs : OracleSafe step (bankScope Q)) (ht : Controlled test) + (g : SizePolynomial) (hw : ∀ n O S x,Q n O S x → width x≤g.eval S) : + OracleSafe (hitStepCode step test) (bankScope (fun n O S x => Q n O S x.1)) := by + let W : SizePolynomial := .add (.mul (.constant 2) g) (.constant 2) + have hw' : ∀ n O S x,Q n O S x.1 → width (a:=.prod a .bool) x≤W.eval S := by + intro n O S x hx + have hh := hw n O S x.1 hx + rw [width_pair (a:=a) (b:=.bool),width_bool] + dsimp [W,SizePolynomial.eval] + omega + unfold hitStepCode + apply oracleSafe_choose _ _ _ _ (by cc) + · apply oracleSafe_mapControlled _ _ _ _ (by cc) + exact oracleSafe_precompose fst step _ Q + (oracleSafe_controlled _ (by cc) _ W hw') hs + (by intro n O S x hx y hy; cases hy; exact hx) + · exact oracleSafe_pure ident _ (oracleSafe_controlled _ (by cc) _ W hw') + +abbrev SearchData := DataType.prod WeightInput .bool +def searchScope : OraclePredicate SearchData := fun n O S x => weightScope n O S x.1 +def searchInputScope : OraclePredicate (.prod .nat SearchData) := fun n O S x => + x.1≤S+1 ∧ ∃ (m : SamplerModel n O),m.Bounded S ∧ ∃ h : m.Hist,h.length≤S ∧ + ∃ j,j≤S ∧ ∃ u : SearchState (ChainIndex (pairedSlots n)) (plainPredicate (pairedSlots n)), + x.2=searchEncode (m.weightValue h j) u +lemma searchScope_width : ∀ n O S x,searchScope n O S x → width x≤(sourceWidthPoly 202).eval S := by + intro n O S x hx + have hh := weightScope_width n O S x.1 hx + rw [eval_sourceWidthPoly] at hh ⊢ + rw [width_pair (a:=WeightInput) (b:=.bool),width_bool] + have hp : 1≤(S+1)^3 := (Nat.succ_le_succ (Nat.zero_le S)).trans (Nat.le_self_pow (by decide) _) + omega +lemma searchEncode_scope {n : ℕ} {O : IndependenceOracle n} (m : SamplerModel n O) + (S : ℕ) (hm : m.Bounded S) (h : m.Hist) (hh : h.length≤S) (j : ℕ) (hj : j≤S) + (u : SearchState (ChainIndex (pairedSlots n)) (plainPredicate (pairedSlots n))) : + searchScope n O S (searchEncode (m.weightValue h j) u) := by + cases u with + | inl x => exact ⟨m,hm,h,hh,j,hj,x,rfl⟩ + | inr x => exact ⟨m,hm,h,hh,j,hj,x.val,rfl⟩ +lemma safe_repeatHit : OracleSafe + (repeatCode (hitStepCode (withContext storedStepCode) (snd >>> Expression.plainCode))) + (bankScope searchInputScope) := by + have hs : OracleSafe (withContext storedStepCode) (bankScope weightScope) := + oracleSafe_withContext storedStepCode _ safe_storedStep + apply oracleSafe_repeat_law _ searchInputScope searchScope + (oracleSafe_hitStep _ _ weightScope hs (by cc) _ weightScope_width) (sourceWidthPoly 204) + · intro n O S k x hx + obtain ⟨hk,m,hm,h,hh,j,hj,u,rfl⟩ := hx + have hw := searchScope_width n O S _ (searchEncode_scope m S hm h hh j hj u) + rw [eval_sourceWidthPoly] at hw ⊢ + have hp : S+1≤(S+1)^3 := Nat.le_self_pow (by decide) _ + have harith : ∀ (k v T P : ℕ), k≤T → T≤P → v≤202*P → k+v≤204*P := by intros; omega + exact harith k _ (S+1) _ hk hp hw + · intro n O S k x hx l hl + obtain ⟨hk,m,hm,h,hh,j,hj,u,rfl⟩ := hx + let f := canonicalStepTree n m.positive m.rank O m.samples h j + let e := m.weightValue h j + let P := plainPredicate (pairedSlots n) + refine ⟨SearchState (ChainIndex (pairedSlots n)) P,searchEncode e, + treeRepeat (searchStep f P) l u,?_,?_⟩ + · apply law_repeat O _ _ _ _ l u + exact law_hitStep O (withContext storedStepCode) _ e f P + (fun T => law_withContext O storedStepCode _ (m.weightContext h j) _ _ + (storedStepCode_source m.M₁ m.M₂ O m.exact m.ground₁ m.ground₂ m.rank m.samples h j m.positive T)) + (fun T => MachineCode.plainCode_source O T.val) + · apply DrawTree.all_of_forall + intro v + have hv := searchEncode_scope m S hm h hh j hj v + refine ⟨?_,hv⟩ + have hw := searchScope_width n O S _ hv + rw [eval_sourceWidthPoly] at hw ⊢ + exact hw.trans (Nat.mul_le_mul_right _ (by decide : 202≤204)) + +def traceScope : OraclePredicate (.prod .nat WeightInput) := fun n O S x => + x.1≤S+1 ∧ weightScope n O S x.2 +lemma traceScope_width : ∀ n O S x,traceScope n O S x → width x≤(sourceWidthPoly 110).eval S := by + intro n O S x hx + have hk := (bits_length_le_value x.1).trans hx.1 + have hh := weightScope_width n O S x.2 hx.2 + rw [eval_sourceWidthPoly] at hh ⊢ + rw [width_pair (a:=.nat) (b:=WeightInput),width_nat] + have hp : S+1≤(S+1)^3 := Nat.le_self_pow (by decide) _ + omega +lemma safe_trace : OracleSafe traceCode (bankScope traceScope) := by + unfold traceCode + apply oracleSafe_mapControlled _ _ _ _ (by cc) + unfold hittingCode + apply oracleSafe_precompose _ _ traceScope searchInputScope + (oracleSafe_controlled _ (by cc) _ _ traceScope_width) + (oracleSafe_mapControlled _ _ _ safe_repeatHit (by unfold hitFinish; cc)) + intro n O S x hx y hy + have he : (x.1,(x.2,false))=y := Option.some.inj hy + subst y + obtain ⟨m,hm,h,hh,j,hj,T,he⟩ := hx.2 + exact ⟨hx.1,m,hm,h,hh,j,hj,Sum.inl T,by rw [he]; rfl⟩ +end Effect + +open Expression +lemma attr_rangeCode : AttrSafe rangeCode (fun S k => k≤S) := + polySafe_mono rangeCode polySafe_rangeCode (by intro S k hk; exact hk.2) +lemma attr_powCode : AttrSafe powCode (fun S x => x.2≤S) := by + apply polySafe_mono powCode polySafe_powCode + intro S x hx + exact ⟨(width_fst (a:=.nat) (b:=.nat) x).trans hx.1,hx.2⟩ +lemma attr_paddedBits : AttrSafe paddedBitsCode (fun S x => x.1≤S) := by + unfold paddedBitsCode + apply attrSafe_post + · apply attrSafe_both + · apply attrSafe_pull fst rangeCode _ _ (by cc) attr_rangeCode + (fun S T h k hk => hk.trans h) + intro n O S x hx y hy + cases hy; exact hx + · exact attrSafe_controlled _ (by cc) _ + · cc +lemma attr_plainDecode : AttrSafe plainDecodeCode (fun S x => x.1≤S) := by + unfold plainDecodeCode + exact attrSafe_post _ _ _ attr_paddedBits (by cc) +namespace Effect +lemma attr_plain : EffectSafe plainCode (fun S x => x≤S) := by + unfold plainCode + apply attr_letIn (a:=.nat) (b:=.nat) (c:=StateData) _ _ + (fun (S : ℕ) (x : ℕ) => x≤S) (fun (S : ℕ) (x : ℕ × ℕ) => x.1≤S) + (fun S T h x hx => hx.trans h) + · apply attr_preControlled _ _ _ (fun S T h x hx => hx.trans h) _ controlled_draw + apply attrSafe_pull _ powCode _ _ (by cc) attr_powCode + (fun S T h x hx => hx.trans h) + intro n O S x hx y hy + cases hy + exact hx + · exact attr_pure plainDecodeCode _ (fun S T h x hx => hx.trans h) attr_plainDecode + · intro S x y hx + exact hx +lemma safe_plain : OracleSafe plainCode (bankScope (fun _ _ S x => x≤S)) := by + apply oracleSafe_effectAttr plainCode _ (fun S T h x hx => hx.trans h) attr_plain _ .input + · intro n O S x hx + exact (bits_length_le_value x).trans hx + · intros; assumption +end Effect + +open Expression +open scoped Classical +namespace SamplerModel +lemma Bounded.mono {n : ℕ} {O : IndependenceOracle n} {m : SamplerModel n O} + {S T : ℕ} (hm : m.Bounded S) (h : S≤T) : m.Bounded T := + ⟨hm.1.trans h,hm.2.1.trans h,hm.2.2.1.trans h,hm.2.2.2.1.trans h, + hm.2.2.2.2.1.trans h,hm.2.2.2.2.2.trans h⟩ +end SamplerModel +namespace Effect +def restartScope : OraclePredicate RestartState := fun n O S z => + ∃ (m : SamplerModel n O),m.Bounded S ∧ ∃ h : m.Hist,h.length≤S ∧ + ∃ j,j≤S ∧ ∃ x : PlainIndex (pairedSlots n),z=m.restartValue h j x +lemma restartScope_width : ∀ n O S z,restartScope n O S z → width z≤(sourceWidthPoly 200).eval S := by + intro n O S z hz + obtain ⟨m,hm,h,hh,j,hj,x,rfl⟩ := hz + rw [eval_sourceWidthPoly] + exact m.width_restartValue S hm h hh j hj x +lemma safe_traceAt : OracleSafe traceAtCode (bankScope restartScope) := by + unfold traceAtCode + apply oracleSafe_precompose traceAtPrep traceCode restartScope traceScope + (oracleSafe_controlled _ (by unfold traceAtPrep; cc) _ _ restartScope_width) safe_trace + intro n O S z hz y hy + obtain ⟨m,hm,h,hh,j,hj,x,rfl⟩ := hz + have he : (m.cap+1,m.weightValue h j x.val)=y := Option.some.inj hy + subst y + exact ⟨Nat.add_le_add_right hm.2.2.2.2.1 1,m,hm,h,hh,j,hj,x.val,rfl⟩ + +def traceRepeatScope : OraclePredicate (.prod .nat (Optional RestartState)) := fun n O S z => + z.1≤S ∧ ∃ (m : SamplerModel n O),m.Bounded S ∧ ∃ h : m.Hist,h.length≤S ∧ + ∃ j,j≤S ∧ ∃ x : PlainIndex (pairedSlots n),z.2=optionEncode (m.restartValue h j) (some x) +def restartOptWidth : SizePolynomial := + .add (sourceWidthPoly 200) (.constant (width (zeroValue RestartState)+3)) +lemma restartOptWidth_bound {n : ℕ} {O : IndependenceOracle n} (m : SamplerModel n O) + (S : ℕ) (hm : m.Bounded S) (h : m.Hist) (hh : h.length≤S) (j : ℕ) (hj : j≤S) + (v : Option (PlainIndex (pairedSlots n))) : + width (optionEncode (m.restartValue h j) v)≤restartOptWidth.eval S := by + have hw := width_optionEncode (m.restartValue h j) v ((sourceWidthPoly 200).eval S) + (fun x => by rw [eval_sourceWidthPoly]; exact m.width_restartValue S hm h hh j hj x) + change _ ≤ (sourceWidthPoly 200).eval S + (width (zeroValue RestartState)+3) + omega +lemma safe_repeatTrace : OracleSafe (repeatCode (optionContinue (withOptionContext traceAtCode))) + (bankScope traceRepeatScope) := by + apply oracleSafe_repeat_law _ traceRepeatScope (optionScope restartScope) + (oracleSafe_optionContinue _ _ (oracleSafe_withOptionContext _ _ safe_traceAt)) + (.add .input restartOptWidth) + · intro n O S k z hz + obtain ⟨hk,m,hm,h,hh,j,hj,x,rfl⟩ := hz + exact Nat.add_le_add hk (restartOptWidth_bound m S hm h hh j hj _) + · intro n O S k z hz l hl + obtain ⟨hk,m,hm,h,hh,j,hj,x,rfl⟩ := hz + let e := m.restartValue h j + let f := canonicalTraceTree n m.positive m.rank O m.samples h j m.cap + let F : Option (PlainIndex (pairedSlots n)) → DrawTree (Option (PlainIndex (pairedSlots n))) := + fun u => match u with | none => .leaf none | some y => f y + refine ⟨Option (PlainIndex (pairedSlots n)),optionEncode e,treeRepeat F l (some x),?_,?_⟩ + · apply law_repeat O _ _ F _ l (some x) + intro u + change RealizesLaw O (optionContinue (withOptionContext traceAtCode)) (optionEncode e) + (optionEncode e u) (match u with | none => .leaf none | some y => f y) + cases u <;> exact law_optionContinue O (withOptionContext traceAtCode) e e f _ (fun y => + law_withOptionContext O traceAtCode (fun x : PlainIndex (pairedSlots n) => stateEncode x.val.val) + (m.restartContext h,j) (stateEncode y.val.val) (f y) + (traceAtCode_source m.M₁ m.M₂ O m.exact m.ground₁ m.ground₂ + m.rank m.samples m.phases h m.positive m.cap j y)) + · apply DrawTree.all_of_forall + intro v + refine ⟨(restartOptWidth_bound m S hm h hh j hj v).trans (Nat.le_add_left _ _),?_⟩ + apply optionScope_encode + intro y + exact ⟨m,hm,h,hh,j,hj,y,rfl⟩ + +def iterateTraceScope : OraclePredicate (.prod .nat RestartState) := fun n O S z => + z.1≤S ∧ restartScope n O S z.2 +lemma iterateTraceScope_width : ∀ n O S z,iterateTraceScope n O S z → + width z≤(SizePolynomial.add (.mul (.constant 2) .input) (.add (.constant 1) (sourceWidthPoly 200))).eval S := by + intro n O S z hz + have hk := (bits_length_le_value z.1).trans hz.1 + have hh := restartScope_width n O S z.2 hz.2 + rw [width_pair (a:=.nat) (b:=RestartState),width_nat] + change _ ≤ 2*S+(1+(sourceWidthPoly 200).eval S) + omega +lemma safe_iterateTrace : OracleSafe (iterateCode (withOptionContext traceAtCode)) + (bankScope iterateTraceScope) := by + unfold iterateCode + apply oracleSafe_precompose _ _ iterateTraceScope traceRepeatScope + (oracleSafe_controlled _ (by cc) _ _ iterateTraceScope_width) safe_repeatTrace + intro n O S z hz y hy + have he : (z.1,(true,z.2))=y := Option.some.inj hy + subst y + obtain ⟨m,hm,h,hh,j,hj,x,he⟩ := hz.2 + exact ⟨hz.1,m,hm,h,hh,j,hj,x,by rw [he]; rfl⟩ +lemma safe_restartTick : OracleSafe restartTick (bankScope restartScope) := by + unfold restartTick + apply oracleSafe_precompose restartTickPrep _ restartScope + (fun n O S z => iterateTraceScope n O (S+1) z) + (oracleSafe_controlled _ (by unfold restartTickPrep; cc) _ _ restartScope_width) + · apply oracleSafe_mono _ (oracleSafe_reparam _ _ safe_iterateTrace (.add .input (.constant 1))) + intro n O S z hz + exact ⟨hz.1,hz.2.trans (Nat.le_add_right S 1)⟩ + · intro n O S z hz y hy + obtain ⟨m,hm,h,hh,j,hj,x,rfl⟩ := hz + have he : (m.tau,m.restartValue h (j+1) x)=y := Option.some.inj hy + subst y + exact ⟨hm.2.2.2.2.2.trans (Nat.le_add_right S 1),m,hm.mono (Nat.le_add_right S 1), + h,hh.trans (Nat.le_add_right S 1),j+1,Nat.add_le_add_right hj 1,x,rfl⟩ +end Effect + +open Expression +open scoped Classical +namespace SamplerModel +noncomputable def restartInput {n : ℕ} {O : IndependenceOracle n} (m : SamplerModel n O) + (h : m.Hist) (k : ℕ) : Value RestartInput := (n,(k,m.restartContext h)) +lemma width_restartInput {n : ℕ} {O : IndependenceOracle n} (m : SamplerModel n O) + (S : ℕ) (hm : m.Bounded S) (h : m.Hist) (hh : h.length≤S) (k : ℕ) (hk : k≤S) : + width (m.restartInput h k)≤(sourceWidthPoly 210).eval S := by + let x : PlainIndex (pairedSlots n) := Classical.choice + (plainIndex_nonempty (pairedSlots n) (pairedSlots_fresh n) (pairedSlots_cover n)) + have hw := m.width_restartValue S hm h hh 0 (Nat.zero_le S) x + have hc : width (m.restartContext h)≤200*(S+1)^3 := + (width_fst (a:=RestartContext) (b:=.nat) (m.restartContext h,0)).trans + ((width_fst (a:=.prod RestartContext .nat) (b:=StateData) (m.restartValue h 0 x)).trans hw) + have hn := (bits_length_le_value n).trans hm.1 + have hb := (bits_length_le_value k).trans hk + rw [eval_sourceWidthPoly,restartInput,width_pair (a:=.nat) (b:=.prod .nat RestartContext), + width_pair (a:=.nat) (b:=RestartContext),width_nat,width_nat] + have hp : S+1≤(S+1)^3 := Nat.le_self_pow (by decide) _ + omega +end SamplerModel +namespace Effect +def restartRepeatScope : OraclePredicate (.prod .nat (Optional RestartState)) := fun n O S z => + z.1≤S ∧ ∃ (m : SamplerModel n O),m.Bounded S ∧ ∃ h : m.Hist,h.length≤S ∧ + ∃ x : PlainIndex (pairedSlots n),z.2=optionEncode (m.restartValue h 0) (some x) +lemma safe_restartRepeat : OracleSafe (repeatCode (optionContinue restartTick)) + (bankScope restartRepeatScope) := by + apply oracleSafe_repeat_law _ restartRepeatScope (optionScope restartScope) + (oracleSafe_optionContinue _ _ safe_restartTick) (.add .input restartOptWidth) + · intro n O S k z hz + obtain ⟨hk,m,hm,h,hh,x,rfl⟩ := hz + exact Nat.add_le_add hk (restartOptWidth_bound m S hm h hh 0 (Nat.zero_le S) _) + · intro n O S k z hz j hj + obtain ⟨hk,m,hm,h,hh,x,rfl⟩ := hz + let f := fun l => DrawTree.iterate (canonicalTraceTree n m.positive m.rank O m.samples h l m.cap) m.tau + refine ⟨Option (PlainIndex (pairedSlots n)),optionEncode (m.restartValue h j), + phaseRepeat f j x,?_,?_⟩ + · apply law_phaseRepeat O restartTick (m.restartValue h) f _ j x + intro l y + exact restartTick_source m.M₁ m.M₂ O m.exact m.ground₁ m.ground₂ + m.rank m.samples m.phases h m.positive m.cap l y + · apply DrawTree.all_of_forall + intro v + refine ⟨(restartOptWidth_bound m S hm h hh j (hj.trans hk) v).trans (Nat.le_add_left _ _),?_⟩ + apply optionScope_encode + intro y + exact ⟨m,hm,h,hh,j,hj.trans hk,y,rfl⟩ +def restartInputScope : OraclePredicate RestartInput := fun n O S z => + ∃ (m : SamplerModel n O),m.Bounded S ∧ ∃ h : m.Hist,h.length≤S ∧ + ∃ k,k≤S ∧ z=m.restartInput h k +lemma restartInputScope_width : ∀ n O S z,restartInputScope n O S z → width z≤(sourceWidthPoly 210).eval S := by + intro n O S z hz + obtain ⟨m,hm,h,hh,k,hk,rfl⟩ := hz + exact m.width_restartInput S hm h hh k hk +def restartAfterPlainScope : OraclePredicate (.prod RestartInput StateData) := fun n O S z => + ∃ (m : SamplerModel n O),m.Bounded S ∧ ∃ h : m.Hist,h.length≤S ∧ + ∃ k,k≤S ∧ ∃ x : PlainIndex (pairedSlots n),z=(m.restartInput h k,stateEncode x.val.val) +lemma restartAfterPlainScope_width : ∀ n O S z,restartAfterPlainScope n O S z → + width z≤(sourceWidthPoly 430).eval S := by + intro n O S z hz + obtain ⟨m,hm,h,hh,k,hk,x,rfl⟩ := hz + have hw := m.width_restartInput S hm h hh k hk + rw [width_pair (a:=RestartInput) (b:=StateData),width_stateEncode,eval_sourceWidthPoly] + rw [eval_sourceWidthPoly] at hw + have hn := hm.1 + have hp : S+1≤(S+1)^3 := Nat.le_self_pow (by decide) _ + omega +lemma safe_restart : OracleSafe restartCode (bankScope restartInputScope) := by + unfold restartCode + apply oracleSafe_mapControlled _ _ _ _ (by cc) + apply oracleSafe_letIn _ _ restartInputScope restartAfterPlainScope + · apply oracleSafe_precompose fst plainCode restartInputScope (fun _ _ S x => x≤S) + (oracleSafe_controlled _ (by cc) _ _ restartInputScope_width) safe_plain + intro n O S z hz y hy + obtain ⟨m,hm,h,hh,k,hk,rfl⟩ := hz + cases hy + exact hm.1 + · apply oracleSafe_precompose restartPrep _ restartAfterPlainScope restartRepeatScope + (oracleSafe_controlled _ (by unfold restartPrep; cc) _ _ restartAfterPlainScope_width) safe_restartRepeat + intro n O S z hz y hy + obtain ⟨m,hm,h,hh,k,hk,x,rfl⟩ := hz + have he : (k,optionEncode (m.restartValue h 0) (some x))=y := Option.some.inj hy + subst y + exact ⟨hk,m,hm,h,hh,x,rfl⟩ + · intro n O S z bank hz hb y rest hy + obtain ⟨m,hm,h,hh,k,hk,rfl⟩ := hz + have hl := law_precompose O fst plainCode _ (m.restartInput h k) n _ rfl (plainCode_source O) + obtain ⟨x,he,_,hr⟩ := hl.output_some_all (fun _ => True) (DrawTree.all_of_forall _ _ (by intros; trivial)) bank y rest hy + exact ⟨⟨m,hm,h,hh,k,hk,x,by rw [he]⟩,hr.trans hb⟩ +end Effect + +namespace SamplerModel +noncomputable def phaseState {n : ℕ} {O : IndependenceOracle n} (m : SamplerModel n O) + (h : m.Hist) (x : ChainIndex (pairedSlots n)) : Value (.prod PhaseInput StateData) := + (m.phaseValue h,stateEncode x.val) +lemma width_phaseState {n : ℕ} {O : IndependenceOracle n} (m : SamplerModel n O) + (S : ℕ) (hm : m.Bounded S) (h : m.Hist) (hh : h.length≤S) (x : ChainIndex (pairedSlots n)) : + width (m.phaseState h x)≤(sourceWidthPoly 210).eval S := by + have hw := m.width_phaseValue S hm h hh + rw [phaseState,width_pair (a:=PhaseInput) (b:=StateData),width_stateEncode,eval_sourceWidthPoly] + have hn := hm.1 + have hp : S+1≤(S+1)^3 := Nat.le_self_pow (by decide) _ + omega +end SamplerModel +namespace Effect +def phaseScope : OraclePredicate PhaseInput := fun n O S z => + ∃ (m : SamplerModel n O),m.Bounded S ∧ ∃ h : m.Hist,h.length≤S ∧ z=m.phaseValue h +lemma phaseScope_width : ∀ n O S z,phaseScope n O S z → width z≤(sourceWidthPoly 100).eval S := by + intro n O S z hz + obtain ⟨m,hm,h,hh,rfl⟩ := hz + rw [eval_sourceWidthPoly] + exact m.width_phaseValue S hm h hh +lemma safe_phaseRestart : OracleSafe phaseRestartCode (bankScope phaseScope) := by + unfold phaseRestartCode + apply oracleSafe_precompose phaseRestartPrep restartCode phaseScope restartInputScope + (oracleSafe_controlled _ (by unfold phaseRestartPrep; cc) _ _ phaseScope_width) safe_restart + intro n O S z hz y hy + obtain ⟨m,hm,h,hh,rfl⟩ := hz + have he : run O phaseRestartPrep (m.phaseValue h)=some (m.restartInput h h.length) := by + simp only [phaseRestartPrep,SamplerModel.phaseValue,params,run_both,run_compose,run_fst,run_snd, + Option.bind_some,Option.map_some] + rw [run_listLength] + simp only [SamplerModel.histValue,historyEncode,List.length_map] + rfl + have hey := Option.some.inj (he.symm.trans hy) + subst y + exact ⟨m,hm,h,hh,h.length,hh,rfl⟩ +lemma safe_start : OracleSafe startCode (bankScope phaseScope) := by + unfold startCode + exact oracleSafe_mapControlled _ _ _ safe_phaseRestart (by cc) +def phaseStateScope : OraclePredicate (.prod PhaseInput StateData) := fun n O S z => + ∃ (m : SamplerModel n O),m.Bounded S ∧ ∃ h : m.Hist,h.length≤S ∧ + ∃ x : ChainIndex (pairedSlots n),z=m.phaseState h x +lemma phaseStateScope_width : ∀ n O S z,phaseStateScope n O S z → width z≤(sourceWidthPoly 210).eval S := by + intro n O S z hz + obtain ⟨m,hm,h,hh,x,rfl⟩ := hz + exact m.width_phaseState S hm h hh x +lemma safe_phaseStep : OracleSafe phaseStepCode (bankScope phaseStateScope) := by + unfold phaseStepCode + apply oracleSafe_precompose phaseStepPrep storedStepCode phaseStateScope weightScope + (oracleSafe_controlled _ (by unfold phaseStepPrep; cc) _ _ phaseStateScope_width) safe_storedStep + intro n O S z hz y hy + obtain ⟨m,hm,h,hh,x,rfl⟩ := hz + have he : run O phaseStepPrep (m.phaseState h x)=some (m.weightValue h h.length x) := by + simp only [phaseStepPrep,SamplerModel.phaseState,SamplerModel.phaseValue,params,run_both,run_compose,run_fst,run_snd, + Option.bind_some,Option.map_some] + rw [run_listLength] + simp only [SamplerModel.histValue,historyEncode,List.length_map] + rfl + have hey := Option.some.inj (he.symm.trans hy) + subst y + exact ⟨m,hm,h,hh,h.length,hh,x,rfl⟩ + +lemma repeatSample_length {X : Type*} (f : X → DrawTree X) (k : ℕ) (acc : List X) (x : X) : + DrawTree.All (fun s => s.1.length=acc.length+k) (treeRepeat (sampleTickTree f) k (acc,x)) := by + induction k generalizing acc x with + | zero => exact Nat.add_zero _ |>.symm + | succ k ih => + unfold treeRepeat sampleTickTree + rw [DrawTree.map_bind] + apply DrawTree.all_bind_of_all (f x) _ (fun _ => True) _ (DrawTree.all_of_forall _ _ (by intros; trivial)) + intro y _ + exact (ih (x::acc) y).mono (by intro s hs; simpa only [List.length_cons,Nat.add_assoc,Nat.add_comm 1 k] using hs) + +abbrev SampleNodeData := DataType.prod PhaseInput StateData +abbrev SampleAccData := DataType.prod (.list SampleNodeData) SampleNodeData +noncomputable def sampleAccValue {n : ℕ} {O : IndependenceOracle n} (m : SamplerModel n O) + (h : m.Hist) (s : List (ChainIndex (pairedSlots n)) × ChainIndex (pairedSlots n)) : Value SampleAccData := + (s.1.map (m.phaseState h),m.phaseState h s.2) +def sampleAccWidth : SizePolynomial := + .add (.mul (.constant 2) (.mul .input (.add (.mul (.constant 2) (sourceWidthPoly 210)) (.constant 2)))) + (.add (.constant 1) (sourceWidthPoly 210)) +lemma sampleAccValue_width {n : ℕ} {O : IndependenceOracle n} (m : SamplerModel n O) + (S : ℕ) (hm : m.Bounded S) (h : m.Hist) (hh : h.length≤S) + (acc : List (ChainIndex (pairedSlots n))) (ha : acc.length≤S) (x : ChainIndex (pairedSlots n)) : + width (sampleAccValue m h (acc,x))≤ sampleAccWidth.eval S := by + have hw : ∀ y,width (m.phaseState h y)≤(sourceWidthPoly 210).eval S := m.width_phaseState S hm h hh + have hl : width (a:=.list SampleNodeData) (acc.map (m.phaseState h))≤ + S*(2*(sourceWidthPoly 210).eval S+2) := by + apply (width_list_le _ _ ?_).trans + · simp only [List.length_map]; exact Nat.mul_le_mul_right _ ha + · intro y hy + obtain ⟨z,hz,rfl⟩ := List.mem_map.mp hy + exact hw z + rw [sampleAccValue,width_pair (a:=.list SampleNodeData) (b:=SampleNodeData)] + change 2*width (a:=.list SampleNodeData) (acc.map (m.phaseState h))+1+width (m.phaseState h x) + ≤ 2*(S*(2*(sourceWidthPoly 210).eval S+2))+(1+(sourceWidthPoly 210).eval S) + have hx := hw x + omega +def sampleAccScope : OraclePredicate SampleAccData := fun n O S z => + ∃ (m : SamplerModel n O),m.Bounded S ∧ ∃ h : m.Hist,h.length≤S ∧ + ∃ acc : List (ChainIndex (pairedSlots n)),acc.length≤S ∧ + ∃ x : ChainIndex (pairedSlots n),z=sampleAccValue m h (acc,x) +lemma sampleAccScope_width : ∀ n O S z,sampleAccScope n O S z → width z≤ sampleAccWidth.eval S := by + intro n O S z hz + obtain ⟨m,hm,h,hh,acc,ha,x,rfl⟩ := hz + exact sampleAccValue_width m S hm h hh acc ha x +lemma safe_sampleTick : OracleSafe (sampleTick (withContext phaseStepCode)) (bankScope sampleAccScope) := by + unfold sampleTick + apply oracleSafe_letControlled _ _ _ _ (by ec) + apply oracleSafe_precompose snd _ sampleAccScope phaseStateScope + (oracleSafe_controlled _ (by cc) _ _ sampleAccScope_width) + (oracleSafe_withContext _ _ safe_phaseStep) + intro n O S z hz y hy + obtain ⟨m,hm,h,hh,acc,ha,x,rfl⟩ := hz + cases hy + exact ⟨m,hm,h,hh,x,rfl⟩ +def sampleRepeatScope : OraclePredicate (.prod .nat SampleAccData) := fun n O S z => + z.1≤S ∧ ∃ (m : SamplerModel n O),m.Bounded S ∧ ∃ h : m.Hist,h.length≤S ∧ + ∃ x : ChainIndex (pairedSlots n),z.2=sampleAccValue m h ([],x) +lemma safe_sampleRepeat : OracleSafe (repeatCode (sampleTick (withContext phaseStepCode))) + (bankScope sampleRepeatScope) := by + apply oracleSafe_repeat_law _ sampleRepeatScope sampleAccScope safe_sampleTick (.add .input sampleAccWidth) + · intro n O S k z hz + obtain ⟨hk,m,hm,h,hh,x,rfl⟩ := hz + exact Nat.add_le_add hk (sampleAccValue_width m S hm h hh [] (Nat.zero_le S) x) + · intro n O S k z hz j hj + obtain ⟨hk,m,hm,h,hh,x,rfl⟩ := hz + let f := canonicalStepTree n m.positive m.rank O m.samples h h.length + let e := m.phaseState h + refine ⟨List (ChainIndex (pairedSlots n)) × ChainIndex (pairedSlots n),sampleAccValue m h, + treeRepeat (sampleTickTree f) j ([],x),?_,?_⟩ + · apply law_repeat O _ _ _ _ j ([],x) + apply law_sampleTick O (withContext phaseStepCode) e f + intro y + apply law_withContext + exact phaseStepCode_source m.M₁ m.M₂ O m.exact m.ground₁ m.ground₂ + m.rank m.samples m.phases h m.positive y + · apply (repeatSample_length f j [] x).mono + intro v hv + have hl : v.1.length≤S := by + simp only [List.length_nil,Nat.zero_add] at hv + exact hv.le.trans (hj.trans hk) + exact ⟨(sampleAccValue_width m S hm h hh v.1 hl v.2).trans (Nat.le_add_left _ _), + m,hm,h,hh,v.1,hl,v.2,rfl⟩ +def sampleInputScope : OraclePredicate (.prod .nat SampleNodeData) := fun n O S z => + z.1≤S ∧ phaseStateScope n O S z.2 +lemma sampleInputScope_width : ∀ n O S z,sampleInputScope n O S z → + width z≤(SizePolynomial.add (.mul (.constant 2) .input) (.add (.constant 1) (sourceWidthPoly 210))).eval S := by + intro n O S z hz + have hk := (bits_length_le_value z.1).trans hz.1 + have hw := phaseStateScope_width n O S z.2 hz.2 + rw [width_pair (a:=.nat) (b:=SampleNodeData),width_nat] + change _ ≤ 2*S+(1+(sourceWidthPoly 210).eval S) + omega +lemma safe_sampleCode : OracleSafe (sampleCode (withContext phaseStepCode)) (bankScope sampleInputScope) := by + unfold sampleCode + apply oracleSafe_precompose _ _ sampleInputScope sampleRepeatScope + (oracleSafe_controlled _ (by cc) _ _ sampleInputScope_width) + · exact oracleSafe_mapControlled _ _ _ safe_sampleRepeat (by unfold sampleFinish; cc) + · intro n O S z hz y hy + cases hy + obtain ⟨m,hm,h,hh,x,he⟩ := hz.2 + exact ⟨hz.1,m,hm,h,hh,x,by rw [he]; rfl⟩ +lemma safe_phaseSample : OracleSafe phaseSampleCode (bankScope phaseStateScope) := by + unfold phaseSampleCode + apply oracleSafe_precompose _ _ phaseStateScope sampleInputScope + (oracleSafe_controlled _ (by unfold phaseSamplePrep; cc) _ _ phaseStateScope_width) + · exact oracleSafe_mapControlled _ _ _ safe_sampleCode (by unfold mapEach; cc) + · intro n O S z hz y hy + obtain ⟨m,hm,h,hh,x,rfl⟩ := hz + have he : run O phaseSamplePrep (m.phaseState h x)=some (m.samples-1,m.phaseState h x) := by + simp only [phaseSamplePrep,SamplerModel.phaseState,SamplerModel.phaseValue,params, + run_both,run_compose,run_fst,run_snd,run_ident,run_constant,Option.bind_some,Option.map_some] + rw [run_natSub]; rfl + have hey := Option.some.inj (he.symm.trans hy) + subst y + exact ⟨(Nat.sub_le _ _).trans hm.2.2.1,m,hm,h,hh,x,rfl⟩ +end Effect + +open Expression +lemma attrSafe_mapStep {a b c : DataType} (p : Expression (.prod a c) b) + (A : Attribute (.prod a c)) (hA : A.Mono) (hp : AttrSafe p A) : + AttrSafe (mapStep p) (fun S z => A S (z.1,z.2.2)) := by + unfold mapStep + apply attrSafe_both + · apply attrSafe_post _ _ _ _ (by cc) + apply attrSafe_both + · apply attrSafe_pull _ p _ A (by cc) hp hA + intro n O S z hz y hy + cases hy; exact hz + · exact attrSafe_controlled _ (by cc) _ + · exact attrSafe_controlled _ (by cc) _ + +lemma attrSafe_mapFold {a b c : DataType} (p : Expression (.prod a c) b) + (A : Attribute (.prod a c)) (hA : A.Mono) (hp : AttrSafe p A) : + AttrSafe (.fold (mapStep p)) (fun S z => ∀ x∈z.1,A S (x,z.2.2)) := by + obtain ⟨f,hf⟩ := hp + let s : SizePolynomial := .add (.mul (.constant 3) .input) (.constant 1) + let g : SizePolynomial := .mul (.add (.mul (.constant 4) .input) (.constant 3)) + (.add (.mul (.constant 2) (f.subst s)) (.constant 3)) + have hacc : ∀ {n : ℕ} (O : IndependenceOracle n) S xs zs ctx, + width (a:=.prod (.list a) (.prod (.list b) c)) (xs,(zs,ctx))≤S → + (∀ x∈xs,A S (x,ctx)) → ∀ pre post,xs=pre++post → ∀ y, + foldValue (run O (mapStep p)) pre (zs,ctx)=some y → width y≤g.eval S ∧ y.2=ctx := by + intro n O S xs zs ctx hw ha pre post he y hy + have hx : width (a:=.list a) xs≤S := (width_fst _).trans hw + have hzs : width (a:=.list b) zs≤S := (width_fst (a:=.list b) (b:=c) (zs,ctx)).trans ((width_snd _).trans hw) + have hc : width ctx≤S := (width_snd (a:=.list b) (b:=c) (zs,ctx)).trans ((width_snd _).trans hw) + have hl : pre.length≤S := by + have hh := (list_length_le_width xs).trans hx + rw [he,List.length_append] at hh + omega + let U := f.eval (s.eval S) + have hh := fold_mapStep_bound O p pre zs ctx U (by + intro x hxp v hv + have hxx : x∈xs := by rw [he]; exact List.mem_append_left post hxp + have hxb := (width_list_member x xs hxx).trans hx + apply safe_output (hf O (s.eval S) (x,ctx) ⟨?_,?_⟩) hv + · rw [width_pair (a:=a) (b:=c)] + change _≤3*S+1 + omega + · exact hA S _ (by change S≤3*S+1; omega) (x,ctx) (ha x hxx)) y hy + have hm := Nat.mul_le_mul_right (2*U+2) hl + have hy' : width (a:=.list b) y.1≤S+S*(2*U+2) := by omega + refine ⟨?_,hh.2⟩ + have hw' : width y=2*width (a:=.list b) y.1+1+width ctx := by + rw [width_pair (a:=.list b) (b:=c),hh.2] + rw [hw'] + simp only [g,SizePolynomial.eval,SizePolynomial.eval_subst] + change _≤(4*S+3)*(2*U+3) + nlinarith + let W : SizePolynomial := .add (.mul (.constant 3) .input) (.add g (.constant 1)) + apply polySafe_fold (mapStep p) _ (fun S (z : Value (.prod a (.prod (.list b) c))) => width z≤W.eval S ∧ A (W.eval S) (z.1,z.2.2)) + (polySafe_reparam _ _ (attrSafe_mapStep p A hA ⟨f,hf⟩) W) (.add .input g) + · intro S z hz; exact hz.1.trans (Nat.le_add_right _ _) + · intro n O S xs z hz pre post he y hy + exact (hacc O S xs z.1 z.2 hz.1 hz.2 pre post he y hy).1.trans (Nat.le_add_left _ _) + · intro n O S xs z hz pre x post he y hy + have hh := hacc O S xs z.1 z.2 hz.1 hz.2 pre (x::post) he y hy + have hm : x∈xs := by rw [he]; simp + have hwx := (width_list_member x xs hm).trans ((width_fst _).trans hz.1) + refine ⟨?_,?_⟩ + · rw [width_pair (a:=a) (b:=.prod (.list b) c)] + change _≤3*S+(g.eval S+1) + omega + · rw [hh.2] + exact hA S _ (by change S≤3*S+(g.eval S+1); omega) (x,z.2) (hz.2 x hm) +lemma attrSafe_mapWith {a b c : DataType} (p : Expression (.prod a c) b) + (A : Attribute (.prod a c)) (hA : A.Mono) (hp : AttrSafe p A) : + AttrSafe (mapWith p) (fun S z => ∀ x∈z.1,A S (x,z.2)) := by + unfold mapWith + apply attrSafe_pull _ _ _ (fun S (z : Value (.prod (.list a) (.prod (.list b) c))) => ∀ x∈z.1,A S (x,z.2.2)) (by cc) + · exact attrSafe_post _ _ _ (attrSafe_mapFold p A hA hp) (by cc) + · intro S T h z hz x hx; exact hA S T h (x,z.2.2) (hz x hx) + · intro n O S z hz y hy + cases hy; exact hz + +lemma attrSafe_allRange {a : DataType} (p : Expression (.prod .nat a) .bool) + (A : Attribute (.prod .nat a)) (hA : A.Mono) (hp : AttrSafe p A) : + AttrSafe (allRange p) (fun S z => z.1≤S ∧ ∀ i ∀ i∈z.1,A S (i,z.2)) + · apply attrSafe_both + · apply attrSafe_pull fst rangeCode _ _ (by cc) attr_rangeCode + · intro S T h x hx; exact hx.trans h + · intro n O S z hz y hy; cases hy; exact hz.1 + · exact attrSafe_controlled _ (by cc) _ + · exact attrSafe_post _ _ _ (attrSafe_mapWith p A hA hp) (by cc) + · intro S T h z hz i hi; exact hA S T h (i,z.2) (hz i hi) + · intro n O S z hz y hy + have he : run O (both (fst >>> rangeCode) snd) z=some (List.range z.1,z.2) := by + simp only [run_both,run_compose,run_fst,run_snd,Option.bind_some,run_rangeCode,Option.map_some] + have hey := Option.some.inj (he.symm.trans hy) + subst y + intro i hi + exact hz.2 i (List.mem_range.mp hi) + +lemma controlled_pairPositive : Controlled pairPositiveCode := by + have h := controlled_historyWeight + unfold pairPositiveCode + cc +lemma attr_slotRow : AttrSafe slotRowCode (fun S z => z.2.1≤S) := by + unfold slotRowCode + apply attrSafe_pull _ _ _ (fun S (z : Value (.prod .nat (.prod .nat HistoryData))) => + z.1≤S ∧ ∀ i True) (by intro S T h z hz; exact True.intro) + (attrSafe_controlled _ (by have h := controlled_pairPositive; cc) _) + · intro S T h z hz; exact ⟨hz.1.trans h,by intros; trivial⟩ + · intro n O S z hz y hy; cases hy; exact ⟨hz,by intros; trivial⟩ +lemma attr_slotsPositive : AttrSafe slotsPositiveCode (fun S z => z.1≤S) := by + unfold slotsPositiveCode + apply attrSafe_pull _ _ _ (fun S (z : Value (.prod .nat (.prod .nat HistoryData))) => + z.1≤S ∧ ∀ i z.2.1≤S) + (by intro S T h z hz; exact hz.trans h) attr_slotRow + · intro S T h z hz; exact ⟨hz.1.trans h,fun i hi => (hz.2 i hi).trans h⟩ + · intro n O S z hz y hy; cases hy; exact ⟨hz,fun _ _ => hz⟩ +lemma attr_prefixPositive : AttrSafe prefixPositiveCode (fun S z => z.2.1≤S) := by + unfold prefixPositiveCode + apply attrSafe_pull _ _ _ (fun S (z : Value (.prod .nat HistoryData)) => z.1≤S) + (by cc) attr_slotsPositive + · intro S T h z hz; exact hz.trans h + · intro n O S z hz y hy + have he : z.2.1=y.1 := Option.some.inj (run_both_parts O _ _ z y hy).1 + exact he ▸ hz +lemma attr_historyPositive : AttrSafe historyPositiveCode (fun S z => z.1≤S) := by + let prep : Expression (.prod .nat HistoryData) (.prod .nat (.prod .nat HistoryData)) := + both (snd >>> listLength >>> (both ident (constant 1) >>> add)) ident + have hc : Controlled prep := by dsimp [prep]; cc + obtain ⟨f,hf⟩ := hc + let g : SizePolynomial := .add f (.add .input (.constant 1)) + change PolySafe (prep >>> allRange prefixPositiveCode) (fun S z => width z≤S ∧ z.1≤S) + apply polySafe_compose prep _ _ (fun S z => width z≤g.eval S ∧ + (z.1≤g.eval S ∧ ∀ i z.2.1≤S) + (by intro S T h z hz; exact hz.trans h) attr_prefixPositive) g) + intro n O S z hz y hy + have hd : y=(z.2.length+1,z) := by + have he : run O prep z=some (z.2.length+1,z) := by + simp only [prep,run_both,run_compose,run_snd,run_ident,run_constant, + Option.bind_some,Option.map_some,run_listLength] + rfl + exact Option.some.inj (hy.symm.trans he) + have hw : width y≤f.eval S := (safe_output (hf O z) hy).trans (f.monotone hz.1) + have hl := (list_length_le_width z.2).trans ((width_snd (a:=.nat) (b:=HistoryData) z).trans hz.1) + refine ⟨hw.trans (Nat.le_add_right _ _),?_,?_⟩ + · rw [hd] + change z.2.length+1≤f.eval S+(S+1) + omega + · intro i hi + rw [hd] + exact hz.2.trans (by change S≤f.eval S+(S+1); omega) + +open Expression +open scoped Classical +namespace Effect +lemma oracleSafe_chooseScoped {a b : DataType} (t : Expression a .bool) (p q : Effect a b) + (R : OraclePredicate a) (ht : OracleSafe t R) + (hp : OracleSafe p (bankScope R)) (hq : OracleSafe q (bankScope R)) : + OracleSafe (choose t p q) (bankScope R) := by + apply oracleSafe_applyIf _ _ _ (bankScope R) + · exact safe_scope_fst t R ht + · exact oracleSafe_mono p hp (by intro n O S x hx; exact hx.1) + · exact oracleSafe_mono q hq (by intro n O S x hx; exact hx.1) +lemma oracleSafe_some {a b : DataType} (p : Effect a b) (R : OraclePredicate (.prod a BankData)) + (hp : OracleSafe p R) : OracleSafe (someCode p) R := by + unfold someCode + exact oracleSafe_mapControlled _ _ R hp (by cc) +lemma attr_positiveTest : AttrSafe positiveTest (fun S z => z.1.1.1≤S) := by + unfold positiveTest + apply attrSafe_pull _ _ _ (fun S (z : Value (.prod .nat HistoryData)) => z.1≤S) + (by cc) attr_historyPositive + · intro S T h z hz; exact hz.trans h + · intro n O S z hz y hy; cases hy; exact hz +lemma safe_positiveTest : OracleSafe positiveTest phaseScope := by + apply oracleSafe_attr _ _ (by intro S T h z hz; exact hz.trans h) + attr_positiveTest phaseScope _ phaseScope_width + intro n O S z hz + obtain ⟨m,hm,h,hh,rfl⟩ := hz + exact hm.1 +lemma safe_phaseNone : OracleSafe (noneCode (a:=PhaseInput) (b:=SampleData)) (bankScope phaseScope) := by + exact oracleSafe_pure _ phaseScope (oracleSafe_controlled _ (by cc) _ _ phaseScope_width) +lemma safe_phase : OracleSafe phaseCode (bankScope phaseScope) := by + unfold phaseCode + apply oracleSafe_chooseScoped _ _ _ phaseScope safe_positiveTest safe_phaseNone + apply oracleSafe_optionBind _ _ phaseScope phaseStateScope + (oracleSafe_retainOption _ _ safe_start) (oracleSafe_some _ _ safe_phaseSample) + intro n O S z bank hz hb y rest hy + obtain ⟨m,hm,h,hh,rfl⟩ := hz + have hl := law_retainOption O startCode (fun x : ChainIndex (pairedSlots n) => stateEncode x.val) + (m.phaseValue h) _ (startCode_source m.M₁ m.M₂ O m.exact m.ground₁ m.ground₂ + m.rank m.samples m.phases h m.positive) + obtain ⟨v,he,hr⟩ := hl.output_some bank y rest hy + refine ⟨?_,hr.trans hb⟩ + rw [he] + apply optionScope_encode + intro x + exact ⟨m,hm,h,hh,x,rfl⟩ +lemma safe_witness : OracleSafe witnessCode (bankScope phaseScope) := by + unfold witnessCode + apply oracleSafe_chooseScoped _ _ _ phaseScope safe_positiveTest _ safe_phaseRestart + exact oracleSafe_pure _ phaseScope (oracleSafe_controlled _ (by cc) _ _ phaseScope_width) +end Effect + +section +open Expression +open scoped Classical +namespace Expression + +def weightedPlainCode : Expression (.prod .nat StateData) NN := + applyIf (snd >>> plainCode) (constant (0,1)) + (both (both (both fst (constant 1)) (constant [])) snd >>> annealCode) +def weightedListCode : Expression (.prod .nat SampleData) (.list NN) := + both snd fst >>> mapWith (Expression.swap >>> weightedPlainCode) +def weightedMeanCode : Expression (.prod .nat SampleData) NN := + letIn weightedListCode (both (snd >>> ratSumCode) (fst >>> snd >>> listLength >>> natRatCode) >>> ratDiv) +def plainMeanCode : Expression (.prod .nat SampleData) NN := + both (snd >>> countPlainCode) (snd >>> listLength) >>> normalizeRat +def ratioCode : Expression (.prod .nat SampleData) NN := both weightedMeanCode plainMeanCode >>> ratDiv +end Expression +variable {n : ℕ} (M₁ M₂ : Matroid (Fin n)) (O : IndependenceOracle n) + (hO : ExactOracles M₁ M₂ O) (hE₁ : M₁.E=Set.univ) (hE₂ : M₂.E=Set.univ) (r : ℕ) +local notation "GS" => pairedSlots n +local notation "f" => (fun S => rationalPlain GS (fun S => rationalRho n^oracleDeficiency n r O S) S) +lemma weightedPlain_nonneg (S : Set (Fin n⊕Fin n)) : 0≤f S := by + change 0 ≤ if PlainState GS S then rationalRho n ^ oracleDeficiency n r O S else 0 + split_ifs + · exact pow_nonneg (Expression.rationalRho_nonneg n) _ + · rfl +include M₁ M₂ hO hE₁ hE₂ +lemma weightedPlainCode_source (S : Set (Fin n⊕Fin n)) : + run O weightedPlainCode (r,stateEncode S)=some (rationalPair (f S)) := by + rw [weightedPlainCode,run_applyIf] + change ((run O Expression.plainCode (stateEncode S)).bind fun b => _)=_ + rw [plainCode_source] + by_cases hs : PlainState GS S + · simp only [hs,decide_true,Option.bind_some,ite_true] + change run O annealCode (((r,1),historyEncode ([] : List (List (Set (Fin n⊕Fin n))))),stateEncode S)=_ + rw [annealCode_source M₁ M₂ O hO hE₁ hE₂] + simp only [rationalPlain,hs,ite_true,pow_one] + · simp only [hs,decide_false,Option.bind_some,Bool.false_eq_true,ite_false,run_constant,rationalPlain] + rfl +lemma weightedListCode_source (xs : List (Set (Fin n⊕Fin n))) : + run O weightedListCode (r,sampleEncode xs)=some ((xs.map f).map rationalPair) := by + change run O (mapWith (Expression.swap >>> weightedPlainCode)) (xs.map stateEncode,r)=_ + rw [run_mapWith_source O (Expression.swap >>> weightedPlainCode) stateEncode (fun S => rationalPair (f S)) r + (weightedPlainCode_source M₁ M₂ O hO hE₁ hE₂ r) xs] + simp only [List.map_map,Function.comp_def] +lemma weightedMeanCode_source (xs : List (Set (Fin n⊕Fin n))) : + run O weightedMeanCode (r,sampleEncode xs)=some (rationalPair (rationalEmpirical f xs)) := by + rw [weightedMeanCode,run_letIn,weightedListCode_source M₁ M₂ O hO hE₁ hE₂ r xs,Option.bind_some] + simp only [run_compose,run_both,run_fst,run_snd,Option.bind_some] + rw [run_ratSumCode O (xs.map f) (by intro q hq; obtain ⟨S,hS,rfl⟩ := List.mem_map.mp hq; exact weightedPlain_nonneg O r S)] + simp only [Option.bind_some] + rw [run_listLength] + simp only [sampleEncode,List.length_map,Option.bind_some] + rw [run_natRatCode] + simp only [Option.bind_some,Option.map_some] + apply run_ratDiv + · exact List.sum_nonneg (by intro q hq; obtain ⟨S,hS,rfl⟩ := List.mem_map.mp hq; exact weightedPlain_nonneg O r S) + · positivity +omit M₁ M₂ hO hE₁ hE₂ in +lemma plainMeanCode_source (xs : List (Set (Fin n⊕Fin n))) : + run O plainMeanCode (r,sampleEncode xs)=some (rationalPair (rationalEmpirical (rationalPlain GS (fun _ => 1)) xs)) := by + simp only [plainMeanCode,run_compose,run_both,run_snd,Option.bind_some] + rw [run_countPlainCode,run_listLength] + simp only [Option.bind_some,Option.map_some] + rw [run_normalizeRat_pair,countPlainValue_source] + unfold rationalEmpirical rationalPlain + dsimp only + rw [indicator_list_sum] + simp only [sampleEncode,List.length_map] +lemma ratioCode_source (xs : List (Set (Fin n⊕Fin n))) : + run O ratioCode (r,sampleEncode xs)=some (rationalPair (rationalRatio GS (fun S => rationalRho n^oracleDeficiency n r O S) xs)) := by + simp only [ratioCode,run_compose,run_both] + rw [weightedMeanCode_source M₁ M₂ O hO hE₁ hE₂ r xs,plainMeanCode_source O r xs] + simp only [Option.bind_some,Option.map_some] + apply run_ratDiv + · unfold rationalEmpirical + apply div_nonneg + · apply List.sum_nonneg + intro q hq + obtain ⟨S,hS,rfl⟩ := List.mem_map.mp hq + exact weightedPlain_nonneg O r S + · positivity + · unfold rationalEmpirical rationalPlain + rw [indicator_list_sum] + positivity +end + +section +open Expression +namespace Effect + +def historyTickCode {a c} (p : Effect (.prod c (.list a)) (Optional a)) : + Effect (.prod c (.list a)) (Optional (.prod c (.list a))) := + map (retainOption p) (optionMapCode (both (fst >>> fst) + (both (fst >>> snd) (both snd (constant []) >>> cons) >>> listAppend))) +def historyTickTree {X : Type*} (K : List X → DrawTree (Option X)) (h : List X) : DrawTree (Option (List X)) := + (K h).map (Option.map (fun x => h++[x])) +lemma optionRepeat_none {X : Type*} (f : X → DrawTree (Option X)) (k : ℕ) : + treeRepeat (fun x => match x with | none => .leaf none | some y => f y) k none=.leaf none := by + induction k with + | zero => rfl + | succ k ih => exact ih +lemma iterate_history {X : Type*} (K : List X → DrawTree (Option X)) (k : ℕ) (h : List X) : + DrawTree.iterate (historyTickTree K) k h=DrawTree.history K k h := by + rw [←treeRepeat_option] + induction k generalizing h with + | zero => rfl + | succ k ih => + simp only [treeRepeat,historyTickTree,DrawTree.map_bind,DrawTree.history,DrawTree.optionBind] + congr 1 + funext u + cases u with + | none => exact optionRepeat_none _ k + | some x => exact ih (h++[x]) +lemma law_historyTickCode {n : ℕ} (O : IndependenceOracle n) {X : Type*} {a c} + (p : Effect (.prod c (.list a)) (Optional a)) (e : X → Value a) (ctx : Value c) + (K : List X → DrawTree (Option X)) (h : List X) + (hp : RealizesLaw O p (optionEncode e) (ctx,h.map e) (K h)) : + RealizesLaw O (historyTickCode p) (optionEncode (fun h => (ctx,h.map e))) (ctx,h.map e) (historyTickTree K h) := by + apply law_optionMap O (retainOption p) _ (fun y => ((ctx,h.map e),e y)) _ _ _ (fun x => h++[x]) + · exact law_retainOption O p e (ctx,h.map e) (K h) hp + · intro x + simp only [run_both,run_compose,run_fst,run_snd,run_constant,Option.bind_some,Option.map_some] + change ((run O listAppend (h.map e,[e x])).map fun l => (ctx,l))=_ + rw [run_listAppend] + simp + +def historyCode {a c} (p : Effect (.prod c (.list a)) (Optional a)) : + Effect (.prod .nat (.prod c (.list a))) (Optional (.prod c (.list a))) := iterateCode (historyTickCode p) +lemma law_historyCode {n : ℕ} (O : IndependenceOracle n) {X : Type*} {a c} + (p : Effect (.prod c (.list a)) (Optional a)) (e : X → Value a) (ctx : Value c) + (K : List X → DrawTree (Option X)) + (hp : ∀ h,RealizesLaw O p (optionEncode e) (ctx,h.map e) (K h)) (k : ℕ) (h : List X) : + RealizesLaw O (historyCode p) (optionEncode (fun h => (ctx,h.map e))) (k,(ctx,h.map e)) (DrawTree.history K k h) := by + rw [←iterate_history] + exact law_iterate O (historyTickCode p) _ _ (fun h => law_historyTickCode O p e ctx K h (hp h)) k h +end Effect + +open Expression +open scoped BigOperators Classical +namespace Expression + +def historyAtCode : Expression (.prod HistoryData .nat) SampleData := both ident (constant []) >>> getDCode +def ratioAtCode : Expression (.prod .nat PhaseInput) NN := + both (snd >>> fst >>> fst >>> snd) (both (snd >>> snd) fst >>> historyAtCode) >>> ratioCode + +def estimateCode : Expression PhaseInput NN := + both (both (constant (b:=.nat) 2) (fst >>> fst >>> fst : Expression PhaseInput .nat) >>> Expression.powCode >>> natRatCode) + (both (fst >>> snd >>> fst >>> snd >>> rangeCode) ident >>> mapWith ratioAtCode >>> ratProductCode) >>> ratMul + +def guardCode : Expression (.prod PhaseInput StateData) NN := + applyIf (both (fst >>> fst >>> fst >>> snd) snd >>> deficiencyCode >>> natEqZero) + (constant (0,1)) (fst >>> estimateCode) +end Expression + +lemma historyAtCode_source {n N : ℕ} (O : IndependenceOracle n) (h : List (PhaseSample n N)) (j : ℕ) : + run O historyAtCode (historyEncode (h.map (observedSets n N)),j)= + some (sampleEncode (historySample (observedSets n N) h j)) := by + change run O getDCode ((historyEncode (h.map (observedSets n N)),j),[])=_ + rw [run_getDCode] + unfold historyEncode historySample + simp only [List.getD_eq_getElem?_getD,List.getElem?_map] + cases h[j]? <;> rfl +lemma ratio_nonnegative {n : ℕ} (O : IndependenceOracle n) (r : ℕ) (xs : List (Set (Fin n⊕Fin n))) : + 0≤rationalRatio (pairedSlots n) (fun S => rationalRho n^oracleDeficiency n r O S) xs := by + unfold rationalRatio rationalEmpirical + apply div_nonneg + · apply div_nonneg + · apply List.sum_nonneg + intro q hq + obtain ⟨S,hS,rfl⟩ := List.mem_map.mp hq + exact weightedPlain_nonneg O r S + · positivity + · apply div_nonneg + · unfold rationalPlain + rw [indicator_list_sum] + positivity + · positivity +variable {n : ℕ} (M₁ M₂ : Matroid (Fin n)) (O : IndependenceOracle n) + (hO : ExactOracles M₁ M₂ O) (hE₁ : M₁.E=Set.univ) (hE₂ : M₂.E=Set.univ) (r N L : ℕ) +local notation "GS" => pairedSlots n +include M₁ M₂ hO hE₁ hE₂ +lemma ratioAtCode_source (h : List (PhaseSample n N)) (j : ℕ) : + run O ratioAtCode (j,(params n r N L,historyEncode (h.map (observedSets n N))))= + some (rationalPair (rationalRatio GS (fun S => rationalRho n^oracleDeficiency n r O S) + (historySample (observedSets n N) h j))) := by + simp only [ratioAtCode,run_compose,run_both,run_fst,run_snd,params,Option.bind_some,Option.map_some] + rw [historyAtCode_source] + simp only [Option.bind_some,Option.map_some] + exact ratioCode_source M₁ M₂ O hO hE₁ hE₂ r _ +lemma estimateCode_source (h : List (PhaseSample n N)) : + run O estimateCode (params n r N L,historyEncode (h.map (observedSets n N)))= + some (rationalPair (oracleEstimate n r O N L h)) := by + simp only [estimateCode,run_compose,run_both,run_fst,run_snd,run_ident,run_constant,params,Option.bind_some,Option.map_some] + rw [run_powCode,Option.bind_some,run_natRatCode,Option.bind_some,run_rangeCode] + simp only [Option.bind_some] + let f : ℕ → ℚ := fun j => rationalRatio GS (fun S => rationalRho n^oracleDeficiency n r O S) + (historySample (observedSets n N) h j) + have hm := run_mapWith_source O ratioAtCode id (fun j => rationalPair (f j)) + (params n r N L,historyEncode (h.map (observedSets n N))) + (ratioAtCode_source M₁ M₂ O hO hE₁ hE₂ r N L h) (List.range L) + simp only [List.map_id,params] at hm + rw [run_compose,hm] + simp only [Option.bind_some] + have he : (List.range L).map (fun j => rationalPair (f j))=((List.range L).map f).map rationalPair := by + simp only [List.map_map,Function.comp_def] + rw [he,run_ratProductCode O _ (by + intro q hq + obtain ⟨j,hj,rfl⟩ := List.mem_map.mp hq + exact ratio_nonnegative O r _)] + simp only [Option.bind_some,Option.map_some] + rw [run_ratMul O _ _ (by positivity) (by + apply List.prod_nonneg + intro q hq + obtain ⟨j,hj,rfl⟩ := List.mem_map.mp hq + exact ratio_nonnegative O r _)] + congr 2 + unfold oracleEstimate + rw [Nat.cast_pow,Nat.cast_ofNat] + congr 1 +lemma guardCode_source (h : List (PhaseSample n N)) (x : PlainIndex GS) : + run O guardCode ((params n r N L,historyEncode (h.map (observedSets n N))),stateEncode x.val.val)= + some (rationalPair (oracleGuard n r O N L h x)) := by + rw [guardCode,run_applyIf] + simp only [run_compose,run_both,run_fst,run_snd,params,Option.bind_some,Option.map_some] + rw [deficiencyCode_source M₁ M₂ O hO hE₁ hE₂ r _ _ (stateEncode_left_length _) (stateEncode_right_length _), + stateEncode_repr,Option.bind_some,run_natEqZero] + by_cases hz : oracleDeficiency n r O x.val.val=0 + · simp only [hz,decide_true,Option.bind_some,ite_true] + simpa only [params,oracleGuard,hz,ite_true] using estimateCode_source M₁ M₂ O hO hE₁ hE₂ r N L h + · simp only [hz,decide_false,Option.bind_some,Bool.false_eq_true,ite_false,run_constant,oracleGuard] + rfl +end + +section +open Expression +open Effect +open scoped Classical +namespace Effect + +def finalGuardCode : Effect PhaseInput (Optional NN) := + map (retainOption witnessCode) (optionMapCode guardCode) +def algorithmHistoryCode : Effect AlgorithmParams (Optional PhaseInput) := + precompose (both (snd >>> fst >>> snd) (both ident (constant []))) (historyCode phaseCode) +def algorithmCode : Effect AlgorithmParams (Optional NN) := optionBind algorithmHistoryCode finalGuardCode +end Effect +variable {n : ℕ} (M₁ M₂ : Matroid (Fin n)) (O : IndependenceOracle n) + (hO : ExactOracles M₁ M₂ O) (hE₁ : M₁.E=Set.univ) (hE₂ : M₂.E=Set.univ) + (r N L : ℕ) (hn : 0 pairedSlots n +include M₁ M₂ hO hE₁ hE₂ +lemma algorithmHistoryCode_source : + RealizesLaw O algorithmHistoryCode + (optionEncode (fun h : List (PhaseSample n N) => (params n r N L,historyEncode (h.map (observedSets n N))))) + (params n r N L) (DrawTree.history (canonicalPhaseTree n hn r O N L) L []) := by + apply law_precompose O _ _ _ _ _ _ rfl + have hh := law_historyCode O phaseCode (fun v : PhaseSample n N => sampleEncode (observedSets n N v)) + (params n r N L) (canonicalPhaseTree n hn r O N L) + (fun h => by + simpa only [historyEncode,List.map_map,Function.comp_def] using + phaseCode_source M₁ M₂ O hO hE₁ hE₂ r N L h hn) L [] + simpa only [historyEncode,List.map_map,Function.comp_def,List.map_nil] using hh +lemma finalGuardCode_source (h : List (PhaseSample n N)) : + RealizesLaw O finalGuardCode (optionEncode rationalPair) + (params n r N L,historyEncode (h.map (observedSets n N))) + ((canonicalWitnessTree n hn r O N L h).map (Option.map (oracleGuard n r O N L h))) := by + apply law_optionMap O (retainOption witnessCode) guardCode + (fun x : PlainIndex GS => ((params n r N L,historyEncode (h.map (observedSets n N))),stateEncode x.val.val)) + rationalPair _ _ (oracleGuard n r O N L h) + · exact law_retainOption O witnessCode _ _ _ (witnessCode_source M₁ M₂ O hO hE₁ hE₂ r N L h hn) + · exact guardCode_source M₁ M₂ O hO hE₁ hE₂ r N L h + +lemma algorithmCode_source : + RealizesLaw O algorithmCode (optionEncode rationalPair) (params n r N L) + (canonicalAlgorithmTree n hn r O N L) := by + exact law_optionBind O algorithmHistoryCode finalGuardCode + (fun h : List (PhaseSample n N) => (params n r N L,historyEncode (h.map (observedSets n N)))) + rationalPair (params n r N L) _ _ + (algorithmHistoryCode_source M₁ M₂ O hO hE₁ hE₂ r N L hn) + (fun h => finalGuardCode_source M₁ M₂ O hO hE₁ hE₂ r N L hn h) +end + +open Expression +open scoped Classical +namespace Effect +lemma history_length {X : Type*} (K : List X → DrawTree (Option X)) (k : ℕ) (h : List X) : + DrawTree.All (fun v => ∀ h',v=some h' → h'.length=h.length+k) (DrawTree.history K k h) := by + induction k generalizing h with + | zero => intro h' he; cases he; simp + | succ k ih => + unfold DrawTree.history DrawTree.optionBind + apply DrawTree.all_bind_of_all (K h) _ (fun _ => True) _ (DrawTree.all_of_forall _ _ (by intros; trivial)) + intro u _ + cases u with + | none => intro h' he; cases he + | some x => + apply (ih (h++[x])).mono + intro v hv h' he + have hh := hv h' he + simpa only [List.length_append,List.length_singleton,Nat.add_assoc,Nat.add_comm 1 k] using hh +lemma safe_historyTick : OracleSafe (historyTickCode phaseCode) (bankScope phaseScope) := by + unfold historyTickCode + exact oracleSafe_mapControlled _ _ _ (oracleSafe_retainOption _ _ safe_phase) (by cc) +noncomputable def phaseOptWidth : SizePolynomial := + .add (sourceWidthPoly 100) (.constant (width (zeroValue PhaseInput)+3)) +lemma phaseOptWidth_bound {n : ℕ} {O : IndependenceOracle n} (m : SamplerModel n O) + (S : ℕ) (hm : m.Bounded S) (v : Option m.Hist) + (hv : ∀ h,v=some h → h.length≤S) : + width (optionEncode m.phaseValue v)≤phaseOptWidth.eval S := by + cases v with + | none => + rw [optionEncode,optionalValue,width_pair (a:=.bool) (b:=PhaseInput),width_bool] + change 2*1+1+width (zeroValue PhaseInput)≤(sourceWidthPoly 100).eval S+(width (zeroValue PhaseInput)+3) + omega + | some h => + have hw := m.width_phaseValue S hm h (hv h rfl) + rw [optionEncode,optionalValue,width_pair (a:=.bool) (b:=PhaseInput),width_bool] + change 2*1+1+width (m.phaseValue h)≤(sourceWidthPoly 100).eval S+(width (zeroValue PhaseInput)+3) + rw [eval_sourceWidthPoly] + omega +lemma historyTick_source {n : ℕ} {O : IndependenceOracle n} (m : SamplerModel n O) (h : m.Hist) : + RealizesLaw O (historyTickCode phaseCode) (optionEncode m.phaseValue) (m.phaseValue h) + (historyTickTree (canonicalPhaseTree n m.positive m.rank O m.samples m.phases) h) := by + have hl := law_historyTickCode O phaseCode + (fun v : PhaseSample n m.samples => sampleEncode (observedSets n m.samples v)) + (params n m.rank m.samples m.phases) + (canonicalPhaseTree n m.positive m.rank O m.samples m.phases) h (by + simpa only [SamplerModel.phaseValue,SamplerModel.histValue,historyEncode,List.map_map,Function.comp_def] using + phaseCode_source m.M₁ m.M₂ O m.exact m.ground₁ m.ground₂ m.rank m.samples m.phases h m.positive) + change RealizesLaw O _ (optionEncode (fun h => m.phaseValue h)) _ _ + simpa only [SamplerModel.phaseValue,SamplerModel.histValue,historyEncode,List.map_map,Function.comp_def] using hl + +def historyRepeatScope : OraclePredicate (.prod .nat (Optional PhaseInput)) := fun n O S z => + z.1≤S ∧ ∃ (m : SamplerModel n O),m.Bounded S ∧ z.2=optionEncode m.phaseValue (some []) +lemma safe_historyRepeat : OracleSafe (repeatCode (optionContinue (historyTickCode phaseCode))) + (bankScope historyRepeatScope) := by + apply oracleSafe_repeat_law _ historyRepeatScope (optionScope phaseScope) + (oracleSafe_optionContinue _ _ safe_historyTick) (.add .input phaseOptWidth) + · intro n O S k z hz + obtain ⟨hk,m,hm,rfl⟩ := hz + exact Nat.add_le_add hk (phaseOptWidth_bound m S hm (some []) (by intro h he; cases he; exact Nat.zero_le S)) + · intro n O S k z hz j hj + obtain ⟨hk,m,hm,rfl⟩ := hz + let K := canonicalPhaseTree n m.positive m.rank O m.samples m.phases + let f := historyTickTree K + let F : Option m.Hist → DrawTree (Option m.Hist) := fun u => match u with + | none => .leaf none | some h => f h + refine ⟨Option m.Hist,optionEncode m.phaseValue,treeRepeat F j (some []),?_,?_⟩ + · apply law_repeat O _ _ F _ j (some []) + intro u + change RealizesLaw O (optionContinue (historyTickCode phaseCode)) (optionEncode m.phaseValue) + (optionEncode m.phaseValue u) (match u with | none => .leaf none | some h => f h) + cases u <;> exact law_optionContinue O (historyTickCode phaseCode) m.phaseValue m.phaseValue f _ + (fun h => historyTick_source m h) + · have he : treeRepeat F j (some [])=DrawTree.iterate f j [] := by + convert treeRepeat_option f j ([] : m.Hist) using 2 + funext u; cases u <;> rfl + rw [he] + change DrawTree.All _ (DrawTree.iterate (historyTickTree K) j []) + rw [iterate_history] + apply (history_length K j []).mono + intro v hv + have hb : ∀ h,v=some h → h.length≤S := by + intro h he + have hh := hv h he + simp only [List.length_nil,Nat.zero_add] at hh + exact hh.le.trans (hj.trans hk) + refine ⟨(phaseOptWidth_bound m S hm v hb).trans (Nat.le_add_left _ _),?_⟩ + cases v with + | none => exact Or.inl rfl + | some h => exact Or.inr ⟨rfl,m,hm,h,hb h rfl,rfl⟩ +def historyInputScope : OraclePredicate (.prod .nat PhaseInput) := fun n O S z => + z.1≤S ∧ ∃ (m : SamplerModel n O),m.Bounded S ∧ z.2=m.phaseValue [] +lemma historyInputScope_width : ∀ n O S z,historyInputScope n O S z → + width z≤(SizePolynomial.add (.mul (.constant 2) .input) (.add (.constant 1) (sourceWidthPoly 100))).eval S := by + intro n O S z hz + obtain ⟨hk,m,hm,he⟩ := hz + have hb := (bits_length_le_value z.1).trans hk + have hw := m.width_phaseValue S hm [] (Nat.zero_le S) + rw [width_pair (a:=.nat) (b:=PhaseInput),width_nat,he] + change _≤2*S+(1+(sourceWidthPoly 100).eval S) + rw [eval_sourceWidthPoly] + omega +lemma safe_historyCode : OracleSafe (historyCode phaseCode) (bankScope historyInputScope) := by + unfold historyCode iterateCode + apply oracleSafe_precompose _ _ historyInputScope historyRepeatScope + (oracleSafe_controlled _ (by cc) _ _ historyInputScope_width) safe_historyRepeat + intro n O S z hz y hy + cases hy + obtain ⟨hk,m,hm,he⟩ := hz + exact ⟨hk,m,hm,by rw [he]; rfl⟩ +def algorithmScope : OraclePredicate AlgorithmParams := fun n O S z => + ∃ (m : SamplerModel n O),m.Bounded S ∧ z=params n m.rank m.samples m.phases +lemma algorithmScope_width : ∀ n O S z,algorithmScope n O S z → width z≤(sourceWidthPoly 100).eval S := by + intro n O S z hz + obtain ⟨m,hm,rfl⟩ := hz + rw [eval_sourceWidthPoly] + exact (width_fst (a:=AlgorithmParams) (b:=HistoryData) (m.phaseValue [])).trans + (m.width_phaseValue S hm [] (Nat.zero_le S)) +lemma safe_algorithmHistory : OracleSafe algorithmHistoryCode (bankScope algorithmScope) := by + unfold algorithmHistoryCode + apply oracleSafe_precompose _ _ algorithmScope historyInputScope + (oracleSafe_controlled _ (by cc) _ _ algorithmScope_width) safe_historyCode + intro n O S z hz y hy + obtain ⟨m,hm,rfl⟩ := hz + cases hy + exact ⟨hm.2.2.2.1,m,hm,rfl⟩ +end Effect + +open Expression +lemma attrSafe_fst {a b c : DataType} (p : Expression a c) (A : Attribute a) + (hp : AttrSafe p A) : AttrSafe (fst >>> p) (fun S (z : Value (.prod a b)) => A S z.1) := by + obtain ⟨f,hf⟩ := hp + refine ⟨.add .input f,fun O S x hx => ?_⟩ + have hw := (width_fst (a:=a) (b:=b) x).trans hx.1 + apply safe_compose O fst p x + · exact ⟨hx.1.trans (Nat.le_add_right _ _),fun y hy => by cases hy; exact hw.trans (Nat.le_add_right _ _),trivial⟩ + · intro y hy + cases hy + exact safe_mono p x.1 (hf O S x.1 ⟨hw,hx.2⟩) (Nat.le_add_left _ _) +lemma attrSafe_snd {a b c : DataType} (p : Expression b c) (A : Attribute b) + (hp : AttrSafe p A) : AttrSafe (snd >>> p) (fun S (z : Value (.prod a b)) => A S z.2) := by + obtain ⟨f,hf⟩ := hp + refine ⟨.add .input f,fun O S x hx => ?_⟩ + have hw := (width_snd (a:=a) (b:=b) x).trans hx.1 + apply safe_compose O snd p x + · exact ⟨hx.1.trans (Nat.le_add_right _ _),fun y hy => by cases hy; exact hw.trans (Nat.le_add_right _ _),trivial⟩ + · intro y hy + cases hy + exact safe_mono p x.2 (hf O S x.2 ⟨hw,hx.2⟩) (Nat.le_add_left _ _) + +lemma attrSafe_shift {a b : DataType} (p : Expression a b) (A : Attribute a) + (hp : AttrSafe p A) : AttrSafe p (fun S x => A (S+1) x) := by + apply polySafe_mono p (polySafe_reparam p _ hp (.add .input (.constant 1))) + intro S x hx + exact ⟨hx.1.trans (Nat.le_add_right S 1),hx.2⟩ +lemma attr_anneal : AttrSafe annealCode weightAttr := + polySafe_mono annealCode polySafe_anneal (by intro S x hx; exact ⟨hx.1,hx.2.1,hx.2.2⟩) +lemma attr_weightedPlain : AttrSafe weightedPlainCode (fun S z => z.1≤S) := by + unfold weightedPlainCode + apply attrSafe_applyIf _ _ _ _ (by intro S T h z hz; exact hz.trans h) + (attrSafe_controlled _ (by have h := controlled_plainCode; cc) _) (attrSafe_controlled _ (by cc) _) + apply attrSafe_pull _ annealCode _ (fun S z => weightAttr (S+1) z) (by cc) + (attrSafe_shift _ _ attr_anneal) + · intro S T h z hz + exact weightAttr_mono _ _ (Nat.add_le_add_right h 1) z hz + · intro n O S z hz y hy + cases hy + exact ⟨hz.trans (Nat.le_add_right S 1),Nat.le_add_left 1 S⟩ +lemma attr_weightedList : AttrSafe weightedListCode (fun S z => z.1≤S) := by + unfold weightedListCode + apply attrSafe_pull _ _ _ (fun S (z : Value (.prod SampleData .nat)) => ∀ x∈z.1,z.2≤S) (by cc) + · apply attrSafe_mapWith _ (fun S (z : Value (.prod StateData .nat)) => z.2≤S) (by intro S T h z hz; exact hz.trans h) + apply attrSafe_pull _ _ _ (fun S (z : Value (.prod .nat StateData)) => z.1≤S) (by cc) attr_weightedPlain + · intro S T h z hz; exact hz.trans h + · intro n O S z hz y hy; cases hy; exact hz + · intro S T h z hz x hx; exact (hz x hx).trans h + · intro n O S z hz y hy; cases hy; exact fun _ _ => hz +lemma controlled_plainMean : Controlled plainMeanCode := by + have h := controlled_countPlain + unfold plainMeanCode; cc +lemma attr_weightedMean : AttrSafe weightedMeanCode (fun S z => z.1≤S) := by + unfold weightedMeanCode Expression.letIn + apply attrSafe_post + · exact attrSafe_both _ _ _ (attrSafe_controlled _ (by cc) _) attr_weightedList + · unfold natRatCode; cc +lemma attr_ratio : AttrSafe ratioCode (fun S z => z.1≤S) := by + unfold ratioCode + exact attrSafe_post _ _ _ (attrSafe_both _ _ _ attr_weightedMean + (attrSafe_controlled _ controlled_plainMean _)) controlled_ratDiv +lemma controlled_historyAt : Controlled historyAtCode := by unfold historyAtCode; cc +lemma attr_ratioAt : AttrSafe ratioAtCode (fun S z => z.2.1.1.2≤S) := by + unfold ratioAtCode + apply attrSafe_pull _ _ _ (fun S (z : Value (.prod .nat SampleData)) => z.1≤S) (by have h := controlled_historyAt; cc) attr_ratio + · intro S T h z hz; exact hz.trans h + · intro n O S z hz y hy + have he : z.2.1.1.2=y.1 := Option.some.inj (run_both_parts O _ _ z y hy).1 + exact he ▸ hz +lemma attr_pow : AttrSafe Expression.powCode (fun S z => z.2≤S) := by + apply polySafe_mono _ polySafe_powCode + intro S z hz + exact ⟨(width_fst (a:=.nat) (b:=.nat) z).trans hz.1,hz.2⟩ +def estimatorAttr (S : ℕ) (z : Value PhaseInput) : Prop := + z.1.1.1≤S ∧ z.1.1.2≤S ∧ z.1.2.1.2≤S +lemma estimatorAttr_mono : Attribute.Mono (a:=PhaseInput) estimatorAttr := by + intro S T h z hz; exact ⟨hz.1.trans h,hz.2.1.trans h,hz.2.2.trans h⟩ +lemma attr_estimate : AttrSafe estimateCode estimatorAttr := by + unfold estimateCode + apply attrSafe_post + · apply attrSafe_both + · apply attrSafe_pull _ _ _ (fun S (z : Value (.prod .nat .nat)) => z.2≤S) (by cc) + · exact attrSafe_post _ _ _ attr_pow (by unfold natRatCode; cc) + · intro S T h z hz; exact hz.trans h + · intro n O S z hz y hy; cases hy; exact hz.1 + · apply attrSafe_compose _ _ _ (fun S (z : Value (.prod (.list .nat) PhaseInput)) => ∀ i∈z.1,z.2.1.1.2≤S) + · apply attrSafe_both + · apply attrSafe_mono _ (attrSafe_fst _ _ (attrSafe_snd _ _ (attrSafe_fst _ _ (attrSafe_snd _ _ attr_rangeCode)))) + intro S z hz; exact hz.2.2 + · exact attrSafe_controlled _ (by cc) _ + · apply attrSafe_post _ _ _ _ controlled_ratProduct + exact attrSafe_mapWith _ (fun S (z : Value (.prod .nat PhaseInput)) => z.2.1.1.2≤S) + (by intro S T h z hz; exact hz.trans h) attr_ratioAt + · intro S T h z hz i hi; exact (hz i hi).trans h + · intro n O S z hz y hy + have he : z=y.2 := Option.some.inj (run_both_parts O _ _ z y hy).2 + intro i hi + rw [←he]; exact hz.2.1 + · exact controlled_ratMul +lemma attr_guard : AttrSafe guardCode (fun S z => estimatorAttr S z.1) := by + unfold guardCode + apply attrSafe_applyIf _ _ _ _ (fun S T h (z : Value (.prod PhaseInput StateData)) hz => estimatorAttr_mono S T h z.1 hz) + (attrSafe_controlled _ (by cc) _) (attrSafe_controlled _ (by cc) _) + apply attrSafe_pull fst _ _ estimatorAttr (by cc) attr_estimate estimatorAttr_mono + intro n O S z hz y hy; cases hy; exact hz + +open Expression Effect +lemma oracleSafe_optionMap {a b : DataType} (p : Expression a b) + (R : OraclePredicate a) (hp : OracleSafe p R) : OracleSafe (optionMapCode p) (optionScope R) := by + obtain ⟨f,hf⟩ := oracleSafe_input_bound p R hp + let W : SizePolynomial := .add f (.constant (width (zeroValue a)+3)) + have hw : ∀ n O S x,optionScope R n O S x → width x≤W.eval S := optionScope_width R f hf + unfold optionMapCode + apply oracleSafe_applyIf _ _ _ (optionScope R) + · exact oracleSafe_controlled _ (by cc) _ W hw + · exact oracleSafe_controlled _ (by cc) _ W (by intro n O S x hx; exact hw n O S x hx.1) + · apply oracleSafe_both + · exact oracleSafe_controlled _ (by cc) _ W (by intro n O S x hx; exact hw n O S x hx.1) + · apply oracleSafe_pull snd p _ R (by cc) W (by intro n O S x hx; exact hw n O S x hx.1) hp + intro n O S x hx y hy + cases hy + have hv : x.1=true := Option.some.inj hx.2 + rcases hx.1 with hz | ⟨_,hr⟩ + · rw [hz] at hv; cases hv + · exact hr + +open Expression +open scoped Classical +namespace Effect +lemma safe_guard : OracleSafe guardCode phaseStateScope := by + apply oracleSafe_attr _ _ (fun S T h (z : Value (.prod PhaseInput StateData)) hz => estimatorAttr_mono S T h z.1 hz) + attr_guard phaseStateScope _ phaseStateScope_width + intro n O S z hz + obtain ⟨m,hm,h,hh,x,rfl⟩ := hz + exact ⟨hm.1,hm.2.1,hm.2.2.2.1⟩ +lemma safe_finalGuard : OracleSafe finalGuardCode (bankScope phaseScope) := by + unfold finalGuardCode map + apply oracleSafe_bind _ _ phaseScope (optionScope phaseStateScope) + (oracleSafe_retainOption _ _ safe_witness) (oracleSafe_pure _ _ (oracleSafe_optionMap _ _ safe_guard)) + intro n O S z bank hz hb y rest hy + obtain ⟨m,hm,h,hh,rfl⟩ := hz + have hl := law_retainOption O witnessCode (fun x : PlainIndex (pairedSlots n) => stateEncode x.val.val) + (m.phaseValue h) _ (witnessCode_source m.M₁ m.M₂ O m.exact m.ground₁ m.ground₂ + m.rank m.samples m.phases h m.positive) + obtain ⟨v,he,hr⟩ := hl.output_some bank y rest hy + refine ⟨?_,hr.trans hb⟩ + rw [he] + apply optionScope_encode + intro x + exact ⟨m,hm,h,hh,x.val,rfl⟩ + +lemma safe_algorithm : OracleSafe algorithmCode (bankScope algorithmScope) := by + unfold algorithmCode + apply oracleSafe_optionBind _ _ algorithmScope phaseScope safe_algorithmHistory safe_finalGuard + intro n O S z bank hz hb y rest hy + obtain ⟨m,hm,rfl⟩ := hz + have hl := algorithmHistoryCode_source m.M₁ m.M₂ O m.exact m.ground₁ m.ground₂ + m.rank m.samples m.phases m.positive + have ha := history_length (canonicalPhaseTree n m.positive m.rank O m.samples m.phases) m.phases ([] : m.Hist) + obtain ⟨v,he,hv,hr⟩ := hl.output_some_all _ ha bank y rest hy + refine ⟨?_,hr.trans hb⟩ + rw [he] + cases v with + | none => exact Or.inl rfl + | some h => + have hh : h.length≤S := by + have he := hv h rfl + simp only [List.length_nil,Nat.zero_add] at he + exact he.le.trans hm.2.2.2.1 + exact Or.inr ⟨rfl,m,hm,h,hh,rfl⟩ +end Effect + +open Expression +lemma oracleSafe_mapStep {a b c : DataType} (p : Expression (.prod a c) b) + (Q : OraclePredicate (.prod a c)) (hp : OracleSafe p Q) (g : SizePolynomial) : + OracleSafe (mapStep p) (fun n O S z => width z≤g.eval S ∧ Q n O S (z.1,z.2.2)) := by + let R : OraclePredicate (.prod a (.prod (.list b) c)) := fun n O S z => width z≤g.eval S ∧ Q n O S (z.1,z.2.2) + have hc : ∀ {d} (q : Expression (.prod a (.prod (.list b) c)) d),Controlled q → OracleSafe q R := + fun q hq => oracleSafe_controlled q hq R g (by intro n O S z hz; exact hz.1) + unfold mapStep + apply oracleSafe_both + · apply oracleSafe_post _ _ R _ (by cc) + apply oracleSafe_both + · apply oracleSafe_pull _ p R Q (by cc) g (by intro n O S z hz; exact hz.1) hp + intro n O S z hz y hy; cases hy; exact hz.2 + · exact hc _ (by cc) + · exact hc _ (by cc) +lemma oracleSafe_mapFold {a b c : DataType} (p : Expression (.prod a c) b) + (Q : OraclePredicate (.prod a c)) (hp : OracleSafe p Q) (g : SizePolynomial) : + OracleSafe (.fold (mapStep p)) + (fun n O S z => width z≤g.eval S ∧ ∀ x∈z.1,Q n O S (x,z.2.2)) := by + obtain ⟨f,hf⟩ := hp + let U : SizePolynomial := .mul (.add (.mul (.constant 4) g) (.constant 3)) + (.add (.mul (.constant 2) f) (.constant 3)) + have hacc : ∀ {n : ℕ} (O : IndependenceOracle n) S xs zs ctx, + width (a:=.prod (.list a) (.prod (.list b) c)) (xs,(zs,ctx))≤g.eval S → + (∀ x∈xs,Q n O S (x,ctx)) → ∀ pre post,xs=pre++post → ∀ y, + foldValue (run O (mapStep p)) pre (zs,ctx)=some y → width y≤U.eval S ∧ y.2=ctx := by + intro n O S xs zs ctx hw ha pre post he y hy + have hx : width (a:=.list a) xs≤g.eval S := (width_fst _).trans hw + have hzs : width (a:=.list b) zs≤g.eval S := (width_fst (a:=.list b) (b:=c) (zs,ctx)).trans ((width_snd _).trans hw) + have hc : width ctx≤g.eval S := (width_snd (a:=.list b) (b:=c) (zs,ctx)).trans ((width_snd _).trans hw) + have hl : pre.length≤g.eval S := by + have hh := (list_length_le_width xs).trans hx + rw [he,List.length_append] at hh; omega + have hh := fold_mapStep_bound O p pre zs ctx (f.eval S) (by + intro x hxp v hv + exact safe_output (hf O S (x,ctx) (ha x (by rw [he]; exact List.mem_append_left post hxp))) hv) y hy + have hm := Nat.mul_le_mul_right (2*f.eval S+2) hl + have hy' : width (a:=.list b) y.1≤g.eval S+g.eval S*(2*f.eval S+2) := by omega + refine ⟨?_,hh.2⟩ + have hw' : width y=2*width (a:=.list b) y.1+1+width ctx := by + rw [width_pair (a:=.list b) (b:=c),hh.2] + rw [hw'] + simp only [U,SizePolynomial.eval] + nlinarith + let W : SizePolynomial := .add (.mul (.constant 3) g) (.add U (.constant 1)) + apply oracleSafe_fold (mapStep p) _ + (fun n O S (z : Value (.prod a (.prod (.list b) c))) => width z≤W.eval S ∧ Q n O S (z.1,z.2.2)) + (oracleSafe_mapStep p Q ⟨f,hf⟩ W) (.add g U) + · intro n O S z hz; exact hz.1.trans (Nat.le_add_right _ _) + · intro n O S xs z hz pre post he y hy + exact (hacc O S xs z.1 z.2 hz.1 hz.2 pre post he y hy).1.trans (Nat.le_add_left _ _) + · intro n O S xs z hz pre x post he y hy + have hh := hacc O S xs z.1 z.2 hz.1 hz.2 pre (x::post) he y hy + have hm : x∈xs := by rw [he]; simp + have hx := (width_list_member x xs hm).trans ((width_fst _).trans hz.1) + refine ⟨?_,?_⟩ + · rw [width_pair (a:=a) (b:=.prod (.list b) c)] + change _≤3*g.eval S+(U.eval S+1); omega + · rw [hh.2]; exact hz.2 x hm +lemma oracleSafe_mapWith {a b c : DataType} (p : Expression (.prod a c) b) + (Q : OraclePredicate (.prod a c)) (hp : OracleSafe p Q) (g : SizePolynomial) : + OracleSafe (mapWith p) (fun n O S z => width z≤g.eval S ∧ ∀ x∈z.1,Q n O S (x,z.2)) := by + let R : OraclePredicate (.prod (.list a) c) := fun n O S z => width z≤g.eval S ∧ ∀ x∈z.1,Q n O S (x,z.2) + let prep : Expression (.prod (.list a) c) (.prod (.list a) (.prod (.list b) c)) := both fst (both (constant []) snd) + have hprep : OracleSafe prep R := oracleSafe_controlled prep (by dsimp [prep]; cc) R g (by intro n O S z hz; exact hz.1) + obtain ⟨f,hf⟩ := hprep + unfold mapWith + apply oracleSafe_compose _ _ R + (fun n O S (z : Value (.prod (.list a) (.prod (.list b) c))) => width z≤f.eval S ∧ ∀ x∈z.1,Q n O S (x,z.2.2)) ⟨f,hf⟩ + · exact oracleSafe_post _ _ _ (oracleSafe_mapFold p Q hp f) (by cc) + · intro n O S z hz y hy + refine ⟨safe_output (hf O S z hz) hy,?_⟩ + cases hy; exact hz.2 + +namespace Expression +abbrev InsertState := DataType.prod NN (.prod (.list NN) (.list NN)) +def insertStep : Expression (.prod NN InsertState) InsertState := + both (snd >>> fst) (both (both fst (snd >>> snd >>> fst) >>> Expression.cons) + (applyIf (both fst (snd >>> fst) >>> ratLess) + (both (snd >>> fst) (both fst (snd >>> snd >>> fst) >>> Expression.cons) >>> Expression.cons) + (both fst (snd >>> snd >>> snd) >>> Expression.cons))) +def insertInit : Expression (.prod NN (.list NN)) InsertState := + both fst (both (constant (b:=.list NN) []) + (both fst (constant (b:=.list NN) []) >>> Expression.cons (a:=NN))) +def insertRatCode : Expression (.prod NN (.list NN)) (.list NN) := + both (snd >>> listReverse) insertInit >>> fold insertStep >>> snd >>> snd +def sortRatCode : Expression (.list NN) (.list NN) := + both listReverse (constant []) >>> fold insertRatCode +def medianCode : Expression (.list NN) NN := + both (both sortRatCode (listLength >>> both (constant 2) ident >>> natDiv)) (constant (0,1)) >>> getDCode + +lemma run_insertStep {n : ℕ} (O : IndependenceOracle n) (q x : ℚ) (hq : 0≤q) (hx : 0≤x) + (xs ys : List ℚ) : + run O insertStep (rationalPair x,(rationalPair q,(xs.map rationalPair,ys.map rationalPair)))= + some (rationalPair q,((x::xs).map rationalPair, + (if x simp [h,run] +lemma run_insertRatCode {n : ℕ} (O : IndependenceOracle n) (q : ℚ) (hq : 0≤q) + (xs : List ℚ) (hx : ∀ x∈xs,0≤x) : + run O insertRatCode (rationalPair q,xs.map rationalPair)= + some ((xs.orderedInsert (·≤·) q).map rationalPair) := by + have hf : ∀ xs : List ℚ,(∀x∈xs,0≤x) → + foldValue (run O insertStep) (xs.map rationalPair).reverse + (rationalPair q,([], [rationalPair q]))= + some (rationalPair q,(xs.map rationalPair,(xs.orderedInsert (·≤·) q).map rationalPair)) := by + intro xs + induction xs with + | nil => intro hx; rfl + | cons x xs ih => + intro hx + simp only [List.map_cons,List.reverse_cons,foldValue_append] + rw [ih (fun y hy => hx y (by simp [hy])),Option.bind_some,foldValue] + rw [run_insertStep O q x hq (hx x (by simp)),Option.bind_some] + simp only [foldValue,List.orderedInsert_cons] + by_cases h : x some z.2.2)=_ + rw [hf xs hx] + rfl +lemma run_sortRatCode {n : ℕ} (O : IndependenceOracle n) (xs : List ℚ) (hx : ∀ x∈xs,0≤x) : + run O sortRatCode (xs.map rationalPair)=some ((xs.mergeSort (·≤·)).map rationalPair) := by + have hf : ∀ xs : List ℚ,(∀x∈xs,0≤x) → + foldValue (run O insertRatCode) (xs.map rationalPair).reverse []= + some ((xs.insertionSort (·≤·)).map rationalPair) := by + intro xs + induction xs with + | nil => intro hx; rfl + | cons x xs ih => + intro hx + simp only [List.map_cons,List.reverse_cons,foldValue_append] + rw [ih (fun y hy => hx y (by simp [hy])),Option.bind_some,foldValue] + rw [run_insertRatCode O x (hx x (by simp)) _ (by + intro y hy + exact hx y (by simpa using Or.inr ((List.perm_insertionSort _ _).mem_iff.mp hy)))] + rfl + simp only [sortRatCode,run_compose,run_both,run_constant,run_listReverse,Option.bind_some,Option.map_some] + change foldValue (run O insertRatCode) (xs.map rationalPair).reverse []=_ + rw [hf xs hx,List.mergeSort_eq_insertionSort] +lemma run_medianCode {n : ℕ} (O : IndependenceOracle n) (xs : List ℚ) (hx : ∀ x∈xs,0≤x) : + run O medianCode (xs.map rationalPair)=some (rationalPair (rationalMedian xs)) := by + simp only [medianCode,run_compose,run_both,run_ident,run_constant] + rw [run_sortRatCode O xs hx] + simp only [Option.bind_some,Option.map_some] + rw [run_listLength] + simp only [Option.bind_some,List.length_map] + simp only [run_compose,run_both,run_constant,run_ident,Option.bind_some,Option.map_some] + rw [run_natDiv] + simp only [Option.bind_some,Option.map_some] + rw [run_getDCode] + unfold rationalMedian + simp only [List.getD_eq_getElem?_getD,List.getElem?_map] + cases (xs.mergeSort (·≤·))[xs.length/2]? <;> rfl +end Expression + +lemma run_insertStep_raw {n : ℕ} (O : IndependenceOracle n) (x q : Value NN) + (xs ys : List (Value NN)) : run O insertStep (x,(q,(xs,ys)))= + some (q,(x::xs,if x.1*q.2 rfl +lemma insertFold_width {n : ℕ} (O : IndependenceOracle n) (xs : List (Value NN)) + (q : Value NN) (zs ys : List (Value NN)) (y : Value InsertState) + (hy : foldValue (run O insertStep) xs (q,(zs,ys))=some y) : + y.1=q ∧ width (a:=.list NN) y.2.1=width (a:=.list NN) zs+width (a:=.list NN) xs ∧ + width (a:=.list NN) y.2.2≤ max (width (a:=.list NN) ys) + (2*width (a:=NN) q+2+width (a:=.list NN) zs)+width (a:=.list NN) xs := by + induction xs generalizing zs ys with + | nil => cases hy; exact ⟨rfl,by rw [width_nil,Nat.add_zero],by rw [width_nil,Nat.add_zero]; exact Nat.le_max_left _ _⟩ + | cons x xs ih => + rw [foldValue,run_insertStep_raw,Option.bind_some] at hy + have hh := ih (x::zs) (if x.1*q.2 simp only [width_cons (a:=NN)] at hh ⊢ <;> omega +lemma controlled_insertStep : Controlled insertStep := by unfold insertStep; cc +lemma controlled_insertFold : Controlled (.fold insertStep) := by + apply controlled_fold _ controlled_insertStep (.add (.mul (.constant 5) .input) (.constant 5)) + intro n O xs z pre post he y hy + obtain ⟨q,zs,ys⟩ := z + have hh := insertFold_width O pre q zs ys y hy + have hp : width (a:=.list NN) pre≤width (a:=.list NN) xs := by + rw [he,width_list_append]; omega + rw [width_pair (a:=NN) (b:=.prod (.list NN) (.list NN)),hh.1, + width_pair (a:=.list NN) (b:=.list NN),hh.2.1] + change 2*width (a:=NN) q+1+(2*(width (a:=.list NN) zs+width (a:=.list NN) pre)+1+width (a:=.list NN) y.2.2)≤5*width (a:=.prod (.list NN) InsertState) (xs,(q,(zs,ys)))+5 + rw [width_pair (a:=.list NN) (b:=InsertState),width_pair (a:=NN) (b:=.prod (.list NN) (.list NN)), + width_pair (a:=.list NN) (b:=.list NN)] + omega +lemma controlled_insertRat : Controlled insertRatCode := by + have hi := controlled_insertFold + unfold insertRatCode insertInit; cc +lemma insertRat_width {n : ℕ} (O : IndependenceOracle n) (q : Value NN) (xs ys : List (Value NN)) + (hy : run O insertRatCode (q,xs)=some ys) : + width (a:=.list NN) ys≤width (a:=.list NN) xs+2*(2*width (a:=NN) q+2) := by + simp only [insertRatCode,insertInit,run_compose,run_both,run_fst,run_snd,run_constant, + Option.bind_some,Option.map_some,run_listReverse] at hy + change ((foldValue (run O insertStep) xs.reverse (q,([],[q]))).bind fun z => some z.2.2)=some ys at hy + cases he : foldValue (run O insertStep) xs.reverse (q,([],[q])) with + | none => simp [he] at hy + | some v => + simp only [he,Option.bind_some,Option.some.injEq] at hy + subst ys + have hh := (insertFold_width O xs.reverse q [] [q] v he).2.2 + simp only [width_nil (a:=NN),width_cons (a:=NN),width_list_reverse (a:=NN)] at hh + omega +lemma sortFold_width {n : ℕ} (O : IndependenceOracle n) (xs zs ys : List (Value NN)) + (hy : foldValue (run O insertRatCode) xs zs=some ys) : + width (a:=.list NN) ys≤width (a:=.list NN) zs+2*width (a:=.list NN) xs := by + induction xs generalizing zs with + | nil => cases hy; simp + | cons x xs ih => + rw [foldValue] at hy + cases he : run O insertRatCode (x,zs) with + | none => simp [he] at hy + | some v => + simp only [he,Option.bind_some] at hy + have hv := insertRat_width O x zs v he + have hh := ih v hy + rw [width_cons] + omega +lemma controlled_sortFold : Controlled (.fold insertRatCode) := by + apply controlled_fold _ controlled_insertRat (.mul (.constant 3) .input) + intro n O xs zs pre post he ys hy + have hh := sortFold_width O pre zs ys hy + have hp : width (a:=.list NN) pre≤width (a:=.list NN) xs := by + rw [he,width_list_append]; omega + change _≤3*width (a:=.prod (.list NN) (.list NN)) (xs,zs) + rw [width_pair (a:=.list NN) (b:=.list NN)] + omega +lemma controlled_sortRat : Controlled sortRatCode := by + have hi := controlled_sortFold + unfold sortRatCode; cc +lemma controlled_median : Controlled medianCode := by + have hi := controlled_sortRat + unfold medianCode; cc + +namespace Expression + +def optionalRatCode : Expression (Optional NN) NN := applyIf fst (constant (0,1)) snd +def singleCode : Expression (.prod AlgorithmParams BankData) NN := + Effect.algorithmCode >>> fst >>> applyIf fst (constant (0,1)) (snd >>> optionalRatCode) +def amplifiedCode : Expression (.prod AlgorithmParams (.list BankData)) NN := + swap >>> mapWith (swap >>> singleCode) >>> medianCode +lemma run_optionalRatCode {n : ℕ} (O : IndependenceOracle n) (x : Option ℚ) : + run O optionalRatCode (optionEncode rationalPair x)=some (rationalPair (x.getD 0)) := by + cases x <;> rfl +lemma run_singleCode {n : ℕ} (O : IndependenceOracle n) (x : Value AlgorithmParams) + (t : DrawTree (Option ℚ)) + (ht : Effect.Realizes O Effect.algorithmCode (optionEncode rationalPair) x t) + (bank : Bank) : + run O singleCode (x,bank)=some (rationalPair ((bankEval t bank).1.join.getD 0)) := by + rw [singleCode,run_compose,ht,Option.bind_some] + cases h : (bankEval t bank).1 with + | none => rfl + | some v => + cases v <;> rfl +lemma run_amplifiedCode {n : ℕ} (O : IndependenceOracle n) (x : Value AlgorithmParams) + (t : DrawTree (Option ℚ)) + (ht : Effect.Realizes O Effect.algorithmCode (optionEncode rationalPair) x t) + (banks : List Bank) (hz : ∀ bank∈banks,0≤(bankEval t bank).1.join.getD 0) : + run O amplifiedCode (x,banks)= + some (rationalPair (rationalMedian (banks.map (fun bank => (bankEval t bank).1.join.getD 0)))) := by + simp only [amplifiedCode,run_compose] + change ((run O (mapWith (swap >>> singleCode)) (banks,x)).bind (run O medianCode))=_ + have hm := run_mapWith_source O (swap >>> singleCode) (fun bank : Bank => bank) + (fun bank => rationalPair ((bankEval t bank).1.join.getD 0)) x + (fun bank => by change run O singleCode (x,bank)=_; exact run_singleCode O x t ht bank) banks + simp only [List.map_id_fun',id_eq] at hm + rw [hm] + simp only [Option.bind_some] + rw [show banks.map (fun bank => rationalPair ((bankEval t bank).1.join.getD 0))= + (banks.map (fun bank => (bankEval t bank).1.join.getD 0)).map rationalPair by simp only [List.map_map]; rfl] + apply run_medianCode + intro q hq + obtain ⟨bank,hbank,rfl⟩ := List.mem_map.mp hq + exact hz bank hbank +end Expression + +open Expression Effect +lemma safe_single : OracleSafe singleCode (bankScope algorithmScope) := by + unfold singleCode + exact oracleSafe_post _ _ _ safe_algorithm (by unfold optionalRatCode; cc) +def amplificationScope : OraclePredicate (.prod AlgorithmParams (.list BankData)) := + fun n O S z => algorithmScope n O S z.1 ∧ width (a:=.list BankData) z.2≤S +lemma amplificationScope_width : ∀ n O S z,amplificationScope n O S z → + width z≤(.add (.mul (.constant 2) (sourceWidthPoly 100)) (.add .input (.constant 1)) : SizePolynomial).eval S := by + intro n O S z hz + have hp := algorithmScope_width n O S z.1 hz.1 + have hb := hz.2 + rw [width_pair (a:=AlgorithmParams) (b:=.list BankData)] + change _≤2*(sourceWidthPoly 100).eval S+(S+1) + omega +lemma safe_amplified : OracleSafe amplifiedCode amplificationScope := by + let Q : OraclePredicate (.prod BankData AlgorithmParams) := fun n O S z => bankScope algorithmScope n O S (z.2,z.1) + let W : SizePolynomial := .add (.mul (.constant 2) .input) (.add (.constant 1) (sourceWidthPoly 100)) + have hq : OracleSafe (Expression.swap >>> singleCode) Q := by + refine oracleSafe_pull Expression.swap singleCode Q (bankScope algorithmScope) (by cc) W ?_ safe_single ?_ + · intro n O S z hz + have hp := algorithmScope_width n O S z.2 hz.1 + have hb : width (a:=BankData) z.1≤S := hz.2 + rw [width_pair (a:=BankData) (b:=AlgorithmParams)] + change 2*width (a:=BankData) z.1+1+width (a:=AlgorithmParams) z.2≤2*S+(1+(sourceWidthPoly 100).eval S) + omega + · intro n O S z hz y hy; cases hy; exact hz + let T : OraclePredicate (.prod (.list BankData) AlgorithmParams) := fun n O S z => width z≤W.eval S ∧ ∀ bank∈z.1,Q n O S (bank,z.2) + unfold amplifiedCode + apply oracleSafe_pull Expression.swap _ amplificationScope T (by cc) _ amplificationScope_width + (oracleSafe_post _ _ _ (oracleSafe_mapWith _ Q hq W) controlled_median) + intro n O S z hz y hy + cases hy + refine ⟨?_,?_⟩ + · have hp := algorithmScope_width n O S z.1 hz.1 + have hb := hz.2 + rw [width_pair (a:=.list BankData) (b:=AlgorithmParams)] + change _≤2*S+(1+(sourceWidthPoly 100).eval S) + omega + · intro bank hb + exact ⟨hz.1,(width_list_member bank z.2 hb).trans hz.2⟩ + +open Expression +abbrev FrozenData := DataType.prod NN (.prod NN NN) +def frozenValue (n r : ℕ) (ε δ : ℚ) : Value FrozenData := + ((n,r),((ε.num.natAbs,ε.den),(δ.num.natAbs,δ.den))) +namespace Expression + +def natPow : ℕ → Expression .nat .nat + | 0 => constant 1 + | k+1 => both ident (natPow k) >>> mul +lemma run_natPow {n : ℕ} (O : IndependenceOracle n) (k x : ℕ) : + run O (natPow k) x=some (x^k) := by + induction k with + | zero => rfl + | succ k ih => simp [natPow,run_compose,ih,run,pow_succ,Nat.mul_comm] +lemma controlled_natPow (k : ℕ) : Controlled (natPow k) := by + induction k with + | zero => unfold natPow; cc + | succ k ih => unfold natPow; cc + +def sumE {a} (p q : Expression a .nat) : Expression a .nat := both p q >>> add +def prodE {a} (p q : Expression a .nat) : Expression a .nat := both p q >>> mul +lemma run_sumE {n : ℕ} (O : IndependenceOracle n) {a} (p q : Expression a .nat) + (x : Value a) (u v : ℕ) (hp : run O p x=some u) (hq : run O q x=some v) : + run O (sumE p q) x=some (u+v) := by simp [sumE,run_compose,hp,hq,run] +lemma run_prodE {n : ℕ} (O : IndependenceOracle n) {a} (p q : Expression a .nat) + (x : Value a) (u v : ℕ) (hp : run O p x=some u) (hq : run O q x=some v) : + run O (prodE p q) x=some (u*v) := by simp [prodE,run_compose,hp,hq,run] +lemma controlled_sumE {a} (p q : Expression a .nat) (hp : Controlled p) (hq : Controlled q) : + Controlled (sumE p q) := by unfold sumE; cc +lemma controlled_prodE {a} (p q : Expression a .nat) (hp : Controlled p) (hq : Controlled q) : + Controlled (prodE p q) := by unfold prodE; cc + +def ceilDivCode : Expression NN .nat := + both fst (both (sumE snd fst) (constant 1) >>> natSub) >>> divRem >>> snd +lemma run_ceilDivCode {n : ℕ} (O : IndependenceOracle n) (a b : ℕ) (ha : 0>> toList >>> listLength +lemma run_lengthNatCode {n : ℕ} (O : IndependenceOracle n) (x : ℕ) : + run O lengthNatCode x=some x.bits.length := by + change run O (listLength (a:=.bool)) x.bits=_ + exact run_listLength O _ +lemma controlled_lengthNatCode : Controlled lengthNatCode := by + unfold lengthNatCode + have h := controlled_listLength (a:=.bool) + cc + +def annealLengthCode : Expression NN .nat := + prodE (prodE (constant 2) fst) (sumE fst (sumE snd (constant 5))) +lemma run_annealLengthCode {n : ℕ} (O : IndependenceOracle n) (x e : ℕ) : + run O annealLengthCode (x,e)=some (2*x*(x+(e+5))) := by + simp [annealLengthCode,prodE,sumE,run_compose,run] +lemma controlled_annealLengthCode : Controlled annealLengthCode := by unfold annealLengthCode prodE sumE; cc + +def sampleCountCode : Expression (.prod .nat NN) .nat := + sumE (prodE (prodE (prodE (constant (10^14)) + (sumE (snd >>> fst) (constant 1) >>> natPow 3)) (fst >>> natPow 14)) + (snd >>> snd >>> natPow 2)) (constant 1) +lemma run_sampleCountCode {n : ℕ} (O : IndependenceOracle n) (x L E : ℕ) : + run O sampleCountCode (x,(L,E))=some (10^14*(L+1)^3*x^14*E^2+1) := by + simp only [sampleCountCode,prodE,sumE,run_compose,run_both,run_constant,run_fst,run_snd, + Option.bind_some,Option.map_some,run_natPow] + rfl +lemma controlled_sampleCountCode : Controlled sampleCountCode := by + unfold sampleCountCode + apply controlled_sumE + · apply controlled_prodE + · apply controlled_prodE + · apply controlled_prodE + · cc + · apply controlled_compose + · apply controlled_sumE <;> cc + · exact controlled_natPow 3 + · apply controlled_compose + · cc + · exact controlled_natPow 14 + · apply controlled_compose + · cc + · apply controlled_compose + · cc + · exact controlled_natPow 2 + · cc + +def tauCode : Expression NN .nat := + prodE (prodE (constant 20) (fst >>> natPow 4)) + (sumE (prodE fst (sumE snd (constant 1))) (constant 2)) +def capCode : Expression NN .nat := + prodE (prodE (prodE (constant 2000) (sumE snd (constant 1) >>> natPow 2)) + (fst >>> natPow 2)) tauCode +lemma run_tauCode {n : ℕ} (O : IndependenceOracle n) (x L : ℕ) : + run O tauCode (x,L)=some (20*x^4*(x*(L+1)+2)) := by + simp only [tauCode,prodE,sumE,run_compose,run_both,run_constant,run_fst,run_snd, + Option.bind_some,Option.map_some,run_natPow] + rfl +lemma run_capCode {n : ℕ} (O : IndependenceOracle n) (x L : ℕ) : + run O capCode (x,L)=some (restartCap x L) := by + simp only [capCode,prodE,sumE,run_compose,run_both,run_constant,run_fst,run_snd, + Option.bind_some,Option.map_some,run_natPow] + simp only [run,Option.bind_some,Option.map_some] + rw [run_tauCode] + rfl +lemma controlled_tauCode : Controlled tauCode := by + unfold tauCode prodE sumE + have h4 := controlled_natPow 4 + cc +lemma controlled_capCode : Controlled capCode := by + unfold capCode prodE sumE + have h2 := controlled_natPow 2 + have ht := controlled_tauCode + cc + +def chunkValues {α : Type*} (m h : ℕ) (xs : List α) : List (List α) := + (List.range m).map (fun i => (xs.drop (i*h)).take h) +def chunkStep {a : DataType} : Expression (.prod .nat (.prod (.list a) .nat)) (.list a) := + both (both (snd >>> fst) (prodE fst (snd >>> snd)) >>> dropCode) (snd >>> snd) >>> takeCode +def chunksCode {a : DataType} : Expression (.prod (.list a) NN) (.list (.list a)) := + both ((snd >>> fst) >>> rangeCode) (both fst (snd >>> snd)) >>> mapWith chunkStep +lemma run_chunkStep {n : ℕ} (O : IndependenceOracle n) {a : DataType} + (i h : ℕ) (xs : List (Value a)) : + run O chunkStep (i,(xs,h))=some ((xs.drop (i*h)).take h) := by + simp only [chunkStep,prodE,run_compose,run_both,run_fst,run_snd,Option.bind_some,Option.map_some] + simp only [run,Option.map_some,Option.bind_some] + rw [run_dropCode,Option.bind_some,Option.bind_some,run_takeCode] +lemma run_chunksCode {n : ℕ} (O : IndependenceOracle n) {a : DataType} + (xs : List (Value a)) (m h : ℕ) : + run O chunksCode (xs,(m,h))=some (chunkValues m h xs) := by + simp only [chunksCode,run_compose,run_both,run_fst,run_snd,Option.bind_some,Option.map_some] + rw [run_rangeCode,Option.bind_some,Option.bind_some] + exact run_mapWith O chunkStep (fun i ctx => (ctx.1.drop (i*ctx.2)).take ctx.2) + (fun i ctx => run_chunkStep O i ctx.2 ctx.1) _ _ +lemma chunkValues_zero {α : Type*} (h : ℕ) (xs : List α) : chunkValues 0 h xs=[] := rfl +lemma chunkValues_succ {α : Type*} (m h : ℕ) (xs : List α) : + chunkValues (m+1) h xs=xs.take h::chunkValues m h (xs.drop h) := by + simp only [chunkValues,List.range_succ_eq_map,List.map_cons,List.map_map,Nat.zero_mul,List.drop_zero] + congr 1 + apply List.map_congr_left + intro i hi + simp only [Function.comp_apply,Nat.succ_eq_add_one,List.drop_drop,Nat.add_mul,Nat.one_mul,Nat.add_comm h] +lemma chunkValues_flatten {α : Type*} (h : ℕ) (xs : List (List α)) + (hx : ∀ x∈xs,x.length=h) : chunkValues xs.length h xs.flatten=xs := by + induction xs with + | nil => rfl + | cons x xs ih => + have hh := hx x (by simp) + have ht := ih (fun y hy => hx y (by simp [hy])) + rw [List.length_cons,chunkValues_succ,List.flatten_cons,←hh,List.take_left,List.drop_left,hh,ht] +lemma chunkValues_ofFn {α : Type*} (m h : ℕ) (f : Fin m → Fin h → α) : + chunkValues m h ((List.ofFn (fun i => List.ofFn (f i))).flatten)= + List.ofFn (fun i => List.ofFn (f i)) := by + convert chunkValues_flatten h (List.ofFn (fun i => List.ofFn (f i))) (by + intro xs hx + obtain ⟨i,rfl⟩ := List.mem_ofFn.mp hx + exact List.length_ofFn) using 1 ; simp +end Expression +lemma controlled_chunkStep {a : DataType} : Controlled (chunkStep (a:=a)) := by + unfold chunkStep prodE + cc +lemma attr_chunksCode {a : DataType} : AttrSafe (chunksCode (a:=a)) (fun S x => x.2.1≤S) := by + unfold chunksCode + apply attrSafe_post + · apply attrSafe_both + · apply attrSafe_pull _ rangeCode _ _ (by cc) attr_rangeCode + (fun S T h k hk => hk.trans h) + intro n O S x hx y hy + cases hy; exact hx + · exact attrSafe_controlled _ (by cc) _ + · exact controlled_mapWith _ controlled_chunkStep + +lemma ceil_nat_ratio (a b : ℕ) (ha : 0 rw [←Rat.num_div_den ε,inv_div] +open Expression Effect +namespace Expression +def frozenN : Expression FrozenData .nat := fst >>> fst +def frozenL : Expression FrozenData .nat := + both frozenN (snd >>> fst >>> snd >>> lengthNatCode) >>> annealLengthCode +def frozenE : Expression FrozenData .nat := snd >>> fst >>> ceilDivCode +def frozenSamples : Expression FrozenData .nat := + both frozenN (both frozenL frozenE) >>> sampleCountCode +def frozenParams : Expression FrozenData AlgorithmParams := + both fst (both (both frozenSamples frozenL) + (both (both frozenN frozenL >>> capCode) (both frozenN frozenL >>> tauCode))) +def frozenReps : Expression FrozenData .nat := + prodE (constant 64) (sumE (snd >>> snd >>> snd >>> lengthNatCode) (constant 1)) + +abbrev Recipe3 := DataType.prod .nat NN +def drawsCode : Expression Recipe3 .nat := + prodE (sumE (sumE (constant 1) + (prodE (prodE (prodE (constant 3) (snd >>> snd)) + (sumE (both fst (snd >>> snd) >>> capCode) (constant 1))) + (both fst (snd >>> snd) >>> tauCode))) + (prodE (constant 3) (snd >>> fst))) (sumE (snd >>> snd) (constant 1)) +def wordBoundCode : Expression Recipe3 .nat := + sumE (sumE (sumE + (prodE (constant 2) (sumE (sumE (constant 2) (prodE (snd >>> fst) (snd >>> snd))) + (prodE (prodE (constant 2) fst) (prodE fst (snd >>> snd))))) + (fst >>> natPow 2)) fst) (constant 4) +def frozenRecipe3 : Expression FrozenData Recipe3 := both frozenN (both frozenSamples frozenL) +def frozenDraws : Expression FrozenData .nat := frozenRecipe3 >>> drawsCode +def frozenWordBound : Expression FrozenData .nat := frozenRecipe3 >>> wordBoundCode +abbrev BankShape := DataType.prod .nat NN +abbrev PreparedData := DataType.prod AlgorithmParams BankShape +def frozenPrepared : Expression FrozenData PreparedData := + both frozenParams (both frozenReps (both frozenDraws frozenWordBound)) +def bitCountCode : Expression BankShape .nat := + prodE (prodE (prodE fst (snd >>> snd)) (sumE (snd >>> fst) (constant 6))) (snd >>> fst) +def frozenBitCount : Expression FrozenData .nat := + frozenPrepared >>> snd >>> bitCountCode +lemma run_frozenN {n : ℕ} (O : IndependenceOracle n) (r : ℕ) (ε δ : ℚ) : + run O frozenN (frozenValue n r ε δ)=some n := rfl +lemma run_frozenL {n : ℕ} (O : IndependenceOracle n) (r : ℕ) (ε δ : ℚ) : + run O frozenL (frozenValue n r ε δ)=some (annealLength n (accuracyExponent ε)) := by + simp only [frozenL,frozenN,run_compose,run_both,run_fst,run_snd,Option.bind_some,frozenValue] + rw [run_lengthNatCode,Option.map_some,Option.bind_some,run_annealLengthCode] + rfl +lemma run_frozenE {n : ℕ} (O : IndependenceOracle n) (r : ℕ) (ε δ : ℚ) (hε : 0<ε) : + run O frozenE (frozenValue n r ε δ)=some ⌈ε⁻¹⌉₊ := by + change run O ceilDivCode (ε.num.natAbs,ε.den)=_ + rw [run_ceilDivCode O _ _ (Int.natAbs_pos.mpr (ne_of_gt (Rat.num_pos.mpr hε))),inverse_ceiling_input ε hε] +lemma run_frozenSamples {n : ℕ} (O : IndependenceOracle n) (r : ℕ) (ε δ : ℚ) (hε : 0<ε) : + run O frozenSamples (frozenValue n r ε δ)=some (sampleCount n (annealLength n (accuracyExponent ε)) ε) := by + simp only [frozenSamples,run_compose,run_both,run_frozenN,run_frozenL,run_frozenE O r ε δ hε,Option.bind_some,Option.map_some] + rw [run_sampleCountCode]; rfl +lemma run_frozenParams {n : ℕ} (O : IndependenceOracle n) (r : ℕ) (ε δ : ℚ) (hε : 0<ε) : + run O frozenParams (frozenValue n r ε δ)=some (params n r (sampleCount n (annealLength n (accuracyExponent ε)) ε) (annealLength n (accuracyExponent ε))) := by + simp only [frozenParams,run_both,run_compose,run_fst,run_frozenN,run_frozenL,run_frozenSamples O r ε δ hε,Option.bind_some,Option.map_some] + rw [run_capCode,run_tauCode]; rfl +lemma run_frozenReps {n : ℕ} (O : IndependenceOracle n) (r : ℕ) (ε δ : ℚ) : + run O frozenReps (frozenValue n r ε δ)=some (repetitionCount δ) := by + simp only [frozenReps,prodE,sumE,run_compose,run_both,run_constant,run_snd,Option.bind_some,Option.map_some,frozenValue] + rw [run_lengthNatCode]; rfl +lemma run_drawsCode {n : ℕ} (O : IndependenceOracle n) (x N L : ℕ) : + run O drawsCode (x,(N,L))=some (algorithmDrawBound x N L) := by + simp only [drawsCode,prodE,sumE,run_compose,run_both,run_constant,run_fst,run_snd,Option.bind_some,Option.map_some] + rw [run_capCode O,run_tauCode O] + rfl +lemma run_wordBoundCode {n : ℕ} (O : IndependenceOracle n) (x N L : ℕ) : + run O wordBoundCode (x,(N,L))=some (drawWordBound x N L) := by + simp only [wordBoundCode,prodE,sumE,run_compose,run_both,run_constant,run_fst,run_snd,Option.bind_some,Option.map_some,run_natPow] + rfl +lemma run_frozenRecipe3 {n : ℕ} (O : IndependenceOracle n) (r : ℕ) (ε δ : ℚ) (hε : 0<ε) : + run O frozenRecipe3 (frozenValue n r ε δ)=some (n,(sampleCount n (annealLength n (accuracyExponent ε)) ε,annealLength n (accuracyExponent ε))) := by + simp only [frozenRecipe3,run_both,run_frozenN,run_frozenL,run_frozenSamples O r ε δ hε,Option.bind_some,Option.map_some] +lemma run_frozenPrepared {n : ℕ} (O : IndependenceOracle n) (r : ℕ) (ε δ : ℚ) (hε : 0<ε) : + let L := annealLength n (accuracyExponent ε) + let N := sampleCount n L ε + run O frozenPrepared (frozenValue n r ε δ)=some (params n r N L,(repetitionCount δ,(algorithmDrawBound n N L,drawWordBound n N L))) := by + simp only [frozenPrepared,frozenDraws,frozenWordBound,run_both,run_compose,run_frozenParams O r ε δ hε,run_frozenReps,run_frozenRecipe3 O r ε δ hε,Option.bind_some] + rw [run_drawsCode O,run_wordBoundCode O] + rfl +lemma run_bitCountCode {n : ℕ} (O : IndependenceOracle n) (R M H : ℕ) : + run O bitCountCode (R,(M,H))=some (R*H*(M+6)*M) := by + simp only [bitCountCode,prodE,sumE,run_compose,run_both,run_constant,run_fst,run_snd,Option.bind_some,Option.map_some] + rfl +lemma run_frozenBitCount {n : ℕ} (O : IndependenceOracle n) (r : ℕ) (ε δ : ℚ) (hε : 0<ε) : + run O frozenBitCount (frozenValue n r ε δ)=some (fairBitCount n ε δ) := by + simp only [frozenBitCount,run_compose,run_frozenPrepared O r ε δ hε,run_snd,Option.bind_some] + rfl +lemma controlled_frozenN : Controlled frozenN := by unfold frozenN; cc +lemma controlled_frozenL : Controlled frozenL := by + unfold frozenL + have hn := controlled_frozenN + have hl := controlled_lengthNatCode + have ha := controlled_annealLengthCode + cc +lemma controlled_frozenE : Controlled frozenE := by + unfold frozenE + have h := controlled_ceilDivCode + cc +lemma controlled_frozenSamples : Controlled frozenSamples := by + unfold frozenSamples + have hn := controlled_frozenN + have hl := controlled_frozenL + have he := controlled_frozenE + have hs := controlled_sampleCountCode + cc +lemma controlled_frozenParams : Controlled frozenParams := by + unfold frozenParams + have hn := controlled_frozenN + have hl := controlled_frozenL + have hs := controlled_frozenSamples + have hc := controlled_capCode + have ht := controlled_tauCode + cc +lemma controlled_frozenReps : Controlled frozenReps := by + unfold frozenReps prodE sumE + have h := controlled_lengthNatCode + cc +lemma controlled_drawsCode : Controlled drawsCode := by + unfold drawsCode prodE sumE + have hc := controlled_capCode + have ht := controlled_tauCode + cc +lemma controlled_wordBoundCode : Controlled wordBoundCode := by + unfold wordBoundCode prodE sumE + have h := controlled_natPow 2 + cc +lemma controlled_frozenRecipe3 : Controlled frozenRecipe3 := by + unfold frozenRecipe3 + have hn := controlled_frozenN + have hl := controlled_frozenL + have hs := controlled_frozenSamples + cc +lemma controlled_frozenPrepared : Controlled frozenPrepared := by + unfold frozenPrepared frozenDraws frozenWordBound + have hp := controlled_frozenParams + have hr := controlled_frozenReps + have h3 := controlled_frozenRecipe3 + have hd := controlled_drawsCode + have hw := controlled_wordBoundCode + cc +lemma controlled_bitCountCode : Controlled bitCountCode := by unfold bitCountCode prodE sumE; cc +lemma controlled_frozenBitCount : Controlled frozenBitCount := by + unfold frozenBitCount + have hp := controlled_frozenPrepared + have hb := controlled_bitCountCode + cc + +abbrev Shape3 := DataType.prod .nat NN +abbrev Shape4 := DataType.prod .nat Shape3 + +def rowsCode : Expression (.prod (.list .bool) NN) RandomRows := + chunksCode >>> mapEach fromList +def bankCode : Expression (.prod (.list .bool) Shape3) BankData := + both (both fst (both (snd >>> fst) (prodE (snd >>> snd >>> fst) (snd >>> snd >>> snd))) >>> chunksCode) + (snd >>> snd) >>> mapWith rowsCode +def banksCode : Expression (.prod (.list .bool) Shape4) (.list BankData) := + both (both fst (both (snd >>> fst) (prodE (snd >>> snd >>> fst) + (prodE (snd >>> snd >>> snd >>> fst) (snd >>> snd >>> snd >>> snd)))) >>> chunksCode) + (snd >>> snd) >>> mapWith bankCode +def shape4Code : Expression BankShape Shape4 := + both fst (both (snd >>> fst) (both (sumE (snd >>> fst) (constant 6)) (snd >>> snd))) +def reshapeCode : Expression (.prod .word BankShape) (.list BankData) := + both (fst >>> toList) (snd >>> shape4Code) >>> banksCode +lemma run_rowsCode {n : ℕ} (O : IndependenceOracle n) (xs : List Bool) (D H : ℕ) : + run O rowsCode (xs,(D,H))=some (chunkValues D H xs) := by + rw [rowsCode,run_compose,run_chunksCode,Option.bind_some] + simpa using run_mapEach O fromList (fun x => x) (run_fromList O) (chunkValues D H xs) +lemma run_bankCode {n : ℕ} (O : IndependenceOracle n) (xs : List Bool) (M D H : ℕ) : + run O bankCode (xs,(M,(D,H)))= + some ((chunkValues M (D*H) xs).map (chunkValues D H)) := by + simp only [bankCode,prodE,run_compose,run_both,run_fst,run_snd,Option.bind_some,Option.map_some] + simp only [run,Option.map_some,Option.bind_some,Option.bind_assoc] + change ((run O chunksCode (xs,(M,D*H))).bind fun ys => run O (mapWith rowsCode) (ys,(D,H)))=_ + rw [run_chunksCode,Option.bind_some] + exact run_mapWith O rowsCode (fun ys ctx => chunkValues ctx.1 ctx.2 ys) + (fun ys ctx => run_rowsCode O ys ctx.1 ctx.2) _ _ +lemma run_banksCode {n : ℕ} (O : IndependenceOracle n) (xs : List Bool) (R M D H : ℕ) : + run O banksCode (xs,(R,(M,(D,H))))= + some ((chunkValues R (M*(D*H)) xs).map (fun ys => + (chunkValues M (D*H) ys).map (chunkValues D H))) := by + simp only [banksCode,prodE,run_compose,run_both,run_fst,run_snd,Option.bind_some,Option.map_some] + simp only [run,Option.map_some,Option.bind_some,Option.bind_assoc] + change ((run O chunksCode (xs,(R,M*(D*H)))).bind fun ys => run O (mapWith bankCode) (ys,(M,(D,H))))=_ + rw [run_chunksCode,Option.bind_some] + exact run_mapWith O bankCode (fun ys ctx => + (chunkValues ctx.1 (ctx.2.1*ctx.2.2) ys).map (chunkValues ctx.2.1 ctx.2.2)) + (fun ys ctx => run_bankCode O ys ctx.1 ctx.2.1 ctx.2.2) _ _ +lemma run_shape4Code {n : ℕ} (O : IndependenceOracle n) (R M H : ℕ) : + run O shape4Code (R,(M,H))=some (R,(M,(M+6,H))) := rfl +lemma controlled_shape4Code : Controlled shape4Code := by unfold shape4Code sumE; cc +lemma attr_rowsCode : AttrSafe rowsCode (fun S z => z.2.1≤S) := by + unfold rowsCode + exact attrSafe_post _ _ _ attr_chunksCode (controlled_mapEach _ controlled_fromList) +lemma attr_bankCode : AttrSafe bankCode (fun S z => z.2.1≤S ∧ z.2.2.1≤S) := by + let A : Attribute (.prod (.list (.list .bool)) NN) := fun S z => z.2.1≤S + have hm : A.Mono := by intro S T h z hz; exact hz.trans h + unfold bankCode + refine attrSafe_compose _ _ _ A ?_ ?_ hm ?_ + · apply attrSafe_both + · apply attrSafe_pull _ chunksCode _ _ (by unfold prodE; cc) attr_chunksCode + (fun S T h z hz => hz.trans h) + intro n O S z hz y hy + cases hy; exact hz.1 + · exact attrSafe_controlled _ (by cc) _ + · apply attrSafe_mono _ (attrSafe_mapWith rowsCode (fun S z => z.2.1≤S) + (fun S T h z hz => hz.trans h) attr_rowsCode) + intro S z hz xs hxs; exact hz + · intro n O S z hz y hy + have he := (run_both_parts O _ _ z y hy).2 + have he' : z.2.2=y.2 := Option.some.inj he + dsimp only [A] + rw [←he'] + exact hz.2 +lemma attr_banksCode : AttrSafe banksCode (fun S z => z.2.1≤S ∧ z.2.2.1≤S ∧ z.2.2.2.1≤S) := by + let A : Attribute (.prod (.list (.list .bool)) Shape3) := fun S z => z.2.1≤S ∧ z.2.2.1≤S + have hm : A.Mono := by intro S T h z hz; exact ⟨hz.1.trans h,hz.2.trans h⟩ + unfold banksCode + refine attrSafe_compose _ _ _ A ?_ ?_ hm ?_ + · apply attrSafe_both + · apply attrSafe_pull _ chunksCode _ _ (by unfold prodE; cc) attr_chunksCode + (fun S T h z hz => hz.trans h) + intro n O S z hz y hy + cases hy; exact hz.1 + · exact attrSafe_controlled _ (by cc) _ + · apply attrSafe_mono _ (attrSafe_mapWith bankCode (fun S z => z.2.1≤S ∧ z.2.2.1≤S) + (fun S T h z hz => ⟨hz.1.trans h,hz.2.trans h⟩) attr_bankCode) + intro S z hz xs hxs; exact hz + · intro n O S z hz y hy + have he := (run_both_parts O _ _ z y hy).2 + have he' : z.2.2=y.2 := Option.some.inj he + dsimp only [A] + rw [←he'] + exact hz.2 +lemma attr_reshapeCode : AttrSafe reshapeCode (fun S z => z.2.1≤S ∧ z.2.2.1+6≤S) := by + unfold reshapeCode + apply attrSafe_pull _ banksCode _ _ (by have h := controlled_shape4Code; cc) attr_banksCode + (fun S T h z hz => ⟨hz.1.trans h,hz.2.1.trans h,hz.2.2.trans h⟩) + intro n O S z hz y hy + cases hy + exact ⟨hz.1,(Nat.le_add_right _ 6).trans hz.2,hz.2⟩ + +def preambleCode : Expression FrozenData (.prod .word PreparedData) := + both (frozenBitCount >>> unary) frozenPrepared +abbrev RawData := DataType.prod .word PreparedData +abbrev AmplifyInput := DataType.prod AlgorithmParams (.list BankData) +def reshapePrepared : Expression RawData AmplifyInput := + both (snd >>> fst) (both fst (snd >>> snd) >>> reshapeCode) +def finishCode : Expression AmplifyInput NN := + applyIf (fst >>> fst >>> fst >>> natEqZero) amplifiedCode (constant (1,1)) +def postambleCode : Expression RawData NN := reshapePrepared >>> finishCode +end Expression +lemma safe_preamble : OracleSafe preambleCode (fun _ O S x => + width x≤S ∧ ∀ k,run O frozenBitCount x=some k → k≤S) := by + unfold preambleCode + apply oracleSafe_both + · apply oracleSafe_compose _ unary _ (fun _ _ S k => k≤S) + (oracleSafe_controlled _ controlled_frozenBitCount _ .input (by intro n O S x hx; exact hx.1)) + (oracleSafe_lift _ _ polySafe_unary) + intro n O S x hx k hk; exact hx.2 k hk + · exact oracleSafe_controlled _ controlled_frozenPrepared _ .input (by intro n O S x hx; exact hx.1) +def rawScope : OraclePredicate RawData := fun n O S z => + width z≤S ∧ z.2.2.1≤S ∧ z.2.2.2.1+6≤S ∧ + z.2.1.1.1=n ∧ (0 z.2.2.1≤S ∧ z.2.2.2.1+6≤S) + (fun S T h z hz => ⟨hz.1.trans h,hz.2.trans h⟩) ?_ rawScope .input + (by intro n O S z hz; exact hz.1) (by intro n O S z hz; exact ⟨hz.2.1,hz.2.2.1⟩) + apply attrSafe_pull _ reshapeCode _ _ (by cc) attr_reshapeCode + (fun S T h z hz => ⟨hz.1.trans h,hz.2.trans h⟩) + intro n O S z hz y hy; cases hy; exact hz +def finishScope : OraclePredicate AmplifyInput := fun n O S z => + width z≤S ∧ z.1.1.1=n ∧ (0 finishScope n O (g.eval S) z) + ⟨f,hf⟩ (oracleSafe_reparam _ _ safe_finish g) + intro n O S z hz y hy + have he : z.2.1=y.1 := Option.some.inj (run_both_parts O _ _ z y hy).1 + refine ⟨(safe_output (hf O S z hz) hy).trans (Nat.le_add_right _ _),?_,?_⟩ + · rw [←he]; exact hz.2.2.2.1 + · intro hn + rw [←he] + exact algorithmScope_mono (hz.2.2.2.2 hn) (Nat.le_add_left _ _) + +def coinPush {k : ℕ} (a : Fin (k+8)) : Block k := fork .coin (push a false) (push a true) +lemma runs_coinPush {k n : ℕ} (O : IndependenceOracle n) (bits : ℕ → Bool) + (R : Registers k) (a : Fin (k+8)) : + Runs (coinPush a) O bits R (Function.update R a (bits 0::R a)) 2 0 2 := by + cases h : bits 0 + · exact fork_run_no .coin _ _ O bits (by simp [Test.result,h]) + (runs_push O (fun i => bits (1+i)) R a false) + · exact fork_run_yes .coin _ _ O bits (by simp [Test.result,h]) + (runs_push O (fun i => bits (1+i)) R a true) + +def sampledWord : ℕ → (ℕ → Bool) → Word + | 0,_ => [] + | m+1,bits => sampledWord m (fun i => bits (3+i)) ++ [bits 1] +lemma sampledWord_length (m : ℕ) (bits : ℕ → Bool) : (sampledWord m bits).length=m := by + induction m generalizing bits with + | zero => rfl + | succ m ih => simp [sampledWord,ih] +lemma sampledWord_get (m : ℕ) (bits : ℕ → Bool) (i : ℕ) (hi : i < m) : + (sampledWord m bits)[i]'(by rw [sampledWord_length]; exact hi)= + bits (3*(m-1-i)+1) := by + induction m generalizing bits i with + | zero => omega + | succ m ih => + by_cases him : i < m + · simp only [sampledWord] + rw [List.getElem_append_left (by rw [sampledWord_length]; exact him),ih _ _ him] + congr 1 + omega + · have he : i=m := by omega + subst i + simp [sampledWord,List.getElem_append_right,sampledWord_length] +lemma sampledWord_ofFn (m : ℕ) (bits : ℕ → Bool) : + sampledWord m bits=List.ofFn (fun i : Fin m => bits (3*(m-1-i.val)+1)) := by + apply List.ext_getElem + · simp [sampledWord_length] + · intro i hi hj + simp only [List.getElem_ofFn] + exact sampledWord_get m bits i (by simpa [sampledWord_length] using hi) +lemma runs_coinLoop {k n : ℕ} (O : IndependenceOracle n) (bits : ℕ → Bool) + (R : Registers k) (a b : Fin (k+8)) (hab : a≠b) (xs : Word) : + Runs (repeatBlock (coinPush b) a) O bits (Function.update R a xs) + (Function.update (Function.update R b (sampledWord xs.length bits ++ R b)) a []) + (3*xs.length+1) 0 (3*xs.length+1) := by + induction xs generalizing R bits with + | nil => + intro q w + have h := repeatProgram_empty (coinPush b).code a O R q w bits + convert h using 1 <;> simp [repeatBlock,sampledWord,state,loopConfig] ; rfl + | cons x xs ih => + have hp := runs_coinPush O (fun i => bits (1+i)) (Function.update R a xs) b + have hi := ih (fun i => bits (3+i)) (Function.update R b (bits 1::R b)) + have hc : Function.update (Function.update R a xs) b (bits 1::(Function.update R a xs) b)= + Function.update (Function.update R b (bits 1::R b)) a xs := by + rw [Function.update_of_ne hab.symm] + exact Function.update_comm hab .. + rw [hc] at hp + have h := runs_repeat_cons (b:=x) hp hi + convert h using 1 <;> simp only [sampledWord,List.length_cons] + · simp only [Function.update_self,List.append_assoc,List.singleton_append] + rw [Function.update_idem] + · omega + · omega + +lemma runs_pack_any {k n : ℕ} (a d : Fin (k+8)) (had : a≠d) + (O : IndependenceOracle n) (R : Registers k) (bits : ℕ → Bool) : + Runs (pack a d) O bits R + (Function.update (Function.update R a []) d (pair (R a) (R d))) + (3*(R a).length+2) 0 (3*(R a).length+2) := by + have h := runs_pack a d had O R (R a) (R d) bits + have he : pairRegisters R a d (R a) (R d)=R := by + simp [pairRegisters] + rw [he] at h + exact h +lemma runs_move_any {k n : ℕ} (a b d : Fin (k+8)) (hab : a≠b) (had : a≠d) (hbd : b≠d) + (O : IndependenceOracle n) (R : Registers k) (hb : R b=[]) (hd : R d=[]) + (bits : ℕ → Bool) : + Runs (move a b d) O bits R (Function.update (Function.update R a []) d (R a)) + (4*(R a).length+2) 0 (4*(R a).length+2) := by + have h := runs_move a b d hab had hbd O R (R a) [] bits + have he : tripleRegisters R a b d (R a) [] []=R := by + unfold tripleRegisters pairRegisters + rw [Function.update_eq_self] + have h1 : Function.update R b []=R := by rw [←hb, Function.update_eq_self] + rw [h1] + rw [←hd,Function.update_eq_self] + rw [he] at h + simp only [List.append_nil] at h + convert h using 1 + simp only [tripleRegisters, pairRegisters] + rw [Function.update_comm hab,show Function.update R b []=R by rw [←hb,Function.update_eq_self]] +def sixRegs (a b c d e f : Word) : Registers 1 := fun i => + match i.val with + | 0 => a | 1 => b | 2 => c | 3 => d | 4 => e | 5 => f | _ => [] +def inputPack : Block 1 := + seq (pack 4 5) (seq (pack 2 3) (seq (pack 3 5) (seq (pack 0 1) + (seq (pack 1 5) (move 5 2 0))))) +def inputTime (a b c d e f : Word) : ℕ := + (3*e.length+2)+((3*c.length+2)+((3*(pair c d).length+2)+((3*a.length+2)+ + ((3*(pair a b).length+2)+(4*(pair (pair a b) (pair (pair c d) (pair e f))).length+2))))) +lemma runs_inputPack {n : ℕ} (O : IndependenceOracle n) (bits : ℕ → Bool) + (a b c d e f : Word) : + Runs inputPack O bits (sixRegs a b c d e f) + (regs (pair (pair a b) (pair (pair c d) (pair e f))) [] [] []) + (inputTime a b c d e f) 0 (inputTime a b c d e f) := by + have h1 (bits) : Runs (pack 4 5) O bits (sixRegs a b c d e f) + (sixRegs a b c d [] (pair e f)) (3*e.length+2) 0 (3*e.length+2) := by + convert runs_pack_any (k:=1) 4 5 (by decide) O (sixRegs a b c d e f) bits using 1 + all_goals first | rfl | (funext i; fin_cases i <;> simp [sixRegs]) + have h2 (bits) : Runs (pack 2 3) O bits (sixRegs a b c d [] (pair e f)) + (sixRegs a b [] (pair c d) [] (pair e f)) (3*c.length+2) 0 (3*c.length+2) := by + convert runs_pack_any (k:=1) 2 3 (by decide) O (sixRegs a b c d [] (pair e f)) bits using 1 + all_goals first | rfl | (funext i; fin_cases i <;> simp [sixRegs]) + have h3 (bits) : Runs (pack 3 5) O bits (sixRegs a b [] (pair c d) [] (pair e f)) + (sixRegs a b [] [] [] (pair (pair c d) (pair e f))) + (3*(pair c d).length+2) 0 (3*(pair c d).length+2) := by + convert runs_pack_any (k:=1) 3 5 (by decide) O (sixRegs a b [] (pair c d) [] (pair e f)) bits using 1 + all_goals first | rfl | (funext i; fin_cases i <;> simp [sixRegs]) + have h4 (bits) : Runs (pack 0 1) O bits (sixRegs a b [] [] [] (pair (pair c d) (pair e f))) + (sixRegs [] (pair a b) [] [] [] (pair (pair c d) (pair e f))) + (3*a.length+2) 0 (3*a.length+2) := by + convert runs_pack_any (k:=1) 0 1 (by decide) O (sixRegs a b [] [] [] (pair (pair c d) (pair e f))) bits using 1 + all_goals first | rfl | (funext i; fin_cases i <;> simp [sixRegs]) + have h5 (bits) : Runs (pack 1 5) O bits (sixRegs [] (pair a b) [] [] [] (pair (pair c d) (pair e f))) + (sixRegs [] [] [] [] [] (pair (pair a b) (pair (pair c d) (pair e f)))) + (3*(pair a b).length+2) 0 (3*(pair a b).length+2) := by + convert runs_pack_any (k:=1) 1 5 (by decide) O (sixRegs [] (pair a b) [] [] [] (pair (pair c d) (pair e f))) bits using 1 + all_goals first | rfl | (funext i; fin_cases i <;> simp [sixRegs]) + have h6 (bits) : Runs (move 5 2 0) O bits + (sixRegs [] [] [] [] [] (pair (pair a b) (pair (pair c d) (pair e f)))) + (regs (pair (pair a b) (pair (pair c d) (pair e f))) [] [] []) + (4*(pair (pair a b) (pair (pair c d) (pair e f))).length+2) 0 + (4*(pair (pair a b) (pair (pair c d) (pair e f))).length+2) := by + convert runs_move_any (k:=1) 5 2 0 (by decide) (by decide) (by decide) O + (sixRegs [] [] [] [] [] (pair (pair a b) (pair (pair c d) (pair e f)))) rfl rfl bits using 1 + all_goals first | rfl | (funext i; fin_cases i <;> simp [sixRegs,regs]) + exact runs_seq O bits (h1 _) (runs_seq O _ (h2 _) (runs_seq O _ (h3 _) + (runs_seq O _ (h4 _) (runs_seq O _ (h5 _) (h6 _))))) +lemma inputTime_bound (a b c d e f : Word) : + inputTime a b c d e f≤100*(6+a.length+b.length+c.length+d.length+e.length+f.length) := by + simp only [inputTime,pair_length] + omega +lemma frozen_width (n r : ℕ) (ε δ : ℚ) : + width (frozenValue n r ε δ)≤4*inputLength n r ε δ := by + simp only [width,frozenValue,encode,pair_length] + unfold inputLength + omega +lemma initialConfig_state (s n r : ℕ) (ε δ : ℚ) : + initialConfig 1 s n r ε δ=state (sixRegs n.bits r.bits ε.num.natAbs.bits ε.den.bits + δ.num.natAbs.bits δ.den.bits) 0 0 0 := rfl + +open Expression +def preparedValue (n r : ℕ) (ε δ : ℚ) : Value PreparedData := + let L := annealLength n (accuracyExponent ε) + let N := sampleCount n L ε + (params n r N L,(repetitionCount δ,(algorithmDrawBound n N L,drawWordBound n N L))) +def rawValue (n r : ℕ) (ε δ : ℚ) (w : BitWord (fairBitCount n ε δ)) : Value RawData := + (List.ofFn w,preparedValue n r ε δ) + +open Expression +namespace SizePolynomial +def pow (p : SizePolynomial) : ℕ → SizePolynomial + | 0 => .constant 1 + | k+1 => .mul (pow p k) p +lemma eval_pow (p : SizePolynomial) (k x : ℕ) : (p.pow k).eval x=(p.eval x)^k := by + induction k with + | zero => rfl + | succ k ih => simp only [pow,eval,ih,pow_succ] +end SizePolynomial + +def masterParameter (n r : ℕ) (ε δ : ℚ) : ℕ := + 1+n+inputLength n r ε δ+⌈ε⁻¹⌉₊+Nat.clog 2 ⌈δ⁻¹⌉₊ +def atomPoly : SizePolynomial := .mul (.constant (10^22)) (.pow (.add .input (.constant 1)) 24) +def tauPoly : SizePolynomial := + .mul (.mul (.constant 20) (atomPoly.pow 4)) + (.add (.mul atomPoly (.add atomPoly (.constant 1))) (.constant 2)) +def capPoly : SizePolynomial := + .mul (.mul (.mul (.constant 2000) ((SizePolynomial.add atomPoly (.constant 1)).pow 2)) (atomPoly.pow 2)) tauPoly +def fairPoly : SizePolynomial := .mul (.constant (10^66)) ((SizePolynomial.add .input (.constant 1)).pow 73) +def sourceEnvelope : SizePolynomial := + .add (.add (.add (.add atomPoly tauPoly) capPoly) fairPoly) (.constant 6) +def scopeEnvelope : SizePolynomial := .mul (.constant 100) (.add sourceEnvelope (.constant 1)) +lemma master_pos (n r : ℕ) (ε δ : ℚ) : 0 < masterParameter n r ε δ := by + unfold masterParameter; omega +lemma rank_le_ground {n r : ℕ} (M : Matroid (Fin n)) (hr : M.eRank=(r:ℕ∞)) : r ≤ n := by + have h := M.eRank_le_encard_ground + rw [hr] at h + have hg : M.E.encard ≤ n := (Set.encard_mono (Set.subset_univ _)).trans_eq (by simp) + exact_mod_cast h.trans hg +lemma master_fields (n r : ℕ) (ε δ : ℚ) : + n ≤ masterParameter n r ε δ ∧ inputLength n r ε δ ≤ masterParameter n r ε δ ∧ + ε.den.bits.length ≤ masterParameter n r ε δ ∧ δ.den.bits.length ≤ masterParameter n r ε δ ∧ + ⌈ε⁻¹⌉₊ ≤ masterParameter n r ε δ ∧ bitResourceParameter n ε δ ≤ masterParameter n r ε δ := by + unfold masterParameter bitResourceParameter inputLength + omega +lemma atom_ge (T : ℕ) : T ≤ atomPoly.eval T ∧ 1 ≤ atomPoly.eval T := by + simp only [atomPoly,SizePolynomial.eval,SizePolynomial.eval_pow] + have h : T+1 ≤ (T+1)^24 := Nat.le_self_pow (by decide) _ + constructor <;> omega +lemma recipe_atom_bounds (n r : ℕ) (ε δ : ℚ) : + let T := masterParameter n r ε δ + let L := annealLength n (accuracyExponent ε) + let N := sampleCount n L ε + n ≤ atomPoly.eval T ∧ L ≤ atomPoly.eval T ∧ N ≤ atomPoly.eval T ∧ + drawWordBound n N L ≤ atomPoly.eval T ∧ algorithmDrawBound n N L ≤ atomPoly.eval T ∧ + repetitionCount δ ≤ atomPoly.eval T := by + let T := masterParameter n r ε δ + have hf := master_fields n r ε δ + have hh := polynomial_recipe_bounds n ε.den.bits.length δ.den.bits.length ⌈ε⁻¹⌉₊ T + (master_pos n r ε δ) hf.1 hf.2.2.1 hf.2.2.2.1 hf.2.2.2.2.1 + have hp (k : ℕ) (hk : k ≤ 24) : T^k ≤ (T+1)^24 := + (Nat.pow_le_pow_left (by omega : T ≤ T+1) k).trans + (Nat.pow_le_pow_right (by omega : 1 ≤ T+1) hk) + have h1 := hp 1 (by omega) + simp only [pow_one] at h1 + refine ⟨hf.1.trans (atom_ge T).1,?_,?_,?_,?_,?_⟩ + all_goals simp only [atomPoly,SizePolynomial.eval_pow,SizePolynomial.eval] + all_goals dsimp only [T] at h1 hp hh + · exact hh.1.trans (by have h := hp 2 (by omega); omega) + · exact hh.2.1.trans (by have h := hp 22 (by omega); omega) + · exact hh.2.2.1.trans (by have h := hp 24 (by omega); omega) + · exact hh.2.2.2.1.trans (by have h := hp 24 (by omega); omega) + · exact hh.2.2.2.2.trans (by omega) +lemma envelope_parameters (n r : ℕ) (ε δ : ℚ) (hr : r ≤ n) : + let T := masterParameter n r ε δ + let S := sourceEnvelope.eval T + let L := annealLength n (accuracyExponent ε) + let N := sampleCount n L ε + n ≤ S ∧ r ≤ S ∧ N ≤ S ∧ L ≤ S ∧ restartCap n L ≤ S ∧ 20*n^4*(n*(L+1)+2) ≤ S ∧ + repetitionCount δ ≤ S ∧ algorithmDrawBound n N L+6 ≤ S ∧ drawWordBound n N L ≤ S ∧ + fairBitCount n ε δ ≤ S ∧ inputLength n r ε δ ≤ S := by + let T := masterParameter n r ε δ + let A := atomPoly.eval T + let L := annealLength n (accuracyExponent ε) + have hh := recipe_atom_bounds n r ε δ + have ht : 20*n^4*(n*(L+1)+2) ≤ tauPoly.eval T := by + simp only [tauPoly,SizePolynomial.eval,SizePolynomial.eval_pow] + gcongr + · exact hh.1 + · exact hh.1 + · exact hh.2.1 + have hc : restartCap n L ≤ capPoly.eval T := by + unfold restartCap + simp only [capPoly,SizePolynomial.eval,SizePolynomial.eval_pow] + gcongr <;> first | exact hh.2.1 | exact hh.1 + have hb : fairBitCount n ε δ ≤ fairPoly.eval T := by + apply (fairBitCount_polynomial n ε δ).trans + simp only [fairPoly,SizePolynomial.eval,SizePolynomial.eval_pow] + gcongr + have hf := (master_fields n r ε δ).2.2.2.2.2 + omega + have hi : inputLength n r ε δ ≤ atomPoly.eval T := + (master_fields n r ε δ).2.1.trans (atom_ge T).1 + dsimp only [sourceEnvelope,SizePolynomial.eval] + dsimp only at hh + dsimp only [T,L] at ht hc hb hi + exact ⟨by omega,by omega,by omega,by omega,by omega,by omega, + by omega,by omega,by omega,by omega,by omega⟩ + +open Expression Effect +lemma width_six (a b c d e f : ℕ) : + width (a:=FrozenData) ((a,b),((c,d),(e,f)))= + 4*a.bits.length+2*b.bits.length+4*c.bits.length+2*d.bits.length+ + 2*e.bits.length+f.bits.length+7 := by + rw [width_pair (a:=NN) (b:=.prod NN NN),width_pair (a:=NN) (b:=NN)] + simp only [width_pair (a:=.nat) (b:=.nat),width_nat] + omega +lemma width_frozen (n r : ℕ) (ε δ : ℚ) : + width (frozenValue n r ε δ)≤4*inputLength n r ε δ := by + rw [frozenValue,width_six] + unfold inputLength + omega +lemma width_prepared_bound (n r : ℕ) (ε δ : ℚ) (hr : r≤n) : + width (preparedValue n r ε δ)≤35*sourceEnvelope.eval (masterParameter n r ε δ)+17 := by + have hh := envelope_parameters n r ε δ hr + dsimp only at hh + have hn := (bits_length_le_value n).trans hh.1 + have hr := (bits_length_le_value r).trans hh.2.1 + have hN := (bits_length_le_value _).trans hh.2.2.1 + have hL := (bits_length_le_value _).trans hh.2.2.2.1 + have hc := (bits_length_le_value _).trans hh.2.2.2.2.1 + have ht := (bits_length_le_value _).trans hh.2.2.2.2.2.1 + have hR := (bits_length_le_value _).trans hh.2.2.2.2.2.2.1 + have hM := (bits_length_le_value _).trans (show algorithmDrawBound n + (sampleCount n (annealLength n (accuracyExponent ε)) ε) (annealLength n (accuracyExponent ε))≤ + sourceEnvelope.eval (masterParameter n r ε δ) from by omega) + have hH := (bits_length_le_value _).trans hh.2.2.2.2.2.2.2.2.1 + rw [preparedValue,width_pair (a:=AlgorithmParams) (b:=BankShape),params,width_six, + width_pair (a:=.nat) (b:=NN),width_pair (a:=.nat) (b:=.nat)] + simp only [width_nat] + omega +lemma scopeEnvelope_ge (T : ℕ) : sourceEnvelope.eval T≤ scopeEnvelope.eval T := by + simp only [scopeEnvelope,SizePolynomial.eval] + omega +lemma rawValue_scope {n : ℕ} (r : ℕ) (M₁ M₂ : Matroid (Fin n)) (O : IndependenceOracle n) + (hO : ExactOracles M₁ M₂ O) (hE₁ : M₁.E=Set.univ) (hE₂ : M₂.E=Set.univ) + (hr₁ : M₁.eRank=(r:ℕ∞)) (ε δ : ℚ) (w : BitWord (fairBitCount n ε δ)) : + rawScope n O (scopeEnvelope.eval (masterParameter n r ε δ)) (rawValue n r ε δ w) := by + have hr := rank_le_ground M₁ hr₁ + have hs := scopeEnvelope_ge (masterParameter n r ε δ) + have hh := envelope_parameters n r ε δ hr + dsimp only at hh + have hw := width_prepared_bound n r ε δ hr + refine ⟨?_,hh.2.2.2.2.2.2.1.trans hs,hh.2.2.2.2.2.2.2.1.trans hs,rfl,?_⟩ + · rw [rawValue,width_pair (a:=.word) (b:=PreparedData),width_word,List.length_ofFn] + simp only [scopeEnvelope,SizePolynomial.eval] + omega + · intro hn + let m : SamplerModel n O := ⟨M₁,M₂,hO,hE₁,hE₂,hn,r, + sampleCount n (annealLength n (accuracyExponent ε)) ε,annealLength n (accuracyExponent ε)⟩ + refine ⟨m,?_,rfl⟩ + exact ⟨hh.1.trans hs,hh.2.1.trans hs,hh.2.2.1.trans hs,hh.2.2.2.1.trans hs, + hh.2.2.2.2.1.trans hs,hh.2.2.2.2.2.1.trans hs⟩ +lemma frozen_preamble_scope {n : ℕ} (O : IndependenceOracle n) (r : ℕ) (ε δ : ℚ) + (hr : r≤n) (hε : 0<ε) : + width (frozenValue n r ε δ)≤ scopeEnvelope.eval (masterParameter n r ε δ) ∧ + ∀ k,run O frozenBitCount (frozenValue n r ε δ)=some k → + k≤ scopeEnvelope.eval (masterParameter n r ε δ) := by + have hh := envelope_parameters n r ε δ hr + dsimp only at hh + constructor + · have hw := width_frozen n r ε δ + simp only [scopeEnvelope,SizePolynomial.eval] + omega + · intro k hk + rw [run_frozenBitCount O r ε δ hε,Option.some.injEq] at hk + rw [←hk] + exact hh.2.2.2.2.2.2.2.2.2.1.trans (scopeEnvelope_ge _) + +open Expression +lemma compile_safe_bound {n : ℕ} (O : IndependenceOracle n) {a b : DataType} + (p : Expression a b) (S : ℕ) (x : Value a) (y : Value b) + (hs : Safe O S p x) (hr : run O p x=some y) : + Bounded (compile p) O (encode x) (encode y) + (chargeCoefficient p*(S+n+1)^chargeDegree p) := by + rw [←evaluate_forget] at hr + cases he : evaluate O p x with + | none => simp [he] at hr + | some v => + rcases v with ⟨y',c⟩ + simp only [he,Option.map_some,Option.some.injEq] at hr + subst y' + exact bounded_mono (compile_correct O p x y c he) (evaluate_polynomial O p S x y c hs he) + +def compiledMajorant {a b : DataType} (p : Expression a b) (f : SizePolynomial) : SizePolynomial := + .mul (.constant (chargeCoefficient p)) ((SizePolynomial.add + (.add f .input) (.constant 1)).pow (chargeDegree p)) +lemma compile_majorant {n : ℕ} (O : IndependenceOracle n) {a b : DataType} + (p : Expression a b) (f : SizePolynomial) (T : ℕ) (hn : n≤T) + (x : Value a) (y : Value b) (hs : Safe O (f.eval T) p x) (hr : run O p x=some y) : + Bounded (compile p) O (encode x) (encode y) ((compiledMajorant p f).eval T) := by + apply bounded_mono (compile_safe_bound O p (f.eval T) x y hs hr) + simp only [compiledMajorant,SizePolynomial.eval,SizePolynomial.eval_pow] + gcongr + +lemma frozen_uniform_safe : ∃ fp fq : SizePolynomial, + ∀ (n r : ℕ) (M₁ M₂ : Matroid (Fin n)) (O : IndependenceOracle n) (ε δ : ℚ), + ExactOracles M₁ M₂ O → M₁.E=Set.univ → M₂.E=Set.univ → M₁.eRank=(r:ℕ∞) → 0<ε → + Safe O (fp.eval (masterParameter n r ε δ)) preambleCode (frozenValue n r ε δ) ∧ + ∀ w : BitWord (fairBitCount n ε δ), + Safe O (fq.eval (masterParameter n r ε δ)) postambleCode (rawValue n r ε δ w) := by + obtain ⟨fp,hp⟩ := safe_preamble + obtain ⟨fq,hq⟩ := safe_postamble + refine ⟨fp.subst scopeEnvelope,fq.subst scopeEnvelope,?_⟩ + intro n r M₁ M₂ O ε δ hO hE₁ hE₂ hr hε + simp only [SizePolynomial.eval_subst] + refine ⟨hp O _ _ (frozen_preamble_scope O r ε δ (rank_le_ground M₁ hr) hε),?_⟩ + intro w + exact hq O _ _ (rawValue_scope r M₁ M₂ O hO hE₁ hE₂ hr ε δ w) +lemma SizePolynomial.monomial_bound (p : SizePolynomial) (T : ℕ) (hT : 0 if i=6 then a else if i=7 then b else [] +def outputPack : Block 1 := seq (unpack 0 6) (move 0 1 7) +def outputTime (a b : Word) : ℕ := (3*a.length+1)+(4*b.length+2) +lemma runs_outputPack {n : ℕ} (O : IndependenceOracle n) (bits : ℕ → Bool) (a b : Word) : + Runs outputPack O bits (regs (pair a b) [] [] []) (outRegs a b) + (outputTime a b) 0 (outputTime a b) := by + let mid : Registers 1 := fun i => if i=0 then b else if i=6 then a else [] + have h1 (bits) : Runs (unpack 0 6) O bits (regs (pair a b) [] [] []) mid + (3*a.length+1) 0 (3*a.length+1) := by + convert runs_unpack_packed (k:=1) 0 6 (by decide) O (fun _ => []) a b bits using 1 <;> + funext i <;> fin_cases i <;> simp [pairRegisters,regs,mid,pair] + have h2 (bits) : Runs (move 0 1 7) O bits mid (outRegs a b) + (4*b.length+2) 0 (4*b.length+2) := by + convert runs_move_any (k:=1) 0 1 7 (by decide) (by decide) (by decide) O mid + (by simp [mid]) (by simp [mid]) bits using 1 + all_goals first | rfl | (funext i; fin_cases i <;> simp [mid,outRegs]) + exact runs_seq O bits (h1 _) (h2 _) +lemma outputTime_bound (a b : Word) : outputTime a b≤4*(a.length+b.length)+3 := by + unfold outputTime + omega +lemma runs_coinLoop_regs {n : ℕ} (O : IndependenceOracle n) (bits : ℕ → Bool) + (x counter : Word) : + Runs (repeatBlock (coinPush 2) 1) O bits (regs x counter [] []) + (regs x [] (sampledWord counter.length bits) []) + (3*counter.length+1) 0 (3*counter.length+1) := by + have h := runs_coinLoop O bits (regs x [] [] []) 1 2 (by decide) counter + simpa only [update_regs_one,update_regs_two,regs_two,List.append_nil] using h +lemma runs_randomPack {n : ℕ} (O : IndependenceOracle n) (bits : ℕ → Bool) (p w : Word) : + Runs (pack 2 0) O bits (regs p [] w []) (regs (pair w p) [] [] []) + (3*w.length+2) 0 (3*w.length+2) := by + simpa only [update_regs_zero,update_regs_two,regs_two,regs_zero] using + runs_pack_any (k:=1) 2 0 (by decide) O (regs p [] w []) bits + +def pipeline (pre post : Block 1) : Block 1 := + seq inputPack (seq pre (seq (unpack 0 1) (seq (repeatBlock (coinPush 2) 1) + (seq (pack 2 0) (seq post outputPack))))) +def pipelineTime (i pre f post a b : ℕ) : ℕ := + i+(pre+((3*f+1)+((3*f+1)+((3*f+2)+(post+((3*a+1)+(4*b+2))))))) +lemma runs_pipeline {n : ℕ} (O : IndependenceOracle n) (bits : ℕ → Bool) + (a b c d e f : Word) (pre post : Block 1) (counter params x y : Word) + (tp qp wp tq qq wq : ℕ) + (hp : Computes pre O (pair (pair a b) (pair (pair c d) (pair e f))) + (pair counter params) tp qp wp) + (hq : Computes post O + (pair (sampledWord counter.length (fun j => bits (inputTime a b c d e f+tp+(3*counter.length+1)+j))) params) + (pair x y) tq qq wq) : + Runs (pipeline pre post) O bits (sixRegs a b c d e f) (outRegs x y) + (pipelineTime (inputTime a b c d e f) tp counter.length tq x.length y.length) + (qp+qq) + (pipelineTime (inputTime a b c d e f) wp counter.length wq x.length y.length) := by + have h0 := runs_inputPack O bits a b c d e f + have h1 := hp [] (fun j => bits (inputTime a b c d e f+j)) + have h2 := split_pair O counter params [] [] (fun j => bits (inputTime a b c d e f+(tp+j))) + simp only [List.append_nil] at h2 + let bs := fun j => bits (inputTime a b c d e f+(tp+((3*counter.length+1)+j))) + have h3 := runs_coinLoop_regs O bs params counter + have h4 := runs_randomPack O (fun j => bs (3*counter.length+1+j)) params (sampledWord counter.length bs) + have h5 := hq [] (fun j => bs (3*counter.length+1+(3*(sampledWord counter.length bs).length+2+j))) + have he : (fun j => bits (inputTime a b c d e f+tp+(3*counter.length+1)+j))=bs := by + funext j; dsimp [bs]; congr 1; omega + rw [he] at h5 + have h6 := runs_outputPack O + (fun j => bs (3*counter.length+1+(3*(sampledWord counter.length bs).length+2+(tq+j)))) x y + have h := runs_seq O bits h0 (runs_seq O _ h1 (runs_seq O _ h2 + (runs_seq O _ h3 (runs_seq O _ h4 (runs_seq O _ h5 h6))))) + simpa only [pipeline,pipelineTime,outputTime,sampledWord_length,Nat.zero_add,Nat.add_zero] using h + +def physicalWord (start m : ℕ) (bits : ℕ → Bool) : BitWord m := + fun i => bits (start+3*(m-1-i.val)+1) +lemma sampledWord_physical (start m : ℕ) (bits : ℕ → Bool) : + sampledWord m (fun j => bits (start+j))=List.ofFn (physicalWord start m bits) := by + rw [sampledWord_ofFn] + apply congrArg List.ofFn + funext i + unfold physicalWord + congr 1 +def physicalPosition (start m B : ℕ) (h : start+3*m+1≤B) (i : Fin m) : Fin B := + ⟨start+3*(m-1-i.val)+1,by have hi := i.isLt; omega⟩ +lemma physicalPosition_injective (start m B : ℕ) (h : start+3*m+1≤B) : + Function.Injective (physicalPosition start m B h) := by + intro i j he + have hh := congrArg Fin.val he + dsimp only [physicalPosition] at hh + apply Fin.ext + have hi := i.isLt + have hj := j.isLt + omega +lemma physicalWord_finite (start m B : ℕ) (h : start+3*m+1≤B) (w : BitWord B) : + physicalWord start m (finiteBits w)=fun i => w (physicalPosition start m B h i) := by + funext i + unfold physicalWord finiteBits physicalPosition + simp only [dite_eq_left (show start+3*(m-1-i.val)+1 φ (physicalWord start m (finiteBits w)))=uniformAverage φ := by + simp_rw [physicalWord_finite start m B h] + exact uniformAverage_bitEmbedding m B _ (physicalPosition_injective start m B h) φ + +def terminalState (p : Block 1) (x y : Word) (q w : ℕ) : MachineConfig 1 p.size := + ⟨outRegs x y,lastLabel p.size,some ((binaryValue x:ℚ)/(binaryValue y:ℚ)),q,w+x.length+y.length+1⟩ +lemma runs_terminal {n : ℕ} (p : Block 1) (O : IndependenceOracle n) (bits : ℕ → Bool) + (R : Registers 1) (x y : Word) (t q w : ℕ) (h : Runs p O bits R (outRegs x y) t q w) : + execution p.code O (state R 0 0 0) bits (t+1)=terminalState p x y q w := by + rw [execution,h 0 0] + simp only [Nat.zero_add] + unfold machineStep state + simp only [Option.isSome_none,Bool.false_eq_true,ite_false,p.exit_halt] + simp only [outRegs,] + rfl +lemma input_state (s n r : ℕ) (ε δ : ℚ) : + initialConfig 1 s n r ε δ=state + (sixRegs n.bits r.bits ε.num.natAbs.bits ε.den.bits δ.num.natAbs.bits δ.den.bits) 0 0 0 := rfl +lemma terminal_rational (p : Block 1) (z : ℚ) (hz : 0≤z) (q w : ℕ) : + (terminalState p (rationalPair z).1.bits (rationalPair z).2.bits q w).output=some z := by + change some ((binaryValue (rationalPair z).1.bits:ℚ)/(binaryValue (rationalPair z).2.bits:ℚ))=some z + rw [binaryValue_bits,binaryValue_bits,rationalPair_value hz] + +def pipelineBudget (i F cp cq W : ℕ) : ℕ := i+cp+9*F+cq+5*W+10 +lemma pipeline_budget (i F cp cq W tp qp wp tq qq wq a b : ℕ) + (htp : tp≤cp) (hqp : qp≤cp) (hwp : wp≤cp) + (htq : tq≤cq) (hqq : qq≤cq) (hwq : wq≤cq) (ho : 2*a+1+b≤W) : + pipelineTime i tp F tq a b+1≤pipelineBudget i F cp cq W ∧ + qp+qq≤pipelineBudget i F cp cq W ∧ + pipelineTime i wp F wq a b+a+b+1≤pipelineBudget i F cp cq W ∧ + i+tp+(3*F+1)+3*F+1≤pipelineBudget i F cp cq W := by + unfold pipelineTime pipelineBudget + omega + +lemma pipeline_budgeted {n : ℕ} (O : IndependenceOracle n) + (a b c d e f : Word) (pre post : Block 1) (counter params : Word) + (cp cq W B : ℕ) + (hp : Bounded pre O (pair (pair a b) (pair (pair c d) (pair e f))) + (pair counter params) cp) + (v : BitWord counter.length → ℚ) (hv : ∀ w,0≤v w) + (hq : ∀ w,Bounded post O (pair (List.ofFn w) params) + (pair (rationalPair (v w)).1.bits (rationalPair (v w)).2.bits) cq ∧ + 2*(rationalPair (v w)).1.bits.length+1+(rationalPair (v w)).2.bits.length≤W) + (hB : pipelineBudget (inputTime a b c d e f) counter.length cp cq W≤B) : + ∃ start,start+3*counter.length+1≤B ∧ ∀ bits : ℕ → Bool, + let out := execution (pipeline pre post).code O (state (sixRegs a b c d e f) 0 0 0) bits B + out.output=some (v (physicalWord start counter.length bits)) ∧ + out.oracleCalls≤B ∧ out.bitOperations≤B := by + obtain ⟨tp,qp,wp,htp,hqp,hwp,hp⟩ := hp + let start := inputTime a b c d e f+tp+(3*counter.length+1) + have hs : start+3*counter.length+1≤B := by + apply le_trans _ hB + unfold start pipelineBudget + omega + refine ⟨start,hs,?_⟩ + intro bits + let w := physicalWord start counter.length bits + obtain ⟨⟨tq,qq,wq,htq,hqq,hwq,hq⟩,ho⟩ := hq w + have hr := runs_pipeline O bits a b c d e f pre post counter params + (rationalPair (v w)).1.bits (rationalPair (v w)).2.bits tp qp wp tq qq wq hp + (by rw [sampledWord_physical]; exact hq) + have hb := pipeline_budget (inputTime a b c d e f) counter.length cp cq W + tp qp wp tq qq wq (rationalPair (v w)).1.bits.length (rationalPair (v w)).2.bits.length + htp hqp hwp htq hqq hwq ho + have ht := runs_terminal (pipeline pre post) O bits _ _ _ _ _ _ hr + have hout := terminal_rational (pipeline pre post) (v w) (hv w) (qp+qq) + (pipelineTime (inputTime a b c d e f) wp counter.length wq + (rationalPair (v w)).1.bits.length (rationalPair (v w)).2.bits.length) + have hsome : (execution (pipeline pre post).code O (state (sixRegs a b c d e f) 0 0 0) bits + (pipelineTime (inputTime a b c d e f) tp counter.length tq + (rationalPair (v w)).1.bits.length (rationalPair (v w)).2.bits.length+1)).output.isSome := by + rw [ht,hout]; rfl + have he := execution_extend_output (pipeline pre post).code O (state (sixRegs a b c d e f) 0 0 0) + bits _ B (hb.1.trans hB) hsome + dsimp only + rw [he,ht] + exact ⟨hout,hb.2.1.trans hB,hb.2.2.1.trans hB⟩ + +lemma pipeline_budgeted_length {n : ℕ} (O : IndependenceOracle n) + (a b c d e f : Word) (pre post : Block 1) (counter params : Word) + (F cp cq W B : ℕ) (hF : counter.length=F) + (hp : Bounded pre O (pair (pair a b) (pair (pair c d) (pair e f))) + (pair counter params) cp) + (v : BitWord F → ℚ) (hv : ∀ w,0≤v w) + (hq : ∀ w,Bounded post O (pair (List.ofFn w) params) + (pair (rationalPair (v w)).1.bits (rationalPair (v w)).2.bits) cq ∧ + 2*(rationalPair (v w)).1.bits.length+1+(rationalPair (v w)).2.bits.length≤W) + (hB : pipelineBudget (inputTime a b c d e f) F cp cq W≤B) : + ∃ start,start+3*F+1≤B ∧ ∀ bits : ℕ → Bool, + let out := execution (pipeline pre post).code O (state (sixRegs a b c d e f) 0 0 0) bits B + out.output=some (v (physicalWord start F bits)) ∧ + out.oracleCalls≤B ∧ out.bitOperations≤B := by + subst F + exact pipeline_budgeted O a b c d e f pre post counter params cp cq W B hp v hv hq hB + +open Expression + +def totalResourcePoly (fp fq : SizePolynomial) : SizePolynomial := + .mul (.constant 200) (.add (.add (.add sourceEnvelope (compiledMajorant preambleCode fp)) + (compiledMajorant postambleCode fq)) (.add fq (.constant 1))) +lemma totalResourcePoly_budget (fp fq : SizePolynomial) (n r : ℕ) (ε δ : ℚ) (hr : r≤n) : + pipelineBudget + (inputTime n.bits r.bits ε.num.natAbs.bits ε.den.bits δ.num.natAbs.bits δ.den.bits) + (fairBitCount n ε δ) ((compiledMajorant preambleCode fp).eval (masterParameter n r ε δ)) + ((compiledMajorant postambleCode fq).eval (masterParameter n r ε δ)) + (fq.eval (masterParameter n r ε δ)) ≤ + (totalResourcePoly fp fq).eval (masterParameter n r ε δ) := by + have hi := inputTime_bound n.bits r.bits ε.num.natAbs.bits ε.den.bits δ.num.natAbs.bits δ.den.bits + change _ ≤ 100*inputLength n r ε δ at hi + have ha := envelope_parameters n r ε δ hr + have hF := ha.2.2.2.2.2.2.2.2.2.1 + have hI := ha.2.2.2.2.2.2.2.2.2.2 + simp only [pipelineBudget,totalResourcePoly,SizePolynomial.eval] + omega + +def fprasBlock : Block 1 := pipeline (compile preambleCode) (compile postambleCode) + +open Expression Effect +open scoped Classical +noncomputable def treeBankOutput (t : DrawTree (Option ℚ)) (bank : Bank) : ℚ := + (bankEval t bank).1.join.getD 0 +noncomputable def treeBanksOutput (t : DrawTree (Option ℚ)) (banks : List Bank) : ℚ := + rationalMedian (banks.map (treeBankOutput t)) +lemma treeBankOutput_all (t : DrawTree (Option ℚ)) (Z : ℕ) + (ht : DrawTree.All (fun a : Option ℚ => ∀ z,a=some z → 0≤z ∧ (Z=0 → z=0)) t) + (bank : Bank) : 0≤treeBankOutput t bank ∧ (Z=0 → treeBankOutput t bank=0) := by + unfold treeBankOutput + cases h : (bankEval t bank).1 with + | none => simp + | some a => + cases a with + | none => simp + | some z => + simpa only [Option.join_some,Option.getD_some] using bankEval_all t _ ht bank (some z) h z rfl +lemma treeBanksOutput_all (t : DrawTree (Option ℚ)) (Z : ℕ) + (ht : DrawTree.All (fun a : Option ℚ => ∀ z,a=some z → 0≤z ∧ (Z=0 → z=0)) t) + (banks : List Bank) : 0≤treeBanksOutput t banks ∧ (Z=0 → treeBanksOutput t banks=0) := by + constructor + · apply rationalMedian_all (fun z => 0≤z) _ (by norm_num) + intro z hz + obtain ⟨bank,hbank,rfl⟩ := List.mem_map.mp hz + exact (treeBankOutput_all t Z ht bank).1 + · intro hZ + apply rationalMedian_all (fun z => z=0) _ rfl + intro z hz + obtain ⟨bank,hbank,rfl⟩ := List.mem_map.mp hz + exact (treeBankOutput_all t Z ht bank).2 hZ +lemma reindexed_bank_law {t u : DrawTree (Option ℚ)} (h : DrawTree.Reindexed t u) + (H D M : ℕ) (ht : DrawTree.Fits H M t) (φ : ℚ → ℝ) : + uniformAverage (fun bits : Fin M → Fin D → BitWord H => φ (treeBankOutput u (bankEncode bits)))= + uniformAverage (fun bits : Fin M → Fin D → BitWord H => φ ((DrawTree.run H D M t bits).join.getD 0)) := by + unfold treeBankOutput + simp only [bankEval_run H D M u (h.fits H M ht)] + exact (h.run_observable H D M ht (fun a : Option (Option ℚ) => φ (a.join.getD 0))).symm +lemma reindexed_banks_law {t u : DrawTree (Option ℚ)} (h : DrawTree.Reindexed t u) + (H D M R : ℕ) (ht : DrawTree.Fits H M t) (φ : ℚ → ℝ) : + uniformAverage (fun bits : Fin R → Fin M → Fin D → BitWord H => + φ (treeBanksOutput u (List.ofFn (fun i => bankEncode (bits i)))))= + uniformAverage (fun bits : Fin R → Fin M → Fin D → BitWord H => + φ (rationalMedian (List.ofFn (fun i => (DrawTree.run H D M t (bits i)).join.getD 0)))) := by + simp only [treeBanksOutput,List.map_ofFn,Function.comp_def] + exact uniformAverage_independent_eq (fun bits => treeBankOutput u (bankEncode bits)) + (fun bits => (DrawTree.run H D M t bits).join.getD 0) (reindexed_bank_law h H D M ht) R + (fun z => φ (rationalMedian (List.ofFn z))) +lemma canonicalTree_all {n : ℕ} (hn : 0 ∀ z,a=some z → 0≤z ∧ (commonBaseCount M₁ M₂=0 → z=0)) + (canonicalAlgorithmTree n hn r O N L) := by + apply DrawTree.All.mono + ((canonicalAlgorithmTree_to_rational n hn r O N L M₁ M₂ hO hE₁ hE₂ hr₁ hr₂).symm.all _ + (rationalAlgorithmTree_all n hn M₁ M₂ N L)) + intro a ha z hz + exact ⟨(ha z hz).1,(ha z hz).2 hE₂ (hr₁.trans hr₂.symm)⟩ + +open Expression +lemma bitMatrix_apply (a b : ℕ) (w : BitWord (a*b)) (i : Fin a) (j : Fin b) : + bitMatrixEquiv a b w i j=w (finProdFinEquiv (i,j)) := rfl +lemma ofFn_bitMatrix (a b : ℕ) (w : BitWord (a*b)) : + List.ofFn w=(List.ofFn (fun i => List.ofFn (bitMatrixEquiv a b w i))).flatten := by + rw [List.ofFn_mul] + apply congrArg List.flatten + apply congrArg List.ofFn + funext i + apply congrArg List.ofFn + funext j + rw [bitMatrix_apply] + congr 1 + apply Fin.ext + simp [finProdFinEquiv,Nat.mul_comm,Nat.add_comm] +lemma chunks_bitMatrix (a b : ℕ) (w : BitWord (a*b)) : + chunkValues a b (List.ofFn w)=List.ofFn (fun i => List.ofFn (bitMatrixEquiv a b w i)) := by + rw [ofFn_bitMatrix,chunkValues_ofFn] +lemma run_banksCode_four {n : ℕ} (O : IndependenceOracle n) (R M D H : ℕ) + (w : BitWord (R*(M*(D*H)))) : + run O banksCode (List.ofFn w,(R,(M,(D,H))))= + some (List.ofFn (fun i => bankEncode (fourBitEquiv R M D H w i))) := by + rw [run_banksCode] + simp only [chunks_bitMatrix,List.map_ofFn,Function.comp_def] + rfl +lemma ofFn_finCongr {a b : ℕ} (h : a=b) (w : BitWord a) : + List.ofFn w=List.ofFn ((Equiv.arrowCongr (finCongr h) (Equiv.refl Bool)) w) := by + subst b + rfl +lemma run_reshapeCode_four {n : ℕ} (O : IndependenceOracle n) (R M H : ℕ) + (w : BitWord (R*(M*((M+6)*H)))) : + run O reshapeCode (List.ofFn w,(R,(M,H)))= + some (List.ofFn (fun i => bankEncode (fourBitEquiv R M (M+6) H w i))) := by + change run O banksCode (List.ofFn w,(R,(M,(M+6,H))))=_ + exact run_banksCode_four O R M (M+6) H w +lemma run_reshapeCode_cast {n a : ℕ} (O : IndependenceOracle n) (R M H : ℕ) + (h : a=R*(M*((M+6)*H))) (w : BitWord a) : + run O reshapeCode (List.ofFn w,(R,(M,H)))= + some (List.ofFn (fun i => bankEncode (fourBitEquiv R M (M+6) H + ((Equiv.arrowCongr (finCongr h) (Equiv.refl Bool)) w) i))) := by + subst a + exact run_reshapeCode_four O R M H w + +def bankReshapeEquiv {a : ℕ} (R M H : ℕ) (h : a=R*(M*((M+6)*H))) : + BitWord a ≃ (Fin R → Fin M → Fin (M+6) → BitWord H) := + (Equiv.arrowCongr (finCongr h) (Equiv.refl Bool)).trans (fourBitEquiv R M (M+6) H) +lemma run_reshapeCode_equiv {n a : ℕ} (O : IndependenceOracle n) (R M H : ℕ) + (h : a=R*(M*((M+6)*H))) (w : BitWord a) : + run O reshapeCode (List.ofFn w,(R,(M,H)))= + some (List.ofFn (fun i => bankEncode (bankReshapeEquiv R M H h w i))) := by + exact run_reshapeCode_cast O R M H h w +lemma reshape_count (n : ℕ) (ε δ : ℚ) : + let L := annealLength n (accuracyExponent ε) + let N := sampleCount n L ε + let M := algorithmDrawBound n N L + let H := drawWordBound n N L + fairBitCount n ε δ=repetitionCount δ*(M*((M+6)*H)) := by + change repetitionCount δ * drawWordBound n (sampleCount n (annealLength n (accuracyExponent ε)) ε) + (annealLength n (accuracyExponent ε)) * _ * _ = _ + ac_rfl + +def reshapeWordEquiv (n : ℕ) (ε δ : ℚ) : BitWord (fairBitCount n ε δ) ≃ FPRASBank n ε δ := + bankReshapeEquiv (repetitionCount δ) + (algorithmDrawBound n (sampleCount n (annealLength n (accuracyExponent ε)) ε) (annealLength n (accuracyExponent ε))) + (drawWordBound n (sampleCount n (annealLength n (accuracyExponent ε)) ε) (annealLength n (accuracyExponent ε))) + (reshape_count n ε δ) +lemma run_reshapeCode_source {n : ℕ} (O : IndependenceOracle n) (ε δ : ℚ) + (w : BitWord (fairBitCount n ε δ)) : + let L := annealLength n (accuracyExponent ε) + let N := sampleCount n L ε + run O reshapeCode (List.ofFn w,(repetitionCount δ,(algorithmDrawBound n N L,drawWordBound n N L)))= + some (List.ofFn (fun i => bankEncode (reshapeWordEquiv n ε δ w i))) := by + exact run_reshapeCode_equiv O _ _ _ (reshape_count n ε δ) w + +open Expression +open scoped Classical + +lemma run_preamble_generic {n : ℕ} (O : IndependenceOracle n) (x : Value FrozenData) + (F : ℕ) (p : Value PreparedData) + (hF : run O frozenBitCount x=some F) (hp : run O frozenPrepared x=some p) : + ∃ counter : Word,counter.length=F ∧ run O preambleCode x=some (counter,p) := by + obtain ⟨counter,hc,hl⟩ := run_unary O F + refine ⟨counter,hl,?_⟩ + simp only [preambleCode,run_both,run_compose,hF,hc,hp,Option.bind_some,Option.map_some] +lemma run_preambleCode {n : ℕ} (O : IndependenceOracle n) (r : ℕ) (ε δ : ℚ) (hε : 0<ε) : + ∃ counter : Word,counter.length=fairBitCount n ε δ ∧ + run O preambleCode (frozenValue n r ε δ)=some (counter,preparedValue n r ε δ) := by + exact run_preamble_generic O _ _ _ (run_frozenBitCount O r ε δ hε) (run_frozenPrepared O r ε δ hε) + +lemma run_reshapePrepared_generic {n : ℕ} (O : IndependenceOracle n) (w : Word) + (p : Value AlgorithmParams) (shape : Value BankShape) (banks : Value (.list BankData)) + (h : run O reshapeCode (w,shape)=some banks) : + run O reshapePrepared (w,(p,shape))=some (p,banks) := by + simp only [reshapePrepared,run_both,run_compose,run_fst,run_snd,Option.bind_some,Option.map_some,h] +lemma run_reshapePrepared {n : ℕ} (O : IndependenceOracle n) (r : ℕ) (ε δ : ℚ) + (w : BitWord (fairBitCount n ε δ)) : + let L := annealLength n (accuracyExponent ε) + let N := sampleCount n L ε + run O reshapePrepared (rawValue n r ε δ w)= + some (params n r N L,List.ofFn (fun i => bankEncode (reshapeWordEquiv n ε δ w i))) := by + exact run_reshapePrepared_generic O _ _ _ _ (run_reshapeCode_source O ε δ w) + +def OutputCertificate {n : ℕ} (r : ℕ) (M₁ M₂ : Matroid (Fin n)) + (O : IndependenceOracle n) (ε δ : ℚ) + (v : BitWord (fairBitCount n ε δ) → ℚ) : Prop := + (∀ w,run O postambleCode (rawValue n r ε δ w)=some (rationalPair (v w))) ∧ + (∀ w,0≤v w ∧ (commonBaseCount M₁ M₂=0 → v w=0)) ∧ + (∀ φ : ℚ → ℝ,uniformAverage (fun w => φ (v w))= + uniformAverage (fun banks : FPRASBank n ε δ => φ (canonicalBoundedOutput n r O ε δ banks))) +lemma output_certificate {n : ℕ} (r : ℕ) (M₁ M₂ : Matroid (Fin n)) (O : IndependenceOracle n) + (hO : ExactOracles M₁ M₂ O) (hE₁ : M₁.E=Set.univ) (hE₂ : M₂.E=Set.univ) + (hr₁ : M₁.eRank=(r:ℕ∞)) (hr₂ : M₂.eRank=(r:ℕ∞)) + (ε δ : ℚ) : ∃ v,OutputCertificate r M₁ M₂ O ε δ v := by + let L := annealLength n (accuracyExponent ε) + let N := sampleCount n L ε + by_cases hn : 0 + treeBanksOutput u (List.ofFn (fun i => bankEncode (reshapeWordEquiv n ε δ w i))) + refine ⟨v,?_,?_,?_⟩ + · intro w + rw [postambleCode,run_compose,run_reshapePrepared,Option.bind_some] + have hz : ∀ bank∈List.ofFn (fun i => bankEncode (reshapeWordEquiv n ε δ w i)), + 0≤(bankEval u bank).1.join.getD 0 := fun bank _ => (treeBankOutput_all u _ huall bank).1 + have hh := run_amplifiedCode O (params n r N L) u he _ hz + have hc : run O (Expression.compose fst (Expression.compose fst (Expression.compose fst natEqZero)) : Expression AmplifyInput .bool) + (params n r N L,List.ofFn (fun i => bankEncode (reshapeWordEquiv n ε δ w i)))=some false := by + simp [params,run_natEqZero,run_compose,run_fst,ne_of_gt hn] + rw [finishCode,run_applyIf,hc,Option.bind_some] + simp only [Bool.false_eq_true,ite_false] + exact hh + · intro w; exact treeBanksOutput_all u _ huall _ + · intro φ + have hfit := canonicalAlgorithmTree_fits n hn r O N L M₁ M₂ hO hE₁ hE₂ hr₁ hr₂ + (by dsimp [N,sampleCount]; omega) + have hb := reindexed_banks_law hu (drawWordBound n N L) (algorithmDrawBound n N L+6) + (algorithmDrawBound n N L) (repetitionCount δ) hfit φ + calc + _ = uniformAverage (fun banks : FPRASBank n ε δ => + φ (treeBanksOutput u (List.ofFn (fun i => bankEncode (banks i))))) := + uniformAverage_equiv (reshapeWordEquiv n ε δ) _ + _ = _ := by simpa only [canonicalBoundedOutput,dite_eq_left hn, + canonicalAmplifiedOutput,canonicalFairOutput] using hb + · refine ⟨fun _ => 1,?_,?_,?_⟩ + · intro w + rw [postambleCode,run_compose,run_reshapePrepared,Option.bind_some] + have hc : run O (Expression.compose fst (Expression.compose fst (Expression.compose fst natEqZero)) : Expression AmplifyInput .bool) + (params n r N L,List.ofFn (fun i => bankEncode (reshapeWordEquiv n ε δ w i)))=some true := by + simp [params,run_natEqZero,run_compose,run_fst,show n=0 by omega] + rw [finishCode,run_applyIf,hc,Option.bind_some,ite_eq_left rfl] + rfl + · intro w + have hn0 : n=0 := by omega + subst n + simp [commonBaseCount_empty] + · intro φ + simp only [canonicalBoundedOutput,dite_eq_right hn,uniformAverage_const] + +open Expression +lemma encode_natPair (z : Value NN) : encode z=pair z.1.bits z.2.bits := rfl +lemma encode_rawValue (n r : ℕ) (ε δ : ℚ) (w : BitWord (fairBitCount n ε δ)) : + encode (rawValue n r ε δ w)=pair (List.ofFn w) (encode (preparedValue n r ε δ)) := rfl +lemma width_natPair (z : Value NN) : width z=2*z.1.bits.length+1+z.2.bits.length := by + rw [width,encode_natPair,pair_length] + +lemma frozen_machine (fp fq : SizePolynomial) (n r : ℕ) + (M₁ M₂ : Matroid (Fin n)) (O : IndependenceOracle n) (ε δ : ℚ) + (hO : ExactOracles M₁ M₂ O) (hE₁ : M₁.E=Set.univ) (hE₂ : M₂.E=Set.univ) + (hr₁ : M₁.eRank=(r:ℕ∞)) (hr₂ : M₂.eRank=(r:ℕ∞)) (hε : 0<ε) + (hp : Safe O (fp.eval (masterParameter n r ε δ)) preambleCode (frozenValue n r ε δ)) + (hq : ∀ w : BitWord (fairBitCount n ε δ), + Safe O (fq.eval (masterParameter n r ε δ)) postambleCode (rawValue n r ε δ w)) + (B : ℕ) (hB : (totalResourcePoly fp fq).eval (masterParameter n r ε δ)≤B) : + ∃ (v : BitWord (fairBitCount n ε δ) → ℚ) (start : ℕ), + OutputCertificate r M₁ M₂ O ε δ v ∧ start+3*fairBitCount n ε δ+1≤B ∧ + ∀ bits : ℕ → Bool, + let out := execution fprasBlock.code O (initialConfig 1 fprasBlock.size n r ε δ) bits B + out.output=some (v (physicalWord start (fairBitCount n ε δ) bits)) ∧ + out.oracleCalls≤B ∧ out.bitOperations≤B := by + obtain ⟨v,hv⟩ := output_certificate r M₁ M₂ O hO hE₁ hE₂ hr₁ hr₂ ε δ + obtain ⟨counter,hc,hpc⟩ := run_preambleCode O r ε δ hε + have hn := (master_fields n r ε δ).1 + have hpre := compile_majorant O preambleCode fp (masterParameter n r ε δ) hn _ _ hp hpc + have hpost (w : BitWord (fairBitCount n ε δ)) : + Bounded (compile postambleCode) O (pair (List.ofFn w) (encode (preparedValue n r ε δ))) + (pair (rationalPair (v w)).1.bits (rationalPair (v w)).2.bits) + ((compiledMajorant postambleCode fq).eval (masterParameter n r ε δ)) ∧ + 2*(rationalPair (v w)).1.bits.length+1+(rationalPair (v w)).2.bits.length≤ + fq.eval (masterParameter n r ε δ) := by + constructor + · have hm := compile_majorant O postambleCode fq (masterParameter n r ε δ) hn + (rawValue n r ε δ w) (rationalPair (v w)) (hq w) (hv.1 w) + rw [encode_rawValue,encode_natPair] at hm + exact hm + · have hw := safe_output (hq w) (hv.1 w) + rw [width_natPair] at hw + exact hw + have hb := (totalResourcePoly_budget fp fq n r ε δ (rank_le_ground M₁ hr₁)).trans hB + obtain ⟨start,hs,he⟩ := pipeline_budgeted_length O n.bits r.bits ε.num.natAbs.bits ε.den.bits + δ.num.natAbs.bits δ.den.bits (compile preambleCode) (compile postambleCode) + counter (encode (preparedValue n r ε δ)) (fairBitCount n ε δ) + ((compiledMajorant preambleCode fp).eval (masterParameter n r ε δ)) + ((compiledMajorant postambleCode fq).eval (masterParameter n r ε δ)) + (fq.eval (masterParameter n r ε δ)) B hc hpre v (fun w => (hv.2.1 w).1) hpost hb + exact ⟨v,start,hv,hs,he⟩ + +open scoped Classical + +lemma physical_accuracy {n : ℕ} (r : ℕ) (M₁ M₂ : Matroid (Fin n)) + (O : IndependenceOracle n) (ε δ : ℚ) + (hO : ExactOracles M₁ M₂ O) (hE₁ : M₁.E=Set.univ) (hE₂ : M₂.E=Set.univ) + (hr₁ : M₁.eRank=(r:ℕ∞)) (hr₂ : M₂.eRank=(r:ℕ∞)) + (hε : 0<ε) (hε1 : ε<1) (hδ : 0<δ) + (v : BitWord (fairBitCount n ε δ) → ℚ) (hv : OutputCertificate r M₁ M₂ O ε δ v) + (start B : ℕ) (hstart : start+3*fairBitCount n ε δ+1≤B) : + (1-δ)*(2:ℚ)^B ≤ (Nat.card {bits : BitWord B // relativeAccuracy ε (commonBaseCount M₁ M₂) + (v (physicalWord start (fairBitCount n ε δ) (finiteBits bits)))}:ℚ) := by + have h := (canonical_bounded_fair_experiment n r O M₁ M₂ hO hE₁ hE₂ hr₁ hr₂ ε δ hε hε1 hδ).2 + rw [←hv.2.2 (fun z => if relativeAccuracy ε (commonBaseCount M₁ M₂) z then (1:ℝ) else 0)] at h + rw [←physicalWord_law start (fairBitCount n ε δ) B hstart + (fun w => if relativeAccuracy ε (commonBaseCount M₁ M₂) (v w) then (1:ℝ) else 0)] at h + rw [uniformAverage_indicator_card] at h + have hcard : Fintype.card (BitWord B)=2^B := by simp [BitWord] + rw [hcard,Nat.cast_pow,Nat.cast_ofNat] at h + have hh := (le_div_iff₀ (by positivity : (0:ℝ)<2^B)).mp h + exact_mod_cast hh +end MachineCode +end CommonBasesFPRAS + +open CommonBasesFPRAS CommonBasesFPRAS.MachineCode + +theorem common_bases_fpras : CommonBasesFPRAS.MainTheorem := by + classical + obtain ⟨fp,fq,hs⟩ := frozen_uniform_safe + let p := totalResourcePoly fp fq + refine ⟨1,fprasBlock.size,fprasBlock.code,p.coefficient*2^p.degree+1,p.degree,by omega,?_⟩ + intro n r M₁ M₂ O ε δ hE₁ hE₂ hr₁ hr₂ hO hε hε1 hδ hδ1 + have hh := hs n r M₁ M₂ O ε δ hO hE₁ hE₂ hr₁ hε + let B := resourceBound (p.coefficient*2^p.degree+1) p.degree n r ε δ + have hB : p.eval (masterParameter n r ε δ)≤B := + p.monomial_bound _ (master_pos n r ε δ) + obtain ⟨v,start,hv,hstart,he⟩ := frozen_machine fp fq n r M₁ M₂ O ε δ hO hE₁ hE₂ hr₁ hr₂ hε hh.1 hh.2 B hB + constructor + · intro bits + have h := he bits + refine ⟨?_,h.2.1,h.2.2,?_⟩ + · rw [h.1]; rfl + · intro z hz + rw [h.1] at hz + have hez := Option.some.inj hz + subst z + exact hv.2.1 _ + · have ha := physical_accuracy r M₁ M₂ O ε δ hO hE₁ hE₂ hr₁ hr₂ hε hε1 hδ v hv start B hstart + have hpred (bits : BitWord B) : + (∃ z,(execution fprasBlock.code O (initialConfig 1 fprasBlock.size n r ε δ) (finiteBits bits) B).output=some z ∧ + relativeAccuracy ε (commonBaseCount M₁ M₂) z) ↔ + relativeAccuracy ε (commonBaseCount M₁ M₂) (v (physicalWord start (fairBitCount n ε δ) (finiteBits bits))) := by + rw [(he (finiteBits bits)).1] + simp only [Option.some.injEq,exists_eq_left'] + change (1-δ)*(2:ℚ)^B ≤ (Nat.card {bits : BitWord B // ∃ z, + (execution fprasBlock.code O (initialConfig 1 fprasBlock.size n r ε δ) (finiteBits bits) B).output=some z ∧ + relativeAccuracy ε (commonBaseCount M₁ M₂) z}:ℚ) + simpa only [hpred] using ha + +end OAI diff --git a/lean/OAI/Combinatorics/Order/ChainToggle.lean b/lean/OAI/Combinatorics/Order/ChainToggle.lean new file mode 100644 index 0000000000000000000000000000000000000000..26db7e393285534002aa405344afe1444b7ea839 --- /dev/null +++ b/lean/OAI/Combinatorics/Order/ChainToggle.lean @@ -0,0 +1,162 @@ +import Mathlib.Data.Finset.Lattice.Fold +import Mathlib.Data.Finset.Powerset +import Mathlib.Algebra.BigOperators.Group.Finset.Basic +import Mathlib.Tactic.Ring + +namespace OAI +/-! +The alternating sum of finite chains cancels when an admissibility condition is stable under +joining with a fixed nonbottom element. The involution inserts or removes the join of that +element with the largest chain element that does not lie above it. Bottom is implicit, so +an empty set represents the chain consisting of bottom alone and has sign `+1`. +-/ +namespace FiniteChain +open Finset +variable {α : Type*} [Fintype α] [DecidableEq α] [SemilatticeSup α] [OrderBot α] + +/-- Every pair of members of a finite set is comparable. -/ +def Ordered (s : Finset α) : Prop := ∀ a ∈ s, ∀ b ∈ s, a ≤ b ∨ b ≤ a + +omit [Fintype α] in +theorem sup_bot_or_mem (s : Finset α) (h : Ordered s) : + s.sup id = ⊥ ∨ s.sup id ∈ s := by + induction s using Finset.induction_on with + | empty => simp + | @insert a s ha ih => + have ht : Ordered s := fun x hx y hy => h x (mem_insert_of_mem hx) y (mem_insert_of_mem hy) + rcases ih ht with hb | hm + · rw [sup_insert, id_eq, hb, sup_bot_eq] + exact Or.inr (mem_insert_self _ _) + · rcases h a (mem_insert_self _ _) (s.sup id) (mem_insert_of_mem hm) with hab | hba + · rw [sup_insert, id_eq, sup_eq_right.mpr hab] + exact Or.inr (mem_insert_of_mem hm) + · rw [sup_insert, id_eq, sup_eq_left.mpr hba] + exact Or.inr (mem_insert_self _ _) + +/-- The chain elements which do not lie above the fixed element. -/ +noncomputable def bad (P : α) (s : Finset α) : Finset α := by + classical + exact s.filter (fun q => ¬ P ≤ q) +/-- The largest element of `bad P s`, or bottom if there are none. -/ +noncomputable def pivot (P : α) (s : Finset α) : α := (bad P s).sup id +/-- The element whose presence in the chain is toggled. -/ +noncomputable def inserted (P : α) (s : Finset α) : α := pivot P s ⊔ P +/-- Insert or remove the join of the pivot with the fixed element. -/ +noncomputable def toggle (P : α) (s : Finset α) : Finset α := by + classical + exact if inserted P s ∈ s then s.erase (inserted P s) else insert (inserted P s) s + +omit [Fintype α] in +theorem pivot_description {P : α} (hP : P ≠ ⊥) {s : Finset α} (hs : Ordered s) : + ¬ P ≤ pivot P s ∧ (pivot P s = ⊥ ∨ pivot P s ∈ s) := by + classical + have hb : Ordered (bad P s) := fun a ha b hb => hs a (mem_filter.mp ha).1 b (mem_filter.mp hb).1 + rcases sup_bot_or_mem (bad P s) hb with he | hm + · change (¬ P ≤ (bad P s).sup id) ∧ + ((bad P s).sup id = ⊥ ∨ (bad P s).sup id ∈ s) + rw [he] + exact ⟨fun h => hP (le_bot_iff.mp h), Or.inl rfl⟩ + · exact ⟨(mem_filter.mp hm).2, Or.inr (mem_filter.mp hm).1⟩ + +omit [Fintype α] [DecidableEq α] in +theorem comparable_inserted {P : α} {s : Finset α} (hs : Ordered s) + {x : α} (hx : x ∈ s) : x ≤ inserted P s ∨ inserted P s ≤ x := by + classical + by_cases hp : P ≤ x + · right + apply sup_le _ hp + apply Finset.sup_le_iff.mpr + intro a ha + rcases mem_filter.mp ha with ⟨has, hpa⟩ + rcases hs a has x hx with hax | hxa + · exact hax + · exact False.elim (hpa (hp.trans hxa)) + · left + exact (Finset.le_sup (f := id) (show x ∈ bad P s from mem_filter.mpr ⟨hx, hp⟩)).trans le_sup_left + +omit [Fintype α] in +theorem bad_toggle (P : α) (s : Finset α) : bad P (toggle P s) = bad P s := by + classical + have hr : P ≤ inserted P s := le_sup_right + ext x + by_cases hx : x = inserted P s + · subst x + simp [bad, hr] + · by_cases ht : inserted P s ∈ s + · simp [bad, toggle, ht, hx] + · simp [bad, toggle, ht, hx] + +omit [Fintype α] in +theorem toggle_twice (P : α) (s : Finset α) : toggle P (toggle P s) = s := by + classical + have hr : inserted P (toggle P s) = inserted P s := by + unfold inserted pivot + rw [bad_toggle] + rw [toggle, hr] + by_cases h : inserted P s ∈ s <;> simp [toggle, h] + +/-- A chain of nonbottom elements satisfying the admissibility condition. -/ +def Admissible (allowed : α → Prop) (s : Finset α) : Prop := + Ordered s ∧ ∀ x ∈ s, x ≠ ⊥ ∧ allowed x +/-- The finite set of admissible chains. -/ +noncomputable def chains (allowed : α → Prop) : Finset (Finset α) := by + classical + exact univ.powerset.filter (Admissible allowed) + +omit [Fintype α] in +theorem toggle_admissible {allowed : α → Prop} {P : α} (hP : P ≠ ⊥) + (hbot : allowed ⊥) (hjoin : ∀ q, allowed q → allowed (q ⊔ P)) + {s : Finset α} (hs : Admissible allowed s) : Admissible allowed (toggle P s) := by + classical + have hpiv := pivot_description hP hs.1 + have hr : inserted P s ≠ ⊥ := fun he => hP (le_bot_iff.mp (he ▸ (le_sup_right : P ≤ inserted P s))) + have har : allowed (inserted P s) := by + apply hjoin + rcases hpiv.2 with h | h + · rw [h]; exact hbot + · exact (hs.2 _ h).2 + have hi : Admissible allowed (insert (inserted P s) s) := by + constructor + · intro a ha b hb + rcases mem_insert.mp ha with rfl | ha + · rcases mem_insert.mp hb with rfl | hb + · exact Or.inl le_rfl + · exact (comparable_inserted hs.1 hb).symm + · rcases mem_insert.mp hb with rfl | hb + · exact comparable_inserted hs.1 ha + · exact hs.1 a ha b hb + · intro a ha + rcases mem_insert.mp ha with rfl | ha + · exact ⟨hr, har⟩ + · exact hs.2 a ha + unfold toggle + split_ifs + · exact ⟨fun a ha b hb => hs.1 a (mem_of_mem_erase ha) b (mem_of_mem_erase hb), + fun a ha => hs.2 a (mem_of_mem_erase ha)⟩ + · exact hi + +/-- A join-stable class of chains has vanishing alternating sum. -/ +theorem alternating_chain_sum_zero {allowed : α → Prop} {P : α} (hP : P ≠ ⊥) + (hbot : allowed ⊥) (hjoin : ∀ q, allowed q → allowed (q ⊔ P)) : + ∑ s ∈ chains allowed, (-1 : ℤ) ^ s.card = 0 := by + classical + apply Finset.sum_involution (fun s _ => toggle P s) + · intro s hs + unfold toggle + split_ifs with hr + · have hc := Finset.card_erase_add_one hr + rw [← hc, pow_succ] + ring + · rw [Finset.card_insert_of_notMem hr, pow_succ] + ring + · intro s hs hn he + have hm := congrArg (fun t : Finset α => inserted P s ∈ t) he + by_cases hr : inserted P s ∈ s <;> simp [toggle, hr] at hm + · intro s hs + have ha : Admissible allowed s := (mem_filter.mp hs).2 + exact mem_filter.mpr ⟨mem_powerset.mpr (subset_univ _), toggle_admissible hP hbot hjoin ha⟩ + · intro s hs + exact toggle_twice P s +end FiniteChain + +end OAI diff --git a/lean/OAI/Combinatorics/Order/StrictChains.lean b/lean/OAI/Combinatorics/Order/StrictChains.lean new file mode 100644 index 0000000000000000000000000000000000000000..3eb8cf476d09516c62ecffded4da8e5b7885b94f --- /dev/null +++ b/lean/OAI/Combinatorics/Order/StrictChains.lean @@ -0,0 +1,131 @@ +import OAI.Combinatorics.Order.ChainToggle +import Mathlib.Data.Finset.Sort + +namespace OAI + +namespace FiniteChain + +open Finset + +variable {α : Type*} [DecidableEq α] [SemilatticeSup α] + +/-- Every unordered finite chain has exactly one strictly increasing enumeration. -/ +theorem exists_unique_strict_enumeration (s : Finset α) (hs : Ordered s) : + ∃! l : List α, l.Pairwise (· < ·) ∧ l.toFinset = s := by + classical + let : LinearOrder s := { + (inferInstance : PartialOrder s) with + le_total := fun a b => hs a a.2 b b.2 + toDecidableLE := Classical.decRel _ + toDecidableLT := Classical.decRel _ + toDecidableEq := Classical.decEq _ } + let l : List α := (Finset.univ.sort : List s).map Subtype.val + have hl : l.Pairwise (· < ·) := by + exact List.pairwise_map.mpr (Finset.sortedLT_sort (Finset.univ : Finset s)).pairwise + have he : l.toFinset = s := by + ext a + simp [l] + refine ⟨l, ⟨hl, he⟩, ?_⟩ + intro k hk + have hn : k.Nodup := hk.1.imp (fun h => ne_of_lt h) + have hn' : l.Nodup := hl.imp (fun h => ne_of_lt h) + have hp : k.Perm l := (List.perm_ext_iff_of_nodup hn hn').mpr (by + intro a + have := congrArg (fun t : Finset α => a ∈ t) (hk.2.trans he.symm) + simpa using this) + exact List.Perm.eq_of_pairwise' (hk.1.imp le_of_lt) (hl.imp le_of_lt) hp + +/-- Conversely, an actual strictly increasing list gives a finite chain. -/ +theorem ordered_toFinset {l : List α} (hl : l.Pairwise (· < ·)) : Ordered l.toFinset := by + induction l with + | nil => simp [Ordered] + | cons a l ih => + have ht := hl.tail + intro x hx y hy + simp only [List.toFinset_cons, Finset.mem_insert] at hx hy + rcases hx with rfl | hx + · rcases hy with rfl | hy + · exact Or.inl le_rfl + · exact Or.inl (le_of_lt (hl.rel_head_tail (List.mem_toFinset.mp hy))) + · rcases hy with rfl | hy + · exact Or.inr (le_of_lt (hl.rel_head_tail (List.mem_toFinset.mp hx))) + · exact ih ht x hx y hy + +variable [OrderBot α] + +/-- Adding the initial bottom gives a strict chain whose length after bottom equals +the cardinality of the nonbottom nodes, including the empty chain. -/ +theorem full_chain_enumeration (s : Finset α) (hs : Ordered s) + (hn : ∀ x ∈ s, x ≠ ⊥) : + ∃ l : List α, l.toFinset = s ∧ (⊥ :: l).Pairwise (· < ·) ∧ l.length = s.card := by + obtain ⟨l, hl, _⟩ := exists_unique_strict_enumeration s hs + refine ⟨l, hl.2, ?_, ?_⟩ + · apply List.pairwise_cons.mpr + refine ⟨?_, hl.1⟩ + intro x hx + exact lt_of_le_of_ne bot_le (Ne.symm (hn x (hl.2 ▸ List.mem_toFinset.mpr hx))) + · rw [← hl.2] + exact (List.toFinset_card_of_nodup (hl.1.imp (fun h => ne_of_lt h))).symm + +variable [Fintype α] + +/-- The nodes after the initial bottom in a strict chain. The empty list gives +the chain containing only bottom. -/ +def StrictChain (allowed : α → Prop) := + {l : List α // l.Pairwise (· < ·) ∧ ∀ x ∈ l, x ≠ ⊥ ∧ allowed x} + +noncomputable def strictToFinset (allowed : α → Prop) (l : StrictChain allowed) : + {s : Finset α // s ∈ chains allowed} := by + classical + refine ⟨l.val.toFinset, ?_⟩ + exact mem_filter.mpr ⟨mem_powerset.mpr (subset_univ _), ordered_toFinset l.property.1, + fun x hx => l.property.2 x (List.mem_toFinset.mp hx)⟩ + +noncomputable def strictChainEquiv (allowed : α → Prop) : + StrictChain allowed ≃ {s : Finset α // s ∈ chains allowed} := by + classical + apply Equiv.ofBijective (strictToFinset allowed) + constructor + · intro a b hab + have he : a.val.toFinset = b.val.toFinset := congrArg Subtype.val hab + have hp : a.val.Perm b.val := (List.perm_ext_iff_of_nodup + (a.property.1.imp (fun h => ne_of_lt h)) + (b.property.1.imp (fun h => ne_of_lt h))).mpr (by + intro x + have hx := congrArg (fun s : Finset α => x ∈ s) he + simpa using hx) + apply Subtype.ext + exact List.Perm.eq_of_pairwise' (a.property.1.imp le_of_lt) + (b.property.1.imp le_of_lt) hp + · intro s + have hs : Admissible allowed s.val := (mem_filter.mp s.property).2 + obtain ⟨l, hl, _⟩ := exists_unique_strict_enumeration s.val hs.1 + have ha : ∀ x ∈ l, x ≠ ⊥ ∧ allowed x := by + intro x hx + exact hs.2 x (hl.2 ▸ List.mem_toFinset.mpr hx) + refine ⟨⟨l, hl.1, ha⟩, ?_⟩ + exact Subtype.ext hl.2 + +noncomputable instance strictChainFintype (allowed : α → Prop) : Fintype (StrictChain allowed) := by + classical + letI : DecidableEq α := Classical.decEq α + exact Fintype.ofEquiv {s : Finset α // s ∈ chains allowed} (strictChainEquiv allowed).symm + +/-- Strict enumeration preserves chain length and the signed sum over all chains. -/ +theorem strict_list_weight_eq (allowed : α → Prop) : + (∑ l : StrictChain allowed, (-1 : ℤ)^l.val.length) = + ∑ s ∈ chains allowed, (-1 : ℤ)^s.card := by + classical + calc + (∑ l : StrictChain allowed, (-1 : ℤ)^l.val.length) = + ∑ s : {s : Finset α // s ∈ chains allowed}, (-1 : ℤ)^s.val.card := by + apply Fintype.sum_equiv (strictChainEquiv allowed) + intro l + change (-1 : ℤ)^l.val.length = (-1 : ℤ)^l.val.toFinset.card + rw [List.toFinset_card_of_nodup (l.property.1.imp (fun h => ne_of_lt h))] + _ = ∑ s ∈ chains allowed, (-1 : ℤ)^s.card := + Finset.sum_coe_sort (chains allowed) (fun s : Finset α => (-1 : ℤ)^s.card) + +end FiniteChain + +end OAI diff --git a/lean/OAI/Combinatorics/ParityLifts/Arithmetic.lean b/lean/OAI/Combinatorics/ParityLifts/Arithmetic.lean new file mode 100644 index 0000000000000000000000000000000000000000..49dbbc5dc8b283b92c61318ef60493876cb24eda --- /dev/null +++ b/lean/OAI/Combinatorics/ParityLifts/Arithmetic.lean @@ -0,0 +1,179 @@ +import OAI.Combinatorics.ParityLifts.Parser + +namespace OAI + +namespace ParityWL.Complexity + +lemma fold_pred (n m : ℕ) : (List.replicate n false).foldl (fun a _ => a-1) m = m-n := by + induction n generalizing m with + | zero => simp + | succ n ih => simp [List.replicate_succ, ih]; omega + +lemma fold_succ (n m : ℕ) : (List.replicate n false).foldl (fun a _ => a+1) m = m+n := by + simp + +def PolyProgram.natAdd : PolyProgram (ℕ × ℕ) ℕ (fun x => x.1+x.2) := by + let P := (PolyProgram.snd Bool ℕ).comp PolyProgram.natSucc + have hg (b : Bool) (n : ℕ) : (treeEncode (n+1)).size ≤ + (treeEncode n).size+2*((treeEncode b).size+1)^0 := by simp; omega + let F := P.foldlGrowing 2 0 hg + exact ((((PolyProgram.fst ℕ ℕ).comp PolyProgram.ticks).pair (PolyProgram.snd ℕ ℕ)).comp F).congr + (by intro x; simp [Nat.add_comm]) + +def PolyProgram.natSub : PolyProgram (ℕ × ℕ) ℕ (fun x => x.1-x.2) := by + let P := (PolyProgram.snd Bool ℕ).comp PolyProgram.natPred + have hg (b : Bool) (n : ℕ) : (treeEncode n.pred).size ≤ + (treeEncode n).size+0*((treeEncode b).size+1)^0 := by simp + let F := P.foldlGrowing 0 0 hg + exact ((((PolyProgram.snd ℕ ℕ).comp PolyProgram.ticks).pair (PolyProgram.fst ℕ ℕ)).comp F).congr + (by intro x; exact fold_pred x.2 x.1) + +def PolyProgram.natLe : PolyProgram (ℕ × ℕ) Bool (fun x => decide (x.1≤x.2)) := + (PolyProgram.natSub.comp PolyProgram.natZero).congr (by intro x; simp [Nat.sub_eq_zero_iff_le]) + +def PolyProgram.natMin : PolyProgram (ℕ × ℕ) ℕ (fun x => min x.1 x.2) := + PolyProgram.natLe.ite (PolyProgram.fst ℕ ℕ) (PolyProgram.snd ℕ ℕ) |>.congr + (by intro x; simp [min_def]) + +def PolyProgram.drop (α : Type) [TreeCodec α] : + PolyProgram (ℕ × List α) (List α) (fun x => x.2.drop x.1) := + (PolyProgram.splitAt α).comp (PolyProgram.snd (List α) (List α)) + +def PolyProgram.take (α : Type) [TreeCodec α] : + PolyProgram (ℕ × List α) (List α) (fun x => x.2.take x.1) := + (PolyProgram.splitAt α).comp (PolyProgram.fst (List α) (List α)) + +def PolyProgram.getD (α : Type) [TreeCodec α] (a : α) : + PolyProgram (ℕ × List α) α (fun x => x.2[x.1]?.getD a) := + ((PolyProgram.drop α).comp (PolyProgram.head α a)).congr (by intro x; simp) + +def PolyProgram.evalFin (n : ℕ) (α : Type) [TreeCodec α] : + PolyProgram (Fin n × (Fin n → α)) α (fun x => x.2 x.1) := + .expr (TExpr.caseFin n TExpr.input.left + (fun i => TExpr.input.right.nth i.val) .nil) (by + rintro ⟨i,f⟩ + rw [TExpr.caseFin_eval i _ _ _ _ (by rfl)] + exact TExpr.nth_eval i _ _ f (by rfl)) + +def PolyProgram.finite {n : ℕ} {α : Type} [TreeCodec α] (f : Fin n → α) : + PolyProgram (Fin n) α f := + .expr (TExpr.caseFin n .input (fun i => .const (treeEncode (f i))) .nil) (by + intro i + rw [TExpr.caseFin_eval i _ _ _ _ (by rfl)] + rfl) + +def rangeStep (s : ℕ × List ℕ) : ℕ × List ℕ := (s.1+1,s.1::s.2) + +lemma fold_rangeStep (xs : List Bool) (s : ℕ × List ℕ) : + xs.foldl (fun s _ => rangeStep s) s = (s.1+xs.length, (List.range' s.1 xs.length).reverse++s.2) := by + induction xs generalizing s with + | nil => simp + | cons b xs ih => + change xs.foldl (fun s _ => rangeStep s) (rangeStep s) = _ + rw [ih] + simp only [rangeStep, List.length_cons, List.range'_succ, + List.reverse_cons, List.append_assoc, List.singleton_append] + apply Prod.ext + · omega + · rfl + +lemma treeEncode_range'_size (n m : ℕ) : + (treeEncode (List.range' n m)).size ≤ 1+m*(2*(n+m)+2) := by + rw [treeEncode_list_size] + apply Nat.add_le_add_left + have h := list_sum_map_le (List.range' n m) (fun a => (treeEncode a).size+1) (2*(n+m)+2) ?_ + · simpa using h + intro a ha + have hn := List.mem_range'.mp ha + simp only [treeEncode_nat, numTree_size] + omega + +def PolyProgram.range : PolyProgram ℕ (List ℕ) List.range := by + let P : PolyProgram (Bool × (ℕ × List ℕ)) (ℕ × List ℕ) (fun x => rangeStep x.2) := + .expr (.pair (.pair .nil TExpr.input.right.left) + (.pair TExpr.input.right.left TExpr.input.right.right)) (by intro x; rfl) + have hg (xs : List Bool) (s : ℕ × List ℕ) : + (treeEncode (xs.foldl (fun s _ => rangeStep s) s)).size ≤ + 4*((treeEncode (xs,s)).size+1)^2 := by + rw [fold_rangeStep, treeEncode_prod, DataTree.size] + have h := treeEncode_append_size (List.range' s.1 xs.length).reverse s.2 + rw [treeEncode_reverse_size] at h + have hr := treeEncode_range'_size s.1 xs.length + have hx := treeEncode_list_length xs + simp only [treeEncode_prod, treeEncode_nat, numTree_size, DataTree.size] + nlinarith + let F := P.foldlBounded 4 2 hg + refine (((PolyProgram.ticks.pair (PolyProgram.const (0,([]:List ℕ)))).comp F).comp + (PolyProgram.snd ℕ (List ℕ)) |>.comp (PolyProgram.reverse ℕ)).congr ?_ + intro n + change ((List.replicate n false).foldl (fun s _ => rangeStep s) (0,([]:List ℕ))).2.reverse = _ + simp [fold_rangeStep, List.range_eq_range'] + +end ParityWL.Complexity + +namespace ParityWL.Complexity + +def succBits (bs : List Bool) : List Bool := + List.replicate (truePrefix bs) false ++ true :: bs.drop (truePrefix bs+1) + +@[simp] lemma succBits_nil : succBits [] = [true] := rfl +@[simp] lemma succBits_false (bs : List Bool) : succBits (false::bs) = true::bs := rfl +@[simp] lemma succBits_true (bs : List Bool) : succBits (true::bs) = false::succBits bs := by + simp [succBits, truePrefix, List.replicate_succ, List.drop_succ_cons] + +lemma succBits_bits (n : ℕ) : succBits n.bits = (n+1).bits := by + induction n using Nat.binaryRec' with + | zero => simp + | bit b n hn ih => + cases b with + | false => + have hn' : n≠0 := by intro h; have := hn h; contradiction + simp only [Nat.bit_false, Nat.bit0_bits n hn', succBits_false, Nat.bit1_bits] + | true => + rw [Nat.bit_true, Nat.bit1_bits, succBits_true, ih] + have he : 2*n+1+1=2*(n+1) := by omega + rw [he, Nat.bit0_bits (n+1) (by omega)] + +lemma succBits_size (bs : List Bool) : (treeEncode (succBits bs)).size ≤ (treeEncode bs).size+4 := by + induction bs with + | nil => simp [DataTree.size] + | cons b bs ih => + cases b <;> simp only [succBits_false, succBits_true, treeEncode_cons, DataTree.size, + treeEncode_false, treeEncode_true, DataTree.size] <;> omega + +def PolyProgram.succBits : PolyProgram (List Bool) (List Bool) succBits := by + let P := PolyProgram.truePrefix + let pre := P.comp PolyProgram.ticks + let suffix := (((P.comp PolyProgram.natSucc).pair (PolyProgram.id (List Bool))).comp + (PolyProgram.drop Bool)) + let R := (((PolyProgram.const true).pair suffix).comp (PolyProgram.cons Bool)) + exact (pre.pair R).comp (PolyProgram.append Bool) + +lemma fold_succBits (xs : List Bool) (n : ℕ) : + xs.foldl (fun bs _ => succBits bs) n.bits = (n+xs.length).bits := by + induction xs generalizing n with + | nil => simp + | cons b xs ih => simp only [List.foldl_cons, succBits_bits, ih, List.length_cons]; congr 1; omega + +def PolyProgram.natBits : PolyProgram ℕ (List Bool) Nat.bits := by + let P := (PolyProgram.snd Bool (List Bool)).comp PolyProgram.succBits + have hg (b : Bool) (bs : List Bool) : (treeEncode (Complexity.succBits bs)).size ≤ + (treeEncode bs).size+4*((treeEncode b).size+1)^0 := by simpa using succBits_size bs + let F := P.foldlGrowing 4 0 hg + refine ((PolyProgram.ticks.pair (PolyProgram.const ([]:List Bool))).comp F).congr ?_ + intro n + change (List.replicate n false).foldl (fun bs _ => Complexity.succBits bs) (0:ℕ).bits = n.bits + simpa only [Nat.zero_add, List.length_replicate] using fold_succBits (List.replicate n false) 0 + +def PolyProgram.encodeNat : PolyProgram ℕ (List Bool) encodeNat := by + let B := PolyProgram.natBits + let N := B.comp (PolyProgram.length Bool) + let pre := (N.comp PolyProgram.ticks).comp ((PolyProgram.const (α:=Bool) true).map) + let suffix := ((PolyProgram.const false).pair B).comp (PolyProgram.cons Bool) + refine ((pre.pair suffix).comp (PolyProgram.append Bool)).congr ?_ + intro n + simp [Complexity.encodeNat] + +end ParityWL.Complexity + +end OAI diff --git a/lean/OAI/Combinatorics/ParityLifts/AsymptoticBounds.lean b/lean/OAI/Combinatorics/ParityLifts/AsymptoticBounds.lean new file mode 100644 index 0000000000000000000000000000000000000000..4ba9588b283bab7ef1303f6342b27d3ccff07c02 --- /dev/null +++ b/lean/OAI/Combinatorics/ParityLifts/AsymptoticBounds.lean @@ -0,0 +1,129 @@ +import OAI.Combinatorics.ParityLifts.UniformNormalization + +namespace OAI + +namespace ParityWL.Complexity + +/-- Finite exceptional orders do not change a time bound for a total decider. +The bound is on actual executions, and no effective choice of constants is needed. -/ +lemma extend_wl_time_bound (M : Machine) (header : List Bool) (c : Convention) + (i : Implementation) (k : ℕ) (r C : ℝ) (hr : 0 ≤ r) (hC : 0 hTotal x.1.val x.2.1 x.2.2 + choose times bits emits correct using h + let B : ℕ := Finset.univ.sup times + refine ⟨C+B+1,by positivity,?_⟩ + intro n G H + have hB : (0 : ℝ) ≤ B := Nat.cast_nonneg B + have hpow : 1 ≤ (n+1 : ℝ)^r := Real.one_le_rpow (by have := Nat.cast_nonneg (α:=ℝ) n; linarith) hr + by_cases hn : N₀ ≤ n + · obtain ⟨s,b,hs,hb,ht⟩ := hLarge n hn G H + refine ⟨s,b,hs,hb,ht.trans ?_⟩ + exact mul_le_mul_of_nonneg_right (by linarith) (by positivity) + · let x : X := ⟨⟨n,by omega⟩,G,H⟩ + refine ⟨times x,bits x,emits x,correct x,?_⟩ + have hx : times x ≤ B := Finset.le_sup (Finset.mem_univ x) + have hx' : (times x : ℝ) ≤ B := by exact_mod_cast hx + nlinarith + +/-- The conventional big-O form: total correctness and one eventual n^r bound. +This allows arbitrary behavior at the finitely many smaller graph orders. -/ +noncomputable def AsymptoticFixedWLBound (M : Machine) (c : Convention) + (i : Implementation) (k : ℕ) (r : ℝ) : Prop := + (∀ n : ℕ, ∀ G H : SimpleGraph (Fin n), ∃ s b, + Emits M (encodeGraphs G H) s b ∧ (b=true↔Equivalent G H c i k)) ∧ + ∃ C : ℝ, 0 g k/k) Filter.atTop (nhds 0) ∧ + AsymptoticUniformWLBound M c i f g := by + classical + intro h + obtain ⟨M,f,g,hlim,hM⟩ := h + have hbound : ∀ k : ℕ, ∃ D : ℝ, 0.trans hn) G H + refine ⟨s,b,hs,hb,ht.trans ?_⟩ + have hn1 : (1 : ℝ) ≤ n := by exact_mod_cast (le_max_right N₀ 1 |>.trans hn) + calc + f k*(n : ℝ)^g k ≤ (|f k|+1)*(n : ℝ)^g k := + mul_le_mul_of_nonneg_right (by linarith [le_abs_self (f k)]) + (Real.rpow_nonneg (Nat.cast_nonneg n) _) + _ ≤ (|f k|+1)*(n : ℝ)^|g k| := mul_le_mul_of_nonneg_left + (Real.rpow_le_rpow_of_exponent_le hn1 (le_abs_self _)) (by positivity) + _ ≤ (|f k|+1)*(n+1 : ℝ)^|g k| := mul_le_mul_of_nonneg_left + (Real.rpow_le_rpow (Nat.cast_nonneg n) (by linarith) (abs_nonneg _)) (by positivity)) + exact ⟨D,hD,fun _ => h⟩ + · exact ⟨1,by norm_num,fun h => False.elim (hk h)⟩ + choose D hD hbound using hbound + have hlim' : Filter.Tendsto (fun k : ℕ => |g k|/k) Filter.atTop (nhds 0) := by + have hnat : ∀ k : ℕ, |(k : ℝ)|=k := fun k => abs_of_nonneg (Nat.cast_nonneg k) + simpa only [abs_div,hnat,abs_zero] using hlim.abs + exact uniform_eth hETH c i ⟨M,D,(fun k => |g k|),hlim',hD,(fun k => abs_nonneg (g k)),hbound⟩ + +end ParityWL.Complexity + +end OAI diff --git a/lean/OAI/Combinatorics/ParityLifts/BagTrees.lean b/lean/OAI/Combinatorics/ParityLifts/BagTrees.lean new file mode 100644 index 0000000000000000000000000000000000000000..2920cd8f2191017afc8c1e30831f49839e414c62 --- /dev/null +++ b/lean/OAI/Combinatorics/ParityLifts/BagTrees.lean @@ -0,0 +1,299 @@ +import OAI.Combinatorics.ParityLifts.Witnesses + +namespace OAI + +namespace ParityWL + +open scoped BigOperators + +section BagTrees + +open scoped Classical + +/-- An ordinary finite rooted tree in topological node order. -/ +structure IndexedTree where + nodes : ℕ + root : Fin nodes + parent : Fin nodes → Fin nodes + parent_lt : ∀ i, i ≠ root → parent i < i + +inductive IndexedTree.Ancestor (D : IndexedTree) (i : Fin D.nodes) : Fin D.nodes → Prop + | refl : D.Ancestor i i + | step {j : Fin D.nodes} (hj : j ≠ D.root) : + D.Ancestor i (D.parent j) → D.Ancestor i j + +namespace IndexedTree + +variable (D : IndexedTree) + +lemma Ancestor.le {i j : Fin D.nodes} (h : D.Ancestor i j) : i ≤ j := by + induction h with + | refl => exact le_rfl + | @step j hj h ih => exact ih.trans (D.parent_lt j hj).le + +lemma Ancestor.trans {i j k : Fin D.nodes} (h : D.Ancestor i j) + (g : D.Ancestor j k) : D.Ancestor i k := by + induction g with + | refl => exact h + | step hk g ih => exact .step hk ih + +lemma Ancestor.antisymm {i j : Fin D.nodes} (h : D.Ancestor i j) + (g : D.Ancestor j i) : i = j := le_antisymm (h.le D) (g.le D) + +lemma Ancestor.cases' {i j : Fin D.nodes} (h : D.Ancestor i j) : + i = j ∨ (j ≠ D.root ∧ D.Ancestor i (D.parent j)) := by + cases h with + | refl => exact Or.inl rfl + | step hj h => exact Or.inr ⟨hj, h⟩ + +lemma Ancestor.parent {i j : Fin D.nodes} (h : D.Ancestor i j) (hne : i ≠ j) : + j ≠ D.root ∧ D.Ancestor i (D.parent j) := (h.cases' D).resolve_left hne + +lemma root_ancestor (j : Fin D.nodes) : D.Ancestor D.root j := by + by_cases h : j = D.root + · subst j; exact .refl + · exact .step h (root_ancestor (D.parent j)) +termination_by j.val +decreasing_by exact D.parent_lt j h + +lemma ancestor_chain {i j v : Fin D.nodes} (hi : D.Ancestor i v) + (hj : D.Ancestor j v) : D.Ancestor i j ∨ D.Ancestor j i := by + by_cases hiv : i = v + · subst i; exact Or.inr hj + by_cases hjv : j = v + · subst j; exact Or.inl hi + have hip := hi.parent D hiv + have hjp := hj.parent D hjv + exact ancestor_chain hip.2 hjp.2 +termination_by v.val +decreasing_by exact D.parent_lt v hip.1 + +lemma ancestor_child {i v : Fin D.nodes} (hi : D.Ancestor i v) (hne : i ≠ v) : + ∃ j, j ≠ D.root ∧ D.parent j = i ∧ D.Ancestor j v := by + have hp := hi.parent D hne + by_cases hpi : D.parent v = i + · exact ⟨v, hp.1, hpi, .refl⟩ + obtain ⟨j, hj, hji, hjp⟩ := ancestor_child hp.2 (Ne.symm hpi) + exact ⟨j, hj, hji, .step hp.1 hjp⟩ +termination_by v.val +decreasing_by exact D.parent_lt v hp.1 + +lemma children_eq {i j k v : Fin D.nodes} + (hj : j ≠ D.root) (hji : D.parent j = i) + (hk : k ≠ D.root) (hki : D.parent k = i) + (hjv : D.Ancestor j v) (hkv : D.Ancestor k v) : j = k := by + by_contra hne + have hij : i < j := hji ▸ D.parent_lt j hj + have hik : i < k := hki ▸ D.parent_lt k hk + rcases D.ancestor_chain hjv hkv with h | h + · have hh := (h.parent D hne).2.le D + rw [hki] at hh + exact (not_le_of_gt hij) hh + · have hh := (h.parent D (Ne.symm hne)).2.le D + rw [hji] at hh + exact (not_le_of_gt hik) hh + +end IndexedTree + +variable {W : Type} [Fintype W] {F : SimpleGraph W} {t : ℕ} + +/-- Bags on a finite tree. Occurrences form the subtree above their unique +highest occurrence `top`; the interval axiom is precisely subtree convexity. +The intersections on nonroot edges have size strictly below the bag bound; +this is the exact reduction property needed by the orientation argument. -/ +structure ReducedBagTree (F : SimpleGraph W) (t : ℕ) extends IndexedTree where + bag : Fin nodes → Finset W + top : W → Fin nodes + top_mem : ∀ x, x ∈ bag (top x) + top_ancestor : ∀ x i, x ∈ bag i → toIndexedTree.Ancestor (top x) i + interval_mem : ∀ x i j, toIndexedTree.Ancestor (top x) i → + toIndexedTree.Ancestor i j → x ∈ bag j → x ∈ bag i + edge_cover : ∀ x y, F.Adj x y → ∃ i, x ∈ bag i ∧ y ∈ bag i + width : ∀ i, (bag i).card ≤ t + intersection : ∀ i, i ≠ root → (bag i ∩ bag (parent i)).card < t + +namespace ReducedBagTree + +variable (D : ReducedBagTree F t) + +noncomputable def outer (i : Fin D.nodes) : Finset W := + Finset.univ.filter (fun x => D.toIndexedTree.Ancestor i (D.top x)) + +noncomputable def cuts : RootedCuts W where + nodes := D.nodes + root := D.root + parent := D.parent + parent_lt := D.parent_lt + bag := D.bag + side := D.outer + +lemma mem_outer {i : Fin D.nodes} {x : W} : + x ∈ D.outer i ↔ D.toIndexedTree.Ancestor i (D.top x) := by + simp [outer] + +lemma mem_cut_separator {i : Fin D.nodes} {x : W} : + x ∈ D.cuts.separator i ↔ x ∈ D.bag i ∧ x ∈ D.bag (D.parent i) := by + simp [cuts, RootedCuts.separator] + +lemma outer_disjoint (i : Fin D.nodes) (hi : i ≠ D.root) : + Disjoint (D.outer i) (D.cuts.separator i) := by + apply Finset.disjoint_left.mpr + intro x hx hs + have h1 := (D.mem_outer.mp hx).trans D.toIndexedTree + (D.top_ancestor x (D.parent i) (D.mem_cut_separator.mp hs).2) + exact (not_le_of_gt (D.parent_lt i hi)) (h1.le D.toIndexedTree) + +lemma outside_boundary (i : Fin D.nodes) (hi : i ≠ D.root) + (x : W) (hx : x ∈ D.outer i) (y : W) (hxy : F.Adj x y) + (hy : y ∉ D.outer i) : y ∈ D.cuts.separator i := by + obtain ⟨v, hxv, hyv⟩ := D.edge_cover x y hxy + have hiv := (D.mem_outer.mp hx).trans D.toIndexedTree (D.top_ancestor x v hxv) + have htyi : D.toIndexedTree.Ancestor (D.top y) i := by + rcases D.toIndexedTree.ancestor_chain (D.top_ancestor y v hyv) hiv with h | h + · exact h + · exact (hy (D.mem_outer.mpr h)).elim + have hne : D.top y ≠ i := by + intro h + apply hy + apply D.mem_outer.mpr + rw [h] + exact .refl + apply D.mem_cut_separator.mpr + exact ⟨D.interval_mem y i v htyi hiv hyv, + D.interval_mem y (D.parent i) v (htyi.parent D.toIndexedTree hne).2 + ((IndexedTree.Ancestor.step hi (.refl)).trans D.toIndexedTree hiv) hyv⟩ + +lemma bag_subset_cut (i : Fin D.nodes) (x : W) (hx : x ∈ D.bag i) : + x ∈ D.cuts.separator i ∨ x ∈ D.outer i := by + by_cases h : D.top x = i + · right + apply D.mem_outer.mpr + rw [h] + exact .refl + · left + have ht := (D.top_ancestor x i hx).parent D.toIndexedTree h + exact D.mem_cut_separator.mpr ⟨hx, + D.interval_mem x (D.parent i) i ht.2 (.step ht.1 (.refl)) hx⟩ + +lemma child_outer_disjoint_bag (i j : Fin D.nodes) (hj : j ≠ D.root) + (hp : D.parent j = i) : Disjoint (D.bag i) (D.outer j) := by + apply Finset.disjoint_left.mpr + intro x hx hy + have h := (D.mem_outer.mp hy).trans D.toIndexedTree (D.top_ancestor x i hx) + have hij : i < j := hp ▸ D.parent_lt j hj + exact (not_le_of_gt hij) (h.le D.toIndexedTree) + +lemma child_outer_subset (i j : Fin D.nodes) (hj : j ≠ D.root) + (hp : D.parent j = i) : D.outer j ⊆ D.outer i := by + intro x hx + apply D.mem_outer.mpr + have h : D.toIndexedTree.Ancestor i j := by + rw [← hp] + exact .step hj (.refl) + exact h.trans D.toIndexedTree (D.mem_outer.mp hx) + +lemma branch_disjoint_bag (i j : Fin D.nodes) : Disjoint (D.bag i) (D.cuts.branch i j) := by + unfold RootedCuts.branch + split_ifs with hji hir hp + · simp + · apply Finset.disjoint_left.mpr + intro x hx hy + have hmem := D.bag_subset_cut i x hx + have hn := (Finset.mem_sdiff.mp hy).2 + exact hn (Finset.mem_union.mpr hmem) + · exact D.child_outer_disjoint_bag i j hp.1 hp.2 + · simp + +lemma branch_eq (i j : Fin D.nodes) : D.cuts.branch i j = + if j = i then (if i = D.root then ∅ else D.cuts.reverseSide i) + else if j ≠ D.root ∧ D.parent j = i then D.outer j else ∅ := rfl + +lemma reverse_disjoint_child (i j : Fin D.nodes) (hj : j ≠ D.root) + (hp : D.parent j = i) : Disjoint (D.cuts.reverseSide i) (D.outer j) := by + apply Finset.disjoint_left.mpr + intro x hx hy + exact (Finset.mem_sdiff.mp hx).2 + (Finset.mem_union.mpr (Or.inr (D.child_outer_subset i j hj hp hy))) + +lemma branches_disjoint (i j k : Fin D.nodes) (hjk : j ≠ k) : + Disjoint (D.cuts.branch i j) (D.cuts.branch i k) := by + rw [D.branch_eq, D.branch_eq] + by_cases hji : j = i + · subst j + rw [ite_eq_left rfl, ite_eq_right (Ne.symm hjk)] + by_cases hir : i = D.root + · rw [ite_eq_left hir]; simp + · rw [ite_eq_right hir] + by_cases hpk : k ≠ D.root ∧ D.parent k = i + · rw [ite_eq_left hpk] + exact D.reverse_disjoint_child i k hpk.1 hpk.2 + · rw [ite_eq_right hpk]; simp + · rw [ite_eq_right hji] + by_cases hki : k = i + · subst k + rw [ite_eq_left rfl] + split_ifs with hp hir + · simp + · exact (D.reverse_disjoint_child i j hp.1 hp.2).symm + · simp + · simp + · rw [ite_eq_right hki] + split_ifs with hp hpk + · apply Finset.disjoint_left.mpr + intro x hx hy + exact hjk (D.toIndexedTree.children_eq hp.1 hp.2 hpk.1 hpk.2 + (D.mem_outer.mp hx) (D.mem_outer.mp hy)) + · simp + · simp + · simp + +lemma branch_cover (i : Fin D.nodes) (x : W) : + x ∈ D.bag i ∨ ∃ j, x ∈ D.cuts.branch i j := by + by_cases hx : x ∈ D.bag i + · exact Or.inl hx + right + by_cases hi : D.toIndexedTree.Ancestor i (D.top x) + · have hne : i ≠ D.top x := by + intro h + exact hx (h ▸ D.top_mem x) + obtain ⟨j, hj, hp, hjx⟩ := D.toIndexedTree.ancestor_child hi hne + have hji : j ≠ i := by + have hlt : i < j := hp ▸ D.parent_lt j hj + exact ne_of_gt hlt + refine ⟨j, ?_⟩ + rw [D.branch_eq, ite_eq_right hji, ite_eq_left ⟨hj, hp⟩] + exact D.mem_outer.mpr hjx + · have hir : i ≠ D.root := by + intro h + apply hi + rw [h] + exact D.toIndexedTree.root_ancestor _ + refine ⟨i, ?_⟩ + rw [D.branch_eq, ite_eq_left rfl, ite_eq_right hir] + change x ∈ Finset.univ \ (D.cuts.separator i ∪ D.outer i) + apply Finset.mem_sdiff.mpr + refine ⟨Finset.mem_univ _, ?_⟩ + intro h + rcases Finset.mem_union.mp h with hs | hs + · exact hx (D.mem_cut_separator.mp hs).1 + · exact hi (D.mem_outer.mp hs) + +/-- Extract the actual shores and local vertex partitions from the occurrence +subtrees; vertices are not double-counted even if they occur in many bags. -/ +noncomputable def toReducedCuts : ReducedCutDecomposition F t where + toRootedCuts := D.cuts + width := D.width + intersection := D.intersection + side_disjoint := D.outer_disjoint + boundary := D.outside_boundary + bag_disjoint := D.branch_disjoint_bag + branch_disjoint := D.branches_disjoint + vertex_cover := D.branch_cover + +end ReducedBagTree + +end BagTrees + +end ParityWL + +end OAI diff --git a/lean/OAI/Combinatorics/ParityLifts/BalancedBags.lean b/lean/OAI/Combinatorics/ParityLifts/BalancedBags.lean new file mode 100644 index 0000000000000000000000000000000000000000..f493e0b8da224cd4dc501278879bedd03b37ce08 --- /dev/null +++ b/lean/OAI/Combinatorics/ParityLifts/BalancedBags.lean @@ -0,0 +1,162 @@ +import OAI.Combinatorics.ParityLifts.BaseLabels + +namespace OAI + +namespace ParityWL + +open scoped BigOperators + +section BalancedBags + +open scoped Classical + +variable {t : ℕ} {W : Type} [Fintype W] {F : SimpleGraph W} +variable {a : F →g template t} {b : TemplateVertex t → Bit} + +noncomputable def regionSet {n : ℕ} (region : W → Option (Fin n)) + (i : Option (Fin n)) : Finset W := Finset.univ.filter (fun x => region x = i) + +lemma sum_regions {n : ℕ} (region : W → Option (Fin n)) (f : W → Bit) : + ∑ x, f x = (∑ x ∈ regionSet region none, f x) + + ∑ i, ∑ x ∈ regionSet region (some i), f x := by + rw [← Finset.sum_fiberwise Finset.univ region f, Fintype.sum_option] + rfl + +/-- The star about a sink bag, with its vertex partition obtained from a tree +decomposition. -/ +structure BalancedStar (w : WeightedWitness (template t) F a b) where + regions : ℕ + region : W → Option (Fin regions) + bag : Finset W + bag_eq : bag = regionSet region none + size : bag.card ≤ t + separator : Fin regions → Finset W + separator_sub : ∀ i, separator i ⊆ bag + separator_small : ∀ i, (separator i).card < t + boundary : ∀ i, ∀ x ∈ regionSet region (some i), ∀ y, + F.Adj x y → y ∉ regionSet region (some i) → y ∈ separator i + zero_mass : ∀ i (j : Fin t), + (∀ x ∈ separator i, a x ≠ .inl j) → + w.mass (regionSet region (some i)) (.inl j) = 0 + +omit [Fintype W] in +lemma main_card_le (B : Finset W) (hp : ∀ i : Fin t, ∃ x ∈ B, a x = .inl i) : + t ≤ B.card := by + choose x hx ht using hp + have hinj : Function.Injective x := by + intro i j he + have hh : Sum.inl i = (Sum.inl j : TemplateVertex t) := + (ht i).symm.trans ((congrArg a he).trans (ht j)) + exact Sum.inl.inj hh + have hsub : Finset.univ.image x ⊆ B := by + intro y hy + rcases Finset.mem_image.mp hy with ⟨i, _, rfl⟩ + exact hx i + have hc := Finset.card_le_card hsub + rwa [Finset.card_image_of_injective _ hinj, Finset.card_univ, Fintype.card_fin] at hc + +omit [Fintype W] in +lemma missing_main (B : Finset W) (hB : B.card < t) : + ∃ i : Fin t, ∀ x ∈ B, a x ≠ .inl i := by + by_contra h + push Not at h + have h' := main_card_le (a := a) B h + omega + +lemma BalancedStar.partition_mass (w : WeightedWitness (template t) F a b) + (s : BalancedStar w) (u : TemplateVertex t) : + w.mass Finset.univ u = w.mass s.bag u + + ∑ i, w.mass (regionSet s.region (some i)) u := by + rw [s.bag_eq] + exact sum_regions s.region (fun x => @ite Bit (a x = u) + (Classical.propDecidable _) (w.vertex x) 0) + +lemma BalancedStar.main_present (w : WeightedWitness (template t) F a (starParity t)) + (s : BalancedStar w) (ht : 0 < t) (i : Fin t) : + ∃ x ∈ s.bag, a x = .inl i := by + by_contra h + push Not at h + have hb := w.mass_eq_zero s.bag (.inl i) h + have hz : ∀ j, w.mass (regionSet s.region (some j)) (.inl i) = 0 := by + intro j + exact s.zero_mass j i (fun x hx => h x (s.separator_sub j hx)) + have hm := s.partition_mass w (.inl i) + rw [w.main_mass ht i, hb] at hm + simp only [hz, Finset.sum_const_zero, add_zero] at hm + exact one_ne_zero hm + +lemma BalancedStar.representatives (w : WeightedWitness (template t) F a (starParity t)) + (s : BalancedStar w) (ht : 0 < t) : + ∃ x : Fin t → W, (∀ i, a (x i) = .inl i) ∧ + s.bag = Finset.univ.image x := by + choose x hx ha using s.main_present w ht + have hinj : Function.Injective x := by + intro i j he + have hh : Sum.inl i = (Sum.inl j : TemplateVertex t) := + (ha i).symm.trans ((congrArg a he).trans (ha j)) + exact Sum.inl.inj hh + refine ⟨x, ha, ?_⟩ + symm + apply Finset.eq_of_subset_of_card_le + · intro y hy + obtain ⟨i, _, rfl⟩ := Finset.mem_image.mp hy + exact hx i + · rw [Finset.card_image_of_injective _ hinj, Finset.card_univ, Fintype.card_fin] + exact s.size + +end BalancedBags + +section MismatchPredicates + +open scoped Classical + +variable {t : ℕ} (C : ChoiceSystem t) {W : Type} {F : SimpleGraph W} +variable (φ : F →g baseGraph C) + +noncomputable def leftTest (p : MainPair t) (α : C.Label p) (x : W) : Bit := + if leftLabelAt C p (φ x) = some α then 0 else 1 + +noncomputable def rightTest (p : MainPair t) (α : C.Label p) (x : W) : Bit := + if rightLabelAt C p (φ x) = some α then 1 else 0 + +noncomputable def helperTest (h : Helper t) (α : C.Label h.1.1) (x : W) : Bit := + if helperLabelAt C h (φ x) = some α then 0 else 1 + +lemma test_main_compatible (p : MainPair t) (α : C.Label p) {x y : W} + (hxy : F.Adj x y) (hx : baseType (φ x) = .inl p.1.1) + (hy : baseType (φ y) = .inl p.1.2) : + leftTest C φ p α x + rightTest C φ p α y = 1 := by + have he := base_main_labels C p (φ.map_adj hxy) hx hy + unfold leftTest rightTest + rw [he] + split_ifs <;> simp + +lemma test_helper_left_compatible (h : Helper t) (α : C.Label h.1.1) {x y : W} + (hxy : F.Adj x y) (hx : baseType (φ x) = .inl h.1.1.1.1) + (hy : baseType (φ y) = .inr h) : + leftTest C φ h.1.1 α x = helperTest C φ h α y := by + have he := base_helper_left_labels C h (φ.map_adj hxy.symm) hy hx + unfold leftTest helperTest + rw [he] + +lemma test_helper_right_compatible (h : Helper t) (α : C.Label h.1.1) {x y : W} + (hxy : F.Adj x y) (hx : baseType (φ x) = .inl h.1.1.1.2) + (hy : baseType (φ y) = .inr h) : + rightTest C φ h.1.1 α x = 1 + helperTest C φ h α y := by + have he := base_helper_right_labels C h (φ.map_adj hxy.symm) hy hx + unfold rightTest helperTest + rw [he] + split_ifs <;> simp [CharTwo.add_self_eq_zero] + +lemma bit_complement_left {x y : Bit} (h : x + y = 1) : x = 1 + y := by + have he := congrArg (· + y) h + simpa only [add_assoc, CharTwo.add_self_eq_zero, add_zero] using he + +lemma bit_complement_right {x y : Bit} (h : x + y = 1) : y = 1 + x := + bit_complement_left (by rwa [add_comm]) + +end MismatchPredicates + +end ParityWL + +end OAI diff --git a/lean/OAI/Combinatorics/ParityLifts/BaseLabels.lean b/lean/OAI/Combinatorics/ParityLifts/BaseLabels.lean new file mode 100644 index 0000000000000000000000000000000000000000..12cd2da89480cdfe1fde4d7959cf5c237184e0fb --- /dev/null +++ b/lean/OAI/Combinatorics/ParityLifts/BaseLabels.lean @@ -0,0 +1,190 @@ +import OAI.Combinatorics.ParityLifts.Masses + +namespace OAI + +namespace ParityWL + +open scoped BigOperators + +section BaseLabels + +open scoped Classical + +variable {t : ℕ} (C : ChoiceSystem t) + +lemma baseType_inl_iff (v : BaseVertex C) (i : Fin t) : + baseType v = .inl i ↔ ∃ d : C.Domain i, v = .inl ⟨i, d⟩ := by + cases v with + | inl x => + rcases x with ⟨j, d⟩ + constructor + · intro h + have hj : j = i := Sum.inl.inj h + subst j + exact ⟨d, rfl⟩ + · rintro ⟨e, he⟩ + exact congrArg baseType he + | inr x => simp [baseType] + +lemma baseType_inr_iff (v : BaseVertex C) (h : Helper t) : + baseType v = .inr h ↔ ∃ q : C.Label h.1.1, v = .inr ⟨h, q⟩ := by + cases v with + | inr x => + rcases x with ⟨j, d⟩ + constructor + · intro h' + have hj : j = h := Sum.inr.inj h' + subst j + exact ⟨d, rfl⟩ + · rintro ⟨e, he⟩ + exact congrArg baseType he + | inl x => simp [baseType] + +lemma base_main_label (p : MainPair t) (d : C.Domain p.1.1) (e : C.Domain p.1.2) + (h : (baseGraph C).Adj (.inl ⟨p.1.1, d⟩) (.inl ⟨p.1.2, e⟩)) : + C.leftLabel p d = C.rightLabel p e := by + have forward : ∀ (p' : MainPair t) (d' : C.Domain p'.1.1) (e' : C.Domain p'.1.2), + (.inl ⟨p'.1.1, d'⟩ : BaseVertex C) = .inl ⟨p.1.1, d⟩ → + (.inl ⟨p'.1.2, e'⟩ : BaseVertex C) = .inl ⟨p.1.2, e⟩ → + C.leftLabel p' d' = C.rightLabel p' e' → C.leftLabel p d = C.rightLabel p e := by + intro p' d' e' h0 h1 hlabel + have hi : p'.1.1 = p.1.1 := Sum.inl.inj (congrArg baseType h0) + have hj : p'.1.2 = p.1.2 := Sum.inl.inj (congrArg baseType h1) + have hp : p' = p := Subtype.ext (Prod.ext hi hj) + subst p' + have hd : d' = d := by simpa using h0 + have he : e' = e := by simpa using h1 + simpa [hd, he] using hlabel + generalize hx : (.inl ⟨p.1.1, d⟩ : BaseVertex C) = x at h + generalize hy : (.inl ⟨p.1.2, e⟩ : BaseVertex C) = y at h + rcases h.2 with h | h + · cases h with + | main p' d' e' he => exact forward p' d' e' hx.symm hy.symm he + | left h' d' => cases hx + | right h' e' => cases hx + | third h' q' f' => cases hx + · cases h with + | main p' d' e' he => + have hi : p.1.1 = p'.1.2 := Sum.inl.inj (congrArg baseType hx) + have hj : p.1.2 = p'.1.1 := Sum.inl.inj (congrArg baseType hy) + have := p.property + have := p'.property + omega + | left h' d' => cases hy + | right h' e' => cases hy + | third h' q' f' => cases hy + +lemma base_helper_left_label (h : Helper t) (q : C.Label h.1.1) + (d : C.Domain h.1.1.1.1) + (ha : (baseGraph C).Adj (.inr ⟨h, q⟩) (.inl ⟨h.1.1.1.1, d⟩)) : + q = C.leftLabel h.1.1 d := by + generalize hx : (.inr ⟨h, q⟩ : BaseVertex C) = x at ha + generalize hy : (.inl ⟨h.1.1.1.1, d⟩ : BaseVertex C) = y at ha + rcases ha.2 with ha | ha + · cases ha with + | main p' d' e' he => cases hx + | left h' d' => + have hh : h = h' := Sum.inr.inj (congrArg baseType hx) + subst h' + have hq : q = C.leftLabel h.1.1 d' := by simpa using hx + have hd : d = d' := by simpa using hy + simpa [hd] using hq + | right h' e' => + have hh : h = h' := Sum.inr.inj (congrArg baseType hx) + subst h' + have hi : h.1.1.1.1 = h.1.1.1.2 := Sum.inl.inj (congrArg baseType hy) + exact ((ne_of_lt h.1.1.2) hi).elim + | third h' q' f' => + have hh : h = h' := Sum.inr.inj (congrArg baseType hx) + subst h' + have hi : h.1.1.1.1 = h.1.2 := Sum.inl.inj (congrArg baseType hy) + exact (h.2.1 hi.symm).elim + · cases ha with + | main p' d' e' he => cases hx + | left h' d' => cases hx + | right h' e' => cases hx + | third h' q' f' => cases hx + +lemma base_helper_right_label (h : Helper t) (q : C.Label h.1.1) + (d : C.Domain h.1.1.1.2) + (ha : (baseGraph C).Adj (.inr ⟨h, q⟩) (.inl ⟨h.1.1.1.2, d⟩)) : + q = C.rightLabel h.1.1 d := by + generalize hx : (.inr ⟨h, q⟩ : BaseVertex C) = x at ha + generalize hy : (.inl ⟨h.1.1.1.2, d⟩ : BaseVertex C) = y at ha + rcases ha.2 with ha | ha + · cases ha with + | main p' d' e' he => cases hx + | right h' d' => + have hh : h = h' := Sum.inr.inj (congrArg baseType hx) + subst h' + have hq : q = C.rightLabel h.1.1 d' := by simpa using hx + have hd : d = d' := by simpa using hy + simpa [hd] using hq + | left h' e' => + have hh : h = h' := Sum.inr.inj (congrArg baseType hx) + subst h' + have hi : h.1.1.1.2 = h.1.1.1.1 := Sum.inl.inj (congrArg baseType hy) + exact ((ne_of_lt h.1.1.2) hi.symm).elim + | third h' q' f' => + have hh : h = h' := Sum.inr.inj (congrArg baseType hx) + subst h' + have hi : h.1.1.1.2 = h.1.2 := Sum.inl.inj (congrArg baseType hy) + exact (h.2.2 hi.symm).elim + · cases ha with + | main p' d' e' he => cases hx + | left h' d' => cases hx + | right h' e' => cases hx + | third h' q' f' => cases hx + +noncomputable def leftLabelAt (p : MainPair t) : BaseVertex C → Option (C.Label p) + | .inl ⟨i, d⟩ => if h : i = p.1.1 then some (C.leftLabel p (h ▸ d)) else none + | .inr _ => none + +noncomputable def rightLabelAt (p : MainPair t) : BaseVertex C → Option (C.Label p) + | .inl ⟨i, d⟩ => if h : i = p.1.2 then some (C.rightLabel p (h ▸ d)) else none + | .inr _ => none + +noncomputable def helperLabelAt (h : Helper t) : BaseVertex C → Option (C.Label h.1.1) + | .inl _ => none + | .inr ⟨j, q⟩ => if he : j = h then some (he ▸ q) else none + +@[simp] lemma leftLabelAt_self (p : MainPair t) (d : C.Domain p.1.1) : + leftLabelAt C p (.inl ⟨p.1.1, d⟩) = some (C.leftLabel p d) := by + simp [leftLabelAt] + +@[simp] lemma rightLabelAt_self (p : MainPair t) (d : C.Domain p.1.2) : + rightLabelAt C p (.inl ⟨p.1.2, d⟩) = some (C.rightLabel p d) := by + simp [rightLabelAt] + +@[simp] lemma helperLabelAt_self (h : Helper t) (q : C.Label h.1.1) : + helperLabelAt C h (.inr ⟨h, q⟩) = some q := by + simp [helperLabelAt] + +lemma base_main_labels {x y : BaseVertex C} (p : MainPair t) + (hxy : (baseGraph C).Adj x y) (hx : baseType x = .inl p.1.1) + (hy : baseType y = .inl p.1.2) : leftLabelAt C p x = rightLabelAt C p y := by + obtain ⟨d, rfl⟩ := (baseType_inl_iff C x p.1.1).mp hx + obtain ⟨e, rfl⟩ := (baseType_inl_iff C y p.1.2).mp hy + simp [base_main_label C p d e hxy] + +lemma base_helper_left_labels {x y : BaseVertex C} (h : Helper t) + (hxy : (baseGraph C).Adj x y) (hx : baseType x = .inr h) + (hy : baseType y = .inl h.1.1.1.1) : + helperLabelAt C h x = leftLabelAt C h.1.1 y := by + obtain ⟨q, rfl⟩ := (baseType_inr_iff C x h).mp hx + obtain ⟨d, rfl⟩ := (baseType_inl_iff C y h.1.1.1.1).mp hy + simp [base_helper_left_label C h q d hxy] + +lemma base_helper_right_labels {x y : BaseVertex C} (h : Helper t) + (hxy : (baseGraph C).Adj x y) (hx : baseType x = .inr h) + (hy : baseType y = .inl h.1.1.1.2) : + helperLabelAt C h x = rightLabelAt C h.1.1 y := by + obtain ⟨q, rfl⟩ := (baseType_inr_iff C x h).mp hx + obtain ⟨d, rfl⟩ := (baseType_inl_iff C y h.1.1.1.2).mp hy + simp [base_helper_right_label C h q d hxy] + +end BaseLabels + +end ParityWL + +end OAI diff --git a/lean/OAI/Combinatorics/ParityLifts/BinaryArithmetic.lean b/lean/OAI/Combinatorics/ParityLifts/BinaryArithmetic.lean new file mode 100644 index 0000000000000000000000000000000000000000..f5dc200f8cfe2b2b73d885baa862d71202dd20e2 --- /dev/null +++ b/lean/OAI/Combinatorics/ParityLifts/BinaryArithmetic.lean @@ -0,0 +1,73 @@ +import OAI.Combinatorics.ParityLifts.BitPrograms + +namespace OAI + +namespace ParityWL.Complexity + +def PolyProgram.natMul : PolyProgram (ℕ × ℕ) ℕ (fun x => x.1*x.2) := by + let I := ((PolyProgram.fst ℕ ℕ).comp PolyProgram.ticks).pair + ((PolyProgram.snd ℕ ℕ).comp PolyProgram.ticks) + let P := (PolyProgram.snd Bool (List Bool)).mapWith + refine ((I.comp P).comp (PolyProgram.flatten Bool) |>.comp (PolyProgram.length Bool)).congr ?_ + intro x + simp [Function.comp_def] + +def divStep (s : (ℕ × ℕ) × ℕ) : (ℕ × ℕ) × ℕ := + if s.1.1+1 divStep s) ((n%t,n/t),t) = + (((n+xs.length)%t,(n+xs.length)/t),t) := by + induction xs generalizing n with + | nil => simp + | cons b xs ih => + rw [List.foldl_cons, divStep_quotient _ _ ht, ih] + simp only [List.length_cons] + rw [show n+1+xs.length=n+(xs.length+1) by omega] + +def PolyProgram.natDivPos (t : ℕ) (ht : 0 n/t) := by + let P := (PolyProgram.snd Bool ((ℕ × ℕ) × ℕ)).comp PolyProgram.divStep + have hg (u : Bool) (s : (ℕ × ℕ) × ℕ) : + (treeEncode (Complexity.divStep s)).size ≤ (treeEncode s).size+2*((treeEncode u).size+1)^0 := by + simp only [Complexity.divStep] + split <;> simp [DataTree.size] + all_goals omega + let F := P.foldlGrowing 2 0 hg + let I := PolyProgram.ticks.pair (PolyProgram.const ((0,0),t)) + let R := (I.comp F).comp ((PolyProgram.fst (ℕ × ℕ) ℕ).comp (PolyProgram.snd ℕ ℕ)) + refine R.congr ?_ + intro n + have he := fold_divStep (List.replicate n false) 0 t ht + simpa [R,I,Function.comp_def] using congrArg (fun s => s.1.2) he + +def PolyProgram.width (t : ℕ) (ht : 0 (n+t-1)/t) := + ((((PolyProgram.id ℕ).pair (PolyProgram.const (t-1))).comp PolyProgram.natAdd).comp + (PolyProgram.natDivPos t ht)).congr (by intro n; change (n+(t-1))/t = _; rw [show n+(t-1)=n+t-1 by omega]) + +end ParityWL.Complexity + +end OAI diff --git a/lean/OAI/Combinatorics/ParityLifts/BitGrouping.lean b/lean/OAI/Combinatorics/ParityLifts/BitGrouping.lean new file mode 100644 index 0000000000000000000000000000000000000000..fffd96d90a39f020236fdcfa8c0d0b553e7d34c9 --- /dev/null +++ b/lean/OAI/Combinatorics/ParityLifts/BitGrouping.lean @@ -0,0 +1,84 @@ +import OAI.Combinatorics.ParityLifts.BinaryArithmetic + +namespace OAI + +namespace ParityWL.Complexity + +def chunkWidth (t : ℕ) (F : BitFormula) : ℕ := (F.length+t-1)/t + +def bitGroup (t : ℕ) (F : BitFormula) (i : Fin t) : BitFormula := + (F.drop (i.val*chunkWidth t F)).take (chunkWidth t F) + +lemma length_le_width_mul (t m : ℕ) (ht : 0 simp [names] + | cons C F ih => + have hc := hw C (by simp) + have hh := ih (fun D hD => hw D (by simp [hD])) + simp only [names,List.flatMap_cons,List.length_append,List.length_map,List.length_cons] at * + omega + +lemma group_names_length (t : ℕ) (F : BitFormula) (hw : ∀ C∈F, C.length≤3) (i : Fin t) : + (names (bitGroup t F i)).length≤3*chunkWidth t F := by + apply (names_length_le _ (fun C hC => hw C (bitGroup_subset t F i hC))).trans + apply Nat.mul_le_mul_left + exact List.length_take_le .. + +noncomputable def PolyProgram.chunkWidth (t : ℕ) (ht : 0 Complexity.bitGroup t x.2 x.1) := by + let I := (PolyProgram.fst (Fin t) BitFormula).comp (PolyProgram.finite (fun i : Fin t => i.val)) + let F := PolyProgram.snd (Fin t) BitFormula + let q := F.comp (PolyProgram.chunkWidth t ht) + let n := (I.pair q).comp PolyProgram.natMul + exact (q.pair ((n.pair F).comp (PolyProgram.drop BitClause))).comp (PolyProgram.take BitClause) + +noncomputable def PolyProgram.bitGroups (t : ℕ) (ht : 0 rfl + | bit b n hn ih => + rw [Nat.bits_append_bit n b hn] + change Nat.bit b (decodeBits n.bits)=Nat.bit b n + rw [ih] + +def literalBits {N : ℕ} (l : Literal N) : BitLiteral := (l.1.val.bits,l.2) + +lemma literalBits_injective (N : ℕ) : Function.Injective (@literalBits N) := by + intro a b h + have h1 := congrArg Prod.fst h + have h2 := congrArg Prod.snd h + have hv : a.1.val=b.1.val := by + simpa only [literalBits,decodeBits_bits] using congrArg decodeBits h1 + exact Prod.ext (Fin.ext hv) h2 + +@[instance_reducible] def literalCodec (N : ℕ) : TreeCodec (Literal N) where + encode := fun l => treeEncode (literalBits l) + injective := fun _ _ h => literalBits_injective N (TreeCodec.injective h) + +def Formula.literalLists {N : ℕ} (F : Formula N) : ClauseList (Literal N) := F.map Clause.literals + +def Formula.bitList {N : ℕ} (F : Formula N) : BitFormula := + List.map (List.map literalBits) F.literalLists + +lemma Formula.bitList_parse {N : ℕ} (F : Formula N) : F.bitList=parseFormula (encodeFormula F) := by + rw [parseFormula_encode] + simp only [bitList,literalLists,List.map_map,Function.comp_def] + rfl + +lemma Formula.literalLists_width {N : ℕ} (F : Formula N) : + ∀ C∈F.literalLists, C.length≤3 := by + intro C hC + obtain ⟨D,hD,rfl⟩ := List.mem_map.mp hC + exact D.width + +lemma nat_bits_length_le (n : ℕ) : n.bits.length≤n := by + rw [Nat.size_eq_bits_len,Nat.size_le] + exact Nat.lt_two_pow_self + +lemma literalBits_size {N : ℕ} (l : Literal N) : (treeEncode (literalBits l)).size≤4*N+5 := by + have hs := treeEncode_bits_size l.1.val.bits + have hn := (nat_bits_length_le l.1.val).trans l.1.isLt.le + have hb : (treeEncode l.2).size≤3 := by cases h : l.2 <;> simp [DataTree.size] + simp only [literalBits,treeEncode_pair,DataTree.size] + omega + +lemma Formula.controlled {N : ℕ} (F : Formula N) : + letI := literalCodec N + ListControlled (4*N+5) (minimizeList F.literalLists) := by + let _ := literalCodec N + apply minimize_controlled + intro C hC + refine ⟨F.literalLists_width C hC,?_⟩ + intro l hl + exact literalBits_size l + +lemma Formula.listCNF_width {N : ℕ} (F : Formula N) : + ∀ C∈listCNF F.literalLists, C.card≤3 := by + intro C hC + obtain ⟨D,hD,rfl⟩ := mem_listCNF.mp hC + exact (List.toFinset_card_le D).trans (F.literalLists_width D hD) + +lemma Formula.listCNF_sat {N : ℕ} (F : Formula N) (a : Fin N → Bool) : + Sparsification.Holds (listCNF F.literalLists) (fun l => a l.1=l.2) ↔ F.Satisfied a := by + rw [listCNF_holds] + simp only [literalLists,List.mem_map,forall_exists_index,and_imp] + constructor + · intro h C hC; exact h C.literals C hC rfl + · intro h C D hD he; subst C; exact h D hD + +lemma Formula.bitList_sat {N : ℕ} (F : Formula N) (a : Name → Bool) : + bitSat a F.bitList ↔ F.Satisfied (fun i => a i.val.bits) := by + simp only [bitSat,bitList,literalLists,List.map_map,List.mem_map,forall_exists_index,and_imp] + constructor + · intro h C hC + obtain ⟨l,hl,he⟩ := h _ C hC rfl + obtain ⟨l',hl',rfl⟩ := List.mem_map.mp hl + exact ⟨l',hl',he⟩ + · intro h C D hD he + subst C + obtain ⟨l,hl,hv⟩ := h D hD + exact ⟨literalBits l,List.mem_map.mpr ⟨l,hl,rfl⟩,hv⟩ + +lemma Formula.bitList_satisfiable {N : ℕ} (F : Formula N) : + (∃ a, bitSat a F.bitList) ↔ F.Satisfiable := by + constructor + · rintro ⟨a,ha⟩; exact ⟨_,(F.bitList_sat a).mp ha⟩ + · rintro ⟨a,ha⟩ + let b : Name → Bool := fun w => if h : decodeBits w x.1.idxOf x.2) := + (PolyProgram.equal α).findIndexWith.congr (by intro x; exact findIndex_idxOf x.1 x.2) + +def PolyProgram.names : PolyProgram BitFormula (List Name) Complexity.names := + ((PolyProgram.fst Name Bool).map.map.comp (PolyProgram.flatten Name)).congr (by intro F; rfl) + +noncomputable def PolyProgram.lookupBits : PolyProgram ((List Name × List Bool) × Name) Bool + (fun x => Complexity.lookupBits x.1.1 x.1.2 x.2) := by + let V : PolyProgram ((List Name × List Bool) × Name) (List Name × Name) (fun x => (x.1.1,x.2)) := + .expr (.pair TExpr.input.left.left TExpr.input.right) (by intro x; rfl) + let B : PolyProgram ((List Name × List Bool) × Name) (List Bool) (fun x => x.1.2) := + .expr TExpr.input.left.right (by intro x; rfl) + exact (((V.comp (PolyProgram.idxOf Name)).pair B).comp (PolyProgram.getD Bool false)).congr (by intro x; rfl) + +noncomputable def PolyProgram.literalTest : PolyProgram ((Name × Bool) × (List Name × List Bool)) Bool + (fun x => decide (Complexity.lookupBits x.2.1 x.2.2 x.1.1=x.1.2)) := by + let V : PolyProgram ((Name × Bool) × (List Name × List Bool)) ((List Name × List Bool) × Name) + (fun x => (x.2,x.1.1)) := + .expr (.pair TExpr.input.right TExpr.input.left.left) (by intro x; rfl) + let S : PolyProgram ((Name × Bool) × (List Name × List Bool)) Bool (fun x => x.1.2) := + .expr TExpr.input.left.right (by intro x; rfl) + exact ((V.comp PolyProgram.lookupBits).pair S).comp (PolyProgram.equal Bool) + +noncomputable def PolyProgram.checkFormula : PolyProgram (List Bool × BitFormula) Bool + (fun x => x.2.all (fun C => C.any (fun l => decide (Complexity.lookupBits (Complexity.names x.2) x.1 l.1=l.2)))) := by + let pair := ((PolyProgram.snd (List Bool) BitFormula).comp PolyProgram.names).pair + (PolyProgram.fst (List Bool) BitFormula) + let lit := PolyProgram.literalTest.mapWith.comp (PolyProgram.id Bool).any + let cls := lit.mapWith.comp (PolyProgram.id Bool).all + refine (((PolyProgram.snd (List Bool) BitFormula).pair pair).comp cls).congr ?_ + intro x + simp only [Function.comp_def,List.all_map,List.any_map] + rfl + +noncomputable def PolyProgram.satisfyingWith : PolyProgram (List (List Bool) × BitFormula) (List (List Bool)) + (fun x => x.1.filter (fun bs => x.2.all (fun C => C.any + (fun l => Complexity.lookupBits (Complexity.names x.2) bs l.1 == l.2)))) := by + refine PolyProgram.checkFormula.filterWith.congr ?_ + intro x + rfl + +abbrev KeyInput (t : ℕ) := (Fin t → BitFormula) × (ℕ × (Fin t × (Fin t × List Bool))) + +def PolyProgram.groupAt (t : ℕ) : PolyProgram ((Fin t → BitFormula) × Fin t) BitFormula + (fun x => x.1 x.2) := + ((PolyProgram.snd (Fin t → BitFormula) (Fin t)).pair + (PolyProgram.fst (Fin t → BitFormula) (Fin t))).comp (PolyProgram.evalFin t BitFormula) + +noncomputable def PolyProgram.pairKey (t : ℕ) : PolyProgram (KeyInput t) (List Bool) + (fun x => Complexity.pairKey x.1 x.2.1 x.2.2.1 x.2.2.2.1 x.2.2.2.2) := by + let Q := PolyProgram.fst (Fin t → BitFormula) (ℕ × (Fin t × (Fin t × List Bool))) + let I : PolyProgram (KeyInput t) (Fin t × Fin t) (fun x => (x.2.2.1,x.2.2.2.1)) := + .expr (.pair TExpr.input.right.right.left TExpr.input.right.right.right.left) (by intro x; rfl) + let lo := ((Q.pair (I.comp (PolyProgram.finite2 (min : Fin t → Fin t → Fin t)))).comp + (PolyProgram.groupAt t)).comp PolyProgram.names + let hi := ((Q.pair (I.comp (PolyProgram.finite2 (max : Fin t → Fin t → Fin t)))).comp + (PolyProgram.groupAt t)).comp PolyProgram.names + let own := ((Q.pair (I.comp (PolyProgram.fst (Fin t) (Fin t)))).comp + (PolyProgram.groupAt t)).comp PolyProgram.names + let bs : PolyProgram (KeyInput t) (List Bool) (fun x => x.2.2.2.2) := + .expr TExpr.input.right.right.right.right (by intro x; rfl) + let va : PolyProgram (Name × (List Name × (List Name × List Bool))) Name Prod.fst := + PolyProgram.fst Name (List Name × (List Name × List Bool)) + let hs : PolyProgram (Name × (List Name × (List Name × List Bool))) (List Name) (fun x => x.2.1) := + .expr TExpr.input.right.left (by intro x; rfl) + let os : PolyProgram (Name × (List Name × (List Name × List Bool))) (List Name × List Bool) + (fun x => x.2.2) := .expr TExpr.input.right.right (by intro x; rfl) + let L := ((va.pair hs).comp (PolyProgram.mem Name)).ite + ((os.pair va).comp PolyProgram.lookupBits) (PolyProgram.const false) + let first := (lo.pair (hi.pair (own.pair bs))).comp L.mapWith + let D : PolyProgram (KeyInput t) ℕ (fun x => x.2.1) := + .expr TExpr.input.right.left (by intro x; rfl) + let pad := (((D.pair (lo.comp (PolyProgram.length Name))).comp PolyProgram.natSub).comp PolyProgram.ticks) + refine ((first.pair pad).comp (PolyProgram.append Bool)).congr ?_ + intro x + simp only [Function.comp_def, Complexity.pairKey, decide_eq_true_eq] + +abbrev TableInput (t : ℕ) := (Fin t → BitFormula) × (ℕ × List (List Bool)) + +def choiceWithWords {t : ℕ} (x : TableInput t) : ChoiceData t := + (fun i => (x.2.2.filter (fun bs => (x.1 i).all (fun C => C.any + (fun l => Complexity.lookupBits (Complexity.names (x.1 i)) bs l.1 == l.2)))).map + (fun bs j => x.2.2.idxOf (Complexity.pairKey x.1 x.2.1 i j bs)), + fun _ _ => x.2.2.length) + +lemma choiceWithWords_words {t : ℕ} (Q : Fin t → BitFormula) (d : ℕ) : + Complexity.choiceWithWords (Q,d,words d) = bitChoiceData Q d := rfl + +noncomputable def PolyProgram.rowKeyWith (t : ℕ) : + PolyProgram (List Bool × (Fin t × TableInput t)) (Fin t → ℕ) + (fun x j => x.2.2.2.2.idxOf (Complexity.pairKey x.2.2.1 x.2.2.2.1 x.2.1 j x.1)) := by + let P : PolyProgram (Fin t × (List Bool × (Fin t × TableInput t))) (KeyInput t) + (fun x => (x.2.2.2.1,(x.2.2.2.2.1,(x.2.2.1,(x.1,x.2.1)))) ) := + .expr (.pair TExpr.input.right.right.right.left + (.pair TExpr.input.right.right.right.right.left (.pair TExpr.input.right.right.left + (.pair TExpr.input.left TExpr.input.right.left)))) (by intro x; rfl) + let W : PolyProgram (Fin t × (List Bool × (Fin t × TableInput t))) (List (List Bool)) + (fun x => x.2.2.2.2.2) := + .expr TExpr.input.right.right.right.right.right (by intro x; rfl) + exact ((W.pair (P.comp (PolyProgram.pairKey t))).comp (PolyProgram.idxOf (List Bool))).tabulate + +noncomputable def PolyProgram.domainWith (t : ℕ) : + PolyProgram (Fin t × TableInput t) (List (Fin t → ℕ)) + (fun x => (Complexity.choiceWithWords x.2).1 x.1) := by + let Q : PolyProgram (Fin t × TableInput t) ((Fin t → BitFormula) × Fin t) + (fun x => (x.2.1,x.1)) := + .expr (.pair TExpr.input.right.left TExpr.input.left) (by intro x; rfl) + let W : PolyProgram (Fin t × TableInput t) (List (List Bool)) (fun x => x.2.2.2) := + .expr TExpr.input.right.right.right (by intro x; rfl) + let D := (W.pair (Q.comp (PolyProgram.groupAt t))).comp PolyProgram.satisfyingWith + exact ((D.pair (PolyProgram.id (Fin t × TableInput t))).comp (PolyProgram.rowKeyWith t).mapWith).congr + (by intro x; rfl) + +noncomputable def PolyProgram.choiceWithWords (t : ℕ) : PolyProgram (TableInput t) (ChoiceData t) + Complexity.choiceWithWords := by + let Q := (PolyProgram.domainWith t).tabulate + let W : PolyProgram (TableInput t) (List (List Bool)) (fun x => x.2.2) := + .expr TExpr.input.right.right (by intro x; rfl) + let B := W.comp (PolyProgram.length (List Bool)) + let constPair : PolyProgram (Fin t × (Fin t × ℕ)) ℕ (fun x => x.2.2) := + .expr TExpr.input.right.right (by intro x; rfl) + let C := constPair.tabulate.tabulate + exact (Q.pair (B.comp C)).congr (by intro x; rfl) + +end ParityWL.Complexity + +end OAI diff --git a/lean/OAI/Combinatorics/ParityLifts/BitTables.lean b/lean/OAI/Combinatorics/ParityLifts/BitTables.lean new file mode 100644 index 0000000000000000000000000000000000000000..a974699315ed96c0354ed32d8761ad03246bc93a --- /dev/null +++ b/lean/OAI/Combinatorics/ParityLifts/BitTables.lean @@ -0,0 +1,192 @@ +import OAI.Combinatorics.ParityLifts.TableGraphs + +namespace OAI + +namespace ParityWL.Complexity + +abbrev BitFormula := List BitClause +abbrev Name := List Bool + +def bitClauseSat (a : Name → Bool) (C : BitClause) : Prop := ∃ l∈C, a l.1=l.2 +def bitSat (a : Name → Bool) (F : BitFormula) : Prop := ∀ C∈F, bitClauseSat a C + +def names (F : BitFormula) : List Name := F.flatMap (fun C => C.map Prod.fst) + +lemma mem_names {F : BitFormula} {v : Name} : + v∈names F ↔ ∃ C∈F, ∃ l∈C, l.1=v := by simp [names] + +lemma idxOf_inj_on {α : Type} [BEq α] [LawfulBEq α] {xs : List α} {a b : α} + (ha : a∈xs) (hb : b∈xs) (h : xs.idxOf a=xs.idxOf b) : a=b := by + have hh := congrArg (fun i => xs[i]?) h + simpa only [List.getElem?_idxOf ha,List.getElem?_idxOf hb,Option.some.injEq] using hh + +lemma findIndex_idxOf {α : Type} [BEq α] [LawfulBEq α] [DecidableEq α] (xs : List α) (a : α) : + findIndex (fun b => decide (b=a)) xs = xs.idxOf a := by + induction xs with + | nil => rfl + | cons b xs ih => + rw [findIndex_cons,List.idxOf_cons,ih] + by_cases h : b=a + · subst b; simp + · have hb : (b == a) = false := beq_eq_false_iff_ne.mpr h + simp [h,hb,Nat.add_comm] + +def lookupBits (vs : List Name) (bs : List Bool) (v : Name) : Bool := + bs[vs.idxOf v]?.getD false + +lemma lookupBits_map (vs : List Name) (a : Name → Bool) (xs : List Bool) (v : Name) (hv : v∈vs) : + lookupBits vs (vs.map a ++ xs) v = a v := by + have hi := List.idxOf_lt_length_of_mem hv + unfold lookupBits + rw [List.getElem?_append_left (by simpa using hi), List.getElem?_map, List.getElem?_idxOf hv] + rfl + +lemma bitSat_congr {F : BitFormula} {a b : Name → Bool} + (h : ∀ v∈names F, a v=b v) : bitSat a F ↔ bitSat b F := by + constructor <;> intro hs C hC + · obtain ⟨l,hl,he⟩ := hs C hC + exact ⟨l,hl, (h l.1 (mem_names.mpr ⟨C,hC,l,hl,rfl⟩)).symm.trans he⟩ + · obtain ⟨l,hl,he⟩ := hs C hC + exact ⟨l,hl, (h l.1 (mem_names.mpr ⟨C,hC,l,hl,rfl⟩)).trans he⟩ + +def satisfyingWords (d : ℕ) (F : BitFormula) : List (List Bool) := + (words d).filter (fun bs => F.all (fun C => C.any (fun l => lookupBits (names F) bs l.1 == l.2))) + +@[simp] lemma mem_satisfyingWords (d : ℕ) (F : BitFormula) (bs : List Bool) : + bs∈satisfyingWords d F ↔ bs.length=d ∧ bitSat (lookupBits (names F) bs) F := by + simp [satisfyingWords,bitSat,bitClauseSat,List.all_eq_true,List.any_eq_true] + +/-- The canonical smaller group's variable list fixes the order in a pair key. +The shared-variable mask is identical on the two sides. -/ +def pairKey {t : ℕ} (Q : Fin t → BitFormula) (d : ℕ) (i j : Fin t) (bs : List Bool) : List Bool := + let lo := names (Q (min i j)) + let hi := names (Q (max i j)) + lo.map (fun v => if v∈hi then lookupBits (names (Q i)) bs v else false) ++ + List.replicate (d-lo.length) false + +lemma pairKey_length {t : ℕ} (Q : Fin t → BitFormula) (d : ℕ) + (hd : ∀ i, (names (Q i)).length≤d) (i j : Fin t) (bs : List Bool) : + (pairKey Q d i j bs).length=d := by + simp [pairKey] + exact Nat.add_sub_of_le (hd _) + +lemma pairKey_symm_iff {t : ℕ} (Q : Fin t → BitFormula) (d : ℕ) (i j : Fin t) + (bs cs : List Bool) : pairKey Q d i j bs = pairKey Q d j i cs ↔ + ∀ v, v∈names (Q i) → v∈names (Q j) → + lookupBits (names (Q i)) bs v = lookupBits (names (Q j)) cs v := by + unfold pairKey + rw [min_comm j i,max_comm j i] + rw [List.append_cancel_right_eq,List.map_eq_map_iff] + constructor + · intro h v hi hj + rcases le_total i j with hij | hji + · have hh := h v (by simpa [min_eq_left hij] using hi) + simpa [max_eq_right hij,hj] using hh + · have hh := h v (by simpa [min_eq_right hji] using hj) + simpa [max_eq_left hji,hi] using hh + · intro h v hv + by_cases hw : v∈names (Q (max i j)) + · simp only [hw,↓reduceIte] + apply h v + · rcases le_total i j with hij | hji + · simpa [min_eq_left hij] using hv + · simpa [max_eq_left hji] using hw + · rcases le_total i j with hij | hji + · simpa [max_eq_right hij] using hw + · simpa [min_eq_right hji] using hv + · simp [hw] + +def rowKey {t : ℕ} (Q : Fin t → BitFormula) (d : ℕ) (i : Fin t) (bs : List Bool) : Fin t → ℕ := + fun j => (words d).idxOf (pairKey Q d i j bs) + +def bitChoiceData {t : ℕ} (Q : Fin t → BitFormula) (d : ℕ) : ChoiceData t := + (fun i => (satisfyingWords d (Q i)).map (rowKey Q d i), fun _ _ => (words d).length) + +lemma ChoiceData.success_rows {t : ℕ} (D : ChoiceData t) : + D.system.Successful ↔ ∃ rows : Fin t → Fin t → ℕ, + (∀ i, rows i∈D.1 i) ∧ ∀ i j, i (D.1 i).get (a i),fun i => List.get_mem ..,?_⟩ + intro i j hij + have hh := congrArg Fin.val (ha ⟨(i,j),hij⟩) + simp only [ChoiceData.system,label,entry, List.getElem?_eq_getElem (a i).isLt, + List.getElem?_eq_getElem (a j).isLt, Option.getD_some] at hh + exact hh + + · rintro ⟨rows,hr,he⟩ + choose a ha using fun i => List.mem_iff_get.mp (hr i) + refine ⟨a,?_⟩ + intro p + apply Fin.ext + have hh := he p.1.1 p.1.2 p.2 + simpa [List.get_eq_getElem,ChoiceData.system,label,entry,← ha,List.getElem?_eq_getElem (a p.1.1).isLt, + List.getElem?_eq_getElem (a p.1.2).isLt] using hh + +lemma bitChoiceData_success_iff {t : ℕ} (Q : Fin t → BitFormula) (d : ℕ) + (hd : ∀ i, (names (Q i)).length≤d) : + (bitChoiceData Q d).system.Successful ↔ + ∃ bs : Fin t → List Bool, + (∀ i, bs i∈satisfyingWords d (Q i)) ∧ + ∀ i j v, v∈names (Q i) → v∈names (Q j) → + lookupBits (names (Q i)) (bs i) v = lookupBits (names (Q j)) (bs j) v := by + classical + rw [ChoiceData.success_rows] + constructor + · rintro ⟨rows,hr,he⟩ + choose bs hbs hrow using fun i => List.mem_map.mp (hr i) + refine ⟨bs,hbs,?_⟩ + have he' (i j : Fin t) (hij : i rowKey Q d i (bs i),fun i => List.mem_map.mpr ⟨bs i,hbs i,rfl⟩,?_⟩ + intro i j hij + have hh := (pairKey_symm_iff Q d i j (bs i) (bs j)).mpr (he i j) + simp only [rowKey,bitChoiceData,ChoiceData.pairBound,hh] + +/-- The finite unary tables implement SAT gluing, including empty clauses and +empty groups; no promise of nonempty domains is introduced. -/ +theorem bitChoiceData_correct {t : ℕ} (Q : Fin t → BitFormula) (d : ℕ) + (hd : ∀ i, (names (Q i)).length≤d) : + (bitChoiceData Q d).system.Successful ↔ ∃ a : Name → Bool, ∀ i, bitSat a (Q i) := by + classical + rw [bitChoiceData_success_iff Q d hd] + constructor + · rintro ⟨bs,hbs,he⟩ + let a : Name → Bool := fun v => if h : ∃ i, v∈names (Q i) then + lookupBits (names (Q h.choose)) (bs h.choose) v else false + refine ⟨a,?_⟩ + intro i + have hi := (mem_satisfyingWords d (Q i) (bs i)).mp (hbs i) + apply (bitSat_congr (fun v hv => ?_)).mp hi.2 + dsimp [a] + rw [dite_eq_left ⟨i,hv⟩] + exact he _ _ _ hv (Exists.choose_spec (show ∃ j, v∈names (Q j) from ⟨i,hv⟩)) + · rintro ⟨a,ha⟩ + let bs := fun i => (names (Q i)).map a ++ List.replicate (d-(names (Q i)).length) false + have hb (i : Fin t) (v : Name) (hv : v∈names (Q i)) : + lookupBits (names (Q i)) (bs i) v=a v := lookupBits_map _ _ _ _ hv + refine ⟨bs,?_,?_⟩ + · intro i + rw [mem_satisfyingWords] + refine ⟨?_, (bitSat_congr (hb i)).mpr (ha i)⟩ + simp [bs] + exact Nat.add_sub_of_le (hd i) + · intro i j v hi hj + exact (hb i v hi).trans (hb j v hj).symm + +end ParityWL.Complexity + +end OAI diff --git a/lean/OAI/Combinatorics/ParityLifts/BoolFold.lean b/lean/OAI/Combinatorics/ParityLifts/BoolFold.lean new file mode 100644 index 0000000000000000000000000000000000000000..e3bf38ac9a2a59694a85302f6980b3f53c5b62ce --- /dev/null +++ b/lean/OAI/Combinatorics/ParityLifts/BoolFold.lean @@ -0,0 +1,96 @@ +import OAI.Combinatorics.ParityLifts.LeafBounds + +namespace OAI + +namespace ParityWL.Complexity + +def FCode.anyStep (p : FCode) : FCode := + .cond .right (.seq .left p) (.const (treeEncode true)) + +def FCode.any (p : FCode) : FCode := + .seq (.pair .id (.const (treeEncode false))) + (.seq (.loop p.anyStep.foldBody) .right) + +lemma bool_size (b : Bool) : (treeEncode b).size≤3 := by + cases b <;> decide + +lemma BEval.anyStep {α : Type} [TreeCodec α] (p : FCode) (a : α) (acc b : Bool) (B : ℕ) + (h : BEval p (treeEncode a) B (treeEncode b)) : + BEval p.anyStep (treeEncode (a,acc)) + (10*((treeEncode a).size+B+5)) (treeEncode (acc||b)) := by + have ha := bool_size acc + cases acc + · apply (BEval.nil_cond (g:=FCode.const (treeEncode true)) + (by simpa only [treeEncode_pair,DataTree.child,ite_true,ite_false,treeEncode_false] using BEval.right (treeEncode (a,false))) + ((BEval.left (treeEncode (a,false))).seq h)).mono + simp only [treeEncode_pair,treeEncode_false,DataTree.size] + omega + · apply (BEval.node_cond (f:=FCode.seq .left p) + (by simpa only [treeEncode_pair,DataTree.child,ite_true,ite_false,treeEncode_false] using BEval.right (treeEncode (a,true))) + (by simp : treeEncode true≠.nil) (BEval.const (treeEncode true) (treeEncode (a,true)))).mono + simp only [treeEncode_pair,treeEncode_true,DataTree.size] + omega + +lemma BEval.foldBody {α β : Type} [TreeCodec α] [TreeCodec β] + {p : FCode} {a : α} {xs : List α} {b c : β} {B : ℕ} + (h : BEval p (treeEncode (a,b)) B (treeEncode c)) : + BEval p.foldBody (treeEncode (a::xs,b)) + (10*((treeEncode (a::xs,b)).size+1)+B) (treeEncode (xs,c)) := by + let s := treeEncode (a::xs,b) + have ht := ((BEval.left s).seq (BEval.right (s.child false))) + have hh := ((BEval.left s).seq (BEval.left (s.child false))).pair (BEval.right s) + have hr := ht.pair (hh.seq h) + apply hr.mono + have := s.size_child false + change _≤10*(s.size+1)+B + omega + +lemma BEval.anyLoop {α : Type} [TreeCodec α] (p : FCode) (P : α → Prop) + (S B : ℕ) (xs : List α) (acc : Bool) + (hs : ∀ a∈xs, (treeEncode a).size≤S) + (hb : ∀ a∈xs, ∃ b, BEval p (treeEncode a) B (treeEncode b) ∧ (b=true↔P a)) : + ∃ b, BEval (.loop p.anyStep.foldBody) (treeEncode (xs,acc)) + (100*(xs.length+1)^2*(S+B+5)) (treeEncode (([]:List α),b)) ∧ + (b=true↔acc=true ∨ ∃ a∈xs, P a) := by + induction xs generalizing acc with + | nil => + refine ⟨acc,(BEval.loop_stop _ _ rfl).mono ?_,by simp⟩ + have := bool_size acc + simp only [List.length_nil,Nat.zero_add,one_pow,Nat.mul_one,treeEncode_pair,treeEncode_nil,DataTree.size] + omega + | cons a xs ih => + obtain ⟨b,hb',he⟩ := hb a (by simp) + obtain ⟨c,hc,hec⟩ := ih (acc||b) (fun x hx => hs x (by simp [hx])) + (fun x hx => hb x (by simp [hx])) + refine ⟨c,?_,by simp only [hec,Bool.or_eq_true,List.mem_cons,exists_eq_or_imp,he]; tauto⟩ + have ha := hs a (by simp) + have hsize : (treeEncode (a::xs)).size≤1+(a::xs).length*(S+1) := by + rw [treeEncode_list_size] + have h := list_sum_map_le (a::xs) (fun x => (treeEncode x).size+1) (S+1) (fun x hx => Nat.add_le_add_right (hs x hx) 1) + omega + have hacc := bool_size acc + have hstep := (BEval.anyStep p a acc b B hb').foldBody (xs:=xs) + apply (BEval.loop_next (by simp [DataTree.child]) hstep hc).mono + simp only [treeEncode_pair,DataTree.size,List.length_cons] at * + nlinarith + +lemma BEval.any {α : Type} [TreeCodec α] (p : FCode) (P : α → Prop) + (S B : ℕ) (xs : List α) + (hs : ∀ a∈xs, (treeEncode a).size≤S) + (hb : ∀ a∈xs, ∃ b, BEval p (treeEncode a) B (treeEncode b) ∧ (b=true↔P a)) : + ∃ b, BEval p.any (treeEncode xs) + (500*(xs.length+1)^2*(S+B+5)) (treeEncode b) ∧ (b=true ↔ ∃ a∈xs,P a) := by + obtain ⟨b,hb',he⟩ := BEval.anyLoop p P S B xs false hs hb + have hinit := (BEval.id (treeEncode xs)).pair (BEval.const (treeEncode false) (treeEncode xs)) + have hlast := BEval.right (treeEncode (([]:List α),b)) + refine ⟨b,(hinit.seq (hb'.seq hlast)).mono ?_,by simpa using he⟩ + have hsize : (treeEncode xs).size≤1+xs.length*(S+1) := by + rw [treeEncode_list_size] + have h := list_sum_map_le xs (fun x => (treeEncode x).size+1) (S+1) (fun x hx => Nat.add_le_add_right (hs x hx) 1) + omega + have hbool := bool_size b + simp only [treeEncode_false,DataTree.size,treeEncode_pair,treeEncode_nil] at * + nlinarith +end ParityWL.Complexity + +end OAI diff --git a/lean/OAI/Combinatorics/ParityLifts/BoundedSimulation.lean b/lean/OAI/Combinatorics/ParityLifts/BoundedSimulation.lean new file mode 100644 index 0000000000000000000000000000000000000000..c8962d5b1eab28c770e8a28f7ecabed923bab6a3 --- /dev/null +++ b/lean/OAI/Combinatorics/ParityLifts/BoundedSimulation.lean @@ -0,0 +1,130 @@ +import OAI.Combinatorics.ParityLifts.ParameterLoops + +namespace OAI + +namespace ParityWL.Complexity + +lemma foldl_replicate_iterate {α β : Type} (f : α → α) (b : β) (n : ℕ) (x : α) : + (List.replicate n b).foldl (fun a _ => f a) x=f^[n] x := by + induction n generalizing x with + | zero => rfl + | succ n ih => simp only [List.replicate_succ,List.foldl_cons,ih,Function.iterate_succ_apply] + +lemma TreeProgram.foldWork_replicate_bound {α : Type} [TreeCodec α] {f : α → α} + (P : TreeProgram (Bool × α) α (fun x => f x.2)) (n : ℕ) (x : α) (S B : ℕ) + (hs : ∀ i≤n, (treeEncode (f^[i] x)).size≤S) + (hp : ∀ i + have h := hs 0 (by omega) + simp only [Function.iterate_zero, id_eq] at h + simp only [List.replicate_zero,TreeProgram.foldWork,treeEncode_pair,treeEncode_nil,DataTree.size] + omega + | succ n ih => + have h0 := hs 0 (by omega) + have hb := hp 0 (by omega) + simp only [Function.iterate_zero,id_eq] at h0 hb + have ht := ih (f x) (by + intro i hi + simpa only [Function.iterate_succ_apply] using hs (i+1) (by omega)) (by + intro i hi + simpa only [Function.iterate_succ_apply] using hp (i+1) (by omega)) + have hsz : (treeEncode (List.replicate (n+1) false,x)).size≤2*(n+1)+S+2 := by + simp only [treeEncode_pair,treeEncode_list_size,List.map_replicate,List.sum_replicate, + treeEncode_false,DataTree.size,smul_eq_mul] + omega + rw [List.replicate_succ,TreeProgram.foldWork] + have hsz' : (treeEncode (false::List.replicate n false,x)).size≤2*(n+1)+S+2 := by + simpa only [List.replicate_succ] using hsz + nlinarith + +def smallSizeConstant (M : Machine) : ℕ := + 2*M.extraStates+(M.tapes+1)*(4*M.extraSymbols+16)+4 + +def boundedConfiguration (M : Machine) (n : ℕ) (bs : List Bool) : SmallConfiguration M := + (smallStep M)^[n] (smallInitial M bs) + +def boundedAnswer (M : Machine) (n : ℕ) (bs : List Bool) : Bool × Bool := + (decide ((M.output (boundedConfiguration M n bs).1).isSome), + (M.output (boundedConfiguration M n bs).1).getD false) + +def TreeProgram.boundedConfiguration (M : Machine) : + TreeProgram (ℕ × List Bool) (SmallConfiguration M) + (fun x => Complexity.boundedConfiguration M x.1 x.2) := by + let I := (((PolyProgram.fst ℕ (List Bool)).comp PolyProgram.ticks).pair + ((PolyProgram.snd ℕ (List Bool)).comp (smallInitialProgram M))) + let step : TreeProgram (Bool × SmallConfiguration M) (SmallConfiguration M) (fun x => smallStep M x.2) := + (PolyProgram.expr (TExpr.smallStep M TExpr.input.right) (by intro x; exact TExpr.smallStep_eval M _ _ _ rfl)).program + exact (I.program.comp step.foldl).congr (by + intro x + simp only [Function.comp_def,foldl_replicate_iterate,Complexity.boundedConfiguration]) + +lemma boundedConfiguration_time_bound (M : Machine) : ∃ C d : ℕ, ∀ x : ℕ × List Bool, + (TreeProgram.boundedConfiguration M).time x≤C*((treeEncode x).size+1)^d := by + let I := (((PolyProgram.fst ℕ (List Bool)).comp PolyProgram.ticks).pair + ((PolyProgram.snd ℕ (List Bool)).comp (smallInitialProgram M))) + let e := TExpr.smallStep M TExpr.input.right + let P : TreeProgram (Bool × SmallConfiguration M) (SmallConfiguration M) (fun x => smallStep M x.2) := + (PolyProgram.expr e (by intro x; exact TExpr.smallStep_eval M _ _ _ rfl)).program + let K := smallSizeConstant M + let A := 10*(K+6)+e.cost*(K+3)+K+10 + refine ⟨I.coefficient+A+1,I.degree+2,?_⟩ + rintro ⟨n,bs⟩ + let X := (treeEncode (n,bs)).size+1 + have hX : 1≤X := by dsimp [X]; omega + have hn : n+1≤X := by dsimp [X]; simp only [numTree_size,DataTree.size]; omega + have hl : bs.length+n+1≤X := by + have hb := treeEncode_list_length bs + dsimp [X] + simp only [numTree_size,DataTree.size] + omega + let S := K*X + let B := e.cost*(S+3) + have hs (i : ℕ) (hi : i≤n) : (treeEncode ((smallStep M)^[i] (smallInitial M bs))).size≤S := by + exact (smallRun_size M bs i).trans (Nat.mul_le_mul_left K (by omega)) + have hp (i : ℕ) (hi : i Complexity.boundedConfiguration M x.1 x.2) := by + choose C d h using boundedConfiguration_time_bound + exact ⟨TreeProgram.boundedConfiguration M,C M,d M,h M⟩ + +def PolyProgram.smallAnswerPair (M : Machine) : PolyProgram (SmallConfiguration M) (Bool × Bool) + (fun x => (decide (M.output x.1).isSome,(M.output x.1).getD false)) := by + let e := TExpr.caseFin (M.extraStates+1) TExpr.input.left (fun q => .const (treeEncode + (decide (M.output q).isSome,(M.output q).getD false))) .nil + exact .expr e (by + intro x + apply TExpr.caseFin_eval x.1 TExpr.input.left _ .nil (treeEncode x) + rfl) + +noncomputable def PolyProgram.boundedAnswer (M : Machine) : PolyProgram (ℕ × List Bool) (Bool × Bool) + (fun x => Complexity.boundedAnswer M x.1 x.2) := + (PolyProgram.boundedConfiguration M).comp (PolyProgram.smallAnswerPair M) + +end ParityWL.Complexity + +end OAI diff --git a/lean/OAI/Combinatorics/ParityLifts/ChoiceExtraction.lean b/lean/OAI/Combinatorics/ParityLifts/ChoiceExtraction.lean new file mode 100644 index 0000000000000000000000000000000000000000..5389b5366a705280b7074aae142406966c171683 --- /dev/null +++ b/lean/OAI/Combinatorics/ParityLifts/ChoiceExtraction.lean @@ -0,0 +1,124 @@ +import OAI.Combinatorics.ParityLifts.BalancedBags + +namespace OAI + +namespace ParityWL + +open scoped BigOperators + +section ChoiceFromBalancedStar + +open scoped Classical + +variable {t : ℕ} (C : ChoiceSystem t) {W : Type} [Fintype W] +variable {F : SimpleGraph W} (φ : F →g baseGraph C) +variable (w : WeightedWitness (template t) F ((baseProjection C).comp φ) (starParity t)) + +lemma mismatch_side_zero (p : MainPair t) (α : C.Label p) (Y S : Finset W) + (hb : ∀ x ∈ Y, ∀ y, F.Adj x y → y ∉ Y → y ∈ S) + (hn : ∀ x ∈ S, ∀ h : Helper t, baseType (φ x) ≠ .inr h) + (hp : ∀ x ∈ S, baseType (φ x) = .inl p.1.1 → leftTest C φ p α x = 0) + (hq : ∀ x ∈ S, baseType (φ x) = .inl p.1.2 → rightTest C φ p α x = 0) + (ℓ : Fin t) (hℓ : ∀ x ∈ S, baseType (φ x) ≠ .inl ℓ) + (hm : w.mass Y (.inl ℓ) = 0) : + w.testMass Y (.inl p.1.1) (leftTest C φ p α) + + w.testMass Y (.inl p.1.2) (rightTest C φ p α) = 0 := by + by_cases hi : ℓ = p.1.1 + · subst ℓ + have ht := w.testMass_transfer + (u := .inl p.1.2) (v := .inl p.1.1) (Ne.symm (ne_of_lt p.2)) + Y S (rightTest C φ p α) (fun x => 1 + leftTest C φ p α x) hb hℓ hq (by + intro x y he hx hy + exact bit_complement_right (test_main_compatible C φ p α he.symm hy hx)) + rw [ht, w.testMass_complement, hm] + · by_cases hj : ℓ = p.1.2 + · subst ℓ + have ht := w.testMass_transfer + (u := .inl p.1.1) (v := .inl p.1.2) (ne_of_lt p.2) + Y S (leftTest C φ p α) (fun x => 1 + rightTest C φ p α x) hb hℓ hp (by + intro x y he hx hy + exact bit_complement_left (test_main_compatible C φ p α he hx hy)) + rw [ht, add_comm, w.testMass_complement, hm] + · let h : Helper t := ⟨(p, ℓ), hi, hj⟩ + have hh : ∀ x ∈ S, ((baseProjection C).comp φ) x ≠ .inr h := + fun x hx => hn x hx h + have ht₀ := w.testMass_transfer + (u := .inl p.1.1) (v := .inr h) (Or.inl rfl) + Y S (leftTest C φ p α) (helperTest C φ h α) hb hh hp (by + intro x y he hx hy + exact test_helper_left_compatible C φ h α he hx hy) + have ht₁ := w.testMass_transfer + (u := .inl p.1.2) (v := .inr h) (Or.inr (Or.inl rfl)) + Y S (rightTest C φ p α) (fun x => 1 + helperTest C φ h α x) hb hh hq (by + intro x y he hx hy + exact test_helper_right_compatible C φ h α he hx hy) + have hmass := w.mass_separator + (u := .inr h) (v := .inl ℓ) (Or.inr (Or.inr rfl)) Y S hb hh hℓ + rw [ht₀, ht₁, w.testMass_complement, hmass, hm] + +lemma BalancedStar.partition_testMass + (s : BalancedStar w) (u : TemplateVertex t) (p : W → Bit) : + w.testMass Finset.univ u p = w.testMass s.bag u p + + ∑ i, w.testMass (regionSet s.region (some i)) u p := by + rw [s.bag_eq] + exact sum_regions s.region (fun x => @ite Bit (((baseProjection C).comp φ) x = u) + (Classical.propDecidable _) (w.vertex x * p x) 0) + +/-- The helper boundary argument from a finite partition around a balanced bag. -/ +theorem choice_of_balancedStar (s : BalancedStar w) (ht : 0 < t) : C.Successful := by + obtain ⟨xs, htype, hbag⟩ := s.representatives w ht + have hd' : ∀ i : Fin t, ∃ d : C.Domain i, φ (xs i) = .inl ⟨i, d⟩ := by + intro i + exact (baseType_inl_iff C (φ (xs i)) i).mp (htype i) + choose d hd using hd' + refine ⟨d, ?_⟩ + intro p + by_contra hneq + let α := C.leftLabel p (d p.1.1) + have hp : ∀ x ∈ s.bag, baseType (φ x) = .inl p.1.1 → + leftTest C φ p α x = 0 := by + intro x hx hx' + rw [hbag] at hx + obtain ⟨i, _, rfl⟩ := Finset.mem_image.mp hx + have hi : i = p.1.1 := Sum.inl.inj ((htype i).symm.trans hx') + subst i + simp [leftTest, hd, α] + have hq : ∀ x ∈ s.bag, baseType (φ x) = .inl p.1.2 → + rightTest C φ p α x = 0 := by + intro x hx hx' + rw [hbag] at hx + obtain ⟨i, _, rfl⟩ := Finset.mem_image.mp hx + have hi : i = p.1.2 := Sum.inl.inj ((htype i).symm.trans hx') + subst i + simp [rightTest, hd, α, Ne.symm hneq] + have hn : ∀ x ∈ s.bag, ∀ h : Helper t, baseType (φ x) ≠ .inr h := by + intro x hx h he + rw [hbag] at hx + obtain ⟨i, _, rfl⟩ := Finset.mem_image.mp hx + have hh := (htype i).symm.trans he + cases hh + have ho : ∀ j, w.testMass (regionSet s.region (some j)) (.inl p.1.1) + (leftTest C φ p α) + w.testMass (regionSet s.region (some j)) (.inl p.1.2) + (rightTest C φ p α) = 0 := by + intro j + obtain ⟨ℓ, hℓ⟩ := missing_main (a := (baseProjection C).comp φ) + (s.separator j) (s.separator_small j) + exact mismatch_side_zero C φ w p α _ _ (s.boundary j) + (fun x hx => hn x (s.separator_sub j hx)) + (fun x hx => hp x (s.separator_sub j hx)) + (fun x hx => hq x (s.separator_sub j hx)) ℓ hℓ (s.zero_mass j ℓ hℓ) + have hglobal := w.global_mismatch (u := .inl p.1.1) (v := .inl p.1.2) + (ne_of_lt p.2) (leftTest C φ p α) (rightTest C φ p α) + (fun _ _ he hx hy => test_main_compatible C φ p α he hx hy) + rw [w.main_mass ht p.1.1, s.partition_testMass C φ w, s.partition_testMass C φ w, + w.testMass_zero s.bag (.inl p.1.1) _ hp, + w.testMass_zero s.bag (.inl p.1.2) _ hq, zero_add, zero_add, + ← Finset.sum_add_distrib] at hglobal + simp only [ho, Finset.sum_const_zero] at hglobal + exact zero_ne_one hglobal + +end ChoiceFromBalancedStar + +end ParityWL + +end OAI diff --git a/lean/OAI/Combinatorics/ParityLifts/CodeErasure.lean b/lean/OAI/Combinatorics/ParityLifts/CodeErasure.lean new file mode 100644 index 0000000000000000000000000000000000000000..1ed9c628b9d936bfbbffaa5296dd394ef61f267b --- /dev/null +++ b/lean/OAI/Combinatorics/ParityLifts/CodeErasure.lean @@ -0,0 +1,423 @@ +import OAI.Combinatorics.ParityLifts.SparseMachine + +namespace OAI + +namespace ParityWL.Complexity + +lemma PolyProgram.congr_code {α β : Type} [TreeCodec α] [TreeCodec β] + {f g : α → β} (P : PolyProgram α β f) (h : ∀ x, f x = g x) : + (P.congr h).program.code = P.program.code := by + have he : f=g := funext h + subst g + rfl + +lemma PolyProgram.comp_code {α β γ : Type} [TreeCodec α] [TreeCodec β] [TreeCodec γ] + {f : α → β} {g : β → γ} (P : PolyProgram α β f) (Q : PolyProgram β γ g) : + (P.comp Q).program.code = .seq P.program.code Q.program.code := rfl + +lemma PolyProgram.pair_code {α β γ : Type} [TreeCodec α] [TreeCodec β] [TreeCodec γ] + {f : α → β} {g : α → γ} (P : PolyProgram α β f) (Q : PolyProgram α γ g) : + (P.pair Q).program.code = .pair P.program.code Q.program.code := rfl + +lemma PolyProgram.ite_code {α β : Type} [TreeCodec α] [TreeCodec β] + {p : α → Bool} {f g : α → β} (P : PolyProgram α Bool p) + (F : PolyProgram α β f) (G : PolyProgram α β g) : + (P.ite F G).program.code = .cond P.program.code G.program.code F.program.code := rfl + +lemma PolyProgram.map_code_eq {α β γ δ : Type} [TreeCodec α] [TreeCodec β] [TreeCodec γ] [TreeCodec δ] + {f : α → β} {g : γ → δ} (P : PolyProgram α β f) (Q : PolyProgram γ δ g) + (h : P.program.code=Q.program.code) : P.map.program.code=Q.map.program.code := by + simp only [PolyProgram.map,PolyProgram.reverse,PolyProgram.congr_code,PolyProgram.comp_code, + PolyProgram.pair_code,PolyProgram.foldlGrowing,TreeProgram.foldl,PolyProgram.fst,PolyProgram.snd, + PolyProgram.const,PolyProgram.id,PolyProgram.cons,PolyProgram.expr,PolyProgram.of_linear, + TreeProgram.fst,TreeProgram.snd,TreeProgram.const,TreeProgram.id,treeEncode_nil,h] + +lemma PolyProgram.mapWith_code_eq {α β γ δ ε ζ : Type} [TreeCodec α] [TreeCodec β] [TreeCodec γ] + [TreeCodec δ] [TreeCodec ε] [TreeCodec ζ] {f : α × γ → β} {g : δ × ζ → ε} + (P : PolyProgram (α × γ) β f) (Q : PolyProgram (δ × ζ) ε g) + (h : P.program.code=Q.program.code) : P.mapWith.program.code=Q.mapWith.program.code := by + simp only [PolyProgram.mapWith,PolyProgram.reverse,PolyProgram.congr_code,PolyProgram.comp_code, + PolyProgram.pair_code,PolyProgram.foldlBounded,PolyProgram.foldlGrowing,TreeProgram.foldl, + PolyProgram.fst,PolyProgram.snd,PolyProgram.const,PolyProgram.id,PolyProgram.cons,PolyProgram.expr, + PolyProgram.of_linear,TreeProgram.fst,TreeProgram.snd,TreeProgram.const,TreeProgram.id,treeEncode_nil,h] + +lemma PolyProgram.any_code_eq {α β : Type} [TreeCodec α] [TreeCodec β] + {f : α → Bool} {g : β → Bool} (P : PolyProgram α Bool f) (Q : PolyProgram β Bool g) + (h : P.program.code=Q.program.code) : P.any.program.code=Q.any.program.code := by + simp only [PolyProgram.any,PolyProgram.congr_code,PolyProgram.comp_code,PolyProgram.pair_code, + PolyProgram.foldlBounded,TreeProgram.foldl,PolyProgram.fst,PolyProgram.snd,PolyProgram.const, + PolyProgram.id,PolyProgram.of_linear,TreeProgram.fst,TreeProgram.snd,TreeProgram.const,TreeProgram.id,h] + +lemma PolyProgram.all_code_eq {α β : Type} [TreeCodec α] [TreeCodec β] + {f : α → Bool} {g : β → Bool} (P : PolyProgram α Bool f) (Q : PolyProgram β Bool g) + (h : P.program.code=Q.program.code) : P.all.program.code=Q.all.program.code := by + simp only [PolyProgram.all,PolyProgram.congr_code,PolyProgram.comp_code] + apply congrArg₂ FCode.seq + · apply PolyProgram.any_code_eq + simp only [PolyProgram.comp_code,h] + · rfl + + +lemma PolyProgram.filter_code_eq {α β : Type} [TreeCodec α] [TreeCodec β] + {f : α → Bool} {g : β → Bool} (P : PolyProgram α Bool f) (Q : PolyProgram β Bool g) + (h : P.program.code=Q.program.code) : P.filter.program.code=Q.filter.program.code := by + simp only [PolyProgram.filter,PolyProgram.reverse,PolyProgram.congr_code,PolyProgram.comp_code, + PolyProgram.pair_code,PolyProgram.ite_code,PolyProgram.foldlGrowing,TreeProgram.foldl, + PolyProgram.fst,PolyProgram.snd,PolyProgram.const,PolyProgram.id,PolyProgram.cons,PolyProgram.expr, + PolyProgram.of_linear,TreeProgram.fst,TreeProgram.snd,TreeProgram.const,TreeProgram.id,treeEncode_nil,h] + +lemma FCode.cond_congr {a b c d e f : FCode} (h₁ : a=d) (h₂ : b=e) (h₃ : c=f) : + FCode.cond a b c=FCode.cond d e f := by rw [h₁,h₂,h₃] + +macro "code_congr" : tactic => `(tactic| + repeat' first + | apply congrArg₂ FCode.seq + | apply congrArg₂ FCode.pair + | apply FCode.cond_congr + | apply PolyProgram.mapWith_code_eq + | apply PolyProgram.map_code_eq + | apply PolyProgram.filter_code_eq + | apply PolyProgram.any_code_eq + | apply PolyProgram.all_code_eq + | assumption + | rfl) + +lemma PolyProgram.filterWith_code_eq {α β γ δ : Type} [TreeCodec α] [TreeCodec β] + [TreeCodec γ] [TreeCodec δ] {f : α × β → Bool} {g : γ × δ → Bool} + (P : PolyProgram (α × β) Bool f) (Q : PolyProgram (γ × δ) Bool g) + (h : P.program.code=Q.program.code) : P.filterWith.program.code=Q.filterWith.program.code := by + simp only [PolyProgram.filterWith,PolyProgram.congr_code,PolyProgram.comp_code] + apply congrArg₂ FCode.seq + · apply congrArg₂ FCode.seq + · apply PolyProgram.mapWith_code_eq + simp only [PolyProgram.pair_code,h] + rfl + · apply PolyProgram.filter_code_eq + rfl + · apply PolyProgram.map_code_eq + rfl + +lemma PolyProgram.dedupBy_code_eq {α β γ δ : Type} [TreeCodec α] [TreeCodec γ] + [DecidableEq β] [DecidableEq δ] (f : α → β) (g : γ → δ) + (P : PolyProgram (α × α) Bool (fun x => decide (f x.1=f x.2))) + (Q : PolyProgram (γ × γ) Bool (fun x => decide (g x.1=g x.2))) + (h : P.program.code=Q.program.code) : + (PolyProgram.dedupBy f P).program.code=(PolyProgram.dedupBy g Q).program.code := by + simp only [PolyProgram.dedupBy,PolyProgram.congr_code,PolyProgram.comp_code,PolyProgram.pair_code, + PolyProgram.ite_code,PolyProgram.foldlGrowing,TreeProgram.foldl] + apply congrArg₂ FCode.seq + · rfl + · apply congrArg₂ FCode.seq + · congr 2 + apply FCode.cond_congr + · apply congrArg₂ FCode.seq + · rfl + · apply congrArg₂ FCode.seq + · exact PolyProgram.mapWith_code_eq P Q h + · rfl + · rfl + · rfl + · rfl + +lemma PolyProgram.mem_code_eq (α β : Type) [TreeCodec α] [TreeCodec β] + [DecidableEq α] [DecidableEq β] : + (PolyProgram.mem α).program.code=(PolyProgram.mem β).program.code := by + simp only [PolyProgram.mem,PolyProgram.congr_code,PolyProgram.comp_code] + code_congr + +lemma PolyProgram.subset_code_eq (α β : Type) [TreeCodec α] [TreeCodec β] + [DecidableEq α] [DecidableEq β] : + (PolyProgram.subset α).program.code=(PolyProgram.subset β).program.code := by + simp only [PolyProgram.subset,PolyProgram.congr_code,PolyProgram.comp_code] + apply congrArg₂ FCode.seq + · apply PolyProgram.mapWith_code_eq + exact PolyProgram.mem_code_eq α β + · rfl + +lemma PolyProgram.reverse_code_eq (α β : Type) [TreeCodec α] [TreeCodec β] : + (PolyProgram.reverse α).program.code=(PolyProgram.reverse β).program.code := by + simp only [PolyProgram.reverse,PolyProgram.congr_code,PolyProgram.comp_code,PolyProgram.pair_code, + PolyProgram.foldlGrowing,TreeProgram.foldl,PolyProgram.cons,PolyProgram.expr,PolyProgram.of_linear, + PolyProgram.id,PolyProgram.const,TreeProgram.id,TreeProgram.const,treeEncode_nil] + +lemma PolyProgram.append_code_eq (α β : Type) [TreeCodec α] [TreeCodec β] : + (PolyProgram.append α).program.code=(PolyProgram.append β).program.code := by + simp only [PolyProgram.append,PolyProgram.congr_code,PolyProgram.comp_code,PolyProgram.pair_code, + PolyProgram.foldlGrowing,TreeProgram.foldl,PolyProgram.cons,PolyProgram.expr,PolyProgram.of_linear] + rw [PolyProgram.reverse_code_eq α β] + rfl + +lemma PolyProgram.flatten_code_eq (α β : Type) [TreeCodec α] [TreeCodec β] : + (PolyProgram.flatten α).program.code=(PolyProgram.flatten β).program.code := by + simp only [PolyProgram.flatten,PolyProgram.congr_code,PolyProgram.comp_code,PolyProgram.pair_code, + PolyProgram.foldlGrowing,TreeProgram.foldl] + rw [PolyProgram.reverse_code_eq (List α) (List β),PolyProgram.append_code_eq α β] + rfl + +lemma PolyProgram.length_code_eq (α β : Type) [TreeCodec α] [TreeCodec β] : + (PolyProgram.length α).program.code=(PolyProgram.length β).program.code := by + simp only [PolyProgram.length,PolyProgram.congr_code,PolyProgram.comp_code,PolyProgram.pair_code, + PolyProgram.foldlGrowing,TreeProgram.foldl] + rfl + +lemma PolyProgram.clauseEqual_code_eq (α β : Type) [TreeCodec α] [TreeCodec β] + [DecidableEq α] [DecidableEq β] : + (PolyProgram.clauseEqual α).program.code=(PolyProgram.clauseEqual β).program.code := by + simp only [PolyProgram.clauseEqual,PolyProgram.congr_code,PolyProgram.comp_code,PolyProgram.pair_code] + repeat' first + | apply congrArg₂ FCode.seq + | apply congrArg₂ FCode.pair + | apply PolyProgram.subset_code_eq + | rfl + +lemma PolyProgram.compactCNF_code_eq (α β : Type) [TreeCodec α] [TreeCodec β] + [DecidableEq α] [DecidableEq β] : + (PolyProgram.compactCNF α).program.code=(PolyProgram.compactCNF β).program.code := by + exact PolyProgram.dedupBy_code_eq _ _ _ _ (PolyProgram.clauseEqual_code_eq α β) + +lemma PolyProgram.clauseSubset_code_eq (α β : Type) [TreeCodec α] [TreeCodec β] + [DecidableEq α] [DecidableEq β] : + (PolyProgram.clauseSubset α).program.code=(PolyProgram.clauseSubset β).program.code := by + simp only [PolyProgram.clauseSubset,PolyProgram.congr_code] + exact PolyProgram.subset_code_eq α β + +macro "set_code_congr" : tactic => `(tactic| + repeat' first + | apply congrArg₂ FCode.seq | apply congrArg₂ FCode.pair | apply FCode.cond_congr + | apply PolyProgram.mapWith_code_eq | apply PolyProgram.map_code_eq + | apply PolyProgram.filterWith_code_eq | apply PolyProgram.filter_code_eq + | apply PolyProgram.any_code_eq | apply PolyProgram.all_code_eq + | apply PolyProgram.compactCNF_code_eq | apply PolyProgram.clauseSubset_code_eq + | apply PolyProgram.clauseEqual_code_eq | apply PolyProgram.mem_code_eq + | apply PolyProgram.append_code_eq | apply PolyProgram.flatten_code_eq | apply PolyProgram.length_code_eq | rfl) + +lemma PolyProgram.minimalClause_code_eq (α β : Type) [TreeCodec α] [TreeCodec β] + [DecidableEq α] [DecidableEq β] : + (PolyProgram.minimalClause α).program.code=(PolyProgram.minimalClause β).program.code := by + unfold PolyProgram.minimalClause + simp only [PolyProgram.congr_code,PolyProgram.comp_code] + apply congrArg₂ FCode.seq + · rfl + · apply congrArg₂ FCode.seq + · apply PolyProgram.mapWith_code_eq + simp only [PolyProgram.comp_code,PolyProgram.pair_code] + set_code_congr + · rfl + +lemma PolyProgram.minimizeList_code_eq (α β : Type) [TreeCodec α] [TreeCodec β] + [DecidableEq α] [DecidableEq β] : + (PolyProgram.minimizeList α).program.code=(PolyProgram.minimizeList β).program.code := by + simp only [PolyProgram.minimizeList] + apply congrArg₂ FCode.seq + · apply congrArg₂ FCode.pair + · exact PolyProgram.compactCNF_code_eq α β + · rfl + · apply PolyProgram.filterWith_code_eq + exact PolyProgram.minimalClause_code_eq α β + +lemma PolyProgram.keepClause_code_eq (α β : Type) [TreeCodec α] [TreeCodec β] + [DecidableEq α] [DecidableEq β] : + (PolyProgram.keepClause α).program.code=(PolyProgram.keepClause β).program.code := by + simp only [PolyProgram.keepClause,PolyProgram.congr_code,PolyProgram.comp_code] + set_code_congr + +lemma PolyProgram.pruneList_code_eq (α β : Type) [TreeCodec α] [TreeCodec β] + [DecidableEq α] [DecidableEq β] : + (PolyProgram.pruneList α).program.code=(PolyProgram.pruneList β).program.code := by + simp only [PolyProgram.pruneList] + apply congrArg₂ FCode.seq + · apply congrArg₂ FCode.seq + · apply congrArg₂ FCode.pair + · apply PolyProgram.filterWith_code_eq + exact PolyProgram.keepClause_code_eq α β + · rfl + · exact PolyProgram.append_code_eq (List α) (List β) + · exact PolyProgram.compactCNF_code_eq α β + +lemma PolyProgram.prependAll_code_eq (α β : Type) [TreeCodec α] [TreeCodec β] : + (PolyProgram.prependAll α).program.code=(PolyProgram.prependAll β).program.code := by + simp only [PolyProgram.prependAll,PolyProgram.comp_code] + code_congr + +lemma PolyProgram.allTuples_code_eq (α β : Type) [TreeCodec α] [TreeCodec β] (n : ℕ) : + (PolyProgram.allTuples α n).program.code=(PolyProgram.allTuples β n).program.code := by + induction n with + | zero => rfl + | succ n ih => + simp only [PolyProgram.allTuples] + repeat' first + | apply congrArg₂ FCode.seq + | apply congrArg₂ FCode.pair + | apply PolyProgram.mapWith_code_eq + | apply PolyProgram.prependAll_code_eq + | apply PolyProgram.flatten_code_eq + | exact ih + | rfl + +lemma PolyProgram.clauseDiff_code_eq (α β : Type) [TreeCodec α] [TreeCodec β] + [DecidableEq α] [DecidableEq β] : + (PolyProgram.clauseDiff α).program.code=(PolyProgram.clauseDiff β).program.code := by + simp only [PolyProgram.clauseDiff,PolyProgram.congr_code] + apply PolyProgram.filterWith_code_eq + simp only [PolyProgram.comp_code] + set_code_congr + +lemma PolyProgram.clauseDisjoint_code_eq (α β : Type) [TreeCodec α] [TreeCodec β] + [DecidableEq α] [DecidableEq β] : + (PolyProgram.clauseDisjoint α).program.code=(PolyProgram.clauseDisjoint β).program.code := by + simp only [PolyProgram.clauseDisjoint,PolyProgram.congr_code,PolyProgram.comp_code] + set_code_congr + +lemma PolyProgram.allWith_code_eq {α β γ δ : Type} [TreeCodec α] [TreeCodec β] + [TreeCodec γ] [TreeCodec δ] {f : α × γ → Bool} {g : β × δ → Bool} + (P : PolyProgram (α × γ) Bool f) (Q : PolyProgram (β × δ) Bool g) + (h : P.program.code=Q.program.code) : P.allWith.program.code=Q.allWith.program.code := by + simp only [PolyProgram.allWith,PolyProgram.congr_code,PolyProgram.comp_code] + code_congr + +lemma PolyProgram.card_code_eq (α β : Type) [TreeCodec α] [TreeCodec β] + [DecidableEq α] [DecidableEq β] : + (PolyProgram.card α).program.code=(PolyProgram.card β).program.code := by + simp only [PolyProgram.card,PolyProgram.congr_code,PolyProgram.comp_code] + apply congrArg₂ FCode.seq + · apply PolyProgram.dedupBy_code_eq + rfl + · exact PolyProgram.length_code_eq α β + +lemma PolyProgram.cnfCard_code_eq (α β : Type) [TreeCodec α] [TreeCodec β] + [DecidableEq α] [DecidableEq β] : + (PolyProgram.cnfCard α).program.code=(PolyProgram.cnfCard β).program.code := by + simp only [PolyProgram.cnfCard,PolyProgram.congr_code,PolyProgram.comp_code] + set_code_congr + +lemma PolyProgram.cardEq_code_eq (α β : Type) [TreeCodec α] [TreeCodec β] + [DecidableEq α] [DecidableEq β] (n : ℕ) : + (PolyProgram.cardEq α n).program.code=(PolyProgram.cardEq β n).program.code := by + simp only [PolyProgram.cardEq,PolyProgram.comp_code,PolyProgram.pair_code] + repeat' first + | apply congrArg₂ FCode.seq + | apply congrArg₂ FCode.pair + | apply PolyProgram.card_code_eq + | rfl + +macro "flower_code_congr" : tactic => `(tactic| + repeat' first + | with_reducible apply congrArg₂ FCode.seq | with_reducible apply congrArg₂ FCode.pair | with_reducible apply FCode.cond_congr + | with_reducible apply PolyProgram.mapWith_code_eq | with_reducible apply PolyProgram.map_code_eq + | with_reducible apply PolyProgram.filterWith_code_eq | with_reducible apply PolyProgram.filter_code_eq + | with_reducible apply PolyProgram.any_code_eq | with_reducible apply PolyProgram.all_code_eq | with_reducible apply PolyProgram.allWith_code_eq + | with_reducible apply PolyProgram.compactCNF_code_eq | with_reducible apply PolyProgram.clauseSubset_code_eq + | with_reducible apply PolyProgram.clauseEqual_code_eq | with_reducible apply PolyProgram.mem_code_eq + | with_reducible apply PolyProgram.append_code_eq | with_reducible apply PolyProgram.flatten_code_eq | with_reducible apply PolyProgram.length_code_eq + | with_reducible apply PolyProgram.clauseDisjoint_code_eq | with_reducible apply PolyProgram.clauseDiff_code_eq + | with_reducible apply PolyProgram.cardEq_code_eq | with_reducible apply PolyProgram.cnfCard_code_eq + | with_reducible apply PolyProgram.allTuples_code_eq | rfl) + +lemma PolyProgram.petalsApart_code_eq (α β : Type) [TreeCodec α] [TreeCodec β] + [DecidableEq α] [DecidableEq β] : + (PolyProgram.petalsApart α).program.code=(PolyProgram.petalsApart β).program.code := by + unfold PolyProgram.petalsApart + simp only [PolyProgram.congr_code,PolyProgram.comp_code,PolyProgram.pair_code] + with_reducible apply congrArg₂ FCode.seq + · rfl + · with_reducible apply PolyProgram.allWith_code_eq + simp only [PolyProgram.comp_code] + with_reducible apply congrArg₂ FCode.seq + · rfl + · with_reducible apply PolyProgram.allWith_code_eq + simp only [PolyProgram.comp_code,PolyProgram.pair_code] + flower_code_congr + +lemma PolyProgram.clauseMember_code_eq (α β : Type) [TreeCodec α] [TreeCodec β] + [DecidableEq α] [DecidableEq β] : + (PolyProgram.clauseMember α).program.code=(PolyProgram.clauseMember β).program.code := by + unfold PolyProgram.clauseMember + simp only [PolyProgram.congr_code,PolyProgram.comp_code] + flower_code_congr + +lemma PolyProgram.flowerCover_code_eq (α β : Type) [TreeCodec α] [TreeCodec β] + [DecidableEq α] [DecidableEq β] : + (PolyProgram.flowerCover α).program.code=(PolyProgram.flowerCover β).program.code := by + unfold PolyProgram.flowerCover + simp only [PolyProgram.congr_code,PolyProgram.comp_code] + with_reducible apply congrArg₂ FCode.seq + · rfl + · with_reducible apply PolyProgram.allWith_code_eq + simp only [PolyProgram.comp_code,PolyProgram.pair_code] + with_reducible apply congrArg₂ FCode.seq + · flower_code_congr + · exact PolyProgram.clauseMember_code_eq α β + +lemma PolyProgram.goodFlower_code_eq (α β : Type) [TreeCodec α] [TreeCodec β] + [DecidableEq α] [DecidableEq β] (p q h : ℕ) : + (PolyProgram.goodFlower α p q h).program.code=(PolyProgram.goodFlower β p q h).program.code := by + unfold PolyProgram.goodFlower + simp only [PolyProgram.congr_code,PolyProgram.comp_code,PolyProgram.pair_code] + repeat' first + | with_reducible apply congrArg₂ FCode.seq | with_reducible apply congrArg₂ FCode.pair + | with_reducible apply PolyProgram.flowerCover_code_eq | with_reducible apply PolyProgram.petalsApart_code_eq + | with_reducible apply PolyProgram.cardEq_code_eq | with_reducible apply PolyProgram.cnfCard_code_eq + | (with_reducible apply PolyProgram.all_code_eq; flower_code_congr) + | (with_reducible apply PolyProgram.allWith_code_eq; simp only [PolyProgram.comp_code]; flower_code_congr) + | with_reducible rfl + all_goals first + | exact PolyProgram.all_code_eq _ _ (PolyProgram.cardEq_code_eq α β q) + | rfl + +lemma PolyProgram.flowerCandidates_code_eq (α β : Type) [TreeCodec α] [TreeCodec β] + [DecidableEq α] [DecidableEq β] (p h : ℕ) : + (PolyProgram.flowerCandidates α p h).program.code=(PolyProgram.flowerCandidates β p h).program.code := by + unfold PolyProgram.flowerCandidates + erw [PolyProgram.congr_code, PolyProgram.congr_code] + simp only [PolyProgram.comp_code,PolyProgram.pair_code] + with_reducible apply congrArg₂ FCode.seq + · with_reducible apply congrArg₂ FCode.seq + · flower_code_congr + · with_reducible apply PolyProgram.mapWith_code_eq + simp only [PolyProgram.comp_code] + with_reducible apply congrArg₂ FCode.seq + · rfl + · with_reducible apply PolyProgram.mapWith_code_eq + simp only [PolyProgram.comp_code,PolyProgram.pair_code] + flower_code_congr + · exact PolyProgram.flatten_code_eq (FlowerRecord α) (FlowerRecord β) + +lemma PolyProgram.flowerList_code_eq (α β : Type) [TreeCodec α] [TreeCodec β] + [DecidableEq α] [DecidableEq β] (p q h : ℕ) : + (PolyProgram.flowerList α p q h).program.code=(PolyProgram.flowerList β p q h).program.code := by + unfold PolyProgram.flowerList + erw [PolyProgram.congr_code, PolyProgram.congr_code] + simp only [PolyProgram.comp_code,PolyProgram.pair_code] + with_reducible apply congrArg₂ FCode.seq + · with_reducible apply congrArg₂ FCode.pair + · exact PolyProgram.flowerCandidates_code_eq α β p h + · rfl + · with_reducible apply PolyProgram.filterWith_code_eq + exact PolyProgram.goodFlower_code_eq α β p q h + +lemma PolyProgram.sparseBranch_code (α : Type) [TreeCodec α] [DecidableEq α] : + (PolyProgram.sparseBranch α).program.code = + .pair (.const (boolTree false)) + (.pair (.seq (TExpr.pair TExpr.input.left (.pair TExpr.input.right.left .nil)).compile (PolyProgram.pruneList α).program.code) + (.seq (TExpr.pair TExpr.input.left TExpr.input.right.right).compile (PolyProgram.pruneList α).program.code)) := by + unfold PolyProgram.sparseBranch + exact PolyProgram.congr_code _ _ +lemma PolyProgram.sparseBranch_code_eq (α β : Type) [TreeCodec α] [TreeCodec β] + [DecidableEq α] [DecidableEq β] : + (PolyProgram.sparseBranch α).program.code=(PolyProgram.sparseBranch β).program.code := by + rw [PolyProgram.sparseBranch_code,PolyProgram.sparseBranch_code,PolyProgram.pruneList_code_eq α β] + +lemma PolyProgram.sparseStep_code_eq (α β : Type) [TreeCodec α] [TreeCodec β] + [DecidableEq α] [DecidableEq β] (r : ℕ) : + (PolyProgram.sparseStep α r).program.code=(PolyProgram.sparseStep β r).program.code := by + unfold PolyProgram.sparseStep + erw [PolyProgram.congr_code, PolyProgram.congr_code] + simp only [PolyProgram.comp_code,PolyProgram.pair_code,PolyProgram.ite_code] + repeat' first + | with_reducible apply FCode.cond_congr | with_reducible apply congrArg₂ FCode.seq | with_reducible apply congrArg₂ FCode.pair + | with_reducible apply PolyProgram.flowerList_code_eq | with_reducible apply PolyProgram.sparseBranch_code_eq | with_reducible rfl + all_goals rfl + +end ParityWL.Complexity + +end OAI diff --git a/lean/OAI/Combinatorics/ParityLifts/ColorSpan.lean b/lean/OAI/Combinatorics/ParityLifts/ColorSpan.lean new file mode 100644 index 0000000000000000000000000000000000000000..3708be137e18bc0e59f2de4df458dbe9b2693c41 --- /dev/null +++ b/lean/OAI/Combinatorics/ParityLifts/ColorSpan.lean @@ -0,0 +1,232 @@ +import OAI.Combinatorics.ParityLifts.Interpolation + +namespace OAI + +namespace ParityWL + +open scoped BigOperators + +section ColorSpan + +open scoped Classical + +variable {V W : Type} [Fintype V] [Fintype W] +variable (G : SimpleGraph V) (H : SimpleGraph W) + +noncomputable def pairAtomic {k : ℕ} : TuplePair V W k → AtomicType k := + Sum.elim (atomicType G) (atomicType H) + +noncomputable def pairJoint (k r : ℕ) : TuplePair V W k → JointColor k r := + Sum.elim (jointColor G k r) (jointColor H k r) + +noncomputable def pairSeparate (k r : ℕ) : TuplePair V W k → SeparateColor k r := + Sum.elim (separateColor G k r) (separateColor H k r) + +def boolIndicator (b : Bool) : ℚ := if b then 1 else 0 + +lemma boolIndicator_injective : Function.Injective boolIndicator := by + intro a b h + cases a <;> cases b <;> simp_all [boolIndicator] + +lemma testEval_equality {k t : ℕ} (hkt : k ≤ t) (i j : Fin k) (a : TuplePair V W k) : + testEval G H (equalityTest hkt i j) a = boolIndicator ((pairAtomic G H a i j).1) := by + cases a <;> simp [testEval, equalityTest_count, pairAtomic, atomicType, boolIndicator] + +lemma testEval_edge {k t : ℕ} (hkt : k ≤ t) (i j : Fin k) (a : TuplePair V W k) : + testEval G H (edgeTest hkt i j) a = boolIndicator ((pairAtomic G H a i j).2) := by + cases a <;> simp [testEval, edgeTest_count, pairAtomic, atomicType, boolIndicator] + +lemma atomic_indicator_mem {k t : ℕ} (hkt : k ≤ t) (d : AtomicType k) : + (fun x => if pairAtomic G H x = d then (1 : ℚ) else 0) ∈ testSpan G H k t := by + refine color_indicator_mem_of_separation (testAlgebra G H k t hkt) (pairAtomic G H) ?_ d + intro x y hxy + by_contra! hn + apply hxy + funext i j + apply Prod.ext + · apply boolIndicator_injective + rw [← testEval_equality G H hkt i j x, ← testEval_equality G H hkt i j y] + apply hn _ (testEval_mem G H _) + intro z w hzw + rw [testEval_equality, testEval_equality, hzw] + · apply boolIndicator_injective + rw [← testEval_edge G H hkt i j x, ← testEval_edge G H hkt i j y] + apply hn _ (testEval_mem G H _) + intro z w hzw + rw [testEval_edge, testEval_edge, hzw] + +lemma joint_indicator_sum {k r : ℕ} (d : Fin k → JointColor k r) (a : TuplePair V W k) : + jointReplacementSum (fun i x => if pairJoint G H k r x = d i then (1 : ℚ) else 0) a = + (Multiset.count d (pairJoint G H k (r + 1) a).2 : ℚ) := by + have hprod {D : Type} [DecidableEq D] (c d : Fin k → D) : + (∏ i : Fin k, if c i = d i then (1 : ℚ) else 0) = if c = d then 1 else 0 := by + rw [Finset.prod_boole] + simp only [Finset.mem_univ, true_implies, funext_iff] + cases a with + | inl x => + change (∑ y : V, ∏ i : Fin k, + if jointColor G k r (Function.update x i y) = d i then (1 : ℚ) else 0) = _ + change _ = (Multiset.count d (Finset.univ.val.map + (fun y : V => fun i => jointColor G k r (Function.update x i y))) : ℚ) + rw [count_map_as_sum] + apply Finset.sum_congr rfl + intro y _ + exact hprod _ _ + | inr x => + change (∑ y : W, ∏ i : Fin k, + if jointColor H k r (Function.update x i y) = d i then (1 : ℚ) else 0) = _ + change _ = (Multiset.count d (Finset.univ.val.map + (fun y : W => fun i => jointColor H k r (Function.update x i y))) : ℚ) + rw [count_map_as_sum] + apply Finset.sum_congr rfl + intro y _ + exact hprod _ _ + +lemma separate_indicator_sum {k r : ℕ} (i : Fin k) (d : SeparateColor k r) + (a : TuplePair V W k) : + replacementSum i (fun x => if pairSeparate G H k r x = d then (1 : ℚ) else 0) a = + (Multiset.count d ((pairSeparate G H k (r + 1) a).2 i) : ℚ) := by + cases a with + | inl x => exact (count_map_as_sum _ _).symm + | inr x => exact (count_map_as_sum _ _).symm + +lemma pairJoint_zero {k : ℕ} (a : TuplePair V W k) : + pairJoint G H k 0 a = pairAtomic G H a := by + cases a <;> rfl + +lemma pairSeparate_zero {k : ℕ} (a : TuplePair V W k) : + pairSeparate G H k 0 a = pairAtomic G H a := by + cases a <;> rfl + +lemma pairJoint_fst {k r : ℕ} (a : TuplePair V W k) : + (pairJoint G H k (r + 1) a).1 = pairJoint G H k r a := by + cases a <;> rfl + +lemma pairSeparate_fst {k r : ℕ} (a : TuplePair V W k) : + (pairSeparate G H k (r + 1) a).1 = pairSeparate G H k r a := by + cases a <;> rfl + +lemma joint_indicator_mem {k t : ℕ} (hkt : k + 1 ≤ t) (r : ℕ) (d : JointColor k r) : + (fun x => if pairJoint G H k r x = d then (1 : ℚ) else 0) ∈ testSpan G H k t := by + induction r with + | zero => + convert atomic_indicator_mem G H (k := k) (t := t) (by omega) d using 1 + funext x + split_ifs <;> simp_all [pairJoint_zero] + contradiction + | succ r ih => + refine color_indicator_mem_of_separation (testAlgebra G H k t (by omega)) + (pairJoint G H k (r+1)) ?_ d + intro x y hxy + by_contra! hn + apply hxy + apply Prod.ext + · rw [pairJoint_fst, pairJoint_fst] + have hf := ih (pairJoint G H k r x) + have he := hn _ hf (by + intro z w hzw + have hz : pairJoint G H k r z = pairJoint G H k r w := by + simpa only [pairJoint_fst, pairSeparate_fst] using congrArg Prod.fst hzw + rw [hz]) + by_contra hne + simp only [ite_eq_right (Ne.symm hne), ite_true, one_ne_zero] at he + · apply Multiset.ext.mpr + intro e + have hf := testSpan_jointReplacementSum G H hkt (fun i => ih (e i)) + have he := hn _ hf (by + intro z w hzw + rw [joint_indicator_sum, joint_indicator_sum, hzw]) + rw [joint_indicator_sum, joint_indicator_sum] at he + exact_mod_cast he + +lemma separate_indicator_mem {k t : ℕ} (hkt : k ≤ t) (r : ℕ) (d : SeparateColor k r) : + (fun x => if pairSeparate G H k r x = d then (1 : ℚ) else 0) ∈ testSpan G H k t := by + induction r with + | zero => + convert atomic_indicator_mem G H hkt d using 1 + funext x + split_ifs <;> simp_all [pairSeparate_zero] + contradiction + | succ r ih => + refine color_indicator_mem_of_separation (testAlgebra G H k t hkt) + (pairSeparate G H k (r+1)) ?_ d + intro x y hxy + by_contra! hn + apply hxy + apply Prod.ext + · rw [pairSeparate_fst, pairSeparate_fst] + have hf := ih (pairSeparate G H k r x) + have he := hn _ hf (by + intro z w hzw + have hz : pairSeparate G H k r z = pairSeparate G H k r w := by + simpa only [pairJoint_fst, pairSeparate_fst] using congrArg Prod.fst hzw + rw [hz]) + by_contra hne + simp only [ite_eq_right (Ne.symm hne), ite_true, one_ne_zero] at he + · funext i + apply Multiset.ext.mpr + intro e + have hf := testSpan_replacementSum G H hkt i (ih e) + have he := hn _ hf (by + intro z w hzw + rw [separate_indicator_sum, separate_indicator_sum, hzw]) + rw [separate_indicator_sum, separate_indicator_sum] at he + exact_mod_cast he + +end ColorSpan + +section SpanHistograms + +open scoped Classical + +variable {V W X Y D : Type} [Fintype V] [Fintype W] [Fintype X] [Fintype Y] +variable (G : SimpleGraph V) (H : SimpleGraph W) {k t : ℕ} +variable (l : X → TuplePair V W k) (r : Y → TuplePair V W k) + +lemma sum_eq_of_mem_testSpan + (hF : ∀ F : RootedTest k t, ∑ x, testEval G H F (l x) = ∑ y, testEval G H F (r y)) + {f : TuplePair V W k → ℚ} (hf : f ∈ testSpan G H k t) : + ∑ x, f (l x) = ∑ y, f (r y) := by + refine Submodule.span_induction (p := fun f _ => ∑ x, f (l x) = ∑ y, f (r y)) + ?_ ?_ ?_ ?_ hf + · rintro _ ⟨F, rfl⟩ + exact hF F + · simp only [Pi.zero_apply, Finset.sum_const_zero] + · intro f g _ _ ihf ihg + simp only [Pi.add_apply, Finset.sum_add_distrib, ihf, ihg] + · intro a f _ ih + simp only [Pi.smul_apply, smul_eq_mul, ← Finset.mul_sum, ih] + +lemma histograms_eq_of_tests [DecidableEq D] (c : TuplePair V W k → D) + (hc : ∀ d, (fun x => if c x = d then (1 : ℚ) else 0) ∈ testSpan G H k t) + (hF : ∀ F : RootedTest k t, ∑ x, testEval G H F (l x) = ∑ y, testEval G H F (r y)) : + Finset.univ.val.map (c ∘ l) = Finset.univ.val.map (c ∘ r) := by + apply Multiset.ext.mpr + intro d + have he := sum_eq_of_mem_testSpan G H l r hF (hc d) + apply Nat.cast_injective (R := ℚ) + rw [count_map_as_sum, count_map_as_sum] + exact he + +end SpanHistograms + +theorem no_choice_equivalent (k : ℕ) (hk : 4 ≤ k) (c : Convention) + (C : ChoiceSystem (bagParameter c k)) (hn : ¬ C.Successful) : + WLEquivalent (zeroLift C) (starLift C) c k := by + classical + intro r + cases c with + | joint => + exact histograms_eq_of_tests (zeroLift C) (starLift C) Sum.inl Sum.inr + (pairJoint (zeroLift C) (starLift C) k r) + (joint_indicator_mem _ _ (t := k+1) le_rfl r) + (fun F => no_choice_equal_rooted_total F C (by omega) hn) + | separate => + exact histograms_eq_of_tests (zeroLift C) (starLift C) Sum.inl Sum.inr + (pairSeparate (zeroLift C) (starLift C) k r) + (separate_indicator_mem _ _ (t := k) le_rfl r) + (fun F => no_choice_equal_rooted_total F C (by omega) hn) + +end ParityWL + +end OAI diff --git a/lean/OAI/Combinatorics/ParityLifts/Compiler.lean b/lean/OAI/Combinatorics/ParityLifts/Compiler.lean new file mode 100644 index 0000000000000000000000000000000000000000..86fac545be3a63e84070ed2af08931c2f9160a89 --- /dev/null +++ b/lean/OAI/Combinatorics/ParityLifts/Compiler.lean @@ -0,0 +1,267 @@ +import OAI.Combinatorics.ParityLifts.TreeMachine + +namespace OAI + +namespace ParityWL.Complexity + +/-- Finite structured imperative code. Loops are data-dependent, not bounded by +an external oracle. The cost counts the serialized registers traversed by the +stack compiler. -/ +inductive TreeCode (r : ℕ) where + | skip + | op (op : TreeOp r) + | seq (first second : TreeCode r) + | cond (src : Fin r) (nilCase nodeCase : TreeCode r) + | loop (src : Fin r) (body : TreeCode r) + +def TreeCode.compile {r : ℕ} : TreeCode r → FinTree r + | .skip => .of (.halt true) + | .op instr => .of ((TreeMachine.atomic instr).andThen (.halt true)) + | .seq p q => .of (p.compile.program.andThen q.compile.program) + | .cond i p q => .of (TreeMachine.branch i p.compile.program q.compile.program) + | .loop i p => .of ((TreeMachine.branch i (.halt true) + (p.compile.program.andThen (.halt false))).repeat) + +inductive CodeExec {r : ℕ} : TreeCode r → (Fin r → DataTree) → ℕ → (Fin r → DataTree) → Prop + | skip (d) : CodeExec .skip d 0 d + | op (op : TreeOp r) (d) : CodeExec (.op op) d + (dataMass d + dataMass (op.eval d).1 + 2) (op.eval d).1 + | seq {p q d e z n m} : CodeExec p d n e → CodeExec q e m z → + CodeExec (.seq p q) d (n + dataMass e + 1 + m) z + | nil_cond {i p q d e n} : d i = .nil → CodeExec p d n e → + CodeExec (.cond i p q) d (dataMass d + 1 + n) e + | node_cond {i p q d e n} : d i ≠ .nil → CodeExec q d n e → + CodeExec (.cond i p q) d (dataMass d + 1 + n) e + | nil_loop {i p d} : d i = .nil → CodeExec (.loop i p) d (dataMass d + 1) d + | node_loop {i p d e z n m} : d i ≠ .nil → CodeExec p d n e → + CodeExec (.loop i p) e m z → + CodeExec (.loop i p) d (dataMass d + 1 + n + 2 * (dataMass e + 1) + m) z + +lemma CodeExec.compile {r : ℕ} {p : TreeCode r} {d e : Fin r → DataTree} {n : ℕ} + (h : CodeExec p d n e) : TreeRuns p.compile.program d n e true := by + induction h with + | skip d => exact treeHalt_run true d + | op op d => + have h := (treeAtomic_run op d).andThen (treeHalt_run true (op.eval d).1) + convert h using 1 <;> first | rfl | omega + | seq _ _ ih₁ ih₂ => exact ih₁.andThen ih₂ + | nil_cond h _ ih => exact ih.branch_true _ _ _ h + | node_cond h _ ih => exact ih.branch_false _ _ _ h + | nil_loop h => + simpa [TreeCode.compile, FinTree.of, TreeRuns, TreeMachine.repeat] using + TreeExec.repeat_true ((treeHalt_run true _).branch_true _ _ _ h) + | node_loop h _ _ ih₁ ih₂ => + have hr := (ih₁.andThen (treeHalt_run false _)).branch_false _ (.halt true) _ h + have ht := TreeExec.repeat_false hr (by simpa [TreeCode.compile, FinTree.of] using ih₂) + dsimp only [TreeRuns, TreeCode.compile, FinTree.of] + convert ht using 1 <;> first | rfl | omega + +/-- One code derivation yields a multitape computation, after input +register initialization. No complexity-class closure theorem is assumed. -/ +lemma CodeExec.stack_run {r : ℕ} {p : TreeCode r} {d e : Fin r → DataTree} {n : ℕ} + (h : CodeExec p d n e) : ∃ m, m ≤ 51 * n ∧ + Runs p.compile.program.lower.lower (dataWords d) m (dataWords e) true := by + obtain ⟨m, hm, hr⟩ := h.compile.lower + exact ⟨m, hm, hr.lower⟩ + +end ParityWL.Complexity + +namespace ParityWL.Complexity + +lemma Runs.repeat_true {Q : Type} {t a : ℕ} {P : StackMachine Q t a} + {w v : Words t a} {n : ℕ} (h : Runs P w n v true) : Runs P.repeat w n v true := by + obtain ⟨q, hq⟩ := h + exact ⟨q, hq.repeat_true⟩ + +lemma Runs.repeat_false {Q : Type} {t a : ℕ} {P : StackMachine Q t a} + {w v z : Words t a} {n m : ℕ} (h : Runs P w n v false) + (ht : Runs P.repeat v m z true) : Runs P.repeat w (n + 1 + m) z true := by + obtain ⟨q, hq⟩ := h + obtain ⟨s, hs⟩ := ht + exact ⟨s, hq.repeat_false hs⟩ + +def pushWord {t a : ℕ} (dst : Fin (t + 1)) : List (StackSymbol a) → FinStack t a + | [] => .of (.halt true) + | c :: w => .of ((pushSymbol dst c).andThen (pushWord dst w).program) + +lemma pushWord_run {t a : ℕ} (dst : Fin (t + 1)) (xs : List (StackSymbol a)) + (w : Words t a) : Runs (pushWord dst xs).program w (2 * xs.length) + (Function.update w dst (xs.reverse ++ w dst)) true := by + induction xs generalizing w with + | nil => simpa [pushWord, FinStack.of] using halt_run true w + | cons c xs ih => + have h := (pushSymbol_run dst c w).andThen (ih (Function.update w dst (c :: w dst))) + have he : Function.update (Function.update w dst (c :: w dst)) dst + (xs.reverse ++ Function.update w dst (c :: w dst) dst) = + Function.update w dst ((c :: xs).reverse ++ w dst) := by + simp [List.reverse_cons, List.append_assoc] + rw [he] at h + convert h using 1 <;> first | rfl | (simp only [List.length_cons]; omega) + +def bitChunk (b : Bool) : List (StackSymbol 0) := if b then [1, 1, 0, 0] else [1, 0] + +def DataTree.ofBits : List Bool → DataTree + | [] => .nil + | b :: bs => .node (if b then .node .nil .nil else .nil) (ofBits bs) + +lemma ofBits_code (bs : List Bool) : + (DataTree.ofBits bs).code = bs.flatMap bitChunk ++ [0] := by + induction bs with + | nil => rfl + | cons b bs ih => cases b <;> simp [DataTree.ofBits, bitChunk, DataTree.code, ih] + +def expandBit {t : ℕ} (src dst : Fin (t + 1)) (b : Bool) : FinStack t 0 := + .of (((popSymbol src).andThen (pushWord dst (bitChunk b)).program).andThen (.halt false)) + +def expandBitsBody {t : ℕ} (src dst : Fin (t + 1)) : FinStack t 0 := + .of (StackMachine.branch (fun x => (x src).isNone) (.halt true) + (StackMachine.branch (fun x => decide (x src = some 1)) + (expandBit src dst true).program (expandBit src dst false).program)) + +def expandBits {t : ℕ} (src dst : Fin (t + 1)) := (expandBitsBody src dst).program.repeat + +lemma expandBit_run {t : ℕ} (src dst : Fin (t + 1)) (h : src ≠ dst) + (b : Bool) (w : Words t 0) : Runs (expandBit src dst b).program w + (2 * (bitChunk b).length + 3) + (Function.update (Function.update w src (w src).tail) dst ((bitChunk b).reverse ++ w dst)) false := by + have hr := ((popSymbol_run src w).andThen + (pushWord_run dst (bitChunk b) (Function.update w src (w src).tail))).andThen + (halt_run false _) + simp only [Function.update_of_ne h.symm] at hr + convert hr using 1 <;> first | rfl | omega + +lemma expandBits_run {t : ℕ} (src dst : Fin (t + 1)) (h : src ≠ dst) + (bs : List Bool) (w : Words t 0) (hw : w src = bs.map (stackInputSymbol 0)) : + Runs (expandBits src dst) w (2 * (bs.flatMap bitChunk).length + 6 * bs.length + 1) + (Function.update (Function.update w src []) dst ((bs.flatMap bitChunk).reverse ++ w dst)) true := by + induction bs generalizing w with + | nil => + have hr := Runs.branch_true (fun x => (x src).isNone) (StackMachine.halt true) + (StackMachine.branch (fun x => decide (x src = some 1)) + (expandBit src dst true).program (expandBit src dst false).program) + (w := w) (by simp [hw]) (halt_run true w) + have hh := hr.repeat_true + have hw0 : w src = [] := by simpa using hw + have he : Function.update (Function.update w src []) dst (w dst) = w := by + rw [← hw0, Function.update_eq_self, Function.update_eq_self] + simpa only [List.flatMap_nil, List.length_nil, Nat.mul_zero, Nat.zero_add, + List.reverse_nil, List.nil_append, he, expandBits, expandBitsBody, FinStack.of] using hh + | cons b bs ih => + let v := Function.update (Function.update w src (w src).tail) dst ((bitChunk b).reverse ++ w dst) + have hv : v src = bs.map (stackInputSymbol 0) := by simp [v, h, hw] + have hr := expandBit_run src dst h b w + have hr' : Runs (expandBitsBody src dst).program w + (2 * (bitChunk b).length + 5) v false := by + cases b with + | false => + have ht := hr.branch_false (fun x => decide (x src = some 1)) (expandBit src dst true).program _ + (by simp [hw, stackInputSymbol]) + have hh := ht.branch_false (fun x => (x src).isNone) (StackMachine.halt true) _ (by simp [hw]) + convert hh using 1 + rfl + | true => + have ht := hr.branch_true (fun x => decide (x src = some 1)) _ (expandBit src dst false).program + (by simp [hw, stackInputSymbol]) + have hh := ht.branch_false (fun x => (x src).isNone) (StackMachine.halt true) _ (by simp [hw]) + convert hh using 1 + rfl + have ht := hr'.repeat_false (ih v hv) + have he : Function.update (Function.update v src []) dst + ((bs.flatMap bitChunk).reverse ++ v dst) = + Function.update (Function.update w src []) dst + (((b :: bs).flatMap bitChunk).reverse ++ w dst) := by + ext i + by_cases hid : i = dst + · subst i; simp [v, List.reverse_append, List.append_assoc] + · by_cases his : i = src + · subst i; simp [hid, v] + · simp [Function.update_of_ne hid, Function.update_of_ne his, v] + rw [he] at ht + convert ht using 1 <;> first | rfl | + (simp only [List.flatMap_cons, List.length_append, List.length_cons]; omega) + +def readBits {t : ℕ} (src tmp : Fin (t + 1)) := + ((expandBits src tmp).andThen (pushSymbol tmp 0)).andThen (transfer tmp {src}) + +lemma bitChunk_length (b : Bool) : (bitChunk b).length ≤ 4 := by cases b <;> decide + +lemma flatMap_bitChunk_length (bs : List Bool) : (bs.flatMap bitChunk).length ≤ 4 * bs.length := by + induction bs with + | nil => simp + | cons b bs ih => simp only [List.flatMap_cons, List.length_append, List.length_cons] + have := bitChunk_length b + omega + +lemma readBits_run {t : ℕ} (src tmp : Fin (t + 1)) (h : src ≠ tmp) + (bs : List Bool) (w : Words t 0) (hw : w src = bs.map (stackInputSymbol 0)) + (ht : w tmp = []) : ∃ n, n ≤ 22 * bs.length + 7 ∧ + Runs (readBits src tmp) w n (Function.update w src (DataTree.ofBits bs).code) true := by + let v := Function.update (Function.update w src []) tmp ((bs.flatMap bitChunk).reverse ++ w tmp) + have h₁ := expandBits_run src tmp h bs w hw + have h₂ := pushSymbol_run tmp 0 v + let z := Function.update v tmp (0 :: v tmp) + have h₃ := transfer_run tmp {src} z + have hz : z tmp = 0 :: (bs.flatMap bitChunk).reverse := by simp [z, v, ht] + have he : transferred tmp {src} z = Function.update w src (DataTree.ofBits bs).code := by + ext i + by_cases hi : i = tmp + · subst i; simp [transferred, Function.update, h.symm, ht] + · by_cases hs : i = src + · subst i + simp [transferred, h, z, v, ofBits_code, ht] + · simp [transferred, hi, hs, z, v] + have hr := (h₁.andThen h₂).andThen h₃ + rw [he, hz, List.length_cons, List.length_reverse] at hr + refine ⟨_, ?_, hr⟩ + have := flatMap_bitChunk_length bs + omega + +def inputData (r : ℕ) (bs : List Bool) : Fin (r + 1) → DataTree := + fun i => if i = 0 then DataTree.ofBits bs else .nil + +def inputStacks (r : ℕ) (bs : List Bool) : Words (r + 4) 0 := + fun i => if i.val = 0 then bs.map (stackInputSymbol 0) else [] + +def fillData (r : ℕ) := + primitive (t := r + 4) (a := 0) + (fun _ i => if 0 < i.val ∧ i.val < r + 1 then .push 0 else .keep) (fun _ => true) + +def initializeData (r : ℕ) := + (readBits (dataReg (0 : Fin (r + 1))) (workReg (r + 1) 0)).andThen (fillData r) + +lemma initializeData_run (r : ℕ) (bs : List Bool) : + ∃ n, n ≤ 22 * bs.length + 9 ∧ + Runs (initializeData r) (inputStacks r bs) n (dataWords (inputData r bs)) true := by + have hs : inputStacks r bs (dataReg (0 : Fin (r + 1))) = bs.map (stackInputSymbol 0) := by + simp [inputStacks, dataReg] + have ht : inputStacks r bs (workReg (r + 1) 0) = [] := by simp [inputStacks, workReg] + obtain ⟨n, hn, hr⟩ := readBits_run (dataReg (0 : Fin (r + 1))) (workReg (r + 1) 0) + (dataReg_ne_workReg _ _) bs (inputStacks r bs) hs ht + let w := Function.update (inputStacks r bs) (dataReg (0 : Fin (r + 1))) (DataTree.ofBits bs).code + have hf := primitive_exec (t := r + 4) (a := 0) + (fun _ i => if 0 < i.val ∧ i.val < r + 1 then .push 0 else .keep) (fun _ => true) w + have he : applyOps (fun i => if 0 < i.val ∧ i.val < r + 1 then .push 0 else .keep) w = + dataWords (inputData r bs) := by + funext i + refine Fin.addCases (m := r + 1) (n := 4) (fun j => ?_) (fun j => ?_) i + · change applyOps _ w (dataReg j) = dataWords (inputData r bs) (dataReg j) + rw [dataWords_data] + by_cases hj : j = 0 + · subst j; simp [applyOps, dataReg, StackOp.apply, w, inputData] + · have hv : j.val ≠ 0 := by simpa using hj + simp [applyOps, StackOp.apply, w, inputData, hj, inputStacks, dataReg, DataTree.code, + show 0 < j.val by omega, j.isLt] + · change applyOps _ w (workReg (r + 1) j) = dataWords (inputData r bs) (workReg (r + 1) j) + rw [dataWords_work] + have hv : ¬(0 < (workReg (r + 1) j).val ∧ (workReg (r + 1) j).val < r + 1) := by + simp only [workReg, Fin.val_natAdd] + omega + simp only [applyOps, ite_eq_right hv, StackOp.apply, w, + Function.update_of_ne (Ne.symm (dataReg_ne_workReg (0 : Fin (r + 1)) j))] + simp [inputStacks, workReg] + have hf' : Runs (fillData r) w 1 (dataWords (inputData r bs)) true := ⟨some true, he ▸ hf⟩ + exact ⟨n + 1 + 1, by omega, hr.andThen hf'⟩ + +end ParityWL.Complexity + +end OAI diff --git a/lean/OAI/Combinatorics/ParityLifts/CompilerBounds.lean b/lean/OAI/Combinatorics/ParityLifts/CompilerBounds.lean new file mode 100644 index 0000000000000000000000000000000000000000..9152cb2f3d88f2836f8929ea13db859cbbde4d9a --- /dev/null +++ b/lean/OAI/Combinatorics/ParityLifts/CompilerBounds.lean @@ -0,0 +1,332 @@ +import OAI.Combinatorics.ParityLifts.Compiler + +namespace OAI + +namespace ParityWL.Complexity + +def DataBound {r : ℕ} (d : Fin r → DataTree) (S : ℕ) : Prop := ∀ i, (d i).size ≤ S + +lemma DataBound.mass {r S : ℕ} {d : Fin r → DataTree} (h : DataBound d S) : + dataMass d ≤ r * S := by + simpa [dataMass] using Finset.sum_le_sum (s := Finset.univ) (fun i _ => h i) + +inductive BoundedExec {Q : Type} {r : ℕ} (P : TreeMachine Q r) (S : ℕ) : + Q → (Fin r → DataTree) → ℕ → (Fin r → DataTree) → Bool → Prop + | halt (q d b) (ho : P.output q = some b) (hb : DataBound d S) : BoundedExec P S q d 0 d b + | next (q d) {n e b} (ho : P.output q = none) (hb : DataBound d S) + (tail : BoundedExec P S (P.next q ((P.instruction q).eval d).2) + ((P.instruction q).eval d).1 n e b) : BoundedExec P S q d (n + 1) e b + +lemma BoundedExec.start_bound {Q : Type} {r S : ℕ} {P : TreeMachine Q r} + {q d e n b} (h : BoundedExec P S q d n e b) : DataBound d S := by cases h <;> assumption + +lemma BoundedExec.end_bound {Q : Type} {r S : ℕ} {P : TreeMachine Q r} + {q d e n b} (h : BoundedExec P S q d n e b) : DataBound e S := by + induction h with + | halt _ _ _ _ h => exact h + | next _ _ _ _ _ ih => exact ih + +lemma BoundedExec.work {Q : Type} {r S : ℕ} {P : TreeMachine Q r} + {q d e n b} (h : BoundedExec P S q d n e b) : + ∃ w, w ≤ n * (r * S + 1) ∧ TreeExec P q d w e b := by + induction h with + | halt q d b ho hb => exact ⟨0, by simp, .halt q d b ho⟩ + | next q d ho hb _ ih => + obtain ⟨w, hw, he⟩ := ih + refine ⟨dataMass d + 1 + w, ?_, .next q d ho he⟩ + have hm := hb.mass + nlinarith + +abbrev BoundedRuns {Q : Type} {r : ℕ} (P : TreeMachine Q r) (S : ℕ) + (d : Fin r → DataTree) (n : ℕ) (e : Fin r → DataTree) (b : Bool) : Prop := + BoundedExec P S P.initial d n e b + +lemma boundedHalt {r S : ℕ} (b : Bool) (d : Fin r → DataTree) (h : DataBound d S) : + BoundedRuns (.halt b) S d 0 d b := .halt _ _ _ rfl h + +lemma boundedAtomic {r S : ℕ} (op : TreeOp r) (d : Fin r → DataTree) + (h : DataBound d S) (he : DataBound (op.eval d).1 S) : + BoundedRuns (.atomic op) S d 1 (op.eval d).1 (op.eval d).2 := + .next _ _ rfl h (.halt _ _ _ rfl he) + +lemma BoundedExec.map {Q R : Type} {r S : ℕ} {P : TreeMachine Q r} {T : TreeMachine R r} + (f : Q → R) (ho : ∀ q, T.output (f q) = P.output q) + (hi : ∀ q, P.output q = none → T.instruction (f q) = P.instruction q) + (hn : ∀ q b, P.output q = none → T.next (f q) b = f (P.next q b)) + {q : Q} {d e : Fin r → DataTree} {n : ℕ} {b : Bool} (h : BoundedExec P S q d n e b) : + BoundedExec T S (f q) d n e b := by + induction h with + | halt q d b h hb => exact .halt _ _ _ ((ho q).trans h) hb + | next q d h hb _ ih => + apply BoundedExec.next _ _ ((ho q).trans h) hb + simpa only [hi q h, hn q _ h] using ih + +lemma BoundedExec.andThen_right {Q R : Type} {r S : ℕ} + (P : TreeMachine Q r) (T : TreeMachine R r) + {q : R} {d e : Fin r → DataTree} {n : ℕ} {b : Bool} (h : BoundedExec T S q d n e b) : + BoundedExec (P.andThen T) S (.inr q) d n e b := by + exact h.map (T := P.andThen T) Sum.inr (fun _ => rfl) (fun _ _ => rfl) (fun _ _ _ => rfl) + +lemma BoundedExec.andThen {Q R : Type} {r S : ℕ} + {P : TreeMachine Q r} {T : TreeMachine R r} + {q : Q} {d e z : Fin r → DataTree} {n m : ℕ} {b c : Bool} + (h : BoundedExec P S q d n e b) (ht : BoundedRuns T S e m z c) : + BoundedExec (P.andThen T) S (.inl q) d (n + 1 + m) z c := by + induction h with + | halt q d b ho hb => + have hh := ht.andThen_right P T + have hi : (P.andThen T).instruction (.inl q) = .skip := by simp [TreeMachine.andThen, ho] + have hn : (P.andThen T).next (.inl q) true = .inr T.initial := by simp [TreeMachine.andThen, ho] + have he := BoundedExec.next (P := P.andThen T) (.inl q) d rfl hb + (by simpa only [hi, TreeOp.eval, hn] using hh) + convert he using 1 + omega + | next q d ho hb _ ih => + have hi : (P.andThen T).instruction (.inl q) = P.instruction q := by + simp [TreeMachine.andThen, ho] + have hn : ∀ b, (P.andThen T).next (.inl q) b = .inl (P.next q b) := by + intro b; simp [TreeMachine.andThen, ho] + have hh := BoundedExec.next (P := P.andThen T) (.inl q) d rfl hb + (by simpa only [hi, hn] using ih ht) + convert hh using 1 + omega + +lemma BoundedRuns.andThen {Q R : Type} {r S : ℕ} + {P : TreeMachine Q r} {T : TreeMachine R r} + {d e z : Fin r → DataTree} {n m : ℕ} {b c : Bool} + (h : BoundedRuns P S d n e b) (ht : BoundedRuns T S e m z c) : + BoundedRuns (P.andThen T) S d (n + 1 + m) z c := BoundedExec.andThen h ht + +lemma BoundedRuns.branch_true {Q R : Type} {r S : ℕ} (src : Fin r) + (P : TreeMachine Q r) (T : TreeMachine R r) + {d e : Fin r → DataTree} {n : ℕ} {b : Bool} (h : d src = .nil) + (hr : BoundedRuns P S d n e b) : + BoundedRuns (TreeMachine.branch src P T) S d (n + 1) e b := by + have hm := hr.map (T := TreeMachine.branch src P T) (fun q => .inr (.inl q)) + (fun _ => rfl) (fun _ _ => rfl) (fun _ _ _ => rfl) + apply BoundedExec.next _ _ rfl hr.start_bound + simpa [TreeMachine.branch, TreeOp.eval, h] using hm + +lemma BoundedRuns.branch_false {Q R : Type} {r S : ℕ} (src : Fin r) + (P : TreeMachine Q r) (T : TreeMachine R r) + {d e : Fin r → DataTree} {n : ℕ} {b : Bool} (h : d src ≠ .nil) + (hr : BoundedRuns T S d n e b) : + BoundedRuns (TreeMachine.branch src P T) S d (n + 1) e b := by + have hm := hr.map (T := TreeMachine.branch src P T) (fun q => .inr (.inr q)) + (fun _ => rfl) (fun _ _ => rfl) (fun _ _ _ => rfl) + apply BoundedExec.next _ _ rfl hr.start_bound + simpa [TreeMachine.branch, TreeOp.eval, h] using hm + +lemma BoundedExec.repeat_true {Q : Type} {r S : ℕ} {P : TreeMachine Q r} + {q : Q} {d e : Fin r → DataTree} {n : ℕ} (h : BoundedExec P S q d n e true) : + BoundedExec P.repeat S q d n e true := by + generalize hb : true = b at h + induction h with + | halt q d b ho hd => subst b; exact .halt _ _ _ (by simp [TreeMachine.repeat, ho]) hd + | next q d ho hd _ ih => + apply BoundedExec.next _ _ (by simp [TreeMachine.repeat, ho]) hd + simpa only [TreeMachine.repeat, ho, ↓reduceIte] using ih hb + +lemma BoundedExec.repeat_false {Q : Type} {r S : ℕ} {P : TreeMachine Q r} + {q : Q} {d e z : Fin r → DataTree} {n m : ℕ} + (h : BoundedExec P S q d n e false) (ht : BoundedRuns P.repeat S e m z true) : + BoundedExec P.repeat S q d (n + 1 + m) z true := by + generalize hb : false = b at h + induction h with + | halt q d b ho hd => + subst b + have he := BoundedExec.next (P := P.repeat) q d (by simp [TreeMachine.repeat, ho]) hd + (by simpa [BoundedRuns, TreeMachine.repeat, ho, TreeOp.eval] using ht) + convert he using 1 + omega + | next q d ho hd _ ih => + have hi : P.repeat.instruction q = P.instruction q := by simp [TreeMachine.repeat, ho] + have hn : ∀ b, P.repeat.next q b = P.next q b := by intro b; simp [TreeMachine.repeat, ho] + have hh := BoundedExec.next (P := P.repeat) q d (by simp [TreeMachine.repeat, ho]) hd + (by simpa only [hi, hn] using ih ht hb) + convert hh using 1 + omega + +end ParityWL.Complexity + +namespace ParityWL.Complexity + +noncomputable def extendData {r s : ℕ} (f : Fin r ↪ Fin s) + (d : Fin r → DataTree) (e : Fin s → DataTree) : Fin s → DataTree := Function.extend f d e + +@[simp] lemma extendData_apply {r s : ℕ} (f : Fin r ↪ Fin s) + (d : Fin r → DataTree) (e : Fin s → DataTree) (i : Fin r) : extendData f d e (f i) = d i := + f.injective.extend_apply d e i + +lemma extendData_outside {r s : ℕ} (f : Fin r ↪ Fin s) + (d : Fin r → DataTree) (e : Fin s → DataTree) (j : Fin s) (h : ¬∃ i, f i = j) : + extendData f d e j = e j := Function.extend_apply' d e j h + +lemma extendData_update {r s : ℕ} (f : Fin r ↪ Fin s) + (d : Fin r → DataTree) (e : Fin s → DataTree) (i : Fin r) (x : DataTree) : + extendData f (Function.update d i x) e = Function.update (extendData f d e) (f i) x := by + funext j + by_cases hj : ∃ k, f k = j + · obtain ⟨k, rfl⟩ := hj + by_cases hk : k = i + · subst k; simp + · simp [hk, show f k ≠ f i from fun h => hk (f.injective h)] + · have hi : j ≠ f i := fun h => hj ⟨i, h.symm⟩ + simp [extendData_outside f _ _ j hj, hi] + +lemma DataBound.extend {r s S : ℕ} (f : Fin r ↪ Fin s) + {d : Fin r → DataTree} {e : Fin s → DataTree} (hd : DataBound d S) (he : DataBound e S) : + DataBound (extendData f d e) S := by + intro j + by_cases hj : ∃ i, f i = j + · obtain ⟨i, rfl⟩ := hj; simpa using hd i + · simpa [extendData_outside f d e j hj] using he j + +def TreeOp.rename {r s : ℕ} (f : Fin r ↪ Fin s) : TreeOp r → TreeOp s + | .skip => .skip + | .nil i => .nil (f i) + | .node i j k => .node (f i) (f j) (f k) + | .project i j b => .project (f i) (f j) b + | .test i => .test (f i) + +lemma TreeOp.rename_eval {r s : ℕ} (f : Fin r ↪ Fin s) (op : TreeOp r) + (d : Fin r → DataTree) (e : Fin s → DataTree) : + (op.rename f).eval (extendData f d e) = (extendData f (op.eval d).1 e, (op.eval d).2) := by + cases op <;> simp [TreeOp.rename, TreeOp.eval, extendData_update] + +def TreeMachine.rename {Q : Type} {r s : ℕ} (P : TreeMachine Q r) (f : Fin r ↪ Fin s) : + TreeMachine Q s where + initial := P.initial + output := P.output + instruction := fun q => (P.instruction q).rename f + next := P.next + +lemma BoundedExec.rename {Q : Type} {r s S : ℕ} {P : TreeMachine Q r} + (f : Fin r ↪ Fin s) (e : Fin s → DataTree) (he : DataBound e S) + {q d z n b} (h : BoundedExec P S q d n z b) : + BoundedExec (P.rename f) S q (extendData f d e) n (extendData f z e) b := by + induction h with + | halt q d b ho hd => exact .halt q _ b ho (hd.extend f he) + | next q d ho hd _ ih => + apply BoundedExec.next (P := P.rename f) q _ ho (hd.extend f he) + simpa only [TreeMachine.rename, TreeOp.rename_eval] using ih + +/-- A complete compiler from raw input bits, with explicit initialization and +all serialization work charged. -/ +noncomputable def TreeMachine.compiled {Q : Type} [Fintype Q] {r : ℕ} (P : TreeMachine Q (r + 1)) : Machine := + ((initializeData r).andThen P.lower.lower).compiled + +lemma TreeRuns.compiled {Q : Type} [Fintype Q] {r : ℕ} {P : TreeMachine Q (r + 1)} + {bs : List Bool} {w : ℕ} {e : Fin (r + 1) → DataTree} {b : Bool} + (h : TreeRuns P (inputData r bs) w e b) : + ∃ s, s ≤ 102 * w + 44 * bs.length + 20 ∧ Emits P.compiled bs s b := by + obtain ⟨m, hm, hr⟩ := h.lower + obtain ⟨n, hn, hi⟩ := initializeData_run r bs + have hh := hi.andThen hr.lower + exact ⟨2 * (n + 1 + m), by omega, hh.compiled⟩ + +lemma BoundedRuns.compiled {Q : Type} [Fintype Q] {r S : ℕ} {P : TreeMachine Q (r + 1)} + {bs : List Bool} {n : ℕ} {e : Fin (r + 1) → DataTree} {b : Bool} + (h : BoundedRuns P S (inputData r bs) n e b) : + ∃ s, s ≤ 102 * n * ((r + 1) * S + 1) + 44 * bs.length + 20 ∧ + Emits P.compiled bs s b := by + obtain ⟨w, hw, hr⟩ := h.work + obtain ⟨s, hs, he⟩ := TreeRuns.compiled hr + refine ⟨s, ?_, he⟩ + nlinarith + +end ParityWL.Complexity + +namespace ParityWL.Complexity + +lemma DataBound.update {r S : ℕ} {d : Fin r → DataTree} (h : DataBound d S) + (i : Fin r) (x : DataTree) (hx : x.size ≤ S) : DataBound (Function.update d i x) S := by + intro j + by_cases hj : j = i + · subst j; simpa using hx + · simpa [hj] using h j + +inductive BCodeExec {r : ℕ} (S : ℕ) : + TreeCode r → (Fin r → DataTree) → ℕ → (Fin r → DataTree) → Prop + | skip (d) (hb : DataBound d S) : BCodeExec S .skip d 0 d + | op (op : TreeOp r) (d) (hb : DataBound d S) (he : DataBound (op.eval d).1 S) : + BCodeExec S (.op op) d 2 (op.eval d).1 + | seq {p q d e z n m} : BCodeExec S p d n e → BCodeExec S q e m z → + BCodeExec S (.seq p q) d (n + 1 + m) z + | nil_cond {i p q d e n} : d i = .nil → BCodeExec S p d n e → + BCodeExec S (.cond i p q) d (n + 1) e + | node_cond {i p q d e n} : d i ≠ .nil → BCodeExec S q d n e → + BCodeExec S (.cond i p q) d (n + 1) e + | nil_loop {i p d} : d i = .nil → DataBound d S → BCodeExec S (.loop i p) d 1 d + | node_loop {i p d e z n m} : d i ≠ .nil → BCodeExec S p d n e → + BCodeExec S (.loop i p) e m z → BCodeExec S (.loop i p) d (n + m + 3) z + +lemma BCodeExec.compile {r S : ℕ} {p : TreeCode r} {d e : Fin r → DataTree} {n : ℕ} + (h : BCodeExec S p d n e) : BoundedRuns p.compile.program S d n e true := by + induction h with + | skip d hb => exact boundedHalt true d hb + | op op d hb he => + have h := (boundedAtomic op d hb he).andThen (boundedHalt true (op.eval d).1 he) + simpa [TreeCode.compile, FinTree.of] using h + | seq _ _ ih₁ ih₂ => exact ih₁.andThen ih₂ + | nil_cond h _ ih => exact ih.branch_true _ _ _ h + | node_cond h _ ih => exact ih.branch_false _ _ _ h + | nil_loop h hb => + simpa [TreeCode.compile, FinTree.of, BoundedRuns, TreeMachine.repeat] using + BoundedExec.repeat_true ((boundedHalt true _ hb).branch_true _ _ _ h) + | node_loop h _ _ ih₁ ih₂ => + have hr := (ih₁.andThen (boundedHalt false _ ih₁.end_bound)).branch_false _ (.halt true) _ h + have ht := BoundedExec.repeat_false hr (by simpa [TreeCode.compile, FinTree.of] using ih₂) + dsimp only [BoundedRuns, TreeCode.compile, FinTree.of] + convert ht using 1 <;> first | rfl | omega + +lemma BCodeExec.start_bound {r S : ℕ} {p : TreeCode r} {d e : Fin r → DataTree} {n : ℕ} + (h : BCodeExec S p d n e) : DataBound d S := h.compile.start_bound +lemma BCodeExec.end_bound {r S : ℕ} {p : TreeCode r} {d e : Fin r → DataTree} {n : ℕ} + (h : BCodeExec S p d n e) : DataBound e S := h.compile.end_bound + +lemma BCodeExec.nil {r S : ℕ} (i : Fin r) (d : Fin r → DataTree) + (h : DataBound d S) : + BCodeExec S (.op (.nil i)) d 2 (Function.update d i .nil) := by + exact .op _ _ h (h.update i .nil (by have := DataTree.size_pos (d i); have := h i; simp [DataTree.size]; omega)) + +lemma BCodeExec.node {r S : ℕ} (i j k : Fin r) (d : Fin r → DataTree) + (h : DataBound d S) (hx : (DataTree.node (d j) (d k)).size ≤ S) : + BCodeExec S (.op (.node i j k)) d 2 (Function.update d i (.node (d j) (d k))) := by + exact .op _ _ h (h.update i _ hx) + +lemma DataTree.size_child (x : DataTree) (b : Bool) : (x.child b).size ≤ x.size := by + cases x <;> cases b <;> simp [DataTree.child, DataTree.size] + omega + +lemma BCodeExec.project {r S : ℕ} (i j : Fin r) (b : Bool) (d : Fin r → DataTree) + (h : DataBound d S) : + BCodeExec S (.op (.project i j b)) d 2 (Function.update d i ((d j).child b)) := by + exact .op _ _ h (h.update i _ ((DataTree.size_child _ _).trans (h j))) + +/-- Copying is compiled, not a primitive constant-time operation of the tape model. -/ +def TreeCode.copy {r : ℕ} (dst src : Fin r) : TreeCode r := + .seq (.op (.node dst src src)) (.op (.project dst dst false)) + +lemma BCodeExec.copy {r S : ℕ} (i j : Fin r) (d : Fin r → DataTree) + (h : DataBound d (2 * S + 1)) (hx : (d j).size ≤ S) : + BCodeExec (2 * S + 1) (.copy i j) d 5 (Function.update d i (d j)) := by + have h₁ := BCodeExec.node i j j d h (by simp [DataTree.size]; omega) + have h₂ := BCodeExec.project i i false _ h₁.end_bound + simpa [TreeCode.copy, DataTree.child] using h₁.seq h₂ + +lemma BCodeExec.mono {r S T : ℕ} (hST : S ≤ T) + {p : TreeCode r} {d e : Fin r → DataTree} {n : ℕ} (h : BCodeExec S p d n e) : + BCodeExec T p d n e := by + induction h with + | skip d hb => exact .skip d (fun i => (hb i).trans hST) + | op op d hb he => exact .op op d (fun i => (hb i).trans hST) (fun i => (he i).trans hST) + | seq _ _ ih₁ ih₂ => exact ih₁.seq ih₂ + | nil_cond h _ ih => exact ih.nil_cond h + | node_cond h _ ih => exact ih.node_cond h + | nil_loop h hb => exact .nil_loop h (fun i => (hb i).trans hST) + | node_loop h _ _ ih₁ ih₂ => exact .node_loop h ih₁ ih₂ + +end ParityWL.Complexity + +end OAI diff --git a/lean/OAI/Combinatorics/ParityLifts/DataPrograms.lean b/lean/OAI/Combinatorics/ParityLifts/DataPrograms.lean new file mode 100644 index 0000000000000000000000000000000000000000..fb4c1a0238f97dad3557c26ee62facb1845e17bb --- /dev/null +++ b/lean/OAI/Combinatorics/ParityLifts/DataPrograms.lean @@ -0,0 +1,193 @@ +import OAI.Combinatorics.ParityLifts.PolynomialLists + +namespace OAI + +namespace ParityWL.Complexity + +lemma list_fold_map_context {α β γ : Type} (f : α × γ → β) (xs : List α) + (bs : List β) (c : γ) : + xs.foldl (fun s a => (f (a, s.2) :: s.1, s.2)) (bs, c) = + ((xs.map (fun a => f (a, c))).reverse ++ bs, c) := by + induction xs generalizing bs with + | nil => simp + | cons a xs ih => simp [ih, List.append_assoc] + +def PolyProgram.mapWith {α β γ : Type} [TreeCodec α] [TreeCodec β] [TreeCodec γ] + {f : α × γ → β} (P : PolyProgram (α × γ) β f) : + PolyProgram (List α × γ) (List β) (fun x => x.1.map (fun a => f (a, x.2))) := by + let a := PolyProgram.fst α (List β × γ) + let bs := (PolyProgram.snd α (List β × γ)).comp (PolyProgram.fst (List β) γ) + let c := (PolyProgram.snd α (List β × γ)).comp (PolyProgram.snd (List β) γ) + let stepP := ((((a.pair c).comp P).pair bs).comp (PolyProgram.cons β)).pair c + have hg (xs : List α) (s : List β × γ) : + (treeEncode (xs.foldl (fun s a => (f (a, s.2) :: s.1, s.2)) s)).size ≤ + (P.coefficient + 4) * ((treeEncode (xs, s)).size + 1) ^ (P.degree + 1) := by + rcases s with ⟨bs, c⟩ + rw [list_fold_map_context] + let X := (treeEncode (xs, (bs, c))).size + 1 + have hx : 1 ≤ X := by dsimp [X]; omega + have hxpow : X ≤ X ^ (P.degree + 1) := by + simpa using Nat.pow_le_pow_right hx (show 1 ≤ P.degree + 1 by omega) + have hpow : 1 ≤ X ^ P.degree := Nat.one_le_pow _ _ hx + have hsmall : (treeEncode bs).size + (treeEncode c).size + 1 ≤ X := by + simp only [X, treeEncode_pair, DataTree.size]; omega + have hlen : xs.length ≤ X := by + have h := treeEncode_list_length xs + simp only [X, treeEncode_pair, DataTree.size]; omega + have hsum : ((xs.map (fun a => f (a, c))).map + (fun a => (treeEncode a).size + 1)).sum ≤ + (P.coefficient + 1) * X ^ (P.degree + 1) := by + rw [List.map_map] + have h := list_sum_map_le xs + (fun a => (treeEncode (f (a, c))).size + 1) + ((P.coefficient + 1) * X ^ P.degree) (by + intro a ha + have hs := (P.program.run (a, c)).bounds.2.1 + have ht := P.bound (a, c) + have ha := treeEncode_of_mem ha + have hm : (treeEncode (a, c)).size + 1 ≤ X := by + simp only [X, treeEncode_pair, DataTree.size]; omega + have hp := Nat.mul_le_mul_left P.coefficient (Nat.pow_le_pow_left hm P.degree) + nlinarith) + calc + _ ≤ xs.length * ((P.coefficient + 1) * X ^ P.degree) := h + _ ≤ X * ((P.coefficient + 1) * X ^ P.degree) := by gcongr + _ = _ := by rw [pow_succ]; ring + have he := treeEncode_append_size (xs.map (fun a => f (a, c))).reverse bs + rw [treeEncode_reverse_size] at he + have ht := treeEncode_list_size (xs.map (fun a => f (a, c))) + simp only [treeEncode_pair, DataTree.size] + change _ ≤ (P.coefficient + 4) * X ^ (P.degree + 1) + nlinarith + let F := stepP.foldlBounded (P.coefficient + 4) (P.degree + 1) hg + let init := (PolyProgram.fst (List α) γ).pair + ((PolyProgram.const ([] : List β)).pair (PolyProgram.snd (List α) γ)) + refine (init.comp F |>.comp (PolyProgram.fst (List β) γ) |>.comp + (PolyProgram.reverse β)).congr ?_ + intro x + change (x.1.foldl (fun s a => (f (a, s.2) :: s.1, s.2)) ([], x.2)).1.reverse = _ + simp [list_fold_map_context] + +def PolyProgram.any {α : Type} [TreeCodec α] {p : α → Bool} + (P : PolyProgram α Bool p) : PolyProgram (List α) Bool (fun xs => xs.any p) := by + let stepP := ((PolyProgram.snd α Bool).pair ((PolyProgram.fst α Bool).comp P)).comp PolyProgram.or + have hg (xs : List α) (b : Bool) : + (treeEncode (xs.foldl (fun b a => b || p a) b)).size ≤ + 3 * ((treeEncode (xs, b)).size + 1) ^ 0 := by + cases xs.foldl (fun b a => b || p a) b <;> simp [DataTree.size] + let F := stepP.foldlBounded 3 0 hg + refine (((PolyProgram.id (List α)).pair (PolyProgram.const false)).comp F).congr ?_ + intro xs + change xs.foldl (fun b a => b || p a) false = xs.any p + have he (xs : List α) (b : Bool) : xs.foldl (fun b a => b || p a) b = (b || xs.any p) := by + induction xs generalizing b with + | nil => simp + | cons a xs ih => simp [ih, Bool.or_assoc] + simp [he] + +def PolyProgram.all {α : Type} [TreeCodec α] {p : α → Bool} + (P : PolyProgram α Bool p) : PolyProgram (List α) Bool (fun xs => xs.all p) := by + refine ((P.comp PolyProgram.not).any.comp PolyProgram.not).congr ?_ + intro xs + simp [Function.comp_def, List.all_eq_not_any_not] + +end ParityWL.Complexity + +namespace ParityWL.Complexity + +def numTree : ℕ → DataTree + | 0 => .nil + | n + 1 => .node .nil (numTree n) + +@[simp] lemma numTree_size (n : ℕ) : (numTree n).size = 2 * n + 1 := by + induction n with + | zero => rfl + | succ n ih => simp [numTree, DataTree.size, ih]; omega + +lemma numTree_injective : Function.Injective numTree := by + intro n m h + have := congrArg DataTree.size h + simp only [numTree_size] at this + omega + +instance : TreeCodec ℕ := ⟨numTree, numTree_injective⟩ +instance {n : ℕ} : TreeCodec (Fin n) := + ⟨fun i => numTree i.val, fun _ _ h => Fin.ext (numTree_injective h)⟩ + +@[simp] lemma treeEncode_nat (n : ℕ) : treeEncode n = numTree n := rfl +@[simp] lemma treeEncode_fin {n : ℕ} (i : Fin n) : treeEncode i = numTree i.val := rfl + +instance {n : ℕ} {α : Type} [TreeCodec α] : TreeCodec (Fin n → α) where + encode := fun f => treeEncode (List.ofFn f) + injective := by + intro f g h + have he : List.ofFn f = List.ofFn g := TreeCodec.injective h + exact List.ofFn_inj.mp he + +@[simp] lemma treeEncode_fn_zero {α : Type} [TreeCodec α] (f : Fin 0 → α) : + treeEncode f = .nil := by change treeEncode (List.ofFn f) = _; simp + +@[simp] lemma treeEncode_fn_succ {n : ℕ} {α : Type} [TreeCodec α] (f : Fin (n+1) → α) : + treeEncode f = .node (treeEncode (f 0)) (treeEncode (fun i : Fin n => f i.succ)) := by + change treeEncode (List.ofFn f) = _ + rw [List.ofFn_succ] + rfl + +lemma treeEncode_fn_size {n : ℕ} {α : Type} [TreeCodec α] (f : Fin n → α) : + (treeEncode f).size = 1 + ∑ i, ((treeEncode (f i)).size + 1) := by + induction n with + | zero => simp [DataTree.size] + | succ n ih => + rw [treeEncode_fn_succ] + simp only [DataTree.size, ih, Fin.sum_univ_succ] + omega + +def TExpr.nth (i : ℕ) (e : TExpr) : TExpr := + match i with + | 0 => e.left + | j + 1 => nth j e.right + +lemma TExpr.nth_eval {n : ℕ} {α : Type} [TreeCodec α] (i : Fin n) (e : TExpr) + (x : DataTree) (f : Fin n → α) (h : e.eval x = treeEncode f) : + (e.nth i.val).eval x = treeEncode (f i) := by + induction n generalizing e with + | zero => exact Fin.elim0 i + | succ n ih => + refine Fin.cases ?_ (fun i => ?_) i + · simp [nth, eval, h, DataTree.child] + · apply ih i e.right (fun j => f j.succ) + simp [eval, h, DataTree.child] + +def TExpr.caseFin : (n : ℕ) → TExpr → (Fin n → TExpr) → TExpr → TExpr + | 0, _, _, d => d + | n + 1, e, f, d => .cond e (f 0) (caseFin n e.right (fun i => f i.succ) d) + +lemma TExpr.caseFin_eval {n : ℕ} (i : Fin n) (e : TExpr) (f : Fin n → TExpr) + (d : TExpr) (x : DataTree) (h : e.eval x = numTree i.val) : + (caseFin n e f d).eval x = (f i).eval x := by + induction n generalizing e with + | zero => exact Fin.elim0 i + | succ n ih => + revert h + refine Fin.cases ?_ (fun i => ?_) i + · intro h + simp [caseFin, eval, h, numTree] + · intro h + simp only [caseFin, eval, h, Fin.val_succ, numTree, reduceCtorEq, ↓reduceIte] + apply ih i e.right (fun j => f j.succ) + simp [eval, h, numTree, DataTree.child] + +def TExpr.tuple : (n : ℕ) → (Fin n → TExpr) → TExpr + | 0, _ => .nil + | n + 1, f => .pair (f 0) (tuple n (fun i => f i.succ)) + +lemma TExpr.tuple_eval {n : ℕ} {α : Type} [TreeCodec α] (f : Fin n → TExpr) + (x : DataTree) (g : Fin n → α) (h : ∀ i, (f i).eval x = treeEncode (g i)) : + (tuple n f).eval x = treeEncode g := by + induction n with + | zero => simp [tuple, eval, treeEncode_fn_zero] + | succ n ih => simp [tuple, eval, h 0, ih _ (fun i => g i.succ) (fun i => h i.succ)] + +end ParityWL.Complexity + +end OAI diff --git a/lean/OAI/Combinatorics/ParityLifts/DecompositionCuts.lean b/lean/OAI/Combinatorics/ParityLifts/DecompositionCuts.lean new file mode 100644 index 0000000000000000000000000000000000000000..83fb4488571648450b4db71c26c8e2ce83a5b941 --- /dev/null +++ b/lean/OAI/Combinatorics/ParityLifts/DecompositionCuts.lean @@ -0,0 +1,235 @@ +import OAI.Combinatorics.ParityLifts.ChoiceExtraction + +namespace OAI + +namespace ParityWL + +open scoped BigOperators + +section DecompositionCuts + +open scoped Classical + +/-- A finite rooted tree is indexed in parent-before-child order. The cuts below +are the vertex sides of its edges. Validity is recorded separately. -/ +structure RootedCuts (W : Type) where + nodes : ℕ + root : Fin nodes + parent : Fin nodes → Fin nodes + parent_lt : ∀ i, i ≠ root → parent i < i + bag : Fin nodes → Finset W + side : Fin nodes → Finset W + +variable {W : Type} [Fintype W] + +noncomputable def RootedCuts.separator (D : RootedCuts W) (i : Fin D.nodes) : Finset W := + D.bag i ∩ D.bag (D.parent i) + +noncomputable def RootedCuts.reverseSide (D : RootedCuts W) (i : Fin D.nodes) : Finset W := + Finset.univ \ (D.separator i ∪ D.side i) + +/-- At node `i`, region `i` is the parent branch; a child is indexed by itself. +All other regions are empty. -/ +noncomputable def RootedCuts.branch (D : RootedCuts W) (i j : Fin D.nodes) : Finset W := + if j = i then (if i = D.root then ∅ else D.reverseSide i) + else if j ≠ D.root ∧ D.parent j = i then D.side j else ∅ + +noncomputable def RootedCuts.branchSeparator (D : RootedCuts W) + (i j : Fin D.nodes) : Finset W := + if j = i then (if i = D.root then ∅ else D.separator i) + else if j ≠ D.root ∧ D.parent j = i then D.separator j else ∅ + +/-- Standard finite tree-decomposition cuts: the incident outer sides and the +bag partition the graph, and each cut is separated by the intersection of the +incident bags. The strict intersection bound is the reduced form. No parity +or graph-homomorphism property is part of this definition. -/ +structure ReducedCutDecomposition (F : SimpleGraph W) (t : ℕ) extends RootedCuts W where + width : ∀ i, (bag i).card ≤ t + intersection : ∀ i, i ≠ root → (toRootedCuts.separator i).card < t + side_disjoint : ∀ i, i ≠ root → Disjoint (side i) (toRootedCuts.separator i) + boundary : ∀ i, i ≠ root → ∀ x ∈ side i, ∀ y, + F.Adj x y → y ∉ side i → y ∈ toRootedCuts.separator i + bag_disjoint : ∀ i j, Disjoint (bag i) (toRootedCuts.branch i j) + branch_disjoint : ∀ i j k, j ≠ k → + Disjoint (toRootedCuts.branch i j) (toRootedCuts.branch i k) + vertex_cover : ∀ i x, x ∈ bag i ∨ ∃ j, x ∈ toRootedCuts.branch i j + +variable {F : SimpleGraph W} {t : ℕ} + +lemma ReducedCutDecomposition.reverse_boundary (D : ReducedCutDecomposition F t) + (i : Fin D.nodes) (hi : i ≠ D.root) : + ∀ x ∈ D.reverseSide i, ∀ y, F.Adj x y → y ∉ D.reverseSide i → + y ∈ D.separator i := by + intro x hx y he hy + have hx' : x ∉ D.separator i ∧ x ∉ D.side i := by + simpa [RootedCuts.reverseSide] using hx + have hy' : y ∈ D.separator i ∨ y ∈ D.side i := by + by_cases hs : y ∈ D.separator i + · exact Or.inl hs + · exact Or.inr (by simpa [RootedCuts.reverseSide, hs] using hy) + rcases hy' with hy' | hy' + · exact hy' + · exact (hx'.1 (D.boundary i hi y hy' x he.symm hx'.2)).elim + +lemma ReducedCutDecomposition.branchSeparator_sub (D : ReducedCutDecomposition F t) + (i j : Fin D.nodes) : D.branchSeparator i j ⊆ D.bag i := by + unfold RootedCuts.branchSeparator + split_ifs with h hroot hp + · exact Finset.empty_subset _ + · exact Finset.inter_subset_left + · rw [← hp.2] + exact Finset.inter_subset_right + · exact Finset.empty_subset _ + +lemma ReducedCutDecomposition.branchSeparator_small (D : ReducedCutDecomposition F t) + (ht : 0 < t) (i j : Fin D.nodes) : (D.branchSeparator i j).card < t := by + unfold RootedCuts.branchSeparator + split_ifs with h hroot hp + · simpa using ht + · exact D.intersection i hroot + · exact D.intersection j hp.1 + · simpa using ht + +lemma ReducedCutDecomposition.branch_boundary (D : ReducedCutDecomposition F t) + (i j : Fin D.nodes) : ∀ x ∈ D.branch i j, ∀ y, + F.Adj x y → y ∉ D.branch i j → y ∈ D.branchSeparator i j := by + unfold RootedCuts.branch RootedCuts.branchSeparator + split_ifs with h hroot hp + · simp + · exact D.reverse_boundary i hroot + · exact D.boundary j hp.1 + · simp + +noncomputable def ReducedCutDecomposition.region (D : ReducedCutDecomposition F t) + (i : Fin D.nodes) (x : W) : Option (Fin D.nodes) := + if h : x ∈ D.bag i then none else + some (Classical.choose ((D.vertex_cover i x).resolve_left h)) + +lemma ReducedCutDecomposition.region_none (D : ReducedCutDecomposition F t) + (i : Fin D.nodes) : regionSet (D.region i) none = D.bag i := by + ext x + simp [regionSet, ReducedCutDecomposition.region] + +lemma ReducedCutDecomposition.region_some (D : ReducedCutDecomposition F t) + (i j : Fin D.nodes) : regionSet (D.region i) (some j) = D.branch i j := by + ext x + simp only [regionSet, Finset.mem_filter, Finset.mem_univ, true_and] + unfold ReducedCutDecomposition.region + by_cases hx : x ∈ D.bag i + · have hn : x ∉ D.branch i j := fun h => Finset.disjoint_left.mp + (D.bag_disjoint i j) hx h + simp [hx, hn] + · rw [dite_eq_right hx, Option.some.injEq] + let k := Classical.choose ((D.vertex_cover i x).resolve_left hx) + have hk : x ∈ D.branch i k := Classical.choose_spec + ((D.vertex_cover i x).resolve_left hx) + constructor + · intro he + exact he ▸ hk + · intro hj + by_contra hn + exact (Finset.disjoint_left.mp (D.branch_disjoint i k j hn)) hk hj + +variable {a : F →g template t} + +lemma ReducedCutDecomposition.main_side_equal (D : ReducedCutDecomposition F t) + (w : WeightedWitness (template t) F a (starParity t)) + (i : Fin D.nodes) (hi : i ≠ D.root) (j k : Fin t) + (hj : ∀ x ∈ D.separator i, a x ≠ .inl j) + (hk : ∀ x ∈ D.separator i, a x ≠ .inl k) : + w.mass (D.side i) (.inl j) = w.mass (D.side i) (.inl k) := by + by_cases h : j = k + · rw [h] + · exact w.mass_separator (u := .inl j) (v := .inl k) h + (D.side i) (D.separator i) (D.boundary i hi) hj hk + +lemma ReducedCutDecomposition.main_sides_sum (D : ReducedCutDecomposition F t) + (w : WeightedWitness (template t) F a (starParity t)) (ht : 0 < t) + (i : Fin D.nodes) (hi : i ≠ D.root) (j : Fin t) + (hj : ∀ x ∈ D.separator i, a x ≠ .inl j) : + w.mass (D.side i) (.inl j) + w.mass (D.reverseSide i) (.inl j) = 1 := by + have hcover : (D.separator i ∪ D.side i) ∪ D.reverseSide i = Finset.univ := by + ext x + simp [RootedCuts.reverseSide] + have hd : Disjoint (D.separator i ∪ D.side i) (D.reverseSide i) := by + apply Finset.disjoint_left.mpr + intro x hx hy + exact (Finset.mem_sdiff.mp hy).2 hx + have h := w.main_mass ht j + rw [← hcover, w.mass_union _ _ hd, + w.mass_union _ _ (D.side_disjoint i hi).symm, + w.mass_eq_zero _ _ hj, zero_add] at h + exact h + +/-- The sink is obtained constructively from a largest inward-pointing edge in +parent-before-child order. Empty branch indices contribute zero, as required. -/ +theorem ReducedCutDecomposition.balancedStar (D : ReducedCutDecomposition F t) + (w : WeightedWitness (template t) F a (starParity t)) (ht : 0 < t) : + Nonempty (BalancedStar w) := by + let P : Finset (Fin D.nodes) := Finset.univ.filter fun i => i = D.root ∨ + (i ≠ D.root ∧ ∃ j : Fin t, (∀ x ∈ D.separator i, a x ≠ .inl j) ∧ + w.mass (D.side i) (.inl j) = 1) + have hP : P.Nonempty := ⟨D.root, by simp [P]⟩ + let i := P.max' hP + have hiP : i ∈ P := Finset.max'_mem P hP + have himax : ∀ j ∈ P, j ≤ i := fun j hj => Finset.le_max' P j hj + have hzero : ∀ j (k : Fin t), + (∀ x ∈ D.branchSeparator i j, a x ≠ .inl k) → + w.mass (D.branch i j) (.inl k) = 0 := by + intro j k hk + unfold RootedCuts.branch RootedCuts.branchSeparator at * + split_ifs at hk ⊢ with hji hir hp + · simp [WeightedWitness.mass] + · have hip : ∃ l : Fin t, (∀ x ∈ D.separator i, a x ≠ .inl l) ∧ + w.mass (D.side i) (.inl l) = 1 := by + have hm : i = D.root ∨ (i ≠ D.root ∧ ∃ l : Fin t, + (∀ x ∈ D.separator i, a x ≠ .inl l) ∧ + w.mass (D.side i) (.inl l) = 1) := (Finset.mem_filter.mp hiP).2 + exact (hm.resolve_left hir).2 + obtain ⟨l, hl, hmass⟩ := hip + have hside : w.mass (D.side i) (.inl k) = 1 := + (D.main_side_equal w i hir k l hk hl).trans hmass + have hsum := D.main_sides_sum w ht i hir k hk + rw [hside] at hsum + exact add_left_cancel (show 1 + w.mass (D.reverseSide i) (.inl k) = 1 + 0 by + simpa using hsum) + · apply (bit_zero_or_one _).resolve_right + intro hmass + have hjP : j ∈ P := by + simp only [P, Finset.mem_filter, Finset.mem_univ, true_and] + exact Or.inr ⟨hp.1, k, hk, hmass⟩ + have hlt := D.parent_lt j hp.1 + rw [hp.2] at hlt + exact (not_lt_of_ge (himax j hjP)) hlt + · simp [WeightedWitness.mass] + exact ⟨{ + regions := D.nodes + region := D.region i + bag := D.bag i + bag_eq := (D.region_none i).symm + size := D.width i + separator := D.branchSeparator i + separator_sub := D.branchSeparator_sub i + separator_small := D.branchSeparator_small ht i + boundary := by + intro j + rw [D.region_some] + exact D.branch_boundary i j + zero_mass := by + intro j k hk + rw [D.region_some] + exact hzero j k hk }⟩ + +/-- The helper boundary argument in reduced decomposition-cut form. -/ +theorem choice_of_reducedCutDecomposition {C : ChoiceSystem t} + (φ : F →g baseGraph C) + (w : WeightedWitness (template t) F ((baseProjection C).comp φ) (starParity t)) + (D : ReducedCutDecomposition F t) (ht : 0 < t) : C.Successful := by + obtain ⟨s⟩ := D.balancedStar w ht + exact choice_of_balancedStar C φ w s ht + +end DecompositionCuts + +end ParityWL + +end OAI diff --git a/lean/OAI/Combinatorics/ParityLifts/Degree.lean b/lean/OAI/Combinatorics/ParityLifts/Degree.lean new file mode 100644 index 0000000000000000000000000000000000000000..ffb8d26884ccc6d68d77f87516b25afea5aec3f6 --- /dev/null +++ b/lean/OAI/Combinatorics/ParityLifts/Degree.lean @@ -0,0 +1,93 @@ +import OAI.Combinatorics.ParityLifts.LeafProducer + +namespace OAI + +namespace ParityWL.Complexity + +lemma PolyProgram.comp_degree {α β γ : Type} [TreeCodec α] [TreeCodec β] [TreeCodec γ] + {f : α → β} {g : β → γ} (P : PolyProgram α β f) (Q : PolyProgram β γ g) : + (P.comp Q).degree=P.degree+P.degree*Q.degree := rfl + +lemma PolyProgram.pair_degree {α β γ : Type} [TreeCodec α] [TreeCodec β] [TreeCodec γ] + {f : α → β} {g : α → γ} (P : PolyProgram α β f) (Q : PolyProgram α γ g) : + (P.pair Q).degree=P.degree+Q.degree := rfl + +lemma PolyProgram.ite_degree {α β : Type} [TreeCodec α] [TreeCodec β] + {p : α → Bool} {f g : α → β} (P : PolyProgram α Bool p) + (F : PolyProgram α β f) (G : PolyProgram α β g) : + (P.ite F G).degree=P.degree+(F.degree+G.degree) := rfl + +lemma PolyProgram.const_degree {α β : Type} [TreeCodec α] [TreeCodec β] (b : β) : + (PolyProgram.const (α:=α) b).degree=1 := rfl +lemma PolyProgram.id_degree (α : Type) [TreeCodec α] : (PolyProgram.id α).degree=1 := rfl +lemma PolyProgram.fst_degree (α β : Type) [TreeCodec α] [TreeCodec β] : (PolyProgram.fst α β).degree=1 := rfl +lemma PolyProgram.snd_degree (α β : Type) [TreeCodec α] [TreeCodec β] : (PolyProgram.snd α β).degree=1 := rfl +lemma PolyProgram.expr_degree {α β : Type} [TreeCodec α] [TreeCodec β] {f : α → β} + (e : TExpr) (he : ∀ x, e.eval (treeEncode x)=treeEncode (f x)) : + (PolyProgram.expr e he).degree=1 := rfl +lemma PolyProgram.equal_degree (α : Type) [TreeCodec α] [DecidableEq α] : (PolyProgram.equal α).degree=2 := rfl +lemma PolyProgram.foldlGrowing_degree {α β : Type} [TreeCodec α] [TreeCodec β] + {f : α × β → β} (P : PolyProgram (α × β) β f) (D e : ℕ) (hg) : + (P.foldlGrowing D e hg).degree=(e+1)+(e+1)*P.degree+1 := rfl +lemma PolyProgram.foldlBounded_degree {α β : Type} [TreeCodec α] [TreeCodec β] + {f : α × β → β} (P : PolyProgram (α × β) β f) (D e : ℕ) (hg) : + (P.foldlBounded D e hg).degree=(e+1)+(e+1)*P.degree+1 := rfl + +lemma PolyProgram.map_degree_eq {α β γ δ : Type} [TreeCodec α] [TreeCodec β] [TreeCodec γ] [TreeCodec δ] + {f : α → β} {g : γ → δ} (P : PolyProgram α β f) (Q : PolyProgram γ δ g) + (h : P.degree=Q.degree) : P.map.degree=Q.map.degree := by + simp only [PolyProgram.map,PolyProgram.reverse,PolyProgram.congr_degree,PolyProgram.comp_degree, + PolyProgram.pair_degree,PolyProgram.foldlGrowing_degree,PolyProgram.fst_degree,PolyProgram.snd_degree, + PolyProgram.const_degree,PolyProgram.id_degree,PolyProgram.cons,PolyProgram.expr,PolyProgram.of_linear,h] +lemma PolyProgram.mapWith_degree_eq {α β γ δ ε ζ : Type} [TreeCodec α] [TreeCodec β] [TreeCodec γ] + [TreeCodec δ] [TreeCodec ε] [TreeCodec ζ] {f : α × γ → β} {g : δ × ζ → ε} + (P : PolyProgram (α × γ) β f) (Q : PolyProgram (δ × ζ) ε g) + (h : P.degree=Q.degree) : P.mapWith.degree=Q.mapWith.degree := by + simp only [PolyProgram.mapWith,PolyProgram.reverse,PolyProgram.congr_degree,PolyProgram.comp_degree, + PolyProgram.pair_degree,PolyProgram.foldlBounded_degree,PolyProgram.foldlGrowing_degree, + PolyProgram.fst_degree,PolyProgram.snd_degree,PolyProgram.const_degree,PolyProgram.id_degree, + PolyProgram.cons,PolyProgram.expr,PolyProgram.of_linear,h] + +lemma PolyProgram.any_degree_eq {α β : Type} [TreeCodec α] [TreeCodec β] + {f : α → Bool} {g : β → Bool} (P : PolyProgram α Bool f) (Q : PolyProgram β Bool g) + (h : P.degree=Q.degree) : P.any.degree=Q.any.degree := by + simp only [PolyProgram.any,PolyProgram.congr_degree,PolyProgram.comp_degree,PolyProgram.pair_degree, + PolyProgram.foldlBounded_degree,PolyProgram.fst_degree,PolyProgram.snd_degree,PolyProgram.const_degree, + PolyProgram.id_degree,PolyProgram.or,PolyProgram.expr,PolyProgram.of_linear,h] + +lemma PolyProgram.all_degree_eq {α β : Type} [TreeCodec α] [TreeCodec β] + {f : α → Bool} {g : β → Bool} (P : PolyProgram α Bool f) (Q : PolyProgram β Bool g) + (h : P.degree=Q.degree) : P.all.degree=Q.all.degree := by + simp only [PolyProgram.all,PolyProgram.congr_degree,PolyProgram.comp_degree] + rw [PolyProgram.any_degree_eq (P.comp PolyProgram.not) (Q.comp PolyProgram.not) (by + simp only [PolyProgram.comp_degree,h])] + +lemma PolyProgram.filter_degree_eq {α β : Type} [TreeCodec α] [TreeCodec β] + {f : α → Bool} {g : β → Bool} (P : PolyProgram α Bool f) (Q : PolyProgram β Bool g) + (h : P.degree=Q.degree) : P.filter.degree=Q.filter.degree := by + simp only [PolyProgram.filter,PolyProgram.reverse,PolyProgram.congr_degree,PolyProgram.comp_degree, + PolyProgram.pair_degree,PolyProgram.ite_degree,PolyProgram.foldlGrowing_degree, + PolyProgram.fst_degree,PolyProgram.snd_degree,PolyProgram.const_degree,PolyProgram.id_degree, + PolyProgram.cons,PolyProgram.expr,PolyProgram.of_linear,h] + +lemma PolyProgram.tabulate_degree_eq {α β γ δ : Type} [TreeCodec α] [TreeCodec β] [TreeCodec γ] [TreeCodec δ] + {n m : ℕ} {f : Fin n × α → β} {g : Fin m × γ → δ} + (P : PolyProgram (Fin n × α) β f) (Q : PolyProgram (Fin m × γ) δ g) + (h : P.degree=Q.degree) : P.tabulate.degree=Q.tabulate.degree := by + simp only [PolyProgram.tabulate,PolyProgram.recode,PolyProgram.comp_degree,PolyProgram.pair_degree, + PolyProgram.const_degree,PolyProgram.id_degree,PolyProgram.mapWith_degree_eq P Q h] + +lemma PolyProgram.filterWith_degree_eq {α β γ δ : Type} [TreeCodec α] [TreeCodec β] + [TreeCodec γ] [TreeCodec δ] {f : α × β → Bool} {g : γ × δ → Bool} + (P : PolyProgram (α × β) Bool f) (Q : PolyProgram (γ × δ) Bool g) + (h : P.degree=Q.degree) : P.filterWith.degree=Q.filterWith.degree := by + simp only [PolyProgram.filterWith,PolyProgram.congr_degree,PolyProgram.comp_degree] + have hmap := PolyProgram.mapWith_degree_eq ((PolyProgram.fst α β).pair P) ((PolyProgram.fst γ δ).pair Q) + (by simp only [PolyProgram.pair_degree,PolyProgram.fst_degree,h]) + have hfil := PolyProgram.filter_degree_eq (PolyProgram.snd α Bool) (PolyProgram.snd γ Bool) rfl + have hmap' := PolyProgram.map_degree_eq (PolyProgram.fst α Bool) (PolyProgram.fst γ Bool) rfl + simp only [hmap,hfil,hmap'] + +end ParityWL.Complexity + +end OAI diff --git a/lean/OAI/Combinatorics/ParityLifts/DegreeBits.lean b/lean/OAI/Combinatorics/ParityLifts/DegreeBits.lean new file mode 100644 index 0000000000000000000000000000000000000000..30962ec832846abf7c0219b90f665a3c9ba94ba5 --- /dev/null +++ b/lean/OAI/Combinatorics/ParityLifts/DegreeBits.lean @@ -0,0 +1,48 @@ +import OAI.Combinatorics.ParityLifts.DegreeGraph + +namespace OAI + +namespace ParityWL.Complexity +attribute [local simp] PolyProgram.congr_degree PolyProgram.comp_degree PolyProgram.pair_degree + PolyProgram.ite_degree PolyProgram.const_degree PolyProgram.id_degree PolyProgram.fst_degree + PolyProgram.snd_degree PolyProgram.equal_degree PolyProgram.foldlGrowing_degree + PolyProgram.foldlBounded_degree PolyProgram.map_degree PolyProgram.reverse_degree + PolyProgram.mapWith_degree PolyProgram.filter_degree PolyProgram.any_degree + PolyProgram.expr PolyProgram.of_linear PolyProgram.finite_degree PolyProgram.finite2_degree + PolyProgram.evalFin_degree PolyProgram.length_degree + +lemma PolyProgram.tabulate_degree {α β : Type} [TreeCodec α] [TreeCodec β] {n : ℕ} + {f : Fin n × α → β} (P : PolyProgram (Fin n × α) β f) : + P.tabulate.degree=2+2*(468*P.degree^2+1950*P.degree+2184) := by + unfold PolyProgram.tabulate PolyProgram.recode + simp +attribute [local simp] PolyProgram.tabulate_degree +lemma PolyProgram.groupAt_degree (t : ℕ) : + (PolyProgram.groupAt t).degree=(PolyProgram.groupAt 1).degree := by + simp only [PolyProgram.groupAt]; simp +attribute [local simp] PolyProgram.groupAt_degree +lemma PolyProgram.pairKey_degree (t : ℕ) : + (PolyProgram.pairKey t).degree=(PolyProgram.pairKey 1).degree := by + unfold PolyProgram.pairKey + erw [PolyProgram.congr_degree,PolyProgram.congr_degree] + simp +attribute [local simp] PolyProgram.pairKey_degree +lemma PolyProgram.rowKeyWith_degree (t : ℕ) : + (PolyProgram.rowKeyWith t).degree=(PolyProgram.rowKeyWith 1).degree := by + unfold PolyProgram.rowKeyWith + simp +attribute [local simp] PolyProgram.rowKeyWith_degree +lemma PolyProgram.domainWith_degree (t : ℕ) : + (PolyProgram.domainWith t).degree=(PolyProgram.domainWith 1).degree := by + unfold PolyProgram.domainWith + erw [PolyProgram.congr_degree,PolyProgram.congr_degree] + simp +attribute [local simp] PolyProgram.domainWith_degree +lemma PolyProgram.choiceWithWords_degree (t : ℕ) : + (PolyProgram.choiceWithWords t).degree=(PolyProgram.choiceWithWords 1).degree := by + unfold PolyProgram.choiceWithWords + erw [PolyProgram.congr_degree,PolyProgram.congr_degree] + simp +end ParityWL.Complexity + +end OAI diff --git a/lean/OAI/Combinatorics/ParityLifts/DegreeForm.lean b/lean/OAI/Combinatorics/ParityLifts/DegreeForm.lean new file mode 100644 index 0000000000000000000000000000000000000000..32db626a80ea98a4e9ce4339ec87e51979339aea --- /dev/null +++ b/lean/OAI/Combinatorics/ParityLifts/DegreeForm.lean @@ -0,0 +1,30 @@ +import OAI.Combinatorics.ParityLifts.Degree + +namespace OAI + +namespace ParityWL.Complexity +lemma PolyProgram.mapWith_degree {α β γ : Type} [TreeCodec α] [TreeCodec β] [TreeCodec γ] + {f : α × γ → β} (P : PolyProgram (α × γ) β f) : + P.mapWith.degree = 468*P.degree^2+1950*P.degree+2184 := by + simp only [PolyProgram.mapWith,PolyProgram.congr_degree,PolyProgram.comp_degree, + PolyProgram.pair_degree,PolyProgram.foldlBounded_degree,PolyProgram.fst_degree, + PolyProgram.snd_degree,PolyProgram.const_degree,PolyProgram.cons,PolyProgram.expr, + PolyProgram.of_linear,PolyProgram.reverse_degree] + ring_nf +lemma PolyProgram.filter_degree {α : Type} [TreeCodec α] {f : α → Bool} (P : PolyProgram α Bool f) : + P.filter.degree = 260+52*P.degree := by + simp only [PolyProgram.filter,PolyProgram.congr_degree,PolyProgram.comp_degree, + PolyProgram.pair_degree,PolyProgram.foldlGrowing_degree,PolyProgram.fst_degree, + PolyProgram.snd_degree,PolyProgram.const_degree,PolyProgram.cons,PolyProgram.expr, + PolyProgram.of_linear,PolyProgram.reverse_degree,PolyProgram.ite_degree,PolyProgram.id_degree] + ring_nf +lemma PolyProgram.any_degree {α : Type} [TreeCodec α] {f : α → Bool} (P : PolyProgram α Bool f) : + P.any.degree = 14+4*P.degree := by + simp only [PolyProgram.any,PolyProgram.congr_degree,PolyProgram.comp_degree, + PolyProgram.pair_degree,PolyProgram.foldlBounded_degree,PolyProgram.fst_degree, + PolyProgram.snd_degree,PolyProgram.const_degree,PolyProgram.or,PolyProgram.expr, + PolyProgram.of_linear,PolyProgram.id_degree] + ring_nf +end ParityWL.Complexity + +end OAI diff --git a/lean/OAI/Combinatorics/ParityLifts/DegreeGraph.lean b/lean/OAI/Combinatorics/ParityLifts/DegreeGraph.lean new file mode 100644 index 0000000000000000000000000000000000000000..2789f0e2c03eb058bf172039e22d6196bef66134 --- /dev/null +++ b/lean/OAI/Combinatorics/ParityLifts/DegreeGraph.lean @@ -0,0 +1,118 @@ +import OAI.Combinatorics.ParityLifts.DegreeForm + +namespace OAI + +namespace ParityWL.Complexity +attribute [local simp] PolyProgram.congr_degree PolyProgram.comp_degree PolyProgram.pair_degree + PolyProgram.ite_degree PolyProgram.const_degree PolyProgram.id_degree PolyProgram.fst_degree + PolyProgram.snd_degree PolyProgram.equal_degree PolyProgram.foldlGrowing_degree + PolyProgram.foldlBounded_degree PolyProgram.map_degree PolyProgram.reverse_degree + PolyProgram.mapWith_degree PolyProgram.filter_degree PolyProgram.any_degree + PolyProgram.expr PolyProgram.of_linear + +lemma PolyProgram.finite_degree {n : ℕ} {α : Type} [TreeCodec α] (f : Fin n → α) : + (PolyProgram.finite f).degree=1 := rfl +lemma PolyProgram.finite2_degree {n m : ℕ} {α : Type} [TreeCodec α] (f : Fin n → Fin m → α) : + (PolyProgram.finite2 f).degree=1 := rfl +lemma PolyProgram.evalFin_degree (n : ℕ) (α : Type) [TreeCodec α] : + (PolyProgram.evalFin n α).degree=1 := rfl +lemma PolyProgram.length_degree (α : Type) [TreeCodec α] : + (PolyProgram.length α).degree=(PolyProgram.length Bool).degree := by + simp only [PolyProgram.length]; simp +lemma PolyProgram.listShift_degree (α : Type) [TreeCodec α] : + (PolyProgram.listShift α).degree=1 := rfl +attribute [local simp] PolyProgram.finite_degree PolyProgram.finite2_degree PolyProgram.evalFin_degree + PolyProgram.length_degree PolyProgram.listShift_degree +lemma PolyProgram.splitAt_degree (α : Type) [TreeCodec α] : + (PolyProgram.splitAt α).degree=(PolyProgram.splitAt Bool).degree := by + simp only [PolyProgram.splitAt]; simp +attribute [local simp] PolyProgram.splitAt_degree +lemma PolyProgram.getD_degree (α : Type) [TreeCodec α] (a : α) : + (PolyProgram.getD α a).degree=(PolyProgram.getD Bool false).degree := by + simp only [PolyProgram.getD,PolyProgram.drop,PolyProgram.head]; simp +lemma PolyProgram.append_degree (α : Type) [TreeCodec α] : + (PolyProgram.append α).degree=(PolyProgram.append Bool).degree := by + simp only [PolyProgram.append,PolyProgram.cons]; simp +attribute [local simp] PolyProgram.getD_degree PolyProgram.append_degree +lemma PolyProgram.flatten_degree (α : Type) [TreeCodec α] : + (PolyProgram.flatten α).degree=(PolyProgram.flatten Bool).degree := by + simp only [PolyProgram.flatten]; simp +attribute [local simp] PolyProgram.flatten_degree + +lemma PolyProgram.choiceEntry_degree (t : ℕ) : + (PolyProgram.choiceEntry t).degree=(PolyProgram.choiceEntry 1).degree := by + simp only [PolyProgram.choiceEntry]; simp +lemma PolyProgram.choiceBound_degree (t : ℕ) : + (PolyProgram.choiceBound t).degree=(PolyProgram.choiceBound 1).degree := by + simp only [PolyProgram.choiceBound]; simp +attribute [local simp] PolyProgram.choiceEntry_degree PolyProgram.choiceBound_degree +lemma PolyProgram.choiceLabel_degree (t : ℕ) : + (PolyProgram.choiceLabel t).degree=(PolyProgram.choiceLabel 1).degree := by + simp only [PolyProgram.choiceLabel]; simp +attribute [local simp] PolyProgram.choiceLabel_degree +lemma PolyProgram.indexSize_degree (t : ℕ) [NeZero t] (b : TemplateVertex t → Bit) : + (PolyProgram.indexSize t b).degree=(PolyProgram.indexSize 1 (fun _ => 0)).degree := by + simp only [PolyProgram.indexSize]; simp +attribute [local simp] PolyProgram.indexSize_degree +lemma PolyProgram.vertices_degree (t : ℕ) [NeZero t] (b : TemplateVertex t → Bit) : + (PolyProgram.vertices t b).degree=(PolyProgram.vertices 1 (fun _ => 0)).degree := by + unfold PolyProgram.vertices + simp only [_root_.id] + simp +attribute [local simp] PolyProgram.vertices_degree +lemma PolyProgram.evalRule_degree (t : ℕ) : + (PolyProgram.evalRule t).degree=(PolyProgram.evalRule 1).degree := by + simp only [PolyProgram.evalRule]; simp +attribute [local simp] PolyProgram.evalRule_degree +lemma PolyProgram.edgeTest_degree (t : ℕ) [NeZero t] (b : TemplateVertex t → Bit) : + (PolyProgram.edgeTest t b).degree=(PolyProgram.edgeTest 1 (fun _ => 0)).degree := by + simp only [PolyProgram.edgeTest]; simp +attribute [local simp] PolyProgram.edgeTest_degree +lemma PolyProgram.matrixRow_degree (t : ℕ) [NeZero t] (b : TemplateVertex t → Bit) : + (PolyProgram.matrixRow t b).degree=(PolyProgram.matrixRow 1 (fun _ => 0)).degree := by + simp only [PolyProgram.matrixRow]; simp +attribute [local simp] PolyProgram.matrixRow_degree +lemma PolyProgram.matrixRows_degree (t : ℕ) [NeZero t] (b : TemplateVertex t → Bit) : + (PolyProgram.matrixRows t b).degree=(PolyProgram.matrixRows 1 (fun _ => 0)).degree := by + simp only [PolyProgram.matrixRows]; simp +attribute [local simp] PolyProgram.matrixRows_degree +lemma PolyProgram.rowMatrix_degree (t : ℕ) [NeZero t] (b : TemplateVertex t → Bit) : + (PolyProgram.rowMatrix t b).degree=(PolyProgram.rowMatrix 1 (fun _ => 0)).degree := by + simp only [PolyProgram.rowMatrix]; simp +attribute [local simp] PolyProgram.rowMatrix_degree +lemma PolyProgram.matrix_degree_form (t : ℕ) [NeZero t] (b : TemplateVertex t → Bit) : + (PolyProgram.matrix t b).degree= + ((PolyProgram.rowMatrix t b).comp (PolyProgram.flatten Bool)).degree := by + unfold PolyProgram.matrix + exact PolyProgram.congr_degree _ _ +lemma PolyProgram.matrix_degree (t : ℕ) [NeZero t] (b : TemplateVertex t → Bit) : + (PolyProgram.matrix t b).degree=(PolyProgram.matrix 1 (fun _ => 0)).degree := by + rw [PolyProgram.matrix_degree_form,PolyProgram.matrix_degree_form] + simp +attribute [local simp] PolyProgram.matrix_degree +lemma PolyProgram.vertexCount_degree (t : ℕ) [NeZero t] : + (PolyProgram.vertexCount t).degree=(PolyProgram.vertexCount 1).degree := by + simp only [PolyProgram.vertexCount]; simp +attribute [local simp] PolyProgram.vertexCount_degree +lemma PolyProgram.orderPrefix_degree (t : ℕ) [NeZero t] : + (PolyProgram.orderPrefix t).degree=(PolyProgram.orderPrefix 1).degree := by + simp only [PolyProgram.orderPrefix]; simp +attribute [local simp] PolyProgram.orderPrefix_degree +lemma PolyProgram.leftOutput_degree (t : ℕ) [NeZero t] : + (PolyProgram.leftOutput t).degree=(PolyProgram.leftOutput 1).degree := by + simp only [PolyProgram.leftOutput]; simp +attribute [local simp] PolyProgram.leftOutput_degree +lemma PolyProgram.graphOutput_degree_form (t : ℕ) [NeZero t] : + (PolyProgram.graphOutput t).degree= + (((PolyProgram.leftOutput t).pair (PolyProgram.matrix t (starParity t))).comp + (PolyProgram.append Bool)).degree := by + unfold PolyProgram.graphOutput + exact PolyProgram.congr_degree _ _ +lemma PolyProgram.graphOutput_degree (t : ℕ) [NeZero t] : + (PolyProgram.graphOutput t).degree=(PolyProgram.graphOutput 1).degree := by + rw [PolyProgram.graphOutput_degree_form,PolyProgram.graphOutput_degree_form] + simp + +end ParityWL.Complexity + +end OAI diff --git a/lean/OAI/Combinatorics/ParityLifts/Detection.lean b/lean/OAI/Combinatorics/ParityLifts/Detection.lean new file mode 100644 index 0000000000000000000000000000000000000000..b46a770e14fd76ddbeebe30b72a4a2cab933ec9d --- /dev/null +++ b/lean/OAI/Combinatorics/ParityLifts/Detection.lean @@ -0,0 +1,382 @@ +import OAI.Combinatorics.ParityLifts.TagSizes + +namespace OAI + +namespace ParityWL + +open scoped BigOperators + +section Detection + +open scoped Classical + +lemma sum_eq_of_color_histograms {U V D : Type} [Fintype U] [Fintype V] + (f : U → D) (g : V → D) (a : U → ℕ) (b : V → ℕ) + (h : Finset.univ.val.map f = Finset.univ.val.map g) + (hab : ∀ x y, f x = g y → a x = b y) : ∑ x, a x = ∑ y, b y := by + have hr := Multiset.rel_map.mp (Multiset.rel_eq.mpr h) + have hs := hr.mono (fun x _ y _ hxy => hab x y hxy) + have he : Finset.univ.val.map a = Finset.univ.val.map b := + Multiset.rel_eq.mp (Multiset.rel_map.mpr hs) + exact congrArg Multiset.sum he + +variable {V W : Type} [Fintype V] [Fintype W] +variable (G : SimpleGraph V) (H : SimpleGraph W) + +omit [Fintype V] [Fintype W] in +lemma atomic_eq_adj {k : ℕ} {x : Fin k → V} {y : Fin k → W} + (h : atomicType G x = atomicType H y) (i j : Fin k) : + G.Adj (x i) (x j) ↔ H.Adj (y i) (y j) := by + have he := congrArg (fun a : AtomicType k => (a i j).2) h + simpa only [atomicType, decide_eq_decide] using he + +lemma joint_eq_old {k r : ℕ} {x : Fin k → V} {y : Fin k → W} + (h : jointColor G k (r + 1) x = jointColor H k (r + 1) y) : + jointColor G k r x = jointColor H k r y := congrArg Prod.fst h + +lemma separate_eq_old {k r : ℕ} {x : Fin k → V} {y : Fin k → W} + (h : separateColor G k (r + 1) x = separateColor H k (r + 1) y) : + separateColor G k r x = separateColor H k r y := congrArg Prod.fst h + +noncomputable def tripleCount (a b c : V) : ℕ := + Fintype.card {v : V // G.Adj v a ∧ G.Adj v b ∧ G.Adj v c} + +lemma tripleCount_sum (a b c : V) : + tripleCount G a b c = ∑ v : V, if G.Adj v a ∧ G.Adj v b ∧ G.Adj v c then 1 else 0 := by + rw [tripleCount, Fintype.card_subtype, Finset.card_filter] + +lemma coordinate_outside {k : ℕ} (hk : 4 ≤ k) (a b c : Fin k) : + ∃ i : Fin k, i ≠ a ∧ i ≠ b ∧ i ≠ c := by + have hc : ({a, b, c} : Finset (Fin k)).card ≤ 3 := by + exact (Finset.card_insert_le _ _).trans (by + have hh := Finset.card_insert_le b ({c} : Finset (Fin k)) + simp only [Finset.card_singleton] at hh + omega) + have hlt : ({a, b, c} : Finset (Fin k)).card < Fintype.card (Fin k) := by + simpa only [Fintype.card_fin] using hc.trans_lt (by omega) + obtain ⟨i, _, hi⟩ := Finset.exists_mem_notMem_of_card_lt_card + (hlt.trans_eq (Finset.card_univ.symm)) + refine ⟨i, ?_⟩ + simpa only [Finset.mem_insert, Finset.mem_singleton, not_or] using hi + +lemma coordinate_other {k : ℕ} (hk : 2 ≤ k) (a : Fin k) : + ∃ i : Fin k, i ≠ a := by + have hlt : ({a} : Finset (Fin k)).card < Fintype.card (Fin k) := by simp; omega + obtain ⟨i, _, hi⟩ := Finset.exists_mem_notMem_of_card_lt_card + (hlt.trans_eq (Finset.card_univ.symm)) + exact ⟨i, by simpa only [Finset.mem_singleton] using hi⟩ + +lemma tripleCount_eq_separate_one {k : ℕ} (hk : 4 ≤ k) + {x : Fin k → V} {y : Fin k → W} + (h : separateColor G k 1 x = separateColor H k 1 y) (a b c : Fin k) : + tripleCount G (x a) (x b) (x c) = tripleCount H (y a) (y b) (y c) := by + obtain ⟨i, hia, hib, hic⟩ := coordinate_outside hk a b c + rw [tripleCount_sum, tripleCount_sum] + apply sum_eq_of_color_histograms + (fun v => atomicType G (Function.update x i v)) + (fun w => atomicType H (Function.update y i w)) _ _ + (congrArg (fun z => z.2 i) h) + intro v w he + have hadj (p : Fin k) (hp : p ≠ i) : G.Adj v (x p) ↔ H.Adj w (y p) := by + simpa only [Function.update_self, Function.update_of_ne hp] using atomic_eq_adj G H he i p + simp only [hadj a hia.symm, hadj b hib.symm, hadj c hic.symm] + +lemma tripleCount_eq_joint_one {k : ℕ} (hk : 2 ≤ k) + {x : Fin k → V} {y : Fin k → W} + (h : jointColor G k 1 x = jointColor H k 1 y) (a b c : Fin k) : + tripleCount G (x a) (x b) (x c) = tripleCount H (y a) (y b) (y c) := by + rw [tripleCount_sum, tripleCount_sum] + apply sum_eq_of_color_histograms + (fun v => fun i => atomicType G (Function.update x i v)) + (fun w => fun i => atomicType H (Function.update y i w)) _ _ + (congrArg Prod.snd h) + intro v w he + have hadj (p : Fin k) : G.Adj v (x p) ↔ H.Adj w (y p) := by + obtain ⟨i, hi⟩ := coordinate_other hk p + simpa only [Function.update_self, Function.update_of_ne hi.symm] using + atomic_eq_adj G H (congrFun he i) i p + simp only [hadj a, hadj b, hadj c] + +def MainClique {t : ℕ} (z : Fin t → V) : Prop := + ∀ i j, i ≠ j → G.Adj (z i) (z j) + +noncomputable def templateExtensions {t : ℕ} (z : Fin t → V) : ℕ := + if MainClique G z then + ∏ h : Helper t, tripleCount G (z h.1.1.1.1) (z h.1.1.1.2) (z h.1.2) else 0 + +noncomputable def templateHomsEquiv (t : ℕ) : + ((template t) →g G) ≃ + ((z : {z : Fin t → V // MainClique G z}) × + ((h : Helper t) → {v : V // G.Adj v (z.1 h.1.1.1.1) ∧ + G.Adj v (z.1 h.1.1.1.2) ∧ G.Adj v (z.1 h.1.2)})) where + toFun f := ⟨⟨fun i => f (.inl i), fun i j hij => f.map_adj hij⟩, + fun h => ⟨f (.inr h), f.map_adj (Or.inl rfl), f.map_adj (Or.inr (Or.inl rfl)), + f.map_adj (Or.inr (Or.inr rfl))⟩⟩ + invFun f := + { toFun := fun v => match v with | .inl i => f.1.1 i | .inr h => (f.2 h).1 + map_rel' := by + intro a b hab + cases a with + | inl i => + cases b with + | inl j => exact f.1.2 i j hab + | inr h => + rcases hab with hi | hi | hi <;> subst i + · exact (f.2 h).2.1.symm + · exact (f.2 h).2.2.1.symm + · exact (f.2 h).2.2.2.symm + | inr h => + cases b with + | inl i => + rcases hab with hi | hi | hi <;> subst i + · exact (f.2 h).2.1 + · exact (f.2 h).2.2.1 + · exact (f.2 h).2.2.2 + | inr h' => exact hab.elim } + left_inv f := by apply RelHom.ext; intro v; cases v <;> rfl + right_inv f := by rcases f with ⟨⟨z, hz⟩, f⟩; rfl + +lemma homCount_card_equiv {U X : Type} [Fintype U] [Fintype X] + (F : SimpleGraph U) (e : (F →g G) ≃ X) : homCount F G = Fintype.card X := by + classical + exact Fintype.card_congr e + +lemma homCount_template (t : ℕ) : + homCount (template t) G = ∑ z : Fin t → V, templateExtensions G z := by + rw [homCount_card_equiv G (template t) (templateHomsEquiv G t), Fintype.card_sigma] + simp only [Fintype.card_pi] + exact sum_subtype_indicator (MainClique G) + (fun z => ∏ h : Helper t, tripleCount G (z h.1.1.1.1) (z h.1.1.1.2) (z h.1.2)) + +lemma templateExtensions_eq_separate_one {k : ℕ} (hk : 4 ≤ k) + {x : Fin k → V} {y : Fin k → W} + (h : separateColor G k 1 x = separateColor H k 1 y) : + templateExtensions G x = templateExtensions H y := by + have hc : MainClique G x ↔ MainClique H y := by + unfold MainClique + exact forall_congr' (fun i => forall_congr' (fun j => + imp_congr_right (fun _ => atomic_eq_adj G H (separate_eq_old G H h) i j))) + simp only [templateExtensions, hc] + split_ifs + · apply Finset.prod_congr rfl + intro p _ + exact tripleCount_eq_separate_one G H hk h _ _ _ + · rfl + +lemma homCount_template_eq_separate_one {k : ℕ} (hk : 4 ≤ k) + (h : sameHistogram G H .separate k 1) : + homCount (template k) G = homCount (template k) H := by + rw [homCount_template, homCount_template] + exact sum_eq_of_color_histograms _ _ _ _ h + (fun _ _ hxy => templateExtensions_eq_separate_one G H hk hxy) + +def extendTuple {k : ℕ} (x : Fin k → V) (v : V) : Fin (k + 1) → V := + Fin.lastCases v x + +def faceIndex {k : ℕ} (i : Fin k) : Fin (k + 1) → Fin k := Fin.lastCases i id + +omit [Fintype V] in +lemma extend_face {k : ℕ} (x : Fin k → V) (v : V) (i : Fin k) + (a : Fin (k + 1)) (ha : a ≠ i.castSucc) : + Function.update x i v (faceIndex i a) = extendTuple x v a := by + revert ha + refine Fin.lastCases ?_ (fun j => ?_) a + · intro _; simp [faceIndex, extendTuple] + · intro ha + have hji : j ≠ i := by intro h; apply ha; exact congrArg Fin.castSucc h + simp [faceIndex, extendTuple, Function.update_of_ne hji] + +lemma face_avoiding {k : ℕ} (hk : 4 ≤ k) (a b c : Fin (k + 1)) : + ∃ i : Fin k, a ≠ i.castSucc ∧ b ≠ i.castSucc ∧ c ≠ i.castSucc := by + let f : Fin (k + 1) → Fin k := Fin.lastCases ⟨0, by omega⟩ id + obtain ⟨i, hia, hib, hic⟩ := coordinate_outside hk (f a) (f b) (f c) + refine ⟨i, ?_, ?_, ?_⟩ + · intro h; apply hia; rw [h]; simp [f] + · intro h; apply hib; rw [h]; simp [f] + · intro h; apply hic; rw [h]; simp [f] + +lemma extend_adj_eq {k : ℕ} (hk : 4 ≤ k) {x : Fin k → V} {y : Fin k → W} + {v : V} {w : W} + (h : (fun i => jointColor G k 1 (Function.update x i v)) = + (fun i => jointColor H k 1 (Function.update y i w))) (a b : Fin (k + 1)) : + G.Adj (extendTuple x v a) (extendTuple x v b) ↔ + H.Adj (extendTuple y w a) (extendTuple y w b) := by + obtain ⟨i, ha, hb, _⟩ := face_avoiding hk a b b + rw [← extend_face x v i a ha, ← extend_face x v i b hb, + ← extend_face y w i a ha, ← extend_face y w i b hb] + exact atomic_eq_adj G H (joint_eq_old G H (congrFun h i)) _ _ + +lemma extend_triple_eq {k : ℕ} (hk : 4 ≤ k) {x : Fin k → V} {y : Fin k → W} + {v : V} {w : W} + (h : (fun i => jointColor G k 1 (Function.update x i v)) = + (fun i => jointColor H k 1 (Function.update y i w))) (a b c : Fin (k + 1)) : + tripleCount G (extendTuple x v a) (extendTuple x v b) (extendTuple x v c) = + tripleCount H (extendTuple y w a) (extendTuple y w b) (extendTuple y w c) := by + obtain ⟨i, ha, hb, hc⟩ := face_avoiding hk a b c + rw [← extend_face x v i a ha, ← extend_face x v i b hb, ← extend_face x v i c hc, + ← extend_face y w i a ha, ← extend_face y w i b hb, ← extend_face y w i c hc] + exact tripleCount_eq_joint_one G H (by omega) (congrFun h i) _ _ _ + +lemma extensions_eq_joint_vector {k : ℕ} (hk : 4 ≤ k) + {x : Fin k → V} {y : Fin k → W} {v : V} {w : W} + (h : (fun i => jointColor G k 1 (Function.update x i v)) = + (fun i => jointColor H k 1 (Function.update y i w))) : + templateExtensions G (extendTuple x v) = templateExtensions H (extendTuple y w) := by + have hc : MainClique G (extendTuple x v) ↔ MainClique H (extendTuple y w) := by + unfold MainClique + exact forall_congr' (fun i => forall_congr' (fun j => + imp_congr_right (fun _ => extend_adj_eq G H hk h i j))) + simp only [templateExtensions, hc] + split_ifs + · apply Finset.prod_congr rfl + intro p _ + exact extend_triple_eq G H hk h _ _ _ + · rfl + +noncomputable def jointTemplateValue {k : ℕ} (x : Fin k → V) : ℕ := + ∑ v : V, templateExtensions G (extendTuple x v) + +lemma jointTemplateValue_eq {k : ℕ} (hk : 4 ≤ k) {x : Fin k → V} {y : Fin k → W} + (h : jointColor G k 2 x = jointColor H k 2 y) : + jointTemplateValue G x = jointTemplateValue H y := by + exact sum_eq_of_color_histograms _ _ _ _ (congrArg Prod.snd h) + (fun v w he => extensions_eq_joint_vector G H hk he) + +def extendTupleEquiv (k : ℕ) : ((Fin k → V) × V) ≃ (Fin (k + 1) → V) where + toFun q := extendTuple q.1 q.2 + invFun z := (fun i => z i.castSucc, z (Fin.last k)) + left_inv q := by rcases q with ⟨x, v⟩; simp [extendTuple] + right_inv z := by + funext i + refine Fin.lastCases ?_ (fun j => ?_) i <;> simp [extendTuple] + +lemma homCount_template_joint (k : ℕ) : + homCount (template (k + 1)) G = ∑ x : Fin k → V, jointTemplateValue G x := by + rw [homCount_template] + symm + change (∑ x : Fin k → V, ∑ v : V, templateExtensions G (extendTuple x v)) = _ + calc + _ = ∑ q : (Fin k → V) × V, templateExtensions G (extendTuple q.1 q.2) := + (Fintype.sum_prod_type _).symm + _ = _ := Fintype.sum_equiv (extendTupleEquiv k) _ _ (fun _ => rfl) + +lemma homCount_template_eq_joint_two {k : ℕ} (hk : 4 ≤ k) + (h : sameHistogram G H .joint k 2) : + homCount (template (k + 1)) G = homCount (template (k + 1)) H := by + rw [homCount_template_joint, homCount_template_joint] + exact sum_eq_of_color_histograms _ _ _ _ h + (fun _ _ hxy => jointTemplateValue_eq G H hk hxy) + +lemma tripleCount_inl (a b c : V) : + tripleCount (G.sum H) (.inl a) (.inl b) (.inl c) = tripleCount G a b c := by + rw [tripleCount_sum, tripleCount_sum, Fintype.sum_sum_type] + simp only [SimpleGraph.sum_adj, false_and, ite_false, Finset.sum_const_zero, add_zero] + +lemma tripleCount_inr (a b c : W) : + tripleCount (G.sum H) (.inr a) (.inr b) (.inr c) = tripleCount H a b c := by + rw [tripleCount_sum, tripleCount_sum, Fintype.sum_sum_type] + simp only [SimpleGraph.sum_adj, false_and, ite_false, Finset.sum_const_zero, zero_add] + +lemma templateExtensions_inl {t : ℕ} (z : Fin t → V) : + templateExtensions (G.sum H) (Sum.inl ∘ z) = templateExtensions G z := by + have hc : MainClique (G.sum H) (Sum.inl ∘ z) ↔ MainClique G z := Iff.rfl + by_cases h : MainClique G z + · simp only [templateExtensions, ite_eq_left h, ite_eq_left (hc.mpr h), Function.comp_apply] + exact Finset.prod_congr rfl (fun p _ => tripleCount_inl G H _ _ _) + · simp only [templateExtensions, ite_eq_right h, ite_eq_right (mt hc.mp h)] + +lemma templateExtensions_inr {t : ℕ} (z : Fin t → W) : + templateExtensions (G.sum H) (Sum.inr ∘ z) = templateExtensions H z := by + have hc : MainClique (G.sum H) (Sum.inr ∘ z) ↔ MainClique H z := Iff.rfl + by_cases h : MainClique H z + · simp only [templateExtensions, ite_eq_left h, ite_eq_left (hc.mpr h), Function.comp_apply] + exact Finset.prod_congr rfl (fun p _ => tripleCount_inr G H _ _ _) + · simp only [templateExtensions, ite_eq_right h, ite_eq_right (mt hc.mp h)] + +lemma homCount_template_eq_pure_separate_one {k : ℕ} (hk : 4 ≤ k) + (h : samePureHistogram G H .separate k 1) : + homCount (template k) G = homCount (template k) H := by + rw [homCount_template, homCount_template] + apply sum_eq_of_color_histograms _ _ _ _ h + intro x y he + rw [← templateExtensions_inl G H, ← templateExtensions_inr G H] + exact templateExtensions_eq_separate_one (G.sum H) (G.sum H) hk he + +omit [Fintype V] in +lemma extendTuple_map {X : Type} {k : ℕ} (f : V → X) (x : Fin k → V) (v : V) : + extendTuple (f ∘ x) (f v) = f ∘ extendTuple x v := by + funext i + refine Fin.lastCases ?_ (fun j => ?_) i <;> simp [extendTuple] + +lemma jointTemplateValue_inl {k : ℕ} (hk : 1 ≤ k) (x : Fin k → V) : + jointTemplateValue (G.sum H) (Sum.inl ∘ x) = jointTemplateValue G x := by + unfold jointTemplateValue + rw [Fintype.sum_sum_type] + have hz (w : W) : templateExtensions (G.sum H) (extendTuple (Sum.inl ∘ x) (.inr w)) = 0 := by + have hnc : ¬ MainClique (G.sum H) (extendTuple (Sum.inl ∘ x) (.inr w)) := by + intro hc + have hh := hc (⟨0, by omega⟩ : Fin k).castSucc (Fin.last k) (Fin.castSucc_ne_last _) + simp only [extendTuple, Fin.lastCases_castSucc, Fin.lastCases_last, + Function.comp_apply, SimpleGraph.sum_adj] at hh + simp only [templateExtensions, ite_eq_right hnc] + simp only [extendTuple_map, templateExtensions_inl, hz, Finset.sum_const_zero, add_zero] + +lemma jointTemplateValue_inr {k : ℕ} (hk : 1 ≤ k) (x : Fin k → W) : + jointTemplateValue (G.sum H) (Sum.inr ∘ x) = jointTemplateValue H x := by + unfold jointTemplateValue + rw [Fintype.sum_sum_type] + have hz (v : V) : templateExtensions (G.sum H) (extendTuple (Sum.inr ∘ x) (.inl v)) = 0 := by + have hnc : ¬ MainClique (G.sum H) (extendTuple (Sum.inr ∘ x) (.inl v)) := by + intro hc + have hh := hc (⟨0, by omega⟩ : Fin k).castSucc (Fin.last k) (Fin.castSucc_ne_last _) + simp only [extendTuple, Fin.lastCases_castSucc, Fin.lastCases_last, + Function.comp_apply, SimpleGraph.sum_adj] at hh + simp only [templateExtensions, ite_eq_right hnc] + simp only [extendTuple_map, templateExtensions_inr, hz, Finset.sum_const_zero, zero_add] + +lemma homCount_template_eq_pure_joint_two {k : ℕ} (hk : 4 ≤ k) + (h : samePureHistogram G H .joint k 2) : + homCount (template (k + 1)) G = homCount (template (k + 1)) H := by + rw [homCount_template_joint, homCount_template_joint] + apply sum_eq_of_color_histograms _ _ _ _ h + intro x y he + rw [← jointTemplateValue_inl G H (by omega), ← jointTemplateValue_inr G H (by omega)] + exact jointTemplateValue_eq (G.sum H) (G.sum H) hk he + +end Detection + +/-- The "compatible choice" direction, including the claimed short round and +both implementations. This uses the actual uncolored graphs. -/ +theorem successful_detected (k : ℕ) (hk : 4 ≤ k) (c : Convention) + (C : ChoiceSystem (bagParameter c k)) (hs : C.Successful) : + ¬ sameHistogram (zeroLift C) (starLift C) c k (detectionRound c) ∧ + ¬ samePureHistogram (zeroLift C) (starLift C) c k (detectionRound c) := by + have hg := successful_template_count_gap (C := C) (show 0 < bagParameter c k by + cases c <;> simp only [bagParameter] <;> omega) hs + cases c + · constructor + · intro h + exact (ne_of_lt hg) (homCount_template_eq_joint_two _ _ hk h).symm + · intro h + exact (ne_of_lt hg) (homCount_template_eq_pure_joint_two _ _ hk h).symm + · constructor + · intro h + exact (ne_of_lt hg) (homCount_template_eq_separate_one _ _ hk h).symm + · intro h + exact (ne_of_lt hg) (homCount_template_eq_pure_separate_one _ _ hk h).symm + +theorem equivalent_no_choice (k : ℕ) (hk : 4 ≤ k) (c : Convention) + (C : ChoiceSystem (bagParameter c k)) + (h : WLEquivalent (zeroLift C) (starLift C) c k) : ¬ C.Successful := by + intro hs + exact (successful_detected k hk c C hs).1 (h (detectionRound c)) + +theorem pure_equivalent_no_choice (k : ℕ) (hk : 4 ≤ k) (c : Convention) + (C : ChoiceSystem (bagParameter c k)) + (h : PureWLEquivalent (zeroLift C) (starLift C) c k) : ¬ C.Successful := by + intro hs + exact (successful_detected k hk c C hs).2 (h (detectionRound c)) + +end ParityWL + +end OAI diff --git a/lean/OAI/Combinatorics/ParityLifts/Evaluation.lean b/lean/OAI/Combinatorics/ParityLifts/Evaluation.lean new file mode 100644 index 0000000000000000000000000000000000000000..ce749f9e5b98d65dd59ae0ed6e3efbe237502af6 --- /dev/null +++ b/lean/OAI/Combinatorics/ParityLifts/Evaluation.lean @@ -0,0 +1,73 @@ +import OAI.Combinatorics.ParityLifts.CodeErasure + +namespace OAI + +namespace ParityWL.Complexity + +lemma FEval.output_unique {S T : ℕ} {p : FCode} {x y z : DataTree} {n m : ℕ} + (h : FEval S p x n y) (h' : FEval T p x m z) : y=z := by + induction h using FEval.rec generalizing T m z with + | id x hx => cases h'; rfl + | nil x hx => cases h'; rfl + | left x hx => cases h'; rfl + | right x hx => cases h'; rfl + | pair hf hg hb ihf ihg => + cases h' with + | pair hf' hg' hb' => exact congrArg₂ DataTree.node (ihf hf') (ihg hg') + | seq hf hg ihf ihg => + cases h' with + | seq hf' hg' => + have he := ihf hf' + subst he + exact ihg hg' + | nil_branch hf ih => + cases h' with + | nil_branch hf' => exact ih hf' + | node_branch hx hg => exact False.elim (hx rfl) + | node_branch hx hg ih => + cases h' with + | nil_branch hf' => exact False.elim (hx rfl) + | node_branch hx' hg' => exact ih hg' + | nil_cond hp hf ihp ihf => + cases h' with + | nil_cond hp' hf' => exact ihf hf' + | node_cond hp' hz hg => exact False.elim (hz (ihp hp').symm) + | node_cond hp hz hg ihp ihg => + cases h' with + | nil_cond hp' hf' => exact False.elim (hz (ihp hp')) + | node_cond hp' hz' hg' => exact ihg hg' + | loop_stop f x hx he => + cases h' with + | loop_stop => rfl + | loop_next he' h tail => exact False.elim (he' he) + | loop_next he h tail ih iht => + cases h' with + | loop_stop f x hx he' => exact False.elim (he he') + | loop_next he' h' tail' => + have hy := ih h' + subst hy + exact iht tail' + +lemma BEval.output_unique {p : FCode} {x y z : DataTree} {B C : ℕ} + (h : BEval p x B y) (h' : BEval p x C z) : y=z := + h.choose_spec.2.output_unique h'.choose_spec.2 + +lemma PolyProgram.encoding_natural {α β γ δ : Type} [TreeCodec α] [TreeCodec β] + [TreeCodec γ] [TreeCodec δ] {f : α → β} {g : γ → δ} + (P : PolyProgram α β f) (Q : PolyProgram γ δ g) + (h : P.program.code=Q.program.code) (a : α) (c : γ) (hac : treeEncode a=treeEncode c) : + treeEncode (f a)=treeEncode (g c) := by + have hp := P.program.run a + rw [h,hac] at hp + exact hp.output_unique (Q.program.run c) + +lemma treeEncode_map {α β : Type} [TreeCodec α] [TreeCodec β] (f : α → β) + (h : ∀ a, treeEncode (f a)=treeEncode a) (xs : List α) : + treeEncode (xs.map f)=treeEncode xs := by + induction xs with + | nil => rfl + | cons a xs ih => simp only [List.map_cons,treeEncode_cons,h,ih] + +end ParityWL.Complexity + +end OAI diff --git a/lean/OAI/Combinatorics/ParityLifts/ExpBounds.lean b/lean/OAI/Combinatorics/ParityLifts/ExpBounds.lean new file mode 100644 index 0000000000000000000000000000000000000000..ffa49796740b429ac4d3ee816c14b4dc524c11b3 --- /dev/null +++ b/lean/OAI/Combinatorics/ParityLifts/ExpBounds.lean @@ -0,0 +1,120 @@ +import OAI.Combinatorics.ParityLifts.SparseCertificate + +namespace OAI + +namespace ParityWL.Complexity +open Filter Topology + +def ExpBound (f : ℕ → ℝ) (r : ℝ) : Prop := + (∀ n, 0 ≤ f n) ∧ ∃ C : ℝ, 0 C) 0 := by + refine ⟨fun _ => hC, C+1,by positivity,0,?_⟩ + intro n + simp only [pow_zero,zero_mul,Real.rpow_zero,mul_one] + linarith + +lemma ExpBound.poly (d : ℕ) : ExpBound (fun n => (n+1 : ℝ)^d) 0 := by + refine ⟨by intro n; positivity,1,by norm_num,d,?_⟩ + intro n; simp + +lemma ExpBound.exp (r : ℝ) : ExpBound (fun n => (2 : ℝ)^(r*n)) r := by + exact ⟨fun _ => (Real.rpow_pos_of_pos (by norm_num) _).le,1,by norm_num,0,by intro n; simp⟩ + +lemma ExpBound.mono {f g : ℕ → ℝ} {r : ℝ} (h : ExpBound f r) + (hg : ∀ n,0 ≤ g n) (hle : ∀ n,g n ≤ f n) : ExpBound g r := by + obtain ⟨_,C,hC,d,h⟩ := h + exact ⟨hg,C,hC,d,fun n => (hle n).trans (h n)⟩ + +lemma ExpBound.mul {f g : ℕ → ℝ} {r s : ℝ} (hf : ExpBound f r) (hg : ExpBound g s) : + ExpBound (fun n => f n*g n) (r+s) := by + obtain ⟨hf0,C,hC,d,hf⟩ := hf + obtain ⟨hg0,D,hD,e,hg⟩ := hg + refine ⟨fun n => mul_nonneg (hf0 n) (hg0 n),C*D,mul_pos hC hD,d+e,?_⟩ + intro n + calc + _ ≤ (C*(n+1 : ℝ)^d*2^(r*n))*(D*(n+1 : ℝ)^e*2^(s*n)) := + mul_le_mul (hf n) (hg n) (hg0 n) (by positivity) + _ = _ := by rw [add_mul,Real.rpow_add (by norm_num),pow_add]; ring + +lemma ExpBound.mono_rate {f : ℕ → ℝ} {r s : ℝ} (h : ExpBound f r) (hrs : r ≤ s) : + ExpBound f s := by + obtain ⟨hn,C,hC,d,h⟩ := h + refine ⟨hn,C,hC,d,?_⟩ + intro n + apply (h n).trans + apply mul_le_mul_of_nonneg_left _ (by positivity) + exact Real.rpow_le_rpow_of_exponent_le (by norm_num) (mul_le_mul_of_nonneg_right hrs (Nat.cast_nonneg n)) + +lemma ExpBound.add_same {f g : ℕ → ℝ} {r : ℝ} (hf : ExpBound f r) (hg : ExpBound g r) : + ExpBound (fun n => f n+g n) r := by + obtain ⟨hf0,C,hC,d,hf⟩ := hf + obtain ⟨hg0,D,hD,e,hg⟩ := hg + refine ⟨fun n => add_nonneg (hf0 n) (hg0 n),C+D,add_pos hC hD,d+e,?_⟩ + intro n + have hb : (1 : ℝ) ≤ n+1 := by have := Nat.cast_nonneg (α:=ℝ) n; linarith + have hd : (n+1 : ℝ)^d ≤ (n+1 : ℝ)^(d+e) := pow_le_pow_right₀ hb (by omega) + have he : (n+1 : ℝ)^e ≤ (n+1 : ℝ)^(d+e) := pow_le_pow_right₀ hb (by omega) + have h₁ := mul_le_mul_of_nonneg_right (mul_le_mul_of_nonneg_left hd hC.le) + (Real.rpow_nonneg (by norm_num : (0:ℝ) ≤ 2) (r*n)) + have h₂ := mul_le_mul_of_nonneg_right (mul_le_mul_of_nonneg_left he hD.le) + (Real.rpow_nonneg (by norm_num : (0:ℝ) ≤ 2) (r*n)) + nlinarith [hf n,hg n] + +lemma ExpBound.add {f g : ℕ → ℝ} {r s : ℝ} (hf : ExpBound f r) (hg : ExpBound g s) + (hr : 0 ≤ r) (hs : 0 ≤ s) : ExpBound (fun n => f n+g n) (r+s) := + (hf.mono_rate (by linarith)).add_same (hg.mono_rate (by linarith)) + +lemma ExpBound.pow {f : ℕ → ℝ} {r : ℝ} (hf : ExpBound f r) (d : ℕ) : + ExpBound (fun n => f n^d) (d*r) := by + induction d with + | zero => simpa using ExpBound.const 1 (by norm_num) + | succ d ih => + convert ih.mul hf using 1 <;> simp [pow_succ,Nat.cast_add,Nat.cast_one,add_mul] + +lemma polynomial_absorb (d : ℕ) (ε : ℝ) (hε : 0<ε) : + ∃ C : ℝ, 0 (n : ℝ)+1) atTop atTop := + tendsto_atTop_add_const_right atTop 1 tendsto_natCast_atTop_atTop + have hevent := ht.eventually hsmall + obtain ⟨N,hN⟩ := Filter.eventually_atTop.mp hevent + let C := Real.exp a+(N+1 : ℝ)^d + refine ⟨C,by dsimp [C]; positivity,?_⟩ + intro n + have hp : (1 : ℝ) ≤ 2^(ε*n) := Real.one_le_rpow (by norm_num) (by positivity) + by_cases hn : N ≤ n + · have h := hN n hn + simp only [Real.norm_eq_abs,abs_of_nonneg (show 0 ≤ (n+1 : ℝ)^d by positivity), + abs_of_pos (Real.exp_pos _),one_mul] at h + have he : Real.exp (a*((n : ℝ)+1))=Real.exp a*2^(ε*n) := by + rw [Real.rpow_def_of_pos (by norm_num)] + rw [←Real.exp_add] + congr 1 + dsimp [a]; ring + rw [he] at h + apply h.trans + gcongr + dsimp [C]; exact le_add_of_nonneg_right (by positivity) + · have hpow : (n+1 : ℝ)^d ≤ (N+1 : ℝ)^d := by gcongr; exact_mod_cast (show n ≤ N by omega) + calc + _ ≤ (N+1 : ℝ)^d := hpow + _ ≤ C := by dsimp [C]; exact le_add_of_nonneg_left (Real.exp_pos a).le + _ ≤ C*2^(ε*n) := le_mul_of_one_le_right (by dsimp [C]; positivity) hp + +lemma ExpBound.absorb {f : ℕ → ℝ} {r : ℝ} (hf : ExpBound f r) (ε : ℝ) (hε : 0<ε) : + ∃ C : ℝ, 0 + C*(L+1 : ℝ)^(2*normalizeProgram.degree+2)* + 2^((reductionRate P j (bagParameter c k) r+ε)*N)) := by + obtain ⟨P,hP,h⟩ := leafCost_rate + refine ⟨P,hP,?_⟩ + intro j hj k hk c _ i M r hr hm ε hε + obtain ⟨C,hC,hRun⟩ := leafMachine_run k hk c i M r hr hm + obtain ⟨W,hW,hWF⟩ := h (bagParameter c k) (12*j) M C r hC hr + have hpos : 0 ≤ (P : ℝ)*(r+1)*leafSlope (bagParameter c k) (12*j) := + mul_nonneg (by positivity) (leafSlope_nonneg _ _) + have hp := @postCode_run j hj (leafDecisionCode (bagParameter c k) M) W hW.1 (by + intro N F hsz hlen hw + obtain ⟨b,hb,he⟩ := hRun F hw + exact ⟨b,hb.mono (hWF N F hsz hlen),he⟩) + have hRate := postBudget_rate j W _ hpos hW + have hpos' : 0 ≤ 2/(j : ℝ)+(P : ℝ)*(r+1)*leafSlope (bagParameter c k) (12*j) := by positivity + obtain ⟨D,hD,hDtime⟩ := sat_code_rate _ _ _ hpos' hRate hp ε hε + refine ⟨D,hD,?_⟩ + dsimp only [fixedSATCode] + convert hDtime using 1 + funext N L + dsimp only [reductionRate] + congr 2 + ring + +lemma SATTimeBound.mono {M : Machine} {B D : ℕ → ℕ → ℝ} + (h : SATTimeBound M B) (hd : ∀ N L,B N L ≤ D N L) : SATTimeBound M D := by + intro N F + obtain ⟨s,b,hs,hb,ht⟩ := h N F + exact ⟨s,b,hs,hb,ht.trans (hd N (encodeFormula F).length)⟩ + +lemma SATTimeBound.rate_mono {M : Machine} {C a b : ℝ} {d : ℕ} + (hC : 0 ≤ C) (hab : a ≤ b) + (h : SATTimeBound M (fun N L => C*(L+1 : ℝ)^d*2^(a*N))) : + SATTimeBound M (fun N L => C*(L+1 : ℝ)^d*2^(b*N)) := + h.mono (by + intro N L + apply mul_le_mul_of_nonneg_left _ (by positivity) + exact Real.rpow_le_rpow_of_exponent_le (by norm_num) + (mul_le_mul_of_nonneg_right hab (Nat.cast_nonneg N))) +end ParityWL.Complexity + +end OAI diff --git a/lean/OAI/Combinatorics/ParityLifts/FixedETH.lean b/lean/OAI/Combinatorics/ParityLifts/FixedETH.lean new file mode 100644 index 0000000000000000000000000000000000000000..03e4c85fdd6ab45bf0c8461fc8e516b8d572105d --- /dev/null +++ b/lean/OAI/Combinatorics/ParityLifts/FixedETH.lean @@ -0,0 +1,72 @@ +import OAI.Combinatorics.ParityLifts.FixedBridge + +namespace OAI + +namespace ParityWL.Complexity + +lemma rate_parameters (P : ℕ) (δ : ℝ) (hδ : 0<δ) : + ∃ (j : ℕ), 0 simp [bagParameter] + let : NeZero (bagParameter conv k) := ⟨by omega⟩ + obtain ⟨C,hC,hSAT⟩ := hRed j hj k hk4 conv i M (c*k) (by positivity) hM (δ/4) (by positivity) + exact hETH ⟨(fixedSATCode j (bagParameter conv k) M).decision,C, + 2*normalizeProgram.degree+2,hC,hSAT.rate_mono hC.le (hRate k _ hk hkt)⟩ + +end ParityWL.Complexity + +end OAI diff --git a/lean/OAI/Combinatorics/ParityLifts/FlowerPrograms.lean b/lean/OAI/Combinatorics/ParityLifts/FlowerPrograms.lean new file mode 100644 index 0000000000000000000000000000000000000000..2264dc1ee73f1fdfb20f69ea0d357a5b65af6624 --- /dev/null +++ b/lean/OAI/Combinatorics/ParityLifts/FlowerPrograms.lean @@ -0,0 +1,121 @@ +import OAI.Combinatorics.ParityLifts.FlowerSearch + +namespace OAI + +namespace ParityWL.Complexity + +def PolyProgram.swap (α β : Type) [TreeCodec α] [TreeCodec β] : + PolyProgram (α × β) (β × α) (fun x => (x.2,x.1)) := + .expr (.pair TExpr.input.right TExpr.input.left) (by intro x; rfl) + + +noncomputable def PolyProgram.allWith {α γ : Type} [TreeCodec α] [TreeCodec γ] + {p : α × γ → Bool} (P : PolyProgram (α × γ) Bool p) : + PolyProgram (List α × γ) Bool (fun x => x.1.all (fun a => p (a,x.2))) := + (P.mapWith.comp (PolyProgram.id Bool).all).congr (by intro x; simp only [Function.comp_def,List.all_map,id_eq]) + +noncomputable def PolyProgram.card (α : Type) [TreeCodec α] [DecidableEq α] : + PolyProgram (List α) ℕ (fun x => x.toFinset.card) := by + let P := PolyProgram.dedupBy (_root_.id : α → α) (PolyProgram.equal α) + exact (P.comp (PolyProgram.length α)).congr (by + intro x + have h := List.toFinset_card_of_nodup (dedupBy_nodup (_root_.id : α → α) x) + have he : (Complexity.dedupBy (_root_.id : α → α) x).toFinset=x.toFinset := by + simpa only [List.map_id] using dedupBy_set (_root_.id : α → α) x + simpa only [List.map_id,he,Function.comp_def] using h.symm) + +noncomputable def PolyProgram.cnfCard (α : Type) [TreeCodec α] [DecidableEq α] : + PolyProgram (ClauseList α) ℕ (fun x => (listCNF x).card) := + ((PolyProgram.compactCNF α).comp (PolyProgram.length (List α))).congr (compactCNF_length) + +noncomputable def PolyProgram.cardEq (α : Type) [TreeCodec α] [DecidableEq α] (n : ℕ) : + PolyProgram (List α) Bool (fun x => decide (x.toFinset.card=n)) := + (((PolyProgram.card α).pair (PolyProgram.const n)).comp (PolyProgram.equal ℕ)) + +noncomputable def PolyProgram.petalsApart (α : Type) [TreeCodec α] [DecidableEq α] : + PolyProgram (ClauseList α) Bool (fun xs => decide (∀ P∈xs, ∀ Q∈xs, + P.toFinset=Q.toFinset ∨ Disjoint P.toFinset Q.toFinset)) := by + classical + let R := (((PolyProgram.clauseEqual α).pair (PolyProgram.clauseDisjoint α)).comp PolyProgram.or).allWith + let S := ((PolyProgram.swap (List α) (ClauseList α)).comp R).allWith + exact (((PolyProgram.id (ClauseList α)).pair (PolyProgram.id (ClauseList α))).comp S).congr (by + intro xs + apply Bool.eq_iff_iff.mpr + simp only [Function.comp_def,id_eq,List.all_eq_true,Bool.or_eq_true,decide_eq_true_eq] + constructor <;> intro h P hP Q hQ <;> exact h Q hQ P hP) + +noncomputable def PolyProgram.clauseMember (α : Type) [TreeCodec α] [DecidableEq α] : + PolyProgram (List α × ClauseList α) Bool (fun x => decide (x.1.toFinset∈listCNF x.2)) := by + let sw : PolyProgram (List α × ClauseList α) (ClauseList α × List α) (fun x => (x.2,x.1)) := + .expr (.pair TExpr.input.right TExpr.input.left) (by intro x; rfl) + exact (sw.comp ((PolyProgram.clauseEqual α).mapWith.comp (PolyProgram.id Bool).any)).congr (by + intro x + apply Bool.eq_iff_iff.mpr + simp only [Function.comp_def,List.any_map,id_eq,List.any_eq_true,decide_eq_true_eq,mem_listCNF]) + +noncomputable def PolyProgram.flowerCover (α : Type) [TreeCodec α] [DecidableEq α] : + PolyProgram (FlowerRecord α × ClauseList α) Bool (fun x => decide (∀ P∈x.1.2, + x.1.1.toFinset∪P.toFinset∈listCNF x.2)) := by + classical + let pa : PolyProgram (List α × (List α × ClauseList α)) (List α × List α) (fun x => (x.2.1,x.1)) := + .expr (.pair TExpr.input.right.left TExpr.input.left) (by intro x; rfl) + let fs : PolyProgram (List α × (List α × ClauseList α)) (ClauseList α) (fun x => x.2.2) := + .expr TExpr.input.right.right (by intro x; rfl) + let P := (((pa.comp (PolyProgram.append α)).pair fs).comp (PolyProgram.clauseMember α)).allWith + let sw : PolyProgram (FlowerRecord α × ClauseList α) (ClauseList α × (List α × ClauseList α)) + (fun x => (x.1.2,(x.1.1,x.2))) := + .expr (.pair TExpr.input.left.right (.pair TExpr.input.left.left TExpr.input.right)) (by intro x; rfl) + exact (sw.comp P).congr (by + intro x + apply Bool.eq_iff_iff.mpr + simp only [Function.comp_def,List.all_eq_true,decide_eq_true_eq,List.toFinset_append]) + +noncomputable def PolyProgram.goodFlower (α : Type) [TreeCodec α] [DecidableEq α] (p q h : ℕ) : + PolyProgram (FlowerRecord α × ClauseList α) Bool (fun x => @decide (GoodFlower x.2 p q h x.1) (Classical.propDecidable _)) := by + classical + let core : PolyProgram (FlowerRecord α × ClauseList α) (List α) (fun x => x.1.1) := + .expr TExpr.input.left.left (by intro x; rfl) + let petals : PolyProgram (FlowerRecord α × ClauseList α) (ClauseList α) (fun x => x.1.2) := + .expr TExpr.input.left.right (by intro x; rfl) + let cp := core.comp (PolyProgram.cardEq α p) + let hp := ((petals.comp (PolyProgram.cnfCard α)).pair (PolyProgram.const h)).comp (PolyProgram.equal ℕ) + let qp := petals.comp (PolyProgram.cardEq α q).all + let sw : PolyProgram (List α × List α) (List α × List α) (fun x => (x.2,x.1)) := + .expr (.pair TExpr.input.right TExpr.input.left) (by intro x; rfl) + let apart := (petals.pair core).comp (sw.comp (PolyProgram.clauseDisjoint α)).allWith + let pp := petals.comp (PolyProgram.petalsApart α) + let H := (PolyProgram.flowerCover α) + let H' := (pp.pair H).comp PolyProgram.and + let H'' := (apart.pair H').comp PolyProgram.and + let H''' := (qp.pair H'').comp PolyProgram.and + let H'''' := (hp.pair H''').comp PolyProgram.and + exact ((cp.pair H'''').comp PolyProgram.and).congr (by + intro x + apply Bool.eq_iff_iff.mpr + simp only [decide_eq_true_eq] + simp only [Function.comp_def,Bool.and_eq_true,decide_eq_true_eq,List.all_eq_true,GoodFlower]) + +noncomputable def PolyProgram.flowerCandidates (α : Type) [TreeCodec α] [DecidableEq α] (p h : ℕ) : + PolyProgram (ClauseList α) (List (FlowerRecord α)) (fun F => Complexity.flowerCandidates F p h) := by + let form := PolyProgram.id (ClauseList α) + let cores := form.comp ((PolyProgram.flatten α).comp (PolyProgram.allTuples α p)) + let clauses := form.comp (PolyProgram.allTuples (List α) h) + let petalMap := (PolyProgram.clauseDiff α).mapWith + let sw : PolyProgram (List α × ClauseList α) (ClauseList α × List α) (fun x => (x.2,x.1)) := + .expr (.pair TExpr.input.right TExpr.input.left) (by intro x; rfl) + let cell := (PolyProgram.fst (List α) (ClauseList α)).pair (sw.comp petalMap) + let sw2 : PolyProgram (ClauseList α × List α) (List α × ClauseList α) (fun x => (x.2,x.1)) := + .expr (.pair TExpr.input.right TExpr.input.left) (by intro x; rfl) + let cells := (PolyProgram.swap (List α) (List (ClauseList α))).comp (sw2.comp cell).mapWith + exact (((cores.pair clauses).comp cells.mapWith).comp (PolyProgram.flatten (FlowerRecord α))).congr (by + intro F + simp only [Complexity.flowerCandidates,Function.comp_def,id_eq,List.flatMap_def]) + +noncomputable def PolyProgram.flowerList (α : Type) [TreeCodec α] [DecidableEq α] (p q h : ℕ) : + PolyProgram (ClauseList α) (List (FlowerRecord α)) (fun F => Complexity.flowerList F p q h) := + ((((PolyProgram.flowerCandidates α p h).pair (PolyProgram.id (ClauseList α))).comp + (PolyProgram.goodFlower α p q h).filterWith)).congr (by intro F; rfl) + +end ParityWL.Complexity + +end OAI diff --git a/lean/OAI/Combinatorics/ParityLifts/FlowerSearch.lean b/lean/OAI/Combinatorics/ParityLifts/FlowerSearch.lean new file mode 100644 index 0000000000000000000000000000000000000000..c9c79351859e29933a749bd500702a0226edbde0 --- /dev/null +++ b/lean/OAI/Combinatorics/ParityLifts/FlowerSearch.lean @@ -0,0 +1,148 @@ +import OAI.Combinatorics.ParityLifts.SetPrograms + +namespace OAI + +namespace ParityWL.Complexity + +abbrev FlowerRecord (α : Type) := List α × ClauseList α + +noncomputable def GoodFlower {α : Type} [DecidableEq α] (F : ClauseList α) + (p q h : ℕ) (z : FlowerRecord α) : Prop := + z.1.toFinset.card=p ∧ (listCNF z.2).card=h ∧ + (∀ P∈z.2, P.toFinset.card=q) ∧ + (∀ P∈z.2, Disjoint z.1.toFinset P.toFinset) ∧ + (∀ P∈z.2, ∀ Q∈z.2, P.toFinset=Q.toFinset ∨ Disjoint P.toFinset Q.toFinset) ∧ + ∀ P∈z.2, z.1.toFinset ∪ P.toFinset∈listCNF F + +noncomputable def GoodFlower.toFlower {α : Type} [DecidableEq α] {F : ClauseList α} + {p q h : ℕ} {z : FlowerRecord α} (hz : GoodFlower F p q h z) : + Sparsification.Flower (listCNF F) p q h where + core := z.1.toFinset + petals := listCNF z.2 + core_card := hz.1 + petals_card := hz.2.1 + petal_card := by + intro P hP + obtain ⟨Q,hQ,rfl⟩ := mem_listCNF.mp hP + exact hz.2.2.1 Q hQ + apart := by + intro P hP + obtain ⟨Q,hQ,rfl⟩ := mem_listCNF.mp hP + exact hz.2.2.2.1 Q hQ + pairwise := by + intro P hP R hR hne + obtain ⟨Q,hQ,rfl⟩ := mem_listCNF.mp hP + obtain ⟨S,hS,rfl⟩ := mem_listCNF.mp hR + exact (hz.2.2.2.2.1 Q hQ S hS).resolve_left hne + cover := by + intro P hP + obtain ⟨Q,hQ,rfl⟩ := mem_listCNF.mp hP + exact hz.2.2.2.2.2 Q hQ + +lemma GoodFlower.ofFlower {α : Type} [DecidableEq α] {F : ClauseList α} + {p q h : ℕ} {z : FlowerRecord α} (f : Sparsification.Flower (listCNF F) p q h) + (hc : z.1.toFinset=f.core) (hp : listCNF z.2=f.petals) : GoodFlower F p q h z := by + have hm (P : List α) (hP : P∈z.2) : P.toFinset∈f.petals := by + rw [← hp] + exact mem_listCNF.mpr ⟨P,hP,rfl⟩ + refine ⟨by rw [hc,f.core_card],by rw [hp,f.petals_card],?_,?_,?_,?_⟩ + · intro P hP; exact f.petal_card _ (hm P hP) + · intro P hP; rw [hc]; exact f.apart _ (hm P hP) + · intro P hP Q hQ + by_cases he : P.toFinset=Q.toFinset + · exact Or.inl he + · exact Or.inr (f.pairwise (hm P hP) (hm Q hQ) he) + · intro P hP; rw [hc]; exact f.cover _ (hm P hP) + +noncomputable def flowerCandidates {α : Type} [DecidableEq α] + (F : ClauseList α) (p h : ℕ) : List (FlowerRecord α) := + (allTuples p F.flatten).flatMap (fun C => (allTuples h F).map (fun As => + (C, As.map (fun A => clauseDiff A C)))) + +lemma mem_flowerCandidates {α : Type} [DecidableEq α] (F : ClauseList α) (p h : ℕ) + (z : FlowerRecord α) : z∈flowerCandidates F p h ↔ + ∃ C As, C.length=p ∧ C⊆F.flatten ∧ As.length=h ∧ As⊆F ∧ + z=(C,As.map (fun A => clauseDiff A C)) := by + simp only [flowerCandidates,List.mem_flatMap,List.mem_map,mem_allTuples] + constructor + · rintro ⟨C,⟨hC,hCF⟩,As,⟨hAs,hAF⟩,he⟩ + exact ⟨C,As,hC,hCF,hAs,hAF,he.symm⟩ + · rintro ⟨C,As,hC,hCF,hAs,hAF,rfl⟩ + exact ⟨C,⟨hC,hCF⟩,As,⟨hAs,hAF⟩,rfl⟩ + +lemma flowerCandidates_complete {α : Type} [DecidableEq α] {F : ClauseList α} + {p q h : ℕ} (hh : 0 rep P.1 P.2) + let Bs := As.map (fun A => clauseDiff A C) + have hC : C.toFinset=f.core := Finset.toList_toFinset _ + have hBset (P : {P // P∈f.petals}) : + (clauseDiff (rep P.1 P.2) C).toFinset=P.1 := by + rw [clauseDiff_set,hset,hC] + ext a + have hdis := Finset.disjoint_left.mp (f.apart P.1 P.2) + simp only [Finset.mem_sdiff,Finset.mem_union] + exact ⟨fun he => he.1.resolve_left he.2, + fun he => ⟨Or.inr he,fun ha => hdis ha he⟩⟩ + have hBs : listCNF Bs=f.petals := by + ext P + simp only [listCNF,Bs,As,List.map_map,List.mem_toFinset,List.mem_map,Function.comp_def,hBset] + constructor + · rintro ⟨Q,_,rfl⟩; exact Q.2 + · intro hP + exact ⟨⟨P,hP⟩,by simp [Ps],rfl⟩ + have hcore : C⊆F.flatten := by + obtain ⟨P,hP⟩ := Finset.card_pos.mp (by rw [f.petals_card]; exact hh) + intro a ha + apply List.mem_flatten.mpr + exact ⟨rep P hP,hrep P hP,List.mem_toFinset.mp (by rw [hset]; exact Finset.mem_union_left _ (by simpa [C] using ha))⟩ + have hAs : As⊆F := by + intro A hA + obtain ⟨P,_,rfl⟩ := List.mem_map.mp hA + exact hrep P.1 P.2 + refine ⟨(C,Bs),(mem_flowerCandidates F p h _).mpr ⟨C,As,?_,hcore,?_,hAs,rfl⟩,?_⟩ + · simpa [C] using f.core_card + · simpa [As,Ps] using f.petals_card + · exact GoodFlower.ofFlower f hC hBs + +noncomputable def flowerList {α : Type} [DecidableEq α] (F : ClauseList α) (p q h : ℕ) : + List (FlowerRecord α) := by + classical + exact (flowerCandidates F p h).filter (fun z => decide (GoodFlower F p q h z)) + +lemma mem_flowerList {α : Type} [DecidableEq α] (F : ClauseList α) (p q h : ℕ) (z : FlowerRecord α) : + z∈flowerList F p q h ↔ z∈flowerCandidates F p h ∧ GoodFlower F p q h z := by + classical + simp [flowerList] + +lemma flowerList_ne_nil {α : Type} [DecidableEq α] (F : ClauseList α) (p q h : ℕ) (hh : 0 exact (he heq).elim + | cons a as => simp)).2 + +end ParityWL.Complexity + +end OAI diff --git a/lean/OAI/Combinatorics/ParityLifts/Flowers.lean b/lean/OAI/Combinatorics/ParityLifts/Flowers.lean new file mode 100644 index 0000000000000000000000000000000000000000..7d7b5966cfae8627c0e42273ec06d6c438e9b8db --- /dev/null +++ b/lean/OAI/Combinatorics/ParityLifts/Flowers.lean @@ -0,0 +1,273 @@ +import OAI.Combinatorics.ParityLifts.ReducedCNF + +namespace OAI + +namespace Sparsification + +variable {α : Type} [DecidableEq α] + +omit [DecidableEq α] in +lemma singletons_pairwise (A : CNF α) (hA : ∀ C ∈ A, C.card = 1) : + (↑A : Set (Finset α)).Pairwise Disjoint := by + intro C hC D hD hne + obtain ⟨x, rfl⟩ := Finset.card_eq_one.mp (hA C hC) + obtain ⟨y, rfl⟩ := Finset.card_eq_one.mp (hA D hD) + simpa using fun he : x = y => hne (he ▸ rfl) + +lemma pairwise_degree_le_one (A : CNF α) (hA : (↑A : Set (Finset α)).Pairwise Disjoint) + (x : α) : degree A x ≤ 1 := by + apply Finset.card_le_one.mpr + intro C hC D hD + by_contra hne + exact Finset.disjoint_left.mp + (hA (Finset.mem_filter.mp hC).1 (Finset.mem_filter.mp hD).1 hne) + (Finset.mem_filter.mp hC).2 (Finset.mem_filter.mp hD).2 + +lemma singleton_degree_le_one (C : Finset α) (x : α) : degree {C} x ≤ 1 := by + exact (Finset.card_filter_le _ _).trans (by simp) + +lemma erase_image_injective (S : CNF α) (x : α) (hx : ∀ C ∈ S, x ∈ C) : + Set.InjOn (fun C : Finset α => C.erase x) ↑S := by + intro C hC D hD he + have hc := Finset.insert_erase (hx C hC) + have hd := Finset.insert_erase (hx D hD) + change C.erase x = D.erase x at he + rw [← hc, ← hd, he] + +lemma flower_two_of_degree {F : CNF α} {h : ℕ} (x : α) + (hd : h ≤ degree (binaries F) x) : Nonempty (Flower F 1 1 h) := by + obtain ⟨S, hS, hc⟩ := Finset.exists_subset_card_eq hd + have hsx : ∀ C ∈ S, x ∈ C := fun C hC => (Finset.mem_filter.mp (hS hC)).2 + have hsc : ∀ C ∈ S, C.card = 2 := fun C hC => + (Finset.mem_filter.mp (Finset.mem_filter.mp (hS hC)).1).2 + let A := S.image (fun C => C.erase x) + have hAc : ∀ P ∈ A, P.card = 1 := by + intro P hP + obtain ⟨C, hC, rfl⟩ := Finset.mem_image.mp hP + rw [Finset.card_erase_of_mem (hsx C hC), hsc C hC] + refine ⟨{ + core := {x} + petals := A + core_card := by simp + petals_card := ?_ + petal_card := hAc + apart := ?_ + pairwise := singletons_pairwise A hAc + cover := ?_ }⟩ + · exact (Finset.card_image_of_injOn (erase_image_injective S x hsx)).trans hc + · intro P hP + obtain ⟨C, _hC, rfl⟩ := Finset.mem_image.mp hP + simp + · intro P hP + obtain ⟨C, hC, rfl⟩ := Finset.mem_image.mp hP + simpa [Finset.singleton_union, Finset.insert_erase (hsx C hC)] using + (Finset.mem_filter.mp (Finset.mem_filter.mp (hS hC)).1).1 + +lemma no_two_flower_degree {F : CNF α} {h : ℕ} (hn : ¬ Nonempty (Flower F 1 1 h)) : + ∀ x, degree (binaries F) x < h := by + intro x + by_contra hx + exact hn (flower_two_of_degree x (by omega)) + +/-- The rank-two sunflower bound, proved directly by a largest disjoint family. -/ +lemma rank_two_sunflower {F : CNF α} {h : ℕ} (hsize : ∀ C ∈ F, C.card = 2) + (hcard : 2 * h ^ 2 < F.card) : + Nonempty (Flower F 0 2 h) ∨ Nonempty (Flower F 1 1 h) := by + classical + let P : Finset (CNF α) := F.powerset.filter + (fun S : CNF α => (↑S : Set (Finset α)).Pairwise Disjoint) + obtain ⟨S, hS, hmax⟩ := Finset.exists_max_image P Finset.card + ⟨∅, by simp [P, Set.pairwise_empty]⟩ + have hSF : S ⊆ F := Finset.mem_powerset.mp (Finset.mem_filter.mp hS).1 + have hpair : (↑S : Set (Finset α)).Pairwise Disjoint := (Finset.mem_filter.mp hS).2 + by_cases hh : h ≤ S.card + · obtain ⟨A, hAS, hAc⟩ := Finset.exists_subset_card_eq hh + left + exact ⟨{ + core := ∅ + petals := A + core_card := by simp + petals_card := hAc + petal_card := fun C hC => hsize C (hSF (hAS hC)) + apart := by intros; exact disjoint_bot_left + pairwise := hpair.mono hAS + cover := by intro C hC; simpa using hSF (hAS hC) }⟩ + · have cover : ∀ C ∈ F, ∃ x ∈ S.biUnion id, x ∈ C := by + intro C hC + by_contra hn + have hd : ∀ D ∈ S, Disjoint C D := by + intro D hD + apply Finset.disjoint_left.mpr + intro x hx hxD + exact hn ⟨x, Finset.mem_biUnion.mpr ⟨D, hD, hxD⟩, hx⟩ + have hCS : C ∉ S := by + intro hcs + have hem : C = ∅ := disjoint_self.mp (hd C hcs) + have := hsize C hC + simp [hem] at this + have hp : insert C S ∈ P := by + apply Finset.mem_filter.mpr + refine ⟨Finset.mem_powerset.mpr (Finset.insert_subset hC hSF), ?_⟩ + intro D hD E hE hne + rcases Finset.mem_insert.mp hD with hDC | hDS + · subst D + rcases Finset.mem_insert.mp hE with hEC | hES + · exact False.elim (hne hEC.symm) + · exact hd E hES + · rcases Finset.mem_insert.mp hE with hEC | hES + · subst E + exact (hd D hDS).symm + · exact hpair hDS hES hne + have hm := hmax (insert C S) hp + rw [Finset.card_insert_of_notMem hCS] at hm + omega + have hcovercard : (S.biUnion id).card ≤ 2 * S.card := by + calc + _ ≤ ∑ C ∈ S, C.card := Finset.card_biUnion_le + _ = ∑ _C ∈ S, 2 := Finset.sum_congr rfl (fun C hC => hsize C (hSF hC)) + _ = _ := by simp [Nat.mul_comm] + have hs : F ⊆ (S.biUnion id).biUnion (fun x => F.filter (fun C => x ∈ C)) := by + intro C hC + obtain ⟨x, hx, hxC⟩ := cover C hC + exact Finset.mem_biUnion.mpr ⟨x, hx, Finset.mem_filter.mpr ⟨hC, hxC⟩⟩ + have hex : ∃ x ∈ S.biUnion id, h ≤ degree F x := by + by_contra hn + have hdeg : ∀ x ∈ S.biUnion id, degree F x ≤ h := by + intro x hx + by_contra hgt + exact hn ⟨x, hx, by omega⟩ + have hc : F.card ≤ (S.biUnion id).card * h := by + calc + _ ≤ ((S.biUnion id).biUnion (fun x => F.filter (fun C => x ∈ C))).card := + Finset.card_le_card hs + _ ≤ ∑ x ∈ S.biUnion id, degree F x := Finset.card_biUnion_le + _ ≤ ∑ _x ∈ S.biUnion id, h := Finset.sum_le_sum hdeg + _ = _ := by simp + nlinarith + obtain ⟨x, _hx, hx⟩ := hex + right + apply flower_two_of_degree x + have hb : binaries F = F := Finset.filter_eq_self.mpr hsize + simpa [hb] using hx + +end Sparsification + + +namespace Sparsification + +variable {α : Type} [DecidableEq α] + +lemma Flower.reattach {E F : CNF α} {p q h : ℕ} (f : Flower E p q h) + (x : α) (hx : ∀ C ∈ E, x ∉ C) (hc : ∀ C ∈ E, insert x C ∈ F) (hh : 0 < h) : + Nonempty (Flower F (p + 1) q h) := by + have hn : x ∉ f.core := by + obtain ⟨P, hP⟩ := Finset.card_pos.mp (by rw [f.petals_card]; exact hh) + intro hxc + exact hx _ (f.cover P hP) (Finset.mem_union_left _ hxc) + refine ⟨{ + core := insert x f.core + petals := f.petals + core_card := by rw [Finset.card_insert_of_notMem hn, f.core_card] + petals_card := f.petals_card + petal_card := f.petal_card + apart := ?_ + pairwise := f.pairwise + cover := ?_ }⟩ + · intro P hP + have hxp : x ∉ P := fun h => hx _ (f.cover P hP) (Finset.mem_union_right _ h) + simp [Finset.disjoint_insert_left, hxp, f.apart P hP] + · intro P hP + simpa [Finset.insert_union] using hc _ (f.cover P hP) + +def triples (F : CNF α) : CNF α := F.filter (fun C => C.card = 3) + +lemma no_three_flower_degree {F : CNF α} {h : ℕ} (hh : 0 < h) + (h1 : ¬ Nonempty (Flower F 1 2 h)) (h2 : ¬ Nonempty (Flower F 2 1 h)) : + ∀ x, degree (triples F) x ≤ 2 * h ^ 2 := by + intro x + by_contra hgt + let S := (triples F).filter (fun C => x ∈ C) + have hsx : ∀ C ∈ S, x ∈ C := fun C hC => (Finset.mem_filter.mp hC).2 + have hsc : ∀ C ∈ S, C.card = 3 := fun C hC => + (Finset.mem_filter.mp (Finset.mem_filter.mp hC).1).2 + let E := S.image (fun C => C.erase x) + have hec : ∀ C ∈ E, C.card = 2 := by + intro C hC + obtain ⟨D, hD, rfl⟩ := Finset.mem_image.mp hC + rw [Finset.card_erase_of_mem (hsx D hD), hsc D hD] + have hcard : 2 * h ^ 2 < E.card := by + have he := Finset.card_image_of_injOn (erase_image_injective S x hsx) + dsimp only [E] + rw [he] + exact Nat.lt_of_not_ge hgt + have hex : ∀ C ∈ E, x ∉ C := by + intro C hC + obtain ⟨D, _hD, rfl⟩ := Finset.mem_image.mp hC + exact Finset.notMem_erase _ _ + have heF : ∀ C ∈ E, insert x C ∈ F := by + intro C hC + obtain ⟨D, hD, rfl⟩ := Finset.mem_image.mp hC + rw [Finset.insert_erase (hsx D hD)] + exact (Finset.mem_filter.mp (Finset.mem_filter.mp hD).1).1 + rcases rank_two_sunflower hec hcard with hf | hf + · obtain ⟨f⟩ := hf + exact h1 (f.reattach x hex heF hh) + · obtain ⟨f⟩ := hf + exact h2 (f.reattach x hex heF hh) + +variable [Fintype α] + +lemma width_three_count (F : CNF α) (hw : ∀ C ∈ F, C.card ≤ 3) : + F.card ≤ 1 + (units F).card + (binaries F).card + (triples F).card := by + let U := (units F).image (fun x => ({x} : Finset α)) + have hs : F ⊆ (({∅} ∪ U) ∪ binaries F) ∪ triples F := by + intro C hC + have hh := hw C hC + by_cases h2 : C.card = 2 + · exact Finset.mem_union_left _ (Finset.mem_union_right _ (Finset.mem_filter.mpr ⟨hC, h2⟩)) + by_cases h3 : C.card = 3 + · exact Finset.mem_union_right _ (Finset.mem_filter.mpr ⟨hC, h3⟩) + rcases Nat.le_one_iff_eq_zero_or_eq_one.mp (show C.card ≤ 1 by omega) with hz | ho + · have hc : C = ∅ := Finset.card_eq_zero.mp hz + subst C + simp + · obtain ⟨x, rfl⟩ := Finset.card_eq_one.mp ho + apply Finset.mem_union_left + apply Finset.mem_union_left + apply Finset.mem_union_right + exact Finset.mem_image.mpr ⟨x, (mem_units F x).mpr hC, rfl⟩ + have h0 := Finset.card_le_card hs + have h1 := Finset.card_union_le ({∅} : CNF α) U + have h2 := Finset.card_union_le ({∅} ∪ U) (binaries F) + have h3 := Finset.card_union_le (({∅} ∪ U) ∪ binaries F) (triples F) + have hU : U.card ≤ (units F).card := Finset.card_image_le + simp only [Finset.card_singleton] at h1 + omega + +lemma sparse_leaf_density (F : CNF α) (h₂ h₃ : ℕ) (hh : 0 < h₃) + (hw : ∀ C ∈ F, C.card ≤ 3) + (hn2 : ¬ Nonempty (Flower F 1 1 h₂)) + (hn31 : ¬ Nonempty (Flower F 1 2 h₃)) (hn32 : ¬ Nonempty (Flower F 2 1 h₃)) : + F.card ≤ 1 + Fintype.card α * (1 + h₂ + 2 * h₃ ^ 2) := by + have hb : (binaries F).card ≤ Fintype.card α * h₂ := by + apply marked_card_bound + · intro C hC + apply Finset.card_pos.mp + rw [(Finset.mem_filter.mp hC).2] + omega + · intro x + exact (no_two_flower_degree hn2 x).le + have ht : (triples F).card ≤ Fintype.card α * (2 * h₃ ^ 2) := by + apply marked_card_bound + · intro C hC + apply Finset.card_pos.mp + rw [(Finset.mem_filter.mp hC).2] + omega + · exact no_three_flower_degree hh hn31 hn32 + have hu : (units F).card ≤ Fintype.card α := Finset.card_le_univ _ + have hF := width_three_count F hw + nlinarith + +end Sparsification + +end OAI diff --git a/lean/OAI/Combinatorics/ParityLifts/FunctionalCode.lean b/lean/OAI/Combinatorics/ParityLifts/FunctionalCode.lean new file mode 100644 index 0000000000000000000000000000000000000000..9e29f6a8fe9a5f4511d4366e19192bdf1ecb1da3 --- /dev/null +++ b/lean/OAI/Combinatorics/ParityLifts/FunctionalCode.lean @@ -0,0 +1,149 @@ +import OAI.Combinatorics.ParityLifts.CompilerBounds + +namespace OAI + +namespace ParityWL.Complexity + +/-- A finite first-order functional language on binary trees. There are no +function-valued atoms: only projections, pairing, composition, branching and +an ordinary data-dependent loop. -/ +inductive FCode where + | id | nil | left | right + | pair (f g : FCode) + | seq (f g : FCode) + | branch (nilCase nodeCase : FCode) + | cond (test nilCase nodeCase : FCode) + | loop (body : FCode) + deriving DecidableEq + +inductive FWhile (S : ℕ) (R : DataTree → ℕ → DataTree → Prop) : + DataTree → ℕ → DataTree → Prop + | stop (x) (hx : x.size ≤ S) (he : x.child false = .nil) : FWhile S R x 1 x + | next {x y z n m} (he : x.child false ≠ .nil) (h : R x n y) + (tail : FWhile S R y m z) : FWhile S R x (n + m + 1) z + +inductive FEval (S : ℕ) : FCode → DataTree → ℕ → DataTree → Prop + | id (x) (h : x.size ≤ S) : FEval S .id x 1 x + | nil (x) (h : x.size ≤ S) : FEval S .nil x 1 .nil + | left (x) (h : x.size ≤ S) : FEval S .left x 1 (x.child false) + | right (x) (h : x.size ≤ S) : FEval S .right x 1 (x.child true) + | pair {f g x y z n m} (hf : FEval S f x n y) (hg : FEval S g x m z) + (hb : (DataTree.node y z).size ≤ S) : FEval S (.pair f g) x (n + m + 1) (.node y z) + | seq {f g x y z n m} (hf : FEval S f x n y) (hg : FEval S g y m z) : + FEval S (.seq f g) x (n + m + 1) z + | nil_branch {f g y n} (hf : FEval S f .nil n y) : FEval S (.branch f g) .nil (n + 1) y + | node_branch {f g x y n} (hx : x ≠ .nil) (hg : FEval S g x n y) : + FEval S (.branch f g) x (n + 1) y + | nil_cond {p f g x y n m} (hp : FEval S p x n .nil) (hf : FEval S f x m y) : + FEval S (.cond p f g) x (n + m + 1) y + | node_cond {p f g x y z n m} (hp : FEval S p x n z) (hz : z ≠ .nil) + (hg : FEval S g x m y) : FEval S (.cond p f g) x (n + m + 1) y + | loop_stop (f x) (hx : x.size ≤ S) (he : x.child false = .nil) : + FEval S (.loop f) x 1 x + | loop_next {f x y z n m} (he : x.child false ≠ .nil) (h : FEval S f x n y) + (tail : FEval S (.loop f) y m z) : FEval S (.loop f) x (n + m + 1) z + +lemma FEval.bounds {S : ℕ} {f : FCode} {x y : DataTree} {n : ℕ} (h : FEval S f x n y) : + x.size ≤ S ∧ y.size ≤ S ∧ 0 < n := by + induction h using FEval.rec with + | id x h => exact ⟨h, h, by omega⟩ + | nil x h => exact ⟨h, by have := x.size_pos; simp [DataTree.size]; omega, by omega⟩ + | left x h => exact ⟨h, (x.size_child false).trans h, by omega⟩ + | right x h => exact ⟨h, (x.size_child true).trans h, by omega⟩ + | pair _ _ hb ih₁ ih₂ => exact ⟨ih₁.1, hb, by omega⟩ + | seq _ _ ih₁ ih₂ => exact ⟨ih₁.1, ih₂.2.1, by omega⟩ + | nil_branch _ ih => exact ⟨ih.1, ih.2.1, by omega⟩ + | node_branch _ _ ih => exact ⟨ih.1, ih.2.1, by omega⟩ + | nil_cond _ _ ip hf => exact ⟨ip.1, hf.2.1, by omega⟩ + | node_cond _ _ _ ip hg => exact ⟨ip.1, hg.2.1, by omega⟩ + | loop_stop f x hx he => exact ⟨hx, hx, by omega⟩ + | loop_next he _ _ ih₁ ih₂ => exact ⟨ih₁.1, ih₂.2.1, by omega⟩ + +lemma FEval.loop_iff {S : ℕ} {f : FCode} {x y : DataTree} {n : ℕ} : + FEval S (.loop f) x n y ↔ FWhile S (FEval S f) x n y := by + constructor + · intro h + induction n using Nat.strong_induction_on generalizing x y with + | h n ih => + cases h with + | loop_stop _ x hx he => exact .stop x hx he + | loop_next he hb ht => exact .next he hb (ih _ (by omega) ht) + · intro h + induction h with + | stop x hx he => exact .loop_stop f x hx he + | next he h _ ih => exact .loop_next he h ih + +def FCode.depth : FCode → ℕ + | .id | .nil | .left | .right => 1 + | .pair f g => max (f.depth + 1) (g.depth + 2) + | .seq f g | .branch f g => max f.depth g.depth + | .cond p f g => max (p.depth + 1) (max f.depth g.depth) + | .loop f => max f.depth 2 + +lemma FCode.depth_pos (f : FCode) : 0 < f.depth := by + induction f <;> simp_all [FCode.depth] + +def FCode.lower {r : ℕ} (f : FCode) (i : Fin r) (h : i.val + f.depth ≤ r) : TreeCode r := + match f with + | .id => .skip + | .nil => .op (.nil i) + | .left => .op (.project i i false) + | .right => .op (.project i i true) + | .pair f g => + let j : Fin r := ⟨i.val + 1, by have := g.depth_pos; simp only [FCode.depth] at h; omega⟩ + let k : Fin r := ⟨i.val + 2, by have := g.depth_pos; simp only [FCode.depth] at h; omega⟩ + .seq (.copy j i) (.seq (f.lower j (by simp only [FCode.depth] at h; dsimp [j]; omega)) + (.seq (.copy k i) (.seq (g.lower k (by simp only [FCode.depth] at h; dsimp [k]; omega)) + (.seq (.op (.node i j k)) (.seq (.op (.nil j)) (.op (.nil k))))))) + | .seq f g => .seq (f.lower i (by simp only [FCode.depth] at h; omega)) + (g.lower i (by simp only [FCode.depth] at h; omega)) + | .branch f g => .cond i (f.lower i (by simp only [FCode.depth] at h; omega)) + (g.lower i (by simp only [FCode.depth] at h; omega)) + | .cond p f g => + let j : Fin r := ⟨i.val + 1, by have := p.depth_pos; simp only [FCode.depth] at h; omega⟩ + .seq (.copy j i) (.seq (p.lower j (by dsimp [j]; simp only [FCode.depth] at h; omega)) + (.cond j (.seq (.op (.nil j)) (f.lower i (by simp only [FCode.depth] at h; omega))) + (.seq (.op (.nil j)) (g.lower i (by simp only [FCode.depth] at h; omega))))) + | .loop f => + let j : Fin r := ⟨i.val + 1, by simp only [FCode.depth] at h; omega⟩ + let body := .seq (.op (.nil j)) + (.seq (f.lower i (by simp only [FCode.depth] at h; omega)) (.op (.project j i false))) + .seq (.op (.project j i false)) (.seq (.loop j body) (.op (.nil j))) + +def FCode.factor : FCode → ℕ + | .id | .nil | .left | .right => 2 + | .pair f g => f.factor + g.factor + 30 + | .seq f g | .branch f g => f.factor + g.factor + 1 + | .cond p f g => p.factor + f.factor + g.factor + 20 + | .loop f => f.factor + 20 + +lemma FCode.factor_pos (f : FCode) : 0 < f.factor := by cases f <;> simp [FCode.factor] + +def CleanAbove {r : ℕ} (d : Fin r → DataTree) (i : Fin r) : Prop := + ∀ j, i.val < j.val → d j = .nil + +lemma CleanAbove.update_self {r : ℕ} {d : Fin r → DataTree} {i : Fin r} + (h : CleanAbove d i) (x : DataTree) : CleanAbove (Function.update d i x) i := by + intro j hj + have hn : j ≠ i := by intro h; subst j; omega + simp [hn, h j hj] + +lemma CleanAbove.update_later {r : ℕ} {d : Fin r → DataTree} {i j : Fin r} + (h : CleanAbove d i) (hj : i.val < j.val) (x : DataTree) : + CleanAbove (Function.update d j x) j := by + intro k hk + have hn : k ≠ j := by intro h; subst k; omega + simp [hn, h k (by omega)] + +lemma CleanAbove.erase_next {r : ℕ} {d : Fin r → DataTree} {i j : Fin r} + (h : CleanAbove d j) (hj : j.val = i.val + 1) : + CleanAbove (Function.update d j .nil) i := by + intro k hk + by_cases he : k = j + · subst k; simp + · have hn : j.val < k.val := by have := Fin.val_ne_of_ne he; omega + simp [he, h k hn] + +end ParityWL.Complexity + +end OAI diff --git a/lean/OAI/Combinatorics/ParityLifts/FunctionalCompile.lean b/lean/OAI/Combinatorics/ParityLifts/FunctionalCompile.lean new file mode 100644 index 0000000000000000000000000000000000000000..90ec46cc18f2661593ee77bf44b125893db07fe1 --- /dev/null +++ b/lean/OAI/Combinatorics/ParityLifts/FunctionalCompile.lean @@ -0,0 +1,356 @@ +import OAI.Combinatorics.ParityLifts.FunctionalCode + +namespace OAI + +namespace ParityWL.Complexity + +lemma FWhile.lower {S r : ℕ} {f : FCode} (i j : Fin r) (hj : j.val = i.val + 1) + (hf : i.val + f.depth ≤ r) + (realize : ∀ {x y n}, FEval S f x n y → ∀ (d : Fin r → DataTree), + d i = x → CleanAbove d i → DataBound d (2 * S + 1) → + ∃ m, m ≤ f.factor * n ∧ + BCodeExec (2 * S + 1) (f.lower i hf) d m (Function.update d i y)) + {x y n} (h : FWhile S (FEval S f) x n y) (d : Fin r → DataTree) + (hdi : d i = x) (hc : CleanAbove d i) (hd : DataBound d (2 * S + 1)) : + ∃ m, m ≤ (f.factor + 10) * n ∧ + BCodeExec (2 * S + 1) + (.loop j (.seq (.op (.nil j)) (.seq (f.lower i hf) (.op (.project j i false))))) + (Function.update d j (x.child false)) m (Function.update d i y) := by + have hji : j ≠ i := by intro he; subst j; omega + have hnil : d j = .nil := hc j (by omega) + induction h generalizing d with + | stop x hx he => + have h₁ : Function.update d j (x.child false) = d := by rw [he, ← hnil]; exact Function.update_eq_self j d + have h₂ : Function.update d i x = d := by rw [← hdi]; exact Function.update_eq_self i d + refine ⟨1, by omega, ?_⟩ + rw [h₁, h₂] + exact .nil_loop hnil hd + | @next x y z n m he hb ht ih => + let a := Function.update d j (x.child false) + have ha : DataBound a (2 * S + 1) := hd.update j _ + ((x.size_child false).trans (by have := hb.bounds.1; omega)) + have h₁ : BCodeExec (2 * S + 1) (.op (.nil j)) a 2 d := by + simpa [a, ← hnil] using BCodeExec.nil j a ha + obtain ⟨u, hu, hfRun⟩ := realize hb d hdi hc hd + have hc' : CleanAbove (Function.update d i y) i := hc.update_self y + have h₃ := BCodeExec.project j i false _ hfRun.end_bound + have hh : BCodeExec (2 * S + 1) + (.seq (.op (.nil j)) (.seq (f.lower i hf) (.op (.project j i false)))) + a (u + 6) (Function.update (Function.update d i y) j (y.child false)) := by + convert h₁.seq (hfRun.seq h₃) using 1 <;> simp + omega + obtain ⟨v, hv, hl⟩ := ih (Function.update d i y) (by simp) hc' hfRun.end_bound + (by simp [hji, hnil]) + have hres := BCodeExec.node_loop (i := j) (by simpa [a] using he) hh hl + refine ⟨u + 6 + v + 3, ?_, ?_⟩ + · nlinarith + · simpa using hres + +lemma FEval.lower {S : ℕ} {f : FCode} {x y : DataTree} {n : ℕ} + (h : FEval S f x n y) {r : ℕ} (i : Fin r) (hi : i.val + f.depth ≤ r) + (d : Fin r → DataTree) (hdi : d i = x) (hc : CleanAbove d i) + (hd : DataBound d (2 * S + 1)) : + ∃ m, m ≤ f.factor * n ∧ + BCodeExec (2 * S + 1) (f.lower i hi) d m (Function.update d i y) := by + induction f generalizing r i S d x y n with + | id => + cases h with + | id x hx => + refine ⟨0, by simp, ?_⟩ + simpa [FCode.lower, ← hdi] using BCodeExec.skip d hd + | nil => + cases h with + | nil x hx => exact ⟨2, by simp [FCode.factor], BCodeExec.nil i d hd⟩ + | left => + cases h with + | left x hx => + refine ⟨2, by simp [FCode.factor], ?_⟩ + simpa [FCode.lower, hdi] using BCodeExec.project i i false d hd + | right => + cases h with + | right x hx => + refine ⟨2, by simp [FCode.factor], ?_⟩ + simpa [FCode.lower, hdi] using BCodeExec.project i i true d hd + | pair f g ihf ihg => + cases h with + | @pair _ _ _ y z n m hhf hhg hsz => + have hjr : i.val + 1 < r := by have := g.depth_pos; simp only [FCode.depth] at hi; omega + have hkr : i.val + 2 < r := by have := g.depth_pos; simp only [FCode.depth] at hi; omega + let j : Fin r := ⟨i.val + 1, hjr⟩ + let k : Fin r := ⟨i.val + 2, hkr⟩ + have hji : j ≠ i := by intro hh; have := congrArg Fin.val hh; dsimp [j] at this; omega + have hki : k ≠ i := by intro hh; have := congrArg Fin.val hh; dsimp [k] at this; omega + have hkj : k ≠ j := by intro hh; have := congrArg Fin.val hh; dsimp [j, k] at this; omega + have hnj : d j = .nil := hc j (by dsimp [j]; omega) + have hnk : d k = .nil := hc k (by dsimp [k]; omega) + let d₁ := Function.update d j x + have h₁ : BCodeExec (2 * S + 1) (.copy j i) d 5 d₁ := by + simpa [d₁, hdi] using BCodeExec.copy j i d hd (hdi ▸ hhf.bounds.1) + have hc₁ : CleanAbove d₁ j := hc.update_later (by dsimp [j]; omega) x + have hfj : j.val + f.depth ≤ r := by dsimp [j]; simp only [FCode.depth] at hi; omega + obtain ⟨a, ha, h₂⟩ := ihf hhf j hfj d₁ (by simp [d₁]) hc₁ h₁.end_bound + let d₂ := Function.update d j y + have h₂' : BCodeExec (2 * S + 1) (f.lower j hfj) d₁ a d₂ := by + simpa [d₁, d₂] using h₂ + let d₃ := Function.update d₂ k x + have h₃ : BCodeExec (2 * S + 1) (.copy k i) d₂ 5 d₃ := by + have hd₂i : d₂ i = x := by simp [d₂, Ne.symm hji, hdi] + simpa [d₃, hd₂i] using BCodeExec.copy k i d₂ h₂'.end_bound (hd₂i ▸ hhg.bounds.1) + have hc₂ : CleanAbove d₂ j := hc.update_later (by dsimp [j]; omega) y + have hc₃ : CleanAbove d₃ k := hc₂.update_later (by dsimp [j, k]; omega) x + have hgk : k.val + g.depth ≤ r := by dsimp [k]; simp only [FCode.depth] at hi; omega + obtain ⟨b, hb, h₄⟩ := ihg hhg k hgk d₃ (by simp [d₃]) hc₃ h₃.end_bound + let d₄ := Function.update d₂ k z + have h₄' : BCodeExec (2 * S + 1) (g.lower k hgk) d₃ b d₄ := by + simpa [d₃, d₄] using h₄ + have h₅ := BCodeExec.node i j k d₄ h₄'.end_bound + (by simpa [d₄, d₂, Ne.symm hkj] using (show (DataTree.node y z).size ≤ 2 * S + 1 by omega)) + have h₆ := BCodeExec.nil j _ h₅.end_bound + have h₇ := BCodeExec.nil k _ h₆.end_bound + have hres := h₁.seq (h₂'.seq (h₃.seq (h₄'.seq (h₅.seq (h₆.seq h₇))))) + have he : Function.update (Function.update (Function.update d₄ i (.node (d₄ j) (d₄ k))) j .nil) k .nil = + Function.update d i (.node y z) := by + funext q + by_cases hqk : q = k + · subst q; simp [hki, hnk] + by_cases hqj : q = j + · subst q; simp [Ne.symm hkj, hji, hnj] + by_cases hqi : q = i + · subst q; simp [d₄, d₂, Ne.symm hji, Ne.symm hki, Ne.symm hkj] + · simp [d₄, d₂, hqk, hqj, hqi] + rw [he] at hres + refine ⟨a + b + 22, ?_, ?_⟩ + · simp only [FCode.factor]; nlinarith + · convert hres using 1 <;> first | rfl | omega + | seq f g ihf ihg => + cases h with + | seq hf hg => + have hfi : i.val + f.depth ≤ r := by simp only [FCode.depth] at hi; omega + have hgi : i.val + g.depth ≤ r := by simp only [FCode.depth] at hi; omega + obtain ⟨a, ha, h₁⟩ := ihf hf i hfi d hdi hc hd + obtain ⟨b, hb, h₂⟩ := ihg hg i hgi _ (by simp) (hc.update_self _) h₁.end_bound + refine ⟨a + 1 + b, ?_, ?_⟩ + · simp only [FCode.factor]; nlinarith + · simpa [FCode.lower] using h₁.seq h₂ + | branch f g ihf ihg => + have hfi : i.val + f.depth ≤ r := by simp only [FCode.depth] at hi; omega + have hgi : i.val + g.depth ≤ r := by simp only [FCode.depth] at hi; omega + cases h with + | nil_branch hf => + obtain ⟨a, ha, h₁⟩ := ihf hf i hfi d hdi hc hd + exact ⟨a + 1, by simp only [FCode.factor]; nlinarith, h₁.nil_cond hdi⟩ + | node_branch hx hg => + obtain ⟨b, hb, h₂⟩ := ihg hg i hgi d hdi hc hd + exact ⟨b + 1, by simp only [FCode.factor]; nlinarith, h₂.node_cond (by simpa [hdi] using hx)⟩ + | cond p f g ihp ihf ihg => + have hjr : i.val + 1 < r := by have := p.depth_pos; simp only [FCode.depth] at hi; omega + let j : Fin r := ⟨i.val + 1, hjr⟩ + have hji : j ≠ i := by intro hh; have := congrArg Fin.val hh; dsimp [j] at this; omega + have hnj : d j = .nil := hc j (by dsimp [j]; omega) + have hpj : j.val + p.depth ≤ r := by dsimp [j]; simp only [FCode.depth] at hi; omega + have hfi : i.val + f.depth ≤ r := by simp only [FCode.depth] at hi; omega + have hgi : i.val + g.depth ≤ r := by simp only [FCode.depth] at hi; omega + cases h with + | nil_cond hp hf => + have h₁ : BCodeExec (2 * S + 1) (.copy j i) d 5 (Function.update d j x) := by + simpa [hdi] using BCodeExec.copy j i d hd (hdi ▸ hp.bounds.1) + obtain ⟨a, ha, h₂⟩ := ihp hp j hpj _ (by simp) + (hc.update_later (by dsimp [j]; omega) x) h₁.end_bound + have h₂' : BCodeExec (2 * S + 1) (p.lower j hpj) (Function.update d j x) a d := by + simpa [← hnj] using h₂ + have h₃ : BCodeExec (2 * S + 1) (.op (.nil j)) d 2 d := by + simpa [← hnj] using BCodeExec.nil j d hd + obtain ⟨b, hb, h₄⟩ := ihf hf i hfi d hdi hc hd + have hres := h₁.seq (h₂'.seq ((h₃.seq h₄).nil_cond (q := .seq (.op (.nil j)) (g.lower i hgi)) hnj)) + refine ⟨a + b + 11, ?_, ?_⟩ + · simp only [FCode.factor]; nlinarith + · convert hres using 1 <;> first | rfl | omega + | @node_cond _ _ _ _ _ z n m hp hz hg => + have h₁ : BCodeExec (2 * S + 1) (.copy j i) d 5 (Function.update d j x) := by + simpa [hdi] using BCodeExec.copy j i d hd (hdi ▸ hp.bounds.1) + obtain ⟨a, ha, h₂⟩ := ihp hp j hpj _ (by simp) + (hc.update_later (by dsimp [j]; omega) x) h₁.end_bound + have h₂' : BCodeExec (2 * S + 1) (p.lower j hpj) (Function.update d j x) a + (Function.update d j z) := by simpa using h₂ + have h₃ : BCodeExec (2 * S + 1) (.op (.nil j)) (Function.update d j z) 2 d := by + simpa [← hnj] using BCodeExec.nil j _ h₂'.end_bound + obtain ⟨b, hb, h₄⟩ := ihg hg i hgi d hdi hc hd + have hres := h₁.seq (h₂'.seq ((h₃.seq h₄).node_cond (i := j) + (p := .seq (.op (.nil j)) (f.lower i hfi)) (by simpa using hz))) + refine ⟨a + b + 11, ?_, ?_⟩ + · simp only [FCode.factor]; nlinarith + · convert hres using 1 <;> first | rfl | omega + | loop f ih => + have hfi : i.val + f.depth ≤ r := by simp only [FCode.depth] at hi; omega + let j : Fin r := ⟨i.val + 1, by simp only [FCode.depth] at hi; omega⟩ + have hji : j ≠ i := by intro hh; have := congrArg Fin.val hh; dsimp [j] at this; omega + have hnj : d j = .nil := hc j (by dsimp [j]; omega) + obtain ⟨a, ha, hr⟩ := FWhile.lower i j rfl hfi (fun hh dd hdi hc hd => ih hh i hfi dd hdi hc hd) + (FEval.loop_iff.mp h) d hdi hc hd + have h₁ := BCodeExec.project j i false d hd + simp only [hdi] at h₁ + have h₂ := BCodeExec.nil j _ hr.end_bound + have he : Function.update (Function.update d i y) j .nil = Function.update d i y := by + have hn : Function.update d i y j = .nil := by simp [hji, hnj] + rw [← hn] + exact Function.update_eq_self j _ + have hres := h₁.seq (hr.seq h₂) + simp only [he] at hres + refine ⟨a + 6, ?_, ?_⟩ + · have := h.bounds.2.2; simp only [FCode.factor]; nlinarith + · convert hres using 1 <;> first | rfl | omega + +end ParityWL.Complexity + +namespace ParityWL.Complexity + +noncomputable def FCode.decision (p : FCode) : Machine := + let i : Fin (p.depth + 1) := 0 + let P := (p.lower i (by simp [i])).compile.program + (P.andThen (TreeMachine.branch i (.halt false) (.halt true))).compiled + +lemma FEval.decision {S n : ℕ} {p : FCode} {bs : List Bool} {y : DataTree} + (h : FEval S p (DataTree.ofBits bs) n y) : + ∃ s, s ≤ 102 * (p.factor * n + 2) * ((p.depth + 1) * (2 * S + 1) + 1) + + 44 * bs.length + 20 ∧ Emits p.decision bs s (decide (y ≠ .nil)) := by + let d := inputData p.depth bs + let i : Fin (p.depth + 1) := 0 + have hdi : d i = DataTree.ofBits bs := by simp [d, i, inputData] + have hd : DataBound d (2 * S + 1) := by + intro j + by_cases hj : j = 0 + · subst j; simp [d, inputData]; have := h.bounds.1; omega + · simp [d, inputData, hj, DataTree.size] + have hc : CleanAbove d i := by + intro j hj + have hn : j ≠ 0 := by intro hh; subst j; dsimp [i] at hj; omega + simp [d, inputData, hn] + obtain ⟨m, hm, hr⟩ := h.lower i (by simp [i]) d hdi hc hd + let decider := TreeMachine.branch i (TreeMachine.halt (r := p.depth + 1) false) (.halt true) + have he : BoundedRuns decider (2 * S + 1) (Function.update d i y) 1 + (Function.update d i y) (decide (y ≠ .nil)) := by + by_cases hy : y = .nil + · subst y + simpa [decider] using (boundedHalt false _ hr.end_bound).branch_true i + (.halt false) (.halt true) (by simp) + · simpa [decider, hy] using (boundedHalt true _ hr.end_bound).branch_false i + (.halt false) (.halt true) (by simpa using hy) + have run := hr.compile.andThen he + obtain ⟨s, hs, hem⟩ := run.compiled + refine ⟨s, ?_, hem⟩ + have hmul : 102 * (m + 1 + 1) * ((p.depth + 1) * (2 * S + 1) + 1) ≤ + 102 * (p.factor * n + 2) * ((p.depth + 1) * (2 * S + 1) + 1) := by + exact Nat.mul_le_mul_right _ (Nat.mul_le_mul_left _ (by omega)) + omega + +end ParityWL.Complexity + +namespace ParityWL.Complexity + +lemma FEval.mono {S T : ℕ} (hST : S ≤ T) {p : FCode} {x y : DataTree} {n : ℕ} + (h : FEval S p x n y) : FEval T p x n y := by + induction h with + | id x hx => exact .id x (hx.trans hST) + | nil x hx => exact .nil x (hx.trans hST) + | left x hx => exact .left x (hx.trans hST) + | right x hx => exact .right x (hx.trans hST) + | pair _ _ hb hf hg => exact .pair hf hg (hb.trans hST) + | seq _ _ hf hg => exact .seq hf hg + | nil_branch _ hf => exact .nil_branch hf + | node_branch hx _ hg => exact .node_branch hx hg + | nil_cond _ _ hp hf => exact .nil_cond hp hf + | node_cond _ hz _ hp hg => exact .node_cond hp hz hg + | loop_stop f x hx he => exact .loop_stop f x (hx.trans hST) he + | loop_next he _ _ hf ht => exact .loop_next he hf ht + +/-- One common budget bounds both the number of functional instructions and +every intermediate serialized value. The compiler uses a universal quadratic +power, independent of the finite program's syntax. -/ +def BEval (p : FCode) (x : DataTree) (B : ℕ) (y : DataTree) : Prop := + ∃ n, n ≤ B ∧ FEval B p x n y + +lemma BEval.mono {p : FCode} {x y : DataTree} {B C : ℕ} (hBC : B ≤ C) + (h : BEval p x B y) : BEval p x C y := by + obtain ⟨n, hn, he⟩ := h + exact ⟨n, hn.trans hBC, he.mono hBC⟩ + +lemma BEval.bounds {p : FCode} {x y : DataTree} {B : ℕ} (h : BEval p x B y) : + x.size ≤ B ∧ y.size ≤ B ∧ 0 < B := by + obtain ⟨n, hn, he⟩ := h + have hh := he.bounds + exact ⟨hh.1, hh.2.1, by omega⟩ + +lemma BEval.id (x : DataTree) : BEval .id x x.size x := + ⟨1, x.size_pos, .id x le_rfl⟩ +lemma BEval.nil (x : DataTree) : BEval .nil x x.size .nil := + ⟨1, x.size_pos, .nil x le_rfl⟩ +lemma BEval.left (x : DataTree) : BEval .left x x.size (x.child false) := + ⟨1, x.size_pos, .left x le_rfl⟩ +lemma BEval.right (x : DataTree) : BEval .right x x.size (x.child true) := + ⟨1, x.size_pos, .right x le_rfl⟩ + +lemma BEval.pair {p q : FCode} {x y z : DataTree} {B C : ℕ} + (h : BEval p x B y) (ht : BEval q x C z) : BEval (.pair p q) x (B + C + 1) (.node y z) := by + obtain ⟨n, hn, he⟩ := h + obtain ⟨m, hm, hf⟩ := ht + refine ⟨n + m + 1, by omega, .pair (he.mono (by omega)) (hf.mono (by omega)) ?_⟩ + have := he.bounds.2.1 + have := hf.bounds.2.1 + simp only [DataTree.size]; omega + +lemma BEval.seq {p q : FCode} {x y z : DataTree} {B C : ℕ} + (h : BEval p x B y) (ht : BEval q y C z) : BEval (.seq p q) x (B + C + 1) z := by + obtain ⟨n, hn, he⟩ := h + obtain ⟨m, hm, hf⟩ := ht + exact ⟨n + m + 1, by omega, .seq (he.mono (by omega)) (hf.mono (by omega))⟩ + +lemma BEval.nil_branch {p q : FCode} {y : DataTree} {B : ℕ} + (h : BEval p .nil B y) : BEval (.branch p q) .nil (B + 1) y := by + obtain ⟨n, hn, he⟩ := h + exact ⟨n + 1, by omega, .nil_branch (he.mono (by omega))⟩ + +lemma BEval.node_branch {p q : FCode} {x y : DataTree} {B : ℕ} + (hx : x ≠ .nil) (h : BEval q x B y) : BEval (.branch p q) x (B + 1) y := by + obtain ⟨n, hn, he⟩ := h + exact ⟨n + 1, by omega, .node_branch hx (he.mono (by omega))⟩ + +lemma BEval.nil_cond {p f g : FCode} {x y : DataTree} {B C : ℕ} + (hp : BEval p x B .nil) (hf : BEval f x C y) : BEval (.cond p f g) x (B + C + 1) y := by + obtain ⟨n, hn, he⟩ := hp + obtain ⟨m, hm, ht⟩ := hf + exact ⟨n + m + 1, by omega, .nil_cond (he.mono (by omega)) (ht.mono (by omega))⟩ + +lemma BEval.node_cond {p f g : FCode} {x y z : DataTree} {B C : ℕ} + (hp : BEval p x B z) (hz : z ≠ .nil) (hg : BEval g x C y) : + BEval (.cond p f g) x (B + C + 1) y := by + obtain ⟨n, hn, he⟩ := hp + obtain ⟨m, hm, ht⟩ := hg + exact ⟨n + m + 1, by omega, .node_cond (he.mono (by omega)) hz (ht.mono (by omega))⟩ + +lemma BEval.loop_stop (p : FCode) (x : DataTree) (he : x.child false = .nil) : + BEval (.loop p) x x.size x := ⟨1, x.size_pos, .loop_stop p x le_rfl he⟩ + +lemma BEval.loop_next {p : FCode} {x y z : DataTree} {B C : ℕ} + (hx : x.child false ≠ .nil) (h : BEval p x B y) (ht : BEval (.loop p) y C z) : + BEval (.loop p) x (B + C + 1) z := by + obtain ⟨n, hn, he⟩ := h + obtain ⟨m, hm, hf⟩ := ht + exact ⟨n + m + 1, by omega, .loop_next hx (he.mono (by omega)) (hf.mono (by omega))⟩ + +lemma BEval.decision {p : FCode} {bs : List Bool} {y : DataTree} {B : ℕ} + (h : BEval p (DataTree.ofBits bs) B y) : + ∃ s, s ≤ 500 * (p.factor + 2) * (p.depth + 2) * (B + 1) ^ 2 + + 44 * bs.length + 20 ∧ Emits p.decision bs s (decide (y ≠ .nil)) := by + obtain ⟨n, hn, he⟩ := h + obtain ⟨s, hs, hr⟩ := he.decision + refine ⟨s, hs.trans ?_, hr⟩ + have h₁ : p.factor * n + 2 ≤ (p.factor + 2) * (B + 1) := by nlinarith + have h₂ : (p.depth + 1) * (2 * B + 1) + 1 ≤ 3 * (p.depth + 2) * (B + 1) := by nlinarith + calc + _ ≤ 102 * ((p.factor + 2) * (B + 1)) * (3 * (p.depth + 2) * (B + 1)) + + 44 * bs.length + 20 := by gcongr + _ ≤ _ := by nlinarith [Nat.zero_le ((p.factor + 2) * (p.depth + 2) * (B + 1) ^ 2)] + +end ParityWL.Complexity + +end OAI diff --git a/lean/OAI/Combinatorics/ParityLifts/GlueTrees.lean b/lean/OAI/Combinatorics/ParityLifts/GlueTrees.lean new file mode 100644 index 0000000000000000000000000000000000000000..350b7530bacb686846a54aea48329bc65797c8af --- /dev/null +++ b/lean/OAI/Combinatorics/ParityLifts/GlueTrees.lean @@ -0,0 +1,119 @@ +import OAI.Combinatorics.ParityLifts.RootedTests + +namespace OAI + +namespace ParityWL + +open scoped BigOperators + +section GlueTrees + +open scoped Classical + +variable {I : Type} {r : I → ℕ} {t : ℕ} (F : (i : I) → RootedTest (r i) t) + +abbrev GlueNode := Option ((i : I) × {n : (F i).Node // n ≠ (F i).tree.root}) + +noncomputable def glueNodeMap (i : I) (n : (F i).Node) : GlueNode F := + if h : n = (F i).tree.root then none else some ⟨i, ⟨n, h⟩⟩ + +noncomputable def glueNodeParent : GlueNode F → GlueNode F + | none => none + | some ⟨i, n⟩ => glueNodeMap F i ((F i).tree.parent n) + +noncomputable def glueNodeRank : GlueNode F → ℕ + | none => 0 + | some ⟨i, n⟩ => (F i).tree.rank n + 1 + +noncomputable def glueTree : RankedTree (GlueNode F) where + root := none + parent := glueNodeParent F + rank := glueNodeRank F + parent_lt := by + intro n hn + cases n with + | none => exact (hn rfl).elim + | some q => + rcases q with ⟨i, n⟩ + simp only [glueNodeParent, glueNodeMap] + split_ifs + · simp only [glueNodeRank]; omega + · simpa only [glueNodeRank, Nat.add_lt_add_iff_right] using + (F i).tree.parent_lt n.1 n.2 + +lemma glueNodeMap_root (i : I) : glueNodeMap F i (F i).tree.root = none := by + simp [glueNodeMap] + +lemma glueNodeMap_nonroot (i : I) (n : (F i).Node) (hn : n ≠ (F i).tree.root) : + glueNodeMap F i n = some ⟨i, ⟨n, hn⟩⟩ := by + simp only [glueNodeMap, dite_eq_right hn] + +lemma glueTree_map_ancestor (i : I) {a b : (F i).Node} + (h : (F i).tree.toRankedTree.Ancestor a b) : + (glueTree F).Ancestor (glueNodeMap F i a) (glueNodeMap F i b) := by + apply RankedTree.Ancestor.map _ (glueTree F) (glueNodeMap F i) _ h + intro j hj + rw [glueNodeMap_nonroot F i j hj] + apply RankedTree.Ancestor.step (by simp [glueTree]) + exact .refl + +lemma glueTree_ancestor_from_some {i : I} + {a : {n : (F i).Node // n ≠ (F i).tree.root}} {n : GlueNode F} + (h : (glueTree F).Ancestor (some ⟨i, a⟩) n) : + ∃ b : {n : (F i).Node // n ≠ (F i).tree.root}, n = some ⟨i, b⟩ ∧ + (F i).tree.toRankedTree.Ancestor a.1 b.1 := by + induction h with + | refl => exact ⟨a, rfl, .refl⟩ + | @step n hn h ih => + cases n with + | none => exact (hn rfl).elim + | some q => + rcases q with ⟨j, b⟩ + obtain ⟨c, hc, hac⟩ := ih + change glueNodeMap F j ((F j).tree.parent b.1) = some ⟨i, c⟩ at hc + by_cases hp : (F j).tree.parent b.1 = (F j).tree.root + · simp only [glueNodeMap, dite_eq_left hp] at hc + cases hc + · rw [glueNodeMap_nonroot F j _ hp] at hc + have hji : j = i := congrArg Sigma.fst (Option.some.inj hc) + subst j + have hb : (F i).tree.parent b.1 = c.1 := by + have he : (⟨(F i).tree.parent b.1, hp⟩ : {n // n ≠ (F i).tree.root}) = c := by + simpa only [Option.some.injEq, Sigma.mk.inj_iff, heq_eq_eq, true_and] using hc + exact congrArg Subtype.val he + exact ⟨b, rfl, .step b.2 (by rwa [hb])⟩ + +lemma glueTree_ancestor_nonroot {i : I} + {a b : {n : (F i).Node // n ≠ (F i).tree.root}} + (h : (glueTree F).Ancestor (some ⟨i, a⟩) (some ⟨i, b⟩)) : + (F i).tree.toRankedTree.Ancestor a.1 b.1 := by + obtain ⟨c, hc, hac⟩ := glueTree_ancestor_from_some F h + have he : b = c := by + simpa only [Option.some.injEq, Sigma.mk.inj_iff, heq_eq_eq, true_and] using hc + rwa [he] + +lemma RankedTree.ancestor_root_eq {N : Type} (D : RankedTree N) {i : N} + (h : D.Ancestor i D.root) : i = D.root := by + rcases h.cases' D with he | ⟨hne, _⟩ + · exact he + · exact (hne rfl).elim + +lemma rooted_top_eq_root (i : I) {a : (F i).Vertex} + (ha : ∃ j, (F i).roots j = a) : (F i).tree.top a = (F i).tree.root := by + apply RankedTree.ancestor_root_eq + apply (F i).tree.top_ancestor + rw [(F i).root_bag] + simpa only [Finset.mem_image, Finset.mem_univ, true_and] using ha + +lemma rooted_mem_ancestor (i : I) {a : (F i).Vertex} {n m : (F i).Node} + (ha : ∃ j, (F i).roots j = a) (hn : (F i).tree.toRankedTree.Ancestor n m) + (ham : a ∈ (F i).tree.bag m) : a ∈ (F i).tree.bag n := by + apply (F i).tree.interval_mem a n m _ hn ham + rw [rooted_top_eq_root F i ha] + exact (F i).tree.toRankedTree.root_ancestor n + +end GlueTrees + +end ParityWL + +end OAI diff --git a/lean/OAI/Combinatorics/ParityLifts/GlueVertices.lean b/lean/OAI/Combinatorics/ParityLifts/GlueVertices.lean new file mode 100644 index 0000000000000000000000000000000000000000..2dfc61d426d4d082f140455150692faae8f2885e --- /dev/null +++ b/lean/OAI/Combinatorics/ParityLifts/GlueVertices.lean @@ -0,0 +1,325 @@ +import OAI.Combinatorics.ParityLifts.GlueTrees + +namespace OAI + +namespace ParityWL + +open scoped BigOperators + +section GlueVertices + +open scoped Classical + +variable {I : Type} {r : I → ℕ} {t m : ℕ} +variable (F : (i : I) → RootedTest (r i) t) (η : (i : I) → Fin (r i) → Fin m) + +def GlueRootRel (a b : Fin m) : Prop := + ∃ i j l, a = η i j ∧ b = η i l ∧ (F i).roots j = (F i).roots l + +def GlueRoot := Quot (GlueRootRel F η) + +noncomputable instance glueRootFintype : Fintype (GlueRoot F η) := + Fintype.ofSurjective (Quot.mk (GlueRootRel F η)) + (fun q => Quot.inductionOn q (fun a => ⟨a, rfl⟩)) + +abbrev GlueInternal (i : I) := {a : (F i).Vertex // ¬ ∃ j, (F i).roots j = a} + +abbrev GlueVertex := GlueRoot F η ⊕ ((i : I) × GlueInternal F i) + +noncomputable local instance : DecidableEq (GlueVertex F η) := Classical.decEq _ + +noncomputable def glueRoot (j : Fin m) : GlueVertex F η := .inl (Quot.mk _ j) + +noncomputable def glueMap (i : I) (a : (F i).Vertex) : GlueVertex F η := + if h : ∃ j, (F i).roots j = a then + .inl (Quot.mk _ (η i h.choose)) else .inr ⟨i, ⟨a, h⟩⟩ + +lemma glueMap_root (i : I) (j : Fin (r i)) : + glueMap F η i ((F i).roots j) = glueRoot F η (η i j) := by + unfold glueMap glueRoot + split_ifs with h + · apply congrArg Sum.inl + apply Quot.sound + exact ⟨i, h.choose, j, rfl, rfl, h.choose_spec⟩ + · exact (h ⟨j, rfl⟩).elim + +lemma glueMap_internal (i : I) (a : GlueInternal F i) : + glueMap F η i a = .inr ⟨i, a⟩ := by + simp only [glueMap, dite_eq_right a.2] + +lemma glueMap_eq_inl (i : I) (a : (F i).Vertex) (q : GlueRoot F η) + (h : glueMap F η i a = .inl q) : ∃ j, (F i).roots j = a := by + by_contra hn + simp only [glueMap, dite_eq_right hn] at h + cases h + +lemma glueMap_eq_internal (i j : I) (a : (F i).Vertex) (b : GlueInternal F j) + (h : glueMap F η i a = .inr ⟨j, b⟩) : + ∃ e : i = j, e ▸ a = b.1 := by + by_cases ha : ∃ j, (F i).roots j = a + · simp only [glueMap, dite_eq_left ha] at h + cases h + · simp only [glueMap, dite_eq_right ha] at h + have he := Sum.inr.inj h + have hij : i = j := congrArg Sigma.fst he + subst i + refine ⟨rfl, ?_⟩ + have hab : (⟨a, ha⟩ : GlueInternal F j) = b := by + simpa only [Sigma.mk.inj_iff, heq_eq_eq, true_and] using he + exact congrArg Subtype.val hab + +noncomputable def glueBag : GlueNode F → Finset (GlueVertex F η) + | none => Finset.univ.image (glueRoot F η) + | some ⟨i, n⟩ => ((F i).tree.bag n).image (glueMap F η i) + +lemma glueBag_root_mem (q : GlueRoot F η) : + Sum.inl q ∈ glueBag F η none := by + induction q using Quot.inductionOn with + | h j => exact Finset.mem_image.mpr ⟨j, Finset.mem_univ _, rfl⟩ + +lemma glueMap_mem_bag (i : I) (n : (F i).Node) {a : (F i).Vertex} + (ha : a ∈ (F i).tree.bag n) : + glueMap F η i a ∈ glueBag F η (glueNodeMap F i n) := by + by_cases hn : n = (F i).tree.root + · subst n + rw [(F i).root_bag] at ha + obtain ⟨j, _, rfl⟩ := Finset.mem_image.mp ha + rw [glueNodeMap_root, glueMap_root] + exact glueBag_root_mem F η _ + · rw [glueNodeMap_nonroot F i n hn] + exact Finset.mem_image.mpr ⟨a, ha, rfl⟩ + +lemma glueBag_internal {i : I} (a : GlueInternal F i) (n : GlueNode F) : + Sum.inr ⟨i, a⟩ ∈ glueBag F η n ↔ + ∃ b : {n : (F i).Node // n ≠ (F i).tree.root}, + n = some ⟨i, b⟩ ∧ a.1 ∈ (F i).tree.bag b := by + cases n with + | none => + constructor + · intro h + obtain ⟨j, _, he⟩ := Finset.mem_image.mp h + cases he + · rintro ⟨b, hb, _⟩ + cases hb + | some q => + rcases q with ⟨j, n⟩ + constructor + · intro h + obtain ⟨b, hb, he⟩ := Finset.mem_image.mp h + obtain ⟨hji, hba⟩ := glueMap_eq_internal F η j i b a he + subst j + change b = a.1 at hba + subst b + exact ⟨n, rfl, hb⟩ + · rintro ⟨b, hb, ha⟩ + have hji : j = i := congrArg Sigma.fst (Option.some.inj hb) + subst j + have hnb : n = b := by + simpa only [Option.some.injEq, Sigma.mk.inj_iff, heq_eq_eq, true_and] using hb + subst n + exact Finset.mem_image.mpr ⟨a.1, ha, glueMap_internal F η i a⟩ + +lemma glueBag_root_ancestor (q : GlueRoot F η) {n l : GlueNode F} + (hnl : (glueTree F).Ancestor n l) (hql : Sum.inl q ∈ glueBag F η l) : + Sum.inl q ∈ glueBag F η n := by + cases n with + | none => exact glueBag_root_mem F η q + | some p => + rcases p with ⟨i, n⟩ + obtain ⟨b, rfl, hnb⟩ := glueTree_ancestor_from_some F hnl + obtain ⟨a, hab, he⟩ := Finset.mem_image.mp hql + have har := glueMap_eq_inl F η i a q he + exact Finset.mem_image.mpr ⟨a, rooted_mem_ancestor F i har hnb hab, he⟩ + +lemma glueBag_internal_same {i : I} (a : GlueInternal F i) + (n : {n : (F i).Node // n ≠ (F i).tree.root}) : + Sum.inr ⟨i, a⟩ ∈ glueBag F η (some ⟨i, n⟩) ↔ a.1 ∈ (F i).tree.bag n := by + rw [glueBag_internal] + constructor + · rintro ⟨b, hb, ha⟩ + have hnb : n = b := by + simpa only [Option.some.injEq, Sigma.mk.inj_iff, heq_eq_eq, true_and] using hb + rwa [hnb] + · intro ha + exact ⟨n, rfl, ha⟩ + +lemma internal_top_nonroot (i : I) (a : GlueInternal F i) : + (F i).tree.top a.1 ≠ (F i).tree.root := by + intro he + have ha := (F i).tree.top_mem a.1 + rw [he, (F i).root_bag] at ha + exact a.2 (by simpa only [Finset.mem_image, Finset.mem_univ, true_and] using ha) + +noncomputable def glueTop : GlueVertex F η → GlueNode F + | .inl _ => none + | .inr ⟨i, a⟩ => glueNodeMap F i ((F i).tree.top a) + +lemma glueTop_mem (a : GlueVertex F η) : a ∈ glueBag F η (glueTop F η a) := by + cases a with + | inl q => exact glueBag_root_mem F η q + | inr p => + rcases p with ⟨i, a⟩ + change Sum.inr ⟨i, a⟩ ∈ glueBag F η (glueNodeMap F i ((F i).tree.top a)) + rw [← glueMap_internal F η i a] + exact glueMap_mem_bag F η i _ ((F i).tree.top_mem a) + +lemma glueTop_ancestor (a : GlueVertex F η) (n : GlueNode F) + (ha : a ∈ glueBag F η n) : (glueTree F).Ancestor (glueTop F η a) n := by + cases a with + | inl q => exact (glueTree F).root_ancestor n + | inr p => + rcases p with ⟨i, a⟩ + obtain ⟨b, rfl, hab⟩ := (glueBag_internal F η a n).mp ha + have hh := glueTree_map_ancestor F i ((F i).tree.top_ancestor a.1 b.1 hab) + rwa [glueNodeMap_nonroot F i b.1 b.2] at hh + +lemma glueInterval_mem (a : GlueVertex F η) (n l : GlueNode F) + (hn : (glueTree F).Ancestor (glueTop F η a) n) + (hnl : (glueTree F).Ancestor n l) (ha : a ∈ glueBag F η l) : + a ∈ glueBag F η n := by + cases a with + | inl q => exact glueBag_root_ancestor F η q hnl ha + | inr p => + rcases p with ⟨i, a⟩ + change (glueTree F).Ancestor (glueNodeMap F i ((F i).tree.top a.1)) n at hn + rw [glueNodeMap_nonroot F i _ (internal_top_nonroot F i a)] at hn + obtain ⟨b, rfl, htb⟩ := glueTree_ancestor_from_some F hn + obtain ⟨c, rfl, hbc⟩ := glueTree_ancestor_from_some F hnl + rw [glueBag_internal_same] at ha ⊢ + exact (F i).tree.interval_mem a.1 b.1 c.1 htb hbc ha + +lemma glueIntersection_sub (i : I) (n : {n : (F i).Node // n ≠ (F i).tree.root}) : + glueBag F η (some ⟨i, n⟩) ∩ glueBag F η ((glueTree F).parent (some ⟨i, n⟩)) ⊆ + ((F i).tree.bag n ∩ (F i).tree.bag ((F i).tree.parent n)).image (glueMap F η i) := by + intro a ha + obtain ⟨han, hap⟩ := Finset.mem_inter.mp ha + obtain ⟨b, hbn, rfl⟩ := Finset.mem_image.mp han + refine Finset.mem_image.mpr ⟨b, Finset.mem_inter.mpr ⟨hbn, ?_⟩, rfl⟩ + by_cases hb : ∃ j, (F i).roots j = b + · exact rooted_mem_ancestor F i hb (.step n.2 .refl) hbn + · have he := glueMap_internal F η i ⟨b, hb⟩ + rw [he] at hap + change Sum.inr ⟨i, (⟨b, hb⟩ : GlueInternal F i)⟩ ∈ + glueBag F η (glueNodeMap F i ((F i).tree.parent n)) at hap + by_cases hp : (F i).tree.parent n = (F i).tree.root + · rw [hp, glueNodeMap_root] at hap + obtain ⟨j, _, hj⟩ := Finset.mem_image.mp hap + cases hj + · rw [glueNodeMap_nonroot F i _ hp, glueBag_internal_same] at hap + exact hap + +def glueRelation (a b : GlueVertex F η) : Prop := + ∃ i u v, (F i).relation u v ∧ glueMap F η i u = a ∧ glueMap F η i v = b + +lemma glueRelation_symm : Std.Symm (glueRelation F η) := by + refine ⟨?_⟩ + rintro a b ⟨i, u, v, huv, rfl, rfl⟩ + exact ⟨i, v, u, (F i).symmetric.symm u v huv, rfl, rfl⟩ + +noncomputable def glueBagTree (hm : m ≤ t) : + RankedBagTree (N := GlueNode F) (glueRelation F η) t where + toRankedTree := glueTree F + bag := glueBag F η + top := glueTop F η + top_mem := glueTop_mem F η + top_ancestor := glueTop_ancestor F η + interval_mem := glueInterval_mem F η + edge_cover := by + rintro a b ⟨i, u, v, huv, rfl, rfl⟩ + obtain ⟨n, hun, hvn⟩ := (F i).tree.edge_cover u v huv + exact ⟨glueNodeMap F i n, glueMap_mem_bag F η i n hun, + glueMap_mem_bag F η i n hvn⟩ + width := by + intro n + cases n with + | none => + exact le_trans (Finset.card_image_le) (by simpa only [Finset.card_univ, + Fintype.card_fin] using hm) + | some q => exact le_trans Finset.card_image_le ((F q.1).tree.width q.2) + intersection := by + intro n hn + cases n with + | none => exact (hn rfl).elim + | some q => + rcases q with ⟨i, n⟩ + exact lt_of_le_of_lt ((Finset.card_le_card (glueIntersection_sub F η i n)).trans + Finset.card_image_le) ((F i).tree.intersection n.1 n.2) + +noncomputable def glueTest [Fintype I] (hm : m ≤ t) : RootedTest m t where + Vertex := GlueVertex F η + vertexFintype := inferInstance + relation := glueRelation F η + symmetric := glueRelation_symm F η + roots := glueRoot F η + Node := GlueNode F + nodeFintype := inferInstance + tree := glueBagTree F η hm + root_bag := rfl + +variable {V : Type} (G : SimpleGraph V) (x : Fin m → V) + +noncomputable def glueValue (g : (i : I) → (F i).Maps G (x ∘ η i)) : + GlueVertex F η → V + | .inl q => Quot.lift x (by + rintro a b ⟨i, j, l, rfl, rfl, hjl⟩ + exact (g i).2 j |>.symm.trans (by + rw [hjl] + exact (g i).2 l)) q + | .inr ⟨i, a⟩ => (g i).1.1 a + +lemma glueValue_root (g : (i : I) → (F i).Maps G (x ∘ η i)) (j : Fin m) : + glueValue F η G x g (glueRoot F η j) = x j := rfl + +lemma glueValue_map (g : (i : I) → (F i).Maps G (x ∘ η i)) + (i : I) (a : (F i).Vertex) : glueValue F η G x g (glueMap F η i a) = (g i).1.1 a := by + by_cases ha : ∃ j, (F i).roots j = a + · obtain ⟨j, rfl⟩ := ha + rw [glueMap_root, glueValue_root] + exact ((g i).2 j).symm + · rw [glueMap_internal F η i ⟨a, ha⟩] + rfl + +noncomputable def glueMapsEquiv [Fintype I] (hm : m ≤ t) : + (glueTest F η hm).Maps G x ≃ ((i : I) → (F i).Maps G (x ∘ η i)) where + toFun f i := + ⟨⟨fun a => f.1.1 (glueMap F η i a), fun a b hab => + f.1.2 _ _ ⟨i, a, b, hab, rfl, rfl⟩⟩, + fun j => by + change f.1.1 (glueMap F η i ((F i).roots j)) = x (η i j) + rw [glueMap_root] + exact f.2 (η i j)⟩ + invFun g := + ⟨⟨glueValue F η G x g, by + rintro a b ⟨i, u, v, huv, rfl, rfl⟩ + rw [glueValue_map, glueValue_map] + exact (g i).1.2 u v huv⟩, + glueValue_root F η G x g⟩ + left_inv f := by + apply Subtype.ext + apply Subtype.ext + funext a + cases a with + | inl q => + induction q using Quot.inductionOn with + | h j => exact (f.2 j).symm + | inr p => + rcases p with ⟨i, a⟩ + change f.1.1 (glueMap F η i a.1) = f.1.1 (.inr ⟨i, a⟩) + rw [glueMap_internal] + right_inv g := by + funext i + apply Subtype.ext + apply Subtype.ext + funext a + exact glueValue_map F η G x g i a + +lemma glueTest_count [Fintype I] [Fintype V] (hm : m ≤ t) : + (glueTest F η hm).count G x = ∏ i : I, (F i).count G (x ∘ η i) := by + unfold RootedTest.count + rw [Fintype.card_congr (glueMapsEquiv F η G x hm), Fintype.card_pi, Nat.cast_prod] + +end GlueVertices + +end ParityWL + +end OAI diff --git a/lean/OAI/Combinatorics/ParityLifts/GraphIso.lean b/lean/OAI/Combinatorics/ParityLifts/GraphIso.lean new file mode 100644 index 0000000000000000000000000000000000000000..53303bd9e561fbd3ab5eb5d704a317bb86da62d4 --- /dev/null +++ b/lean/OAI/Combinatorics/ParityLifts/GraphIso.lean @@ -0,0 +1,120 @@ +import OAI.Combinatorics.ParityLifts.SATChoice + +namespace OAI + +namespace ParityWL + +lemma finite_histogram_equiv {α β γ : Type} [Fintype α] [Fintype β] + (e : α ≃ β) (f : α → γ) (g : β → γ) (h : ∀ a, f a = g (e a)) : + Finset.univ.val.map f = Finset.univ.val.map g := by + calc + _ = Finset.univ.val.map (g ∘ e) := by congr 1; funext a; exact h a + _ = (Finset.univ.val.map e).map g := (Multiset.map_map _ _ _).symm + _ = _ := by rw [Multiset.map_univ_val_equiv] + +lemma iso_atomicType {V W : Type} (G : SimpleGraph V) (H : SimpleGraph W) + (e : G ≃g H) (k : ℕ) (x : Fin k → V) : atomicType G x = atomicType H (e ∘ x) := by + classical + funext i j + simp [atomicType, e.injective.eq_iff, e.map_adj_iff] + +lemma iso_update {V W : Type} (f : V → W) (k : ℕ) (x : Fin k → V) (i : Fin k) (v : V) : + f ∘ Function.update x i v = Function.update (f ∘ x) i (f v) := by + classical + funext j + by_cases h : j=i <;> simp [h] + +lemma iso_jointColor {V W : Type} [Fintype V] [Fintype W] + (G : SimpleGraph V) (H : SimpleGraph W) (e : G ≃g H) (k r : ℕ) (x : Fin k → V) : + jointColor G k r x = jointColor H k r (e ∘ x) := by + induction r generalizing x with + | zero => exact iso_atomicType G H e k x + | succ r ih => + change (_,_) = (_,_) + congr 1 + · exact ih x + · apply finite_histogram_equiv e.toEquiv + intro v + funext i + rw [ih, iso_update] + rfl + +lemma iso_separateColor {V W : Type} [Fintype V] [Fintype W] + (G : SimpleGraph V) (H : SimpleGraph W) (e : G ≃g H) (k r : ℕ) (x : Fin k → V) : + separateColor G k r x = separateColor H k r (e ∘ x) := by + induction r generalizing x with + | zero => exact iso_atomicType G H e k x + | succ r ih => + change (_,_) = (_,_) + congr 1 + · exact ih x + · funext i + apply finite_histogram_equiv e.toEquiv + intro v + rw [ih, iso_update] + rfl + +lemma iso_jointHistogram {V W : Type} [Fintype V] [Fintype W] + (G : SimpleGraph V) (H : SimpleGraph W) (e : G ≃g H) (k r : ℕ) : + Finset.univ.val.map (jointColor G k r) = Finset.univ.val.map (jointColor H k r) := by + apply finite_histogram_equiv (Equiv.arrowCongr (Equiv.refl (Fin k)) e.toEquiv) + exact iso_jointColor G H e k r + +lemma iso_separateHistogram {V W : Type} [Fintype V] [Fintype W] + (G : SimpleGraph V) (H : SimpleGraph W) (e : G ≃g H) (k r : ℕ) : + Finset.univ.val.map (separateColor G k r) = Finset.univ.val.map (separateColor H k r) := by + apply finite_histogram_equiv (Equiv.arrowCongr (Equiv.refl (Fin k)) e.toEquiv) + exact iso_separateColor G H e k r + +lemma iso_sameHistogram {V V' W W' : Type} [Fintype V] [Fintype V'] [Fintype W] [Fintype W'] + (G : SimpleGraph V) (G' : SimpleGraph V') (H : SimpleGraph W) (H' : SimpleGraph W') + (e : G ≃g G') (f : H ≃g H') (c : Convention) (k r : ℕ) : + sameHistogram G H c k r ↔ sameHistogram G' H' c k r := by + cases c + · simp only [sameHistogram, iso_jointHistogram G G' e, iso_jointHistogram H H' f] + · simp only [sameHistogram, iso_separateHistogram G G' e, iso_separateHistogram H H' f] + +lemma iso_samePureHistogram {V V' W W' : Type} [Fintype V] [Fintype V'] [Fintype W] [Fintype W'] + (G : SimpleGraph V) (G' : SimpleGraph V') (H : SimpleGraph W) (H' : SimpleGraph W') + (e : G ≃g G') (f : H ≃g H') (c : Convention) (k r : ℕ) : + samePureHistogram G H c k r ↔ samePureHistogram G' H' c k r := by + let E := e.sumCongr f + have hj₁ : Finset.univ.val.map (fun x : Fin k → V => jointColor (G.sum H) k r (Sum.inl ∘ x)) = + Finset.univ.val.map (fun x : Fin k → V' => jointColor (G'.sum H') k r (Sum.inl ∘ x)) := by + apply finite_histogram_equiv (Equiv.arrowCongr (Equiv.refl (Fin k)) e.toEquiv) + intro x + exact iso_jointColor _ _ E k r _ + have hj₂ : Finset.univ.val.map (fun x : Fin k → W => jointColor (G.sum H) k r (Sum.inr ∘ x)) = + Finset.univ.val.map (fun x : Fin k → W' => jointColor (G'.sum H') k r (Sum.inr ∘ x)) := by + apply finite_histogram_equiv (Equiv.arrowCongr (Equiv.refl (Fin k)) f.toEquiv) + intro x + exact iso_jointColor _ _ E k r _ + have hs₁ : Finset.univ.val.map (fun x : Fin k → V => separateColor (G.sum H) k r (Sum.inl ∘ x)) = + Finset.univ.val.map (fun x : Fin k → V' => separateColor (G'.sum H') k r (Sum.inl ∘ x)) := by + apply finite_histogram_equiv (Equiv.arrowCongr (Equiv.refl (Fin k)) e.toEquiv) + intro x + exact iso_separateColor _ _ E k r _ + have hs₂ : Finset.univ.val.map (fun x : Fin k → W => separateColor (G.sum H) k r (Sum.inr ∘ x)) = + Finset.univ.val.map (fun x : Fin k → W' => separateColor (G'.sum H') k r (Sum.inr ∘ x)) := by + apply finite_histogram_equiv (Equiv.arrowCongr (Equiv.refl (Fin k)) f.toEquiv) + intro x + exact iso_separateColor _ _ E k r _ + cases c + · simp only [samePureHistogram, hj₁, hj₂] + · simp only [samePureHistogram, hs₁, hs₂] + +lemma iso_WLEquivalent {V V' W W' : Type} [Fintype V] [Fintype V'] [Fintype W] [Fintype W'] + (G : SimpleGraph V) (G' : SimpleGraph V') (H : SimpleGraph W) (H' : SimpleGraph W') + (e : G ≃g G') (f : H ≃g H') (c : Convention) (k : ℕ) : + WLEquivalent G H c k ↔ WLEquivalent G' H' c k := + forall_congr' (iso_sameHistogram G G' H H' e f c k) + +lemma iso_PureWLEquivalent {V V' W W' : Type} [Fintype V] [Fintype V'] [Fintype W] [Fintype W'] + (G : SimpleGraph V) (G' : SimpleGraph V') (H : SimpleGraph W) (H' : SimpleGraph W') + (e : G ≃g G') (f : H ≃g H') (c : Convention) (k : ℕ) : + PureWLEquivalent G H c k ↔ PureWLEquivalent G' H' c k := + forall_congr' (iso_samePureHistogram G G' H H' e f c k) + +end ParityWL + +end OAI diff --git a/lean/OAI/Combinatorics/ParityLifts/GraphOutput.lean b/lean/OAI/Combinatorics/ParityLifts/GraphOutput.lean new file mode 100644 index 0000000000000000000000000000000000000000..e2c6a5689c89b7f36ef0a0cf74d987c472f729a5 --- /dev/null +++ b/lean/OAI/Combinatorics/ParityLifts/GraphOutput.lean @@ -0,0 +1,102 @@ +import OAI.Combinatorics.ParityLifts.BitGrouping + +namespace OAI + +namespace ParityWL.Complexity + +open Classical + +lemma ChoiceData.matrix_eq {t : ℕ} (D : ChoiceData t) (b : TemplateVertex t → Bit) : + D.matrix b = (List.ofFn (fun i : Fin (D.vertices b).length => + List.ofFn (fun j : Fin (D.vertices b).length => decide ((D.indexedGraph b).Adj i j)))).flatten := by + classical + have he (i j : Fin (D.vertices b).length) : decide ((D.indexedGraph b).Adj i j) = + D.edgeTest b ((D.vertices b).get i) ((D.vertices b).get j) := by + apply Bool.eq_iff_iff.mpr + simpa using D.indexed_adj b i j + simp only [he] + simp only [List.get_eq_getElem, List.ofFn_getElem_eq_map] + simp only [ChoiceData.matrix, List.flatMap_def] + congr 1 + exact (List.ofFn_getElem_eq_map _ _).symm + +lemma ChoiceData.vertices_length_eq {t : ℕ} (D : ChoiceData t) (ht : 2≤t) : + (D.vertices (fun _ => 0)).length = (D.vertices (starParity t)).length := by + have h0 := Fintype.card_congr (D.vertexEquiv (fun _ => 0)) + have h1 := Fintype.card_congr (D.vertexEquiv (starParity t)) + simp only [Fintype.card_fin] at h0 h1 + exact h0.trans ((choice_lifts_equal_order ht D.system).trans h1.symm) + +noncomputable def ChoiceData.output {t : ℕ} (D : ChoiceData t) : List Bool := + encodeNat (D.vertices (fun _ => 0)).length ++ D.matrix (fun _ => 0) ++ D.matrix (starParity t) + +noncomputable def PolyProgram.vertexCount (t : ℕ) [NeZero t] : + PolyProgram (ChoiceData t) ℕ (fun D => (D.vertices (fun _ => 0)).length) := by + exact (PolyProgram.vertices t (fun _ => 0)).comp + (PolyProgram.length (TagIndex t (fun _ => 0) × ℕ)) + +noncomputable def PolyProgram.orderPrefix (t : ℕ) [NeZero t] : + PolyProgram (ChoiceData t) (List Bool) + (fun D => Complexity.encodeNat (D.vertices (fun _ => 0)).length) := by + refine ((PolyProgram.vertexCount t).comp PolyProgram.encodeNat).congr ?_ + intro D + rfl + +noncomputable def PolyProgram.leftOutput (t : ℕ) [NeZero t] : + PolyProgram (ChoiceData t) (List Bool) + (fun D => Complexity.encodeNat (D.vertices (fun _ => 0)).length ++ D.matrix (fun _ => 0)) := by + refine (((PolyProgram.orderPrefix t).pair (PolyProgram.matrix t (fun _ => 0))).comp + (PolyProgram.append Bool)).congr ?_ + intro D + rfl + +noncomputable def PolyProgram.graphOutput (t : ℕ) [NeZero t] : + PolyProgram (ChoiceData t) (List Bool) (fun D => D.output) := by + refine (((PolyProgram.leftOutput t).pair (PolyProgram.matrix t (starParity t))).comp + (PolyProgram.append Bool)).congr ?_ + intro D + rfl + +lemma matrix_cast {n m : ℕ} (e : n=m) (G : SimpleGraph (Fin m)) : + (List.ofFn (fun i : Fin n => List.ofFn (fun j : Fin n => + decide ((G.comap (Fin.cast e)).Adj i j)))).flatten = + (List.ofFn (fun i : Fin m => List.ofFn (fun j : Fin m => decide (G.Adj i j)))).flatten := by + classical + subst m + rfl + +/-- The actual generated bit string is the two full adjacency matrices of the +uncolored simple graphs in the parity reduction, up to proved finite indexing. -/ +theorem ChoiceData.output_spec (k : ℕ) (hk : 4≤k) (c : Convention) + (D : ChoiceData (bagParameter c k)) : + ∃ (n : ℕ) (G H : SimpleGraph (Fin n)), + D.output = encodeGraphs G H ∧ + (∀ i : Implementation, Equivalent G H c i k ↔ ¬ D.system.Successful) ∧ + n = (D.vertices (fun _ => 0)).length := by + classical + let t := bagParameter c k + have ht : 2≤t := by cases c <;> simp only [t,bagParameter] <;> omega + let n := (D.vertices (fun _ => 0)).length + let m := (D.vertices (starParity t)).length + have he : n=m := D.vertices_length_eq ht + let G := D.indexedGraph (fun _ => 0) + let H := (D.indexedGraph (starParity t)).comap (Fin.cast he) + have Hiso : H ≃g starLift D.system := + (SimpleGraph.Iso.comap (finCongr he) (D.indexedGraph (starParity t))).trans (D.indexedIso (starParity t)) + refine ⟨n,G,H,?_,?_,rfl⟩ + · unfold ChoiceData.output encodeGraphs + rw [D.matrix_eq, D.matrix_eq] + apply congrArg (fun z => encodeNat n ++ (List.ofFn (fun i : Fin n => + List.ofFn (fun j : Fin n => decide (G.Adj i j)))).flatten ++ z) + exact (matrix_cast he (D.indexedGraph (starParity t))).symm + · intro i + have hp := parity_reduction k hk c D.system + cases i with + | commonColors => exact + (iso_WLEquivalent G (zeroLift D.system) H (starLift D.system) (D.indexedIso _) Hiso c k).trans hp.2.2.1 + | pureUnion => exact + (iso_PureWLEquivalent G (zeroLift D.system) H (starLift D.system) (D.indexedIso _) Hiso c k).trans hp.2.2.2.1 + +end ParityWL.Complexity + +end OAI diff --git a/lean/OAI/Combinatorics/ParityLifts/GraphPrograms.lean b/lean/OAI/Combinatorics/ParityLifts/GraphPrograms.lean new file mode 100644 index 0000000000000000000000000000000000000000..b583d1adcd23dc78d914180ed3a0322f53ae3376 --- /dev/null +++ b/lean/OAI/Combinatorics/ParityLifts/GraphPrograms.lean @@ -0,0 +1,209 @@ +import OAI.Combinatorics.ParityLifts.BitTables + +namespace OAI + +namespace ParityWL.Complexity + +def PolyProgram.finite2 {n m : ℕ} {α : Type} [TreeCodec α] + (f : Fin n → Fin m → α) : PolyProgram (Fin n × Fin m) α (fun x => f x.1 x.2) := + .expr (TExpr.caseFin n TExpr.input.left (fun i => + TExpr.caseFin m TExpr.input.right (fun j => .const (treeEncode (f i j))) .nil) .nil) (by + rintro ⟨i,j⟩ + rw [TExpr.caseFin_eval i _ _ _ _ (by rfl), TExpr.caseFin_eval j _ _ _ _ (by rfl)] + rfl) + +def PolyProgram.choiceEntry (t : ℕ) : + PolyProgram (ChoiceData t × (Fin t × (ℕ × Fin t))) ℕ + (fun x => x.1.entry x.2.1 x.2.2.1 x.2.2.2) := by + let row : PolyProgram (ChoiceData t × (Fin t × (ℕ × Fin t))) (Fin t × (Fin t → List (Fin t → ℕ))) + (fun x => (x.2.1,x.1.1)) := .expr (.pair TExpr.input.right.left TExpr.input.left.left) (by intro x; rfl) + let R := row.comp (PolyProgram.evalFin t (List (Fin t → ℕ))) + let idx : PolyProgram (ChoiceData t × (Fin t × (ℕ × Fin t))) ℕ (fun x => x.2.2.1) := + .expr TExpr.input.right.right.left (by intro x; rfl) + let V := (idx.pair R).comp (PolyProgram.getD (Fin t → ℕ) (fun _ => 0)) + let col : PolyProgram (ChoiceData t × (Fin t × (ℕ × Fin t))) (Fin t) (fun x => x.2.2.2) := + .expr TExpr.input.right.right.right (by intro x; rfl) + exact (col.pair V).comp (PolyProgram.evalFin t ℕ) + +def PolyProgram.choiceBound (t : ℕ) : + PolyProgram (ChoiceData t × (Fin t × Fin t)) ℕ (fun x => x.1.pairBound x.2.1 x.2.2) := by + let I := (PolyProgram.snd (ChoiceData t) (Fin t × Fin t)).comp + (PolyProgram.finite2 (fun i j : Fin t => (min i j,max i j))) + let T := (PolyProgram.fst (ChoiceData t) (Fin t × Fin t)).comp + (PolyProgram.snd (Fin t → List (Fin t → ℕ)) (Fin t → Fin t → ℕ)) + let R := ((I.comp (PolyProgram.fst (Fin t) (Fin t))).pair T).comp + (PolyProgram.evalFin t (Fin t → ℕ)) + exact ((I.comp (PolyProgram.snd (Fin t) (Fin t))).pair R).comp (PolyProgram.evalFin t ℕ) + +def PolyProgram.choiceLabel (t : ℕ) : + PolyProgram (ChoiceData t × (Fin t × (ℕ × Fin t))) ℕ + (fun x => x.1.label x.2.1 x.2.2.1 x.2.2.2) := by + let Q : PolyProgram (ChoiceData t × (Fin t × (ℕ × Fin t))) (ChoiceData t × (Fin t × Fin t)) + (fun x => (x.1,(x.2.1,x.2.2.2))) := + .expr (.pair TExpr.input.left (.pair TExpr.input.right.left TExpr.input.right.right.right)) (by intro x; rfl) + exact ((PolyProgram.choiceEntry t).pair (Q.comp (PolyProgram.choiceBound t))).comp PolyProgram.natMin + +/-- The finite role data is compiled into finite control, independent of table size. -/ +noncomputable def roleCode {t : ℕ} [NeZero t] : TemplateVertex t → Bool × (Fin t × Fin t) + | .inl i => (false,(i,i)) + | .inr h => (true,(h.1.1.1.1,h.1.1.1.2)) + +noncomputable def PolyProgram.indexSize (t : ℕ) [NeZero t] (b : TemplateVertex t → Bit) : + PolyProgram (TagIndex t b × ChoiceData t) ℕ (fun x => x.2.indexSize b x.1) := by + let R := (PolyProgram.fst (TagIndex t b) (ChoiceData t)).comp + (PolyProgram.finite (fun z => roleCode (tagDecode t b z).1)) + let I := R.comp (PolyProgram.snd Bool (Fin t × Fin t)) + let D := PolyProgram.snd (TagIndex t b) (ChoiceData t) + let Ds := D.comp (PolyProgram.fst (Fin t → List (Fin t → ℕ)) (Fin t → Fin t → ℕ)) + let row := ((I.comp (PolyProgram.fst (Fin t) (Fin t))).pair Ds).comp + (PolyProgram.evalFin t (List (Fin t → ℕ))) |>.comp (PolyProgram.length (Fin t → ℕ)) + let Bs := D.comp (PolyProgram.snd (Fin t → List (Fin t → ℕ)) (Fin t → Fin t → ℕ)) + let brow := ((I.comp (PolyProgram.fst (Fin t) (Fin t))).pair Bs).comp (PolyProgram.evalFin t (Fin t → ℕ)) + let val := ((I.comp (PolyProgram.snd (Fin t) (Fin t))).pair brow).comp (PolyProgram.evalFin t ℕ) |>.comp PolyProgram.natSucc + refine ((R.comp (PolyProgram.fst Bool (Fin t × Fin t))).ite val row).congr ?_ + intro x + change (if (roleCode (tagDecode t b x.1).1).1 then _ else _) = _ + rcases h : (tagDecode t b x.1).1 with i | h + · simp [roleCode, ChoiceData.indexSize, ChoiceData.roleSize, h] + · simp [roleCode, ChoiceData.indexSize, ChoiceData.roleSize, h] + +noncomputable def PolyProgram.vertices (t : ℕ) [NeZero t] (b : TemplateVertex t → Bit) : + PolyProgram (ChoiceData t) (List (TagIndex t b × ℕ)) (fun D => D.vertices b) := by + let R := (PolyProgram.indexSize t b).comp PolyProgram.range + let pairTag : PolyProgram (ℕ × TagIndex t b) (TagIndex t b × ℕ) (fun x => (x.2,x.1)) := + .expr (.pair TExpr.input.right TExpr.input.left) (by intro x; rfl) + let group := (R.pair (PolyProgram.fst (TagIndex t b) (ChoiceData t))).comp pairTag.mapWith + unfold ChoiceData.vertices enumPairs + exact (((PolyProgram.const (List.ofFn (_root_.id : TagIndex t b → TagIndex t b))).pair + (PolyProgram.id (ChoiceData t))).comp group.mapWith).comp (PolyProgram.flatten (TagIndex t b × ℕ)) + +/-- 0 and 1 are constants; 2 compares two labels; 3 and 4 compare a label and a helper value. -/ +def baseRule {t : ℕ} [NeZero t] : TemplateVertex t → TemplateVertex t → Fin 5 × (Fin t × Fin t) + | .inl i, .inl j => (if i=j then 0 else 2,(i,j)) + | .inl i, .inr h => + if i=h.1.1.1.1 then (3,(i,h.1.1.1.2)) + else if i=h.1.1.1.2 then (3,(i,h.1.1.1.1)) + else (if i=h.1.2 then 1 else 0,(0,0)) + | .inr h, .inl i => + if i=h.1.1.1.1 then (4,(i,h.1.1.1.2)) + else if i=h.1.1.1.2 then (4,(i,h.1.1.1.1)) + else (if i=h.1.2 then 1 else 0,(0,0)) + | .inr _, .inr _ => (0,(0,0)) + +def evalRule {t : ℕ} (D : ChoiceData t) (r : Fin 5 × (Fin t × Fin t)) (d e : ℕ) : Bool := + if r.1=0 then false else if r.1=1 then true + else if r.1=2 then decide (D.label r.2.1 d r.2.2=D.label r.2.2 e r.2.1) + else if r.1=3 then decide (D.label r.2.1 d r.2.2=e) + else decide (D.label r.2.1 e r.2.2=d) + +lemma eval_baseRule {t : ℕ} [NeZero t] (D : ChoiceData t) (a b : TemplateVertex t) (d e : ℕ) : + evalRule D (baseRule a b) d e = D.baseTest a d b e := by + cases a with + | inl i => + cases b with + | inl j => by_cases h : i=j <;> simp [evalRule,baseRule,ChoiceData.baseTest,h] + | inr h => + by_cases h1 : i=h.1.1.1.1 <;> by_cases h2 : i=h.1.1.1.2 <;> by_cases h3 : i=h.1.2 <;> + simp_all [evalRule,baseRule,ChoiceData.baseTest,ChoiceData.helperTest] + | inr h => + cases b with + | inl i => + by_cases h1 : i=h.1.1.1.1 <;> by_cases h2 : i=h.1.1.1.2 <;> by_cases h3 : i=h.1.2 <;> + simp_all [evalRule,baseRule,ChoiceData.baseTest,ChoiceData.helperTest] + | inr g => simp [evalRule,baseRule,ChoiceData.baseTest] + +noncomputable def edgeRule {t : ℕ} [NeZero t] (b : TemplateVertex t → Bit) (x y : TagIndex t b) : + Fin 5 × (Fin t × Fin t) := + if tagTest b (tagDecode t b x) (tagDecode t b y) then + baseRule (tagDecode t b x).1 (tagDecode t b y).1 else (0,(0,0)) + +lemma eval_edgeRule {t : ℕ} [NeZero t] (D : ChoiceData t) (b : TemplateVertex t → Bit) + (x y : TagIndex t b × ℕ) : evalRule D (edgeRule b x.1 y.1) x.2 y.2 = D.edgeTest b x y := by + unfold edgeRule ChoiceData.edgeTest + split + · rw [eval_baseRule]; simp_all + · simp_all [evalRule] + +noncomputable def PolyProgram.evalRule (t : ℕ) : + PolyProgram (ChoiceData t × ((Fin 5 × (Fin t × Fin t)) × (ℕ × ℕ))) Bool + (fun x => Complexity.evalRule x.1 x.2.1 x.2.2.1 x.2.2.2) := by + let K : PolyProgram (ChoiceData t × ((Fin 5 × (Fin t × Fin t)) × (ℕ × ℕ))) (Fin 5) + (fun x => x.2.1.1) := .expr TExpr.input.right.left.left (by intro x; rfl) + let L : PolyProgram (ChoiceData t × ((Fin 5 × (Fin t × Fin t)) × (ℕ × ℕ))) + (ChoiceData t × (Fin t × (ℕ × Fin t))) + (fun x => (x.1,(x.2.1.2.1,(x.2.2.1,x.2.1.2.2)))) := + .expr (.pair TExpr.input.left (.pair TExpr.input.right.left.right.left + (.pair TExpr.input.right.right.left TExpr.input.right.left.right.right))) (by intro x; rfl) + let R : PolyProgram (ChoiceData t × ((Fin 5 × (Fin t × Fin t)) × (ℕ × ℕ))) + (ChoiceData t × (Fin t × (ℕ × Fin t))) + (fun x => (x.1,(x.2.1.2.2,(x.2.2.2,x.2.1.2.1)))) := + .expr (.pair TExpr.input.left (.pair TExpr.input.right.left.right.right + (.pair TExpr.input.right.right.right TExpr.input.right.left.right.left))) (by intro x; rfl) + let R' : PolyProgram (ChoiceData t × ((Fin 5 × (Fin t × Fin t)) × (ℕ × ℕ))) + (ChoiceData t × (Fin t × (ℕ × Fin t))) + (fun x => (x.1,(x.2.1.2.1,(x.2.2.2,x.2.1.2.2)))) := + .expr (.pair TExpr.input.left (.pair TExpr.input.right.left.right.left + (.pair TExpr.input.right.right.right TExpr.input.right.left.right.right))) (by intro x; rfl) + let d : PolyProgram (ChoiceData t × ((Fin 5 × (Fin t × Fin t)) × (ℕ × ℕ))) ℕ + (fun x => x.2.2.1) := .expr TExpr.input.right.right.left (by intro x; rfl) + let e : PolyProgram (ChoiceData t × ((Fin 5 × (Fin t × Fin t)) × (ℕ × ℕ))) ℕ + (fun x => x.2.2.2) := .expr TExpr.input.right.right.right (by intro x; rfl) + let LL := L.comp (PolyProgram.choiceLabel t) + let RR := R.comp (PolyProgram.choiceLabel t) + let Rr := R'.comp (PolyProgram.choiceLabel t) + let test := fun (n : Fin 5) => K.comp (PolyProgram.finite (fun i => decide (i=n))) + refine ((test 0).ite (PolyProgram.const false) ((test 1).ite (PolyProgram.const true) + ((test 2).ite ((LL.pair RR).comp (PolyProgram.equal ℕ)) + ((test 3).ite ((LL.pair e).comp (PolyProgram.equal ℕ)) ((Rr.pair d).comp (PolyProgram.equal ℕ)))))).congr ?_ + intro x + change (if decide (_=0) then _ else _) = _ + simp [Complexity.evalRule] + +noncomputable def PolyProgram.edgeTest (t : ℕ) [NeZero t] (b : TemplateVertex t → Bit) : + PolyProgram ((TagIndex t b × ℕ) × ((TagIndex t b × ℕ) × ChoiceData t)) Bool + (fun x => x.2.2.edgeTest b x.1 x.2.1) := by + let tags : PolyProgram ((TagIndex t b × ℕ) × ((TagIndex t b × ℕ) × ChoiceData t)) + (TagIndex t b × TagIndex t b) (fun x => (x.1.1,x.2.1.1)) := + .expr (.pair TExpr.input.left.left TExpr.input.right.left.left) (by intro x; rfl) + let rule := tags.comp (PolyProgram.finite2 (edgeRule b)) + let nums : PolyProgram ((TagIndex t b × ℕ) × ((TagIndex t b × ℕ) × ChoiceData t)) + (ℕ × ℕ) (fun x => (x.1.2,x.2.1.2)) := + .expr (.pair TExpr.input.left.right TExpr.input.right.left.right) (by intro x; rfl) + let D : PolyProgram ((TagIndex t b × ℕ) × ((TagIndex t b × ℕ) × ChoiceData t)) + (ChoiceData t) (fun x => x.2.2) := .expr TExpr.input.right.right (by intro x; rfl) + exact ((D.pair (rule.pair nums)).comp (PolyProgram.evalRule t)).congr + (by intro x; exact eval_edgeRule x.2.2 b x.1 x.2.1) + +noncomputable def ChoiceData.matrix {t : ℕ} (D : ChoiceData t) (b : TemplateVertex t → Bit) : List Bool := + (D.vertices b).flatMap (fun x => (D.vertices b).map (D.edgeTest b x)) + +noncomputable def PolyProgram.matrixRow (t : ℕ) [NeZero t] (b : TemplateVertex t → Bit) : + PolyProgram ((TagIndex t b × ℕ) × ChoiceData t) (List Bool) + (fun x => (x.2.vertices b).map (x.2.edgeTest b x.1)) := by + let swap : PolyProgram ((TagIndex t b × ℕ) × ((TagIndex t b × ℕ) × ChoiceData t)) + ((TagIndex t b × ℕ) × ((TagIndex t b × ℕ) × ChoiceData t)) + (fun x => (x.2.1,(x.1,x.2.2))) := + .expr (.pair TExpr.input.right.left (.pair TExpr.input.left TExpr.input.right.right)) (by intro x; rfl) + let row := (((PolyProgram.snd (TagIndex t b × ℕ) (ChoiceData t)).comp (PolyProgram.vertices t b)).pair + (PolyProgram.id ((TagIndex t b × ℕ) × ChoiceData t))).comp ((swap.comp (PolyProgram.edgeTest t b)).mapWith) + exact row + +noncomputable def PolyProgram.matrixRows (t : ℕ) [NeZero t] (b : TemplateVertex t → Bit) : + PolyProgram (List (TagIndex t b × ℕ) × ChoiceData t) (List (List Bool)) + (fun x => x.1.map (fun y => (x.2.vertices b).map (x.2.edgeTest b y))) := + (PolyProgram.matrixRow t b).mapWith + +noncomputable def PolyProgram.rowMatrix (t : ℕ) [NeZero t] (b : TemplateVertex t → Bit) : + PolyProgram (ChoiceData t) (List (List Bool)) + (fun D => (D.vertices b).map (fun y => (D.vertices b).map (D.edgeTest b y))) := + ((PolyProgram.vertices t b).pair (PolyProgram.id (ChoiceData t))).comp (PolyProgram.matrixRows t b) + +noncomputable def PolyProgram.matrix (t : ℕ) [NeZero t] (b : TemplateVertex t → Bit) : + PolyProgram (ChoiceData t) (List Bool) (fun D => D.matrix b) := by + refine ((PolyProgram.rowMatrix t b).comp (PolyProgram.flatten Bool)).congr ?_ + intro D + rfl + +end ParityWL.Complexity + +end OAI diff --git a/lean/OAI/Combinatorics/ParityLifts/Interpolation.lean b/lean/OAI/Combinatorics/ParityLifts/Interpolation.lean new file mode 100644 index 0000000000000000000000000000000000000000..706fd8098f943cbb0820792f543d805a9f2fe048 --- /dev/null +++ b/lean/OAI/Combinatorics/ParityLifts/Interpolation.lean @@ -0,0 +1,158 @@ +import OAI.Combinatorics.ParityLifts.TestAlgebra + +namespace OAI + +namespace ParityWL + +open scoped BigOperators + +section FiniteInterpolation + +open scoped Classical + +lemma color_indicator_mem_of_separation {X D : Type} [Fintype X] [DecidableEq D] + (A : Subalgebra ℚ (X → ℚ)) (c : X → D) + (hsep : ∀ x y, c x ≠ c y → ∃ f ∈ A, + (∀ z w, c z = c w → f z = f w) ∧ f x ≠ f y) (d : D) : + (fun x => if c x = d then (1 : ℚ) else 0) ∈ A := by + by_cases hex : ∃ x, c x = d + · obtain ⟨x₀, hx₀⟩ := hex + let Y := {y : X // c x₀ ≠ c y} + choose f hf hinv hne using (fun y : Y => hsep x₀ y.1 y.2) + let p : X → ℚ := ∏ y : Y, (f y x₀ - f y y.1)⁻¹ • (f y - (f y y.1) • 1) + have hp : p ∈ A := A.prod_mem (fun y _ => + A.smul_mem (A.sub_mem (hf y) (A.smul_mem A.one_mem (f y y.1))) _) + have he : p = fun x => if c x = d then (1 : ℚ) else 0 := by + funext x + dsimp only [p] + rw [Finset.prod_apply] + by_cases hx : c x = d + · rw [ite_eq_left hx] + apply Finset.prod_eq_one + intro y _ + simp only [Pi.smul_apply, Pi.sub_apply, Pi.one_apply, smul_eq_mul, mul_one] + rw [hinv y x x₀ (hx.trans hx₀.symm)] + exact inv_mul_cancel₀ (sub_ne_zero.mpr (hne y)) + · rw [ite_eq_right hx] + let y : Y := ⟨x, fun he => hx (he.symm.trans hx₀)⟩ + apply Finset.prod_eq_zero (Finset.mem_univ y) + simp only [Pi.smul_apply, Pi.sub_apply, Pi.one_apply, smul_eq_mul, mul_one] + change _ * (f y x - f y x) = 0 + rw [sub_self, mul_zero] + rwa [he] at hp + · have he : (fun x => if c x = d then (1 : ℚ) else 0) = 0 := by + funext x + exact ite_eq_right (fun h => hex ⟨x, h⟩) + rw [he] + exact A.zero_mem + +lemma count_map_as_sum {X D : Type} [Fintype X] [DecidableEq D] (c : X → D) (d : D) : + (Multiset.count d (Finset.univ.val.map c) : ℚ) = + ∑ x : X, if c x = d then (1 : ℚ) else 0 := by + rw [Multiset.count_map, Finset.sum_boole] + congr 1 + exact congrArg Multiset.card (by + apply Multiset.filter_congr + intro x _ + exact eq_comm) + +end FiniteInterpolation + +section RefinementOperators + +open scoped Classical + +variable {V W : Type} [Fintype V] [Fintype W] +variable (G : SimpleGraph V) (H : SimpleGraph W) + +noncomputable def replacementSum {k : ℕ} (i : Fin k) (f : TuplePair V W k → ℚ) : + TuplePair V W k → ℚ := + Sum.elim (fun x => ∑ y : V, f (.inl (Function.update x i y))) + (fun x => ∑ y : W, f (.inr (Function.update x i y))) + +lemma insertNth_comp_succAbove {k : ℕ} {A : Type} (i : Fin (k + 1)) (y : A) + (x : Fin (k + 1) → A) : + i.insertNth y (x ∘ i.succAbove) = Function.update x i y := + Fin.insertNth_removeNth i y x + +lemma testSpan_replacementSum {k t : ℕ} (hkt : k ≤ t) (i : Fin k) + {f : TuplePair V W k → ℚ} (hf : f ∈ testSpan G H k t) : + replacementSum i f ∈ testSpan G H k t := by + cases k with + | zero => exact i.elim0 + | succ k => + have hmem := testSpan_reindex G H hkt i.succAbove + (testSpan_sumInsert G H (by omega) i hf) + have he : replacementSum i f = reindexLinear i.succAbove (sumInsertLinear i f) := by + funext a + cases a with + | inl x => + change (∑ y : V, f (.inl (Function.update x i y))) = + ∑ y : V, f (.inl (i.insertNth y (x ∘ i.succAbove))) + simp only [insertNth_comp_succAbove] + | inr x => + change (∑ y : W, f (.inr (Function.update x i y))) = + ∑ y : W, f (.inr (i.insertNth y (x ∘ i.succAbove))) + simp only [insertNth_comp_succAbove] + rwa [← he] at hmem + +def replaceEmbedding {k : ℕ} (i j : Fin k) : Fin (k + 1) := + if j = i then Fin.last k else j.castSucc + +lemma insertNth_replaceEmbedding {k : ℕ} {A : Type} (i : Fin k) (y : A) (x : Fin k → A) : + ((Fin.last k).insertNth y x) ∘ replaceEmbedding i = Function.update x i y := by + funext j + by_cases hj : j = i + · subst j + simp [replaceEmbedding] + · simp only [Function.comp_apply, replaceEmbedding, ite_eq_right hj, Function.update_of_ne hj] + rw [← Fin.succAbove_last_apply j, Fin.insertNth_apply_succAbove] + +noncomputable def jointReplacementSum {k : ℕ} (f : Fin k → TuplePair V W k → ℚ) : + TuplePair V W k → ℚ := + Sum.elim (fun x => ∑ y : V, ∏ i : Fin k, f i (.inl (Function.update x i y))) + (fun x => ∑ y : W, ∏ i : Fin k, f i (.inr (Function.update x i y))) + +lemma testSpan_jointReplacementSum {k t : ℕ} (hkt : k + 1 ≤ t) + {f : Fin k → TuplePair V W k → ℚ} (hf : ∀ i, f i ∈ testSpan G H k t) : + jointReplacementSum f ∈ testSpan G H k t := by + have hp : (∏ i : Fin k, reindexLinear (replaceEmbedding i) (f i)) ∈ + testSpan G H (k + 1) t := + (testAlgebra G H (k + 1) t hkt).prod_mem + (fun i _ => testSpan_reindex G H hkt (replaceEmbedding i) (hf i)) + have hs := testSpan_sumInsert G H (by omega) (Fin.last k) hp + have he : jointReplacementSum f = sumInsertLinear (Fin.last k) + (∏ i : Fin k, reindexLinear (replaceEmbedding i) (f i)) := by + funext a + cases a with + | inl x => + change (∑ y : V, ∏ i : Fin k, f i (.inl (Function.update x i y))) = + ∑ y : V, (∏ i : Fin k, reindexLinear (replaceEmbedding i) (f i)) + (.inl ((Fin.last k).insertNth y x)) + apply Finset.sum_congr rfl + intro y _ + rw [Finset.prod_apply] + apply Finset.prod_congr rfl + intro i _ + change f i (.inl (Function.update x i y)) = + f i (.inl (((Fin.last k).insertNth y x) ∘ replaceEmbedding i)) + rw [insertNth_replaceEmbedding] + | inr x => + change (∑ y : W, ∏ i : Fin k, f i (.inr (Function.update x i y))) = + ∑ y : W, (∏ i : Fin k, reindexLinear (replaceEmbedding i) (f i)) + (.inr ((Fin.last k).insertNth y x)) + apply Finset.sum_congr rfl + intro y _ + rw [Finset.prod_apply] + apply Finset.prod_congr rfl + intro i _ + change f i (.inr (Function.update x i y)) = + f i (.inr (((Fin.last k).insertNth y x) ∘ replaceEmbedding i)) + rw [insertNth_replaceEmbedding] + rwa [← he] at hs + +end RefinementOperators + +end ParityWL + +end OAI diff --git a/lean/OAI/Combinatorics/ParityLifts/LeafBounds.lean b/lean/OAI/Combinatorics/ParityLifts/LeafBounds.lean new file mode 100644 index 0000000000000000000000000000000000000000..e9ec64d74db5024894f985ca49e08b5403af96c5 --- /dev/null +++ b/lean/OAI/Combinatorics/ParityLifts/LeafBounds.lean @@ -0,0 +1,123 @@ +import OAI.Combinatorics.ParityLifts.DegreeBits + +namespace OAI + +namespace ParityWL.Complexity + +lemma PolyProgram.wordsOutput_degree_form (t : ℕ) [NeZero t] : + (PolyProgram.wordsOutput t).degree= + ((PolyProgram.choiceWithWords t).comp (PolyProgram.graphOutput t)).degree := by + unfold PolyProgram.wordsOutput + exact PolyProgram.congr_degree _ _ +lemma PolyProgram.wordsOutput_degree (t : ℕ) [NeZero t] : + (PolyProgram.wordsOutput t).degree=(PolyProgram.wordsOutput 1).degree := by + rw [PolyProgram.wordsOutput_degree_form,PolyProgram.wordsOutput_degree_form] + simp only [PolyProgram.comp_degree,PolyProgram.choiceWithWords_degree,PolyProgram.graphOutput_degree] + +lemma TreeProgram.leafOutput_time (t : ℕ) [NeZero t] (ht : 0 + intro s hn + rcases state_terminal_or_split hr s with ht | hf + · refine ⟨[s.formula], ?_, ?_, ?_⟩ + · intro F hF + obtain rfl := List.mem_singleton.mp hF + exact ⟨s.reduced, s.width, ht⟩ + · intro v + simp + · simp only [List.length_singleton, Nat.cast_one, one_mul] + exact pow_le_pow_right₀ hb s.spent_bound + · obtain ⟨f⟩ := hf + have hl : K - f.left.spent < n := by + have hK : f.left.spent ≤ K := f.left.spent_bound + have he := f.left_spent + have hx := f.x_pos + omega + have ht : K - f.right.spent < n := by + have hK : f.right.spent ≤ K := f.right.spent_bound + have he := f.right_spent + have hy := f.y_pos + omega + obtain ⟨L, hL, hLv, hLc⟩ := ih _ hl f.left rfl + obtain ⟨T, hT, hTv, hTc⟩ := ih _ ht f.right rfl + refine ⟨L ++ T, ?_, ?_, ?_⟩ + · intro F hF + rcases List.mem_append.mp hF with hF | hF + · exact hL F hF + · exact hT F hF + · intro v + rw [f.holds v, hLv v, hTv v] + simp only [List.mem_append, or_and_right, exists_or] + · rw [List.length_append] + rw [f.left_spent] at hLc + rw [f.right_spent] at hTc + exact weighted_split _ hp s.spent f.x f.y K L.length T.length hLc hTc f.split_bound + +/-- Width-three sparsification, with the explicit branching base and linear +leaf density. No sparsification theorem is imported or presumed. -/ +theorem sparsification_parameter (F : CNF α) (hw : ∀ C ∈ F, C.card ≤ 3) + (r : ℕ) (hr : 0 < r) : ∃ L : List (CNF α), + (∀ H ∈ L, Reduced H ∧ (∀ C ∈ H, C.card ≤ 3) ∧ + H.card ≤ 1 + Fintype.card α * (1 + r ^ 2 + 2 * r ^ 8)) ∧ + (∀ v : α → Prop, Holds F v ↔ ∃ H ∈ L, Holds H v) ∧ + (L.length : ℝ) ≤ branchBase r ^ (3 * Fintype.card α * r ^ 2) := by + obtain ⟨L, hL, hv, hc⟩ := state_leaves hr (initialState F hw (r ^ 2)) + refine ⟨L, ?_, ?_, ?_⟩ + · intro H hH + obtain ⟨hred, hwidth, hn2, hn31, hn32⟩ := hL H hH + refine ⟨hred, hwidth, ?_⟩ + have he : (r ^ 4) ^ 2 = r ^ 8 := by ring + simpa [he] using sparse_leaf_density H (r ^ 2) (r ^ 4) (pow_pos hr _) hwidth hn2 hn31 hn32 + · intro v + exact (minimize_holds F v).symm.trans (hv v) + · have hp : 1 ≤ branchBase r ^ (initialState F hw (r ^ 2)).spent := + one_le_pow₀ (branchBase_gt_one hr).le + exact (le_mul_of_one_le_right (Nat.cast_nonneg _) hp).trans hc + +end Sparsification + + +namespace Sparsification + +lemma branch_base_exponential (r n : ℕ) (hr : 0 < r) : + branchBase r ^ (3 * n * r ^ 2) ≤ Real.exp (3 * (n : ℝ) / r) := by + have hp : (0 : ℝ) < r := Nat.cast_pos.mpr hr + have he : branchBase r ≤ Real.exp (1 / (r : ℝ) ^ 3) := by + dsimp [branchBase] + linarith [Real.add_one_le_exp (1 / (r : ℝ) ^ 3)] + calc + _ ≤ Real.exp (1 / (r : ℝ) ^ 3) ^ (3 * n * r ^ 2) := by + exact pow_le_pow_left₀ (le_of_lt (lt_trans zero_lt_one (branchBase_gt_one hr))) he _ + _ = Real.exp ((3 * n * r ^ 2 : ℕ) * (1 / (r : ℝ) ^ 3)) := (Real.exp_nat_mul _ _).symm + _ = _ := by congr 1; push_cast; field_simp + +lemma indexed_rate_bound (j N : ℕ) (hj : 0 < j) : + branchBase (12 * j) ^ (3 * (2 * N) * (12 * j) ^ 2) ≤ + (2 : ℝ) ^ ((N : ℝ) / j) := by + have hp : (0 : ℝ) < j := Nat.cast_pos.mpr hj + have hl : (1 / 2 : ℝ) ≤ Real.log 2 := by linarith [Real.log_two_gt_d9] + calc + _ ≤ Real.exp (3 * (2 * N : ℕ) / (12 * j : ℕ)) := + branch_base_exponential _ _ (by omega) + _ ≤ Real.exp (Real.log 2 * ((N : ℝ) / j)) := by + apply Real.exp_le_exp.mpr + have hm := mul_le_mul_of_nonneg_right hl + (div_nonneg (Nat.cast_nonneg N) hp.le) + push_cast + calc + 3 * (2 * (N : ℝ)) / (12 * j) = (1 / 2 : ℝ) * (N / j) := by ring + _ ≤ _ := hm + _ = _ := (Real.rpow_def_of_pos (by norm_num : (0 : ℝ) < 2) _).symm + +theorem indexed_sparsification {α : Type} [DecidableEq α] [Fintype α] + (N : ℕ) (hα : Fintype.card α = 2 * N) (F : CNF α) + (hw : ∀ C ∈ F, C.card ≤ 3) (j : ℕ) (hj : 0 < j) : + ∃ L : List (CNF α), + (∀ H ∈ L, Reduced H ∧ (∀ C ∈ H, C.card ≤ 3) ∧ + H.card ≤ 1 + 2 * N * (1 + (12 * j) ^ 2 + 2 * (12 * j) ^ 8)) ∧ + (∀ v : α → Prop, Holds F v ↔ ∃ H ∈ L, Holds H v) ∧ + (L.length : ℝ) ≤ (2 : ℝ) ^ ((N : ℝ) / j) := by + obtain ⟨L, hL, hv, hc⟩ := sparsification_parameter F hw (12 * j) (by omega) + refine ⟨L, ?_, hv, ?_⟩ + · simpa only [hα] using hL + · exact (by simpa only [hα] using hc : + (L.length : ℝ) ≤ branchBase (12 * j) ^ (3 * (2 * N) * (12 * j) ^ 2)).trans + (indexed_rate_bound j N hj) + +end Sparsification + +end OAI diff --git a/lean/OAI/Combinatorics/ParityLifts/LeafMachine.lean b/lean/OAI/Combinatorics/ParityLifts/LeafMachine.lean new file mode 100644 index 0000000000000000000000000000000000000000..1d7f8bcd81db95bf5f8452d25aaa8a62021b13c8 --- /dev/null +++ b/lean/OAI/Combinatorics/ParityLifts/LeafMachine.lean @@ -0,0 +1,95 @@ +import OAI.Combinatorics.ParityLifts.RealEval + +namespace OAI + +namespace ParityWL.Complexity + +noncomputable def leafDecisionCode (t : ℕ) [NeZero t] (M : Machine) : FCode := + .seq (TreeProgram.leafOutput t (Nat.pos_of_neZero t)).code + (.seq (simulationCode M) PolyProgram.not.program.code) + +def negateCost : ℕ := PolyProgram.not.program.time false+PolyProgram.not.program.time true+1 + +lemma negate_cost (b : Bool) : PolyProgram.not.program.time b≤negateCost := by + cases b <;> dsimp only [negateCost] <;> omega + +noncomputable def leafTime (t : ℕ) [NeZero t] (F : BitFormula) : ℕ := + (TreeProgram.leafOutput t (Nat.pos_of_neZero t)).time F + +noncomputable def leafCost (t : ℕ) [NeZero t] (M : Machine) (C r : ℝ) (F : BitFormula) : ℝ := + leafTime t F+simulationCoefficient M*(leafTime t F+C*2^(r*leafWords t F)+1)^simulationDegree+negateCost+2 + +lemma power_order_bound (n q m : ℕ) (r : ℝ) (hr : 0≤r) + (hn : n≤(2^q+1)*m) : + (n+1 : ℝ)^r≤(2*(m+1 : ℝ))^r*2^(r*q) := by + have hq : (1 : ℝ)≤(2 : ℝ)^q := one_le_pow₀ (by norm_num) + have hn' : (n : ℝ)≤((2 : ℝ)^q+1)*m := by exact_mod_cast hn + have hh : (n+1 : ℝ)≤2*(m+1 : ℝ)*(2 : ℝ)^q := by + have hm := Nat.cast_nonneg (α:=ℝ) m + nlinarith + calc + (n+1 : ℝ)^r ≤ (2*(m+1 : ℝ)*(2 : ℝ)^q)^r := Real.rpow_le_rpow (by positivity) hh hr + _ = (2*(m+1 : ℝ))^r*((2 : ℝ)^q)^r := Real.mul_rpow (by positivity) (by positivity) + _ = _ := by + rw [←Real.rpow_natCast,←Real.rpow_mul (by norm_num)] + rw [mul_comm (q : ℝ) r] + +lemma TreeProgram.output_length {α β : Type} [TreeCodec α] [TreeCodec β] + {f : α → List β} (P : TreeProgram α (List β) f) (x : α) : + (f x).length ≤ P.time x := by + have h := (treeEncode_list_length (f x)).trans (P.run x).bounds.2.1 + omega + +lemma simulation_after {α : Type} [TreeCodec α] {f : α → List Bool} + (P : TreeProgram α (List Bool) f) (x : α) {M : Machine} {s : ℕ} {b : Bool} + {R : ℝ} (hs : Emits M (f x) s b) (hr : (s : ℝ) ≤ R) : + RBEval (.seq P.code (.seq (simulationCode M) PolyProgram.not.program.code)) + (treeEncode x) + (P.time x+simulationCoefficient M*(P.time x+R+1 : ℝ)^simulationDegree+negateCost+2) + (treeEncode (!b)) := by + have hp := P.run x + have hlen : ((f x).length : ℝ) ≤ P.time x := by exact_mod_cast P.output_length x + have hsim := RBEval.simulation hs hr + have hnot := (PolyProgram.not.program.run b).real.mono + (show (PolyProgram.not.program.time b : ℝ) ≤ negateCost by exact_mod_cast negate_cost b) + apply (hp.real.seq (hsim.seq hnot)).mono + have hbase : 0 ≤ ((f x).length : ℝ)+R+1 := by + have := (Nat.cast_nonneg (α:=ℝ) s).trans hr + positivity + have hpow := pow_le_pow_left₀ hbase (show ((f x).length : ℝ)+R+1 ≤ P.time x+R+1 by linarith) simulationDegree + nlinarith [mul_le_mul_of_nonneg_left hpow (Nat.cast_nonneg (simulationCoefficient M))] + +lemma leafDecision_eval (t : ℕ) [NeZero t] (F : BitFormula) {M : Machine} + {s : ℕ} {b : Bool} {C r : ℝ} + (hs : Emits M (leafOutput t F) s b) (ht : (s : ℝ) ≤ C*2^(r*leafWords t F)) : + RBEval (leafDecisionCode t M) (treeEncode F) (leafCost t M C r F) (treeEncode (!b)) := by + unfold leafDecisionCode leafCost leafTime + exact simulation_after (TreeProgram.leafOutput t (Nat.pos_of_neZero t)) F hs ht + +lemma leafMachine_run (k : ℕ) (hk : 4≤k) (c : Convention) + [NeZero (bagParameter c k)] (i : Implementation) (M : Machine) (r : ℝ) + (hr : 0≤r) (hm : FixedWLBound M c i k r) : + ∃ C : ℝ, 0 simp_all +end ParityWL.Complexity + +end OAI diff --git a/lean/OAI/Combinatorics/ParityLifts/LeafProducer.lean b/lean/OAI/Combinatorics/ParityLifts/LeafProducer.lean new file mode 100644 index 0000000000000000000000000000000000000000..2f45ec1bd503316da1b904f32629fd98dbc7b1f9 --- /dev/null +++ b/lean/OAI/Combinatorics/ParityLifts/LeafProducer.lean @@ -0,0 +1,87 @@ +import OAI.Combinatorics.ParityLifts.GraphOutput + +namespace OAI + +namespace ParityWL.Complexity + +def leafWords (t : ℕ) (F : BitFormula) : ℕ := 3*chunkWidth t F + +def leafData (t : ℕ) (F : BitFormula) : ChoiceData t := bitChoiceData (bitGroup t F) (leafWords t F) + +noncomputable def leafOutput (t : ℕ) (F : BitFormula) : List Bool := + (choiceWithWords (bitGroup t F,leafWords t F,words (leafWords t F))).output + +noncomputable def PolyProgram.leafWords (t : ℕ) (ht : 0 (Complexity.bitGroup t F,Complexity.leafWords t F)) := + (PolyProgram.bitGroups t ht).pair (PolyProgram.leafWords t ht) + +def TreeProgram.insertWords (t : ℕ) : + TreeProgram ((Fin t → BitFormula) × ℕ) (TableInput t) (fun x => (x.1,x.2,Complexity.words x.2)) := + (TreeProgram.fst (Fin t → BitFormula) ℕ).pair + ((TreeProgram.snd (Fin t → BitFormula) ℕ).pair + ((TreeProgram.snd (Fin t → BitFormula) ℕ).comp TreeProgram.words)) + +noncomputable def PolyProgram.wordsOutput (t : ℕ) [NeZero t] : + PolyProgram (TableInput t) (List Bool) (fun x => (Complexity.choiceWithWords x).output) := + ((PolyProgram.choiceWithWords t).comp (PolyProgram.graphOutput t)).congr (by intro x; rfl) + +def TreeProgram.leafCompose (t : ℕ) + (P : TreeProgram BitFormula ((Fin t → BitFormula) × ℕ) + (fun F => (bitGroup t F,leafWords t F))) + (Q : TreeProgram (TableInput t) (List Bool) (fun x => (choiceWithWords x).output)) : + TreeProgram BitFormula (List Bool) (Complexity.leafOutput t) where + code := .seq (.seq P.code (TreeProgram.insertWords t).code) Q.code + time := fun F => P.time F+(TreeProgram.insertWords t).time (bitGroup t F,leafWords t F)+1+ + Q.time (bitGroup t F,leafWords t F,Complexity.words (leafWords t F))+1 + run := fun F => ((P.run F).seq ((TreeProgram.insertWords t).run (bitGroup t F,leafWords t F))).seq + (Q.run (bitGroup t F,leafWords t F,Complexity.words (leafWords t F))) + +noncomputable def TreeProgram.leafOutput (t : ℕ) [NeZero t] (ht : 0 bitGroup_sat t ht F a) + +lemma leafData_size (t : ℕ) (F : BitFormula) : + (leafData t F).system.SizeAtMost (2^leafWords t F+1) := by + constructor + · intro i + change Fintype.card (Fin _ )≤_ + rw [Fintype.card_fin] + change (List.map _ (satisfyingWords (leafWords t F) (bitGroup t F i))).length≤_ + rw [List.length_map] + exact (List.length_filter_le _ _).trans (by rw [length_words]; omega) + · intro p + change Fintype.card (Fin _)≤_ + rw [Fintype.card_fin] + change (words (leafWords t F)).length+1≤_ + rw [length_words] + +lemma leafOutput_spec (k : ℕ) (hk : 4≤k) (c : Convention) (F : BitFormula) + (hw : ∀ C∈F, C.length≤3) : + ∃ (n : ℕ) (G H : SimpleGraph (Fin n)), + leafOutput (bagParameter c k) F=encodeGraphs G H ∧ + (∀ i, Equivalent G H c i k ↔ ¬ ∃ a, bitSat a F) ∧ + n≤(2^leafWords (bagParameter c k) F+1)*orderFactor (bagParameter c k) := by + let t := bagParameter c k + have ht : 0 simp only [t,bagParameter] <;> omega + obtain ⟨n,G,H,he,hg,hn⟩ := (leafData t F).output_spec k hk c + refine ⟨n,G,H,he,fun i => (hg i).trans (not_congr (leafData_success t ht F hw)),?_⟩ + have hb := choice_lift_order_bound (show 2≤t by cases c <;> simp only [t,bagParameter] <;> omega) + (leafData t F).system (2^leafWords t F+1) (leafData_size t F) (fun _ => 0) + have hc := Fintype.card_congr ((leafData t F).vertexEquiv (fun _ => 0)) + simp only [Fintype.card_fin] at hc + rw [hn,hc] + exact hb + +end ParityWL.Complexity + +end OAI diff --git a/lean/OAI/Combinatorics/ParityLifts/LeafRate.lean b/lean/OAI/Combinatorics/ParityLifts/LeafRate.lean new file mode 100644 index 0000000000000000000000000000000000000000..c5b648ab4a52c7b71ff0d5f20c0c2a678bd43eb7 --- /dev/null +++ b/lean/OAI/Combinatorics/ParityLifts/LeafRate.lean @@ -0,0 +1,99 @@ +import OAI.Combinatorics.ParityLifts.SparseRates + +namespace OAI + +namespace ParityWL.Complexity + +noncomputable def leafSlope (t r : ℕ) : ℝ := 3*(densityFactor r : ℝ)/t + +lemma leafSlope_nonneg (t r : ℕ) : 0 ≤ leafSlope t r := by unfold leafSlope; positivity + +lemma ExpBound.scale {f : ℕ → ℝ} {r : ℝ} (h : ExpBound f r) (C : ℝ) (hC : 0 ≤ C) : + ExpBound (fun n => C*f n) r := by simpa using (ExpBound.const C hC).mul h + +lemma ExpBound.add_const {f : ℕ → ℝ} {r : ℝ} (h : ExpBound f r) (hr : 0 ≤ r) + (C : ℝ) (hC : 0 ≤ C) : ExpBound (fun n => f n+C) r := + h.add_same ((ExpBound.const C hC).mono_rate hr) + +lemma nat_two_exp_cast (E q : ℕ) : ((2^(E*q) : ℕ) : ℝ)=(2 : ℝ)^((E : ℝ)*q) := by + rw [Nat.cast_pow,Nat.cast_ofNat,←Real.rpow_natCast,Nat.cast_mul] + +lemma cost_mono (T U V W A B : ℝ) (d : ℕ) (hT : 0 ≤ T) (hV : 0 ≤ V) + (hA : 0 ≤ A) (ht : T ≤ U) (hv : V ≤ W) : + T+A*(T+V+1)^d+B+2 ≤ U+A*(U+W+1)^d+B+2 := by + have hp := pow_le_pow_left₀ (by positivity : 0 ≤ T+V+1) + (show T+V+1 ≤ U+W+1 by linarith) d + nlinarith [mul_le_mul_of_nonneg_left hp hA] + +lemma leafTime_rate : ∃ E : ℕ, 0 < E ∧ ∀ t : ℕ, ∀ [NeZero t], ∀ R : ℕ, + ∃ T : ℕ → ℝ, ExpBound T ((E : ℝ)*leafSlope t R) ∧ + ∀ N (F : BitFormula), (treeEncode F).size ≤ literalSizeBound N → + F.length ≤ sparseDensity R N → (leafTime t F : ℝ) ≤ T N := by + obtain ⟨E,hE,hB⟩ := leafOutput_bound + refine ⟨E,hE,?_⟩ + intro t _ R + obtain ⟨C,d,hC,hB⟩ := hB t (Nat.pos_of_neZero t) + let T : ℕ → ℝ := fun N => C*(literalSizeBound N+1 : ℝ)^d* + 2^((E : ℝ)*(leafSlope t R*N+6)) + refine ⟨T,?_,?_⟩ + · have hp := sparseSize_rate.add_same (ExpBound.const 1 (by norm_num)) + have hp' := (hp.polypow d).scale (C : ℝ) (Nat.cast_nonneg _) + simpa only [zero_add] using hp'.mul (ExpBound.affine_exp_mul E (leafSlope t R) 6) + · intro N F hsz hlen + have ht := hB F + have hc : (leafTime t F : ℝ) ≤ C*((treeEncode F).size+1 : ℝ)^d* + (2 : ℝ)^((E : ℝ)*leafWords t F) := by + unfold leafTime + rw [←nat_two_exp_cast] + exact_mod_cast ht + have hq := sparse_leafWords_bound t R N (Nat.pos_of_neZero t) F hlen + have hsz' : ((treeEncode F).size : ℝ) ≤ literalSizeBound N := by exact_mod_cast hsz + apply hc.trans + dsimp only [T] + gcongr + · norm_num + · exact hq + +lemma leafCost_rate : ∃ P : ℕ, 0 < P ∧ ∀ t : ℕ, ∀ [NeZero t], ∀ R : ℕ, + ∀ M : Machine, ∀ C r : ℝ, 0 < C → 0 ≤ r → + ∃ W : ℕ → ℝ, ExpBound W ((P : ℝ)*(r+1)*leafSlope t R) ∧ + ∀ N (F : BitFormula), (treeEncode F).size ≤ literalSizeBound N → + F.length ≤ sparseDensity R N → leafCost t M C r F ≤ W N := by + obtain ⟨E,hE,hT⟩ := leafTime_rate + let P := (simulationDegree+1)*(E+1) + refine ⟨P,by dsimp [P]; positivity,?_⟩ + intro t _ R M C r hC hr + obtain ⟨T,hT,hTF⟩ := hT t R + let s := leafSlope t R + have hs : 0 ≤ s := leafSlope_nonneg _ _ + let U : ℕ → ℝ := fun N => C*2^(r*(s*N+6)) + have hU : ExpBound U (r*s) := (ExpBound.affine_exp_mul r s 6).scale C hC.le + let W : ℕ → ℝ := fun N => T N+simulationCoefficient M*(T N+U N+1)^simulationDegree+negateCost+2 + have ha : 0 ≤ (E : ℝ)*s := by positivity + have hb : 0 ≤ r*s := by positivity + have hinner := (hT.add hU ha hb).add_const (by positivity) 1 (by norm_num) + have hpow := (hinner.pow simulationDegree).scale (simulationCoefficient M) (Nat.cast_nonneg _) + have hW := ((hT.add hpow ha (by positivity)).add_const (by positivity) negateCost (Nat.cast_nonneg _)).add_const (by positivity) 2 (by norm_num) + refine ⟨W,hW.mono_rate ?_,?_⟩ + · change (E : ℝ)*s+(simulationDegree : ℝ)*((E : ℝ)*s+r*s) ≤ (P : ℝ)*(r+1)*s + dsimp only [P] + push_cast + have h₁ := mul_nonneg (mul_nonneg (Nat.cast_nonneg (α:=ℝ) E) hr) hs + have h₂ := mul_nonneg (Nat.cast_nonneg (α:=ℝ) simulationDegree) h₁ + have h₃ := mul_nonneg hr hs + nlinarith + · intro N F hsz hlen + have ht := hTF N F hsz hlen + have hq := sparse_leafWords_bound t R N (Nat.pos_of_neZero t) F hlen + have hu : C*2^(r*leafWords t F) ≤ U N := by + dsimp only [U] + apply mul_le_mul_of_nonneg_left _ hC.le + apply Real.rpow_le_rpow_of_exponent_le (by norm_num) + exact mul_le_mul_of_nonneg_left hq hr + exact cost_mono (leafTime t F) (T N) (C*2^(r*leafWords t F)) (U N) + (simulationCoefficient M) negateCost simulationDegree (Nat.cast_nonneg _) + (mul_nonneg hC.le (Real.rpow_nonneg (by norm_num) _)) + (Nat.cast_nonneg _) ht hu +end ParityWL.Complexity + +end OAI diff --git a/lean/OAI/Combinatorics/ParityLifts/LiftCounts.lean b/lean/OAI/Combinatorics/ParityLifts/LiftCounts.lean new file mode 100644 index 0000000000000000000000000000000000000000..71833d896283c57b187bad1dc66d11e247f65b09 --- /dev/null +++ b/lean/OAI/Combinatorics/ParityLifts/LiftCounts.lean @@ -0,0 +1,260 @@ +import OAI.Combinatorics.ParityLifts.Model + +namespace OAI + +namespace ParityWL + +open scoped BigOperators + +section Lifts + +variable {A V : Type} [Fintype A] (T : SimpleGraph A) (G : SimpleGraph V) + + +noncomputable def liftProjection (τ : G →g T) (b : A → Bit) : + liftGraph T G τ b →g G where + toFun := Sigma.fst + map_rel' := fun h => h.1 + +end Lifts + +section LiftCounts + +open scoped Classical + +variable {A V W : Type} [Fintype A] [Fintype V] [Fintype W] +variable (T : SimpleGraph A) (G : SimpleGraph V) (F : SimpleGraph W) +variable (τ : G →g T) (φ : F →g G) + +abbrev Variables := (x : W) → T.neighborSet (τ (φ x)) → Bit + +noncomputable instance variablesFintype : Fintype (Variables T G F τ φ) := by + classical + unfold Variables + infer_instance + +noncomputable def LiftEquations (b : A → Bit) (z : Variables T G F τ φ) : Prop := + (∀ x, ∑ v, z x v = b (τ (φ x))) ∧ + (∀ x y (h : F.Adj x y), + z x ⟨τ (φ y), τ.map_adj (φ.map_adj h)⟩ = + z y ⟨τ (φ x), τ.map_adj (φ.map_adj h.symm)⟩) + +noncomputable def Solutions (b : A → Bit) := + {z : Variables T G F τ φ // LiftEquations T G F τ φ b z} + +noncomputable instance solutionsFintype (b : A → Bit) : + Fintype (Solutions T G F τ φ b) := by + classical + unfold Solutions + infer_instance + +noncomputable def zeroSolution : Solutions T G F τ φ (fun _ => 0) := + ⟨fun _ _ => 0, by classical simp [LiftEquations]⟩ + +noncomputable def solutionHom (b : A → Bit) (z : Solutions T G F τ φ b) : + F →g liftGraph T G τ b where + toFun x := ⟨φ x, ⟨z.1 x, z.2.1 x⟩⟩ + map_rel' := by + intro x y h + exact ⟨φ.map_adj h, z.2.2 x y h⟩ + +noncomputable def homSolutionsEquiv (b : A → Bit) : + (F →g liftGraph T G τ b) ≃ ((φ : F →g G) × Solutions T G F τ φ b) where + toFun f := ⟨(liftProjection T G τ b).comp f, + ⟨fun x => (f x).2.1, + ⟨fun x => (f x).2.2, fun x y h => (f.map_adj h).2⟩⟩⟩ + invFun p := solutionHom T G F τ p.1 b p.2 + left_inv f := by + apply RelHom.ext + intro x + rfl + right_inv p := by + rcases p with ⟨φ, z, hz⟩ + rfl + +noncomputable def homogeneousTranslate (b : A → Bit) (v : Solutions T G F τ φ b) : + Solutions T G F τ φ b ≃ Solutions T G F τ φ (fun _ => 0) where + toFun z := ⟨z.1 - v.1, by + classical + constructor + · intro x + change ∑ w, (z.1 x w - v.1 x w) = 0 + rw [Finset.sum_sub_distrib, z.2.1 x, v.2.1 x, sub_self] + · intro x y h + change z.1 x _ - v.1 x _ = z.1 y _ - v.1 y _ + rw [z.2.2 x y h, v.2.2 x y h]⟩ + invFun z := ⟨z.1 + v.1, by + classical + constructor + · intro x + change ∑ w, (z.1 x w + v.1 x w) = b (τ (φ x)) + rw [Finset.sum_add_distrib, z.2.1 x, v.2.1 x, zero_add] + · intro x y h + change z.1 x _ + v.1 x _ = z.1 y _ + v.1 y _ + rw [z.2.2 x y h, v.2.2 x y h]⟩ + left_inv z := by + apply Subtype.ext + exact sub_add_cancel z.1 v.1 + right_inv z := by + apply Subtype.ext + exact add_sub_cancel_right z.1 v.1 + +omit [Fintype V] in +lemma solutions_card_eq_of_nonempty (b : A → Bit) + (h : Nonempty (Solutions T G F τ φ b)) : + Fintype.card (Solutions T G F τ φ b) = + Fintype.card (Solutions T G F τ φ (fun _ => 0)) := by + obtain ⟨v⟩ := h + exact Fintype.card_congr (homogeneousTranslate T G F τ φ b v) + +omit [Fintype V] in +lemma solutions_card_le (b : A → Bit) : + Fintype.card (Solutions T G F τ φ b) ≤ + Fintype.card (Solutions T G F τ φ (fun _ => 0)) := by + classical + by_cases h : Nonempty (Solutions T G F τ φ b) + · exact (solutions_card_eq_of_nonempty T G F τ φ b h).le + · have : IsEmpty (Solutions T G F τ φ b) := not_nonempty_iff.mp h + simp + +omit [Fintype V] in +lemma solutions_card_eq_iff (b : A → Bit) : + Fintype.card (Solutions T G F τ φ b) = + Fintype.card (Solutions T G F τ φ (fun _ => 0)) ↔ + Nonempty (Solutions T G F τ φ b) := by + constructor + · intro h + have : Nonempty (Solutions T G F τ φ (fun _ => 0)) := + ⟨zeroSolution T G F τ φ⟩ + apply Fintype.card_pos_iff.mp + rw [h] + exact Fintype.card_pos + · exact solutions_card_eq_of_nonempty T G F τ φ b + +noncomputable def homCount {U : Type} [Fintype U] (H : SimpleGraph U) : ℕ := by + classical + exact Fintype.card (F →g H) + +lemma homCount_lift (b : A → Bit) : + homCount F (liftGraph T G τ b) = + ∑ φ : F →g G, Fintype.card (Solutions T G F τ φ b) := by + classical + unfold homCount + rw [Fintype.card_congr (homSolutionsEquiv T G F τ b), Fintype.card_sigma] + +/-- Noncancellation for every uncolored homomorphism, not just typed witnesses. -/ +theorem homCount_lift_le (b : A → Bit) : + homCount F (liftGraph T G τ b) ≤ homCount F (liftGraph T G τ (fun _ => 0)) := by + classical + rw [homCount_lift T G F τ b, homCount_lift T G F τ (fun _ => 0)] + exact Finset.sum_le_sum (fun φ _ => solutions_card_le T G F τ φ b) + + +lemma homCount_lift_eq_iff (b : A → Bit) : + homCount F (liftGraph T G τ b) = homCount F (liftGraph T G τ (fun _ => 0)) ↔ + ∀ φ : F →g G, Nonempty (Solutions T G F τ φ b) := by + classical + rw [homCount_lift T G F τ b, homCount_lift T G F τ (fun _ => 0), + Finset.sum_eq_sum_iff_of_le (fun φ _ => solutions_card_le T G F τ φ b)] + simp only [Finset.mem_univ, forall_const, solutions_card_eq_iff] + +/-- A strict uncolored count gap comes from an inconsistent projected system. -/ +theorem homCount_lift_strict_iff (b : A → Bit) : + homCount F (liftGraph T G τ b) < homCount F (liftGraph T G τ (fun _ => 0)) ↔ + ∃ φ : F →g G, ¬ Nonempty (Solutions T G F τ φ b) := by + have hle := homCount_lift_le T G F τ b + have heq := homCount_lift_eq_iff T G F τ b + constructor + · intro h + by_contra hn + push Not at hn + have := heq.mpr hn + omega + · rintro ⟨φ, hφ⟩ + have hn : homCount F (liftGraph T G τ b) ≠ + homCount F (liftGraph T G τ (fun _ => 0)) := fun h => hφ (heq.mp h φ) + omega + +abbrev EquationRow := W ⊕ F.Dart + +noncomputable def constraintMap : + Variables T G F τ φ →ₗ[Bit] (EquationRow F → Bit) where + toFun z := fun row => match row with + | .inl x => ∑ v, z x v + | .inr d => + z d.fst ⟨τ (φ d.snd), τ.map_adj (φ.map_adj d.adj)⟩ + + z d.snd ⟨τ (φ d.fst), τ.map_adj (φ.map_adj d.adj.symm)⟩ + map_add' z w := by + funext row + cases row with + | inl x => exact Finset.sum_add_distrib + | inr d => dsimp; ring + map_smul' a z := by + funext row + cases row with + | inl x => + change (∑ v, a * z x v) = a * ∑ v, z x v + exact (Finset.mul_sum ..).symm + | inr d => dsimp; ring + +noncomputable def constraintRHS (b : A → Bit) : EquationRow F → Bit + | .inl x => b (τ (φ x)) + | .inr _ => 0 + +omit [Fintype V] [Fintype W] in +lemma liftEquations_iff (b : A → Bit) (z : Variables T G F τ φ) : + LiftEquations T G F τ φ b z ↔ + constraintMap T G F τ φ z = constraintRHS T G F τ φ b := by + constructor + · rintro ⟨hvertex, hedge⟩ + funext row + cases row with + | inl x => exact hvertex x + | inr d => + change z d.fst _ + z d.snd _ = 0 + rw [hedge d.fst d.snd d.adj, CharTwo.add_self_eq_zero] + · intro h + constructor + · intro x + exact congrFun h (.inl x) + · intro x y hxy + have he := congrFun h (.inr ⟨(x, y), hxy⟩) + change z x _ + z y _ = 0 at he + rwa [← CharTwo.sub_eq_add, sub_eq_zero] at he + +end LiftCounts + +section BinaryDuality + +variable {E H : Type} [AddCommGroup E] [Module Bit E] [AddCommGroup H] [Module Bit H] + +lemma bit_zero_or_one (b : Bit) : b = 0 ∨ b = 1 := by + have h : ∀ b : Bit, b = 0 ∨ b = 1 := by decide + exact h b + +/-- Linear-algebra separation without a rank assumption. -/ +theorem binary_alternative (L : E →ₗ[Bit] H) (c : H) : + (¬ ∃ z, L z = c) ↔ + ∃ f : H →ₗ[Bit] Bit, (∀ z, f (L z) = 0) ∧ f c = 1 := by + classical + constructor + · intro h + have hc : c ∉ LinearMap.range L := h + obtain ⟨f, hf, hmap⟩ := + Submodule.exists_dual_map_eq_bot_of_notMem hc inferInstance + refine ⟨f, ?_, ?_⟩ + · intro z + have hz : f (L z) ∈ (LinearMap.range L).map f := + ⟨L z, ⟨z, rfl⟩, rfl⟩ + rwa [hmap, Submodule.mem_bot] at hz + · exact (bit_zero_or_one (f c)).resolve_left hf + · rintro ⟨f, hf, hc⟩ ⟨z, hz⟩ + have h := hf z + rw [hz, hc] at h + exact one_ne_zero h + +end BinaryDuality + +end ParityWL + +end OAI diff --git a/lean/OAI/Combinatorics/ParityLifts/ListPrograms.lean b/lean/OAI/Combinatorics/ParityLifts/ListPrograms.lean new file mode 100644 index 0000000000000000000000000000000000000000..701a9def88da4459cb37c75880a693c3a33939e2 --- /dev/null +++ b/lean/OAI/Combinatorics/ParityLifts/ListPrograms.lean @@ -0,0 +1,139 @@ +import OAI.Combinatorics.ParityLifts.Words + +namespace OAI + +namespace ParityWL.Complexity + +def PolyProgram.recode {α β γ : Type} [TreeCodec α] [TreeCodec β] [TreeCodec γ] + {f : α → β} {g : α → γ} (P : PolyProgram α β f) + (h : ∀ x, treeEncode (f x) = treeEncode (g x)) : PolyProgram α γ g where + program := { + code := P.program.code + time := P.program.time + run := fun x => by rw [← h x]; exact P.program.run x } + coefficient := P.coefficient + degree := P.degree + bound := P.bound + +def PolyProgram.tabulate {α β : Type} [TreeCodec α] [TreeCodec β] {n : ℕ} + {f : Fin n × α → β} (P : PolyProgram (Fin n × α) β f) : + PolyProgram α (Fin n → β) (fun x i => f (i,x)) := by + let Q := ((PolyProgram.const (List.ofFn (_root_.id : Fin n → Fin n))).pair (PolyProgram.id α)).comp P.mapWith + refine Q.recode ?_ + intro x + change treeEncode ((List.ofFn (_root_.id : Fin n → Fin n)).map (fun i => f (i,x))) = _ + simp only [List.map_ofFn] + rfl + +def PolyProgram.filterWith {α γ : Type} [TreeCodec α] [TreeCodec γ] {f : α × γ → Bool} + (P : PolyProgram (α × γ) Bool f) : + PolyProgram (List α × γ) (List α) (fun x => x.1.filter (fun a => f (a,x.2))) := by + let R := (PolyProgram.fst α γ).pair P + let Q : PolyProgram (α × Bool) Bool Prod.snd := PolyProgram.snd α Bool + refine (R.mapWith.comp Q.filter |>.comp (PolyProgram.fst α Bool).map).congr ?_ + intro x + simp [List.filter_map, Function.comp_def] + +noncomputable def PolyProgram.mem (α : Type) [TreeCodec α] [DecidableEq α] : + PolyProgram (α × List α) Bool (fun x => decide (x.1∈x.2)) := by + let swap : PolyProgram (α × List α) (List α × α) (fun x => (x.2,x.1)) := + .expr (.pair TExpr.input.right TExpr.input.left) (by intro x; rfl) + refine (swap.comp (PolyProgram.equal α).mapWith |>.comp (PolyProgram.id Bool).any).congr ?_ + intro x + simp only [Function.comp_apply, List.any_map] + change x.2.any (fun a => decide (a=x.1)) = decide (x.1∈x.2) + apply Bool.eq_iff_iff.mpr + simp only [List.any_eq_true, decide_eq_true_eq] + exact ⟨fun ⟨a,ha,he⟩ => he ▸ ha, fun h => ⟨x.1,h,rfl⟩⟩ + +noncomputable def PolyProgram.subset (α : Type) [TreeCodec α] [DecidableEq α] : + PolyProgram (List α × List α) Bool (fun x => decide (∀ a∈x.1, a∈x.2)) := by + refine ((PolyProgram.mem α).mapWith.comp (PolyProgram.id Bool).all).congr ?_ + intro x + apply Bool.eq_iff_iff.mpr + simp [List.all_map, List.all_eq_true] + +lemma fold_dedup_append {α : Type} [DecidableEq α] (xs acc : List α) : + (xs.foldl (fun s a => if a∈s then s else a::s) acc).toFinset = xs.toFinset ∪ acc.toFinset := by + induction xs generalizing acc with + | nil => simp + | cons a xs ih => + rw [List.foldl_cons, ih] + by_cases ha : a∈acc + · simp [ha, Finset.insert_union, Finset.insert_eq_of_mem (Finset.mem_union_right _ (List.mem_toFinset.mpr ha))] + · simp [ha, Finset.union_insert, Finset.insert_union] + +noncomputable def dedupList {α : Type} [DecidableEq α] (xs : List α) : List α := + xs.foldl (fun s a => if a∈s then s else a::s) [] + +@[simp] lemma dedupList_toFinset {α : Type} [DecidableEq α] (xs : List α) : + (dedupList xs).toFinset = xs.toFinset := by simp [dedupList,fold_dedup_append] + +noncomputable def PolyProgram.dedup (α : Type) [TreeCodec α] [DecidableEq α] : + PolyProgram (List α) (List α) dedupList := by + let P := (PolyProgram.mem α).ite (PolyProgram.snd α (List α)) (PolyProgram.cons α) + have hg (a : α) (xs : List α) : + (treeEncode (if decide (a∈xs) then xs else a::xs)).size ≤ + (treeEncode xs).size+1*((treeEncode a).size+1)^1 := by + split <;> simp [DataTree.size] + all_goals omega + let F := P.foldlGrowing 1 1 hg + refine (((PolyProgram.id (List α)).pair (PolyProgram.const ([]:List α))).comp F).congr ?_ + intro xs + simp only [decide_eq_true_eq] + rfl + +/-- First-index search, expressed by one polynomial fold rather than an oracle. -/ +def findIndex {α : Type} (p : α → Bool) (xs : List α) : ℕ := xs.takeWhile (fun x => !p x) |>.length + +lemma findIndex_nil {α : Type} (p : α → Bool) : findIndex p []=0 := rfl +lemma findIndex_cons {α : Type} (p : α → Bool) (a : α) (xs : List α) : + findIndex p (a::xs) = if p a then 0 else 1+findIndex p xs := by + cases h : p a <;> simp [findIndex, h, Nat.add_comm] + +lemma fold_findIndex {α : Type} (p : α → Bool) (xs : List α) (n : ℕ) : + xs.foldr (fun a n => if p a then 0 else n+1) n = + if xs.any p then findIndex p xs else n+xs.length := by + induction xs with + | nil => simp + | cons a xs ih => + cases h : p a <;> cases h' : xs.any p <;> + simp [h,h',List.foldr_cons,ih,findIndex_cons] <;> omega + +lemma findIndex_eq_length {α : Type} (p : α → Bool) (xs : List α) (h : xs.any p=false) : + findIndex p xs=xs.length := by + induction xs with + | nil => rfl + | cons a xs ih => + have hp : p a=false ∧ xs.any p=false := by simpa using h + simp [findIndex_cons,hp.1,ih hp.2,Nat.add_comm] + +lemma findIndex_le {α : Type} (p : α → Bool) (xs : List α) : findIndex p xs≤xs.length := by + exact (List.takeWhile_sublist ..).length_le + +noncomputable def PolyProgram.findIndexWith {α γ : Type} [TreeCodec α] [TreeCodec γ] + {p : α × γ → Bool} (P : PolyProgram (α × γ) Bool p) : + PolyProgram (List α × γ) ℕ (fun x => findIndex (fun a => p (a,x.2)) x.1) := by + let S := (PolyProgram.fst Bool ℕ).ite (PolyProgram.const 0) + ((PolyProgram.snd Bool ℕ).comp PolyProgram.natSucc) + have hg (b : Bool) (n : ℕ) : + (treeEncode (if b then 0 else n+1)).size ≤ (treeEncode n).size+2*((treeEncode b).size+1)^0 := by + cases b <;> simp + all_goals omega + let F := S.foldlGrowing 2 0 hg + let Q := ((P.mapWith.comp (PolyProgram.reverse Bool)).pair (PolyProgram.const 0)).comp F + refine Q.congr ?_ + intro x + change ((x.1.map (fun a => p (a,x.2))).reverse.foldl (fun n b => if b then 0 else n+1) 0)=_ + rw [← List.foldr_eq_foldl_reverse] + rw [List.foldr_map] + rw [fold_findIndex] + split + · rfl + · rename_i h + have hh : x.1.any (fun a => p (a,x.2))=false := Bool.eq_false_iff.mpr h + simpa using (findIndex_eq_length _ _ hh).symm + +end ParityWL.Complexity + +end OAI diff --git a/lean/OAI/Combinatorics/ParityLifts/Machines.lean b/lean/OAI/Combinatorics/ParityLifts/Machines.lean new file mode 100644 index 0000000000000000000000000000000000000000..ae5c9cdafbf42bda2b53078185ab23b0ffbf2485 --- /dev/null +++ b/lean/OAI/Combinatorics/ParityLifts/Machines.lean @@ -0,0 +1,164 @@ +import OAI.Combinatorics.ParityLifts.Main + +namespace OAI + +namespace ParityWL + +/-! Finite-alphabet deterministic multitape model. +A transition reads and writes only the currently scanned +cell on each tape and moves each head by at most one cell. -/ +namespace Complexity + +inductive Move | left | stay | right + deriving DecidableEq + +instance : Fintype Move := + ⟨{Move.left, Move.stay, Move.right}, by intro x; cases x <;> simp⟩ + +def Move.offset : Move → ℤ + | .left => -1 + | .stay => 0 + | .right => 1 + +/-- Blank is 0, input bits are 1 and 2. Every work alphabet, state space and +collection of tapes is finite. Tapes are two-way infinite. -/ +structure Machine where + tapes : ℕ + extraSymbols : ℕ + extraStates : ℕ + initial : Fin (extraStates + 1) + output : Fin (extraStates + 1) → Option Bool + transition : Fin (extraStates + 1) → + (Fin (tapes + 1) → Fin (extraSymbols + 3)) → + Fin (extraStates + 1) × (Fin (tapes + 1) → Fin (extraSymbols + 3) × Move) + +structure Configuration (M : Machine) where + state : Fin (M.extraStates + 1) + head : Fin (M.tapes + 1) → ℤ + tape : Fin (M.tapes + 1) → ℤ → Fin (M.extraSymbols + 3) + +def inputSymbol (M : Machine) (b : Bool) : Fin (M.extraSymbols + 3) := + if b then ⟨2, by omega⟩ else ⟨1, by omega⟩ + +def initialConfiguration (M : Machine) (input : List Bool) : Configuration M where + state := M.initial + head := fun _ => 0 + tape := fun i z => if i.val = 0 ∧ 0 ≤ z then + match input[z.toNat]? with + | some b => inputSymbol M b + | none => 0 + else 0 + +def step (M : Machine) (x : Configuration M) : Configuration M := + match M.output x.state with + | some _ => x + | none => + let a := M.transition x.state (fun i => x.tape i (x.head i)) + { state := a.1 + head := fun i => x.head i + (a.2 i).2.offset + tape := fun i z => if z = x.head i then (a.2 i).1 else x.tape i z } + +def run (M : Machine) (input : List Bool) (s : ℕ) : Configuration M := + (step M)^[s] (initialConfiguration M input) + +def Emits (M : Machine) (input : List Bool) (s : ℕ) (b : Bool) : Prop := + M.output (run M input s).state = some b + + +end Complexity +end ParityWL + +namespace ParityWL.Complexity + +/-- A finite-control presentation of the very same local multitape model. +`packed` below changes ONLY the names of states, with zero simulation cost. -/ +structure LocalMachine (Q : Type) (t a : ℕ) where + initial : Q + output : Q → Option Bool + transition : Q → (Fin (t + 1) → Fin (a + 3)) → + Q × (Fin (t + 1) → Fin (a + 3) × Move) + +structure LocalConfiguration (Q : Type) (t a : ℕ) where + state : Q + head : Fin (t + 1) → ℤ + tape : Fin (t + 1) → ℤ → Fin (a + 3) + +def localInputSymbol (a : ℕ) (b : Bool) : Fin (a + 3) := + if b then ⟨2, by omega⟩ else ⟨1, by omega⟩ + +def LocalMachine.initialConfiguration {Q : Type} {t a : ℕ} + (P : LocalMachine Q t a) (input : List Bool) : LocalConfiguration Q t a where + state := P.initial + head := fun _ => 0 + tape := fun i z => if i.val = 0 ∧ 0 ≤ z then + match input[z.toNat]? with + | some b => localInputSymbol a b + | none => 0 + else 0 + +def LocalMachine.step {Q : Type} {t a : ℕ} (P : LocalMachine Q t a) + (x : LocalConfiguration Q t a) : LocalConfiguration Q t a := + match P.output x.state with + | some _ => x + | none => + let b := P.transition x.state (fun i => x.tape i (x.head i)) + { state := b.1 + head := fun i => x.head i + (b.2 i).2.offset + tape := fun i z => if z = x.head i then (b.2 i).1 else x.tape i z } + +def LocalMachine.run {Q : Type} {t a : ℕ} (P : LocalMachine Q t a) + (input : List Bool) (s : ℕ) : LocalConfiguration Q t a := + P.step^[s] (P.initialConfiguration input) + +noncomputable def LocalMachine.stateEquiv {Q : Type} [Fintype Q] {t a : ℕ} + (P : LocalMachine Q t a) : Q ≃ Fin (Fintype.card Q - 1 + 1) := by + have hcard : 0 < Fintype.card Q := Fintype.card_pos_iff.mpr ⟨P.initial⟩ + exact Fintype.equivFinOfCardEq (by omega) + +noncomputable def LocalMachine.packed {Q : Type} [Fintype Q] {t a : ℕ} + (P : LocalMachine Q t a) : Machine where + tapes := t + extraSymbols := a + extraStates := Fintype.card Q - 1 + initial := P.stateEquiv P.initial + output := fun q => P.output (P.stateEquiv.symm q) + transition := fun q x => let b := P.transition (P.stateEquiv.symm q) x + (P.stateEquiv b.1, b.2) + +noncomputable def LocalMachine.packConfiguration {Q : Type} [Fintype Q] {t a : ℕ} + (P : LocalMachine Q t a) (x : LocalConfiguration Q t a) : Configuration P.packed where + state := P.stateEquiv x.state + head := x.head + tape := x.tape + +lemma LocalMachine.pack_initial {Q : Type} [Fintype Q] {t a : ℕ} + (P : LocalMachine Q t a) (input : List Bool) : + P.packConfiguration (P.initialConfiguration input) = Complexity.initialConfiguration P.packed input := by + rfl + +lemma LocalMachine.pack_step {Q : Type} [Fintype Q] {t a : ℕ} + (P : LocalMachine Q t a) (x : LocalConfiguration Q t a) : + P.packConfiguration (P.step x) = Complexity.step P.packed (P.packConfiguration x) := by + simp only [LocalMachine.step, Complexity.step, LocalMachine.packConfiguration, LocalMachine.packed, + Equiv.symm_apply_apply] + cases h : P.output x.state <;> rfl + +lemma LocalMachine.pack_run {Q : Type} [Fintype Q] {t a : ℕ} + (P : LocalMachine Q t a) (input : List Bool) (s : ℕ) : + P.packConfiguration (P.run input s) = Complexity.run P.packed input s := by + induction s with + | zero => exact P.pack_initial input + | succ s ih => + simpa only [LocalMachine.run, Complexity.run, Function.iterate_succ_apply', P.pack_step] using + congrArg (Complexity.step P.packed) ih + +lemma LocalMachine.packed_emits {Q : Type} [Fintype Q] {t a : ℕ} + (P : LocalMachine Q t a) (input : List Bool) (s : ℕ) (b : Bool) : + Emits P.packed input s b ↔ P.output (P.run input s).state = some b := by + unfold Emits + rw [← P.pack_run] + simp only [LocalMachine.packed, LocalMachine.packConfiguration, Equiv.symm_apply_apply] + +end ParityWL.Complexity + +end OAI diff --git a/lean/OAI/Combinatorics/ParityLifts/Main.lean b/lean/OAI/Combinatorics/ParityLifts/Main.lean new file mode 100644 index 0000000000000000000000000000000000000000..b199a12418a6f4dd4c658b8fefc06a403d9281dd --- /dev/null +++ b/lean/OAI/Combinatorics/ParityLifts/Main.lean @@ -0,0 +1,114 @@ +import OAI.Combinatorics.ParityLifts.PureComponents + +namespace OAI + +namespace ParityWL + +open scoped BigOperators + +section PureTotals + +open scoped Classical + +variable {k t : ℕ} (F : RootedTest k t) +variable {V W : Type} (G : SimpleGraph V) (H : SimpleGraph W) + +noncomputable def pureLeftTotalEquiv : + ((x : Fin k → V) × F.Maps (G.sum H) (Sum.inl ∘ x)) ≃ PureLeftMaps F G H where + toFun f := ⟨f.2.1, fun i => by rw [f.2.2 i]; rfl⟩ + invFun f := ⟨fun i => (f.1.1 (F.roots i)).getLeft (f.2 i), + ⟨f.1, fun i => (Sum.inl_getLeft _ _).symm⟩⟩ + left_inv f := by + rcases f with ⟨x, f, hf⟩ + have hx : (fun i => (f.1 (F.roots i)).getLeft (by rw [hf i]; rfl)) = x := by + funext i + exact (Sum.getLeft_eq_iff _).mpr (hf i) + dsimp only + apply Sigma.ext hx + apply (Subtype.heq_iff_coe_eq (fun g => by dsimp only; rw [hx])).mpr + rfl + right_inv _ := rfl + +lemma sum_pureLeft_count [Fintype V] [Fintype W] : + ∑ x : Fin k → V, F.count (G.sum H) (Sum.inl ∘ x) = + (Fintype.card (PureLeftMaps F G H) : ℚ) := by + unfold RootedTest.count + rw [← Nat.cast_sum, ← Fintype.card_sigma, Fintype.card_congr (pureLeftTotalEquiv F G H)] + +noncomputable def rootedMapsIso {U : Type} {K : SimpleGraph U} (e : G ≃g K) (x : Fin k → V) : + F.Maps G x ≃ F.Maps K (e ∘ x) where + toFun f := ⟨⟨e ∘ f.1.1, fun a b hab => e.map_adj_iff.mpr (f.1.2 a b hab)⟩, + fun i => congrArg e (f.2 i)⟩ + invFun f := ⟨⟨e.symm ∘ f.1.1, fun a b hab => e.symm.map_adj_iff.mpr (f.1.2 a b hab)⟩, + fun i => by simpa only [Function.comp_apply, e.symm_apply_apply] using congrArg e.symm (f.2 i)⟩ + left_inv f := by + apply Subtype.ext + apply Subtype.ext + funext a + exact e.symm_apply_apply _ + right_inv f := by + apply Subtype.ext + apply Subtype.ext + funext a + exact e.apply_symm_apply _ + +lemma count_pureRight_swap [Fintype V] [Fintype W] (x : Fin k → W) : + F.count (G.sum H) (Sum.inr ∘ x) = F.count (H.sum G) (Sum.inl ∘ x) := by + have he := Fintype.card_congr (rootedMapsIso F (G.sum H) + (SimpleGraph.Iso.sumComm : G.sum H ≃g H.sum G) (Sum.inr ∘ x)) + exact congrArg (fun n : ℕ => (n : ℚ)) he + +lemma sum_pureRight_count [Fintype V] [Fintype W] : + ∑ x : Fin k → W, F.count (G.sum H) (Sum.inr ∘ x) = + (Fintype.card (PureLeftMaps F H G) : ℚ) := by + simp only [count_pureRight_swap, sum_pureLeft_count] + +lemma no_choice_equal_pure_total (C : ChoiceSystem t) (ht : 0 < t) (hn : ¬ C.Successful) : + ∑ x, F.count ((zeroLift C).sum (starLift C)) (Sum.inl ∘ x) = + ∑ x, F.count ((zeroLift C).sum (starLift C)) (Sum.inr ∘ x) := by + rw [sum_pureLeft_count, sum_pureRight_count, pureLeft_card, pureLeft_card] + apply congrArg (fun n : ℕ => (n : ℚ)) + apply Finset.sum_congr rfl + intro s _ + have hl := no_choice_equal_relation C ht hn + (fun a b : MaskLeft F s => F.relation a.1 b.1) + ⟨fun a b h => F.symmetric.symm a.1 b.1 h⟩ (F.tree.induce (fun a => s.1 a = true)) + have hr := no_choice_equal_relation C ht hn + (fun a b : MaskRight F s => F.relation a.1 b.1) + ⟨fun a b h => F.symmetric.symm a.1 b.1 h⟩ (F.tree.induce (fun a => s.1 a = false)) + rw [hl, hr] + +end PureTotals + +theorem no_choice_pure_equivalent (k : ℕ) (hk : 4 ≤ k) (c : Convention) + (C : ChoiceSystem (bagParameter c k)) (hn : ¬ C.Successful) : + PureWLEquivalent (zeroLift C) (starLift C) c k := by + classical + intro r + let U := (zeroLift C).sum (starLift C) + cases c with + | joint => + exact histograms_eq_of_tests U U + (fun x => Sum.inl (Sum.inl ∘ x)) (fun x => Sum.inr (Sum.inr ∘ x)) + (pairJoint U U k r) (joint_indicator_mem _ _ (t := k+1) le_rfl r) + (fun F => no_choice_equal_pure_total F C (by omega) hn) + | separate => + exact histograms_eq_of_tests U U + (fun x => Sum.inl (Sum.inl ∘ x)) (fun x => Sum.inr (Sum.inr ∘ x)) + (pairSeparate U U k r) (separate_indicator_mem _ _ (t := k) le_rfl r) + (fun F => no_choice_equal_pure_total F C (by omega) hn) + +/-- The parity reduction on the explicitly constructed +uncolored simple lifts, including empty choice domains. -/ +theorem parity_reduction : ParityReductionStatement := by + intro k hk c C + have ht : 2 ≤ bagParameter c k := by cases c <;> simp only [bagParameter] <;> omega + refine ⟨choice_lifts_equal_order ht C, ?_, ?_, ?_, successful_detected k hk c C⟩ + · intro A _ hA + exact choice_lift_order_bound ht C A hA (fun _ => 0) + · exact ⟨equivalent_no_choice k hk c C, no_choice_equivalent k hk c C⟩ + · exact ⟨pure_equivalent_no_choice k hk c C, no_choice_pure_equivalent k hk c C⟩ + +end ParityWL + +end OAI diff --git a/lean/OAI/Combinatorics/ParityLifts/Masses.lean b/lean/OAI/Combinatorics/ParityLifts/Masses.lean new file mode 100644 index 0000000000000000000000000000000000000000..f3434f45541ca7098312dcbfb6d1e331874db9d5 --- /dev/null +++ b/lean/OAI/Combinatorics/ParityLifts/Masses.lean @@ -0,0 +1,256 @@ +import OAI.Combinatorics.ParityLifts.WeightedDual + +namespace OAI + +namespace ParityWL + +open scoped BigOperators + +section Masses + +open scoped Classical + +variable {A W : Type} [Fintype W] +variable {T : SimpleGraph A} {F : SimpleGraph W} {a : F →g T} {b : A → Bit} + +noncomputable def WeightedWitness.mass (w : WeightedWitness T F a b) + (Y : Finset W) (u : A) : Bit := + ∑ x ∈ Y, if a x = u then w.vertex x else 0 + +lemma WeightedWitness.coordinate_mass (w : WeightedWitness T F a b) + {u v : A} (huv : T.Adj u v) (Y : Finset W) : + w.mass Y u = ∑ x ∈ Y, ∑ y, + if a x = u ∧ a y = v then w.edge x y else 0 := by + apply Finset.sum_congr rfl + intro x _ + by_cases hx : a x = u + · have h := w.coordinate x ⟨v, hx ▸ huv⟩ + simpa [hx] using h.symm + · simp [hx] + +lemma WeightedWitness.mass_univ_adj (w : WeightedWitness T F a b) + {u v : A} (huv : T.Adj u v) : + w.mass Finset.univ u = w.mass Finset.univ v := by + rw [w.coordinate_mass huv, w.coordinate_mass huv.symm, Finset.sum_comm] + apply Finset.sum_congr rfl + intro x _ + apply Finset.sum_congr rfl + intro y _ + simp [and_comm, w.symmetric] + +lemma WeightedWitness.mass_union (w : WeightedWitness T F a b) + (X Y : Finset W) (h : Disjoint X Y) (u : A) : + w.mass (X ∪ Y) u = w.mass X u + w.mass Y u := + Finset.sum_union h + +lemma WeightedWitness.mass_eq_zero (w : WeightedWitness T F a b) + (Y : Finset W) (u : A) (h : ∀ x ∈ Y, a x ≠ u) : w.mass Y u = 0 := by + apply Finset.sum_eq_zero + intro x hx + simp [h x hx] + +lemma WeightedWitness.mass_univ_reachable (w : WeightedWitness T F a b) + {u v : A} (h : T.Reachable u v) : + w.mass Finset.univ u = w.mass Finset.univ v := by + obtain ⟨p⟩ := h + induction p with + | nil => rfl + | @cons x y z h p ih => exact (w.mass_univ_adj h).trans ih + +/-- Two types absent from the boundary of a separated vertex set have equal mass. -/ +lemma WeightedWitness.mass_separator (w : WeightedWitness T F a b) + {u v : A} (huv : T.Adj u v) (Y S : Finset W) + (hboundary : ∀ x ∈ Y, ∀ y, F.Adj x y → y ∉ Y → y ∈ S) + (hu : ∀ x ∈ S, a x ≠ u) (hv : ∀ x ∈ S, a x ≠ v) : + w.mass Y u = w.mass Y v := by + have restrict : ∀ (q r : A), T.Adj q r → (∀ x ∈ S, a x ≠ r) → + w.mass Y q = ∑ x ∈ Y, ∑ y ∈ Y, + if a x = q ∧ a y = r then w.edge x y else 0 := by + intro q r hqr hr + rw [w.coordinate_mass hqr] + apply Finset.sum_congr rfl + intro x hx + symm + apply Finset.sum_subset (Finset.subset_univ _) + intro y _ hy + by_cases hy' : a y = r + · have hn : ¬ F.Adj x y := fun hxy => hr y (hboundary x hx y hxy hy) hy' + simp [w.supported x y hn] + · simp [hy'] + rw [restrict u v huv hv, restrict v u huv.symm hu, Finset.sum_comm] + apply Finset.sum_congr rfl + intro x _ + apply Finset.sum_congr rfl + intro y _ + simp [and_comm, w.symmetric] + +end Masses + +section TemplateMass + +open scoped Classical + +lemma starParity_value {t : ℕ} (ht : 0 < t) (u : TemplateVertex t) : + starParity t u = if u = .inl ⟨0, ht⟩ then 1 else 0 := by + have hi : ∀ i : Fin t, i.val = 0 ↔ i = ⟨0, ht⟩ := by + intro i + exact (Fin.ext_iff (a := i) (b := ⟨0, ht⟩)).symm + simp [starParity, hi] + +variable {t : ℕ} {W : Type} [Fintype W] {F : SimpleGraph W} +variable {a : F →g template t} + +lemma WeightedWitness.main_mass (w : WeightedWitness (template t) F a (starParity t)) + (ht : 0 < t) (i : Fin t) : w.mass Finset.univ (.inl i) = 1 := by + have hz : w.mass Finset.univ (.inl ⟨0, ht⟩) = 1 := by + calc + _ = ∑ x, w.vertex x * starParity t (a x) := by + apply Finset.sum_congr rfl + intro x _ + rw [starParity_value ht] + by_cases h : a x = .inl ⟨0, ht⟩ <;> simp [h] + _ = 1 := w.odd + by_cases hi : i = ⟨0, ht⟩ + · simpa [hi] using hz + · have := w.mass_univ_adj (u := .inl i) (v := .inl ⟨0, ht⟩) hi + exact this.trans hz + +lemma WeightedWitness.template_mass (w : WeightedWitness (template t) F a (starParity t)) + (ht : 0 < t) (u : TemplateVertex t) : w.mass Finset.univ u = 1 := by + cases u with + | inl i => exact w.main_mass ht i + | inr q => + exact (w.mass_univ_adj (u := .inr q) (v := .inl q.1.1.1.1) (Or.inl rfl)).trans + (w.main_mass ht q.1.1.1.1) + +end TemplateMass + +section BoundaryTests + +open scoped Classical + +variable {A W : Type} [Fintype W] +variable {T : SimpleGraph A} {F : SimpleGraph W} {a : F →g T} {b : A → Bit} + +noncomputable def WeightedWitness.testMass (w : WeightedWitness T F a b) + (Y : Finset W) (u : A) (p : W → Bit) : Bit := + ∑ x ∈ Y, if a x = u then w.vertex x * p x else 0 + +lemma WeightedWitness.testMass_add (w : WeightedWitness T F a b) + (Y : Finset W) (u : A) (p q : W → Bit) : + w.testMass Y u (p + q) = w.testMass Y u p + w.testMass Y u q := by + unfold WeightedWitness.testMass + rw [← Finset.sum_add_distrib] + apply Finset.sum_congr rfl + intro x _ + by_cases h : a x = u <;> simp [h, mul_add] + +lemma WeightedWitness.testMass_one (w : WeightedWitness T F a b) + (Y : Finset W) (u : A) : w.testMass Y u (fun _ => 1) = w.mass Y u := by + simp [WeightedWitness.testMass, WeightedWitness.mass] + +lemma WeightedWitness.testMass_zero (w : WeightedWitness T F a b) + (Y : Finset W) (u : A) (p : W → Bit) + (h : ∀ x ∈ Y, a x = u → p x = 0) : w.testMass Y u p = 0 := by + apply Finset.sum_eq_zero + intro x hx + by_cases ha : a x = u <;> simp [ha, h x hx] + +lemma WeightedWitness.testMass_coordinate (w : WeightedWitness T F a b) + {u v : A} (huv : T.Adj u v) (Y : Finset W) (p : W → Bit) : + w.testMass Y u p = ∑ x ∈ Y, ∑ y, + if a x = u ∧ a y = v then w.edge x y * p x else 0 := by + apply Finset.sum_congr rfl + intro x _ + by_cases hx : a x = u + · have h := w.coordinate x ⟨v, hx ▸ huv⟩ + simp only [hx, ↓reduceIte, true_and] + rw [← h, Finset.sum_mul] + apply Finset.sum_congr rfl + intro y _ + by_cases hy : a y = v <;> simp [hy] + · simp [hx] + +/-- Transfer of a tested type mass across a separator. The test vanishes on its +boundary representatives; target-type vertices are absent from the boundary. +This includes every boundary edge rather than dropping such edges. -/ +lemma WeightedWitness.testMass_transfer (w : WeightedWitness T F a b) + {u v : A} (huv : T.Adj u v) (Y S : Finset W) (p q : W → Bit) + (hboundary : ∀ x ∈ Y, ∀ y, F.Adj x y → y ∉ Y → y ∈ S) + (hv : ∀ x ∈ S, a x ≠ v) + (hp : ∀ x ∈ S, a x = u → p x = 0) + (hcompat : ∀ x y, F.Adj x y → a x = u → a y = v → p x = q y) : + w.testMass Y u p = w.testMass Y v q := by + rw [w.testMass_coordinate huv] + have hr : (∑ x ∈ Y, ∑ y, + if a x = u ∧ a y = v then w.edge x y * p x else 0) = + ∑ x ∈ Y, ∑ y ∈ Y, + if a x = u ∧ a y = v then w.edge x y * p x else 0 := by + apply Finset.sum_congr rfl + intro x hx + symm + apply Finset.sum_subset (Finset.subset_univ _) + intro y _ hy + by_cases hxy : F.Adj x y + · have hn := hv y (hboundary x hx y hxy hy) + simp [hn] + · simp [w.supported x y hxy] + rw [hr, Finset.sum_comm] + have hr' : (∑ y ∈ Y, ∑ x ∈ Y, + if a x = u ∧ a y = v then w.edge x y * p x else 0) = + ∑ y ∈ Y, ∑ x, + if a x = u ∧ a y = v then w.edge x y * p x else 0 := by + apply Finset.sum_congr rfl + intro y hy + apply Finset.sum_subset (Finset.subset_univ _) + intro x _ hx + by_cases hxy : F.Adj y x + · by_cases ha : a x = u + · simp [hp x (hboundary y hy x hxy hx) ha] + · simp [ha] + · have hn : ¬ F.Adj x y := fun h => hxy h.symm + simp [w.supported x y hn] + rw [hr', w.testMass_coordinate huv.symm] + apply Finset.sum_congr rfl + intro y _ + apply Finset.sum_congr rfl + intro x _ + by_cases hx : a x = u + · by_cases hy : a y = v + · simp only [hx, hy, and_self, ↓reduceIte] + by_cases hxy : F.Adj x y + · rw [w.symmetric, hcompat x y hxy hx hy] + · rw [w.supported x y hxy, ← w.symmetric x y, w.supported x y hxy] + simp + · simp [hy] + · simp [hx] + +lemma WeightedWitness.testMass_complement (w : WeightedWitness T F a b) + (Y : Finset W) (u : A) (p : W → Bit) : + w.testMass Y u p + w.testMass Y u (fun x => 1 + p x) = w.mass Y u := by + rw [← w.testMass_add] + have he : p + (fun x => 1 + p x) = fun _ => (1 : Bit) := by + funext x + change p x + (1 + p x) = 1 + rw [add_left_comm, CharTwo.add_self_eq_zero, add_zero] + rw [he, w.testMass_one] + +/-- The global mismatch identity, including arbitrary zero representative weights. -/ +lemma WeightedWitness.global_mismatch (w : WeightedWitness T F a b) + {u v : A} (huv : T.Adj u v) (p q : W → Bit) + (hc : ∀ x y, F.Adj x y → a x = u → a y = v → p x + q y = 1) : + w.testMass Finset.univ u p + w.testMass Finset.univ v q = + w.mass Finset.univ u := by + have ht := w.testMass_transfer huv.symm Finset.univ ∅ q (fun x => 1 + p x) + (by simp) (by simp) (by simp) (by + intro x y hxy hx hy + have he := hc y x hxy.symm hy hx + have hh := congrArg (fun e => p y + e) he + simpa only [← add_assoc, CharTwo.add_self_eq_zero, zero_add, add_comm, add_zero] using hh) + rw [ht, w.testMass_complement] + +end BoundaryTests + +end ParityWL + +end OAI diff --git a/lean/OAI/Combinatorics/ParityLifts/Model.lean b/lean/OAI/Combinatorics/ParityLifts/Model.lean new file mode 100644 index 0000000000000000000000000000000000000000..22eaa32415141a80b4970f1644f87b5940eb82dc --- /dev/null +++ b/lean/OAI/Combinatorics/ParityLifts/Model.lean @@ -0,0 +1,206 @@ +import Mathlib + +namespace OAI + + + +namespace ParityWL + +open scoped BigOperators + +abbrev Bit := ZMod 2 +abbrev MainPair (t : ℕ) := {p : Fin t × Fin t // p.1 < p.2} +abbrev Helper (t : ℕ) := + {q : MainPair t × Fin t // q.2 ≠ q.1.1.1 ∧ q.2 ≠ q.1.1.2} +abbrev TemplateVertex (t : ℕ) := Fin t ⊕ Helper t + +structure ChoiceSystem (t : ℕ) where + Domain : Fin t → Type + domainFintype : ∀ i, Fintype (Domain i) + Label : MainPair t → Type + labelFintype : ∀ p, Fintype (Label p) + leftLabel : (p : MainPair t) → Domain p.1.1 → Label p + rightLabel : (p : MainPair t) → Domain p.1.2 → Label p + +attribute [instance] ChoiceSystem.domainFintype ChoiceSystem.labelFintype + +def ChoiceSystem.Successful {t : ℕ} (C : ChoiceSystem t) : Prop := + ∃ d : (i : Fin t) → C.Domain i, + ∀ p : MainPair t, C.leftLabel p (d p.1.1) = C.rightLabel p (d p.1.2) + +def ChoiceSystem.SizeAtMost {t : ℕ} (C : ChoiceSystem t) (A : ℕ) : Prop := + (∀ i, Fintype.card (C.Domain i) ≤ A) ∧ (∀ p, Fintype.card (C.Label p) ≤ A) + +def helperIncident {t : ℕ} (h : Helper t) (i : Fin t) : Prop := + i = h.1.1.1.1 ∨ i = h.1.1.1.2 ∨ i = h.1.2 + +def templateAdj {t : ℕ} : TemplateVertex t → TemplateVertex t → Prop + | .inl i, .inl j => i ≠ j + | .inl i, .inr h => helperIncident h i + | .inr h, .inl i => helperIncident h i + | .inr _, .inr _ => False + +def template (t : ℕ) : SimpleGraph (TemplateVertex t) where + Adj := templateAdj + symm := ⟨by + intro x y h + cases x <;> cases y <;> simp_all [templateAdj, ne_comm]⟩ + loopless := ⟨by + intro x + cases x <;> simp [templateAdj]⟩ + +abbrev BaseVertex {t : ℕ} (C : ChoiceSystem t) := + ((i : Fin t) × C.Domain i) ⊕ ((h : Helper t) × C.Label h.1.1) + +def baseType {t : ℕ} {C : ChoiceSystem t} : BaseVertex C → TemplateVertex t + | .inl x => .inl x.1 + | .inr x => .inr x.1 + +inductive BaseArc {t : ℕ} (C : ChoiceSystem t) : BaseVertex C → BaseVertex C → Prop + | main (p : MainPair t) (d : C.Domain p.1.1) (e : C.Domain p.1.2) + (h : C.leftLabel p d = C.rightLabel p e) : + BaseArc C (.inl ⟨p.1.1, d⟩) (.inl ⟨p.1.2, e⟩) + | left (h : Helper t) (d : C.Domain h.1.1.1.1) : + BaseArc C (.inr ⟨h, C.leftLabel h.1.1 d⟩) (.inl ⟨h.1.1.1.1, d⟩) + | right (h : Helper t) (e : C.Domain h.1.1.1.2) : + BaseArc C (.inr ⟨h, C.rightLabel h.1.1 e⟩) (.inl ⟨h.1.1.1.2, e⟩) + | third (h : Helper t) (q : C.Label h.1.1) (f : C.Domain h.1.2) : + BaseArc C (.inr ⟨h, q⟩) (.inl ⟨h.1.2, f⟩) + +def baseGraph {t : ℕ} (C : ChoiceSystem t) : SimpleGraph (BaseVertex C) := + SimpleGraph.fromRel (BaseArc C) + +def baseProjection {t : ℕ} (C : ChoiceSystem t) : baseGraph C →g template t where + toFun := baseType + map_rel' := by + intro x y h + have arc : ∀ u v, BaseArc C u v → (template t).Adj (baseType u) (baseType v) := by + intro u v huv + cases huv with + | main p d e he => exact ne_of_lt p.property + | left h d => exact Or.inl rfl + | right h e => exact Or.inr (Or.inl rfl) + | third h q f => exact Or.inr (Or.inr rfl) + rcases h.2 with hxy | hyx + · exact arc x y hxy + · exact (arc y x hyx).symm + +section Lifts + +variable {A V : Type} [Fintype A] (T : SimpleGraph A) (G : SimpleGraph V) + +noncomputable def Tag (b : A → Bit) (a : A) := by + classical + exact {z : T.neighborSet a → Bit // ∑ v, z v = b a} + +noncomputable instance tagFintype (b : A → Bit) (a : A) : Fintype (Tag T b a) := by + classical + unfold Tag + infer_instance + +abbrev LiftVertex (τ : G →g T) (b : A → Bit) := (u : V) × Tag T b (τ u) + +noncomputable def liftGraph (τ : G →g T) (b : A → Bit) : + SimpleGraph (LiftVertex T G τ b) where + Adj u v := ∃ h : G.Adj u.1 v.1, + u.2.1 ⟨τ v.1, τ.map_adj h⟩ = v.2.1 ⟨τ u.1, τ.map_adj h.symm⟩ + symm := ⟨by + intro u v h + rcases h with ⟨h, e⟩ + exact ⟨h.symm, e.symm⟩⟩ + loopless := ⟨by + intro u h + exact G.irrefl h.1⟩ + +end Lifts + +noncomputable def starParity (t : ℕ) : TemplateVertex t → Bit := + fun a => if ∃ i : Fin t, i.val = 0 ∧ a = .inl i then 1 else 0 + +noncomputable def zeroLift {t : ℕ} (C : ChoiceSystem t) := + liftGraph (template t) (baseGraph C) (baseProjection C) (fun _ => 0) + +noncomputable def starLift {t : ℕ} (C : ChoiceSystem t) := + liftGraph (template t) (baseGraph C) (baseProjection C) (starParity t) + +inductive Convention | joint | separate + deriving DecidableEq + +def bagParameter (c : Convention) (k : ℕ) : ℕ := + match c with | .joint => k + 1 | .separate => k + +def detectionRound : Convention → ℕ | .joint => 2 | .separate => 1 + +def orderFactor (t : ℕ) : ℕ := + t * 2 ^ (t - 2 + 3 * (t - 1).choose 2) + 12 * t.choose 3 + +abbrev AtomicType (k : ℕ) := Fin k → Fin k → Bool × Bool + +def JointColor (k : ℕ) : ℕ → Type + | 0 => AtomicType k + | r + 1 => JointColor k r × Multiset (Fin k → JointColor k r) + +def SeparateColor (k : ℕ) : ℕ → Type + | 0 => AtomicType k + | r + 1 => SeparateColor k r × (Fin k → Multiset (SeparateColor k r)) + +noncomputable def atomicType {V : Type} (G : SimpleGraph V) {k : ℕ} + (x : Fin k → V) : AtomicType k := by + classical + exact fun i j => (decide (x i = x j), decide (G.Adj (x i) (x j))) + +noncomputable def jointColor {V : Type} [Fintype V] (G : SimpleGraph V) (k : ℕ) : + (r : ℕ) → (Fin k → V) → JointColor k r + | 0, x => atomicType G x + | r + 1, x => (jointColor G k r x, + Finset.univ.val.map (fun y => fun i => jointColor G k r (Function.update x i y))) + +noncomputable def separateColor {V : Type} [Fintype V] (G : SimpleGraph V) (k : ℕ) : + (r : ℕ) → (Fin k → V) → SeparateColor k r + | 0, x => atomicType G x + | r + 1, x => (separateColor G k r x, + fun i => Finset.univ.val.map (fun y => separateColor G k r (Function.update x i y))) + +noncomputable def sameHistogram {V W : Type} [Fintype V] [Fintype W] + (G : SimpleGraph V) (H : SimpleGraph W) (c : Convention) (k r : ℕ) : Prop := + match c with + | .joint => Finset.univ.val.map (jointColor G k r) = + Finset.univ.val.map (jointColor H k r) + | .separate => Finset.univ.val.map (separateColor G k r) = + Finset.univ.val.map (separateColor H k r) + +noncomputable def samePureHistogram {V W : Type} [Fintype V] [Fintype W] + (G : SimpleGraph V) (H : SimpleGraph W) (c : Convention) (k r : ℕ) : Prop := + match c with + | .joint => + Finset.univ.val.map (fun x : Fin k → V => jointColor (G.sum H) k r (Sum.inl ∘ x)) = + Finset.univ.val.map (fun x : Fin k → W => jointColor (G.sum H) k r (Sum.inr ∘ x)) + | .separate => + Finset.univ.val.map (fun x : Fin k → V => separateColor (G.sum H) k r (Sum.inl ∘ x)) = + Finset.univ.val.map (fun x : Fin k → W => separateColor (G.sum H) k r (Sum.inr ∘ x)) + +noncomputable def WLEquivalent {V W : Type} [Fintype V] [Fintype W] + (G : SimpleGraph V) (H : SimpleGraph W) (c : Convention) (k : ℕ) : Prop := + ∀ r, sameHistogram G H c k r + +noncomputable def PureWLEquivalent {V W : Type} [Fintype V] [Fintype W] + (G : SimpleGraph V) (H : SimpleGraph W) (c : Convention) (k : ℕ) : Prop := + ∀ r, samePureHistogram G H c k r + +noncomputable def ParityReductionStatement : Prop := + ∀ (k : ℕ), 4 ≤ k → ∀ c : Convention, ∀ C : ChoiceSystem (bagParameter c k), + let T := template (bagParameter c k) + let G := baseGraph C + let τ := baseProjection C + let V₀ := LiftVertex T G τ (fun _ => 0) + let V₁ := LiftVertex T G τ (starParity (bagParameter c k)) + Fintype.card V₀ = Fintype.card V₁ ∧ + (∀ A : ℕ, 1 ≤ A → C.SizeAtMost A → Fintype.card V₀ ≤ A * orderFactor (bagParameter c k)) ∧ + (WLEquivalent (zeroLift C) (starLift C) c k ↔ ¬ C.Successful) ∧ + (PureWLEquivalent (zeroLift C) (starLift C) c k ↔ ¬ C.Successful) ∧ + (C.Successful → ¬ sameHistogram (zeroLift C) (starLift C) c k (detectionRound c) ∧ + ¬ samePureHistogram (zeroLift C) (starLift C) c k (detectionRound c)) + +end ParityWL + +end OAI diff --git a/lean/OAI/Combinatorics/ParityLifts/ParamTables.lean b/lean/OAI/Combinatorics/ParityLifts/ParamTables.lean new file mode 100644 index 0000000000000000000000000000000000000000..88f720d850868f2a17ca889b8f36cd08a0287456 --- /dev/null +++ b/lean/OAI/Combinatorics/ParityLifts/ParamTables.lean @@ -0,0 +1,112 @@ +import OAI.Combinatorics.ParityLifts.UniformTables + +namespace OAI + +namespace ParityWL.Complexity + +abbrev RawKeyInput := List BitFormula × (ℕ × (ℕ × (ℕ × List Bool))) + +def PolyProgram.rawGroupAt : PolyProgram (List BitFormula × ℕ) BitFormula + (fun x => x.1[x.2]?.getD []) := + ((PolyProgram.snd (List BitFormula) ℕ).pair (PolyProgram.fst (List BitFormula) ℕ)).comp + (PolyProgram.getD BitFormula []) + +noncomputable def PolyProgram.natMax : PolyProgram (ℕ × ℕ) ℕ (fun x => max x.1 x.2) := + (PolyProgram.natLe.ite (PolyProgram.snd ℕ ℕ) (PolyProgram.fst ℕ ℕ)).congr + (by intro x; simp only [decide_eq_true_eq,max_def]) +noncomputable def PolyProgram.rawPairKey : PolyProgram RawKeyInput (List Bool) + (fun x => Complexity.rawPairKey x.1 x.2.1 x.2.2.1 x.2.2.2.1 x.2.2.2.2) := by + let Q := PolyProgram.fst (List BitFormula) (ℕ × (ℕ × (ℕ × List Bool))) + let I : PolyProgram RawKeyInput (ℕ × ℕ) (fun x => (x.2.2.1,x.2.2.2.1)) := + .expr (.pair TExpr.input.right.right.left TExpr.input.right.right.right.left) (by intro x; rfl) + let lo := ((Q.pair (I.comp PolyProgram.natMin)).comp + PolyProgram.rawGroupAt).comp PolyProgram.names + let hi := ((Q.pair (I.comp PolyProgram.natMax)).comp + PolyProgram.rawGroupAt).comp PolyProgram.names + let own := ((Q.pair (I.comp (PolyProgram.fst ℕ ℕ))).comp + PolyProgram.rawGroupAt).comp PolyProgram.names + let bs : PolyProgram RawKeyInput (List Bool) (fun x => x.2.2.2.2) := + .expr TExpr.input.right.right.right.right (by intro x; rfl) + let va : PolyProgram (Name × (List Name × (List Name × List Bool))) Name Prod.fst := + PolyProgram.fst Name (List Name × (List Name × List Bool)) + let hs : PolyProgram (Name × (List Name × (List Name × List Bool))) (List Name) (fun x => x.2.1) := + .expr TExpr.input.right.left (by intro x; rfl) + let os : PolyProgram (Name × (List Name × (List Name × List Bool))) (List Name × List Bool) + (fun x => x.2.2) := .expr TExpr.input.right.right (by intro x; rfl) + let L := ((va.pair hs).comp (PolyProgram.mem Name)).ite + ((os.pair va).comp PolyProgram.lookupBits) (PolyProgram.const false) + let first := (lo.pair (hi.pair (own.pair bs))).comp L.mapWith + let D : PolyProgram RawKeyInput ℕ (fun x => x.2.1) := + .expr TExpr.input.right.left (by intro x; rfl) + let pad := (((D.pair (lo.comp (PolyProgram.length Name))).comp PolyProgram.natSub).comp PolyProgram.ticks) + refine ((first.pair pad).comp (PolyProgram.append Bool)).congr ?_ + intro x + simp only [Function.comp_def, Complexity.rawPairKey, decide_eq_true_eq] + + +noncomputable def PolyProgram.rawRowKey : + PolyProgram (List Bool × (ℕ × RawTableInput)) (List ℕ) + (fun x => Complexity.rawRowKey x.2.2 x.2.1 x.1) := by + let P : PolyProgram (ℕ × (List Bool × (ℕ × RawTableInput))) RawKeyInput + (fun x => (x.2.2.2.1,(x.2.2.2.2.1,(x.2.2.1,(x.1,x.2.1))))) := + .expr (.pair TExpr.input.right.right.right.left + (.pair TExpr.input.right.right.right.right.left (.pair TExpr.input.right.right.left + (.pair TExpr.input.left TExpr.input.right.left)))) (by intro x; rfl) + let W : PolyProgram (ℕ × (List Bool × (ℕ × RawTableInput))) (List (List Bool)) + (fun x => x.2.2.2.2.2) := + .expr TExpr.input.right.right.right.right.right (by intro x; rfl) + let Q := (W.pair (P.comp PolyProgram.rawPairKey)).comp (PolyProgram.idxOf (List Bool)) + let gs : PolyProgram (List Bool × (ℕ × RawTableInput)) (List BitFormula) (fun x => x.2.2.1) := + .expr TExpr.input.right.right.left (by intro x; rfl) + let rng := gs.comp (PolyProgram.length BitFormula) |>.comp PolyProgram.range + exact ((rng.pair (PolyProgram.id _)).comp Q.mapWith).congr (by intro x; rfl) + +noncomputable def PolyProgram.rawDomain : + PolyProgram (ℕ × RawTableInput) (List (List ℕ)) + (fun x => Complexity.rawDomain x.2 x.1) := by + let Q : PolyProgram (ℕ × RawTableInput) (List BitFormula × ℕ) + (fun x => (x.2.1,x.1)) := + .expr (.pair TExpr.input.right.left TExpr.input.left) (by intro x; rfl) + let W : PolyProgram (ℕ × RawTableInput) (List (List Bool)) (fun x => x.2.2.2) := + .expr TExpr.input.right.right.right (by intro x; rfl) + let D := (W.pair (Q.comp PolyProgram.rawGroupAt)).comp PolyProgram.satisfyingWith + exact ((D.pair (PolyProgram.id (ℕ × RawTableInput))).comp PolyProgram.rawRowKey.mapWith).congr + (by intro x; rfl) + +noncomputable def PolyProgram.rawChoiceWithWords : PolyProgram RawTableInput RawChoiceData + Complexity.rawChoiceWithWords := by + let gs := (PolyProgram.fst (List BitFormula) (ℕ × List (List Bool))).comp + (PolyProgram.length BitFormula) |>.comp PolyProgram.range + let Q := (gs.pair (PolyProgram.id _)).comp PolyProgram.rawDomain.mapWith + let W : PolyProgram RawTableInput (List (List Bool)) (fun x => x.2.2) := + .expr TExpr.input.right.right (by intro x; rfl) + let B := W.comp (PolyProgram.length (List Bool)) + let row := (gs.pair B).comp (PolyProgram.snd ℕ ℕ).mapWith + exact (Q.pair ((gs.pair row).comp (PolyProgram.snd ℕ (List ℕ)).mapWith)).congr + (by intro x; rfl) + +def PolyProgram.runtimeChunkWidth : PolyProgram (ℕ × BitFormula) ℕ + (fun x => Complexity.chunkWidth x.1 x.2) := by + let n := (PolyProgram.snd ℕ BitFormula).comp (PolyProgram.length BitClause) + let t := PolyProgram.fst ℕ BitFormula + let num := (((n.pair t).comp PolyProgram.natAdd).pair (PolyProgram.const 1)).comp PolyProgram.natSub + exact (num.pair t).comp PolyProgram.natDiv + +noncomputable def PolyProgram.rawGroups : PolyProgram (ℕ × BitFormula) (List BitFormula) + (fun x => Complexity.rawGroups x.1 x.2) := by + let i := PolyProgram.fst ℕ (ℕ × BitFormula) + let w := (PolyProgram.snd ℕ (ℕ × BitFormula)).comp PolyProgram.runtimeChunkWidth + let F : PolyProgram (ℕ × (ℕ × BitFormula)) BitFormula (fun x => x.2.2) := + .expr TExpr.input.right.right (by intro x; rfl) + let row := (w.pair (((i.pair w).comp PolyProgram.natMul).pair F |>.comp + (PolyProgram.drop BitClause))).comp (PolyProgram.take BitClause) + exact ((((PolyProgram.fst ℕ BitFormula).comp PolyProgram.range).pair (PolyProgram.id _)).comp + row.mapWith).congr (by intro x; rfl) + +noncomputable def PolyProgram.rawLeafPrepare : PolyProgram (ℕ × BitFormula) (List BitFormula × ℕ) + (fun x => (Complexity.rawGroups x.1 x.2,Complexity.leafWords x.1 x.2)) := + PolyProgram.rawGroups.pair (((PolyProgram.const 3).pair PolyProgram.runtimeChunkWidth).comp PolyProgram.natMul) + +end ParityWL.Complexity + +end OAI diff --git a/lean/OAI/Combinatorics/ParityLifts/ParamTags.lean b/lean/OAI/Combinatorics/ParityLifts/ParamTags.lean new file mode 100644 index 0000000000000000000000000000000000000000..7408f3ddc380d80b0af07cacac08e270f7f2cf5a --- /dev/null +++ b/lean/OAI/Combinatorics/ParityLifts/ParamTags.lean @@ -0,0 +1,71 @@ +import OAI.Combinatorics.ParityLifts.ParamTables + +namespace OAI + +namespace ParityWL.Complexity + +noncomputable def PolyProgram.roleValid : PolyProgram (RawRole × ℕ) Bool + (fun x => decide (RoleValid x.2 x.1)) := by + let a : PolyProgram (RawRole × ℕ) ℕ (fun x => x.1.1) := + .expr TExpr.input.left.left (by intro x; rfl) + let b : PolyProgram (RawRole × ℕ) ℕ (fun x => x.1.2.1) := + .expr TExpr.input.left.right.left (by intro x; rfl) + let c : PolyProgram (RawRole × ℕ) ℕ (fun x => x.1.2.2) := + .expr TExpr.input.left.right.right (by intro x; rfl) + let t := PolyProgram.snd RawRole ℕ + let h := ((a.eqOn b).andOn (c.eqOn a)).orOn + (((a.pair b).comp PolyProgram.natLt).andOn + (((c.eqOn a).comp PolyProgram.not).andOn ((c.eqOn b).comp PolyProgram.not))) + refine (((a.pair t).comp PolyProgram.natLt).andOn + (((b.pair t).comp PolyProgram.natLt).andOn (((c.pair t).comp PolyProgram.natLt).andOn h))).congr ?_ + intro x + apply Bool.eq_iff_iff.mpr + erw [decide_eq_true_eq] + simp only [Function.comp_apply,Bool.and_eq_true,Bool.or_eq_true,decide_eq_true_eq, + Bool.not_eq_true',decide_eq_false_iff_not,RoleValid] + +noncomputable def PolyProgram.allRoles : PolyProgram ℕ (List RawRole) Complexity.allRoles := + (((PolyProgram.range.pair (PolyProgram.range.pair PolyProgram.range |>.comp (PolyProgram.product ℕ ℕ))) + |>.comp (PolyProgram.product ℕ (ℕ × ℕ))).pair (PolyProgram.id ℕ) |>.comp + PolyProgram.roleValid.filterWith).congr (by intro x; rfl) + +noncomputable def PolyProgram.rawNeighbors : PolyProgram (ℕ × RawRole) (List RawRole) + (fun x => Complexity.rawNeighbors x.1 x.2) := by + let Q := (PolyProgram.swap RawRole RawRole).comp PolyProgram.rawAdjacent + exact ((((PolyProgram.fst ℕ RawRole).comp PolyProgram.allRoles).pair + (PolyProgram.snd ℕ RawRole)).comp Q.filterWith).congr (by intro x; rfl) + +noncomputable def PolyProgram.rawCharge : PolyProgram (Bool × RawRole) ℕ + (fun x => Complexity.rawCharge x.1 x.2) := + (((PolyProgram.fst Bool RawRole).andOn ((PolyProgram.snd Bool RawRole).eqOn + (PolyProgram.const (0,0,0)))).ite (PolyProgram.const 1) (PolyProgram.const 0)).congr (by intro x; rfl) + +noncomputable def TreeProgram.rawTags : TreeProgram (ℕ × Bool) (List RawTag) + (fun x => Complexity.rawTags x.1 x.2) := by + let p : PolyProgram (RawRole × (ℕ × Bool)) (ℕ × RawRole) (fun x => (x.2.1,x.1)) := + .expr (.pair TExpr.input.right.left TExpr.input.left) (by intro x; rfl) + let nb := (p.comp PolyProgram.rawNeighbors).program.comp (TreeProgram.sublists RawRole) + let r : PolyProgram (RawRole × (ℕ × Bool)) (Bool × RawRole) (fun x => (x.2.2,x.1)) := + .expr (.pair TExpr.input.right.right TExpr.input.left) (by intro x; rfl) + let charge := (r.comp PolyProgram.rawCharge).program + let cond := ((PolyProgram.fst (List RawRole) ℕ).comp (PolyProgram.length RawRole) |>.comp PolyProgram.natModTwo) + |>.eqOn (PolyProgram.snd (List RawRole) ℕ) + let good := (nb.pair charge).comp cond.filterWith.program + let a := TreeProgram.fst RawRole (ℕ × Bool) + let tag : PolyProgram (List RawRole × RawRole) RawTag (fun x => (x.2,x.1)) := + .expr (.pair TExpr.input.right TExpr.input.left) (by intro x; rfl) + let tags := (good.pair a).comp tag.mapWith.program + let roles := (PolyProgram.fst ℕ Bool).comp PolyProgram.allRoles + refine (((roles.program.pair (TreeProgram.id (ℕ × Bool))).comp tags.mapWith).comp + (PolyProgram.flatten RawTag).program).congr ?_ + intro x + simp only [Complexity.rawTags,Function.comp_apply,List.flatMap_def,id_eq] + +noncomputable def TreeProgram.tagPair : TreeProgram ℕ (List RawTag × List RawTag) + (fun t => (Complexity.rawTags t false,Complexity.rawTags t true)) := + (((TreeProgram.id ℕ).pair (TreeProgram.const false)).comp TreeProgram.rawTags).pair + (((TreeProgram.id ℕ).pair (TreeProgram.const true)).comp TreeProgram.rawTags) + +end ParityWL.Complexity + +end OAI diff --git a/lean/OAI/Combinatorics/ParityLifts/ParameterBounds.lean b/lean/OAI/Combinatorics/ParityLifts/ParameterBounds.lean new file mode 100644 index 0000000000000000000000000000000000000000..5929e9ee17de9d77c24ba99c1a038ef4725413cf --- /dev/null +++ b/lean/OAI/Combinatorics/ParityLifts/ParameterBounds.lean @@ -0,0 +1,22 @@ +import OAI.Combinatorics.ParityLifts.RaceBounds + +namespace OAI + +namespace ParityWL.Complexity + +def ParamPolyProgram.post {ρ α β γ : Type} [TreeCodec ρ] [TreeCodec α] [TreeCodec β] [TreeCodec γ] + {f : ρ → α → β} {g : β → γ} (P : ParamPolyProgram ρ α β f) (Q : PolyProgram β γ g) : + ParamPolyProgram ρ α γ (fun r x => g (f r x)) := + P.comp (ParamPolyProgram.ofPoly (f := fun (_ : ρ) b => g b) ((PolyProgram.snd ρ β).comp Q)) + +def ParamPolyProgram.lift {ρ α β : Type} [TreeCodec ρ] [TreeCodec α] [TreeCodec β] + {f : α → β} (P : PolyProgram α β f) : ParamPolyProgram ρ α β (fun _ x => f x) := + ParamPolyProgram.ofPoly (f := fun (_ : ρ) x => f x) ((PolyProgram.snd ρ α).comp P) + +def ParamPolyProgram.parameter (ρ α : Type) [TreeCodec ρ] [TreeCodec α] : + ParamPolyProgram ρ α ρ (fun r _ => r) := + .ofPoly (f := fun r (_ : α) => r) (PolyProgram.fst ρ α) + +end ParityWL.Complexity + +end OAI diff --git a/lean/OAI/Combinatorics/ParityLifts/ParameterLoops.lean b/lean/OAI/Combinatorics/ParityLifts/ParameterLoops.lean new file mode 100644 index 0000000000000000000000000000000000000000..9e7b85a9cebf00c0633acd9b7f3054022fd7bcaa --- /dev/null +++ b/lean/OAI/Combinatorics/ParityLifts/ParameterLoops.lean @@ -0,0 +1,102 @@ +import OAI.Combinatorics.ParityLifts.ParameterPolynomial + +namespace OAI + +namespace ParityWL.Complexity + +lemma TreeProgram.poly_comp_at {α β γ : Type} [TreeCodec α] [TreeCodec β] [TreeCodec γ] + {f : α → β} {g : β → γ} (P : TreeProgram α β f) (Q : TreeProgram β γ g) + (x : α) (A a B b : ℕ) (hp : P.time x≤A*((treeEncode x).size+1)^a) + (hq : Q.time (f x)≤B*((treeEncode (f x)).size+1)^b) : + (P.comp Q).time x≤(A+B*(A+1)^b+1)*((treeEncode x).size+1)^(a+a*b) := by + let X := (treeEncode x).size+1 + have hx : 1≤X := by dsimp [X]; omega + have hs := (P.run x).bounds.2.1 + have ht : Q.time (f x)≤B*(A+1)^b*X^(a*b) := by + calc + _ ≤ B*(A*X^a+1)^b := by apply hq.trans; gcongr; exact hs.trans hp + _ ≤ _ := nat_poly_substitute X A B a b hx + exact (Nat.add_le_add_right (Nat.add_le_add hp ht) 1).trans (nat_poly_add X _ _ _ _ hx) + +def ParamPolyProgram.congr {ρ α β : Type} [TreeCodec ρ] [TreeCodec α] [TreeCodec β] + {f g : ρ → α → β} (P : ParamPolyProgram ρ α β f) (h : ∀ r x, f r x=g r x) : + ParamPolyProgram ρ α β g := by + have : f=g := funext (fun r => funext (h r)) + subst g + exact P + +def ParamPolyProgram.reindex {ρ σ α β : Type} [TreeCodec ρ] [TreeCodec σ] [TreeCodec α] [TreeCodec β] + {f : ρ → α → β} {g : σ → ρ} (P : ParamPolyProgram ρ α β f) (Q : PolyProgram σ ρ g) : + ParamPolyProgram σ α β (fun s x => f (g s) x) := by + let I := (((PolyProgram.fst σ α).comp Q).pair (PolyProgram.snd σ α)) + exact { + program := I.program.comp P.program + coefficient := fun s => I.coefficient+P.coefficient (g s)*(I.coefficient+1)^(P.degree (g s))+1 + degree := fun s => I.degree+I.degree*P.degree (g s) + bound := fun s x => TreeProgram.poly_comp_at I.program P.program (s,x) _ _ _ _ (I.bound _) (P.bound (g s) x) + } + +def ParamPolyProgram.ite {ρ α β : Type} [TreeCodec ρ] [TreeCodec α] [TreeCodec β] + {p : ρ → α → Bool} {f g : ρ → α → β} + (P : ParamPolyProgram ρ α Bool p) (F : ParamPolyProgram ρ α β f) (G : ParamPolyProgram ρ α β g) : + ParamPolyProgram ρ α β (fun r x => if p r x then f r x else g r x) where + program := P.program.ite F.program G.program + coefficient := fun r => P.coefficient r+(F.coefficient r+G.coefficient r+1)+1 + degree := fun r => P.degree r+(F.degree r+G.degree r) + bound := by + intro r x + have hfg := nat_poly_add ((treeEncode (r,x)).size+1) (F.coefficient r) (G.coefficient r) + (F.degree r) (G.degree r) (by omega) + have h : (if p r x then F.program.time (r,x) else G.program.time (r,x)) ≤ + (F.coefficient r+G.coefficient r+1)*((treeEncode (r,x)).size+1)^(F.degree r+G.degree r) := by + split + · exact (F.bound r x).trans (by omega) + · exact (G.bound r x).trans (by omega) + exact (Nat.add_le_add_right (Nat.add_le_add (P.bound r x) h) 1).trans (nat_poly_add _ _ _ _ _ (by omega)) + +noncomputable def ParamPolyProgram.foldTimes {α : Type} [TreeCodec α] + {f : Bool × α → α} (P : PolyProgram (Bool × α) α f) : + ParamPolyProgram ℕ α α (fun n x => (List.replicate n false).foldl (fun a b => f (b,a)) x) := by + let I := ((PolyProgram.fst ℕ α).comp PolyProgram.ticks).pair (PolyProgram.snd ℕ α) + choose C d h using TreeProgram.fixed_fold_polynomial P + have hf (n : ℕ) (x : α) : P.program.foldl.time (List.replicate n false,x) ≤ + (2*C n+1)*((treeEncode (List.replicate n false,x)).size+1)^(d n) := by + have hh := h n (List.replicate n false) x (by simp) + have hout := (P.program.foldLoop_run (List.replicate n false) x).bounds.2.1 + have h1 := Nat.one_le_pow (d n) ((treeEncode (List.replicate n false,x)).size+1) (by omega) + change P.program.foldWork _ _+(treeEncode (([] : List Bool),_)).size+1≤_ + nlinarith only [hh,hout,h1] + exact { + program := I.program.comp P.program.foldl + coefficient := fun n => I.coefficient+(2*C n+1)*(I.coefficient+1)^(d n)+1 + degree := fun n => I.degree+I.degree*d n + bound := fun n x => TreeProgram.poly_comp_at I.program P.program.foldl (n,x) _ _ _ _ (I.bound _) (hf n x) + } + +noncomputable def ParamPolyProgram.allTuples (α : Type) [TreeCodec α] : + ParamPolyProgram ℕ (List α) (List (List α)) (fun n xs => Complexity.allTuples n xs) := by + let U := ((PolyProgram.prependAll α).mapWith).comp (PolyProgram.flatten (List α)) + let step := (PolyProgram.snd Bool (List α × List (List α))).comp + ((PolyProgram.fst (List α) (List (List α))).pair U) + let init : PolyProgram (ℕ × List α) (List α × List (List α)) (fun x => (x.2,[[]])) := + .expr (.pair TExpr.input.right (.pair .nil .nil)) (by intro x; rfl) + let out : PolyProgram (ℕ × (List α × List (List α))) (List (List α)) (fun x => x.2.2) := + .expr TExpr.input.right.right (by intro x; rfl) + let P := (ParamPolyProgram.ofPoly (f := fun (_ : ℕ) (xs : List α) => (xs,[[]])) init).comp (ParamPolyProgram.foldTimes step) |>.comp (ParamPolyProgram.ofPoly (f := fun (_ : ℕ) (x : List α × List (List α)) => x.2) out) + refine P.congr ?_ + intro n xs + change ((List.replicate n false).foldl + (fun s (_ : Bool) => (s.1,(s.1.map (fun a => s.2.map (a::·))).flatten)) (xs,[[]])).2=Complexity.allTuples n xs + have h : (List.replicate n false).foldl + (fun s (_ : Bool) => (s.1,(s.1.map (fun a => s.2.map (a::·))).flatten)) (xs,[[]])= + (xs,Complexity.allTuples n xs) := by + induction n with + | zero => rfl + | succ n ih => + rw [List.replicate_succ',List.foldl_append,ih] + simp only [List.foldl_cons,List.foldl_nil,Complexity.allTuples,List.flatMap_def] + exact congrArg Prod.snd h + +end ParityWL.Complexity + +end OAI diff --git a/lean/OAI/Combinatorics/ParityLifts/ParameterPolynomial.lean b/lean/OAI/Combinatorics/ParityLifts/ParameterPolynomial.lean new file mode 100644 index 0000000000000000000000000000000000000000..917b4c1c377ec3ae8661501e3ac02e946c24a15d --- /dev/null +++ b/lean/OAI/Combinatorics/ParityLifts/ParameterPolynomial.lean @@ -0,0 +1,130 @@ +import OAI.Combinatorics.ParityLifts.UniformBasics + +namespace OAI + +namespace ParityWL.Complexity + +/-- A single finite program, polynomial on each fixed parameter fibre. The +parameter is genuine input data, not an infinite family of finite controls. -/ +structure ParamPolyProgram (ρ α β : Type) [TreeCodec ρ] [TreeCodec α] [TreeCodec β] + (f : ρ → α → β) where + program : TreeProgram (ρ × α) β (fun x => f x.1 x.2) + coefficient : ρ → ℕ + degree : ρ → ℕ + bound : ∀ r x, program.time (r,x) ≤ coefficient r*((treeEncode (r,x)).size+1)^(degree r) + +def ParamPolyProgram.ofPoly {ρ α β : Type} [TreeCodec ρ] [TreeCodec α] [TreeCodec β] + {f : ρ → α → β} (P : PolyProgram (ρ × α) β (fun x => f x.1 x.2)) : ParamPolyProgram ρ α β f where + program := P.program + coefficient := fun _ => P.coefficient + degree := fun _ => P.degree + bound := fun r x => P.bound (r,x) + +def ParamPolyProgram.pair {ρ α β γ : Type} [TreeCodec ρ] [TreeCodec α] [TreeCodec β] [TreeCodec γ] + {f : ρ → α → β} {g : ρ → α → γ} (P : ParamPolyProgram ρ α β f) (Q : ParamPolyProgram ρ α γ g) : + ParamPolyProgram ρ α (β × γ) (fun r x => (f r x,g r x)) where + program := P.program.pair Q.program + coefficient := fun r => P.coefficient r+Q.coefficient r+1 + degree := fun r => P.degree r+Q.degree r + bound := by + intro r x + exact (Nat.add_le_add_right (Nat.add_le_add (P.bound r x) (Q.bound r x)) 1).trans + (nat_poly_add _ _ _ _ _ (by omega)) + +def ParamPolyProgram.comp {ρ α β γ : Type} [TreeCodec ρ] [TreeCodec α] [TreeCodec β] [TreeCodec γ] + {f : ρ → α → β} {g : ρ → β → γ} (P : ParamPolyProgram ρ α β f) (Q : ParamPolyProgram ρ β γ g) : + ParamPolyProgram ρ α γ (fun r x => g r (f r x)) where + program := ((TreeProgram.fst ρ α).pair P.program).comp Q.program + coefficient := fun r => 2*P.coefficient r+Q.coefficient r*(2*(P.coefficient r+1))^(Q.degree r)+2 + degree := fun r => P.degree r+P.degree r*Q.degree r + bound := by + intro r x + let X := (treeEncode (r,x)).size+1 + have hX : 1≤X := by dsimp [X]; omega + let A := P.coefficient r + let a := P.degree r + let B := Q.coefficient r + let b := Q.degree r + have hp : P.program.time (r,x)≤A*X^a := P.bound r x + have hs := (P.program.run (r,x)).bounds.1 + have ho := (P.program.run (r,x)).bounds.2.1 + have hr : (treeEncode r).size≤(treeEncode (r,x)).size := by simp [DataTree.size]; omega + have hi : (treeEncode (r,f r x)).size+1≤(2*(A+1))*X^a := by + simp only [treeEncode_pair,DataTree.size] + have h1 := Nat.one_le_pow a X hX + change (treeEncode (f r x)).size≤P.program.time (r,x) at ho + nlinarith + have hq : Q.program.time (r,f r x)≤B*(2*(A+1))^b*X^(a*b) := by + calc + _ ≤ B*((treeEncode (r,f r x)).size+1)^b := Q.bound r _ + _ ≤ B*((2*(A+1))*X^a)^b := by gcongr + _ = _ := by rw [mul_pow,←pow_mul]; ring + have h0 : (treeEncode (r,x)).size+P.program.time (r,x)+1≤(2*A+1)*X^a := by + have h1 := Nat.one_le_pow a X hX + nlinarith + have hn := nat_poly_add X (2*A+1) (B*(2*(A+1))^b) a (a*b) hX + change (treeEncode (r,x)).size+P.program.time (r,x)+1+Q.program.time (r,f r x)+1≤_ + dsimp only [A,a,B,b,X] at h0 hq hn + nlinarith only [(Nat.add_le_add_right (Nat.add_le_add h0 hq) 1).trans hn] + +lemma TreeProgram.fixed_fold_polynomial {α β : Type} [TreeCodec α] [TreeCodec β] + {f : α × β → β} (P : PolyProgram (α × β) β f) (n : ℕ) : + ∃ C d : ℕ, ∀ (xs : List α) (b : β), xs.length≤n → + P.program.foldWork xs b ≤ C*((treeEncode (xs,b)).size+1)^d := by + induction n with + | zero => + refine ⟨1,1,?_⟩ + intro xs b hn + have hx : xs=[] := List.length_eq_zero_iff.mp (by omega) + subst xs + simp only [TreeProgram.foldWork,pow_one,one_mul] + omega + | succ n ih => + obtain ⟨C,d,ih⟩ := ih + let A := P.coefficient + let a := P.degree + refine ⟨A+12+C*(A+2)^d,(a+1)*(d+1),?_⟩ + intro xs b hn + let X := (treeEncode (xs,b)).size+1 + have hX : 1≤X := by dsimp [X]; omega + have hpow : X≤X^(a+1) := by + simpa using Nat.pow_le_pow_right hX (show 1≤a+1 by omega) + have hpow' : X≤X^((a+1)*(d+1)) := by + simpa using Nat.pow_le_pow_right hX (show 1≤(a+1)*(d+1) by nlinarith) + cases xs with + | nil => + simp only [TreeProgram.foldWork] + dsimp only [X] at hpow' + exact (by omega : (treeEncode (([] : List α),b)).size≤((treeEncode (([] : List α),b)).size+1)^((a+1)*(d+1))).trans + (Nat.le_mul_of_pos_left _ (by omega)) + | cons u us => + have hup : (treeEncode (u,b)).size≤(treeEncode (u::us,b)).size := by simp [DataTree.size]; omega + have hp : P.program.time (u,b)≤A*X^a := by + exact (P.bound _).trans (Nat.mul_le_mul_left _ (Nat.pow_le_pow_left (Nat.add_le_add_right hup 1) _)) + have ho := (P.program.run (u,b)).bounds.2.1 + change (treeEncode (f (u,b))).size≤P.program.time (u,b) at ho + have htail : (treeEncode (us,f (u,b))).size+1≤(A+2)*X^(a+1) := by + have haa : X^a≤X^(a+1) := Nat.pow_le_pow_right hX (by omega) + have h1 := Nat.one_le_pow (a+1) X hX + have hun : (treeEncode us).size+2≤X := by dsimp [X]; simp [DataTree.size]; omega + simp only [treeEncode_pair,DataTree.size] + nlinarith [Nat.mul_le_mul_left A haa] + have ht : P.program.foldWork us (f (u,b))≤C*(A+2)^d*X^((a+1)*d) := by + calc + _ ≤ C*((treeEncode (us,f (u,b))).size+1)^d := ih us _ (by simpa using hn) + _ ≤ C*((A+2)*X^(a+1))^d := by gcongr + _ = _ := by rw [mul_pow,←pow_mul]; ring + have hbase : 10*X+P.program.time (u,b)+1≤(A+11)*X^(a+1) := by + have haa : X^a≤X^(a+1) := Nat.pow_le_pow_right hX (by omega) + have h1 := Nat.one_le_pow (a+1) X hX + nlinarith [Nat.mul_le_mul_left A haa] + have hadd := nat_poly_add X (A+11) (C*(A+2)^d) (a+1) ((a+1)*d) hX + change 10*X+P.program.time (u,b)+P.program.foldWork us (f (u,b))+1≤_ + have hh := (Nat.add_le_add_right (Nat.add_le_add hbase ht) 1).trans hadd + rw [show (a+1)*(d+1)=(a+1)+(a+1)*d by ring] + dsimp only [X] at hh ⊢ + nlinarith only [hh] + +end ParityWL.Complexity + +end OAI diff --git a/lean/OAI/Combinatorics/ParityLifts/Parser.lean b/lean/OAI/Combinatorics/ParityLifts/Parser.lean new file mode 100644 index 0000000000000000000000000000000000000000..bc014f6d92dbc7752dab2d35f5ef54ed5ff344b2 --- /dev/null +++ b/lean/OAI/Combinatorics/ParityLifts/Parser.lean @@ -0,0 +1,237 @@ +import OAI.Combinatorics.ParityLifts.SAT + +namespace OAI + +namespace ParityWL.Complexity + +lemma TreeProgram.loop_completes {α : Type} [TreeCodec α] {f : α → α} + (P : TreeProgram α α f) (x : α) (n B S : ℕ) + (hb : ∀ j, j < n → P.time (f^[j] x) ≤ B) + (hs : ∀ j, j ≤ n → (treeEncode (f^[j] x)).size ≤ S) + (hf : ∀ y, (treeEncode y).child false = .nil → f y = y) + (he : (treeEncode (f^[n] x)).child false = .nil) : + BEval (.loop P.code) (treeEncode x) ((n+1)*(B+S+1)) (treeEncode (f^[n] x)) := by + induction n generalizing x with + | zero => + simpa using (BEval.loop_stop P.code (treeEncode x) (by simpa using he)).mono + (show (treeEncode x).size ≤ (0+1)*(B+S+1) from by + have hx := hs 0 (by omega) + simpa only [Function.iterate_zero, id_eq, Nat.zero_add, Nat.one_mul] using hx.trans (by omega)) + | succ n ih => + by_cases hx : (treeEncode x).child false = .nil + · rw [Function.iterate_fixed (hf x hx)] + exact (BEval.loop_stop P.code (treeEncode x) hx).mono (by + have ht := hs 0 (by omega) + simp only [Function.iterate_zero, id_eq] at ht + nlinarith) + · have ht := ih (f x) + (fun j hj => by simpa [Function.iterate_succ_apply] using hb (j+1) (by omega)) + (fun j hj => by simpa [Function.iterate_succ_apply] using hs (j+1) (by omega)) + (by simpa [Function.iterate_succ_apply] using he) + have h₀ := (P.run x).mono (by simpa using hb 0 (by omega)) + simpa [Function.iterate_succ_apply] using (BEval.loop_next hx h₀ ht).mono + (show B+(n+1)*(B+S+1)+1 ≤ (n+1+1)*(B+S+1) by nlinarith) + +def streamStep {α : Type} (p : List Bool → α × List Bool) (x : List Bool × List α) : + List Bool × List α := + if x.1 = [] then x else ((p x.1).2, (p x.1).1 :: x.2) + +lemma streamStep_fixed {α : Type} (p : List Bool → α × List Bool) (xs : List α) : + streamStep p ([],xs) = ([],xs) := by simp [streamStep] + +lemma streamStep_remaining {α : Type} (p : List Bool → α × List Bool) + (hp : ∀ xs, xs≠[] → (p xs).2.length < xs.length) (n : ℕ) (x : List Bool × List α) : + ((streamStep p)^[n] x).1.length ≤ x.1.length-n := by + induction n generalizing x with + | zero => simp + | succ n ih => + rw [Function.iterate_succ_apply] + have hj := ih (streamStep p x) + by_cases hx : x.1=[] + · simpa [streamStep, hx] using hj + · have hs := hp x.1 hx + simpa only [streamStep, ite_eq_right hx] using hj.trans (show (streamStep p x).1.length-n ≤ x.1.length-(n+1) by + simp only [streamStep, ite_eq_right hx] + omega) + +lemma streamStep_potential {α : Type} [TreeCodec α] (p : List Bool → α × List Bool) (D : ℕ) + (hp : ∀ xs, xs≠[] → (treeEncode (p xs).1).size+1+D*(p xs).2.length ≤ D*xs.length) + (n : ℕ) (x : List Bool × List α) : + D*((streamStep p)^[n] x).1.length + (treeEncode ((streamStep p)^[n] x).2).size ≤ + D*x.1.length+(treeEncode x.2).size := by + induction n generalizing x with + | zero => simp + | succ n ih => + rw [Function.iterate_succ_apply] + apply (ih (streamStep p x)).trans + by_cases hx : x.1=[] + · simp [streamStep, hx] + · have h := hp x.1 hx + simp only [streamStep, ite_eq_right hx, treeEncode_cons, DataTree.size] + omega + +def streamRun {α : Type} (p : List Bool → α × List Bool) (xs : List Bool) : List Bool × List α := + (streamStep p)^[xs.length] (xs,[]) + +def parseStream {α : Type} (p : List Bool → α × List Bool) (xs : List Bool) : List α := + (streamRun p xs).2.reverse + +def PolyProgram.streamStep {α : Type} [TreeCodec α] {p : List Bool → α × List Bool} + (P : PolyProgram (List Bool) (α × List Bool) p) : + PolyProgram (List Bool × List α) (List Bool × List α) (streamStep p) := by + let F := PolyProgram.fst (List Bool) (List α) + let G := PolyProgram.snd (List Bool) (List α) + let E : PolyProgram ((α × List Bool) × List α) (List Bool × List α) + (fun x => (x.1.2,x.1.1::x.2)) := + .expr (.pair TExpr.input.left.right (.pair TExpr.input.left.left TExpr.input.right)) + (by intro x; rfl) + let Q := ((F.comp P).pair G).comp E + refine ((F.comp (PolyProgram.null Bool)).ite (PolyProgram.id _) Q).congr ?_ + rintro ⟨xs,ys⟩ + cases xs <;> simp [Complexity.streamStep, List.isEmpty] + +def PolyProgram.streamRun {α : Type} [TreeCodec α] {p : List Bool → α × List Bool} + (P : PolyProgram (List Bool) (α × List Bool) p) (D : ℕ) + (hc : ∀ xs, xs≠[] → (p xs).2.length < xs.length) + (ha : ∀ xs, xs≠[] → (treeEncode (p xs).1).size+1+D*(p xs).2.length ≤ D*xs.length) : + PolyProgram (List Bool) (List Bool × List α) (streamRun p) := by + let Q := P.streamStep + let d := Q.degree + let a := Q.coefficient*(D+9)^d + let A := a+D+20 + refine ⟨⟨.seq (.pair .id .nil) (.loop Q.program.code), + (fun xs => A*((treeEncode xs).size+1)^(d+2)), ?_⟩, A, d+2, fun _ => le_rfl⟩ + intro xs + let X := (treeEncode xs).size+1 + let S := (D+8)*X + let B := a*X^d + have hx : 1 ≤ X := by dsimp [X]; have := (treeEncode xs).size_pos; omega + have hL : xs.length+1 ≤ X := by have := treeEncode_list_length xs; dsimp [X]; omega + have hs (j : ℕ) : (treeEncode ((Complexity.streamStep p)^[j] (xs,([]:List α)))).size ≤ S := by + have hr := streamStep_remaining p hc j (xs,([]:List α)) + have ha := streamStep_potential p D ha j (xs,([]:List α)) + have hl := treeEncode_bits_size ((Complexity.streamStep p)^[j] (xs,([]:List α))).1 + simp only [treeEncode_nil, DataTree.size] at ha + have hlen : ((Complexity.streamStep p)^[j] (xs,([]:List α))).1.length ≤ xs.length := hr.trans (Nat.sub_le _ _) + have hacc : (treeEncode ((Complexity.streamStep p)^[j] (xs,([]:List α))).2).size ≤ D*xs.length+1 := by omega + change _ ≤ S + rw [treeEncode_prod, DataTree.size] + dsimp only [S] + nlinarith [Nat.mul_le_mul_left D (show xs.length ≤ X from by omega)] + have hb (j : ℕ) : Q.program.time ((Complexity.streamStep p)^[j] (xs,([]:List α))) ≤ B := by + apply (Q.bound _).trans + change _ ≤ Q.coefficient*(D+9)^d*X^d + have ht := hs j + have he : (treeEncode ((Complexity.streamStep p)^[j] (xs,([]:List α)))).size+1 ≤ (D+9)*X := by + change (treeEncode ((Complexity.streamStep p)^[j] (xs,([]:List α)))).size ≤ (D+8)*X at ht + nlinarith + calc + _ ≤ Q.coefficient*((D+9)*X)^d := Nat.mul_le_mul_left _ (Nat.pow_le_pow_left he _) + _ = _ := by rw [mul_pow]; ring + have he : (treeEncode ((Complexity.streamStep p)^[xs.length] (xs,([]:List α)))).child false = .nil := by + have hr := streamStep_remaining p hc xs.length (xs,([]:List α)) + have hn : ((Complexity.streamStep p)^[xs.length] (xs,([]:List α))).1=[] := by + apply List.length_eq_zero_iff.mp + simp only [Nat.sub_self, Nat.le_zero_eq] at hr + exact hr + simp [treeEncode_prod, DataTree.child, hn] + have hf : ∀ y : List Bool × List α, (treeEncode y).child false = .nil → Complexity.streamStep p y=y := by + rintro ⟨ys,zs⟩ hh + cases ys with + | nil => exact streamStep_fixed _ _ + | cons b ys => simp [DataTree.child] at hh + have hr := Q.program.loop_completes (xs,[]) xs.length B S (fun j _ => hb j) (fun j _ => hs j) hf he + have hi := (BEval.id (treeEncode xs)).pair (BEval.nil (treeEncode xs)) + have hi' : BEval (.pair .id .nil) (treeEncode xs) (2*(treeEncode xs).size+1) + (treeEncode (xs,([]:List α))) := by simpa [two_mul] using hi + apply (hi'.seq hr).mono + change 2*(treeEncode xs).size+1+(xs.length+1)*(B+S+1)+1 ≤ A*X^(d+2) + have hpow₁ : X ≤ X^(d+1) := by simpa using Nat.pow_le_pow_right hx (show 1 ≤ d+1 by omega) + have hpowd : X^d ≤ X^(d+1) := Nat.pow_le_pow_right hx (by omega) + have hp : 1 ≤ X^(d+1) := Nat.one_le_pow _ _ hx + have hBS : B+S+1 ≤ (a+D+9)*X^(d+1) := by + dsimp [B,S] + nlinarith [Nat.mul_le_mul_left a hpowd, Nat.mul_le_mul_left (D+8) hpow₁] + have hm := Nat.mul_le_mul hL hBS + have hid : X*((a+D+9)*X^(d+1)) = (a+D+9)*X^(d+2) := by rw [show d+2=(d+1)+1 by omega, pow_succ]; ring + rw [hid] at hm + have hp' : X ≤ X^(d+2) := by simpa using Nat.pow_le_pow_right hx (show 1 ≤ d+2 by omega) + have heX : (treeEncode xs).size+1=X := rfl + dsimp only [A] + nlinarith + +def PolyProgram.parseStream {α : Type} [TreeCodec α] {p : List Bool → α × List Bool} + (P : PolyProgram (List Bool) (α × List Bool) p) (D : ℕ) + (hc : ∀ xs, xs≠[] → (p xs).2.length < xs.length) + (ha : ∀ xs, xs≠[] → (treeEncode (p xs).1).size+1+D*(p xs).2.length ≤ D*xs.length) : + PolyProgram (List Bool) (List α) (parseStream p) := + ((P.streamRun D hc ha).comp (PolyProgram.snd (List Bool) (List α))).comp (PolyProgram.reverse α) + +end ParityWL.Complexity + +namespace ParityWL.Complexity + +lemma streamStep_chunks {α β : Type} (p : List Bool → β × List Bool) + (enc : α → List Bool) (val : α → β) + (hp : ∀ a xs, p (enc a ++ xs) = (val a,xs)) + (he : ∀ a, enc a ≠ []) (as : List α) (bs : List β) : + (streamStep p)^[as.length] (as.flatMap enc,bs) = ([], (as.map val).reverse ++ bs) := by + induction as generalizing bs with + | nil => simp + | cons a as ih => + rw [List.length_cons, Function.iterate_succ_apply] + have hne : (a::as).flatMap enc ≠ [] := by simp [he a] + simp only [List.flatMap_cons] at hne + simp only [streamStep, List.flatMap_cons, hne, ↓reduceIte, hp] + rw [ih] + simp [List.reverse_cons, List.append_assoc] + +lemma chunks_length {α : Type} (enc : α → List Bool) (he : ∀ a, enc a ≠ []) (as : List α) : + as.length ≤ (as.flatMap enc).length := by + induction as with + | nil => simp + | cons a as ih => + have hn := List.length_pos_iff_ne_nil.mpr (he a) + simp only [List.length_cons, List.flatMap_cons, List.length_append] + omega + +lemma parseStream_chunks {α β : Type} (p : List Bool → β × List Bool) + (enc : α → List Bool) (val : α → β) + (hp : ∀ a xs, p (enc a ++ xs) = (val a,xs)) + (he : ∀ a, enc a ≠ []) (as : List α) : + parseStream p (as.flatMap enc) = as.map val := by + have hl := chunks_length enc he as + have hk : (as.flatMap enc).length = ((as.flatMap enc).length-as.length)+as.length := by omega + unfold parseStream streamRun + rw [hk, Function.iterate_add_apply, streamStep_chunks p enc val hp he] + rw [Function.iterate_fixed (streamStep_fixed p _)] + simp + +lemma encodeNat_ne_nil (n : ℕ) : encodeNat n ≠ [] := by simp [encodeNat] + +lemma encodeClause_ne_nil {N : ℕ} (C : Clause N) : encodeClause C ≠ [] := by + simp [encodeClause, encodeNat_ne_nil] + +def parseClauses (xs : List Bool) : List BitClause := parseStream readClause xs + +noncomputable def PolyProgram.parseClauses : PolyProgram (List Bool) (List BitClause) parseClauses := + PolyProgram.readClause.parseStream 40 readClause_consumes readClause_account + +lemma parseClauses_encode {N : ℕ} (F : Formula N) : + parseClauses (F.flatMap encodeClause) = F.map (fun C => C.literals.map (fun l => (l.1.val.bits,l.2))) := + parseStream_chunks readClause encodeClause _ readClause_encode encodeClause_ne_nil F + +def parseFormula (xs : List Bool) : List BitClause := + parseClauses (readNatBits (readNatBits xs).2).2 + +noncomputable def PolyProgram.parseFormula : PolyProgram (List Bool) (List BitClause) parseFormula := by + let P := PolyProgram.readNatBits.comp (PolyProgram.snd (List Bool) (List Bool)) + exact (P.comp P).comp PolyProgram.parseClauses + +lemma parseFormula_encode {N : ℕ} (F : Formula N) : + parseFormula (encodeFormula F) = F.map (fun C => C.literals.map (fun l => (l.1.val.bits,l.2))) := by + simp [parseFormula, encodeFormula, List.append_assoc, readNatBits_encode, parseClauses_encode] + +end ParityWL.Complexity + +end OAI diff --git a/lean/OAI/Combinatorics/ParityLifts/Polynomial.lean b/lean/OAI/Combinatorics/ParityLifts/Polynomial.lean new file mode 100644 index 0000000000000000000000000000000000000000..e604991ff84ee16731751a064157e28ec6f94a57 --- /dev/null +++ b/lean/OAI/Combinatorics/ParityLifts/Polynomial.lean @@ -0,0 +1,338 @@ +import OAI.Combinatorics.ParityLifts.ProgramLoops + +namespace OAI + +namespace ParityWL.Complexity + +lemma nat_poly_add (x A B a b : ℕ) (hx : 1 ≤ x) : + A * x ^ a + B * x ^ b + 1 ≤ (A + B + 1) * x ^ (a + b) := by + have ha : x ^ a ≤ x ^ (a + b) := Nat.pow_le_pow_right hx (by omega) + have hb : x ^ b ≤ x ^ (a + b) := Nat.pow_le_pow_right hx (by omega) + have h₁ := Nat.mul_le_mul_left A ha + have h₂ := Nat.mul_le_mul_left B hb + have h₃ : 1 ≤ x ^ (a + b) := Nat.one_le_pow _ _ hx + nlinarith + +lemma nat_poly_substitute (x A B a b : ℕ) (hx : 1 ≤ x) : + B * (A * x ^ a + 1) ^ b ≤ B * (A + 1) ^ b * x ^ (a * b) := by + have hp : 1 ≤ x ^ a := Nat.one_le_pow _ _ hx + calc + _ ≤ B * ((A + 1) * x ^ a) ^ b := by gcongr; nlinarith + _ = _ := by rw [mul_pow, ← pow_mul]; ring + +/-- Polynomial cost is witnessed by an actual finite tree program. -/ +structure PolyProgram (α β : Type) [TreeCodec α] [TreeCodec β] (f : α → β) where + program : TreeProgram α β f + coefficient : ℕ + degree : ℕ + bound : ∀ x, program.time x ≤ coefficient * ((treeEncode x).size + 1) ^ degree + +def PolyProgram.of_linear {α β : Type} [TreeCodec α] [TreeCodec β] {f : α → β} + (P : TreeProgram α β f) (C : ℕ) + (h : ∀ x, P.time x ≤ C * ((treeEncode x).size + 1)) : PolyProgram α β f where + program := P + coefficient := C + degree := 1 + bound := by simpa using h + +def PolyProgram.id (α : Type) [TreeCodec α] : PolyProgram α α id := + .of_linear (.id α) 1 (by intro x; simp [TreeProgram.id]) + +def PolyProgram.const {α β : Type} [TreeCodec α] [TreeCodec β] (b : β) : + PolyProgram α β (fun _ => b) := + .of_linear (.const b) (treeEncode b).size (by intro x; rfl) + +def PolyProgram.fst (α β : Type) [TreeCodec α] [TreeCodec β] : + PolyProgram (α × β) α Prod.fst := + .of_linear (.fst α β) 1 (by intro x; simp [TreeProgram.fst]) + +def PolyProgram.snd (α β : Type) [TreeCodec α] [TreeCodec β] : + PolyProgram (α × β) β Prod.snd := + .of_linear (.snd α β) 1 (by intro x; simp [TreeProgram.snd]) + +def PolyProgram.comp {α β γ : Type} [TreeCodec α] [TreeCodec β] [TreeCodec γ] + {f : α → β} {g : β → γ} (P : PolyProgram α β f) (Q : PolyProgram β γ g) : + PolyProgram α γ (g ∘ f) where + program := P.program.comp Q.program + coefficient := P.coefficient + Q.coefficient * (P.coefficient + 1) ^ Q.degree + 1 + degree := P.degree + P.degree * Q.degree + bound := by + intro x + let X := (treeEncode x).size + 1 + have hx : 1 ≤ X := by dsimp [X]; omega + have hs := (P.program.run x).bounds.2.1 + have hp := P.bound x + have hq := Q.bound (f x) + have ht : Q.program.time (f x) ≤ + Q.coefficient * (P.coefficient + 1) ^ Q.degree * X ^ (P.degree * Q.degree) := by + calc + _ ≤ Q.coefficient * (P.coefficient * X ^ P.degree + 1) ^ Q.degree := by + apply hq.trans + gcongr + exact hs.trans hp + _ ≤ _ := nat_poly_substitute X _ _ _ _ hx + exact (Nat.add_le_add_right (Nat.add_le_add hp ht) 1).trans + (nat_poly_add X _ _ _ _ hx) + +def PolyProgram.pair {α β γ : Type} [TreeCodec α] [TreeCodec β] [TreeCodec γ] + {f : α → β} {g : α → γ} (P : PolyProgram α β f) (Q : PolyProgram α γ g) : + PolyProgram α (β × γ) (fun x => (f x, g x)) where + program := P.program.pair Q.program + coefficient := P.coefficient + Q.coefficient + 1 + degree := P.degree + Q.degree + bound := by + intro x + exact (Nat.add_le_add_right (Nat.add_le_add (P.bound x) (Q.bound x)) 1).trans + (nat_poly_add _ _ _ _ _ (by omega)) + +def PolyProgram.congr {α β : Type} [TreeCodec α] [TreeCodec β] + {f g : α → β} (P : PolyProgram α β f) (h : ∀ x, f x = g x) : + PolyProgram α β g := by + have : f = g := funext h + subst g + exact P + +def PolyProgram.ite {α β : Type} [TreeCodec α] [TreeCodec β] + {p : α → Bool} {f g : α → β} (P : PolyProgram α Bool p) + (F : PolyProgram α β f) (G : PolyProgram α β g) : + PolyProgram α β (fun x => if p x then f x else g x) where + program := P.program.ite F.program G.program + coefficient := P.coefficient + (F.coefficient + G.coefficient + 1) + 1 + degree := P.degree + (F.degree + G.degree) + bound := by + intro x + have hfg := nat_poly_add ((treeEncode x).size + 1) F.coefficient G.coefficient + F.degree G.degree (by omega) + have h : (if p x then F.program.time x else G.program.time x) ≤ + (F.coefficient + G.coefficient + 1) * ((treeEncode x).size + 1) ^ (F.degree + G.degree) := by + split + · exact (F.bound x).trans ((by omega : _ ≤ _).trans hfg) + · exact (G.bound x).trans ((by omega : _ ≤ _).trans hfg) + exact (Nat.add_le_add_right (Nat.add_le_add (P.bound x) h) 1).trans + (nat_poly_add _ _ _ _ _ (by omega)) + +noncomputable def PolyProgram.equal (α : Type) [TreeCodec α] [DecidableEq α] : + PolyProgram (α × α) Bool (fun x => decide (x.1 = x.2)) where + program := TreeProgram.equal α + coefficient := 100 * (equalExpr.cost + 1) + degree := 2 + bound := fun _ => le_rfl + +end ParityWL.Complexity + +namespace ParityWL.Complexity + +def PolyProgram.expr {α β : Type} [TreeCodec α] [TreeCodec β] {f : α → β} + (e : TExpr) (he : ∀ x, e.eval (treeEncode x) = treeEncode (f x)) : PolyProgram α β f := + .of_linear { + code := e.compile + time := fun x => e.cost * ((treeEncode x).size + 1) + run := fun x => by simpa only [he] using e.run (treeEncode x) + } e.cost (fun _ => le_rfl) + +def PolyProgram.cons (α : Type) [TreeCodec α] : + PolyProgram (α × List α) (List α) (fun x => x.1 :: x.2) := + .expr .input (fun _ => rfl) + +def PolyProgram.tail (α : Type) [TreeCodec α] : + PolyProgram (List α) (List α) List.tail := + .expr (TExpr.input.right) (by intro x; cases x <;> rfl) + +def PolyProgram.head (α : Type) [TreeCodec α] (a : α) : + PolyProgram (List α) α (fun x => x.headD a) := + .expr (.cond .input (.const (treeEncode a)) TExpr.input.left) + (by intro x; cases x <;> rfl) + +def PolyProgram.null (α : Type) [TreeCodec α] : + PolyProgram (List α) Bool List.isEmpty := + .expr (.cond .input (.const (boolTree true)) .nil) + (by intro x; cases x <;> rfl) + +def PolyProgram.not : PolyProgram Bool Bool Bool.not := + .expr (.cond .input (.const (boolTree true)) .nil) + (by intro x; cases x <;> rfl) + +def PolyProgram.and : PolyProgram (Bool × Bool) Bool (fun x => x.1 && x.2) := + .expr (.cond TExpr.input.left .nil TExpr.input.right) + (by intro x; rcases x with ⟨a, b⟩; cases a <;> rfl) + +def PolyProgram.or : PolyProgram (Bool × Bool) Bool (fun x => x.1 || x.2) := + .expr (.cond TExpr.input.left TExpr.input.right (.const (boolTree true))) + (by intro x; rcases x with ⟨a, b⟩; cases a <;> rfl) + +lemma treeEncode_list_length {α : Type} [TreeCodec α] (xs : List α) : + xs.length + 1 ≤ (treeEncode xs).size := by + induction xs with + | nil => rfl + | cons a xs ih => simp [DataTree.size]; omega + +lemma treeEncode_of_mem {α : Type} [TreeCodec α] {a : α} {xs : List α} (ha : a ∈ xs) : + (treeEncode a).size + 1 ≤ (treeEncode xs).size := by + induction xs with + | nil => simp at ha + | cons b xs ih => + rcases List.mem_cons.mp ha with he | ht + · subst b; simp [DataTree.size]; omega + · have := ih ht + simp [DataTree.size]; omega + +lemma treeEncode_append_size {α : Type} [TreeCodec α] (xs ys : List α) : + (treeEncode (xs ++ ys)).size + 1 = (treeEncode xs).size + (treeEncode ys).size := by + induction xs with + | nil => simp [DataTree.size]; omega + | cons a xs ih => simp [DataTree.size]; omega + +lemma treeEncode_reverse_size {α : Type} [TreeCodec α] (xs : List α) : + (treeEncode xs.reverse).size = (treeEncode xs).size := by + simp only [treeEncode_list_size, List.map_reverse, List.sum_reverse] + +lemma TreeProgram.foldWork_growing {α β : Type} [TreeCodec α] [TreeCodec β] + {f : α × β → β} (P : PolyProgram (α × β) β f) (w : α → ℕ) + (hw : ∀ a b, (treeEncode (f (a, b))).size ≤ (treeEncode b).size + w a) + (xs : List α) (b : β) : + let W := (treeEncode xs).size + (treeEncode b).size + (xs.map w).sum + 1 + P.program.foldWork xs b ≤ (xs.length + 1) * + (10 * (W + 1) + P.coefficient * (W + 1) ^ P.degree + 1) := by + dsimp only + induction xs generalizing b with + | nil => simp only [foldWork, treeEncode_pair, DataTree.size, treeEncode_nil, + List.map_nil, List.sum_nil, List.length_nil]; omega + | cons a xs ih => + have hi := ih (f (a, b)) + have hg := hw a b + let W := (treeEncode (a :: xs)).size + (treeEncode b).size + + ((a :: xs).map w).sum + 1 + have hw' : (treeEncode xs).size + (treeEncode (f (a, b))).size + + (xs.map w).sum + 1 ≤ W := by + simp only [W, treeEncode_cons, DataTree.size, List.map_cons, List.sum_cons] + omega + have hp : P.program.time (a, b) ≤ P.coefficient * (W + 1) ^ P.degree := by + apply (P.bound (a, b)).trans + gcongr + simp only [treeEncode_pair, DataTree.size, W, treeEncode_cons, List.map_cons, List.sum_cons] + omega + have hm : 10 * ((treeEncode xs).size + (treeEncode (f (a, b))).size + (xs.map w).sum + 1 + 1) + + P.coefficient * ((treeEncode xs).size + (treeEncode (f (a, b))).size + (xs.map w).sum + 1 + 1) ^ P.degree + 1 ≤ + 10 * (W + 1) + P.coefficient * (W + 1) ^ P.degree + 1 := by gcongr + have hm' := Nat.mul_le_mul_left (xs.length + 1) hm + have hstate : (treeEncode (a :: xs, b)).size ≤ W := by + simp only [treeEncode_pair, DataTree.size, W]; omega + change _ ≤ (List.length (a :: xs) + 1) * + (10 * (W + 1) + P.coefficient * (W + 1) ^ P.degree + 1) + simp only [foldWork, List.length_cons] + nlinarith + +end ParityWL.Complexity + +namespace ParityWL.Complexity + +lemma list_sum_map_le {α : Type} (l : List α) (w : α → ℕ) (B : ℕ) + (h : ∀ x ∈ l, w x ≤ B) : (l.map w).sum ≤ l.length * B := by + induction l with + | nil => simp + | cons x xs ih => + have hx := h x (by simp) + have ht := ih (fun a ha => h a (by simp [ha])) + simp only [List.length_cons, List.map_cons, List.sum_cons] + nlinarith + +lemma list_polynomial_sum {α : Type} [TreeCodec α] (xs : List α) (D e : ℕ) : + (xs.map (fun a => D * ((treeEncode a).size + 1) ^ e)).sum ≤ + D * (treeEncode xs).size ^ (e + 1) := by + have h := list_sum_map_le xs (fun a => D * ((treeEncode a).size + 1) ^ e) + (D * (treeEncode xs).size ^ e) (by + intro a ha + gcongr + exact treeEncode_of_mem ha) + have hl := treeEncode_list_length xs + calc + _ ≤ xs.length * (D * (treeEncode xs).size ^ e) := h + _ ≤ (treeEncode xs).size * (D * (treeEncode xs).size ^ e) := by gcongr; omega + _ = _ := by rw [pow_succ]; ring + +def PolyProgram.foldlGrowing {α β : Type} [TreeCodec α] [TreeCodec β] + {f : α × β → β} (P : PolyProgram (α × β) β f) (D e : ℕ) + (hg : ∀ a b, (treeEncode (f (a, b))).size ≤ + (treeEncode b).size + D * ((treeEncode a).size + 1) ^ e) : + PolyProgram (List α × β) β (fun x => x.1.foldl (fun b a => f (a, b)) x.2) where + program := P.program.foldl + coefficient := 2 * (10 * (D + 2) + P.coefficient * (D + 2) ^ P.degree + 1) + 1 + degree := (e + 1) + (e + 1) * P.degree + 1 + bound := by + rintro ⟨xs, b⟩ + let X := (treeEncode (xs, b)).size + 1 + let m := e + 1 + let d := P.degree + let H := D + 2 + let A := 10 * H + P.coefficient * H ^ d + 1 + let W := (treeEncode xs).size + (treeEncode b).size + + (xs.map (fun a => D * ((treeEncode a).size + 1) ^ e)).sum + 1 + have hx : 1 ≤ X := by dsimp [X]; omega + have hxL : (treeEncode xs).size ≤ X := by simp [X, DataTree.size]; omega + have hlen : xs.length + 1 ≤ X := (treeEncode_list_length xs).trans hxL + have hw : W + 1 ≤ H * X ^ m := by + have hsum := list_polynomial_sum xs D e + have hsum' : D * (treeEncode xs).size ^ (e + 1) ≤ D * X ^ m := by + dsimp only [m]; gcongr + have hpow : X ≤ X ^ m := by + simpa using Nat.pow_le_pow_right hx (show 1 ≤ m by dsimp [m]; omega) + have hp : 1 ≤ X ^ m := Nat.one_le_pow _ _ hx + have heq : W + 1 = X + (xs.map (fun a => D * ((treeEncode a).size + 1) ^ e)).sum := by + simp only [W, X, treeEncode_pair, DataTree.size] + omega + rw [heq] + dsimp only [H] + nlinarith + have hbody : 10 * (W + 1) + P.coefficient * (W + 1) ^ d + 1 ≤ A * X ^ (m + m * d) := by + have h₁ := Nat.mul_le_mul_left 10 hw + have h₂ : P.coefficient * (W + 1) ^ d ≤ + P.coefficient * H ^ d * X ^ (m * d) := by + calc + _ ≤ P.coefficient * (H * X ^ m) ^ d := by gcongr + _ = _ := by rw [mul_pow, ← pow_mul]; ring + have h := nat_poly_add X (10 * H) (P.coefficient * H ^ d) m (m * d) hx + dsimp only [A] + nlinarith + have hfold := TreeProgram.foldWork_growing P + (fun a => D * ((treeEncode a).size + 1) ^ e) hg xs b + change _ ≤ (xs.length + 1) * (10 * (W + 1) + P.coefficient * (W + 1) ^ d + 1) at hfold + have hwork : P.program.foldWork xs b ≤ A * X ^ (m + m * d + 1) := by + calc + _ ≤ (xs.length + 1) * (10 * (W + 1) + P.coefficient * (W + 1) ^ d + 1) := hfold + _ ≤ X * (A * X ^ (m + m * d)) := Nat.mul_le_mul hlen hbody + _ = _ := by rw [pow_succ]; ring + have hout := (P.program.foldLoop_run xs b).bounds.2.1 + have hp : 1 ≤ X ^ (m + m * d + 1) := Nat.one_le_pow _ _ hx + change P.program.foldWork xs b + + (treeEncode (([] : List α), xs.foldl (fun c a => f (a, c)) b)).size + 1 ≤ + (2 * A + 1) * X ^ (m + m * d + 1) + nlinarith + +lemma list_fold_cons {α : Type} (xs ys : List α) : + xs.foldl (fun b a => a :: b) ys = xs.reverse ++ ys := by + induction xs generalizing ys with + | nil => simp + | cons a xs ih => simp [ih, List.append_assoc] + +def PolyProgram.reverse (α : Type) [TreeCodec α] : + PolyProgram (List α) (List α) List.reverse := by + let P := (PolyProgram.cons α).foldlGrowing 1 1 (by + intro a b + simp [DataTree.size] + omega) + exact ((PolyProgram.id (List α)).pair (PolyProgram.const ([] : List α))).comp P |>.congr + (by intro xs; simp) + +def PolyProgram.append (α : Type) [TreeCodec α] : + PolyProgram (List α × List α) (List α) (fun x => x.1 ++ x.2) := by + let P := (PolyProgram.cons α).foldlGrowing 1 1 (by + intro a b + simp [DataTree.size] + omega) + exact (((PolyProgram.fst (List α) (List α)).comp (PolyProgram.reverse α)).pair + (PolyProgram.snd (List α) (List α))).comp P |>.congr + (by intro x; simp) + +end ParityWL.Complexity + +end OAI diff --git a/lean/OAI/Combinatorics/ParityLifts/PolynomialLists.lean b/lean/OAI/Combinatorics/ParityLifts/PolynomialLists.lean new file mode 100644 index 0000000000000000000000000000000000000000..014ac7916653e23814dfba2ad1c9b413fa479714 --- /dev/null +++ b/lean/OAI/Combinatorics/ParityLifts/PolynomialLists.lean @@ -0,0 +1,181 @@ +import OAI.Combinatorics.ParityLifts.Polynomial + +namespace OAI + +namespace ParityWL.Complexity + +def PolyProgram.map {α β : Type} [TreeCodec α] [TreeCodec β] + {f : α → β} (P : PolyProgram α β f) : + PolyProgram (List α) (List β) (List.map f) := by + let stepP := ((PolyProgram.fst α (List β)).comp P).pair (PolyProgram.snd α (List β)) |>.comp + (PolyProgram.cons β) + have hg (a : α) (bs : List β) : + (treeEncode (f a :: bs)).size ≤ (treeEncode bs).size + + (P.coefficient + 1) * ((treeEncode a).size + 1) ^ (P.degree + 1) := by + have hs := (P.program.run a).bounds.2.1 + have ht := P.bound a + have hm : ((treeEncode a).size + 1) ^ P.degree ≤ + ((treeEncode a).size + 1) ^ (P.degree + 1) := Nat.pow_le_pow_right (by omega) (by omega) + have hm' := Nat.mul_le_mul_left P.coefficient hm + have hp : 1 ≤ ((treeEncode a).size + 1) ^ (P.degree + 1) := Nat.one_le_pow _ _ (by omega) + simp only [treeEncode_cons, DataTree.size] + nlinarith + let F := stepP.foldlGrowing (P.coefficient + 1) (P.degree + 1) hg + let init := (PolyProgram.id (List α)).pair (PolyProgram.const ([] : List β)) + refine (init.comp F |>.comp (PolyProgram.reverse β)).congr ?_ + intro xs + change (xs.foldl (fun bs a => f a :: bs) []).reverse = xs.map f + have he (xs : List α) (bs : List β) : + xs.foldl (fun ys a => f a :: ys) bs = (xs.map f).reverse ++ bs := by + induction xs generalizing bs with + | nil => simp + | cons a xs ih => simp [ih, List.append_assoc] + simp [he] + +def PolyProgram.filter {α : Type} [TreeCodec α] + {f : α → Bool} (P : PolyProgram α Bool f) : + PolyProgram (List α) (List α) (List.filter f) := by + let stepP := ((PolyProgram.fst α (List α)).comp P).ite + (PolyProgram.cons α) (PolyProgram.snd α (List α)) + have hg (a : α) (bs : List α) : + (treeEncode (if f a then a :: bs else bs)).size ≤ + (treeEncode bs).size + 1 * ((treeEncode a).size + 1) ^ 1 := by + cases f a <;> simp only [Bool.false_eq_true, ↓reduceIte, treeEncode_cons, DataTree.size, Nat.one_mul, pow_one] <;> omega + let F := stepP.foldlGrowing 1 1 hg + refine (((PolyProgram.id (List α)).pair (PolyProgram.const ([] : List α))).comp F |>.comp + (PolyProgram.reverse α)).congr ?_ + intro xs + change (xs.foldl (fun bs a => if f a then a :: bs else bs) []).reverse = xs.filter f + have he (xs : List α) (bs : List α) : + xs.foldl (fun ys a => if f a then a :: ys else ys) bs = (xs.filter f).reverse ++ bs := by + induction xs generalizing bs with + | nil => simp + | cons a xs ih => cases h : f a <;> simp [h, ih, List.append_assoc] + simp [he] + +def PolyProgram.flatten (α : Type) [TreeCodec α] : + PolyProgram (List (List α)) (List α) List.flatten := by + let stepP := PolyProgram.append α + have hg (a b : List α) : (treeEncode (a ++ b)).size ≤ + (treeEncode b).size + 1 * ((treeEncode a).size + 1) ^ 1 := by + have := treeEncode_append_size a b + simp only [Nat.one_mul, pow_one] + omega + let F := stepP.foldlGrowing 1 1 hg + let init := ((PolyProgram.reverse (List α)).pair (PolyProgram.const ([] : List α))) + refine (init.comp F).congr ?_ + intro xs + change xs.reverse.foldl (fun bs a => a ++ bs) [] = xs.flatten + rw [List.foldl_reverse] + induction xs with + | nil => rfl + | cons a xs ih => simp [ih] + +end ParityWL.Complexity + +namespace ParityWL.Complexity + +lemma TreeProgram.foldWork_prefix {α β : Type} [TreeCodec α] [TreeCodec β] + {f : α × β → β} (P : TreeProgram (α × β) β f) (xs : List α) (b : β) (S B : ℕ) + (hs : ∀ ys zs, ys ++ zs = xs → + (treeEncode (zs, ys.foldl (fun c a => f (a, c)) b)).size ≤ S) + (hb : ∀ ys a zs, ys ++ a :: zs = xs → + P.time (a, ys.foldl (fun c a => f (a, c)) b) ≤ B) : + P.foldWork xs b ≤ (xs.length + 1) * (10 * (S + 1) + B + 1) := by + induction xs generalizing b with + | nil => + have h := hs [] [] rfl + simpa only [foldWork, List.nil_append, List.foldl_nil] using h.trans + (show S ≤ (List.length ([] : List α) + 1) * (10 * (S + 1) + B + 1) by simp; omega) + | cons a xs ih => + have h := hs [] (a :: xs) rfl + have hb₀ := hb [] a xs rfl + have ht := ih (f (a, b)) + (fun ys zs he => by + simpa using hs (a :: ys) zs (by simpa using congrArg (List.cons a) he)) + (fun ys c zs he => by + simpa using hb (a :: ys) c zs (by simpa using congrArg (List.cons a) he)) + simp only [List.foldl_nil] at h hb₀ + simp only [foldWork, List.length_cons] + nlinarith + +def PolyProgram.foldlBounded {α β : Type} [TreeCodec α] [TreeCodec β] + {f : α × β → β} (P : PolyProgram (α × β) β f) (A e : ℕ) + (hg : ∀ (xs : List α) (b : β), (treeEncode (xs.foldl (fun c a => f (a, c)) b)).size ≤ + A * ((treeEncode (xs, b)).size + 1) ^ e) : + PolyProgram (List α × β) β (fun x => x.1.foldl (fun b a => f (a, b)) x.2) where + program := P.program.foldl + coefficient := 2 * (10 * (A + 3) + P.coefficient * (A + 3) ^ P.degree + 1) + 1 + degree := (e + 1) + (e + 1) * P.degree + 1 + bound := by + rintro ⟨xs, b⟩ + let X := (treeEncode (xs, b)).size + 1 + let R := A * X ^ e + let S := (treeEncode xs).size + R + 1 + let m := e + 1 + let d := P.degree + let H := A + 3 + let K := 10 * H + P.coefficient * H ^ d + 1 + have hx : 1 ≤ X := by dsimp [X]; omega + have hxL : (treeEncode xs).size ≤ X := by simp [X, DataTree.size]; omega + have hlen : xs.length + 1 ≤ X := (treeEncode_list_length xs).trans hxL + have hpref (ys zs : List α) (he : ys ++ zs = xs) : + (treeEncode (ys.foldl (fun c a => f (a, c)) b)).size ≤ R := by + have h := treeEncode_append_size ys zs + have hz := (treeEncode zs).size_pos + rw [he] at h + apply (hg ys b).trans + dsimp only [R] + gcongr + simp only [X, treeEncode_pair, DataTree.size] + omega + have hW : S + 1 ≤ H * X ^ m := by + have he : X ^ e ≤ X ^ m := Nat.pow_le_pow_right hx (by dsimp [m]; omega) + have hm : X ≤ X ^ m := by + simpa using Nat.pow_le_pow_right hx (show 1 ≤ m by dsimp [m]; omega) + have hp : 1 ≤ X ^ m := Nat.one_le_pow _ _ hx + have he' := Nat.mul_le_mul_left A he + dsimp only [S, R, H] + nlinarith + have hs (ys zs : List α) (he : ys ++ zs = xs) : + (treeEncode (zs, ys.foldl (fun c a => f (a, c)) b)).size ≤ S := by + have h := hpref ys zs he + have hzs := treeEncode_append_size ys zs + have hy := (treeEncode ys).size_pos + rw [he] at hzs + simp only [treeEncode_pair, DataTree.size, S] + omega + have hb (ys : List α) (a : α) (zs : List α) (he : ys ++ a :: zs = xs) : + P.program.time (a, ys.foldl (fun c a => f (a, c)) b) ≤ + P.coefficient * (S + 1) ^ d := by + have hz := hs ys (a :: zs) he + apply (P.bound _).trans + dsimp only [d] + gcongr + simp only [treeEncode_pair, treeEncode_cons, DataTree.size] at hz ⊢ + omega + have hfold := P.program.foldWork_prefix xs b S (P.coefficient * (S + 1) ^ d) hs hb + have hbody : 10 * (S + 1) + P.coefficient * (S + 1) ^ d + 1 ≤ K * X ^ (m + m * d) := by + have h₁ := Nat.mul_le_mul_left 10 hW + have h₂ : P.coefficient * (S + 1) ^ d ≤ P.coefficient * H ^ d * X ^ (m * d) := by + calc + _ ≤ P.coefficient * (H * X ^ m) ^ d := by gcongr + _ = _ := by rw [mul_pow, ← pow_mul]; ring + have h := nat_poly_add X (10 * H) (P.coefficient * H ^ d) m (m * d) hx + dsimp only [K] + nlinarith + have hwork : P.program.foldWork xs b ≤ K * X ^ (m + m * d + 1) := by + calc + _ ≤ (xs.length + 1) * (10 * (S + 1) + P.coefficient * (S + 1) ^ d + 1) := hfold + _ ≤ X * (K * X ^ (m + m * d)) := Nat.mul_le_mul hlen hbody + _ = _ := by rw [pow_succ]; ring + have hout := (P.program.foldLoop_run xs b).bounds.2.1 + have hp : 1 ≤ X ^ (m + m * d + 1) := Nat.one_le_pow _ _ hx + change P.program.foldWork xs b + + (treeEncode (([] : List α), xs.foldl (fun c a => f (a, c)) b)).size + 1 ≤ + (2 * K + 1) * X ^ (m + m * d + 1) + nlinarith + +end ParityWL.Complexity + +end OAI diff --git a/lean/OAI/Combinatorics/ParityLifts/ProgramLoops.lean b/lean/OAI/Combinatorics/ParityLifts/ProgramLoops.lean new file mode 100644 index 0000000000000000000000000000000000000000..f6b761cb6de3dcc911abf76d1cbe3be91b5876a0 --- /dev/null +++ b/lean/OAI/Combinatorics/ParityLifts/ProgramLoops.lean @@ -0,0 +1,166 @@ +import OAI.Combinatorics.ParityLifts.TreePrograms + +namespace OAI + +namespace ParityWL.Complexity + +@[simp] lemma treeEncode_tree (t : DataTree) : treeEncode t = t := rfl + +lemma TreeProgram.loop_wf {α : Type} [TreeCodec α] {f : α → α} + (P : TreeProgram α α f) (I : α → Prop) (μ : α → ℕ) (C : ℕ) + (hs : ∀ x, I x → (treeEncode x).size ≤ C * (μ x + 1)) + (hb : ∀ x, I x → (treeEncode x).child false ≠ .nil → P.time x ≤ C * (μ x + 1)) + (hn : ∀ x, I x → (treeEncode x).child false ≠ .nil → I (f x) ∧ μ (f x) < μ x) + (x : α) (hx : I x) : + ∃ y, I y ∧ (treeEncode y).child false = .nil ∧ + BEval (.loop P.code) (treeEncode x) ((2 * C + 1) * (μ x + 1) ^ 2) (treeEncode y) := by + generalize he : μ x = n + induction n using Nat.strong_induction_on generalizing x with + | h n ih => + by_cases hg : (treeEncode x).child false = .nil + · refine ⟨x, hx, hg, (BEval.loop_stop P.code (treeEncode x) hg).mono ?_⟩ + rw [← he] + have hsq : μ x + 1 ≤ (μ x + 1) ^ 2 := by nlinarith [Nat.zero_le (μ x ^ 2)] + calc + _ ≤ C * (μ x + 1) := hs x hx + _ ≤ C * (μ x + 1) ^ 2 := Nat.mul_le_mul_left C hsq + _ ≤ (2 * C + 1) * (μ x + 1) ^ 2 := Nat.mul_le_mul_right _ (by omega) + · obtain ⟨hI, hμ⟩ := hn x hx hg + obtain ⟨y, hy, hnil, hr⟩ := ih (μ (f x)) (by omega) (f x) hI rfl + refine ⟨y, hy, hnil, (BEval.loop_next hg ((P.run x).mono (hb x hx hg)) hr).mono ?_⟩ + rw [← he] + have hsq : (μ (f x) + 1) ^ 2 ≤ (μ x) ^ 2 := Nat.pow_le_pow_left (by omega) 2 + have hmul := Nat.mul_le_mul_left (2 * C + 1) hsq + nlinarith + +abbrev EqualState := List (DataTree × DataTree) × Bool + +def equalStep : EqualState → EqualState + | ([], b) => ([], b) + | ((.nil, .nil) :: xs, b) => (xs, b) + | ((.node l r, .node l' r') :: xs, b) => ((l, l') :: (r, r') :: xs, b) + | (_ :: _, _) => ([], false) + +def equalExpr : TExpr := + let tasks := TExpr.input.left + let flag := TExpr.input.right + let x := tasks.left.left + let y := tasks.left.right + let pop := TExpr.pair tasks.right flag + let fail := TExpr.pair .nil .nil + let expand := TExpr.pair + (.pair (.pair x.left y.left) (.pair (.pair x.right y.right) tasks.right)) flag + .cond x (.cond y pop fail) (.cond y fail expand) + +lemma equalExpr_eval (s : EqualState) : equalExpr.eval (treeEncode s) = treeEncode (equalStep s) := by + rcases s with ⟨xs, b⟩ + cases xs with + | nil => simp [equalExpr, TExpr.eval, DataTree.child, equalStep] + | cons p xs => + rcases p with ⟨x, y⟩ + cases x <;> cases y <;> simp [equalExpr, TExpr.eval, DataTree.child, equalStep] + +def equalStepProgram : TreeProgram EqualState EqualState equalStep where + code := equalExpr.compile + time := fun x => equalExpr.cost * ((treeEncode x).size + 1) + run := fun x => by simpa only [equalExpr_eval] using equalExpr.run (treeEncode x) + +def equalMeasure (s : EqualState) : ℕ := (s.1.map (fun p => p.1.size + p.2.size)).sum + +def equalGood (s : EqualState) : Prop := s.2 = true ∧ ∀ p ∈ s.1, p.1 = p.2 + +lemma equalStep_good (s : EqualState) : equalGood (equalStep s) ↔ equalGood s := by + rcases s with ⟨xs, b⟩ + cases xs with + | nil => rfl + | cons p xs => + rcases p with ⟨x, y⟩ + cases x <;> cases y <;> simp [equalStep, equalGood, and_assoc, and_comm] + +lemma equalStep_decreases (s : EqualState) (hs : (treeEncode s).child false ≠ .nil) : + equalMeasure (equalStep s) < equalMeasure s := by + rcases s with ⟨xs, b⟩ + cases xs with + | nil => simp [DataTree.child] at hs + | cons p xs => + rcases p with ⟨x, y⟩ + cases x <;> cases y + all_goals simp [equalStep, equalMeasure, DataTree.size] + all_goals omega + +lemma equalState_size (s : EqualState) : (treeEncode s).size ≤ 2 * equalMeasure s + 5 := by + rcases s with ⟨xs, b⟩ + have hlist : (treeEncode xs).size ≤ 2 * (xs.map (fun p => p.1.size + p.2.size)).sum + 1 := by + induction xs with + | nil => simp [DataTree.size] + | cons p xs ih => + rcases p with ⟨x, y⟩ + have hx := x.size_pos + have hy := y.size_pos + simp only [treeEncode_cons, DataTree.size, treeEncode_pair, treeEncode_tree, + List.map_cons, List.sum_cons] + omega + change 1 + (treeEncode xs).size + (treeEncode b).size ≤ + 2 * (xs.map (fun p => p.1.size + p.2.size)).sum + 5 + cases b <;> simp only [treeEncode_false, treeEncode_true, DataTree.size] <;> omega + +def FCode.treeEqual : FCode := + .seq (.pair (.pair .id .nil) (.const (boolTree true))) + (.seq (.loop equalStepProgram.code) .right) + +lemma BEval.treeEqual (x y : DataTree) : + BEval FCode.treeEqual (.node x y) + (100 * (equalExpr.cost + 1) * ((DataTree.node x y).size + 1) ^ 2) + (treeEncode (decide (x = y))) := by + let C := 6 * (equalExpr.cost + 1) + have hs (s : EqualState) : (treeEncode s).size ≤ C * (equalMeasure s + 1) := by + have := equalState_size s + change (treeEncode s).size ≤ 6 * (equalExpr.cost + 1) * (equalMeasure s + 1) + nlinarith + have hb (s : EqualState) : equalStepProgram.time s ≤ C * (equalMeasure s + 1) := by + have := equalState_size s + change equalExpr.cost * ((treeEncode s).size + 1) ≤ + 6 * (equalExpr.cost + 1) * (equalMeasure s + 1) + nlinarith + obtain ⟨s, hi, he, hr⟩ := equalStepProgram.loop_wf + (fun s => equalGood s ↔ x = y) equalMeasure C + (fun s _ => hs s) (fun s _ _ => hb s) + (fun s h hne => ⟨(equalStep_good s).trans h, equalStep_decreases s hne⟩) + ([(x, y)], true) (by simp [equalGood]) + have hnil : s.1 = [] := by + have henc : treeEncode s.1 = .nil := by simpa [DataTree.child] using he + exact TreeCodec.injective (by simpa using henc) + have hbool : s.2 = decide (x = y) := by + simp only [equalGood, hnil, List.not_mem_nil, IsEmpty.forall_iff, implies_true, and_true] at hi + cases h : s.2 <;> simp_all + have hinit := (BEval.id (.node x y)).pair (BEval.nil (.node x y)) + have hini := hinit.pair (BEval.const (boolTree true) (.node x y)) + have ht := hr.seq (BEval.right (treeEncode s)) + have h := hini.seq (by simpa [boolTree] using ht) + have hout := hr.bounds.2.1 + simpa [FCode.treeEqual, DataTree.child, hbool] using h.mono (show _ ≤ + 100 * (equalExpr.cost + 1) * ((DataTree.node x y).size + 1) ^ 2 from by + simp only [equalMeasure, C, List.map_cons, List.map_nil, List.sum_cons, List.sum_nil, + Nat.add_zero] at hout ⊢ + simp only [boolTree, ↓reduceIte, DataTree.size] + simp only [treeEncode_prod, DataTree.size] at hout + generalize equalExpr.cost = E at hout ⊢ + nlinarith only [hout, Nat.zero_le E, Nat.zero_le x.size, Nat.zero_le y.size, + Nat.zero_le (E * (x.size + y.size + 1) ^ 2), Nat.zero_le (E * x.size), + Nat.zero_le (E * y.size)]) + +noncomputable def TreeProgram.equal (α : Type) [TreeCodec α] [DecidableEq α] : + TreeProgram (α × α) Bool (fun x => decide (x.1 = x.2)) := by + classical + exact { + code := FCode.treeEqual + time := fun x => 100 * (equalExpr.cost + 1) * ((treeEncode x).size + 1) ^ 2 + run := fun x => by + have he : (treeEncode x.1 = treeEncode x.2) ↔ x.1 = x.2 := + ⟨fun h => TreeCodec.injective (α := α) h, congrArg treeEncode⟩ + simpa [he] using BEval.treeEqual (treeEncode x.1) (treeEncode x.2) + } + +end ParityWL.Complexity + +end OAI diff --git a/lean/OAI/Combinatorics/ParityLifts/PureComponents.lean b/lean/OAI/Combinatorics/ParityLifts/PureComponents.lean new file mode 100644 index 0000000000000000000000000000000000000000..c4926d6cac08b477e0ada625055af4eeaa36d1a3 --- /dev/null +++ b/lean/OAI/Combinatorics/ParityLifts/PureComponents.lean @@ -0,0 +1,186 @@ +import OAI.Combinatorics.ParityLifts.ColorSpan + +namespace OAI + +namespace ParityWL + +open scoped BigOperators + +section InducedBagTree + +open scoped Classical + +variable {A N : Type} {R : A → A → Prop} {t : ℕ} + +noncomputable def RankedBagTree.induce (D : RankedBagTree (N := N) R t) (P : A → Prop) : + RankedBagTree (N := N) (fun a b : Subtype P => R a.1 b.1) t where + toRankedTree := D.toRankedTree + bag n := (D.bag n).subtype P + top a := D.top a.1 + top_mem a := Finset.mem_subtype.mpr (D.top_mem a.1) + top_ancestor a n ha := D.top_ancestor a.1 n (Finset.mem_subtype.mp ha) + interval_mem a n l hn hnl ha := + Finset.mem_subtype.mpr (D.interval_mem a.1 n l hn hnl (Finset.mem_subtype.mp ha)) + edge_cover a b hab := by + obtain ⟨n, han, hbn⟩ := D.edge_cover a.1 b.1 hab + exact ⟨n, Finset.mem_subtype.mpr han, Finset.mem_subtype.mpr hbn⟩ + width n := by + rw [Finset.card_subtype] + exact (Finset.card_filter_le _ _).trans (D.width n) + intersection n hn := by + let : DecidableEq (Subtype P) := Classical.decEq _ + have he : (D.bag n).subtype P ∩ (D.bag (D.parent n)).subtype P = + (D.bag n ∩ D.bag (D.parent n)).subtype P := by + ext a + simp only [Finset.mem_inter, Finset.mem_subtype] + rw [he, Finset.card_subtype] + exact lt_of_le_of_lt (Finset.card_filter_le _ _) (D.intersection n hn) + +end InducedBagTree + +section PureComponents + +open scoped Classical + +variable {k t : ℕ} (F : RootedTest k t) +variable {V W : Type} (G : SimpleGraph V) (H : SimpleGraph W) + +noncomputable def PureLeftMaps := + {f : RelationMaps F.relation (G.sum H) // ∀ i, (f.1 (F.roots i)).isLeft} + +noncomputable instance pureLeftMapsFintype [Fintype V] [Fintype W] : Fintype (PureLeftMaps F G H) := by + unfold PureLeftMaps + infer_instance + +def ComponentMask := {s : F.Vertex → Bool // + (∀ a b, F.relation a b → s a = s b) ∧ ∀ i, s (F.roots i) = true} + +noncomputable instance componentMaskFintype : Fintype (ComponentMask F) := by + unfold ComponentMask + infer_instance + +abbrev MaskLeft (s : ComponentMask F) := {a : F.Vertex // s.1 a = true} +abbrev MaskRight (s : ComponentMask F) := {a : F.Vertex // s.1 a = false} + +noncomputable def ComponentMaps (s : ComponentMask F) := + RelationMaps (fun a b : MaskLeft F s => F.relation a.1 b.1) G × + RelationMaps (fun a b : MaskRight F s => F.relation a.1 b.1) H + +noncomputable instance componentMapsFintype [Fintype V] [Fintype W] (s : ComponentMask F) : + Fintype (ComponentMaps F G H s) := by + unfold ComponentMaps + infer_instance + +noncomputable def assembleFunction (s : ComponentMask F) (f : ComponentMaps F G H s) + (a : F.Vertex) : V ⊕ W := + if h : s.1 a = true then .inl (f.1.1 ⟨a, h⟩) + else .inr (f.2.1 ⟨a, Bool.eq_false_iff.mpr h⟩) + +lemma assembleFunction_left (s : ComponentMask F) (f : ComponentMaps F G H s) + (a : MaskLeft F s) : assembleFunction F G H s f a.1 = .inl (f.1.1 a) := by + simp only [assembleFunction, dite_eq_left a.2] + +lemma assembleFunction_right (s : ComponentMask F) (f : ComponentMaps F G H s) + (a : MaskRight F s) : assembleFunction F G H s f a.1 = .inr (f.2.1 a) := by + have ha : s.1 a.1 ≠ true := by rw [a.2]; decide + simp only [assembleFunction, dite_eq_right ha] + +lemma assembleFunction_isLeft (s : ComponentMask F) (f : ComponentMaps F G H s) + (a : F.Vertex) : (assembleFunction F G H s f a).isLeft = s.1 a := by + by_cases h : s.1 a = true + · rw [assembleFunction_left F G H s f ⟨a, h⟩] + exact h.symm + · rw [assembleFunction_right F G H s f ⟨a, Bool.eq_false_iff.mpr h⟩] + exact (Bool.eq_false_iff.mpr h).symm + +noncomputable def assemblePure (f : (s : ComponentMask F) × ComponentMaps F G H s) : + PureLeftMaps F G H := ⟨⟨assembleFunction F G H f.1 f.2, by + intro a b hab + have he := f.1.2.1 a b hab + by_cases ha : f.1.1 a = true + · have hb : f.1.1 b = true := he.symm.trans ha + rw [assembleFunction_left F G H f.1 f.2 ⟨a, ha⟩, + assembleFunction_left F G H f.1 f.2 ⟨b, hb⟩] + exact f.2.1.2 ⟨a, ha⟩ ⟨b, hb⟩ hab + · have ha' : f.1.1 a = false := Bool.eq_false_iff.mpr ha + have hb : f.1.1 b = false := he.symm.trans ha' + rw [assembleFunction_right F G H f.1 f.2 ⟨a, ha'⟩, + assembleFunction_right F G H f.1 f.2 ⟨b, hb⟩] + exact f.2.2.2 ⟨a, ha'⟩ ⟨b, hb⟩ hab⟩, + fun i => by rw [assembleFunction_isLeft]; exact f.1.2.2 i⟩ + +lemma assemblePure_injective : Function.Injective (assemblePure F G H) := by + rintro ⟨s, f⟩ ⟨s', f'⟩ he + have hefun (a : F.Vertex) : assembleFunction F G H s f a = assembleFunction F G H s' f' a := + congrFun (congrArg (fun p => p.1.1) he) a + have hs : s = s' := by + apply Subtype.ext + funext a + rw [← assembleFunction_isLeft F G H s f a, ← assembleFunction_isLeft F G H s' f' a, hefun a] + subst s' + apply congrArg (Sigma.mk s) + apply Prod.ext + · apply Subtype.ext + funext a + apply Sum.inl_injective + rw [← assembleFunction_left F G H s f a, ← assembleFunction_left F G H s f' a] + exact hefun a.1 + · apply Subtype.ext + funext a + apply Sum.inr_injective + rw [← assembleFunction_right F G H s f a, ← assembleFunction_right F G H s f' a] + exact hefun a.1 + +lemma sum_adj_same_side {a b : V ⊕ W} (h : (G.sum H).Adj a b) : a.isLeft = b.isLeft := by + cases a <;> cases b <;> simp_all only [SimpleGraph.sum_adj, Sum.isLeft_inl, Sum.isLeft_inr] + +noncomputable def mapMask (f : PureLeftMaps F G H) : ComponentMask F := + ⟨fun a => (f.1.1 a).isLeft, + (fun a b hab => sum_adj_same_side G H (f.1.2 a b hab)), f.2⟩ + +noncomputable def mapComponents (f : PureLeftMaps F G H) : ComponentMaps F G H (mapMask F G H f) := + (⟨fun a => (f.1.1 a.1).getLeft a.2, by + intro a b hab + have he := f.1.2 a.1 b.1 hab + rw [← Sum.inl_getLeft (f.1.1 a.1) a.2, ← Sum.inl_getLeft (f.1.1 b.1) b.2] at he + exact he⟩, + ⟨fun a => (f.1.1 a.1).getRight (Sum.isLeft_eq_false.mp a.2), by + intro a b hab + have he := f.1.2 a.1 b.1 hab + rw [← Sum.inr_getRight (f.1.1 a.1) (Sum.isLeft_eq_false.mp a.2), + ← Sum.inr_getRight (f.1.1 b.1) (Sum.isLeft_eq_false.mp b.2)] at he + exact he⟩) + +lemma assemble_mapComponents (f : PureLeftMaps F G H) : + assemblePure F G H ⟨mapMask F G H f, mapComponents F G H f⟩ = f := by + apply Subtype.ext + apply Subtype.ext + funext a + change assembleFunction F G H (mapMask F G H f) (mapComponents F G H f) a = f.1.1 a + by_cases h : (f.1.1 a).isLeft = true + · rw [assembleFunction_left F G H (mapMask F G H f) (mapComponents F G H f) ⟨a, h⟩] + exact Sum.inl_getLeft _ _ + · rw [assembleFunction_right F G H (mapMask F G H f) (mapComponents F G H f) + ⟨a, Bool.eq_false_iff.mpr h⟩] + exact Sum.inr_getRight _ _ + +noncomputable def componentEquiv : + ((s : ComponentMask F) × ComponentMaps F G H s) ≃ PureLeftMaps F G H := + Equiv.ofBijective (assemblePure F G H) ⟨assemblePure_injective F G H, + fun f => ⟨⟨mapMask F G H f, mapComponents F G H f⟩, assemble_mapComponents F G H f⟩⟩ + +lemma pureLeft_card [Fintype V] [Fintype W] : + Fintype.card (PureLeftMaps F G H) = + ∑ s : ComponentMask F, + Fintype.card (RelationMaps (fun a b : MaskLeft F s => F.relation a.1 b.1) G) * + Fintype.card (RelationMaps (fun a b : MaskRight F s => F.relation a.1 b.1) H) := by + rw [← Fintype.card_congr (componentEquiv F G H), Fintype.card_sigma] + apply Finset.sum_congr rfl + intro s _ + exact Fintype.card_prod _ _ + +end PureComponents + +end ParityWL + +end OAI diff --git a/lean/OAI/Combinatorics/ParityLifts/RaceBounds.lean b/lean/OAI/Combinatorics/ParityLifts/RaceBounds.lean new file mode 100644 index 0000000000000000000000000000000000000000..c0af84c8b4e4a75c36f3b46f58362c5fcb9fa5e1 --- /dev/null +++ b/lean/OAI/Combinatorics/ParityLifts/RaceBounds.lean @@ -0,0 +1,75 @@ +import OAI.Combinatorics.ParityLifts.RaceLoop + +namespace OAI + +namespace ParityWL.Complexity + +lemma race_budget_numeric (A q B L : ℕ) : + (1000*(B+L+2)^2*(A*(20*(B+L+2)+1)^q+1) : ℝ) ≤ + (1000*(A*21^q+1))*(B+L+2)^(q+2) := by + let X : ℝ := B+L+2 + have hX : 1 ≤ X := by dsimp only [X]; have := Nat.cast_nonneg (α:=ℝ) B; have := Nat.cast_nonneg (α:=ℝ) L; linarith + have hpow : (20*X+1)^q ≤ (21*X)^q := by gcongr; linarith + have h1 : 1 ≤ X^q := one_le_pow₀ hX + rw [mul_pow] at hpow + have hsecond : (A : ℝ)*(20*X+1)^q+1 ≤ (A*21^q+1)*X^q := by + nlinarith [mul_le_mul_of_nonneg_left hpow (Nat.cast_nonneg (α:=ℝ) A)] + have hh := mul_le_mul_of_nonneg_left hsecond (by positivity : 0 ≤ 1000*X^2) + calc + _ ≤ 1000*X^2*((A*21^q+1)*X^q) := hh + _ = _ := by rw [pow_add]; dsimp only [X]; ring + +lemma race_machine_numeric (D E : ℝ) (q B L t : ℕ) (hD : 0 ≤ D) (hE : 0 ≤ E) + (ht : (t : ℝ) ≤ D*(E*(B+L+2 : ℝ)^q+1)^2+44*L+20) : + (t : ℝ) ≤ (D*(E+2)^2+64)*(B+L+2 : ℝ)^(2*q+2) := by + have hcost : (t : ℝ) ≤ D*(E*(B+L+2 : ℝ)^q+0+2)^2+44*(B+L+1 : ℕ)+20 := by + apply ht.trans + push_cast + have h1 : 0 ≤ E*(B+L+2 : ℝ)^q := by positivity + have hh : (E*(B+L+2 : ℝ)^q+1)^2 ≤ (E*(B+L+2 : ℝ)^q+0+2)^2 := by nlinarith + nlinarith [mul_le_mul_of_nonneg_left hh hD, Nat.cast_nonneg (α:=ℝ) B] + have hT : E*(B+L+2 : ℝ)^q ≤ E*((B+L+1 : ℕ)+1 : ℝ)^q := by + push_cast + ring_nf + exact le_rfl + have hh := decision_numeric_bound D E 0 0 q (B+L+1) 0 + (E*(B+L+2 : ℝ)^q) 0 t hD hE (by norm_num) (by norm_num) + (by positivity) (by norm_num) hT (by norm_num) hcost + simpa only [Nat.cast_add,Nat.cast_one,Nat.cast_zero,mul_zero,Real.rpow_zero,mul_one, + add_zero,add_assoc,one_add_one_eq_two] using hh + +/-- One fixed finite machine enumerates all parameter pairs and bounded simulations. +The exponent and multiplier do not depend on the pair which eventually halts. -/ +lemma raceDecision_bound (M : Machine) : ∃ A : ℝ, 0 x.2.2) := + .expr TExpr.input.right.right (by intro x; rfl) + let stage := core.comp (PolyProgram.raceStage M) + let flag := (stage.comp (PolyProgram.fst Bool Bool)).comp PolyProgram.not + let ans := stage.comp (PolyProgram.snd Bool Bool) + let next := ((core.comp (PolyProgram.fst ℕ (List Bool))).comp PolyProgram.natSucc).pair + (core.comp (PolyProgram.snd ℕ (List Bool))) + exact flag.pair (ans.pair next) + +lemma raceState_size (a b : Bool) (n : ℕ) (bs : List Bool) : + (treeEncode (a,(b,(n,bs)))).size ≤ 20*(n+bs.length+1) := by + have ha := bool_size a + have hb := bool_size b + have hs := treeEncode_bits_size bs + simp only [treeEncode_pair,DataTree.size,treeEncode_nat,numTree_size] + omega + +noncomputable def raceStepBudget (M : Machine) (B L : ℕ) : ℕ := + (PolyProgram.raceStep M).coefficient*(20*(B+L+2)+1)^(PolyProgram.raceStep M).degree + +lemma raceStepBudget_bound (M : Machine) (bs : List Bool) (B n : ℕ) (b : Bool) (hn : n ≤ B+1) : + (PolyProgram.raceStep M).program.time (true,(b,(n,bs))) ≤ raceStepBudget M B bs.length := by + apply (PolyProgram.raceStep M).bound _ |>.trans + apply Nat.mul_le_mul_left + apply Nat.pow_le_pow_left + have h := raceState_size true b n bs + omega + +lemma raceLoop_run (M : Machine) (bs : List Bool) (P : Bool → Prop) + (hM : ∀ j : ℕ, 0 + intro n hn a + have hn' : n=B := by omega + subst n + let ans := (raceStage M B bs).2 + have hstep := ((PolyProgram.raceStep M).program.run (true,(a,(B,bs)))).mono + (raceStepBudget_bound M bs B B a (by omega)) + have he : raceStep M (true,(a,(B,bs)))=(false,(ans,(B+1,bs))) := by + simp only [raceStep,hB,Bool.not_true,ans] + rw [he] at hstep + have hs := raceState_size false ans (B+1) bs + have hstop := BEval.loop_stop (PolyProgram.raceStep M).program.code + (treeEncode (false,(ans,(B+1,bs)))) rfl + refine ⟨B+1,ans,le_rfl,?_,raceStage_sound M bs P hM B hB⟩ + apply (BEval.loop_next (by simp [DataTree.child]) hstep hstop).mono + omega + | succ fuel ih => + intro n hn a + let ans := (raceStage M n bs).2 + have hstep := ((PolyProgram.raceStep M).program.run (true,(a,(n,bs)))).mono + (raceStepBudget_bound M bs B n a (by omega)) + cases hh : (raceStage M n bs).1 with + | true => + have he : raceStep M (true,(a,(n,bs)))=(false,(ans,(n+1,bs))) := by + simp only [raceStep,hh,Bool.not_true,ans] + rw [he] at hstep + have hs := (raceState_size false ans (n+1) bs).trans + (show 20*(n+1+bs.length+1) ≤ 20*(B+bs.length+2) by omega) + have hstop := BEval.loop_stop (PolyProgram.raceStep M).program.code + (treeEncode (false,(ans,(n+1,bs)))) rfl + refine ⟨n+1,ans,by omega,?_,raceStage_sound M bs P hM n hh⟩ + apply (BEval.loop_next (by simp [DataTree.child]) hstep hstop).mono + nlinarith + | false => + have he : raceStep M (true,(a,(n,bs)))=(true,(ans,(n+1,bs))) := by + simp only [raceStep,hh,Bool.not_false,ans] + rw [he] at hstep + obtain ⟨m,b,hm,hr,hP⟩ := ih (n+1) (by omega) ans + refine ⟨m,b,hm,?_,hP⟩ + apply (BEval.loop_next (by simp [DataTree.child]) hstep hr).mono + nlinarith + +def raceInitExpr : TExpr := .pair (.const (treeEncode true)) (.pair .nil (.pair .nil .input)) + +noncomputable def raceCode (M : Machine) : FCode := + .seq raceInitExpr.compile (.seq (.loop (PolyProgram.raceStep M).program.code) (.seq .right .left)) + +lemma raceCode_run (M : Machine) (bs : List Bool) (P : Bool → Prop) + (hM : ∀ j : ℕ, 0 exact h + | succ t ht ih => + change M.output ((step M)^[t+1] (initialConfiguration M bs)).state=some b + rw [Function.iterate_succ_apply'] + change M.output (step M (run M bs t)).state=some b + unfold Emits at ih + simp only [step,ih] + +lemma Emits.unique {M : Machine} {bs : List Bool} {s t : ℕ} {b c : Bool} + (h : Emits M bs s b) (hg : Emits M bs t c) : b=c := by + rcases le_total s t with hst | hts + · have hh := h.mono hst + unfold Emits at hh hg + simp_all + · have hh := hg.mono hts + unfold Emits at h hh + simp_all + +lemma boundedAnswer_of_emits {M : Machine} {bs : List Bool} {s n : ℕ} {b : Bool} + (h : Emits M bs s b) (hs : s ≤ n) : boundedAnswer M n bs=(true,b) := by + have hh := smallRun_output (h.mono hs) + simp only [boundedAnswer,boundedConfiguration,hh,Option.isSome_some,decide_true,Option.getD_some] + +lemma boundedAnswer_emits {M : Machine} {bs : List Bool} {n : ℕ} + (h : (boundedAnswer M n bs).1=true) : Emits M bs n (boundedAnswer M n bs).2 := by + have hr := (smallRun_represents M bs n).1 + unfold boundedAnswer boundedConfiguration at * + unfold Emits + rw [hr] + generalize M.output ((smallStep M)^[n] (smallInitial M bs)).1=o at * + cases o <;> simp_all + +def PolyProgram.trueTicks : PolyProgram ℕ (List Bool) (fun n => List.replicate n true) := + (PolyProgram.ticks.comp (PolyProgram.const true |>.map)).congr (by intro n; simp) + +def PolyProgram.trialInput : PolyProgram ((ℕ × ℕ) × List Bool) (List Bool) + (fun x => Complexity.trialInput x.1.1 x.1.2 x.2) := by + let p := PolyProgram.fst (ℕ × ℕ) (List Bool) + let j := (p.comp (PolyProgram.fst ℕ ℕ)).comp PolyProgram.trueTicks + let k := (p.comp (PolyProgram.snd ℕ ℕ)).comp PolyProgram.trueTicks + let bs := PolyProgram.snd (ℕ × ℕ) (List Bool) + let tail := (k.pair (((PolyProgram.const false).pair bs).comp (PolyProgram.cons Bool))).comp (PolyProgram.append Bool) + exact (j.pair (((PolyProgram.const false).pair tail).comp (PolyProgram.cons Bool))).comp (PolyProgram.append Bool) + +def racePairs (n : ℕ) : List (ℕ × ℕ) := (List.range (n+1)).product (List.range (n+1)) + +def raceProbe (M : Machine) (p : ℕ × ℕ) (x : ℕ × List Bool) : Bool × Bool := + boundedAnswer M x.1 (trialInput (p.1+1) (p.2+4) x.2) + +def raceStage (M : Machine) (n : ℕ) (bs : List Bool) : Bool × Bool := + (((racePairs n).map (fun p => raceProbe M p (n,bs))).filter Prod.fst).headD (false,false) + +noncomputable def PolyProgram.raceProbe (M : Machine) : + PolyProgram ((ℕ × ℕ) × (ℕ × List Bool)) (Bool × Bool) (fun x => Complexity.raceProbe M x.1 x.2) := by + let ps := PolyProgram.fst (ℕ × ℕ) (ℕ × List Bool) + let x := PolyProgram.snd (ℕ × ℕ) (ℕ × List Bool) + let j := (ps.comp (PolyProgram.fst ℕ ℕ)).comp PolyProgram.natSucc + let k := (((ps.comp (PolyProgram.snd ℕ ℕ)).pair (PolyProgram.const 4)).comp PolyProgram.natAdd) + let bs := x.comp (PolyProgram.snd ℕ (List Bool)) + let inp := (((j.pair k).pair bs).comp PolyProgram.trialInput) + exact ((x.comp (PolyProgram.fst ℕ (List Bool))).pair inp).comp (PolyProgram.boundedAnswer M) + +def PolyProgram.racePairs : PolyProgram ℕ (List (ℕ × ℕ)) racePairs := + ((PolyProgram.natSucc.comp PolyProgram.range).pair (PolyProgram.natSucc.comp PolyProgram.range)).comp (PolyProgram.product ℕ ℕ) + +noncomputable def PolyProgram.raceStage (M : Machine) : + PolyProgram (ℕ × List Bool) (Bool × Bool) (fun x => Complexity.raceStage M x.1 x.2) := + (((((PolyProgram.fst ℕ (List Bool)).comp PolyProgram.racePairs).pair (PolyProgram.id (ℕ × List Bool))).comp + (PolyProgram.raceProbe M).mapWith).comp ((PolyProgram.fst Bool Bool).filter)).comp (PolyProgram.head (Bool × Bool) (false,false)) + +lemma filter_first_sound (xs : List (Bool × Bool)) (P : Bool → Prop) + (h : ∀ x∈xs, x.1=true → P x.2) + (ht : ((xs.filter Prod.fst).headD (false,false)).1=true) : + P ((xs.filter Prod.fst).headD (false,false)).2 := by + cases he : xs.filter Prod.fst with + | nil => simp [he] at ht + | cons a ys => + have ha : a∈xs.filter Prod.fst := by rw [he]; simp + rw [he] at ht + exact h a (List.mem_filter.mp ha).1 ht + +lemma filter_first_complete (xs : List (Bool × Bool)) + (h : ∃ x∈xs, x.1=true) : ((xs.filter Prod.fst).headD (false,false)).1=true := by + obtain ⟨x,hx,ht⟩ := h + have hm : x∈xs.filter Prod.fst := List.mem_filter.mpr ⟨hx,ht⟩ + cases he : xs.filter Prod.fst with + | nil => simp [he] at hm + | cons a ys => + have ha : a∈xs.filter Prod.fst := by rw [he]; simp + simpa [he] using (List.mem_filter.mp ha).2 + +lemma raceStage_sound (M : Machine) (bs : List Bool) (P : Bool → Prop) + (hM : ∀ j : ℕ, 0 exact h + | step hk g ih => exact .step hk ih + +lemma Ancestor.cases' {i j : N} (h : D.Ancestor i j) : + i = j ∨ (j ≠ D.root ∧ D.Ancestor i (D.parent j)) := by + cases h with + | refl => exact Or.inl rfl + | step h g => exact Or.inr ⟨h, g⟩ + +lemma root_ancestor (j : N) : D.Ancestor D.root j := by + by_cases h : j = D.root + · subst j; exact .refl + · exact .step h (root_ancestor (D.parent j)) +termination_by D.rank j +decreasing_by exact D.parent_lt j h + +theorem Ancestor.map {M : Type} (E : RankedTree M) (f : N → M) + (hstep : ∀ j, j ≠ D.root → E.Ancestor (f (D.parent j)) (f j)) + {i j : N} (h : D.Ancestor i j) : E.Ancestor (f i) (f j) := by + induction h with + | refl => exact .refl + | @step j hj h ih => exact ih.trans E (hstep j hj) + +variable [Fintype N] + +@[instance_reducible] noncomputable def nodeOrder : LinearOrder N := + LinearOrder.lift' (fun i => (toLex (D.rank i, (Fintype.equivFin N i).val))) (by + intro i j h + have he : Fintype.equivFin N i = Fintype.equivFin N j := Fin.ext + (congrArg (fun p : Lex (ℕ × ℕ) => (ofLex p).2) h) + exact (Fintype.equivFin N).injective he) + +noncomputable def enumeration : Fin (Fintype.card N) ≃ N := by + letI := D.nodeOrder + exact (Fintype.orderIsoFinOfCardEq N rfl).toEquiv + +noncomputable def indexed : IndexedTree where + nodes := Fintype.card N + root := D.enumeration.symm D.root + parent i := D.enumeration.symm (D.parent (D.enumeration i)) + parent_lt i hi := by + let := D.nodeOrder + change (Fintype.orderIsoFinOfCardEq N rfl).symm + (D.parent ((Fintype.orderIsoFinOfCardEq N rfl) i)) < i + rw [OrderIso.symm_apply_lt] + change Prod.Lex (· < ·) (· < ·) + (D.rank (D.parent _), _) (D.rank _, _) + apply Prod.Lex.left + apply D.parent_lt + intro he + apply hi + apply D.enumeration.injective + simpa only [enumeration, Equiv.apply_symm_apply, OrderIso.coe_toEquiv] using he + +lemma ancestor_indexed {i j : N} (h : D.Ancestor i j) : + D.indexed.Ancestor (D.enumeration.symm i) (D.enumeration.symm j) := by + induction h with + | refl => exact .refl + | @step j hj h ih => + apply IndexedTree.Ancestor.step + · intro he + apply hj + exact D.enumeration.symm.injective he + · simpa only [indexed, Equiv.apply_symm_apply] using ih + +lemma indexed_ancestor {i j : Fin (Fintype.card N)} (h : D.indexed.Ancestor i j) : + D.Ancestor (D.enumeration i) (D.enumeration j) := by + have hm : ∀ (T : IndexedTree) (f : Fin T.nodes → N), + (∀ j, j ≠ T.root → D.Ancestor (f (T.parent j)) (f j)) → + ∀ i j, T.Ancestor i j → D.Ancestor (f i) (f j) := by + intro T f hf i j h + induction h with + | refl => exact .refl + | @step j hj h ih => exact ih.trans D (hf j hj) + apply hm D.indexed D.enumeration _ i j h + intro j hj + apply Ancestor.step + · intro he + apply hj + apply D.enumeration.injective + simpa only [indexed, Equiv.apply_symm_apply] using he + · simp only [indexed, Equiv.apply_symm_apply] + exact .refl + +end RankedTree + +/-- This records ordinary bag axioms, not lift solvability or any WL promise. -/ +structure RankedBagTree {W N : Type} (R : W → W → Prop) (t : ℕ) extends RankedTree N where + bag : N → Finset W + top : W → N + top_mem : ∀ x, x ∈ bag (top x) + top_ancestor : ∀ x i, x ∈ bag i → toRankedTree.Ancestor (top x) i + interval_mem : ∀ x i j, toRankedTree.Ancestor (top x) i → + toRankedTree.Ancestor i j → x ∈ bag j → x ∈ bag i + edge_cover : ∀ x y, R x y → ∃ i, x ∈ bag i ∧ y ∈ bag i + width : ∀ i, (bag i).card ≤ t + intersection : ∀ i, i ≠ root → (bag i ∩ bag (parent i)).card < t + +namespace RankedBagTree + +variable {W N : Type} [Fintype W] [Fintype N] {F : SimpleGraph W} {t : ℕ} + +noncomputable def toIndexed (D : RankedBagTree (N := N) F.Adj t) : ReducedBagTree F t where + toIndexedTree := D.toRankedTree.indexed + bag i := D.bag (D.toRankedTree.enumeration i) + top x := D.toRankedTree.enumeration.symm (D.top x) + top_mem x := by simp only [Equiv.apply_symm_apply]; exact D.top_mem x + top_ancestor x i hx := by + change Fin (Fintype.card N) at i + simpa only [RankedTree.indexed, Equiv.symm_apply_apply] using + D.toRankedTree.ancestor_indexed (D.top_ancestor x _ hx) + interval_mem x i j hi hij hx := by + apply D.interval_mem x _ _ _ (D.toRankedTree.indexed_ancestor hij) hx + simpa only [Equiv.apply_symm_apply] using D.toRankedTree.indexed_ancestor hi + edge_cover x y h := by + obtain ⟨i, hx, hy⟩ := D.edge_cover x y h + exact ⟨D.toRankedTree.enumeration.symm i, by simpa, by simpa⟩ + width i := D.width _ + intersection i hi := by + simp only [RankedTree.indexed, Equiv.apply_symm_apply] + apply D.intersection + intro he + apply hi + apply D.toRankedTree.enumeration.injective + simpa only [RankedTree.indexed, Equiv.apply_symm_apply] using he + +end RankedBagTree + +/-- Equality for every genuinely decomposed uncolored source. -/ +theorem no_choice_equal_decomposed {W N : Type} [Fintype W] [Fintype N] + {t : ℕ} (C : ChoiceSystem t) (ht : 0 < t) (hn : ¬ C.Successful) + (F : SimpleGraph W) (D : RankedBagTree (N := N) F.Adj t) : + homCount F (zeroLift C) = homCount F (starLift C) := by + apply le_antisymm + · by_contra h + have hlt : homCount F (starLift C) < homCount F (zeroLift C) := by omega + obtain ⟨φ, ⟨w⟩⟩ := homCount_lift_strict_iff_witness.mp hlt + exact hn (choice_of_reducedCutDecomposition φ w D.toIndexed.toReducedCuts ht) + · exact homCount_lift_le _ _ _ _ _ + +end RankedTrees + +end ParityWL + +end OAI diff --git a/lean/OAI/Combinatorics/ParityLifts/RealEval.lean b/lean/OAI/Combinatorics/ParityLifts/RealEval.lean new file mode 100644 index 0000000000000000000000000000000000000000..186d9d1d32021ec55ca238a26f12a09d57116987 --- /dev/null +++ b/lean/OAI/Combinatorics/ParityLifts/RealEval.lean @@ -0,0 +1,70 @@ +import OAI.Combinatorics.ParityLifts.BoolFold + +namespace OAI + +namespace ParityWL.Complexity + +def RBEval (p : FCode) (x : DataTree) (R : ℝ) (y : DataTree) : Prop := + ∃ B : ℕ, BEval p x B y ∧ (B : ℝ)≤R + +lemma BEval.real {p : FCode} {x y : DataTree} {B : ℕ} (h : BEval p x B y) : + RBEval p x B y := ⟨B,h,le_rfl⟩ + +lemma RBEval.mono {p : FCode} {x y : DataTree} {R S : ℝ} + (h : RBEval p x R y) (hrs : R≤S) : RBEval p x S y := by + obtain ⟨B,hB,h⟩ := h + exact ⟨B,hB,h.trans hrs⟩ + +lemma RBEval.nonneg {p : FCode} {x y : DataTree} {R : ℝ} (h : RBEval p x R y) : 0≤R := by + obtain ⟨B,_,h⟩ := h + exact (Nat.cast_nonneg B).trans h + +lemma RBEval.seq {p q : FCode} {x y z : DataTree} {R S : ℝ} + (h : RBEval p x R y) (hg : RBEval q y S z) : RBEval (.seq p q) x (R+S+1) z := by + obtain ⟨B,hB,h⟩ := h + obtain ⟨C,hC,hg⟩ := hg + exact ⟨B+C+1,hB.seq hC,by push_cast; linarith⟩ + +lemma RBEval.ceil {p : FCode} {x y : DataTree} {R : ℝ} (h : RBEval p x R y) : + BEval p x ⌈R⌉₊ y := by + obtain ⟨B,hB,h⟩ := h + exact hB.mono (by exact_mod_cast h.trans (Nat.le_ceil R)) + +lemma RBEval.any {α : Type} [TreeCodec α] (p : FCode) (P : α → Prop) + (S : ℕ) (R : ℝ) (hR : 0≤R) (xs : List α) + (hs : ∀ a∈xs,(treeEncode a).size≤S) + (hb : ∀ a∈xs,∃ b,RBEval p (treeEncode a) R (treeEncode b) ∧ (b=true↔P a)) : + ∃ b,RBEval p.any (treeEncode xs) + (500*(xs.length+1 : ℝ)^2*(S+R+6)) (treeEncode b) ∧ (b=true↔∃ a∈xs,P a) := by + obtain ⟨b,hb',he⟩ := BEval.any p P S ⌈R⌉₊ xs hs (by + intro a ha + obtain ⟨b,hb,he⟩ := hb a ha + exact ⟨b,hb.ceil,he⟩) + refine ⟨b,hb'.real.mono ?_,he⟩ + have hc := Nat.ceil_lt_add_one hR + push_cast + apply mul_le_mul_of_nonneg_left _ (by positivity) + linarith + +lemma RBEval.simulation {M : Machine} {bs : List Bool} {s : ℕ} {b : Bool} {R : ℝ} + (h : Emits M bs s b) (hs : (s : ℝ)≤R) : + RBEval (simulationCode M) (treeEncode bs) + (simulationCoefficient M*(bs.length+R+1 : ℝ)^simulationDegree) (treeEncode b) := by + apply (simulation_run h).real.mono + push_cast + gcongr + +lemma RBEval.decision {p : FCode} {bs : List Bool} {b : Bool} {R : ℝ} + (h : RBEval p (treeEncode bs) R (treeEncode b)) : + ∃ s, Emits p.decision bs s b ∧ + (s : ℝ)≤500*(p.factor+2 : ℝ)*(p.depth+2 : ℝ)*(R+1)^2+44*bs.length+20 := by + obtain ⟨B,hB,h⟩ := h + rw [treeEncode_bits] at hB + obtain ⟨s,hs,he⟩ := hB.decision + refine ⟨s,by cases b <;> simpa using he,?_⟩ + calc + (s : ℝ) ≤ 500*(p.factor+2 : ℝ)*(p.depth+2 : ℝ)*(B+1 : ℝ)^2+44*bs.length+20 := by exact_mod_cast hs + _ ≤ _ := by gcongr +end ParityWL.Complexity + +end OAI diff --git a/lean/OAI/Combinatorics/ParityLifts/ReducedCNF.lean b/lean/OAI/Combinatorics/ParityLifts/ReducedCNF.lean new file mode 100644 index 0000000000000000000000000000000000000000..0ede1b3c2135de6eaac03c18ddaeb2133308894a --- /dev/null +++ b/lean/OAI/Combinatorics/ParityLifts/ReducedCNF.lean @@ -0,0 +1,321 @@ +import OAI.Combinatorics.ParityLifts.ListPrograms + +namespace OAI + +namespace Sparsification + +variable {α : Type} [DecidableEq α] + +abbrev CNF (α : Type) := Finset (Finset α) + +def Reduced (F : CNF α) : Prop := + ∀ C ∈ F, ∀ D ∈ F, C ⊆ D → C = D + +def Holds (F : CNF α) (v : α → Prop) : Prop := + ∀ C ∈ F, ∃ x ∈ C, v x + +def minimize (F : CNF α) : CNF α := + F.filter (fun C => ∀ D ∈ F, D ⊆ C → C ⊆ D) + +lemma minimize_reduced (F : CNF α) : Reduced (minimize F) := by + intro C hC D hD hCD + exact Finset.Subset.antisymm hCD ((Finset.mem_filter.mp hD).2 C + (Finset.mem_filter.mp hC).1 hCD) + +lemma minimal_subclause (F : CNF α) (C : Finset α) (hC : C ∈ F) : + ∃ D ∈ minimize F, D ⊆ C := by + let S := F.filter (fun D => D ⊆ C) + obtain ⟨D, hD, hm⟩ := Finset.exists_min_image S Finset.card ⟨C, by simp [S, hC]⟩ + refine ⟨D, Finset.mem_filter.mpr ⟨(Finset.mem_filter.mp hD).1, ?_⟩, + (Finset.mem_filter.mp hD).2⟩ + intro E hE hED + have hES : E ∈ S := Finset.mem_filter.mpr ⟨hE, hED.trans (Finset.mem_filter.mp hD).2⟩ + have hc : D.card ≤ E.card := hm E hES + have he := Finset.eq_of_subset_of_card_le hED hc + exact he.symm.subset + +lemma minimize_holds (F : CNF α) (v : α → Prop) : Holds (minimize F) v ↔ Holds F v := by + constructor + · intro h C hC + obtain ⟨D, hD, hDC⟩ := minimal_subclause F C hC + obtain ⟨x, hx, hv⟩ := h D hD + exact ⟨x, hDC hx, hv⟩ + · intro h C hC + exact h C (Finset.mem_filter.mp hC).1 + +/-- A new clause has no old subclause, including no equal old clause. -/ +def Fresh (F A : CNF α) : Prop := ∀ D ∈ A, ∀ C ∈ F, ¬ C ⊆ D + +def prune (F A : CNF α) : CNF α := + F.filter (fun C => ¬ ∃ D ∈ A, D ⊆ C) ∪ A + +lemma prune_holds (F A : CNF α) (v : α → Prop) : + Holds (prune F A) v ↔ Holds F v ∧ Holds A v := by + classical + constructor + · intro h + constructor + · intro C hC + by_cases he : ∃ D ∈ A, D ⊆ C + · obtain ⟨D, hD, hDC⟩ := he + obtain ⟨x, hx, hv⟩ := h D (Finset.mem_union_right _ hD) + exact ⟨x, hDC hx, hv⟩ + · exact h C (Finset.mem_union_left _ (Finset.mem_filter.mpr ⟨hC, he⟩)) + · intro C hC + exact h C (Finset.mem_union_right _ hC) + · rintro ⟨hF, hA⟩ C hC + rcases Finset.mem_union.mp hC with hC | hC + · exact hF C (Finset.mem_filter.mp hC).1 + · exact hA C hC + +lemma prune_reduced {F A : CNF α} (hF : Reduced F) (hA : Reduced A) + (hf : Fresh F A) : Reduced (prune F A) := by + intro C hC D hD hCD + rcases Finset.mem_union.mp hC with hC | hC <;> + rcases Finset.mem_union.mp hD with hD | hD + · exact hF C (Finset.mem_filter.mp hC).1 D (Finset.mem_filter.mp hD).1 hCD + · exact False.elim (hf D hD C (Finset.mem_filter.mp hC).1 hCD) + · exact False.elim ((Finset.mem_filter.mp hD).2 ⟨C, hC, hCD⟩) + · exact hA C hC D hD hCD + +structure Flower (F : CNF α) (p q h : ℕ) where + core : Finset α + petals : CNF α + core_card : core.card = p + petals_card : petals.card = h + petal_card : ∀ P ∈ petals, P.card = q + apart : ∀ P ∈ petals, Disjoint core P + pairwise : (↑petals : Set (Finset α)).Pairwise Disjoint + cover : ∀ P ∈ petals, core ∪ P ∈ F + +lemma Flower.core_fresh {F : CNF α} {p q h : ℕ} (f : Flower F p q h) + (hF : Reduced F) (hq : 0 < q) (hh : 0 < h) : Fresh F {f.core} := by + intro D hD C hC hCD + have hD' : D = f.core := Finset.mem_singleton.mp hD + subst D + obtain ⟨P, hP⟩ := Finset.card_pos.mp (by rw [f.petals_card]; exact hh : 0 < f.petals.card) + have hc := hF C hC (f.core ∪ P) (f.cover P hP) (hCD.trans Finset.subset_union_left) + have hp : P ⊆ f.core := by rw [hc] at hCD; exact Finset.subset_union_right.trans hCD + have he : P = ∅ := disjoint_self.mp ((f.apart P hP).mono_left hp) + have := f.petal_card P hP + simp [he] at this + omega + +lemma Flower.petals_fresh {F : CNF α} {p q h : ℕ} (f : Flower F p q h) + (hF : Reduced F) (hp : 0 < p) : Fresh F f.petals := by + intro P hP C hC hCP + have hc := hF C hC (f.core ∪ P) (f.cover P hP) (hCP.trans Finset.subset_union_right) + have hs : f.core ⊆ P := by rw [hc] at hCP; exact Finset.subset_union_left.trans hCP + have he : f.core = ∅ := disjoint_self.mp ((f.apart P hP).mono_right hs) + have := f.core_card + simp [he] at this + omega + +lemma Flower.petals_reduced {F : CNF α} {p q h : ℕ} (f : Flower F p q h) : + Reduced f.petals := by + intro C hC D hD hCD + apply Finset.eq_of_subset_of_card_le hCD + rw [f.petal_card C hC, f.petal_card D hD] + +lemma Flower.branch_holds {F : CNF α} {p q h : ℕ} (f : Flower F p q h) + (v : α → Prop) : + Holds F v ↔ Holds (prune F {f.core}) v ∨ Holds (prune F f.petals) v := by + classical + simp only [prune_holds] + constructor + · intro hF + by_cases hc : ∃ x ∈ f.core, v x + · exact Or.inl ⟨hF, by intro C hC; obtain rfl := Finset.mem_singleton.mp hC; exact hc⟩ + · right + refine ⟨hF, ?_⟩ + intro P hP + obtain ⟨x, hx, hv⟩ := hF _ (f.cover P hP) + rcases Finset.mem_union.mp hx with hx | hx + · exact False.elim (hc ⟨x, hx, hv⟩) + · exact ⟨x, hx, hv⟩ + · rintro (⟨hF, _⟩ | ⟨hF, _⟩) <;> exact hF + +end Sparsification + + +namespace Sparsification + +variable {α : Type} [DecidableEq α] [Fintype α] + +def units (F : CNF α) : Finset α := Finset.univ.filter (fun x => ({x} : Finset α) ∈ F) + +def binaries (F : CNF α) : CNF α := F.filter (fun C => C.card = 2) + +def degree (M : CNF α) (x : α) : ℕ := (M.filter (fun C => x ∈ C)).card + +@[simp] lemma mem_units (F : CNF α) (x : α) : x ∈ units F ↔ ({x} : Finset α) ∈ F := by + simp [units] + +omit [DecidableEq α] [Fintype α] in +lemma clause_eq_singleton {C : Finset α} {x : α} (hc : C.Nonempty) (hs : C ⊆ {x}) : + C = {x} := by + obtain ⟨y, hy⟩ := hc + have he : y = x := Finset.mem_singleton.mp (hs hy) + exact Finset.Subset.antisymm hs (by simpa [← he] using Finset.singleton_subset_iff.mpr hy) + +lemma units_prune (F A : CNF α) (hA : ∀ C ∈ A, C.Nonempty) : + units (prune F A) = units F ∪ units A := by + ext x + simp only [mem_units, Finset.mem_union] + constructor + · intro hx + rcases Finset.mem_union.mp hx with hx | hx + · exact Or.inl (Finset.mem_filter.mp hx).1 + · exact Or.inr hx + · rintro (hx | hx) + · by_cases he : ∃ C ∈ A, C ⊆ {x} + · obtain ⟨C, hC, hs⟩ := he + have hc := clause_eq_singleton (hA C hC) hs + exact Finset.mem_union_right _ (hc ▸ hC) + · exact Finset.mem_union_left _ (Finset.mem_filter.mpr ⟨hx, he⟩) + · exact Finset.mem_union_right _ hx + +lemma units_disjoint_of_fresh {F A : CNF α} (hf : Fresh F A) : + Disjoint (units F) (units A) := by + apply Finset.disjoint_left.mpr + intro x hx hy + exact hf {x} (mem_units A x |>.mp hy) {x} (mem_units F x |>.mp hx) (Finset.Subset.refl _) + +lemma units_card_of_singletons (A : CNF α) (hA : ∀ C ∈ A, C.card = 1) : + (units A).card = A.card := by + have he : (units A).image (fun x => ({x} : Finset α)) = A := by + ext C + constructor + · intro hmem + obtain ⟨x, hx, hxc⟩ := Finset.mem_image.mp hmem + rw [← hxc] + exact (mem_units A x).mp hx + · intro hC + obtain ⟨x, rfl⟩ := Finset.card_eq_one.mp (hA C hC) + exact Finset.mem_image.mpr ⟨x, (mem_units A x).mpr hC, rfl⟩ + calc + _ = ((units A).image (fun x => ({x} : Finset α))).card := + (Finset.card_image_of_injective _ (fun _ _ h => Finset.singleton_injective h)).symm + _ = _ := congrArg Finset.card he + +lemma units_empty_of_binaries (A : CNF α) (hA : ∀ C ∈ A, C.card = 2) : + units A = ∅ := by + apply Finset.eq_empty_iff_forall_notMem.mpr + intro x hx + have := hA {x} ((mem_units A x).mp hx) + simp at this + +lemma card_le_sum_degrees (M : CNF α) (hne : ∀ C ∈ M, C.Nonempty) : + M.card ≤ ∑ x : α, degree M x := by + have hs : M ⊆ Finset.univ.biUnion (fun x : α => M.filter (fun C => x ∈ C)) := by + intro C hC + obtain ⟨x, hx⟩ := hne C hC + exact Finset.mem_biUnion.mpr ⟨x, Finset.mem_univ _, Finset.mem_filter.mpr ⟨hC, hx⟩⟩ + exact (Finset.card_le_card hs).trans Finset.card_biUnion_le + +lemma marked_card_bound (M : CNF α) (h : ℕ) (hne : ∀ C ∈ M, C.Nonempty) + (hd : ∀ x, degree M x ≤ h) : M.card ≤ Fintype.card α * h := by + calc + _ ≤ ∑ x : α, degree M x := card_le_sum_degrees M hne + _ ≤ ∑ _x : α, h := Finset.sum_le_sum (fun x _ => hd x) + _ = _ := by simp + +def survived (M A : CNF α) : CNF α := M.filter (fun C => ¬ ∃ D ∈ A, D ⊆ C) + +omit [Fintype α] in +lemma degree_survived_le (M A : CNF α) (x : α) : degree (survived M A) x ≤ degree M x := by + apply Finset.card_le_card + intro C hC + exact Finset.mem_filter.mpr ⟨(Finset.mem_filter.mp (Finset.mem_filter.mp hC).1).1, + (Finset.mem_filter.mp hC).2⟩ + +lemma removed_card_bound (M A : CNF α) (h : ℕ) + (hA : ∀ C ∈ A, C.card = 1) (hd : ∀ x, degree M x ≤ h) : + M.card ≤ (survived M A).card + h * A.card := by + have hs : M ⊆ survived M A ∪ (units A).biUnion (fun x => M.filter (fun C => x ∈ C)) := by + intro C hC + by_cases he : ∃ D ∈ A, D ⊆ C + · obtain ⟨D, hD, hDC⟩ := he + obtain ⟨x, rfl⟩ := Finset.card_eq_one.mp (hA D hD) + exact Finset.mem_union_right _ (Finset.mem_biUnion.mpr + ⟨x, (mem_units A x).mpr hD, Finset.mem_filter.mpr + ⟨hC, Finset.singleton_subset_iff.mp hDC⟩⟩) + · exact Finset.mem_union_left _ (Finset.mem_filter.mpr ⟨hC, he⟩) + calc + _ ≤ (survived M A ∪ (units A).biUnion (fun x => M.filter (fun C => x ∈ C))).card := + Finset.card_le_card hs + _ ≤ (survived M A).card + ((units A).biUnion (fun x => M.filter (fun C => x ∈ C))).card := + Finset.card_union_le _ _ + _ ≤ (survived M A).card + ∑ x ∈ units A, degree M x := + Nat.add_le_add_left Finset.card_biUnion_le _ + _ ≤ (survived M A).card + ∑ _x ∈ units A, h := + Nat.add_le_add_left (Finset.sum_le_sum (fun x _ => hd x)) _ + _ = _ := by simp [units_card_of_singletons A hA, Nat.mul_comm] + +lemma units_prune_card (F A : CNF α) (hf : Fresh F A) (hA : ∀ C ∈ A, C.card = 1) : + (units (prune F A)).card = (units F).card + A.card := by + rw [units_prune F A (fun C hC => Finset.card_pos.mp (by rw [hA C hC]; omega)), + Finset.card_union_of_disjoint (units_disjoint_of_fresh hf), units_card_of_singletons A hA] + +lemma unit_resource {F M A : CNF α} {a h : ℕ} (hf : Fresh F A) + (hA : ∀ C ∈ A, C.card = 1) (hd : ∀ x, degree M x ≤ h) + (hi : a ≤ M.card + h * (units F).card) : + a ≤ (survived M A).card + h * (units (prune F A)).card := by + have hr := removed_card_bound M A h hA hd + rw [units_prune_card F A hf hA, Nat.mul_add] + omega + +omit [Fintype α] in +lemma survived_binary_eq {F M A : CNF α} (hf : Fresh F A) (hM : M ⊆ binaries F) + (hA : ∀ C ∈ A, C.card = 2) : survived M A = M := by + apply Finset.filter_eq_self.mpr + intro C hC + rintro ⟨D, hD, hDC⟩ + have hm := Finset.mem_filter.mp (hM hC) + have he : D = C := Finset.eq_of_subset_of_card_le hDC (by rw [hA D hD, hm.2]) + exact hf D hD C hm.1 (he ▸ (Finset.Subset.refl _)) + +omit [DecidableEq α] [Fintype α] in +lemma marked_binary_disjoint {F M A : CNF α} (hf : Fresh F A) (hM : M ⊆ binaries F) : + Disjoint M A := by + apply Finset.disjoint_left.mpr + intro C hC hA + exact hf C hA C (Finset.mem_filter.mp (hM hC)).1 (Finset.Subset.refl _) + +lemma binary_resource {F M A : CNF α} {a h : ℕ} (hf : Fresh F A) + (hM : M ⊆ binaries F) (hA : ∀ C ∈ A, C.card = 2) + (hi : a ≤ M.card + h * (units F).card) : + a + A.card ≤ (M ∪ A).card + h * (units (prune F A)).card := by + rw [Finset.card_union_of_disjoint (marked_binary_disjoint hf hM), + units_prune F A (fun C hC => Finset.card_pos.mp (by rw [hA C hC]; omega)), + units_empty_of_binaries A hA, Finset.union_empty] + omega + +omit [Fintype α] in +lemma degree_union_le (M A : CNF α) (x : α) : + degree (M ∪ A) x ≤ degree M x + degree A x := by + unfold degree + rw [Finset.filter_union] + exact Finset.card_union_le _ _ + +omit [Fintype α] in +lemma degree_le_of_subset (M F : CNF α) (hM : M ⊆ F) (x : α) : degree M x ≤ degree F x := by + apply Finset.card_le_card + intro C hC + exact Finset.mem_filter.mpr + ⟨hM (Finset.mem_filter.mp hC).1, (Finset.mem_filter.mp hC).2⟩ + +omit [Fintype α] in +lemma binary_degree_invariant {F M A : CNF α} {h : ℕ} (hM : M ⊆ binaries F) + (hF : ∀ x, degree (binaries F) x < h) (hA : ∀ x, degree A x ≤ 1) : + ∀ x, degree (M ∪ A) x ≤ h := by + intro x + have h1 := degree_union_le M A x + have h2 := degree_le_of_subset M (binaries F) hM x + have h3 := hF x + have h4 := hA x + omega + +end Sparsification + +end OAI diff --git a/lean/OAI/Combinatorics/ParityLifts/Rerooting.lean b/lean/OAI/Combinatorics/ParityLifts/Rerooting.lean new file mode 100644 index 0000000000000000000000000000000000000000..42fd0ac68a4ad164130106c01974e40c7ee79cbc --- /dev/null +++ b/lean/OAI/Combinatorics/ParityLifts/Rerooting.lean @@ -0,0 +1,210 @@ +import OAI.Combinatorics.ParityLifts.GlueVertices + +namespace OAI + +namespace ParityWL + +open scoped BigOperators + +section AddRoot + +open scoped Classical + +variable {N : Type} (D : RankedTree N) + +noncomputable def addRootTree : RankedTree (Option N) where + root := none + parent := fun n => match n with + | none => none + | some a => if a = D.root then none else some (D.parent a) + rank := fun n => match n with + | none => 0 + | some a => D.rank a + 1 + parent_lt := by + intro n hn + cases n with + | none => exact (hn rfl).elim + | some a => + dsimp only + split_ifs with ha + · simp only; omega + · exact Nat.add_lt_add_right (D.parent_lt a ha) 1 + +lemma addRoot_map_ancestor {a b : N} (h : D.Ancestor a b) : + (addRootTree D).Ancestor (some a) (some b) := by + apply RankedTree.Ancestor.map D (addRootTree D) some _ h + intro j hj + apply RankedTree.Ancestor.step (by simp [addRootTree]) + simp only [addRootTree, ite_eq_right hj] + exact .refl + +lemma addRoot_ancestor_some {a : N} {n : Option N} + (h : (addRootTree D).Ancestor (some a) n) : + ∃ b, n = some b ∧ D.Ancestor a b := by + induction h with + | refl => exact ⟨a, rfl, .refl⟩ + | @step n hn h ih => + cases n with + | none => exact (hn rfl).elim + | some b => + obtain ⟨c, hc, hac⟩ := ih + change (if b = D.root then none else some (D.parent b)) = some c at hc + by_cases hb : b = D.root + · rw [ite_eq_left hb] at hc + cases hc + · rw [ite_eq_right hb] at hc + exact ⟨b, rfl, .step hb (by rwa [Option.some.inj hc])⟩ + +lemma addRoot_ancestor_iff {a b : N} : + (addRootTree D).Ancestor (some a) (some b) ↔ D.Ancestor a b := by + constructor + · intro h + obtain ⟨c, hc, hac⟩ := addRoot_ancestor_some D h + rwa [Option.some.inj hc] + · exact addRoot_map_ancestor D + +end AddRoot + +section ReRoot + +open scoped Classical + +variable {r k t : ℕ} (F : RootedTest r t) (ρ : Fin k → Fin r) + +def keepRoot (a : F.Vertex) := ∃ j, F.roots (ρ j) = a + +noncomputable def reRootBag : Option F.Node → Finset F.Vertex + | none => Finset.univ.image (F.roots ∘ ρ) + | some n => F.tree.bag n + +noncomputable def reRootTop (a : F.Vertex) : Option F.Node := + if keepRoot F ρ a then none else some (F.tree.top a) + +lemma keep_top {a : F.Vertex} (ha : keepRoot F ρ a) : F.tree.top a = F.tree.root := by + apply RankedTree.ancestor_root_eq + apply F.tree.top_ancestor + rw [F.root_bag] + obtain ⟨j, hj⟩ := ha + exact Finset.mem_image.mpr ⟨ρ j, Finset.mem_univ _, hj⟩ + +lemma reRootTop_mem (a : F.Vertex) : a ∈ reRootBag F ρ (reRootTop F ρ a) := by + by_cases ha : keepRoot F ρ a + · simp only [reRootTop, ite_eq_left ha, reRootBag, Finset.mem_image, Finset.mem_univ, + true_and, Function.comp_apply] + exact ha + · simpa only [reRootTop, ite_eq_right ha, reRootBag] using F.tree.top_mem a + +lemma reRootTop_ancestor (a : F.Vertex) (n : Option F.Node) + (han : a ∈ reRootBag F ρ n) : + (addRootTree F.tree.toRankedTree).Ancestor (reRootTop F ρ a) n := by + by_cases ha : keepRoot F ρ a + · rw [reRootTop, ite_eq_left ha] + exact (addRootTree F.tree.toRankedTree).root_ancestor n + · rw [reRootTop, ite_eq_right ha] + cases n with + | none => exact (ha (by simpa only [keepRoot, reRootBag, Finset.mem_image, + Finset.mem_univ, true_and, Function.comp_apply] using han)).elim + | some n => exact addRoot_map_ancestor _ (F.tree.top_ancestor a n han) + +lemma reRootInterval_mem (a : F.Vertex) (n l : Option F.Node) + (hn : (addRootTree F.tree.toRankedTree).Ancestor (reRootTop F ρ a) n) + (hnl : (addRootTree F.tree.toRankedTree).Ancestor n l) (ha : a ∈ reRootBag F ρ l) : + a ∈ reRootBag F ρ n := by + cases n with + | none => + have he := RankedTree.ancestor_root_eq (addRootTree F.tree.toRankedTree) hn + have hk : keepRoot F ρ a := by + by_contra hk + rw [reRootTop, ite_eq_right hk] at he + cases he + simpa only [keepRoot, reRootBag, Finset.mem_image, Finset.mem_univ, + true_and, Function.comp_apply] using hk + | some n => + obtain ⟨l, rfl, hnl'⟩ := addRoot_ancestor_some _ hnl + apply F.tree.interval_mem a n l _ hnl' ha + by_cases hk : keepRoot F ρ a + · rw [keep_top F ρ hk] + exact F.tree.toRankedTree.root_ancestor n + · rw [reRootTop, ite_eq_right hk] at hn + exact (addRoot_ancestor_iff _).mp hn + +noncomputable def reRootTest (hk : k < t) : RootedTest k t where + Vertex := F.Vertex + vertexFintype := F.vertexFintype + relation := F.relation + symmetric := F.symmetric + roots := F.roots ∘ ρ + Node := Option F.Node + nodeFintype := inferInstance + tree := + { toRankedTree := addRootTree F.tree.toRankedTree + bag := reRootBag F ρ + top := reRootTop F ρ + top_mem := reRootTop_mem F ρ + top_ancestor := reRootTop_ancestor F ρ + interval_mem := reRootInterval_mem F ρ + edge_cover := by + intro a b hab + obtain ⟨n, han, hbn⟩ := F.tree.edge_cover a b hab + exact ⟨some n, han, hbn⟩ + width := by + intro n + cases n with + | none => + exact le_trans Finset.card_image_le + (by simpa only [Finset.card_univ, Fintype.card_fin] using hk.le) + | some n => exact F.tree.width n + intersection := by + intro n hn + cases n with + | none => exact (hn rfl).elim + | some n => + change (F.tree.bag n ∩ reRootBag F ρ + (if n = F.tree.root then none else some (F.tree.parent n))).card < t + by_cases he : n = F.tree.root + · rw [ite_eq_left he] + exact lt_of_le_of_lt ((Finset.card_le_card Finset.inter_subset_right).trans + Finset.card_image_le) (by simpa using hk) + · rw [ite_eq_right he] + exact F.tree.intersection n he } + root_bag := rfl + +end ReRoot + +section ForgetCount + +open scoped Classical + +variable {k t : ℕ} (F : RootedTest (k + 1) t) (i : Fin (k + 1)) (hk : k < t) +variable {V : Type} (G : SimpleGraph V) (x : Fin k → V) + +noncomputable def reRootMapsEquiv : + (reRootTest F i.succAbove hk).Maps G x ≃ ((y : V) × F.Maps G (i.insertNth y x)) where + toFun f := ⟨f.1.1 (F.roots i), ⟨f.1, by + intro j + refine Fin.succAboveCases i ?_ (fun l => ?_) j + · simp only [Fin.insertNth_apply_same] + · rw [Fin.insertNth_apply_succAbove] + exact f.2 l⟩⟩ + invFun f := ⟨f.2.1, by + intro j + change f.2.1.1 (F.roots (i.succAbove j)) = x j + simpa only [Fin.insertNth_apply_succAbove] using f.2.2 (i.succAbove j)⟩ + left_inv _ := rfl + right_inv f := by + rcases f with ⟨y, f, hf⟩ + have hy : f.1 (F.roots i) = y := by + simpa only [Fin.insertNth_apply_same] using hf i + subst y + rfl + +lemma reRootTest_count [Fintype V] : + (reRootTest F i.succAbove hk).count G x = ∑ y : V, F.count G (i.insertNth y x) := by + unfold RootedTest.count + rw [Fintype.card_congr (reRootMapsEquiv F i hk G x), Fintype.card_sigma, Nat.cast_sum] + +end ForgetCount + +end ParityWL + +end OAI diff --git a/lean/OAI/Combinatorics/ParityLifts/RootedTests.lean b/lean/OAI/Combinatorics/ParityLifts/RootedTests.lean new file mode 100644 index 0000000000000000000000000000000000000000..8b86b1faa3112c4b7a6dabd6062f3756e29274ed --- /dev/null +++ b/lean/OAI/Combinatorics/ParityLifts/RootedTests.lean @@ -0,0 +1,150 @@ +import OAI.Combinatorics.ParityLifts.RankedTrees + +namespace OAI + +namespace ParityWL + +open scoped BigOperators + +section RootedTests + +open scoped Classical + +/-- Sources may have loops during root gluing. A loop contributes zero on every +simple target; it is never silently deleted. -/ +structure RootedTest (k t : ℕ) where + Vertex : Type + vertexFintype : Fintype Vertex + relation : Vertex → Vertex → Prop + symmetric : Std.Symm relation + roots : Fin k → Vertex + Node : Type + nodeFintype : Fintype Node + tree : RankedBagTree (N := Node) relation t + root_bag : tree.bag tree.root = Finset.univ.image roots + +attribute [instance] RootedTest.vertexFintype RootedTest.nodeFintype + +noncomputable def RelationMaps {A V : Type} (R : A → A → Prop) (G : SimpleGraph V) := + {f : A → V // ∀ a b, R a b → G.Adj (f a) (f b)} + +noncomputable instance relationMapsFintype {A V : Type} [Fintype A] [Fintype V] + (R : A → A → Prop) (G : SimpleGraph V) : Fintype (RelationMaps R G) := by + unfold RelationMaps + infer_instance + +noncomputable def RootedTest.Maps {k t : ℕ} (F : RootedTest k t) {V : Type} + (G : SimpleGraph V) (x : Fin k → V) := + {f : RelationMaps F.relation G // ∀ i, f.1 (F.roots i) = x i} + +noncomputable instance rootedMapsFintype {k t : ℕ} (F : RootedTest k t) + {V : Type} [Fintype V] (G : SimpleGraph V) (x : Fin k → V) : Fintype (F.Maps G x) := by + unfold RootedTest.Maps + infer_instance + +noncomputable def RootedTest.count {k t : ℕ} (F : RootedTest k t) + {V : Type} [Fintype V] (G : SimpleGraph V) (x : Fin k → V) : ℚ := + Fintype.card (F.Maps G x) + +noncomputable def RootedTest.totalEquiv {k t : ℕ} (F : RootedTest k t) + {V : Type} (G : SimpleGraph V) : + ((x : Fin k → V) × F.Maps G x) ≃ RelationMaps F.relation G where + toFun f := f.2.1 + invFun f := ⟨fun i => f.1 (F.roots i), ⟨f, fun _ => rfl⟩⟩ + left_inv f := by + rcases f with ⟨x, f, hf⟩ + have he : (fun i => f.1 (F.roots i)) = x := funext hf + subst x + rfl + right_inv _ := rfl + +lemma RootedTest.sum_count {k t : ℕ} (F : RootedTest k t) + {V : Type} [Fintype V] (G : SimpleGraph V) : + ∑ x : Fin k → V, F.count G x = (Fintype.card (RelationMaps F.relation G) : ℚ) := by + unfold count + rw [← Nat.cast_sum, ← Fintype.card_sigma, Fintype.card_congr (F.totalEquiv G)] + +noncomputable def relationMapsSimpleEquiv {A V : Type} (F : SimpleGraph A) + (G : SimpleGraph V) : RelationMaps F.Adj G ≃ (F →g G) where + toFun f := ⟨f.1, fun h => f.2 _ _ h⟩ + invFun f := ⟨f, fun _ _ h => f.map_adj h⟩ + left_inv _ := rfl + right_inv _ := rfl + +lemma relationMaps_loop {A V : Type} [Fintype A] [Fintype V] + (R : A → A → Prop) (G : SimpleGraph V) {a : A} (ha : R a a) : + Fintype.card (RelationMaps R G) = 0 := by + have : IsEmpty (RelationMaps R G) := ⟨fun f => (f.2 a a ha).ne rfl⟩ + exact Fintype.card_eq_zero + +lemma no_choice_equal_relation {W N : Type} [Fintype W] [Fintype N] + {t : ℕ} (C : ChoiceSystem t) (ht : 0 < t) (hn : ¬ C.Successful) + (R : W → W → Prop) (hs : Std.Symm R) (D : RankedBagTree (N := N) R t) : + Fintype.card (RelationMaps R (zeroLift C)) = Fintype.card (RelationMaps R (starLift C)) := by + by_cases hloop : ∃ x, R x x + · obtain ⟨x, hx⟩ := hloop + rw [relationMaps_loop R _ hx, relationMaps_loop R _ hx] + · let F : SimpleGraph W := ⟨R, hs, ⟨fun x hx => hloop ⟨x, hx⟩⟩⟩ + have hz : Fintype.card (RelationMaps R (zeroLift C)) = homCount F (zeroLift C) := + (homCount_card_equiv (zeroLift C) F (relationMapsSimpleEquiv F (zeroLift C)).symm).symm + have ho : Fintype.card (RelationMaps R (starLift C)) = homCount F (starLift C) := + (homCount_card_equiv (starLift C) F (relationMapsSimpleEquiv F (starLift C)).symm).symm + rw [hz, ho] + exact no_choice_equal_decomposed C ht hn F D + +lemma no_choice_equal_rooted_total {k t : ℕ} (F : RootedTest k t) + (C : ChoiceSystem t) (ht : 0 < t) (hn : ¬ C.Successful) : + ∑ x, F.count (zeroLift C) x = ∑ x, F.count (starLift C) x := by + rw [F.sum_count, F.sum_count, + no_choice_equal_relation C ht hn F.relation F.symmetric F.tree] + +noncomputable def singleBagTest {k t : ℕ} {A : Type} [Fintype A] + (R : A → A → Prop) (hs : Std.Symm R) (r : Fin k → A) + (hr : Function.Surjective r) (hA : Fintype.card A ≤ t) : RootedTest k t where + Vertex := A + vertexFintype := inferInstance + relation := R + symmetric := hs + roots := r + Node := Unit + nodeFintype := inferInstance + tree := + { root := () + parent := fun _ => () + rank := fun _ => 0 + parent_lt := by intro i hi; exact (hi (Subsingleton.elim _ _)).elim + bag := fun _ => Finset.univ + top := fun _ => () + top_mem := fun _ => Finset.mem_univ _ + top_ancestor := by intro x i _; cases i; exact .refl + interval_mem := by intros; exact Finset.mem_univ _ + edge_cover := fun _ _ _ => ⟨(), Finset.mem_univ _, Finset.mem_univ _⟩ + width := by intro _; simpa only [Finset.card_univ] using hA + intersection := by intro i hi; exact (hi (Subsingleton.elim _ _)).elim } + root_bag := by + ext a + simp only [Finset.mem_univ, Finset.mem_image, true_and, true_iff] + exact hr a + +noncomputable def isolatedTest (k t : ℕ) (hkt : k ≤ t) : RootedTest k t := + singleBagTest (fun _ _ : Fin k => False) ⟨fun _ _ h => h⟩ id Function.surjective_id + (by simpa using hkt) + +lemma isolatedTest_count (k t : ℕ) (hkt : k ≤ t) {V : Type} [Fintype V] + (G : SimpleGraph V) (x : Fin k → V) : (isolatedTest k t hkt).count G x = 1 := by + let f : (isolatedTest k t hkt).Maps G x := ⟨⟨x, fun _ _ h => h.elim⟩, fun _ => rfl⟩ + have hi : Unique ((isolatedTest k t hkt).Maps G x) := + { default := f + uniq := by + intro g + apply Subtype.ext + apply Subtype.ext + funext i + exact g.2 i } + simp only [RootedTest.count, Fintype.card_unique, Nat.cast_one] + +end RootedTests + +end ParityWL + +end OAI diff --git a/lean/OAI/Combinatorics/ParityLifts/SAT.lean b/lean/OAI/Combinatorics/ParityLifts/SAT.lean new file mode 100644 index 0000000000000000000000000000000000000000..cb4d79834066285ff912c8b2675f38a5a13a1c85 --- /dev/null +++ b/lean/OAI/Combinatorics/ParityLifts/SAT.lean @@ -0,0 +1,319 @@ +import OAI.Combinatorics.ParityLifts.Simulation + +namespace OAI + +namespace ParityWL.Complexity +abbrev Literal (N : ℕ) := Fin N × Bool + +structure Clause (N : ℕ) where + literals : List (Literal N) + width : literals.length ≤ 3 + +abbrev Formula (N : ℕ) := List (Clause N) + +def Clause.Satisfied {N : ℕ} (C : Clause N) (a : Fin N → Bool) : Prop := + ∃ l ∈ C.literals, a l.1 = l.2 + +def Formula.Satisfied {N : ℕ} (F : Formula N) (a : Fin N → Bool) : Prop := + ∀ C ∈ F, C.Satisfied a + +def Formula.Satisfiable {N : ℕ} (F : Formula N) : Prop := + ∃ a, F.Satisfied a + +/-- Self-delimiting binary natural numbers, followed by the explicit formula. +The clause width is encoded even for an empty clause. -/ +def encodeNat (n : ℕ) : List Bool := + List.replicate n.bits.length true ++ false :: n.bits + +def encodeClause {N : ℕ} (C : Clause N) : List Bool := + encodeNat C.literals.length ++ C.literals.flatMap (fun l => encodeNat l.1.val ++ [l.2]) + +def encodeFormula {N : ℕ} (F : Formula N) : List Bool := + encodeNat N ++ encodeNat F.length ++ F.flatMap encodeClause + + +end ParityWL.Complexity + +namespace ParityWL.Complexity + +@[simp] lemma treeEncode_ticks (n : ℕ) : treeEncode (List.replicate n false) = numTree n := by + induction n with + | zero => rfl + | succ n ih => simp [List.replicate_succ, numTree, ih] + +def PolyProgram.ticks : PolyProgram ℕ (List Bool) (fun n => List.replicate n false) := + .expr .input (by intro n; simp [TExpr.eval]) + +def PolyProgram.natSucc : PolyProgram ℕ ℕ Nat.succ := + .expr (.pair .nil .input) (by intro n; rfl) + +def PolyProgram.natPred : PolyProgram ℕ ℕ Nat.pred := + .expr TExpr.input.right (by intro n; cases n <;> rfl) + +def PolyProgram.natZero : PolyProgram ℕ Bool (fun n => decide (n=0)) := + .expr (.cond .input (.const (boolTree true)) .nil) (by intro n; cases n <;> rfl) + +lemma list_foldl_succ (xs : List Bool) (n : ℕ) : + xs.foldl (fun m _ => m+1) n = n+xs.length := by + induction xs generalizing n with + | nil => simp + | cons b bs ih => simp [ih]; omega + +def PolyProgram.length (α : Type) [TreeCodec α] : PolyProgram (List α) ℕ List.length := by + let S := (PolyProgram.snd α ℕ).comp PolyProgram.natSucc + have hg (a : α) (n : ℕ) : (treeEncode (n+1)).size ≤ + (treeEncode n).size + 2*((treeEncode a).size+1)^0 := by simp; omega + let F := S.foldlGrowing 2 0 hg + refine (((PolyProgram.id (List α)).pair (PolyProgram.const 0)).comp F).congr ?_ + intro xs + change xs.foldl (fun n _ => n+1) 0 = xs.length + have he (ys : List α) (n : ℕ) : ys.foldl (fun m _ => m+1) n = n+ys.length := by + induction ys generalizing n with + | nil => simp + | cons a ys ih => simp [ih]; omega + exact (he xs 0).trans (Nat.zero_add _) + +def truePrefix : List Bool → ℕ + | [] => 0 + | true :: xs => truePrefix xs + 1 + | false :: _ => 0 + +lemma truePrefix_foldr (xs : List Bool) : + xs.foldr (fun b n => if b then n+1 else 0) 0 = truePrefix xs := by + induction xs with + | nil => rfl + | cons b xs ih => cases b <;> simp [truePrefix, ih] + +lemma truePrefix_le (xs : List Bool) : truePrefix xs ≤ xs.length := by + induction xs with + | nil => simp [truePrefix] + | cons b xs ih => cases b <;> simp [truePrefix, ih] + +def PolyProgram.truePrefix : PolyProgram (List Bool) ℕ truePrefix := by + let S := (PolyProgram.fst Bool ℕ).ite + ((PolyProgram.snd Bool ℕ).comp PolyProgram.natSucc) (PolyProgram.const 0) + have hg (b : Bool) (n : ℕ) : (treeEncode (if b then n+1 else 0)).size ≤ + (treeEncode n).size + 2*((treeEncode b).size+1)^0 := by + cases b <;> simp + omega + let F := S.foldlGrowing 2 0 hg + refine ((((PolyProgram.reverse Bool).pair (PolyProgram.const 0)).comp F)).congr ?_ + intro xs + change xs.reverse.foldl (fun n b => if b then n+1 else 0) 0 = Complexity.truePrefix xs + rw [List.foldl_reverse, truePrefix_foldr] + +def listShift {α : Type} (x : List α × List α) : List α × List α := + match x.1 with + | [] => x + | a :: xs => (xs, a :: x.2) + +lemma listShift_size {α : Type} [TreeCodec α] (x : List α × List α) : + (treeEncode (listShift x)).size = (treeEncode x).size := by + rcases x with ⟨xs, ys⟩ + cases xs <;> simp [listShift, DataTree.size] + omega + +def PolyProgram.listShift (α : Type) [TreeCodec α] : + PolyProgram (List α × List α) (List α × List α) listShift := + .expr (.cond TExpr.input.left .input + (.pair TExpr.input.left.right (.pair TExpr.input.left.left TExpr.input.right))) + (by rintro ⟨xs, ys⟩; cases xs <;> rfl) + +lemma fold_shift {α : Type} (n : ℕ) (xs ys : List α) : + (List.replicate n false).foldl (fun s _ => listShift s) (xs,ys) = + (xs.drop n, (xs.take n).reverse ++ ys) := by + induction n generalizing xs ys with + | zero => simp + | succ n ih => + cases xs with + | nil => simpa [List.replicate_succ, listShift] using ih [] ys + | cons a xs => + simpa only [List.replicate_succ, List.foldl_cons, listShift, List.take_succ_cons, + List.drop_succ_cons, List.reverse_cons, List.append_assoc, List.singleton_append] + using ih xs (a :: ys) + +def PolyProgram.splitAt (α : Type) [TreeCodec α] : + PolyProgram (ℕ × List α) (List α × List α) (fun x => (x.2.take x.1, x.2.drop x.1)) := by + let S := (PolyProgram.snd Bool (List α × List α)).comp (PolyProgram.listShift α) + have hg (b : Bool) (x : List α × List α) : + (treeEncode (Complexity.listShift x)).size ≤ (treeEncode x).size + 0*((treeEncode b).size+1)^0 := by + simpa only [Nat.zero_mul, Nat.add_zero] using le_of_eq (listShift_size x) + let F := S.foldlGrowing 0 0 hg + let I := ((PolyProgram.fst ℕ (List α)).comp PolyProgram.ticks).pair + ((PolyProgram.snd ℕ (List α)).pair (PolyProgram.const ([] : List α))) + let O := ((PolyProgram.snd (List α) (List α)).comp (PolyProgram.reverse α)).pair + (PolyProgram.fst (List α) (List α)) + refine ((I.comp F).comp O).congr ?_ + rintro ⟨n,xs⟩ + change (((List.replicate n false).foldl _ (xs,[])).2.reverse, + ((List.replicate n false).foldl _ (xs,[])).1) = _ + simp [fold_shift] + +def readNatBits (xs : List Bool) : List Bool × List Bool := + let n := truePrefix xs + ((xs.drop (n+1)).take n, (xs.drop (n+1)).drop n) + +def PolyProgram.readNatBits : PolyProgram (List Bool) (List Bool × List Bool) readNatBits := by + let fst := PolyProgram.fst ℕ (List Bool) + let snd := PolyProgram.snd ℕ (List Bool) + let skip := ((fst.comp PolyProgram.natSucc).pair snd).comp (PolyProgram.splitAt Bool) + let P := fst.pair (skip.comp (PolyProgram.snd (List Bool) (List Bool))) + exact ((PolyProgram.truePrefix.pair (PolyProgram.id (List Bool))).comp P).comp + (PolyProgram.splitAt Bool) + +lemma truePrefix_encodeNat (n : ℕ) (xs : List Bool) : + truePrefix (encodeNat n ++ xs) = n.bits.length := by + unfold encodeNat + rw [List.append_assoc, List.cons_append] + generalize n.bits.length = k + induction k with + | zero => simp [truePrefix] + | succ k ih => simp [List.replicate_succ, truePrefix, ih] + +lemma readNatBits_encode (n : ℕ) (xs : List Bool) : + readNatBits (encodeNat n ++ xs) = (n.bits,xs) := by + rw [readNatBits, truePrefix_encodeNat] + simp [encodeNat, List.drop_append] + +lemma readNatBits_sizes (xs : List Bool) : + (readNatBits xs).1.length ≤ xs.length ∧ (readNatBits xs).2.length ≤ xs.length := by + simp [readNatBits, List.length_take, List.length_drop] + +end ParityWL.Complexity + +namespace ParityWL.Complexity + +abbrev BitLiteral := List Bool × Bool +abbrev BitClause := List BitLiteral + +def readLiteral (xs : List Bool) : BitLiteral × List Bool := + let x := readNatBits xs + ((x.1,x.2.headD false),x.2.tail) + +def PolyProgram.readLiteral : PolyProgram (List Bool) (BitLiteral × List Bool) readLiteral := by + let E : PolyProgram (List Bool × List Bool) (BitLiteral × List Bool) + (fun x => ((x.1,x.2.headD false),x.2.tail)) := .expr + (.pair (.pair TExpr.input.left (.cond TExpr.input.right .nil TExpr.input.right.left)) TExpr.input.right.right) + (by rintro ⟨a,b⟩; cases b <;> rfl) + exact PolyProgram.readNatBits.comp E + +def readLiterals : ℕ → List Bool → BitClause × List Bool + | 0, xs => ([], xs) + | n+1, xs => + let x := readLiteral xs + let y := readLiterals n x.2 + (x.1::y.1,y.2) + +def PolyProgram.readLiterals : (n : ℕ) → PolyProgram (List Bool) (BitClause × List Bool) (readLiterals n) + | 0 => .expr (.pair .nil .input) (by intro xs; rfl) + | n+1 => + let P := (PolyProgram.fst BitLiteral (List Bool)).pair + ((PolyProgram.snd BitLiteral (List Bool)).comp (PolyProgram.readLiterals n)) + let Q : PolyProgram (BitLiteral × (BitClause × List Bool)) (BitClause × List Bool) + (fun x => (x.1 :: x.2.1, x.2.2)) := + .expr (.pair (.pair TExpr.input.left TExpr.input.right.left) TExpr.input.right.right) + (by intro x; rfl) + (PolyProgram.readLiteral.comp P).comp Q + +def readWidth (xs : List Bool) : ℕ := + if xs = (1 : ℕ).bits then 1 else if xs = (2 : ℕ).bits then 2 else + if xs = (3 : ℕ).bits then 3 else 0 + +lemma readWidth_le (xs : List Bool) : readWidth xs ≤ 3 := by unfold readWidth; split_ifs <;> omega + +lemma readWidth_bits (n : ℕ) (hn : n≤3) : readWidth n.bits = n := by + interval_cases n <;> decide + +def readClause (xs : List Bool) : BitClause × List Bool := + let x := readNatBits xs + readLiterals (readWidth x.1) x.2 + +noncomputable def PolyProgram.readClause : PolyProgram (List Bool) (BitClause × List Bool) readClause := by + let P (n : ℕ) := ((PolyProgram.fst (List Bool) (List Bool)).pair + (PolyProgram.const n.bits)).comp (PolyProgram.equal (List Bool)) + let Q (n : ℕ) := (PolyProgram.snd (List Bool) (List Bool)).comp (PolyProgram.readLiterals n) + refine (PolyProgram.readNatBits.comp ((P 1).ite (Q 1) ((P 2).ite (Q 2) ((P 3).ite (Q 3) (Q 0))))).congr ?_ + intro xs + simp only [Function.comp_def] + change (if decide ((Complexity.readNatBits xs).1 = (1:ℕ).bits) then _ else _) = _ + simp only [Complexity.readClause, readWidth, decide_eq_true_eq] + split_ifs <;> rfl + +lemma readNatBits_remainder (xs : List Bool) : + (readNatBits xs).2.length ≤ xs.length := (readNatBits_sizes xs).2 + +lemma readNatBits_consumes (xs : List Bool) (hx : xs ≠ []) : + (readNatBits xs).2.length < xs.length := by + have hp := List.length_pos_iff_ne_nil.mpr hx + simp only [readNatBits, List.length_drop] + omega + +lemma readNatBits_account (xs : List Bool) : + (readNatBits xs).1.length + (readNatBits xs).2.length ≤ xs.length := by + simp only [readNatBits, List.length_take, List.length_drop] + omega + +lemma readLiteral_remainder (xs : List Bool) : (readLiteral xs).2.length ≤ xs.length := by + have := readNatBits_remainder xs + simpa only [readLiteral, List.length_tail] using (Nat.sub_le (readNatBits xs).2.length 1).trans this + +lemma readLiteral_account (xs : List Bool) : + (treeEncode (readLiteral xs).1).size + 4*(readLiteral xs).2.length ≤ 4*xs.length+8 := by + have h := readNatBits_account xs + have ht := treeEncode_bits_size (readNatBits xs).1 + have hb : (treeEncode ((readNatBits xs).2.headD false)).size ≤ 3 := by + cases (readNatBits xs).2.headD false <;> simp [DataTree.size] + simp only [readLiteral, treeEncode_pair, DataTree.size, List.length_tail] + omega + +lemma readLiterals_remainder (n : ℕ) (xs : List Bool) : + (readLiterals n xs).2.length ≤ xs.length := by + induction n generalizing xs with + | zero => exact le_rfl + | succ n ih => exact (ih (readLiteral xs).2).trans (readLiteral_remainder xs) + +lemma readLiterals_account (n : ℕ) (xs : List Bool) : + (treeEncode (readLiterals n xs).1).size + 4*(readLiterals n xs).2.length ≤ + 4*xs.length+9*n+1 := by + induction n generalizing xs with + | zero => simp [readLiterals, DataTree.size]; omega + | succ n ih => + have h := ih (readLiteral xs).2 + have h' := readLiteral_account xs + simp only [readLiterals, treeEncode_cons, DataTree.size] + omega + +lemma readClause_consumes (xs : List Bool) (hx : xs≠[]) : (readClause xs).2.length < xs.length := + (readLiterals_remainder _ _).trans_lt (readNatBits_consumes xs hx) + +lemma readClause_account (xs : List Bool) (hx : xs≠[]) : + (treeEncode (readClause xs).1).size+1+40*(readClause xs).2.length ≤ 40*xs.length := by + have h := readLiterals_account (readWidth (readNatBits xs).1) (readNatBits xs).2 + have h' := readLiterals_remainder (readWidth (readNatBits xs).1) (readNatBits xs).2 + have hn := readNatBits_consumes xs hx + have hw := readWidth_le (readNatBits xs).1 + dsimp only [readClause] + omega + +lemma readLiteral_encode (n : ℕ) (b : Bool) (xs : List Bool) : + readLiteral (encodeNat n ++ b::xs) = ((n.bits,b),xs) := by + simp [readLiteral, readNatBits_encode] + +lemma readLiterals_encode (xs : List (ℕ × Bool)) (ys : List Bool) : + readLiterals xs.length (xs.flatMap (fun x => encodeNat x.1 ++ [x.2]) ++ ys) = + (xs.map (fun x => (x.1.bits,x.2)),ys) := by + induction xs generalizing ys with + | nil => simp [readLiterals] + | cons x xs ih => simp [readLiterals, List.append_assoc, readLiteral_encode, ih] + +lemma readClause_encode {N : ℕ} (C : Clause N) (xs : List Bool) : + readClause (encodeClause C ++ xs) = + (C.literals.map (fun l => (l.1.val.bits,l.2)),xs) := by + simp only [readClause, encodeClause, List.append_assoc, readNatBits_encode, + readWidth_bits C.literals.length C.width] + have ht := readLiterals_encode (C.literals.map (fun l => (l.1.val,l.2))) xs + simpa only [List.length_map, List.flatMap_map, Function.comp_def, List.map_map] using ht + +end ParityWL.Complexity + +end OAI diff --git a/lean/OAI/Combinatorics/ParityLifts/SATChoice.lean b/lean/OAI/Combinatorics/ParityLifts/SATChoice.lean new file mode 100644 index 0000000000000000000000000000000000000000..379ce6007cf9ac963c5555e4466ece2825f38dee --- /dev/null +++ b/lean/OAI/Combinatorics/ParityLifts/SATChoice.lean @@ -0,0 +1,341 @@ +import OAI.Combinatorics.ParityLifts.LeafCounts + +namespace OAI + +namespace ParityWL +namespace Complexity +/-- This is a full row-major adjacency matrix, not an adjacency oracle or a +colored-graph promise. Both matrices and their common order appear on the tape. -/ +noncomputable def encodeGraphs {n : ℕ} (G H : SimpleGraph (Fin n)) : List Bool := by + classical + exact encodeNat n ++ + (List.ofFn (fun i : Fin n => List.ofFn (fun j : Fin n => decide (G.Adj i j)))).flatten ++ + (List.ofFn (fun i : Fin n => List.ofFn (fun j : Fin n => decide (H.Adj i j)))).flatten + +inductive Implementation | commonColors | pureUnion + deriving DecidableEq + +noncomputable def Equivalent {n : ℕ} (G H : SimpleGraph (Fin n)) + (c : Convention) (i : Implementation) (k : ℕ) : Prop := + match i with + | .commonColors => WLEquivalent G H c k + | .pureUnion => PureWLEquivalent G H c k + +/-- An actual execution bound; no computation is hidden in its interpretation. -/ +def SATTimeBound (M : Machine) (B : ℕ → ℕ → ℝ) : Prop := + ∀ (N : ℕ) (F : Formula N), ∃ s b, + Emits M (encodeFormula F) s b ∧ (b = true ↔ F.Satisfiable) ∧ + (s : ℝ) ≤ B N (encodeFormula F).length + +/-- Positive-rate ETH: one positive forbidden rate, with arbitrary fixed +polynomial input factor. This is not the weaker uniform premise below. -/ +def PositiveRateETH : Prop := + ∃ δ : ℝ, 0 < δ ∧ ¬ ∃ (M : Machine) (C : ℝ) (d : ℕ), + 0 < C ∧ SATTimeBound M (fun N L => C * (L + 1 : ℝ) ^ d * (2 : ℝ) ^ (δ * N)) + +/-- The same single machine must meet every positive exponential rate, with +one fixed polynomial input factor. Constants may depend on the chosen rate. -/ +def UniformSubexponentialETH : Prop := + ¬ ∃ (M : Machine) (d : ℕ), ∀ ε : ℝ, 0 < ε → ∃ C : ℝ, 0 < C ∧ + SATTimeBound M (fun N L => C * (L + 1 : ℝ) ^ d * (2 : ℝ) ^ (ε * N)) + +/-- Using n+1 includes the zero-order input and is exactly O(n^r) on positive +orders. The finite exceptional small orders can be absorbed in the constant. -/ +noncomputable def FixedWLBound (M : Machine) (c : Convention) (i : Implementation) + (k : ℕ) (r : ℝ) : Prop := + ∃ C : ℝ, 0 < C ∧ ∀ (n : ℕ) (G H : SimpleGraph (Fin n)), ∃ s b, + Emits M (encodeGraphs G H) s b ∧ (b = true ↔ Equivalent G H c i k) ∧ + (s : ℝ) ≤ C * (n + 1 : ℝ) ^ r + +noncomputable def UniformWLBound (M : Machine) (c : Convention) (i : Implementation) + (f g : ℕ → ℝ) : Prop := + (∀ k, 0 < f k) ∧ (∀ k, 0 ≤ g k) ∧ + ∀ (k : ℕ), 4 ≤ k → ∀ (n : ℕ) (G H : SimpleGraph (Fin n)), ∃ s b, + Emits M (encodeNat k ++ encodeGraphs G H) s b ∧ + (b = true ↔ Equivalent G H c i k) ∧ (s : ℝ) ≤ f k * (n + 1 : ℝ) ^ g k + +noncomputable def FixedDimensionETHStatement : Prop := + PositiveRateETH → ∃ c : ℝ, 0 < c ∧ ∃ K : ℕ, 4 ≤ K ∧ + ∀ k : ℕ, K ≤ k → ∀ conv : Convention, ∀ i : Implementation, + ¬ ∃ M : Machine, FixedWLBound M conv i k (c * k) + +noncomputable def UniformETHStatement : Prop := + UniformSubexponentialETH → ∀ c : Convention, ∀ i : Implementation, + ¬ ∃ (M : Machine) (f g : ℕ → ℝ), + Filter.Tendsto (fun k : ℕ => g k / k) Filter.atTop (nhds 0) ∧ + UniformWLBound M c i f g + + +end Complexity +namespace Complexity + +def groupWidth (m t : ℕ) : ℕ := (m + t - 1) / t + +lemma le_groupWidth_mul (m t : ℕ) (ht : 0 < t) : m ≤ groupWidth m t * t := by + have hr := Nat.mod_lt (m + t - 1) ht + have he := Nat.div_add_mod (m + t - 1) t + dsimp [groupWidth] + rw [Nat.mul_comm] at he + omega + +def groupAt {N t : ℕ} (F : Formula N) (ht : 0 < t) (q : Fin F.length) : Fin t := + ⟨q.val % t, Nat.mod_lt _ ht⟩ + +def groupIndices {N t : ℕ} (F : Formula N) (ht : 0 < t) (i : Fin t) : + Finset (Fin F.length) := Finset.univ.filter (fun q => groupAt F ht q = i) + +lemma group_indices_card {N t : ℕ} (F : Formula N) (ht : 0 < t) (i : Fin t) : + (groupIndices F ht i).card ≤ groupWidth F.length t := by + let e : (groupIndices F ht i) → Fin (groupWidth F.length t) := fun q => + ⟨q.1.val / t, (Nat.div_lt_iff_lt_mul ht).mpr + (lt_of_lt_of_le q.1.isLt (le_groupWidth_mul F.length t ht))⟩ + have hinj : Function.Injective e := by + intro q r he + apply Subtype.ext + apply Fin.ext + have hq : groupAt F ht q.1 = i := (Finset.mem_filter.mp q.2).2 + have hr : groupAt F ht r.1 = i := (Finset.mem_filter.mp r.2).2 + have hm : q.1.val % t = r.1.val % t := congrArg Fin.val (hq.trans hr.symm) + have hd : q.1.val / t = r.1.val / t := congrArg Fin.val he + have h1 := Nat.div_add_mod q.1.val t + have h2 := Nat.div_add_mod r.1.val t + rw [hd, hm] at h1 + omega + simpa using Fintype.card_le_of_injective e hinj + +def clauseScope {N : ℕ} (C : Clause N) : Finset (Fin N) := + C.literals.toFinset.image Prod.fst + +def groupScope {N t : ℕ} (F : Formula N) (ht : 0 < t) (i : Fin t) : Finset (Fin N) := + (groupIndices F ht i).biUnion (fun q => clauseScope (F.get q)) + +lemma clauseScope_card {N : ℕ} (C : Clause N) : (clauseScope C).card ≤ 3 := + (Finset.card_image_le.trans (List.toFinset_card_le _)).trans C.width + +lemma groupScope_card {N t : ℕ} (F : Formula N) (ht : 0 < t) (i : Fin t) : + (groupScope F ht i).card ≤ 3 * groupWidth F.length t := by + calc + _ ≤ ∑ q ∈ groupIndices F ht i, (clauseScope (F.get q)).card := Finset.card_biUnion_le + _ ≤ ∑ _q ∈ groupIndices F ht i, 3 := Finset.sum_le_sum (fun q _ => clauseScope_card _) + _ = 3 * (groupIndices F ht i).card := by simp [Nat.mul_comm] + _ ≤ _ := Nat.mul_le_mul_left 3 (group_indices_card F ht i) + +def extendScope {N : ℕ} (s : Finset (Fin N)) (a : s → Bool) (v : Fin N) : Bool := + if h : v ∈ s then a ⟨v, h⟩ else false + +@[simp] lemma extendScope_apply {N : ℕ} (s : Finset (Fin N)) (a : s → Bool) + (v : Fin N) (hv : v ∈ s) : extendScope s a v = a ⟨v, hv⟩ := by + simp [extendScope, hv] + +noncomputable def groupedChoice {N t : ℕ} (F : Formula N) (ht : 0 < t) : ChoiceSystem t := by + classical + exact { + Domain := fun i => {a : groupScope F ht i → Bool // + ∀ q ∈ groupIndices F ht i, (F.get q).Satisfied (extendScope (groupScope F ht i) a)} + domainFintype := fun _ => inferInstance + Label := fun p => ↥(groupScope F ht p.1.1 ∩ groupScope F ht p.1.2) → Bool + labelFintype := fun _ => inferInstance + leftLabel := fun _ a v => a.1 ⟨v.1, (Finset.mem_inter.mp v.2).1⟩ + rightLabel := fun _ a v => a.1 ⟨v.1, (Finset.mem_inter.mp v.2).2⟩ } + +lemma groupedChoice_size {N t : ℕ} (F : Formula N) (ht : 0 < t) : + (groupedChoice F ht).SizeAtMost (2 ^ (3 * groupWidth F.length t)) := by + classical + constructor + · intro i + change Fintype.card {a : groupScope F ht i → Bool // _} ≤ _ + calc + _ ≤ Fintype.card (groupScope F ht i → Bool) := Fintype.card_subtype_le _ + _ = 2 ^ (groupScope F ht i).card := by simp + _ ≤ _ := Nat.pow_le_pow_right (by omega) (groupScope_card F ht i) + · intro p + change Fintype.card (↥(groupScope F ht p.1.1 ∩ groupScope F ht p.1.2) → Bool) ≤ _ + simp only [Fintype.card_fun, Fintype.card_bool, Fintype.card_coe] + apply Nat.pow_le_pow_right (by omega) + exact (Finset.card_le_card Finset.inter_subset_left).trans (groupScope_card F ht p.1.1) + +lemma literal_mem_groupScope {N t : ℕ} (F : Formula N) (ht : 0 < t) (i : Fin t) + (q : Fin F.length) (hq : q ∈ groupIndices F ht i) (l : Literal N) + (hl : l ∈ (F.get q).literals) : l.1 ∈ groupScope F ht i := by + exact Finset.mem_biUnion.mpr ⟨q, hq, Finset.mem_image.mpr ⟨l, by simpa using hl, rfl⟩⟩ + +lemma groupedChoice_successful_of_sat {N t : ℕ} (F : Formula N) (ht : 0 < t) + (hF : F.Satisfiable) : (groupedChoice F ht).Successful := by + classical + rcases hF with ⟨a, ha⟩ + let d : (i : Fin t) → (groupedChoice F ht).Domain i := fun i => + ⟨fun v => a v.1, by + intro q hq + rcases ha _ (F.get_mem q) with ⟨l, hl, he⟩ + exact ⟨l, hl, by simpa [extendScope, literal_mem_groupScope F ht i q hq l hl] using he⟩⟩ + refine ⟨d, ?_⟩ + intro p + rfl + +lemma groupedChoice_agreement {N t : ℕ} (F : Formula N) (ht : 0 < t) + (d : (i : Fin t) → (groupedChoice F ht).Domain i) + (hd : ∀ p : MainPair t, + (groupedChoice F ht).leftLabel p (d p.1.1) = (groupedChoice F ht).rightLabel p (d p.1.2)) + (i j : Fin t) (v : Fin N) (hi : v ∈ groupScope F ht i) (hj : v ∈ groupScope F ht j) : + (d i).1 ⟨v, hi⟩ = (d j).1 ⟨v, hj⟩ := by + rcases lt_trichotomy i j with h | rfl | h + · exact congrFun (hd ⟨(i, j), h⟩) ⟨v, Finset.mem_inter.mpr ⟨hi, hj⟩⟩ + · rfl + · exact (congrFun (hd ⟨(j, i), h⟩) ⟨v, Finset.mem_inter.mpr ⟨hj, hi⟩⟩).symm + +lemma sat_of_groupedChoice_successful {N t : ℕ} (F : Formula N) (ht : 0 < t) + (hF : (groupedChoice F ht).Successful) : F.Satisfiable := by + classical + rcases hF with ⟨d, hd⟩ + let a : Fin N → Bool := fun v => + if h : ∃ i, v ∈ groupScope F ht i then (d h.choose).1 ⟨v, h.choose_spec⟩ else false + have hh : ∀ i v (hv : v ∈ groupScope F ht i), a v = (d i).1 ⟨v, hv⟩ := by + intro i v hv + have he : ∃ j, v ∈ groupScope F ht j := ⟨i, hv⟩ + dsimp [a] + rw [dite_eq_left he] + exact groupedChoice_agreement F ht d hd he.choose i v he.choose_spec hv + refine ⟨a, ?_⟩ + intro C hC + rcases List.get_of_mem hC with ⟨q, rfl⟩ + let i := groupAt F ht q + have hq : q ∈ groupIndices F ht i := by simp [groupIndices, i] + rcases (d i).2 q hq with ⟨l, hl, he⟩ + refine ⟨l, hl, ?_⟩ + have hv := literal_mem_groupScope F ht i q hq l hl + rw [hh i l.1 hv] + simpa [extendScope, hv] using he + +/-- The grouping reduction, including empty groups, empty overlaps, and empty domains. -/ +theorem sat_grouping {N t : ℕ} (F : Formula N) (ht : 0 < t) : + (groupedChoice F ht).SizeAtMost (2 ^ (3 * groupWidth F.length t)) ∧ + ((groupedChoice F ht).Successful ↔ F.Satisfiable) := + ⟨groupedChoice_size F ht, + ⟨sat_of_groupedChoice_successful F ht, groupedChoice_successful_of_sat F ht⟩⟩ + +end Complexity + +namespace Complexity + +lemma bagParameter_pos (c : Convention) (k : ℕ) (hk : 4 ≤ k) : 0 < bagParameter c k := by + cases c <;> simp only [bagParameter] <;> omega + +noncomputable def satChoice (c : Convention) (k : ℕ) (hk : 4 ≤ k) + {N : ℕ} (F : Formula N) : ChoiceSystem (bagParameter c k) := + groupedChoice F (bagParameter_pos c k hk) + +/-- The mathematical SAT-to-uncolored-graph reduction. -/ +theorem sat_parity_reduction (c : Convention) (k : ℕ) (hk : 4 ≤ k) + {N : ℕ} (F : Formula N) : + let C := satChoice c k hk F + Fintype.card (LiftVertex (template (bagParameter c k)) (baseGraph C) + (baseProjection C) (fun _ => 0)) = + Fintype.card (LiftVertex (template (bagParameter c k)) (baseGraph C) + (baseProjection C) (starParity (bagParameter c k))) ∧ + Fintype.card (LiftVertex (template (bagParameter c k)) (baseGraph C) + (baseProjection C) (fun _ => 0)) ≤ + 2 ^ (3 * groupWidth F.length (bagParameter c k)) * orderFactor (bagParameter c k) ∧ + (WLEquivalent (zeroLift C) (starLift C) c k ↔ ¬ F.Satisfiable) ∧ + (PureWLEquivalent (zeroLift C) (starLift C) c k ↔ ¬ F.Satisfiable) ∧ + (F.Satisfiable → + ¬ sameHistogram (zeroLift C) (starLift C) c k (detectionRound c) ∧ + ¬ samePureHistogram (zeroLift C) (starLift C) c k (detectionRound c)) := by + dsimp only + have hs := sat_grouping F (bagParameter_pos c k hk) + have hc : (satChoice c k hk F).Successful ↔ F.Satisfiable := hs.2 + obtain ⟨he, hb, hw, hp, hd⟩ := parity_reduction k hk c (satChoice c k hk F) + exact ⟨he, hb _ (Nat.one_le_pow _ _ (by omega)) hs.1, + hw.trans (not_congr hc), hp.trans (not_congr hc), fun h => hd (hc.mpr h)⟩ + +end Complexity + +end ParityWL + +namespace ParityWL + +namespace Complexity + +open Sparsification + +def Formula.toCNF {N : ℕ} (F : Formula N) : CNF (Literal N) := + (F.map (fun C => C.literals.toFinset)).toFinset + +lemma Formula.toCNF_width {N : ℕ} (F : Formula N) : + ∀ C ∈ F.toCNF, C.card ≤ 3 := by + intro C hC + obtain ⟨D, hD, rfl⟩ := List.mem_map.mp (List.mem_toFinset.mp hC) + exact (List.toFinset_card_le _).trans D.width + +lemma Formula.toCNF_holds {N : ℕ} (F : Formula N) (a : Fin N → Bool) : + Holds F.toCNF (fun l => a l.1 = l.2) ↔ F.Satisfied a := by + constructor + · intro h C hC + have hc := h C.literals.toFinset (List.mem_toFinset.mpr (List.mem_map.mpr ⟨C, hC, rfl⟩)) + simpa only [Clause.Satisfied, List.mem_toFinset] using hc + · intro h C hC + obtain ⟨D, hD, rfl⟩ := List.mem_map.mp (List.mem_toFinset.mp hC) + simpa only [Clause.Satisfied, List.mem_toFinset] using h D hD + +noncomputable def CNF.toFormula {N : ℕ} (F : CNF (Literal N)) + (hw : ∀ C ∈ F, C.card ≤ 3) : Formula N := + F.attach.toList.map (fun C => ⟨C.val.toList, by simpa using hw C.val C.property⟩) + +lemma CNF.toFormula_length {N : ℕ} (F : CNF (Literal N)) + (hw : ∀ C ∈ F, C.card ≤ 3) : (CNF.toFormula F hw).length = F.card := by + simp [CNF.toFormula] + +lemma CNF.toFormula_holds {N : ℕ} (F : CNF (Literal N)) + (hw : ∀ C ∈ F, C.card ≤ 3) (a : Fin N → Bool) : + (CNF.toFormula F hw).Satisfied a ↔ Holds F (fun l => a l.1 = l.2) := by + constructor + · intro h C hC + have hm : (⟨C.toList, by simpa using hw C hC⟩ : Clause N) ∈ CNF.toFormula F hw := by + exact List.mem_map.mpr ⟨⟨C, hC⟩, by simp, rfl⟩ + simpa only [Clause.Satisfied, Finset.mem_toList] using h _ hm + · intro h C hC + obtain ⟨D, hD, rfl⟩ := List.mem_map.mp hC + simpa only [Clause.Satisfied, Finset.mem_toList] using h D.val D.property + +/-- The combinatorial IPZ producer at computably chosen thresholds 12j. -/ +theorem sat_sparsification {N : ℕ} (F : Formula N) (j : ℕ) (hj : 0 < j) : + ∃ L : List (Formula N), + (∀ H ∈ L, H.length ≤ 1 + 2 * N * (1 + (12 * j) ^ 2 + 2 * (12 * j) ^ 8)) ∧ + (∀ a : Fin N → Bool, F.Satisfied a ↔ ∃ H ∈ L, H.Satisfied a) ∧ + (L.length : ℝ) ≤ (2 : ℝ) ^ ((N : ℝ) / j) := by + classical + obtain ⟨L, hL, hv, hc⟩ := indexed_sparsification N (by simp [Literal, Nat.mul_comm]) + F.toCNF F.toCNF_width j hj + let T : List (Formula N) := L.attach.map (fun H => + CNF.toFormula H.val (hL H.val H.property).2.1) + refine ⟨T, ?_, ?_, ?_⟩ + · intro H hH + obtain ⟨D, hD, rfl⟩ := List.mem_map.mp hH + rw [CNF.toFormula_length] + exact (hL D.val D.property).2.2 + · intro a + rw [← F.toCNF_holds a, hv (fun l => a l.1 = l.2)] + constructor + · rintro ⟨H, hH, hHa⟩ + refine ⟨CNF.toFormula H (hL H hH).2.1, ?_, ?_⟩ + · exact List.mem_map.mpr ⟨⟨H, hH⟩, by simp, rfl⟩ + · exact (CNF.toFormula_holds _ _ a).mpr hHa + · rintro ⟨H, hH, hHa⟩ + obtain ⟨D, hD, rfl⟩ := List.mem_map.mp hH + exact ⟨D.val, D.property, (CNF.toFormula_holds _ _ a).mp hHa⟩ + · simpa [T] using hc + +lemma sat_sparsification_or {N : ℕ} (F : Formula N) (L : List (Formula N)) + (hv : ∀ a : Fin N → Bool, F.Satisfied a ↔ ∃ H ∈ L, H.Satisfied a) : + F.Satisfiable ↔ ∃ H ∈ L, H.Satisfiable := by + constructor + · rintro ⟨a, ha⟩ + obtain ⟨H, hH, hHa⟩ := (hv a).mp ha + exact ⟨H, hH, a, hHa⟩ + · rintro ⟨H, hH, a, ha⟩ + exact ⟨a, (hv a).mpr ⟨H, hH, ha⟩⟩ + +end Complexity + +end ParityWL + +end OAI diff --git a/lean/OAI/Combinatorics/ParityLifts/SATRates.lean b/lean/OAI/Combinatorics/ParityLifts/SATRates.lean new file mode 100644 index 0000000000000000000000000000000000000000..ea66d33a3e867af6edb670e1cbfbf38e54bedaf0 --- /dev/null +++ b/lean/OAI/Combinatorics/ParityLifts/SATRates.lean @@ -0,0 +1,107 @@ +import OAI.Combinatorics.ParityLifts.SparsePost + +namespace OAI + +namespace ParityWL.Complexity + +noncomputable def normalizeProgram : PolyProgram (List Bool) BitFormula + (fun bs => minimizeList (parseFormula bs)) := + PolyProgram.parseFormula.comp (PolyProgram.minimizeList BitLiteral) + +noncomputable def satCode (p : FCode) : FCode := .seq normalizeProgram.program.code p + +lemma normalize_run {N : ℕ} (F : Formula N) : + BEval normalizeProgram.program.code (treeEncode (encodeFormula F)) + (normalizeProgram.program.time (encodeFormula F)) (treeEncode (minimizeList F.bitList)) := by + rw [Formula.bitList_parse] + exact normalizeProgram.program.run (encodeFormula F) + +lemma poly_bit_input_bound {α : Type} [TreeCodec α] {f : List Bool → α} + (P : PolyProgram (List Bool) α f) : + ∃ A : ℝ, 0 + C*(L+1 : ℝ)^(2*normalizeProgram.degree+2)*2^((2*r+ε)*N)) := by + intro ε hε + obtain ⟨A,hA,hpre⟩ := poly_bit_input_bound normalizeProgram + obtain ⟨B,hB,hpost⟩ := hR.absorb (ε/2) (by positivity) + let D : ℝ := 500*((satCode p).factor+2 : ℝ)*((satCode p).depth+2 : ℝ) + let C := D*(A+B+2)^2+64 + refine ⟨C,by dsimp [C,D]; positivity,?_⟩ + intro N F + obtain ⟨b,hb,he⟩ := hp F + have hrun := (normalize_run F).real.seq hb + obtain ⟨s,hs,hcost⟩ := hrun.decision + refine ⟨s,b,hs,he,?_⟩ + have hcost' : (s : ℝ) ≤ D*((normalizeProgram.program.time (encodeFormula F) : ℝ)+R N+2)^2+ + 44*(encodeFormula F).length+20 := by + convert hcost using 1 + dsimp only [D,satCode] + ring + have hh := decision_numeric_bound D A B (r+ε/2) normalizeProgram.degree + (encodeFormula F).length N (normalizeProgram.program.time (encodeFormula F)) (R N) s + (by dsimp [D]; positivity) hA.le hB.le (by positivity) (Nat.cast_nonneg _) (hR.1 N) + (hpre (encodeFormula F)) (hpost N) hcost' + rw [show 2*(r+ε/2)=2*r+ε by ring] at hh + exact hh + +end ParityWL.Complexity + +end OAI diff --git a/lean/OAI/Combinatorics/ParityLifts/SetLists.lean b/lean/OAI/Combinatorics/ParityLifts/SetLists.lean new file mode 100644 index 0000000000000000000000000000000000000000..9fcddd2ad9dc6417b44b0ce0c5d09ceefb4ae53c --- /dev/null +++ b/lean/OAI/Combinatorics/ParityLifts/SetLists.lean @@ -0,0 +1,168 @@ +import OAI.Combinatorics.ParityLifts.LeafMachine + +namespace OAI + +namespace ParityWL.Complexity + +noncomputable def dedupBy {α β : Type} [DecidableEq β] (f : α → β) (xs : List α) : List α := + xs.foldl (fun acc a => if f a∈acc.map f then acc else a::acc) [] + +lemma fold_dedupBy_set {α β : Type} [DecidableEq β] (f : α → β) (xs acc : List α) : + ((xs.foldl (fun s a => if f a∈s.map f then s else a::s) acc).map f).toFinset = + (xs.map f).toFinset ∪ (acc.map f).toFinset := by + induction xs generalizing acc with + | nil => simp + | cons a xs ih => + rw [List.foldl_cons,ih] + by_cases h : f a∈acc.map f + · simp [h,Finset.insert_union,Finset.insert_eq_of_mem (Finset.mem_union_right _ (List.mem_toFinset.mpr h))] + · simp [h,Finset.union_insert,Finset.insert_union] + +lemma fold_dedupBy_nodup {α β : Type} [DecidableEq β] (f : α → β) (xs acc : List α) + (ha : (acc.map f).Nodup) : + ((xs.foldl (fun s a => if f a∈s.map f then s else a::s) acc).map f).Nodup := by + induction xs generalizing acc with + | nil => exact ha + | cons a xs ih => + rw [List.foldl_cons] + apply ih + split + · exact ha + · rename_i h + simpa using (show ¬f a∈acc.map f ∧ (acc.map f).Nodup from ⟨h,ha⟩) + +@[simp] lemma dedupBy_set {α β : Type} [DecidableEq β] (f : α → β) (xs : List α) : + ((dedupBy f xs).map f).toFinset = (xs.map f).toFinset := by + rw [dedupBy,fold_dedupBy_set] + simp only [List.map_nil,List.toFinset_nil,Finset.union_empty] + +lemma dedupBy_nodup {α β : Type} [DecidableEq β] (f : α → β) (xs : List α) : + ((dedupBy f xs).map f).Nodup := fold_dedupBy_nodup f xs [] (by simp) + +lemma fold_dedupBy_subset {α β : Type} [DecidableEq β] (f : α → β) (xs acc : List α) : + xs.foldl (fun s a => if f a∈s.map f then s else a::s) acc ⊆ xs++acc := by + induction xs generalizing acc with + | nil => simp + | cons a xs ih => + rw [List.foldl_cons] + apply List.Subset.trans (ih _) + intro b hb + split at hb <;> simp only [List.mem_append,List.mem_cons] at * <;> tauto + +lemma dedupBy_subset {α β : Type} [DecidableEq β] (f : α → β) (xs : List α) : + dedupBy f xs ⊆ xs := by simpa [dedupBy] using fold_dedupBy_subset f xs [] + +noncomputable def PolyProgram.dedupBy {α β : Type} [TreeCodec α] [DecidableEq β] + (f : α → β) (P : PolyProgram (α × α) Bool (fun x => decide (f x.1=f x.2))) : + PolyProgram (List α) (List α) (Complexity.dedupBy f) := by + let sw : PolyProgram (α × List α) (List α × α) (fun x => (x.2,x.1)) := + .expr (.pair TExpr.input.right TExpr.input.left) (by intro x; rfl) + let test := sw.comp (P.mapWith.comp (PolyProgram.id Bool).any) + let test' : PolyProgram (α × List α) Bool (fun x => decide (f x.1∈x.2.map f)) := test.congr (by + intro x + apply Bool.eq_iff_iff.mpr + simp only [Function.comp_def,id_eq,List.any_map,List.any_eq_true,decide_eq_true_eq,List.mem_map] + ) + let Q := test'.ite (PolyProgram.snd α (List α)) (PolyProgram.cons α) + have hg (a : α) (acc : List α) : + (treeEncode (if decide (f a∈acc.map f) then acc else a::acc)).size ≤ + (treeEncode acc).size+1*((treeEncode a).size+1)^1 := by + split <;> simp [DataTree.size] + all_goals omega + let F := Q.foldlGrowing 1 1 hg + exact (((PolyProgram.id (List α)).pair (PolyProgram.const ([]:List α))).comp F).congr + (by intro xs; simp only [decide_eq_true_eq]; rfl) + +abbrev ClauseList (α : Type) := List (List α) + +def listCNF {α : Type} [DecidableEq α] (F : ClauseList α) : Sparsification.CNF α := + (F.map List.toFinset).toFinset + +@[simp] lemma mem_listCNF {α : Type} [DecidableEq α] {F : ClauseList α} {C : Finset α} : + C∈listCNF F ↔ ∃ D∈F, D.toFinset=C := by simp [listCNF] + +lemma listCNF_holds {α : Type} [DecidableEq α] (F : ClauseList α) (v : α → Prop) : + Sparsification.Holds (listCNF F) v ↔ ∀ C∈F, ∃ a∈C, v a := by + simp only [Sparsification.Holds,mem_listCNF,forall_exists_index,and_imp] + constructor + · intro h C hC; simpa using h C.toFinset C hC rfl + · intro h C D hD he; rw [← he]; simpa using h D hD + +noncomputable def compactCNF {α : Type} [DecidableEq α] (F : ClauseList α) : ClauseList α := + dedupBy List.toFinset F + +@[simp] lemma listCNF_compact {α : Type} [DecidableEq α] (F : ClauseList α) : + listCNF (compactCNF F) = listCNF F := by simp [listCNF,compactCNF] + +lemma compactCNF_length {α : Type} [DecidableEq α] (F : ClauseList α) : + (compactCNF F).length=(listCNF F).card := by + have h := List.toFinset_card_of_nodup (dedupBy_nodup List.toFinset F) + simpa only [List.length_map,dedupBy_set,compactCNF,listCNF] using h.symm + +noncomputable def PolyProgram.clauseEqual (α : Type) [TreeCodec α] [DecidableEq α] : + PolyProgram (List α × List α) Bool (fun x => decide (x.1.toFinset=x.2.toFinset)) := by + let sw : PolyProgram (List α × List α) (List α × List α) (fun x => (x.2,x.1)) := + .expr (.pair TExpr.input.right TExpr.input.left) (by intro x; rfl) + refine (((PolyProgram.subset α).pair (sw.comp (PolyProgram.subset α))).comp PolyProgram.and).congr ?_ + intro x + apply Bool.eq_iff_iff.mpr + simp only [Function.comp_def,Bool.and_eq_true,decide_eq_true_eq] + exact ⟨fun h => Finset.Subset.antisymm (by simpa only [Finset.subset_iff,List.mem_toFinset] using h.1) (by simpa only [Finset.subset_iff,List.mem_toFinset] using h.2), + fun h => ⟨by simpa only [Finset.subset_iff,List.mem_toFinset] using h.subset,by simpa only [Finset.subset_iff,List.mem_toFinset] using h.symm.subset⟩⟩ + +noncomputable def PolyProgram.compactCNF (α : Type) [TreeCodec α] [DecidableEq α] : + PolyProgram (ClauseList α) (ClauseList α) Complexity.compactCNF := + PolyProgram.dedupBy List.toFinset (PolyProgram.clauseEqual α) + +noncomputable def minimizeList {α : Type} [DecidableEq α] (F : ClauseList α) : ClauseList α := + (compactCNF F).filter (fun C => F.all (fun D => + !decide (D.toFinset⊆C.toFinset) || decide (C.toFinset⊆D.toFinset))) + +lemma listCNF_minimize {α : Type} [DecidableEq α] (F : ClauseList α) : + listCNF (minimizeList F)=Sparsification.minimize (listCNF F) := by + ext C + simp only [mem_listCNF,Sparsification.minimize,Finset.mem_filter,List.mem_filter,minimizeList, + List.all_eq_true,Bool.or_eq_true,Bool.not_eq_true',decide_eq_false_iff_not,decide_eq_true_eq] + constructor + · rintro ⟨D,⟨hD,h⟩,rfl⟩ + have hm : D.toFinset∈listCNF F := by rw [← listCNF_compact F]; exact mem_listCNF.mpr ⟨D,hD,rfl⟩ + refine ⟨mem_listCNF.mp hm,?_⟩ + rintro E ⟨A,hA,rfl⟩ hAD + exact (h A hA).resolve_left (not_not.mpr hAD) + · rintro ⟨hC,h⟩ + have hc : C∈listCNF (compactCNF F) := by rw [listCNF_compact]; exact mem_listCNF.mpr hC + obtain ⟨D,hD,rfl⟩ := mem_listCNF.mp hc + refine ⟨D,⟨hD,?_⟩,rfl⟩ + intro A hA + exact or_iff_not_imp_left.mpr (fun hAD => h A.toFinset ⟨A,hA,rfl⟩ (not_not.mp hAD)) + +noncomputable def pruneList {α : Type} [DecidableEq α] (F A : ClauseList α) : ClauseList α := + compactCNF (F.filter (fun C => !(A.any (fun D => decide (D.toFinset⊆C.toFinset)))) ++ A) + +lemma listCNF_prune {α : Type} [DecidableEq α] (F A : ClauseList α) : + listCNF (pruneList F A)=Sparsification.prune (listCNF F) (listCNF A) := by + rw [pruneList,listCNF_compact] + have ha (C : List α) : (!(A.any (fun D => decide (D.toFinset⊆C.toFinset))))=true ↔ + ¬∃ D∈A, D.toFinset⊆C.toFinset := by + rw [Bool.not_eq_true',Bool.eq_false_iff] + simp only [ne_eq,List.any_eq_true,decide_eq_true_eq] + ext C + simp only [mem_listCNF,Sparsification.prune,Finset.mem_union,Finset.mem_filter,List.mem_append, + List.mem_filter,ha] + constructor + · rintro ⟨D,hD,rfl⟩ + rcases hD with ⟨hD,he⟩ | hD + · left + refine ⟨⟨D,hD,rfl⟩,?_⟩ + rintro ⟨E,⟨B,hB,rfl⟩,hBD⟩ + exact he ⟨B,hB,hBD⟩ + · exact Or.inr ⟨D,hD,rfl⟩ + · rintro (⟨⟨D,hD,rfl⟩,he⟩ | ⟨D,hD,rfl⟩) + · refine ⟨D,Or.inl ⟨hD,?_⟩,rfl⟩ + rintro ⟨B,hB,hBD⟩ + exact he ⟨B.toFinset,⟨B,hB,rfl⟩,hBD⟩ + · exact ⟨D,Or.inr hD,rfl⟩ + +end ParityWL.Complexity + +end OAI diff --git a/lean/OAI/Combinatorics/ParityLifts/SetPrograms.lean b/lean/OAI/Combinatorics/ParityLifts/SetPrograms.lean new file mode 100644 index 0000000000000000000000000000000000000000..51923728dd9c5b1110ea2517c10c0d7943d597bc --- /dev/null +++ b/lean/OAI/Combinatorics/ParityLifts/SetPrograms.lean @@ -0,0 +1,115 @@ +import OAI.Combinatorics.ParityLifts.SetLists + +namespace OAI + +namespace ParityWL.Complexity + +noncomputable def PolyProgram.clauseSubset (α : Type) [TreeCodec α] [DecidableEq α] : + PolyProgram (List α × List α) Bool (fun x => decide (x.1.toFinset⊆x.2.toFinset)) := + (PolyProgram.subset α).congr (by + intro x + apply Bool.eq_iff_iff.mpr + simp only [decide_eq_true_eq,Finset.subset_iff,List.mem_toFinset]) + +noncomputable def PolyProgram.minimalClause (α : Type) [TreeCodec α] [DecidableEq α] : + PolyProgram (List α × ClauseList α) Bool + (fun x => x.2.all (fun D => !decide (D.toFinset⊆x.1.toFinset) || decide (x.1.toFinset⊆D.toFinset))) := by + let sw : PolyProgram (List α × List α) (List α × List α) (fun x => (x.2,x.1)) := + .expr (.pair TExpr.input.right TExpr.input.left) (by intro x; rfl) + let P := (((PolyProgram.clauseSubset α).comp PolyProgram.not).pair + (sw.comp (PolyProgram.clauseSubset α))).comp PolyProgram.or + let sw' : PolyProgram (List α × ClauseList α) (ClauseList α × List α) (fun x => (x.2,x.1)) := + .expr (.pair TExpr.input.right TExpr.input.left) (by intro x; rfl) + exact (sw'.comp (P.mapWith.comp (PolyProgram.id Bool).all)).congr + (by intro x; simp only [Function.comp_def,List.all_map,id_eq]) + +noncomputable def PolyProgram.minimizeList (α : Type) [TreeCodec α] [DecidableEq α] : + PolyProgram (ClauseList α) (ClauseList α) Complexity.minimizeList := + (((PolyProgram.compactCNF α).pair (PolyProgram.id (ClauseList α))).comp + (PolyProgram.minimalClause α).filterWith).congr (by intro F; rfl) + +noncomputable def PolyProgram.keepClause (α : Type) [TreeCodec α] [DecidableEq α] : + PolyProgram (List α × ClauseList α) Bool + (fun x => !(x.2.any (fun D => decide (D.toFinset⊆x.1.toFinset)))) := by + let sw : PolyProgram (List α × ClauseList α) (ClauseList α × List α) (fun x => (x.2,x.1)) := + .expr (.pair TExpr.input.right TExpr.input.left) (by intro x; rfl) + exact ((sw.comp ((PolyProgram.clauseSubset α).mapWith.comp (PolyProgram.id Bool).any)).comp + PolyProgram.not).congr (by intro x; simp only [Function.comp_def,List.any_map,id_eq]) + +noncomputable def PolyProgram.pruneList (α : Type) [TreeCodec α] [DecidableEq α] : + PolyProgram (ClauseList α × ClauseList α) (ClauseList α) (fun x => Complexity.pruneList x.1 x.2) := by + let P := (PolyProgram.keepClause α).filterWith + exact (((P.pair (PolyProgram.snd (ClauseList α) (ClauseList α))).comp (PolyProgram.append (List α))).comp + (PolyProgram.compactCNF α)).congr (by intro x; rfl) + +def allTuples {α : Type} : ℕ → List α → List (List α) + | 0, _ => [[]] + | n+1, xs => xs.flatMap (fun a => (allTuples n xs).map (a::·)) + +lemma mem_allTuples {α : Type} (n : ℕ) (xs bs : List α) : + bs∈allTuples n xs ↔ bs.length=n ∧ bs⊆xs := by + induction n generalizing bs with + | zero => simp only [allTuples,List.mem_singleton,List.length_eq_zero_iff] + exact ⟨fun h => ⟨h,by simp [h]⟩,fun h => h.1⟩ + | succ n ih => + cases bs with + | nil => simp [allTuples] + | cons a bs => + simp only [allTuples,List.mem_flatMap,List.mem_map,List.cons.injEq] + constructor + · rintro ⟨b,hb,cs,hcs,rfl,rfl⟩ + obtain ⟨hn,hs⟩ := (ih cs).mp hcs + exact ⟨by simp [hn],by simpa using (show b∈xs ∧ cs⊆xs from ⟨hb,hs⟩)⟩ + · rintro ⟨hn,hs⟩ + have hmem : a∈xs := hs (by simp) + have hsub : bs⊆xs := fun b hb => hs (by simp [hb]) + exact ⟨a,hmem,bs,(ih bs).mpr ⟨by simpa using hn,hsub⟩,rfl,rfl⟩ + +lemma allTuples_length {α : Type} (n : ℕ) (xs : List α) : + (allTuples n xs).length=xs.length^n := by + induction n with + | zero => simp [allTuples] + | succ n ih => + simp only [allTuples,List.length_flatMap,List.length_map,ih,pow_succ] + rw [List.map_const',List.sum_replicate] + change xs.length * xs.length ^ n = xs.length ^ n * xs.length + exact Nat.mul_comm .. + +def PolyProgram.prependAll (α : Type) [TreeCodec α] : + PolyProgram (α × List (List α)) (List (List α)) (fun x => x.2.map (x.1::·)) := by + let sw : PolyProgram (List α × α) (α × List α) (fun x => (x.2,x.1)) := + .expr (.pair TExpr.input.right TExpr.input.left) (by intro x; rfl) + let sw' : PolyProgram (α × List (List α)) (List (List α) × α) (fun x => (x.2,x.1)) := + .expr (.pair TExpr.input.right TExpr.input.left) (by intro x; rfl) + exact sw'.comp (sw.comp (PolyProgram.cons α)).mapWith + +def PolyProgram.allTuples (α : Type) [TreeCodec α] : + (n : ℕ) → PolyProgram (List α) (List (List α)) (Complexity.allTuples n) + | 0 => PolyProgram.const [[]] + | n+1 => (((PolyProgram.id (List α)).pair (PolyProgram.allTuples α n)).comp + (PolyProgram.prependAll α).mapWith |>.comp (PolyProgram.flatten (List α))).congr + (by intro xs; simp only [Complexity.allTuples,Function.comp_def,List.flatMap_def,id_eq]) + +noncomputable def clauseDiff {α : Type} [DecidableEq α] (C D : List α) : List α := + C.filter (fun a => decide (a∉D)) + +@[simp] lemma clauseDiff_set {α : Type} [DecidableEq α] (C D : List α) : + (clauseDiff C D).toFinset=C.toFinset\D.toFinset := by + ext a + simp [clauseDiff] + +noncomputable def PolyProgram.clauseDiff (α : Type) [TreeCodec α] [DecidableEq α] : + PolyProgram (List α × List α) (List α) (fun x => Complexity.clauseDiff x.1 x.2) := + ((PolyProgram.mem α).comp PolyProgram.not).filterWith.congr (by intro x; simp [Complexity.clauseDiff]) + +noncomputable def PolyProgram.clauseDisjoint (α : Type) [TreeCodec α] [DecidableEq α] : + PolyProgram (List α × List α) Bool (fun x => decide (Disjoint x.1.toFinset x.2.toFinset)) := by + refine (((PolyProgram.mem α).mapWith.comp (PolyProgram.id Bool).any).comp PolyProgram.not).congr ?_ + intro x + apply Bool.eq_iff_iff.mpr + simp only [Function.comp_def,id_eq,List.any_map,Bool.not_eq_true',Bool.eq_false_iff,ne_eq,List.any_eq_true,decide_eq_true_eq] + simp only [Finset.disjoint_left,List.mem_toFinset,not_exists,not_and] + +end ParityWL.Complexity + +end OAI diff --git a/lean/OAI/Combinatorics/ParityLifts/Simulation.lean b/lean/OAI/Combinatorics/ParityLifts/Simulation.lean new file mode 100644 index 0000000000000000000000000000000000000000..b12f71da9b3cf3328502629307b455c777e4e88e --- /dev/null +++ b/lean/OAI/Combinatorics/ParityLifts/Simulation.lean @@ -0,0 +1,327 @@ +import OAI.Combinatorics.ParityLifts.Simulator + +namespace OAI + +namespace ParityWL.Complexity + +lemma BEval.loop_completes (p : FCode) (f : DataTree → DataTree) (x : DataTree) + (n B S : ℕ) + (hb : ∀ j, j < n → BEval p (f^[j] x) B (f^[j + 1] x)) + (hs : ∀ j, j ≤ n → (f^[j] x).size ≤ S) + (hf : ∀ y, y.child false = .nil → f y = y) + (he : (f^[n] x).child false = .nil) : + BEval (.loop p) x ((n + 1) * (B + S + 1)) (f^[n] x) := by + induction n generalizing x with + | zero => + simpa using (BEval.loop_stop p x (by simpa using he)).mono + (show x.size ≤ (0 + 1) * (B + S + 1) from by + have hx : x.size ≤ S := by simpa using hs 0 (by omega) + omega) + | succ n ih => + by_cases hx : x.child false = .nil + · rw [Function.iterate_fixed (hf x hx)] + exact (BEval.loop_stop p x hx).mono (by + have h := hs 0 (by omega) + simp only [Function.iterate_zero, id_eq] at h + nlinarith) + · have ht := ih (f x) + (fun j hj => by simpa [Function.iterate_succ_apply] using hb (j + 1) (by omega)) + (fun j hj => by simpa [Function.iterate_succ_apply] using hs (j + 1) (by omega)) + (by simpa [Function.iterate_succ_apply] using he) + have h₀ : BEval p x B (f x) := by simpa using hb 0 (by omega) + have h := BEval.loop_next hx h₀ ht + simpa [Function.iterate_succ_apply] using h.mono + (show B + (n + 1) * (B + S + 1) + 1 ≤ (n + 1 + 1) * (B + S + 1) by nlinarith) + +def smallControl (M : Machine) (x : SmallConfiguration M) : Bool × SmallConfiguration M := + ((M.output x.1).isNone, x) + +def simStepExpr (M : Machine) : TExpr := + .cond TExpr.input.left .input + (.pair (TExpr.smallContinue M (TExpr.smallStep M TExpr.input.right)) + (TExpr.smallStep M TExpr.input.right)) + +def simStartExpr (M : Machine) : TExpr := .pair (TExpr.smallContinue M .input) .input + +def simAnswerExpr (M : Machine) : TExpr := TExpr.smallAnswer M TExpr.input.right + +lemma simStartExpr_eval (M : Machine) (x : SmallConfiguration M) : + (simStartExpr M).eval (treeEncode x) = treeEncode (smallControl M x) := by + simp only [simStartExpr, TExpr.eval, TExpr.smallContinue_eval M .input _ x rfl] + rfl + +lemma simStepExpr_fixed (M : Machine) (x : DataTree) (h : x.child false = .nil) : + (simStepExpr M).eval x = x := by simp [simStepExpr, TExpr.eval, h] + +lemma simStepExpr_eval (M : Machine) (x : SmallConfiguration M) : + (simStepExpr M).eval (treeEncode (smallControl M x)) = + treeEncode (smallControl M (smallStep M x)) := by + have hr : TExpr.input.right.eval (treeEncode (smallControl M x)) = treeEncode x := rfl + have hn := TExpr.smallStep_eval M TExpr.input.right _ x hr + have hc := TExpr.smallContinue_eval M (TExpr.smallStep M TExpr.input.right) _ (smallStep M x) hn + cases ho : M.output x.1 with + | some b => + simp [simStepExpr, TExpr.eval, smallControl, ho, smallStep, treeEncode_prod, DataTree.child] + | none => + change (if (treeEncode (smallControl M x)).child false = .nil then _ else _) = _ + have hg : (treeEncode (smallControl M x)).child false ≠ .nil := by + simp [smallControl, ho, DataTree.child] + rw [ite_eq_right hg] + change DataTree.node _ _ = _ + rw [hn, hc] + rfl + +lemma simStepExpr_iterate (M : Machine) (x : SmallConfiguration M) (n : ℕ) : + ((simStepExpr M).eval)^[n] (treeEncode (smallControl M x)) = + treeEncode (smallControl M ((smallStep M)^[n] x)) := by + induction n with + | zero => rfl + | succ n ih => rw [Function.iterate_succ_apply', ih, simStepExpr_eval, Function.iterate_succ_apply'] + +lemma smallControl_size (M : Machine) (x : SmallConfiguration M) : + (treeEncode (smallControl M x)).size ≤ (treeEncode x).size + 4 := by + simp only [smallControl, treeEncode_pair, DataTree.size] + cases (M.output x.1).isNone <;> simp [DataTree.size] <;> omega + +lemma simLoop_run {M : Machine} {xs : List Bool} {s : ℕ} {b : Bool} + (h : Emits M xs s b) : + let C := 2 * M.extraStates + (M.tapes + 1) * (4 * M.extraSymbols + 16) + 4 + BEval (.loop (simStepExpr M).compile) (treeEncode (smallControl M (smallInitial M xs))) + (((simStepExpr M).cost + 2) * (C + 5) * (xs.length + s + 1)^2) + (treeEncode (smallControl M ((smallStep M)^[s] (smallInitial M xs)))) := by + dsimp only + let C := 2 * M.extraStates + (M.tapes + 1) * (4 * M.extraSymbols + 16) + 4 + let X := xs.length + s + 1 + let S := (C+4)*X + have hs (j : ℕ) (hj : j ≤ s) : + (((simStepExpr M).eval)^[j] (treeEncode (smallControl M (smallInitial M xs)))).size ≤ S := by + rw [simStepExpr_iterate] + have hsz := smallControl_size M ((smallStep M)^[j] (smallInitial M xs)) + have ht := smallRun_size M xs j + change _ ≤ C * (xs.length+j+1) at ht + have hm : C * (xs.length+j+1) ≤ C*X := Nat.mul_le_mul_left C (by dsimp [X]; omega) + dsimp only [S] + have hx : 1 ≤ X := by dsimp [X]; omega + nlinarith + have hr := BEval.loop_completes (simStepExpr M).compile (simStepExpr M).eval + (treeEncode (smallControl M (smallInitial M xs))) s ((simStepExpr M).cost*(S+1)) S + (fun j hj => by + rw [Function.iterate_succ_apply'] + exact ((simStepExpr M).run _).mono (Nat.mul_le_mul_left _ (by have := hs j (by omega); omega))) + hs (simStepExpr_fixed M) (by + rw [simStepExpr_iterate] + simp [smallControl, smallRun_output h, DataTree.child]) + rw [simStepExpr_iterate] at hr + apply hr.mono + change (s+1)*((simStepExpr M).cost*(S+1)+S+1) ≤ + ((simStepExpr M).cost+2)*(C+5)*X^2 + have hx : 1 ≤ X := by dsimp [X]; omega + have hn : s+1 ≤ X := by dsimp [X]; omega + have hb : (simStepExpr M).cost*(S+1)+S+1 ≤ ((simStepExpr M).cost+2)*(C+5)*X := by + dsimp [S] + nlinarith + calc + _ ≤ X * (((simStepExpr M).cost+2)*(C+5)*X) := Nat.mul_le_mul hn hb + _ = _ := by ring + +def smallInitialExpr (M : Machine) : TExpr := + .pair (.const (treeEncode M.initial)) (.tuple (M.tapes+1) + (fun i => .pair .nil (if i.val = 0 then .input else .nil))) + +def smallBitProgram (M : Machine) : PolyProgram Bool (Fin (M.extraSymbols+3)) (inputSymbol M) := + .expr (.cond .input (.const (numTree 1)) (.const (numTree 2))) + (by intro b; cases b <;> rfl) + +def smallInitialProgram (M : Machine) : + PolyProgram (List Bool) (SmallConfiguration M) (smallInitial M) := by + let B := (smallBitProgram M).map + let E : PolyProgram (List (Fin (M.extraSymbols+3))) (SmallConfiguration M) + (fun xs => (M.initial, fun i => ([], if i.val = 0 then xs else []))) := + .expr (smallInitialExpr M) (by + intro xs + simp only [smallInitialExpr, TExpr.eval, treeEncode_pair] + congr 1 + apply TExpr.tuple_eval + intro i + by_cases hi : i.val=0 <;> simp [hi, TExpr.eval]) + exact B.comp E + +lemma PolyProgram.congr_degree {α β : Type} [TreeCodec α] [TreeCodec β] + {f g : α → β} (P : PolyProgram α β f) (h : ∀ x, f x = g x) : + (P.congr h).degree = P.degree := by + have he : f = g := funext h + subst g + rfl + +lemma PolyProgram.reverse_degree (α : Type) [TreeCodec α] : + (PolyProgram.reverse α).degree = 12 := by + simp only [PolyProgram.reverse, PolyProgram.congr_degree, PolyProgram.comp, + PolyProgram.pair, PolyProgram.id, PolyProgram.const, PolyProgram.foldlGrowing, + PolyProgram.cons, PolyProgram.expr, PolyProgram.of_linear] + +lemma PolyProgram.map_degree {α β : Type} [TreeCodec α] [TreeCodec β] + {f : α → β} (P : PolyProgram α β f) : + P.map.degree = 13 * (4 * P.degree^2 + 18 * P.degree + 24) := by + simp only [PolyProgram.map, PolyProgram.congr_degree, PolyProgram.comp, + PolyProgram.pair, PolyProgram.id, PolyProgram.const, PolyProgram.foldlGrowing, + PolyProgram.cons, PolyProgram.expr, PolyProgram.of_linear, + PolyProgram.fst, PolyProgram.snd, PolyProgram.reverse_degree] + ring + +def smallInitialDegree : ℕ := 1196 + +lemma smallInitialProgram_degree (M : Machine) : + (smallInitialProgram M).degree = smallInitialDegree := by + simp only [smallInitialProgram, PolyProgram.comp, PolyProgram.map_degree, smallBitProgram, + PolyProgram.expr, PolyProgram.of_linear, smallInitialDegree] + norm_num + +end ParityWL.Complexity + +namespace ParityWL.Complexity + +lemma treeEncode_bits_size (bs : List Bool) : (treeEncode bs).size ≤ 4 * bs.length + 1 := by + induction bs with + | nil => simp [DataTree.size] + | cons b bs ih => cases b <;> simp [DataTree.size] <;> omega + +def simulationCode (M : Machine) : FCode := + .seq (smallInitialProgram M).program.code + (.seq (simStartExpr M).compile + (.seq (.loop (simStepExpr M).compile) (simAnswerExpr M).compile)) + +def simulationDegree : ℕ := smallInitialDegree + 2 + +def simulationCoefficient (M : Machine) : ℕ := + let C := 2 * M.extraStates + (M.tapes + 1) * (4 * M.extraSymbols + 16) + 4 + (smallInitialProgram M).coefficient * 4 ^ smallInitialDegree + + (simStartExpr M).cost * (C + 1) + + ((simStepExpr M).cost + 2) * (C + 5) + + (simAnswerExpr M).cost * (C + 5) + 3 + +lemma simulation_run {M : Machine} {bs : List Bool} {s : ℕ} {b : Bool} + (h : Emits M bs s b) : + BEval (simulationCode M) (treeEncode bs) + (simulationCoefficient M * (bs.length + s + 1)^simulationDegree) (treeEncode b) := by + let C := 2 * M.extraStates + (M.tapes + 1) * (4 * M.extraSymbols + 16) + 4 + let X := bs.length + s + 1 + have hx : 1 ≤ X := by dsimp [X]; omega + have hpow (j : ℕ) (hj : j ≤ simulationDegree) : X^j ≤ X^simulationDegree := + Nat.pow_le_pow_right hx hj + have hp : 1 ≤ X^simulationDegree := Nat.one_le_pow _ _ hx + have hl : bs.length + 1 ≤ X := by dsimp [X]; omega + have hint := (smallInitialProgram M).program.run bs + have hinit : (smallInitialProgram M).program.time bs ≤ + (smallInitialProgram M).coefficient * 4^smallInitialDegree * X^simulationDegree := by + have hsz : (treeEncode bs).size+1 ≤ 4*X := by + have := treeEncode_bits_size bs + dsimp [X] + omega + calc + _ ≤ (smallInitialProgram M).coefficient * ((treeEncode bs).size+1)^smallInitialDegree := by + simpa only [smallInitialProgram_degree] using (smallInitialProgram M).bound bs + _ ≤ (smallInitialProgram M).coefficient * (4*X)^smallInitialDegree := by gcongr + _ = (smallInitialProgram M).coefficient * 4^smallInitialDegree * X^smallInitialDegree := by rw [mul_pow]; ring + _ ≤ _ := Nat.mul_le_mul_left _ (hpow _ (by dsimp [simulationDegree]; omega)) + have hs₀ : (treeEncode (smallInitial M bs)).size+1 ≤ (C+1)*X := by + have hq := smallRun_size M bs 0 + simp only [Function.iterate_zero, id_eq, Nat.add_zero] at hq + change _ ≤ C*(bs.length+1) at hq + nlinarith [Nat.mul_le_mul_left C hl] + have hs₁ : (treeEncode (smallControl M ((smallStep M)^[s] (smallInitial M bs)))).size+1 ≤ + (C+5)*X := by + have hq := smallRun_size M bs s + change _ ≤ C*X at hq + have hr := smallControl_size M ((smallStep M)^[s] (smallInitial M bs)) + nlinarith + have hstart := (simStartExpr M).run (treeEncode (smallInitial M bs)) + rw [simStartExpr_eval] at hstart + have ha := (simAnswerExpr M).run + (treeEncode (smallControl M ((smallStep M)^[s] (smallInitial M bs)))) + have hea : (simAnswerExpr M).eval + (treeEncode (smallControl M ((smallStep M)^[s] (smallInitial M bs)))) = treeEncode b := by + rw [simAnswerExpr, TExpr.smallAnswer_eval M TExpr.input.right _ _ rfl] + change boolTree ((M.output ((smallStep M)^[s] (smallInitial M bs)).1).getD false) = _ + rw [smallRun_output h] + rfl + rw [hea] at ha + have hr := hint.seq (hstart.seq ((simLoop_run h).seq ha)) + change BEval (simulationCode M) _ _ _ at hr + apply hr.mono + have hp₁ : X ≤ X^simulationDegree := by simpa using hpow 1 (by decide) + have hp₂ := hpow 2 (by dsimp [simulationDegree]; omega) + have hb₁ := Nat.mul_le_mul_left (simStartExpr M).cost hs₀ + have hb₂ := Nat.mul_le_mul_left (simAnswerExpr M).cost hs₁ + have hstart' : (simStartExpr M).cost*((treeEncode (smallInitial M bs)).size+1) ≤ + (simStartExpr M).cost*(C+1)*X^simulationDegree := by + calc + _ ≤ (simStartExpr M).cost*(C+1)*X := by simpa [mul_assoc] using hb₁ + _ ≤ _ := Nat.mul_le_mul_left _ hp₁ + have hans : (simAnswerExpr M).cost * + ((treeEncode (smallControl M ((smallStep M)^[s] (smallInitial M bs)))).size+1) ≤ + (simAnswerExpr M).cost*(C+5)*X^simulationDegree := by + calc + _ ≤ (simAnswerExpr M).cost*(C+5)*X := by simpa [mul_assoc] using hb₂ + _ ≤ _ := Nat.mul_le_mul_left _ hp₁ + have hloop := Nat.mul_le_mul_left (((simStepExpr M).cost+2)*(C+5)) hp₂ + change _ ≤ simulationCoefficient M * X^simulationDegree + change (smallInitialProgram M).program.time bs + + ((simStartExpr M).cost*((treeEncode (smallInitial M bs)).size+1) + + (((simStepExpr M).cost+2)*(C+5)*X^2 + + (simAnswerExpr M).cost*((treeEncode (smallControl M ((smallStep M)^[s] (smallInitial M bs)))).size+1)+1)+1)+1 ≤ + ((smallInitialProgram M).coefficient*4^smallInitialDegree + + (simStartExpr M).cost*(C+1)+((simStepExpr M).cost+2)*(C+5)+(simAnswerExpr M).cost*(C+5)+3)*X^simulationDegree + nlinarith + +noncomputable def Machine.preprocess (M : Machine) (p : FCode) : Machine := (FCode.seq p (simulationCode M)).decision + +def preprocessingDegree : ℕ := 2*simulationDegree + +lemma Machine.preprocess_run (M : Machine) (p : FCode) : + ∃ C : ℕ, 0 < C ∧ ∀ (xs ys : List Bool) (B s : ℕ) (b : Bool), + BEval p (treeEncode xs) B (treeEncode ys) → Emits M ys s b → + ∃ r, Emits (M.preprocess p) xs r b ∧ + r ≤ C*(B+xs.length+s+1)^preprocessingDegree := by + let d := simulationDegree + let A := simulationCoefficient M + 2 + let q := FCode.seq p (simulationCode M) + let K := 500*(q.factor+2)*(q.depth+2) + refine ⟨K*(A+1)^2+65, by omega, ?_⟩ + intro xs ys B s b hp hm + have hyr : ys.length ≤ B := by + have hl := treeEncode_list_length ys + have hb := hp.bounds.2 + omega + have hs := simulation_run hm + have hr := hp.seq hs + rw [treeEncode_bits] at hr + obtain ⟨r, hb, he⟩ := hr.decision + have he' : Emits (M.preprocess p) xs r b := by + cases b <;> simpa [Machine.preprocess] using he + refine ⟨r, he', hb.trans ?_⟩ + let X := B+xs.length+s+1 + have hx : 1 ≤ X := by dsimp [X]; omega + have hp₁ : X ≤ X^d := by + simpa using Nat.pow_le_pow_right hx (show 1 ≤ d from by decide) + have hp₀ : 1 ≤ X^d := Nat.one_le_pow _ _ hx + have hB : B ≤ X^d := (show B ≤ X by dsimp [X]; omega).trans hp₁ + have hY : (ys.length+s+1)^d ≤ X^d := Nat.pow_le_pow_left (by dsimp [X]; omega) _ + have hcost : B+simulationCoefficient M*(ys.length+s+1)^d+1 ≤ A*X^d := by + dsimp [A] + nlinarith [Nat.mul_le_mul_left (simulationCoefficient M) hY] + have hcost' : B+simulationCoefficient M*(ys.length+s+1)^d+1+1 ≤ (A+1)*X^d := by nlinarith + have hsquare := Nat.pow_le_pow_left hcost' 2 + have hx₂ : X^d ≤ X^(2*d) := Nat.pow_le_pow_right hx (by omega) + have hL : xs.length ≤ X^(2*d) := (show xs.length ≤ X by dsimp [X]; omega).trans (hp₁.trans hx₂) + have h1 : 1 ≤ X^(2*d) := Nat.one_le_pow _ _ hx + have hc := Nat.mul_le_mul_left K hsquare + rw [mul_pow, ← pow_mul] at hc + have hed : d*2 = 2*d := by omega + rw [hed] at hc + change K*((B+simulationCoefficient M*(ys.length+s+1)^d+1)+1)^2+44*xs.length+20 ≤ _ + change _ ≤ (K*(A+1)^2+65)*X^(2*d) + nlinarith + +end ParityWL.Complexity + +end OAI diff --git a/lean/OAI/Combinatorics/ParityLifts/Simulator.lean b/lean/OAI/Combinatorics/ParityLifts/Simulator.lean new file mode 100644 index 0000000000000000000000000000000000000000..171f8811f413b514a5edc297740d0b0ef56f6605 --- /dev/null +++ b/lean/OAI/Combinatorics/ParityLifts/Simulator.lean @@ -0,0 +1,309 @@ +import OAI.Combinatorics.ParityLifts.DataPrograms + +namespace OAI + +namespace ParityWL.Complexity + +abbrev TapePair (a : ℕ) := List (Fin (a + 3)) × List (Fin (a + 3)) + +def listCell {a : ℕ} (xs : List (Fin (a + 3))) (n : ℕ) : Fin (a + 3) := + xs[n]?.getD 0 + +@[simp] lemma listCell_nil {a : ℕ} (n : ℕ) : listCell ([] : List (Fin (a+3))) n = 0 := by + simp [listCell] +@[simp] lemma listCell_cons_zero {a : ℕ} (c : Fin (a+3)) (xs : List (Fin (a+3))) : + listCell (c :: xs) 0 = c := rfl +@[simp] lemma listCell_cons_succ {a : ℕ} (c : Fin (a+3)) (xs : List (Fin (a+3))) (n : ℕ) : + listCell (c :: xs) (n+1) = listCell xs n := rfl +lemma listCell_tail {a : ℕ} (xs : List (Fin (a+3))) (n : ℕ) : + listCell xs.tail n = listCell xs (n+1) := by cases xs <;> simp +lemma listCell_zero {a : ℕ} (xs : List (Fin (a+3))) : + listCell xs 0 = xs.headD 0 := by cases xs <;> rfl + +def TapePair.cell {a : ℕ} (x : TapePair a) : ℤ → Fin (a+3) + | .ofNat n => listCell x.2 n + | .negSucc n => listCell x.1 n + +def TapePair.advance {a : ℕ} (x : TapePair a) (c : Fin (a+3)) : Move → TapePair a + | .stay => (x.1, c :: x.2.tail) + | .right => (c :: x.1, x.2.tail) + | .left => (x.1.tail, x.1.headD 0 :: c :: x.2.tail) + +lemma TapePair.advance_cell {a : ℕ} (x : TapePair a) (c : Fin (a+3)) (m : Move) (z : ℤ) : + (x.advance c m).cell z = if z + m.offset = 0 then c else x.cell (z + m.offset) := by + cases m with + | stay => + change (x.advance c .stay).cell z = if z + 0 = 0 then c else x.cell (z + 0) + simp only [add_zero] + cases z with + | ofNat n => + cases n with + | zero => rfl + | succ n => + rw [ite_eq_right (by simp only [Int.ofNat_eq_natCast]; omega : Int.ofNat (n+1) ≠ 0)] + exact listCell_tail x.2 n + | negSucc n => + rw [ite_eq_right (by simp only [Int.negSucc_eq]; omega : Int.negSucc n ≠ 0)] + rfl + | right => + change (x.advance c .right).cell z = if z + 1 = 0 then c else x.cell (z + 1) + cases z with + | ofNat n => + rw [show Int.ofNat n + 1 = Int.ofNat (n+1) by simp only [Int.ofNat_eq_natCast]; omega, + ite_eq_right (by simp only [Int.ofNat_eq_natCast]; omega : Int.ofNat (n+1) ≠ 0)] + exact listCell_tail x.2 n + | negSucc n => + cases n with + | zero => rfl + | succ n => + rw [show Int.negSucc (n+1) + 1 = Int.negSucc n by simp only [Int.negSucc_eq]; omega, + ite_eq_right (by simp only [Int.negSucc_eq]; omega : Int.negSucc n ≠ 0)] + rfl + | left => + change (x.advance c .left).cell z = if z + -1 = 0 then c else x.cell (z + -1) + cases z with + | ofNat n => + cases n with + | zero => + rw [ite_eq_right (by simp only [Int.ofNat_eq_natCast]; omega : Int.ofNat 0 + -1 ≠ 0)] + exact (listCell_zero x.1).symm + | succ n => + cases n with + | zero => rfl + | succ n => + rw [show Int.ofNat (n+1+1) + -1 = Int.ofNat (n+1) by simp only [Int.ofNat_eq_natCast]; omega, + ite_eq_right (by simp only [Int.ofNat_eq_natCast]; omega : Int.ofNat (n+1) ≠ 0)] + exact listCell_tail x.2 n + | negSucc n => + rw [show Int.negSucc n + -1 = Int.negSucc (n+1) by simp only [Int.negSucc_eq]; omega, + ite_eq_right (by simp only [Int.negSucc_eq]; omega : Int.negSucc (n+1) ≠ 0)] + exact listCell_tail x.1 n + +lemma TapePair.advance_length {a : ℕ} (x : TapePair a) (c : Fin (a+3)) (m : Move) : + (x.advance c m).1.length + (x.advance c m).2.length ≤ x.1.length + x.2.length + 2 := by + cases m <;> simp [advance, List.length_tail] <;> omega + +end ParityWL.Complexity + +namespace ParityWL.Complexity + +abbrev SmallConfiguration (M : Machine) := + Fin (M.extraStates + 1) × (Fin (M.tapes + 1) → TapePair M.extraSymbols) + +def smallStep (M : Machine) (x : SmallConfiguration M) : SmallConfiguration M := + match M.output x.1 with + | some _ => x + | none => + let a := M.transition x.1 (fun i => (x.2 i).2.headD 0) + (a.1, fun i => (x.2 i).advance (a.2 i).1 (a.2 i).2) + +def smallInitial (M : Machine) (xs : List Bool) : SmallConfiguration M := + (M.initial, fun i => ([], if i.val = 0 then xs.map (inputSymbol M) else [])) + +def SmallRepresents (M : Machine) (x : SmallConfiguration M) (y : Configuration M) : Prop := + y.state = x.1 ∧ ∀ i z, y.tape i z = (x.2 i).cell (z - y.head i) + +lemma smallStep_represents (M : Machine) (x : SmallConfiguration M) (y : Configuration M) + (h : SmallRepresents M x y) : SmallRepresents M (smallStep M x) (step M y) := by + have hread : (fun i => y.tape i (y.head i)) = fun i => (x.2 i).2.headD 0 := by + funext i + rw [h.2 i, sub_self] + exact listCell_zero _ + cases ho : M.output x.1 with + | some b => simpa only [smallStep, step, h.1, ho] using h + | none => + simp only [SmallRepresents, smallStep, step, h.1, ho, hread] + refine ⟨trivial, fun i z => ?_⟩ + rw [TapePair.advance_cell] + have he : z - (y.head i + ((M.transition x.1 (fun i => (x.2 i).2.headD 0)).2 i).2.offset) + + ((M.transition x.1 (fun i => (x.2 i).2.headD 0)).2 i).2.offset = z - y.head i := by ring + rw [he] + by_cases hz : z = y.head i + · simp [hz] + · simp only [↓reduceIte, sub_eq_zero, hz] + exact h.2 i z + +lemma smallInitial_represents (M : Machine) (xs : List Bool) : + SmallRepresents M (smallInitial M xs) (initialConfiguration M xs) := by + refine ⟨rfl, ?_⟩ + intro i z + simp only [initialConfiguration, smallInitial, sub_zero] + by_cases hi : i.val = 0 + · simp only [hi, true_and, ↓reduceIte] + cases z with + | ofNat n => + simp only [Int.ofNat_eq_natCast, Int.natCast_nonneg, ↓reduceIte, Int.toNat_natCast] + change (match xs[n]? with | some b => inputSymbol M b | none => 0) = + listCell (xs.map (inputSymbol M)) n + simp [listCell, List.getElem?_map] + cases xs[n]? <;> rfl + | negSucc n => + have hn : ¬ 0 ≤ Int.negSucc n := by simp [Int.negSucc_eq]; omega + simp only [hn, ↓reduceIte, TapePair.cell, listCell_nil] + · simp only [hi, false_and, ↓reduceIte] + cases z <;> simp [TapePair.cell] + +lemma smallRun_represents (M : Machine) (xs : List Bool) (s : ℕ) : + SmallRepresents M ((smallStep M)^[s] (smallInitial M xs)) (run M xs s) := by + induction s with + | zero => exact smallInitial_represents M xs + | succ s ih => + simpa only [run, Function.iterate_succ_apply'] using smallStep_represents M _ _ ih + +lemma smallRun_output {M : Machine} {xs : List Bool} {s : ℕ} {b : Bool} + (h : Emits M xs s b) : M.output ((smallStep M)^[s] (smallInitial M xs)).1 = some b := by + rw [← (smallRun_represents M xs s).1] + exact h + +lemma smallRun_tape_length (M : Machine) (xs : List Bool) (s : ℕ) (i : Fin (M.tapes + 1)) : + (((smallStep M)^[s] (smallInitial M xs)).2 i).1.length + + (((smallStep M)^[s] (smallInitial M xs)).2 i).2.length ≤ xs.length + 2 * s := by + induction s with + | zero => simp [smallInitial]; split <;> simp + | succ s ih => + rw [Function.iterate_succ_apply'] + rw [smallStep] + split + · omega + · have h := TapePair.advance_length + (((smallStep M)^[s] (smallInitial M xs)).2 i) + ((M.transition ((smallStep M)^[s] (smallInitial M xs)).1 + (fun j => (((smallStep M)^[s] (smallInitial M xs)).2 j).2.headD 0)).2 i).1 + ((M.transition ((smallStep M)^[s] (smallInitial M xs)).1 + (fun j => (((smallStep M)^[s] (smallInitial M xs)).2 j).2.headD 0)).2 i).2 + exact h.trans (by omega) + +lemma treeEncode_symbol_list_size {a : ℕ} (xs : List (Fin (a+3))) : + (treeEncode xs).size ≤ 1 + xs.length * (2 * a + 6) := by + rw [treeEncode_list_size] + have h := list_sum_map_le xs (fun x => (treeEncode x).size + 1) (2*a+6) (by + intro x _ + simp [numTree_size] + omega) + omega + +lemma smallRun_size (M : Machine) (xs : List Bool) (s : ℕ) : + (treeEncode ((smallStep M)^[s] (smallInitial M xs))).size ≤ + (2 * M.extraStates + (M.tapes + 1) * (4 * M.extraSymbols + 16) + 4) * + (xs.length + s + 1) := by + let x := (smallStep M)^[s] (smallInitial M xs) + have hstate : (treeEncode x.1).size ≤ 2 * M.extraStates + 1 := by + simp only [treeEncode_fin, numTree_size] + have := x.1.isLt + omega + have htape (i : Fin (M.tapes+1)) : + (treeEncode (x.2 i)).size + 1 ≤ (4 * M.extraSymbols + 16) * (xs.length + s + 1) := by + have h := smallRun_tape_length M xs s i + have hl := treeEncode_symbol_list_size (x.2 i).1 + have hr := treeEncode_symbol_list_size (x.2 i).2 + change (x.2 i).1.length + (x.2 i).2.length ≤ xs.length + 2*s at h + simp only [treeEncode_prod, DataTree.size] + have hm := Nat.mul_le_mul_right (2 * M.extraSymbols + 6) h + nlinarith + have hsum := Finset.sum_le_sum (fun i (_ : i ∈ (Finset.univ : Finset (Fin (M.tapes+1)))) => htape i) + simp only [Finset.sum_const, Finset.card_univ, Fintype.card_fin, smul_eq_mul] at hsum + change (treeEncode x).size ≤ _ + rw [treeEncode_prod] + simp only [DataTree.size, treeEncode_fn_size] + nlinarith + +end ParityWL.Complexity + +namespace ParityWL.Complexity + +def TExpr.caseTuple : (n m : ℕ) → (Fin n → TExpr) → + ((Fin n → Fin m) → TExpr) → TExpr → TExpr + | 0, _, _, f, _ => f Fin.elim0 + | n+1, m, es, f, d => caseFin m (es 0) + (fun a => caseTuple n m (fun i => es i.succ) (fun xs => f (Fin.cons a xs)) d) d + +lemma TExpr.caseTuple_eval {n m : ℕ} (es : Fin n → TExpr) + (f : (Fin n → Fin m) → TExpr) (d : TExpr) (x : DataTree) (v : Fin n → Fin m) + (h : ∀ i, (es i).eval x = treeEncode (v i)) : + (caseTuple n m es f d).eval x = (f v).eval x := by + induction n with + | zero => + have he : (Fin.elim0 : Fin 0 → Fin m) = v := funext (fun i => Fin.elim0 i) + simp [caseTuple, he] + | succ n ih => + rw [caseTuple, caseFin_eval (v 0) _ _ d x (h 0)] + rw [ih (fun i => es i.succ) (fun xs => f (Fin.cons (v 0) xs)) (fun i => v i.succ) + (fun i => h i.succ)] + congr 2 + exact Fin.cons_self_tail v + +def TExpr.tapeHead (e : TExpr) : TExpr := + .cond e.right (.const (treeEncode (0 : Fin 3))) e.right.left + +def TExpr.tapeAdvance {a : ℕ} (e : TExpr) (c : Fin (a+3)) : Move → TExpr + | .stay => .pair e.left (.pair (.const (treeEncode c)) e.right.right) + | .right => .pair (.pair (.const (treeEncode c)) e.left) e.right.right + | .left => .pair e.left.right + (.pair (.cond e.left .nil e.left.left) (.pair (.const (treeEncode c)) e.right.right)) + +lemma TExpr.tapeHead_eval {a : ℕ} (e : TExpr) (x : DataTree) (t : TapePair a) + (h : e.eval x = treeEncode t) : + (tapeHead e).eval x = treeEncode (t.2.headD 0) := by + rcases t with ⟨l, r⟩ + cases r <;> simp [tapeHead, eval, h, DataTree.child, numTree] + +lemma TExpr.tapeAdvance_eval {a : ℕ} (e : TExpr) (x : DataTree) (t : TapePair a) + (h : e.eval x = treeEncode t) (c : Fin (a+3)) (m : Move) : + (tapeAdvance e c m).eval x = treeEncode (t.advance c m) := by + rcases t with ⟨l, r⟩ + cases m <;> cases l <;> cases r <;> + simp [tapeAdvance, eval, h, TapePair.advance, DataTree.child, numTree] + +def TExpr.smallStep (M : Machine) (e : TExpr) : TExpr := + .caseFin (M.extraStates+1) e.left (fun q => + match M.output q with + | some _ => e + | none => .caseTuple (M.tapes+1) (M.extraSymbols+3) + (fun i => tapeHead (e.right.nth i.val)) + (fun v => + let a := M.transition q v + .pair (.const (treeEncode a.1)) + (.tuple (M.tapes+1) (fun i => tapeAdvance (e.right.nth i.val) (a.2 i).1 (a.2 i).2))) .nil) .nil + +lemma TExpr.smallStep_eval (M : Machine) (e : TExpr) (x : DataTree) + (c : SmallConfiguration M) (h : e.eval x = treeEncode c) : + (smallStep M e).eval x = treeEncode (Complexity.smallStep M c) := by + have hq : e.left.eval x = numTree c.1.val := by simp [eval, h, DataTree.child] + rw [smallStep, caseFin_eval c.1 _ _ _ x hq] + cases ho : M.output c.1 with + | some b => simpa [ho, Complexity.smallStep] using h + | none => + simp only [ho, Complexity.smallStep] + have hv (i : Fin (M.tapes+1)) : + (tapeHead (e.right.nth i.val)).eval x = treeEncode ((c.2 i).2.headD 0) := by + exact tapeHead_eval _ _ _ (nth_eval i e.right x c.2 (by simp [eval, h, DataTree.child])) + rw [caseTuple_eval _ _ _ x (fun i => (c.2 i).2.headD 0) hv] + simp only [eval, treeEncode_pair] + congr 1 + apply tuple_eval + intro i + exact tapeAdvance_eval _ _ _ (nth_eval i e.right x c.2 (by simp [eval, h, DataTree.child])) _ _ + +def TExpr.smallContinue (M : Machine) (e : TExpr) : TExpr := + .caseFin (M.extraStates+1) e.left + (fun q => .const (boolTree (M.output q).isNone)) .nil + +def TExpr.smallAnswer (M : Machine) (e : TExpr) : TExpr := + .caseFin (M.extraStates+1) e.left + (fun q => .const (boolTree ((M.output q).getD false))) .nil + +lemma TExpr.smallContinue_eval (M : Machine) (e : TExpr) (x : DataTree) + (c : SmallConfiguration M) (h : e.eval x = treeEncode c) : + (smallContinue M e).eval x = boolTree (M.output c.1).isNone := by + apply caseFin_eval c.1 e.left _ .nil x + simp [eval, h, DataTree.child] + +lemma TExpr.smallAnswer_eval (M : Machine) (e : TExpr) (x : DataTree) + (c : SmallConfiguration M) (h : e.eval x = treeEncode c) : + (smallAnswer M e).eval x = boolTree ((M.output c.1).getD false) := by + apply caseFin_eval c.1 e.left _ .nil x + simp [eval, h, DataTree.child] + +end ParityWL.Complexity + +end OAI diff --git a/lean/OAI/Combinatorics/ParityLifts/SparseBounds.lean b/lean/OAI/Combinatorics/ParityLifts/SparseBounds.lean new file mode 100644 index 0000000000000000000000000000000000000000..743ea7aa7530a6d12e2ac882e11555e232e639fd --- /dev/null +++ b/lean/OAI/Combinatorics/ParityLifts/SparseBounds.lean @@ -0,0 +1,135 @@ +import OAI.Combinatorics.ParityLifts.SparseTree + +namespace OAI + +namespace ParityWL.Complexity + +lemma cnf_card_bound {α : Type} [DecidableEq α] [Fintype α] (F : Sparsification.CNF α) + (hw : ∀ C∈F, C.card≤3) : F.card≤4*(Fintype.card α+1)^3 := by + classical + have hs : F⊆(Finset.range 4).biUnion (fun i => (Finset.univ:Finset α).powersetCard i) := by + intro C hC + apply Finset.mem_biUnion.mpr + exact ⟨C.card,Finset.mem_range.mpr (by have := hw C hC; omega), + Finset.mem_powersetCard.mpr ⟨Finset.subset_univ _,rfl⟩⟩ + calc + F.card ≤ ((Finset.range 4).biUnion (fun i => (Finset.univ:Finset α).powersetCard i)).card := Finset.card_le_card hs + _ ≤ ∑ i∈Finset.range 4, ((Finset.univ:Finset α).powersetCard i).card := Finset.card_biUnion_le + _ = ∑ i∈Finset.range 4, (Fintype.card α).choose i := by simp + _ ≤ ∑ _i∈Finset.range 4, (Fintype.card α+1)^3 := by + apply Finset.sum_le_sum + intro i hi + calc + _ ≤ Fintype.card α^i := Nat.choose_le_pow _ _ + _ ≤ (Fintype.card α+1)^i := Nat.pow_le_pow_left (by omega) _ + _ ≤ (Fintype.card α+1)^3 := Nat.pow_le_pow_right (by omega) (by have := Finset.mem_range.mp hi; omega) + _ = _ := by simp + +/-- Finite-memory invariant: stored representatives, not just their sets. -/ +def ClauseControlled {α : Type} [TreeCodec α] (S : ℕ) (C : List α) : Prop := + C.length≤3 ∧ ∀ a∈C, (treeEncode a).size≤S + +def ListControlled {α : Type} [TreeCodec α] [DecidableEq α] (S : ℕ) (F : ClauseList α) : Prop := + (F.map List.toFinset).Nodup ∧ ∀ C∈F, ClauseControlled S C + +lemma ClauseControlled.subset {α : Type} [TreeCodec α] {S : ℕ} {C D : List α} + (hC : ClauseControlled S C) (hD : D.Sublist C) : ClauseControlled S D := + ⟨hD.length_le.trans hC.1,fun a ha => hC.2 a (hD.subset ha)⟩ + +lemma ListControlled.width {α : Type} [TreeCodec α] [DecidableEq α] {S : ℕ} {F : ClauseList α} + (hF : ListControlled S F) : ∀ C∈listCNF F, C.card≤3 := by + intro C hC + obtain ⟨D,hD,rfl⟩ := mem_listCNF.mp hC + exact (List.toFinset_card_le D).trans (hF.2 D hD).1 + +lemma ListControlled.size {α : Type} [TreeCodec α] [DecidableEq α] [Fintype α] + {S : ℕ} {F : ClauseList α} (hF : ListControlled S F) : + (treeEncode F).size ≤ 1+4*(Fintype.card α+1)^3*(2+3*(S+1)) := by + have hlen : F.length=(listCNF F).card := by + simpa [listCNF] using (List.toFinset_card_of_nodup hF.1).symm + have hf := cnf_card_bound (listCNF F) hF.width + rw [treeEncode_list_size] + have hc : ∀ C∈F, (treeEncode C).size+1≤2+3*(S+1) := by + intro C hC + have hCC := hF.2 C hC + rw [treeEncode_list_size] + have hs := list_sum_map_le C (fun a => (treeEncode a).size+1) (S+1) (by + intro a ha; have := hCC.2 a ha; omega) + have hm := Nat.mul_le_mul_right (S+1) hCC.1 + omega + have hs := list_sum_map_le F (fun C => (treeEncode C).size+1) (2+3*(S+1)) hc + have hm := Nat.mul_le_mul_right (2+3*(S+1)) (show F.length≤4*(Fintype.card α+1)^3 by omega) + omega + +lemma compact_controlled {α : Type} [TreeCodec α] [DecidableEq α] (F : ClauseList α) (S : ℕ) + (hF : ∀ C∈F, ClauseControlled S C) : ListControlled S (compactCNF F) := + ⟨dedupBy_nodup List.toFinset F,fun C hC => hF C (dedupBy_subset List.toFinset F hC)⟩ + +lemma minimize_controlled {α : Type} [TreeCodec α] [DecidableEq α] (F : ClauseList α) (S : ℕ) + (hF : ∀ C∈F, ClauseControlled S C) : ListControlled S (minimizeList F) := by + have hc := compact_controlled F S hF + exact ⟨((List.filter_sublist (l:=compactCNF F)).map List.toFinset).nodup hc.1, + fun C hC => hc.2 C (List.mem_filter.mp hC).1⟩ + +lemma prune_controlled {α : Type} [TreeCodec α] [DecidableEq α] (F A : ClauseList α) (S : ℕ) + (hF : ∀ C∈F, ClauseControlled S C) (hA : ∀ C∈A, ClauseControlled S C) : + ListControlled S (pruneList F A) := by + apply compact_controlled + intro C hC + rcases List.mem_append.mp hC with hC | hC + · exact hF C (List.mem_filter.mp hC).1 + · exact hA C hC + +lemma selected_controlled {α : Type} [TreeCodec α] [DecidableEq α] + (F : ClauseList α) (S p q h : ℕ) (hp : p≤3) (hF : ∀ C∈F, ClauseControlled S C) + (hx : (flowerList F p q h).isEmpty≠true) : + ClauseControlled S (selectedFlower F p q h).1 ∧ + ∀ P∈(selectedFlower F p q h).2, ClauseControlled S P := by + have hm : selectedFlower F p q h∈flowerList F p q h := by + unfold selectedFlower + cases he : flowerList F p q h with + | nil => simp [he] at hx + | cons a as => simp + obtain ⟨C,As,hC,hCF,hAs,hAF,he⟩ := (mem_flowerCandidates F p h _).mp ((mem_flowerList F p q h _).mp hm).1 + rw [he] + refine ⟨⟨hC.trans_le hp,?_⟩,?_⟩ + · intro a ha + obtain ⟨D,hD,haD⟩ := List.mem_flatten.mp (hCF ha) + exact (hF D hD).2 a haD + · intro P hP + obtain ⟨D,hD,rfl⟩ := List.mem_map.mp hP + exact (hF D (hAF hD)).subset (List.filter_sublist) + +lemma sparseStep_controlled {α : Type} [TreeCodec α] [DecidableEq α] + {F : ClauseList α} {S : ℕ} (r : ℕ) (hF : ListControlled S F) : + ListControlled S (sparseStep r F).2.1 ∧ ListControlled S (sparseStep r F).2.2 := by + have branch (p q h : ℕ) (hp : p≤3) (hx : (flowerList F p q h).isEmpty≠true) : + ListControlled S (sparseBranch F (selectedFlower F p q h)).2.1 ∧ + ListControlled S (sparseBranch F (selectedFlower F p q h)).2.2 := by + obtain ⟨hc,hp⟩ := selected_controlled F S p q h hp hF.2 hx + exact ⟨prune_controlled F _ S hF.2 (by intro C hC; simpa using (List.mem_singleton.mp hC) ▸ hc), + prune_controlled F _ S hF.2 hp⟩ + unfold sparseStep + split + · split + · split + · exact ⟨hF,hF⟩ + · exact branch 1 2 _ (by omega) ‹_› + · exact branch 2 1 _ (by omega) ‹_› + · exact branch 1 1 _ (by omega) ‹_› + +lemma SparseTree.controlled {α : Type} [TreeCodec α] [DecidableEq α] + {r S : ℕ} (T : SparseTree α) (hT : T.Valid r) (hF : ListControlled S T.root) : + T.All (ListControlled S) := by + induction T with + | leaf F => exact hF + | branch F l t hl ht => + obtain ⟨_,hleft,hright,hlv,htv⟩ := hT + have h := sparseStep_controlled r hF + dsimp only [SparseTree.root] at h + rw [hleft,hright] at h + exact ⟨hF,hl hlv h.1,ht htv h.2⟩ + +end ParityWL.Complexity + +end OAI diff --git a/lean/OAI/Combinatorics/ParityLifts/SparseCertificate.lean b/lean/OAI/Combinatorics/ParityLifts/SparseCertificate.lean new file mode 100644 index 0000000000000000000000000000000000000000..fdbf55a3ea8a97fe5fcc231e02b62a11e2f34394 --- /dev/null +++ b/lean/OAI/Combinatorics/ParityLifts/SparseCertificate.lean @@ -0,0 +1,103 @@ +import OAI.Combinatorics.ParityLifts.BitNormalize + +namespace OAI + +namespace ParityWL.Complexity + +lemma bitSat_literal_map {N : ℕ} (F : ClauseList (Literal N)) (a : Name → Bool) : + bitSat a (ClauseList.map literalBits F) ↔ + Sparsification.Holds (listCNF F) (fun l => a l.1.val.bits=l.2) := by + rw [listCNF_holds] + simp only [bitSat,ClauseList.map,List.mem_map,forall_exists_index,and_imp] + constructor + · intro h C hC + obtain ⟨l,hl,he⟩ := h _ C hC rfl + obtain ⟨l',hl',rfl⟩ := List.mem_map.mp hl + exact ⟨l',hl',he⟩ + · intro h C D hD he + subst C + obtain ⟨l,hl,hv⟩ := h D hD + exact ⟨literalBits l,List.mem_map.mpr ⟨l,hl,rfl⟩,hv⟩ + +lemma literal_assignment_extend {N : ℕ} (a : Fin N → Bool) : + ∃ b : Name → Bool, ∀ i : Fin N, b i.val.bits=a i := by + let b : Name → Bool := fun w => if h : decodeBits w (treeEncode H).size≤literalSizeBound N) ∧ + (T.leaves.length : ℝ)≤(2 : ℝ)^((N : ℝ)/j) ∧ + (∀ H∈T.leaves, H.length ≤ sparseDensity (12*j) N ∧ ∀ C∈H, C.length≤3) ∧ + ((∃ H∈T.leaves, ∃ a, bitSat a H) ↔ F.Satisfiable) := by + let _ := literalCodec N + let r := 12*j + have hr : 0 a i.val.bits) := by + simp only [T,SparseTree.map_leaves,List.mem_map,exists_exists_and_eq_and,bitSat_literal_map] + rw [← hholds,holds_minimizeList] + exact F.listCNF_sat (fun i => a i.val.bits) + constructor + · rintro ⟨H,hH,a,ha⟩ + exact ⟨_,(hrholds a).mp ⟨H,hH,ha⟩⟩ + · rintro ⟨a,ha⟩ + obtain ⟨b,hb⟩ := literal_assignment_extend a + have hs : F.Satisfied (fun i => b i.val.bits) := by simpa only [hb] using ha + obtain ⟨H,hH,hh⟩ := (hrholds b).mpr hs + exact ⟨H,hH,b,hh⟩ + +end ParityWL.Complexity + +end OAI diff --git a/lean/OAI/Combinatorics/ParityLifts/SparseEncoding.lean b/lean/OAI/Combinatorics/ParityLifts/SparseEncoding.lean new file mode 100644 index 0000000000000000000000000000000000000000..c2ffeb53fdf08cba8dbc66fb6bed5587499d7408 --- /dev/null +++ b/lean/OAI/Combinatorics/ParityLifts/SparseEncoding.lean @@ -0,0 +1,79 @@ +import OAI.Combinatorics.ParityLifts.Evaluation + +namespace OAI + +namespace ParityWL.Complexity + +def ClauseList.map {α β : Type} (f : α → β) (F : ClauseList α) : ClauseList β := + List.map (List.map f) F + +lemma ClauseList.map_encode {α β : Type} [TreeCodec α] [TreeCodec β] + (f : α → β) (hf : ∀ a, treeEncode (f a)=treeEncode a) (F : ClauseList α) : + treeEncode (ClauseList.map f F)=treeEncode F := + treeEncode_map (List.map f) (treeEncode_map f hf) F + +lemma minimizeList_map_encode {α β : Type} [TreeCodec α] [TreeCodec β] + [DecidableEq α] [DecidableEq β] (f : α → β) + (hf : ∀ a, treeEncode (f a)=treeEncode a) (F : ClauseList α) : + minimizeList (ClauseList.map f F)=ClauseList.map f (minimizeList F) := by + apply TreeCodec.injective + change treeEncode (minimizeList (ClauseList.map f F))=treeEncode (ClauseList.map f (minimizeList F)) + rw [ClauseList.map_encode f hf] + exact ((PolyProgram.minimizeList α).encoding_natural (PolyProgram.minimizeList β) + (PolyProgram.minimizeList_code_eq α β) F (ClauseList.map f F) + (ClauseList.map_encode f hf F).symm).symm + +lemma sparseStep_map_encode {α β : Type} [TreeCodec α] [TreeCodec β] + [DecidableEq α] [DecidableEq β] (f : α → β) + (hf : ∀ a, treeEncode (f a)=treeEncode a) (r : ℕ) (F : ClauseList α) : + sparseStep r (ClauseList.map f F)=((sparseStep r F).1, + ClauseList.map f (sparseStep r F).2.1,ClauseList.map f (sparseStep r F).2.2) := by + apply TreeCodec.injective + change treeEncode (sparseStep r (ClauseList.map f F))=treeEncode ((sparseStep r F).1, + ClauseList.map f (sparseStep r F).2.1,ClauseList.map f (sparseStep r F).2.2) + simp only [treeEncode_pair,ClauseList.map_encode f hf] + exact ((PolyProgram.sparseStep α r).encoding_natural (PolyProgram.sparseStep β r) + (PolyProgram.sparseStep_code_eq α β r) F (ClauseList.map f F) + (ClauseList.map_encode f hf F).symm).symm + +def SparseTree.map {α β : Type} (f : α → β) : SparseTree α → SparseTree β + | .leaf F => .leaf (ClauseList.map f F) + | .branch F l t => .branch (ClauseList.map f F) (l.map f) (t.map f) + +@[simp] lemma SparseTree.map_root {α β : Type} (f : α → β) (T : SparseTree α) : + (T.map f).root=ClauseList.map f T.root := by cases T <;> rfl + +@[simp] lemma SparseTree.map_leaves {α β : Type} (f : α → β) (T : SparseTree α) : + (T.map f).leaves=T.leaves.map (ClauseList.map f) := by + induction T with + | leaf F => rfl + | branch F l t hl ht => simp only [map,leaves,hl,ht,List.map_append] + +@[simp] lemma SparseTree.map_nodes {α β : Type} (f : α → β) (T : SparseTree α) : + (T.map f).nodes=T.nodes := by + induction T with + | leaf F => rfl + | branch F l t hl ht => simp only [map,nodes,hl,ht] + +lemma SparseTree.map_valid {α β : Type} [TreeCodec α] [TreeCodec β] [DecidableEq α] [DecidableEq β] + (f : α → β) (hf : ∀ a, treeEncode (f a)=treeEncode a) (r : ℕ) (T : SparseTree α) + (hT : T.Valid r) : (T.map f).Valid r := by + induction T with + | leaf F => simpa only [map,Valid,sparseStep_map_encode f hf] using hT + | branch F l t hl ht => + obtain ⟨hF,hlr,htr,hlv,htv⟩ := hT + simpa only [map,Valid,sparseStep_map_encode f hf,map_root,hlr,htr] using + (show (sparseStep r F).1=false ∧ ClauseList.map f l.root=ClauseList.map f l.root ∧ + ClauseList.map f t.root=ClauseList.map f t.root ∧ (l.map f).Valid r ∧ (t.map f).Valid r + from ⟨hF,rfl,rfl,hl hlv,ht htv⟩) + +lemma SparseTree.map_all {α β : Type} (f : α → β) (P : ClauseList α → Prop) + (Q : ClauseList β → Prop) (hf : ∀ F, P F → Q (ClauseList.map f F)) + (T : SparseTree α) (hT : T.All P) : (T.map f).All Q := by + induction T with + | leaf F => exact hf F hT + | branch F l t hl ht => exact ⟨hf F hT.1,hl hT.2.1,ht hT.2.2⟩ + +end ParityWL.Complexity + +end OAI diff --git a/lean/OAI/Combinatorics/ParityLifts/SparseMachine.lean b/lean/OAI/Combinatorics/ParityLifts/SparseMachine.lean new file mode 100644 index 0000000000000000000000000000000000000000..0e07928dbf11de2565fe7b5f025d7d6f84620ebb --- /dev/null +++ b/lean/OAI/Combinatorics/ParityLifts/SparseMachine.lean @@ -0,0 +1,236 @@ +import OAI.Combinatorics.ParityLifts.SparseBounds + +namespace OAI + +namespace ParityWL.Complexity + +abbrev DFSState (α : Type) := List (ClauseList α) × List (ClauseList α) + +def dfsHead {α : Type} (s : DFSState α) : ClauseList α := s.1.headD [] + +def dfsMerge {α : Type} (x : SparseResult α × DFSState α) : DFSState α := + if x.1.1 then (x.2.1.tail,dfsHead x.2::x.2.2) + else (x.1.2.1::x.1.2.2::x.2.1.tail,x.2.2) + +noncomputable def dfsStep {α : Type} [DecidableEq α] (r : ℕ) (s : DFSState α) : DFSState α := + dfsMerge (sparseStep r (dfsHead s),s) + +def dfsHeadExpr : TExpr := TExpr.input.left.left + +def dfsMergeExpr : TExpr := + let res := TExpr.input.left + let old := TExpr.input.right + .cond res.left + (.pair (.pair res.right.left (.pair res.right.right old.left.right)) old.right) + (.pair old.left.right (.pair old.left.left old.right)) + +lemma dfsHeadExpr_eval {α : Type} [TreeCodec α] (s : DFSState α) : + dfsHeadExpr.eval (treeEncode s)=treeEncode (dfsHead s) := by + rcases s with ⟨xs,ys⟩ + cases xs <;> rfl + +lemma dfsMergeExpr_eval {α : Type} [TreeCodec α] (x : SparseResult α × DFSState α) : + dfsMergeExpr.eval (treeEncode x)=treeEncode (dfsMerge x) := by + rcases x with ⟨⟨b,F,G⟩,⟨xs,ys⟩⟩ + cases xs <;> cases b <;> rfl + +noncomputable def dfsProgram (α : Type) [TreeCodec α] [DecidableEq α] (r : ℕ) : + TreeProgram (DFSState α) (DFSState α) (dfsStep r) where + code := .seq (.pair (.seq dfsHeadExpr.compile (PolyProgram.sparseStep α r).program.code) .id) + dfsMergeExpr.compile + time := fun s => 1000*((treeEncode s).size+(PolyProgram.sparseStep α r).program.time (dfsHead s)+1) + run := by + intro s + let P := (PolyProgram.sparseStep α r).program + have hh : BEval dfsHeadExpr.compile (treeEncode s) + (dfsHeadExpr.cost*((treeEncode s).size+1)) (treeEncode (dfsHead s)) := by + simpa only [dfsHeadExpr_eval] using dfsHeadExpr.run (treeEncode s) + have hc := hh.seq (P.run (dfsHead s)) + have hm := hc.pair (BEval.id (treeEncode s)) + have hf : BEval dfsMergeExpr.compile (treeEncode (sparseStep r (dfsHead s),s)) + (dfsMergeExpr.cost*((treeEncode (sparseStep r (dfsHead s),s)).size+1)) + (treeEncode (dfsStep r s)) := by + simpa only [dfsMergeExpr_eval,dfsStep] using dfsMergeExpr.run (treeEncode (sparseStep r (dfsHead s),s)) + have hsize := (P.run (dfsHead s)).bounds.2.1 + apply (hm.seq hf).mono + simp only [dfsHeadExpr,dfsMergeExpr,TExpr.cost,treeEncode_pair,DataTree.size] + change (treeEncode (sparseStep r (dfsHead s))).size≤P.time (dfsHead s) at hsize + dsimp only [P] at hsize ⊢ + omega + +lemma SparseTree.All.root {α : Type} {P : ClauseList α → Prop} {T : SparseTree α} (h : T.All P) : P T.root := by + cases T with + | leaf F => exact h + | branch F l t => exact h.1 + +lemma SparseTree.All.leaf {α : Type} {P : ClauseList α → Prop} {T : SparseTree α} (h : T.All P) : + ∀ F∈T.leaves, P F := by + induction T with + | leaf F => simpa [SparseTree.leaves, SparseTree.All] using h + | branch F l t hl ht => + intro G hG + rcases List.mem_append.mp hG with hG | hG + · exact hl h.2.1 G hG + · exact ht h.2.2 G hG + +lemma SparseTree.nodes_pos {α : Type} (T : SparseTree α) : 0 simp [SparseTree.nodes] + +lemma forest_roots_length {α : Type} (ts : List (SparseTree α)) : ts.length≤(ts.map SparseTree.nodes).sum := by + induction ts with + | nil => simp + | cons t ts ih => simp only [List.length_cons,List.map_cons,List.sum_cons]; have := t.nodes_pos; omega + +lemma dfsState_size {α : Type} [TreeCodec α] (ts : List (SparseTree α)) (acc : List (ClauseList α)) + (S A : ℕ) (ht : ∀ t∈ts, t.All (fun F => (treeEncode F).size≤S)) + (ha : ∀ F∈acc, (treeEncode F).size≤S) (hN : (ts.map SparseTree.nodes).sum+acc.length≤A) : + (treeEncode (ts.map SparseTree.root,acc)).size≤3+A*(S+1) := by + have hr : (treeEncode (ts.map SparseTree.root)).size≤1+ts.length*(S+1) := by + rw [treeEncode_list_size] + have hs := list_sum_map_le (ts.map SparseTree.root) (fun F => (treeEncode F).size+1) (S+1) (by + intro F hF + obtain ⟨t,ht',rfl⟩ := List.mem_map.mp hF + have := (ht t ht').root + omega) + simpa only [List.length_map] using Nat.add_le_add_left hs 1 + have har : (treeEncode acc).size≤1+acc.length*(S+1) := by + rw [treeEncode_list_size] + apply Nat.add_le_add_left + exact list_sum_map_le acc (fun F => (treeEncode F).size+1) (S+1) (by intro F hF; have := ha F hF; omega) + have hn := forest_roots_length ts + have hm := Nat.mul_le_mul_right (S+1) (show ts.length+acc.length≤A by omega) + simp only [treeEncode_pair,DataTree.size] + nlinarith + +lemma dfsLoop_run {α : Type} [TreeCodec α] [DecidableEq α] (r S A B : ℕ) + (hb : ∀ F : ClauseList α, (treeEncode F).size≤S → (PolyProgram.sparseStep α r).program.time F≤B) + (ts : List (SparseTree α)) (acc : List (ClauseList α)) + (hv : ∀ t∈ts, t.Valid r) (ht : ∀ t∈ts, t.All (fun F => (treeEncode F).size≤S)) + (ha : ∀ F∈acc, (treeEncode F).size≤S) (hN : (ts.map SparseTree.nodes).sum+acc.length≤A) : + BEval (.loop (dfsProgram α r).code) (treeEncode (ts.map SparseTree.root,acc)) + (((ts.map SparseTree.nodes).sum+1)*(1002*(4+A*(S+1)+B))) + (treeEncode (([]:List (ClauseList α)),(ts.flatMap SparseTree.leaves).reverse++acc)) := by + generalize he : (ts.map SparseTree.nodes).sum=n + induction n using Nat.strong_induction_on generalizing ts acc with + | h n ih => + have hsize := dfsState_size ts acc S A ht ha hN + cases ts with + | nil => + have hh := BEval.loop_stop (dfsProgram α r).code (treeEncode (([]:List (ClauseList α)),acc)) rfl + have hz : n=0 := by simpa using he.symm + subst n + simp only [List.map_nil] at hsize + simpa using hh.mono (by + simp only [treeEncode_pair,treeEncode_nil] at hsize ⊢ + nlinarith) + | cons t ts => + have hts : ∀ t∈ts, t.Valid r := fun t ht => hv t (by simp [ht]) + have hss : ∀ t∈ts, t.All (fun F => (treeEncode F).size≤S) := fun t hu => ht t (by simp [hu]) + have htv := hv t (by simp) + have htt := ht t (by simp) + have hh := (dfsProgram α r).run ((t::ts).map SparseTree.root,acc) + have htime := hb t.root htt.root + have hhead : dfsHead ((t::ts).map SparseTree.root,acc)=t.root := rfl + change BEval _ _ (1000*((treeEncode ((t::ts).map SparseTree.root,acc)).size+ + (PolyProgram.sparseStep α r).program.time (dfsHead ((t::ts).map SparseTree.root,acc))+1)) _ at hh + rw [hhead] at hh + have hbnd : 1000*((treeEncode ((t::ts).map SparseTree.root,acc)).size+ + (PolyProgram.sparseStep α r).program.time t.root+1)≤1000*(4+A*(S+1)+B) := by omega + have hnil : (treeEncode ((t::ts).map SparseTree.root,acc)).child false≠.nil := by simp [DataTree.child] + cases t with + | leaf F => + change (sparseStep r F).1=true at htv + have hout : dfsStep r ((SparseTree.leaf F::ts).map SparseTree.root,acc)=(ts.map SparseTree.root,F::acc) := by + simp only [dfsStep,dfsHead,List.map_cons,List.headD_cons,dfsMerge,htv, + SparseTree.root,↓reduceIte,List.tail_cons] + have hn : (ts.map SparseTree.nodes).sum + obtain ⟨hf,hl,hr,hlv,htv⟩ := htv + have hout : dfsStep r ((SparseTree.branch F l t::ts).map SparseTree.root,acc)=((l::t::ts).map SparseTree.root,acc) := by + simp only [dfsStep,dfsHead,List.map_cons,List.headD_cons,dfsMerge,SparseTree.root,hf,hl,hr, + Bool.false_eq_true,↓reduceIte,List.tail_cons] + have hn : ((l::t::ts).map SparseTree.nodes).sum (treeEncode F).size≤S) := by + intro u hu; rcases List.mem_cons.mp hu with rfl | hu + · exact htt.2.1 + · rcases List.mem_cons.mp hu with rfl | hu + · exact htt.2.2 + · exact hss u hu + obtain hrec := ih _ hn (l::t::ts) acc hv' ht' ha hn' rfl + rw [hout] at hh + have hrun := BEval.loop_next hnil (hh.mono hbnd) hrec + convert hrun.mono (show _≤(n+1)*(1002*(4+A*(S+1)+B)) from by + simp only [List.map_cons,List.sum_cons,SparseTree.nodes] at he ⊢ + generalize 4+A*(S+1)+B=D at * + nlinarith) using 1; simp [SparseTree.leaves,List.append_assoc] + +lemma SparseTree.All.mono {α : Type} {P Q : ClauseList α → Prop} {T : SparseTree α} + (h : T.All P) (hp : ∀ F, P F → Q F) : T.All Q := by + induction T with + | leaf F => exact hp F h + | branch F l t hl ht => exact ⟨hp F h.1,hl h.2.1,ht h.2.2⟩ + +def dfsInitExpr : TExpr := .pair (.pair .input .nil) .nil + +noncomputable def sparseCode (α : Type) [TreeCodec α] [DecidableEq α] (r : ℕ) : FCode := + .seq dfsInitExpr.compile (.seq (.loop (dfsProgram α r).code) .right) + +lemma sparseCode_run {α : Type} [TreeCodec α] [DecidableEq α] (r S B : ℕ) + (hb : ∀ F : ClauseList α, (treeEncode F).size≤S → (PolyProgram.sparseStep α r).program.time F≤B) + (T : SparseTree α) (hv : T.Valid r) (ht : T.All (fun F => (treeEncode F).size≤S)) : + BEval (sparseCode α r) (treeEncode T.root) + (2010*(T.nodes+1)^2*(S+B+5)) (treeEncode T.leaves.reverse) := by + have hinit : BEval dfsInitExpr.compile (treeEncode T.root) + (dfsInitExpr.cost*((treeEncode T.root).size+1)) + (treeEncode ([T.root],([]:List (ClauseList α)))) := dfsInitExpr.run _ + have hloop := dfsLoop_run r S T.nodes B hb [T] [] + (by intro t ht; simpa using (List.mem_singleton.mp ht) ▸ hv) + (by intro t ht'; simpa using (List.mem_singleton.mp ht') ▸ ht) + (by simp) (by simp) + simp only [List.map_cons,List.map_nil,List.sum_cons,List.sum_nil,Nat.add_zero, + List.flatMap_cons,List.flatMap_nil,List.append_nil] at hloop + have hr := BEval.right (treeEncode (([]:List (ClauseList α)),T.leaves.reverse)) + change BEval _ _ _ (treeEncode T.leaves.reverse) at hr + have hs := hloop.bounds.2.1 + have hroot := ht.root + apply (hinit.seq (hloop.seq hr)).mono + simp only [dfsInitExpr,TExpr.cost,DataTree.size] at * + have hn := T.nodes_pos + generalize T.nodes=n at * + generalize (treeEncode T.root).size=sz at * + generalize (treeEncode (([]:List (ClauseList α)),T.leaves.reverse)).size=z at * + let X := (n+1)^2*(S+B+5) + have hc : (n+1)*(1002*(4+n*(S+1)+B))≤1002*X := by + calc + _ ≤ (n+1)*(1002*((n+1)*(S+B+5))) := by gcongr; nlinarith + _ = _ := by dsimp [X]; ring + have hX : S+B+5≤X := Nat.le_mul_of_pos_left _ (by positivity) + calc + _ ≤ 2010*X := by omega + _ = _ := by dsimp [X]; ring + +end ParityWL.Complexity + +end OAI diff --git a/lean/OAI/Combinatorics/ParityLifts/SparsePost.lean b/lean/OAI/Combinatorics/ParityLifts/SparsePost.lean new file mode 100644 index 0000000000000000000000000000000000000000..7db9d4950815269cf63348f684c8c7b46115c1f5 --- /dev/null +++ b/lean/OAI/Combinatorics/ParityLifts/SparsePost.lean @@ -0,0 +1,92 @@ +import OAI.Combinatorics.ParityLifts.LeafRate + +namespace OAI + +namespace ParityWL.Complexity + +noncomputable def sparseStepBudget (j N : ℕ) : ℕ := + (PolyProgram.sparseStep BitLiteral (12*j)).coefficient* + (literalSizeBound N+1)^(PolyProgram.sparseStep BitLiteral (12*j)).degree + +lemma sparseStepBudget_rate (j : ℕ) : ExpBound (fun N => (sparseStepBudget j N : ℝ)) 0 := + polynomial_program_rate (PolyProgram.sparseStep BitLiteral (12*j)) literalSizeBound sparseSize_rate + +lemma sparseStepBudget_bound (j N : ℕ) (F : BitFormula) + (hs : (treeEncode F).size ≤ literalSizeBound N) : + (PolyProgram.sparseStep BitLiteral (12*j)).program.time F ≤ sparseStepBudget j N := by + apply (PolyProgram.sparseStep BitLiteral (12*j)).bound F |>.trans + exact Nat.mul_le_mul_left _ (Nat.pow_le_pow_left (Nat.add_le_add_right hs 1) _) + +noncomputable def leafNumber (j N : ℕ) : ℝ := 2^((1/(j : ℝ))*N) + +noncomputable def postBudget (j : ℕ) (W : ℕ → ℝ) (N : ℕ) : ℝ := + 2010*(2*leafNumber j N)^2*(literalSizeBound N+sparseStepBudget j N+5 : ℕ)+ + 500*(leafNumber j N+1)^2*(literalSizeBound N+W N+6)+1 + +noncomputable def postCode (j : ℕ) (p : FCode) : FCode := .seq (sparseCode BitLiteral (12*j)) p.any + +lemma postCode_run (j : ℕ) (hj : 0 ∃ a,bitSat a F) + (literalSizeBound N) (W N) (hw N) T.leaves.reverse + (by intro G hG; exact hs.leaf G (List.mem_reverse.mp hG)) + (by + intro G hG + have hG' := List.mem_reverse.mp hG + exact hp N G (hs.leaf G hG') (hden G hG').1 (hden G hG').2) + have hb'' : RBEval p.any (treeEncode T.leaves.reverse) + (500*(leafNumber j N+1)^2*(literalSizeBound N+W N+6)) (treeEncode b) := by + apply hb.mono + rw [List.length_reverse] + have hwN := hw N + gcongr + rw [hr] at ht' + exact ⟨b,ht'.seq hb'',hb'.trans ((by simp only [List.mem_reverse] : + (∃ G∈T.leaves.reverse, ∃ a,bitSat a G)↔∃ G∈T.leaves,∃ a,bitSat a G).trans he)⟩ + +lemma postBudget_rate (j : ℕ) (W : ℕ → ℝ) (r : ℝ) (hr : 0 ≤ r) + (hW : ExpBound W r) : ExpBound (postBudget j W) (2/(j : ℝ)+r) := by + have hq : ExpBound (leafNumber j) (1/(j : ℝ)) := ExpBound.exp _ + have hq0 : 0 ≤ 1/(j : ℝ) := by positivity + have hpoly : ExpBound (fun N => (literalSizeBound N+sparseStepBudget j N+5 : ℕ)) 0 := by + simpa only [Nat.cast_add,Nat.cast_ofNat] using + (sparseSize_rate.add_same (sparseStepBudget_rate j)).add_same (ExpBound.const 5 (by norm_num)) + have ht := (((ExpBound.const 2 (by norm_num)).mul hq).pow 2).mul hpoly + have ht' : ExpBound (fun N => 2010*(2*leafNumber j N)^2*(literalSizeBound N+sparseStepBudget j N+5 : ℕ)) (2/(j : ℝ)+r) := by + have hh := (ExpBound.const 2010 (by norm_num)).mul ht + simp only [zero_add,add_zero] at hh + have hh' : ExpBound (fun N => 2010*((2*leafNumber j N)^2*(literalSizeBound N+sparseStepBudget j N+5 : ℕ))) (2/(j : ℝ)) := by + convert hh using 1 + ring + convert hh'.mono_rate (show 2/(j : ℝ) ≤ 2/(j : ℝ)+r by linarith) using 1 + funext N; ring + have hsize := (sparseSize_rate.mono_rate hr).add_same hW |>.add_same + ((ExpBound.const 6 (by norm_num)).mono_rate hr) + have hl := (hq.add_same ((ExpBound.const 1 (by norm_num)).mono_rate hq0)).pow 2 + have ha := ((ExpBound.const 500 (by norm_num)).mul hl).mul hsize + have ha' : ExpBound (fun N => 500*(leafNumber j N+1)^2*(literalSizeBound N+W N+6)) (2/(j : ℝ)+r) := by + convert ha using 1 + ring + exact (ht'.add_same ha').add_same ((ExpBound.const 1 (by norm_num)).mono_rate (by positivity)) + +end ParityWL.Complexity + +end OAI diff --git a/lean/OAI/Combinatorics/ParityLifts/SparseRates.lean b/lean/OAI/Combinatorics/ParityLifts/SparseRates.lean new file mode 100644 index 0000000000000000000000000000000000000000..3876563b91e92e25e6492a38ac0bffcaf4252880 --- /dev/null +++ b/lean/OAI/Combinatorics/ParityLifts/SparseRates.lean @@ -0,0 +1,80 @@ +import OAI.Combinatorics.ParityLifts.ExpBounds + +namespace OAI + +namespace ParityWL.Complexity + +def densityFactor (r : ℕ) : ℕ := 2*(1+r^2+2*(r^4)^2) + +lemma sparseDensity_eq (r N : ℕ) : sparseDensity r N=1+densityFactor r*N := by + simp only [sparseDensity,densityFactor]; ring + +lemma ExpBound.polymul {f g : ℕ → ℝ} (hf : ExpBound f 0) (hg : ExpBound g 0) : + ExpBound (fun n => f n*g n) 0 := by simpa using hf.mul hg + +lemma ExpBound.polypow {f : ℕ → ℝ} (hf : ExpBound f 0) (d : ℕ) : + ExpBound (fun n => f n^d) 0 := by simpa using hf.pow d + +lemma sparseSize_rate : ExpBound (fun N => (literalSizeBound N : ℝ)) 0 := by + have hN : ExpBound (fun N => (N : ℝ)) 0 := + (ExpBound.poly 1).mono (fun N => Nat.cast_nonneg N) (by intro N; simp) + have h1 := ExpBound.const 1 (by norm_num) + have h2 := ExpBound.const 2 (by norm_num) + have h3 := ExpBound.const 3 (by norm_num) + have h4 := ExpBound.const 4 (by norm_num) + have h6 := ExpBound.const 6 (by norm_num) + have he := h1.add_same (h4.polymul (((h2.polymul hN).add_same h1).polypow 3) |>.polymul + (h2.add_same (h3.polymul ((h4.polymul hN).add_same h6)))) + simpa only [literalSizeBound,Nat.cast_add,Nat.cast_mul,Nat.cast_ofNat,Nat.cast_one, + Nat.cast_pow,add_zero,zero_add,mul_zero,zero_mul] using he + +lemma ceilWidth_bound (m t : ℕ) (ht : 0 (2 : ℝ)^(a*n+b)) a := by + refine ⟨fun _ => (Real.rpow_pos_of_pos (by norm_num) _).le, + 2^b,Real.rpow_pos_of_pos (by norm_num) _,0,?_⟩ + intro n + change 2^(a*(n : ℝ)+b)≤2^b*(n+1 : ℝ)^0*2^(a*n) + rw [pow_zero,mul_one,Real.rpow_add (by norm_num),mul_comm] + +lemma ExpBound.affine_exp_mul (a b c : ℝ) : + ExpBound (fun n => (2 : ℝ)^(a*(b*n+c))) (a*b) := by + convert ExpBound.affine_exp (a*b) (a*c) using 1 + funext n + congr 1 + ring + +lemma polynomial_program_rate {α β : Type} [TreeCodec α] [TreeCodec β] + {f : α → β} (P : PolyProgram α β f) (S : ℕ → ℕ) + (hS : ExpBound (fun N => (S N : ℝ)) 0) : + ExpBound (fun N => (P.coefficient*(S N+1)^P.degree : ℕ)) 0 := by + have h := (ExpBound.const P.coefficient (Nat.cast_nonneg _)).mul + ((hS.add_same (ExpBound.const 1 (by norm_num))).pow P.degree) + simpa only [Nat.cast_mul,Nat.cast_pow,Nat.cast_add,Nat.cast_one,mul_zero,add_zero] using h +end ParityWL.Complexity + +end OAI diff --git a/lean/OAI/Combinatorics/ParityLifts/SparseStates.lean b/lean/OAI/Combinatorics/ParityLifts/SparseStates.lean new file mode 100644 index 0000000000000000000000000000000000000000..14d5059023feb85dc0df348c598be3d73a2d16c0 --- /dev/null +++ b/lean/OAI/Combinatorics/ParityLifts/SparseStates.lean @@ -0,0 +1,234 @@ +import OAI.Combinatorics.ParityLifts.Flowers + +namespace OAI + +namespace Sparsification + +lemma bernoulli_split (S : ℝ) (hS : 0 < S) (x y : ℕ) + (hxy : S ^ 2 ≤ (x : ℝ) * y) : + (1 / (1 + 1 / S) ^ x) + (1 / (1 + 1 / S) ^ y) ≤ 1 := by + have hi : 0 ≤ 1 / S := le_of_lt (one_div_pos.mpr hS) + have hx := one_add_mul_le_pow (by linarith : (-2 : ℝ) ≤ 1 / S) x + have hy := one_add_mul_le_pow (by linarith : (-2 : ℝ) ≤ 1 / S) y + have hax : (0 : ℝ) < (1 + 1 / S) ^ x := pow_pos (by linarith) _ + have hay : (0 : ℝ) < (1 + 1 / S) ^ y := pow_pos (by linarith) _ + have hab : 1 ≤ ((x : ℝ) * (1 / S)) * ((y : ℝ) * (1 / S)) := by + have he : ((x : ℝ) * (1 / S)) * ((y : ℝ) * (1 / S)) = (x * y : ℝ) / S ^ 2 := by ring + rw [he] + exact (le_div_iff₀ (sq_pos_of_pos hS)).mpr (by simpa using hxy) + have hm := mul_le_mul (show (x : ℝ) * (1 / S) ≤ (1 + 1 / S) ^ x - 1 by linarith) + (show (y : ℝ) * (1 / S) ≤ (1 + 1 / S) ^ y - 1 by linarith) + (mul_nonneg (Nat.cast_nonneg _) hi) + (show 0 ≤ (1 + 1 / S) ^ x - 1 by nlinarith [mul_nonneg (Nat.cast_nonneg x) hi]) + have he : (1 / (1 + 1 / S) ^ x + 1 / (1 + 1 / S) ^ y) = + ((1 + 1 / S) ^ y + (1 + 1 / S) ^ x) / + ((1 + 1 / S) ^ x * (1 + 1 / S) ^ y) := by field_simp + rw [he] + apply (div_le_iff₀ (mul_pos hax hay)).mpr + nlinarith + +noncomputable def branchBase (r : ℕ) : ℝ := 1 + 1 / (r : ℝ) ^ 3 + +lemma branchBase_gt_one {r : ℕ} (hr : 0 < r) : 1 < branchBase r := by + have hr' : (0 : ℝ) < r := Nat.cast_pos.mpr hr + dsimp [branchBase] + have hi := one_div_pos.mpr (pow_pos hr' 3) + linarith + +lemma split_units {r : ℕ} (hr : 0 < r) : + 1 / branchBase r ^ (r ^ 2) + 1 / branchBase r ^ (r ^ 4) ≤ 1 := by + apply bernoulli_split ((r : ℝ) ^ 3) (pow_pos (Nat.cast_pos.mpr hr) _) (r ^ 2) (r ^ 4) + push_cast + ring_nf + rfl + +lemma split_binary {r : ℕ} (hr : 0 < r) : + 1 / branchBase r ^ 1 + 1 / branchBase r ^ (r ^ 6) ≤ 1 := by + apply bernoulli_split ((r : ℝ) ^ 3) (pow_pos (Nat.cast_pos.mpr hr) _) 1 (r ^ 6) + push_cast + ring_nf + rfl + +end Sparsification + + +namespace Sparsification + +variable {α : Type} [DecidableEq α] [Fintype α] + +structure State (α : Type) [DecidableEq α] [Fintype α] (h : ℕ) where + formula : CNF α + marked : CNF α + created : ℕ + reduced : Reduced formula + width : ∀ C ∈ formula, C.card ≤ 3 + marked_sub : marked ⊆ binaries formula + marked_degree : ∀ x, degree marked x ≤ h + resource : created ≤ marked.card + h * (units formula).card + +def State.spent {h : ℕ} (s : State α h) : ℕ := h * (units s.formula).card + s.created + +lemma State.spent_bound {h : ℕ} (s : State α h) : s.spent ≤ 3 * Fintype.card α * h := by + have hm := marked_card_bound s.marked h (fun C hC => Finset.card_pos.mp (by + rw [(Finset.mem_filter.mp (s.marked_sub hC)).2]; omega)) s.marked_degree + have hu : (units s.formula).card ≤ Fintype.card α := Finset.card_le_univ _ + have hr := s.resource + unfold State.spent + nlinarith + +omit [Fintype α] in +lemma minimize_subset (F : CNF α) : minimize F ⊆ F := Finset.filter_subset _ _ + +def initialState (F : CNF α) (hw : ∀ C ∈ F, C.card ≤ 3) (h : ℕ) : State α h where + formula := minimize F + marked := ∅ + created := 0 + reduced := minimize_reduced F + width := by + intro C hC + exact hw C (minimize_subset F hC) + marked_sub := Finset.empty_subset _ + marked_degree := by intro x; simp [degree] + resource := Nat.zero_le _ + +omit [DecidableEq α] [Fintype α] in +lemma singleton_reduced (C : Finset α) : Reduced {C} := by + intro D hD E hE _ + exact (Finset.mem_singleton.mp hD).trans (Finset.mem_singleton.mp hE).symm + +omit [Fintype α] in +lemma prune_width {F A : CNF α} (hF : ∀ C ∈ F, C.card ≤ 3) + (hA : ∀ C ∈ A, C.card ≤ 3) : ∀ C ∈ prune F A, C.card ≤ 3 := by + intro C hC + rcases Finset.mem_union.mp hC with hC | hC + · exact hF C (Finset.mem_filter.mp hC).1 + · exact hA C hC + +omit [Fintype α] in +lemma survived_sub_binaries {F M A : CNF α} (hm : M ⊆ binaries F) : + survived M A ⊆ binaries (prune F A) := by + intro C hC + have hC' := Finset.mem_filter.mp hC + have hc := Finset.mem_filter.mp (hm hC'.1) + exact Finset.mem_filter.mpr ⟨Finset.mem_union_left _ (Finset.mem_filter.mpr + ⟨hc.1, hC'.2⟩), hc.2⟩ + +def State.addUnits {h : ℕ} (s : State α h) (A : CNF α) + (ha : ∀ C ∈ A, C.card = 1) (hf : Fresh s.formula A) : State α h where + formula := prune s.formula A + marked := survived s.marked A + created := s.created + reduced := prune_reduced s.reduced (by + intro C hC D hD hCD + exact Finset.eq_of_subset_of_card_le hCD (by rw [ha C hC, ha D hD])) hf + width := prune_width s.width (by intro C hC; rw [ha C hC]; omega) + marked_sub := survived_sub_binaries s.marked_sub + marked_degree := fun x => (degree_survived_le _ _ x).trans (s.marked_degree x) + resource := unit_resource hf ha s.marked_degree s.resource + +lemma State.spent_addUnits {h : ℕ} (s : State α h) (A : CNF α) + (ha : ∀ C ∈ A, C.card = 1) (hf : Fresh s.formula A) : + (s.addUnits A ha hf).spent = s.spent + h * A.card := by + simp only [State.spent, State.addUnits, units_prune_card _ _ hf ha] + ring + +def State.addBinaries {h : ℕ} (s : State α h) (A : CNF α) + (ha : ∀ C ∈ A, C.card = 2) (hf : Fresh s.formula A) + (hdeg : ∀ x, degree A x ≤ 1) + (hn : ¬ Nonempty (Flower s.formula 1 1 h)) : State α h where + formula := prune s.formula A + marked := s.marked ∪ A + created := s.created + A.card + reduced := prune_reduced s.reduced (by + intro C hC D hD hCD + exact Finset.eq_of_subset_of_card_le hCD (by rw [ha C hC, ha D hD])) hf + width := prune_width s.width (by intro C hC; rw [ha C hC]; omega) + marked_sub := by + intro C hC + rcases Finset.mem_union.mp hC with hC | hC + · apply survived_sub_binaries s.marked_sub + rw [survived_binary_eq hf s.marked_sub ha] + exact hC + · exact Finset.mem_filter.mpr ⟨Finset.mem_union_right _ hC, ha C hC⟩ + marked_degree := binary_degree_invariant s.marked_sub (no_two_flower_degree hn) hdeg + resource := binary_resource hf s.marked_sub ha s.resource + +lemma State.spent_addBinaries {h : ℕ} (s : State α h) (A : CNF α) + (ha : ∀ C ∈ A, C.card = 2) (hf : Fresh s.formula A) + (hdeg : ∀ x, degree A x ≤ 1) (hn : ¬ Nonempty (Flower s.formula 1 1 h)) : + (s.addBinaries A ha hf hdeg hn).spent = s.spent + A.card := by + have hne : ∀ C ∈ A, C.Nonempty := by + intro C hC; exact Finset.card_pos.mp (by rw [ha C hC]; omega) + simp only [State.spent, State.addBinaries, units_prune _ _ hne, + units_empty_of_binaries A ha, Finset.union_empty] + ring + +/-- A split stores its actual successor states, progress and the exact semantic +branching equation. Its numerical inequality is proved for the three cases. -/ +structure Split {r : ℕ} (s : State α (r ^ 2)) where + left : State α (r ^ 2) + right : State α (r ^ 2) + x : ℕ + y : ℕ + x_pos : 0 < x + y_pos : 0 < y + left_spent : left.spent = s.spent + x + right_spent : right.spent = s.spent + y + split_bound : 1 / branchBase r ^ x + 1 / branchBase r ^ y ≤ 1 + holds : ∀ v : α → Prop, Holds s.formula v ↔ Holds left.formula v ∨ Holds right.formula v + +def Terminal (F : CNF α) (r : ℕ) : Prop := + ¬ Nonempty (Flower F 1 1 (r ^ 2)) ∧ + ¬ Nonempty (Flower F 1 2 (r ^ 4)) ∧ ¬ Nonempty (Flower F 2 1 (r ^ 4)) + +lemma state_terminal_or_split {r : ℕ} (hr : 0 < r) (s : State α (r ^ 2)) : + Terminal s.formula r ∨ Nonempty (Split s) := by + classical + have hr2 : 0 < r ^ 2 := pow_pos hr _ + have hr4 : 0 < r ^ 4 := pow_pos hr _ + by_cases h2 : Nonempty (Flower s.formula 1 1 (r ^ 2)) + · obtain ⟨f⟩ := h2 + have hc : ∀ C ∈ ({f.core} : CNF α), C.card = 1 := by + intro C hC; obtain rfl := Finset.mem_singleton.mp hC; exact f.core_card + let l := s.addUnits {f.core} hc (f.core_fresh s.reduced (by omega) hr2) + let t := s.addUnits f.petals f.petal_card (f.petals_fresh s.reduced (by omega)) + right + refine ⟨⟨l, t, r ^ 2, r ^ 4, hr2, hr4, ?_, ?_, split_units hr, ?_⟩⟩ + · simpa [l] using s.spent_addUnits {f.core} hc (f.core_fresh s.reduced (by omega) hr2) + · have he : r ^ 2 * r ^ 2 = r ^ 4 := by ring + simpa [t, f.petals_card, he] using + s.spent_addUnits f.petals f.petal_card (f.petals_fresh s.reduced (by omega)) + · exact f.branch_holds + by_cases h32 : Nonempty (Flower s.formula 2 1 (r ^ 4)) + · obtain ⟨f⟩ := h32 + have hc : ∀ C ∈ ({f.core} : CNF α), C.card = 2 := by + intro C hC; obtain rfl := Finset.mem_singleton.mp hC; exact f.core_card + let l := s.addBinaries {f.core} hc (f.core_fresh s.reduced (by omega) hr4) + (singleton_degree_le_one f.core) h2 + let t := s.addUnits f.petals f.petal_card (f.petals_fresh s.reduced (by omega)) + right + refine ⟨⟨l, t, 1, r ^ 6, by omega, pow_pos hr _, ?_, ?_, split_binary hr, ?_⟩⟩ + · simpa [l] using s.spent_addBinaries {f.core} hc + (f.core_fresh s.reduced (by omega) hr4) (singleton_degree_le_one f.core) h2 + · have he : r ^ 2 * r ^ 4 = r ^ 6 := by ring + simpa [t, f.petals_card, he] using + s.spent_addUnits f.petals f.petal_card (f.petals_fresh s.reduced (by omega)) + · exact f.branch_holds + by_cases h31 : Nonempty (Flower s.formula 1 2 (r ^ 4)) + · obtain ⟨f⟩ := h31 + have hc : ∀ C ∈ ({f.core} : CNF α), C.card = 1 := by + intro C hC; obtain rfl := Finset.mem_singleton.mp hC; exact f.core_card + let l := s.addUnits {f.core} hc (f.core_fresh s.reduced (by omega) hr4) + let t := s.addBinaries f.petals f.petal_card (f.petals_fresh s.reduced (by omega)) + (pairwise_degree_le_one f.petals f.pairwise) h2 + right + refine ⟨⟨l, t, r ^ 2, r ^ 4, hr2, hr4, ?_, ?_, split_units hr, ?_⟩⟩ + · simpa [l] using s.spent_addUnits {f.core} hc (f.core_fresh s.reduced (by omega) hr4) + · simpa [t, f.petals_card] using s.spent_addBinaries f.petals f.petal_card + (f.petals_fresh s.reduced (by omega)) (pairwise_degree_le_one f.petals f.pairwise) h2 + · exact f.branch_holds + exact Or.inl ⟨h2, h31, h32⟩ + +end Sparsification + +end OAI diff --git a/lean/OAI/Combinatorics/ParityLifts/SparseStep.lean b/lean/OAI/Combinatorics/ParityLifts/SparseStep.lean new file mode 100644 index 0000000000000000000000000000000000000000..ac800a23467342e5dee435a4ab21b17de517a2ad --- /dev/null +++ b/lean/OAI/Combinatorics/ParityLifts/SparseStep.lean @@ -0,0 +1,133 @@ +import OAI.Combinatorics.ParityLifts.FlowerPrograms + +namespace OAI + +namespace Sparsification + +variable {α : Type} [DecidableEq α] [Fintype α] {r : ℕ} + +lemma split_from_two (hr : 0 b=true) h0 + have branch (p q h : ℕ) (hx : (flowerList F p q h).isEmpty≠true) + (hs : ∀ f : Sparsification.Flower s.formula p q h, + ∃ sp : Sparsification.Split s, sp.left.formula=Sparsification.prune s.formula {f.core} ∧ + sp.right.formula=Sparsification.prune s.formula f.petals) : + ∃ sp : Sparsification.Split s, + listCNF (sparseBranch F (selectedFlower F p q h)).2.1=sp.left.formula ∧ + listCNF (sparseBranch F (selectedFlower F p q h)).2.2=sp.right.formula := by + have hg := selectedFlower_good F p q h (by simpa using hx) + let f := hg.toFlower + let f' : Sparsification.Flower s.formula p q h := { f with + cover := fun P hP => he ▸ f.cover P hP } + obtain ⟨sp,hl,ht⟩ := hs f' + have hc : f'.core=(selectedFlower F p q h).1.toFinset := by rfl + have hp : f'.petals=listCNF (selectedFlower F p q h).2 := by rfl + refine ⟨sp,?_,?_⟩ <;> simp only [sparseBranch,listCNF_prune] + · rw [hl,hc,he]; rfl + · rw [ht,hp,he] + unfold sparseStep + split + · rename_i h2 + split + · rename_i h32 + split + · rename_i h31 + exact Or.inl ⟨rfl,rfl,rfl,hterm 1 1 _ (pow_pos hr _) h2, + hterm 1 2 _ (pow_pos hr _) h31,hterm 2 1 _ (pow_pos hr _) h32⟩ + · rename_i h31 + exact Or.inr ⟨rfl,branch 1 2 _ h31 (Sparsification.split_from_three_unit hr s (hterm 1 1 _ (pow_pos hr _) h2))⟩ + · rename_i h32 + exact Or.inr ⟨rfl,branch 2 1 _ h32 (Sparsification.split_from_three_binary hr s (hterm 1 1 _ (pow_pos hr _) h2))⟩ + · rename_i h2 + exact Or.inr ⟨rfl,branch 1 1 _ h2 (Sparsification.split_from_two hr s)⟩ + +noncomputable def PolyProgram.sparseBranch (α : Type) [TreeCodec α] [DecidableEq α] : + PolyProgram (ClauseList α × FlowerRecord α) (SparseResult α) (fun x => Complexity.sparseBranch x.1 x.2) := by + let fc : PolyProgram (ClauseList α × FlowerRecord α) (ClauseList α × ClauseList α) (fun x => (x.1,[x.2.1])) := + .expr (.pair TExpr.input.left (.pair TExpr.input.right.left .nil)) (by intro x; rfl) + let fp : PolyProgram (ClauseList α × FlowerRecord α) (ClauseList α × ClauseList α) (fun x => (x.1,x.2.2)) := + .expr (.pair TExpr.input.left TExpr.input.right.right) (by intro x; rfl) + exact ((PolyProgram.const false).pair ((fc.comp (PolyProgram.pruneList α)).pair + (fp.comp (PolyProgram.pruneList α)))).congr (by intro x; rfl) + +noncomputable def PolyProgram.sparseStep (α : Type) [TreeCodec α] [DecidableEq α] (r : ℕ) : + PolyProgram (ClauseList α) (SparseResult α) (Complexity.sparseStep r) := by + let test (p q h : ℕ) := (PolyProgram.flowerList α p q h).comp (PolyProgram.null (FlowerRecord α)) + let branch (p q h : ℕ) := (((PolyProgram.id (ClauseList α)).pair + ((PolyProgram.flowerList α p q h).comp (PolyProgram.head (FlowerRecord α) ([],[])))).comp + (PolyProgram.sparseBranch α)) + let done : PolyProgram (ClauseList α) (SparseResult α) (fun F => (true,F,F)) := + .expr (.pair (.const (boolTree true)) (.pair .input .input)) (by intro x; rfl) + exact ((test 1 1 (r^2)).ite ((test 2 1 (r^4)).ite ((test 1 2 (r^4)).ite done + (branch 1 2 (r^4))) (branch 2 1 (r^4))) (branch 1 1 (r^2))).congr (by intro F; rfl) + +end ParityWL.Complexity + +end OAI diff --git a/lean/OAI/Combinatorics/ParityLifts/SparseTree.lean b/lean/OAI/Combinatorics/ParityLifts/SparseTree.lean new file mode 100644 index 0000000000000000000000000000000000000000..f7058e8ca3630e62b798132205ea3ac5e174e63b --- /dev/null +++ b/lean/OAI/Combinatorics/ParityLifts/SparseTree.lean @@ -0,0 +1,106 @@ +import OAI.Combinatorics.ParityLifts.SparseStep + +namespace OAI + +namespace ParityWL.Complexity + +inductive SparseTree (α : Type) where + | leaf : ClauseList α → SparseTree α + | branch : ClauseList α → SparseTree α → SparseTree α → SparseTree α + +def SparseTree.root {α : Type} : SparseTree α → ClauseList α + | .leaf F => F + | .branch F _ _ => F + +def SparseTree.leaves {α : Type} : SparseTree α → List (ClauseList α) + | .leaf F => [F] + | .branch _ l t => l.leaves++t.leaves + +def SparseTree.nodes {α : Type} : SparseTree α → ℕ + | .leaf _ => 1 + | .branch _ l t => l.nodes+t.nodes+1 + +lemma SparseTree.nodes_eq {α : Type} (T : SparseTree α) : T.nodes+1=2*T.leaves.length := by + induction T with + | leaf F => simp [nodes,leaves] + | branch F l t hl ht => simp only [nodes,leaves,List.length_append] at *; omega + +lemma SparseTree.nodes_le {α : Type} (T : SparseTree α) : T.nodes≤2*T.leaves.length := by + have := T.nodes_eq + omega + +noncomputable def SparseTree.Valid {α : Type} [DecidableEq α] (r : ℕ) : SparseTree α → Prop + | .leaf F => (sparseStep r F).1=true + | .branch F l t => (sparseStep r F).1=false ∧ (sparseStep r F).2.1=l.root ∧ + (sparseStep r F).2.2=t.root ∧ l.Valid r ∧ t.Valid r + +def SparseTree.All {α : Type} (P : ClauseList α → Prop) : SparseTree α → Prop + | .leaf F => P F + | .branch F l t => P F ∧ l.All P ∧ t.All P + +lemma sparse_tree_exists {α : Type} [DecidableEq α] [Fintype α] {r : ℕ} (hr : 0 + intro s hn F he + rcases sparseStep_spec hr s F he with ht | ⟨hflag,sp,hl,hright⟩ + · refine ⟨.leaf F,rfl,ht.1,?_,?_,?_⟩ + · intro H hH + have hh : H=F := by simpa [SparseTree.leaves] using hH + subst H + rw [he] + exact ⟨s.reduced,s.width,ht.2.2.2⟩ + · intro v; simp [SparseTree.leaves] + · simp only [SparseTree.leaves,List.length_singleton,Nat.cast_one,one_mul] + exact pow_le_pow_right₀ hb s.spent_bound + · have hls := sp.left_spent + have hrs := sp.right_spent + have hleft : K-sp.left.spent 0 + | some x => x.succ + +def decodeTop {a : ℕ} (x : Fin (a + 3)) : Option (StackSymbol a) := + Fin.cases none some x + +@[simp] lemma decode_encodeTop {a : ℕ} (x : Option (StackSymbol a)) : + decodeTop (encodeTop x) = x := by cases x <;> simp [decodeTop, encodeTop] + +@[simp] lemma encode_decodeTop {a : ℕ} (x : Fin (a + 3)) : + encodeTop (decodeTop x) = x := by + refine Fin.cases ?_ (fun x => ?_) x <;> simp [decodeTop, encodeTop] + +@[simp] lemma encodeTop_zero_iff {a : ℕ} (x : Option (StackSymbol a)) : + encodeTop x = 0 ↔ x = none := by + cases x with + | none => simp [encodeTop] + | some x => simp only [encodeTop, Fin.succ_ne_zero, Option.some_ne_none] + +def wordCell {a : ℕ} (w : List (StackSymbol a)) (z : ℤ) : Fin (a + 3) := + if 0 ≤ z then encodeTop w[z.toNat]? else 0 + +@[simp] lemma wordCell_zero {a : ℕ} (w : List (StackSymbol a)) : + wordCell w 0 = encodeTop w.head? := by simp [wordCell, List.head?_eq_getElem?] + +@[simp] lemma wordCell_nil {a : ℕ} (z : ℤ) : wordCell ([] : List (StackSymbol a)) z = 0 := by + simp [wordCell, encodeTop] + +lemma wordCell_neg {a : ℕ} (w : List (StackSymbol a)) {z : ℤ} (hz : z < 0) : + wordCell w z = 0 := ite_eq_right (by omega) + +lemma wordCell_cons {a : ℕ} (x : StackSymbol a) (w : List (StackSymbol a)) (z : ℤ) : + wordCell (x :: w) z = if z = 0 then encodeTop (some x) else wordCell w (z - 1) := by + by_cases hz : z = 0 + · subst z; simp + by_cases hp : 0 < z + · obtain ⟨n, hn⟩ := Int.eq_ofNat_of_zero_le (by omega : 0 ≤ z - 1) + have he : z = (n : ℤ) + 1 := by omega + rw [he] + simp [wordCell, Int.toNat_add, show 0 ≤ (n : ℤ) + 1 by omega, + show ¬ (n : ℤ) + 1 = 0 by omega] + · rw [wordCell_neg _ (by omega), ite_eq_right hz, wordCell_neg _ (by omega)] + +lemma wordCell_pop {a : ℕ} (x : StackSymbol a) (w : List (StackSymbol a)) (z : ℤ) : + (if z = 0 then 0 else wordCell (x :: w) z) = wordCell w (z - 1) := by + rw [wordCell_cons] + by_cases hz : z = 0 + · subst z; simp [wordCell] + · simp [hz] + +inductive StackOp (a : ℕ) where + | keep + | pop + | push (symbol : StackSymbol a) + deriving DecidableEq + +def StackOp.apply {a : ℕ} : StackOp a → List (StackSymbol a) → List (StackSymbol a) + | .keep, w => w + | .pop, w => w.tail + | .push x, w => x :: w + +def StackOp.action {a : ℕ} : StackOp a → Fin (a + 3) → Fin (a + 3) × Move + | .keep, z => (z, .stay) + | .pop, z => if z = 0 then (0, .stay) else (0, .right) + | .push _, z => (z, .left) + +def StackOp.pending {a : ℕ} : StackOp a → Option (StackSymbol a) + | .push x => some x + | _ => none + +def finishWrite {a : ℕ} (x : Option (StackSymbol a)) (z : Fin (a + 3)) : Fin (a + 3) := + match x with | none => z | some x => encodeTop (some x) + +lemma tape_operation {a : ℕ} (op : StackOp a) (w : List (StackSymbol a)) + (h : ℤ) (f : ℤ → Fin (a + 3)) (hf : ∀ z, f z = wordCell w (z - h)) : + let act := op.action (f h) + let h' := h + act.2.offset + let f' := fun z => if z = h then act.1 else f z + ∀ z, (if z = h' then finishWrite op.pending (f' h') else f' z) = + wordCell (op.apply w) (z - h') := by + have hread : f h = encodeTop w.head? := by simpa using hf h + cases op with + | keep => + simp only [StackOp.action, Move.offset, add_zero, StackOp.pending, finishWrite, StackOp.apply] + intro z + by_cases hz : z = h + · subst z; simp [hread] + · simpa [hz] using hf z + | pop => + cases w with + | nil => + have hz : f h = 0 := by simpa [encodeTop] using hread + simp only [StackOp.action, hz, ↓reduceIte, Move.offset, add_zero, + StackOp.pending, finishWrite, StackOp.apply, List.tail_nil] + intro z + by_cases he : z = h + · simp [he, encodeTop] + · simpa [he] using hf z + | cons x w => + have hz : f h ≠ 0 := by rw [hread]; simp + simp only [StackOp.action, ite_eq_right hz, Move.offset, StackOp.pending, + finishWrite, StackOp.apply, List.tail_cons] + intro z + have he : ¬ h + 1 = h := by omega + by_cases hz' : z = h + 1 + · subst z + simp only [↓reduceIte, ite_eq_right he] + rw [hf, wordCell_cons] + norm_num + · simp only [ite_eq_right hz'] + rw [hf] + have hc := wordCell_pop x w (z - h) + have h0 : z - h = 0 ↔ z = h := sub_eq_zero + have h1 : z - h - 1 = z - (h + 1) := by ring + simpa only [h0, h1] using hc + | push x => + dsimp only [StackOp.action, Move.offset, StackOp.pending, finishWrite, StackOp.apply] + intro z + by_cases hz : z = h + -1 + · subst z; simp + · rw [ite_eq_right hz] + rw [wordCell_cons] + have h0 : ¬ z - (h + -1) = 0 := by omega + have h1 : z - (h + -1) - 1 = z - h := by ring + rw [ite_eq_right h0, h1] + by_cases he : z = h + · subst z; simp [hread] + · simpa [he] using hf z + +structure StackMachine (Q : Type) (t a : ℕ) where + initial : Q + output : Q → Option Bool + transition : Q → (Fin (t + 1) → Option (StackSymbol a)) → Q × (Fin (t + 1) → StackOp a) + +structure StackConfiguration (Q : Type) (t a : ℕ) where + state : Q + word : Fin (t + 1) → List (StackSymbol a) + +def StackMachine.step {Q : Type} {t a : ℕ} (P : StackMachine Q t a) + (x : StackConfiguration Q t a) : StackConfiguration Q t a := + match P.output x.state with + | some _ => x + | none => + let b := P.transition x.state (fun i => (x.word i).head?) + { state := b.1, word := fun i => (b.2 i).apply (x.word i) } + +abbrev StackControl (Q : Type) (t a : ℕ) := Q ⊕ (Q × (Fin (t + 1) → Option (StackSymbol a))) + +def StackMachine.lower {Q : Type} {t a : ℕ} (P : StackMachine Q t a) : + LocalMachine (StackControl Q t a) t a where + initial := Sum.inl P.initial + output := fun q => match q with | .inl q => P.output q | .inr _ => none + transition := fun q x => match q with + | .inl q => + let b := P.transition q (fun i => decodeTop (x i)) + (.inr (b.1, fun i => (b.2 i).pending), fun i => (b.2 i).action (x i)) + | .inr (q, p) => (.inl q, fun i => (finishWrite (p i) (x i), .stay)) + +def StackMachine.Represents {Q : Type} {t a : ℕ} (_P : StackMachine Q t a) + (x : StackConfiguration Q t a) (y : LocalConfiguration (StackControl Q t a) t a) : Prop := + y.state = Sum.inl x.state ∧ ∀ i z, y.tape i z = wordCell (x.word i) (z - y.head i) + +lemma StackMachine.lower_two_steps {Q : Type} {t a : ℕ} (P : StackMachine Q t a) + (x : StackConfiguration Q t a) (y : LocalConfiguration (StackControl Q t a) t a) + (h : P.Represents x y) : P.Represents (P.step x) (P.lower.step (P.lower.step y)) := by + have hread : (fun i => decodeTop (y.tape i (y.head i))) = fun i => (x.word i).head? := by + funext i + rw [h.2 i, sub_self, wordCell_zero, decode_encodeTop] + cases ho : P.output x.state with + | some b => + have he : P.lower.step y = y := by + simp only [LocalMachine.step, StackMachine.lower, h.1, ho] + rw [he, he] + simpa only [StackMachine.step, ho] using h + | none => + simp only [StackMachine.Represents, StackMachine.step, LocalMachine.step, + StackMachine.lower, h.1, ho, hread, Move.offset, add_zero] + constructor + · trivial + · intro i z + exact tape_operation _ _ _ _ (h.2 i) z + +end ParityWL.Complexity + +namespace ParityWL.Complexity + +def stackInputSymbol (a : ℕ) (b : Bool) : StackSymbol a := + if b then ⟨1, by omega⟩ else 0 + +lemma encodeTop_input (a : ℕ) (b : Bool) : + encodeTop (some (stackInputSymbol a b)) = localInputSymbol a b := by + cases b <;> rfl + +def StackMachine.initialConfiguration {Q : Type} {t a : ℕ} + (P : StackMachine Q t a) (input : List Bool) : StackConfiguration Q t a where + state := P.initial + word := fun i => if i.val = 0 then input.map (stackInputSymbol a) else [] + +def StackMachine.run {Q : Type} {t a : ℕ} (P : StackMachine Q t a) + (input : List Bool) (s : ℕ) : StackConfiguration Q t a := + P.step^[s] (P.initialConfiguration input) + +lemma StackMachine.lower_initial {Q : Type} {t a : ℕ} + (P : StackMachine Q t a) (input : List Bool) : + P.Represents (P.initialConfiguration input) (P.lower.initialConfiguration input) := by + constructor + · rfl + · intro i z + change (if i.val = 0 ∧ 0 ≤ z then + match input[z.toNat]? with + | some b => localInputSymbol a b + | none => 0 + else 0) = wordCell (if i.val = 0 then input.map (stackInputSymbol a) else []) (z - 0) + rw [sub_zero] + by_cases hi : i.val = 0 + · simp only [hi, true_and, ↓reduceIte, wordCell, List.getElem?_map] + by_cases hz : 0 ≤ z + · simp only [hz, ↓reduceIte] + cases h : input[z.toNat]? with + | none => rfl + | some b => exact (encodeTop_input a b).symm + · simp [hz] + · simp [hi] + +lemma StackMachine.lower_iterate {Q : Type} {t a : ℕ} + (P : StackMachine Q t a) (x : StackConfiguration Q t a) + (y : LocalConfiguration (StackControl Q t a) t a) (h : P.Represents x y) (s : ℕ) : + P.Represents (P.step^[s] x) (P.lower.step^[2 * s] y) := by + induction s with + | zero => exact h + | succ s ih => + have he : 2 * (s + 1) = 2 * s + 1 + 1 := by omega + rw [he, Function.iterate_succ_apply', Function.iterate_succ_apply', + Function.iterate_succ_apply'] + exact P.lower_two_steps _ _ ih + +lemma StackMachine.lower_run {Q : Type} {t a : ℕ} (P : StackMachine Q t a) + (input : List Bool) (s : ℕ) : + P.Represents (P.run input s) (P.lower.run input (2 * s)) := + P.lower_iterate _ _ (P.lower_initial input) s + +/-- Every machine with finite control and finitely many finite-alphabet stacks +is realized by the multitape `Machine`, at exactly two local steps per +stack step. This includes input preparation and halting semantics. -/ +noncomputable def StackMachine.compiled {Q : Type} [Fintype Q] {t a : ℕ} + (P : StackMachine Q t a) : Machine := P.lower.packed + +lemma StackMachine.compiled_emits {Q : Type} [Fintype Q] {t a : ℕ} + (P : StackMachine Q t a) (input : List Bool) (s : ℕ) (b : Bool) : + Emits P.compiled input (2 * s) b ↔ P.output (P.run input s).state = some b := by + rw [StackMachine.compiled, LocalMachine.packed_emits] + rw [(P.lower_run input s).1] + rfl + +end ParityWL.Complexity + +end OAI diff --git a/lean/OAI/Combinatorics/ParityLifts/StackRoutines.lean b/lean/OAI/Combinatorics/ParityLifts/StackRoutines.lean new file mode 100644 index 0000000000000000000000000000000000000000..94058ed079995646a90dbc1ea9e6f14ef8f5a88e --- /dev/null +++ b/lean/OAI/Combinatorics/ParityLifts/StackRoutines.lean @@ -0,0 +1,322 @@ +import OAI.Combinatorics.ParityLifts.StackMachine + +namespace OAI + +namespace ParityWL.Complexity + +abbrev Words (t a : ℕ) := Fin (t + 1) → List (StackSymbol a) + +def applyOps {t a : ℕ} (ops : Fin (t + 1) → StackOp a) (w : Words t a) : Words t a := + fun i => (ops i).apply (w i) + +inductive StackExec {Q : Type} {t a : ℕ} (P : StackMachine Q t a) : + StackConfiguration Q t a → ℕ → StackConfiguration Q t a → Bool → Prop + | halt (x : StackConfiguration Q t a) (b : Bool) (h : P.output x.state = some b) : + StackExec P x 0 x b + | next (x : StackConfiguration Q t a) {n : ℕ} {y : StackConfiguration Q t a} {b : Bool} + (h : P.output x.state = none) (tail : StackExec P (P.step x) n y b) : + StackExec P x (n + 1) y b + +lemma StackExec.output {Q : Type} {t a : ℕ} {P : StackMachine Q t a} + {x y : StackConfiguration Q t a} {n : ℕ} {b : Bool} (h : StackExec P x n y b) : + P.output y.state = some b := by + induction h with + | halt _ _ h => exact h + | next _ _ _ ih => exact ih + +lemma StackExec.iterate {Q : Type} {t a : ℕ} {P : StackMachine Q t a} + {x y : StackConfiguration Q t a} {n : ℕ} {b : Bool} (h : StackExec P x n y b) : + P.step^[n] x = y := by + induction h with + | halt => rfl + | next _ _ _ ih => exact (Function.iterate_succ_apply _ _ _).trans ih + +lemma StackExec.map {Q R : Type} {t a : ℕ} {P : StackMachine Q t a} {T : StackMachine R t a} + (f : StackConfiguration Q t a → StackConfiguration R t a) + (ho : ∀ x, T.output (f x).state = P.output x.state) + (hs : ∀ x, P.output x.state = none → T.step (f x) = f (P.step x)) + {x y : StackConfiguration Q t a} {n : ℕ} {b : Bool} (h : StackExec P x n y b) : + StackExec T (f x) n (f y) b := by + induction h with + | halt x b h => exact .halt _ _ ((ho x).trans h) + | next x h _ ih => + apply StackExec.next _ ((ho x).trans h) + rw [hs x h] + exact ih + +/-- Structured sequential composition; one finite-control step starts the +second routine once the first has returned. No external simulator is presumed. -/ +def StackMachine.andThen {Q R : Type} {t a : ℕ} + (P : StackMachine Q t a) (T : StackMachine R t a) : StackMachine (Q ⊕ R) t a where + initial := Sum.inl P.initial + output := fun q => match q with | .inl _ => none | .inr q => T.output q + transition := fun q x => match q with + | .inl q => match P.output q with + | none => let b := P.transition q x; (.inl b.1, b.2) + | some _ => (.inr T.initial, fun _ => .keep) + | .inr q => let b := T.transition q x; (.inr b.1, b.2) + +def StackConfiguration.inl {Q R : Type} {t a : ℕ} (x : StackConfiguration Q t a) : + StackConfiguration (Q ⊕ R) t a := ⟨Sum.inl x.state, x.word⟩ + +def StackConfiguration.inr {Q R : Type} {t a : ℕ} (x : StackConfiguration R t a) : + StackConfiguration (Q ⊕ R) t a := ⟨Sum.inr x.state, x.word⟩ + +lemma StackExec.andThen_right {Q R : Type} {t a : ℕ} + (P : StackMachine Q t a) (T : StackMachine R t a) + {x y : StackConfiguration R t a} {n : ℕ} {b : Bool} (h : StackExec T x n y b) : + StackExec (P.andThen T) x.inr n y.inr b := by + apply StackExec.map StackConfiguration.inr (fun _ => rfl) ?_ h + intro x hx + simp only [StackMachine.step, StackMachine.andThen, StackConfiguration.inr, hx] + +lemma StackExec.andThen {Q R : Type} {t a : ℕ} + {P : StackMachine Q t a} {T : StackMachine R t a} + {x z : StackConfiguration Q t a} {y : StackConfiguration R t a} + {n m : ℕ} {b c : Bool} (h : StackExec P x n z b) + (ht : StackExec T ⟨T.initial, z.word⟩ m y c) : + StackExec (P.andThen T) x.inl (n + 1 + m) y.inr c := by + induction h with + | halt x b hx => + have hr := ht.andThen_right P T + have he : (P.andThen T).step x.inl = (⟨T.initial, x.word⟩ : StackConfiguration R t a).inr := by + simp only [StackMachine.step, StackMachine.andThen, StackConfiguration.inl, hx, + StackConfiguration.inr, StackOp.apply] + have hh := StackExec.next x.inl (by rfl : (P.andThen T).output x.inl.state = none) + (he ▸ hr) + simpa only [Nat.zero_add, Nat.add_comm 1 m] using hh + | next x hx h ih => + have he : (P.andThen T).step x.inl = (P.step x).inl := by + simp only [StackMachine.step, StackMachine.andThen, StackConfiguration.inl, hx] + have hh := StackExec.next x.inl (by rfl : (P.andThen T).output x.inl.state = none) + (he ▸ ih ht) + convert hh using 1 + omega + +/-- Repeat a returning routine until it returns true, removing the halt marker +on false. Restarting takes one local stack step and does not touch data. -/ +def StackMachine.repeat {Q : Type} {t a : ℕ} (P : StackMachine Q t a) : StackMachine Q t a where + initial := P.initial + output := fun q => if P.output q = some true then some true else none + transition := fun q x => match P.output q with + | none => P.transition q x + | some _ => (P.initial, fun _ => .keep) + +lemma StackExec.repeat_true {Q : Type} {t a : ℕ} {P : StackMachine Q t a} + {x y : StackConfiguration Q t a} {n : ℕ} (h : StackExec P x n y true) : + StackExec P.repeat x n y true := by + generalize hb : true = b at h + induction h with + | halt x b hx => subst b; exact .halt _ _ (by simp [StackMachine.repeat, hx]) + | next x hx h ih => + apply StackExec.next _ (by simp [StackMachine.repeat, hx]) + have he : P.repeat.step x = P.step x := by simp [StackMachine.step, StackMachine.repeat, hx] + rw [he] + exact ih hb + +lemma StackExec.repeat_false {Q : Type} {t a : ℕ} {P : StackMachine Q t a} + {x z y : StackConfiguration Q t a} {n m : ℕ} + (h : StackExec P x n z false) + (ht : StackExec P.repeat ⟨P.initial, z.word⟩ m y true) : + StackExec P.repeat x (n + 1 + m) y true := by + generalize hb : false = b at h + induction h with + | halt x b hx => + subst b + have he : P.repeat.step x = ⟨P.initial, x.word⟩ := by + simp [StackMachine.step, StackMachine.repeat, hx, StackOp.apply] + have hh := StackExec.next x (by simp [StackMachine.repeat, hx]) (he ▸ ht) + simpa only [Nat.zero_add, Nat.add_comm 1 m] using hh + | next x hx h ih => + have he : P.repeat.step x = P.step x := by simp [StackMachine.step, StackMachine.repeat, hx] + have hh := StackExec.next x (by simp [StackMachine.repeat, hx]) (he ▸ ih ht hb) + convert hh using 1 + omega + +/-- One finite-table operation, including a return bit chosen from scanned tops. +All alphabets and control sets of this routine are visibly finite. -/ +def primitive {t a : ℕ} + (ops : (Fin (t + 1) → Option (StackSymbol a)) → Fin (t + 1) → StackOp a) + (test : (Fin (t + 1) → Option (StackSymbol a)) → Bool) : + StackMachine (Option Bool) t a where + initial := none + output := id + transition := fun _ x => (some (test x), ops x) + +lemma primitive_exec {t a : ℕ} + (ops : (Fin (t + 1) → Option (StackSymbol a)) → Fin (t + 1) → StackOp a) + (test : (Fin (t + 1) → Option (StackSymbol a)) → Bool) (w : Words t a) : + let tops := fun i => (w i).head? + StackExec (primitive ops test) ⟨none, w⟩ 1 + ⟨some (test tops), applyOps (ops tops) w⟩ (test tops) := by + dsimp only + apply StackExec.next _ rfl + exact StackExec.halt _ _ rfl + +def Runs {Q : Type} {t a : ℕ} (P : StackMachine Q t a) + (w : Words t a) (n : ℕ) (v : Words t a) (b : Bool) : Prop := + ∃ q, StackExec P ⟨P.initial, w⟩ n ⟨q, v⟩ b + +lemma Runs.andThen {Q R : Type} {t a : ℕ} + {P : StackMachine Q t a} {T : StackMachine R t a} + {w v z : Words t a} {n m : ℕ} {b c : Bool} + (h : Runs P w n v b) (ht : Runs T v m z c) : + Runs (P.andThen T) w (n + 1 + m) z c := by + obtain ⟨q, hq⟩ := h + obtain ⟨r, hr⟩ := ht + exact ⟨Sum.inr r, hq.andThen hr⟩ + +lemma Runs.compiled {Q : Type} [Fintype Q] {t a : ℕ} + {P : StackMachine Q t a} {input : List Bool} {n : ℕ} {v : Words t a} {b : Bool} + (h : Runs P (fun i => if i.val = 0 then input.map (stackInputSymbol a) else []) n v b) : + Emits P.compiled input (2 * n) b := by + rw [P.compiled_emits] + obtain ⟨q, hq⟩ := h + exact (congrArg (fun x => P.output x.state) hq.iterate).trans hq.output + +end ParityWL.Complexity + +namespace ParityWL.Complexity + +/-- A finite control-flow chart whose nodes are verified stack routines. -/ +structure MacroMachine (Q : Type) (t a : ℕ) where + Control : Q → Type + initial : Q + output : Q → Option Bool + routine : (q : Q) → StackMachine (Control q) t a + next : Q → Bool → Q + +def MacroMachine.lower {Q : Type} {t a : ℕ} (P : MacroMachine Q t a) : + StackMachine ((q : Q) × P.Control q) t a where + initial := ⟨P.initial, (P.routine P.initial).initial⟩ + output := fun q => P.output q.1 + transition := fun ⟨q, r⟩ x => match (P.routine q).output r with + | none => let v := (P.routine q).transition r x; (⟨q, v.1⟩, v.2) + | some b => let q' := P.next q b; (⟨q', (P.routine q').initial⟩, fun _ => .keep) + +def MacroMachine.lift {Q : Type} {t a : ℕ} (P : MacroMachine Q t a) (q : Q) + (x : StackConfiguration (P.Control q) t a) : + StackConfiguration ((q : Q) × P.Control q) t a := ⟨⟨q, x.state⟩, x.word⟩ + +lemma MacroMachine.exec_routine {Q : Type} {t a : ℕ} (P : MacroMachine Q t a) + (q : Q) (ho : P.output q = none) + {x z : StackConfiguration (P.Control q) t a} {n m : ℕ} {b c : Bool} + {y : StackConfiguration ((q : Q) × P.Control q) t a} + (h : StackExec (P.routine q) x n z b) + (ht : StackExec P.lower + ⟨⟨P.next q b, (P.routine (P.next q b)).initial⟩, z.word⟩ m y c) : + StackExec P.lower (P.lift q x) (n + 1 + m) y c := by + induction h with + | halt x b hx => + have he : P.lower.step (P.lift q x) = + ⟨⟨P.next q b, (P.routine (P.next q b)).initial⟩, x.word⟩ := by + simp only [StackMachine.step, MacroMachine.lower, MacroMachine.lift, ho, hx, StackOp.apply] + have hh := StackExec.next (P.lift q x) (by exact ho) (he ▸ ht) + simpa only [Nat.zero_add, Nat.add_comm 1 m] using hh + | next x hx _ ih => + have he : P.lower.step (P.lift q x) = P.lift q ((P.routine q).step x) := by + simp only [StackMachine.step, MacroMachine.lower, MacroMachine.lift, ho, hx] + have hh := StackExec.next (P.lift q x) (by exact ho) (he ▸ ih ht) + convert hh using 1 + omega + +inductive MacroExec {Q : Type} {t a : ℕ} (P : MacroMachine Q t a) : + Q → Words t a → ℕ → Words t a → Bool → Prop + | halt (q : Q) (w : Words t a) (b : Bool) (h : P.output q = some b) : + MacroExec P q w 0 w b + | next (q : Q) (w : Words t a) {v z : Words t a} {n m : ℕ} {b c : Bool} + (h : P.output q = none) (hr : Runs (P.routine q) w n v b) + (tail : MacroExec P (P.next q b) v m z c) : + MacroExec P q w (n + 1 + m) z c + +lemma MacroExec.lower {Q : Type} {t a : ℕ} {P : MacroMachine Q t a} + {q : Q} {w v : Words t a} {n : ℕ} {b : Bool} (h : MacroExec P q w n v b) : + ∃ r, StackExec P.lower ⟨⟨q, (P.routine q).initial⟩, w⟩ n ⟨r, v⟩ b := by + induction h with + | halt q w b h => exact ⟨_, .halt _ _ h⟩ + | next q w h hr _ ih => + obtain ⟨r, hr⟩ := hr + obtain ⟨s, hs⟩ := ih + exact ⟨s, P.exec_routine q h hr hs⟩ + +lemma MacroExec.compiled {Q : Type} [Fintype Q] {t a : ℕ} + {P : MacroMachine Q t a} [∀ q, Fintype (P.Control q)] + {input : List Bool} {n : ℕ} {v : Words t a} {b : Bool} + (h : MacroExec P P.initial + (fun i => if i.val = 0 then input.map (stackInputSymbol a) else []) n v b) : + Emits P.lower.compiled input (2 * n) b := by + exact Runs.compiled h.lower + +/-- A finite-table transfer step. The source is popped; a prescribed subset of +other stacks receives its top symbol. An empty source returns true. -/ +def transferStep {t a : ℕ} (src : Fin (t + 1)) (dst : Finset (Fin (t + 1))) : + StackMachine (Option Bool) t a := + primitive (fun x i => match x src with + | none => .keep + | some c => if i = src then .pop else if i ∈ dst then .push c else .keep) + (fun x => (x src).isNone) + +def transfer {t a : ℕ} (src : Fin (t + 1)) (dst : Finset (Fin (t + 1))) := + (transferStep (a := a) src dst).repeat + +def transferred {t a : ℕ} (src : Fin (t + 1)) (dst : Finset (Fin (t + 1))) + (w : Words t a) : Words t a := + fun i => if i = src then [] else if i ∈ dst then (w src).reverse ++ w i else w i + +lemma transfer_run {t a : ℕ} (src : Fin (t + 1)) (dst : Finset (Fin (t + 1))) + (w : Words t a) : + Runs (transfer src dst) w (2 * (w src).length + 1) (transferred src dst w) true := by + generalize he : w src = l + induction l generalizing w with + | nil => + have h := primitive_exec (t := t) (a := a) + (fun x i => match x src with + | none => .keep + | some c => if i = src then .pop else if i ∈ dst then .push c else .keep) + (fun x => (x src).isNone) w + simp only [he, List.head?_nil, Option.isNone_none] at h + have hw : applyOps (fun _ => StackOp.keep) w = transferred src dst w := by + funext i + simp only [applyOps, StackOp.apply, transferred, he, List.reverse_nil, List.nil_append] + split_ifs with hi + · simpa [hi] using he + · rfl + · rfl + change StackExec (transferStep src dst) _ _ _ true at h + exact ⟨some true, hw ▸ h.repeat_true⟩ + | cons c l ih => + let w' := applyOps (fun i => if i = src then .pop else if i ∈ dst then .push c else .keep) w + have hs : w' src = l := by simp [w', applyOps, StackOp.apply, he] + obtain ⟨q, hq⟩ := ih w' hs + have h := primitive_exec (t := t) (a := a) + (fun x i => match x src with + | none => .keep + | some c => if i = src then .pop else if i ∈ dst then .push c else .keep) + (fun x => (x src).isNone) w + simp only [he, List.head?_cons, Option.isNone_some] at h + change StackExec (transferStep src dst) _ 1 ⟨some false, w'⟩ false at h + have hw : transferred src dst w' = transferred src dst w := by + funext i + simp only [transferred, hs, he, List.reverse_cons] + split_ifs with hi hd + · rfl + · simp [w', applyOps, hi, hd, StackOp.apply, List.append_assoc] + · simp [w', applyOps, hi, hd, StackOp.apply] + have hh := h.repeat_false hq + refine ⟨q, ?_⟩ + rw [hw] at hh + change StackExec (transferStep src dst).repeat ⟨none, w⟩ + (2 * (l.length + 1) + 1) ⟨q, transferred src dst w⟩ true + convert hh using 1 + omega + +/-- Emptying a stack never modifies another stack. -/ +lemma clear_run {t a : ℕ} (src : Fin (t + 1)) (w : Words t a) : + Runs (transfer src ∅) w (2 * (w src).length + 1) (Function.update w src []) true := by + convert transfer_run src ∅ w using 1 + funext i + by_cases hi : i = src <;> simp [transferred, Function.update, hi] + +end ParityWL.Complexity + +end OAI diff --git a/lean/OAI/Combinatorics/ParityLifts/TableGraphs.lean b/lean/OAI/Combinatorics/ParityLifts/TableGraphs.lean new file mode 100644 index 0000000000000000000000000000000000000000..24b9a4dd237a8873191ad8351b7eb698eb31e613 --- /dev/null +++ b/lean/OAI/Combinatorics/ParityLifts/TableGraphs.lean @@ -0,0 +1,264 @@ +import OAI.Combinatorics.ParityLifts.GraphIso + +namespace OAI + +namespace ParityWL.Complexity + +abbrev ChoiceData (t : ℕ) := (Fin t → List (Fin t → ℕ)) × (Fin t → Fin t → ℕ) + +def ChoiceData.entry {t : ℕ} (D : ChoiceData t) (i : Fin t) (d : ℕ) (j : Fin t) : ℕ := + (D.1 i)[d]?.getD (fun _ => 0) j + +def ChoiceData.pairBound {t : ℕ} (D : ChoiceData t) (i j : Fin t) : ℕ := + D.2 (min i j) (max i j) + +def ChoiceData.label {t : ℕ} (D : ChoiceData t) (i : Fin t) (d : ℕ) (j : Fin t) : ℕ := + min (D.entry i d j) (D.pairBound i j) + +lemma ChoiceData.pairBound_symm {t : ℕ} (D : ChoiceData t) (i j : Fin t) : + D.pairBound i j = D.pairBound j i := by simp [pairBound, min_comm, max_comm] + +noncomputable def ChoiceData.system {t : ℕ} (D : ChoiceData t) : ChoiceSystem t where + Domain i := Fin (D.1 i).length + domainFintype _ := inferInstance + Label p := Fin (D.2 p.1.1 p.1.2+1) + labelFintype _ := inferInstance + leftLabel p d := ⟨D.label p.1.1 d.val p.1.2, by + change min (D.entry p.1.1 d.val p.1.2) (D.pairBound p.1.1 p.1.2) < _ + rw [pairBound, min_eq_left p.2.le, max_eq_right p.2.le] + exact Nat.lt_succ_of_le (min_le_right _ _)⟩ + rightLabel p d := ⟨D.label p.1.2 d.val p.1.1, by + change min (D.entry p.1.2 d.val p.1.1) (D.pairBound p.1.2 p.1.1) < _ + rw [pairBound, min_eq_right p.2.le, max_eq_left p.2.le] + exact Nat.lt_succ_of_le (min_le_right _ _)⟩ + +def ChoiceData.roleSize {t : ℕ} (D : ChoiceData t) : TemplateVertex t → ℕ + | .inl i => (D.1 i).length + | .inr h => D.2 h.1.1.1.1 h.1.1.1.2+1 + +def ChoiceData.vertex {t : ℕ} (D : ChoiceData t) : (a : TemplateVertex t) → + Fin (D.roleSize a) → BaseVertex D.system + | .inl i, d => .inl ⟨i,d⟩ + | .inr h, q => .inr ⟨h,q⟩ + +@[simp] lemma ChoiceData.vertex_type {t : ℕ} (D : ChoiceData t) (a : TemplateVertex t) + (d : Fin (D.roleSize a)) : baseType (D.vertex a d) = a := by cases a <;> rfl + +def ChoiceData.baseIndex {t : ℕ} (D : ChoiceData t) : BaseVertex D.system → ℕ + | .inl x => x.2.val + | .inr x => x.2.val + +@[simp] lemma ChoiceData.vertex_index {t : ℕ} (D : ChoiceData t) (a : TemplateVertex t) + (d : Fin (D.roleSize a)) : D.baseIndex (D.vertex a d) = d.val := by cases a <;> rfl + +def ChoiceData.helperTest {t : ℕ} (D : ChoiceData t) (h : Helper t) (q : ℕ) (i : Fin t) (d : ℕ) : Bool := + if i=h.1.1.1.1 then decide (D.label i d h.1.1.1.2 = q) + else if i=h.1.1.1.2 then decide (D.label i d h.1.1.1.1 = q) + else decide (i=h.1.2) + +def ChoiceData.baseTest {t : ℕ} (D : ChoiceData t) : TemplateVertex t → ℕ → TemplateVertex t → ℕ → Bool + | .inl i, d, .inl j, e => decide (i≠j) && decide (D.label i d j = D.label j e i) + | .inl i, d, .inr h, q => D.helperTest h q i d + | .inr h, q, .inl i, d => D.helperTest h q i d + | .inr _, _, .inr _, _ => false + +lemma ChoiceData.baseTest_symm {t : ℕ} (D : ChoiceData t) (a b : TemplateVertex t) (d e : ℕ) : + D.baseTest a d b e = D.baseTest b e a d := by + cases a <;> cases b <;> simp [baseTest, eq_comm] + +lemma ChoiceData.baseTest_arc {t : ℕ} (D : ChoiceData t) {x y : BaseVertex D.system} + (h : BaseArc D.system x y) : D.baseTest (baseType x) (D.baseIndex x) (baseType y) (D.baseIndex y) = true := by + cases h with + | main p d e h => + have he := congrArg Fin.val h + simp only [ChoiceData.system] at he + simp [baseType, baseIndex, baseTest, ne_of_lt p.2, he] + | left h d => simp [baseType, baseIndex, baseTest, helperTest, ChoiceData.system] + | right h d => + simp [baseType, baseIndex, baseTest, helperTest, ChoiceData.system, ne_of_gt h.1.1.2] + | third h q d => + simp [baseType, baseIndex, baseTest, helperTest, h.2.1, h.2.2] + +lemma ChoiceData.baseTest_adj {t : ℕ} (D : ChoiceData t) {x y : BaseVertex D.system} + (h : (baseGraph D.system).Adj x y) : + D.baseTest (baseType x) (D.baseIndex x) (baseType y) (D.baseIndex y) = true := by + rcases h.2 with h | h + · exact D.baseTest_arc h + · rw [D.baseTest_symm] + exact D.baseTest_arc h + +lemma ChoiceData.helperTest_arc {t : ℕ} (D : ChoiceData t) (h : Helper t) + (q : D.system.Label h.1.1) (i : Fin t) (d : D.system.Domain i) + (he : D.helperTest h q.val i d.val = true) : + BaseArc D.system (.inr ⟨h,q⟩) (.inl ⟨i,d⟩) := by + by_cases hi : i=h.1.1.1.1 + · subst i + have hq : D.system.leftLabel h.1.1 d=q := by + apply Fin.ext + simpa [helperTest, ChoiceData.system] using he + rw [← hq] + exact BaseArc.left h d + · by_cases hj : i=h.1.1.1.2 + · subst i + have hq : D.system.rightLabel h.1.1 d=q := by + apply Fin.ext + simpa [helperTest, hi, ChoiceData.system] using he + rw [← hq] + exact BaseArc.right h d + · have hk : i=h.1.2 := by simpa [helperTest, hi, hj] using he + subst i + exact BaseArc.third h q d + +lemma ChoiceData.adj_of_baseTest {t : ℕ} (D : ChoiceData t) (x y : BaseVertex D.system) + (hr : D.baseTest (baseType x) (D.baseIndex x) (baseType y) (D.baseIndex y) = true) : + (baseGraph D.system).Adj x y := by + rcases x with ⟨i,d⟩ | ⟨h,q⟩ <;> rcases y with ⟨j,e⟩ | ⟨g,r⟩ + · have he : i≠j ∧ D.label i d.val j=D.label j e.val i := by simpa [baseTest, baseType, baseIndex] using hr + have hne : (.inl ⟨i,d⟩ : BaseVertex D.system) ≠ .inl ⟨j,e⟩ := by + intro hh + have hi := congrArg baseType hh + exact he.1 (Sum.inl.inj hi) + refine ⟨hne, ?_⟩ + rcases lt_or_gt_of_ne he.1 with hij | hji + · exact Or.inl (BaseArc.main ⟨(i,j),hij⟩ d e (Fin.ext he.2)) + · exact Or.inr (BaseArc.main ⟨(j,i),hji⟩ e d (Fin.ext he.2.symm)) + · exact ⟨by simp, Or.inr (D.helperTest_arc g r i d hr)⟩ + · exact ⟨by simp, Or.inl (D.helperTest_arc h q j e hr)⟩ + · simp [baseType, baseIndex, baseTest] at hr + +lemma ChoiceData.baseTest_iff {t : ℕ} (D : ChoiceData t) (x y : BaseVertex D.system) : + D.baseTest (baseType x) (D.baseIndex x) (baseType y) (D.baseIndex y) = true ↔ + (baseGraph D.system).Adj x y := + ⟨D.adj_of_baseTest x y, D.baseTest_adj⟩ + +end ParityWL.Complexity + +namespace ParityWL.Complexity + +def enumPairs {m : ℕ} (n : Fin m → ℕ) : List (Fin m × ℕ) := + (List.ofFn id).flatMap (fun z => (List.range (n z)).map (z,·)) + +@[simp] lemma mem_enumPairs {m : ℕ} (n : Fin m → ℕ) (z : Fin m) (d : ℕ) : + (z,d) ∈ enumPairs n ↔ d congrArg Prod.snd h) + · apply (List.nodup_ofFn.mpr (Function.injective_id)).imp + intro z w h x hx hy + obtain ⟨d, _, rfl⟩ := List.mem_map.mp hx + obtain ⟨e, _, he⟩ := List.mem_map.mp hy + exact h (congrArg Prod.fst he).symm + +def enumPairsEquiv {m : ℕ} (n : Fin m → ℕ) : Fin (enumPairs n).length ≃ (z : Fin m) × Fin (n z) := + (List.Nodup.getEquiv _ (nodup_enumPairs n)).trans { + toFun := fun x => ⟨x.val.1,⟨x.val.2,(mem_enumPairs n _ _).mp x.property⟩⟩ + invFun := fun x => ⟨(x.1,x.2.val),(mem_enumPairs n _ _).mpr x.2.isLt⟩ + left_inv := by intro x; rfl + right_inv := by intro x; rfl } + +@[simp] lemma enumPairsEquiv_fst {m : ℕ} (n : Fin m → ℕ) (i : Fin (enumPairs n).length) : + (enumPairsEquiv n i).1 = ((enumPairs n).get i).1 := rfl +@[simp] lemma enumPairsEquiv_snd {m : ℕ} (n : Fin m → ℕ) (i : Fin (enumPairs n).length) : + (enumPairsEquiv n i).2.val = ((enumPairs n).get i).2 := rfl + +abbrev GlobalTag (t : ℕ) (b : TemplateVertex t → Bit) := (a : TemplateVertex t) × Tag (template t) b a + +abbrev TagIndex (t : ℕ) (b : TemplateVertex t → Bit) := Fin (Fintype.card (GlobalTag t b)) + +noncomputable def tagDecode (t : ℕ) (b : TemplateVertex t → Bit) : TagIndex t b ≃ GlobalTag t b := + (Fintype.equivFin (GlobalTag t b)).symm + +noncomputable def ChoiceData.globalLiftEquiv {t : ℕ} (D : ChoiceData t) (b : TemplateVertex t → Bit) : + ((z : GlobalTag t b) × Fin (D.roleSize z.1)) ≃ + LiftVertex (template t) (baseGraph D.system) (baseProjection D.system) b where + toFun x := match x with + | ⟨⟨.inl i,z⟩,d⟩ => ⟨.inl ⟨i,d⟩,z⟩ + | ⟨⟨.inr h,z⟩,q⟩ => ⟨.inr ⟨h,q⟩,z⟩ + invFun x := match x with + | ⟨.inl ⟨i,d⟩,z⟩ => ⟨⟨.inl i,z⟩,d⟩ + | ⟨.inr ⟨h,q⟩,z⟩ => ⟨⟨.inr h,z⟩,q⟩ + left_inv := by rintro ⟨⟨i,z⟩,d⟩; cases i <;> rfl + right_inv := by rintro ⟨x,z⟩; rcases x with ⟨i,d⟩ | ⟨h,q⟩ <;> rfl + +noncomputable def ChoiceData.indexSize {t : ℕ} (D : ChoiceData t) (b : TemplateVertex t → Bit) + (z : TagIndex t b) : ℕ := D.roleSize (tagDecode t b z).1 + +noncomputable def ChoiceData.vertices {t : ℕ} (D : ChoiceData t) (b : TemplateVertex t → Bit) : + List (TagIndex t b × ℕ) := enumPairs (D.indexSize b) + +noncomputable def ChoiceData.vertexEquiv {t : ℕ} (D : ChoiceData t) (b : TemplateVertex t → Bit) : + Fin (D.vertices b).length ≃ LiftVertex (template t) (baseGraph D.system) (baseProjection D.system) b := + (enumPairsEquiv (D.indexSize b)).trans + ((Equiv.sigmaCongrLeft (β := fun z : GlobalTag t b => Fin (D.roleSize z.1)) (tagDecode t b)).trans + (D.globalLiftEquiv b)) + +noncomputable def ChoiceData.indexedGraph {t : ℕ} (D : ChoiceData t) (b : TemplateVertex t → Bit) : + SimpleGraph (Fin (D.vertices b).length) := + (liftGraph (template t) (baseGraph D.system) (baseProjection D.system) b).comap (D.vertexEquiv b) + +noncomputable def ChoiceData.indexedIso {t : ℕ} (D : ChoiceData t) (b : TemplateVertex t → Bit) : + D.indexedGraph b ≃g liftGraph (template t) (baseGraph D.system) (baseProjection D.system) b := + SimpleGraph.Iso.comap (D.vertexEquiv b) _ + +noncomputable def tagTest {t : ℕ} (b : TemplateVertex t → Bit) (x y : GlobalTag t b) : Bool := by + classical + exact if h : (template t).Adj x.1 y.1 then decide (x.2.1 ⟨y.1,h⟩ = y.2.1 ⟨x.1,h.symm⟩) else false + +noncomputable def ChoiceData.edgeTest {t : ℕ} (D : ChoiceData t) (b : TemplateVertex t → Bit) + (x y : TagIndex t b × ℕ) : Bool := + D.baseTest (tagDecode t b x.1).1 x.2 (tagDecode t b y.1).1 y.2 && + tagTest b (tagDecode t b x.1) (tagDecode t b y.1) + +lemma ChoiceData.lift_arc_iff {t : ℕ} (D : ChoiceData t) (b : TemplateVertex t → Bit) + (x y : LiftVertex (template t) (baseGraph D.system) (baseProjection D.system) b) : + (liftGraph (template t) (baseGraph D.system) (baseProjection D.system) b).Adj x y ↔ + D.baseTest (baseType x.1) (D.baseIndex x.1) (baseType y.1) (D.baseIndex y.1) = true ∧ + tagTest b ⟨baseType x.1,x.2⟩ ⟨baseType y.1,y.2⟩ = true := by + classical + rw [D.baseTest_iff] + constructor + · rintro ⟨h,he⟩ + refine ⟨h, ?_⟩ + have ht : (template t).Adj (baseType x.1) (baseType y.1) := + (baseProjection D.system).map_adj h + simp only [tagTest, ht, ↓reduceDIte, decide_eq_true_eq] + exact he + · rintro ⟨h,he⟩ + refine ⟨h, ?_⟩ + have ht : (template t).Adj (baseType x.1) (baseType y.1) := + (baseProjection D.system).map_adj h + simp only [tagTest, ht, ↓reduceDIte, decide_eq_true_eq] at he + exact he + +lemma ChoiceData.globalLift_raw {t : ℕ} (D : ChoiceData t) (b : TemplateVertex t → Bit) + (x : (z : GlobalTag t b) × Fin (D.roleSize z.1)) : + (⟨baseType (D.globalLiftEquiv b x).1,(D.globalLiftEquiv b x).2⟩ : GlobalTag t b) = x.1 ∧ + D.baseIndex (D.globalLiftEquiv b x).1=x.2.val := by + rcases x with ⟨⟨a,z⟩,d⟩ + cases a <;> exact ⟨rfl,rfl⟩ + +lemma ChoiceData.vertexEquiv_raw {t : ℕ} (D : ChoiceData t) (b : TemplateVertex t → Bit) + (i : Fin (D.vertices b).length) : + (⟨baseType (D.vertexEquiv b i).1,(D.vertexEquiv b i).2⟩ : GlobalTag t b) = + tagDecode t b ((D.vertices b).get i).1 ∧ + D.baseIndex (D.vertexEquiv b i).1=((D.vertices b).get i).2 := by + exact D.globalLift_raw b _ + +lemma ChoiceData.indexed_adj {t : ℕ} (D : ChoiceData t) (b : TemplateVertex t → Bit) + (i j : Fin (D.vertices b).length) : + (D.indexedGraph b).Adj i j ↔ D.edgeTest b ((D.vertices b).get i) ((D.vertices b).get j) = true := by + change (liftGraph (template t) (baseGraph D.system) (baseProjection D.system) b).Adj _ _ ↔ _ + rw [D.lift_arc_iff] + obtain ⟨hx,hxi⟩ := D.vertexEquiv_raw b i + obtain ⟨hy,hyi⟩ := D.vertexEquiv_raw b j + have hx' : baseType (D.vertexEquiv b i).1 = (tagDecode t b ((D.vertices b).get i).1).1 := congrArg Sigma.fst hx + have hy' : baseType (D.vertexEquiv b j).1 = (tagDecode t b ((D.vertices b).get j).1).1 := congrArg Sigma.fst hy + simp only [edgeTest, Bool.and_eq_true, hx, hy, hx', hy', hxi, hyi] + +end ParityWL.Complexity + +end OAI diff --git a/lean/OAI/Combinatorics/ParityLifts/TagSizes.lean b/lean/OAI/Combinatorics/ParityLifts/TagSizes.lean new file mode 100644 index 0000000000000000000000000000000000000000..592f00bb54192005df49a9d831ec2b8aadffe877 --- /dev/null +++ b/lean/OAI/Combinatorics/ParityLifts/TagSizes.lean @@ -0,0 +1,311 @@ +import OAI.Combinatorics.ParityLifts.BagTrees + +namespace OAI + +namespace ParityWL + +open scoped BigOperators + +section TagSizes + +open scoped Classical + +variable {I : Type} [Fintype I] + +lemma sum_split_at (a : I) (f : I → Bit) : + ∑ i, f i = f a + ∑ i : {i : I // i ≠ a}, f i := by + have hs := (Fintype.sum_subtype_add_sum_subtype (fun i => i = a) f).symm + simp only [Fintype.sum_unique] at hs + simpa only [(default : {i : I // i = a}).property] using hs + +noncomputable def sumFiberEquiv (a : I) (b : Bit) : + {f : I → Bit // ∑ i, f i = b} ≃ ({i : I // i ≠ a} → Bit) where + toFun f i := f.1 i + invFun f := ⟨fun i => if h : i = a then b - ∑ j, f j else f ⟨i, h⟩, by + rw [sum_split_at a] + have he : (∑ i : {i : I // i ≠ a}, + if h : (i : I) = a then b - ∑ j, f j else f ⟨i, h⟩) = ∑ i, f i := by + apply Finset.sum_congr rfl + intro i _ + simp only [dite_eq_right i.property] + rw [he] + rw [dite_eq_left rfl] + exact sub_add_cancel b (∑ j, f j)⟩ + left_inv := by + intro f + apply Subtype.ext + funext i + by_cases h : i = a + · subst i + dsimp only + rw [dite_eq_left rfl] + have hf := f.2 + rw [sum_split_at a] at hf + exact eq_sub_of_add_eq hf |>.symm + · simp [h] + right_inv := by + intro f + funext i + simp [i.property] + +lemma card_sumFiber (a : I) (b : Bit) : + Fintype.card {f : I → Bit // ∑ i, f i = b} = 2 ^ (Fintype.card I - 1) := by + rw [Fintype.card_congr (sumFiberEquiv a b), Fintype.card_fun, ZMod.card] + congr 1 + simp [Fintype.card_subtype_compl] + +lemma card_tag {A : Type} [Fintype A] (T : SimpleGraph A) (b : A → Bit) + (a : A) (h : (T.neighborSet a).Nonempty) : + Fintype.card (Tag T b a) = 2 ^ (Fintype.card (T.neighborSet a) - 1) := by + classical + obtain ⟨i, hi⟩ := h + exact Fintype.card_congr (sumFiberEquiv (⟨i, hi⟩ : T.neighborSet a) (b a)) |>.trans (by + rw [Fintype.card_fun, ZMod.card, Fintype.card_subtype_compl, Fintype.card_subtype_eq]) + +lemma template_positive_degree {t : ℕ} (ht : 2 ≤ t) (a : TemplateVertex t) : + ((template t).neighborSet a).Nonempty := by + cases a with + | inl i => + by_cases hi : i.val = 0 + · refine ⟨.inl ⟨1, by omega⟩, ?_⟩ + change i ≠ ⟨1, by omega⟩ + intro h + have hh := congrArg Fin.val h + change i.val = 1 at hh + omega + · refine ⟨.inl ⟨0, by omega⟩, ?_⟩ + change i ≠ ⟨0, by omega⟩ + intro h + exact hi (congrArg Fin.val h) + | inr h => exact ⟨.inl h.1.1.1.1, Or.inl rfl⟩ + +lemma lift_card_eq {A V : Type} [Fintype A] [Fintype V] + (T : SimpleGraph A) (G : SimpleGraph V) (τ : G →g T) (b c : A → Bit) + (h : ∀ a, (T.neighborSet a).Nonempty) : + Fintype.card (LiftVertex T G τ b) = Fintype.card (LiftVertex T G τ c) := by + simp only [LiftVertex, Fintype.card_sigma] + apply Finset.sum_congr rfl + intro u _ + rw [card_tag T b (τ u) (h _), card_tag T c (τ u) (h _)] + +lemma choice_lifts_equal_order {t : ℕ} (ht : 2 ≤ t) (C : ChoiceSystem t) : + Fintype.card (LiftVertex (template t) (baseGraph C) (baseProjection C) (fun _ => 0)) = + Fintype.card (LiftVertex (template t) (baseGraph C) (baseProjection C) (starParity t)) := + lift_card_eq _ _ _ _ _ (template_positive_degree ht) + +noncomputable def mainPairEquiv (t : ℕ) : MainPair t ≃ ((j : Fin t) × Fin j.val) where + toFun p := ⟨p.1.2, ⟨p.1.1.val, p.2⟩⟩ + invFun p := ⟨(⟨p.2.val, p.2.isLt.trans p.1.isLt⟩, p.1), p.2.isLt⟩ + left_inv _p := rfl + right_inv _p := rfl + +lemma card_mainPair (t : ℕ) : Fintype.card (MainPair t) = t.choose 2 := by + rw [Fintype.card_congr (mainPairEquiv t), Fintype.card_sigma] + simp only [Fintype.card_fin] + rw [Fin.sum_univ_eq_sum_range (fun n => n), Finset.sum_range_id, Nat.choose_two_right] + +lemma card_avoid_two {J : Type} [Fintype J] [DecidableEq J] (a b : J) (hab : a ≠ b) : + Fintype.card {i : J // i ≠ a ∧ i ≠ b} = Fintype.card J - 2 := by + have he : Fintype.card {i : J // i = a ∨ i = b} = 2 := by + have h := Fintype.card_coe ({a, b} : Finset J) + simpa [hab] using h + have h := Fintype.card_subtype_compl (fun i : J => i = a ∨ i = b) + simpa only [not_or, he] using h + +noncomputable def helperSigmaEquiv (t : ℕ) : + Helper t ≃ ((p : MainPair t) × {i : Fin t // i ≠ p.1.1 ∧ i ≠ p.1.2}) where + toFun h := ⟨h.1.1, ⟨h.1.2, h.2⟩⟩ + invFun h := ⟨(h.1, h.2.1), h.2.2⟩ + left_inv _h := rfl + right_inv _h := rfl + +lemma card_helper (t : ℕ) : Fintype.card (Helper t) = 3 * t.choose 3 := by + rw [Fintype.card_congr (helperSigmaEquiv t), Fintype.card_sigma] + have h : ∀ p : MainPair t, + Fintype.card {i : Fin t // i ≠ p.1.1 ∧ i ≠ p.1.2} = t - 2 := by + intro p + simpa using card_avoid_two p.1.1 p.1.2 (ne_of_lt p.2) + simp_rw [h] + simp only [Finset.sum_const, Finset.card_univ, smul_eq_mul, card_mainPair] + simpa only [Nat.mul_comm] using (Nat.choose_succ_right_eq t 2).symm + +abbrev OrderedPair (J : Type) [LT J] := {p : J × J // p.1 < p.2} + +noncomputable def orderedPairEquiv {J : Type} [Fintype J] [LinearOrder J] : + OrderedPair J ≃ MainPair (Fintype.card J) := by + let e := (Fintype.orderIsoFinOfCardEq J rfl).symm + exact + { toFun := fun p => ⟨(e p.1.1, e p.1.2), e.strictMono p.2⟩ + invFun := fun p => ⟨(e.symm p.1.1, e.symm p.1.2), e.symm.strictMono p.2⟩ + left_inv := by intro p; apply Subtype.ext; simp + right_inv := by intro p; apply Subtype.ext; simp } + +lemma card_orderedPair {J : Type} [Fintype J] [LinearOrder J] : + Fintype.card (OrderedPair J) = (Fintype.card J).choose 2 := by + rw [Fintype.card_congr orderedPairEquiv, card_mainPair] + +abbrev PairsThrough {t : ℕ} (i : Fin t) := + {p : MainPair t // i = p.1.1 ∨ i = p.1.2} + +noncomputable def pairOther {t : ℕ} (i : Fin t) (p : PairsThrough i) : + {j : Fin t // j ≠ i} := + if h : i = p.1.1.1 then + ⟨p.1.1.2, fun he => (ne_of_lt p.1.2) (h.symm.trans he.symm)⟩ + else ⟨p.1.1.1, fun he => h he.symm⟩ + +lemma pairOther_injective {t : ℕ} (i : Fin t) : Function.Injective (pairOther i) := by + intro p q hpq + have he := congrArg Subtype.val hpq + dsimp only [pairOther] at he + apply Subtype.ext + apply Subtype.ext + by_cases hp : i = p.1.1.1 <;> by_cases hq : i = q.1.1.1 + · simp only [dite_eq_left hp, dite_eq_left hq] at he + exact Prod.ext (hp.symm.trans hq) he + · simp only [dite_eq_left hp, dite_eq_right hq] at he + have hq' : i = q.1.1.2 := q.2.resolve_left hq + have hlt := p.1.2 + have hlt' := q.1.2 + rw [← hp, he] at hlt + rw [← hq'] at hlt' + exact (lt_asymm hlt hlt').elim + · simp only [dite_eq_right hp, dite_eq_left hq] at he + have hp' : i = p.1.1.2 := p.2.resolve_left hp + have hlt := p.1.2 + have hlt' := q.1.2 + rw [← hp'] at hlt + rw [← hq, ← he] at hlt' + exact (lt_asymm hlt hlt').elim + · simp only [dite_eq_right hp, dite_eq_right hq] at he + exact Prod.ext he ((p.2.resolve_left hp).symm.trans (q.2.resolve_left hq)) + +lemma card_pairsThrough_le {t : ℕ} (i : Fin t) : + Fintype.card (PairsThrough i) ≤ t - 1 := by + have h := Fintype.card_le_of_injective _ (pairOther_injective i) + simpa [Fintype.card_subtype_compl] using h + +noncomputable def helperThirdEquiv {t : ℕ} (i : Fin t) : + {h : Helper t // i = h.1.2} ≃ OrderedPair {j : Fin t // j ≠ i} where + toFun h := ⟨(⟨h.1.1.1.1.1, by simpa [h.2] using h.1.2.1.symm⟩, + ⟨h.1.1.1.1.2, by simpa [h.2] using h.1.2.2.symm⟩), h.1.1.1.2⟩ + invFun p := ⟨⟨(⟨(p.1.1.1, p.1.2.1), p.2⟩, i), + ⟨p.1.1.2.symm, p.1.2.2.symm⟩⟩, rfl⟩ + left_inv h := by apply Subtype.ext; apply Subtype.ext; exact Prod.ext rfl h.2 + right_inv p := rfl + +noncomputable def helperEndpointEquiv {t : ℕ} (i : Fin t) : + {h : Helper t // i = h.1.1.1.1 ∨ i = h.1.1.1.2} ≃ + ((p : PairsThrough i) × {j : Fin t // j ≠ p.1.1.1 ∧ j ≠ p.1.1.2}) where + toFun h := ⟨⟨h.1.1.1, h.2⟩, ⟨h.1.1.2, h.1.2⟩⟩ + invFun p := ⟨⟨(p.1.1, p.2.1), p.2.2⟩, p.1.2⟩ + left_inv _h := rfl + right_inv _p := rfl + +lemma card_helpersIncident_le {t : ℕ} (i : Fin t) : + Fintype.card {h : Helper t // helperIncident h i} ≤ 3 * (t - 1).choose 2 := by + have he : Fintype.card {h : Helper t // i = h.1.1.1.1 ∨ i = h.1.1.1.2} ≤ + (t - 1) * (t - 2) := by + rw [Fintype.card_congr (helperEndpointEquiv i), Fintype.card_sigma] + have hc : ∀ p : PairsThrough i, + Fintype.card {j : Fin t // j ≠ p.1.1.1 ∧ j ≠ p.1.1.2} = t - 2 := + fun p => by simpa using card_avoid_two p.1.1.1 p.1.1.2 (ne_of_lt p.1.2) + simp_rw [hc] + simpa only [Finset.sum_const, Finset.card_univ, smul_eq_mul] using + Nat.mul_le_mul_right (t - 2) (card_pairsThrough_le i) + have ht : Fintype.card {h : Helper t // i = h.1.2} = (t - 1).choose 2 := by + rw [Fintype.card_congr (helperThirdEquiv i), card_orderedPair] + simp [Fintype.card_subtype_compl] + have h := Fintype.card_subtype_or + (fun h : Helper t => i = h.1.1.1.1 ∨ i = h.1.1.1.2) + (fun h : Helper t => i = h.1.2) + have h' : Fintype.card {h : Helper t // helperIncident h i} ≤ + (t - 1) * (t - 2) + (t - 1).choose 2 := by + have h0 : Fintype.card {h : Helper t // helperIncident h i} ≤ + Fintype.card {h : Helper t // i = h.1.1.1.1 ∨ i = h.1.1.1.2} + + Fintype.card {h : Helper t // i = h.1.2} := by + have hc := Fintype.card_congr (Equiv.subtypeEquivRight (fun h : Helper t => + show helperIncident h i ↔ (i = h.1.1.1.1 ∨ i = h.1.1.1.2) ∨ i = h.1.2 + from or_assoc.symm)) + exact hc.le.trans h + exact h0.trans (Nat.add_le_add he ht.le) + have hc := Nat.choose_succ_right_eq (t - 1) 1 + simp only [Nat.choose_one_right, Nat.sub_sub, Nat.reduceAdd] at hc + omega + +noncomputable def templateMainNeighbors {t : ℕ} (i : Fin t) : + (template t).neighborSet (.inl i) ≃ + ({j : Fin t // j ≠ i} ⊕ {h : Helper t // helperIncident h i}) where + toFun v := match v with + | ⟨.inl j, h⟩ => .inl ⟨j, (show i ≠ j from h).symm⟩ + | ⟨.inr h, e⟩ => .inr ⟨h, e⟩ + invFun v := match v with + | .inl j => ⟨.inl j.1, j.2.symm⟩ + | .inr h => ⟨.inr h.1, h.2⟩ + left_inv v := by rcases v with ⟨v, hv⟩; cases v <;> rfl + right_inv v := by cases v <;> rfl + +lemma template_degree_main_le {t : ℕ} (i : Fin t) : + Fintype.card ((template t).neighborSet (.inl i)) ≤ + t - 1 + 3 * (t - 1).choose 2 := by + rw [Fintype.card_congr (templateMainNeighbors i), Fintype.card_sum] + have h : Fintype.card {j : Fin t // j ≠ i} = t - 1 := by + simp [Fintype.card_subtype_compl] + rw [h] + exact Nat.add_le_add_left (card_helpersIncident_le i) _ + +lemma template_degree_helper {t : ℕ} (h : Helper t) : + Fintype.card ((template t).neighborSet (.inr h)) = 3 := by + let s : Finset (TemplateVertex t) := + {.inl h.1.1.1.1, .inl h.1.1.1.2, .inl h.1.2} + have hs : ∀ v, v ∈ s ↔ v ∈ (template t).neighborSet (.inr h) := by + intro v + cases v <;> simp [s, template, templateAdj, helperIncident] + rw [Fintype.card_of_finset' s hs] + simp [s, ne_of_lt h.1.1.2, h.2.1.symm, h.2.2.symm] + +lemma tag_main_bound {t : ℕ} (ht : 2 ≤ t) (b : TemplateVertex t → Bit) + (i : Fin t) : + Fintype.card (Tag (template t) b (.inl i)) ≤ + 2 ^ (t - 2 + 3 * (t - 1).choose 2) := by + rw [card_tag _ _ _ (template_positive_degree ht _)] + apply Nat.pow_le_pow_right (by omega) + have h := template_degree_main_le i + omega + +lemma tag_helper_card {t : ℕ} (ht : 2 ≤ t) (b : TemplateVertex t → Bit) + (h : Helper t) : Fintype.card (Tag (template t) b (.inr h)) = 4 := by + rw [card_tag _ _ _ (template_positive_degree ht _), template_degree_helper] + norm_num + +lemma choice_lift_order_bound {t : ℕ} (ht : 2 ≤ t) (C : ChoiceSystem t) + (A : ℕ) (hA : C.SizeAtMost A) (b : TemplateVertex t → Bit) : + Fintype.card (LiftVertex (template t) (baseGraph C) (baseProjection C) b) ≤ + A * orderFactor t := by + let q := 2 ^ (t - 2 + 3 * (t - 1).choose 2) + rw [Fintype.card_sigma] + change (∑ u : BaseVertex C, Fintype.card (Tag (template t) b (baseType u))) ≤ _ + rw [Fintype.sum_sum_type] + rw [Fintype.sum_sigma, Fintype.sum_sigma] + change (∑ i : Fin t, ∑ _d : C.Domain i, Fintype.card (Tag (template t) b (.inl i))) + + (∑ h : Helper t, ∑ _c : C.Label h.1.1, Fintype.card (Tag (template t) b (.inr h))) ≤ _ + simp only [Finset.sum_const, Finset.card_univ, smul_eq_mul] + calc + _ ≤ (∑ _i : Fin t, A * q) + (∑ _h : Helper t, A * 4) := by + apply Nat.add_le_add + · apply Finset.sum_le_sum + intro i _ + exact Nat.mul_le_mul (hA.1 i) (tag_main_bound ht b i) + · apply Finset.sum_le_sum + intro h _ + rw [tag_helper_card ht] + exact Nat.mul_le_mul_right 4 (hA.2 h.1.1) + _ = A * orderFactor t := by + simp only [Finset.sum_const, Finset.card_univ, smul_eq_mul, Fintype.card_fin, card_helper] + dsimp only [q, orderFactor] + ring + +end TagSizes + +end ParityWL + +end OAI diff --git a/lean/OAI/Combinatorics/ParityLifts/TestAlgebra.lean b/lean/OAI/Combinatorics/ParityLifts/TestAlgebra.lean new file mode 100644 index 0000000000000000000000000000000000000000..c5c26209f1201257fac856cfce30a7a06416e733 --- /dev/null +++ b/lean/OAI/Combinatorics/ParityLifts/TestAlgebra.lean @@ -0,0 +1,237 @@ +import OAI.Combinatorics.ParityLifts.Rerooting + +namespace OAI + +namespace ParityWL + +open scoped BigOperators + +section AtomicTests + +open scoped Classical + +variable {k t : ℕ} + +def EqRootRel (i j a b : Fin k) : Prop := a = i ∧ b = j + +def EqRoot (i j : Fin k) := Quot (EqRootRel i j) + +noncomputable instance eqRootFintype (i j : Fin k) : Fintype (EqRoot i j) := + Fintype.ofSurjective (Quot.mk (EqRootRel i j)) + (fun q => Quot.inductionOn q (fun a => ⟨a, rfl⟩)) + +noncomputable def equalityTest (hkt : k ≤ t) (i j : Fin k) : RootedTest k t := by + letI : Fintype (Quot (EqRootRel i j)) := eqRootFintype i j + exact singleBagTest (A := EqRoot i j) (fun _ _ : EqRoot i j => False) ⟨fun _ _ h => h⟩ + (Quot.mk (EqRootRel i j)) (fun q => Quot.inductionOn q (fun a => ⟨a, rfl⟩)) + ((Fintype.card_le_of_surjective (fun a : Fin k => (Quot.mk (EqRootRel i j) a : EqRoot i j)) + (fun q => Quot.inductionOn q (fun a => ⟨a, rfl⟩))).trans (by simpa using hkt)) + +lemma equalityTest_count (hkt : k ≤ t) (i j : Fin k) {V : Type} [Fintype V] + (G : SimpleGraph V) (x : Fin k → V) : + (equalityTest hkt i j).count G x = if x i = x j then 1 else 0 := by + by_cases h : x i = x j + · rw [ite_eq_left h] + let f : (equalityTest hkt i j).Maps G x := + ⟨⟨Quot.lift x (by rintro a b ⟨rfl, rfl⟩; exact h), fun _ _ h => h.elim⟩, + fun _ => rfl⟩ + have : Unique ((equalityTest hkt i j).Maps G x) := + { default := f + uniq := by + intro g + apply Subtype.ext + apply Subtype.ext + funext q + induction q using Quot.inductionOn with + | h a => exact g.2 a } + simp only [RootedTest.count, Fintype.card_unique, Nat.cast_one] + · rw [ite_eq_right h] + have : IsEmpty ((equalityTest hkt i j).Maps G x) := ⟨by + intro g + apply h + rw [← g.2 i, ← g.2 j] + apply congrArg g.1.1 + exact Quot.sound ⟨rfl, rfl⟩⟩ + simp only [RootedTest.count, Fintype.card_eq_zero, Nat.cast_zero] + +noncomputable def edgeTest (hkt : k ≤ t) (i j : Fin k) : RootedTest k t := + singleBagTest (fun a b : Fin k => (a = i ∧ b = j) ∨ (a = j ∧ b = i)) + ⟨by rintro a b (⟨rfl, rfl⟩ | ⟨rfl, rfl⟩) + <;> simp only [true_and, true_or, or_true]⟩ + id Function.surjective_id (by simpa using hkt) + +lemma edgeTest_count (hkt : k ≤ t) (i j : Fin k) {V : Type} [Fintype V] + (G : SimpleGraph V) (x : Fin k → V) : + (edgeTest hkt i j).count G x = if G.Adj (x i) (x j) then 1 else 0 := by + by_cases h : G.Adj (x i) (x j) + · rw [ite_eq_left h] + let f : (edgeTest hkt i j).Maps G x := ⟨⟨x, by + intro a b hab + change (a = i ∧ b = j) ∨ (a = j ∧ b = i) at hab + rcases hab with ⟨hai, hbj⟩ | ⟨haj, hbi⟩ + · rw [hai, hbj]; exact h + · rw [haj, hbi]; exact h.symm⟩, fun _ => rfl⟩ + have : Unique ((edgeTest hkt i j).Maps G x) := + { default := f + uniq := by + intro g + apply Subtype.ext + apply Subtype.ext + funext a + exact g.2 a } + simp only [RootedTest.count, Fintype.card_unique, Nat.cast_one] + · rw [ite_eq_right h] + have : IsEmpty ((edgeTest hkt i j).Maps G x) := ⟨by + intro g + apply h + rw [← g.2 i, ← g.2 j] + exact g.1.2 i j (.inl ⟨rfl, rfl⟩)⟩ + simp only [RootedTest.count, Fintype.card_eq_zero, Nat.cast_zero] + +end AtomicTests + +section TestAlgebra + +open scoped Classical + +abbrev TuplePair (V W : Type) (k : ℕ) := (Fin k → V) ⊕ (Fin k → W) + +variable {V W : Type} [Fintype V] [Fintype W] (G : SimpleGraph V) (H : SimpleGraph W) + +noncomputable def testEval {k t : ℕ} (F : RootedTest k t) : TuplePair V W k → ℚ := + Sum.elim (F.count G) (F.count H) + +noncomputable def testSpan (k t : ℕ) : Submodule ℚ (TuplePair V W k → ℚ) := + Submodule.span ℚ (Set.range (fun F : RootedTest k t => testEval G H F)) + +lemma testEval_mem {k t : ℕ} (F : RootedTest k t) : testEval G H F ∈ testSpan G H k t := + Submodule.subset_span ⟨F, rfl⟩ + +lemma testSpan_one {k t : ℕ} (hkt : k ≤ t) : (1 : TuplePair V W k → ℚ) ∈ testSpan G H k t := by + have he : testEval G H (isolatedTest k t hkt) = 1 := by + funext a + cases a with + | inl x => exact isolatedTest_count k t hkt G x + | inr x => exact isolatedTest_count k t hkt H x + rw [← he] + exact testEval_mem _ _ _ + +lemma testEval_mul_mem {k t : ℕ} (hkt : k ≤ t) (F L : RootedTest k t) : + testEval G H F * testEval G H L ∈ testSpan G H k t := by + let Fs : Fin 2 → RootedTest k t := ![F, L] + let P := glueTest Fs (fun _ => id) hkt + have he : testEval G H P = testEval G H F * testEval G H L := by + funext a + cases a with + | inl x => + change P.count G x = F.count G x * L.count G x + simp only [P, glueTest_count, Fin.prod_univ_two, Fs, Matrix.cons_val_zero, + Matrix.cons_val_one, Function.comp_id] + | inr x => + change P.count H x = F.count H x * L.count H x + simp only [P, glueTest_count, Fin.prod_univ_two, Fs, Matrix.cons_val_zero, + Matrix.cons_val_one, Function.comp_id] + rw [← he] + exact testEval_mem _ _ _ + +lemma testSpan_mul {k t : ℕ} (hkt : k ≤ t) {f g : TuplePair V W k → ℚ} + (hf : f ∈ testSpan G H k t) (hg : g ∈ testSpan G H k t) : f * g ∈ testSpan G H k t := by + refine Submodule.span_induction₂ (p := fun f g _ _ => f * g ∈ testSpan G H k t) + ?_ ?_ ?_ ?_ ?_ ?_ ?_ hf hg + · rintro _ _ ⟨F, rfl⟩ ⟨L, rfl⟩ + exact testEval_mul_mem G H hkt F L + · intro _ _ + simpa only [zero_mul] using (testSpan G H k t).zero_mem + · intro _ _ + simpa only [mul_zero] using (testSpan G H k t).zero_mem + · intro f g h _ _ _ hf hg + simpa only [add_mul] using (testSpan G H k t).add_mem hf hg + · intro f g h _ _ _ hf hg + simpa only [mul_add] using (testSpan G H k t).add_mem hf hg + · intro a f g _ _ hf + simpa only [smul_mul_assoc] using (testSpan G H k t).smul_mem a hf + · intro a f g _ _ hf + simpa only [mul_smul_comm] using (testSpan G H k t).smul_mem a hf + +noncomputable def testAlgebra (k t : ℕ) (hkt : k ≤ t) : Subalgebra ℚ (TuplePair V W k → ℚ) where + carrier := testSpan G H k t + mul_mem' := testSpan_mul G H hkt + one_mem' := testSpan_one G H hkt + add_mem' := (testSpan G H k t).add_mem + zero_mem' := (testSpan G H k t).zero_mem + algebraMap_mem' a := by + rw [Algebra.algebraMap_eq_smul_one] + exact (testSpan G H k t).smul_mem a (testSpan_one G H hkt) + +end TestAlgebra + +section TestOperations + +open scoped Classical + +variable {V W : Type} [Fintype V] [Fintype W] +variable (G : SimpleGraph V) (H : SimpleGraph W) + +def tupleReindex {k m : ℕ} (φ : Fin k → Fin m) : TuplePair V W m → TuplePair V W k := + Sum.map (fun x => x ∘ φ) (fun x => x ∘ φ) + +noncomputable def reindexLinear {k m : ℕ} (φ : Fin k → Fin m) : + (TuplePair V W k → ℚ) →ₗ[ℚ] (TuplePair V W m → ℚ) where + toFun f := f ∘ tupleReindex φ + map_add' _ _ := rfl + map_smul' _ _ := rfl + +lemma testSpan_reindex {k m t : ℕ} (hm : m ≤ t) (φ : Fin k → Fin m) + {f : TuplePair V W k → ℚ} (hf : f ∈ testSpan G H k t) : + reindexLinear φ f ∈ testSpan G H m t := by + have h : testSpan G H k t ≤ (testSpan G H m t).comap (reindexLinear φ) := by + apply Submodule.span_le.mpr + rintro _ ⟨F, rfl⟩ + let P := glueTest (fun _ : Unit => F) (fun _ => φ) hm + have he : reindexLinear φ (testEval G H F) = testEval G H P := by + funext a + cases a with + | inl x => + change F.count G (x ∘ φ) = P.count G x + simp only [P, glueTest_count, Fintype.prod_unique] + | inr x => + change F.count H (x ∘ φ) = P.count H x + simp only [P, glueTest_count, Fintype.prod_unique] + change reindexLinear φ (testEval G H F) ∈ testSpan G H m t + rw [he] + exact testEval_mem _ _ _ + exact h hf + +noncomputable def sumInsertLinear {k : ℕ} (i : Fin (k + 1)) : + (TuplePair V W (k + 1) → ℚ) →ₗ[ℚ] (TuplePair V W k → ℚ) where + toFun f := Sum.elim (fun x => ∑ y : V, f (.inl (i.insertNth y x))) + (fun x => ∑ y : W, f (.inr (i.insertNth y x))) + map_add' f g := by + funext a + cases a <;> simp only [Sum.elim_inl, Sum.elim_inr, Pi.add_apply, Finset.sum_add_distrib] + map_smul' a f := by + funext x + cases x <;> simp only [Sum.elim_inl, Sum.elim_inr, Pi.smul_apply, Finset.smul_sum, + RingHom.id_apply] + +lemma testSpan_sumInsert {k t : ℕ} (hk : k < t) (i : Fin (k + 1)) + {f : TuplePair V W (k + 1) → ℚ} (hf : f ∈ testSpan G H (k + 1) t) : + sumInsertLinear i f ∈ testSpan G H k t := by + have h : testSpan G H (k + 1) t ≤ (testSpan G H k t).comap (sumInsertLinear i) := by + apply Submodule.span_le.mpr + rintro _ ⟨F, rfl⟩ + have he : sumInsertLinear i (testEval G H F) = testEval G H (reRootTest F i.succAbove hk) := by + funext a + cases a with + | inl x => exact (reRootTest_count F i hk G x).symm + | inr x => exact (reRootTest_count F i hk H x).symm + change sumInsertLinear i (testEval G H F) ∈ testSpan G H k t + rw [he] + exact testEval_mem _ _ _ + exact h hf + +end TestOperations + +end ParityWL + +end OAI diff --git a/lean/OAI/Combinatorics/ParityLifts/TreeMachine.lean b/lean/OAI/Combinatorics/ParityLifts/TreeMachine.lean new file mode 100644 index 0000000000000000000000000000000000000000..de2d17b3b4c298f32a0cc4067528d9ea7be5d40c --- /dev/null +++ b/lean/OAI/Combinatorics/ParityLifts/TreeMachine.lean @@ -0,0 +1,353 @@ +import OAI.Combinatorics.ParityLifts.TreeRoutines + +namespace OAI + +namespace ParityWL.Complexity + +structure FinStack (t a : ℕ) where + State : Type + finite : Fintype State + program : StackMachine State t a + +attribute [instance] FinStack.finite + +def FinStack.of {Q : Type} [Fintype Q] {t a : ℕ} (P : StackMachine Q t a) : FinStack t a := + ⟨Q, inferInstance, P⟩ + +def dataReg {r : ℕ} (i : Fin r) : Fin (r + 3 + 1) := Fin.castAdd 4 i + +def workReg (r : ℕ) (i : Fin 4) : Fin (r + 3 + 1) := Fin.natAdd r i + +lemma dataReg_ne_workReg {r : ℕ} (i : Fin r) (j : Fin 4) : dataReg i ≠ workReg r j := by + intro h + have := congrArg Fin.val h + dsimp [dataReg, workReg] at this + omega + +lemma workReg_injective (r : ℕ) : Function.Injective (workReg r) := by + intro i j h + apply Fin.ext + have := congrArg Fin.val h + dsimp [workReg] at this + omega + +def dataWords {r : ℕ} (d : Fin r → DataTree) : Words (r + 3) 0 := + Fin.append (m := r) (n := 4) (fun i => (d i).code) (fun _ : Fin 4 => []) + +@[simp] lemma dataWords_data {r : ℕ} (d : Fin r → DataTree) (i : Fin r) : + dataWords d (dataReg i) = (d i).code := by simp [dataWords, dataReg] + +@[simp] lemma dataWords_work {r : ℕ} (d : Fin r → DataTree) (j : Fin 4) : + dataWords d (workReg r j) = [] := by simp [dataWords, workReg] + +lemma dataWords_update {r : ℕ} (d : Fin r → DataTree) (i : Fin r) (x : DataTree) : + dataWords (Function.update d i x) = Function.update (dataWords d) (dataReg i) x.code := by + funext j + refine Fin.addCases (m := r) (n := 4) (fun j => ?_) (fun j => ?_) j + · change dataWords (Function.update d i x) (dataReg j) = _ + change dataWords (Function.update d i x) (dataReg j) = + Function.update (dataWords d) (dataReg i) x.code (dataReg j) + by_cases he : j = i + · subst j; simp + · have hn : dataReg j ≠ dataReg i := by + intro h + apply he + have hv := congrArg (fun x : Fin (r + 3 + 1) => x.val) h + exact Fin.ext hv + simp [he, hn] + · change dataWords (Function.update d i x) (workReg r j) = + Function.update (dataWords d) (dataReg i) x.code (workReg r j) + simp [Ne.symm (dataReg_ne_workReg i j)] + +def dataMass {r : ℕ} (d : Fin r → DataTree) : ℕ := ∑ i, (d i).size + +lemma dataSize_le_mass {r : ℕ} (d : Fin r → DataTree) (i : Fin r) : + (d i).size ≤ dataMass d := by + exact Finset.single_le_sum (f := fun i => (d i).size) (fun _ _ => Nat.zero_le _) (Finset.mem_univ i) + +inductive TreeOp (r : ℕ) where + | skip + | nil (dst : Fin r) + | node (dst left right : Fin r) + | project (dst src : Fin r) (right : Bool) + | test (src : Fin r) + +def TreeOp.eval {r : ℕ} (op : TreeOp r) (d : Fin r → DataTree) : (Fin r → DataTree) × Bool := + match op with + | .skip => (d, true) + | .nil i => (Function.update d i .nil, true) + | .node i j k => (Function.update d i (.node (d j) (d k)), true) + | .project i j b => (Function.update d i ((d j).child b), true) + | .test i => (d, decide (d i = .nil)) + +def testNil {t : ℕ} (src : Fin (t + 1)) := + primitive (a := 0) (fun _ _ => .keep) (fun x => decide (x src = some 0)) + +lemma testNil_run {r : ℕ} (i : Fin r) (d : Fin r → DataTree) : + Runs (testNil (dataReg i)) (dataWords d) 1 (dataWords d) (decide (d i = .nil)) := by + have he : (dataWords d (dataReg i)).head? = some 0 ↔ d i = .nil := by + rw [dataWords_data] + cases d i <;> simp [DataTree.code] + have h := primitive_exec (fun (_ : Fin (r + 3 + 1) → Option (StackSymbol 0)) _ => + StackOp.keep) (fun x => decide (x (dataReg i) = some 0)) (dataWords d) + have hh : (fun i => (dataWords d i).head?) (dataReg i) = some 0 ↔ d i = .nil := he + simp only [hh] at h + exact ⟨some (decide (d i = .nil)), h⟩ + +def TreeOp.routine {r : ℕ} : TreeOp r → FinStack (r + 3) 0 + | .skip => .of (.halt true) + | .nil i => .of (nilWord (dataReg i)) + | .node i j k => .of (nodeWord (dataReg i) (dataReg j) (dataReg k) + (workReg r 0) (workReg r 1)) + | .project i j b => .of (projectWord (dataReg i) (dataReg j) + (workReg r 0) (workReg r 1) (workReg r 2) (workReg r 3) b) + | .test i => .of (testNil (dataReg i)) + +lemma TreeOp.routine_run {r : ℕ} (op : TreeOp r) (d : Fin r → DataTree) : + ∃ n, n ≤ 50 * (dataMass d + 1) ∧ + Runs op.routine.program (dataWords d) n (dataWords (op.eval d).1) (op.eval d).2 := by + have hw (i j : Fin 4) (h : i ≠ j) : workReg r i ≠ workReg r j := fun he => h (workReg_injective r he) + cases op with + | skip => exact ⟨0, by omega, halt_run true (dataWords d)⟩ + | nil i => + have h := nilWord_run (dataReg i) (dataWords d) + rw [dataWords_data, DataTree.length_code] at h + refine ⟨2 * (d i).size + 3, ?_, ?_⟩ + · have hi := dataSize_le_mass d i; omega + · simpa only [TreeOp.routine, FinStack.of, TreeOp.eval, dataWords_update, DataTree.code] using h + | node i j k => + have h := nodeWord_run (dataReg i) (dataReg j) (dataReg k) (workReg r 0) (workReg r 1) + (dataReg_ne_workReg i 0) (dataReg_ne_workReg i 1) + (dataReg_ne_workReg j 0) (dataReg_ne_workReg j 1) + (dataReg_ne_workReg k 0) (dataReg_ne_workReg k 1) (hw 0 1 (by decide)) + (dataWords d) (by simp) (by simp) + simp only [dataWords_data, DataTree.length_code] at h + refine ⟨10 * ((d j).size + (d k).size) + 2 * (d i).size + 23, ?_, ?_⟩ + · have hi := dataSize_le_mass d i + have hj := dataSize_le_mass d j + have hk := dataSize_le_mass d k + omega + · simpa only [TreeOp.routine, FinStack.of, TreeOp.eval, dataWords_update, DataTree.code] using h + | project i j b => + obtain ⟨n, hn, h⟩ := projectWord_run (dataReg i) (dataReg j) + (workReg r 0) (workReg r 1) (workReg r 2) (workReg r 3) + (dataReg_ne_workReg i 0) (dataReg_ne_workReg i 1) + (dataReg_ne_workReg j 0) (dataReg_ne_workReg j 1) + (hw 0 1 (by decide)) (hw 0 2 (by decide)) (hw 0 3 (by decide)) (hw 2 3 (by decide)) + b (d j) (dataWords d) (by simp) (by simp) (by simp) (by simp) (by simp) + simp only [dataWords_data, DataTree.length_code] at hn + refine ⟨n, ?_, ?_⟩ + · have hi := dataSize_le_mass d i + have hj := dataSize_le_mass d j + omega + · simpa only [TreeOp.routine, FinStack.of, TreeOp.eval, dataWords_update] using h + | test i => + exact ⟨1, by omega, testNil_run i d⟩ + +/-- Finite code over unbounded but explicitly serialized binary trees. -/ +structure TreeMachine (Q : Type) (r : ℕ) where + initial : Q + output : Q → Option Bool + instruction : Q → TreeOp r + next : Q → Bool → Q + +def TreeMachine.lower {Q : Type} {r : ℕ} (P : TreeMachine Q r) : MacroMachine Q (r + 3) 0 where + Control := fun q => (P.instruction q).routine.State + initial := P.initial + output := P.output + routine := fun q => (P.instruction q).routine.program + next := P.next + +instance {Q : Type} {r : ℕ} (P : TreeMachine Q r) (q : Q) : + Fintype (P.lower.Control q) := (P.instruction q).routine.finite + +/-- Work is the sum of one plus the size of all live data before each step. +The compiler bound below is linear in this actual execution measure. -/ +inductive TreeExec {Q : Type} {r : ℕ} (P : TreeMachine Q r) : + Q → (Fin r → DataTree) → ℕ → (Fin r → DataTree) → Bool → Prop + | halt (q d b) (h : P.output q = some b) : TreeExec P q d 0 d b + | next (q d) {m z c} (h : P.output q = none) + (tail : TreeExec P (P.next q ((P.instruction q).eval d).2) + ((P.instruction q).eval d).1 m z c) : + TreeExec P q d (dataMass d + 1 + m) z c + +lemma TreeExec.lower {Q : Type} {r : ℕ} {P : TreeMachine Q r} + {q : Q} {d e : Fin r → DataTree} {w : ℕ} {b : Bool} (h : TreeExec P q d w e b) : + ∃ n, n ≤ 51 * w ∧ MacroExec P.lower q (dataWords d) n (dataWords e) b := by + induction h with + | halt q d b h => exact ⟨0, by omega, .halt q _ b h⟩ + | next q d ho _ ih => + obtain ⟨m, hm, ht⟩ := ih + obtain ⟨n, hn, hr⟩ := (P.instruction q).routine_run d + exact ⟨n + 1 + m, by omega, MacroExec.next q _ ho hr ht⟩ + +end ParityWL.Complexity + +namespace ParityWL.Complexity + +structure FinTree (r : ℕ) where + State : Type + finite : Fintype State + program : TreeMachine State r + +attribute [instance] FinTree.finite + +def FinTree.of {Q : Type} [Fintype Q] {r : ℕ} (P : TreeMachine Q r) : FinTree r := + ⟨Q, inferInstance, P⟩ + +def TreeRuns {Q : Type} {r : ℕ} (P : TreeMachine Q r) (d : Fin r → DataTree) + (w : ℕ) (e : Fin r → DataTree) (b : Bool) : Prop := TreeExec P P.initial d w e b + +def TreeMachine.halt {r : ℕ} (b : Bool) : TreeMachine Unit r where + initial := () + output := fun _ => some b + instruction := fun _ => .skip + next := fun _ _ => () + +lemma treeHalt_run {r : ℕ} (b : Bool) (d : Fin r → DataTree) : + TreeRuns (.halt b) d 0 d b := .halt _ _ _ rfl + +def TreeMachine.atomic {r : ℕ} (op : TreeOp r) : TreeMachine (Option Bool) r where + initial := none + output := id + instruction := fun _ => op + next := fun _ b => some b + +lemma treeAtomic_run {r : ℕ} (op : TreeOp r) (d : Fin r → DataTree) : + TreeRuns (.atomic op) d (dataMass d + 1) (op.eval d).1 (op.eval d).2 := by + have h := TreeExec.next (P := .atomic op) none d (m := 0) rfl + (.halt _ _ _ rfl) + simpa [TreeRuns, TreeMachine.atomic] using h + +lemma TreeExec.map {Q R : Type} {r : ℕ} {P : TreeMachine Q r} {T : TreeMachine R r} + (f : Q → R) (ho : ∀ q, T.output (f q) = P.output q) + (hi : ∀ q, P.output q = none → T.instruction (f q) = P.instruction q) + (hn : ∀ q b, P.output q = none → T.next (f q) b = f (P.next q b)) + {q : Q} {d e : Fin r → DataTree} {n : ℕ} {b : Bool} (h : TreeExec P q d n e b) : + TreeExec T (f q) d n e b := by + induction h with + | halt q d b h => exact .halt _ _ _ ((ho q).trans h) + | next q d h _ ih => + apply TreeExec.next _ _ ((ho q).trans h) + simpa only [hi q h, hn q _ h] using ih + +def TreeMachine.andThen {Q R : Type} {r : ℕ} (P : TreeMachine Q r) (T : TreeMachine R r) : + TreeMachine (Q ⊕ R) r where + initial := .inl P.initial + output := fun q => match q with | .inl _ => none | .inr q => T.output q + instruction := fun q => match q with + | .inl q => if P.output q = none then P.instruction q else .skip + | .inr q => T.instruction q + next := fun q b => match q with + | .inl q => if P.output q = none then .inl (P.next q b) else .inr T.initial + | .inr q => .inr (T.next q b) + +lemma TreeExec.andThen_right {Q R : Type} {r : ℕ} + (P : TreeMachine Q r) (T : TreeMachine R r) + {q : R} {d e : Fin r → DataTree} {n : ℕ} {b : Bool} (h : TreeExec T q d n e b) : + TreeExec (P.andThen T) (.inr q) d n e b := by + exact h.map (T := P.andThen T) Sum.inr (fun _ => rfl) (fun _ _ => rfl) (fun _ _ _ => rfl) + +lemma TreeExec.andThen {Q R : Type} {r : ℕ} + {P : TreeMachine Q r} {T : TreeMachine R r} + {q : Q} {d e z : Fin r → DataTree} {n m : ℕ} {b c : Bool} + (h : TreeExec P q d n e b) (ht : TreeRuns T e m z c) : + TreeExec (P.andThen T) (.inl q) d (n + dataMass e + 1 + m) z c := by + induction h with + | halt q d b ho => + have hh := ht.andThen_right P T + have hi : (P.andThen T).instruction (.inl q) = .skip := by simp [TreeMachine.andThen, ho] + have hn : (P.andThen T).next (.inl q) true = .inr T.initial := by simp [TreeMachine.andThen, ho] + simp only [Nat.zero_add] + apply TreeExec.next _ _ rfl + simpa only [hi, TreeOp.eval, hn] using hh + | next q d ho _ ih => + have hi : (P.andThen T).instruction (.inl q) = P.instruction q := by + simp [TreeMachine.andThen, ho] + have hn : ∀ b, (P.andThen T).next (.inl q) b = .inl (P.next q b) := by + intro b; simp [TreeMachine.andThen, ho] + have hh := TreeExec.next (P := P.andThen T) (.inl q) d rfl + (by simpa only [hi, hn] using ih ht) + convert hh using 1 + omega + +lemma TreeRuns.andThen {Q R : Type} {r : ℕ} + {P : TreeMachine Q r} {T : TreeMachine R r} + {d e z : Fin r → DataTree} {n m : ℕ} {b c : Bool} + (h : TreeRuns P d n e b) (ht : TreeRuns T e m z c) : + TreeRuns (P.andThen T) d (n + dataMass e + 1 + m) z c := TreeExec.andThen h ht + +def TreeMachine.branch {Q R : Type} {r : ℕ} (src : Fin r) + (P : TreeMachine Q r) (T : TreeMachine R r) : TreeMachine (Unit ⊕ Q ⊕ R) r where + initial := .inl () + output := fun q => match q with + | .inl _ => none + | .inr (.inl q) => P.output q + | .inr (.inr q) => T.output q + instruction := fun q => match q with + | .inl _ => .test src + | .inr (.inl q) => P.instruction q + | .inr (.inr q) => T.instruction q + next := fun q b => match q with + | .inl _ => if b then .inr (.inl P.initial) else .inr (.inr T.initial) + | .inr (.inl q) => .inr (.inl (P.next q b)) + | .inr (.inr q) => .inr (.inr (T.next q b)) + +lemma TreeRuns.branch_true {Q R : Type} {r : ℕ} (src : Fin r) + (P : TreeMachine Q r) (T : TreeMachine R r) + {d e : Fin r → DataTree} {n : ℕ} {b : Bool} (h : d src = .nil) + (hr : TreeRuns P d n e b) : + TreeRuns (TreeMachine.branch src P T) d (dataMass d + 1 + n) e b := by + have hm := hr.map (T := TreeMachine.branch src P T) (fun q => .inr (.inl q)) + (fun _ => rfl) (fun _ _ => rfl) (fun _ _ _ => rfl) + apply TreeExec.next _ _ rfl + simpa [TreeMachine.branch, TreeOp.eval, h] using hm + +lemma TreeRuns.branch_false {Q R : Type} {r : ℕ} (src : Fin r) + (P : TreeMachine Q r) (T : TreeMachine R r) + {d e : Fin r → DataTree} {n : ℕ} {b : Bool} (h : d src ≠ .nil) + (hr : TreeRuns T d n e b) : + TreeRuns (TreeMachine.branch src P T) d (dataMass d + 1 + n) e b := by + have hm := hr.map (T := TreeMachine.branch src P T) (fun q => .inr (.inr q)) + (fun _ => rfl) (fun _ _ => rfl) (fun _ _ _ => rfl) + apply TreeExec.next _ _ rfl + simpa [TreeMachine.branch, TreeOp.eval, h] using hm + +def TreeMachine.repeat {Q : Type} {r : ℕ} (P : TreeMachine Q r) : TreeMachine Q r where + initial := P.initial + output := fun q => if P.output q = some true then some true else none + instruction := fun q => if P.output q = none then P.instruction q else .skip + next := fun q b => if P.output q = none then P.next q b else P.initial + +lemma TreeExec.repeat_true {Q : Type} {r : ℕ} {P : TreeMachine Q r} + {q : Q} {d e : Fin r → DataTree} {n : ℕ} (h : TreeExec P q d n e true) : + TreeExec P.repeat q d n e true := by + generalize hb : true = b at h + induction h with + | halt q d b ho => subst b; exact .halt _ _ _ (by simp [TreeMachine.repeat, ho]) + | next q d ho _ ih => + apply TreeExec.next _ _ (by simp [TreeMachine.repeat, ho]) + simpa only [TreeMachine.repeat, ho, ↓reduceIte] using ih hb + +lemma TreeExec.repeat_false {Q : Type} {r : ℕ} {P : TreeMachine Q r} + {q : Q} {d e z : Fin r → DataTree} {n m : ℕ} + (h : TreeExec P q d n e false) (ht : TreeRuns P.repeat e m z true) : + TreeExec P.repeat q d (n + dataMass e + 1 + m) z true := by + generalize hb : false = b at h + induction h with + | halt q d b ho => + subst b + simp only [Nat.zero_add] + apply TreeExec.next _ _ (by simp [TreeMachine.repeat, ho]) + simpa [TreeRuns, TreeMachine.repeat, ho, TreeOp.eval] using ht + | next q d ho _ ih => + have hi : P.repeat.instruction q = P.instruction q := by simp [TreeMachine.repeat, ho] + have hn : ∀ b, P.repeat.next q b = P.next q b := by intro b; simp [TreeMachine.repeat, ho] + have hh := TreeExec.next (P := P.repeat) q d (by simp [TreeMachine.repeat, ho]) + (by simpa only [hi, hn] using ih ht hb) + convert hh using 1 + omega + +end ParityWL.Complexity + +end OAI diff --git a/lean/OAI/Combinatorics/ParityLifts/TreePrograms.lean b/lean/OAI/Combinatorics/ParityLifts/TreePrograms.lean new file mode 100644 index 0000000000000000000000000000000000000000..438a4d172517a9781c58c4145678ad46c5d129d1 --- /dev/null +++ b/lean/OAI/Combinatorics/ParityLifts/TreePrograms.lean @@ -0,0 +1,359 @@ +import OAI.Combinatorics.ParityLifts.FunctionalCompile + +namespace OAI + +namespace ParityWL.Complexity + +def FCode.const : DataTree → FCode + | .nil => .nil + | .node l r => .pair (const l) (const r) + +lemma BEval.const (t x : DataTree) : BEval (FCode.const t) x + (t.size * (x.size + 1)) t := by + induction t with + | nil => exact (BEval.nil x).mono (by simp [DataTree.size]) + | node l r hl hr => + exact (hl.pair hr).mono (by simp [DataTree.size]; nlinarith) + +/-- Finite tree expressions are uniformly linear in the size of their argument; +no arithmetic or lookup oracle is concealed in an expression. -/ +inductive TExpr where + | input + | const (t : DataTree) + | child (right : Bool) (e : TExpr) + | pair (left right : TExpr) + | cond (test nilCase nodeCase : TExpr) + +def TExpr.eval : TExpr → DataTree → DataTree + | .input, x => x + | .const t, _ => t + | .child b e, x => (e.eval x).child b + | .pair e f, x => .node (e.eval x) (f.eval x) + | .cond p e f, x => if p.eval x = .nil then e.eval x else f.eval x + +def TExpr.compile : TExpr → FCode + | .input => .id + | .const t => .const t + | .child false e => .seq e.compile .left + | .child true e => .seq e.compile .right + | .pair e f => .pair e.compile f.compile + | .cond p e f => .cond p.compile e.compile f.compile + +def TExpr.cost : TExpr → ℕ + | .input => 1 + | .const t => t.size + | .child _ e => 2 * e.cost + 2 + | .pair e f => e.cost + f.cost + 1 + | .cond p e f => p.cost + e.cost + f.cost + 1 + +lemma TExpr.run (e : TExpr) (x : DataTree) : + BEval e.compile x (e.cost * (x.size + 1)) (e.eval x) := by + induction e with + | input => exact (BEval.id x).mono (by simp [TExpr.cost]) + | const t => exact BEval.const t x + | child b e ih => + have hx := ih.bounds.2.1 + cases b + · exact (ih.seq (BEval.left (e.eval x))).mono (by simp only [TExpr.cost]; nlinarith) + · exact (ih.seq (BEval.right (e.eval x))).mono (by simp only [TExpr.cost]; nlinarith) + | pair e f ih₁ ih₂ => + exact (ih₁.pair ih₂).mono (by simp [TExpr.cost]; nlinarith) + | cond p e f ihp ihe ihf => + by_cases hp : p.eval x = .nil + · have h := BEval.nil_cond (g := f.compile) (hp ▸ ihp) ihe + simp only [TExpr.eval, hp, ↓reduceIte] + exact h.mono (by simp [TExpr.cost]; nlinarith) + · have h := BEval.node_cond (f := e.compile) ihp hp ihf + simp only [TExpr.eval, hp, ↓reduceIte] + exact h.mono (by simp [TExpr.cost]; nlinarith) + +abbrev TExpr.left (e : TExpr) : TExpr := .child false e +abbrev TExpr.right (e : TExpr) : TExpr := .child true e +abbrev TExpr.nil : TExpr := .const .nil + +lemma BEval.loop_iterate (p : FCode) (f : DataTree → DataTree) (x : DataTree) + (n B S : ℕ) + (hb : ∀ j, j < n → BEval p (f^[j] x) B (f^[j + 1] x)) + (hs : ∀ j, j ≤ n → (f^[j] x).size ≤ S) + (hc : ∀ j, j < n → (f^[j] x).child false ≠ .nil) + (he : (f^[n] x).child false = .nil) : + BEval (.loop p) x ((n + 1) * (B + S + 1)) (f^[n] x) := by + induction n generalizing x with + | zero => + simpa using (BEval.loop_stop p x (by simpa using he)).mono + (show x.size ≤ (0 + 1) * (B + S + 1) from by + have hx : x.size ≤ S := by simpa using hs 0 (by omega) + omega) + | succ n ih => + have ht := ih (f x) + (fun j hj => by simpa [Function.iterate_succ_apply] using hb (j + 1) (by omega)) + (fun j hj => by simpa [Function.iterate_succ_apply] using hs (j + 1) (by omega)) + (fun j hj => by simpa [Function.iterate_succ_apply] using hc (j + 1) (by omega)) + (by simpa [Function.iterate_succ_apply] using he) + have h₀ : BEval p x B (f x) := by simpa using hb 0 (by omega) + have hn : x.child false ≠ .nil := by simpa using hc 0 (by omega) + have h := BEval.loop_next hn h₀ ht + simpa [Function.iterate_succ_apply] using h.mono + (show B + (n + 1) * (B + S + 1) + 1 ≤ (n + 1 + 1) * (B + S + 1) by nlinarith) + +end ParityWL.Complexity + +namespace ParityWL.Complexity + +class TreeCodec (α : Type) where + encode : α → DataTree + injective : Function.Injective encode + +abbrev treeEncode {α : Type} [TreeCodec α] (a : α) : DataTree := TreeCodec.encode a + +instance : TreeCodec DataTree := ⟨id, Function.injective_id⟩ + +def boolTree (b : Bool) : DataTree := if b then .node .nil .nil else .nil +instance : TreeCodec Bool where + encode := boolTree + injective := by intro a b h; cases a <;> cases b <;> simp_all [boolTree] + +@[simp] lemma treeEncode_false : treeEncode false = .nil := rfl +@[simp] lemma treeEncode_true : treeEncode true = .node .nil .nil := rfl + +instance {α β : Type} [TreeCodec α] [TreeCodec β] : TreeCodec (α × β) where + encode := fun x => .node (treeEncode x.1) (treeEncode x.2) + injective := by + intro a b h + have hl := congrArg (DataTree.child false) h + have hr := congrArg (DataTree.child true) h + simp only [DataTree.child, Bool.false_eq_true, ↓reduceIte] at hl + simp only [DataTree.child, ↓reduceIte] at hr + exact Prod.ext (TreeCodec.injective hl) (TreeCodec.injective hr) + +@[simp] lemma treeEncode_pair {α β : Type} [TreeCodec α] [TreeCodec β] (a : α) (b : β) : + treeEncode (a, b) = .node (treeEncode a) (treeEncode b) := rfl + +@[simp] lemma treeEncode_prod {α β : Type} [TreeCodec α] [TreeCodec β] (x : α × β) : + treeEncode x = .node (treeEncode x.1) (treeEncode x.2) := rfl + +def DataTree.ofList : List DataTree → DataTree + | [] => .nil + | x :: xs => .node x (ofList xs) + +lemma DataTree.ofList_injective : Function.Injective ofList := by + intro xs + induction xs with + | nil => intro ys h; cases ys <;> simp_all [ofList] + | cons x xs ih => + intro ys h + cases ys with + | nil => cases h + | cons y ys => + have hl := congrArg (DataTree.child false) h + have hr := congrArg (DataTree.child true) h + simp [ofList, child] at hl hr + simp [hl, ih hr] + +instance {α : Type} [TreeCodec α] : TreeCodec (List α) where + encode := fun xs => DataTree.ofList (xs.map treeEncode) + injective := by + intro xs ys h + exact List.map_injective_iff.mpr TreeCodec.injective (DataTree.ofList_injective h) + +@[simp] lemma treeEncode_nil {α : Type} [TreeCodec α] : treeEncode ([] : List α) = .nil := rfl +@[simp] lemma treeEncode_cons {α : Type} [TreeCodec α] (x : α) (xs : List α) : + treeEncode (x :: xs) = .node (treeEncode x) (treeEncode xs) := rfl + +lemma treeEncode_list_size {α : Type} [TreeCodec α] (xs : List α) : + (treeEncode xs).size = 1 + (xs.map (fun x => (treeEncode x).size + 1)).sum := by + induction xs with + | nil => rfl + | cons x xs ih => simp [DataTree.size, ih]; omega + +lemma treeEncode_bits (bs : List Bool) : treeEncode bs = DataTree.ofBits bs := by + induction bs with + | nil => rfl + | cons b bs ih => simp [DataTree.ofBits, ih]; rfl + +/-- A verified program on a concrete tree encoding. `time` is a proved bound on +both work and intermediate storage, never an oracle interpretation of `code`. -/ +structure TreeProgram (α β : Type) [TreeCodec α] [TreeCodec β] (f : α → β) where + code : FCode + time : α → ℕ + run : ∀ x, BEval code (treeEncode x) (time x) (treeEncode (f x)) + +def TreeProgram.id (α : Type) [TreeCodec α] : TreeProgram α α id where + code := .id + time := fun x => (treeEncode x).size + run := fun x => BEval.id (treeEncode x) + +def TreeProgram.const {α β : Type} [TreeCodec α] [TreeCodec β] (b : β) : + TreeProgram α β (fun _ => b) where + code := .const (treeEncode b) + time := fun x => (treeEncode b).size * ((treeEncode x).size + 1) + run := fun x => BEval.const (treeEncode b) (treeEncode x) + +def TreeProgram.fst (α β : Type) [TreeCodec α] [TreeCodec β] : TreeProgram (α × β) α Prod.fst where + code := .left + time := fun x => (treeEncode x).size + run := fun x => by + cases x with + | mk a b => simpa [DataTree.child] using BEval.left (treeEncode (a, b)) + +def TreeProgram.snd (α β : Type) [TreeCodec α] [TreeCodec β] : TreeProgram (α × β) β Prod.snd where + code := .right + time := fun x => (treeEncode x).size + run := fun x => by + cases x with + | mk a b => simpa [DataTree.child] using BEval.right (treeEncode (a, b)) + +def TreeProgram.comp {α β γ : Type} [TreeCodec α] [TreeCodec β] [TreeCodec γ] + {f : α → β} {g : β → γ} (P : TreeProgram α β f) (Q : TreeProgram β γ g) : + TreeProgram α γ (g ∘ f) where + code := .seq P.code Q.code + time := fun x => P.time x + Q.time (f x) + 1 + run := fun x => (P.run x).seq (Q.run (f x)) + +def TreeProgram.pair {α β γ : Type} [TreeCodec α] [TreeCodec β] [TreeCodec γ] + {f : α → β} {g : α → γ} (P : TreeProgram α β f) (Q : TreeProgram α γ g) : + TreeProgram α (β × γ) (fun x => (f x, g x)) where + code := .pair P.code Q.code + time := fun x => P.time x + Q.time x + 1 + run := fun x => (P.run x).pair (Q.run x) + +def TreeProgram.ite {α β : Type} [TreeCodec α] [TreeCodec β] + {p : α → Bool} {f g : α → β} (P : TreeProgram α Bool p) + (F : TreeProgram α β f) (G : TreeProgram α β g) : + TreeProgram α β (fun x => if p x then f x else g x) where + code := .cond P.code G.code F.code + time := fun x => P.time x + (if p x then F.time x else G.time x) + 1 + run := by + intro x + cases hp : p x + · simpa [hp] using (BEval.nil_cond (g := F.code) (by simpa [hp] using P.run x) (G.run x)) + · simpa [hp] using (BEval.node_cond (f := G.code) (by simpa [hp] using P.run x) + (show treeEncode true ≠ .nil by simp) (F.run x)) + +lemma BEval.loop_terminates (p : FCode) (f : DataTree → DataTree) (I : DataTree → Prop) + (μ : DataTree → ℕ) (C : ℕ) + (hs : ∀ x, I x → x.size ≤ C * (μ x + 1)) + (hb : ∀ x, I x → x.child false ≠ .nil → BEval p x (C * (μ x + 1)) (f x)) + (hn : ∀ x, I x → x.child false ≠ .nil → I (f x) ∧ μ (f x) < μ x) + (x : DataTree) (hx : I x) : + ∃ y, I y ∧ y.child false = .nil ∧ + BEval (.loop p) x ((2 * C + 1) * (μ x + 1) ^ 2) y := by + generalize he : μ x = n + induction n using Nat.strong_induction_on generalizing x with + | h n ih => + by_cases hg : x.child false = .nil + · refine ⟨x, hx, hg, (BEval.loop_stop p x hg).mono ?_⟩ + have hsz := hs x hx + have hsq : μ x + 1 ≤ (μ x + 1) ^ 2 := by nlinarith [Nat.zero_le (μ x ^ 2)] + rw [← he] + calc + x.size ≤ C * (μ x + 1) := hsz + _ ≤ C * (μ x + 1) ^ 2 := Nat.mul_le_mul_left C hsq + _ ≤ (2 * C + 1) * (μ x + 1) ^ 2 := Nat.mul_le_mul_right _ (by omega) + · obtain ⟨hI, hμ⟩ := hn x hx hg + obtain ⟨y, hy, hnil, hr⟩ := ih (μ (f x)) (by omega) (f x) hI rfl + refine ⟨y, hy, hnil, (BEval.loop_next hg (hb x hx hg) hr).mono ?_⟩ + have hsq : (μ (f x) + 1) ^ 2 ≤ (μ x) ^ 2 := Nat.pow_le_pow_left (by omega) 2 + rw [← he] + have hmul := Nat.mul_le_mul_left (2 * C + 1) hsq + nlinarith + +end ParityWL.Complexity + +namespace ParityWL.Complexity + +def TreeProgram.congr {α β : Type} [TreeCodec α] [TreeCodec β] + {f g : α → β} (P : TreeProgram α β f) (h : ∀ x, f x = g x) : + TreeProgram α β g := by + have : f = g := funext h + subst g + exact P + +def FCode.foldBody (p : FCode) : FCode := + .pair (.seq .left .right) (.seq (.pair (.seq .left .left) .right) p) + +def TreeProgram.foldWork {α β : Type} [TreeCodec α] [TreeCodec β] + {f : α × β → β} (P : TreeProgram (α × β) β f) : List α → β → ℕ + | [], b => (treeEncode (([] : List α), b)).size + | a :: xs, b => 10 * ((treeEncode (a :: xs, b)).size + 1) + P.time (a, b) + + P.foldWork xs (f (a, b)) + 1 + +lemma TreeProgram.foldBody_run {α β : Type} [TreeCodec α] [TreeCodec β] + {f : α × β → β} (P : TreeProgram (α × β) β f) (a : α) (xs : List α) (b : β) : + BEval P.code.foldBody (treeEncode (a :: xs, b)) + (10 * ((treeEncode (a :: xs, b)).size + 1) + P.time (a, b)) + (treeEncode (xs, f (a, b))) := by + let s := treeEncode (a :: xs, b) + have hl : s.child false = treeEncode (a :: xs) := rfl + have hll : (s.child false).child false = treeEncode a := rfl + have hlr : (s.child false).child true = treeEncode xs := rfl + have hr : s.child true = treeEncode b := rfl + have ht := (BEval.left s).seq (BEval.right (s.child false)) + have hh := ((BEval.left s).seq (BEval.left (s.child false))).pair (BEval.right s) + have ha := (hh.seq (by simpa [hll, hr] using P.run (a, b))) + have result := ht.pair ha + simpa [FCode.foldBody, hlr, s, DataTree.child] using result.mono + (show _ ≤ 10 * (s.size + 1) + P.time (a, b) by + have := s.size_child false + omega) + +lemma TreeProgram.foldLoop_run {α β : Type} [TreeCodec α] [TreeCodec β] + {f : α × β → β} (P : TreeProgram (α × β) β f) (xs : List α) (b : β) : + BEval (.loop P.code.foldBody) (treeEncode (xs, b)) (P.foldWork xs b) + (treeEncode (([] : List α), xs.foldl (fun c a => f (a, c)) b)) := by + induction xs generalizing b with + | nil => exact BEval.loop_stop _ _ rfl + | cons a xs ih => + exact BEval.loop_next (by simp [DataTree.child]) (P.foldBody_run a xs b) (ih (f (a, b))) + +def TreeProgram.foldl {α β : Type} [TreeCodec α] [TreeCodec β] + {f : α × β → β} (P : TreeProgram (α × β) β f) : + TreeProgram (List α × β) β (fun x => x.1.foldl (fun c a => f (a, c)) x.2) where + code := .seq (.loop P.code.foldBody) .right + time := fun x => P.foldWork x.1 x.2 + + (treeEncode (([] : List α), x.1.foldl (fun c a => f (a, c)) x.2)).size + 1 + run := by + intro x + simpa [DataTree.child] using (P.foldLoop_run x.1 x.2).seq + (BEval.right (treeEncode (([] : List α), x.1.foldl (fun c a => f (a, c)) x.2))) + +lemma treeEncode_list_size_mono {α : Type} [TreeCodec α] {xs ys : List α} (h : xs.Sublist ys) : + (treeEncode xs).size ≤ (treeEncode ys).size := by + rw [treeEncode_list_size, treeEncode_list_size] + exact Nat.add_le_add_left (List.Sublist.sum_le_sum (h.map _) (fun _ _ => Nat.zero_le _)) 1 + +lemma TreeProgram.foldWork_bound {α β : Type} [TreeCodec α] [TreeCodec β] + {f : α × β → β} (P : TreeProgram (α × β) β f) (xs : List α) (b : β) + (I : β → Prop) (B A : ℕ) (hb : I b) + (hs : ∀ b, I b → (treeEncode b).size ≤ A) + (ht : ∀ a ∈ xs, ∀ b, I b → P.time (a, b) ≤ B) + (hi : ∀ a ∈ xs, ∀ b, I b → I (f (a, b))) : + P.foldWork xs b ≤ (xs.length + 1) * + (10 * ((treeEncode xs).size + A + 2) + B + 1) ∧ + I (xs.foldl (fun c a => f (a, c)) b) := by + induction xs generalizing b with + | nil => + constructor + · simp only [foldWork, treeEncode_pair, DataTree.size, treeEncode_nil, List.length_nil] + have := hs b hb + omega + · exact hb + | cons a xs ih => + obtain ⟨hcost, hres⟩ := ih (f (a, b)) (hi a (by simp) b hb) + (fun x hx c hc => ht x (by simp [hx]) c hc) + (fun x hx c hc => hi x (by simp [hx]) c hc) + constructor + · have htime := ht a (by simp) b hb + have hsize := hs b hb + have hlist : (treeEncode xs).size ≤ (treeEncode (a :: xs)).size := by + simp [DataTree.size] + have hmul := Nat.mul_le_mul_left (xs.length + 1) + (show 10 * ((treeEncode xs).size + A + 2) + B + 1 ≤ + 10 * ((treeEncode (a :: xs)).size + A + 2) + B + 1 by omega) + simp only [foldWork, List.length_cons, treeEncode_pair, DataTree.size] + nlinarith + · exact hres + +end ParityWL.Complexity + +end OAI diff --git a/lean/OAI/Combinatorics/ParityLifts/TreeRoutines.lean b/lean/OAI/Combinatorics/ParityLifts/TreeRoutines.lean new file mode 100644 index 0000000000000000000000000000000000000000..d693cc41406b8187b80fca258e1f79ed23b86d9c --- /dev/null +++ b/lean/OAI/Combinatorics/ParityLifts/TreeRoutines.lean @@ -0,0 +1,298 @@ +import OAI.Combinatorics.ParityLifts.TreeWords + +namespace OAI + +namespace ParityWL.Complexity + +def StackMachine.halt {t a : ℕ} (b : Bool) : StackMachine Unit t a where + initial := () + output := fun _ => some b + transition := fun _ _ => ((), fun _ => .keep) + +lemma halt_run {t a : ℕ} (b : Bool) (w : Words t a) : + Runs (.halt b) w 0 w b := ⟨(), .halt _ _ rfl⟩ + +/-- Branching tests only the finitely many currently scanned stack symbols. -/ +def StackMachine.branch {Q R : Type} {t a : ℕ} + (test : (Fin (t + 1) → Option (StackSymbol a)) → Bool) + (P : StackMachine Q t a) (T : StackMachine R t a) : + StackMachine (Unit ⊕ Q ⊕ R) t a where + initial := .inl () + output := fun q => match q with + | .inl _ => none + | .inr (.inl q) => P.output q + | .inr (.inr q) => T.output q + transition := fun q x => match q with + | .inl _ => (if test x then .inr (.inl P.initial) else .inr (.inr T.initial), fun _ => .keep) + | .inr (.inl q) => let v := P.transition q x; (.inr (.inl v.1), v.2) + | .inr (.inr q) => let v := T.transition q x; (.inr (.inr v.1), v.2) + +lemma Runs.branch_true {Q R : Type} {t a : ℕ} + (test : (Fin (t + 1) → Option (StackSymbol a)) → Bool) + (P : StackMachine Q t a) (T : StackMachine R t a) + {w v : Words t a} {n : ℕ} {b : Bool} (h : test (fun i => (w i).head?) = true) + (hr : Runs P w n v b) : Runs (StackMachine.branch test P T) w (1 + n) v b := by + obtain ⟨q, hq⟩ := hr + let f : StackConfiguration Q t a → StackConfiguration (Unit ⊕ Q ⊕ R) t a := + fun x => ⟨.inr (.inl x.state), x.word⟩ + have hm := hq.map (T := StackMachine.branch test P T) f (fun _ => rfl) (by + intro x hx + simp only [f, StackMachine.step, StackMachine.branch, hx]) + have he : (StackMachine.branch test P T).step ⟨.inl (), w⟩ = f ⟨P.initial, w⟩ := by + simp [f, StackMachine.step, StackMachine.branch, h, StackOp.apply] + refine ⟨.inr (.inl q), ?_⟩ + have hh := StackExec.next ⟨.inl (), w⟩ (by rfl : (StackMachine.branch test P T).output _ = none) + (he ▸ hm) + simpa only [Nat.add_comm 1 n, f, StackMachine.branch] using hh + +lemma Runs.branch_false {Q R : Type} {t a : ℕ} + (test : (Fin (t + 1) → Option (StackSymbol a)) → Bool) + (P : StackMachine Q t a) (T : StackMachine R t a) + {w v : Words t a} {n : ℕ} {b : Bool} (h : test (fun i => (w i).head?) = false) + (hr : Runs T w n v b) : Runs (StackMachine.branch test P T) w (1 + n) v b := by + obtain ⟨q, hq⟩ := hr + let f : StackConfiguration R t a → StackConfiguration (Unit ⊕ Q ⊕ R) t a := + fun x => ⟨.inr (.inr x.state), x.word⟩ + have hm := hq.map (T := StackMachine.branch test P T) f (fun _ => rfl) (by + intro x hx + simp only [f, StackMachine.step, StackMachine.branch, hx]) + have he : (StackMachine.branch test P T).step ⟨.inl (), w⟩ = f ⟨T.initial, w⟩ := by + simp [f, StackMachine.step, StackMachine.branch, h, StackOp.apply] + refine ⟨.inr (.inr q), ?_⟩ + have hh := StackExec.next ⟨.inl (), w⟩ (by rfl : (StackMachine.branch test P T).output _ = none) + (he ▸ hm) + simpa only [Nat.add_comm 1 n, f, StackMachine.branch] using hh + +def popSymbol {t a : ℕ} (src : Fin (t + 1)) := + primitive (a := a) (fun _ i => if i = src then .pop else .keep) (fun _ => true) + +lemma popSymbol_run {t a : ℕ} (src : Fin (t + 1)) (w : Words t a) : + Runs (popSymbol src) w 1 (Function.update w src (w src).tail) true := by + refine ⟨some true, ?_⟩ + have h := primitive_exec (fun (_ : Fin (t + 1) → Option (StackSymbol a)) i => + if i = src then StackOp.pop else .keep) (fun _ => true) w + have he : applyOps (fun i => if i = src then .pop else .keep) w = + Function.update w src (w src).tail := by + funext i + by_cases hi : i = src <;> simp [applyOps, StackOp.apply, Function.update, hi] + exact he ▸ h + +end ParityWL.Complexity + +namespace ParityWL.Complexity + +/-- Assemble a binary node without changing either operand, even if the +store destination aliases an operand. The buffer and temporary are cleared. -/ +def nodeWord {t : ℕ} (dst left right buf tmp : Fin (t + 1)) := + (((((copyWord (a := 0) right buf tmp).andThen (copyWord left buf tmp)).andThen + (pushSymbol buf 1)).andThen (transfer dst ∅)).andThen + (copyWord buf dst tmp)).andThen (transfer buf ∅) + +lemma nodeWord_run {t : ℕ} (dst left right buf tmp : Fin (t + 1)) + (hdb : dst ≠ buf) (hdt : dst ≠ tmp) (hlb : left ≠ buf) (hlt : left ≠ tmp) + (hrb : right ≠ buf) (hrt : right ≠ tmp) (hbt : buf ≠ tmp) + (w : Words t 0) (hb : w buf = []) (ht : w tmp = []) : + Runs (nodeWord dst left right buf tmp) w + (10 * ((w left).length + (w right).length) + 2 * (w dst).length + 23) + (Function.update w dst (1 :: w left ++ w right)) true := by + let u := w left + let v := w right + let z := w dst + let c := 1 :: u ++ v + let w₁ := Function.update w buf v + let w₂ := Function.update w buf (u ++ v) + let w₃ := Function.update w buf c + let w₄ := Function.update w₃ dst [] + let w₅ := Function.update w₃ dst c + let w₆ := Function.update w dst c + have h₁ : Runs (copyWord right buf tmp) w (4 * v.length + 3) w₁ true := by + simpa [w₁, v, hb] using copyWord_run right buf tmp hrb hrt hbt w ht + have h₂ : Runs (copyWord left buf tmp) w₁ (4 * u.length + 3) w₂ true := by + have h := copyWord_run left buf tmp hlb hlt hbt w₁ (by simp [w₁, Ne.symm hbt, ht]) + simpa [w₁, w₂, hlb, u] using h + have h₃ : Runs (pushSymbol buf 1) w₂ 1 w₃ true := by + simpa [w₂, w₃, c] using pushSymbol_run buf (1 : StackSymbol 0) w₂ + have h₄ : Runs (transfer dst ∅) w₃ (2 * z.length + 1) w₄ true := by + simpa [w₄, z, w₃, hdb] using clear_run dst w₃ + have h₅ : Runs (copyWord buf dst tmp) w₄ (4 * c.length + 3) w₅ true := by + have h := copyWord_run buf dst tmp (Ne.symm hdb) hbt hdt w₄ + (by simp [w₄, w₃, Ne.symm hdt, Ne.symm hbt, ht]) + simpa [w₄, w₅, w₃, Ne.symm hdb] using h + have h₆ : Runs (transfer buf ∅) w₅ (2 * c.length + 1) w₆ true := by + have h := clear_run buf w₅ + have he : Function.update w₅ buf [] = w₆ := by + funext i + by_cases hi : i = buf + · subst i; simp [w₆, Ne.symm hdb, hb] + · simp [w₅, w₃, w₆, Function.update, hi] + rw [he] at h + simpa [w₅, w₃, Ne.symm hdb] using h + have hh := ((((h₁.andThen h₂).andThen h₃).andThen h₄).andThen h₅).andThen h₆ + unfold nodeWord + have hc : c.length = 1 + u.length + v.length := by simp [c]; omega + convert hh using 1 + dsimp only [u, v, z] at hc ⊢ + omega + +def nilWord {t : ℕ} (dst : Fin (t + 1)) := + (transfer (a := 0) dst ∅).andThen (pushSymbol dst 0) + +lemma nilWord_run {t : ℕ} (dst : Fin (t + 1)) (w : Words t 0) : + Runs (nilWord dst) w (2 * (w dst).length + 3) + (Function.update w dst [0]) true := by + have h₁ := clear_run dst w + have h₂ := pushSymbol_run dst (0 : StackSymbol 0) (Function.update w dst []) + have h := h₁.andThen h₂ + have he : 2 * (w dst).length + 3 = 2 * (w dst).length + 1 + 1 + 1 := by omega + simpa [nilWord, he] using h + +end ParityWL.Complexity + +namespace ParityWL.Complexity + +def DataTree.child (right : Bool) : DataTree → DataTree + | .nil => .nil + | .node l r => if right then r else l + +def selectChildTail {t : ℕ} (buf out : Fin (t + 1)) (right : Bool) := + StackMachine.branch (fun _ => right) (transfer (a := 0) out ∅) + ((transfer buf ∅).andThen (transfer out {buf})) + +def selectChild {t : ℕ} (buf out pending : Fin (t + 1)) (right : Bool) := + StackMachine.branch (fun x => decide (x buf = some 0)) (.halt true) + (((popSymbol buf).andThen (moveTree buf out pending)).andThen + (selectChildTail buf out right)) + +lemma selectChild_run {t : ℕ} (buf out pending : Fin (t + 1)) + (hbo : buf ≠ out) (hbp : buf ≠ pending) (hop : out ≠ pending) + (right : Bool) (d : DataTree) (w : Words t 0) + (hb : w buf = d.code) (ho : w out = []) (hp : w pending = []) : + ∃ n, n ≤ 5 * d.size + 12 ∧ Runs (selectChild buf out pending right) w n + (Function.update w buf (d.child right).code) true := by + cases d with + | nil => + have h := (halt_run true w).branch_true (fun x => decide (x buf = some 0)) + (.halt true) (((popSymbol buf).andThen (moveTree buf out pending)).andThen + (selectChildTail buf out right)) (by simp [hb, DataTree.code]) + have he : Function.update w buf ((DataTree.nil).child right).code = w := by + simp [DataTree.child, ← hb] + refine ⟨1, by simp [DataTree.size], ?_⟩ + simpa only [he, Nat.add_zero, selectChild] using h + | node l r => + let w₁ := Function.update w buf (l.code ++ r.code) + let w₂ := Function.update (Function.update w buf r.code) out l.code.reverse + have h₁ : Runs (popSymbol buf) w 1 w₁ true := by + simpa [w₁, hb, DataTree.code] using popSymbol_run buf w + have h₂ : Runs (moveTree buf out pending) w₁ (l.size + 3) w₂ true := by + have h := moveTree_run buf out pending hbo hbp hop l r.code w₁ + (by simp [w₁]) (by simp [w₁, Ne.symm hbp, hp]) + have he : scanResult buf out pending w₁ l r.code 0 = w₂ := by + funext i + by_cases hi : i = pending + · subst i + simp [scanResult, scanUpdate, w₂, Ne.symm hop, Ne.symm hbp, hp] + · by_cases he : i = buf + · subst i; simp [scanResult, scanUpdate, w₁, w₂, hbp, hbo] + · by_cases hd : i = out + · subst i; simp [scanResult, scanUpdate, w₁, w₂, hop, Ne.symm hbo, ho] + · simp [scanResult, scanUpdate, w₁, w₂, Function.update, hi, he, hd] + exact he ▸ h + have hpre := h₁.andThen h₂ + have htail : ∃ m, m ≤ 2 * l.size + 2 * r.size + 4 ∧ + Runs (selectChildTail buf out right) w₂ m + (Function.update w buf ((DataTree.node l r).child right).code) true := by + cases right with + | false => + let z := Function.update w₂ buf [] + have hc : Runs (transfer buf ∅) w₂ (2 * r.size + 1) z true := by + simpa [z, w₂, hbo] using clear_run buf w₂ + have ht := transfer_run out {buf} z + have hzout : z out = l.code.reverse := by simp [z, w₂, Ne.symm hbo] + have hz : transferred out {buf} z = Function.update w buf l.code := by + funext i + by_cases hi : i = out + · subst i; simp [transferred, Function.update, Ne.symm hbo, ho] + · by_cases he : i = buf + · subst i; simp [transferred, hbo, hzout, z] + · simp [transferred, hi, he, z, w₂, Function.update] + rw [hzout, List.length_reverse, DataTree.length_code, hz] at ht + have hh := (hc.andThen ht).branch_false (fun _ => false) + (transfer out ∅) ((transfer buf ∅).andThen (transfer out {buf})) rfl + refine ⟨_, ?_, hh⟩ + omega + | true => + have hc := clear_run out w₂ + have hz : Function.update w₂ out [] = Function.update w buf r.code := by + funext i + by_cases hi : i = out + · subst i; simp [Function.update, Ne.symm hbo, ho] + · simp [w₂, Function.update, hi] + have hout : w₂ out = l.code.reverse := by simp [w₂] + rw [hout, List.length_reverse, DataTree.length_code, hz] at hc + have hh := hc.branch_true (fun _ => true) + (transfer out ∅) ((transfer buf ∅).andThen (transfer out {buf})) rfl + exact ⟨_, by omega, hh⟩ + obtain ⟨m, hm, ht⟩ := htail + have hn := (hpre.andThen ht).branch_false (fun x => decide (x buf = some 0)) + (.halt true) (((popSymbol buf).andThen (moveTree buf out pending)).andThen + (selectChildTail buf out right)) (by simp [hb, DataTree.code]) + refine ⟨_, ?_, hn⟩ + simp only [DataTree.size] + omega + +/-- Tree projection with untouched operand and clean finite work stacks. -/ +def projectWord {t : ℕ} (dst src buf tmp out pending : Fin (t + 1)) (right : Bool) := + ((((copyWord (a := 0) src buf tmp).andThen (selectChild buf out pending right)).andThen + (transfer dst ∅)).andThen (copyWord buf dst tmp)).andThen (transfer buf ∅) + +lemma projectWord_run {t : ℕ} (dst src buf tmp out pending : Fin (t + 1)) + (hdb : dst ≠ buf) (hdt : dst ≠ tmp) + (hsb : src ≠ buf) (hst : src ≠ tmp) + (hbt : buf ≠ tmp) (hbo : buf ≠ out) (hbp : buf ≠ pending) + (hop : out ≠ pending) + (right : Bool) (d : DataTree) (w : Words t 0) + (hs : w src = d.code) (hb : w buf = []) (ht : w tmp = []) + (ho : w out = []) (hp : w pending = []) : + ∃ n, n ≤ 20 * (d.size + (w dst).length + 1) ∧ + Runs (projectWord dst src buf tmp out pending right) w n + (Function.update w dst (d.child right).code) true := by + let w₁ := Function.update w buf d.code + let w₂ := Function.update w buf (d.child right).code + let w₃ := Function.update w₂ dst [] + let w₄ := Function.update w₂ dst (d.child right).code + have h₁ : Runs (copyWord src buf tmp) w (4 * d.size + 3) w₁ true := by + simpa [w₁, hs, hb] using copyWord_run src buf tmp hsb hst hbt w ht + obtain ⟨m, hm, h₂⟩ := selectChild_run buf out pending hbo hbp hop right d w₁ + (by simp [w₁]) (by simp [w₁, Ne.symm hbo, ho]) (by simp [w₁, Ne.symm hbp, hp]) + change Runs (selectChild buf out pending right) w₁ m + (Function.update w₁ buf (d.child right).code) true at h₂ + have he : Function.update w₁ buf (d.child right).code = w₂ := by simp [w₁, w₂] + rw [he] at h₂ + have h₃ : Runs (transfer dst ∅) w₂ (2 * (w dst).length + 1) w₃ true := by + simpa [w₃, w₂, hdb] using clear_run dst w₂ + have h₄ : Runs (copyWord buf dst tmp) w₃ (4 * (d.child right).size + 3) w₄ true := by + have h := copyWord_run buf dst tmp (Ne.symm hdb) hbt hdt w₃ + (by simp [w₃, w₂, Ne.symm hdt, Ne.symm hbt, ht]) + simpa [w₃, w₂, w₄, Ne.symm hdb] using h + have h₅ : Runs (transfer buf ∅) w₄ (2 * (d.child right).size + 1) + (Function.update w dst (d.child right).code) true := by + have h := clear_run buf w₄ + have he : Function.update w₄ buf [] = Function.update w dst (d.child right).code := by + funext i + by_cases hi : i = buf + · subst i; simp [Ne.symm hdb, hb] + · simp [w₄, w₂, Function.update, hi] + rw [he] at h + simpa [w₄, w₂, Ne.symm hdb] using h + have hh := (((h₁.andThen h₂).andThen h₃).andThen h₄).andThen h₅ + have hc : (d.child right).size ≤ d.size := by + cases d with + | nil => rfl + | node l r => cases right <;> simp [DataTree.child, DataTree.size]; omega + have hd := d.size_pos + refine ⟨_, ?_, hh⟩ + omega + +end ParityWL.Complexity + +end OAI diff --git a/lean/OAI/Combinatorics/ParityLifts/TreeWords.lean b/lean/OAI/Combinatorics/ParityLifts/TreeWords.lean new file mode 100644 index 0000000000000000000000000000000000000000..51d61b6f00176738be6885a999e933ee91334c21 --- /dev/null +++ b/lean/OAI/Combinatorics/ParityLifts/TreeWords.lean @@ -0,0 +1,279 @@ +import OAI.Combinatorics.ParityLifts.StackRoutines + +namespace OAI + +namespace ParityWL.Complexity + +@[ext] lemma StackConfiguration.ext {Q : Type} {t a : ℕ} + {x y : StackConfiguration Q t a} (hs : x.state = y.state) (hw : x.word = y.word) : + x = y := by + cases x; cases y; cases hs; cases hw; rfl + +inductive StackTrace {Q : Type} {t a : ℕ} (P : StackMachine Q t a) : + StackConfiguration Q t a → ℕ → StackConfiguration Q t a → Prop + | refl (x) : StackTrace P x 0 x + | next (x) {n y} (h : P.output x.state = none) + (tail : StackTrace P (P.step x) n y) : StackTrace P x (n + 1) y + +lemma StackTrace.exec {Q : Type} {t a : ℕ} {P : StackMachine Q t a} + {x y z : StackConfiguration Q t a} {n m : ℕ} {b : Bool} + (h : StackTrace P x n y) (he : StackExec P y m z b) : + StackExec P x (n + m) z b := by + induction h with + | refl => simpa using he + | next x h _ ih => + have hh := StackExec.next x h (ih he) + convert hh using 1 + omega + +lemma StackTrace.trans {Q : Type} {t a : ℕ} {P : StackMachine Q t a} + {x y z : StackConfiguration Q t a} {n m : ℕ} + (h : StackTrace P x n y) (he : StackTrace P y m z) : + StackTrace P x (n + m) z := by + induction h with + | refl => simpa using he + | next x h _ ih => + have hh := StackTrace.next x h (ih he) + convert hh using 1 + omega + +lemma StackTrace.one {Q : Type} {t a : ℕ} {P : StackMachine Q t a} + (x : StackConfiguration Q t a) (h : P.output x.state = none) : + StackTrace P x 1 (P.step x) := .next _ h (.refl _) + +/-- Prepending a copy preserves the source and clears the temporary stack. -/ +def copyWord {t a : ℕ} (src dst tmp : Fin (t + 1)) := + (transfer (a := a) src {tmp}).andThen (transfer tmp {src, dst}) + +lemma copyWord_run {t a : ℕ} (src dst tmp : Fin (t + 1)) + (hsd : src ≠ dst) (hst : src ≠ tmp) (hdt : dst ≠ tmp) + (w : Words t a) (ht : w tmp = []) : + Runs (copyWord src dst tmp) w (4 * (w src).length + 3) + (Function.update w dst (w src ++ w dst)) true := by + have h1 := transfer_run src {tmp} w + have h2 := transfer_run tmp {src, dst} (transferred src {tmp} w) + have ht' : transferred src {tmp} w tmp = (w src).reverse := by + simp [transferred, Ne.symm hst, ht] + have hout : transferred tmp {src, dst} (transferred src {tmp} w) = + Function.update w dst (w src ++ w dst) := by + funext i + by_cases hi : i = tmp + · subst i + simp [transferred, Function.update, Ne.symm hdt, ht] + · by_cases hs : i = src + · subst i + simp [transferred, hst, Ne.symm hst, ht, Function.update, hsd] + · by_cases hd : i = dst + · subst i + simp [transferred, hdt, Ne.symm hst, ht, Ne.symm hsd, Function.update] + · simp [transferred, hi, hs, hd, Function.update] + have h := h1.andThen h2 + rw [ht', List.length_reverse, hout] at h + change Runs ((transfer src {tmp}).andThen (transfer tmp {src, dst})) _ _ _ _ + convert h using 1 + omega + +/-- A fixed one-cell insertion. -/ +def pushSymbol {t a : ℕ} (dst : Fin (t + 1)) (c : StackSymbol a) := + primitive (fun _ i => if i = dst then .push c else .keep) (fun _ => true) + +lemma pushSymbol_run {t a : ℕ} (dst : Fin (t + 1)) (c : StackSymbol a) (w : Words t a) : + Runs (pushSymbol dst c) w 1 (Function.update w dst (c :: w dst)) true := by + refine ⟨some true, ?_⟩ + have h := primitive_exec (fun (_ : Fin (t + 1) → Option (StackSymbol a)) i => + if i = dst then StackOp.push c else .keep) (fun _ => true) w + have he : applyOps (fun i => if i = dst then .push c else .keep) w = + Function.update w dst (c :: w dst) := by + funext i + by_cases hi : i = dst <;> simp [applyOps, StackOp.apply, Function.update, hi] + exact he ▸ h + +/-- A prefix-encoded finite binary tree; every code is nonempty and uniquely +self-delimiting. Working trees need no infinite-alphabet cells. -/ +inductive DataTree where + | nil + | node (left right : DataTree) + deriving DecidableEq + +def DataTree.code : DataTree → List (StackSymbol 0) + | .nil => [0] + | .node l r => 1 :: l.code ++ r.code + +def DataTree.size : DataTree → ℕ + | .nil => 1 + | .node l r => 1 + l.size + r.size + +@[simp] lemma DataTree.length_code (d : DataTree) : d.code.length = d.size := by + induction d with + | nil => rfl + | node l r hl hr => simp [DataTree.code, DataTree.size, hl, hr]; omega + +lemma DataTree.size_pos (d : DataTree) : 0 < d.size := by cases d <;> simp [DataTree.size] + +/-- Sweep one prefix tree into `dst` in reverse order, tracking unvisited child +slots on a unary stack. A null pending stack terminates; all transitions are +constant-size finite-table operations. -/ +def treeScan {t : ℕ} (src dst pending : Fin (t + 1)) : StackMachine Bool t 0 where + initial := false + output := fun b => if b then some true else none + transition := fun _ x => + if (x pending).isNone then (true, fun _ => .keep) else + (false, fun i => if i = src then .pop else + if i = dst then match x src with | none => .keep | some c => .push c else + if i = pending then if x src = some 1 then .push 0 else .pop else .keep) + +def scanUpdate {t : ℕ} (src dst pending : Fin (t + 1)) + (w : Words t 0) (chunk rest : List (StackSymbol 0)) (p : ℕ) : Words t 0 := + Function.update (Function.update (Function.update w src rest) dst + (chunk.reverse ++ w dst)) pending (List.replicate p 0) + +def scanResult {t : ℕ} (src dst pending : Fin (t + 1)) + (w : Words t 0) (d : DataTree) (rest : List (StackSymbol 0)) (p : ℕ) : Words t 0 := + scanUpdate src dst pending w d.code rest p + +lemma treeScan_nil_step {t : ℕ} (src dst pending : Fin (t + 1)) + (hsd : src ≠ dst) (hsp : src ≠ pending) (hdp : dst ≠ pending) + (w : Words t 0) (rest : List (StackSymbol 0)) (p : ℕ) + (hs : w src = 0 :: rest) (hp : w pending = List.replicate (p + 1) 0) : + (treeScan src dst pending).step ⟨false, w⟩ = + ⟨false, scanResult src dst pending w .nil rest p⟩ := by + apply StackConfiguration.ext + · simp [StackMachine.step, treeScan, hp, List.replicate_succ] + · funext i + simp only [StackMachine.step, treeScan, Bool.false_eq_true, ↓reduceIte, + hp, List.replicate_succ, List.head?_cons, Option.isNone_some] + by_cases hi : i = src + · subst i + simp [scanResult, scanUpdate, hsp, hsd, Function.update, StackOp.apply, hs] + · by_cases hd : i = dst + · subst i + simp [scanResult, scanUpdate, Ne.symm hsd, hdp, Function.update, StackOp.apply, hs, + DataTree.code] + · by_cases hpen : i = pending + · subst i + simp [scanResult, scanUpdate, Ne.symm hsp, Ne.symm hdp, Function.update, StackOp.apply, + hs, hp, List.replicate_succ] + · simp [scanResult, scanUpdate, hi, hd, hpen, Function.update, StackOp.apply] + +end ParityWL.Complexity + +namespace ParityWL.Complexity + +lemma scanUpdate_comp {t : ℕ} (src dst pending : Fin (t + 1)) + (hsd : src ≠ dst) (hsp : src ≠ pending) (hdp : dst ≠ pending) + (w : Words t 0) (u v rest mid : List (StackSymbol 0)) (p q : ℕ) : + scanUpdate src dst pending (scanUpdate src dst pending w u mid p) v rest q = + scanUpdate src dst pending w (u ++ v) rest q := by + funext i + by_cases hi : i = src + · subst i; simp [scanUpdate, hsp, hsd] + · by_cases hd : i = dst + · subst i + simp [scanUpdate, hdp, List.reverse_append, List.append_assoc] + · by_cases hp : i = pending + · subst i; simp [scanUpdate] + · simp [scanUpdate, Function.update, hi, hd, hp] + +lemma treeScan_node_step {t : ℕ} (src dst pending : Fin (t + 1)) + (hsd : src ≠ dst) (hsp : src ≠ pending) (hdp : dst ≠ pending) + (w : Words t 0) (rest : List (StackSymbol 0)) (p : ℕ) + (hs : w src = 1 :: rest) (hp : w pending = List.replicate (p + 1) 0) : + (treeScan src dst pending).step ⟨false, w⟩ = + ⟨false, scanUpdate src dst pending w [1] rest (p + 2)⟩ := by + apply StackConfiguration.ext + · simp [StackMachine.step, treeScan, hp, List.replicate_succ] + · funext i + simp only [StackMachine.step, treeScan, Bool.false_eq_true, ↓reduceIte, + hp, List.replicate_succ, List.head?_cons, Option.isNone_some] + by_cases hi : i = src + · subst i + simp [scanUpdate, hsp, hsd, Function.update, StackOp.apply, hs] + · by_cases hd : i = dst + · subst i + simp [scanUpdate, Ne.symm hsd, hdp, Function.update, StackOp.apply, hs] + · by_cases hpen : i = pending + · subst i + simp [scanUpdate, Ne.symm hsp, Ne.symm hdp, Function.update, StackOp.apply, + hs, hp, List.replicate_succ] + · simp [scanUpdate, hi, hd, hpen, Function.update, StackOp.apply] + +lemma treeScan_trace {t : ℕ} (src dst pending : Fin (t + 1)) + (hsd : src ≠ dst) (hsp : src ≠ pending) (hdp : dst ≠ pending) + (d : DataTree) (rest : List (StackSymbol 0)) (p : ℕ) (w : Words t 0) + (hs : w src = d.code ++ rest) (hp : w pending = List.replicate (p + 1) 0) : + StackTrace (treeScan src dst pending) ⟨false, w⟩ d.size + ⟨false, scanResult src dst pending w d rest p⟩ := by + induction d generalizing w rest p with + | nil => + have h := StackTrace.one (P := treeScan src dst pending) ⟨false, w⟩ rfl + rw [treeScan_nil_step src dst pending hsd hsp hdp w rest p hs hp] at h + exact h + | node l r hl hr => + let w₁ := scanUpdate src dst pending w [1] (l.code ++ r.code ++ rest) (p + 2) + have h₁ : StackTrace (treeScan src dst pending) ⟨false, w⟩ 1 ⟨false, w₁⟩ := by + have h := StackTrace.one (P := treeScan src dst pending) ⟨false, w⟩ rfl + rw [treeScan_node_step src dst pending hsd hsp hdp w _ p + (by simpa [DataTree.code, List.append_assoc] using hs) hp] at h + simpa [w₁, List.append_assoc] using h + have hls : w₁ src = l.code ++ (r.code ++ rest) := by + simp [w₁, scanUpdate, hsp, hsd, List.append_assoc] + have hlp : w₁ pending = List.replicate (p + 1 + 1) 0 := by + simp [w₁, scanUpdate] + have h₂ := hl (r.code ++ rest) (p + 1) w₁ hls hlp + let w₂ := scanResult src dst pending w₁ l (r.code ++ rest) (p + 1) + have hrs : w₂ src = r.code ++ rest := by simp [w₂, scanResult, scanUpdate, hsp, hsd] + have hrp : w₂ pending = List.replicate (p + 1) 0 := by simp [w₂, scanResult, scanUpdate] + have h₃ := hr rest p w₂ hrs hrp + have hout : scanResult src dst pending w₂ r rest p = + scanResult src dst pending w (.node l r) rest p := by + dsimp only [w₂, w₁, scanResult] + rw [scanUpdate_comp src dst pending hsd hsp hdp, + scanUpdate_comp src dst pending hsd hsp hdp] + simp [DataTree.code] + rw [hout] at h₃ + simpa [DataTree.size, Nat.add_assoc] using h₁.trans (h₂.trans h₃) + +lemma treeScan_run {t : ℕ} (src dst pending : Fin (t + 1)) + (hsd : src ≠ dst) (hsp : src ≠ pending) (hdp : dst ≠ pending) + (d : DataTree) (rest : List (StackSymbol 0)) (w : Words t 0) + (hs : w src = d.code ++ rest) (hp : w pending = [0]) : + Runs (treeScan src dst pending) w (d.size + 1) + (scanResult src dst pending w d rest 0) true := by + have h := treeScan_trace src dst pending hsd hsp hdp d rest 0 w hs hp + let v := scanResult src dst pending w d rest 0 + have hv : v pending = [] := by simp [v, scanResult, scanUpdate] + have he : (treeScan src dst pending).step ⟨false, v⟩ = ⟨true, v⟩ := by + simp [StackMachine.step, treeScan, hv, StackOp.apply] + have halt : StackExec (treeScan src dst pending) ⟨false, v⟩ 1 ⟨true, v⟩ true := by + apply StackExec.next _ rfl + rw [he] + exact .halt _ _ rfl + exact ⟨true, h.exec halt⟩ + +def moveTree {t : ℕ} (src dst pending : Fin (t + 1)) := + (pushSymbol (a := 0) pending 0).andThen (treeScan src dst pending) + +lemma moveTree_run {t : ℕ} (src dst pending : Fin (t + 1)) + (hsd : src ≠ dst) (hsp : src ≠ pending) (hdp : dst ≠ pending) + (d : DataTree) (rest : List (StackSymbol 0)) (w : Words t 0) + (hs : w src = d.code ++ rest) (hp : w pending = []) : + Runs (moveTree src dst pending) w (d.size + 3) + (scanResult src dst pending w d rest 0) true := by + have h₁ := pushSymbol_run pending (0 : StackSymbol 0) w + have h₂ := treeScan_run src dst pending hsd hsp hdp d rest + (Function.update w pending (0 :: w pending)) (by simpa [hsp] using hs) (by simp [hp]) + have hout : scanResult src dst pending (Function.update w pending (0 :: w pending)) d rest 0 = + scanResult src dst pending w d rest 0 := by + funext i + by_cases he : i = pending + · subst i; simp [scanResult, scanUpdate] + · simp [scanResult, scanUpdate, Function.update, he, hdp] + have h := h₁.andThen h₂ + rw [hout] at h + change Runs ((pushSymbol pending 0).andThen (treeScan src dst pending)) _ _ _ _ + convert h using 1 + omega + +end ParityWL.Complexity + +end OAI diff --git a/lean/OAI/Combinatorics/ParityLifts/UniformBasics.lean b/lean/OAI/Combinatorics/ParityLifts/UniformBasics.lean new file mode 100644 index 0000000000000000000000000000000000000000..daa04d71b1744c783cf3539f2361b67cfd942a00 --- /dev/null +++ b/lean/OAI/Combinatorics/ParityLifts/UniformBasics.lean @@ -0,0 +1,84 @@ +import OAI.Combinatorics.ParityLifts.FixedETH + +namespace OAI + +namespace ParityWL.Complexity + +def TreeProgram.mapWith {α β γ : Type} [TreeCodec α] [TreeCodec β] [TreeCodec γ] + {f : α × γ → β} (P : TreeProgram (α × γ) β f) : + TreeProgram (List α × γ) (List β) (fun x => x.1.map (fun a => f (a,x.2))) := by + let a := TreeProgram.fst α (List β × γ) + let bs := (TreeProgram.snd α (List β × γ)).comp (TreeProgram.fst (List β) γ) + let c := (TreeProgram.snd α (List β × γ)).comp (TreeProgram.snd (List β) γ) + let step := ((((a.pair c).comp P).pair bs).comp (PolyProgram.cons β).program).pair c + let init := (TreeProgram.fst (List α) γ).pair + ((TreeProgram.const ([] : List β)).pair (TreeProgram.snd (List α) γ)) + refine (init.comp step.foldl |>.comp (TreeProgram.fst (List β) γ) |>.comp + (PolyProgram.reverse β).program).congr ?_ + intro x + change (x.1.foldl (fun s a => (f (a,s.2)::s.1,s.2)) ([],x.2)).1.reverse=_ + simp [list_fold_map_context] + +def TreeProgram.map {α β : Type} [TreeCodec α] [TreeCodec β] {f : α → β} + (P : TreeProgram α β f) : TreeProgram (List α) (List β) (List.map f) := by + let Q := (TreeProgram.fst α Bool).comp P + exact (((TreeProgram.id (List α)).pair (TreeProgram.const false)).comp Q.mapWith).congr (by intro x; rfl) + +def TreeProgram.sublists (α : Type) [TreeCodec α] : + TreeProgram (List α) (List (List α)) List.sublists := by + let Q : PolyProgram (List α × α) (List (List α)) (fun x => [x.1,x.2::x.1]) := + .expr (.pair TExpr.input.left (.pair (.pair TExpr.input.right TExpr.input.left) .nil)) (by intro x; rfl) + let sw : PolyProgram (α × List (List α)) (List (List α) × α) (fun x => (x.2,x.1)) := + .expr (.pair TExpr.input.right TExpr.input.left) (by intro x; rfl) + let step := (sw.comp Q.mapWith |>.comp (PolyProgram.flatten (List α))).program + let init := (PolyProgram.reverse α).program.pair (TreeProgram.const ([[]] : List (List α))) + refine (init.comp step.foldl).congr ?_ + intro xs + change xs.reverse.foldl (fun s a => (s.map (fun l => [l,a::l])).flatten) [[]]=xs.sublists + rw [List.foldl_reverse] + induction xs with + | nil => rfl + | cons a xs ih => + simp only [List.foldr_cons,List.sublists_cons,ih] + rfl + +def PolyProgram.product (α β : Type) [TreeCodec α] [TreeCodec β] : + PolyProgram (List α × List β) (List (α × β)) (fun x => x.1.product x.2) := by + let sw : PolyProgram (β × α) (α × β) (fun x => (x.2,x.1)) := + .expr (.pair TExpr.input.right TExpr.input.left) (by intro x; rfl) + let input : PolyProgram (α × List β) (List β × α) (fun x => (x.2,x.1)) := + .expr (.pair TExpr.input.right TExpr.input.left) (by intro x; rfl) + exact ((input.comp sw.mapWith).mapWith.comp (PolyProgram.flatten (α × β))).congr (by intro x; rfl) + +def PolyProgram.natLt : PolyProgram (ℕ × ℕ) Bool (fun x => decide (x.1 n%2) := by + let Q := (((PolyProgram.natDivPos 2 (by omega)).pair (PolyProgram.const 2)).comp PolyProgram.natMul) + exact (((PolyProgram.id ℕ).pair Q).comp PolyProgram.natSub).congr (by intro n; change n-(n/2)*2=n%2; omega) + +def PolyProgram.natDiv : PolyProgram (ℕ × ℕ) ℕ (fun x => x.1/x.2) := by + let P := (PolyProgram.snd Bool ((ℕ × ℕ) × ℕ)).comp PolyProgram.divStep + have hg (u : Bool) (s : (ℕ × ℕ) × ℕ) : + (treeEncode (Complexity.divStep s)).size ≤ (treeEncode s).size+2*((treeEncode u).size+1)^0 := by + simp only [Complexity.divStep] + split <;> simp [DataTree.size] + all_goals omega + let F := P.foldlGrowing 2 0 hg + let init : PolyProgram (ℕ × ℕ) ((ℕ × ℕ) × ℕ) (fun x => ((0,0),x.2)) := + .expr (.pair (.pair .nil .nil) TExpr.input.right) (by intro x; rfl) + let I := ((PolyProgram.fst ℕ ℕ).comp PolyProgram.ticks).pair init + let R := (I.comp F).comp ((PolyProgram.fst (ℕ × ℕ) ℕ).comp (PolyProgram.snd ℕ ℕ)) + let Z := (PolyProgram.snd ℕ ℕ).comp PolyProgram.natZero + refine (Z.ite (PolyProgram.const 0) R).congr ?_ + intro ⟨n,t⟩ + by_cases ht : t=0 + · simp [ht] + · simp only [Function.comp_apply,decide_eq_true_eq,ht,↓reduceIte] + have he := fold_divStep (List.replicate n false) 0 t (by omega) + simpa [R,I,init,Function.comp_def] using congrArg (fun s => s.1.2) he + +end ParityWL.Complexity + +end OAI diff --git a/lean/OAI/Combinatorics/ParityLifts/UniformBridge.lean b/lean/OAI/Combinatorics/ParityLifts/UniformBridge.lean new file mode 100644 index 0000000000000000000000000000000000000000..48a3a7afa0136d58860701cf3423fefb10b2a24e --- /dev/null +++ b/lean/OAI/Combinatorics/ParityLifts/UniformBridge.lean @@ -0,0 +1,63 @@ +import OAI.Combinatorics.ParityLifts.UniformCompose + +namespace OAI + +namespace ParityWL.Complexity + +/-- A single parameter-oblivious finite machine meets every positive rate. Its +input polynomial degree is also fixed before choosing the rate. -/ +theorem uniform_reduction (c : Convention) (i : Implementation) (M : Machine) (f g : ℕ → ℝ) + (hlim : Filter.Tendsto (fun k : ℕ => g k/k) Filter.atTop (nhds 0)) + (hM : UniformWLBound M c i f g) : + ∃ d : ℕ, ∀ ε : ℝ, 0<ε → ∃ C : ℝ, 0 C*(L+1 : ℝ)^d*2^(ε*N)) := by + obtain ⟨D,P,_,_,hTrial⟩ := trialCode_rate + obtain ⟨A,hA,d,hd,hRace⟩ := raceDecision_bound (trialCode c M).decision + refine ⟨(2*trialNormalizeProgram.degree+3)*d,?_⟩ + intro ε hε + let η : ℝ := ε/(4*(d+1)) + have hη : 0<η := by dsimp only [η]; positivity + obtain ⟨j,hj,k,hk,hSmall⟩ := uniform_rate_parameters D P g hM.2.1 hlim η hη + have hkt : k ≤ bagParameter c k := by cases c <;> simp [bagParameter] + have hbase := hSmall (bagParameter c k) hkt + let r : ℝ := (D : ℝ)/j+(P : ℝ)*(g k+1)*leafSlope (bagParameter c k) (12*j)+η + have hr : 0 ≤ r := by + have hg := hM.2.1 k + have hs := leafSlope_nonneg (bagParameter c k) (12*j) + dsimp only [r] + positivity + have hrate : r*d ≤ ε := by + have heq : η*(4*(d+1))=ε := by + dsimp only [η] + exact div_mul_cancel₀ _ (by positivity) + have hb : r ≤ 2*η := by dsimp only [r]; linarith + have hp := mul_le_mul_of_nonneg_right hb (Nat.cast_nonneg (α:=ℝ) d) + nlinarith + obtain ⟨C,hC,hRun⟩ := hTrial c i M f g hM j hj k hk η hη + let K : ℝ := A*(C+j+k+3)^d + have hK : 0 b=true↔F.Satisfiable) + hall j k s hj hk b hs + refine ⟨t,a,ha,hans,?_⟩ + have hnum := trial_race_numeric A C r d (2*trialNormalizeProgram.degree+2) + j k (encodeFormula F).length N s t hA.le hC.le hr ht htime + apply hnum.trans + change K*_*(2 : ℝ)^((r*d)*N) ≤ K*_*(2 : ℝ)^(ε*N) + apply mul_le_mul_of_nonneg_left _ (by positivity) + exact Real.rpow_le_rpow_of_exponent_le (by norm_num) + (mul_le_mul_of_nonneg_right hrate (Nat.cast_nonneg N)) + +end ParityWL.Complexity + +end OAI diff --git a/lean/OAI/Combinatorics/ParityLifts/UniformCompose.lean b/lean/OAI/Combinatorics/ParityLifts/UniformCompose.lean new file mode 100644 index 0000000000000000000000000000000000000000..494bfd5321fe3b78ec324f5b37628a82ccdc8b26 --- /dev/null +++ b/lean/OAI/Combinatorics/ParityLifts/UniformCompose.lean @@ -0,0 +1,42 @@ +import OAI.Combinatorics.ParityLifts.UniformRates + +namespace OAI + +namespace ParityWL.Complexity + +lemma trial_race_numeric (A C r : ℝ) (d e j k L N s t : ℕ) + (hA : 0 ≤ A) (hC : 0 ≤ C) (hr : 0 ≤ r) + (hs : (s : ℝ) ≤ C*(L+1 : ℝ)^e*2^(r*N)) + (ht : (t : ℝ) ≤ A*(s+j+k+L+2 : ℝ)^d) : + (t : ℝ) ≤ A*(C+j+k+3 : ℝ)^d*(L+1 : ℝ)^((e+1)*d)*2^((r*d)*N) := by + let X : ℝ := (L+1 : ℝ)^(e+1)*2^(r*N) + have hL : (1 : ℝ) ≤ L+1 := by have := Nat.cast_nonneg (α:=ℝ) L; linarith + have hExp : (1 : ℝ) ≤ 2^(r*N) := Real.one_le_rpow (by norm_num) (by positivity) + have hXp : (1 : ℝ) ≤ (L+1 : ℝ)^(e+1) := one_le_pow₀ hL + have hX : 1 ≤ X := by dsimp only [X]; nlinarith + have hLs : (L : ℝ) ≤ X := by + calc + _ ≤ (L+1 : ℝ)^1 := by simp + _ ≤ (L+1 : ℝ)^(e+1) := pow_le_pow_right₀ hL (by omega) + _ ≤ X := le_mul_of_one_le_right (by positivity) hExp + have hCT : C*(L+1 : ℝ)^e*2^(r*N) ≤ C*X := by + dsimp only [X] + rw [←mul_assoc] + exact mul_le_mul_of_nonneg_right (mul_le_mul_of_nonneg_left + (pow_le_pow_right₀ hL (show e ≤ e+1 by omega)) hC) (Real.rpow_nonneg (by norm_num) _) + have hsum : (s+j+k+L+2 : ℝ) ≤ (C+j+k+3)*X := by + have hn : (0 : ℝ) ≤ j+k+2 := by positivity + have hconst := mul_le_mul_of_nonneg_left hX hn + nlinarith + have hpow := pow_le_pow_left₀ (by positivity : (0 : ℝ) ≤ s+j+k+L+2) hsum d + have he : ((2 : ℝ)^(r*N))^d=2^((r*d)*N) := by + rw [←Real.rpow_natCast,←Real.rpow_mul (by norm_num)] + congr 1 + ring + calc + _ ≤ A*((C+j+k+3)*X)^d := ht.trans (mul_le_mul_of_nonneg_left hpow hA) + _ = _ := by dsimp only [X]; rw [mul_pow,mul_pow,←pow_mul,he]; ring + +end ParityWL.Complexity + +end OAI diff --git a/lean/OAI/Combinatorics/ParityLifts/UniformDFS.lean b/lean/OAI/Combinatorics/ParityLifts/UniformDFS.lean new file mode 100644 index 0000000000000000000000000000000000000000..87dfd83ccfeed764331f250a77fdd96c21e555a2 --- /dev/null +++ b/lean/OAI/Combinatorics/ParityLifts/UniformDFS.lean @@ -0,0 +1,198 @@ +import OAI.Combinatorics.ParityLifts.UniformFlower + +namespace OAI + +namespace ParityWL.Complexity + +abbrev RuntimeDFSState (α : Type) := List (ClauseList α) × List (ClauseList α) × ℕ + +def runtimeDfsHead {α : Type} (s : RuntimeDFSState α) : ClauseList α := s.1.headD [] + +def runtimeDfsMerge {α : Type} (x : SparseResult α × RuntimeDFSState α) : RuntimeDFSState α := + if x.1.1 then (x.2.1.tail,dfsHead (x.2.1,x.2.2.1)::x.2.2.1,x.2.2.2) + else (x.1.2.1::x.1.2.2::x.2.1.tail,x.2.2) + +noncomputable def runtimeDfsStep {α : Type} [DecidableEq α] (s : RuntimeDFSState α) : RuntimeDFSState α := + runtimeDfsMerge (sparseStep s.2.2 (runtimeDfsHead s),s) + +def runtimeDfsHeadExpr : TExpr := .pair TExpr.input.right.right TExpr.input.left.left + +def runtimeDfsMergeExpr : TExpr := + let res := TExpr.input.left + let old := TExpr.input.right + .cond res.left + (.pair (.pair res.right.left (.pair res.right.right old.left.right)) old.right) + (.pair old.left.right (.pair (.pair old.left.left old.right.left) old.right.right)) + +lemma runtimeDfsHeadExpr_eval {α : Type} [TreeCodec α] (s : RuntimeDFSState α) : + runtimeDfsHeadExpr.eval (treeEncode s)=treeEncode (s.2.2,runtimeDfsHead s) := by + rcases s with ⟨xs,ys,r⟩ + cases xs <;> rfl + +lemma runtimeDfsMergeExpr_eval {α : Type} [TreeCodec α] (x : SparseResult α × RuntimeDFSState α) : + runtimeDfsMergeExpr.eval (treeEncode x)=treeEncode (runtimeDfsMerge x) := by + rcases x with ⟨⟨b,F,G⟩,⟨xs,ys,r⟩⟩ + cases xs <;> cases b <;> rfl + +noncomputable def runtimeDfsProgram (α : Type) [TreeCodec α] [DecidableEq α] : + TreeProgram (RuntimeDFSState α) (RuntimeDFSState α) runtimeDfsStep where + code := .seq (.pair (.seq runtimeDfsHeadExpr.compile (ParamPolyProgram.sparseStep α).program.code) .id) + runtimeDfsMergeExpr.compile + time := fun s => 1000*((treeEncode s).size+(ParamPolyProgram.sparseStep α).program.time (s.2.2,runtimeDfsHead s)+1) + run := by + intro s + let P := (ParamPolyProgram.sparseStep α).program + have hh : BEval runtimeDfsHeadExpr.compile (treeEncode s) + (runtimeDfsHeadExpr.cost*((treeEncode s).size+1)) (treeEncode (s.2.2,runtimeDfsHead s)) := by + simpa only [runtimeDfsHeadExpr_eval] using runtimeDfsHeadExpr.run (treeEncode s) + have hc := hh.seq (P.run (s.2.2,runtimeDfsHead s)) + have hm := hc.pair (BEval.id (treeEncode s)) + have hf : BEval runtimeDfsMergeExpr.compile (treeEncode (sparseStep s.2.2 (runtimeDfsHead s),s)) + (runtimeDfsMergeExpr.cost*((treeEncode (sparseStep s.2.2 (runtimeDfsHead s),s)).size+1)) + (treeEncode (runtimeDfsStep s)) := by + simpa only [runtimeDfsMergeExpr_eval,runtimeDfsStep] using runtimeDfsMergeExpr.run (treeEncode (sparseStep s.2.2 (runtimeDfsHead s),s)) + have hsize := (P.run (s.2.2,runtimeDfsHead s)).bounds.2.1 + apply (hm.seq hf).mono + simp only [runtimeDfsHeadExpr,runtimeDfsMergeExpr,TExpr.cost,treeEncode_pair,DataTree.size] + change (treeEncode (sparseStep s.2.2 (runtimeDfsHead s))).size≤P.time (s.2.2,runtimeDfsHead s) at hsize + dsimp only [P] at hsize ⊢ + omega + +lemma runtimeDfsState_size {α : Type} [TreeCodec α] (ts : List (SparseTree α)) (acc : List (ClauseList α)) + (r S A : ℕ) (ht : ∀ t∈ts, t.All (fun F => (treeEncode F).size≤S)) + (ha : ∀ F∈acc, (treeEncode F).size≤S) (hN : (ts.map SparseTree.nodes).sum+acc.length≤A) : + (treeEncode (ts.map SparseTree.root,acc,r)).size≤4+A*(S+1)+(treeEncode r).size := by + have h := dfsState_size ts acc S A ht ha hN + simp only [treeEncode_pair,DataTree.size] at * + omega + +lemma runtimeDfsLoop_run {α : Type} [TreeCodec α] [DecidableEq α] (r S A B : ℕ) + (hb : ∀ F : ClauseList α, (treeEncode F).size≤S → (ParamPolyProgram.sparseStep α).program.time (r,F)≤B) + (ts : List (SparseTree α)) (acc : List (ClauseList α)) + (hv : ∀ t∈ts, t.Valid r) (ht : ∀ t∈ts, t.All (fun F => (treeEncode F).size≤S)) + (ha : ∀ F∈acc, (treeEncode F).size≤S) (hN : (ts.map SparseTree.nodes).sum+acc.length≤A) : + BEval (.loop (runtimeDfsProgram α).code) (treeEncode (ts.map SparseTree.root,acc,r)) + (((ts.map SparseTree.nodes).sum+1)*(1002*(5+A*(S+1)+(treeEncode r).size+B))) + (treeEncode (([]:List (ClauseList α)),(ts.flatMap SparseTree.leaves).reverse++acc,r)) := by + generalize he : (ts.map SparseTree.nodes).sum=n + induction n using Nat.strong_induction_on generalizing ts acc with + | h n ih => + have hsize := runtimeDfsState_size ts acc r S A ht ha hN + cases ts with + | nil => + have hh := BEval.loop_stop (runtimeDfsProgram α).code (treeEncode (([]:List (ClauseList α)),acc,r)) rfl + have hz : n=0 := by simpa using he.symm + subst n + simp only [List.map_nil] at hsize + simpa using hh.mono (by + simp only [treeEncode_pair,treeEncode_nil,treeEncode_nat,numTree_size] at hsize ⊢ + nlinarith) + | cons t ts => + have hts : ∀ t∈ts, t.Valid r := fun t ht => hv t (by simp [ht]) + have hss : ∀ t∈ts, t.All (fun F => (treeEncode F).size≤S) := fun t hu => ht t (by simp [hu]) + have htv := hv t (by simp) + have htt := ht t (by simp) + have hh := (runtimeDfsProgram α).run ((t::ts).map SparseTree.root,acc,r) + have htime := hb t.root htt.root + have hhead : runtimeDfsHead ((t::ts).map SparseTree.root,acc,r)=t.root := rfl + change BEval _ _ (1000*((treeEncode ((t::ts).map SparseTree.root,acc,r)).size+ + (ParamPolyProgram.sparseStep α).program.time (r,runtimeDfsHead ((t::ts).map SparseTree.root,acc,r))+1)) _ at hh + rw [hhead] at hh + have hbnd : 1000*((treeEncode ((t::ts).map SparseTree.root,acc,r)).size+ + (ParamPolyProgram.sparseStep α).program.time (r,t.root)+1)≤1000*(5+A*(S+1)+(treeEncode r).size+B) := by omega + have hnil : (treeEncode ((t::ts).map SparseTree.root,acc,r)).child false≠.nil := by simp [DataTree.child] + cases t with + | leaf F => + change (sparseStep r F).1=true at htv + have hout : runtimeDfsStep ((SparseTree.leaf F::ts).map SparseTree.root,acc,r)=(ts.map SparseTree.root,F::acc,r) := by + simp only [runtimeDfsStep,runtimeDfsHead,dfsHead,List.map_cons,List.headD_cons,runtimeDfsMerge,htv, + SparseTree.root,↓reduceIte,List.tail_cons] + have hn : (ts.map SparseTree.nodes).sum + obtain ⟨hf,hl,hr,hlv,htv⟩ := htv + have hout : runtimeDfsStep ((SparseTree.branch F l t::ts).map SparseTree.root,acc,r)=((l::t::ts).map SparseTree.root,acc,r) := by + simp only [runtimeDfsStep,runtimeDfsHead,List.map_cons,List.headD_cons,runtimeDfsMerge,SparseTree.root,hf,hl,hr, + Bool.false_eq_true,↓reduceIte,List.tail_cons] + have hn : ((l::t::ts).map SparseTree.nodes).sum (treeEncode F).size≤S) := by + intro u hu; rcases List.mem_cons.mp hu with rfl | hu + · exact htt.2.1 + · rcases List.mem_cons.mp hu with rfl | hu + · exact htt.2.2 + · exact hss u hu + obtain hrec := ih _ hn (l::t::ts) acc hv' ht' ha hn' rfl + rw [hout] at hh + have hrun := BEval.loop_next hnil (hh.mono hbnd) hrec + convert hrun.mono (show _≤(n+1)*(1002*(5+A*(S+1)+(treeEncode r).size+B)) from by + simp only [List.map_cons,List.sum_cons,SparseTree.nodes] at he ⊢ + generalize 5+A*(S+1)+(treeEncode r).size+B=D at * + nlinarith) using 1; simp [SparseTree.leaves,List.append_assoc] + + +def runtimeDfsInitExpr : TExpr := + .pair (.pair TExpr.input.right .nil) (.pair .nil TExpr.input.left) + +noncomputable def runtimeSparseCode (α : Type) [TreeCodec α] [DecidableEq α] : FCode := + .seq runtimeDfsInitExpr.compile (.seq (.loop (runtimeDfsProgram α).code) (.seq .right .left)) + +lemma runtimeSparseCode_run {α : Type} [TreeCodec α] [DecidableEq α] (r S B : ℕ) + (hb : ∀ F : ClauseList α, (treeEncode F).size≤S → (ParamPolyProgram.sparseStep α).program.time (r,F)≤B) + (T : SparseTree α) (hv : T.Valid r) (ht : T.All (fun F => (treeEncode F).size≤S)) : + BEval (runtimeSparseCode α) (treeEncode (r,T.root)) + (4000*(T.nodes+1)^2*(S+B+(treeEncode r).size+6)) (treeEncode T.leaves.reverse) := by + have hinit : BEval runtimeDfsInitExpr.compile (treeEncode (r,T.root)) + (runtimeDfsInitExpr.cost*((treeEncode (r,T.root)).size+1)) + (treeEncode ([T.root],([]:List (ClauseList α)),r)) := runtimeDfsInitExpr.run _ + have hloop := runtimeDfsLoop_run r S T.nodes B hb [T] [] + (by intro t ht; simpa using (List.mem_singleton.mp ht) ▸ hv) + (by intro t ht'; simpa using (List.mem_singleton.mp ht') ▸ ht) + (by simp) (by simp) + simp only [List.map_cons,List.map_nil,List.sum_cons,List.sum_nil,Nat.add_zero, + List.flatMap_cons,List.flatMap_nil,List.append_nil] at hloop + have hr := (BEval.right (treeEncode (([]:List (ClauseList α)),T.leaves.reverse,r))).seq + (BEval.left (treeEncode (T.leaves.reverse,r))) + change BEval _ _ _ (treeEncode T.leaves.reverse) at hr + have hs := hloop.bounds.2.1 + have hroot := ht.root + apply (hinit.seq (hloop.seq hr)).mono + simp only [runtimeDfsInitExpr,TExpr.cost,treeEncode_pair,DataTree.size] at * + have hn := T.nodes_pos + generalize T.nodes=n at * + generalize (treeEncode T.root).size=sz at * + generalize (treeEncode T.leaves.reverse).size=z at * + generalize (treeEncode r).size=R at * + let X := (n+1)^2*(S+B+R+6) + have hc : (n+1)*(1002*(5+n*(S+1)+R+B))≤1002*X := by + calc + _ ≤ (n+1)*(1002*((n+1)*(S+B+R+6))) := by gcongr; nlinarith + _ = _ := by dsimp [X]; ring + have hX : S+B+R+6≤X := Nat.le_mul_of_pos_left _ (by positivity) + calc + _ ≤ 4000*X := by omega + _ = _ := by dsimp [X]; ring + +end ParityWL.Complexity + +end OAI diff --git a/lean/OAI/Combinatorics/ParityLifts/UniformData.lean b/lean/OAI/Combinatorics/ParityLifts/UniformData.lean new file mode 100644 index 0000000000000000000000000000000000000000..76e1c698eeb0c26caa02cae6db9c3a9dc93d82e9 --- /dev/null +++ b/lean/OAI/Combinatorics/ParityLifts/UniformData.lean @@ -0,0 +1,99 @@ +import OAI.Combinatorics.ParityLifts.UniformTags + +namespace OAI + +namespace ParityWL.Complexity + +abbrev RawChoiceData := List (List (List ℕ)) × List (List ℕ) + +def ChoiceData.raw {t : ℕ} (D : ChoiceData t) : RawChoiceData := + (List.ofFn (fun i => (D.1 i).map List.ofFn),List.ofFn (fun i => List.ofFn (D.2 i))) + +def RawChoiceData.entry (D : RawChoiceData) (i d j : ℕ) : ℕ := + (((D.1[i]?.getD [])[d]?.getD [])[j]?).getD 0 + +def RawChoiceData.bound (D : RawChoiceData) (i j : ℕ) : ℕ := + ((D.2[min i j]?.getD [])[max i j]?).getD 0 + +def RawChoiceData.label (D : RawChoiceData) (i d j : ℕ) : ℕ := + min (D.entry i d j) (D.bound i j) + +lemma ChoiceData.raw_entry {t : ℕ} (D : ChoiceData t) (i : Fin t) (d : ℕ) (j : Fin t) : + D.raw.entry i.val d j.val=D.entry i d j := by + simp only [RawChoiceData.entry,raw,List.getElem?_ofFn,Fin.eta] + cases h : (D.1 i)[d]? with + | none => simp [h,entry] + | some row => simp [h,entry,j.isLt] + +lemma ChoiceData.raw_bound {t : ℕ} (D : ChoiceData t) (i j : Fin t) : + D.raw.bound i.val j.val=D.pairBound i j := by + have hi : min i.val j.val simp [RawChoiceData.roleSize,rawRole,raw,roleSize,i.isLt] + | inr h => + have hn : h.1.1.1.1.val≠h.1.1.1.2.val := ne_of_lt h.1.1.2 + dsimp only [RawChoiceData.roleSize,rawRole,raw,roleSize] + rw [ite_eq_right hn] + simp [h.1.1.1.1.isLt,h.1.1.1.2.isLt] + +def RawChoiceData.helperTest (D : RawChoiceData) (h : RawRole) (q i d : ℕ) : Bool := + if i=h.1 then decide (D.label i d h.2.1=q) + else if i=h.2.1 then decide (D.label i d h.1=q) + else decide (i=h.2.2) + +def RawChoiceData.baseTest (D : RawChoiceData) (a : RawRole) (d : ℕ) (b : RawRole) (e : ℕ) : Bool := + if a.1=a.2.1 then + if b.1=b.2.1 then decide (a.1≠b.1) && decide (D.label a.1 d b.1=D.label b.1 e a.1) + else D.helperTest b e a.1 d + else if b.1=b.2.1 then D.helperTest a d b.1 e else false + +lemma ChoiceData.raw_helperTest {t : ℕ} (D : ChoiceData t) (h : Helper t) (q : ℕ) (i : Fin t) (d : ℕ) : + D.raw.helperTest (rawRole (.inr h)) q i.val d=D.helperTest h q i d := by + dsimp only [RawChoiceData.helperTest,rawRole,helperTest] + rw [D.raw_label,D.raw_label] + simp only [Fin.val_inj] + +lemma ChoiceData.raw_baseTest {t : ℕ} (D : ChoiceData t) (a b : TemplateVertex t) (d e : ℕ) : + D.raw.baseTest (rawRole a) d (rawRole b) e=D.baseTest a d b e := by + cases a with + | inl i => + cases b with + | inl j => + dsimp only [RawChoiceData.baseTest,rawRole,baseTest] + simp only [ite_true,D.raw_label] + congr 2 + exact propext (not_congr Fin.val_inj) + | inr h => + have hn : h.1.1.1.1.val≠h.1.1.1.2.val := ne_of_lt h.1.1.2 + dsimp only [RawChoiceData.baseTest,rawRole,baseTest] + rw [ite_eq_right hn] + simpa only [ite_true,rawRole] using D.raw_helperTest h e i d + | inr h => + have hn : h.1.1.1.1.val≠h.1.1.1.2.val := ne_of_lt h.1.1.2 + cases b with + | inl i => + dsimp only [RawChoiceData.baseTest,rawRole,baseTest] + rw [ite_eq_right hn] + simpa only [ite_true,rawRole] using D.raw_helperTest h d i e + | inr g => + have gn : g.1.1.1.1.val≠g.1.1.1.2.val := ne_of_lt g.1.1.2 + dsimp only [RawChoiceData.baseTest,rawRole,baseTest] + rw [ite_eq_right hn,ite_eq_right gn] + +end ParityWL.Complexity + +end OAI diff --git a/lean/OAI/Combinatorics/ParityLifts/UniformETH.lean b/lean/OAI/Combinatorics/ParityLifts/UniformETH.lean new file mode 100644 index 0000000000000000000000000000000000000000..1d41667efc7730deba330503402f4b293a18c965 --- /dev/null +++ b/lean/OAI/Combinatorics/ParityLifts/UniformETH.lean @@ -0,0 +1,17 @@ +import OAI.Combinatorics.ParityLifts.UniformBridge + +namespace OAI + +namespace ParityWL.Complexity + +/-- Uniform exclusion under the weaker, single-machine subexponential +hypothesis; no positive forbidden rate and no convergence modulus are assumed. -/ +theorem uniform_eth : UniformETHStatement := by + intro hETH c i h + obtain ⟨M,f,g,hlim,hm⟩ := h + obtain ⟨d,hd⟩ := uniform_reduction c i M f g hlim hm + exact hETH ⟨(raceCode (trialCode c M).decision).decision,d,hd⟩ + +end ParityWL.Complexity + +end OAI diff --git a/lean/OAI/Combinatorics/ParityLifts/UniformFlower.lean b/lean/OAI/Combinatorics/ParityLifts/UniformFlower.lean new file mode 100644 index 0000000000000000000000000000000000000000..fa0794247756b1e2ad1146668732bfcb48f1ed93 --- /dev/null +++ b/lean/OAI/Combinatorics/ParityLifts/UniformFlower.lean @@ -0,0 +1,75 @@ +import OAI.Combinatorics.ParityLifts.UniformGraphs + +namespace OAI + +namespace ParityWL.Complexity + +noncomputable def PolyProgram.runtimeGoodFlower (α : Type) [TreeCodec α] [DecidableEq α] (p q : ℕ) : + PolyProgram (FlowerRecord α × (ℕ × ClauseList α)) Bool + (fun x => @decide (GoodFlower x.2.2 p q x.2.1 x.1) (Classical.propDecidable _)) := by + classical + let core : PolyProgram (FlowerRecord α × (ℕ × ClauseList α)) (List α) (fun x => x.1.1) := + .expr TExpr.input.left.left (by intro x; rfl) + let petals : PolyProgram (FlowerRecord α × (ℕ × ClauseList α)) (ClauseList α) (fun x => x.1.2) := + .expr TExpr.input.left.right (by intro x; rfl) + let h : PolyProgram (FlowerRecord α × (ℕ × ClauseList α)) ℕ (fun x => x.2.1) := + .expr TExpr.input.right.left (by intro x; rfl) + let input : PolyProgram (FlowerRecord α × (ℕ × ClauseList α)) (FlowerRecord α × ClauseList α) + (fun x => (x.1,x.2.2)) := .expr (.pair TExpr.input.left TExpr.input.right.right) (by intro x; rfl) + let cp := core.comp (PolyProgram.cardEq α p) + let hp := ((petals.comp (PolyProgram.cnfCard α)).pair h).comp (PolyProgram.equal ℕ) + let qp := petals.comp (PolyProgram.cardEq α q).all + let apart := (petals.pair core).comp ((PolyProgram.swap (List α) (List α)).comp (PolyProgram.clauseDisjoint α)).allWith + let pp := petals.comp (PolyProgram.petalsApart α) + let H := input.comp (PolyProgram.flowerCover α) + exact (cp.andOn (hp.andOn (qp.andOn (apart.andOn (pp.andOn H))))).congr (by + intro x + apply Bool.eq_iff_iff.mpr + simp only [decide_eq_true_eq] + simp only [Function.comp_def,Bool.and_eq_true,decide_eq_true_eq,List.all_eq_true,GoodFlower]) + +noncomputable def ParamPolyProgram.flowerCandidates (α : Type) [TreeCodec α] [DecidableEq α] (p : ℕ) : + ParamPolyProgram ℕ (ClauseList α) (List (FlowerRecord α)) (fun h F => Complexity.flowerCandidates F p h) := by + let cores : ParamPolyProgram ℕ (ClauseList α) (List (List α)) (fun _ F => Complexity.allTuples p F.flatten) := + .lift ((PolyProgram.flatten α).comp (PolyProgram.allTuples α p)) + let clauses := ParamPolyProgram.allTuples (List α) + let petalMap := (PolyProgram.clauseDiff α).mapWith + let cell := (PolyProgram.fst (List α) (ClauseList α)).pair + ((PolyProgram.swap (List α) (ClauseList α)).comp petalMap) + let cells := (PolyProgram.swap (List α) (List (ClauseList α))).comp + ((PolyProgram.swap (ClauseList α) (List α)).comp cell).mapWith + exact (((cores.pair clauses).post cells.mapWith).post (PolyProgram.flatten (FlowerRecord α))).congr (by + intro h F + simp only [Complexity.flowerCandidates,Function.comp_def,List.flatMap_def]) + +noncomputable def ParamPolyProgram.flowerList (α : Type) [TreeCodec α] [DecidableEq α] (p q : ℕ) : + ParamPolyProgram ℕ (ClauseList α) (List (FlowerRecord α)) (fun h F => Complexity.flowerList F p q h) := by + let rest : ParamPolyProgram ℕ (ClauseList α) (ℕ × ClauseList α) (fun h F => (h,F)) := + .ofPoly (f := fun h F => (h,F)) (PolyProgram.id _) + exact (((ParamPolyProgram.flowerCandidates α p).pair rest).post + (PolyProgram.runtimeGoodFlower α p q).filterWith).congr (by intro h F; rfl) + +noncomputable def ParamPolyProgram.sparseStep (α : Type) [TreeCodec α] [DecidableEq α] : + ParamPolyProgram ℕ (ClauseList α) (SparseResult α) (fun r F => Complexity.sparseStep r F) := by + let square := ((PolyProgram.id ℕ).pair (PolyProgram.id ℕ)).comp PolyProgram.natMul + let fourth := square.comp square + let L₁ := (ParamPolyProgram.flowerList α 1 1).reindex square + let L₂ := (ParamPolyProgram.flowerList α 2 1).reindex fourth + let L₃ := (ParamPolyProgram.flowerList α 1 2).reindex fourth + let I : ParamPolyProgram ℕ (ClauseList α) (ClauseList α) (fun _ F => F) := .lift (PolyProgram.id _) + let done : PolyProgram (ClauseList α) (SparseResult α) (fun F => (true,F,F)) := + .expr (.pair (.const (boolTree true)) (.pair .input .input)) (by intro x; rfl) + let B₁ := (I.pair (L₁.post (PolyProgram.head (FlowerRecord α) ([],[])))).post (PolyProgram.sparseBranch α) + let B₂ := (I.pair (L₂.post (PolyProgram.head (FlowerRecord α) ([],[])))).post (PolyProgram.sparseBranch α) + let B₃ := (I.pair (L₃.post (PolyProgram.head (FlowerRecord α) ([],[])))).post (PolyProgram.sparseBranch α) + let test := PolyProgram.null (FlowerRecord α) + exact ((L₁.post test).ite ((L₂.post test).ite ((L₃.post test).ite (.lift done) B₃) B₂) B₁).congr (by + intro r F + have h2 : r*r=r^2 := (pow_two r).symm + have h4 : r^2*r^2=r^4 := by ring + simp only [Complexity.sparseStep,Function.comp_def,id_eq,h4,h2] + rfl) + +end ParityWL.Complexity + +end OAI diff --git a/lean/OAI/Combinatorics/ParityLifts/UniformGraphs.lean b/lean/OAI/Combinatorics/ParityLifts/UniformGraphs.lean new file mode 100644 index 0000000000000000000000000000000000000000..6628c58e4794c5ee8f54529d901fbea5811d9365 --- /dev/null +++ b/lean/OAI/Combinatorics/ParityLifts/UniformGraphs.lean @@ -0,0 +1,199 @@ +import OAI.Combinatorics.ParityLifts.UniformOutput + +namespace OAI + +namespace ParityWL.Complexity + +noncomputable def PolyProgram.eqOn {α β : Type} [TreeCodec α] [TreeCodec β] [DecidableEq β] + {f g : α → β} (P : PolyProgram α β f) (Q : PolyProgram α β g) : + PolyProgram α Bool (fun x => decide (f x=g x)) := (P.pair Q).comp (PolyProgram.equal β) + +def PolyProgram.andOn {α : Type} [TreeCodec α] {f g : α → Bool} + (P : PolyProgram α Bool f) (Q : PolyProgram α Bool g) : + PolyProgram α Bool (fun x => f x && g x) := (P.ite Q (PolyProgram.const false)).congr + (by intro x; cases f x <;> rfl) + +def PolyProgram.orOn {α : Type} [TreeCodec α] {f g : α → Bool} + (P : PolyProgram α Bool f) (Q : PolyProgram α Bool g) : + PolyProgram α Bool (fun x => f x || g x) := (P.ite (PolyProgram.const true) Q).congr + (by intro x; cases f x <;> rfl) + +noncomputable def PolyProgram.rawAdjacent : PolyProgram (RawRole × RawRole) Bool + (fun x => Complexity.rawAdjacent x.1 x.2) := by + let a : PolyProgram (RawRole × RawRole) ℕ (fun x => x.1.1) := .expr TExpr.input.left.left (by intro x; rfl) + let b : PolyProgram (RawRole × RawRole) ℕ (fun x => x.1.2.1) := .expr TExpr.input.left.right.left (by intro x; rfl) + let c : PolyProgram (RawRole × RawRole) ℕ (fun x => x.1.2.2) := .expr TExpr.input.left.right.right (by intro x; rfl) + let d : PolyProgram (RawRole × RawRole) ℕ (fun x => x.2.1) := .expr TExpr.input.right.left (by intro x; rfl) + let e : PolyProgram (RawRole × RawRole) ℕ (fun x => x.2.2.1) := .expr TExpr.input.right.right.left (by intro x; rfl) + let f : PolyProgram (RawRole × RawRole) ℕ (fun x => x.2.2.2) := .expr TExpr.input.right.right.right (by intro x; rfl) + refine ((a.eqOn b).ite ((d.eqOn e).ite ((a.eqOn d).comp PolyProgram.not) + ((a.eqOn d).orOn ((a.eqOn e).orOn (a.eqOn f)))) + ((d.eqOn e).ite ((d.eqOn a).orOn ((d.eqOn b).orOn (d.eqOn c))) (PolyProgram.const false))).congr ?_ + intro x + simp only [Function.comp_apply,decide_eq_true_eq,Complexity.rawAdjacent] + split <;> split <;> simp [Bool.decide_or,decide_not] + +noncomputable def PolyProgram.rawEntry : + PolyProgram (RawChoiceData × (ℕ × (ℕ × ℕ))) ℕ (fun x => x.1.entry x.2.1 x.2.2.1 x.2.2.2) := by + let D : PolyProgram (RawChoiceData × (ℕ × (ℕ × ℕ))) (List (List (List ℕ))) (fun x => x.1.1) := + .expr TExpr.input.left.left (by intro x; rfl) + let i : PolyProgram (RawChoiceData × (ℕ × (ℕ × ℕ))) ℕ (fun x => x.2.1) := + .expr TExpr.input.right.left (by intro x; rfl) + let d : PolyProgram (RawChoiceData × (ℕ × (ℕ × ℕ))) ℕ (fun x => x.2.2.1) := + .expr TExpr.input.right.right.left (by intro x; rfl) + let j : PolyProgram (RawChoiceData × (ℕ × (ℕ × ℕ))) ℕ (fun x => x.2.2.2) := + .expr TExpr.input.right.right.right (by intro x; rfl) + exact (j.pair ((d.pair ((i.pair D).comp (PolyProgram.getD (List (List ℕ)) []))).comp + (PolyProgram.getD (List ℕ) []))).comp (PolyProgram.getD ℕ 0) + +noncomputable def PolyProgram.rawBound : PolyProgram (RawChoiceData × (ℕ × ℕ)) ℕ + (fun x => x.1.bound x.2.1 x.2.2) := by + let D : PolyProgram (RawChoiceData × (ℕ × ℕ)) (List (List ℕ)) (fun x => x.1.2) := + .expr TExpr.input.left.right (by intro x; rfl) + let ij := PolyProgram.snd RawChoiceData (ℕ × ℕ) + let lo := ij.comp PolyProgram.natMin + let i := ij.comp (PolyProgram.fst ℕ ℕ) + let j := ij.comp (PolyProgram.snd ℕ ℕ) + let hi := ((i.pair j).comp PolyProgram.natLe).ite j i + refine (hi.pair ((lo.pair D).comp (PolyProgram.getD (List ℕ) [])) |>.comp (PolyProgram.getD ℕ 0)).congr ?_ + intro x + change _[if decide (x.2.1≤x.2.2) then x.2.2 else x.2.1]?.getD 0=_ + rw [show (if decide (x.2.1≤x.2.2) then x.2.2 else x.2.1)=max x.2.1 x.2.2 by + by_cases h : x.2.1≤x.2.2 <;> simp [h,max_def]] + rfl + +noncomputable def PolyProgram.rawLabel : PolyProgram (RawChoiceData × (ℕ × (ℕ × ℕ))) ℕ + (fun x => x.1.label x.2.1 x.2.2.1 x.2.2.2) := by + let Q : PolyProgram (RawChoiceData × (ℕ × (ℕ × ℕ))) (RawChoiceData × (ℕ × ℕ)) + (fun x => (x.1,x.2.1,x.2.2.2)) := + .expr (.pair TExpr.input.left (.pair TExpr.input.right.left TExpr.input.right.right.right)) (by intro x; rfl) + exact (PolyProgram.rawEntry.pair (Q.comp PolyProgram.rawBound)).comp PolyProgram.natMin + +noncomputable def PolyProgram.rawRoleSize : PolyProgram (RawChoiceData × RawRole) ℕ + (fun x => x.1.roleSize x.2) := by + let i : PolyProgram (RawChoiceData × RawRole) ℕ (fun x => x.2.1) := + .expr TExpr.input.right.left (by intro x; rfl) + let j : PolyProgram (RawChoiceData × RawRole) ℕ (fun x => x.2.2.1) := + .expr TExpr.input.right.right.left (by intro x; rfl) + let D : PolyProgram (RawChoiceData × RawRole) (List (List (List ℕ))) (fun x => x.1.1) := + .expr TExpr.input.left.left (by intro x; rfl) + let B : PolyProgram (RawChoiceData × RawRole) (List (List ℕ)) (fun x => x.1.2) := + .expr TExpr.input.left.right (by intro x; rfl) + let nr := (i.pair D |>.comp (PolyProgram.getD (List (List ℕ)) [])).comp (PolyProgram.length (List ℕ)) + let nb := (j.pair (i.pair B |>.comp (PolyProgram.getD (List ℕ) [])) |>.comp + (PolyProgram.getD ℕ 0)).comp PolyProgram.natSucc + exact ((i.eqOn j).ite nr nb).congr (by intro x; simp only [Function.comp_apply,decide_eq_true_eq]; rfl) + +noncomputable def PolyProgram.rawHelperTest : PolyProgram (RawChoiceData × (RawRole × (ℕ × (ℕ × ℕ)))) Bool + (fun x => x.1.helperTest x.2.1 x.2.2.1 x.2.2.2.1 x.2.2.2.2) := by + let i : PolyProgram (RawChoiceData × (RawRole × (ℕ × (ℕ × ℕ)))) ℕ (fun x => x.2.2.2.1) := + .expr TExpr.input.right.right.right.left (by intro x; rfl) + let a : PolyProgram (RawChoiceData × (RawRole × (ℕ × (ℕ × ℕ)))) ℕ (fun x => x.2.1.1) := + .expr TExpr.input.right.left.left (by intro x; rfl) + let b : PolyProgram (RawChoiceData × (RawRole × (ℕ × (ℕ × ℕ)))) ℕ (fun x => x.2.1.2.1) := + .expr TExpr.input.right.left.right.left (by intro x; rfl) + let c : PolyProgram (RawChoiceData × (RawRole × (ℕ × (ℕ × ℕ)))) ℕ (fun x => x.2.1.2.2) := + .expr TExpr.input.right.left.right.right (by intro x; rfl) + let d : PolyProgram (RawChoiceData × (RawRole × (ℕ × (ℕ × ℕ)))) ℕ (fun x => x.2.2.2.2) := + .expr TExpr.input.right.right.right.right (by intro x; rfl) + let q : PolyProgram (RawChoiceData × (RawRole × (ℕ × (ℕ × ℕ)))) ℕ (fun x => x.2.2.1) := + .expr TExpr.input.right.right.left (by intro x; rfl) + let D := PolyProgram.fst RawChoiceData (RawRole × (ℕ × (ℕ × ℕ))) + exact ((i.eqOn a).ite (((D.pair (i.pair (d.pair b))).comp PolyProgram.rawLabel).eqOn q) + ((i.eqOn b).ite (((D.pair (i.pair (d.pair a))).comp PolyProgram.rawLabel).eqOn q) + (i.eqOn c))).congr (by intro x; simp only [Function.comp_apply,decide_eq_true_eq]; rfl) + +noncomputable def PolyProgram.rawBaseTest : PolyProgram (RawChoiceData × (RawVertex × RawVertex)) Bool + (fun x => x.1.baseTest x.2.1.1.1 x.2.1.2 x.2.2.1.1 x.2.2.2) := by + let D : PolyProgram (RawChoiceData × (RawVertex × RawVertex)) (RawChoiceData) (fun x => x.1) := + .expr TExpr.input.left (by intro x; rfl) + let a : PolyProgram (RawChoiceData × (RawVertex × RawVertex)) (RawRole) (fun x => x.2.1.1.1) := + .expr TExpr.input.right.left.left.left (by intro x; rfl) + let b : PolyProgram (RawChoiceData × (RawVertex × RawVertex)) (RawRole) (fun x => x.2.2.1.1) := + .expr TExpr.input.right.right.left.left (by intro x; rfl) + let d : PolyProgram (RawChoiceData × (RawVertex × RawVertex)) (ℕ) (fun x => x.2.1.2) := + .expr TExpr.input.right.left.right (by intro x; rfl) + let e : PolyProgram (RawChoiceData × (RawVertex × RawVertex)) (ℕ) (fun x => x.2.2.2) := + .expr TExpr.input.right.right.right (by intro x; rfl) + let a₁ := a.comp (PolyProgram.fst ℕ (ℕ × ℕ)) + let a₂ := a.comp ((PolyProgram.snd ℕ (ℕ × ℕ)).comp (PolyProgram.fst ℕ ℕ)) + let b₁ := b.comp (PolyProgram.fst ℕ (ℕ × ℕ)) + let b₂ := b.comp ((PolyProgram.snd ℕ (ℕ × ℕ)).comp (PolyProgram.fst ℕ ℕ)) + let L := (D.pair (a₁.pair (d.pair b₁))).comp PolyProgram.rawLabel + let R := (D.pair (b₁.pair (e.pair a₁))).comp PolyProgram.rawLabel + let H1 := (D.pair (b.pair (e.pair (a₁.pair d)))).comp PolyProgram.rawHelperTest + let H2 := (D.pair (a.pair (d.pair (b₁.pair e)))).comp PolyProgram.rawHelperTest + refine ((a₁.eqOn a₂).ite ((b₁.eqOn b₂).ite + (((a₁.eqOn b₁).comp PolyProgram.not).andOn (L.eqOn R)) H1) + ((b₁.eqOn b₂).ite H2 (PolyProgram.const false))).congr ?_ + intro x + simp only [Function.comp_apply,decide_eq_true_eq,RawChoiceData.baseTest,decide_not] + +noncomputable def PolyProgram.rawTagTest : PolyProgram (RawTag × RawTag) Bool + (fun x => Complexity.rawTagTest x.1 x.2) := by + let a : PolyProgram (RawTag × RawTag) (RawRole) (fun x => x.1.1) := + .expr TExpr.input.left.left (by intro x; rfl) + let as : PolyProgram (RawTag × RawTag) (List RawRole) (fun x => x.1.2) := + .expr TExpr.input.left.right (by intro x; rfl) + let b : PolyProgram (RawTag × RawTag) (RawRole) (fun x => x.2.1) := + .expr TExpr.input.right.left (by intro x; rfl) + let bs : PolyProgram (RawTag × RawTag) (List RawRole) (fun x => x.2.2) := + .expr TExpr.input.right.right (by intro x; rfl) + let A := (b.pair as).comp (PolyProgram.mem RawRole) + let B := (a.pair bs).comp (PolyProgram.mem RawRole) + refine ((a.pair b |>.comp PolyProgram.rawAdjacent).andOn (A.eqOn B)).congr ?_ + intro x + simp only [Function.comp_apply,Complexity.rawTagTest] + congr 1 + apply Bool.eq_iff_iff.mpr + simp only [decide_eq_true_eq,decide_eq_decide] + +noncomputable def PolyProgram.rawEdgeTest : PolyProgram (RawChoiceData × (RawVertex × RawVertex)) Bool + (fun x => Complexity.rawEdgeTest x.1 x.2.1 x.2.2) := by + let P : PolyProgram (RawChoiceData × (RawVertex × RawVertex)) (RawTag × RawTag) + (fun x => (x.2.1.1,x.2.2.1)) := + .expr (.pair TExpr.input.right.left.left TExpr.input.right.right.left) (by intro x; rfl) + exact PolyProgram.rawBaseTest.andOn (P.comp PolyProgram.rawTagTest) + +noncomputable def PolyProgram.rawVertices : PolyProgram (RawChoiceData × List RawTag) (List RawVertex) + (fun x => Complexity.rawVertices x.1 x.2) := by + let R : PolyProgram (RawTag × RawChoiceData) (RawChoiceData × RawRole) (fun x => (x.2,x.1.1)) := + .expr (.pair TExpr.input.right TExpr.input.left.left) (by intro x; rfl) + let ns := R.comp PolyProgram.rawRoleSize |>.comp PolyProgram.range + let swap : PolyProgram (ℕ × RawTag) RawVertex (fun x => (x.2,x.1)) := + .expr (.pair TExpr.input.right TExpr.input.left) (by intro x; rfl) + let Q := (ns.pair (PolyProgram.fst RawTag RawChoiceData)).comp swap.mapWith + let S : PolyProgram (RawChoiceData × List RawTag) (List RawTag × RawChoiceData) (fun x => (x.2,x.1)) := + .expr (.pair TExpr.input.right TExpr.input.left) (by intro x; rfl) + exact (S.comp Q.mapWith |>.comp (PolyProgram.flatten RawVertex)).congr (by intro x; rfl) + +noncomputable def PolyProgram.rawMatrix : PolyProgram (RawChoiceData × List RawTag) (List Bool) + (fun x => Complexity.rawMatrix x.1 x.2) := by + let E : PolyProgram (RawVertex × (RawVertex × RawChoiceData)) (RawChoiceData × (RawVertex × RawVertex)) + (fun x => (x.2.2,x.2.1,x.1)) := + .expr (.pair TExpr.input.right.right (.pair TExpr.input.right.left TExpr.input.left)) (by intro x; rfl) + let V : PolyProgram (RawVertex × (RawChoiceData × List RawTag)) (List RawVertex) + (fun x => Complexity.rawVertices x.2.1 x.2.2) := + (PolyProgram.snd RawVertex (RawChoiceData × List RawTag)).comp PolyProgram.rawVertices + let C : PolyProgram (RawVertex × (RawChoiceData × List RawTag)) (RawVertex × RawChoiceData) + (fun x => (x.1,x.2.1)) := + .expr (.pair TExpr.input.left TExpr.input.right.left) (by intro x; rfl) + let Q := (V.pair C).comp (E.comp PolyProgram.rawEdgeTest).mapWith + exact ((PolyProgram.rawVertices.pair (PolyProgram.id (RawChoiceData × List RawTag))).comp Q.mapWith + |>.comp (PolyProgram.flatten Bool)).congr (by intro x; rfl) + +noncomputable def PolyProgram.rawOutput : PolyProgram (RawChoiceData × (List RawTag × List RawTag)) (List Bool) + (fun x => Complexity.rawOutput x.1 x.2) := by + let L : PolyProgram (RawChoiceData × (List RawTag × List RawTag)) (RawChoiceData × List RawTag) + (fun x => (x.1,x.2.1)) := + .expr (.pair TExpr.input.left TExpr.input.right.left) (by intro x; rfl) + let R : PolyProgram (RawChoiceData × (List RawTag × List RawTag)) (RawChoiceData × List RawTag) + (fun x => (x.1,x.2.2)) := + .expr (.pair TExpr.input.left TExpr.input.right.right) (by intro x; rfl) + let C := L.comp PolyProgram.rawVertices |>.comp (PolyProgram.length RawVertex) |>.comp PolyProgram.encodeNat + exact ((C.pair (L.comp PolyProgram.rawMatrix) |>.comp (PolyProgram.append Bool)).pair + (R.comp PolyProgram.rawMatrix) |>.comp (PolyProgram.append Bool)).congr (by intro x; rfl) + +end ParityWL.Complexity + +end OAI diff --git a/lean/OAI/Combinatorics/ParityLifts/UniformHeaders.lean b/lean/OAI/Combinatorics/ParityLifts/UniformHeaders.lean new file mode 100644 index 0000000000000000000000000000000000000000..f924a3ee4df2b247fbd03560558c8cb5ec760728 --- /dev/null +++ b/lean/OAI/Combinatorics/ParityLifts/UniformHeaders.lean @@ -0,0 +1,45 @@ +import OAI.Combinatorics.ParityLifts.BoundedSimulation + +namespace OAI + +namespace ParityWL.Complexity + +def trialInput (j k : ℕ) (bs : List Bool) : List Bool := + List.replicate j true++false::(List.replicate k true++false::bs) + +def readUnary (bs : List Bool) : ℕ × List Bool := (truePrefix bs,bs.drop (truePrefix bs+1)) + +def PolyProgram.readUnary : PolyProgram (List Bool) (ℕ × List Bool) readUnary := by + let n := PolyProgram.truePrefix + let rem := (((n.comp PolyProgram.natSucc).pair (PolyProgram.id (List Bool))).comp + (PolyProgram.splitAt Bool)).comp (PolyProgram.snd (List Bool) (List Bool)) + exact n.pair rem + +lemma readUnary_encode (n : ℕ) (bs : List Bool) : + readUnary (List.replicate n true++false::bs)=(n,bs) := by + have h : truePrefix (List.replicate n true++false::bs)=n := by + induction n with + | zero => simp [truePrefix] + | succ n ih => simp [List.replicate_succ,truePrefix,ih] + simp [readUnary,h,List.drop_append] + +noncomputable def trialNormalize (bs : List Bool) : (ℕ × ℕ) × BitFormula := + let x := readUnary bs + let y := readUnary x.2 + ((x.1,y.1),minimizeList (parseFormula y.2)) + +noncomputable def trialNormalizeProgram : PolyProgram (List Bool) ((ℕ × ℕ) × BitFormula) trialNormalize := by + let j := PolyProgram.fst ℕ (List Bool) + let second := (PolyProgram.snd ℕ (List Bool)).comp PolyProgram.readUnary + let k := second.comp (PolyProgram.fst ℕ (List Bool)) + let F := (second.comp (PolyProgram.snd ℕ (List Bool))).comp normalizeProgram + exact PolyProgram.readUnary.comp ((j.pair k).pair F) + +lemma trialNormalize_encode {N : ℕ} (j k : ℕ) (F : Formula N) : + trialNormalize (trialInput j k (encodeFormula F))=((j,k),minimizeList F.bitList) := by + simp only [trialNormalize,trialInput,readUnary_encode,←Formula.bitList_parse] + + +end ParityWL.Complexity + +end OAI diff --git a/lean/OAI/Combinatorics/ParityLifts/UniformLeaf.lean b/lean/OAI/Combinatorics/ParityLifts/UniformLeaf.lean new file mode 100644 index 0000000000000000000000000000000000000000..0eeda451ff13b5db285610d3ce2ec6dc699be8ca --- /dev/null +++ b/lean/OAI/Combinatorics/ParityLifts/UniformLeaf.lean @@ -0,0 +1,111 @@ +import OAI.Combinatorics.ParityLifts.ParamTags + +namespace OAI + +namespace ParityWL.Complexity + +abbrev TagPair := List RawTag × List RawTag +abbrev RawLeafPreparation := (List BitFormula × TagPair) × ℕ +abbrev RawLeafTable := (List BitFormula × TagPair) × ℕ × List (List Bool) + +noncomputable def ParamPolyProgram.tags (α : Type) [TreeCodec α] : + ParamPolyProgram ℕ α TagPair (fun t _ => (rawTags t false,rawTags t true)) where + program := (TreeProgram.fst ℕ α).comp TreeProgram.tagPair + coefficient := fun t => TreeProgram.tagPair.time t+2 + degree := fun _ => 1 + bound := by + intro t x + change (treeEncode (t,x)).size+TreeProgram.tagPair.time t+1≤_ + simp only [pow_one] + nlinarith + +noncomputable def ParamPolyProgram.rawPreparation : + ParamPolyProgram ℕ BitFormula RawLeafPreparation + (fun t F => ((rawGroups t F,(rawTags t false,rawTags t true)),leafWords t F)) := by + let G := ParamPolyProgram.ofPoly PolyProgram.rawGroups + let W := ParamPolyProgram.ofPoly (f := fun t F => Complexity.leafWords t F) (((PolyProgram.const 3).pair PolyProgram.runtimeChunkWidth).comp PolyProgram.natMul) + exact (G.pair (ParamPolyProgram.tags BitFormula)).pair W + +def TreeProgram.addWords (α : Type) [TreeCodec α] : + TreeProgram (α × ℕ) (α × ℕ × List (List Bool)) (fun x => (x.1,x.2,Complexity.words x.2)) := + (TreeProgram.fst α ℕ).pair ((TreeProgram.snd α ℕ).pair ((TreeProgram.snd α ℕ).comp TreeProgram.words)) + +noncomputable def PolyProgram.rawWordsOutput : PolyProgram RawLeafTable (List Bool) + (fun x => Complexity.rawOutput (Complexity.rawChoiceWithWords (x.1.1,x.2)) x.1.2) := by + let I : PolyProgram RawLeafTable RawTableInput (fun x => (x.1.1,x.2)) := + .expr (.pair TExpr.input.left.left TExpr.input.right) (by intro x; rfl) + let T : PolyProgram RawLeafTable TagPair (fun x => x.1.2) := + .expr TExpr.input.left.right (by intro x; rfl) + exact ((I.comp PolyProgram.rawChoiceWithWords).pair T).comp PolyProgram.rawOutput + +def uniformLeafOutput (t : ℕ) (F : BitFormula) : List Bool := + rawOutput (rawLeafData t F) (rawTags t false,rawTags t true) + +noncomputable def TreeProgram.uniformLeafOutput : TreeProgram (ℕ × BitFormula) (List Bool) + (fun x => Complexity.uniformLeafOutput x.1 x.2) := + ((ParamPolyProgram.rawPreparation.program.comp (TreeProgram.addWords (List BitFormula × TagPair))).comp + PolyProgram.rawWordsOutput.program).congr (by intro x; rfl) + +lemma addWords_time {α : Type} [TreeCodec α] (x : α × ℕ) : + (TreeProgram.addWords α).time x=TreeProgram.words.time x.2+3*(treeEncode x).size+3 := by + simp only [TreeProgram.addWords,TreeProgram.pair,TreeProgram.comp,TreeProgram.fst,TreeProgram.snd] + omega + +lemma addWords_size {α : Type} [TreeCodec α] (x : α × ℕ) : + (treeEncode (x.1,x.2,words x.2)).size+1 ≤ 10*((treeEncode x).size+1)*2^x.2 := by + obtain ⟨a,q⟩ := x + have hw := words_size q + have hp : 1≤2^q := Nat.one_le_two_pow + simp only [treeEncode_pair,treeEncode_nat,numTree_size,DataTree.size] at * + nlinarith [DataTree.size_pos (treeEncode a)] + +theorem uniformLeafOutput_bound : ∃ E : ℕ, 0 simp only [t,bagParameter] <;> omega + obtain ⟨n,G,H,he,hg,hn⟩ := rawOutput_spec k hk c (leafData t F) + refine ⟨n,G,H,?_,fun i => (hg i).trans (not_congr (leafData_success t ht F hw)),?_⟩ + · simpa only [uniformLeafOutput,rawLeafData_eq] using he + · have hc := Fintype.card_congr (rawIndexEquiv (leafData t F) false) + simp only [Fintype.card_fin,tagCharge_false] at hc + rw [hn,hc] + exact choice_lift_order_bound (by cases c <;> simp only [t,bagParameter] <;> omega) + (leafData t F).system (2^leafWords t F+1) (leafData_size t F) (fun _ => 0) + +end ParityWL.Complexity + +end OAI diff --git a/lean/OAI/Combinatorics/ParityLifts/UniformMachine.lean b/lean/OAI/Combinatorics/ParityLifts/UniformMachine.lean new file mode 100644 index 0000000000000000000000000000000000000000..6bce0124a736af194169785197a50ffe53cf0c05 --- /dev/null +++ b/lean/OAI/Combinatorics/ParityLifts/UniformMachine.lean @@ -0,0 +1,64 @@ +import OAI.Combinatorics.ParityLifts.UniformLeaf + +namespace OAI + +namespace ParityWL.Complexity + +def PolyProgram.bagParameter (c : Convention) : PolyProgram ℕ ℕ (ParityWL.bagParameter c) := by + cases c with + | joint => exact (((PolyProgram.id ℕ).pair (PolyProgram.const 1)).comp PolyProgram.natAdd) + | separate => exact PolyProgram.id ℕ + +noncomputable def TreeProgram.uniformLeafPair (c : Convention) : + TreeProgram (ℕ × BitFormula) (ℕ × List Bool) + (fun x => (x.1,Complexity.uniformLeafOutput (bagParameter c x.1) x.2)) := + (TreeProgram.fst ℕ BitFormula).pair + ((((PolyProgram.fst ℕ BitFormula).comp (PolyProgram.bagParameter c)).pair + (PolyProgram.snd ℕ BitFormula)).program.comp TreeProgram.uniformLeafOutput) + +noncomputable def PolyProgram.withDimension : PolyProgram (ℕ × List Bool) (List Bool) + (fun x => Complexity.encodeNat x.1++x.2) := + ((((PolyProgram.fst ℕ (List Bool)).comp PolyProgram.encodeNat).pair + (PolyProgram.snd ℕ (List Bool))).comp (PolyProgram.append Bool)) + +noncomputable def TreeProgram.uniformWLInput (c : Convention) : + TreeProgram (ℕ × BitFormula) (List Bool) + (fun x => Complexity.encodeNat x.1++Complexity.uniformLeafOutput (bagParameter c x.1) x.2) := + (TreeProgram.uniformLeafPair c).comp PolyProgram.withDimension.program + +noncomputable def uniformLeafDecisionCode (c : Convention) (M : Machine) : FCode := + .seq (TreeProgram.uniformWLInput c).code (.seq (simulationCode M) PolyProgram.not.program.code) + +noncomputable def uniformLeafTime (c : Convention) (k : ℕ) (F : BitFormula) : ℕ := + (TreeProgram.uniformWLInput c).time (k,F) + +noncomputable def uniformLeafCost (c : Convention) (k : ℕ) (M : Machine) (C r : ℝ) (F : BitFormula) : ℝ := + uniformLeafTime c k F+simulationCoefficient M*(uniformLeafTime c k F+C*2^(r*leafWords (bagParameter c k) F)+1)^simulationDegree+negateCost+2 + +lemma uniformLeafMachine_run (k : ℕ) (hk : 4≤k) (c : Convention) + (i : Implementation) (M : Machine) (f g : ℕ → ℝ) + (hm : UniformWLBound M c i f g) : + ∃ C : ℝ, 0 simp_all + +end ParityWL.Complexity + +end OAI diff --git a/lean/OAI/Combinatorics/ParityLifts/UniformNormalization.lean b/lean/OAI/Combinatorics/ParityLifts/UniformNormalization.lean new file mode 100644 index 0000000000000000000000000000000000000000..10ed6ba3b1b2057974ad9451655385a5e4086a51 --- /dev/null +++ b/lean/OAI/Combinatorics/ParityLifts/UniformNormalization.lean @@ -0,0 +1,36 @@ +import OAI.Combinatorics.ParityLifts.UniformETH + +namespace OAI + +namespace ParityWL.Complexity + +/-- Nonnegative exponents and positive multipliers in `UniformWLBound` are a +normalization, not an added restriction on uniform exclusion. -/ +theorem uniform_eth_unrestricted_exponents (hETH : UniformSubexponentialETH) + (c : Convention) (i : Implementation) : + ¬ ∃ (M : Machine) (f g : ℕ → ℝ), + Filter.Tendsto (fun k : ℕ => g k/k) Filter.atTop (nhds 0) ∧ + ∀ k : ℕ, 4 ≤ k → ∀ (n : ℕ) (G H : SimpleGraph (Fin n)), ∃ s b, + Emits M (encodeNat k++encodeGraphs G H) s b ∧ + (b=true↔Equivalent G H c i k) ∧ (s : ℝ) ≤ f k*(n+1 : ℝ)^g k := by + intro h + obtain ⟨M,f,g,hlim,hm⟩ := h + have hlim' : Filter.Tendsto (fun k : ℕ => |g k|/k) Filter.atTop (nhds 0) := by + have hnat : ∀ k : ℕ, |(k : ℝ)|=k := fun k => abs_of_nonneg (Nat.cast_nonneg k) + simpa only [abs_div,hnat,abs_zero] using hlim.abs + apply uniform_eth hETH c i + refine ⟨M,(fun k => |f k|+1),(fun k => |g k|),hlim',?_⟩ + refine ⟨by intro k; positivity,fun k => abs_nonneg (g k),?_⟩ + intro k hk n G H + obtain ⟨s,b,hs,hb,ht⟩ := hm k hk n G H + refine ⟨s,b,hs,hb,ht.trans ?_⟩ + have hn : (1 : ℝ) ≤ n+1 := by have := Nat.cast_nonneg (α:=ℝ) n; linarith + calc + f k*(n+1 : ℝ)^g k ≤ (|f k|+1)*(n+1 : ℝ)^g k := + mul_le_mul_of_nonneg_right (by linarith [le_abs_self (f k)]) (Real.rpow_nonneg (by positivity) _) + _ ≤ (|f k|+1)*(n+1 : ℝ)^|g k| := + mul_le_mul_of_nonneg_left (Real.rpow_le_rpow_of_exponent_le hn (le_abs_self _)) (by positivity) + +end ParityWL.Complexity + +end OAI diff --git a/lean/OAI/Combinatorics/ParityLifts/UniformOutput.lean b/lean/OAI/Combinatorics/ParityLifts/UniformOutput.lean new file mode 100644 index 0000000000000000000000000000000000000000..cde148a97eea01714cff030d86f9752db3e56b4d --- /dev/null +++ b/lean/OAI/Combinatorics/ParityLifts/UniformOutput.lean @@ -0,0 +1,90 @@ +import OAI.Combinatorics.ParityLifts.UniformVertices + +namespace OAI + +namespace ParityWL.Complexity +open Classical + +lemma rawIndexed_adj {t : ℕ} (D : ChoiceData t) (odd : Bool) + (i j : Fin (rawVertices D.raw (rawTags t odd)).length) : + (rawIndexedGraph D odd).Adj i j ↔ rawEdgeTest D.raw + ((rawVertices D.raw (rawTags t odd)).get i) ((rawVertices D.raw (rawTags t odd)).get j)=true := by + let E := List.Nodup.getEquiv _ (rawVertices_nodup D.raw _ (rawTags_nodup t odd)) + let a := (rawVertexEquiv D odd).symm (E i) + let b := (rawVertexEquiv D odd).symm (E j) + have ha : rawVertexEncode D odd a=(rawVertices D.raw (rawTags t odd)).get i := + congrArg Subtype.val ((rawVertexEquiv D odd).apply_symm_apply (E i)) + have hb : rawVertexEncode D odd b=(rawVertices D.raw (rawTags t odd)).get j := + congrArg Subtype.val ((rawVertexEquiv D odd).apply_symm_apply (E j)) + have hh := rawEdgeTest_encode D odd a b + rw [ha,hb] at hh + exact hh.symm + +def rawMatrix (D : RawChoiceData) (ts : List RawTag) : List Bool := + (rawVertices D ts).flatMap (fun x => (rawVertices D ts).map (rawEdgeTest D x)) + +def rawOutput (D : RawChoiceData) (ts : List RawTag × List RawTag) : List Bool := + encodeNat (rawVertices D ts.1).length ++ rawMatrix D ts.1 ++ rawMatrix D ts.2 + +lemma rawMatrix_eq {t : ℕ} (D : ChoiceData t) (odd : Bool) : + rawMatrix D.raw (rawTags t odd) = + (List.ofFn (fun i : Fin (rawVertices D.raw (rawTags t odd)).length => + List.ofFn (fun j : Fin (rawVertices D.raw (rawTags t odd)).length => + decide ((rawIndexedGraph D odd).Adj i j)))).flatten := by + have he (i j : Fin (rawVertices D.raw (rawTags t odd)).length) : + decide ((rawIndexedGraph D odd).Adj i j) = + rawEdgeTest D.raw ((rawVertices D.raw (rawTags t odd)).get i) + ((rawVertices D.raw (rawTags t odd)).get j) := by + apply Bool.eq_iff_iff.mpr + simpa only [decide_eq_true_eq] using rawIndexed_adj D odd i j + simp only [he,List.get_eq_getElem,List.ofFn_getElem_eq_map] + simp only [rawMatrix,List.flatMap_def] + congr 1 + exact (List.ofFn_getElem_eq_map _ _).symm + +lemma rawVertices_length_eq {t : ℕ} (D : ChoiceData t) (ht : 2≤t) : + (rawVertices D.raw (rawTags t false)).length = (rawVertices D.raw (rawTags t true)).length := by + have h0 := Fintype.card_congr (rawIndexEquiv D false) + have h1 := Fintype.card_congr (rawIndexEquiv D true) + simp only [Fintype.card_fin,tagCharge_false,tagCharge_true] at h0 h1 + exact h0.trans ((choice_lifts_equal_order ht D.system).trans h1.symm) + +noncomputable def liftChargeIso {t : ℕ} (D : ChoiceData t) (b b' : TemplateVertex t → Bit) (h : b=b') : + liftGraph (template t) (baseGraph D.system) (baseProjection D.system) b ≃g + liftGraph (template t) (baseGraph D.system) (baseProjection D.system) b' := by + subst b' + exact RelIso.refl _ + +theorem rawOutput_spec (k : ℕ) (hk : 4≤k) (c : Convention) + (D : ChoiceData (bagParameter c k)) : + ∃ (n : ℕ) (G H : SimpleGraph (Fin n)), + rawOutput D.raw (rawTags (bagParameter c k) false,rawTags (bagParameter c k) true)=encodeGraphs G H ∧ + (∀ i : Implementation, Equivalent G H c i k ↔ ¬D.system.Successful) ∧ + n = (rawVertices D.raw (rawTags (bagParameter c k) false)).length := by + let t := bagParameter c k + have ht : 2≤t := by cases c <;> simp only [t,bagParameter] <;> omega + let n := (rawVertices D.raw (rawTags t false)).length + let m := (rawVertices D.raw (rawTags t true)).length + have he : n=m := rawVertices_length_eq D ht + let G := rawIndexedGraph D false + let H := (rawIndexedGraph D true).comap (Fin.cast he) + have Gi : G ≃g zeroLift D.system := (rawIndexedIso D false).trans + (liftChargeIso D _ _ (tagCharge_false t)) + have Hi : H ≃g starLift D.system := + ((SimpleGraph.Iso.comap (finCongr he) (rawIndexedGraph D true)).trans (rawIndexedIso D true)).trans + (liftChargeIso D _ _ (tagCharge_true t)) + refine ⟨n,G,H,?_,?_,rfl⟩ + · unfold rawOutput encodeGraphs + rw [rawMatrix_eq,rawMatrix_eq] + apply congrArg (fun z => encodeNat n ++ (List.ofFn (fun i : Fin n => + List.ofFn (fun j : Fin n => decide (G.Adj i j)))).flatten ++ z) + exact (matrix_cast he (rawIndexedGraph D true)).symm + · intro i + have hp := parity_reduction k hk c D.system + cases i with + | commonColors => exact (iso_WLEquivalent G _ H _ Gi Hi c k).trans hp.2.2.1 + | pureUnion => exact (iso_PureWLEquivalent G _ H _ Gi Hi c k).trans hp.2.2.2.1 + +end ParityWL.Complexity + +end OAI diff --git a/lean/OAI/Combinatorics/ParityLifts/UniformPost.lean b/lean/OAI/Combinatorics/ParityLifts/UniformPost.lean new file mode 100644 index 0000000000000000000000000000000000000000..1ca976c01830782d0428cc2f8440d2ea04baf916 --- /dev/null +++ b/lean/OAI/Combinatorics/ParityLifts/UniformPost.lean @@ -0,0 +1,173 @@ +import OAI.Combinatorics.ParityLifts.UniformRate + +namespace OAI + +namespace ParityWL.Complexity + +lemma RBEval.pair {p q : FCode} {x y z : DataTree} {R S : ℝ} + (h : RBEval p x R y) (hg : RBEval q x S z) : RBEval (.pair p q) x (R+S+1) (.node y z) := by + obtain ⟨B,hB,h⟩ := h + obtain ⟨C,hC,hg⟩ := hg + exact ⟨B+C+1,hB.pair hC,by push_cast; linarith⟩ + +lemma RBEval.size_le {p : FCode} {x y : DataTree} {R : ℝ} (h : RBEval p x R y) : + (y.size : ℝ) ≤ R := by + obtain ⟨B,hB,h⟩ := h + exact (by exact_mod_cast hB.bounds.2.1 : (y.size : ℝ) ≤ B).trans h + +lemma RBEval.post {α β : Type} [TreeCodec α] [TreeCodec β] {f : α → β} + {p : FCode} {x : DataTree} {a : α} {R : ℝ} (h : RBEval p x R (treeEncode a)) + (P : PolyProgram α β f) : + RBEval (.seq p P.program.code) x (R+P.coefficient*(R+1)^P.degree+1) (treeEncode (f a)) := by + have hp : (P.program.time a : ℝ) ≤ P.coefficient*(R+1)^P.degree := by + have hb : (P.program.time a : ℝ) ≤ P.coefficient*((treeEncode a).size+1 : ℝ)^P.degree := by + exact_mod_cast P.bound a + apply hb.trans + gcongr + exact h.size_le + exact (h.seq (P.program.run a).real).mono (by linarith) + +noncomputable def PolyProgram.uniformPostStart : + PolyProgram ((ℕ × ℕ) × BitFormula) (ℕ × (ℕ × BitFormula)) + (fun x => (x.1.2,(12*x.1.1,x.2))) := by + let j := (PolyProgram.fst (ℕ × ℕ) BitFormula).comp (PolyProgram.fst ℕ ℕ) + let k := (PolyProgram.fst (ℕ × ℕ) BitFormula).comp (PolyProgram.snd ℕ ℕ) + let r := ((PolyProgram.const 12).pair j).comp PolyProgram.natMul + exact k.pair (r.pair (PolyProgram.snd (ℕ × ℕ) BitFormula)) + +noncomputable def PolyProgram.pairLeaves : PolyProgram (ℕ × List BitFormula) (List (ℕ × BitFormula)) + (fun x => x.2.map (fun F => (x.1,F))) := by + let P : PolyProgram (BitFormula × ℕ) (ℕ × BitFormula) (fun x => (x.2,x.1)) := + .expr (.pair TExpr.input.right TExpr.input.left) (by intro x; rfl) + exact ((PolyProgram.snd ℕ (List BitFormula)).pair (PolyProgram.fst ℕ (List BitFormula))).comp P.mapWith + +noncomputable def uniformPostCode (p : FCode) : FCode := + .seq PolyProgram.uniformPostStart.program.code + (.seq (.seq (.pair .left (.seq .right (runtimeSparseCode BitLiteral))) + PolyProgram.pairLeaves.program.code) p.any) + +noncomputable def runtimeStepBudget (j N : ℕ) : ℕ := + (ParamPolyProgram.sparseStep BitLiteral).coefficient (12*j)* + (literalSizeBound N+(treeEncode (12*j)).size+2)^ + ((ParamPolyProgram.sparseStep BitLiteral).degree (12*j)) + +lemma runtimeStepBudget_bound (j N : ℕ) (F : BitFormula) + (hs : (treeEncode F).size ≤ literalSizeBound N) : + (ParamPolyProgram.sparseStep BitLiteral).program.time (12*j,F) ≤ runtimeStepBudget j N := by + apply (ParamPolyProgram.sparseStep BitLiteral).bound (12*j) F |>.trans + apply Nat.mul_le_mul_left + apply Nat.pow_le_pow_left + simp only [treeEncode_pair,DataTree.size] + omega + +lemma runtimeStepBudget_rate (j : ℕ) : ExpBound (fun N => (runtimeStepBudget j N : ℝ)) 0 := by + let P := ParamPolyProgram.sparseStep BitLiteral + have h := ((sparseSize_add_rate ((treeEncode (12*j)).size+2)).polypow (P.degree (12*j))).scale + (P.coefficient (12*j)) (Nat.cast_nonneg _) + simpa only [runtimeStepBudget,Nat.add_assoc,Nat.cast_mul,Nat.cast_pow] using h + +lemma uniformPostCode_rate : ∃ D : ℕ, 0 literalSizeBound N+(treeEncode ((j,k) : ℕ × ℕ)).size+1 + have hS : ExpBound (fun N => (S N : ℝ)) 0 := by + simpa only [S,Nat.add_assoc] using sparseSize_add_rate ((treeEncode ((j,k) : ℕ × ℕ)).size+1) + let I := PolyProgram.uniformPostStart + let A : ℕ → ℝ := fun N => I.coefficient*(S N+1 : ℝ)^I.degree + have hA : ExpBound A 0 := by + simpa only [A,Nat.cast_mul,Nat.cast_pow,Nat.cast_add,Nat.cast_one] using polynomial_program_rate I S hS + let Q := leafNumber j + have hQ : ExpBound Q (1/(j : ℝ)) := ExpBound.exp _ + have hq : 0 ≤ 1/(j : ℝ) := by positivity + let U : ℕ → ℝ := fun N => 4000*(2*Q N)^2*(literalSizeBound N+runtimeStepBudget j N+(treeEncode (12*j)).size+6 : ℕ) + have hU : ExpBound U (2/(j : ℝ)) := by + have hh := (((hQ.scale 2 (by norm_num)).pow 2).mul + (((sparseSize_rate.add_same (runtimeStepBudget_rate j)).add_const (by norm_num) + ((treeEncode (12*j)).size+6) (by positivity)))).scale 4000 (by norm_num) + convert hh using 1 + · funext N; dsimp only [U,Q]; push_cast; ring + · ring + let V : ℕ → ℝ := fun N => 2*A N+U N+2 + have hV : ExpBound V (2/(j : ℝ)) := by + have hh := ((hA.scale 2 (by norm_num)).add hU (by norm_num) (by positivity)).add_const (by positivity) 2 (by norm_num) + simpa only [zero_add] using hh + let K : ℕ → ℝ := fun N => V N+PolyProgram.pairLeaves.coefficient*(V N+1)^d+1 + have hK := hV.post (by positivity : 0 ≤ 2/(j : ℝ)) PolyProgram.pairLeaves.coefficient d + let B : ℕ → ℝ := fun N => 500*(Q N+1)^2*(literalSizeBound N+(treeEncode k).size+1+W N+6) + have hB : ExpBound B (2/(j : ℝ)+r) := by + have hs := ((sparseSize_add_rate ((treeEncode k).size+1)).mono_rate hr).add_same hW |>.add_const hr 6 (by norm_num) + have hh := (((hQ.add_const hq 1 (by norm_num)).pow 2).mul hs).scale 500 (by norm_num) + convert hh using 1 + · funext N; dsimp only [B,Q]; push_cast; ring + · ring + let R : ℕ → ℝ := fun N => A N+(K N+B N+1)+1 + refine ⟨R,?_,?_⟩ + · have hh := (hA.add ((hK.add hB (by positivity) (by positivity)).add_const (by positivity) 1 (by norm_num)) + (by norm_num) (by positivity)).add_const (by positivity) 1 (by norm_num) + convert hh using 1 + push_cast + ring + · intro N F + obtain ⟨T,hroot,hvalid,hsize,hnum,hden,he⟩ := bit_sparse_certificate F j hj + have hn : (T.leaves.length : ℝ) ≤ Q N := by simpa only [Q,leafNumber,one_div,inv_mul_eq_div] using hnum + have hsz : (treeEncode ((j,k),T.root)).size ≤ S N := by + simp only [treeEncode_pair,DataTree.size,S] + have hh := hsize.root + omega + have ha : RBEval I.program.code (treeEncode ((j,k),T.root)) (A N) (treeEncode (k,(12*j,T.root))) := by + apply (I.program.run ((j,k),T.root)).real.mono + dsimp only [A] + exact_mod_cast (I.bound ((j,k),T.root)).trans (Nat.mul_le_mul_left _ (Nat.pow_le_pow_left (Nat.add_le_add_right hsz 1) _)) + have hu : RBEval (runtimeSparseCode BitLiteral) (treeEncode (12*j,T.root)) (U N) (treeEncode T.leaves.reverse) := by + apply (runtimeSparseCode_run (12*j) (literalSizeBound N) (runtimeStepBudget j N) + (runtimeStepBudget_bound j N) T hvalid hsize).real.mono + rw [SparseTree.nodes_eq] + dsimp only [U] + push_cast + gcongr + have hz : ((treeEncode (k,(12*j,T.root))).size : ℝ) ≤ A N := ha.size_le + have hl := (BEval.left (treeEncode (k,(12*j,T.root)))).real.mono hz + have hh := (BEval.right (treeEncode (k,(12*j,T.root)))).real.mono hz + have hv : RBEval (.pair .left (.seq .right (runtimeSparseCode BitLiteral))) + (treeEncode (k,(12*j,T.root))) (V N) (treeEncode (k,T.leaves.reverse)) := by + apply (hl.pair (hh.seq hu)).mono + dsimp only [V]; linarith + have hk := hv.post PolyProgram.pairLeaves + obtain ⟨b,hb,hb'⟩ := RBEval.any p (fun x : ℕ × BitFormula => ∃ a,bitSat a x.2) + (literalSizeBound N+(treeEncode k).size+1) (W N) (hW.1 N) + (T.leaves.reverse.map (fun F => (k,F))) + (by + intro x hx + obtain ⟨G,hG,rfl⟩ := List.mem_map.mp hx + have hg := hsize.leaf G (List.mem_reverse.mp hG) + simp only [treeEncode_pair,DataTree.size]; omega) + (by + intro x hx + obtain ⟨G,hG,rfl⟩ := List.mem_map.mp hx + have hg := List.mem_reverse.mp hG + exact hp N G (hsize.leaf G hg) (hden G hg).1 (hden G hg).2) + have hb'' : RBEval p.any (treeEncode (T.leaves.reverse.map (fun F => (k,F)))) (B N) (treeEncode b) := by + apply hb.mono + simp only [List.length_map,List.length_reverse] + dsimp only [B] + push_cast + have hw := hW.1 N + gcongr + refine ⟨b,?_,?_⟩ + · rw [hroot] at ha hk + exact ha.seq (hk.seq hb'') + · exact hb'.trans ((by simp only [List.mem_map,List.mem_reverse]; aesop : + (∃ x∈T.leaves.reverse.map (fun F => (k,F)),∃ a,bitSat a x.2)↔∃ G∈T.leaves,∃ a,bitSat a G).trans he) + +end ParityWL.Complexity + +end OAI diff --git a/lean/OAI/Combinatorics/ParityLifts/UniformRate.lean b/lean/OAI/Combinatorics/ParityLifts/UniformRate.lean new file mode 100644 index 0000000000000000000000000000000000000000..b18407caf445f9a579372cc0138f701ec6866e10 --- /dev/null +++ b/lean/OAI/Combinatorics/ParityLifts/UniformRate.lean @@ -0,0 +1,147 @@ +import OAI.Combinatorics.ParityLifts.UniformMachine + +namespace OAI + +namespace ParityWL.Complexity + +lemma TreeProgram.post_time_le {α β γ : Type} [TreeCodec α] [TreeCodec β] [TreeCodec γ] + {f : α → β} {g : β → γ} (P : TreeProgram α β f) (Q : PolyProgram β γ g) + (x : α) (T : ℝ) (hT : (P.time x : ℝ) ≤ T) : + ((P.comp Q.program).time x : ℝ) ≤ T+Q.coefficient*(T+1)^Q.degree+1 := by + have hs : ((treeEncode (f x)).size : ℝ) ≤ T := + (by exact_mod_cast (P.run x).bounds.2.1 : ((treeEncode (f x)).size : ℝ) ≤ P.time x).trans hT + have hq : (Q.program.time (f x) : ℝ) ≤ Q.coefficient*((treeEncode (f x)).size+1 : ℝ)^Q.degree := by + exact_mod_cast Q.bound (f x) + have hq' : (Q.program.time (f x) : ℝ) ≤ Q.coefficient*(T+1)^Q.degree := by + apply hq.trans + gcongr + change ((P.time x+Q.program.time (f x)+1 : ℕ) : ℝ) ≤ _ + push_cast + linarith + +lemma ExpBound.post {T : ℕ → ℝ} {r : ℝ} (hT : ExpBound T r) (hr : 0 ≤ r) (A d : ℕ) : + ExpBound (fun N => T N+A*(T N+1)^d+1) ((d+1 : ℕ)*r) := by + have hp := ((hT.add_const hr 1 (by norm_num)).pow d).scale A (Nat.cast_nonneg _) + have h := (hT.add hp hr (by positivity)).add_const (by positivity) 1 (by norm_num) + convert h using 1 + push_cast + ring + +lemma sparseSize_add_rate (a : ℕ) : ExpBound (fun N => (literalSizeBound N+a : ℕ)) 0 := by + simpa only [Nat.cast_add] using sparseSize_rate.add_const (by norm_num) a (Nat.cast_nonneg _) + +lemma uniformRawTime_rate : ∃ E : ℕ, 0 literalSizeBound N+(treeEncode t).size+1 + have hS : ExpBound (fun N => (S N : ℝ)) 0 := by + simpa only [S,Nat.add_assoc] using sparseSize_add_rate ((treeEncode t).size+1) + let T : ℕ → ℝ := fun N => C*(S N+1 : ℝ)^d*2^((E : ℝ)*(leafSlope t R*N+6)) + refine ⟨T,?_,?_⟩ + · have hp := ((hS.add_const (by norm_num) 1 (by norm_num)).polypow d).scale C (Nat.cast_nonneg _) + simpa only [zero_add] using hp.mul (ExpBound.affine_exp_mul E (leafSlope t R) 6) + · intro N F hs hn + have hb : (TreeProgram.uniformLeafOutput.time (t,F) : ℝ) ≤ + C*((treeEncode (t,F)).size+1 : ℝ)^d*2^((E : ℝ)*leafWords t F) := by + rw [←nat_two_exp_cast] + exact_mod_cast hB F + have hsz : (treeEncode (t,F)).size ≤ S N := by + simp only [treeEncode_pair,DataTree.size,S] + omega + have hq := sparse_leafWords_bound t R N ht F hn + apply hb.trans + dsimp only [T] + gcongr + · norm_num + · exact hq + +lemma uniformLeafTime_rate : ∃ E : ℕ, 0 simp only [t,bagParameter] <;> omega + obtain ⟨U,hU,hUF⟩ := hRaw t R ht + let I := (((PolyProgram.fst ℕ BitFormula).comp (PolyProgram.bagParameter c)).pair + (PolyProgram.snd ℕ BitFormula)) + let S : ℕ → ℕ := fun N => literalSizeBound N+(treeEncode k).size+1 + have hS : ExpBound (fun N => (S N : ℝ)) 0 := by + simpa only [S,Nat.add_assoc] using sparseSize_add_rate ((treeEncode k).size+1) + let V : ℕ → ℝ := fun N => S N+I.coefficient*(S N+1 : ℝ)^I.degree+U N+2 + have hr : 0 ≤ (E : ℝ)*leafSlope t R := mul_nonneg (Nat.cast_nonneg _) (leafSlope_nonneg _ _) + have hi := polynomial_program_rate I S hS + have hV : ExpBound V ((E : ℝ)*leafSlope t R) := by + have hm := ((hS.add_same hi).mono_rate hr).add_same hU |>.add_const hr 2 (by norm_num) + simpa only [Nat.cast_mul,Nat.cast_pow,Nat.cast_add,Nat.cast_one] using hm + have hVF (N : ℕ) (F : BitFormula) (hs : (treeEncode F).size ≤ literalSizeBound N) + (hn : F.length ≤ sparseDensity R N) : ((TreeProgram.uniformLeafPair c).time (k,F) : ℝ) ≤ V N := by + have hsz : (treeEncode (k,F)).size ≤ S N := by simp only [treeEncode_pair,DataTree.size,S]; omega + have hsz' : ((treeEncode (k,F)).size : ℝ) ≤ S N := by exact_mod_cast hsz + have hb := (I.bound (k,F)).trans (Nat.mul_le_mul_left _ (Nat.pow_le_pow_left (Nat.add_le_add_right hsz 1) _)) + have hb' : (I.program.time (k,F) : ℝ) ≤ I.coefficient*(S N+1 : ℝ)^I.degree := by exact_mod_cast hb + have hu := hUF N F hs hn + change (( (treeEncode (k,F)).size+(I.program.time (k,F)+TreeProgram.uniformLeafOutput.time (t,F)+1)+1 : ℕ) : ℝ) ≤ _ + dsimp only [V] + push_cast + linarith + refine ⟨fun N => V N+PolyProgram.withDimension.coefficient*(V N+1)^D+1,?_,?_⟩ + · convert hV.post hr PolyProgram.withDimension.coefficient D using 1 + push_cast + ring + · intro N F hs hn + exact TreeProgram.post_time_le (TreeProgram.uniformLeafPair c) PolyProgram.withDimension (k,F) (V N) (hVF N F hs hn) + +lemma uniformLeafCost_rate : ∃ P : ℕ, 0

simp only [t,bagParameter] <;> omega + let s := leafSlope t R + have hs : 0 ≤ s := leafSlope_nonneg _ _ + let U : ℕ → ℝ := fun N => C*2^(r*(s*N+6)) + have hU : ExpBound U (r*s) := (ExpBound.affine_exp_mul r s 6).scale C hC.le + let W : ℕ → ℝ := fun N => T N+simulationCoefficient M*(T N+U N+1)^simulationDegree+negateCost+2 + have ha : 0 ≤ (E : ℝ)*s := by positivity + have hb : 0 ≤ r*s := by positivity + have hinner := (hT.add hU ha hb).add_const (by positivity) 1 (by norm_num) + have hpow := (hinner.pow simulationDegree).scale (simulationCoefficient M) (Nat.cast_nonneg _) + have hW := ((hT.add hpow ha (by positivity)).add_const (by positivity) negateCost (Nat.cast_nonneg _)).add_const (by positivity) 2 (by norm_num) + refine ⟨W,hW.mono_rate ?_,?_⟩ + · change (E : ℝ)*s+(simulationDegree : ℝ)*((E : ℝ)*s+r*s) ≤ (P : ℝ)*(r+1)*s + dsimp only [P] + push_cast + have h₁ := mul_nonneg (mul_nonneg (Nat.cast_nonneg (α:=ℝ) E) hr) hs + have h₂ := mul_nonneg (Nat.cast_nonneg (α:=ℝ) simulationDegree) h₁ + have h₃ := mul_nonneg hr hs + nlinarith + · intro N F hsz hlen + have ht' := hTF N F hsz hlen + have hq := sparse_leafWords_bound t R N ht F hlen + have hu : C*2^(r*leafWords t F) ≤ U N := by + dsimp only [U] + apply mul_le_mul_of_nonneg_left _ hC.le + apply Real.rpow_le_rpow_of_exponent_le (by norm_num) + exact mul_le_mul_of_nonneg_left hq hr + exact cost_mono (uniformLeafTime c k F) (T N) (C*2^(r*leafWords t F)) (U N) + (simulationCoefficient M) negateCost simulationDegree (Nat.cast_nonneg _) + (mul_nonneg hC.le (Real.rpow_nonneg (by norm_num) _)) (Nat.cast_nonneg _) ht' hu + +end ParityWL.Complexity + +end OAI diff --git a/lean/OAI/Combinatorics/ParityLifts/UniformRates.lean b/lean/OAI/Combinatorics/ParityLifts/UniformRates.lean new file mode 100644 index 0000000000000000000000000000000000000000..1091d78438ec9c561e22267671f9df687254dede --- /dev/null +++ b/lean/OAI/Combinatorics/ParityLifts/UniformRates.lean @@ -0,0 +1,60 @@ +import OAI.Combinatorics.ParityLifts.UniformTrial + +namespace OAI + +namespace ParityWL.Complexity + +lemma uniform_rate_parameters (D P : ℕ) (g : ℕ → ℝ) + (hg : ∀ k,0 ≤ g k) + (hlim : Filter.Tendsto (fun k : ℕ => g k/k) Filter.atTop (nhds 0)) + (η : ℝ) (hη : 0<η) : ∃ j : ℕ, 0 (i.val,i.val,i.val) + | .inr h => (h.1.1.1.1.val,h.1.1.1.2.val,h.1.2.val) + +lemma rawRole_valid {t : ℕ} (a : TemplateVertex t) : RoleValid t (rawRole a) := by + cases a with + | inl i => exact ⟨i.isLt,i.isLt,i.isLt,Or.inl ⟨rfl,rfl⟩⟩ + | inr h => + exact ⟨h.1.1.1.1.isLt,h.1.1.1.2.isLt,h.1.2.isLt,Or.inr ⟨h.1.1.2, + (fun e => h.2.1 (Fin.ext e)),fun e => h.2.2 (Fin.ext e)⟩⟩ + +def roleDecode {t : ℕ} (r : {r : RawRole // RoleValid t r}) : TemplateVertex t := + if h : r.val.1=r.val.2.1 then .inl ⟨r.val.1,r.property.1⟩ + else .inr ⟨(⟨(⟨r.val.1,r.property.1⟩,⟨r.val.2.1,r.property.2.1⟩),by + rcases r.property.2.2.2 with hh | hh + · exact False.elim (h hh.1) + · exact hh.1⟩,⟨r.val.2.2,r.property.2.2.1⟩),by + rcases r.property.2.2.2 with hh | hh + · exact False.elim (h hh.1) + · exact ⟨fun e => hh.2.1 (congrArg Fin.val e),fun e => hh.2.2 (congrArg Fin.val e)⟩⟩ + +@[simp] lemma roleDecode_rawRole {t : ℕ} (a : TemplateVertex t) : + roleDecode ⟨rawRole a,rawRole_valid a⟩=a := by + cases a with + | inl i => simp [roleDecode,rawRole] + | inr h => simp [roleDecode,rawRole,ne_of_lt (show h.1.1.1.1.val decide (RoleValid t r)) + +@[simp] lemma mem_allRoles (t : ℕ) (r : RawRole) : r∈allRoles t ↔ RoleValid t r := by + constructor + · intro h + exact of_decide_eq_true (List.mem_filter.mp h).2 + · intro h + apply List.mem_filter.mpr + refine ⟨?_,decide_eq_true h⟩ + exact List.mem_product.mpr ⟨List.mem_range.mpr h.1, + List.mem_product.mpr ⟨List.mem_range.mpr h.2.1,List.mem_range.mpr h.2.2.1⟩⟩ + +lemma allRoles_nodup (t : ℕ) : (allRoles t).Nodup := by + apply List.Nodup.filter + exact List.nodup_range.product (List.nodup_range.product List.nodup_range) + +def rawAdjacent (a b : RawRole) : Bool := + if a.1=a.2.1 then + if b.1=b.2.1 then decide (a.1≠b.1) + else decide (a.1=b.1 ∨ a.1=b.2.1 ∨ a.1=b.2.2) + else if b.1=b.2.1 then decide (b.1=a.1 ∨ b.1=a.2.1 ∨ b.1=a.2.2) + else false + +lemma rawAdjacent_iff {t : ℕ} (a b : TemplateVertex t) : + rawAdjacent (rawRole a) (rawRole b)=true ↔ (template t).Adj a b := by + cases a with + | inl i => + cases b with + | inl j => + dsimp only [rawAdjacent,rawRole,template,templateAdj] + simp only [ite_true,decide_eq_true_eq,ne_eq,Fin.val_inj] + | inr h => + have hn : h.1.1.1.1.val≠h.1.1.1.2.val := ne_of_lt h.1.1.2 + dsimp only [rawAdjacent,rawRole,template,templateAdj,helperIncident] + rw [ite_eq_right hn] + simp only [ite_true,decide_eq_true_eq,Fin.val_inj] + | inr h => + have hn : h.1.1.1.1.val≠h.1.1.1.2.val := ne_of_lt h.1.1.2 + cases b with + | inl i => + dsimp only [rawAdjacent,rawRole,template,templateAdj,helperIncident] + rw [ite_eq_right hn] + simp only [ite_true,decide_eq_true_eq,Fin.val_inj] + | inr g => + have gn : g.1.1.1.1.val≠g.1.1.1.2.val := ne_of_lt g.1.1.2 + dsimp only [rawAdjacent,rawRole,template,templateAdj] + simp only [ite_eq_right hn,ite_eq_right gn,Bool.false_eq_true] + +def rawNeighbors (t : ℕ) (a : RawRole) : List RawRole := + (allRoles t).filter (rawAdjacent a) + +lemma mem_rawNeighbors (t : ℕ) (a b : RawRole) : + b∈rawNeighbors t a ↔ RoleValid t b ∧ rawAdjacent a b=true := by + simp [rawNeighbors] + +lemma rawNeighbors_nodup (t : ℕ) (a : RawRole) : (rawNeighbors t a).Nodup := + (allRoles_nodup t).filter _ + +end ParityWL.Complexity + +end OAI diff --git a/lean/OAI/Combinatorics/ParityLifts/UniformTables.lean b/lean/OAI/Combinatorics/ParityLifts/UniformTables.lean new file mode 100644 index 0000000000000000000000000000000000000000..5abc45d2d05987a4770c8f34b13aff70f8a46314 --- /dev/null +++ b/lean/OAI/Combinatorics/ParityLifts/UniformTables.lean @@ -0,0 +1,74 @@ +import OAI.Combinatorics.ParityLifts.UniformDFS + +namespace OAI + +namespace ParityWL.Complexity + +lemma map_range_ofFn {α : Type} (t : ℕ) (f : ℕ → α) : + (List.range t).map f=List.ofFn (fun i : Fin t => f i.val) := by + apply List.ext_getElem + · simp + · intro i hi hj + simp + +abbrev RawTableInput := List BitFormula × ℕ × List (List Bool) + +def rawPairKey (Q : List BitFormula) (d i j : ℕ) (bs : List Bool) : List Bool := + let lo := names (Q[min i j]?.getD []) + let hi := names (Q[max i j]?.getD []) + lo.map (fun v => if v∈hi then lookupBits (names (Q[i]?.getD [])) bs v else false) ++ + List.replicate (d-lo.length) false + +lemma rawPairKey_ofFn {t : ℕ} (Q : Fin t → BitFormula) (d : ℕ) (i j : Fin t) (bs : List Bool) : + rawPairKey (List.ofFn Q) d i.val j.val bs=pairKey Q d i j bs := by + have hi : min i.val j.val x.2.2.idxOf (rawPairKey x.1 x.2.1 i j bs)) + +def rawDomain (x : RawTableInput) (i : ℕ) : List (List ℕ) := + (x.2.2.filter (fun bs => (x.1[i]?.getD []).all (fun C => C.any + (fun l => lookupBits (names (x.1[i]?.getD [])) bs l.1 == l.2)))).map (rawRowKey x i) + +def rawChoiceWithWords (x : RawTableInput) : RawChoiceData := + ((List.range x.1.length).map (rawDomain x), + (List.range x.1.length).map (fun _ => (List.range x.1.length).map (fun _ => x.2.2.length))) + +lemma rawChoiceWithWords_ofFn {t : ℕ} (x : TableInput t) : + rawChoiceWithWords (List.ofFn x.1,x.2)=(choiceWithWords x).raw := by + have hrow (i : Fin t) (bs : List Bool) : + rawRowKey (List.ofFn x.1,x.2) i.val bs= + List.ofFn (fun j => x.2.2.idxOf (pairKey x.1 x.2.1 i j bs)) := by + simp only [rawRowKey,List.length_ofFn,map_range_ofFn,rawPairKey_ofFn] + dsimp only [rawChoiceWithWords,ChoiceData.raw,choiceWithWords] + simp only [List.length_ofFn,map_range_ofFn] + congr 1 + apply congrArg List.ofFn + funext i + dsimp only [rawDomain] + simp only [List.getElem?_ofFn,i.isLt,↓reduceDIte,Option.getD_some,Fin.eta,List.map_map] + apply List.map_congr_left + intro bs _ + exact hrow i bs + +def rawGroups (t : ℕ) (F : BitFormula) : List BitFormula := + (List.range t).map (fun i => (F.drop (i*chunkWidth t F)).take (chunkWidth t F)) + +lemma rawGroups_ofFn (t : ℕ) (F : BitFormula) : rawGroups t F=List.ofFn (bitGroup t F) := by + rw [rawGroups,map_range_ofFn] + rfl + +def rawLeafData (t : ℕ) (F : BitFormula) : RawChoiceData := + rawChoiceWithWords (rawGroups t F,leafWords t F,words (leafWords t F)) + +lemma rawLeafData_eq (t : ℕ) (F : BitFormula) : rawLeafData t F=(leafData t F).raw := by + rw [rawLeafData,rawGroups_ofFn] + exact rawChoiceWithWords_ofFn (bitGroup t F,leafWords t F,words (leafWords t F)) + +end ParityWL.Complexity + +end OAI diff --git a/lean/OAI/Combinatorics/ParityLifts/UniformTags.lean b/lean/OAI/Combinatorics/ParityLifts/UniformTags.lean new file mode 100644 index 0000000000000000000000000000000000000000..ac6249da4951d31bb43b06f5b84baa083da738b1 --- /dev/null +++ b/lean/OAI/Combinatorics/ParityLifts/UniformTags.lean @@ -0,0 +1,205 @@ +import OAI.Combinatorics.ParityLifts.UniformRoles + +namespace OAI + +namespace ParityWL.Complexity +open scoped BigOperators +open Classical + +lemma bit_zero_or_one (x : Bit) : x=0 ∨ x=1 := by + have hx := ZMod.val_lt x + have he := ZMod.natCast_zmod_val x + have hv : x.val=0 ∨ x.val=1 := by omega + rcases hv with hv | hv + · left; simpa [hv] using he.symm + · right; simpa [hv] using he.symm + +lemma sum_indicator_list {α β R : Type} [Fintype α] [BEq β] [LawfulBEq β] + [AddCommMonoidWithOne R] (f : α → β) (hf : Function.Injective f) + (s : List β) (hs : s.Nodup) (hc : ∀ x∈s, ∃ a,f a=x) : + ∑ a : α, (if f a∈s then (1 : R) else 0) = (s.length : R) := by + classical + rw [Finset.sum_boole] + congr 1 + let e : α ↪ β := ⟨f,hf⟩ + have he : (Finset.univ.filter (fun a => f a∈s)).map e=s.toFinset := by + ext x + simp only [Finset.mem_map,Finset.mem_filter,Finset.mem_univ,true_and,List.mem_toFinset] + constructor + · rintro ⟨a,ha,rfl⟩; exact ha + · intro hx + obtain ⟨a,ha⟩ := hc x hx + exact ⟨a,ha ▸ hx,ha⟩ + rw [←Finset.card_map e,he,List.toFinset_card_of_nodup hs] + +lemma rawTag_sum {t : ℕ} (a : TemplateVertex t) (s : List RawRole) + (hs : s.Sublist (rawNeighbors t (rawRole a))) : + ∑ v : (template t).neighborSet a, (if rawRole v.val∈s then (1 : Bit) else 0) = (s.length : Bit) := by + classical + apply sum_indicator_list _ (by + intro v w h + exact Subtype.ext ((rawRole_injective t) h)) s (List.Nodup.sublist hs (rawNeighbors_nodup t _)) + intro r hr + have h := (mem_rawNeighbors t _ r).mp (hs.subset hr) + let v := roleDecode ⟨r,h.1⟩ + have hv : rawRole v=r := rawRole_roleDecode ⟨r,h.1⟩ + have ha : (template t).Adj a v := (rawAdjacent_iff a v).mp (by simpa only [hv] using h.2) + exact ⟨⟨v,ha⟩,hv⟩ + +noncomputable def tagOnes {t : ℕ} (a : TemplateVertex t) (z : (template t).neighborSet a → Bit) : List RawRole := by + classical + exact (rawNeighbors t (rawRole a)).filter (fun r => decide (∃ v : (template t).neighborSet a, rawRole v.val=r ∧ z v=1)) + +lemma tagOnes_sublist {t : ℕ} (a : TemplateVertex t) (z : (template t).neighborSet a → Bit) : + (tagOnes a z).Sublist (rawNeighbors t (rawRole a)) := List.filter_sublist + +lemma mem_tagOnes {t : ℕ} (a : TemplateVertex t) (z : (template t).neighborSet a → Bit) + (v : (template t).neighborSet a) : rawRole v.val∈tagOnes a z ↔ z v=1 := by + classical + simp only [tagOnes,List.mem_filter,decide_eq_true_eq] + constructor + · rintro ⟨_,w,hw,hz⟩ + have he : w=v := Subtype.ext ((rawRole_injective t) hw) + simpa only [he] using hz + · intro hz + exact ⟨(mem_rawNeighbors t _ _).mpr ⟨rawRole_valid v.val,(rawAdjacent_iff a v.val).mpr v.property⟩, + v,rfl,hz⟩ + +lemma tagOnes_sum {t : ℕ} (a : TemplateVertex t) (z : (template t).neighborSet a → Bit) : + ((tagOnes a z).length : Bit)=∑ v,z v := by + classical + rw [←rawTag_sum a _ (tagOnes_sublist a z)] + apply Finset.sum_congr rfl + intro v _ + rcases bit_zero_or_one (z v) with hz | hz <;> simp [mem_tagOnes,hz] + +abbrev RawTag := RawRole × List RawRole + +def rawCharge (odd : Bool) (a : RawRole) : ℕ := if odd && decide (a=(0,0,0)) then 1 else 0 + +def tagCharge (t : ℕ) (odd : Bool) : TemplateVertex t → Bit := + fun a => (rawCharge odd (rawRole a) : Bit) + +def rawTags (t : ℕ) (odd : Bool) : List RawTag := + (allRoles t).flatMap (fun a => ((rawNeighbors t a).sublists.filter (fun s => decide (s.length%2=rawCharge odd a))).map (a,·)) + +lemma mem_rawTags (t : ℕ) (odd : Bool) (z : RawTag) : + z∈rawTags t odd ↔ RoleValid t z.1 ∧ z.2.Sublist (rawNeighbors t z.1) ∧ z.2.length%2=rawCharge odd z.1 := by + rcases z with ⟨a,s⟩ + simp only [rawTags,List.mem_flatMap,List.mem_map,List.mem_filter,List.mem_sublists,decide_eq_true_eq] + constructor + · rintro ⟨b,hb,u,hu,he⟩ + cases he + exact ⟨(mem_allRoles t a).mp hb,hu⟩ + · rintro ⟨ha,hs,he⟩ + exact ⟨a,(mem_allRoles t a).mpr ha,s,⟨hs,he⟩,rfl⟩ + +lemma cast_rawCharge (odd : Bool) (a : RawRole) : (rawCharge odd a : Bit).val=rawCharge odd a := by + unfold rawCharge + split <;> simp [ZMod.val_one_eq_one_mod] + +lemma mod_two_charge (n : ℕ) (odd : Bool) (a : RawRole) : + (n : Bit)=(rawCharge odd a : Bit) ↔ n%2=rawCharge odd a := by + have hc : rawCharge odd a<2 := by unfold rawCharge; split <;> omega + constructor + · intro h + have hh := congrArg ZMod.val h + simpa only [ZMod.val_natCast,Nat.mod_eq_of_lt hc] using hh + · intro h + apply ZMod.val_injective + simpa only [ZMod.val_natCast,Nat.mod_eq_of_lt hc] using h + +noncomputable def rawTagEncode {t : ℕ} (odd : Bool) (z : GlobalTag t (tagCharge t odd)) : RawTag := + (rawRole z.1,tagOnes z.1 z.2.val) + +lemma rawTagEncode_mem {t : ℕ} (odd : Bool) (z : GlobalTag t (tagCharge t odd)) : + rawTagEncode odd z∈rawTags t odd := by + apply (mem_rawTags t odd _).mpr + refine ⟨rawRole_valid z.1,tagOnes_sublist z.1 z.2.val,?_⟩ + apply (mod_two_charge _ odd _).mp + exact (tagOnes_sum z.1 z.2.val).trans z.2.property + +lemma rawTags_nodup (t : ℕ) (odd : Bool) : (rawTags t odd).Nodup := by + apply List.nodup_flatMap.mpr + constructor + · intro a _ + exact ((rawNeighbors_nodup t a).sublists.filter _).map (fun _ _ h => congrArg Prod.snd h) + · apply (allRoles_nodup t).imp + intro a b hab z ha hb + obtain ⟨s,_,he⟩ := List.mem_map.mp ha + obtain ⟨u,_,hf⟩ := List.mem_map.mp hb + exact hab ((congrArg Prod.fst he).trans (congrArg Prod.fst hf).symm) + +noncomputable def rawTagDecode {t : ℕ} (odd : Bool) (z : {z // z∈rawTags t odd}) : + GlobalTag t (tagCharge t odd) := by + classical + have hz := (mem_rawTags t odd z.val).mp z.property + let a := roleDecode ⟨z.val.1,hz.1⟩ + have ha : rawRole a=z.val.1 := rawRole_roleDecode ⟨z.val.1,hz.1⟩ + refine ⟨a,⟨fun v => if rawRole v.val∈z.val.2 then 1 else 0,?_⟩⟩ + rw [rawTag_sum a z.val.2 (by simpa only [ha] using hz.2.1)] + change _=(rawCharge odd (rawRole a) : Bit) + rw [ha] + exact (mod_two_charge _ odd _).mpr hz.2.2 + +lemma tagOnes_indicator {t : ℕ} (a : TemplateVertex t) (s : List RawRole) + (hs : s.Sublist (rawNeighbors t (rawRole a))) : + tagOnes a (fun v => if rawRole v.val∈s then 1 else 0)=s := by + classical + have hmem (r : RawRole) : r∈tagOnes a (fun v => if rawRole v.val∈s then 1 else 0) ↔ r∈s := by + by_cases hr : r∈rawNeighbors t (rawRole a) + · have hv := (mem_rawNeighbors t _ _).mp hr + let v := roleDecode ⟨r,hv.1⟩ + have he : rawRole v=r := rawRole_roleDecode ⟨r,hv.1⟩ + have hadj : (template t).Adj a v := (rawAdjacent_iff a v).mp (by simpa only [he] using hv.2) + simpa only [he,ite_eq_left_iff,zero_ne_one,imp_false,not_not] using + (mem_tagOnes a (fun v => if rawRole v.val∈s then 1 else 0) ⟨v,hadj⟩) + · exact iff_of_false (fun h => hr ((tagOnes_sublist a _).subset h)) (fun h => hr (hs.subset h)) + apply Eq.symm + apply List.Sublist.eq_of_length_le + · have hf : s.filter (fun r => decide (∃ v : (template t).neighborSet a, + rawRole v.val=r ∧ (if rawRole v.val∈s then (1 : Bit) else 0)=1))=s := by + apply List.filter_eq_self.mpr + intro r hr + exact (List.mem_filter.mp ((hmem r).mpr hr)).2 + simpa only [tagOnes,hf] using hs.filter (fun r => decide (∃ v : (template t).neighborSet a, + rawRole v.val=r ∧ (if rawRole v.val∈s then (1 : Bit) else 0)=1)) + · exact (List.Nodup.sublist (tagOnes_sublist a _) (rawNeighbors_nodup t _)).length_le_of_subset + (fun _ h => (hmem _).mp h) + +@[simp] lemma rawTagEncode_decode {t : ℕ} (odd : Bool) (z : {z // z∈rawTags t odd}) : + rawTagEncode odd (rawTagDecode odd z)=z.val := by + classical + have hz := (mem_rawTags t odd z.val).mp z.property + let a := roleDecode ⟨z.val.1,hz.1⟩ + have ha : rawRole a=z.val.1 := rawRole_roleDecode ⟨z.val.1,hz.1⟩ + change (rawRole a,tagOnes a (fun v => if rawRole v.val∈z.val.2 then 1 else 0))=z.val + rw [tagOnes_indicator a z.val.2 (by simpa only [ha] using hz.2.1),ha] + +lemma rawTagEncode_injective (t : ℕ) (odd : Bool) : Function.Injective (@rawTagEncode t odd) := by + classical + rintro ⟨a,z⟩ ⟨b,w⟩ he + have hab := (rawRole_injective t) (congrArg Prod.fst he) + change a=b at hab + subst b + have hzw : z=w := by + apply Subtype.ext + funext v + have hone : z.val v=1 ↔ w.val v=1 := by + rw [←mem_tagOnes a z.val v,←mem_tagOnes a w.val v] + rw [show tagOnes a z.val=tagOnes a w.val from congrArg Prod.snd he] + rcases bit_zero_or_one (z.val v) with hz | hz <;> + rcases bit_zero_or_one (w.val v) with hw | hw <;> simp_all + cases hzw + rfl + +noncomputable def rawTagEquiv (t : ℕ) (odd : Bool) : + GlobalTag t (tagCharge t odd) ≃ {z // z∈rawTags t odd} where + toFun z := ⟨rawTagEncode odd z,rawTagEncode_mem odd z⟩ + invFun := rawTagDecode odd + left_inv _z := rawTagEncode_injective t odd (rawTagEncode_decode odd _) + right_inv z := Subtype.ext (rawTagEncode_decode odd z) + +end ParityWL.Complexity + +end OAI diff --git a/lean/OAI/Combinatorics/ParityLifts/UniformTrial.lean b/lean/OAI/Combinatorics/ParityLifts/UniformTrial.lean new file mode 100644 index 0000000000000000000000000000000000000000..a4d395bc7431c213b3fd0408a49defbfe4e6fcb3 --- /dev/null +++ b/lean/OAI/Combinatorics/ParityLifts/UniformTrial.lean @@ -0,0 +1,76 @@ +import OAI.Combinatorics.ParityLifts.UniformPost + +namespace OAI + +namespace ParityWL.Complexity + +noncomputable def trialCode (c : Convention) (M : Machine) : FCode := + .seq trialNormalizeProgram.program.code (uniformPostCode (uniformLeafDecisionCode c M)) + +lemma trialCode_rate : ∃ D P : ℕ, 0 0) := by + funext a + simp [tagCharge,rawCharge] + +lemma tagCharge_true (t : ℕ) : tagCharge t true=starParity t := by + funext a + cases a with + | inl i => + have he : (∃ j : Fin t, j.val=0 ∧ (Sum.inl i : TemplateVertex t)=.inl j) ↔ i.val=0 := by simp + simp only [tagCharge,rawCharge,rawRole,Bool.true_and,decide_eq_true_eq,Prod.mk.injEq, + and_self,starParity,he] + split <;> simp + | inr h => + have hn : h.1.1.1.1.val≠h.1.1.1.2.val := ne_of_lt h.1.1.2 + have hz : (h.1.1.1.1.val,h.1.1.1.2.val,h.1.2.val)≠(0,0,0) := by + intro he + have h1 := congrArg Prod.fst he + have h2 := congrArg (fun x : RawRole => x.2.1) he + exact hn (h1.trans h2.symm) + simp [tagCharge,rawCharge,rawRole,hz,starParity] + +lemma bit_eq_iff_one (x y : Bit) : x=y ↔ (x=1 ↔ y=1) := by + rcases bit_zero_or_one x with hx | hx <;> + rcases bit_zero_or_one y with hy | hy <;> simp [hx,hy] + +def rawTagTest (x y : RawTag) : Bool := + rawAdjacent x.1 y.1 && decide ((y.1∈x.2) ↔ (x.1∈y.2)) + +lemma rawTagTest_encode {t : ℕ} (odd : Bool) (x y : GlobalTag t (tagCharge t odd)) : + rawTagTest (rawTagEncode odd x) (rawTagEncode odd y)=tagTest (tagCharge t odd) x y := by + apply Bool.eq_iff_iff.mpr + change (rawAdjacent (rawRole x.1) (rawRole y.1) && + decide ((rawRole y.1∈tagOnes x.1 x.2.val) ↔ (rawRole x.1∈tagOnes y.1 y.2.val)))=true ↔ _ + rw [Bool.and_eq_true,rawAdjacent_iff,decide_eq_true_eq] + by_cases h : (template t).Adj x.1 y.1 + · have hx := mem_tagOnes x.1 x.2.val ⟨y.1,h⟩ + have hy := mem_tagOnes y.1 y.2.val ⟨x.1,h.symm⟩ + simp only [h,true_and,tagTest,↓reduceDIte,decide_eq_true_eq] + exact (iff_congr hx hy).trans (bit_eq_iff_one _ _).symm + · simp only [h,false_and,tagTest,↓reduceDIte,Bool.false_eq_true] + +abbrev RawVertex := RawTag × ℕ + +def rawVertices (D : RawChoiceData) (tags : List RawTag) : List RawVertex := + tags.flatMap (fun z => (List.range (D.roleSize z.1)).map (z,·)) + +lemma mem_rawVertices (D : RawChoiceData) (tags : List RawTag) (x : RawVertex) : + x∈rawVertices D tags ↔ x.1∈tags ∧ x.2 congrArg Prod.snd h) + · apply hs.imp + intro z w hzw x hx hy + obtain ⟨d,_,he⟩ := List.mem_map.mp hx + obtain ⟨e,_,hf⟩ := List.mem_map.mp hy + exact hzw ((congrArg Prod.fst he).trans (congrArg Prod.fst hf).symm) + +noncomputable def rawVertexEncode {t : ℕ} (D : ChoiceData t) (odd : Bool) + (x : (z : GlobalTag t (tagCharge t odd)) × Fin (D.roleSize z.1)) : RawVertex := + (rawTagEncode odd x.1,x.2.val) + +lemma rawVertexEncode_mem {t : ℕ} (D : ChoiceData t) (odd : Bool) + (x : (z : GlobalTag t (tagCharge t odd)) × Fin (D.roleSize z.1)) : + rawVertexEncode D odd x∈rawVertices D.raw (rawTags t odd) := by + rw [mem_rawVertices] + refine ⟨rawTagEncode_mem odd x.1,?_⟩ + change x.2.val ⟨rawVertexEncode D odd x,rawVertexEncode_mem D odd x⟩) ⟨by + intro x y h + exact rawVertexEncode_injective D odd (congrArg Subtype.val h),by + rintro ⟨⟨z,d⟩,hd⟩ + have hz := (mem_rawVertices D.raw (rawTags t odd) (z,d)).mp hd + let w := (rawTagEquiv t odd).symm ⟨z,hz.1⟩ + have hw : rawTagEncode odd w=z := congrArg Subtype.val ((rawTagEquiv t odd).apply_symm_apply ⟨z,hz.1⟩) + have hrole : rawRole w.1=z.1 := congrArg Prod.fst hw + have hsize : D.roleSize w.1=D.raw.roleSize z.1 := by rw [←D.raw_roleSize,hrole] + refine ⟨⟨w,⟨d,by rw [hsize]; exact hz.2⟩⟩,?_⟩ + apply Subtype.ext + change (rawTagEncode odd w,d)=(z,d) + rw [hw]⟩ + +noncomputable def rawIndexEquiv {t : ℕ} (D : ChoiceData t) (odd : Bool) : + Fin (rawVertices D.raw (rawTags t odd)).length ≃ + LiftVertex (template t) (baseGraph D.system) (baseProjection D.system) (tagCharge t odd) := + (List.Nodup.getEquiv _ (rawVertices_nodup D.raw _ (rawTags_nodup t odd))).trans + ((rawVertexEquiv D odd).symm.trans (D.globalLiftEquiv (tagCharge t odd))) + +noncomputable def rawIndexedGraph {t : ℕ} (D : ChoiceData t) (odd : Bool) : + SimpleGraph (Fin (rawVertices D.raw (rawTags t odd)).length) := + (liftGraph (template t) (baseGraph D.system) (baseProjection D.system) (tagCharge t odd)).comap + (rawIndexEquiv D odd) + +noncomputable def rawIndexedIso {t : ℕ} (D : ChoiceData t) (odd : Bool) : + rawIndexedGraph D odd ≃g liftGraph (template t) (baseGraph D.system) (baseProjection D.system) (tagCharge t odd) := + SimpleGraph.Iso.comap (rawIndexEquiv D odd) _ + +def rawEdgeTest (D : RawChoiceData) (x y : RawVertex) : Bool := + D.baseTest x.1.1 x.2 y.1.1 y.2 && rawTagTest x.1 y.1 + +lemma rawEdgeTest_encode {t : ℕ} (D : ChoiceData t) (odd : Bool) + (x y : (z : GlobalTag t (tagCharge t odd)) × Fin (D.roleSize z.1)) : + rawEdgeTest D.raw (rawVertexEncode D odd x) (rawVertexEncode D odd y)=true ↔ + (liftGraph (template t) (baseGraph D.system) (baseProjection D.system) (tagCharge t odd)).Adj + (D.globalLiftEquiv (tagCharge t odd) x) (D.globalLiftEquiv (tagCharge t odd) y) := by + rw [D.lift_arc_iff] + obtain ⟨hx,hxi⟩ := D.globalLift_raw (tagCharge t odd) x + obtain ⟨hy,hyi⟩ := D.globalLift_raw (tagCharge t odd) y + have hx' := congrArg Sigma.fst hx + have hy' := congrArg Sigma.fst hy + have htag := rawTagTest_encode odd x.1 y.1 + dsimp only [rawTagEncode] at htag + dsimp only at hx' hy' + simp only [rawEdgeTest,rawVertexEncode,rawTagEncode,D.raw_baseTest,Bool.and_eq_true, + hx,hy,hx',hy',hxi,hyi,htag] + +end ParityWL.Complexity + +end OAI diff --git a/lean/OAI/Combinatorics/ParityLifts/WeightedDual.lean b/lean/OAI/Combinatorics/ParityLifts/WeightedDual.lean new file mode 100644 index 0000000000000000000000000000000000000000..cededc2bc3f0b395795cef202bc58b0bf09b82dd --- /dev/null +++ b/lean/OAI/Combinatorics/ParityLifts/WeightedDual.lean @@ -0,0 +1,183 @@ +import OAI.Combinatorics.ParityLifts.LiftCounts + +namespace OAI + +namespace ParityWL + +open scoped BigOperators + +section WeightedDual + +open scoped Classical + +lemma linearFunctional_expansion {I : Type} [Fintype I] [DecidableEq I] + (f : (I → Bit) →ₗ[Bit] Bit) (v : I → Bit) : + f v = ∑ i, f (Pi.single i 1) * v i := by + conv_lhs => rw [← Finset.univ_sum_single v] + rw [map_sum] + apply Finset.sum_congr rfl + intro i _ + have h : Pi.single i (v i) = v i • Pi.single i (1 : Bit) := by + rw [← Pi.single_smul] + simp + rw [h, map_smul] + exact mul_comm _ _ + +variable {A V W : Type} [Fintype A] [Fintype V] [Fintype W] +variable (T : SimpleGraph A) (G : SimpleGraph V) (F : SimpleGraph W) +variable (τ : G →g T) (φ : F →g G) + +def dartNeighborsEquiv : F.Dart ≃ ((x : W) × F.neighborSet x) where + toFun d := ⟨d.fst, ⟨d.snd, d.adj⟩⟩ + invFun d := ⟨(d.1, d.2.1), d.2.2⟩ + left_inv _ := rfl + right_inv _ := rfl + +def dartReverseEquiv : F.Dart ≃ F.Dart := + SimpleGraph.Dart.symm_involutive.toPerm + +noncomputable def dualVertex (f : (EquationRow F → Bit) →ₗ[Bit] Bit) (x : W) : Bit := + f (Pi.single (.inl x) 1) + +noncomputable def dualDart (f : (EquationRow F → Bit) →ₗ[Bit] Bit) (d : F.Dart) : Bit := + f (Pi.single (.inr d) 1) + +noncomputable def dualEdge (f : (EquationRow F → Bit) →ₗ[Bit] Bit) (x y : W) : Bit := + if h : F.Adj x y then + dualDart F f ⟨(x, y), h⟩ + dualDart F f ⟨(y, x), h.symm⟩ else 0 + +omit [Fintype W] in +lemma dualEdge_symm (f : (EquationRow F → Bit) →ₗ[Bit] Bit) (x y : W) : + dualEdge F f x y = dualEdge F f y x := by + by_cases h : F.Adj x y + · simp [dualEdge, h, h.symm, add_comm] + · have h' : ¬ F.Adj y x := fun hy => h hy.symm + simp [dualEdge, h, h'] + +omit [Fintype W] in +lemma dualEdge_support (f : (EquationRow F → Bit) →ₗ[Bit] Bit) (x y : W) + (h : ¬ F.Adj x y) : dualEdge F f x y = 0 := by + simp [dualEdge, h] + +omit [Fintype V] in +lemma dual_constraint_expansion (f : (EquationRow F → Bit) →ₗ[Bit] Bit) + (z : Variables T G F τ φ) : + f (constraintMap T G F τ φ z) = + (∑ x, dualVertex F f x * ∑ v, z x v) + + ∑ x, ∑ y : F.neighborSet x, + dualEdge F f x y * z x ⟨τ (φ y), τ.map_adj (φ.map_adj y.2)⟩ := by + rw [linearFunctional_expansion, Fintype.sum_sum_type] + congr 1 + simp only [constraintMap, LinearMap.coe_mk, AddHom.coe_mk] + change (∑ d : F.Dart, dualDart F f d * + (z d.fst ⟨τ (φ d.snd), τ.map_adj (φ.map_adj d.adj)⟩ + z d.snd ⟨τ (φ d.fst), τ.map_adj (φ.map_adj d.adj.symm)⟩)) = _ + simp_rw [mul_add] + rw [Finset.sum_add_distrib] + have hs : (∑ d : F.Dart, dualDart F f d * z d.snd ⟨τ (φ d.fst), τ.map_adj (φ.map_adj d.adj.symm)⟩) = + ∑ d : F.Dart, dualDart F f d.symm * z d.fst ⟨τ (φ d.snd), τ.map_adj (φ.map_adj d.adj)⟩ := by + exact (Equiv.sum_comp (dartReverseEquiv F) + (fun d : F.Dart => dualDart F f d * z d.snd ⟨τ (φ d.fst), τ.map_adj (φ.map_adj d.adj.symm)⟩)).symm + rw [hs, ← Finset.sum_add_distrib] + simp_rw [← add_mul] + calc + _ = ∑ d : ((x : W) × F.neighborSet x), + dualEdge F f d.1 d.2 * z d.1 ⟨τ (φ d.2), τ.map_adj (φ.map_adj d.2.2)⟩ := by + apply Fintype.sum_equiv (dartNeighborsEquiv F) + intro d + dsimp [dartNeighborsEquiv] + rw [dualEdge, dite_eq_left d.adj] + rfl + _ = _ := Fintype.sum_sigma _ + + +lemma sum_subtype_indicator {I : Type} [Fintype I] {R : Type} [AddCommMonoid R] + (p : I → Prop) [DecidablePred p] [Fintype {x // p x}] (v : I → R) : + (∑ x : {x // p x}, v x) = ∑ x, if p x then v x else 0 := by + rw [← Finset.sum_subtype (Finset.univ.filter p) (by simp), Finset.sum_filter] + +noncomputable def variableUnit (x : W) (u : T.neighborSet (τ (φ x))) : + Variables T G F τ φ := + fun y v => if y = x ∧ v.1 = u.1 then 1 else 0 + +omit [Fintype V] [Fintype W] in +lemma variableUnit_sum (x y : W) (u : T.neighborSet (τ (φ x))) : + (∑ v, variableUnit T G F τ φ x u y v) = if y = x then 1 else 0 := by + by_cases h : y = x + · subst y + have he : ∀ v : T.neighborSet (τ (φ x)), v.1 = u.1 ↔ v = u := + fun _ => Subtype.ext_iff.symm + simp [variableUnit, he] + · simp [variableUnit, h] + +omit [Fintype V] in +lemma dual_coordinate (f : (EquationRow F → Bit) →ₗ[Bit] Bit) + (hf : ∀ z, f (constraintMap T G F τ φ z) = 0) + (x : W) (u : T.neighborSet (τ (φ x))) : + (∑ y, if τ (φ y) = u.1 then dualEdge F f x y else 0) = dualVertex F f x := by + have h := hf (variableUnit T G F τ φ x u) + rw [dual_constraint_expansion] at h + have hv : (∑ y, dualVertex F f y * + ∑ v, variableUnit T G F τ φ x u y v) = dualVertex F f x := by + simp_rw [variableUnit_sum, mul_ite, mul_one, mul_zero] + simp + have he : (∑ v, ∑ y : F.neighborSet v, dualEdge F f v y * + variableUnit T G F τ φ x u v ⟨τ (φ y), τ.map_adj (φ.map_adj y.2)⟩) = + ∑ y, if τ (φ y) = u.1 then dualEdge F f x y else 0 := by + rw [Finset.sum_eq_single x] + · simp only [variableUnit, true_and, mul_ite, mul_one, mul_zero] + change (∑ y : {y // F.Adj x y}, + if τ (φ y.1) = u.1 then dualEdge F f x y.1 else 0) = _ + rw [sum_subtype_indicator (F.Adj x) + (fun y => if τ (φ y) = u.1 then dualEdge F f x y else 0)] + apply Finset.sum_congr rfl + intro y _ + by_cases ha : F.Adj x y + · simp [ha] + · simp [ha, dualEdge_support F f x y ha] + · intro v _ hv + simp [variableUnit, hv] + · simp + rw [hv, he] at h + have h' : dualVertex F f x = + (∑ y, if τ (φ y) = u.1 then dualEdge F f x y else 0) := by + rwa [← CharTwo.sub_eq_add, sub_eq_zero] at h + exact h'.symm + +omit [Fintype A] [Fintype V] in +lemma dual_rhs (f : (EquationRow F → Bit) →ₗ[Bit] Bit) (b : A → Bit) : + f (constraintRHS T G F τ φ b) = ∑ x, dualVertex F f x * b (τ (φ x)) := by + rw [linearFunctional_expansion, Fintype.sum_sum_type] + simp [constraintRHS, dualVertex] + +/-- The supported, symmetric dual certificate of the *actual* parity-lift system. -/ +structure WeightedWitness (a : F →g T) (b : A → Bit) where + vertex : W → Bit + edge : W → W → Bit + symmetric : ∀ x y, edge x y = edge y x + supported : ∀ x y, ¬ F.Adj x y → edge x y = 0 + coordinate : ∀ x (u : T.neighborSet (a x)), + (∑ y, if a y = u.1 then edge x y else 0) = vertex x + odd : (∑ x, vertex x * b (a x)) = 1 + +omit [Fintype V] in + theorem inconsistent_weightedWitness (b : A → Bit) + (h : ¬ Nonempty (Solutions T G F τ φ b)) : + Nonempty (WeightedWitness T F (τ.comp φ) b) := by + have hn : ¬ ∃ z, constraintMap T G F τ φ z = constraintRHS T G F τ φ b := by + rintro ⟨z, hz⟩ + exact h ⟨⟨z, (liftEquations_iff T G F τ φ b z).mpr hz⟩⟩ + obtain ⟨f, hf, hb⟩ := (binary_alternative _ _).mp hn + refine ⟨{ + vertex := dualVertex F f + edge := dualEdge F f + symmetric := dualEdge_symm F f + supported := dualEdge_support F f + coordinate := dual_coordinate T G F τ φ f hf + odd := ?_ }⟩ + rwa [dual_rhs] at hb + +end WeightedDual + +end ParityWL + +end OAI diff --git a/lean/OAI/Combinatorics/ParityLifts/Witnesses.lean b/lean/OAI/Combinatorics/ParityLifts/Witnesses.lean new file mode 100644 index 0000000000000000000000000000000000000000..b52bc95c7bec4d75103c43ef955e557c88109a72 --- /dev/null +++ b/lean/OAI/Combinatorics/ParityLifts/Witnesses.lean @@ -0,0 +1,187 @@ +import OAI.Combinatorics.ParityLifts.DecompositionCuts + +namespace OAI + +namespace ParityWL + +open scoped BigOperators + +section WitnessConverse + +open scoped Classical + +variable {A W : Type} [Fintype A] [Fintype W] +variable {T : SimpleGraph A} {F : SimpleGraph W} {a : F →g T} {b : A → Bit} + +omit [Fintype A] in +lemma WeightedWitness.coordinate_neighbors (w : WeightedWitness T F a b) + (x : W) (u : T.neighborSet (a x)) : + (∑ y : F.neighborSet x, if a y = u.1 then w.edge x y else 0) = w.vertex x := by + change (∑ y : {y // F.Adj x y}, if a y.1 = u.1 then w.edge x y.1 else 0) = _ + rw [sum_subtype_indicator (F.Adj x) + (fun y => if a y = u.1 then w.edge x y else 0)] + convert w.coordinate x u using 1 + apply Finset.sum_congr rfl + intro y _ + by_cases h : F.Adj x y + · simp [h] + · simp [h, w.supported x y h] + +lemma WeightedWitness.tag_sum (w : WeightedWitness T F a b) + (z : (x : W) → T.neighborSet (a x) → Bit) : + (∑ x, w.vertex x * ∑ u, z x u) = + ∑ d : F.Dart, w.edge d.fst d.snd * z d.fst ⟨a d.snd, a.map_adj d.adj⟩ := by + have hx : ∀ x, w.vertex x * ∑ u, z x u = + ∑ y : F.neighborSet x, w.edge x y * z x ⟨a y, a.map_adj y.2⟩ := by + intro x + rw [Finset.mul_sum] + calc + _ = ∑ u : T.neighborSet (a x), + (∑ y : F.neighborSet x, if a y = u.1 then w.edge x y else 0) * z x u := by + simp_rw [w.coordinate_neighbors] + _ = ∑ y : F.neighborSet x, ∑ u : T.neighborSet (a x), + if a y = u.1 then w.edge x y * z x u else 0 := by + simp_rw [Finset.sum_mul, ite_mul, zero_mul] + rw [Finset.sum_comm] + _ = _ := by + apply Finset.sum_congr rfl + intro y _ + have he : ∀ u : T.neighborSet (a x), + a y = u.1 ↔ u = ⟨a y, a.map_adj y.2⟩ := by + intro u + constructor + · intro h; exact Subtype.ext h.symm + · intro h; exact (congrArg Subtype.val h).symm + simp [he] + rw [Fintype.sum_congr _ _ hx] + calc + _ = ∑ d : (x : W) × F.neighborSet x, + w.edge d.1 d.2 * z d.1 ⟨a d.2, a.map_adj d.2.2⟩ := + (Fintype.sum_sigma _).symm + _ = _ := (Equiv.sum_comp (dartNeighborsEquiv F) + (fun d : (x : W) × F.neighborSet x => + w.edge d.1 d.2 * z d.1 ⟨a d.2, a.map_adj d.2.2⟩)).symm + +/-- A genuine dual certificate makes the source-indexed tag system inconsistent. -/ +theorem WeightedWitness.no_tags (w : WeightedWitness T F a b) + (z : (x : W) → T.neighborSet (a x) → Bit) + (hz : ∀ x, ∑ u, z x u = b (a x)) + (he : ∀ x y (h : F.Adj x y), + z x ⟨a y, a.map_adj h⟩ = z y ⟨a x, a.map_adj h.symm⟩) : False := by + have h := w.tag_sum z + simp_rw [hz] at h + rw [w.odd] at h + have hzero : (∑ d : F.Dart, w.edge d.fst d.snd * + z d.fst ⟨a d.snd, a.map_adj d.adj⟩) = 0 := by + apply Finset.sum_ninvolution SimpleGraph.Dart.symm + · intro d + change w.edge d.fst d.snd * z d.fst _ + w.edge d.snd d.fst * z d.snd _ = 0 + rw [w.symmetric d.fst d.snd, he d.fst d.snd d.adj] + exact CharTwo.add_self_eq_zero _ + · intro d _ + exact d.symm_ne + · simp + · exact SimpleGraph.Dart.symm_symm + exact one_ne_zero (h.trans hzero) + +variable {V : Type} [Fintype V] {G : SimpleGraph V} {τ : G →g T} {φ : F →g G} + +omit [Fintype V] in +theorem weightedWitness_inconsistent + (w : WeightedWitness T F (τ.comp φ) b) : + ¬ Nonempty (Solutions T G F τ φ b) := by + rintro ⟨z⟩ + exact w.no_tags z.1 z.2.1 z.2.2 + +theorem homCount_lift_strict_iff_witness : + homCount F (liftGraph T G τ b) < homCount F (liftGraph T G τ (fun _ => 0)) ↔ + ∃ φ : F →g G, Nonempty (WeightedWitness T F (τ.comp φ) b) := by + rw [homCount_lift_strict_iff] + constructor + · rintro ⟨φ, hφ⟩ + exact ⟨φ, inconsistent_weightedWitness T G F τ φ b hφ⟩ + · rintro ⟨φ, ⟨w⟩⟩ + exact ⟨φ, weightedWitness_inconsistent w⟩ + +end WitnessConverse + +section PositiveWitness + +open scoped Classical + +variable {t : ℕ} {C : ChoiceSystem t} + +lemma BaseArc.type_adj {x y : BaseVertex C} (h : BaseArc C x y) : + (template t).Adj (baseType x) (baseType y) := by + cases h with + | main p d e he => exact ne_of_lt p.property + | left h d => exact Or.inl rfl + | right h e => exact Or.inr (Or.inl rfl) + | third h q d => exact Or.inr (Or.inr rfl) + +lemma BaseArc.adj {x y : BaseVertex C} (h : BaseArc C x y) : + (baseGraph C).Adj x y := by + refine ⟨?_, Or.inl h⟩ + intro he + exact (template t).ne_of_adj h.type_adj (congrArg baseType he) + +noncomputable def choiceMap (d : (i : Fin t) → C.Domain i) + (hd : ∀ p : MainPair t, C.leftLabel p (d p.1.1) = C.rightLabel p (d p.1.2)) : + template t →g baseGraph C where + toFun + | .inl i => .inl ⟨i, d i⟩ + | .inr h => .inr ⟨h, C.leftLabel h.1.1 (d h.1.1.1.1)⟩ + map_rel' := by + have help : ∀ h i, helperIncident h i → (baseGraph C).Adj + (.inr ⟨h, C.leftLabel h.1.1 (d h.1.1.1.1)⟩) (.inl ⟨i, d i⟩) := by + intro h i hi + rcases hi with rfl | rfl | rfl + · exact (BaseArc.left h _).adj + · rw [hd h.1.1] + exact (BaseArc.right h _).adj + · exact (BaseArc.third h _ _).adj + intro x y he + cases x with + | inl i => + cases y with + | inl j => + rcases lt_or_gt_of_ne he with hij | hji + · exact (BaseArc.main ⟨(i,j), hij⟩ (d i) (d j) (hd _)).adj + · exact (BaseArc.main ⟨(j,i), hji⟩ (d j) (d i) (hd _)).adj.symm + | inr h => exact (help h i he).symm + | inr h => + cases y with + | inl i => exact help h i he + | inr g => exact False.elim he + +@[simp] lemma choiceMap_type (d : (i : Fin t) → C.Domain i) + (hd : ∀ p : MainPair t, C.leftLabel p (d p.1.1) = C.rightLabel p (d p.1.2)) + (v : TemplateVertex t) : baseType (choiceMap d hd v) = v := by + cases v <;> rfl + +/-- The explicit noncancelling source is the uncolored template itself. -/ +theorem successful_template_count_gap (ht : 0 < t) (hs : C.Successful) : + homCount (template t) (starLift C) < homCount (template t) (zeroLift C) := by + obtain ⟨d, hd⟩ := hs + let φ := choiceMap d hd + have hφ : ∀ v, ((baseProjection C).comp φ) v = v := choiceMap_type d hd + apply homCount_lift_strict_iff_witness.mpr + refine ⟨φ, ⟨{ + vertex := fun _ => 1 + edge := fun x y => if (template t).Adj x y then 1 else 0 + symmetric := by intro x y; simp [SimpleGraph.adj_comm] + supported := by intro x y h; simp [h] + coordinate := ?_ + odd := ?_ }⟩⟩ + · intro x u + simp only [hφ] + have hu : (template t).Adj x u.1 := by simpa [hφ] using u.2 + simp [hu] + · simp only [one_mul, hφ] + simp [starParity_value ht] + +end PositiveWitness + +end ParityWL + +end OAI diff --git a/lean/OAI/Combinatorics/ParityLifts/Words.lean b/lean/OAI/Combinatorics/ParityLifts/Words.lean new file mode 100644 index 0000000000000000000000000000000000000000..b1d5e021c6be57d9b619dc3df2c7fde05de93e81 --- /dev/null +++ b/lean/OAI/Combinatorics/ParityLifts/Words.lean @@ -0,0 +1,170 @@ +import OAI.Combinatorics.ParityLifts.Arithmetic + +namespace OAI + +namespace ParityWL.Complexity + +def wordsStep (xs : List (List Bool)) : List (List Bool) := + xs.map (false::·) ++ xs.map (true::·) + +def words : ℕ → List (List Bool) + | 0 => [[]] + | n+1 => wordsStep (words n) + +@[simp] lemma mem_words (n : ℕ) (bs : List Bool) : bs∈words n ↔ bs.length=n := by + induction n generalizing bs with + | zero => simp [words] + | succ n ih => + cases bs with + | nil => simp [words,wordsStep] + | cons b bs => cases b <;> simp [words,wordsStep,ih] + +@[simp] lemma length_words (n : ℕ) : (words n).length=2^n := by + induction n with + | zero => rfl + | succ n ih => simp [words,wordsStep,ih,pow_succ]; omega + +lemma bool_list_size (bs : List Bool) : (treeEncode bs).size≤4*bs.length+1 := by + induction bs with + | nil => simp [DataTree.size] + | cons b bs ih => cases b <;> simp_all [DataTree.size] <;> omega + +lemma words_size (n : ℕ) : (treeEncode (words n)).size≤1+2^n*(4*n+2) := by + rw [treeEncode_list_size] + apply Nat.add_le_add_left + have h := list_sum_map_le (words n) (fun a => (treeEncode a).size+1) (4*n+2) (by + intro a ha + have he := (mem_words n a).mp ha + have hb := bool_list_size a + omega) + simpa using h + +def PolyProgram.wordsStep : PolyProgram (List (List Bool)) (List (List Bool)) wordsStep := by + let F := ((PolyProgram.const false).pair (PolyProgram.id (List Bool))).comp (PolyProgram.cons Bool) + let T := ((PolyProgram.const true).pair (PolyProgram.id (List Bool))).comp (PolyProgram.cons Bool) + exact (F.map.pair T.map).comp (PolyProgram.append (List Bool)) + +lemma fold_wordsStep (xs : List Bool) (n : ℕ) : + xs.foldl (fun s _ => wordsStep s) (words n)=words (n+xs.length) := by + induction xs generalizing n with + | nil => simp + | cons b xs ih => + change xs.foldl (fun s _ => wordsStep s) (words (n+1)) = _ + rw [ih] + congr 1 + simp only [List.length_cons] + omega + +@[simp] lemma TreeProgram.congr_time {α β : Type} [TreeCodec α] [TreeCodec β] + {f g : α → β} (P : TreeProgram α β f) (h : ∀ x, f x=g x) : + (P.congr h).time=P.time := by + cases funext h + rfl + +def TreeProgram.words : TreeProgram ℕ (List (List Bool)) Complexity.words := by + let P := (TreeProgram.snd Bool (List (List Bool))).comp PolyProgram.wordsStep.program + let I := PolyProgram.ticks.program.pair (TreeProgram.const ([[]]:List (List Bool))) + refine (I.comp P.foldl).congr ?_ + intro n + change (List.replicate n false).foldl (fun s _ => Complexity.wordsStep s) (Complexity.words 0)=_ + simp only [fold_wordsStep,List.length_replicate,Nat.zero_add] + +lemma word_stage_size {xs ys zs : List Bool} (n : ℕ) (he : ys++zs=xs) (hn : xs.length=n) : + (treeEncode (zs,words ys.length)).size ≤ 10*(n+1)*2^n := by + have hy : ys.length≤n := by have := congrArg List.length he; simp at this; omega + have hz : zs.length≤n := by have := congrArg List.length he; simp at this; omega + have hpow : 2^ys.length≤2^n := Nat.pow_le_pow_right (by omega) hy + have h1 : 1≤2^n := Nat.one_le_two_pow + have hs := words_size ys.length + have hb := bool_list_size zs + simp only [treeEncode_pair,DataTree.size] + have hm : 2^ys.length*(4*ys.length+2)≤2^n*(4*n+2) := by gcongr + nlinarith + +lemma TreeProgram.words_bound : ∃ (C E : ℕ), ∀ n : ℕ, + TreeProgram.words.time n ≤ C * (n+1)^E * 2^(E*n) := by + let P := (TreeProgram.snd Bool (List (List Bool))).comp PolyProgram.wordsStep.program + let Q := (PolyProgram.snd Bool (List (List Bool))).comp PolyProgram.wordsStep + have hP : Q.program=P := rfl + let E := Q.degree+3 + let C := 1000+100*Q.coefficient*11^Q.degree + refine ⟨C,E,?_⟩ + intro n + let X := (n+1)*2^n + have hx : 1≤X := by dsimp [X]; exact Nat.mul_pos (by omega) (by positivity) + have hw : P.foldWork (List.replicate n false) (Complexity.words 0) ≤ + (n+1)*(10*(10*X+1)+Q.coefficient*(11*X)^Q.degree+1) := by + refine (TreeProgram.foldWork_prefix P _ _ (10*X) (Q.coefficient*(11*X)^Q.degree) ?_ ?_).trans ?_ + · intro ys zs he + change (treeEncode (zs,ys.foldl (fun s _ => wordsStep s) (Complexity.words 0))).size ≤ _ + rw [fold_wordsStep,Nat.zero_add] + simpa only [X,Nat.mul_assoc] using word_stage_size n he (List.length_replicate ..) + · intro ys a zs he + rw [← hP] + apply (Q.bound _).trans + apply Nat.mul_le_mul_left + apply Nat.pow_le_pow_left + have h := word_stage_size n he (List.length_replicate ..) + change (treeEncode (a,ys.foldl (fun s _ => wordsStep s) (Complexity.words 0))).size+1 ≤ _ + rw [fold_wordsStep,Nat.zero_add] + have hta := (treeEncode a).size_pos + simp only [treeEncode_pair,treeEncode_cons,DataTree.size] at h ⊢ + change _ ≤ 11*X + have hX : 10*(n+1)*2^n=10*X := by dsimp [X]; ring + rw [hX] at h + omega + · simp + have ho := words_size n + have hinit : (PolyProgram.ticks.program.pair (TreeProgram.const ([[]]:List (List Bool)))).time n ≤ + 20*(n+1) := by + simp [PolyProgram.ticks, PolyProgram.expr, PolyProgram.of_linear, + TreeProgram.pair, TreeProgram.const, TExpr.cost, DataTree.size] + omega + have ht : TreeProgram.words.time n ≤ + 20*(n+1)+(n+1)*(10*(10*X+1)+Q.coefficient*(11*X)^Q.degree+1)+1+2^n*(4*n+2)+4 := by + simp only [TreeProgram.words, TreeProgram.congr_time] + change (PolyProgram.ticks.program.pair (TreeProgram.const ([[]]:List (List Bool)))).time n + + (P.foldWork (List.replicate n false) (Complexity.words 0) + + (treeEncode (([]:List Bool), (List.replicate n false).foldl + (fun s _ => wordsStep s) (Complexity.words 0))).size + 1) + 1 ≤ _ + rw [fold_wordsStep,List.length_replicate,Nat.zero_add] + simp only [treeEncode_pair,treeEncode_nil,DataTree.size] + omega + have hnX : n+1≤X := by dsimp [X]; exact Nat.le_mul_of_pos_right _ (by positivity) + have hpow : X^Q.degree ≤ X^(Q.degree+2) := Nat.pow_le_pow_right hx (by omega) + have hpow1 : X≤X^(Q.degree+2) := by + simpa using Nat.pow_le_pow_right hx (show 1≤Q.degree+2 by omega) + have hxE : X^(Q.degree+2)*X = X^E := by dsimp [E]; rw [pow_succ]; congr 1 + have hbig : TreeProgram.words.time n ≤ C*X^E := by + let Y := X^(Q.degree+2) + let A := Q.coefficient*11^Q.degree + have hY : 1≤Y := Nat.one_le_pow _ _ hx + have hq : Q.coefficient*(11*X)^Q.degree ≤ A*Y := by + rw [mul_pow]; dsimp only [A,Y] + simpa only [Nat.mul_assoc] using Nat.mul_le_mul_left (Q.coefficient*11^Q.degree) hpow + have hn : 2^n*(4*n+2)≤6*X := by + dsimp [X] + calc + _ ≤ 2^n*(6*(n+1)) := Nat.mul_le_mul_left _ (by omega) + _ = _ := by ring + have hinner : 10*(10*X+1)+Q.coefficient*(11*X)^Q.degree+1 ≤ (111+A)*Y := by + have h100 : 100*X≤100*Y := Nat.mul_le_mul_left 100 hpow1 + nlinarith only [h100,hY,hq] + have houter : (n+1)*(10*(10*X+1)+Q.coefficient*(11*X)^Q.degree+1) ≤ X*((111+A)*Y) := + Nat.mul_le_mul hnX hinner + have hmore : 20*(n+1)+1+2^n*(4*n+2)+4 ≤ 40*X*Y := by + have hh : X≤X*Y := Nat.le_mul_of_pos_right X hY + nlinarith only [hnX,hn,hx,hh] + calc + _ ≤ (40*X*Y)+X*((111+A)*Y) := by omega + _ ≤ (1000+100*A)*(Y*X) := by nlinarith [Nat.zero_le (A*X*Y)] + _ = C*X^E := by dsimp only [C,A,Y]; rw [← hxE]; ring + apply hbig.trans + dsimp only [X] + rw [mul_pow, ← pow_mul] + rw [show n*E=E*n by exact Nat.mul_comm _ _] + exact le_of_eq (by ring) + +end ParityWL.Complexity + +end OAI diff --git a/lean/OAI/Combinatorics/PerfectMatching/AlgorithmPartition.lean b/lean/OAI/Combinatorics/PerfectMatching/AlgorithmPartition.lean new file mode 100644 index 0000000000000000000000000000000000000000..d345173ebe8090fab786813337d888fccaf1c49c --- /dev/null +++ b/lean/OAI/Combinatorics/PerfectMatching/AlgorithmPartition.lean @@ -0,0 +1,103 @@ +import OAI.Combinatorics.PerfectMatching.Partition +import OAI.Combinatorics.PerfectMatching.Ascent + +namespace OAI + +section + +namespace BinaryMatching.Algorithm +noncomputable section +open Finset MatchingEntropy + +def smoothObjective (G : Input) (x : Pair G.n → ℝ) : ℝ := + entropy x/Real.log 2+∑ e,(beta G e:ℝ)*x e + +def Z (G : Input) : ℝ := (completeGraph G.n).weightedZ (fun e => (beta G e:ℝ)) +def logZ (G : Input) : ℝ := Real.log (Z G)/Real.log 2 + +lemma complete_matching_nonempty {n : ℕ} (hn : 4≤ n) (heven : Even n) : + Nonempty (completeGraph n).Matching := by + obtain ⟨p,hp⟩ := ((completeGraph n).mem_polytope_iff _).mp (uniform_feasible hn heven) + by_contra h + have : IsEmpty (completeGraph n).Matching := not_nonempty_iff.mp h + simpa using hp.1.2 + +lemma mass_half {n : ℕ} (heven : Even n) {x : Pair n → ℝ} + (hx : x∈(completeGraph n).polytope) : (∑ e,x e)=(n:ℝ)/2 := by + obtain ⟨r,hr⟩ := heven + have hn : Fintype.card (Fin n)=2*r := by simp; omega + rw [(completeGraph n).marginal_sum hn hx] + have hn' : (n:ℝ)=2*(r:ℝ) := by exact_mod_cast (show n=2*r by omega) + rw [hn']; ring + +lemma q_dyadic_le_one (n : ℕ) : (q n:ℝ)*dyadic (K n)≤1 := by + have hh : (q n:ℝ)≤(2:ℝ)^(K n) := by + exact_mod_cast Nat.le_pow_clog (by norm_num : 1<2) (q n) + rw [dyadic,inv_pow,←div_eq_mul_inv] + exact (div_le_one (by positivity)).mpr hh + +lemma objective_compare (G : Input) (hn : 2≤ G.n) (heven : Even G.n) + {x : Pair G.n → ℝ} (hx : x∈(completeGraph G.n).polytope) : + objective G x≤ smoothObjective G x ∧ smoothObjective G x≤ objective G x+G.n := by + have he : smoothObjective G x-objective G x= + ∑ e,(phi (x e)-psiReal (K G.n) (x e)) := by + simp only [smoothObjective,objective,phi,entropy,sum_add_distrib,sum_sub_distrib,←sum_div] + ring + have hnon : 0≤∑ e,(phi (x e)-psiReal (K G.n) (x e)) := + sum_nonneg fun e _ => (dyadic_entropy_error (K G.n) ((completeGraph G.n).coordinate_mem_Icc hx e)).1 + have hupper : (∑ e,(phi (x e)-psiReal (K G.n) (x e)))≤(G.n:ℝ)/2+1 := by + calc + _ ≤ ∑ e,(x e+dyadic (K G.n)) := sum_le_sum fun e _ => + (dyadic_entropy_error (K G.n) ((completeGraph G.n).coordinate_mem_Icc hx e)).2 + _ = (G.n:ℝ)/2+(q G.n:ℝ)*dyadic (K G.n) := by + rw [sum_add_distrib,mass_half heven hx]; simp [q] + _ ≤ _ := by linarith [q_dyadic_le_one G.n] + have hn' : (2:ℝ)≤ G.n := by exact_mod_cast hn + constructor <;> linarith + +lemma Z_pos (G : Input) (hn : 4≤ G.n) (heven : Even G.n) : 0< Z G := by + have := complete_matching_nonempty hn heven + exact expSum_pos _ + +lemma smooth_lower_partition (G : Input) (hn : 4≤ G.n) (heven : Even G.n) + {x : Pair G.n → ℝ} (hx : x∈(completeGraph G.n).polytope) : + smoothObjective G x-4*(G.n:ℝ)≤ logZ G := by + have hPM := complete_matching_nonempty hn heven + obtain ⟨r,hr⟩ := heven + have hn' : Fintype.card (Fin G.n)=2*r := by simp; omega + have hent := ((completeGraph G.n).entropy_binary_scale hPM hn' hx).1 + have hvar := (completeGraph G.n).weighted_variational_le (fun e => (beta G e:ℝ)) hx + simp only [Fintype.card_fin] at hent + dsimp only [smoothObjective,logZ,Z] + linarith + +lemma smooth_upper_partition (G : Input) (hn : 4≤ G.n) (heven : Even G.n) : + ∃ x∈(completeGraph G.n).polytope,logZ G≤ smoothObjective G x+G.n := by + have hPM := complete_matching_nonempty hn heven + obtain ⟨x,hx,hvar⟩ := (completeGraph G.n).weighted_variational_attained (fun e => (beta G e:ℝ)) + obtain ⟨r,hr⟩ := heven + have hn' : Fintype.card (Fin G.n)=2*r := by simp; omega + have hent := ((completeGraph G.n).entropy_binary_scale hPM hn' hx).2 + simp only [Fintype.card_fin] at hent + refine ⟨x,hx,?_⟩ + dsimp only [smoothObjective,logZ,Z] + linarith + +theorem R_partition_bracket (G : Input) (hn : 4≤ G.n) (heven : Even G.n) : + (R G:ℝ)-4*(G.n:ℝ)≤ logZ G ∧ logZ G≤(R G:ℝ)+3*(G.n:ℝ) := by + obtain ⟨⟨y,hy,hylow⟩,hupp⟩ := R_objective_bracket G hn heven + constructor + · have hobj := (objective_compare G (by omega) heven hy).1 + have hpart := smooth_lower_partition G hn heven hy + linarith + · obtain ⟨x,hx,hpart⟩ := smooth_upper_partition G hn heven + have hobj := (objective_compare G (by omega) heven hx).2 + have hU := hupp x hx + have hn' : (4:ℝ)≤ G.n := by exact_mod_cast hn + linarith + +end +end BinaryMatching.Algorithm +end + +end OAI diff --git a/lean/OAI/Combinatorics/PerfectMatching/Ascent.lean b/lean/OAI/Combinatorics/PerfectMatching/Ascent.lean new file mode 100644 index 0000000000000000000000000000000000000000..ab37ad1c481528a78ea3220db24835bc444f51af --- /dev/null +++ b/lean/OAI/Combinatorics/PerfectMatching/Ascent.lean @@ -0,0 +1,209 @@ +import OAI.Combinatorics.PerfectMatching.ObjectivePenalty + +namespace OAI + +section + +namespace BinaryMatching.Algorithm +noncomputable section +open Finset MatchingEntropy + +lemma q_pos {n : ℕ} (hn : 2 ≤ n) : 0 < q n := by + apply Fintype.card_pos_iff.mpr + exact ⟨⟨(⟨0, by omega⟩, ⟨1, by omega⟩), by change 0 < 1; omega⟩⟩ + +lemma D₀_pos (G : Input) (hn : 2 ≤ G.n) : 0 < D₀ G := by + have hL : 0 < L G := by unfold L; positivity + exact Nat.mul_pos (q_pos hn) (pow_pos (by omega) _) + +lemma clip_sq_le {z : ℝ} (hz : z ∈ Set.Icc (0:ℝ) 1) (t : ℝ) : + (min 1 (max 0 t)-z)^2 ≤ (t-z)^2 := by + by_cases ht : t ≤ 0 + · rw [max_eq_left ht, min_eq_right (by norm_num : (0:ℝ) ≤ 1)] + nlinarith [mul_nonpos_of_nonpos_of_nonneg ht hz.1, sq_nonneg t] + · have ht0 : 0 ≤ t := le_of_not_ge ht + rw [max_eq_right ht0] + by_cases ht1 : 1 ≤ t + · rw [min_eq_left ht1] + nlinarith [mul_nonneg (sub_nonneg.mpr ht1) (show 0 ≤ t+1-2*z by linarith [hz.2])] + · rw [min_eq_right (le_of_not_ge ht1)] + +lemma update_box (G : Input) (a : Table G.n ℤ) (r : Affine G.n) (e : Pair G.n) : + entry (update G a r) e ∈ Set.Icc (0:ℤ) (D₀ G) := by + rw [update, at_toTable] + exact ⟨le_min (Int.natCast_nonneg _) (le_max_left _ _), min_le_left _ _⟩ + +lemma iterate_box (G : Input) (j : ℕ) (e : Pair G.n) : + entry (iterate G j).numerators e ∈ Set.Icc (0:ℤ) (D₀ G) := by + cases j with + | zero => simp [iterate, initial, at_tabulate] + | succ j => exact update_box G _ _ e + +def point (G : Input) (j : ℕ) (e : Pair G.n) : ℝ := + (coordinates (D₀ G) (iterate G j).numerators e : ℝ) + +def sampledValue (G : Input) (j : ℕ) : ℚ := + trialValue G (iterate G j).numerators (activeRow (D₀ G) (iterate G j).numerators) + +lemma coordinates_cast {n : ℕ} (D : ℕ) (a : Table n ℤ) (e : Pair n) : + (coordinates D a e : ℝ) = (↑(entry a e) : ℝ)/(D:ℝ) := by + simp [coordinates] + +lemma point_box (G : Input) (hn : 2 ≤ G.n) (j : ℕ) (e : Pair G.n) : + point G j e ∈ Set.Icc (0:ℝ) 1 := by + have hD : (0:ℝ) < D₀ G := by exact_mod_cast D₀_pos G hn + have ha := iterate_box G j e + have ha' : (↑(entry (iterate G j).numerators e) : ℝ) ∈ Set.Icc (0:ℝ) (D₀ G) := + ⟨by exact_mod_cast ha.1, by exact_mod_cast ha.2⟩ + rw [point, coordinates_cast] + exact ⟨div_nonneg ha'.1 hD.le, (div_le_one hD).mpr ha'.2⟩ + +lemma point_zero (G : Input) (e : Pair G.n) : point G 0 e=0 := by + simp [point, coordinates, iterate, initial, at_tabulate] + +lemma point_succ (G : Input) (hn : 2 ≤ G.n) (j : ℕ) (e : Pair G.n) : + point G (j+1) e = min 1 (max 0 (point G j e+ + (gradient G (iterate G j).numerators (activeRow (D₀ G) (iterate G j).numerators) e:ℝ)/(D₀ G:ℝ))) := by + have hD : (0:ℝ) < D₀ G := by exact_mod_cast D₀_pos G hn + simp only [point, iterate, step, coordinates_cast, update, at_toTable, + Int.cast_min, Int.cast_max, Int.cast_natCast, Int.cast_zero, Int.cast_add] + rw [← min_div_div_right hD.le, ← max_div_div_right hD.le] + rw [div_self hD.ne', zero_div, add_div] + +lemma sampledValue_correct (G : Input) (hn : 2 ≤ G.n) (heven : Even G.n) (j : ℕ) : + (sampledValue G j:ℝ)=penalized G (point G j) := + trialValue_correct G hn heven (D₀_pos G hn) _ (fun e => (iterate_box G j e).1) + +lemma best_spec (G : Input) (t : ℕ) : + ∃ v : ℚ, (iterate G (t+1)).best=some v ∧ + (∃ j < t+1, sampledValue G j=v) ∧ + ∀ j < t+1, sampledValue G j≤v := by + induction t with + | zero => + refine ⟨sampledValue G 0, rfl, ⟨0, by omega, rfl⟩, ?_⟩ + intro j hj + have : j=0 := by omega + subst j; rfl + | succ t ih => + obtain ⟨v, hv, ⟨i, hi, hiv⟩, hmax⟩ := ih + refine ⟨max (sampledValue G (t+1)) v, ?_, ?_, ?_⟩ + · change some ((iterate G (t+1)).best.elim (sampledValue G (t+1)) + (max (sampledValue G (t+1)))) = _ + rw [hv]; rfl + · by_cases h : v ≤ sampledValue G (t+1) + · exact ⟨t+1, by omega, (max_eq_left h).symm⟩ + · exact ⟨i, by omega, hiv.trans (max_eq_right (le_of_not_ge h)).symm⟩ + · intro j hj + by_cases h : j=t+1 + · subst j; exact le_max_left _ _ + · exact (hmax j (by omega)).trans (le_max_right _ _) + +def squareDistance {I : Type*} [Fintype I] (x z : I → ℝ) : ℝ := + ∑ e, (x e-z e)^2 + +lemma squareDistance_nonneg {I : Type*} [Fintype I] (x z : I → ℝ) : + 0 ≤ squareDistance x z := sum_nonneg fun _e _ => sq_nonneg _ + +lemma squareDistance_zero_bound (G : Input) (z : Pair G.n → ℝ) + (hz : ∀ e, z e∈Set.Icc (0:ℝ) 1) : squareDistance (point G 0) z ≤ q G.n := by + calc + _ ≤ ∑ _e : Pair G.n, (1:ℝ) := by + apply sum_le_sum; intro e _ + rw [point_zero]; nlinarith [(hz e).1, (hz e).2] + _ = _ := by simp [q] + +lemma distance_step (G : Input) (hn : 2 ≤ G.n) (heven : Even G.n) (j : ℕ) + (z : Pair G.n → ℝ) (hz : ∀ e,z e∈Set.Icc (0:ℝ) 1) : + 2*(penalized G z-penalized G (point G j)) ≤ + (D₀ G:ℝ)*(squareDistance (point G j) z-squareDistance (point G (j+1)) z)+1 := by + let x := point G j + let g := fun e => (gradient G (iterate G j).numerators + (activeRow (D₀ G) (iterate G j).numerators) e:ℝ) + let D : ℝ := D₀ G + have hD : 0 (iterate_box G j e).1) + have hg := gradient_supergradient G hn heven (D₀_pos G hn) (iterate G j).numerators + (fun e => (iterate_box G j e).1) z + have hsign : (∑ e,g e*(x e-z e)) = -(∑ e,g e*(z e-x e)) := by + rw [← sum_neg_distrib]; apply sum_congr rfl; intro e _; ring + change penalized G z ≤ penalized G x+∑ e,g e*(z e-x e) at hg + have hh := mul_le_mul_of_nonneg_left hs hD.le + rw [he, hsign] at hh + change 2*(penalized G z-penalized G x) ≤ D*(squareDistance x z-squareDistance (point G (j+1)) z)+1 + linarith + +lemma trial_max_bound (G : Input) (hn : 2 ≤ G.n) (heven : Even G.n) : + ∃ v : ℚ, (iterate G (q G.n*D₀ G)).best=some v ∧ + (∃ j < q G.n*D₀ G, sampledValue G j=v) ∧ + ∀ z : Pair G.n → ℝ, (∀ e,z e∈Set.Icc (0:ℝ) 1) → + penalized G z ≤ (v:ℝ)+1 := by + let T := q G.n*D₀ G + have hT : 0 distance_step G hn heven j z hz) + have hilower : (T:ℝ)*(2*(penalized G z-(v:ℝ))) ≤ + ∑ j∈range T,2*(penalized G z-penalized G (point G j)) := by + calc + _ = ∑ _j∈range T,2*(penalized G z-(v:ℝ)) := by simp + _ ≤ _ := by + apply sum_le_sum; intro j hj + have hjv : (sampledValue G j:ℝ)≤(v:ℝ) := by + exact_mod_cast hmax j (mem_range.mp hj) + rw [sampledValue_correct G hn heven] at hjv + linarith + have htel : (∑ j∈range T, ((D₀ G:ℝ)* + (squareDistance (point G j) z-squareDistance (point G (j+1)) z)+1)) = + (D₀ G:ℝ)*(squareDistance (point G 0) z-squareDistance (point G T) z)+T := by + rw [sum_add_distrib,←mul_sum,sum_range_sub'] + simp + rw [htel] at hsteps + have hend := squareDistance_nonneg (point G T) z + have hstart := squareDistance_zero_bound G z hz + have hD : (0:ℝ) norm_num + +omit [Fintype V] [Fintype E] [DecidableEq V] in +@[simp] theorem indicator_le_one (G : LooplessGraph V E) (M : G.Matching) (e : E) : + G.indicator M e ≤ 1 := by + simp only [indicator] + split <;> norm_num + +omit [Fintype V] [DecidableEq V] in +theorem continuous_mean (G : LooplessGraph V E) : Continuous G.mean := by + unfold mean + fun_prop + +def meanLinear (G : LooplessGraph V E) : (G.Matching → ℝ) →ₗ[ℝ] (E → ℝ) where + toFun := G.mean + map_add' p q := by + ext e + simp [mean, add_mul, Finset.sum_add_distrib] + map_smul' a p := by + ext e + simp [mean, mul_assoc, Finset.mul_sum] + +omit [Fintype V] [DecidableEq V] in +theorem mean_mem_polytope (G : LooplessGraph V E) {p : G.Matching → ℝ} + (hp : p ∈ probabilitySimplex G.Matching) : G.mean p ∈ G.polytope := by + have h := (convex_convexHull ℝ (Set.range G.indicator)).sum_mem + (fun M _ ↦ hp.1 M) hp.2 (fun M _ ↦ subset_convexHull ℝ _ (Set.mem_range_self M)) + have he : G.mean p = ∑ M, p M • G.indicator M := by + ext e + simp [mean] + rw [he] + exact h + +omit [Fintype V] [DecidableEq V] in +@[simp] theorem mean_single (G : LooplessGraph V E) (M : G.Matching) : + G.mean (Pi.single M 1) = G.indicator M := by + classical + ext e + simp [mean, Pi.single_apply, ite_mul] + +omit [Fintype V] [DecidableEq V] in +/-- Exact equivalence between the convex hull of matching indicators and feasible finite laws. -/ +theorem mem_polytope_iff (G : LooplessGraph V E) (y : E → ℝ) : + y ∈ G.polytope ↔ (G.feasibleLaws y).Nonempty := by + classical + constructor + · intro hy + have hc : Convex ℝ (G.mean '' probabilitySimplex G.Matching) := + (convex_probabilitySimplex G.Matching).linear_image G.meanLinear + have hs : Set.range G.indicator ⊆ G.mean '' probabilitySimplex G.Matching := by + rintro _ ⟨M, rfl⟩ + exact ⟨Pi.single M 1, single_mem_probabilitySimplex M, G.mean_single M⟩ + obtain ⟨p, hp, rfl⟩ := convexHull_min hs hc hy + exact ⟨p, hp, rfl⟩ + · rintro ⟨p, hp, rfl⟩ + exact G.mean_mem_polytope hp + +omit [Fintype V] [DecidableEq V] in +theorem compact_feasibleLaws (G : LooplessGraph V E) (y : E → ℝ) : + IsCompact (G.feasibleLaws y) := by + exact (isCompact_probabilitySimplex G.Matching).inter_right + (isClosed_eq G.continuous_mean continuous_const) + +omit [Fintype V] [DecidableEq V] in +theorem compact_polytope (G : LooplessGraph V E) : IsCompact G.polytope := by + have heq : G.polytope = G.mean '' probabilitySimplex G.Matching := by + ext y + rw [G.mem_polytope_iff] + rfl + rw [heq] + exact (isCompact_probabilitySimplex G.Matching).image G.continuous_mean + + +end LooplessGraph + +end MatchingEntropy + +end + +end OAI diff --git a/lean/OAI/Combinatorics/PerfectMatching/Calculus.lean b/lean/OAI/Combinatorics/PerfectMatching/Calculus.lean new file mode 100644 index 0000000000000000000000000000000000000000..e1e6e404b4e37ea58821b46bd831dfd3242df818 --- /dev/null +++ b/lean/OAI/Combinatorics/PerfectMatching/Calculus.lean @@ -0,0 +1,253 @@ +import OAI.Combinatorics.PerfectMatching.Duality + +namespace OAI + +/-! +Derivatives of entropy and log-partition, and the nonlinear entropy barrier. +-/ + +noncomputable section + +open scoped BigOperators Topology +open Filter + +namespace MatchingEntropy + +/-- First derivative of a finite exponential partition function. -/ +theorem partition_hasDerivAt {ι : Type*} [Fintype ι] (p a : ι → ℝ) (t : ℝ) : + HasDerivAt (partition p a) (partition (fun i => p i*a i) a t) t := by + apply HasDerivAt.fun_sum + intro i _ + simpa only [one_mul, id_eq, mul_assoc, mul_comm, mul_left_comm] using + (((hasDerivAt_id t).mul_const (a i)).exp.const_mul (p i)) + +/-- The logarithmic partition derivative, with no infinite optimization +or interchange of limits: only finite sums. -/ +theorem logPartition_hasDerivAt {ι : Type*} [Fintype ι] {p : ι → ℝ} + (hp : p ∈ probabilitySimplex ι) (a : ι → ℝ) (t : ℝ) : + HasDerivAt (fun t => Real.log (partition p a t)) + (partition (fun i => p i*a i) a t / partition p a t) t := + (partition_hasDerivAt p a t).log (partition_pos hp a t).ne' + +/-- The second derivative of log-partition at the base law is variance. -/ +theorem logPartition_second {ι : Type*} [Fintype ι] {p : ι → ℝ} + (hp : p ∈ probabilitySimplex ι) (a : ι → ℝ) : + HasDerivAt (fun t => partition (fun i => p i*a i) a t / partition p a t) + ((∑ i, p i*(a i)^2) - (∑ i, p i*a i)^2) 0 := by + have hd := (partition_hasDerivAt (fun i => p i*a i) a 0).div + (partition_hasDerivAt p a 0) (partition_pos hp a 0).ne' + refine hd.congr_deriv ?_ + simp only [partition, zero_mul, Real.exp_zero, mul_one, hp.2, one_pow, div_one] + congr 1 + · apply Finset.sum_congr rfl + intro i _ + ring + · ring + +/-- The explicit first derivative along a supported affine marginal path. -/ +def entropyLineD {ι : Type*} [Fintype ι] (x v : ι → ℝ) (t : ℝ) : ℝ := + -∑ i, v i * Real.log (x i+t*v i) - ∑ i, v i + +theorem entropy_line_hasDerivAt_at {ι : Type*} [Fintype ι] (x v : ι → ℝ) + (t : ℝ) (h : ∀ i, x i+t*v i ≠ 0 ∨ v i = 0) : + HasDerivAt (fun t : ℝ => entropy (fun i => x i+t*v i)) (entropyLineD x v t) t := by + have hd : ∀ i, HasDerivAt (fun t : ℝ => Real.negMulLog (x i+t*v i)) + ((-Real.log (x i+t*v i)-1)*v i) t := by + intro i + rcases h i with hi | hi + · simpa only [one_mul, Function.comp_def, id_eq] using + (Real.hasDerivAt_negMulLog hi).comp t + (((hasDerivAt_id t).mul_const (v i)).const_add (x i)) + · simpa only [hi, mul_zero, add_zero] using (hasDerivAt_const t (Real.negMulLog (x i))) + have he : (∑ i, (-Real.log (x i+t*v i)-1)*v i) = entropyLineD x v t := by + simp_rw [sub_mul, one_mul, neg_mul, mul_comm (Real.log (x _+t*v _))] + rw [Finset.sum_sub_distrib, Finset.sum_neg_distrib] + rfl + rw [← he] + simpa only [entropy, Finset.sum_apply] using + (HasDerivAt.fun_sum (u := Finset.univ) (fun i _ => hd i)) + +theorem entropy_line_deriv_eventually {ι : Type*} [Fintype ι] (x v : ι → ℝ) + (hsupp : ∀ i, x i = 0 → v i = 0) : + deriv (fun t : ℝ => entropy (fun i => x i+t*v i)) =ᶠ[𝓝 0] entropyLineD x v := by + have hh : ∀ᶠ t : ℝ in 𝓝 0, ∀ i, x i+t*v i ≠ 0 ∨ v i = 0 := by + apply Filter.eventually_all.mpr + intro i + by_cases hi : x i = 0 + · exact Filter.Eventually.of_forall (fun t => Or.inr (hsupp i hi)) + · have hc : ContinuousAt (fun t : ℝ => x i+t*v i) 0 := by fun_prop + have hn := hc.eventually_ne (show x i+(0:ℝ)*v i ≠ 0 by simpa using hi) + exact hn.mono (fun t ht => Or.inl ht) + filter_upwards [hh] with t ht + exact (entropy_line_hasDerivAt_at x v t ht).deriv + +theorem entropyLineD_hasDerivAt {ι : Type*} [Fintype ι] (x v : ι → ℝ) + (hsupp : ∀ i, x i = 0 → v i = 0) : + HasDerivAt (entropyLineD x v) (-∑ i, (v i)^2/x i) 0 := by + have hd : ∀ i, HasDerivAt (fun t : ℝ => v i*Real.log (x i+t*v i)) + ((v i)^2/x i) 0 := by + intro i + by_cases hi : x i = 0 + · simpa only [hi, hsupp i hi, zero_mul, zero_pow (by omega : 2 ≠ 0), zero_div] using + (hasDerivAt_const (0:ℝ) (0:ℝ)) + · have hh := ((((hasDerivAt_id (0:ℝ)).mul_const (v i)).const_add (x i)).log + (by simpa using hi)).const_mul (v i) + simpa only [id_eq, one_mul, zero_mul, add_zero, pow_two, mul_div_assoc] using hh + change HasDerivAt (fun t : ℝ => -(∑ i, v i*Real.log (x i+t*v i)) - ∑ i, v i) + (-∑ i, (v i)^2/x i) 0 + exact (HasDerivAt.fun_sum (u := Finset.univ) (fun i _ => hd i)).neg.sub_const (∑ i, v i) + +theorem entropy_line_second {ι : Type*} [Fintype ι] (x v : ι → ℝ) + (hsupp : ∀ i, x i = 0 → v i = 0) : + HasDerivAt (deriv (fun t : ℝ => entropy (fun i => x i+t*v i))) + (-∑ i, (v i)^2/x i) 0 := + (entropyLineD_hasDerivAt x v hsupp).congr_of_eventuallyEq + (entropy_line_deriv_eventually x v hsupp) + +def entropyBarrier (m h : ℝ) : ℝ := h-8*m*(1-Real.exp (-h/m)) +def entropyBarrierD (m h : ℝ) : ℝ := 1-8*Real.exp (-h/m) + +theorem entropyBarrier_hasDerivAt {m : ℝ} (hm : m ≠ 0) (h : ℝ) : + HasDerivAt (entropyBarrier m) (entropyBarrierD m h) h := by + have he := (((hasDerivAt_id h).neg.div_const m).exp.const_sub 1).const_mul (8*m) + have hd := (hasDerivAt_id h).sub he + refine hd.congr_deriv ?_ + dsimp [entropyBarrierD] + field_simp + +theorem entropyBarrierD_hasDerivAt (m h : ℝ) : + HasDerivAt (entropyBarrierD m) (8*Real.exp (-h/m)/m) h := by + have hd := (((hasDerivAt_id h).neg.div_const m).exp.const_mul 8).const_sub 1 + refine hd.congr_deriv ?_ + dsimp + ring + +/-- Second derivative of the scalar barrier composed with any twice +explicitly differentiable path. -/ +theorem barrier_second_path {m : ℝ} (hm : m ≠ 0) {f fD : ℝ → ℝ} {fDD : ℝ} + (hf : ∀ᶠ t in 𝓝 (0:ℝ), HasDerivAt f (fD t) t) + (hDD : HasDerivAt fD fDD 0) : + HasDerivAt (deriv (fun t => entropyBarrier m (f t))) + (entropyBarrierD m (f 0)*fDD + + (8*Real.exp (-f 0/m)/m)*(fD 0)^2) 0 := by + have h0 : HasDerivAt f (fD 0) 0 := hf.self_of_nhds + have he : deriv (fun t => entropyBarrier m (f t)) =ᶠ[𝓝 (0:ℝ)] + (fun t => entropyBarrierD m (f t)*fD t) := by + filter_upwards [hf] with t ht + exact ((entropyBarrier_hasDerivAt hm (f t)).comp t ht).deriv + have hd := ((entropyBarrierD_hasDerivAt m (f 0)).comp 0 h0).mul hDD + have hd' : HasDerivAt (fun t => entropyBarrierD m (f t)*fD t) + (entropyBarrierD m (f 0)*fDD + + (8*Real.exp (-f 0/m)/m)*(fD 0)^2) 0 := by + refine hd.congr_deriv ?_ + dsimp only [Function.comp_apply] + ring + exact hd'.congr_of_eventuallyEq he + + + +/-- A direct second-derivative calculation for the affine-law comparison +path used below. -/ +theorem second_deriv_quadratic_adjustment {f fD g gD : ℝ → ℝ} {fDD gDD c₀ c₁ v : ℝ} + (hf : ∀ᶠ t in 𝓝 (0:ℝ), HasDerivAt f (fD t) t) + (hg : ∀ᶠ t in 𝓝 (0:ℝ), HasDerivAt g (gD t) t) + (hfD : HasDerivAt fD fDD 0) (hgD : HasDerivAt gD gDD 0) : + HasDerivAt (deriv (fun t => f t+c₀+t*c₁+t^2*v-g t)) + (fDD+2*v-gDD) 0 := by + have hfirst : deriv (fun t => f t+c₀+t*c₁+t^2*v-g t) =ᶠ[𝓝 (0:ℝ)] + (fun t => fD t+c₁+2*t*v-gD t) := by + filter_upwards [hf, hg] with t hft hgt + have hd := (((hft.add_const c₀).fun_add ((hasDerivAt_id t).mul_const c₁)).fun_add + (((hasDerivAt_id t).fun_pow 2).mul_const v)).fun_sub hgt + simpa only [Pi.add_apply, Pi.sub_apply, Pi.pow_apply, id_eq, one_mul, + Nat.cast_ofNat, Nat.reduceSub, pow_one, mul_one] using hd.deriv + have hd := ((hfD.add_const c₁).fun_add + (((hasDerivAt_id (0:ℝ)).const_mul 2).mul_const v)).fun_sub hgD + have hd' : HasDerivAt (fun t => fD t+c₁+2*t*v-gD t) (fDD+2*v-gDD) 0 := by + simpa only [Pi.add_apply, Pi.sub_apply, id_eq, mul_one] using hd + exact hd'.congr_of_eventuallyEq hfirst + + +/-- The necessary one-dimensional second-derivative test, also when the +second derivative is defined by Lean's totalized derivative. -/ +theorem second_deriv_nonpos_of_local_max {f : ℝ → ℝ} {x : ℝ} + (hm : IsLocalMax f x) (hc : ContinuousAt f x) : deriv (deriv f) x ≤ 0 := by + by_contra h + have hp : 0 < deriv (deriv f) x := lt_of_not_ge h + have hmin := isLocalMin_of_deriv_deriv_pos hp hm.deriv_eq_zero hc + have he : f =ᶠ[𝓝 x] (fun _ => f x) := by + filter_upwards [hm, hmin] with y h₁ h₂ + exact le_antisymm h₁ h₂ + have hh := he.deriv.deriv_eq + simp only [deriv_const', deriv_const] at hh + linarith + + +/-- All first derivatives on a neighborhood, including boundary coordinates +whose admissible direction is zero. -/ +theorem entropy_line_eventually_hasDerivAt {ι : Type*} [Fintype ι] (x v : ι → ℝ) + (hsupp : ∀ i, x i = 0 → v i = 0) : + ∀ᶠ t : ℝ in 𝓝 0, + HasDerivAt (fun t : ℝ => entropy (fun i => x i+t*v i)) (entropyLineD x v t) t := by + have hh : ∀ᶠ t : ℝ in 𝓝 0, ∀ i, x i+t*v i ≠ 0 ∨ v i = 0 := by + apply Filter.eventually_all.mpr + intro i + by_cases hi : x i = 0 + · exact Filter.Eventually.of_forall (fun t => Or.inr (hsupp i hi)) + · have hc : ContinuousAt (fun t : ℝ => x i+t*v i) 0 := by fun_prop + have hn := hc.eventually_ne (show x i+(0:ℝ)*v i ≠ 0 by simpa using hi) + exact hn.mono (fun t ht => Or.inl ht) + exact hh.mono (fun t ht => entropy_line_hasDerivAt_at x v t ht) + +theorem entropy_barrier_line_second {ι : Type*} [Fintype ι] + (x v : ι → ℝ) (hsupp : ∀ i, x i = 0 → v i = 0) {m : ℝ} (_hm : m ≠ 0) : + HasDerivAt (fun t => entropyBarrierD m (entropy (fun i => x i+t*v i))*entropyLineD x v t) + ((8*Real.exp (-entropy x/m)-1)*(∑ i, (v i)^2/x i) + + (8*Real.exp (-entropy x/m)/m)*(entropyLineD x v 0)^2) 0 := by + have h0 := (entropy_line_eventually_hasDerivAt x v hsupp).self_of_nhds + have hd := ((entropyBarrierD_hasDerivAt m (entropy (fun i => x i+(0:ℝ)*v i))).comp 0 h0).mul + (entropyLineD_hasDerivAt x v hsupp) + refine hd.congr_deriv ?_ + simp only [Function.comp_apply, zero_mul, add_zero, entropyBarrierD] + ring + +/-- The exact second variation along affine laws, proved solely by ordinary +one-variable derivatives and the finite log-partition variance identity. -/ +theorem entropy_second_variation {ι κ : Type*} [Fintype ι] [Fintype κ] + (x v : ι → ℝ) (hsupp : ∀ i, x i = 0 → v i = 0) + {p : κ → ℝ} (hp : p ∈ probabilitySimplex κ) (a : κ → ℝ) + (hcenter : ∑ i, p i*a i = 0) {m : ℝ} (hm : m ≠ 0) (c₀ c₁ : ℝ) + (hlocal : IsLocalMax (fun t => entropyBarrier m (entropy (fun i => x i+t*v i)) + + c₀+t*c₁+t^2*(∑ i, p i*(a i)^2)-Real.log (partition p a t)) 0) : + (8*Real.exp (-entropy x/m)-1)*(∑ i, (v i)^2/x i) + + (8*Real.exp (-entropy x/m)/m)*(entropyLineD x v 0)^2 + + (∑ i, p i*(a i)^2) ≤ 0 := by + have hf : ∀ᶠ t : ℝ in 𝓝 0, HasDerivAt + (fun t => entropyBarrier m (entropy (fun i => x i+t*v i))) + (entropyBarrierD m (entropy (fun i => x i+t*v i))*entropyLineD x v t) t := by + filter_upwards [entropy_line_eventually_hasDerivAt x v hsupp] with t ht + exact (entropyBarrier_hasDerivAt hm _).comp t ht + have hg : ∀ᶠ t : ℝ in 𝓝 0, HasDerivAt (fun t => Real.log (partition p a t)) + (partition (fun i => p i*a i) a t / partition p a t) t := + Filter.Eventually.of_forall (logPartition_hasDerivAt hp a) + have hd := second_deriv_quadratic_adjustment (c₀ := c₀) (c₁ := c₁) + (v := ∑ i, p i*(a i)^2) hf hg (entropy_barrier_line_second x v hsupp hm) + (logPartition_second hp a) + have hc : ContinuousAt (fun t => entropyBarrier m (entropy (fun i => x i+t*v i)) + + c₀+t*c₁+t^2*(∑ i, p i*(a i)^2)-Real.log (partition p a t)) 0 := by + apply ContinuousAt.sub + · apply ContinuousAt.add + · apply ContinuousAt.add + · exact hf.self_of_nhds.continuousAt.add_const c₀ + · fun_prop + · fun_prop + · exact hg.self_of_nhds.continuousAt + have hh := second_deriv_nonpos_of_local_max hlocal hc + rw [hd.deriv, hcenter] at hh + nlinarith + +end MatchingEntropy + +end + +end OAI diff --git a/lean/OAI/Combinatorics/PerfectMatching/CompletePairs.lean b/lean/OAI/Combinatorics/PerfectMatching/CompletePairs.lean new file mode 100644 index 0000000000000000000000000000000000000000..4cc0cc7423a8310860f0166dde7a253d5caee4ed --- /dev/null +++ b/lean/OAI/Combinatorics/PerfectMatching/CompletePairs.lean @@ -0,0 +1,122 @@ +import OAI.Combinatorics.PerfectMatching.DyadicEntropy + +namespace OAI + +section + +namespace BinaryMatching +noncomputable section +open Finset +variable {n : ℕ} + +lemma sum_pairs (f : Fin n → Fin n → ℝ) : + (∑ e : Pair n, f e.val.1 e.val.2)=∑ i,∑ j,if i < j then f i j else 0 := by + let s : Finset (Fin n × Fin n) := univ.filter (fun ij => ij.1 < ij.2) + have hs : ∀ ij : Fin n × Fin n,ij∈s ↔ ij.1 < ij.2 := by simp [s] + rw [←sum_subtype s hs (fun ij => f ij.1 ij.2)] + rw [show s=univ.filter (fun ij => ij.1 < ij.2) from rfl,sum_filter,Fintype.sum_prod_type] + +lemma sum_skip (g : Fin n → ℝ) (v : Fin n) : + (∑ j,if j=v then 0 else g j)=(∑ j,g j)-g v := by + have hh : (∑ j,g j)=(∑ j,if j=v then 0 else g j)+g v := by + calc + _ = ∑ j, ((if j=v then 0 else g j)+(if j=v then g j else 0)) := by + apply sum_congr rfl; intro j _; split_ifs <;> simp + _ = _ := by rw [sum_add_distrib]; simp + linarith + +lemma degree_from_symm (f : Fin n → Fin n → ℝ) (hf : ∀ i j,f i j=f j i) (v : Fin n) : + (completeGraph n).degree (fun e => f e.val.1 e.val.2) v = + ∑ j,if j=v then 0 else f v j := by + change (∑ e : Pair n,if e.val.1=v ∨ e.val.2=v then f e.val.1 e.val.2 else 0)=_ + rw [sum_pairs (fun i j => if i=v ∨ j=v then f i j else 0)] + have he (i j : Fin n) : + (if i < j then (if i=v ∨ j=v then f i j else 0) else 0) = + (if i=v then (if i < j then f i j else 0) else 0)+ + (if j=v then (if i < j then f i j else 0) else 0) := by + by_cases hiv : i=v <;> by_cases hjv : j=v <;> by_cases hij : i < j <;> simp_all + simp_rw [he,sum_add_distrib] + have hleft : (∑ i,∑ j,if i=v then (if i < j then f i j else 0) else 0)= + ∑ j,if v < j then f v j else 0 := by + simp [Finset.sum_ite_irrel] + have hright : (∑ i,∑ j,if j=v then (if i < j then f i j else 0) else 0)= + ∑ j,if j < v then f v j else 0 := by + simp only [sum_ite_eq',mem_univ,ite_true] + apply sum_congr rfl; intro j _; rw [hf j v] + rw [hleft,hright,←sum_add_distrib] + apply sum_congr rfl; intro j _ + rcases lt_trichotomy j v with h|h|h + · simp [h, ne_of_lt h, not_lt_of_ge h.le] + · subst j; simp + · simp [h, ne_of_gt h, not_lt_of_ge h.le] + +lemma degree_constant (b : ℝ) (v : Fin n) : + (completeGraph n).degree (fun _ => b) v=((n:ℝ)-1)*b := by + rw [degree_from_symm (fun _ _ => b) (fun _ _ => rfl),sum_skip] + simp; ring + +lemma degree_vertex_add (d : Fin n → ℝ) (v : Fin n) : + (completeGraph n).degree (fun e => d e.val.1+d e.val.2) v = + ((n:ℝ)-2)*d v+∑ j,d j := by + rw [degree_from_symm (fun i j => d i+d j) (fun _ _ => add_comm _ _),sum_skip] + simp only [sum_add_distrib,sum_const,nsmul_eq_mul,card_univ,Fintype.card_fin] + ring + +lemma cut_from_symm (f : Fin n → Fin n → ℝ) (hf : ∀ i j,f i j=f j i) + (S : Finset (Fin n)) : + (completeGraph n).cutMass (fun e => f e.val.1 e.val.2) S = + ∑ i∈S,∑ j∈Sᶜ,f i j := by + unfold MatchingEntropy.LooplessGraph.cutMass MatchingEntropy.LooplessGraph.cut + rw [sum_filter] + change (∑ e : Pair n,if (e.val.1∈S ∧ e.val.2∉S) ∨ (e.val.1∉S ∧ e.val.2∈S) + then f e.val.1 e.val.2 else 0)=_ + rw [sum_pairs (fun i j => if (i∈S ∧ j∉S) ∨ (i∉S ∧ j∈S) then f i j else 0)] + have he (i j : Fin n) : + (if i < j then (if (i∈S ∧ j∉S) ∨ (i∉S ∧ j∈S) then f i j else 0) else 0) = + (if i < j ∧ i∈S ∧ j∉S then f i j else 0)+ + (if i < j ∧ i∉S ∧ j∈S then f i j else 0) := by + by_cases hij : i < j <;> by_cases hi : i∈S <;> by_cases hj : j∈S <;> simp [hij,hi,hj] + simp_rw [he,sum_add_distrib] + have hswap : (∑ i,∑ j,if i < j ∧ i∉S ∧ j∈S then f i j else 0)= + ∑ i,∑ j,if j < i ∧ i∈S ∧ j∉S then f i j else 0 := by + rw [sum_comm] + apply sum_congr rfl; intro i _ + apply sum_congr rfl; intro j _ + rw [hf j i] + by_cases hij : j < i <;> by_cases hi : i∈S <;> by_cases hj : j∈S <;> simp [hij,hi,hj] + rw [hswap,←sum_add_distrib] + simp_rw [←sum_add_distrib] + have hterm (i j : Fin n) : + (if i < j ∧ i∈S ∧ j∉S then f i j else 0)+ + (if j < i ∧ i∈S ∧ j∉S then f i j else 0)= + if i∈S ∧ j∉S then f i j else 0 := by + rcases lt_trichotomy i j with h|h|h + · simp [h,not_lt_of_ge h.le] + · subst j; simp + · simp [h,not_lt_of_ge h.le] + simp_rw [hterm] + have hS : S=univ.filter (fun i => i∈S) := by ext i; simp + have hSc : Sᶜ=univ.filter (fun j => j∉S) := by ext j; simp + conv_rhs => rw [hS]; rw [sum_filter] + simp only [ite_and] + apply sum_congr rfl; intro i _ + by_cases hi : i∈S + · simp only [hi,ite_true] + rw [←hS,hSc,sum_filter] + · simp only [hi,ite_false,sum_const_zero] + +lemma cut_constant (b : ℝ) (S : Finset (Fin n)) : + (completeGraph n).cutMass (fun _ => b) S=(S.card:ℝ)*(Sᶜ.card:ℝ)*b := by + rw [cut_from_symm (fun _ _ => b) (fun _ _ => rfl)] + simp [mul_assoc] + +lemma q_le_square : Fintype.card (Pair n) ≤ n^2 := by + calc + _ ≤ Fintype.card (Fin n × Fin n) := Fintype.card_subtype_le _ + _ = n^2 := by simp [pow_two] + +end +end BinaryMatching +end + +end OAI diff --git a/lean/OAI/Combinatorics/PerfectMatching/Completion.lean b/lean/OAI/Combinatorics/PerfectMatching/Completion.lean new file mode 100644 index 0000000000000000000000000000000000000000..5d8526ac465952bbffa2c02d388271e8478f501e --- /dev/null +++ b/lean/OAI/Combinatorics/PerfectMatching/Completion.lean @@ -0,0 +1,257 @@ +import OAI.Combinatorics.PerfectMatching.AlgorithmPartition + +namespace OAI + +section + +namespace BinaryMatching.Algorithm +noncomputable section +open Finset MatchingEntropy + +def edgeWeight (G : Input) (e : Pair G.n) : ℝ := Real.exp (Real.log 2*(beta G e:ℝ)) +def matchingWeight (G : Input) (M : (completeGraph G.n).Matching) : ℝ := + ∏ e∈M.val,edgeWeight G e + +def validMatching (G : Input) (M : (completeGraph G.n).Matching) : Prop := + ∀ e∈M.val,0< multiplicity G e + +def goodWeight (G : Input) (M : (completeGraph G.n).Matching) : ℝ := + @ite ℝ (validMatching G M) (Classical.propDecidable _) (matchingWeight G M) 0 + +def badWeight (G : Input) (M : (completeGraph G.n).Matching) : ℝ := + @ite ℝ (validMatching G M) (Classical.propDecidable _) 0 (matchingWeight G M) + +def Zgood (G : Input) : ℝ := ∑ M,goodWeight G M +def Zbad (G : Input) : ℝ := ∑ M,badWeight G M + +def multProduct (G : Input) (M : (completeGraph G.n).Matching) : ℕ := + ∏ e∈M.val,multiplicity G e + +lemma matchingWeight_exp (G : Input) (M : (completeGraph G.n).Matching) : + matchingWeight G M=Real.exp (Real.log 2*((completeGraph G.n).score (fun e => (beta G e:ℝ)) M)) := by + rw [LooplessGraph.score,mul_sum,Real.exp_sum] + rfl + +lemma matchingWeight_pos (G : Input) (M : (completeGraph G.n).Matching) : 0< matchingWeight G M := by + rw [matchingWeight_exp]; exact Real.exp_pos _ + +lemma Z_decompose (G : Input) : Z G=Zgood G+Zbad G := by + unfold Z LooplessGraph.weightedZ expSum Zgood Zbad + rw [←sum_add_distrib] + apply sum_congr rfl; intro M _ + rw [←matchingWeight_exp] + unfold goodWeight badWeight + split_ifs <;> simp + +lemma goodWeight_nonneg (G : Input) (M : (completeGraph G.n).Matching) : 0≤ goodWeight G M := by + unfold goodWeight; split_ifs + · exact (matchingWeight_pos G M).le + · rfl + +lemma badWeight_nonneg (G : Input) (M : (completeGraph G.n).Matching) : 0≤ badWeight G M := by + unfold badWeight; split_ifs + · rfl + · exact (matchingWeight_pos G M).le + +lemma Zgood_nonneg (G : Input) : 0≤ Zgood G := sum_nonneg fun M _ => goodWeight_nonneg G M +lemma Zbad_nonneg (G : Input) : 0≤ Zbad G := sum_nonneg fun M _ => badWeight_nonneg G M + +lemma edgeWeight_present (G : Input) (e : Pair G.n) (he : 0< multiplicity G e) : + edgeWeight G e=(2:ℝ)^Nat.log2 (multiplicity G e) := by + rw [edgeWeight,beta,ite_eq_right (by omega),Int.cast_natCast,mul_comm,Real.exp_nat_mul] + rw [Real.exp_log (by norm_num : (0:ℝ)<2)] + +lemma edgeWeight_rounding (G : Input) (e : Pair G.n) (he : 0< multiplicity G e) : + (multiplicity G e:ℝ)/2≤ edgeWeight G e ∧ edgeWeight G e≤(multiplicity G e:ℝ) := by + rw [edgeWeight_present G e he] + have hlo := Nat.log2_self_le (show multiplicity G e≠0 by omega) + have hhi : multiplicity G e<2^(Nat.log2 (multiplicity G e)+1) := Nat.lt_log2_self + have hlo' : (2:ℝ)^Nat.log2 (multiplicity G e)≤(multiplicity G e:ℝ) := by exact_mod_cast hlo + have hhi' : (multiplicity G e:ℝ)<(2:ℝ)^(Nat.log2 (multiplicity G e)+1) := by exact_mod_cast hhi + rw [pow_succ] at hhi' + constructor <;> linarith + +lemma invalid_product_zero (G : Input) (M : (completeGraph G.n).Matching) + (hM : ¬validMatching G M) : multProduct G M=0 := by + classical + unfold validMatching at hM + push Not at hM + obtain ⟨e,he,hzero⟩ := hM + unfold multProduct + exact prod_eq_zero he (by omega) + +lemma goodWeight_le_product (G : Input) (M : (completeGraph G.n).Matching) : + goodWeight G M≤(multProduct G M:ℝ) := by + unfold goodWeight + split_ifs with hM + · unfold matchingWeight multProduct + push_cast + exact prod_le_prod₀ (fun e _ => (Real.exp_pos _).le) + (fun e he => (edgeWeight_rounding G e (hM e he)).2) + · positivity + +lemma goodWeight_ge_product (G : Input) (M : (completeGraph G.n).Matching) : + (2:ℝ)⁻¹^M.val.card*(multProduct G M:ℝ)≤ goodWeight G M := by + unfold goodWeight + split_ifs with hM + · calc + _ = ∏ e∈M.val,((multiplicity G e:ℝ)/2) := by + simp only [div_eq_mul_inv,prod_mul_distrib,prod_const,multProduct,Nat.cast_prod] + ring + _ ≤ _ := prod_le_prod₀ (fun e _ => by positivity) + (fun e he => (edgeWeight_rounding G e (hM e he)).1) + · rw [invalid_product_zero G M hM,Nat.cast_zero,mul_zero] + +lemma Zgood_bracket (G : Input) {r : ℕ} (hn : G.n=2*r) : + (2:ℝ)⁻¹^r*(count G:ℝ)≤ Zgood G ∧ Zgood G≤(count G:ℝ) := by + have hc (M : (completeGraph G.n).Matching) : M.val.card=r := + (completeGraph G.n).matching_card (by simpa) M + have hncast : (count G:ℝ)=∑ M,(multProduct G M:ℝ) := by simp [count,multProduct] + rw [hncast] + constructor + · rw [mul_sum] + exact sum_le_sum fun M _ => by simpa only [hc M] using goodWeight_ge_product G M + · exact sum_le_sum fun M _ => goodWeight_le_product G M + +lemma positive_count_valid (G : Input) (hN : 0< count G) : + ∃ M : (completeGraph G.n).Matching, validMatching G M := by + have hsum : 0<∑ M,multProduct G M := hN + obtain ⟨M,_hM,hprod⟩ := (sum_pos_iff_of_nonneg (fun M _ => Nat.zero_le (multProduct G M))).mp hsum + refine ⟨M,?_⟩ + by_contra h + rw [invalid_product_zero G M h] at hprod + omega + +lemma validWeight_ge_one (G : Input) (M : (completeGraph G.n).Matching) + (hM : validMatching G M) : 1≤ goodWeight G M := by + rw [goodWeight,ite_eq_left hM] + apply one_le_prod₀ + intro e he + rw [edgeWeight_present G e (hM e he)] + exact one_le_pow₀ (by norm_num) + +lemma Zgood_ge_one (G : Input) (hN : 0< count G) : 1≤ Zgood G := by + obtain ⟨M,hM⟩ := positive_count_valid G hN + exact (validWeight_ge_one G M hM).trans + (single_le_sum (fun N _ => goodWeight_nonneg G N) (mem_univ M)) + +lemma beta_le_B (G : Input) (e : Pair G.n) : (beta G e:ℝ)≤(B G:ℝ) := by + unfold beta + split_ifs + · simp only [Int.cast_neg,Int.cast_natCast] + have : (0:ℝ)≤ B G := by positivity + have : (0:ℝ)≤ L G := by positivity + linarith + · exact_mod_cast multiplicity_log_le_B G e + +lemma matching_card_bound (n : ℕ) : Fintype.card (completeGraph n).Matching≤2^(q n) := by + calc + _ ≤ Fintype.card (Finset (Pair n)) := + Fintype.card_le_of_injective (fun M => M.val) Subtype.val_injective + _ = _ := by rw [Fintype.card_finset]; rfl + +lemma badWeight_bound (G : Input) {r : ℕ} (hn : G.n=2*r) + (M : (completeGraph G.n).Matching) : + badWeight G M≤ Real.exp (Real.log 2*((B G:ℝ)*r-L G)) := by + classical + unfold badWeight + split_ifs with hM + · exact (Real.exp_pos _).le + · have hbad := hM + unfold validMatching at hbad + push Not at hbad + obtain ⟨e,he,hzero⟩ := hbad + have hz : multiplicity G e=0 := by omega + have hbe : (beta G e:ℝ)=-(L G:ℝ) := by simp [beta,hz] + have hc : M.val.card=r := (completeGraph G.n).matching_card (by simpa) M + have hsingle := single_le_sum (s := M.val) (f := fun e => (B G:ℝ)-(beta G e:ℝ)) + (fun e _ => sub_nonneg.mpr (beta_le_B G e)) he + rw [hbe,sum_sub_distrib,sum_const,hc,nsmul_eq_mul] at hsingle + have hB : (0:ℝ)≤ B G := by positivity + have hsum : (∑ e∈M.val,(beta G e:ℝ))≤(B G:ℝ)*r-L G := by nlinarith + rw [matchingWeight_exp] + apply Real.exp_le_exp.mpr + exact mul_le_mul_of_nonneg_left hsum log_two_pos.le + +lemma Zbad_bound (G : Input) {r : ℕ} (hn : G.n=2*r) : + Zbad G≤ Real.exp (Real.log 2*((q G.n:ℝ)+(B G:ℝ)*r-L G)) := by + calc + _ ≤ ∑ _M : (completeGraph G.n).Matching, Real.exp (Real.log 2*((B G:ℝ)*r-L G)) := + sum_le_sum fun M _ => badWeight_bound G hn M + _ = (Fintype.card (completeGraph G.n).Matching:ℝ)*Real.exp (Real.log 2*((B G:ℝ)*r-L G)) := by simp + _ ≤ (2:ℝ)^(q G.n)*Real.exp (Real.log 2*((B G:ℝ)*r-L G)) := by + apply mul_le_mul_of_nonneg_right _ (Real.exp_pos _).le + exact_mod_cast matching_card_bound G.n + _ = _ := by + have he : (2:ℝ)^(q G.n)=Real.exp ((q G.n:ℝ)*Real.log 2) := by + rw [Real.exp_nat_mul,Real.exp_log (by norm_num : (0:ℝ)<2)] + rw [he,←Real.exp_add] + congr 1 + ring + +lemma completion_parameter_bound (G : Input) {r : ℕ} (hn : G.n=2*r) : + q G.n+B G*r+20*G.n≤ L G := by + let t := G.n+B G+1 + have ht1 : 1≤ t := by dsimp [t]; omega + have hnt : G.n≤ t := by dsimp [t]; omega + have hBt : B G≤ t := by dsimp [t]; omega + have hrt : r≤ t := by omega + have hq : q G.n≤ t^2 := (q_le_square (n := G.n)).trans (Nat.pow_le_pow_left hnt 2) + have hBr : B G*r≤ t^2 := by simpa only [pow_two] using Nat.mul_le_mul hBt hrt + have ht13 : t≤ t^3 := Nat.le_self_pow (by omega) t + have ht23 : t^2≤ t^3 := by + calc + t^2=t^2*1 := by ring + _ ≤ t^2*t := Nat.mul_le_mul_left _ ht1 + _ = _ := by ring + change _≤100*t^3 + omega + +lemma Zbad_small (G : Input) (heven : Even G.n) : + Zbad G≤ Real.exp (Real.log 2*(-20*(G.n:ℝ))) := by + obtain ⟨r,hr⟩ := heven + have hn : G.n=2*r := by omega + have hh := Zbad_bound G hn + have hdom : (q G.n:ℝ)+(B G:ℝ)*r+20*(G.n:ℝ)≤ L G := by + exact_mod_cast completion_parameter_bound G hn + apply hh.trans + apply Real.exp_le_exp.mpr + apply mul_le_mul_of_nonneg_left _ log_two_pos.le + linarith + +theorem completion_bracket (G : Input) (hn : 4≤ G.n) (heven : Even G.n) : + (count G=0 → logZ G≤-20*(G.n:ℝ)) ∧ + (0< count G → 1≤ Z G ∧ (2:ℝ)⁻¹^(G.n/2)*(count G:ℝ)≤ Z G ∧ Z G≤2*(count G:ℝ)) := by + have hbad := Zbad_small G heven + have hNsplit := Z_decompose G + have hsmall : Zbad G≤1 := by + apply hbad.trans (Real.exp_le_one_iff.mpr _) + exact mul_nonpos_of_nonneg_of_nonpos log_two_pos.le (mul_nonpos_of_nonpos_of_nonneg (by norm_num) (Nat.cast_nonneg _)) + have hn2 : G.n=2*(G.n/2) := by + obtain ⟨r,hr⟩ := heven + omega + have hgood := Zgood_bracket G hn2 + constructor + · intro hN + have hg : Zgood G=0 := le_antisymm (by simpa only [hN,Nat.cast_zero] using hgood.2) (Zgood_nonneg G) + have hz : Z G≤ Real.exp (Real.log 2*(-20*(G.n:ℝ))) := by linarith + have hl := Real.log_le_log (Z_pos G hn heven) hz + rw [Real.log_exp] at hl + unfold logZ + apply (div_le_iff₀ log_two_pos).2 + nlinarith + · intro hN + have hng : 1≤ Zgood G := Zgood_ge_one G hN + have hN' : (1:ℝ)≤ count G := by exact_mod_cast hN + have hbn := Zbad_nonneg G + constructor + · linarith + constructor + · linarith [hgood.1] + · linarith [hgood.2] + +end +end BinaryMatching.Algorithm +end + +end OAI diff --git a/lean/OAI/Combinatorics/PerfectMatching/Continuity.lean b/lean/OAI/Combinatorics/PerfectMatching/Continuity.lean new file mode 100644 index 0000000000000000000000000000000000000000..ab740425a12c86b9c743e6a30e4bb9a8d9da8237 --- /dev/null +++ b/lean/OAI/Combinatorics/PerfectMatching/Continuity.lean @@ -0,0 +1,83 @@ +import OAI.Combinatorics.PerfectMatching.SecondVariation +import OAI.Combinatorics.PerfectMatching.Face + +namespace OAI + +/-! +Boundary lower semicontinuity of maximum entropy and attainment of the entropy defect. +-/ + +noncomputable section + +open scoped BigOperators Topology +open Filter + +namespace MatchingEntropy + +variable {V E : Type*} [Fintype V] [Fintype E] [DecidableEq V] [DecidableEq E] + +omit [Fintype V] [DecidableEq V] in +/-- Concavity of H follows from mixing genuine optimizing probability laws. -/ +theorem maxMatchingEntropy_mix_ge (G : LooplessGraph V E) {x y : E → ℝ} + (hx : x ∈ G.polytope) (hy : y ∈ G.polytope) {t : ℝ} + (ht : t ∈ Set.Icc (0 : ℝ) 1) : + (1-t)*maxMatchingEntropy G x+t*maxMatchingEntropy G y ≤ + maxMatchingEntropy G ((1-t) • x+t • y) := by + obtain ⟨p,hp,hpe⟩ := maxMatchingEntropy_attained G hx + obtain ⟨q,hq,hqe⟩ := maxMatchingEntropy_attained G hy + rw [← hpe,← hqe] + apply (entropy_mix_ge hp.1.1 hq.1.1 ht).trans + apply entropy_le_maxMatchingEntropy + refine ⟨convex_probabilitySimplex _ hp.1 hq.1 (sub_nonneg.mpr ht.2) ht.1 (by ring),?_⟩ + change G.meanLinear ((1-t) • p+t • q) = _ + rw [map_add,map_smul,map_smul] + change (1-t) • G.mean p+t • G.mean q = _ + rw [hp.2,hq.2] + +/-- Boundary lower semicontinuity, using the finite matching-polytope constraints. +A fixed small mixing coefficient suffices for each prescribed entropy tolerance. -/ +theorem maxMatchingEntropy_lowerSemicontinuousOn (G : LooplessGraph V E) + (heven : Even (Fintype.card V)) : + LowerSemicontinuousOn (maxMatchingEntropy G) G.polytope := by + intro x hx r hr + have hn := maxMatchingEntropy_nonneg G hx + have hden : 0 < maxMatchingEntropy G x+1 := by linarith + have ha : 0 < min (1:ℝ) ((maxMatchingEntropy G x-r)/(maxMatchingEntropy G x+1)) := + lt_min (by norm_num) (div_pos (sub_pos.mpr hr) hden) + obtain ⟨t,ht0,htt⟩ := exists_between ha + have ht1 : t<1 := htt.trans_le (min_le_left _ _) + have htb : t*(maxMatchingEntropy G x+1) < maxMatchingEntropy G x-r := + (lt_div_iff₀ hden).mp (htt.trans_le (min_le_right _ _)) + filter_upwards [G.polytope_eventually_expand heven hx ht0] with y hy + have hh := maxMatchingEntropy_mix_ge G hx hy ⟨ht0.le,ht1.le⟩ + have he : (1-t) • x+t • (x+t⁻¹ • (y-x))=y := by + ext e + simp only [Pi.add_apply,Pi.smul_apply,Pi.sub_apply,smul_eq_mul] + field_simp + ring + rw [he] at hh + have hz := mul_nonneg ht0.le (maxMatchingEntropy_nonneg G hy) + nlinarith + +/-- The actual entropy defect attains a maximum on the closed matching polytope. -/ +theorem entropyDefect_attains_max (G : LooplessGraph V E) + (heven : Even (Fintype.card V)) (hPM : Nonempty G.Matching) (m : ℝ) : + ∃ x ∈ G.polytope, ∀ y ∈ G.polytope, entropyDefect G m y ≤ entropyDefect G m x := by + have hc : Continuous (fun y : E → ℝ => entropyBarrier m (entropy y)) := by + have hb : Continuous (entropyBarrier m) := by unfold entropyBarrier; fun_prop + exact hb.comp continuous_entropy + have hs : UpperSemicontinuousOn (entropyDefect G m) G.polytope := by + change UpperSemicontinuousOn (fun y => entropyBarrier m (entropy y)-maxMatchingEntropy G y) G.polytope + simpa only [sub_eq_add_neg, Pi.neg_apply] using + hc.continuousOn.upperSemicontinuousOn.add + (maxMatchingEntropy_lowerSemicontinuousOn G heven).neg + have hn : G.polytope.Nonempty := by + obtain ⟨M⟩ := hPM + exact ⟨G.indicator M,subset_convexHull ℝ _ (Set.mem_range_self M)⟩ + exact UpperSemicontinuousOn.exists_isMaxOn hn G.compact_polytope hs + +end MatchingEntropy + +end + +end OAI diff --git a/lean/OAI/Combinatorics/PerfectMatching/Contraction.lean b/lean/OAI/Combinatorics/PerfectMatching/Contraction.lean new file mode 100644 index 0000000000000000000000000000000000000000..aecc68369d77ee6bb11c8d54ae41c353a87b8e94 --- /dev/null +++ b/lean/OAI/Combinatorics/PerfectMatching/Contraction.lean @@ -0,0 +1,432 @@ +import OAI.Combinatorics.PerfectMatching.OddCuts +import OAI.Combinatorics.PerfectMatching.Coupling + +namespace OAI + +/-! +Contraction of tight odd cuts and gluing of perfect matchings and their laws. +-/ + +noncomputable section + +open scoped BigOperators Topology +open Filter + +namespace MatchingEntropy + +variable {V E : Type*} [Fintype V] [Fintype E] [DecidableEq V] [DecidableEq E] + +namespace LooplessGraph + +/-- Contraction of the complement of S to a new vertex. Edges retain identities; +only edges with both endpoints outside S are discarded. -/ +def onSide (G : LooplessGraph V E) (S : Finset V) : + LooplessGraph (Option {v // v ∈ S}) {e // G.left e ∈ S ∨ G.right e ∈ S} where + left e := if h : G.left e.val ∈ S then some ⟨G.left e.val, h⟩ else none + right e := if h : G.right e.val ∈ S then some ⟨G.right e.val, h⟩ else none + loopless e := by + dsimp + split_ifs with hl hr + · intro he + have hv := Option.some.inj he + exact G.loopless e.val (congrArg Subtype.val hv) + · simp + · simp + · rename_i hr + exact (e.property.elim hl hr).elim + + +omit [Fintype V] [Fintype E] [DecidableEq E] in +theorem onSide_incident_some (G : LooplessGraph V E) (S : Finset V) + (v : {v // v ∈ S}) (e : {e // G.left e ∈ S ∨ G.right e ∈ S}) : + (G.onSide S).Incident (some v) e ↔ G.Incident v.val e.val := by + have hf : ∀ (w : V), + (if h : w ∈ S then some (⟨w,h⟩ : {v // v ∈ S}) else none) = some v ↔ w=v.val := by + intro w + by_cases hw : w ∈ S + · simp only [hw, ↓reduceDIte, Option.some.injEq] + exact Subtype.ext_iff + · simp only [hw, ↓reduceDIte] + constructor + · intro h + cases h + · intro he + exact (hw (he.symm ▸ v.property)).elim + change ((if h : G.left e.val ∈ S then some ⟨G.left e.val,h⟩ else none) = some v ∨ + (if h : G.right e.val ∈ S then some ⟨G.right e.val,h⟩ else none) = some v) ↔ _ + rw [hf, hf] + rfl + +omit [Fintype V] [Fintype E] [DecidableEq E] in +theorem onSide_incident_none (G : LooplessGraph V E) (S : Finset V) + (e : {e // G.left e ∈ S ∨ G.right e ∈ S}) : + (G.onSide S).Incident none e ↔ G.Crosses S e.val := by + simp only [Incident, onSide, Crosses] + by_cases hl : G.left e.val ∈ S <;> by_cases hr : G.right e.val ∈ S <;> + simp [hl, hr] + exact (e.property.elim hl hr).elim + +def boundaryEdge (G : LooplessGraph V E) (S : Finset V) (M : (G.onSide S).Matching) : + {e // G.left e ∈ S ∨ G.right e ∈ S} := Classical.choose (M.property none) + +omit [Fintype V] [Fintype E] [DecidableEq E] in +theorem boundaryEdge_mem (G : LooplessGraph V E) (S : Finset V) + (M : (G.onSide S).Matching) : G.boundaryEdge S M ∈ M.val := + (Classical.choose_spec (M.property none)).1.1 + +omit [Fintype V] [Fintype E] [DecidableEq E] in +theorem boundaryEdge_crosses (G : LooplessGraph V E) (S : Finset V) + (M : (G.onSide S).Matching) : G.Crosses S (G.boundaryEdge S M).val := + (G.onSide_incident_none S _).mp (Classical.choose_spec (M.property none)).1.2 + +omit [Fintype V] [Fintype E] [DecidableEq E] in +theorem eq_boundaryEdge (G : LooplessGraph V E) (S : Finset V) + (M : (G.onSide S).Matching) {e : {e // G.left e ∈ S ∨ G.right e ∈ S}} + (he : e ∈ M.val) (hc : G.Crosses S e.val) : e = G.boundaryEdge S M := + (Classical.choose_spec (M.property none)).2 e ⟨he, (G.onSide_incident_none S e).mpr hc⟩ + +def liftedEdges (G : LooplessGraph V E) (S : Finset V) (M : (G.onSide S).Matching) : Finset E := + M.val.image Subtype.val + +omit [Fintype V] [Fintype E] in +theorem mem_liftedEdges (G : LooplessGraph V E) (S : Finset V) + (M : (G.onSide S).Matching) (e : {e // G.left e ∈ S ∨ G.right e ∈ S}) : + e.val ∈ G.liftedEdges S M ↔ e ∈ M.val := by + simp only [liftedEdges, Finset.mem_image] + constructor + · rintro ⟨a, ha, he⟩ + have he' : a = e := Subtype.ext he + simpa only [he'] using ha + · intro he + exact ⟨e, he, rfl⟩ + +omit [Fintype V] [Fintype E] in +theorem liftedEdges_keep (G : LooplessGraph V E) (S : Finset V) + (M : (G.onSide S).Matching) {e : E} (he : e ∈ G.liftedEdges S M) : + G.left e ∈ S ∨ G.right e ∈ S := by + rcases Finset.mem_image.mp he with ⟨a, _, rfl⟩ + exact a.property + +omit [Fintype V] [Fintype E] in +theorem lifted_cross_eq_boundary (G : LooplessGraph V E) (S : Finset V) + (M : (G.onSide S).Matching) {e : E} (he : e ∈ G.liftedEdges S M) + (hc : G.Crosses S e) : e = (G.boundaryEdge S M).val := by + let e' : {e // G.left e ∈ S ∨ G.right e ∈ S} := ⟨e, G.liftedEdges_keep S M he⟩ + exact congrArg Subtype.val (G.eq_boundaryEdge S M ((G.mem_liftedEdges S M e').mp he) hc) + +omit [Fintype V] [Fintype E] in +theorem boundary_mem_lifted (G : LooplessGraph V E) (S : Finset V) + (M : (G.onSide S).Matching) : (G.boundaryEdge S M).val ∈ G.liftedEdges S M := + (G.mem_liftedEdges S M _).mpr (G.boundaryEdge_mem S M) + +omit [Fintype E] [DecidableEq E] in +theorem crosses_of_kept_both (G : LooplessGraph V E) (S : Finset V) (e : E) + (h₁ : G.left e ∈ S ∨ G.right e ∈ S) + (h₂ : G.left e ∈ Sᶜ ∨ G.right e ∈ Sᶜ) : G.Crosses S e := by + simp only [Finset.mem_compl] at h₂ + unfold Crosses + tauto + +omit [Fintype E] in +/-- A compatible pair only duplicates its common boundary edge. -/ +theorem lifted_other_subset (G : LooplessGraph V E) (S : Finset V) + (M₁ : (G.onSide S).Matching) (M₂ : (G.onSide Sᶜ).Matching) + (heq : (G.boundaryEdge S M₁).val = (G.boundaryEdge Sᶜ M₂).val) + {e : E} (he : e ∈ G.liftedEdges Sᶜ M₂) + (hkeep : G.left e ∈ S ∨ G.right e ∈ S) : e ∈ G.liftedEdges S M₁ := by + have hc := G.crosses_of_kept_both S e hkeep (G.liftedEdges_keep Sᶜ M₂ he) + have hcb : G.Crosses Sᶜ e := (G.crosses_compl S e).mpr hc + rw [G.lifted_cross_eq_boundary Sᶜ M₂ he hcb, ← heq] + exact G.boundary_mem_lifted S M₁ + +omit [Fintype E] in +/-- Gluing compatible perfect matchings preserves each retained edge choice. -/ +theorem mem_glued_left (G : LooplessGraph V E) (S : Finset V) + (M₁ : (G.onSide S).Matching) (M₂ : (G.onSide Sᶜ).Matching) + (heq : (G.boundaryEdge S M₁).val = (G.boundaryEdge Sᶜ M₂).val) + (e : {e // G.left e ∈ S ∨ G.right e ∈ S}) : + e.val ∈ G.liftedEdges S M₁ ∪ G.liftedEdges Sᶜ M₂ ↔ e ∈ M₁.val := by + simp only [Finset.mem_union] + constructor + · rintro (h | h) + · exact (G.mem_liftedEdges S M₁ e).mp h + · exact (G.mem_liftedEdges S M₁ e).mp (G.lifted_other_subset S M₁ M₂ heq h e.property) + · intro h + exact Or.inl ((G.mem_liftedEdges S M₁ e).mpr h) + +omit [Fintype E] in +theorem mem_glued_right (G : LooplessGraph V E) (S : Finset V) + (M₁ : (G.onSide S).Matching) (M₂ : (G.onSide Sᶜ).Matching) + (heq : (G.boundaryEdge S M₁).val = (G.boundaryEdge Sᶜ M₂).val) + (e : {e // G.left e ∈ Sᶜ ∨ G.right e ∈ Sᶜ}) : + e.val ∈ G.liftedEdges S M₁ ∪ G.liftedEdges Sᶜ M₂ ↔ e ∈ M₂.val := by + simp only [Finset.mem_union] + constructor + · rintro (h | h) + · have hc := G.crosses_of_kept_both S e.val (G.liftedEdges_keep S M₁ h) e.property + have he := (G.lifted_cross_eq_boundary S M₁ h hc).trans heq + apply (G.mem_liftedEdges Sᶜ M₂ e).mp + rw [he] + exact G.boundary_mem_lifted Sᶜ M₂ + · exact (G.mem_liftedEdges Sᶜ M₂ e).mp h + · intro h + exact Or.inr ((G.mem_liftedEdges Sᶜ M₂ e).mpr h) + +omit [Fintype E] in +theorem glued_perfect (G : LooplessGraph V E) (S : Finset V) + (M₁ : (G.onSide S).Matching) (M₂ : (G.onSide Sᶜ).Matching) + (heq : (G.boundaryEdge S M₁).val = (G.boundaryEdge Sᶜ M₂).val) : + G.IsPerfectMatching (G.liftedEdges S M₁ ∪ G.liftedEdges Sᶜ M₂) := by + intro v + by_cases hv : v ∈ S + · obtain ⟨e, ⟨he, hev⟩, hu⟩ := M₁.property (some ⟨v,hv⟩) + have hev' := (G.onSide_incident_some S ⟨v,hv⟩ e).mp hev + refine ⟨e.val, ⟨(G.mem_glued_left S M₁ M₂ heq e).mpr he, hev'⟩, ?_⟩ + rintro f ⟨hf, hfv⟩ + have hk : G.left f ∈ S ∨ G.right f ∈ S := by + rcases hfv with h | h + · exact Or.inl (h.symm ▸ hv) + · exact Or.inr (h.symm ▸ hv) + let f' : {e // G.left e ∈ S ∨ G.right e ∈ S} := ⟨f,hk⟩ + have hf' : f' ∈ M₁.val := (G.mem_glued_left S M₁ M₂ heq f').mp hf + exact congrArg Subtype.val (hu f' ⟨hf', (G.onSide_incident_some S ⟨v,hv⟩ f').mpr hfv⟩) + · have hv' := Finset.mem_compl.mpr hv + obtain ⟨e, ⟨he, hev⟩, hu⟩ := M₂.property (some ⟨v,hv'⟩) + have hev' := (G.onSide_incident_some Sᶜ ⟨v,hv'⟩ e).mp hev + refine ⟨e.val, ⟨(G.mem_glued_right S M₁ M₂ heq e).mpr he, hev'⟩, ?_⟩ + rintro f ⟨hf, hfv⟩ + have hk : G.left f ∈ Sᶜ ∨ G.right f ∈ Sᶜ := by + rcases hfv with h | h + · exact Or.inl (h.symm ▸ hv') + · exact Or.inr (h.symm ▸ hv') + let f' : {e // G.left e ∈ Sᶜ ∨ G.right e ∈ Sᶜ} := ⟨f,hk⟩ + have hf' : f' ∈ M₂.val := (G.mem_glued_right S M₁ M₂ heq f').mp hf + exact congrArg Subtype.val (hu f' ⟨hf', (G.onSide_incident_some Sᶜ ⟨v,hv'⟩ f').mpr hfv⟩) + +def glueMatching (G : LooplessGraph V E) (S : Finset V) + (z : {z : (G.onSide S).Matching × (G.onSide Sᶜ).Matching // + (G.boundaryEdge S z.1).val = (G.boundaryEdge Sᶜ z.2).val}) : G.Matching := + ⟨G.liftedEdges S z.val.1 ∪ G.liftedEdges Sᶜ z.val.2, + G.glued_perfect S z.val.1 z.val.2 z.property⟩ + +omit [Fintype E] in +theorem indicator_glue_left (G : LooplessGraph V E) (S : Finset V) + (z : {z : (G.onSide S).Matching × (G.onSide Sᶜ).Matching // + (G.boundaryEdge S z.1).val = (G.boundaryEdge Sᶜ z.2).val}) + (e : {e // G.left e ∈ S ∨ G.right e ∈ S}) : + G.indicator (G.glueMatching S z) e.val = (G.onSide S).indicator z.val.1 e := by + simp only [indicator, glueMatching, G.mem_glued_left S z.val.1 z.val.2 z.property e] + +omit [Fintype E] in +theorem indicator_glue_right (G : LooplessGraph V E) (S : Finset V) + (z : {z : (G.onSide S).Matching × (G.onSide Sᶜ).Matching // + (G.boundaryEdge S z.1).val = (G.boundaryEdge Sᶜ z.2).val}) + (e : {e // G.left e ∈ Sᶜ ∨ G.right e ∈ Sᶜ}) : + G.indicator (G.glueMatching S z) e.val = (G.onSide Sᶜ).indicator z.val.2 e := by + simp only [indicator, glueMatching, G.mem_glued_right S z.val.1 z.val.2 z.property e] + +omit [Fintype V] [Fintype E] [DecidableEq E] in +theorem boundary_eq_iff_mem (G : LooplessGraph V E) (S : Finset V) + (M : (G.onSide S).Matching) (e : {e // G.left e ∈ S ∨ G.right e ∈ S}) + (hc : G.Crosses S e.val) : (G.boundaryEdge S M).val=e.val ↔ e ∈ M.val := by + constructor + · intro h + have he : G.boundaryEdge S M = e := Subtype.ext h + exact he ▸ G.boundaryEdge_mem S M + · intro h + exact (congrArg Subtype.val (G.eq_boundaryEdge S M h hc)).symm + +omit [Fintype V] in +theorem boundary_fiber (G : LooplessGraph V E) (S : Finset V) + (p : (G.onSide S).Matching → ℝ) (e : {e // G.left e ∈ S ∨ G.right e ∈ S}) + (hc : G.Crosses S e.val) : + fiberMass p (fun M => (G.boundaryEdge S M).val) e.val = (G.onSide S).mean p e := by + unfold fiberMass mean + apply Finset.sum_congr rfl + intro M _ + simp only [G.boundary_eq_iff_mem S M e hc, indicator] + split <;> simp + +omit [Fintype V] in +theorem boundary_fiber_zero (G : LooplessGraph V E) (S : Finset V) + (p : (G.onSide S).Matching → ℝ) (e : E) (hc : ¬G.Crosses S e) : + fiberMass p (fun M => (G.boundaryEdge S M).val) e = 0 := by + apply Finset.sum_eq_zero + intro M _ + have he : (G.boundaryEdge S M).val ≠ e := by + intro h + exact hc (h ▸ G.boundaryEdge_crosses S M) + simp [he] + +/-- Exact coupling across a cut, for multigraphs with distinct edge identities. -/ +theorem couple_laws (G : LooplessGraph V E) (S : Finset V) (x : E → ℝ) + {p : (G.onSide S).Matching → ℝ} {q : (G.onSide Sᶜ).Matching → ℝ} + (hp : p ∈ probabilitySimplex (G.onSide S).Matching) + (hq : q ∈ probabilitySimplex (G.onSide Sᶜ).Matching) + (hpx : ∀ e, (G.onSide S).mean p e = x e.val) + (hqx : ∀ e, (G.onSide Sᶜ).mean q e = x e.val) : + ∃ r, r ∈ G.feasibleLaws x := by + let f := fun M : (G.onSide S).Matching => (G.boundaryEdge S M).val + let g := fun M : (G.onSide Sᶜ).Matching => (G.boundaryEdge Sᶜ M).val + have hc : ∀ e, fiberMass p f e = fiberMass q g e := by + intro e + by_cases he : G.Crosses S e + · have hk : G.left e ∈ S ∨ G.right e ∈ S := he.elim (fun h => Or.inl h.1) (fun h => Or.inr h.2) + have he' := (G.crosses_compl S e).mpr he + have hk' : G.left e ∈ Sᶜ ∨ G.right e ∈ Sᶜ := he'.elim (fun h => Or.inl h.1) (fun h => Or.inr h.2) + rw [G.boundary_fiber S p ⟨e,hk⟩ he, G.boundary_fiber Sᶜ q ⟨e,hk'⟩ he', hpx, hqx] + · have he' : ¬G.Crosses Sᶜ e := fun h => he ((G.crosses_compl S e).mp h) + rw [G.boundary_fiber_zero S p e he, G.boundary_fiber_zero Sᶜ q e he'] + let Z := {z : (G.onSide S).Matching × (G.onSide Sᶜ).Matching // f z.1=g z.2} + let w : Z → ℝ := fun z => jointLaw p q f g z.val + have hw : w ∈ probabilitySimplex Z := compatible_jointLaw_mem_simplex hp hq f g hc + refine ⟨fiberMass w (G.glueMatching S), fiberMass_mem_simplex hw _, ?_⟩ + ext e + rw [mean, fiberMass_expect] + by_cases he : G.left e ∈ S ∨ G.right e ∈ S + · have hi : ∀ z : Z, G.indicator (G.glueMatching S z) e = + (G.onSide S).indicator z.val.1 ⟨e,he⟩ := fun z => G.indicator_glue_left S z ⟨e,he⟩ + simp_rw [hi] + exact (compatible_jointLaw_expect_first hp.1 f g hc + (fun M => (G.onSide S).indicator M ⟨e,he⟩)).trans (hpx ⟨e,he⟩) + · have he' : G.left e ∈ Sᶜ ∨ G.right e ∈ Sᶜ := by + simp only [not_or] at he + exact Or.inl (Finset.mem_compl.mpr he.1) + have hi : ∀ z : Z, G.indicator (G.glueMatching S z) e = + (G.onSide Sᶜ).indicator z.val.2 ⟨e,he'⟩ := fun z => G.indicator_glue_right S z ⟨e,he'⟩ + simp_rw [hi] + exact (compatible_jointLaw_expect_second hq.1 f g hc + (fun M => (G.onSide Sᶜ).indicator M ⟨e,he'⟩)).trans (hqx ⟨e,he'⟩) + +def sideMap (S : Finset V) (v : V) : Option {v // v ∈ S} := + if h : v ∈ S then some ⟨v,h⟩ else none + +def liftVertices (S : Finset V) (T : Finset (Option {v // v ∈ S})) : Finset V := + Finset.univ.filter (fun v => sideMap S v ∈ T) + +@[simp] theorem mem_liftVertices (S : Finset V) + (T : Finset (Option {v // v ∈ S})) (v : V) : + v ∈ liftVertices S T ↔ sideMap S v ∈ T := by simp [liftVertices] + +omit [Fintype V] in +@[simp] theorem sideMap_some (S : Finset V) (v : {v // v ∈ S}) : + sideMap S v.val = some v := by + simp [sideMap, v.property] + +theorem liftVertices_card (S : Finset V) (T : Finset (Option {v // v ∈ S})) + (hn : none ∉ T) : (liftVertices S T).card = T.card := by + apply Finset.card_bij (fun v _ => sideMap S v) + · intro v hv + exact (mem_liftVertices S T v).mp hv + · intro v hv w hw he + have hvS : v ∈ S := by + by_contra h + have hmem := (mem_liftVertices S T v).mp hv + simp only [sideMap, h, ↓reduceDIte] at hmem + exact hn hmem + have hwS : w ∈ S := by + by_contra h + have hmem := (mem_liftVertices S T w).mp hw + simp only [sideMap, h, ↓reduceDIte] at hmem + exact hn hmem + simp only [sideMap, hvS, hwS, ↓reduceDIte, Option.some.injEq] at he + exact congrArg Subtype.val he + · intro t ht + cases t with + | none => exact (hn ht).elim + | some v => exact ⟨v.val, by simpa only [mem_liftVertices, sideMap_some] using ht, sideMap_some S v⟩ + +omit [Fintype E] [DecidableEq E] in +theorem onSide_cut_crosses (G : LooplessGraph V E) (S : Finset V) + (T : Finset (Option {v // v ∈ S})) (e : {e // G.left e ∈ S ∨ G.right e ∈ S}) : + (G.onSide S).Crosses T e ↔ G.Crosses (liftVertices S T) e.val := by + simp only [Crosses, mem_liftVertices] + rfl + +omit [Fintype E] [DecidableEq E] in +theorem crosses_lift_kept (G : LooplessGraph V E) (S : Finset V) + (T : Finset (Option {v // v ∈ S})) (e : E) + (he : G.Crosses (liftVertices S T) e) : G.left e ∈ S ∨ G.right e ∈ S := by + by_contra h + simp only [not_or] at h + simp only [Crosses, mem_liftVertices, sideMap, h.1, h.2, ↓reduceDIte] at he + tauto + +omit [DecidableEq E] in +theorem onSide_cutMass (G : LooplessGraph V E) (S : Finset V) + (x : E → ℝ) (T : Finset (Option {v // v ∈ S})) : + (G.onSide S).cutMass (fun e => x e.val) T = G.cutMass x (liftVertices S T) := by + simp only [cutMass, cut, Finset.sum_filter] + simp_rw [G.onSide_cut_crosses S T] + exact sum_subtype_supported (fun e => G.left e ∈ S ∨ G.right e ∈ S) + (fun e => if G.Crosses (liftVertices S T) e then x e else 0) + (by intro e he; rw [ite_eq_right (fun hc => he (G.crosses_lift_kept S T e hc))]) + +omit [Fintype V] [DecidableEq E] in +theorem onSide_degree_some (G : LooplessGraph V E) (S : Finset V) + (x : E → ℝ) (v : {v // v ∈ S}) : + (G.onSide S).degree (fun e => x e.val) (some v) = G.degree x v.val := by + simp only [degree] + simp_rw [G.onSide_incident_some S v] + apply sum_subtype_supported (fun e => G.left e ∈ S ∨ G.right e ∈ S) + (fun e => if G.Incident v.val e then x e else 0) + intro e he + rw [ite_eq_right] + rintro (h | h) + · exact he (Or.inl (h.symm ▸ v.property)) + · exact he (Or.inr (h.symm ▸ v.property)) + +omit [Fintype V] [DecidableEq E] in +theorem onSide_degree_none (G : LooplessGraph V E) (S : Finset V) (x : E → ℝ) : + (G.onSide S).degree (fun e => x e.val) none = G.cutMass x S := by + simp only [degree, cutMass, cut, Finset.sum_filter] + simp_rw [G.onSide_incident_none S] + apply sum_subtype_supported (fun e => G.left e ∈ S ∨ G.right e ∈ S) + (fun e => if G.Crosses S e then x e else 0) + intro e he + rw [ite_eq_right] + rintro (h | h) + · exact he (Or.inl h.1) + · exact he (Or.inr h.2) + +theorem odd_compl_of_even {W : Type*} [Fintype W] [DecidableEq W] + (hn : Even (Fintype.card W)) {T : Finset W} (hT : Odd T.card) : Odd Tᶜ.card := by + rcases hn with ⟨k,hk⟩ + rcases hT with ⟨l,hl⟩ + have hle := Finset.card_le_univ T + rw [Finset.card_compl] + refine ⟨k-l-1, ?_⟩ + omega + +omit [DecidableEq E] in +/-- Exact inheritance of the odd-cut system under contraction of a tight odd cut. -/ +theorem restriction_mem_constraints (G : LooplessGraph V E) {x : E → ℝ} + (hx : x ∈ G.constraintPolytope) (S : Finset V) (hS : Odd S.card) + (htight : G.cutMass x S = 1) : + (fun e : {e // G.left e ∈ S ∨ G.right e ∈ S} => x e.val) ∈ + (G.onSide S).constraintPolytope := by + refine ⟨fun e => hx.1 e.val, ?_, ?_⟩ + · intro v + cases v with + | none => exact (G.onSide_degree_none S x).trans htight + | some v => exact (G.onSide_degree_some S x v).trans (hx.2.1 v.val) + · intro T hT + by_cases hn : none ∈ T + · have hn' : none ∉ Tᶜ := by simpa using hn + have hnEven : Even (Fintype.card (Option {v // v ∈ S})) := by + simp only [Fintype.card_option, Fintype.card_coe] + exact hS.add_odd odd_one + have hTc := odd_compl_of_even hnEven hT + have hh := hx.2.2 (liftVertices S Tᶜ) (by rwa [liftVertices_card S Tᶜ hn']) + rw [← G.onSide_cutMass S x Tᶜ] at hh + simpa only [cutMass, cut_compl] using hh + · rw [G.onSide_cutMass S x T] + exact hx.2.2 _ (by rwa [liftVertices_card S T hn]) + +end LooplessGraph + +end MatchingEntropy + +end + +end OAI diff --git a/lean/OAI/Combinatorics/PerfectMatching/CountCorrect.lean b/lean/OAI/Combinatorics/PerfectMatching/CountCorrect.lean new file mode 100644 index 0000000000000000000000000000000000000000..f566107a54fa3d7216211a79ea7801d7a50fa36a --- /dev/null +++ b/lean/OAI/Combinatorics/PerfectMatching/CountCorrect.lean @@ -0,0 +1,100 @@ +import OAI.Combinatorics.PerfectMatching.Completion + +namespace OAI + +section + +namespace BinaryMatching.Algorithm +noncomputable section +open Finset MatchingEntropy + +lemma zero_test (G : Input) (hn : 4 ≤ G.n) (heven : Even G.n) : + R G < -10*(G.n:ℤ) ↔ count G = 0 := by + have hp := R_partition_bracket G hn heven + have hc := completion_bracket G hn heven + have hn' : (4:ℝ) ≤ G.n := by exact_mod_cast hn + constructor + · intro hr + by_contra hN + have hNpos : 0 < count G := Nat.pos_of_ne_zero hN + have hz : 0 ≤ logZ G := by + unfold logZ + exact div_nonneg (Real.log_nonneg (hc.2 hNpos).1) log_two_pos.le + have hr' : (R G:ℝ) < -10*(G.n:ℝ) := by exact_mod_cast hr + linarith [hp.2] + · intro hN + have hz := hc.1 hN + have hr' : (R G:ℝ) < -10*(G.n:ℝ) := by linarith [hp.1] + exact_mod_cast hr' + +lemma log_count_bracket (G : Input) (hn : 4 ≤ G.n) (heven : Even G.n) + (hN : 0 < count G) : + (R G:ℝ)-5*(G.n:ℝ) ≤ Real.log (count G)/Real.log 2 ∧ + Real.log (count G)/Real.log 2 ≤ (R G:ℝ)+4*(G.n:ℝ) := by + have hp := R_partition_bracket G hn heven + obtain ⟨_hone,hlo,hhi⟩ := (completion_bracket G hn heven).2 hN + have hN' : (0:ℝ) < count G := by exact_mod_cast hN + have hn' : (4:ℝ) ≤ G.n := by exact_mod_cast hn + have hlo' := Real.log_le_log (show (0:ℝ) < 2⁻¹^(G.n/2)*(count G:ℝ) by positivity) hlo + have hhi' := Real.log_le_log (Z_pos G hn heven) hhi + rw [Real.log_mul (by positivity) hN'.ne',Real.log_pow,Real.log_inv] at hlo' + rw [Real.log_mul (by norm_num) hN'.ne'] at hhi' + have hdiv : ((G.n/2:ℕ):ℝ) ≤ (G.n:ℝ) := by exact_mod_cast Nat.div_le_self G.n 2 + dsimp only [logZ] at hp + constructor + · apply (le_div_iff₀ log_two_pos).2 + have hpart := (le_div_iff₀ log_two_pos).1 hp.1 + nlinarith [log_two_pos] + · apply (div_le_iff₀ log_two_pos).2 + have hpart := (div_le_iff₀ log_two_pos).1 hp.2 + nlinarith [mul_le_mul_of_nonneg_right hdiv log_two_pos.le] + +theorem estimate_correct (G : Input) (hn : 4 ≤ G.n) (heven : Even G.n) : + estimate G ≤ count G ∧ count G ≤ 2^(9*G.n)*estimate G ∧ + (estimate G=0 ↔ count G=0) := by + by_cases hN : count G=0 + · have hr : R G < -(10*(G.n:ℤ)) := by simpa only [neg_mul] using (zero_test G hn heven).2 hN + simp [estimate,hr,hN] + · have hNpos : 0 < count G := Nat.pos_of_ne_zero hN + have hr : ¬R G < -(10*(G.n:ℤ)) := by simpa only [←neg_mul,zero_test G hn heven] using hN + have he : estimate G=2^(R G-5*(G.n:ℤ)).toNat := by simp [estimate,hr] + let rho := (R G-5*(G.n:ℤ)).toNat + have he' : estimate G=2^rho := he + have hrhol : (R G:ℝ)-5*(G.n:ℝ) ≤ (rho:ℝ) := by + have hi : R G-5*(G.n:ℤ) ≤ (rho:ℤ) := Int.self_le_toNat _ + exact_mod_cast hi + have hNc : (0:ℝ) < count G := by exact_mod_cast hNpos + have hN1 : (1:ℝ) ≤ count G := by exact_mod_cast hNpos + have hlog0 : 0 ≤ Real.log (count G)/Real.log 2 := + div_nonneg (Real.log_nonneg hN1) log_two_pos.le + have hbracket := log_count_bracket G hn heven hNpos + have hrhou : (rho:ℝ) ≤ Real.log (count G)/Real.log 2 := by + by_cases hnon : 0 ≤ R G-5*(G.n:ℤ) + · have hh : (rho:ℤ)=R G-5*(G.n:ℤ) := Int.toNat_of_nonneg hnon + have hh' : (rho:ℝ)=(R G:ℝ)-5*(G.n:ℝ) := by exact_mod_cast hh + rw [hh']; exact hbracket.1 + · have hz : rho=0 := Int.toNat_of_nonpos (by omega) + simpa only [hz,Nat.cast_zero] using hlog0 + have hlow : (2:ℝ)^rho ≤ (count G:ℝ) := by + apply (Real.log_le_log_iff (by positivity) hNc).1 + rw [Real.log_pow] + exact (le_div_iff₀ log_two_pos).1 hrhou + have hupp : (count G:ℝ) ≤ (2:ℝ)^(9*G.n)*(2:ℝ)^rho := by + apply (Real.log_le_log_iff hNc (by positivity)).1 + rw [Real.log_mul (by positivity) (by positivity),Real.log_pow,Real.log_pow] + have hh : Real.log (count G)/Real.log 2 ≤ (9*G.n:ℕ)+(rho:ℝ) := by + push_cast; linarith [hbracket.2] + have hh' := (div_le_iff₀ log_two_pos).1 hh + push_cast at hh' ⊢ + nlinarith + have hlow' : 2^rho ≤ count G := by exact_mod_cast hlow + have hupp' : count G ≤ 2^(9*G.n)*2^rho := by exact_mod_cast hupp + rw [he'] + refine ⟨hlow',hupp',?_⟩ + simp [hN] + +end +end BinaryMatching.Algorithm +end + +end OAI diff --git a/lean/OAI/Combinatorics/PerfectMatching/Coupling.lean b/lean/OAI/Combinatorics/PerfectMatching/Coupling.lean new file mode 100644 index 0000000000000000000000000000000000000000..8f812ac8fdbc91ef4792b95724edc3eaab8e6b76 --- /dev/null +++ b/lean/OAI/Combinatorics/PerfectMatching/Coupling.lean @@ -0,0 +1,177 @@ +import OAI.Combinatorics.PerfectMatching.Simplex + +namespace OAI + +/-! +Finite pushforwards and couplings with a prescribed common marginal. +-/ + +noncomputable section + +open scoped BigOperators Topology +open Filter + +namespace MatchingEntropy + +/-- Finite pushforward weights. -/ +def fiberMass {A C : Type*} [Fintype A] [DecidableEq C] + (p : A → ℝ) (f : A → C) (c : C) : ℝ := ∑ a, if f a = c then p a else 0 + +theorem fiberMass_nonneg {A C : Type*} [Fintype A] [DecidableEq C] + {p : A → ℝ} (hp : ∀ a, 0 ≤ p a) (f : A → C) (c : C) : + 0 ≤ fiberMass p f c := by + apply Finset.sum_nonneg + intro a _ + split <;> simp_all + +theorem le_fiberMass_self {A C : Type*} [Fintype A] [DecidableEq C] + {p : A → ℝ} (hp : ∀ a, 0 ≤ p a) (f : A → C) (a : A) : + p a ≤ fiberMass p f (f a) := by + have h := Finset.single_le_sum (s := Finset.univ) (a := a) + (f := fun b => if f b = f a then p b else 0) + (by intro b _; split <;> simp_all) (Finset.mem_univ a) + simpa only [fiberMass, ite_true] using h + +/-- The explicit cut-choice coupling. Only equal choices receive mass. -/ +def jointLaw {A B C : Type*} [Fintype A] [Fintype B] [DecidableEq C] + (p : A → ℝ) (q : B → ℝ) (f : A → C) (g : B → C) (z : A × B) : ℝ := + if f z.1 = g z.2 then p z.1*q z.2 / fiberMass p f (f z.1) else 0 + +theorem jointLaw_nonneg {A B C : Type*} [Fintype A] [Fintype B] [DecidableEq C] + {p : A → ℝ} {q : B → ℝ} (hp : ∀ a, 0 ≤ p a) (hq : ∀ b, 0 ≤ q b) + (f : A → C) (g : B → C) (z : A × B) : 0 ≤ jointLaw p q f g z := by + unfold jointLaw + split + · exact div_nonneg (mul_nonneg (hp _) (hq _)) (fiberMass_nonneg hp f _) + · rfl + +theorem jointLaw_first {A B C : Type*} [Fintype A] [Fintype B] [DecidableEq C] + {p : A → ℝ} {q : B → ℝ} (hp : ∀ a, 0 ≤ p a) + (f : A → C) (g : B → C) (hcompat : ∀ c, fiberMass p f c = fiberMass q g c) + (a : A) : (∑ b, jointLaw p q f g (a,b)) = p a := by + have heq : ∀ b, jointLaw p q f g (a,b) = + (p a / fiberMass p f (f a)) * (if g b=f a then q b else 0) := by + intro b + by_cases h : f a=g b + · simp only [jointLaw, h, ite_true] + ring + · simp [jointLaw, h, Ne.symm h] + simp_rw [heq] + rw [← Finset.mul_sum] + change p a / fiberMass p f (f a) * fiberMass q g (f a) = p a + rw [← hcompat] + by_cases hz : fiberMass p f (f a) = 0 + · have ha : p a = 0 := le_antisymm (by simpa [hz] using le_fiberMass_self hp f a) (hp a) + simp [ha] + · exact div_mul_cancel₀ _ hz + +theorem jointLaw_second {A B C : Type*} [Fintype A] [Fintype B] [DecidableEq C] + {p : A → ℝ} {q : B → ℝ} (hq : ∀ b, 0 ≤ q b) + (f : A → C) (g : B → C) (hcompat : ∀ c, fiberMass p f c = fiberMass q g c) + (b : B) : (∑ a, jointLaw p q f g (a,b)) = q b := by + have heq : ∀ a, jointLaw p q f g (a,b) = + (q b / fiberMass q g (g b)) * (if f a=g b then p a else 0) := by + intro a + by_cases h : f a=g b + · simp only [jointLaw, h, ite_true, ← hcompat] + ring + · simp [jointLaw, h] + simp_rw [heq] + rw [← Finset.mul_sum] + change q b / fiberMass q g (g b) * fiberMass p f (g b) = q b + rw [hcompat] + by_cases hz : fiberMass q g (g b) = 0 + · have hb : q b = 0 := le_antisymm (by simpa [hz] using le_fiberMass_self hq g b) (hq b) + simp [hb] + · exact div_mul_cancel₀ _ hz + +theorem jointLaw_mem_simplex {A B C : Type*} [Fintype A] [Fintype B] [DecidableEq C] + {p : A → ℝ} {q : B → ℝ} (hp : p ∈ probabilitySimplex A) (hq : q ∈ probabilitySimplex B) + (f : A → C) (g : B → C) (hcompat : ∀ c, fiberMass p f c = fiberMass q g c) : + jointLaw p q f g ∈ probabilitySimplex (A × B) := by + refine ⟨jointLaw_nonneg hp.1 hq.1 f g, ?_⟩ + rw [Fintype.sum_prod_type] + simp_rw [jointLaw_first hp.1 f g hcompat] + exact hp.2 + +theorem sum_subtype_supported {A : Type*} [Fintype A] (P : A → Prop) [DecidablePred P] + (w : A → ℝ) (hsupp : ∀ a, ¬P a → w a = 0) : + (∑ a : {a // P a}, w a.val) = ∑ a, w a := by + have hh : (∑ a : {a // ¬P a}, w a.val) = 0 := by + apply Finset.sum_eq_zero + intro a _ + exact hsupp a.val a.property + simpa only [hh, add_zero] using (Fintype.sum_subtype_add_sum_subtype P w) + +/-- No mass is lost in retaining only compatible pairs. -/ +theorem compatible_jointLaw_mem_simplex {A B C : Type*} [Fintype A] [Fintype B] [DecidableEq C] + {p : A → ℝ} {q : B → ℝ} (hp : p ∈ probabilitySimplex A) (hq : q ∈ probabilitySimplex B) + (f : A → C) (g : B → C) (hcompat : ∀ c, fiberMass p f c = fiberMass q g c) : + (fun z : {z : A × B // f z.1=g z.2} => jointLaw p q f g z.val) ∈ + probabilitySimplex {z : A × B // f z.1=g z.2} := by + refine ⟨fun z => jointLaw_nonneg hp.1 hq.1 f g z.val, ?_⟩ + rw [sum_subtype_supported (fun z : A × B => f z.1=g z.2) (jointLaw p q f g) + (by intro z hz; simp [jointLaw, hz])] + exact (jointLaw_mem_simplex hp hq f g hcompat).2 + +theorem fiberMass_sum {A C : Type*} [Fintype A] [Fintype C] [DecidableEq C] + (p : A → ℝ) (f : A → C) : ∑ c, fiberMass p f c = ∑ a, p a := by + unfold fiberMass + rw [Finset.sum_comm] + simp + +theorem fiberMass_expect {A C : Type*} [Fintype A] [Fintype C] [DecidableEq C] + (p : A → ℝ) (f : A → C) (h : C → ℝ) : + ∑ c, fiberMass p f c * h c = ∑ a, p a*h (f a) := by + unfold fiberMass + simp_rw [Finset.sum_mul] + rw [Finset.sum_comm] + apply Finset.sum_congr rfl + intro a _ + simp only [ite_mul, zero_mul] + simp + +theorem fiberMass_mem_simplex {A C : Type*} [Fintype A] [Fintype C] [DecidableEq C] + {p : A → ℝ} (hp : p ∈ probabilitySimplex A) (f : A → C) : + fiberMass p f ∈ probabilitySimplex C := + ⟨fiberMass_nonneg hp.1 f, (fiberMass_sum p f).trans hp.2⟩ + +theorem jointLaw_expect_first {A B C : Type*} [Fintype A] [Fintype B] [DecidableEq C] + {p : A → ℝ} {q : B → ℝ} (hp : ∀ a, 0 ≤ p a) + (f : A → C) (g : B → C) (hcompat : ∀ c, fiberMass p f c = fiberMass q g c) + (h : A → ℝ) : ∑ z : A × B, jointLaw p q f g z * h z.1 = ∑ a, p a*h a := by + rw [Fintype.sum_prod_type] + simp_rw [← Finset.sum_mul, jointLaw_first hp f g hcompat] + +theorem jointLaw_expect_second {A B C : Type*} [Fintype A] [Fintype B] [DecidableEq C] + {p : A → ℝ} {q : B → ℝ} (hq : ∀ b, 0 ≤ q b) + (f : A → C) (g : B → C) (hcompat : ∀ c, fiberMass p f c = fiberMass q g c) + (h : B → ℝ) : ∑ z : A × B, jointLaw p q f g z * h z.2 = ∑ b, q b*h b := by + rw [Fintype.sum_prod_type, Finset.sum_comm] + simp_rw [← Finset.sum_mul, jointLaw_second hq f g hcompat] + +theorem compatible_jointLaw_expect_first {A B C : Type*} [Fintype A] [Fintype B] [DecidableEq C] + {p : A → ℝ} {q : B → ℝ} (hp : ∀ a, 0 ≤ p a) + (f : A → C) (g : B → C) (hcompat : ∀ c, fiberMass p f c = fiberMass q g c) + (h : A → ℝ) : + ∑ z : {z : A × B // f z.1=g z.2}, jointLaw p q f g z.val * h z.val.1 = ∑ a, p a*h a := by + rw [sum_subtype_supported (fun z : A × B => f z.1=g z.2) + (fun z => jointLaw p q f g z * h z.1) + (by intro z hz; simp [jointLaw, hz])] + exact jointLaw_expect_first hp f g hcompat h + +theorem compatible_jointLaw_expect_second {A B C : Type*} [Fintype A] [Fintype B] [DecidableEq C] + {p : A → ℝ} {q : B → ℝ} (hq : ∀ b, 0 ≤ q b) + (f : A → C) (g : B → C) (hcompat : ∀ c, fiberMass p f c = fiberMass q g c) + (h : B → ℝ) : + ∑ z : {z : A × B // f z.1=g z.2}, jointLaw p q f g z.val * h z.val.2 = ∑ b, q b*h b := by + rw [sum_subtype_supported (fun z : A × B => f z.1=g z.2) + (fun z => jointLaw p q f g z * h z.2) + (by intro z hz; simp [jointLaw, hz])] + exact jointLaw_expect_second hq f g hcompat h + +end MatchingEntropy + +end + +end OAI diff --git a/lean/OAI/Combinatorics/PerfectMatching/Covariance.lean b/lean/OAI/Combinatorics/PerfectMatching/Covariance.lean new file mode 100644 index 0000000000000000000000000000000000000000..71ddebbeb74ea9bf5683e9c31645830b5c6d104a --- /dev/null +++ b/lean/OAI/Combinatorics/PerfectMatching/Covariance.lean @@ -0,0 +1,216 @@ +import OAI.Combinatorics.PerfectMatching.Simplex + +namespace OAI + +/-! +Positive semidefinite covariance matrices, rank, trace, and a spectral inequality. +-/ + +noncomputable section + +open scoped BigOperators Topology +open Filter + +namespace MatchingEntropy + +open Matrix + +variable {A I : Type*} [Fintype A] [Fintype I] [DecidableEq A] [DecidableEq I] + +def weightedColumns (p : A → ℝ) (b : A → I → ℝ) : Matrix I A ℝ := + fun i a => Real.sqrt (p a) * b a i + +def covariance (p : A → ℝ) (b : A → I → ℝ) : Matrix I I ℝ := + weightedColumns p b * (weightedColumns p b)ᵀ + +omit [DecidableEq A] [DecidableEq I] in +theorem covariance_posSemidef (p : A → ℝ) (b : A → I → ℝ) : + (covariance p b).PosSemidef := by + simpa only [covariance, conjTranspose_eq_transpose_of_trivial] using + posSemidef_self_mul_conjTranspose (weightedColumns p b) + +omit [Fintype I] [DecidableEq A] [DecidableEq I] in +theorem covariance_entry {p : A → ℝ} (hp : ∀ a, 0 ≤ p a) (b : A → I → ℝ) (i j : I) : + covariance p b i j = ∑ a, p a*b a i*b a j := by + unfold covariance + rw [Matrix.mul_apply] + apply Finset.sum_congr rfl + intro a _ + simp only [weightedColumns, Matrix.transpose_apply] + calc + _ = (Real.sqrt (p a))^2 * b a i * b a j := by ring + _ = _ := by rw [Real.sq_sqrt (hp a)] + +omit [DecidableEq A] [DecidableEq I] in +theorem covariance_mulVec {p : A → ℝ} (hp : ∀ a, 0 ≤ p a) (b : A → I → ℝ) + (u : I → ℝ) (i : I) : + (covariance p b *ᵥ u) i = ∑ a, p a*b a i*(b a ⬝ᵥ u) := by + simp only [Matrix.mulVec, dotProduct, covariance_entry hp, Finset.sum_mul] + rw [Finset.sum_comm] + apply Finset.sum_congr rfl + intro a _ + rw [Finset.mul_sum] + apply Finset.sum_congr rfl + intro j _ + ring + +omit [DecidableEq A] [DecidableEq I] in +theorem covariance_quadratic {p : A → ℝ} (hp : ∀ a, 0 ≤ p a) (b : A → I → ℝ) + (u : I → ℝ) : u ⬝ᵥ (covariance p b *ᵥ u) = ∑ a, p a*(b a ⬝ᵥ u)^2 := by + rw [dotProduct] + simp_rw [covariance_mulVec hp, Finset.mul_sum] + rw [Finset.sum_comm] + apply Finset.sum_congr rfl + intro a _ + calc + (∑ i, u i*(p a*b a i*(b a ⬝ᵥ u))) = + (∑ i, b a i*u i)*(p a*(b a ⬝ᵥ u)) := by + rw [Finset.sum_mul] + apply Finset.sum_congr rfl + intro i _ + ring + _ = p a*(b a ⬝ᵥ u)^2 := by rw [← dotProduct]; ring + +def weightedDirectionSpace (p : A → ℝ) (b : A → I → ℝ) : Submodule ℝ (I → ℝ) := + Submodule.span ℝ (Set.range fun a : {a // 0 < p a} => b a.val) + +omit [Fintype A] [Fintype I] [DecidableEq A] [DecidableEq I] in +theorem weightedColumns_span {p : A → ℝ} (hp : ∀ a, 0 ≤ p a) (b : A → I → ℝ) : + Submodule.span ℝ (Set.range (weightedColumns p b).col) = weightedDirectionSpace p b := by + apply le_antisymm + · apply Submodule.span_le.mpr + rintro _ ⟨a,rfl⟩ + by_cases ha : 0 < p a + · have hb : b a ∈ weightedDirectionSpace p b := Submodule.subset_span ⟨⟨a,ha⟩,rfl⟩ + exact Submodule.smul_mem _ (Real.sqrt (p a)) hb + · have hz := le_antisymm (le_of_not_gt ha) (hp a) + have he : (weightedColumns p b).col a = 0 := by + ext i + simp [weightedColumns, Matrix.col, hz] + rw [he] + exact (weightedDirectionSpace p b).zero_mem + · apply Submodule.span_le.mpr + rintro _ ⟨a,rfl⟩ + have hb : (weightedColumns p b).col a.val ∈ + Submodule.span ℝ (Set.range (weightedColumns p b).col) := Submodule.subset_span ⟨a.val,rfl⟩ + have hs : Real.sqrt (p a.val) ≠ 0 := ne_of_gt (Real.sqrt_pos.2 a.property) + have hh := Submodule.smul_mem _ (Real.sqrt (p a.val))⁻¹ hb + have he : (Real.sqrt (p a.val))⁻¹ • (weightedColumns p b).col a.val = b a.val := by + ext i + change (Real.sqrt (p a.val))⁻¹ * (Real.sqrt (p a.val) * b a.val i) = _ + rw [← mul_assoc, inv_mul_cancel₀ hs, one_mul] + rw [he] at hh + exact hh + +omit [DecidableEq A] [DecidableEq I] in +theorem covariance_rank {p : A → ℝ} (hp : ∀ a, 0 ≤ p a) (b : A → I → ℝ) : + (covariance p b).rank = Module.finrank ℝ (weightedDirectionSpace p b) := by + rw [covariance, rank_self_mul_transpose, rank_eq_finrank_span_cols, weightedColumns_span hp] + +def normalizedCentered (v : A → I → ℝ) (x : I → ℝ) (a : A) (i : I) : ℝ := + (v a i-x i)/Real.sqrt (x i) + +omit [Fintype I] [DecidableEq A] [DecidableEq I] in +theorem normalizedCentered_mean {p : A → ℝ} (hp : ∑ a, p a = 1) + (v : A → I → ℝ) (x : I → ℝ) (hx : ∀ i, ∑ a, p a*v a i = x i) (i : I) : + ∑ a, p a*normalizedCentered v x a i = 0 := by + simp only [normalizedCentered, ← mul_div_assoc, mul_sub, ← Finset.sum_div, + Finset.sum_sub_distrib, ← Finset.sum_mul, hp, one_mul, hx, sub_self, zero_div] + +omit [Fintype I] [DecidableEq A] [DecidableEq I] in +theorem normalizedCentered_variance {p : A → ℝ} (hp : ∑ a, p a = 1) + (v : A → I → ℝ) (hv : ∀ a i, (v a i)^2=v a i) (x : I → ℝ) + (hx : ∀ i, ∑ a, p a*v a i = x i) (hxp : ∀ i, 0 < x i) (i : I) : + ∑ a, p a*(normalizedCentered v x a i)^2 = 1-x i := by + have heq : ∀ a, p a*(normalizedCentered v x a i)^2 = + (p a*v a i-2*x i*(p a*v a i)+(x i)^2*p a)/x i := by + intro a + rw [normalizedCentered, div_pow, Real.sq_sqrt (hxp i).le, ← mul_div_assoc] + congr 1 + calc + _ = p a*(v a i)^2-2*x i*(p a*v a i)+(x i)^2*p a := by ring + _ = _ := by rw [hv] + simp_rw [heq] + rw [← Finset.sum_div] + simp only [Finset.sum_add_distrib, Finset.sum_sub_distrib, ← Finset.mul_sum, + hx, hp, mul_one] + field_simp [ne_of_gt (hxp i)] + ring + +omit [DecidableEq A] [DecidableEq I] in +theorem normalized_covariance_trace {p : A → ℝ} (hp : p ∈ probabilitySimplex A) + (v : A → I → ℝ) (hv : ∀ a i, (v a i)^2=v a i) (x : I → ℝ) + (hx : ∀ i, ∑ a, p a*v a i = x i) (hxp : ∀ i, 0 < x i) : + (covariance p (normalizedCentered v x)).trace = Fintype.card I - ∑ i, x i := by + unfold Matrix.trace Matrix.diag + simp_rw [covariance_entry hp.1] + have heq : ∀ i, (∑ a, p a*normalizedCentered v x a i*normalizedCentered v x a i) = 1-x i := by + intro i + simpa only [pow_two, mul_assoc] using + normalizedCentered_variance hp.2 v hv x hx hxp i + simp_rw [heq] + simp + +/-- Spectral form of the second-variation step, using the full (possibly +singular) covariance rather than introducing an inverse on its image. -/ +theorem covariance_rank_bound {ι : Type*} [Fintype ι] [DecidableEq ι] + {C : Matrix ι ι ℝ} (hC : C.PosSemidef) {a : ℝ} + (hsecond : ∀ u : ι → ℝ, + (a - 1) * ((C *ᵥ u) ⬝ᵥ (C *ᵥ u)) + u ⬝ᵥ (C *ᵥ u) ≤ 0) : + (C.rank : ℝ) ≤ (1-a) * C.trace := by + let eig := hC.isHermitian.eigenvalues + have heig : ∀ i, 0 ≤ eig i := hC.eigenvalues_nonneg + have hone : ∀ i, eig i ≠ 0 → 1 ≤ (1-a) * eig i := by + intro i hi + let v : ι → ℝ := hC.isHermitian.eigenvectorBasis i + have hv : v ⬝ᵥ v = 1 := by + have hn := hC.isHermitian.eigenvectorBasis.orthonormal.1 i + have hi : inner ℝ (hC.isHermitian.eigenvectorBasis i) + (hC.isHermitian.eigenvectorBasis i) = 1 := by + rw [real_inner_self_eq_norm_sq, hn] + norm_num + simpa only [EuclideanSpace.inner_eq_star_dotProduct, star_trivial] using hi + have he : C *ᵥ v = eig i • v := hC.isHermitian.mulVec_eigenvectorBasis i + have hs := hsecond v + rw [he] at hs + simp only [smul_dotProduct, dotProduct_smul, smul_eq_mul, hv, mul_one] at hs + have hp : 0 < eig i := lt_of_le_of_ne (heig i) (Ne.symm hi) + nlinarith + rw [hC.isHermitian.rank_eq_card_non_zero_eigs, + hC.isHermitian.trace_eq_sum_eigenvalues] + change (Fintype.card {i // eig i ≠ 0} : ℝ) ≤ (1-a) * ∑ i, eig i + rw [Finset.mul_sum] + calc + _ = ∑ i : {i // eig i ≠ 0}, (1 : ℝ) := by simp + _ ≤ ∑ i : {i // eig i ≠ 0}, (1-a) * eig i := Finset.sum_le_sum fun i _ => hone i i.property + _ = ∑ i, (1-a) * eig i := by + have hz : (∑ i : {i // ¬ eig i ≠ 0}, (1-a) * eig i) = 0 := by + apply Finset.sum_eq_zero + intro i _ + rw [not_ne_iff.mp i.property, mul_zero] + simpa only [hz, add_zero] using + (Fintype.sum_subtype_add_sum_subtype (fun i => eig i ≠ 0) + (fun i => (1-a) * eig i)) + +/-- The numerical contradiction following covariance rank and trace. -/ +theorem covariance_contradiction {ι : Type*} [Fintype ι] [DecidableEq ι] + {C : Matrix ι ι ℝ} (hC : C.PosSemidef) {a m s : ℝ} + (hm : 0 < m) (hs : 8*m < s) (hrank : s-4*m ≤ C.rank) + (htrace : C.trace = s-m) (ha : 8*m/s ≤ a) + (hsecond : ∀ u : ι → ℝ, + (a-1) * ((C *ᵥ u) ⬝ᵥ (C *ᵥ u)) + u ⬝ᵥ (C *ᵥ u) ≤ 0) : False := by + have hb := covariance_rank_bound hC hsecond + rw [htrace] at hb + have hsp : 0 < s := by linarith + have hsmp : 0 < s-m := by linarith + have hau : a ≤ 3*m/(s-m) := by + apply (le_div_iff₀ hsmp).mpr + nlinarith + have hcross := (div_le_div_iff₀ hsp hsmp).mp (ha.trans hau) + nlinarith [mul_pos hm (show 0 < 5*s-8*m by linarith)] + +end MatchingEntropy + +end + +end OAI diff --git a/lean/OAI/Combinatorics/PerfectMatching/Duality.lean b/lean/OAI/Combinatorics/PerfectMatching/Duality.lean new file mode 100644 index 0000000000000000000000000000000000000000..9eb8bdbbd4ed03db90ebf8cfef84ee8dfaf052a1 --- /dev/null +++ b/lean/OAI/Combinatorics/PerfectMatching/Duality.lean @@ -0,0 +1,136 @@ +import OAI.Combinatorics.PerfectMatching.Optimizer + +namespace OAI + +/-! +Finite exponential tilts, partition functions, and entropy duality on a face. +-/ + +noncomputable section + +open scoped BigOperators Topology +open Filter + +namespace MatchingEntropy + +variable {V E : Type*} [Fintype V] [Fintype E] [DecidableEq V] [DecidableEq E] + +/-- Finite exponential partition function, based on a probability law p. -/ +def partition {ι : Type*} [Fintype ι] (p a : ι → ℝ) (t : ℝ) : ℝ := + ∑ i, p i * Real.exp (t*a i) + +def tiltedLaw {ι : Type*} [Fintype ι] (p a : ι → ℝ) (t : ℝ) (i : ι) : ℝ := + p i * Real.exp (t*a i) / partition p a t + +theorem partition_pos {ι : Type*} [Fintype ι] {p : ι → ℝ} + (hp : p ∈ probabilitySimplex ι) (a : ι → ℝ) (t : ℝ) : 0 < partition p a t := by + obtain ⟨i, _, hi⟩ := (Finset.sum_pos_iff_of_nonneg (fun i (_ : i ∈ Finset.univ) => hp.1 i)).mp + (show 0 < ∑ i, p i by rw [hp.2]; norm_num) + exact (Finset.sum_pos_iff_of_nonneg (fun i _ => mul_nonneg (hp.1 i) (Real.exp_pos _).le)).mpr + ⟨i, Finset.mem_univ _, mul_pos hi (Real.exp_pos _)⟩ + +@[simp] theorem partition_zero {ι : Type*} [Fintype ι] {p : ι → ℝ} + (hp : p ∈ probabilitySimplex ι) (a : ι → ℝ) : partition p a 0 = 1 := by + simpa only [partition, zero_mul, Real.exp_zero, mul_one] using hp.2 + +theorem tiltedLaw_mem_simplex {ι : Type*} [Fintype ι] {p : ι → ℝ} + (hp : p ∈ probabilitySimplex ι) (a : ι → ℝ) (t : ℝ) : + tiltedLaw p a t ∈ probabilitySimplex ι := by + refine ⟨fun i => div_nonneg (mul_nonneg (hp.1 i) (Real.exp_pos _).le) + (partition_pos hp a t).le, ?_⟩ + simp only [tiltedLaw, ← Finset.sum_div] + exact div_self (partition_pos hp a t).ne' + +/-- Gibbs' variational inequality for the explicit finite partition function, +including all boundary laws supported on p. -/ +theorem entropy_partition_bound {ι : Type*} [Fintype ι] {p q : ι → ℝ} + (hp : p ∈ probabilitySimplex ι) (hq : q ∈ probabilitySimplex ι) + (hsupp : ∀ i, p i = 0 → q i = 0) (a : ι → ℝ) (t : ℝ) : + entropy q ≤ Real.log (partition p a t) - ∑ i, q i*Real.log (p i) - + t * ∑ i, q i*a i := by + have hlog : ∀ i, q i * Real.log (tiltedLaw p a t i) = + q i * Real.log (p i) + t*(q i*a i) - q i*Real.log (partition p a t) := by + intro i + by_cases hi : p i = 0 + · simp [hsupp i hi] + · rw [tiltedLaw, Real.log_div (mul_ne_zero hi (Real.exp_ne_zero _)) + (partition_pos hp a t).ne', Real.log_mul hi (Real.exp_ne_zero _), Real.log_exp] + ring + calc + entropy q ≤ -∑ i, q i*Real.log (tiltedLaw p a t i) := + entropy_le_crossEntropy (tiltedLaw_mem_simplex hp a t) hq (by + intro i hi + have hii : p i = 0 := by + have := (div_eq_zero_iff).mp hi + rcases this with hh | hh + · exact (mul_eq_zero.mp hh).resolve_right (Real.exp_ne_zero _) + · exact ((partition_pos hp a t).ne' hh).elim + exact hsupp i hii) + _ = _ := by + simp_rw [hlog] + rw [Finset.sum_sub_distrib, Finset.sum_add_distrib, ← Finset.mul_sum, + ← Finset.sum_mul, hq.2, one_mul] + ring + + +/-- A score affine in the matching vector; the constant permits centering +without changing the duality calculation. -/ +def linearScore (G : LooplessGraph V E) (u : E → ℝ) (c : ℝ) (M : G.Matching) : ℝ := + (∑ e, u e * G.indicator M e) - c + +omit [Fintype V] [DecidableEq V] in +theorem sum_mean_assoc (G : LooplessGraph V E) (p : G.Matching → ℝ) (u : E → ℝ) : + (∑ M, p M * (∑ e, u e * G.indicator M e)) = ∑ e, u e * G.mean p e := by + simp only [LooplessGraph.mean, Finset.mul_sum] + rw [Finset.sum_comm] + apply Finset.sum_congr rfl + intro e _ + apply Finset.sum_congr rfl + intro M _ + ring + +omit [Fintype V] [DecidableEq V] in +theorem linearScore_expectation (G : LooplessGraph V E) (p : G.Matching → ℝ) + (u : E → ℝ) (c : ℝ) : + (∑ M, p M * linearScore G u c M) = + (∑ e, u e * G.mean p e) - c * ∑ M, p M := by + simp only [linearScore, mul_sub, Finset.sum_sub_distrib, ← Finset.sum_mul] + rw [sum_mean_assoc] + ring + +omit [Fintype V] [DecidableEq V] in +/-- A genuine upper bound on the actual maximum entropy at every mean in the +optimizer's face. This is proved from Gibbs' inequality, not assumed as a +replacement definition of H. -/ +theorem matching_entropy_dual_bound (G : LooplessGraph V E) {y : E → ℝ} + {p : G.Matching → ℝ} (hp : p ∈ G.feasibleLaws y) + (hopt : entropy p = maxMatchingEntropy G y) + {r : G.Matching → ℝ} (hr : r ∈ probabilitySimplex G.Matching) + (hrsupport : ∀ M, p M = 0 → r M = 0) + (u : E → ℝ) (c t : ℝ) : + maxMatchingEntropy G (G.mean r) ≤ + Real.log (partition p (linearScore G u c) t) - ∑ M, r M * Real.log (p M) - + t * ∑ M, r M * linearScore G u c M := by + obtain ⟨q, hq, heq⟩ := maxMatchingEntropy_attained G (G.mean_mem_polytope hr) + have hsuppq := matching_optimizer_face_support G hp hopt hq.1 hr hq.2 hrsupport + have hmean : G.mean (q-r) = 0 := by + change G.meanLinear (q-r) = 0 + rw [map_sub] + change G.mean q-G.mean r = 0 + rw [hq.2, sub_self] + have hsum : ∑ M, (q-r) M = 0 := by + simp only [Pi.sub_apply, Finset.sum_sub_distrib, hq.1.2, hr.2, sub_self] + have hlog := matching_optimizer_log_annihilates G hp hopt (q-r) hsum hmean + (fun M hM => by simp [hsuppq M hM, hrsupport M hM]) + simp only [Pi.sub_apply, sub_mul, Finset.sum_sub_distrib, sub_eq_zero] at hlog + have hscore : (∑ M, q M*linearScore G u c M) = ∑ M, r M*linearScore G u c M := by + rw [linearScore_expectation, linearScore_expectation, hq.2, hq.1.2, hr.2] + rw [← heq] + simpa only [hlog, hscore] using entropy_partition_bound hp.1 hq.1 hsuppq + (linearScore G u c) t + +end MatchingEntropy + +end + +end OAI diff --git a/lean/OAI/Combinatorics/PerfectMatching/DyadicEntropy.lean b/lean/OAI/Combinatorics/PerfectMatching/DyadicEntropy.lean new file mode 100644 index 0000000000000000000000000000000000000000..9173c4a88e4a95207d30f152a4a1d75c40c493ee --- /dev/null +++ b/lean/OAI/Combinatorics/PerfectMatching/DyadicEntropy.lean @@ -0,0 +1,149 @@ +import OAI.Combinatorics.PerfectMatching.DyadicEnvelope + +namespace OAI + +section + +namespace BinaryMatching.Algorithm +noncomputable section +open Finset + +lemma concave_affine_chord {S : Set ℝ} {f : ℝ → ℝ} (hf : ConcaveOn ℝ S f) + {l u t p c : ℝ} (hl : l∈S) (hu : u∈S) (hlu : l exact Or.inl (by simpa only [dyadic_zero] using ht.2) + | succ k ih => + by_cases h : t≤dyadic (k+1) + · exact Or.inl h + · right + rcases ih with h'|⟨j,hj,hjt⟩ + · exact ⟨k,Nat.lt_succ_self k,le_of_not_ge h,h'⟩ + · exact ⟨j,Nat.lt_succ_of_lt hj,hjt⟩ + +def phi (t : ℝ) : ℝ := Real.negMulLog t / Real.log 2 + +lemma log_two_pos : 0 if b then t else 1-t) ∈ MatchingEntropy.probabilitySimplex Bool := by + constructor + · intro b; cases b <;> simp [ht.1,sub_nonneg.mpr ht.2] + · simp + have hh := MatchingEntropy.entropy_le_log_card hp + simp only [MatchingEntropy.entropy,Fintype.sum_bool,Fintype.card_bool,Bool.false_eq_true, + ↓reduceIte,Nat.cast_ofNat] at hh + have hn := Real.negMulLog_nonneg (sub_nonneg.mpr ht.2) (by linarith [ht.1] : 1-t≤1) + unfold phi + apply (div_le_one log_two_pos).2 + linarith + +lemma phi_mul (u v : ℝ) : phi (u*v)=v*phi u+u*phi v := by + simp only [phi,Real.negMulLog_mul]; ring + +lemma phi_lower_first (k : ℕ) {t : ℝ} (ht : t∈Set.Icc 0 (dyadic k)) : + (k:ℝ)*t ≤ phi t := by + simpa only [add_zero] using concave_affine_chord phi_concave + (Set.mem_Ici.mpr le_rfl) (Set.mem_Ici.mpr (dyadic_nonneg k)) (dyadic_pos k) ht + (p:=(k:ℝ)) (c:=0) (by simp [phi_zero]) (by rw [phi_dyadic]; ring) + +lemma phi_lower_chord (j : ℕ) {t : ℝ} (ht : t∈Set.Icc (dyadic (j+1)) (dyadic j)) : + ((j:ℝ)-1)*t+dyadic j≤phi t := by + apply concave_affine_chord phi_concave (Set.mem_Ici.mpr (dyadic_nonneg _)) + (Set.mem_Ici.mpr (dyadic_nonneg _)) + (show dyadic (j+1) linarith [hjt.2] + +end +end BinaryMatching.Algorithm +end + +end OAI diff --git a/lean/OAI/Combinatorics/PerfectMatching/DyadicEnvelope.lean b/lean/OAI/Combinatorics/PerfectMatching/DyadicEnvelope.lean new file mode 100644 index 0000000000000000000000000000000000000000..eac73af02541af316dbb2c37a1e195d946f2b9ca --- /dev/null +++ b/lean/OAI/Combinatorics/PerfectMatching/DyadicEnvelope.lean @@ -0,0 +1,148 @@ +import OAI.Computability.MatchingCount.BinaryParser + +namespace OAI + +section + +namespace BinaryMatching.Algorithm +noncomputable section +open Finset + +def Piece.evalReal (p : Piece) (t : ℝ) : ℝ := (p.slope:ℝ)*t+(p.constant:ℝ) + +def selectedReal (k : ℕ) (t : ℝ) : Piece := by + classical + exact ((pieces k).argmin (fun p => p.evalReal t)).getD ⟨k,0⟩ + +def psiReal (k : ℕ) (t : ℝ) : ℝ := (selectedReal k t).evalReal t + +def dyadic (j : ℕ) : ℝ := (2:ℝ)⁻¹^j + +lemma pieces_nonempty (k : ℕ) : pieces k ≠ [] := by simp [pieces] + +lemma selectedPiece_mem_argmin (k : ℕ) (t : ℚ) : + selectedPiece k t ∈ (pieces k).argmin (fun p => p.eval t) := by + unfold selectedPiece + cases he : (pieces k).argmin (fun p => p.eval t) with + | none => exact (pieces_nonempty k (List.argmin_eq_none.mp he)).elim + | some p => simp + +lemma selectedReal_mem_argmin (k : ℕ) (t : ℝ) : + selectedReal k t ∈ (pieces k).argmin (fun p => p.evalReal t) := by + classical + unfold selectedReal + cases he : (pieces k).argmin (fun p => p.evalReal t) with + | none => exact (pieces_nonempty k (List.argmin_eq_none.mp he)).elim + | some p => simp + +lemma psiReal_le_piece (k : ℕ) (t : ℝ) (p : Piece) (hp : p∈pieces k) : + psiReal k t ≤ p.evalReal t := + List.le_of_mem_argmin hp (selectedReal_mem_argmin k t) + +lemma le_psiReal (k : ℕ) (t b : ℝ) (h : ∀ p∈pieces k,b≤p.evalReal t) : + b ≤ psiReal k t := h _ (List.argmin_mem (selectedReal_mem_argmin k t)) + +lemma realPsi_cast (k : ℕ) (t : ℚ) : psiReal k (t:ℝ)=(psi k t:ℝ) := by + have cast_eval (p : Piece) : p.evalReal (t:ℝ)=(p.eval t:ℝ) := by + simp [Piece.eval,Piece.evalReal] + apply le_antisymm + · have h := psiReal_le_piece k (t:ℝ) _ (List.argmin_mem (selectedPiece_mem_argmin k t)) + simpa only [cast_eval,psi] using h + · apply le_psiReal + intro p hp + rw [cast_eval] + exact_mod_cast (List.le_of_mem_argmin hp (selectedPiece_mem_argmin k t)) + +lemma psiReal_concave (k : ℕ) : ConcaveOn ℝ Set.univ (psiReal k) := by + refine ⟨convex_univ,?_⟩ + intro x _ y _ a b ha hb hab + apply le_psiReal + intro p hp + have hx := psiReal_le_piece k x p hp + have hy := psiReal_le_piece k y p hp + simp only [smul_eq_mul] + calc + a*psiReal k x+b*psiReal k y ≤ a*p.evalReal x+b*p.evalReal y := by gcongr + _ = p.evalReal (a*x+b*y) := by + simp only [Piece.evalReal] + have hh := congrArg (fun t => t*(p.constant:ℝ)) hab + nlinarith [hh] + +lemma mem_pieces (k : ℕ) (p : Piece) : + p∈pieces k ↔ p=⟨k,0⟩ ∨ ∃ j rw [hj,dyadic,pow_add] + rw [Nat.add_sub_cancel_left] + change (2:ℝ)⁻¹^l=(2:ℝ)^(j-l)*((2:ℝ)⁻¹^l*(2:ℝ)⁻¹^(j-l)) + calc + _ = (2:ℝ)⁻¹^l*1 := (mul_one _).symm + _ = _ := by rw [←dyadic_mul_pow (j-l)]; unfold dyadic; ring + +lemma chord_above_knot (l j : ℕ) : + (j:ℝ)*dyadic j ≤ ((l:ℝ)-1)*dyadic j+dyadic l := by + rcases lt_trichotomy l j with h|h|h + · have hp : 1+(j-l:ℕ) ≤ (2:ℕ)^(j-l) := by + have hh := one_add_mul_le_pow (show (-2:ℝ)≤1 by norm_num) (j-l) + norm_num at hh + exact_mod_cast hh + have hpR : (1:ℝ)+(j:ℝ)-(l:ℝ) ≤ (2:ℝ)^(j-l) := by + have := Nat.cast_le (α:=ℝ).mpr hp + push_cast [Nat.cast_sub h.le] at this + linarith + rw [dyadic_scale j l h.le] + nlinarith [mul_le_mul_of_nonneg_right hpR (dyadic_nonneg j)] + · subst l; ring_nf; rfl + · have hh : (j:ℝ)+1≤l := by exact_mod_cast h + nlinarith [dyadic_nonneg j,dyadic_nonneg l] + +lemma psiReal_knot (k j : ℕ) (hj : j≤k) : psiReal k (dyadic j)=(j:ℝ)*dyadic j := by + apply le_antisymm + · rcases lt_or_eq_of_le hj with h|h + · have hh := psiReal_le_piece k (dyadic j) _ (chord_mem_pieces k j h) + rw [chord_eval] at hh + nlinarith + · subst j + simpa only [first_eval] using psiReal_le_piece k (dyadic k) _ (first_mem_pieces k) + · apply le_psiReal + intro p hp + rcases (mem_pieces k p).1 hp with rfl|⟨l,_,rfl⟩ + · rw [first_eval] + exact mul_le_mul_of_nonneg_right (by exact_mod_cast hj) (dyadic_nonneg j) + · rw [chord_eval]; exact chord_above_knot l j + +lemma psiReal_zero (k : ℕ) : psiReal k 0=0 := by + apply le_antisymm + · simpa only [first_eval,mul_zero] using psiReal_le_piece k 0 _ (first_mem_pieces k) + · apply le_psiReal + intro p hp + rcases (mem_pieces k p).1 hp with rfl|⟨j,_,rfl⟩ + · simp [first_eval] + · simpa only [chord_eval,mul_zero,zero_add] using dyadic_nonneg j + +end +end BinaryMatching.Algorithm +end + +end OAI diff --git a/lean/OAI/Combinatorics/PerfectMatching/ElementaryCount.lean b/lean/OAI/Combinatorics/PerfectMatching/ElementaryCount.lean new file mode 100644 index 0000000000000000000000000000000000000000..332f0f5aa50c35da505602612d3e3eebceaf6a9b --- /dev/null +++ b/lean/OAI/Combinatorics/PerfectMatching/ElementaryCount.lean @@ -0,0 +1,136 @@ +import OAI.Combinatorics.PerfectMatching.CountCorrect + +namespace OAI + +section + +namespace BinaryMatching.Algorithm +noncomputable section +open Finset MatchingEntropy + +lemma count_zero_vertices (G : Input) (hn : G.n=0) : count G=1 := by + classical + let M : (completeGraph G.n).Matching := ⟨∅,fun v => by have := v.isLt; omega⟩ + have hM (N : (completeGraph G.n).Matching) : N=M := by + apply Subtype.ext + apply Finset.eq_empty_of_forall_notMem + intro e _ + have := e.val.1.isLt + omega + unfold count + rw [sum_eq_single M] + · simp [M] + · intro N _ hne + exact (hne (hM N)).elim + · simp + +lemma count_odd_vertices (G : Input) (hn : Odd G.n) : count G=0 := by + classical + have hempty : IsEmpty (completeGraph G.n).Matching := ⟨fun M => by + have hh := (completeGraph G.n).matching_card_twice M + simp only [Fintype.card_fin] at hh + obtain ⟨r,hr⟩ := hn + omega⟩ + simp [count] + +lemma count_two_vertices (G : Input) (hn : G.n=2) : count G=rawMultiplicity G 0 1 := by + classical + let e : Pair G.n := ⟨(⟨0,by omega⟩,⟨1,by omega⟩),by simp⟩ + have heq (f : Pair G.n) : f=e := by + apply Subtype.ext + apply Prod.ext <;> apply Fin.ext + · have hh := f.property; have h1 := f.val.1.isLt; have h2 := f.val.2.isLt + dsimp [e] at hh ⊢; omega + · have hh := f.property; have h1 := f.val.1.isLt; have h2 := f.val.2.isLt + dsimp [e] at hh ⊢; omega + have heinc (v : Fin G.n) : (completeGraph G.n).Incident v e := by + have hv := v.isLt + change e.val.1=v ∨ e.val.2=v + by_cases hz : v.val=0 + · left; apply Fin.ext; exact hz.symm + · right; apply Fin.ext; dsimp [e]; omega + let M : (completeGraph G.n).Matching := ⟨{e},fun v => ⟨e,⟨by simp,heinc v⟩, + fun _ h => by simpa only [mem_singleton] using h.1⟩⟩ + have hM (N : (completeGraph G.n).Matching) : N=M := by + apply Subtype.ext + apply Finset.ext + intro f + have hfn := heq f + obtain ⟨g,hg,_⟩ := N.property e.val.1 + have hgn := heq g + have hmem : e∈N.val := hgn ▸ hg.1 + simp only [M,mem_singleton,hfn] + exact iff_true_intro hmem + unfold count + rw [sum_eq_single M] + · simp only [M,prod_singleton] + unfold multiplicity rawMultiplicity + dsimp [e] + cases G.records.find? (fun r => r.left=0 && r.right=1) <;> rfl + · intro N _ hne + exact (hne (hM N)).elim + · simp + +lemma present_endpoints_covered (G : Input) (e : Pair G.n) (he : 0 < multiplicity G e) : + e.val.1.val∈covered G ∧ e.val.2.val∈covered G := by + unfold multiplicity at he + cases hf : G.records.find? (fun r => r.left=e.val.1.val && r.right=e.val.2.val) with + | none => simp only [hf] at he; omega + | some r => + have hr := List.mem_of_find?_eq_some hf + have hp := List.find?_some hf + simp only [Bool.and_eq_true,decide_eq_true_eq] at hp + simp only [hf] at he + have hr' : r∈G.records.filter (fun r => 0 < r.multiplicity) := by simp [hr,he] + constructor + · simp only [covered,List.mem_toFinset,List.mem_flatMap] + refine ⟨r,hr',?_⟩ + simp [hp.1] + · simp only [covered,List.mem_toFinset,List.mem_flatMap] + refine ⟨r,hr',?_⟩ + simp [hp.2] + +lemma positive_count_covered (G : Input) (hN : 0 < count G) : G.n ≤ (covered G).card := by + obtain ⟨M,hM⟩ := positive_count_valid G hN + have hsub : range G.n ⊆ covered G := by + intro v hv + let w : Fin G.n := ⟨v,mem_range.mp hv⟩ + obtain ⟨e,⟨he,hinc⟩,_⟩ := M.property w + have hep := present_endpoints_covered G e (hM e he) + rcases hinc with h|h + · have hh : e.val.1.val=v := congrArg Fin.val h + simpa only [hh] using hep.1 + · have hh : e.val.2.val=v := congrArg Fin.val h + simpa only [hh] using hep.2 + simpa only [card_range] using card_le_card hsub + +lemma count_zero_of_uncovered (G : Input) (hu : (covered G).card < G.n) : count G=0 := by + by_contra hN + have := positive_count_covered G (Nat.pos_of_ne_zero hN) + omega + +theorem approximate_correct (G : Input) : + approximate G ≤ count G ∧ count G ≤ 2^(9*G.n)*approximate G ∧ + (approximate G=0 ↔ count G=0) := by + unfold approximate + split_ifs with hn0 hodd hn2 hcover + · rw [count_zero_vertices G hn0,hn0] + norm_num + · rw [count_odd_vertices G hodd] + simp + · rw [count_two_vertices G hn2] + refine ⟨le_rfl,?_,Iff.rfl⟩ + exact Nat.le_mul_of_pos_left _ (by positivity) + · rw [count_zero_of_uncovered G hcover] + simp + · have heven : Even G.n := Nat.not_odd_iff_even.mp hodd + have hn : 4 ≤ G.n := by + obtain ⟨r,hr⟩ := heven + omega + exact estimate_correct G hn heven + +end +end BinaryMatching.Algorithm +end + +end OAI diff --git a/lean/OAI/Combinatorics/PerfectMatching/Entropy.lean b/lean/OAI/Combinatorics/PerfectMatching/Entropy.lean new file mode 100644 index 0000000000000000000000000000000000000000..3588758e6f1e4df34fe2a18fe7165b19052af2ad --- /dev/null +++ b/lean/OAI/Combinatorics/PerfectMatching/Entropy.lean @@ -0,0 +1,178 @@ +import OAI.Combinatorics.PerfectMatching.Basic + +namespace OAI + +/-! +Finite Shannon entropy and attainment of its supremum over feasible matching laws. +-/ + +noncomputable section + +open scoped BigOperators Topology +open Filter + +namespace MatchingEntropy + +variable {V E : Type*} [Fintype V] [Fintype E] [DecidableEq V] [DecidableEq E] + +def entropy {ι : Type*} [Fintype ι] (p : ι → ℝ) : ℝ := + ∑ i, Real.negMulLog (p i) + +def marginalEntropy (y : E → ℝ) : ℝ := entropy y + +def maxMatchingEntropy (G : LooplessGraph V E) (y : E → ℝ) : ℝ := + sSup (entropy '' G.feasibleLaws y) + + + +/-- Shannon entropy is the literal sum of negative probability-log-probability terms. -/ +theorem entropy_eq {ι : Type*} [Fintype ι] (p : ι → ℝ) : + entropy p = -(∑ i, p i * Real.log (p i)) := by + simp [entropy, Real.negMulLog, Finset.sum_neg_distrib, neg_mul] + +theorem continuous_entropy {ι : Type*} [Fintype ι] : + Continuous (entropy : (ι → ℝ) → ℝ) := by + unfold entropy + fun_prop + +theorem entropy_nonneg {ι : Type*} [Fintype ι] {p : ι → ℝ} + (hp : p ∈ probabilitySimplex ι) : 0 ≤ entropy p := by + apply Finset.sum_nonneg + intro i _ + exact Real.negMulLog_nonneg (hp.1 i) + (probabilitySimplex_le_one hp i) + +/-- The entropy bound used in the counting reduction, including zero probabilities. -/ +theorem entropy_le_log_card {ι : Type*} [Fintype ι] {p : ι → ℝ} + (hp : p ∈ probabilitySimplex ι) : entropy p ≤ Real.log (Fintype.card ι) := by + have hn : 0 < Fintype.card ι := by + by_contra h + have hz : Fintype.card ι = 0 := Nat.eq_zero_of_not_pos h + have : IsEmpty ι := Fintype.card_eq_zero_iff.mp hz + simpa using hp.2 + have hnR : (0 : ℝ) < Fintype.card ι := by exact_mod_cast hn + have h := Finset.sum_le_sum (s := Finset.univ) (fun i _ ↦ + Real.negMulLog_le_one_sub_self (mul_nonneg hnR.le (hp.1 i))) + simp_rw [Real.negMulLog_mul] at h + rw [Finset.sum_add_distrib, ← Finset.sum_mul, ← Finset.mul_sum, + hp.2, one_mul, Finset.sum_sub_distrib, ← Finset.mul_sum, hp.2] at h + simp only [Finset.sum_const, Finset.card_univ, nsmul_eq_mul, mul_one, sub_self] at h + change Real.negMulLog (Fintype.card ι) + (Fintype.card ι : ℝ) * entropy p ≤ 0 at h + rw [Real.negMulLog] at h + nlinarith + +namespace LooplessGraph + +omit [Fintype V] [DecidableEq V] in +theorem coordinate_mem_Icc (G : LooplessGraph V E) {y : E → ℝ} + (hy : y ∈ G.polytope) (e : E) : y e ∈ Set.Icc (0 : ℝ) 1 := by + obtain ⟨p, hp, rfl⟩ := (G.mem_polytope_iff y).mp hy + constructor + · exact Finset.sum_nonneg (fun M _ ↦ mul_nonneg (hp.1 M) (G.indicator_nonneg M e)) + · calc + ∑ M, p M * G.indicator M e ≤ ∑ M, p M * 1 := + Finset.sum_le_sum (fun M _ ↦ mul_le_mul_of_nonneg_left (G.indicator_le_one M e) (hp.1 M)) + _ = 1 := by simpa using hp.2 + + +omit [Fintype E] [DecidableEq E] in +/-- Counting the two distinct endpoints; parallel identities are never collapsed. -/ +theorem incident_vertex_sum (G : LooplessGraph V E) (e : E) : + (∑ v, if G.Incident v e then (1 : ℕ) else 0) = 2 := by + classical + have he (v : V) : (if G.Incident v e then (1 : ℕ) else 0) = + (if G.left e = v then 1 else 0) + (if G.right e = v then 1 else 0) := by + by_cases hl : G.left e = v <;> by_cases hr : G.right e = v + · exact False.elim (G.loopless e (hl.trans hr.symm)) + · simp [Incident, hl, hr] + · simp [Incident, hl, hr] + · simp [Incident, hl, hr] + simp_rw [he, Finset.sum_add_distrib] + simp + +omit [Fintype V] [Fintype E] [DecidableEq E] in +theorem matching_incident_sum (G : LooplessGraph V E) (M : G.Matching) (v : V) : + (∑ e ∈ M.val, if G.Incident v e then (1 : ℕ) else 0) = 1 := by + classical + obtain ⟨e, ⟨he, hv⟩, hu⟩ := M.property v + rw [Finset.sum_eq_single e] + · simp [hv] + · intro e' he' hne + have hn : ¬ G.Incident v e' := fun hv' ↦ hne (hu e' ⟨he', hv'⟩) + simp [hn] + · simp [he] + +omit [Fintype E] [DecidableEq E] in +theorem matching_card_twice (G : LooplessGraph V E) (M : G.Matching) : + 2 * M.val.card = Fintype.card V := by + classical + calc + 2 * M.val.card = ∑ e ∈ M.val, ∑ v, if G.Incident v e then (1 : ℕ) else 0 := by + simp_rw [G.incident_vertex_sum] + simp [Nat.mul_comm] + _ = ∑ v, ∑ e ∈ M.val, if G.Incident v e then (1 : ℕ) else 0 := Finset.sum_comm + _ = Fintype.card V := by + simp_rw [G.matching_incident_sum] + simp + +omit [Fintype E] [DecidableEq E] in +theorem matching_card (G : LooplessGraph V E) {m : ℕ} + (hV : Fintype.card V = 2 * m) (M : G.Matching) : M.val.card = m := by + have h := G.matching_card_twice M + omega + +theorem indicator_sum (G : LooplessGraph V E) {m : ℕ} + (hV : Fintype.card V = 2 * m) (M : G.Matching) : + ∑ e, G.indicator M e = (m : ℝ) := by + simp [indicator, G.matching_card hV M] + +/-- All feasible marginal vectors have mass m, as in the entropy proof. -/ +theorem marginal_sum (G : LooplessGraph V E) {m : ℕ} + (hV : Fintype.card V = 2 * m) {y : E → ℝ} (hy : y ∈ G.polytope) : + ∑ e, y e = (m : ℝ) := by + obtain ⟨p, hp, rfl⟩ := (G.mem_polytope_iff y).mp hy + simp_rw [mean] + rw [Finset.sum_comm] + simp_rw [← Finset.mul_sum, G.indicator_sum hV] + rw [← Finset.sum_mul, hp.2, one_mul] + +end LooplessGraph + +omit [Fintype V] [DecidableEq V] in +/-- The supremum in the definition of H is a genuine attained maximum. -/ +theorem maxMatchingEntropy_attained (G : LooplessGraph V E) {y : E → ℝ} + (hy : y ∈ G.polytope) : + ∃ p ∈ G.feasibleLaws y, entropy p = maxMatchingEntropy G y := by + have hc := (G.compact_feasibleLaws y).image continuous_entropy + have hn := ((G.mem_polytope_iff y).mp hy).image entropy + obtain ⟨p, hp, hpe⟩ := hc.sSup_mem hn + exact ⟨p, hp, hpe⟩ + +omit [Fintype V] [DecidableEq V] in +theorem maxMatchingEntropy_nonneg (G : LooplessGraph V E) {y : E → ℝ} + (hy : y ∈ G.polytope) : 0 ≤ maxMatchingEntropy G y := by + obtain ⟨p, hp, he⟩ := maxMatchingEntropy_attained G hy + rw [← he] + exact entropy_nonneg hp.1 + +omit [Fintype V] [DecidableEq V] in +theorem maxMatchingEntropy_le_log_card (G : LooplessGraph V E) {y : E → ℝ} + (hy : y ∈ G.polytope) : + maxMatchingEntropy G y ≤ Real.log (Fintype.card G.Matching) := by + obtain ⟨p, hp, he⟩ := maxMatchingEntropy_attained G hy + rw [← he] + exact entropy_le_log_card hp.1 + +omit [Fintype V] [DecidableEq V] in +theorem entropy_le_maxMatchingEntropy (G : LooplessGraph V E) {y : E → ℝ} + {p : G.Matching → ℝ} (hp : p ∈ G.feasibleLaws y) : + entropy p ≤ maxMatchingEntropy G y := by + apply le_csSup + · exact ((G.compact_feasibleLaws y).image continuous_entropy).bddAbove + · exact ⟨p, hp, rfl⟩ + +end MatchingEntropy + +end + +end OAI diff --git a/lean/OAI/Combinatorics/PerfectMatching/EntropyUpper.lean b/lean/OAI/Combinatorics/PerfectMatching/EntropyUpper.lean new file mode 100644 index 0000000000000000000000000000000000000000..bd014ddcee88ef6e88a2fca3d9c699d7806b1ebc --- /dev/null +++ b/lean/OAI/Combinatorics/PerfectMatching/EntropyUpper.lean @@ -0,0 +1,152 @@ +import OAI.Combinatorics.PerfectMatching.SeparableLower + +namespace OAI + +universe u_1 u_2 + +section + +noncomputable section +open scoped BigOperators +namespace MatchingEntropy + +theorem entropy_le_subprob_crossEntropy {I : Type*} [Fintype I] {p q : I → ℝ} + (hp : ∀ i, 0 ≤ p i) (hpsum : ∑ i, p i ≤ 1) (hq : q ∈ probabilitySimplex I) + (hsupp : ∀ i, p i=0 → q i=0) : + entropy q ≤ -∑ i, q i*Real.log (p i) := by + have hterm : ∀ i, Real.negMulLog (q i) ≤ -(q i*Real.log (p i))+p i-q i := by + intro i + by_cases hi : p i=0 + · simp [hi,hsupp i hi] + · simpa only [neg_mul] using negMulLog_tangent (hq.1 i) + (lt_of_le_of_ne (hp i) (Ne.symm hi)) + have hh := Finset.sum_le_sum (s := Finset.univ) fun i _ => hterm i + simp only [Finset.sum_sub_distrib,Finset.sum_add_distrib,Finset.sum_neg_distrib,hq.2] at hh + change entropy q ≤ -(∑ i, q i*Real.log (p i))+(∑ i,p i)-1 at hh + linarith + +variable {V : Type u_1} {E : Type u_2} [Fintype V] [Fintype E] [DecidableEq V] [DecidableEq E] + +namespace LooplessGraph + +def matchingBits (G : LooplessGraph V E) (M : G.Matching) : E → Bool := + fun e => decide (e ∈ M.val) + +omit [Fintype V] [Fintype E] [DecidableEq V] in +theorem matchingBits_injective (G : LooplessGraph V E) : Function.Injective G.matchingBits := by + intro M N h + apply Subtype.ext + ext e + have he := congrFun h e + simpa only [matchingBits,decide_eq_decide] using he + +end LooplessGraph + +def productBoolean (x : E → ℝ) (b : E → Bool) : ℝ := + ∏ e, if b e then x e else 1-x e + +omit [Fintype V] [DecidableEq V] [DecidableEq E] in +theorem productBoolean_nonneg {x : E → ℝ} (hx : ∀ e, x e ∈ Set.Icc (0:ℝ) 1) + (b : E → Bool) : 0 ≤ productBoolean x b := by + apply Finset.prod_nonneg + intro e _ + split + · exact (hx e).1 + · exact sub_nonneg.mpr (hx e).2 + +omit [Fintype V] [DecidableEq V] in +theorem productBoolean_sum (x : E → ℝ) : (∑ b : E → Bool, productBoolean x b)=1 := by + unfold productBoolean + rw [← Fintype.prod_sum (fun e (b : Bool) => if b then x e else 1-x e)] + simp + +omit [Fintype V] [DecidableEq V] in +theorem matchingBoolean_sum_le (G : LooplessGraph V E) {x : E → ℝ} + (hx : ∀ e, x e ∈ Set.Icc (0:ℝ) 1) : + (∑ M, productBoolean x (G.matchingBits M)) ≤ 1 := by + rw [← productBoolean_sum x] + classical + calc + _ = ∑ b ∈ Finset.univ.image G.matchingBits, productBoolean x b := by + rw [Finset.sum_image] + intro M _ N _ h + exact G.matchingBits_injective h + _ ≤ _ := Finset.sum_le_sum_of_subset_of_nonneg (Finset.subset_univ _) + (fun b _ _ => productBoolean_nonneg hx b) + +omit [Fintype V] [DecidableEq V] in +theorem matching_boolean_factor_pos (G : LooplessGraph V E) {x : E → ℝ} + {p : G.Matching → ℝ} (hp : p ∈ G.feasibleLaws x) {M : G.Matching} (hM : 0

p N*G.indicator N e) + (s := Finset.univ) (fun N _ => mul_nonneg (hp.1.1 N) (G.indicator_nonneg N e)) + (Finset.mem_univ M) + have hm : G.indicator M e=1 := by simp [LooplessGraph.indicator,he] + rw [hm,mul_one] at hh + change p M ≤ G.mean p e at hh + rw [hp.2] at hh + exact hM.trans_le hh + · simp only [he,decide_false] + have hh := Finset.single_le_sum (f := fun N => p N*(1-G.indicator N e)) + (s := Finset.univ) (fun N _ => mul_nonneg (hp.1.1 N) + (sub_nonneg.mpr (G.indicator_le_one N e))) (Finset.mem_univ M) + have hm : G.indicator M e=0 := by simp [LooplessGraph.indicator,he] + simp only [hm,sub_zero,mul_one,mul_sub,Finset.sum_sub_distrib,hp.1.2] at hh + change p M ≤ 1-G.mean p e at hh + rw [hp.2] at hh + exact hM.trans_le hh + +omit [Fintype V] [DecidableEq V] in + +theorem matching_entropy_le_binary (G : LooplessGraph V E) {x : E → ℝ} + {p : G.Matching → ℝ} (hp : p ∈ G.feasibleLaws x) : entropy p ≤ binaryEntropy x := by + have hx := G.coordinate_mem_Icc ((G.mem_polytope_iff x).mpr ⟨p,hp⟩) + have hprod (M : G.Matching) (hM : 0

matching_boolean_factor_pos G hp hM e) + have hcross := entropy_le_subprob_crossEntropy + (fun M => productBoolean_nonneg hx (G.matchingBits M)) (matchingBoolean_sum_le G hx) hp.1 + (fun M hzero => le_antisymm (le_of_not_gt (fun hM => (ne_of_gt (hprod M hM)) hzero)) (hp.1.1 M)) + have hlog (M : G.Matching) : p M*Real.log (productBoolean x (G.matchingBits M)) = + ∑ e, p M*(G.indicator M e*Real.log (x e)+(1-G.indicator M e)*Real.log (1-x e)) := by + by_cases hzero : p M=0 + · simp [hzero] + · have hpos : 0

ne_of_gt (matching_boolean_factor_pos G hp hpos e)), + Finset.mul_sum] + apply Finset.sum_congr rfl + intro e _ + simp only [LooplessGraph.matchingBits,LooplessGraph.indicator] + by_cases he : e ∈ M.val <;> simp [he] + have heq : -(∑ M, p M*Real.log (productBoolean x (G.matchingBits M)))=binaryEntropy x := by + simp_rw [hlog] + rw [Finset.sum_comm] + have he (e : E) : (∑ M, p M*(G.indicator M e*Real.log (x e)+ + (1-G.indicator M e)*Real.log (1-x e)))= + x e*Real.log (x e)+(1-x e)*Real.log (1-x e) := by + simp_rw [mul_add,← mul_assoc,Finset.sum_add_distrib,← Finset.sum_mul] + have hmean : (∑ M,p M*G.indicator M e)=x e := congrFun hp.2 e + have hbar : (∑ M,p M*(1-G.indicator M e))=1-x e := by + simp_rw [mul_sub,mul_one,Finset.sum_sub_distrib,hp.1.2,hmean] + rw [hmean,hbar] + simp_rw [he] + rw [Finset.sum_add_distrib,neg_add_rev] + dsimp only [binaryEntropy] + rw [entropy_eq,entropy_eq] + ring + rwa [heq] at hcross + +omit [Fintype V] [DecidableEq V] in +theorem maxMatchingEntropy_le_binary (G : LooplessGraph V E) (x : E → ℝ) + (hx : x ∈ G.polytope) : maxMatchingEntropy G x ≤ binaryEntropy x := by + obtain ⟨p,hp,hopt⟩ := maxMatchingEntropy_attained G hx + rw [← hopt] + exact matching_entropy_le_binary G hp + +end MatchingEntropy +end +end + +end OAI diff --git a/lean/OAI/Combinatorics/PerfectMatching/Face.lean b/lean/OAI/Combinatorics/PerfectMatching/Face.lean new file mode 100644 index 0000000000000000000000000000000000000000..a7454d598c4f59da001afd19255cec31402f622c --- /dev/null +++ b/lean/OAI/Combinatorics/PerfectMatching/Face.lean @@ -0,0 +1,314 @@ +import OAI.Combinatorics.PerfectMatching.Polytope + +namespace OAI + +/-! +Active face spaces, their codimension bounds, and local radial extension. +-/ + +noncomputable section + +open scoped BigOperators Topology +open Filter + +namespace MatchingEntropy + +variable {V E : Type*} [Fintype V] [Fintype E] [DecidableEq V] [DecidableEq E] + +namespace LooplessGraph + +/-- Restrict the ambient vector space to the genuinely positive edge coordinates. -/ +def positiveExtension (x : E → ℝ) : ({e // 0 if h : 0 simp [h] + map_smul' := by intro a u; ext e; by_cases h : 0 simp [h] } + +omit [Fintype E] [DecidableEq E] in +@[simp] theorem positiveExtension_pos (x : E → ℝ) (u : {e // 0 simp + +def cutLinear (G : LooplessGraph V E) (S : Finset V) : (E → ℝ) →ₗ[ℝ] ℝ where + toFun := fun u => G.cutMass u S + map_add' := by intro u v; simpa using G.cutMass_linear u v 1 1 S + map_smul' := by intro a u; simp [cutMass,Finset.mul_sum] + +/-- The exact active degree and odd-cut kernel, on the positive edge support. -/ +def faceSpace (G : LooplessGraph V E) (x : E → ℝ) : Submodule ℝ ({e // 0 positiveExtension_zero x u he) + (congrFun hu.1) hu.2 + +omit [Fintype V] [DecidableEq E] in + theorem faceSpace_of_eventually_line (G : LooplessGraph V E) {x : E → ℝ} + (hx : x ∈ G.constraintPolytope) {u : {e // 0 -t) (𝓝 0) (𝓝 0) := by simpa using continuous_neg.tendsto (0:ℝ) + exact hc.eventually hu + have hh : ∀ᶠ t : ℝ in 𝓝[>] 0, + (x+t • positiveExtension x u ∈ G.constraintPolytope ∧ + x+(-t) • positiveExtension x u ∈ G.constraintPolytope) ∧ 0 x e.val + +def sideRestriction (G : LooplessGraph V E) (x : E → ℝ) (S : Finset V) : + ({e // 0 u ⟨e.val.val,e.property⟩ + map_add' := by intros; rfl + map_smul' := by intros; rfl + +omit [Fintype V] [Fintype E] [DecidableEq V] [DecidableEq E] in + theorem positiveExtension_side (G : LooplessGraph V E) (x : E → ℝ) (S : Finset V) + (u : {e // 0 G.faceSpace_of_side_spaces heven hx S hS ht) + +/-- Strong face-codimension induction for even orders at least four. -/ +theorem faceCodimension_strong_aux (n : ℕ) : + ∀ {W F : Type*} [Fintype W] [Fintype F] [DecidableEq W] [DecidableEq F] + (G : LooplessGraph W F), Fintype.card W=n → Even n → 4≤n → + ∀ x ∈ G.constraintPolytope, G.faceCodimension x ≤ 2*(n-2) := by + induction n using Nat.strong_induction_on with + | h n ih => + intro W F _ _ _ _ G hcard heven hfour x hx + have heven' : Even (Fintype.card W) := hcard ▸ heven + by_cases hcut : ∃ S : Finset W, Odd S.card ∧ 3≤S.card ∧ 3≤Sᶜ.card ∧ G.cutMass x S=1 + · obtain ⟨S,hS,hlo,hhi,ht⟩ := hcut + have hc := odd_compl_of_even heven' hS + have hlt1 : Fintype.card (Option {v // v ∈ S}) < n := by + simp only [Fintype.card_option,Fintype.card_coe] + have hco := Finset.card_compl S + omega + have hlt2 : Fintype.card (Option {v // v ∈ Sᶜ}) < n := by + simp only [Fintype.card_option,Fintype.card_coe] + have hco := Finset.card_compl S + have hle := Finset.card_le_univ S + omega + have hv1 : Even (Fintype.card (Option {v // v ∈ S})) := by + simpa only [Fintype.card_option,Fintype.card_coe] using hS.add_odd odd_one + have hv2 : Even (Fintype.card (Option {v // v ∈ Sᶜ})) := by + simpa only [Fintype.card_option,Fintype.card_coe] using hc.add_odd odd_one + have hn1 : 4≤Fintype.card (Option {v // v ∈ S}) := by + simp only [Fintype.card_option,Fintype.card_coe]; omega + have hn2 : 4≤Fintype.card (Option {v // v ∈ Sᶜ}) := by + simp only [Fintype.card_option,Fintype.card_coe]; omega + have hx1 := G.restriction_mem_constraints hx S hS ht + have htc : G.cutMass x Sᶜ=1 := by simpa only [cutMass,cut_compl] using ht + have hx2 := G.restriction_mem_constraints hx Sᶜ hc htc + have hb1 := ih _ hlt1 (G.onSide S) rfl hv1 hn1 _ hx1 + have hb2 := ih _ hlt2 (G.onSide Sᶜ) rfl hv2 hn2 _ hx2 + have hb := G.faceCodimension_le_sides heven' hx S hS ht + have hsum : Fintype.card (Option {v // v ∈ S}) + Fintype.card (Option {v // v ∈ Sᶜ})=n+2 := by + simp only [Fintype.card_option,Fintype.card_coe] + have hh := Finset.card_compl_add_card S + omega + change (G.onSide S).faceCodimension (G.sideMarginal x S) ≤ _ at hb1 + change (G.onSide Sᶜ).faceCodimension (G.sideMarginal x Sᶜ) ≤ _ at hb2 + omega + · have hb := G.faceCodimension_no_tight heven' hcut + omega + +/-- The precise coarse face-codimension estimate used by the entropy argument. -/ +theorem faceCodimension_bound (G : LooplessGraph V E) {x : E → ℝ} + (heven : Even (Fintype.card V)) (hx : x ∈ G.polytope) : + G.faceCodimension x ≤ 2*Fintype.card V := by + by_cases hn : 4≤Fintype.card V + · have hb := faceCodimension_strong_aux (Fintype.card V) G rfl heven hn x + (G.polytope_subset_constraintPolytope hx) + omega + · have hnt : ¬ ∃ S : Finset V, Odd S.card ∧ 3≤S.card ∧ 3≤Sᶜ.card ∧ G.cutMass x S=1 := by + rintro ⟨S,_,hlo,hhi,_⟩ + have hh := Finset.card_compl_add_card S + omega + have hb := G.faceCodimension_no_tight heven hnt + omega + + +omit [Fintype V] [DecidableEq E] in + theorem degree_add_smul (G : LooplessGraph V E) (x u : E → ℝ) (t : ℝ) (v : V) : + G.degree (x+t • u) v=G.degree x v+t*G.degree u v := by + simpa using G.degree_linear x u 1 t v + +omit [Fintype V] [DecidableEq E] in + theorem cutMass_add_smul (G : LooplessGraph V E) (x u : E → ℝ) (t : ℝ) (S : Finset V) : + G.cutMass (x+t • u) S=G.cutMass x S+t*G.cutMass u S := by + simpa using G.cutMass_linear x u 1 t S + +omit [DecidableEq E] in +/-- Radial extension for this actual matching polytope. This is needed to prove +lower semicontinuity of the maximum entropy without assuming its regularity. -/ +theorem constraint_eventually_expand (G : LooplessGraph V E) {x : E → ℝ} + (hx : x ∈ G.constraintPolytope) {t : ℝ} (ht : 0 (x+t⁻¹ • (y-x)) e) := by fun_prop + have hh : ∀ᶠ y : E → ℝ in 𝓝 x, 0<(x+t⁻¹ • (y-x)) e := + (isOpen_lt continuous_const hc).mem_nhds (by simpa using hp) + exact (hh.filter_mono nhdsWithin_le_nhds).mono fun y hy => hy.le + have hodd : ∀ᶠ y in 𝓝[G.constraintPolytope] x, + ∀ S : Finset V, Odd S.card → 1≤G.cutMass (x+t⁻¹ • (y-x)) S := by + apply Filter.eventually_all.mpr + intro S + by_cases hS : Odd S.card + · by_cases hs : G.cutMass x S=1 + · filter_upwards [eventually_mem_nhdsWithin] with y hy _ + rw [cutMass_add_smul,cutMass_sub,hs] + have hh := mul_nonneg (inv_nonneg.mpr ht.le) (sub_nonneg.mpr (hy.2.2 S hS)) + linarith + · have hp : 1 G.cutMass (x+t⁻¹ • (y-x)) S) := + (G.continuous_cutMass S).comp (by fun_prop) + have hh : ∀ᶠ y : E → ℝ in 𝓝 x, 1 hy.le + · exact Filter.Eventually.of_forall fun _ h => (hS h).elim + filter_upwards [hn,hodd,eventually_mem_nhdsWithin] with y hn hodd hy + refine ⟨hn,?_,hodd⟩ + intro v + rw [degree_add_smul,degree_sub,hx.2.1,hy.2.1] + ring + + theorem polytope_eventually_expand (G : LooplessGraph V E) {x : E → ℝ} + (heven : Even (Fintype.card V)) (hx : x ∈ G.polytope) {t : ℝ} (ht : 0 x e+z e) v= + (completeGraph n).degree x v+(completeGraph n).degree z v := by + simpa only [one_smul,one_mul,Pi.add_def] using (completeGraph n).degree_linear x z 1 1 v + +lemma cut_add (x z : Pair n → ℝ) (S : Finset (Fin n)) : + (completeGraph n).cutMass (fun e => x e+z e) S= + (completeGraph n).cutMass x S+(completeGraph n).cutMass z S := by + simpa only [one_smul,one_mul,Pi.add_def] using (completeGraph n).cutMass_linear x z 1 1 S + +lemma cut_bound {z : Pair n → ℝ} {b : ℝ} (hb : 0≤b) (hz : ∀ e, |z e|≤b) + (S : Finset (Fin n)) : |(completeGraph n).cutMass z S|≤Fintype.card (Pair n)*b := by + calc + _ ≤ ∑ e∈(completeGraph n).cut S, |z e| := abs_sum_le_sum_abs _ _ + _ ≤ ∑ _e∈(completeGraph n).cut S, b := sum_le_sum (fun e _ => hz e) + _ = ((completeGraph n).cut S).card*b := by simp + _ ≤ Fintype.card (Pair n)*b := by + exact mul_le_mul_of_nonneg_right (by exact_mod_cast card_le_univ _) hb + +def degreeCorrection (x : Pair n → ℝ) (e : Pair n) : ℝ := + let d := fun v => 1-(completeGraph n).degree x v + (d e.val.1+d e.val.2)/((n:ℝ)-2)-(∑ v,d v)/(((n:ℝ)-2)*((n:ℝ)-1)) + +lemma correction_degree (hn : 4≤n) (x : Pair n → ℝ) (v : Fin n) : + (completeGraph n).degree (fun e => x e+degreeCorrection x e) v=1 := by + have hn' : (4:ℝ)≤n := by exact_mod_cast hn + have h2 : (n:ℝ)-2≠0 := by linarith + have h1 : (n:ℝ)-1≠0 := by linarith + let d := fun v => 1-(completeGraph n).degree x v + rw [degree_add] + have hc : degreeCorrection x = ((n:ℝ)-2)⁻¹ • (fun e : Pair n => d e.val.1+d e.val.2) + + (-1:ℝ) • (fun _ => (∑ v,d v)/(((n:ℝ)-2)*((n:ℝ)-1))) := by + funext e; simp only [degreeCorrection,d,Pi.add_apply,Pi.smul_apply,smul_eq_mul]; ring + rw [hc,(completeGraph n).degree_linear,degree_vertex_add,degree_constant] + dsimp [d] + field_simp + ring + +lemma correction_bound (hn : 4≤n) {x : Pair n → ℝ} {w : ℝ} (hw : 0≤w) + (hdeg : ∀ v, |(completeGraph n).degree x v-1|≤w) (e : Pair n) : + |degreeCorrection x e|≤2*w := by + have hn' : (4:ℝ)≤n := by exact_mod_cast hn + have h2 : 0<(n:ℝ)-2 := by linarith + have h1 : 0<(n:ℝ)-1 := by linarith + let d := fun v => 1-(completeGraph n).degree x v + have hd (v) : |d v|≤w := by dsimp [d]; rw [abs_sub_comm]; exact hdeg v + have hsum : |∑ v,d v|≤(n:ℝ)*w := by + calc + _ ≤ ∑ v,|d v| := abs_sum_le_sum_abs _ _ + _ ≤ ∑ _v : Fin n,w := sum_le_sum (fun v _ => hd v) + _ = _ := by simp + have ha : |(d e.val.1+d e.val.2)/((n:ℝ)-2)|≤w := by + rw [abs_div,abs_of_pos h2,div_le_iff₀ h2] + have hh := abs_add_le (d e.val.1) (d e.val.2) + nlinarith [hd e.val.1,hd e.val.2] + have hb : |(∑ v,d v)/(((n:ℝ)-2)*((n:ℝ)-1))|≤w := by + rw [abs_div,abs_of_pos (mul_pos h2 h1),div_le_iff₀ (mul_pos h2 h1)] + have hp : (n:ℝ)≤((n:ℝ)-2)*((n:ℝ)-1) := by nlinarith + exact hsum.trans (by nlinarith [mul_le_mul_of_nonneg_right hp hw]) + exact (abs_sub _ _).trans (by dsimp [degreeCorrection] at *; linarith [ha,hb]) + +def uniform (n : ℕ) : Pair n → ℝ := fun _ => 1/((n:ℝ)-1) + +lemma uniform_box (hn : 4≤n) (e : Pair n) : uniform n e∈Set.Icc (0:ℝ) 1 := by + have hn' : (4:ℝ)≤n := by exact_mod_cast hn + constructor + · exact div_nonneg (by norm_num) (by linarith) + · exact (div_le_one (by linarith)).2 (by linarith) + +lemma uniform_degree (hn : 4≤n) (v : Fin n) : + (completeGraph n).degree (uniform n) v=1 := by + unfold uniform + rw [degree_constant] + have hn' : (4:ℝ)≤n := by exact_mod_cast hn + field_simp [show (n:ℝ)-1≠0 by linarith] + +def TrivialCut (S : Finset (Fin n)) : Prop := S.card=1 ∨ Sᶜ.card=1 + +lemma trivial_cut_degree {x : Pair n → ℝ} (hx : ∀ v,(completeGraph n).degree x v=1) + {S : Finset (Fin n)} (hS : TrivialCut S) : (completeGraph n).cutMass x S=1 := by + rcases hS with h|h + · obtain ⟨v,rfl⟩ := card_eq_one.mp h + simpa using hx v + · obtain ⟨v,hv⟩ := card_eq_one.mp h + have he : (completeGraph n).cutMass x S=(completeGraph n).cutMass x Sᶜ := by + simp only [LooplessGraph.cutMass,LooplessGraph.cut_compl] + rw [he,hv,LooplessGraph.cutMass_singleton,hx] + +lemma uniform_nontrivial_cut (heven : Even n) {S : Finset (Fin n)} (hodd : Odd S.card) + (hS : ¬TrivialCut S) : (3/2:ℝ)≤(completeGraph n).cutMass (uniform n) S := by + have hcards : S.card+Sᶜ.card=n := by simp + have ha : 3≤S.card := by + have ho := Nat.odd_iff.mp hodd + have hh : S.card≠1 := fun h => hS (Or.inl h) + omega + have hb : 3≤Sᶜ.card := by + have ho := Nat.odd_iff.mp hodd + have he := Nat.even_iff.mp heven + have hh : Sᶜ.card≠1 := fun h => hS (Or.inr h) + omega + have ha' : (3:ℝ)≤S.card := by exact_mod_cast ha + have hb' : (3:ℝ)≤Sᶜ.card := by exact_mod_cast hb + have hc' : (S.card:ℝ)+Sᶜ.card=n := by exact_mod_cast hcards + have hn : (6:ℝ)≤n := by linarith + unfold uniform + rw [cut_constant] + rw [mul_one_div,le_div_iff₀ (by linarith : 0<(n:ℝ)-1)] + have hp := mul_nonneg (sub_nonneg.mpr ha') (sub_nonneg.mpr hb') + nlinarith + +lemma uniform_feasible (hn : 4≤n) (heven : Even n) : + uniform n∈(completeGraph n).polytope := by + rw [(completeGraph n).polytope_eq_constraints (by simpa using heven)] + refine ⟨fun e => (uniform_box hn e).1,uniform_degree hn,?_⟩ + intro S hS + by_cases ht : TrivialCut S + · rw [trivial_cut_degree (uniform_degree hn) ht] + · linarith [uniform_nontrivial_cut heven hS ht] + +theorem feasibility_repair (hn : 4≤n) (heven : Even n) {x : Pair n → ℝ} + (hx : ∀ e,x e∈Set.Icc (0:ℝ) 1) {w : ℝ} (hw : 0≤w) + (hdeg : ∀ v, |(completeGraph n).degree x v-1|≤w) + (hcut : ∀ S : Finset (Fin n),Odd S.card → 1-w≤(completeGraph n).cutMass x S) : + ∃ y∈(completeGraph n).polytope,∀ e,|y e-x e|≤(2+10*(n:ℝ)^2)*w := by + let A : ℝ := 10*(n:ℝ)^2 + let c := degreeCorrection x + let x' := fun e => x e+c e + let t := min 1 (A*w) + let y : Pair n → ℝ := (1-t) • x'+t • uniform n + have hn' : (4:ℝ)≤n := by exact_mod_cast hn + have hA : 0≤A := by dsimp [A]; positivity + have ht : 0≤t := le_min (by norm_num) (mul_nonneg hA hw) + have ht1 : t≤1 := min_le_left _ _ + have htw : t≤A*w := min_le_right _ _ + have hc := correction_bound hn hw hdeg + have hx'd := correction_degree hn x + have hx'lo (e) : -2*w≤x' e := by + have hh := (abs_le.mp (hc e)).1 + dsimp [x',c]; linarith [(hx e).1] + have hx'cut (S) (hS : Odd S.card) : + 1-(1+2*(Fintype.card (Pair n):ℝ))*w≤(completeGraph n).cutMass x' S := by + have hh := (abs_le.mp (cut_bound (mul_nonneg (by norm_num) hw) hc S)).1 + dsimp [x',c]; rw [cut_add] + linarith [hcut S hS] + have hA1 : 2≤A/((n:ℝ)-1) := by + apply (le_div_iff₀ (by linarith)).2 + dsimp [A]; nlinarith + have hA2 : 1+2*(Fintype.card (Pair n):ℝ)≤A/2 := by + have hq : (Fintype.card (Pair n):ℝ)≤(n:ℝ)^2 := by exact_mod_cast q_le_square (n:=n) + dsimp [A]; nlinarith + have hyd : ∀ v,(completeGraph n).degree y v=1 := by + intro v; dsimp [y]; rw [LooplessGraph.degree_linear,hx'd,uniform_degree hn]; ring + have hy : y∈(completeGraph n).polytope := by + by_cases hbig : 1≤A*w + · have htt : t=1 := min_eq_left hbig + simpa only [y,htt,sub_self,zero_smul,one_smul,zero_add] using uniform_feasible hn heven + · have htt : t=A*w := min_eq_right (le_of_not_ge hbig) + rw [(completeGraph n).polytope_eq_constraints (by simpa using heven)] + refine ⟨?_,hyd,?_⟩ + · intro e + have h0 := mul_le_mul_of_nonneg_left (hx'lo e) (sub_nonneg.mpr ht1) + have h1 := mul_le_mul_of_nonneg_right hA1 hw + change 0≤(1-t)*x' e+t*uniform n e + unfold uniform + rw [htt] at * + simp only [div_eq_mul_inv] at h1 ⊢ + nlinarith [mul_nonneg ht hw] + · intro S hS + by_cases htr : TrivialCut S + · rw [trivial_cut_degree hyd htr] + · have h0 := mul_le_mul_of_nonneg_left (hx'cut S hS) (sub_nonneg.mpr ht1) + have h1 := mul_le_mul_of_nonneg_left (uniform_nontrivial_cut heven hS htr) ht + have h2 := mul_le_mul_of_nonneg_right hA2 hw + dsimp [y]; rw [LooplessGraph.cutMass_linear] + have hqw : 0≤(1+2*(Fintype.card (Pair n):ℝ))*w := by positivity + rw [htt] at * + nlinarith [mul_nonneg ht hqw] + refine ⟨y,hy,fun e => ?_⟩ + have hu : |uniform n e-x e|≤1 := by + rw [abs_le]; constructor <;> linarith [(uniform_box hn e).1,(uniform_box hn e).2,(hx e).1,(hx e).2] + have he : y e-x e=(1-t)*c e+t*(uniform n e-x e) := by dsimp [y,x']; ring + rw [he] + calc + _ ≤ |(1-t)*c e|+|t*(uniform n e-x e)| := abs_add_le _ _ + _ = (1-t)*|c e|+t*|uniform n e-x e| := by rw [abs_mul,abs_mul,abs_of_nonneg (sub_nonneg.mpr ht1),abs_of_nonneg ht] + _ ≤ (1-t)*(2*w)+t*1 := add_le_add (mul_le_mul_of_nonneg_left (hc e) (sub_nonneg.mpr ht1)) (mul_le_mul_of_nonneg_left hu ht) + _ ≤ (2+10*(n:ℝ)^2)*w := by dsimp [A] at htw; nlinarith [mul_nonneg ht hw] + +end +end BinaryMatching +end + +end OAI diff --git a/lean/OAI/Combinatorics/PerfectMatching/ForcedReduction.lean b/lean/OAI/Combinatorics/PerfectMatching/ForcedReduction.lean new file mode 100644 index 0000000000000000000000000000000000000000..41c5f98e7bc5870652f1f9b9706ee271899af2fb --- /dev/null +++ b/lean/OAI/Combinatorics/PerfectMatching/ForcedReduction.lean @@ -0,0 +1,315 @@ +import OAI.Combinatorics.PerfectMatching.SeparableCovariance + +namespace OAI + +universe u_1 u_2 + +section + +noncomputable section +open scoped BigOperators +namespace MatchingEntropy +namespace LooplessGraph +variable {V : Type u_1} {E : Type u_2} [Fintype V] [Fintype E] [DecidableEq V] [DecidableEq E] + +def RemainingVertex (G : LooplessGraph V E) (e₀ : E) (v : V) : Prop := + ¬G.Incident v e₀ + +instance remainingVertexDecidable (G : LooplessGraph V E) (e₀ : E) (v : V) : + Decidable (G.RemainingVertex e₀ v) := inferInstanceAs (Decidable (¬G.Incident v e₀)) + +def RemainingEdge (G : LooplessGraph V E) (e₀ e : E) : Prop := + G.RemainingVertex e₀ (G.left e) ∧ G.RemainingVertex e₀ (G.right e) + +instance remainingEdgeDecidable (G : LooplessGraph V E) (e₀ e : E) : + Decidable (G.RemainingEdge e₀ e) := inferInstanceAs + (Decidable (G.RemainingVertex e₀ (G.left e) ∧ G.RemainingVertex e₀ (G.right e))) + +def deleteEndpoints (G : LooplessGraph V E) (e₀ : E) : + LooplessGraph {v // G.RemainingVertex e₀ v} {e // G.RemainingEdge e₀ e} where + left e := ⟨G.left e.val, e.property.1⟩ + right e := ⟨G.right e.val, e.property.2⟩ + loopless e he := G.loopless e.val (congrArg Subtype.val he) + +omit [Fintype V] [Fintype E] [DecidableEq V] [DecidableEq E] in +theorem remainingEdge_ne (G : LooplessGraph V E) (e₀ : E) + {e : E} (he : G.RemainingEdge e₀ e) : e ≠ e₀ := by + rintro rfl + exact he.1 (Or.inl rfl) + +omit [Fintype V] [Fintype E] [DecidableEq V] [DecidableEq E] in +theorem remaining_of_incident (G : LooplessGraph V E) (e₀ : E) + {e : E} (he : G.RemainingEdge e₀ e) {v : V} (hv : G.Incident v e) : + G.RemainingVertex e₀ v := by + rcases hv with h | h + · exact h ▸ he.1 + · exact h ▸ he.2 + +omit [Fintype V] [Fintype E] [DecidableEq V] [DecidableEq E] in +@[simp] theorem deleteEndpoints_incident (G : LooplessGraph V E) (e₀ : E) + (v : {v // G.RemainingVertex e₀ v}) (e : {e // G.RemainingEdge e₀ e}) : + (G.deleteEndpoints e₀).Incident v e ↔ G.Incident v.val e.val := by + simp only [Incident, deleteEndpoints, Subtype.ext_iff] + +omit [Fintype V] [Fintype E] [DecidableEq V] [DecidableEq E] in +theorem matching_common_vertex (G : LooplessGraph V E) (M : G.Matching) + {e f : E} (he : e ∈ M.val) (hf : f ∈ M.val) {v : V} + (hve : G.Incident v e) (hvf : G.Incident v f) : e=f := by + obtain ⟨g, _, hg⟩ := M.property v + exact (hg e ⟨he,hve⟩).trans (hg f ⟨hf,hvf⟩).symm + +omit [Fintype V] [Fintype E] [DecidableEq V] [DecidableEq E] in + +theorem matching_remaining (G : LooplessGraph V E) (e₀ : E) (M : G.Matching) + (h₀ : e₀ ∈ M.val) {e : E} (he : e ∈ M.val) (hne : e ≠ e₀) : + G.RemainingEdge e₀ e := by + constructor + · intro hv + exact hne (G.matching_common_vertex M he h₀ (Or.inl rfl) hv) + · intro hv + exact hne (G.matching_common_vertex M he h₀ (Or.inr rfl) hv) + +def addForced (G : LooplessGraph V E) (e₀ : E) (N : (G.deleteEndpoints e₀).Matching) : + G.Matching := by + refine ⟨insert e₀ (N.val.image Subtype.val), ?_⟩ + intro v + by_cases hv : G.Incident v e₀ + · refine ⟨e₀, ⟨by simp, hv⟩, ?_⟩ + rintro f ⟨hf,hfv⟩ + rcases Finset.mem_insert.mp hf with h | h + · exact h + · obtain ⟨g,_,rfl⟩ := Finset.mem_image.mp h + exact False.elim (G.remaining_of_incident e₀ g.property hfv hv) + · let v' : {v // G.RemainingVertex e₀ v} := ⟨v,hv⟩ + obtain ⟨f,⟨hf,hfv⟩, hu⟩ := N.property v' + refine ⟨f.val, ⟨Finset.mem_insert_of_mem (Finset.mem_image.mpr ⟨f,hf,rfl⟩), + (G.deleteEndpoints_incident e₀ v' f).mp hfv⟩, ?_⟩ + rintro g ⟨hg,hgv⟩ + rcases Finset.mem_insert.mp hg with h | h + · exact False.elim (hv (h ▸ hgv)) + · obtain ⟨g',hg',rfl⟩ := Finset.mem_image.mp h + exact congrArg Subtype.val (hu g' ⟨hg', (G.deleteEndpoints_incident e₀ v' g').mpr hgv⟩) + +omit [Fintype V] [Fintype E] in +@[simp] theorem mem_addForced (G : LooplessGraph V E) (e₀ : E) + (N : (G.deleteEndpoints e₀).Matching) (e : E) : + e ∈ (G.addForced e₀ N).val ↔ e=e₀ ∨ ∃ h : G.RemainingEdge e₀ e, ⟨e,h⟩ ∈ N.val := by + simp only [addForced, Finset.mem_insert, Finset.mem_image] + constructor + · rintro (h | ⟨f,hf,rfl⟩) + · exact Or.inl h + · exact Or.inr ⟨f.property,hf⟩ + · rintro (h | ⟨h,he⟩) + · exact Or.inl h + · exact Or.inr ⟨⟨e,h⟩,he,rfl⟩ + +omit [Fintype V] [Fintype E] in +@[simp] theorem mem_addForced_remaining (G : LooplessGraph V E) (e₀ : E) + (N : (G.deleteEndpoints e₀).Matching) (e : {e // G.RemainingEdge e₀ e}) : + e.val ∈ (G.addForced e₀ N).val ↔ e ∈ N.val := by + rw [mem_addForced] + simp only [G.remainingEdge_ne e₀ e.property, false_or] + exact ⟨fun ⟨_,h⟩ => h, fun h => ⟨e.property,h⟩⟩ + +def removeForced (G : LooplessGraph V E) (e₀ : E) + (M : {M : G.Matching // e₀ ∈ M.val}) : (G.deleteEndpoints e₀).Matching := by + refine ⟨M.val.val.subtype (G.RemainingEdge e₀), ?_⟩ + intro v + obtain ⟨e,⟨he,hev⟩,hu⟩ := M.val.property v.val + have hne : e ≠ e₀ := by rintro rfl; exact v.property hev + have hrem := G.matching_remaining e₀ M.val M.property he hne + refine ⟨⟨e,hrem⟩, ⟨by simpa using he, + (G.deleteEndpoints_incident e₀ v ⟨e,hrem⟩).mpr hev⟩, ?_⟩ + rintro f ⟨hf,hfv⟩ + apply Subtype.ext + exact hu f.val ⟨by simpa using hf, (G.deleteEndpoints_incident e₀ v f).mp hfv⟩ + +omit [Fintype V] [Fintype E] [DecidableEq E] in +@[simp] theorem mem_removeForced (G : LooplessGraph V E) (e₀ : E) + (M : {M : G.Matching // e₀ ∈ M.val}) (e : {e // G.RemainingEdge e₀ e}) : + e ∈ (G.removeForced e₀ M).val ↔ e.val ∈ M.val.val := by + simp [removeForced] + +def forcedMatchingEquiv (G : LooplessGraph V E) (e₀ : E) : + (G.deleteEndpoints e₀).Matching ≃ {M : G.Matching // e₀ ∈ M.val} where + toFun N := ⟨G.addForced e₀ N, (G.mem_addForced e₀ N e₀).mpr (Or.inl rfl)⟩ + invFun M := G.removeForced e₀ M + left_inv N := by + apply Subtype.ext + ext e + exact (G.mem_removeForced e₀ _ e).trans (G.mem_addForced_remaining e₀ N e) + right_inv M := by + apply Subtype.ext + apply Subtype.ext + ext e + rw [mem_addForced] + constructor + · rintro (rfl | ⟨h,he⟩) + · exact M.property + · exact (G.mem_removeForced e₀ M ⟨e,h⟩).mp he + · intro he + by_cases h : e=e₀ + · exact Or.inl h + · exact Or.inr ⟨G.matching_remaining e₀ M.val M.property he h, + (G.mem_removeForced e₀ M _).mpr he⟩ + +omit [Fintype V] [Fintype E] in +theorem addForced_injective (G : LooplessGraph V E) (e₀ : E) : + Function.Injective (G.addForced e₀) := by + intro N N' h + apply (G.forcedMatchingEquiv e₀).injective + exact Subtype.ext h + +omit [Fintype E] [DecidableEq E] in +theorem remaining_vertex_card (G : LooplessGraph V E) (e₀ : E) : + Fintype.card {v // G.RemainingVertex e₀ v} + 2 = Fintype.card V := by + have he : Fintype.card {v // G.Incident v e₀}=2 := by + rw [Fintype.card_subtype] + have hf : Finset.univ.filter (fun v => G.Incident v e₀)={G.left e₀, G.right e₀} := by + ext v + simp [Incident, eq_comm] + rw [hf, Finset.card_pair (G.loopless e₀)] + have h := Fintype.card_subtype_compl (G.Incident · e₀) + have hle := Fintype.card_subtype_le (G.Incident · e₀) + change Fintype.card {v // ¬G.Incident v e₀} + 2 = Fintype.card V + omega + +omit [Fintype V] [Fintype E] in +@[simp] theorem range_addForced (G : LooplessGraph V E) (e₀ : E) (M : G.Matching) : + M ∈ Set.range (G.addForced e₀) ↔ e₀ ∈ M.val := by + constructor + · rintro ⟨N,rfl⟩ + exact (G.mem_addForced e₀ N e₀).mpr (Or.inl rfl) + · intro h + refine ⟨G.removeForced e₀ ⟨M,h⟩, ?_⟩ + exact congrArg Subtype.val ((G.forcedMatchingEquiv e₀).apply_symm_apply ⟨M,h⟩) + +omit [Fintype V] [DecidableEq V] in +theorem law_support_of_mean_one (G : LooplessGraph V E) {p : G.Matching → ℝ} + (hp : p ∈ probabilitySimplex G.Matching) {e₀ : E} (he : G.mean p e₀=1) + (M : G.Matching) (hM : e₀ ∉ M.val) : p M=0 := by + have hz : ∑ N, p N*(1-G.indicator N e₀)=0 := by + simp only [mul_sub, mul_one, Finset.sum_sub_distrib, hp.2] + change 1-G.mean p e₀=0 + rw [he, sub_self] + have hh := (Finset.sum_eq_zero_iff_of_nonneg + (fun N (_ : N ∈ Finset.univ) => + mul_nonneg (hp.1 N) (sub_nonneg.mpr (G.indicator_le_one N e₀)))).mp hz M (by simp) + simpa [indicator,hM] using hh + +omit [Fintype V] in + +theorem forcedLaw_feasible (G : LooplessGraph V E) {x : E → ℝ} + {p : G.Matching → ℝ} (hp : p ∈ G.feasibleLaws x) (e₀ : E) (he : x e₀=1) : + (fun N => p (G.addForced e₀ N)) ∈ (G.deleteEndpoints e₀).feasibleLaws + (fun e => x e.val) := by + have hs : ∀ M, e₀ ∉ M.val → p M=0 := + G.law_support_of_mean_one hp.1 (by rw [hp.2,he]) + refine ⟨⟨fun N => hp.1.1 _, ?_⟩, ?_⟩ + · rw [← hp.1.2] + apply Fintype.sum_of_injective (G.addForced e₀) (G.addForced_injective e₀) + · intro M hM + exact hs M (fun hh => hM ((G.range_addForced e₀ M).mpr hh)) + · intro N + rfl + · funext e + rw [← congrFun hp.2 e.val] + apply Fintype.sum_of_injective (G.addForced e₀) (G.addForced_injective e₀) + · intro M hM + rw [hs M (fun hh => hM ((G.range_addForced e₀ M).mpr hh)),zero_mul] + · intro N + simp only [indicator,mem_addForced_remaining] + +omit [Fintype V] [DecidableEq V] in + +theorem forced_coordinate_zero (G : LooplessGraph V E) {x : E → ℝ} + (hx : x ∈ G.polytope) (e₀ : E) (he : x e₀=1) {e : E} + (hneq : e ≠ e₀) (hrem : ¬G.RemainingEdge e₀ e) : x e=0 := by + obtain ⟨p,hp⟩ := (G.mem_polytope_iff x).mp hx + rw [← congrFun hp.2 e] + apply Finset.sum_eq_zero + intro M _ + by_cases hM : e₀ ∈ M.val + · have hh : e ∉ M.val := fun hh => hrem (G.matching_remaining e₀ M hM hh hneq) + simp [indicator,hh] + · rw [G.law_support_of_mean_one hp.1 (by rw [hp.2,he]) M hM,zero_mul] + +omit [Fintype V] in + +theorem separableLower_forced (G : LooplessGraph V E) {x : E → ℝ} + (hx : x ∈ G.polytope) (e₀ : E) (he : x e₀=1) : + separableLower (fun e : {e // G.RemainingEdge e₀ e} => x e.val)=separableLower x := by + have hz : ∀ e, ¬G.RemainingEdge e₀ e → + Real.negMulLog (x e)=0 ∧ Real.negMulLog (1-x e)=0 := by + intro e h + by_cases hneq : e=e₀ + · simp [hneq,he] + · simp [G.forced_coordinate_zero hx e₀ he hneq h] + unfold separableLower entropy + rw [sum_subtype_supported _ _ (fun e h => (hz e h).1), + sum_subtype_supported _ _ (fun e h => (hz e h).2)] + +end LooplessGraph + +theorem entropy_fiberMass_injective {A B : Type*} [Fintype A] [Fintype B] [DecidableEq B] + (p : A → ℝ) (f : A → B) (hf : Function.Injective f) : + entropy (fiberMass p f)=entropy p := by + classical + have hself (a : A) : fiberMass p f (f a)=p a := by + simp [fiberMass,hf.eq_iff] + have hzero (b : B) (hb : b ∉ Set.range f) : fiberMass p f b=0 := by + apply Finset.sum_eq_zero + intro a _ + exact ite_eq_right (fun h => hb ⟨a,h⟩) + symm + apply Fintype.sum_of_injective f hf + · intro b hb + rw [hzero b hb,Real.negMulLog_zero] + · intro a + rw [hself] + +namespace LooplessGraph +variable {V : Type u_1} {E : Type u_2} [Fintype V] [Fintype E] [DecidableEq V] [DecidableEq E] +omit [Fintype V] in + +theorem liftForced_feasible (G : LooplessGraph V E) {x : E → ℝ} + (hx : x ∈ G.polytope) (e₀ : E) (he : x e₀=1) + {q : (G.deleteEndpoints e₀).Matching → ℝ} + (hq : q ∈ (G.deleteEndpoints e₀).feasibleLaws (fun e => x e.val)) : + fiberMass q (G.addForced e₀) ∈ G.feasibleLaws x := by + refine ⟨fiberMass_mem_simplex hq.1 _, ?_⟩ + funext e + rw [mean,fiberMass_expect] + by_cases heq : e=e₀ + · subst e + simpa [indicator] using hq.1.2.trans he.symm + · by_cases hr : G.RemainingEdge e₀ e + · change (∑ N, q N*G.indicator (G.addForced e₀ N) e)=_ + have hm (N : (G.deleteEndpoints e₀).Matching) : + G.indicator (G.addForced e₀ N) e = (G.deleteEndpoints e₀).indicator N ⟨e,hr⟩ := by + simp only [indicator,G.mem_addForced_remaining e₀ N ⟨e,hr⟩] + simp_rw [hm] + exact congrFun hq.2 ⟨e,hr⟩ + · rw [G.forced_coordinate_zero hx e₀ he heq hr] + apply Finset.sum_eq_zero + intro N _ + simp [indicator,heq,hr] + +omit [Fintype V] in + +theorem maxMatchingEntropy_forced_le (G : LooplessGraph V E) {x : E → ℝ} + (hx : x ∈ G.polytope) (e₀ : E) (he : x e₀=1) : + maxMatchingEntropy (G.deleteEndpoints e₀) (fun e => x e.val) ≤ maxMatchingEntropy G x := by + obtain ⟨p,hp⟩ := (G.mem_polytope_iff x).mp hx + have hr := G.forcedLaw_feasible hp e₀ he + have hx' := ((G.deleteEndpoints e₀).mem_polytope_iff _).mpr ⟨_,hr⟩ + obtain ⟨q,hq,hopt⟩ := maxMatchingEntropy_attained (G.deleteEndpoints e₀) hx' + rw [← hopt,← entropy_fiberMass_injective q _ (G.addForced_injective e₀)] + exact entropy_le_maxMatchingEntropy G (G.liftForced_feasible hx e₀ he hq) + +end LooplessGraph +end MatchingEntropy +end +end + +end OAI diff --git a/lean/OAI/Combinatorics/PerfectMatching/Main.lean b/lean/OAI/Combinatorics/PerfectMatching/Main.lean new file mode 100644 index 0000000000000000000000000000000000000000..fc710eb9dc750c1132a31e786d895e3b853e885f --- /dev/null +++ b/lean/OAI/Combinatorics/PerfectMatching/Main.lean @@ -0,0 +1,213 @@ +import OAI.Combinatorics.PerfectMatching.MatchingCovariance + +namespace OAI + +/-! +The nonlinear entropy defect bound +`F - H ≤ 8m (1 - exp (-F/m))` for finite loopless multigraphs on `2m` vertices, +and the perfect matching count bound `[k exp (-8 (1 - 1/k))]^m`, +with its coarse bound `(exp (-8) k)^m`, when the entire edge set +is partitioned into `k ≥ 1` perfect matchings. +-/ + +noncomputable section + +open scoped BigOperators Topology +open Filter + +namespace MatchingEntropy + +open Matrix + +variable {V E : Type*} [Fintype V] [Fintype E] [DecidableEq V] [DecidableEq E] + +/-- The small-entropy regime of the nonlinear barrier function. -/ +theorem entropy_barrier_ge_id {t : ℝ} (ht : 0 ≤ t) (h8 : t ≤ Real.log 8) : + t ≤ 8 * (1-Real.exp (-t)) := by + have he : 1 ≤ Real.exp t := Real.one_le_exp_iff.mpr ht + have he8 : Real.exp t ≤ 8 := by + have hh := Real.exp_le_exp.mpr h8 + rw [Real.exp_log (by norm_num : (0 : ℝ) < 8)] at hh + exact hh + have hlog := Real.log_le_sub_one_of_pos (Real.exp_pos t) + rw [Real.log_exp] at hlog + have hin := Real.exp_neg t + rw [hin] + have hp := Real.exp_pos t + apply (mul_le_mul_iff_right₀ hp).mp + have hmain : t * Real.exp t ≤ 8 * (Real.exp t - 1) := by + have : t ≤ Real.exp t - 1 := hlog + nlinarith + have hprod : Real.exp t * (8*(1-(Real.exp t)⁻¹)) = 8*(Real.exp t-1) := by + field_simp [hp.ne'] + calc + Real.exp t * t = t * Real.exp t := mul_comm _ _ + _ ≤ 8 * (Real.exp t-1) := hmain + _ = _ := hprod.symm + + +/-- Entropy on s positive edge coordinates of total mass m is at most m log(s/m). -/ +theorem marginal_entropy_support_bound (G : LooplessGraph V E) {m : ℕ} + (hm : 0 < m) (hV : Fintype.card V=2*m) {x : E → ℝ} (hx : x ∈ G.polytope) : + 0 ≤ entropy x ∧ 0 < Fintype.card {e // 0 < x e} ∧ + entropy x ≤ (m:ℝ)*Real.log ((Fintype.card {e // 0 < x e}:ℝ)/(m:ℝ)) := by + have hmR : (0:ℝ) < m := by exact_mod_cast hm + have hmass := G.marginal_sum hV hx + have hn : ∀ e, 0 ≤ x e := fun e => (G.coordinate_mem_Icc hx e).1 + have hz : ∀ e, ¬ 0 < x e → x e=0 := fun e he => le_antisymm (le_of_not_gt he) (hn e) + have hsum : (∑ e : {e // 0 < x e}, x e.val)=(m:ℝ) := + (sum_positive_support x x hz).symm.trans hmass + have hent : entropy (fun e : {e // 0 < x e} => x e.val)=entropy x := by + unfold entropy + exact (sum_positive_support x (fun e => Real.negMulLog (x e)) + (fun e he => by rw [hz e he,Real.negMulLog_zero])).symm + have hpossum : 0 < ∑ e, x e := by rw [hmass]; exact hmR + obtain ⟨e,_,he⟩ := (Finset.sum_pos_iff_of_nonneg (fun e _ => hn e)).mp hpossum + have hs : 0 < Fintype.card {e // 0 < x e} := Fintype.card_pos_iff.mpr ⟨⟨e,he⟩⟩ + have hsR : (0:ℝ) < Fintype.card {e // 0 < x e} := by exact_mod_cast hs + refine ⟨Finset.sum_nonneg (fun e _ => Real.negMulLog_nonneg (hn e) (G.coordinate_mem_Icc hx e).2),hs,?_⟩ + let c : ℝ := (Fintype.card {e // 0 < x e}:ℝ)/(m:ℝ) + have hc : 0 < c := div_pos hsR hmR + have hcm : c*(m:ℝ)=Fintype.card {e // 0 < x e} := div_mul_cancel₀ _ hmR.ne' + have hb := Finset.sum_le_sum (s := Finset.univ) (fun e : {e // 0 < x e} => fun _ => + Real.negMulLog_le_one_sub_self (mul_nonneg hc.le e.property.le)) + simp_rw [Real.negMulLog_mul] at hb + rw [Finset.sum_add_distrib,← Finset.sum_mul,← Finset.mul_sum,hsum, + Finset.sum_sub_distrib,← Finset.mul_sum,hsum] at hb + simp only [Finset.sum_const,Finset.card_univ,nsmul_eq_mul,mul_one] at hb + change (m:ℝ)*Real.negMulLog c+c*entropy (fun e : {e // 0 < x e} => x e.val) ≤ + (Fintype.card {e // 0 < x e}:ℝ)-c*(m:ℝ) at hb + rw [hent,Real.negMulLog,hcm,sub_self] at hb + change entropy x ≤ (m:ℝ)*Real.log c + nlinarith + +/-- Main entropy comparison, for every marginal in the actual matching polytope. -/ +theorem entropy_main (G : LooplessGraph V E) (m : ℕ) + (hm : 0 < m) (hV : Fintype.card V = 2 * m) + (hPM : Nonempty G.Matching) (y : E → ℝ) (hy : y ∈ G.polytope) : + marginalEntropy y - maxMatchingEntropy G y ≤ + 8 * (m : ℝ) * (1 - Real.exp (-marginalEntropy y / (m : ℝ))) := by + have hmR : (0:ℝ) < m := by exact_mod_cast hm + have heven : Even (Fintype.card V) := by rw [hV]; exact even_two_mul m + obtain ⟨x,hx,hmax⟩ := entropyDefect_attains_max G heven hPM (m:ℝ) + by_contra htarget + have hypos : 0 < entropyDefect G (m:ℝ) y := by + dsimp [entropyDefect,entropyBarrier,marginalEntropy] at * + linarith + have hpos : 0 < entropyDefect G (m:ℝ) x := hypos.trans_le (hmax y hy) + obtain ⟨p,hp,hopt⟩ := maxMatchingEntropy_attained G hx + obtain ⟨hxnon,hspos,hentropy⟩ := marginal_entropy_support_bound G hm hV hx + have hH := maxMatchingEntropy_nonneg G hx + let s : ℝ := Fintype.card {e // 0 < x e} + have hsR : 0 < s := by dsimp only [s]; exact_mod_cast hspos + have hrpos : 0 < s/(m:ℝ) := div_pos hsR hmR + have hu : entropy x/(m:ℝ) ≤ Real.log (s/(m:ℝ)) := by + apply (div_le_iff₀ hmR).mpr + simpa only [mul_comm] using hentropy + have hlo : Real.log 8 < entropy x/(m:ℝ) := by + by_contra hle + have hb := entropy_barrier_ge_id (div_nonneg hxnon hmR.le) (le_of_not_gt hle) + have hb' := (div_le_iff₀ hmR).mp hb + dsimp only [entropyDefect,entropyBarrier] at hpos + rw [neg_div] at hpos + nlinarith + have hs8 : 8*(m:ℝ) < s := by + have hh := (Real.log_lt_log_iff (by norm_num : (0:ℝ)<8) hrpos).mp (hlo.trans_le hu) + exact (lt_div_iff₀ hmR).mp hh + have ha : 8*(m:ℝ)/s ≤ 8*Real.exp (-entropy x/(m:ℝ)) := by + have hh := Real.exp_le_exp.mpr (neg_le_neg hu) + rw [Real.exp_neg,Real.exp_log hrpos,inv_div] at hh + rw [neg_div,mul_div_assoc] + exact mul_le_mul_of_nonneg_left hh (by norm_num) + have hrankNat := matching_covariance_rank G heven hp hopt + rw [hV] at hrankNat + have hrankR : s ≤ 2*(2*(m:ℝ))+(covariance p (matchingNormalized G x)).rank := by + dsimp only [s] + exact_mod_cast hrankNat + have hrank : s-4*(m:ℝ) ≤ (covariance p (matchingNormalized G x)).rank := by linarith + exact covariance_contradiction (covariance_posSemidef p (matchingNormalized G x)) hmR hs8 + hrank (matching_covariance_trace G hp hV) ha + (matching_covariance_second_variation G hp hopt hmR hmax) + + +omit [Fintype V] [Fintype E] [DecidableEq V] in +/-- An edge partition into k matchings places the exact uniform edge vector in P. -/ +theorem uniform_decomposition_mem (G : LooplessGraph V E) {k : ℕ} (hk : 1 ≤ k) + (M : Fin k → G.Matching) + (hpartition : ∀ e : E, ∃! i : Fin k, e ∈ (M i).val) : + (fun _ : E => 1/(k:ℝ)) ∈ G.polytope := by + classical + have hkR : (0:ℝ) < k := by exact_mod_cast (show 0 < k by omega) + have hsum : (∑ i : Fin k, (1/(k:ℝ)))=1 := by + simp only [Finset.sum_const,Finset.card_univ,Fintype.card_fin,nsmul_eq_mul] + field_simp + have hmean := (convex_convexHull ℝ (Set.range G.indicator)).sum_mem + (fun (i : Fin k) _ => (one_div_pos.mpr hkR).le) hsum + (fun i _ => subset_convexHull ℝ _ (Set.mem_range_self (M i))) + have heq : (∑ i : Fin k, (1/(k:ℝ)) • G.indicator (M i)) = (fun _ : E => 1/(k:ℝ)) := by + ext e + simp only [Finset.sum_apply,Pi.smul_apply,smul_eq_mul] + rw [← Finset.mul_sum] + have hi : (∑ i : Fin k, G.indicator (M i) e)=1 := by + obtain ⟨i,hi,hu⟩ := hpartition e + rw [Finset.sum_eq_single i] + · simp [LooplessGraph.indicator,hi] + · intro j _ hji + have hj : e ∉ (M j).val := fun h => hji (hu j h) + simp [LooplessGraph.indicator,hj] + · simp + rw [hi,mul_one] + rwa [heq] at hmean + +/-- The exact decomposable-graph count theorem, including its coarser bound. -/ +theorem count_main (G : LooplessGraph V E) (m k : ℕ) + (hm : 0 < m) (hV : Fintype.card V = 2 * m) (hk : 1 ≤ k) + (M : Fin k → G.Matching) + (hpartition : ∀ e : E, ∃! i : Fin k, e ∈ (M i).val) : + ((k : ℝ) * Real.exp (-8 * (1 - 1 / (k : ℝ)))) ^ m ≤ + (Fintype.card G.Matching : ℝ) ∧ + (Real.exp (-8) * (k : ℝ)) ^ m ≤ + ((k : ℝ) * Real.exp (-8 * (1 - 1 / (k : ℝ)))) ^ m := by + have hkR : (0:ℝ) < k := by exact_mod_cast (show 0 < k by omega) + have hmR : (0:ℝ) < m := by exact_mod_cast hm + have hPM : Nonempty G.Matching := ⟨M ⟨0,by omega⟩⟩ + let x : E → ℝ := fun _ => 1/(k:ℝ) + have hx : x ∈ G.polytope := uniform_decomposition_mem G hk M hpartition + have hh : marginalEntropy x=(m:ℝ)*Real.log (k:ℝ) := by + have hlog : Real.negMulLog (1/(k:ℝ))=(1/(k:ℝ))*Real.log (k:ℝ) := by + rw [one_div,Real.negMulLog,Real.log_inv] + ring + change (∑ e : E, Real.negMulLog (1/(k:ℝ)))=_ + simp_rw [hlog] + rw [← Finset.sum_mul] + exact congrArg (fun t : ℝ => t*Real.log (k:ℝ)) (G.marginal_sum hV hx) + have hi := entropy_main G m hm hV hPM x hx + have hH := maxMatchingEntropy_le_log_card G hx + have hexp : Real.exp (-((m:ℝ)*Real.log (k:ℝ))/(m:ℝ))=1/(k:ℝ) := by + have he : -((m:ℝ)*Real.log (k:ℝ))/(m:ℝ) = -Real.log (k:ℝ) := by + field_simp + rw [he,Real.exp_neg,Real.exp_log hkR] + simp only [one_div] + rw [hh,hexp] at hi + have hlogbound : (m:ℝ)*(Real.log (k:ℝ)+(-8*(1-1/(k:ℝ)))) ≤ + Real.log (Fintype.card G.Matching:ℝ) := by nlinarith + have hN : (0:ℝ) < Fintype.card G.Matching := by + exact_mod_cast Fintype.card_pos_iff.mpr hPM + constructor + · have he := Real.exp_le_exp.mpr hlogbound + rw [Real.exp_log hN,Real.exp_nat_mul,Real.exp_add,Real.exp_log hkR] at he + exact he + · apply pow_le_pow_left₀ (mul_nonneg (Real.exp_pos _).le hkR.le) + have he : Real.exp (-8) ≤ Real.exp (-8*(1-1/(k:ℝ))) := by + apply Real.exp_le_exp.mpr + have hq := (one_div_pos.mpr hkR).le + nlinarith + calc + Real.exp (-8)*(k:ℝ) = (k:ℝ)*Real.exp (-8) := mul_comm _ _ + _ ≤ _ := mul_le_mul_of_nonneg_left he hkR.le + +end MatchingEntropy + +end + +end OAI diff --git a/lean/OAI/Combinatorics/PerfectMatching/MatchingCovariance.lean b/lean/OAI/Combinatorics/PerfectMatching/MatchingCovariance.lean new file mode 100644 index 0000000000000000000000000000000000000000..4e8a42b8f60d19a41f38082739d9b29f77b4e789 --- /dev/null +++ b/lean/OAI/Combinatorics/PerfectMatching/MatchingCovariance.lean @@ -0,0 +1,249 @@ +import OAI.Combinatorics.PerfectMatching.Continuity +import OAI.Combinatorics.PerfectMatching.Covariance + +namespace OAI + +/-! +Normalized matching covariance: face rank, exact trace, and second variation. +-/ + +noncomputable section + +open scoped BigOperators Topology +open Filter + +namespace MatchingEntropy + +open Matrix + +variable {V E : Type*} [Fintype V] [Fintype E] [DecidableEq V] [DecidableEq E] + +/-- Normalized matching directions on exactly the positive edge support. -/ +def matchingNormalized (G : LooplessGraph V E) (x : E → ℝ) : + G.Matching → {e // 0 < x e} → ℝ := + normalizedCentered (fun M e => G.indicator M e.val) (fun e => x e.val) + +omit [Fintype V] [DecidableEq V] in +theorem matchingNormalized_average (G : LooplessGraph V E) {x y : E → ℝ} + {q : G.Matching → ℝ} (hq : q ∈ G.feasibleLaws y) (e : {e // 0 < x e}) : + (∑ M, q M*matchingNormalized G x M e)=(y e.val-x e.val)/Real.sqrt (x e.val) := by + simp only [matchingNormalized,normalizedCentered,← mul_div_assoc,mul_sub, + ← Finset.sum_div,Finset.sum_sub_distrib,← Finset.sum_mul,hq.1.2,one_mul] + rw [show (∑ M, q M*G.indicator M e.val)=y e.val from congrFun hq.2 e.val] + +omit [Fintype V] [DecidableEq V] in +/-- A feasible two-sided direction has a positive-side law supported on the +entropy optimizer at its midpoint. -/ +theorem midpoint_law_support (G : LooplessGraph V E) {x v : E → ℝ} {a : ℝ} + {p q r : G.Matching → ℝ} (hp : p ∈ G.feasibleLaws x) + (hopt : entropy p=maxMatchingEntropy G x) + (hq : q ∈ G.feasibleLaws (x+a • v)) + (hr : r ∈ G.feasibleLaws (x+(-a) • v)) : + ∀ M, 0 < q M → 0 < p M := by + let w : G.Matching → ℝ := (1/2:ℝ) • q+(1/2:ℝ) • r + have hw : w ∈ G.feasibleLaws x := by + refine ⟨convex_probabilitySimplex _ hq.1 hr.1 (by norm_num) (by norm_num) (by norm_num),?_⟩ + change G.meanLinear ((1/2:ℝ) • q+(1/2:ℝ) • r) = _ + rw [map_add,map_smul,map_smul] + change (1/2:ℝ) • G.mean q+(1/2:ℝ) • G.mean r = _ + rw [hq.2,hr.2] + ext e + simp only [Pi.add_apply,Pi.smul_apply,smul_eq_mul] + ring + intro M hM + apply matching_optimizer_support G hp hw hopt + change 0 < (1/2:ℝ)*q M+(1/2:ℝ)*r M + have hh := hr.1.1 M + linarith + +/-- Every active-face direction belongs to the optimizer's normalized covariance +span. No face support or dimension assertion is being supplied as a hypothesis. -/ +theorem normalized_face_mem (G : LooplessGraph V E) {x : E → ℝ} + (heven : Even (Fintype.card V)) {p : G.Matching → ℝ} + (hp : p ∈ G.feasibleLaws x) (hopt : entropy p=maxMatchingEntropy G x) + {u : {e // 0 < x e} → ℝ} (hu : u ∈ G.faceSpace x) : + (fun e => u e/Real.sqrt (x e.val)) ∈ weightedDirectionSpace p (matchingNormalized G x) := by + have hx : x ∈ G.polytope := (G.mem_polytope_iff x).mpr ⟨p,hp⟩ + have hev := G.faceSpace_eventually_line (G.polytope_subset_constraintPolytope hx) hu + have hneg : ∀ᶠ t : ℝ in 𝓝 0, x+(-t) • LooplessGraph.positiveExtension x u ∈ G.constraintPolytope := by + have hc : Tendsto (fun t : ℝ => -t) (𝓝 0) (𝓝 0) := by simpa using continuous_neg.tendsto (0:ℝ) + exact hc.eventually hev + have hh : ∀ᶠ t : ℝ in 𝓝[>] 0, + (x+t • LooplessGraph.positiveExtension x u ∈ G.constraintPolytope ∧ + x+(-t) • LooplessGraph.positiveExtension x u ∈ G.constraintPolytope) ∧ 0 < t := + ((hev.and hneg).filter_mono nhdsWithin_le_nhds).and eventually_mem_nhdsWithin + obtain ⟨a,⟨ha,hna⟩,ha0⟩ := hh.exists + rw [← G.polytope_eq_constraints heven] at ha hna + obtain ⟨q,hq⟩ := (G.mem_polytope_iff _).mp ha + obtain ⟨r,hr⟩ := (G.mem_polytope_iff _).mp hna + have hsupp := midpoint_law_support G hp hopt hq hr + have hsum : (∑ M, q M • matchingNormalized G x M) ∈ + weightedDirectionSpace p (matchingNormalized G x) := by + apply Submodule.sum_mem + intro M _ + by_cases hM : 0 < p M + · exact Submodule.smul_mem _ _ (Submodule.subset_span ⟨⟨M,hM⟩,rfl⟩) + · have hq0 : q M=0 := le_antisymm (le_of_not_gt fun hqM => hM (hsupp M hqM)) (hq.1.1 M) + simp only [hq0,zero_smul] + exact Submodule.zero_mem _ + have hin := Submodule.smul_mem _ a⁻¹ hsum + have he : a⁻¹ • (∑ M, q M • matchingNormalized G x M) = + (fun e => u e/Real.sqrt (x e.val)) := by + ext e + simp only [Pi.smul_apply,Finset.sum_apply,smul_eq_mul] + rw [matchingNormalized_average G hq] + simp only [Pi.add_apply,Pi.smul_apply,smul_eq_mul,LooplessGraph.positiveExtension_pos] + field_simp + ring + rwa [he] at hin + +def normalizeLinear (x : E → ℝ) : + ({e // 0 < x e} → ℝ) →ₗ[ℝ] ({e // 0 < x e} → ℝ) where + toFun := fun u e => u e/Real.sqrt (x e.val) + map_add' := by intro u v; ext e; exact add_div _ _ _ + map_smul' := by intro a u; ext e; exact mul_div_assoc _ _ _ + +/-- Face codimension gives a lower bound for the rank of the genuine covariance. -/ +theorem matching_covariance_rank (G : LooplessGraph V E) {x : E → ℝ} + (heven : Even (Fintype.card V)) {p : G.Matching → ℝ} + (hp : p ∈ G.feasibleLaws x) (hopt : entropy p=maxMatchingEntropy G x) : + Fintype.card {e // 0 < x e} ≤ 2*Fintype.card V+ + (covariance p (matchingNormalized G x)).rank := by + let W := weightedDirectionSpace p (matchingNormalized G x) + let L : G.faceSpace x →ₗ[ℝ] W := + ((normalizeLinear x).comp (G.faceSpace x).subtype).codRestrict W + (fun u => normalized_face_mem G heven hp hopt u.property) + have hi : Function.Injective L := by + intro u v huv + apply Subtype.ext + funext e + have hh := congrFun (congrArg Subtype.val huv) e + change u.val e/Real.sqrt (x e.val)=v.val e/Real.sqrt (x e.val) at hh + exact (div_left_inj' (ne_of_gt (Real.sqrt_pos.mpr e.property))).mp hh + have hdim := LinearMap.finrank_le_finrank_of_injective hi + have hq := (G.faceSpace x).finrank_quotient_add_finrank + have hc := G.faceCodimension_bound heven ((G.mem_polytope_iff x).mpr ⟨p,hp⟩) + rw [covariance_rank hp.1.1] + have hq' : G.faceCodimension x+Module.finrank ℝ (G.faceSpace x)=Fintype.card {e // 0 < x e} := by + simpa only [LooplessGraph.faceCodimension,Module.finrank_pi,Module.finrank_self,Finset.sum_const, + Finset.card_univ,smul_eq_mul,mul_one] using hq + change Module.finrank ℝ (G.faceSpace x) ≤ Module.finrank ℝ W at hdim + dsimp only [W] at hdim + omega + + +omit [DecidableEq E] in +theorem sum_positive_support (x f : E → ℝ) (hf : ∀ e, ¬ 0 < x e → f e=0) : + (∑ e, f e) = ∑ e : {e // 0 < x e}, f e.val := by + classical + have hz : (∑ e : {e // ¬ 0 < x e}, f e.val)=0 := + Finset.sum_eq_zero fun e _ => hf e.val e.property + have hh := Fintype.sum_subtype_add_sum_subtype (fun e => 0 < x e) f + rw [hz,add_zero] at hh + exact hh.symm + +def matchingScoreWeights (x : E → ℝ) (u : {e // 0 < x e} → ℝ) : E → ℝ := + LooplessGraph.positiveExtension x (fun e => u e/Real.sqrt (x e.val)) + +omit [Fintype V] [DecidableEq V] in +theorem matchingNormalized_score (G : LooplessGraph V E) (x : E → ℝ) + (u : {e // 0 < x e} → ℝ) (M : G.Matching) : + linearScore G (matchingScoreWeights x u) (∑ e, matchingScoreWeights x u e*x e) M = + matchingNormalized G x M ⬝ᵥ u := by + classical + unfold linearScore + rw [← Finset.sum_sub_distrib] + rw [sum_positive_support x _ (fun e he => by simp [matchingScoreWeights,LooplessGraph.positiveExtension,he])] + rw [dotProduct] + apply Finset.sum_congr rfl + intro e _ + simp only [matchingScoreWeights,LooplessGraph.positiveExtension_pos,matchingNormalized,normalizedCentered] + ring + +omit [Fintype V] [DecidableEq V] in +theorem matchingNormalized_mulVec (G : LooplessGraph V E) {x : E → ℝ} + {p : G.Matching → ℝ} (hp : p ∈ G.feasibleLaws x) + (u : {e // 0 < x e} → ℝ) (e : {e // 0 < x e}) : + (covariance p (matchingNormalized G x) *ᵥ u) e = + G.mean (fun M => p M * linearScore G (matchingScoreWeights x u) + (∑ e, matchingScoreWeights x u e*x e) M) e.val / Real.sqrt (x e.val) := by + let a := linearScore G (matchingScoreWeights x u) (∑ e, matchingScoreWeights x u e*x e) + have hcenter : ∑ M, p M*a M=0 := by + dsimp only [a] + rw [linearScore_expectation,hp.2,hp.1.2,mul_one,sub_self] + calc + _ = ∑ M, (p M*a M*G.indicator M e.val-x e.val*(p M*a M))/Real.sqrt (x e.val) := by + rw [covariance_mulVec hp.1.1] + apply Finset.sum_congr rfl + intro M _ + rw [← matchingNormalized_score G x u M] + change p M*((G.indicator M e.val-x e.val)/Real.sqrt (x e.val))*a M = _ + ring + _ = _ := by + rw [← Finset.sum_div,Finset.sum_sub_distrib,← Finset.mul_sum,hcenter,mul_zero,sub_zero] + rfl + +/-- The normalized covariance has the exact trace s-m. -/ +theorem matching_covariance_trace (G : LooplessGraph V E) {x : E → ℝ} + {p : G.Matching → ℝ} (hp : p ∈ G.feasibleLaws x) {m : ℕ} + (hV : Fintype.card V=2*m) : + (covariance p (matchingNormalized G x)).trace = Fintype.card {e // 0 < x e}-(m:ℝ) := by + have hx : x ∈ G.polytope := (G.mem_polytope_iff x).mpr ⟨p,hp⟩ + have hsum : (∑ e : {e // 0 < x e}, x e.val)=(m:ℝ) := by + rw [← G.marginal_sum hV hx] + exact (sum_positive_support x x (fun e he => le_antisymm (le_of_not_gt he) (G.coordinate_mem_Icc hx e).1)).symm + unfold matchingNormalized + rw [normalized_covariance_trace hp.1 _ ?_ _ ?_ (fun e => e.property),hsum] + · intro M e + simp only [LooplessGraph.indicator] + split <;> norm_num + · intro e + exact congrFun hp.2 e.val + +omit [Fintype V] [DecidableEq V] in +/-- Convert the genuine second variation into the covariance spectral inequality. -/ +theorem matching_covariance_second_variation (G : LooplessGraph V E) {x : E → ℝ} + {p : G.Matching → ℝ} (hp : p ∈ G.feasibleLaws x) + (hopt : entropy p=maxMatchingEntropy G x) {m : ℝ} (hm : 0 < m) + (hmax : ∀ y ∈ G.polytope, entropyDefect G m y ≤ entropyDefect G m x) + (u : {e // 0 < x e} → ℝ) : + (8*Real.exp (-entropy x/m)-1)* + ((covariance p (matchingNormalized G x) *ᵥ u) ⬝ᵥ + (covariance p (matchingNormalized G x) *ᵥ u)) + + u ⬝ᵥ (covariance p (matchingNormalized G x) *ᵥ u) ≤ 0 := by + let w := matchingScoreWeights x u + let c := ∑ e, w e*x e + let a := linearScore G w c + have hcenter : ∑ M, p M*a M=0 := by + dsimp only [a,c] + rw [linearScore_expectation,hp.2,hp.1.2,mul_one,sub_self] + have hh := matching_defect_second_variation G hp hopt hm.ne' hmax w c hcenter + have hnorm : (∑ e, (G.mean (fun M => p M*a M) e)^2/x e) = + (covariance p (matchingNormalized G x) *ᵥ u) ⬝ᵥ + (covariance p (matchingNormalized G x) *ᵥ u) := by + have hx : x ∈ G.polytope := (G.mem_polytope_iff x).mpr ⟨p,hp⟩ + rw [sum_positive_support x _ (fun e he => by + have hz : x e=0 := le_antisymm (le_of_not_gt he) (G.coordinate_mem_Icc hx e).1 + simp [hz])] + rw [dotProduct] + apply Finset.sum_congr rfl + intro e _ + rw [matchingNormalized_mulVec G hp,← sq,div_pow,Real.sq_sqrt e.property.le] + have hquad : (∑ M, p M*(a M)^2) = u ⬝ᵥ (covariance p (matchingNormalized G x) *ᵥ u) := by + rw [covariance_quadratic hp.1.1] + apply Finset.sum_congr rfl + intro M _ + rw [← matchingNormalized_score G x u M] + change (8*Real.exp (-entropy x/m)-1)*(∑ e, (G.mean (fun M => p M*a M) e)^2/x e)+ + (8*Real.exp (-entropy x/m)/m)*(entropyLineD x (G.mean (fun M => p M*a M)) 0)^2+ + (∑ M, p M*(a M)^2) ≤ 0 at hh + rw [hnorm,hquad] at hh + have hpterm : 0 ≤ (8*Real.exp (-entropy x/m)/m)* + (entropyLineD x (G.mean (fun M => p M*a M)) 0)^2 := by positivity + linarith + +end MatchingEntropy + +end + +end OAI diff --git a/lean/OAI/Combinatorics/PerfectMatching/Model.lean b/lean/OAI/Combinatorics/PerfectMatching/Model.lean new file mode 100644 index 0000000000000000000000000000000000000000..06ae3ddc4bec49ca96af51a8ffad778e479db670 --- /dev/null +++ b/lean/OAI/Combinatorics/PerfectMatching/Model.lean @@ -0,0 +1,62 @@ +import Mathlib + +namespace OAI + +universe u_1 u_2 + +namespace MatchingEntropy +structure LooplessGraph (V : Type u_1) (E : Type u_2) where + left : E → V + right : E → V + loopless : ∀ e, left e ≠ right e +namespace LooplessGraph +variable {V : Type u_1} {E : Type u_2} [Fintype V] [Fintype E] [DecidableEq V] [DecidableEq E] +def Incident (G : LooplessGraph V E) (v : V) (e : E) : Prop := + G.left e=v ∨ G.right e=v +def IsPerfectMatching (G : LooplessGraph V E) (M : Finset E) : Prop := + ∀ v, ∃! e, e∈M ∧ G.Incident v e +abbrev Matching (G : LooplessGraph V E) := {M : Finset E // G.IsPerfectMatching M} +noncomputable instance matchingFintype (G : LooplessGraph V E) : Fintype G.Matching := + Fintype.ofFinite _ +end LooplessGraph +end MatchingEntropy + +namespace BinaryMatching +abbrev Pair (n : ℕ) := {ij : Fin n × Fin n // ij.1 < ij.2} +def completeGraph (n : ℕ) : MatchingEntropy.LooplessGraph (Fin n) (Pair n) where + left e := e.val.1 + right e := e.val.2 + loopless e := ne_of_lt e.property + +structure Record where + left : ℕ + right : ℕ + multiplicity : ℕ + deriving DecidableEq + +structure Input where + n : ℕ + records : List Record + valid : ∀ e∈records, e.left < e.right ∧ e.right < n + unique : (records.map (fun e => (e.left,e.right))).Nodup + +def multiplicity (G : Input) (e : Pair G.n) : ℕ := + match G.records.find? (fun r => r.left=e.val.1.val && r.right=e.val.2.val) with + | none => 0 + | some r => r.multiplicity + +noncomputable def count (G : Input) : ℕ := + ∑ M : (completeGraph G.n).Matching, ∏ e∈M.val, multiplicity G e + +def encodeNat (n : ℕ) : List Bool := + List.replicate n.bits.length false ++ true :: n.bits + +def encodeRecord (r : Record) : List Bool := + encodeNat r.left ++ encodeNat r.right ++ encodeNat r.multiplicity + +def encodeInput (G : Input) : List Bool := + encodeNat G.n ++ encodeNat G.records.length ++ G.records.flatMap encodeRecord + +end BinaryMatching + +end OAI diff --git a/lean/OAI/Combinatorics/PerfectMatching/ObjectivePenalty.lean b/lean/OAI/Combinatorics/PerfectMatching/ObjectivePenalty.lean new file mode 100644 index 0000000000000000000000000000000000000000..c50599b2642d638f0aefaaf9a839df287cecdc24 --- /dev/null +++ b/lean/OAI/Combinatorics/PerfectMatching/ObjectivePenalty.lean @@ -0,0 +1,206 @@ +import OAI.Combinatorics.PerfectMatching.Violation + +namespace OAI + +section + +namespace BinaryMatching.Algorithm +noncomputable section +open Finset + +lemma foldl_max_le (l : List ℕ) (a b : ℕ) (ha : a≤b) (hl : ∀ x∈l,x≤b) : + l.foldl max a≤b := by + induction l generalizing a with + | nil => exact ha + | cons x xs ih => + exact ih (max a x) (max_le ha (hl x (by simp))) (fun y hy => hl y (by simp [hy])) + +lemma le_foldl_max (l : List ℕ) (a : ℕ) : a≤l.foldl max a := by + induction l generalizing a with + | nil => rfl + | cons x xs ih => exact (le_max_left a x).trans (ih (max a x)) + +lemma mem_le_foldl_max (l : List ℕ) (a x : ℕ) (hx : x∈l) : x≤l.foldl max a := by + induction l generalizing a with + | nil => simp at hx + | cons y ys ih => + rcases List.mem_cons.mp hx with rfl|h + · exact (le_max_right a x).trans (le_foldl_max ys (max a x)) + · exact ih (max a y) h + +lemma record_log_le_B (G : Input) (r : Record) (hr : r∈G.records) : Nat.log2 r.multiplicity≤B G := + mem_le_foldl_max _ 0 _ (List.mem_map.mpr ⟨r,hr,rfl⟩) + +lemma multiplicity_log_le_B (G : Input) (e : Pair G.n) : Nat.log2 (multiplicity G e)≤B G := by + unfold multiplicity + cases he : G.records.find? (fun r => r.left=e.val.1.val && r.right=e.val.2.val) with + | none => simp + | some r => exact record_log_le_B G r (List.mem_of_find?_eq_some he) + +lemma B_le_L (G : Input) : B G≤L G := by + have h : B G≤G.n+B G+1 := by omega + have hp : 1≤G.n+B G+1 := by omega + have hpow : G.n+B G+1≤(G.n+B G+1)^3 := by exact Nat.le_self_pow (by omega) _ + unfold L + omega + +lemma beta_bound (G : Input) (e : Pair G.n) : |(beta G e:ℝ)|≤L G := by + unfold beta + split_ifs + · simp + · have hh := (multiplicity_log_le_B G e).trans (B_le_L G) + norm_cast + +lemma piece_slope_bound (k : ℕ) (p : Piece) (hp : p∈pieces k) : |(p.slope:ℝ)|≤k := by + rcases (mem_pieces k p).1 hp with rfl|⟨j,hj,rfl⟩ + · simp + · simp only [Int.cast_sub,Int.cast_natCast,Int.cast_one] + have hj' : (j:ℝ)+1≤k := by exact_mod_cast hj + have hj0 : (0:ℝ)≤j := by positivity + rw [abs_le]; constructor <;> linarith + +lemma piece_supergradient (k : ℕ) (p : Piece) (hp : p∈pieces k) (x : ℝ) + (ha : p.evalReal x=psiReal k x) (z : ℝ) : + psiReal k z≤psiReal k x+(p.slope:ℝ)*(z-x) := by + have hh := psiReal_le_piece k z p hp + rw [←ha] + calc + _ ≤ p.evalReal z := hh + _ = p.evalReal x+(p.slope:ℝ)*(z-x) := by unfold Piece.evalReal; ring + +lemma selectedPiece_supergradient (k : ℕ) (x : ℚ) (z : ℝ) : + psiReal k z≤psiReal k (x:ℝ)+(slope k x:ℝ)*(z-(x:ℝ)) := by + apply piece_supergradient k (selectedPiece k x) + (List.argmin_mem (selectedPiece_mem_argmin k x)) (x:ℝ) _ z + rw [realPsi_cast] + simp [Piece.evalReal,Piece.eval,psi] + +lemma psiReal_abs_sub (k : ℕ) (x y : ℝ) : |psiReal k x-psiReal k y|≤k*|x-y| := by + have h (a b : ℝ) : psiReal k a-psiReal k b≤k*|a-b| := by + have hm := List.argmin_mem (selectedReal_mem_argmin k b) + have hh := piece_supergradient k (selectedReal k b) hm b rfl a + have hb := piece_slope_bound k _ hm + have hab := le_abs_self ((selectedReal k b).slope*(a-b)) + rw [abs_mul] at hab + have hu := mul_le_mul_of_nonneg_right hb (abs_nonneg (a-b)) + linarith + rw [abs_le] + have hx := h x y + have hy := h y x + rw [abs_sub_comm y x] at hy + exact ⟨by linarith,hx⟩ + +def objective (G : Input) (x : Pair G.n → ℝ) : ℝ := + ∑ e, (psiReal (K G.n) (x e)+(beta G e:ℝ)*x e) + +def penalized (G : Input) (x : Pair G.n → ℝ) : ℝ := + objective G x-(M₀ G:ℝ)*violation x + +lemma objective_lipschitz (G : Input) (x y : Pair G.n → ℝ) : + |objective G x-objective G y|≤(K G.n+L G:ℝ)*∑ e,|x e-y e| := by + unfold objective + rw [←sum_sub_distrib,mul_sum] + apply (abs_sum_le_sum_abs _ _).trans + apply sum_le_sum; intro e _ + have he : psiReal (K G.n) (x e)+(beta G e:ℝ)*x e- + (psiReal (K G.n) (y e)+(beta G e:ℝ)*y e)= + (psiReal (K G.n) (x e)-psiReal (K G.n) (y e))+(beta G e:ℝ)*(x e-y e) := by ring + rw [he] + have hb := mul_le_mul_of_nonneg_right (beta_bound G e) (abs_nonneg (x e-y e)) + have hh := abs_add_le (psiReal (K G.n) (x e)-psiReal (K G.n) (y e)) ((beta G e:ℝ)*(x e-y e)) + rw [abs_mul] at hh + linarith [psiReal_abs_sub (K G.n) (x e) (y e)] + +lemma exact_penalty (G : Input) (hn : 4≤G.n) (heven : Even G.n) + (x : Pair G.n → ℝ) (hx : ∀ e,x e∈Set.Icc (0:ℝ) 1) : + ∃ y∈(completeGraph G.n).polytope,penalized G x≤objective G y := by + obtain ⟨y,hy,hdist⟩ := violation_repair hn heven x hx + refine ⟨y,hy,?_⟩ + have hsum : (∑ e,|x e-y e|)≤(q G.n:ℝ)*(2+10*(G.n:ℝ)^2)*violation x := by + calc + _ ≤ ∑ _e : Pair G.n,(2+10*(G.n:ℝ)^2)*violation x := by + apply sum_le_sum; intro e _; rw [abs_sub_comm]; exact hdist e + _ = _ := by simp [q,mul_assoc] + have hh := objective_lipschitz G x y + have hmul := mul_le_mul_of_nonneg_left hsum (show (0:ℝ)≤K G.n+L G by positivity) + have hM : (M₀ G:ℝ)=(q G.n:ℝ)*(K G.n+L G)*(2+10*(G.n:ℝ)^2) := by + simp [M₀,A₀] + unfold penalized + rw [hM] + have hab := le_abs_self (objective G x-objective G y) + nlinarith + +lemma penalized_feasible (G : Input) (heven : Even G.n) {x : Pair G.n → ℝ} + (hx : x∈(completeGraph G.n).polytope) : penalized G x=objective G x := by + simp [penalized,violation_feasible heven hx] + +lemma trialValue_cast (G : Input) (a : Table G.n ℤ) (r : Affine G.n) : + (trialValue G a r:ℝ)=objective G (fun e => (coordinates (D₀ G) a e:ℝ))- + (M₀ G:ℝ)*r.evalReal (fun e => (coordinates (D₀ G) a e:ℝ)) := by + simp [trialValue,objective,realPsi_cast,eval_cast] + +lemma trialValue_correct (G : Input) (hn : 2≤G.n) (heven : Even G.n) + (hD : 0 (coordinates (D₀ G) a e:ℝ)) := by + rw [trialValue_cast,(activeRow_correct hn heven hD a ha).2] + rfl + +lemma gradient_supergradient (G : Input) (hn : 2≤G.n) (heven : Even G.n) + (hD : 0 (coordinates (D₀ G) a e:ℝ))+ + ∑ e,(gradient G a (activeRow (D₀ G) a) e:ℝ)*(z e-(coordinates (D₀ G) a e:ℝ)) := by + let x := fun e => (coordinates (D₀ G) a e:ℝ) + let r := activeRow (D₀ G) a + obtain ⟨hr,hract⟩ := activeRow_correct hn heven hD a ha + have hrow := active_row_subgradient x r hr hract z + have hf : objective G z≤objective G x+ + ∑ e,((slope (K G.n) (coordinates (D₀ G) a e):ℝ)+(beta G e:ℝ))*(z e-x e) := by + rw [objective,objective,←sum_add_distrib] + apply sum_le_sum; intro e _ + have hh := selectedPiece_supergradient (K G.n) (coordinates (D₀ G) a e) (z e) + dsimp [x] at *; nlinarith + have hm := mul_le_mul_of_nonneg_left hrow (show (0:ℝ)≤M₀ G by positivity) + have hgrad : (∑ e,(gradient G a r e:ℝ)*(z e-x e))= + (∑ e,((slope (K G.n) (coordinates (D₀ G) a e):ℝ)+(beta G e:ℝ))*(z e-x e))- + (M₀ G:ℝ)*∑ e,(r.coeff e:ℝ)*(z e-x e) := by + simp only [gradient,Int.cast_sub,Int.cast_add,Int.cast_mul,Int.cast_natCast, + sub_mul,sum_sub_distrib,mul_assoc,mul_sum] + change penalized G z≤penalized G x+∑ e,(gradient G a r e:ℝ)*(z e-x e) + rw [hgrad] + unfold penalized + linarith + +lemma gradient_bound (G : Input) (hn : 2≤G.n) (heven : Even G.n) + (hD : 0 simp [h, mean] + unfold degree + simp_rw [he] + rw [Finset.sum_comm] + apply Finset.sum_congr rfl + intro M _ + rw [← Finset.mul_sum] + change p M*G.degree (G.indicator M) v = p M + rw [G.degree_indicator, mul_one] + +omit [Fintype V] [Fintype E] [DecidableEq E] in +theorem incidence_sum (G : LooplessGraph V E) (e : E) (S : Finset V) : + (∑ v ∈ S, if G.Incident v e then (1:ℕ) else 0) = + (if G.left e ∈ S then 1 else 0) + (if G.right e ∈ S then 1 else 0) := by + have hv : ∀ v, (if G.Incident v e then (1:ℕ) else 0) = + (if v = G.left e then 1 else 0) + (if v = G.right e then 1 else 0) := by + intro v + by_cases hl : v = G.left e <;> by_cases hr : v = G.right e + · exact ((G.loopless e) (hl.symm.trans hr)).elim + · simp [Incident, hl, G.loopless e, Ne.symm (G.loopless e)] + · simp [Incident, hr, G.loopless e, Ne.symm (G.loopless e)] + · simp [Incident, Ne.symm hl, Ne.symm hr, hl, hr] + simp_rw [hv, Finset.sum_add_distrib] + simp + +omit [Fintype V] [Fintype E] [DecidableEq E] in +theorem matching_incidence_count (G : LooplessGraph V E) (M : G.Matching) + (S : Finset V) : + (∑ e ∈ M.val, ((if G.left e ∈ S then (1:ℕ) else 0) + + (if G.right e ∈ S then 1 else 0))) = S.card := by + have hsum : ∀ v, (∑ e ∈ M.val, if G.Incident v e then (1:ℕ) else 0) = 1 := by + intro v + obtain ⟨e, ⟨he, hev⟩, hu⟩ := M.property v + rw [Finset.sum_eq_single e] + · simp [hev] + · intro e' he' hh + have hv : ¬G.Incident v e' := fun hv => hh (hu e' ⟨he', hv⟩) + simp [hv] + · simp [he] + calc + _ = ∑ e ∈ M.val, ∑ v ∈ S, if G.Incident v e then (1:ℕ) else 0 := by + simp_rw [incidence_sum] + _ = ∑ v ∈ S, ∑ e ∈ M.val, if G.Incident v e then (1:ℕ) else 0 := Finset.sum_comm + _ = S.card := by simp_rw [hsum]; simp + +omit [Fintype V] [Fintype E] [DecidableEq E] in +theorem matching_crosses_odd (G : LooplessGraph V E) (M : G.Matching) + (S : Finset V) (hS : Odd S.card) : ∃ e ∈ M.val, G.Crosses S e := by + by_contra h + push Not at h + have heq : ∀ e ∈ M.val, ((if G.left e ∈ S then (1:ℕ) else 0) + + (if G.right e ∈ S then 1 else 0)) = 2*(if G.left e ∈ S then 1 else 0) := by + intro e he + have hc := h e he + simp only [Crosses] at hc + by_cases hl : G.left e ∈ S <;> by_cases hr : G.right e ∈ S <;> + simp_all + have hh := G.matching_incidence_count M S + have heqsum := Finset.sum_congr rfl heq + rw [heqsum, ← Finset.mul_sum] at hh + obtain ⟨k, hk⟩ := hS + omega + + +omit [Fintype V] [DecidableEq E] in +theorem degree_linear (G : LooplessGraph V E) (x y : E → ℝ) (a b : ℝ) (v : V) : + G.degree (a • x+b • y) v = a*G.degree x v+b*G.degree y v := by + have he : ∀ e, (if G.Incident v e then (a • x+b • y) e else 0) = + a*(if G.Incident v e then x e else 0)+b*(if G.Incident v e then y e else 0) := by + intro e + by_cases h : G.Incident v e <;> simp [h] + simp only [degree, he, Finset.sum_add_distrib, ← Finset.mul_sum] + +omit [Fintype V] [DecidableEq E] in +theorem cutMass_linear (G : LooplessGraph V E) (x y : E → ℝ) (a b : ℝ) (S : Finset V) : + G.cutMass (a • x+b • y) S = a*G.cutMass x S+b*G.cutMass y S := by + simp [cutMass, Finset.sum_add_distrib, Finset.mul_sum] + +omit [Fintype V] [DecidableEq E] in +theorem convex_constraintPolytope (G : LooplessGraph V E) : + Convex ℝ G.constraintPolytope := by + intro x hx y hy a b ha hb hab + refine ⟨fun e => add_nonneg (mul_nonneg ha (hx.1 e)) (mul_nonneg hb (hy.1 e)), ?_, ?_⟩ + · intro v + rw [degree_linear, hx.2.1, hy.2.1, mul_one, mul_one, hab] + · intro S hS + rw [cutMass_linear] + calc + 1 = a*1+b*1 := by linarith + _ ≤ _ := add_le_add (mul_le_mul_of_nonneg_left (hx.2.2 S hS) ha) + (mul_le_mul_of_nonneg_left (hy.2.2 S hS) hb) + +omit [Fintype V] in +theorem indicator_mem_constraintPolytope (G : LooplessGraph V E) (M : G.Matching) : + G.indicator M ∈ G.constraintPolytope := by + refine ⟨?_, G.degree_indicator M, ?_⟩ + · intro e; simp [indicator]; split <;> norm_num + · intro S hS + obtain ⟨e, he, hc⟩ := G.matching_crosses_odd M S hS + have h := Finset.single_le_sum (f := G.indicator M) + (s := G.cut S) (a := e) (by intro e' _; simp [indicator]; split <;> norm_num) + ((G.mem_cut S e).mpr hc) + simpa only [cutMass, indicator, he, ite_true] using h + +omit [Fintype V] in +theorem polytope_subset_constraintPolytope (G : LooplessGraph V E) : + G.polytope ⊆ G.constraintPolytope := by + apply convexHull_min + · rintro x ⟨M, rfl⟩ + exact G.indicator_mem_constraintPolytope M + · exact G.convex_constraintPolytope + +omit [Fintype V] [DecidableEq E] in +theorem constraint_coordinate_le_one (G : LooplessGraph V E) {x : E → ℝ} + (hx : x ∈ G.constraintPolytope) (e : E) : x e ≤ 1 := by + have h := Finset.single_le_sum (f := fun e' => if G.Incident (G.left e) e' then x e' else 0) + (s := Finset.univ) (a := e) (by + intro e' _; split; exact hx.1 e'; rfl) (Finset.mem_univ e) + have he : G.Incident (G.left e) e := Or.inl rfl + change (if G.Incident (G.left e) e then x e else 0) ≤ G.degree x (G.left e) at h + simpa only [he, ite_true, hx.2.1] using h + +omit [Fintype V] [DecidableEq E] in +theorem continuous_degree (G : LooplessGraph V E) (v : V) : + Continuous (fun x : E → ℝ => G.degree x v) := by + unfold degree + apply continuous_finsetSum + intro e _ + split <;> fun_prop + +omit [Fintype V] [DecidableEq E] in +theorem continuous_cutMass (G : LooplessGraph V E) (S : Finset V) : + Continuous (fun x : E → ℝ => G.cutMass x S) := by + unfold cutMass + fun_prop + +omit [Fintype V] [DecidableEq E] in +theorem isClosed_constraintPolytope (G : LooplessGraph V E) : + IsClosed G.constraintPolytope := by + simp only [constraintPolytope, Set.ofPred_and, Set.ofPred_forall] + exact (isClosed_iInter fun e => isClosed_le continuous_const (continuous_apply e)).inter + ((isClosed_iInter fun v => isClosed_eq (G.continuous_degree v) continuous_const).inter + (isClosed_iInter fun S => isClosed_iInter fun _ => + isClosed_le continuous_const (G.continuous_cutMass S))) + +omit [Fintype V] [DecidableEq E] in +theorem isCompact_constraintPolytope (G : LooplessGraph V E) : + IsCompact G.constraintPolytope := by + apply (isCompact_Icc : IsCompact (Set.Icc (0 : E → ℝ) 1)).of_isClosed_subset + G.isClosed_constraintPolytope + intro x hx + exact ⟨hx.1, fun e => G.constraint_coordinate_le_one hx e⟩ + +end LooplessGraph + +end MatchingEntropy + +end + +end OAI diff --git a/lean/OAI/Combinatorics/PerfectMatching/Optimizer.lean b/lean/OAI/Combinatorics/PerfectMatching/Optimizer.lean new file mode 100644 index 0000000000000000000000000000000000000000..6c97a79c4b6705c9ef5d8a122313abb975db6cd7 --- /dev/null +++ b/lean/OAI/Combinatorics/PerfectMatching/Optimizer.lean @@ -0,0 +1,245 @@ +import OAI.Combinatorics.PerfectMatching.Entropy + +namespace OAI + +/-! +Support and first-order identities for entropy-maximizing matching laws. +-/ + +noncomputable section + +open scoped BigOperators Topology +open Filter + +namespace MatchingEntropy + +variable {V E : Type*} [Fintype V] [Fintype E] [DecidableEq V] [DecidableEq E] + +/-- Concavity of actual finite-law Shannon entropy. -/ +theorem entropy_mix_ge {ι : Type*} [Fintype ι] {p q : ι → ℝ} + (hp : ∀ i, 0 ≤ p i) (hq : ∀ i, 0 ≤ q i) + {t : ℝ} (ht : t ∈ Set.Icc (0 : ℝ) 1) : + (1-t) * entropy p + t * entropy q ≤ + entropy (fun i => (1-t)*p i + t*q i) := by + unfold entropy + rw [Finset.mul_sum, Finset.mul_sum, ← Finset.sum_add_distrib] + apply Finset.sum_le_sum + intro i _ + simpa only [smul_eq_mul] using Real.concaveOn_negMulLog.2 + (hp i) (hq i) (sub_nonneg.mpr ht.2) ht.1 (by ring : 1-t+t=1) + +/-- A zero probability gains a strict logarithmic bonus under mixing. +This is the boundary argument needed to obtain a positive entropy optimizer +on the entire face, not an assumed regularity of H. -/ +theorem entropy_mix_zero_bonus {ι : Type*} [Fintype ι] {p q : ι → ℝ} + (hp : ∀ i, 0 ≤ p i) (hq : ∀ i, 0 ≤ q i) {j : ι} (hj : p j = 0) + {t : ℝ} (ht : t ∈ Set.Icc (0 : ℝ) 1) : + (1-t) * entropy p + t * entropy q + q j * Real.negMulLog t ≤ + entropy (fun i => (1-t)*p i + t*q i) := by + classical + have hterm : ∀ i, (1-t) * Real.negMulLog (p i) + t * Real.negMulLog (q i) + + (if i=j then q j * Real.negMulLog t else 0) ≤ + Real.negMulLog ((1-t)*p i+t*q i) := by + intro i + by_cases hi : i=j + · subst i + simp only [hj, Real.negMulLog_zero, mul_zero, zero_add, ite_true, + Real.negMulLog_mul] + linarith + · simp only [hi, ↓reduceIte, add_zero] + simpa only [smul_eq_mul] using Real.concaveOn_negMulLog.2 + (hp i) (hq i) (sub_nonneg.mpr ht.2) ht.1 (by ring : 1-t+t=1) + have hh := Finset.sum_le_sum (s := Finset.univ) (fun i _ => hterm i) + simpa only [Finset.sum_add_distrib, ← Finset.mul_sum, + Finset.sum_ite_eq', Finset.mem_univ, ite_true, entropy] using hh + +/-- Every entropy maximizer on a convex feasible set has maximal support. -/ +theorem entropy_maximizer_support {ι : Type*} [Fintype ι] {p q : ι → ℝ} + (hp : ∀ i, 0 ≤ p i) (hq : ∀ i, 0 ≤ q i) + (hmax : ∀ t ∈ Set.Icc (0 : ℝ) 1, + entropy (fun i => (1-t)*p i+t*q i) ≤ entropy p) {j : ι} (hjq : 0 < q j) : + 0 < p j := by + by_contra hj + have hj0 : p j = 0 := le_antisymm (le_of_not_gt hj) (hp j) + have hqp : entropy q ≤ entropy p := by simpa using hmax 1 (by constructor <;> norm_num) + let c := (entropy p-entropy q)/(q j)+1 + have hc : 0 < c := by dsimp [c]; positivity + let t := Real.exp (-c) + have htp : 0 < t := Real.exp_pos _ + have ht : t ∈ Set.Icc (0 : ℝ) 1 := + ⟨htp.le, Real.exp_le_one_iff.mpr (neg_nonpos.mpr hc.le)⟩ + have hbonus := (entropy_mix_zero_bonus hp hq hj0 ht).trans (hmax t ht) + have hlog : Real.log t = -c := Real.log_exp _ + rw [Real.negMulLog, hlog] at hbonus + have he : q j * c = entropy p-entropy q+q j := by + dsimp [c] + field_simp + nlinarith + +omit [Fintype V] [DecidableEq V] in +/-- The preceding support conclusion for the concrete matching-law optimizer. -/ +theorem matching_optimizer_support (G : LooplessGraph V E) {y : E → ℝ} + {p q : G.Matching → ℝ} (hp : p ∈ G.feasibleLaws y) + (hq : q ∈ G.feasibleLaws y) (hopt : entropy p = maxMatchingEntropy G y) + {M : G.Matching} (hM : 0 < q M) : 0 < p M := by + apply entropy_maximizer_support hp.1.1 hq.1.1 _ hM + intro t ht + apply le_trans (entropy_le_maxMatchingEntropy (G := G) (y := y) ?_) (le_of_eq hopt.symm) + constructor + · exact convex_probabilitySimplex _ hp.1 hq.1 + (sub_nonneg.mpr ht.2) ht.1 (by ring) + · calc + G.mean (fun i => (1-t)*p i+t*q i) = + (1-t) • G.mean p + t • G.mean q := by + exact (G.meanLinear).map_add ((1-t) • p) (t • q) |>.trans (by + rw [LinearMap.map_smul, LinearMap.map_smul]; rfl) + _ = y := by rw [hp.2, hq.2]; ext e; simp only [Pi.add_apply, Pi.smul_apply, smul_eq_mul]; ring + + +/-- Supporting-line inequality for -x log x, with no positivity assumption +on the comparison probability x. -/ +theorem negMulLog_tangent {x y : ℝ} (hx : 0 ≤ x) (hy : 0 < y) : + Real.negMulLog x ≤ -x * Real.log y + y-x := by + have h := mul_le_mul_of_nonneg_left + (Real.negMulLog_le_one_sub_self (div_nonneg hx hy.le)) hy.le + have he : Real.negMulLog x = -x * Real.log y + y * Real.negMulLog (x/y) := by + calc + Real.negMulLog x = Real.negMulLog (y * (x/y)) := by congr 1; field_simp + _ = (x/y) * Real.negMulLog y + y * Real.negMulLog (x/y) := Real.negMulLog_mul _ _ + _ = _ := by unfold Real.negMulLog; field_simp + rw [he] + have hdiv : y * (x/y) = x := by field_simp + nlinarith + +/-- Gibbs' inequality on a finite set, with the exact support condition +needed on boundary faces. -/ +theorem entropy_le_crossEntropy {ι : Type*} [Fintype ι] {p q : ι → ℝ} + (hp : p ∈ probabilitySimplex ι) (hq : q ∈ probabilitySimplex ι) + (hsupp : ∀ i, p i = 0 → q i = 0) : + entropy q ≤ -∑ i, q i * Real.log (p i) := by + have hterm : ∀ i, Real.negMulLog (q i) ≤ + -(q i * Real.log (p i)) + p i-q i := by + intro i + by_cases hi : p i = 0 + · simp [hi, hsupp i hi] + · simpa only [neg_mul] using negMulLog_tangent (hq.1 i) + (lt_of_le_of_ne (hp.1 i) (Ne.symm hi)) + have hh := Finset.sum_le_sum (s := Finset.univ) fun i _ => hterm i + simpa only [Finset.sum_sub_distrib, Finset.sum_add_distrib, + Finset.sum_neg_distrib, hp.2, hq.2, add_sub_cancel_right, entropy] using hh + +/-- Derivative of entropy along a line supported on the positive probabilities. -/ +theorem entropy_line_hasDerivAt {ι : Type*} [Fintype ι] (p v : ι → ℝ) + (hsupp : ∀ i, p i = 0 → v i = 0) : + HasDerivAt (fun t : ℝ => entropy (fun i => p i+t*v i)) + (-∑ i, v i * Real.log (p i) - ∑ i, v i) 0 := by + have hd : ∀ i, HasDerivAt (fun t : ℝ => Real.negMulLog (p i+t*v i)) + ((-Real.log (p i)-1)*v i) 0 := by + intro i + by_cases hi : p i = 0 + · simpa only [hi, hsupp i hi, mul_zero, add_zero, Real.negMulLog_zero] using + (hasDerivAt_const (0 : ℝ) (0 : ℝ)) + · have hp : p i+(0 : ℝ)*v i ≠ 0 := by simpa using hi + simpa only [zero_mul, add_zero, one_mul, Function.comp_def, id_eq] using + (Real.hasDerivAt_negMulLog hp).comp 0 + (((hasDerivAt_id (0 : ℝ)).mul_const (v i)).const_add (p i)) + have he : (∑ i, (-Real.log (p i)-1)*v i) = + -∑ i, v i*Real.log (p i) - ∑ i, v i := by + simp_rw [sub_mul, one_mul, neg_mul, mul_comm (Real.log (p _))] + rw [Finset.sum_sub_distrib, Finset.sum_neg_distrib] + rw [← he] + simpa only [entropy, Finset.sum_apply] using (HasDerivAt.fun_sum (u := Finset.univ) (fun i _ => hd i)) + +omit [Fintype V] [DecidableEq V] in +/-- The log probabilities of the actual optimizer annihilate every feasible +mass/mean-preserving linear variation. No exponential representation assumed. -/ +theorem matching_optimizer_log_annihilates (G : LooplessGraph V E) {y : E → ℝ} + {p : G.Matching → ℝ} (hp : p ∈ G.feasibleLaws y) + (hopt : entropy p = maxMatchingEntropy G y) (v : G.Matching → ℝ) + (hvsum : ∑ M, v M = 0) (hvmean : G.mean v = 0) + (hsupp : ∀ M, p M = 0 → v M = 0) : + ∑ M, v M * Real.log (p M) = 0 := by + have hev : ∀ᶠ t : ℝ in 𝓝 0, ∀ M, 0 ≤ p M+t*v M := by + apply Filter.eventually_all.mpr + intro M + by_cases hM : p M = 0 + · exact Filter.Eventually.of_forall (fun t => by simp [hM, hsupp M hM]) + · have hpos : 0 < p M := lt_of_le_of_ne (hp.1.1 M) (Ne.symm hM) + have hc : Continuous (fun t : ℝ => p M+t*v M) := by fun_prop + have hh : {t : ℝ | 0 < p M+t*v M} ∈ 𝓝 0 := + (isOpen_lt continuous_const hc).mem_nhds (by simpa using hpos) + exact Filter.Eventually.mono hh (fun t ht => ht.le) + have hlocal : IsLocalMax (fun t : ℝ => entropy (fun M => p M+t*v M)) 0 := by + filter_upwards [hev] with t ht + have hmean : G.mean (fun M => p M+t*v M) = y := by + change G.meanLinear (p+t • v) = y + rw [map_add, map_smul] + change G.mean p + t • G.mean v = y + rw [hp.2, hvmean, smul_zero, add_zero] + have hsum : ∑ M, (p M+t*v M) = 1 := by + rw [Finset.sum_add_distrib, ← Finset.mul_sum, hp.1.2, hvsum, mul_zero, add_zero] + have hle := entropy_le_maxMatchingEntropy (G := G) ⟨⟨ht, hsum⟩, hmean⟩ + simpa only [zero_mul, add_zero, ← hopt] using hle + have hh := hlocal.deriv_eq_zero + rw [(entropy_line_hasDerivAt p v hsupp).deriv, hvsum] at hh + linarith + + +/-- A finite nonnegative vector permits small positive motion in any direction +which does not point outwards at its zero coordinates. -/ +theorem exists_pos_nonneg_perturb {ι : Type*} [Fintype ι] (p v : ι → ℝ) + (hp : ∀ i, 0 ≤ p i) (hz : ∀ i, p i = 0 → 0 ≤ v i) : + ∃ t : ℝ, 0 < t ∧ ∀ i, 0 ≤ p i+t*v i := by + have hev : ∀ᶠ t : ℝ in 𝓝 0, ∀ i, p i ≠ 0 → 0 ≤ p i+t*v i := by + apply Filter.eventually_all.mpr + intro i + by_cases hi : p i = 0 + · exact Filter.Eventually.of_forall (fun _ h => (h hi).elim) + · have hc : Continuous (fun t : ℝ => p i+t*v i) := by fun_prop + have hh : {t : ℝ | 0 < p i+t*v i} ∈ 𝓝 0 := + (isOpen_lt continuous_const hc).mem_nhds + (by simpa using lt_of_le_of_ne (hp i) (Ne.symm hi)) + exact Filter.Eventually.mono hh (fun t ht _ => ht.le) + have he' := (hev.filter_mono nhdsWithin_le_nhds).and + (self_mem_nhdsWithin : ∀ᶠ t : ℝ in 𝓝[>] 0, t ∈ Set.Ioi 0) + obtain ⟨t, ht, htp⟩ := he'.exists + refine ⟨t, htp, fun i => ?_⟩ + by_cases hi : p i = 0 + · rw [hi, zero_add] + exact mul_nonneg htp.le (hz i hi) + · exact ht i hi + +omit [Fintype V] [DecidableEq V] in +/-- The support of an optimizing law is a face: every law at a mean generated +by that support is itself supported there. This avoids assuming a face +representation of the marginal polytope in the entropy-optimization step. -/ +theorem matching_optimizer_face_support (G : LooplessGraph V E) {y : E → ℝ} + {p : G.Matching → ℝ} (hp : p ∈ G.feasibleLaws y) + (hopt : entropy p = maxMatchingEntropy G y) + {q r : G.Matching → ℝ} (hq : q ∈ probabilitySimplex G.Matching) + (hr : r ∈ probabilitySimplex G.Matching) (hmean : G.mean q = G.mean r) + (hrsupport : ∀ M, p M = 0 → r M = 0) : + ∀ M, p M = 0 → q M = 0 := by + obtain ⟨t, htp, ht⟩ := exists_pos_nonneg_perturb p (q-r) hp.1.1 + (fun M hM => by simpa [hrsupport M hM] using hq.1 M) + have hsum : ∑ M, (p M+t*(q-r) M) = 1 := by + simp only [Pi.sub_apply, Finset.sum_add_distrib, ← Finset.mul_sum, + Finset.sum_sub_distrib, hp.1.2, hq.2, hr.2] + ring + have hmean' : G.mean (fun M => p M+t*(q-r) M) = y := by + change G.meanLinear (p+t • (q-r)) = y + rw [map_add, map_smul, map_sub] + change G.mean p + t • (G.mean q-G.mean r) = y + rw [hp.2, hmean, sub_self, smul_zero, add_zero] + intro M hM + by_contra hqM + have hqMp : 0 < q M := lt_of_le_of_ne (hq.1 M) (Ne.symm hqM) + have hpM := matching_optimizer_support G hp ⟨⟨ht, hsum⟩, hmean'⟩ hopt + (M := M) (by simpa [hM, hrsupport M hM] using mul_pos htp hqMp) + simp [hM] at hpM + +end MatchingEntropy + +end + +end OAI diff --git a/lean/OAI/Combinatorics/PerfectMatching/ParameterBounds.lean b/lean/OAI/Combinatorics/PerfectMatching/ParameterBounds.lean new file mode 100644 index 0000000000000000000000000000000000000000..32e9b764112f9e09aaefa271f8a13875d6759fba --- /dev/null +++ b/lean/OAI/Combinatorics/PerfectMatching/ParameterBounds.lean @@ -0,0 +1,98 @@ +import OAI.Combinatorics.PerfectMatching.SizeBounds + +namespace OAI + +section + +namespace BinaryMatching.Algorithm +open Finset + +def tau (G : Input) : ℕ := G.n+B G+1 + +def Q (G : Input) : ℕ := D₀ G*2^(K G.n) + +lemma tau_pos (G : Input) : 0 Real.exp_pos (a i)) univ_nonempty + +lemma expLaw_simplex [Nonempty I] (a : I → ℝ) : expLaw a∈probabilitySimplex I := by + refine ⟨fun i => (div_pos (Real.exp_pos _) (expSum_pos a)).le,?_⟩ + simp only [expLaw,←sum_div] + exact div_self (expSum_pos a).ne' + +lemma log_expLaw [Nonempty I] (a : I → ℝ) (i : I) : + Real.log (expLaw a i)=a i-Real.log (expSum a) := by + rw [expLaw,Real.log_div (Real.exp_ne_zero _) (expSum_pos a).ne',Real.log_exp] + +lemma expLaw_cross [Nonempty I] (a : I → ℝ) {p : I → ℝ} + (hp : p∈probabilitySimplex I) : + -(∑ i,p i*Real.log (expLaw a i))=Real.log (expSum a)-∑ i,p i*a i := by + simp only [log_expLaw,mul_sub,sum_sub_distrib,←sum_mul,hp.2,one_mul] + ring + +lemma expSum_variational_le [Nonempty I] (a : I → ℝ) {p : I → ℝ} + (hp : p∈probabilitySimplex I) : entropy p+∑ i,p i*a i≤Real.log (expSum a) := by + have hh := entropy_le_crossEntropy (expLaw_simplex a) hp + (fun i hi => False.elim ((div_pos (Real.exp_pos _) (expSum_pos a)).ne' hi)) + rw [expLaw_cross a hp] at hh + linarith + +lemma expSum_variational_eq [Nonempty I] (a : I → ℝ) : + entropy (expLaw a)+∑ i,expLaw a i*a i=Real.log (expSum a) := by + rw [entropy_eq,expLaw_cross a (expLaw_simplex a)] + ring + +namespace LooplessGraph +variable {V : Type u_1} {E : Type u_2} [Fintype V] [Fintype E] [DecidableEq V] [DecidableEq E] + +def score (G : LooplessGraph V E) (β : E → ℝ) (M : G.Matching) : ℝ := + ∑ e∈M.val,β e + +def weightedZ (G : LooplessGraph V E) (β : E → ℝ) : ℝ := + expSum (fun M => Real.log 2*G.score β M) + +omit [Fintype V] [DecidableEq V] in +lemma score_indicator (G : LooplessGraph V E) (β : E → ℝ) (M : G.Matching) : + G.score β M=∑ e, β e*G.indicator M e := by + simp [score,indicator] + +omit [Fintype V] [DecidableEq V] in +lemma mean_score (G : LooplessGraph V E) (β : E → ℝ) (p : G.Matching → ℝ) : + (∑ M,p M*G.score β M)=∑ e,β e*G.mean p e := by + simp only [score_indicator,mul_sum] + rw [sum_comm] + apply sum_congr rfl; intro e _ + simp only [mean,mul_sum] + apply sum_congr rfl; intro M _; ring + +omit [Fintype V] [DecidableEq V] in +lemma complement_entropy_le_mass (G : LooplessGraph V E) {x : E → ℝ} + (hx : x∈G.polytope) : entropy (fun e => 1-x e)≤∑ e,x e := by + apply sum_le_sum; intro e _ + have hh := Real.negMulLog_le_one_sub_self (sub_nonneg.mpr (G.coordinate_mem_Icc hx e).2) + simpa only [sub_sub_cancel] using hh + +lemma entropy_binary_scale (G : LooplessGraph V E) (hPM : Nonempty G.Matching) + {r : ℕ} (hV : Fintype.card V=2*r) {x : E → ℝ} (hx : x∈G.polytope) : + entropy x/Real.log 2-4*(Fintype.card V:ℝ)≤ maxMatchingEntropy G x/Real.log 2 ∧ + maxMatchingEntropy G x/Real.log 2≤entropy x/Real.log 2+(Fintype.card V:ℝ) := by + have hl := separable_lower G hPM x hx + have hu := maxMatchingEntropy_le_binary G x hx + have hc := G.complement_entropy_le_mass hx + rw [G.marginal_sum hV hx] at hc + have hv : (Fintype.card V:ℝ)=2*(r:ℝ) := by exact_mod_cast hV + have hlog := BinaryMatching.Algorithm.half_le_log_two + have hr : (0:ℝ)≤r := by positivity + have hprod := mul_le_mul_of_nonneg_right hlog hr + dsimp only [separableLower,binaryEntropy] at hl hu + constructor + · apply (le_div_iff₀ BinaryMatching.Algorithm.log_two_pos).2 + rw [sub_mul,div_mul_cancel₀ _ BinaryMatching.Algorithm.log_two_pos.ne',hv] + nlinarith + · apply (div_le_iff₀ BinaryMatching.Algorithm.log_two_pos).2 + rw [add_mul,div_mul_cancel₀ _ BinaryMatching.Algorithm.log_two_pos.ne',hv] + nlinarith + +omit [Fintype V] [DecidableEq V] in +lemma weighted_variational_le (G : LooplessGraph V E) [Nonempty G.Matching] + (β : E → ℝ) {x : E → ℝ} (hx : x∈G.polytope) : + maxMatchingEntropy G x/Real.log 2+∑ e,β e*x e≤Real.log (G.weightedZ β)/Real.log 2 := by + obtain ⟨p,hp,hh⟩ := maxMatchingEntropy_attained G hx + have h := expSum_variational_le (fun M => Real.log 2*G.score β M) hp.1 + have he : (∑ M,p M*(Real.log 2*G.score β M))=Real.log 2*(∑ e,β e*x e) := by + rw [mul_sum] + conv_lhs => arg 2; ext M; rw [mul_left_comm] + rw [←mul_sum,G.mean_score,hp.2,mul_sum] + rw [he,hh] at h + apply (le_div_iff₀ BinaryMatching.Algorithm.log_two_pos).2 + calc + _ = maxMatchingEntropy G x+Real.log 2*(∑ e,β e*x e) := by + rw [add_mul,div_mul_cancel₀ _ BinaryMatching.Algorithm.log_two_pos.ne']; ring + _ ≤ _ := h + +omit [Fintype V] [DecidableEq V] in +lemma weighted_variational_attained (G : LooplessGraph V E) [Nonempty G.Matching] + (β : E → ℝ) : ∃ x∈G.polytope, + Real.log (G.weightedZ β)/Real.log 2≤ maxMatchingEntropy G x/Real.log 2+∑ e,β e*x e := by + let p := expLaw (fun M => Real.log 2*G.score β M) + have hp := expLaw_simplex (fun M => Real.log 2*G.score β M) + have hpx : p∈G.feasibleLaws (G.mean p) := ⟨hp,rfl⟩ + refine ⟨G.mean p,(G.mem_polytope_iff _).mpr ⟨p,hpx⟩,?_⟩ + have he := expSum_variational_eq (fun M => Real.log 2*G.score β M) + have he' : (∑ M,p M*(Real.log 2*G.score β M))=Real.log 2*(∑ e,β e*G.mean p e) := by + calc + _ = Real.log 2*(∑ M,p M*G.score β M) := by + rw [mul_sum]; apply sum_congr rfl; intro M _; ring + _ = _ := by rw [G.mean_score] + change entropy p+(∑ M,p M*(Real.log 2*G.score β M))=Real.log (G.weightedZ β) at he + rw [he'] at he + apply (div_le_iff₀ BinaryMatching.Algorithm.log_two_pos).2 + have hH := entropy_le_maxMatchingEntropy G hpx + calc + _ ≤ maxMatchingEntropy G (G.mean p)+Real.log 2*(∑ e,β e*G.mean p e) := by linarith + _ = _ := by rw [add_mul,div_mul_cancel₀ _ BinaryMatching.Algorithm.log_two_pos.ne']; ring +end LooplessGraph +end MatchingEntropy +end +end + +end OAI diff --git a/lean/OAI/Combinatorics/PerfectMatching/Polyhedron.lean b/lean/OAI/Combinatorics/PerfectMatching/Polyhedron.lean new file mode 100644 index 0000000000000000000000000000000000000000..6e397e0feb258b9747d4c302ea55dc684949c40b --- /dev/null +++ b/lean/OAI/Combinatorics/PerfectMatching/Polyhedron.lean @@ -0,0 +1,122 @@ +import Mathlib + +namespace OAI + +/-! +Finite polyhedra, local perturbations, and quotient dimension bounds. +-/ + +noncomputable section + +open scoped BigOperators Topology +open Filter + +namespace MatchingEntropy + +section PolyhedralPrelude +variable {I J : Type*} [Fintype I] [Fintype J] + +def finitePolyhedron (L : I → (J → ℝ) →ₗ[ℝ] ℝ) (b : I → ℝ) : Set (J → ℝ) := + {x | ∀ i, L i x ≤ b i} + +/-- Finite slack, with every active equation preserved, permits both signs. -/ +theorem finitePolyhedron_eventually_line (L : I → (J → ℝ) →ₗ[ℝ] ℝ) (b : I → ℝ) + {x : J → ℝ} (hx : x ∈ finitePolyhedron L b) (u : J → ℝ) + (hu : ∀ i, L i x = b i → L i u = 0) : + ∀ᶠ t : ℝ in 𝓝 0, x+t • u ∈ finitePolyhedron L b := by + apply Filter.eventually_all.mpr + intro i + by_cases hi : L i x=b i + · apply Filter.Eventually.of_forall + intro t + rw [map_add, map_smul, hu i hi, smul_zero, add_zero, hi] + · have hlt : L i x < b i := lt_of_le_of_ne (hx i) hi + have hc : Continuous (fun t : ℝ => L i (x+t • u)) := + (L i).continuous_of_finiteDimensional.comp (by fun_prop) + have hh : ∀ᶠ t : ℝ in 𝓝 0, L i (x+t • u) < b i := + (isOpen_lt hc continuous_const).mem_nhds (by simpa using hlt : L i (x+(0:ℝ) • u) < b i) + exact hh.mono fun t ht => le_of_lt ht + +/-- Radial expansion about x preserves every active inequality for arbitrary +nearby feasible points. Inactive inequalities are handled by finite slack. -/ +theorem finitePolyhedron_eventually_expand (L : I → (J → ℝ) →ₗ[ℝ] ℝ) (b : I → ℝ) + {x : J → ℝ} (hx : x ∈ finitePolyhedron L b) {t : ℝ} (ht : 0 < t) : + ∀ᶠ y in 𝓝[finitePolyhedron L b] x, x+t⁻¹ • (y-x) ∈ finitePolyhedron L b := by + apply Filter.eventually_all.mpr + intro i + by_cases hi : L i x=b i + · filter_upwards [eventually_mem_nhdsWithin] with y hy + rw [map_add, map_smul, map_sub, hi] + change b i+t⁻¹ * (L i y-b i) ≤ b i + have hh := mul_nonpos_of_nonneg_of_nonpos (inv_nonneg.mpr ht.le) (sub_nonpos.mpr (hy i)) + linarith + · have hlt : L i x < b i := lt_of_le_of_ne (hx i) hi + have hc : Continuous (fun y : J → ℝ => L i (x+t⁻¹ • (y-x))) := + (L i).continuous_of_finiteDimensional.comp (by fun_prop) + have hh : ∀ᶠ y : J → ℝ in 𝓝 x, L i (x+t⁻¹ • (y-x)) < b i := + (isOpen_lt hc continuous_const).mem_nhds (by simpa using hlt : L i (x+t⁻¹ • (x-x)) < b i) + exact (hh.filter_mono nhdsWithin_le_nhds).mono fun y hy => le_of_lt hy + +omit [Fintype J] in +theorem extreme_point_direction_zero (P : Set (J → ℝ)) {x : J → ℝ} + (hx : x ∈ Set.extremePoints ℝ P) (u : J → ℝ) + (hu : ∀ᶠ t : ℝ in 𝓝 0, x+t • u ∈ P) : u=0 := by + have hu' : ∀ᶠ t : ℝ in 𝓝 0, x+(-t) • u ∈ P := by + have hc : Tendsto (fun t : ℝ => -t) (𝓝 0) (𝓝 0) := by simpa using (continuous_neg.tendsto (0:ℝ)) + exact hc.eventually hu + -- choose a strictly positive point using the right-hand punctured neighborhood + have hh : ∀ᶠ t : ℝ in 𝓝[>] 0, (x+t • u ∈ P ∧ x+(-t) • u ∈ P) ∧ 0.1 + ext j + have hj := congrFun he j + change x j+a*u j=x j at hj + change u j=0 + exact (mul_eq_zero.mp (by linarith : a*u j=0)).resolve_left (ne_of_gt ha0) + + +section LinearHelper +open Module +variable {A B C : Type*} [AddCommGroup A] [AddCommGroup B] [AddCommGroup C] + [Module ℝ A] [Module ℝ B] [Module ℝ C] + [FiniteDimensional ℝ A] [FiniteDimensional ℝ B] [FiniteDimensional ℝ C] + +theorem quotient_finrank_le_of_ker_le (U : Submodule ℝ A) (f : A →ₗ[ℝ] B) + (h : f.ker ≤ U) : finrank ℝ (A ⧸ U) ≤ finrank ℝ B := by + have h1 := U.finrank_quotient_add_finrank + have h2 := f.finrank_range_add_finrank_ker + have h3 := Submodule.finrank_mono h + have h4 : finrank ℝ f.range ≤ finrank ℝ B := Submodule.finrank_le _ + omega + +theorem quotient_finrank_le_pair (U : Submodule ℝ A) (W : Submodule ℝ B) (Z : Submodule ℝ C) + (f : A →ₗ[ℝ] B) (g : A →ₗ[ℝ] C) + (h : ∀ u, f u ∈ W → g u ∈ Z → u ∈ U) : + finrank ℝ (A ⧸ U) ≤ finrank ℝ (B ⧸ W)+finrank ℝ (C ⧸ Z) := by + let F := (W.mkQ.comp f).prod (Z.mkQ.comp g) + have hk : F.ker ≤ U := by + intro u hu + have hh : (W.mkQ (f u), Z.mkQ (g u))=0 := hu + have hW : f u ∈ W := by + have hq := congrArg Prod.fst hh + simpa using hq + have hZ : g u ∈ Z := by + have hq := congrArg Prod.snd hh + simpa using hq + exact h u hW hZ + simpa using quotient_finrank_le_of_ker_le U F hk + +end LinearHelper +end PolyhedralPrelude + +end MatchingEntropy + +end + +end OAI diff --git a/lean/OAI/Combinatorics/PerfectMatching/Polytope.lean b/lean/OAI/Combinatorics/PerfectMatching/Polytope.lean new file mode 100644 index 0000000000000000000000000000000000000000..6486d47661ee4e349467d2fc6e74fa0d08f6e449 --- /dev/null +++ b/lean/OAI/Combinatorics/PerfectMatching/Polytope.lean @@ -0,0 +1,395 @@ +import OAI.Combinatorics.PerfectMatching.Contraction +import OAI.Combinatorics.PerfectMatching.Polyhedron + +namespace OAI + +/-! +Tutte's criterion and Edmonds' perfect matching polytope theorem for multigraphs. +-/ + +noncomputable section + +open scoped BigOperators Topology +open Filter + +namespace MatchingEntropy + +variable {V E : Type*} [Fintype V] [Fintype E] [DecidableEq V] [DecidableEq E] + +namespace LooplessGraph + +/-- The simple support graph forgets only parallel-edge identities. -/ +def supportSimple (G : LooplessGraph V E) (x : E → ℝ) : SimpleGraph V where + Adj v w := ∃ e, 0 < x e ∧ ((G.left e=v ∧ G.right e=w) ∨ (G.left e=w ∧ G.right e=v)) + symm := ⟨by intro v w; rintro ⟨e,hx,h⟩; exact ⟨e,hx,h.symm⟩⟩ + loopless := ⟨by + intro v + rintro ⟨e,_,(⟨hl,hr⟩ | ⟨hl,hr⟩)⟩ <;> exact G.loopless e (hl.trans hr.symm)⟩ + +omit [Fintype V] [Fintype E] [DecidableEq V] [DecidableEq E] in + theorem supportSimple_edge (G : LooplessGraph V E) {x : E → ℝ} {e : E} (he : 0 < x e) : + (G.supportSimple x).Adj (G.left e) (G.right e) := ⟨e,he,Or.inl ⟨rfl,rfl⟩⟩ + +theorem sum_pred_le_one {C : Type*} [Fintype C] (P : C → Prop) [DecidablePred P] + (huniq : ∀ a b, P a → P b → a=b) : (∑ c, if P c then (1 : ℝ) else 0) ≤ 1 := by + by_cases h : ∃ a, P a + · obtain ⟨a,ha⟩ := h + rw [Finset.sum_eq_single a] + · simp [ha] + · intro b _ hb + rw [ite_eq_right] + intro hPb + exact hb (huniq b a hPb ha) + · simp + · simp only [not_exists] at h + simp [h] + +omit [Fintype V] [DecidableEq E] in +/-- The weighted cut-counting argument in Tutte's criterion. -/ +theorem odd_family_bound (G : LooplessGraph V E) {x : E → ℝ} + (hx : x ∈ G.constraintPolytope) {C : Type*} [Fintype C] [DecidableEq C] + (U : Finset V) (T : C → Finset V) + (hodd : ∀ c, Odd (T c).card) + (hdisj : ∀ c v, v ∈ T c → v ∉ U) + (huniq : ∀ a b v, v ∈ T a → v ∈ T b → a=b) + (hclosed : ∀ e, 0 < x e → G.left e ∉ U → G.right e ∉ U → + ∀ c, G.left e ∈ T c ↔ G.right e ∈ T c) : + Fintype.card C ≤ U.card := by + have hcuts : (Fintype.card C : ℝ) ≤ ∑ c, G.cutMass x (T c) := by + calc + _ = ∑ c : C, (1 : ℝ) := by simp + _ ≤ _ := Finset.sum_le_sum fun c _ => hx.2.2 (T c) (hodd c) + have hedges : ∀ e, (∑ c, if G.Crosses (T c) e then x e else 0) ≤ + (if G.left e ∈ U then x e else 0) + (if G.right e ∈ U then x e else 0) := by + intro e + by_cases hz : x e=0 + · simp [hz] + have hp : 0 < x e := lt_of_le_of_ne (hx.1 e) (Ne.symm hz) + by_cases hl : G.left e ∈ U <;> by_cases hr : G.right e ∈ U + · have hzero : ∀ c, ¬G.Crosses (T c) e := by + intro c hc + rcases hc with h | h + · exact hdisj c _ h.1 hl + · exact hdisj c _ h.2 hr + simp [hzero, hl, hr, hx.1 e] + · have heq : ∀ c, G.Crosses (T c) e ↔ G.right e ∈ T c := by + intro c + have hn : G.left e ∉ T c := fun h => hdisj c _ h hl + simp [Crosses, hn] + simp_rw [heq] + have hcount := sum_pred_le_one (fun c => G.right e ∈ T c) + (fun a b => huniq a b (G.right e)) + have heq' : (∑ c, if G.right e ∈ T c then x e else 0) = + (∑ c, if G.right e ∈ T c then (1 : ℝ) else 0) * x e := by + rw [Finset.sum_mul] + apply Finset.sum_congr rfl + intro c _ + split <;> simp + rw [heq'] + simpa [hl, hr] using mul_le_mul_of_nonneg_right hcount (hx.1 e) + · have heq : ∀ c, G.Crosses (T c) e ↔ G.left e ∈ T c := by + intro c + have hn : G.right e ∉ T c := fun h => hdisj c _ h hr + simp [Crosses, hn] + simp_rw [heq] + have hcount := sum_pred_le_one (fun c => G.left e ∈ T c) + (fun a b => huniq a b (G.left e)) + have heq' : (∑ c, if G.left e ∈ T c then x e else 0) = + (∑ c, if G.left e ∈ T c then (1 : ℝ) else 0) * x e := by + rw [Finset.sum_mul] + apply Finset.sum_congr rfl + intro c _ + split <;> simp + rw [heq'] + simpa [hl, hr] using mul_le_mul_of_nonneg_right hcount (hx.1 e) + · have hzero : ∀ c, ¬G.Crosses (T c) e := by + intro c hc + have hiff := hclosed e hp hl hr c + unfold Crosses at hc + tauto + simp [hzero, hl, hr] + have hdegree : ∑ v ∈ U, G.degree x v = (U.card : ℝ) := by + simp_rw [hx.2.1] + simp + have hsum : (∑ e : E, ((if G.left e ∈ U then x e else 0) + + (if G.right e ∈ U then x e else 0))) = ∑ v ∈ U, G.degree x v := by + simp only [degree] + rw [Finset.sum_comm] + apply Finset.sum_congr rfl + intro e _ + have hf : ∀ v, (if G.Incident v e then x e else 0) = + (if G.left e = v then x e else 0) + (if G.right e = v then x e else 0) := by + intro v + by_cases hl : G.left e=v <;> by_cases hr : G.right e=v + · exact (G.loopless e (hl.trans hr.symm)).elim + all_goals simp [Incident, hl, hr] + simp_rw [hf] + rw [Finset.sum_add_distrib] + simp + have hbound := (Finset.sum_le_sum (fun e (_ : e ∈ Finset.univ) => hedges e)) + rw [hsum, hdegree] at hbound + have hcutEq : (∑ c, G.cutMass x (T c)) = ∑ e, ∑ c, if G.Crosses (T c) e then x e else 0 := by + simp only [cutMass, cut, Finset.sum_filter] + exact Finset.sum_comm + exact_mod_cast hcuts.trans (hcutEq ▸ hbound) + + +omit [DecidableEq E] in +theorem supportSimple_has_perfectMatching (G : LooplessGraph V E) {x : E → ℝ} + (hx : x ∈ G.constraintPolytope) : + ∃ M : (G.supportSimple x).Subgraph, M.IsPerfectMatching := by + classical + apply SimpleGraph.tutte.mpr + intro U + let H := (⊤ : (G.supportSimple x).Subgraph).deleteVerts U + let C := H.coe.oddComponents + let : Fintype C := Fintype.ofFinite C + let T : C → Finset V := fun c => (Subtype.val '' c.val.supp).toFinset + have hnot : ∀ v : H.verts, v.val ∉ U := by + intro v + have hv := v.property + simpa [H] using hv + have hT : ∀ c : C, ∀ v : V, v ∈ T c ↔ ∃ w : H.verts, w ∈ c.val.supp ∧ w.val=v := by + intro c v + simp [T] + have hodd : ∀ c : C, Odd (T c).card := by + intro c + have hc := c.property + change Odd c.val.supp.ncard at hc + change Odd ((Subtype.val '' c.val.supp).toFinset.card) + rw [← Set.ncard_eq_toFinset_card', Set.ncard_image_of_injective _ Subtype.val_injective] + exact hc + have hdisj : ∀ c v, v ∈ T c → v ∉ U.toFinset := by + intro c v hv + obtain ⟨w,_,rfl⟩ := (hT c v).mp hv + simpa using hnot w + have huniq : ∀ a b v, v ∈ T a → v ∈ T b → a=b := by + intro a b v ha hb + obtain ⟨wa,hwa,rfl⟩ := (hT a v).mp ha + obtain ⟨wb,hwb,he⟩ := (hT b wa.val).mp hb + have hw : wb=wa := Subtype.ext he + subst wb + exact Subtype.ext (SimpleGraph.ConnectedComponent.eq_of_common_vertex hwa hwb) + have hclosed : ∀ e, 0 SimpleGraph.ConnectedComponent.mem_coe_supp_of_adj h hr' ha, + fun h => SimpleGraph.ConnectedComponent.mem_coe_supp_of_adj h hl' ha.symm⟩ + have hb := G.odd_family_bound hx U.toFinset T hodd hdisj huniq hclosed + change ¬ U.ncard < H.coe.oddComponents.ncard + have hcard : Fintype.card C = H.coe.oddComponents.ncard := by + simp [C, ← Nat.card_eq_fintype_card, Nat.card_coe_set_eq] + rw [hcard] at hb + exact not_lt_of_ge (by simpa only [← Set.ncard_eq_toFinset_card'] using hb) + + +theorem exists_supported_matching (G : LooplessGraph V E) {x : E → ℝ} + (hx : x ∈ G.constraintPolytope) : + ∃ M : G.Matching, ∀ e ∈ M.val, 0 < x e := by + classical + obtain ⟨M,hM⟩ := G.supportSimple_has_perfectMatching hx + have he : ∀ q ∈ M.edgeSet, ∃ e, 0 + intro hq + obtain ⟨e,he,hor⟩ := (SimpleGraph.Subgraph.mem_edgeSet.mp hq).adj_sub + refine ⟨e,he,Sym2.eq_iff.mpr hor⟩ + let f : M.edgeSet → E := fun q => (he q.val q.property).choose + have hf : ∀ q, 0 (he q.val q.property).choose_spec + let F : Finset E := Finset.univ.image f + have hF : G.IsPerfectMatching F := by + intro v + obtain ⟨w,hw,hu⟩ := SimpleGraph.Subgraph.isPerfectMatching_iff.mp hM v + let q : M.edgeSet := ⟨s(v,w),SimpleGraph.Subgraph.mem_edgeSet.mpr hw⟩ + refine ⟨f q,⟨Finset.mem_image.mpr ⟨q,Finset.mem_univ _,rfl⟩,?_⟩,?_⟩ + · rcases Sym2.eq_iff.mp (hf q).2 with h | h + · exact Or.inl h.1 + · exact Or.inr h.2 + · intro e he' + obtain ⟨q',_,rfl⟩ := Finset.mem_image.mp he'.1 + have hq : q'=q := by + apply Subtype.ext + rcases he'.2 with hl | hr + · have hval : q'.val=s(v,G.right (f q')) := by rw [← (hf q').2, hl] + have hAdj : M.Adj v (G.right (f q')) := + SimpleGraph.Subgraph.mem_edgeSet.mp (hval ▸ q'.property) + rw [hval, hu _ hAdj] + · have hval : q'.val=s(v,G.left (f q')) := by + rw [← (hf q').2, hr, Sym2.eq_swap] + have hAdj : M.Adj v (G.left (f q')) := + SimpleGraph.Subgraph.mem_edgeSet.mp (hval ▸ q'.property) + rw [hval, hu _ hAdj] + exact congrArg f hq + refine ⟨⟨F,hF⟩,?_⟩ + intro e he' + obtain ⟨q,_,rfl⟩ := Finset.mem_image.mp he' + exact (hf q).1 + + +omit [Fintype V] [Fintype E] [DecidableEq E] in +@[simp] theorem crosses_singleton (G : LooplessGraph V E) (v : V) (e : E) : + G.Crosses {v} e ↔ G.Incident v e := by + have hh := G.loopless e + simp only [Crosses, Finset.mem_singleton, Incident] + have hn : ¬ (G.left e=v ∧ G.right e=v) := fun h => hh (h.1.trans h.2.symm) + tauto + +omit [Fintype V] [DecidableEq E] in +@[simp] theorem cutMass_singleton (G : LooplessGraph V E) (x : E → ℝ) (v : V) : + G.cutMass x {v} = G.degree x v := by + simp [cutMass,cut,Finset.sum_filter,degree] + +omit [DecidableEq E] in +/-- Local two-sided perturbations for the degree and odd-cut constraint system. -/ +theorem constraint_eventually_line (G : LooplessGraph V E) {x : E → ℝ} + (hx : x ∈ G.constraintPolytope) (u : E → ℝ) + (hzero : ∀ e, x e=0 → u e=0) (hdeg : ∀ v, G.degree u v=0) + (hcut : ∀ S, Odd S.card → G.cutMass x S=1 → G.cutMass u S=0) : + ∀ᶠ t : ℝ in 𝓝 0, x+t • u ∈ G.constraintPolytope := by + have hn : ∀ᶠ t : ℝ in 𝓝 0, ∀ e, 0≤(x+t • u) e := by + apply Filter.eventually_all.mpr + intro e + by_cases he : x e=0 + · exact Filter.Eventually.of_forall (by intro t; simp [he,hzero e he]) + · have hp : 0 (x+t • u) e) := by fun_prop + have hh : ∀ᶠ t : ℝ in 𝓝 0, 0<(x+t • u) e := (isOpen_lt continuous_const hc).mem_nhds + (by simpa using hp : 0<(x+(0:ℝ) • u) e) + exact hh.mono fun t ht => ht.le + have hodd : ∀ᶠ t : ℝ in 𝓝 0, ∀ S : Finset V, Odd S.card → 1≤G.cutMass (x+t • u) S := by + apply Filter.eventually_all.mpr + intro S + by_cases hS : Odd S.card + · by_cases ht : G.cutMass x S=1 + · exact Filter.Eventually.of_forall (by + intro t _ + have he := G.cutMass_linear x u 1 t S + simp only [one_smul, one_mul, hcut S hS ht, mul_zero, add_zero, ht] at he + exact he.ge) + · have hp : 1 G.cutMass (x+t • u) S) := + (G.continuous_cutMass S).comp (by fun_prop) + have hh : ∀ᶠ t : ℝ in 𝓝 0, 1 ht.le + · exact Filter.Eventually.of_forall fun _ h => (hS h).elim + filter_upwards [hn,hodd] with t hn hodd + refine ⟨hn,?_,hodd⟩ + intro v + have he := G.degree_linear x u 1 t v + simpa only [one_smul, one_mul, hdeg, mul_zero, add_zero, hx.2.1] using he + +omit [Fintype V] [DecidableEq E] in + theorem degree_sub (G : LooplessGraph V E) (x y : E → ℝ) (v : V) : + G.degree (x-y) v = G.degree x v-G.degree y v := by + have h := G.degree_linear x y 1 (-1) v + simpa [sub_eq_add_neg] using h + +omit [Fintype V] [DecidableEq E] in + theorem cutMass_sub (G : LooplessGraph V E) (x y : E → ℝ) (S : Finset V) : + G.cutMass (x-y) S = G.cutMass x S-G.cutMass y S := by + have h := G.cutMass_linear x y 1 (-1) S + simpa [sub_eq_add_neg] using h + +omit [DecidableEq E] in +/-- Without a nontrivial tight odd cut, only degrees constrain a supported direction. -/ +theorem trivial_tight_cut_preserved (G : LooplessGraph V E) {x : E → ℝ} + (heven : Even (Fintype.card V)) + (hnt : ¬∃ S : Finset V, Odd S.card ∧ 3≤S.card ∧ 3≤Sᶜ.card ∧ G.cutMass x S=1) + (u : E → ℝ) (hdeg : ∀ v, G.degree u v=0) : + ∀ S, Odd S.card → G.cutMass x S=1 → G.cutMass u S=0 := by + intro S hS ht + have hc := odd_compl_of_even heven hS + have hsmall : S.card=1 ∨ Sᶜ.card=1 := by + have hn : ¬ (3≤S.card ∧ 3≤Sᶜ.card) := fun h => hnt ⟨S,hS,h.1,h.2,ht⟩ + rcases hS with ⟨k,hk⟩ + rcases hc with ⟨l,hl⟩ + omega + rcases hsmall with hs | hs + · obtain ⟨v,rfl⟩ := Finset.card_eq_one.mp hs + simpa using hdeg v + · obtain ⟨v,hv⟩ := Finset.card_eq_one.mp hs + have hh : G.cutMass u Sᶜ=0 := by rw [hv,cutMass_singleton,hdeg] + simpa only [cutMass,cut_compl] using hh + + theorem extreme_no_tight_integral (G : LooplessGraph V E) {x : E → ℝ} + (heven : Even (Fintype.card V)) (hx : x ∈ Set.extremePoints ℝ G.constraintPolytope) + (hnt : ¬∃ S : Finset V, Odd S.card ∧ 3≤S.card ∧ 3≤Sᶜ.card ∧ G.cutMass x S=1) : + ∃ M : G.Matching, G.indicator M=x := by + have hxQ := (mem_extremePoints.mp hx).1 + obtain ⟨M,hM⟩ := G.exists_supported_matching hxQ + have hd : ∀ v, G.degree (G.indicator M-x) v=0 := by + intro v + rw [degree_sub,degree_indicator,hxQ.2.1,sub_self] + have hz : ∀ e, x e=0 → (G.indicator M-x) e=0 := by + intro e he + have hn : e ∉ M.val := fun h => (hM e h).ne' he + simp [indicator,hn,he] + have hu := G.constraint_eventually_line hxQ (G.indicator M-x) hz hd + (G.trivial_tight_cut_preserved heven hnt _ hd) + have he := extreme_point_direction_zero G.constraintPolytope hx _ hu + exact ⟨M,sub_eq_zero.mp he⟩ + + +/-- Induction over even orders, using only proved cut coupling and Mathlib Tutte. -/ +theorem constraint_subset_polytope_aux (n : ℕ) : + ∀ {W F : Type*} [Fintype W] [Fintype F] [DecidableEq W] [DecidableEq F] + (G : LooplessGraph W F), Fintype.card W=n → Even n → + G.constraintPolytope ⊆ G.polytope := by + induction n using Nat.strong_induction_on with + | h n ih => + intro W F _ _ _ _ G hcard heven + have heven' : Even (Fintype.card W) := hcard ▸ heven + have hex : Set.extremePoints ℝ G.constraintPolytope ⊆ G.polytope := by + intro x hx + have hxQ := (mem_extremePoints.mp hx).1 + by_cases hcut : ∃ S : Finset W, Odd S.card ∧ 3≤S.card ∧ 3≤Sᶜ.card ∧ G.cutMass x S=1 + · obtain ⟨S,hS,hlo,hhi,ht⟩ := hcut + have hc := odd_compl_of_even heven' hS + have hlt1 : Fintype.card (Option {v // v ∈ S}) < n := by + simp only [Fintype.card_option,Fintype.card_coe] + have hco := Finset.card_compl S + omega + have hlt2 : Fintype.card (Option {v // v ∈ Sᶜ}) < n := by + simp only [Fintype.card_option,Fintype.card_coe] + have hco := Finset.card_compl S + have hle := Finset.card_le_univ S + omega + have hv1 : Even (Fintype.card (Option {v // v ∈ S})) := by + simpa only [Fintype.card_option,Fintype.card_coe] using hS.add_odd odd_one + have hv2 : Even (Fintype.card (Option {v // v ∈ Sᶜ})) := by + simpa only [Fintype.card_option,Fintype.card_coe] using hc.add_odd odd_one + have hx1 := ih _ hlt1 (G.onSide S) rfl hv1 (G.restriction_mem_constraints hxQ S hS ht) + have htc : G.cutMass x Sᶜ=1 := by simpa only [cutMass,cut_compl] using ht + have hx2 := ih _ hlt2 (G.onSide Sᶜ) rfl hv2 (G.restriction_mem_constraints hxQ Sᶜ hc htc) + obtain ⟨p,hp,hpx⟩ := ((G.onSide S).mem_polytope_iff _).mp hx1 + obtain ⟨q,hq,hqx⟩ := ((G.onSide Sᶜ).mem_polytope_iff _).mp hx2 + exact (G.mem_polytope_iff x).mpr (G.couple_laws S x hp hq (congrFun hpx) (congrFun hqx)) + · obtain ⟨M,rfl⟩ := G.extreme_no_tight_integral heven' hx hcut + exact subset_convexHull ℝ _ (Set.mem_range_self M) + rw [← closure_convexHull_extremePoints G.isCompact_constraintPolytope G.convex_constraintPolytope] + exact closure_minimal (convexHull_min hex (convex_convexHull ℝ _)) G.compact_polytope.isClosed + +/-- Edmonds' perfect matching polytope equality, with parallel edges retained. -/ +theorem polytope_eq_constraints (G : LooplessGraph V E) (heven : Even (Fintype.card V)) : + G.polytope = G.constraintPolytope := by + exact Set.Subset.antisymm G.polytope_subset_constraintPolytope + (constraint_subset_polytope_aux (Fintype.card V) G rfl heven) + +end LooplessGraph + +end MatchingEntropy + +end + +end OAI diff --git a/lean/OAI/Combinatorics/PerfectMatching/SecondVariation.lean b/lean/OAI/Combinatorics/PerfectMatching/SecondVariation.lean new file mode 100644 index 0000000000000000000000000000000000000000..c4cd8419c299938ef856c8eb5853270817626754 --- /dev/null +++ b/lean/OAI/Combinatorics/PerfectMatching/SecondVariation.lean @@ -0,0 +1,113 @@ +import OAI.Combinatorics.PerfectMatching.Calculus + +namespace OAI + +/-! +The second-variation inequality at a maximum of the actual entropy defect. +-/ + +noncomputable section + +open scoped BigOperators Topology +open Filter + +namespace MatchingEntropy + +variable {V E : Type*} [Fintype V] [Fintype E] [DecidableEq V] [DecidableEq E] + +def entropyDefect (G : LooplessGraph V E) (m : ℝ) (y : E → ℝ) : ℝ := + entropyBarrier m (entropy y)-maxMatchingEntropy G y + +theorem score_law_eventually_simplex {ι : Type*} [Fintype ι] {p : ι → ℝ} + (hp : p ∈ probabilitySimplex ι) (a : ι → ℝ) (hcenter : ∑ i, p i*a i = 0) : + ∀ᶠ t : ℝ in 𝓝 0, (fun i => p i+t*(p i*a i)) ∈ probabilitySimplex ι := by + have hh : ∀ᶠ t : ℝ in 𝓝 0, ∀ i, 0 < 1+t*a i := by + apply Filter.eventually_all.mpr + intro i + have hc : Continuous (fun t : ℝ => 1+t*a i) := by fun_prop + exact (isOpen_lt continuous_const hc).mem_nhds (by norm_num) + filter_upwards [hh] with t ht + constructor + · intro i + have h := mul_nonneg (hp.1 i) (ht i).le + nlinarith + · rw [Finset.sum_add_distrib, ← Finset.mul_sum, hp.2, hcenter] + ring + +omit [Fintype V] [DecidableEq V] in +theorem mean_score_support (G : LooplessGraph V E) {p : G.Matching → ℝ} + (hp : p ∈ probabilitySimplex G.Matching) (a : G.Matching → ℝ) : + ∀ e, G.mean p e = 0 → G.mean (fun M => p M*a M) e = 0 := by + intro e he + have hterms : ∀ M, p M*G.indicator M e = 0 := by + have hh := (Finset.sum_eq_zero_iff_of_nonneg + (fun M (_ : M ∈ Finset.univ) => mul_nonneg (hp.1 M) (G.indicator_nonneg M e))).mp he + exact fun M => hh M (Finset.mem_univ M) + apply Finset.sum_eq_zero + intro M _ + calc + _ = a M*(p M*G.indicator M e) := by ring + _ = 0 := by rw [hterms, mul_zero] + +omit [Fintype V] [DecidableEq V] in +/-- A maximum of the *actual* entropy defect satisfies the second-variation +inequality. The comparison uses optimizing probability laws rather than a replacement for H. -/ +theorem matching_defect_second_variation (G : LooplessGraph V E) {x : E → ℝ} + {p : G.Matching → ℝ} (hp : p ∈ G.feasibleLaws x) + (hopt : entropy p = maxMatchingEntropy G x) {m : ℝ} (hm : m ≠ 0) + (hmax : ∀ y ∈ G.polytope, entropyDefect G m y ≤ entropyDefect G m x) + (u : E → ℝ) (c : ℝ) (hcenter : ∑ M, p M*linearScore G u c M = 0) : + (8*Real.exp (-entropy x/m)-1)* + (∑ e, (G.mean (fun M => p M*linearScore G u c M) e)^2/x e) + + (8*Real.exp (-entropy x/m)/m)* + (entropyLineD x (G.mean (fun M => p M*linearScore G u c M)) 0)^2 + + (∑ M, p M*(linearScore G u c M)^2) ≤ 0 := by + let a := linearScore G u c + let v := G.mean (fun M => p M*a M) + let c₀ := ∑ M, p M*Real.log (p M) + let c₁ := ∑ M, (p M*a M)*Real.log (p M) + have hsupp : ∀ e, x e = 0 → v e = 0 := by + rw [← hp.2] + exact mean_score_support G hp.1 a + apply entropy_second_variation x v hsupp hp.1 a hcenter hm c₀ c₁ + filter_upwards [score_law_eventually_simplex hp.1 a hcenter] with t ht + let r := fun M => p M+t*(p M*a M) + have hr : r ∈ probabilitySimplex G.Matching := ht + have hrmean : G.mean r = fun e => x e+t*v e := by + change G.meanLinear (p+t • (fun M => p M*a M)) = _ + rw [map_add, map_smul] + change G.mean p+t • v = _ + rw [hp.2] + rfl + have hdual := matching_entropy_dual_bound G hp hopt hr + (fun M hM => by dsimp [r]; simp [hM]) u c t + have hscore : (∑ M, r M*a M) = t*(∑ M, p M*(a M)^2) := by + dsimp [r] + simp_rw [add_mul, mul_assoc t, Finset.sum_add_distrib, ← Finset.mul_sum] + rw [hcenter, zero_add] + congr 1 + apply Finset.sum_congr rfl + intro M _ + ring + have hlog : (∑ M, r M*Real.log (p M)) = c₀+t*c₁ := by + dsimp [r, c₀, c₁] + simp_rw [add_mul, mul_assoc t, Finset.sum_add_distrib, ← Finset.mul_sum] + change maxMatchingEntropy G (G.mean r) ≤ + Real.log (partition p a t) - (∑ M, r M*Real.log (p M)) - t*(∑ M, r M*a M) at hdual + rw [hlog, hscore] at hdual + have hmaxr := hmax (G.mean r) (G.mean_mem_polytope hr) + dsimp only [entropyDefect] at hmaxr + have hzero := partition_zero hp.1 a + simp only [zero_mul, zero_pow (by omega : 2 ≠ 0), add_zero, hzero, + Real.log_one, sub_zero] + rw [← hopt] at hmaxr + rw [entropy_eq p] at hmaxr + rw [← hrmean] + dsimp only [c₀] at * + nlinarith + +end MatchingEntropy + +end + +end OAI diff --git a/lean/OAI/Combinatorics/PerfectMatching/Separable.lean b/lean/OAI/Combinatorics/PerfectMatching/Separable.lean new file mode 100644 index 0000000000000000000000000000000000000000..b1343f62c03e9e494a54733688e2f805a79a6c0f --- /dev/null +++ b/lean/OAI/Combinatorics/PerfectMatching/Separable.lean @@ -0,0 +1,178 @@ +import OAI.Combinatorics.PerfectMatching.Main + +namespace OAI + +universe u_1 u_2 + +section + +noncomputable section +open scoped BigOperators Topology +open Filter +namespace MatchingEntropy + +variable {V : Type u_1} {E : Type u_2} [Fintype V] [Fintype E] [DecidableEq V] [DecidableEq E] + +def binaryEntropy (x : E → ℝ) : ℝ := entropy x + entropy (fun e => 1 - x e) + +def separableLower (x : E → ℝ) : ℝ := entropy x - 3 * entropy (fun e => 1 - x e) + +def structuralBase (k : ℕ) : ℝ := + if k = 1 then 1 else (k : ℝ) * (1 - 1 / (k : ℝ)) ^ (3 * (k - 1)) + +omit [Fintype V] [DecidableEq V] [DecidableEq E] in +theorem continuous_separableLower : Continuous (separableLower (E := E)) := by + exact continuous_entropy.sub (continuous_const.mul (continuous_entropy.comp (by fun_prop))) + +def separableLineD (x v : E → ℝ) (t : ℝ) : ℝ := + entropyLineD x v t - 3 * entropyLineD (fun e => 1-x e) (fun e => -v e) t + +omit [Fintype V] [DecidableEq V] [DecidableEq E] in +theorem separable_line_eventually_hasDerivAt (x v : E → ℝ) + (hzero : ∀ e, x e = 0 → v e = 0) (hone : ∀ e, x e = 1 → v e = 0) : + ∀ᶠ t : ℝ in 𝓝 0, + HasDerivAt (fun t => separableLower (fun e => x e+t*v e)) + (separableLineD x v t) t := by + have hbar : ∀ e, 1-x e=0 → -v e=0 := by + intro e he + rw [hone e (by linarith), neg_zero] + filter_upwards [entropy_line_eventually_hasDerivAt x v hzero, + entropy_line_eventually_hasDerivAt (fun e => 1-x e) (fun e => -v e) hbar] + with t ht hb + have he : (fun t => separableLower (fun e => x e+t*v e)) = + (fun t => entropy (fun e => x e+t*v e) - + 3 * entropy (fun e => (1-x e)+t*(-v e))) := by + funext t + unfold separableLower + congr 2 + congr 1 + funext e + ring + rw [he] + exact ht.sub (hb.const_mul 3) + +omit [Fintype V] [DecidableEq V] [DecidableEq E] in +theorem separableLineD_hasDerivAt (x v : E → ℝ) + (hzero : ∀ e, x e = 0 → v e = 0) (hone : ∀ e, x e = 1 → v e = 0) : + HasDerivAt (separableLineD x v) + (-(∑ e, (v e)^2/x e) + 3*(∑ e, (v e)^2/(1-x e))) 0 := by + have hbar : ∀ e, 1-x e=0 → -v e=0 := by + intro e he + rw [hone e (by linarith), neg_zero] + have hd := (entropyLineD_hasDerivAt x v hzero).sub + ((entropyLineD_hasDerivAt (fun e => 1-x e) (fun e => -v e) hbar).const_mul 3) + exact hd.congr_deriv (by simp only [neg_sq]; ring) + +omit [Fintype V] [DecidableEq V] [DecidableEq E] in +theorem separable_second_variation {A : Type*} [Fintype A] + (x v : E → ℝ) (hzero : ∀ e, x e=0 → v e=0) (hone : ∀ e, x e=1 → v e=0) + {p : A → ℝ} (hp : p ∈ probabilitySimplex A) (a : A → ℝ) + (hcenter : ∑ i, p i*a i=0) (c₀ c₁ : ℝ) + (hlocal : IsLocalMax (fun t => separableLower (fun e => x e+t*v e) + + c₀+t*c₁+t^2*(∑ i, p i*(a i)^2)-Real.log (partition p a t)) 0) : + -(∑ e, (v e)^2/x e) + 3*(∑ e, (v e)^2/(1-x e)) + + (∑ i, p i*(a i)^2) ≤ 0 := by + have hf := separable_line_eventually_hasDerivAt x v hzero hone + have hg : ∀ᶠ t : ℝ in 𝓝 0, HasDerivAt (fun t => Real.log (partition p a t)) + (partition (fun i => p i*a i) a t / partition p a t) t := + Filter.Eventually.of_forall (logPartition_hasDerivAt hp a) + have hd := second_deriv_quadratic_adjustment (c₀ := c₀) (c₁ := c₁) + (v := ∑ i, p i*(a i)^2) hf hg (separableLineD_hasDerivAt x v hzero hone) + (logPartition_second hp a) + have hc : ContinuousAt (fun t => separableLower (fun e => x e+t*v e) + + c₀+t*c₁+t^2*(∑ i, p i*(a i)^2)-Real.log (partition p a t)) 0 := by + apply ContinuousAt.sub + · apply ContinuousAt.add + · apply ContinuousAt.add + · exact hf.self_of_nhds.continuousAt.add_const c₀ + · fun_prop + · fun_prop + · exact hg.self_of_nhds.continuousAt + have hh := second_deriv_nonpos_of_local_max hlocal hc + rw [hd.deriv, hcenter] at hh + nlinarith + +omit [Fintype V] [DecidableEq V] in +theorem mean_score_one (G : LooplessGraph V E) {p : G.Matching → ℝ} + (hp : p ∈ probabilitySimplex G.Matching) (a : G.Matching → ℝ) + (hcenter : ∑ M, p M*a M=0) : + ∀ e, G.mean p e=1 → G.mean (fun M => p M*a M) e=0 := by + intro e he + have hz : ∑ M, p M*(1-G.indicator M e)=0 := by + simp only [mul_sub, mul_one, Finset.sum_sub_distrib, hp.2] + change 1-G.mean p e=0 + rw [he, sub_self] + have hterms : ∀ M, p M*(1-G.indicator M e)=0 := by + exact fun M => (Finset.sum_eq_zero_iff_of_nonneg + (fun M (_ : M ∈ Finset.univ) => + mul_nonneg (hp.1 M) (sub_nonneg.mpr (G.indicator_le_one M e)))).mp hz M (by simp) + calc + _ = ∑ M, p M*a M := by + apply Finset.sum_congr rfl + intro M _ + have hh := hterms M + have hh' : a M*(p M*(1-G.indicator M e))=0 := by rw [hh, mul_zero] + nlinarith [hh'] + _ = 0 := hcenter + +omit [Fintype V] [DecidableEq V] in + +theorem matching_separable_second_variation (G : LooplessGraph V E) {x : E → ℝ} + {p : G.Matching → ℝ} (hp : p ∈ G.feasibleLaws x) + (hopt : entropy p=maxMatchingEntropy G x) + (hmax : ∀ y ∈ G.polytope, separableLower y-maxMatchingEntropy G y ≤ + separableLower x-maxMatchingEntropy G x) + (u : E → ℝ) (c : ℝ) (hcenter : ∑ M, p M*linearScore G u c M=0) : + -(∑ e, (G.mean (fun M => p M*linearScore G u c M) e)^2/x e) + + 3*(∑ e, (G.mean (fun M => p M*linearScore G u c M) e)^2/(1-x e)) + + (∑ M, p M*(linearScore G u c M)^2) ≤ 0 := by + let a := linearScore G u c + let v := G.mean (fun M => p M*a M) + let c₀ := ∑ M, p M*Real.log (p M) + let c₁ := ∑ M, (p M*a M)*Real.log (p M) + have hzero : ∀ e, x e=0 → v e=0 := by + rw [← hp.2] + exact mean_score_support G hp.1 a + have hone : ∀ e, x e=1 → v e=0 := by + rw [← hp.2] + exact mean_score_one G hp.1 a hcenter + apply separable_second_variation x v hzero hone hp.1 a hcenter c₀ c₁ + filter_upwards [score_law_eventually_simplex hp.1 a hcenter] with t ht + let r := fun M => p M+t*(p M*a M) + have hr : r ∈ probabilitySimplex G.Matching := ht + have hrmean : G.mean r=fun e => x e+t*v e := by + change G.meanLinear (p+t • (fun M => p M*a M)) = _ + rw [map_add, map_smul] + change G.mean p+t • v = _ + rw [hp.2] + rfl + have hdual := matching_entropy_dual_bound G hp hopt hr + (fun M hM => by dsimp [r]; simp [hM]) u c t + have hscore : (∑ M, r M*a M)=t*(∑ M, p M*(a M)^2) := by + dsimp [r] + simp_rw [add_mul, mul_assoc t, Finset.sum_add_distrib, ← Finset.mul_sum] + rw [hcenter, zero_add] + congr 1 + apply Finset.sum_congr rfl + intro M _ + ring + have hlog : (∑ M, r M*Real.log (p M))=c₀+t*c₁ := by + dsimp [r, c₀, c₁] + simp_rw [add_mul, mul_assoc t, Finset.sum_add_distrib, ← Finset.mul_sum] + change maxMatchingEntropy G (G.mean r) ≤ + Real.log (partition p a t) - (∑ M, r M*Real.log (p M)) - t*(∑ M, r M*a M) at hdual + rw [hlog, hscore] at hdual + have hmaxr := hmax (G.mean r) (G.mean_mem_polytope hr) + have hpart := partition_zero hp.1 a + simp only [zero_mul, zero_pow (by omega : 2 ≠ 0), add_zero, hpart, + Real.log_one, sub_zero] + rw [← hopt, entropy_eq p] at hmaxr + rw [← hrmean] + dsimp only [c₀] at * + nlinarith + +end MatchingEntropy +end +end + +end OAI diff --git a/lean/OAI/Combinatorics/PerfectMatching/SeparableCount.lean b/lean/OAI/Combinatorics/PerfectMatching/SeparableCount.lean new file mode 100644 index 0000000000000000000000000000000000000000..df47b01a209d7ede8dc94fbcaa5faa1f931b990c --- /dev/null +++ b/lean/OAI/Combinatorics/PerfectMatching/SeparableCount.lean @@ -0,0 +1,184 @@ +import OAI.Combinatorics.PerfectMatching.EntropyUpper + +namespace OAI + +universe u_1 u_2 + +noncomputable section +open scoped BigOperators +namespace MatchingEntropy +variable {V : Type u_1} {E : Type u_2} [Fintype V] [Fintype E] [DecidableEq V] [DecidableEq E] + +theorem separable_entropy_main (G : LooplessGraph V E) + (_hn : 2 ≤ Fintype.card V) (hPM : Nonempty G.Matching) + (x : E → ℝ) (hx : x ∈ G.polytope) : + separableLower x ≤ maxMatchingEntropy G x ∧ + maxMatchingEntropy G x ≤ binaryEntropy x := + ⟨separable_lower G hPM x hx, maxMatchingEntropy_le_binary G x hx⟩ + +omit [Fintype V] [Fintype E] [DecidableEq V] in + +theorem selected_uniform_mean (G : LooplessGraph V E) {k : ℕ} (hk : 1 ≤ k) + (M : Fin k → G.Matching) + (hdisjoint : ∀ i j, i ≠ j → Disjoint (M i).val (M j).val) : + ∃ x ∈ G.polytope, ∀ e, x e=0 ∨ x e=1/(k:ℝ) := by + classical + have hkR : (0:ℝ) (one_div_pos.mpr hkR).le) hsum + (fun i _ => subset_convexHull ℝ _ (Set.mem_range_self (M i))) + · intro e + dsimp only [x] + simp only [Finset.sum_apply,Pi.smul_apply,smul_eq_mul] + by_cases he : ∃ i, e ∈ (M i).val + · obtain ⟨i,hi⟩ := he + right + rw [Finset.sum_eq_single i] + · simp [LooplessGraph.indicator,hi] + · intro j _ hji + have hj : e ∉ (M j).val := fun h => + Finset.disjoint_left.mp (hdisjoint j i hji) h hi + simp [LooplessGraph.indicator,hj] + · simp + · left + apply Finset.sum_eq_zero + intro i _ + have hi : e ∉ (M i).val := fun h => he ⟨i,h⟩ + simp [LooplessGraph.indicator,hi] + +theorem separableLower_uniform (G : LooplessGraph V E) {r k : ℕ} + (hV : Fintype.card V=2*r) (hk : 2 ≤ k) {x : E → ℝ} (hx : x ∈ G.polytope) + (huniform : ∀ e, x e=0 ∨ x e=1/(k:ℝ)) : + separableLower x = (r:ℝ)*(Real.log (k:ℝ)+ + (3*((k-1:ℕ):ℝ))*Real.log (1-1/(k:ℝ))) := by + have hkR : (0:ℝ) 1/(k:ℝ)) ∈ G.polytope := by + have hkR : (0:ℝ) (one_div_pos.mpr hkR).le,?_,?_⟩ + · intro v + unfold LooplessGraph.degree + rw [← Finset.sum_filter] + simp only [Finset.sum_const,nsmul_eq_mul,hregular] + field_simp + · intro S hS + unfold LooplessGraph.cutMass + simp only [Finset.sum_const,nsmul_eq_mul] + have hc : (k:ℝ) ≤ (G.cut S).card := by exact_mod_cast hodd S hS + calc + 1 = (k:ℝ)*(1/(k:ℝ)) := by field_simp + _ ≤ _ := mul_le_mul_of_nonneg_right hc (one_div_pos.mpr hkR).le + +theorem regular_count_main (G : LooplessGraph V E) (r k : ℕ) + (_hr : 0 Or.inr rfl) + +end MatchingEntropy +end + +end OAI diff --git a/lean/OAI/Combinatorics/PerfectMatching/SeparableCovariance.lean b/lean/OAI/Combinatorics/PerfectMatching/SeparableCovariance.lean new file mode 100644 index 0000000000000000000000000000000000000000..3a584e3d76cf2aab7a1decdc17062904f0b6ddd1 --- /dev/null +++ b/lean/OAI/Combinatorics/PerfectMatching/SeparableCovariance.lean @@ -0,0 +1,180 @@ +import OAI.Combinatorics.PerfectMatching.WeightedSpectrum + +namespace OAI + +universe u_1 u_2 + +section + +noncomputable section +open scoped BigOperators Topology +open Matrix Filter +namespace MatchingEntropy +variable {V : Type u_1} {E : Type u_2} [Fintype V] [Fintype E] [DecidableEq V] [DecidableEq E] + +theorem separableDefect_attains_max (G : LooplessGraph V E) + (heven : Even (Fintype.card V)) (hPM : Nonempty G.Matching) : + ∃ x ∈ G.polytope, ∀ y ∈ G.polytope, + separableLower y-maxMatchingEntropy G y ≤ separableLower x-maxMatchingEntropy G x := by + have hs : UpperSemicontinuousOn (fun y => separableLower y-maxMatchingEntropy G y) + G.polytope := by + simpa only [sub_eq_add_neg, Pi.neg_apply] using + continuous_separableLower.continuousOn.upperSemicontinuousOn.add + (maxMatchingEntropy_lowerSemicontinuousOn G heven).neg + have hn : G.polytope.Nonempty := by + obtain ⟨M⟩ := hPM + exact ⟨G.indicator M,subset_convexHull ℝ _ (Set.mem_range_self M)⟩ + exact UpperSemicontinuousOn.exists_isMaxOn hn G.compact_polytope hs + +theorem matching_covariance_rank_face (G : LooplessGraph V E) {x : E → ℝ} + (heven : Even (Fintype.card V)) {p : G.Matching → ℝ} + (hp : p ∈ G.feasibleLaws x) (hopt : entropy p=maxMatchingEntropy G x) : + Fintype.card {e // 0 < x e} ≤ G.faceCodimension x+ + (covariance p (matchingNormalized G x)).rank := by + let W := weightedDirectionSpace p (matchingNormalized G x) + let L : G.faceSpace x →ₗ[ℝ] W := + ((normalizeLinear x).comp (G.faceSpace x).subtype).codRestrict W + (fun u => normalized_face_mem G heven hp hopt u.property) + have hi : Function.Injective L := by + intro u v huv + apply Subtype.ext + funext e + have hh := congrFun (congrArg Subtype.val huv) e + change u.val e/Real.sqrt (x e.val)=v.val e/Real.sqrt (x e.val) at hh + exact (div_left_inj' (ne_of_gt (Real.sqrt_pos.mpr e.property))).mp hh + have hdim := LinearMap.finrank_le_finrank_of_injective hi + have hq := (G.faceSpace x).finrank_quotient_add_finrank + rw [covariance_rank hp.1.1] + have hq' : G.faceCodimension x+Module.finrank ℝ (G.faceSpace x)=Fintype.card {e // 0 < x e} := by + simpa only [LooplessGraph.faceCodimension,Module.finrank_pi,Module.finrank_self,Finset.sum_const, + Finset.card_univ,smul_eq_mul,mul_one] using hq + change Module.finrank ℝ (G.faceSpace x) ≤ Module.finrank ℝ W at hdim + dsimp only [W] at hdim + omega + +theorem faceCodimension_strict (G : LooplessGraph V E) {x : E → ℝ} + (heven : Even (Fintype.card V)) (hn : 0 < Fintype.card V) (hx : x ∈ G.polytope) : + G.faceCodimension x < 2*Fintype.card V := by + by_cases hn4 : 4 ≤ Fintype.card V + · have hb := LooplessGraph.faceCodimension_strong_aux (Fintype.card V) G rfl heven hn4 x + (G.polytope_subset_constraintPolytope hx) + omega + · have hnt : ¬∃ S : Finset V, Odd S.card ∧ 3≤S.card ∧ 3≤Sᶜ.card ∧ G.cutMass x S=1 := by + rintro ⟨S,_,hlo,hhi,_⟩ + have hh := Finset.card_compl_add_card S + omega + have hb := G.faceCodimension_no_tight heven hnt + omega + +omit [Fintype V] [DecidableEq V] in + +theorem matching_separable_covariance (G : LooplessGraph V E) {x : E → ℝ} + {p : G.Matching → ℝ} (hp : p ∈ G.feasibleLaws x) + (hopt : entropy p=maxMatchingEntropy G x) + (hmax : ∀ y ∈ G.polytope, separableLower y-maxMatchingEntropy G y ≤ + separableLower x-maxMatchingEntropy G x) + (u : {e // 0 < x e} → ℝ) : + u ⬝ᵥ (covariance p (matchingNormalized G x) *ᵥ u) ≤ + ∑ e, (1-3*x e.val/(1-x e.val))*((covariance p (matchingNormalized G x) *ᵥ u) e)^2 := by + let w := matchingScoreWeights x u + let c := ∑ e, w e*x e + let a := linearScore G w c + let v := G.mean (fun M => p M*a M) + have hx : x ∈ G.polytope := (G.mem_polytope_iff x).mpr ⟨p,hp⟩ + have hcenter : ∑ M, p M*a M=0 := by + dsimp only [a,c] + rw [linearScore_expectation,hp.2,hp.1.2,mul_one,sub_self] + have hh := matching_separable_second_variation G hp hopt hmax w c hcenter + have hzero : ∀ e, ¬0 < x e → v e=0 := by + intro e he + have he0 : x e=0 := le_antisymm (le_of_not_gt he) (G.coordinate_mem_Icc hx e).1 + exact mean_score_support G hp.1 a e (by rw [hp.2,he0]) + have hnorm : (∑ e, (v e)^2/x e) = + ∑ e, ((covariance p (matchingNormalized G x) *ᵥ u) e)^2 := by + rw [sum_positive_support x _ (fun e he => by rw [hzero e he]; simp)] + apply Finset.sum_congr rfl + intro e _ + rw [matchingNormalized_mulVec G hp,div_pow,Real.sq_sqrt e.property.le] + have hbar : (∑ e, (v e)^2/(1-x e)) = + ∑ e, x e.val/(1-x e.val)*((covariance p (matchingNormalized G x) *ᵥ u) e)^2 := by + rw [sum_positive_support x _ (fun e he => by rw [hzero e he]; simp)] + apply Finset.sum_congr rfl + intro e _ + rw [matchingNormalized_mulVec G hp,div_pow,Real.sq_sqrt e.property.le] + change (v e.val)^2/(1-x e.val)=x e.val/(1-x e.val)*((v e.val)^2/x e.val) + field_simp [ne_of_gt e.property] + have hquad : (∑ M, p M*(a M)^2)=u ⬝ᵥ (covariance p (matchingNormalized G x) *ᵥ u) := by + rw [covariance_quadratic hp.1.1] + apply Finset.sum_congr rfl + intro M _ + rw [← matchingNormalized_score G x u M] + change -(∑ e, (v e)^2/x e)+3*(∑ e, (v e)^2/(1-x e))+(∑ M,p M*(a M)^2) ≤ 0 at hh + rw [hnorm,hbar,hquad] at hh + have heq : (∑ e, (1-3*x e.val/(1-x e.val))*((covariance p (matchingNormalized G x) *ᵥ u) e)^2) = + (∑ e, ((covariance p (matchingNormalized G x) *ᵥ u) e)^2)- + 3*(∑ e, x e.val/(1-x e.val)*((covariance p (matchingNormalized G x) *ᵥ u) e)^2) := by + simp_rw [sub_mul,one_mul,Finset.sum_sub_distrib,Finset.mul_sum] + congr 1 + apply Finset.sum_congr rfl + intro e _ + ring + rw [heq] + linarith + +omit [Fintype V] [DecidableEq V] in +theorem matching_covariance_diagonal (G : LooplessGraph V E) {x : E → ℝ} + {p : G.Matching → ℝ} (hp : p ∈ G.feasibleLaws x) (e : {e // 0 G.indicator M e.val) + (by intro M e; simp only [LooplessGraph.indicator]; split <;> norm_num) + (fun e => x e.val) (fun e => congrFun hp.2 e.val) (fun e => e.property) e + convert hh using 1 + apply Finset.sum_congr rfl + intro M _ + change p M*matchingNormalized G x M e*matchingNormalized G x M e= + p M*(matchingNormalized G x M e)^2 + ring + +theorem separable_max_has_forced (G : LooplessGraph V E) {x : E → ℝ} + (heven : Even (Fintype.card V)) (hn : 0 < Fintype.card V) (hx : x ∈ G.polytope) + (hmax : ∀ y ∈ G.polytope, separableLower y-maxMatchingEntropy G y ≤ + separableLower x-maxMatchingEntropy G x) : ∃ e, x e=1 := by + by_contra hforced + push Not at hforced + obtain ⟨p,hp,hopt⟩ := maxMatchingEntropy_attained G hx + have hsecond := covariance_weighted_rank (covariance_posSemidef p (matchingNormalized G x)) + (fun e => 1-3*x e.val/(1-x e.val)) (matching_separable_covariance G hp hopt hmax) + have htrace : (∑ e : {e // 0 + le_antisymm (le_of_not_gt he) (G.coordinate_mem_Icc hx e).1)).symm + rw [hs,hv] + simp only [Finset.sum_const,Finset.card_univ,nsmul_eq_mul,mul_one,Nat.cast_mul,Nat.cast_ofNat] + ring + rw [htrace] at hsecond + have hrank := matching_covariance_rank_face G heven hp hopt + have hstrict := faceCodimension_strict G heven hn hx + have hrankR : (Fintype.card {e // 0 + intro V E _ _ _ _ G hcard heven y hy + by_cases hn : n=0 + · have : IsEmpty V := Fintype.card_eq_zero_iff.mp (hcard.trans hn) + have : IsEmpty E := ⟨fun e => isEmptyElim (G.left e)⟩ + simpa [separableLower,entropy] using maxMatchingEntropy_nonneg G hy + · have heven' : Even (Fintype.card V) := hcard ▸ heven + have hPM : Nonempty G.Matching := by + obtain ⟨p,hp⟩ := (G.mem_polytope_iff y).mp hy + by_contra h + have : IsEmpty G.Matching := not_nonempty_iff.mp h + simpa using hp.1.2 + obtain ⟨x,hx,hmax⟩ := separableDefect_attains_max G heven' hPM + obtain ⟨e₀,he₀⟩ := separable_max_has_forced G heven' (by omega) hx hmax + have hc := G.remaining_vertex_card e₀ + have hlt : Fintype.card {v // G.RemainingVertex e₀ v} norm_num + · simp + +theorem probabilitySimplex_le_one {Index : Type*} [Fintype Index] {weights : Index → ℝ} + (mem : weights ∈ probabilitySimplex Index) (index : Index) : weights index ≤ 1 := by + rw [← mem.2] + exact Finset.single_le_sum (fun other _ ↦ mem.1 other) (Finset.mem_univ index) + +theorem isCompact_probabilitySimplex (Index : Type*) [Fintype Index] : + IsCompact (probabilitySimplex Index) := by + rw [probabilitySimplex_eq_range] + exact isCompact_range + (Convexity.StdSimplex.isEmbedding_toFun_comp_weights ℝ Index).continuous + +end MatchingEntropy + +end + +end OAI diff --git a/lean/OAI/Combinatorics/PerfectMatching/SizeBounds.lean b/lean/OAI/Combinatorics/PerfectMatching/SizeBounds.lean new file mode 100644 index 0000000000000000000000000000000000000000..a759c39df61ac3c83e4d62416911bbe957c45f7c --- /dev/null +++ b/lean/OAI/Combinatorics/PerfectMatching/SizeBounds.lean @@ -0,0 +1,120 @@ +import OAI.Combinatorics.PerfectMatching.ElementaryCount + +namespace OAI + +section + +namespace BinaryMatching.Algorithm +noncomputable section +open Finset + +def inputLength (G : Input) : ℕ := (encodeInput G).length + +lemma encodeNat_length (n : ℕ) : (encodeNat n).length=2*n.bits.length+1 := by + simp [encodeNat]; omega + +lemma encodeRecord_length (r : Record) : + (encodeRecord r).length=2*(r.left.bits.length+r.right.bits.length+r.multiplicity.bits.length)+3 := by + simp only [encodeRecord,List.length_append,encodeNat_length] + omega + +lemma records_length_le_input (G : Input) : G.records.length≤ inputLength G := by + have hh (rs : List Record) : rs.length≤(rs.flatMap encodeRecord).length := by + induction rs with + | nil => simp + | cons r rs ih => + simp only [List.length_cons,List.flatMap_cons,List.length_append,encodeRecord_length] + omega + have := hh G.records + simp only [inputLength,encodeInput,List.length_append] + omega + +lemma record_bits_le_input (G : Input) (r : Record) (hr : r∈G.records) : + r.multiplicity.bits.length≤ inputLength G := by + have hh : (encodeRecord r).length≤(G.records.flatMap encodeRecord).length := by + rw [List.length_flatMap] + exact List.le_sum_of_mem (List.mem_map.mpr ⟨r,hr,rfl⟩) + rw [encodeRecord_length] at hh + unfold inputLength encodeInput + simp only [List.length_append] + omega + +lemma log2_le_bits (m : ℕ) : Nat.log2 m≤ m.bits.length := by + by_cases hm : m=0 + · subst m; simp + · rw [Nat.size_eq_bits_len] + exact (Nat.lt_size.mpr (Nat.log2_self_le hm)).le + +lemma B_le_input (G : Input) : B G≤ inputLength G := by + apply foldl_max_le _ _ _ (Nat.zero_le _) + intro b hb + obtain ⟨r,hr,rfl⟩ := List.mem_map.mp hb + exact (log2_le_bits r.multiplicity).trans (record_bits_le_input G r hr) + +lemma covered_card_le_records (G : Input) : (covered G).card≤2*G.records.length := by + have hh := List.toFinset_card_le + ((G.records.filter (fun e => 0< e.multiplicity)).flatMap (fun e => [e.left,e.right])) + have hlen : ((G.records.filter (fun e => 0< e.multiplicity)).flatMap (fun e => [e.left,e.right])).length= + 2*(G.records.filter (fun e => 0< e.multiplicity)).length := by + rw [List.length_flatMap] + simp + omega + rw [hlen] at hh + exact hh.trans (Nat.mul_le_mul_left 2 (List.length_filter_le _ _)) + +lemma positive_count_order_bound (G : Input) (hN : 0< count G) : G.n≤2*inputLength G := by + exact (positive_count_covered G hN).trans + ((covered_card_le_records G).trans (Nat.mul_le_mul_left _ (records_length_le_input G))) + +lemma multiplicity_pow_bound (G : Input) (e : Pair G.n) : multiplicity G e≤2^(B G+1) := by + apply (Nat.lt_log2_self (n := multiplicity G e)).le.trans + exact Nat.pow_le_pow_right (by norm_num) (by have := multiplicity_log_le_B G e; omega) + +lemma count_pow_bound (G : Input) : count G≤2^((B G+2)*q G.n) := by + have hM (M : (completeGraph G.n).Matching) : multProduct G M≤2^((B G+1)*q G.n) := by + calc + _ ≤ ∏ _e∈M.val,2^(B G+1) := prod_le_prod (fun e _ => multiplicity_pow_bound G e) + _ = (2^(B G+1))^M.val.card := by simp + _ ≤ (2^(B G+1))^(q G.n) := + Nat.pow_le_pow_right (by positivity) (card_le_univ M.val) + _ = _ := by rw [pow_mul] + calc + _ ≤ ∑ _M : (completeGraph G.n).Matching,2^((B G+1)*q G.n) := sum_le_sum fun M _ => hM M + _ = Fintype.card (completeGraph G.n).Matching*2^((B G+1)*q G.n) := by simp + _ ≤ 2^(q G.n)*2^((B G+1)*q G.n) := Nat.mul_le_mul_right _ (matching_card_bound G.n) + _ = _ := by rw [←pow_add]; congr 1; ring + +lemma approximate_bits_bound (G : Input) : + (approximate G).bits.length≤4*(inputLength G)^2*(inputLength G+2)+1 := by + by_cases hN : count G=0 + · have ha := (approximate_correct G).2.2.mpr hN + simp [ha] + · have hNpos : 0< count G := Nat.pos_of_ne_zero hN + have hn := positive_count_order_bound G hNpos + have hb := B_le_input G + have hq : q G.n≤4*(inputLength G)^2 := by + apply (q_le_square (n := G.n)).trans + calc + G.n^2≤(2*inputLength G)^2 := Nat.pow_le_pow_left hn 2 + _ = _ := by ring + have hExp : (B G+2)*q G.n≤4*(inputLength G)^2*(inputLength G+2) := by + have := Nat.mul_le_mul (Nat.add_le_add_right hb 2) hq + nlinarith + rw [Nat.size_eq_bits_len] + apply (Nat.size_le_size (approximate_correct G).1).trans + apply (Nat.size_le_size (count_pow_bound G)).trans + rw [Nat.size_pow] + omega + +theorem approximate_polynomial_output : + ∃ P : Polynomial ℕ,∀ G,(approximate G).bits.length≤ P.eval (encodeInput G).length := by + refine ⟨Polynomial.C 4*Polynomial.X^2*(Polynomial.X+Polynomial.C 2)+Polynomial.C 1,?_⟩ + intro G + simpa only [Polynomial.eval_add,Polynomial.eval_mul,Polynomial.eval_pow,Polynomial.eval_X, + Polynomial.eval_C,inputLength] using approximate_bits_bound G + +end +end BinaryMatching.Algorithm +end + +end OAI diff --git a/lean/OAI/Combinatorics/PerfectMatching/Violation.lean b/lean/OAI/Combinatorics/PerfectMatching/Violation.lean new file mode 100644 index 0000000000000000000000000000000000000000..cfca8e54a721e418bbffda83d81ad9553fba0586 --- /dev/null +++ b/lean/OAI/Combinatorics/PerfectMatching/Violation.lean @@ -0,0 +1,215 @@ +import OAI.Combinatorics.PerfectMatching.FeasibilityRepair + +namespace OAI + +section + +namespace BinaryMatching.Algorithm +noncomputable section +open Finset MatchingEntropy +variable {n : ℕ} + +def Affine.evalReal (r : Affine n) (x : Pair n → ℝ) : ℝ := + (∑ e,(r.coeff e:ℝ)*x e)+r.constant + +def allRows (n : ℕ) : List (Affine n) := + zeroRow :: ((List.finRange n).flatMap (fun v => [degreeRow v true,degreeRow v false])) ++ + (univ.toList.filter (fun S : Finset (Fin n) => decide (Odd S.card))).map cutRow + +def maxRow (x : Pair n → ℝ) : Affine n := by + classical + exact ((allRows n).argmax (fun r => r.evalReal x)).getD zeroRow + +def violation (x : Pair n → ℝ) : ℝ := (maxRow x).evalReal x + +lemma maxRow_mem_argmax (x : Pair n → ℝ) : + maxRow x ∈ (allRows n).argmax (fun r => r.evalReal x) := by + classical + unfold maxRow + cases he : (allRows n).argmax (fun r => r.evalReal x) with + | none => have hh := List.argmax_eq_none.mp he; simp [allRows] at hh + | some r => simp + +lemma row_le_violation (x : Pair n → ℝ) (r : Affine n) (hr : r∈allRows n) : + r.evalReal x≤violation x := List.le_of_mem_argmax hr (maxRow_mem_argmax x) + +lemma violation_le (x : Pair n → ℝ) (b : ℝ) (h : ∀ r∈allRows n,r.evalReal x≤b) : + violation x≤b := h _ (List.argmax_mem (maxRow_mem_argmax x)) + +lemma mem_allRows (r : Affine n) : r∈allRows n ↔ + r=zeroRow ∨ (∃ v,r=degreeRow v true ∨ r=degreeRow v false) ∨ + ∃ S : Finset (Fin n),Odd S.card ∧ r=cutRow S := by + simp only [allRows,List.mem_append,List.mem_cons,List.mem_flatMap,List.mem_finRange, + true_and,List.mem_map,List.mem_filter,mem_toList,mem_univ] + aesop + +lemma zero_row_eval (x : Pair n → ℝ) : (zeroRow : Affine n).evalReal x=0 := by + simp [Affine.evalReal,zeroRow] + +lemma degree_row_eval_pos (x : Pair n → ℝ) (v : Fin n) : + (degreeRow v true).evalReal x=(completeGraph n).degree x v-1 := by + simp [Affine.evalReal,degreeRow,LooplessGraph.degree,LooplessGraph.Incident,completeGraph, + ite_mul,sub_eq_add_neg] + apply sum_congr rfl; intro e _; rfl + +lemma degree_row_eval_neg (x : Pair n → ℝ) (v : Fin n) : + (degreeRow v false).evalReal x=1-(completeGraph n).degree x v := by + simp only [Affine.evalReal,degreeRow,Bool.false_eq_true,↓reduceIte,Int.cast_one, + Int.cast_ite,Int.cast_neg,Int.cast_zero,ite_mul,neg_one_mul,zero_mul] + have he : (∑ e : Pair n,if e.val.1=v ∨ e.val.2=v then -x e else 0)= + -(completeGraph n).degree x v := by + simp only [LooplessGraph.degree,LooplessGraph.Incident,completeGraph,←sum_neg_distrib] + apply sum_congr rfl; intro e _; split_ifs <;> simp_all + rw [he]; ring + +lemma cut_row_eval (x : Pair n → ℝ) (S : Finset (Fin n)) : + (cutRow S).evalReal x=1-(completeGraph n).cutMass x S := by + have he (e : Pair n) : ((e.val.1∈S ∧ e.val.2∉S) ∨ (e.val.2∈S ∧ e.val.1∉S)) ↔ + (completeGraph n).Crosses S e := by + simp only [LooplessGraph.Crosses,completeGraph]; tauto + simp only [Affine.evalReal,cutRow,he,Int.cast_ite,Int.cast_neg,Int.cast_one, + Int.cast_zero,ite_mul,neg_one_mul,zero_mul] + have hsum : (∑ e : Pair n,if (completeGraph n).Crosses S e then -x e else 0)= + -(completeGraph n).cutMass x S := by + simp only [LooplessGraph.cutMass,LooplessGraph.cut,sum_filter,←sum_neg_distrib] + apply sum_congr rfl; intro e _; split_ifs <;> simp_all + rw [hsum]; ring + +lemma violation_nonneg (x : Pair n → ℝ) : 0≤violation x := by + simpa only [zero_row_eval] using row_le_violation x zeroRow ((mem_allRows _).2 (Or.inl rfl)) + +lemma degree_violation (x : Pair n → ℝ) (v : Fin n) : + |(completeGraph n).degree x v-1|≤violation x := by + have hp := row_le_violation x (degreeRow v true) + ((mem_allRows _).2 (Or.inr (Or.inl ⟨v,Or.inl rfl⟩))) + have hm := row_le_violation x (degreeRow v false) + ((mem_allRows _).2 (Or.inr (Or.inl ⟨v,Or.inr rfl⟩))) + rw [degree_row_eval_pos] at hp; rw [degree_row_eval_neg] at hm + exact abs_le.mpr ⟨by linarith,hp⟩ + +lemma cut_violation (x : Pair n → ℝ) (S : Finset (Fin n)) (hS : Odd S.card) : + 1-violation x≤(completeGraph n).cutMass x S := by + have hh := row_le_violation x (cutRow S) + ((mem_allRows _).2 (Or.inr (Or.inr ⟨S,hS,rfl⟩))) + rw [cut_row_eval] at hh; linarith + +lemma violation_feasible (heven : Even n) {x : Pair n → ℝ} + (hx : x∈(completeGraph n).polytope) : violation x=0 := by + rw [(completeGraph n).polytope_eq_constraints (by simpa using heven)] at hx + apply le_antisymm _ (violation_nonneg x) + apply violation_le + intro r hr + rcases (mem_allRows r).1 hr with rfl|⟨v,rfl|rfl⟩|⟨S,hS,rfl⟩ + · rw [zero_row_eval] + · rw [degree_row_eval_pos,hx.2.1]; norm_num + · rw [degree_row_eval_neg,hx.2.1]; norm_num + · rw [cut_row_eval]; linarith [hx.2.2 S hS] + +lemma violation_repair (hn : 4≤n) (heven : Even n) (x : Pair n → ℝ) + (hx : ∀ e,x e∈Set.Icc (0:ℝ) 1) : ∃ y∈(completeGraph n).polytope, + ∀ e,|y e-x e|≤(2+10*(n:ℝ)^2)*violation x := + feasibility_repair hn heven hx (violation_nonneg x) (degree_violation x) (cut_violation x) + +lemma row_difference (r : Affine n) (x z : Pair n → ℝ) : + r.evalReal z=r.evalReal x+∑ e,(r.coeff e:ℝ)*(z e-x e) := by + simp only [Affine.evalReal,mul_sub,sum_sub_distrib]; ring + +lemma row_coeff_bound (r : Affine n) (hr : r∈allRows n) (e : Pair n) : |(r.coeff e:ℝ)|≤1 := by + rcases (mem_allRows r).1 hr with rfl|⟨v,rfl|rfl⟩|⟨S,_,rfl⟩ + · simp [zeroRow] + · simp only [degreeRow,↓reduceIte]; split_ifs <;> norm_num + · simp only [degreeRow,Bool.false_eq_true,↓reduceIte]; split_ifs <;> norm_num + · simp only [cutRow]; split_ifs <;> norm_num + +lemma active_row_subgradient (x : Pair n → ℝ) (r : Affine n) + (hr : r∈allRows n) (ha : r.evalReal x=violation x) (z : Pair n → ℝ) : + violation x+∑ e,(r.coeff e:ℝ)*(z e-x e)≤violation z := by + rw [←ha,←row_difference] + exact row_le_violation z r hr + +lemma eval_cast (a : Affine n) (x : Pair n → ℚ) : + a.evalReal (fun e => (x e:ℝ))=(a.eval x:ℝ) := by + simp [Affine.eval,Affine.evalReal] + +lemma capacities_symm (a : Table n ℤ) (i j : Fin n) : capacities a i j=capacities a j i := by + unfold capacities + rcases lt_trichotomy i j with h|h|h + · simp [h,not_lt_of_ge h.le] + · subst j; rfl + · simp [h,not_lt_of_ge h.le] + +lemma capacities_pair (a : Table n ℤ) (e : Pair n) : + capacities a e.val.1 e.val.2=(entry a e).toNat := by + simp [capacities,e.property,entry] + +lemma cut_coordinates (D : ℕ) (a : Table n ℤ) (ha : ∀ e,0≤entry a e) + (S : Finset (Fin n)) : + (completeGraph n).cutMass (fun e => (coordinates D a e:ℝ)) S= + (UnitFlow.cutCapacity (capacities a) S:ℝ)/(D:ℝ) := by + have hx : (fun e => (coordinates D a e:ℝ))= + (fun e : Pair n => (capacities a e.val.1 e.val.2:ℝ)/(D:ℝ)) := by + funext e + simp only [coordinates,Rat.cast_div,Rat.cast_intCast,Rat.cast_natCast,capacities_pair] + have he : ((entry a e).toNat:ℝ)=((entry a e:ℤ):ℝ) := by exact_mod_cast Int.toNat_of_nonneg (ha e) + rw [he] + rw [hx,cut_from_symm (fun i j => (capacities a i j:ℝ)/(D:ℝ)) (fun i j => by rw [capacities_symm a i j])] + simp only [UnitFlow.cutCapacity,Nat.cast_sum,sum_div] + +lemma activeRows_nonempty (a : Table n ℤ) : activeRows a≠[] := by simp [activeRows] + +lemma activeRow_mem_argmax (D : ℕ) (a : Table n ℤ) : + activeRow D a∈(activeRows a).argmax (fun r => r.eval (coordinates D a)) := by + unfold activeRow + cases he : (activeRows a).argmax (fun r => r.eval (coordinates D a)) with + | none => exact (activeRows_nonempty a (List.argmax_eq_none.mp he)).elim + | some r => simp + +lemma mem_activeRows (a : Table n ℤ) (r : Affine n) : r∈activeRows a ↔ + r=zeroRow ∨ (∃ v,r=degreeRow v true ∨ r=degreeRow v false) ∨ + r=cutRow (OddMincut.oddCut (capacities a) univ) := by + simp only [activeRows,List.mem_append,List.mem_cons,List.mem_flatMap,List.mem_finRange, + true_and] + aesop + +lemma activeRow_correct (hn : 2≤n) (heven : Even n) {D : ℕ} (hD : 0 (coordinates D a e:ℝ))= + violation (fun e => (coordinates D a e:ℝ)) := by + let S₀ := OddMincut.oddCut (capacities a) univ + have hh := OddMincut.oddCut_correct (capacities a) (capacities_symm a) univ + (by simpa using heven) (by simpa using hn) + have hodd : Odd S₀.card := by simpa [OddCutParity.OddSide] using hh.1 + have hmin (S : Finset (Fin n)) (hS : Odd S.card) : + UnitFlow.cutCapacity (capacities a) S₀≤UnitFlow.cutCapacity (capacities a) S := + hh.2 S (by simpa [OddCutParity.OddSide] using hS) + have hsub : ∀ r∈activeRows a,r∈allRows n := by + intro r hr + rcases (mem_activeRows a r).1 hr with h|h|h + · exact (mem_allRows r).2 (Or.inl h) + · exact (mem_allRows r).2 (Or.inr (Or.inl h)) + · exact (mem_allRows r).2 (Or.inr (Or.inr ⟨S₀,hodd,h⟩)) + have ham := List.argmax_mem (activeRow_mem_argmax D a) + refine ⟨hsub _ ham,le_antisymm (row_le_violation _ _ (hsub _ ham)) ?_⟩ + apply violation_le + intro r hr + have hdom (r' : Affine n) (hr' : r'∈activeRows a) : + r'.evalReal (fun e => (coordinates D a e:ℝ))≤ + (activeRow D a).evalReal (fun e => (coordinates D a e:ℝ)) := by + simp only [eval_cast] + exact_mod_cast List.le_of_mem_argmax hr' (activeRow_mem_argmax D a) + rcases (mem_allRows r).1 hr with h|h|⟨S,hS,rfl⟩ + · exact hdom r ((mem_activeRows a r).2 (Or.inl h)) + · exact hdom r ((mem_activeRows a r).2 (Or.inr (Or.inl h))) + · apply le_trans _ (hdom (cutRow S₀) ((mem_activeRows a _).2 (Or.inr (Or.inr rfl)))) + rw [cut_row_eval,cut_row_eval,cut_coordinates D a ha,cut_coordinates D a ha] + have hd : (0:ℝ)≤D := (Nat.cast_pos.mpr hD).le + have hle : (UnitFlow.cutCapacity (capacities a) S₀:ℝ)≤ + UnitFlow.cutCapacity (capacities a) S := by exact_mod_cast hmin S hS + linarith [div_le_div_of_nonneg_right hle hd] + +end +end BinaryMatching.Algorithm +end + +end OAI diff --git a/lean/OAI/Combinatorics/PerfectMatching/WeightedSpectrum.lean b/lean/OAI/Combinatorics/PerfectMatching/WeightedSpectrum.lean new file mode 100644 index 0000000000000000000000000000000000000000..c338edd300aaa69c1e3639e6fe8ef1e962dfa93b --- /dev/null +++ b/lean/OAI/Combinatorics/PerfectMatching/WeightedSpectrum.lean @@ -0,0 +1,79 @@ +import OAI.Combinatorics.PerfectMatching.Separable + +namespace OAI + +universe u_1 u_2 + +section + +noncomputable section +open scoped BigOperators +open Matrix +namespace MatchingEntropy + +theorem spectral_diagonal {I : Type*} [Fintype I] [DecidableEq I] + {C : Matrix I I ℝ} (hC : C.IsHermitian) (e : I) : + C e e = ∑ i, hC.eigenvalues i * (hC.eigenvectorBasis i e)^2 := by + have hh := congrArg (fun A : Matrix I I ℝ => A e e) hC.spectral_theorem + rw [Unitary.conjStarAlgAut_apply] at hh + simpa only [mul_apply, diagonal_apply, star_eq_conjTranspose, conjTranspose_apply, + star_trivial, Function.comp_apply, RCLike.ofReal_real_eq_id, id_eq, + mul_ite, ite_mul, mul_zero, zero_mul, Finset.sum_ite_eq', Finset.mem_univ, ite_true, + Matrix.IsHermitian.eigenvectorUnitary_apply, pow_two, mul_comm, mul_left_comm, + mul_assoc] using hh + +theorem covariance_weighted_rank {I : Type*} [Fintype I] [DecidableEq I] + {C : Matrix I I ℝ} (hC : C.PosSemidef) (w : I → ℝ) + (hsecond : ∀ u : I → ℝ, + u ⬝ᵥ (C *ᵥ u) ≤ ∑ e, w e * ((C *ᵥ u) e)^2) : + (C.rank : ℝ) ≤ ∑ e, w e * C e e := by + let eig := hC.isHermitian.eigenvalues + let b := hC.isHermitian.eigenvectorBasis + have heig : ∀ i, 0 ≤ eig i := hC.eigenvalues_nonneg + have hone : ∀ i, eig i ≠ 0 → 1 ≤ eig i * (∑ e, w e * (b i e)^2) := by + intro i hi + let v : I → ℝ := b i + have hv : v ⬝ᵥ v=1 := by + have hn := b.orthonormal.1 i + have hb : inner ℝ (b i) (b i)=1 := by + rw [real_inner_self_eq_norm_sq, hn] + norm_num + simpa only [EuclideanSpace.inner_eq_star_dotProduct, star_trivial] using hb + have he : C *ᵥ v=eig i • v := hC.isHermitian.mulVec_eigenvectorBasis i + have hs := hsecond v + rw [he] at hs + simp only [dotProduct_smul, smul_eq_mul, hv, mul_one, Pi.smul_apply] at hs + have heq : (∑ e, w e*(eig i * v e)^2) = + (eig i)^2 * (∑ e, w e*(v e)^2) := by + rw [Finset.mul_sum] + apply Finset.sum_congr rfl + intro e _ + ring + rw [heq] at hs + have hp : 0 < eig i := lt_of_le_of_ne (heig i) (Ne.symm hi) + nlinarith + rw [hC.isHermitian.rank_eq_card_non_zero_eigs] + calc + (Fintype.card {i // eig i ≠ 0} : ℝ) = ∑ i : {i // eig i ≠ 0}, (1:ℝ) := by simp + _ ≤ ∑ i : {i // eig i ≠ 0}, eig i * (∑ e, w e*(b i e)^2) := + Finset.sum_le_sum fun i _ => hone i i.property + _ = ∑ i, eig i * (∑ e, w e*(b i e)^2) := by + exact sum_subtype_supported (fun i => eig i ≠ 0) + (fun i => eig i * (∑ e, w e*(b i e)^2)) + (by intro i hi; rw [not_ne_iff.mp hi, zero_mul]) + _ = ∑ e, w e * C e e := by + simp_rw [Finset.mul_sum] + rw [Finset.sum_comm] + apply Finset.sum_congr rfl + intro e _ + rw [spectral_diagonal hC.isHermitian e, Finset.mul_sum] + apply Finset.sum_congr rfl + intro i _ + dsimp [eig, b] + ring + +end MatchingEntropy +end +end + +end OAI diff --git a/lean/OAI/Combinatorics/Permanent/Main.lean b/lean/OAI/Combinatorics/Permanent/Main.lean new file mode 100644 index 0000000000000000000000000000000000000000..361bccd0c8fb36d933b44c59340bf7f02f282ccd --- /dev/null +++ b/lean/OAI/Combinatorics/Permanent/Main.lean @@ -0,0 +1,116 @@ +import OAI.Combinatorics.Permanent.Perturbation + +namespace OAI + +noncomputable section +namespace FourRow +open scoped BigOperators + +def strictExponent : ℝ := 2 - 1 / 100000 + +def robustRadius : ℝ := 1 / 100000 + +theorem normalized_robust_permanent (ν : Law) (hp : IsProbability ν) + (hm : UniformMarginals ν) (htv : totalVariation ν < robustRadius) + (f : Functions) (hf : ∀ i j, 0 ≤ f i j) (hn : ∀ i, rowSq (f i) = 4) : + permanentExpectation ν f ≤ ∏ i, lpNorm strictExponent (f i) := by + have h1 := normalized_uniform_stability f hf hn + have h2 := normalized_perturbation ν hp hm f hf hn + have h3 := normalized_product_norm_lower strictExponent (by norm_num [strictExponent]) + (by norm_num [strictExponent]) f hf hn + have hd := totalDist_nonneg f + have ht := mul_le_mul_of_nonneg_right (le_of_lt htv) hd + dsimp [robustRadius] at ht + dsimp [strictExponent] at h3 ⊢ + linarith + + +/- Homogeneity extends the bound to unrestricted nonnegative rows. -/ +theorem lpNorm_scale (p : ℝ) (hp : p ≠ 0) (c : ℝ) (hc : 0 ≤ c) + (a : Site → ℝ) (ha : ∀ j, 0 ≤ a j) : + lpNorm p (fun j => c * a j) = c * lpNorm p a := by + unfold lpNorm + simp_rw [Real.mul_rpow hc (ha _)] + rw [← Finset.mul_sum, mul_div_assoc] + rw [Real.mul_rpow (Real.rpow_nonneg hc p) + (div_nonneg (Finset.sum_nonneg (fun j _ => Real.rpow_nonneg (ha j) p)) (by norm_num))] + rw [← Real.rpow_mul hc, one_div, mul_inv_cancel₀ hp, Real.rpow_one] + +theorem expectation_scale (ν : Law) (c : Site → ℝ) (f : Functions) : + permanentExpectation ν (fun i j => c i * f i j) = + (∏ i, c i) * permanentExpectation ν f := by + unfold permanentExpectation + simp_rw [Finset.prod_mul_distrib] + rw [Finset.mul_sum] + apply Finset.sum_congr rfl + intro π _ + ring + +theorem rowSq_zero_entries (a : Site → ℝ) (h : rowSq a = 0) : ∀ j, a j = 0 := by + intro j + have hs : a j ^ 2 ≤ rowSq a := + Finset.single_le_sum (fun k _ => sq_nonneg (a k)) (Finset.mem_univ j) + rw [h] at hs + nlinarith [sq_nonneg (a j)] + +theorem robust_permanent_explicit (ν : Law) (hp : IsProbability ν) + (htv : totalVariation ν < robustRadius) (hm : UniformMarginals ν) + (f : Functions) (hf : ∀ i j, 0 ≤ f i j) : + permanentExpectation ν f ≤ ∏ i, lpNorm strictExponent (f i) := by + by_cases hz : ∃ i, rowSq (f i) = 0 + · obtain ⟨i, hi⟩ := hz + have hf0 := rowSq_zero_entries (f i) hi + have hprod (π : Perm) : ∏ k, f k (π k) = 0 := by + exact Finset.prod_eq_zero (Finset.mem_univ i) (hf0 (π i)) + have hexp : permanentExpectation ν f = 0 := by + simp only [permanentExpectation, hprod, mul_zero, Finset.sum_const_zero] + rw [hexp] + exact Finset.prod_nonneg (fun k _ => lpNorm_nonneg _ _ (hf k)) + · have hspos (i : Site) : 0 < rowSq (f i) := by + have := rowSq_nonneg (f i) + have : rowSq (f i) ≠ 0 := fun hi => hz ⟨i, hi⟩ + positivity + let c : Site → ℝ := fun i => Real.sqrt (rowSq (f i) / 4) + have hcpos (i : Site) : 0 < c i := Real.sqrt_pos.2 (div_pos (hspos i) (by norm_num)) + have hc0 (i : Site) : 0 ≤ c i := le_of_lt (hcpos i) + have hcne (i : Site) : c i ≠ 0 := ne_of_gt (hcpos i) + have hcsq (i : Site) : c i ^ 2 = rowSq (f i) / 4 := + Real.sq_sqrt (div_nonneg (le_of_lt (hspos i)) (by norm_num)) + let g : Functions := fun i j => f i j / c i + have hg0 (i j : Site) : 0 ≤ g i j := div_nonneg (hf i j) (hc0 i) + have hgn (i : Site) : rowSq (g i) = 4 := by + dsimp [rowSq, g] + simp_rw [div_pow, ← Finset.sum_div] + change rowSq (f i) / c i ^ 2 = 4 + rw [hcsq] + field_simp [ne_of_gt (hspos i)] + have heq : f = fun i j => c i * g i j := by + funext i j + dsimp [g] + field_simp [hcne i] + have h := normalized_robust_permanent ν hp hm htv g hg0 hgn + have hcprod : 0 ≤ ∏ i, c i := Finset.prod_nonneg (fun i _ => hc0 i) + have hscaled := mul_le_mul_of_nonneg_left h hcprod + rw [heq, expectation_scale] + simp_rw [lpNorm_scale strictExponent (by norm_num [strictExponent]) _ (hc0 _) _ (hg0 _)] + rw [Finset.prod_mul_distrib] + exact hscaled + +/-- A robust permanent inequality with explicit absolute constants. -/ +theorem robust_permanent : + ∃ p₀ : ℝ, 4 / 3 < p₀ ∧ p₀ < 2 ∧ + ∃ ε : ℝ, 0 < ε ∧ ∀ ν : Law, + IsProbability ν → totalVariation ν < ε → UniformMarginals ν → + ∀ f : Functions, (∀ i j, 0 ≤ f i j) → + permanentExpectation ν f ≤ ∏ i, lpNorm p₀ (f i) := by + refine ⟨strictExponent, ?_, ?_, robustRadius, ?_, ?_⟩ + · norm_num [strictExponent] + · norm_num [strictExponent] + · norm_num [robustRadius] + · intro ν hp htv hm f hf + exact robust_permanent_explicit ν hp htv hm f hf + +end FourRow +end + +end OAI diff --git a/lean/OAI/Combinatorics/Permanent/Model.lean b/lean/OAI/Combinatorics/Permanent/Model.lean new file mode 100644 index 0000000000000000000000000000000000000000..0c06b90ba4b922ca664c29887a606c6e1b7f23e9 --- /dev/null +++ b/lean/OAI/Combinatorics/Permanent/Model.lean @@ -0,0 +1,40 @@ +import Mathlib + +namespace OAI + +/-! +# A robust four-row permanent inequality + +`Fin 4` labels four sites. A law is represented by real probability masses; +`IsProbability` asserts nonnegativity and total mass one. All row norms use +the uniform counting normalization. +-/ + +noncomputable section +namespace FourRow +open scoped BigOperators + +abbrev Site := Fin 4 +abbrev Perm := Equiv.Perm Site +abbrev Law := Perm → ℝ +abbrev Functions := Site → Site → ℝ + +def IsProbability (ν : Law) : Prop := + (∀ π, 0 ≤ ν π) ∧ ∑ π, ν π = 1 + +def UniformMarginals (ν : Law) : Prop := + ∀ i j : Site, ∑ π, (if π i = j then ν π else 0) = 1 / 4 + +def totalVariation (ν : Law) : ℝ := + (∑ π, |ν π - 1 / 24|) / 2 + +def lpNorm (p : ℝ) (f : Site → ℝ) : ℝ := + ((∑ j, (f j) ^ p) / 4) ^ (1 / p) + +def permanentExpectation (ν : Law) (f : Functions) : ℝ := + ∑ π, ν π * ∏ i, f i (π i) + +end FourRow +end + +end OAI diff --git a/lean/OAI/Combinatorics/Permanent/Norm.lean b/lean/OAI/Combinatorics/Permanent/Norm.lean new file mode 100644 index 0000000000000000000000000000000000000000..2eaed900db5ccce417a0f04bb3d768d56581b46d --- /dev/null +++ b/lean/OAI/Combinatorics/Permanent/Norm.lean @@ -0,0 +1,138 @@ +import OAI.Combinatorics.Permanent.Stability + +namespace OAI + +noncomputable section +namespace FourRow +open scoped BigOperators + +/- Below-two control by the tangent bound for the exponential. -/ +theorem scalar_rpow_lower (x δ : ℝ) (hx : 0 ≤ x) (hδ : 0 ≤ δ) + (hp : 0 < 2 - δ) : + x ^ 2 - δ * x ^ 2 * (x - 1) ≤ x ^ (2 - δ) := by + rcases eq_or_lt_of_le hx with hx | hx + · subst x + simp [Real.zero_rpow (ne_of_gt hp)] + have hlog := mul_le_mul_of_nonneg_left (Real.log_le_sub_one_of_pos hx) hδ + calc + x ^ 2 - δ * x ^ 2 * (x - 1) = x ^ 2 * (1 - δ * (x - 1)) := by ring + _ ≤ x ^ 2 * (1 - δ * Real.log x) := + mul_le_mul_of_nonneg_left (by linarith) (sq_nonneg x) + _ ≤ x ^ 2 * Real.exp (Real.log x * (-δ)) := by + apply mul_le_mul_of_nonneg_left _ (sq_nonneg x) + nlinarith [Real.add_one_le_exp (Real.log x * (-δ))] + _ = x ^ (2 - δ) := by + rw [sub_eq_add_neg, Real.rpow_add hx, Real.rpow_two, Real.rpow_def_of_pos hx] + +theorem normalized_entry_le (a : Site → ℝ) (ha : ∀ j, 0 ≤ a j) + (hq : rowSq a = 4) (j : Site) : a j ≤ 2 := by + have h : a j ^ 2 ≤ 4 := by + calc + a j ^ 2 ≤ rowSq a := + Finset.single_le_sum (fun i _ => sq_nonneg (a i)) (Finset.mem_univ j) + _ = 4 := hq + exact (sq_le_sq₀ (ha j) (by norm_num : (0 : ℝ) ≤ 2)).mp (by norm_num; exact h) + +theorem cubic_sum_bound (a : Site → ℝ) (ha : ∀ j, 0 ≤ a j) + (hq : rowSq a = 4) : + (∑ j, a j ^ 2 * (a j - 1)) ≤ (5 / 2) * rowDist a := by + have hpoint (j : Site) : a j ^ 2 * (a j - 1) ≤ + (5 / 2) * (a j - 1) ^ 2 + (a j ^ 2 - 1) / 2 := by + nlinarith [mul_nonneg (show 0 ≤ 2 - a j by linarith [normalized_entry_le a ha hq j]) + (sq_nonneg (a j - 1))] + have hsum := Finset.sum_le_sum (fun j (_ : j ∈ (Finset.univ : Finset Site)) => hpoint j) + simp only [rowSq, Fin.sum_univ_four] at hq + simp only [rowDist, Fin.sum_univ_four] at hsum ⊢ + linarith + +theorem lpNorm_nonneg (p : ℝ) (a : Site → ℝ) (ha : ∀ j, 0 ≤ a j) : + 0 ≤ lpNorm p a := + Real.rpow_nonneg (div_nonneg (Finset.sum_nonneg fun j _ => Real.rpow_nonneg + (ha j) _) (by norm_num)) _ + +theorem lpNorm_lower (p : ℝ) (a : Site → ℝ) (hp1 : 1 ≤ p) (hp2 : p ≤ 2) + (ha : ∀ j, 0 ≤ a j) (hq : rowSq a = 4) : + 1 - (5 * (2 - p) / 8) * rowDist a ≤ lpNorm p a := by + have hp0 : 0 < p := by linarith + have hδ : 0 ≤ 2 - p := by linarith + have hraw : 1 - (5 * (2 - p) / 8) * rowDist a ≤ + (∑ j, (a j) ^ p) / 4 := by + have hpoint (j : Site) := scalar_rpow_lower (a j) (2 - p) (ha j) hδ (by linarith) + have hs : (∑ j, (a j ^ 2 - (2 - p) * a j ^ 2 * (a j - 1))) ≤ + ∑ j, a j ^ p := by + apply Finset.sum_le_sum + intro j _ + simpa only [show (2 : ℝ) - (2 - p) = p by ring] using hpoint j + have hpoly := cubic_sum_bound a ha hq + calc + 1 - (5 * (2 - p) / 8) * rowDist a = + (4 - (2 - p) * ((5 / 2) * rowDist a)) / 4 := by ring + _ ≤ (4 - (2 - p) * (∑ j, a j ^ 2 * (a j - 1))) / 4 := by + gcongr + _ = (∑ j, (a j ^ 2 - (2 - p) * a j ^ 2 * (a j - 1))) / 4 := by + rw [Finset.sum_sub_distrib] + simp_rw [mul_assoc (2 - p), ← Finset.mul_sum] + rw [show (∑ j, a j ^ 2) = 4 from hq] + _ ≤ (∑ j, a j ^ p) / 4 := by gcongr + let L := 1 - (5 * (2 - p) / 8) * rowDist a + have hL1 : L ≤ 1 := by + dsimp [L] + have := mul_nonneg hδ (rowDist_nonneg a) + nlinarith + by_cases hL0 : 0 < L + · have hroot : L ≤ L ^ (1 / p) := by + have h := Real.rpow_le_rpow_of_exponent_ge hL0 hL1 + (show (1 : ℝ) / p ≤ 1 by rw [div_le_one hp0]; exact hp1) + simpa only [Real.rpow_one] using h + exact hroot.trans (Real.rpow_le_rpow (le_of_lt hL0) hraw (by positivity)) + · exact (le_of_not_gt hL0).trans (lpNorm_nonneg p a ha) +theorem one_sub_sum_le_prod {ι : Type*} [DecidableEq ι] (s : Finset ι) + (e : ι → ℝ) (h0 : ∀ i ∈ s, 0 ≤ e i) (h1 : ∀ i ∈ s, e i ≤ 1) : + 1 - ∑ i ∈ s, e i ≤ ∏ i ∈ s, (1 - e i) := by + induction s using Finset.induction_on with + | empty => simp + | @insert i s hi ih => + have he0 := h0 i (Finset.mem_insert_self _ _) + have he1 := h1 i (Finset.mem_insert_self _ _) + have hs0 : ∀ j ∈ s, 0 ≤ e j := fun j hj => h0 j (Finset.mem_insert_of_mem hj) + have hs1 : ∀ j ∈ s, e j ≤ 1 := fun j hj => h1 j (Finset.mem_insert_of_mem hj) + have hsum0 : 0 ≤ ∑ j ∈ s, e j := Finset.sum_nonneg hs0 + rw [Finset.sum_insert hi, Finset.prod_insert hi] + calc + 1 - (e i + ∑ j ∈ s, e j) ≤ (1 - e i) * (1 - ∑ j ∈ s, e j) := by + nlinarith [mul_nonneg he0 hsum0] + _ ≤ _ := mul_le_mul_of_nonneg_left (ih hs0 hs1) (by linarith) + +theorem normalized_rowDist_le (a : Site → ℝ) (ha : ∀ j, 0 ≤ a j) + (hq : rowSq a = 4) : rowDist a ≤ 8 := by + simp only [rowSq, Fin.sum_univ_four] at hq + simp only [rowDist, Fin.sum_univ_four] + nlinarith [ha 0, ha 1, ha 2, ha 3] + +theorem normalized_product_norm_lower (p : ℝ) (hp0 : 9 / 5 ≤ p) (hp2 : p ≤ 2) + (f : Functions) (hf : ∀ i j, 0 ≤ f i j) (hn : ∀ i, rowSq (f i) = 4) : + 1 - (5 * (2 - p) / 8) * totalDist f ≤ ∏ i, lpNorm p (f i) := by + let e : Site → ℝ := fun i => (5 * (2 - p) / 8) * rowDist (f i) + have he0 (i : Site) : 0 ≤ e i := by + dsimp [e] + exact mul_nonneg (by linarith) (rowDist_nonneg _) + have he1 (i : Site) : e i ≤ 1 := by + have := normalized_rowDist_le (f i) (hf i) (hn i) + have := rowDist_nonneg (f i) + dsimp [e] + nlinarith [mul_nonneg (show 0 ≤ p - 9 / 5 by linarith) + (rowDist_nonneg (f i))] + have hb := one_sub_sum_le_prod Finset.univ e (fun i _ => he0 i) (fun i _ => he1 i) + have hp : ∏ i, (1 - e i) ≤ ∏ i, lpNorm p (f i) := by + apply Finset.prod_le_prod₀ + · intro i _; linarith [he1 i] + · intro i _; exact lpNorm_lower p (f i) (by linarith) hp2 (hf i) (hn i) + have heq : ∑ i, e i = (5 * (2 - p) / 8) * totalDist f := by + simp only [e, totalDist, Finset.mul_sum] + rw [heq] at hb + exact hb.trans hp + +end FourRow +end + +end OAI diff --git a/lean/OAI/Combinatorics/Permanent/Perturbation.lean b/lean/OAI/Combinatorics/Permanent/Perturbation.lean new file mode 100644 index 0000000000000000000000000000000000000000..c417735f1a5b8a98d0f99d957070a1adb0d5aa26 --- /dev/null +++ b/lean/OAI/Combinatorics/Permanent/Perturbation.lean @@ -0,0 +1,124 @@ +import OAI.Combinatorics.Permanent.Norm + +namespace OAI + +noncomputable section +namespace FourRow +open scoped BigOperators + +/- Exact marginal cancellation controls all perturbations quadratically. -/ +theorem abs_mul_le_half_sq (a b : ℝ) : |a * b| ≤ (a ^ 2 + b ^ 2) / 2 := by + apply abs_le.mpr + constructor + · nlinarith [sq_nonneg (a + b)] + · nlinarith [sq_nonneg (a - b)] + +theorem pair_shift_sq_le (a b : ℝ) (hb0 : 0 ≤ 1 + b) (hb2 : 1 + b ≤ 2) : + (a * (1 + b) + b) ^ 2 ≤ 5 * (a ^ 2 + b ^ 2) := by + have hb : (1 + b) ^ 2 ≤ 4 := by nlinarith + nlinarith [sq_nonneg (a - b * (1 + b)), + mul_nonneg (sq_nonneg a) (show 0 ≤ 4 - (1 + b) ^ 2 by linarith), + mul_nonneg (sq_nonneg b) (show 0 ≤ 4 - (1 + b) ^ 2 by linarith)] + +theorem product_remainder_bound (a : Site → ℝ) (ha0 : ∀ i, 0 ≤ a i) + (ha2 : ∀ i, a i ≤ 2) : + |(∏ i, a i) - 1 - ∑ i, (a i - 1)| ≤ 3 * ∑ i, (a i - 1) ^ 2 := by + let g := fun i => a i - 1 + let A := g 0 * (1 + g 1) + g 1 + let B := g 2 * (1 + g 3) + g 3 + have hA : A ^ 2 ≤ 5 * (g 0 ^ 2 + g 1 ^ 2) := + pair_shift_sq_le _ _ (by dsimp [g]; linarith [ha0 1]) + (by dsimp [g]; linarith [ha2 1]) + have hB : B ^ 2 ≤ 5 * (g 2 ^ 2 + g 3 ^ 2) := + pair_shift_sq_le _ _ (by dsimp [g]; linarith [ha0 3]) + (by dsimp [g]; linarith [ha2 3]) + have hid : (∏ i, a i) - 1 - ∑ i, (a i - 1) = g 0 * g 1 + g 2 * g 3 + A * B := by + simp only [Fin.prod_univ_four, Fin.sum_univ_four] + dsimp [A, B, g] + ring + rw [hid] + have ht : |g 0 * g 1 + g 2 * g 3 + A * B| ≤ + |g 0 * g 1| + |g 2 * g 3| + |A * B| := + (abs_add_le _ _).trans (add_le_add (abs_add_le _ _) (le_refl _)) + have h1 := abs_mul_le_half_sq (g 0) (g 1) + have h2 := abs_mul_le_half_sq (g 2) (g 3) + have h3 := abs_mul_le_half_sq A B + change _ ≤ 3 * ∑ i, g i ^ 2 + simp only [Fin.sum_univ_four] + linarith + +theorem uniform_probability : IsProbability uniformLaw := by + constructor + · intro π; norm_num [uniformLaw] + · norm_num [uniformLaw, Fintype.card_perm, Site, Nat.factorial] + +theorem uniform_marginals : UniformMarginals uniformLaw := by + intro i j + fin_cases i <;> fin_cases j <;> + simp only [uniformLaw, sum_perm_succ, Fin.sum_univ_succ, Fintype.sum_unique] <;> + simp [decompose4_two, decompose4_three, decompose3_two, Equiv.swap_apply_def] <;> norm_num + +theorem marginal_average (ν : Law) (hν : UniformMarginals ν) (i : Site) + (a : Site → ℝ) : (∑ π, ν π * a (π i)) = (∑ j, a j) / 4 := by + have hrepr (π : Perm) : ν π * a (π i) = ∑ j, (if π i = j then ν π else 0) * a j := by + simp + simp_rw [hrepr] + rw [Finset.sum_comm] + simp_rw [← Finset.sum_mul, hν i] + rw [← Finset.mul_sum] + ring + +theorem law_linear_expectation (ν : Law) (hp : IsProbability ν) + (hm : UniformMarginals ν) (f : Functions) : + (∑ π, ν π * (1 + ∑ i, (f i (π i) - 1))) = + 1 + ∑ i, (∑ j, (f i j - 1)) / 4 := by + simp_rw [mul_add, mul_one, Finset.sum_add_distrib, Finset.mul_sum] + rw [hp.2, Finset.sum_comm] + exact congrArg (fun x => 1 + x) (Finset.sum_congr rfl (fun i _ => marginal_average ν hm i (fun j => f i j - 1))) + +theorem normalized_perturbation (ν : Law) (hp : IsProbability ν) + (hm : UniformMarginals ν) (f : Functions) (hf : ∀ i j, 0 ≤ f i j) + (hn : ∀ i, rowSq (f i) = 4) : + permanentExpectation ν f ≤ permanentExpectation uniformLaw f + + 6 * totalVariation ν * totalDist f := by + let R : Perm → ℝ := fun π => (∏ i, f i (π i)) - 1 - ∑ i, (f i (π i) - 1) + have hR (π : Perm) : |R π| ≤ 3 * totalDist f := by + have hpoint := product_remainder_bound (fun i => f i (π i)) + (fun i => hf i (π i)) (fun i => normalized_entry_le (f i) (hf i) (hn i) (π i)) + apply hpoint.trans + apply mul_le_mul_of_nonneg_left _ (by norm_num) + apply Finset.sum_le_sum + intro i _ + exact Finset.single_le_sum (fun j _ => sq_nonneg (f i j - 1)) (Finset.mem_univ _) + have heq : permanentExpectation ν f - permanentExpectation uniformLaw f = + ∑ π, (ν π - uniformLaw π) * R π := by + have hν := law_linear_expectation ν hp hm f + have hu := law_linear_expectation uniformLaw uniform_probability uniform_marginals f + dsimp [permanentExpectation] + dsimp [R] + have hid (π : Perm) : + (ν π - uniformLaw π) * ((∏ i, f i (π i)) - 1 - ∑ i, (f i (π i) - 1)) = + ν π * (∏ i, f i (π i)) - uniformLaw π * (∏ i, f i (π i)) - + (ν π * (1 + ∑ i, (f i (π i) - 1)) - + uniformLaw π * (1 + ∑ i, (f i (π i) - 1))) := by ring + simp_rw [hid] + rw [Finset.sum_sub_distrib, Finset.sum_sub_distrib, Finset.sum_sub_distrib, hν, hu] + ring + have hbound : (∑ π, (ν π - uniformLaw π) * R π) ≤ + (∑ π, |ν π - uniformLaw π|) * (3 * totalDist f) := by + rw [Finset.sum_mul] + apply Finset.sum_le_sum + intro π _ + calc + _ ≤ |(ν π - uniformLaw π) * R π| := le_abs_self _ + _ = |ν π - uniformLaw π| * |R π| := abs_mul _ _ + _ ≤ _ := mul_le_mul_of_nonneg_left (hR π) (abs_nonneg _) + rw [← heq] at hbound + change _ ≤ _ + 6 * ((∑ π, |ν π - 1 / 24|) / 2) * totalDist f + dsimp [uniformLaw] at hbound + linarith + +end FourRow +end + +end OAI diff --git a/lean/OAI/Combinatorics/Permanent/Stability.lean b/lean/OAI/Combinatorics/Permanent/Stability.lean new file mode 100644 index 0000000000000000000000000000000000000000..97649967b37ccc799084ef67f6c57c0d23205838 --- /dev/null +++ b/lean/OAI/Combinatorics/Permanent/Stability.lean @@ -0,0 +1,204 @@ +import OAI.Combinatorics.Permanent.Model + +namespace OAI + +noncomputable section +namespace FourRow +open scoped BigOperators + +/- Quantitative exponent-two stability estimates. -/ +def rowSq (a : Site → ℝ) : ℝ := ∑ j, a j ^ 2 + +def rowDist (a : Site → ℝ) : ℝ := ∑ j, (a j - 1) ^ 2 + +def rowDot (a b : Site → ℝ) : ℝ := ∑ j, a j * b j + +def pairEntries (a b : Site → ℝ) : Fin 6 → ℝ := + ![a 0 * b 1 + a 1 * b 0, + a 0 * b 2 + a 2 * b 0, + a 0 * b 3 + a 3 * b 0, + a 1 * b 2 + a 2 * b 1, + a 1 * b 3 + a 3 * b 1, + a 2 * b 3 + a 3 * b 2] + +def pairSq (a b : Site → ℝ) : ℝ := ∑ j, pairEntries a b j ^ 2 + +theorem rowSq_nonneg (a : Site → ℝ) : 0 ≤ rowSq a := + Finset.sum_nonneg fun _ _ => sq_nonneg _ + +theorem rowDist_nonneg (a : Site → ℝ) : 0 ≤ rowDist a := + Finset.sum_nonneg fun _ _ => sq_nonneg _ + +theorem pairSq_nonneg (a b : Site → ℝ) : 0 ≤ pairSq a b := + Finset.sum_nonneg fun _ _ => sq_nonneg _ + +theorem pairSq_identity (a b : Site → ℝ) : + pairSq a b = rowSq a * rowSq b + rowDot a b ^ 2 - + 2 * ∑ j, (a j * b j) ^ 2 := by + simp only [pairSq, pairEntries, rowSq, rowDot, Fin.sum_univ_six, + Fin.sum_univ_four, Matrix.cons_val_zero, Matrix.cons_val_one, + Matrix.cons_val] + ring + +theorem pairSq_comm (a b : Site → ℝ) : pairSq a b = pairSq b a := by + simp only [pairSq_identity, rowDot, mul_comm] + +theorem rowDot_sq_le (a b : Site → ℝ) : + rowDot a b ^ 2 ≤ rowSq a * rowSq b := + Finset.sum_mul_sq_le_sq_mul_sq Finset.univ a b + +theorem rowDot_sq_le_four (a b : Site → ℝ) : + rowDot a b ^ 2 ≤ 4 * ∑ j, (a j * b j) ^ 2 := by + have h := Finset.sum_mul_sq_le_sq_mul_sq Finset.univ + (fun j : Site => (1 : ℝ)) (fun j => a j * b j) + simpa [rowDot] using h + +theorem pair_stability_one (a b : Site → ℝ) + (ha : ∀ j, 0 ≤ a j) (hb : ∀ j, 0 ≤ b j) + (haq : rowSq a = 4) (hbq : rowSq b = 4) : + rowDist a ≤ 9 * (24 - pairSq a b) := by + let t := rowDot a b + let s := ∑ j, (a j * b j) ^ 2 + let d := ∑ j, (a j - b j) ^ 2 + let e := ∑ j, (a j * b j - 1) ^ 2 + let D := 24 - pairSq a b + have ht0 : 0 ≤ t := Finset.sum_nonneg fun j _ => mul_nonneg (ha j) (hb j) + have ht2 : t ^ 2 ≤ 16 := by + have h := rowDot_sq_le a b + rw [haq, hbq] at h + norm_num at h + exact h + have ht4 : t ≤ 4 := by nlinarith + have htprod : 0 ≤ t * (4 - t) := mul_nonneg ht0 (by linarith) + have hts : t ^ 2 ≤ 4 * s := rowDot_sq_le_four a b + have hD : D = 8 - t ^ 2 + 2 * s := by + dsimp [D, t, s] + rw [pairSq_identity, haq, hbq] + ring + have hd : d = 8 - 2 * t := by + have h : d = rowSq a + rowSq b - 2 * t := by + dsimp [d, rowSq, t, rowDot] + simp only [Fin.sum_univ_four] + ring + rw [h, haq, hbq] + ring + have he : e = s - 2 * t + 4 := by + dsimp [e, s, t, rowDot] + simp only [Fin.sum_univ_four] + ring + have hdD : d ≤ D := by nlinarith + have heD : 2 * e ≤ D := by nlinarith + have hpoint (j : Site) : (a j - 1) ^ 2 ≤ + 8 * (a j - b j) ^ 2 + 2 * (a j * b j - 1) ^ 2 := by + have haj : a j ^ 2 ≤ 4 := by + calc + a j ^ 2 ≤ rowSq a := + Finset.single_le_sum (fun i _ => sq_nonneg (a i)) (Finset.mem_univ j) + _ = 4 := haq + have h1 : (a j - 1) ^ 2 ≤ (a j ^ 2 - 1) ^ 2 := by + nlinarith [mul_nonneg (mul_nonneg (ha j) (show 0 ≤ a j + 2 by linarith [ha j])) + (sq_nonneg (a j - 1))] + have h2 : (a j ^ 2 - a j * b j) ^ 2 ≤ 4 * (a j - b j) ^ 2 := by + nlinarith [mul_nonneg (show 0 ≤ 4 - a j ^ 2 by linarith) + (sq_nonneg (a j - b j))] + nlinarith [sq_nonneg (a j ^ 2 - 2 * a j * b j + 1)] + have hs := Finset.sum_le_sum (fun j (_ : j ∈ (Finset.univ : Finset Site)) => hpoint j) + have hbound : rowDist a ≤ 8 * d + 2 * e := by + simpa only [rowDist, Finset.sum_add_distrib, ← Finset.mul_sum] using hs + linarith + +theorem pair_stability (a b : Site → ℝ) + (ha : ∀ j, 0 ≤ a j) (hb : ∀ j, 0 ≤ b j) + (haq : rowSq a = 4) (hbq : rowSq b = 4) : + rowDist a + rowDist b ≤ 18 * (24 - pairSq a b) := by + have h1 := pair_stability_one a b ha hb haq hbq + have h2 := pair_stability_one b a hb ha hbq haq + rw [pairSq_comm b a] at h2 + linarith + + +theorem sum_perm_succ {n : ℕ} (f : Equiv.Perm (Fin (n + 1)) → ℝ) : + ∑ σ, f σ = ∑ i : Fin (n + 1), ∑ τ : Equiv.Perm (Fin n), + f (Equiv.Perm.decomposeFin.symm (i, τ)) := by + rw [← Equiv.sum_comp Equiv.Perm.decomposeFin.symm f] + exact Fintype.sum_prod_type _ + +theorem decompose4_two (i : Fin 4) (e : Equiv.Perm (Fin 3)) : + Equiv.Perm.decomposeFin.symm (i, e) 2 = Equiv.swap 0 i (e 1).succ := + Equiv.Perm.decomposeFin_symm_apply_succ e i 1 + +theorem decompose4_three (i : Fin 4) (e : Equiv.Perm (Fin 3)) : + Equiv.Perm.decomposeFin.symm (i, e) 3 = Equiv.swap 0 i (e 2).succ := + Equiv.Perm.decomposeFin_symm_apply_succ e i 2 + +theorem decompose3_two (i : Fin 3) (e : Equiv.Perm (Fin 2)) : + Equiv.Perm.decomposeFin.symm (i, e) 2 = Equiv.swap 0 i (e 1).succ := + Equiv.Perm.decomposeFin_symm_apply_succ e i 1 + +theorem permanent_pair_identity (f : Functions) : + (∑ π : Perm, ∏ i, f i (π i)) = + ∑ j : Fin 6, pairEntries (f 0) (f 1) j * + pairEntries (f 2) (f 3) (Fin.rev j) := by + change (∑ π : Equiv.Perm (Fin 4), ∏ i : Fin 4, f i (π i)) = _ + simp only [sum_perm_succ, Fin.sum_univ_succ, Fintype.sum_unique, + Fin.prod_univ_four, pairEntries] + simp [decompose4_two, decompose4_three, decompose3_two, + Equiv.swap_apply_def, Fin.rev] + ring + + +def uniformLaw : Law := fun _ => 1 / 24 + +def totalDist (f : Functions) : ℝ := ∑ i, rowDist (f i) + +theorem totalDist_nonneg (f : Functions) : 0 ≤ totalDist f := + Finset.sum_nonneg fun i _ => rowDist_nonneg (f i) + +theorem pairSq_le (a b : Site → ℝ) + (ha : ∀ j, 0 ≤ a j) (hb : ∀ j, 0 ≤ b j) + (haq : rowSq a = 4) (hbq : rowSq b = 4) : pairSq a b ≤ 24 := by + have h := pair_stability_one a b ha hb haq hbq + have h0 := rowDist_nonneg a + linarith + +theorem uniform_expectation_eq (f : Functions) : + permanentExpectation uniformLaw f = (∑ π : Perm, ∏ i, f i (π i)) / 24 := by + simp only [permanentExpectation, uniformLaw, ← Finset.mul_sum] + ring + +theorem normalized_uniform_stability (f : Functions) + (hf : ∀ i j, 0 ≤ f i j) (hn : ∀ i, rowSq (f i) = 4) : + permanentExpectation uniformLaw f ≤ 1 - totalDist f / 1728 := by + let P := permanentExpectation uniformLaw f + let U := pairSq (f 0) (f 1) + let V := pairSq (f 2) (f 3) + have hU0 : 0 ≤ U := pairSq_nonneg _ _ + have hV0 : 0 ≤ V := pairSq_nonneg _ _ + have hU : U ≤ 24 := pairSq_le _ _ (hf 0) (hf 1) (hn 0) (hn 1) + have hV : V ≤ 24 := pairSq_le _ _ (hf 2) (hf 3) (hn 2) (hn 3) + have hcs := Finset.sum_mul_sq_le_sq_mul_sq Finset.univ + (pairEntries (f 0) (f 1)) (fun j => pairEntries (f 2) (f 3) (Fin.rev j)) + have hrev : (∑ j : Fin 6, pairEntries (f 2) (f 3) (Fin.rev j) ^ 2) = V := + Equiv.sum_comp Fin.revPerm (fun j => pairEntries (f 2) (f 3) j ^ 2) + rw [← permanent_pair_identity, hrev] at hcs + change (∑ π : Perm, ∏ i, f i (π i)) ^ 2 ≤ U * V at hcs + have hP2 : 576 * P ^ 2 ≤ U * V := by + dsimp [P] + rw [uniform_expectation_eq] + nlinarith [hcs] + have hUV : U * V ≤ 12 * (U + V) := by + nlinarith [mul_nonneg hU0 (show 0 ≤ 24 - V by linarith), + mul_nonneg hV0 (show 0 ≤ 24 - U by linarith)] + have hd : totalDist f ≤ 18 * (48 - U - V) := by + have h1 := pair_stability _ _ (hf 0) (hf 1) (hn 0) (hn 1) + have h2 := pair_stability _ _ (hf 2) (hf 3) (hn 2) (hn 3) + simp only [totalDist, Fin.sum_univ_four] + dsimp [U, V] + linarith + change P ≤ _ + nlinarith [sq_nonneg (P - 1)] + +end FourRow +end + +end OAI diff --git a/lean/OAI/Combinatorics/PlanarL1/Ambient.lean b/lean/OAI/Combinatorics/PlanarL1/Ambient.lean new file mode 100644 index 0000000000000000000000000000000000000000..94c6d6a6dc4107016bdcb87e7702689e8e9059d6 --- /dev/null +++ b/lean/OAI/Combinatorics/PlanarL1/Ambient.lean @@ -0,0 +1,372 @@ +import OAI.Combinatorics.PlanarL1.OrderedState +import OAI.Combinatorics.PlanarL1.Increments + +namespace OAI + +section + +namespace PlanarL1.Columns.Model +open scoped NNReal +variable {k : ℕ} {M : Model (k+1)} + +/-- Full columns regarded in the unrestricted path pseudometric. Connectedness +here is supplied by the connected graph realization, not an extra condition on +the embedding theorem. -/ +structure Ambient (M : Model (k+1)) where + root : Fin (k+1) + connected : ∀ i, (M.activeGraph Set.univ).Reachable root i + +namespace Ambient +variable (A : Ambient M) + +def point (i : Fin (k+1)) (H : ℝ) : M.Point Set.univ A.root := + ⟨i,H,Set.mem_univ H,A.connected i⟩ + +lemma point_dist (i : Fin (k+1)) (H T : ℝ) : + dist (A.point i H) (A.point i T)=|H-T| := (A.point i H).dist_same_column _ rfl + +lemma point_switch (i j : Fin (k+1)) (H : ℝ) (hh : H ∈ M.heights i j) : + dist (A.point i H) (A.point j H)=0 := by + apply le_antisymm _ dist_nonneg + simpa only [point,sub_self,abs_zero,add_zero] using + (A.point i H).dist_le_switch (A.point j H) (Set.mem_univ H) hh + +lemma taper_switch {r : ℝ} (hr : 0 < r) (S : Set (M.Point Set.univ A.root)) + (i j : Fin (k+1)) (H : ℝ) (hh : H ∈ M.heights i j) : + Increment.taper S r (A.point i H)=Increment.taper S r (A.point j H) := by + have h := Increment.taper_difference (S := S) hr (A.point i H) (A.point j H) + rw [A.point_switch i j H hh,zero_div] at h + exact sub_eq_zero.mp (abs_nonpos_iff.mp h) + +/-- Every signed increment from the recorded lifetime is retained. Regions are +those at their creation times and are not re-tapered after subsequent changes. -/ +noncomputable def historyField {I : Set ℝ} (s : M.Field I 4) (a b : Fin (k+1)) + {m : ℕ} (r : Fin m → ℝ) (regions : Fin m → Set (M.Point Set.univ A.root)) + (sign : Fin m → Bool) (c : ℝ) (hc : 0 < c) (hcr : c ≤ 4) + (hr : ∀ j, 0 < r j) + (hsep : ∀ i j, i ≠ j → 10*r i ≤ c*r j ∨ 10*r j ≤ c*r i) : M.Field I 100 where + value i H := ∑ j, Increment.signedDamped (sign j) (c*r j) (r j) + ((s.transverse (by norm_num) a b).value i) + (fun T : I => Increment.taper (regions j)ᶜ (r j) (A.point i T.val)) H + vertical i := by + have h := Increment.damped_lifetime Finset.univ (r := r) + (t := (s.transverse (by norm_num) a b).value i) + (w := fun j (H : I) => Increment.taper (regions j)ᶜ (r j) (A.point i H.val)) + sign hc hcr (fun j _ => hr j) ((s.transverse (by norm_num) a b).vertical i) + (fun j _ H => Increment.taper_bounds (hr j) (A.point i H.val)) + (fun j _ H T => by + have h := Increment.taper_difference (S := (regions j)ᶜ) (hr j) (A.point i H.val) (A.point i T.val) + simpa only [A.point_dist,Subtype.dist_eq,Real.dist_eq] using h) + (fun i _ j _ hij => hsep i j hij) + simpa only [Finset.mem_univ,Finset.sum_const_zero,ite_true] using h.weaken (by norm_num : (68:ℝ≥0) ≤ 100) + switch i j H hh := by + apply Finset.sum_congr rfl + intro q _ + have ht := (s.transverse (by norm_num) a b).switch i j H hh + have hw := A.taper_switch (hr q) (regions q)ᶜ i j H.val hh + simp only [Increment.signedDamped,Increment.damped,ht,hw] + +end Ambient +end PlanarL1.Columns.Model + + + +end + +section + +namespace PlanarL1.Columns.Model.Ambient +open scoped NNReal +variable {k : ℕ} {M : Model (k+1)} + +/-- The literal finite list of increments already recorded for an identifier. +Regions are recorded at creation time, as required by . -/ +structure History (A : Ambient M) (c : ℝ) where + count : ℕ + radius : Fin count → ℝ + region : Fin count → Set (M.Point Set.univ A.root) + sign : Fin count → Bool + positive : ∀ i, 0 < radius i + separated : ∀ i j, i≠j → 10*radius i ≤ c*radius j ∨ 10*radius j ≤ c*radius i + +namespace History +variable {A : Ambient M} {c : ℝ} + +def empty (A : Ambient M) (c : ℝ) : History A c where + count := 0 + radius := Fin.elim0 + region := Fin.elim0 + sign := Fin.elim0 + positive := fun i => Fin.elim0 i + separated := fun i => Fin.elim0 i + +noncomputable def field (H : History A c) {I : Set ℝ} (s : M.Field I 4) + (a b : Fin (k+1)) (hc : 0 < c) (hcr : c ≤ 4) : M.Field I 100 := + A.historyField s a b H.radius H.region H.sign c hc hcr H.positive H.separated + +lemma field_empty {I : Set ℝ} (s : M.Field I 4) (a b : Fin (k+1)) + (hc : 0 < c) (hcr : c ≤ 4) (i : Fin (k+1)) (T : I) : + ((empty A c).field s a b hc hcr).value i T=0 := by + simp only [field,empty,historyField] + exact Finset.sum_eq_zero (fun i _ => Fin.elim0 i) + +def append (H : History A c) (r : ℝ) (S : Set (M.Point Set.univ A.root)) (e : Bool) + (hr : 0 < r) (hcross : ∀ j, 10*r ≤ c*H.radius j) : History A c where + count := H.count+1 + radius := Fin.snoc H.radius r + region := Fin.snoc H.region S + sign := Fin.snoc H.sign e + positive i := by + cases i using Fin.lastCases with + | last => simpa only [Fin.snoc_last] using hr + | cast i => simpa only [Fin.snoc_castSucc] using H.positive i + separated i j hij := by + cases i using Fin.lastCases with + | last => + cases j using Fin.lastCases with + | last => exact (hij rfl).elim + | cast j => exact Or.inl (by simpa only [Fin.snoc_last,Fin.snoc_castSucc] using hcross j) + | cast i => + cases j using Fin.lastCases with + | last => exact Or.inr (by simpa only [Fin.snoc_last,Fin.snoc_castSucc] using hcross i) + | cast j => + simpa only [Fin.snoc_castSucc] using H.separated i j (fun h => hij (congrArg Fin.castSucc h)) + +/-- No earlier summand is re-tapered or otherwise modified by appending a step. -/ +lemma field_append_value (H : History A c) (r : ℝ) (S : Set (M.Point Set.univ A.root)) + (e : Bool) (hr : 0 < r) (hcross : ∀ j, 10*r ≤ c*H.radius j) + {I : Set ℝ} (s : M.Field I 4) (a b : Fin (k+1)) (hc : 0 < c) (hcr : c ≤ 4) + (i : Fin (k+1)) (T : I) : + ((H.append r S e hr hcross).field s a b hc hcr).value i T = + (H.field s a b hc hcr).value i T+ + Increment.signedDamped e (c*r) r ((s.transverse (by norm_num) a b).value i) + (fun U : I => Increment.taper Sᶜ r (A.point i U.val)) T := by + change (∑ j : Fin (H.count+1), _) = (∑ j : Fin H.count, _)+_ + rw [Fin.sum_univ_castSucc] + simp only [append,Fin.snoc_castSucc,Fin.snoc_last] + +end History +end PlanarL1.Columns.Model.Ambient + + + +end + +section + +namespace PlanarL1.Columns.Model +open MeasureTheory +open scoped NNReal +attribute [local instance] Classical.propDecidable +variable {k : ℕ} {M : Model (k+1)} + +namespace BData +variable {A : Ambient M} {c : ℝ} + +def Recorded (D : BData M) (H : A.History c) (hc : 0 < c) (hcr : c ≤ 4) : Prop := + match D with + | .ordinary _ => True + | .ordered D => ∀ i T, D.auxiliary.value i T=(H.field D.base D.lower D.upper hc hcr).value i T + +noncomputable def incrementAuxiliary (D : BData M) (H : A.History c) + (r : ℝ) (region : Set (M.Point Set.univ A.root)) (e : Bool) + (hc : 0 < c) (hcr : c ≤ 4) (hr : 0 < r) + (hcross : ∀ j, 10*r ≤ c*H.radius j) : D.Auxiliary := + match D with + | .ordinary _ => () + | .ordered D => (H.append r region e hr hcross).field D.base D.lower D.upper hc hcr + +/-- The actual recorded increment, not a replacement of the old history. -/ +lemma increment_difference (D : OrderedData M) (H : A.History c) + (r : ℝ) (region : Set (M.Point Set.univ A.root)) (e : Bool) + (hc : 0 < c) (hcr : c ≤ 4) (hr : 0 < r) + (hcross : ∀ j, 10*r ≤ c*H.radius j) + (hrec : (BData.ordered D).Recorded H hc hcr) + (lam : ℝ≥0) (hlam : lam ≤ (1:ℝ≥0)/100) + (i : Fin (k+1)) (T : D.band) : + ((BData.ordered D).auxiliaryField + ((BData.ordered D).incrementAuxiliary H r region e hc hcr hr hcross) lam hlam).value i T - + D.value lam i T = + lam*Increment.signedDamped e (c*r) r ((D.base.transverse (by norm_num) D.lower D.upper).value i) + (fun U : D.band => Increment.taper regionᶜ r (A.point i U.val)) T := by + change ((D.withAuxiliary ((H.append r region e hr hcross).field D.base D.lower D.upper hc hcr)).field lam hlam).value i T - D.value lam i T = _ + erw [OrderedData.field_value,OrderedData.withAuxiliary_value] + rw [hrec i T,Ambient.History.field_append_value] + ring + +lemma increment_boundary (D : BData M) (H : A.History c) + (r : ℝ) (region : Set (M.Point Set.univ A.root)) (e : Bool) + (hc : 0 < c) (hcr : c ≤ 4) (hr : 0 < r) + (hcross : ∀ j, 10*r ≤ c*H.radius j) (hrec : D.Recorded H hc hcr) + (lam : ℝ≥0) (hlam : lam ≤ (1:ℝ≥0)/100) + (i : Fin (k+1)) (T : D.band) (U : ℝ) (hU : A.point i U ∉ region) : + |(D.auxiliaryField (D.incrementAuxiliary H r region e hc hcr hr hcross) lam hlam).value i T - + D.value lam i T| ≤ (lam:ℝ)*10*|T.val-U| := by + cases D with + | ordinary D => + change |D.value i T-D.value i T| ≤ _ + rw [sub_self,abs_zero] + positivity + | ordered D => + dsimp only [BData.value] + erw [increment_difference D H r region e hc hcr hr hcross hrec lam hlam] + rw [abs_mul,abs_of_nonneg lam.coe_nonneg] + have hb := Increment.signed_tapered_magnitude e (mul_pos hc hr) hr + (by nlinarith : 2*(c*r) ≤ 8*r) (show A.point i U ∈ regionᶜ from hU) + (x := A.point i T.val) (q := (D.base.transverse (by norm_num) D.lower D.upper).value i T) + rw [A.point_dist] at hb + simpa only [Increment.signedDamped,Increment.damped,mul_assoc] using + mul_le_mul_of_nonneg_left hb lam.coe_nonneg + +/-- Ordinary identifiers record no increments. Ordered identifiers keep the +entire old list and append precisely the new signed region-tapered term. -/ +def incrementHistory (D : BData M) (H : A.History c) + (r : ℝ) (region : Set (M.Point Set.univ A.root)) (e : Bool) + (hr : 0 < r) (hcross : ∀ j, 10*r ≤ c*H.radius j) : A.History c := + match D with + | .ordinary _ => H + | .ordered _ => H.append r region e hr hcross + +lemma increment_recorded (D : BData M) (H : A.History c) + (r : ℝ) (region : Set (M.Point Set.univ A.root)) (e : Bool) + (hc : 0 < c) (hcr : c ≤ 4) (hr : 0 < r) + (hcross : ∀ j, 10*r ≤ c*H.radius j) : + (D.withAuxiliary (D.incrementAuxiliary H r region e hc hcr hr hcross)).Recorded + (D.incrementHistory H r region e hr hcross) hc hcr := by + cases D with + | ordinary D => trivial + | ordered D => exact fun _ _ => rfl + +lemma increment_magnitude (D : BData M) (H : A.History c) + (r : ℝ) (region : Set (M.Point Set.univ A.root)) (e : Bool) + (hc : 0 < c) (hcr : c ≤ 4) (hr : 0 < r) + (hcross : ∀ j, 10*r ≤ c*H.radius j) (hrec : D.Recorded H hc hcr) + (lam : ℝ≥0) (hlam : lam ≤ (1:ℝ≥0)/100) + (i : Fin (k+1)) (T : D.band) : + |(D.auxiliaryField (D.incrementAuxiliary H r region e hc hcr hr hcross) lam hlam).value i T - + D.value lam i T| ≤ (lam:ℝ)*10*r := by + cases D with + | ordinary D => + change |D.value i T-D.value i T| ≤ _ + rw [sub_self,abs_zero] + positivity + | ordered D => + dsimp only [BData.value] + erw [increment_difference D H r region e hc hcr hr hcross hrec lam hlam, + abs_mul,abs_of_nonneg lam.coe_nonneg] + have hb : |Increment.signedDamped e (c*r) r + ((D.base.transverse (by norm_num) D.lower D.upper).value i) + (fun U : D.band => Increment.taper regionᶜ r (A.point i U.val)) T| ≤ 10*r := by + have hs := Increment.scalar_magnitude (mul_pos hc hr) hr (by nlinarith : 2*(c*r) ≤ 8*r) + (t := (D.base.transverse (by norm_num) D.lower D.upper).value i T) + have ht := Increment.taper_bounds (S := regionᶜ) hr (A.point i T.val) + have hh : |Increment.damped (c*r) r + ((D.base.transverse (by norm_num) D.lower D.upper).value i) + (fun U : D.band => Increment.taper regionᶜ r (A.point i U.val)) T| ≤ 10*r := by + unfold Increment.damped + rw [abs_mul,abs_of_nonneg ht.1] + exact (mul_le_mul hs ht.2 ht.1 (by positivity)).trans_eq (mul_one _) + cases e <;> simpa only [Increment.signedDamped,Bool.false_eq_true,ite_false,ite_true,abs_neg] using hh + simpa only [mul_assoc] using mul_le_mul_of_nonneg_left hb lam.coe_nonneg + +end BData + +namespace BState +variable {κ : ℝ} {lam : ℝ≥0} {Ω : Type*} [MeasurableSpace Ω] {μ : Measure Ω} + (S : BState M κ lam Ω μ) (A : Ambient M) + +/-- A region is exactly the old identifier's inverse image in the full-column +ambient model. No approximation of its boundary is used. -/ +def region (a : Fin (S.count+1)) : Set (M.Point Set.univ A.root) := + {p | S.name p.column p.height=a} + +lemma other_height_not_region (i : Fin (k+1)) (H T : ℝ) + (hne : S.name i H≠S.name i T) : A.point i T ∉ S.region A (S.name i H) := by + exact fun h => hne h.symm + +noncomputable def incrementFields {c r : ℝ} + (hist : Fin (S.count+1) → A.History c) (sign : Fin (S.count+1) → Bool) + (hc : 0 < c) (hcr : c ≤ 4) (hr : 0 < r) + (hcross : ∀ a j, 10*r ≤ c*(hist a).radius j) + (hlam : lam ≤ (1:ℝ≥0)/100) : ∀ a, M.Field (S.chart a).band 5 := + fun a => (S.chart a).auxiliaryField + ((S.chart a).incrementAuxiliary (hist a) r (S.region A a) (sign a) hc hcr hr (hcross a)) lam hlam + +lemma increment_boundary {c r : ℝ} + (hist : Fin (S.count+1) → A.History c) (sign : Fin (S.count+1) → Bool) + (hc : 0 < c) (hcr : c ≤ 4) (hr : 0 < r) + (hcross : ∀ a j, 10*r ≤ c*(hist a).radius j) + (hrec : ∀ a, (S.chart a).Recorded (hist a) hc hcr) + (hk : 0 ≤ κ) (hlam : lam ≤ (1:ℝ≥0)/100) (hsmall : κ*(lam:ℝ)*10 ≤ 1/8) + (i : Fin (k+1)) (H T : ℝ) (hne : S.name i H≠S.name i T) : + |S.newValue (S.incrementFields A hist sign hc hcr hr hcross hlam) i H-S.oldValue i H| ≤ + |H-T|/8 := by + unfold newValue oldValue + rw [← mul_sub,abs_mul,abs_of_nonneg hk] + have hb := (S.chart (S.name i H)).increment_boundary (hist (S.name i H)) r + (S.region A (S.name i H)) (sign (S.name i H)) hc hcr hr (hcross (S.name i H)) + (hrec (S.name i H)) lam hlam i ⟨H,S.height_in i H⟩ T + (S.other_height_not_region A i H T hne) + calc + _ ≤ κ*((lam:ℝ)*10*|H-T|) := mul_le_mul_of_nonneg_left hb hk + _ ≤ |H-T|/8 := by nlinarith [mul_le_mul_of_nonneg_right hsmall (abs_nonneg (H-T))] + +noncomputable def increment {c r : ℝ} + (hist : Fin (S.count+1) → A.History c) (sign : Fin (S.count+1) → Bool) + (hc : 0 < c) (hcr : c ≤ 4) (hr : 0 < r) + (hcross : ∀ a j, 10*r ≤ c*(hist a).radius j) + (hrec : ∀ a, (S.chart a).Recorded (hist a) hc hcr) + (hk : 0 ≤ κ) (hsmall : κ*5 ≤ 1/2) (hlam : lam ≤ (1:ℝ≥0)/100) + (hboundary : κ*(lam:ℝ)*10 ≤ 1/8) : BState M κ lam Ω μ := + S.withAuxiliary + (fun a => (S.chart a).incrementAuxiliary (hist a) r (S.region A a) (sign a) hc hcr hr (hcross a)) + hk hsmall hlam (S.increment_boundary A hist sign hc hcr hr hcross hrec hk hlam hboundary) + +lemma increment_names {c r : ℝ} + (hist : Fin (S.count+1) → A.History c) (sign : Fin (S.count+1) → Bool) + (hc : 0 < c) (hcr : c ≤ 4) (hr : 0 < r) + (hcross : ∀ a j, 10*r ≤ c*(hist a).radius j) + (hrec : ∀ a, (S.chart a).Recorded (hist a) hc hcr) + (hk : 0 ≤ κ) (hsmall : κ*5 ≤ 1/2) (hlam : lam ≤ (1:ℝ≥0)/100) + (hboundary : κ*(lam:ℝ)*10 ≤ 1/8) : + (S.increment A hist sign hc hcr hr hcross hrec hk hsmall hlam hboundary).name=S.name := rfl + +lemma increment_recorded {c r : ℝ} + (hist : Fin (S.count+1) → A.History c) (sign : Fin (S.count+1) → Bool) + (hc : 0 < c) (hcr : c ≤ 4) (hr : 0 < r) + (hcross : ∀ a j, 10*r ≤ c*(hist a).radius j) + (hrec : ∀ a, (S.chart a).Recorded (hist a) hc hcr) + (hk : 0 ≤ κ) (hsmall : κ*5 ≤ 1/2) (hlam : lam ≤ (1:ℝ≥0)/100) + (hboundary : κ*(lam:ℝ)*10 ≤ 1/8) (a : Fin (S.count+1)) : + ((S.increment A hist sign hc hcr hr hcross hrec hk hsmall hlam hboundary).chart a).Recorded + ((S.chart a).incrementHistory (hist a) r (S.region A a) (sign a) hr (hcross a)) hc hcr := + (S.chart a).increment_recorded (hist a) r (S.region A a) (sign a) hc hcr hr (hcross a) + +lemma increment_movement {c r : ℝ} + (hist : Fin (S.count+1) → A.History c) (sign : Fin (S.count+1) → Bool) + (hc : 0 < c) (hcr : c ≤ 4) (hr : 0 < r) + (hcross : ∀ a j, 10*r ≤ c*(hist a).radius j) + (hrec : ∀ a, (S.chart a).Recorded (hist a) hc hcr) + (hk : 0 ≤ κ) (hsmall : κ*5 ≤ 1/2) (hlam : lam ≤ (1:ℝ≥0)/100) + (hboundary : κ*(lam:ℝ)*10 ≤ 1/8) (i : Fin (k+1)) (H : ℝ) : + (∫ ω, |((S.increment A hist sign hc hcr hr hcross hrec hk hsmall hlam hboundary).sets.activity ω).indicator i H- + (S.sets.activity ω).indicator i H| ∂μ) ≤ κ*(lam:ℝ)*10*r := by + change (∫ ω, |(S.fieldActivity (S.incrementFields A hist sign hc hcr hr hcross hlam) + hk hsmall hlam (S.increment_boundary A hist sign hc hcr hr hcross hrec hk hlam hboundary) ω).indicator i H-(S.sets.activity ω).indicator i H| ∂μ) ≤ _ + simp_rw [S.field_indicator,S.old_indicator] + rw [(S.labels (S.name i H)).distance,sub_self,abs_zero,max_eq_right (abs_nonneg _)] + unfold newValue oldValue + rw [← mul_sub,abs_mul,abs_of_nonneg hk] + have hb := (S.chart (S.name i H)).increment_magnitude (hist (S.name i H)) r + (S.region A (S.name i H)) (sign (S.name i H)) hc hcr hr (hcross (S.name i H)) + (hrec (S.name i H)) lam hlam i ⟨H,S.height_in i H⟩ + simpa only [mul_assoc,incrementFields] using mul_le_mul_of_nonneg_left hb hk + +end BState +end PlanarL1.Columns.Model + + + +end + +end OAI diff --git a/lean/OAI/Combinatorics/PlanarL1/BandTrees.lean b/lean/OAI/Combinatorics/PlanarL1/BandTrees.lean new file mode 100644 index 0000000000000000000000000000000000000000..477539e6de6666d5f4049bab79228338e0c7ecae --- /dev/null +++ b/lean/OAI/Combinatorics/PlanarL1/BandTrees.lean @@ -0,0 +1,327 @@ +import OAI.Combinatorics.PlanarL1.Tiling +import OAI.Combinatorics.PlanarL1.Ambient + +namespace OAI + + +section + +namespace PlanarL1.Columns.Model +open scoped BigOperators +attribute [local instance] Classical.propDecidable +variable {n : ℕ} (M : Model n) + +namespace BandTrees +variable (P : Parameters.Interpolation) (lo : ℝ) + +def band : Set ℝ := Set.Icc lo (lo+P.width) +abbrev Component := (M.activeGraph (band P lo)).ConnectedComponent +noncomputable def root (C : Component M P lo) : Fin n := C.nonempty_supp.choose +lemma root_mem (C : Component M P lo) : root M P lo C ∈ C.supp := C.nonempty_supp.choose_spec + +noncomputable def middle : ℝ := lo+P.width/2 +lemma middle_mem : middle P lo ∈ band P lo := by + constructor <;> dsimp [middle] <;> linarith [P.width_pos] + +noncomputable def point (C : Component M P lo) (i : C.supp) : + M.Point (band P lo) (root M P lo C) := + ⟨i.val,middle P lo,middle_mem P lo,C.reachable_of_mem_supp (root_mem M P lo C) i.property⟩ +noncomputable def base (C : Component M P lo) : M.Point (band P lo) (root M P lo C) := + point M P lo C ⟨root M P lo C,root_mem M P lo C⟩ +noncomputable def tree (C : Component M P lo) : + Point.RadialTree (M := M) (J := band P lo) (root := root M P lo C) where + base := base M P lo C + δ := P.error/8 + a := P.width + ζ := P.zeta + delta_pos := div_pos P.error_pos (by norm_num) + width_pos := P.width_pos + zeta_pos := P.zeta_pos + zeta_lt_one := P.zeta_lt + width_bound := P.width_bound + half_width := by + intro T hT + change |lo+P.width/2-T|≤P.width/2 + obtain ⟨h1,h2⟩ := hT + exact abs_le.mpr ⟨by linarith,by linarith⟩ + closed_band := isClosed_Icc + interval_band := Set.ordConnected_Icc + +lemma reachable_mem (C : Component M P lo) {i : Fin n} + (hi : (M.activeGraph (band P lo)).Reachable (root M P lo C) i) : i ∈ C.supp := by + rw [SimpleGraph.ConnectedComponent.mem_supp_iff] + exact (SimpleGraph.ConnectedComponent.sound hi).symm.trans + ((SimpleGraph.ConnectedComponent.mem_supp_iff C _).mp (root_mem M P lo C)) + +/-- Only the radial layers meeting a column occur. No infinite layer family +or arbitrary cut-off is added to the finite random step. -/ +noncomputable def levels (C : Component M P lo) (phase width : ℝ) : Finset ℤ := + Finset.univ.image (fun i : C.supp => Tiling.index width phase (dist (base M P lo C) (point M P lo C i))) + +lemma level_of_mem (C : Component M P lo) {phase width : ℝ} (hw : 0 < width) (k : ℤ) + {i : Fin n} (hi : i ∈ (base M P lo C).layer (middle P lo) (middle_mem P lo) + (phase+(k:ℝ)*width) width) : k ∈ levels M P lo C phase width := by + obtain ⟨hr,hl,hu⟩ := hi + let u : C.supp := ⟨i,reachable_mem M P lo C hr⟩ + have hind : Tiling.index width phase (dist (base M P lo C) (point M P lo C u))=k := by + apply Int.floor_eq_iff.mpr + constructor + · apply (le_div_iff₀ hw).mpr + change phase+(k:ℝ)*width≤dist (base M P lo C) (point M P lo C u) at hl + linarith + · apply (div_lt_iff₀ hw).mpr + change dist (base M P lo C) (point M P lo C u) exact ⟨.nil i,rfl⟩ + | @cons i u j H hH hs p ih => + have htri := abs_sub_le H a c + rw [abs_sub_comm H a] at htri + have htail : |H-c|+p.length H b≤t := by + change |a-c|+(|a-H|+p.length H b)≤t at hp + linarith + have hh : H ∈ J := hJ H (by linarith [p.length_nonneg H b]) + obtain ⟨q,hq⟩ := ih H htail + exact ⟨.cons H hh hs q,by simp only [length,hq]⟩ +end Path + +namespace Point +lemma dist_coordinates (x y : M.Point J r) (x' y' : M.Point J s) + (hx : x.column=x'.column) (hX : x.height=x'.height) + (hy : y.column=y'.column) (hY : y.height=y'.height) : dist x y=dist x' y' := by + change (⨅ p : M.Path J x.column y.column, p.length x.height y.height)= + (⨅ p : M.Path J x'.column y'.column, p.length x'.height y'.height) + rw [hx,hX,hy,hY] + +/-- On a ball farther from the band ends than its radius, unrestricted shortest +paths give exact intrinsic distances from its center. -/ +lemma local_point (x y : M.Point I r) (x' : M.Point J s) + (hx : x'.column=x.column) (hX : x'.height=x.height) + (hI : IsClosed I) (hJI : J ⊆ I) {t : ℝ} + (hJ : ∀ H, |H-x.height|≤t → H ∈ J) (hxy : dist x y≤t) : + ∃ y' : M.Point J s, y'.column=y.column ∧ y'.height=y.height ∧ dist x' y'=dist x y := by + obtain ⟨p,_,hp⟩ := x.exists_shortest hI y + obtain ⟨q,hq⟩ := p.restrict_of_length x.height y.height x.height t hJ (by simpa [hp] using hxy) + have hyJ : y.height ∈ J := hJ _ (by + rw [abs_sub_comm] + exact (x.height_change_le y).trans hxy) + let yy : M.Point J s := ⟨y.column,y.height,hyJ,x'.reachable.trans (hx ▸ q.word.reachable)⟩ + refine ⟨yy,rfl,rfl,le_antisymm ?_ ?_⟩ + · have hh := x'.distance_le yy (hx ▸ q) + change dist x' yy ≤ (hx ▸ q).length x'.height yy.height at hh + have he : (hx ▸ q).length x'.height yy.height=q.length x.height y.height := by + obtain ⟨xc,xh,xi,xr⟩ := x' + dsimp only at hx hX + subst xc + subst xh + rfl + rw [he,hq,hp] at hh + exact hh + · have h := x'.dist_widen_le yy hJI + have he := dist_coordinates (x'.widen hJI) (yy.widen hJI) x y hx hX rfl rfl + exact he ▸ h +end Point +end PlanarL1.Columns.Model + +end + + +section + +namespace PlanarL1.Columns.Model +open MeasureTheory +open scoped NNReal +attribute [local instance] Classical.propDecidable +variable {k : ℕ} {M : Model (k+1)} + +namespace Field +lemma constant_ordered {I : Set ℝ} (c : ℝ) (a b : Fin (k+1)) : + (constant M I c).OrderedFrom a b := by + exact ⟨fun _ _ => le_rfl,fun _ _ _ _ _ => le_rfl,fun _ _ _ _ _ => le_rfl⟩ +end Field + +namespace OrdinaryData +/-- The support required by a secondary group is constructed from the actual +old point source. The comparison outside that source's component is never used. -/ +lemma support_at (D : OrdinaryData M) (i : Fin (k+1)) (H : ℝ) (hi : D.Contains i H) : + ∃ (F : M.Field D.band 1) (a b : Fin (k+1)), F.OrderedFrom a b ∧ + F.value i ⟨H,hi.1⟩=D.comparison.value i ⟨H,hi.1⟩ ∧ + ∀ (j : Fin (k+1)) (T : ℝ) (hj : D.Contains j T), + F.value j ⟨T,hj.1⟩≤D.comparison.value j ⟨T,hj.1⟩ := by + by_cases ho : D.origin=none + · + refine ⟨Field.constant M D.band 0,0,0,Field.constant_ordered 0 0 0,?_,?_⟩ + · simp only [comparison,ho] + · intro j T hj + simp only [comparison,ho,Field.constant,le_refl] + · obtain ⟨o,ho⟩ := Option.ne_none_iff_exists'.mp ho + let w : M.Point D.band o.1 := ⟨i,H,hi.1,hi.2 o.1 o.2 ho⟩ + obtain ⟨F,hord,_,_,hw,hF⟩ := Point.exists_ordered_support D.closed o.2 w + have hv (j : Fin (k+1)) (T : ℝ) (hj : D.Contains j T) : + D.comparison.value j ⟨T,hj.1⟩= + dist o.2 (⟨j,T,hj.1,hj.2 o.1 o.2 ho⟩ : M.Point D.band o.1) := by + simp only [comparison,ho] + exact o.2.radialField_eval (⟨j,T,hj.1,hj.2 o.1 o.2 ho⟩ : M.Point D.band o.1) + refine ⟨F,o.2.column,w.column,hord,?_,?_⟩ + · rw [hv i H hi] + exact hw + · intro j T hj + rw [hv j T hj] + exact hF (⟨j,T,hj.1,hj.2 o.1 o.2 ho⟩ : M.Point D.band o.1) +end OrdinaryData + +namespace Ambient +variable (A : Ambient M) + +lemma coordinate_point (x : M.Point Set.univ A.root) : A.point x.column x.height=x := by + cases x + rfl + +lemma point_dist_same (i : Fin (k+1)) (H T : ℝ) : + dist (A.point i H) (A.point i T)=|H-T| := A.point_dist i H T + +/-- A chart identifier is common on the actual unrestricted closed ball. +The test includes every representative, not merely the original vertices. -/ +def Common {ι : Type*} (name : Fin (k+1) → ℝ → ι) + (x : M.Point Set.univ A.root) (r : ℝ) (a : ι) : Prop := + ∀ y : M.Point Set.univ A.root, dist x y≤r → name y.column y.height=a + +lemma Common.mono {ι : Type*} {name : Fin (k+1) → ℝ → ι} + {x : M.Point Set.univ A.root} {r t : ℝ} {a : ι} + (h : A.Common name x r a) (ht : t≤r) : A.Common name x t a := + fun y hy => h y (hy.trans ht) + +lemma Common.center {ι : Type*} {name : Fin (k+1) → ℝ → ι} + {x : M.Point Set.univ A.root} {r : ℝ} {a : ι} + (h : A.Common name x r a) (hr : 0≤r) : name x.column x.height=a := by + exact h x (by simpa using hr) + +lemma Common.shift {ι : Type*} {name : Fin (k+1) → ℝ → ι} + {x y : M.Point Set.univ A.root} {r t : ℝ} {a : ι} + (h : A.Common name x r a) (ht : dist x y+t≤r) : A.Common name y t a := by + intro z hz + exact h z ((dist_triangle x y z).trans (by linarith)) + +end Ambient + +namespace OrdinaryState +variable {κ : ℝ} {Ω : Type*} [MeasurableSpace Ω] {μ : Measure Ω} +variable (A : Ambient M) (S : OrdinaryState M κ Ω μ) + +/-- Band containment follows from a common geometric ball and ordinary +vertical segments, rather than being assumed in a secondary update. -/ +lemma ball_band {x : M.Point Set.univ A.root} {a : Fin (S.count+1)} {r : ℝ} + (h : A.Common S.name x r a) {J : Set ℝ} + (hJ : ∀ H ∈ J, |x.height-H|≤r) : J ⊆ (S.chart a).band := by + intro H hH + have hh := h (A.point x.column H) (by + conv_lhs => lhs; rw [← A.coordinate_point x] + rw [A.point_dist] + exact hJ H hH) + change S.name x.column H = a at hh + simpa only [hh] using S.height_in x.column H +end OrdinaryState + +namespace BState +variable {κ : ℝ} {lam : ℝ≥0} {Ω : Type*} [MeasurableSpace Ω] {μ : Measure Ω} +variable (A : Ambient M) (S : BState M κ lam Ω μ) + +lemma height_named (i : Fin (k+1)) (H : ℝ) (a : Fin (S.count+1)) + (ha : S.name i H=a) : H ∈ (S.chart a).band := by + subst a + exact S.height_in i H + +lemma uses_named (i : Fin (k+1)) (H : ℝ) (a : Fin (S.count+1)) + (ha : S.name i H=a) : (S.chart a).Uses i := by + subst a + exact S.component_in i H + +lemma ball_band {x : M.Point Set.univ A.root} {a : Fin (S.count+1)} {r : ℝ} + (h : A.Common S.name x r a) {J : Set ℝ} + (hJ : ∀ H ∈ J, |x.height-H|≤r) : J ⊆ (S.chart a).band := by + intro H hH + have hh := h (A.point x.column H) (by + conv_lhs => lhs; rw [← A.coordinate_point x] + rw [A.point_dist] + exact hJ H hH) + exact S.height_named x.column H a hh +end BState +end PlanarL1.Columns.Model + +end + +end OAI diff --git a/lean/OAI/Combinatorics/PlanarL1/Bands.lean b/lean/OAI/Combinatorics/PlanarL1/Bands.lean new file mode 100644 index 0000000000000000000000000000000000000000..c630b82c5a927ba5ed07361405585d2a2640bebe --- /dev/null +++ b/lean/OAI/Combinatorics/PlanarL1/Bands.lean @@ -0,0 +1,868 @@ +import OAI.Combinatorics.PlanarL1.SeedPacking + +namespace OAI + +section + +namespace PlanarL1.Columns + +lemma consecutive_rotate {n : ℕ} (i j : Fin (n+1)) : + Consecutive (finRotate (n+1) i) (finRotate (n+1) j) ↔ Consecutive i j := by + by_cases hi : i = Fin.last n <;> by_cases hj : j = Fin.last n + · subst i; subst j + simp [Consecutive, eq_comm] + · subst i + rw [finRotate_last] + simp only [Consecutive, Fin.val_zero, Fin.val_last, coe_finRotate_of_ne_last hj] + have := j.isLt + have hjv : j.val ≠ n := fun h => hj (Fin.ext h) + clear hj + try simp only [true_and, and_true] + omega + · subst j + rw [finRotate_last] + simp only [Consecutive, Fin.val_zero, Fin.val_last, coe_finRotate_of_ne_last hi] + have := i.isLt + have hiv : i.val ≠ n := fun h => hi (Fin.ext h) + clear hi + try simp only [true_and, and_true] + omega + · simp only [Consecutive, coe_finRotate_of_ne_last hi, coe_finRotate_of_ne_last hj] + have := i.isLt + have := j.isLt + have hiv : i.val ≠ n := fun h => hi (Fin.ext h) + clear hi + have hjv : j.val ≠ n := fun h => hj (Fin.ext h) + clear hj + try simp only [true_and, and_true] + omega + + +lemma consecutive_iterate {n : ℕ} (k : ℕ) (i j : Fin (n+1)) : + Consecutive ((finRotate (n+1))^[k] i) ((finRotate (n+1))^[k] j) ↔ + Consecutive i j := by + induction k generalizing i j with + | zero => rfl + | succ k ih => + rw [Function.iterate_succ_apply, Function.iterate_succ_apply, ih, consecutive_rotate] + +lemma consecutive_cycle {n : ℕ} (a i j : Fin (n+1)) : + Consecutive (finCycle a i) (finCycle a j) ↔ Consecutive i j := by + rw [finCycle_eq_finRotate_iterate] + exact consecutive_iterate a.val i j + +namespace Model + +/-- Relabelling columns does not change geometry. The two order conditions +are explicit, so the construction never assumes invariance under an arbitrary +permutation of the circular order. -/ +def relabel {n : ℕ} (M : Model n) (e : Equiv.Perm (Fin n)) + (hnc : ColumnOrder.Noncrossing (M.link.comap e)) + (hcon : ∀ i j, Consecutive (e i) (e j) ↔ Consecutive i j) : Model n where + link := M.link.comap e + heights i j := M.heights (e i) (e j) + symm i j := M.symm (e i) (e j) + permitted i j H h := M.permitted (e i) (e j) H h + compact i j := M.compact (e i) (e j) + noncrossing := hnc + terminal i j h hn := by + obtain ⟨H,hH,ht⟩ := M.terminal (e i) (e j) h (fun hc => hn ((hcon i j).mp hc)) + exact ⟨H,hH,fun k T h => ht (e k) T h⟩ + +variable {n : ℕ} {M : Model n} {e : Equiv.Perm (Fin n)} + {hnc : ColumnOrder.Noncrossing (M.link.comap e)} + {hcon : ∀ i j, Consecutive (e i) (e j) ↔ Consecutive i j} + {J : Set ℝ} {root i j : Fin n} + +/-- Undo a column relabelling on actual finite switching paths. -/ +def Path.unlabel : {i j : Fin n} → (M.relabel e hnc hcon).Path J i j → + M.Path J (e i) (e j) + | _, _, .nil _ => .nil _ + | _, _, .cons H hH hs p => .cons H hH hs p.unlabel + +@[simp] lemma Path.length_unlabel (p : (M.relabel e hnc hcon).Path J i j) (s t : ℝ) : + p.unlabel.length s t = p.length s t := by + induction p generalizing s with + | nil => rfl + | cons H hH hs p ih => simp only [Path.unlabel, Path.length, ih] + +def Path.label : {i j : Fin n} → M.Path J i j → + (M.relabel e hnc hcon).Path J (e.symm i) (e.symm j) + | _, _, .nil _ => .nil _ + | _, _, .cons H hH hs p => .cons H hH (by simpa only [relabel, e.apply_symm_apply] using hs) + p.label + +@[simp] lemma Path.length_label (p : M.Path J i j) (s t : ℝ) : + (p.label (hnc := hnc) (hcon := hcon)).length s t = p.length s t := by + induction p generalizing s with + | nil => rfl + | cons H hH hs p ih => simp only [Path.label, Path.length, ih] + +/-- The point map keeps the height and moves only the column name. -/ +def Point.unlabel (x : (M.relabel e hnc hcon).Point J root) : M.Point J (e root) where + column := e x.column + height := x.height + inBand := x.inBand + reachable := by + obtain ⟨p⟩ := x.reachable + obtain ⟨q,hq⟩ := Path.exists_word p + exact ⟨q.unlabel.word⟩ + +def Path.cast {i j k l : Fin n} (p : M.Path J i j) (h : i = k) (g : j = l) : + M.Path J k l := h ▸ g ▸ p + +@[simp] lemma Path.length_cast {i j k l : Fin n} (p : M.Path J i j) + (h : i = k) (g : j = l) (s t : ℝ) : (p.cast h g).length s t = p.length s t := by + subst k; subst l; rfl + +lemma Point.dist_unlabel (x y : (M.relabel e hnc hcon).Point J root) : + dist x.unlabel y.unlabel = dist x y := by + apply le_antisymm + · change x.unlabel.distance y.unlabel ≤ _ + have := x.paths_nonempty y + apply le_ciInf + intro p + exact (x.unlabel.distance_le y.unlabel p.unlabel).trans_eq (p.length_unlabel _ _) + · change x.distance y ≤ x.unlabel.distance y.unlabel + have := x.unlabel.paths_nonempty y.unlabel + apply le_ciInf + intro p + let q := p.label (hnc := hnc) (hcon := hcon) + have he₁ : e.symm x.unlabel.column = x.column := e.symm_apply_apply _ + have he₂ : e.symm y.unlabel.column = y.column := e.symm_apply_apply _ + have hd := x.distance_le y (q.cast he₁ he₂) + exact hd.trans_eq ((Path.length_cast q he₁ he₂ x.height y.height).trans + (Path.length_label p x.height y.height)) + +end Model +end PlanarL1.Columns + +namespace PlanarL1.Columns.Model + +variable {n : ℕ} {M : Model n} {I J : Set ℝ} {root : Fin n} + +/-- Inclusion of intrinsic components into a larger band. No equality of the +intrinsic metrics is asserted. -/ +def Point.widen (x : M.Point J root) (hJI : J ⊆ I) : M.Point I root where + column := x.column + height := x.height + inBand := hJI x.inBand + reachable := by + obtain ⟨p⟩ := x.reachable + obtain ⟨q,_⟩ := Path.exists_word p + exact ⟨(q.widen hJI).word⟩ + +lemma Point.dist_widen_le (x y : M.Point J root) (hJI : J ⊆ I) : + dist (x.widen hJI) (y.widen hJI) ≤ dist x y := by + change (x.widen hJI).distance (y.widen hJI) ≤ x.distance y + have := x.paths_nonempty y + apply le_ciInf + intro p + exact ((x.widen hJI).distance_le (y.widen hJI) (p.widen hJI)).trans_eq (p.length_widen _ _ _) + +namespace Path + +/-- The vertical connection to a tip uses only the thin band, not the much +wider old chart band where scalar distance fields are defined. -/ +lemma tip_connection {i l b : Fin n} {s H a : ℝ} + (hsJ : s ∈ J) (hHJ : H ∈ J) (hs : H ∈ M.heights l b) + (hw : ∀ s ∈ J, ∀ t ∈ J, |s-t| ≤ a) (hi : i = l ∨ i = b) : + ∃ p : M.Path J i l, p.length s H ≤ a := by + rcases hi with rfl | rfl + · exact ⟨.nil _,hw s hsJ H hHJ⟩ + · refine ⟨.cons H hHJ (by rwa [M.symm]) (.nil _),?_⟩ + simpa only [length,sub_self,abs_zero,add_zero] using hw s hsJ H hHJ + +end Path + +namespace Field + +/-- The source descent lives in the BROAD CURRENT band J, whereas the old +comparison field and witnesses live in the OLD chart I, possibly in different +J-components. The attaining condition refers to J, not to the larger band. -/ +structure BandDescent (F : M.Field I 1) (J : Set ℝ) (x : M.Point I root) (ε : ℝ) where + start_in : x.height ∈ J + target : M.Point I root + target_in : target.height ∈ J + path : M.Path J x.column target.column + shortest : ∀ p : M.Path J x.column target.column, + path.length x.height target.height ≤ p.length x.height target.height + lower : (1:ℝ)/100000 ≤ path.length x.height target.height + upper : path.length x.height target.height ≤ (1:ℝ)/50 + drop : F.eval target ≤ F.eval x-path.length x.height target.height+ε + +namespace BandDescent + +variable {F : M.Field I 1} {x : M.Point I root} {ε : ℝ} + +lemma column_prefix (D : F.BandDescent J x ε) (hJI : J ⊆ I) + {v : Fin n} (hv : v ∈ D.path.word.support) : + ∃ z : M.Point I root, z.column = v ∧ z.height ∈ J ∧ + ∃ q : M.Path J x.column z.column, + q.length x.height z.height ≤ (1:ℝ)/50 ∧ + F.eval z ≤ F.eval x-q.length x.height z.height+ε := by + obtain ⟨T,hT,q,r,hqr⟩ := D.path.split_at_column D.start_in D.target_in hv + let z : M.Point I root := ⟨v,T,hJI hT,x.reachable.trans (q.widen hJI).word.reachable⟩ + have hf := F.path_bound (r.widen hJI) ⟨T,hJI hT⟩ ⟨D.target.height,D.target.inBand⟩ + rw [NNReal.coe_one,one_mul,Path.length_widen] at hf + have hzval : F.eval z-F.eval D.target ≤ r.length T D.target.height := + (le_abs_self _).trans hf + have hn := r.length_nonneg T D.target.height + have hu := D.upper + have hd := D.drop + refine ⟨z,rfl,hT,q,?_,?_⟩ + all_goals dsimp only [z]; linarith + +/-- Actual bounded-length path to a separating tip, even when the witness's +broad-band component was not known to be the seed's component beforehand. -/ +lemma path_to_tip (D : F.BandDescent J x ε) (hJI : J ⊆ I) + (e : M.Point I root) {b : Fin n} {a : ℝ} + (heJ : e.height ∈ J) (hs : e.height ∈ M.heights e.column b) + (hw : ∀ s ∈ J, ∀ t ∈ J, |s-t| ≤ a) + (hx : e.column < x.column ∧ x.column < b) + (hz : D.target.column < e.column ∨ b < D.target.column) : + ∃ p : M.Path J x.column e.column, p.length x.height e.height ≤ (1:ℝ)/50+a := by + have hadj : (M.activeGraph J).Adj e.column b := ⟨e.height,heJ,hs⟩ + have hv := ColumnOrder.chord_separation (M.active_noncrossing J) hadj D.path.word hx hz + have hcase {v : Fin n} (hv : v ∈ D.path.word.support) (he : v = e.column ∨ v = b) : + ∃ p : M.Path J x.column e.column, p.length x.height e.height ≤ (1:ℝ)/50+a := by + obtain ⟨z,hz,hzJ,q,hq,_⟩ := D.column_prefix hJI hv + obtain ⟨r,hr⟩ := Path.tip_connection hzJ heJ hs hw (hz ▸ he) + exact ⟨q.append r,(q.length_append_le r x.height z.height e.height).trans (add_le_add hq hr)⟩ + exact hv.elim (fun h => hcase h (Or.inl rfl)) (fun h => hcase h (Or.inr rfl)) + +/-- The fine near-tip bound is witnessed by a path in the CURRENT broad band. +Only scalar evaluation, not path geometry, uses the old chart. -/ +lemma short_path_to_tip (D : F.BandDescent J x ε) (hJI : J ⊆ I) + (e : M.Point I root) {b : Fin n} {a j : ℝ} + (heJ : e.height ∈ J) (hs : e.height ∈ M.heights e.column b) + (hw : ∀ s ∈ J, ∀ t ∈ J, |s-t| ≤ a) + (hx : e.column < x.column ∧ x.column < b) + (hz : D.target.column < e.column ∨ b < D.target.column) + (hlow : F.eval x-j ≤ F.eval e) : + ∃ p : M.Path J x.column e.column, p.length x.height e.height ≤ j+ε+2*a := by + have hadj : (M.activeGraph J).Adj e.column b := ⟨e.height,heJ,hs⟩ + have hv := ColumnOrder.chord_separation (M.active_noncrossing J) hadj D.path.word hx hz + have hcase {v : Fin n} (hv : v ∈ D.path.word.support) (he : v = e.column ∨ v = b) : + ∃ p : M.Path J x.column e.column, p.length x.height e.height ≤ j+ε+2*a := by + obtain ⟨z,hz,hzJ,q,_,hdrop⟩ := D.column_prefix hJI hv + obtain ⟨r,hr⟩ := Path.tip_connection hzJ heJ hs hw (hz ▸ he) + have hf := F.path_bound (r.widen hJI) ⟨z.height,z.inBand⟩ ⟨e.height,e.inBand⟩ + rw [NNReal.coe_one,one_mul,Path.length_widen] at hf + have hlo : F.eval e-F.eval z ≤ a := by + have hn := (neg_le_abs (F.eval z-F.eval e)).trans (hf.trans hr) + simpa only [neg_sub] using hn + refine ⟨q.append r,?_⟩ + have hb := q.length_append_le r x.height z.height e.height + linarith + exact hv.elim (fun h => hcase h (Or.inl rfl)) (fun h => hcase h (Or.inr rfl)) + +end BandDescent +end Field +end PlanarL1.Columns.Model + +namespace PlanarL1.Columns.Model.Point + +variable {n : ℕ} {M : Model n} {I J : Set ℝ} {root : Fin n} + +/-- Actual distance field of an old chart. Outside its component we choose +zero only to make a whole-band scalar function; radial sublevels retain the +source's +infinity convention and never include those columns. -/ +noncomputable def radialValue (o : M.Point I root) (i : Fin n) (H : I) : ℝ := by + classical + exact if hi : (M.activeGraph I).Reachable root i then + dist o (⟨i,H.val,H.property,hi⟩ : M.Point I root) else 0 + +lemma radialValue_vertical (o : M.Point I root) (i : Fin n) : + LipschitzWith 1 (o.radialValue i) := by + by_cases hi : (M.activeGraph I).Reachable root i + · apply LipschitzWith.of_dist_le_mul + intro H T + simp only [radialValue,dite_eq_left hi,NNReal.coe_one,one_mul] + exact (dist_dist_dist_le_right o + (⟨i,H.val,H.property,hi⟩ : M.Point I root) + (⟨i,T.val,T.property,hi⟩ : M.Point I root)).trans_eq + (Point.dist_same_column _ _ rfl) + · apply LipschitzWith.of_dist_le_mul + intro H T + simp only [radialValue,dite_eq_right hi,dist_self,NNReal.coe_one,one_mul] + exact dist_nonneg + +lemma radialValue_switch (o : M.Point I root) (i j : Fin n) (H : I) + (hs : H.val ∈ M.heights i j) : o.radialValue i H = o.radialValue j H := by + have ha : (M.activeGraph I).Adj i j := ⟨H.val,H.property,hs⟩ + by_cases hi : (M.activeGraph I).Reachable root i + · have hj := hi.trans ha.reachable + simp only [radialValue,dite_eq_left hi,dite_eq_left hj] + let x : M.Point I root := ⟨i,H.val,H.property,hi⟩ + let y : M.Point I root := ⟨j,H.val,H.property,hj⟩ + have hz : dist x y = 0 := by + apply le_antisymm _ dist_nonneg + simpa only [x,y,sub_self,abs_zero,add_zero] using x.dist_le_switch y H.property hs + exact PseudoMetricSpace.dist_eq_of_dist_zero o hz + · have hj : ¬(M.activeGraph I).Reachable root j := by + intro hj + exact hi (hj.trans ha.symm.reachable) + simp only [radialValue,dite_eq_right hi,dite_eq_right hj] + +noncomputable def radialField (o : M.Point I root) : M.Field I 1 where + value := o.radialValue + vertical := o.radialValue_vertical + switch := o.radialValue_switch + +@[simp] lemma radialField_eval (o x : M.Point I root) : o.radialField.eval x = dist o x := by + simp only [Field.eval,radialField,radialValue,dite_eq_left x.reachable] + +lemma sublevel_link_preconnected (hI : IsClosed I) (o : M.Point I root) + (H : ℝ) (hH : H ∈ I) (t : ℝ) : + (M.link.induce (o.sublevel H hH t)).Preconnected := by + intro x y + obtain ⟨p⟩ := o.sublevel_preconnected hI H hH t x y + let f : (M.activeGraph I).induce (o.sublevel H hH t) →g + M.link.induce (o.sublevel H hH t) := + { toFun := id, map_rel' := fun {_ _} h => M.active_subgraph I h } + exact ⟨p.map f⟩ + +/-- The actual target of each almost-descending broad-band path is a member +of the old-distance low sublevel. Width is used only for the broad band J. -/ +lemma descent_target_low (o w x : M.Point I root) (hJI : J ⊆ I) + {ε a B δ : ℝ} (D : o.radialField.BandDescent J x ε) {H : ℝ} (hHJ : H ∈ J) + (hw : ∀ s ∈ J, ∀ t ∈ J, |s-t| ≤ a) + (hclose : dist o x ≤ dist o w+B) + (hsmall : B+ε+a < (1:ℝ)/100000-δ) : + D.target.column ∈ o.sublevel H (hJI hHJ) (dist o w-δ) := by + rw [o.mem_sublevel_iff D.target H (hJI hHJ)] + have hd := D.drop + rw [radialField_eval,radialField_eval] at hd + have hv := D.target.dist_withHeight H (hJI hHJ) + have hv' : dist D.target (D.target.withHeight H (hJI hHJ)) ≤ a := by + rw [hv] + exact hw _ D.target_in _ hHJ + have ht := dist_triangle o D.target (D.target.withHeight H (hJI hHJ)) + have hl := D.lower + linarith + +/-- The same old-distance sublevel misses EVERY visited column of a short +center path. This establishes the manuscript's avoidance condition rather +than postulating it of a chosen set. -/ +lemma short_path_avoids_low (o w c : M.Point I root) (hJI : J ⊆ I) + {a A δ : ℝ} {H : ℝ} (hHJ : H ∈ J) + (hw : ∀ s ∈ J, ∀ t ∈ J, |s-t| ≤ a) + (hcJ : c.height ∈ J) (hcw : dist c w ≤ A) (hsmall : 2*A+a < δ) + {v : Fin n} (p : M.Path J c.column v) {T : ℝ} + (hp : p.length c.height T ≤ A) : + ∀ k ∈ p.word.support, k ∉ o.sublevel H (hJI hHJ) (dist o w-δ) := by + intro k hk hlow + obtain ⟨U,hU,hu⟩ := p.trace_on_column hcJ hk + obtain ⟨z,hzk,hzU,hcz⟩ := c.point_on_trace hJI p hU hu + have hl : dist o (z.withHeight H (hJI hHJ)) ≤ dist o w-δ := by + exact (o.mem_sublevel_iff z H (hJI hHJ) _).mp (hzk.symm ▸ hlow) + have hz : dist z (z.withHeight H (hJI hHJ)) ≤ a := by + rw [z.dist_withHeight,hzU] + exact hw _ hU _ hHJ + have hzw : dist w z ≤ 2*A := by + have ht := dist_triangle w c z + rw [dist_comm w c] at ht + linarith + have ht₁ := dist_triangle o (z.withHeight H (hJI hHJ)) z + have ht₂ := dist_triangle o z w + rw [dist_comm (z.withHeight H (hJI hHJ)) z] at ht₁ + rw [dist_comm z w] at ht₂ + linarith + +end PlanarL1.Columns.Model.Point + +namespace PlanarL1.Columns.Model.Field + +variable {n : ℕ} {M : Model n} {I J K : Set ℝ} {root : Fin n} + +lemma BandDescent.partner_outside_tip {F : M.Field I 1} {ε a A : ℝ} + (x y e : M.Point I root) (D : F.BandDescent K y ε) (hKI : K ⊆ I) + {b : Fin n} (heK : e.height ∈ K) (hs : e.height ∈ M.heights e.column b) + (hw : ∀ s ∈ K, ∀ t ∈ K, |s-t| ≤ a) + (hz : D.target.column < e.column ∨ b < D.target.column) + (hxy : 1 ≤ dist x y) (hxe : dist x e ≤ A) (hsmall : (1:ℝ)/50+a+A < 1) : + y.column < e.column ∨ b < y.column := by + by_contra h + have hle : e.column ≤ y.column ∧ y.column ≤ b := by push Not at h; exact h + have hd : ∃ p : M.Path K y.column e.column, + p.length y.height e.height ≤ (1:ℝ)/50+a := by + by_cases hy : y.column = e.column + · obtain ⟨p,hp⟩ := Path.tip_connection D.start_in heK hs hw (Or.inl hy) + exact ⟨p,by linarith⟩ + by_cases hy' : y.column = b + · obtain ⟨p,hp⟩ := Path.tip_connection D.start_in heK hs hw (Or.inr hy') + exact ⟨p,by linarith⟩ + exact D.path_to_tip hKI e heK hs hw + ⟨lt_of_le_of_ne hle.1 (Ne.symm hy),lt_of_le_of_ne hle.2 hy'⟩ hz + obtain ⟨p,hp⟩ := hd + have hd := y.distance_le e (p.widen hKI) + rw [Path.length_widen] at hd + change dist y e ≤ _ at hd + have ht := dist_triangle x e y + rw [dist_comm e y] at ht + linarith + +/-- The skipped-seed estimate keeps the old chart, broad current band and +narrow center-path band distinct. Its conclusion contains an ACTUAL broad-band +path to the trace, not just a distance in the larger old chart. -/ +lemma skipped_seed_broad_path (F : M.Field I 1) + {S : Set (Fin n)} (hS : (M.link.induce S).Preconnected) + {cut : Fin n} (hcut : cut ∈ S) (hmin : ∀ v, cut ≤ v) + (hJK : J ⊆ K) (hKI : K ⊆ I) {a A j ε : ℝ} + (hw : ∀ s ∈ K, ∀ t ∈ K, |s-t| ≤ a) + (c x y : M.Point I root) (Dx : F.BandDescent K x ε) (Dy : F.BandDescent K y ε) + (hxS : Dx.target.column ∈ S) (hyS : Dy.target.column ∈ S) + (hxy : 1 ≤ dist x y) (hcx : dist c x ≤ A) (hA : 2*A ≤ 1) + (hsmall : (1:ℝ)/50+a+2*A < 1) (hretain : F.NoLowTip x y J j) + {v : Fin n} (p : M.Path J c.column v) {H : ℝ} (hp : p.length c.height H ≤ A) + (havoid : ∀ k ∈ p.word.support, k ∉ S) (hskip : ColumnOrder.JumpsAcross x.column p.word) : + ∃ e : M.Point I root, e.height ∈ J ∧ (e.column,e.height) ∈ p.trace c.height H ∧ + ∃ q : M.Path K x.column e.column, q.length x.height e.height ≤ j+ε+2*a := by + obtain ⟨d,hd,hcross⟩ := hskip + obtain ⟨T,hT,hs,ht₁,ht₂⟩ := p.dart_on_trace c.height H d hd + have hcase {l r : Fin n} (hlr : l < x.column ∧ x.column < r) + (hs : T ∈ M.heights l r) (htl : (l,T) ∈ p.trace c.height H) + (htr : (r,T) ∈ p.trace c.height H) : + ∃ e : M.Point I root, e.height ∈ J ∧ (e.column,e.height) ∈ p.trace c.height H ∧ + ∃ q : M.Path K x.column e.column, q.length x.height e.height ≤ j+ε+2*a := by + have hl : l ∉ S := havoid l (p.trace_column htl) + have hr : r ∉ S := havoid r (p.trace_column htr) + have hcl : cut < l := lt_of_le_of_ne (hmin l) (fun h => hl (h ▸ hcut)) + have hgap := ColumnOrder.gap_of_chord M.noncrossing hS + (M.permitted l r T hs) hl hr hcut (Or.inl hcl) + obtain ⟨e,hecol,heheight,helen⟩ := c.point_on_trace (hJK.trans hKI) p hT htl + have hetrace : (e.column,e.height) ∈ p.trace c.height H := by rwa [hecol,heheight] + have hxe : dist x e ≤ 2*A := by + have ht := dist_triangle x c e + rw [dist_comm x c] at ht + linarith + have hes : e.height ∈ M.heights e.column r := by rwa [hecol,heheight] + have heJ : e.height ∈ J := heheight ▸ hT + have hyp : y.column < e.column ∨ r < y.column := Dy.partner_outside_tip x y e hKI + (hJK heJ) hes hw (by simpa only [hecol] using hgap _ hyS) hxy hxe hsmall + have hnc : ¬ Consecutive e.column r := by + rw [hecol] + exact not_consecutive_of_between hlr (Or.inl hcl) + have hlow := (hretain e r heJ hes hnc + (Or.inl ⟨by simpa only [hecol] using hlr.1,hlr.2,hyp⟩) (Or.inl (hxe.trans hA))).1 + refine ⟨e,heJ,hetrace,Dx.short_path_to_tip hKI e (hJK heJ) hes hw ?_ ?_ hlow⟩ + · simpa only [hecol] using hlr + · simpa only [hecol] using hgap _ hxS + rcases hcross with hc | hc + · exact hcase hc hs ht₁ ht₂ + · exact hcase hc (by rwa [M.symm]) ht₂ ht₁ + +theorem restricted_broad_packing {W : Type*} [Fintype W] + (F : M.Field I 1) + {S : Set (Fin n)} (hS : (M.link.induce S).Preconnected) + {cut : Fin n} (hcut : cut ∈ S) (hmin : ∀ v, cut ≤ v) + (hJK : J ⊆ K) (hKI : K ⊆ I) {a A j ε b : ℝ} (hw : ∀ s ∈ K, ∀ t ∈ K, |s-t| ≤ a) + (hA₀ : 0 ≤ A) (hA : 2*A ≤ 1) (hsmall : (1:ℝ)/50+a+2*A < 1) + (hb : 0 < b) (hpad : j+ε+2*a ≤ b/4) (hvisit : a ≤ j+ε+2*a) + (c : M.Point K root) (hc : c.height ∈ J) (hcS : c.column ∉ S) + (seed : W → M.Point K root) (partner : W → M.Point I root) + (Dx : ∀ w, F.BandDescent K ((seed w).widen hKI) ε) (Dy : ∀ w, F.BandDescent K (partner w) ε) + (hxS : ∀ w, (Dx w).target.column ∈ S) (hyS : ∀ w, (Dy w).target.column ∈ S) + (hxy : ∀ w, 1 ≤ dist ((seed w).widen hKI) (partner w)) + (hretain : ∀ w, F.NoLowTip ((seed w).widen hKI) (partner w) J j) + (cp : ∀ w, M.Path J c.column (seed w).column) + (hp : ∀ w, (cp w).length c.height (seed w).height ≤ A) + (havoid : ∀ w k, k ∈ (cp w).word.support → k ∉ S) + (hsep : ∀ w v, w ≠ v → b ≤ dist (seed w) (seed v)) : + (Fintype.card W : ℝ) ≤ 2+4*A/b := by + classical + let endpoint : Option W → M.Point K root := Option.elim' c seed + let path : ∀ w : Option W, M.Path J c.column (endpoint w).column := fun w => + Option.rec (.nil c.column) cp w + have hlen : ∀ w, (path w).length c.height (endpoint w).height ≤ A := by + intro w + cases w with + | none => simpa only [path,endpoint,Option.elim',Path.length,sub_self,abs_zero] using hA₀ + | some w => exact hp w + have hav : ∀ w k, k ∈ (path w).word.support → k ∉ S := by + intro w k hk + cases w with + | none => + have he : k = c.column := by + change k ∈ [c.column] at hk + exact List.mem_singleton.mp hk + exact he ▸ hcS + | some w => exact havoid w k hk + obtain ⟨l,_,hl⟩ := Finset.exists_min_image (Finset.univ : Finset (Option W)) + (fun w => (endpoint w).column) ⟨none,Finset.mem_univ _⟩ + obtain ⟨r,_,hr⟩ := Finset.exists_max_image (Finset.univ : Finset (Option W)) + (fun w => (endpoint w).column) ⟨none,Finset.mem_univ _⟩ + let select : Fin 2 → Option W := ![l,r] + let paths (s : Fin 2) := path (select s) + have hone (w : W) (v : Option W) + (hv : (seed w).column ∈ (path v).word.support ∨ + ColumnOrder.JumpsAcross (seed w).column (path v).word) : + ∃ e : M.Point K root, (e.column,e.height) ∈ (path v).trace c.height (endpoint v).height ∧ + dist (seed w) e ≤ j+ε+2*a := by + rcases hv with hv | hv + · obtain ⟨e,he,hnear⟩ := visited_seed_near_trace hJK hw c (seed w) hc (path v) hv + exact ⟨e,he,hnear.trans hvisit⟩ + · have hcs : dist c (seed w) ≤ A := by + have hd := c.distance_le (seed w) ((cp w).widen hJK) + rw [Path.length_widen] at hd + exact hd.trans (hp w) + obtain ⟨e,heJ,he,q,hq⟩ := F.skipped_seed_broad_path hS hcut hmin hJK hKI hw + (c.widen hKI) ((seed w).widen hKI) (partner w) (Dx w) (Dy w) (hxS w) (hyS w) + (hxy w) ((c.dist_widen_le (seed w) hKI).trans hcs) hA hsmall (hretain w) + (path v) (hlen v) (hav v) hv + let eb : M.Point K root := ⟨e.column,e.height,hJK heJ, + (seed w).reachable.trans q.word.reachable⟩ + exact ⟨eb,he,((seed w).distance_le eb q).trans hq⟩ + have hprox : ∀ w : W, ∃ (s : Fin 2) (e : M.Point K root), + (e.column,e.height) ∈ (paths s).trace c.height (endpoint (select s)).height ∧ + dist (seed w) e ≤ j+ε+2*a := by + intro w + have h := ColumnOrder.extreme_words (path l).word (path r).word + (hl (some w) (Finset.mem_univ _)) (hr (some w) (Finset.mem_univ _)) + rcases h with h | h + · obtain ⟨e,he,hnear⟩ := hone w l h + exact ⟨0,e,by simpa only [paths,select,Matrix.cons_val_zero] using he,hnear⟩ + · obtain ⟨e,he,hnear⟩ := hone w r h + exact ⟨1,e,by simpa only [paths,select,Matrix.cons_val_one,Matrix.cons_val_zero] using he,hnear⟩ + choose side near htrace hnear using hprox + exact near_two_traces_count hJK hb hA₀ hpad (fun _ => c.column) + (fun s => (endpoint (select s)).column) paths (fun _ => c.height) + (fun s => (endpoint (select s)).height) (fun s => hlen (select s)) + seed near side htrace hsep hnear + + +end PlanarL1.Columns.Model.Field + + +namespace PlanarL1.Columns.Model + +variable {n : ℕ} {M : Model n} {e : Equiv.Perm (Fin n)} + {hnc : ColumnOrder.Noncrossing (M.link.comap e)} + {hcon : ∀ i j, Consecutive (e i) (e j) ↔ Consecutive i j} + {J I : Set ℝ} {root : Fin n} + +def Point.label (x : M.Point J (e root)) : (M.relabel e hnc hcon).Point J root where + column := e.symm x.column + height := x.height + inBand := x.inBand + reachable := by + obtain ⟨p⟩ := x.reachable + obtain ⟨q,_⟩ := Path.exists_word p + simpa only [e.symm_apply_apply] using + (q.label (hnc := hnc) (hcon := hcon)).word.reachable + +@[simp] lemma Point.unlabel_label (x : M.Point J (e root)) : + (x.label (hnc := hnc) (hcon := hcon)).unlabel = x := by + cases x + simp only [Point.label,Point.unlabel,e.apply_symm_apply] + +@[simp] lemma Point.label_unlabel (x : (M.relabel e hnc hcon).Point J root) : + x.unlabel.label = x := by + cases x + simp only [Point.label,Point.unlabel,e.symm_apply_apply] + +lemma Point.dist_label (x y : M.Point J (e root)) : + dist (x.label (hnc := hnc) (hcon := hcon)) y.label = dist x y := by + rw [← Point.dist_unlabel,Point.unlabel_label,Point.unlabel_label] + +noncomputable def Point.labelEquiv : M.Point J (e root) ≃ (M.relabel e hnc hcon).Point J root where + toFun := Point.label + invFun := Point.unlabel + left_inv := Point.unlabel_label + right_inv := Point.label_unlabel + +def Field.label {L : NNReal} (F : M.Field I L) : (M.relabel e hnc hcon).Field I L where + value := fun i => F.value (e i) + vertical := fun i => F.vertical (e i) + switch := fun i j H h => F.switch (e i) (e j) H h + +@[simp] lemma Field.eval_label {L : NNReal} (F : M.Field I L) (x : M.Point I (e root)) : + (F.label (hnc := hnc) (hcon := hcon)).eval x.label = F.eval x := by + simp only [Field.eval,Field.label,Point.label,e.apply_symm_apply] + +@[simp] lemma Field.eval_unlabel {L : NNReal} (F : M.Field I L) + (x : (M.relabel e hnc hcon).Point I root) : + (F.label (hnc := hnc) (hcon := hcon)).eval x = F.eval x.unlabel := rfl + +noncomputable def Field.BandDescent.label {F : M.Field I 1} {x : M.Point I (e root)} {ε : ℝ} + (D : F.BandDescent J x ε) : + (F.label (hnc := hnc) (hcon := hcon)).BandDescent J x.label ε where + start_in := D.start_in + target := D.target.label + target_in := D.target_in + path := D.path.label + shortest := by + intro p + let q := p.unlabel + have he₁ : e (x.label (hnc := hnc) (hcon := hcon)).column = x.column := e.apply_symm_apply _ + have he₂ : e (D.target.label (hnc := hnc) (hcon := hcon)).column = D.target.column := e.apply_symm_apply _ + have hd := D.shortest (q.cast he₁ he₂) + rw [Path.length_cast] at hd + dsimp only [q] at hd + rw [Path.length_unlabel] at hd + simpa only [Path.length_label,Point.label] using hd + lower := by simpa only [Path.length_label,Point.label] using D.lower + upper := by simpa only [Path.length_label,Point.label] using D.upper + drop := by + simpa only [Path.length_label,Field.eval,Field.label,Point.label,e.apply_symm_apply] using D.drop + +end PlanarL1.Columns.Model + +namespace PlanarL1.Columns.Model.Field + +/-- Strictly opposite sides of an unoriented circular chord. -/ +def CircularTipSeparates {n : ℕ} (a b x y : Fin n) : Prop := + TipSeparates a b x y ∨ TipSeparates b a x y + +lemma circularTip_rotate {n : ℕ} (a b x y : Fin (n+1)) : + CircularTipSeparates (finRotate (n+1) a) (finRotate (n+1) b) + (finRotate (n+1) x) (finRotate (n+1) y) ↔ CircularTipSeparates a b x y := by + have hval (i : Fin (n+1)) : (finRotate (n+1) i).val = + if i.val = n then 0 else i.val+1 := by + split_ifs with hi + · have he : i = Fin.last n := Fin.ext hi + rw [he,finRotate_last] + rfl + · exact coe_finRotate_of_ne_last (fun h => hi (congrArg Fin.val h)) + unfold CircularTipSeparates TipSeparates + simp only [Fin.lt_def,hval] + split_ifs <;> omega + +lemma circularTip_iterate {n : ℕ} (k : ℕ) (a b x y : Fin (n+1)) : + CircularTipSeparates ((finRotate (n+1))^[k] a) ((finRotate (n+1))^[k] b) + ((finRotate (n+1))^[k] x) ((finRotate (n+1))^[k] y) ↔ CircularTipSeparates a b x y := by + induction k generalizing a b x y with + | zero => rfl + | succ k ih => + rw [Function.iterate_succ_apply,Function.iterate_succ_apply, + Function.iterate_succ_apply,Function.iterate_succ_apply,ih,circularTip_rotate] + +lemma circularTip_cycle {n : ℕ} (c a b x y : Fin (n+1)) : + CircularTipSeparates (finCycle c a) (finCycle c b) (finCycle c x) (finCycle c y) ↔ + CircularTipSeparates a b x y := by + rw [finCycle_eq_finRotate_iterate] + exact circularTip_iterate c.val a b x y + +end PlanarL1.Columns.Model.Field + +namespace PlanarL1.Columns.Model + +variable {n : ℕ} {M : Model n} {e : Equiv.Perm (Fin n)} + {hnc : ColumnOrder.Noncrossing (M.link.comap e)} + {hcon : ∀ i j, Consecutive (e i) (e j) ↔ Consecutive i j} + {J I : Set ℝ} {root : Fin n} + +@[simp] lemma Point.widen_label (x : M.Point J (e root)) (hJI : J ⊆ I) : + (x.label (hnc := hnc) (hcon := hcon)).widen hJI = (x.widen hJI).label := rfl + +lemma Path.support_word_label {i j : Fin n} (p : M.Path J i j) : + (p.label (hnc := hnc) (hcon := hcon)).word.support = p.word.support.map e.symm := by + induction p with + | nil => rfl + | cons H hH hs p ih => + change _ :: p.label.word.support = _ :: p.word.support.map e.symm + rw [ih] + +namespace Field + +/-- Absence of a low separating tip is intrinsically circular: reversing +the listed chord endpoints does not change the exclusion test. -/ +def NoLowCircular (F : M.Field I 1) (x y : M.Point I root) (J : Set ℝ) (j : ℝ) : Prop := + ∀ (v : M.Point I root) (b : Fin n), v.height ∈ J → + v.height ∈ M.heights v.column b → ¬ Consecutive v.column b → + CircularTipSeparates v.column b x.column y.column → + (dist x v ≤ 1 ∨ dist y v ≤ 1) → + F.eval x-j ≤ F.eval v ∧ F.eval y-j ≤ F.eval v + +lemma NoLowCircular.toNoLowTip {F : M.Field I 1} {x y : M.Point I root} {j : ℝ} + (h : F.NoLowCircular x y J j) : F.NoLowTip x y J j := by + intro v b hJ hs hc ht hd + exact h v b hJ hs hc (Or.inl ht) hd + +lemma NoLowCircular.label {F : M.Field I 1} {x y : M.Point I (e root)} {j : ℝ} + (h : F.NoLowCircular x y J j) + (hcirc : ∀ a b v w, CircularTipSeparates (e a) (e b) (e v) (e w) ↔ + CircularTipSeparates a b v w) : + (F.label (hnc := hnc) (hcon := hcon)).NoLowCircular x.label y.label J j := by + intro v b hvJ hvs hvc hvsep hvdist + have h₁ : dist x v.unlabel = dist x.label v := by + simpa only [Point.unlabel_label] using + (Point.dist_unlabel (x.label (hnc := hnc) (hcon := hcon)) v) + have h₂ : dist y v.unlabel = dist y.label v := by + simpa only [Point.unlabel_label] using + (Point.dist_unlabel (y.label (hnc := hnc) (hcon := hcon)) v) + have hsep := (hcirc v.column b x.label.column y.label.column).mpr hvsep + simp only [Point.label,e.apply_symm_apply] at hsep + have hc : ¬Consecutive v.unlabel.column (e b) := fun hh => hvc ((hcon _ _).mp hh) + have hh := h v.unlabel (e b) hvJ hvs hc hsep (by simpa only [h₁,h₂] using hvdist) + simpa only [Field.eval_label,Field.eval_unlabel,Point.unlabel_label] using hh + +end Field +end PlanarL1.Columns.Model + +namespace PlanarL1.ColumnOrder + +lemma preconnected_comap {n : ℕ} {G : SimpleGraph (Fin n)} {S : Set (Fin n)} + (hS : (G.induce S).Preconnected) (e : Equiv.Perm (Fin n)) : + ((G.comap e).induce (e ⁻¹' S)).Preconnected := by + let f : G.induce S →g (G.comap e).induce (e ⁻¹' S) := + { toFun := fun v => ⟨e.symm v.val,by simpa only [Set.mem_preimage,e.apply_symm_apply] using v.property⟩ + map_rel' := fun {_ _} h => by + change G.Adj _ _ at h + change G.Adj (e (e.symm _)) (e (e.symm _)) + simpa only [e.apply_symm_apply, Function.Embedding.subtype_apply] using h } + intro x y + obtain ⟨p⟩ := hS ⟨e x.val,x.property⟩ ⟨e y.val,y.property⟩ + have hx : f ⟨e x.val,x.property⟩ = x := by + apply Subtype.ext + exact e.symm_apply_apply _ + have hy : f ⟨e y.val,y.property⟩ = y := by + apply Subtype.ext + exact e.symm_apply_apply _ + exact ⟨(p.map f).copy hx hy⟩ + +end PlanarL1.ColumnOrder + +namespace PlanarL1.Columns.Model.Field + +/-- Restricted geometric packing with NO privileged linear cut. The proof +rotates the actual model, fields, paths and all distance data at a low column. +The result measures separation in the BROAD current intrinsic component. -/ +theorem circular_broad_packing {n : ℕ} {M : Model (n+1)} {I J K : Set ℝ} {root : Fin (n+1)} + {W : Type*} [Fintype W] (F : M.Field I 1) + {S : Set (Fin (n+1))} (hS : (M.link.induce S).Preconnected) + {cut : Fin (n+1)} (hcut : cut ∈ S) + (hJK : J ⊆ K) (hKI : K ⊆ I) {a A j ε b : ℝ} + (hw : ∀ s ∈ K, ∀ t ∈ K, |s-t| ≤ a) + (hA₀ : 0 ≤ A) (hA : 2*A ≤ 1) (hsmall : (1:ℝ)/50+a+2*A < 1) + (hb : 0 < b) (hpad : j+ε+2*a ≤ b/4) (hvisit : a ≤ j+ε+2*a) + (c : M.Point K root) (hc : c.height ∈ J) (hcS : c.column ∉ S) + (seed : W → M.Point K root) (partner : W → M.Point I root) + (Dx : ∀ w, F.BandDescent K ((seed w).widen hKI) ε) + (Dy : ∀ w, F.BandDescent K (partner w) ε) + (hxS : ∀ w, (Dx w).target.column ∈ S) (hyS : ∀ w, (Dy w).target.column ∈ S) + (hxy : ∀ w, 1 ≤ dist ((seed w).widen hKI) (partner w)) + (hretain : ∀ w, F.NoLowCircular ((seed w).widen hKI) (partner w) J j) + (cp : ∀ w, M.Path J c.column (seed w).column) + (hp : ∀ w, (cp w).length c.height (seed w).height ≤ A) + (havoid : ∀ w k, k ∈ (cp w).word.support → k ∉ S) + (hsep : ∀ w v, w ≠ v → b ≤ dist (seed w) (seed v)) : + (Fintype.card W : ℝ) ≤ 2+4*A/b := by + let e := finCycle cut + obtain ⟨r,rfl⟩ := e.surjective root + let hnc := ColumnOrder.noncrossing_comap_cycle M.noncrossing cut + let hcon := consecutive_cycle cut + let N := M.relabel e hnc hcon + let F' : N.Field I 1 := F.label + let c' : N.Point K r := c.label + let seed' (w : W) : N.Point K r := (seed w).label + let partner' (w : W) : N.Point I r := (partner w).label + let dy' (w : W) : F'.BandDescent K (partner' w) ε := (Dy w).label + -- Use the explicit transported data, so target membership is not lost + -- behind a propositional existence witness. + let dx' (w : W) : F'.BandDescent K ((seed' w).widen hKI) ε := (Dx w).label + have hzero : e 0 = cut := by simp only [e,finCycle_apply,zero_add] + refine F'.restricted_broad_packing (S := e ⁻¹' S) + (ColumnOrder.preconnected_comap hS e) (cut := 0) (by simpa only [Set.mem_preimage,hzero] using hcut) + (fun v => Fin.zero_le v) hJK hKI hw hA₀ hA hsmall hb hpad hvisit c' hc + (by simpa only [c',Point.label,Set.mem_preimage,e.apply_symm_apply] using hcS) + seed' partner' dx' dy' ?_ ?_ ?_ ?_ (fun w => (cp w).label) ?_ ?_ ?_ + · intro w + simpa only [dx',Field.BandDescent.label,Point.label,Set.mem_preimage,e.apply_symm_apply] using hxS w + · intro w + simpa only [dy',Field.BandDescent.label,Point.label,Set.mem_preimage,e.apply_symm_apply] using hyS w + · intro w + exact (hxy w).trans_eq + (Point.dist_label (hnc := hnc) (hcon := hcon) ((seed w).widen hKI) (partner w)).symm + · intro w + exact ((hretain w).label (hnc := hnc) (hcon := hcon) (circularTip_cycle cut)).toNoLowTip + · intro w + simpa only [c',seed',Point.label,Path.length_label] using hp w + · intro w k hk + change k ∈ ((cp w).label (hnc := hnc) (hcon := hcon)).word.support at hk + rw [Path.support_word_label] at hk + obtain ⟨v,hv,rfl⟩ := List.mem_map.mp hk + change e (e.symm v) ∉ S + simpa only [e.apply_symm_apply] using havoid w v hv + · intro w v hwv + exact (hsep w v hwv).trans_eq + (Point.dist_label (hnc := hnc) (hcon := hcon) (seed w) (seed v)).symm + +end PlanarL1.Columns.Model.Field + +namespace PlanarL1.Columns.Model.Field + +/-- The low-set and circular-gap hypotheses of geometric packing are DERIVED +from the actual old chart distance and actual witness descents. This is the +band-faithful application of `pack:bound` to surviving seeds. -/ +theorem radial_surviving_packing {n : ℕ} {M : Model (n+1)} {I J K : Set ℝ} + {root : Fin (n+1)} {W : Type*} [Fintype W] + (hI : IsClosed I) (hJK : J ⊆ K) (hKI : K ⊆ I) + {a A E δ j ε b : ℝ} (hw : ∀ s ∈ K, ∀ t ∈ K, |s-t| ≤ a) + (hA₀ : 0 ≤ A) (hA : 2*A ≤ 1) (hE : 0 ≤ E) + (hsmall : (1:ℝ)/50+a+2*A < 1) + (hlow : 2*A+E+ε+a < (1:ℝ)/100000-δ) (hhigh : 2*A+a < δ) + (hb : 0 < b) (hpad : j+ε+2*a ≤ b/4) (hvisit : a ≤ j+ε+2*a) + (o : M.Point I root) (c : M.Point K root) (hc : c.height ∈ J) + (seed : W → M.Point K root) (partner : W → M.Point I root) + (hseed : ∀ w, (seed w).height ∈ J) + (Dx : ∀ w, o.radialField.BandDescent K ((seed w).widen hKI) ε) + (Dy : ∀ w, o.radialField.BandDescent K (partner w) ε) + (hxy : ∀ w, 1 ≤ dist ((seed w).widen hKI) (partner w)) + (hfield : ∀ w, |dist o (partner w)-dist o ((seed w).widen hKI)| ≤ E) + (hretain : ∀ w, o.radialField.NoLowCircular ((seed w).widen hKI) (partner w) J j) + (cp : ∀ w, M.Path J c.column (seed w).column) + (hp : ∀ w, (cp w).length c.height (seed w).height ≤ A) + (hsep : ∀ w v, w ≠ v → b ≤ dist (seed w) (seed v)) : + (Fintype.card W : ℝ) ≤ 2+4*A/b := by + classical + by_cases hn : Nonempty W + · obtain ⟨w₀⟩ := hn + let star := (seed w₀).widen hKI + let H := (seed w₀).height + have hHJ : H ∈ J := hseed w₀ + have hHI : H ∈ I := hKI (hJK hHJ) + let S := o.sublevel H hHI (dist o star-δ) + have hcs (w : W) : dist (c.widen hKI) ((seed w).widen hKI) ≤ A := by + apply (c.dist_widen_le (seed w) hKI).trans + exact (c.distance_le (seed w) ((cp w).widen hJK)).trans + (by simpa only [Path.length_widen] using hp w) + have hclose (w : W) : dist o ((seed w).widen hKI) ≤ dist o star+2*A+E := by + have h₁ := dist_triangle o star (c.widen hKI) + have h₂ := dist_triangle o (c.widen hKI) ((seed w).widen hKI) + have hc₀ := hcs w₀ + change dist (c.widen hKI) star ≤ A at hc₀ + rw [dist_comm (c.widen hKI) star] at hc₀ + linarith [hcs w] + have hclosePartner (w : W) : dist o (partner w) ≤ dist o star+(2*A+E) := by + have h₁ := dist_triangle o star (c.widen hKI) + have h₂ := dist_triangle o (c.widen hKI) ((seed w).widen hKI) + have hc₀ := hcs w₀ + change dist (c.widen hKI) star ≤ A at hc₀ + rw [dist_comm (c.widen hKI) star] at hc₀ + have hf := (abs_le.mp (hfield w)).2 + linarith [hcs w] + have hxS (w : W) : (Dx w).target.column ∈ S := by + exact o.descent_target_low star ((seed w).widen hKI) hKI (Dx w) (hJK hHJ) hw + (by linarith [hclose w]) hlow + have hyS (w : W) : (Dy w).target.column ∈ S := by + exact o.descent_target_low star (partner w) hKI (Dy w) (hJK hHJ) hw (hclosePartner w) hlow + have hav (w : W) : ∀ k ∈ (cp w).word.support, k ∉ S := by + exact o.short_path_avoids_low star (c.widen hKI) (hJK.trans hKI) hHJ + (fun s hs t ht => hw s (hJK hs) t (hJK ht)) hc (hcs w₀) hhigh (cp w) (hp w) + exact o.radialField.circular_broad_packing (o.sublevel_link_preconnected hI H hHI _) + (hxS w₀) hJK hKI hw hA₀ hA hsmall hb hpad hvisit c hc + (hav w₀ c.column (cp w₀).word.start_mem_support) + seed partner Dx Dy hxS hyS hxy hretain cp hp hav hsep + · have : IsEmpty W := not_nonempty_iff.mp hn + simp only [Fintype.card_of_isEmpty,Nat.cast_zero] + positivity + +end PlanarL1.Columns.Model.Field + + + +end + +end OAI diff --git a/lean/OAI/Combinatorics/PlanarL1/Clipping.lean b/lean/OAI/Combinatorics/PlanarL1/Clipping.lean new file mode 100644 index 0000000000000000000000000000000000000000..29eb27e1668b56086316fe2e8e9d9d7d361c4dba --- /dev/null +++ b/lean/OAI/Combinatorics/PlanarL1/Clipping.lean @@ -0,0 +1,273 @@ +import Mathlib + +namespace OAI + +section + +namespace PlanarL1.Clipping + +open scoped NNReal + +variable {X : Type*} [PseudoMetricSpace X] + +/-- The literal capped frontier extension; the empty frontier contributes ++infinity before taking the minimum, so the finite result is the cap. -/ +noncomputable def envelope (S : Set X) (s : X → ℝ) (cap t : ℝ) (x : X) : ℝ := by + classical + exact if S.Nonempty then min cap (sInf ((fun z => s z+t*dist x z) '' S)) else cap + +lemma envelope_le_cap (S : Set X) (s : X → ℝ) (cap t : ℝ) (x : X) : + envelope S s cap t x ≤ cap := by + classical + unfold envelope + split + · exact min_le_left _ _ + · rfl + +lemma cost_continuousOn {S : Set X} {s : X → ℝ} (hs : ContinuousOn s S) (t : ℝ) (x : X) : + ContinuousOn (fun z => s z+t*dist x z) S := + hs.add (continuous_const.mul (continuous_const.dist continuous_id)).continuousOn + +lemma inf_attained {S : Set X} {s : X → ℝ} (hS : IsCompact S) (hs : ContinuousOn s S) + (hne : S.Nonempty) (t : ℝ) (x : X) : + ∃ z ∈ S, sInf ((fun z => s z+t*dist x z) '' S) = s z+t*dist x z := by + obtain ⟨z,hz,hmin⟩ := hS.exists_isMinOn hne (cost_continuousOn hs t x) + refine ⟨z,hz,le_antisymm ?_ ?_⟩ + · exact csInf_le (hS.image_of_continuousOn (cost_continuousOn hs t x)).bddBelow + ⟨z,hz,rfl⟩ + · apply le_csInf (hne.image _) + rintro _ ⟨y,hy,rfl⟩ + exact hmin hy + +lemma envelope_le_cost {S : Set X} {s : X → ℝ} (hS : IsCompact S) (hs : ContinuousOn s S) + (cap t : ℝ) (x : X) {z : X} (hz : z ∈ S) : + envelope S s cap t x ≤ s z+t*dist x z := by + classical + rw [envelope,ite_eq_left ⟨z,hz⟩] + exact (min_le_right _ _).trans (csInf_le + (hS.image_of_continuousOn (cost_continuousOn hs t x)).bddBelow ⟨z,hz,rfl⟩) + +lemma envelope_frontier {S : Set X} {s : X → ℝ} (hS : IsCompact S) (hs : ContinuousOn s S) + (cap t : ℝ) {x : X} (hx : x ∈ S) : envelope S s cap t x ≤ s x := by + simpa only [dist_self,mul_zero,add_zero] using envelope_le_cost hS hs cap t x hx + +lemma envelope_cases {S : Set X} {s : X → ℝ} (hS : IsCompact S) (hs : ContinuousOn s S) + (cap t : ℝ) (x : X) : + envelope S s cap t x = cap ∨ + ∃ z ∈ S, envelope S s cap t x = s z+t*dist x z := by + classical + by_cases hn : S.Nonempty + · obtain ⟨z,hz,he⟩ := inf_attained hS hs hn t x + rw [envelope,ite_eq_left hn,he] + rcases le_total cap (s z+t*dist x z) with h | h + · exact Or.inl (min_eq_left h) + · exact Or.inr ⟨z,hz,min_eq_right h⟩ + · exact Or.inl (by rw [envelope,ite_eq_right hn]) + +lemma envelope_one_sided {S : Set X} {s : X → ℝ} (hS : IsCompact S) + (hs : ContinuousOn s S) (cap : ℝ) {t : ℝ} (ht : 0 ≤ t) (x y : X) : + envelope S s cap t x ≤ envelope S s cap t y+t*dist x y := by + obtain h | ⟨z,hz,h⟩ := envelope_cases hS hs cap t y + · rw [h] + exact (envelope_le_cap S s cap t x).trans (le_add_of_nonneg_right (mul_nonneg ht dist_nonneg)) + · rw [h] + have hc := envelope_le_cost hS hs cap t x hz + have hm := mul_le_mul_of_nonneg_left (dist_triangle x y z) ht + linarith + +lemma envelope_lipschitz {S : Set X} {s : X → ℝ} (hS : IsCompact S) + (hs : ContinuousOn s S) (cap : ℝ) (t : ℝ≥0) : LipschitzWith t (envelope S s cap t) := by + apply LipschitzWith.of_dist_le_mul + intro x y + rw [Real.dist_eq,abs_le] + have ha := envelope_one_sided hS hs cap t.coe_nonneg x y + have hb := envelope_one_sided hS hs cap t.coe_nonneg y x + rw [dist_comm y x] at hb + constructor <;> linarith + +/-- Single kept-cell clipping, before chart identifiers/rebasing. -/ +noncomputable def clip (s F H : X → ℝ) (x : X) : ℝ := max (s x) (min (F x) (H x)) + +lemma clip_lipschitz {s F H : X → ℝ} {K : ℝ≥0} + (hs : LipschitzWith K s) (hF : LipschitzWith K F) (hH : LipschitzWith K H) : + LipschitzWith K (clip s F H) := by + unfold clip + simpa only [max_self] using hs.max (hF.min hH) + +omit [PseudoMetricSpace X] in +lemma clip_unchanged {s F H : X → ℝ} {x : X} (h : F x ≤ s x ∨ H x ≤ s x) : + clip s F H x = s x := by + apply max_eq_left + rcases h with h | h + · exact (min_le_left _ _).trans h + · exact (min_le_right _ _).trans h + +omit [PseudoMetricSpace X] in +lemma clip_movement {s F H : X → ℝ} {B : ℝ} (hB : 0 ≤ B) (x : X) + (hF : F x ≤ s x+B) : 0 ≤ clip s F H x-s x ∧ clip s F H x-s x ≤ B := by + constructor + · exact sub_nonneg.mpr (le_max_left _ _) + · have : clip s F H x ≤ s x+B := max_le (by linarith) ((min_le_left _ _).trans hF) + linarith + +/-- The source main raise-or-descend alternative, including the empty frontier. +The radius interval is obtained from actual radial padding and weak diameter +when this lemma is applied to the literal full-column frontier. -/ +lemma raise_or_descending_endpoint {S : Set X} {s F H : X → ℝ} + (hS : IsCompact S) (hs : ContinuousOn s S) (w : X) (cap ζ E ε : ℝ) + (happrox : envelope S s cap (1-ζ) w-5*E ≤ F w) + (hshield : s w+2*E < H w) (hcap : s w+7*E < cap) + (hrad : ∀ z ∈ S, (0.00001:ℝ) ≤ dist w z ∧ dist w z ≤ 0.02) + (hzeta : 0 ≤ ζ) (herr : ζ*0.02+7*E ≤ ε) : + s w+2*E < clip s F H w ∨ + ∃ z ∈ S, (0.00001:ℝ) ≤ dist w z ∧ dist w z ≤ 0.02 ∧ + s z ≤ s w-dist w z+ε := by + by_cases hraise : s w+2*E < clip s F H w + · exact Or.inl hraise + · right + have hc : min (F w) (H w) ≤ s w+2*E := + (le_max_right _ _).trans (not_lt.mp hraise) + have hFw : F w ≤ s w+2*E := (min_le_iff.mp hc).resolve_right (not_le.mpr hshield) + have he : envelope S s cap (1-ζ) w ≤ s w+7*E := by linarith + obtain h | ⟨z,hz,h⟩ := envelope_cases hS hs cap (1-ζ) w + · rw [h] at he + exact (not_le.mpr hcap he).elim + · refine ⟨z,hz,(hrad z hz).1,(hrad z hz).2,?_⟩ + rw [h] at he + have hm := mul_le_mul_of_nonneg_left (hrad z hz).2 hzeta + nlinarith + +end PlanarL1.Clipping + + +end + +section + +namespace PlanarL1.Clipping +open scoped NNReal + +/-- Literal trapezoidal height branch, constant outside the closed band. -/ +noncomputable def heightShield (lo a s α H : ℝ) : ℝ := + s-1+α + 3 * min 1 (max 0 (min (H-lo) (lo+a-H)) / (9*a/100)) + +lemma heightShield_left {lo a s α H : ℝ} (hH : H ≤ lo) : + heightShield lo a s α H = s-1+α := by + have hm : min (H-lo) (lo+a-H) ≤ 0 := (min_le_left _ _).trans (sub_nonpos.mpr hH) + simp only [heightShield,max_eq_left hm,zero_div,min_eq_right (by norm_num : (0:ℝ) ≤ 1),mul_zero,add_zero] + +lemma heightShield_right {lo a s α H : ℝ} (hH : lo+a ≤ H) : + heightShield lo a s α H = s-1+α := by + have hm : min (H-lo) (lo+a-H) ≤ 0 := (min_le_right _ _).trans (sub_nonpos.mpr hH) + simp only [heightShield,max_eq_left hm,zero_div,min_eq_right (by norm_num : (0:ℝ) ≤ 1),mul_zero,add_zero] + +lemma heightShield_plateau {lo a s α H : ℝ} (ha : 0 < a) + (hl : lo+9*a/100 ≤ H) (hr : H ≤ lo+a-9*a/100) : + heightShield lo a s α H = s+2+α := by + have hb : 0 < 9*a/100 := by positivity + have hm : 9*a/100 ≤ min (H-lo) (lo+a-H) := le_min (by linarith) (by linarith) + have hq : 1 ≤ max 0 (min (H-lo) (lo+a-H)) / (9*a/100) := by + apply (le_div_iff₀ hb).mpr + simpa only [one_mul] using hm.trans (le_max_right _ _) + rw [heightShield,min_eq_left hq] + ring + +lemma heightShield_bounds {lo a s α H : ℝ} (ha : 0 < a) : + s-1+α ≤ heightShield lo a s α H ∧ heightShield lo a s α H ≤ s+2+α := by + have hb : 0 < 9*a/100 := by positivity + have hz : 0 ≤ min 1 (max 0 (min (H-lo) (lo+a-H)) / (9*a/100)) := + le_min (by norm_num) (div_nonneg (le_max_left _ _) hb.le) + have ho := min_le_left (1:ℝ) (max 0 (min (H-lo) (lo+a-H)) / (9*a/100)) + dsimp only [heightShield] + constructor <;> linarith + +lemma heightShield_lipschitz (lo s α : ℝ) {a : ℝ} (ha : 0 < a) : + LipschitzWith ⟨3/(9*a/100),by positivity⟩ (heightShield lo a s α) := by + have hb : 0 < 9*a/100 := by positivity + have hl : LipschitzWith 1 (fun H : ℝ => H-lo) := by + apply LipschitzWith.of_dist_le_mul + intro x y + simp only [dist_sub_right,NNReal.coe_one,one_mul,le_refl] + have hr : LipschitzWith 1 (fun H : ℝ => lo+a-H) := by + apply LipschitzWith.of_dist_le_mul + intro x y + simp only [dist_sub_left,NNReal.coe_one,one_mul,le_refl] + have hm : LipschitzWith 1 (fun H : ℝ => max 0 (min (H-lo) (lo+a-H))) := by + simpa only [max_self, max_eq_right (show (0:ℝ≥0) ≤ 1 by norm_num)] using + (LipschitzWith.const (0:ℝ)).max (hl.min hr) + have hq : LipschitzWith ⟨1/(9*a/100),by positivity⟩ + (fun H : ℝ => max 0 (min (H-lo) (lo+a-H))/(9*a/100)) := by + apply LipschitzWith.of_dist_le_mul + intro x y + change dist _ _ ≤ (1/(9*a/100))*dist x y + rw [Real.dist_eq,← sub_div,abs_div,abs_of_pos hb] + have h := hm.dist_le_mul x y + rw [Real.dist_eq,NNReal.coe_one,one_mul] at h + calc + _ ≤ dist x y/(9*a/100) := div_le_div_of_nonneg_right h hb.le + _ = _ := by ring + have hp : LipschitzWith ⟨1/(9*a/100),by positivity⟩ + (fun H : ℝ => min 1 (max 0 (min (H-lo) (lo+a-H))/(9*a/100))) := by + exact hq.const_min 1 + apply LipschitzWith.of_dist_le_mul + intro x y + have h := hp.dist_le_mul x y + change dist _ _ ≤ (1/(9*a/100))*dist x y at h + rw [Real.dist_eq] at h + change dist _ _ ≤ (3/(9*a/100))*dist x y + rw [heightShield,heightShield,Real.dist_eq] + let f (H : ℝ) := min 1 (max 0 (min (H-lo) (lo+a-H))/(9*a/100)) + change |(s-1+α+3*f x)-(s-1+α+3*f y)| ≤ (3/(9*a/100))*dist x y + change |f x-f y| ≤ (1/(9*a/100))*dist x y at h + calc + _ = 3*|f x-f y| := by + rw [show (s-1+α+3*f x)-(s-1+α+3*f y) = 3*(f x-f y) by ring, + abs_mul,abs_of_pos (by norm_num : (0:ℝ) < 3)] + _ ≤ 3*((1/(9*a/100))*dist x y) := + mul_le_mul_of_nonneg_left h (by norm_num) + _ = _ := by ring + +end PlanarL1.Clipping + + +end + +section + +namespace PlanarL1.Clipping +variable {X : Type*} + +noncomputable def orderedBranch (pc radius α : ℝ) (L : X → ℝ) (x : X) : ℝ := + pc+radius/20+4*(L x-pc)+α + +lemma orderedBranch_boundary {pc radius α p : ℝ} {L : X → ℝ} {x : X} + (hα : α ≤ radius/1000) (hL : L x ≤ p) (hp : p < pc-(65/100:ℝ)*radius) : + orderedBranch pc radius α L x < p-(1899/1000:ℝ)*radius := by + dsimp only [orderedBranch] + linarith + +lemma orderedBranch_seed {pc radius α p : ℝ} {L : X → ℝ} {x : X} (hr : 0 < radius) + (hα : 0 ≤ α) (hL : |L x-pc| ≤ (10/1000000:ℝ)*radius) + (hp : |p-pc| ≤ (60/1000000:ℝ)*radius) : + p+radius/25 < orderedBranch pc radius α L x := by + have hl := (abs_le.mp hL).1 + have hu := (abs_le.mp hp).2 + dsimp only [orderedBranch] + linarith + +lemma ordinary_boundary_margin {pc radius α p T : ℝ} {L : X → ℝ} {x : X} (hr : 0 ≤ radius) + (hα : α ≤ radius/1000) (hL : L x ≤ p) (hT : T ≤ pc-(849/1000:ℝ)*radius) : + min T (orderedBranch pc radius α L x) ≤ p-(199/1000:ℝ)*radius := by + by_cases hp : pc-(65/100:ℝ)*radius ≤ p + · exact (min_le_left _ _).trans (by linarith) + · have ho := orderedBranch_boundary hα hL (lt_of_not_ge hp) + exact (min_le_right _ _).trans (by linarith) + +end PlanarL1.Clipping + + + + +end + +end OAI diff --git a/lean/OAI/Combinatorics/PlanarL1/Columns.lean b/lean/OAI/Combinatorics/PlanarL1/Columns.lean new file mode 100644 index 0000000000000000000000000000000000000000..fcf93cbff8d521b592b49911db70d7a19b375b87 --- /dev/null +++ b/lean/OAI/Combinatorics/PlanarL1/Columns.lean @@ -0,0 +1,404 @@ +import OAI.Combinatorics.PlanarL1.Noncrossing + +namespace OAI + +section + +namespace PlanarL1 +/-! ## Finite switching paths in the manuscript's column models +A switch retains height and has zero cost. Between switches a path travels +vertically; its length is the sum of all vertical variations. The band argument +below does not identify an ambient distance with a band distance. -/ +namespace Columns + +/-- Neighbors in the cyclic order, including the wrap-around edge. -/ +def Consecutive {n : ℕ} (i j : Fin n) : Prop := + i.val + 1 = j.val ∨ j.val + 1 = i.val ∨ + (i.val = 0 ∧ j.val + 1 = n) ∨ (j.val = 0 ∧ i.val + 1 = n) + +/-- The data and standing hypotheses of a column model. +Only the actual prescribed switch heights identify columns. -/ +structure Model (n : ℕ) where + link : SimpleGraph (Fin n) + heights : Fin n → Fin n → Set ℝ + symm : ∀ i j, heights i j = heights j i + permitted : ∀ i j H, H ∈ heights i j → link.Adj i j + compact : ∀ i j, IsCompact (heights i j) + noncrossing : ColumnOrder.Noncrossing link + terminal : ∀ i j, link.Adj i j → ¬ Consecutive i j → + ∃ H, heights i j = {H} ∧ ∀ k T, + (T ∈ heights i k ∨ T ∈ heights j k) → T ≤ H + +namespace Model + +variable {n : ℕ} (M : Model n) + +/-- A link is active in a band exactly when it has an allowed height there. -/ +def activeGraph (J : Set ℝ) : SimpleGraph (Fin n) where + Adj i j := ∃ H ∈ J, H ∈ M.heights i j + symm := ⟨by + intro i j + rintro ⟨H, hH, h⟩ + exact ⟨H, hH, by rwa [M.symm i j] at h⟩⟩ + loopless := ⟨by + intro i + rintro ⟨H, _, h⟩ + exact M.link.loopless.irrefl i (M.permitted i i H h)⟩ + +lemma active_subgraph (J : Set ℝ) : M.activeGraph J ≤ M.link := by + rintro i j ⟨H, _, h⟩ + exact M.permitted i j H h + +lemma active_noncrossing (J : Set ℝ) : ColumnOrder.Noncrossing (M.activeGraph J) := by + intro a b c d hab hbc hcd h + exact M.noncrossing a b c d hab hbc hcd + ⟨M.active_subgraph J h.1, M.active_subgraph J h.2⟩ + +/-- A finite column word with an allowed band-switch height at every step. +Endpoint heights are supplied separately; the nil word is a vertical segment. -/ +inductive Path (J : Set ℝ) : Fin n → Fin n → Type + | nil (i : Fin n) : Path J i i + | cons {i j k : Fin n} (H : ℝ) (inBand : H ∈ J) + (switch : H ∈ M.heights i j) (tail : Path J j k) : Path J i k + +namespace Path + +variable {M} {J : Set ℝ} {i j k : Fin n} + +/-- Source length: sum of the lengths of vertical segments, with switches free. -/ +def length : {i j : Fin n} → M.Path J i j → ℝ → ℝ → ℝ + | _, _, .nil _, a, b => |a - b| + | _, _, .cons H _ _ p, a, b => |a - H| + p.length H b + +/-- The associated walk in the active column graph, used for planar separation. -/ +def word : {i j : Fin n} → M.Path J i j → (M.activeGraph J).Walk i j + | _, _, .nil _ => .nil + | _, _, .cons H hH hs p => .cons ⟨H, hH, hs⟩ p.word + +lemma length_nonneg (p : M.Path J i j) (a b : ℝ) : 0 ≤ p.length a b := by + induction p generalizing a with + | nil => exact abs_nonneg _ + | cons H _ _ p ih => exact add_nonneg (abs_nonneg _) (ih H) + +lemma height_change_le (p : M.Path J i j) (a b : ℝ) : |a - b| ≤ p.length a b := by + induction p generalizing a with + | nil => exact le_rfl + | cons H hH hs p ih => + dsimp only [length] + linarith [abs_sub_le a H b, ih H] + +/-- Moving just the final endpoint vertically changes a path length by at most +that vertical distance. The intermediate switch heights stay unchanged. -/ +lemma length_end_le (p : M.Path J i j) (a b c : ℝ) : + p.length a c ≤ p.length a b + |b - c| := by + induction p generalizing a with + | nil => exact abs_sub_le a b c + | cons H hH hs p ih => + dsimp only [length] + linarith [ih H] + +lemma length_start_le (p : M.Path J i j) (a b c : ℝ) : + p.length a c ≤ |a - b| + p.length b c := by + cases p with + | nil => exact abs_sub_le a b c + | cons H hH hs p => + dsimp only [length] + linarith [abs_sub_le a b H] + +/-- Concatenate switching words. Any redundant final/initial vertical detour at +the common column is removed, so length can only decrease. -/ +def append : {i j k : Fin n} → M.Path J i j → M.Path J j k → M.Path J i k + | _, _, _, .nil _, q => q + | _, _, _, .cons H hH hs p, q => .cons H hH hs (p.append q) + +lemma length_append_le (p : M.Path J i j) (q : M.Path J j k) (a b c : ℝ) : + (p.append q).length a c ≤ p.length a b + q.length b c := by + induction p generalizing a with + | nil => exact q.length_start_le a b c + | cons H hH hs p ih => + dsimp only [length, append] + linarith [ih q H] + +/-- Adjoin one final switch at height `H`. -/ +def snoc (p : M.Path J i j) (H : ℝ) (hH : H ∈ J) (hs : H ∈ M.heights j k) : + M.Path J i k := p.append (.cons H hH hs (.nil k)) + +lemma length_snoc (p : M.Path J i j) (H : ℝ) (hH : H ∈ J) + (hs : H ∈ M.heights j k) (a b : ℝ) : + (p.snoc H hH hs).length a b = p.length a H + |H - b| := by + induction p generalizing a with + | nil => rfl + | cons T hT ht p ih => + dsimp only [snoc, append, length] at * + rw [ih] + ring + +/-- Reverse the column word and all its zero-cost switches. -/ +def reverse : {i j : Fin n} → M.Path J i j → M.Path J j i + | _, _, .nil _ => .nil _ + | _, _, .cons H hH hs p => p.reverse.snoc H hH (by rwa [M.symm] at hs) + +lemma length_reverse (p : M.Path J i j) (a b : ℝ) : + p.reverse.length b a = p.length a b := by + induction p generalizing a with + | nil => exact abs_sub_comm b a + | cons H hH hs p ih => + dsimp only [reverse] + rw [length_snoc, ih] + dsimp only [length] + rw [abs_sub_comm H a, add_comm] + +/-- Every walk in the active graph really is a switching path: one chooses an +available height independently for each prescribed switch. -/ +lemma exists_word (p : (M.activeGraph J).Walk i j) : + ∃ q : M.Path J i j, q.word = p := by + induction p with + | nil => exact ⟨.nil _, rfl⟩ + | cons h p ih => + obtain ⟨H, hH, hs⟩ := h + obtain ⟨q, hq⟩ := ih + exact ⟨.cons H hH hs q, by simp only [word, hq]⟩ + +/-- A visit in a column word admits a genuine length-exact split at a height +in the band. This keeps paths that leave an individual radial cell available. -/ +lemma split_at_column (p : M.Path J i j) {a b : ℝ} (ha : a ∈ J) (_hb : b ∈ J) + {v : Fin n} (hv : v ∈ p.word.support) : + ∃ H ∈ J, ∃ (q : M.Path J i v) (r : M.Path J v j), + q.length a H + r.length H b = p.length a b := by + induction p generalizing a with + | nil i => + have hvi : v = i := by simpa only [word, SimpleGraph.Walk.support_nil, + List.mem_singleton] using hv + subst v + exact ⟨a, ha, .nil _, .nil _, by simp only [length, sub_self, abs_zero, zero_add]⟩ + | @cons i z j H hH hs p ih => + rcases List.mem_cons.mp hv with hvi | hv + · subst v + exact ⟨a, ha, .nil _, .cons H hH hs p, + by simp only [length, sub_self, abs_zero, zero_add]⟩ + · obtain ⟨T, hT, q, r, hqr⟩ := ih hH hv + refine ⟨T, hT, .cons H hH hs q, r, ?_⟩ + dsimp only [length] + linarith + +/-- Split a vertical segment at a prescribed traveled length, remaining in +its closed interval. This is valid for every interval band in the paper. -/ +lemma vertical_split (hJ : Set.OrdConnected J) {a b ℓ : ℝ} + (ha : a ∈ J) (hb : b ∈ J) (hℓ : 0 ≤ ℓ) (hbound : ℓ ≤ |a - b|) : + ∃ T ∈ J, |a - T| = ℓ ∧ |T - b| = |a - b| - ℓ := by + by_cases hab : a ≤ b + · have hlen : |a - b| = b - a := by rw [abs_of_nonpos (by linarith)]; ring + refine ⟨a + ℓ, hJ.out ha hb ⟨by linarith, by rw [hlen] at hbound; linarith⟩, ?_, ?_⟩ + · rw [abs_of_nonpos (by linarith)]; ring + · rw [abs_of_nonpos (by rw [hlen] at hbound; linarith), hlen]; ring + · have hlen : |a - b| = a - b := abs_of_nonneg (by linarith) + refine ⟨a - ℓ, hJ.out hb ha ⟨by rw [hlen] at hbound; linarith, by linarith⟩, ?_, ?_⟩ + · rw [abs_of_nonneg (by linarith)]; ring + · rw [abs_of_nonneg (by rw [hlen] at hbound; linarith), hlen]; ring + +/-- Every intermediate arclength is attained on a switching path in an +interval band, by actual finite prefix and suffix paths. No abstract length +space or geodesicity hypothesis is added. -/ +lemma split_at_length (hJ : Set.OrdConnected J) (p : M.Path J i j) + {a b ℓ : ℝ} (ha : a ∈ J) (hb : b ∈ J) (hℓ : 0 ≤ ℓ) + (hbound : ℓ ≤ p.length a b) : + ∃ (k : Fin n) (T : ℝ), T ∈ J ∧ + ∃ (q : M.Path J i k) (r : M.Path J k j), + q.length a T = ℓ ∧ r.length T b = p.length a b - ℓ := by + induction p generalizing a ℓ with + | nil i => + obtain ⟨T, hT, h₁, h₂⟩ := vertical_split hJ ha hb hℓ hbound + exact ⟨i, T, hT, .nil _, .nil _, h₁, h₂⟩ + | @cons i k j H hH hs p ih => + by_cases hfirst : ℓ ≤ |a - H| + · obtain ⟨T, hT, h₁, h₂⟩ := vertical_split hJ ha hH hℓ hfirst + refine ⟨i, T, hT, .nil _, .cons H hH hs p, h₁, ?_⟩ + dsimp only [length] + rw [h₂] + ring + · have htail : ℓ - |a - H| ≤ p.length H b := by + change ℓ ≤ |a - H| + p.length H b at hbound + linarith + obtain ⟨v, T, hT, q, r, hq, hr⟩ := ih hH (by linarith) htail + refine ⟨v, T, hT, .cons H hH hs q, r, ?_, ?_⟩ + · dsimp only [length] + linarith + · dsimp only [length] + linarith + +/-- A finite switching word from outside a column set to inside it has a +crossing switch. The decomposition retains the exact metric length, including +both endpoint vertical segments. -/ +lemma crosses_set (p : M.Path J i j) (S : Set (Fin n)) (hi : i ∉ S) (hj : j ∈ S) + (a b : ℝ) : + ∃ (u v : Fin n) (H : ℝ) (_hH : H ∈ J) (_hs : H ∈ M.heights u v), + u ∉ S ∧ v ∈ S ∧ ∃ (q : M.Path J i u) (r : M.Path J v j), + q.length a H + r.length H b = p.length a b := by + classical + induction p generalizing a with + | nil => exact False.elim (hi hj) + | @cons i z j H hH hs p ih => + by_cases hz : z ∈ S + · exact ⟨i, z, H, hH, hs, hi, hz, .nil _, p, rfl⟩ + · obtain ⟨u, v, T, hT, ht, hu, hv, q, r, he⟩ := ih hz hj H + refine ⟨u, v, T, hT, ht, hu, hv, .cons H hH hs q, r, ?_⟩ + dsimp only [length] at * + linarith + +/-- Deleting a prefix up to a visited column cannot increase vertical +variation, even when the new initial height is the old initial height. -/ +lemma suffix_at_column (p : M.Path J i j) (a b : ℝ) {v : Fin n} + (hv : v ∈ p.word.support) : + ∃ r : M.Path J v j, r.word.support.Sublist p.word.support ∧ + r.length a b ≤ p.length a b := by + induction p generalizing a with + | nil i => + have hvi : v = i := by simpa only [word, SimpleGraph.Walk.support_nil, + List.mem_singleton] using hv + subst v + exact ⟨.nil _, List.Sublist.refl _, le_rfl⟩ + | @cons i z j H hH hs p ih => + rcases List.mem_cons.mp hv with hvi | hv + · subst v + exact ⟨.cons H hH hs p, List.Sublist.refl _, le_rfl⟩ + · obtain ⟨r, hr, hlen⟩ := ih H hv + refine ⟨r, hr.trans (List.sublist_cons_self _ _), ?_⟩ + exact (r.length_start_le a H b).trans (add_le_add (le_refl _) hlen) + +/-- Loop erasure with its essential metric estimate: replacing a detour by +vertical travel never increases length. The resulting word has no repeated +column, so the later minimization is over finitely many words. -/ +lemma simple_replacement (p : M.Path J i j) (a b : ℝ) : + ∃ q : M.Path J i j, q.word.IsPath ∧ q.length a b ≤ p.length a b := by + classical + induction p generalizing a with + | nil i => exact ⟨.nil i, by simp [word], le_rfl⟩ + | @cons i z j H hH hs p ih => + obtain ⟨q, hq, hlen⟩ := ih H + by_cases hi : i ∈ q.word.support + · obtain ⟨r, hr, hlenr⟩ := q.suffix_at_column H b hi + refine ⟨r, ?_, ?_⟩ + · exact SimpleGraph.Walk.IsPath.mk' (hq.support_nodup.sublist hr) + · exact (r.length_start_le a H b).trans + (add_le_add (le_refl _) (hlenr.trans hlen)) + · refine ⟨.cons H hH hs q, ?_, add_le_add (le_refl _) hlen⟩ + exact SimpleGraph.Walk.IsPath.mk' (List.nodup_cons.mpr ⟨hi, hq.support_nodup⟩) + +/-- Zero length is possible only at one common height, through switches all +available at exactly that height. -/ +lemma zero_length_identifies (p : M.Path J i j) (a b : ℝ) + (h : p.length a b = 0) : + a = b ∧ (M.activeGraph {a}).Reachable i j := by + induction p generalizing a with + | nil => + exact ⟨sub_eq_zero.mp (abs_eq_zero.mp h), .refl _⟩ + | @cons i k j H hH hs p ih => + have ht : p.length H b = 0 := by + have := p.length_nonneg H b + have := abs_nonneg (a - H) + dsimp only [length] at h + linarith + have ha : a = H := by + have hn := p.length_nonneg H b + have hz : |a - H| = 0 := by dsimp only [length] at h; linarith [abs_nonneg (a-H)] + exact sub_eq_zero.mp (abs_eq_zero.mp hz) + obtain ⟨hb, hr⟩ := ih H ht + subst a + exact ⟨hb, (show (M.activeGraph {H}).Adj i k from ⟨H, rfl, hs⟩).reachable.trans hr⟩ + +lemma exists_zero_path (H : ℝ) (hH : H ∈ J) (w : (M.activeGraph {H}).Walk i j) : + ∃ p : M.Path J i j, p.length H H = 0 := by + induction w with + | nil => exact ⟨.nil _, by simp only [length, sub_self, abs_zero]⟩ + | @cons i k j hk p ih => + obtain ⟨q, hq⟩ := ih + obtain ⟨T, hT, hs⟩ := hk + have he : T = H := hT + subst T + exact ⟨.cons H hH hs q, + by simp only [length, sub_self, abs_zero, zero_add, hq]⟩ + +end Path + +/-- A schedule specifies one allowed height for each edge of a fixed word. +This recursive finite product carries its usual compact topology when the band +is closed. -/ +def Schedule (J : Set ℝ) : {i j : Fin n} → (M.activeGraph J).Walk i j → Type + | _, _, .nil => PUnit + | _, _, @SimpleGraph.Walk.cons _ _ i k _ _ p => + ↥(M.heights i k ∩ J) × Schedule J p + +namespace Schedule + +variable {M} {J : Set ℝ} {i j : Fin n} + +noncomputable instance topology (w : (M.activeGraph J).Walk i j) : TopologicalSpace (M.Schedule J w) := by + induction w with + | nil => exact inferInstanceAs (TopologicalSpace PUnit) + | @cons i k j h p ih => + change TopologicalSpace (↥(M.heights i k ∩ J) × M.Schedule J p) + letI := ih + infer_instance + +lemma compactSpace (hJ : IsClosed J) (w : (M.activeGraph J).Walk i j) : + CompactSpace (M.Schedule J w) := by + induction w with + | nil => exact inferInstanceAs (CompactSpace PUnit) + | @cons i k j h p ih => + have hc := (M.compact i k).inter_right hJ + let : CompactSpace ↥(M.heights i k ∩ J) := isCompact_iff_compactSpace.mp hc + let := ih + exact inferInstanceAs (CompactSpace (↥(M.heights i k ∩ J) × M.Schedule J p)) + +/-- Realize a schedule as the literal switching path of the fixed word. -/ +def toPath : {i j : Fin n} → {w : (M.activeGraph J).Walk i j} → + M.Schedule J w → M.Path J i j + | i, _, .nil, _ => .nil i + | _, _, .cons _ _, s => .cons s.1.val s.1.property.2 s.1.property.1 (toPath s.2) + +lemma word_toPath {w : (M.activeGraph J).Walk i j} (s : M.Schedule J w) : + (toPath s).word = w := by + induction w with + | nil => rfl + | cons h p ih => + change SimpleGraph.Walk.cons _ (toPath s.2).word = .cons h p + rw [ih] + +def ofPath : {i j : Fin n} → (p : M.Path J i j) → M.Schedule J p.word + | _, _, .nil _ => PUnit.unit + | _, _, .cons H hH hs p => (⟨H, hs, hH⟩, ofPath p) + +lemma toPath_ofPath (p : M.Path J i j) : toPath (ofPath p) = p := by + induction p with + | nil => rfl + | cons H hH hs p ih => + change Path.cons H hH hs (toPath (ofPath p)) = _ + rw [ih] + +/-- Length is a continuous function of all endpoint and switch heights. -/ +lemma continuous_length {T : Type*} [TopologicalSpace T] + (w : (M.activeGraph J).Walk i j) (a b : T → ℝ) (s : T → M.Schedule J w) + (ha : Continuous a) (hb : Continuous b) (hs : Continuous s) : + Continuous (fun t => (toPath (s t)).length (a t) (b t)) := by + induction w generalizing a b with + | nil => exact (ha.sub hb).abs + | @cons i k j h p ih => + have hH : Continuous (fun t => ((s t).1 : ℝ)) := continuous_subtype_val.comp hs.fst + exact ((ha.sub hH).abs).add (ih _ b (fun t => (s t).2) hH hb hs.snd) + +end Schedule + +/-- Points before quotienting, in one component of the intrinsic band. -/ +structure Point (J : Set ℝ) (root : Fin n) where + column : Fin n + height : ℝ + inBand : height ∈ J + reachable : (M.activeGraph J).Reachable root column + +end Model +end Columns +end PlanarL1 + +end + +end OAI diff --git a/lean/OAI/Combinatorics/PlanarL1/CoupledState.lean b/lean/OAI/Combinatorics/PlanarL1/CoupledState.lean new file mode 100644 index 0000000000000000000000000000000000000000..c391b455a41ad6de388e77516bab119ea1a6f575 --- /dev/null +++ b/lean/OAI/Combinatorics/PlanarL1/CoupledState.lean @@ -0,0 +1,256 @@ +import OAI.Combinatorics.PlanarL1.SelectedGain +import OAI.Combinatorics.PlanarL1.FamilyPersistence + +namespace OAI + + +section + +namespace PlanarL1.Parameters +noncomputable def heightLoss (ρ : ℝ) (m : ℕ) : ℝ := + (2*ρ+2*a₁/m)/a₁+(2*ρ+2*a₂/m)/a₂ +lemma heightLoss_nonneg {ρ : ℝ} (hρ : 0≤ρ) (m : ℕ) : 0≤heightLoss ρ m := by + unfold heightLoss + apply add_nonneg + · exact div_nonneg (add_nonneg (mul_nonneg (by norm_num) hρ) + (div_nonneg (mul_nonneg (by norm_num) interpolationA.2.1.le) (Nat.cast_nonneg m))) interpolationA.2.1.le + · exact div_nonneg (add_nonneg (mul_nonneg (by norm_num) hρ) + (div_nonneg (mul_nonneg (by norm_num) interpolationB.2.1.le) (Nat.cast_nonneg m))) interpolationB.2.1.le +end PlanarL1.Parameters + +namespace PlanarL1.Columns.Model.VertexBands +open Parameters FiniteRandom +attribute [local instance] Classical.propDecidable +attribute [local irreducible] FiniteRandom.prob +variable {k : ℕ} {M : Model (k+1)} {L U : ℝ} + +def HeightPadded {m : ℕ} (c : Choices m L U M) (H ρ : ℝ) : Prop := + Tiling.Padded a₁ (shift m a₁ c.1.1) H ρ ∧ + Tiling.Padded a₂ (shift m a₂ c.1.2) H ρ + +lemma height_padding_loss (m : ℕ) (hm : 0 < m) (H : ℝ) {ρ : ℝ} (hρ : 0≤ρ) : + (geometricExecution m L U M).prob (fun c => ¬HeightPadded c H ρ)≤heightLoss ρ m := by + let P := fun h : HeightChoices m => ¬Tiling.Padded a₁ (shift m a₁ h.1) H ρ + let Q := fun h : HeightChoices m => ¬Tiling.Padded a₂ (shift m a₂ h.2) H ρ + have hp : prob P≤(2*ρ+2*a₁/m)/a₁ := by + apply prob_prod_bound_left + intro j + apply (prob_mono (Q := fun i => Tiling.NearBoundary a₁ (a₁/m*i.val) H ρ) ?_).trans + (periodic_probability m hm interpolationA.2.1 hρ H) + intro i hi + by_contra hn + exact hi (Tiling.padded_of_avoid interpolationA.2.1 hn) + have hq : prob Q≤(2*ρ+2*a₂/m)/a₂ := by + apply prob_prod_bound + intro i + apply (prob_mono (Q := fun j => Tiling.NearBoundary a₂ (a₂/m*j.val) H ρ) ?_).trans + (periodic_probability m hm interpolationB.2.1 hρ H) + intro j hj + by_contra hn + exact hj (Tiling.padded_of_avoid interpolationB.2.1 hn) + have he : (geometricExecution m L U M).prob (fun c => ¬HeightPadded c H ρ)= + prob (fun h : HeightChoices m => P h ∨ Q h) := by + unfold geometricExecution + rw [Execution.prob_bind] + simp only [Execution.prob_bind_pure,HeightPadded,not_and_or] + change Execution.uniform.mean (fun h : HeightChoices m => + Execution.uniform.prob (fun _ : RadialChoices m (shift m a₁ h.1) L U M => P h ∨ Q h))=_ + have hc (h : HeightChoices m) : + Execution.uniform.prob (fun _ : RadialChoices m (shift m a₁ h.1) L U M => P h ∨ Q h)= + if P h ∨ Q h then 1 else 0 := by + by_cases hh : P h ∨ Q h <;> simp only [Execution.prob,hh,ite_true,ite_false,Execution.mean_const] + simp_rw [hc] + calc + _ = Execution.uniform.prob (fun h : HeightChoices m => P h ∨ Q h) := by + unfold Execution.prob + congr 1 + funext h + by_cases hh : P h ∨ Q h <;> simp [hh] + _ = _ := Execution.prob_uniform _ + rw [he] + exact (prob_or_le P Q).trans (add_le_add hp hq) + +lemma conditional_persistence {β : Type*} (m : ℕ) (hm : 0 < m) (H : ℝ) + {ρ b : ℝ} (hρ : 0≤ρ) (hb : 0≤b) + (F : Choices m L U M → Execution β) (P : β → Prop) + (hF : ∀ c, HeightPadded c H ρ → (F c).prob (fun z => ¬P z)≤b) : + ((geometricExecution m L U M).bind F).prob (fun z => ¬P z)≤heightLoss ρ m+b := + (Execution.conditional_loss _ F (fun c => HeightPadded c H ρ) P hb hF).trans + (add_le_add (height_padding_loss (M := M) (L := L) (U := U) m hm H hρ) le_rfl) +end PlanarL1.Columns.Model.VertexBands + +end + + + +section + +namespace PlanarL1.Columns.Model +open MeasureTheory Parameters +open scoped NNReal +variable {k : ℕ} {M : Model (k+1)} {Ω Ξ : Type*} +variable [MeasurableSpace Ω] [MeasurableSpace Ξ] {μ : Measure Ω} {ν : Measure Ξ} + +namespace SetSystem +lemma lift_separation (S : SetSystem M Ω μ) (i j : Fin (k+1)) (H T : ℝ) : + S.lift.separation i H j T=S.separation i H j T := by + let hp := measurePreserving_fst (μ := μ) (ν := Threshold.fair) + change (∫ z : Ω × Bool, |(S.activity z.1).indicator i H-(S.activity z.1).indicator j T| ∂μ.prod Threshold.fair)=_ + have he := integral_map_of_stronglyMeasurable (μ := μ.prod Threshold.fair) hp.measurable + (((S.measurable_indicator i H).sub (S.measurable_indicator j T)).abs.stronglyMeasurable) + rw [hp.map_eq] at he + exact he.symm +end SetSystem + +namespace PairGeometry +variable {V : Type*} {A : Ambient M} {SA : OrdinaryState M kappaA Ω μ} +variable {v : V → M.Point Set.univ A.root} {x y : V} {b d : ℝ} +lemma Certificate.mono (h : Certificate A SA v (x := x) (y := y) b) (hdb : d≤b) : + Certificate A SA v (x := x) (y := y) d := by + obtain ⟨a,c,H,E,hH,hac,hsep,hE,hm,hx,hy,hn⟩ := h + exact ⟨a,c,H,E,hH,hac,hsep,hE,hdb.trans hm,hx,hy,hn⟩ +lemma Certificate.lift (h : Certificate A SA v (x := x) (y := y) b) : + Certificate A SA.lift v (x := x) (y := y) b := by + obtain ⟨a,c,H,E,hH,hac,hsep,hE,hm,hx,hy,hn⟩ := h + refine ⟨a,c,H,Prod.fst ⁻¹' E,hH,hac,hsep,hE.preimage measurable_fst,?_,?_,?_,?_⟩ + · rw [(measurePreserving_fst (μ := μ) (ν := Threshold.fair)).measureReal_preimage hE.nullMeasurableSet] + exact hm + · intro z hz; exact hx z.1 hz + · intro z hz; exact hy z.1 hz + · intro z hz; exact hn z.1 hz +end PairGeometry + +/-- The two literal cut/chart systems together with every B chart's recorded +increment history. The radius bound is an invariant, not a separation promise. -/ +structure CoupledState (A : Ambient M) (Ω Ξ : Type*) [MeasurableSpace Ω] [MeasurableSpace Ξ] + (μ : Measure Ω) (ν : Measure Ξ) (t : ℝ) where + left : OrdinaryState M kappaA Ω μ + right : BState M kappaB SecondaryGeometry.Group.lam Ξ ν + histories : BState.Histories A (c := R/200) (by norm_num [R]) (by norm_num [R]) right t + +namespace CoupledState +variable {A : Ambient M} {t : ℝ} (S : CoupledState A Ω Ξ μ ν t) +noncomputable def lift : CoupledState A (Ω × Bool) (Ξ × Bool) + (μ.prod Threshold.fair) (ν.prod Threshold.fair) t where + left := S.left.lift + right := S.right.lift + histories := S.histories.lift +noncomputable def weaken {s : ℝ} (h : s≤t) : CoupledState A Ω Ξ μ ν s where + left := S.left + right := S.right + histories := S.histories.weaken h +noncomputable def dilate {q : ℝ} (hq : 0 (E j).prob_nonneg P) (Finset.mem_univ i)) (by positivity) +lemma choose4_lower (E : Fin 4 → Execution α) (P : α → Prop) (i : Fin 4) : + (E i).prob P/4 ≤ (Execution.choose 3 E).prob P := by + convert choose_lower 3 E P i using 1 + norm_num +lemma prob_pure (x : α) (P : α → Prop) [Decidable (P x)] : + (Execution.pure x).prob P=if P x then 1 else 0 := by + classical + by_cases h : P x <;> simp only [prob,mean,h,ite_true,ite_false] +lemma prob_pure_of (x : α) (P : α → Prop) (h : P x) : (Execution.pure x).prob P=1 := by + classical + simp only [prob_pure,h,ite_true] +end PlanarL1.Execution + +namespace PlanarL1.Columns.Model.CoupledState +open MeasureTheory Parameters SecondaryGeometry VertexBands +open scoped NNReal +attribute [local instance] Classical.propDecidable +variable {k : ℕ} {M : Model (k+1)} {V Ω Ξ : Type*} +variable [MeasurableSpace Ω] [MeasurableSpace Ξ] {μ : Measure Ω} {ν : Measure Ξ} +variable {A : Ambient M} {t : ℝ} (S : CoupledState A Ω Ξ μ ν t) +variable (ht : 1≤t) (hgap : 10≤(R/200)*t) + +include hgap in +lemma cross (a : Fin (S.right.count+1)) (i : Fin ((S.histories.history a).count)) : + 10≤(R/200)*(S.histories.history a).radius i := + hgap.trans (mul_le_mul_of_nonneg_left (S.histories.older a i) (by norm_num [R])) + +abbrev Next := CoupledState A (Ω × Bool) (Ξ × Bool) + (μ.prod Threshold.fair) (ν.prod Threshold.fair) 1 + +noncomputable def unchanged : Next (A := A) (μ := μ) (ν := ν) := (S.weaken ht).lift + +variable [SFinite μ] [SFinite ν] +variable (v : V → M.Point Set.univ A.root) {L U : ℝ} +variable (hv : ∀ x, (v x).height ∈ Set.Icc L U) +variable {q : ℝ} (phaseD : MainFamily.BandComponent (M := M) q L U → ℝ) +variable {m : ℕ} (hm : 0 < m) + +noncomputable def main (omega : MainFamily.Sample phaseD m) : Next (A := A) (μ := μ) (ν := ν) where + left := MainFamily.result A S.left phaseD hm omega + right := S.right.lift + histories := (S.histories.weaken ht).lift + +variable [Fintype V] (p : ℝ) (phaseG : MainFamily.BandComponent (M := M) q L U → ℝ) +noncomputable def groups := RetainedSelection.group A S.left S.right v hv (p := p) (phaseD := phaseD) (phaseG := phaseG) + +noncomputable def secondary (omega : SecondaryGeometry.Sample (S.groups v hv phaseD p phaseG) m) : + Next (A := A) (μ := μ) (ν := ν) where + left := S.left.lift + right := SecondaryGeometry.result (S.groups v hv phaseD p phaseG) hm omega + histories := BState.SecondaryLayer.histories A (by norm_num [R]) (by norm_num [R]) + (SecondaryGeometry.layer (S.groups v hv phaseD p phaseG) hm omega) (S.histories.weaken ht) + +noncomputable def increment (sign : Fin (S.right.count+1) → Bool) : Next (A := A) (μ := μ) (ν := ν) where + left := S.left.lift + right := (IncrementStep.update A S.right S.histories.history (S.cross hgap) S.histories.recorded sign).lift + histories := (S.histories.increment sign (by norm_num : (0:ℝ)<1) le_rfl ht (by simpa using S.cross hgap) + verticalB.1 (by norm_num [kappaB,a₂]) Group.lam_bound + (by change kappaB*lambda*10≤1/8; norm_num [kappaB,a₂,lambda,R])).lift + +noncomputable def branches : Fin 4 → Execution (Next (A := A) (μ := μ) (ν := ν)) := + ![.pure (S.unchanged ht), + Execution.uniform.bind (fun omega => .pure (S.main ht phaseD hm omega)), + Execution.uniform.bind (fun omega => .pure (S.secondary ht v hv phaseD hm p phaseG omega)), + Execution.uniform.bind (fun sign => .pure (S.increment ht hgap sign))] +noncomputable def modes : Execution (Next (A := A) (μ := μ) (ν := ν)) := + .choose 3 (S.branches ht hgap v hv phaseD hm p phaseG) + +noncomputable def step : Execution (Next (A := A) (μ := μ) (ν := ν)) := + (geometricExecution m L U M).bind (fun c => + S.modes ht hgap v hv (phase D c.2.1) hm (shift m a₂ c.1.2) (phase g c.2.2)) + +end PlanarL1.Columns.Model.CoupledState + +end + +end OAI diff --git a/lean/OAI/Combinatorics/PlanarL1/Crossings.lean b/lean/OAI/Combinatorics/PlanarL1/Crossings.lean new file mode 100644 index 0000000000000000000000000000000000000000..fb4e74c2ad927de70c7e60592a38b3f7dbe04fb1 --- /dev/null +++ b/lean/OAI/Combinatorics/PlanarL1/Crossings.lean @@ -0,0 +1,1049 @@ +import OAI.Combinatorics.PlanarL1.Fields + +namespace OAI + +section + +namespace PlanarL1.ColumnOrder + +/-- The combinatorial core of overlapping traversals: a path reaching a +middle profile value intersects any path crossing that value if each switch +has small profile error. Monotonicity is needed only on their common arc. -/ +lemma overlapping_words {n : ℕ} {G : SimpleGraph (Fin n)} + (hnc : Noncrossing G) {S : Set (Fin n)} {q : Fin n → ℝ} + (hq : MonotoneOn q S) {x x' y y' i : Fin n} + (p : G.Walk x x') (r : G.Walk y y') + (hp : ∀ v ∈ p.support, v ∈ S) (hr : ∀ v ∈ r.support, v ∈ S) + (hi : i ∈ p.support) {δ : ℝ} + (hx : q x + δ < q i) (hy : q y < q i) (hy' : q i < q y') + (hs : ∀ e ∈ r.darts, |q e.fst - q e.snd| ≤ δ) : + ∃ v, v ∈ p.support ∧ v ∈ r.support := by + have order {u v : Fin n} (hu : u ∈ S) (hv : v ∈ S) (h : q u < q v) : u < v := by + by_contra hn + have := hq hv hu (le_of_not_gt hn) + linarith + have hiy : y < i := order (hr y r.start_mem_support) (hp i hi) hy + have hiy' : i < y' := order (hp i hi) (hr y' r.end_mem_support) hy' + rcases visits_or_skips r hiy hiy' with hm | ⟨e,he,hea⟩ + · exact ⟨i,hi,hm⟩ + have hef : e.fst ∈ r.support := r.dart_fst_mem_support_of_mem_darts he + have hes : e.snd ∈ r.support := r.dart_snd_mem_support_of_mem_darts he + have core (a b : Fin n) (hab : G.Adj a b) + (ha : a ∈ r.support) (hb : b ∈ r.support) + (hai : a < i) (hib : i < b) (hgap : |q a - q b| ≤ δ) : + ∃ v, v ∈ p.support ∧ v ∈ r.support := by + have hibq := hq (hp i hi) (hr b hb) hib.le + have hxa : q x < q a := by + have hh := (abs_le.mp hgap).1 + linarith + have hxa' := order (hp x p.start_mem_support) (hr a ha) hxa + let t := (p.takeUntil i hi).reverse + have hmem : ∀ v ∈ t.support, v ∈ p.support := by + intro v hv + apply (p.isSubwalk_takeUntil hi).support_subset + simpa only [t,SimpleGraph.Walk.support_reverse,List.mem_reverse] using hv + rcases chord_separation hnc hab t ⟨hai,hib⟩ (Or.inl hxa') with hm | hm + · exact ⟨a,hmem a hm,ha⟩ + · exact ⟨b,hmem b hm,hb⟩ + rcases hea with hea | hea + · exact core e.fst e.snd e.adj hef hes hea.1 hea.2 (hs e he) + · exact core e.snd e.fst e.adj.symm hes hef hea.1 hea.2 + (by simpa only [abs_sub_comm] using hs e he) + +end PlanarL1.ColumnOrder + +namespace PlanarL1.Columns.Model + +namespace Path + +variable {n : ℕ} {M : Model n} {J : Set ℝ} + +lemma exists_trace_of_mem_support {i j v : Fin n} (p : M.Path J i j) + {a b : ℝ} (hv : v ∈ p.word.support) : ∃ T, (v,T) ∈ p.trace a b := by + induction p generalizing a with + | nil i => + have he : v = i := by simpa only [word,SimpleGraph.Walk.support_nil,List.mem_singleton] using hv + subst v + exact ⟨a,rfl,Set.left_mem_uIcc⟩ + | @cons i z j H hH hs p ih => + rcases List.mem_cons.mp hv with hv | hv + · subst v + exact ⟨a,Or.inl ⟨rfl,Set.left_mem_uIcc⟩⟩ + · obtain ⟨T,hT⟩ := ih hv (a := H) + exact ⟨T,Or.inr hT⟩ + +end Path + +namespace Field + +variable {n : ℕ} {M : Model n} {J : Set ℝ} {L : NNReal} + +lemma profile_error (F : M.Field J L) {η : ℝ} + (hw : ∀ a ∈ J, ∀ b ∈ J, |a-b| ≤ η) (i : Fin n) (H T : J) : + |F.value i H - F.value i T| ≤ L*η := by + have he := (F.vertical i).dist_le_mul H T + simp only [Real.dist_eq,Subtype.dist_eq] at he + exact he.trans (mul_le_mul_of_nonneg_left (hw _ H.property _ T.property) L.coe_nonneg) + +lemma profile_switch_error (F : M.Field J L) {η : ℝ} + (hw : ∀ a ∈ J, ∀ b ∈ J, |a-b| ≤ η) (H : J) {i j : Fin n} + (hij : (M.activeGraph J).Adj i j) : + |F.value i H - F.value j H| ≤ 2*(L*η) := by + obtain ⟨T,hT,hs⟩ := hij + have hi := F.profile_error hw i H ⟨T,hT⟩ + have hj := F.profile_error hw j ⟨T,hT⟩ H + rw [← F.switch i j ⟨T,hT⟩ hs] at hj + have ht := abs_sub_le (F.value i H) (F.value i ⟨T,hT⟩) (F.value j H) + linarith + +/-- Ordered overlap with an arbitrary cut of the circular order. The same +proof applies to the other arc by negating the field and reversing paths. +Its conclusion is actual shared-column support, prior to metric estimates. -/ +lemma overlap_columns (F : M.Field J L) (hJ : Set.OrdConnected J) + (e : Fin n ≃ Fin n) (hnc : ColumnOrder.Noncrossing ((M.activeGraph J).comap e)) + (S : Set (Fin n)) (T : J) + (ho : MonotoneOn (fun i => F.value (e i) T) S) + {η u v : ℝ} (hw : ∀ a ∈ J, ∀ b ∈ J, |a-b| ≤ η) + (hgap : 8*(L*η) < v-u) + {i j k l : Fin n} (p : M.Path J i j) (r : M.Path J k l) + (a b c d : J) + (hp : ∀ z ∈ p.word.support, e.symm z ∈ S) + (hr : ∀ z ∈ r.word.support, e.symm z ∈ S) + (ha : F.value i a ≤ u) (hb : v ≤ F.value j b) + (hc : F.value k c ≤ u) (hd : v ≤ F.value l d) : + ∃ z, z ∈ p.word.support ∧ z ∈ r.word.support := by + have hη : 0 ≤ η := by simpa using hw T.val T.property T.val T.property + have hε : 0 ≤ (L : ℝ)*η := mul_nonneg L.coe_nonneg hη + have huv : u ≤ v := by linarith + obtain ⟨z,H,htrace,hmid⟩ := F.path_intermediate hJ p a b + (c := (u+v)/2) (by linarith) (by linarith) + have hz := p.trace_column htrace + let f := (SimpleGraph.Iso.comap e (M.activeGraph J)).symm.toHom + let P := p.word.map f + let Q := r.word.map f + have mem {x y : Fin n} (w : (M.activeGraph J).Walk x y) {z : Fin n} + (hz : z ∈ (w.map f).support) : e z ∈ w.support := by + obtain ⟨t,ht,he⟩ := List.mem_map.mp (by simpa only [SimpleGraph.Walk.support_map] using hz) + change e.symm t = z at he + simpa only [← he,e.apply_symm_apply] using ht + have hpS : ∀ z ∈ P.support, z ∈ S := by + intro z hz + have := hp (e z) (mem p.word hz) + simpa only [e.symm_apply_apply] using this + have hrS : ∀ z ∈ Q.support, z ∈ S := by + intro z hz + have := hr (e z) (mem r.word hz) + simpa only [e.symm_apply_apply] using this + have hzP : e.symm z ∈ P.support := by + rw [SimpleGraph.Walk.support_map] + exact List.mem_map.mpr ⟨z,hz,rfl⟩ + have ep := F.profile_error hw i a T + have ez := F.profile_error hw z H T + have er := F.profile_error hw k c T + have er' := F.profile_error hw l d T + rw [hmid] at ez + obtain ⟨t,htP,htQ⟩ := ColumnOrder.overlapping_words hnc ho P Q hpS hrS hzP + (δ := 2*(L*η)) + (by change F.value (e (e.symm i)) T + _ < F.value (e (e.symm z)) T + simp only [e.apply_symm_apply]; have := (abs_le.mp ep).1 + have := (abs_le.mp ez).2; linarith) + (by change F.value (e (e.symm k)) T < F.value (e (e.symm z)) T + simp only [e.apply_symm_apply]; have := (abs_le.mp er).1 + have := (abs_le.mp ez).2; linarith) + (by change F.value (e (e.symm z)) T < F.value (e (e.symm l)) T + simp only [e.apply_symm_apply]; have := (abs_le.mp er').2 + have := (abs_le.mp ez).1; linarith) + (by intro edge _; exact F.profile_switch_error hw T edge.adj) + exact ⟨e t,mem p.word htP,mem r.word htQ⟩ + +end Field +end PlanarL1.Columns.Model + +namespace PlanarL1.ColumnOrder + +/-- Stop at the first vertex outside a set. The constructed walk consists +only of original visited columns, and its last step crosses the set boundary. -/ +lemma first_exit {V : Type*} {G : SimpleGraph V} {S : Set V} {x y : V} + (p : G.Walk x y) (hx : x ∈ S) (hy : y ∉ S) : + ∃ a b, G.Adj a b ∧ a ∈ S ∧ b ∉ S ∧ + ∃ r : G.Walk x b, + (∀ v ∈ r.support, v ∈ p.support) ∧ + (∀ v ∈ r.support, v ∈ S ∨ v = b) := by + induction p with + | nil => exact False.elim (hy hx) + | @cons x z y hxz p ih => + by_cases hz : z ∈ S + · obtain ⟨a,b,hab,ha,hb,r,hr,hS⟩ := ih hz hy + refine ⟨a,b,hab,ha,hb,r.cons hxz,?_,?_⟩ + · intro v hv + rcases List.mem_cons.mp hv with hv | hv + · exact List.mem_cons.mpr (Or.inl hv) + · exact List.mem_cons_of_mem _ (hr v hv) + · intro v hv + rcases List.mem_cons.mp hv with hv | hv + · exact Or.inl (hv ▸ hx) + · exact hS v hv + · refine ⟨x,z,hxz,hx,hz,(.nil : G.Walk z z).cons hxz,?_,?_⟩ + · intro v hv + rcases List.mem_cons.mp hv with hv | hv + · exact List.mem_cons.mpr (Or.inl hv) + · have he : v = z := by simpa only [SimpleGraph.Walk.support_nil,List.mem_singleton] using hv + exact List.mem_cons_of_mem _ (he ▸ p.start_mem_support) + · intro v hv + rcases List.mem_cons.mp hv with hv | hv + · exact Or.inl (hv ▸ hx) + · right + simpa only [SimpleGraph.Walk.support_nil,List.mem_singleton] using hv + +/-- A discrete traversal of a value band. Every visited column lies in the +band enlarged by one switch error; no continuous path-parameter choice or +first/last hitting time is postulated. -/ +lemma traverse_band {V : Type*} {G : SimpleGraph V} (q : V → ℝ) {δ u v : ℝ} + (hδ : 0 ≤ δ) (huv : u < v) (hedge : ∀ {a b}, G.Adj a b → |q a-q b| ≤ δ) + {x y : V} (p : G.Walk x y) (hx : q x ≤ u) (hy : v ≤ q y) : + ∃ a b, ∃ r : G.Walk a b, + q a ≤ u ∧ v ≤ q b ∧ + (∀ z ∈ r.support, z ∈ p.support) ∧ + (∀ z ∈ r.support, u-δ ≤ q z ∧ q z ≤ v+δ) := by + obtain ⟨a,b,hab,ha,hb,s,hs,hS⟩ := first_exit p + (S := {z | q z < v}) (by dsimp; linarith) (by dsimp; linarith) + change q a < v at ha + change ¬q b < v at hb + have hb' : v ≤ q b := le_of_not_gt hb + have hbup : q b ≤ v+δ := by + have := (abs_le.mp (hedge hab)).1 + linarith + have hsupper (z) (hz : z ∈ s.support) : q z ≤ v+δ := by + rcases hS z hz with hz | rfl + · change q z < v at hz + linarith + · exact hbup + obtain ⟨c,d,hcd,hc,hd,t,ht,hT⟩ := first_exit s.reverse + (S := {z | u < q z}) (by dsimp; linarith) (by dsimp; linarith) + change u < q c at hc + change ¬u < q d at hd + have hd' : q d ≤ u := le_of_not_gt hd + have hdlow : u-δ ≤ q d := by + have := (abs_le.mp (hedge hcd)).2 + linarith + refine ⟨d,b,t.reverse,hd',hb',?_,?_⟩ + · intro z hz + have hzt : z ∈ t.support := by simpa only [SimpleGraph.Walk.support_reverse,List.mem_reverse] using hz + have hzs : z ∈ s.support := by simpa only [SimpleGraph.Walk.support_reverse,List.mem_reverse] using ht z hzt + exact hs z hzs + · intro z hz + have hzt : z ∈ t.support := by simpa only [SimpleGraph.Walk.support_reverse,List.mem_reverse] using hz + have hzs : z ∈ s.support := by simpa only [SimpleGraph.Walk.support_reverse,List.mem_reverse] using ht z hzt + refine ⟨?_,hsupper z hzs⟩ + rcases hT z hzt with hz | rfl + · change u < q z at hz + linarith + · exact hdlow + +end PlanarL1.ColumnOrder + +namespace PlanarL1.Columns.Model + +namespace Path + +variable {n : ℕ} {M : Model n} {I J : Set ℝ} + +/-- The same finite path is permitted in a larger band. -/ +def widen (hJI : J ⊆ I) {i j : Fin n} : M.Path J i j → M.Path I i j + | .nil i => .nil i + | .cons H hH hs p => .cons H (hJI hH) hs (widen hJI p) + +lemma length_widen (hJI : J ⊆ I) {i j : Fin n} (p : M.Path J i j) (a b : ℝ) : + (p.widen hJI).length a b = p.length a b := by + induction p generalizing a with + | nil => rfl + | cons H hH hs p ih => simp only [widen,length,ih] + +end Path + +namespace Point + +variable {n : ℕ} {M : Model n} {I J : Set ℝ} {root : Fin n} + +/-- Geometric control of visits to a set of columns. The witnesses are actual +points at heights in J and actual ambient-band distances from the center. -/ +def NearColumns (x : M.Point I root) (J : Set ℝ) (A : ℝ) (S : Set (Fin n)) : Prop := + ∀ v ∈ S, ∃ z : M.Point I root, z.column = v ∧ z.height ∈ J ∧ dist x z ≤ A + +lemma NearColumns.mono {x : M.Point I root} {A : ℝ} {S T : Set (Fin n)} + (h : x.NearColumns J A S) (hTS : T ⊆ S) : x.NearColumns J A T := + fun v hv => h v (hTS hv) + +lemma NearColumns.union {x : M.Point I root} {A : ℝ} {S T : Set (Fin n)} + (hS : x.NearColumns J A S) (hT : x.NearColumns J A T) : + x.NearColumns J A (S ∪ T) := fun v hv => hv.elim (hS v) (hT v) + +/-- Every visited column of a path of length A from x has a point genuinely +reachable within A, even when the ambient metric permits leaving J. -/ +lemma near_path (hJI : J ⊆ I) (x : M.Point I root) (hx : x.height ∈ J) + {j : Fin n} (p : M.Path J x.column j) {H A : ℝ} (hH : H ∈ J) + (hA : p.length x.height H ≤ A) : + x.NearColumns J A {v | v ∈ p.word.support} := by + intro v hv + obtain ⟨T,hT,q,r,hqr⟩ := p.split_at_column hx hH hv + let z : M.Point I root := ⟨v,T,hJI hT,x.reachable.trans (q.widen hJI).word.reachable⟩ + refine ⟨z,rfl,hT,?_⟩ + have hd := x.distance_le z (q.widen hJI) + rw [Path.length_widen] at hd + have hn := r.length_nonneg T H + change x.distance z ≤ A + dsimp only [z] at hd + linarith + +/-- Metric completion of the overlapping-traversal argument. Only one +vertical transfer is needed, hence eta rather than the source's 2 eta. -/ +lemma dist_le_of_near_intersection (x y : M.Point I root) {A B η : ℝ} + {S T : Set (Fin n)} (hx : x.NearColumns J A S) (hy : y.NearColumns J B T) + (hw : ∀ a ∈ J, ∀ b ∈ J, |a-b| ≤ η) {v : Fin n} (hvS : v ∈ S) (hvT : v ∈ T) : + dist x y ≤ A+B+η := by + obtain ⟨z,hz,hzJ,hxz⟩ := hx v hvS + obtain ⟨w,hwv,hwJ,hyw⟩ := hy v hvT + have he := Point.dist_same_column z w (hz.trans hwv.symm) + have hd := hw z.height hzJ w.height hwJ + have h₁ := dist_triangle x z y + have h₂ := dist_triangle z w y + rw [dist_comm w y] at h₂ + linarith + +end Point +end PlanarL1.Columns.Model + +namespace PlanarL1.ColumnOrder + +/-- A crosslink joining the two monotone arcs separates all strict lower +profile values from all strict upper values. This uses noncrossing of the +ambient graph, not an assumed connectivity of a scalar level set. -/ +lemma ordered_chord_barrier {n : ℕ} {G : SimpleGraph (Fin n)} + (hnc : Noncrossing G) (f : Fin n → ℝ) (m : Fin n) + (hleft : ∀ i j, i ≤ j → j ≤ m → f i ≤ f j) + (hright : ∀ i j, m ≤ i → i ≤ j → f j ≤ f i) + {a b x y : Fin n} (ham : a ≤ m) (hmb : m ≤ b) + (hab : G.Adj a b) (heq : f a = f b) + (p : G.Walk x y) (hx : f x < f a) (hy : f a < f y) : + a ∈ p.support ∨ b ∈ p.support := by + have hay : a < y := by + by_contra hn + have := hleft y a (le_of_not_gt hn) ham + linarith + have hyb : y < b := by + by_contra hn + have := hright b y hmb (le_of_not_gt hn) + linarith + have hside : x < a ∨ b < x := by + by_cases hxm : x ≤ m + · left + by_contra hn + have := hleft a x (le_of_not_gt hn) hxm + linarith + · right + by_contra hn + have := hright x b (le_of_not_ge hxm) (le_of_not_gt hn) + linarith + have hc := chord_separation hnc hab p.reverse ⟨hay,hyb⟩ hside + simpa only [SimpleGraph.Walk.support_reverse,List.mem_reverse] using hc + +end PlanarL1.ColumnOrder + +namespace PlanarL1.Columns.Model.Field + +variable {k : ℕ} {M : Model (k + 1)} {I J : Set ℝ} {L : NNReal} + +lemma ordered_maximum (F : M.Field I L) {a b : Fin (k+1)} (ho : F.OrderedFrom a b) + (H : I) (i : Fin (k+1)) : F.value i H ≤ F.value b H := by + let e := finCycle a + rcases le_total (e.symm i) (e.symm b) with hi | hi + · simpa only [e,Equiv.apply_symm_apply] using ho.2.1 H (e.symm i) (e.symm b) hi le_rfl + · simpa only [e,Equiv.apply_symm_apply] using ho.2.2 H (e.symm b) (e.symm i) le_rfl hi + +lemma arcSign_one_lt {a b i : Fin (k+1)} (h : arcSign a b i = 1) : + (finCycle a).symm i < (finCycle a).symm b := by + unfold arcSign at h + split_ifs at h with hbd hlt + · norm_num at h + · exact hlt + · norm_num at h + +lemma arcSign_neg_one_gt {a b i : Fin (k+1)} (h : arcSign a b i = -1) : + (finCycle a).symm b < (finCycle a).symm i := by + unfold arcSign at h + split_ifs at h with hbd hlt + · norm_num at h + · norm_num at h + · have hib : i ≠ b := fun he => hbd (Or.inr he) + have he : (finCycle a).symm i ≠ (finCycle a).symm b := fun he => hib ((finCycle a).symm.injective he) + exact lt_of_le_of_ne (le_of_not_gt hlt) (Ne.symm he) + +/-- Actual crosslink barrier for arbitrary finite paths in any band. The +crosslink itself may be outside that band, as required by the empty-wall +rectangle argument. -/ +lemma crosslink_barrier (F : M.Field I L) {a b : Fin (k+1)} (ho : F.OrderedFrom a b) + (H : I) {u v : Fin (k+1)} (hs : H.val ∈ M.heights u v) + (hu : arcSign a b u = 1) (hv : arcSign a b v = -1) + {x y : Fin (k+1)} (p : (M.activeGraph J).Walk x y) + (hx : F.value x H < F.value u H) (hy : F.value u H < F.value y H) : + u ∈ p.support ∨ v ∈ p.support := by + let e := finCycle a + let f := (SimpleGraph.Iso.comap e M.link).symm.toHom + let q := (p.mapLe (M.active_subgraph J)).map f + have hnc := ColumnOrder.noncrossing_comap_cycle M.noncrossing a + have heq : F.value (e (e.symm u)) H = F.value (e (e.symm v)) H := by + simpa only [e.apply_symm_apply] using F.switch u v H hs + have hc := ColumnOrder.ordered_chord_barrier hnc (fun i => F.value (e i) H) (e.symm b) + (ho.2.1 H) (ho.2.2 H) (arcSign_one_lt hu).le (arcSign_neg_one_gt hv).le + (a := e.symm u) (b := e.symm v) (by change M.link.Adj (e (e.symm u)) (e (e.symm v)); simpa only [e.apply_symm_apply] using M.permitted u v H.val hs) + heq q + (by change F.value (e (e.symm x)) H < F.value (e (e.symm u)) H; simpa only [e.apply_symm_apply] using hx) + (by change F.value (e (e.symm u)) H < F.value (e (e.symm y)) H; simpa only [e.apply_symm_apply] using hy) + have mem (z : Fin (k+1)) (hz : e.symm z ∈ q.support) : z ∈ p.support := by + rw [SimpleGraph.Walk.support_map,SimpleGraph.Walk.support_mapLe_eq_support,List.mem_map] at hz + obtain ⟨w,hw,he⟩ := hz + have hwe : w = z := e.symm.injective he + exact hwe ▸ hw + exact hc.elim (fun h => Or.inl (mem u h)) (fun h => Or.inr (mem v h)) + +end PlanarL1.Columns.Model.Field + +namespace PlanarL1.Columns.Model.Point + +variable {n : ℕ} {M : Model n} {I J : Set ℝ} {root : Fin n} + +/-- Two controlled column sets each hitting an endpoint of the same actual +link can be joined through that link at its prescribed height. -/ +lemma dist_le_of_near_link (x y : M.Point I root) {A B D H : ℝ} + {S T : Set (Fin n)} (hx : x.NearColumns J A S) (hy : y.NearColumns J B T) + (hD : ∀ t ∈ J, |t-H| ≤ D) (hH : H ∈ I) + {u v : Fin n} (hlink : H ∈ M.heights u v) + (hp : u ∈ S ∨ v ∈ S) (hq : u ∈ T ∨ v ∈ T) : + dist x y ≤ A+B+2*D := by + have core (z w : M.Point I root) (hz : z.height ∈ J) (hw : w.height ∈ J) + (hxz : dist x z ≤ A) (hyw : dist y w ≤ B) + (hzw : z.column = w.column ∨ H ∈ M.heights z.column w.column) : + dist x y ≤ A+B+2*D := by + have hd : dist z w ≤ 2*D := by + rcases hzw with hzw | hzw + · rw [Point.dist_same_column z w hzw] + have he := abs_sub_le z.height H w.height + have hzD := hD z.height hz + have hwD := hD w.height hw + rw [abs_sub_comm H w.height] at he + linarith + · have he := z.dist_le_switch w hH hzw + have hzD := hD z.height hz + have hwD := hD w.height hw + rw [abs_sub_comm H w.height] at he + linarith + have ht := dist_triangle x z y + have ht' := dist_triangle z w y + rw [dist_comm w y] at ht' + linarith + rcases hp with hp | hp <;> rcases hq with hq | hq + · obtain ⟨z,hz,hzJ,hxz⟩ := hx u hp + obtain ⟨w,hw,hwJ,hyw⟩ := hy u hq + exact core z w hzJ hwJ hxz hyw (Or.inl (hz.trans hw.symm)) + · obtain ⟨z,hz,hzJ,hxz⟩ := hx u hp + obtain ⟨w,hw,hwJ,hyw⟩ := hy v hq + exact core z w hzJ hwJ hxz hyw (Or.inr (by simpa only [hz,hw] using hlink)) + · obtain ⟨z,hz,hzJ,hxz⟩ := hx v hp + obtain ⟨w,hw,hwJ,hyw⟩ := hy u hq + exact core z w hzJ hwJ hxz hyw (Or.inr (by simpa only [hz,hw,M.symm v u] using hlink)) + · obtain ⟨z,hz,hzJ,hxz⟩ := hx v hp + obtain ⟨w,hw,hwJ,hyw⟩ := hy v hq + exact core z w hzJ hwJ hxz hyw (Or.inl (hz.trans hw.symm)) + +end PlanarL1.Columns.Model.Point + +namespace PlanarL1.Columns.Model.Field + +variable {k : ℕ} {M : Model (k+1)} {I J : Set ℝ} {L : NNReal} {root : Fin (k+1)} + +/-- Empty-wall rectangle, in its geometric form before inserting the source +constants. A hypothetical wall point between both controlled traversals +creates a quantitatively short ambient path. -/ +lemma wall_traversal_distance (F : M.Field I L) {a b : Fin (k+1)} + (ho : F.OrderedFrom a b) (H : I) {c A B D : ℝ} + (hw : (c,H.val) ∈ F.wall a b) + (x y : M.Point I root) {x₀ x₁ y₀ y₁ : Fin (k+1)} + (p : (M.activeGraph J).Walk x₀ x₁) (q : (M.activeGraph J).Walk y₀ y₁) + (hp : x.NearColumns J A {v | v ∈ p.support}) + (hq : y.NearColumns J B {v | v ∈ q.support}) + (hD : ∀ t ∈ J, |t-H.val| ≤ D) + (hx₀ : F.value x₀ H < c) (hx₁ : c < F.value x₁ H) + (hy₀ : F.value y₀ H < c) (hy₁ : c < F.value y₁ H) : + dist x y ≤ A+B+2*D := by + rcases hw with ⟨T,he⟩ | ⟨T,he⟩ | ⟨u,v,T,hs,hu,hv,he⟩ + · have hT : T = H := Subtype.ext (congrArg Prod.snd he).symm + subst T + have hc : c = F.value a H := congrArg Prod.fst he + have := ho.1 H x₀ + exfalso + linarith + · have hT : T = H := Subtype.ext (congrArg Prod.snd he).symm + subst T + have hc : c = F.value b H := congrArg Prod.fst he + have := F.ordered_maximum ho H x₁ + exfalso + linarith + · have hT : T = H := Subtype.ext (congrArg Prod.snd he).symm + subst T + have hc : c = F.value u H := congrArg Prod.fst he + have hpu := F.crosslink_barrier ho H hs hu hv p (by rwa [← hc]) (by rwa [← hc]) + have hqu := F.crosslink_barrier ho H hs hu hv q (by rwa [← hc]) (by rwa [← hc]) + exact x.dist_le_of_near_link y hp hq hD H.property hs hpu hqu + +end PlanarL1.Columns.Model.Field + +namespace PlanarL1.Columns.Model.Field + +variable {n : ℕ} {M : Model n} {I J : Set ℝ} {L : NNReal} {root : Fin n} + +abbrev eval (F : M.Field I L) (z : M.Point I root) : ℝ := + F.value z.column ⟨z.height,z.inBand⟩ + +/-- The genuine pair of short low/high paths in : no scalar +separation or arc conclusion is included as an assumption. -/ +structure Excursions (F : M.Field I L) (hJI : J ⊆ I) (z : M.Point I root) (A ε : ℝ) where + inBand : z.height ∈ J + lowColumn : Fin n + highColumn : Fin n + lowHeight : J + highHeight : J + lowPath : M.Path J z.column lowColumn + highPath : M.Path J z.column highColumn + lowLength : lowPath.length z.height lowHeight.val ≤ A + highLength : highPath.length z.height highHeight.val ≤ A + lowValue : F.value lowColumn ⟨lowHeight.val,hJI lowHeight.property⟩ < F.eval z - ε + highValue : F.eval z + ε < F.value highColumn ⟨highHeight.val,hJI highHeight.property⟩ + +namespace Excursions + +variable {F : M.Field I L} {hJI : J ⊆ I} {z : M.Point I root} {A ε : ℝ} + +def traversal (E : F.Excursions hJI z A ε) : + (M.activeGraph J).Walk E.lowColumn E.highColumn := + E.lowPath.word.reverse.append E.highPath.word + +lemma near_traversal (E : F.Excursions hJI z A ε) : + z.NearColumns J A {v | v ∈ E.traversal.support} := by + have hlo := z.near_path hJI E.inBand E.lowPath E.lowHeight.property E.lowLength + have hhi := z.near_path hJI E.inBand E.highPath E.highHeight.property E.highLength + intro v hv + rcases (SimpleGraph.Walk.mem_support_append_iff _ _).mp hv with hv | hv + · exact hlo v (by + change v ∈ E.lowPath.word.support + simpa only [SimpleGraph.Walk.support_reverse,List.mem_reverse] using hv) + · exact hhi v hv + +lemma low_profile (E : F.Excursions hJI z A ε) (H : I) {D : ℝ} + (hD : ∀ t ∈ J, |t-H.val| ≤ D) : + F.value E.lowColumn H < F.eval z - ε + L*D := by + have h := (F.vertical E.lowColumn).dist_le_mul + (⟨E.lowHeight.val,hJI E.lowHeight.property⟩ : I) H + simp only [Real.dist_eq,Subtype.dist_eq] at h + have h' := h.trans (mul_le_mul_of_nonneg_left (hD _ E.lowHeight.property) L.coe_nonneg) + have h'' := (abs_le.mp h').1 + linarith [E.lowValue] + +lemma high_profile (E : F.Excursions hJI z A ε) (H : I) {D : ℝ} + (hD : ∀ t ∈ J, |t-H.val| ≤ D) : + F.eval z + ε - L*D < F.value E.highColumn H := by + have h := (F.vertical E.highColumn).dist_le_mul + (⟨E.highHeight.val,hJI E.highHeight.property⟩ : I) H + simp only [Real.dist_eq,Subtype.dist_eq] at h + have h' := h.trans (mul_le_mul_of_nonneg_left (hD _ E.highHeight.property) L.coe_nonneg) + have h'' := (abs_le.mp h').2 + linarith [E.highValue] + +end Excursions + +/-- The closed wall-free rectangle with the manuscript's exact numerical +margins, uniform in every field, every finite column model and every size. -/ +lemma empty_rectangle {k : ℕ} {M : Model (k+1)} {I J : Set ℝ} {root : Fin (k+1)} + (F : M.Field I 4) {a b : Fin (k+1)} (ho : F.OrderedFrom a b) + {R η : ℝ} (hR : 0 < R) (hη : η ≤ R/1000000) + (hJI : J ⊆ I) (hw : ∀ s ∈ J, ∀ t ∈ J, |s-t| ≤ η) + (x y : M.Point I root) + (Ex : F.Excursions hJI x (2*R) (2*R/5)) + (Ey : F.Excursions hJI y (2*R) (2*R/5)) + (hclose : |F.eval x-F.eval y| ≤ R/1000) + (hfar : 4*R+2*(R/50+η) < dist x y) + (H : I) {c : ℝ} (hc : |c-F.eval x| ≤ R/5) (hH : |H.val-x.height| ≤ R/50) : + (c,H.val) ∉ F.wall a b := by + intro hwall + have hD : ∀ t ∈ J, |t-H.val| ≤ R/50+η := by + intro t ht + have h := abs_sub_le t x.height H.val + have h' := hw t ht x.height Ex.inBand + rw [abs_sub_comm x.height H.val] at h + linarith + have hxlo := Ex.low_profile H hD + have hxhi := Ex.high_profile H hD + have hylo := Ey.low_profile H hD + have hyhi := Ey.high_profile H hD + have hcv := abs_le.mp hc + have hxy := abs_le.mp hclose + norm_num only [NNReal.coe_ofNat] at hxlo hxhi hylo hyhi + have hd := F.wall_traversal_distance ho H hwall x y Ex.traversal Ey.traversal + Ex.near_traversal Ey.near_traversal hD + (by linarith) (by linarith) (by linarith) (by linarith) + linarith + +/-- Quantitative wall avoidance implies an infimum-distance bound at any +center whose max-norm ball fits into the verified empty rectangle. -/ +lemma infDist_lower_of_rectangle {k : ℕ} {M : Model (k+1)} {I : Set ℝ} {L : NNReal} + (F : M.Field I L) (a b : Fin (k+1)) (T : I) + {s h U V r : ℝ} + (hempty : ∀ (c : ℝ) (H : I), |c-s| ≤ U → |H.val-h| ≤ V → (c,H.val) ∉ F.wall a b) + (i : Fin (k+1)) (hU : |F.value i T-s|+r ≤ U) (hV : |T.val-h|+r ≤ V) : + r ≤ Metric.infDist (F.value i T,T.val) (F.wall a b) := by + apply (Metric.le_infDist (F.wall_nonempty a b T)).mpr + intro z hz + by_contra hn + have hd : dist (F.value i T,T.val) z < r := lt_of_not_ge hn + rw [Prod.dist_eq,Real.dist_eq,Real.dist_eq,max_lt_iff] at hd + have hzu : |z.1-s| ≤ U := by + have ht := abs_sub_le z.1 (F.value i T) s + rw [abs_sub_comm z.1 (F.value i T)] at ht + linarith + have hzv : |z.2-h| ≤ V := by + have ht := abs_sub_le z.2 T.val h + rw [abs_sub_comm z.2 T.val] at ht + linarith + have hzI : z.2 ∈ I := by + rcases hz with ⟨H,rfl⟩ | ⟨H,rfl⟩ | ⟨u,v,H,_,_,_,rfl⟩ <;> exact H.property + exact hempty z.1 ⟨z.2,hzI⟩ hzu hzv hz + +end PlanarL1.Columns.Model.Field + +namespace PlanarL1.ColumnOrder + +/-- Discrete profile intervals suffice for overlap. The midpoint visit is +constructed by stopping at the first exiting column, including its switch error. -/ +lemma overlapping_ranges {n : ℕ} {G : SimpleGraph (Fin n)} (hnc : Noncrossing G) + {S : Set (Fin n)} {q : Fin n → ℝ} (hq : MonotoneOn q S) + {δ u v : ℝ} (hgap : 2*δ < v-u) + (hedge : ∀ {a b}, G.Adj a b → |q a-q b| ≤ δ) + {x x' y y' : Fin n} (p : G.Walk x x') (r : G.Walk y y') + (hp : ∀ z ∈ p.support, z ∈ S) (hr : ∀ z ∈ r.support, z ∈ S) + (hx : q x ≤ u) (hx' : v ≤ q x') (hy : q y ≤ u) (hy' : v ≤ q y') + (hδ : 0 ≤ δ) : ∃ z, z ∈ p.support ∧ z ∈ r.support := by + obtain ⟨a,b,hab,ha,hb,t,ht,_⟩ := first_exit p + (S := {z | q z < (u+v)/2}) (by dsimp; linarith) (by dsimp; linarith) + change q a < (u+v)/2 at ha + change ¬q b < (u+v)/2 at hb + have hb' : (u+v)/2 ≤ q b := le_of_not_gt hb + have hbup : q b < (u+v)/2+δ := by + have := (abs_le.mp (hedge hab)).1 + linarith + exact overlapping_words hnc hq p r hp hr (ht b t.end_mem_support) + (by linarith) (by linarith) (by linarith) (fun e _ => hedge e.adj) + +lemma overlapping_ranges_anti {n : ℕ} {G : SimpleGraph (Fin n)} (hnc : Noncrossing G) + {S : Set (Fin n)} {q : Fin n → ℝ} (hq : AntitoneOn q S) + {δ u v : ℝ} (hgap : 2*δ < v-u) + (hedge : ∀ {a b}, G.Adj a b → |q a-q b| ≤ δ) + {x x' y y' : Fin n} (p : G.Walk x x') (r : G.Walk y y') + (hp : ∀ z ∈ p.support, z ∈ S) (hr : ∀ z ∈ r.support, z ∈ S) + (hx : q x ≤ u) (hx' : v ≤ q x') (hy : q y ≤ u) (hy' : v ≤ q y') + (hδ : 0 ≤ δ) : ∃ z, z ∈ p.support ∧ z ∈ r.support := by + have hmono : MonotoneOn (fun z => -q z) S := by + intro i hi j hj hij + exact neg_le_neg (hq hi hj hij) + have he {a b} (h : G.Adj a b) : |(-q a)-(-q b)| ≤ δ := by + simpa only [neg_sub_neg,abs_sub_comm] using hedge h + have hp' : ∀ z ∈ p.reverse.support, z ∈ S := by simpa only [SimpleGraph.Walk.support_reverse,List.mem_reverse] + have hr' : ∀ z ∈ r.reverse.support, z ∈ S := by simpa only [SimpleGraph.Walk.support_reverse,List.mem_reverse] + obtain ⟨z,hz,hz'⟩ := overlapping_ranges hnc hmono (u := -v) (v := -u) + (by linarith) he p.reverse r.reverse hp' hr' + (by linarith) (by linarith) (by linarith) (by linarith) hδ + exact ⟨z,by simpa only [SimpleGraph.Walk.support_reverse,List.mem_reverse] using hz, + by simpa only [SimpleGraph.Walk.support_reverse,List.mem_reverse] using hz'⟩ + +lemma walk_label_const {V K : Type*} {G : SimpleGraph V} {S : Set V} (label : V → K) + (hedge : ∀ {a b}, G.Adj a b → a ∈ S → b ∈ S → label a = label b) + {x y : V} (p : G.Walk x y) (hp : ∀ v ∈ p.support, v ∈ S) : + ∀ v ∈ p.support, label v = label x := by + induction p with + | @nil x => + intro v hv + have hv' : v = x := by simpa using hv + subst v + rfl + | @cons x z y hxz p ih => + have hp' : ∀ v ∈ p.support, v ∈ S := fun v hv => hp v (List.mem_cons_of_mem x hv) + intro v hv + rcases List.mem_cons.mp hv with rfl | hv + · rfl + · exact (ih hp' v hv).trans (hedge hxz (hp x (List.mem_cons_self ..)) + (hp' z p.start_mem_support)).symm + +end PlanarL1.ColumnOrder + +namespace PlanarL1.Columns.Model.Field + +variable {k : ℕ} {M : Model (k+1)} {I J : Set ℝ} {L : NNReal} + +/-- Profile overlap on either open arc; the cyclic relabelling and the +antitone second arc are both explicit. -/ +lemma same_arc_overlap (F : M.Field I L) {a b : Fin (k+1)} + (ho : F.OrderedFrom a b) (H : I) {δ u v σ : ℝ} + (hσ : σ = 1 ∨ σ = -1) (hδ : 0 ≤ δ) (hgap : 2*δ < v-u) + (hedge : ∀ {i j}, (M.activeGraph J).Adj i j → |F.value i H-F.value j H| ≤ δ) + {x x' y y' : Fin (k+1)} (p : (M.activeGraph J).Walk x x') + (r : (M.activeGraph J).Walk y y') + (hp : ∀ z ∈ p.support, arcSign a b z = σ) + (hr : ∀ z ∈ r.support, arcSign a b z = σ) + (hx : F.value x H ≤ u) (hx' : v ≤ F.value x' H) + (hy : F.value y H ≤ u) (hy' : v ≤ F.value y' H) : + ∃ z, z ∈ p.support ∧ z ∈ r.support := by + let e := finCycle a + let f := (SimpleGraph.Iso.comap e (M.activeGraph J)).symm.toHom + let P := p.map f + let Q := r.map f + let S : Set (Fin (k+1)) := {i | arcSign a b (e i) = σ} + have mem {i j : Fin (k+1)} (t : (M.activeGraph J).Walk i j) {z} + (hz : z ∈ (t.map f).support) : e z ∈ t.support := by + rw [SimpleGraph.Walk.support_map,List.mem_map] at hz + obtain ⟨w,hw,rfl⟩ := hz + change e (e.symm w) ∈ t.support + simpa only [e.apply_symm_apply] using hw + have hP : ∀ z ∈ P.support, z ∈ S := fun z hz => hp _ (mem p hz) + have hQ : ∀ z ∈ Q.support, z ∈ S := fun z hz => hr _ (mem r hz) + have he {i j} (h : ((M.activeGraph J).comap e).Adj i j) : + |F.value (e i) H-F.value (e j) H| ≤ δ := hedge h + have hx0 : F.value (e (e.symm x)) H ≤ u := by simpa only [e.apply_symm_apply] using hx + have hx1 : v ≤ F.value (e (e.symm x')) H := by simpa only [e.apply_symm_apply] using hx' + have hy0 : F.value (e (e.symm y)) H ≤ u := by simpa only [e.apply_symm_apply] using hy + have hy1 : v ≤ F.value (e (e.symm y')) H := by simpa only [e.apply_symm_apply] using hy' + have hnc := ColumnOrder.noncrossing_comap_cycle (M.active_noncrossing J) a + have hit : ∃ z, z ∈ P.support ∧ z ∈ Q.support := by + rcases hσ with rfl | rfl + · have hmono : MonotoneOn (fun i => F.value (e i) H) S := by + intro i hi j hj hij + have hjb := arcSign_one_lt hj + simp only [e,Equiv.symm_apply_apply] at hjb + exact ho.2.1 H i j hij hjb.le + exact ColumnOrder.overlapping_ranges hnc hmono hgap he P Q hP hQ hx0 hx1 hy0 hy1 hδ + · have hanti : AntitoneOn (fun i => F.value (e i) H) S := by + intro i hi j hj hij + have hib := arcSign_neg_one_gt hi + simp only [e,Equiv.symm_apply_apply] at hib + exact ho.2.2 H i j hib.le hij + exact ColumnOrder.overlapping_ranges_anti hnc hanti hgap he P Q hP hQ hx0 hx1 hy0 hy1 hδ + obtain ⟨z,hz,hz'⟩ := hit + exact ⟨e z,mem p hz,mem r hz'⟩ + +/-- An empty wall rectangle rules out every boundary column and every +side-changing active switch in a slightly narrower reference-profile strip. -/ +lemma strip_arc_const (F : M.Field I L) (a b : Fin (k+1)) (T : I) + (hJI : J ⊆ I) {s h U V W D : ℝ} + (hempty : ∀ (c : ℝ) (H : I), |c-s| ≤ U → |H.val-h| ≤ V → (c,H.val) ∉ F.wall a b) + (hT : |T.val-h| ≤ V) (hD : ∀ t ∈ J, |t-T.val| ≤ D) + (hV : ∀ t ∈ J, |t-h| ≤ V) (hW : W+L*D ≤ U) (hD0 : 0 ≤ D) : + (∀ i, |F.value i T-s| ≤ W → arcSign a b i ≠ 0) ∧ + (∀ {i j}, (M.activeGraph J).Adj i j → |F.value i T-s| ≤ W → + |F.value j T-s| ≤ W → arcSign a b i = arcSign a b j) := by + constructor + · intro i hi hz + exact hempty _ T (by nlinarith [L.coe_nonneg]) hT (F.wall_of_boundary a b i T hz) + · intro i j hij hi _ + by_contra hne + obtain ⟨t,ht,hs⟩ := hij + let H : I := ⟨t,hJI ht⟩ + have hlip := (F.vertical i).dist_le_mul H T + simp only [Real.dist_eq,Subtype.dist_eq] at hlip + have he : |F.value i H-F.value i T| ≤ L*D := hlip.trans + (mul_le_mul_of_nonneg_left (hD t ht) L.coe_nonneg) + have hc : |F.value i H-s| ≤ U := + (abs_sub_le _ _ _).trans (by linarith) + exact hempty _ H hc (hV t ht) (F.wall_of_switch a b i j H hs hne) + +end PlanarL1.Columns.Model.Field + +namespace PlanarL1.ColumnOrder + +/-- A center-to-exit traversal of a scalar strip, with the visited center +retained and the support enlarged by only one edge error. -/ +lemma center_exit_band {V : Type*} {G : SimpleGraph V} (q : V → ℝ) + {s r c δ : ℝ} (hcr : c < r) (hδ : 0 ≤ δ) + (hedge : ∀ {a b}, G.Adj a b → |q a-q b| ≤ δ) + {x y : V} (p : G.Walk x y) (hx : |q x-s| ≤ c) (hy : s+r ≤ q y) : + ∃ a b, ∃ t : G.Walk a b, + (∀ z ∈ t.support, z ∈ p.support) ∧ x ∈ t.support ∧ + (∀ z ∈ t.support, |q z-s| ≤ r+δ) ∧ + ((q a ≤ s+c ∧ s+r ≤ q b) ∨ (q a ≤ s-r ∧ s-c ≤ q b)) := by + obtain ⟨a,b,hab,ha,hb,t,ht,hT⟩ := first_exit p + (S := {z | |q z-s| < r}) (lt_of_le_of_lt hx hcr) + (by intro h; change |q y-s| < r at h; have := (abs_lt.mp h).2; linarith) + change |q a-s| < r at ha + change ¬|q b-s| < r at hb + have hbabs : |q b-s| ≤ r+δ := by + have hed := hedge hab + rw [abs_sub_comm] at hed + exact (abs_sub_le _ _ _).trans (by linarith) + have hband : ∀ z ∈ t.support, |q z-s| ≤ r+δ := by + intro z hz + rcases hT z hz with hz | rfl + · change |q z-s| < r at hz + linarith + · exact hbabs + have hout : q b ≤ s-r ∨ s+r ≤ q b := by + by_contra hn + push Not at hn + exact hb (abs_lt.mpr ⟨by linarith,by linarith⟩) + rcases hout with hlo | hhi + · refine ⟨b,x,t.reverse,?_,?_,?_,Or.inr ⟨hlo,?_⟩⟩ + · simpa only [SimpleGraph.Walk.support_reverse,List.mem_reverse] using ht + · simpa only [SimpleGraph.Walk.support_reverse,List.mem_reverse] using t.start_mem_support + · simpa only [SimpleGraph.Walk.support_reverse,List.mem_reverse] using hband + · have := (abs_le.mp hx).1; linarith + · refine ⟨x,b,t,ht,t.start_mem_support,hband,Or.inl ⟨?_,hhi⟩⟩ + have := (abs_le.mp hx).2; linarith + +end PlanarL1.ColumnOrder + +namespace PlanarL1.ColumnOrder + +/-- Two disjoint low-to-high traversals, each issuing from a central column, +must have opposite central labels when the strip has precisely two lanes and +same-lane overlapping ranges intersect. This is the finite-word form of the +last two paragraphs of 's two-side argument. -/ +lemma two_lane_centers {V : Type*} {G : SimpleGraph V} (q label : V → ℝ) + {s r c δ : ℝ} (hc : 0 ≤ c) (hδ : 0 ≤ δ) (hgap : 2*δ < r-c) + (hedge : ∀ {a b}, G.Adj a b → |q a-q b| ≤ δ) + (hlabels : ∀ z, |q z-s| ≤ r+δ → label z = 1 ∨ label z = -1) + (hconstant : ∀ {a b}, G.Adj a b → |q a-s| ≤ r+δ → |q b-s| ≤ r+δ → label a = label b) + (hover : ∀ {a b d e : V} (p : G.Walk a b) (t : G.Walk d e) {u v σ : ℝ}, + σ = 1 ∨ σ = -1 → 2*δ < v-u → + (∀ z ∈ p.support, label z = σ) → (∀ z ∈ t.support, label z = σ) → + q a ≤ u → v ≤ q b → q d ≤ u → v ≤ q e → + ∃ z, z ∈ p.support ∧ z ∈ t.support) + {x₀ x₁ y₀ y₁ x y : V} (P : G.Walk x₀ x₁) (Q : G.Walk y₀ y₁) + (U : G.Walk x x₁) (Vw : G.Walk y y₁) + (hU : ∀ z ∈ U.support, z ∈ P.support) (hV : ∀ z ∈ Vw.support, z ∈ Q.support) + (hx₀ : q x₀ ≤ s-r) (hx₁ : s+r ≤ q x₁) + (hy₀ : q y₀ ≤ s-r) (hy₁ : s+r ≤ q y₁) + (hx : |q x-s| ≤ c) (hy : |q y-s| ≤ c) + (hdisj : ∀ z ∈ P.support, z ∉ Q.support) : label x ≠ label y := by + have hr : 0 < r := by linarith + have hcr : c < r := by linarith + have fullgap : 2*δ < (s+r)-(s-r) := by linarith + have band {z : V} (hz : s-r-δ ≤ q z ∧ q z ≤ s+r+δ) : |q z-s| ≤ r+δ := + abs_le.mpr ⟨by linarith [hz.1],by linarith [hz.2]⟩ + obtain ⟨a,b,p,ha,hb,hp,hpb⟩ := traverse_band q hδ (by linarith : s-r < s+r) hedge P hx₀ hx₁ + obtain ⟨d,e,t,hd,he,ht,htb⟩ := traverse_band q hδ (by linarith : s-r < s+r) hedge Q hy₀ hy₁ + have hpa : ∀ z ∈ p.support, label z = label a := + walk_label_const label (S := {z | |q z-s| ≤ r+δ}) hconstant p (fun z hz => band (hpb z hz)) + have htd : ∀ z ∈ t.support, label z = label d := + walk_label_const label (S := {z | |q z-s| ≤ r+δ}) hconstant t (fun z hz => band (htb z hz)) + have hα := hlabels a (band (hpb a p.start_mem_support)) + have hβ := hlabels d (band (htb d t.start_mem_support)) + have hαβ : label a ≠ label d := by + intro heq + obtain ⟨z,hz,hz'⟩ := hover p t hα fullgap hpa + (fun z hz => (htd z hz).trans heq.symm) ha hb hd he + exact hdisj z (hp z hz) (ht z hz') + obtain ⟨a',b',p',hp',hxp',hp'b,hprange⟩ := center_exit_band q hcr hδ hedge U hx hx₁ + obtain ⟨d',e',t',ht',hyt',ht'b,htrange⟩ := center_exit_band q hcr hδ hedge Vw hy hy₁ + have hpx : ∀ z ∈ p'.support, label z = label x := by + have hl := walk_label_const label (S := {z | |q z-s| ≤ r+δ}) hconstant p' hp'b + intro z hz + exact (hl z hz).trans (hl x hxp').symm + have hty : ∀ z ∈ t'.support, label z = label y := by + have hl := walk_label_const label (S := {z | |q z-s| ≤ r+δ}) hconstant t' ht'b + intro z hz + exact (hl z hz).trans (hl y hyt').symm + have hγ := hlabels x (by linarith : |q x-s| ≤ r+δ) + intro hxy + by_cases hαx : label a = label x + · have htt : ∀ z ∈ t'.support, label z = label a := + fun z hz => (hty z hz).trans (hxy.symm.trans hαx.symm) + have hit : ∃ z, z ∈ p.support ∧ z ∈ t'.support := by + rcases htrange with hl | hl + · exact hover p t' hα (by linarith : 2*δ < (s+r)-(s+c)) hpa htt + (by linarith) hb hl.1 hl.2 + · exact hover p t' hα (by linarith : 2*δ < (s-c)-(s-r)) hpa htt + ha (by linarith) hl.1 hl.2 + obtain ⟨z,hz,hz'⟩ := hit + exact hdisj z (hp z hz) (hV z (ht' z hz')) + · have hβx : label d = label x := by + rcases hα with hα | hα + · rcases hβ with hβ | hβ + · exact False.elim (hαβ (hα.trans hβ.symm)) + · rcases hγ with hγ | hγ + · exact False.elim (hαx (hα.trans hγ.symm)) + · exact hβ.trans hγ.symm + · rcases hβ with hβ | hβ + · rcases hγ with hγ | hγ + · exact hβ.trans hγ.symm + · exact False.elim (hαx (hα.trans hγ.symm)) + · exact False.elim (hαβ (hα.trans hβ.symm)) + have hpp : ∀ z ∈ p'.support, label z = label d := fun z hz => (hpx z hz).trans hβx.symm + have hit : ∃ z, z ∈ p'.support ∧ z ∈ t.support := by + rcases hprange with hl | hl + · exact hover p' t hβ (by linarith : 2*δ < (s+r)-(s+c)) hpp htd + hl.1 hl.2 (by linarith) he + · exact hover p' t hβ (by linarith : 2*δ < (s-c)-(s-r)) hpp htd + hl.1 hl.2 hd (by linarith) + obtain ⟨z,hz,hz'⟩ := hit + exact hdisj z (hU z (hp' z hz)) (ht z hz') + +end PlanarL1.ColumnOrder + +namespace PlanarL1.Columns.Model.Field + +variable {k : ℕ} {M : Model (k+1)} {I J : Set ℝ} {L : NNReal} + +def restrict (F : M.Field I L) (hJI : J ⊆ I) : M.Field J L where + value i H := F.value i ⟨H.val,hJI H.property⟩ + vertical i := by + apply LipschitzWith.of_dist_le_mul + intro H T + exact (F.vertical i).dist_le_mul ⟨H.val,hJI H.property⟩ ⟨T.val,hJI T.property⟩ + switch i j H hs := F.switch i j ⟨H.val,hJI H.property⟩ hs + +/-- Quantitative opposite-arc conclusion from genuine short excursions. The +only extra displayed inequality says exactly that the constructed short join +would contradict the given separation; at R=10^-8 it follows from d≥1. -/ +lemma two_side_arcs (F : M.Field I 4) {a b : Fin (k+1)} (ho : F.OrderedFrom a b) + {root : Fin (k+1)} {R η : ℝ} (hR : 0 < R) (hη : η ≤ R/1000000) + (hJI : J ⊆ I) (hw : ∀ s ∈ J, ∀ t ∈ J, |s-t| ≤ η) + (x y : M.Point I root) + (Ex : F.Excursions hJI x (2*R) (2*R/5)) + (Ey : F.Excursions hJI y (2*R) (2*R/5)) + (hclose : |F.eval x-F.eval y| ≤ R/1000) + (hfar : 4*R+2*(R/50+η) < dist x y) : + arcSign a b x.column ≠ 0 ∧ arcSign a b y.column ≠ 0 ∧ + arcSign a b x.column ≠ arcSign a b y.column ∧ + R/100 ≤ Metric.infDist (F.eval x,x.height) (F.wall a b) ∧ + R/100 ≤ Metric.infDist (F.eval y,y.height) (F.wall a b) := by + let T : I := ⟨x.height,x.inBand⟩ + let s := F.eval x + let q : Fin (k+1) → ℝ := fun i => F.value i T + have hη0 : 0 ≤ η := by simpa using hw x.height Ex.inBand x.height Ex.inBand + have hD : ∀ t ∈ J, |t-T.val| ≤ η := fun t ht => hw t ht x.height Ex.inBand + have hempty : ∀ (c : ℝ) (H : I), |c-s| ≤ R/5 → |H.val-x.height| ≤ R/50 → + (c,H.val) ∉ F.wall a b := fun c H hc hH => + F.empty_rectangle ho hR hη hJI hw x y Ex Ey hclose hfar H hc hH + have hstrip := F.strip_arc_const a b T hJI (s := s) (h := x.height) + (U := R/5) (V := R/50) (W := R/6+8*η) (D := η) hempty + (by dsimp [T]; rw [sub_self,abs_zero]; linarith) hD + (fun t ht => (hD t ht).trans (by linarith)) + (by norm_num; linarith) hη0 + have he {i j} (hij : (M.activeGraph J).Adj i j) : |q i-q j| ≤ 8*η := by + have hh := (F.restrict hJI).profile_switch_error hw (⟨x.height,Ex.inBand⟩ : J) hij + change |q i-q j| ≤ 2*(4*η) at hh + linarith + have hlabels (z) (hz : |q z-s| ≤ R/6+8*η) : arcSign a b z = 1 ∨ arcSign a b z = -1 := by + rcases arcSign_cases a b z with hz0 | hz1 | hz1 + · exact False.elim (hstrip.1 z hz hz0) + · exact Or.inl hz1 + · exact Or.inr hz1 + have hqx : |q x.column-s| ≤ R/100 := by simp only [q,T,s,eval,sub_self,abs_zero]; linarith + have hqy : |q y.column-s| ≤ R/100 := by + have hp := (F.restrict hJI).profile_error hw y.column + (⟨x.height,Ex.inBand⟩ : J) ⟨y.height,Ey.inBand⟩ + change |q y.column-F.eval y| ≤ 4*η at hp + have hh := abs_sub_le (q y.column) (F.eval y) s + have hcl : |F.eval y-s| ≤ R/1000 := by simpa only [s,abs_sub_comm] using hclose + linarith + have hxl := Ex.low_profile T hD + have hxh := Ex.high_profile T hD + have hyl := Ey.low_profile T hD + have hyh := Ey.high_profile T hD + norm_num only [NNReal.coe_ofNat] at hxl hxh hyl hyh + have hcl := abs_le.mp hclose + have disj : ∀ z ∈ Ex.traversal.support, z ∉ Ey.traversal.support := by + intro z hz hz' + have hd := x.dist_le_of_near_intersection y Ex.near_traversal Ey.near_traversal hw hz hz' + linarith + have hU : ∀ z ∈ Ex.highPath.word.support, z ∈ Ex.traversal.support := by + intro z hz + exact (SimpleGraph.Walk.mem_support_append_iff _ _).mpr (Or.inr hz) + have hV : ∀ z ∈ Ey.highPath.word.support, z ∈ Ey.traversal.support := by + intro z hz + exact (SimpleGraph.Walk.mem_support_append_iff _ _).mpr (Or.inr hz) + have hneq := ColumnOrder.two_lane_centers q (arcSign a b) (s := s) + (r := R/6) (c := R/100) (δ := 8*η) (by linarith) (by linarith) (by linarith) + he hlabels hstrip.2 + (fun {i j l m} p t {u v σ} hσ hg hp ht hl hh hl' hh' => F.same_arc_overlap ho T hσ + (by linarith) hg he p t hp ht hl hh hl' hh') + Ex.traversal Ey.traversal Ex.highPath.word Ey.highPath.word hU hV + (by change F.value Ex.lowColumn T ≤ F.eval x-R/6; linarith) + (by change F.eval x+R/6 ≤ F.value Ex.highColumn T; linarith) + (by change F.value Ey.lowColumn T ≤ F.eval x-R/6; linarith) + (by change F.eval x+R/6 ≤ F.value Ey.highColumn T; linarith) + hqx hqy disj + refine ⟨hstrip.1 x.column (by linarith),hstrip.1 y.column (by linarith),hneq,?_,?_⟩ + · exact F.infDist_lower_of_rectangle a b T hempty x.column + (by change |F.eval x-F.eval x|+R/100 ≤ R/5; rw [sub_self,abs_zero]; linarith) + (by change |x.height-x.height|+R/100 ≤ R/50; rw [sub_self,abs_zero]; linarith) + · exact F.infDist_lower_of_rectangle a b ⟨y.height,y.inBand⟩ hempty y.column + (by change |F.eval y-F.eval x|+R/100 ≤ R/5; rw [abs_sub_comm]; linarith) + (by have hh := hw y.height Ey.inBand x.height Ex.inBand; dsimp; linarith) + +lemma abs_add_eq_abs_sub_of_opposite {u v : ℝ} (huv : u*v < 0) : |u|+|v| = |u-v| := by + by_cases hu : 0 ≤ u + · have hv : v < 0 := by nlinarith + rw [abs_of_nonneg hu,abs_of_neg hv,abs_of_nonneg (by linarith : 0 ≤ u-v)] + ring + · have hu' : u < 0 := lt_of_not_ge hu + have hv : 0 < v := by nlinarith + rw [abs_of_neg hu',abs_of_pos hv,abs_of_neg (by linarith : u-v < 0)] + ring + +/-- Full quantitative two-side lemma (, ord:two-side) in intrinsic +band coordinates. An ambient application uses the source hypothesis d_I=d. -/ +theorem two_side (F : M.Field I 4) {a b : Fin (k+1)} (ho : F.OrderedFrom a b) + (hI : IsClosed I) {root : Fin (k+1)} {η : ℝ} + (hη : η ≤ (1:ℝ)/100000000/1000000) + (hJI : J ⊆ I) (hw : ∀ s ∈ J, ∀ t ∈ J, |s-t| ≤ η) + (x y : M.Point I root) (hlo : 1 ≤ dist x y) (hhi : dist x y ≤ 2) + (Ex : F.Excursions hJI x (2*((1:ℝ)/100000000)) (2*((1:ℝ)/100000000)/5)) + (Ey : F.Excursions hJI y (2*((1:ℝ)/100000000)) (2*((1:ℝ)/100000000)/5)) + (hclose : |F.eval x-F.eval y| ≤ (1:ℝ)/100000000/1000) : + (F.transverse (by norm_num) a b).eval x * (F.transverse (by norm_num) a b).eval y < 0 ∧ + (1:ℝ)/100000000/100 ≤ |(F.transverse (by norm_num) a b).eval x| ∧ + (1:ℝ)/100000000/100 ≤ |(F.transverse (by norm_num) a b).eval y| ∧ + |(F.transverse (by norm_num) a b).eval x| ≤ 8 ∧ + |(F.transverse (by norm_num) a b).eval y| ≤ 8 := by + obtain ⟨hx,hy,hneq,hDx,hDy⟩ := F.two_side_arcs ho (by norm_num) hη hJI hw x y Ex Ey hclose (by linarith) + let tx := (F.transverse (by norm_num) a b).eval x + let ty := (F.transverse (by norm_num) a b).eval y + have hax : |tx| = Metric.infDist (F.eval x,x.height) (F.wall a b) := + F.transverse_abs a b x.column ⟨x.height,x.inBand⟩ hx + have hay : |ty| = Metric.infDist (F.eval y,y.height) (F.wall a b) := + F.transverse_abs a b y.column ⟨y.height,y.inBand⟩ hy + have hDx0 : 0 < Metric.infDist (F.eval x,x.height) (F.wall a b) := lt_of_lt_of_le (by norm_num) hDx + have hDy0 : 0 < Metric.infDist (F.eval y,y.height) (F.wall a b) := lt_of_lt_of_le (by norm_num) hDy + have hprod : tx*ty < 0 := by + change (arcSign a b x.column * _) * (arcSign a b y.column * _) < 0 + rcases arcSign_cases a b x.column with hx0 | hx1 | hx1 + · exact False.elim (hx hx0) + · rcases arcSign_cases a b y.column with hy0 | hy1 | hy1 + · exact False.elim (hy hy0) + · exact False.elim (hneq (hx1.trans hy1.symm)) + · rw [hx1,hy1,one_mul,neg_one_mul,mul_neg] + exact neg_neg_of_pos (mul_pos hDx0 hDy0) + · rcases arcSign_cases a b y.column with hy0 | hy1 | hy1 + · exact False.elim (hy hy0) + · rw [hx1,hy1,one_mul,neg_one_mul,neg_mul] + exact neg_neg_of_pos (mul_pos hDx0 hDy0) + · exact False.elim (hneq (hx1.trans hy1.symm)) + have hd := ((F.transverse (by norm_num) a b).lipschitz hI root).dist_le_mul x y + change dist tx ty ≤ (4:NNReal)*dist x y at hd + rw [Real.dist_eq] at hd + norm_num only [NNReal.coe_ofNat] at hd + have hsum := abs_add_eq_abs_sub_of_opposite hprod + refine ⟨hprod,by rwa [hax],by rwa [hay],?_,?_⟩ <;> linarith [abs_nonneg tx,abs_nonneg ty] + +end PlanarL1.Columns.Model.Field + + +end + +end OAI diff --git a/lean/OAI/Combinatorics/PlanarL1/CutExtraction.lean b/lean/OAI/Combinatorics/PlanarL1/CutExtraction.lean new file mode 100644 index 0000000000000000000000000000000000000000..97ab4de39ca50e91c139ccc55954f99773aa7e95 --- /dev/null +++ b/lean/OAI/Combinatorics/PlanarL1/CutExtraction.lean @@ -0,0 +1,232 @@ +import OAI.Combinatorics.PlanarL1.StepSuccess + +namespace OAI + + +section + +namespace PlanarL1.Columns.Model +open MeasureTheory Parameters +attribute [local instance] Classical.propDecidable +variable {k : ℕ} {M : Model (k+1)} {Ω Ξ V : Type*} +variable [MeasurableSpace Ω] [MeasurableSpace Ξ] {μ : Measure Ω} {ν : Measure Ξ} +variable {A : Ambient M} +namespace SetSystem +local instance : MeasurableSpace (Set (Fin (k+1))) := ⊤ +variable [Fintype V] (S : SetSystem M Ω μ) (v : V → M.Point Set.univ A.root) +noncomputable def refinedBinary : FiniteL1.BinarySystem (V := V) + (μ.prod (Measure.count : Measure (Set (Fin (k+1))))) where + active w x := (S.activity w.1).active (v x).column (v x).height ∧ w.2=(S.activity w.1).component (v x).column + measurable x := by + have hm : Measurable (fun w : Ω × Set (Fin (k+1)) => (S.activity w.1).vector (v x).column (v x).height w.2) := + measurable_from_prod_countable_left (fun c => S.measurable_vector (v x).column (v x).height c) + convert measurableSet_eq_fun hm (measurable_const : Measurable (fun _ : Ω × Set (Fin (k+1)) => (1:ℝ))) using 1 + ext w + simp [Activity.vector] + integrable x y := by + convert (S.integrable_coordinateDifference (Classical.choice ((v x).paths_nonempty (v y))) (v x).height (v y).height).abs using 1 + funext w + by_cases hx : (S.activity w.1).active (v x).column (v x).height ∧ w.2=(S.activity w.1).component (v x).column <;> + by_cases hy : (S.activity w.1).active (v y).column (v y).height ∧ w.2=(S.activity w.1).component (v y).column <;> + simp [SetSystem.coordinateDifference,Activity.vector,hx,hy] +noncomputable def cuts : FiniteL1.CutFamily V := FiniteL1.CutFamily.ofBinary (S.refinedBinary v) +variable [SFinite μ] +lemma cuts_distance (x y : V) : + (S.cuts v).distance x y=∫ w, (S.activity w).cost (v x).column (v y).column (v x).height (v y).height ∂μ := by + rw [cuts,FiniteL1.CutFamily.distance_ofBinary] + rw [← S.integral_norm_coordinates (Classical.choice ((v x).paths_nonempty (v y))) (v x).height (v y).height] + apply integral_congr_ae + apply Filter.Eventually.of_forall + intro w + by_cases hx : (S.activity w.1).active (v x).column (v x).height ∧ w.2=(S.activity w.1).component (v x).column <;> + by_cases hy : (S.activity w.1).active (v y).column (v y).height ∧ w.2=(S.activity w.1).component (v y).column <;> + simp [Real.norm_eq_abs,SetSystem.coordinateDifference,Activity.vector,FiniteL1.BinarySystem.indicator,refinedBinary,hx,hy] +lemma cuts_upper (x y : V) : (S.cuts v).distance x y ≤ dist (v x) (v y) := by + rw [S.cuts_distance] + exact S.integral_cost_le_dist isClosed_univ _ _ +lemma cuts_dominates (x y : V) : S.separation (v x).column (v x).height (v y).column (v y).height ≤ (S.cuts v).distance x y := by + rw [S.cuts_distance,← S.norm_refinedMap_sub (v x)] + exact S.refinedMap_dominates _ _ _ +end SetSystem +namespace PairGeometry +variable [SFinite μ] [Fintype V] {SA : OrdinaryState M kappaA Ω μ} +variable {v : V → M.Point Set.univ A.root} {x y : V} {b : ℝ} +lemma Certificate.cuts (h : Certificate A SA v (x := x) (y := y) b) : + b ≤ (SA.sets.cuts v).distance x y := by + obtain ⟨a,c,H,E,hH,hac,hsep,hE,hm,hx,hy,hn⟩ := h + rw [SA.sets.cuts_distance,← SA.sets.norm_refinedMap_sub (v x)] + have bound {a c : Fin (k+1)} (hH : H ∈ M.heights a c) (hac : ¬Consecutive a c) + (hsep : Field.TipSeparates a c (v x).column (v y).column) + (hn : ∀ w ∈ E, ¬(SA.sets.activity w).active a H) : + 2*μ.real E ≤ ‖SA.sets.refinedMap (v x) (v x)-SA.sets.refinedMap (v x) (v y)‖ := by + rcases hsep with ⟨h1,h2,hout⟩|⟨h1,h2,hout⟩ + · exact (SA.sets.refinedMap_terminal_certificate (v x) (v x) (v y) hH hac ⟨h1,h2⟩ hout E hE hn hx hy).2 + · simpa only [norm_sub_rev] using (SA.sets.refinedMap_terminal_certificate (v x) (v y) (v x) hH hac ⟨h1,h2⟩ hout E hE hn hy hx).2 + have hh : 2*μ.real E ≤ ‖SA.sets.refinedMap (v x) (v x)-SA.sets.refinedMap (v x) (v y)‖ := by + rcases hsep with hsep|hsep + · exact bound hH hac hsep hn + · apply bound (M.symm a c ▸ hH) (fun h => hac (by simpa only [Consecutive,or_comm,or_left_comm,or_assoc] using h)) hsep + intro w hw hwa + exact hn w hw ((SA.sets.activity w).switch a c H hH |>.mpr hwa) + linarith [measureReal_nonneg (μ := μ) (s := E)] +end PairGeometry +namespace CoupledState +variable [SFinite μ] [SFinite ν] [Fintype V] +variable {t : ℝ} (S : CoupledState A Ω Ξ μ ν t) (v : V → M.Point Set.univ A.root) +noncomputable def cuts : FiniteL1.CutFamily V := (S.left.sets.cuts v).add (S.right.sets.cuts v) +lemma cuts_upper (x y : V) : (S.cuts v).distance x y ≤ 2*dist (v x) (v y) := by + rw [CoupledState.cuts,FiniteL1.CutFamily.distance_add] + linarith [S.left.sets.cuts_upper v x y,S.right.sets.cuts_upper v x y] +lemma Successful.cuts {x y : V} {b : ℝ} (h : S.Successful v b x y) : b ≤ (S.cuts v).distance x y := by + rw [CoupledState.cuts,FiniteL1.CutFamily.distance_add] + rcases h with h|h|h + · exact (h.trans (S.left.sets.cuts_dominates v x y)).trans (le_add_of_nonneg_right (FiniteL1.CutFamily.distance_nonneg _ _ _)) + · exact (h.trans (S.right.sets.cuts_dominates v x y)).trans (le_add_of_nonneg_left (FiniteL1.CutFamily.distance_nonneg _ _ _)) + · exact h.cuts.trans (le_add_of_nonneg_right (FiniteL1.CutFamily.distance_nonneg _ _ _)) +end CoupledState +end PlanarL1.Columns.Model + +end + + + +section + +namespace PlanarL1.Threshold +open MeasureTheory +instance labelMeasure_sfinite : SFinite labelMeasure := by + rw [labelMeasure_eq] + infer_instance +end PlanarL1.Threshold + +namespace PlanarL1.Columns.Model +open MeasureTheory Parameters + +/-- A state of the actual construction in its current physical units. Both +label spaces are enlarged at every step, even in the no-change mode. -/ +structure World (k : ℕ) (V : Type*) (Q : ℝ) where + model : Model (k+1) + ambient : Ambient model + vertex : V → model.Point Set.univ ambient.root + sample : Type + [measurable : MeasurableSpace sample] + measure : Measure sample + [sfinite : SFinite measure] + state : CoupledState ambient sample sample measure measure Q + +namespace World +attribute [instance] measurable sfinite +variable {k : ℕ} {V : Type*} [Fintype V] {Q : ℝ} +variable (hQ : 0 < Q) (h1 : 1 ≤ Q) (hgap : 10 ≤ (R/200)*Q) +variable (W : World k V Q) +noncomputable def heightBound : ℝ := ∑ x, |(W.vertex x).height| +lemma height_bounds (x : V) : (W.vertex x).height ∈ Set.Icc (-W.heightBound) W.heightBound := by + have hh : |(W.vertex x).height| ≤ W.heightBound := + Finset.single_le_sum (f := fun y => |(W.vertex y).height|) (fun y _ => abs_nonneg _) (Finset.mem_univ x) + exact abs_le.mp hh + +noncomputable def after (T : CoupledState.Next (A := W.ambient) (μ := W.measure) (ν := W.measure)) : World k V Q where + model := W.model.dilate Q hQ + ambient := W.ambient.dilate hQ + vertex x := W.ambient.scaleEquiv hQ (W.vertex x) + sample := W.sample × Bool + measure := ENNReal.ofReal Q • (W.measure.prod Threshold.fair) + state := (T.dilate hQ).weaken (by simp) + +noncomputable def step {m : ℕ} (hm : 0 < m) : Execution (World k V Q) := + (W.state.step h1 hgap W.vertex W.height_bounds hm).bind (fun T => .pure (W.after hQ T)) + +def Coherent (x : V) (ρ : ℝ) : Prop := W.state.Coherent (W.vertex x) ρ +def Successful (b : ℝ) (x y : V) : Prop := W.state.Successful W.vertex b x y +noncomputable def distance (x y : V) : ℝ := dist (W.vertex x) (W.vertex y) +noncomputable def cuts : FiniteL1.CutFamily V := W.state.cuts W.vertex +lemma cuts_upper (x y : V) : W.cuts.distance x y ≤ 2*W.distance x y := W.state.cuts_upper W.vertex x y +lemma Successful.cuts {b : ℝ} {x y : V} (h : W.Successful b x y) : b ≤ W.cuts.distance x y := CoupledState.Successful.cuts W.state W.vertex h +omit [Fintype V] in +lemma Successful.mono {b c : ℝ} {x y : V} (h : W.Successful b x y) (hc : c ≤ b) : W.Successful c x y := CoupledState.Successful.mono W.state W.vertex h hc + +omit [Fintype V] in +lemma after_distance (T : CoupledState.Next (A := W.ambient) (μ := W.measure) (ν := W.measure)) (x y : V) : + (W.after hQ T).distance x y=Q*W.distance x y := W.ambient.scaleEquiv_dist hQ _ _ +omit [Fintype V] in +lemma after_coherent (T : CoupledState.Next (A := W.ambient) (μ := W.measure) (ν := W.measure)) (x : V) (ρ : ℝ) : + (W.after hQ T).Coherent x (Q*ρ) ↔ T.Coherent (W.vertex x) ρ := + T.coherent_dilate hQ _ _ +omit [Fintype V] in +lemma after_successful (T : CoupledState.Next (A := W.ambient) (μ := W.measure) (ν := W.measure)) + {x y : V} {b : ℝ} (h : T.Successful W.vertex b x y) : (W.after hQ T).Successful (Q*b) x y := h.dilate hQ T W.vertex + +lemma step_distances {m : ℕ} (hm : 0 < m) : (W.step hQ h1 hgap hm).Holds + (fun Z => ∀ x y, Z.distance x y=Q*W.distance x y) := by + apply Execution.holds_bind_of_forall + intro T x y + exact W.after_distance hQ T x y + +lemma step_survives {m : ℕ} (hm : 0 < m) {x y : V} {b : ℝ} (h : W.Successful b x y) : + (W.step hQ h1 hgap hm).Holds (fun Z => Z.Successful (Q*(b-3)) x y) := by + apply (W.state.step_moves h1 hgap W.vertex W.height_bounds hm).bind + intro T hT + exact W.after_successful hQ T (by simpa only [mul_one] using hT.successful W.state (by norm_num) W.vertex h) + +lemma step_persistence {m : ℕ} (hm : 0 < m) {x : V} {ρ : ℝ} (hρ : 0 ≤ ρ) + (hr : ρ ≤ persistenceRadius) (hold : W.Coherent x ρ) : + (W.step hQ h1 hgap hm).prob (fun Z => ¬Z.Coherent x (Q*ρ)) ≤ persistenceLoss ρ m := by + rw [step,Execution.prob_bind_pure] + have he : (fun T : CoupledState.Next (A := W.ambient) (μ := W.measure) (ν := W.measure) => + ¬(W.after hQ T).Coherent x (Q*ρ))=(fun T => ¬T.Coherent (W.vertex x) ρ) := by + funext T + exact propext (not_congr (W.after_coherent hQ T x ρ)) + rw [he] + exact W.state.step_persistence h1 hgap W.vertex W.height_bounds hm x hρ hr hold + +omit [Fintype V] in +lemma coherent_eligible {x y : V} (h : W.Coherent x 20) (hd : W.distance x y < 2) : + VertexTests.Eligible W.ambient W.state.left W.state.right W.vertex x y := by + refine ⟨?_,?_,?_,?_⟩ + · intro z hz + exact (h z (hz.trans (by norm_num))).1 + · intro z hz + have hxz : dist (W.vertex x) z ≤ 20 := by + have ht := dist_triangle (W.vertex x) (W.vertex y) z + change dist (W.vertex x) (W.vertex y)<2 at hd + linarith + exact (h z hxz).1 + · intro z hz + exact (h z (hz.trans (by norm_num))).2 + · intro z hz + have hxz : dist (W.vertex x) z ≤ 20 := by + have ht := dist_triangle (W.vertex x) (W.vertex y) z + change dist (W.vertex x) (W.vertex y)<2 at hd + linarith + exact (h z hxz).2 + +lemma step_success {m : ℕ} (hm : 0 < m) (hmany : 10000 ≤ m) {x y : V} + (hc : W.Coherent x 20) (hlo : 1 ≤ W.distance x y) (hhi : W.distance x y < 2) : + successChance ≤ (W.step hQ h1 hgap hm).prob (fun Z => Z.Successful (Q*successGain) x y) := by + rw [step,Execution.prob_bind_pure] + apply le_trans (W.state.step_success h1 hgap W.vertex W.height_bounds hm (W.coherent_eligible hc hhi) hlo hhi hmany) + apply Execution.prob_mono + intro T hT + exact W.after_successful hQ T hT + +noncomputable def initial {M : Model (k+1)} (A : Ambient M) (v : V → M.Point Set.univ A.root) : World k V Q where + model := M + ambient := A + vertex := v + sample := Bool × ℝ + measure := Threshold.labelMeasure + state := { + left := OrdinaryState.initial M kappaA + right := BState.initial M kappaB SecondaryGeometry.Group.lam + histories := BState.Histories.ofOrdinary (A := A) (hc := by norm_num [R]) (hcr := by norm_num [R]) (OrdinaryState.initial M kappaB) } +omit [Fintype V] in +lemma initial_coherent {M : Model (k+1)} (A : Ambient M) (v : V → M.Point Set.univ A.root) (x : V) (ρ : ℝ) : + (initial (Q := Q) A v).Coherent x ρ := by + intro z hz + exact ⟨rfl,rfl⟩ +end World +end PlanarL1.Columns.Model + +end + +end OAI diff --git a/lean/OAI/Combinatorics/PlanarL1/Cuts.lean b/lean/OAI/Combinatorics/PlanarL1/Cuts.lean new file mode 100644 index 0000000000000000000000000000000000000000..19077bdf295fcd28a0c8e06852c7ecb9e1d43002 --- /dev/null +++ b/lean/OAI/Combinatorics/PlanarL1/Cuts.lean @@ -0,0 +1,597 @@ +import OAI.Combinatorics.PlanarL1.Fields + +namespace OAI + +section + +namespace PlanarL1.Columns.Model + +/-- One label of a nested-set system. Nesting and exact switching are the +set invariants, not any embedding or separation assumption. -/ +structure Activity {n : ℕ} (M : Model n) where + active : Fin n → ℝ → Prop + increasing : ∀ i s t, s ≤ t → active i s → active i t + switch : ∀ i j H, H ∈ M.heights i j → (active i H ↔ active j H) + +namespace Activity + +attribute [local instance] Classical.propDecidable + +variable {n : ℕ} {M : Model n} (A : Activity M) + +def graph : SimpleGraph (Fin n) where + Adj i j := ∃ H, H ∈ M.heights i j ∧ A.active i H + symm := ⟨by + rintro i j ⟨H,hH,hA⟩ + exact ⟨H,by rwa [M.symm i j] at hH,(A.switch i j H hH).mp hA⟩⟩ + loopless := ⟨by + rintro i ⟨H,hH,_⟩ + exact M.link.loopless.irrefl i (M.permitted i i H hH)⟩ + +lemma graph_le : A.graph ≤ M.link := by + rintro i j ⟨H,hH,_⟩ + exact M.permitted i j H hH + +def component (i : Fin n) : Set (Fin n) := {k | A.graph.Reachable i k} + +lemma mem_component_self (i : Fin n) : i ∈ A.component i := .refl i + +lemma component_eq_iff (i j : Fin n) : A.component i = A.component j ↔ A.graph.Reachable i j := by + constructor + · intro h + change j ∈ A.component i + rw [h] + exact A.mem_component_self j + · intro h + ext k + exact ⟨fun hik => h.symm.trans hik,fun hjk => h.trans hjk⟩ + +/-- Active points get a single component coordinate; inactive points get zero. +The finite coordinate set consists of all subsets of columns. -/ +noncomputable def vector (i : Fin n) (H : ℝ) (S : Set (Fin n)) : ℝ := + if A.active i H ∧ S = A.component i then 1 else 0 + +noncomputable def indicator (i : Fin n) (H : ℝ) : ℝ := if A.active i H then 1 else 0 + +noncomputable def cost (i j : Fin n) (s t : ℝ) : ℝ := + ∑ S : Set (Fin n), |A.vector i s S - A.vector j t S| + +lemma cost_nonneg (i j : Fin n) (s t : ℝ) : 0 ≤ A.cost i j s t := by + unfold cost + exact Finset.sum_nonneg fun _ _ => abs_nonneg _ + +lemma vector_inactive {i : Fin n} {H : ℝ} (h : ¬ A.active i H) : A.vector i H = 0 := by + funext S + simp only [vector,h,false_and,ite_false,Pi.zero_apply] + +lemma vector_active {i : Fin n} {H : ℝ} (h : A.active i H) (S : Set (Fin n)) : + A.vector i H S = if S = A.component i then 1 else 0 := by + simp only [vector,h,true_and] + +lemma cost_comm (i j : Fin n) (s t : ℝ) : A.cost i j s t = A.cost j i t s := by + unfold cost + apply Finset.sum_congr rfl + intro S _ + exact abs_sub_comm _ _ + +lemma sum_vector (i : Fin n) (H : ℝ) : + ∑ S : Set (Fin n), A.vector i H S = A.indicator i H := by + classical + by_cases h : A.active i H + · simp only [A.vector_active h, indicator,h,ite_true] + simp + · rw [A.vector_inactive h] + simp only [Pi.zero_apply,Finset.sum_const_zero,indicator,h,ite_false] + +lemma vector_nonneg (i : Fin n) (H : ℝ) (S : Set (Fin n)) : 0 ≤ A.vector i H S := by + unfold vector + split <;> norm_num + +lemma dominates_indicator (i j : Fin n) (s t : ℝ) : + |A.indicator i s-A.indicator j t| ≤ A.cost i j s t := by + rw [← A.sum_vector i s,← A.sum_vector j t,← Finset.sum_sub_distrib] + exact Finset.abs_sum_le_sum_abs _ _ + +lemma cost_triangle (i j k : Fin n) (s t u : ℝ) : + A.cost i k s u ≤ A.cost i j s t+A.cost j k t u := by + unfold cost + rw [← Finset.sum_add_distrib] + exact Finset.sum_le_sum fun S _ => abs_sub_le _ _ _ + +lemma cost_vertical (i : Fin n) (s t : ℝ) : + A.cost i i s t = |A.indicator i s-A.indicator i t| := by + classical + by_cases hs : A.active i s <;> by_cases ht : A.active i t + · simp only [cost,A.vector_active hs,A.vector_active ht,sub_self,abs_zero, + Finset.sum_const_zero,indicator,hs,ht,ite_true] + · simp only [cost,A.vector_active hs,A.vector_inactive ht,Pi.zero_apply,sub_zero, + indicator,hs,ht,ite_true,ite_false] + simp only [apply_ite abs,abs_one,abs_zero] + simp + · rw [A.cost_comm] + simp only [cost,A.vector_active ht,A.vector_inactive hs,Pi.zero_apply,sub_zero, + indicator,hs,ht,ite_true,ite_false] + simp only [apply_ite abs,abs_one,abs_zero] + simp + · simp only [cost,A.vector_inactive hs,A.vector_inactive ht,Pi.zero_apply,sub_self, + abs_zero,Finset.sum_const_zero,indicator,hs,ht,ite_false] + +lemma vector_switch {i j : Fin n} {H : ℝ} (hH : H ∈ M.heights i j) : + A.vector i H = A.vector j H := by + classical + by_cases hi : A.active i H + · have hj := (A.switch i j H hH).mp hi + have he := (A.component_eq_iff i j).mpr (SimpleGraph.Adj.reachable ⟨H,hH,hi⟩) + funext S + simp only [A.vector_active hi,A.vector_active hj,he] + · rw [A.vector_inactive hi,A.vector_inactive (fun h => hi ((A.switch i j H hH).mpr h))] + +lemma cost_switch {i j : Fin n} {H : ℝ} (hH : H ∈ M.heights i j) : A.cost i j H H = 0 := by + simp only [cost,A.vector_switch hH,sub_self,abs_zero,Finset.sum_const_zero] + +lemma cost_of_active_distinct {i j : Fin n} {s t : ℝ} + (hi : A.active i s) (hj : A.active j t) (hne : A.component i ≠ A.component j) : + A.cost i j s t = 2 := by + classical + have hr : ∀ S : Set (Fin n), |A.vector i s S-A.vector j t S| = + (if S = A.component i then 1 else 0)+(if S = A.component j then 1 else 0) := by + intro S + rw [A.vector_active hi,A.vector_active hj] + by_cases h₁ : S = A.component i <;> by_cases h₂ : S = A.component j + · exact False.elim (hne (h₁.symm.trans h₂)) + · simp only [ite_eq_left h₁,ite_eq_right h₂]; norm_num + · simp only [ite_eq_right h₁,ite_eq_left h₂]; norm_num + · simp only [ite_eq_right h₁,ite_eq_right h₂]; norm_num + simp only [cost,hr,Finset.sum_add_distrib] + norm_num + +/-- An inactive terminal tip isolates BOTH of its endpoint columns in the +active-link graph. This uses the terminal-switch standing hypothesis. -/ +lemma terminal_isolated {a b : Fin n} {H : ℝ} + (hH : H ∈ M.heights a b) (hn : ¬ Consecutive a b) (hA : ¬ A.active a H) : + (∀ k, ¬ A.graph.Adj a k) ∧ (∀ k, ¬ A.graph.Adj b k) := by + obtain ⟨T,hT,ht⟩ := M.terminal a b (M.permitted a b H hH) hn + have he : H = T := by simpa only [hT,Set.mem_singleton_iff] using hH + subst T + constructor + · rintro k ⟨U,hU,hu⟩ + exact hA (A.increasing a U H (ht k U (Or.inl hU)) hu) + · rintro k ⟨U,hU,hu⟩ + exact hA ((A.switch a b H hH).mpr (A.increasing b U H (ht k U (Or.inr hU)) hu)) + +lemma separated_components {a b x y : Fin n} {H : ℝ} + (hH : H ∈ M.heights a b) (hn : ¬ Consecutive a b) (hA : ¬ A.active a H) + (hx : a < x ∧ x < b) (hy : y < a ∨ b < y) : A.component x ≠ A.component y := by + intro he + obtain ⟨p⟩ := (A.component_eq_iff x y).mp he + have hxy : x ≠ y := by omega + have hp := SimpleGraph.Walk.not_nil_of_ne (p := p) hxy + obtain ⟨ha,hb⟩ := A.terminal_isolated hH hn hA + have hsep := ColumnOrder.chord_separation M.noncrossing (M.permitted a b H hH) + (p.mapLe A.graph_le) hx hy + rw [SimpleGraph.Walk.support_mapLe_eq_support] at hsep + rcases hsep with hsep | hsep + · obtain ⟨k,_,hk⟩ := SimpleGraph.adj_of_mem_walk_support p hp hsep + exact ha k hk + · obtain ⟨k,_,hk⟩ := SimpleGraph.adj_of_mem_walk_support p hp hsep + exact hb k hk + +/-- Exact labelwise component-certificate separation (sets:component-refinement). +The other switches may change arbitrarily, subject only to the invariants. -/ +lemma terminal_certificate {a b x y : Fin n} {H s t : ℝ} + (hH : H ∈ M.heights a b) (hn : ¬ Consecutive a b) (hA : ¬ A.active a H) + (hx : a < x ∧ x < b) (hy : y < a ∨ b < y) + (hs : A.active x s) (ht : A.active y t) : A.cost x y s t = 2 := + A.cost_of_active_distinct hs ht (A.separated_components hH hn hA hx hy) + +/-- The unrefined costs of the vertical pieces of an ACTUAL permitted path. -/ +noncomputable def pathCost {J : Set ℝ} : {i j : Fin n} → M.Path J i j → ℝ → ℝ → ℝ + | _, _, .nil i, s, t => |A.indicator i s-A.indicator i t| + | i, _, .cons H _ _ p, s, t => |A.indicator i s-A.indicator i H|+pathCost p H t + +lemma cost_le_pathCost {J : Set ℝ} {i j : Fin n} (p : M.Path J i j) (s t : ℝ) : + A.cost i j s t ≤ A.pathCost p s t := by + induction p generalizing s with + | nil => exact le_of_eq (A.cost_vertical _ _ _) + | @cons i k j H hH hs p ih => + have h₁ := A.cost_triangle i k j H H t + rw [A.cost_switch hs,zero_add] at h₁ + have h₂ := A.cost_triangle i i j s H t + rw [A.cost_vertical] at h₂ + change A.cost i j s t ≤ |A.indicator i s-A.indicator i H|+A.pathCost p H t + linarith [ih H] + +end Activity +end PlanarL1.Columns.Model + +namespace PlanarL1.Columns.Model +open MeasureTheory + +/-- The exact hypotheses in the component-refinement lemma, put on an actual +measure space. The vertical bound is the invariant of the cut construction. -/ +structure SetSystem {n : ℕ} (M : Model n) (Ω : Type*) [MeasurableSpace Ω] + (μ : Measure Ω) where + activity : Ω → Activity M + measurable_active : ∀ i H, MeasurableSet {ω | (activity ω).active i H} + vertical_integrable : ∀ i s t, + Integrable (fun ω => |(activity ω).indicator i s-(activity ω).indicator i t|) μ + vertical_bound : ∀ i s t, + (∫ ω, |(activity ω).indicator i s-(activity ω).indicator i t| ∂μ) ≤ |s-t| + +namespace SetSystem +variable {n : ℕ} {M : Model n} {Ω : Type*} [MeasurableSpace Ω] + {μ : Measure Ω} (A : SetSystem M Ω μ) + +lemma measurable_indicator (i : Fin n) (H : ℝ) : + Measurable (fun ω => (A.activity ω).indicator i H) := by + exact Measurable.ite (A.measurable_active i H) measurable_const measurable_const + +/-- Compactness and monotonicity reduce active-link measurability to ONE fixed +height. There is no uncountable union of switching events. -/ +lemma measurable_adj (i j : Fin n) : + MeasurableSet {ω | (A.activity ω).graph.Adj i j} := by + by_cases h : (M.heights i j).Nonempty + · obtain ⟨H,hH,hmax⟩ := (M.compact i j).exists_isGreatest h + have he : {ω | (A.activity ω).graph.Adj i j} = + {ω | (A.activity ω).active i H} := by + ext ω + constructor + · rintro ⟨T,hT,ha⟩ + exact (A.activity ω).increasing i T H (hmax hT) ha + · intro ha + exact ⟨H,hH,ha⟩ + rw [he] + exact A.measurable_active i H + · have he : {ω | (A.activity ω).graph.Adj i j} = ∅ := by + ext ω + constructor + · rintro ⟨H,hH,_⟩ + exact h ⟨H,hH⟩ + · exact False.elim + rw [he] + exact MeasurableSet.empty + +lemma measurable_graph_fiber (G : SimpleGraph (Fin n)) : + MeasurableSet {ω | (A.activity ω).graph = G} := by + have he : {ω | (A.activity ω).graph = G} = + ⋂ i, ⋂ j, {ω | (A.activity ω).graph.Adj i j ↔ G.Adj i j} := by + ext ω + simp only [Set.mem_ofPred_eq,Set.mem_iInter] + constructor + · intro h; rw [h]; exact fun _ _ => Iff.rfl + · intro h; exact SimpleGraph.ext (funext fun i => funext fun j => propext (h i j)) + rw [he] + apply MeasurableSet.iInter + intro i + apply MeasurableSet.iInter + intro j + by_cases h : G.Adj i j + · simpa only [h,iff_true] using A.measurable_adj i j + · simpa only [h,iff_false,Set.compl_ofPred] using (A.measurable_adj i j).compl + +lemma measurable_component (i : Fin n) (S : Set (Fin n)) : + MeasurableSet {ω | (A.activity ω).component i = S} := by + let : MeasurableSpace (SimpleGraph (Fin n)) := ⊤ + have hm : Measurable (fun ω => (A.activity ω).graph) := + measurable_to_countable' (A.measurable_graph_fiber) + exact hm (t := {G | {k | G.Reachable i k} = S}) trivial + +lemma measurable_vector (i : Fin n) (H : ℝ) (S : Set (Fin n)) : + Measurable (fun ω => (A.activity ω).vector i H S) := by + have hh : MeasurableSet {ω | S = (A.activity ω).component i} := by + simpa only [eq_comm] using A.measurable_component i S + exact Measurable.ite ((A.measurable_active i H).inter hh) + measurable_const measurable_const + +lemma measurable_cost (i j : Fin n) (s t : ℝ) : + Measurable (fun ω => (A.activity ω).cost i j s t) := by + classical + exact Finset.measurable_sum _ fun S _ => + ((A.measurable_vector i s S).sub (A.measurable_vector j t S)).abs + +lemma pathCost_integrable {J : Set ℝ} {i j : Fin n} (p : M.Path J i j) (s t : ℝ) : + Integrable (fun ω => (A.activity ω).pathCost p s t) μ := by + induction p generalizing s with + | nil => exact A.vertical_integrable _ _ _ + | cons H _ _ p ih => exact (A.vertical_integrable _ _ _).add (ih H) + +lemma integral_pathCost_le {J : Set ℝ} {i j : Fin n} (p : M.Path J i j) (s t : ℝ) : + (∫ ω, (A.activity ω).pathCost p s t ∂μ) ≤ p.length s t := by + induction p generalizing s with + | nil => exact A.vertical_bound _ _ _ + | @cons i k j H _ _ p ih => + change (∫ ω, |(A.activity ω).indicator i s-(A.activity ω).indicator i H|+ + (A.activity ω).pathCost p H t ∂μ) ≤ |s-H|+p.length H t + rw [integral_add (A.vertical_integrable i s H) (A.pathCost_integrable p H t)] + exact add_le_add (A.vertical_bound i s H) (ih H) + +lemma cost_integrable {J : Set ℝ} {i j : Fin n} (p : M.Path J i j) (s t : ℝ) : + Integrable (fun ω => (A.activity ω).cost i j s t) μ := by + apply (A.pathCost_integrable p s t).mono' (A.measurable_cost i j s t).aestronglyMeasurable + exact Filter.Eventually.of_forall fun ω => by + rw [Real.norm_eq_abs,abs_of_nonneg ((A.activity ω).cost_nonneg i j s t)] + exact (A.activity ω).cost_le_pathCost p s t + +lemma integral_cost_le_length {J : Set ℝ} {i j : Fin n} (p : M.Path J i j) (s t : ℝ) : + (∫ ω, (A.activity ω).cost i j s t ∂μ) ≤ p.length s t := by + apply le_trans _ (A.integral_pathCost_le p s t) + exact integral_mono (A.cost_integrable p s t) (A.pathCost_integrable p s t) + (fun ω => (A.activity ω).cost_le_pathCost p s t) + +lemma integral_cost_le_dist {J : Set ℝ} {root : Fin n} (hJ : IsClosed J) + (x y : M.Point J root) : + (∫ ω, (A.activity ω).cost x.column y.column x.height y.height ∂μ) ≤ dist x y := by + obtain ⟨p,_,hp⟩ := x.exists_shortest hJ y + exact (A.integral_cost_le_length p x.height y.height).trans_eq hp + +/-- Finitely many coordinates, with the discrete sigma algebra. -/ +local instance componentMeasurableSpace : MeasurableSpace (Set (Fin n)) := ⊤ + +noncomputable def coordinateDifference (i j : Fin n) (s t : ℝ) + (z : Ω × Set (Fin n)) : ℝ := + (A.activity z.1).vector i s z.2-(A.activity z.1).vector j t z.2 + +lemma measurable_coordinateDifference (i j : Fin n) (s t : ℝ) : + Measurable (A.coordinateDifference i j s t) := by + apply measurable_from_prod_countable_left + intro S + exact (A.measurable_vector i s S).sub (A.measurable_vector j t S) + +lemma integrable_coordinateDifference {J : Set ℝ} {i j : Fin n} + (p : M.Path J i j) (s t : ℝ) : + Integrable (A.coordinateDifference i j s t) (μ.prod Measure.count) := by + classical + apply (integrable_prod_iff (A.measurable_coordinateDifference i j s t).aestronglyMeasurable).mpr + constructor + · exact Filter.Eventually.of_forall fun ω => + memLp_one_iff_integrable.mp MemLp.of_discrete + · have he : (fun ω => ∫ S, ‖A.coordinateDifference i j s t (ω,S)‖ ∂Measure.count) = + (fun ω => (A.activity ω).cost i j s t) := by + funext ω + rw [integral_count] + simp only [coordinateDifference,Real.norm_eq_abs,Activity.cost] + rw [he] + exact A.cost_integrable p s t + +variable [SFinite μ] + +lemma integral_norm_coordinates {J : Set ℝ} {i j : Fin n} + (p : M.Path J i j) (s t : ℝ) : + (∫ z, ‖A.coordinateDifference i j s t z‖ ∂μ.prod Measure.count) = + ∫ ω, (A.activity ω).cost i j s t ∂μ := by + rw [integral_prod _ (A.integrable_coordinateDifference p s t).norm] + apply integral_congr_ae + exact Filter.Eventually.of_forall fun ω => by + dsimp only + rw [integral_count] + simp only [coordinateDifference,Real.norm_eq_abs,Activity.cost] + +/-- Subtracting the actual reference point makes the component assignment +integrable, even when the original label measure is infinite. -/ +noncomputable def refinedMap {J : Set ℝ} {root : Fin n} (o x : M.Point J root) : + Lp ℝ 1 (μ.prod (Measure.count : Measure (Set (Fin n)))) := + (A.integrable_coordinateDifference (Classical.choice (x.paths_nonempty o)) x.height o.height).toL1 + (A.coordinateDifference x.column o.column x.height o.height) + +lemma norm_refinedMap_sub {J : Set ℝ} {root : Fin n} (o x y : M.Point J root) : + ‖A.refinedMap o x-A.refinedMap o y‖ = + ∫ ω, (A.activity ω).cost x.column y.column x.height y.height ∂μ := by + rw [L1.norm_eq_integral_norm] + calc + (∫ z, ‖(A.refinedMap o x-A.refinedMap o y) z‖ ∂μ.prod Measure.count) = + ∫ z, ‖A.coordinateDifference x.column y.column x.height y.height z‖ ∂μ.prod Measure.count := by + apply integral_congr_ae + have hx := (A.integrable_coordinateDifference (Classical.choice (x.paths_nonempty o)) + x.height o.height).coeFn_toL1 + have hy := (A.integrable_coordinateDifference (Classical.choice (y.paths_nonempty o)) + y.height o.height).coeFn_toL1 + filter_upwards [Lp.coeFn_sub (A.refinedMap o x) (A.refinedMap o y),hx,hy] with z hz hx hy + change (A.refinedMap o x) z = _ at hx + change (A.refinedMap o y) z = _ at hy + rw [hz,Pi.sub_apply,hx,hy] + congr 1 + simp only [coordinateDifference] + ring + _ = _ := A.integral_norm_coordinates (Classical.choice (x.paths_nonempty y)) x.height y.height + +lemma refinedMap_lipschitz {J : Set ℝ} {root : Fin n} (hJ : IsClosed J) + (o x y : M.Point J root) : ‖A.refinedMap o x-A.refinedMap o y‖ ≤ dist x y := by + rw [A.norm_refinedMap_sub] + exact A.integral_cost_le_dist hJ x y + +omit [SFinite μ] in +lemma unrefined_integrable {J : Set ℝ} {i j : Fin n} + (p : M.Path J i j) (s t : ℝ) : + Integrable (fun ω => |(A.activity ω).indicator i s-(A.activity ω).indicator j t|) μ := by + apply (A.cost_integrable p s t).mono' (((A.measurable_indicator i s).sub + (A.measurable_indicator j t)).abs.aestronglyMeasurable) + exact Filter.Eventually.of_forall fun ω => by + rw [Real.norm_eq_abs,abs_abs] + exact (A.activity ω).dominates_indicator i j s t + +lemma refinedMap_dominates {J : Set ℝ} {root : Fin n} (o x y : M.Point J root) : + (∫ ω, |(A.activity ω).indicator x.column x.height- + (A.activity ω).indicator y.column y.height| ∂μ) ≤ + ‖A.refinedMap o x-A.refinedMap o y‖ := by + rw [A.norm_refinedMap_sub] + let p := Classical.choice (x.paths_nonempty y) + exact integral_mono (A.unrefined_integrable p x.height y.height) + (A.cost_integrable p x.height y.height) + (fun ω => (A.activity ω).dominates_indicator _ _ _ _) + +/-- The actual final certificate yields twice its label mass in the refined +real L1 map. Its mass is necessarily finite, although μ itself is infinite. -/ +lemma refinedMap_terminal_certificate {J : Set ℝ} {root : Fin n} (o x y : M.Point J root) + {a b : Fin n} {H : ℝ} (hH : H ∈ M.heights a b) (hn : ¬ Consecutive a b) + (hx : a < x.column ∧ x.column < b) (hy : y.column < a ∨ b < y.column) + (E : Set Ω) (hE : MeasurableSet E) + (hA : ∀ ω ∈ E, ¬ (A.activity ω).active a H) + (hX : ∀ ω ∈ E, (A.activity ω).active x.column x.height) + (hY : ∀ ω ∈ E, (A.activity ω).active y.column y.height) : + μ E < ⊤ ∧ 2*μ.real E ≤ ‖A.refinedMap o x-A.refinedMap o y‖ := by + classical + have hbnd : ∀ ω, ‖E.indicator (fun _ => (2:ℝ)) ω‖ ≤ + (A.activity ω).cost x.column y.column x.height y.height := by + intro ω + by_cases hω : ω ∈ E + · rw [Set.indicator_of_mem hω, + (A.activity ω).terminal_certificate hH hn (hA ω hω) hx hy (hX ω hω) (hY ω hω)] + norm_num + · rw [Set.indicator_of_notMem hω,norm_zero] + exact (A.activity ω).cost_nonneg _ _ _ _ + have hi : Integrable (E.indicator (fun _ => (2:ℝ))) μ := + (A.cost_integrable (Classical.choice (x.paths_nonempty y)) x.height y.height).mono' + (measurable_const.indicator hE).aestronglyMeasurable (Filter.Eventually.of_forall hbnd) + constructor + · have ht := (integrableOn_const_iff (C := (2:ℝ))).mp + ((integrable_indicator_iff hE).mp hi) + simpa using ht + · rw [A.norm_refinedMap_sub] + calc + 2*μ.real E = ∫ ω, E.indicator (fun _ => (2:ℝ)) ω ∂μ := by + rw [integral_indicator_const _ hE,smul_eq_mul,mul_comm] + _ ≤ _ := integral_mono hi + (A.cost_integrable (Classical.choice (x.paths_nonempty y)) x.height y.height) + (fun ω => (le_abs_self _).trans (by simpa only [Real.norm_eq_abs] using hbnd ω)) + +end SetSystem +end PlanarL1.Columns.Model + + + +end + +section + +namespace PlanarL1.Columns.Model +open MeasureTheory +attribute [local instance] Classical.propDecidable +namespace Activity +variable {n : ℕ} {M : Model n} + +/-- Pointwise membership movement; component labels are deliberately not moved. -/ +noncomputable def movement (A B : Activity M) (i : Fin n) (H : ℝ) : ℝ := + |B.indicator i H-A.indicator i H| + +lemma movement_nonneg (A B : Activity M) (i : Fin n) (H : ℝ) : 0 ≤ A.movement B i H := + abs_nonneg _ + +lemma terminal_survival (A B : Activity M) {a b x y : Fin n} {H s t : ℝ} + (hH : H ∈ M.heights a b) (hn : ¬ Consecutive a b) + (hx : a (A.activity ω).movement_nonneg (B.activity ω) i H) + +lemma movement_triangle (C : SetSystem M Ω μ) (i : Fin n) (H : ℝ) + (hab : Integrable (fun ω => (B.activity ω).indicator i H-(A.activity ω).indicator i H) μ) + (hbc : Integrable (fun ω => (C.activity ω).indicator i H-(B.activity ω).indicator i H) μ) : + A.movement C i H ≤ A.movement B i H+B.movement C i H := by + have hac : Integrable (fun ω => (C.activity ω).indicator i H-(A.activity ω).indicator i H) μ := by + have he : (fun ω => (C.activity ω).indicator i H-(A.activity ω).indicator i H) = + (fun ω => ((C.activity ω).indicator i H-(B.activity ω).indicator i H)+ + ((B.activity ω).indicator i H-(A.activity ω).indicator i H)) := by + funext ω + ring + rw [he] + exact hbc.add hab + change (∫ ω, |(C.activity ω).indicator i H-(A.activity ω).indicator i H| ∂μ) ≤ _ + calc + _ ≤ ∫ ω, |(B.activity ω).indicator i H-(A.activity ω).indicator i H|+ + |(C.activity ω).indicator i H-(B.activity ω).indicator i H| ∂μ := by + apply integral_mono hac.abs + (hab.abs.add hbc.abs) + intro ω + simpa only [Pi.add_apply,add_comm] using abs_sub_le ((C.activity ω).indicator i H) + ((B.activity ω).indicator i H) ((A.activity ω).indicator i H) + _ = _ := integral_add hab.abs + hbc.abs + +/-- Survival of the source's component certificate after arbitrary later +unrefined movements at the two vertices and the fixed bridge tip. No estimate +on changes of active-component labels is used or assumed. -/ +lemma refined_certificate_survival [SFinite μ] {J : Set ℝ} {root : Fin n} (o x y : M.Point J root) + {a b : Fin n} {H : ℝ} (hH : H ∈ M.heights a b) (hn : ¬ Consecutive a b) + (hx : a (B.activity ω).indicator i H- + (A.activity ω).indicator i H) μ) : + 2*μ.real E ≤ ‖B.refinedMap o x-B.refinedMap o y‖+ + 2*(A.movement B x.column x.height+A.movement B y.column y.height+A.movement B a H) := by + have hfin := (A.refinedMap_terminal_certificate o x y hH hn hx hy E hE ha hax hay).1 + have hEI : Integrable (E.indicator (fun _ => (2:ℝ))) μ := by + apply (integrable_indicator_iff hE).mpr + exact (integrableOn_const_iff (C := (2:ℝ))).mpr (Or.inr hfin) + have hmI (i : Fin n) (z : ℝ) : Integrable (fun ω => + (A.activity ω).movement (B.activity ω) i z) μ := by + simpa only [Activity.movement,Real.norm_eq_abs] using (hmove i z).norm + have hxI := hmI x.column x.height + have hyI := hmI y.column y.height + have haI := hmI a H + let p := Classical.choice (x.paths_nonempty y) + have hcost := B.cost_integrable p x.height y.height + have hg := integral_mono hEI (hcost.add (((hxI.add hyI).add haI).const_mul 2)) + (fun ω => show E.indicator (fun _ => (2:ℝ)) ω ≤ + (B.activity ω).cost x.column y.column x.height y.height+ + 2*((A.activity ω).movement (B.activity ω) x.column x.height+ + (A.activity ω).movement (B.activity ω) y.column y.height+ + (A.activity ω).movement (B.activity ω) a H) by + by_cases he : ω ∈ E + · rw [Set.indicator_of_mem he] + exact (A.activity ω).terminal_survival (B.activity ω) hH hn hx hy + (ha ω he) (hax ω he) (hay ω he) + · rw [Set.indicator_of_notMem he] + linarith [(B.activity ω).cost_nonneg x.column y.column x.height y.height, + (A.activity ω).movement_nonneg (B.activity ω) x.column x.height, + (A.activity ω).movement_nonneg (B.activity ω) y.column y.height, + (A.activity ω).movement_nonneg (B.activity ω) a H]) + rw [integral_indicator_const _ hE,smul_eq_mul,mul_comm] at hg + rw [B.norm_refinedMap_sub] + change _ ≤ _+2*((∫ ω, |(B.activity ω).indicator x.column x.height- + (A.activity ω).indicator x.column x.height| ∂μ)+ + (∫ ω, |(B.activity ω).indicator y.column y.height- + (A.activity ω).indicator y.column y.height| ∂μ)+ + (∫ ω, |(B.activity ω).indicator a H-(A.activity ω).indicator a H| ∂μ)) + dsimp only [Pi.add_apply] at hg + have e1 := integral_add hcost (((hxI.add hyI).add haI).const_mul 2) + have e2 := integral_add (hxI.add hyI) haI + have e3 := integral_add hxI hyI + simp only [Pi.add_apply] at e1 e2 e3 + rw [e1,integral_const_mul,e2,e3] at hg + exact hg + +end SetSystem +end PlanarL1.Columns.Model + + + +end + +end OAI diff --git a/lean/OAI/Combinatorics/PlanarL1/Dilation.lean b/lean/OAI/Combinatorics/PlanarL1/Dilation.lean new file mode 100644 index 0000000000000000000000000000000000000000..2821944fc5ca5f49c2603c5f8f4f1ebd7352747f --- /dev/null +++ b/lean/OAI/Combinatorics/PlanarL1/Dilation.lean @@ -0,0 +1,485 @@ +import OAI.Combinatorics.PlanarL1.SecondaryBatch + +namespace OAI + +section + +namespace PlanarL1.Columns.Model +open Set +open scoped NNReal +attribute [local instance] Classical.propDecidable +variable {n : ℕ} (M : Model n) (c : ℝ) (hc : 0 c*H) '' M.heights i j + symm i j := by rw [M.symm i j] + permitted i j H h := by + obtain ⟨T,hT,rfl⟩ := h + exact M.permitted i j T hT + compact i j := (M.compact i j).image (continuous_const.mul continuous_id) + noncrossing := M.noncrossing + terminal i j ha hn := by + obtain ⟨H,hH,hT⟩ := M.terminal i j ha hn + refine ⟨c*H,by simp only [hH,image_singleton],?_⟩ + intro k T ht + rcases ht with ⟨U,hU,rfl⟩ | ⟨U,hU,rfl⟩ + · exact mul_le_mul_of_nonneg_left (hT k U (Or.inl hU)) hc.le + · exact mul_le_mul_of_nonneg_left (hT k U (Or.inr hU)) hc.le + +include hc in +lemma mem_dilate_set {J : Set ℝ} {H : ℝ} : + H ∈ (fun T => c*T) '' J ↔ H/c ∈ J := by + constructor + · rintro ⟨T,hT,rfl⟩ + simpa [hc.ne'] using hT + · intro h + exact ⟨H/c,h,mul_div_cancel₀ H hc.ne'⟩ + +lemma dilate_mem_heights {i j : Fin n} {H : ℝ} : + H ∈ (M.dilate c hc).heights i j ↔ H/c ∈ M.heights i j := + mem_dilate_set c hc + +lemma dilate_activeGraph (J : Set ℝ) : + (M.dilate c hc).activeGraph ((fun T => c*T) '' J)=M.activeGraph J := by + ext i j + simp only [activeGraph,mem_dilate_set c hc,dilate_mem_heights] + constructor + · rintro ⟨H,hH,hs⟩ + exact ⟨H/c,hH,hs⟩ + · rintro ⟨H,hH,hs⟩ + exact ⟨c*H,by simpa [hc.ne'] using hH,by simpa [hc.ne'] using hs⟩ + +namespace Path +variable {M c} {J : Set ℝ} {i j : Fin n} + +noncomputable def dilate : {i j : Fin n} → M.Path J i j → + (M.dilate c hc).Path ((fun T => c*T) '' J) i j + | _,_,.nil i => .nil i + | _,_,.cons H hH hs p => .cons (c*H) ⟨H,hH,rfl⟩ ⟨H,hs,rfl⟩ (dilate p) + +lemma dilate_length (p : M.Path J i j) (a b : ℝ) : + (p.dilate hc).length (c*a) (c*b)=c*p.length a b := by + induction p generalizing a with + | nil => simp only [dilate,length,← mul_sub,abs_mul,abs_of_pos hc] + | cons H hH hs p ih => + simp only [dilate,length,ih,← mul_sub,abs_mul,abs_of_pos hc,mul_add] + +noncomputable def undilate : {i j : Fin n} → + (M.dilate c hc).Path ((fun T => c*T) '' J) i j → M.Path J i j + | _,_,.nil i => .nil i + | _,_,.cons H hH hs p => .cons (H/c) ((mem_dilate_set c hc).mp hH) + ((M.dilate_mem_heights c hc).mp hs) (undilate p) + +lemma undilate_length (p : (M.dilate c hc).Path ((fun T => c*T) '' J) i j) (a b : ℝ) : + c*(p.undilate hc).length (a/c) (b/c)=p.length a b := by + induction p generalizing a with + | nil => + simp only [undilate,length,← sub_div,abs_div,abs_of_pos hc] + exact mul_div_cancel₀ _ hc.ne' + | cons H hH hs p ih => + simp only [undilate,length,mul_add,ih,← sub_div,abs_div,abs_of_pos hc, + mul_div_cancel₀ _ hc.ne'] +end Path + +namespace Point +variable {M c} {J : Set ℝ} {root : Fin n} + +noncomputable def dilate (x : M.Point J root) : + (M.dilate c hc).Point ((fun T => c*T) '' J) root where + column := x.column + height := c*x.height + inBand := ⟨x.height,x.inBand,rfl⟩ + reachable := by rw [M.dilate_activeGraph]; exact x.reachable + +noncomputable def undilate (x : (M.dilate c hc).Point ((fun T => c*T) '' J) root) : + M.Point J root where + column := x.column + height := x.height/c + inBand := (mem_dilate_set c hc).mp x.inBand + reachable := by rw [← M.dilate_activeGraph c hc J]; exact x.reachable + +lemma dilate_distance (x y : M.Point J root) : + (x.dilate hc).distance (y.dilate hc)=c*x.distance y := by + apply le_antisymm + · rw [mul_comm c] + apply (div_le_iff₀ hc).mp + have := x.paths_nonempty y + apply le_ciInf + intro p + have h := (x.dilate hc).distance_le (y.dilate hc) (p.dilate hc) + change (x.dilate hc).distance (y.dilate hc) ≤ + (p.dilate hc).length (c*x.height) (c*y.height) at h + rw [Path.dilate_length hc] at h + exact (div_le_iff₀ hc).mpr (by nlinarith only [h]) + · have := (x.dilate hc).paths_nonempty (y.dilate hc) + apply le_ciInf + intro p + have h := mul_le_mul_of_nonneg_left (x.distance_le y (p.undilate hc)) hc.le + have he := p.undilate_length hc (c*x.height) (c*y.height) + simp only [mul_div_cancel_left₀ _ hc.ne'] at he + exact h.trans_eq he + +lemma dilate_dist (x y : M.Point J root) : + dist (x.dilate hc) (y.dilate hc)=c*dist x y := x.dilate_distance hc y + +@[simp] lemma undilate_dilate (x : M.Point J root) : (x.dilate hc).undilate hc=x := by + cases x + simp only [dilate,undilate,mul_div_cancel_left₀ _ hc.ne'] + +@[simp] lemma dilate_undilate (x : (M.dilate c hc).Point ((fun T => c*T) '' J) root) : + (x.undilate hc).dilate hc=x := by + cases x + simp only [dilate,undilate,mul_div_cancel₀ _ hc.ne'] + +lemma undilate_dist (x y : (M.dilate c hc).Point ((fun T => c*T) '' J) root) : + dist (x.undilate hc) (y.undilate hc)=dist x y/c := by + have h := (x.undilate hc).dilate_dist hc (y.undilate hc) + rw [dilate_undilate,dilate_undilate] at h + apply (eq_div_iff hc.ne').mpr + nlinarith only [h] +end Point + +include hc in +lemma dilate_set_closed {J : Set ℝ} (hJ : IsClosed J) : + IsClosed ((fun T => c*T) '' J) := by + have he : (fun T => c*T) '' J = (fun T => T/c) ⁻¹' J := by + ext H + exact mem_dilate_set c hc + rw [he] + exact hJ.preimage (continuous_id.div_const c) + +include hc in +lemma dilate_set_convex {J : Set ℝ} (hJ : J.OrdConnected) : + ((fun T => c*T) '' J).OrdConnected := by + have he : (fun T => c*T) '' J = (fun T => T/c) ⁻¹' J := by + ext H + exact mem_dilate_set c hc + rw [he] + exact hJ.preimage_mono (fun _ _ h => div_le_div_of_nonneg_right h hc.le) + +namespace Field +variable {M c} {J : Set ℝ} {L : ℝ≥0} + +/-- Field values have length units too. The vertical Lipschitz constant does +not change on passing to new physical units. -/ +noncomputable def dilate (F : M.Field J L) : + (M.dilate c hc).Field ((fun T => c*T) '' J) L where + value i H := c*F.value i ⟨H.val/c,(mem_dilate_set c hc).mp H.property⟩ + vertical i := by + apply LipschitzWith.of_dist_le_mul + intro H T + have h := (F.vertical i).dist_le_mul + ⟨H.val/c,(mem_dilate_set c hc).mp H.property⟩ + ⟨T.val/c,(mem_dilate_set c hc).mp T.property⟩ + simp only [Real.dist_eq,Subtype.dist_eq] at h ⊢ + rw [← mul_sub,abs_mul,abs_of_pos hc] + apply (mul_le_mul_of_nonneg_left h hc.le).trans_eq + rw [← sub_div,abs_div,abs_of_pos hc] + field_simp + switch i j H hs := by + rw [F.switch i j ⟨H.val/c,(mem_dilate_set c hc).mp H.property⟩ + ((M.dilate_mem_heights c hc).mp hs)] + +lemma dilate_eval (F : M.Field J L) {root : Fin n} (x : M.Point J root) : + (F.dilate hc).eval (x.dilate hc)=c*F.eval x := by + simp only [eval,dilate,Point.dilate,mul_div_cancel_left₀ _ hc.ne'] + +lemma dilate_orderedFrom {k : ℕ} {M : Model (k+1)} {J : Set ℝ} {L : ℝ≥0} + (F : M.Field J L) {a b : Fin (k+1)} (ho : F.OrderedFrom a b) : + (F.dilate hc).OrderedFrom a b := by + refine ⟨?_,?_,?_⟩ + · intro H i + exact mul_le_mul_of_nonneg_left (ho.1 ⟨H.val/c,(mem_dilate_set c hc).mp H.property⟩ i) hc.le + · intro H i j hij hjb + exact mul_le_mul_of_nonneg_left (ho.2.1 ⟨H.val/c,(mem_dilate_set c hc).mp H.property⟩ i j hij hjb) hc.le + · intro H i j hbi hij + exact mul_le_mul_of_nonneg_left (ho.2.2 ⟨H.val/c,(mem_dilate_set c hc).mp H.property⟩ i j hbi hij) hc.le +end Field + +namespace Point +variable {M c} {J : Set ℝ} {root : Fin n} +lemma dilate_radialValue (o : M.Point J root) (i : Fin n) + (H : (fun T => c*T) '' J) : + (o.dilate hc).radialValue i H = + c*o.radialValue i ⟨H.val/c,(mem_dilate_set c hc).mp H.property⟩ := by + by_cases hi : (M.activeGraph J).Reachable root i + · have hi' : ((M.dilate c hc).activeGraph ((fun T => c*T) '' J)).Reachable root i := by + rwa [M.dilate_activeGraph] + simp only [radialValue,dite_eq_left hi,dite_eq_left hi'] + let x : M.Point J root := ⟨i,H.val/c,(mem_dilate_set c hc).mp H.property,hi⟩ + have hx : (x.dilate hc)=(⟨i,H.val,H.property,hi'⟩ : + (M.dilate c hc).Point ((fun T => c*T) '' J) root) := by + simp only [x,dilate,mul_div_cancel₀ _ hc.ne'] + rw [← hx] + exact o.dilate_dist hc x + · have hi' : ¬((M.dilate c hc).activeGraph ((fun T => c*T) '' J)).Reachable root i := by + rwa [M.dilate_activeGraph] + simp only [radialValue,dite_eq_right hi,dite_eq_right hi',mul_zero] +end Point + +namespace OrdinaryData +variable {M c} +noncomputable def dilate (D : OrdinaryData M) : OrdinaryData (M.dilate c hc) where + band := (fun T => c*T) '' D.band + closed := dilate_set_closed c hc D.closed + convex := dilate_set_convex c hc D.convex + origin := D.origin.map (fun o => ⟨o.1,o.2.dilate hc⟩) + constant := c*D.constant + orientation := D.orientation + unit_orientation := D.unit_orientation + +lemma dilate_comparison (D : OrdinaryData M) (i : Fin n) (H : (D.dilate hc).band) : + (D.dilate hc).comparison.value i H = + c*D.comparison.value i ⟨H.val/c,(mem_dilate_set c hc).mp H.property⟩ := by + cases he : D.origin with + | none => simp only [comparison,dilate,he,Option.map_none,Field.constant,mul_zero] + | some o => + simp only [comparison,dilate,he,Option.map_some,Point.radialField] + exact o.2.dilate_radialValue hc i H + +lemma dilate_value (D : OrdinaryData M) (i : Fin n) (H : (D.dilate hc).band) : + (D.dilate hc).value i H = + c*D.value i ⟨H.val/c,(mem_dilate_set c hc).mp H.property⟩ := by + simp only [value,dilate_comparison] + change c*D.constant+D.orientation*(c*D.comparison.value i _) = _ + ring +end OrdinaryData + +namespace OrderedData +variable {k : ℕ} {M : Model (k+1)} {c} +noncomputable def dilate (D : OrderedData M) : OrderedData (M.dilate c hc) where + band := (fun T => c*T) '' D.band + closed := dilate_set_closed c hc D.closed + convex := dilate_set_convex c hc D.convex + base := D.base.dilate hc + lower := D.lower + upper := D.upper + ordered := D.base.dilate_orderedFrom hc D.ordered + auxiliary := D.auxiliary.dilate hc + +lemma dilate_value (D : OrderedData M) (lam : ℝ≥0) (i : Fin (k+1)) (H : (D.dilate hc).band) : + (D.dilate hc).value lam i H = + c*D.value lam i ⟨H.val/c,(mem_dilate_set c hc).mp H.property⟩ := by + simp only [value,dilate,Field.dilate] + ring +end OrderedData + +namespace BData +variable {k : ℕ} {M : Model (k+1)} {c} +noncomputable def dilate : BData M → BData (M.dilate c hc) + | .ordinary D => .ordinary (D.dilate hc) + | .ordered D => .ordered (D.dilate hc) + +lemma dilate_band (D : BData M) : (D.dilate hc).band=(fun T => c*T) '' D.band := by + cases D <;> rfl + +lemma dilate_value (D : BData M) (lam : ℝ≥0) (i : Fin (k+1)) (H : (D.dilate hc).band) : + (D.dilate hc).value lam i H = + c*D.value lam i ⟨H.val/c,(mem_dilate_set c hc).mp (D.dilate_band hc ▸ H.property)⟩ := by + cases D with + | ordinary D => exact D.dilate_value hc i H + | ordered D => exact D.dilate_value hc lam i H +end BData +end PlanarL1.Columns.Model + + +namespace PlanarL1.Threshold +open MeasureTheory +open scoped ENNReal NNReal +variable (c : ℝ) (hc : 0 (z.1,c*z.2)) + (ENNReal.ofReal c • labelMeasure) labelMeasure := by + have hreal : MeasurePreserving (fun H : ℝ => c*H) + (ENNReal.ofReal c • volume) volume := by + refine ⟨measurable_const.mul measurable_id,?_⟩ + rw [Measure.map_smul (ENNReal.ofReal c) (f := fun H : ℝ => c*H) + (measurable_const.mul measurable_id).aemeasurable] + simpa only [abs_of_pos hc] using Real.smul_map_volume_mul_left hc.ne' + have hp := (MeasurePreserving.id fair).prod hreal + have hf : Prod.map (id : Bool → Bool) (fun H : ℝ => c*H) = + (fun z : Bool × ℝ => (z.1,c*z.2)) := by + funext z + cases z + rfl + simpa only [Measure.prod_smul_right,← labelMeasure_eq,hf] using hp + +namespace Variables +variable {Ω : Type*} [MeasurableSpace Ω] {μ : Measure Ω} {c} + +noncomputable def dilate (Z : Variables Ω μ) : + Variables Ω (ENNReal.ofReal c • μ) where + value ω := ((Z.value ω).1,c*(Z.value ω).2) + preserving := by + apply (dilation_preserving c hc).comp + refine ⟨Z.preserving.measurable,?_⟩ + rw [Measure.map_smul (hf := Z.preserving.measurable.aemeasurable),Z.preserving.map_eq] + +lemma dilate_active (Z : Variables Ω μ) (H P : ℝ) (ω : Ω) : + active (Z.dilate hc) H (c*P) ω ↔ active Z (H/c) P ω := by + change c*(Z.value ω).2 < (if (Z.value ω).1 then H+c*P else H-c*P) ↔ _ + have hH : H=c*(H/c) := (mul_div_cancel₀ H hc.ne').symm + rw [hH] + unfold active + cases hb : (Z.value ω).1 <;> simp only [Bool.false_eq_true,ite_false,ite_true] + · rw [← mul_sub,mul_lt_mul_iff_right₀ hc,mul_div_cancel_left₀ _ hc.ne'] + · rw [← mul_add,mul_lt_mul_iff_right₀ hc,mul_div_cancel_left₀ _ hc.ne'] +end Variables +end PlanarL1.Threshold + +namespace PlanarL1.Columns.Model +open MeasureTheory +open scoped ENNReal NNReal +variable {n : ℕ} {M : Model n} {c : ℝ} (hc : 0 c*T) '' D.band)).Reachable r i + rw [M.dilate_activeGraph,← hs] + exact h s p hp +end OrdinaryData + +namespace BData +variable {k : ℕ} {M : Model (k+1)} +lemma dilate_uses (D : BData M) (i : Fin (k+1)) (h : D.Uses i) : + (D.dilate hc).Uses i := by + cases D with + | ordinary D => exact D.dilate_origin_reachable hc i h + | ordered D => trivial +end BData + +namespace OrdinaryState +variable {κ : ℝ} {Ω : Type*} [MeasurableSpace Ω] {μ : Measure Ω} + +noncomputable def dilate (S : OrdinaryState M κ Ω μ) : + OrdinaryState (M.dilate c hc) κ Ω (ENNReal.ofReal c • μ) where + sets := S.sets.dilate hc + count := S.count + chart q := (S.chart q).dilate hc + labels q := (S.labels q).dilate hc + name i H := S.name i (H/c) + height_in i H := (mem_dilate_set c hc).mpr (S.height_in i (H/c)) + component_in i H := (S.chart (S.name i (H/c))).dilate_origin_reachable hc i + (S.component_in i (H/c)) + switch_name i j H hH := S.switch_name i j (H/c) ((M.dilate_mem_heights c hc).mp hH) + represents ω i H := by + change (S.sets.activity ω).active i (H/c) ↔ + Threshold.active ((S.labels (S.name i (H/c))).dilate hc) H + (κ*((S.chart (S.name i (H/c))).dilate hc).value i _) ω + rw [OrdinaryData.dilate_value hc] + rw [show κ*(c*(S.chart (S.name i (H/c))).value i _) = + c*(κ*(S.chart (S.name i (H/c))).value i _) by ring] + rw [Threshold.Variables.dilate_active hc] + exact S.represents ω i (H/c) +end OrdinaryState + +namespace BState +variable {k : ℕ} {M : Model (k+1)} +variable {κ : ℝ} {lam : ℝ≥0} {Ω : Type*} [MeasurableSpace Ω] {μ : Measure Ω} + +noncomputable def dilate (S : BState M κ lam Ω μ) : + BState (M.dilate c hc) κ lam Ω (ENNReal.ofReal c • μ) where + sets := S.sets.dilate hc + count := S.count + chart q := (S.chart q).dilate hc + labels q := (S.labels q).dilate hc + name i H := S.name i (H/c) + height_in i H := by + rw [BData.dilate_band] + exact (mem_dilate_set c hc).mpr (S.height_in i (H/c)) + component_in i H := (S.chart (S.name i (H/c))).dilate_uses hc i (S.component_in i (H/c)) + switch_name i j H hH := S.switch_name i j (H/c) ((M.dilate_mem_heights c hc).mp hH) + represents ω i H := by + change (S.sets.activity ω).active i (H/c) ↔ + Threshold.active ((S.labels (S.name i (H/c))).dilate hc) H + (κ*((S.chart (S.name i (H/c))).dilate hc).value lam i _) ω + rw [BData.dilate_value hc] + rw [show κ*(c*(S.chart (S.name i (H/c))).value lam i _) = + c*(κ*(S.chart (S.name i (H/c))).value lam i _) by ring] + rw [Threshold.Variables.dilate_active hc] + exact S.represents ω i (H/c) +end BState +end PlanarL1.Columns.Model + + + +end + +end OAI diff --git a/lean/OAI/Combinatorics/PlanarL1/DiskCrossing.lean b/lean/OAI/Combinatorics/PlanarL1/DiskCrossing.lean new file mode 100644 index 0000000000000000000000000000000000000000..70d5cb96bcc46f05a2302614ef2ff4e498b3cbd2 --- /dev/null +++ b/lean/OAI/Combinatorics/PlanarL1/DiskCrossing.lean @@ -0,0 +1,372 @@ +import OAI.Combinatorics.PlanarL1.Noncrossing + +namespace OAI + +section + +/-! ## Planar disk crossing by covering-angle lifting. -/ + +namespace PlanarL1.Topology +open Complex Real + +/-- The planar rectangle crossing obstruction, proved by lifting angles rather +than assuming a Jordan separation theorem. -/ +lemma rectangle_zero (F : C(unitInterval × unitInterval, ℂ)) + (hleft : ∀ t, (F (0,t)).re < 0) + (hright : ∀ t, 0 < (F (1,t)).re) + (hbottom : ∀ s, 0 < (F (s,0)).im) + (htop : ∀ s, (F (s,1)).im < 0) : + ∃ p, F p=0 := by + by_contra! hn + let cov : IsCoveringMap ((↑) : ℝ → Real.Angle) := AddCircle.isCoveringMap_coe (2*π) + let H : C(unitInterval × unitInterval, Real.Angle) := + ⟨fun p => (Complex.arg (F p) : Real.Angle), by + apply continuous_iff_continuousAt.mpr + intro p + exact (Complex.continuousAt_arg_coe_angle (hn p)).comp F.continuous.continuousAt⟩ + have left_cont : Continuous (fun t : unitInterval => Complex.arg (-F (0,t))+π) := by + apply Continuous.add_const + apply continuous_iff_continuousAt.mpr + intro t + exact (Complex.continuousAt_arg (by + left + simpa using neg_pos.mpr (hleft t))).comp + ((F.continuous.comp (continuous_const.prodMk continuous_id)).neg.continuousAt) + let L : C(unitInterval, ℝ) := ⟨fun t => Complex.arg (-F (0,t))+π,left_cont⟩ + have hL (t : unitInterval) : H (0,t) = (L t : Real.Angle) := by + dsimp [H,L] + rw [Complex.arg_neg_coe_angle (hn _)] + simp only [add_assoc,Real.Angle.coe_pi_add_coe_pi,add_zero] + let θ := cov.liftHomotopy H L hL + have θ_left : ∀ t, θ (0,t)=L t := cov.liftHomotopy_zero H L hL + have θ_lifts (p : unitInterval × unitInterval) : (θ p : Real.Angle)=H p := + congr_fun (cov.liftHomotopy_lifts H L hL) p + have arg_cont (f : C(unitInterval, ℂ)) (hf : ∀ t, f t ∈ Complex.slitPlane) : + Continuous (fun t => Complex.arg (f t)) := by + exact continuous_iff_continuousAt.mpr fun t => + (Complex.continuousAt_arg (hf t)).comp f.continuous.continuousAt + have bottom_cont : Continuous (fun s : unitInterval => Complex.arg (F (s,0))) := by + apply arg_cont ⟨fun s => F (s,0),F.continuous.comp (continuous_id.prodMk continuous_const)⟩ + intro s + exact Or.inr (ne_of_gt (hbottom s)) + have top_cont : Continuous (fun s : unitInterval => Complex.arg (F (s,1))) := by + apply arg_cont ⟨fun s => F (s,1),F.continuous.comp (continuous_id.prodMk continuous_const)⟩ + intro s + exact Or.inr (ne_of_lt (htop s)) + have right_cont : Continuous (fun t : unitInterval => Complex.arg (F (1,t))) := by + apply arg_cont ⟨fun t => F (1,t),F.continuous.comp (continuous_const.prodMk continuous_id)⟩ + intro t + exact Or.inl (hright t) + have hbottom_eq : (fun s : unitInterval => θ (s,0)) = fun s => Complex.arg (F (s,0)) := by + refine cov.eq_of_comp_eq + (θ.continuous.comp (continuous_id.prodMk continuous_const)) bottom_cont ?_ 0 ?_ + · exact funext fun s => θ_lifts (s,0) + · rw [θ_left] + dsimp [L] + rw [Complex.arg_neg_eq_arg_sub_pi_of_im_pos (hbottom 0)] + ring + have hright_eq : (fun t : unitInterval => θ (1,t)) = fun t => Complex.arg (F (1,t)) := by + refine cov.eq_of_comp_eq + (θ.continuous.comp (continuous_const.prodMk continuous_id)) right_cont ?_ 0 ?_ + · exact funext fun t => θ_lifts (1,t) + · exact congr_fun hbottom_eq 1 + have htop_eq : (fun s : unitInterval => θ (s,1)) = + fun s => Complex.arg (F (s,1))+2*π := by + refine cov.eq_of_comp_eq + (θ.continuous.comp (continuous_id.prodMk continuous_const)) (top_cont.add_const _) ?_ 0 ?_ + · funext s + change (θ (s,1) : Real.Angle) = ((Complex.arg (F (s,1))+2*π : ℝ) : Real.Angle) + rw [Real.Angle.coe_add,Real.Angle.coe_two_pi,add_zero] + exact θ_lifts (s,1) + · rw [θ_left] + dsimp [L] + rw [Complex.arg_neg_eq_arg_add_pi_of_im_neg (htop 0)] + ring + have hb := congr_fun htop_eq 1 + have hr := congr_fun hright_eq 1 + have := Real.pi_pos + linarith + +lemma disk_re_lt_one {z : ℂ} (h : ‖z‖ ≤ 1) (hne : z ≠ 1) : z.re < 1 := by + have hre := Complex.re_le_norm z + have hs := Complex.sq_norm_sub_sq_re z + have hn := norm_nonneg z + by_contra! hc + have he : z.re=1 := by linarith + have hi : z.im=0 := by nlinarith [sq_nonneg z.im] + exact hne (Complex.ext (by simpa using he) (by simpa using hi)) + +lemma disk_im_lt_one {z : ℂ} (h : ‖z‖ ≤ 1) (hne : z ≠ Complex.I) : z.im < 1 := by + have him := Complex.im_le_norm z + have hs := Complex.sq_norm_sub_sq_im z + have hn := norm_nonneg z + by_contra! hc + have he : z.im=1 := by linarith + have hr : z.re=0 := by nlinarith [sq_nonneg z.re] + exact hne (Complex.ext (by simpa using hr) (by simpa using he)) + +/-- Opposite endpoints in a disk force two continuous arcs to meet. This is +one normal form of nonalternation. -/ +lemma disk_opposite_arcs_meet (f g : C(unitInterval, ℂ)) + (hf : ∀ s, ‖f s‖ ≤ 1) (hg : ∀ t, ‖g t‖ ≤ 1) + (hf0 : f 0 = -1) (hf1 : f 1 = 1) + (hg0 : g 0 = -Complex.I) (hg1 : g 1 = Complex.I) : + ∃ s t, f s=g t := by + by_contra! hn + let F : C(unitInterval × unitInterval, ℂ) := + ⟨fun p => f p.1-g p.2,(f.continuous.comp continuous_fst).sub + (g.continuous.comp continuous_snd)⟩ + have hleft (t : unitInterval) : (F (0,t)).re < 0 := by + have hne : -g t ≠ (1 : ℂ) := by + intro he + apply hn 0 t + rw [hf0] + exact (neg_eq_iff_eq_neg.mp he).symm + have hh := disk_re_lt_one (z := -g t) (by simpa using hg t) hne + dsimp [F] + simp only [Complex.neg_re] at hh + simp only [hf0,Complex.neg_re,Complex.one_re] + linarith + have hright (t : unitInterval) : 0 < (F (1,t)).re := by + have hh := disk_re_lt_one (hg t) (by + intro he + exact hn 1 t (hf1.trans he.symm)) + dsimp [F] + simp only [hf1,Complex.one_re] + linarith + have hbottom (s : unitInterval) : 0 < (F (s,0)).im := by + have hne : -f s ≠ Complex.I := by + intro he + exact hn s 0 ((neg_eq_iff_eq_neg.mp he).trans hg0.symm) + have hh := disk_im_lt_one (z := -f s) (by simpa using hf s) hne + dsimp [F] + simp only [hg0,Complex.neg_im,Complex.I_im] at * + linarith + have htop (s : unitInterval) : (F (s,1)).im < 0 := by + have hh := disk_im_lt_one (hf s) (by + intro he + exact hn s 1 (he.trans hg1.symm)) + dsimp [F] + simp only [hg1,Complex.I_im] + linarith + obtain ⟨⟨s,t⟩,h⟩ := rectangle_zero F hleft hright hbottom htop + exact hn s t (sub_eq_zero.mp h) + +end PlanarL1.Topology + + + +end + +section + +/-! ## General cyclic-endpoint disk separation -/ + +namespace PlanarL1.Topology +open Complex Real Set + +/- An explicit annular extension reduces arbitrary cyclic boundary endpoints + to the already-proved cardinal-endpoint disk crossing obstruction. -/ +noncomputable def annularConnector (a b : ℝ) : + Path (Circle.exp a : ℂ) ((2 : ℂ) * (Circle.exp b : ℂ)) where + toFun t := ((1 + (t : ℝ) : ℝ) : ℂ) * + (Circle.exp ((1 - (t : ℝ)) * a + (t : ℝ) * b) : ℂ) + continuous_toFun := by fun_prop + source' := by simp + target' := by norm_num + +lemma norm_annularConnector (a b : ℝ) (t : unitInterval) : + ‖annularConnector a b t‖ = 1 + (t : ℝ) := by + change ‖((1 + (t : ℝ) : ℝ) : ℂ) * + (Circle.exp ((1 - (t : ℝ)) * a + (t : ℝ) * b) : ℂ)‖ = _ + rw [norm_mul, Circle.norm_coe, mul_one, Complex.norm_real, + Real.norm_eq_abs, abs_of_nonneg (by linarith [t.2.1])] + +lemma annularConnector_disjoint {a a' b b' : ℝ} + (ha : a < a') (ha' : a' - a < 2 * π) + (hb : b < b') (hb' : b' - b < 2 * π) : + Disjoint (range (annularConnector a b)) (range (annularConnector a' b')) := by + rw [Set.disjoint_left] + rintro z ⟨s, hs⟩ ⟨t, ht⟩ + have he : annularConnector a b s = annularConnector a' b' t := hs.trans ht.symm + have hn := congrArg norm he + rw [norm_annularConnector, norm_annularConnector] at hn + have hst : s = t := Subtype.ext (by linarith) + subst t + have hs0 := s.2.1 + have hs1 := s.2.2 + let u := (1 - (s : ℝ)) * a + (s : ℝ) * b + let v := (1 - (s : ℝ)) * a' + (s : ℝ) * b' + have huv : u < v := by + dsimp [u,v] + by_cases hz : (s : ℝ) = 0 + · simpa [hz] using ha + · have hp : 0 < (s : ℝ) := lt_of_le_of_ne hs0 (Ne.symm hz) + exact add_lt_add_of_le_of_lt + (mul_le_mul_of_nonneg_left ha.le (sub_nonneg.mpr hs1)) + (mul_lt_mul_of_pos_left hb hp) + have hspan : v - u < 2 * π := by + dsimp [u,v] + by_cases hz : (s : ℝ) = 0 + · simpa [hz] using ha' + · have hp : 0 < (s : ℝ) := lt_of_le_of_ne hs0 (Ne.symm hz) + have h₁ := mul_le_mul_of_nonneg_left ha'.le (sub_nonneg.mpr hs1) + have h₂ := mul_lt_mul_of_pos_left hb' hp + nlinarith + have hrad : ((1 + (s : ℝ) : ℝ) : ℂ) ≠ 0 := by + exact_mod_cast (ne_of_gt (by linarith : 0 < 1 + (s : ℝ))) + have he' : Circle.exp u = Circle.exp v := by + apply Subtype.ext + exact mul_left_cancel₀ hrad he + have heq := Circle.exp_injOn_Icc hspan + (show u ∈ Icc u v from ⟨le_rfl,huv.le⟩) + (show v ∈ Icc u v from ⟨huv.le,le_rfl⟩) he' + exact (ne_of_lt huv) heq + +/-- An annular connector meets the closed unit disk only at its source. -/ +lemma annularConnector_disk {a b : ℝ} {z : ℂ} + (hz : z ∈ range (annularConnector a b)) (hn : ‖z‖ ≤ 1) : + z = (Circle.exp a : ℂ) := by + rcases hz with ⟨t,rfl⟩ + rw [norm_annularConnector] at hn + have ht : t = 0 := Subtype.ext (by change (t : ℝ) = 0; linarith [t.2.1]) + subst t + exact (annularConnector a b).source + +lemma annularConnector_disjoint_disk {a b : ℝ} {S : Set ℂ} + (hS : ∀ z ∈ S, ‖z‖ ≤ 1) (ha : (Circle.exp a : ℂ) ∉ S) : + Disjoint (range (annularConnector a b)) S := by + rw [Set.disjoint_left] + intro z hz hzS + exact ha ((annularConnector_disk hz (hS z hzS)) ▸ hzS) + +lemma annular_extension_bound {a c : ℝ} + (p : Path (Circle.exp a : ℂ) (Circle.exp c : ℂ)) + (hp : ∀ t, ‖p t‖ ≤ 1) (b d : ℝ) : + ∀ t, ‖((annularConnector a b).symm.trans + (p.trans (annularConnector c d))) t‖ ≤ 2 := by + intro t + have hm := Set.mem_range_self + (f := ((annularConnector a b).symm.trans (p.trans (annularConnector c d)))) t + rw [Path.trans_range, Path.symm_range, Path.trans_range] at hm + rcases hm with hm | hm | hm + · rcases hm with ⟨s,hs⟩ + rw [← hs, norm_annularConnector] + linarith [s.2.2] + · rcases hm with ⟨s,hs⟩ + rw [← hs] + exact (hp s).trans (by norm_num) + · rcases hm with ⟨s,hs⟩ + rw [← hs, norm_annularConnector] + linarith [s.2.2] + +/-- Arbitrary four boundary endpoints in strict cyclic order, with no + injectivity requirement on either of the two disk paths. -/ +lemma disk_cyclic_arcs_meet (a₀ a₁ a₂ a₃ : ℝ) + (h₀₁ : a₀ < a₁) (h₁₂ : a₁ < a₂) (h₂₃ : a₂ < a₃) + (hspan : a₃ < a₀ + 2 * π) + (f : Path (Circle.exp a₀ : ℂ) (Circle.exp a₂ : ℂ)) + (g : Path (Circle.exp a₁ : ℂ) (Circle.exp a₃ : ℂ)) + (hf : ∀ s, ‖f s‖ ≤ 1) (hg : ∀ s, ‖g s‖ ≤ 1) : + ∃ s t, f s = g t := by + by_contra! hn + have hfg : Disjoint (range f) (range g) := by + rw [Set.disjoint_left] + rintro z ⟨s,rfl⟩ ⟨t,ht⟩ + exact hn s t ht.symm + let q₀ := annularConnector a₀ (-π) + let q₁ := annularConnector a₁ (-π/2) + let q₂ := annularConnector a₂ 0 + let q₃ := annularConnector a₃ (π/2) + have hq₀₁ : Disjoint (range q₀) (range q₁) := by + apply annularConnector_disjoint h₀₁ <;> linarith [Real.pi_pos] + have hq₀₃ : Disjoint (range q₀) (range q₃) := by + apply annularConnector_disjoint <;> linarith [Real.pi_pos] + have hq₂₁ : Disjoint (range q₂) (range q₁) := by + apply Disjoint.symm + apply annularConnector_disjoint h₁₂ <;> linarith [Real.pi_pos] + have hq₂₃ : Disjoint (range q₂) (range q₃) := by + apply annularConnector_disjoint h₂₃ <;> linarith [Real.pi_pos] + have hfg₀ : (Circle.exp a₀ : ℂ) ∉ range g := by + exact fun hm => Set.disjoint_left.mp hfg f.source_mem_range hm + have hfg₂ : (Circle.exp a₂ : ℂ) ∉ range g := by + exact fun hm => Set.disjoint_left.mp hfg f.target_mem_range hm + have hgf₁ : (Circle.exp a₁ : ℂ) ∉ range f := by + exact fun hm => Set.disjoint_left.mp hfg hm g.source_mem_range + have hgf₃ : (Circle.exp a₃ : ℂ) ∉ range f := by + exact fun hm => Set.disjoint_left.mp hfg hm g.target_mem_range + have hf' : ∀ z ∈ range f, ‖z‖ ≤ 1 := by rintro z ⟨s,rfl⟩; exact hf s + have hg' : ∀ z ∈ range g, ‖z‖ ≤ 1 := by rintro z ⟨s,rfl⟩; exact hg s + have hq₀g := annularConnector_disjoint_disk (b := -π) hg' hfg₀ + have hq₂g := annularConnector_disjoint_disk (b := 0) hg' hfg₂ + have hfq₁ := (annularConnector_disjoint_disk (b := -π/2) hf' hgf₁).symm + have hfq₃ := (annularConnector_disjoint_disk (b := π/2) hf' hgf₃).symm + let F := q₀.symm.trans (f.trans q₂) + let G := q₁.symm.trans (g.trans q₃) + have hFG : Disjoint (range F) (range G) := by + simp only [F,G,Path.trans_range,Path.symm_range, + Set.disjoint_union_left,Set.disjoint_union_right] + exact ⟨⟨hq₀₁,hfq₁,hq₂₁⟩,⟨hq₀g,hfg,hq₂g⟩,hq₀₃,hfq₃,hq₂₃⟩ + let F' : C(unitInterval, ℂ) := ⟨fun s => F s / 2,by fun_prop⟩ + let G' : C(unitInterval, ℂ) := ⟨fun t => G t / 2,by fun_prop⟩ + have hF : ∀ s, ‖F' s‖ ≤ 1 := by + intro s + change ‖F s / 2‖ ≤ 1 + rw [norm_div, Complex.norm_ofNat] + exact (div_le_one (by norm_num)).mpr (annular_extension_bound f hf (-π) 0 s) + have hG : ∀ s, ‖G' s‖ ≤ 1 := by + intro s + change ‖G s / 2‖ ≤ 1 + rw [norm_div, Complex.norm_ofNat] + exact (div_le_one (by norm_num)).mpr + (annular_extension_bound g hg (-π/2) (π/2) s) + have hF₀ : F' 0 = -1 := by + change F 0 / 2 = -1 + rw [F.source] + simp [Circle.coe_exp] + have hF₁ : F' 1 = 1 := by + change F 1 / 2 = 1 + rw [F.target] + simp + have hG₀ : G' 0 = -Complex.I := by + change G 0 / 2 = -Complex.I + rw [G.source] + simp only [Circle.coe_exp, Complex.ofReal_div, Complex.ofReal_neg, + Complex.ofReal_ofNat, Complex.exp_neg_pi_div_two_mul_I] + ring + have hG₁ : G' 1 = Complex.I := by + change G 1 / 2 = Complex.I + rw [G.target] + simp [Circle.coe_exp, Complex.exp_pi_div_two_mul_I] + obtain ⟨s,t,hst⟩ := disk_opposite_arcs_meet F' G' hF hG hF₀ hF₁ hG₀ hG₁ + have he : F s = G t := (div_left_inj' (by norm_num : (2 : ℂ) ≠ 0)).mp hst + exact Set.disjoint_left.mp hFG (Set.mem_range_self s) (he ▸ Set.mem_range_self t) + +/-- Disjoint disk arcs with cyclically ordered boundary positions give exactly + the combinatorial noncrossing relation used by column models. This is the + final step of the complementary-disk argument. -/ +lemma noncrossing_of_disk_arcs {n : ℕ} (G : SimpleGraph (Fin n)) + (angle : Fin n → ℝ) (horder : StrictMono angle) + (hspan : ∀ i j, angle j - angle i < 2 * π) + (arc : ∀ i j, G.Adj i j → Path (Circle.exp (angle i) : ℂ) + (Circle.exp (angle j) : ℂ)) + (hdisk : ∀ i j h t, ‖arc i j h t‖ ≤ 1) + (hdisjoint : ∀ i j h k l h', i ≠ k → i ≠ l → j ≠ k → j ≠ l → + Disjoint (range (arc i j h)) (range (arc k l h'))) : + PlanarL1.ColumnOrder.Noncrossing G := by + intro a b c d hab hbc hcd h + obtain ⟨s,t,hst⟩ := disk_cyclic_arcs_meet + (angle a) (angle b) (angle c) (angle d) + (horder hab) (horder hbc) (horder hcd) (by linarith [hspan a d]) + (arc a c h.1) (arc b d h.2) (hdisk a c h.1) (hdisk b d h.2) + have hd := hdisjoint a c h.1 b d h.2 (ne_of_lt hab) + (ne_of_lt (hab.trans (hbc.trans hcd))) (ne_of_gt hbc) (ne_of_lt hcd) + exact Set.disjoint_left.mp hd (Set.mem_range_self s) (hst ▸ Set.mem_range_self t) + +end PlanarL1.Topology + + + +end + +end OAI diff --git a/lean/OAI/Combinatorics/PlanarL1/Distance.lean b/lean/OAI/Combinatorics/PlanarL1/Distance.lean new file mode 100644 index 0000000000000000000000000000000000000000..1e65cf7747d2e1ecd04c1e63ccaf9643bb1366cd --- /dev/null +++ b/lean/OAI/Combinatorics/PlanarL1/Distance.lean @@ -0,0 +1,1088 @@ +import OAI.Combinatorics.PlanarL1.Columns + +namespace OAI + +section + +namespace PlanarL1 +namespace Columns +namespace Model + +variable {n : ℕ} (M : Model n) +namespace Point + +variable {M} {J : Set ℝ} {root : Fin n} + +lemma paths_nonempty (x y : M.Point J root) : Nonempty (M.Path J x.column y.column) := by + obtain ⟨p⟩ := x.reachable.symm.trans y.reachable + obtain ⟨q, _⟩ := Path.exists_word p + exact ⟨q⟩ + +noncomputable def distance (x y : M.Point J root) : ℝ := + ⨅ p : M.Path J x.column y.column, p.length x.height y.height + +lemma lengths_bddBelow (x y : M.Point J root) : + BddBelow (Set.range fun p : M.Path J x.column y.column => p.length x.height y.height) := + ⟨0, by rintro _ ⟨p, rfl⟩; exact p.length_nonneg _ _⟩ + +lemma distance_le (x y : M.Point J root) (p : M.Path J x.column y.column) : + x.distance y ≤ p.length x.height y.height := + ciInf_le (x.lengths_bddBelow y) p + +lemma distance_nonneg (x y : M.Point J root) : 0 ≤ x.distance y := by + have := x.paths_nonempty y + exact le_ciInf (fun p => p.length_nonneg _ _) + +lemma height_change_le (x y : M.Point J root) : |x.height - y.height| ≤ x.distance y := by + have := x.paths_nonempty y + exact le_ciInf (fun p => p.height_change_le _ _) + +lemma distance_self (x : M.Point J root) : x.distance x = 0 := by + apply le_antisymm _ (x.distance_nonneg x) + simpa only [Path.length, sub_self, abs_zero] using x.distance_le x (.nil _) + +lemma distance_triangle (x y z : M.Point J root) : + x.distance z ≤ x.distance y + y.distance z := by + have := x.paths_nonempty y + have := y.paths_nonempty z + apply le_ciInf_add + intro p + apply le_add_ciInf + intro q + exact (x.distance_le z (p.append q)).trans (p.length_append_le q _ _ _) + +lemma distance_comm (x y : M.Point J root) : x.distance y = y.distance x := by + have := x.paths_nonempty y + have := y.paths_nonempty x + suffices ∀ x y : M.Point J root, x.distance y ≤ y.distance x by + exact le_antisymm (this x y) (this y x) + intro x y + have := y.paths_nonempty x + apply le_ciInf + intro p + simpa only [Path.length_reverse] using x.distance_le y p.reverse + +noncomputable instance : PseudoMetricSpace (M.Point J root) where + dist := distance + dist_self := distance_self + dist_comm := distance_comm + dist_triangle := distance_triangle + +/-- The full vertical interval is isometric, before or after the quotient. +No path's vertical variation can improve upon direct travel. -/ +lemma dist_same_column (x y : M.Point J root) (h : x.column = y.column) : + dist x y = |x.height - y.height| := by + rcases x with ⟨i, a, ha, hx⟩ + rcases y with ⟨j, b, hb, hy⟩ + change i = j at h + subst j + let x : M.Point J root := ⟨i, a, ha, hx⟩ + let y : M.Point J root := ⟨i, b, hb, hy⟩ + exact le_antisymm (x.distance_le y (.nil i)) (x.height_change_le y) + +/-- Vertical motion on a chosen column representative. -/ +def withHeight (x : M.Point J root) (H : ℝ) (hH : H ∈ J) : M.Point J root := + ⟨x.column, H, hH, x.reachable⟩ + +@[simp] lemma withHeight_self (x : M.Point J root) : + x.withHeight x.height x.inBand = x := rfl + +lemma dist_withHeight (x : M.Point J root) (H : ℝ) (hH : H ∈ J) : + dist x (x.withHeight H hH) = |x.height - H| := x.dist_same_column _ rfl + +lemma dist_le_switch (x y : M.Point J root) {H : ℝ} (hH : H ∈ J) + (hs : H ∈ M.heights x.column y.column) : + dist x y ≤ |x.height - H| + |H - y.height| := + x.distance_le y (.cons H hH hs (.nil _)) + +/-- The source's adjacent-midpoint estimate: one available switch costs at +most the width of the band. -/ +lemma dist_midpoints_le (x y : M.Point J root) {H a : ℝ} + (hx : x.height = H) (hy : y.height = H) + (hhalf : ∀ T ∈ J, |H - T| ≤ a / 2) + (h : (M.activeGraph J).Adj x.column y.column) : dist x y ≤ a := by + obtain ⟨T, hT, hs⟩ := h + have hd := x.dist_le_switch y hT hs + rw [hx, hy, abs_sub_comm T H] at hd + linarith [hhalf T hT] + +/-- Lengths realized by words with no repeated column. -/ +def simpleLengths (x y : M.Point J root) : Set ℝ := + ⋃ w : (M.activeGraph J).Path x.column y.column, + Set.range (fun s : M.Schedule J w.val => s.toPath.length x.height y.height) + +lemma mem_simpleLengths (x y : M.Point J root) (p : M.Path J x.column y.column) + (hp : p.word.IsPath) : p.length x.height y.height ∈ x.simpleLengths y := by + apply Set.mem_iUnion.mpr + refine ⟨⟨p.word, hp⟩, ?_⟩ + exact ⟨Schedule.ofPath p, by simp only [Schedule.toPath_ofPath]⟩ + +lemma simpleLengths_nonempty (x y : M.Point J root) : (x.simpleLengths y).Nonempty := by + obtain ⟨p⟩ := x.paths_nonempty y + obtain ⟨q, hq, _⟩ := p.simple_replacement x.height y.height + exact ⟨q.length x.height y.height, x.mem_simpleLengths y q hq⟩ + +lemma isCompact_simpleLengths (hJ : IsClosed J) (x y : M.Point J root) : + IsCompact (x.simpleLengths y) := by + classical + apply isCompact_iUnion + intro w + let := Schedule.compactSpace hJ w.val + exact isCompact_range (Schedule.continuous_length w.val _ _ id + continuous_const continuous_const continuous_id) + +/-- Geometry, `geo:geodesics`: finite intrinsic distances are attained by a +switching path with no repeated column. Compactness is required of the actual +switch-height sets, rather than of an artificial discretization. -/ +lemma exists_shortest (hJ : IsClosed J) (x y : M.Point J root) : + ∃ p : M.Path J x.column y.column, + p.word.IsPath ∧ p.length x.height y.height = dist x y := by + have hc := x.isCompact_simpleLengths hJ y + have hm := hc.isLeast_sInf (x.simpleLengths_nonempty y) + obtain ⟨w, s, hs⟩ := Set.mem_iUnion.mp hm.1 + change s.toPath.length x.height y.height = sInf (x.simpleLengths y) at hs + refine ⟨s.toPath, ?_, ?_⟩ + · rw [Schedule.word_toPath] + exact w.property + · apply le_antisymm _ (x.distance_le y s.toPath) + have := x.paths_nonempty y + apply le_ciInf + intro p + obtain ⟨q, hq, hlen⟩ := p.simple_replacement x.height y.height + rw [hs] + exact (hm.2 (x.mem_simpleLengths y q hq)).trans hlen + +/-- Two short paths whose projected words meet on a column give a short +connection, with only one band-width paid for the vertical transfer. -/ +lemma dist_le_of_shared_column (x y : M.Point J root) {i j v : Fin n} + (p : M.Path J x.column i) (q : M.Path J y.column j) + {H T a : ℝ} (hH : H ∈ J) (hT : T ∈ J) + (hwidth : ∀ r ∈ J, ∀ s ∈ J, |r - s| ≤ a) + (hpv : v ∈ p.word.support) (hqv : v ∈ q.word.support) : + dist x y ≤ p.length x.height H + q.length y.height T + a := by + obtain ⟨A, hA, p₁, p₂, hp⟩ := p.split_at_column x.inBand hH hpv + obtain ⟨B, hB, q₁, q₂, hq⟩ := q.split_at_column y.inBand hT hqv + have hd := x.distance_le y (p₁.append q₁.reverse) + have ha := p₁.length_append_le q₁.reverse x.height B y.height + have he := p₁.length_end_le x.height A B + rw [q₁.length_reverse] at ha + have hw := hwidth A hA B hB + have hn₁ := p₂.length_nonneg A H + have hn₂ := q₂.length_nonneg B T + change x.distance y ≤ _ + linarith + +/-- The source's quotient identifies precisely finite chains of switches at a +single height. This verifies that metric separation has not introduced any +extra quotient relations. -/ +lemma zero_distance_iff (hJ : IsClosed J) (x y : M.Point J root) : + dist x y = 0 ↔ x.height = y.height ∧ + (M.activeGraph {x.height}).Reachable x.column y.column := by + constructor + · intro h + obtain ⟨p, _, hp⟩ := x.exists_shortest hJ y + exact p.zero_length_identifies _ _ (hp.trans h) + · rintro ⟨hxy, ⟨w⟩⟩ + obtain ⟨p, hp⟩ := Path.exists_zero_path x.height x.inBand w + apply le_antisymm _ dist_nonneg + have h := x.distance_le y p + rwa [← hxy, hp] at h + +/-- Exact shortest paths to a fixed-height column stay in its distance +sublevel after projection to column indices. This is the metric assertion +underlying `geo:sublevel`, not merely a graph-connectivity assumption. -/ +lemma shortest_sublevel (hJ : IsClosed J) (o y : M.Point J root) : + ∃ p : M.Path J o.column y.column, + p.length o.height y.height = dist o y ∧ + ∀ v ∈ p.word.support, ∃ hv : (M.activeGraph J).Reachable root v, + dist o (⟨v, y.height, y.inBand, hv⟩ : M.Point J root) ≤ dist o y := by + obtain ⟨p, _, hp⟩ := o.exists_shortest hJ y + refine ⟨p, hp, ?_⟩ + intro v hv + obtain ⟨H, _, q, r, hqr⟩ := p.split_at_column o.inBand y.inBand hv + refine ⟨o.reachable.trans q.word.reachable, ?_⟩ + let z : M.Point J root := ⟨v, y.height, y.inBand, o.reachable.trans q.word.reachable⟩ + have h1 := o.distance_le z q + have h2 := q.length_end_le o.height H y.height + have h3 := r.height_change_le H y.height + change o.distance z ≤ dist o y + linarith + +/-- The fixed-height radial sublevel in the active column graph. Columns +outside the chosen component are absent, as for the source's value `+∞`. -/ +def sublevel (o : M.Point J root) (H : ℝ) (hH : H ∈ J) (t : ℝ) : Set (Fin n) := + {i | ∃ hi : (M.activeGraph J).Reachable root i, + dist o (⟨i, H, hH, hi⟩ : M.Point J root) ≤ t} + +lemma mem_sublevel_iff (o x : M.Point J root) (H : ℝ) (hH : H ∈ J) (t : ℝ) : + x.column ∈ o.sublevel H hH t ↔ dist o (x.withHeight H hH) ≤ t := by + constructor + · rintro ⟨_, hd⟩ + exact hd + · intro hd + exact ⟨x.reachable, hd⟩ + +lemma sublevel_preconnected (hJ : IsClosed J) (o : M.Point J root) + (H : ℝ) (hH : H ∈ J) (t : ℝ) : + ((M.activeGraph J).induce (o.sublevel H hH t)).Preconnected := by + intro x y + obtain ⟨hx, hdx⟩ := x.property + obtain ⟨hy, hdy⟩ := y.property + obtain ⟨p, _, hp⟩ := o.shortest_sublevel hJ ⟨x.val, H, hH, hx⟩ + obtain ⟨q, _, hq⟩ := o.shortest_sublevel hJ ⟨y.val, H, hH, hy⟩ + have hmem : ∀ v ∈ (p.word.reverse.append q.word).support, + v ∈ o.sublevel H hH t := by + intro v hv + rcases (p.word.reverse.mem_support_append_iff q.word).mp hv with hv | hv + · have hv' : v ∈ p.word.support := by simpa using hv + obtain ⟨hvr, hdv⟩ := hp v hv' + exact ⟨hvr, hdv.trans hdx⟩ + · obtain ⟨hvr, hdv⟩ := hq v hv + exact ⟨hvr, hdv.trans hdy⟩ + exact ⟨(p.word.reverse.append q.word).induce _ hmem⟩ + +/-- Geometry, Lemma `geo:sublevel`, including the actual nonemptiness +hypothesis and connectivity in the induced graph, not merely in the ambient +component. -/ +lemma sublevel_connected (hJ : IsClosed J) (o : M.Point J root) + (H : ℝ) (hH : H ∈ J) (t : ℝ) (hne : (o.sublevel H hH t).Nonempty) : + ((M.activeGraph J).induce (o.sublevel H hH t)).Connected := by + have : Nonempty (o.sublevel H hH t) := hne.to_subtype + exact ⟨o.sublevel_preconnected hJ H hH t⟩ + +/-- The short connector in the portal argument. We use the connected +fixed-height sublevel at `t - 12a`; this changes the source's intermediate +13a estimate to 14a, still strictly below the required 100a separation. -/ +lemma short_connector (hJ : IsClosed J) (o x : M.Point J root) + {H a t : ℝ} (hH : H ∈ J) (ha : 0 < a) (ht : 30 * a ≤ t) + (hhalf : ∀ T ∈ J, |H - T| ≤ a / 2) + (hx : t ≤ dist o (x.withHeight H hH)) (hnear : dist o x < t + a) : + ∃ v ∈ o.sublevel H hH (t - 12 * a), ∃ T ∈ J, + ∃ p : M.Path J x.column v, p.length x.height T ≤ 14 * a := by + let S := o.sublevel H hH (t - 12 * a) + have hxo : x.column ∉ S := by + intro h + have hd := (o.mem_sublevel_iff x H hH (t - 12 * a)).mp h + linarith + have hoo : o.column ∈ S := by + apply (o.mem_sublevel_iff o H hH (t - 12 * a)).mpr + rw [o.dist_withHeight, abs_sub_comm] + linarith [hhalf o.height o.inBand] + obtain ⟨p, _, hp⟩ := x.exists_shortest hJ o + obtain ⟨u, v, T, hT, hs, hu, hv, q, r, hqr⟩ := + p.crosses_set S hxo hoo x.height o.height + let z : M.Point J root := ⟨u, T, hT, x.reachable.trans q.word.reachable⟩ + have hout : t - 12 * a < dist o (z.withHeight H hH) := by + apply lt_of_not_ge + intro h + exact hu ((o.mem_sublevel_iff z H hH _).mpr h) + have hz : dist o z ≤ r.length T o.height := by + have hh := z.distance_le o (.cons T hT hs r) + rw [dist_comm o z] + change z.distance o ≤ r.length T o.height + simpa only [Path.length, z, sub_self, abs_zero, zero_add] using hh + have hvshift : dist z (z.withHeight H hH) ≤ a / 2 := by + rw [z.dist_withHeight] + change |T - H| ≤ a / 2 + rw [abs_sub_comm] + exact hhalf T hT + have htri := dist_triangle o z (z.withHeight H hH) + have hlen : q.length x.height T ≤ 14 * a := by + rw [hp, dist_comm x o] at hqr + linarith + refine ⟨v, hv, T, hT, q.snoc T hT hs, ?_⟩ + simpa only [Path.length_snoc, sub_self, abs_zero, add_zero] using hlen + +/-- Quantitative exclusion behind the two-portals lemma: three entrance-range +midpoints in a connected high set cannot be mutually more than 100 widths +apart. No minor-exclusion or short-connector hypothesis is assumed. -/ +lemma no_three_far_entrances (hJ : IsClosed J) (o : M.Point J root) + {H a t : ℝ} (hH : H ∈ J) (ha : 0 < a) + (hhalf : ∀ T ∈ J, |H - T| ≤ a / 2) + {C : Set (Fin n)} (hC : ((M.activeGraph J).induce C).Preconnected) + (hhigh : ∀ z : M.Point J root, z.column ∈ C → t ≤ dist o (z.withHeight H hH)) + (x : Fin 3 → M.Point J root) (hxc : ∀ i, (x i).column ∈ C) + (hnear : ∀ i, dist o (x i) < t + a) + (hfar : Pairwise (fun i j => 100 * a < dist (x i) (x j))) : False := by + by_cases ht : 30 * a ≤ t + · let L := o.sublevel H hH (t - 12 * a) + have hCL : Disjoint C L := by + apply Set.disjoint_left.mpr + rintro v hv ⟨hr, hd⟩ + let z : M.Point J root := ⟨v, H, hH, hr⟩ + have hz := hhigh z hv + change t ≤ dist o z at hz + linarith + have hno : ∀ u ∈ C, ∀ v ∈ L, ¬ (M.activeGraph J).Adj u v := by + rintro u hu v ⟨hr, hd⟩ huv + let y : M.Point J root := ⟨v, H, hH, hr⟩ + let z : M.Point J root := ⟨u, H, hH, + hr.trans (SimpleGraph.Adj.reachable huv.symm)⟩ + have hz := hhigh z hu + change t ≤ dist o z at hz + have hzy := z.dist_midpoints_le y rfl rfl hhalf huv + have hh := dist_triangle o y z + rw [dist_comm y z] at hh + change dist o y ≤ t - 12 * a at hd + linarith + have hcon := fun i => o.short_connector hJ (x i) hH ha ht hhalf + (hhigh (x i) (hxc i)) (hnear i) + choose v hv T hT p hp using hcon + have hwidth : ∀ r ∈ J, ∀ s ∈ J, |r - s| ≤ a := by + intro r hr s hs + have hb := abs_sub_le r H s + rw [abs_sub_comm r H] at hb + linarith [hhalf r hr, hhalf s hs] + have hdis : Pairwise (fun i j => Disjoint + {w | w ∈ (p i).word.support} {w | w ∈ (p j).word.support}) := by + intro i j hij + apply Set.disjoint_left.mpr + intro w hwi hwj + have hd := (x i).dist_le_of_shared_column (x j) (p i) (p j) + (hT i) (hT j) hwidth hwi hwj + have hf := hfar hij + linarith [hp i, hp j] + exact ColumnOrder.no_three_connectors (M.active_noncrossing J) hC + (o.sublevel_preconnected hJ H hH (t - 12 * a)) hCL hno + (fun i => (x i).column) v hxc hv (fun i => (p i).word) hdis + · have hf := hfar (show (0 : Fin 3) ≠ 1 by decide) + have hd := dist_triangle (x 0) o (x 1) + rw [dist_comm (x 0) o] at hd + linarith [hnear 0, hnear 1] + +/-- Two entrances cover all entrance midpoints. The two chosen values may +coincide, representing the one-portal case; both are actual entrances. -/ +lemma two_portal_midpoints (hJ : IsClosed J) (o : M.Point J root) + {H a t : ℝ} (hH : H ∈ J) (ha : 0 < a) + (hhalf : ∀ T ∈ J, |H - T| ≤ a / 2) + {C : Set (Fin n)} (hC : ((M.activeGraph J).induce C).Preconnected) + (hhigh : ∀ z : M.Point J root, z.column ∈ C → t ≤ dist o (z.withHeight H hH)) + {E : Set (M.Point J root)} (hne : E.Nonempty) + (heC : ∀ x ∈ E, x.column ∈ C) (hnear : ∀ x ∈ E, dist o x < t + a) : + ∃ p ∈ E, ∃ q ∈ E, ∀ x ∈ E, dist x p ≤ 100 * a ∨ dist x q ≤ 100 * a := by + classical + obtain ⟨p, hp⟩ := hne + by_cases hex : ∃ q ∈ E, 100 * a < dist p q + · obtain ⟨q, hq, hpq⟩ := hex + refine ⟨p, hp, q, hq, ?_⟩ + intro z hz + by_contra h + push Not at h + apply o.no_three_far_entrances hJ hH ha hhalf hC hhigh ![p, q, z] + · intro i + fin_cases i + · exact heC p hp + · exact heC q hq + · exact heC z hz + · intro i + fin_cases i + · exact hnear p hp + · exact hnear q hq + · exact hnear z hz + · intro i j hij + fin_cases i <;> fin_cases j <;> simp_all [dist_comm] + · refine ⟨p, hp, p, hp, ?_⟩ + intro x hx + left + rw [dist_comm] + exact le_of_not_gt (fun h => hex ⟨x, hx, h⟩) + +/-- Geometry `geo:portals`, the full-column covering conclusion with the +stated 200a constant. The entrance-range hypothesis is derived from adjacency +by `dist_midpoints_le`; the two portal centers are selected from `E` itself. -/ +lemma two_portals (hJ : IsClosed J) (o : M.Point J root) + {H a t : ℝ} (hH : H ∈ J) (ha : 0 < a) + (hhalf : ∀ T ∈ J, |H - T| ≤ a / 2) + {C : Set (Fin n)} (hC : ((M.activeGraph J).induce C).Preconnected) + (hhigh : ∀ z : M.Point J root, z.column ∈ C → t ≤ dist o (z.withHeight H hH)) + {E : Set (M.Point J root)} (hne : E.Nonempty) + (heC : ∀ x ∈ E, x.column ∈ C) (hnear : ∀ x ∈ E, dist o x < t + a) : + ∃ p ∈ E, ∃ q ∈ E, ∀ x : M.Point J root, x.withHeight H hH ∈ E → + dist x p ≤ 200 * a ∨ dist x q ≤ 200 * a := by + obtain ⟨p, hp, q, hq, hcover⟩ := o.two_portal_midpoints hJ hH ha hhalf hC hhigh + hne heC hnear + refine ⟨p, hp, q, hq, ?_⟩ + intro x hx + have hv : dist x (x.withHeight H hH) ≤ a / 2 := by + rw [x.dist_withHeight, abs_sub_comm] + exact hhalf x.height x.inBand + rcases hcover _ hx with h | h + · left + linarith [dist_triangle x (x.withHeight H hH) p] + · right + linarith [dist_triangle x (x.withHeight H hH) q] + +/-- Radial superlevels contain exactly the reachable columns whose midpoints +have radial value at least the threshold. -/ +def superlevel (o : M.Point J root) (H : ℝ) (hH : H ∈ J) (t : ℝ) : Set (Fin n) := + {i | ∃ hi : (M.activeGraph J).Reachable root i, + t ≤ dist o (⟨i, H, hH, hi⟩ : M.Point J root)} + +lemma mem_superlevel_iff (o x : M.Point J root) (H : ℝ) (hH : H ∈ J) (t : ℝ) : + x.column ∈ o.superlevel H hH t ↔ t ≤ dist o (x.withHeight H hH) := by + constructor + · rintro ⟨_, hd⟩ + exact hd + · intro hd + exact ⟨x.reachable, hd⟩ + +/-- The actual entrance midpoints of a radial high component. The adjacent +low column, rather than a separate entrance-range hypothesis, is part of the +definition. -/ +def entrances (o : M.Point J root) (H : ℝ) (hH : H ∈ J) (t : ℝ) + (C : ((M.activeGraph J).induce (o.superlevel H hH t)).ConnectedComponent) : + Set (M.Point J root) := + {x | x.height = H ∧ x.column ∈ ColumnOrder.componentColumns C ∧ + ∃ y : M.Point J root, y.height = H ∧ + (M.activeGraph J).Adj x.column y.column ∧ dist o y < t} + +lemma entrance_radial (o : M.Point J root) {H a t : ℝ} (hH : H ∈ J) + (hhalf : ∀ T ∈ J, |H - T| ≤ a / 2) + (C : ((M.activeGraph J).induce (o.superlevel H hH t)).ConnectedComponent) + {x : M.Point J root} (hx : x ∈ o.entrances H hH t C) : + t ≤ dist o x ∧ dist o x < t + a := by + obtain ⟨hxH, hxC, y, hyH, hxy, hy⟩ := hx + have hhigh := (o.mem_superlevel_iff x H hH t).mp + (ColumnOrder.componentColumns_subset C hxC) + have heq : x.withHeight H hH = x := by + simpa only [← hxH] using x.withHeight_self + rw [heq] at hhigh + have hd := x.dist_midpoints_le y hxH hyH hhalf hxy + have htri := dist_triangle o y x + rw [dist_comm y x] at htri + exact ⟨hhigh, by linarith⟩ + +/-- Exit a high component along an attained shortest path. The final high +column is an actual entrance. The estimate retains the distance to the radial +threshold, and is the geometric input for both cell diameters and portal levels. -/ +lemma exit_superlevel (hJ : IsClosed J) (o x : M.Point J root) + {H a t : ℝ} (hH : H ∈ J) (ht : a / 2 < t) + (hhalf : ∀ T ∈ J, |H - T| ≤ a / 2) + (C : ((M.activeGraph J).induce (o.superlevel H hH t)).ConnectedComponent) + (hx : x.column ∈ ColumnOrder.componentColumns C) : + ∃ z : M.Point J root, z.withHeight H hH ∈ o.entrances H hH t C ∧ + dist x z ≤ dist o x - t + a / 2 := by + let S := ColumnOrder.componentColumns C + have hoo : o.column ∉ S := by + intro ho + have hh := (o.mem_superlevel_iff o H hH t).mp + (ColumnOrder.componentColumns_subset C ho) + rw [o.dist_withHeight, abs_sub_comm] at hh + linarith [hhalf o.height o.inBand] + obtain ⟨p, _, hp⟩ := x.exists_shortest hJ o + obtain ⟨u, v, T, hT, hs, hu, hv, q, r, hqr⟩ := + p.crosses_set Sᶜ (by simpa only [Set.mem_compl_iff, not_not] using hx) + hoo x.height o.height + have huC : u ∈ S := by simpa only [Set.mem_compl_iff, not_not] using hu + have huv : (M.activeGraph J).Adj u v := ⟨T, hT, hs⟩ + let z : M.Point J root := ⟨u, T, hT, x.reachable.trans q.word.reachable⟩ + let y : M.Point J root := ⟨v, H, hH, z.reachable.trans huv.reachable⟩ + have hy : dist o y < t := by + apply lt_of_not_ge + intro h + exact hv (ColumnOrder.componentColumns_adj C huC huv ⟨y.reachable, h⟩) + have hentrance : z.withHeight H hH ∈ o.entrances H hH t C := + ⟨rfl, huC, y, rfl, huv, hy⟩ + refine ⟨z, hentrance, ?_⟩ + have hhigh := (o.mem_superlevel_iff z H hH t).mp + (ColumnOrder.componentColumns_subset C huC) + have hvshift : dist z (z.withHeight H hH) ≤ a / 2 := by + rw [z.dist_withHeight, abs_sub_comm] + exact hhalf T hT + have hz : dist o z ≤ r.length T o.height := by + have hh := z.distance_le o (.cons T hT hs r) + rw [dist_comm o z] + change z.distance o ≤ r.length T o.height + simpa only [Path.length, z, sub_self, abs_zero, zero_add] using hh + have htri := dist_triangle o z (z.withHeight H hH) + have hdx := x.distance_le z q + change dist x z ≤ q.length x.height T at hdx + rw [hp, dist_comm x o] at hqr + linarith + +/-- Nonempty radial high components have entrances above the initial +half-width. This discharges the existence clause of `geo:portals`. -/ +lemma entrances_nonempty (hJ : IsClosed J) (o : M.Point J root) + {H a t : ℝ} (hH : H ∈ J) (ht : a / 2 < t) + (hhalf : ∀ T ∈ J, |H - T| ≤ a / 2) + (C : ((M.activeGraph J).induce (o.superlevel H hH t)).ConnectedComponent) : + (o.entrances H hH t C).Nonempty := by + obtain ⟨i, hi⟩ := C.nonempty_supp + obtain ⟨hr, _⟩ := i.property + let x : M.Point J root := ⟨i.val, H, hH, hr⟩ + obtain ⟨z, hz, _⟩ := o.exit_superlevel hJ x hH ht hhalf C ⟨i, hi, rfl⟩ + exact ⟨z.withHeight H hH, hz⟩ + +/-- Geometry `geo:portals` with the actual radial component and actual +entrances. In particular no covering or radial-range conclusion is assumed. -/ +lemma component_two_portals (hJ : IsClosed J) (o : M.Point J root) + {H a t : ℝ} (hH : H ∈ J) (ha : 0 < a) + (hhalf : ∀ T ∈ J, |H - T| ≤ a / 2) + (C : ((M.activeGraph J).induce (o.superlevel H hH t)).ConnectedComponent) + (hne : (o.entrances H hH t C).Nonempty) : + ∃ p ∈ o.entrances H hH t C, ∃ q ∈ o.entrances H hH t C, + (t ≤ dist o p ∧ dist o p < t + a) ∧ + (t ≤ dist o q ∧ dist o q < t + a) ∧ + ∀ x : M.Point J root, x.withHeight H hH ∈ o.entrances H hH t C → + dist x p ≤ 200 * a ∨ dist x q ≤ 200 * a := by + obtain ⟨p, hp, q, hq, hcover⟩ := o.two_portals hJ hH ha hhalf + (ColumnOrder.componentColumns_connected C).preconnected + (fun z hz => (o.mem_superlevel_iff z H hH t).mp + (ColumnOrder.componentColumns_subset C hz)) hne + (fun _ hx => hx.2.1) (fun _ hx => (o.entrance_radial hH hhalf C hx).2) + exact ⟨p, hp, q, hq, o.entrance_radial hH hhalf C hp, + o.entrance_radial hH hhalf C hq, hcover⟩ + +/-- The geodesic-to-root estimate behind radial cells: every point of a +high component whose radial distance is bounded is close to a chosen portal. -/ +lemma component_portal_cover (hJ : IsClosed J) (o : M.Point J root) + {H a t : ℝ} (hH : H ∈ J) (ha : 0 < a) (ht : a / 2 < t) + (hhalf : ∀ T ∈ J, |H - T| ≤ a / 2) + (C : ((M.activeGraph J).induce (o.superlevel H hH t)).ConnectedComponent) : + ∃ p ∈ o.entrances H hH t C, ∃ q ∈ o.entrances H hH t C, + ∀ x : M.Point J root, x.column ∈ ColumnOrder.componentColumns C → + dist x p ≤ dist o x - t + 201 * a ∨ + dist x q ≤ dist o x - t + 201 * a := by + obtain ⟨p, hp, q, hq, _, _, hc⟩ := o.component_two_portals hJ hH ha hhalf C + (o.entrances_nonempty hJ hH ht hhalf C) + refine ⟨p, hp, q, hq, ?_⟩ + intro x hx + obtain ⟨z, hz, hd⟩ := o.exit_superlevel hJ x hH ht hhalf C hx + rcases hc z hz with hz | hz + · left + linarith [dist_triangle x z p] + · right + linarith [dist_triangle x z q] + +/-- The half-open radial layer of the source. Its connected components, +not components of the ambient graph, are the cell column sets. -/ +def layer (o : M.Point J root) (H : ℝ) (hH : H ∈ J) (q D : ℝ) : Set (Fin n) := + {i | ∃ hi : (M.activeGraph J).Reachable root i, + q ≤ dist o (⟨i, H, hH, hi⟩ : M.Point J root) ∧ + dist o (⟨i, H, hH, hi⟩ : M.Point J root) < q + D} + +lemma layer_subset_superlevel (o : M.Point J root) (H : ℝ) (hH : H ∈ J) (q D : ℝ) : + o.layer H hH q D ⊆ o.superlevel H hH q := by + rintro i ⟨hr, hlow, _⟩ + exact ⟨hr, hlow⟩ + +lemma mem_layer_iff (o x : M.Point J root) (H : ℝ) (hH : H ∈ J) (q D : ℝ) : + x.column ∈ o.layer H hH q D ↔ + q ≤ dist o (x.withHeight H hH) ∧ dist o (x.withHeight H hH) < q + D := by + constructor + · rintro ⟨_, hd⟩ + exact hd + · intro hd + exact ⟨x.reachable, hd⟩ + +/-- The weak-diameter assertion of `geo:cells` for the literal full-column +cell. Paths measuring distance may leave the cell, exactly as in the source. -/ +lemma radial_cell_diameter (hJ : IsClosed J) (o : M.Point J root) + {H a q D : ℝ} (hH : H ∈ J) (ha : 0 < a) (hthin : a ≤ D / 1000) + (hhalf : ∀ T ∈ J, |H - T| ≤ a / 2) + (C : ((M.activeGraph J).induce (o.layer H hH q D)).ConnectedComponent) + (x y : M.Point J root) (hx : x.column ∈ ColumnOrder.componentColumns C) + (hy : y.column ∈ ColumnOrder.componentColumns C) : dist x y ≤ 10 * D := by + classical + have hD : 0 < D := by linarith + have hup : ∀ z : M.Point J root, z.column ∈ ColumnOrder.componentColumns C → + dist o z < q + D + a / 2 := by + intro z hz + have hr := (o.mem_layer_iff z H hH q D).mp + (ColumnOrder.componentColumns_subset C hz) + have hv := hhalf z.height z.inBand + have hd := dist_triangle o (z.withHeight H hH) z + rw [dist_comm (z.withHeight H hH) z, z.dist_withHeight, abs_sub_comm] at hd + linarith [hr.2] + by_cases hq : q ≤ 30 * a + · have hd := dist_triangle x o y + rw [dist_comm x o] at hd + linarith [hup x hx, hup y hy] + · let Cplus := ColumnOrder.componentAbove (o.layer_subset_superlevel H hH q D) C + have hsub := ColumnOrder.componentColumns_above (o.layer_subset_superlevel H hH q D) C + have ht : a / 2 < q := by linarith + obtain ⟨p, _, r, _, hc⟩ := o.component_portal_cover hJ hH ha ht hhalf Cplus + let f : ColumnOrder.componentColumns C → M.Point J root := fun i => + ⟨i.val, H, hH, (ColumnOrder.componentColumns_subset C i.property).choose⟩ + have hedge : ∀ i j, ((M.activeGraph J).induce (ColumnOrder.componentColumns C)).Adj i j → + dist (f i) (f j) ≤ a := by + intro i j hij + exact (f i).dist_midpoints_le (f j) rfl rfl hhalf hij + have hcover : ∀ i, dist (f i) p ≤ D + 210 * a ∨ dist (f i) r ≤ D + 210 * a := by + intro i + have hfi : (f i).column ∈ ColumnOrder.componentColumns C := i.property + have hu := hup (f i) hfi + rcases hc (f i) (hsub hfi) with h | h + · exact Or.inl (by linarith) + · exact Or.inr (by linarith) + have hd := ColumnOrder.connected_two_balls + (ColumnOrder.componentColumns_connected C).preconnected f p r + (show 0 ≤ D + 210 * a by positivity) ha.le hedge hcover ⟨x.column, hx⟩ ⟨y.column, hy⟩ + have hvx : dist x (f ⟨x.column, hx⟩) ≤ a / 2 := by + change dist x (x.withHeight H hH) ≤ a / 2 + rw [x.dist_withHeight, abs_sub_comm] + exact hhalf x.height x.inBand + have hvy : dist (f ⟨y.column, hy⟩) y ≤ a / 2 := by + change dist (y.withHeight H hH) y ≤ a / 2 + rw [dist_comm, y.dist_withHeight, abs_sub_comm] + exact hhalf y.height y.inBand + have ht₁ := dist_triangle x (f ⟨x.column, hx⟩) y + have ht₂ := dist_triangle (f ⟨x.column, hx⟩) (f ⟨y.column, hy⟩) y + linarith + +/-- Changing to the fixed midheight costs at most one band width in any +radial comparison. This also controls all zero-distance representatives. -/ +lemma radial_difference_le (o x y : M.Point J root) {H a : ℝ} (hH : H ∈ J) + (hhalf : ∀ T ∈ J, |H - T| ≤ a / 2) : + |dist o (x.withHeight H hH) - dist o (y.withHeight H hH)| ≤ dist x y + a := by + have hx : dist x (x.withHeight H hH) ≤ a / 2 := by + rw [x.dist_withHeight, abs_sub_comm] + exact hhalf x.height x.inBand + have hy : dist y (y.withHeight H hH) ≤ a / 2 := by + rw [y.dist_withHeight, abs_sub_comm] + exact hhalf y.height y.inBand + have h₁ := abs_dist_sub_le (x.withHeight H hH) (y.withHeight H hH) o + rw [dist_comm (x.withHeight H hH) o, dist_comm (y.withHeight H hH) o] at h₁ + have h₂ := dist_triangle (x.withHeight H hH) x (y.withHeight H hH) + have h₃ := dist_triangle x y (y.withHeight H hH) + rw [dist_comm (x.withHeight H hH) x] at h₂ + linarith + +/-- A column visited by a short switching path has a nearby radial midpoint. +The conclusion uses the actual path prefix, rather than a shortest path +constrained to a radial cell. -/ +lemma path_radial_bound (o x y : M.Point J root) {H a : ℝ} (hH : H ∈ J) + (hhalf : ∀ T ∈ J, |H - T| ≤ a / 2) (p : M.Path J x.column y.column) + {i : Fin n} (hi : i ∈ p.word.support) : + ∃ hr : (M.activeGraph J).Reachable root i, + |dist o (⟨i, H, hH, hr⟩ : M.Point J root) - dist o (x.withHeight H hH)| ≤ + p.length x.height y.height + a := by + obtain ⟨T, hT, q, r, hqr⟩ := p.split_at_column x.inBand y.inBand hi + let z : M.Point J root := ⟨i, T, hT, x.reachable.trans q.word.reachable⟩ + have hd : dist x z ≤ p.length x.height y.height := by + have hq := x.distance_le z q + have hr := r.length_nonneg T y.height + change dist x z ≤ q.length x.height T at hq + linarith + refine ⟨z.reachable, ?_⟩ + have hb := o.radial_difference_le z x hH hhalf + rw [dist_comm z x] at hb + change |dist o (z.withHeight H hH) - dist o (x.withHeight H hH)| ≤ _ + linarith + +/-- Deterministic padding in one actual radial layer. All representatives of +all endpoints are covered because the lemma is stated on the pseudometric +space of representatives. -/ +lemma radial_cell_padding (o x y : M.Point J root) {H a q D ρ : ℝ} + (hH : H ∈ J) (ha : 0 ≤ a) (hhalf : ∀ T ∈ J, |H - T| ≤ a / 2) + (C : ((M.activeGraph J).induce (o.layer H hH q D)).ConnectedComponent) + (hx : x.column ∈ ColumnOrder.componentColumns C) + (hlow : q + ρ + 2 * a < dist o (x.withHeight H hH)) + (hupp : dist o (x.withHeight H hH) < q + D - ρ - 2 * a) + (p : M.Path J x.column y.column) (hp : p.length x.height y.height ≤ ρ) : + y.column ∈ ColumnOrder.componentColumns C := by + apply ColumnOrder.componentColumns_of_walk C p.word hx + intro i hi + obtain ⟨hr, hb⟩ := o.path_radial_bound x y hH hhalf p hi + obtain ⟨h₁, h₂⟩ := abs_le.mp hb + refine ⟨hr, ?_, ?_⟩ <;> linarith + +lemma radial_ball_padding (hJ : IsClosed J) (o x y : M.Point J root) + {H a q D ρ : ℝ} (hH : H ∈ J) (ha : 0 ≤ a) + (hhalf : ∀ T ∈ J, |H - T| ≤ a / 2) + (C : ((M.activeGraph J).induce (o.layer H hH q D)).ConnectedComponent) + (hx : x.column ∈ ColumnOrder.componentColumns C) + (hlow : q + ρ + 2 * a < dist o (x.withHeight H hH)) + (hupp : dist o (x.withHeight H hH) < q + D - ρ - 2 * a) + (hxy : dist x y ≤ ρ) : y.column ∈ ColumnOrder.componentColumns C := by + obtain ⟨p, _, hp⟩ := x.exists_shortest hJ y + exact o.radial_cell_padding x y hH ha hhalf C hx hlow hupp p (hp ▸ hxy) + +/-- The literal full-column frontier of a column cell in the active graph. -/ +def frontier (C : Set (Fin n)) : Set (Fin n) := + {i | i ∈ C ∧ ∃ j, (M.activeGraph J).Adj i j ∧ j ∉ C} + +/-- A frontier midpoint is within one width of a layer threshold. The +neighbor cannot be in the same layer, since the cell is a component there. -/ +lemma frontier_radial (o z : M.Point J root) {H a q D : ℝ} (hH : H ∈ J) + (hhalf : ∀ T ∈ J, |H - T| ≤ a / 2) + (C : ((M.activeGraph J).induce (o.layer H hH q D)).ConnectedComponent) + (hz : z.column ∈ frontier (M := M) (J := J) (ColumnOrder.componentColumns C)) : + dist o (z.withHeight H hH) < q + a ∨ + q + D - a ≤ dist o (z.withHeight H hH) := by + obtain ⟨hzc, j, hzj, hj⟩ := hz + let w : M.Point J root := ⟨j, H, hH, z.reachable.trans hzj.reachable⟩ + have hnot : j ∉ o.layer H hH q D := by + intro h + exact hj (ColumnOrder.componentColumns_adj C hzc hzj h) + have hd : dist (z.withHeight H hH) w ≤ a := + (z.withHeight H hH).dist_midpoints_le w rfl rfl hhalf hzj + have hw : ¬ (q ≤ dist o w ∧ dist o w < q + D) := by + intro h + exact hnot ⟨w.reachable, h⟩ + have ht₁ := dist_triangle o (z.withHeight H hH) w + have ht₂ := dist_triangle o w (z.withHeight H hH) + rw [dist_comm w (z.withHeight H hH)] at ht₂ + by_cases hq : dist o w < q + · exact Or.inl (by linarith) + · exact Or.inr (by have h := not_lt.mp hq; have h' : q + D ≤ dist o w := + le_of_not_gt (fun hu => hw ⟨h, hu⟩); linarith) + +/-- Exact strict avoidance of the frontier, the second assertion of +`geo:padding`. The empty-frontier case is automatic, not assigned distance 0. -/ +lemma radial_frontier_distance (o x z : M.Point J root) {H a q D ρ : ℝ} + (hH : H ∈ J) (hhalf : ∀ T ∈ J, |H - T| ≤ a / 2) + (C : ((M.activeGraph J).induce (o.layer H hH q D)).ConnectedComponent) + (hlow : q + ρ + 2 * a < dist o (x.withHeight H hH)) + (hupp : dist o (x.withHeight H hH) < q + D - ρ - 2 * a) + (hz : z.column ∈ frontier (M := M) (J := J) (ColumnOrder.componentColumns C)) : + ρ < dist x z := by + obtain h | h := o.frontier_radial z hH hhalf C hz + · have hb := (abs_le.mp (o.radial_difference_le x z hH hhalf)).2 + linarith + · have hb := (abs_le.mp (o.radial_difference_le x z hH hhalf)).1 + linarith + + +/-- Every fixed column is an isometric copy of its allowed height interval. -/ +def columnMap (i : Fin n) (hi : (M.activeGraph J).Reachable root i) : J → M.Point J root := + fun H => ⟨i, H.val, H.property, hi⟩ + +lemma columnMap_isometry (i : Fin n) (hi : (M.activeGraph J).Reachable root i) : + Isometry (columnMap i hi) := by + apply Isometry.of_dist_eq + intro H T + exact (columnMap i hi H).dist_same_column (columnMap i hi T) rfl + +/-- Compactness of any full-column subset in a compact band, including the +literal radial cells and their frontiers. This argument works before taking +the separation quotient and does not require a false Hausdorff assumption. -/ +lemma fullColumns_compact (hJ : IsCompact J) (C : Set (Fin n)) : + IsCompact {x : M.Point J root | x.column ∈ C} := by + classical + let : CompactSpace J := isCompact_iff_compactSpace.mp hJ + let I := {i : Fin n // i ∈ C ∧ (M.activeGraph J).Reachable root i} + have heq : {x : M.Point J root | x.column ∈ C} = + ⋃ i : I, Set.range (columnMap i.val i.property.2) := by + ext x + constructor + · intro hx + refine Set.mem_iUnion.mpr ⟨⟨x.column, hx, x.reachable⟩, ?_⟩ + exact ⟨⟨x.height, x.inBand⟩, rfl⟩ + · intro hx + obtain ⟨i, H, rfl⟩ := Set.mem_iUnion.mp hx + exact i.property.1 + rw [heq] + exact isCompact_iUnion (fun i => isCompact_range (columnMap_isometry i.val i.property.2).continuous) + +/-- A continuous scalar frontier constraint attains its infimum whenever +there is a frontier point. Used by the main raise-or-descend test. -/ +lemma frontier_minimizer (hJ : IsCompact J) (C : Set (Fin n)) + (s : M.Point J root → ℝ) (hs : Continuous s) (x : M.Point J root) (c : ℝ) + (hne : ∃ z : M.Point J root, z.column ∈ frontier (M := M) (J := J) C) : + ∃ z : M.Point J root, z.column ∈ frontier (M := M) (J := J) C ∧ + ∀ w : M.Point J root, w.column ∈ frontier (M := M) (J := J) C → + s z + c * dist x z ≤ s w + c * dist x w := by + have hc := fullColumns_compact (M := M) (root := root) hJ + (frontier (M := M) (J := J) C) + have hf : Continuous (fun z : M.Point J root => s z + c * dist x z) := + hs.add (continuous_const.mul (continuous_const.dist continuous_id)) + obtain ⟨z, hz, hmin⟩ := hc.exists_isMinOn hne hf.continuousOn + exact ⟨z, hz, hmin⟩ + + +/-- The metric interpolation property of an actual attained shortest path. +This is the geodesic fact used by the small-ball and descending-path arguments. -/ +lemma exists_between (hJ : IsClosed J) (hconv : Set.OrdConnected J) + (x y : M.Point J root) {ℓ : ℝ} (hℓ : 0 ≤ ℓ) (hlen : ℓ ≤ dist x y) : + ∃ z : M.Point J root, dist x z = ℓ ∧ dist z y = dist x y - ℓ := by + obtain ⟨p, _, hp⟩ := x.exists_shortest hJ y + obtain ⟨k, T, hT, q, r, hq, hr⟩ := p.split_at_length hconv x.inBand y.inBand hℓ + (hp ▸ hlen) + let z : M.Point J root := ⟨k, T, hT, x.reachable.trans q.word.reachable⟩ + have h₁ : dist x z ≤ ℓ := by + have h := x.distance_le z q + exact h.trans_eq hq + have h₂ : dist z y ≤ dist x y - ℓ := by + have h := z.distance_le y r + exact h.trans_eq (hr.trans (by rw [hp])) + have ht := dist_triangle x z y + exact ⟨z, by linarith, by linarith⟩ + +/-- Every point on a shortest descending path retains the endpoint's deficit +bound. This is `main:ray-prefix`, expressed by exact arclength distances. -/ +lemma descent_along_shortest {s : M.Point J root → ℝ} {ε : ℝ} + (hs : ∀ u v, s u - s v ≤ dist u v) (x z v : M.Point J root) + (hshort : dist x v + dist v z = dist x z) + (hdrop : s z ≤ s x - dist x z + ε) : + s v ≤ s x - dist x v + ε := by + linarith [hs v z] + + +/-- All representatives of the intrinsic closed ball, projected to columns. +Using representatives includes columns identified by zero-length paths. -/ +def ballColumns (x : M.Point J root) (ρ : ℝ) : Set (Fin n) := + {i | ∃ y : M.Point J root, y.column = i ∧ dist x y ≤ ρ} + +lemma mem_ballColumns (x y : M.Point J root) {ρ : ℝ} (hy : dist x y ≤ ρ) : + y.column ∈ x.ballColumns ρ := ⟨y, rfl, hy⟩ + +lemma path_ballColumns (x y : M.Point J root) (p : M.Path J x.column y.column) + {ρ : ℝ} (hp : p.length x.height y.height ≤ ρ) : + ∀ v ∈ p.word.support, v ∈ x.ballColumns ρ := by + intro v hv + obtain ⟨T, hT, q, r, hqr⟩ := p.split_at_column x.inBand y.inBand hv + let z : M.Point J root := ⟨v, T, hT, x.reachable.trans q.word.reachable⟩ + refine ⟨z, rfl, ?_⟩ + have h := x.distance_le z q + have hr := r.length_nonneg T y.height + change dist x z ≤ q.length x.height T at h + linarith + +/-- The projection of an actual closed ball is induced-connected. This is +not an assumed graph property in the local interpolation argument. -/ +lemma ballColumns_preconnected (hJ : IsClosed J) (x : M.Point J root) (ρ : ℝ) : + ((M.activeGraph J).induce (x.ballColumns ρ)).Preconnected := by + intro i j + obtain ⟨y, hy, hxy⟩ := i.property + obtain ⟨z, hz, hxz⟩ := j.property + obtain ⟨p, _, hp⟩ := x.exists_shortest hJ y + obtain ⟨q, _, hq⟩ := x.exists_shortest hJ z + have hm : ∀ v ∈ (p.word.reverse.append q.word).support, + v ∈ x.ballColumns ρ := by + intro v hv + rcases (p.word.reverse.mem_support_append_iff q.word).mp hv with h | h + · exact x.path_ballColumns y p (hp ▸ hxy) v (by simpa using h) + · exact x.path_ballColumns z q (hq ▸ hxz) v h + have hreach := (p.word.reverse.append q.word).induce _ hm + exact ⟨hreach.copy (Subtype.ext hy) (Subtype.ext hz)⟩ + +lemma ballColumns_nonempty (x : M.Point J root) {ρ : ℝ} (hρ : 0 ≤ ρ) : + (x.ballColumns ρ).Nonempty := + ⟨x.column, x.mem_ballColumns x (by simpa using hρ)⟩ + +/-- The sharper `2ρ+a` version of the source's `2ρ+2a` radial spread. -/ +lemma ball_radial_spread (o x y z : M.Point J root) {H a ρ : ℝ} (hH : H ∈ J) + (hhalf : ∀ T ∈ J, |H - T| ≤ a / 2) + (hy : dist x y ≤ ρ) (hz : dist x z ≤ ρ) : + |dist o (y.withHeight H hH) - dist o (z.withHeight H hH)| ≤ 2 * ρ + a := by + have h := o.radial_difference_le y z hH hhalf + have ht := dist_triangle y x z + rw [dist_comm y x] at ht + linarith + +/-- A shortest path to any point outside a high component reaches an actual +entrance within its total length. Unlike `exit_superlevel`, no radial decrease +to the root is needed. -/ +lemma exit_superlevel_to (hJ : IsClosed J) (o x y : M.Point J root) + {H t : ℝ} (hH : H ∈ J) + (C : ((M.activeGraph J).induce (o.superlevel H hH t)).ConnectedComponent) + (hx : x.column ∈ ColumnOrder.componentColumns C) + (hy : y.column ∉ ColumnOrder.componentColumns C) : + ∃ z : M.Point J root, z.withHeight H hH ∈ o.entrances H hH t C ∧ + dist x z ≤ dist x y := by + let S := ColumnOrder.componentColumns C + obtain ⟨p, _, hp⟩ := x.exists_shortest hJ y + obtain ⟨u, v, T, hT, hs, hu, hv, q, r, hqr⟩ := + p.crosses_set Sᶜ (by simpa only [Set.mem_compl_iff, not_not] using hx) + hy x.height y.height + have huC : u ∈ S := by simpa only [Set.mem_compl_iff, not_not] using hu + have huv : (M.activeGraph J).Adj u v := ⟨T, hT, hs⟩ + let z : M.Point J root := ⟨u, T, hT, x.reachable.trans q.word.reachable⟩ + let w : M.Point J root := ⟨v, H, hH, z.reachable.trans huv.reachable⟩ + have hw : dist o w < t := by + apply lt_of_not_ge + intro h + exact hv (ColumnOrder.componentColumns_adj C huC huv ⟨w.reachable, h⟩) + refine ⟨z, ⟨rfl, huC, w, rfl, huv, hw⟩, ?_⟩ + have hdx := x.distance_le z q + change dist x z ≤ q.length x.height T at hdx + have hr := r.length_nonneg T y.height + linarith + +/-- Any point in a high component and within `L` of a point outside it is +within `L+200a` of one of its two fixed entrance portals. -/ +lemma near_component_portal (hJ : IsClosed J) (o : M.Point J root) + {H a t : ℝ} (hH : H ∈ J) (ha : 0 < a) + (hhalf : ∀ T ∈ J, |H - T| ≤ a / 2) + (C : ((M.activeGraph J).induce (o.superlevel H hH t)).ConnectedComponent) + (hne : (o.entrances H hH t C).Nonempty) : + ∃ p ∈ o.entrances H hH t C, ∃ q ∈ o.entrances H hH t C, + ∀ x y : M.Point J root, x.column ∈ ColumnOrder.componentColumns C → + y.column ∉ ColumnOrder.componentColumns C → + dist x p ≤ dist x y + 200 * a ∨ dist x q ≤ dist x y + 200 * a := by + obtain ⟨p, hp, q, hq, _, _, hc⟩ := o.component_two_portals hJ hH ha hhalf C hne + refine ⟨p, hp, q, hq, ?_⟩ + intro x y hx hy + obtain ⟨z, hz, hdist⟩ := o.exit_superlevel_to hJ x y hH C hx hy + rcases hc z hz with h | h + · exact Or.inl (by linarith [dist_triangle x z p]) + · exact Or.inr (by linarith [dist_triangle x z q]) + + +/-- The fixed-height radial profile attains its minimum among the finite +set of columns represented in a nonempty closed ball. -/ +lemma ball_radial_minimum (o x : M.Point J root) {H ρ : ℝ} (hH : H ∈ J) + (hρ : 0 ≤ ρ) : + ∃ y : M.Point J root, dist x y ≤ ρ ∧ + ∀ z : M.Point J root, dist x z ≤ ρ → + dist o (y.withHeight H hH) ≤ dist o (z.withHeight H hH) := by + let R := {i : Fin n // (M.activeGraph J).Reachable root i} + let S : Set R := {i | i.val ∈ x.ballColumns ρ} + let f : R → ℝ := fun i => dist o ⟨i.val, H, hH, i.property⟩ + have hne : S.Nonempty := + ⟨⟨x.column, x.reachable⟩, x.mem_ballColumns x (by simpa using hρ)⟩ + obtain ⟨i, hi, hmin⟩ := Set.exists_min_image S f (Set.toFinite _) hne + obtain ⟨y, hy, hxy⟩ := hi + refine ⟨y, hxy, ?_⟩ + intro z hz + have heq : (⟨i.val, H, hH, i.property⟩ : M.Point J root) = y.withHeight H hH := by + cases y + simp_all only [withHeight] + have h := hmin ⟨z.column, z.reachable⟩ (x.mem_ballColumns z hz) + change dist o _ ≤ dist o (z.withHeight H hH) at h + rwa [heq] at h + +/-- The exact geometric content of the one-chain small-ball argument: +there are only two consecutive radial layer depths in a sufficiently small +ball, and all its representatives lie in one node at the lower depth. -/ +lemma ball_two_layers (hJ : IsClosed J) (o x : M.Point J root) + {H a ρ δ : ℝ} (hH : H ∈ J) (hρ : 0 ≤ ρ) (hδ : 0 < δ) + (hhalf : ∀ T ∈ J, |H - T| ≤ a / 2) (hsmall : 2 * ρ + a < δ) : + ∃ k : ℕ, ∃ y : M.Point J root, + ∃ C : ((M.activeGraph J).induce (o.superlevel H hH (k * δ))).ConnectedComponent, + dist x y ≤ ρ ∧ dist o (y.withHeight H hH) < (k + 1) * δ ∧ + (∀ z : M.Point J root, dist x z ≤ ρ → + z.column ∈ ColumnOrder.componentColumns C ∧ + (k : ℝ) * δ ≤ dist o (z.withHeight H hH) ∧ + dist o (z.withHeight H hH) < (k + 2) * δ) := by + obtain ⟨y, hy, hmin⟩ := o.ball_radial_minimum x hH hρ + let b := dist o (y.withHeight H hH) + let k := ⌊b / δ⌋₊ + have hb : 0 ≤ b / δ := div_nonneg dist_nonneg hδ.le + have hlo : (k : ℝ) * δ ≤ b := (le_div_iff₀ hδ).mp (Nat.floor_le hb) + have hhi : b < (k + 1) * δ := (div_lt_iff₀ hδ).mp (Nat.lt_floor_add_one (b / δ)) + have hbound : ∀ z : M.Point J root, dist x z ≤ ρ → + (k : ℝ) * δ ≤ dist o (z.withHeight H hH) ∧ + dist o (z.withHeight H hH) < (k + 2) * δ := by + intro z hz + have hminz := hmin z hz + have hspread := o.ball_radial_spread x z y hH hhalf hz hy + have hu := (abs_le.mp hspread).2 + constructor + · exact hlo.trans hminz + · dsimp [b] at hhi + linarith + have hsub : x.ballColumns ρ ⊆ o.superlevel H hH (k * δ) := by + rintro _ ⟨z, rfl, hz⟩ + exact (o.mem_superlevel_iff z H hH (k * δ)).mpr (hbound z hz).1 + obtain ⟨C, hC⟩ := ColumnOrder.exists_component_containing + (x.ballColumns_nonempty hρ) (x.ballColumns_preconnected hJ ρ) hsub + exact ⟨k, y, C, hy, hhi, fun z hz => ⟨hC (x.mem_ballColumns z hz), hbound z hz⟩⟩ + + +/-- At depth zero the single radial node contains every reachable column, +including the chosen basepoint column. -/ +lemma mem_zero_component (o x : M.Point J root) {H : ℝ} (hH : H ∈ J) + (C : ((M.activeGraph J).induce (o.superlevel H hH 0)).ConnectedComponent) : + x.column ∈ ColumnOrder.componentColumns C := by + classical + obtain ⟨i, hi⟩ := C.nonempty_supp + obtain ⟨hr, _⟩ := i.property + obtain ⟨p⟩ := hr.symm.trans x.reachable + apply ColumnOrder.componentColumns_of_walk C p ⟨i, hi, rfl⟩ + intro v hv + exact ⟨hr.trans (p.takeUntil v hv).reachable, dist_nonneg⟩ + +/-- Two fixed geometric portals, with all bounds required by the actual +interpolation hierarchy. Repeated portals encode the one-portal case. -/ +structure PortalData (o : M.Point J root) (H : ℝ) (hH : H ∈ J) (a t : ℝ) + (C : ((M.activeGraph J).induce (o.superlevel H hH t)).ConnectedComponent) where + left : M.Point J root + right : M.Point J root + left_height : left.height = H + right_height : right.height = H + left_mem : left.column ∈ ColumnOrder.componentColumns C + right_mem : right.column ∈ ColumnOrder.componentColumns C + left_radial : t ≤ dist o left ∧ dist o left < t + a + right_radial : t ≤ dist o right ∧ dist o right < t + a + cover : ∀ x : M.Point J root, x.column ∈ ColumnOrder.componentColumns C → + min (dist x left) (dist x right) ≤ dist o x - t + 201 * a + entrance_cover : ∀ x : M.Point J root, + x.withHeight H hH ∈ o.entrances H hH t C → + min (dist x left) (dist x right) ≤ 200 * a + +/-- The portal data are constructed from the proved geometry, including the +root convention; they are not assumptions on the interpolation input. -/ +lemma portalData_nonempty (hJ : IsClosed J) (o : M.Point J root) + {H a t : ℝ} (hH : H ∈ J) (ho : o.height = H) (ha : 0 < a) + (hhalf : ∀ T ∈ J, |H - T| ≤ a / 2) (ht : t = 0 ∨ a / 2 < t) + (C : ((M.activeGraph J).induce (o.superlevel H hH t)).ConnectedComponent) : + Nonempty (o.PortalData H hH a t C) := by + rcases ht with rfl | ht + · refine ⟨⟨o, o, ho, ho, o.mem_zero_component o hH C, + o.mem_zero_component o hH C, ?_, ?_, ?_, ?_⟩⟩ + · simpa only [dist_self, zero_add] using And.intro (le_refl (0 : ℝ)) ha + · simpa only [dist_self, zero_add] using And.intro (le_refl (0 : ℝ)) ha + · intro x _ + simp only [min_self, sub_zero, dist_comm x o] + linarith + · rintro x ⟨_, _, y, _, _, hy⟩ + exact (not_lt_of_ge dist_nonneg hy).elim + · obtain ⟨p, hp, q, hq, hpr, hqr, hc⟩ := o.component_two_portals hJ hH ha hhalf C + (o.entrances_nonempty hJ hH ht hhalf C) + refine ⟨⟨p, q, hp.1, hq.1, hp.2.1, hq.2.1, hpr, hqr, ?_, ?_⟩⟩ + · intro x hx + obtain ⟨z, hz, hd⟩ := o.exit_superlevel hJ x hH ht hhalf C hx + rcases hc z hz with hz | hz + · exact (min_le_left _ _).trans (by linarith [dist_triangle x z p]) + · exact (min_le_right _ _).trans (by linarith [dist_triangle x z q]) + · intro x hx + exact min_le_iff.mpr (hc x hx) + +namespace PortalData + +variable {o : M.Point J root} {H a t : ℝ} {hH : H ∈ J} + {C : ((M.activeGraph J).induce (o.superlevel H hH t)).ConnectedComponent} + +/-- Layer points and points only slightly beyond its top are close to a +fixed portal. The radial allowance is kept explicit for child portals. -/ +lemma near_of_radial (K : o.PortalData H hH a t C) + {δ e : ℝ} (x : M.Point J root) (hx : x.column ∈ ColumnOrder.componentColumns C) + (hr : dist o x ≤ t + δ + e) : + min (dist x K.left) (dist x K.right) ≤ δ + e + 201 * a := by + linarith [K.cover x hx] + +lemma near_layer (K : o.PortalData H hH a t C) + (hhalf : ∀ T ∈ J, |H - T| ≤ a / 2) (ha : 0 ≤ a) + {δ : ℝ} (x : M.Point J root) (hx : x.column ∈ ColumnOrder.componentColumns C) + (hr : dist o (x.withHeight H hH) < t + δ) : + min (dist x K.left) (dist x K.right) ≤ δ + 220 * a := by + have hv : dist (x.withHeight H hH) x ≤ a / 2 := by + rw [dist_comm, x.dist_withHeight, abs_sub_comm] + exact hhalf x.height x.inBand + have htri := dist_triangle o (x.withHeight H hH) x + linarith [K.cover x hx] + +/-- A near-exit point is in the equality collar of these same portals; +there is no resampling or reselecting a different portal pair. -/ +lemma near_exit (K : o.PortalData H hH a t C) (hJ : IsClosed J) + (x y : M.Point J root) (hx : x.column ∈ ColumnOrder.componentColumns C) + (hy : y.column ∉ ColumnOrder.componentColumns C) : + min (dist x K.left) (dist x K.right) ≤ dist x y + 200 * a := by + obtain ⟨z, hz, hd⟩ := o.exit_superlevel_to hJ x y hH C hx hy + rcases min_le_iff.mp (K.entrance_cover z hz) with h | h + · exact (min_le_left _ _).trans (by linarith [dist_triangle x z K.left]) + · exact (min_le_right _ _).trans (by linarith [dist_triangle x z K.right]) + +end PortalData + +end Point + +end Model +end Columns +end PlanarL1 + +end + +end OAI diff --git a/lean/OAI/Combinatorics/PlanarL1/Drawing.lean b/lean/OAI/Combinatorics/PlanarL1/Drawing.lean new file mode 100644 index 0000000000000000000000000000000000000000..a2926b1138caf709d617a5e290b85371573991c5 --- /dev/null +++ b/lean/OAI/Combinatorics/PlanarL1/Drawing.lean @@ -0,0 +1,563 @@ +import OAI.Combinatorics.PlanarL1.Statement +import OAI.Combinatorics.PlanarL1.DiskCrossing + +namespace OAI + +section + +namespace PlanarL1.Topology +open Set Metric + +/-- The literal topological drawing, with its coordinates identified with the +complex plane. No polygonal or combinatorial planarity assumption is added. -/ +structure Drawing {V : Type} (G : SimpleGraph V) where + point : V → ℂ + point_injective : Function.Injective point + edge : ∀ u v, G.Adj u v → Path (point u) (point v) + edge_injective : ∀ u v h, Function.Injective (edge u v h) + interior_avoid : ∀ u v h (t : unitInterval) w, + 0<(t:ℝ) → (t:ℝ)<1 → edge u v h t ≠ point w + interior_disjoint : ∀ u v h x y k (s t : unitInterval), + 0<(s:ℝ) → (s:ℝ)<1 → 0<(t:ℝ) → (t:ℝ)<1 → + edge u v h s=edge x y k t → (u=x ∧ v=y) ∨ (u=y ∧ v=x) + +lemma drawing_of_planar {V : Type} {G : SimpleGraph V} (h : IsPlanar G) : + Nonempty (Drawing G) := by + obtain ⟨p,a,hp,ha,hi,hv,hd⟩ := h + let e := Complex.equivRealProdCLM.symm + refine ⟨⟨fun v => e (p v),e.injective.comp hp, + fun u v h => ⟨⟨fun t => e (a u v h t),e.continuous.comp (a u v h).continuous⟩, + congrArg e (ha u v h).1,congrArg e (ha u v h).2⟩,?_,?_,?_⟩⟩ + · intro u v h + exact e.injective.comp (hi u v h) + · intro u v h t w ht ht' he + exact hv u v h t w ht ht' (e.injective he) + · intro u v h x y k s t hs hs' ht ht' he + exact hd u v h x y k s t hs hs' ht ht' (e.injective he) + +namespace Drawing +variable {V : Type} {G : SimpleGraph V} (D : Drawing G) + +lemma point_on_edge_iff (u v : V) (h : G.Adj u v) (w : V) (t : unitInterval) : + D.edge u v h t=D.point w ↔ (t=0 ∧ w=u) ∨ (t=1 ∧ w=v) := by + constructor + · intro he + by_cases h0 : t=0 + · left + refine ⟨h0,?_⟩ + rw [h0,Path.source] at he + exact (D.point_injective he).symm + by_cases h1 : t=1 + · right + refine ⟨h1,?_⟩ + rw [h1,Path.target] at he + exact (D.point_injective he).symm + exact False.elim (D.interior_avoid u v h t w + (lt_of_le_of_ne t.2.1 (by intro he; exact h0 (Subtype.ext he.symm))) + (lt_of_le_of_ne t.2.2 (by intro he; exact h1 (Subtype.ext he))) he) + · rintro (⟨rfl,rfl⟩ | ⟨rfl,rfl⟩) <;> simp + +/-- Away from the first/last third of an incident edge, every vertex is +uniformly separated from that edge. The set is closed even at both cutoffs. -/ +def excludedTimes (w : V) (d : G.Dart) : Set unitInterval := + {t | (w≠d.fst ∨ (1/3:ℝ)≤(t:ℝ)) ∧ (w≠d.snd ∨ (t:ℝ)≤(2/3:ℝ))} + +lemma excludedTimes_closed (w : V) (d : G.Dart) : IsClosed (excludedTimes w d) := by + have hu : IsClosed {t : unitInterval | w≠d.fst} := by + by_cases h : w≠d.fst <;> simp [h] + have hv : IsClosed {t : unitInterval | w≠d.snd} := by + by_cases h : w≠d.snd <;> simp [h] + exact (hu.union (isClosed_le continuous_const continuous_subtype_val)).inter + (hv.union (isClosed_le continuous_subtype_val continuous_const)) + +lemma excludedTimes_avoid (w : V) (d : G.Dart) : + D.point w ∉ D.edge d.fst d.snd d.adj '' excludedTimes w d := by + rintro ⟨t,ht,he⟩ + rcases (D.point_on_edge_iff _ _ _ _ t).mp he with ⟨rfl,rfl⟩ | ⟨rfl,rfl⟩ + · rcases ht.1 with h | h + · exact h rfl + · norm_num at h + · rcases ht.2 with h | h + · exact h rfl + · norm_num at h + +variable [Fintype V] +/-- A compact forbidden set for a vertex disk: other vertices and the +parts of every drawn edge that must stay outside that disk. -/ +def forbidden (w : V) : Set ℂ := + (⋃ v : {v : V // v≠w}, {D.point v.val}) ∪ + ⋃ d : G.Dart, D.edge d.fst d.snd d.adj '' excludedTimes w d + +lemma forbidden_compact (w : V) : IsCompact (D.forbidden w) := by + classical + apply IsCompact.union + · exact isCompact_iUnion (fun _ => isCompact_singleton) + · exact isCompact_iUnion (fun d => + (excludedTimes_closed w d).isCompact.image (D.edge _ _ _).continuous) + +omit [Fintype V] in +lemma forbidden_avoid (w : V) : D.point w ∉ D.forbidden w := by + rintro (h | h) + · obtain ⟨⟨v,hv⟩,he⟩ := mem_iUnion.mp h + exact hv (D.point_injective (mem_singleton_iff.mp he).symm) + · obtain ⟨d,hd⟩ := mem_iUnion.mp h + exact D.excludedTimes_avoid w d hd + +lemma vertex_disk (w : V) : + ∃ r>0, ∀ z ∈ D.forbidden w, r ?_⟩ + have hnot : ¬dist z (D.point w) hball h hz + rw [dist_comm] at hnot + linarith + +/-- One common positive radius works for all vertices; arbitrary edge +oscillations and arbitrary straight-line distances between drawn vertices are +allowed. This radius is topological auxiliary data, not a metric edge scale. -/ +lemma uniform_vertex_disks : + ∃ r>0, ∀ w z, z ∈ D.forbidden w → 5*r exact ⟨1,by norm_num,fun w => isEmptyElim w⟩ + | inr h => + choose e he hs using D.vertex_disk + let R := Finset.univ.inf' (Finset.univ_nonempty : (Finset.univ : Finset V).Nonempty) e + have hR : 0 he w) + refine ⟨R/10,by positivity,fun w z hz => ?_⟩ + have hRw : R≤e w := Finset.inf'_le e (Finset.mem_univ w) + have hz' := hs w z hz + linarith + +end Drawing + +/-- Last exit from a closed disk before a specified later time. This works +for arbitrary continuous paths, including paths which oscillate infinitely +near their endpoint. No local straightness of a topological arc is assumed. -/ +lemma path_lastExit {X : Type*} [MetricSpace X] {x y : X} (p : Path x y) + {b r : ℝ} (hb : 0 ?_⟩ + by_contra! h + exact (not_le_of_gt hat) (hamax ⟨⟨ha0.le.trans hat.le,htb⟩,h⟩) + +lemma path_trimStart {X : Type*} [MetricSpace X] {x y : X} (p : Path x y) + {b : unitInterval} {r : ℝ} (hb : 0<(b:ℝ)) (hr : 0 ?_⟩ + · change dist (p.extend (a':ℝ)) x=r at he + rw [p.extend_apply a'.property] at he + exact he + · by_cases htb : t≤b + · have ht' := ht t hat htb + simpa only [p.extend_apply t.property] using ht' + · exact hout t (le_of_not_ge htb) + +namespace Drawing +variable {V : Type} {G : SimpleGraph V} (D : Drawing G) + +lemma edge_mem_forbidden (w : V) (d : G.Dart) (t : unitInterval) + (h : t ∈ excludedTimes w d) : + D.edge d.fst d.snd d.adj t ∈ D.forbidden w := + Or.inr (mem_iUnion.mpr ⟨d,⟨t,h,rfl⟩⟩) + +lemma point_mem_forbidden (w v : V) (h : v≠w) : D.point v ∈ D.forbidden w := + Or.inl (mem_iUnion.mpr ⟨⟨v,h⟩,rfl⟩) + +/-- Truncate one actual drawn edge outside disjoint small vertex disks. +The middle arc stays outside every disk, with equality only at its own ends. -/ +structure EdgeTrim (r : ℝ) (d : G.Dart) where + first : unitInterval + last : unitInterval + first_pos : 0<(first:ℝ) + first_lt : (first:ℝ)<1/3 + last_gt : (2/3:ℝ)<(last:ℝ) + last_lt_one : (last:ℝ)<1 + first_sphere : dist (D.edge d.fst d.snd d.adj first) (D.point d.fst)=r + last_sphere : dist (D.edge d.fst d.snd d.adj last) (D.point d.snd)=r + after_first : ∀ t : unitInterval, first(z:ℝ) at hzb + change (2/3:ℝ)<1-(z:ℝ) + linarith + · change 1-(z:ℝ)<1 + linarith + · exact hz + · intro t ht + let t' : unitInterval := ⟨1-(t:ℝ),by linarith [t.2.2],by linarith [t.2.1]⟩ + have ht' : z segment ℝ a b ⊆ S) x y + +lemma polygonallyJoined_of_path {S : Set E} (hS : IsOpen S) {x y : E} + (p : Path x y) (hp : Set.range p ⊆ S) : PolygonallyJoined S x y := by + classical + let A := {z | z ∈ S ∧ PolygonallyJoined S x z} + let B := S \ A + have hA : IsOpen A := by + apply Metric.isOpen_iff.mpr + intro z hz + obtain ⟨r,hr,hball⟩ := Metric.isOpen_iff.mp hS z hz.1 + refine ⟨r,hr,fun w hw => ⟨hball hw,?_⟩⟩ + exact hz.2.tail ((convex_ball z r).segment_subset (by simpa using hr) hw |>.trans hball) + have hB : IsOpen B := by + apply Metric.isOpen_iff.mpr + intro z hz + obtain ⟨r,hr,hball⟩ := Metric.isOpen_iff.mp hS z hz.1 + refine ⟨r,hr,fun w hw => ⟨hball hw,fun hwA => hz.2 ⟨hz.1,?_⟩⟩⟩ + exact hwA.2.tail ((convex_ball z r).segment_subset hw (by simpa using hr) |>.trans hball) + have hd : Disjoint A B := Set.disjoint_left.mpr (fun z ha hb => hb.2 ha) + have hu : Set.range p ⊆ A ∪ B := by + intro z hz + by_cases ha : z ∈ A + · exact Or.inl ha + · exact Or.inr ⟨hp hz,ha⟩ + have hne : (Set.range p ∩ A).Nonempty := + ⟨x,⟨0,p.source⟩,hp ⟨0,p.source⟩,Relation.ReflTransGen.refl⟩ + have hall := IsPreconnected.subset_left_of_subset_union hA hB hd hu hne + (isPreconnected_range p.continuous) + exact (hall ⟨1,p.target⟩).2 + +/-- Polygonal connectivity has literal finite-list witnesses. -/ +lemma PolygonallyJoined.exists_chain {S : Set E} {x y : E} + (h : PolygonallyJoined S x y) : + ∃ l : List E, (x::l).IsChain (fun a b => segment ℝ a b ⊆ S) ∧ + (x::l).getLast (by simp)=y := by + exact List.exists_isChain_cons_of_relationReflTransGen h + +/-- Disjoint compact arcs can be simultaneously thickened, while avoiding +separate closed obstacles. No finiteness or regularity of the arcs themselves +beyond compactness is used. -/ +lemma finite_disjoint_open_neighborhoods {ι X : Type*} [Fintype ι] [MetricSpace X] + (K F : ι → Set X) (hK : ∀ i, IsCompact (K i)) (hF : ∀ i, IsClosed (F i)) + (hKF : ∀ i, Disjoint (K i) (F i)) (hKK : Pairwise (fun i j => Disjoint (K i) (K j))) : + ∃ U : ι → Set X, (∀ i, IsOpen (U i) ∧ K i ⊆ U i ∧ Disjoint (U i) (F i)) ∧ + Pairwise (fun i j => Disjoint (U i) (U j)) := by + classical + let O (i : ι) := F i ∪ ⋃ j : {j : ι // j≠i}, K j.val + have hO (i : ι) : IsClosed (O i) := + (hF i).union (isClosed_iUnion_of_finite (fun j => (hK j).isClosed)) + have hKO (i : ι) : Disjoint (K i) (O i) := by + apply Disjoint.union_right (hKF i) + refine Set.disjoint_iUnion_right.mpr (fun j => ?_) + exact hKK j.property.symm + choose r hr hd using fun i => (hKO i).exists_thickenings (hK i) (hO i) + refine ⟨fun i => Metric.thickening (r i) (K i),?_,?_⟩ + · intro i + refine ⟨Metric.isOpen_thickening,Metric.self_subset_thickening (hr i) _,?_⟩ + exact (hd i).mono_right ((show F i ⊆ O i from Set.subset_union_left).trans + (Metric.self_subset_thickening (hr i) _)) + · intro i j hij + have hji : K j ⊆ O i := fun x hx => Or.inr (mem_iUnion.mpr ⟨⟨j,hij.symm⟩,hx⟩) + have hij' : K i ⊆ O j := fun x hx => Or.inr (mem_iUnion.mpr ⟨⟨i,hij⟩,hx⟩) + rcases le_total (r j) (r i) with h | h + · exact (hd i).mono_right ((Metric.thickening_mono h _).trans + (Metric.thickening_subset_of_subset _ hji)) + · exact ((hd j).mono_right ((Metric.thickening_mono h _).trans + (Metric.thickening_subset_of_subset _ hij'))).symm + +end PlanarL1.Topology + + +namespace PlanarL1.Topology +open Set Metric + +/-- On a radial segment, the endpoint is the only point at its maximal +radius. This is valid in every real normed space, without strict convexity. -/ +lemma radial_segment_boundary {E : Type*} [NormedAddCommGroup E] [NormedSpace ℝ E] + {x y z : E} {r : ℝ} (hr : 0 dist q x) he + simp only [dist_eq_norm,add_sub_cancel_left,norm_smul,Real.norm_eq_abs, + abs_of_nonneg ht.1,abs_of_nonneg hs.1] at hn + rw [← dist_eq_norm,← dist_eq_norm,hw,hy] at hn + have hst : s=t := (mul_right_cancel₀ hr.ne' hn) + subst s + by_cases ht0 : t=0 + · simp [ht0] + · have hvec := add_left_cancel he + have hew := (smul_right_injective E ht0) hvec + exact False.elim (hne (sub_left_inj.mp hew).symm) + +/-- Choosing only the forward dart avoids treating the two independently +supplied oriented parametrizations as one geometric edge. -/ +def ForwardDart {V : Type} [LinearOrder V] (G : SimpleGraph V) := + {d : G.Dart // d.fst + Disjoint (Set.range (T d).middle) (Set.range (T e).middle)) := by + intro d e hde + apply Set.disjoint_left.mpr + intro z hz hz' + rw [(T d).middle_range] at hz + rw [(T e).middle_range] at hz' + obtain ⟨s,hs,rfl⟩ := hz + obtain ⟨t,ht,he⟩ := hz' + exact hde (ForwardDart.eq_of_endpoints d e (D.interior_disjoint _ _ _ _ _ _ s t + ((T d).first_pos.trans_le hs.1) ((show (s:ℝ)≤(T d).last from hs.2).trans_lt (T d).last_lt_one) + ((T e).first_pos.trans_le ht.1) ((show (t:ℝ)≤(T e).last from ht.2).trans_lt (T e).last_lt_one) he.symm)) + +/-- Obstacles for the middle of an edge: all vertices and the radial heads +of every other unoriented edge. -/ +noncomputable def middleObstacle (d : ForwardDart G) : Set ℂ := + Set.range D.point ∪ ⋃ e : {e : ForwardDart G // e≠d}, + (segment ℝ (D.point e.val.val.fst) + (D.edge e.val.val.fst e.val.val.snd e.val.val.adj (T e.val).first)) ∪ + (segment ℝ (D.point e.val.val.snd) + (D.edge e.val.val.fst e.val.val.snd e.val.val.adj (T e.val).last)) + +lemma middleObstacle_closed (d : ForwardDart G) : IsClosed (D.middleObstacle T d) := by + classical + exact (Set.finite_range D.point).isClosed.union (isClosed_iUnion_of_finite (fun e => + (compact_segment_complex _ _).isClosed.union (compact_segment_complex _ _).isClosed)) + +omit [Fintype V] in +lemma middleObstacle_disjoint (hr : 0 ?_) + have hne : ¬ ((d.val.fst=e.val.val.fst ∧ d.val.snd=e.val.val.snd) ∨ + (d.val.fst=e.val.val.snd ∧ d.val.snd=e.val.val.fst)) := + fun h => e.property (ForwardDart.eq_of_endpoints d e.val h).symm + exact Disjoint.union_right ((T d).middle_radial_head (T e.val) hr hsep hne) + ((T d).middle_radial_tail (T e.val) hr hsep hne) + +/-- Every trimmed edge can be replaced by a literal finite segment chain, +inside mutually disjoint open tubes avoiding all other edge heads and all +vertices. This is the needed simultaneous polygonalization step. -/ +lemma polygonal_middles (hr : 0 Disjoint (U d) (U e)) := by + classical + obtain ⟨U,hU,hd⟩ := finite_disjoint_open_neighborhoods + (fun d => Set.range (T d).middle) (D.middleObstacle T) + (fun d => (T d).middle_compact) (D.middleObstacle_closed T) + (D.middleObstacle_disjoint T hr hsep) (D.forward_middles_disjoint T) + exact ⟨U,fun d => ⟨(hU d).1,(hU d).2.2, + polygonallyJoined_of_path (hU d).1 (T d).middle (hU d).2.1⟩,hd⟩ + +end Drawing +end PlanarL1.Topology + + + +end + +end OAI diff --git a/lean/OAI/Combinatorics/PlanarL1/Embedding.lean b/lean/OAI/Combinatorics/PlanarL1/Embedding.lean new file mode 100644 index 0000000000000000000000000000000000000000..6a5cafc6b9160f9a407372b33300b047d0fe5330 --- /dev/null +++ b/lean/OAI/Combinatorics/PlanarL1/Embedding.lean @@ -0,0 +1,124 @@ +import OAI.Combinatorics.PlanarL1.Schedule +import OAI.Combinatorics.PlanarL1.PlanarMetric + +namespace OAI + + +section + +universe u +namespace PlanarL1.Columns.Model.Ambient +open Parameters +variable {k : ℕ} {V : Type u} [Fintype V] {M : Model (k+1)} +variable {q : ℕ} (g : GoodSpacing q) (A : Ambient M) (v : V → M.Point Set.univ A.root) +include g + +/-- The actual finite coupled process produces a cut metric with a universal +lower bound. The finite initial units, mesh and number of steps are selected +from the given vertices; they do not enter the distortion constant. -/ +lemma exists_uniform_cuts : ∃ C : FiniteL1.CutFamily V, ∀ x y, + (scheduleGain/(q:ℝ))*dist (v x) (v y) ≤ C.distance x y ∧ + C.distance x y ≤ 2*dist (v x) (v y) := by + classical + obtain ⟨ε,hε,N,hcover⟩ := finite_schedule_cover (fun x y => dist (v x) (v y)) + (fun _ _ => dist_nonneg) g.gt_one + obtain ⟨m,hm,hmany,hmesh⟩ := exists_mesh N + let σ : Fin q → ℝ := fun i => ε/((i.val+1:ℕ):ℝ) + have hσ (i : Fin q) : 0<σ i := div_pos hε (Nat.cast_pos.mpr (Nat.zero_lt_succ _)) + let C : Fin q → FiniteL1.CutFamily V := fun i => World.normalizedCuts g A v (hσ i) hm N + let D : FiniteL1.CutFamily V := FiniteL1.CutFamily.scale (1/(q:ℝ)) (div_nonneg (by norm_num) g.pos.le) + (FiniteL1.CutFamily.sum C) + have hupper (i : Fin q) (x y : V) : (C i).distance x y ≤ 2*dist (v x) (v y) := + World.normalizedCuts_upper g A v (hσ i) hm N x y + have hdistance (x y : V) : D.distance x y=(1/(q:ℝ))*∑ i, (C i).distance x y := by + rw [FiniteL1.CutFamily.distance_scale,FiniteL1.CutFamily.distance_sum] + refine ⟨D,fun x y => ⟨?_,?_⟩⟩ + · by_cases hxy : 0 (C j).distance_nonneg x y) (Finset.mem_univ i) + rw [hdistance] + have hh := mul_le_mul_of_nonneg_left (hl.trans hs) (div_nonneg (show (0:ℝ)≤1 by norm_num) g.pos.le) + calc + _ = (1/(q:ℝ))*(scheduleGain*dist (v x) (v y)) := by ring + _ ≤ _ := hh + · have he : dist (v x) (v y)=0 := le_antisymm (le_of_not_gt hxy) dist_nonneg + rw [he,mul_zero] + exact D.distance_nonneg x y + · rw [hdistance] + calc + _ ≤ (1/(q:ℝ))*∑ i : Fin q, 2*dist (v x) (v y) := + mul_le_mul_of_nonneg_left (Finset.sum_le_sum (fun i _ => hupper i x y)) + (div_nonneg (by norm_num) g.pos.le) + _ = 2*dist (v x) (v y) := by + simp only [Finset.sum_const,Finset.card_univ,Fintype.card_fin,nsmul_eq_mul] + rw [← mul_assoc,one_div,inv_mul_cancel₀ g.pos.ne',one_mul] + +/-- A finite-dimensional real L1 embedding of vertices of any connected +terminal noncrossing column model, with a constant depending only on q. -/ +lemma exists_L1_embedding : ∃ (Ω : Type u) (measurable : MeasurableSpace Ω) + (μ : @MeasureTheory.Measure Ω measurable) + (f : V → @MeasureTheory.Lp Ω ℝ measurable _ 1 μ), ∀ x y, + dist (v x) (v y) ≤ ‖f x-f y‖ ∧ + ‖f x-f y‖ ≤ (2/(scheduleGain/(q:ℝ)))*dist (v x) (v y) := by + obtain ⟨C,hC⟩ := A.exists_uniform_cuts g v + let : MeasurableSpace (Set V) := ⊤ + obtain ⟨f,hf⟩ := C.embedding_of_bounds (fun x y => dist (v x) (v y)) + (div_pos scheduleGain_pos g.pos) (fun x y => (hC x y).1) (fun x y => (hC x y).2) + exact ⟨Set V,⊤,MeasureTheory.Measure.count,f,hf⟩ +end PlanarL1.Columns.Model.Ambient + +end + + + +section + +namespace PlanarL1.HeightTree.Layout +open Columns +variable {U : Type*} [Fintype U] {T : HeightTree U} {k : ℕ} +noncomputable def ambient (L : T.Layout (k+1)) : Model.Ambient L.model where + root := L.column T.root + connected i := by + obtain ⟨p,_⟩ := L.exists_prefixPath (T.root_ancestor (L.leaf (L.column T.root))) + (T.root_ancestor (L.leaf i)) le_rfl le_rfl + exact ⟨p.word⟩ +end PlanarL1.HeightTree.Layout + +namespace PlanarL1 +open Parameters Columns.Model + +/-- Theorem 1.1 of the literal source. The spacing is selected once, before +any graph or length data. Its finite cut embedding is converted to real Lp1. +All geometric realization and process hypotheses are discharged above. -/ +theorem planar_graph_metrics_embed_L1 : MainStatement := by + classical + obtain ⟨q,g⟩ := exists_goodSpacing + refine ⟨max 1 (2/(scheduleGain/(q:ℝ))),le_max_left _ _,?_⟩ + intro n G length hc hp hs hl + let o : Fin n := Classical.choice hc.nonempty + obtain ⟨s,L,hL,hd⟩ := Weighted.EnlargedTree.column_model_of_planar hc hs hl o hp + cases s with + | zero => exact (Fin.elim0 (L.column (Weighted.EnlargedTree.tree hc hs hl o).root)) + | succ k => + let A := L.ambient + obtain ⟨Ω,measurable,μ,f,hf⟩ := A.exists_L1_embedding g (fun v => L.point (.inl v)) + refine ⟨Ω,measurable,μ,f,?_⟩ + intro x y + have he : dist (L.point (.inl x)) (L.point (.inl y))=graphDistance G length x y := hd x y + have hh := hf x y + change (L.point (.inl x)).distance (L.point (.inl y)) ≤ ‖f x-f y‖ ∧ + ‖f x-f y‖ ≤ (2/(scheduleGain/(q:ℝ)))*(L.point (.inl x)).distance (L.point (.inl y)) at hh + rw [hd x y] at hh + refine ⟨hh.1,hh.2.trans ?_⟩ + apply mul_le_mul_of_nonneg_right (le_max_right _ _) + rw [← he] + exact dist_nonneg +end PlanarL1 + + +end + +end OAI diff --git a/lean/OAI/Combinatorics/PlanarL1/Execution.lean b/lean/OAI/Combinatorics/PlanarL1/Execution.lean new file mode 100644 index 0000000000000000000000000000000000000000..eb15dac546fc520ad67c24f883c8215ae83c7e8c --- /dev/null +++ b/lean/OAI/Combinatorics/PlanarL1/Execution.lean @@ -0,0 +1,219 @@ +import OAI.Combinatorics.PlanarL1.Probability + +namespace OAI + +section + +namespace PlanarL1 + +/-- Finite adaptive execution trees. Every node makes an actual uniform finite +choice; its continuation, including the number of later choices, may depend on +that choice. This is the finite probability law used by the manuscript. -/ +inductive Execution (α : Type*) where + | pure : α → Execution α + | choose (n : ℕ) : (Fin (n+1) → Execution α) → Execution α + +namespace Execution +attribute [local instance] Classical.propDecidable +variable {α β : Type*} + +noncomputable def mean : Execution α → (α → ℝ) → ℝ + | .pure x, f => f x + | .choose n E, f => (∑ i, mean (E i) f)/(n+1) + +noncomputable def prob (E : Execution α) (P : α → Prop) : ℝ := by + classical + exact E.mean (fun x => if P x then 1 else 0) + +def bind : Execution α → (α → Execution β) → Execution β + | .pure x, f => f x + | .choose n E, f => .choose n (fun i => bind (E i) f) + +lemma mean_const (E : Execution α) (c : ℝ) : E.mean (fun _ => c) = c := by + induction E with + | pure x => rfl + | choose n E ih => simp [mean,ih]; field_simp + +lemma mean_add (E : Execution α) (f g : α → ℝ) : + E.mean (fun x => f x+g x)=E.mean f+E.mean g := by + induction E with + | pure x => rfl + | choose n E ih => simp only [mean,ih,Finset.sum_add_distrib,add_div] + +lemma mean_smul (E : Execution α) (c : ℝ) (f : α → ℝ) : + E.mean (fun x => c*f x)=c*E.mean f := by + induction E with + | pure x => rfl + | choose n E ih => simp only [mean,ih,← Finset.mul_sum]; ring + +lemma mean_mono (E : Execution α) {f g : α → ℝ} (h : ∀ x, f x ≤ g x) : + E.mean f ≤ E.mean g := by + induction E with + | pure x => exact h x + | choose n E ih => exact div_le_div_of_nonneg_right (Finset.sum_le_sum (fun i _ => ih i)) (by positivity) + +lemma mean_nonneg (E : Execution α) {f : α → ℝ} (h : ∀ x, 0 ≤ f x) : 0 ≤ E.mean f := by + simpa only [mean_const] using E.mean_mono h + +lemma mean_bind (E : Execution α) (F : α → Execution β) (f : β → ℝ) : + (E.bind F).mean f = E.mean (fun x => (F x).mean f) := by + induction E with + | pure x => rfl + | choose n E ih => simp only [bind,mean,ih] + +lemma prob_bind (E : Execution α) (F : α → Execution β) (P : β → Prop) : + (E.bind F).prob P=E.mean (fun x => (F x).prob P) := E.mean_bind F _ + +lemma prob_nonneg (E : Execution α) (P : α → Prop) : 0 ≤ E.prob P := by + classical + exact E.mean_nonneg (by intro x; split_ifs <;> norm_num) + +lemma prob_le_one (E : Execution α) (P : α → Prop) : E.prob P ≤ 1 := by + classical + simpa only [prob,mean_const] using E.mean_mono (f := fun x => if P x then 1 else 0) + (g := fun _ => (1:ℝ)) (by intro x; split_ifs <;> norm_num) + +lemma prob_compl (E : Execution α) (P : α → Prop) : E.prob (fun x => ¬P x)=1-E.prob P := by + classical + have h : E.prob P+E.prob (fun x => ¬P x)=1 := by + unfold prob + rw [← mean_add] + calc + _=E.mean (fun _ => 1) := by + congr 1 + funext x + by_cases hx : P x <;> simp [hx] + _=1 := E.mean_const 1 + linarith + +lemma prob_mono (E : Execution α) {P Q : α → Prop} (h : ∀ x, P x → Q x) : + E.prob P ≤ E.prob Q := by + classical + apply E.mean_mono + intro x + by_cases hp : P x + · simp [hp,h x hp] + · simp only [hp, ite_false]; split_ifs <;> norm_num + +lemma mean_lower_of_event (E : Execution α) {P : α → Prop} {f : α → ℝ} {c : ℝ} + (hf : ∀ x, 0 ≤ f x) (h : ∀ x, P x → c ≤ f x) : c*E.prob P ≤ E.mean f := by + classical + rw [prob,← mean_smul] + apply E.mean_mono + intro x + by_cases hx : P x <;> simp only [hx,ite_true,ite_false,mul_one,mul_zero] + · exact h x hx + · exact hf x + +/-- Conditional failure bounds compose even when later grids and cell choices +are chosen using the entire previous history. -/ +lemma conditional_loss (E : Execution α) (F : α → Execution β) + (P : α → Prop) (Q : β → Prop) {ε : ℝ} (hε : 0 ≤ ε) + (h : ∀ x, P x → (F x).prob (fun y => ¬Q y) ≤ ε) : + (E.bind F).prob (fun y => ¬Q y) ≤ E.prob (fun x => ¬P x)+ε := by + classical + rw [prob_bind] + calc + _ ≤ E.mean (fun x => (if ¬P x then 1 else 0)+ε) := by + apply E.mean_mono + intro x + by_cases hx : P x + · simpa only [hx,not_true_eq_false,ite_false,zero_add] using h x hx + · simpa only [hx,not_false_eq_true,ite_true] using (F x).prob_le_one (fun y => ¬Q y) |>.trans (le_add_of_nonneg_right hε) + _ = _ := by + rw [mean_add,mean_const] + unfold prob + congr 2 + funext x + by_cases hx : P x <;> simp [hx] + +lemma conditional_success (E : Execution α) (F : α → Execution β) + (P : α → Prop) (Q : β → Prop) {p : ℝ} + (h : ∀ x, P x → p ≤ (F x).prob Q) : + p*E.prob P ≤ (E.bind F).prob Q := by + rw [prob_bind] + exact E.mean_lower_of_event (fun x => (F x).prob_nonneg Q) h + +/-- Evolution retains the complete state, which can itself contain the past. -/ +def evolve (step : ℕ → α → Execution α) (start : Execution α) : ℕ → Execution α + | 0 => start + | k+1 => (evolve step start k).bind (step k) + +lemma evolve_loss (step : ℕ → α → Execution α) (start : Execution α) + (P : ℕ → α → Prop) (ε : ℕ → ℝ) (hε : ∀ k, 0 ≤ ε k) + (h : ∀ k x, P k x → (step k x).prob (fun y => ¬P (k+1) y) ≤ ε k) (N : ℕ) : + (evolve step start N).prob (fun x => ¬P N x) ≤ + start.prob (fun x => ¬P 0 x)+∑ k ∈ Finset.range N, ε k := by + induction N with + | zero => simp only [evolve,Finset.range_zero,Finset.sum_empty,add_zero,le_refl] + | succ N ih => + have hh := conditional_loss (evolve step start N) (step N) (P N) (P (N+1)) (hε N) (h N) + simp only [evolve] at * + rw [Finset.sum_range_succ] + linarith + +/-- The source's `1/2 · p · br/2` calculation, including adaptive first loss. -/ +theorem surviving_success (E : Execution α) (F : α → Execution β) + (P : α → Prop) (Q : β → Prop) {p c d : ℝ} (hp : 0 ≤ p) (hc : 0 ≤ c) + (hloss : E.prob (fun x => ¬P x) ≤ 1/2) + (hs : ∀ x, P x → p ≤ (F x).prob Q) + (value : β → ℝ) (hv : ∀ y, 0 ≤ value y) + (hq : ∀ y, Q y → c ≤ value y) (hd : d ≤ c*p/2) : + d ≤ (E.bind F).mean value := by + have hgood : 1/2 ≤ E.prob P := by rw [E.prob_compl P] at hloss; linarith + have hsuc := E.conditional_success F P Q hs + have hmean := (E.bind F).mean_lower_of_event hv hq + have hprod := mul_le_mul_of_nonneg_left hgood hp + have hprod' := mul_le_mul_of_nonneg_left (hprod.trans hsuc) hc + nlinarith + +end Execution +end PlanarL1 + +namespace PlanarL1.Execution +variable {α β ι : Type*} + +noncomputable def uniform [Fintype α] [Nonempty α] : Execution α := by + classical + let e : Fin (Fintype.card α-1+1) ≃ α := + (finCongr (Nat.sub_add_cancel (Fintype.card_pos_iff.mpr inferInstance))).trans + (Fintype.equivFin α).symm + exact .choose (Fintype.card α-1) (fun i => .pure (e i)) + +lemma mean_uniform [Fintype α] [Nonempty α] (f : α → ℝ) : + (uniform (α := α)).mean f=(∑ x, f x)/Fintype.card α := by + classical + unfold uniform + simp only [mean] + have he : (∑ i : Fin (Fintype.card α-1+1), f (((finCongr + (Nat.sub_add_cancel (Fintype.card_pos_iff.mpr inferInstance))).trans + (Fintype.equivFin α).symm) i))=∑ x, f x := Equiv.sum_comp _ _ + rw [he] + have h : 0 < Fintype.card α := Fintype.card_pos + have hc : (↑(Fintype.card α-1):ℝ)+1=Fintype.card α := by + exact_mod_cast Nat.sub_add_cancel h + rw [hc] + +lemma prob_uniform [Fintype α] [Nonempty α] (P : α → Prop) : + (uniform (α := α)).prob P=FiniteRandom.prob P := by + classical + rw [prob,mean_uniform] + unfold FiniteRandom.prob + congr 1 + simp only [Finset.sum_boole,FiniteRandom.event] + +lemma mean_sum (E : Execution α) [Fintype ι] (f : ι → α → ℝ) : + E.mean (fun x => ∑ i, f i x)=∑ i, E.mean (f i) := by + classical + induction E with + | pure x => rfl + | choose n F ih => + simp only [mean,ih] + rw [Finset.sum_comm,Finset.sum_div] + +end PlanarL1.Execution + + +end + +end OAI diff --git a/lean/OAI/Combinatorics/PlanarL1/FamilyPersistence.lean b/lean/OAI/Combinatorics/PlanarL1/FamilyPersistence.lean new file mode 100644 index 0000000000000000000000000000000000000000..2f757a7bf2ee0f27d0b4226f896ecc1a082a5515 --- /dev/null +++ b/lean/OAI/Combinatorics/PlanarL1/FamilyPersistence.lean @@ -0,0 +1,696 @@ +import OAI.Combinatorics.PlanarL1.LocalPersistence + +namespace OAI + + +section + +namespace PlanarL1.Columns.Model +open MeasureTheory Parameters +open scoped NNReal +attribute [local instance] Classical.propDecidable +variable {k : ℕ} {M : Model (k+1)} +namespace SecondaryCell +variable {J : Set ℝ} {root : Fin (k+1)} +lemma mem_domain_iff_distance (seeds : Finset (M.Point J root)) (radius : ℝ) + (x : M.Point J root) : x.height ∈ domain seeds radius x.column ↔ seedDistance seeds x≤radius := by + constructor + · intro h + obtain ⟨z,hc,hH,hd⟩ := (mem_domain seeds radius).mp h + exact Point.eq_of_coordinates z x hc hH ▸ hd + · intro h + exact (mem_domain seeds radius).mpr ⟨x,rfl,rfl,h⟩ +lemma point_eq (seeds : Finset (M.Point J root)) (radius : ℝ) (x : M.Point J root) + (h : x.height ∈ domain seeds radius x.column) : point seeds radius _ _ h=x := + Point.eq_of_coordinates _ _ (point_column _ _ _) (point_height _ _ _) +end SecondaryCell +namespace BState.SecondaryStep +open PlanarL1.Interpolation +variable {κ : ℝ} {lam : ℝ≥0} {Ω : Type*} [MeasurableSpace Ω] {μ : Measure Ω} + {S : BState M κ lam Ω μ} {J : Set ℝ} {root : Fin (k+1)} +variable (U : SecondaryStep S J root) +lemma fullNamed_at (z : M.Point J root) (hz : SecondaryCell.seedDistance U.seeds z≤U.radius) : + U.fullNamed z.column ⟨z.height,U.sub_old z.inBand⟩=U.named z := by + have hd := (SecondaryCell.mem_domain_iff_distance U.seeds U.radius z).mpr hz + simp only [fullNamed,dite_eq_left hd,SecondaryCell.point_eq] + +/-- A crossed seed-domain is identically old on the small ball, including its +actual deterministic branch name. No independence or pruning assumption. -/ +lemma fullNamed_boundary_ball (x y : M.Point J root) {ρ : ℝ} + (hsmall : 18*ρ≤(199/1000:ℝ)*U.radius) (hy : dist x y≤ρ) + (hout : y.height ∉ SecondaryCell.domain U.seeds U.radius y.column) + (z : M.Point J root) (hz : dist x z≤ρ) : + U.fullNamed z.column ⟨z.height,U.sub_old z.inBand⟩=⟨0,U.old z⟩ := by + by_cases hd : z.height ∈ SecondaryCell.domain U.seeds U.radius z.column + · have hin := (SecondaryCell.mem_domain_iff_distance U.seeds U.radius z).mp hd + rw [U.fullNamed_at z hin] + have hyout : U.radius≤SecondaryCell.seedDistance U.seeds y := le_of_lt (lt_of_not_ge + (fun h => hout ((SecondaryCell.mem_domain_iff_distance U.seeds U.radius y).mpr h))) + exact SecondaryCell.namedReplacement_boundary_ball U.tree U.seeds U.old U.supportValue U.data.isOrdinary + U.seeds_nonempty U.old_lipschitz U.support_lipschitz U.zeta_eq U.radius_nonneg + U.ordered_bound U.delta_eq U.noise_bounds U.support_le U.admitted U.shield_offset U.lo + x y hsmall hy hyout z hz hin + · rw [fullNamed,dite_eq_right hd] + rfl +end BState.SecondaryStep +end PlanarL1.Columns.Model + +namespace PlanarL1.Columns.Model.RetainedSelection +open Parameters MeasureTheory +attribute [local instance] Classical.propDecidable +variable {k : ℕ} {M : Model (k+1)} {V Ω Ξ : Type*} +variable [Fintype V] [MeasurableSpace Ω] [MeasurableSpace Ξ] +variable {μ : Measure Ω} {ν : Measure Ξ} +variable (A : Ambient M) (SA : OrdinaryState M kappaA Ω μ) +variable (SB : BState M kappaB SecondaryGeometry.Group.lam Ξ ν) +variable (v : V → M.Point Set.univ A.root) +variable {L U : ℝ} (hv : ∀ x, (v x).height ∈ Set.Icc L U) +variable {q p : ℝ} {phaseD phaseG : MainFamily.BandComponent (M := M) q L U → ℝ} +variable (x : M.Point Set.univ A.root) {ρ : ℝ} (hρ : 0≤ρ) +variable (hp : Tiling.Padded a₂ p x.height ρ) +variable (i : GroupIndex A SA SB v hv (p := p) (phaseD := phaseD) (phaseG := phaseG)) +variable (positive : Bool) (C : (group A SA SB v hv i).Component) +variable {z : M.Point Set.univ A.root} (hz : dist x z≤ρ) +variable (hd : z.height ∈ SecondaryCell.domain ((group A SA SB v hv i).admittedSeeds positive C) R z.column) +include hρ hp hz hd +lemma group_touched_band : i.1.2.val.val=Tiling.index a₂ p x.height := by + apply Tiling.near_band_unique interpolationB.2.1 hρ hp _ + (i.1.narrow_eq ▸ SecondaryCell.inBand_of_mem _ _ hd) + rw [abs_sub_comm] + exact (x.height_change_le z).trans hz +lemma group_touched_envelope : ∀ H, |H-x.height|≤ρ → H ∈ BandTrees.band narrow (group A SA SB v hv i).lower := by + intro H hH + have he := group_touched_band A SA SB v hv x hρ hp i positive C hz hd + have hb := Tiling.near_mem_band interpolationB.2.1 hρ hp hH + rw [←he,←i.1.narrow_eq] at hb + exact hb +lemma group_local_center : ∃ x' : M.Point (BandTrees.band narrow (group A SA SB v hv i).lower) + ((group A SA SB v hv i).root C), x'.column=x.column ∧ x'.height=x.height := + Point.local_center x z (SecondaryCell.point _ _ _ _ hd) + (SecondaryCell.point_column _ _ _) (SecondaryCell.point_height _ _ _) hρ + (group_touched_envelope A SA SB v hv x hρ hp i positive C hz hd) hz + +lemma ball_domain_touch (b : Block (M := M) q p L U) + (c : M.Point (BandTrees.band broad b.lower) (BandTrees.root M broad b.lower b.1.2)) + (hc : c.column=x.column) (hH : c.height=x.height) + (hC : ((group A SA SB v hv i).admittedSeeds positive C).Nonempty) (hsmall : ρ+R≤4*R) : + Touch A SA SB v hv b c i := by + obtain ⟨ha,w,hw,r,hr⟩ := (group A SA SB v hv i).domain_near positive C hC z.column z.height hd + obtain ⟨s,_,hs⟩ := x.exists_shortest isClosed_univ z + obtain ⟨t,ht⟩ := s.restrict_of_length x.height z.height x.height ρ + (group_touched_envelope A SA SB v hv x hρ hp i positive C hz hd) (by simpa [hs] using hz) + obtain ⟨u,hu,he⟩ := (SurvivingGroups.seed_mem + (localSeeds A SA SB v hv (phaseD := phaseD) (phaseG := phaseG) i.1) i.2).mp hw + subst w + refine ⟨?_,u,hu,(t.cast hc.symm rfl).append r,?_⟩ + · rw [hH] + exact group_touched_envelope A SA SB v hv x hρ hp i positive C hz hd _ (by simpa using hρ) + · have ht' : (t.cast hc.symm rfl).length c.height z.height≤ρ := by + rw [Path.length_cast,hH,ht,hs] + exact hz + exact ((t.cast hc.symm rfl).length_append_le r c.height z.height _).trans (by linarith) +end PlanarL1.Columns.Model.RetainedSelection + +end + + + +section + +namespace PlanarL1.Columns.Model +open MeasureTheory Parameters +open PlanarL1.Interpolation +open scoped NNReal +attribute [local instance] Classical.propDecidable +variable {k : ℕ} {M : Model (k+1)} +namespace Field +lemma ball_variation {J : Set ℝ} {r : Fin (k+1)} {K : ℝ≥0} (F : M.Field J K) + (x z : M.Point Set.univ r) {ρ : ℝ} (hρ : 0≤ρ) + (hJ : ∀ H, |H-x.height|≤ρ → H ∈ J) (hz : dist x z≤ρ) : + ∃ (hx : x.height ∈ J) (hZ : z.height ∈ J), + |F.value x.column ⟨x.height,hx⟩-F.value z.column ⟨z.height,hZ⟩|≤(K:ℝ)*ρ := by + have hx := hJ x.height (by simpa using hρ) + have hZ := hJ z.height (by rw [abs_sub_comm]; exact (x.height_change_le z).trans hz) + obtain ⟨p,_,hp⟩ := x.exists_shortest isClosed_univ z + obtain ⟨q,hq⟩ := p.restrict_of_length x.height z.height x.height ρ hJ (by simpa [hp] using hz) + refine ⟨hx,hZ,(F.path_bound q ⟨x.height,hx⟩ ⟨z.height,hZ⟩).trans ?_⟩ + rw [hq,hp] + exact mul_le_mul_of_nonneg_left hz (NNReal.coe_nonneg K) +end Field +namespace BState.SecondaryStep +variable {κ : ℝ} {lam : ℝ≥0} {Ω : Type*} [MeasurableSpace Ω] {μ : Measure Ω} + {S : BState M κ lam Ω μ} {J : Set ℝ} {root r : Fin (k+1)} +variable (U : SecondaryStep S J root) + +lemma point_dist (x z : M.Point Set.univ r) {ρ : ℝ} + (hJ : ∀ H, |H-x.height|≤ρ → H ∈ J) (hz : dist x z≤ρ) + (hx : x.height ∈ SecondaryCell.domain U.seeds U.radius x.column) + (hZ : z.height ∈ SecondaryCell.domain U.seeds U.radius z.column) : + dist (SecondaryCell.point U.seeds U.radius _ _ hx) (SecondaryCell.point U.seeds U.radius _ _ hZ)=dist x z := by + obtain ⟨z',hc,hH,hd⟩ := Point.local_point x z (SecondaryCell.point _ _ _ _ hx) + (SecondaryCell.point_column _ _ _) (SecondaryCell.point_height _ _ _) isClosed_univ + (Set.subset_univ _) hJ hz + have he : z'=SecondaryCell.point U.seeds U.radius _ _ hZ := Point.eq_of_coordinates _ _ + (hc.trans (SecondaryCell.point_column _ _ _).symm) (hH.trans (SecondaryCell.point_height _ _ _).symm) + rwa [he] at hd + +/-- Crossing the domain anywhere on the ambient small ball makes this actual +proposal identically old on that ball. Intrinsic paths are derived by height +padding, rather than silently identified with ambient paths. -/ +lemma fullNamed_boundary_global (x y z : M.Point Set.univ r) {ρ : ℝ} (hρ : 0≤ρ) + (hJ : ∀ H, |H-x.height|≤ρ → H ∈ J) + (hsmall : 18*ρ≤(199/1000:ℝ)*U.radius) (hy : dist x y≤ρ) + (hout : y.height ∉ SecondaryCell.domain U.seeds U.radius y.column) + (hz : dist x z≤ρ) (hZ : z.height ∈ U.data.band) : + U.fullNamed z.column ⟨z.height,hZ⟩=⟨0,U.comparison.value z.column ⟨z.height,hZ⟩⟩ := by + by_cases hd : z.height ∈ SecondaryCell.domain U.seeds U.radius z.column + · let zp := SecondaryCell.point U.seeds U.radius _ _ hd + obtain ⟨xp,hxc,hxh⟩ := Point.local_center x z zp + (SecondaryCell.point_column _ _ _) (SecondaryCell.point_height _ _ _) hρ hJ hz + obtain ⟨yp,hyc,hyh,hdy⟩ := Point.local_point x y xp hxc hxh isClosed_univ (Set.subset_univ _) hJ hy + obtain ⟨zz,hzc,hzh,hdz⟩ := Point.local_point x z xp hxc hxh isClosed_univ (Set.subset_univ _) hJ hz + have hout' : yp.height ∉ SecondaryCell.domain U.seeds U.radius yp.column := by rwa [hyc,hyh] + have he := U.fullNamed_boundary_ball xp yp hsmall (hdy.le.trans hy) hout' zz (hdz.le.trans hz) + have hzz : zz.column=z.column := hzc + have hZZ : zz.height=z.height := hzh + simpa only [hzz,hZZ,old] using he + · rw [fullNamed,dite_eq_right hd] +end BState.SecondaryStep +end PlanarL1.Columns.Model + +end + + + +section + +namespace PlanarL1.Parameters +open scoped NNReal +noncomputable def secondaryK : ℝ≥0 := max 5 ⟨3/(9*a₂/100),by norm_num [a₂]⟩ +noncomputable def secondaryQ : ℝ := zetaB*(EB/8)/20 +noncomputable def secondaryRadius : ℝ := zetaB*(EB/8)/1000 +noncomputable def secondaryN : ℕ := 6*(⌈15/zetaB⌉₊+3+1)+3 +noncomputable def secondaryTestLoss (ρ : ℝ) (m : ℕ) : ℝ := + (4*(secondaryK:ℝ)*ρ+secondaryQ/m)/secondaryQ+(4*(secondaryK:ℝ)*ρ+EB/m)/EB +lemma secondaryTestLoss_nonneg {ρ : ℝ} (hρ : 0 ≤ ρ) (m : ℕ) : 0 ≤ secondaryTestLoss ρ m := by + unfold secondaryTestLoss + positivity [show 0 < secondaryQ by norm_num [secondaryQ,zetaB,EB,R],interpolationB.1] +end PlanarL1.Parameters + +namespace PlanarL1.Columns.Model.SecondaryGeometry.Group +open Parameters MeasureTheory PlanarL1.Interpolation +open scoped NNReal +attribute [local instance] Classical.propDecidable +variable {k : ℕ} {M : Model (k+1)} {Ω : Type*} [MeasurableSpace Ω] {μ : Measure Ω} +variable {A : Ambient M} {S : BState M kappaB lam Ω μ} +variable (G : SecondaryGeometry.Group A S) (positive : Bool) (C : G.Component) +variable (hC : (G.admittedSeeds positive C).Nonempty) {m : ℕ} (hm : 0 < m) +abbrev Offset := Point.RadialTree.GridSample (n := k+1) (G.tree C).depthCap m × Fin (m+1) × Fin (m+1) +noncomputable def sampledStep (w : Offset G C (m := m)) := + G.step positive C hC ((G.tree C).gridNoise _ m w.1) ((G.tree C).gridNoise_bounds _ _ hm w.1) + (EB/m*w.2.1.val) (EB/m*w.2.2.val) (offset_bound hm _) (offset_bound hm _) + +variable (x : M.Point Set.univ A.root) {ρ : ℝ} (hρ : 0 ≤ ρ) +abbrev Ball := {z : M.Point Set.univ A.root // dist x z ≤ ρ} +noncomputable def ballCenter : Ball x (ρ := ρ) := ⟨x,by simpa using hρ⟩ +variable (hBand : ∀ z : Ball x (ρ := ρ), z.val.height∈G.data.band) +noncomputable def oldOnBall (z : Ball x (ρ := ρ)) : ℝ := + (G.comparison positive).value z.val.column ⟨z.val.height,hBand z⟩ +noncomputable def sampledOnBall (w : Offset G C (m := m)) (z : Ball x (ρ := ρ)) : NamedValue := + (G.sampledStep positive C hC hm w).fullNamed z.val.column ⟨z.val.height,hBand z⟩ + +lemma sampledStep_seeds (w : Offset G C (m := m)) : + (G.sampledStep positive C hC hm w).seeds=G.admittedSeeds positive C := rfl +lemma sampledStep_radius (w : Offset G C (m := m)) : + (G.sampledStep positive C hC hm w).radius=R := rfl + +lemma component_local_list + (hsmall : 18*ρ ≤ (199/1000:ℝ)*R) (hr : ρ ≤ secondaryRadius) + (hOld : ∀ z, |G.oldOnBall positive x hBand (ballCenter x hρ)-G.oldOnBall positive x hBand z| ≤ (secondaryK:ℝ)*ρ) + (hEnv : (∃ z : Ball x (ρ := ρ), z.val.height∈SecondaryCell.domain (G.admittedSeeds positive C) R z.val.column) → + ∀ H, |H-x.height| ≤ ρ → H ∈ BandTrees.band narrow G.lower) : + ∃ L : LocalList (G.oldOnBall positive x hBand) (G.sampledOnBall positive C hC hm x hBand) + (ballCenter x hρ) ((secondaryK:ℝ)*ρ) (secondaryTestLoss ρ m), + L.names.card ≤ secondaryN ∧ + ((¬∀ z : Ball x (ρ := ρ), z.val.height∈SecondaryCell.domain (G.admittedSeeds positive C) R z.val.column) → L.names={0}) := by + classical + by_cases hfull : ∀ z : Ball x (ρ := ρ), z.val.height∈SecondaryCell.domain (G.admittedSeeds positive C) R z.val.column + · let lift := fun z : Ball x (ρ := ρ) => SecondaryCell.point _ _ _ _ (hfull z) + let w0 : Offset G C (m := m) := Classical.arbitrary _ + let U := G.sampledStep positive C hC hm w0 + have hJ := hEnv ⟨ballCenter x hρ,hfull _⟩ + have hdist z : dist (lift (ballCenter x hρ)) (lift z) ≤ ρ := by + have he := U.point_dist x z.val hJ z.property (hfull (ballCenter x hρ)) (hfull z) + exact he.le.trans z.property + have hrad : ρ ≤ U.tree.radius := hr + have hex := SecondaryCell.sampled_local_list U.tree U.seeds U.old U.supportValue lift + (ballCenter x hρ) hρ hrad hdist U.data.isOrdinary U.old_lipschitz U.support_lipschitz U.zeta_eq + U.pc U.radius U.lo EB interpolationB.1 m hm + have ho : (fun z => U.old (lift z))=G.oldOnBall positive x hBand := by + funext z + simp only [BState.SecondaryStep.old,lift,SecondaryCell.point_column,SecondaryCell.point_height] + rfl + have hf : (fun (w : Offset G C (m := m)) z => + SecondaryCell.namedReplacement U.tree U.seeds U.old U.supportValue U.data.isOrdinary U.pc U.radius + (EB/m*w.2.1.val) (EB/m*w.2.2.val) U.lo (U.tree.gridNoise U.tree.depthCap m w.1) (lift z))= + G.sampledOnBall positive C hC hm x hBand := by + funext w z + unfold sampledOnBall BState.SecondaryStep.fullNamed + split + · rfl + · rename_i hn + exact False.elim (hn (hfull z)) + have heK : SecondaryCell.replacementConstant U.tree=secondaryK := rfl + have heQ : U.tree.q=secondaryQ := rfl + erw [ho,hf,heK,heQ] at hex + obtain ⟨L,hh⟩ := hex + exact ⟨L,hh,fun hn => False.elim (hn hfull)⟩ + · have he : G.sampledOnBall positive C hC hm x hBand=fun (_ : Offset G C (m := m)) z => + ⟨0,G.oldOnBall positive x hBand z⟩ := by + funext w z + obtain ⟨y,hy⟩ := not_forall.mp hfull + by_cases hz : z.val.height∈SecondaryCell.domain (G.admittedSeeds positive C) R z.val.column + · exact (G.sampledStep positive C hC hm w).fullNamed_boundary_global x y.val z.val hρ + (hEnv ⟨z,hz⟩) hsmall y.property hy z.property (hBand z) + · unfold sampledOnBall BState.SecondaryStep.fullNamed + split + · exact False.elim (hz ‹_›) + · rfl + rw [he] + refine ⟨oldLocalList (G.oldOnBall positive x hBand) (ballCenter x hρ) hOld,?_,fun _ => rfl⟩ + change ({0} : Finset ℕ).card ≤ secondaryN + simp only [Finset.card_singleton] + unfold secondaryN + omega +end PlanarL1.Columns.Model.SecondaryGeometry.Group + +end + + + +section + +namespace PlanarL1.Interpolation +noncomputable def scaleNamed (c : ℝ) (a : NamedValue) : NamedValue := ⟨a.name,c*a.value⟩ +lemma maxNamed_scale {c : ℝ} (hc : 0 rfl +lemma maxSelection_scale {X : Type*} {c : ℝ} (hc : 0 scaleNamed c (old z)) + (Fs.map (fun F z => scaleNamed c (F z))) x=scaleNamed c (maxSelection old Fs x) := by + induction Fs with + | nil => rfl + | cons F Fs ih => simpa only [List.map_cons,maxSelection,ih] using maxNamed_scale hc _ _ +lemma familySelection_scale {X : Type*} {k : ℕ} {c : ℝ} (hc : 0 c*old z) (fun g z => scaleNamed c (F g z)) x= + scaleNamed c (familySelection old F x) := by + unfold familySelection + rw [←maxSelection_scale hc] + congr 2 + rw [List.map_ofFn] + rfl +end PlanarL1.Interpolation + +end + + + +section + +namespace PlanarL1.Columns.Model.SecondaryGeometry +open MeasureTheory Parameters PlanarL1.Interpolation +attribute [local instance] Classical.propDecidable +variable {k : ℕ} {M : Model (k+1)} {Ω : Type*} [MeasurableSpace Ω] {μ : Measure Ω} +variable {A : Ambient M} {S : BState M kappaB Group.lam Ω μ} +variable {I : Type*} [Fintype I] (G : I → Group A S) +abbrev Coordinate := Σ i, (G i).Component +abbrev Offsets (m : ℕ) := ∀ u : Coordinate G, ComponentSample G u.1 u.2 m +noncomputable instance : Fintype (Coordinate G) := Fintype.ofFinite _ +variable (o : Fin (S.count+1) → Bool) (c : I → Bool) {m : ℕ} +noncomputable def flatSample (w : Offsets G m) : Sample G m := (o,c,fun i C => w ⟨i,C⟩) +noncomputable def fixedSample : Sample G m := flatSample G o c (Classical.arbitrary _) +noncomputable def slot (a : Fin (S.count+1)) (j : Fin (Fintype.card (Acting G (fixedSample G o c (m := m)) a))) : + Acting G (fixedSample G o c (m := m)) a := (Fintype.equivFin _).symm j +noncomputable def coord (a : Fin (S.count+1)) (j : Fin (Fintype.card (Acting G (fixedSample G o c (m := m)) a))) : + Coordinate G := (slot G o c (m := m) a j).val +lemma coord_injective (a : Fin (S.count+1)) : Function.Injective (coord G o c (m := m) a) := by + intro i j he + apply (Fintype.equivFin (Acting G (fixedSample G o c (m := m)) a)).symm.injective + exact Subtype.ext he + +omit [Fintype I] in +lemma flat_actingStep (hm : 0 < m) (w : Offsets G m) (a : Fin (S.count+1)) + (u : Acting G (fixedSample G o c (m := m)) a) : + actingStep G hm (flatSample G o c w) a u= + (G u.val.1).sampledStep (o a) u.val.2 u.property.2.2 hm (w u.val) := rfl + +lemma coord_index (a : Fin (S.count+1)) (j : Fin (Fintype.card (Acting G (fixedSample G o c (m := m)) a))) : + (G (coord G o c (m := m) a j).1).index=a := (slot G o c (m := m) a j).property.1 +lemma slot_band (a : Fin (S.count+1)) (j : Fin (Fintype.card (Acting G (fixedSample G o c (m := m)) a))) + (H : (S.chart a).band) : H.val∈(G (coord G o c (m := m) a j).1).data.band := by + change H.val∈(S.chart (G (coord G o c (m := m) a j).1).index).band + rw [coord_index] + exact H.property + +lemma selected_flat (hm : 0 < m) (w : Offsets G m) (a : Fin (S.count+1)) + (i : Fin (k+1)) (H : (S.chart a).band) : + ((batch G hm (flatSample G o c w) a).selected i H).name= + (familySelection (fun T : (S.chart a).band => ((S.chart a).comparison Group.lam Group.lam_bound (o a)).value i T) + (fun j T => ((G (coord G o c (m := m) a j).1).sampledStep (o a) (coord G o c (m := m) a j).2 + (slot G o c (m := m) a j).property.2.2 hm (w (coord G o c (m := m) a j))).fullNamed i + ⟨T.val,slot_band G o c (m := m) a j T⟩) H).name := by + change (familySelection (fun T : (S.chart a).band => kappaB*((S.chart a).comparison Group.lam Group.lam_bound (o a)).value i T) + (fun j T => scaleNamed kappaB (((G (coord G o c (m := m) a j).1).sampledStep (o a) (coord G o c (m := m) a j).2 + (slot G o c (m := m) a j).property.2.2 hm (w (coord G o c (m := m) a j))).fullNamed i + ⟨T.val,slot_band G o c (m := m) a j T⟩)) H).name=_ + rw [familySelection_scale (by norm_num [kappaB,a₂])] + rfl +end PlanarL1.Columns.Model.SecondaryGeometry + +end + + + +section + +namespace PlanarL1.Interpolation +lemma maxSelection_map {X Y : Type*} (old : Y → NamedValue) + (Fs : List (Y → NamedValue)) (f : X → Y) (x : X) : + maxSelection (old ∘ f) (Fs.map (fun F => F ∘ f)) x=maxSelection old Fs (f x) := by + induction Fs with + | nil => rfl + | cons F Fs ih => simp only [List.map_cons,maxSelection,Function.comp_apply,ih] +lemma familySelection_map {X Y : Type*} {k : ℕ} (old : Y → ℝ) + (F : Fin k → Y → NamedValue) (f : X → Y) (x : X) : + familySelection (old ∘ f) (fun g => F g ∘ f) x=familySelection old F (f x) := by + unfold familySelection + rw [←maxSelection_map _ _ f x,List.map_ofFn] + rfl +lemma maxSelection_eq_fold {X : Type*} (old : X → NamedValue) + (Fs : List (X → NamedValue)) (x : X) : + maxSelection old Fs x=(Fs.map (fun F => F x)).foldr maxNamed (old x) := by + induction Fs with + | nil => rfl + | cons F Fs ih => simpa only [maxSelection,List.map_cons,List.foldr_cons] using congrArg (maxNamed (F x)) ih +lemma familySelection_congr_at {X Y : Type*} {k : ℕ} (old : X → ℝ) (old' : Y → ℝ) + (F : Fin k → X → NamedValue) (F' : Fin k → Y → NamedValue) + (x : X) (y : Y) (ho : old x=old' y) (hF : ∀ g, F g x=F' g y) : + familySelection old F x=familySelection old' F' y := by + simp only [familySelection,maxSelection_eq_fold,List.map_ofFn,ho] + congr 2 + funext g + dsimp only [Function.comp_apply] + rw [hF g] +end PlanarL1.Interpolation + +end + + + +section + +namespace PlanarL1.Columns.Model.SecondaryGeometry +open MeasureTheory Parameters PlanarL1.Interpolation FiniteRandom +attribute [local instance] Classical.propDecidable +attribute [local irreducible] FiniteRandom.prob +variable {k : ℕ} {M : Model (k+1)} {Ω : Type*} [MeasurableSpace Ω] {μ : Measure Ω} +variable {A : Ambient M} {S : BState M kappaB Group.lam Ω μ} +variable {I : Type*} [Fintype I] (G : I → Group A S) +variable (o : Fin (S.count+1) → Bool) (c : I → Bool) {m : ℕ} +variable (a : Fin (S.count+1)) (x : M.Point Set.univ A.root) {ρ : ℝ} +abbrev Slot := Fin (Fintype.card (Acting G (fixedSample G o c (m := m)) a)) +variable (hBand : ∀ z : Group.Ball x (ρ := ρ), z.val.height∈(S.chart a).band) +noncomputable def ballOld (z : Group.Ball x (ρ := ρ)) : ℝ := + ((S.chart a).comparison Group.lam Group.lam_bound (o a)).value z.val.column ⟨z.val.height,hBand z⟩ +include hBand in +lemma ball_slot_band (j : Slot G o c a (m := m)) (z : Group.Ball x (ρ := ρ)) : + z.val.height∈(G (coord G o c (m := m) a j).1).data.band := + slot_band G o c (m := m) a j ⟨z.val.height,hBand z⟩ +noncomputable def ballFamily (hm : 0 < m) (j : Slot G o c a (m := m)) + (w : ComponentSample G (coord G o c (m := m) a j).1 (coord G o c (m := m) a j).2 m) (z : Group.Ball x (ρ := ρ)) : NamedValue := + (G (coord G o c (m := m) a j).1).sampledOnBall (o a) (coord G o c (m := m) a j).2 + (slot G o c (m := m) a j).property.2.2 hm x (ball_slot_band G o c (m := m) a x hBand j) w z +lemma ballOld_eq (j : Slot G o c a (m := m)) : + (G (coord G o c (m := m) a j).1).oldOnBall (o a) x (ball_slot_band G o c (m := m) a x hBand j)=ballOld o a x hBand := by + funext z + unfold Group.oldOnBall Group.comparison ballOld + simp only [Group.data] + have heval (b : Fin (S.count+1)) (hb : z.val.height∈(S.chart b).band) (he : b=a) : + ((S.chart b).comparison Group.lam Group.lam_bound (o a)).value z.val.column ⟨z.val.height,hb⟩ = + ((S.chart a).comparison Group.lam Group.lam_bound (o a)).value z.val.column ⟨z.val.height,hBand z⟩ := by + subst b + rfl + exact heval _ _ (coord_index G o c (m := m) a j) +lemma selected_ball (hm : 0 < m) (w : Offsets G m) (z : Group.Ball x (ρ := ρ)) : + ((batch G hm (flatSample G o c w) a).selected z.val.column ⟨z.val.height,hBand z⟩).name= + (familySelection (ballOld o a x hBand) (fun j => ballFamily G o c a x hBand hm j (w (coord G o c (m := m) a j))) z).name := by + apply (selected_flat G o c hm w a z.val.column ⟨z.val.height,hBand z⟩).trans + apply congrArg NamedValue.name + refine familySelection_congr_at _ _ _ _ _ _ ?_ ?_ + · rfl + · intro j + rfl +noncomputable def wholeBallSlots : Finset (Slot G o c a (m := m)) := Finset.univ.filter fun j => + ∀ z : Group.Ball x (ρ := ρ), z.val.height∈SecondaryCell.domain + ((G (coord G o c (m := m) a j).1).admittedSeeds (o a) (coord G o c (m := m) a j).2) R z.val.column + +lemma persistence_flat [SFinite μ] (hρ : 0 ≤ ρ) (hm : 0 < m) + (hsmall : 18*ρ ≤ (199/1000:ℝ)*R) (hr : ρ ≤ secondaryRadius) + (hOld : ∀ z, |ballOld o a x hBand (Group.ballCenter x hρ)-ballOld o a x hBand z| ≤ (secondaryK:ℝ)*ρ) + (hold : ∀ z : Group.Ball x (ρ := ρ), S.name z.val.column z.val.height=a) + (hEnv : ∀ j : Slot G o c a (m := m), + (∃ z : Group.Ball x (ρ := ρ), z.val.height∈SecondaryCell.domain + ((G (coord G o c (m := m) a j).1).admittedSeeds (o a) (coord G o c (m := m) a j).2) R z.val.column) → + ∀ H, |H-x.height| ≤ ρ → H ∈ BandTrees.band narrow (G (coord G o c (m := m) a j).1).lower) + {B : ℕ} (hpack : (wholeBallSlots G o c a x (ρ := ρ) (m := m)).card ≤ B) : + prob (fun w : Offsets G m => ∃ z : Group.Ball x (ρ := ρ), + (result G hm (flatSample G o c w)).name z.val.column z.val.height≠ + (result G hm (flatSample G o c w)).name x.column x.height) ≤ + (1+B*secondaryN : ℕ)^2*secondaryTestLoss ρ m := by + classical + have hList (j : Slot G o c a (m := m)) : + ∃ L : LocalList (ballOld o a x hBand) (ballFamily G o c a x hBand hm j) + (Group.ballCenter x hρ) ((secondaryK:ℝ)*ρ) (secondaryTestLoss ρ m), + L.names.card ≤ secondaryN ∧ (j∉wholeBallSlots G o c a x (ρ := ρ) (m := m) → L.names={0}) := by + have ho := hOld + rw [←ballOld_eq G o c (m := m) a x hBand j] at ho + have he := (G (coord G o c (m := m) a j).1).component_local_list (o a) (coord G o c (m := m) a j).2 + (slot G o c (m := m) a j).property.2.2 hm x hρ (ball_slot_band G o c (m := m) a x hBand j) + hsmall hr ho (hEnv j) + erw [ballOld_eq G o c (m := m) a x hBand j] at he + obtain ⟨L,hN,hout⟩ := he + exact ⟨L,hN,fun hn => hout (by simpa only [wholeBallSlots,Finset.mem_filter,Finset.mem_univ,true_and] using hn)⟩ + choose L hN hout using hList + have hprob := LocalList.family_probability (D := fun u : Coordinate G => ComponentSample G u.1 u.2 m) + (coord G o c (m := m) a) (coord_injective G o c (m := m) a) (ballOld o a x hBand) + (ballFamily G o c a x hBand hm) (Group.ballCenter x hρ) (secondaryTestLoss_nonneg hρ m) hOld L + (wholeBallSlots G o c a x (ρ := ρ) (m := m)) (fun j _ => hN j) + (fun j hj => (hout j hj).le) hpack + apply (prob_mono (Q := fun w : Offsets G m => ∃ z : Group.Ball x (ρ := ρ), + (familySelection (ballOld o a x hBand) (fun j => ballFamily G o c a x hBand hm j (w (coord G o c (m := m) a j))) z).name≠ + (familySelection (ballOld o a x hBand) (fun j => ballFamily G o c a x hBand hm j (w (coord G o c (m := m) a j))) (Group.ballCenter x hρ)).name) ?_).trans hprob + rintro w ⟨z,hz⟩ + refine ⟨z,fun he => hz ?_⟩ + apply (layer G hm (flatSample G o c w)).name_eq_of_selected a (hBand z) (hBand (Group.ballCenter x hρ)) + (hold z) (hold (Group.ballCenter x hρ)) + exact (selected_ball G o c a x hBand hm w z).trans + (he.trans (selected_ball G o c a x hBand hm w (Group.ballCenter x hρ)).symm) +end PlanarL1.Columns.Model.SecondaryGeometry + +end + + + +section + +namespace PlanarL1.Columns.Model.SecondaryGeometry.Group +open Parameters +attribute [local instance] Classical.propDecidable +variable {k : ℕ} {M : Model (k+1)} {Ω : Type*} [MeasurableSpace Ω] + {μ : MeasureTheory.Measure Ω} {A : Ambient M} + {S : BState M kappaB lam Ω μ} (G : SecondaryGeometry.Group A S) +lemma component_eq_of_domain (positive : Bool) (C D : G.Component) (i : Fin (k+1)) (H : ℝ) + (hC : H ∈ SecondaryCell.domain (G.admittedSeeds positive C) R i) + (hD : H ∈ SecondaryCell.domain (G.admittedSeeds positive D) R i) : C=D := by + let x := SecondaryCell.point _ _ _ _ hC + let y := SecondaryCell.point _ _ _ _ hD + have hc : x.column=i := SecondaryCell.point_column _ _ _ + have hd : y.column=i := SecondaryCell.point_column _ _ _ + have h1 := BandTrees.reachable_mem M narrow G.lower C x.reachable + have h2 := BandTrees.reachable_mem M narrow G.lower D y.reachable + rw [hc] at h1 + rw [hd] at h2 + exact ((SimpleGraph.ConnectedComponent.mem_supp_iff C i).mp h1).symm.trans + ((SimpleGraph.ConnectedComponent.mem_supp_iff D i).mp h2) +end PlanarL1.Columns.Model.SecondaryGeometry.Group + +namespace PlanarL1.Columns.Model.RetainedSelection +open Parameters MeasureTheory SecondaryGeometry +attribute [local instance] Classical.propDecidable +variable {k : ℕ} {M : Model (k+1)} {V Ω Ξ : Type*} +variable [Fintype V] [MeasurableSpace Ω] [MeasurableSpace Ξ] +variable {μ : Measure Ω} {ν : Measure Ξ} +variable (A : Ambient M) (SA : OrdinaryState M kappaA Ω μ) +variable (SB : BState M kappaB SecondaryGeometry.Group.lam Ξ ν) +variable (v : V → M.Point Set.univ A.root) +variable {L U : ℝ} (hv : ∀ x, (v x).height ∈ Set.Icc L U) +variable {q p : ℝ} {phaseD phaseG : MainFamily.BandComponent (M := M) q L U → ℝ} +variable (b : Block (M := M) q p L U) +variable (c : M.Point (BandTrees.band broad b.lower) (BandTrees.root M broad b.lower b.1.2)) +variable (hc : c.height ∈ BandTrees.band narrow b.lower₂) +variable {ρ τ : ℝ} (hρ : 0≤ρ) (hτ : 0≤τ) +variable (hp : Tiling.Padded a₁ q c.height ρ) (hn : Tiling.Padded a₂ p c.height τ) +variable {m : ℕ} (omega : Sample (group A SA SB v hv (p := p) (phaseD := phaseD) (phaseG := phaseG)) m) +variable (a : Fin (SB.count+1)) + +noncomputable def centerActs : Finset (Acting (group A SA SB v hv) omega a) := + Finset.univ.filter fun u => c.height ∈ SecondaryCell.domain + ((group A SA SB v hv u.val.1).admittedSeeds (omega.1 a) u.val.2) R c.column + +include hc hρ hτ hp hn in +lemma centerActs_card : (centerActs A SA SB v hv b c omega a).card≤SurvivingGroups.packBound := by + let f : (centerActs A SA SB v hv b c omega a) → Hits A SA SB v hv b c + (phaseD := phaseD) (phaseG := phaseG) := fun u => + ⟨u.val.val.1, domain_touch A SA SB v hv b c _ (omega.1 a) _ u.val.property.2.2 + (Finset.mem_filter.mp u.property).2⟩ + have hf : Function.Injective f := by + intro u w he + have hi := congrArg Subtype.val he + change u.val.val.1=w.val.val.1 at hi + apply Subtype.ext + apply Subtype.ext + apply Sigma.ext hi + cases u with | mk u hu => + cases w with | mk w hw => + cases u with | mk u hu' => + cases w with | mk w hw' => + cases u with | mk i C => + cases w with | mk j D => + dsimp only at hi + subst j + apply heq_of_eq + exact (group A SA SB v hv i).component_eq_of_domain (omega.1 a) C D c.column c.height + (Finset.mem_filter.mp hu).2 (Finset.mem_filter.mp hw).2 + have he := Fintype.card_le_of_injective f hf + rw [Fintype.card_coe] at he + exact he.trans (touching_card_small A SA SB v hv b c hc hρ hτ hp hn) +end PlanarL1.Columns.Model.RetainedSelection + +end + + + +section + +namespace PlanarL1.Columns.Model.RetainedSelection +open Parameters MeasureTheory SecondaryGeometry +attribute [local instance] Classical.propDecidable +variable {k : ℕ} {M : Model (k+1)} {V Ω Ξ : Type*} +variable [Fintype V] [MeasurableSpace Ω] [MeasurableSpace Ξ] +variable {μ : Measure Ω} {ν : Measure Ξ} +variable (A : Ambient M) (SA : OrdinaryState M kappaA Ω μ) +variable (SB : BState M kappaB SecondaryGeometry.Group.lam Ξ ν) +variable (v : V → M.Point Set.univ A.root) +variable {L U : ℝ} (hv : ∀ x, (v x).height ∈ Set.Icc L U) +variable {q p : ℝ} {phaseD phaseG : MainFamily.BandComponent (M := M) q L U → ℝ} +variable (x : M.Point Set.univ A.root) + +lemma center_point_of_domain + (i : GroupIndex A SA SB v hv (p := p) (phaseD := phaseD) (phaseG := phaseG)) + (positive : Bool) (C : (group A SA SB v hv i).Component) + (hC : ((group A SA SB v hv i).admittedSeeds positive C).Nonempty) + (hd : x.height∈SecondaryCell.domain ((group A SA SB v hv i).admittedSeeds positive C) R x.column) : + ∃ z : M.Point (BandTrees.band broad i.1.lower) (BandTrees.root M broad i.1.lower i.1.1.2), + z.column=x.column ∧ z.height=x.height ∧ z.height∈BandTrees.band narrow i.1.lower₂ := by + obtain ⟨hH,w,_,path,_⟩ := (group A SA SB v hv i).domain_near positive C hC x.column x.height hd + refine ⟨{ column := x.column + height := x.height + inBand := i.1.sub hH + reachable := w.reachable.trans (path.widen i.1.sub).word.reachable.symm }, rfl,rfl,hH⟩ + +lemma wholeBallSlots_card (o : Fin (SB.count+1) → Bool) + (coins : GroupIndex A SA SB v hv (p := p) (phaseD := phaseD) (phaseG := phaseG) → Bool) + (a : Fin (SB.count+1)) {m : ℕ} {ρ : ℝ} (hρ : 0 ≤ ρ) + (hp : Tiling.Padded a₁ q x.height ρ) (hn : Tiling.Padded a₂ p x.height ρ) : + (wholeBallSlots (group A SA SB v hv) o coins a x (ρ := ρ) (m := m)).card ≤ SurvivingGroups.packBound := by + classical + let G := group A SA SB v hv (p := p) (phaseD := phaseD) (phaseG := phaseG) + let T := wholeBallSlots G o coins a x (ρ := ρ) (m := m) + by_cases he : T.Nonempty + · obtain ⟨j,hj⟩ := he + have hd := (Finset.mem_filter.mp hj).2 (Group.ballCenter x hρ) + obtain ⟨z,hzc,hzh,hzband⟩ := center_point_of_domain A SA SB v hv x (coord G o coins (m := m) a j).1 + (o a) (coord G o coins (m := m) a j).2 (slot G o coins (m := m) a j).property.2.2 hd + let b := (coord G o coins (m := m) a j).1.1 + let omega := fixedSample G o coins (m := m) + let f : T → centerActs A SA SB v hv b z omega a := fun t => + ⟨slot G o coins (m := m) a t.val,Finset.mem_filter.mpr ⟨Finset.mem_univ _,by + change z.height∈SecondaryCell.domain + ((G (coord G o coins (m := m) a t.val).1).admittedSeeds (o a) (coord G o coins (m := m) a t.val).2) R z.column + rw [hzc,hzh] + exact (Finset.mem_filter.mp t.property).2 (Group.ballCenter x hρ)⟩⟩ + have hf : Function.Injective f := by + intro s t he + apply Subtype.ext + exact (Fintype.equivFin (Acting G omega a)).symm.injective (congrArg Subtype.val he) + have hh := Fintype.card_le_of_injective f hf + rw [Fintype.card_coe,Fintype.card_coe] at hh + exact hh.trans (centerActs_card A SA SB v hv b z hzband hρ hρ + (by simpa only [hzh] using hp) (by simpa only [hzh] using hn) omega a) + · exact (Finset.card_eq_zero.mpr (Finset.not_nonempty_iff_eq_empty.mp he)).le.trans (Nat.zero_le _) +end PlanarL1.Columns.Model.RetainedSelection + +end + + + +section + +namespace PlanarL1.Parameters +open scoped NNReal +noncomputable def mainK : ℝ≥0 := max 1 ⟨3/(9*a₁/100),by norm_num [a₁]⟩ +noncomputable def mainQ : ℝ := zetaA*(EA/8)/20 +noncomputable def mainRadius : ℝ := zetaA*(EA/8)/1000 +noncomputable def mainN : ℕ := 6*(⌈15/zetaA⌉₊+3+1)+2 +noncomputable def mainTestLoss (ρ : ℝ) (m : ℕ) : ℝ := + (4*(mainK:ℝ)*ρ+mainQ/m)/mainQ+(4*(mainK:ℝ)*ρ+EA/m)/EA +noncomputable def mainLoss (ρ : ℝ) (m : ℕ) : ℝ := (mainN:ℝ)^2*mainTestLoss ρ m +noncomputable def secondaryLoss (ρ : ℝ) (m : ℕ) : ℝ := + (1+Columns.Model.SurvivingGroups.packBound*secondaryN : ℕ)^2*secondaryTestLoss ρ m +lemma mainQ_pos : 0 < mainQ := by norm_num [mainQ,zetaA,EA,epsilon] +lemma mainRadius_pos : 0 < mainRadius := by norm_num [mainRadius,zetaA,EA,epsilon] +lemma secondaryQ_pos : 0 < secondaryQ := by norm_num [secondaryQ,zetaB,EB,R] +lemma secondaryRadius_pos : 0 < secondaryRadius := by norm_num [secondaryRadius,zetaB,EB,R] +noncomputable def persistenceRadius : ℝ := + min (EA/20) (min mainRadius (min ((199/18000:ℝ)*R) secondaryRadius)) +lemma persistenceRadius_pos : 0 < persistenceRadius := by + exact lt_min (div_pos interpolationA.1 (by norm_num)) + (lt_min mainRadius_pos (lt_min (by norm_num [R]) secondaryRadius_pos)) +lemma persistence_main_small {ρ : ℝ} (h : ρ≤persistenceRadius) : 4*ρ<3*EA := by + have h' := h.trans (min_le_left _ _) + have hE := interpolationA.1 + linarith +lemma persistence_main_radius {ρ : ℝ} (h : ρ≤persistenceRadius) : ρ ≤ mainRadius := + h.trans (le_trans (min_le_right (EA/20) _) (min_le_left mainRadius _)) +lemma persistence_secondary_small {ρ : ℝ} (h : ρ≤persistenceRadius) : 18*ρ≤(199/1000:ℝ)*R := by + have h' := h.trans (le_trans (min_le_right (EA/20) _) (le_trans (min_le_right mainRadius _) (min_le_left ((199/18000:ℝ)*R) _))) + linarith +lemma persistence_secondary_radius {ρ : ℝ} (h : ρ≤persistenceRadius) : ρ ≤ secondaryRadius := + h.trans (le_trans (min_le_right (EA/20) _) (le_trans (min_le_right mainRadius _) (min_le_right ((199/18000:ℝ)*R) _))) +end PlanarL1.Parameters + +namespace PlanarL1.Columns.Model.MainFamily +open Parameters MeasureTheory +variable {k : ℕ} {M : Model (k+1)} {q L U : ℝ} +variable (phase : BandComponent (M := M) q L U → ℝ) +lemma localLoss_eq (c : CellIndex q L U phase) (ρ : ℝ) (m : ℕ) : + localLoss phase c ρ m=mainLoss ρ m := rfl +lemma radius_eq (c : CellIndex q L U phase) : (tree phase c).radius=mainRadius := rfl +end PlanarL1.Columns.Model.MainFamily + +end + +end OAI diff --git a/lean/OAI/Combinatorics/PlanarL1/Fields.lean b/lean/OAI/Combinatorics/PlanarL1/Fields.lean new file mode 100644 index 0000000000000000000000000000000000000000..c68108eb92a9d4b09abaa37c128ffb19fbc8acb7 --- /dev/null +++ b/lean/OAI/Combinatorics/PlanarL1/Fields.lean @@ -0,0 +1,611 @@ +import OAI.Combinatorics.PlanarL1.Distance + +namespace OAI + +section + +namespace PlanarL1 +namespace Columns +namespace Model + +variable {n : ℕ} (M : Model n) +/-- A scalar field on the whole band, including all its components. Its only +compatibility condition is equality at actual allowed switch heights. -/ +structure Field (J : Set ℝ) (L : NNReal) where + value : Fin n → J → ℝ + vertical : ∀ i, LipschitzWith L (value i) + switch : ∀ i j (H : J), H.val ∈ M.heights i j → value i H = value j H + +namespace Field + +variable {M} {J : Set ℝ} {L : NNReal} + +lemma path_bound (F : M.Field J L) {i j : Fin n} (p : M.Path J i j) + (a b : J) : |F.value i a - F.value j b| ≤ L * p.length a.val b.val := by + induction p generalizing a b with + | nil i => + simpa only [Path.length, Real.dist_eq, Subtype.dist_eq] using (F.vertical i).dist_le_mul a b + | @cons i j k H hH hs p ih => + have ht := abs_sub_le (F.value i a) (F.value i ⟨H,hH⟩) (F.value k b) + rw [F.switch i j ⟨H,hH⟩ hs] at ht + have hv := (F.vertical i).dist_le_mul a ⟨H,hH⟩ + rw [Real.dist_eq, Subtype.dist_eq, Real.dist_eq, F.switch i j ⟨H,hH⟩ hs] at hv + have hi := ih ⟨H,hH⟩ b + change _ ≤ L * (|a.val - H| + p.length H b.val) + nlinarith + +/-- Vertical Lipschitz bounds and switch equality imply the intrinsic bound, +by summing on an actual attaining shortest path. -/ +lemma lipschitz (F : M.Field J L) (hJ : IsClosed J) (root : Fin n) : + LipschitzWith L (fun x : M.Point J root => F.value x.column ⟨x.height,x.inBand⟩) := by + apply LipschitzWith.of_dist_le_mul + intro x y + obtain ⟨p, _, hp⟩ := x.exists_shortest hJ y + rw [Real.dist_eq] + simpa only [hp] using F.path_bound p ⟨x.height,x.inBand⟩ ⟨y.height,y.inBand⟩ + +end Field + +namespace Point + +variable {M} {J : Set ℝ} {root : Fin n} + +/-- Truncated point distance on EVERY column. Columns outside the metric +component have the constant ceiling. -/ +noncomputable def truncated (o : M.Point J root) (D : ℝ) (i : Fin n) (H : J) : ℝ := by + classical + exact if hi : (M.activeGraph J).Reachable root i then + min (dist o (⟨i,H.val,H.property,hi⟩ : M.Point J root)) D else D + +lemma truncated_of_reachable (o : M.Point J root) (D : ℝ) (i : Fin n) (H : J) + (hi : (M.activeGraph J).Reachable root i) : + o.truncated D i H = min (dist o (⟨i,H.val,H.property,hi⟩ : M.Point J root)) D := by + simp only [truncated, dite_eq_left hi] + +lemma truncated_le (o : M.Point J root) (D : ℝ) (i : Fin n) (H : J) : + o.truncated D i H ≤ D := by + unfold truncated + split + · exact min_le_right _ _ + · exact le_rfl + +lemma truncated_vertical (o : M.Point J root) (D : ℝ) (i : Fin n) : + LipschitzWith 1 (o.truncated D i) := by + by_cases hi : (M.activeGraph J).Reachable root i + · have hp : LipschitzWith 1 (fun H : J => (⟨i,H.val,H.property,hi⟩ : M.Point J root)) := by + apply LipschitzWith.of_dist_le_mul + intro x y + rw [Point.dist_same_column (⟨i,x.val,x.property,hi⟩ : M.Point J root) + (⟨i,y.val,y.property,hi⟩ : M.Point J root) rfl] + simp only [NNReal.coe_one, one_mul, Subtype.dist_eq, Real.dist_eq] + exact le_rfl + have ho : LipschitzWith 1 (fun x : M.Point J root => dist o x) := by + apply LipschitzWith.of_dist_le_mul + intro x y + simpa only [NNReal.coe_one,one_mul] using dist_dist_dist_le_right o x y + have hd := ho.comp hp + have he : o.truncated D i = (fun H : J => min (dist o + (⟨i,H.val,H.property,hi⟩ : M.Point J root)) D) := + funext (fun H => o.truncated_of_reachable D i H hi) + rw [he] + simpa only [mul_one,Function.comp_apply] using hd.min_const D + · apply LipschitzWith.of_dist_le_mul + intro x y + simp only [truncated,dite_eq_right hi,dist_self,NNReal.coe_one,one_mul] + exact dist_nonneg + +lemma truncated_switch (o : M.Point J root) (D : ℝ) (i j : Fin n) (H : J) + (hs : H.val ∈ M.heights i j) : o.truncated D i H = o.truncated D j H := by + have ha : (M.activeGraph J).Adj i j := ⟨H.val,H.property,hs⟩ + by_cases hi : (M.activeGraph J).Reachable root i + · have hj := hi.trans ha.reachable + rw [truncated_of_reachable _ _ _ _ hi, truncated_of_reachable _ _ _ _ hj] + congr 1 + let x : M.Point J root := ⟨i,H.val,H.property,hi⟩ + let y : M.Point J root := ⟨j,H.val,H.property,hj⟩ + have hz : dist x y = 0 := by + apply le_antisymm _ dist_nonneg + simpa only [x,y,sub_self,abs_zero,add_zero] using x.dist_le_switch y H.property hs + exact PseudoMetricSpace.dist_eq_of_dist_zero o hz + · have hj : ¬(M.activeGraph J).Reachable root j := by + intro hj + exact hi (hj.trans ha.symm.reachable) + simp only [truncated,dite_eq_right hi,dite_eq_right hj] + +noncomputable def truncatedField (o : M.Point J root) (D : ℝ) : M.Field J 1 where + value := o.truncated D + vertical := o.truncated_vertical D + switch := o.truncated_switch D + +lemma truncated_root (o : M.Point J root) (D : ℝ) (H : J) : + o.truncated D o.column H = min |o.height - H.val| D := by + rw [truncated_of_reachable _ _ _ _ o.reachable, + Point.dist_same_column o (⟨o.column,H.val,H.property,o.reachable⟩ : M.Point J root) rfl] + +lemma truncated_minimum (o : M.Point J root) (D : ℝ) (i : Fin n) (H : J) : + o.truncated D o.column H ≤ o.truncated D i H := by + rw [truncated_root] + by_cases hi : (M.activeGraph J).Reachable root i + · rw [truncated_of_reachable _ _ _ _ hi] + exact min_le_min_right D (o.height_change_le (⟨i,H.val,H.property,hi⟩ : M.Point J root)) + · simp only [truncated,dite_eq_right hi] + exact min_le_right _ _ + +/-- The strict sublevel connects to the root by a real shortest switching +path; every visited column remains in the same strict sublevel. -/ +lemma truncated_sublevel_path (hJ : IsClosed J) (o : M.Point J root) (D t : ℝ) + (ht : t ≤ D) (i : Fin n) (H : J) (hi : o.truncated D i H < t) : + ∃ w : (M.activeGraph J).Walk i o.column, + ∀ z ∈ w.support, o.truncated D z H < t := by + have hir : (M.activeGraph J).Reachable root i := by + by_contra hn + simp only [truncated,dite_eq_right hn] at hi + exact (not_lt_of_ge ht) hi + rw [truncated_of_reachable _ _ _ _ hir] at hi + have hdist : dist o (⟨i,H.val,H.property,hir⟩ : M.Point J root) < t := by + rcases (min_lt_iff).mp hi with hi | hi + · exact hi + · exact False.elim ((not_lt_of_ge ht) hi) + obtain ⟨p, _, hp⟩ := o.shortest_sublevel hJ (⟨i,H.val,H.property,hir⟩ : M.Point J root) + refine ⟨p.word.reverse, ?_⟩ + intro z hz + obtain ⟨hzr, hdz⟩ := hp z (by simpa only [SimpleGraph.Walk.support_reverse,List.mem_reverse] using hz) + rw [truncated_of_reachable _ _ _ _ hzr] + exact (min_le_left _ _).trans_lt (hdz.trans_lt hdist) + +/-- The literal running-minimum projection of point distance, after cutting +at the chosen representative of the root. -/ +noncomputable def supportValue {k : ℕ} {M : Model (k + 1)} {J : Set ℝ} {r : Fin (k + 1)} + (o w : M.Point J r) (i : Fin (k + 1)) (H : J) : ℝ := + Ordered.running ((finCycle o.column).symm w.column) + (fun j => o.truncated (dist o w) (finCycle o.column j) H) + ((finCycle o.column).symm i) + +lemma supportValue_vertical {k : ℕ} {M : Model (k + 1)} {J : Set ℝ} {r : Fin (k + 1)} + (o w : M.Point J r) (i : Fin (k + 1)) : LipschitzWith 1 (o.supportValue w i) := by + exact Ordered.running_lipschitz _ _ _ 1 (fun j => o.truncated_vertical _ _) + +lemma supportValue_switch {k : ℕ} {M : Model (k + 1)} {J : Set ℝ} {r : Fin (k + 1)} + (hJ : IsClosed J) (o w : M.Point J r) (i j : Fin (k + 1)) (H : J) + (hs : H.val ∈ M.heights i j) : o.supportValue w i H = o.supportValue w j H := by + let e := finCycle o.column + let f := fun z => o.truncated (dist o w) (e z) H + have hzero : e 0 = o.column := by simp [e,finCycle_apply] + have hmin : ∀ z, f 0 ≤ f z := by + intro z + simpa only [f,hzero] using o.truncated_minimum (dist o w) (e z) H + have hpath : ∀ t ≤ dist o w, ∀ z, f z < t → + ∃ p : ((M.activeGraph J).comap e).Walk z 0, ∀ v ∈ p.support, f v < t := by + intro t ht z hz + obtain ⟨p,hp⟩ := o.truncated_sublevel_path hJ (dist o w) t ht (e z) H hz + obtain ⟨q,hq⟩ := ColumnOrder.walk_comap_equiv e (p.copy rfl hzero.symm) + refine ⟨q,fun v hv => ?_⟩ + exact hp (e v) (by simpa only [SimpleGraph.Walk.support_copy] using hq v hv) + have hnc := ColumnOrder.noncrossing_comap_cycle (M.active_noncrossing J) o.column + have heq : f (e.symm i) = f (e.symm j) := by + simpa only [f,Equiv.apply_symm_apply] using o.truncated_switch (dist o w) i j H hs + have hadj : ((M.activeGraph J).comap e).Adj (e.symm i) (e.symm j) := by + simpa only [SimpleGraph.comap_adj,Equiv.apply_symm_apply] using + (show (M.activeGraph J).Adj i j from ⟨H.val,H.property,hs⟩) + change Ordered.running (e.symm w.column) f (e.symm i) = + Ordered.running (e.symm w.column) f (e.symm j) + rcases lt_trichotomy (e.symm i) (e.symm j) with hij | hij | hij + · apply Ordered.running_switch _ _ hmin hij heq + exact ColumnOrder.collision hnc f (dist o w) (fun z => o.truncated_le _ _ _) hpath hij hadj heq + · rw [hij] + · symm + apply Ordered.running_switch _ _ hmin hij heq.symm + exact ColumnOrder.collision hnc f (dist o w) (fun z => o.truncated_le _ _ _) hpath hij hadj.symm heq.symm + +/-- Ordered support, with actual vertical and switch proofs. -/ +noncomputable def supportField {k : ℕ} {M : Model (k + 1)} {J : Set ℝ} {r : Fin (k + 1)} + (hJ : IsClosed J) (o w : M.Point J r) : M.Field J 1 where + value := o.supportValue w + vertical := o.supportValue_vertical w + switch := o.supportValue_switch hJ w + +lemma supportValue_root {k : ℕ} {M : Model (k + 1)} {J : Set ℝ} {r : Fin (k + 1)} + (o w : M.Point J r) (H : J) : + o.supportValue w o.column H = min |o.height - H.val| (dist o w) := by + simp only [supportValue,finCycle_symm_apply,sub_self,Ordered.running_zero, + finCycle_apply,zero_add,truncated_root] + +lemma supportValue_target {k : ℕ} {M : Model (k + 1)} {J : Set ℝ} {r : Fin (k + 1)} + (o w : M.Point J r) : o.supportValue w w.column ⟨w.height,w.inBand⟩ = dist o w := by + rw [supportValue,Ordered.running_target,Equiv.apply_symm_apply, + truncated_of_reachable _ _ _ _ w.reachable] + exact min_self _ + +lemma supportValue_bounds {k : ℕ} {M : Model (k + 1)} {J : Set ℝ} {r : Fin (k + 1)} + (o w : M.Point J r) (i : Fin (k + 1)) (H : J) : + 0 ≤ o.supportValue w i H ∧ o.supportValue w i H ≤ o.truncated (dist o w) i H := by + let e := finCycle o.column + let f := fun j => o.truncated (dist o w) (e j) H + have hzero : e 0 = o.column := by simp [e,finCycle_apply] + have hmin : ∀ z, f 0 ≤ f z := by + intro z + simpa only [f,hzero] using o.truncated_minimum (dist o w) (e z) H + have hnonneg : 0 ≤ f 0 := by + dsimp only [f] + rw [hzero,truncated_root] + exact le_min (abs_nonneg _) dist_nonneg + exact ⟨hnonneg.trans (Ordered.le_running _ _ hmin _), + by simpa only [supportValue,f,e,Equiv.apply_symm_apply] using + Ordered.running_le (e.symm w.column) f (e.symm i)⟩ + +end Point + +/-- Monotonicity on the two arcs, expressed in the circle cut at `a`. +The separate minimum condition records the wrap-around step to index zero. -/ +def Field.OrderedFrom {k : ℕ} {M : Model (k + 1)} {J : Set ℝ} {L : NNReal} + (F : M.Field J L) (a b : Fin (k + 1)) : Prop := + (∀ (H : J) i, F.value a H ≤ F.value i H) ∧ + (∀ (H : J) (i j : Fin (k + 1)), i ≤ j → j ≤ (finCycle a).symm b → + F.value (finCycle a i) H ≤ F.value (finCycle a j) H) ∧ + (∀ (H : J) (i j : Fin (k + 1)), (finCycle a).symm b ≤ i → i ≤ j → + F.value (finCycle a j) H ≤ F.value (finCycle a i) H) + +namespace Point + +lemma supportField_ordered {k : ℕ} {M : Model (k + 1)} {J : Set ℝ} {r : Fin (k + 1)} + (hJ : IsClosed J) (o w : M.Point J r) : + (o.supportField hJ w).OrderedFrom o.column w.column := by + have hmin (H : J) : ∀ z, o.truncated (dist o w) (finCycle o.column 0) H ≤ + o.truncated (dist o w) (finCycle o.column z) H := by + simp only [finCycle_apply,zero_add] + intro z + exact o.truncated_minimum _ _ _ + refine ⟨?_,?_,?_⟩ + · intro H i + change o.supportValue w o.column H ≤ o.supportValue w i H + unfold supportValue + simp only [finCycle_symm_apply,sub_self,Ordered.running_zero] + simpa only [finCycle_symm_apply] using + Ordered.le_running ((finCycle o.column).symm w.column) + (fun z => o.truncated (dist o w) (finCycle o.column z) H) (hmin H) + ((finCycle o.column).symm i) + · intro H i j hij hjb + change o.supportValue w (finCycle o.column i) H ≤ o.supportValue w (finCycle o.column j) H + simp only [supportValue,Equiv.symm_apply_apply] + exact Ordered.running_mono_left _ _ (hmin H) hij hjb + · intro H i j hbi hij + change o.supportValue w (finCycle o.column j) H ≤ o.supportValue w (finCycle o.column i) H + simp only [supportValue,Equiv.symm_apply_apply] + exact Ordered.running_mono_right _ _ hbi hij + +/-- Lemma ord:support, on every representative of the whole band. No +connectivity of the whole band is assumed. The upper distance bound is on the +chosen finite-distance component, just as the source's infinite convention. -/ +theorem exists_ordered_support {k : ℕ} {M : Model (k + 1)} {J : Set ℝ} {r : Fin (k + 1)} + (hJ : IsClosed J) (o w : M.Point J r) : + ∃ F : M.Field J 1, F.OrderedFrom o.column w.column ∧ + (∀ i H, 0 ≤ F.value i H ∧ F.value i H ≤ dist o w) ∧ + F.value o.column ⟨o.height,o.inBand⟩ = 0 ∧ + F.value w.column ⟨w.height,w.inBand⟩ = dist o w ∧ + ∀ x : M.Point J r, F.value x.column ⟨x.height,x.inBand⟩ ≤ dist o x := by + refine ⟨o.supportField hJ w, o.supportField_ordered hJ w, ?_, ?_, ?_, ?_⟩ + · intro i H + exact ⟨(o.supportValue_bounds w i H).1, + (o.supportValue_bounds w i H).2.trans (o.truncated_le _ _ _)⟩ + · change o.supportValue w o.column ⟨o.height,o.inBand⟩ = 0 + rw [supportValue_root,sub_self,abs_zero,min_eq_left dist_nonneg] + · exact o.supportValue_target w + · intro x + have h := (o.supportValue_bounds w x.column ⟨x.height,x.inBand⟩).2 + rw [truncated_of_reachable _ _ _ _ x.reachable] at h + exact h.trans (min_le_left _ _) + +end Point + +namespace Field + +/-- Signed open-arc membership. Boundary columns have sign zero. -/ +def arcSign {k : ℕ} (a b i : Fin (k + 1)) : ℝ := + if i = a ∨ i = b then 0 else if (finCycle a).symm i < (finCycle a).symm b then 1 else -1 + +lemma arcSign_cases {k : ℕ} (a b i : Fin (k + 1)) : + arcSign a b i = 0 ∨ arcSign a b i = 1 ∨ arcSign a b i = -1 := by + unfold arcSign + split_ifs <;> simp + +lemma arcSign_zero_iff {k : ℕ} (a b i : Fin (k + 1)) : + arcSign a b i = 0 ↔ i = a ∨ i = b := by + unfold arcSign + split_ifs <;> simp_all + +lemma abs_arcSign_le {k : ℕ} (a b i : Fin (k + 1)) : |arcSign a b i| ≤ 1 := by + rcases arcSign_cases a b i with h | h | h <;> simp [h] + +/-- Source Z_s in the max metric on R x R: the two boundary images and the +images of actual switches between opposite OPEN arcs. -/ +def wall {k : ℕ} {M : Model (k + 1)} {J : Set ℝ} {L : NNReal} + (F : M.Field J L) (a b : Fin (k + 1)) : Set (ℝ × ℝ) := + {z | (∃ H : J, z = (F.value a H,H.val)) ∨ + (∃ H : J, z = (F.value b H,H.val)) ∨ + ∃ (i j : Fin (k + 1)) (H : J), H.val ∈ M.heights i j ∧ + arcSign a b i = 1 ∧ arcSign a b j = -1 ∧ z = (F.value i H,H.val)} + +lemma wall_nonempty {k : ℕ} {M : Model (k + 1)} {J : Set ℝ} {L : NNReal} + (F : M.Field J L) (a b : Fin (k + 1)) (H : J) : (F.wall a b).Nonempty := by + exact ⟨(F.value a H,H.val),Or.inl ⟨H,rfl⟩⟩ + +lemma wall_of_boundary {k : ℕ} {M : Model (k + 1)} {J : Set ℝ} {L : NNReal} + (F : M.Field J L) (a b i : Fin (k + 1)) (H : J) (hi : arcSign a b i = 0) : + (F.value i H,H.val) ∈ F.wall a b := by + rcases (arcSign_zero_iff a b i).mp hi with hi | hi + · exact Or.inl ⟨H,by rw [hi]⟩ + · exact Or.inr (Or.inl ⟨H,by rw [hi]⟩) + +lemma wall_of_switch {k : ℕ} {M : Model (k + 1)} {J : Set ℝ} {L : NNReal} + (F : M.Field J L) (a b i j : Fin (k + 1)) (H : J) (hs : H.val ∈ M.heights i j) + (hneq : arcSign a b i ≠ arcSign a b j) : (F.value i H,H.val) ∈ F.wall a b := by + by_cases hi : arcSign a b i = 0 + · exact F.wall_of_boundary a b i H hi + by_cases hj : arcSign a b j = 0 + · rw [F.switch i j H hs] + exact F.wall_of_boundary a b j H hj + rcases arcSign_cases a b i with hi' | hi' | hi' + · exact False.elim (hi hi') + · rcases arcSign_cases a b j with hj' | hj' | hj' + · exact False.elim (hj hj') + · exact False.elim (hneq (hi'.trans hj'.symm)) + · exact Or.inr (Or.inr ⟨i,j,H,hs,hi',hj',rfl⟩) + · rcases arcSign_cases a b j with hj' | hj' | hj' + · exact False.elim (hj hj') + · exact Or.inr (Or.inr ⟨j,i,H,by rwa [M.symm j i],hj',hi',by rw [F.switch i j H hs]⟩) + · exact False.elim (hneq (hi'.trans hj'.symm)) + +noncomputable def transverseValue {k : ℕ} {M : Model (k + 1)} {J : Set ℝ} {L : NNReal} + (F : M.Field J L) (a b i : Fin (k + 1)) (H : J) : ℝ := + arcSign a b i * Metric.infDist (F.value i H,H.val) (F.wall a b) + +lemma coordinate_lipschitz {k : ℕ} {M : Model (k + 1)} {J : Set ℝ} {L : NNReal} + (F : M.Field J L) (hL : 1 ≤ L) (i : Fin (k + 1)) : + LipschitzWith L (fun H : J => (F.value i H,H.val)) := by + apply LipschitzWith.of_dist_le_mul + intro H T + rw [Prod.dist_eq] + refine max_le ((F.vertical i).dist_le_mul H T) ?_ + change dist H T ≤ L * dist H T + have hL' : (1 : ℝ) ≤ L := by exact_mod_cast hL + nlinarith [dist_nonneg (x := H) (y := T)] + +lemma transverse_vertical {k : ℕ} {M : Model (k + 1)} {J : Set ℝ} {L : NNReal} + (F : M.Field J L) (hL : 1 ≤ L) (a b i : Fin (k + 1)) : + LipschitzWith L (F.transverseValue a b i) := by + have hd := (Metric.lipschitz_infDist_pt (F.wall a b)).comp (F.coordinate_lipschitz hL i) + apply LipschitzWith.of_dist_le_mul + intro H T + have hh := hd.dist_le_mul H T + simp only [one_mul,Function.comp_apply,Real.dist_eq] at hh + rw [Real.dist_eq,transverseValue,transverseValue,← mul_sub,abs_mul] + exact (mul_le_of_le_one_left (abs_nonneg _) (abs_arcSign_le a b i)).trans hh + +lemma transverse_switch {k : ℕ} {M : Model (k + 1)} {J : Set ℝ} {L : NNReal} + (F : M.Field J L) (a b i j : Fin (k + 1)) (H : J) (hs : H.val ∈ M.heights i j) : + F.transverseValue a b i H = F.transverseValue a b j H := by + by_cases he : arcSign a b i = arcSign a b j + · simp only [transverseValue,he,F.switch i j H hs] + · have hz := Metric.infDist_zero_of_mem (F.wall_of_switch a b i j H hs he) + unfold transverseValue + rw [F.switch i j H hs] at hz ⊢ + rw [hz,mul_zero,mul_zero] + +/-- The transverse field. Its slope bound is inherited +from the original field (and at least one), with the switch identity proved. -/ +noncomputable def transverse {k : ℕ} {M : Model (k + 1)} {J : Set ℝ} {L : NNReal} + (F : M.Field J L) (hL : 1 ≤ L) (a b : Fin (k + 1)) : M.Field J L where + value := F.transverseValue a b + vertical := F.transverse_vertical hL a b + switch := F.transverse_switch a b + +lemma transverse_abs {k : ℕ} {M : Model (k + 1)} {J : Set ℝ} {L : NNReal} + (F : M.Field J L) (a b i : Fin (k + 1)) (H : J) (hi : arcSign a b i ≠ 0) : + |F.transverseValue a b i H| = Metric.infDist (F.value i H,H.val) (F.wall a b) := by + rw [transverseValue,abs_mul,abs_of_nonneg Metric.infDist_nonneg] + rcases arcSign_cases a b i with he | he | he + · exact False.elim (hi he) + · simp [he] + · simp [he] + +end Field + +namespace Path + +variable {M} {J : Set ℝ} + +/-- The actual set of representatives visited by a finite switching path, +including every point of its vertical segments. -/ +def trace : {i j : Fin n} → M.Path J i j → ℝ → ℝ → Set (Fin n × ℝ) + | i, _, .nil _, a, b => {z | z.1 = i ∧ z.2 ∈ Set.uIcc a b} + | i, _, .cons H _ _ p, a, b => {z | z.1 = i ∧ z.2 ∈ Set.uIcc a H} ∪ p.trace H b + +lemma trace_column {i j : Fin n} (p : M.Path J i j) {a b : ℝ} {z : Fin n × ℝ} + (hz : z ∈ p.trace a b) : z.1 ∈ p.word.support := by + induction p generalizing a with + | nil i => + simpa only [word,SimpleGraph.Walk.support_nil,List.mem_singleton] using hz.1 + | cons H hH hs p ih => + rcases hz with hz | hz + · exact List.mem_cons.mpr (Or.inl hz.1) + · exact List.mem_cons_of_mem _ (ih hz) + +lemma trace_height (hJ : Set.OrdConnected J) {i j : Fin n} (p : M.Path J i j) + {a b : ℝ} (ha : a ∈ J) (hb : b ∈ J) {z : Fin n × ℝ} (hz : z ∈ p.trace a b) : z.2 ∈ J := by + induction p generalizing a with + | nil i => exact hJ.uIcc_subset ha hb hz.2 + | cons H hH hs p ih => + rcases hz with hz | hz + · exact hJ.uIcc_subset ha hH hz.2 + · exact ih hH hz + +lemma abs_split {a b T : ℝ} (hT : T ∈ Set.uIcc a b) : |a - T| + |T - b| = |a - b| := by + rcases le_total a b with hab | hab + · have ht : a ≤ T ∧ T ≤ b := by + rcases Set.mem_uIcc.mp hT with ht | ht <;> constructor <;> linarith + rw [abs_of_nonpos (sub_nonpos.mpr ht.1),abs_of_nonpos (sub_nonpos.mpr ht.2), + abs_of_nonpos (sub_nonpos.mpr hab)] + ring + · have ht : b ≤ T ∧ T ≤ a := by + rcases Set.mem_uIcc.mp hT with ht | ht <;> constructor <;> linarith + rw [abs_of_nonneg (sub_nonneg.mpr ht.2),abs_of_nonneg (sub_nonneg.mpr ht.1), + abs_of_nonneg (sub_nonneg.mpr hab)] + ring + +/-- A visit admits an exact-length prefix and suffix, not just an unrelated +path to the same column. -/ +lemma trace_split {i j : Fin n} (p : M.Path J i j) {a b : ℝ} {z : Fin n × ℝ} + (hz : z ∈ p.trace a b) : ∃ (q : M.Path J i z.1) (r : M.Path J z.1 j), + q.length a z.2 + r.length z.2 b = p.length a b := by + induction p generalizing a with + | nil i => + obtain ⟨hz,hT⟩ := hz + subst i + exact ⟨.nil _,.nil _,abs_split hT⟩ + | @cons i v j H hH hs p ih => + rcases hz with hz | hz + · obtain ⟨hz,hT⟩ := hz + subst i + exact ⟨.nil _,.cons H hH hs p,by dsimp only [length]; linarith [abs_split hT]⟩ + · obtain ⟨q,r,hqr⟩ := ih hz + refine ⟨.cons H hH hs q,r,?_⟩ + dsimp only [length] + linarith + +end Path + +namespace Field + +variable {M} {J : Set ℝ} {L : NNReal} + +lemma vertical_intermediate (F : M.Field J L) (hJ : Set.OrdConnected J) (i : Fin n) + (a b : J) {c : ℝ} (ha : F.value i a ≤ c) (hb : c ≤ F.value i b) : + ∃ T ∈ Set.uIcc a.val b.val, ∃ hT : T ∈ J, F.value i ⟨T,hT⟩ = c := by + let K := Set.uIcc a.val b.val + let f : K → J := fun T => ⟨T.val,hJ.uIcc_subset a.property b.property T.property⟩ + have hf : Continuous f := continuous_subtype_val.subtype_mk _ + have : PreconnectedSpace K := Subtype.preconnectedSpace (isPreconnected_uIcc : IsPreconnected K) + have hc := (F.vertical i).continuous.comp hf + obtain ⟨T,hT⟩ := intermediate_value_univ + (⟨a.val,Set.left_mem_uIcc⟩ : K) (⟨b.val,Set.right_mem_uIcc⟩ : K) hc ⟨ha,hb⟩ + exact ⟨T.val,T.property,(f T).property,hT⟩ + +/-- Every intermediate scalar value on a switching path is attained on its +actual trace. Switch compatibility supplies continuity across the joins. -/ +lemma path_intermediate (F : M.Field J L) (hJ : Set.OrdConnected J) {i j : Fin n} + (p : M.Path J i j) (a b : J) {c : ℝ} (ha : F.value i a ≤ c) (hb : c ≤ F.value j b) : + ∃ (v : Fin n) (T : J), (v,T.val) ∈ p.trace a.val b.val ∧ F.value v T = c := by + induction p generalizing a with + | nil i => + obtain ⟨T,hT,hTJ,he⟩ := F.vertical_intermediate hJ i a b ha hb + exact ⟨i,⟨T,hTJ⟩,⟨rfl,hT⟩,he⟩ + | @cons i v j H hH hs p ih => + by_cases hc : c ≤ F.value i ⟨H,hH⟩ + · obtain ⟨T,hT,hTJ,he⟩ := F.vertical_intermediate hJ i a ⟨H,hH⟩ ha hc + exact ⟨i,⟨T,hTJ⟩,Or.inl ⟨rfl,hT⟩,he⟩ + · have hh : F.value v ⟨H,hH⟩ ≤ c := by + rw [← F.switch i v ⟨H,hH⟩ hs] + exact (lt_of_not_ge hc).le + obtain ⟨z,T,hT,he⟩ := ih ⟨H,hH⟩ hh hb + exact ⟨z,T,Or.inr hT,he⟩ + +end Field + +/-- The metric component is precisely the separation quotient of the +intrinsic pseudometric on representatives. No additional edges are inserted. -/ +abbrev Component (J : Set ℝ) (root : Fin n) := SeparationQuotient (M.Point J root) + + +end Model +end Columns + +end PlanarL1 + +end + +section + +namespace PlanarL1.Columns.Model.Point +open scoped NNReal +variable {n : ℕ} {M : Model n} {J : Set ℝ} {root : Fin n} + +/-- A Lipschitz scalar on one intrinsic component, continued constantly on the +other components, is a genuine vertical/switch-compatible field. -/ +noncomputable def extendValue (f : M.Point J root → ℝ) (i : Fin n) (H : J) : ℝ := by + classical + exact if h : (M.activeGraph J).Reachable root i then f ⟨i,H.val,H.property,h⟩ else 0 + +lemma extendValue_point (f : M.Point J root → ℝ) (x : M.Point J root) : + extendValue f x.column ⟨x.height,x.inBand⟩ = f x := by + simp only [extendValue,dite_eq_left x.reachable] + +lemma extendValue_vertical {K : ℝ≥0} (f : M.Point J root → ℝ) (hf : LipschitzWith K f) + (i : Fin n) : LipschitzWith K (extendValue f i) := by + apply LipschitzWith.of_dist_le_mul + intro a b + by_cases hi : (M.activeGraph J).Reachable root i + · simp only [extendValue,dite_eq_left hi] + have h := hf.dist_le_mul (⟨i,a.val,a.property,hi⟩ : M.Point J root) + (⟨i,b.val,b.property,hi⟩ : M.Point J root) + rw [Point.dist_same_column (⟨i,a.val,a.property,hi⟩ : M.Point J root) + (⟨i,b.val,b.property,hi⟩ : M.Point J root) rfl] at h + simpa only [Subtype.dist_eq,Real.dist_eq] using h + · simp only [extendValue,dite_eq_right hi,dist_self] + positivity + +lemma extendValue_switch {K : ℝ≥0} (f : M.Point J root → ℝ) (hf : LipschitzWith K f) + (i j : Fin n) (H : J) (hs : H.val ∈ M.heights i j) : + extendValue f i H = extendValue f j H := by + have ha : (M.activeGraph J).Adj i j := ⟨H.val,H.property,hs⟩ + by_cases hi : (M.activeGraph J).Reachable root i + · have hj := hi.trans ha.reachable + simp only [extendValue,dite_eq_left hi,dite_eq_left hj] + let x : M.Point J root := ⟨i,H.val,H.property,hi⟩ + let y : M.Point J root := ⟨j,H.val,H.property,hj⟩ + have hd : dist x y = 0 := by + apply le_antisymm _ dist_nonneg + simpa only [x,y,sub_self,abs_zero,add_zero] using x.dist_le_switch y H.property hs + have h := hf.dist_le_mul x y + rw [hd,mul_zero] at h + exact dist_le_zero.mp h + · have hj : ¬ (M.activeGraph J).Reachable root j := fun h => hi (h.trans ha.symm.reachable) + simp only [extendValue,dite_eq_right hi,dite_eq_right hj] + +noncomputable def extendField {K : ℝ≥0} (f : M.Point J root → ℝ) (hf : LipschitzWith K f) : + M.Field J K where + value := extendValue f + vertical := extendValue_vertical f hf + switch := extendValue_switch f hf + +/-- A continuous scalar intermediate value is attained on an actual shortest +switching path, with the exact metric betweenness identity. -/ +lemma intermediate_between {K : ℝ≥0} (f : M.Point J root → ℝ) (hf : LipschitzWith K f) + (hJ : IsClosed J) (hI : Set.OrdConnected J) (x y : M.Point J root) {c : ℝ} + (hx : f x ≤ c) (hy : c ≤ f y) : + ∃ z : M.Point J root, f z=c ∧ dist x z+dist z y=dist x y := by + obtain ⟨p,_,hp⟩ := x.exists_shortest hJ y + have hx' : (extendField f hf).value x.column ⟨x.height,x.inBand⟩ ≤ c := by + simpa only [extendField,extendValue_point] using hx + have hy' : c ≤ (extendField f hf).value y.column ⟨y.height,y.inBand⟩ := by + simpa only [extendField,extendValue_point] using hy + obtain ⟨i,H,hT,hF⟩ := (extendField f hf).path_intermediate hI p + ⟨x.height,x.inBand⟩ ⟨y.height,y.inBand⟩ hx' hy' + obtain ⟨q,r,hqr⟩ := p.trace_split hT + let z : M.Point J root := ⟨i,H.val,H.property,x.reachable.trans q.word.reachable⟩ + have hz : f z=c := by + change extendValue f z.column ⟨z.height,z.inBand⟩=c at hF + rwa [extendValue_point] at hF + refine ⟨z,hz,le_antisymm ?_ (dist_triangle x z y)⟩ + have hq := x.distance_le z q + have hr := z.distance_le y r + change dist x z ≤ q.length x.height H.val at hq + change dist z y ≤ r.length H.val y.height at hr + rw [← hp] + linarith + +end PlanarL1.Columns.Model.Point + + +end + +end OAI diff --git a/lean/OAI/Combinatorics/PlanarL1/FiniteL1.lean b/lean/OAI/Combinatorics/PlanarL1/FiniteL1.lean new file mode 100644 index 0000000000000000000000000000000000000000..d74d9f6994cf4ad8c44f20afc8e4db60b5b36aee --- /dev/null +++ b/lean/OAI/Combinatorics/PlanarL1/FiniteL1.lean @@ -0,0 +1,315 @@ +import OAI.Combinatorics.PlanarL1.Cuts +import OAI.Combinatorics.PlanarL1.Execution + +namespace OAI + +section + +namespace PlanarL1.FiniteL1 + +open MeasureTheory + +variable {I : Type*} [Fintype I] [MeasurableSpace I] [DiscreteMeasurableSpace I] + +noncomputable def ofFunction (f : I → ℝ) : Lp ℝ 1 (Measure.count : Measure I) := + (MemLp.of_discrete : MemLp f 1 Measure.count).toLp f + +lemma norm_ofFunction (f : I → ℝ) : ‖ofFunction f‖ = ∑ i, |f i| := by + rw [L1.norm_eq_integral_norm] + calc + (∫ i, ‖ofFunction f i‖ ∂Measure.count) = ∫ i, |f i| ∂Measure.count := by + apply integral_congr_ae + exact (MemLp.coeFn_toLp (MemLp.of_discrete : MemLp f 1 Measure.count)).mono fun i h => by + change ‖(MemLp.of_discrete : MemLp f 1 Measure.count).toLp f i‖ = |f i| + rw [h,Real.norm_eq_abs] + _ = _ := integral_count _ + +lemma ofFunction_sub (f g : I → ℝ) : + ofFunction f - ofFunction g = ofFunction (fun i => f i-g i) := by + exact (MemLp.toLp_sub (MemLp.of_discrete : MemLp f 1 Measure.count) + (MemLp.of_discrete : MemLp g 1 Measure.count)).symm + +lemma norm_sub (f g : I → ℝ) : ‖ofFunction f-ofFunction g‖ = ∑ i, |f i-g i| := by + rw [ofFunction_sub,norm_ofFunction] + +/-- The final finite cut-coordinate formula, valued in the ACTUAL real L1 +space requested by the main theorem, rather than an abstract cut cone. -/ +noncomputable def cutMap {V : Type*} (cut : I → Set V) (weight : I → ℝ) (v : V) : + Lp ℝ 1 (Measure.count : Measure I) := by + classical + exact ofFunction (fun i => if v ∈ cut i then weight i else 0) + +lemma norm_cutMap {V : Type*} (cut : I → Set V) (weight : I → ℝ) + (hweight : ∀ i, 0 ≤ weight i) (x y : V) : + ‖cutMap cut weight x-cutMap cut weight y‖ = + ∑ i, weight i*|((cut i).indicator (fun _ => (1:ℝ)) x)- + ((cut i).indicator (fun _ => (1:ℝ)) y)| := by + classical + rw [cutMap,cutMap,norm_sub] + apply Finset.sum_congr rfl + intro i _ + by_cases hx : x ∈ cut i <;> by_cases hy : y ∈ cut i <;> + simp [hx,hy,abs_of_nonneg (hweight i)] + +end PlanarL1.FiniteL1 + + + +end + +section + +namespace PlanarL1.FiniteL1 +open Set MeasureTheory +attribute [local instance] Classical.propDecidable + +variable {V Ω : Type*} [Fintype V] [MeasurableSpace Ω] (μ : Measure Ω) + +/-- Binary measurable assignments with integrable pair differences; individual +sets may have infinite measure, exactly as for the paper's label half-lines. -/ +structure BinarySystem where + active : Ω → V → Prop + measurable : ∀ v, MeasurableSet {ω | active ω v} + integrable : ∀ x y, Integrable (fun ω => + |(if active ω x then (1:ℝ) else 0)-(if active ω y then (1:ℝ) else 0)|) μ + +namespace BinarySystem +variable {μ} (B : BinarySystem (V := V) μ) + +noncomputable def indicator (v : V) (ω : Ω) : ℝ := if B.active ω v then 1 else 0 +noncomputable def fiber (S : Set V) : Set Ω := {ω | ∀ v, B.active ω v ↔ v ∈ S} +noncomputable def fiberValue (S : Set V) (ω : Ω) : ℝ := if ω ∈ B.fiber S then 1 else 0 + +def Proper (S : Set V) : Prop := S.Nonempty ∧ Sᶜ.Nonempty + +noncomputable def contribution (S : Set V) (ω : Ω) : ℝ := + if Proper S then B.fiberValue S ω else 0 + +noncomputable def weight (S : Set V) : ℝ := ∫ ω, B.contribution S ω ∂μ + +lemma measurable_fiber (S : Set V) : MeasurableSet (B.fiber S) := by + have he : B.fiber S = ⋂ v, {ω | B.active ω v ↔ v ∈ S} := by ext ω; simp [fiber] + rw [he] + apply MeasurableSet.iInter + intro v + by_cases hv : v ∈ S + · simpa only [hv,iff_true] using B.measurable v + · simpa only [hv,iff_false,Set.compl_ofPred] using (B.measurable v).compl + +lemma measurable_fiberValue (S : Set V) : Measurable (B.fiberValue S) := + Measurable.ite (B.measurable_fiber S) measurable_const measurable_const + +lemma measurable_contribution (S : Set V) : Measurable (B.contribution S) := by + unfold contribution + split_ifs + · exact B.measurable_fiberValue S + · exact measurable_const + +omit [Fintype V] in +lemma contribution_nonneg (S : Set V) (ω : Ω) : 0 ≤ B.contribution S ω := by + unfold contribution fiberValue + split_ifs <;> norm_num + +lemma integrable_contribution (S : Set V) : Integrable (B.contribution S) μ := by + by_cases hp : Proper S + · obtain ⟨x,hx⟩ := hp.1 + obtain ⟨y,hy⟩ := hp.2 + apply (B.integrable x y).mono' (B.measurable_contribution S).aestronglyMeasurable + apply Filter.Eventually.of_forall + intro ω + rw [Real.norm_eq_abs,abs_of_nonneg (B.contribution_nonneg S ω)] + by_cases hf : ω ∈ B.fiber S + · have hfx := (hf x).mpr hx + have hfy : ¬B.active ω y := fun h => hy ((hf y).mp h) + simp only [contribution,ite_eq_left hp,fiberValue,ite_eq_left hf,ite_eq_left hfx,ite_eq_right hfy, + sub_zero,abs_one,le_refl] + · simp only [contribution,ite_eq_left hp,fiberValue,ite_eq_right hf] + exact abs_nonneg _ + · have he : B.contribution S = fun _ => 0 := by + funext ω + exact ite_eq_right hp + rw [he] + exact integrable_zero _ _ _ + +omit [Fintype V] in +lemma weight_nonneg (S : Set V) : 0 ≤ B.weight S := + integral_nonneg (fun ω => B.contribution_nonneg S ω) + +noncomputable def cutCost (S : Set V) (x y : V) : ℝ := + |(S.indicator (fun _ => (1:ℝ)) x)-(S.indicator (fun _ => (1:ℝ)) y)| + +omit [Fintype V] in +lemma cutCost_nonneg (S : Set V) (x y : V) : 0 ≤ cutCost S x y := abs_nonneg _ + +omit [Fintype V] in +lemma cutCost_eq_zero_of_not_proper {S : Set V} (hS : ¬Proper S) (x y : V) : + cutCost S x y = 0 := by + classical + by_cases hx : x ∈ S <;> by_cases hy : y ∈ S + · simp [cutCost,hx,hy] + · exact (hS ⟨⟨x,hx⟩,⟨y,hy⟩⟩).elim + · exact (hS ⟨⟨y,hy⟩,⟨x,hx⟩⟩).elim + · simp [cutCost,hx,hy] + +lemma sum_contribution (x y : V) (ω : Ω) : + ∑ S : Set V, B.contribution S ω * cutCost S x y = + |B.indicator x ω-B.indicator y ω| := by + classical + let S₀ : Set V := {v | B.active ω v} + have hf : ω ∈ B.fiber S₀ := by intro v; rfl + have ho : ∀ S, S ≠ S₀ → B.contribution S ω = 0 := by + intro S hS + have hnf : ω ∉ B.fiber S := by + intro h + apply hS + ext v + exact (h v).symm + simp only [contribution,fiberValue,ite_eq_right hnf,ite_self] + rw [Finset.sum_eq_single S₀ (fun S _ hs => by rw [ho S hs,zero_mul]) + (fun h => (h (Finset.mem_univ _)).elim)] + have hc : cutCost S₀ x y = |B.indicator x ω-B.indicator y ω| := by + simp only [cutCost,Set.indicator_apply,indicator,S₀,Set.mem_ofPred_eq] + by_cases hp : Proper S₀ + · rw [contribution,ite_eq_left hp,fiberValue,ite_eq_left hf,one_mul,hc] + · rw [contribution,ite_eq_right hp,zero_mul,← hc,cutCost_eq_zero_of_not_proper hp] + +/-- Exact cut coefficients, not a finite-dimensional approximation of the label +metric. Empty/full cuts are zero; proper weights are finite by pair integrability. -/ +lemma cut_decomposition (x y : V) : + ∑ S : Set V, B.weight S * cutCost S x y = + ∫ ω, |B.indicator x ω-B.indicator y ω| ∂μ := by + classical + calc + _ = ∑ S : Set V, ∫ ω, B.contribution S ω*cutCost S x y ∂μ := by + apply Finset.sum_congr rfl + intro S _ + rw [integral_mul_const] + rfl + _ = ∫ ω, ∑ S : Set V, B.contribution S ω*cutCost S x y ∂μ := by + symm + exact integral_finsetSum _ (fun S _ => (B.integrable_contribution S).mul_const _) + _ = _ := integral_congr_ae (Filter.Eventually.of_forall (B.sum_contribution x y)) + +local instance : MeasurableSpace (Set V) := ⊤ + +noncomputable def embedding (x : V) : Lp ℝ 1 (Measure.count : Measure (Set V)) := + cutMap id B.weight x + +lemma distance_embedding (x y : V) : + ‖B.embedding x-B.embedding y‖ = ∫ ω, |B.indicator x ω-B.indicator y ω| ∂μ := by + rw [embedding,embedding,norm_cutMap id B.weight B.weight_nonneg] + exact B.cut_decomposition x y + +end BinarySystem +end PlanarL1.FiniteL1 + + +end + +section + +namespace PlanarL1.FiniteL1 +open MeasureTheory + +/-- All final metrics, and all adaptive averages of them, use the same finite +cut index type. No finite approximation to the label space is made. -/ +structure CutFamily (V : Type*) where + weight : Set V → ℝ + nonneg : ∀ S, 0 ≤ weight S + +namespace CutFamily +variable {V α ι : Type*} [Fintype V] + +noncomputable def distance (C : CutFamily V) (x y : V) : ℝ := by + classical + exact ∑ S : Set V, C.weight S * BinarySystem.cutCost S x y + +lemma distance_nonneg (C : CutFamily V) (x y : V) : 0 ≤ C.distance x y := by + classical + exact Finset.sum_nonneg (fun S _ => mul_nonneg (C.nonneg S) (abs_nonneg _)) + +noncomputable def ofBinary {Ω : Type*} [MeasurableSpace Ω] {μ : Measure Ω} + (B : BinarySystem (V := V) μ) : CutFamily V := ⟨B.weight,B.weight_nonneg⟩ + +lemma distance_ofBinary {Ω : Type*} [MeasurableSpace Ω] {μ : Measure Ω} + (B : BinarySystem (V := V) μ) (x y : V) : + (ofBinary B).distance x y=∫ ω, |B.indicator x ω-B.indicator y ω| ∂μ := + B.cut_decomposition x y + +noncomputable def add (C D : CutFamily V) : CutFamily V where + weight S := C.weight S+D.weight S + nonneg S := add_nonneg (C.nonneg S) (D.nonneg S) + +lemma distance_add (C D : CutFamily V) (x y : V) : + (C.add D).distance x y=C.distance x y+D.distance x y := by + classical + simp only [distance,add,add_mul,Finset.sum_add_distrib] + +noncomputable def sum [Fintype ι] (C : ι → CutFamily V) : CutFamily V where + weight S := ∑ i, (C i).weight S + nonneg S := Finset.sum_nonneg (fun i _ => (C i).nonneg S) + +lemma distance_sum [Fintype ι] (C : ι → CutFamily V) (x y : V) : + (sum C).distance x y=∑ i, (C i).distance x y := by + classical + simp only [distance,sum,Finset.sum_mul] + exact Finset.sum_comm + +noncomputable def average (E : Execution α) (C : α → CutFamily V) : CutFamily V where + weight S := E.mean (fun a => (C a).weight S) + nonneg S := E.mean_nonneg (fun a => (C a).nonneg S) + +lemma distance_average (E : Execution α) (C : α → CutFamily V) (x y : V) : + (average E C).distance x y=E.mean (fun a => (C a).distance x y) := by + classical + simp only [distance,average,Execution.mean_sum] + apply Finset.sum_congr rfl + intro S _ + rw [mul_comm,← Execution.mean_smul] + congr 1 + funext a + exact mul_comm _ _ + +noncomputable def scale (c : ℝ) (hc : 0 ≤ c) (C : CutFamily V) : CutFamily V where + weight S := c*C.weight S + nonneg S := mul_nonneg hc (C.nonneg S) + +lemma distance_scale (c : ℝ) (hc : 0 ≤ c) (C : CutFamily V) (x y : V) : + (scale c hc C).distance x y=c*C.distance x y := by + classical + simp only [distance,scale,Finset.mul_sum,mul_assoc] + +local instance : MeasurableSpace (Set V) := ⊤ + +noncomputable def embedding (C : CutFamily V) (x : V) : Lp ℝ 1 (Measure.count : Measure (Set V)) := + cutMap id C.weight x + +lemma norm_embedding (C : CutFamily V) (x y : V) : + ‖C.embedding x-C.embedding y‖=C.distance x y := by + classical + exact norm_cutMap id C.weight C.nonneg x y + +/-- The last rescaling step in the manuscript, using actual real Lp1. The +geometric lower bound is a prerequisite proved by the random construction. -/ +theorem embedding_of_bounds (C : CutFamily V) (d : V → V → ℝ) {a b : ℝ} + (ha : 0 < a) (hl : ∀ x y, a*d x y ≤ C.distance x y) + (hu : ∀ x y, C.distance x y ≤ b*d x y) : + ∃ f : V → Lp ℝ 1 (Measure.count : Measure (Set V)), + ∀ x y, d x y ≤ ‖f x-f y‖ ∧ ‖f x-f y‖ ≤ (b/a)*d x y := by + refine ⟨(scale a⁻¹ (inv_nonneg.mpr ha.le) C).embedding,?_⟩ + intro x y + rw [norm_embedding,distance_scale] + constructor + · have h := mul_le_mul_of_nonneg_left (hl x y) (inv_nonneg.mpr ha.le) + simpa only [← mul_assoc,inv_mul_cancel₀ ha.ne',one_mul] using h + · have h := mul_le_mul_of_nonneg_left (hu x y) (inv_nonneg.mpr ha.le) + simpa only [div_eq_mul_inv,mul_assoc,mul_comm,mul_left_comm] using h + +end CutFamily +end PlanarL1.FiniteL1 + + + +end + +end OAI diff --git a/lean/OAI/Combinatorics/PlanarL1/Gluing.lean b/lean/OAI/Combinatorics/PlanarL1/Gluing.lean new file mode 100644 index 0000000000000000000000000000000000000000..19d151f84c62a0ec0613c9b5c414b4c57d3c4d2f --- /dev/null +++ b/lean/OAI/Combinatorics/PlanarL1/Gluing.lean @@ -0,0 +1,567 @@ +import OAI.Combinatorics.PlanarL1.Threshold + +namespace OAI + +section + +namespace PlanarL1.Gluing +open Set +open scoped NNReal +attribute [local instance] Classical.propDecidable + +lemma frontier_between_right {S : Set ℝ} (hS : IsClosed S) {x y : ℝ} + (hxy : x ≤ y) (hx : x ∈ S) (hy : y ∉ S) : + ∃ z ∈ frontier S, x ≤ z ∧ z ≤ y := by + have hc : IsCompact (Icc x y ∩ S) := isCompact_Icc.inter_right hS + obtain ⟨z,hz,hmax⟩ := hc.exists_isGreatest ⟨x,⟨⟨le_rfl,hxy⟩,hx⟩⟩ + refine ⟨z,?_,hz.1⟩ + rw [frontier,mem_sdiff,hS.closure_eq] + refine ⟨hz.2,?_⟩ + intro hzi + obtain ⟨ε,hε,hball⟩ := Metric.isOpen_iff.mp isOpen_interior z hzi + have hzy : z < y := lt_of_le_of_ne hz.1.2 (fun h => hy (h ▸ hz.2)) + let t := z + min ε (y-z)/2 + have ht1 : z < t := by dsimp [t]; have := lt_min hε (sub_pos.mpr hzy); linarith + have ht2 : t ≤ y := by dsimp [t]; have := min_le_right ε (y-z); linarith + have htd : dist t z < ε := by + rw [Real.dist_eq,abs_of_pos (sub_pos.mpr ht1)] + dsimp [t] + have := min_le_left ε (y-z) + linarith + have htS := interior_subset (hball htd) + exact (not_le.mpr ht1) (hmax ⟨⟨hz.1.1.trans ht1.le,ht2⟩,htS⟩) + +lemma frontier_between_left {S : Set ℝ} (hS : IsClosed S) {x y : ℝ} + (hxy : x ≤ y) (hx : x ∉ S) (hy : y ∈ S) : + ∃ z ∈ frontier S, x ≤ z ∧ z ≤ y := by + have hc : IsCompact (Icc x y ∩ S) := isCompact_Icc.inter_right hS + obtain ⟨z,hz,hmin⟩ := hc.exists_isLeast ⟨y,⟨⟨hxy,le_rfl⟩,hy⟩⟩ + refine ⟨z,?_,hz.1⟩ + rw [frontier,mem_sdiff,hS.closure_eq] + refine ⟨hz.2,?_⟩ + intro hzi + obtain ⟨ε,hε,hball⟩ := Metric.isOpen_iff.mp isOpen_interior z hzi + have hxz : x < z := lt_of_le_of_ne hz.1.1 (fun h => hx (h.symm ▸ hz.2)) + let t := z - min ε (z-x)/2 + have ht1 : t < z := by dsimp [t]; have := lt_min hε (sub_pos.mpr hxz); linarith + have ht2 : x ≤ t := by dsimp [t]; have := min_le_right ε (z-x); linarith + have htd : dist t z < ε := by + rw [Real.dist_eq,abs_of_neg (sub_neg.mpr ht1)] + dsimp [t] + have := min_le_left ε (z-x) + linarith + have htS := interior_subset (hball htd) + exact (not_le.mpr ht1) (hmin ⟨⟨ht2,ht1.le.trans hz.1.2⟩,htS⟩) + +lemma monotone_piecewise {S : Set ℝ} (hS : IsClosed S) + {β : Type*} [Preorder β] {f g : ℝ → β} + (hf : Monotone f) (hg : MonotoneOn g S) (he : EqOn g f (frontier S)) : + Monotone (S.piecewise g f) := by + classical + intro x y hxy + by_cases hx : x ∈ S <;> by_cases hy : y ∈ S + · simpa only [piecewise_eq_of_mem _ _ _ hx,piecewise_eq_of_mem _ _ _ hy] using hg hx hy hxy + · obtain ⟨z,hz,hxz,hzy⟩ := frontier_between_right hS hxy hx hy + have hzS : z ∈ S := hS.frontier_subset hz + have h : g x ≤ f y := (hg hx hzS hxz).trans (by rw [he hz]; exact hf hzy) + simpa only [piecewise_eq_of_mem _ _ _ hx,piecewise_eq_of_notMem _ _ _ hy] using h + · obtain ⟨z,hz,hxz,hzy⟩ := frontier_between_left hS hxy hx hy + have hzS : z ∈ S := hS.frontier_subset hz + have h : f x ≤ g y := (hf hxz).trans (by rw [← he hz]; exact hg hzS hy hzy) + simpa only [piecewise_eq_of_notMem _ _ _ hx,piecewise_eq_of_mem _ _ _ hy] using h + · simpa only [piecewise_eq_of_notMem _ _ _ hx,piecewise_eq_of_notMem _ _ _ hy] using hf hxy + +lemma lipschitz_piecewise {S : Set ℝ} (hS : IsClosed S) + {β : Type*} [PseudoMetricSpace β] {f g : ℝ → β} {K : ℝ≥0} + (hf : LipschitzWith K f) (hg : LipschitzOnWith K g S) + (he : EqOn g f (frontier S)) : LipschitzWith K (S.piecewise g f) := by + classical + have hb (x y : ℝ) (hxy : x ≤ y) : + dist (S.piecewise g f x) (S.piecewise g f y) ≤ K * (y-x) := by + by_cases hx : x ∈ S <;> by_cases hy : y ∈ S + · simpa only [piecewise_eq_of_mem _ _ _ hx,piecewise_eq_of_mem _ _ _ hy, + Real.dist_eq,abs_of_nonpos (sub_nonpos.mpr hxy),neg_sub] using hg.dist_le_mul x hx y hy + · obtain ⟨z,hz,hxz,hzy⟩ := frontier_between_right hS hxy hx hy + have hzS : z ∈ S := hS.frontier_subset hz + have h1 := hg.dist_le_mul x hx z hzS + have h2 := hf.dist_le_mul z y + rw [he hz] at h1 + rw [Real.dist_eq,abs_of_nonpos (sub_nonpos.mpr hxz),neg_sub] at h1 + rw [Real.dist_eq,abs_of_nonpos (sub_nonpos.mpr hzy),neg_sub] at h2 + have h3 := dist_triangle (g x) (f z) (f y) + simp only [piecewise_eq_of_mem _ _ _ hx,piecewise_eq_of_notMem _ _ _ hy] + nlinarith + · obtain ⟨z,hz,hxz,hzy⟩ := frontier_between_left hS hxy hx hy + have hzS : z ∈ S := hS.frontier_subset hz + have h1 := hf.dist_le_mul x z + have h2 := hg.dist_le_mul z hzS y hy + rw [he hz] at h2 + rw [Real.dist_eq,abs_of_nonpos (sub_nonpos.mpr hxz),neg_sub] at h1 + rw [Real.dist_eq,abs_of_nonpos (sub_nonpos.mpr hzy),neg_sub] at h2 + have h3 := dist_triangle (f x) (f z) (g y) + simp only [piecewise_eq_of_notMem _ _ _ hx,piecewise_eq_of_mem _ _ _ hy] + nlinarith + · simpa only [piecewise_eq_of_notMem _ _ _ hx,piecewise_eq_of_notMem _ _ _ hy, + Real.dist_eq,abs_of_nonpos (sub_nonpos.mpr hxy),neg_sub] using hf.dist_le_mul x y + apply LipschitzWith.of_dist_le_mul + intro x y + obtain hxy | hyx := le_total x y + · simpa only [Real.dist_eq,abs_of_nonpos (sub_nonpos.mpr hxy),neg_sub] using hb x y hxy + · simpa only [dist_comm (S.piecewise g f y),Real.dist_eq,abs_of_nonneg (sub_nonneg.mpr hyx)] using hb y x hyx + +end PlanarL1.Gluing + + + +end + +section + +namespace PlanarL1.Gluing +open MeasureTheory Set +attribute [local instance] Classical.propDecidable + +variable {Ω : Type*} [MeasurableSpace Ω] {μ : Measure Ω} + +/-- The upper-bound invariant on a set of heights, stated on differences +because individual half-line indicators need not be integrable. -/ +def VerticalBound (μ : Measure Ω) (f : ℝ → Ω → ℝ) (S : Set ℝ) : Prop := + ∀ s ∈ S, ∀ t ∈ S, Integrable (fun ω => f s ω-f t ω) μ ∧ + (∫ ω, |f s ω-f t ω| ∂μ) ≤ |s-t| + +lemma difference_triangle {f g h : Ω → ℝ} + (hf : Integrable (fun ω => f ω-g ω) μ) + (hg : Integrable (fun ω => g ω-h ω) μ) : + Integrable (fun ω => f ω-h ω) μ ∧ + (∫ ω, |f ω-h ω| ∂μ) ≤ (∫ ω, |f ω-g ω| ∂μ)+(∫ ω, |g ω-h ω| ∂μ) := by + have hadd : Integrable (fun ω => (f ω-g ω)+(g ω-h ω)) μ := hf.add hg + have hi : Integrable (fun ω => f ω-h ω) μ := by + simpa only [sub_add_sub_cancel] using hadd + have hfn : Integrable (fun ω => |f ω-g ω|) μ := hf.norm + have hgn : Integrable (fun ω => |g ω-h ω|) μ := hg.norm + have hin : Integrable (fun ω => |f ω-h ω|) μ := hi.norm + have hsum : Integrable (fun ω => |f ω-g ω|+|g ω-h ω|) μ := hfn.add hgn + refine ⟨hi,?_⟩ + calc + _ ≤ ∫ ω, |f ω-g ω|+|g ω-h ω| ∂μ := by + exact integral_mono hin hsum (fun ω => abs_sub_le _ _ _) + _ = _ := integral_add hfn hgn + +lemma verticalBound_piecewise {S : Set ℝ} (hS : IsClosed S) + {f g : ℝ → Ω → ℝ} (hf : VerticalBound μ f univ) + (hg : VerticalBound μ g S) (he : EqOn g f (frontier S)) : + VerticalBound μ (S.piecewise g f) univ := by + classical + have hb (x y : ℝ) (hxy : x ≤ y) : + Integrable (fun ω => S.piecewise g f x ω-S.piecewise g f y ω) μ ∧ + (∫ ω, |S.piecewise g f x ω-S.piecewise g f y ω| ∂μ) ≤ y-x := by + by_cases hx : x ∈ S <;> by_cases hy : y ∈ S + · simpa only [piecewise_eq_of_mem _ _ _ hx,piecewise_eq_of_mem _ _ _ hy, + abs_of_nonpos (sub_nonpos.mpr hxy),neg_sub] using hg x hx y hy + · obtain ⟨z,hz,hxz,hzy⟩ := frontier_between_right hS hxy hx hy + have hgz := hg x hx z (hS.frontier_subset hz) + have hfz := hf z (mem_univ z) y (mem_univ y) + rw [he hz] at hgz + obtain ⟨hi,hb⟩ := difference_triangle hgz.1 hfz.1 + simp only [piecewise_eq_of_mem _ _ _ hx,piecewise_eq_of_notMem _ _ _ hy] + refine ⟨hi,?_⟩ + have h1 := hgz.2 + have h2 := hfz.2 + rw [abs_of_nonpos (sub_nonpos.mpr hxz),neg_sub] at h1 + rw [abs_of_nonpos (sub_nonpos.mpr hzy),neg_sub] at h2 + linarith + · obtain ⟨z,hz,hxz,hzy⟩ := frontier_between_left hS hxy hx hy + have hfz := hf x (mem_univ x) z (mem_univ z) + have hgz := hg z (hS.frontier_subset hz) y hy + rw [he hz] at hgz + obtain ⟨hi,hb⟩ := difference_triangle hfz.1 hgz.1 + simp only [piecewise_eq_of_notMem _ _ _ hx,piecewise_eq_of_mem _ _ _ hy] + refine ⟨hi,?_⟩ + have h1 := hfz.2 + have h2 := hgz.2 + rw [abs_of_nonpos (sub_nonpos.mpr hxz),neg_sub] at h1 + rw [abs_of_nonpos (sub_nonpos.mpr hzy),neg_sub] at h2 + linarith + · simpa only [piecewise_eq_of_notMem _ _ _ hx,piecewise_eq_of_notMem _ _ _ hy, + abs_of_nonpos (sub_nonpos.mpr hxy),neg_sub] using hf x (mem_univ x) y (mem_univ y) + intro x _ y _ + rcases le_total x y with hxy | hyx + · simpa only [abs_of_nonpos (sub_nonpos.mpr hxy),neg_sub] using hb x y hxy + · obtain ⟨hi,hb⟩ := hb y x hyx + constructor + · have hn : Integrable (fun ω => -(S.piecewise g f y ω-S.piecewise g f x ω)) μ := hi.neg + simpa only [neg_sub] using hn + · simpa only [abs_sub_comm (S.piecewise g f x _),abs_of_nonneg (sub_nonneg.mpr hyx)] using hb + +end PlanarL1.Gluing + +namespace PlanarL1.Columns.Model +open MeasureTheory Set +attribute [local instance] Classical.propDecidable +variable {n : ℕ} {M : Model n} {Ω : Type*} [MeasurableSpace Ω] {μ : Measure Ω} + +/-- Local update data on closed full-column pieces. Cross-domain switches +must be unchanged, as ensured by the strict frontier margins in the source. -/ +structure SetPatch (A : SetSystem M Ω μ) where + domain : Fin n → Set ℝ + closed : ∀ i, IsClosed (domain i) + active : Ω → Fin n → ℝ → Prop + measurable_active : ∀ i H, MeasurableSet {ω | active ω i H} + increasing : ∀ ω i, MonotoneOn (active ω i) (domain i) + boundary : ∀ ω i H, H ∈ frontier (domain i) → + (active ω i H ↔ (A.activity ω).active i H) + switch_inside : ∀ ω i j H, H ∈ M.heights i j → H ∈ domain i → H ∈ domain j → + (active ω i H ↔ active ω j H) + switch_outside : ∀ ω i j H, H ∈ M.heights i j → H ∈ domain i → H ∉ domain j → + (active ω i H ↔ (A.activity ω).active i H) + vertical : ∀ i, Gluing.VerticalBound μ (fun H ω => if active ω i H then 1 else 0) (domain i) + +namespace SetPatch +variable {A : SetSystem M Ω μ} (P : SetPatch A) + +noncomputable def patchedActivity (ω : Ω) : Activity M where + active i H := if H ∈ P.domain i then P.active ω i H else (A.activity ω).active i H + increasing i s t hst := by + have hf : Monotone ((A.activity ω).active i) := by + intro s t hst + exact (A.activity ω).increasing i s t hst + have hm := Gluing.monotone_piecewise (P.closed i) + hf (P.increasing ω i) + (fun H hH => propext (P.boundary ω i H hH)) + exact hm hst + switch i j H hs := by + by_cases hi : H ∈ P.domain i <;> by_cases hj : H ∈ P.domain j + · simpa only [ite_eq_left hi,ite_eq_left hj] using P.switch_inside ω i j H hs hi hj + · simpa only [ite_eq_left hi,ite_eq_right hj] using + (P.switch_outside ω i j H hs hi hj).trans ((A.activity ω).switch i j H hs) + · have hs' : H ∈ M.heights j i := by rwa [M.symm] + simpa only [ite_eq_right hi,ite_eq_left hj] using + ((A.activity ω).switch i j H hs).trans (P.switch_outside ω j i H hs' hj hi).symm + · simpa only [ite_eq_right hi,ite_eq_right hj] using (A.activity ω).switch i j H hs + +lemma indicator_eq (ω : Ω) (i : Fin n) (H : ℝ) : + (P.patchedActivity ω).indicator i H = + (P.domain i).piecewise (fun H ω => if P.active ω i H then (1:ℝ) else 0) + (fun H ω => (A.activity ω).indicator i H) H ω := by + unfold patchedActivity Activity.indicator + by_cases h : H ∈ P.domain i <;> simp [h,Set.piecewise] + +lemma verticalBound (i : Fin n) : Gluing.VerticalBound μ + (fun H ω => (P.patchedActivity ω).indicator i H) univ := by + have hf : Gluing.VerticalBound μ (fun H ω => (A.activity ω).indicator i H) univ := by + intro s _ t _ + constructor + · apply (integrable_norm_iff ((A.measurable_indicator i s).sub + (A.measurable_indicator i t)).aestronglyMeasurable).mp + simpa only [Real.norm_eq_abs,Pi.sub_apply] using A.vertical_integrable i s t + · exact A.vertical_bound i s t + have he : EqOn (fun H ω => if P.active ω i H then (1:ℝ) else 0) + (fun H ω => (A.activity ω).indicator i H) (frontier (P.domain i)) := by + intro H hH + ext ω + simp only [Activity.indicator,P.boundary ω i H hH] + have hb := Gluing.verticalBound_piecewise (P.closed i) hf (P.vertical i) he + simpa only [indicator_eq] using hb + +noncomputable def apply : SetSystem M Ω μ where + activity := P.patchedActivity + measurable_active i H := by + by_cases h : H ∈ P.domain i + · simpa only [patchedActivity,ite_eq_left h] using P.measurable_active i H + · simpa only [patchedActivity,ite_eq_right h] using A.measurable_active i H + vertical_integrable i s t := by + exact (P.verticalBound i s (mem_univ s) t (mem_univ t)).1.norm + vertical_bound i s t := (P.verticalBound i s (mem_univ s) t (mem_univ t)).2 + +lemma unchanged {i : Fin n} {H : ℝ} (h : H ∉ P.domain i) (ω : Ω) : + (P.apply.activity ω).active i H ↔ (A.activity ω).active i H := by + simp only [apply,patchedActivity,ite_eq_right h] + +lemma inside {i : Fin n} {H : ℝ} (h : H ∈ P.domain i) (ω : Ω) : + (P.apply.activity ω).active i H ↔ P.active ω i H := by + simp only [apply,patchedActivity,ite_eq_left h] + +end SetPatch +end PlanarL1.Columns.Model + +namespace PlanarL1.Threshold +open MeasureTheory Set +open scoped NNReal +attribute [local instance] Classical.propDecidable + +variable {Ω : Type*} [MeasurableSpace Ω] {μ : Measure Ω} + +lemma active_verticalBound (Z : Variables Ω μ) {S : Set ℝ} {P : ℝ → ℝ} + (hP : LipschitzOnWith 1 P S) : Gluing.VerticalBound μ + (fun H ω => if active Z H (P H) ω then (1:ℝ) else 0) S := by + intro s hs t ht + simp only [active_indicator] + refine ⟨Z.integrable_difference s (P s) t (P t),?_⟩ + rw [Z.distance] + have h := hP.dist_le_mul s hs t ht + rw [Real.dist_eq,Real.dist_eq,NNReal.coe_one,one_mul] at h + exact max_le le_rfl h + +/-- A literal common-label scalar chart replacement yields local patch data. +P already contains the source κ and comparison-orientation factors. -/ +noncomputable def chartPatch {n : ℕ} {M : Columns.Model n} + (A : M.SetSystem Ω μ) (Z : Variables Ω μ) (D : Fin n → Set ℝ) + (hD : ∀ i, IsClosed (D i)) (P : Fin n → ℝ → ℝ) + (hP : ∀ i, LipschitzOnWith 1 (P i) (D i)) + (hb : ∀ ω i H, H ∈ frontier (D i) → + (active Z H (P i H) ω ↔ (A.activity ω).active i H)) + (hs : ∀ i j H, H ∈ M.heights i j → H ∈ D i → H ∈ D j → P i H = P j H) + (hc : ∀ ω i j H, H ∈ M.heights i j → H ∈ D i → H ∉ D j → + (active Z H (P i H) ω ↔ (A.activity ω).active i H)) : Columns.Model.SetPatch A where + domain := D + closed := hD + active ω i H := active Z H (P i H) ω + measurable_active i H := measurable_active Z H (P i H) + increasing ω i := active_increasing Z (hP i) ω + boundary := hb + switch_inside ω i j H hij hi hj := by rw [hs i j H hij hi hj] + switch_outside := hc + vertical i := active_verticalBound Z (hP i) + +end PlanarL1.Threshold + + +end + +section + +namespace PlanarL1.Columns.Model +open MeasureTheory +attribute [local instance] Classical.propDecidable +variable {n : ℕ} {M : Model n} {Ω : Type*} [MeasurableSpace Ω] {μ : Measure Ω} + +lemma Activity.indicator_mono (A : Activity M) (i : Fin n) : Monotone (A.indicator i) := by + intro s t hst + by_cases hs : A.active i s + · simp only [Activity.indicator,ite_eq_left hs,ite_eq_left (A.increasing i s t hst hs),le_refl] + · simp only [Activity.indicator,ite_eq_right hs] + split_ifs <;> norm_num + +/-- Balanced changes of one-point marginals preserve the exact vertical bound +once genuine nestedness has been established. This avoids an unjustified +finite-boundary assumption on chart regions. -/ +noncomputable def SetSystem.balancedUpdate (S : SetSystem M Ω μ) (A : Ω → Activity M) + (hm : ∀ i H, MeasurableSet {ω | (A ω).active i H}) + (hi : ∀ i H, Integrable (fun ω => (A ω).indicator i H-(S.activity ω).indicator i H) μ) + (hz : ∀ i H, (∫ ω, (A ω).indicator i H-(S.activity ω).indicator i H ∂μ)=0) : + SetSystem M Ω μ := by + have hoi (i : Fin n) (s t : ℝ) : + Integrable (fun ω => (S.activity ω).indicator i s-(S.activity ω).indicator i t) μ := by + apply (integrable_norm_iff ((S.measurable_indicator i s).sub + (S.measurable_indicator i t)).aestronglyMeasurable).mp + simpa only [Real.norm_eq_abs,Pi.sub_apply] using S.vertical_integrable i s t + have hnew (i : Fin n) (s t : ℝ) : + Integrable (fun ω => (A ω).indicator i s-(A ω).indicator i t) μ ∧ + (∫ ω, (A ω).indicator i s-(A ω).indicator i t ∂μ)= + ∫ ω, (S.activity ω).indicator i s-(S.activity ω).indicator i t ∂μ := by + have he : (fun ω => (A ω).indicator i s-(A ω).indicator i t) = fun ω => + ((A ω).indicator i s-(S.activity ω).indicator i s)+ + ((S.activity ω).indicator i s-(S.activity ω).indicator i t)- + ((A ω).indicator i t-(S.activity ω).indicator i t) := by funext ω; ring + rw [he] + constructor + · exact ((hi i s).add (hoi i s t)).sub (hi i t) + · have hsum : Integrable (fun ω => + ((A ω).indicator i s-(S.activity ω).indicator i s)+ + ((S.activity ω).indicator i s-(S.activity ω).indicator i t)) μ := + (hi i s).add (hoi i s t) + rw [integral_sub hsum (hi i t), + integral_add (hi i s) (hoi i s t),hz i s,hz i t,zero_add,sub_zero] + have habs (i : Fin n) (s t : ℝ) : + (∫ ω, |(A ω).indicator i s-(A ω).indicator i t| ∂μ)= + ∫ ω, |(S.activity ω).indicator i s-(S.activity ω).indicator i t| ∂μ := by + rcases le_total t s with h | h + · simp only [abs_of_nonneg (sub_nonneg.mpr ((A _).indicator_mono i h)), + abs_of_nonneg (sub_nonneg.mpr ((S.activity _).indicator_mono i h))] + exact (hnew i s t).2 + · simp only [abs_of_nonpos (sub_nonpos.mpr ((A _).indicator_mono i h)), + abs_of_nonpos (sub_nonpos.mpr ((S.activity _).indicator_mono i h)),integral_neg] + rw [(hnew i s t).2] + exact { + activity := A + measurable_active := hm + vertical_integrable := fun i s t => (hnew i s t).1.norm + vertical_bound := fun i s t => (habs i s t).trans_le (S.vertical_bound i s t) + } +end PlanarL1.Columns.Model + + + +end + +section + +namespace PlanarL1.Columns.Model.SetPatch +open MeasureTheory Set +attribute [local instance] Classical.propDecidable +variable {n : ℕ} {M : Model n} {Ω : Type*} [MeasurableSpace Ω] {μ : Measure Ω} + {A : SetSystem M Ω μ} + +/-- A patch can be installed after other patches which have not changed its +closed domain. Its actual activity and all clipping data are retained. -/ +def rebase (P : SetPatch A) (B : SetSystem M Ω μ) + (hB : ∀ ω i H, H ∈ P.domain i → ((B.activity ω).active i H ↔ (A.activity ω).active i H)) : + SetPatch B where + domain := P.domain + closed := P.closed + active := P.active + measurable_active := P.measurable_active + increasing := P.increasing + boundary ω i H hH := (P.boundary ω i H hH).trans + (hB ω i H ((P.closed i).frontier_subset hH)).symm + switch_inside := P.switch_inside + switch_outside ω i j H hs hi hj := (P.switch_outside ω i j H hs hi hj).trans (hB ω i H hi).symm + vertical := P.vertical + +def UnchangedOverlap (P Q : SetPatch A) : Prop := + ∀ ω i H, H ∈ P.domain i → H ∈ Q.domain i → + (P.active ω i H ↔ (A.activity ω).active i H) ∧ + (Q.active ω i H ↔ (A.activity ω).active i H) + +/-- The deterministic tie rule chooses the first closed cell containing a +point. On all main-cell overlaps every proposal is the original activity. -/ +noncomputable def selectActive : List (SetPatch A) → Ω → Fin n → ℝ → Prop + | [],ω,i,H => (A.activity ω).active i H + | P::L,ω,i,H => if H ∈ P.domain i then P.active ω i H else selectActive L ω i H + +lemma selectActive_old (L : List (SetPatch A)) (ω : Ω) (i : Fin n) (H : ℝ) + (h : ∀ P ∈ L, H ∈ P.domain i → (P.active ω i H ↔ (A.activity ω).active i H)) : + selectActive L ω i H ↔ (A.activity ω).active i H := by + induction L with + | nil => rfl + | cons P L ih => + dsimp only [selectActive] + split_ifs with hi + · exact h P (List.mem_cons_self) hi + · exact ih (fun Q hQ => h Q (List.mem_cons_of_mem P hQ)) + +lemma exists_batch (L : List (SetPatch A)) (hL : L.Pairwise UnchangedOverlap) : + ∃ B : SetSystem M Ω μ, ∀ ω i H, (B.activity ω).active i H ↔ selectActive L ω i H := by + induction L with + | nil => exact ⟨A,fun _ _ _ => Iff.rfl⟩ + | cons P L ih => + obtain ⟨hPL,hL⟩ := List.pairwise_cons.mp hL + obtain ⟨B,hB⟩ := ih hL + have hB0 (ω i H) (hi : H ∈ P.domain i) : + (B.activity ω).active i H ↔ (A.activity ω).active i H := by + rw [hB] + exact selectActive_old L ω i H (fun Q hQ hj => (hPL Q hQ ω i H hi hj).2) + refine ⟨(P.rebase B hB0).apply,?_⟩ + intro ω i H + by_cases hi : H ∈ P.domain i + · exact ((P.rebase B hB0).inside hi ω).trans (by simp only [selectActive,ite_eq_left hi,rebase]) + · exact ((P.rebase B hB0).unchanged hi ω).trans (by simpa only [selectActive,ite_eq_right hi] using hB ω i H) + +noncomputable def batch (L : List (SetPatch A)) (hL : L.Pairwise UnchangedOverlap) : SetSystem M Ω μ := + (exists_batch L hL).choose + +lemma batch_active (L : List (SetPatch A)) (hL : L.Pairwise UnchangedOverlap) (ω i H) : + ((batch L hL).activity ω).active i H ↔ selectActive L ω i H := + (exists_batch L hL).choose_spec ω i H + +lemma selectActive_choice (L : List (SetPatch A)) (i : Fin n) (H : ℝ) : + (∀ ω, selectActive L ω i H ↔ (A.activity ω).active i H) ∨ + ∃ P ∈ L, ∀ ω, selectActive L ω i H ↔ (P.apply.activity ω).active i H := by + induction L with + | nil => exact Or.inl (fun _ => Iff.rfl) + | cons P L ih => + by_cases hi : H ∈ P.domain i + · right + refine ⟨P,List.mem_cons_self,?_⟩ + intro ω + simpa only [selectActive,ite_eq_left hi] using (P.inside hi ω).symm + · rcases ih with h | ⟨Q,hQ,h⟩ + · left + intro ω + simpa only [selectActive,ite_eq_right hi] using h ω + · right + refine ⟨Q,List.mem_cons_of_mem P hQ,?_⟩ + intro ω + simpa only [selectActive,ite_eq_right hi] using h ω + +/-- Simultaneous disjoint main clipping has the one-patch movement bound, +not the sum over cells. Covers all points, not just the listed vertices. -/ +lemma batch_movement (L : List (SetPatch A)) (hL : L.Pairwise UnchangedOverlap) + {b : ℝ} (hb : 0 ≤ b) + (hp : ∀ P ∈ L, ∀ i H, (∫ ω, |(P.apply.activity ω).indicator i H-(A.activity ω).indicator i H| ∂μ) ≤ b) + (i : Fin n) (H : ℝ) : + (∫ ω, |((batch L hL).activity ω).indicator i H-(A.activity ω).indicator i H| ∂μ) ≤ b := by + rcases selectActive_choice L i H with h | ⟨P,hP,h⟩ + · have he : (fun ω => |((batch L hL).activity ω).indicator i H-(A.activity ω).indicator i H|) = + fun _ => 0 := by + funext ω + simp only [Activity.indicator,batch_active,h,sub_self,abs_zero] + rw [he,integral_zero] + exact hb + · have he : (fun ω => |((batch L hL).activity ω).indicator i H-(A.activity ω).indicator i H|) = + fun ω => |(P.apply.activity ω).indicator i H-(A.activity ω).indicator i H| := by + funext ω + simp only [Activity.indicator,batch_active,h] + rw [he] + exact hp P hP i H + +lemma batch_movement_integrable (L : List (SetPatch A)) (hL : L.Pairwise UnchangedOverlap) + (hp : ∀ P ∈ L, ∀ i H, Integrable + (fun ω => (P.apply.activity ω).indicator i H-(A.activity ω).indicator i H) μ) + (i : Fin n) (H : ℝ) : Integrable + (fun ω => ((batch L hL).activity ω).indicator i H-(A.activity ω).indicator i H) μ := by + rcases selectActive_choice L i H with h | ⟨P,hP,h⟩ + · have he : (fun ω => ((batch L hL).activity ω).indicator i H-(A.activity ω).indicator i H) = + fun _ => 0 := by + funext ω + simp only [Activity.indicator,batch_active,h,sub_self] + rw [he] + exact integrable_zero _ _ _ + · have he : (fun ω => ((batch L hL).activity ω).indicator i H-(A.activity ω).indicator i H) = + fun ω => (P.apply.activity ω).indicator i H-(A.activity ω).indicator i H := by + funext ω + simp only [Activity.indicator,batch_active,h] + rw [he] + exact hp P hP i H + +end PlanarL1.Columns.Model.SetPatch + + +namespace PlanarL1.Columns.Model.SetPatch +open MeasureTheory Set +attribute [local instance] Classical.propDecidable +variable {n : ℕ} {M : Model n} {Ω : Type*} [MeasurableSpace Ω] {μ : Measure Ω} + {A : SetSystem M Ω μ} + +lemma selectActive_inside (L : List (SetPatch A)) (hL : L.Pairwise UnchangedOverlap) + {P : SetPatch A} (hP : P ∈ L) (ω i H) (hi : H ∈ P.domain i) : + selectActive L ω i H ↔ P.active ω i H := by + induction L with + | nil => simp only [List.not_mem_nil] at hP + | cons Q L ih => + obtain ⟨hQL,hL⟩ := List.pairwise_cons.mp hL + rcases List.mem_cons.mp hP with hP | hP + · subst P + simp only [selectActive,ite_eq_left hi] + · by_cases hj : H ∈ Q.domain i + · simp only [selectActive,ite_eq_left hj] + exact (hQL P hP ω i H hj hi).1.trans (hQL P hP ω i H hj hi).2.symm + · simpa only [selectActive,ite_eq_right hj] using ih hL hP + +lemma batch_inside (L : List (SetPatch A)) (hL : L.Pairwise UnchangedOverlap) + {P : SetPatch A} (hP : P ∈ L) (ω i H) (hi : H ∈ P.domain i) : + ((batch L hL).activity ω).active i H ↔ (P.apply.activity ω).active i H := + (batch_active L hL ω i H).trans ((selectActive_inside L hL hP ω i H hi).trans + (P.inside hi ω).symm) + +lemma batch_old (L : List (SetPatch A)) (hL : L.Pairwise UnchangedOverlap) + (ω i H) (hp : ∀ P ∈ L, (P.apply.activity ω).active i H ↔ (A.activity ω).active i H) : + ((batch L hL).activity ω).active i H ↔ (A.activity ω).active i H := by + apply (batch_active L hL ω i H).trans + exact selectActive_old L ω i H (fun P hP hi => (P.inside hi ω).symm.trans (hp P hP)) +end PlanarL1.Columns.Model.SetPatch + + +end + +end OAI diff --git a/lean/OAI/Combinatorics/PlanarL1/Growth.lean b/lean/OAI/Combinatorics/PlanarL1/Growth.lean new file mode 100644 index 0000000000000000000000000000000000000000..81c7daea1b3b305dc17851afade380b857dd1808 --- /dev/null +++ b/lean/OAI/Combinatorics/PlanarL1/Growth.lean @@ -0,0 +1,945 @@ +import OAI.Combinatorics.PlanarL1.Stem + +namespace OAI + +section + + + +namespace PlanarL1.Topology +open Set Metric Filter +variable {V W : Type} [LinearOrder V] [Finite V] [LinearOrder W] [Finite W] + [LinearOrder (V⊕W)] {G : SimpleGraph V} {B : Set V} + +/-- After processing a frontier vertex, the old remaining ports and all its +new children are the frontier. -/ +def starPorts (B : Set V) (v : V) : Set (V⊕W) := + {w | Sum.elim (fun u => u∈B ∧ u≠v) (fun _ => True) w} + +namespace DiskCore +variable (C : DiskCore G B) {target : V → ℂ} + +lemma grow_star (E : ExteriorPorts C.drawing.point target B C.disk) + (hleaf : ∀ w∈B, ∀ u u', G.Adj w u → G.Adj w u' → u=u') + {v : V} (hv : v∈B) {K : Set ℂ} (hK : IsClosed K) + (hCK : Disjoint (closure C.disk) K) (hEK : Disjoint (E.region v) K) + (hsegE : segment ℝ (C.drawing.point v) (target v) ⊆ E.region v) + (hrad : C.drawing.point v∈segment ℝ C.center (target v)) + (child : W → ℂ) (n : W → ℕ) + (P : ∀ w, SegmentChain Set.univ (target v) (child w) (n w+1)) + (hP : ∀ w, (P w).IsSimple) + (hPC : ∀ w, Disjoint (closure C.disk) (P w).trace) + (hPE : ∀ w u, u∈B → ∀ z∈(P w).trace, z∈E.region u → u=v ∧ z=target v) + (hPP : ∀ w w', w≠w' → ∀ z∈(P w).trace, z∈(P w').trace → z=target v) + (hPK : ∀ w, ∀ z∈(P w).trace, z∈K → z=child w) + (hotherK : ∀ u∈B, ∀ z∈E.region u, z∈K → z=target u) : + ∃ C' : DiskCore (leafExtension (W := W) G v) (starPorts B v), + ∃ E' : ExteriorPorts C'.drawing.point (Sum.elim target child) (starPorts B v) C'.disk, + C'.drawing.point (.inl v)=target v ∧ + Disjoint (closure C'.disk) K ∧ + (∀ w∈starPorts B v, ∀ z∈E'.region w, z∈K → z=Sum.elim target child w) := by + classical + let m (w : W) := target v+(1/2:ℝ)•((P w).vertex 1-target v) + have hm (w : W) : m w∈segment ℝ (target v) ((P w).vertex 1) := by + rw [segment_eq_image' ℝ]; exact ⟨1/2,by norm_num,rfl⟩ + let U (w : W) := ((P w).cutFirst (m w) (hm w)).trace + have hUsub (w : W) : U w ⊆ (P w).trace := (P w).cutFirst_subset _ _ + have hyU (w : W) : target v∉U w := (P w).cut_avoids_start (hP w) (by norm_num) (by norm_num) + let F := K ∪ (⋃ w, U w) ∪ ⋃ u : {u // u∈B ∧ u≠v}, E.region u + have hF : IsClosed F := (hK.union (isClosed_iUnion_of_finite + (fun w => ((P w).cutFirst _ _).trace_compact.isClosed))).union + (isClosed_iUnion_of_finite (fun u => (E.compact u u.property.1).isClosed)) + have hdisj : Disjoint (segment ℝ C.center (target v)) F := by + rw [segment_split hrad] + apply Disjoint.union_left + · apply Set.disjoint_left.mpr + intro z hz hzF + rcases hzF with (hzK|hzU)|hzE + · exact Set.disjoint_left.mp hCK (C.spoke_subset hz) hzK + · obtain ⟨w,hw⟩ := Set.mem_iUnion.mp hzU + exact Set.disjoint_left.mp (hPC w) (C.spoke_subset hz) (hUsub w hw) + · obtain ⟨u,hu⟩ := Set.mem_iUnion.mp hzE + exact Set.disjoint_left.mp (E.spoke_disjoint C.drawing.point_injective C.convex + C.isOpen C.center_mem C.port hv u.property.1 (Ne.symm u.property.2)) hz hu + · apply Set.disjoint_left.mpr + intro z hz hzF + rcases hzF with (hzK|hzU)|hzE + · exact Set.disjoint_left.mp hEK (hsegE hz) hzK + · obtain ⟨w,hw⟩ := Set.mem_iUnion.mp hzU + exact hyU w ((hPE w v hv z (hUsub w hw) (hsegE hz)).2 ▸ hw) + · obtain ⟨u,hu⟩ := Set.mem_iUnion.mp hzE + exact Set.disjoint_left.mp (E.disjoint v hv u u.property.1 (Ne.symm u.property.2)) (hsegE hz) hu + obtain ⟨T,hT,hTop,hTb,hseg,hd⟩ := convex_tube_avoiding hF hdisj + have hyT : target v∈T := hseg (right_mem_segment ℝ _ _) + have hxT : C.drawing.point v∈T := hseg hrad + have haT : C.center∈T := hseg (left_mem_segment ℝ _ _) + have htail (w : W) : Disjoint (closure T) (P w).tail.trace := by + apply hd.mono_right + intro z hz + apply Or.inl; apply Or.inr; apply Set.mem_iUnion.mpr + refine ⟨w,?_⟩ + change z∈((P w).cutFirst _ _).trace + rw [(P w).cutFirst_trace]; exact Or.inr hz + choose q hq hqfr hqne hqny hqin using fun w => + (P w).exit_frontier (hP w) hT hTop hyT (htail w) + let A (w : W) := (P w).cutFirst (q w) (hq w) + have hAsub (w : W) : (A w).trace ⊆ (P w).trace := (P w).cutFirst_subset _ _ + have hother (u : V) (hu : u∈B) (he : u≠v) : Disjoint (closure T) (E.region u) := + hd.mono_right (fun z hz => Or.inr (Set.mem_iUnion.mpr ⟨⟨u,hu,he⟩,hz⟩)) + obtain ⟨Q,hQ⟩ := C.drawing.retube_at C.convex C.isOpen C.center_mem C.bounded + C.point_mem C.trace_mem C.port hleaf hv hT hTop haT hxT (subset_closure hyT) + (fun u hu he hz => Set.disjoint_left.mp (hother u hu he) hz (E.start u hu)) + (fun z hz hzS => E.inside v hv z (hsegE hz) hzS) + let arm (w : W) := segment ℝ (target v) (q w) + have harm (w : W) : arm w ⊆ (P w).trace := + ((convex_segment (target v) ((P w).vertex 1)).segment_subset (left_mem_segment ℝ _ _) (hq w)).trans + (P w).first_segment_subset + have harmT (w : W) : arm w ⊆ closure T := + hT.closure.segment_subset (subset_closure hyT) (frontier_subset_closure (hqfr w)) + have hmeet (w : W) (z : ℂ) (hz : z∈closure C.disk ∪ segment ℝ (C.drawing.point v) (target v)) + (hzP : z∈(P w).trace) : z=target v := by + rcases hz with hz|hz + · exact False.elim (Set.disjoint_left.mp (hPC w) hz hzP) + · exact (hPE w v hv z hzP (hsegE hz)).2 + have hvertex (w : W) (u : V) (hu : Q.point u∈arm w) : u=v := + Q.point_injective ((hmeet w _ (hQ.point_control u) (harm w hu)).trans hQ.selected.symm) + have hcross (w : W) (u x : V) (hux : G.Adj u x) (z : ℂ) + (hz : z∈arm w) (hz' : z∈Q.region u x) : z=Q.point v := by + rw [Q.region_eq u x hux] at hz' + exact (hmeet w z (hQ.trace_control _ hz') (harm w hz)).trans hQ.selected.symm + obtain ⟨R,hpR,hrR⟩ := Q.attachLeaves v q arm + (fun w => by rw [hQ.selected]; exact hqny w) + (fun w => hQ.selected.symm ▸ left_mem_segment ℝ _ _) + (fun w => right_mem_segment ℝ _ _) + (fun w => hQ.selected.symm ▸ Relation.ReflTransGen.single Set.Subset.rfl) + hvertex + (fun w w' hww z hz hz' => (hPP w w' hww z (harm w hz) (harm w' hz')).trans hQ.selected.symm) + hcross + have hpold (u : V) : R.point (.inl u)=Q.point u := congrFun hpR (.inl u) + have hpnew (w : W) : R.point (.inr w)=q w := congrFun hpR (.inr w) + let C' : DiskCore (leafExtension (W := W) G v) (starPorts B v) := { + drawing := R + disk := T + center := target v + convex := hT + isOpen := hTop + bounded := hTb + center_mem := hyT + point_mem := by + intro u; cases u with + | inl u => rw [hpold]; exact hQ.point_mem u + | inr w => rw [hpnew]; exact frontier_subset_closure (hqfr w) + trace_mem := by + intro d z hz + have hh := hrR d hz + rcases d with ⟨⟨⟨u,x⟩,hux⟩,hord⟩ + cases u <;> cases x <;> simp only [PLDrawing.starRegion] at hh + case inl.inl u x => + rw [Q.region_eq u x hux] at hh + exact hQ.trace_mem _ hh + case inl.inr u w => exact harmT w hh + case inr.inl w u => exact harmT w hh + case inr.inr w w' => exact False.elim hh + port := by + intro u hu; cases u with + | inl u => rw [hpold]; exact hQ.on_frontier u hu.1 hu.2 + | inr w => rw [hpnew]; exact hqfr w } + let E₀ := E.update (PortFrame.ofMove hQ) C.drawing.point_injective C.port hv hother + isCompact_singleton (show target v∈({target v}:Set ℂ) from rfl) + (Set.singleton_subset_iff.mpr (E.end_mem v hv)) + (fun z hz _ => hz) (Relation.ReflTransGen.refl) + have hEold (u : V) (he : u≠v) : + E₀.region u=segment ℝ (Q.point u) (C.drawing.point u) ∪ E.region u := by + simp [E₀,ExteriorPorts.update,ExteriorPorts.updatedRegion,he] + have hEarm (u : V) (hu : u∈B) (he : u≠v) (w : W) : + Disjoint (E₀.region u) (A w).trace := by + rw [hEold u he] + apply Disjoint.union_left + · exact (hPC w).mono (hQ.tail_old u hu he) (hAsub w) + · apply Set.disjoint_left.mpr + intro z hz hz' + exact he (hPE w u hu z (hAsub w hz') hz).1 + have hyA (w : W) : target v∉(A w).trace := by + intro hy + exact hqny w (hqin w _ hy (subset_closure hyT)).symm + let E' : ExteriorPorts C'.drawing.point (Sum.elim target child) (starPorts B v) C'.disk := { + region := Sum.elim E₀.region (fun w => (A w).trace) + compact := by + intro u hu; cases u with + | inl u => exact E₀.compact u hu.1 + | inr w => exact (A w).trace_compact + start := by + intro u hu; cases u with + | inl u => change R.point (.inl u)∈E₀.region u; rw [hpold]; exact E₀.start u hu.1 + | inr w => change R.point (.inr w)∈(A w).trace; rw [hpnew]; exact (A w).start_mem_trace + joined := by + intro u hu; cases u with + | inl u => change PolygonallyJoined (E₀.region u) (R.point (.inl u)) (target u) + rw [hpold]; exact E₀.joined u hu.1 + | inr w => change PolygonallyJoined (A w).trace (R.point (.inr w)) (child w) + rw [hpnew]; exact (A w).joined_trace + inside := by + intro u hu z hz hzT; cases u with + | inl u => change z=R.point (.inl u); rw [hpold]; exact E₀.inside u hu.1 z hz hzT + | inr w => change z=R.point (.inr w); rw [hpnew]; exact hqin w z hz hzT + disjoint := by + intro u hu x hx hux + cases u with + | inl u => cases x with + | inl x => exact E₀.disjoint u hu.1 x hx.1 (fun he => hux (congrArg Sum.inl he)) + | inr w => exact hEarm u hu.1 hu.2 w + | inr w => cases x with + | inl u => exact (hEarm u hx.1 hx.2 w).symm + | inr w' => + apply Set.disjoint_left.mpr + intro z hz hz' + exact hyA w ((hPP w w' (fun he => hux (congrArg Sum.inr he)) z (hAsub w hz) (hAsub w' hz')) ▸ hz) } + refine ⟨C',E',(hpold v).trans hQ.selected,hd.mono_right (fun z hz => Or.inl (Or.inl hz)),?_⟩ + intro u hu z hz hzK + cases u with + | inl u => + change z∈E₀.region u at hz + rw [hEold u hu.2] at hz + rcases hz with hz|hz + · exact False.elim (Set.disjoint_left.mp hCK (hQ.tail_old u hu.1 hu.2 hz) hzK) + · exact hotherK u hu.1 z hz hzK + | inr w => exact hPK w z (hAsub w hz) hzK + +end DiskCore +end PlanarL1.Topology + + + + +namespace PlanarL1.HeightTree +open Set +variable {V : Type} (T : HeightTree V) + +lemma parent_ne {v : V} (hv : v≠T.root) : T.parent v≠v := by + intro he + have hh := T.step_depth (show T.Step (T.parent v) v from ⟨hv,rfl⟩) + rw [he] at hh + exact lt_irrefl _ hh + +lemma step_ne {u v : V} (h : T.Step u v) : u≠v := by + exact h.2 ▸ T.parent_ne h.1 + +/-- Vertices already absorbed into the disk form a parent-closed set. -/ +def ParentClosed (S : Finset V) : Prop := ∀ v∈S, T.parent v∈S + +def Frontier (S : Finset V) (v : V) : Prop := v∉S ∧ T.parent v∈S + +def Scope (S : Finset V) (v : V) : Prop := v∈S ∨ T.Frontier S v + +lemma frontier_ne_root {S : Finset V} {v : V} (hv : T.Frontier S v) : v≠T.root := by + intro he; subst v + exact hv.1 (T.at_root ▸ hv.2) + +lemma scope_parent {S : Finset V} (hS : T.ParentClosed S) {v : V} (hv : T.Scope S v) : T.parent v∈S := by + exact hv.elim (hS v) And.right + +lemma frontier_neighbor {S : Finset V} (hS : T.ParentClosed S) {v u : V} + (hv : T.Frontier S v) (hu : T.Scope S u) (hvu : T.graph.Adj v u) : u=T.parent v := by + rcases hvu with h|h + · exact False.elim (hv.1 (h.2.symm ▸ T.scope_parent hS hu)) + · exact h.2 + +lemma frontier_leaf {S : Finset V} (hS : T.ParentClosed S) {v : {v // T.Scope S v}} + (hv : T.Frontier S v.val) (u u' : {v // T.Scope S v}) + (hu : (SimpleGraph.comap Subtype.val T.graph).Adj v u) + (hu' : (SimpleGraph.comap Subtype.val T.graph).Adj v u') : u=u' := by + exact Subtype.ext ((T.frontier_neighbor hS hv u.property hu).trans + (T.frontier_neighbor hS hv u'.property hu').symm) + +lemma child_out {S : Finset V} (hS : T.ParentClosed S) {v w : V} + (hv : T.Frontier S v) (hw : T.Step v w) : ¬T.Scope S w := by + intro h + exact hv.1 (hw.2.symm ▸ T.scope_parent hS h) + +variable [DecidableEq V] + +lemma insert_closed {S : Finset V} (hS : T.ParentClosed S) {v : V} (hv : T.Frontier S v) : + T.ParentClosed (insert v S) := by + classical + intro w hw + rcases Finset.mem_insert.mp hw with rfl|hw + · exact Finset.mem_insert_of_mem hv.2 + · exact Finset.mem_insert_of_mem (hS w hw) + +lemma frontier_insert {S : Finset V} (hS : T.ParentClosed S) {v w : V} (hv : T.Frontier S v) : + T.Frontier (insert v S) w ↔ (T.Frontier S w ∧ w≠v) ∨ T.Step v w := by + classical + simp only [Frontier,Finset.mem_insert,not_or] at * + constructor + · rintro ⟨⟨hwv,hwS⟩,hp⟩ + rcases hp with hp|hp + · exact Or.inr ⟨fun he => by subst w; rw [T.at_root] at hp; exact hwv hp,hp.symm⟩ + · exact Or.inl ⟨⟨hwS,hp⟩,hwv⟩ + · rintro (⟨⟨hwS,hp⟩,hwv⟩|hw) + · exact ⟨⟨hwv,hwS⟩,Or.inr hp⟩ + · exact ⟨⟨Ne.symm (T.step_ne hw),fun hwS => + hv.1 (hw.2.symm ▸ hS w hwS)⟩,Or.inl hw.2.symm⟩ + +lemma scope_insert {S : Finset V} (hS : T.ParentClosed S) {v w : V} (hv : T.Frontier S v) : + T.Scope (insert v S) w ↔ T.Scope S w ∨ T.Step v w := by + classical + rw [Scope,T.frontier_insert hS hv] + constructor + · rintro (h|h) + · rcases Finset.mem_insert.mp h with rfl|h + · exact Or.inl (Or.inr hv) + · exact Or.inl (Or.inl h) + · exact h.elim (fun h => Or.inl (Or.inr h.1)) Or.inr + · rintro (h|h) + · rcases h with h|h + · exact Or.inl (Finset.mem_insert_of_mem h) + · by_cases he : w=v + · exact Or.inl (Finset.mem_insert.mpr (Or.inl he)) + · exact Or.inr (Or.inl ⟨h,he⟩) + · exact Or.inr (Or.inr h) + +omit [DecidableEq V] in +lemma old_child_adj {S : Finset V} (hS : T.ParentClosed S) {v u w : V} + (hv : T.Frontier S v) (hu : T.Scope S u) (hw : T.Step v w) : + T.graph.Adj u w ↔ u=v := by + constructor + · rintro (h|h) + · exact h.2.trans hw.2.symm + · exact False.elim (T.child_out hS hv hw (Or.inl (h.2 ▸ T.scope_parent hS hu))) + · intro he; subst u; exact Or.inl hw + +omit [DecidableEq V] in +lemma children_not_adj {v u w : V} (hu : T.Step v u) (hw : T.Step v w) : + ¬T.graph.Adj u w := by + rintro (h|h) + · exact T.step_ne hu (h.2.trans hw.2.symm).symm + · exact T.step_ne hw (h.2.trans hu.2.symm).symm + +noncomputable def extensionMap {S : Finset V} (v : V) : + ({u // T.Scope S u} ⊕ {w // T.Step v w}) → V := Sum.elim Subtype.val Subtype.val + +omit [DecidableEq V] in +lemma extensionMap_injective {S : Finset V} (hS : T.ParentClosed S) {v : V} (hv : T.Frontier S v) : + Function.Injective (T.extensionMap (S := S) v) := by + intro a b he + cases a with + | inl a => cases b with + | inl b => exact congrArg Sum.inl (Subtype.ext he) + | inr b => + change a.val=b.val at he + exact False.elim (T.child_out hS hv b.property (he ▸ a.property)) + | inr a => cases b with + | inl b => + change a.val=b.val at he + exact False.elim (T.child_out hS hv a.property (he.symm ▸ b.property)) + | inr b => exact congrArg Sum.inr (Subtype.ext he) + +noncomputable def extensionEquiv {S : Finset V} (hS : T.ParentClosed S) {v : V} (hv : T.Frontier S v) : + ({u // T.Scope S u} ⊕ {w // T.Step v w}) ≃ {u // T.Scope (insert v S) u} := + Equiv.ofBijective (fun a => ⟨T.extensionMap v a,by + apply (T.scope_insert hS hv).mpr + cases a with + | inl a => exact Or.inl a.property + | inr a => exact Or.inr a.property⟩) ⟨ + fun a b h => T.extensionMap_injective hS hv (congrArg Subtype.val h),by + intro a + rcases (T.scope_insert hS hv).mp a.property with h|h + · exact ⟨.inl ⟨a.val,h⟩,rfl⟩ + · exact ⟨.inr ⟨a.val,h⟩,rfl⟩⟩ + +lemma extension_graph {S : Finset V} (hS : T.ParentClosed S) {v : V} (hv : T.Frontier S v) : + Topology.leafExtension (W := {w // T.Step v w}) + (SimpleGraph.comap Subtype.val T.graph) (⟨v,Or.inr hv⟩:{u // T.Scope S u}) = + SimpleGraph.comap (T.extensionEquiv hS hv) + (SimpleGraph.comap Subtype.val T.graph) := by + ext a b + cases a with + | inl a => cases b with + | inl b => rfl + | inr b => + change (a=⟨v,Or.inr hv⟩) ↔ T.graph.Adj a.val b.val + rw [T.old_child_adj hS hv a.property b.property] + exact Subtype.ext_iff + | inr a => cases b with + | inl b => + change (b=⟨v,Or.inr hv⟩) ↔ T.graph.Adj a.val b.val + rw [T.graph.adj_comm,T.old_child_adj hS hv b.property a.property] + exact Subtype.ext_iff + | inr b => + exact iff_false_intro (T.children_not_adj a.property b.property) |>.symm + +lemma extension_ports {S : Finset V} (hS : T.ParentClosed S) {v : V} (hv : T.Frontier S v) + (a : {u // T.Scope S u} ⊕ {w // T.Step v w}) : + a∈Topology.starPorts {w : {u // T.Scope S u} | T.Frontier S w.val} ⟨v,Or.inr hv⟩ ↔ + T.Frontier (insert v S) (T.extensionEquiv hS hv a).val := by + rw [T.frontier_insert hS hv] + cases a with + | inl a => + change (T.Frontier S a.val ∧ a≠⟨v,Or.inr hv⟩) ↔ + (T.Frontier S a.val ∧ a.val≠v) ∨ T.Step v a.val + have ha : ¬T.Step v a.val := fun h => T.child_out hS hv h a.property + simp only [ha,or_false,ne_eq,Subtype.ext_iff] + | inr a => + exact iff_true_intro (Or.inr a.property) |>.symm + +end PlanarL1.HeightTree + + + + +namespace PlanarL1.Topology +open Set +variable {V W : Type} [LinearOrder V] [LinearOrder W] + {G : SimpleGraph V} {H : SimpleGraph W} + +lemma PLDrawing.pullback (P : PLDrawing G) (f : W → V) (hf : Function.Injective f) + (hG : ∀ u v, H.Adj u v → G.Adj (f u) (f v)) : + ∃ Q : PLDrawing H, Q.point=P.point ∘ f ∧ + ∀ d, (Q.chain d).trace ⊆ P.region (f d.val.fst) (f d.val.snd) := by + apply PLDrawing.ofSymmetricRegions (P.point ∘ f) (P.point_injective.comp hf) + (fun u v => P.region (f u) (f v)) + · intro u v h; exact P.region_start _ _ (hG u v h) + · intro u v h; exact P.region_joined _ _ (hG u v h) + · intro u v h w hw + exact (P.region_vertex _ _ (hG u v h) _ hw).elim (fun he => Or.inl (hf he)) (fun he => Or.inr (hf he)) + · intro u v w x h h' hne z hz hz' + exact P.region_intersect _ _ _ _ (hG u v h) (hG w x h') + (fun he => hne (he.elim (fun h => Or.inl ⟨hf h.1,hf h.2⟩) + (fun h => Or.inr ⟨hf h.1,hf h.2⟩))) hz hz' + +noncomputable def ExteriorPorts.retarget {p t : V → ℂ} {B : Set V} {S : Set ℂ} + (E : ExteriorPorts p t B S) (t' : V → ℂ) (ht : ∀ w, t w=t' w) : + ExteriorPorts p t' B S := { + region := E.region + compact := E.compact + start := E.start + joined := fun w hw => by rw [← ht w]; exact E.joined w hw + inside := E.inside + disjoint := E.disjoint } + +namespace DiskCore +variable {B : Set V} (C : DiskCore G B) {target : V → ℂ} + +lemma region_mem (u v : V) (h : G.Adj u v) : C.drawing.region u v ⊆ closure C.disk := by + rw [C.drawing.region_eq u v h] + exact C.trace_mem _ + +/-- Relabel an actual core and all exterior paths along an injective graph map. +No drawing or disk existence is assumed beyond the supplied core. -/ +lemma pullback (E : ExteriorPorts C.drawing.point target B C.disk) + (f : W → V) (hf : Function.Injective f) + (hG : ∀ u v, H.Adj u v → G.Adj (f u) (f v)) + {B' : Set W} (hB : ∀ w∈B', f w∈B) : + ∃ C' : DiskCore H B', ∃ E' : ExteriorPorts C'.drawing.point (target ∘ f) B' C'.disk, + C'.disk=C.disk ∧ (∀ w, C'.drawing.point w=C.drawing.point (f w)) ∧ + (∀ w, E'.region w=E.region (f w)) := by + obtain ⟨Q,hQ,hsub⟩ := C.drawing.pullback f hf hG + let C' : DiskCore H B' := ⟨Q,C.disk,C.center,C.convex,C.isOpen,C.bounded,C.center_mem, + (fun w => by rw [hQ]; exact C.point_mem (f w)), + (fun d => (hsub d).trans (C.region_mem _ _ (hG _ _ d.val.adj))), + (fun w hw => by rw [hQ]; exact C.port (f w) (hB w hw))⟩ + let E' : ExteriorPorts C'.drawing.point (target ∘ f) B' C'.disk := { + region := fun w => E.region (f w) + compact := fun w hw => E.compact (f w) (hB w hw) + start := fun w hw => by change Q.point w∈_; rw [hQ]; exact E.start (f w) (hB w hw) + joined := fun w hw => by change PolygonallyJoined _ (Q.point w) _; rw [hQ]; exact E.joined (f w) (hB w hw) + inside := fun w hw z hz hz' => by + change z=Q.point w; rw [hQ]; exact E.inside (f w) (hB w hw) z hz hz' + disjoint := fun w hw u hu hne => E.disjoint (f w) (hB w hw) (f u) (hB u hu) (hf.ne hne) } + exact ⟨C',E',rfl,(fun w => congrFun hQ w),fun _ => rfl⟩ + +end DiskCore +end PlanarL1.Topology + + + + +namespace PlanarL1.Topology.PLDrawing +open Set +variable {V : Type} [LinearOrder V] {G : SimpleGraph V} (P : PLDrawing G) + +def carrier (S : Set V) : Set ℂ := + (⋃ v : S, {P.point v.val}) ∪ ⋃ u : S, ⋃ v : S, P.region u.val v.val + +lemma point_mem_carrier {S : Set V} {v : V} (hv : v∈S) : P.point v∈P.carrier S := + Or.inl (mem_iUnion.mpr ⟨⟨v,hv⟩,rfl⟩) + +lemma region_mem_carrier {S : Set V} {u v : V} (hu : u∈S) (hv : v∈S) : + P.region u v ⊆ P.carrier S := fun _ hz => + Or.inr (mem_iUnion.mpr ⟨⟨u,hu⟩,mem_iUnion.mpr ⟨⟨v,hv⟩,hz⟩⟩) + +lemma carrier_mono {S T : Set V} (h : S ⊆ T) : P.carrier S ⊆ P.carrier T := by + rintro z (hz|hz) + · obtain ⟨v,hv⟩ := mem_iUnion.mp hz + rcases hv with rfl + exact P.point_mem_carrier (h v.property) + · obtain ⟨u,hu⟩ := mem_iUnion.mp hz + obtain ⟨v,hv⟩ := mem_iUnion.mp hu + exact P.region_mem_carrier (h u.property) (h v.property) hv + +lemma carrier_compact [Finite V] (S : Set V) : IsCompact (P.carrier S) := + (isCompact_iUnion (fun _ => isCompact_singleton)).union + (isCompact_iUnion (fun u => isCompact_iUnion (fun v => P.region_compact u.val v.val))) + +lemma region_adj {u v : V} {z : ℂ} (hz : z∈P.region u v) : G.Adj u v := by + classical + by_contra h + simp [region,h] at hz + +lemma point_carrier_iff {S : Set V} {v : V} : P.point v∈P.carrier S ↔ v∈S := by + constructor + · rintro (hz|hz) + · obtain ⟨w,hw⟩ := mem_iUnion.mp hz + exact P.point_injective (mem_singleton_iff.mp hw) ▸ w.property + · obtain ⟨u,hu⟩ := mem_iUnion.mp hz + obtain ⟨w,hw⟩ := mem_iUnion.mp hu + exact (P.region_vertex _ _ (P.region_adj hw) v hw).elim + (fun he => he ▸ u.property) (fun he => he ▸ w.property) + · exact P.point_mem_carrier + +lemma region_carrier_intersection {S : Set V} {u v : V} (h : G.Adj u v) + (hu : u∉S) {z : ℂ} (hz : z∈P.region u v) (hzS : z∈P.carrier S) : + z=P.point v := by + rcases hzS with hzS|hzS + · obtain ⟨w,hw⟩ := mem_iUnion.mp hzS + have he := mem_singleton_iff.mp hw + rw [he] at hz + rcases P.region_vertex _ _ h w.val hz with he'|he' + · exact False.elim (hu (he' ▸ w.property)) + · exact he.trans (congrArg P.point he') + · obtain ⟨w,hw⟩ := mem_iUnion.mp hzS + obtain ⟨x,hx⟩ := mem_iUnion.mp hw + have hne : ¬((u=w.val ∧ v=x.val) ∨ (u=x.val ∧ v=w.val)) := by + rintro (he|he) + · exact hu (he.1.symm ▸ w.property) + · exact hu (he.1.symm ▸ x.property) + rcases (P.region_intersect _ _ _ _ h (P.region_adj hx) hne hz hx).1 with he|he + · have : P.point u∈P.carrier S := by rw [← he]; exact P.region_mem_carrier w.property x.property hx + exact False.elim (hu ((P.point_carrier_iff).mp this)) + · exact he + +lemma carrier_disjoint {S T : Set V} (h : Disjoint S T) : + Disjoint (P.carrier S) (P.carrier T) := by + rw [disjoint_left] + intro z hz hz' + rcases hz with hz|hz + · obtain ⟨v,hv⟩ := mem_iUnion.mp hz + rw [mem_singleton_iff.mp hv] at hz' + exact disjoint_left.mp h v.property (P.point_carrier_iff.mp hz') + · obtain ⟨u,hu⟩ := mem_iUnion.mp hz + obtain ⟨v,hv⟩ := mem_iUnion.mp hu + have he := P.region_carrier_intersection (P.region_adj hv) + (fun hu => disjoint_left.mp h u.property hu) hv hz' + rw [he] at hz' + exact disjoint_left.mp h v.property (P.point_carrier_iff.mp hz') + +lemma region_simple_chain {u v : V} (h : G.Adj u v) : + ∃ n : ℕ, ∃ C : SegmentChain Set.univ (P.point u) (P.point v) (n+1), + C.IsSimple ∧ C.trace ⊆ P.region u v := by + obtain ⟨n,C,hC⟩ := (P.region_joined u v h).exists_simple_segmentChain + cases n with + | zero => exact False.elim (h.ne (P.point_injective (C.start.symm.trans C.finish))) + | succ n => exact ⟨n,C.mapSet (subset_univ _),C.mapSet_simple _ hC, + C.trace_subset (P.region_start u v h)⟩ + +end PlanarL1.Topology.PLDrawing + + + + +namespace PlanarL1.HeightTree +open Set PlanarL1.Topology +variable {V : Type} [Fintype V] [LinearOrder V] (T : HeightTree V) + {G : SimpleGraph V} (P : PLDrawing G) + +/-- The raw unprocessed drawing is a fixed closed obstacle at each stage. -/ +def outside (S : Finset V) : Set ℂ := P.carrier {v | v∉S} + +lemma outside_closed (S : Finset V) : IsClosed (outside P S) := + (P.carrier_compact _).isClosed + +omit [Fintype V] in +lemma outside_insert_subset (S : Finset V) (v : V) : + outside P (insert v S) ⊆ outside P S := + P.carrier_mono (fun _ h => fun hw => h (Finset.mem_insert_of_mem hw)) + +omit [Fintype V] in +lemma point_outside_iff (S : Finset V) (v : V) : P.point v∈outside P S ↔ v∉S := + P.point_carrier_iff + +/-- A partially swallowed tree, retaining real residual stems to the original +frontier vertices in the supplied polygonal drawing. -/ +structure Growth (S : Finset V) where + core : DiskCore (SimpleGraph.comap Subtype.val T.graph) + {w : {w // T.Scope S w} | T.Frontier S w.val} + stems : ExteriorPorts core.drawing.point (fun w => P.point w.val) + {w : {w // T.Scope S w} | T.Frontier S w.val} core.disk + avoid : Disjoint (closure core.disk) (outside P S) + contact : ∀ w, T.Frontier S w.val → ∀ z∈stems.region w, + z∈outside P S → z=P.point w.val + +namespace Growth +variable {T P} + +lemma advance {S : Finset V} (hS : T.ParentClosed S) (H : T.Growth P S) + (hG : T.graph ≤ G) {v : V} (hv : T.Frontier S v) : + Nonempty (T.Growth P (insert v S)) := by + classical + let A := {u // T.Scope S u} + let W := {w // T.Step v w} + let a : A := ⟨v,Or.inr hv⟩ + let e := T.extensionEquiv hS hv + let : LinearOrder (A⊕W) := LinearOrder.lift' e e.injective + have hleaf : ∀ w : A, T.Frontier S w.val → ∀ u u', + (SimpleGraph.comap Subtype.val T.graph).Adj w u → + (SimpleGraph.comap Subtype.val T.graph).Adj w u' → u=u' := + fun _ hw _ _ h h' => T.frontier_leaf hS hw _ _ h h' + have htK : P.point v∈outside P S := (point_outside_iff P S v).mpr hv.1 + obtain ⟨C,E,hseg,hrad,hCK,hprotect⟩ := H.core.prepare_stem H.stems hleaf + (v := a) hv (outside_closed P S) H.avoid htK (H.contact a hv) + have hcontact (u : A) (hu : T.Frontier S u.val) (z : ℂ) (hz : z∈E.region u) + (hzK : z∈outside P S) : z=P.point u.val := + H.contact u hu z (hprotect u hu z hz hzK) hzK + have hCK' : Disjoint (closure C.disk) (outside P (insert v S)) := + hCK.mono_right (outside_insert_subset P S v) + have hvn : P.point v∉outside P (insert v S) := by + rw [point_outside_iff]; simp + have hEK' : Disjoint (E.region a) (outside P (insert v S)) := by + rw [disjoint_left]; intro z hz hzK + exact hvn (hcontact a hv z hz (outside_insert_subset P S v hzK) ▸ hzK) + have he (w : W) : G.Adj v w.val := hG (Or.inl w.property) + choose n Q hQ hsub using fun w : W => P.region_simple_chain (he w) + have hout (w : W) : (Q w).trace ⊆ outside P S := + (hsub w).trans (P.region_mem_carrier hv.1 (fun hw => + T.child_out hS hv w.property (Or.inl hw))) + have hPC (w : W) : Disjoint (closure C.disk) (Q w).trace := hCK.mono_right (hout w) + have hPE (w : W) (u : A) (hu : T.Frontier S u.val) (z : ℂ) + (hz : z∈(Q w).trace) (hzE : z∈E.region u) : u=a ∧ z=P.point v := by + have hz' := hcontact u hu z hzE (hout w hz) + have hmem : P.point u.val∈P.region v w.val := hz' ▸ hsub w hz + rcases P.region_vertex _ _ (he w) u.val hmem with hu'|hu' + · exact ⟨Subtype.ext hu',hz'.trans (congrArg P.point hu')⟩ + · exact False.elim (T.child_out hS hv w.property (hu' ▸ u.property)) + have hPP (w w' : W) (hne : w≠w') (z : ℂ) + (hz : z∈(Q w).trace) (hz' : z∈(Q w').trace) : z=P.point v := by + have hne' : ¬((v=v ∧ w.val=w'.val) ∨ (v=w'.val ∧ w.val=v)) := by + rintro (hh|hh) + · exact hne (Subtype.ext hh.2) + · exact (he w).ne hh.2.symm + rcases (P.region_intersect _ _ _ _ (he w) (he w') hne' (hsub w hz) (hsub w' hz')).1 with hh|hh + · exact hh + · have hm : P.point w.val∈P.region v w'.val := hh ▸ hsub w' hz' + rcases P.region_vertex _ _ (he w') w.val hm with hh'|hh' + · exact (he w).ne hh'.symm |>.elim + · exact hne (Subtype.ext hh') |>.elim + have hPK (w : W) (z : ℂ) (hz : z∈(Q w).trace) + (hzK : z∈outside P (insert v S)) : z=P.point w.val := + P.region_carrier_intersection (he w) (by simp) (hsub w hz) hzK + obtain ⟨C₁,E₁,hselected,havoid,hcontact₁⟩ := C.grow_star E hleaf hv + (outside_closed P (insert v S)) hCK' hEK' hseg hrad (fun w : W => P.point w.val) + n Q hQ hPC hPE hPP hPK + (fun u hu z hz hzK => hcontact u hu z hz (outside_insert_subset P S v hzK)) + have hgraph : ∀ u u', (SimpleGraph.comap Subtype.val T.graph).Adj u u' → + (leafExtension (W := W) (SimpleGraph.comap Subtype.val T.graph) a).Adj (e.symm u) (e.symm u') := by + intro u u' h + rw [T.extension_graph hS hv] + change T.graph.Adj (e (e.symm u)).val (e (e.symm u')).val + change T.graph.Adj u.val u'.val at h + simpa only [Equiv.apply_symm_apply] using h + have hports : ∀ w : {u // T.Scope (insert v S) u}, T.Frontier (insert v S) w.val → + e.symm w∈starPorts {u : A | T.Frontier S u.val} a := by + intro w hw + apply (T.extension_ports hS hv (e.symm w)).mpr + change T.Frontier (insert v S) (e (e.symm w)).val + simpa only [Equiv.apply_symm_apply] using hw + obtain ⟨C₂,E₂,hD,hp,hE⟩ := C₁.pullback E₁ e.symm e.symm.injective hgraph hports + have htarget (w : {u // T.Scope (insert v S) u}) : + (Sum.elim (fun u : A => P.point u.val) (fun u : W => P.point u.val) ∘ e.symm) w=P.point w.val := by + have heq := congrArg Subtype.val (e.apply_symm_apply w) + change T.extensionMap v (e.symm w)=w.val at heq + have hm : Sum.elim (fun u : A => P.point u.val) (fun u : W => P.point u.val) (e.symm w)= + P.point (T.extensionMap v (e.symm w)) := by cases e.symm w <;> rfl + exact hm.trans (congrArg P.point heq) + let E₃ := E₂.retarget (fun w => P.point w.val) htarget + refine ⟨⟨C₂,E₃,?_,?_⟩⟩ + · rw [hD]; exact havoid + · intro w hw z hz hzK + have hz' : z∈E₁.region (e.symm w) := (hE w) ▸ hz + exact (hcontact₁ (e.symm w) (hports w hw) z hz' hzK).trans (htarget w) + +end Growth +end PlanarL1.HeightTree + + + + +namespace PlanarL1.HeightTree +open Set +variable {V : Type} (T : HeightTree V) + +lemma singleton_closed : T.ParentClosed {T.root} := by + intro v hv + have he : v=T.root := Finset.mem_singleton.mp hv + subst v + simpa only [T.at_root] using Finset.mem_singleton_self T.root + +lemma frontier_root_iff (v : V) : T.Frontier {T.root} v ↔ T.Step T.root v := by + simp only [Frontier,Finset.mem_singleton,Step] + exact and_congr_right (fun _ => eq_comm) + +lemma scope_root_iff (v : V) : T.Scope {T.root} v ↔ v=T.root ∨ T.Step T.root v := by + rw [Scope,T.frontier_root_iff] + simp only [Finset.mem_singleton] + +noncomputable def rootMap : PUnit ⊕ {w // T.Step T.root w} → V := Sum.elim (fun _ => T.root) Subtype.val + +lemma rootMap_injective : Function.Injective T.rootMap := by + intro a b he + cases a with + | inl a => cases b with + | inl b => exact congrArg Sum.inl (Subsingleton.elim a b) + | inr b => exact False.elim (b.property.1 he.symm) + | inr a => cases b with + | inl b => exact False.elim (a.property.1 he) + | inr b => exact congrArg Sum.inr (Subtype.ext he) + +noncomputable def rootEquiv : (PUnit ⊕ {w // T.Step T.root w}) ≃ {w // T.Scope {T.root} w} := + Equiv.ofBijective (fun a => ⟨T.rootMap a,by + apply (T.scope_root_iff _).mpr + cases a with + | inl a => exact Or.inl rfl + | inr a => exact Or.inr a.property⟩) ⟨ + fun a b h => T.rootMap_injective (congrArg Subtype.val h),by + intro a + rcases (T.scope_root_iff _).mp a.property with h|h + · exact ⟨.inl PUnit.unit,Subtype.ext h.symm⟩ + · exact ⟨.inr ⟨a.val,h⟩,rfl⟩⟩ + +lemma root_graph : + PlanarL1.Topology.leafExtension (W := {w // T.Step T.root w}) (⊥ : SimpleGraph PUnit) PUnit.unit = + SimpleGraph.comap T.rootEquiv (SimpleGraph.comap Subtype.val T.graph) := by + classical + ext a b + cases a with + | inl a => cases b with + | inl b => exact iff_false_intro (fun h : T.graph.Adj T.root T.root => h.ne rfl) |>.symm + | inr b => + change a=PUnit.unit ↔ T.graph.Adj T.root b.val + exact ⟨fun _ => Or.inl b.property,fun _ => Subsingleton.elim _ _⟩ + | inr a => cases b with + | inl b => + change b=PUnit.unit ↔ T.graph.Adj a.val T.root + exact ⟨fun _ => Or.inr a.property,fun _ => Subsingleton.elim _ _⟩ + | inr b => exact iff_false_intro (T.children_not_adj a.property b.property) |>.symm + +lemma root_ports (a : PUnit ⊕ {w // T.Step T.root w}) : + a.isRight ↔ T.Frontier {T.root} (T.rootEquiv a).val := by + rw [T.frontier_root_iff] + cases a with + | inl a => + change (false=true) ↔ T.Step T.root T.root + simp only [Bool.false_eq_true,false_iff] + exact fun h => h.1 rfl + | inr a => + change (true=true) ↔ T.Step T.root a.val + exact ⟨fun _ => a.property,fun _ => rfl⟩ + +end PlanarL1.HeightTree + + + + +namespace PlanarL1.Topology +open Set +variable {W : Type} [LinearOrder W] [Finite W] [LinearOrder (PUnit⊕W)] + +noncomputable def singletonDrawing (y : ℂ) : PLDrawing (⊥ : SimpleGraph PUnit) where + point := fun _ => y + point_injective := fun _ _ _ => Subsingleton.elim _ _ + count := fun d => False.elim d.val.adj + chain := fun d => False.elim d.val.adj + simple := fun d => False.elim d.val.adj + on_vertex := fun d => False.elim d.val.adj + intersect := fun d => False.elim d.val.adj + +/-- The first enclosing disk cuts each outgoing polygonal arm once, leaving +its entire residual trace outside. -/ +lemma star_core (y : ℂ) (child : W → ℂ) (n : W → ℕ) + (P : ∀ w, SegmentChain Set.univ y (child w) (n w+1)) + (hP : ∀ w, (P w).IsSimple) + (hPP : ∀ w w', w≠w' → ∀ z∈(P w).trace, z∈(P w').trace → z=y) + {K : Set ℂ} (hK : IsClosed K) (hyK : y∉K) + (hPK : ∀ w, ∀ z∈(P w).trace, z∈K → z=child w) : + ∃ C : DiskCore (leafExtension (W := W) (⊥ : SimpleGraph PUnit) PUnit.unit) + {w | w.isRight}, + ∃ E : ExteriorPorts C.drawing.point (Sum.elim (fun _ => y) child) {w | w.isRight} C.disk, + C.drawing.point (.inl PUnit.unit)=y ∧ Disjoint (closure C.disk) K ∧ + (∀ w, w.isRight → ∀ z∈E.region w, z∈K → z=Sum.elim (fun _ : PUnit => y) child w) := by + classical + let m (w : W) := y+(1/2:ℝ)•((P w).vertex 1-y) + have hm (w : W) : m w∈segment ℝ y ((P w).vertex 1) := by + rw [segment_eq_image' ℝ]; exact ⟨1/2,by norm_num,rfl⟩ + let U (w : W) := ((P w).cutFirst (m w) (hm w)).trace + have hyU (w : W) : y∉U w := (P w).cut_avoids_start (hP w) (by norm_num) (by norm_num) + let F := K ∪ ⋃ w, U w + have hF : IsClosed F := hK.union (isClosed_iUnion_of_finite + (fun w => ((P w).cutFirst _ _).trace_compact.isClosed)) + have hyF : y∉F := by + rintro (h|h) + · exact hyK h + · obtain ⟨w,hw⟩ := mem_iUnion.mp h; exact hyU w hw + have hdis : Disjoint (segment ℝ y y) F := by simpa only [segment_same] using disjoint_singleton_left.mpr hyF + obtain ⟨T,hT,hTop,hTb,hseg,hd⟩ := convex_tube_avoiding hF hdis + have hyT : y∈T := hseg (left_mem_segment ℝ _ _) + have htail (w : W) : Disjoint (closure T) (P w).tail.trace := by + apply hd.mono_right + intro z hz + apply Or.inr; apply mem_iUnion.mpr; refine ⟨w,?_⟩ + change z∈((P w).cutFirst _ _).trace + rw [(P w).cutFirst_trace]; exact Or.inr hz + choose q hq hqfr hqne hqny hqin using fun w => + (P w).exit_frontier (hP w) hT hTop hyT (htail w) + let A (w : W) := (P w).cutFirst (q w) (hq w) + have hAsub (w : W) : (A w).trace ⊆ (P w).trace := (P w).cutFirst_subset _ _ + let arm (w : W) := segment ℝ y (q w) + have harm (w : W) : arm w ⊆ (P w).trace := + ((convex_segment y ((P w).vertex 1)).segment_subset (left_mem_segment ℝ _ _) (hq w)).trans + (P w).first_segment_subset + have harmT (w : W) : arm w ⊆ closure T := + hT.closure.segment_subset (subset_closure hyT) (frontier_subset_closure (hqfr w)) + let Q₀ := singletonDrawing y + obtain ⟨Q,hQ,htrace⟩ := Q₀.attachLeaves PUnit.unit q arm hqny + (fun w => left_mem_segment ℝ _ _) (fun w => right_mem_segment ℝ _ _) + (fun w => Relation.ReflTransGen.single (by exact subset_rfl)) + (fun _ _ _ => Subsingleton.elim _ _) + (fun w w' h z hz hz' => hPP w w' h z (harm w hz) (harm w' hz')) + (fun _ _ _ h => False.elim h) + let C : DiskCore (leafExtension (W := W) (⊥ : SimpleGraph PUnit) PUnit.unit) {w | w.isRight} := { + drawing := Q + disk := T + center := y + convex := hT + isOpen := hTop + bounded := hTb + center_mem := hyT + point_mem := by + intro w; rw [hQ]; cases w with + | inl w => exact subset_closure hyT + | inr w => exact frontier_subset_closure (hqfr w) + trace_mem := by + intro d z hz + have hh := htrace d hz + cases ha : d.val.fst with + | inl a => cases hb : d.val.snd with + | inl b => have h := d.val.adj; rw [ha,hb] at h; exact False.elim h + | inr b => rw [ha,hb] at hh; exact harmT b hh + | inr a => cases hb : d.val.snd with + | inl b => rw [ha,hb] at hh; exact harmT a hh + | inr b => have h := d.val.adj; rw [ha,hb] at h; exact False.elim h + port := by + intro w hw; cases w with + | inl w => simp at hw + | inr w => rw [hQ]; exact hqfr w } + let E : ExteriorPorts C.drawing.point (Sum.elim (fun _ => y) child) {w | w.isRight} C.disk := { + region := Sum.elim (fun _ => ∅) (fun w => (A w).trace) + compact := by intro w hw; cases w with + | inl w => simp at hw + | inr w => exact (A w).trace_compact + start := by intro w hw; cases w with + | inl w => simp at hw + | inr w => change Q.point (.inr w)∈_; rw [hQ]; exact (A w).start_mem_trace + joined := by intro w hw; cases w with + | inl w => simp at hw + | inr w => change PolygonallyJoined _ (Q.point (.inr w)) _; rw [hQ]; exact (A w).joined_trace + inside := by intro w hw z hz hz'; cases w with + | inl w => simp at hw + | inr w => change z=Q.point (.inr w); rw [hQ]; exact hqin w z hz hz' + disjoint := by + intro w hw w' hw' hne + cases w with + | inl w => simp at hw + | inr w => cases w' with + | inl w' => simp at hw' + | inr w' => + apply disjoint_left.mpr + intro z hz hz' + have he := hPP w w' (fun he => hne (congrArg Sum.inr he)) z (hAsub w hz) (hAsub w' hz') + have he' := hqin w z hz (he.symm ▸ subset_closure hyT) + exact hqny w (he'.symm.trans he) } + refine ⟨C,E,?_,hd.mono_right subset_union_left,?_⟩ + · change Q.point (.inl PUnit.unit)=y; rw [hQ]; rfl + · intro w hw z hz hzK + cases w with + | inl w => simp at hw + | inr w => exact hPK w z (hAsub w hz) hzK + +end PlanarL1.Topology + + + + +namespace PlanarL1.HeightTree +open Set PlanarL1.Topology +variable {V : Type} [Fintype V] [LinearOrder V] (T : HeightTree V) + {G : SimpleGraph V} (P : PLDrawing G) + +lemma initial_growth (hG : T.graph ≤ G) : Nonempty (T.Growth P {T.root}) := by + classical + let W := {w // T.Step T.root w} + let e := T.rootEquiv + let : LinearOrder (PUnit⊕W) := LinearOrder.lift' e e.injective + have he (w : W) : G.Adj T.root w.val := hG (Or.inl w.property) + choose n Q hQ hsub using fun w : W => P.region_simple_chain (he w) + have hPP (w w' : W) (hne : w≠w') (z : ℂ) + (hz : z∈(Q w).trace) (hz' : z∈(Q w').trace) : z=P.point T.root := by + have hne' : ¬((T.root=T.root ∧ w.val=w'.val) ∨ (T.root=w'.val ∧ w.val=T.root)) := by + rintro (hh|hh) + · exact hne (Subtype.ext hh.2) + · exact (he w).ne hh.2.symm + rcases (P.region_intersect _ _ _ _ (he w) (he w') hne' (hsub w hz) (hsub w' hz')).1 with hh|hh + · exact hh + · have hm : P.point w.val∈P.region T.root w'.val := hh ▸ hsub w' hz' + rcases P.region_vertex _ _ (he w') w.val hm with hh'|hh' + · exact (he w).ne hh'.symm |>.elim + · exact hne (Subtype.ext hh') |>.elim + have hyK : P.point T.root∉outside P {T.root} := by rw [point_outside_iff]; simp + have hPK (w : W) (z : ℂ) (hz : z∈(Q w).trace) + (hzK : z∈outside P {T.root}) : z=P.point w.val := + P.region_carrier_intersection (he w) (by simp) (hsub w hz) hzK + obtain ⟨C,E,hroot,havoid,hcontact⟩ := star_core (P.point T.root) (fun w : W => P.point w.val) + n Q hQ hPP (outside_closed P {T.root}) hyK hPK + have hgraph : ∀ u u', (SimpleGraph.comap Subtype.val T.graph).Adj u u' → + (leafExtension (W := W) (⊥ : SimpleGraph PUnit) PUnit.unit).Adj (e.symm u) (e.symm u') := by + intro u u' h + rw [T.root_graph] + change T.graph.Adj (e (e.symm u)).val (e (e.symm u')).val + change T.graph.Adj u.val u'.val at h + simpa only [Equiv.apply_symm_apply] using h + have hports : ∀ w : {u // T.Scope {T.root} u}, T.Frontier {T.root} w.val → + (e.symm w).isRight := by + intro w hw + apply (T.root_ports (e.symm w)).mpr + change T.Frontier {T.root} (e (e.symm w)).val + simpa only [Equiv.apply_symm_apply] using hw + obtain ⟨C₂,E₂,hD,hp,hE⟩ := C.pullback E e.symm e.symm.injective hgraph hports + have htarget (w : {u // T.Scope {T.root} u}) : + (Sum.elim (fun _ : PUnit => P.point T.root) (fun u : W => P.point u.val) ∘ e.symm) w=P.point w.val := by + have heq := congrArg Subtype.val (e.apply_symm_apply w) + change T.rootMap (e.symm w)=w.val at heq + have hm : Sum.elim (fun _ : PUnit => P.point T.root) (fun u : W => P.point u.val) (e.symm w)= + P.point (T.rootMap (e.symm w)) := by cases e.symm w <;> rfl + exact hm.trans (congrArg P.point heq) + let E₃ := E₂.retarget (fun w => P.point w.val) htarget + refine ⟨⟨C₂,E₃,?_,?_⟩⟩ + · rw [hD]; exact havoid + · intro w hw z hz hzK + have hz' : z∈E.region (e.symm w) := (hE w) ▸ hz + exact (hcontact (e.symm w) (hports w hw) z hz' hzK).trans (htarget w) + +end PlanarL1.HeightTree + + + +end + +end OAI diff --git a/lean/OAI/Combinatorics/PlanarL1/HeightTree.lean b/lean/OAI/Combinatorics/PlanarL1/HeightTree.lean new file mode 100644 index 0000000000000000000000000000000000000000..0bc7823801825563cd6f7345be2ada58ba69a822 --- /dev/null +++ b/lean/OAI/Combinatorics/PlanarL1/HeightTree.lean @@ -0,0 +1,682 @@ +import OAI.Combinatorics.PlanarL1.WeightedMetric +import OAI.Combinatorics.PlanarL1.Distance + +namespace OAI + +section + + + +namespace PlanarL1 + +/-- A rooted incidence tree with a nondecreasing metric height. Unlike the +shortest-path tree, added terminal branches are permitted to have zero length. +Termination follows the incidence tree, not strict metric height. -/ +structure HeightTree (V : Type*) where + root : V + parent : V → V + at_root : parent root = root + wf : WellFounded (fun u v => v ≠ root ∧ u = parent v) + height : V → ℝ + height_mono : ∀ v, height (parent v) ≤ height v + +namespace HeightTree +attribute [local instance] Classical.propDecidable +variable {V : Type*} (T : HeightTree V) + +abbrev Step (u v : V) : Prop := v ≠ T.root ∧ u = T.parent v +abbrev Ancestor (u v : V) : Prop := Relation.ReflTransGen T.Step u v + +lemma ancestor_height {u v : V} (h : T.Ancestor u v) : T.height u ≤ T.height v := by + induction h with + | refl => rfl + | tail _ h ih => exact ih.trans (h.2 ▸ T.height_mono _) + +/-- McShane cones over the finite ancestral chain. The recursive minimum is +used instead of linear interpolation, so zero-length incidences need no division. -/ +noncomputable def profile (q : V → ℝ) (v : V) : ℝ → ℝ := + T.wf.fix (fun v rec => if h : v = T.root then fun H => q v + |H-T.height v| + else fun H => min (rec (T.parent v) ⟨h,rfl⟩ H) (q v + |H-T.height v|)) v + +lemma profile_eq (q : V → ℝ) (v : V) : + T.profile q v = if _h : v = T.root then fun H => q v + |H-T.height v| + else fun H => min (T.profile q (T.parent v) H) (q v + |H-T.height v|) := by + rw [profile,WellFounded.fix_eq] + rfl + +lemma profile_root (q : V → ℝ) (H : ℝ) : + T.profile q T.root H = q T.root + |H-T.height T.root| := by + rw [profile_eq,dite_eq_left rfl] + +lemma profile_child (q : V → ℝ) {v : V} (hv : v ≠ T.root) (H : ℝ) : + T.profile q v H = min (T.profile q (T.parent v) H) (q v + |H-T.height v|) := by + rw [profile_eq,dite_eq_right hv] + +lemma profile_le_cone (q : V → ℝ) (v : V) (H : ℝ) : + T.profile q v H ≤ q v + |H-T.height v| := by + by_cases hv : v = T.root + · subst v; rw [profile_root] + · rw [profile_child _ _ hv]; exact min_le_right _ _ + +lemma profile_lipschitz (q : V → ℝ) (v : V) : LipschitzWith 1 (T.profile q v) := by + induction v using T.wf.induction with + | h v ih => + have hcone : LipschitzWith 1 (fun H : ℝ => q v + |H-T.height v|) := by + apply LipschitzWith.of_dist_le_mul + intro x y + simpa only [Real.dist_eq,add_sub_add_comm,sub_self,zero_add,NNReal.coe_one,one_mul] using + abs_dist_sub_le x y (T.height v) + by_cases hv : v = T.root + · rw [profile_eq,dite_eq_left hv]; exact hcone + · rw [profile_eq,dite_eq_right hv] + simpa only [max_self] using (ih (T.parent v) ⟨hv,rfl⟩).min hcone + +/-- Discrete one-Lipschitz data along the actual tree edges. -/ +def Compatible (q : V → ℝ) : Prop := + ∀ v, |q v-q (T.parent v)| ≤ T.height v-T.height (T.parent v) + +lemma profile_above {q : V → ℝ} (hq : T.Compatible q) (v : V) {H : ℝ} + (hH : T.height v ≤ H) : T.profile q v H = q v + (H-T.height v) := by + induction v using T.wf.induction with + | h v ih => + by_cases hv : v = T.root + · subst v; rw [profile_root,abs_of_nonneg (sub_nonneg.mpr hH)] + · rw [profile_child _ _ hv,ih (T.parent v) ⟨hv,rfl⟩ ((T.height_mono v).trans hH), + abs_of_nonneg (sub_nonneg.mpr hH)] + apply min_eq_right + have hb := (abs_le.mp (hq v)).2 + linarith + +lemma profile_at {q : V → ℝ} (hq : T.Compatible q) (v : V) : + T.profile q v (T.height v) = q v := by + simpa only [sub_self,add_zero] using T.profile_above hq v le_rfl + +lemma profile_below_parent {q : V → ℝ} (hq : T.Compatible q) {v : V} + (hv : v ≠ T.root) {H : ℝ} (hH : H ≤ T.height (T.parent v)) : + T.profile q v H = T.profile q (T.parent v) H := by + rw [profile_child _ _ hv] + apply min_eq_left + have hc := T.profile_le_cone q (T.parent v) H + rw [abs_of_nonpos (sub_nonpos.mpr hH)] at hc + rw [abs_of_nonpos (sub_nonpos.mpr (hH.trans (T.height_mono v)))] + have hb := (abs_le.mp (hq v)).1 + linarith + +/-- Common root prefixes receive literally the same potential on every copy. -/ +lemma profile_ancestor {q : V → ℝ} (hq : T.Compatible q) {u v : V} + (h : T.Ancestor u v) {H : ℝ} (hH : H ≤ T.height u) : + T.profile q v H = T.profile q u H := by + induction h with + | refl => rfl + | @tail v w huv hvw ih => + rw [T.profile_below_parent hq hvw.1 (hH.trans (T.ancestor_height huv) |>.trans_eq (congrArg T.height hvw.2)), + ← hvw.2] + exact ih + +lemma root_ancestor (v : V) : T.Ancestor T.root v := by + induction v using T.wf.induction with + | h v ih => + by_cases hv : v = T.root + · subst v; exact Relation.ReflTransGen.refl + · exact (ih (T.parent v) ⟨hv,rfl⟩).tail ⟨hv,rfl⟩ + +noncomputable def depth (v : V) : ℕ := + T.wf.fix (fun v rec => if h : v = T.root then 0 + else rec (T.parent v) ⟨h,rfl⟩ + 1) v + +lemma depth_eq (v : V) : + T.depth v = if _h : v = T.root then 0 else T.depth (T.parent v)+1 := by + rw [depth,WellFounded.fix_eq] + rfl + +lemma step_depth {u v : V} (h : T.Step u v) : T.depth u < T.depth v := by + rw [T.depth_eq v,dite_eq_right h.1,← h.2] + omega + +lemma ancestor_depth {u v : V} (h : T.Ancestor u v) : T.depth u ≤ T.depth v := by + induction h with + | refl => rfl + | tail _ h ih => exact ih.trans (T.step_depth h).le + +lemma ancestor_antisymm {u v : V} (h : T.Ancestor u v) (h' : T.Ancestor v u) : u=v := by + cases h with + | refl => rfl + | tail huv hwv => + have h₁ := T.ancestor_depth h' + have h₂ := T.ancestor_depth huv + have h₃ := T.step_depth hwv + omega + +def IsLeaf (v : V) : Prop := ∀ w, ¬T.Step v w + +lemma exists_leaf [Fintype V] (v : V) : ∃ w, T.Ancestor v w ∧ T.IsLeaf w := by + classical + let S := Finset.univ.filter (T.Ancestor v) + obtain ⟨w,hw,hmax⟩ := Finset.exists_max_image S T.depth ⟨v,Finset.mem_filter.mpr ⟨Finset.mem_univ v,Relation.ReflTransGen.refl⟩⟩ + have hw' : T.Ancestor v w := (Finset.mem_filter.mp hw).2 + refine ⟨w,hw',fun u hu => ?_⟩ + have hu' : u∈S := Finset.mem_filter.mpr ⟨Finset.mem_univ u,hw'.tail hu⟩ + exact (not_lt_of_ge (hmax u hu')) (T.step_depth hu) + +noncomputable def leafAbove [Fintype V] (v : V) : {w : V // T.IsLeaf w} := + ⟨(T.exists_leaf v).choose,(T.exists_leaf v).choose_spec.2⟩ + +lemma ancestor_leafAbove [Fintype V] (v : V) : T.Ancestor v (T.leafAbove v).val := + (T.exists_leaf v).choose_spec.1 + +end HeightTree +end PlanarL1 + +namespace PlanarL1.Weighted +open SimpleGraph +attribute [local instance] Classical.propDecidable +variable {V : Type} [Fintype V] {G : SimpleGraph V} {l : V → V → ℝ} + +/-- Each orientation is one distinct new branch incidence. Paired incidences +are not identified until the column switch is installed. -/ +def ExtraDart (hc : G.Connected) (hs : ∀ u v, l u v=l v u) + (hl : ∀ u v, G.Adj u v → 0 d.property h.symm⟩ + +lemma reverse_reverse (d : ExtraDart hc hs hl o) : + reverse hc hs hl o (reverse hc hs hl o d)=d := by + apply Subtype.ext + exact SimpleGraph.Dart.symm_symm d.val + +noncomputable def tipHeight (d : ExtraDart hc hs hl o) : ℝ := + (l d.val.fst d.val.snd + graphDistance G l o d.val.fst + graphDistance G l o d.val.snd)/2 + +lemma tipHeight_reverse (d : ExtraDart hc hs hl o) : + tipHeight hc hs hl o (reverse hc hs hl o d)=tipHeight hc hs hl o d := by + change (l d.val.snd d.val.fst + graphDistance G l o d.val.snd + graphDistance G l o d.val.fst)/2 = _ + rw [hs d.val.snd d.val.fst] + unfold tipHeight + ring + +lemma height_le_tip (d : ExtraDart hc hs hl o) : + graphDistance G l o d.val.fst ≤ tipHeight hc hs hl o d := by + have h := (abs_le.mp (height_edge hc hs (fun u v h => (hl u v h).le) o d.val.adj)).2 + unfold tipHeight + linarith + +end ExtraDart + +namespace EnlargedTree +variable (hc : G.Connected) (hs : ∀ u v, l u v=l v u) + (hl : ∀ u v, G.Adj u v → 0 .inl ((shortestParents hc hs hl o).parent v) + | .inr d => .inl d.val.fst + +noncomputable def height : Node hc hs hl o → ℝ + | .inl v => graphDistance G l o v + | .inr d => ExtraDart.tipHeight hc hs hl o d + +lemma parent_wf : WellFounded (fun u v : Node hc hs hl o => + v ≠ .inl o ∧ u = parent hc hs hl o v) := by + let D := shortestParents hc hs hl o + have ha : ∀ v : V, Acc (fun u v : Node hc hs hl o => + v ≠ .inl o ∧ u = parent hc hs hl o v) (.inl v) := by + intro v + induction v using D.wellFounded.induction with + | h v ih => + constructor + rintro u ⟨hv,rfl⟩ + exact ih (D.parent v) (D.descent v (fun he => hv (congrArg Sum.inl he))) + constructor + intro v + cases v with + | inl v => exact ha v + | inr d => + constructor + rintro u ⟨_,rfl⟩ + exact ha d.val.fst + +/-- An abstract height tree, including zero-length branches. -/ +noncomputable def tree : HeightTree (Node hc hs hl o) where + root := .inl o + parent := parent hc hs hl o + at_root := congrArg Sum.inl (shortestParents hc hs hl o).at_root + wf := parent_wf hc hs hl o + height := height hc hs hl o + height_mono := by + intro v + cases v with + | inl v => + change (shortestParents hc hs hl o).height _ ≤ (shortestParents hc hs hl o).height v + by_cases hv : v=o + · subst v + have hr : (shortestParents hc hs hl o).parent o=o := (shortestParents hc hs hl o).at_root + rw [hr] + · exact ((shortestParents hc hs hl o).descent v hv).le + | inr d => exact ExtraDart.height_le_tip hc hs hl o d + +lemma extra_leaf (d : ExtraDart hc hs hl o) : + (tree hc hs hl o).IsLeaf (.inr d) := by + intro v h + cases v <;> exact Sum.inr_ne_inl h.2 + +/-- Graph-distance potentials extended to the two endpoints of each split +edge by their shortest distance through either of that edge's endpoints. -/ +noncomputable def potential (z : V) : Node hc hs hl o → ℝ + | .inl v => graphDistance G l z v + | .inr d => min + (graphDistance G l z d.val.fst + ExtraDart.tipHeight hc hs hl o d - graphDistance G l o d.val.fst) + (graphDistance G l z d.val.snd + ExtraDart.tipHeight hc hs hl o d - graphDistance G l o d.val.snd) + +lemma potential_reverse (z : V) (d : ExtraDart hc hs hl o) : + potential hc hs hl o z (.inr (ExtraDart.reverse hc hs hl o d)) = + potential hc hs hl o z (.inr d) := by + change min + (graphDistance G l z d.val.snd + ExtraDart.tipHeight hc hs hl o (ExtraDart.reverse hc hs hl o d) - graphDistance G l o d.val.snd) + (graphDistance G l z d.val.fst + ExtraDart.tipHeight hc hs hl o (ExtraDart.reverse hc hs hl o d) - graphDistance G l o d.val.fst) = _ + rw [ExtraDart.tipHeight_reverse] + exact min_comm _ _ + +lemma min_split_compatible {du dv a b : ℝ} (ha : 0≤a) + (h : |du-dv|≤a+b) : |min (du+a) (dv+b)-du|≤a := by + apply abs_le.mpr + constructor + · have h₁ : du-a≤du+a := by linarith + have h₂ : du-a≤dv+b := by have := (abs_le.mp h).2; linarith + have := le_min h₁ h₂ + linarith + · have := min_le_left (du+a) (dv+b) + linarith + +lemma potential_compatible (z : V) : + (tree hc hs hl o).Compatible (potential hc hs hl o z) := by + intro v + cases v with + | inl v => + change |graphDistance G l z v - graphDistance G l z ((shortestParents hc hs hl o).parent v)| ≤ + graphDistance G l o v - graphDistance G l o ((shortestParents hc hs hl o).parent v) + by_cases hv : v=o + · subst v + have hr : (shortestParents hc hs hl o).parent o=o := (shortestParents hc hs hl o).at_root + rw [hr,sub_self,abs_zero,sub_self] + · obtain ⟨hedge,hlen⟩ := shortestParents.parent_step hc hs hl o v hv + have h := height_edge hc hs (fun u v h => (hl u v h).le) z hedge.symm + rw [hs v ((shortestParents hc hs hl o).parent v)] at h + linarith + | inr d => + have ha := ExtraDart.height_le_tip hc hs hl o d + have hd := height_edge hc hs (fun u v h => (hl u v h).le) z d.val.adj + have hsum : (ExtraDart.tipHeight hc hs hl o d-graphDistance G l o d.val.fst)+ + (ExtraDart.tipHeight hc hs hl o d-graphDistance G l o d.val.snd)=l d.val.fst d.val.snd := by + unfold ExtraDart.tipHeight + ring + have hx := min_split_compatible (du := graphDistance G l z d.val.fst) + (dv := graphDistance G l z d.val.snd) + (b := ExtraDart.tipHeight hc hs hl o d-graphDistance G l o d.val.snd) + (sub_nonneg.mpr ha) (by rw [hsum]; exact hd) + change |min (_ + _ - _) (_ + _ - _) - graphDistance G l z d.val.fst| ≤ ExtraDart.tipHeight hc hs hl o d-graphDistance G l o d.val.fst + simpa only [add_sub_assoc] using hx + +end EnlargedTree +end PlanarL1.Weighted + +namespace PlanarL1.HeightTree +open Set Columns +attribute [local instance] Classical.propDecidable +variable {V : Type*} [Fintype V] {n : ℕ} (T : HeightTree V) + +/-- Adjacent copies in the cyclic contour of an ancestral subtree. -/ +def prefixGraph (leaf : Fin n → V) (a : V) : SimpleGraph (Fin n) where + Adj i j := i ≠ j ∧ Consecutive i j ∧ T.Ancestor a (leaf i) ∧ T.Ancestor a (leaf j) + symm := ⟨by + rintro i j ⟨hij,hc,hi,hj⟩ + refine ⟨hij.symm,?_,hj,hi⟩ + rcases hc with h | h | h | h + · exact Or.inr (Or.inl h) + · exact Or.inl h + · exact Or.inr (Or.inr (Or.inr h)) + · exact Or.inr (Or.inr (Or.inl h))⟩ + loopless := ⟨fun _ h => h.1 rfl⟩ + +/-- The combinatorial output of a planar tree contour construction. No metric +realization or metric estimates are part of this data. -/ +structure Layout (n : ℕ) where + leaf : Fin n → V + isLeaf : ∀ i, T.IsLeaf (leaf i) + injective : Function.Injective leaf + covers : ∀ v, T.IsLeaf v → ∃ i, leaf i = v + prefix_connected : ∀ a i j, T.Ancestor a (leaf i) → T.Ancestor a (leaf j) → + (T.prefixGraph leaf a).Reachable i j + pair : SimpleGraph (Fin n) + noncrossing : ColumnOrder.Noncrossing pair + paired_height : ∀ i j, pair.Adj i j → T.height (leaf i)=T.height (leaf j) + matching : ∀ i j k, pair.Adj i j → pair.Adj i k → j=k + +namespace Layout +variable {T} (L : T.Layout n) + +noncomputable def heights (i j : Fin n) : Set ℝ := + (⋃ a : V, if i ≠ j ∧ Consecutive i j ∧ T.Ancestor a (L.leaf i) ∧ T.Ancestor a (L.leaf j) + then Icc (T.height T.root) (T.height a) else ∅) ∪ + (if L.pair.Adj i j then {T.height (L.leaf i)} else ∅) + +omit [Fintype V] in +lemma mem_heights (i j : Fin n) (H : ℝ) : H ∈ L.heights i j ↔ + (∃ a, (T.prefixGraph L.leaf a).Adj i j ∧ T.height T.root ≤ H ∧ H ≤ T.height a) ∨ + (L.pair.Adj i j ∧ H=T.height (L.leaf i)) := by + classical + simp only [heights,mem_union,mem_iUnion,mem_ite_empty_right,mem_Icc,mem_singleton_iff,prefixGraph] + +omit [Fintype V] in +lemma heights_symm (i j : Fin n) : L.heights i j=L.heights j i := by + ext H + simp only [mem_heights] + constructor <;> intro h + · rcases h with ⟨a,ha,hH⟩ | ⟨ha,rfl⟩ + · exact Or.inl ⟨a,ha.symm,hH⟩ + · exact Or.inr ⟨ha.symm,L.paired_height i j ha⟩ + · rcases h with ⟨a,ha,hH⟩ | ⟨ha,rfl⟩ + · exact Or.inl ⟨a,ha.symm,hH⟩ + · exact Or.inr ⟨ha.symm,L.paired_height j i ha⟩ + +lemma heights_compact (i j : Fin n) : IsCompact (L.heights i j) := by + apply IsCompact.union + · apply isCompact_iUnion + intro a + split_ifs <;> first | exact isCompact_Icc | exact isCompact_empty + · split_ifs <;> first | exact isCompact_singleton | exact isCompact_empty + +omit [Fintype V] in +lemma switch_le_tip {i j : Fin n} {H : ℝ} (h : H ∈ L.heights i j) : + H ≤ T.height (L.leaf i) := by + rcases (L.mem_heights i j H).mp h with ⟨a,ha,_,hH⟩ | ⟨_,rfl⟩ + · exact hH.trans (T.ancestor_height ha.2.2.1) + · rfl + +noncomputable def model : Model n where + link := (T.prefixGraph L.leaf T.root) ⊔ L.pair + heights := L.heights + symm := L.heights_symm + permitted i j H h := by + rcases (L.mem_heights i j H).mp h with ⟨a,ha,_⟩ | ⟨ha,_⟩ + · exact Or.inl ⟨ha.1,ha.2.1,T.root_ancestor _,T.root_ancestor _⟩ + · exact Or.inr ha + compact := L.heights_compact + noncrossing := by + intro a b c d hab hbc hcd h + have hac : ¬Consecutive a c := by + simp only [Consecutive] + omega + have hbd : ¬Consecutive b d := by + simp only [Consecutive] + omega + rcases h.1 with ha | ha + · exact hac ha.2.1 + · rcases h.2 with hb | hb + · exact hbd hb.2.1 + · exact L.noncrossing a b c d hab hbc hcd ⟨ha,hb⟩ + terminal i j ha hn := by + have hp : L.pair.Adj i j := ha.resolve_left (fun h => hn h.2.1) + refine ⟨T.height (L.leaf i),?_,?_⟩ + · ext H + rw [L.mem_heights] + constructor + · rintro (⟨a,ha,_⟩ | ⟨_,he⟩) + · exact (hn ha.2.1).elim + · exact he + · intro he + exact Or.inr ⟨hp,he⟩ + · intro k H hH + rcases hH with hH | hH + · exact L.switch_le_tip hH + · rw [L.paired_height i j hp] + exact L.switch_le_tip hH + +/-- Constant-height switches connect all copies on a common root prefix. -/ +noncomputable def prefixPath {a : V} {i j : Fin n} + (p : (T.prefixGraph L.leaf a).Walk i j) {H : ℝ} + (hlo : T.height T.root ≤ H) (hhi : H ≤ T.height a) : + L.model.Path univ i j := + match p with + | .nil => .nil _ + | .cons h p => .cons H (mem_univ H) ((L.mem_heights _ _ _).mpr (Or.inl ⟨a,h,hlo,hhi⟩)) + (prefixPath p hlo hhi) + +lemma prefixPath_length {a : V} {i j : Fin n} + (p : (T.prefixGraph L.leaf a).Walk i j) {H : ℝ} + (hlo : T.height T.root ≤ H) (hhi : H ≤ T.height a) : + (L.prefixPath p hlo hhi).length H H=0 := by + induction p with + | nil => simp only [prefixPath,Model.Path.length,sub_self,abs_zero] + | cons h p ih => simp only [prefixPath,Model.Path.length,sub_self,abs_zero,zero_add,ih] + +lemma exists_prefixPath {a : V} {i j : Fin n} + (hi : T.Ancestor a (L.leaf i)) (hj : T.Ancestor a (L.leaf j)) {H : ℝ} + (hlo : T.height T.root ≤ H) (hhi : H ≤ T.height a) : + ∃ p : L.model.Path univ i j, p.length H H=0 := by + obtain ⟨p⟩ := L.prefix_connected a i j hi hj + exact ⟨L.prefixPath p hlo hhi,L.prefixPath_length p hlo hhi⟩ + +noncomputable def column (v : V) : Fin n := + (L.covers _ (T.leafAbove v).property).choose + +lemma ancestor_column (v : V) : T.Ancestor v (L.leaf (L.column v)) := by + rw [column,(L.covers _ (T.leafAbove v).property).choose_spec] + exact T.ancestor_leafAbove v + +noncomputable def point (v : V) : L.model.Point univ (L.column T.root) where + column := L.column v + height := T.height v + inBand := mem_univ _ + reachable := by + obtain ⟨p,_⟩ := L.exists_prefixPath (T.root_ancestor (L.leaf (L.column T.root))) + (T.root_ancestor (L.leaf (L.column v))) le_rfl le_rfl + exact ⟨p.word⟩ + +end Layout +end PlanarL1.HeightTree + +namespace PlanarL1.Columns.Model +open Set +variable {n : ℕ} (M : Model n) + +/-- A scalar potential compatible with every actual switch bounds the length +of every switching path, irrespective of excursions into the separate tails. -/ +lemma Path.potential_le {J : Set ℝ} {i j : Fin n} (p : M.Path J i j) + (q : Fin n → ℝ → ℝ) (hLip : ∀ i, LipschitzWith 1 (q i)) + (hSwitch : ∀ i j H, H ∈ M.heights i j → q i H=q j H) (a b : ℝ) : + |q i a-q j b| ≤ p.length a b := by + induction p generalizing a with + | nil i => simpa only [Path.length,Real.dist_eq,NNReal.coe_one,one_mul] using (hLip i).dist_le_mul a b + | @cons i j k H hH hs p ih => + have hl : |q i a-q i H|≤|a-H| := by + simpa only [Real.dist_eq,NNReal.coe_one,one_mul] using (hLip i).dist_le_mul a H + have hb := abs_sub_le (q i a) (q i H) (q k b) + rw [hSwitch i j H hs] at hb + exact hb.trans (add_le_add (by rwa [← hSwitch i j H hs]) (ih H)) + +lemma Point.potential_le {J : Set ℝ} {root : Fin n} (x y : M.Point J root) + (q : Fin n → ℝ → ℝ) (hLip : ∀ i, LipschitzWith 1 (q i)) + (hSwitch : ∀ i j H, H ∈ M.heights i j → q i H=q j H) : + |q x.column x.height-q y.column y.height| ≤ x.distance y := by + have := x.paths_nonempty y + exact le_ciInf (fun p => p.potential_le M q hLip hSwitch x.height y.height) +end PlanarL1.Columns.Model + +namespace PlanarL1.HeightTree +open Set Columns +attribute [local instance] Classical.propDecidable +variable {V : Type*} [Fintype V] {n : ℕ} {T : HeightTree V} + +omit [Fintype V] in +lemma IsLeaf.ancestor_eq {v w : V} (hv : T.IsLeaf v) (h : T.Ancestor v w) : v=w := by + induction h with + | refl => rfl + | @tail u w hvu huw ih => exact (hv w (ih ▸ huw)).elim + +namespace Layout +variable (L : T.Layout n) + +lemma leaf_column {v : V} (hv : T.IsLeaf v) : L.leaf (L.column v)=v := + (hv.ancestor_eq (L.ancestor_column v)).symm + +lemma column_leaf (i : Fin n) : L.column (L.leaf i)=i := + L.injective (L.leaf_column (L.isLeaf i)) + +lemma profile_switch {q : V → ℝ} (hq : T.Compatible q) + (hpair : ∀ i j, L.pair.Adj i j → q (L.leaf i)=q (L.leaf j)) + (i j : Fin n) (H : ℝ) (hs : H ∈ L.model.heights i j) : + T.profile q (L.leaf i) H=T.profile q (L.leaf j) H := by + rcases (L.mem_heights i j H).mp hs with ⟨a,ha,_,hH⟩ | ⟨ha,rfl⟩ + · rw [T.profile_ancestor hq ha.2.2.1 hH,T.profile_ancestor hq ha.2.2.2 hH] + · rw [T.profile_at hq,L.paired_height i j ha,T.profile_at hq,hpair i j ha] + +lemma potential_le {q : V → ℝ} (hq : T.Compatible q) + (hpair : ∀ i j, L.pair.Adj i j → q (L.leaf i)=q (L.leaf j)) (v w : V) : + |q v-q w|≤(L.point v).distance (L.point w) := by + have h := (L.point v).potential_le L.model (L.point w) + (fun i => T.profile q (L.leaf i)) (fun i => T.profile_lipschitz q (L.leaf i)) + (L.profile_switch hq hpair) + change |T.profile q (L.leaf (L.column v)) (T.height v)- + T.profile q (L.leaf (L.column w)) (T.height w)|≤_ at h + rwa [T.profile_ancestor hq (L.ancestor_column v) le_rfl, + T.profile_ancestor hq (L.ancestor_column w) le_rfl,T.profile_at hq,T.profile_at hq] at h + +lemma parent_distance_le (v : V) : + (L.point v).distance (L.point (T.parent v))≤T.height v-T.height (T.parent v) := by + by_cases hv : v=T.root + · subst v + rw [T.at_root,Model.Point.distance_self,sub_self] + · have had : T.Ancestor (T.parent v) (L.leaf (L.column v)) := + (Relation.ReflTransGen.single ⟨hv,rfl⟩).trans (L.ancestor_column v) + obtain ⟨p,hp⟩ := L.exists_prefixPath had (L.ancestor_column (T.parent v)) + (T.ancestor_height (T.root_ancestor (T.parent v))) le_rfl + have h := (L.point v).distance_le (L.point (T.parent v)) p + have hb := p.length_start_le (T.height v) (T.height (T.parent v)) (T.height (T.parent v)) + rw [hp,add_zero,abs_of_nonneg (sub_nonneg.mpr (T.height_mono v))] at hb + exact h.trans hb + +lemma pair_distance_zero {i j : Fin n} (h : L.pair.Adj i j) : + (L.point (L.leaf i)).distance (L.point (L.leaf j))=0 := by + apply le_antisymm _ (Model.Point.distance_nonneg _ _) + let p : L.model.Path univ (L.point (L.leaf i)).column (L.point (L.leaf j)).column := + .cons (T.height (L.leaf i)) (mem_univ _) (by + change T.height (L.leaf i) ∈ L.heights (L.column (L.leaf i)) (L.column (L.leaf j)) + rw [L.column_leaf,L.column_leaf] + exact (L.mem_heights _ _ _).mpr (Or.inr ⟨h,rfl⟩)) (.nil _) + have he : p.length (T.height (L.leaf i)) (T.height (L.leaf j))=0 := by + simp only [p,Model.Path.length,sub_self,abs_zero,L.paired_height i j h,zero_add] + exact ((L.point (L.leaf i)).distance_le _ p).trans_eq he + +end Layout +end PlanarL1.HeightTree + +namespace PlanarL1.Weighted +open SimpleGraph +attribute [local instance] Classical.propDecidable +variable {V : Type} [Fintype V] {G : SimpleGraph V} {l : V → V → ℝ} + (hc : G.Connected) (hs : ∀ u v, l u v=l v u) + (hl : ∀ u v, G.Adj u v → 0 by + obtain ⟨d,hi,hj⟩ := (hpair i j).mp h + rw [hi,hj] + exact (potential_reverse hc hs hl o u d).symm) (.inl u) (.inl v) + change |graphDistance G l u u-graphDistance G l u v|≤_ at hh + rwa [distance_self (fun u v h => (hl u v h).le),zero_sub,abs_neg, + abs_of_nonneg (distance_nonneg (fun u v h => (hl u v h).le) (hc.preconnected u v))] at hh + +lemma tip_pair (hpair : ExactPairs L) (d : ExtraDart hc hs hl o) : + L.pair.Adj (L.column (.inr d)) (L.column (.inr (ExtraDart.reverse hc hs hl o d))) := by + apply (hpair _ _).mpr + exact ⟨d,L.leaf_column (extra_leaf hc hs hl o d), + L.leaf_column (extra_leaf hc hs hl o (ExtraDart.reverse hc hs hl o d))⟩ + +lemma tip_distance_zero (hpair : ExactPairs L) (d : ExtraDart hc hs hl o) : + (L.point (.inr d)).distance (L.point (.inr (ExtraDart.reverse hc hs hl o d)))=0 := by + have h := L.pair_distance_zero (tip_pair L hpair d) + rwa [L.leaf_column (extra_leaf hc hs hl o d), + L.leaf_column (extra_leaf hc hs hl o (ExtraDart.reverse hc hs hl o d))] at h + +lemma original_parent_distance (v : V) (hv : v≠o) : + (L.point (.inl v)).distance (L.point (.inl ((shortestParents hc hs hl o).parent v))) ≤ + l v ((shortestParents hc hs hl o).parent v) := by + have h := L.parent_distance_le (.inl v) + change (L.point (.inl v)).distance (L.point (.inl ((shortestParents hc hs hl o).parent v))) ≤ + graphDistance G l o v-graphDistance G l o ((shortestParents hc hs hl o).parent v) at h + obtain ⟨_,he⟩ := shortestParents.parent_step hc hs hl o v hv + rw [hs v ((shortestParents hc hs hl o).parent v)] + linarith + +lemma original_edge_distance (hpair : ExactPairs L) {u v : V} (h : G.Adj u v) : + (L.point (.inl u)).distance (L.point (.inl v))≤l u v := by + by_cases ht : (shortestParents hc hs hl o).graph.Adj u v + · rcases ht with ⟨hu,rfl⟩ | ⟨hv,rfl⟩ + · exact original_parent_distance L u hu + · rw [Columns.Model.Point.distance_comm,hs] + exact original_parent_distance L v hv + · let d : ExtraDart hc hs hl o := ⟨⟨(u,v),h⟩,ht⟩ + have hd := L.parent_distance_le (.inr d) + have hr := L.parent_distance_le (.inr (ExtraDart.reverse hc hs hl o d)) + have hz := tip_distance_zero L hpair d + have h₁ := (L.point (.inl u)).distance_triangle (L.point (.inr d)) (L.point (.inl v)) + have h₂ := (L.point (.inr d)).distance_triangle + (L.point (.inr (ExtraDart.reverse hc hs hl o d))) (L.point (.inl v)) + rw [hz,zero_add] at h₂ + change (L.point (.inr d)).distance (L.point (.inl u))≤ + ExtraDart.tipHeight hc hs hl o d-graphDistance G l o u at hd + change (L.point (.inr (ExtraDart.reverse hc hs hl o d))).distance (L.point (.inl v))≤ + ExtraDart.tipHeight hc hs hl o (ExtraDart.reverse hc hs hl o d)-graphDistance G l o v at hr + rw [ExtraDart.tipHeight_reverse] at hr + rw [Columns.Model.Point.distance_comm] at hd + have hsum : (ExtraDart.tipHeight hc hs hl o d-graphDistance G l o u)+ + (ExtraDart.tipHeight hc hs hl o d-graphDistance G l o v)=l u v := by + dsimp [ExtraDart.tipHeight,d] + ring + linarith + +lemma original_walk_distance (hpair : ExactPairs L) {u v : V} (p : G.Walk u v) : + (L.point (.inl u)).distance (L.point (.inl v))≤walkLength l p := by + induction p with + | nil => rw [walkLength,Columns.Model.Point.distance_self] + | @cons u w v h p ih => + exact ((L.point (.inl u)).distance_triangle (L.point (.inl w)) (L.point (.inl v))).trans + (add_le_add (original_edge_distance L hpair h) ih) + +/-- The original weighted graph embeds isometrically into the actual column +path metric. In particular all tails and zero-length branch incidences are +accounted for; the lower bound is certified by graph-distance potentials. -/ +lemma original_distance (hpair : ExactPairs L) (u v : V) : + (L.point (.inl u)).distance (L.point (.inl v))=graphDistance G l u v := by + apply le_antisymm _ (original_distance_lower L hpair u v) + obtain ⟨p,hp,_⟩ := distance_eq_length (fun u v h => (hl u v h).le) (hc.preconnected u v) + rw [hp] + exact original_walk_distance L hpair p.val + +end EnlargedTree +end PlanarL1.Weighted + + + +end + +end OAI diff --git a/lean/OAI/Combinatorics/PlanarL1/Increments.lean b/lean/OAI/Combinatorics/PlanarL1/Increments.lean new file mode 100644 index 0000000000000000000000000000000000000000..c1226ee26233331eeb721af6c8520aff1dd88964 --- /dev/null +++ b/lean/OAI/Combinatorics/PlanarL1/Increments.lean @@ -0,0 +1,517 @@ +import OAI.Combinatorics.PlanarL1.Clipping +import OAI.Combinatorics.PlanarL1.Gluing + +namespace OAI + +section + +namespace PlanarL1.Increment +open Set +open scoped NNReal +attribute [local instance] Classical.propDecidable + +noncomputable def clamp (a b t : ℝ) : ℝ := min b (max a t) + +lemma clamp_bounds {a b t : ℝ} (hab : a ≤ b) : a ≤ clamp a b t ∧ clamp a b t ≤ b := + ⟨le_min hab (le_max_left _ _),min_le_left _ _⟩ + +lemma clamp_lipschitz (a b : ℝ) : LipschitzWith 1 (clamp a b) := + (LipschitzWith.id.const_max a).const_min b + +lemma clamp_eq {a b t : ℝ} (hat : a ≤ t) (htb : t ≤ b) : clamp a b t = t := by + rw [clamp,max_eq_right hat,min_eq_right htb] + +lemma clamp_left {a b t : ℝ} (hab : a ≤ b) (ht : t ≤ a) : clamp a b t = a := by + rw [clamp,max_eq_left ht,min_eq_right hab] + +lemma clamp_right {a b t : ℝ} (ht : b ≤ t) : clamp a b t = b := by + exact min_eq_left (ht.trans (le_max_right _ _)) + +noncomputable def quadratic (a b c d t : ℝ) : ℝ := + clamp a b t * (c-clamp a b t)/d + +lemma quadratic_lipschitz {a b c d : ℝ} {K : ℝ≥0} (hab : a ≤ b) (hd : 0 < d) + (hlo : -(K:ℝ)*d ≤ c-2*b) (hhi : c-2*a ≤ (K:ℝ)*d) : + LipschitzWith K (quadratic a b c d) := by + apply LipschitzWith.of_dist_le_mul + intro x y + obtain ⟨hxa,hxb⟩ := clamp_bounds (t := x) hab + obtain ⟨hya,hyb⟩ := clamp_bounds (t := y) hab + have hf : |c-clamp a b x-clamp a b y| ≤ (K:ℝ)*d := by + rw [abs_le] + constructor <;> linarith + have hc := (clamp_lipschitz a b).dist_le_mul x y + rw [Real.dist_eq,NNReal.coe_one,one_mul] at hc + rw [Real.dist_eq] + have he : quadratic a b c d x-quadratic a b c d y = + (clamp a b x-clamp a b y)*(c-clamp a b x-clamp a b y)/d := by + unfold quadratic + ring + rw [he,abs_div,abs_mul,abs_of_pos hd] + calc + _ ≤ (|clamp a b x-clamp a b y| *((K:ℝ)*d))/d := + div_le_div_of_nonneg_right (mul_le_mul_of_nonneg_left hf (abs_nonneg _)) hd.le + _ = (K:ℝ)*|clamp a b x-clamp a b y| := by field_simp + _ ≤ (K:ℝ)*dist x y := mul_le_mul_of_nonneg_left hc K.coe_nonneg + +noncomputable def splice (c : ℝ) (f g : ℝ → ℝ) (t : ℝ) : ℝ := if t ≤ c then f t else g t + +lemma splice_lipschitz {K : ℝ≥0} {c : ℝ} {f g : ℝ → ℝ} + (hf : LipschitzWith K f) (hg : LipschitzWith K g) (he : f c = g c) : + LipschitzWith K (splice c f g) := by + have h : LipschitzWith K ((Iic c).piecewise f g) := Gluing.lipschitz_piecewise isClosed_Iic + hg hf.lipschitzOnWith (by simpa only [frontier_Iic,eqOn_singleton] using he) + exact h + +noncomputable def low (a t : ℝ) : ℝ := -quadratic a (2*a) a a t +noncomputable def high (r t : ℝ) : ℝ := splice (8*r) id (quadratic (8*r) (10*r) (10*r) (2*r)) t +noncomputable def positivePart (a r t : ℝ) : ℝ := splice (2*a) (low a) (high r) t +noncomputable def scalar (a r t : ℝ) : ℝ := splice 0 (fun t => -positivePart a r (-t)) (positivePart a r) t + +lemma low_lipschitz {a : ℝ} (ha : 0 < a) : LipschitzWith 6 (low a) := by + have h : LipschitzWith 6 (quadratic a (2*a) a a) := + quadratic_lipschitz (by linarith) ha (by norm_num; linarith) (by norm_num; linarith) + exact h.neg + +lemma high_lipschitz {r : ℝ} (hr : 0 < r) : LipschitzWith 6 (high r) := by + apply splice_lipschitz (LipschitzWith.id.weaken (by norm_num)) + · exact quadratic_lipschitz (by linarith) (by linarith) (by norm_num; linarith) (by norm_num; linarith) + · dsimp only [id,quadratic] + rw [clamp_eq (by rfl) (by linarith)] + field_simp + ring + +lemma positive_zero {a r t : ℝ} (ha : 0 < a) (ht : t ≤ a) : positivePart a r t = 0 := by + rw [positivePart,splice,ite_eq_left (by linarith),low,quadratic,clamp_left (by linarith) ht] + ring + +lemma positive_plateau {a r t : ℝ} (ha : 0 < a) (hl : 2*a ≤ t) (hu : t ≤ 8*r) : + positivePart a r t = t := by + by_cases he : t = 2*a + · rw [positivePart,splice,ite_eq_left (by linarith),low,quadratic,clamp_right hl,he] + field_simp + ring + · rw [positivePart,splice,ite_eq_right (by intro h; exact he (le_antisymm h hl)),high,splice,ite_eq_left hu] + rfl + +lemma positive_lipschitz {a r : ℝ} (ha : 0 < a) (hr : 0 < r) (har : 2*a ≤ 8*r) : + LipschitzWith 6 (positivePart a r) := by + apply splice_lipschitz (low_lipschitz ha) (high_lipschitz hr) + rw [low,quadratic,clamp_right (le_refl _),high,splice,ite_eq_left har] + dsimp only [id] + field_simp + ring + +lemma scalar_lipschitz {a r : ℝ} (ha : 0 < a) (hr : 0 < r) (har : 2*a ≤ 8*r) : + LipschitzWith 6 (scalar a r) := by + have hp := positive_lipschitz ha hr har + have hn : LipschitzWith 6 (fun t => -positivePart a r (-t)) := by + apply LipschitzWith.of_dist_le_mul + intro x y + simpa only [dist_neg_neg] using hp.dist_le_mul (-x) (-y) + apply splice_lipschitz hn hp + simp only [neg_zero,positive_zero ha (by linarith : (0:ℝ) ≤ a)] + +lemma positive_far_zero {a r t : ℝ} (hr : 0 < r) (har : 2*a ≤ 8*r) + (ht : 10*r ≤ t) : positivePart a r t = 0 := by + rw [positivePart,splice,ite_eq_right (by linarith),high,splice,ite_eq_right (by linarith), + quadratic,clamp_right ht] + ring + +lemma positive_nonneg {a r t : ℝ} (ha : 0 < a) (hr : 0 < r) + (ht : 0 ≤ t) : 0 ≤ positivePart a r t := by + unfold positivePart splice + split_ifs with h + · obtain ⟨hl,hu⟩ := clamp_bounds (t := t) (show a ≤ 2*a by linarith) + unfold low quadratic + exact neg_nonneg.mpr (div_nonpos_of_nonpos_of_nonneg + (mul_nonpos_of_nonneg_of_nonpos (by linarith) (by linarith)) ha.le) + · unfold high splice + split_ifs with h' + · exact ht + · obtain ⟨hl,hu⟩ := clamp_bounds (t := t) (show 8*r ≤ 10*r by linarith) + unfold quadratic + exact div_nonneg (mul_nonneg (by linarith) (by linarith)) (by linarith) + +lemma positive_le {a r t : ℝ} (ha : 0 < a) (hr : 0 < r) (har : 2*a ≤ 8*r) : + positivePart a r t ≤ 10*r := by + unfold positivePart splice + split_ifs with h + · obtain ⟨hl,hu⟩ := clamp_bounds (t := t) (show a ≤ 2*a by linarith) + have hc : clamp a (2*a) t * (clamp a (2*a) t-a) ≤ 2*a*a := by + nlinarith [sq_nonneg (clamp a (2*a) t-2*a)] + unfold low quadratic + calc + _ = (clamp a (2*a) t * (clamp a (2*a) t-a))/a := by ring + _ ≤ (2*a*a)/a := div_le_div_of_nonneg_right hc ha.le + _ = 2*a := by field_simp + _ ≤ 10*r := by linarith + · unfold high splice + split_ifs with h' + · dsimp + linarith + · obtain ⟨hl,hu⟩ := clamp_bounds (t := t) (show 8*r ≤ 10*r by linarith) + unfold quadratic + rw [div_le_iff₀ (by linarith : 0 < 2*r)] + nlinarith [sq_nonneg (clamp (8*r) (10*r) t-8*r)] + +lemma scalar_support {a r t : ℝ} (ha : 0 < a) (hr : 0 < r) (har : 2*a ≤ 8*r) + (hne : scalar a r t ≠ 0) : a < |t| ∧ |t| < 10*r := by + by_cases ht : t ≤ 0 + · have he : |t| = -t := abs_of_nonpos ht + rw [scalar,splice,ite_eq_left ht,neg_ne_zero] at hne + rw [he] + constructor + · exact lt_of_not_ge (fun h => hne (positive_zero ha h)) + · exact lt_of_not_ge (fun h => hne (positive_far_zero hr har h)) + · have he : |t| = t := abs_of_pos (lt_of_not_ge ht) + rw [scalar,splice,ite_eq_right ht] at hne + rw [he] + constructor + · exact lt_of_not_ge (fun h => hne (positive_zero ha h)) + · exact lt_of_not_ge (fun h => hne (positive_far_zero hr har h)) + +lemma scalar_magnitude {a r t : ℝ} (ha : 0 < a) (hr : 0 < r) (har : 2*a ≤ 8*r) : + |scalar a r t| ≤ 10*r := by + unfold scalar splice + split_ifs with ht + · rw [abs_neg,abs_of_nonneg (positive_nonneg ha hr (by linarith))] + exact positive_le ha hr har + · rw [abs_of_nonneg (positive_nonneg ha hr (by linarith))] + exact positive_le ha hr har + +lemma scalar_plateau {a r t : ℝ} (ha : 0 < a) (hl : 2*a ≤ |t|) (hu : |t| ≤ 8*r) : + scalar a r t = t := by + unfold scalar splice + split_ifs with ht + · dsimp only + rw [abs_of_nonpos ht] at hl hu + rw [positive_plateau ha hl hu,neg_neg] + · rw [abs_of_pos (by linarith)] at hl hu + exact positive_plateau ha hl hu + +section Taper +variable {X : Type*} [PseudoMetricSpace X] +open Metric + +noncomputable def taper (S : Set X) (r : ℝ) (x : X) : ℝ := + if S.Nonempty then min 1 (infDist x S/r) else 1 + +lemma taper_bounds {S : Set X} {r : ℝ} (hr : 0 < r) (x : X) : + 0 ≤ taper S r x ∧ taper S r x ≤ 1 := by + unfold taper + split_ifs + · exact ⟨le_min (by norm_num) (div_nonneg infDist_nonneg hr.le),min_le_left _ _⟩ + · norm_num + +lemma taper_difference {S : Set X} {r : ℝ} (hr : 0 < r) (x y : X) : + |taper S r x-taper S r y| ≤ dist x y/r := by + by_cases hS : S.Nonempty + · simp only [taper,hS,ite_true] + have h := (LipschitzWith.id.const_min (1:ℝ)).dist_le_mul (infDist x S/r) (infDist y S/r) + simp only [Real.dist_eq,NNReal.coe_one,one_mul,id_eq] at h + have hd := (lipschitz_infDist_pt S).dist_le_mul x y + rw [Real.dist_eq,NNReal.coe_one,one_mul] at hd + calc + _ ≤ |infDist x S/r-infDist y S/r| := h + _ = |infDist x S-infDist y S|/r := by rw [← sub_div,abs_div,abs_of_pos hr] + _ ≤ dist x y/r := div_le_div_of_nonneg_right hd hr.le + · simp only [taper,hS,ite_false,sub_self,abs_zero] + exact div_nonneg dist_nonneg hr.le + +lemma taper_zero {S : Set X} {r : ℝ} {x : X} (hx : x ∈ S) : taper S r x = 0 := by + simp only [taper,show S.Nonempty from ⟨x,hx⟩,ite_true,infDist_zero_of_mem hx, + zero_div,min_eq_right (by norm_num : (0:ℝ) ≤ 1)] + +noncomputable def update (S : Set X) (a r : ℝ) (t : X → ℝ) (x : X) : ℝ := + scalar a r (t x)*taper S r x + +lemma update_lipschitz {S : Set X} {a r : ℝ} {t : X → ℝ} + (ha : 0 < a) (hr : 0 < r) (har : 2*a ≤ 8*r) (ht : LipschitzWith 4 t) : + LipschitzWith 34 (update S a r t) := by + have hs : LipschitzWith 24 (fun x => scalar a r (t x)) := by + simpa only [Function.comp_def,show (6:ℝ≥0)*4=24 by norm_num] using + (scalar_lipschitz ha hr har).comp ht + apply LipschitzWith.of_dist_le_mul + intro x y + have hxy := hs.dist_le_mul x y + rw [Real.dist_eq] at hxy + norm_num at hxy ⊢ + obtain ⟨hfx,hfx'⟩ := taper_bounds (S := S) hr x + have he : update S a r t x-update S a r t y = + (scalar a r (t x)-scalar a r (t y))*taper S r x+ + scalar a r (t y)*(taper S r x-taper S r y) := by unfold update; ring + rw [Real.dist_eq,he] + calc + _ ≤ |(scalar a r (t x)-scalar a r (t y))*taper S r x|+ + |scalar a r (t y)*(taper S r x-taper S r y)| := abs_add_le _ _ + _ = |scalar a r (t x)-scalar a r (t y)| *taper S r x+ + |scalar a r (t y)| *|taper S r x-taper S r y| := by rw [abs_mul,abs_mul,abs_of_nonneg hfx] + _ ≤ (24*dist x y)*1+(10*r)*(dist x y/r) := by + exact add_le_add (mul_le_mul hxy hfx' hfx (by positivity)) + (mul_le_mul (scalar_magnitude ha hr har) (taper_difference hr x y) + (abs_nonneg _) (by positivity)) + _ = 34*dist x y := by field_simp; ring + +lemma update_magnitude {S : Set X} {a r : ℝ} {t : X → ℝ} + (ha : 0 < a) (hr : 0 < r) (har : 2*a ≤ 8*r) (x : X) : + |update S a r t x| ≤ 10*r := by + obtain ⟨h,h'⟩ := taper_bounds (S := S) hr x + rw [update,abs_mul,abs_of_nonneg h] + calc + _ ≤ (10*r)*1 := mul_le_mul (scalar_magnitude ha hr har) h' h (by positivity) + _ = 10*r := mul_one _ + +lemma update_zero {S : Set X} {a r : ℝ} {t : X → ℝ} {x : X} (hx : x ∈ S) : + update S a r t x = 0 := by rw [update,taper_zero hx,mul_zero] + +lemma update_support {S : Set X} {a r : ℝ} {t : X → ℝ} + (ha : 0 < a) (hr : 0 < r) (har : 2*a ≤ 8*r) {x : X} + (hx : update S a r t x ≠ 0) : a < |t x| ∧ |t x| < 10*r := + scalar_support ha hr har (left_ne_zero_of_mul hx) + +lemma sum_lipschitz_sparse {I : Type*} (A : Finset I) {f : I → X → ℝ} {K : ℝ≥0} + (hf : ∀ i ∈ A, LipschitzWith K (f i)) + (hs : ∀ x, (A.filter (fun i => f i x ≠ 0)).card ≤ 1) : + LipschitzWith (2*K) (fun x => ∑ i ∈ A, f i x) := by + classical + apply LipschitzWith.of_dist_le_mul + intro x y + let T := (A.filter (fun i => f i x ≠ 0)) ∪ (A.filter (fun i => f i y ≠ 0)) + have hTA : T ⊆ A := Finset.union_subset (Finset.filter_subset _ _) (Finset.filter_subset _ _) + have hc : T.card ≤ 2 := (Finset.card_union_le _ _).trans (by linarith [hs x,hs y]) + have he : ∑ i ∈ A, (f i x-f i y) = ∑ i ∈ T, (f i x-f i y) := by + symm + apply Finset.sum_subset hTA + intro i hi hnot + have hix : f i x = 0 := by + by_contra h + exact hnot (Finset.mem_union_left _ (Finset.mem_filter.mpr ⟨hi,h⟩)) + have hiy : f i y = 0 := by + by_contra h + exact hnot (Finset.mem_union_right _ (Finset.mem_filter.mpr ⟨hi,h⟩)) + rw [hix,hiy,sub_self] + rw [Real.dist_eq,← Finset.sum_sub_distrib,he] + calc + _ ≤ ∑ i ∈ T, |f i x-f i y| := Finset.abs_sum_le_sum_abs _ _ + _ ≤ ∑ _i ∈ T, (K:ℝ)*dist x y := Finset.sum_le_sum (fun i hi => + by simpa only [Real.dist_eq] using (hf i (hTA hi)).dist_le_mul x y) + _ = (T.card:ℝ)*((K:ℝ)*dist x y) := by simp + _ ≤ 2*((K:ℝ)*dist x y) := + mul_le_mul_of_nonneg_right (by exact_mod_cast hc) (by positivity) + _ = ((2*K:ℝ≥0):ℝ)*dist x y := by simp; ring + +lemma update_sparse {I : Type*} (A : Finset I) {c : ℝ} {r : I → ℝ} {t : X → ℝ} + {S : I → Set X} (hc : 0 < c) (hcr : c ≤ 4) + (hr : ∀ i ∈ A, 0 < r i) + (hsep : ∀ i ∈ A, ∀ j ∈ A, i ≠ j → 10*r i ≤ c*r j ∨ 10*r j ≤ c*r i) + (x : X) : (A.filter (fun i => update (S i) (c*r i) (r i) t x ≠ 0)).card ≤ 1 := by + classical + apply Finset.card_le_one.mpr + intro i hi j hj + obtain ⟨hiA,hi⟩ := Finset.mem_filter.mp hi + obtain ⟨hjA,hj⟩ := Finset.mem_filter.mp hj + by_contra hij + obtain ⟨hil,hiu⟩ := update_support (mul_pos hc (hr i hiA)) (hr i hiA) + (by nlinarith [hr i hiA]) hi + obtain ⟨hjl,hju⟩ := update_support (mul_pos hc (hr j hjA)) (hr j hjA) + (by nlinarith [hr j hjA]) hj + rcases hsep i hiA j hjA hij with h | h <;> linarith + +lemma lifetime_lipschitz {I : Type*} (A : Finset I) {c : ℝ} {r : I → ℝ} {t : X → ℝ} + {S : I → Set X} (hc : 0 < c) (hcr : c ≤ 4) + (hr : ∀ i ∈ A, 0 < r i) (ht : LipschitzWith 4 t) + (hsep : ∀ i ∈ A, ∀ j ∈ A, i ≠ j → 10*r i ≤ c*r j ∨ 10*r j ≤ c*r i) : + LipschitzWith 68 (fun x => ∑ i ∈ A, update (S i) (c*r i) (r i) t x) := by + have h := sum_lipschitz_sparse A (K := 34) + (f := fun i => update (S i) (c*r i) (r i) t) + (fun i hi => update_lipschitz (mul_pos hc (hr i hi)) (hr i hi) + (by nlinarith [hr i hi]) ht) (update_sparse A hc hcr hr hsep) + norm_num only at h + exact h + +noncomputable def signedUpdate (e : Bool) (S : Set X) (a r : ℝ) (t : X → ℝ) (x : X) : ℝ := + if e then update S a r t x else -update S a r t x + +lemma signed_lifetime_lipschitz {I : Type*} (A : Finset I) {c : ℝ} {r : I → ℝ} {t : X → ℝ} + {S : I → Set X} (e : I → Bool) (hc : 0 < c) (hcr : c ≤ 4) + (hr : ∀ i ∈ A, 0 < r i) (ht : LipschitzWith 4 t) + (hsep : ∀ i ∈ A, ∀ j ∈ A, i ≠ j → 10*r i ≤ c*r j ∨ 10*r j ≤ c*r i) : + LipschitzWith 68 (fun x => ∑ i ∈ A, signedUpdate (e i) (S i) (c*r i) (r i) t x) := by + have hf (i) (hi : i ∈ A) : LipschitzWith 34 (signedUpdate (e i) (S i) (c*r i) (r i) t) := by + have h := update_lipschitz (S := S i) (mul_pos hc (hr i hi)) (hr i hi) + (by nlinarith [hr i hi]) ht + cases e i + · exact h.neg + · exact h + have he (x) : A.filter (fun i => signedUpdate (e i) (S i) (c*r i) (r i) t x ≠ 0) = + A.filter (fun i => update (S i) (c*r i) (r i) t x ≠ 0) := by + apply Finset.filter_congr + intro i _ + cases e i <;> simp [signedUpdate] + have h := sum_lipschitz_sparse A hf (fun x => by rw [he]; exact update_sparse A hc hcr hr hsep x) + norm_num only at h + exact h + +lemma taper_one {S : Set X} {r : ℝ} {x : X} (hr : 0 < r) + (hx : S.Nonempty → r ≤ infDist x S) : taper S r x = 1 := by + unfold taper + split_ifs with h + · apply min_eq_left + exact (le_div_iff₀ hr).mpr (by simpa only [one_mul] using hx h) + · rfl + +lemma update_plateau {S : Set X} {a r : ℝ} {t : X → ℝ} {x : X} + (ha : 0 < a) (hr : 0 < r) (hl : 2*a ≤ |t x|) (hu : |t x| ≤ 8*r) + (hx : S.Nonempty → r ≤ infDist x S) : update S a r t x = t x := by + rw [update,scalar_plateau ha hl hu,taper_one hr hx,mul_one] + +end Taper + +lemma opposite_sign_gain (p q : ℝ) : |q| ≤ |p+q| ∨ |q| ≤ |p-q| := by + by_contra h + push Not at h + have ht := abs_sub_le (p+q) 0 (p-q) + have he : |(p+q)-(p-q)| = 2*|q| := by + rw [show (p+q)-(p-q) = 2*q by ring,abs_mul,abs_of_pos (by norm_num : (0:ℝ) < 2)] + rw [he,sub_zero,zero_sub,abs_neg] at ht + linarith + +lemma geometric_separation {r c Q : ℝ} (hr : 0 < r) + (hQ : 1 < Q) (hsep : 10 ≤ c*Q) {i j : ℕ} (hij : i < j) : + 10*(r/Q^j) ≤ c*(r/Q^i) := by + have hpow : Q^(i+1) ≤ Q^j := (pow_le_pow_right₀ hQ.le (Nat.succ_le_of_lt hij)) + have hpos : 0 < Q^i := pow_pos (by linarith) _ + calc + _ ≤ 10*(r/Q^(i+1)) := mul_le_mul_of_nonneg_left + (div_le_div_of_nonneg_left hr.le (pow_pos (by linarith) _) hpow) (by norm_num) + _ ≤ c*(r/Q^i) := by + rw [pow_succ] + calc + _ ≤ (c*Q)*(r/(Q^i*Q)) := mul_le_mul_of_nonneg_right hsep + (div_nonneg hr.le (mul_pos hpos (by linarith)).le) + _ = c*(r/Q^i) := by field_simp + + +end PlanarL1.Increment + + + +end + +section + +namespace PlanarL1.Increment +open scoped NNReal +variable {X : Type*} [PseudoMetricSpace X] + +/-- The actual increment with an ambient-metric taper. The scalar transverse +field is measured intrinsically, while this weight may use the unrestricted +metric. -/ +noncomputable def damped (a r : ℝ) (t w : X → ℝ) (x : X) : ℝ := + scalar a r (t x)*w x + +lemma damped_lipschitz {a r : ℝ} {t w : X → ℝ} + (ha : 0 < a) (hr : 0 < r) (har : 2*a ≤ 8*r) (ht : LipschitzWith 4 t) + (hw : ∀ x, 0 ≤ w x ∧ w x ≤ 1) + (hd : ∀ x y, |w x-w y| ≤ dist x y/r) : + LipschitzWith 34 (damped a r t w) := by + have hs : LipschitzWith 24 (fun x => scalar a r (t x)) := by + simpa only [Function.comp_def,show (6:ℝ≥0)*4=24 by norm_num] using + (scalar_lipschitz ha hr har).comp ht + apply LipschitzWith.of_dist_le_mul + intro x y + have hxy := hs.dist_le_mul x y + rw [Real.dist_eq] at hxy + norm_num at hxy ⊢ + have he : damped a r t w x-damped a r t w y = + (scalar a r (t x)-scalar a r (t y))*w x+ + scalar a r (t y)*(w x-w y) := by unfold damped; ring + rw [Real.dist_eq,he] + calc + _ ≤ |(scalar a r (t x)-scalar a r (t y))*w x|+ + |scalar a r (t y)*(w x-w y)| := abs_add_le _ _ + _ = |scalar a r (t x)-scalar a r (t y)| *w x+ + |scalar a r (t y)| *|w x-w y| := by rw [abs_mul,abs_mul,abs_of_nonneg (hw x).1] + _ ≤ (24*dist x y)*1+(10*r)*(dist x y/r) := by + exact add_le_add (mul_le_mul hxy (hw x).2 (hw x).1 (by positivity)) + (mul_le_mul (scalar_magnitude ha hr har) (hd x y) + (abs_nonneg _) (by positivity)) + _ = 34*dist x y := by field_simp; ring + +noncomputable def signedDamped (e : Bool) (a r : ℝ) (t w : X → ℝ) (x : X) : ℝ := + if e then damped a r t w x else -damped a r t w x + +omit [PseudoMetricSpace X] in +lemma signedDamped_support {e : Bool} {a r : ℝ} {t w : X → ℝ} + (ha : 0 < a) (hr : 0 < r) (har : 2*a ≤ 8*r) {x : X} + (hx : signedDamped e a r t w x ≠ 0) : a < |t x| ∧ |t x| < 10*r := by + have hn : damped a r t w x ≠ 0 := by + cases e <;> simpa only [signedDamped,Bool.false_eq_true,ite_false,ite_true,neg_ne_zero] using hx + exact scalar_support ha hr har (left_ne_zero_of_mul hn) + +lemma damped_lifetime {I : Type*} (A : Finset I) {c : ℝ} {r : I → ℝ} {t : X → ℝ} + {w : I → X → ℝ} (e : I → Bool) (hc : 0 < c) (hcr : c ≤ 4) + (hr : ∀ i ∈ A, 0 < r i) (ht : LipschitzWith 4 t) + (hw : ∀ i ∈ A, ∀ x, 0 ≤ w i x ∧ w i x ≤ 1) + (hd : ∀ i ∈ A, ∀ x y, |w i x-w i y| ≤ dist x y/r i) + (hsep : ∀ i ∈ A, ∀ j ∈ A, i ≠ j → 10*r i ≤ c*r j ∨ 10*r j ≤ c*r i) : + LipschitzWith 68 (fun x => ∑ i ∈ A, signedDamped (e i) (c*r i) (r i) t (w i) x) := by + have hf (i) (hi : i ∈ A) : + LipschitzWith 34 (signedDamped (e i) (c*r i) (r i) t (w i)) := by + have h := damped_lipschitz (mul_pos hc (hr i hi)) (hr i hi) + (by nlinarith [hr i hi]) ht (hw i hi) (hd i hi) + cases e i + · exact h.neg + · exact h + have hs (x : X) : (A.filter (fun i => signedDamped (e i) (c*r i) (r i) t (w i) x ≠ 0)).card ≤ 1 := by + classical + apply Finset.card_le_one.mpr + intro i hi j hj + obtain ⟨hiA,hi⟩ := Finset.mem_filter.mp hi + obtain ⟨hjA,hj⟩ := Finset.mem_filter.mp hj + by_contra hij + obtain ⟨hil,hiu⟩ := signedDamped_support (mul_pos hc (hr i hiA)) (hr i hiA) + (by nlinarith [hr i hiA]) hi + obtain ⟨hjl,hju⟩ := signedDamped_support (mul_pos hc (hr j hjA)) (hr j hjA) + (by nlinarith [hr j hjA]) hj + rcases hsep i hiA j hjA hij with h | h <;> linarith + simpa only [show (2:ℝ≥0)*34=68 by norm_num] using sum_lipschitz_sparse A hf hs +end PlanarL1.Increment + + +end + +section + +namespace PlanarL1.Increment +open scoped NNReal +variable {X : Type*} [PseudoMetricSpace X] + +lemma tapered_magnitude {a r q : ℝ} {S : Set X} {x y : X} + (ha : 0 < a) (hr : 0 < r) (har : 2*a ≤ 8*r) (hy : y ∈ S) : + |scalar a r q*taper S r x| ≤ 10*dist x y := by + have hb : taper S r x ≤ dist x y/r := by + unfold taper + rw [ite_eq_left (show S.Nonempty from ⟨y,hy⟩)] + exact (min_le_right _ _).trans + (div_le_div_of_nonneg_right (Metric.infDist_le_dist_of_mem hy) hr.le) + rw [abs_mul,abs_of_nonneg (taper_bounds hr x).1] + calc + _ ≤ (10*r)*(dist x y/r) := mul_le_mul (scalar_magnitude ha hr har) hb + (taper_bounds hr x).1 (by positivity) + _ = 10*dist x y := by field_simp + +lemma signed_tapered_magnitude (e : Bool) {a r q : ℝ} {S : Set X} {x y : X} + (ha : 0 < a) (hr : 0 < r) (har : 2*a ≤ 8*r) (hy : y ∈ S) : + |if e then scalar a r q*taper S r x else -(scalar a r q*taper S r x)| ≤ + 10*dist x y := by + cases e <;> simpa only [Bool.false_eq_true,ite_false,ite_true,abs_neg] using + tapered_magnitude ha hr har hy + +end PlanarL1.Increment + + +end + +end OAI diff --git a/lean/OAI/Combinatorics/PlanarL1/Interpolation.lean b/lean/OAI/Combinatorics/PlanarL1/Interpolation.lean new file mode 100644 index 0000000000000000000000000000000000000000..d9bdcb6703fc62bb5a1f04b4016e0fd217bc22c4 --- /dev/null +++ b/lean/OAI/Combinatorics/PlanarL1/Interpolation.lean @@ -0,0 +1,768 @@ +import OAI.Combinatorics.PlanarL1.Probability + +namespace OAI + +section + +namespace PlanarL1 +/-! ## The deterministic clamping core of thin-band interpolation +No probabilistic or geometric claim is assumed by +these lemmas; they establish the scalar inequalities used at each actual node. -/ + +namespace Interpolation + +/-- The exact parent/tentative clamp in the source: `U=max parent A`, +`L=min parent B`, and `F=min U (max L T)`. -/ +def nodeValue (parent upper lower tentative : ℝ) : ℝ := + min (max parent upper) (max (min parent lower) tentative) + +/-- Whenever both barrier cones exclude movement, an equality collar preserves +the parent value exactly. -/ +theorem nodeValue_collar {parent upper lower tentative : ℝ} + (hu : upper ≤ parent) (hl : parent ≤ lower) : + nodeValue parent upper lower tentative = parent := by + simp only [nodeValue, max_eq_left hu, min_eq_left hl] + exact min_eq_left (le_max_left _ _) + +/-- Clamping into an interval whose upper end is not too small and whose lower +end is not too large preserves the claimed accuracy window. -/ +theorem nodeValue_bounds {parent upper lower tentative lo hi : ℝ} + (hlo : lo ≤ upper) (hhi : lower ≤ hi) + (htlo : lo ≤ tentative) (hthi : tentative ≤ hi) : + lo ≤ nodeValue parent upper lower tentative ∧ + nodeValue parent upper lower tentative ≤ hi := by + constructor + · exact le_min (hlo.trans (le_max_right _ _)) (htlo.trans (le_max_right _ _)) + · exact (min_le_right _ _).trans (max_le ((min_le_right _ _).trans hhi) hthi) + +/-- The obstruction in `int:depth`: a distant node cannot pass an accurate +parent value unchanged. The constants 6, 7 and 13 are the source's constants. -/ +theorem distant_node_overwrites {parent upper lower tentative p δ : ℝ} + (hδ : 0 < δ) (hp : |parent - p| ≤ 6 * δ) + (hu : p + 7 * δ < upper) (hl : lower < p - 7 * δ) + (ht : p + 13 * δ < tentative) : + p + 7 * δ < nodeValue parent upper lower tentative ∧ + nodeValue parent upper lower tentative ≠ parent := by + have habs := abs_le.mp hp + have hup : parent < upper := by linarith + have hlow : lower < parent := by linarith + have hv : p + 7 * δ < nodeValue parent upper lower tentative := by + simp only [nodeValue, max_eq_right hup.le, min_eq_right hlow.le] + exact lt_min hu ((by linarith : p + 7 * δ < tentative).trans_le (le_max_right _ _)) + refine ⟨hv, ?_⟩ + intro heq + rw [heq] at hv + linarith + +/-- An atom evaluation together with its deterministic priority/inheritance +name. Its value may depend on all the already sampled ancestor noises. -/ +structure NamedValue where + name : ℕ + value : ℝ + +/-- Minima and maxima both resolve ties toward the earliest atom name. -/ +noncomputable def minNamed (a b : NamedValue) : NamedValue := + if a.value < b.value ∨ (a.value = b.value ∧ a.name ≤ b.name) then a else b + +noncomputable def maxNamed (a b : NamedValue) : NamedValue := + if b.value < a.value ∨ (a.value = b.value ∧ a.name ≤ b.name) then a else b + +lemma minNamed_mem (a b : NamedValue) : minNamed a b = a ∨ minNamed a b = b := by + unfold minNamed + split_ifs <;> simp + +lemma maxNamed_mem (a b : NamedValue) : maxNamed a b = a ∨ maxNamed a b = b := by + unfold maxNamed + split_ifs <;> simp + +@[simp] +lemma minNamed_value (a b : NamedValue) : (minNamed a b).value = min a.value b.value := by + unfold minNamed + split_ifs with h + · rcases h with h | ⟨h, _⟩ + · exact (min_eq_left h.le).symm + · exact (min_eq_left h.le).symm + · have hh : b.value ≤ a.value := le_of_not_gt (fun hh => h (Or.inl hh)) + exact (min_eq_right hh).symm + +@[simp] +lemma maxNamed_value (a b : NamedValue) : (maxNamed a b).value = max a.value b.value := by + unfold maxNamed + split_ifs with h + · rcases h with h | ⟨h, _⟩ + · exact (max_eq_left h.le).symm + · exact (max_eq_left h.ge).symm + · have hh : a.value ≤ b.value := le_of_not_gt (fun hh => h (Or.inl hh)) + exact (max_eq_right hh).symm + +/-- The clamp with the manuscript's consistent atom-name tie rule. -/ +noncomputable def nodeNamed (parent upper lower tentative : NamedValue) : NamedValue := + minNamed (maxNamed parent upper) (maxNamed (minNamed parent lower) tentative) + +@[simp] +lemma nodeNamed_value (parent upper lower tentative : NamedValue) : + (nodeNamed parent upper lower tentative).value = + nodeValue parent.value upper.value lower.value tentative.value := by + simp [nodeNamed, nodeValue] + +lemma nodeNamed_mem (parent upper lower tentative : NamedValue) : + nodeNamed parent upper lower tentative = parent ∨ + nodeNamed parent upper lower tentative = upper ∨ + nodeNamed parent upper lower tentative = lower ∨ + nodeNamed parent upper lower tentative = tentative := by + rcases minNamed_mem (maxNamed parent upper) + (maxNamed (minNamed parent lower) tentative) with h | h + · rcases maxNamed_mem parent upper with h' | h' + · exact Or.inl (h.trans h') + · exact Or.inr (Or.inl (h.trans h')) + · rcases maxNamed_mem (minNamed parent lower) tentative with h' | h' + · rcases minNamed_mem parent lower with h'' | h'' + · exact Or.inl ((h.trans h').trans h'') + · exact Or.inr (Or.inr (Or.inl ((h.trans h').trans h''))) + · exact Or.inr (Or.inr (Or.inr (h.trans h'))) + +/-- A name from before the current node can only be selected by literally +inheriting the parent's atom. In particular its scalar value is inherited too. -/ +lemma nodeNamed_old {parent upper lower tentative : NamedValue} {cutoff : ℕ} + (hu : cutoff ≤ upper.name) (hl : cutoff ≤ lower.name) + (ht : cutoff ≤ tentative.name) + (h : (nodeNamed parent upper lower tentative).name < cutoff) : + nodeNamed parent upper lower tentative = parent := by + rcases nodeNamed_mem parent upper lower tentative with heq | heq | heq | heq + · exact heq + all_goals rw [heq] at h; omega + +/-- The complete equality collar, including exact retention of the parent +atom's name . -/ +lemma nodeNamed_collar {parent upper lower tentative : NamedValue} + (hu : upper.value < parent.value) (hl : parent.value < lower.value) + (ht : parent.name ≤ tentative.name) : + nodeNamed parent upper lower tentative = parent := by + have hU : maxNamed parent upper = parent := by + simp only [maxNamed, ite_eq_left (Or.inl hu)] + have hL : minNamed parent lower = parent := by + simp only [minNamed, ite_eq_left (Or.inl hl)] + simp only [nodeNamed, hU, hL] + rcases lt_trichotomy parent.value tentative.value with h | h | h + · have hm : maxNamed parent tentative = tentative := by + apply ite_eq_right + push Not + exact ⟨h.le, fun hh => (h.ne hh).elim⟩ + rw [hm] + exact ite_eq_left (Or.inl h) + · have hm : maxNamed parent tentative = parent := ite_eq_left (Or.inr ⟨h, ht⟩) + rw [hm] + exact ite_eq_left (Or.inr ⟨rfl, le_rfl⟩) + · have hm : maxNamed parent tentative = parent := ite_eq_left (Or.inl h) + rw [hm] + exact ite_eq_left (Or.inr ⟨rfl, le_rfl⟩) + +/-- Iterated inheritance along a fixed ancestor chain. This does not make +any independence assumption on the already computed scalar intercepts. -/ +lemma chain_inherits {F U L T : ℕ → NamedValue} {k n cutoff : ℕ} + (hkn : k ≤ n) + (hrec : ∀ j, F (j + 1) = nodeNamed (F j) (U (j + 1)) (L (j + 1)) (T (j + 1))) + (hnew : ∀ j, k ≤ j → j < n → + cutoff ≤ (U (j + 1)).name ∧ cutoff ≤ (L (j + 1)).name ∧ + cutoff ≤ (T (j + 1)).name) + (hout : (F n).name < cutoff) : F n = F k := by + induction n, hkn using Nat.le_induction with + | base => rfl + | succ n hkn ih => + obtain ⟨hu, hl, ht⟩ := hnew n hkn (Nat.lt_succ_self n) + have hstep : F (n + 1) = F n := by + rw [hrec n] at hout ⊢ + exact nodeNamed_old hu hl ht hout + exact hstep.trans (ih (fun j hkj hjn => hnew j hkj (hjn.trans (Nat.lt_succ_self n))) + (hstep ▸ hout)) + +/-- Quantitative bounded ancestry. At a distant node `k`, the source's 7δ/13δ +barriers prevent an accurate final value from retaining a name originating +strictly before `k`. All actual new atoms of stage `j` have names ≥ `6*j`. +This is the substantive inheritance argument of lemma `int:depth`. -/ +theorem bounded_ancestry {F U L T : ℕ → NamedValue} {k n : ℕ} {p δ : ℝ} + (hk : 1 ≤ k) (hkn : k ≤ n) (hδ : 0 < δ) + (hrec : ∀ j, F (j + 1) = nodeNamed (F j) (U (j + 1)) (L (j + 1)) (T (j + 1))) + (hnew : ∀ j, 6 * j ≤ (U j).name ∧ 6 * j ≤ (L j).name ∧ 6 * j ≤ (T j).name) + (haccuracy : |(F n).value - p| ≤ 6 * δ) + (hu : p + 7 * δ < (U k).value) (hl : (L k).value < p - 7 * δ) + (ht : p + 13 * δ < (T k).value) : 6 * k ≤ (F n).name := by + by_contra hh + have hout : (F n).name < 6 * k := by omega + have heq : F n = F (k - 1) := by + apply chain_inherits (by omega) hrec _ hout + intro j hj hjn + have hkj : 6 * k ≤ 6 * (j + 1) := by omega + exact ⟨hkj.trans (hnew (j + 1)).1, hkj.trans (hnew (j + 1)).2.1, + hkj.trans (hnew (j + 1)).2.2⟩ + have hmid : F n = F k := by + apply chain_inherits hkn hrec _ hout + intro j hj hjn + have hkj : 6 * k ≤ 6 * (j + 1) := by omega + exact ⟨hkj.trans (hnew (j + 1)).1, hkj.trans (hnew (j + 1)).2.1, + hkj.trans (hnew (j + 1)).2.2⟩ + have hkrec : F k = nodeNamed (F (k - 1)) (U k) (L k) (T k) := by + simpa only [Nat.sub_add_cancel hk] using hrec (k - 1) + have hp : |(F (k - 1)).value - p| ≤ 6 * δ := by simpa only [← heq] using haccuracy + have hneq := (distant_node_overwrites hδ hp hu hl ht).2 + apply hneq + rw [← nodeNamed_value, ← hkrec, ← hmid, heq] + +/-- There are at most `6*(M+1)` names in the last `M+1` levels, independently +of the total depth. This is the exact deterministic list-size bound `N`. -/ +lemma recent_name_count (n M : ℕ) : + (Finset.Ico (6 * (n - M)) (6 * (n + 1))).card ≤ 6 * (M + 1) := by + rw [Nat.card_Ico] + omega + +/-- Both signed distance cones have their exact unit Lipschitz constant. -/ +lemma distance_cone_lipschitz {X : Type*} [PseudoMetricSpace X] (x : X) (c : ℝ) : + LipschitzWith 1 (fun v => c + dist x v) ∧ + LipschitzWith 1 (fun v => c - dist x v) := by + constructor <;> apply LipschitzWith.of_dist_le_mul <;> intro u v + · simpa only [Real.dist_eq, add_sub_add_left_eq_sub, NNReal.coe_one, one_mul, dist_comm x] using + abs_dist_sub_le u v x + · rw [Real.dist_eq] + have he : c - dist x u - (c - dist x v) = dist x v - dist x u := by ring + rw [he, abs_sub_comm] + simpa only [NNReal.coe_one, one_mul, dist_comm x] using abs_dist_sub_le u v x + +lemma nodeValue_lipschitz {X : Type*} [PseudoMetricSpace X] + {P A B T : X → ℝ} (hP : LipschitzWith 1 P) (hA : LipschitzWith 1 A) + (hB : LipschitzWith 1 B) (hT : LipschitzWith 1 T) : + LipschitzWith 1 (fun x => nodeValue (P x) (A x) (B x) (T x)) := by + simpa only [nodeValue, max_self] using (hP.max hA).min ((hP.min hB).max hT) + + +end Interpolation + + + +end PlanarL1 + +end + +section + +namespace PlanarL1.Interpolation +open scoped NNReal + +/-- A continuous finite selection cannot change its recorded branch on a ball +without a near tie at the center. This includes the old-field branch of a +clipping, even though that branch has no fresh offset of its own. -/ +lemma selection_near_tie {X : Type*} [PseudoMetricSpace X] {K : ℝ≥0} + (F : X → NamedValue) (atom : ℕ → X → ℝ) (S : Finset ℕ) + (hF : LipschitzWith K (fun z => (F z).value)) + (hA : ∀ i ∈ S, LipschitzWith K (atom i)) (x : X) {ρ : ℝ} + (hρ : 0 ≤ ρ) + (hlist : ∀ z, dist x z ≤ ρ → (F z).name ∈ S ∧ (F z).value = atom (F z).name z) + (hbad : ∃ z, dist x z ≤ ρ ∧ (F z).name ≠ (F x).name) : + ∃ i ∈ S, ∃ j ∈ S, i ≠ j ∧ |atom i x-atom j x| ≤ 2*K*ρ := by + obtain ⟨z,hz,hn⟩ := hbad + have hx := hlist x (by simpa using hρ) + have hz' := hlist z hz + refine ⟨(F x).name,hx.1,(F z).name,hz'.1,Ne.symm hn,?_⟩ + have hf := hF.dist_le_mul x z + have ha := (hA (F z).name hz'.1).dist_le_mul z x + rw [Real.dist_eq,dist_comm z x,← hz'.2] at ha + rw [Real.dist_eq] at hf + rw [← hx.2] + have ht := abs_sub_le (F x).value (F z).value (atom (F z).name x) + have hm := mul_le_mul_of_nonneg_left hz K.coe_nonneg + linarith + +lemma selection_probability {X Ω : Type*} [PseudoMetricSpace X] [Fintype Ω] + {K : ℝ≥0} (F : Ω → X → NamedValue) (atom : Ω → ℕ → X → ℝ) + (S : Finset ℕ) (hF : ∀ ω, LipschitzWith K (fun z => (F ω z).value)) + (hA : ∀ ω i, i ∈ S → LipschitzWith K (atom ω i)) (x : X) {ρ b : ℝ} + (hρ : 0 ≤ ρ) (hb : 0 ≤ b) + (hlist : ∀ ω z, dist x z ≤ ρ → (F ω z).name ∈ S ∧ + (F ω z).value = atom ω (F ω z).name z) + (hpair : ∀ i ∈ S, ∀ j ∈ S, i ≠ j → + FiniteRandom.prob (fun ω => |atom ω i x-atom ω j x| ≤ 2*K*ρ) ≤ b) : + FiniteRandom.prob (fun ω => ∃ z, dist x z ≤ ρ ∧ (F ω z).name ≠ (F ω x).name) ≤ + S.card^2*b := by + apply (FiniteRandom.prob_mono (fun ω h => + selection_near_tie (F ω) (atom ω) S (hF ω) (hA ω) x hρ (hlist ω) h)).trans + exact FiniteRandom.prob_pair_bound S _ hb hpair + +end PlanarL1.Interpolation + + +end + +section + +namespace PlanarL1.Interpolation +open scoped NNReal + +noncomputable def clippedNamed (o p h : NamedValue) : NamedValue := + maxNamed o (minNamed p h) + +lemma clippedNamed_mem (o p h : NamedValue) : + clippedNamed o p h = o ∨ clippedNamed o p h = p ∨ clippedNamed o p h = h := by + rcases maxNamed_mem o (minNamed p h) with he | he + · exact Or.inl he + · rcases minNamed_mem p h with he' | he' + · exact Or.inr (Or.inl (he.trans he')) + · exact Or.inr (Or.inr (he.trans he')) + +lemma clippedNamed_value (o p h : NamedValue) : + (clippedNamed o p h).value = max o.value (min p.value h.value) := by + simp only [clippedNamed,maxNamed_value,minNamed_value] + +noncomputable def clipNames (S : Finset ℕ) : Finset ℕ := + insert 0 (insert 1 (S.image (fun i => i+2))) + +lemma clipNames_card (S : Finset ℕ) : (clipNames S).card ≤ S.card+2 := by + calc + _ ≤ (insert 1 (S.image (fun i => i+2))).card+1 := Finset.card_insert_le _ _ + _ ≤ (S.image (fun i => i+2)).card+1+1 := Nat.add_le_add_right (Finset.card_insert_le _ _) _ + _ ≤ S.card+2 := by have h := Finset.card_image_le (s := S) (f := fun i => i+2); omega + +lemma mem_clipNames {S : Finset ℕ} {i : ℕ} : + i ∈ clipNames S ↔ i = 0 ∨ i = 1 ∨ (2 ≤ i ∧ i-2 ∈ S) := by + simp only [clipNames,Finset.mem_insert,Finset.mem_image] + constructor + · rintro (h | h | ⟨j,hj,rfl⟩) + · exact Or.inl h + · exact Or.inr (Or.inl h) + · exact Or.inr (Or.inr ⟨by omega,by simpa using hj⟩) + · rintro (h | h | ⟨hi,hS⟩) + · exact Or.inl h + · exact Or.inr (Or.inl h) + · exact Or.inr (Or.inr ⟨i-2,hS,by omega⟩) + +/-- The old field has priority zero; the shield has priority one, and actual +inherited atom identities are shifted by two. Thus a retaining tie keeps the +old identifier, just as required by the source chart update. -/ +noncomputable def namedClip {X : Type*} (F : X → NamedValue) (old shield : X → ℝ) + (x : X) : NamedValue := + clippedNamed ⟨0,old x⟩ ⟨(F x).name+2,(F x).value⟩ ⟨1,shield x⟩ + +noncomputable def clipAtom {X : Type*} (atom : ℕ → X → ℝ) (old shield : X → ℝ) + (i : ℕ) (x : X) : ℝ := if i = 0 then old x else if i = 1 then shield x else atom (i-2) x + +lemma namedClip_list {X : Type*} (F : X → NamedValue) (atom : ℕ → X → ℝ) + (old shield : X → ℝ) (S : Finset ℕ) (x : X) + (hm : (F x).name ∈ S) (he : (F x).value = atom (F x).name x) : + (namedClip F old shield x).name ∈ clipNames S ∧ + (namedClip F old shield x).value = clipAtom atom old shield (namedClip F old shield x).name x := by + rcases clippedNamed_mem ⟨0,old x⟩ ⟨(F x).name+2,(F x).value⟩ ⟨1,shield x⟩ with h | h | h + · change namedClip F old shield x = _ at h + rw [h] + simp [clipNames,clipAtom] + · change namedClip F old shield x = _ at h + rw [h] + dsimp only + have hz : (F x).name+2 ≠ 0 := by omega + have ho : (F x).name+2 ≠ 1 := by omega + constructor + · exact mem_clipNames.mpr (Or.inr (Or.inr ⟨by omega,by simpa using hm⟩)) + · simpa only [clipAtom,ite_eq_right hz,ite_eq_right ho,Nat.add_sub_cancel] using he + · change namedClip F old shield x = _ at h + rw [h] + simp [clipNames,clipAtom] + +lemma clipAtom_lipschitz {X : Type*} [PseudoMetricSpace X] {K : ℝ≥0} + (atom : ℕ → X → ℝ) (old shield : X → ℝ) + (hA : ∀ i, LipschitzWith K (atom i)) (ho : LipschitzWith K old) + (hh : LipschitzWith K shield) (i : ℕ) : + LipschitzWith K (clipAtom atom old shield i) := by + apply LipschitzWith.of_dist_le_mul + intro x y + dsimp only [clipAtom] + split_ifs with hi hi' + · exact ho.dist_le_mul x y + · exact hh.dist_le_mul x y + · exact (hA (i-2)).dist_le_mul x y + +end PlanarL1.Interpolation + + +namespace PlanarL1.Interpolation +lemma clippedNamed_retains {o p h : NamedValue} (hp : p.value < o.value) : + clippedNamed o p h = o := by + have ht : (minNamed p h).value < o.value := by + rw [minNamed_value] + exact (min_le_left _ _).trans_lt hp + exact ite_eq_left (Or.inl ht) +end PlanarL1.Interpolation + + +end + +section + +namespace PlanarL1.Interpolation +open scoped NNReal + +noncomputable def secondaryNames (S : Finset ℕ) : Finset ℕ := + insert 0 (insert 1 (insert 2 (S.image (fun i => i+3)))) + +lemma secondaryNames_card (S : Finset ℕ) : (secondaryNames S).card ≤ S.card+3 := by + unfold secondaryNames + calc + _ ≤ ((S.image (fun i => i+3)).card+1)+1+1 := by + exact (Finset.card_insert_le _ _).trans (Nat.add_le_add_right + ((Finset.card_insert_le _ _).trans (Nat.add_le_add_right + (Finset.card_insert_le _ _) 1)) 1) + _ ≤ S.card+3 := by have h := Finset.card_image_le (s := S) (f := fun i => i+3); omega + +lemma mem_secondaryNames {S : Finset ℕ} {i : ℕ} : + i ∈ secondaryNames S ↔ i=0 ∨ i=1 ∨ i=2 ∨ (3 ≤ i ∧ i-3 ∈ S) := by + classical + simp only [secondaryNames,Finset.mem_insert,Finset.mem_image] + constructor + · rintro (h | h | h | ⟨j,hj,h⟩) + · exact Or.inl h + · exact Or.inr (Or.inl h) + · exact Or.inr (Or.inr (Or.inl h)) + · right; right; right + exact ⟨by omega,by simpa only [← h,Nat.add_sub_cancel] using hj⟩ + · rintro (h | h | h | ⟨hi,h⟩) + · exact Or.inl h + · exact Or.inr (Or.inl h) + · exact Or.inr (Or.inr (Or.inl h)) + · right; right; right + exact ⟨i-3,h,by omega⟩ + +noncomputable def secondaryNamed {X : Type*} (F : X → NamedValue) + (old ordered shield : X → ℝ) (ordinary : Bool) (x : X) : NamedValue := + clippedNamed ⟨0,old x⟩ + (if ordinary then minNamed ⟨(F x).name+3,(F x).value⟩ ⟨2,ordered x⟩ + else ⟨(F x).name+3,(F x).value⟩) ⟨1,shield x⟩ + +noncomputable def secondaryAtom {X : Type*} (atom : ℕ → X → ℝ) + (old ordered shield : X → ℝ) (i : ℕ) (x : X) : ℝ := + if i=0 then old x else if i=1 then shield x else if i=2 then ordered x else atom (i-3) x + +lemma secondaryNamed_value {X : Type*} (F : X → NamedValue) + (old ordered shield : X → ℝ) (ordinary : Bool) (x : X) : + (secondaryNamed F old ordered shield ordinary x).value = + max (old x) (min (if ordinary then min (F x).value (ordered x) else (F x).value) (shield x)) := by + cases ordinary <;> simp only [secondaryNamed,clippedNamed_value,Bool.false_eq_true, + ite_false,ite_true,minNamed_value] + +lemma secondaryNamed_mem {X : Type*} (F : X → NamedValue) + (old ordered shield : X → ℝ) (ordinary : Bool) (x : X) : + secondaryNamed F old ordered shield ordinary x = ⟨0,old x⟩ ∨ + secondaryNamed F old ordered shield ordinary x = ⟨1,shield x⟩ ∨ + secondaryNamed F old ordered shield ordinary x = ⟨2,ordered x⟩ ∨ + secondaryNamed F old ordered shield ordinary x = ⟨(F x).name+3,(F x).value⟩ := by + rcases clippedNamed_mem ⟨0,old x⟩ + (if ordinary then minNamed ⟨(F x).name+3,(F x).value⟩ ⟨2,ordered x⟩ + else ⟨(F x).name+3,(F x).value⟩) ⟨1,shield x⟩ with h | h | h + · exact Or.inl h + · change secondaryNamed F old ordered shield ordinary x = _ at h + cases ordinary with + | false => exact Or.inr (Or.inr (Or.inr h)) + | true => + rcases minNamed_mem ⟨(F x).name+3,(F x).value⟩ ⟨2,ordered x⟩ with ha | ha + · exact Or.inr (Or.inr (Or.inr (h.trans ha))) + · exact Or.inr (Or.inr (Or.inl (h.trans ha))) + · exact Or.inr (Or.inl h) + +lemma secondaryNamed_list {X : Type*} (F : X → NamedValue) (atom : ℕ → X → ℝ) + (old ordered shield : X → ℝ) (ordinary : Bool) (S : Finset ℕ) (x : X) + (hm : (F x).name ∈ S) (he : (F x).value = atom (F x).name x) : + (secondaryNamed F old ordered shield ordinary x).name ∈ secondaryNames S ∧ + (secondaryNamed F old ordered shield ordinary x).value = + secondaryAtom atom old ordered shield (secondaryNamed F old ordered shield ordinary x).name x := by + rcases secondaryNamed_mem F old ordered shield ordinary x with h | h | h | h + · rw [h]; simp [secondaryNames,secondaryAtom] + · rw [h]; simp [secondaryNames,secondaryAtom] + · rw [h]; simp [secondaryNames,secondaryAtom] + · rw [h] + dsimp only + have h0 : (F x).name+3 ≠ 0 := by omega + have h1 : (F x).name+3 ≠ 1 := by omega + have h2 : (F x).name+3 ≠ 2 := by omega + constructor + · exact mem_secondaryNames.mpr (Or.inr (Or.inr (Or.inr ⟨by omega,by simpa using hm⟩))) + · simpa only [secondaryAtom,ite_eq_right h0,ite_eq_right h1,ite_eq_right h2,Nat.add_sub_cancel] using he + +lemma secondaryAtom_lipschitz {X : Type*} [PseudoMetricSpace X] {K : ℝ≥0} + (atom : ℕ → X → ℝ) (old ordered shield : X → ℝ) + (hA : ∀ i, LipschitzWith K (atom i)) (ho : LipschitzWith K old) + (hO : LipschitzWith K ordered) (hh : LipschitzWith K shield) (i : ℕ) : + LipschitzWith K (secondaryAtom atom old ordered shield i) := by + apply LipschitzWith.of_dist_le_mul + intro x y + dsimp only [secondaryAtom] + split_ifs with hi hi' hi'' + · exact ho.dist_le_mul x y + · exact hh.dist_le_mul x y + · exact hO.dist_le_mul x y + · exact (hA (i-3)).dist_le_mul x y + +end PlanarL1.Interpolation + + +end + +section + +namespace PlanarL1.Interpolation +open scoped NNReal + +/-- Retained old branches are shared (name zero). Every genuinely new group +branch receives a distinct name including its group, not merely its formula. -/ +def familyName {k : ℕ} (g : Fin k) (i : ℕ) : ℕ := + if i=0 then 0 else Nat.pair g.val (i-1)+1 + +lemma familyName_zero {k : ℕ} (g : Fin k) : familyName g 0 = 0 := by + simp [familyName] + +lemma familyName_ne_zero {k : ℕ} (g : Fin k) {i : ℕ} (hi : i ≠ 0) : + familyName g i ≠ 0 := by simp [familyName,hi] + +lemma familyName_inj {k : ℕ} (g h : Fin k) {i j : ℕ} (hi : i ≠ 0) (hj : j ≠ 0) : + familyName g i = familyName h j ↔ g=h ∧ i=j := by + simp only [familyName,ite_eq_right hi,ite_eq_right hj,Nat.add_right_cancel_iff,Nat.pair_eq_pair] + constructor + · rintro ⟨hg,hs⟩ + exact ⟨Fin.ext hg,by omega⟩ + · rintro ⟨rfl,rfl⟩; exact ⟨rfl,rfl⟩ + +noncomputable def familyNames {k : ℕ} (S : Fin k → Finset ℕ) : Finset ℕ := + insert 0 (Finset.univ.biUnion (fun g => (S g).image (familyName g))) + +lemma mem_familyNames {k : ℕ} {S : Fin k → Finset ℕ} {i : ℕ} : + i ∈ familyNames S ↔ i=0 ∨ ∃ g, ∃ j ∈ S g, familyName g j=i := by + classical + simp [familyNames] + +lemma familyNames_card {k N : ℕ} (S : Fin k → Finset ℕ) + (hS : ∀ g, (S g).card ≤ N) : (familyNames S).card ≤ 1+k*N := by + classical + calc + _ ≤ (Finset.univ.biUnion (fun g => (S g).image (familyName g))).card+1 := Finset.card_insert_le _ _ + _ ≤ (∑ g : Fin k, ((S g).image (familyName g)).card)+1 := + Nat.add_le_add_right Finset.card_biUnion_le 1 + _ ≤ (∑ _g : Fin k, N)+1 := Nat.add_le_add_right (Finset.sum_le_sum (fun g _ => + (Finset.card_image_le (s := S g) (f := familyName g)).trans (hS g))) 1 + _ = 1+k*N := by simp [Nat.add_comm] + +noncomputable def familyAtom {X : Type*} {k : ℕ} (old : X → ℝ) + (A : Fin k → ℕ → X → ℝ) (i : ℕ) (x : X) : ℝ := + if i=0 then old x else if h : (Nat.unpair (i-1)).1 < k then + A ⟨(Nat.unpair (i-1)).1,h⟩ ((Nat.unpair (i-1)).2+1) x else old x + +lemma familyAtom_zero {X : Type*} {k : ℕ} (old : X → ℝ) + (A : Fin k → ℕ → X → ℝ) (x : X) : familyAtom old A 0 x = old x := by + simp [familyAtom] + +lemma familyAtom_name {X : Type*} {k : ℕ} (old : X → ℝ) + (A : Fin k → ℕ → X → ℝ) (g : Fin k) {i : ℕ} (hi : i ≠ 0) (x : X) : + familyAtom old A (familyName g i) x = A g i x := by + have hg := g.isLt + simp [familyAtom,familyName,hi,Nat.unpair_pair,hg,show i-1+1=i by omega] + +lemma familyAtom_lipschitz {X : Type*} [PseudoMetricSpace X] {k : ℕ} {K : ℝ≥0} + (old : X → ℝ) (A : Fin k → ℕ → X → ℝ) (ho : LipschitzWith K old) + (hA : ∀ g i, LipschitzWith K (A g i)) (i : ℕ) : + LipschitzWith K (familyAtom old A i) := by + unfold familyAtom + split_ifs with h h' + · exact ho + · exact hA _ _ + · exact ho + +/-- Comparisons in one group use the local fresh-offset estimate. Comparisons +between groups condition on all other samples and then use a constant test. -/ +lemma familyAtomPair_probability {X Ω : Type*} {k : ℕ} [Fintype Ω] [Nonempty Ω] + (old : X → ℝ) (A : Fin k → Ω → ℕ → X → ℝ) (S : Fin k → Finset ℕ) + (x : X) {t b : ℝ} + (hpair : ∀ g i, i ∈ S g → ∀ j, j ∈ S g → i ≠ j → + FiniteRandom.prob (fun ω => |A g ω i x-A g ω j x| ≤ t) ≤ b) + (hconst : ∀ g i, i ∈ S g → i ≠ 0 → ∀ c : ℝ, + FiniteRandom.prob (fun ω => |A g ω i x-c| ≤ t) ≤ b) + (i j : ℕ) (hi : i ∈ familyNames S) (hj : j ∈ familyNames S) (hne : i ≠ j) : + FiniteRandom.prob (fun ω : Fin k → Ω => + |familyAtom old (fun g => A g (ω g)) i x-familyAtom old (fun g => A g (ω g)) j x| ≤ t) ≤ b := by + classical + rcases mem_familyNames.mp hi with rfl | ⟨g,a,ha,rfl⟩ + · obtain ⟨h,c,hc,hcj⟩ := (mem_familyNames.mp hj).resolve_left (Ne.symm hne) + subst j + have hc0 : c ≠ 0 := by intro he; subst c; simp only [familyName_zero] at hne; exact hne rfl + simp only [familyAtom_zero,familyAtom_name old _ h hc0] + apply FiniteRandom.prob_update_bound h + intro ω + simpa only [Function.update_self,abs_sub_comm] using hconst h c hc hc0 (old x) + · rcases mem_familyNames.mp hj with rfl | ⟨h,c,hc,rfl⟩ + · have ha0 : a ≠ 0 := by intro he; subst a; simp only [familyName_zero] at hne; exact hne rfl + simp only [familyAtom_name old _ g ha0,familyAtom_zero] + apply FiniteRandom.prob_update_bound g + intro ω + simpa only [Function.update_self] using hconst g a ha ha0 (old x) + · by_cases ha0 : a=0 + · subst a + have hc0 : c ≠ 0 := by intro he; subst c; simp only [familyName_zero] at hne; exact hne rfl + simp only [familyName_zero,familyAtom_zero,familyAtom_name old _ h hc0] + apply FiniteRandom.prob_update_bound h + intro ω + simpa only [Function.update_self,abs_sub_comm] using hconst h c hc hc0 (old x) + · by_cases hc0 : c=0 + · subst c + simp only [familyName_zero,familyAtom_zero,familyAtom_name old _ g ha0] + apply FiniteRandom.prob_update_bound g + intro ω + simpa only [Function.update_self] using hconst g a ha ha0 (old x) + · simp only [familyAtom_name old _ g ha0,familyAtom_name old _ h hc0] + by_cases hgh : g=h + · subst h + have hac : a ≠ c := by intro he; subst c; exact hne rfl + apply FiniteRandom.prob_update_bound g + intro ω + simpa only [Function.update_self] using hpair g a ha c hc hac + · apply FiniteRandom.prob_update_bound g + intro ω + simpa only [Function.update_self,Function.update_of_ne (Ne.symm hgh)] using + hconst g a ha ha0 (A h (ω h) c x) + + +noncomputable def maxSelection {X : Type*} (old : X → NamedValue) : + List (X → NamedValue) → X → NamedValue + | [], x => old x + | F::Fs, x => maxNamed (F x) (maxSelection old Fs x) + +lemma maxSelection_mem {X : Type*} (old : X → NamedValue) + (Fs : List (X → NamedValue)) (x : X) : + maxSelection old Fs x = old x ∨ ∃ F ∈ Fs, maxSelection old Fs x = F x := by + induction Fs with + | nil => exact Or.inl rfl + | cons F Fs ih => + rcases maxNamed_mem (F x) (maxSelection old Fs x) with h | h + · exact Or.inr ⟨F,by simp,h⟩ + · change maxSelection old (F::Fs) x = _ at h + rcases ih with ih | ⟨G,hG,he⟩ + · exact Or.inl (h.trans ih) + · exact Or.inr ⟨G,List.mem_cons_of_mem _ hG,h.trans he⟩ + +lemma maxSelection_lipschitz {X : Type*} [PseudoMetricSpace X] {K : ℝ≥0} + (old : X → NamedValue) (Fs : List (X → NamedValue)) + (ho : LipschitzWith K (fun x => (old x).value)) + (hF : ∀ F ∈ Fs, LipschitzWith K (fun x => (F x).value)) : + LipschitzWith K (fun x => (maxSelection old Fs x).value) := by + induction Fs with + | nil => exact ho + | cons F Fs ih => + simp only [maxSelection,maxNamed_value] + simpa only [max_self] using (hF F (by simp)).max (ih (fun G hG => hF G (List.mem_cons_of_mem _ hG))) + +noncomputable def familySelection {X : Type*} {k : ℕ} (old : X → ℝ) + (F : Fin k → X → NamedValue) : X → NamedValue := + maxSelection (fun x => ⟨0,old x⟩) + (List.ofFn (fun g => fun x => ⟨familyName g (F g x).name,(F g x).value⟩)) + +lemma familySelection_list {X : Type*} {k : ℕ} (old : X → ℝ) + (F : Fin k → X → NamedValue) (A : Fin k → ℕ → X → ℝ) (S : Fin k → Finset ℕ) + (hzero : ∀ g x, A g 0 x = old x) (x : X) + (hlist : ∀ g, (F g x).name ∈ S g ∧ (F g x).value = A g (F g x).name x) : + (familySelection old F x).name ∈ familyNames S ∧ + (familySelection old F x).value = familyAtom old A (familySelection old F x).name x := by + rcases maxSelection_mem (fun x => ⟨0,old x⟩) + (List.ofFn (fun g => fun x => ⟨familyName g (F g x).name,(F g x).value⟩)) x with h | ⟨G,hG,h⟩ + · change familySelection old F x = _ at h + rw [h] + exact ⟨mem_familyNames.mpr (Or.inl rfl),(familyAtom_zero old A x).symm⟩ + · obtain ⟨g,rfl⟩ := List.mem_ofFn.mp hG + change familySelection old F x = _ at h + rw [h] + dsimp only + constructor + · exact mem_familyNames.mpr (Or.inr ⟨g,(F g x).name,(hlist g).1,rfl⟩) + · rw [(hlist g).2] + by_cases he : (F g x).name=0 + · rw [he,familyName_zero,familyAtom_zero,hzero] + · rw [familyAtom_name old A g he] + +lemma familySelection_lipschitz {X : Type*} [PseudoMetricSpace X] {k : ℕ} {K : ℝ≥0} + (old : X → ℝ) (F : Fin k → X → NamedValue) (ho : LipschitzWith K old) + (hF : ∀ g, LipschitzWith K (fun x => (F g x).value)) : + LipschitzWith K (fun x => (familySelection old F x).value) := by + apply maxSelection_lipschitz _ _ ho + intro G hG + obtain ⟨g,rfl⟩ := List.mem_ofFn.mp hG + exact hF g + +/-- The literal deterministic finite maximum has a single identifier throughout +one small ball except for the finite pair-comparison events. -/ +lemma familySelection_probability {X Ω : Type*} [PseudoMetricSpace X] + [Fintype Ω] [Nonempty Ω] {k N : ℕ} {K : ℝ≥0} + (old : X → ℝ) (F : Fin k → Ω → X → NamedValue) + (A : Fin k → Ω → ℕ → X → ℝ) (S : Fin k → Finset ℕ) + (ho : LipschitzWith K old) + (hF : ∀ g ω, LipschitzWith K (fun z => (F g ω z).value)) + (hA : ∀ g ω i, LipschitzWith K (A g ω i)) + (hzero : ∀ g ω z, A g ω 0 z=old z) (hcard : ∀ g, (S g).card ≤ N) + (x : X) {ρ b : ℝ} (hρ : 0 ≤ ρ) (hb : 0 ≤ b) + (hlist : ∀ g ω z, dist x z ≤ ρ → (F g ω z).name ∈ S g ∧ + (F g ω z).value = A g ω (F g ω z).name z) + (hpair : ∀ g i, i ∈ S g → ∀ j, j ∈ S g → i ≠ j → + FiniteRandom.prob (fun ω => |A g ω i x-A g ω j x| ≤ 2*K*ρ) ≤ b) + (hconst : ∀ g i, i ∈ S g → i ≠ 0 → ∀ c : ℝ, + FiniteRandom.prob (fun ω => |A g ω i x-c| ≤ 2*K*ρ) ≤ b) : + FiniteRandom.prob (fun ω : Fin k → Ω => ∃ z, dist x z ≤ ρ ∧ + (familySelection old (fun g => F g (ω g)) z).name ≠ + (familySelection old (fun g => F g (ω g)) x).name) ≤ (1+k*N : ℕ)^2*b := by + have hp := selection_probability + (fun ω : Fin k → Ω => familySelection old (fun g => F g (ω g))) + (fun ω => familyAtom old (fun g => A g (ω g))) (familyNames S) + (fun ω => familySelection_lipschitz old _ ho (fun g => hF g (ω g))) + (fun ω i _ => familyAtom_lipschitz old _ ho (fun g j => hA g (ω g) j) i) + x hρ hb (fun ω z hz => familySelection_list old _ _ S + (fun g y => hzero g (ω g) y) z (fun g => hlist g (ω g) z hz)) + (fun i hi j hj hij => familyAtomPair_probability old A S x hpair hconst i j hi hj hij) + refine hp.trans ?_ + apply mul_le_mul_of_nonneg_right _ hb + apply pow_le_pow_left₀ (Nat.cast_nonneg _) + exact_mod_cast familyNames_card S hcard + +end PlanarL1.Interpolation + + +end + +section + +namespace PlanarL1.Interpolation +open scoped NNReal + +lemma clippedNamed_eq_old_of_value {o p h : NamedValue} + (hname : o.name = 0) (he : (clippedNamed o p h).value = o.value) : + clippedNamed o p h = o := by + have hle : (minNamed p h).value ≤ o.value := by + rw [clippedNamed_value] at he + rw [minNamed_value] + exact max_eq_left_iff.mp he + apply ite_eq_left + rcases lt_or_eq_of_le hle with hh | hh + · exact Or.inl hh + · exact Or.inr ⟨hh.symm,by omega⟩ + +lemma namedClip_eq_old_iff {X : Type*} (F : X → NamedValue) (old shield : X → ℝ) + (x : X) : (namedClip F old shield x).name = 0 ↔ + (namedClip F old shield x).value = old x := by + constructor + · intro hn + rcases clippedNamed_mem ⟨0,old x⟩ ⟨(F x).name+2,(F x).value⟩ ⟨1,shield x⟩ with h | h | h + · exact congrArg NamedValue.value h + · change namedClip F old shield x = _ at h + rw [h] at hn + simp only at hn + omega + · change namedClip F old shield x = _ at h + rw [h] at hn + contradiction + · intro he + exact congrArg NamedValue.name (clippedNamed_eq_old_of_value rfl he) + +end PlanarL1.Interpolation + + + +end + +end OAI diff --git a/lean/OAI/Combinatorics/PlanarL1/Layout.lean b/lean/OAI/Combinatorics/PlanarL1/Layout.lean new file mode 100644 index 0000000000000000000000000000000000000000..a192c9f4c31ed3c62752088fc13d7dccf100d4af --- /dev/null +++ b/lean/OAI/Combinatorics/PlanarL1/Layout.lean @@ -0,0 +1,540 @@ +import OAI.Combinatorics.PlanarL1.Growth + +namespace OAI + +section + + + +namespace PlanarL1.HeightTree +open Set PlanarL1.Topology +attribute [local instance] Classical.propDecidable +variable {V : Type} [Fintype V] [LinearOrder V] (T : HeightTree V) + {G : SimpleGraph V} (P : PLDrawing G) + +lemma growth_exists (hG : T.graph ≤ G) (S : Finset V) + (hroot : T.root∈S) (hS : T.ParentClosed S) : Nonempty (T.Growth P S) := by + classical + induction S using Finset.strongInductionOn with + | _ S ih => + by_cases hs : S={T.root} + · subst S; exact T.initial_growth P hG + have hne : (S.erase T.root).Nonempty := by + by_contra hh + have hempty := Finset.not_nonempty_iff_eq_empty.mp hh + apply hs + exact (Finset.insert_erase hroot).symm.trans (by rw [hempty]; rfl) + obtain ⟨v,hv,hmax⟩ := Finset.exists_max_image (S.erase T.root) T.depth hne + have hvr : v≠T.root := (Finset.mem_erase.mp hv).1 + have hvS : v∈S := (Finset.mem_erase.mp hv).2 + have hroot' : T.root∈S.erase v := Finset.mem_erase.mpr ⟨hvr.symm,hroot⟩ + have hS' : T.ParentClosed (S.erase v) := by + intro w hw + have hwv := (Finset.mem_erase.mp hw).1 + have hwS := (Finset.mem_erase.mp hw).2 + refine Finset.mem_erase.mpr ⟨?_,hS w hwS⟩ + intro he + by_cases hwr : w=T.root + · subst w; exact hvr (he.symm.trans T.at_root) + · have hd := T.step_depth (show T.Step v w from ⟨hwr,he.symm⟩) + exact (not_lt_of_ge (hmax w (Finset.mem_erase.mpr ⟨hwr,hwS⟩))) hd + have hfront : T.Frontier (S.erase v) v := by + refine ⟨(by simp),Finset.mem_erase.mpr ⟨T.parent_ne hvr,hS v hvS⟩⟩ + obtain ⟨H⟩ := ih (S.erase v) (Finset.erase_ssubset hvS) hroot' hS' + simpa only [Finset.insert_erase hvS] using H.advance hS' hG hfront + +noncomputable def internal : Finset V := Finset.univ.filter (fun v => ¬T.IsLeaf v) + +omit [LinearOrder V] in +lemma mem_internal (v : V) : v∈T.internal ↔ ¬T.IsLeaf v := by simp [internal] + +lemma internal_closed : T.ParentClosed T.internal := by + intro v hv + by_cases he : v=T.root + · subst v; rwa [T.at_root] + · apply (T.mem_internal _).mpr + exact fun h => h v ⟨he,rfl⟩ + +omit [LinearOrder V] in +lemma internal_scope (hroot : ¬T.IsLeaf T.root) (v : V) : T.Scope T.internal v := by + by_cases h : T.IsLeaf v + · refine Or.inr ⟨fun hv => (T.mem_internal v).mp hv h,(T.mem_internal _).mpr ?_⟩ + have hvr : v≠T.root := fun he => hroot (he ▸ h) + exact fun hh => hh v ⟨hvr,rfl⟩ + · exact Or.inl ((T.mem_internal _).mpr h) + +omit [LinearOrder V] in +lemma internal_frontier (hroot : ¬T.IsLeaf T.root) (v : V) : + T.Frontier T.internal v ↔ T.IsLeaf v := by + constructor + · intro h + by_contra hh + exact h.1 ((T.mem_internal _).mpr hh) + · intro h + rcases T.internal_scope hroot v with hv|hv + · exact False.elim ((T.mem_internal _).mp hv h) + · exact hv + +/-- Every actual polygonally drawn finite tree can be enclosed in a convex disk, +with the leaf stubs left as disjoint exterior polygonal arcs. All untouched raw +leaf-to-leaf drawing pieces remain outside the closed disk. -/ +lemma tree_core (hG : T.graph ≤ G) (hroot : ¬T.IsLeaf T.root) : + ∃ C : DiskCore T.graph {v | T.IsLeaf v}, + ∃ E : ExteriorPorts C.drawing.point P.point {v | T.IsLeaf v} C.disk, + Disjoint (closure C.disk) (P.carrier {v | T.IsLeaf v}) ∧ + ∀ v, T.IsLeaf v → ∀ z∈E.region v, z∈P.carrier {v | T.IsLeaf v} → z=P.point v := by + classical + obtain ⟨H⟩ := T.growth_exists P hG T.internal ((T.mem_internal _).mpr hroot) T.internal_closed + let i : V → {v // T.Scope T.internal v} := fun v => ⟨v,T.internal_scope hroot v⟩ + have hi : Function.Injective i := fun _ _ h => congrArg Subtype.val h + have hgraph : ∀ u v, T.graph.Adj u v → + (SimpleGraph.comap Subtype.val T.graph).Adj (i u) (i v) := fun _ _ h => h + have hports : ∀ v, T.IsLeaf v → T.Frontier T.internal (i v).val := + fun v h => (T.internal_frontier hroot v).mpr h + obtain ⟨C,E,hD,hp,hE⟩ := H.core.pullback H.stems i hi hgraph hports + have hout : outside P T.internal=P.carrier {v | T.IsLeaf v} := by + unfold outside + congr 1 + ext v + simp only [mem_ofPred_eq,T.mem_internal,not_not] + refine ⟨C,E,?_,?_⟩ + · rw [hD,← hout]; exact H.avoid + · intro v hv z hz hzK + apply H.contact (i v) (hports v hv) z + · exact (hE v) ▸ hz + · rwa [hout] + +end PlanarL1.HeightTree + + + + +namespace PlanarL1.Topology +open Set + +lemma PolygonallyJoined.exists_path {S : Set ℂ} {x y : ℂ} + (h : PolygonallyJoined S x y) (hx : x∈S) : + ∃ p : Path x y, range p ⊆ S := by + induction h with + | refl => exact ⟨Path.refl x,by rintro z ⟨t,rfl⟩; exact hx⟩ + | @tail y z h hz ih => + obtain ⟨p,hp⟩ := ih + exact ⟨p.trans (Path.segment y z),by rw [Path.trans_range,Path.range_segment]; exact union_subset hp hz⟩ + +namespace DiskCore +variable {V : Type} [LinearOrder V] {G : SimpleGraph V} {B : Set V} (C : DiskCore G B) + +lemma carrier_subset (S : Set V) : C.drawing.carrier S ⊆ closure C.disk := by + intro z hz + rcases hz with hz|hz + · obtain ⟨v,hv⟩ := mem_iUnion.mp hz + exact mem_singleton_iff.mp hv ▸ C.point_mem v.val + · obtain ⟨u,hu⟩ := mem_iUnion.mp hz + obtain ⟨v,hv⟩ := mem_iUnion.mp hu + exact C.region_mem _ _ (C.drawing.region_adj hv) hv + +end DiskCore +end PlanarL1.Topology + +namespace PlanarL1.HeightTree +open Set PlanarL1.Topology Real +attribute [local instance] Classical.propDecidable +variable {V : Type} [LinearOrder V] (T : HeightTree V) + +lemma ancestor_plpath (P : PLDrawing T.graph) {u v : V} (h : T.Ancestor u v) + {S : Set V} (hS : ∀ w, T.Ancestor u w → T.Ancestor w v → w∈S) : + ∃ p : Path (P.point u) (P.point v), range p ⊆ P.carrier S := by + induction h with + | refl => exact ⟨Path.refl _,by rintro z ⟨t,rfl⟩; exact P.point_mem_carrier (hS _ .refl .refl)⟩ + | @tail v w huv hvw ih => + obtain ⟨p,hp⟩ := ih (fun a ha hb => hS a ha (hb.tail hvw)) + obtain ⟨q,hq⟩ := (P.region_joined v w (Or.inl hvw)).exists_path (P.region_start v w (Or.inl hvw)) + refine ⟨p.trans q,?_⟩ + rw [Path.trans_range] + exact union_subset hp (hq.trans (P.region_mem_carrier (hS v huv (.single hvw)) + (hS w (huv.tail hvw) .refl))) + +lemma descendants_pljoined (P : PLDrawing T.graph) (a : V) {u v : V} + (hu : T.Ancestor a u) (hv : T.Ancestor a v) : + ∃ p : Path (P.point u) (P.point v), range p ⊆ P.carrier {w | T.Ancestor a w} := by + obtain ⟨p,hp⟩ := T.ancestor_plpath P hu (fun _ h _ => h) + obtain ⟨q,hq⟩ := T.ancestor_plpath P hv (fun _ h _ => h) + exact ⟨p.symm.trans q,by rw [Path.trans_range,Path.symm_range]; exact union_subset hp hq⟩ + +lemma nondescendants_pljoined (P : PLDrawing T.graph) (a : V) {u v : V} + (hu : ¬T.Ancestor a u) (hv : ¬T.Ancestor a v) : + ∃ p : Path (P.point u) (P.point v), range p ⊆ P.carrier {w | ¬T.Ancestor a w} := by + obtain ⟨p,hp⟩ := T.ancestor_plpath P (T.root_ancestor u) + (S := {w | ¬T.Ancestor a w}) (fun _ _ h ha => hu (ha.trans h)) + obtain ⟨q,hq⟩ := T.ancestor_plpath P (T.root_ancestor v) + (S := {w | ¬T.Ancestor a w}) (fun _ _ h ha => hv (ha.trans h)) + exact ⟨p.symm.trans q,by rw [Path.trans_range,Path.symm_range]; exact union_subset hp hq⟩ + +lemma core_prefix_connected {B : Set V} {n : ℕ} (C : DiskCore T.graph B) + (h : ℂ ≃ₜ ℂ) (hbound : ∀ z∈closure C.disk, ‖h z‖≤1) + (leaf : Fin n → V) (angle : Fin n → ℝ) + (hend : ∀ i, h (C.drawing.point (leaf i))=(Circle.exp (angle i) : ℂ)) + (horder : StrictMono angle) (hspan : ∀ i j, angle j-angle i<2*π) + (a : V) {i j : Fin n} (hi : T.Ancestor a (leaf i)) (hj : T.Ancestor a (leaf j)) : + (T.prefixGraph leaf a).Reachable i j := by + apply Columns.consecutive_connected (T.prefixGraph leaf a) {k | T.Ancestor a (leaf k)} + (fun _ _ hne hc ha hb => ⟨hne,hc,ha,hb⟩) _ hi hj + intro w x y z hwx hxy hyz hbad + suffices impossible : ∀ (S U : Set V), Disjoint S U → + (∃ p : Path (C.drawing.point (leaf w)) (C.drawing.point (leaf y)), range p⊆C.drawing.carrier S) → + (∃ q : Path (C.drawing.point (leaf x)) (C.drawing.point (leaf z)), range q⊆C.drawing.carrier U) → False by + rcases hbad with ⟨hw,hx,hy,hz⟩ | ⟨hw,hx,hy,hz⟩ + · exact impossible {v | T.Ancestor a v} {v | ¬T.Ancestor a v} + disjoint_compl_right (T.descendants_pljoined C.drawing a hw hy) + (T.nondescendants_pljoined C.drawing a hx hz) + · exact impossible {v | ¬T.Ancestor a v} {v | T.Ancestor a v} + disjoint_compl_left (T.nondescendants_pljoined C.drawing a hw hy) + (T.descendants_pljoined C.drawing a hx hz) + intro S U hdis ⟨p,hp⟩ ⟨q,hq⟩ + let p' := (p.map h.continuous).cast (hend w).symm (hend y).symm + let q' := (q.map h.continuous).cast (hend x).symm (hend z).symm + obtain ⟨s,t,hst⟩ := Topology.disk_cyclic_arcs_meet (angle w) (angle x) (angle y) (angle z) + (horder hwx) (horder hxy) (horder hyz) (by linarith [hspan w z]) p' q' + (fun t => hbound _ (C.carrier_subset S (hp (mem_range_self t)))) + (fun t => hbound _ (C.carrier_subset U (hq (mem_range_self t)))) + have he : p s=q t := h.injective hst + exact disjoint_left.mp (C.drawing.carrier_disjoint hdis) (hp (mem_range_self s)) + (he ▸ hq (mem_range_self t)) + +lemma layout_of_core [Fintype V] (C : DiskCore T.graph {v | T.IsLeaf v}) + (P : SimpleGraph {v : V // T.IsLeaf v}) + (hheight : ∀ i j, P.Adj i j → T.height i.val=T.height j.val) + (hmatch : ∀ i j k, P.Adj i j → P.Adj i k → j=k) + (arc : ∀ i j, P.Adj i j → Path (C.drawing.point i.val) (C.drawing.point j.val)) + (hout : ∀ i j h t, arc i j h t∉C.disk) + (hdis : ∀ i j h k l h', i≠k → i≠l → j≠k → j≠l → + Disjoint (range (arc i j h)) (range (arc k l h'))) : + ∃ (L : T.Layout (Fintype.card {v : V // T.IsLeaf v})), + ∀ i j, L.pair.Adj i j ↔ P.Adj ⟨L.leaf i,L.isLeaf i⟩ ⟨L.leaf j,L.isLeaf j⟩ := by + classical + obtain ⟨h,hi,hcl,hfr⟩ := exists_homeomorph_image_interior_closure_frontier_eq_unitBall C.convex + (show (interior C.disk).Nonempty by rw [C.isOpen.interior_eq]; exact ⟨C.center,C.center_mem⟩) C.bounded + have hnorm (v : {v : V // T.IsLeaf v}) : ‖h (C.drawing.point v.val)‖=1 := by + have hm := mem_image_of_mem h (C.port v.val v.property) + rw [hfr] at hm + simpa only [Metric.mem_sphere,dist_zero_right] using hm + have hbound (z : ℂ) (hz : z∈closure C.disk) : ‖h z‖≤1 := by + have hm := mem_image_of_mem h hz + rw [hcl] at hm + simpa only [Metric.mem_closedBall,dist_zero_right] using hm + have hexterior (z : ℂ) (hz : z∉C.disk) : 1≤‖h z‖ := by + by_contra! hn + have hm : h z∈Metric.ball (0:ℂ) 1 := by simpa only [Metric.mem_ball,dist_zero_right] using hn + rw [← hi] at hm + obtain ⟨w,hw,he⟩ := hm + exact hz (h.injective he ▸ interior_subset hw) + obtain ⟨e,he,hspan⟩ := Topology.finite_port_order (fun v : {v : V // T.IsLeaf v} => h (C.drawing.point v.val)) + hnorm (h.injective.comp (C.drawing.point_injective.comp Subtype.val_injective)) + let angle (i : Fin (Fintype.card {v : V // T.IsLeaf v})) := Complex.arg (h (C.drawing.point (e i).val)) + have hend i : h (C.drawing.point (e i).val)=(Circle.exp (angle i) : ℂ) := + (Topology.circle_exp_arg (hnorm (e i))).symm + let A : ∀ i j, (SimpleGraph.comap e P).Adj i j → + Path (Circle.exp (angle i) : ℂ) (Circle.exp (angle j) : ℂ) := + fun i j hij => ((arc (e i) (e j) hij).map h.continuous).cast (hend i).symm (hend j).symm + have hnc : ColumnOrder.Noncrossing (SimpleGraph.comap e P) := by + apply Topology.noncrossing_of_exterior_arcs _ angle he hspan A + · intro i j hij t; exact hexterior _ (hout (e i) (e j) hij t) + · intro i j hij k l hkl hik hil hjk hjl + rw [disjoint_left] + rintro z ⟨s,hs⟩ ⟨t,ht⟩ + have hh : h (arc (e i) (e j) hij s)=h (arc (e k) (e l) hkl t) := hs.trans ht.symm + exact disjoint_left.mp (hdis (e i) (e j) hij (e k) (e l) hkl + (e.injective.ne hik) (e.injective.ne hil) (e.injective.ne hjk) (e.injective.ne hjl)) + (mem_range_self s) (h.injective hh ▸ mem_range_self t) + let L : T.Layout (Fintype.card {v : V // T.IsLeaf v}) := { + leaf := fun i => (e i).val + isLeaf := fun i => (e i).property + injective := Subtype.val_injective.comp e.injective + covers := fun v hv => ⟨e.symm ⟨v,hv⟩,by simp⟩ + prefix_connected := fun a i j hi hj => + T.core_prefix_connected C h hbound _ angle hend he hspan a hi hj + pair := SimpleGraph.comap e P + noncrossing := hnc + paired_height := fun i j hij => hheight (e i) (e j) hij + matching := fun i j k hij hik => e.injective (hmatch (e i) (e j) (e k) hij hik) } + exact ⟨L,fun _ _ => Iff.rfl⟩ + +end PlanarL1.HeightTree + + + + +namespace PlanarL1.Topology +open Set +variable {V : Type} [LinearOrder V] {G : SimpleGraph V} (P : PLDrawing G) + {p : V → ℂ} {B : Set V} {D : Set ℂ} (E : ExteriorPorts p P.point B D) + +/-- The untouched raw carrier together with the actual exterior stubs. -/ +def stemCarrier (S : Set V) : Set ℂ := P.carrier S ∪ ⋃ v : S, E.region v.val + +lemma stemCarrier_disjoint + (hcontact : ∀ v∈B, ∀ z∈E.region v, z∈P.carrier B → z=P.point v) + {S U : Set V} (hS : S⊆B) (hU : U⊆B) (hSU : Disjoint S U) : + Disjoint (stemCarrier P E S) (stemCarrier P E U) := by + have cross {S U : Set V} (hS : S⊆B) (hU : U⊆B) (hSU : Disjoint S U) : + Disjoint (P.carrier S) (⋃ v : U, E.region v.val) := by + rw [disjoint_left] + intro z hz hz' + obtain ⟨v,hv⟩ := mem_iUnion.mp hz' + have he := hcontact v.val (hU v.property) z hv (P.carrier_mono hS hz) + exact disjoint_left.mp hSU (P.point_carrier_iff.mp (he ▸ hz)) v.property + apply Disjoint.union_left + · exact Disjoint.union_right (P.carrier_disjoint hSU) (cross hS hU hSU) + · apply Disjoint.union_right (cross hU hS hSU.symm).symm + rw [disjoint_left] + intro z hz hz' + obtain ⟨v,hv⟩ := mem_iUnion.mp hz + obtain ⟨w,hw⟩ := mem_iUnion.mp hz' + exact disjoint_left.mp (E.disjoint v.val (hS v.property) w.val (hU w.property) + (fun he => disjoint_left.mp hSU v.property (he ▸ w.property))) hv hw + +end PlanarL1.Topology + +namespace PlanarL1.HeightTree +open Set PlanarL1.Topology +attribute [local instance] Classical.propDecidable +variable {V : Type} [Fintype V] [LinearOrder V] (T : HeightTree V) + {G : SimpleGraph V} (P : PLDrawing G) + +/-- The literal planar leaf layout is constructed from a real raw drawing of +its tree and terminal matching. Neither a contour order nor a disk is assumed. -/ +lemma layout_of_drawing (P : PLDrawing G) (hG : T.graph ≤ G) (hroot : ¬T.IsLeaf T.root) + (M : SimpleGraph {v : V // T.IsLeaf v}) + (hMG : ∀ i j, M.Adj i j → G.Adj i.val j.val) + (hheight : ∀ i j, M.Adj i j → T.height i.val=T.height j.val) + (hmatch : ∀ i j k, M.Adj i j → M.Adj i k → j=k) : + ∃ (L : T.Layout (Fintype.card {v : V // T.IsLeaf v})), + ∀ i j, L.pair.Adj i j ↔ M.Adj ⟨L.leaf i,L.isLeaf i⟩ ⟨L.leaf j,L.isLeaf j⟩ := by + classical + obtain ⟨C,E,havoid,hcontact⟩ := T.tree_core P hG hroot + choose s hs using fun v : {v // T.IsLeaf v} => + (E.joined v.val v.property).exists_path (E.start v.val v.property) + choose r hr using fun i j (h : M.Adj i j) => + (P.region_joined i.val j.val (hMG i j h)).exists_path (P.region_start i.val j.val (hMG i j h)) + let A : ∀ i j, M.Adj i j → Path (C.drawing.point i.val) (C.drawing.point j.val) := + fun i j h => ((s i).trans (r i j h)).trans (s j).symm + have hS (i j : {v // T.IsLeaf v}) : ({i.val,j.val} : Set V) ⊆ {v | T.IsLeaf v} := by + intro v hv + rcases hv with rfl|hv + · exact i.property + · rw [mem_singleton_iff] at hv; exact hv ▸ j.property + have hArange (i j : {v // T.IsLeaf v}) (h : M.Adj i j) : + range (A i j h) ⊆ stemCarrier P E {i.val,j.val} := by + change range (((s i).trans (r i j h)).trans (s j).symm) ⊆ _ + rw [Path.trans_range,Path.trans_range,Path.symm_range] + refine union_subset (union_subset ?_ ?_) ?_ + · intro z hz; exact Or.inr (mem_iUnion.mpr ⟨⟨i.val,by simp⟩,hs i hz⟩) + · intro z hz; exact Or.inl (P.region_mem_carrier (by simp) (by simp) (hr i j h hz)) + · intro z hz; exact Or.inr (mem_iUnion.mpr ⟨⟨j.val,by simp⟩,hs j hz⟩) + have houtside (S : Set V) (hS : S⊆{v | T.IsLeaf v}) (z : ℂ) + (hz : z∈stemCarrier P E S) : z∉C.disk := by + intro hzD + rcases hz with hz|hz + · exact disjoint_left.mp havoid (subset_closure hzD) (P.carrier_mono hS hz) + · obtain ⟨v,hv⟩ := mem_iUnion.mp hz + have he := E.inside v.val (hS v.property) z hv (subset_closure hzD) + have hf := C.port v.val (hS v.property) + have hn : C.drawing.point v.val∉interior C.disk := hf.2 + exact hn (by rw [C.isOpen.interior_eq]; exact he ▸ hzD) + apply T.layout_of_core C M hheight hmatch A + · intro i j h t; exact houtside _ (hS i j) _ (hArange i j h (mem_range_self t)) + · intro i j h k l h' hik hil hjk hjl + have hSU : Disjoint ({i.val,j.val} : Set V) {k.val,l.val} := by + simp only [disjoint_left,mem_insert_iff,mem_singleton_iff] + intro v hv hv' + rcases hv with rfl|rfl <;> rcases hv' with he|he + · exact hik (Subtype.ext he) + · exact hil (Subtype.ext he) + · exact hjk (Subtype.ext he) + · exact hjl (Subtype.ext he) + exact (stemCarrier_disjoint P E hcontact (hS i j) (hS k l) hSU).mono + (hArange i j h) (hArange k l h') + +end PlanarL1.HeightTree + + + + +namespace PlanarL1.Topology.Drawing +open Set +variable {V : Type} [LinearOrder V] {G : SimpleGraph V} (D : Drawing G) + +lemma forward_interior_meet (d e : ForwardDart G) {s t : unitInterval} + (hs : 0<(s:ℝ)) (hs' : (s:ℝ)<1) (ht : 0<(t:ℝ)) (ht' : (t:ℝ)<1) + (he : D.edge d.val.fst d.val.snd d.val.adj s=D.edge e.val.fst e.val.snd e.val.adj t) : + d=e ∧ s=t := by + have hd := ForwardDart.eq_of_endpoints d e (D.interior_disjoint _ _ _ _ _ _ s t hs hs' ht ht' he) + subst e + exact ⟨rfl,D.edge_injective _ _ _ he⟩ + +namespace Split +attribute [local instance] Classical.propDecidable +variable (S : Set (ForwardDart G)) + +abbrev Tip := S × Fin 2 +abbrev Node := V ⊕ Tip S +abbrev Piece := {d : ForwardDart G // d∉S} ⊕ (S × Fin 3) + +noncomputable def tipTime (k : Fin 2) : unitInterval := ⟨((k.val:ℝ)+1)/3,by + constructor + · positivity + · have hk : (k.val:ℝ)<2 := by exact_mod_cast k.isLt + linarith⟩ + +lemma tipTime_pos (k : Fin 2) : 0<(tipTime k:ℝ) := by dsimp [tipTime]; positivity +lemma tipTime_lt_one (k : Fin 2) : (tipTime k:ℝ)<1 := by + have hk : (k.val:ℝ)<2 := by exact_mod_cast k.isLt + dsimp [tipTime]; linarith + +noncomputable def point : Node S → ℂ + | .inl v => D.point v + | .inr (d,k) => D.edge d.val.val.fst d.val.val.snd d.val.val.adj (tipTime k) + +lemma point_injective : Function.Injective (point D S) := by + intro a b he + cases a with + | inl a => cases b with + | inl b => exact congrArg Sum.inl (D.point_injective he) + | inr b => exact False.elim (D.interior_avoid _ _ _ _ a (tipTime_pos b.2) (tipTime_lt_one b.2) he.symm) + | inr a => cases b with + | inl b => exact False.elim (D.interior_avoid _ _ _ _ b (tipTime_pos a.2) (tipTime_lt_one a.2) he) + | inr b => + obtain ⟨hd,ht⟩ := D.forward_interior_meet a.1.val b.1.val + (tipTime_pos a.2) (tipTime_lt_one a.2) (tipTime_pos b.2) (tipTime_lt_one b.2) he + have hk : a.2=b.2 := by + apply Fin.ext + have hh := congrArg Subtype.val ht + change ((a.2.val:ℝ)+1)/3=((b.2.val:ℝ)+1)/3 at hh + exact_mod_cast (show (a.2.val:ℝ)=(b.2.val:ℝ) by linarith) + exact congrArg Sum.inr (Prod.ext (Subtype.ext hd) hk) + +def meshNode (d : S) (r : Fin 4) : Node S := + if h0 : r.val=0 then .inl d.val.val.fst + else if h3 : r.val=3 then .inl d.val.val.snd + else .inr (d,⟨r.val-1,by omega⟩) + +noncomputable def meshTime (r : Fin 4) : unitInterval := ⟨(r.val:ℝ)/3,by + constructor + · positivity + · have hr : (r.val:ℝ)<4 := by exact_mod_cast r.isLt + have hr' : r.val≤3 := by omega + have hr'' : (r.val:ℝ)≤3 := by exact_mod_cast hr' + linarith⟩ + +lemma mesh_point (d : S) (r : Fin 4) : + point D S (meshNode S d r)=D.edge d.val.val.fst d.val.val.snd d.val.val.adj (meshTime r) := by + fin_cases r <;> norm_num [meshNode,point,meshTime,tipTime] + +noncomputable def label : Piece S → ForwardDart G + | .inl d => d.val + | .inr (d,_) => d.val + +def src : Piece S → Node S + | .inl d => .inl d.val.val.fst + | .inr (d,k) => meshNode S d k.castSucc + +def dst : Piece S → Node S + | .inl d => .inl d.val.val.snd + | .inr (d,k) => meshNode S d k.succ + +noncomputable def first : Piece S → unitInterval + | .inl _ => 0 + | .inr (_,k) => meshTime k.castSucc + +noncomputable def last : Piece S → unitInterval + | .inl _ => 1 + | .inr (_,k) => meshTime k.succ + +lemma first_lt_last (p : Piece S) : (first S p:ℝ)<(last S p:ℝ) := by + cases p with + | inl p => exact zero_lt_one + | inr p => dsimp [first,last,meshTime]; push_cast; linarith + +lemma src_point (p : Piece S) : + point D S (src S p)=D.edge (label S p).val.fst (label S p).val.snd (label S p).val.adj (first S p) := by + cases p with + | inl p => exact (Path.source _).symm + | inr p => exact mesh_point D S p.1 p.2.castSucc + +lemma dst_point (p : Piece S) : + point D S (dst S p)=D.edge (label S p).val.fst (label S p).val.snd (label S p).val.adj (last S p) := by + cases p with + | inl p => exact (Path.target _).symm + | inr p => exact mesh_point D S p.1 p.2.succ + +lemma src_ne_dst (D : Drawing G) (p : Piece S) : src S p≠dst S p := by + intro he + have hp := congrArg (point D S) he + rw [src_point,dst_point] at hp + have ht := congrArg Subtype.val (D.edge_injective _ _ _ hp) + exact (ne_of_lt (first_lt_last S p)) ht + +lemma interior_point_avoid (p : Piece S) {t : unitInterval} + (ht₀ : (first S p:ℝ)<(t:ℝ)) (ht₁ : (t:ℝ)<(last S p:ℝ)) (v : Node S) : + D.edge (label S p).val.fst (label S p).val.snd (label S p).val.adj t≠point D S v := by + have ht : 0<(t:ℝ) := lt_of_le_of_lt (first S p).property.1 ht₀ + have ht' : (t:ℝ)<1 := lt_of_lt_of_le ht₁ (last S p).property.2 + intro he + cases v with + | inl v => exact D.interior_avoid _ _ _ t v ht ht' he + | inr v => + obtain ⟨hd,htt⟩ := D.forward_interior_meet (label S p) v.1.val ht ht' + (tipTime_pos v.2) (tipTime_lt_one v.2) he + cases p with + | inl p => + change p.val=v.1.val at hd + exact p.property (hd.symm ▸ v.1.property) + | inr p => + rw [htt] at ht₀ ht₁ + change (p.2.val:ℝ)/3 < ((v.2.val:ℝ)+1)/3 at ht₀ + change ((v.2.val:ℝ)+1)/3 < ((p.2.val+1:ℕ):ℝ)/3 at ht₁ + have hlo : p.2.val cases q with + | inl q => exact congrArg Sum.inl (Subtype.ext hd) + | inr q => + change p.val=q.1.val at hd + exact False.elim (p.property (hd.symm ▸ q.1.property)) + | inr p => cases q with + | inl q => + change p.1.val=q.val at hd + exact False.elim (q.property (hd ▸ p.1.property)) + | inr q => + have hk : p.2=q.2 := by + apply Fin.ext + change (p.2.val:ℝ)/3 < (s:ℝ) at hs₀ + change (s:ℝ)<((p.2.val+1:ℕ):ℝ)/3 at hs₁ + change (q.2.val:ℝ)/3 < (s:ℝ) at ht₀ + change (s:ℝ)<((q.2.val+1:ℕ):ℝ)/3 at ht₁ + push_cast at hs₁ ht₁ + have hpq : p.2.val familyName a.1 (a.2.val+1)) := by + intro a b hab + obtain ⟨ha,hb⟩ := (familyName_inj a.1 b.1 (by omega) (by omega)).mp hab + rcases a with ⟨a,i⟩ + rcases b with ⟨b,j⟩ + dsimp only at ha hb + subst b + have he : i=j := Fin.ext (by omega) + subst j + rfl +lemma chosen_iff_name (i : Fin (k+1)) (H : B.data.band) (a : B.NewIndex) : + B.chosen i H.val a ↔ (B.selected i H).name=familyName a.1 (a.2.val+1) := by + constructor + · exact B.chosen_name i H a + · intro he + have hn : (B.selected i H).name≠0 := by rw [he]; exact familyName_ne_zero _ (by omega) + obtain ⟨b,hb⟩ := B.exists_chosen i H hn + have he' : b=a := B.newIndex_names_injective ((B.chosen_name i H b hb).symm.trans he) + exact he' ▸ hb +lemma choose_eq_of_name {i j : Fin (k+1)} (H T : B.data.band) + (hn : (B.selected i H).name=(B.selected j T).name) : + B.choose i H.val=B.choose j T.val := by + have he : B.chosen i H.val=B.chosen j T.val := by + funext a + exact propext ((B.chosen_iff_name i H a).trans (hn ▸ (B.chosen_iff_name j T a).symm)) + unfold choose + simp only [he] +lemma choose_none_of_old_name {i : Fin (k+1)} {H : ℝ} (hne : S.name i H≠B.index) : + B.choose i H=none := by + have hn : ¬∃ a, B.chosen i H a := by + rintro ⟨a,ha⟩ + exact hne (B.domain_name (B.mem_domain.mpr ⟨a.1,B.chosen_domain i H a ha⟩)) + exact dite_eq_right hn +end SecondaryBatch +namespace SecondaryLayer +variable (B : SecondaryLayer S) +lemma choose_eq {i j : Fin (k+1)} {H T : ℝ} + (he : ∀ a, (B.batch a).choose i H=(B.batch a).choose j T) : + B.choose i H=B.choose j T := by + have h : B.chosen i H=B.chosen j T := by + funext a + simp only [chosen,he a.1] + unfold choose + simp only [h] +lemma name_eq [SFinite μ] {i j : Fin (k+1)} {H T : ℝ} + (hold : S.name i H=S.name j T) (he : B.choose i H=B.choose j T) : + B.apply.name i H=B.apply.name j T := by + dsimp only [apply,BState.append,BState.lift] + rw [he,hold] +lemma name_eq_of_selected [SFinite μ] {i j : Fin (k+1)} {H T : ℝ} + (a : Fin (S.count+1)) (hH : H ∈ (B.batch a).data.band) (hT : T ∈ (B.batch a).data.band) + (hi : S.name i H=a) (hj : S.name j T=a) + (hn : ((B.batch a).selected i ⟨H,hH⟩).name=((B.batch a).selected j ⟨T,hT⟩).name) : + B.apply.name i H=B.apply.name j T := by + apply B.name_eq (hi.trans hj.symm) + apply B.choose_eq + intro b + by_cases hb : b=a + · subst b + exact (B.batch a).choose_eq_of_name _ _ hn + · rw [(B.batch b).choose_none_of_old_name (by simpa only [hi,B.same_index] using Ne.symm hb), + (B.batch b).choose_none_of_old_name (by simpa only [hj,B.same_index] using Ne.symm hb)] +end SecondaryLayer +end PlanarL1.Columns.Model.BState + +end + + + +section + +namespace PlanarL1.Columns.Model.RetainedSelection +open Parameters +variable {k : ℕ} {M : Model (k+1)} {q p L U : ℝ} +namespace Block +variable (b : Block (M := M) q p L U) +/-- At a doubly height-interior point, a narrow-band path can reach a seed +only in this very processed broad/component/narrow block. -/ +lemma eq_of_path_small (d : Block (M := M) q p L U) + (c : M.Point (BandTrees.band broad b.lower) (BandTrees.root M broad b.lower b.1.2)) + (e : M.Point (BandTrees.band broad d.lower) (BandTrees.root M broad d.lower d.1.2)) + (hc : c.height ∈ BandTrees.band narrow b.lower₂) + (hd : c.height ∈ BandTrees.band narrow d.lower₂) + {ρ τ : ℝ} (hρ : 0≤ρ) (hτ : 0≤τ) + (hp : Tiling.Padded a₁ q c.height ρ) + (hn : Tiling.Padded a₂ p c.height τ) + (path : M.Path (BandTrees.band narrow d.lower₂) c.column e.column) : b=d := by + have hNb : b.2.val.val=Tiling.index a₂ p c.height := + Tiling.unique_band_of_padded interpolationB.2.1 hτ hn (b.narrow_eq ▸ hc) + have hNd : d.2.val.val=Tiling.index a₂ p c.height := + Tiling.unique_band_of_padded interpolationB.2.1 hτ hn (d.narrow_eq ▸ hd) + have hBb : b.1.1.val=Tiling.index a₁ q c.height := + Tiling.unique_band_of_padded interpolationA.2.1 hρ hp (b.broad_eq ▸ c.inBand) + have hBd : d.1.1.val=Tiling.index a₁ q c.height := + Tiling.unique_band_of_padded interpolationA.2.1 hρ hp (d.broad_eq ▸ d.sub hd) + have hB : b.1.1=d.1.1 := Subtype.ext (hBb.trans hBd.symm) + rcases b with ⟨⟨bi,bC⟩,bn⟩ + rcases d with ⟨⟨di,dC⟩,dn⟩ + dsimp only at hB + subst di + have hC : bC=dC := by + have hr := c.reachable.trans ((path.widen (Block.sub ⟨⟨bi,dC⟩,dn⟩)).word.reachable.trans e.reachable.symm) + have hm := SimpleGraph.ConnectedComponent.sound hr + have hb : (M.activeGraph (BandTrees.band broad (MainFamily.lower q L U bi))).connectedComponentMk + (BandTrees.root M broad (MainFamily.lower q L U bi) bC)=bC := BandTrees.root_mem _ _ _ _ + have hd' : (M.activeGraph (BandTrees.band broad (MainFamily.lower q L U bi))).connectedComponentMk + (BandTrees.root M broad (MainFamily.lower q L U bi) dC)=dC := BandTrees.root_mem _ _ _ _ + exact hb.symm.trans (hm.trans hd') + subst dC + have hN : bn=dn := Subtype.ext (Subtype.ext (hNb.trans hNd.symm)) + subst dn + rfl +end Block +end PlanarL1.Columns.Model.RetainedSelection + +namespace PlanarL1.Columns.Model.RetainedSelection +open Parameters MeasureTheory +attribute [local instance] Classical.propDecidable +variable {k : ℕ} {M : Model (k+1)} {V Ω Ξ : Type*} +variable [Fintype V] [MeasurableSpace Ω] [MeasurableSpace Ξ] +variable {μ : Measure Ω} {ν : Measure Ξ} +variable (A : Ambient M) (SA : OrdinaryState M kappaA Ω μ) +variable (SB : BState M kappaB SecondaryGeometry.Group.lam Ξ ν) +variable (v : V → M.Point Set.univ A.root) +variable {L U : ℝ} (hv : ∀ x, (v x).height ∈ Set.Icc L U) +variable {q p : ℝ} {phaseD phaseG : MainFamily.BandComponent (M := M) q L U → ℝ} +variable (b : Block (M := M) q p L U) +variable (c : M.Point (BandTrees.band broad b.lower) (BandTrees.root M broad b.lower b.1.2)) + +variable (hc : c.height ∈ BandTrees.band narrow b.lower₂) +variable {ρ τ : ℝ} (hρ : 0≤ρ) (hτ : 0≤τ) +variable (hp : Tiling.Padded a₁ q c.height ρ) (hn : Tiling.Padded a₂ p c.height τ) +include hc hρ hτ hp hn + +lemma touch_block_small {i : GroupIndex A SA SB v hv (p := p) (phaseD := phaseD) (phaseG := phaseG)} + (h : Touch A SA SB v hv b c i) : i.1=b := by + obtain ⟨w,_,path,_⟩ := h.2 + exact (b.eq_of_path_small i.1 c (localSeeds A SA SB v hv (phaseD := phaseD) (phaseG := phaseG) i.1 w).point hc h.1 hρ hτ hp hn path).symm + +noncomputable def localHit_small (i : Hits A SA SB v hv b c (phaseD := phaseD) (phaseG := phaseG)) : + SurvivingGroups.Hits (localSeeds A SA SB v hv (phaseD := phaseD) (phaseG := phaseG) b) c := by + have he := touch_block_small A SA SB v hv b c hc hρ hτ hp hn i.property + rcases i with ⟨⟨d,j⟩,hi⟩ + dsimp only at he + subst d + exact ⟨j,hi.2⟩ + +lemma localHit_injective_small : Function.Injective + (localHit_small A SA SB v hv b c hc hρ hτ hp hn (phaseD := phaseD) (phaseG := phaseG)) := by + intro i j he + have hi := touch_block_small A SA SB v hv b c hc hρ hτ hp hn i.property + have hj := touch_block_small A SA SB v hv b c hc hρ hτ hp hn j.property + rcases i with ⟨⟨d,i⟩,hi'⟩ + rcases j with ⟨⟨e,j⟩,hj'⟩ + dsimp only at hi hj + subst d + subst e + have hraw : i=j := congrArg Subtype.val he + subst j + rfl + +/-- Universal packing for the whole actual, finitely selected family. Both +old identifiers are derived by the local packing theorem, not assumed. -/ +lemma touching_card_small : Fintype.card (Hits A SA SB v hv b c (phaseD := phaseD) (phaseG := phaseG))≤ + SurvivingGroups.packBound := by + let := SurvivingGroups.instFintypeHits + (localSeeds A SA SB v hv (phaseD := phaseD) (phaseG := phaseG) b) c + have hb := SurvivingGroups.touching_card + (localSeeds A SA SB v hv (phaseD := phaseD) (phaseG := phaseG) b) b.sub c hc + apply le_trans _ hb + exact Fintype.card_le_of_injective _ (localHit_injective_small A SA SB v hv b c hc hρ hτ hp hn) + +lemma touching_finset_card_small : + (Finset.univ.filter (Touch A SA SB v hv b c (phaseD := phaseD) (phaseG := phaseG))).card≤ + SurvivingGroups.packBound := by + simpa only [Hits,Fintype.card_subtype] using touching_card_small A SA SB v hv b c hc hρ hτ hp hn + +end PlanarL1.Columns.Model.RetainedSelection + +end + + + +section + +namespace PlanarL1.FiniteRandom +attribute [local irreducible] prob +lemma prob_update_bound_pi {I : Type*} {D : I → Type*} [Fintype I] [DecidableEq I] + [∀ i, Fintype (D i)] [∀ i, Nonempty (D i)] (i : I) (P : (∀ i, D i) → Prop) {b : ℝ} + (h : ∀ α, prob (fun r : D i => P (Function.update α i r)) ≤ b) : prob P≤b := by + classical + let e := (Equiv.piSplitAt i D).trans (Equiv.prodComm _ _) + rw [←prob_equiv e.symm P] + apply prob_prod_bound + intro rest + let α : ∀ i, D i := e.symm (rest, Classical.arbitrary (D i)) + have hu (r : D i) : e.symm (rest,r)=Function.update α i r := by + funext j + by_cases hj : j=i + · subst j; simp [e,α,Equiv.piSplitAt] + · simp [e,α,Equiv.piSplitAt,hj] + simpa only [hu] using h α +end PlanarL1.FiniteRandom + +namespace PlanarL1.Interpolation +attribute [local irreducible] FiniteRandom.prob +lemma familyAtomPair_probability_pi {X I : Type*} {D : I → Type*} {k : ℕ} + [Fintype I] [DecidableEq I] [∀ i, Fintype (D i)] [∀ i, Nonempty (D i)] + (ι : Fin k → I) (hinj : Function.Injective ι) + (old : X → ℝ) (A : ∀ g : Fin k, D (ι g) → ℕ → X → ℝ) (S : Fin k → Finset ℕ) + (x : X) {t b : ℝ} + (hpair : ∀ g i, i ∈ S g → ∀ j, j ∈ S g → i ≠ j → + FiniteRandom.prob (fun ω => |A g ω i x-A g ω j x| ≤ t) ≤ b) + (hconst : ∀ g i, i ∈ S g → i ≠ 0 → ∀ c : ℝ, + FiniteRandom.prob (fun ω => |A g ω i x-c| ≤ t) ≤ b) + (i j : ℕ) (hi : i ∈ familyNames S) (hj : j ∈ familyNames S) (hne : i ≠ j) : + FiniteRandom.prob (fun ω : ∀ i, D i => + |familyAtom old (fun g => A g (ω (ι g))) i x-familyAtom old (fun g => A g (ω (ι g))) j x| ≤ t) ≤ b := by + classical + rcases mem_familyNames.mp hi with rfl | ⟨g,a,ha,rfl⟩ + · obtain ⟨h,c,hc,hcj⟩ := (mem_familyNames.mp hj).resolve_left (Ne.symm hne) + subst j + have hc0 : c ≠ 0 := by intro he; subst c; simp only [familyName_zero] at hne; exact hne rfl + simp only [familyAtom_zero,familyAtom_name old _ h hc0] + apply FiniteRandom.prob_update_bound_pi (ι h) + intro ω + simpa only [Function.update_self,abs_sub_comm] using hconst h c hc hc0 (old x) + · rcases mem_familyNames.mp hj with rfl | ⟨h,c,hc,rfl⟩ + · have ha0 : a ≠ 0 := by intro he; subst a; simp only [familyName_zero] at hne; exact hne rfl + simp only [familyAtom_name old _ g ha0,familyAtom_zero] + apply FiniteRandom.prob_update_bound_pi (ι g) + intro ω + simpa only [Function.update_self] using hconst g a ha ha0 (old x) + · by_cases ha0 : a=0 + · subst a + have hc0 : c ≠ 0 := by intro he; subst c; simp only [familyName_zero] at hne; exact hne rfl + simp only [familyName_zero,familyAtom_zero,familyAtom_name old _ h hc0] + apply FiniteRandom.prob_update_bound_pi (ι h) + intro ω + simpa only [Function.update_self,abs_sub_comm] using hconst h c hc hc0 (old x) + · by_cases hc0 : c=0 + · subst c + simp only [familyName_zero,familyAtom_zero,familyAtom_name old _ g ha0] + apply FiniteRandom.prob_update_bound_pi (ι g) + intro ω + simpa only [Function.update_self] using hconst g a ha ha0 (old x) + · simp only [familyAtom_name old _ g ha0,familyAtom_name old _ h hc0] + by_cases hgh : g=h + · subst h + have hac : a ≠ c := by intro he; subst c; exact hne rfl + apply FiniteRandom.prob_update_bound_pi (ι g) + intro ω + simpa only [Function.update_self] using hpair g a ha c hc hac + · apply FiniteRandom.prob_update_bound_pi (ι g) + intro ω + simpa only [Function.update_self,Function.update_of_ne (fun he => hgh (hinj he).symm)] using + hconst g a ha ha0 (A h (ω (ι h)) c x) + + +lemma familyNames_card_sparse {k N : ℕ} (S : Fin k → Finset ℕ) (T : Finset (Fin k)) + (hS : ∀ g ∈ T, (S g).card≤N) (hout : ∀ g, g∉T → S g⊆{0}) : + (familyNames S).card≤1+T.card*N := by + classical + have hsub : familyNames S⊆insert 0 (T.biUnion (fun g => (S g).image (familyName g))) := by + intro i hi + rcases mem_familyNames.mp hi with rfl | ⟨g,j,hj,rfl⟩ + · exact Finset.mem_insert_self _ _ + · by_cases hg : g∈T + · exact Finset.mem_insert_of_mem (Finset.mem_biUnion.mpr ⟨g,hg,Finset.mem_image.mpr ⟨j,hj,rfl⟩⟩) + · have hj0 : j=0 := Finset.mem_singleton.mp (hout g hg hj) + rw [hj0,familyName_zero] + exact Finset.mem_insert_self _ _ + calc + _ ≤ (insert 0 (T.biUnion (fun g => (S g).image (familyName g)))).card := Finset.card_le_card hsub + _ ≤ (T.biUnion (fun g => (S g).image (familyName g))).card+1 := Finset.card_insert_le _ _ + _ ≤ (∑ g∈T, ((S g).image (familyName g)).card)+1 := Nat.add_le_add_right Finset.card_biUnion_le 1 + _ ≤ (∑ _g∈T, N)+1 := Nat.add_le_add_right (Finset.sum_le_sum (fun g hg => + (Finset.card_image_le (s := S g) (f := familyName g)).trans (hS g hg))) 1 + _ = 1+T.card*N := by simp [Nat.add_comm] + +lemma selection_near_tie_modulus {X : Type*} (F : X → NamedValue) + (atom : ℕ → X → ℝ) (S : Finset ℕ) (x : X) (P : X → Prop) (hx : P x) {e : ℝ} + (hF : ∀ z, P z → |(F x).value-(F z).value|≤e) + (hA : ∀ i∈S, ∀ z, P z → |atom i z-atom i x|≤e) + (hlist : ∀ z, P z → (F z).name∈S ∧ (F z).value=atom (F z).name z) + (hbad : ∃ z, P z ∧ (F z).name≠(F x).name) : + ∃ i∈S, ∃ j∈S, i≠j ∧ |atom i x-atom j x|≤2*e := by + obtain ⟨z,hz,hn⟩ := hbad + refine ⟨(F x).name,(hlist x hx).1,(F z).name,(hlist z hz).1,Ne.symm hn,?_⟩ + have hf := hF z hz + have ha := hA (F z).name (hlist z hz).1 z hz + rw [←(hlist z hz).2] at ha + rw [←(hlist x hx).2] + have ht := abs_sub_le (F x).value (F z).value (atom (F z).name x) + linarith + +lemma selection_probability_modulus {X Ω : Type*} [Fintype Ω] + (F : Ω → X → NamedValue) (atom : Ω → ℕ → X → ℝ) (S : Finset ℕ) + (x : X) (P : X → Prop) (hx : P x) {e b : ℝ} (hb : 0≤b) + (hF : ∀ ω z, P z → |(F ω x).value-(F ω z).value|≤e) + (hA : ∀ ω i, i∈S → ∀ z, P z → |atom ω i z-atom ω i x|≤e) + (hlist : ∀ ω z, P z → (F ω z).name∈S ∧ (F ω z).value=atom ω (F ω z).name z) + (hpair : ∀ i∈S, ∀ j∈S, i≠j → + FiniteRandom.prob (fun ω => |atom ω i x-atom ω j x|≤2*e)≤b) : + FiniteRandom.prob (fun ω => ∃ z, P z ∧ (F ω z).name≠(F ω x).name)≤S.card^2*b := by + apply (FiniteRandom.prob_mono (fun ω h => selection_near_tie_modulus (F ω) (atom ω) S x P hx + (hF ω) (hA ω) (hlist ω) h)).trans + exact FiniteRandom.prob_pair_bound S _ hb hpair + +lemma maxSelection_modulus {X : Type*} (old : X → NamedValue) + (Fs : List (X → NamedValue)) (x z : X) {e : ℝ} + (ho : |(old x).value-(old z).value|≤e) + (hF : ∀ F∈Fs, |(F x).value-(F z).value|≤e) : + |(maxSelection old Fs x).value-(maxSelection old Fs z).value|≤e := by + induction Fs with + | nil => exact ho + | cons F Fs ih => + simp only [maxSelection,maxNamed_value] + exact (abs_max_sub_max_le_max _ _ _ _).trans (max_le (hF F (by simp)) + (ih (fun G hG => hF G (List.mem_cons_of_mem _ hG)))) + +lemma familySelection_modulus {X : Type*} {k : ℕ} (old : X → ℝ) + (F : Fin k → X → NamedValue) (x z : X) {e : ℝ} + (ho : |old x-old z|≤e) (hF : ∀ g, |(F g x).value-(F g z).value|≤e) : + |(familySelection old F x).value-(familySelection old F z).value|≤e := by + apply maxSelection_modulus _ _ _ _ ho + intro G hG + obtain ⟨g,rfl⟩ := List.mem_ofFn.mp hG + exact hF g + +lemma familyAtom_modulus {X : Type*} {k : ℕ} (old : X → ℝ) + (A : Fin k → ℕ → X → ℝ) (x z : X) {e : ℝ} + (ho : |old z-old x|≤e) (hA : ∀ g i, |A g i z-A g i x|≤e) (i : ℕ) : + |familyAtom old A i z-familyAtom old A i x|≤e := by + simp only [familyAtom] + split_ifs with h h' + · exact ho + · exact hA _ _ + · exact ho + +/-- Sparse, genuinely independent component samples in the literal maximum. +The full family numbering is retained even for groups irrelevant to the ball. -/ +lemma familySelection_probability_sparse {X I : Type*} {D : I → Type*} + [Fintype I] [DecidableEq I] [∀ i, Fintype (D i)] [∀ i, Nonempty (D i)] + {k N B : ℕ} (ι : Fin k → I) (hinj : Function.Injective ι) + (old : X → ℝ) (F : ∀ g : Fin k, D (ι g) → X → NamedValue) + (A : ∀ g : Fin k, D (ι g) → ℕ → X → ℝ) + (S : Fin k → Finset ℕ) (T : Finset (Fin k)) + (hcard : ∀ g∈T, (S g).card≤N) (hout : ∀ g, g∉T → S g⊆{0}) (hT : T.card≤B) + (x : X) (P : X → Prop) (hx : P x) {e b : ℝ} (hb : 0≤b) + (ho : ∀ z, P z → |old x-old z|≤e) + (hF : ∀ g ω z, P z → |(F g ω x).value-(F g ω z).value|≤e) + (hA : ∀ g ω i z, P z → |A g ω i z-A g ω i x|≤e) + (hzero : ∀ g ω z, A g ω 0 z=old z) + (hlist : ∀ g ω z, P z → (F g ω z).name∈S g ∧ (F g ω z).value=A g ω (F g ω z).name z) + (hpair : ∀ g i, i∈S g → ∀ j, j∈S g → i≠j → + FiniteRandom.prob (fun ω => |A g ω i x-A g ω j x|≤2*e)≤b) + (hconst : ∀ g i, i∈S g → i≠0 → ∀ c : ℝ, + FiniteRandom.prob (fun ω => |A g ω i x-c|≤2*e)≤b) : + FiniteRandom.prob (fun ω : ∀ i, D i => ∃ z, P z ∧ + (familySelection old (fun g => F g (ω (ι g))) z).name≠ + (familySelection old (fun g => F g (ω (ι g))) x).name) ≤ (1+B*N : ℕ)^2*b := by + have hp := selection_probability_modulus + (fun ω : ∀ i, D i => familySelection old (fun g => F g (ω (ι g)))) + (fun ω => familyAtom old (fun g => A g (ω (ι g)))) (familyNames S) x P hx hb + (fun ω z hz => familySelection_modulus old _ x z (ho z hz) (fun g => hF g _ z hz)) + (fun ω i _ z hz => familyAtom_modulus old _ x z ((abs_sub_comm _ _).trans_le (ho z hz)) + (fun g j => hA g _ j z hz) i) + (fun ω z hz => familySelection_list old _ _ S (fun g y => hzero g _ y) z (fun g => hlist g _ z hz)) + (fun i hi j hj hij => familyAtomPair_probability_pi ι hinj old A S x hpair hconst i j hi hj hij) + refine hp.trans (mul_le_mul_of_nonneg_right (pow_le_pow_left₀ (Nat.cast_nonneg (familyNames S).card) ?_ 2) hb) + exact_mod_cast (familyNames_card_sparse S T hcard hout).trans + (Nat.add_le_add_left (Nat.mul_le_mul_right N hT) 1) +end PlanarL1.Interpolation + +end + + + +section + +namespace PlanarL1.Interpolation +/-- A local finite atom expansion, including its proved one-coordinate tests. +This is proof data for an actual named field, not a substitute for a chart. -/ +structure LocalList {X W : Type*} [Fintype W] (old : X → ℝ) + (F : W → X → NamedValue) (x : X) (e b : ℝ) where + names : Finset ℕ + atom : W → ℕ → X → ℝ + zero : ∀ w z, atom w 0 z=old z + selected : ∀ w z, (F w z).name∈names ∧ (F w z).value=atom w (F w z).name z + field_variation : ∀ w z, |(F w x).value-(F w z).value|≤e + atom_variation : ∀ w i z, |atom w i z-atom w i x|≤e + pair_test : ∀ i∈names, ∀ j∈names, i≠j → + FiniteRandom.prob (fun w => |atom w i x-atom w j x|≤2*e)≤b + constant_test : ∀ i∈names, i≠0 → ∀ c : ℝ, + FiniteRandom.prob (fun w => |atom w i x-c|≤2*e)≤b + +noncomputable def oldLocalList {X W : Type*} [Fintype W] (old : X → ℝ) + (x : X) {e b : ℝ} (ho : ∀ z, |old x-old z|≤e) : + LocalList old (fun (_ : W) z => ⟨0,old z⟩) x e b where + names := {0} + atom _ _ z := old z + zero _ _ := rfl + selected _ _ := ⟨Finset.mem_singleton_self _,rfl⟩ + field_variation _ z := ho z + atom_variation _ _ z := (abs_sub_comm _ _).trans_le (ho z) + pair_test _i hi _j hj hn := False.elim (hn ((Finset.mem_singleton.mp hi).trans (Finset.mem_singleton.mp hj).symm)) + constant_test _i hi hn := False.elim (hn (Finset.mem_singleton.mp hi)) + +lemma LocalList.family_probability {X I : Type*} {D : I → Type*} + [Fintype I] [DecidableEq I] [∀ i, Fintype (D i)] [∀ i, Nonempty (D i)] + {k N B : ℕ} (ι : Fin k → I) (hinj : Function.Injective ι) + (old : X → ℝ) (F : ∀ g : Fin k, D (ι g) → X → NamedValue) + (x : X) {e b : ℝ} (hb : 0≤b) (ho : ∀ z, |old x-old z|≤e) + (L : ∀ g, LocalList old (F g) x e b) (T : Finset (Fin k)) + (hc : ∀ g∈T, (L g).names.card≤N) (hout : ∀ g, g∉T → (L g).names⊆{0}) (hT : T.card≤B) : + FiniteRandom.prob (fun w : ∀ i, D i => ∃ z, + (familySelection old (fun g => F g (w (ι g))) z).name≠ + (familySelection old (fun g => F g (w (ι g))) x).name)≤(1+B*N : ℕ)^2*b := by + simpa only [true_and] using familySelection_probability_sparse ι hinj old F + (fun g => (L g).atom) (fun g => (L g).names) T hc hout hT x (fun _ => True) trivial hb + (fun z _ => ho z) (fun g w z _ => (L g).field_variation w z) + (fun g w i z _ => (L g).atom_variation w i z) (fun g => (L g).zero) + (fun g w z _ => (L g).selected w z) (fun g => (L g).pair_test) (fun g => (L g).constant_test) +end PlanarL1.Interpolation + +namespace PlanarL1.Columns.Model.SecondaryCell +open PlanarL1.Interpolation +open scoped NNReal +variable {n : ℕ} {M : Model n} {J : Set ℝ} {root : Fin n} +variable (R : Point.RadialTree (M := M) (J := J) (root := root)) +variable (S : Finset (M.Point J root)) (old L : M.Point J root → ℝ) + +/-- Literal secondary field has a bounded local atom expansion on any lifted +ball. The chosen radial node and the whole list precede all fresh offsets. -/ +lemma sampled_local_list {X : Type*} (lift : X → M.Point J root) (x : X) {ρ : ℝ} + (hρ : 0≤ρ) (hs : ρ≤R.radius) (hd : ∀ z, dist (lift x) (lift z)≤ρ) + (ordinary : Bool) (hOld : LipschitzWith 5 old) (hL : LipschitzWith 1 L) + (hζ : R.ζ=(1:ℝ)/10) (pc radius lo B : ℝ) (hB : 0 < B) (m : ℕ) (hm : 0 < m) : + ∃ C : LocalList (fun z => old (lift z)) + (fun (w : Point.RadialTree.GridSample (n := n) R.depthCap m × Fin (m+1) × Fin (m+1)) z => + namedReplacement R S old L ordinary pc radius (B/m*w.2.1.val) (B/m*w.2.2.val) lo + (R.gridNoise R.depthCap m w.1) (lift z)) x ((replacementConstant R : ℝ)*ρ) + (((4*(replacementConstant R : ℝ)*ρ+R.q/m)/R.q)+(4*(replacementConstant R : ℝ)*ρ+B/m)/B), + C.names.card≤6*(R.lookback+1)+3 := by + classical + obtain ⟨k,A,hlo,heq⟩ := R.common_formula (lift x) hρ hs + have hk : k < R.depthCap := (R.depth_le_layerDepth (lift x) (hlo _ (by simpa using hρ))).trans_lt + (R.layerDepth_lt_cap _) + let atom := fun (w : Point.RadialTree.GridSample (n := n) R.depthCap m × Fin (m+1) × Fin (m+1)) + (i : ℕ) z => localAtom R S old L A pc radius (B/m*w.2.1.val) (B/m*w.2.2.val) lo + (R.gridNoise R.depthCap m w.1) i (lift z) + have ha (w : Point.RadialTree.GridSample (n := n) R.depthCap m × Fin (m+1) × Fin (m+1)) (i : ℕ) : LipschitzWith (replacementConstant R) + (localAtom R S old L A pc radius (B/m*w.2.1.val) (B/m*w.2.2.val) lo + (R.gridNoise R.depthCap m w.1) i) := localAtom_lipschitz R S old L hOld hL A _ _ _ _ _ _ i + refine ⟨{ names := secondaryNames (R.recentNames A R.lookback) + atom := atom + zero := ?_ + selected := ?_ + field_variation := ?_ + atom_variation := ?_ + pair_test := ?_ + constant_test := ?_ }, ?_⟩ + · intro w z + simp [atom,localAtom,secondaryAtom] + · intro w z + exact namedReplacement_local_list R S old L hζ A (lift x) hlo heq ordinary _ _ _ _ _ _ + (R.gridNoise_bounds _ _ hm _) (lift z) (hd z) + · intro w z + exact ((sampledReplacement_lipschitz R S old L ordinary hOld hL pc radius lo B _ m hm w).dist_le_mul + (lift x) (lift z)).trans (mul_le_mul_of_nonneg_left (hd z) (NNReal.coe_nonneg _)) + · intro w i z + have hh := (ha w i).dist_le_mul (lift z) (lift x) + rw [Real.dist_eq,dist_comm (lift z)] at hh + exact hh.trans (mul_le_mul_of_nonneg_left (hd z) (NNReal.coe_nonneg _)) + · intro i hi j hj hij + simpa only [atom,show 2*(2*((replacementConstant R : ℝ)*ρ))=4*(replacementConstant R : ℝ)*ρ by ring] using + localAtomPair_probability R S old L A (lift x) pc radius lo B hB _ m hk hm i j hi hj hij + (show 0≤2*((replacementConstant R : ℝ)*ρ) by positivity) + · intro i hi hi0 c + simpa only [atom,show 2*(2*((replacementConstant R : ℝ)*ρ))=4*(replacementConstant R : ℝ)*ρ by ring] using + localAtomConstant_probability R S old L A (lift x) pc radius lo B hB _ m hk hm i hi hi0 c + (show 0≤2*((replacementConstant R : ℝ)*ρ) by positivity) + · exact (secondaryNames_card _).trans (Nat.add_le_add_right (R.recentNames_card A R.lookback) 3) +end PlanarL1.Columns.Model.SecondaryCell + +end + +end OAI diff --git a/lean/OAI/Combinatorics/PlanarL1/MainCells.lean b/lean/OAI/Combinatorics/PlanarL1/MainCells.lean new file mode 100644 index 0000000000000000000000000000000000000000..0b2b55309bb3085ab1968a70ef8e1836d1bc925f --- /dev/null +++ b/lean/OAI/Combinatorics/PlanarL1/MainCells.lean @@ -0,0 +1,780 @@ +import OAI.Combinatorics.PlanarL1.Bands +import OAI.Combinatorics.PlanarL1.RadialTree +import OAI.Combinatorics.PlanarL1.Gluing +import OAI.Combinatorics.PlanarL1.Clipping + +namespace OAI + +section + +namespace PlanarL1.Columns.Model + +open scoped NNReal +variable {n : ℕ} {M : Model n} {I J : Set ℝ} {root : Fin n} + +lemma Field.widen_lipschitz (F : M.Field I 1) (hJI : J ⊆ I) (hJ : IsClosed J) : + LipschitzWith 1 (fun x : M.Point J root => F.eval (x.widen hJI)) := by + apply LipschitzWith.of_dist_le_mul + intro x y + obtain ⟨p, _, hp⟩ := x.exists_shortest hJ y + have hf := F.path_bound (p.widen hJI) ⟨x.height,hJI x.inBand⟩ ⟨y.height,hJI y.inBand⟩ + simpa only [Real.dist_eq, NNReal.coe_one, one_mul, Path.length_widen,hp,Field.eval,Point.widen] using hf + +namespace MainCell +variable (F : M.Field I 1) (hJI : J ⊆ I) +variable (R : Point.RadialTree (M := M) (J := J) (root := root)) (q : ℝ) +abbrev Cell := ((M.activeGraph J).induce (R.base.layer R.base.height R.base.inBand q (1/1000))).ConnectedComponent +variable (C : Cell R q) + +noncomputable def old (x : M.Point J root) : ℝ := F.eval (x.widen hJI) + +def boundary : Set (M.Point J root) := + {x | x.column ∈ Point.frontier (M := M) (J := J) (ColumnOrder.componentColumns C)} + +noncomputable def input (v : M.Point J root) : M.Point J root → ℝ := + Clipping.envelope (boundary R q C) (old F hJI) (old F hJI v+1) (1-R.ζ) + +noncomputable def proposal (v : M.Point J root) (α : Point.RadialTree.Noise (n := n)) + (E : ℝ) (x : M.Point J root) : ℝ := + (R.pasted (input F hJI R q C v) α x).value-4*E + +lemma boundary_compact (hJ : IsCompact J) : IsCompact (boundary R q C) := + Point.fullColumns_compact hJ _ + +include R in +lemma old_lipschitz : LipschitzWith 1 (old F hJI : M.Point J root → ℝ) := + F.widen_lipschitz hJI R.closed_band + +lemma input_lipschitz (hJ : IsCompact J) (v : M.Point J root) : + R.InputLip (input F hJI R q C v) := by + let t : ℝ≥0 := ⟨1-R.ζ,by linarith [R.zeta_lt_one]⟩ + have h := Clipping.envelope_lipschitz (boundary_compact R q C hJ) + (old_lipschitz F hJI R).continuous.continuousOn (old F hJI v+1) t + intro x y + exact h.dist_le_mul x y + +lemma proposal_accuracy (hJ : IsCompact J) (v x : M.Point J root) + {α : Point.RadialTree.Noise (n := n)} (hα : R.NoiseBounds α) {E : ℝ} (hE : 0 ≤ E) + (hδ : R.δ = E/8) : + input F hJI R q C v x-5*E ≤ proposal F hJI R q C v α E x ∧ + proposal F hJI R q C v α E x ≤ input F hJI R q C v x-3*E := by + have ha := abs_le.mp (R.pasted_accuracy (input_lipschitz F hJI R q C hJ v) hα x) + dsimp only [proposal] + rw [hδ] at ha + constructor <;> linarith + +lemma proposal_lipschitz (v : M.Point J root) {α : Point.RadialTree.Noise (n := n)} + (hα : R.NoiseBounds α) (E : ℝ) : LipschitzWith 1 (proposal F hJI R q C v α E) := by + apply LipschitzWith.of_dist_le_mul + intro x y + simpa only [proposal,dist_sub_right] using (R.pasted_lipschitz (input F hJI R q C v) hα).dist_le_mul x y + +lemma frontier_margin (hJ : IsCompact J) (v : M.Point J root) + {α : Point.RadialTree.Noise (n := n)} (hα : R.NoiseBounds α) {E : ℝ} (hE : 0 ≤ E) + (hδ : R.δ = E/8) {z : M.Point J root} (hz : z ∈ boundary R q C) : + proposal F hJI R q C v α E z ≤ old F hJI z-3*E := by + have hf := Clipping.envelope_frontier (boundary_compact R q C hJ) + (old_lipschitz F hJI R).continuous.continuousOn (old F hJI v+1) (1-R.ζ) hz + have hp := (proposal_accuracy F hJI R q C hJ v z hα hE hδ).2 + change input F hJI R q C v z ≤ old F hJI z at hf + linarith + +lemma variation (hthin : R.a ≤ (1/1000:ℝ)/1000) (v x : M.Point J root) + (hv : v.column ∈ ColumnOrder.componentColumns C) + (hx : x.column ∈ ColumnOrder.componentColumns C) : + |old F hJI v-old F hJI x| ≤ (1:ℝ)/100 := by + have hd := R.base.radial_cell_diameter R.closed_band R.base.inBand + R.width_pos hthin R.half_width C v x hv hx + have hf := (old_lipschitz F hJI R).dist_le_mul v x + rw [Real.dist_eq,NNReal.coe_one,one_mul] at hf + exact hf.trans (by linarith) + +lemma movement (hJ : IsCompact J) (hthin : R.a ≤ (1/1000:ℝ)/1000) + (v x : M.Point J root) (hv : v.column ∈ ColumnOrder.componentColumns C) + (hx : x.column ∈ ColumnOrder.componentColumns C) + {α : Point.RadialTree.Noise (n := n)} (hα : R.NoiseBounds α) {E : ℝ} (hE : 0 ≤ E) + (hδ : R.δ = E/8) (H : M.Point J root → ℝ) : + 0 ≤ Clipping.clip (old F hJI) (proposal F hJI R q C v α E) H x-old F hJI x ∧ + Clipping.clip (old F hJI) (proposal F hJI R q C v α E) H x-old F hJI x ≤ 1+(1:ℝ)/100 := by + apply Clipping.clip_movement (by norm_num) + have hf := (proposal_accuracy F hJI R q C hJ v x hα hE hδ).2 + have hc := Clipping.envelope_le_cap (boundary R q C) (old F hJI) (old F hJI v+1) (1-R.ζ) x + have hvx := (abs_le.mp (variation F hJI R q C hthin v x hv hx)).2 + change input F hJI R q C v x ≤ old F hJI v+1 at hc + linarith + +/-- The literal main test: the proposal is the actual interpolated compact +frontier envelope, and failure to raise constructs an attaining path in J. -/ +lemma raise_or_descent (hJ : IsCompact J) (v w : M.Point J root) + (hv : v.column ∈ ColumnOrder.componentColumns C) + (hw : w.column ∈ ColumnOrder.componentColumns C) + {ε : ℝ} (hε : 0 < ε) (hεsmall : ε ≤ (1:ℝ)/100) + (hζ : R.ζ = ε/100) (hδ : R.δ = (ε/1000)/8) + {α : Point.RadialTree.Noise (n := n)} (hα : R.NoiseBounds α) + (H : M.Point J root → ℝ) (hH : old F hJI v+2 ≤ H w) + (hlow : q+(1:ℝ)/100000+2*R.a < dist R.base (w.withHeight R.base.height R.base.inBand)) + (hupp : dist R.base (w.withHeight R.base.height R.base.inBand) < q+(1:ℝ)/1000-(1:ℝ)/100000-2*R.a) : + old F hJI w+2*(ε/1000) < + Clipping.clip (old F hJI) (proposal F hJI R q C v α (ε/1000)) H w ∨ + Nonempty (F.BandDescent J (w.widen hJI) ε) := by + have hthin : R.a ≤ (1/1000:ℝ)/1000 := by + have hb := R.width_bound + have hm := mul_lt_mul_of_pos_right R.zeta_lt_one R.delta_pos + rw [hδ] at hb hm + nlinarith + have hvw := abs_le.mp (variation F hJI R q C hthin v w hv hw) + have hrad : ∀ z ∈ boundary R q C, (0.00001:ℝ) ≤ dist w z ∧ dist w z ≤ 0.02 := by + intro z hz + have hl := R.base.radial_frontier_distance w z R.base.inBand R.half_width C hlow hupp hz + have hu := R.base.radial_cell_diameter R.closed_band R.base.inBand R.width_pos hthin + R.half_width C w z hw hz.1 + constructor <;> linarith + have hraise := Clipping.raise_or_descending_endpoint (H := H) (boundary_compact R q C hJ) + (old_lipschitz F hJI R).continuous.continuousOn w (old F hJI v+1) R.ζ (ε/1000) ε + (proposal_accuracy F hJI R q C hJ v w hα (by linarith) hδ).1 + (by linarith) (by linarith) hrad R.zeta_pos.le (by rw [hζ]; linarith) + rcases hraise with hh | ⟨z,hz,hlo,hup,hdrop⟩ + · exact Or.inl hh + · right + obtain ⟨p,_,hp⟩ := w.exists_shortest R.closed_band z + refine ⟨{ + start_in := w.inBand + target := z.widen hJI + target_in := z.inBand + path := p + shortest := ?_ + lower := ?_ + upper := ?_ + drop := ?_ }⟩ + · intro p' + change p.length w.height z.height ≤ p'.length w.height z.height + rw [hp] + exact w.distance_le z p' + · change (1:ℝ)/100000 ≤ p.length w.height z.height + rw [hp] + linarith + · change p.length w.height z.height ≤ (1:ℝ)/50 + rw [hp] + linarith + · change old F hJI z ≤ old F hJI w-p.length w.height z.height+ε + rwa [hp] + +end MainCell +end PlanarL1.Columns.Model + + +end + +section + +namespace PlanarL1.Columns.Model.MainCell +open scoped NNReal +open Set MeasureTheory +attribute [local instance] Classical.propDecidable +variable {n : ℕ} {M : Model n} {I J : Set ℝ} {root : Fin n} +variable (F : M.Field I 1) (hJI : J ⊆ I) +variable (R : Point.RadialTree (M := M) (J := J) (root := root)) (q : ℝ) +variable (C : Cell R q) + +noncomputable def replacement (v : M.Point J root) + (α : Point.RadialTree.Noise (n := n)) (E β lo : ℝ) (x : M.Point J root) : ℝ := + Clipping.clip (old F hJI) (proposal F hJI R q C v α E) + (fun x => Clipping.heightShield lo R.a (old F hJI v) β x.height) x + +noncomputable def replacementConstant : ℝ≥0 := + max 1 ⟨3/(9*R.a/100), by positivity [R.width_pos]⟩ + +lemma replacement_lipschitz (v : M.Point J root) + {α : Point.RadialTree.Noise (n := n)} (hα : R.NoiseBounds α) (E β lo : ℝ) : + LipschitzWith (replacementConstant R) (replacement F hJI R q C v α E β lo) := by + apply Clipping.clip_lipschitz + · exact (old_lipschitz F hJI R).weaken (le_max_left _ _) + · exact (proposal_lipschitz F hJI R q C v hα E).weaken (le_max_left _ _) + · apply LipschitzWith.of_dist_le_mul + intro x y + have h := (Clipping.heightShield_lipschitz lo (old F hJI v) β R.width_pos).dist_le_mul + x.height y.height + have hheight := x.height_change_le y + change |x.height-y.height| ≤ dist x y at hheight + change dist _ _ ≤ (replacementConstant R : ℝ)*dist x y + change dist _ _ ≤ (3/(9*R.a/100))*dist x.height y.height at h + rw [Real.dist_eq x.height y.height] at h + exact h.trans ((mul_le_mul_of_nonneg_left hheight (by positivity [R.width_pos])).trans + (mul_le_mul_of_nonneg_right (le_max_right (1:ℝ) (3/(9*R.a/100))) dist_nonneg)) + +lemma replacement_switch (v x y : M.Point J root) + {α : Point.RadialTree.Noise (n := n)} (hα : R.NoiseBounds α) (E β lo : ℝ) + (he : x.height = y.height) (hs : x.height ∈ M.heights x.column y.column) : + replacement F hJI R q C v α E β lo x = replacement F hJI R q C v α E β lo y := by + have hd := x.dist_le_switch y x.inBand hs + rw [he,sub_self,abs_zero,add_zero] at hd + have hh := (replacement_lipschitz F hJI R q C v hα E β lo).dist_le_mul x y + rw [le_antisymm hd dist_nonneg,mul_zero] at hh + exact dist_le_zero.mp hh + +lemma replacement_frontier (hJ : IsCompact J) (v x : M.Point J root) + {α : Point.RadialTree.Noise (n := n)} (hα : R.NoiseBounds α) + {E : ℝ} (hE : 0 ≤ E) (hδ : R.δ = E/8) (β lo : ℝ) + (hx : x ∈ boundary R q C) : + replacement F hJI R q C v α E β lo x = old F hJI x := by + apply Clipping.clip_unchanged + left + have h := frontier_margin F hJI R q C hJ v hα hE hδ hx + linarith + +lemma replacement_endpoint (hthin : R.a ≤ (1/1000:ℝ)/1000) + (v x : M.Point J root) (hv : v.column ∈ ColumnOrder.componentColumns C) + (hx : x.column ∈ ColumnOrder.componentColumns C) + (α : Point.RadialTree.Noise (n := n)) (E β lo : ℝ) (hβ : β ≤ (1:ℝ)/100) + (he : x.height = lo ∨ x.height = lo+R.a) : + replacement F hJI R q C v α E β lo x = old F hJI x := by + apply Clipping.clip_unchanged + right + have h := (abs_le.mp (variation F hJI R q C hthin v x hv hx)).2 + have hh : Clipping.heightShield lo R.a (old F hJI v) β x.height = old F hJI v-1+β := by + rcases he with he | he + · exact Clipping.heightShield_left (by rw [he]) + · exact Clipping.heightShield_right (by rw [he]) + rw [hh] + linarith + + +lemma scaled_replacement_constant (ha : R.a ≤ 1) : + (R.a/1000000) * (replacementConstant R : ℝ) ≤ 1 := by + change (R.a/1000000) * max 1 (3/(9*R.a/100)) ≤ 1 + rw [mul_max_of_nonneg (1:ℝ) (3/(9*R.a/100)) (by positivity [R.width_pos])] + apply max_le + · linarith + · have hpos : 0 < 9*R.a/100 := by positivity [R.width_pos] + rw [← mul_div_assoc] + apply (div_le_iff₀ hpos).mpr + nlinarith [R.width_pos] + +/-- Actual closed full-column update domain. -/ +def domain (i : Fin n) : Set ℝ := + if i ∈ ColumnOrder.componentColumns C then J else ∅ + +lemma mem_domain {i : Fin n} {H : ℝ} : + H ∈ domain R q C i ↔ i ∈ ColumnOrder.componentColumns C ∧ H ∈ J := by + by_cases hi : i ∈ ColumnOrder.componentColumns C <;> simp [domain,hi] + +lemma closed_domain (i : Fin n) : IsClosed (domain R q C i) := by + by_cases hi : i ∈ ColumnOrder.componentColumns C <;> + simp only [domain,hi,ite_true,ite_false] + · exact R.closed_band + · exact isClosed_empty + +/-- The actual point in the broad component underlying a cell-domain point. -/ +def cellPoint (i : Fin n) (H : ℝ) (h : H ∈ domain R q C i) : M.Point J root := + ⟨i,H,((mem_domain R q C).mp h).2, + (ColumnOrder.componentColumns_subset C ((mem_domain R q C).mp h).1).choose⟩ + +noncomputable def converted (v : M.Point J root) + (α : Point.RadialTree.Noise (n := n)) (E β lo c η κ : ℝ) (i : Fin n) (H : ℝ) : ℝ := + if h : H ∈ domain R q C i then + κ * (c + η * replacement F hJI R q C v α E β lo (cellPoint R q C i H h)) else 0 + +lemma converted_on (v : M.Point J root) + (α : Point.RadialTree.Noise (n := n)) (E β lo c η κ : ℝ) {i : Fin n} {H : ℝ} + (h : H ∈ domain R q C i) : + converted F hJI R q C v α E β lo c η κ i H = + κ * (c + η * replacement F hJI R q C v α E β lo (cellPoint R q C i H h)) := by + simp only [converted,dite_eq_left h] + +lemma converted_lipschitz (v : M.Point J root) + {α : Point.RadialTree.Noise (n := n)} (hα : R.NoiseBounds α) (E β lo c η κ : ℝ) + (hη : |η| = 1) (hκ : 0 ≤ κ) (hκK : κ*(replacementConstant R : ℝ) ≤ 1) (i : Fin n) : + LipschitzOnWith 1 (converted F hJI R q C v α E β lo c η κ i) (domain R q C i) := by + apply LipschitzOnWith.of_dist_le_mul + intro H hH T hT + rw [converted_on F hJI R q C v α E β lo c η κ hH, + converted_on F hJI R q C v α E β lo c η κ hT] + let x := cellPoint R q C i H hH + let y := cellPoint R q C i T hT + have h := (replacement_lipschitz F hJI R q C v hα E β lo).dist_le_mul x y + rw [x.dist_same_column y rfl] at h + simp only [Real.dist_eq,NNReal.coe_one,one_mul] + change |κ*(c+η*replacement F hJI R q C v α E β lo x)- + κ*(c+η*replacement F hJI R q C v α E β lo y)| ≤ |H-T| + rw [show κ*(c+η*replacement F hJI R q C v α E β lo x)- + κ*(c+η*replacement F hJI R q C v α E β lo y) = + κ*η*(replacement F hJI R q C v α E β lo x-replacement F hJI R q C v α E β lo y) by ring, + abs_mul,abs_mul,abs_of_nonneg hκ,hη,mul_one] + rw [Real.dist_eq] at h + change |_ - _| ≤ (replacementConstant R : ℝ) * |H-T| at h + calc + _ ≤ κ*((replacementConstant R : ℝ)*|H-T|) := mul_le_mul_of_nonneg_left h hκ + _ = (κ*(replacementConstant R : ℝ))*|H-T| := by ring + _ ≤ 1*|H-T| := mul_le_mul_of_nonneg_right hκK (abs_nonneg _) + _ = _ := one_mul _ + + +/-- A kept main cell, with the literal interpolated proposal and trapezoidal +shield, is an actual invariant-preserving measurable set update. The old +chart agreement is used only on its real update domain. -/ +noncomputable def patch {Ω : Type*} [MeasurableSpace Ω] {μ : Measure Ω} + (A : SetSystem M Ω μ) (Z : Threshold.Variables Ω μ) + (hJ : IsCompact J) (lo : ℝ) (hband : J = Icc lo (lo+R.a)) + (hthin : R.a ≤ (1/1000:ℝ)/1000) + (v : M.Point J root) (hv : v.column ∈ ColumnOrder.componentColumns C) + {α : Point.RadialTree.Noise (n := n)} (hα : R.NoiseBounds α) + (E β c η κ : ℝ) (hE : 0 ≤ E) (hδ : R.δ = E/8) (hβ : β ≤ (1:ℝ)/100) + (hη : |η| = 1) (hκ : 0 ≤ κ) (hκK : κ*(replacementConstant R : ℝ) ≤ 1) + (hchart : ∀ ω i H (h : H ∈ domain R q C i), + Threshold.active Z H (κ*(c+η*old F hJI (cellPoint R q C i H h))) ω ↔ + (A.activity ω).active i H) : SetPatch A := by + apply Threshold.chartPatch A Z (domain R q C) (closed_domain R q C) + (converted F hJI R q C v α E β lo c η κ) + (converted_lipschitz F hJI R q C v hα E β lo c η κ hη hκ hκK) + · intro ω i H hH + have hd : H ∈ domain R q C i := (closed_domain R q C i).frontier_subset hH + have hi := ((mem_domain R q C).mp hd).1 + rw [converted_on F hJI R q C v α E β lo c η κ hd] + have he : H = lo ∨ H = lo+R.a := by + simpa only [domain,ite_eq_left hi,hband,frontier_Icc (a := lo) (b := lo+R.a) (by linarith [R.width_pos]), + mem_insert_iff,mem_singleton_iff] using hH + rw [replacement_endpoint F hJI R q C hthin v (cellPoint R q C i H hd) + hv hi α E β lo hβ he] + exact hchart ω i H hd + · intro i j H hs hi hj + rw [converted_on F hJI R q C v α E β lo c η κ hi, + converted_on F hJI R q C v α E β lo c η κ hj, + replacement_switch F hJI R q C v (cellPoint R q C i H hi) + (cellPoint R q C j H hj) hα E β lo rfl hs] + · intro ω i j H hs hi hj + have hmem := (mem_domain R q C).mp hi + have hnj : j ∉ ColumnOrder.componentColumns C := by + intro h + exact hj ((mem_domain R q C).mpr ⟨h,hmem.2⟩) + have hf : cellPoint R q C i H hi ∈ boundary R q C := + ⟨hmem.1,j,⟨H,hmem.2,hs⟩,hnj⟩ + rw [converted_on F hJI R q C v α E β lo c η κ hi, + replacement_frontier F hJI R q C hJ v (cellPoint R q C i H hi) hα hE hδ β lo hf] + exact hchart ω i H hi + +end PlanarL1.Columns.Model.MainCell + + +end + +section + +namespace PlanarL1.Columns.Model.Point +variable {n : ℕ} {M : Model n} {J : Set ℝ} {root : Fin n} + +/-- A shortest path leaving any full-column cell meets its actual frontier +before using more than its total length. No shape/convexity of the cell is used. -/ +lemma near_frontier_of_not_mem (hJ : IsClosed J) (S : Set (Fin n)) + (x y : M.Point J root) (hx : x.column ∈ S) (hy : y.column ∉ S) : + ∃ z : M.Point J root, z.column ∈ frontier (M := M) (J := J) S ∧ dist x z ≤ dist x y := by + obtain ⟨p,_,hp⟩ := x.exists_shortest hJ y + obtain ⟨u,v,T,hT,hs,hu,hv,q,r,hqr⟩ := + p.crosses_set Sᶜ (by simpa only [Set.mem_compl_iff,not_not] using hx) hy x.height y.height + have huS : u ∈ S := by simpa only [Set.mem_compl_iff,not_not] using hu + let z : M.Point J root := ⟨u,T,hT,x.reachable.trans q.word.reachable⟩ + refine ⟨z,⟨huS,v,⟨T,hT,hs⟩,hv⟩,?_⟩ + have hd := x.distance_le z q + change dist x z ≤ q.length x.height T at hd + rw [hp] at hqr + linarith [r.length_nonneg T y.height] + +end PlanarL1.Columns.Model.Point + +namespace PlanarL1.Columns.Model.MainCell +open PlanarL1.Interpolation +open scoped NNReal +variable {n : ℕ} {M : Model n} {I J : Set ℝ} {root : Fin n} +variable (F : M.Field I 1) (hJI : J ⊆ I) +variable (R : Point.RadialTree (M := M) (J := J) (root := root)) (q : ℝ) +variable (C : Cell R q) + +noncomputable def namedReplacement (v : M.Point J root) + (α : Point.RadialTree.Noise (n := n)) (E β lo : ℝ) (x : M.Point J root) : NamedValue := + namedClip (fun z => let A := R.pasted (input F hJI R q C v) α z; ⟨A.name,A.value-4*E⟩) + (old F hJI) (fun z => Clipping.heightShield lo R.a (old F hJI v) β z.height) x + +lemma namedReplacement_value (v : M.Point J root) + (α : Point.RadialTree.Noise (n := n)) (E β lo : ℝ) (x : M.Point J root) : + (namedReplacement F hJI R q C v α E β lo x).value = + replacement F hJI R q C v α E β lo x := by + exact clippedNamed_value _ _ _ + +noncomputable def localClipAtom {k : ℕ} (A : R.Node k) (v : M.Point J root) + (α : Point.RadialTree.Noise (n := n)) (E β lo : ℝ) : ℕ → M.Point J root → ℝ := + clipAtom (fun i z => (R.listedAtom (input F hJI R q C v) α A R.lookback i z).value-4*E) + (old F hJI) (fun z => Clipping.heightShield lo R.a (old F hJI v) β z.height) + +lemma shield_lipschitz (v : M.Point J root) (β lo : ℝ) : + LipschitzWith (replacementConstant R) + (fun z : M.Point J root => Clipping.heightShield lo R.a (old F hJI v) β z.height) := by + apply LipschitzWith.of_dist_le_mul + intro x y + have ht := (Clipping.heightShield_lipschitz lo (old F hJI v) β R.width_pos).dist_le_mul x.height y.height + have hx := x.height_change_le y + change |x.height-y.height| ≤ dist x y at hx + change dist _ _ ≤ (replacementConstant R : ℝ)*dist x y + change dist _ _ ≤ (3/(9*R.a/100))*dist x.height y.height at ht + rw [Real.dist_eq] at ht + exact ht.trans ((mul_le_mul_of_nonneg_left hx (by positivity [R.width_pos])).trans + (mul_le_mul_of_nonneg_right (le_max_right (1:ℝ) (3/(9*R.a/100))) dist_nonneg)) + +lemma localClipAtom_lipschitz {k : ℕ} (A : R.Node k) (v : M.Point J root) + (α : Point.RadialTree.Noise (n := n)) (E β lo : ℝ) (i : ℕ) : + LipschitzWith (replacementConstant R) (localClipAtom F hJI R q C A v α E β lo i) := by + apply clipAtom_lipschitz + · intro i + apply LipschitzWith.weaken (K := 1) _ (le_max_left _ _) + apply LipschitzWith.of_dist_le_mul + intro x y + simpa only [Real.dist_eq,sub_sub_sub_cancel_right] using + (R.listedAtom_lipschitz (input F hJI R q C v) α A R.lookback i).dist_le_mul x y + · exact (old_lipschitz F hJI R).weaken (le_max_left _ _) + · exact shield_lipschitz F hJI R v β lo + + +lemma localClipPair_probability_lt {k : ℕ} (A : R.Node k) (v x : M.Point J root) + (E lo B : ℝ) (hB : 0 < B) (cap m : ℕ) (hk : k < cap) (hm : 0 < m) + (i j : ℕ) (hi : i ∈ clipNames (R.recentNames A R.lookback)) + (hj : j ∈ clipNames (R.recentNames A R.lookback)) (hij : i < j) + {t : ℝ} (ht : 0 ≤ t) : + FiniteRandom.prob (fun ω : Point.RadialTree.GridSample (n := n) cap m × Fin (m+1) => + |localClipAtom F hJI R q C A v (R.gridNoise cap m ω.1) E (B/m*ω.2.val) lo i x- + localClipAtom F hJI R q C A v (R.gridNoise cap m ω.1) E (B/m*ω.2.val) lo j x| ≤ t) ≤ + (2*t+R.q/m)/R.q + (2*t+B/m)/B := by + have hpos₁ : 0 ≤ (2*t+R.q/m)/R.q := by positivity [R.q_pos] + have hpos₂ : 0 ≤ (2*t+B/m)/B := by positivity + by_cases hjlow : j < 2 + · have hi0 : i = 0 := by omega + have hj1 : j = 1 := by omega + subst i; subst j + apply FiniteRandom.prob_prod_bound + intro ω + let c := Clipping.heightShield lo R.a (old F hJI v) 0 x.height-old F hJI x + apply (FiniteRandom.prob_mono (fun r h => ?_)).trans + ((FiniteRandom.grid_probability m hm hB ht c).trans (le_add_of_nonneg_left hpos₁)) + have he : c+B/m*r.val = + localClipAtom F hJI R q C A v (R.gridNoise cap m ω) E (B/m*r.val) lo 1 x- + localClipAtom F hJI R q C A v (R.gridNoise cap m ω) E (B/m*r.val) lo 0 x := by + simp only [localClipAtom,clipAtom,reduceCtorEq,ite_true,ite_false,c,Clipping.heightShield] + ring + rw [he,abs_sub_comm] + exact h + · have hj2 : 2 ≤ j := by omega + have hj0 : j ≠ 0 := by omega + have hj1 : j ≠ 1 := by omega + have hjS : j-2 ∈ R.recentNames A R.lookback := by + rcases mem_clipNames.mp hj with h | h | h + · omega + · omega + · exact h.2 + apply FiniteRandom.prob_prod_bound_left + intro r + by_cases hi2 : 2 ≤ i + · have hi0 : i ≠ 0 := by omega + have hi1 : i ≠ 1 := by omega + have hiS : i-2 ∈ R.recentNames A R.lookback := by + rcases mem_clipNames.mp hi with h | h | h + · omega + · omega + · exact h.2 + have hp := R.listedPair_probability (input F hJI R q C v) A R.lookback (i-2) (j-2) + hiS hjS (by omega) x cap m hk hm ht + apply (FiniteRandom.prob_mono (fun ω h => ?_)).trans + (hp.trans (le_add_of_nonneg_right hpos₂)) + simpa only [localClipAtom,clipAtom,ite_eq_right hi0,ite_eq_right hi1,ite_eq_right hj0,ite_eq_right hj1, + sub_sub_sub_cancel_right] using h + · let c := if i = 0 then old F hJI x else Clipping.heightShield lo R.a (old F hJI v) (B/m*r.val) x.height + have hc (ω : Point.RadialTree.GridSample (n := n) cap m) : + localClipAtom F hJI R q C A v (R.gridNoise cap m ω) E (B/m*r.val) lo i x = c := by + by_cases hi0 : i = 0 + · simp only [localClipAtom,clipAtom,ite_eq_left hi0,c] + · have hi1 : i = 1 := by omega + simp only [localClipAtom,clipAtom,ite_eq_right hi0,ite_eq_left hi1,c] + have hp := R.listedConstant_probability (input F hJI R q C v) A R.lookback (j-2) + hjS x (c+4*E) cap m hk hm ht + apply (FiniteRandom.prob_mono (fun ω h => ?_)).trans + (hp.trans (le_add_of_nonneg_right hpos₂)) + rw [hc] at h + have he : (R.listedAtom (input F hJI R q C v) (R.gridNoise cap m ω) A R.lookback (j-2) x).value-(c+4*E) = + localClipAtom F hJI R q C A v (R.gridNoise cap m ω) E (B/m*r.val) lo j x-c := by + simp only [localClipAtom,clipAtom,ite_eq_right hj0,ite_eq_right hj1] + ring + rw [he,abs_sub_comm] + exact h + +lemma localClipPair_probability {k : ℕ} (A : R.Node k) (v x : M.Point J root) + (E lo B : ℝ) (hB : 0 < B) (cap m : ℕ) (hk : k < cap) (hm : 0 < m) + (i j : ℕ) (hi : i ∈ clipNames (R.recentNames A R.lookback)) + (hj : j ∈ clipNames (R.recentNames A R.lookback)) (hij : i ≠ j) + {t : ℝ} (ht : 0 ≤ t) : + FiniteRandom.prob (fun ω : Point.RadialTree.GridSample (n := n) cap m × Fin (m+1) => + |localClipAtom F hJI R q C A v (R.gridNoise cap m ω.1) E (B/m*ω.2.val) lo i x- + localClipAtom F hJI R q C A v (R.gridNoise cap m ω.1) E (B/m*ω.2.val) lo j x| ≤ t) ≤ + (2*t+R.q/m)/R.q + (2*t+B/m)/B := by + rcases lt_or_gt_of_ne hij with hij | hji + · exact localClipPair_probability_lt F hJI R q C A v x E lo B hB cap m hk hm i j hi hj hij ht + · simpa only [abs_sub_comm] using + localClipPair_probability_lt F hJI R q C A v x E lo B hB cap m hk hm j i hj hi hji ht + + +/-- The main clipping part of chart persistence. This is +for the literal interpolated, shifted, height-clipped proposal, including the +old field's retaining branch and inherited names through interpolation layers. -/ +lemma namedReplacement_probability (hJ : IsCompact J) (v x : M.Point J root) + (E lo B : ℝ) (hB : 0 < B) {ρ : ℝ} (hρ : 0 ≤ ρ) (hs : ρ ≤ R.radius) + (m : ℕ) (hm : 0 < m) : + FiniteRandom.prob (fun ω : Point.RadialTree.GridSample (n := n) R.depthCap m × Fin (m+1) => + ∃ z : M.Point J root, dist x z ≤ ρ ∧ + (namedReplacement F hJI R q C v (R.gridNoise R.depthCap m ω.1) E (B/m*ω.2.val) lo z).name ≠ + (namedReplacement F hJI R q C v (R.gridNoise R.depthCap m ω.1) E (B/m*ω.2.val) lo x).name) ≤ + (6*(R.lookback+1)+2 : ℕ)^2 * + ((4*(replacementConstant R : ℝ)*ρ+R.q/m)/R.q + + (4*(replacementConstant R : ℝ)*ρ+B/m)/B) := by + classical + obtain ⟨k,A,hlo,heq⟩ := R.common_formula x hρ hs + have hk : k < R.depthCap := + (R.depth_le_layerDepth x (hlo x (by simpa using hρ))).trans_lt (R.layerDepth_lt_cap x) + have hlist (ω : Point.RadialTree.GridSample (n := n) R.depthCap m × Fin (m+1)) + (z : M.Point J root) (hz : dist x z ≤ ρ) : + (namedReplacement F hJI R q C v (R.gridNoise R.depthCap m ω.1) E (B/m*ω.2.val) lo z).name ∈ + clipNames (R.recentNames A R.lookback) ∧ + (namedReplacement F hJI R q C v (R.gridNoise R.depthCap m ω.1) E (B/m*ω.2.val) lo z).value = + localClipAtom F hJI R q C A v (R.gridNoise R.depthCap m ω.1) E (B/m*ω.2.val) lo + (namedReplacement F hJI R q C v (R.gridNoise R.depthCap m ω.1) E (B/m*ω.2.val) lo z).name z := by + let p := input F hJI R q C v + let α := R.gridNoise R.depthCap m ω.1 + have hα := R.gridNoise_bounds R.depthCap m hm ω.1 + have hp := input_lipschitz F hJI R q C hJ v + have ha : |(R.formula p α k A z).value-p z| ≤ 6*R.δ := by + rw [← heq p α hα z hz] + exact R.pasted_accuracy hp hα z + have hn : (R.pasted p α z).name ∈ R.recentNames A R.lookback := by + rw [heq p α hα z hz] + exact R.formula_name_recent hp hα k A z (hlo z hz) ha + have hv : R.pasted p α z = R.listedAtom p α A R.lookback (R.pasted p α z).name z := by + rw [heq p α hα z hz] + exact R.formula_eq_listed hp hα k A z (hlo z hz) ha + apply namedClip_list + (fun z => ⟨(R.pasted p α z).name,(R.pasted p α z).value-4*E⟩) + (fun i z => (R.listedAtom p α A R.lookback i z).value-4*E) + (old F hJI) (fun z => Clipping.heightShield lo R.a (old F hJI v) (B/m*ω.2.val) z.height) + (R.recentNames A R.lookback) z hn + exact congrArg (fun Z : NamedValue => Z.value-4*E) hv + let b : ℝ := (4*(replacementConstant R : ℝ)*ρ+R.q/m)/R.q + + (4*(replacementConstant R : ℝ)*ρ+B/m)/B + have hb : 0 ≤ b := by dsimp [b]; positivity [R.q_pos] + have hF (ω : Point.RadialTree.GridSample (n := n) R.depthCap m × Fin (m+1)) : + LipschitzWith (replacementConstant R) + (fun z => (namedReplacement F hJI R q C v (R.gridNoise R.depthCap m ω.1) E (B/m*ω.2.val) lo z).value) := by + simpa only [namedReplacement_value] using + replacement_lipschitz F hJI R q C v (R.gridNoise_bounds _ _ hm ω.1) E (B/m*ω.2.val) lo + have hp := selection_probability + (fun ω : Point.RadialTree.GridSample (n := n) R.depthCap m × Fin (m+1) => + namedReplacement F hJI R q C v (R.gridNoise R.depthCap m ω.1) E (B/m*ω.2.val) lo) + (fun ω => localClipAtom F hJI R q C A v (R.gridNoise R.depthCap m ω.1) E (B/m*ω.2.val) lo) + (clipNames (R.recentNames A R.lookback)) hF + (fun ω i _ => localClipAtom_lipschitz F hJI R q C A v _ E _ lo i) x hρ hb hlist + (fun i hi j hj hij => by + simpa only [show 2*(2*(replacementConstant R : ℝ)*ρ) = 4*(replacementConstant R : ℝ)*ρ by ring] using + localClipPair_probability F hJI R q C A v x E lo B hB R.depthCap m hk hm i j hi hj hij + (t := 2*(replacementConstant R : ℝ)*ρ) (by positivity)) + refine hp.trans ?_ + apply mul_le_mul_of_nonneg_right _ hb + apply pow_le_pow_left₀ (Nat.cast_nonneg _) + exact_mod_cast (clipNames_card (R.recentNames A R.lookback)).trans + (Nat.add_le_add_right (R.recentNames_card A R.lookback) 2) + + +lemma namedReplacement_near_frontier (hJ : IsCompact J) (v x z : M.Point J root) + {α : Point.RadialTree.Noise (n := n)} (hα : R.NoiseBounds α) + {E : ℝ} (hE : 0 ≤ E) (hδ : R.δ = E/8) (β lo : ℝ) + (hz : z ∈ boundary R q C) (hd : 2*dist x z < 3*E) : + namedReplacement F hJI R q C v α E β lo x = ⟨0,old F hJI x⟩ := by + apply clippedNamed_retains + change proposal F hJI R q C v α E x < old F hJI x + have hm := frontier_margin F hJI R q C hJ v hα hE hδ hz + have hxz := (proposal_lipschitz F hJI R q C v hα E).dist_le_mul x z + have hs := (old_lipschitz F hJI R).dist_le_mul z x + simp only [Real.dist_eq,NNReal.coe_one,one_mul] at hxz hs + rw [dist_comm z x] at hs + have hp := (abs_le.mp hxz).2 + have ho := (abs_le.mp hs).2 + linarith + +/-- Crossing a main-cell boundary causes no identifier loss at all. This is +exactly why no radial padding error proportional to the band width is needed +in the source persistence bound. -/ +lemma namedReplacement_retained_on_touched_ball (hJ : IsCompact J) + (v x : M.Point J root) {ρ : ℝ} {α : Point.RadialTree.Noise (n := n)} + (hα : R.NoiseBounds α) {E : ℝ} (hE : 0 ≤ E) (hδ : R.δ = E/8) + (β lo : ℝ) (hρ : 4*ρ < 3*E) + (hex : ∃ y : M.Point J root, dist x y ≤ ρ ∧ y.column ∉ ColumnOrder.componentColumns C) : + ∀ w : M.Point J root, dist x w ≤ ρ → w.column ∈ ColumnOrder.componentColumns C → + namedReplacement F hJI R q C v α E β lo w = ⟨0,old F hJI w⟩ := by + intro w hw hwC + obtain ⟨y,hy,hyC⟩ := hex + obtain ⟨z,hz,hd⟩ := Point.near_frontier_of_not_mem R.closed_band + (ColumnOrder.componentColumns C) w y hwC hyC + apply namedReplacement_near_frontier F hJI R q C hJ v w z hα hE hδ β lo hz + have ht := dist_triangle w x y + rw [dist_comm w x] at ht + linarith + +end PlanarL1.Columns.Model.MainCell + + + +end + +section + +namespace PlanarL1.Columns.Model.MainCell +open PlanarL1.Interpolation +open scoped NNReal +variable {n : ℕ} {M : Model n} {I J : Set ℝ} {root : Fin n} +variable (F : M.Field I 1) (hJI : J ⊆ I) +variable (R : Point.RadialTree (M := M) (J := J) (root := root)) (q : ℝ) +variable (C : Cell R q) + +lemma namedReplacement_cases (v : M.Point J root) + (α : Point.RadialTree.Noise (n := n)) (E β lo : ℝ) (x : M.Point J root) : + (namedReplacement F hJI R q C v α E β lo x = ⟨0,old F hJI x⟩) ∨ + (namedReplacement F hJI R q C v α E β lo x = + ⟨1,Clipping.heightShield lo R.a (old F hJI v) β x.height⟩) ∨ + (namedReplacement F hJI R q C v α E β lo x = + ⟨(R.pasted (input F hJI R q C v) α x).name+2, + (R.pasted (input F hJI R q C v) α x).value-4*E⟩) := by + rcases clippedNamed_mem ⟨0,old F hJI x⟩ + ⟨(R.pasted (input F hJI R q C v) α x).name+2, + (R.pasted (input F hJI R q C v) α x).value-4*E⟩ + ⟨1,Clipping.heightShield lo R.a (old F hJI v) β x.height⟩ with h | h | h + · exact Or.inl h + · exact Or.inr (Or.inr h) + · exact Or.inr (Or.inl h) + +lemma namedReplacement_bound (v : M.Point J root) + (α : Point.RadialTree.Noise (n := n)) (E β lo : ℝ) (x : M.Point J root) : + (namedReplacement F hJI R q C v α E β lo x).name < 3*n*R.depthCap+2 := by + rcases namedReplacement_cases F hJI R q C v α E β lo x with h | h | h + · rw [h]; simp only; omega + · rw [h]; simp only; omega + · rw [h] + exact Nat.add_lt_add_right + ((R.formula_name_bound (input F hJI R q C v) α + (R.layerDepth x) (R.layerNode x) x).trans_le + (Nat.mul_le_mul_left (3*n) (R.layerDepth_lt_cap x))) 2 + +lemma namedReplacement_congr_zero (v x y : M.Point J root) + {α : Point.RadialTree.Noise (n := n)} (hα : R.NoiseBounds α) (E β lo : ℝ) + (hxy : dist x y=0) : + namedReplacement F hJI R q C v α E β lo x = + namedReplacement F hJI R q C v α E β lo y := by + have hp := R.pasted_congr_zero (input F hJI R q C v) hα x y hxy + have ho : old F hJI x=old F hJI y := by + apply dist_le_zero.mp + have ht := (old_lipschitz F hJI R).dist_le_mul x y + simpa only [hxy,mul_zero] using ht + have hh : x.height=y.height := by + have ht : |x.height-y.height| ≤ dist x y := x.height_change_le y + rw [hxy] at ht + exact sub_eq_zero.mp (abs_eq_zero.mp (le_antisymm ht (abs_nonneg _))) + simp only [namedReplacement,namedClip,hp,ho,hh] + + +/-- A local winner other than the old field receives exactly one new name. +The height-only branch is zero in the fresh block, and spatial atom a is a+1. -/ +noncomputable def choose (v : M.Point J root) + (α : Point.RadialTree.Noise (n := n)) (E β lo : ℝ) (i : Fin n) (H : ℝ) : + Option (Fin (3*n*R.depthCap+1)) := by + classical + exact if hd : H ∈ domain R q C i then + let t := namedReplacement F hJI R q C v α E β lo (cellPoint R q C i H hd) + if ht : t.name=0 then none else some ⟨t.name-1,by + have hb := namedReplacement_bound F hJI R q C v α E β lo (cellPoint R q C i H hd) + dsimp only [t] at ht ⊢ + omega⟩ + else none + +lemma choose_spec (v : M.Point J root) + (α : Point.RadialTree.Noise (n := n)) (E β lo : ℝ) (i : Fin n) (H : ℝ) + (a : Fin (3*n*R.depthCap+1)) (ha : choose F hJI R q C v α E β lo i H=some a) : + ∃ hd : H ∈ domain R q C i, + (namedReplacement F hJI R q C v α E β lo (cellPoint R q C i H hd)).name=a.val+1 := by + classical + by_cases hd : H ∈ domain R q C i + · simp only [choose,dite_eq_left hd] at ha + split_ifs at ha with ht + refine ⟨hd,?_⟩ + have he := congrArg Fin.val (Option.some.inj ha) + dsimp only at he ht + omega + · simp only [choose,dite_eq_right hd] at ha + cases ha + +lemma choose_none_inside (v : M.Point J root) + (α : Point.RadialTree.Noise (n := n)) (E β lo : ℝ) (i : Fin n) (H : ℝ) + (hd : H ∈ domain R q C i) (hc : choose F hJI R q C v α E β lo i H=none) : + (namedReplacement F hJI R q C v α E β lo (cellPoint R q C i H hd)).name=0 := by + classical + by_contra hn + simp only [choose,dite_eq_left hd,dite_eq_right hn] at hc + cases hc + +lemma choose_none_outside (v : M.Point J root) + (α : Point.RadialTree.Noise (n := n)) (E β lo : ℝ) (i : Fin n) (H : ℝ) + (hd : H ∉ domain R q C i) : choose F hJI R q C v α E β lo i H=none := by + simp only [choose,dite_eq_right hd] + +lemma choose_none_frontier (hJ : IsCompact J) (v : M.Point J root) + {α : Point.RadialTree.Noise (n := n)} (hα : R.NoiseBounds α) + {E : ℝ} (hE : 0 by_cases hj : H ∈ domain R q C j + · have hd : dist (cellPoint R q C i H hi) (cellPoint R q C j H hj)=0 := by + apply le_antisymm _ dist_nonneg + have ht := (cellPoint R q C i H hi).dist_le_switch (cellPoint R q C j H hj) + ((mem_domain R q C).mp hi).2 hs + simpa only [cellPoint,sub_self,abs_zero,add_zero] using ht + have hn := namedReplacement_congr_zero F hJI R q C v + (cellPoint R q C i H hi) (cellPoint R q C j H hj) hα E β lo hd + simp only [choose,dite_eq_left hi,dite_eq_left hj] + simp only [hn] + · have hx := (mem_domain R q C).mp hi + have hn : j ∉ ColumnOrder.componentColumns C := by + intro h + exact hj ((mem_domain R q C).mpr ⟨h,hx.2⟩) + rw [choose_none_frontier F hJI R q C hJ v hα hE hδ β lo i H hi + ⟨hx.1,j,⟨H,hx.2,hs⟩,hn⟩,choose_none_outside F hJI R q C v α E β lo j H hj] + · have hx := (mem_domain R q C).mp hj + have hn : i ∉ ColumnOrder.componentColumns C := by + intro h + exact hi ((mem_domain R q C).mpr ⟨h,hx.2⟩) + have hs' : H ∈ M.heights j i := by rwa [M.symm] + rw [choose_none_outside F hJI R q C v α E β lo i H hi, + choose_none_frontier F hJI R q C hJ v hα hE hδ β lo j H hj + ⟨hx.1,i,⟨H,hx.2,hs'⟩,hn⟩] + · rw [choose_none_outside F hJI R q C v α E β lo i H hi, + choose_none_outside F hJI R q C v α E β lo j H hj] + +end PlanarL1.Columns.Model.MainCell + + + +end + +end OAI diff --git a/lean/OAI/Combinatorics/PlanarL1/MainFamily.lean b/lean/OAI/Combinatorics/PlanarL1/MainFamily.lean new file mode 100644 index 0000000000000000000000000000000000000000..29bd72ebc713a6fe1889e0e2449c04f15f9998a9 --- /dev/null +++ b/lean/OAI/Combinatorics/PlanarL1/MainFamily.lean @@ -0,0 +1,370 @@ +import OAI.Combinatorics.PlanarL1.BandTrees +import OAI.Combinatorics.PlanarL1.MainStep + +namespace OAI + + +section + +namespace PlanarL1.Columns.Model +open MeasureTheory +attribute [local instance] Classical.propDecidable +variable {k : ℕ} {M : Model (k+1)} {Ω : Type*} [MeasurableSpace Ω] {μ : Measure Ω} + +namespace MainFamily +open Parameters +variable (A : Ambient M) (S : OrdinaryState M kappaA Ω μ) +variable (q L U : ℝ) + +noncomputable abbrev BandIndex := Tiling.processed a₁ q L U +noncomputable def lower (b : BandIndex q L U) : ℝ := q+(b.val:ℝ)*a₁ +abbrev BandComponent := Σ b : BandIndex q L U, BandTrees.Component M broad (lower q L U b) +noncomputable instance : Fintype (BandComponent (M := M) q L U) := Fintype.ofFinite _ + +abbrev CellIndex (phase : BandComponent (M := M) q L U → ℝ) := + Σ b : BandComponent (M := M) q L U, + BandTrees.MainIndex M broad (lower q L U b.1) b.2 (phase b) +noncomputable instance (phase : BandComponent (M := M) q L U → ℝ) : + Fintype (CellIndex q L U phase) := Fintype.ofFinite _ + +variable {q L U} (phase : BandComponent (M := M) q L U → ℝ) +variable (c : CellIndex q L U phase) +noncomputable abbrev tree := BandTrees.tree M broad (lower q L U c.1.1) c.1.2 +noncomputable def radial := phase c.1+(c.2.1.val:ℝ)*(1/1000) +noncomputable abbrev anchor := BandTrees.anchor M broad (lower q L U c.1.1) c.1.2 (phase c.1) c.2 +noncomputable def domain (i : Fin (k+1)) : Set ℝ := MainCell.domain (tree phase c) (radial phase c) c.2.2 i + +/-- Availability is the manuscript's entire closed radius-one neighborhood of +this full-column cell, not just tests at the finite original vertices. -/ +def neighborhood : Set (M.Point Set.univ A.root) := + {y | ∃ i H, H ∈ domain phase c i ∧ dist y (A.point i H)≤1} +def Available : Prop := ∃ index : Fin (S.count+1), + ∀ y ∈ neighborhood A phase c, S.name y.column y.height=index + +noncomputable def index (hc : Available A S phase c) : Fin (S.count+1) := hc.choose +lemma same_name (hc : Available A S phase c) (i : Fin (k+1)) (H : ℝ) + (hi : H ∈ domain phase c i) : S.name i H=index A S phase c hc := + hc.choose_spec (A.point i H) ⟨i,H,hi,by simp⟩ + +lemma sub_old (hc : Available A S phase c) : BandTrees.band broad (lower q L U c.1.1) ⊆ + (S.chart (index A S phase c hc)).band := by + intro H hH + have hi : H ∈ domain phase c (anchor phase c).column := + (MainCell.mem_domain _ _ _).mpr ⟨BandTrees.anchor_mem _ _ _ _ _ _,hH⟩ + have hh := S.height_in (anchor phase c).column H + rw [same_name A S phase c hc _ _ hi] at hh + exact hh + +/-- Every kept, available cell becomes an actual MainStep, including its old +chart and exact interpolation tree. All parameters are the fixed constants. -/ +noncomputable def step (hc : Available A S phase c) + (noise : Point.RadialTree.Noise (n := k+1)) (hn : (tree phase c).NoiseBounds noise) + (beta : ℝ) (hb : beta ≤ EA) : + OrdinaryState.MainStep S (BandTrees.band broad (lower q L U c.1.1)) + (BandTrees.root M broad (lower q L U c.1.1) c.1.2) where + index := index A S phase c hc + tree := tree phase c + phase := radial phase c + cell := c.2.2 + anchor := anchor phase c + anchor_mem := BandTrees.anchor_mem _ _ _ _ _ _ + lo := lower q L U c.1.1 + band_eq := rfl + thin := thinA + sub_old := sub_old A S phase c hc + same_name := same_name A S phase c hc + noise := noise + noise_bounds := hn + error := EA + error_pos := interpolationA.1 + delta_eq := rfl + shield_offset := beta + shield_bound := hb.trans (by norm_num [EA,epsilon]) + kappa_nonneg := verticalA.1 + vertical_bound := verticalA.2.1 + shield_strict := verticalA.2.2 + +lemma cell_column_component {i : Fin (k+1)} (hi : i ∈ ColumnOrder.componentColumns c.2.2) : + i ∈ c.1.2.supp := + BandTrees.reachable_mem M broad (lower q L U c.1.1) c.1.2 + (ColumnOrder.componentColumns_subset c.2.2 hi).choose + +lemma unique_in_band {c d : CellIndex q L U phase} (he : c.1.1=d.1.1) + {i : Fin (k+1)} {H : ℝ} (hi : H ∈ domain phase c i) (hj : H ∈ domain phase d i) : c=d := by + obtain ⟨⟨b,C⟩,K⟩ := c + obtain ⟨⟨b',D⟩,T⟩ := d + dsimp only at he + subst b' + have hci := cell_column_component phase (Sigma.mk ⟨b,C⟩ K) ((MainCell.mem_domain _ _ _).mp hi).1 + have hcj := cell_column_component phase (Sigma.mk ⟨b,D⟩ T) ((MainCell.mem_domain _ _ _).mp hj).1 + have hCD : C=D := ((SimpleGraph.ConnectedComponent.mem_supp_iff C i).mp hci).symm.trans + ((SimpleGraph.ConnectedComponent.mem_supp_iff D i).mp hcj) + subst D + have hKT : K=T := by + by_contra hn + exact Set.disjoint_left.mp (BandTrees.main_disjoint M broad (lower q L U b) C (phase ⟨b,C⟩) hn) + ((MainCell.mem_domain _ _ _).mp hi).1 ((MainCell.mem_domain _ _ _).mp hj).1 + subst T + rfl + +lemma domain_band {i : Fin (k+1)} {H : ℝ} (hi : H ∈ domain phase c i) : + H ∈ Tiling.band a₁ q c.1.1.val := by + obtain ⟨_,hl,hu⟩ := (MainCell.mem_domain _ _ _).mp hi + change q+(c.1.1.val:ℝ)*a₁≤H ∧ H≤q+((c.1.1.val:ℝ)+1)*a₁ + dsimp [BandTrees.band,lower,broad] at hl hu + constructor <;> linarith + +end MainFamily + +namespace OrdinaryState.MainStep +variable {κ : ℝ} {S : OrdinaryState M κ Ω μ} {J : Set ℝ} {root : Fin (k+1)} +variable (V : MainStep S J root) +lemma endpoint_old (ω : Ω × Bool) (i : Fin (k+1)) (H : ℝ) + (hi : H ∈ V.patch.domain i) (he : H=V.lo ∨ H=V.lo+V.tree.a) : + V.patch.active ω i H ↔ (S.lift.sets.activity ω).active i H := by + apply V.patch.boundary + change H ∈ frontier (MainCell.domain V.tree V.phase V.cell i) + have hc := ((MainCell.mem_domain V.tree V.phase V.cell).mp hi).1 + rw [MainCell.domain,ite_eq_left hc,V.band_eq,frontier_Icc (by linarith [V.tree.width_pos])] + simpa only [Set.mem_insert_iff,Set.mem_singleton_iff] using he +end OrdinaryState.MainStep +end PlanarL1.Columns.Model + +end + + + +section + +namespace PlanarL1.Columns.Model.MainFamily +open MeasureTheory Parameters +attribute [local instance] Classical.propDecidable +variable {k : ℕ} {M : Model (k+1)} {Ω : Type*} [MeasurableSpace Ω] {μ : Measure Ω} +variable (A : Ambient M) (S : OrdinaryState M kappaA Ω μ) +variable {q L U : ℝ} (phase : BandComponent (M := M) q L U → ℝ) + +abbrev CellSample (c : CellIndex q L U phase) (m : ℕ) := + Point.RadialTree.GridSample (n := k+1) (tree phase c).depthCap m × Fin (m+1) × Bool +abbrev Sample (m : ℕ) := ∀ c : CellIndex q L U phase, CellSample phase c m +noncomputable instance (m : ℕ) : Fintype (Sample phase m) := inferInstanceAs (Fintype (∀ _, _)) +instance (m : ℕ) : Nonempty (Sample phase m) := inferInstanceAs (Nonempty (∀ _, _)) + +variable {m : ℕ} (hm : 0 < m) (omega : Sample phase m) + +def kept (c : CellIndex q L U phase) : Prop := Available A S phase c ∧ (omega c).2.2=true +abbrev Kept := {c : CellIndex q L U phase // kept A S phase omega c} +noncomputable instance : Fintype (Kept A S phase omega) := Fintype.ofFinite _ + +include hm in +lemma shield_bound (c : CellIndex q L U phase) : EA/(m:ℝ)*((omega c).2.1.val:ℝ)≤EA := by + have hmR : (0:ℝ)< m := by exact_mod_cast hm + have hi : (((omega c).2.1.val):ℝ)≤ m := by exact_mod_cast (omega c).2.1.is_le + have hp : 0≤EA/m := div_nonneg (interpolationA.1.le) hmR.le + calc _ ≤ EA/m*m := mul_le_mul_of_nonneg_left hi hp + _ = EA := div_mul_cancel₀ _ hmR.ne' + +noncomputable def keptStep (c : Kept A S phase omega) := + step A S phase c.val c.property.1 + ((tree phase c.val).gridNoise (tree phase c.val).depthCap m (omega c.val).1) + ((tree phase c.val).gridNoise_bounds _ _ hm (omega c.val).1) + (EA/m*(omega c.val).2.1.val) (shield_bound phase hm omega c.val) + +lemma overlap {c d : Kept A S phase omega} (hne : c≠d) : + SetPatch.UnchangedOverlap (keptStep A S phase hm omega c).patch + (keptStep A S phase hm omega d).patch := by + intro w i H hi hj + have hi' : H ∈ domain phase c.val i := hi + have hj' : H ∈ domain phase d.val i := hj + have hbands : c.val.1.1≠d.val.1.1 := by + intro he + exact hne (Subtype.ext (unique_in_band phase he hi' hj')) + have hne' : c.val.1.1.val≠d.val.1.1.val := fun he => hbands (Subtype.ext he) + have hc := domain_band phase c.val hi' + have hd := domain_band phase d.val hj' + have hout : ∀ {e : Kept A S phase omega}, H ∈ (keptStep A S phase hm omega e).patch.domain i → + (H=lower q L U e.val.1.1 ∨ H=lower q L U e.val.1.1+a₁) → + ((keptStep A S phase hm omega e).patch.active w i H ↔ (S.lift.sets.activity w).active i H) := by + intro e he he' + exact (keptStep A S phase hm omega e).endpoint_old w i H he he' + rcases lt_or_gt_of_ne hne' with he | he + · obtain ⟨h1,h2⟩ := Tiling.overlap interpolationA.2.1 he hc hd + exact ⟨hout hi (Or.inr (by dsimp [lower]; linarith)),hout hj (Or.inl h2)⟩ + · obtain ⟨h1,h2⟩ := Tiling.overlap interpolationA.2.1 he hd hc + exact ⟨hout hi (Or.inl h2),hout hj (Or.inr (by dsimp [lower]; linarith))⟩ + +/-- The simultaneous main mode is now genuinely defined for every old state +and every finite sample. Its family contains exactly the available kept cells. -/ +noncomputable def batch : OrdinaryState.MainBatch S where + count := Fintype.card (Kept A S phase omega) + band a := BandTrees.band broad (lower q L U ((Fintype.equivFin (Kept A S phase omega)).symm a).val.1.1) + root a := BandTrees.root M broad + (lower q L U ((Fintype.equivFin (Kept A S phase omega)).symm a).val.1.1) + ((Fintype.equivFin (Kept A S phase omega)).symm a).val.1.2 + step a := keptStep A S phase hm omega ((Fintype.equivFin (Kept A S phase omega)).symm a) + overlap := by + apply List.pairwise_ofFn.mpr + intro a b hab + apply overlap A S phase hm omega + exact fun he => (ne_of_lt hab) ((Fintype.equivFin (Kept A S phase omega)).symm.injective he) + +noncomputable def result [SFinite μ] : OrdinaryState M kappaA (Ω × Bool) (μ.prod Threshold.fair) := + (batch A S phase hm omega).apply + +/-- Fresh offsets and cell coins are sampled as a finite product, after the +bands and radial origins; unavailable cells simply discard their sample. -/ +noncomputable def execution [SFinite μ] : + Execution (OrdinaryState M kappaA (Ω × Bool) (μ.prod Threshold.fair)) := + (Execution.uniform (α := Sample phase m)).bind (fun omega => .pure (result A S phase hm omega)) + +end PlanarL1.Columns.Model.MainFamily + +end + + +section + +namespace PlanarL1.Columns.Model.OrdinaryState.MainBatch +open MeasureTheory +attribute [local instance] Classical.propDecidable +variable {n : ℕ} {M : Model n} {κ : ℝ} {Ω : Type*} [MeasurableSpace Ω] {μ : Measure Ω} + {S : OrdinaryState M κ Ω μ} (B : MainBatch S) + +lemma point_description (i : Fin n) (H : ℝ) : + (∃ q : Fin B.count, ∀ ω, (B.sets.activity ω).active i H ↔ + ((B.step q).patch.apply.activity ω).active i H) ∨ + (∀ ω, (B.sets.activity ω).active i H ↔ (S.lift.sets.activity ω).active i H) := by + classical + by_cases h : ∃ q : Fin B.count, H ∈ (B.step q).patch.domain i + · obtain ⟨q,hq⟩ := h + exact Or.inl ⟨q,fun ω => SetPatch.batch_inside _ B.overlap + (List.mem_ofFn.mpr ⟨q,rfl⟩) ω i H hq⟩ + · right + intro ω + apply SetPatch.batch_old _ B.overlap ω i H + intro P hP + obtain ⟨q,rfl⟩ := List.mem_ofFn.mp hP + exact (B.step q).patch.unchanged (fun hh => h ⟨q,hh⟩) ω + +lemma apply_sets [SFinite μ] : B.apply.sets=B.sets := rfl + +lemma movement_integrable (i : Fin n) (H : ℝ) : + Integrable (fun ω => (B.sets.activity ω).indicator i H- + (S.lift.sets.activity ω).indicator i H) (μ.prod Threshold.fair) := by + rcases B.point_description i H with ⟨q,hq⟩ | h + · have he (ω) : (B.sets.activity ω).indicator i H=((B.step q).patch.apply.activity ω).indicator i H := by + simp only [Activity.indicator,hq ω] + simp_rw [he] + exact (B.step q).movement_integrable i H + · have he (ω) : (B.sets.activity ω).indicator i H=(S.lift.sets.activity ω).indicator i H := by + simp only [Activity.indicator,h ω] + simp only [he,sub_self] + exact integrable_zero _ _ _ + +/-- The number of simultaneous cells never enters the movement bound. -/ +lemma movement_bound (hκ : 0≤κ) (i : Fin n) (H : ℝ) : + (∫ ω, |(B.sets.activity ω).indicator i H- + (S.lift.sets.activity ω).indicator i H| ∂(μ.prod Threshold.fair)) ≤ κ*(1+(1:ℝ)/100) := by + rcases B.point_description i H with ⟨q,hq⟩ | h + · have he (ω) : (B.sets.activity ω).indicator i H=((B.step q).patch.apply.activity ω).indicator i H := by + simp only [Activity.indicator,hq ω] + simp_rw [he] + exact (B.step q).movement_bound i H + · have he (ω) : (B.sets.activity ω).indicator i H=(S.lift.sets.activity ω).indicator i H := by + simp only [Activity.indicator,h ω] + simp only [he,sub_self,abs_zero,integral_zero] + positivity + +end PlanarL1.Columns.Model.OrdinaryState.MainBatch + +end + + + +section + +namespace PlanarL1.Columns.Model +open MeasureTheory +attribute [local instance] Classical.propDecidable +variable {k : ℕ} {M : Model (k+1)} +namespace BandTrees +variable (P : Parameters.Interpolation) (lo : ℝ) (C : Component M P lo) +lemma main_cover (phase : ℝ) {i : Fin (k+1)} (hi : i ∈ C.supp) : + ∃ c : MainIndex M P lo C phase, i ∈ ColumnOrder.componentColumns c.2 := by + let x := point M P lo C ⟨i,hi⟩ + let l := Tiling.index (1/1000) phase (dist (base M P lo C) x) + have hl : l ∈ levels M P lo C phase (1/1000) := + Finset.mem_image.mpr ⟨⟨i,hi⟩,Finset.mem_univ _,rfl⟩ + have hx : i ∈ (base M P lo C).layer (middle P lo) (middle_mem P lo) + (phase+(l:ℝ)*(1/1000)) (1/1000) := by + refine ⟨x.reachable,?_,?_⟩ + · have h := Int.floor_le ((dist (base M P lo C) x-phase)/(1/1000)) + have hh := (le_div_iff₀ (by norm_num : (0:ℝ)<1/1000)).mp h + change phase+(l:ℝ)*(1/1000)≤dist (base M P lo C) x + dsimp [l,Tiling.index] + linarith + · have h := Int.lt_floor_add_one ((dist (base M P lo C) x-phase)/(1/1000)) + have hh := (div_lt_iff₀ (by norm_num : (0:ℝ)<1/1000)).mp h + change dist (base M P lo C) x dsimp [Tiling.band] at hHb <;> linarith [hHb.1,hHb.2] + +lemma ambient_dist_le {J : Set ℝ} {root : Fin (k+1)} (x y : M.Point J root) : + dist (A.point x.column x.height) (A.point y.column y.height)≤dist x y := by + have h := x.dist_widen_le y (Set.subset_univ J) + have he := Point.dist_coordinates (x.widen (Set.subset_univ J)) (y.widen (Set.subset_univ J)) + (A.point x.column x.height) (A.point y.column y.height) rfl rfl rfl rfl + exact he ▸ h + +lemma cell_diameter (c : CellIndex q L U phase) {i j : Fin (k+1)} {H T : ℝ} + (hi : H ∈ domain phase c i) (hj : T ∈ domain phase c j) : + dist (A.point i H) (A.point j T)≤1/100 := by + let x := MainCell.cellPoint (tree phase c) (radial phase c) c.2.2 i H hi + let y := MainCell.cellPoint (tree phase c) (radial phase c) c.2.2 j T hj + have hh := (tree phase c).base.radial_cell_diameter (tree phase c).closed_band + (tree phase c).base.inBand (tree phase c).width_pos thinA (tree phase c).half_width c.2.2 x y + ((MainCell.mem_domain _ _ _).mp hi).1 ((MainCell.mem_domain _ _ _).mp hj).1 + exact (ambient_dist_le A x y).trans (by simpa only [show (10:ℝ)*(1/1000)=1/100 by norm_num] using hh) + +/-- The full-neighborhood availability test is derived from a common old +radius-20 ball; it is not an extra hypothesis on the random execution. -/ +lemma available_of_ball (c : CellIndex q L U phase) (x : M.Point Set.univ A.root) + (hx : x.height ∈ domain phase c x.column) + (hname : ∃ a : Fin (S.count+1), ∀ y : M.Point Set.univ A.root, + dist x y≤20 → S.name y.column y.height=a) : Available A S phase c := by + obtain ⟨a,ha⟩ := hname + refine ⟨a,fun y hy => ha y ?_⟩ + obtain ⟨i,H,hi,hd⟩ := hy + have hxpoint : A.point x.column x.height=x := by cases x; rfl + have hc := cell_diameter A phase c hx hi + rw [hxpoint] at hc + have ht := dist_triangle x (A.point i H) y + rw [dist_comm (A.point i H) y] at ht + linarith + +end MainFamily +end PlanarL1.Columns.Model + +end + +end OAI diff --git a/lean/OAI/Combinatorics/PlanarL1/MainGain.lean b/lean/OAI/Combinatorics/PlanarL1/MainGain.lean new file mode 100644 index 0000000000000000000000000000000000000000..bc9013b408c93c580f487d51fe6e3f4f74873f81 --- /dev/null +++ b/lean/OAI/Combinatorics/PlanarL1/MainGain.lean @@ -0,0 +1,357 @@ +import OAI.Combinatorics.PlanarL1.PairSelection + +namespace OAI + + +section + +namespace PlanarL1.Columns.Model.MainFamily +open Parameters MeasureTheory +attribute [local instance] Classical.propDecidable +variable {k : ℕ} {M : Model (k+1)} {Ω : Type*} [MeasurableSpace Ω] {μ : Measure Ω} +variable (A : Ambient M) (S : OrdinaryState M kappaA Ω μ) +variable {q L U : ℝ} (phase : BandComponent (M := M) q L U → ℝ) + +lemma unique_at_padded {c d : CellIndex q L U phase} {i : Fin (k+1)} {H : ℝ} + (hp : Tiling.Padded a₁ q H (a₁/10)) + (hc : H ∈ domain phase c i) (hd : H ∈ domain phase d i) : c=d := by + apply unique_in_band phase _ hc hd + apply Subtype.ext + exact (Tiling.unique_band_of_padded interpolationA.2.1 (by norm_num [a₁]) hp + (domain_band phase c hc)).trans + (Tiling.unique_band_of_padded interpolationA.2.1 (by norm_num [a₁]) hp + (domain_band phase d hd)).symm + +variable {m : ℕ} (hm : 0 < m) (omega : Sample phase m) +lemma batch_inside_kept (c : Kept A S phase omega) (w : Ω × Bool) + (i : Fin (k+1)) (H : ℝ) (hH : H ∈ domain phase c.val i) : + ((batch A S phase hm omega).sets.activity w).active i H ↔ + ((keptStep A S phase hm omega c).patch.apply.activity w).active i H := by + apply SetPatch.batch_inside _ (batch A S phase hm omega).overlap + · apply List.mem_ofFn.mpr + let e := @Fintype.equivFin (Kept A S phase omega) (instFintypeKept A S phase omega) + refine ⟨e c, ?_⟩ + exact congrArg (fun d => (keptStep A S phase hm omega d).patch) (e.symm_apply_apply c) + · exact hH + +lemma batch_old_suppressed (c : CellIndex q L U phase) (w : Ω × Bool) + (i : Fin (k+1)) (H : ℝ) (hH : H ∈ domain phase c i) + (hp : Tiling.Padded a₁ q H (a₁/10)) (hoff : (omega c).2.2=false) : + ((batch A S phase hm omega).sets.activity w).active i H ↔ + (S.lift.sets.activity w).active i H := by + apply SetPatch.batch_old _ (batch A S phase hm omega).overlap + intro P hP + obtain ⟨d,rfl⟩ := List.mem_ofFn.mp hP + apply ((batch A S phase hm omega).step d).patch.unchanged + intro hd + let d' : Kept A S phase omega := (Fintype.equivFin _).symm d + have hd' : H ∈ domain phase d'.val i := hd + have he : c=d'.val := unique_at_padded phase hp hH hd' + have ht := d'.property.2 + rw [←he,hoff] at ht + cases ht + +end PlanarL1.Columns.Model.MainFamily + +end + + + +section + +namespace PlanarL1.FiniteRandom +attribute [local instance] Classical.propDecidable +lemma prob_second {Ω Λ : Type*} [Fintype Ω] [Nonempty Ω] [Fintype Λ] + (P : Λ → Prop) : prob (fun z : Ω × Λ => P z.2)=prob P := by + rw [prob_prod] + simp only [Finset.sum_const,Finset.card_univ,nsmul_eq_mul] + exact mul_div_cancel_left₀ _ (by positivity) + +/-- Separate coins from all other finite independent local data, including +when the local data type depends on the cell/group. -/ +def coinProduct {I : Type*} (D : I → Type*) : + (∀ i, D i × Bool) ≃ (∀ i, D i) × (I → Bool) where + toFun f := (fun i => (f i).1,fun i => (f i).2) + invFun f i := (f.1 i,f.2 i) + left_inv f := by funext i; rfl + right_inv f := by cases f; rfl +lemma prob_coinProduct {I : Type*} [Fintype I] (D : I → Type*) + [∀ i, Fintype (D i)] [∀ i, Nonempty (D i)] (P : (I → Bool) → Prop) : + prob (fun f : ∀ i, D i × Bool => P (fun i => (f i).2))=prob P := by + rw [←prob_equiv (coinProduct D).symm] + exact prob_second P +end PlanarL1.FiniteRandom + +namespace PlanarL1.Columns.Model.MainFamily +open Parameters FiniteRandom +attribute [local instance] Classical.propDecidable +variable {k : ℕ} {M : Model (k+1)} {q L U : ℝ} +variable (phase : BandComponent (M := M) q L U → ℝ) (m : ℕ) +abbrev Uncoined (c : CellIndex q L U phase) := + Point.RadialTree.GridSample (n := k+1) (tree phase c).depthCap m × Fin (m+1) +def restructure : Sample phase m ≃ (∀ c, Uncoined phase m c × Bool) where + toFun f c := (((f c).1,(f c).2.1),(f c).2.2) + invFun f c := ((f c).1.1,((f c).1.2,(f c).2)) + left_inv f := by funext c; rfl + right_inv f := by funext c; rfl +lemma prob_coins (P : (CellIndex q L U phase → Bool) → Prop) : + prob (fun omega : Sample phase m => P (fun c => (omega c).2.2))=prob P := by + let e := (restructure phase m).trans (coinProduct (Uncoined phase m)) + have he := prob_equiv e.symm (fun omega : Sample phase m => P (fun c => (omega c).2.2)) + change prob (fun f : (∀ c, Uncoined phase m c) × (CellIndex q L U phase → Bool) => P f.2)=_ at he + exact he.symm.trans (prob_second P) +lemma prob_keep_suppress (c d : CellIndex q L U phase) (hne : c≠d) : + prob (fun omega : Sample phase m => (omega c).2.2=true ∧ (omega d).2.2=false)=1/4 := by + apply (prob_coins phase m (fun f => f c=true ∧ f d=false)).trans + convert prob_two_coins c d hne true false using 1 + exact congrArg (fun F : Fintype (CellIndex q L U phase → Bool) => + @prob _ F (fun f => f c=true ∧ f d=false)) (Subsingleton.elim _ _) +end PlanarL1.Columns.Model.MainFamily + +end + + + +section + +namespace PlanarL1.Columns.Model.MainFamily +open Parameters MeasureTheory +attribute [local instance] Classical.propDecidable +variable {k : ℕ} {M : Model (k+1)} {Ω : Type*} [MeasurableSpace Ω] {μ : Measure Ω} +variable (A : Ambient M) (S : OrdinaryState M kappaA Ω μ) +variable {q L U : ℝ} (phase : BandComponent (M := M) q L U → ℝ) +variable {m : ℕ} (hm : 0 < m) (omega : Sample phase m) + +lemma batch_pair_kept_suppressed (c : Kept A S phase omega) (d : CellIndex q L U phase) + (ii jj : Fin (k+1)) (H T : ℝ) + (hx : H ∈ domain phase c.val ii) (hy : T ∈ domain phase d jj) + (hp : Tiling.Padded a₁ q T (a₁/10)) (hoff : (omega d).2.2=false) : + (∫ w, |((batch A S phase hm omega).sets.activity w).indicator ii H- + ((batch A S phase hm omega).sets.activity w).indicator jj T| ∂(μ.prod Threshold.fair)) = + (∫ w, |((keptStep A S phase hm omega c).patch.apply.activity w).indicator ii H- + ((keptStep A S phase hm omega c).patch.apply.activity w).indicator jj T| ∂(μ.prod Threshold.fair)) := by + have hout : T ∉ domain phase c.val jj := by + intro hc + have he := unique_at_padded phase hp hy hc + have ht := c.property.2 + rw [←he,hoff] at ht + cases ht + apply integral_congr_ae + filter_upwards [] with w + have heX := batch_inside_kept A S phase hm omega c w ii H hx + have heY := batch_old_suppressed A S phase hm omega d w jj T hy hp hoff + have hpY := (keptStep A S phase hm omega c).patch.unchanged hout w + simp only [Activity.indicator,heX,heY,hpY] + +lemma padded_height {c : CellIndex q L U phase} {i : Fin (k+1)} {H : ℝ} + (hx : H ∈ domain phase c i) (hp : Tiling.Padded a₁ q H (a₁/10)) : + lower q L U c.1.1+a₁/10 < H ∧ H < lower q L U c.1.1+a₁-a₁/10 := by + have he := Tiling.unique_band_of_padded interpolationA.2.1 (by norm_num [a₁]) hp + (domain_band phase c hx) + unfold Tiling.Padded at hp + rw [←he] at hp + change q+(c.1.1.val:ℝ)*a₁+a₁/10 < H ∧ H < q+(c.1.1.val:ℝ)*a₁+a₁-a₁/10 + constructor <;> linarith [hp.1,hp.2] + +lemma kept_shield (c : Kept A S phase omega) + (x : M.Point (BandTrees.band broad (lower q L U c.val.1.1)) + (BandTrees.root M broad (lower q L U c.val.1.1) c.val.1.2)) + (hx : x.height ∈ domain phase c.val x.column) + (hp : Tiling.Padded a₁ q x.height (a₁/10)) : + MainCell.old (keptStep A S phase hm omega c).comparison + (keptStep A S phase hm omega c).sub_old (keptStep A S phase hm omega c).anchor+2 ≤ + Clipping.heightShield (keptStep A S phase hm omega c).lo (keptStep A S phase hm omega c).tree.a + (MainCell.old (keptStep A S phase hm omega c).comparison + (keptStep A S phase hm omega c).sub_old (keptStep A S phase hm omega c).anchor) + (keptStep A S phase hm omega c).shield_offset x.height := by + have hpad := padded_height phase hx hp + have he := Clipping.heightShield_plateau (s := + MainCell.old (keptStep A S phase hm omega c).comparison + (keptStep A S phase hm omega c).sub_old (keptStep A S phase hm omega c).anchor) + (α := (keptStep A S phase hm omega c).shield_offset) + interpolationA.2.1 (lo := lower q L U c.val.1.1) (H := x.height) + (by linarith [hpad.1]) (by linarith [hpad.2]) + change _ ≤ Clipping.heightShield (lower q L U c.val.1.1) a₁ _ _ x.height + rw [he] + have hpos : 0 ≤ EA/(m:ℝ)*((omega c.val).2.1.val:ℝ) := + mul_nonneg (div_nonneg interpolationA.1.le (Nat.cast_nonneg _)) (Nat.cast_nonneg _) + change _ ≤ _+2+EA/(m:ℝ)*((omega c.val).2.1.val:ℝ) + linarith + +/-- A literal missing descent in an available padded cell produces the gain +in the *whole* simultaneous main update on the keep/suppress coin event. -/ +lemma no_descent_gain (c d : CellIndex q L U phase) (hc : Available A S phase c) + (x : M.Point (BandTrees.band broad (lower q L U c.1.1)) + (BandTrees.root M broad (lower q L U c.1.1) c.1.2)) + (ii : Fin (k+1)) (T : ℝ) + (hx : x.column ∈ ColumnOrder.componentColumns c.2.2) + (hy : T ∈ domain phase d ii) + (hpx : Tiling.Padded a₁ q x.height (a₁/10)) (hpy : Tiling.Padded a₁ q T (a₁/10)) + (hr : BandTrees.RadialInterior D (phase c.1) x) + (hn : S.name ii T=index A S phase c hc) + (hT : T ∈ (S.chart (index A S phase c hc)).band) + (hclose : |(S.chart (index A S phase c hc)).comparison.eval + (x.widen (sub_old A S phase c hc))- + (S.chart (index A S phase c hc)).comparison.value ii ⟨T,hT⟩| ≤ EA) + (hno : ¬Nonempty ((S.chart (index A S phase c hc)).comparison.BandDescent + (BandTrees.band broad (lower q L U c.1.1)) (x.widen (sub_old A S phase c hc)) epsilon)) + (hon : (omega c).2.2=true) (hoff : (omega d).2.2=false) : + kappaA*EA < (∫ w, |((batch A S phase hm omega).sets.activity w).indicator x.column x.height- + ((batch A S phase hm omega).sets.activity w).indicator ii T| ∂(μ.prod Threshold.fair)) := by + let ck : Kept A S phase omega := ⟨c,hc,hon⟩ + let V := keptStep A S phase hm omega ck + have hxi : x.height ∈ domain phase c x.column := (MainCell.mem_domain _ _ _).mpr ⟨hx,x.inBand⟩ + rw [batch_pair_kept_suppressed A S phase hm omega ck d _ _ _ _ hxi hy hpy hoff] + have hout : T ∉ domain phase c ii := by + intro hzc + have he := unique_at_padded phase hpy hy hzc + rw [he,hon] at hoff + cases hoff + have hr' : BandTrees.RadialInterior (1/1000) (phase c.1) x := by + norm_num [D] at hr ⊢ + exact hr + have hp := BandTrees.radialInterior_padding (by norm_num) (by norm_num [a₁]) x hr' c.2 hx + apply V.pair_separation_external x ii T hT hx hout hn (by norm_num [kappaA,a₁]) + (ε := epsilon) (by norm_num [epsilon]) (by norm_num [epsilon]) rfl rfl hclose + (kept_shield A S phase hm omega ck x hxi hpx) _ _ hno + · change radial phase c+1/100000+2*a₁ < BandTrees.radialValue x + norm_num [radial] at hp ⊢ + exact hp.1 + · change BandTrees.radialValue x < radial phase c+1/1000-1/100000-2*a₁ + norm_num [radial] at hp ⊢ + exact hp.2 + +end PlanarL1.Columns.Model.MainFamily + +end + + + +section + +namespace PlanarL1.Columns.Model.MainFamily +open Parameters MeasureTheory +attribute [local instance] Classical.propDecidable +variable {k : ℕ} {M : Model (k+1)} {Ω : Type*} [MeasurableSpace Ω] {μ : Measure Ω} +variable (A : Ambient M) (S : OrdinaryState M kappaA Ω μ) +variable {q L U : ℝ} (phase : BandComponent (M := M) q L U → ℝ) +variable {m : ℕ} (hm : 0 < m) + +lemma no_descent_probability (c d : CellIndex q L U phase) (hc : Available A S phase c) + (x : M.Point (BandTrees.band broad (lower q L U c.1.1)) + (BandTrees.root M broad (lower q L U c.1.1) c.1.2)) + (ii : Fin (k+1)) (T : ℝ) + (hx : x.column ∈ ColumnOrder.componentColumns c.2.2) + (hy : T ∈ domain phase d ii) + (hpx : Tiling.Padded a₁ q x.height (a₁/10)) (hpy : Tiling.Padded a₁ q T (a₁/10)) + (hr : BandTrees.RadialInterior D (phase c.1) x) + (hn : S.name ii T=index A S phase c hc) + (hT : T ∈ (S.chart (index A S phase c hc)).band) + (hclose : |(S.chart (index A S phase c hc)).comparison.eval + (x.widen (sub_old A S phase c hc))- + (S.chart (index A S phase c hc)).comparison.value ii ⟨T,hT⟩| ≤ EA) + (hno : ¬Nonempty ((S.chart (index A S phase c hc)).comparison.BandDescent + (BandTrees.band broad (lower q L U c.1.1)) (x.widen (sub_old A S phase c hc)) epsilon)) + (hne : c≠d) : + 1/4 ≤ FiniteRandom.prob (fun omega : Sample phase m => + kappaA*EA < (∫ w, |((batch A S phase hm omega).sets.activity w).indicator x.column x.height- + ((batch A S phase hm omega).sets.activity w).indicator ii T| ∂(μ.prod Threshold.fair))) := by + rw [←prob_keep_suppress phase m c d hne] + exact FiniteRandom.prob_mono (fun omega h => no_descent_gain A S phase hm omega c d hc x ii T + hx hy hpx hpy hr hn hT hclose hno h.1 h.2) + +end PlanarL1.Columns.Model.MainFamily + +end + + + +section + +namespace PlanarL1.Columns.Model.VertexBands +open Parameters MeasureTheory +variable {k : ℕ} {M : Model (k+1)} {V : Type*} +variable (A : Ambient M) (v : V → M.Point Set.univ A.root) +variable {L U : ℝ} (hv : ∀ x, (v x).height ∈ Set.Icc L U) +variable {q : ℝ} (phase : MainFamily.BandComponent (M := M) q L U → ℝ) +noncomputable def mainCell (x : V) : MainFamily.CellIndex q L U phase := + ⟨bandComponent A v L U hv q x, + (BandTrees.main_cover broad (lower A v L U hv q x) (component A v L U hv q x) + (phase (bandComponent A v L U hv q x)) (i := (v x).column) rfl).choose⟩ +lemma mainCell_column (x : V) : (v x).column ∈ ColumnOrder.componentColumns (mainCell A v hv phase x).2.2 := + (BandTrees.main_cover broad (lower A v L U hv q x) (component A v L U hv q x) + (phase (bandComponent A v L U hv q x)) (i := (v x).column) rfl).choose_spec +lemma mainCell_mem (x : V) : (v x).height∈MainFamily.domain phase (mainCell A v hv phase x) (v x).column := + (MainCell.mem_domain _ _ _).mpr ⟨mainCell_column A v hv phase x,height_mem A v L U hv q x⟩ +end PlanarL1.Columns.Model.VertexBands + +namespace PlanarL1.Columns.Model.PairGeometry +open Parameters MeasureTheory VertexTests VertexBands +attribute [local instance] Classical.propDecidable +attribute [local irreducible] FiniteRandom.prob +variable {k : ℕ} {M : Model (k+1)} {V Ω Ξ : Type*} +variable [MeasurableSpace Ω] [MeasurableSpace Ξ] {μ : Measure Ω} {ν : Measure Ξ} +variable (A : Ambient M) (SA : OrdinaryState M kappaA Ω μ) +variable (SB : BState M kappaB SecondaryGeometry.Group.lam Ξ ν) +variable (v : V → M.Point Set.univ A.root) +variable {L U : ℝ} (hv : ∀ x, (v x).height ∈ Set.Icc L U) +variable {q p : ℝ} {phaseD phaseG : MainFamily.BandComponent (M := M) q L U → ℝ} +variable {x y : V} (he : Eligible A SA SB v x y) +variable (hi : Interior A v (hv := hv) q p phaseD phaseG x) +variable (hj : Interior A v (hv := hv) q p phaseD phaseG y) +variable (hc : Cutoffs A SA SB v x y) (ha : 1≤dist (v x) (v y)) + +include he in +lemma main_available : MainFamily.Available A SA phaseD (mainCell A v hv phaseD x) := + MainFamily.available_of_ball5 A SA phaseD _ (v x) (mainCell_mem A v hv phaseD x) he.1 +lemma main_index : MainFamily.index A SA phaseD (mainCell A v hv phaseD x) (main_available A SA SB v hv he)=indexA A SA v x := + (MainFamily.same_name A SA phaseD _ (main_available A SA SB v hv he) _ _ (mainCell_mem A v hv phaseD x)).symm + +private lemma comparison_coordinates {D E : OrdinaryData M} (hDE : D=E) + {i j : Fin (k+1)} (hij : i=j) {H T : ℝ} (hHT : H=T) (hD : H∈D.band) (hE : T∈E.band) : + D.comparison.value i ⟨H,hD⟩=E.comparison.value j ⟨T,hE⟩ := by + subst E; subst j; subst T; rfl + +include hj hc ha in +lemma no_descent_probability {m : ℕ} (hm : 0 < m) + (hno : ¬Nonempty ((SA.chart (indexA A SA v x)).comparison.BandDescent + (BandTrees.band broad (lower A v L U hv q x)) + ((position A SA SB v hv he hi).point.widen (position A SA SB v hv he hi).subA) epsilon)) : + 1/4≤FiniteRandom.prob (fun omega : MainFamily.Sample phaseD m => + kappaA*EA < (MainFamily.batch A SA phaseD hm omega).sets.separation + (v x).column (v x).height (v y).column (v y).height) := by + let c := mainCell A v hv phaseD x + let d := mainCell A v hv phaseD y + let hav := main_available A SA SB v hv he (phaseD := phaseD) + have hidx := main_index A SA SB v hv he (phaseD := phaseD) + have hn : SA.name (v y).column (v y).height=MainFamily.index A SA phaseD c hav := + (he.namesA A SA SB v).trans hidx.symm + have hT : (v y).height∈(SA.chart (MainFamily.index A SA phaseD c hav)).band := by + rw [←hn]; exact SA.height_in _ _ + have hclose : |(SA.chart (MainFamily.index A SA phaseD c hav)).comparison.eval + ((point A v L U hv q x).widen (MainFamily.sub_old A SA phaseD c hav))- + (SA.chart (MainFamily.index A SA phaseD c hav)).comparison.value + (v y).column ⟨(v y).height,hT⟩|≤EA := by + have hx := comparison_coordinates (congrArg SA.chart hidx) (i := (v x).column) rfl + (H := (v x).height) rfl + (MainFamily.sub_old A SA phaseD c hav (height_mem A v L U hv q x)) (SA.height_in _ _) + have hy := comparison_coordinates (congrArg SA.chart (hidx.trans (he.namesA A SA SB v).symm)) + (i := (v y).column) rfl (H := (v y).height) rfl hT (SA.height_in _ _) + change |(SA.chart (MainFamily.index A SA phaseD c hav)).comparison.value (v x).column _- + (SA.chart (MainFamily.index A SA phaseD c hav)).comparison.value (v y).column _|≤EA + have hb : |(SA.chart (MainFamily.index A SA phaseD c hav)).comparison.value (v x).column ⟨(v x).height,MainFamily.sub_old A SA phaseD c hav (height_mem A v L U hv q x)⟩ - (SA.chart (MainFamily.index A SA phaseD c hav)).comparison.value (v y).column ⟨(v y).height,hT⟩| ≤ EA := by + rw [hx,hy] + exact hc.2.1.le + exact hb + apply MainFamily.no_descent_probability A SA phaseD hm c d hav (point A v L U hv q x) + (v y).column (v y).height (mainCell_column A v hv phaseD x) (mainCell_mem A v hv phaseD y) + hi.1 hj.1 hi.2.2.1 hn hT hclose _ + (MainFamily.distinct_cells A phaseD (v x) (v y) ha c d (mainCell_mem A v hv phaseD x) (mainCell_mem A v hv phaseD y)) + intro h + apply hno + exact OrdinaryData.descent_coordinates (congrArg SA.chart hidx) rfl _ _ h rfl rfl +end PlanarL1.Columns.Model.PairGeometry + +end + +end OAI diff --git a/lean/OAI/Combinatorics/PlanarL1/MainPersistence.lean b/lean/OAI/Combinatorics/PlanarL1/MainPersistence.lean new file mode 100644 index 0000000000000000000000000000000000000000..575eb1734ad948972640d82a060ede543f6f351e --- /dev/null +++ b/lean/OAI/Combinatorics/PlanarL1/MainPersistence.lean @@ -0,0 +1,451 @@ +import OAI.Combinatorics.PlanarL1.MainFamily + +namespace OAI + + +section + +namespace PlanarL1.Columns.Model +open MeasureTheory +attribute [local instance] Classical.propDecidable +variable {n : ℕ} {M : Model n} {Ω : Type*} [MeasurableSpace Ω] {μ : Measure Ω} + +namespace OrdinaryState.MainBatch +variable {κ : ℝ} {S : OrdinaryState M κ Ω μ} (B : MainBatch S) +lemma choose_eq {i j : Fin n} {H T : ℝ} + (he : ∀ q, (B.step q).choose i H=(B.step q).choose j T) : + B.choose i H=B.choose j T := by + have h : B.chosen i H=B.chosen j T := by + funext a + simp only [chosen,he a.1] + unfold choose + simp only [h] + +lemma name_eq [SFinite μ] {i j : Fin n} {H T : ℝ} + (hold : S.name i H=S.name j T) (he : B.choose i H=B.choose j T) : + B.apply.name i H=B.apply.name j T := by + dsimp only [apply,OrdinaryState.append,OrdinaryState.lift] + rw [he,hold] +end OrdinaryState.MainBatch + +namespace MainCell +variable {I J : Set ℝ} {root : Fin n} (F : M.Field I 1) (hJI : J ⊆ I) + (R : Point.RadialTree (M := M) (J := J) (root := root)) (q : ℝ) + (C : Cell R q) +lemma choose_eq_of_name (v : M.Point J root) + (α : Point.RadialTree.Noise (n := n)) (E β lo : ℝ) {i j : Fin n} {H T : ℝ} + (hi : H ∈ domain R q C i) (hj : T ∈ domain R q C j) + (hn : (namedReplacement F hJI R q C v α E β lo (cellPoint R q C i H hi)).name= + (namedReplacement F hJI R q C v α E β lo (cellPoint R q C j T hj)).name) : + choose F hJI R q C v α E β lo i H=choose F hJI R q C v α E β lo j T := by + simp only [choose,dite_eq_left hi,dite_eq_left hj] + simp only [hn] + +lemma choose_none_of_name (v : M.Point J root) + (α : Point.RadialTree.Noise (n := n)) (E β lo : ℝ) {i : Fin n} {H : ℝ} + (hi : H ∈ domain R q C i) + (hn : (namedReplacement F hJI R q C v α E β lo (cellPoint R q C i H hi)).name=0) : + choose F hJI R q C v α E β lo i H=none := by + simp only [choose,dite_eq_left hi,dite_eq_left hn] +end MainCell +end PlanarL1.Columns.Model + +end + + + +section + +namespace PlanarL1.Tiling +lemma near_band_unique {a q h t H : ℝ} (ha : 0 linarith +end PlanarL1.Tiling + +namespace PlanarL1.Columns.Model +attribute [local instance] Classical.propDecidable +variable {k : ℕ} {M : Model (k+1)} +namespace Point +lemma local_center {J : Set ℝ} {r s : Fin (k+1)} + (x y : M.Point Set.univ r) (y' : M.Point J s) + (hy : y'.column=y.column) (_hY : y'.height=y.height) {ρ : ℝ} (hρ : 0≤ρ) + (hJ : ∀ H, |H-x.height|≤ρ → H ∈ J) (hd : dist x y≤ρ) : + ∃ x' : M.Point J s, x'.column=x.column ∧ x'.height=x.height := by + obtain ⟨p,_,hp⟩ := x.exists_shortest isClosed_univ y + obtain ⟨q,_⟩ := p.restrict_of_length x.height y.height x.height ρ hJ (by simpa [hp] using hd) + have hxJ : x.height ∈ J := hJ _ (by simpa using hρ) + refine ⟨⟨x.column,x.height,hxJ,?_⟩,rfl,rfl⟩ + exact y'.reachable.trans (hy.symm ▸ q.word.reachable.symm) +end Point +namespace MainFamily +open Parameters +variable (A : Ambient M) {q L U : ℝ} + (phase : BandComponent (M := M) q L U → ℝ) + (x : M.Point Set.univ A.root) {ρ : ℝ} (hρ : 0≤ρ) + (hp : Tiling.Padded a₁ q x.height ρ) + +include hρ hp +lemma touched_band {c : CellIndex q L U phase} {y : M.Point Set.univ A.root} + (hy : dist x y≤ρ) (hc : y.height ∈ domain phase c y.column) : + c.1.1.val=Tiling.index a₁ q x.height := by + apply Tiling.near_band_unique interpolationA.2.1 hρ hp _ (domain_band phase c hc) + rw [abs_sub_comm] + exact (x.height_change_le y).trans hy + +lemma touched_envelope {c : CellIndex q L U phase} {y : M.Point Set.univ A.root} + (hy : dist x y≤ρ) (hc : y.height ∈ domain phase c y.column) : + ∀ H, |H-x.height|≤ρ → H ∈ BandTrees.band broad (lower q L U c.1.1) := by + intro H hH + have he := touched_band A phase x hρ hp hy hc + have hb := Tiling.near_mem_band interpolationA.2.1 hρ hp hH + rw [←he] at hb + change q+(c.1.1.val:ℝ)*a₁≤H ∧ H≤q+(c.1.1.val:ℝ)*a₁+a₁ + dsimp only [Tiling.band,Set.mem_Icc] at hb + constructor <;> linarith [hb.1,hb.2] + +lemma local_center {c : CellIndex q L U phase} {y : M.Point Set.univ A.root} + (hy : dist x y≤ρ) (hc : y.height ∈ domain phase c y.column) : + ∃ x' : M.Point (BandTrees.band broad (lower q L U c.1.1)) + (BandTrees.root M broad (lower q L U c.1.1) c.1.2), + x'.column=x.column ∧ x'.height=x.height := + Point.local_center x y (MainCell.cellPoint (tree phase c) (radial phase c) c.2.2 _ _ hc) + rfl rfl hρ (touched_envelope A phase x hρ hp hy hc) hy + +lemma local_ball {c : CellIndex q L U phase} + (x' : M.Point (BandTrees.band broad (lower q L U c.1.1)) + (BandTrees.root M broad (lower q L U c.1.1) c.1.2)) + (hx : x'.column=x.column) (hX : x'.height=x.height) + {y : M.Point Set.univ A.root} (hy : dist x y≤ρ) + (hc : c.1.1.val=Tiling.index a₁ q x.height) : + ∃ y' : M.Point (BandTrees.band broad (lower q L U c.1.1)) + (BandTrees.root M broad (lower q L U c.1.1) c.1.2), + y'.column=y.column ∧ y'.height=y.height ∧ dist x' y'=dist x y := by + apply Point.local_point x y x' hx hX isClosed_univ (Set.subset_univ _) _ hy + intro H hH + have hb := Tiling.near_mem_band interpolationA.2.1 hρ hp hH + rw [←hc] at hb + change q+(c.1.1.val:ℝ)*a₁≤H ∧ H≤q+(c.1.1.val:ℝ)*a₁+a₁ + dsimp only [Tiling.band,Set.mem_Icc] at hb + constructor <;> linarith [hb.1,hb.2] +end MainFamily +end PlanarL1.Columns.Model + +end + + + +section + +namespace PlanarL1.Columns.Model +open MeasureTheory +attribute [local instance] Classical.propDecidable +variable {k : ℕ} {M : Model (k+1)} +namespace Point +lemma eq_of_coordinates {J : Set ℝ} {r : Fin (k+1)} (x y : M.Point J r) + (hc : x.column=y.column) (hh : x.height=y.height) : x=y := by + cases x + cases y + cases hc + cases hh + rfl +end Point +namespace MainFamily +open Parameters +variable {Ω : Type*} [MeasurableSpace Ω] {μ : Measure Ω} +variable (A : Ambient M) (S : OrdinaryState M kappaA Ω μ) +variable {q L U : ℝ} (phase : BandComponent (M := M) q L U → ℝ) +variable {m : ℕ} (hm : 0 < m) (omega : Sample phase m) +variable (x : M.Point Set.univ A.root) {ρ : ℝ} (hρ : 0≤ρ) + (hp : Tiling.Padded a₁ q x.height ρ) (hsmall : 4*ρ<3*EA) + +include hρ hp hsmall +/-- An actual available main cell does not install an identifier anywhere in a +small padded ball if that ball has a column outside the cell. -/ +lemma choose_none_crossed (c : Kept A S phase omega) + (hex : ∃ y : M.Point Set.univ A.root, dist x y≤ρ ∧ + y.column ∉ ColumnOrder.componentColumns c.val.2.2) + (z : M.Point Set.univ A.root) (hz : dist x z≤ρ) : + (keptStep A S phase hm omega c).choose z.column z.height=none := by + let V := keptStep A S phase hm omega c + change MainCell.choose V.comparison V.sub_old V.tree V.phase V.cell V.anchor + V.noise V.error V.shield_offset V.lo z.column z.height=none + by_cases hd : z.height ∈ domain phase c.val z.column + · obtain ⟨x',hx,hX⟩ := local_center A phase x hρ hp hz hd + have hb := touched_band A phase x hρ hp hz hd + obtain ⟨w,hw,hW,hdw⟩ := local_ball A phase x hρ hp x' hx hX hz hb + have hw' : w=MainCell.cellPoint V.tree V.phase V.cell z.column z.height hd := + Point.eq_of_coordinates _ _ hw hW + obtain ⟨y,hy,hout⟩ := hex + obtain ⟨y',hy',hY,hdy⟩ := local_ball A phase x hρ hp x' hx hX hy hb + have hh := MainCell.namedReplacement_retained_on_touched_ball V.comparison V.sub_old + V.tree V.phase V.cell isCompact_Icc V.anchor x' V.noise_bounds + interpolationA.1.le (show V.tree.δ=EA/8 by rfl) V.shield_offset V.lo hsmall + ⟨y',by simpa only [hdy] using hy,by + change y'.column ∉ ColumnOrder.componentColumns c.val.2.2 + rwa [hy']⟩ + w (by simpa only [hdw] using hz) (by + rw [hw] + exact ((MainCell.mem_domain _ _ _).mp hd).1) + apply MainCell.choose_none_of_name V.comparison V.sub_old V.tree V.phase V.cell + V.anchor V.noise V.error V.shield_offset V.lo hd + rw [←hw'] + exact congrArg PlanarL1.Interpolation.NamedValue.name hh + · exact MainCell.choose_none_outside V.comparison V.sub_old V.tree V.phase V.cell + V.anchor V.noise V.error V.shield_offset V.lo _ _ hd + +/-- If two main cells are seen by the center ball, every cell's chosen name is +none on the ball. This also covers two representatives of the same quotient +point and arbitrarily many touched cells. -/ +lemma all_choices_none_crossed (c : CellIndex q L U phase) + (hc : x.height ∈ domain phase c x.column) + (hex : ∃ y : M.Point Set.univ A.root, dist x y≤ρ ∧ + y.column ∉ ColumnOrder.componentColumns c.2.2) + (z : M.Point Set.univ A.root) (hz : dist x z≤ρ) + (d : Kept A S phase omega) : + (keptStep A S phase hm omega d).choose z.column z.height=none := by + by_cases hd : z.height ∈ domain phase d.val z.column + · apply choose_none_crossed A S phase hm omega x hρ hp hsmall d _ z hz + by_cases he : c=d.val + · subst c + exact hex + · refine ⟨x,by simpa using hρ,?_⟩ + intro hx + have hb := touched_band A phase x hρ hp hz hd + have hcband := touched_band A phase x hρ hp (y := x) (by simpa using hρ) hc + have hband : c.1.1=d.val.1.1 := Subtype.ext (hcband.trans hb.symm) + have hxd : x.height ∈ domain phase d.val x.column := + (MainCell.mem_domain _ _ _).mpr ⟨hx,touched_envelope A phase x hρ hp hz hd + x.height (by simpa using hρ)⟩ + exact he (unique_in_band phase hband hc hxd) + · exact MainCell.choose_none_outside + (keptStep A S phase hm omega d).comparison (keptStep A S phase hm omega d).sub_old + (tree phase d.val) (radial phase d.val) d.val.2.2 (anchor phase d.val) + (keptStep A S phase hm omega d).noise EA (keptStep A S phase hm omega d).shield_offset + (lower q L U d.val.1.1) z.column z.height hd +end MainFamily +end PlanarL1.Columns.Model + +end + + + +section + +namespace PlanarL1.FiniteRandom +lemma prob_pi_eval_bound {I : Type*} {D : I → Type*} [Fintype I] [DecidableEq I] + [∀ i, Fintype (D i)] [∀ i, Nonempty (D i)] (i : I) (P : D i → Prop) + {b : ℝ} (h : prob P≤b) : prob (fun f : ∀ i, D i => P (f i))≤b := by + classical + let e := Equiv.piSplitAt i D + have he (u : D i × (∀ j : {j // j≠i}, D j.val)) : (e.symm u) i=u.1 := + congrArg Prod.fst (e.apply_symm_apply u) + rw [←prob_equiv e.symm] + apply prob_prod_bound_left + intro f + simpa only [he] using h +end PlanarL1.FiniteRandom + +end + + + +section + +namespace PlanarL1.Columns.Model.MainFamily +open MeasureTheory Parameters +attribute [local instance] Classical.propDecidable +variable {k : ℕ} {M : Model (k+1)} {Ω : Type*} [MeasurableSpace Ω] {μ : Measure Ω} +variable (A : Ambient M) (S : OrdinaryState M kappaA Ω μ) +variable {q L U : ℝ} (phase : BandComponent (M := M) q L U → ℝ) +variable {m : ℕ} (hm : 0 < m) (omega : Sample phase m) +variable (x : M.Point Set.univ A.root) {ρ : ℝ} (hρ : 0≤ρ) + (hp : Tiling.Padded a₁ q x.height ρ) (hsmall : 4*ρ<3*EA) + +noncomputable def sampleName (c : CellIndex q L U phase) (hc : Available A S phase c) + (w : Point.RadialTree.GridSample (n := k+1) (tree phase c).depthCap m × Fin (m+1)) + (z : M.Point (BandTrees.band broad (lower q L U c.1.1)) + (BandTrees.root M broad (lower q L U c.1.1) c.1.2)) : ℕ := + (MainCell.namedReplacement (S.chart (index A S phase c hc)).comparison + (sub_old A S phase c hc) (tree phase c) (radial phase c) c.2.2 (anchor phase c) + ((tree phase c).gridNoise (tree phase c).depthCap m w.1) EA (EA/m*w.2.val) + (lower q L U c.1.1) z).name + +include hρ hp in +lemma choose_none_other (c : CellIndex q L U phase) + (hfull : ∀ z : M.Point Set.univ A.root, dist x z≤ρ → z.height ∈ domain phase c z.column) + (d : Kept A S phase omega) (hne : d.val≠c) + (z : M.Point Set.univ A.root) (hz : dist x z≤ρ) : + (keptStep A S phase hm omega d).choose z.column z.height=none := by + apply MainCell.choose_none_outside + intro hd + have hd' : z.height ∈ domain phase d.val z.column := hd + have hb := touched_band A phase x hρ hp hz hd' + have hcband := touched_band A phase x hρ hp hz (hfull z hz) + exact hne (unique_in_band phase (Subtype.ext (hb.trans hcband.symm)) hd' (hfull z hz)) + +include hρ hp hsmall in +lemma result_name_eq [SFinite μ] (c : CellIndex q L U phase) + (hc : x.height ∈ domain phase c x.column) + (hcontrol : ∀ hav : Available A S phase c, + let x' := MainCell.cellPoint (tree phase c) (radial phase c) c.2.2 x.column x.height hc + ∀ z, dist x' z≤ρ → + sampleName A S phase c hav ((omega c).1,(omega c).2.1) z= + sampleName A S phase c hav ((omega c).1,(omega c).2.1) x') + (z : M.Point Set.univ A.root) (hz : dist x z≤ρ) + (hold : S.name z.column z.height=S.name x.column x.height) : + (result A S phase hm omega).name z.column z.height= + (result A S phase hm omega).name x.column x.height := by + apply OrdinaryState.MainBatch.name_eq _ hold + apply OrdinaryState.MainBatch.choose_eq + intro j + let d : Kept A S phase omega := (Fintype.equivFin (Kept A S phase omega)).symm j + change (keptStep A S phase hm omega d).choose z.column z.height= + (keptStep A S phase hm omega d).choose x.column x.height + by_cases hex : ∃ y : M.Point Set.univ A.root, dist x y≤ρ ∧ + y.column ∉ ColumnOrder.componentColumns c.2.2 + · rw [all_choices_none_crossed A S phase hm omega x hρ hp hsmall c hc hex z hz d, + all_choices_none_crossed A S phase hm omega x hρ hp hsmall c hc hex x (by simpa using hρ) d] + · have hfull (y : M.Point Set.univ A.root) (hy : dist x y≤ρ) : + y.height ∈ domain phase c y.column := by + apply (MainCell.mem_domain _ _ _).mpr + refine ⟨?_,?_⟩ + · by_contra hn + exact hex ⟨y,hy,hn⟩ + · apply touched_envelope A phase x hρ hp (by simpa using hρ) hc + rw [abs_sub_comm] + exact (x.height_change_le y).trans hy + by_cases he : d.val=c + · subst c + let V := keptStep A S phase hm omega d + have hdz := hfull z hz + apply MainCell.choose_eq_of_name V.comparison V.sub_old V.tree V.phase V.cell V.anchor + V.noise V.error V.shield_offset V.lo hdz hc + let x' := MainCell.cellPoint (tree phase d.val) (radial phase d.val) d.val.2.2 + x.column x.height hc + have hb := touched_band A phase x hρ hp (by simpa using hρ) hc + obtain ⟨z',hz',hZ,hd⟩ := local_ball A phase x hρ hp x' rfl rfl hz hb + have hd' : dist x' z'≤ρ := hd.le.trans hz + have hn := hcontrol d.property.1 z' hd' + have hzP : z'=MainCell.cellPoint (tree phase d.val) (radial phase d.val) d.val.2.2 + z.column z.height hdz := Point.eq_of_coordinates _ _ hz' hZ + rw [hzP] at hn + exact hn + · rw [choose_none_other A S phase hm omega x hρ hp c hfull d he z hz, + choose_none_other A S phase hm omega x hρ hp c hfull d he x (by simpa using hρ)] +end PlanarL1.Columns.Model.MainFamily + +end + + + +section + +namespace PlanarL1.Columns.Model.MainFamily +open MeasureTheory Parameters FiniteRandom +attribute [local instance] Classical.propDecidable +attribute [local irreducible] FiniteRandom.prob +variable {k : ℕ} {M : Model (k+1)} {Ω : Type*} [MeasurableSpace Ω] {μ : Measure Ω} +variable (A : Ambient M) (S : OrdinaryState M kappaA Ω μ) +variable {q L U : ℝ} (phase : BandComponent (M := M) q L U → ℝ) + +noncomputable def localLoss (c : CellIndex q L U phase) (ρ : ℝ) (m : ℕ) : ℝ := + (6*((tree phase c).lookback+1)+2 : ℕ)^2 * + ((4*(MainCell.replacementConstant (tree phase c) : ℝ)*ρ+(tree phase c).q/m)/(tree phase c).q+ + (4*(MainCell.replacementConstant (tree phase c) : ℝ)*ρ+EA/m)/EA) +lemma localLoss_nonneg (c : CellIndex q L U phase) {ρ : ℝ} (hρ : 0≤ρ) (m : ℕ) : + 0≤localLoss phase c ρ m := by + unfold localLoss + positivity [(tree phase c).q_pos,interpolationA.1] + +lemma sampleName_probability (c : CellIndex q L U phase) (hc : Available A S phase c) + (x : M.Point (BandTrees.band broad (lower q L U c.1.1)) + (BandTrees.root M broad (lower q L U c.1.1) c.1.2)) + {ρ : ℝ} (hρ : 0≤ρ) (hr : ρ≤(tree phase c).radius) (m : ℕ) (hm : 0 < m) : + prob (fun omega : Sample phase m => ∃ z, dist x z≤ρ ∧ + sampleName A S phase c hc ((omega c).1,(omega c).2.1) z≠ + sampleName A S phase c hc ((omega c).1,(omega c).2.1) x)≤localLoss phase c ρ m := by + classical + apply prob_pi_eval_bound (D := fun d => CellSample phase d m) c + (fun w => ∃ z, dist x z≤ρ ∧ + sampleName A S phase c hc (w.1,w.2.1) z≠sampleName A S phase c hc (w.1,w.2.1) x) + let e := Equiv.prodAssoc + (Point.RadialTree.GridSample (n := k+1) (tree phase c).depthCap m) (Fin (m+1)) Bool + rw [←prob_equiv e] + apply prob_prod_bound_left + intro b + exact MainCell.namedReplacement_probability (S.chart (index A S phase c hc)).comparison + (sub_old A S phase c hc) (tree phase c) (radial phase c) c.2.2 isCompact_Icc + (anchor phase c) x EA (lower q L U c.1.1) EA interpolationA.1 hρ hr m hm + +/-- Chart persistence for the **whole literal main mode**, conditional on the +padded height band. No factor depending on the number of graph cells occurs. -/ +lemma persistence_probability [SFinite μ] (x : M.Point Set.univ A.root) + (c : CellIndex q L U phase) (hc : x.height ∈ domain phase c x.column) + {ρ : ℝ} (hρ : 0≤ρ) (hp : Tiling.Padded a₁ q x.height ρ) + (hsmall : 4*ρ<3*EA) (hr : ρ≤(tree phase c).radius) + (hold : ∀ z : M.Point Set.univ A.root, dist x z≤ρ → + S.name z.column z.height=S.name x.column x.height) + (m : ℕ) (hm : 0 < m) : + prob (fun omega : Sample phase m => ∃ z : M.Point Set.univ A.root, dist x z≤ρ ∧ + (result A S phase hm omega).name z.column z.height≠ + (result A S phase hm omega).name x.column x.height) ≤ localLoss phase c ρ m := by + classical + by_cases hav : Available A S phase c + · let x' := MainCell.cellPoint (tree phase c) (radial phase c) c.2.2 x.column x.height hc + apply (prob_mono (Q := fun omega : Sample phase m => ∃ z, dist x' z≤ρ ∧ + sampleName A S phase c hav ((omega c).1,(omega c).2.1) z≠ + sampleName A S phase c hav ((omega c).1,(omega c).2.1) x') _).trans + (sampleName_probability A S phase c hav x' hρ hr m hm) + intro omega hbad + by_contra hn + obtain ⟨z,hz,hz'⟩ := hbad + apply hz' + apply result_name_eq A S phase hm omega x hρ hp hsmall c hc _ z hz (hold z hz) + intro hc' + dsimp only + intro y hy + exact not_ne_iff.mp (fun he => hn ⟨y,hy,he⟩) + · have hzero : prob (fun omega : Sample phase m => ∃ z : M.Point Set.univ A.root, + dist x z≤ρ ∧ (result A S phase hm omega).name z.column z.height≠ + (result A S phase hm omega).name x.column x.height)≤prob (fun _ : Sample phase m => False) := by + apply prob_mono + intro omega ⟨z,hz,hz'⟩ + exact hz' (result_name_eq A S phase hm omega x hρ hp hsmall c hc + (fun hc' => False.elim (hav hc')) z hz (hold z hz)) + rw [prob_false] at hzero + exact hzero.trans (localLoss_nonneg phase c hρ m) +end PlanarL1.Columns.Model.MainFamily + +end + +end OAI diff --git a/lean/OAI/Combinatorics/PlanarL1/MainStep.lean b/lean/OAI/Combinatorics/PlanarL1/MainStep.lean new file mode 100644 index 0000000000000000000000000000000000000000..e59177af8bbd3582fa71d2466b034fe8c643ba53 --- /dev/null +++ b/lean/OAI/Combinatorics/PlanarL1/MainStep.lean @@ -0,0 +1,578 @@ +import OAI.Combinatorics.PlanarL1.OrdinaryState +import OAI.Combinatorics.PlanarL1.FiniteL1 + +namespace OAI + +section + +namespace PlanarL1.Columns.Model +open MeasureTheory +open scoped NNReal +attribute [local instance] Classical.propDecidable + +namespace OrdinaryState +variable {n : ℕ} {M : Model n} {κ : ℝ} {Ω : Type*} [MeasurableSpace Ω] {μ : Measure Ω} + +lemma represents_named (S : OrdinaryState M κ Ω μ) (ω : Ω) (i : Fin n) (H : ℝ) + (a : Fin (S.count+1)) (he : S.name i H=a) (hi : H ∈ (S.chart a).band) : + (S.sets.activity ω).active i H ↔ + Threshold.active (S.labels a) H (κ*(S.chart a).value i ⟨H,hi⟩) ω := by + subst a + exact S.represents ω i H + +lemma contains_named (S : OrdinaryState M κ Ω μ) (i : Fin n) (H : ℝ) + (a : Fin (S.count+1)) (he : S.name i H=a) : (S.chart a).Contains i H := by + subst a + exact ⟨S.height_in i H,S.component_in i H⟩ + +/-- Literal deterministic data of a kept eligible main cell. Fresh signs are +label coordinates, not assumptions of independence between existing labels. -/ +structure MainStep (S : OrdinaryState M κ Ω μ) (J : Set ℝ) (root : Fin n) where + index : Fin (S.count+1) + tree : Point.RadialTree (M := M) (J := J) (root := root) + phase : ℝ + cell : MainCell.Cell tree phase + anchor : M.Point J root + anchor_mem : anchor.column ∈ ColumnOrder.componentColumns cell + lo : ℝ + band_eq : J=Set.Icc lo (lo+tree.a) + thin : tree.a ≤ (1/1000:ℝ)/1000 + sub_old : J ⊆ (S.chart index).band + same_name : ∀ i H, H ∈ MainCell.domain tree phase cell i → S.name i H=index + noise : Point.RadialTree.Noise (n := n) + noise_bounds : tree.NoiseBounds noise + error : ℝ + error_pos : 0 Threshold.active (S.labels U.index).lift H (κ*p) ω) + hvalue.symm)) + + +lemma unchosen (ω : Ω × Bool) (i : Fin n) (H : ℝ) (hc : U.choose i H=none) : + (U.patch.apply.activity ω).active i H ↔ (S.lift.sets.activity ω).active i H := by + by_cases hd : H ∈ MainCell.domain U.tree U.phase U.cell i + · have hn := MainCell.choose_none_inside U.comparison U.sub_old U.tree U.phase U.cell + U.anchor U.noise U.error U.shield_offset U.lo i H hd hc + have hv := (PlanarL1.Interpolation.namedClip_eq_old_iff _ _ _ _).mp hn + change (MainCell.namedReplacement U.comparison U.sub_old U.tree U.phase U.cell + U.anchor U.noise U.error U.shield_offset U.lo + (MainCell.cellPoint U.tree U.phase U.cell i H hd)).value = _ at hv + rw [MainCell.namedReplacement_value U.comparison U.sub_old U.tree U.phase U.cell + U.anchor U.noise U.error U.shield_offset U.lo] at hv + have hp := U.patch_inside ω i H hd + rw [hv] at hp + exact hp.trans (U.old_agreement ω i H hd) + · exact U.patch.unchanged hd ω + +lemma choose_switch (i j : Fin n) (H : ℝ) (hh : H ∈ M.heights i j) : + U.choose i H=U.choose j H := + MainCell.choose_switch U.comparison U.sub_old U.tree U.phase U.cell U.compact_band + U.anchor U.noise_bounds U.error_pos U.delta_eq U.shield_offset U.lo i j H hh + +/-- The exact single kept main-cell update, including the fresh shield label +rebase and retention of every old identifier wherever the scalar clip is old. -/ +noncomputable def apply [SFinite μ] : OrdinaryState M κ (Ω × Bool) (μ.prod Threshold.fair) := + S.lift.append U.patch.apply (3*n*U.tree.depthCap+1) U.newData U.newLabels U.choose + (fun i H a hc => (U.chosen_description i H a hc).1.1) + (fun i H a hc => (U.chosen_description i H a hc).1.2) + U.choose_switch U.unchosen + (fun ω i H a hc => (U.chosen_description i H a hc).2 ω _) + +lemma apply_sets [SFinite μ] : U.apply.sets=U.patch.apply := rfl + +end MainStep +end OrdinaryState +end PlanarL1.Columns.Model + + +namespace PlanarL1.Columns.Model +open MeasureTheory +open scoped NNReal +attribute [local instance] Classical.propDecidable +namespace OrdinaryState.MainStep +variable {n : ℕ} {M : Model n} {κ : ℝ} {Ω : Type*} [MeasurableSpace Ω] {μ : Measure Ω} +variable {S : OrdinaryState M κ Ω μ} {J : Set ℝ} {root : Fin n} +variable (U : MainStep S J root) + +lemma indicator_inside (ω : Ω × Bool) (i : Fin n) (H : ℝ) + (hi : H ∈ MainCell.domain U.tree U.phase U.cell i) : + (U.patch.apply.activity ω).indicator i H = + Threshold.chartValue H (κ*(U.data.constant+U.data.orientation* + MainCell.replacement U.comparison U.sub_old U.tree U.phase U.cell U.anchor + U.noise U.error U.shield_offset U.lo (MainCell.cellPoint U.tree U.phase U.cell i H hi))) + ((S.labels U.index).lift.value ω) := by + simp only [Activity.indicator,U.patch_inside ω i H hi,Threshold.active, + Threshold.chartValue,Threshold.half] + +lemma old_indicator (ω : Ω × Bool) (i : Fin n) (H : ℝ) + (hi : H ∈ MainCell.domain U.tree U.phase U.cell i) : + (S.lift.sets.activity ω).indicator i H = + Threshold.chartValue H (κ*(U.data.constant+U.data.orientation* + MainCell.old U.comparison U.sub_old (MainCell.cellPoint U.tree U.phase U.cell i H hi))) + ((S.labels U.index).lift.value ω) := by + simp only [Activity.indicator,← U.old_agreement ω i H hi,Threshold.active, + Threshold.chartValue,Threshold.half] + +/-- Actual label mass moved by one kept main cell equals the oriented scalar +raise times κ. This compares the new sets with the lifted old sets. -/ +lemma movement_exact (i : Fin n) (H : ℝ) + (hi : H ∈ MainCell.domain U.tree U.phase U.cell i) : + (∫ ω, |(U.patch.apply.activity ω).indicator i H- + (S.lift.sets.activity ω).indicator i H| ∂(μ.prod Threshold.fair)) = + κ*(MainCell.replacement U.comparison U.sub_old U.tree U.phase U.cell U.anchor + U.noise U.error U.shield_offset U.lo (MainCell.cellPoint U.tree U.phase U.cell i H hi)- + MainCell.old U.comparison U.sub_old (MainCell.cellPoint U.tree U.phase U.cell i H hi)) := by + simp_rw [U.indicator_inside _ i H hi,U.old_indicator _ i H hi] + rw [(S.labels U.index).lift.distance] + rw [sub_self,abs_zero,max_eq_right (abs_nonneg _)] + have hm := MainCell.movement U.comparison U.sub_old U.tree U.phase U.cell + U.compact_band U.thin U.anchor (MainCell.cellPoint U.tree U.phase U.cell i H hi) + U.anchor_mem ((MainCell.mem_domain U.tree U.phase U.cell).mp hi).1 + U.noise_bounds U.error_pos.le U.delta_eq + (fun x => Clipping.heightShield U.lo U.tree.a (MainCell.old U.comparison U.sub_old U.anchor) + U.shield_offset x.height) + rw [show κ*(U.data.constant+U.data.orientation*MainCell.replacement U.comparison U.sub_old + U.tree U.phase U.cell U.anchor U.noise U.error U.shield_offset U.lo + (MainCell.cellPoint U.tree U.phase U.cell i H hi))- + κ*(U.data.constant+U.data.orientation*MainCell.old U.comparison U.sub_old + (MainCell.cellPoint U.tree U.phase U.cell i H hi)) = + κ*U.data.orientation*(MainCell.replacement U.comparison U.sub_old U.tree U.phase U.cell + U.anchor U.noise U.error U.shield_offset U.lo (MainCell.cellPoint U.tree U.phase U.cell i H hi)- + MainCell.old U.comparison U.sub_old (MainCell.cellPoint U.tree U.phase U.cell i H hi)) by ring, + abs_mul,abs_mul,abs_of_nonneg U.kappa_nonneg,U.data.unit_orientation,mul_one] + congr 1 + exact abs_of_nonneg hm.1 + +lemma movement_integrable (i : Fin n) (H : ℝ) : + Integrable (fun ω => (U.patch.apply.activity ω).indicator i H- + (S.lift.sets.activity ω).indicator i H) (μ.prod Threshold.fair) := by + by_cases hi : H ∈ MainCell.domain U.tree U.phase U.cell i + · simp_rw [U.indicator_inside _ i H hi,U.old_indicator _ i H hi] + exact (S.labels U.index).lift.integrable_difference _ _ _ _ + · have he : (fun ω => (U.patch.apply.activity ω).indicator i H- + (S.lift.sets.activity ω).indicator i H) = fun _ => 0 := by + funext ω + simp only [Activity.indicator,U.patch.unchanged hi ω,sub_self] + rw [he] + exact integrable_zero _ _ _ + +lemma movement_bound (i : Fin n) (H : ℝ) : + (∫ ω, |(U.patch.apply.activity ω).indicator i H- + (S.lift.sets.activity ω).indicator i H| ∂(μ.prod Threshold.fair)) ≤ κ*(1+(1:ℝ)/100) := by + by_cases hi : H ∈ MainCell.domain U.tree U.phase U.cell i + · rw [U.movement_exact i H hi] + apply mul_le_mul_of_nonneg_left _ U.kappa_nonneg + exact (MainCell.movement U.comparison U.sub_old U.tree U.phase U.cell + U.compact_band U.thin U.anchor (MainCell.cellPoint U.tree U.phase U.cell i H hi) + U.anchor_mem ((MainCell.mem_domain U.tree U.phase U.cell).mp hi).1 + U.noise_bounds U.error_pos.le U.delta_eq _).2 + · have he : (fun ω => |(U.patch.apply.activity ω).indicator i H- + (S.lift.sets.activity ω).indicator i H|) = fun _ => 0 := by + funext ω + simp only [Activity.indicator,U.patch.unchanged hi ω,sub_self,abs_zero] + rw [he,integral_zero] + positivity [U.kappa_nonneg] + +/-- Under the literal padded-cell main test, either there is an actual shortest +band descent or the kept-cell movement has the claimed strict positive mass. -/ +lemma movement_or_descent (w : M.Point J root) + (hw : w.column ∈ ColumnOrder.componentColumns U.cell) + {ε : ℝ} (hε : 0<ε) (hεsmall : ε ≤ (1:ℝ)/100) + (hζ : U.tree.ζ=ε/100) (hE : U.error=ε/1000) + (hκ : 0<κ) + (hshield : MainCell.old U.comparison U.sub_old U.anchor+2 ≤ + Clipping.heightShield U.lo U.tree.a (MainCell.old U.comparison U.sub_old U.anchor) + U.shield_offset w.height) + (hlow : U.phase+(1:ℝ)/100000+2*U.tree.a < + dist U.tree.base (w.withHeight U.tree.base.height U.tree.base.inBand)) + (hupp : dist U.tree.base (w.withHeight U.tree.base.height U.tree.base.inBand) < + U.phase+(1:ℝ)/1000-(1:ℝ)/100000-2*U.tree.a) : + 2*κ*U.error < (∫ ω, |(U.patch.apply.activity ω).indicator w.column w.height- + (S.lift.sets.activity ω).indicator w.column w.height| ∂(μ.prod Threshold.fair)) ∨ + Nonempty (U.comparison.BandDescent J (w.widen U.sub_old) ε) := by + have hδ : U.tree.δ=(ε/1000)/8 := by rw [U.delta_eq,hE] + have hh := MainCell.raise_or_descent U.comparison U.sub_old U.tree U.phase U.cell + U.compact_band U.anchor w U.anchor_mem hw hε hεsmall hζ hδ U.noise_bounds + (fun x => Clipping.heightShield U.lo U.tree.a (MainCell.old U.comparison U.sub_old U.anchor) + U.shield_offset x.height) hshield hlow hupp + rcases hh with hh | hh + · left + have hi := (MainCell.mem_domain U.tree U.phase U.cell).mpr ⟨hw,w.inBand⟩ + rw [U.movement_exact _ _ hi] + have he : MainCell.cellPoint U.tree U.phase U.cell w.column w.height hi=w := by + cases w + rfl + rw [he] + change MainCell.old U.comparison U.sub_old w+2*(ε/1000) < + MainCell.replacement U.comparison U.sub_old U.tree U.phase U.cell U.anchor + U.noise (ε/1000) U.shield_offset U.lo w at hh + rw [← hE] at hh + nlinarith + · exact Or.inr hh + +end OrdinaryState.MainStep +end PlanarL1.Columns.Model + + + +end + +section + + + +namespace PlanarL1.Columns.Model +open MeasureTheory +attribute [local instance] Classical.propDecidable +namespace OrdinaryState.MainStep +variable {n : ℕ} {M : Model n} {κ : ℝ} {Ω : Type*} [MeasurableSpace Ω] {μ : Measure Ω} +variable {S : OrdinaryState M κ Ω μ} {J : Set ℝ} {root : Fin n} +variable (U : MainStep S J root) + +lemma old_indicator_named (ω : Ω × Bool) (y : M.Point J root) + (hy : S.name y.column y.height=U.index) : + (S.lift.sets.activity ω).indicator y.column y.height = + Threshold.chartValue y.height (κ*(U.data.constant+U.data.orientation* + MainCell.old U.comparison U.sub_old y)) ((S.labels U.index).lift.value ω) := by + have he := S.represents_named ω.1 y.column y.height U.index hy (U.sub_old y.inBand) + simp only [Activity.indicator,Threshold.chartValue,Threshold.half,Threshold.active] at * + exact if_congr he rfl rfl + +/-- Actual common-label pair distance when one cell is kept and the other +endpoint is outside it. The comparison uses old labels, not new chart names. -/ +lemma pair_distance (x y : M.Point J root) + (hx : x.column ∈ ColumnOrder.componentColumns U.cell) + (hy : y.column ∉ ColumnOrder.componentColumns U.cell) + (hyn : S.name y.column y.height=U.index) : + (∫ ω, |(U.patch.apply.activity ω).indicator x.column x.height- + (U.patch.apply.activity ω).indicator y.column y.height| ∂(μ.prod Threshold.fair)) = + max |x.height-y.height| + (κ*|MainCell.replacement U.comparison U.sub_old U.tree U.phase U.cell U.anchor + U.noise U.error U.shield_offset U.lo x-MainCell.old U.comparison U.sub_old y|) := by + have hxi := (MainCell.mem_domain U.tree U.phase U.cell).mpr ⟨hx,x.inBand⟩ + have hyi : y.height ∉ MainCell.domain U.tree U.phase U.cell y.column := by + intro h + exact hy ((MainCell.mem_domain U.tree U.phase U.cell).mp h).1 + have he : MainCell.cellPoint U.tree U.phase U.cell x.column x.height hxi=x := by + cases x + rfl + have hid (ω : Ω × Bool) : + (U.patch.apply.activity ω).indicator y.column y.height = + (S.lift.sets.activity ω).indicator y.column y.height := by + simp only [Activity.indicator,U.patch.unchanged hyi ω] + simp_rw [U.indicator_inside _ _ _ hxi,he,hid,U.old_indicator_named _ y hyn] + rw [(S.labels U.index).lift.distance] + congr 1 + rw [show κ*(U.data.constant+U.data.orientation*MainCell.replacement U.comparison U.sub_old + U.tree U.phase U.cell U.anchor U.noise U.error U.shield_offset U.lo x)- + κ*(U.data.constant+U.data.orientation*MainCell.old U.comparison U.sub_old y) = + κ*U.data.orientation*(MainCell.replacement U.comparison U.sub_old U.tree U.phase U.cell + U.anchor U.noise U.error U.shield_offset U.lo x-MainCell.old U.comparison U.sub_old y) by ring, + abs_mul,abs_mul,abs_of_nonneg U.kappa_nonneg,U.data.unit_orientation,mul_one] + +lemma separation_of_raise (x y : M.Point J root) + (hx : x.column ∈ ColumnOrder.componentColumns U.cell) + (hy : y.column ∉ ColumnOrder.componentColumns U.cell) + (hyn : S.name y.column y.height=U.index) (hκ : 0<κ) + (hclose : |MainCell.old U.comparison U.sub_old x-MainCell.old U.comparison U.sub_old y| ≤ U.error) + (hraise : MainCell.old U.comparison U.sub_old x+2*U.error < + MainCell.replacement U.comparison U.sub_old U.tree U.phase U.cell U.anchor + U.noise U.error U.shield_offset U.lo x) : + κ*U.error < (∫ ω, |(U.patch.apply.activity ω).indicator x.column x.height- + (U.patch.apply.activity ω).indicator y.column y.height| ∂(μ.prod Threshold.fair)) := by + rw [U.pair_distance x y hx hy hyn] + apply lt_of_lt_of_le _ (le_max_right _ _) + apply mul_lt_mul_of_pos_left _ hκ + have hb := (abs_le.mp hclose).1 + have ha := le_abs_self (MainCell.replacement U.comparison U.sub_old U.tree U.phase U.cell + U.anchor U.noise U.error U.shield_offset U.lo x-MainCell.old U.comparison U.sub_old y) + linarith + +/-- Literal deterministic favorable branch in the main pair-separation test. -/ +lemma pair_separation_of_no_descent (x y : M.Point J root) + (hx : x.column ∈ ColumnOrder.componentColumns U.cell) + (hy : y.column ∉ ColumnOrder.componentColumns U.cell) + (hyn : S.name y.column y.height=U.index) (hκ : 0<κ) + {ε : ℝ} (hε : 0<ε) (hεsmall : ε ≤ (1:ℝ)/100) + (hζ : U.tree.ζ=ε/100) (hE : U.error=ε/1000) + (hclose : |MainCell.old U.comparison U.sub_old x-MainCell.old U.comparison U.sub_old y| ≤ U.error) + (hshield : MainCell.old U.comparison U.sub_old U.anchor+2 ≤ + Clipping.heightShield U.lo U.tree.a (MainCell.old U.comparison U.sub_old U.anchor) + U.shield_offset x.height) + (hlow : U.phase+(1:ℝ)/100000+2*U.tree.a < + dist U.tree.base (x.withHeight U.tree.base.height U.tree.base.inBand)) + (hupp : dist U.tree.base (x.withHeight U.tree.base.height U.tree.base.inBand) < + U.phase+(1:ℝ)/1000-(1:ℝ)/100000-2*U.tree.a) + (hno : ¬Nonempty (U.comparison.BandDescent J (x.widen U.sub_old) ε)) : + κ*U.error < (∫ ω, |(U.patch.apply.activity ω).indicator x.column x.height- + (U.patch.apply.activity ω).indicator y.column y.height| ∂(μ.prod Threshold.fair)) := by + apply U.separation_of_raise x y hx hy hyn hκ hclose + have hδ : U.tree.δ=(ε/1000)/8 := by rw [U.delta_eq,hE] + have hh := MainCell.raise_or_descent U.comparison U.sub_old U.tree U.phase U.cell + U.compact_band U.anchor x U.anchor_mem hx hε hεsmall hζ hδ U.noise_bounds + (fun z => Clipping.heightShield U.lo U.tree.a (MainCell.old U.comparison U.sub_old U.anchor) + U.shield_offset z.height) hshield hlow hupp + rcases hh with hh | hh + · simpa only [hE,MainCell.replacement] using hh + · exact (hno hh).elim + +end OrdinaryState.MainStep +end PlanarL1.Columns.Model + + + + + +end + +section + +namespace PlanarL1.Columns.Model.OrdinaryState +open MeasureTheory +attribute [local instance] Classical.propDecidable +variable {n : ℕ} {M : Model n} {κ : ℝ} {Ω : Type*} [MeasurableSpace Ω] {μ : Measure Ω} + {S : OrdinaryState M κ Ω μ} + +/-- A finite family of the actual main-cell proposals. Distinct cells may meet +at unchanged boundary points; no disjointness of their closed domains is assumed. -/ +structure MainBatch (S : OrdinaryState M κ Ω μ) where + count : ℕ + band : Fin count → Set ℝ + root : Fin count → Fin n + step : ∀ q, MainStep S (band q) (root q) + overlap : (List.ofFn (fun q => (step q).patch)).Pairwise SetPatch.UnchangedOverlap + +namespace MainBatch +variable (B : MainBatch S) + +def NewIndex := Σ q : Fin B.count, Fin (3*n*(B.step q).tree.depthCap+1) +noncomputable instance : Fintype B.NewIndex := inferInstanceAs (Fintype (Sigma _)) + +noncomputable def newData (a : B.NewIndex) : OrdinaryData M := + (B.step a.1).newData a.2 +noncomputable def newLabels [SFinite μ] (a : B.NewIndex) : + Threshold.Variables (Ω × Bool) (μ.prod Threshold.fair) := + (B.step a.1).newLabels a.2 + +noncomputable def chosen (i : Fin n) (H : ℝ) (a : B.NewIndex) : Prop := + (B.step a.1).choose i H = some a.2 + +noncomputable def choose (i : Fin n) (H : ℝ) : Option B.NewIndex := + if h : ∃ a, B.chosen i H a then some h.choose else none + +lemma choose_some (i : Fin n) (H : ℝ) (a : B.NewIndex) + (ha : B.choose i H=some a) : B.chosen i H a := by + unfold choose at ha + split_ifs at ha with h + · have he : h.choose=a := Option.some.inj ha + exact he ▸ h.choose_spec + +lemma choose_none (i : Fin n) (H : ℝ) (ha : B.choose i H=none) (q : Fin B.count) : + (B.step q).choose i H=none := by + cases he : (B.step q).choose i H with + | none => rfl + | some a => + have hex : ∃ a, B.chosen i H a := ⟨⟨q,a⟩,he⟩ + simp [choose,hex] at ha + +lemma choose_switch (i j : Fin n) (H : ℝ) (hs : H ∈ M.heights i j) : + B.choose i H=B.choose j H := by + have he : B.chosen i H=B.chosen j H := by + funext a + simp only [chosen,(B.step a.1).choose_switch i j H hs] + unfold choose + simp only [he] + +noncomputable def sets : SetSystem M (Ω × Bool) (μ.prod Threshold.fair) := + SetPatch.batch (List.ofFn (fun q => (B.step q).patch)) B.overlap + +lemma chosen_description [SFinite μ] (i : Fin n) (H : ℝ) (a : B.NewIndex) + (ha : B.chosen i H a) : (B.newData a).Contains i H ∧ + ∀ (ω : Ω × Bool) (hi : H ∈ (B.newData a).band), + (B.sets.activity ω).active i H ↔ + Threshold.active (B.newLabels a) H (κ*(B.newData a).value i ⟨H,hi⟩) ω := by + have h := (B.step a.1).chosen_description i H a.2 ha + refine ⟨h.1,?_⟩ + intro ω hi + obtain ⟨hd,-⟩ := MainCell.choose_spec (B.step a.1).comparison (B.step a.1).sub_old + (B.step a.1).tree (B.step a.1).phase (B.step a.1).cell (B.step a.1).anchor + (B.step a.1).noise (B.step a.1).error (B.step a.1).shield_offset (B.step a.1).lo i H a.2 ha + apply (SetPatch.batch_inside _ B.overlap (List.mem_ofFn.mpr ⟨a.1,rfl⟩) ω i H hd).trans + exact h.2 ω hi + +lemma unchosen (ω : Ω × Bool) (i : Fin n) (H : ℝ) (ha : B.choose i H=none) : + (B.sets.activity ω).active i H ↔ (S.lift.sets.activity ω).active i H := by + apply SetPatch.batch_old _ B.overlap ω i H + intro P hP + obtain ⟨q,rfl⟩ := List.mem_ofFn.mp hP + exact (B.step q).unchosen ω i H (B.choose_none i H ha q) + +/-- Actual finite main update, with the chart table containing every ancestor +formula and each shield's rebased label variables. -/ +noncomputable def apply [SFinite μ] : OrdinaryState M κ (Ω × Bool) (μ.prod Threshold.fair) := by + let e := Fintype.equivFin B.NewIndex + let pick : Fin n → ℝ → Option (Fin (Fintype.card B.NewIndex)) := + fun i H => (B.choose i H).map e + have hpick (i H a) (ha : pick i H=some a) : B.chosen i H (e.symm a) := by + obtain ⟨b,hb,hba⟩ := Option.map_eq_some_iff.mp ha + have he : b=e.symm a := by rw [← hba]; simp + exact he ▸ B.choose_some i H b hb + exact S.lift.append B.sets (Fintype.card B.NewIndex) + (B.newData ∘ e.symm) (B.newLabels ∘ e.symm) pick + (fun i H a ha => (B.chosen_description i H (e.symm a) (hpick i H a ha)).1.1) + (fun i H a ha => (B.chosen_description i H (e.symm a) (hpick i H a ha)).1.2) + (fun i j H hs => congrArg (Option.map e) (B.choose_switch i j H hs)) + (fun ω i H ha => B.unchosen ω i H (Option.map_eq_none_iff.mp ha)) + (fun ω i H a ha => (B.chosen_description i H (e.symm a) (hpick i H a ha)).2 ω _) + +end MainBatch +end PlanarL1.Columns.Model.OrdinaryState + + + +end + +end OAI diff --git a/lean/OAI/Combinatorics/PlanarL1/Movement.lean b/lean/OAI/Combinatorics/PlanarL1/Movement.lean new file mode 100644 index 0000000000000000000000000000000000000000..c26344610fb4a00ba02d81da90c0bc0604fa20de --- /dev/null +++ b/lean/OAI/Combinatorics/PlanarL1/Movement.lean @@ -0,0 +1,406 @@ +import OAI.Combinatorics.PlanarL1.CoupledState + +namespace OAI + + +section + +namespace PlanarL1.Columns.Model.BState +open MeasureTheory Set +open scoped NNReal +attribute [local instance] Classical.propDecidable +variable {k : ℕ} {M : Model (k+1)} {κ : ℝ} {lam : ℝ≥0} +variable {Ω : Type*} [MeasurableSpace Ω] {μ : Measure Ω} {S : BState M κ lam Ω μ} + +namespace SecondaryStep +variable {J : Set ℝ} {root : Fin (k+1)} (U : SecondaryStep S J root) +lemma full_movement (i : Fin (k+1)) (H : U.data.band) : + |U.fullReplacement i H-U.comparison.value i H| ≤ (51/1000:ℝ) := by + by_cases hd : H.val ∈ SecondaryCell.domain U.seeds U.radius i + · rw [U.fullReplacement_inside i H hd,←U.point_old hd] + have hh := SecondaryCell.replacement_movement U.tree U.seeds U.old U.supportValue U.data.isOrdinary + (αo := U.ordered_offset) (αh := U.shield_offset) (lo := U.lo) + U.seeds_nonempty U.old_lipschitz U.zeta_eq U.radius_nonneg U.delta_eq U.noise_bounds + U.seed_near (SecondaryCell.point_distance U.seeds U.radius hd) + exact hh.trans (by linarith [U.radius_small]) + · rw [U.fullReplacement_outside i H hd,sub_self,abs_zero] + norm_num +end SecondaryStep + +namespace SecondaryBatch +variable (B : SecondaryBatch S) +lemma selected_movement (i : Fin (k+1)) (H : B.data.band) : + |(B.selected i H).value-κ*B.comparison.value i H| ≤ κ*(51/1000:ℝ) := by + rcases B.selected_cases i H with he|⟨a,he⟩ + · rw [he]; simp only [sub_self,abs_zero] + exact mul_nonneg B.kappa_nonneg (by norm_num) + · rw [he]; change |(B.groupNamed a i H).value-κ*B.comparison.value i H| ≤ _ + rw [B.groupNamed_value,←B.step_comparison a i H,←mul_sub,abs_mul,abs_of_nonneg B.kappa_nonneg] + exact mul_le_mul_of_nonneg_left ((B.step a).full_movement i (B.groupHeight a H)) B.kappa_nonneg + +lemma old_indicator_inside (w : Ω × Bool) (i : Fin (k+1)) (H : ℝ) (hd : H ∈ B.domain i) : + (S.lift.sets.activity w).indicator i H=Threshold.chartValue H + (κ*(B.data.offset+B.data.orientation B.positive*B.comparison.value i ⟨H,B.domain_band hd⟩)) + ((S.labels B.index).lift.value w) := by + have hr := S.represents_named w.1 i H B.index (B.domain_name hd) (B.domain_band hd) + have he := B.data.comparison_convert lam B.lambda_bound B.positive i ⟨H,B.domain_band hd⟩ + change (S.sets.activity w.1).active i H ↔ Threshold.active (S.labels B.index) H + (κ*B.data.value lam i ⟨H,B.domain_band hd⟩) w.1 at hr + rw [he] at hr + change (S.sets.activity w.1).indicator i H=_ + simp only [Activity.indicator,Threshold.chartValue,Threshold.half,Threshold.active] at * + exact if_congr hr rfl rfl + +lemma movement_integrable (i : Fin (k+1)) (H : ℝ) : Integrable + (fun w => (B.patch.apply.activity w).indicator i H-(S.lift.sets.activity w).indicator i H) + (μ.prod Threshold.fair) := by + by_cases hd : H ∈ B.domain i + · simp_rw [B.indicator_inside _ i H hd,B.old_indicator_inside _ i H hd] + exact (S.labels B.index).lift.integrable_difference _ _ _ _ + · have he (w : Ω × Bool) : (B.patch.apply.activity w).indicator i H=(S.lift.sets.activity w).indicator i H := by + simp only [Activity.indicator,B.patch.unchanged hd w] + simp only [he,sub_self] + exact integrable_zero _ _ _ + +lemma movement_bound (i : Fin (k+1)) (H : ℝ) : + (∫ w, |(B.patch.apply.activity w).indicator i H-(S.lift.sets.activity w).indicator i H| ∂μ.prod Threshold.fair) + ≤ κ*(51/1000:ℝ) := by + by_cases hd : H ∈ B.domain i + · simp_rw [B.indicator_inside _ i H hd,B.old_indicator_inside _ i H hd] + rw [(S.labels B.index).lift.distance,sub_self,abs_zero,max_eq_right (abs_nonneg _), + B.converted_on i H (B.domain_band hd)] + rw [show κ*B.data.offset+B.data.orientation B.positive*(B.selected i ⟨H,B.domain_band hd⟩).value- + κ*(B.data.offset+B.data.orientation B.positive*B.comparison.value i ⟨H,B.domain_band hd⟩)= + B.data.orientation B.positive*((B.selected i ⟨H,B.domain_band hd⟩).value-κ*B.comparison.value i ⟨H,B.domain_band hd⟩) by ring, + abs_mul,B.data.orientation_unit,one_mul] + exact B.selected_movement i ⟨H,B.domain_band hd⟩ + · have he (w : Ω × Bool) : (B.patch.apply.activity w).indicator i H=(S.lift.sets.activity w).indicator i H := by + simp only [Activity.indicator,B.patch.unchanged hd w] + simp only [he,sub_self,abs_zero,integral_zero] + exact mul_nonneg B.kappa_nonneg (by norm_num) +end SecondaryBatch + +namespace SecondaryLayer +variable (B : SecondaryLayer S) +lemma movement_integrable (i : Fin (k+1)) (H : ℝ) : Integrable + (fun w => (B.sets.activity w).indicator i H-(S.lift.sets.activity w).indicator i H) + (μ.prod Threshold.fair) := by + apply SetPatch.batch_movement_integrable + intro P hP i H + obtain ⟨a,rfl⟩ := List.mem_ofFn.mp hP + exact (B.batch a).movement_integrable i H +lemma movement_bound (hκ : 0 ≤ κ) (i : Fin (k+1)) (H : ℝ) : + (∫ w, |(B.sets.activity w).indicator i H-(S.lift.sets.activity w).indicator i H| ∂μ.prod Threshold.fair) + ≤ κ*(51/1000:ℝ) := by + apply SetPatch.batch_movement _ _ (mul_nonneg hκ (by norm_num)) + intro P hP i H + obtain ⟨a,rfl⟩ := List.mem_ofFn.mp hP + exact (B.batch a).movement_bound i H +end SecondaryLayer +end PlanarL1.Columns.Model.BState + +end + + + +section + +namespace PlanarL1.Columns.Model +open MeasureTheory Set +attribute [local instance] Classical.propDecidable +variable {k : ℕ} {M : Model (k+1)} {Ω : Type*} [MeasurableSpace Ω] {μ : Measure Ω} +namespace SetSystem +variable (S T : SetSystem M Ω μ) +lemma separation_survival {J : Set ℝ} {r : Fin (k+1)} (x y : M.Point J r) + (hmove : ∀ i H, Integrable (fun w => (T.activity w).indicator i H-(S.activity w).indicator i H) μ) : + S.separation x.column x.height y.column y.height ≤ + T.separation x.column x.height y.column y.height+ + S.movement T x.column x.height+S.movement T y.column y.height := by + let p := Classical.choice (x.paths_nonempty y) + have hi := T.unrefined_integrable p x.height y.height + have hx := (hmove x.column x.height).abs + have hy := (hmove y.column y.height).abs + have hp (w : Ω) : |(S.activity w).indicator x.column x.height-(S.activity w).indicator y.column y.height| ≤ + |(T.activity w).indicator x.column x.height-(T.activity w).indicator y.column y.height|+ + |(T.activity w).indicator x.column x.height-(S.activity w).indicator x.column x.height|+ + |(T.activity w).indicator y.column y.height-(S.activity w).indicator y.column y.height| := by + linarith [abs_sub_le ((S.activity w).indicator x.column x.height) + ((T.activity w).indicator x.column x.height) ((S.activity w).indicator y.column y.height), + abs_sub_le ((T.activity w).indicator x.column x.height) + ((T.activity w).indicator y.column y.height) ((S.activity w).indicator y.column y.height), + abs_sub_comm ((S.activity w).indicator x.column x.height) ((T.activity w).indicator x.column x.height)] + have he := integral_mono (S.unrefined_integrable p x.height y.height) ((hi.add hx).add hy) hp + simp only [Pi.add_apply] at he + have he1 := integral_add (hi.add hx) hy + have he2 := integral_add hi hx + simp only [Pi.add_apply] at he1 he2 + rw [he1,he2] at he + exact he +end SetSystem + +namespace PairGeometry +variable {V : Type*} {A : Ambient M} {S T : OrdinaryState M Parameters.kappaA Ω μ} +variable {v : V → M.Point Set.univ A.root} {x y : V} {b B : ℝ} +lemma Certificate.survive (h : Certificate A S v (x := x) (y := y) b) (hb : 0 (T.sets.activity w).indicator i H-(S.sets.activity w).indicator i H) μ) + (hbound : ∀ i H, S.sets.movement T.sets i H≤B) : + Certificate A T v (x := x) (y := y) (b-3*B) := by + obtain ⟨a,c,H,E,hH,hac,hsep,hE,hm,hx,hy,hn⟩ := h + have hfin : μ E<⊤ := by + by_contra hh + have ht : μ E=⊤ := top_unique (not_lt.mp hh) + have hz : μ.real E=0 := by simp [Measure.real,ht] + linarith + let F : Set Ω := E ∩ {w | (T.sets.activity w).active (v x).column (v x).height} ∩ + {w | (T.sets.activity w).active (v y).column (v y).height} ∩ + {w | ¬(T.sets.activity w).active a H} + have hF : MeasurableSet F := ((hE.inter (T.sets.measurable_active _ _)).inter + (T.sets.measurable_active _ _)).inter (T.sets.measurable_active _ _).compl + have hFE : F⊆E := fun _ h => h.1.1.1 + have hI : Integrable (E.indicator (fun _ => (1:ℝ))) μ := + (integrable_indicator_iff hE).mpr ((integrableOn_const_iff).mpr (Or.inr hfin)) + have hJ : Integrable (F.indicator (fun _ => (1:ℝ))) μ := + (integrable_indicator_iff hF).mpr ((integrableOn_const_iff).mpr (Or.inr ((measure_mono hFE).trans_lt hfin))) + have hC (w : Ω) : E.indicator (fun _ => (1:ℝ)) w ≤ + F.indicator (fun _ => (1:ℝ)) w+ + |(T.sets.activity w).indicator (v x).column (v x).height-(S.sets.activity w).indicator (v x).column (v x).height|+ + |(T.sets.activity w).indicator (v y).column (v y).height-(S.sets.activity w).indicator (v y).column (v y).height|+ + |(T.sets.activity w).indicator a H-(S.sets.activity w).indicator a H| := by + by_cases hw : w∈E + · have h1 := hx w hw; have h2 := hy w hw; have h3 := hn w hw + by_cases htx : (T.sets.activity w).active (v x).column (v x).height <;> + by_cases hty : (T.sets.activity w).active (v y).column (v y).height <;> + by_cases hta : (T.sets.activity w).active a H <;> + simp [F,hw,htx,hty,hta,Activity.indicator,h1,h2,h3] + · have hf : w∉F := fun he => hw (hFE he) + simp only [Set.indicator_of_notMem hw,Set.indicator_of_notMem hf,zero_add] + positivity + have he := integral_mono hI (((hJ.add (hmove _ _).abs).add (hmove _ _).abs).add (hmove _ _).abs) hC + simp only [Pi.add_apply] at he + rw [integral_add,integral_add,integral_add] at he + · rw [integral_indicator_const _ hE,integral_indicator_const _ hF,smul_eq_mul,smul_eq_mul,mul_one,mul_one] at he + refine ⟨a,c,H,F,hH,hac,hsep,hF,?_,?_,?_,?_⟩ + · have h1 := hbound (v x).column (v x).height + have h2 := hbound (v y).column (v y).height + have h3 := hbound a H + change (∫ w, |(T.sets.activity w).indicator (v x).column (v x).height-(S.sets.activity w).indicator (v x).column (v x).height| ∂μ)≤B at h1 + change (∫ w, |(T.sets.activity w).indicator (v y).column (v y).height-(S.sets.activity w).indicator (v y).column (v y).height| ∂μ)≤B at h2 + change (∫ w, |(T.sets.activity w).indicator a H-(S.sets.activity w).indicator a H| ∂μ)≤B at h3 + linarith + · exact fun _ h => h.1.1.2 + · exact fun _ h => h.1.2 + · exact fun _ h => h.2 + all_goals first | exact hJ | exact (hmove _ _).abs | exact hJ.add (hmove _ _).abs | exact (hJ.add (hmove _ _).abs).add (hmove _ _).abs +end PairGeometry +end PlanarL1.Columns.Model + +end + + + +section + +namespace PlanarL1.Execution +variable {α β : Type*} +def Holds : Execution α → (α → Prop) → Prop + | .pure x, P => P x + | .choose _ E, P => ∀ i, Holds (E i) P +lemma holds_of_forall (E : Execution α) {P : α → Prop} (h : ∀ x, P x) : E.Holds P := by + induction E with + | pure x => exact h x + | choose n E ih => exact ih +lemma Holds.mono {E : Execution α} {P Q : α → Prop} (h : E.Holds P) + (hp : ∀ x, P x → Q x) : E.Holds Q := by + induction E with + | pure x => exact hp x h + | choose n E ih => exact fun i => ih i (h i) +lemma Holds.bind {E : Execution α} {P : α → Prop} (h : E.Holds P) + (F : α → Execution β) {Q : β → Prop} (hf : ∀ x, P x → (F x).Holds Q) : + (E.bind F).Holds Q := by + induction E with + | pure x => exact hf x h + | choose n E ih => exact fun i => ih i (h i) +lemma holds_bind_of_forall (E : Execution α) (F : α → Execution β) {Q : β → Prop} + (h : ∀ x, (F x).Holds Q) : (E.bind F).Holds Q := + (E.holds_of_forall (fun _ => True.intro)).bind F (fun x _ => h x) +lemma Holds.mean_mono {E : Execution α} {f g : α → ℝ} (h : E.Holds (fun x => f x≤g x)) : + E.mean f≤E.mean g := by + induction E with + | pure x => exact h + | choose n E ih => + exact div_le_div_of_nonneg_right + (Finset.sum_le_sum (fun i _ => ih i (h i))) (by positivity) +lemma Holds.prob_mono {E : Execution α} {P Q : α → Prop} (h : E.Holds (fun x => P x → Q x)) : + E.prob P≤E.prob Q := by + classical + apply Holds.mean_mono + apply h.mono + intro x hp + by_cases hx : P x + · simp [hx,hp hx] + · simp only [hx,ite_false]; split_ifs <;> norm_num +lemma Holds.prob_eq_one {E : Execution α} {P : α → Prop} (h : E.Holds P) : E.prob P=1 := by + have hh := h.mono (Q := fun x => True → P x) (fun _ hx _ => hx) + apply le_antisymm (E.prob_le_one P) + have he : E.prob (fun _ => True)=1 := by simp [prob,E.mean_const] + simpa only [he] using hh.prob_mono +lemma Holds.mean_eq {E : Execution α} {f g : α → ℝ} (h : E.Holds (fun x => f x=g x)) : + E.mean f=E.mean g := + le_antisymm (h.mono (fun _ hx => hx.le)).mean_mono (h.mono (fun _ hx => hx.ge)).mean_mono +end PlanarL1.Execution + +end + + + +section + +namespace PlanarL1.Columns.Model +open MeasureTheory +open scoped NNReal +variable {k : ℕ} {M : Model (k+1)} {Ω : Type*} [MeasurableSpace Ω] {μ : Measure Ω} +namespace SetSystem +lemma lift_movement (S T : SetSystem M Ω μ) (i : Fin (k+1)) (H : ℝ) : + S.lift.movement T.lift i H=S.movement T i H := by + let hp := measurePreserving_fst (μ := μ) (ν := Threshold.fair) + change (∫ z : Ω × Bool, |(T.activity z.1).indicator i H-(S.activity z.1).indicator i H| ∂μ.prod Threshold.fair)=_ + have he := integral_map_of_stronglyMeasurable (μ := μ.prod Threshold.fair) hp.measurable + (((T.measurable_indicator i H).sub (S.measurable_indicator i H)).abs.stronglyMeasurable) + rw [hp.map_eq] at he + exact he.symm +end SetSystem + +namespace BState +variable {κ : ℝ} {lam : ℝ≥0} (S : BState M κ lam Ω μ) (A : Ambient M) +lemma increment_integrable {c r : ℝ} + (hist : Fin (S.count+1) → A.History c) (sign : Fin (S.count+1) → Bool) + (hc : 0 ((S.increment A hist sign hc hcr hr hcross hrec hk hsmall hlam hboundary).sets.activity w).indicator i H- + (S.sets.activity w).indicator i H) μ := by + change Integrable (fun w => (S.fieldActivity (S.incrementFields A hist sign hc hcr hr hcross hlam) + hk hsmall hlam (S.increment_boundary A hist sign hc hcr hr hcross hrec hk hlam hboundary) w).indicator i H- + (S.sets.activity w).indicator i H) μ + simp_rw [S.field_indicator,S.old_indicator] + exact (S.labels (S.name i H)).integrable_difference _ _ _ _ +end BState + +namespace CoupledState +open Parameters SecondaryGeometry VertexBands +attribute [local instance] Classical.propDecidable +variable {Ξ : Type*} [MeasurableSpace Ξ] {ν : Measure Ξ} +variable {A : Ambient M} {t : ℝ} (S : CoupledState A Ω Ξ μ ν t) +variable {t' : ℝ} +def Moves (T : CoupledState A (Ω × Bool) (Ξ × Bool) (μ.prod Threshold.fair) (ν.prod Threshold.fair) t') (B : ℝ) : Prop := + (∀ i H, Integrable (fun w => (T.left.sets.activity w).indicator i H-(S.left.lift.sets.activity w).indicator i H) (μ.prod Threshold.fair)) ∧ + (∀ i H, Integrable (fun w => (T.right.sets.activity w).indicator i H-(S.right.lift.sets.activity w).indicator i H) (ν.prod Threshold.fair)) ∧ + (∀ i H, S.left.lift.sets.movement T.left.sets i H ≤ B) ∧ + (∀ i H, S.right.lift.sets.movement T.right.sets i H ≤ B) + +lemma Moves.successful {T : CoupledState A (Ω × Bool) (Ξ × Bool) (μ.prod Threshold.fair) (ν.prod Threshold.fair) t'} + {B : ℝ} (h : S.Moves T B) (hB : 0 ≤ B) {V : Type*} (v : V → M.Point Set.univ A.root) + {b : ℝ} {x y : V} (hs : S.Successful v b x y) : T.Successful v (b-3*B) x y := by + by_cases hb : 0 S.Moves T 1) := by + intro i + fin_cases i + · exact S.unchanged_moves ht + · apply Execution.holds_bind_of_forall + intro omega + exact S.main_moves ht phaseD hm omega + · apply Execution.holds_bind_of_forall + intro omega + exact S.secondary_moves ht v hv phaseD hm p phaseG omega + · apply Execution.holds_bind_of_forall + intro sign + exact S.increment_moves ht hgap sign +lemma step_moves : (S.step ht hgap v hv hm).Holds (fun T => S.Moves T 1) := by + apply Execution.holds_bind_of_forall + intro c + exact S.modes_moves ht hgap v hv (phase D c.2.1) hm (shift m a₂ c.1.2) (phase g c.2.2) +end CoupledState +end PlanarL1.Columns.Model + +end + + + +section + +namespace PlanarL1.FiniteRandom +lemma prob_eq_instances {Ω : Type*} (F F' : Fintype Ω) (P : Ω → Prop) : + @prob Ω F P = @prob Ω F' P := by + cases Subsingleton.elim F' F + rfl +lemma prob_bound_of_instances {Ω : Type*} {F F' : Fintype Ω} (P : Ω → Prop) {b : ℝ} + (h : @prob Ω F' P ≤ b) : @prob Ω F P ≤ b := + (prob_eq_instances F F' P).trans_le h +lemma prob_prod_bound_any {Ω Λ : Type*} [Fintype Ω] [Nonempty Ω] [Fintype Λ] + (F : Fintype (Ω × Λ)) (P : Ω × Λ → Prop) {b : ℝ} + (h : ∀ w, prob (fun z : Λ => P (w,z)) ≤ b) : @prob (Ω × Λ) F P ≤ b := by + rw [prob_eq_instances F (instFintypeProd Ω Λ) P] + exact prob_prod_bound P h +end PlanarL1.FiniteRandom + +end + +end OAI diff --git a/lean/OAI/Combinatorics/PlanarL1/Noncrossing.lean b/lean/OAI/Combinatorics/PlanarL1/Noncrossing.lean new file mode 100644 index 0000000000000000000000000000000000000000..c490974eb4c374220cc59ed45fb175aa2f7b9269 --- /dev/null +++ b/lean/OAI/Combinatorics/PlanarL1/Noncrossing.lean @@ -0,0 +1,638 @@ +import OAI.Combinatorics.PlanarL1.Order + +namespace OAI + +section + +namespace PlanarL1 +/-! ## Noncrossing column words +These are the exact combinatorial separation tools used in the surviving-seed +packing argument. The circular set has been cut at index 0. -/ + +namespace ColumnOrder + +/-- No two links have four alternating, distinct endpoints in cyclic order. -/ +def Noncrossing {n : ℕ} (G : SimpleGraph (Fin n)) : Prop := + ∀ a b c d : Fin n, a < b → b < c → c < d → + ¬ (G.Adj a c ∧ G.Adj b d) + +lemma noncrossing_comap_rotate {n : ℕ} {G : SimpleGraph (Fin (n + 1))} + (hG : Noncrossing G) : Noncrossing (G.comap (finRotate (n + 1))) := by + intro a b c d hab hbc hcd h + have ha : a ≠ Fin.last n := by intro he; subst a; exact (not_lt_of_ge b.le_last) hab + have hb : b ≠ Fin.last n := by intro he; subst b; exact (not_lt_of_ge c.le_last) hbc + have hc : c ≠ Fin.last n := by intro he; subst c; exact (not_lt_of_ge d.le_last) hcd + have hab' : finRotate _ a < finRotate _ b := by + rw [Fin.lt_def, coe_finRotate_of_ne_last ha, coe_finRotate_of_ne_last hb] + exact Nat.add_lt_add_right hab 1 + have hbc' : finRotate _ b < finRotate _ c := by + rw [Fin.lt_def, coe_finRotate_of_ne_last hb, coe_finRotate_of_ne_last hc] + exact Nat.add_lt_add_right hbc 1 + change G.Adj (finRotate _ a) (finRotate _ c) ∧ G.Adj (finRotate _ b) (finRotate _ d) at h + by_cases hd : d = Fin.last n + · have hz : (0 : Fin (n + 1)) < finRotate _ a := by + rw [Fin.lt_def, coe_finRotate_of_ne_last ha] + exact Nat.zero_lt_succ _ + rw [hd, finRotate_last] at h + exact hG 0 (finRotate _ a) (finRotate _ b) (finRotate _ c) hz hab' hbc' ⟨h.2.symm,h.1⟩ + · have hcd' : finRotate _ c < finRotate _ d := by + rw [Fin.lt_def, coe_finRotate_of_ne_last hc, coe_finRotate_of_ne_last hd] + exact Nat.add_lt_add_right hcd 1 + exact hG _ _ _ _ hab' hbc' hcd' h + +lemma noncrossing_comap_iterate {n : ℕ} {G : SimpleGraph (Fin (n + 1))} + (hG : Noncrossing G) (k : ℕ) : Noncrossing (G.comap ((finRotate (n + 1))^[k])) := by + induction k with + | zero => exact hG + | succ k ih => + have h := noncrossing_comap_rotate ih + simpa only [Function.iterate_succ, SimpleGraph.comap_comap] using h + +lemma noncrossing_comap_cycle {n : ℕ} {G : SimpleGraph (Fin (n + 1))} + (hG : Noncrossing G) (a : Fin (n + 1)) : Noncrossing (G.comap (finCycle a)) := by + rw [finCycle_eq_finRotate_iterate] + exact noncrossing_comap_iterate hG a.val + + +/-- An edge cannot leave the strict interior of a chord without meeting one +of the chord endpoints. -/ +theorem adj_stays_between {n : ℕ} {G : SimpleGraph (Fin n)} + (hnc : Noncrossing G) {a b x y : Fin n} (hab : G.Adj a b) + (hax : a < x) (hxb : x < b) (hxy : G.Adj x y) + (hya : y ≠ a) (hyb : y ≠ b) : a < y ∧ y < b := by + have hleft : ¬ y < a := by + intro h + exact hnc y a x b h hax hxb ⟨hxy.symm, hab⟩ + have hright : ¬ b < y := by + intro h + exact hnc a x b y hax hxb h ⟨hab, hxy⟩ + constructor <;> omega + +/-- A column word avoiding the endpoints of a chord remains on its starting +strict side. This is the induction behind the chord-separation lemma. -/ +theorem walk_stays_between {n : ℕ} {G : SimpleGraph (Fin n)} + (hnc : Noncrossing G) {a b x y : Fin n} (hab : G.Adj a b) + (p : G.Walk x y) (hx : a < x ∧ x < b) + (ha : a ∉ p.support) (hb : b ∉ p.support) : a < y ∧ y < b := by + induction p with + | nil => exact hx + | @cons x z y hxz p ih => + have haz : z ≠ a := by + intro h + apply ha + exact List.mem_cons_of_mem x (h ▸ p.start_mem_support) + have hbz : z ≠ b := by + intro h + apply hb + exact List.mem_cons_of_mem x (h ▸ p.start_mem_support) + have hz := adj_stays_between hnc hab hx.1 hx.2 hxz haz hbz + exact ih hz (fun h => ha (by simp [h])) (fun h => hb (by simp [h])) + +/-- Geometry, Lemma `geo:chord-separation`, with a cut in the circular order +outside the chosen strict interval. It applies to paths as well as walks. -/ +theorem chord_separation {n : ℕ} {G : SimpleGraph (Fin n)} + (hnc : Noncrossing G) {a b x y : Fin n} (hab : G.Adj a b) + (p : G.Walk x y) (hx : a < x ∧ x < b) + (hy : y < a ∨ b < y) : a ∈ p.support ∨ b ∈ p.support := by + by_contra h + push Not at h + have hi := walk_stays_between hnc hab p hx h.1 h.2 + rcases hy with hy | hy <;> omega + +/-- Occurrence of a step of the word that skips the specified index strictly. -/ +def JumpsAcross {n : ℕ} {G : SimpleGraph (Fin n)} (i : Fin n) + {x y : Fin n} (p : G.Walk x y) : Prop := + ∃ e ∈ p.darts, (e.fst < i ∧ i < e.snd) ∨ (e.snd < i ∧ i < e.fst) + +/-- Geometry, Lemma `geo:skipping`: passage from one side of an index to the +other either visits it or has a step jumping strictly across it. -/ +theorem visits_or_skips {n : ℕ} {G : SimpleGraph (Fin n)} {i x y : Fin n} + (p : G.Walk x y) (hx : x < i) (hy : i < y) : + i ∈ p.support ∨ JumpsAcross i p := by + induction p with + | nil => omega + | @cons x z y hxz p ih => + by_cases hz : z = i + · left + exact List.mem_cons_of_mem x (hz ▸ p.start_mem_support) + by_cases hzi : z < i + · rcases ih hzi hy with hm | ⟨e, he, hcross⟩ + · left + simp [hm] + · right + exact ⟨e, by simp [he], hcross⟩ + · right + refine ⟨⟨(x, z), hxz⟩, ?_, Or.inl ⟨hx, ?_⟩⟩ + · simp + · change i < z + omega + +/-- A connected set is a barrier between any two of its vertices in the +linear order. The edge and the set's connecting paths may belong to different +subgraphs; only noncrossing in the common ambient graph matters. -/ +lemma adj_between_connected {n : ℕ} {G : SimpleGraph (Fin n)} + (hnc : Noncrossing G) {S : Set (Fin n)} (hS : (G.induce S).Preconnected) + {a b x y : Fin n} (ha : a ∈ S) (hb : b ∈ S) + (hx : a < x ∧ x < b) (hxy : G.Adj x y) (hxs : x ∉ S) (hys : y ∉ S) : + a < y ∧ y < b := by + have hya : y ≠ a := fun h => hys (h ▸ ha) + have hyb : y ≠ b := fun h => hys (h ▸ hb) + obtain ⟨q⟩ := hS ⟨a, ha⟩ ⟨b, hb⟩ + let p := q.map (SimpleGraph.Embedding.induce S).toHom + have hmem : ∀ v ∈ p.support, v ∈ S := by + intro v hv + obtain ⟨w, _, hw⟩ := List.mem_map.mp (by simpa only [p, SimpleGraph.Walk.support_map] using hv) + exact hw ▸ w.property + have hpx : x ∉ p.support := fun h => hxs (hmem x h) + have hpy : y ∉ p.support := fun h => hys (hmem y h) + have hleft : ¬ y < a := by + intro h + have he := chord_separation hnc hxy.symm p ⟨h, hx.1⟩ (Or.inr hx.2) + exact he.elim hpy hpx + have hright : ¬ b < y := by + intro h + have he := chord_separation hnc hxy p.reverse ⟨hx.2, h⟩ (Or.inl hx.1) + exact he.elim (by simpa only [SimpleGraph.Walk.support_reverse, List.mem_reverse] using hpx) + (by simpa only [SimpleGraph.Walk.support_reverse, List.mem_reverse] using hpy) + constructor <;> omega + +/-- Paths avoiding a connected set have constant membership in every interval +whose endpoints belong to that set. This is the cut-independent content of +`geo:gap`: such a path stays in one open circular gap. -/ +lemma walk_same_gap {n : ℕ} {G : SimpleGraph (Fin n)} + (hnc : Noncrossing G) {S : Set (Fin n)} (hS : (G.induce S).Preconnected) + {x y : Fin n} (p : G.Walk x y) (hp : ∀ v ∈ p.support, v ∉ S) + {a b : Fin n} (ha : a ∈ S) (hb : b ∈ S) : + (a < x ∧ x < b) ↔ (a < y ∧ y < b) := by + suffices ∀ {x y : Fin n} (p : G.Walk x y), (∀ v ∈ p.support, v ∉ S) → + a < x ∧ x < b → a < y ∧ y < b by + constructor + · exact this p hp + · apply this p.reverse + simpa only [SimpleGraph.Walk.support_reverse, List.mem_reverse] using hp + intro x y p hp hx + induction p with + | nil => exact hx + | @cons x z y hxz p ih => + have hz := adj_between_connected hnc hS ha hb hx hxz + (hp x (by simp)) (hp z (List.mem_cons_of_mem _ p.start_mem_support)) + exact ih (fun v hv => hp v (by simp [hv])) hz + +/-- Disjoint connected vertex sets cannot have representatives in alternating +circular order. This upgrades the individual-chord barrier to branch sets. -/ +lemma connected_noninterleaving {n : ℕ} {G : SimpleGraph (Fin n)} + (hnc : Noncrossing G) {S T : Set (Fin n)} + (hS : (G.induce S).Preconnected) (hT : (G.induce T).Preconnected) + (hdis : Disjoint S T) {a b c d : Fin n} + (ha : a ∈ S) (hb : b ∈ T) (hc : c ∈ S) (hd : d ∈ T) + (hab : a < b) (hbc : b < c) (hcd : c < d) : False := by + obtain ⟨q⟩ := hT ⟨b, hb⟩ ⟨d, hd⟩ + let p := q.map (SimpleGraph.Embedding.induce T).toHom + have hp : ∀ v ∈ p.support, v ∉ S := by + intro v hv hvs + obtain ⟨w, _, hw⟩ := List.mem_map.mp (by simpa only [p, SimpleGraph.Walk.support_map] using hv) + have hvt : v ∈ T := hw ▸ w.property + exact Set.disjoint_left.mp hdis hvs hvt + have hi := (walk_same_gap hnc hS p hp ha hc).mp ⟨hab, hbc⟩ + exact (not_lt_of_ge hcd.le) hi.2 + +/-- A genuine finite branch-set model of a graph minor. Each branch is +nonempty and connected; branches are disjoint and edges are witnessed by +actual ambient edges. No topological or minor-exclusion axiom is hidden here. -/ +structure BranchModel {n : ℕ} {W : Type*} (H : SimpleGraph W) + (G : SimpleGraph (Fin n)) where + branch : W → Set (Fin n) + nonempty : ∀ w, (branch w).Nonempty + connected : ∀ w, (G.induce (branch w)).Preconnected + disjoint : Pairwise (fun i j => Disjoint (branch i) (branch j)) + edge : ∀ {i j}, H.Adj i j → ∃ a ∈ branch i, ∃ b ∈ branch j, G.Adj a b + +namespace BranchModel + +variable {n : ℕ} {W : Type*} {H : SimpleGraph W} {G : SimpleGraph (Fin n)} + +lemma representative_injective (B : BranchModel H G) (r : W → Fin n) + (hr : ∀ i, r i ∈ B.branch i) : Function.Injective r := by + intro i j hij + by_contra h + exact Set.disjoint_left.mp (B.disjoint h) (hr i) (hij ▸ hr j) + +lemma union_connected (B : BranchModel H G) {i j : W} (h : H.Adj i j) : + (G.induce (B.branch i ∪ B.branch j)).Connected := by + obtain ⟨a, ha, b, hb, hab⟩ := B.edge h + exact SimpleGraph.connected_induce_union (B.connected i) (B.connected j) ha hb hab + +/-- Noncrossing is inherited by every genuine branch-set minor, using any +chosen representative of each branch. This proves the needed minor closure +directly from walk separation, without a planar cone or a Jordan-curve axiom. -/ +lemma noncrossing (B : BranchModel H G) (hnc : Noncrossing G) + (r : W ↪ Fin n) (hr : ∀ i, r i ∈ B.branch i) : Noncrossing (H.map r) := by + intro a b c d hab hbc hcd he + obtain ⟨i, j, hij, rfl, rfl⟩ := (SimpleGraph.map_adj r H a c).mp he.1 + obtain ⟨k, l, hkl, rfl, rfl⟩ := (SimpleGraph.map_adj r H b d).mp he.2 + apply connected_noninterleaving hnc (B.union_connected hij).preconnected + (B.union_connected hkl).preconnected _ (Or.inl (hr i)) (Or.inl (hr k)) + (Or.inr (hr j)) (Or.inr (hr l)) hab hbc hcd + apply Set.disjoint_union_left.mpr + constructor <;> apply Set.disjoint_union_right.mpr + · constructor + · exact B.disjoint (fun h => (ne_of_lt hab) (congrArg r h)) + · exact B.disjoint (fun h => (ne_of_lt (hab.trans (hbc.trans hcd))) (congrArg r h)) + · constructor + · exact B.disjoint (fun h => (ne_of_lt hbc) (congrArg r h).symm) + · exact B.disjoint (fun h => (ne_of_lt hcd) (congrArg r h)) + +end BranchModel + +/-- For two fixed hubs in a noncrossing graph, two distinct common neighbors +must lie on opposite open circular arcs of the hubs. -/ +lemma common_neighbors_opposite {n : ℕ} {G : SimpleGraph (Fin n)} + (hnc : Noncrossing G) {a b c d : Fin n} (hab : a < b) (hcd : c ≠ d) + (hac : G.Adj a c) (had : G.Adj a d) (hbc : G.Adj b c) (hbd : G.Adj b d) : + (a < c ∧ c < b) ↔ ¬ (a < d ∧ d < b) := by + have hac' := hac.ne + have had' := had.ne + have hbc' := hbc.ne + have hbd' := hbd.ne + have h1 : ¬ (a < c ∧ c < d ∧ d < b) := fun h => + hnc a c d b h.1 h.2.1 h.2.2 ⟨had, hbc.symm⟩ + have h2 : ¬ (a < d ∧ d < c ∧ c < b) := fun h => + hnc a d c b h.1 h.2.1 h.2.2 ⟨hac, hbd.symm⟩ + have h3 : ¬ (c < d ∧ d < a) := fun h => + hnc c d a b h.1 h.2 hab ⟨hac.symm, hbd.symm⟩ + have h4 : ¬ (d < c ∧ c < a) := fun h => + hnc d c a b h.1 h.2 hab ⟨had.symm, hbc.symm⟩ + have h5 : ¬ (b < c ∧ c < d) := fun h => + hnc a b c d hab h.1 h.2 ⟨hac, hbd⟩ + have h6 : ¬ (b < d ∧ d < c) := fun h => + hnc a b d c hab h.1 h.2 ⟨had, hbc⟩ + have h7 : ¬ (c < a ∧ b < d) := fun h => + hnc c a b d h.1 hab h.2 ⟨hbc.symm, had⟩ + have h8 : ¬ (d < a ∧ b < c) := fun h => + hnc d a b c h.1 hab h.2 ⟨hbd.symm, hac⟩ + omega + +lemma no_three_common_neighbors {n : ℕ} {G : SimpleGraph (Fin n)} + (hnc : Noncrossing G) {a b c d e : Fin n} (hab : a ≠ b) + (hcd : c ≠ d) (hce : c ≠ e) (hde : d ≠ e) + (hac : G.Adj a c) (had : G.Adj a d) (hae : G.Adj a e) + (hbc : G.Adj b c) (hbd : G.Adj b d) (hbe : G.Adj b e) : False := by + rcases lt_or_gt_of_ne hab with hab | hab + · have h1 := common_neighbors_opposite hnc hab hcd hac had hbc hbd + have h2 := common_neighbors_opposite hnc hab hce hac hae hbc hbe + have h3 := common_neighbors_opposite hnc hab hde had hae hbd hbe + tauto + · have h1 := common_neighbors_opposite hnc hab hcd hbc hbd hac had + have h2 := common_neighbors_opposite hnc hab hce hbc hbe hac hae + have h3 := common_neighbors_opposite hnc hab hde hbd hbe had hae + tauto + +/-- Geometry `geo:outerplanar`: no noncrossing circular graph has a +branch-set minor with two hubs and three distinct common neighbors. -/ +lemma BranchModel.no_three_common_neighbors {n : ℕ} {W : Type*} + {H : SimpleGraph W} {G : SimpleGraph (Fin n)} (B : BranchModel H G) + (hnc : Noncrossing G) {a b c d e : W} (hab : a ≠ b) + (hcd : c ≠ d) (hce : c ≠ e) (hde : d ≠ e) + (hac : H.Adj a c) (had : H.Adj a d) (hae : H.Adj a e) + (hbc : H.Adj b c) (hbd : H.Adj b d) (hbe : H.Adj b e) : False := by + classical + let r : W → Fin n := fun i => (B.nonempty i).choose + have hr : ∀ i, r i ∈ B.branch i := fun i => (B.nonempty i).choose_spec + let f : W ↪ Fin n := ⟨r, B.representative_injective r hr⟩ + have he {i j : W} (h : H.Adj i j) : (H.map f).Adj (f i) (f j) := + (SimpleGraph.map_adj f H (f i) (f j)).mpr ⟨i, j, h, rfl, rfl⟩ + exact PlanarL1.ColumnOrder.no_three_common_neighbors (B.noncrossing hnc f hr) + (fun h => hab (f.injective h)) (fun h => hcd (f.injective h)) + (fun h => hce (f.injective h)) (fun h => hde (f.injective h)) + (he hac) (he had) (he hae) (he hbc) (he hbd) (he hbe) + +/-- Trimming a connector after its last visit to one set and before its first +visit to the other. The nonadjacency assumption guarantees a nonempty core. +The proof minimizes the number of edges, not the metric length. -/ +lemma connector_core {V : Type*} {G : SimpleGraph V} {C L T : Set V} + (hCL : Disjoint C L) (hno : ∀ x ∈ C, ∀ y ∈ L, ¬ G.Adj x y) + {x y : V} (hx : x ∈ C) (hy : y ∈ L) (p : G.Walk x y) + (hp : ∀ v ∈ p.support, v ∈ T) : + ∃ K : Set V, K.Nonempty ∧ (G.induce K).Preconnected ∧ K ⊆ T ∧ + Disjoint K C ∧ Disjoint K L ∧ + (∃ a ∈ C, ∃ b ∈ K, G.Adj a b) ∧ + (∃ a ∈ L, ∃ b ∈ K, G.Adj a b) := by + classical + let P : ℕ → Prop := fun m => ∃ a ∈ C, ∃ b ∈ L, ∃ q : G.Walk a b, + q.length = m ∧ ∀ v ∈ q.support, v ∈ T + have hex : ∃ m, P m := ⟨p.length, x, hx, y, hy, p, rfl, hp⟩ + obtain ⟨a, ha, b, hb, q, hlen, hmem⟩ := Nat.find_spec hex + have hmin {c d : V} (hc : c ∈ C) (hd : d ∈ L) (r : G.Walk c d) + (hr : ∀ v ∈ r.support, v ∈ T) : q.length ≤ r.length := by + rw [hlen] + exact Nat.find_min' hex ⟨c, hc, d, hd, r, rfl, hr⟩ + cases q with + | nil => exact False.elim (Set.disjoint_left.mp hCL ha hb) + | @cons a c b hac q => + have hq : ¬ q.Nil := by + intro h + have he := h.eq + subst b + exact hno a ha c hb hac + let r := q.dropLast + have hlast : G.Adj q.penultimate b := q.adj_penultimate hq + have hrmem : ∀ v ∈ r.support, v ∈ T := by + intro v hv + apply hmem v + apply List.mem_cons_of_mem + exact List.mem_of_mem_dropLast (by simpa only [r, q.support_dropLast hq] using hv) + have hshort : r.length + 1 = q.length := q.length_dropLast_add_one hq + have hout : ∀ v ∈ r.support, v ∉ C ∧ v ∉ L := by + intro v hv + constructor + · intro hvC + have hh := hmin hvC hb ((r.dropUntil v hv).concat hlast) (by + intro z hz + rw [SimpleGraph.Walk.support_concat] at hz + rcases List.mem_append.mp hz with hz | hz + · exact hrmem z (r.support_dropUntil_subset_support hv hz) + · have hz' : z = b := List.mem_singleton.mp hz + subst z + exact hmem b (SimpleGraph.Walk.cons hac q).end_mem_support) + have hd := r.length_dropUntil_le_length hv + simp only [SimpleGraph.Walk.length_concat, SimpleGraph.Walk.length_cons] at hh + omega + · intro hvL + have hh := hmin ha hvL (SimpleGraph.Walk.cons hac (r.takeUntil v hv)) (by + intro z hz + rcases List.mem_cons.mp hz with hz | hz + · subst z + exact hmem a (SimpleGraph.Walk.cons hac q).start_mem_support + · exact hrmem z (r.support_takeUntil_subset_support hv hz)) + have hd := r.length_takeUntil_le_length hv + simp only [SimpleGraph.Walk.length_cons] at hh + omega + refine ⟨{v | v ∈ r.support}, ⟨c, r.start_mem_support⟩, + r.connected_induce_support.preconnected, hrmem, ?_, ?_, + ⟨a, ha, c, r.start_mem_support, hac⟩, + ⟨b, hb, q.penultimate, r.end_mem_support, hlast.symm⟩⟩ + · exact Set.disjoint_left.mpr (fun v hv hvC => (hout v hv).1 hvC) + · exact Set.disjoint_left.mpr (fun v hv hvL => (hout v hv).2 hvL) + +/-- Three disjoint connected connector cores between two disjoint connected +sets would give the forbidden `K₂,₃` minor. -/ +lemma no_three_cores {n : ℕ} {G : SimpleGraph (Fin n)} (hnc : Noncrossing G) + {C L : Set (Fin n)} (hC : C.Nonempty) (hL : L.Nonempty) + (hc : (G.induce C).Preconnected) (hl : (G.induce L).Preconnected) + (hCL : Disjoint C L) (K : Fin 3 → Set (Fin n)) + (hne : ∀ i, (K i).Nonempty) (hconn : ∀ i, (G.induce (K i)).Preconnected) + (hdis : Pairwise (fun i j => Disjoint (K i) (K j))) + (hdC : ∀ i, Disjoint (K i) C) (hdL : ∀ i, Disjoint (K i) L) + (heC : ∀ i, ∃ a ∈ C, ∃ b ∈ K i, G.Adj a b) + (heL : ∀ i, ∃ a ∈ L, ∃ b ∈ K i, G.Adj a b) : False := by + let H := completeBipartiteGraph Bool (Fin 3) + let B : BranchModel H G := { + branch := Sum.elim (fun b : Bool => cond b C L) K + nonempty := by + intro i + rcases i with i | i + · cases i + · exact hL + · exact hC + · exact hne i + connected := by + intro i + rcases i with i | i + · cases i + · exact hl + · exact hc + · exact hconn i + disjoint := by + intro i j hij + rcases i with i | i <;> rcases j with j | j + · cases i <;> cases j + · exact False.elim (hij rfl) + · exact hCL.symm + · exact hCL + · exact False.elim (hij rfl) + · cases i + · exact (hdL j).symm + · exact (hdC j).symm + · cases j + · exact hdL i + · exact hdC i + · exact hdis (fun h => hij (congrArg Sum.inr h)) + edge := by + intro i j hij + rcases i with i | i <;> rcases j with j | j + · simp [H, completeBipartiteGraph] at hij + · cases i + · exact heL j + · exact heC j + · cases j + · obtain ⟨a, ha, b, hb, hab⟩ := heL i + exact ⟨b, hb, a, ha, hab.symm⟩ + · obtain ⟨a, ha, b, hb, hab⟩ := heC i + exact ⟨b, hb, a, ha, hab.symm⟩ + · simp [H, completeBipartiteGraph] at hij } + apply B.no_three_common_neighbors hnc + (a := Sum.inl false) (b := Sum.inl true) + (c := Sum.inr 0) (d := Sum.inr 1) (e := Sum.inr 2) + all_goals simp [H, completeBipartiteGraph] + +/-- The projected disjoint short portions used in the two-portals argument +cannot exist. This includes the trimming and nonempty-interior justifications. -/ +lemma no_three_connectors {n : ℕ} {G : SimpleGraph (Fin n)} (hnc : Noncrossing G) + {C L : Set (Fin n)} (hc : (G.induce C).Preconnected) + (hl : (G.induce L).Preconnected) (hCL : Disjoint C L) + (hno : ∀ x ∈ C, ∀ y ∈ L, ¬ G.Adj x y) + (x y : Fin 3 → Fin n) (hx : ∀ i, x i ∈ C) (hy : ∀ i, y i ∈ L) + (p : ∀ i, G.Walk (x i) (y i)) + (hdis : Pairwise (fun i j => Disjoint + {v | v ∈ (p i).support} {v | v ∈ (p j).support})) : False := by + classical + have hcores := fun i => connector_core hCL hno (hx i) (hy i) (p i) (fun _ h => h) + choose K hne hk hsub hdC hdL heC heL using hcores + exact no_three_cores hnc ⟨x 0, hx 0⟩ ⟨y 0, hy 0⟩ hc hl hCL K hne hk + (fun i j hij => (hdis hij).mono (hsub i) (hsub j)) hdC hdL heC heL + +/-- The vertices of an induced-graph component, as a set in the original +vertex type. Components here are Mathlib's actual reachability quotients. -/ +def componentColumns {V : Type*} {G : SimpleGraph V} {S : Set V} + (C : (G.induce S).ConnectedComponent) : Set V := Subtype.val '' C.supp + +lemma componentColumns_subset {V : Type*} {G : SimpleGraph V} {S : Set V} + (C : (G.induce S).ConnectedComponent) : componentColumns C ⊆ S := by + rintro _ ⟨v, _, rfl⟩ + exact v.property + +lemma componentColumns_connected {V : Type*} {G : SimpleGraph V} {S : Set V} + (C : (G.induce S).ConnectedComponent) : (G.induce (componentColumns C)).Connected := by + let f : C.toSimpleGraph →g G.induce (componentColumns C) := + ⟨fun v => ⟨v.val.val, ⟨v.val, v.property, rfl⟩⟩, fun h => h⟩ + have : Nonempty (componentColumns C) := by + obtain ⟨v, hv⟩ := C.nonempty_supp + exact ⟨⟨v.val, ⟨v, hv, rfl⟩⟩⟩ + refine ⟨?_⟩ + rintro ⟨x, hx⟩ ⟨y, hy⟩ + obtain ⟨u, hu, rfl⟩ := hx + obtain ⟨v, hv, rfl⟩ := hy + exact (C.reachable_toSimpleGraph hu hv).map f + +lemma componentColumns_adj {V : Type*} {G : SimpleGraph V} {S : Set V} + (C : (G.induce S).ConnectedComponent) {x y : V} + (hx : x ∈ componentColumns C) (hxy : G.Adj x y) (hy : y ∈ S) : + y ∈ componentColumns C := by + obtain ⟨u, hu, rfl⟩ := hx + exact ⟨⟨y, hy⟩, C.mem_supp_of_adj_mem_supp hu hxy, rfl⟩ + +/-- Any walk inside the induced vertex set propagates membership in an +actual connected component. -/ +lemma componentColumns_of_walk {V : Type*} {G : SimpleGraph V} {S : Set V} + (C : (G.induce S).ConnectedComponent) {x y : V} (p : G.Walk x y) + (hx : x ∈ componentColumns C) (hp : ∀ v ∈ p.support, v ∈ S) : + y ∈ componentColumns C := by + induction p with + | nil => exact hx + | @cons x z y hxz p ih => + exact ih (componentColumns_adj C hx hxz (hp z (by simp))) + (fun v hv => hp v (by simp [hv])) + +/-- A nonempty induced-connected subset lies in one actual component of +any larger induced subgraph. -/ +lemma exists_component_containing {V : Type*} {G : SimpleGraph V} {S T : Set V} + (hne : S.Nonempty) (hS : (G.induce S).Preconnected) (hST : S ⊆ T) : + ∃ C : (G.induce T).ConnectedComponent, S ⊆ componentColumns C := by + obtain ⟨x, hx⟩ := hne + let C := (G.induce T).connectedComponentMk ⟨x, hST hx⟩ + refine ⟨C, ?_⟩ + intro y hy + obtain ⟨w⟩ := hS ⟨x, hx⟩ ⟨y, hy⟩ + let p := w.map (SimpleGraph.Embedding.induce S).toHom + apply componentColumns_of_walk C p + · exact ⟨⟨x, hST hx⟩, rfl, rfl⟩ + · intro v hv + obtain ⟨z, _, hz⟩ := List.mem_map.mp + (by simpa only [p, SimpleGraph.Walk.support_map] using hv) + exact hz ▸ hST z.property + +/-- Components of one induced graph sharing an original vertex are equal. -/ +lemma component_eq_of_column {V : Type*} {G : SimpleGraph V} {S : Set V} + {C D : (G.induce S).ConnectedComponent} {i : V} + (hC : i ∈ componentColumns C) (hD : i ∈ componentColumns D) : C = D := by + obtain ⟨x, hx, rfl⟩ := hC + obtain ⟨y, hy, hyx⟩ := hD + have he : y = x := Subtype.ext hyx + subst y + exact SimpleGraph.ConnectedComponent.eq_of_common_vertex hx hy + +/-- The parent component under inclusion of vertex sets. -/ +def componentAbove {V : Type*} {G : SimpleGraph V} {S T : Set V} + (hST : S ⊆ T) (C : (G.induce S).ConnectedComponent) : + (G.induce T).ConnectedComponent := + C.map ⟨fun x => ⟨x.val, hST x.property⟩, fun h => h⟩ + +lemma componentColumns_above {V : Type*} {G : SimpleGraph V} {S T : Set V} + (hST : S ⊆ T) (C : (G.induce S).ConnectedComponent) : + componentColumns C ⊆ componentColumns (componentAbove hST C) := by + rintro _ ⟨x, hx, rfl⟩ + refine ⟨⟨x.val, hST x.property⟩, ?_, rfl⟩ + change (G.induce T).connectedComponentMk _ = componentAbove hST C + change (G.induce S).connectedComponentMk x = C at hx + rw [← hx] + rfl + +/-- A discrete connected union of two metric balls has controlled diameter. +The single edge allowance avoids assuming any continuous realization of the +column graph. It will be absorbed by the source's 10D constant. -/ +lemma connected_two_balls {V X : Type*} [PseudoMetricSpace X] {G : SimpleGraph V} + (hG : G.Preconnected) (f : V → X) (p q : X) {R a : ℝ} (hR : 0 ≤ R) + (ha : 0 ≤ a) (hedge : ∀ i j, G.Adj i j → dist (f i) (f j) ≤ a) + (hcover : ∀ i, dist (f i) p ≤ R ∨ dist (f i) q ≤ R) (x y : V) : + dist (f x) (f y) ≤ 4 * R + a := by + have near : ∀ i j, dist (f i) p ≤ R → dist (f j) q ≤ R → + dist p q ≤ 2 * R + a → dist (f i) (f j) ≤ 4 * R + a := by + intro i j hi hj hpq + have h₁ := dist_triangle (f i) p (f j) + have h₂ := dist_triangle p q (f j) + rw [dist_comm q (f j)] at h₂ + linarith + by_cases hpq : dist p q ≤ 2 * R + a + · rcases hcover x with hx | hx <;> rcases hcover y with hy | hy + · have h := dist_triangle (f x) p (f y) + rw [dist_comm p (f y)] at h + linarith + · exact near x y hx hy hpq + · rw [dist_comm] + exact near y x hy hx hpq + · have h := dist_triangle (f x) q (f y) + rw [dist_comm q (f y)] at h + linarith + · have stay : ∀ {i j} (w : G.Walk i j), dist (f i) p ≤ R → dist (f j) p ≤ R := by + intro i j w + induction w with + | nil => exact id + | @cons i z j hiz w ih => + intro hi + apply ih + rcases hcover z with hz | hz + · exact hz + · exfalso + apply hpq + have h₁ := dist_triangle p (f i) q + have h₂ := dist_triangle (f i) (f z) q + rw [dist_comm p (f i)] at h₁ + linarith [hedge i z hiz] + rcases hcover x with hx | hx + · obtain ⟨w⟩ := hG x y + have hy := stay w hx + have h := dist_triangle (f x) p (f y) + rw [dist_comm p (f y)] at h + linarith + · rcases hcover y with hy | hy + · obtain ⟨w⟩ := hG y x + have hx' := stay w hy + have h := dist_triangle (f x) p (f y) + rw [dist_comm p (f y)] at h + linarith + · have h := dist_triangle (f x) q (f y) + rw [dist_comm q (f y)] at h + linarith + +/-- Walks transport through a relabelling without introducing any new visited +columns. This is used to cut the circular order at a chosen root. -/ +lemma walk_comap_equiv {n : ℕ} {G : SimpleGraph (Fin n)} (e : Fin n ≃ Fin n) + {i j : Fin n} (w : G.Walk (e i) (e j)) : + ∃ p : (G.comap e).Walk i j, ∀ z ∈ p.support, e z ∈ w.support := by + let f := (SimpleGraph.Iso.comap e G).symm.toHom + have hi : f (e i) = i := e.symm_apply_apply i + have hj : f (e j) = j := e.symm_apply_apply j + refine ⟨(w.map f).copy hi hj, ?_⟩ + intro z hz + rw [SimpleGraph.Walk.support_copy, SimpleGraph.Walk.support_map, List.mem_map] at hz + obtain ⟨v,hv,hvz⟩ := hz + have he : e.symm v = z := hvz + rw [← he, e.apply_symm_apply] + exact hv + +/-- Collision inequality for a profile whose strict sublevels connect back to +zero. The ceiling is kept explicit: only thresholds at or below it are used. -/ +lemma collision {n : ℕ} {G : SimpleGraph (Fin (n + 1))} + (hnc : Noncrossing G) (f : Fin (n + 1) → ℝ) (D : ℝ) + (hbound : ∀ i, f i ≤ D) + (hpath : ∀ t ≤ D, ∀ i, f i < t → + ∃ w : G.Walk i 0, ∀ z ∈ w.support, f z < t) + {p q : Fin (n + 1)} (_hpq : p < q) (hadj : G.Adj p q) (heq : f p = f q) + (hp : p ≠ 0) (z : Fin (n + 1)) (hpz : p ≤ z) (hzq : z ≤ q) : f p ≤ f z := by + by_contra hn + have hz : f z < f p := lt_of_not_ge hn + have hpz' : p < z := lt_of_le_of_ne hpz (by intro he; subst z; exact (lt_irrefl _) hz) + have hzq' : z < q := lt_of_le_of_ne hzq (by intro he; subst z; exact (not_lt_of_ge heq.le) hz) + obtain ⟨w,hw⟩ := hpath _ (hbound p) z hz + have h0 : (0 : Fin (n + 1)) < p := lt_of_le_of_ne (Fin.zero_le p) (Ne.symm hp) + rcases chord_separation hnc hadj w ⟨hpz',hzq'⟩ (Or.inl h0) with hpw | hqw + · exact (lt_irrefl _) (hw p hpw) + · exact (not_lt_of_ge heq.le) (hw q hqw) + +end ColumnOrder + +end PlanarL1 + +end + +end OAI diff --git a/lean/OAI/Combinatorics/PlanarL1/Order.lean b/lean/OAI/Combinatorics/PlanarL1/Order.lean new file mode 100644 index 0000000000000000000000000000000000000000..4e8323a9e98971cee79988e55cd5012548de7585 --- /dev/null +++ b/lean/OAI/Combinatorics/PlanarL1/Order.lean @@ -0,0 +1,221 @@ +import Mathlib + +namespace OAI + +section + +namespace PlanarL1.Ordered + +/-- Running minimum toward a target in the circle cut at its root, index zero. +The exceptional root retains its global minimum. -/ +noncomputable def running {n : ℕ} (b : Fin (n + 1)) (f : Fin (n + 1) → ℝ) + (i : Fin (n + 1)) : ℝ := + if i = 0 then f 0 else (Finset.uIcc i b).inf' Finset.nonempty_uIcc f + +lemma running_zero {n : ℕ} (b : Fin (n + 1)) (f : Fin (n + 1) → ℝ) : + running b f 0 = f 0 := by simp [running] + +lemma running_le {n : ℕ} (b : Fin (n + 1)) (f : Fin (n + 1) → ℝ) + (i : Fin (n + 1)) : running b f i ≤ f i := by + by_cases hi : i = 0 + · simp [running, hi] + · simp only [running, ite_eq_right hi] + exact Finset.inf'_le f (Finset.left_mem_uIcc) + +lemma le_running {n : ℕ} (b : Fin (n + 1)) (f : Fin (n + 1) → ℝ) + (hmin : ∀ i, f 0 ≤ f i) (i : Fin (n + 1)) : f 0 ≤ running b f i := by + by_cases hi : i = 0 + · simp [running, hi] + · simp only [running, ite_eq_right hi] + exact Finset.le_inf' _ _ (fun j _ => hmin j) + +lemma running_target {n : ℕ} (b : Fin (n + 1)) (f : Fin (n + 1) → ℝ) : + running b f b = f b := by + by_cases hb : b = 0 + · simp [running, hb] + · simp [running, hb] + +lemma running_mono_left {n : ℕ} (b : Fin (n + 1)) (f : Fin (n + 1) → ℝ) + (hmin : ∀ i, f 0 ≤ f i) {i j : Fin (n + 1)} (hij : i ≤ j) (hjb : j ≤ b) : + running b f i ≤ running b f j := by + by_cases hi : i = 0 + · rw [hi, running_zero] + exact le_running b f hmin j + have hj : j ≠ 0 := by intro hj; subst j; exact hi (le_antisymm hij (Fin.zero_le i)) + simp only [running, ite_eq_right hi, ite_eq_right hj] + apply Finset.inf'_mono f _ Finset.nonempty_uIcc + intro z hz + simp only [Finset.mem_uIcc, min_eq_left (hij.trans hjb), max_eq_right (hij.trans hjb), min_eq_left hjb, max_eq_right hjb] at hz ⊢ + exact ⟨hij.trans hz.1, hz.2⟩ + +lemma running_mono_right {n : ℕ} (b : Fin (n + 1)) (f : Fin (n + 1) → ℝ) + {i j : Fin (n + 1)} (hbi : b ≤ i) (hij : i ≤ j) : + running b f j ≤ running b f i := by + by_cases hi : i = 0 + · have hb : b = 0 := le_antisymm (hi ▸ hbi) (Fin.zero_le b) + subst b + have hj : running 0 f j ≤ f 0 := by + by_cases hz : j = 0 + · simp [hz, running_zero] + · simp only [running, ite_eq_right hz] + exact Finset.inf'_le f Finset.right_mem_uIcc + simpa only [hi, running_zero] using hj + have hj : j ≠ 0 := by intro hj; subst j; exact hi (le_antisymm hij (Fin.zero_le i)) + simp only [running, ite_eq_right hi, ite_eq_right hj] + apply Finset.inf'_mono f _ Finset.nonempty_uIcc + intro z hz + simp only [Finset.mem_uIcc, min_eq_right hbi, max_eq_left hbi, min_eq_right (hbi.trans hij), max_eq_left (hbi.trans hij)] at hz ⊢ + exact ⟨hz.1, hz.2.trans hij⟩ + +/-- Collision inequality for a chord is exactly what is needed to make running +minima respect its switch, including chords that straddle the target. -/ +lemma running_switch {n : ℕ} (b : Fin (n + 1)) (f : Fin (n + 1) → ℝ) + (hmin : ∀ i, f 0 ≤ f i) {p q : Fin (n + 1)} (hpq : p < q) (he : f p = f q) + (hcollision : p ≠ 0 → ∀ z, p ≤ z → z ≤ q → f p ≤ f z) : + running b f p = running b f q := by + by_cases hp : p = 0 + · rw [hp, running_zero] + exact le_antisymm (le_running b f hmin q) ((running_le b f q).trans_eq (hp ▸ he).symm) + have hq : q ≠ 0 := by intro hz; subst q; exact (not_lt_of_ge (Fin.zero_le p)) hpq + simp only [running, ite_eq_right hp, ite_eq_right hq] + by_cases hqb : q ≤ b + · have hpb := hpq.le.trans hqb + apply le_antisymm + · apply Finset.inf'_mono f _ Finset.nonempty_uIcc + intro z hz + simp only [Finset.mem_uIcc, min_eq_left hqb, max_eq_right hqb, min_eq_left hpb, max_eq_right hpb] at hz ⊢ + exact ⟨hpq.le.trans hz.1, hz.2⟩ + · apply Finset.le_inf' + intro z hz + have hz' : p ≤ z ∧ z ≤ b := by + simpa only [Finset.mem_uIcc, min_eq_left hpb, max_eq_right hpb] using hz + by_cases hqz : q ≤ z + · exact Finset.inf'_le f (by simpa only [Finset.mem_uIcc, min_eq_left hqb, max_eq_right hqb] using And.intro hqz hz'.2) + · exact (Finset.inf'_le f Finset.left_mem_uIcc).trans + (he ▸ hcollision hp z hz'.1 (lt_of_not_ge hqz).le) + · by_cases hbp : b ≤ p + · have hbq := hbp.trans hpq.le + apply le_antisymm + · apply Finset.le_inf' + intro z hz + have hz' : b ≤ z ∧ z ≤ q := by + simpa only [Finset.mem_uIcc, min_eq_right hbq, max_eq_left hbq] using hz + by_cases hzp : z ≤ p + · exact Finset.inf'_le f (by simpa only [Finset.mem_uIcc, min_eq_right hbp, max_eq_left hbp] using And.intro hz'.1 hzp) + · exact (Finset.inf'_le f Finset.left_mem_uIcc).trans + (hcollision hp z (lt_of_not_ge hzp).le hz'.2) + · apply Finset.inf'_mono f _ Finset.nonempty_uIcc + intro z hz + simp only [Finset.mem_uIcc, min_eq_right hbp, max_eq_left hbp, min_eq_right hbq, max_eq_left hbq] at hz ⊢ + exact ⟨hz.1, hz.2.trans hpq.le⟩ + · have hpb : p ≤ b := (lt_of_not_ge hbp).le + have hbq : b ≤ q := (lt_of_not_ge hqb).le + have hleft : (Finset.uIcc p b).inf' Finset.nonempty_uIcc f = f p := by + apply le_antisymm (Finset.inf'_le f Finset.left_mem_uIcc) + apply Finset.le_inf' + intro z hz + have hz' : p ≤ z ∧ z ≤ b := by + simpa only [Finset.mem_uIcc, min_eq_left hpb, max_eq_right hpb] using hz + exact hcollision hp z hz'.1 (hz'.2.trans hbq) + have hright : (Finset.uIcc q b).inf' Finset.nonempty_uIcc f = f p := by + apply le_antisymm ((Finset.inf'_le f Finset.left_mem_uIcc).trans_eq he.symm) + apply Finset.le_inf' + intro z hz + have hz' : b ≤ z ∧ z ≤ q := by + simpa only [Finset.mem_uIcc, min_eq_right hbq, max_eq_left hbq] using hz + exact hcollision hp z (hpb.trans hz'.1) hz'.2 + exact hleft.trans hright.symm + +lemma finite_inf_lipschitz {X ι : Type*} [PseudoMetricSpace X] (S : Finset ι) + (hne : S.Nonempty) (f : ι → X → ℝ) (L : NNReal) + (hf : ∀ i ∈ S, LipschitzWith L (f i)) : + LipschitzWith L (fun x => S.inf' hne (fun i => f i x)) := by + have hbound (x y : X) : S.inf' hne (fun i => f i x) - S.inf' hne (fun i => f i y) ≤ + L * dist x y := by + obtain ⟨i, hi, he⟩ := Finset.exists_mem_eq_inf' hne (fun i => f i y) + have hl := (hf i hi).dist_le_mul x y + rw [Real.dist_eq] at hl + have hle := Finset.inf'_le (fun i => f i x) hi + rw [he] + linarith [(abs_le.mp hl).2] + apply LipschitzWith.of_dist_le_mul + intro x y + rw [Real.dist_eq, abs_le] + constructor + · have h := hbound y x + rw [dist_comm y x] at h + linarith + · exact hbound x y + +lemma running_lipschitz {n : ℕ} {X : Type*} [PseudoMetricSpace X] (b i : Fin (n + 1)) + (f : Fin (n + 1) → X → ℝ) (L : NNReal) (hf : ∀ j, LipschitzWith L (f j)) : + LipschitzWith L (fun x => running b (fun j => f j x) i) := by + by_cases hi : i = 0 + · simpa only [hi, running_zero] using hf 0 + · simp only [running, ite_eq_right hi] + exact finite_inf_lipschitz _ _ f L (fun j _ => hf j) + +end PlanarL1.Ordered + +end + +section + +namespace PlanarL1.Ordered + +lemma rotate_unimodal_neg {k : ℕ} (b : Fin (k+1)) (f : Fin (k+1) → ℝ) + (hmin : ∀ i, f 0 ≤ f i) + (hl : ∀ i j, i ≤ j → j ≤ b → f i ≤ f j) + (hr : ∀ i j, b ≤ i → i ≤ j → f j ≤ f i) : + (∀ i, -f b ≤ -f (i+b)) ∧ + (∀ i j : Fin (k+1), i ≤ j → j ≤ -b → -f (i+b) ≤ -f (j+b)) ∧ + (∀ i j : Fin (k+1), -b ≤ i → i ≤ j → -f (j+b) ≤ -f (i+b)) := by + have hmax (i : Fin (k+1)) : f i ≤ f b := by + rcases le_total i b with hi | hi + · exact hl i b hi le_rfl + · exact hr b i le_rfl hi + by_cases hb : b=0 + · have he (i : Fin (k+1)) : f i=f 0 := le_antisymm (hb ▸ hmax i) (hmin i) + simp only [he,le_refl,implies_true,and_self] + have hbpos : 0 < b.val := by exact Nat.pos_of_ne_zero (fun h => hb (Fin.ext h)) + have hv : (-b).val=k+1-b.val := by + simp only [Fin.val_neg,ite_eq_right hb] + have add_before (i : Fin (k+1)) (hi : i < -b) : (i+b).val=i.val+b.val := by + rw [Fin.val_add,Nat.mod_eq_of_lt] + change i.val < (-b).val at hi + rw [hv] at hi + omega + have add_after (i : Fin (k+1)) (hi : -b ≤ i) : + (i+b).val=i.val+b.val-(k+1) := by + rw [Fin.val_add,Nat.mod_eq_sub_mod (by change (-b).val ≤ i.val at hi; rw [hv] at hi; omega), + Nat.mod_eq_of_lt (by omega)] + refine ⟨fun i => neg_le_neg (hmax _),?_,?_⟩ + · intro i j hij hj + by_cases he : j = -b + · rw [he,neg_add_cancel] + exact neg_le_neg (hmin _) + · have hjs : j < -b := lt_of_le_of_ne hj he + have his : i < -b := hij.trans_lt hjs + apply neg_le_neg + apply hr + · change b.val ≤ (i+b).val + rw [add_before i his] + omega + · change (i+b).val ≤ (j+b).val + rw [add_before i his,add_before j hjs] + exact Nat.add_le_add_right hij b.val + · intro i j hi hij + apply neg_le_neg + apply hl + · change (i+b).val ≤ (j+b).val + rw [add_after i hi,add_after j (hi.trans hij)] + exact Nat.sub_le_sub_right (Nat.add_le_add_right hij b.val) _ + · change (j+b).val ≤ b.val + rw [add_after j (hi.trans hij)] + omega +end PlanarL1.Ordered + + +end + +end OAI diff --git a/lean/OAI/Combinatorics/PlanarL1/OrderedState.lean b/lean/OAI/Combinatorics/PlanarL1/OrderedState.lean new file mode 100644 index 0000000000000000000000000000000000000000..1198a4c7a5072033bb48d4d474f13a5e5b74731e --- /dev/null +++ b/lean/OAI/Combinatorics/PlanarL1/OrderedState.lean @@ -0,0 +1,524 @@ +import OAI.Combinatorics.PlanarL1.OrdinaryState + +namespace OAI + +section + +namespace PlanarL1.Columns.Model.Field +open scoped NNReal +variable {k : ℕ} {M : Model (k+1)} {I : Set ℝ} {L : ℝ≥0} + +noncomputable def negate (F : M.Field I L) : M.Field I L where + value i H := -F.value i H + vertical i := (F.vertical i).neg + switch i j H hs := congrArg Neg.neg (F.switch i j H hs) + +lemma ordered_negate (F : M.Field I L) {a b : Fin (k+1)} (ho : F.OrderedFrom a b) : + F.negate.OrderedFrom b a := by + have hrot (H : I) := Ordered.rotate_unimodal_neg (b-a) + (fun i => F.value (finCycle a i) H) + (by simpa only [finCycle_apply,zero_add] using fun i => ho.1 H (finCycle a i)) + (by simpa only [finCycle_symm_apply] using ho.2.1 H) + (by simpa only [finCycle_symm_apply] using ho.2.2 H) + have had (i : Fin (k+1)) : (i+(b-a))+a=i+b := by abel + have hbal : -(b-a)=a-b := by abel + refine ⟨?_,?_,?_⟩ + · intro H i + exact neg_le_neg (F.ordered_maximum ho H i) + · intro H i j hij hj + have hh := (hrot H).2.1 i j hij (by simpa only [hbal,finCycle_symm_apply] using hj) + simpa only [finCycle_apply,had,negate] using hh + · intro H i j hi hij + have hh := (hrot H).2.2 i j (by simpa only [hbal,finCycle_symm_apply] using hi) hij + simpa only [finCycle_apply,had,negate] using hh + +noncomputable def affine (F : M.Field I L) (c : ℝ) (q : ℝ≥0) : M.Field I (q*L) where + value i H := c+q*F.value i H + vertical i := by + apply LipschitzWith.of_dist_le_mul + intro H T + have hh := (F.vertical i).dist_le_mul H T + simp only [Real.dist_eq] at hh ⊢ + rw [show c+(q:ℝ)*F.value i H-(c+(q:ℝ)*F.value i T) = + (q:ℝ)*(F.value i H-F.value i T) by ring, abs_mul,abs_of_nonneg q.coe_nonneg] + simpa only [NNReal.coe_mul,mul_assoc] using mul_le_mul_of_nonneg_left hh q.coe_nonneg + switch i j H hs := by rw [F.switch i j H hs] + +lemma ordered_affine (F : M.Field I L) {a b : Fin (k+1)} (ho : F.OrderedFrom a b) + (c : ℝ) (q : ℝ≥0) : (F.affine c q).OrderedFrom a b := by + refine ⟨?_,?_,?_⟩ + · intro H i + simpa only [affine,add_comm] using add_le_add_left (mul_le_mul_of_nonneg_left (ho.1 H i) q.coe_nonneg) c + · intro H i j hij hj + simpa only [affine,add_comm] using add_le_add_left (mul_le_mul_of_nonneg_left (ho.2.1 H i j hij hj) q.coe_nonneg) c + · intro H i j hi hij + simpa only [affine,add_comm] using add_le_add_left (mul_le_mul_of_nonneg_left (ho.2.2 H i j hi hij) q.coe_nonneg) c + +end PlanarL1.Columns.Model.Field + + +namespace PlanarL1.Columns.Model +open MeasureTheory +open scoped NNReal + +namespace Field +variable {n : ℕ} {M : Model n} {I : Set ℝ} {L K : ℝ≥0} + +def weaken (F : M.Field I L) (h : L ≤ K) : M.Field I K where + value := F.value + vertical i := (F.vertical i).weaken h + switch := F.switch + +noncomputable def add (F : M.Field I L) (G : M.Field I K) : M.Field I (L+K) where + value i H := F.value i H+G.value i H + vertical i := (F.vertical i).add (G.vertical i) + switch i j H h := by rw [F.switch i j H h,G.switch i j H h] +end Field + +/-- The ordered-chart data. The base ordered field never +changes during this identifier's lifetime. The auxiliary field is replaced by +its actual signed increment history; its bound is 100, not an unbounded sum +of the individual increments. -/ +structure OrderedData {k : ℕ} (M : Model (k+1)) where + band : Set ℝ + closed : IsClosed band + convex : band.OrdConnected + base : M.Field band 4 + lower : Fin (k+1) + upper : Fin (k+1) + ordered : base.OrderedFrom lower upper + auxiliary : M.Field band 100 + +namespace OrderedData +variable {k : ℕ} {M : Model (k+1)} + +noncomputable def value (D : OrderedData M) (lam : ℝ≥0) (i : Fin (k+1)) (H : D.band) : ℝ := + D.base.value i H+lam*D.auxiliary.value i H + +noncomputable def field (D : OrderedData M) (lam : ℝ≥0) (hlam : lam ≤ (1:ℝ≥0)/100) : + M.Field D.band 5 := + (D.base.add (D.auxiliary.affine 0 lam)).weaken (by nlinarith) + +lemma field_value (D : OrderedData M) (lam : ℝ≥0) (hlam : lam ≤ (1:ℝ≥0)/100) + (i : Fin (k+1)) (H : D.band) : (D.field lam hlam).value i H=D.value lam i H := by + simp only [field,Field.weaken,Field.add,Field.affine,zero_add,value] + +/-- Install the spatial ordered branch O_F, with zero auxiliary history. +The boolean is the conversion back to the old chart orientation. Negation +exchanges, rather than discards, the two circular boundary columns. -/ +noncomputable def install {I : Set ℝ} (hI : IsClosed I) (hc : I.OrdConnected) + (L : M.Field I 1) (a b : Fin (k+1)) (ho : L.OrderedFrom a b) + (c : ℝ) (positive : Bool) : OrderedData M where + band := I + closed := hI + convex := hc + base := if positive then + (L.affine c 4).weaken (by norm_num) else + ((L.affine c 4).negate).weaken (by norm_num) + lower := if positive then a else b + upper := if positive then b else a + ordered := by + cases positive + · exact (L.affine c 4).ordered_negate (L.ordered_affine ho c 4) + · exact L.ordered_affine ho c 4 + auxiliary := (Field.constant M I 0).weaken (by norm_num) + +lemma install_value {I : Set ℝ} (hI : IsClosed I) (hc : I.OrdConnected) + (L : M.Field I 1) (a b : Fin (k+1)) (ho : L.OrderedFrom a b) + (c : ℝ) (positive : Bool) (lam : ℝ≥0) (i : Fin (k+1)) (H : I) : + (install hI hc L a b ho c positive).value lam i H = + if positive then c+4*L.value i H else -(c+4*L.value i H) := by + cases positive <;> simp [install,value,Field.weaken,Field.affine,Field.negate,Field.constant] +end OrderedData + +/-- System B has precisely the ordinary and ordered chart alternatives. -/ +inductive BData {k : ℕ} (M : Model (k+1)) + | ordinary : OrdinaryData M → BData M + | ordered : OrderedData M → BData M + +namespace BData +variable {k : ℕ} {M : Model (k+1)} + +def band : BData M → Set ℝ + | .ordinary D => D.band + | .ordered D => D.band + +lemma closed (D : BData M) : IsClosed D.band := by + cases D with + | ordinary D => exact D.closed + | ordered D => exact D.closed + +lemma convex (D : BData M) : D.band.OrdConnected := by + cases D with + | ordinary D => exact D.convex + | ordered D => exact D.convex + +noncomputable def value (lam : ℝ≥0) : (D : BData M) → Fin (k+1) → D.band → ℝ + | .ordinary D => D.value + | .ordered D => D.value lam + +noncomputable def field (lam : ℝ≥0) (hlam : lam ≤ (1:ℝ≥0)/100) : + (D : BData M) → M.Field D.band 5 + | .ordinary D => D.field.weaken (by norm_num) + | .ordered D => D.field lam hlam + +lemma field_value (lam : ℝ≥0) (hlam : lam ≤ (1:ℝ≥0)/100) (D : BData M) + (i : Fin (k+1)) (H : D.band) : (D.field lam hlam).value i H=D.value lam i H := by + cases D with + | ordinary D => rfl + | ordered D => exact D.field_value lam hlam i H + +/-- Component restriction is attached only to a genuine point-source chart; +the ordered formula is defined on every component of its recorded band. -/ +def Uses (D : BData M) (i : Fin (k+1)) : Prop := + match D with + | .ordinary C => ∀ r o, C.origin=some ⟨r,o⟩ → (M.activeGraph C.band).Reachable r i + | .ordered _ => True +end BData + +structure BState {k : ℕ} (M : Model (k+1)) (κ : ℝ) (lam : ℝ≥0) (Ω : Type*) + [MeasurableSpace Ω] (μ : Measure Ω) where + sets : SetSystem M Ω μ + count : ℕ + chart : Fin (count+1) → BData M + labels : Fin (count+1) → Threshold.Variables Ω μ + name : Fin (k+1) → ℝ → Fin (count+1) + height_in : ∀ i H, H ∈ (chart (name i H)).band + component_in : ∀ i H, (chart (name i H)).Uses i + switch_name : ∀ i j H, H ∈ M.heights i j → name i H = name j H + represents : ∀ ω i H, + (sets.activity ω).active i H ↔ Threshold.active (labels (name i H)) H + (κ*(chart (name i H)).value lam i ⟨H,height_in i H⟩) ω + +namespace BState +variable {k : ℕ} {M : Model (k+1)} {κ : ℝ} {lam : ℝ≥0} + {Ω : Type*} [MeasurableSpace Ω] {μ : Measure Ω} + +noncomputable def ofOrdinary (S : OrdinaryState M κ Ω μ) : BState M κ lam Ω μ where + sets := S.sets + count := S.count + chart a := .ordinary (S.chart a) + labels := S.labels + name := S.name + height_in := S.height_in + component_in := S.component_in + switch_name := S.switch_name + represents := S.represents + +noncomputable def initial (M : Model (k+1)) (κ : ℝ) (lam : ℝ≥0) : + BState M κ lam (Bool × ℝ) Threshold.labelMeasure := + ofOrdinary (OrdinaryState.initial M κ) + +noncomputable def lift (S : BState M κ lam Ω μ) : + BState M κ lam (Ω × Bool) (μ.prod Threshold.fair) where + sets := S.sets.lift + count := S.count + chart := S.chart + labels a := (S.labels a).lift + name := S.name + height_in := S.height_in + component_in := S.component_in + switch_name := S.switch_name + represents ω i H := S.represents ω.1 i H + +/-- Finite chart-table extension. Old identifiers are literally retained in the +right summand; installing a fresh chart never refines the old regions. -/ +noncomputable def append (S : BState M κ lam Ω μ) (B : SetSystem M Ω μ) + (m : ℕ) (D : Fin m → BData M) (Z : Fin m → Threshold.Variables Ω μ) + (choose : Fin (k+1) → ℝ → Option (Fin m)) + (hin : ∀ i H a, choose i H = some a → H ∈ (D a).band) + (hcomp : ∀ i H a, choose i H = some a → (D a).Uses i) + (hswitch : ∀ i j H, H ∈ M.heights i j → choose i H = choose j H) + (hold : ∀ ω i H, choose i H = none → + ((B.activity ω).active i H ↔ (S.sets.activity ω).active i H)) + (hnew : ∀ ω i H a (hc : choose i H = some a), + ((B.activity ω).active i H ↔ Threshold.active (Z a) H + (κ*(D a).value lam i ⟨H,hin i H a hc⟩) ω)) : BState M κ lam Ω μ where + sets := B + count := m+S.count + chart := Fin.addCases (m := m) (n := S.count+1) D S.chart + labels := Fin.addCases (m := m) (n := S.count+1) Z S.labels + name i H := match choose i H with + | none => Fin.natAdd m (S.name i H) + | some a => Fin.castAdd (S.count+1) a + height_in i H := by + cases hc : choose i H with + | none => simpa only [hc,Fin.addCases_right] using S.height_in i H + | some a => simpa only [hc,Fin.addCases_left] using hin i H a hc + component_in i H := by + let Uses (D : BData M) : Prop := D.Uses i + change Uses (Fin.addCases (m := m) (n := S.count+1) D S.chart + (match choose i H with + | none => Fin.natAdd m (S.name i H) + | some a => Fin.castAdd (S.count+1) a)) + cases hc : choose i H with + | none => + simp only [Fin.addCases_right] + exact S.component_in i H + | some a => + simp only [Fin.addCases_left] + exact hcomp i H a hc + switch_name i j H hh := by + have hc := hswitch i j H hh + rw [hc] + cases choose j H with + | none => exact congrArg (Fin.natAdd m) (S.switch_name i j H hh) + | some a => rfl + represents ω i H := by + let Rep (D : BData M) (Z : Threshold.Variables Ω μ) : Prop := + ∀ hi : H ∈ D.band, (B.activity ω).active i H ↔ + Threshold.active Z H (κ*D.value lam i ⟨H,hi⟩) ω + have hr : Rep + (Fin.addCases (m := m) (n := S.count+1) D S.chart + (match choose i H with + | none => Fin.natAdd m (S.name i H) + | some a => Fin.castAdd (S.count+1) a)) + (Fin.addCases (m := m) (n := S.count+1) Z S.labels + (match choose i H with + | none => Fin.natAdd m (S.name i H) + | some a => Fin.castAdd (S.count+1) a)) := by + cases hc : choose i H with + | none => + simp only [Fin.addCases_right] + intro hi + exact (hold ω i H hc).trans (S.represents ω i H) + | some a => + simp only [Fin.addCases_left] + intro hi + exact hnew ω i H a hc + exact hr _ + +/-- Deterministic chart distance on a common identifier, with no independence +assumed between different identifiers. -/ +lemma chart_distance (S : BState M κ lam Ω μ) (i j : Fin (k+1)) (H T : ℝ) + (he : S.name i H=S.name j T) : + (∫ ω, |(S.sets.activity ω).indicator i H-(S.sets.activity ω).indicator j T| ∂μ) = + max |H-T| |κ*(S.chart (S.name i H)).value lam i ⟨H,S.height_in i H⟩- + κ*(S.chart (S.name j T)).value lam j ⟨T,S.height_in j T⟩| := by + have hid (i : Fin (k+1)) (H : ℝ) (ω : Ω) : + (S.sets.activity ω).indicator i H = Threshold.chartValue H + (κ*(S.chart (S.name i H)).value lam i ⟨H,S.height_in i H⟩) + ((S.labels (S.name i H)).value ω) := by + simp only [Activity.indicator,S.represents,Threshold.active,Threshold.chartValue,Threshold.half] + simp_rw [hid] + rw [show S.labels (S.name j T)=S.labels (S.name i H) from congrArg S.labels he.symm] + exact (S.labels (S.name i H)).distance _ _ _ _ + +end BState +end PlanarL1.Columns.Model + + + +end + +section + +namespace PlanarL1.Columns.Model +open MeasureTheory +open scoped NNReal +attribute [local instance] Classical.propDecidable +variable {k : ℕ} {M : Model (k+1)} {κ : ℝ} {lam : ℝ≥0} + {Ω : Type*} [MeasurableSpace Ω] {μ : Measure Ω} + +namespace BState +variable (S : BState M κ lam Ω μ) + +noncomputable def oldValue (i : Fin (k+1)) (H : ℝ) : ℝ := + κ*(S.chart (S.name i H)).value lam i ⟨H,S.height_in i H⟩ + +lemma oldValue_eq (i : Fin (k+1)) (H : ℝ) (a : Fin (S.count+1)) + (h : S.name i H=a) : S.oldValue i H = + κ*(S.chart a).value lam i ⟨H,by simpa only [h] using S.height_in i H⟩ := by + subst a + rfl + +noncomputable def newValue (F : ∀ a, M.Field (S.chart a).band 5) + (i : Fin (k+1)) (H : ℝ) : ℝ := + κ*(F (S.name i H)).value i ⟨H,S.height_in i H⟩ + +lemma newValue_eq (F : ∀ a, M.Field (S.chart a).band 5) + (i : Fin (k+1)) (H : ℝ) (a : Fin (S.count+1)) (h : S.name i H=a) : + S.newValue F i H = κ*(F a).value i ⟨H,by simpa only [h] using S.height_in i H⟩ := by + subst a + rfl + +lemma newValue_lipschitz (F : ∀ a, M.Field (S.chart a).band 5) (hk : 0 ≤ κ) + (i : Fin (k+1)) (H T : ℝ) (he : S.name i H=S.name i T) : + |S.newValue F i H-S.newValue F i T| ≤ (κ*5)*|H-T| := by + rw [S.newValue_eq F i H (S.name i H) rfl,S.newValue_eq F i T (S.name i H) he.symm] + rw [← mul_sub,abs_mul,abs_of_nonneg hk] + have hb := ((F (S.name i H)).vertical i).dist_le_mul + ⟨H,S.height_in i H⟩ ⟨T,by simpa only [he] using S.height_in i T⟩ + simp only [Real.dist_eq,Subtype.dist_eq,NNReal.coe_ofNat] at hb + simpa only [mul_assoc] using mul_le_mul_of_nonneg_left hb hk + +lemma oldValue_lipschitz (hk : 0 ≤ κ) (hlam : lam ≤ (1:ℝ≥0)/100) + (i : Fin (k+1)) (H T : ℝ) (he : S.name i H=S.name i T) : + |S.oldValue i H-S.oldValue i T| ≤ (κ*5)*|H-T| := by + have hf (i H) : S.newValue (fun a => (S.chart a).field lam hlam) i H=S.oldValue i H := by + simp only [newValue,oldValue,BData.field_value] + simpa only [hf] using S.newValue_lipschitz (fun a => (S.chart a).field lam hlam) hk i H T he + +/-- A simultaneous same-identifier update, defined by the actual new fields. +The boundary estimate is exactly what the ambient complement taper provides. +The name map is retained literally; it is not refined to a partition with +better-behaved boundaries. -/ +noncomputable def fieldActivity (F : ∀ a, M.Field (S.chart a).band 5) + (hk : 0 ≤ κ) (hsmall : κ*5 ≤ 1/2) (hlam : lam ≤ (1:ℝ≥0)/100) + (hd : ∀ i H T, S.name i H≠S.name i T → + |S.newValue F i H-S.oldValue i H| ≤ |H-T|/8) + (ω : Ω) : Activity M where + active i H := Threshold.active (S.labels (S.name i H)) H (S.newValue F i H) ω + increasing i H T hHT := by + apply Threshold.named_nested (S.name i) S.labels (S.oldValue i) (S.newValue F i) + (fun H ω => (S.sets.activity ω).active i H) + (fun ω s t hst => (S.sets.activity ω).increasing i s t hst) + (fun H ω => S.represents ω i H) + (fun s t he => (S.oldValue_lipschitz hk hlam i s t he).trans (by + nlinarith [abs_nonneg (s-t)])) + (fun s t he => (S.newValue_lipschitz F hk i s t he).trans (by + nlinarith [abs_nonneg (s-t)])) + (hd i) ω hHT + switch i j H hh := by + have he := S.switch_name i j H hh + have hv : S.newValue F i H=S.newValue F j H := by + rw [S.newValue_eq F i H (S.name i H) rfl, + S.newValue_eq F j H (S.name i H) he.symm] + rw [(F (S.name i H)).switch i j ⟨H,S.height_in i H⟩ hh] + simp only [he,hv] + +lemma field_indicator (F : ∀ a, M.Field (S.chart a).band 5) + (hk : 0 ≤ κ) (hsmall : κ*5 ≤ 1/2) (hlam : lam ≤ (1:ℝ≥0)/100) + (hd : ∀ i H T, S.name i H≠S.name i T → + |S.newValue F i H-S.oldValue i H| ≤ |H-T|/8) + (ω : Ω) (i : Fin (k+1)) (H : ℝ) : + (S.fieldActivity F hk hsmall hlam hd ω).indicator i H = + Threshold.chartValue H (S.newValue F i H) ((S.labels (S.name i H)).value ω) := rfl + +lemma old_indicator (ω : Ω) (i : Fin (k+1)) (H : ℝ) : + (S.sets.activity ω).indicator i H = + Threshold.chartValue H (S.oldValue i H) ((S.labels (S.name i H)).value ω) := by + simp only [Activity.indicator,S.represents,oldValue, + Threshold.chartValue,Threshold.half,Threshold.active] + rfl + +noncomputable def fieldUpdate (F : ∀ a, M.Field (S.chart a).band 5) + (hk : 0 ≤ κ) (hsmall : κ*5 ≤ 1/2) (hlam : lam ≤ (1:ℝ≥0)/100) + (hd : ∀ i H T, S.name i H≠S.name i T → + |S.newValue F i H-S.oldValue i H| ≤ |H-T|/8) : SetSystem M Ω μ := + S.sets.balancedUpdate (S.fieldActivity F hk hsmall hlam hd) + (fun i H => Threshold.measurable_active _ _ _) + (fun i H => by + simp only [S.field_indicator,S.old_indicator] + exact (S.labels (S.name i H)).integrable_difference _ _ _ _) + (fun i H => by + simp only [S.field_indicator,S.old_indicator] + rw [(S.labels (S.name i H)).integral_difference,sub_self]) + +end BState +end PlanarL1.Columns.Model + + + +end + +section + +namespace PlanarL1.Columns.Model +open scoped NNReal +namespace OrderedData +variable {k : ℕ} {M : Model (k+1)} + +/-- Replace only the auxiliary history; all data determining t_s stay fixed. -/ +def withAuxiliary (D : OrderedData M) (u : M.Field D.band 100) : OrderedData M := + { D with auxiliary := u } + +lemma withAuxiliary_value (D : OrderedData M) (u : M.Field D.band 100) + (lam : ℝ≥0) (i : Fin (k+1)) (H : D.band) : + (D.withAuxiliary u).value lam i H-D.value lam i H = + lam*(u.value i H-D.auxiliary.value i H) := by + unfold withAuxiliary value + ring + +end OrderedData +end PlanarL1.Columns.Model + + + + +end + +section + +namespace PlanarL1.Columns.Model +open MeasureTheory +open scoped NNReal +attribute [local instance] Classical.propDecidable +variable {k : ℕ} {M : Model (k+1)} + +namespace BData + +def Auxiliary : BData M → Type + | .ordinary _ => Unit + | .ordered D => M.Field D.band 100 + +def withAuxiliary (D : BData M) (u : D.Auxiliary) : BData M := + match D with + | .ordinary C => .ordinary C + | .ordered C => .ordered (C.withAuxiliary u) + +@[simp] lemma withAuxiliary_band (D : BData M) (u : D.Auxiliary) : + (D.withAuxiliary u).band=D.band := by cases D <;> rfl + +lemma withAuxiliary_uses (D : BData M) (u : D.Auxiliary) (i : Fin (k+1)) : + (D.withAuxiliary u).Uses i ↔ D.Uses i := by cases D <;> rfl + +noncomputable def auxiliaryField (D : BData M) (u : D.Auxiliary) + (lam : ℝ≥0) (hlam : lam ≤ (1:ℝ≥0)/100) : M.Field D.band 5 := + match D with + | .ordinary C => C.field.weaken (by norm_num) + | .ordered C => (C.withAuxiliary u).field lam hlam + +lemma auxiliaryField_value (D : BData M) (u : D.Auxiliary) + (lam : ℝ≥0) (hlam : lam ≤ (1:ℝ≥0)/100) (i : Fin (k+1)) (H : D.band) : + (D.auxiliaryField u lam hlam).value i H = + (D.withAuxiliary u).value lam i ⟨H.val,by simp⟩ := by + cases D with + | ordinary C => rfl + | ordered C => exact (C.withAuxiliary u).field_value lam hlam i H + +end BData + +namespace BState +variable {κ : ℝ} {lam : ℝ≥0} {Ω : Type*} [MeasurableSpace Ω] {μ : Measure Ω} + (S : BState M κ lam Ω μ) + +/-- Simultaneously replace every ordered history, while retaining literally all +old chart names and all label variables. Ordinary charts are unaltered. -/ +noncomputable def withAuxiliary (U : ∀ a, (S.chart a).Auxiliary) + (hk : 0 ≤ κ) (hsmall : κ*5 ≤ 1/2) (hlam : lam ≤ (1:ℝ≥0)/100) + (hd : ∀ i H T, S.name i H≠S.name i T → + |S.newValue (fun a => (S.chart a).auxiliaryField (U a) lam hlam) i H-S.oldValue i H| ≤ + |H-T|/8) : BState M κ lam Ω μ where + sets := S.fieldUpdate (fun a => (S.chart a).auxiliaryField (U a) lam hlam) hk hsmall hlam hd + count := S.count + chart a := (S.chart a).withAuxiliary (U a) + labels := S.labels + name := S.name + height_in i H := by simpa only [BData.withAuxiliary_band] using S.height_in i H + component_in i H := (BData.withAuxiliary_uses _ _ _).mpr (S.component_in i H) + switch_name := S.switch_name + represents ω i H := by + change Threshold.active (S.labels (S.name i H)) H + (S.newValue (fun a => (S.chart a).auxiliaryField (U a) lam hlam) i H) ω ↔ _ + unfold newValue + rw [BData.auxiliaryField_value] + +end BState +end PlanarL1.Columns.Model + + + +end + +end OAI diff --git a/lean/OAI/Combinatorics/PlanarL1/OrdinaryState.lean b/lean/OAI/Combinatorics/PlanarL1/OrdinaryState.lean new file mode 100644 index 0000000000000000000000000000000000000000..9ff5e8d91ad487366dfac4fc85bbb017e7595d5d --- /dev/null +++ b/lean/OAI/Combinatorics/PlanarL1/OrdinaryState.lean @@ -0,0 +1,465 @@ +import OAI.Combinatorics.PlanarL1.MainCells + +namespace OAI + +section + +namespace PlanarL1.Columns.Model +open MeasureTheory +open scoped NNReal + +namespace SetSystem +variable {n : ℕ} {M : Model n} {Ω Ω' : Type*} [MeasurableSpace Ω] + [MeasurableSpace Ω'] {μ : Measure Ω} {μ' : Measure Ω'} + +/-- Change label coordinates only: every individual set and component graph is +pulled back, and the upper invariant is transported by the actual measure. -/ +noncomputable def pullback (A : SetSystem M Ω μ) {g : Ω' → Ω} + (hg : MeasurePreserving g μ' μ) : SetSystem M Ω' μ' where + activity ω := A.activity (g ω) + measurable_active i H := (A.measurable_active i H).preimage hg.measurable + vertical_integrable i s t := hg.integrable_comp_of_integrable (A.vertical_integrable i s t) + vertical_bound i s t := by + have he : (∫ ω, |(A.activity (g ω)).indicator i s-(A.activity (g ω)).indicator i t| ∂μ') = + ∫ ω, |(A.activity ω).indicator i s-(A.activity ω).indicator i t| ∂μ := by + calc + _ = ∫ ω, |(A.activity ω).indicator i s-(A.activity ω).indicator i t| + ∂Measure.map g μ' := + (integral_map_of_stronglyMeasurable hg.measurable + (((A.measurable_indicator i s).sub + (A.measurable_indicator i t)).abs.stronglyMeasurable)).symm + _ = _ := congrArg (fun ν => ∫ ω, + |(A.activity ω).indicator i s-(A.activity ω).indicator i t| ∂ν) hg.map_eq + exact he.trans_le (A.vertical_bound i s t) + +noncomputable def lift (A : SetSystem M Ω μ) : SetSystem M (Ω × Bool) (μ.prod Threshold.fair) := + A.pullback (measurePreserving_fst (μ := μ) (ν := Threshold.fair)) + +@[simp] lemma lift_active (A : SetSystem M Ω μ) (z : Ω × Bool) (i : Fin n) (H : ℝ) : + (A.lift.activity z).active i H ↔ (A.activity z.1).active i H := Iff.rfl + +end SetSystem + +namespace Field +variable {n : ℕ} (M : Model n) (I : Set ℝ) +noncomputable def constant (c : ℝ) : M.Field I 1 where + value _ _ := c + vertical _ := (LipschitzWith.const c).weaken (by norm_num) + switch _ _ _ _ := rfl +end Field + +/-- The literal ordinary-chart scalar data. A nonconstant chart remembers its +old band component and its one point source, rather than just a Lipschitz bound. +The zero extension outside that component is never used on the chart's region. -/ +structure OrdinaryData {n : ℕ} (M : Model n) where + band : Set ℝ + closed : IsClosed band + convex : band.OrdConnected + origin : Option (Σ r : Fin n, M.Point band r) + constant : ℝ + orientation : ℝ + unit_orientation : |orientation| = 1 + +namespace OrdinaryData +variable {n : ℕ} {M : Model n} + +noncomputable def comparison (D : OrdinaryData M) : M.Field D.band 1 := + match D.origin with + | none => Field.constant M D.band 0 + | some o => o.2.radialField + +noncomputable def value (D : OrdinaryData M) (i : Fin n) (H : D.band) : ℝ := + D.constant + D.orientation * D.comparison.value i H + +lemma vertical (D : OrdinaryData M) (i : Fin n) : LipschitzWith 1 (D.value i) := by + apply LipschitzWith.of_dist_le_mul + intro s t + rw [Real.dist_eq] + change |D.constant+D.orientation*D.comparison.value i s- + (D.constant+D.orientation*D.comparison.value i t)| ≤ _ + rw [show D.constant+D.orientation*D.comparison.value i s- + (D.constant+D.orientation*D.comparison.value i t) = + D.orientation*(D.comparison.value i s-D.comparison.value i t) by ring, + abs_mul,D.unit_orientation,one_mul] + exact (D.comparison.vertical i).dist_le_mul s t + +lemma switch (D : OrdinaryData M) (i j : Fin n) (H : D.band) + (h : H.val ∈ M.heights i j) : D.value i H = D.value j H := by + simp only [value,D.comparison.switch i j H h] + +noncomputable def field (D : OrdinaryData M) : M.Field D.band 1 := + ⟨D.value,D.vertical,D.switch⟩ + +noncomputable def initial (M : Model n) : OrdinaryData M where + band := Set.univ + closed := isClosed_univ + convex := Set.ordConnected_univ + origin := none + constant := 0 + orientation := 1 + unit_orientation := by norm_num + +@[simp] lemma initial_value (M : Model n) (i : Fin n) (H : ℝ) : + (initial M).value i ⟨H,Set.mem_univ H⟩ = 0 := by + simp [initial,value,comparison,Field.constant] + +/-- Conversion of an actual signed atom back to the old ordinary orientation. -/ +noncomputable def atom (D : OrdinaryData M) (J : Set ℝ) (hJ : IsClosed J) + (hc : J.OrdConnected) {r : Fin n} (o : M.Point J r) (c η : ℝ) (hη : |η| = 1) : + OrdinaryData M where + band := J + closed := hJ + convex := hc + origin := some ⟨r,o⟩ + constant := D.constant+D.orientation*c + orientation := D.orientation*η + unit_orientation := by rw [abs_mul,D.unit_orientation,hη,mul_one] + +lemma atom_value (D : OrdinaryData M) (J : Set ℝ) (hJ : IsClosed J) + (hc : J.OrdConnected) {r : Fin n} (o x : M.Point J r) (c η : ℝ) (hη : |η| = 1) : + (D.atom J hJ hc o c η hη).value x.column ⟨x.height,x.inBand⟩ = + D.constant+D.orientation*(c+η*dist o x) := by + have he : o.radialField.value x.column ⟨x.height,x.inBand⟩=dist o x := o.radialField_eval x + simp only [value,atom,comparison,he] + ring + +end OrdinaryData + +/-- A finite ordinary chart partition for system A, with the actual globally +nested sets and actual jointly distributed label variables. Chart regions may +be disconnected; no artificial connected-component identifiers are introduced. -/ +structure OrdinaryState {n : ℕ} (M : Model n) (κ : ℝ) (Ω : Type*) + [MeasurableSpace Ω] (μ : Measure Ω) where + sets : SetSystem M Ω μ + count : ℕ + chart : Fin (count+1) → OrdinaryData M + labels : Fin (count+1) → Threshold.Variables Ω μ + name : Fin n → ℝ → Fin (count+1) + height_in : ∀ i H, H ∈ (chart (name i H)).band + component_in : ∀ i H r o, (chart (name i H)).origin = some ⟨r,o⟩ → + (M.activeGraph (chart (name i H)).band).Reachable r i + switch_name : ∀ i j H, H ∈ M.heights i j → name i H = name j H + represents : ∀ ω i H, + (sets.activity ω).active i H ↔ Threshold.active (labels (name i H)) H + (κ*(chart (name i H)).value i ⟨H,height_in i H⟩) ω + +namespace OrdinaryState +variable {n : ℕ} {M : Model n} {κ : ℝ} {Ω : Type*} [MeasurableSpace Ω] {μ : Measure Ω} + +noncomputable def initial (M : Model n) (κ : ℝ) : + OrdinaryState M κ (Bool × ℝ) Threshold.labelMeasure where + sets := Threshold.chartSystem (Field.constant M Set.univ 0) (by norm_num) + count := 0 + chart _ := OrdinaryData.initial M + labels _ := Threshold.Variables.initial + name _ _ := 0 + height_in _ _ := Set.mem_univ _ + component_in _ _ r o h := by cases h + switch_name _ _ _ _ := rfl + represents ω i H := by + simp only [Threshold.chartSystem,Threshold.chartActivity,OrdinaryData.initial_value, + mul_zero,Field.constant,Threshold.active,Threshold.Variables.initial] + rfl + +noncomputable def lift (S : OrdinaryState M κ Ω μ) : + OrdinaryState M κ (Ω × Bool) (μ.prod Threshold.fair) where + sets := S.sets.lift + count := S.count + chart := S.chart + labels j := (S.labels j).lift + name := S.name + height_in := S.height_in + component_in := S.component_in + switch_name := S.switch_name + represents ω i H := S.represents ω.1 i H + +/-- Deterministic chart distance on a common identifier, with no independence +assumed between different identifiers. -/ +lemma chart_distance (S : OrdinaryState M κ Ω μ) (i j : Fin n) (H T : ℝ) + (he : S.name i H=S.name j T) : + (∫ ω, |(S.sets.activity ω).indicator i H-(S.sets.activity ω).indicator j T| ∂μ) = + max |H-T| |κ*(S.chart (S.name i H)).value i ⟨H,S.height_in i H⟩- + κ*(S.chart (S.name j T)).value j ⟨T,S.height_in j T⟩| := by + have hid (i : Fin n) (H : ℝ) (ω : Ω) : + (S.sets.activity ω).indicator i H = Threshold.chartValue H + (κ*(S.chart (S.name i H)).value i ⟨H,S.height_in i H⟩) + ((S.labels (S.name i H)).value ω) := by + simp only [Activity.indicator,S.represents,Threshold.active,Threshold.chartValue,Threshold.half] + simp_rw [hid] + rw [show S.labels (S.name j T)=S.labels (S.name i H) from congrArg S.labels he.symm] + exact (S.labels (S.name i H)).distance _ _ _ _ + +end OrdinaryState +end PlanarL1.Columns.Model + + +namespace PlanarL1.Columns.Model.Point.RadialTree +open PlanarL1.Interpolation +variable {n : ℕ} {M : Model n} {J : Set ℝ} {root : Fin n} +variable (R : RadialTree (M := M) (J := J) (root := root)) + +lemma atomName_depth_eq {k l : ℕ} (u v : M.Point J root) (t t' : Fin 3) + (he : atomName k u t = atomName l v t') : k = l := by + have hu := atomName_bounds k u t + have hv := atomName_bounds l v t' + rcases lt_trichotomy k l with h | h | h + · have hm := Nat.mul_le_mul_left (3*n) (Nat.succ_le_of_lt h) + simp only [Nat.succ_eq_add_one] at hm + omega + · exact h + · have hm := Nat.mul_le_mul_left (3*n) (Nat.succ_le_of_lt h) + simp only [Nat.succ_eq_add_one] at hm + omega + +lemma portalAt_mem {k : ℕ} (C : R.Node k) (i : Fin 2) : + (R.portalAt C i).column ∈ ColumnOrder.componentColumns C := by + by_cases hi : i = 0 + · simpa only [portalAt,ite_eq_left hi] using (R.portals C).left_mem + · simpa only [portalAt,ite_eq_right hi] using (R.portals C).right_mem + +lemma node_eq_of_portal_column {k : ℕ} (C D : R.Node k) (i j : Fin 2) + (he : (R.portalAt C i).column=(R.portalAt D j).column) : C = D := by + apply ColumnOrder.component_eq_of_column (R.portalAt_mem C i) + rw [he] + exact R.portalAt_mem D j + +/-- A name is global to the whole interpolation tree, not only a chosen chain. +Different node occurrences cannot silently give one identifier two fields. -/ +lemma nodeAtom_eq_global (p : M.Point J root → ℝ) (α : Noise (n := n)) + {k l : ℕ} (C : R.Node k) (D : R.Node l) (i j : Fin 2) (t t' : Fin 3) + (he : atomName k (R.portalAt C i) t = atomName l (R.portalAt D j) t') : + R.nodeAtom p α C i t = R.nodeAtom p α D j t' := by + have hk := atomName_depth_eq (R.portalAt C i) (R.portalAt D j) t t' he + subst l + obtain ⟨hc,ht⟩ := atomName_same_depth _ _ _ _ he + have hC := R.node_eq_of_portal_column C D i j hc + subst D + exact R.nodeAtom_eq_of_name p α C i j t t' he + +/-- The exact portal occurrence from which an atom identifier originates. -/ +structure AtomSource (a : ℕ) where + depth : ℕ + node : R.Node depth + portal : Fin 2 + kind : Fin 3 + name_eq : atomName depth (R.portalAt node portal) kind = a + +lemma pasted_has_source (p : M.Point J root → ℝ) (α : Noise (n := n)) + (x : M.Point J root) : Nonempty (R.AtomSource (R.pasted p α x).name) := by + obtain ⟨k,hk,i,t,he⟩ := R.formula_eq_atom p α (R.layerDepth x) (R.layerNode x) x + refine ⟨⟨k,R.ancestor (R.layerNode x) k hk,i,t,?_⟩⟩ + exact (congrArg NamedValue.name he).symm + +lemma pasted_name_lt (p : M.Point J root → ℝ) (α : Noise (n := n)) + (x : M.Point J root) : (R.pasted p α x).name < 3*n*R.depthCap := by + exact (R.formula_name_bound p α (R.layerDepth x) (R.layerNode x) x).trans_le + (Nat.mul_le_mul_left (3*n) (R.layerDepth_lt_cap x)) + +namespace AtomSource +variable {R} {a : ℕ} + +noncomputable def eval (S : R.AtomSource a) (p : M.Point J root → ℝ) + (α : Noise (n := n)) : M.Point J root → NamedValue := + R.nodeAtom p α S.node S.portal S.kind + +lemma eval_eq (S T : R.AtomSource a) (p : M.Point J root → ℝ) (α : Noise (n := n)) : + S.eval p α = T.eval p α := + R.nodeAtom_eq_global p α S.node T.node S.portal T.portal S.kind T.kind + (S.name_eq.trans T.name_eq.symm) + +noncomputable def center (S : R.AtomSource a) : M.Point J root := R.portalAt S.node S.portal + +noncomputable def intercept (S : R.AtomSource a) (p : M.Point J root → ℝ) + (α : Noise (n := n)) : ℝ := + (if S.kind = 0 then p S.center else R.parentValue p α S.depth S.node S.center) + + (if S.kind = 1 then -α S.depth S.center.column S.kind else α S.depth S.center.column S.kind) + +noncomputable def sign (S : R.AtomSource a) : ℝ := if S.kind = 2 then -1 else 1 + +lemma sign_unit (S : R.AtomSource a) : |S.sign| = 1 := by + unfold sign + split_ifs <;> norm_num + +lemma eval_formula (S : R.AtomSource a) (p : M.Point J root → ℝ) + (α : Noise (n := n)) (x : M.Point J root) : + (S.eval p α x).value = S.intercept p α+S.sign*dist S.center x := by + simp only [eval,nodeAtom,atomIntercept,intercept,sign,center] + split_ifs <;> ring + +/-- Convert back to the old ordinary orientation, as in /main-packing. +The -4E proposal shift is part of the literal atom constant. -/ +noncomputable def chart (S : R.AtomSource a) (D : OrdinaryData M) + (p : M.Point J root → ℝ) (α : Noise (n := n)) (E : ℝ) : OrdinaryData M := + D.atom J R.closed_band R.interval_band S.center (S.intercept p α-4*E) S.sign S.sign_unit + +lemma chart_value (S : R.AtomSource a) (D : OrdinaryData M) + (p : M.Point J root → ℝ) (α : Noise (n := n)) (E : ℝ) (x : M.Point J root) : + (S.chart D p α E).value x.column ⟨x.height,x.inBand⟩ = + D.constant+D.orientation*((S.eval p α x).value-4*E) := by + calc _ = D.constant+D.orientation*((S.intercept p α-4*E)+S.sign*dist S.center x) := + OrdinaryData.atom_value D J R.closed_band R.interval_band S.center x _ _ _ + _ = _ := by rw [S.eval_formula]; ring + +end AtomSource + +/-- A finite globally consistent chart table for every possible spatial atom. +Unused identifiers get a constant chart and can never be selected by pasted. -/ +noncomputable def atomChart (D : OrdinaryData M) (p : M.Point J root → ℝ) + (α : Noise (n := n)) (E : ℝ) (a : ℕ) : OrdinaryData M := by + classical + exact if h : Nonempty (R.AtomSource a) then h.some.chart D p α E else OrdinaryData.initial M + +lemma source_eval_pasted (p : M.Point J root → ℝ) (α : Noise (n := n)) + (x : M.Point J root) (S : R.AtomSource (R.pasted p α x).name) : + S.eval p α x = R.pasted p α x := by + obtain ⟨k,hk,i,t,he⟩ := R.formula_eq_atom p α (R.layerDepth x) (R.layerNode x) x + have hn : atomName k (R.portalAt (R.ancestor (R.layerNode x) k hk) i) t = + (R.pasted p α x).name := (congrArg NamedValue.name he).symm + have hsame := R.nodeAtom_eq_global p α S.node (R.ancestor (R.layerNode x) k hk) + S.portal i S.kind t (S.name_eq.trans hn.symm) + exact (congrFun hsame x).trans he.symm + +lemma atomChart_value (D : OrdinaryData M) (p : M.Point J root → ℝ) + (α : Noise (n := n)) (E : ℝ) (x : M.Point J root) : + ∃ h : x.height ∈ (R.atomChart D p α E (R.pasted p α x).name).band, + (R.atomChart D p α E (R.pasted p α x).name).value x.column ⟨x.height,h⟩ = + D.constant+D.orientation*((R.pasted p α x).value-4*E) := by + have h := R.pasted_has_source p α x + let Q : OrdinaryData M → Prop := fun T => ∃ hi : x.height ∈ T.band, + T.value x.column ⟨x.height,hi⟩ = + D.constant+D.orientation*((R.pasted p α x).value-4*E) + change Q (R.atomChart D p α E (R.pasted p α x).name) + have he : R.atomChart D p α E (R.pasted p α x).name = h.some.chart D p α E := dite_eq_left h + rw [he] + exact ⟨x.inBand,(AtomSource.chart_value h.some D p α E x).trans + (by rw [R.source_eval_pasted])⟩ + +end PlanarL1.Columns.Model.Point.RadialTree + + +namespace PlanarL1.Columns.Model +open MeasureTheory +namespace OrdinaryState +variable {n : ℕ} {M : Model n} {κ : ℝ} {Ω : Type*} [MeasurableSpace Ω] {μ : Measure Ω} + +/-- Finite chart-table extension. Old identifiers are literally retained in the +right summand; installing a fresh chart never refines the old regions. -/ +noncomputable def append (S : OrdinaryState M κ Ω μ) (B : SetSystem M Ω μ) + (k : ℕ) (D : Fin k → OrdinaryData M) (Z : Fin k → Threshold.Variables Ω μ) + (choose : Fin n → ℝ → Option (Fin k)) + (hin : ∀ i H a, choose i H = some a → H ∈ (D a).band) + (hcomp : ∀ i H a (_hc : choose i H = some a) r o, + (D a).origin = some ⟨r,o⟩ → (M.activeGraph (D a).band).Reachable r i) + (hswitch : ∀ i j H, H ∈ M.heights i j → choose i H = choose j H) + (hold : ∀ ω i H, choose i H = none → + ((B.activity ω).active i H ↔ (S.sets.activity ω).active i H)) + (hnew : ∀ ω i H a (hc : choose i H = some a), + ((B.activity ω).active i H ↔ Threshold.active (Z a) H + (κ*(D a).value i ⟨H,hin i H a hc⟩) ω)) : OrdinaryState M κ Ω μ where + sets := B + count := k+S.count + chart := Fin.addCases (m := k) (n := S.count+1) D S.chart + labels := Fin.addCases (m := k) (n := S.count+1) Z S.labels + name i H := match choose i H with + | none => Fin.natAdd k (S.name i H) + | some a => Fin.castAdd (S.count+1) a + height_in i H := by + cases hc : choose i H with + | none => simpa only [hc,Fin.addCases_right] using S.height_in i H + | some a => simpa only [hc,Fin.addCases_left] using hin i H a hc + component_in i H := by + let Uses (D : OrdinaryData M) : Prop := ∀ r o, + D.origin = some ⟨r,o⟩ → (M.activeGraph D.band).Reachable r i + change Uses (Fin.addCases (m := k) (n := S.count+1) D S.chart + (match choose i H with + | none => Fin.natAdd k (S.name i H) + | some a => Fin.castAdd (S.count+1) a)) + cases hc : choose i H with + | none => + simp only [Fin.addCases_right] + exact S.component_in i H + | some a => + simp only [Fin.addCases_left] + exact hcomp i H a hc + switch_name i j H hh := by + have hc := hswitch i j H hh + rw [hc] + cases choose j H with + | none => exact congrArg (Fin.natAdd k) (S.switch_name i j H hh) + | some a => rfl + represents ω i H := by + let Rep (D : OrdinaryData M) (Z : Threshold.Variables Ω μ) : Prop := + ∀ hi : H ∈ D.band, (B.activity ω).active i H ↔ + Threshold.active Z H (κ*D.value i ⟨H,hi⟩) ω + have hr : Rep + (Fin.addCases (m := k) (n := S.count+1) D S.chart + (match choose i H with + | none => Fin.natAdd k (S.name i H) + | some a => Fin.castAdd (S.count+1) a)) + (Fin.addCases (m := k) (n := S.count+1) Z S.labels + (match choose i H with + | none => Fin.natAdd k (S.name i H) + | some a => Fin.castAdd (S.count+1) a)) := by + cases hc : choose i H with + | none => + simp only [Fin.addCases_right] + intro hi + exact (hold ω i H hc).trans (S.represents ω i H) + | some a => + simp only [Fin.addCases_left] + intro hi + exact hnew ω i H a hc + exact hr _ + +end OrdinaryState +end PlanarL1.Columns.Model + + +end + +section + +namespace PlanarL1.Columns.Model.OrdinaryData +variable {n : ℕ} {M : Model n} + +/-- The actual chart domain, with the connected-component requirement made +explicit. Different copies of a quotient point satisfy the same condition. -/ +def Contains (D : OrdinaryData M) (i : Fin n) (H : ℝ) : Prop := + H ∈ D.band ∧ ∀ r o, D.origin = some ⟨r,o⟩ → (M.activeGraph D.band).Reachable r i + +lemma initial_contains (i : Fin n) (H : ℝ) : (initial M).Contains i H := by + refine ⟨Set.mem_univ _,?_⟩ + intro r o he + cases he + +lemma atom_contains (D : OrdinaryData M) (J : Set ℝ) (hJ : IsClosed J) + (hc : J.OrdConnected) {r : Fin n} (o x : M.Point J r) (c η : ℝ) (hη : |η|=1) : + (D.atom J hJ hc o c η hη).Contains x.column x.height := by + refine ⟨x.inBand,?_⟩ + intro r' o' he + have hr : r=r' := congrArg (fun z : Option (Σ r : Fin n, M.Point J r) => + z.map Sigma.fst) he |> Option.some.inj + subst r' + exact x.reachable + +end PlanarL1.Columns.Model.OrdinaryData + +namespace PlanarL1.Columns.Model.Point.RadialTree +open PlanarL1.Interpolation +variable {n : ℕ} {M : Model n} {J : Set ℝ} {root : Fin n} +variable (R : RadialTree (M := M) (J := J) (root := root)) + +lemma atomChart_contains (D : OrdinaryData M) (p : M.Point J root → ℝ) + (α : Noise (n := n)) (E : ℝ) (x : M.Point J root) : + (R.atomChart D p α E (R.pasted p α x).name).Contains x.column x.height := by + have h := R.pasted_has_source p α x + have he : R.atomChart D p α E (R.pasted p α x).name = h.some.chart D p α E := dite_eq_left h + rw [he] + exact OrdinaryData.atom_contains D J R.closed_band R.interval_band h.some.center x _ _ _ + +end PlanarL1.Columns.Model.Point.RadialTree + + +end + +end OAI diff --git a/lean/OAI/Combinatorics/PlanarL1/PairGeometry.lean b/lean/OAI/Combinatorics/PlanarL1/PairGeometry.lean new file mode 100644 index 0000000000000000000000000000000000000000..3b5e6630d4d43eadb5f2bf223c0a1942b33c2564 --- /dev/null +++ b/lean/OAI/Combinatorics/PlanarL1/PairGeometry.lean @@ -0,0 +1,355 @@ +import OAI.Combinatorics.PlanarL1.Separation + +namespace OAI + + +section + +namespace PlanarL1.Columns.Model +open MeasureTheory +namespace Activity +variable {n : ℕ} {M : Model n} +lemma terminal_certificate_circular (A : Activity M) {a b x y : Fin n} {H s t : ℝ} + (hH : H ∈ M.heights a b) (hn : ¬Consecutive a b) (hA : ¬A.active a H) + (hs : Field.CircularTipSeparates a b x y) + (hx : A.active x s) (hy : A.active y t) : A.cost x y s t=2 := by + have hb : H ∈ M.heights b a := M.symm a b ▸ hH + have hn' : ¬Consecutive b a := by simpa only [Consecutive,or_comm,or_left_comm,or_assoc] using hn + have hB : ¬A.active b H := fun h => hA ((A.switch a b H hH).mpr h) + rcases hs with (⟨hax,hxb,hyy⟩ | ⟨hay,hyb,hxx⟩) | (⟨hbx,hxa,hyy⟩ | ⟨hby,hya,hxx⟩) + · exact A.terminal_certificate hH hn hA ⟨hax,hxb⟩ hyy hx hy + · rw [A.cost_comm] + exact A.terminal_certificate hH hn hA ⟨hay,hyb⟩ hxx hy hx + · exact A.terminal_certificate hb hn' hB ⟨hbx,hxa⟩ hyy hx hy + · rw [A.cost_comm] + exact A.terminal_certificate hb hn' hB ⟨hby,hya⟩ hxx hy hx + +lemma terminal_survival_circular (A B : Activity M) {a b x y : Fin n} {H s t : ℝ} + (hH : H ∈ M.heights a b) (hn : ¬Consecutive a b) + (hs : Field.CircularTipSeparates a b x y) + (ha : ¬A.active a H) (hax : A.active x s) (hay : A.active y t) : + 2≤B.cost x y s t+2*(A.movement B x s+A.movement B y t+A.movement B a H) := by + by_cases hba : B.active a H + · have hm : A.movement B a H=1 := by simp [movement,indicator,ha,hba] + linarith [A.movement_nonneg B x s,A.movement_nonneg B y t,B.cost_nonneg x y s t] + by_cases hbx : B.active x s + · by_cases hby : B.active y t + · rw [B.terminal_certificate_circular hH hn hba hs hbx hby] + linarith [A.movement_nonneg B x s,A.movement_nonneg B y t,A.movement_nonneg B a H] + · have hm : A.movement B y t=1 := by simp [movement,indicator,hay,hby] + linarith [A.movement_nonneg B x s,A.movement_nonneg B a H,B.cost_nonneg x y s t] + · have hm : A.movement B x s=1 := by simp [movement,indicator,hax,hbx] + linarith [A.movement_nonneg B y t,A.movement_nonneg B a H,B.cost_nonneg x y s t] +end Activity + +namespace SetSystem +variable {n : ℕ} {M : Model n} {Ω : Type*} [MeasurableSpace Ω] {μ : Measure Ω} +variable (A B : SetSystem M Ω μ) +lemma refinedMap_terminal_circular [SFinite μ] {J : Set ℝ} {root : Fin n} (o x y : M.Point J root) + {a b : Fin n} {H : ℝ} (hH : H ∈ M.heights a b) (hn : ¬Consecutive a b) + (hs : Field.CircularTipSeparates a b x.column y.column) + (E : Set Ω) (hE : MeasurableSet E) + (hA : ∀ ω ∈ E, ¬(A.activity ω).active a H) + (hX : ∀ ω ∈ E, (A.activity ω).active x.column x.height) + (hY : ∀ ω ∈ E, (A.activity ω).active y.column y.height) : + μ E<⊤ ∧ 2*μ.real E≤‖A.refinedMap o x-A.refinedMap o y‖ := by + have hbnd : ∀ ω, ‖E.indicator (fun _ => (2:ℝ)) ω‖≤ + (A.activity ω).cost x.column y.column x.height y.height := by + intro ω + by_cases hω : ω ∈ E + · rw [Set.indicator_of_mem hω, + (A.activity ω).terminal_certificate_circular hH hn (hA ω hω) hs (hX ω hω) (hY ω hω)] + norm_num + · rw [Set.indicator_of_notMem hω,norm_zero] + exact (A.activity ω).cost_nonneg _ _ _ _ + have hi : Integrable (E.indicator (fun _ => (2:ℝ))) μ := + (A.cost_integrable (Classical.choice (x.paths_nonempty y)) x.height y.height).mono' + (measurable_const.indicator hE).aestronglyMeasurable (Filter.Eventually.of_forall hbnd) + constructor + · have ht := (integrableOn_const_iff (C := (2:ℝ))).mp ((integrable_indicator_iff hE).mp hi) + simpa using ht + · rw [A.norm_refinedMap_sub] + calc + 2*μ.real E = ∫ ω, E.indicator (fun _ => (2:ℝ)) ω ∂μ := by + rw [integral_indicator_const _ hE,smul_eq_mul,mul_comm] + _ ≤ _ := integral_mono hi + (A.cost_integrable (Classical.choice (x.paths_nonempty y)) x.height y.height) + (fun ω => (le_abs_self _).trans (by simpa only [Real.norm_eq_abs] using hbnd ω)) + +lemma refined_certificate_survival_circular [SFinite μ] {J : Set ℝ} {root : Fin n} + (o x y : M.Point J root) {a b : Fin n} {H : ℝ} + (hH : H ∈ M.heights a b) (hn : ¬Consecutive a b) + (hs : Field.CircularTipSeparates a b x.column y.column) + (E : Set Ω) (hE : MeasurableSet E) + (ha : ∀ ω ∈ E, ¬(A.activity ω).active a H) + (hax : ∀ ω ∈ E, (A.activity ω).active x.column x.height) + (hay : ∀ ω ∈ E, (A.activity ω).active y.column y.height) + (hmove : ∀ i H, Integrable (fun ω => (B.activity ω).indicator i H- + (A.activity ω).indicator i H) μ) : + 2*μ.real E≤‖B.refinedMap o x-B.refinedMap o y‖+ + 2*(A.movement B x.column x.height+A.movement B y.column y.height+A.movement B a H) := by + have hfin := (A.refinedMap_terminal_circular o x y hH hn hs E hE ha hax hay).1 + have hEI : Integrable (E.indicator (fun _ => (2:ℝ))) μ := by + apply (integrable_indicator_iff hE).mpr + exact (integrableOn_const_iff (C := (2:ℝ))).mpr (Or.inr hfin) + have hmI (i : Fin n) (z : ℝ) : Integrable (fun ω => (A.activity ω).movement (B.activity ω) i z) μ := by + simpa only [Activity.movement,Real.norm_eq_abs] using (hmove i z).norm + have hxI := hmI x.column x.height + have hyI := hmI y.column y.height + have haI := hmI a H + let path := Classical.choice (x.paths_nonempty y) + have hcost := B.cost_integrable path x.height y.height + have hg := integral_mono hEI (hcost.add (((hxI.add hyI).add haI).const_mul 2)) + (fun ω => show E.indicator (fun _ => (2:ℝ)) ω≤ + (B.activity ω).cost x.column y.column x.height y.height+ + 2*((A.activity ω).movement (B.activity ω) x.column x.height+ + (A.activity ω).movement (B.activity ω) y.column y.height+ + (A.activity ω).movement (B.activity ω) a H) by + by_cases he : ω ∈ E + · rw [Set.indicator_of_mem he] + exact (A.activity ω).terminal_survival_circular (B.activity ω) hH hn hs + (ha ω he) (hax ω he) (hay ω he) + · rw [Set.indicator_of_notMem he] + linarith [(B.activity ω).cost_nonneg x.column y.column x.height y.height, + (A.activity ω).movement_nonneg (B.activity ω) x.column x.height, + (A.activity ω).movement_nonneg (B.activity ω) y.column y.height, + (A.activity ω).movement_nonneg (B.activity ω) a H]) + rw [integral_indicator_const _ hE,smul_eq_mul,mul_comm] at hg + rw [B.norm_refinedMap_sub] + change _≤_+2*((∫ ω, |(B.activity ω).indicator x.column x.height- + (A.activity ω).indicator x.column x.height| ∂μ)+ + (∫ ω, |(B.activity ω).indicator y.column y.height- + (A.activity ω).indicator y.column y.height| ∂μ)+ + (∫ ω, |(B.activity ω).indicator a H-(A.activity ω).indicator a H| ∂μ)) + dsimp only [Pi.add_apply] at hg + have e1 := integral_add hcost (((hxI.add hyI).add haI).const_mul 2) + have e2 := integral_add (hxI.add hyI) haI + have e3 := integral_add hxI hyI + simp only [Pi.add_apply] at e1 e2 e3 + rw [e1,integral_const_mul,e2,e3] at hg + exact hg +end SetSystem +end PlanarL1.Columns.Model + +end + + + +section + +namespace PlanarL1.Threshold.Variables +open MeasureTheory Set +open scoped ENNReal +variable {Ω : Type*} [MeasurableSpace Ω] {μ : Measure Ω} + +/-- A literal half-sign label rectangle, pulled back through the actual old +chart variables. No independence of different old charts is asserted. -/ +noncomputable def slab (Z : Variables Ω μ) (b : Bool) (lo hi : ℝ) : Set Ω := + Z.value ⁻¹' ({b} ×ˢ Ico lo hi) +lemma measurable_slab (Z : Variables Ω μ) (b : Bool) (lo hi : ℝ) : + MeasurableSet (Z.slab b lo hi) := + ((measurableSet_singleton b).prod measurableSet_Ico).preimage Z.preserving.measurable +lemma mem_slab (Z : Variables Ω μ) (b : Bool) (lo hi : ℝ) (ω : Ω) : + ω ∈ Z.slab b lo hi ↔ (Z.value ω).1=b ∧ lo ≤ (Z.value ω).2 ∧ (Z.value ω).2 < hi := by + simp only [slab,mem_preimage,mem_prod,mem_singleton_iff,mem_Ico] +lemma measure_slab (Z : Variables Ω μ) (b : Bool) {lo hi : ℝ} (hh : lo ≤ hi) : + μ.real (Z.slab b lo hi)=(hi-lo)/2 := by + unfold Measure.real slab + rw [Z.preserving.measure_preimage (((measurableSet_singleton b).prod measurableSet_Ico).nullMeasurableSet), + labelMeasure_eq,Measure.prod_prod, fair,Measure.smul_apply,smul_eq_mul, + Measure.count_singleton,mul_one,Real.volume_Ico,ENNReal.toReal_mul, + ENNReal.toReal_ofReal (sub_nonneg.mpr hh)] + norm_num + ring +end PlanarL1.Threshold.Variables + +namespace PlanarL1.Columns.Model.OrdinaryState +open Parameters MeasureTheory +attribute [local instance] Classical.propDecidable +variable {n : ℕ} {M : Model n} {Ω : Type*} [MeasurableSpace Ω] {μ : Measure Ω} +variable (S : OrdinaryState M kappaA Ω μ) + +/-- The elementary barrier rectangle in one literal ordinary chart. All three +memberships and its uniform real mass are produced, rather than assumed. -/ +lemma barrier_labels (a : Fin (S.count+1)) {root : Fin n} + (x y e : M.Point (S.chart a).band root) + (hx : S.name x.column x.height=a) (hy : S.name y.column y.height=a) + (he : S.name e.column e.height=a) + {lo : ℝ} (hxH : x.height ∈ Set.Icc lo (lo+a₂)) + (hyH : y.height ∈ Set.Icc lo (lo+a₂)) (heH : e.height ∈ Set.Icc lo (lo+a₂)) + (hclose : |(S.chart a).comparison.eval x-(S.chart a).comparison.eval y| ≤ EA) + (hdrop : (S.chart a).comparison.eval e < (S.chart a).comparison.eval x-j ∨ + (S.chart a).comparison.eval e < (S.chart a).comparison.eval y-j) : + ∃ E : Set Ω, MeasurableSet E ∧ kappaA*j/4 ≤ μ.real E ∧ + (∀ ω ∈ E, (S.sets.activity ω).active x.column x.height) ∧ + (∀ ω ∈ E, (S.sets.activity ω).active y.column y.height) ∧ + (∀ ω ∈ E, ¬(S.sets.activity ω).active e.column e.height) := by + let sx := (S.chart a).comparison.eval x + let sy := (S.chart a).comparison.eval y + let se := (S.chart a).comparison.eval e + let τ := (S.chart a).orientation + let c := (S.chart a).constant + obtain ⟨b,hb⟩ : ∃ b : Bool, (if b then (1:ℝ) else -1)=τ := by + obtain h | h := (abs_eq (by norm_num : (0:ℝ) ≤ 1)).mp (S.chart a).unit_orientation + · exact ⟨true,h.symm⟩ + · exact ⟨false,h.symm⟩ + let tx := x.height+kappaA*τ*c+kappaA*sx + let ty := y.height+kappaA*τ*c+kappaA*sy + let te := e.height+kappaA*τ*c+kappaA*se + have hsx : j-EA ≤ sx-se := by + dsimp only [sx,sy,se] at * + obtain h | h := hdrop + · linarith [show 0 ≤ EA by norm_num [EA,epsilon]] + · linarith [(abs_le.mp hclose).1] + have hsy : j-EA ≤ sy-se := by + dsimp only [sx,sy,se] at * + obtain h | h := hdrop + · linarith [(abs_le.mp hclose).2] + · linarith [show 0 ≤ EA by norm_num [EA,epsilon]] + have hk : 0 < kappaA := by norm_num [kappaA,a₁] + have hj : 0 < j := by norm_num [j,R] + have hnum : kappaA*j/2 ≤ kappaA*(j-EA)-a₂ := by + norm_num [kappaA,a₁,j,R,EA,epsilon,a₂] + have htx : kappaA*j/2 ≤ tx-te := by + have := mul_le_mul_of_nonneg_left hsx hk.le + dsimp only [tx,te] + nlinarith [hxH.1,heH.2] + have hty : kappaA*j/2 ≤ ty-te := by + have := mul_le_mul_of_nonneg_left hsy hk.le + dsimp only [ty,te] + nlinarith [hyH.1,heH.2] + have hmin : kappaA*j/2 ≤ min tx ty-te := by + rw [← min_sub_sub_right] + exact le_min htx hty + have hle : te ≤ min tx ty := by nlinarith + have hformula (z : M.Point (S.chart a).band root) : + (if b then z.height+kappaA*(S.chart a).value z.column ⟨z.height,z.inBand⟩ + else z.height-kappaA*(S.chart a).value z.column ⟨z.height,z.inBand⟩)= + z.height+kappaA*τ*c+kappaA*(S.chart a).comparison.eval z := by + cases b <;> simp only [Bool.false_eq_true,ite_false,ite_true] at hb ⊢ <;> + dsimp only [OrdinaryData.value,Field.eval] + · have hτ : (S.chart a).orientation = -1 := hb.symm + simp only [hτ] + dsimp only [τ,c] + rw [hτ] + ring + · have hτ : (S.chart a).orientation = 1 := hb.symm + simp only [hτ] + dsimp only [τ,c] + rw [hτ] + ring + let E := (S.labels a).slab b te (min tx ty) + refine ⟨E,(S.labels a).measurable_slab b te (min tx ty),?_,?_,?_,?_⟩ + · rw [(S.labels a).measure_slab b hle] + linarith + · intro ω hω + obtain ⟨hωb,_,hω⟩ := ((S.labels a).mem_slab b te (min tx ty) ω).mp hω + rw [S.represents_named ω _ _ a hx x.inBand] + unfold Threshold.active + rw [hωb,hformula x] + exact hω.trans_le (min_le_left _ _) + · intro ω hω + obtain ⟨hωb,_,hω⟩ := ((S.labels a).mem_slab b te (min tx ty) ω).mp hω + rw [S.represents_named ω _ _ a hy y.inBand] + unfold Threshold.active + rw [hωb,hformula y] + exact hω.trans_le (min_le_right _ _) + · intro ω hω ha + obtain ⟨hωb,hω,_⟩ := ((S.labels a).mem_slab b te (min tx ty) ω).mp hω + rw [S.represents_named ω _ _ a he e.inBand] at ha + unfold Threshold.active at ha + rw [hωb,hformula e] at ha + exact (not_lt_of_ge hω) ha +end PlanarL1.Columns.Model.OrdinaryState + +end + + + +section + +namespace PlanarL1.Columns.Model +open MeasureTheory +attribute [local instance] Classical.propDecidable +namespace OrdinaryState.MainStep +variable {n : ℕ} {M : Model n} {κ : ℝ} {Ω : Type*} [MeasurableSpace Ω] {μ : Measure Ω} +variable {S : OrdinaryState M κ Ω μ} {J : Set ℝ} {root : Fin n} +variable (U : MainStep S J root) + +/-- The other endpoint can be in another broad component. Only its actual old +identifier and its absence from this cell matter for the indicator calculation. -/ +lemma pair_distance_external (x : M.Point J root) (j : Fin n) (T : ℝ) + (hT : T ∈ U.data.band) (hx : x.column ∈ ColumnOrder.componentColumns U.cell) + (hy : T ∉ MainCell.domain U.tree U.phase U.cell j) (hyn : S.name j T=U.index) : + (∫ ω, |(U.patch.apply.activity ω).indicator x.column x.height- + (U.patch.apply.activity ω).indicator j T| ∂(μ.prod Threshold.fair)) = + max |x.height-T| (κ*|MainCell.replacement U.comparison U.sub_old U.tree U.phase U.cell + U.anchor U.noise U.error U.shield_offset U.lo x-U.comparison.value j ⟨T,hT⟩|) := by + have hxi := (MainCell.mem_domain U.tree U.phase U.cell).mpr ⟨hx,x.inBand⟩ + have he : MainCell.cellPoint U.tree U.phase U.cell x.column x.height hxi=x := by cases x; rfl + have hid (ω : Ω × Bool) : + (U.patch.apply.activity ω).indicator j T = + Threshold.chartValue T (κ*(U.data.constant+U.data.orientation*U.comparison.value j ⟨T,hT⟩)) + ((S.labels U.index).lift.value ω) := by + have hr := S.represents_named ω.1 j T U.index hyn hT + have hp := U.patch.unchanged hy ω + simp only [Activity.indicator,Threshold.chartValue,Threshold.half,Threshold.active] at * + exact if_congr (hp.trans hr) rfl rfl + simp_rw [U.indicator_inside _ _ _ hxi,he,hid] + rw [(S.labels U.index).lift.distance] + congr 1 + rw [show κ*(U.data.constant+U.data.orientation*MainCell.replacement U.comparison U.sub_old + U.tree U.phase U.cell U.anchor U.noise U.error U.shield_offset U.lo x)- + κ*(U.data.constant+U.data.orientation*U.comparison.value j ⟨T,hT⟩) = + κ*U.data.orientation*(MainCell.replacement U.comparison U.sub_old U.tree U.phase U.cell + U.anchor U.noise U.error U.shield_offset U.lo x-U.comparison.value j ⟨T,hT⟩) by ring, + abs_mul,abs_mul,abs_of_nonneg U.kappa_nonneg,U.data.unit_orientation,mul_one] + +lemma separation_of_raise_external (x : M.Point J root) (j : Fin n) (T : ℝ) + (hT : T ∈ U.data.band) (hx : x.column ∈ ColumnOrder.componentColumns U.cell) + (hy : T ∉ MainCell.domain U.tree U.phase U.cell j) (hyn : S.name j T=U.index) (hκ : 0<κ) + (hclose : |MainCell.old U.comparison U.sub_old x-U.comparison.value j ⟨T,hT⟩| ≤ U.error) + (hraise : MainCell.old U.comparison U.sub_old x+2*U.error < + MainCell.replacement U.comparison U.sub_old U.tree U.phase U.cell U.anchor + U.noise U.error U.shield_offset U.lo x) : + κ*U.error < (∫ ω, |(U.patch.apply.activity ω).indicator x.column x.height- + (U.patch.apply.activity ω).indicator j T| ∂(μ.prod Threshold.fair)) := by + rw [U.pair_distance_external x j T hT hx hy hyn] + apply lt_of_lt_of_le _ (le_max_right _ _) + apply mul_lt_mul_of_pos_left _ hκ + have hb := (abs_le.mp hclose).1 + have ha := le_abs_self (MainCell.replacement U.comparison U.sub_old U.tree U.phase U.cell + U.anchor U.noise U.error U.shield_offset U.lo x-U.comparison.value j ⟨T,hT⟩) + linarith + +lemma pair_separation_external (x : M.Point J root) (j : Fin n) (T : ℝ) + (hT : T ∈ U.data.band) (hx : x.column ∈ ColumnOrder.componentColumns U.cell) + (hy : T ∉ MainCell.domain U.tree U.phase U.cell j) (hyn : S.name j T=U.index) (hκ : 0<κ) + {ε : ℝ} (hε : 0<ε) (hεsmall : ε ≤ (1:ℝ)/100) + (hζ : U.tree.ζ=ε/100) (hE : U.error=ε/1000) + (hclose : |MainCell.old U.comparison U.sub_old x-U.comparison.value j ⟨T,hT⟩| ≤ U.error) + (hshield : MainCell.old U.comparison U.sub_old U.anchor+2 ≤ + Clipping.heightShield U.lo U.tree.a (MainCell.old U.comparison U.sub_old U.anchor) + U.shield_offset x.height) + (hlow : U.phase+(1:ℝ)/100000+2*U.tree.a < + dist U.tree.base (x.withHeight U.tree.base.height U.tree.base.inBand)) + (hupp : dist U.tree.base (x.withHeight U.tree.base.height U.tree.base.inBand) < + U.phase+(1:ℝ)/1000-(1:ℝ)/100000-2*U.tree.a) + (hno : ¬Nonempty (U.comparison.BandDescent J (x.widen U.sub_old) ε)) : + κ*U.error < (∫ ω, |(U.patch.apply.activity ω).indicator x.column x.height- + (U.patch.apply.activity ω).indicator j T| ∂(μ.prod Threshold.fair)) := by + apply U.separation_of_raise_external x j T hT hx hy hyn hκ hclose + have hδ : U.tree.δ=(ε/1000)/8 := by rw [U.delta_eq,hE] + have hh := MainCell.raise_or_descent U.comparison U.sub_old U.tree U.phase U.cell + U.compact_band U.anchor x U.anchor_mem hx hε hεsmall hζ hδ U.noise_bounds + (fun z => Clipping.heightShield U.lo U.tree.a (MainCell.old U.comparison U.sub_old U.anchor) + U.shield_offset z.height) hshield hlow hupp + rcases hh with hh | hh + · simpa only [hE,MainCell.replacement] using hh + · exact (hno hh).elim +end OrdinaryState.MainStep +end PlanarL1.Columns.Model + +end + +end OAI diff --git a/lean/OAI/Combinatorics/PlanarL1/PairSelection.lean b/lean/OAI/Combinatorics/PlanarL1/PairSelection.lean new file mode 100644 index 0000000000000000000000000000000000000000..212cebdb07672f33d4433366f7721d9ca7fe9e82 --- /dev/null +++ b/lean/OAI/Combinatorics/PlanarL1/PairSelection.lean @@ -0,0 +1,856 @@ +import OAI.Combinatorics.PlanarL1.PairGeometry + +namespace OAI + + +section + +namespace PlanarL1.Columns.Model.BandTrees +open Parameters +attribute [local instance] Classical.propDecidable +variable {k : ℕ} {M : Model (k+1)} {lo : ℝ} {C : Component M broad lo} + +noncomputable def radialValue (x : M.Point (band broad lo) (root M broad lo C)) : ℝ := + dist (base M broad lo C) (x.withHeight (middle broad lo) (middle_mem broad lo)) + +/-- All column representatives, not only the chosen one, pass the radial +interior test. The quantification is over zero-distance geometric points. -/ +def RadialInterior (width phase : ℝ) (x : M.Point (band broad lo) (root M broad lo C)) : Prop := + ∀ y : M.Point (band broad lo) (root M broad lo C), dist x y=0 → + ¬Tiling.NearBoundary width phase (radialValue y) (width/50) + +lemma radial_difference (x y : M.Point (band broad lo) (root M broad lo C)) : + |radialValue x-radialValue y|≤dist x y+a₁ := + (base M broad lo C).radial_difference_le x y (middle_mem broad lo) + (tree M broad lo C).half_width + +lemma radialInterior_of_avoid {width phase : ℝ} + (x : M.Point (band broad lo) (root M broad lo C)) + (hn : ¬Tiling.NearBoundary width phase (radialValue x) (width/50+a₁)) : + RadialInterior width phase x := by + intro y hy hn' + have hd := radial_difference y x + rw [dist_comm y x,hy,zero_add] at hd + exact hn (hn'.perturb.mono (by linarith)) + +/-- Intrinsic zero-distance representatives are exactly enough: any other +unrestricted representative localizes into the same broad component. -/ +lemma RadialInterior.ambient (A : Ambient M) {width phase : ℝ} + {x : M.Point (band broad lo) (root M broad lo C)} (h : RadialInterior width phase x) + (y : M.Point Set.univ A.root) (hy : dist (A.point x.column x.height) y=0) : + ∃ y' : M.Point (band broad lo) (root M broad lo C), + y'.column=y.column ∧ y'.height=y.height ∧ + ¬Tiling.NearBoundary width phase (radialValue y') (width/50) := by + obtain ⟨y',hi,hH,hd⟩ := Point.local_point (A.point x.column x.height) y x rfl rfl + isClosed_univ (Set.subset_univ _) (t := 0) (by + intro H hH + have he : H=x.height := sub_eq_zero.mp (abs_eq_zero.mp (le_antisymm hH (abs_nonneg _))) + simpa only [he] using x.inBand) hy.le + exact ⟨y',hi,hH,h y' (hd.trans hy)⟩ + +lemma radialInterior_padding {width phase : ℝ} + (hw : 0 + NearBoundary width (width/m*(ω i).val) x (width/50+a₁) ∨ + NearBoundary width (width/m*(ω j).val) y (width/50+a₁)) ≤81/1000 := by + have hm0 : 0 < m := by omega + have hmR : (10000:ℝ) ≤ m := by exact_mod_cast hm + have hmesh : width/m≤width/10000 := div_le_div_of_nonneg_left hw.le (by norm_num) hmR + have hb : (2*(width/50+a₁)+2*width/m)/width≤81/2000 := by + apply (div_le_iff₀ hw).mpr + rw [mul_div_assoc] + linarith + have hp (h : ℝ) := (periodic_probability m hm0 hw + (show 0≤width/50+a₁ by have ha := interpolationA.2.1; positivity) h).trans hb + have h₁ := prob_eval_bound i (fun r : Fin (m+1) => + NearBoundary width (width/m*r.val) x (width/50+a₁)) (hp x) + have h₂ := prob_eval_bound j (fun r : Fin (m+1) => + NearBoundary width (width/m*r.val) y (width/50+a₁)) (hp y) + exact (prob_or_le _ _).trans (by linarith) + +end PlanarL1.FiniteRandom + +end + + + +section + +namespace PlanarL1.Columns.Model.VertexBands +open Parameters +attribute [local instance] Classical.propDecidable +variable {k : ℕ} {M : Model (k+1)} {V : Type*} +variable (A : Ambient M) (v : V → M.Point Set.univ A.root) +variable (L U : ℝ) (hv : ∀ x, (v x).height ∈ Set.Icc L U) + +noncomputable def bandIndex (q : ℝ) (x : V) : MainFamily.BandIndex q L U := + ⟨Tiling.index a₁ q (v x).height,(Tiling.mem_processed interpolationA.2.1 q L U _).mpr + ⟨(v x).height,Tiling.mem_band_index interpolationA.2.1 q _,hv x⟩⟩ +noncomputable def lower (q : ℝ) (x : V) := MainFamily.lower q L U (bandIndex A v L U hv q x) +noncomputable def component (q : ℝ) (x : V) : + BandTrees.Component M broad (lower A v L U hv q x) := + (M.activeGraph (BandTrees.band broad (lower A v L U hv q x))).connectedComponentMk (v x).column +noncomputable def bandComponent (q : ℝ) (x : V) : MainFamily.BandComponent (M := M) q L U := + ⟨bandIndex A v L U hv q x,component A v L U hv q x⟩ +lemma height_mem (q : ℝ) (x : V) : (v x).height ∈ BandTrees.band broad (lower A v L U hv q x) := by + have h := Tiling.mem_band_index interpolationA.2.1 q (v x).height + change q+(Tiling.index a₁ q (v x).height:ℝ)*a₁≤(v x).height ∧ + (v x).height≤q+(Tiling.index a₁ q (v x).height:ℝ)*a₁+a₁ + constructor <;> dsimp [Tiling.band] at h <;> linarith [h.1,h.2] +noncomputable def point (q : ℝ) (x : V) : + M.Point (BandTrees.band broad (lower A v L U hv q x)) + (BandTrees.root M broad (lower A v L U hv q x) (component A v L U hv q x)) where + column := (v x).column + height := (v x).height + inBand := height_mem A v L U hv q x + reachable := (component A v L U hv q x).reachable_of_mem_supp + (BandTrees.root_mem _ _ _ _) rfl + +variable {L U hv} +noncomputable def radial (q : ℝ) (width : ℝ) + (phase : MainFamily.BandComponent (M := M) q L U → ℝ) (x : V) : Prop := + BandTrees.RadialInterior width (phase (bandComponent A v L U hv q x)) + (point A v L U hv q x) + +/-- Exactly the literal vertex interior predicate. Narrow containment follows +from broad height padding and is included below as a checked consequence. -/ +def Interior (q p : ℝ) (phaseD phaseG : MainFamily.BandComponent (M := M) q L U → ℝ) + (x : V) : Prop := + Tiling.Padded a₁ q (v x).height (a₁/10) ∧ + Tiling.Padded a₂ p (v x).height (a₂/10) ∧ + radial A v (hv := hv) q D phaseD x ∧ radial A v (hv := hv) q g phaseG x + +lemma Interior.narrow_sub {q p : ℝ} + {phaseD phaseG : MainFamily.BandComponent (M := M) q L U → ℝ} {x : V} + (h : Interior A v (hv := hv) q p phaseD phaseG x) : + Tiling.band a₂ p (Tiling.index a₂ p (v x).height) ⊆ + BandTrees.band broad (lower A v L U hv q x) := by + have hs := Tiling.narrow_contained (p := p) h.1 + convert hs using 1 + ext H + simp only [BandTrees.band,lower,MainFamily.lower,bandIndex,Tiling.band,Set.mem_Icc] + change (_≤H ∧ H≤q+(Tiling.index a₁ q (v x).height:ℝ)*a₁+a₁) ↔ + (_≤H ∧ H≤q+((Tiling.index a₁ q (v x).height:ℝ)+1)*a₁) + ring_nf + +end PlanarL1.Columns.Model.VertexBands + +namespace PlanarL1.Tiling +lemma same_index_of_padded {a q h x t : ℝ} (ha : 0 .pure (f x))).prob P=E.prob (fun x => P (f x)) := by + rw [prob_bind] + rfl +end PlanarL1.Execution + +namespace PlanarL1.Columns.Model.VertexBands +open Parameters FiniteRandom +attribute [local instance] Classical.propDecidable +variable {k : ℕ} {M : Model (k+1)} {V : Type*} +variable (A : Ambient M) (v : V → M.Point Set.univ A.root) +variable {L U : ℝ} (hv : ∀ x, (v x).height ∈ Set.Icc L U) + +abbrev HeightChoices (m : ℕ) := Fin (m+1) × Fin (m+1) +noncomputable def shift (m : ℕ) (width : ℝ) (i : Fin (m+1)) : ℝ := width/m*i.val +abbrev RadialChoices (m : ℕ) (q L U : ℝ) (M : Model (k+1)) := + (MainFamily.BandComponent (M := M) q L U → Fin (m+1)) × + (MainFamily.BandComponent (M := M) q L U → Fin (m+1)) +abbrev Choices (m : ℕ) (L U : ℝ) (M : Model (k+1)) := + Σ h : HeightChoices m, RadialChoices m (shift m a₁ h.1) L U M +noncomputable def phase {m : ℕ} {q L U : ℝ} (width : ℝ) + (r : MainFamily.BandComponent (M := M) q L U → Fin (m+1)) : + MainFamily.BandComponent (M := M) q L U → ℝ := fun b => shift m width (r b) + +noncomputable def geometricExecution (m : ℕ) (L U : ℝ) (M : Model (k+1)) : + Execution (Choices m L U M) := + Execution.uniform.bind (fun h : HeightChoices m => + Execution.uniform.bind (fun r : RadialChoices m (shift m a₁ h.1) L U M => + .pure ⟨h,r⟩)) + +def InteriorAt {m : ℕ} (c : Choices m L U M) (x : V) : Prop := + Interior A v (hv := hv) (shift m a₁ c.1.1) (shift m a₂ c.1.2) + (phase D c.2.1) (phase g c.2.2) x + +lemma radial_pair_failure (m : ℕ) (hm : 10000 ≤ m) (q : ℝ) (x y : V) + {width : ℝ} (hw : 0 + ¬(radial A v (hv := hv) q width (phase width r) x ∧ + radial A v (hv := hv) q width (phase width r) y))≤81/1000 := by + let i := bandComponent A v L U hv q x + let j := bandComponent A v L U hv q y + let X := BandTrees.radialValue (point A v L U hv q x) + let Y := BandTrees.radialValue (point A v L U hv q y) + apply (prob_mono (P := fun r => ¬(radial A v (hv := hv) q width (phase width r) x ∧ + radial A v (hv := hv) q width (phase width r) y)) + (Q := fun r => Tiling.NearBoundary width (width/m*(r i).val) X (width/50+a₁) ∨ + Tiling.NearBoundary width (width/m*(r j).val) Y (width/50+a₁)) ?_).trans + (radial_pair_probability m hm i j X Y hw hs) + intro r hr + by_contra hn + push Not at hn + exact hr ⟨BandTrees.radialInterior_of_avoid _ hn.1,BandTrees.radialInterior_of_avoid _ hn.2⟩ + +lemma radial_both_failure (m : ℕ) (hm : 10000 ≤ m) (q : ℝ) (x y : V) : + prob (fun r : RadialChoices m q L U M => + ¬(radial A v (hv := hv) q D (phase D r.1) x ∧ + radial A v (hv := hv) q D (phase D r.1) y ∧ + radial A v (hv := hv) q g (phase g r.2) x ∧ + radial A v (hv := hv) q g (phase g r.2) y))≤81/500 := by + let P := fun r : RadialChoices m q L U M => + ¬(radial A v (hv := hv) q D (phase D r.1) x ∧ radial A v (hv := hv) q D (phase D r.1) y) + let Q := fun r : RadialChoices m q L U M => + ¬(radial A v (hv := hv) q g (phase g r.2) x ∧ radial A v (hv := hv) q g (phase g r.2) y) + have hp : prob P≤81/1000 := prob_prod_bound_left P (fun _ => + radial_pair_failure A v hv m hm q x y (width := D) (by norm_num [D]) (by norm_num [a₁,D])) + have hq : prob Q≤81/1000 := prob_prod_bound Q (fun _ => + radial_pair_failure A v hv m hm q x y (width := g) (by norm_num [g]) (by norm_num [a₁,g])) + apply (prob_mono (Q := fun r => P r ∨ Q r) ?_).trans ((prob_or_le P Q).trans (by linarith)) + intro r hr + by_contra hn + have hP : ¬P r := (not_or.mp hn).1 + have hQ : ¬Q r := (not_or.mp hn).2 + exact hr ⟨(not_not.mp hP).1,(not_not.mp hP).2,(not_not.mp hQ).1,(not_not.mp hQ).2⟩ + +/-- A literal finite sequence of shifts followed by component-indexed radial +origins. Component types may depend on the height shifts; using bind avoids a +spurious uniform law on a dependent sum. -/ +lemma interior_pair_probability (m : ℕ) (hm : 10000 ≤ m) (x y : V) + (hd : |(v y).height-(v x).height|≤a₂/10000) : + 1/4≤(geometricExecution m L U M).prob + (fun c => InteriorAt A v hv c x ∧ InteriorAt A v hv c y) := by + let H := fun h : HeightChoices m => + Tiling.Padded a₁ (shift m a₁ h.1) (v x).height (a₁/10) ∧ + Tiling.Padded a₁ (shift m a₁ h.1) (v y).height (a₁/10) ∧ + Tiling.Padded a₂ (shift m a₂ h.2) (v x).height (a₂/10) ∧ + Tiling.Padded a₂ (shift m a₂ h.2) (v y).height (a₂/10) + let P := fun h : HeightChoices m => ¬(Tiling.Padded a₁ (shift m a₁ h.1) (v x).height (a₁/10) ∧ + Tiling.Padded a₁ (shift m a₁ h.1) (v y).height (a₁/10)) + let Q := fun h : HeightChoices m => ¬(Tiling.Padded a₂ (shift m a₂ h.2) (v x).height (a₂/10) ∧ + Tiling.Padded a₂ (shift m a₂ h.2) (v y).height (a₂/10)) + have hp : prob P≤21/100 := prob_prod_bound_left _ (fun _ => + Tiling.height_pair_probability m hm interpolationA.2.1 (by norm_num [a₁,a₂]) hd) + have hq : prob Q≤21/100 := prob_prod_bound _ (fun _ => + Tiling.height_pair_probability m hm interpolationB.2.1 le_rfl hd) + have hheight : Execution.uniform.prob (fun h : HeightChoices m => ¬H h)≤21/50 := by + rw [Execution.prob_uniform] + apply (prob_mono (Q := fun h => P h ∨ Q h) ?_).trans ((prob_or_le P Q).trans (by linarith)) + intro h hh + by_contra hn + have hP : ¬P h := (not_or.mp hn).1 + have hQ : ¬Q h := (not_or.mp hn).2 + exact hh ⟨(not_not.mp hP).1,(not_not.mp hP).2,(not_not.mp hQ).1,(not_not.mp hQ).2⟩ + have hl := Execution.conditional_loss (Execution.uniform (α := HeightChoices m)) + (fun h => Execution.uniform.bind (fun r : RadialChoices m (shift m a₁ h.1) L U M => + .pure (⟨h,r⟩ : Choices m L U M))) H + (fun c => InteriorAt A v hv c x ∧ InteriorAt A v hv c y) + (show (0:ℝ)≤81/500 by norm_num) (by + intro h hh + rw [Execution.prob_bind_pure,Execution.prob_uniform] + apply (prob_mono (Q := fun r : RadialChoices m (shift m a₁ h.1) L U M => + ¬(radial A v (hv := hv) _ D (phase D r.1) x ∧ + radial A v (hv := hv) _ D (phase D r.1) y ∧ + radial A v (hv := hv) _ g (phase g r.2) x ∧ + radial A v (hv := hv) _ g (phase g r.2) y)) ?_).trans + (radial_both_failure A v hv m hm _ x y) + intro r hr hs + dsimp [InteriorAt,Interior] at hr + exact hr ⟨⟨hh.1,hh.2.2.1,hs.1,hs.2.2.1⟩,⟨hh.2.1,hh.2.2.2,hs.2.1,hs.2.2.2⟩⟩) + change (geometricExecution m L U M).prob + (fun c => ¬(InteriorAt A v hv c x ∧ InteriorAt A v hv c y))≤_ at hl + rw [Execution.prob_compl] at hl + linarith + +end PlanarL1.Columns.Model.VertexBands + +end + + + +section + +namespace PlanarL1.Columns.Model.PairGeometry +open Parameters MeasureTheory VertexTests +attribute [local instance] Classical.propDecidable +variable {k : ℕ} {M : Model (k+1)} {V Ω Ξ : Type*} +variable [MeasurableSpace Ω] [MeasurableSpace Ξ] {μ : Measure Ω} {ν : Measure Ξ} +variable (A : Ambient M) (SA : OrdinaryState M kappaA Ω μ) +variable (SB : BState M kappaB SecondaryGeometry.Group.lam Ξ ν) +variable (v : V → M.Point Set.univ A.root) +variable {L U : ℝ} (hv : ∀ x, (v x).height ∈ Set.Icc L U) +variable (q p : ℝ) (phaseD phaseG : MainFamily.BandComponent (M := M) q L U → ℝ) + +noncomputable def narrowLower (x : V) : ℝ := p+(Tiling.index a₂ p (v x).height:ℝ)*a₂ +lemma narrow_height (x : V) : (v x).height ∈ BandTrees.band narrow (narrowLower A v p x) := by + have hh := Tiling.mem_band_index interpolationB.2.1 p (v x).height + change p+(Tiling.index a₂ p (v x).height:ℝ)*a₂≤(v x).height ∧ + (v x).height≤p+(Tiling.index a₂ p (v x).height:ℝ)*a₂+a₂ + constructor <;> dsimp [Tiling.band] at hh <;> linarith [hh.1,hh.2] + +variable {q p phaseD phaseG} {x y : V} +variable (he : Eligible A SA SB v x y) +variable (hi : VertexBands.Interior A v (hv := hv) q p phaseD phaseG x) + +lemma gcell_exists : ∃ c : BandTrees.RadialIndex M broad (VertexBands.lower A v L U hv q x) + (VertexBands.component A v L U hv q x) g (phaseG (VertexBands.bandComponent A v L U hv q x)), + (v x).column ∈ ColumnOrder.componentColumns c.2 := + BandTrees.radial_cover (hw := by norm_num [g]) (hi := rfl) + +noncomputable def position : SurvivingGroups.Position A SA SB + (VertexBands.lower A v L U hv q x) (VertexBands.component A v L U hv q x) + (narrowLower A v p x) (phaseG (VertexBands.bandComponent A v L U hv q x)) where + point := VertexBands.point A v L U hv q x + narrow_height := narrow_height A v p x + cell := (gcell_exists A v hv (q := q) (phaseG := phaseG) (x := x)).choose + cell_mem := (gcell_exists A v hv (q := q) (phaseG := phaseG) (x := x)).choose_spec + lower_pad := (BandTrees.radialInterior_padding (by norm_num [g]) (by norm_num [a₁,g]) + (VertexBands.point A v L U hv q x) hi.2.2.2 _ + (gcell_exists A v hv (q := q) (phaseG := phaseG) (x := x)).choose_spec).1 + upper_pad := (BandTrees.radialInterior_padding (by norm_num [g]) (by norm_num [a₁,g]) + (VertexBands.point A v L U hv q x) hi.2.2.2 _ + (gcell_exists A v hv (q := q) (phaseG := phaseG) (x := x)).choose_spec).2 + indexA := indexA A SA v x + indexB := indexB A SB v x + commonA := by simpa only [VertexBands.point,A.coordinate_point] using he.1 + commonB := by simpa only [VertexBands.point,A.coordinate_point] using he.2.2.1 + +variable (hd : dist (v x) (v y)<2) +include hd in +lemma partner_exists : ∃ z : M.Point (SA.chart (indexA A SA v x)).band + (BandTrees.root M broad (VertexBands.lower A v L U hv q x) (VertexBands.component A v L U hv q x)), + z.column=(v y).column ∧ z.height=(v y).height ∧ + dist ((position A SA SB v hv he hi).point.widen (position A SA SB v hv he hi).subA) z= + dist (v x) (v y) := by + let w := position A SA SB v hv he hi + apply Point.local_point (v x) (v y) (w.point.widen w.subA) rfl rfl + isClosed_univ (Set.subset_univ _) (t := 2) ?_ hd.le + intro H hH + have hs := SA.ball_band A he.1 (J := {H : ℝ | |H-(v x).height|≤2}) (by + intro T hT + rw [abs_sub_comm] + exact hT.trans (by norm_num)) + exact hs hH + +noncomputable def partner : M.Point (SA.chart (indexA A SA v x)).band + (BandTrees.root M broad (VertexBands.lower A v L U hv q x) (VertexBands.component A v L U hv q x)) := + (partner_exists A SA SB v hv he hi hd).choose +lemma partner_column : (partner A SA SB v hv he hi hd).column=(v y).column := + (partner_exists A SA SB v hv he hi hd).choose_spec.1 +lemma partner_height : (partner A SA SB v hv he hi hd).height=(v y).height := + (partner_exists A SA SB v hv he hi hd).choose_spec.2.1 +lemma partner_dist : dist ((position A SA SB v hv he hi).point.widen (position A SA SB v hv he hi).subA) + (partner A SA SB v hv he hi hd)=dist (v x) (v y) := + (partner_exists A SA SB v hv he hi hd).choose_spec.2.2 + +private lemma comparison_transport {D E : OrdinaryData M} (he : D=E) + (i : Fin (k+1)) (H : ℝ) (hD : H ∈ D.band) (hE : H ∈ E.band) : + D.comparison.value i ⟨H,hD⟩=E.comparison.value i ⟨H,hE⟩ := by subst E; rfl + +lemma partner_value : (SA.chart (indexA A SA v x)).comparison.eval (partner A SA SB v hv he hi hd)= + ordinaryValue A SA v y := by + let z := partner A SA SB v hv he hi hd + have hiZ : z.column=(v y).column := partner_column A SA SB v hv he hi hd + have hHZ : z.height=(v y).height := partner_height A SA SB v hv he hi hd + have hHy : (v y).height ∈ (SA.chart (indexA A SA v x)).band := hHZ ▸ z.inBand + have hcell : (SA.chart (indexA A SA v x)).comparison.eval z= + (SA.chart (indexA A SA v x)).comparison.value (v y).column ⟨(v y).height,hHy⟩ := by + change (SA.chart (indexA A SA v x)).comparison.value z.column ⟨z.height,z.inBand⟩=_ + rw [hiZ] + exact congrArg ((SA.chart (indexA A SA v x)).comparison.value (v y).column) (Subtype.ext hHZ) + exact hcell.trans (comparison_transport (congrArg SA.chart (he.namesA A SA SB v).symm) _ _ _ _) + +lemma position_value : (SA.chart (indexA A SA v x)).comparison.eval + ((position A SA SB v hv he hi).point.widen (position A SA SB v hv he hi).subA)=ordinaryValue A SA v x := rfl + +/-- The actual surviving test is just the two descending-path tests and the +absence of a low separating tip, after the literal earlier tests. -/ +def Retained : Prop := + Nonempty ((SA.chart (indexA A SA v x)).comparison.BandDescent + (BandTrees.band broad (VertexBands.lower A v L U hv q x)) + ((position A SA SB v hv he hi).point.widen (position A SA SB v hv he hi).subA) epsilon) ∧ + Nonempty ((SA.chart (indexA A SA v x)).comparison.BandDescent + (BandTrees.band broad (VertexBands.lower A v L U hv q x)) (partner A SA SB v hv he hi hd) epsilon) ∧ + (SA.chart (indexA A SA v x)).comparison.NoLowCircular + ((position A SA SB v hv he hi).point.widen (position A SA SB v hv he hi).subA) + (partner A SA SB v hv he hi hd) (BandTrees.band narrow (narrowLower A v p x)) j + +noncomputable def seed (ha : 1≤dist (v x) (v y)) (hc : Cutoffs A SA SB v x y) + (hr : Retained A SA SB v hv he hi hd) : SurvivingGroups.Seed A SA SB + (VertexBands.lower A v L U hv q x) (VertexBands.component A v L U hv q x) + (narrowLower A v p x) (phaseG (VertexBands.bandComponent A v L U hv q x)) where + toPosition := position A SA SB v hv he hi + partner := partner A SA SB v hv he hi hd + descent := hr.1.some + partner_descent := hr.2.1.some + apart := by rw [partner_dist]; exact ha + close := by + change |(SA.chart (indexA A SA v x)).comparison.eval (partner A SA SB v hv he hi hd)- + (SA.chart (indexA A SA v x)).comparison.eval + ((position A SA SB v hv he hi).point.widen (position A SA SB v hv he hi).subA)|≤EA + rw [partner_value,position_value,abs_sub_comm] + exact hc.2.1.le + retained := hr.2.2 + +end PlanarL1.Columns.Model.PairGeometry + +end + + + +section + +namespace PlanarL1.Columns.Model.OrdinaryState +open MeasureTheory Parameters +attribute [local instance] Classical.propDecidable +variable {n : ℕ} {M : Model n} {Ω : Type*} [MeasurableSpace Ω] {μ : Measure Ω} +variable (S : OrdinaryState M kappaA Ω μ) + +/-- Failure of the actual circular low-tip test produces the literal source +certificate, including its tip and measurable positive label mass. -/ +lemma low_tip_certificate (a : Fin (S.count+1)) {root : Fin n} + (x y : M.Point (S.chart a).band root) (lo : ℝ) + (hx : S.name x.column x.height=a) (hy : S.name y.column y.height=a) + (hxH : x.height ∈ Set.Icc lo (lo+a₂)) (hyH : y.height ∈ Set.Icc lo (lo+a₂)) + (hclose : |(S.chart a).comparison.eval x-(S.chart a).comparison.eval y| ≤ EA) + (hnear : ∀ e : M.Point (S.chart a).band root, + (dist x e ≤ 1 ∨ dist y e ≤ 1) → S.name e.column e.height=a) + (hf : ¬(S.chart a).comparison.NoLowCircular x y (Set.Icc lo (lo+a₂)) j) : + ∃ (e : M.Point (S.chart a).band root) (b : Fin n) (E : Set Ω), + e.height ∈ M.heights e.column b ∧ ¬Consecutive e.column b ∧ + Field.CircularTipSeparates e.column b x.column y.column ∧ + (dist x e ≤ 1 ∨ dist y e ≤ 1) ∧ + MeasurableSet E ∧ kappaA*j/4 ≤ μ.real E ∧ + (∀ ω ∈ E, (S.sets.activity ω).active x.column x.height) ∧ + (∀ ω ∈ E, (S.sets.activity ω).active y.column y.height) ∧ + (∀ ω ∈ E, ¬(S.sets.activity ω).active e.column e.height) := by + unfold Field.NoLowCircular at hf + push Not at hf + obtain ⟨e,b,heH,hlink,hn,hsep,hd,hdrop⟩ := hf + have hdrop' : (S.chart a).comparison.eval e < (S.chart a).comparison.eval x-j ∨ + (S.chart a).comparison.eval e < (S.chart a).comparison.eval y-j := by + by_cases h : (S.chart a).comparison.eval e < (S.chart a).comparison.eval x-j + · exact Or.inl h + · exact Or.inr (hdrop (le_of_not_gt h)) + obtain ⟨E,hE,hm,hX,hY,hN⟩ := S.barrier_labels a x y e hx hy (hnear e hd) hxH hyH heH hclose hdrop' + exact ⟨e,b,E,hlink,hn,hsep,hd,hE,hm,hX,hY,hN⟩ + +lemma barrier_refined_separation [SFinite μ] (a : Fin (S.count+1)) {root : Fin n} + (o x y e : M.Point (S.chart a).band root) (b : Fin n) + (hx : S.name x.column x.height=a) (hy : S.name y.column y.height=a) + (he : S.name e.column e.height=a) + {lo : ℝ} (hxH : x.height ∈ Set.Icc lo (lo+a₂)) + (hyH : y.height ∈ Set.Icc lo (lo+a₂)) (heH : e.height ∈ Set.Icc lo (lo+a₂)) + (hclose : |(S.chart a).comparison.eval x-(S.chart a).comparison.eval y| ≤ EA) + (hdrop : (S.chart a).comparison.eval e < (S.chart a).comparison.eval x-j ∨ + (S.chart a).comparison.eval e < (S.chart a).comparison.eval y-j) + (hlink : e.height ∈ M.heights e.column b) (hn : ¬Consecutive e.column b) + (hsep : Field.CircularTipSeparates e.column b x.column y.column) : + kappaA*j/2 ≤ ‖S.sets.refinedMap o x-S.sets.refinedMap o y‖ := by + obtain ⟨E,hE,hm,hX,hY,hN⟩ := S.barrier_labels a x y e hx hy he hxH hyH heH hclose hdrop + have h := (S.sets.refinedMap_terminal_circular o x y hlink hn hsep E hE hN hX hY).2 + linarith +end PlanarL1.Columns.Model.OrdinaryState + +end + + + +section + +namespace PlanarL1.Columns.Model +attribute [local instance] Classical.propDecidable +variable {n : ℕ} {M : Model n} {I J K : Set ℝ} {r s : Fin n} +namespace Point +lemma eq_coordinates (x y : M.Point I r) (hc : x.column=y.column) (hh : x.height=y.height) : x=y := by + cases x + cases y + cases hc + cases hh + rfl +end Point +namespace Field +variable {F : M.Field I 1} {ε j : ℝ} +lemma BandDescent.coordinates {x : M.Point I r} {y : M.Point I s} + (D : F.BandDescent J x ε) (hc : x.column=y.column) (hh : x.height=y.height) : + Nonempty (F.BandDescent J y ε) := by + have hr : (M.activeGraph I).Reachable s r := y.reachable.trans (hc ▸ x.reachable).symm + have he : x.reRoot hr=y := Point.eq_coordinates _ _ hc hh + exact he ▸ ⟨D.reRoot hr⟩ + +lemma NoLowCircular.symm {x y : M.Point I r} (h : F.NoLowCircular x y J j) : + F.NoLowCircular y x J j := by + intro v b hv hs hn ht hd + have ht' : CircularTipSeparates v.column b x.column y.column := by + simpa only [CircularTipSeparates,TipSeparates,or_comm] using ht + exact (h v b hv hs hn ht' hd.symm).symm + +lemma NoLowCircular.coordinates {x y : M.Point I r} {x' y' : M.Point I s} + (H : F.NoLowCircular x y J j) + (hxc : x.column=x'.column) (hxh : x.height=x'.height) + (hyc : y.column=y'.column) (hyh : y.height=y'.height) : F.NoLowCircular x' y' J j := by + have hr : (M.activeGraph I).Reachable s r := x'.reachable.trans (hxc ▸ x.reachable).symm + have he : x.reRoot hr=x' := Point.eq_coordinates _ _ hxc hxh + have hf : y.reRoot hr=y' := Point.eq_coordinates _ _ hyc hyh + exact he ▸ hf ▸ H.reRoot hr +end Field +namespace OrdinaryData +lemma descent_coordinates {D E : OrdinaryData M} (hDE : D=E) {J K : Set ℝ} (hJK : J=K) + {r s : Fin n} (x : M.Point D.band r) (y : M.Point E.band s) {ε : ℝ} + (h : Nonempty (D.comparison.BandDescent J x ε)) + (hc : x.column=y.column) (hh : x.height=y.height) : + Nonempty (E.comparison.BandDescent K y ε) := by + subst E + subst K + exact h.some.coordinates hc hh +lemma noLow_coordinates {D E : OrdinaryData M} (hDE : D=E) {J K : Set ℝ} (hJK : J=K) + {r s : Fin n} (x y : M.Point D.band r) (x' y' : M.Point E.band s) {j : ℝ} + (h : D.comparison.NoLowCircular x y J j) + (hxc : x.column=x'.column) (hxh : x.height=x'.height) + (hyc : y.column=y'.column) (hyh : y.height=y'.height) : E.comparison.NoLowCircular x' y' K j := by + subst E + subst K + exact h.coordinates hxc hxh hyc hyh +end OrdinaryData +end PlanarL1.Columns.Model + +end + + + +section + +namespace PlanarL1.Columns.Model.RetainedSelection +open Parameters MeasureTheory VertexTests +attribute [local instance] Classical.propDecidable +variable {k : ℕ} {M : Model (k+1)} {V Ω Ξ : Type*} +variable [Fintype V] [MeasurableSpace Ω] [MeasurableSpace Ξ] +variable {μ : Measure Ω} {ν : Measure Ξ} +variable (A : Ambient M) (SA : OrdinaryState M kappaA Ω μ) +variable (SB : BState M kappaB SecondaryGeometry.Group.lam Ξ ν) +variable (v : V → M.Point Set.univ A.root) +variable (L U : ℝ) (hv : ∀ x, (v x).height ∈ Set.Icc L U) +variable (q p : ℝ) (phaseD phaseG : MainFamily.BandComponent (M := M) q L U → ℝ) + +/-- A literal surviving partner. This is tested before any group coin or +orientation is drawn, and never asserts success of an update. -/ +structure Witness (x : V) where + other : V + test : PairTest A SA SB v (x,other) + cutoffs : Cutoffs A SA SB v x other + interior : VertexBands.Interior A v (hv := hv) q p phaseD phaseG x + other_interior : VertexBands.Interior A v (hv := hv) q p phaseD phaseG other + retained : PairGeometry.Retained A SA SB v hv test.2.2 interior test.2.1 + +noncomputable def remaining : Finset V := + Finset.univ.filter (fun x => Nonempty (Witness A SA SB v L U hv q p phaseD phaseG x)) +noncomputable abbrev Endpoint := remaining A SA SB v L U hv q p phaseD phaseG +noncomputable instance : Fintype (Endpoint A SA SB v L U hv q p phaseD phaseG) := Fintype.ofFinite _ + +variable {L U q p phaseD phaseG} +lemma mem_remaining (x : V) : x ∈ remaining A SA SB v L U hv q p phaseD phaseG ↔ + Nonempty (Witness A SA SB v L U hv q p phaseD phaseG x) := by + simp only [remaining,Finset.mem_filter,Finset.mem_univ,true_and] +noncomputable def witness (w : Endpoint A SA SB v L U hv q p phaseD phaseG) : + Witness A SA SB v L U hv q p phaseD phaseG w.val := + ((mem_remaining A SA SB v hv w.val).mp w.property).some + +/-- Finite processed broad-component/narrow-band blocks. In particular no +infinite family of unused tail bands is randomized. -/ +def Block (q p L U : ℝ) := Σ b : MainFamily.BandComponent (M := M) q L U, + {n : Tiling.processed a₂ p L U // + Tiling.band a₂ p n.val ⊆ BandTrees.band broad (MainFamily.lower q L U b.1)} +noncomputable instance : Fintype (Block (M := M) q p L U) := by + unfold Block + exact Fintype.ofFinite _ + +namespace Block +variable (b : Block (M := M) q p L U) +noncomputable def lower : ℝ := MainFamily.lower q L U b.1.1 +noncomputable def lower₂ : ℝ := p+(b.2.val.val:ℝ)*a₂ +lemma sub : BandTrees.band narrow b.lower₂ ⊆ BandTrees.band broad b.lower := by + change _ ⊆ BandTrees.band broad (MainFamily.lower q L U b.1.1) + convert b.2.property using 1 + ext H + simp only [BandTrees.band,lower₂,Tiling.band,Set.mem_Icc] + change (_≤H ∧ H≤p+(b.2.val.val:ℝ)*a₂+a₂) ↔ (_≤H ∧ H≤p+((b.2.val.val:ℝ)+1)*a₂) + ring_nf +end Block + +noncomputable def block (w : Endpoint A SA SB v L U hv q p phaseD phaseG) : Block (M := M) q p L U := + ⟨VertexBands.bandComponent A v L U hv q w.val, + ⟨⟨Tiling.index a₂ p (v w.val).height, + (Tiling.mem_processed interpolationB.2.1 p L U _).mpr + ⟨(v w.val).height,Tiling.mem_band_index interpolationB.2.1 p _,hv w.val⟩⟩, + (witness A SA SB v hv w).interior.narrow_sub A v⟩⟩ + +abbrev LocalSeed (b : Block (M := M) q p L U) := + SurvivingGroups.Seed A SA SB b.lower b.1.2 b.lower₂ (phaseG b.1) + +noncomputable def rawSeed (w : Endpoint A SA SB v L U hv q p phaseD phaseG) : + LocalSeed A SA SB (phaseG := phaseG) (block A SA SB v hv w) := + PairGeometry.seed A SA SB v hv (witness A SA SB v hv w).test.2.2 + (witness A SA SB v hv w).interior (witness A SA SB v hv w).test.2.1 + (witness A SA SB v hv w).test.1 (witness A SA SB v hv w).cutoffs + (witness A SA SB v hv w).retained + +abbrev Slice (b : Block (M := M) q p L U) := + {w : Endpoint A SA SB v L U hv q p phaseD phaseG // block A SA SB v hv w=b} +noncomputable def localSeeds (b : Block (M := M) q p L U) (w : Slice A SA SB v hv (phaseD := phaseD) (phaseG := phaseG) b) : + LocalSeed A SA SB (phaseG := phaseG) b := w.property ▸ rawSeed A SA SB v hv w.val + +noncomputable abbrev GroupIndex := Σ b : Block (M := M) q p L U, + SurvivingGroups.GroupIndex (localSeeds A SA SB v hv (phaseD := phaseD) (phaseG := phaseG) b) +noncomputable instance : Fintype (GroupIndex A SA SB v hv (p := p) (phaseD := phaseD) (phaseG := phaseG)) := + Fintype.ofFinite _ + +noncomputable def group (i : GroupIndex A SA SB v hv (p := p) (phaseD := phaseD) (phaseG := phaseG)) : + SecondaryGeometry.Group A SB := SurvivingGroups.group (localSeeds A SA SB v hv i.1) i.1.sub i.2 + +noncomputable def groupOf (w : Endpoint A SA SB v L U hv q p phaseD phaseG) : + GroupIndex A SA SB v hv (p := p) (phaseD := phaseD) (phaseG := phaseG) := + ⟨block A SA SB v hv w,⟨SurvivingGroups.key (localSeeds A SA SB v hv _) ⟨w,rfl⟩, + Finset.mem_image.mpr ⟨⟨w,rfl⟩,Finset.mem_univ _,rfl⟩⟩⟩ + +lemma localSeeds_self (w : Endpoint A SA SB v L U hv q p phaseD phaseG) : + localSeeds A SA SB v hv (block A SA SB v hv w) ⟨w,rfl⟩=rawSeed A SA SB v hv w := rfl + +lemma groupOf_seed (w : Endpoint A SA SB v L U hv q p phaseD phaseG) : + (rawSeed A SA SB v hv w).point ∈ (group A SA SB v hv (groupOf A SA SB v hv w)).seeds := by + exact (SurvivingGroups.seed_mem _ _).mpr ⟨⟨w,rfl⟩,rfl,rfl⟩ + +lemma rawSeed_column (w : Endpoint A SA SB v L U hv q p phaseD phaseG) : + (rawSeed A SA SB v hv w).point.column=(v w.val).column := rfl +lemma rawSeed_height (w : Endpoint A SA SB v L U hv q p phaseD phaseG) : + (rawSeed A SA SB v hv w).point.height=(v w.val).height := rfl + +end PlanarL1.Columns.Model.RetainedSelection + +end + + + +section + +namespace PlanarL1.Columns.Model.PairGeometry +open Parameters MeasureTheory VertexTests +variable {k : ℕ} {M : Model (k+1)} {V Ω Ξ : Type*} +variable [MeasurableSpace Ω] [MeasurableSpace Ξ] {μ : Measure Ω} {ν : Measure Ξ} +variable (A : Ambient M) (SA : OrdinaryState M kappaA Ω μ) +variable (SB : BState M kappaB SecondaryGeometry.Group.lam Ξ ν) +variable (v : V → M.Point Set.univ A.root) +variable {L U : ℝ} (hv : ∀ x, (v x).height ∈ Set.Icc L U) +variable {q p : ℝ} {phaseD phaseG : MainFamily.BandComponent (M := M) q L U → ℝ} +variable {x y : V} (he : Eligible A SA SB v x y) +variable (hi : VertexBands.Interior A v (hv := hv) q p phaseD phaseG x) +variable (hj : VertexBands.Interior A v (hv := hv) q p phaseD phaseG y) +variable (hc : Cutoffs A SA SB v x y) (hd : dist (v x) (v y)<2) + +include hi hc in +lemma broad_lower_eq : VertexBands.lower A v L U hv q y=VertexBands.lower A v L U hv q x := by + have hxy : |(v y).height-(v x).height|≤a₁/10 := by + rw [abs_sub_comm] + exact hc.1.le.trans (by norm_num [a₂,a₁]) + have hn := Tiling.same_index_of_padded interpolationA.2.1 hi.1 hxy + change q+(Tiling.index a₁ q (v y).height:ℝ)*a₁=q+(Tiling.index a₁ q (v x).height:ℝ)*a₁ + rw [hn] + +include hi hc in +lemma narrow_lower_eq : narrowLower A v p y=narrowLower A v p x := by + have hxy : |(v y).height-(v x).height|≤a₂/10 := by + rw [abs_sub_comm] + exact hc.1.le.trans (by norm_num [a₂]) + have hn := Tiling.same_index_of_padded interpolationB.2.1 hi.2.1 hxy + unfold narrowLower + rw [hn] + +include hc in +lemma Retained.symm (hr : Retained A SA SB v hv he hi hd) : + Retained A SA SB v hv (he.symm A SA SB v) hj (by simpa only [dist_comm] using hd) := by + have hD : SA.chart (indexA A SA v x)=SA.chart (indexA A SA v y) := + congrArg SA.chart (he.namesA A SA SB v).symm + have hJ : BandTrees.band broad (VertexBands.lower A v L U hv q x)= + BandTrees.band broad (VertexBands.lower A v L U hv q y) := + congrArg (BandTrees.band broad) (broad_lower_eq A SA SB v hv hi hc).symm + have hK : BandTrees.band narrow (narrowLower A v p x)=BandTrees.band narrow (narrowLower A v p y) := + congrArg (BandTrees.band narrow) (narrow_lower_eq A SA SB v hv hi hc).symm + let he' := he.symm A SA SB v + have hd' : dist (v y) (v x)<2 := by simpa only [dist_comm] using hd + have hyc : (partner A SA SB v hv he hi hd).column= + ((position A SA SB v hv he' hj).point.widen (position A SA SB v hv he' hj).subA).column := + partner_column A SA SB v hv he hi hd + have hyh : (partner A SA SB v hv he hi hd).height= + ((position A SA SB v hv he' hj).point.widen (position A SA SB v hv he' hj).subA).height := + partner_height A SA SB v hv he hi hd + have hxc : ((position A SA SB v hv he hi).point.widen (position A SA SB v hv he hi).subA).column= + (partner A SA SB v hv he' hj hd').column := + (partner_column A SA SB v hv he' hj hd').symm + have hxh : ((position A SA SB v hv he hi).point.widen (position A SA SB v hv he hi).subA).height= + (partner A SA SB v hv he' hj hd').height := + (partner_height A SA SB v hv he' hj hd').symm + exact ⟨OrdinaryData.descent_coordinates hD hJ _ _ hr.2.1 hyc hyh, + OrdinaryData.descent_coordinates hD hJ _ _ hr.1 hxc hxh, + OrdinaryData.noLow_coordinates hD hK _ _ _ _ hr.2.2.symm hyc hyh hxc hxh⟩ +end PlanarL1.Columns.Model.PairGeometry + +end + + + +section + +namespace PlanarL1.Columns.Model.Ambient +variable {k : ℕ} {M : Model (k+1)} (A : Ambient M) +lemma coordinate_dist_le {J : Set ℝ} {r : Fin (k+1)} (x y : M.Point J r) : + dist (A.point x.column x.height) (A.point y.column y.height) ≤ dist x y := by + calc + _ = dist (x.widen (Set.subset_univ _)) (y.widen (Set.subset_univ _)) := + Point.dist_coordinates _ _ _ _ rfl rfl rfl rfl + _ ≤ _ := x.dist_widen_le y (Set.subset_univ _) +end PlanarL1.Columns.Model.Ambient + +namespace PlanarL1.Columns.Model.PairGeometry +open Parameters MeasureTheory VertexTests +attribute [local instance] Classical.propDecidable +variable {k : ℕ} {M : Model (k+1)} {V Ω Ξ : Type*} +variable [MeasurableSpace Ω] [MeasurableSpace Ξ] {μ : Measure Ω} {ν : Measure Ξ} +variable (A : Ambient M) (SA : OrdinaryState M kappaA Ω μ) +variable (SB : BState M kappaB SecondaryGeometry.Group.lam Ξ ν) +variable (v : V → M.Point Set.univ A.root) +variable {L U : ℝ} (hv : ∀ x, (v x).height ∈ Set.Icc L U) +variable {q p : ℝ} {phaseD phaseG : MainFamily.BandComponent (M := M) q L U → ℝ} +variable {x y : V} (he : Eligible A SA SB v x y) +variable (hi : VertexBands.Interior A v (hv := hv) q p phaseD phaseG x) +variable (hc : Cutoffs A SA SB v x y) (hd : dist (v x) (v y)<2) + +/-- The source component certificate on literal active labels and an actual +terminal link. Its labels, tip and positive mass are not extra input. -/ +def Certificate (b : ℝ) : Prop := + ∃ (a c : Fin (k+1)) (H : ℝ) (E : Set Ω), + H ∈ M.heights a c ∧ ¬Consecutive a c ∧ + Field.CircularTipSeparates a c (v x).column (v y).column ∧ + MeasurableSet E ∧ b ≤ μ.real E ∧ + (∀ ω ∈ E, (SA.sets.activity ω).active (v x).column (v x).height) ∧ + (∀ ω ∈ E, (SA.sets.activity ω).active (v y).column (v y).height) ∧ + (∀ ω ∈ E, ¬(SA.sets.activity ω).active a H) + +include hc in +lemma certificate_of_excluded + (hf : ¬(SA.chart (indexA A SA v x)).comparison.NoLowCircular + ((position A SA SB v hv he hi).point.widen (position A SA SB v hv he hi).subA) + (partner A SA SB v hv he hi hd) (BandTrees.band narrow (narrowLower A v p x)) j) : + Certificate A SA v (x := x) (y := y) (kappaA*j/4) := by + let u : M.Point (SA.chart (indexA A SA v x)).band + (BandTrees.root M broad (VertexBands.lower A v L U hv q x) (VertexBands.component A v L U hv q x)) := (position A SA SB v hv he hi).point.widen (position A SA SB v hv he hi).subA + let z := partner A SA SB v hv he hi hd + have hxH : u.height ∈ Set.Icc (narrowLower A v p x) (narrowLower A v p x+a₂) := + narrow_height A v p x + have hyH : z.height ∈ Set.Icc (narrowLower A v p x) (narrowLower A v p x+a₂) := by + have hy := narrow_height A v p y + rw [narrow_lower_eq A SA SB v hv hi hc] at hy + simpa only [z,partner_height,BandTrees.band,narrow] using hy + have hn : SA.name z.column z.height=indexA A SA v x := by + rw [partner_column,partner_height] + exact he.namesA A SA SB v + have hnear (e : M.Point (SA.chart (indexA A SA v x)).band + (BandTrees.root M broad (VertexBands.lower A v L U hv q x) (VertexBands.component A v L U hv q x))) + (h : dist u e≤1 ∨ dist z e≤1) : SA.name e.column e.height=indexA A SA v x := by + rcases h with h | h + · have hb := (A.coordinate_dist_le u e).trans h + change dist (A.point (v x).column (v x).height) (A.point e.column e.height)≤1 at hb + rw [A.coordinate_point] at hb + exact he.1 _ (hb.trans (by norm_num)) + · have hb := (A.coordinate_dist_le z e).trans h + rw [partner_column,partner_height,A.coordinate_point] at hb + exact he.2.1 _ (hb.trans (by norm_num)) + have hclose : |(SA.chart (indexA A SA v x)).comparison.eval u- + (SA.chart (indexA A SA v x)).comparison.eval z|≤EA := by + calc + _ = |ordinaryValue A SA v x-ordinaryValue A SA v y| := + congrArg₂ (fun a b : ℝ => |a-b|) (position_value A SA SB v hv he hi) + (partner_value A SA SB v hv he hi hd) + _ ≤ _ := hc.2.1.le + obtain ⟨e,c,E,hlink,hnot,hsep,_,hE,hm,hX,hY,hN⟩ := + SA.low_tip_certificate (indexA A SA v x) u z (narrowLower A v p x) rfl hn hxH hyH hclose hnear hf + refine ⟨e.column,c,e.height,E,hlink,hnot,?_,hE,hm,hX,?_,hN⟩ + · change Field.CircularTipSeparates e.column c (v x).column z.column at hsep + simpa only [z,partner_column] using hsep + · simpa only [z,partner_column,partner_height] using hY +end PlanarL1.Columns.Model.PairGeometry + +end + + + +section + +namespace PlanarL1.Columns.Model.MainFamily +open Parameters MeasureTheory +attribute [local instance] Classical.propDecidable +variable {k : ℕ} {M : Model (k+1)} {Ω : Type*} +variable [MeasurableSpace Ω] {μ : Measure Ω} +variable (A : Ambient M) (S : OrdinaryState M kappaA Ω μ) +variable {q L U : ℝ} (phase : BandComponent (M := M) q L U → ℝ) + +/-- The literal radius-five eligibility test suffices for the full closed +one-neighborhood availability of every cell containing this endpoint. -/ +lemma available_of_ball5 (c : CellIndex q L U phase) (x : M.Point Set.univ A.root) + (hx : x.height ∈ domain phase c x.column) {a : Fin (S.count+1)} + (hname : A.Common S.name x 5 a) : Available A S phase c := by + refine ⟨a,fun y hy => hname y ?_⟩ + obtain ⟨i,H,hi,hd⟩ := hy + have hxpoint : A.point x.column x.height=x := A.coordinate_point x + have hc := cell_diameter A phase c hx hi + rw [hxpoint] at hc + have ht := dist_triangle x (A.point i H) y + rw [dist_comm (A.point i H) y] at ht + linarith + +lemma distinct_cells (x y : M.Point Set.univ A.root) + (ha : 1≤dist x y) (c d : CellIndex q L U phase) + (hx : x.height ∈ domain phase c x.column) (hy : y.height ∈ domain phase d y.column) : c≠d := by + intro he + subst d + have h := cell_diameter A phase c hx hy + rw [A.coordinate_point x,A.coordinate_point y] at h + linarith + +end PlanarL1.Columns.Model.MainFamily + +end + +end OAI diff --git a/lean/OAI/Combinatorics/PlanarL1/Parameters.lean b/lean/OAI/Combinatorics/PlanarL1/Parameters.lean new file mode 100644 index 0000000000000000000000000000000000000000..13c078d0bf089be4b0e32b4e0dcdba183a8cb6eb --- /dev/null +++ b/lean/OAI/Combinatorics/PlanarL1/Parameters.lean @@ -0,0 +1,71 @@ +import Mathlib + +namespace OAI + + +section + +namespace PlanarL1.Parameters +noncomputable section +/-- Universal ordered parameter choices. The two free widths are chosen +strictly smaller than every displayed upper bound, not adapted to a graph. -/ +def R : ℝ := 1/10^8 +def D : ℝ := 1/10^3 +def g : ℝ := 1/10^14 +def j : ℝ := 1/10^20 +def epsilon : ℝ := 1/10^24 +def EA : ℝ := epsilon/1000 +def EB : ℝ := R/1000 +def zetaA : ℝ := epsilon/100 +def zetaB : ℝ := 1/10 +def a₁ : ℝ := 1/10^100 +def a₂ : ℝ := 1/10^160 +def kappaA : ℝ := a₁/10^6 +def kappaB : ℝ := a₂/10^6 +def lambda : ℝ := R/(10^12*100) + +lemma positive : 0 ∃ z : Group.Ball x (ρ := ρ), + (SecondaryGeometry.result (group A SA SB v hv) hm (flatSample (group A SA SB v hv) o coins w)).name z.val.column z.val.height≠ + (SecondaryGeometry.result (group A SA SB v hv) hm (flatSample (group A SA SB v hv) o coins w)).name x.column x.height) ≤ + (1+SurvivingGroups.packBound*secondaryN : ℕ)^2*secondaryTestLoss ρ m := by + classical + let G := group A SA SB v hv (p := p) (phaseD := phaseD) (phaseG := phaseG) + have hBand (z : Group.Ball x (ρ := ρ)) : z.val.height∈(SB.chart a).band := + SB.height_named _ _ _ (hold z.val z.property) + apply prob_bound_of_instances + apply persistence_flat G o coins a x hBand hρ hm hsmall hr _ + (fun z => hold z.val z.property) _ (wholeBallSlots_card A SA SB v hv x o coins a hρ hp hn) + · intro z + have hb : ∀ H, |H-x.height|≤ρ → H∈(SB.chart a).band := by + intro H hH + exact SB.ball_band A hold (J := {T | |T-x.height|≤ρ}) + (fun T hT => by simpa only [Set.mem_ofPred_eq,abs_sub_comm] using hT) hH + obtain ⟨hX,hZ,he⟩ := ((SB.chart a).comparison Group.lam Group.lam_bound (o a)).ball_variation x z.val hρ hb z.property + apply he.trans + apply mul_le_mul_of_nonneg_right _ hρ + exact_mod_cast (le_max_left (5 : ℝ≥0) ⟨3/(9*a₂/100),by norm_num [a₂]⟩) + · intro j ⟨z,hz⟩ H hH + exact group_touched_envelope A SA SB v hv x hρ hn + (coord G o coins (m := m) a j).1 (o a) (coord G o coins (m := m) a j).2 + z.property hz H hH + +lemma persistence_probability [SFinite ν] : + prob (fun omega : Sample (group A SA SB v hv (p := p) (phaseD := phaseD) (phaseG := phaseG)) m => + ∃ z : Group.Ball x (ρ := ρ), + (SecondaryGeometry.result (group A SA SB v hv) hm omega).name z.val.column z.val.height≠ + (SecondaryGeometry.result (group A SA SB v hv) hm omega).name x.column x.height) ≤ + (1+SurvivingGroups.packBound*secondaryN : ℕ)^2*secondaryTestLoss ρ m := by + classical + let G := group A SA SB v hv (p := p) (phaseD := phaseD) (phaseG := phaseG) + apply prob_prod_bound_any + intro o + apply prob_prod_bound_any + intro coins + rw [←prob_equiv (Equiv.piCurry (fun i C => ComponentSample G i C m))] + apply prob_bound_of_instances + exact persistence_fixed A SA SB v hv x hρ hp hn a hold hsmall hr hm o coins +end PlanarL1.Columns.Model.RetainedSelection + +end + + + +section + +namespace PlanarL1.Execution +variable {α : Type*} +lemma choose_upper (n : ℕ) (E : Fin (n+1) → Execution α) (P : α → Prop) {b : ℝ} + (h : ∀ i, (E i).prob P ≤ b) : (Execution.choose n E).prob P ≤ b := by + change (∑ i, (E i).prob P)/(n+1) ≤ b + have hp : (0:ℝ) h i) + _ = _ := by simp; ring +end PlanarL1.Execution + +namespace PlanarL1.Parameters +lemma mainLoss_nonneg {ρ : ℝ} (hρ : 0 ≤ ρ) (m : ℕ) : 0 ≤ mainLoss ρ m := by + unfold mainLoss mainTestLoss + positivity [mainQ_pos,interpolationA.1] +lemma secondaryLoss_nonneg {ρ : ℝ} (hρ : 0 ≤ ρ) (m : ℕ) : 0 ≤ secondaryLoss ρ m := + mul_nonneg (sq_nonneg _) (secondaryTestLoss_nonneg hρ m) +noncomputable def persistenceLoss (ρ : ℝ) (m : ℕ) : ℝ := + heightLoss ρ m+(mainLoss ρ m+secondaryLoss ρ m) +end PlanarL1.Parameters + +namespace PlanarL1.Columns.Model.CoupledState +open MeasureTheory Parameters SecondaryGeometry VertexBands VertexTests +open scoped NNReal +attribute [local instance] Classical.propDecidable +attribute [local irreducible] FiniteRandom.prob +variable {k : ℕ} {M : Model (k+1)} {V Ω Ξ : Type*} +variable [MeasurableSpace Ω] [MeasurableSpace Ξ] {μ : Measure Ω} {ν : Measure Ξ} +variable {A : Ambient M} {t : ℝ} (S : CoupledState A Ω Ξ μ ν t) + +def Coherent (x : M.Point Set.univ A.root) (ρ : ℝ) : Prop := + ∀ z : M.Point Set.univ A.root, dist x z ≤ ρ → + S.left.name z.column z.height=S.left.name x.column x.height ∧ + S.right.name z.column z.height=S.right.name x.column x.height + +lemma Coherent.lift {x : M.Point Set.univ A.root} {ρ : ℝ} (h : S.Coherent x ρ) : + S.lift.Coherent x ρ := h + +variable (ht : 1 ≤ t) (hgap : 10 ≤ (R/200)*t) +variable [SFinite μ] [SFinite ν] [Fintype V] +variable (v : V → M.Point Set.univ A.root) {L U : ℝ} +variable (hv : ∀ x, (v x).height ∈ Set.Icc L U) +variable {q : ℝ} (phaseD : MainFamily.BandComponent (M := M) q L U → ℝ) +variable {m : ℕ} (hm : 0 < m) (p : ℝ) (phaseG : MainFamily.BandComponent (M := M) q L U → ℝ) +variable (x : V) {ρ : ℝ} (hρ : 0 ≤ ρ) (hr : ρ ≤ persistenceRadius) (hold : S.Coherent (v x) ρ) + +omit [SFinite ν] [Fintype V] in +include hv hρ hr hold in +lemma main_persistence (hp : Tiling.Padded a₁ q (v x).height ρ) : + FiniteRandom.prob (fun omega : MainFamily.Sample phaseD m => + ¬(S.main ht phaseD hm omega).Coherent (v x) ρ) ≤ mainLoss ρ m := by + let c := mainCell A v hv phaseD x + have hh := MainFamily.persistence_probability A S.left phaseD (v x) c + (mainCell_mem A v hv phaseD x) hρ hp (persistence_main_small hr) + (persistence_main_radius hr) (fun z hz => (hold z hz).1) m hm + apply (FiniteRandom.prob_mono (Q := fun omega : MainFamily.Sample phaseD m => + ∃ z : M.Point Set.univ A.root, dist (v x) z ≤ ρ ∧ + (MainFamily.result A S.left phaseD hm omega).name z.column z.height≠ + (MainFamily.result A S.left phaseD hm omega).name (v x).column (v x).height) ?_).trans hh + intro omega hb + by_contra hn + apply hb + intro z hz + exact ⟨not_ne_iff.mp (fun he => hn ⟨z,hz,he⟩),(hold z hz).2⟩ + +omit [SFinite μ] in +include hv hρ hr hold in +lemma secondary_persistence (hp : Tiling.Padded a₁ q (v x).height ρ) + (hn : Tiling.Padded a₂ p (v x).height ρ) : + FiniteRandom.prob (fun omega : SecondaryGeometry.Sample (S.groups v hv phaseD p phaseG) m => + ¬(S.secondary ht v hv phaseD hm p phaseG omega).Coherent (v x) ρ) ≤ secondaryLoss ρ m := by + have hh := RetainedSelection.persistence_probability A S.left S.right v hv (phaseD := phaseD) (phaseG := phaseG) (v x) hρ hp hn + (S.right.name (v x).column (v x).height) (fun z hz => (hold z hz).2) + (persistence_secondary_small hr) (persistence_secondary_radius hr) hm + apply (FiniteRandom.prob_mono (Q := fun omega : SecondaryGeometry.Sample (S.groups v hv phaseD p phaseG) m => + ∃ z : Group.Ball (v x) (ρ := ρ), + (SecondaryGeometry.result (S.groups v hv phaseD p phaseG) hm omega).name z.val.column z.val.height≠ + (SecondaryGeometry.result (S.groups v hv phaseD p phaseG) hm omega).name (v x).column (v x).height) ?_).trans hh + intro omega hb + by_contra hn + apply hb + intro z hz + exact ⟨(hold z hz).1,not_ne_iff.mp (fun he => hn ⟨⟨z,hz⟩,he⟩)⟩ + +include hv hρ hr hold in +lemma modes_persistence (hp : Tiling.Padded a₁ q (v x).height ρ) + (hn : Tiling.Padded a₂ p (v x).height ρ) : + (S.modes ht hgap v hv phaseD hm p phaseG).prob (fun z => ¬z.Coherent (v x) ρ) ≤ + mainLoss ρ m+secondaryLoss ρ m := by + have hA := mainLoss_nonneg hρ m + have hB := secondaryLoss_nonneg hρ m + apply Execution.choose_upper + intro i + fin_cases i + · change (Execution.pure (S.unchanged ht)).prob (fun z => ¬z.Coherent (v x) ρ) ≤ _ + have hg : (S.unchanged ht).Coherent (v x) ρ := hold + simp only [Execution.prob_pure,hg,not_true_eq_false,ite_false] + exact add_nonneg hA hB + · change (Execution.uniform.bind (fun omega => .pure (S.main ht phaseD hm omega))).prob + (fun z => ¬z.Coherent (v x) ρ) ≤ _ + rw [Execution.prob_bind_pure,Execution.prob_uniform] + exact (S.main_persistence ht v hv phaseD hm x hρ hr hold hp).trans (le_add_of_nonneg_right hB) + · change (Execution.uniform.bind (fun omega => .pure (S.secondary ht v hv phaseD hm p phaseG omega))).prob + (fun z => ¬z.Coherent (v x) ρ) ≤ _ + rw [Execution.prob_bind_pure,Execution.prob_uniform] + exact (S.secondary_persistence ht v hv phaseD hm p phaseG x hρ hr hold hp hn).trans (le_add_of_nonneg_left hA) + · change (Execution.uniform.bind (fun sign => .pure (S.increment ht hgap sign))).prob + (fun z => ¬z.Coherent (v x) ρ) ≤ _ + rw [Execution.prob_bind_pure,Execution.prob_uniform] + have hh : ∀ sign, (S.increment ht hgap sign).Coherent (v x) ρ := fun _ => hold + have he : (fun sign => ¬(S.increment ht hgap sign).Coherent (v x) ρ)=(fun _ => False) := + funext (fun sign => propext (iff_false_intro (not_not.mpr (hh sign)))) + rw [he,FiniteRandom.prob_false] + exact add_nonneg hA hB + +include hv hρ hr hold in +lemma step_persistence : (S.step ht hgap v hv hm).prob (fun z => ¬z.Coherent (v x) ρ) ≤ persistenceLoss ρ m := by + apply VertexBands.conditional_persistence m hm (v x).height hρ + (add_nonneg (mainLoss_nonneg hρ m) (secondaryLoss_nonneg hρ m)) + intro c hc + exact S.modes_persistence ht hgap v hv (phase D c.2.1) hm (shift m a₂ c.1.2) (phase g c.2.2) x hρ hr hold hc.1 hc.2 +end PlanarL1.Columns.Model.CoupledState + +end + + + +section + +namespace PlanarL1.Columns.Model +open MeasureTheory Parameters +variable {k : ℕ} {M : Model (k+1)} {Ω Ξ V : Type*} +variable [MeasurableSpace Ω] [MeasurableSpace Ξ] {μ : Measure Ω} {ν : Measure Ξ} +variable {A : Ambient M} {q : ℝ} (hq : 0 < q) +namespace SetSystem +lemma dilate_separation (S : SetSystem M Ω μ) (i j : Fin (k+1)) (H T : ℝ) : + (S.dilate hq).separation i (q*H) j (q*T)=q*S.separation i H j T := by + simp only [separation,dilate,Activity.dilate_indicator,integral_smul_measure, + smul_eq_mul,ENNReal.toReal_ofReal hq.le,mul_div_cancel_left₀ _ hq.ne'] +end SetSystem +namespace PairGeometry +variable {SA : OrdinaryState M kappaA Ω μ} {v : V → M.Point Set.univ A.root} +variable {x y : V} {b : ℝ} +lemma Certificate.dilate (h : Certificate A SA v (x := x) (y := y) b) : + Certificate (A.dilate hq) (SA.dilate hq) (fun x => A.scaleEquiv hq (v x)) + (x := x) (y := y) (q*b) := by + obtain ⟨a,c,H,E,hH,hac,hsep,hE,hm,hx,hy,hn⟩ := h + refine ⟨a,c,q*H,E,⟨H,hH,rfl⟩,hac,hsep,hE,?_,?_,?_,?_⟩ + · simpa only [Measure.real,Measure.smul_apply,smul_eq_mul,ENNReal.toReal_mul, + ENNReal.toReal_ofReal hq.le] using mul_le_mul_of_nonneg_left hm hq.le + · intro w hw + change (SA.sets.activity w).active (v x).column (q*(v x).height/q) + simpa only [mul_div_cancel_left₀ _ hq.ne'] using hx w hw + · intro w hw + change (SA.sets.activity w).active (v y).column (q*(v y).height/q) + simpa only [mul_div_cancel_left₀ _ hq.ne'] using hy w hw + · intro w hw + change ¬(SA.sets.activity w).active a (q*H/q) + simpa only [mul_div_cancel_left₀ _ hq.ne'] using hn w hw +end PairGeometry +namespace CoupledState +variable {t : ℝ} (S : CoupledState A Ω Ξ μ ν t) (v : V → M.Point Set.univ A.root) +lemma Successful.dilate {x y : V} {b : ℝ} (h : S.Successful v b x y) : + (S.dilate hq).Successful (fun x => A.scaleEquiv hq (v x)) (q*b) x y := by + rcases h with h|h|h + · apply Or.inl + change q*b ≤ (S.left.sets.dilate hq).separation _ (q*_) _ (q*_) + rw [SetSystem.dilate_separation] + exact mul_le_mul_of_nonneg_left h hq.le + · apply Or.inr ∘ Or.inl + change q*b ≤ (S.right.sets.dilate hq).separation _ (q*_) _ (q*_) + rw [SetSystem.dilate_separation] + exact mul_le_mul_of_nonneg_left h hq.le + · exact Or.inr (Or.inr (h.dilate hq)) +lemma coherent_dilate (x : M.Point Set.univ A.root) (ρ : ℝ) : + (S.dilate hq).Coherent (A.scaleEquiv hq x) (q*ρ) ↔ S.Coherent x ρ := by + constructor + · intro h z hz + have hh := h (A.scaleEquiv hq z) (by rw [A.scaleEquiv_dist]; exact mul_le_mul_of_nonneg_left hz hq.le) + change S.left.name z.column (q*z.height/q)=S.left.name x.column (q*x.height/q) ∧ + S.right.name z.column (q*z.height/q)=S.right.name x.column (q*x.height/q) at hh + simpa only [mul_div_cancel_left₀ _ hq.ne'] using hh + · intro h z hz + obtain ⟨z,rfl⟩ := (A.scaleEquiv hq).surjective z + rw [A.scaleEquiv_dist] at hz + have hh := h z (by nlinarith only [hz,hq]) + change S.left.name z.column (q*z.height/q)=S.left.name x.column (q*x.height/q) ∧ + S.right.name z.column (q*z.height/q)=S.right.name x.column (q*x.height/q) + simpa only [mul_div_cancel_left₀ _ hq.ne'] using hh +end CoupledState +end PlanarL1.Columns.Model + +end + +end OAI diff --git a/lean/OAI/Combinatorics/PlanarL1/PlanarMetric.lean b/lean/OAI/Combinatorics/PlanarL1/PlanarMetric.lean new file mode 100644 index 0000000000000000000000000000000000000000..b61b6d8d340f68df3237c1d34680d9265d1f5f5c --- /dev/null +++ b/lean/OAI/Combinatorics/PlanarL1/PlanarMetric.lean @@ -0,0 +1,372 @@ +import OAI.Combinatorics.PlanarL1.Layout + +namespace OAI + +section + + + +namespace PlanarL1.Topology.Drawing.Split +open Set +variable {V : Type} [LinearOrder V] {G : SimpleGraph V} (D : Drawing G) + (S : Set (ForwardDart G)) + +noncomputable def param (p : Piece S) (t : unitInterval) : unitInterval := + Icc.convexComb (first S p) (last S p) t + +lemma param_injective (p : Piece S) : Function.Injective (param S p) := by + intro a b he + apply Subtype.ext + have hh := congrArg Subtype.val he + change (1-(a:ℝ))*(first S p:ℝ)+(a:ℝ)*(last S p:ℝ)= + (1-(b:ℝ))*(first S p:ℝ)+(b:ℝ)*(last S p:ℝ) at hh + have hp := first_lt_last S p + nlinarith + +lemma param_interior (p : Piece S) (t : unitInterval) (ht : 0<(t:ℝ)) (ht' : (t:ℝ)<1) : + (first S p:ℝ)<(param S p t:ℝ) ∧ (param S p t:ℝ)<(last S p:ℝ) := by + have hp := first_lt_last S p + change (first S p:ℝ)<(1-(t:ℝ))*(first S p:ℝ)+(t:ℝ)*(last S p:ℝ) ∧ + (1-(t:ℝ))*(first S p:ℝ)+(t:ℝ)*(last S p:ℝ)<(last S p:ℝ) + constructor <;> nlinarith + +noncomputable def piecePath (p : Piece S) : Path (point D S (src S p)) (point D S (dst S p)) := + ((D.edge (label S p).val.fst (label S p).val.snd (label S p).val.adj).subpath + (first S p) (last S p)).cast (src_point D S p) (dst_point D S p) + +lemma piecePath_apply (p : Piece S) (t : unitInterval) : + piecePath D S p t=D.edge (label S p).val.fst (label S p).val.snd (label S p).val.adj (param S p t) := rfl + +lemma piecePath_injective (p : Piece S) : Function.Injective (piecePath D S p) := + (D.edge_injective _ _ _).comp (param_injective S p) + +abbrev Directed := Piece S × Bool + +def start (d : Directed S) : Node S := if d.2 then dst S d.1 else src S d.1 + +def finish (d : Directed S) : Node S := if d.2 then src S d.1 else dst S d.1 + +def flip (d : Directed S) : Directed S := (d.1,!d.2) + +lemma start_flip (d : Directed S) : start S (flip S d)=finish S d := by + rcases d with ⟨p,(_|_)⟩ <;> rfl + +lemma finish_flip (d : Directed S) : finish S (flip S d)=start S d := by + rcases d with ⟨p,(_|_)⟩ <;> rfl + +lemma start_ne_finish (D : Drawing G) (d : Directed S) : start S d≠finish S d := by + rcases d with ⟨p,(_|_)⟩ + · exact src_ne_dst S D p + · exact (src_ne_dst S D p).symm + +noncomputable def arc (d : Directed S) : Path (point D S (start S d)) (point D S (finish S d)) := + if h : d.2=true then (piecePath D S d.1).symm.cast (by simp [start,h]) (by simp [finish,h]) + else (piecePath D S d.1).cast (by simp [start,h]) (by simp [finish,h]) + +lemma arc_injective (d : Directed S) : Function.Injective (arc D S d) := by + rcases d with ⟨p,(_|_)⟩ + · simpa only [arc,Bool.false_eq_true,↓reduceDIte,Path.cast_coe] using piecePath_injective D S p + · intro s t he + have hh : piecePath D S p (unitInterval.symm s)=piecePath D S p (unitInterval.symm t) := he + apply Subtype.ext + have hh' := congrArg Subtype.val (piecePath_injective D S p hh) + change 1-(s:ℝ)=1-(t:ℝ) at hh' + linarith + +lemma arc_location (d : Directed S) (t : unitInterval) (ht : 0<(t:ℝ)) (ht' : (t:ℝ)<1) : + ∃ r : unitInterval, (first S d.1:ℝ)<(r:ℝ) ∧ (r:ℝ)<(last S d.1:ℝ) ∧ + arc D S d t=D.edge (label S d.1).val.fst (label S d.1).val.snd (label S d.1).val.adj r := by + rcases d with ⟨p,(_|_)⟩ + · exact ⟨param S p t,(param_interior S p t ht ht').1,(param_interior S p t ht ht').2,rfl⟩ + · have hs : 0<(unitInterval.symm t:ℝ) := by change 0<1-(t:ℝ); linarith + have hs' : (unitInterval.symm t:ℝ)<1 := by change 1-(t:ℝ)<1; linarith + exact ⟨param S p (unitInterval.symm t),(param_interior S p _ hs hs').1, + (param_interior S p _ hs hs').2,rfl⟩ + +noncomputable def graph : SimpleGraph (Node S) where + Adj u v := ∃ d : Directed S, start S d=u ∧ finish S d=v + symm := ⟨by + rintro u v ⟨d,hu,hv⟩ + exact ⟨flip S d,(start_flip S d).trans hv,(finish_flip S d).trans hu⟩⟩ + loopless := ⟨by + rintro u ⟨d,hu,hv⟩ + exact start_ne_finish S D d (hu.trans hv.symm)⟩ + +lemma unsplit_adj (d : ForwardDart G) (hd : d∉S) : + (graph D S).Adj (.inl d.val.fst) (.inl d.val.snd) := + ⟨(.inl ⟨d,hd⟩,false),rfl,rfl⟩ + +lemma first_adj (d : S) : (graph D S).Adj (.inl d.val.val.fst) (.inr (d,0)) := + ⟨(.inr (d,0),false),rfl,rfl⟩ + +lemma last_adj (d : S) : (graph D S).Adj (.inl d.val.val.snd) (.inr (d,1)) := + ⟨(.inr (d,2),true),rfl,rfl⟩ + +lemma middle_adj (d : S) : (graph D S).Adj (.inr (d,0)) (.inr (d,1)) := + ⟨(.inr (d,1),false),rfl,rfl⟩ + +noncomputable def drawing : Drawing (graph D S) where + point := point D S + point_injective := point_injective D S + edge u v h := (arc D S h.choose).cast (congrArg (point D S) h.choose_spec.1.symm) + (congrArg (point D S) h.choose_spec.2.symm) + edge_injective u v h := arc_injective D S h.choose + interior_avoid := by + intro u v h t w ht ht' he + obtain ⟨r,hr,hr',heq⟩ := arc_location D S h.choose t ht ht' + exact interior_point_avoid D S h.choose.1 hr hr' w (heq.symm.trans he) + interior_disjoint := by + intro u v h x y k s t hs hs' ht ht' he + obtain ⟨r,hr,hr',heq⟩ := arc_location D S h.choose s hs hs' + obtain ⟨q,hq,hq',heq'⟩ := arc_location D S k.choose t ht ht' + have hp := interior_piece_unique D S h.choose.1 k.choose.1 hr hr' hq hq' + (heq.symm.trans (he.trans heq')) + have hu := h.choose_spec.1 + have hv := h.choose_spec.2 + have hx := k.choose_spec.1 + have hy := k.choose_spec.2 + rcases hh : h.choose with ⟨p,b⟩ + rcases hk : k.choose with ⟨p',b'⟩ + rw [hh,hk] at hp + change p=p' at hp + subst p' + rw [hh] at hu hv + rw [hk] at hx hy + cases b <;> cases b' <;> simp only [start,finish,Bool.false_eq_true,↓reduceIte] at hu hv hx hy + all_goals aesop + +end PlanarL1.Topology.Drawing.Split + + + + +namespace PlanarL1.Topology.Drawing +variable {V W : Type} {G : SimpleGraph V} {H : SimpleGraph W} + +noncomputable def pullback (D : Drawing G) (f : W → V) (hf : Function.Injective f) + (hG : ∀ u v, H.Adj u v → G.Adj (f u) (f v)) : Drawing H where + point := D.point ∘ f + point_injective := D.point_injective.comp hf + edge u v h := D.edge (f u) (f v) (hG u v h) + edge_injective u v h := D.edge_injective _ _ _ + interior_avoid u v h t w ht ht' := D.interior_avoid _ _ _ t (f w) ht ht' + interior_disjoint := by + intro u v h x y k s t hs hs' ht ht' he + exact (D.interior_disjoint _ _ _ _ _ _ s t hs hs' ht ht' he).elim + (fun h => Or.inl ⟨hf h.1,hf h.2⟩) (fun h => Or.inr ⟨hf h.1,hf h.2⟩) + +end PlanarL1.Topology.Drawing + +namespace PlanarL1.Weighted.EnlargedTree +open PlanarL1.Topology PlanarL1.Topology.Drawing +attribute [local instance] Classical.propDecidable +variable {V : Type} [Fintype V] [LinearOrder V] {G : SimpleGraph V} {l : V → V → ℝ} + (hc : G.Connected) (hs : ∀ u v, l u v=l v u) + (hl : ∀ u v, G.Adj u v → 0 d.property ht.symm⟩,1) + +lemma splitTip_injective : Function.Injective (splitTip hc hs hl o) := by + intro d e he + by_cases hd : d.val.fst by_cases hh : e.val.fst t.1.val.val) he) + · have hk := congrArg Prod.snd he + simp [splitTip,hd,hh] at hk + · have hk := congrArg Prod.snd he + simp [splitTip,hd,hh] at hk + · simp only [splitTip,dite_eq_right hd,dite_eq_right hh] at he + have hh := congrArg (fun t => t.1.val.val.symm) he + exact Subtype.ext hh + +noncomputable def splitMap : Node hc hs hl o → Split.Node (splitSet hc hs hl o) + | .inl v => .inl v + | .inr d => .inr (splitTip hc hs hl o d) + +lemma splitMap_injective : Function.Injective (splitMap hc hs hl o) := by + intro u v he + cases u with + | inl u => cases v with + | inl v => exact congrArg Sum.inl (Sum.inl.inj he) + | inr v => exact False.elim (Sum.inl_ne_inr he) + | inr u => cases v with + | inl v => exact False.elim (Sum.inr_ne_inl he) + | inr v => exact congrArg Sum.inr (splitTip_injective hc hs hl o (Sum.inr.inj he)) + +noncomputable def drawingGraph (D : Drawing G) : SimpleGraph (Node hc hs hl o) := + SimpleGraph.comap (splitMap hc hs hl o) (Split.graph D (splitSet hc hs hl o)) + +lemma original_tree_adj (D : Drawing G) {u v : V} + (h : (shortestParents hc hs hl o).graph.Adj u v) : + (drawingGraph hc hs hl o D).Adj (.inl u) (.inl v) := by + have hg := shortestParents.graph_le hc hs hl o h + by_cases huv : u d.property h.symm⟩ + +lemma tree_le_drawingGraph (D : Drawing G) : + (tree hc hs hl o).graph ≤ drawingGraph hc hs hl o D := by + suffices step : ∀ u v, (tree hc hs hl o).Step u v → (drawingGraph hc hs hl o D).Adj u v by + intro u v h + exact h.elim (step u v) (fun h => (step v u h).symm) + intro u v h + obtain ⟨hv,rfl⟩ := h + cases v with + | inl v => + apply original_tree_adj hc hs hl o D + exact Or.inr ⟨fun he => hv (congrArg Sum.inl he),rfl⟩ + | inr d => exact branch_adj hc hs hl o D d + +lemma pair_adj (D : Drawing G) (d : ExtraDart hc hs hl o) : + (drawingGraph hc hs hl o D).Adj (.inr d) (.inr (ExtraDart.reverse hc hs hl o d)) := by + change (Split.graph D (splitSet hc hs hl o)).Adj (.inr (splitTip hc hs hl o d)) + (.inr (splitTip hc hs hl o (ExtraDart.reverse hc hs hl o d))) + unfold splitTip + by_cases hd : d.val.fst d.property h.symm⟩).symm + +noncomputable def enlargedDrawing (D : Drawing G) : Drawing (drawingGraph hc hs hl o D) := + (Split.drawing D (splitSet hc hs hl o)).pullback (splitMap hc hs hl o) + (splitMap_injective hc hs hl o) (fun _ _ h => h) + +end PlanarL1.Weighted.EnlargedTree + + + + +namespace PlanarL1.Weighted.EnlargedTree +open PlanarL1.Topology +attribute [local instance] Classical.propDecidable +variable {V : Type} [Fintype V] {G : SimpleGraph V} {l : V → V → ℝ} + (hc : G.Connected) (hs : ∀ u v, l u v=l v u) + (hl : ∀ u v, G.Adj u v → 0 d.val.fst) he + exact d.val.adj.ne hh.symm + +noncomputable def matchingGraph : SimpleGraph {v : Node hc hs hl o // (tree hc hs hl o).IsLeaf v} where + Adj i j := ∃ d : ExtraDart hc hs hl o, i.val=.inr d ∧ j.val=.inr (ExtraDart.reverse hc hs hl o d) + symm := ⟨by + rintro i j ⟨d,hi,hj⟩ + refine ⟨ExtraDart.reverse hc hs hl o d,hj,?_⟩ + rw [ExtraDart.reverse_reverse]; exact hi⟩ + loopless := ⟨by + rintro i ⟨d,hi,hj⟩ + exact reverse_ne hc hs hl o d (Sum.inr.inj (hj.symm.trans hi))⟩ + +lemma matchingGraph_height (i j : {v : Node hc hs hl o // (tree hc hs hl o).IsLeaf v}) + (h : (matchingGraph hc hs hl o).Adj i j) : + (tree hc hs hl o).height i.val=(tree hc hs hl o).height j.val := by + obtain ⟨d,hi,hj⟩ := h + rw [hi,hj] + exact (ExtraDart.tipHeight_reverse hc hs hl o d).symm + +lemma matchingGraph_matching (i j k : {v : Node hc hs hl o // (tree hc hs hl o).IsLeaf v}) + (h : (matchingGraph hc hs hl o).Adj i j) (h' : (matchingGraph hc hs hl o).Adj i k) : j=k := by + obtain ⟨d,hi,hj⟩ := h + obtain ⟨e,hi',hk⟩ := h' + have he : d=e := Sum.inr.inj (hi.symm.trans hi') + subst e + exact Subtype.ext (hj.trans hk.symm) + +lemma layout_of_planar [LinearOrder V] (hp : IsPlanar G) + (hroot : ¬(tree hc hs hl o).IsLeaf (tree hc hs hl o).root) : + ∃ n : ℕ, ∃ L : (tree hc hs hl o).Layout n, ExactPairs L := by + classical + let : LinearOrder (Node hc hs hl o) := LinearOrder.lift' (Fintype.equivFin _) (Fintype.equivFin _).injective + obtain ⟨D⟩ := drawing_of_planar hp + obtain ⟨P,_⟩ := (enlargedDrawing hc hs hl o D).polygonal + obtain ⟨L,hL⟩ := (tree hc hs hl o).layout_of_drawing P (tree_le_drawingGraph hc hs hl o D) + hroot (matchingGraph hc hs hl o) (by + rintro i j ⟨d,hi,hj⟩ + rw [hi,hj] + exact pair_adj hc hs hl o D d) + (matchingGraph_height hc hs hl o) (matchingGraph_matching hc hs hl o) + exact ⟨_,L,hL⟩ + +end PlanarL1.Weighted.EnlargedTree + +namespace PlanarL1.HeightTree +variable {V : Type} [Fintype V] (T : HeightTree V) (hroot : T.IsLeaf T.root) + +noncomputable def rootLeafLayout : T.Layout 1 where + leaf := fun _ => T.root + isLeaf := fun _ => hroot + injective := fun _ _ _ => Subsingleton.elim _ _ + covers := fun v _ => ⟨0,hroot.ancestor_eq (T.root_ancestor v)⟩ + prefix_connected := by + intro a i j hi hj + have he : i=j := Subsingleton.elim _ _ + subst j + exact .rfl + pair := ⊥ + noncrossing := fun _ _ _ _ _ _ _ h => h.1 + paired_height := fun _ _ h => h.elim + matching := fun _ _ _ h => h.elim + +end PlanarL1.HeightTree + +namespace PlanarL1.Weighted.EnlargedTree +open PlanarL1.Topology +variable {V : Type} [Fintype V] {G : SimpleGraph V} {l : V → V → ℝ} + (hc : G.Connected) (hs : ∀ u v, l u v=l v u) + (hl : ∀ u v, G.Adj u v → 0 exact ⟨0,⟨SegmentChain.nil _⟩⟩ + | @tail y z h hyz ih => + obtain ⟨n,⟨P⟩⟩ := ih + exact ⟨n+1,⟨P.append hyz⟩⟩ + +/-- A collinear broken segment covers the direct segment. -/ +lemma collinear_segment_union {a b c : E} (h : Collinear ℝ ({a,b,c} : Set E)) : + segment ℝ a c ⊆ segment ℝ a b ∪ segment ℝ b c := by + by_cases hac : a=c + · subst c + simp only [segment_same,singleton_subset_iff,mem_union] + exact Or.inl (left_mem_segment ℝ a b) + have hb : b ∈ line[ℝ,a,c] := h.mem_affineSpan_of_mem_of_ne + (by simp) (by simp) (by simp) hac + obtain ⟨t,ht⟩ := mem_affineSpan_pair_iff_exists_lineMap_eq.mp hb + apply (openSegment_subset_iff_segment_subset (𝕜 := ℝ) + (s := segment ℝ a b ∪ segment ℝ b c) + (Or.inl (left_mem_segment ℝ a b)) (Or.inr (right_mem_segment ℝ b c))).mp + intro z hz + rcases openSegment_subset_union a c (⟨t,ht⟩ : b ∈ Set.range (AffineMap.lineMap a c : ℝ → E)) hz with + hzb | hzb | hzb + · exact Or.inl (hzb ▸ right_mem_segment ℝ a b) + · exact Or.inl (openSegment_subset_segment ℝ a b hzb) + · exact Or.inr (openSegment_subset_segment ℝ b c hzb) + +/-- Adjacent non-collinear segments have no intersection except their common +endpoint. This elementary fact supplies loop erasure without a Jordan theorem. -/ +lemma collinear_of_adjacent_overlap {a b c z : E} + (hz : z ∈ segment ℝ a b) (hz' : z ∈ segment ℝ b c) (hne : z≠b) : + Collinear ℝ ({a,b,c} : Set E) := by + have h₁ := (mem_segment_iff_wbtw.mp hz).collinear + have h₂ := (mem_segment_iff_wbtw.mp hz').collinear + have h₂' : Collinear ℝ ({c,b,z} : Set E) := by + have hs : ({c,b,z} : Set E) = {b,z,c} := by + ext w + simp only [mem_insert_iff,mem_singleton_iff] + tauto + rw [hs] + exact h₂ + have hh := (h₁.collinear_insert_iff_of_ne (p₁:=c) (p₂:=b) (p₃:=z) + (by simp) (by simp) hne.symm).mpr h₂' + exact Collinear.subset (by + intro w hw + simp only [mem_insert_iff,mem_singleton_iff] at hw ⊢ + tauto) hh + +namespace SegmentChain +variable {S : Set E} {x y : E} {n : ℕ} (P : SegmentChain S x y n) + +def IsMinimal (_P : SegmentChain S x y n) : Prop := + ∀ m, Nonempty (SegmentChain S x y m) → n ≤ m + +def IsSimple : Prop := + Set.InjOn P.vertex (Set.Iic n) ∧ + ∀ i j, i ?_⟩ + by_cases heq : j=i+1 + · subst j + exact ⟨rfl,P.minimal_adjacent h hjn hzi hzj⟩ + · exact False.elim (Set.disjoint_left.mp (P.minimal_nonadjacent h (by omega) hjn) hzi hzj) +end SegmentChain + +/-- Every finite polygonal connection contains a simple finite polygonal +connection with the same endpoints and no larger trace. -/ +lemma PolygonallyJoined.exists_simple_segmentChain {S : Set E} {x y : E} + (h : PolygonallyJoined S x y) : + ∃ n, ∃ P : SegmentChain S x y n, P.IsSimple := by + classical + let hh := h.exists_segmentChain + let n := Nat.find hh + let P := Classical.choice (Nat.find_spec hh) + exact ⟨n,P,P.minimal_simple (fun m hm => Nat.find_min' hh hm)⟩ + +end PlanarL1.Topology + +namespace PlanarL1.Topology +open Set Metric + +variable {E : Type*} [NormedAddCommGroup E] [NormedSpace ℝ E] + +lemma PolygonallyJoined.mono {S T : Set E} {x y : E} + (h : PolygonallyJoined S x y) (hST : S ⊆ T) : PolygonallyJoined T x y := by + induction h with + | refl => exact Relation.ReflTransGen.refl + | tail h hab ih => exact ih.tail (hab.trans hST) + +namespace SegmentChain +variable {S : Set E} {x y : E} {n : ℕ} (P : SegmentChain S x y n) + +/-- The finite geometric trace, including the degenerate chain's endpoint. -/ +def trace : Set E := {x} ∪ ⋃ i : Fin n, segment ℝ (P.vertex i) (P.vertex (i+1)) + +lemma trace_subset (hx : x ∈ S) : P.trace ⊆ S := by + rintro z (rfl | hz) + · exact hx + · obtain ⟨i,hi⟩ := mem_iUnion.mp hz + exact P.segment_mem i i.isLt hi + +lemma vertex_mem_trace (i : ℕ) (hi : i ≤ n) : P.vertex i ∈ P.trace := by + by_cases h0 : i=0 + · simp [h0,P.start,trace] + · have hi' : i-1 simp only [Bool.false_eq_true,ite_false,ite_true] + · exact ⟨(T d).first_pos,by linarith [(T d).first_lt]⟩ + · exact ⟨by linarith [(T d).last_gt],(T d).last_lt_one⟩ + exact hde (ForwardDart.eq_of_endpoints d e (D.interior_disjoint _ _ _ _ _ _ _ _ + (h d b).1 (h d b).2 (h e c).1 (h e c).2 he)) + +lemma heads_intersect (hr : 0 hne h.symm)) + have ht := dist_triangle (D.point (portVertex d b)) z (D.point (portVertex e c)) + have h₁ := D.head_dist T hr hz + have h₂ := D.head_dist T hr hz' + rw [dist_comm z (D.point (portVertex d b))] at h₁ + linarith + have hw : dist (D.port T e c) (D.point (portVertex d b))=r := + heq ▸ D.port_sphere T e c + have he : z=D.point (portVertex d b) := radial_heads_intersect hr + (D.port_sphere T d b) hw (D.ports_distinct T hde b c) hz (by simpa [head,heq] using hz') + exact ⟨he,he.trans (congrArg D.point heq)⟩ + +lemma vertex_mem_head (hr : 0 Or.inr (Or.inl hz)) + have h₂ : PolygonallyJoined (D.edgeRegion T U d) (D.port T d true) (D.point d.val.snd) := + Relation.ReflTransGen.single (fun _ hz => Or.inr (Or.inr (by + simpa [head,portVertex,segment_symm] using hz))) + exact (h₁.trans (h.mono Set.subset_union_left)).trans h₂ + +lemma region_vertex (hr : 0 Disjoint (U d) (U e))) + {d e : ForwardDart G} (hde : d≠e) {z : ℂ} + (hz : z ∈ D.edgeRegion T U d) (hz' : z ∈ D.edgeRegion T U e) : + (z=D.point d.val.fst ∨ z=D.point d.val.snd) ∧ + (z=D.point e.val.fst ∨ z=D.point e.val.snd) := by + have leftHead (b : Bool) (hb : z ∈ D.head T d b) : z ∉ U e := by + intro hu + exact Set.disjoint_left.mp (hU e) hu (D.head_mem_obstacle T hde b hb) + have rightHead (b : Bool) (hb : z ∈ D.head T e b) : z ∉ U d := by + intro hu + exact Set.disjoint_left.mp (hU d) hu (D.head_mem_obstacle T hde.symm b hb) + rcases hz with hz | hz | hz <;> rcases hz' with hz' | hz' | hz' + · exact False.elim (Set.disjoint_left.mp (hUU hde) hz hz') + · exact False.elim (rightHead false hz' hz) + · exact False.elim (rightHead true hz' hz) + · exact False.elim (leftHead false hz hz') + · have he := D.heads_intersect T hr hsep hde hz hz' + exact ⟨Or.inl he.1,Or.inl he.2⟩ + · have he := D.heads_intersect T hr hsep hde hz hz' + exact ⟨Or.inl he.1,Or.inr he.2⟩ + · exact False.elim (leftHead true hz hz') + · have he := D.heads_intersect T hr hsep hde hz hz' + exact ⟨Or.inr he.1,Or.inl he.2⟩ + · have he := D.heads_intersect T hr hsep hde hz hz' + exact ⟨Or.inr he.1,Or.inr he.2⟩ + +end Drawing +end PlanarL1.Topology + +namespace PlanarL1.Topology +open Set + +namespace SegmentChain +variable {E : Type*} [NormedAddCommGroup E] [NormedSpace ℝ E] +variable {S T : Set E} {x y : E} {n : ℕ} (P : SegmentChain S x y n) + +def mapSet (h : S ⊆ T) : SegmentChain T x y n where + vertex := P.vertex + start := P.start + finish := P.finish + segment_mem i hi := (P.segment_mem i hi).trans h + +lemma mapSet_simple (h : S ⊆ T) (hP : P.IsSimple) : (P.mapSet h).IsSimple := hP +lemma mapSet_trace (h : S ⊆ T) : (P.mapSet h).trace=P.trace := rfl + +end SegmentChain + +/-- A literal finite polyline drawing. Simplicity is a proved property of the +finite segment chains, not an added planarity promise. -/ +structure PLDrawing {V : Type} [LinearOrder V] (G : SimpleGraph V) where + point : V → ℂ + point_injective : Function.Injective point + count : ForwardDart G → ℕ + chain : ∀ d : ForwardDart G, SegmentChain Set.univ (point d.val.fst) (point d.val.snd) (count d) + simple : ∀ d, (chain d).IsSimple + on_vertex : ∀ d w, point w ∈ (chain d).trace → w=d.val.fst ∨ w=d.val.snd + intersect : ∀ d e, d≠e → ∀ z, z ∈ (chain d).trace → z ∈ (chain e).trace → + (z=point d.val.fst ∨ z=point d.val.snd) ∧ (z=point e.val.fst ∨ z=point e.val.snd) + +/-- Simultaneous polygonalization of a finite topological graph drawing. +The original positions of all vertices are retained. -/ +lemma Drawing.polygonal {V : Type} [Fintype V] [LinearOrder V] {G : SimpleGraph V} + (D : Drawing G) : ∃ P : PLDrawing G, P.point=D.point := by + classical + obtain ⟨r,hr,hsep⟩ := D.uniform_vertex_disks + let T (d : ForwardDart G) : D.EdgeTrim r d.val := + Classical.choice (D.edgeTrim_nonempty hr hsep d.val) + obtain ⟨U,hU,hUU⟩ := D.polygonal_middles T hr hsep + have hj (d : ForwardDart G) := D.region_joined T d (hU d).2.2 + choose n P hP using fun d => (hj d).exists_simple_segmentChain + have hstart (d : ForwardDart G) : D.point d.val.fst ∈ D.edgeRegion T U d := + Or.inr (Or.inl (left_mem_segment ℝ _ _)) + refine ⟨⟨D.point,D.point_injective,n,fun d => (P d).mapSet (Set.subset_univ _), + fun d => (P d).mapSet_simple _ (hP d),?_,?_⟩,rfl⟩ + · intro d w hw + apply D.region_vertex T hr hsep (fun d => (hU d).2.1) + exact (P d).trace_subset (hstart d) hw + · intro d e hde z hz hz' + exact D.regions_intersect T hr hsep (fun d => (hU d).2.1) hUU hde + ((P d).trace_subset (hstart d) hz) ((P e).trace_subset (hstart e) hz') + +lemma polygonal_of_planar {V : Type} [Fintype V] [LinearOrder V] {G : SimpleGraph V} + (h : IsPlanar G) : Nonempty (PLDrawing G) := by + obtain ⟨D⟩ := drawing_of_planar h + obtain ⟨P,_⟩ := D.polygonal + exact ⟨P⟩ + +end PlanarL1.Topology + + +namespace PlanarL1.Topology +open Set Metric Filter + +variable {E : Type*} [NormedAddCommGroup E] [NormedSpace ℝ E] + +/-- Boundary points of a convex neighbourhood have a unique positive radial +coordinate. This will keep the extended leaf ports disjoint when shrinking +an embedded finite tree inside a convex merging region. -/ +lemma convex_frontier_radial_injective {S : Set E} (hS : Convex ℝ S) + (h0 : S ∈ nhds (0:E)) {p q : E} (hp : p ∈ frontier S) (hq : q ∈ frontier S) + {s t : ℝ} (hs : 0 c•x) '' closure S) : z=c•p := by + rw [segment_eq_image' ℝ (c•p) p] at hz + obtain ⟨t,ht,rfl⟩ := hz + obtain ⟨w,hw,he⟩ := hcore + have hform : c•p+t•(p-c•p)=(c+t*(1-c))•p := by module + dsimp only at he ⊢ + rw [hform] at he ⊢ + have hg := congrArg (gauge S) he + have hp' := (gauge_eq_one_iff_mem_frontier hS h0).mpr hp + have hcoef : 0≤c+t*(1-c) := add_nonneg hc.le (mul_nonneg ht.1 (sub_nonneg.mpr hc1)) + rw [gauge_smul_of_nonneg hc.le,gauge_smul_of_nonneg hcoef,hp',smul_eq_mul,smul_eq_mul,mul_one] at hg + have hw' : gauge S w≤1 := (gauge_le_one_iff_mem_closure hS h0).mpr hw + have hle : c+t*(1-c)≤c := by nlinarith + have hge : c≤c+t*(1-c) := by nlinarith [mul_nonneg ht.1 (sub_nonneg.mpr hc1)] + rw [le_antisymm hle hge] + +end PlanarL1.Topology + +namespace PlanarL1.Topology +open Set Metric Filter + +/-- A straight selected tree piece has an arbitrarily thin bounded convex +merging region avoiding every closed nonincident obstacle. -/ +lemma convex_tube_avoiding {a b : ℂ} {F : Set ℂ} (hF : IsClosed F) + (hdisj : Disjoint (segment ℝ a b) F) : + ∃ S : Set ℂ, Convex ℝ S ∧ IsOpen S ∧ Bornology.IsBounded S ∧ + segment ℝ a b ⊆ S ∧ Disjoint (closure S) F := by + obtain ⟨r,hr,hsub⟩ := (compact_segment_complex a b).exists_cthickening_subset_open + hF.isOpen_compl hdisj.subset_compl_right + refine ⟨thickening r (segment ℝ a b),(convex_segment a b).thickening r, + isOpen_thickening,?_,self_subset_thickening hr _,?_⟩ + · exact (compact_segment_complex a b).isBounded.thickening + · exact Set.disjoint_left.mpr (fun z hz hzF => + hsub (closure_thickening_subset_cthickening r _ hz) hzF) + +end PlanarL1.Topology + + +namespace PlanarL1.Topology +open Set Metric Filter + +variable {E : Type*} [NormedAddCommGroup E] [NormedSpace ℝ E] + +lemma image_segment_smul (c : ℝ) (x y : E) : + (fun z : E => c•z) '' segment ℝ x y=segment ℝ (c•x) (c•y) := by + simp only [segment_eq_image' ℝ,Set.image_image] + congr 1 + funext t + module + +lemma PolygonallyJoined.smul {S : Set E} {x y : E} + (h : PolygonallyJoined S x y) (c : ℝ) : + PolygonallyJoined ((fun z : E => c•z) '' S) (c•x) (c•y) := by + induction h with + | refl => exact Relation.ReflTransGen.refl + | tail h hab ih => + refine ih.tail ?_ + rw [← image_segment_smul] + exact Set.image_mono hab + +lemma SegmentChain.joined_trace {S : Set E} {x y : E} {n : ℕ} (P : SegmentChain S x y n) : + PolygonallyJoined P.trace x y := by + have h : ∀ i, i≤n → PolygonallyJoined P.trace x (P.vertex i) := by + intro i + induction i with + | zero => intro _; rw [P.start]; exact Relation.ReflTransGen.refl + | succ i ih => + intro hi + refine (ih (by omega)).tail ?_ + intro z hz + exact Or.inr (Set.mem_iUnion.mpr ⟨⟨i,by omega⟩,hz⟩) + simpa only [P.finish] using h n le_rfl + +namespace PLDrawing +variable {V : Type} [LinearOrder V] {G : SimpleGraph V} (P : PLDrawing G) + +def Incident (d : ForwardDart G) (v : V) : Prop := v=d.val.fst ∨ v=d.val.snd + +lemma leaf_incident_unique {B : Set V} + (hleaf : ∀ v ∈ B, ∀ a b, G.Adj v a → G.Adj v b → a=b) + {v : V} (hv : v∈B) {d e : ForwardDart G} + (hd : Incident d v) (he : Incident e v) : d=e := by + rcases hd with hd | hd <;> rcases he with he | he + · have hv' : d.val.fst=e.val.fst := hd.symm.trans he + apply ForwardDart.eq_of_endpoints + exact Or.inl ⟨hv',hleaf v hv _ _ (hd.symm ▸ d.val.adj) (he.symm ▸ e.val.adj)⟩ + · have hv' : d.val.fst=e.val.snd := hd.symm.trans he + apply ForwardDart.eq_of_endpoints + exact Or.inr ⟨hv',hleaf v hv _ _ (hd.symm ▸ d.val.adj) (he.symm ▸ e.val.adj.symm)⟩ + · have hv' : d.val.snd=e.val.fst := hd.symm.trans he + apply ForwardDart.eq_of_endpoints + exact Or.inr ⟨hleaf v hv _ _ (hd.symm ▸ d.val.adj.symm) (he.symm ▸ e.val.adj),hv'⟩ + · have hv' : d.val.snd=e.val.snd := hd.symm.trans he + apply ForwardDart.eq_of_endpoints + exact Or.inl ⟨hleaf v hv _ _ (hd.symm ▸ d.val.adj.symm) (he.symm ▸ e.val.adj.symm),hv'⟩ + +noncomputable def expandedPoint (B : Set V) (c : ℝ) (v : V) : ℂ := + by classical exact if v∈B then P.point v else c•P.point v + +def portTail (c : ℝ) (v : V) : Set ℂ := segment ℝ (c•P.point v) (P.point v) + +def expandedRegion (B : Set V) (c : ℝ) (d : ForwardDart G) : Set ℂ := + (fun z : ℂ => c•z) '' (P.chain d).trace ∪ + ⋃ v : {v : V // v∈B ∧ Incident d v}, P.portTail c v.val + +variable {S : Set ℂ} (hS : Convex ℝ S) (h0 : S ∈ nhds (0:ℂ)) + (hpoint : ∀ v, P.point v ∈ closure S) + {B : Set V} (hport : ∀ v ∈ B, P.point v ∈ frontier S) + {c : ℝ} (hc : 0 c•z) '' closure S := by + rintro ⟨z,hz,he⟩ + have hg := congrArg (gauge S) he + rw [gauge_smul_of_nonneg hc.le, + (gauge_eq_one_iff_mem_frontier hS h0).mpr (hport v hv)] at hg + have hz' := (gauge_le_one_iff_mem_closure hS h0).mpr hz + change c*gauge S z=1 at hg + nlinarith + +include hpoint + +lemma expandedPoint_injective : Function.Injective (P.expandedPoint B c) := by + classical + intro v w he + by_cases hv : v∈B <;> by_cases hw : w∈B + · exact P.point_injective (by simpa [expandedPoint,hv,hw] using he) + · exfalso + apply P.port_not_core hS h0 hport hc hc1 hv + exact ⟨P.point w,hpoint w,by simpa [expandedPoint,hv,hw] using he.symm⟩ + · exfalso + apply P.port_not_core hS h0 hport hc hc1 hw + exact ⟨P.point v,hpoint v,by simpa [expandedPoint,hv,hw] using he⟩ + · apply P.point_injective + exact smul_right_injective ℂ hc.ne' (by simpa [expandedPoint,hv,hw] using he) + +lemma newpoint_in_tail {v w : V} (hw : w∈B) + (hv : P.expandedPoint B c v ∈ P.portTail c w) : v=w := by + classical + by_cases hvB : v∈B + · by_contra hne + have hd := convex_frontier_tails_disjoint hS h0 (hport v hvB) (hport w hw) + (fun h => hne (P.point_injective h)) hc hc1.le + exact Set.disjoint_left.mp hd (right_mem_segment ℝ _ _) + (by simpa [expandedPoint,hvB,portTail] using hv) + · apply P.point_injective + apply smul_right_injective ℂ hc.ne' + exact convex_frontier_tail_core hS h0 (hport w hw) hc hc1.le + (by simpa [expandedPoint,hvB,portTail] using hv) ⟨P.point v,hpoint v,rfl⟩ + +omit hpoint in +lemma newpoint_in_core {d : ForwardDart G} {v : V} + (hv : P.expandedPoint B c v ∈ (fun z : ℂ => c•z) '' (P.chain d).trace) + (htrace : (P.chain d).trace ⊆ closure S) : ¬v∈B ∧ Incident d v := by + classical + have hvB : ¬v∈B := by + intro h + apply P.port_not_core hS h0 hport hc hc1 h + simpa [expandedPoint,h] using Set.image_mono htrace hv + refine ⟨hvB,?_⟩ + obtain ⟨z,hz,he⟩ := hv + have he' : z=P.point v := smul_right_injective ℂ hc.ne' + (by simpa [expandedPoint,hvB] using he) + exact P.on_vertex d v (he' ▸ hz) + +lemma expandedRegion_vertex {d : ForwardDart G} {v : V} + (htrace : (P.chain d).trace ⊆ closure S) + (hv : P.expandedPoint B c v ∈ P.expandedRegion B c d) : Incident d v := by + rcases hv with hv | hv + · exact (P.newpoint_in_core hS h0 hport hc hc1 hv htrace).2 + · obtain ⟨w,hw⟩ := Set.mem_iUnion.mp hv + have he := P.newpoint_in_tail hS h0 hpoint hport hc hc1 w.property.1 hw + exact he ▸ w.property.2 + + +variable (htrace : ∀ d, (P.chain d).trace ⊆ closure S) + (hleaf : ∀ v ∈ B, ∀ a b, G.Adj v a → G.Adj v b → a=b) +include htrace hleaf + +omit hpoint in +lemma different_core_tail {d e : ForwardDart G} (hde : d≠e) + {v : V} (hv : v∈B) (he : Incident e v) : + Disjoint ((fun z : ℂ => c•z) '' (P.chain d).trace) (P.portTail c v) := by + apply Set.disjoint_left.mpr + intro z hz hz' + obtain ⟨w,hw,rfl⟩ := hz + have heq := convex_frontier_tail_core hS h0 (hport v hv) hc hc1.le hz' + ⟨w,htrace d hw,rfl⟩ + have hwv : w=P.point v := smul_right_injective ℂ hc.ne' heq + have hd : Incident d v := P.on_vertex d v (hwv ▸ hw) + exact hde (leaf_incident_unique hleaf hv hd he) + +omit hpoint htrace in +lemma different_tails {d e : ForwardDart G} (hde : d≠e) + {v w : V} (hv : v∈B) (hw : w∈B) (hd : Incident d v) (he : Incident e w) : + Disjoint (P.portTail c v) (P.portTail c w) := by + apply convex_frontier_tails_disjoint hS h0 (hport v hv) (hport w hw) _ hc hc1.le + intro h + have hvw := P.point_injective h + exact hde (leaf_incident_unique hleaf hv hd (hvw.symm ▸ he)) + +omit hpoint in +lemma expandedRegions_intersect {d e : ForwardDart G} (hde : d≠e) + {z : ℂ} (hz : z∈P.expandedRegion B c d) (hz' : z∈P.expandedRegion B c e) : + (z=P.expandedPoint B c d.val.fst ∨ z=P.expandedPoint B c d.val.snd) ∧ + (z=P.expandedPoint B c e.val.fst ∨ z=P.expandedPoint B c e.val.snd) := by + classical + rcases hz with hz | hz <;> rcases hz' with hz' | hz' + · obtain ⟨w,hw,rfl⟩ := hz + obtain ⟨w',hw',heq⟩ := hz' + have heww : w'=w := smul_right_injective ℂ hc.ne' heq + subst w' + have hint := P.intersect d e hde w hw hw' + have hnB (v : V) (h : w=P.point v) : v∉B := by + intro hv + exact hde (leaf_incident_unique hleaf hv (P.on_vertex d v (h ▸ hw)) + (P.on_vertex e v (h ▸ hw'))) + constructor + · rcases hint.1 with hd | hd + · exact Or.inl (by simp [expandedPoint,hnB _ hd,hd]) + · exact Or.inr (by simp [expandedPoint,hnB _ hd,hd]) + · rcases hint.2 with he | he + · exact Or.inl (by simp [expandedPoint,hnB _ he,he]) + · exact Or.inr (by simp [expandedPoint,hnB _ he,he]) + · obtain ⟨v,hv⟩ := Set.mem_iUnion.mp hz' + exact False.elim (Set.disjoint_left.mp + (P.different_core_tail hS h0 hport hc hc1 htrace hleaf hde v.property.1 v.property.2) hz hv) + · obtain ⟨v,hv⟩ := Set.mem_iUnion.mp hz + exact False.elim (Set.disjoint_left.mp + (P.different_core_tail hS h0 hport hc hc1 htrace hleaf hde.symm v.property.1 v.property.2) hz' hv) + · obtain ⟨v,hv⟩ := Set.mem_iUnion.mp hz + obtain ⟨w,hw⟩ := Set.mem_iUnion.mp hz' + exact False.elim (Set.disjoint_left.mp + (P.different_tails hS h0 hport hc hc1 hleaf hde + v.property.1 w.property.1 v.property.2 w.property.2) hv hw) + +omit hS h0 hport hc hc1 hpoint htrace hleaf in +lemma expandedPoint_mem_region {B : Set V} {c : ℝ} {d : ForwardDart G} {v : V} + (hv : Incident d v) : P.expandedPoint B c v ∈ P.expandedRegion B c d := by + classical + by_cases hvB : v∈B + · exact Or.inr (Set.mem_iUnion.mpr ⟨⟨v,hvB,hv⟩,by + simpa [expandedPoint,hvB,portTail] using right_mem_segment ℝ (c•P.point v) (P.point v)⟩) + · apply Or.inl + refine ⟨P.point v,?_,by simp [expandedPoint,hvB]⟩ + rcases hv with rfl | rfl + · exact (P.chain d).start_mem_trace + · exact (P.chain d).finish_mem_trace + +omit hS h0 hport hc hc1 hpoint htrace hleaf in +lemma expandedRegion_joined (B : Set V) (c : ℝ) (d : ForwardDart G) : + PolygonallyJoined (P.expandedRegion B c d) + (P.expandedPoint B c d.val.fst) (P.expandedPoint B c d.val.snd) := by + classical + have hseg (v : V) (hv : Incident d v) : + segment ℝ (c•P.point v) (P.expandedPoint B c v) ⊆ P.expandedRegion B c d := by + by_cases hvB : v∈B + · intro z hz + exact Or.inr (Set.mem_iUnion.mpr ⟨⟨v,hvB,hv⟩, + by simpa [expandedPoint,hvB,portTail] using hz⟩) + · simp only [expandedPoint,hvB,ite_false,segment_same] + intro z hz + have he : z=c•P.point v := hz + subst z + simpa [expandedPoint,hvB] using P.expandedPoint_mem_region (B:=B) (c:=c) hv + have hfirst : PolygonallyJoined (P.expandedRegion B c d) + (P.expandedPoint B c d.val.fst) (c•P.point d.val.fst) := + Relation.ReflTransGen.single (by rw [segment_symm]; exact hseg _ (Or.inl rfl)) + have hmiddle := ((P.chain d).joined_trace.smul c).mono + (show (fun z : ℂ => c•z) '' (P.chain d).trace ⊆ P.expandedRegion B c d from fun _ h => Or.inl h) + exact (hfirst.trans hmiddle).tail (hseg _ (Or.inr rfl)) + +/-- Inside a convex merging region, shrink the complete drawn core but retain +all its distinct leaf ports. Extending each leaf radially introduces no +intersections. The result is again an actual finite polyline drawing. -/ +lemma expand_leaf_ports : ∃ Q : PLDrawing G, + Q.point=P.expandedPoint B c ∧ ∀ d, (Q.chain d).trace ⊆ P.expandedRegion B c d := by + classical + choose n R hR using fun d => (P.expandedRegion_joined B c d).exists_simple_segmentChain + have hstart (d : ForwardDart G) := P.expandedPoint_mem_region (B:=B) (c:=c) (d:=d) (Or.inl rfl) + refine ⟨⟨P.expandedPoint B c,P.expandedPoint_injective hS h0 hpoint hport hc hc1, + n,fun d => (R d).mapSet (Set.subset_univ _), + fun d => (R d).mapSet_simple _ (hR d),?_,?_⟩,rfl,?_⟩ + · intro d v hv + exact P.expandedRegion_vertex hS h0 hpoint hport hc hc1 (htrace d) + ((R d).trace_subset (hstart d) hv) + · intro d e hde z hz hz' + exact P.expandedRegions_intersect hS h0 hport hc hc1 htrace hleaf hde + ((R d).trace_subset (hstart d) hz) ((R e).trace_subset (hstart e) hz') + · intro d + exact (R d).trace_subset (hstart d) + +end PLDrawing +end PlanarL1.Topology + + + +end + +end OAI diff --git a/lean/OAI/Combinatorics/PlanarL1/Probability.lean b/lean/OAI/Combinatorics/PlanarL1/Probability.lean new file mode 100644 index 0000000000000000000000000000000000000000..c982917eed50f1b1d63e1df6e3511572942147d9 --- /dev/null +++ b/lean/OAI/Combinatorics/PlanarL1/Probability.lean @@ -0,0 +1,327 @@ +import Mathlib + +namespace OAI + +section + +namespace PlanarL1.FiniteRandom + +attribute [local instance] Classical.propDecidable + +noncomputable def event {Ω : Type*} [Fintype Ω] (P : Ω → Prop) : Finset Ω := by + classical + exact Finset.univ.filter P + +lemma mem_event {Ω : Type*} [Fintype Ω] (P : Ω → Prop) (w : Ω) : w ∈ event P ↔ P w := by + classical + simp [event] + +noncomputable def prob {Ω : Type*} [Fintype Ω] (P : Ω → Prop) : ℝ := by + classical + exact ((event P).card : ℝ) / Fintype.card Ω + +lemma prob_nonneg {Ω : Type*} [Fintype Ω] (P : Ω → Prop) : 0 ≤ prob P := by + unfold prob + positivity + +lemma prob_eq_sum {Ω : Type*} [Fintype Ω] (P : Ω → Prop) : + prob P = (∑ w, if P w then (1 : ℝ) else 0) / Fintype.card Ω := by + classical + simp [prob, event, Finset.sum_boole] + +lemma prob_mono {Ω : Type*} [Fintype Ω] {P Q : Ω → Prop} (h : ∀ w, P w → Q w) : + prob P ≤ prob Q := by + classical + apply div_le_div_of_nonneg_right _ (Nat.cast_nonneg _) + exact_mod_cast Finset.card_le_card (show event P ⊆ event Q from + fun w hw => (mem_event Q w).mpr (h w ((mem_event P w).mp hw))) + +lemma prob_equiv {Ω Λ : Type*} [Fintype Ω] [Fintype Λ] (e : Ω ≃ Λ) (P : Λ → Prop) : + prob (fun w => P (e w)) = prob P := by + classical + rw [prob_eq_sum, prob_eq_sum, Fintype.card_congr e] + exact congrArg (fun z : ℝ => z / Fintype.card Λ) + (e.sum_comp (fun z : Λ => if P z then (1 : ℝ) else 0)) + +lemma prob_prod {Ω Λ : Type*} [Fintype Ω] [Fintype Λ] (P : Ω × Λ → Prop) : + prob P = (∑ w : Ω, prob (fun z : Λ => P (w,z))) / Fintype.card Ω := by + classical + simp only [prob_eq_sum, Fintype.sum_prod_type, Fintype.card_prod, Nat.cast_mul] + rw [← Finset.sum_div] + ring + +lemma prob_prod_bound {Ω Λ : Type*} [Fintype Ω] [Nonempty Ω] [Fintype Λ] + (P : Ω × Λ → Prop) {b : ℝ} (h : ∀ w, prob (fun z : Λ => P (w,z)) ≤ b) : + prob P ≤ b := by + rw [prob_prod] + have hc : (0 : ℝ) < Fintype.card Ω := by exact_mod_cast Fintype.card_pos + apply (div_le_iff₀ hc).mpr + calc + ∑ w : Ω, prob (fun z : Λ => P (w,z)) ≤ ∑ _w : Ω, b := Finset.sum_le_sum (fun w _ => h w) + _ = b * Fintype.card Ω := by simp [mul_comm] + +lemma prob_union_bound {Ω ι : Type*} [Fintype Ω] (S : Finset ι) (P : ι → Ω → Prop) : + prob (fun w => ∃ i ∈ S, P i w) ≤ ∑ i ∈ S, prob (P i) := by + classical + unfold prob + rw [← Finset.sum_div] + apply div_le_div_of_nonneg_right _ (Nat.cast_nonneg _) + have he : event (fun w => ∃ i ∈ S, P i w) = + S.biUnion (fun i => event (P i)) := by + ext w + simp [mem_event] + rw [he] + exact_mod_cast (Finset.card_biUnion_le : + (S.biUnion (fun i => event (P i))).card ≤ + ∑ i ∈ S, (event (P i)).card) + +/-- Cardinality of a grid subset is controlled by the span of its indices. -/ +lemma grid_card_span (s : Finset ℕ) {a b : ℕ} (h : ∀ i ∈ s, a ≤ i ∧ i ≤ b) : + s.card ≤ b + 1 - a := by + have hs : s ⊆ Finset.Icc a b := fun i hi => Finset.mem_Icc.mpr (h i hi) + simpa using Finset.card_le_card hs + +/-- An interval of radius t meets at most 2t/step+1 equally spaced points. +This argument is exact and includes both endpoints of the grid. -/ +lemma grid_count (m : ℕ) {step t : ℝ} (hstep : 0 < step) (ht : 0 ≤ t) (c : ℝ) : + ((event (fun i : Fin (m + 1) => |c + step * i.val| ≤ t)).card : ℝ) * step ≤ + 2 * t + step := by + classical + let A := event (fun i : Fin (m + 1) => |c + step * i.val| ≤ t) + by_cases hA : A.Nonempty + · let a := A.min' hA + let b := A.max' hA + have ha : a ∈ A := A.min'_mem hA + have hb : b ∈ A := A.max'_mem hA + have hab : a.val ≤ b.val := A.min'_le b hb + have hsub : A.image Fin.val ⊆ Finset.Icc a.val b.val := by + rintro i hi + obtain ⟨z, hz, rfl⟩ := Finset.mem_image.mp hi + exact Finset.mem_Icc.mpr ⟨A.min'_le z hz, A.le_max' z hz⟩ + have hcard : A.card ≤ b.val + 1 - a.val := by + have hc := Finset.card_le_card hsub + simpa only [Finset.card_image_of_injective _ Fin.val_injective, Nat.card_Icc] using hc + have hcard' : (A.card : ℝ) ≤ (b.val : ℝ) - a.val + 1 := by + have he : b.val + 1 - a.val + a.val = b.val + 1 := Nat.sub_add_cancel (by omega) + have hh : (b.val + 1 - a.val : ℕ) + a.val ≤ b.val + 1 := he.le + have hi : A.card + a.val ≤ b.val + 1 := by omega + have hir : (A.card : ℝ) + a.val ≤ (b.val : ℝ) + 1 := by exact_mod_cast hi + linarith + have ham : |c + step * a.val| ≤ t := (mem_event _ a).mp ha + have hbm : |c + step * b.val| ≤ t := (mem_event _ b).mp hb + have ha' := (abs_le.mp ham).1 + have hb' := (abs_le.mp hbm).2 + have hm := mul_le_mul_of_nonneg_right hcard' hstep.le + change (A.card : ℝ) * step ≤ 2 * t + step + nlinarith + · have he : A = ∅ := Finset.not_nonempty_iff_eq_empty.mp hA + change (A.card : ℝ) * step ≤ 2 * t + step + rw [he] + simp only [Finset.card_empty, Nat.cast_zero, zero_mul] + linarith + +/-- Uniform endpoint grid estimate in the normalization used by the paper. -/ +lemma grid_probability (m : ℕ) (hm : 0 < m) {q t : ℝ} (hq : 0 < q) (ht : 0 ≤ t) (c : ℝ) : + prob (fun i : Fin (m + 1) => |c + q / m * i.val| ≤ t) ≤ (2 * t + q / m) / q := by + have hm' : (0 : ℝ) < m := by exact_mod_cast hm + have hs : 0 < q / m := div_pos hq hm' + have hcount := grid_count m hs ht c + have hc : (0 : ℝ) < (m + 1 : ℕ) := by positivity + unfold prob + rw [Fintype.card_fin] + apply (div_le_iff₀ hc).mpr + rw [div_mul_eq_mul_div] + apply (le_div_iff₀ hq).mpr + have hn : (0 : ℝ) ≤ (event (fun i : Fin (m + 1) => |c + q / m * i.val| ≤ t)).card := + Nat.cast_nonneg _ + have hh := mul_le_mul_of_nonneg_right hcount hm'.le + have hmul : q / (m : ℝ) * m = q := div_mul_cancel₀ q (ne_of_gt hm') + rw [mul_assoc, hmul] at hh + push_cast + nlinarith + +end PlanarL1.FiniteRandom + +namespace PlanarL1.FiniteRandom + +attribute [local instance] Classical.propDecidable + +/-- Independent uniform grid coordinates can be exposed one at a time by an +actual equivalence of finite sample spaces. -/ +lemma coordinate_probability {I : Type*} [Fintype I] [DecidableEq I] + (i : I) (m : ℕ) (hm : 0 < m) {q t : ℝ} (hq : 0 < q) (ht : 0 ≤ t) + (F : (I → Fin (m + 1)) → ℝ) + (hF : ∀ α : I → Fin (m + 1), ∃ c : ℝ, + (∀ r : Fin (m + 1), F (Function.update α i r) = c + q / m * r.val) ∨ + (∀ r : Fin (m + 1), F (Function.update α i r) = c - q / m * r.val)) : + prob (fun α => |F α| ≤ t) ≤ (2 * t + q / m) / q := by + classical + let e : (I → Fin (m + 1)) ≃ ({j : I // j ≠ i} → Fin (m + 1)) × Fin (m + 1) := + (Equiv.funSplitAt i (Fin (m + 1))).trans (Equiv.prodComm _ _) + have he := prob_equiv e.symm (fun α => |F α| ≤ t) + rw [← he] + apply prob_prod_bound + intro rest + let α : I → Fin (m + 1) := e.symm (rest, 0) + have hu (r : Fin (m + 1)) : e.symm (rest,r) = Function.update α i r := by + funext j + by_cases hj : j = i + · subst j + simp [e, α, Equiv.funSplitAt_symm_apply] + · simp [e, α, Equiv.funSplitAt_symm_apply, hj] + obtain ⟨c, hc⟩ := hF α + rcases hc with hc | hc + · have hp := prob_mono (fun r (hr : |F (e.symm (rest,r))| ≤ t) => + (show |c + q / m * r.val| ≤ t by simpa only [hu r, hc r] using hr)) + exact hp.trans (grid_probability m hm hq ht c) + · have hp := prob_mono (fun r (hr : |F (e.symm (rest,r))| ≤ t) => + (show |-c + q / m * r.val| ≤ t by + rw [hu r, hc r] at hr + rw [show -c + q / m * r.val = -(c - q / m * r.val) by ring, abs_neg] + exact hr)) + exact hp.trans (grid_probability m hm hq ht (-c)) + +lemma prob_false {Ω : Type*} [Fintype Ω] : prob (fun _ : Ω => False) = 0 := by + simp [prob, event] + +lemma prob_pair_bound {Ω ι : Type*} [Fintype Ω] [DecidableEq ι] + (S : Finset ι) (P : ι → ι → Ω → Prop) {b : ℝ} (hb : 0 ≤ b) + (h : ∀ i ∈ S, ∀ j ∈ S, i ≠ j → prob (P i j) ≤ b) : + prob (fun w => ∃ i ∈ S, ∃ j ∈ S, i ≠ j ∧ P i j w) ≤ (S.card : ℝ)^2 * b := by + classical + have he : (fun w => ∃ i ∈ S, ∃ j ∈ S, i ≠ j ∧ P i j w) = + (fun w => ∃ ij ∈ S ×ˢ S, ij.1 ≠ ij.2 ∧ P ij.1 ij.2 w) := by + funext w + simp only [Finset.mem_product, Prod.exists] + aesop + rw [he] + calc + prob (fun w => ∃ ij ∈ S ×ˢ S, ij.1 ≠ ij.2 ∧ P ij.1 ij.2 w) ≤ + ∑ ij ∈ S ×ˢ S, prob (fun w => ij.1 ≠ ij.2 ∧ P ij.1 ij.2 w) := prob_union_bound _ _ + _ ≤ ∑ _ij ∈ S ×ˢ S, b := by + apply Finset.sum_le_sum + intro ij hij + by_cases heq : ij.1 = ij.2 + · have hz : prob (fun w => ij.1 ≠ ij.2 ∧ P ij.1 ij.2 w) = 0 := by + simpa only [heq, ne_eq, not_true_eq_false, false_and] using (prob_false (Ω := Ω)) + rw [hz] + exact hb + · exact (prob_mono (fun _ hw => hw.2)).trans + (h ij.1 (Finset.mem_product.mp hij).1 ij.2 (Finset.mem_product.mp hij).2 heq) + _ = (S.card : ℝ)^2 * b := by simp [pow_two] + +end PlanarL1.FiniteRandom + +end + +section + +namespace PlanarL1.FiniteRandom +lemma prob_prod_bound_left {Ω Λ : Type*} [Fintype Ω] [Fintype Λ] [Nonempty Λ] + (P : Ω × Λ → Prop) {b : ℝ} (h : ∀ z, prob (fun w : Ω => P (w,z)) ≤ b) : + prob P ≤ b := by + rw [← prob_equiv (Equiv.prodComm Λ Ω) P] + exact prob_prod_bound _ h +end PlanarL1.FiniteRandom + + +end + +section + +namespace PlanarL1.FiniteRandom + +/-- Expose one independent finite coordinate, retaining every other coordinate. +This is the conditional probability step used between distinct seed groups. -/ +lemma prob_update_bound {I Ω : Type*} [Fintype I] [DecidableEq I] + [Fintype Ω] [Nonempty Ω] (i : I) (P : (I → Ω) → Prop) {b : ℝ} + (h : ∀ α, prob (fun r : Ω => P (Function.update α i r)) ≤ b) : + prob P ≤ b := by + classical + let e : (I → Ω) ≃ ({j : I // j ≠ i} → Ω) × Ω := + (Equiv.funSplitAt i Ω).trans (Equiv.prodComm _ _) + rw [← prob_equiv e.symm P] + apply prob_prod_bound + intro rest + let α : I → Ω := e.symm (rest, Classical.arbitrary Ω) + have hu (r : Ω) : e.symm (rest,r) = Function.update α i r := by + funext j + by_cases hj : j=i + · subst j; simp [e,α,Equiv.funSplitAt_symm_apply] + · simp [e,α,Equiv.funSplitAt_symm_apply,hj] + simpa only [hu] using h α + +end PlanarL1.FiniteRandom + + +end + +section + +namespace PlanarL1.FiniteRandom +attribute [local instance] Classical.propDecidable + +lemma prob_singleton {Ω : Type*} [Fintype Ω] (x : Ω) : + prob (fun ω => ω=x) = 1/(Fintype.card Ω : ℝ) := by + classical + have he : event (fun ω : Ω => ω=x)={x} := by + ext ω + simp only [mem_event,Finset.mem_singleton] + rw [prob,he] + simp + +/-- Exact probability of any finite prescribed set of independent fair coins. +Unprescribed coins are unrestricted, so their number does not affect the bound. -/ +lemma prob_prescribed {I : Type*} [Fintype I] (S : Finset I) (b : I → Bool) : + prob (fun ω : I → Bool => ∀ i ∈ S, ω i=b i) = 1/(2:ℝ)^S.card := by + classical + let e : (I → Bool) ≃ ({i : I // i ∉ S} → Bool) × ({i : I // i ∈ S} → Bool) := + (Equiv.piEquivPiSubtypeProd (fun i => i ∈ S) (fun _ => Bool)).trans (Equiv.prodComm _ _) + let f : {i : I // i ∈ S} → Bool := fun i => b i + have he (ω : ({i : I // i ∉ S} → Bool) × ({i : I // i ∈ S} → Bool)) : + (∀ i ∈ S, e.symm ω i=b i) ↔ ω.2=f := by + constructor + · intro h + funext i + simpa [e,f,Equiv.piEquivPiSubtypeProd] using h i i.property + · intro h i hi + simpa [e,f,Equiv.piEquivPiSubtypeProd,hi] using congrFun h ⟨i,hi⟩ + rw [← prob_equiv e.symm (fun ω : I → Bool => ∀ i ∈ S, ω i=b i)] + simp_rw [he] + rw [prob_prod] + simp_rw [prob_singleton] + have hc : (Fintype.card ({i : I // i ∉ S} → Bool) : ℝ) ≠ 0 := by positivity + simp only [Finset.sum_const,Finset.card_univ,nsmul_eq_mul] + rw [mul_div_cancel_left₀ _ hc] + simp + +lemma prob_two_coins {I : Type*} [Fintype I] (i j : I) (hij : i ≠ j) (a b : Bool) : + prob (fun ω : I → Bool => ω i=a ∧ ω j=b) = (1:ℝ)/4 := by + classical + have h := prob_prescribed ({i,j} : Finset I) (Function.update (fun _ => b) i a) + have hp (ω : I → Bool) : (∀ k ∈ ({i,j} : Finset I), + ω k=Function.update (fun _ => b) i a k) ↔ ω i=a ∧ ω j=b := by + simp [Function.update,Ne.symm hij] + have hc : ({i,j} : Finset I).card=2 := by simp [hij] + simpa only [hp,hc,pow_two,show (2:ℝ)*2=4 by norm_num] using h + +/-- Any event forced by at most k independently prescribed group/cell coins +has probability at least 2⁻ᵏ. -/ +lemma prob_at_least_prescription {I : Type*} [Fintype I] + (S : Finset I) (b : I → Bool) (P : (I → Bool) → Prop) {k : ℕ} + (hk : S.card ≤ k) (h : ∀ ω, (∀ i ∈ S, ω i=b i) → P ω) : + 1/(2:ℝ)^k ≤ prob P := by + calc + _ ≤ 1/(2:ℝ)^S.card := by + apply one_div_le_one_div_of_le (by positivity) + exact pow_le_pow_right₀ (by norm_num) hk + _ = prob (fun ω : I → Bool => ∀ i ∈ S, ω i=b i) := (prob_prescribed S b).symm + _ ≤ prob P := prob_mono h + +end PlanarL1.FiniteRandom + + + +end + +end OAI diff --git a/lean/OAI/Combinatorics/PlanarL1/RadialTree.lean b/lean/OAI/Combinatorics/PlanarL1/RadialTree.lean new file mode 100644 index 0000000000000000000000000000000000000000..2d88fe3cf2f8aa82e1925c42a82e9c718181d1c2 --- /dev/null +++ b/lean/OAI/Combinatorics/PlanarL1/RadialTree.lean @@ -0,0 +1,1520 @@ +import OAI.Combinatorics.PlanarL1.Distance +import OAI.Combinatorics.PlanarL1.Interpolation + +namespace OAI + +section + +namespace PlanarL1 +namespace Columns +namespace Model + +variable {n : ℕ} (M : Model n) + +namespace Point + +variable {M} {J : Set ℝ} {root : Fin n} + +/-! ### The actual radial-node tree and its interpolation formulas +The geometric data below use precisely the thin-band constants. Nodes and their +parent maps are induced-graph components, not an assumed abstract hierarchy. -/ + +structure RadialTree where + base : M.Point J root + δ : ℝ + a : ℝ + ζ : ℝ + delta_pos : 0 < δ + width_pos : 0 < a + zeta_pos : 0 < ζ + zeta_lt_one : ζ < 1 + width_bound : a ≤ ζ * δ / 1000000 + half_width : ∀ T ∈ J, |base.height - T| ≤ a / 2 + closed_band : IsClosed J + interval_band : Set.OrdConnected J + +namespace RadialTree + +variable (R : RadialTree (M := M) (J := J) (root := root)) + +def Node (k : ℕ) := + ((M.activeGraph J).induce + (R.base.superlevel R.base.height R.base.inBand (k * R.δ))).ConnectedComponent + +lemma width_small : R.a < R.δ / 1000 := by + have h := mul_lt_mul_of_pos_right R.zeta_lt_one R.delta_pos + nlinarith [R.width_bound, R.delta_pos] + +lemma superlevel_antitone {k m : ℕ} (hkm : k ≤ m) : + R.base.superlevel R.base.height R.base.inBand (m * R.δ) ⊆ + R.base.superlevel R.base.height R.base.inBand (k * R.δ) := by + rintro i ⟨hr, hi⟩ + refine ⟨hr, le_trans ?_ hi⟩ + exact mul_le_mul_of_nonneg_right (by exact_mod_cast hkm) R.delta_pos.le + +def parent {k : ℕ} (C : R.Node (k + 1)) : R.Node k := + ColumnOrder.componentAbove (R.superlevel_antitone (Nat.le_succ k)) C + +lemma mem_parent {k : ℕ} (C : R.Node (k + 1)) : + ColumnOrder.componentColumns C ⊆ ColumnOrder.componentColumns (R.parent C) := + ColumnOrder.componentColumns_above _ C + +noncomputable def portals {k : ℕ} (C : R.Node k) : + R.base.PortalData R.base.height R.base.inBand R.a (k * R.δ) C := + Classical.choice (R.base.portalData_nonempty R.closed_band R.base.inBand rfl + R.width_pos R.half_width (by + by_cases hk : k = 0 + · left; simp [hk] + · right + have hk' : (1 : ℝ) ≤ k := by exact_mod_cast Nat.one_le_iff_ne_zero.mpr hk + have hw := R.width_small + nlinarith [mul_le_mul_of_nonneg_right hk' R.delta_pos.le, R.delta_pos]) C) + +lemma parent_near {k : ℕ} (C : R.Node (k + 1)) (v : M.Point J root) + (hv : v = (R.portals C).left ∨ v = (R.portals C).right) : + min (dist v (R.portals (R.parent C)).left) + (dist v (R.portals (R.parent C)).right) ≤ R.δ + 220 * R.a := by + have hm : v.column ∈ ColumnOrder.componentColumns (R.parent C) := by + apply R.mem_parent C + rcases hv with rfl | rfl + · exact (R.portals C).left_mem + · exact (R.portals C).right_mem + have hr : dist R.base v < (k : ℝ) * R.δ + R.δ + R.a := by + rcases hv with rfl | rfl + · simpa only [Nat.cast_add, Nat.cast_one, add_mul, one_mul] using + (R.portals C).left_radial.2 + · simpa only [Nat.cast_add, Nat.cast_one, add_mul, one_mul] using + (R.portals C).right_radial.2 + linarith [(R.portals (R.parent C)).near_of_radial v hm hr.le, R.width_pos] + +lemma parent_separated {k : ℕ} (C : R.Node (k + 1)) (u v : M.Point J root) + (hu : u = (R.portals (R.parent C)).left ∨ u = (R.portals (R.parent C)).right) + (hv : v = (R.portals C).left ∨ v = (R.portals C).right) : + R.δ - 10 * R.a ≤ dist u v := by + have hr : dist R.base u < (k : ℝ) * R.δ + R.a := by + rcases hu with rfl | rfl + · exact (R.portals (R.parent C)).left_radial.2 + · exact (R.portals (R.parent C)).right_radial.2 + have hs : (k : ℝ) * R.δ + R.δ ≤ dist R.base v := by + rcases hv with rfl | rfl + · simpa only [Nat.cast_add, Nat.cast_one, add_mul, one_mul] using + (R.portals C).left_radial.1 + · simpa only [Nat.cast_add, Nat.cast_one, add_mul, one_mul] using + (R.portals C).right_radial.1 + linarith [dist_triangle R.base u v, R.width_pos] + +/-- Atom names use depth, portal column and type. Equal portals therefore have +one name and one noise, including the root's single tentative atom. -/ +def atomName (k : ℕ) (v : M.Point J root) (j : Fin 3) : ℕ := + 3 * (n * k + v.column.val) + j.val + +lemma atomName_bounds (k : ℕ) (v : M.Point J root) (j : Fin 3) : + 3 * n * k ≤ atomName k v j ∧ atomName k v j < 3 * n * (k + 1) := by + simp only [atomName, Nat.mul_add, Nat.mul_one, Nat.mul_assoc] + have := v.column.isLt + have := j.isLt + constructor <;> omega + +/-- A complete noise assignment. Bounds and independence are imposed on the +actual probability space later, not assumed properties of the output. -/ +abbrev Noise := ℕ → Fin n → Fin 3 → ℝ + +open Interpolation + +noncomputable def tentative (p : M.Point J root → ℝ) (α : Noise (n := n)) + {k : ℕ} (C : R.Node k) (v : M.Point J root) : NamedValue := + minNamed + ⟨atomName k (R.portals C).left 0, + p (R.portals C).left + dist (R.portals C).left v + α k (R.portals C).left.column 0⟩ + ⟨atomName k (R.portals C).right 0, + p (R.portals C).right + dist (R.portals C).right v + α k (R.portals C).right.column 0⟩ + +noncomputable def upperCone (F : M.Point J root → NamedValue) (α : Noise (n := n)) + {k : ℕ} (C : R.Node k) (v : M.Point J root) : NamedValue := + minNamed + ⟨atomName k (R.portals C).left 1, + (F (R.portals C).left).value + dist (R.portals C).left v - α k (R.portals C).left.column 1⟩ + ⟨atomName k (R.portals C).right 1, + (F (R.portals C).right).value + dist (R.portals C).right v - α k (R.portals C).right.column 1⟩ + +noncomputable def lowerCone (F : M.Point J root → NamedValue) (α : Noise (n := n)) + {k : ℕ} (C : R.Node k) (v : M.Point J root) : NamedValue := + maxNamed + ⟨atomName k (R.portals C).left 2, + (F (R.portals C).left).value - dist (R.portals C).left v + α k (R.portals C).left.column 2⟩ + ⟨atomName k (R.portals C).right 2, + (F (R.portals C).right).value - dist (R.portals C).right v + α k (R.portals C).right.column 2⟩ + +/-- The manuscript's recursive named formulas, on the whole metric component. -/ +noncomputable def formula (p : M.Point J root → ℝ) (α : Noise (n := n)) : + (k : ℕ) → R.Node k → M.Point J root → NamedValue + | 0, C, v => R.tentative p α C v + | k + 1, C, v => + let F := formula p α k (R.parent C) + nodeNamed (F v) (R.upperCone F α C v) (R.lowerCone F α C v) (R.tentative p α C v) + +lemma tentative_names (p : M.Point J root → ℝ) (α : Noise (n := n)) + {k : ℕ} (C : R.Node k) (v : M.Point J root) : + 3 * n * k ≤ (R.tentative p α C v).name ∧ + (R.tentative p α C v).name < 3 * n * (k + 1) := by + rcases minNamed_mem _ _ with h | h + · rw [tentative, h] + exact atomName_bounds k (R.portals C).left 0 + · rw [tentative, h] + exact atomName_bounds k (R.portals C).right 0 + +lemma upperCone_names (F : M.Point J root → NamedValue) (α : Noise (n := n)) + {k : ℕ} (C : R.Node k) (v : M.Point J root) : + 3 * n * k ≤ (R.upperCone F α C v).name ∧ + (R.upperCone F α C v).name < 3 * n * (k + 1) := by + rcases minNamed_mem _ _ with h | h + · rw [upperCone, h] + exact atomName_bounds k (R.portals C).left 1 + · rw [upperCone, h] + exact atomName_bounds k (R.portals C).right 1 + +lemma lowerCone_names (F : M.Point J root → NamedValue) (α : Noise (n := n)) + {k : ℕ} (C : R.Node k) (v : M.Point J root) : + 3 * n * k ≤ (R.lowerCone F α C v).name ∧ + (R.lowerCone F α C v).name < 3 * n * (k + 1) := by + rcases maxNamed_mem _ _ with h | h + · rw [lowerCone, h] + exact atomName_bounds k (R.portals C).left 2 + · rw [lowerCone, h] + exact atomName_bounds k (R.portals C).right 2 + +lemma formula_name_bound (p : M.Point J root → ℝ) (α : Noise (n := n)) + (k : ℕ) (C : R.Node k) (v : M.Point J root) : + (R.formula p α k C v).name < 3 * n * (k + 1) := by + induction k with + | zero => exact (R.tentative_names p α C v).2 + | succ k ih => + rw [formula] + rcases nodeNamed_mem _ _ _ _ with h | h | h | h + · rw [h] + exact (ih (R.parent C)).trans_le (Nat.mul_le_mul_left (3 * n) (Nat.le_succ (k + 1))) + · rw [h] + exact (R.upperCone_names _ _ _ _).2 + · rw [h] + exact (R.lowerCone_names _ _ _ _).2 + · rw [h] + exact (R.tentative_names _ _ _ _).2 + +lemma tentative_lipschitz (p : M.Point J root → ℝ) (α : Noise (n := n)) + {k : ℕ} (C : R.Node k) : LipschitzWith 1 (fun v => (R.tentative p α C v).value) := by + let l := (R.portals C).left + let r := (R.portals C).right + have hl := (distance_cone_lipschitz l (p l + α k l.column 0)).1 + have hr := (distance_cone_lipschitz r (p r + α k r.column 0)).1 + simpa only [tentative, minNamed_value, max_self, add_right_comm] using hl.min hr + +lemma upperCone_lipschitz (F : M.Point J root → NamedValue) (α : Noise (n := n)) + {k : ℕ} (C : R.Node k) : LipschitzWith 1 (fun v => (R.upperCone F α C v).value) := by + let l := (R.portals C).left + let r := (R.portals C).right + have hl := (distance_cone_lipschitz l ((F l).value - α k l.column 1)).1 + have hr := (distance_cone_lipschitz r ((F r).value - α k r.column 1)).1 + simpa only [upperCone, minNamed_value, max_self, sub_add_eq_add_sub] using hl.min hr + +lemma lowerCone_lipschitz (F : M.Point J root → NamedValue) (α : Noise (n := n)) + {k : ℕ} (C : R.Node k) : LipschitzWith 1 (fun v => (R.lowerCone F α C v).value) := by + let l := (R.portals C).left + let r := (R.portals C).right + have hl := (distance_cone_lipschitz l ((F l).value + α k l.column 2)).2 + have hr := (distance_cone_lipschitz r ((F r).value + α k r.column 2)).2 + simpa only [lowerCone, maxNamed_value, max_self, sub_add_eq_add_sub] using hl.max hr + +lemma formula_lipschitz (p : M.Point J root → ℝ) (α : Noise (n := n)) + (k : ℕ) (C : R.Node k) : LipschitzWith 1 (fun v => (R.formula p α k C v).value) := by + induction k with + | zero => exact R.tentative_lipschitz p α C + | succ k ih => + simpa only [formula, nodeNamed_value] using + nodeValue_lipschitz (ih (R.parent C)) (R.upperCone_lipschitz _ _ _) + (R.lowerCone_lipschitz _ _ _) (R.tentative_lipschitz _ _ _) + +noncomputable def q : ℝ := R.ζ * R.δ / 20 + +lemma q_pos : 0 < R.q := div_pos (mul_pos R.zeta_pos R.delta_pos) (by norm_num) + +lemma q_small : 2 * R.q ≤ R.δ / 10 := by + have h := mul_lt_mul_of_pos_right R.zeta_lt_one R.delta_pos + dsimp [q] + linarith + +def NoiseBounds (α : Noise (n := n)) : Prop := + ∀ k i j, R.q ≤ α k i j ∧ α k i j ≤ 2 * R.q + +def InputLip (p : M.Point J root → ℝ) : Prop := + ∀ x y, |p x - p y| ≤ (1 - R.ζ) * dist x y + +noncomputable def portalDistance {k : ℕ} (C : R.Node k) (v : M.Point J root) : ℝ := + min (dist (R.portals C).left v) (dist (R.portals C).right v) + +lemma portalDistance_nonneg {k : ℕ} (C : R.Node k) (v : M.Point J root) : + 0 ≤ R.portalDistance C v := le_min dist_nonneg dist_nonneg + +lemma tentative_bounds {p : M.Point J root → ℝ} {α : Noise (n := n)} + (hp : R.InputLip p) (hα : R.NoiseBounds α) {k : ℕ} (C : R.Node k) (v : M.Point J root) : + p v + R.ζ * R.portalDistance C v + R.q ≤ (R.tentative p α C v).value ∧ + (R.tentative p α C v).value ≤ p v + (2 - R.ζ) * R.portalDistance C v + 2 * R.q := by + have atom (w : M.Point J root) : + p v + R.ζ * dist w v + R.q ≤ p w + dist w v + α k w.column 0 ∧ + p w + dist w v + α k w.column 0 ≤ p v + (2 - R.ζ) * dist w v + 2 * R.q := by + have hlip := abs_le.mp (hp w v) + have hn := hα k w.column 0 + constructor <;> nlinarith + have hleft := atom (R.portals C).left + have hright := atom (R.portals C).right + simp only [tentative, minNamed_value] + constructor + · apply le_min + · have hd := mul_le_mul_of_nonneg_left + (min_le_left (dist (R.portals C).left v) (dist (R.portals C).right v)) R.zeta_pos.le + dsimp [portalDistance] + linarith + · have hd := mul_le_mul_of_nonneg_left + (min_le_right (dist (R.portals C).left v) (dist (R.portals C).right v)) R.zeta_pos.le + dsimp [portalDistance] + linarith + · rcases le_total (dist (R.portals C).left v) (dist (R.portals C).right v) with h | h + · rw [portalDistance, min_eq_left h] + exact (min_le_left _ _).trans hleft.2 + · rw [portalDistance, min_eq_right h] + exact (min_le_right _ _).trans hright.2 + +lemma cone_bounds {p : M.Point J root → ℝ} {α : Noise (n := n)} + (hp : R.InputLip p) (hα : R.NoiseBounds α) {k : ℕ} (C : R.Node k) + (F : M.Point J root → NamedValue) + (hF : ∀ w, w = (R.portals C).left ∨ w = (R.portals C).right → + |(F w).value - p w| ≤ 5 * R.δ) (v : M.Point J root) : + p v - 5 * R.δ + R.ζ * R.portalDistance C v - 2 * R.q ≤ (R.upperCone F α C v).value ∧ + (R.lowerCone F α C v).value ≤ p v + 5 * R.δ - R.ζ * R.portalDistance C v + 2 * R.q := by + have atom (w : M.Point J root) (hw : w = (R.portals C).left ∨ w = (R.portals C).right) + (hd : R.portalDistance C v ≤ dist w v) : + p v - 5 * R.δ + R.ζ * R.portalDistance C v - 2 * R.q ≤ + (F w).value + dist w v - α k w.column 1 ∧ + (F w).value - dist w v + α k w.column 2 ≤ + p v + 5 * R.δ - R.ζ * R.portalDistance C v + 2 * R.q := by + have hlip := abs_le.mp (hp w v) + have ha := abs_le.mp (hF w hw) + have hn₁ := hα k w.column 1 + have hn₂ := hα k w.column 2 + have hz := mul_le_mul_of_nonneg_left hd R.zeta_pos.le + constructor <;> nlinarith + have hl := atom (R.portals C).left (Or.inl rfl) (min_le_left _ _) + have hr := atom (R.portals C).right (Or.inr rfl) (min_le_right _ _) + exact ⟨by simpa only [upperCone, minNamed_value, le_min_iff] using And.intro hl.1 hr.1, + by simpa only [lowerCone, maxNamed_value, max_le_iff] using And.intro hl.2 hr.2⟩ + +/-- With the thin-band constants, every nearby tentative value lies in the +same three-delta window used in the manuscript's induction. -/ +lemma tentative_near {p : M.Point J root → ℝ} {α : Noise (n := n)} + (hp : R.InputLip p) (hα : R.NoiseBounds α) {k : ℕ} (C : R.Node k) (v : M.Point J root) + (hn : R.portalDistance C v ≤ R.δ + 220 * R.a) : + p v ≤ (R.tentative p α C v).value ∧ (R.tentative p α C v).value ≤ p v + 3 * R.δ := by + obtain ⟨hl, hu⟩ := R.tentative_bounds hp hα C v + have hd := R.portalDistance_nonneg C v + have hz := R.zeta_pos + have hδ := R.delta_pos + constructor + · nlinarith [R.q_pos] + · have h := mul_le_mul_of_nonneg_left hn (by linarith [R.zeta_lt_one] : 0 ≤ 2 - R.ζ) + have hw := R.width_small + have hq := R.q_small + nlinarith [R.width_pos, mul_nonneg hz.le hd] + +/-- Exact named inheritance on the genuine entrance collar. -/ +lemma formula_collar (p : M.Point J root → ℝ) {α : Noise (n := n)} + (hα : R.NoiseBounds α) {k : ℕ} (C : R.Node (k + 1)) (v : M.Point J root) + (hc : R.portalDistance C v ≤ R.ζ * R.δ / 50) : + R.formula p α (k + 1) C v = R.formula p α k (R.parent C) v := by + let F := R.formula p α k (R.parent C) + have hF := R.formula_lipschitz p α k (R.parent C) + have hcq : 2 * (R.ζ * R.δ / 50) < R.q := by + dsimp [q] + nlinarith [mul_pos R.zeta_pos R.delta_pos] + have single (w : M.Point J root) (hw : dist w v ≤ R.ζ * R.δ / 50) : + (F w).value + dist w v - α (k + 1) w.column 1 < (F v).value ∧ + (F v).value < (F w).value - dist w v + α (k + 1) w.column 2 := by + have hlip := hF.dist_le_mul w v + change |(F w).value - (F v).value| ≤ (1 : ℝ) * dist w v at hlip + simp only [one_mul, abs_le] at hlip + have hn₁ := hα (k + 1) w.column 1 + have hn₂ := hα (k + 1) w.column 2 + constructor <;> linarith + have hcones : (R.upperCone F α C v).value < (F v).value ∧ + (F v).value < (R.lowerCone F α C v).value := by + simp only [upperCone, lowerCone, minNamed_value, maxNamed_value] + rcases min_le_iff.mp hc with h | h + · have hs := single (R.portals C).left h + exact ⟨lt_of_le_of_lt (min_le_left _ _) hs.1, + lt_of_lt_of_le hs.2 (le_max_left _ _)⟩ + · have hs := single (R.portals C).right h + exact ⟨lt_of_le_of_lt (min_le_right _ _) hs.1, + lt_of_lt_of_le hs.2 (le_max_right _ _)⟩ + change nodeNamed (F v) _ _ _ = F v + apply nodeNamed_collar hcones.1 hcones.2 + exact (R.formula_name_bound p α k (R.parent C) v).le.trans + (R.tentative_names p α C v).1 + + +lemma portal_spacing : 2 * R.q ≤ R.ζ * (R.δ - 10 * R.a) := by + have hw : R.δ / 10 ≤ R.δ - 10 * R.a := by linarith [R.width_small, R.delta_pos] + have hh := mul_le_mul_of_nonneg_left hw R.zeta_pos.le + dsimp [q] + nlinarith + +/-- The complete quantitative induction on the ACTUAL component hierarchy. +The second bound applies to child portals; the first applies on the own layer. -/ +lemma formula_near_accuracy {p : M.Point J root → ℝ} {α : Noise (n := n)} + (hp : R.InputLip p) (hα : R.NoiseBounds α) (k : ℕ) (C : R.Node k) (v : M.Point J root) + (hn : R.portalDistance C v ≤ R.δ + 220 * R.a) : + |(R.formula p α k C v).value - p v| ≤ 5 * R.δ + 2 * R.q ∧ + (2 * R.q ≤ R.ζ * R.portalDistance C v → + |(R.formula p α k C v).value - p v| ≤ 5 * R.δ) := by + induction k generalizing v with + | zero => + have hT := R.tentative_near hp hα C v hn + simp only [formula, abs_le] + constructor + · constructor <;> linarith [R.delta_pos, R.q_pos] + · intro _ + constructor <;> linarith [R.delta_pos] + | succ k ih => + let F := R.formula p α k (R.parent C) + have hF : ∀ w, w = (R.portals C).left ∨ w = (R.portals C).right → + |(F w).value - p w| ≤ 5 * R.δ := by + intro w hw + have hn' : R.portalDistance (R.parent C) w ≤ R.δ + 220 * R.a := by + simpa only [portalDistance, dist_comm w] using R.parent_near C w hw + have hd : R.δ - 10 * R.a ≤ R.portalDistance (R.parent C) w := + le_min (R.parent_separated C _ w (Or.inl rfl) hw) + (R.parent_separated C _ w (Or.inr rfl) hw) + have hs := R.portal_spacing.trans (mul_le_mul_of_nonneg_left hd R.zeta_pos.le) + exact (ih (R.parent C) w hn').2 hs + obtain ⟨hA, hB⟩ := R.cone_bounds hp hα C F hF v + obtain ⟨hTlo, hThi⟩ := R.tentative_near hp hα C v hn + have hval : (R.formula p α (k + 1) C v).value = + nodeValue (F v).value (R.upperCone F α C v).value + (R.lowerCone F α C v).value (R.tentative p α C v).value := by + simp only [formula, nodeNamed_value, F] + have bound (e : ℝ) (he : 3 * R.δ ≤ e) + (hu : 5 * R.δ - R.ζ * R.portalDistance C v + 2 * R.q ≤ e) : + |(R.formula p α (k + 1) C v).value - p v| ≤ e := by + have hb := nodeValue_bounds (parent := (F v).value) + (lo := p v - e) (hi := p v + e) + (show p v - e ≤ (R.upperCone F α C v).value by linarith) + (show (R.lowerCone F α C v).value ≤ p v + e by linarith) + (show p v - e ≤ (R.tentative p α C v).value by linarith [R.delta_pos]) + (show (R.tentative p α C v).value ≤ p v + e by linarith) + rw [hval, abs_le] + constructor <;> linarith + constructor + · apply bound (5 * R.δ + 2 * R.q) + · linarith [R.delta_pos, R.q_pos] + · nlinarith [mul_nonneg R.zeta_pos.le (R.portalDistance_nonneg C v)] + · intro hs + exact bound (5 * R.δ) (by linarith [R.delta_pos]) (by linarith) + +lemma formula_child_accuracy {p : M.Point J root → ℝ} {α : Noise (n := n)} + (hp : R.InputLip p) (hα : R.NoiseBounds α) {k : ℕ} (C : R.Node (k + 1)) + (v : M.Point J root) (hv : v = (R.portals C).left ∨ v = (R.portals C).right) : + |(R.formula p α k (R.parent C) v).value - p v| ≤ 5 * R.δ := by + have hn : R.portalDistance (R.parent C) v ≤ R.δ + 220 * R.a := by + simpa only [portalDistance, dist_comm v] using R.parent_near C v hv + have hd : R.δ - 10 * R.a ≤ R.portalDistance (R.parent C) v := + le_min (R.parent_separated C _ v (Or.inl rfl) hv) + (R.parent_separated C _ v (Or.inr rfl) hv) + exact (R.formula_near_accuracy hp hα k (R.parent C) v hn).2 + (R.portal_spacing.trans (mul_le_mul_of_nonneg_left hd R.zeta_pos.le)) + +lemma formula_layer_accuracy {p : M.Point J root → ℝ} {α : Noise (n := n)} + (hp : R.InputLip p) (hα : R.NoiseBounds α) {k : ℕ} (C : R.Node k) (v : M.Point J root) + (hv : v.column ∈ ColumnOrder.componentColumns C) + (hr : dist R.base (v.withHeight R.base.height R.base.inBand) < (k + 1 : ℕ) * R.δ) : + |(R.formula p α k C v).value - p v| ≤ 6 * R.δ := by + have hn : R.portalDistance C v ≤ R.δ + 220 * R.a := by + have hh : dist R.base (v.withHeight R.base.height R.base.inBand) < (k : ℝ) * R.δ + R.δ := by + simpa only [Nat.cast_add, Nat.cast_one, add_mul, one_mul] using hr + simpa only [portalDistance, dist_comm v] using + (R.portals C).near_layer R.half_width R.width_pos.le v hv hh + have ha := (R.formula_near_accuracy hp hα k C v hn).1 + linarith [R.q_small, R.delta_pos] + + +/-- The unique depth of the layer assigned to a column. -/ +noncomputable def layerDepth (v : M.Point J root) : ℕ := + ⌊dist R.base (v.withHeight R.base.height R.base.inBand) / R.δ⌋₊ + +lemma layerDepth_bounds (v : M.Point J root) : + (R.layerDepth v : ℝ) * R.δ ≤ dist R.base (v.withHeight R.base.height R.base.inBand) ∧ + dist R.base (v.withHeight R.base.height R.base.inBand) < (R.layerDepth v + 1 : ℕ) * R.δ := by + have hl := Nat.floor_le (div_nonneg (dist_nonneg (x := R.base) + (y := v.withHeight R.base.height R.base.inBand)) R.delta_pos.le) + have hu := Nat.lt_floor_add_one + (dist R.base (v.withHeight R.base.height R.base.inBand) / R.δ) + constructor + · exact (le_div_iff₀ R.delta_pos).mp hl + · simpa only [layerDepth, Nat.cast_add, Nat.cast_one] using (div_lt_iff₀ R.delta_pos).mp hu + +lemma layerDepth_eq {k : ℕ} (v : M.Point J root) + (hl : (k : ℝ) * R.δ ≤ dist R.base (v.withHeight R.base.height R.base.inBand)) + (hu : dist R.base (v.withHeight R.base.height R.base.inBand) < (k + 1 : ℕ) * R.δ) : + R.layerDepth v = k := by + apply (Nat.floor_eq_iff (div_nonneg dist_nonneg R.delta_pos.le)).mpr + refine ⟨(le_div_iff₀ R.delta_pos).mpr hl, ?_⟩ + apply (div_lt_iff₀ R.delta_pos).mpr + simpa only [Nat.cast_add, Nat.cast_one] using hu + +noncomputable def nodeOf (k : ℕ) (v : M.Point J root) + (hv : (k : ℝ) * R.δ ≤ dist R.base (v.withHeight R.base.height R.base.inBand)) : R.Node k := + ((M.activeGraph J).induce _).connectedComponentMk + ⟨v.column, (R.base.mem_superlevel_iff v R.base.height R.base.inBand (k * R.δ)).mpr hv⟩ + +lemma mem_nodeOf (k : ℕ) (v : M.Point J root) + (hv : (k : ℝ) * R.δ ≤ dist R.base (v.withHeight R.base.height R.base.inBand)) : + v.column ∈ ColumnOrder.componentColumns (R.nodeOf k v hv) := + ⟨⟨v.column, (R.base.mem_superlevel_iff v R.base.height R.base.inBand (k * R.δ)).mpr hv⟩, rfl, rfl⟩ + +noncomputable def layerNode (v : M.Point J root) : R.Node (R.layerDepth v) := + R.nodeOf (R.layerDepth v) v (R.layerDepth_bounds v).1 + +lemma mem_layerNode (v : M.Point J root) : + v.column ∈ ColumnOrder.componentColumns (R.layerNode v) := + R.mem_nodeOf (R.layerDepth v) v (R.layerDepth_bounds v).1 + +/-- The actual pasted named output on representatives. -/ +noncomputable def pasted (p : M.Point J root → ℝ) (α : Noise (n := n)) (v : M.Point J root) : NamedValue := + R.formula p α (R.layerDepth v) (R.layerNode v) v + +lemma pasted_eq_of_layer (p : M.Point J root → ℝ) (α : Noise (n := n)) + {k : ℕ} (C : R.Node k) (v : M.Point J root) + (hm : v.column ∈ ColumnOrder.componentColumns C) + (hl : (k : ℝ) * R.δ ≤ dist R.base (v.withHeight R.base.height R.base.inBand)) + (hu : dist R.base (v.withHeight R.base.height R.base.inBand) < (k + 1 : ℕ) * R.δ) : + R.pasted p α v = R.formula p α k C v := by + have hd := R.layerDepth_eq v hl hu + subst k + have he : R.layerNode v = C := ColumnOrder.component_eq_of_column (R.mem_layerNode v) hm + simp only [pasted, he] + +lemma pasted_accuracy {p : M.Point J root → ℝ} {α : Noise (n := n)} + (hp : R.InputLip p) (hα : R.NoiseBounds α) (v : M.Point J root) : + |(R.pasted p α v).value - p v| ≤ 6 * R.δ := + R.formula_layer_accuracy hp hα (R.layerNode v) v (R.mem_layerNode v) (R.layerDepth_bounds v).2 + +noncomputable def radius : ℝ := R.ζ * R.δ / 1000 + +lemma radius_pos : 0 < R.radius := div_pos (mul_pos R.zeta_pos R.delta_pos) (by norm_num) + +lemma radius_bounds {ρ : ℝ} (hρ : ρ ≤ R.radius) : + 2 * ρ + R.a < R.δ ∧ 2 * ρ + 200 * R.a ≤ R.ζ * R.δ / 50 := by + have hw := R.width_bound + have hd := mul_lt_mul_of_pos_right R.zeta_lt_one R.delta_pos + have hz := mul_pos R.zeta_pos R.delta_pos + dsimp [radius] at hρ + constructor <;> nlinarith + +/-- One deterministic node formula, with identical atom names, represents the +pasted output on the whole small ball (including every zero-distance copy). +The node exists independently of the noises and the input. -/ +lemma common_formula (x : M.Point J root) {ρ : ℝ} (hρ : 0 ≤ ρ) (hs : ρ ≤ R.radius) : + ∃ k : ℕ, ∃ C : R.Node k, + (∀ z : M.Point J root, dist x z ≤ ρ → + (k : ℝ) * R.δ ≤ dist R.base (z.withHeight R.base.height R.base.inBand)) ∧ + (∀ (p : M.Point J root → ℝ) (α : Noise (n := n)), R.NoiseBounds α → + ∀ z : M.Point J root, dist x z ≤ ρ → R.pasted p α z = R.formula p α k C z) := by + obtain ⟨k, y, C, hy, hylo, hC⟩ := R.base.ball_two_layers R.closed_band x R.base.inBand + hρ R.delta_pos R.half_width (R.radius_bounds hs).1 + refine ⟨k, C, fun z hz => (hC z hz).2.1, ?_⟩ + intro p α hα z hz + obtain ⟨hzm, hzl, hzu⟩ := hC z hz + by_cases hlo : dist R.base (z.withHeight R.base.height R.base.inBand) < (k + 1 : ℕ) * R.δ + · exact R.pasted_eq_of_layer p α C z hzm hzl hlo + · have hzl' := le_of_not_gt hlo + let D := R.nodeOf (k + 1) z hzl' + have hD := R.mem_nodeOf (k + 1) z hzl' + have hparent : R.parent D = C := + ColumnOrder.component_eq_of_column (R.mem_parent D hD) hzm + have hyout : y.column ∉ ColumnOrder.componentColumns D := by + intro hym + have hry := (R.base.mem_superlevel_iff y R.base.height R.base.inBand (((k + 1 : ℕ) : ℝ) * R.δ)).mp + (ColumnOrder.componentColumns_subset D hym) + have hyp : dist R.base (y.withHeight R.base.height R.base.inBand) < ((k + 1 : ℕ) : ℝ) * R.δ := by + simpa only [Nat.cast_add, Nat.cast_one] using hylo + exact hyp.not_ge hry + have hexit := (R.portals D).near_exit R.closed_band z y hD hyout + have hzy : dist z y ≤ 2 * ρ := by + have ht := dist_triangle z x y + rw [dist_comm z x] at ht + linarith + have hcollar : R.portalDistance D z ≤ R.ζ * R.δ / 50 := by + dsimp only [portalDistance] + simp only [dist_comm z] at hexit + rw [dist_comm y z] at hexit + linarith [(R.radius_bounds hs).2] + have hupper : dist R.base (z.withHeight R.base.height R.base.inBand) < ((k + 1 + 1 : ℕ) : ℝ) * R.δ := by + simpa only [Nat.cast_add, Nat.cast_one, Nat.cast_ofNat, add_assoc, one_add_one_eq_two] using hzu + rw [R.pasted_eq_of_layer p α D z hD hzl' hupper, + R.formula_collar p hα D z hcollar, hparent] + +lemma formula_congr_zero (p : M.Point J root → ℝ) (α : Noise (n := n)) + (k : ℕ) (C : R.Node k) (x y : M.Point J root) (hxy : dist x y = 0) : + R.formula p α k C x = R.formula p α k C y := by + have hd (w : M.Point J root) : dist w x = dist w y := by + apply le_antisymm + · have ht := dist_triangle w y x + rw [dist_comm y x, hxy, add_zero] at ht + exact ht + · have ht := dist_triangle w x y + rw [hxy, add_zero] at ht + exact ht + induction k with + | zero => simp only [formula, tentative, hd] + | succ k ih => simp only [formula, tentative, upperCone, lowerCone, hd, ih] + +lemma pasted_congr_zero (p : M.Point J root → ℝ) {α : Noise (n := n)} + (hα : R.NoiseBounds α) (x y : M.Point J root) (hxy : dist x y = 0) : + R.pasted p α x = R.pasted p α y := by + obtain ⟨k, C, _, hC⟩ := R.common_formula x R.radius_pos.le le_rfl + rw [hC p α hα x (by simpa using R.radius_pos.le), hC p α hα y (by simpa [hxy] using R.radius_pos.le)] + exact R.formula_congr_zero p α k C x y hxy + +lemma pasted_local_lipschitz (p : M.Point J root → ℝ) {α : Noise (n := n)} + (hα : R.NoiseBounds α) (x y : M.Point J root) (hxy : dist x y ≤ R.radius) : + |(R.pasted p α x).value - (R.pasted p α y).value| ≤ dist x y := by + obtain ⟨k, C, _, hC⟩ := R.common_formula x R.radius_pos.le le_rfl + rw [hC p α hα x (by simpa using R.radius_pos.le), hC p α hα y hxy] + simpa only [Real.dist_eq, NNReal.coe_one, one_mul] using (R.formula_lipschitz p α k C).dist_le_mul x y + +/-- Uniform local unit bounds extend globally by genuine shortest-path +interpolation. No length-space axiom has been added. -/ +lemma pasted_lipschitz (p : M.Point J root → ℝ) {α : Noise (n := n)} (hα : R.NoiseBounds α) : + LipschitzWith 1 (fun v => (R.pasted p α v).value) := by + have bound (m : ℕ) : ∀ x y : M.Point J root, dist x y ≤ m * R.radius → + |(R.pasted p α x).value - (R.pasted p α y).value| ≤ dist x y := by + induction m with + | zero => + intro x y hxy + have hzero : dist x y ≤ 0 := by simpa only [Nat.cast_zero, zero_mul] using hxy + exact R.pasted_local_lipschitz p hα x y (hzero.trans R.radius_pos.le) + | succ m ih => + intro x y hxy + by_cases hsmall : dist x y ≤ R.radius + · exact R.pasted_local_lipschitz p hα x y hsmall + · obtain ⟨z, hxz, hzy⟩ := x.exists_between R.closed_band R.interval_band y + R.radius_pos.le (le_of_not_ge hsmall) + have hzsmall : dist z y ≤ m * R.radius := by + simp only [Nat.cast_succ, add_mul, one_mul] at hxy + linarith + have h₁ := R.pasted_local_lipschitz p hα x z hxz.le + have h₂ := ih z y hzsmall + have htri := abs_sub_le (R.pasted p α x).value (R.pasted p α z).value (R.pasted p α y).value + linarith + apply LipschitzWith.of_dist_le_mul + intro x y + obtain ⟨m, hm⟩ := exists_nat_ge (dist x y / R.radius) + have hdist := bound m x y ((div_le_iff₀ R.radius_pos).mp hm) + simpa only [Real.dist_eq, NNReal.coe_one, one_mul] using hdist + + +/-- Ancestors are constructed by inclusion of actual superlevel components. -/ +def ancestor {k : ℕ} (C : R.Node k) (j : ℕ) (hj : j ≤ k) : R.Node j := + ColumnOrder.componentAbove (R.superlevel_antitone hj) C + +lemma mem_ancestor {k : ℕ} (C : R.Node k) (j : ℕ) (hj : j ≤ k) : + ColumnOrder.componentColumns C ⊆ ColumnOrder.componentColumns (R.ancestor C j hj) := + ColumnOrder.componentColumns_above _ C + +lemma ancestor_self {k : ℕ} (C : R.Node k) (h : k ≤ k) : R.ancestor C k h = C := by + obtain ⟨i, hi⟩ := C.nonempty_supp + exact ColumnOrder.component_eq_of_column (R.mem_ancestor C k h ⟨i, hi, rfl⟩) ⟨i, hi, rfl⟩ + +lemma ancestor_parent {k j : ℕ} (C : R.Node (k + 1)) (hj : j ≤ k) : + R.ancestor (R.parent C) j hj = R.ancestor C j (hj.trans (Nat.le_succ k)) := by + obtain ⟨i, hi⟩ := C.nonempty_supp + have hm : i.val ∈ ColumnOrder.componentColumns C := ⟨i, hi, rfl⟩ + exact ColumnOrder.component_eq_of_column + (R.mem_ancestor (R.parent C) j hj (R.mem_parent C hm)) (R.mem_ancestor C j _ hm) + +lemma parent_ancestor {k j : ℕ} (C : R.Node k) (hj : j + 1 ≤ k) : + R.parent (R.ancestor C (j + 1) hj) = R.ancestor C j (by omega) := by + obtain ⟨i, hi⟩ := C.nonempty_supp + have hm : i.val ∈ ColumnOrder.componentColumns C := ⟨i, hi, rfl⟩ + exact ColumnOrder.component_eq_of_column + (R.mem_parent _ (R.mem_ancestor C (j + 1) hj hm)) (R.mem_ancestor C j _ hm) + +/-- A name older than a chosen depth is inherited literally all the way back +through the actual hierarchy. Intercepts are not re-evaluated or renamed. -/ +lemma formula_inherits (p : M.Point J root → ℝ) (α : Noise (n := n)) + (k : ℕ) (C : R.Node k) (j : ℕ) (hj : j ≤ k) (v : M.Point J root) + (hname : (R.formula p α k C v).name < 3 * n * j) : + R.formula p α k C v = R.formula p α j (R.ancestor C j hj) v := by + induction k generalizing j with + | zero => + have hj0 : j = 0 := by omega + subst j + rw [R.ancestor_self] + | succ k ih => + by_cases hlast : j = k + 1 + · subst j + rw [R.ancestor_self] + · have hjk : j ≤ k := by omega + have hstep : R.formula p α (k + 1) C v = R.formula p α k (R.parent C) v := by + change nodeNamed _ _ _ _ = _ + apply nodeNamed_old (cutoff := 3 * n * j) + · exact (Nat.mul_le_mul_left (3 * n) hj).trans (R.upperCone_names _ _ C v).1 + · exact (Nat.mul_le_mul_left (3 * n) hj).trans (R.lowerCone_names _ _ C v).1 + · exact (Nat.mul_le_mul_left (3 * n) hj).trans (R.tentative_names p α C v).1 + · exact hname + have hi := ih (R.parent C) j hjk (by simpa only [hstep] using hname) + rw [R.ancestor_parent C hjk] at hi + exact hstep.trans hi + +/-- A far node cannot output an accurate value carrying an earlier name. -/ +lemma formula_far_name {p : M.Point J root → ℝ} {α : Noise (n := n)} + (hp : R.InputLip p) (hα : R.NoiseBounds α) {k : ℕ} (C : R.Node (k + 1)) (v : M.Point J root) + (hfar : 13 * R.δ < R.ζ * R.portalDistance C v) + (hacc : |(R.formula p α (k + 1) C v).value - p v| ≤ 6 * R.δ) : + 3 * n * (k + 1) ≤ (R.formula p α (k + 1) C v).name := by + by_contra hn + have hn' := lt_of_not_ge hn + let F := R.formula p α k (R.parent C) + have hF : ∀ w, w = (R.portals C).left ∨ w = (R.portals C).right → + |(F w).value - p w| ≤ 5 * R.δ := R.formula_child_accuracy hp hα C + obtain ⟨hA, hB⟩ := R.cone_bounds hp hα C F hF v + have hT := (R.tentative_bounds hp hα C v).1 + have hsame : R.formula p α (k + 1) C v = F v := by + apply nodeNamed_old (R.upperCone_names F α C v).1 (R.lowerCone_names F α C v).1 + (R.tentative_names p α C v).1 hn' + have hparent : |(F v).value - p v| ≤ 6 * R.δ := by simpa only [hsame] using hacc + have hneq := (distant_node_overwrites R.delta_pos hparent + (show p v + 7 * R.δ < (R.upperCone F α C v).value by linarith [R.q_small, R.delta_pos]) + (show (R.lowerCone F α C v).value < p v - 7 * R.δ by linarith [R.q_small, R.delta_pos]) + (show p v + 13 * R.δ < (R.tentative p α C v).value by linarith [R.q_pos])).2 + apply hneq + have heq := congrArg NamedValue.value hsame + simpa only [formula, nodeNamed_value, F] using heq + +/-- The source's lookback constant, independent of diameter and tree depth. -/ +noncomputable def lookback : ℕ := ⌈15 / R.ζ⌉₊ + 3 + +lemma lookback_large : 15 ≤ R.ζ * (R.lookback : ℝ) := by + have hh := Nat.le_ceil (15 / R.ζ) + have hb : 15 / R.ζ ≤ (R.lookback : ℝ) := by + dsimp [lookback] + push_cast + linarith + have h := (div_le_iff₀ R.zeta_pos).mp hb + nlinarith + +lemma ancestor_distance {k j : ℕ} (C : R.Node k) (hj : j ≤ k) (v : M.Point J root) + (hv : (k : ℝ) * R.δ ≤ dist R.base (v.withHeight R.base.height R.base.inBand)) : + ((k : ℝ) - j) * R.δ - 3 * R.a ≤ R.portalDistance (R.ancestor C j hj) v := by + let D := R.ancestor C j hj + have hver : dist v (v.withHeight R.base.height R.base.inBand) ≤ R.a / 2 := by + rw [v.dist_withHeight, abs_sub_comm] + exact R.half_width v.height v.inBand + have hrad := dist_triangle R.base v (v.withHeight R.base.height R.base.inBand) + have single (w : M.Point J root) (hw : dist R.base w < (j : ℝ) * R.δ + R.a) : + ((k : ℝ) - j) * R.δ - 3 * R.a ≤ dist w v := by + nlinarith [dist_triangle R.base w v, R.width_pos] + exact le_min (single (R.portals D).left (R.portals D).left_radial.2) + (single (R.portals D).right (R.portals D).right_radial.2) + +lemma far_after_lookback {r : ℝ} (hr : (R.lookback : ℝ) * R.δ - 3 * R.a ≤ r) : + 13 * R.δ < R.ζ * r := by + have h₁ := mul_le_mul_of_nonneg_left hr R.zeta_pos.le + have h₂ := mul_le_mul_of_nonneg_right R.lookback_large R.delta_pos.le + have h₃ : R.ζ * R.a ≤ R.a := by + have hh := mul_lt_mul_of_pos_right R.zeta_lt_one R.width_pos + linarith + nlinarith [R.width_small, R.delta_pos] + +/-- Selected names of an accurate node at high radial points originate no +more than `lookback` generations earlier. This is not an assumed depth bound. -/ +lemma formula_recent_bound {p : M.Point J root → ℝ} {α : Noise (n := n)} + (hp : R.InputLip p) (hα : R.NoiseBounds α) (k : ℕ) (C : R.Node k) (v : M.Point J root) + (hv : (k : ℝ) * R.δ ≤ dist R.base (v.withHeight R.base.height R.base.inBand)) + (ha : |(R.formula p α k C v).value - p v| ≤ 6 * R.δ) : + 3 * n * (k - R.lookback) ≤ (R.formula p α k C v).name := by + by_cases hk : k ≤ R.lookback + · simp only [Nat.sub_eq_zero_of_le hk, Nat.mul_zero, Nat.zero_le] + · have hmk : k - R.lookback ≤ k := Nat.sub_le _ _ + obtain ⟨j, hj⟩ := Nat.exists_eq_succ_of_ne_zero + (show k - R.lookback ≠ 0 by omega) + have hjk : j + 1 ≤ k := by omega + by_contra hname + have hn : (R.formula p α k C v).name < 3 * n * (j + 1) := by + simpa only [hj] using lt_of_not_ge hname + have heq := R.formula_inherits p α k C (j + 1) hjk v hn + let D := R.ancestor C (j + 1) hjk + have hacc : |(R.formula p α (j + 1) D v).value - p v| ≤ 6 * R.δ := by + simpa only [heq] using ha + have hfar := R.ancestor_distance C hjk v hv + have hcast : (k : ℝ) - (j + 1 : ℕ) = R.lookback := by + have hn : k = j + 1 + R.lookback := by omega + exact_mod_cast (show (k : ℤ) - (j + 1) = R.lookback by omega) + rw [hcast] at hfar + have hnew := R.formula_far_name hp hα D v (R.far_after_lookback hfar) hacc + rw [heq] at hn + exact hn.not_ge hnew + + +/-- The fixed enumeration remembers whichever portal occurrence generated a +name. Duplicated portals still produce the same name. -/ +noncomputable def portalAt {k : ℕ} (C : R.Node k) (i : Fin 2) : M.Point J root := + if i = 0 then (R.portals C).left else (R.portals C).right + +noncomputable def nodeNames {k : ℕ} (C : R.Node k) : Finset ℕ := + Finset.univ.image (fun ij : Fin 2 × Fin 3 => atomName k (R.portalAt C ij.1) ij.2) + +lemma nodeNames_card {k : ℕ} (C : R.Node k) : (R.nodeNames C).card ≤ 6 := by + calc + (R.nodeNames C).card ≤ (Finset.univ : Finset (Fin 2 × Fin 3)).card := Finset.card_image_le + _ = 6 := by simp + +lemma nodeNames_mem {k : ℕ} (C : R.Node k) (i : Fin 2) (t : Fin 3) : + atomName k (R.portalAt C i) t ∈ R.nodeNames C := by + exact Finset.mem_image.mpr ⟨(i, t), Finset.mem_univ _, rfl⟩ + +lemma nodeNames_left {k : ℕ} (C : R.Node k) (t : Fin 3) : + atomName k (R.portals C).left t ∈ R.nodeNames C := by + simpa [portalAt] using R.nodeNames_mem C 0 t + +lemma nodeNames_right {k : ℕ} (C : R.Node k) (t : Fin 3) : + atomName k (R.portals C).right t ∈ R.nodeNames C := by + simpa only [portalAt, show (1 : Fin 2) ≠ 0 by decide, ite_false] using R.nodeNames_mem C 1 t + +lemma nodeNames_bounds {k : ℕ} (C : R.Node k) {m : ℕ} (hm : m ∈ R.nodeNames C) : + 3 * n * k ≤ m ∧ m < 3 * n * (k + 1) := by + obtain ⟨⟨i,t⟩, _, rfl⟩ := Finset.mem_image.mp hm + exact atomName_bounds k (R.portalAt C i) t + +lemma tentative_name_mem (p : M.Point J root → ℝ) (α : Noise (n := n)) + {k : ℕ} (C : R.Node k) (v : M.Point J root) : + (R.tentative p α C v).name ∈ R.nodeNames C := by + rcases minNamed_mem _ _ with h | h + · rw [tentative, h]; exact R.nodeNames_left C 0 + · rw [tentative, h]; exact R.nodeNames_right C 0 + +lemma upperCone_name_mem (F : M.Point J root → NamedValue) (α : Noise (n := n)) + {k : ℕ} (C : R.Node k) (v : M.Point J root) : + (R.upperCone F α C v).name ∈ R.nodeNames C := by + rcases minNamed_mem _ _ with h | h + · rw [upperCone, h]; exact R.nodeNames_left C 1 + · rw [upperCone, h]; exact R.nodeNames_right C 1 + +lemma lowerCone_name_mem (F : M.Point J root → NamedValue) (α : Noise (n := n)) + {k : ℕ} (C : R.Node k) (v : M.Point J root) : + (R.lowerCone F α C v).name ∈ R.nodeNames C := by + rcases maxNamed_mem _ _ with h | h + · rw [lowerCone, h]; exact R.nodeNames_left C 2 + · rw [lowerCone, h]; exact R.nodeNames_right C 2 + +lemma formula_name_origin (p : M.Point J root → ℝ) (α : Noise (n := n)) + (k : ℕ) (C : R.Node k) (v : M.Point J root) : + ∃ j : ℕ, ∃ hj : j ≤ k, + (R.formula p α k C v).name ∈ R.nodeNames (R.ancestor C j hj) := by + induction k with + | zero => + refine ⟨0, le_rfl, ?_⟩ + rw [R.ancestor_self] + exact R.tentative_name_mem p α C v + | succ k ih => + rw [formula] + rcases nodeNamed_mem _ _ _ _ with h | h | h | h + · obtain ⟨j, hj, hm⟩ := ih (R.parent C) + refine ⟨j, hj.trans (Nat.le_succ k), ?_⟩ + rw [h, ← R.ancestor_parent C hj] + exact hm + · refine ⟨k + 1, le_rfl, ?_⟩ + rw [h, R.ancestor_self] + exact R.upperCone_name_mem _ _ C v + · refine ⟨k + 1, le_rfl, ?_⟩ + rw [h, R.ancestor_self] + exact R.lowerCone_name_mem _ _ C v + · refine ⟨k + 1, le_rfl, ?_⟩ + rw [h, R.ancestor_self] + exact R.tentative_name_mem _ _ C v + +/-- The deterministic, diameter-independent list at a node. -/ +noncomputable def recentNames {k : ℕ} (C : R.Node k) (L : ℕ) : Finset ℕ := + (Finset.Icc (k - L) k).attach.biUnion + (fun j => R.nodeNames (R.ancestor C j (Finset.mem_Icc.mp j.property).2)) + +lemma recentNames_card {k : ℕ} (C : R.Node k) (L : ℕ) : + (R.recentNames C L).card ≤ 6 * (L + 1) := by + calc + (R.recentNames C L).card ≤ + ∑ j ∈ (Finset.Icc (k - L) k).attach, + (R.nodeNames (R.ancestor C j (Finset.mem_Icc.mp j.property).2)).card := + Finset.card_biUnion_le + _ ≤ ∑ _j ∈ (Finset.Icc (k - L) k).attach, 6 := + Finset.sum_le_sum (fun _ _ => R.nodeNames_card _) + _ = (k + 1 - (k - L)) * 6 := by simp + _ ≤ 6 * (L + 1) := by omega + +lemma mem_recentNames {k j : ℕ} (C : R.Node k) (L : ℕ) (hj : j ≤ k) (hl : k - L ≤ j) + {m : ℕ} (hm : m ∈ R.nodeNames (R.ancestor C j hj)) : m ∈ R.recentNames C L := by + apply Finset.mem_biUnion.mpr + exact ⟨⟨j, Finset.mem_Icc.mpr ⟨hl, hj⟩⟩, Finset.mem_attach _ _, hm⟩ + +lemma formula_name_recent {p : M.Point J root → ℝ} {α : Noise (n := n)} + (hp : R.InputLip p) (hα : R.NoiseBounds α) (k : ℕ) (C : R.Node k) (v : M.Point J root) + (hv : (k : ℝ) * R.δ ≤ dist R.base (v.withHeight R.base.height R.base.inBand)) + (ha : |(R.formula p α k C v).value - p v| ≤ 6 * R.δ) : + (R.formula p α k C v).name ∈ R.recentNames C R.lookback := by + obtain ⟨j, hj, hm⟩ := R.formula_name_origin p α k C v + have hlow := R.formula_recent_bound hp hα k C v hv ha + have hu := (R.nodeNames_bounds _ hm).2 + have hn : 0 < n := Nat.zero_lt_of_lt v.column.isLt + have hmul : 0 < 3 * n := by omega + have hjlow : k - R.lookback ≤ j := by + by_contra h + have hj' : j + 1 ≤ k - R.lookback := by omega + have hle := Nat.mul_le_mul_left (3 * n) hj' + omega + exact R.mem_recentNames C R.lookback hj hjlow hm + +/-- The source's bounded local name theorem, derived from the actual tree and +from actual metric balls. Its list is fixed before input/noise sampling. -/ +lemma local_name_list (x : M.Point J root) {ρ : ℝ} (hρ : 0 ≤ ρ) (hs : ρ ≤ R.radius) : + ∃ S : Finset ℕ, S.card ≤ 6 * (R.lookback + 1) ∧ + ∀ (p : M.Point J root → ℝ) (α : Noise (n := n)), + R.InputLip p → R.NoiseBounds α → + ∀ z : M.Point J root, dist x z ≤ ρ → (R.pasted p α z).name ∈ S := by + obtain ⟨k, C, hlo, heq⟩ := R.common_formula x hρ hs + refine ⟨R.recentNames C R.lookback, R.recentNames_card C R.lookback, ?_⟩ + intro p α hp hα z hz + rw [heq p α hα z hz] + apply R.formula_name_recent hp hα k C z (hlo z hz) + rw [← heq p α hα z hz] + exact R.pasted_accuracy hp hα z + +lemma portalAt_height {k : ℕ} (C : R.Node k) (i : Fin 2) : + (R.portalAt C i).height = R.base.height := by + dsimp only [portalAt] + split + · exact (R.portals C).left_height + · exact (R.portals C).right_height + +lemma portalAt_eq_of_column {k : ℕ} (C : R.Node k) (i i' : Fin 2) + (h : (R.portalAt C i).column = (R.portalAt C i').column) : + R.portalAt C i = R.portalAt C i' := by + have hh := (R.portalAt_height C i).trans (R.portalAt_height C i').symm + have hext : ∀ x y : M.Point J root, x.column = y.column → x.height = y.height → x = y := by + rintro ⟨xc, xh, xb, xr⟩ ⟨yc, yh, yb, yr⟩ hc hh + cases hc + cases hh + rfl + exact hext _ _ h hh + +lemma atomName_same_depth {k : ℕ} (u v : M.Point J root) (t t' : Fin 3) + (h : atomName k u t = atomName k v t') : u.column = v.column ∧ t = t' := by + have ht := t.isLt + have ht' := t'.isLt + simp only [atomName] at h + constructor <;> apply Fin.ext <;> omega + +/-- A node's parent intercept uses no noise from the current depth. The +root convention below merely fills unused clamping slots with the fixed input. -/ +noncomputable def parentValue (p : M.Point J root → ℝ) (α : Noise (n := n)) : + (k : ℕ) → R.Node k → M.Point J root → ℝ + | 0, _, v => p v + | k + 1, C, v => (R.formula p α k (R.parent C) v).value + +noncomputable def atomIntercept (p : M.Point J root → ℝ) (α : Noise (n := n)) + {k : ℕ} (C : R.Node k) (i : Fin 2) (t : Fin 3) (v : M.Point J root) : ℝ := + (if t = 0 then p (R.portalAt C i) else R.parentValue p α k C (R.portalAt C i)) + + (if t = 2 then -dist (R.portalAt C i) v else dist (R.portalAt C i) v) + +noncomputable def nodeAtom (p : M.Point J root → ℝ) (α : Noise (n := n)) + {k : ℕ} (C : R.Node k) (i : Fin 2) (t : Fin 3) (v : M.Point J root) : NamedValue := + ⟨atomName k (R.portalAt C i) t, + R.atomIntercept p α C i t v + + (if t = 1 then -α k (R.portalAt C i).column t else α k (R.portalAt C i).column t)⟩ + +lemma tentative_eq_atom (p : M.Point J root → ℝ) (α : Noise (n := n)) + {k : ℕ} (C : R.Node k) (v : M.Point J root) : + ∃ i : Fin 2, R.tentative p α C v = R.nodeAtom p α C i 0 v := by + rcases minNamed_mem _ _ with h | h + · refine ⟨0, ?_⟩ + rw [tentative, h] + simp [nodeAtom, atomIntercept, portalAt] + · refine ⟨1, ?_⟩ + rw [tentative, h] + simp [nodeAtom, atomIntercept, portalAt] + +lemma upperCone_eq_atom (p : M.Point J root → ℝ) (α : Noise (n := n)) + {k : ℕ} (C : R.Node (k + 1)) (v : M.Point J root) : + ∃ i : Fin 2, R.upperCone (R.formula p α k (R.parent C)) α C v = R.nodeAtom p α C i 1 v := by + rcases minNamed_mem _ _ with h | h + · refine ⟨0, ?_⟩ + rw [upperCone, h] + simp [nodeAtom, atomIntercept, portalAt, parentValue, sub_eq_add_neg] + · refine ⟨1, ?_⟩ + rw [upperCone, h] + simp [nodeAtom, atomIntercept, portalAt, parentValue, sub_eq_add_neg] + +lemma lowerCone_eq_atom (p : M.Point J root → ℝ) (α : Noise (n := n)) + {k : ℕ} (C : R.Node (k + 1)) (v : M.Point J root) : + ∃ i : Fin 2, R.lowerCone (R.formula p α k (R.parent C)) α C v = R.nodeAtom p α C i 2 v := by + rcases maxNamed_mem _ _ with h | h + · refine ⟨0, ?_⟩ + rw [lowerCone, h] + simp [nodeAtom, atomIntercept, portalAt, parentValue, sub_eq_add_neg] + · refine ⟨1, ?_⟩ + rw [lowerCone, h] + simp [nodeAtom, atomIntercept, portalAt, parentValue, sub_eq_add_neg] + +/-- Selection is of literal named functions, not just numerical atom names. -/ +lemma formula_eq_atom (p : M.Point J root → ℝ) (α : Noise (n := n)) + (k : ℕ) (C : R.Node k) (v : M.Point J root) : + ∃ j : ℕ, ∃ hj : j ≤ k, ∃ i : Fin 2, ∃ t : Fin 3, + R.formula p α k C v = R.nodeAtom p α (R.ancestor C j hj) i t v := by + induction k with + | zero => + obtain ⟨i, hi⟩ := R.tentative_eq_atom p α C v + exact ⟨0, le_rfl, i, 0, by simpa only [formula, R.ancestor_self] using hi⟩ + | succ k ih => + rw [formula] + rcases nodeNamed_mem _ _ _ _ with h | h | h | h + · obtain ⟨j, hj, i, t, heq⟩ := ih (R.parent C) + refine ⟨j, hj.trans (Nat.le_succ k), i, t, ?_⟩ + rw [h, ← R.ancestor_parent C hj] + exact heq + · obtain ⟨i, hi⟩ := R.upperCone_eq_atom p α C v + exact ⟨k + 1, le_rfl, i, 1, by simpa only [h, R.ancestor_self] using hi⟩ + · obtain ⟨i, hi⟩ := R.lowerCone_eq_atom p α C v + exact ⟨k + 1, le_rfl, i, 2, by simpa only [h, R.ancestor_self] using hi⟩ + · obtain ⟨i, hi⟩ := R.tentative_eq_atom p α C v + exact ⟨k + 1, le_rfl, i, 0, by simpa only [h, R.ancestor_self] using hi⟩ + +lemma formula_noise_congr (p : M.Point J root → ℝ) (α β : Noise (n := n)) + (k : ℕ) (h : ∀ j ≤ k, ∀ i t, α j i t = β j i t) + (C : R.Node k) (v : M.Point J root) : R.formula p α k C v = R.formula p β k C v := by + induction k generalizing v with + | zero => simp only [formula, tentative, h 0 le_rfl] + | succ k ih => + have he : R.formula p α k (R.parent C) = R.formula p β k (R.parent C) := + funext (fun w => ih (fun j hj => h j (hj.trans (Nat.le_succ k))) (R.parent C) w) + simp only [formula, he, upperCone, lowerCone, tentative, h (k + 1) le_rfl] + +lemma parentValue_noise_congr (p : M.Point J root → ℝ) (α β : Noise (n := n)) + (k : ℕ) (h : ∀ j < k, ∀ i t, α j i t = β j i t) + (C : R.Node k) (v : M.Point J root) : R.parentValue p α k C v = R.parentValue p β k C v := by + cases k with + | zero => rfl + | succ k => exact congrArg NamedValue.value (R.formula_noise_congr p α β k + (fun j hj => h j (Nat.lt_succ_of_le hj)) (R.parent C) v) + +lemma atomIntercept_noise_congr (p : M.Point J root → ℝ) (α β : Noise (n := n)) + (k : ℕ) (h : ∀ j < k, ∀ i t, α j i t = β j i t) + (C : R.Node k) (i : Fin 2) (t : Fin 3) (v : M.Point J root) : + R.atomIntercept p α C i t v = R.atomIntercept p β C i t v := by + simp only [atomIntercept, R.parentValue_noise_congr p α β k h] + +lemma nodeAtom_lipschitz (p : M.Point J root → ℝ) (α : Noise (n := n)) + {k : ℕ} (C : R.Node k) (i : Fin 2) (t : Fin 3) : + LipschitzWith 1 (fun v => (R.nodeAtom p α C i t v).value) := by + let c := (if t = 0 then p (R.portalAt C i) else R.parentValue p α k C (R.portalAt C i)) + + (if t = 1 then -α k (R.portalAt C i).column t else α k (R.portalAt C i).column t) + by_cases ht : t = 2 + · have he : (fun v => (R.nodeAtom p α C i t v).value) = (fun v => c - dist (R.portalAt C i) v) := by + funext v + simp only [nodeAtom, atomIntercept, ite_eq_left ht] + dsimp only [c] + ring + rw [he] + exact (distance_cone_lipschitz (R.portalAt C i) c).2 + · have he : (fun v => (R.nodeAtom p α C i t v).value) = (fun v => c + dist (R.portalAt C i) v) := by + funext v + simp only [nodeAtom, atomIntercept, ite_eq_right ht] + dsimp only [c] + ring + rw [he] + exact (distance_cone_lipschitz (R.portalAt C i) c).1 + +lemma nodeAtom_eq_of_name (p : M.Point J root → ℝ) (α : Noise (n := n)) + {k : ℕ} (C : R.Node k) (i i' : Fin 2) (t t' : Fin 3) + (h : atomName k (R.portalAt C i) t = atomName k (R.portalAt C i') t') : + R.nodeAtom p α C i t = R.nodeAtom p α C i' t' := by + obtain ⟨hc, rfl⟩ := atomName_same_depth _ _ _ _ h + have he := R.portalAt_eq_of_column C i i' hc + funext v + simp only [nodeAtom, atomIntercept, he] + +/-- Explicit positions in the ancestor chain. The name, not this occurrence, +is the randomized identity; opposite portal occurrences may coincide. -/ +abbrev ChainIndex (k : ℕ) := Fin (k + 1) × Fin 2 × Fin 3 + +noncomputable def chainName {k : ℕ} (C : R.Node k) (u : ChainIndex k) : ℕ := + atomName u.1 (R.portalAt (R.ancestor C u.1 (Nat.le_of_lt_succ u.1.isLt)) u.2.1) u.2.2 + +noncomputable def chainAtom (p : M.Point J root → ℝ) (α : Noise (n := n)) + {k : ℕ} (C : R.Node k) (u : ChainIndex k) : M.Point J root → NamedValue := + R.nodeAtom p α (R.ancestor C u.1 (Nat.le_of_lt_succ u.1.isLt)) u.2.1 u.2.2 + +lemma chainName_bounds {k : ℕ} (C : R.Node k) (u : ChainIndex k) : + 3 * n * u.1.val ≤ R.chainName C u ∧ R.chainName C u < 3 * n * (u.1.val + 1) := + atomName_bounds _ _ _ + +lemma chainAtom_eq_of_name (p : M.Point J root → ℝ) (α : Noise (n := n)) + {k : ℕ} (C : R.Node k) (u u' : ChainIndex k) (h : R.chainName C u = R.chainName C u') : + R.chainAtom p α C u = R.chainAtom p α C u' := by + have h₁ := R.chainName_bounds C u + have h₂ := R.chainName_bounds C u' + have hd : u.1.val = u'.1.val := by + rcases lt_trichotomy u.1.val u'.1.val with hl | he | hr + · have hb := Nat.mul_le_mul_left (3 * n) (Nat.succ_le_of_lt hl) + simp only [Nat.succ_eq_add_one] at hb + omega + · exact he + · have hb := Nat.mul_le_mul_left (3 * n) (Nat.succ_le_of_lt hr) + simp only [Nat.succ_eq_add_one] at hb + omega + rcases u with ⟨j, i, t⟩ + rcases u' with ⟨j', i', t'⟩ + have hj : j = j' := Fin.ext hd + subst j' + exact R.nodeAtom_eq_of_name p α _ i i' t t' h + +lemma recentNames_representation {k : ℕ} (C : R.Node k) (L m : ℕ) + (hm : m ∈ R.recentNames C L) : ∃ u : ChainIndex k, R.chainName C u = m := by + obtain ⟨j, _, hj⟩ := Finset.mem_biUnion.mp hm + obtain ⟨⟨i,t⟩, _, he⟩ := Finset.mem_image.mp hj + exact ⟨(⟨j.val, Nat.lt_succ_of_le (Finset.mem_Icc.mp j.property).2⟩, i, t), he⟩ + +noncomputable def representative {k : ℕ} (C : R.Node k) (L m : ℕ) + (hm : m ∈ R.recentNames C L) : ChainIndex k := + (R.recentNames_representation C L m hm).choose + +lemma representative_name {k : ℕ} (C : R.Node k) (L m : ℕ) + (hm : m ∈ R.recentNames C L) : R.chainName C (R.representative C L m hm) = m := + (R.recentNames_representation C L m hm).choose_spec + +/-- A fixed representation for each name, chosen from geometry before noises. +Off the list the harmless zero branch makes this a total function. -/ +noncomputable def listedAtom (p : M.Point J root → ℝ) (α : Noise (n := n)) + {k : ℕ} (C : R.Node k) (L m : ℕ) (v : M.Point J root) : NamedValue := + if hm : m ∈ R.recentNames C L then R.chainAtom p α C (R.representative C L m hm) v + else ⟨m, 0⟩ + +lemma listedAtom_name (p : M.Point J root → ℝ) (α : Noise (n := n)) + {k : ℕ} (C : R.Node k) (L m : ℕ) (v : M.Point J root) : + (R.listedAtom p α C L m v).name = m := by + unfold listedAtom + split_ifs with hm + · exact R.representative_name C L m hm + · rfl + +lemma listedAtom_lipschitz (p : M.Point J root → ℝ) (α : Noise (n := n)) + {k : ℕ} (C : R.Node k) (L m : ℕ) : + LipschitzWith 1 (fun v => (R.listedAtom p α C L m v).value) := by + unfold listedAtom + split_ifs with hm + · exact R.nodeAtom_lipschitz p α _ _ _ + · exact (LipschitzWith.const (0 : ℝ)).weaken (by simp) + +lemma formula_eq_listed {p : M.Point J root → ℝ} {α : Noise (n := n)} + (hp : R.InputLip p) (hα : R.NoiseBounds α) (k : ℕ) (C : R.Node k) (v : M.Point J root) + (hv : (k : ℝ) * R.δ ≤ dist R.base (v.withHeight R.base.height R.base.inBand)) + (ha : |(R.formula p α k C v).value - p v| ≤ 6 * R.δ) : + R.formula p α k C v = R.listedAtom p α C R.lookback (R.formula p α k C v).name v := by + have hm := R.formula_name_recent hp hα k C v hv ha + obtain ⟨j, hj, i, t, he⟩ := R.formula_eq_atom p α k C v + rw [listedAtom, dite_eq_left hm] + let u : ChainIndex k := (⟨j, Nat.lt_succ_of_le hj⟩, i, t) + have hu : R.chainName C u = (R.formula p α k C v).name := (congrArg NamedValue.name he).symm + have hn := R.representative_name C R.lookback (R.formula p α k C v).name hm + have heq := congrFun (R.chainAtom_eq_of_name p α C u _ (hu.trans hn.symm)) v + exact he.trans heq + +/-- The complete local list, including the actual named Lipschitz functions. +At most six atoms per recent ancestor survive. -/ +lemma local_atom_list (x : M.Point J root) {ρ : ℝ} (hρ : 0 ≤ ρ) (hs : ρ ≤ R.radius) : + ∃ k : ℕ, ∃ C : R.Node k, + ∀ (p : M.Point J root → ℝ) (α : Noise (n := n)), + R.InputLip p → R.NoiseBounds α → ∀ z : M.Point J root, dist x z ≤ ρ → + (R.pasted p α z).name ∈ R.recentNames C R.lookback ∧ + R.pasted p α z = R.listedAtom p α C R.lookback (R.pasted p α z).name z := by + obtain ⟨k, C, hlo, heq⟩ := R.common_formula x hρ hs + refine ⟨k, C, ?_⟩ + intro p α hp hα z hz + have ha : |(R.formula p α k C z).value - p z| ≤ 6 * R.δ := by + rw [← heq p α hα z hz] + exact R.pasted_accuracy hp hα z + rw [heq p α hα z hz] + exact ⟨R.formula_name_recent hp hα k C z (hlo z hz) ha, + R.formula_eq_listed hp hα k C z (hlo z hz) ha⟩ + +/-- Off the finite near-tie event the selected name is constant. Direct +Lipschitz comparison proves this on the entire ball without a topological +selection argument, and also covers zero-distance representatives. -/ +lemma stable_names_of_no_tie (x : M.Point J root) {ρ : ℝ} (hρ : 0 ≤ ρ) + {k : ℕ} (C : R.Node k) (p : M.Point J root → ℝ) (α : Noise (n := n)) + (hα : R.NoiseBounds α) + (hlist : ∀ z : M.Point J root, dist x z ≤ ρ → + (R.pasted p α z).name ∈ R.recentNames C R.lookback ∧ + R.pasted p α z = R.listedAtom p α C R.lookback (R.pasted p α z).name z) + (hgap : ∀ m ∈ R.recentNames C R.lookback, ∀ m' ∈ R.recentNames C R.lookback, m ≠ m' → + 2 * ρ < |(R.listedAtom p α C R.lookback m x).value - + (R.listedAtom p α C R.lookback m' x).value|) : + ∀ z : M.Point J root, dist x z ≤ ρ → (R.pasted p α z).name = (R.pasted p α x).name := by + intro z hz + have hx := hlist x (by simpa using hρ) + have hz' := hlist z hz + by_contra hn + have hg := hgap (R.pasted p α x).name hx.1 (R.pasted p α z).name hz'.1 (Ne.symm hn) + have hl₁ := (R.pasted_lipschitz p hα).dist_le_mul x z + have hl₂ := (R.listedAtom_lipschitz p α C R.lookback (R.pasted p α z).name).dist_le_mul z x + simp only [Real.dist_eq, NNReal.coe_one, one_mul] at hl₁ hl₂ + rw [dist_comm z x] at hl₂ + have he₁ := congrArg NamedValue.value hx.2 + have he₂ := congrArg NamedValue.value hz'.2 + have ht := abs_sub_le (R.pasted p α x).value (R.pasted p α z).value + (R.listedAtom p α C R.lookback (R.pasted p α z).name x).value + rw [← he₂] at hl₂ + rw [← he₁] at hg + linarith + +/-- Replacement of exactly one current interpolation noise. -/ +noncomputable def replaceNoise (α : Noise (n := n)) (d : ℕ) (c : Fin n) (t : Fin 3) (r : ℝ) : + Noise (n := n) := fun j i s => if j = d ∧ i = c ∧ s = t then r else α j i s + +lemma replaceNoise_self (α : Noise (n := n)) (d : ℕ) (c : Fin n) (t : Fin 3) (r : ℝ) : + replaceNoise α d c t r d c t = r := by simp [replaceNoise] + +lemma replaceNoise_other (α : Noise (n := n)) (d j : ℕ) (c i : Fin n) (t s : Fin 3) (r : ℝ) + (h : ¬ (j = d ∧ i = c ∧ s = t)) : replaceNoise α d c t r j i s = α j i s := by + simp only [replaceNoise, ite_eq_right h] + +lemma atomIntercept_replace (p : M.Point J root → ℝ) (α : Noise (n := n)) + {k d : ℕ} (C : R.Node k) (i : Fin 2) (t : Fin 3) (v : M.Point J root) + (hd : k ≤ d) (c : Fin n) (s : Fin 3) (r : ℝ) : + R.atomIntercept p (replaceNoise α d c s r) C i t v = R.atomIntercept p α C i t v := by + apply R.atomIntercept_noise_congr + intro j hj u w + exact replaceNoise_other α d j c u s w r (by omega) + +lemma nodeAtom_replace_self (p : M.Point J root → ℝ) (α : Noise (n := n)) + {k : ℕ} (C : R.Node k) (i : Fin 2) (t : Fin 3) (v : M.Point J root) (r : ℝ) : + (R.nodeAtom p (replaceNoise α k (R.portalAt C i).column t r) C i t v).value = + R.atomIntercept p α C i t v + (if t = 1 then -r else r) := by + simp only [nodeAtom, R.atomIntercept_replace p α C i t v le_rfl, + replaceNoise_self] + +lemma nodeAtom_replace_other (p : M.Point J root → ℝ) (α : Noise (n := n)) + {k d : ℕ} (C : R.Node k) (i : Fin 2) (t : Fin 3) (v : M.Point J root) + (hd : k ≤ d) (c : Fin n) (s : Fin 3) (r : ℝ) + (h : ¬ (k = d ∧ (R.portalAt C i).column = c ∧ t = s)) : + R.nodeAtom p (replaceNoise α d c s r) C i t v = R.nodeAtom p α C i t v := by + simp only [nodeAtom, R.atomIntercept_replace p α C i t v hd, + replaceNoise_other α d k c (R.portalAt C i).column s t r h] + +/-- Every distinct pair on the ancestor chain has a fresh coordinate: after +all other noises are fixed, their difference is affine with slope ±1 in it. -/ +lemma chainPair_fresh (p : M.Point J root → ℝ) {k : ℕ} (C : R.Node k) + (u u' : ChainIndex k) (hne : R.chainName C u ≠ R.chainName C u') (v : M.Point J root) : + ∃ d ≤ k, ∃ c : Fin n, ∃ s : Fin 3, + ∀ α : Noise (n := n), ∃ b : ℝ, + (∀ r : ℝ, (R.chainAtom p (replaceNoise α d c s r) C u v).value - + (R.chainAtom p (replaceNoise α d c s r) C u' v).value = b + r) ∨ + (∀ r : ℝ, (R.chainAtom p (replaceNoise α d c s r) C u v).value - + (R.chainAtom p (replaceNoise α d c s r) C u' v).value = b - r) := by + let D := R.ancestor C u.1 (Nat.le_of_lt_succ u.1.isLt) + let D' := R.ancestor C u'.1 (Nat.le_of_lt_succ u'.1.isLt) + have hcoord : ¬ (u.1.val = u'.1.val ∧ + (R.portalAt D u.2.1).column = (R.portalAt D' u'.2.1).column ∧ u.2.2 = u'.2.2) := by + rintro ⟨hd, hc, ht⟩ + apply hne + simp only [chainName, atomName] + change 3 * (n * u.1.val + (R.portalAt D u.2.1).column.val) + u.2.2.val = + 3 * (n * u'.1.val + (R.portalAt D' u'.2.1).column.val) + u'.2.2.val + simp only [hd, hc, ht] + by_cases hd : u.1.val ≤ u'.1.val + · refine ⟨u'.1, Nat.le_of_lt_succ u'.1.isLt, (R.portalAt D' u'.2.1).column, u'.2.2, ?_⟩ + intro α + refine ⟨(R.chainAtom p α C u v).value - R.atomIntercept p α D' u'.2.1 u'.2.2 v, ?_⟩ + by_cases hs : u'.2.2 = 1 + · left + intro r + dsimp only [chainAtom] + rw [R.nodeAtom_replace_other p α D _ _ v hd _ _ r hcoord, + R.nodeAtom_replace_self p α D' _ _ v r, ite_eq_left hs] + ring + · right + intro r + dsimp only [chainAtom] + rw [R.nodeAtom_replace_other p α D _ _ v hd _ _ r hcoord, + R.nodeAtom_replace_self p α D' _ _ v r, ite_eq_right hs] + ring + · have hd' : u'.1.val ≤ u.1.val := by omega + have hcoord' : ¬ (u'.1.val = u.1.val ∧ + (R.portalAt D' u'.2.1).column = (R.portalAt D u.2.1).column ∧ u'.2.2 = u.2.2) := by + rintro ⟨he, hc, ht⟩ + exact hcoord ⟨he.symm, hc.symm, ht.symm⟩ + refine ⟨u.1, Nat.le_of_lt_succ u.1.isLt, (R.portalAt D u.2.1).column, u.2.2, ?_⟩ + intro α + refine ⟨R.atomIntercept p α D u.2.1 u.2.2 v - (R.chainAtom p α C u' v).value, ?_⟩ + by_cases hs : u.2.2 = 1 + · right + intro r + dsimp only [chainAtom] + rw [R.nodeAtom_replace_other p α D' _ _ v hd' _ _ r hcoord', + R.nodeAtom_replace_self p α D _ _ v r, ite_eq_left hs] + ring + · left + intro r + dsimp only [chainAtom] + rw [R.nodeAtom_replace_other p α D' _ _ v hd' _ _ r hcoord', + R.nodeAtom_replace_self p α D _ _ v r, ite_eq_right hs] + ring + +/-- The finite noise sample space used by the construction. -/ +abbrev GridSample (cap m : ℕ) := (Fin cap × Fin n × Fin 3) → Fin (m + 1) + +noncomputable def gridNoise (cap m : ℕ) (ω : GridSample (n := n) cap m) : Noise (n := n) := + fun j i t => if hj : j < cap then R.q + R.q / m * (ω (⟨j,hj⟩,i,t)).val else R.q + +lemma gridNoise_bounds (cap m : ℕ) (hm : 0 < m) (ω : GridSample (n := n) cap m) : + R.NoiseBounds (R.gridNoise cap m ω) := by + intro j i t + have hm' : (0 : ℝ) < m := by exact_mod_cast hm + have hstep : 0 < R.q / m := div_pos R.q_pos hm' + have hmul : R.q / (m : ℝ) * m = R.q := div_mul_cancel₀ R.q (ne_of_gt hm') + simp only [gridNoise] + split_ifs with hj + · have hval : ((ω (⟨j,hj⟩,i,t)).val : ℝ) ≤ m := by + exact_mod_cast Nat.le_of_lt_succ (ω (⟨j,hj⟩,i,t)).isLt + have hhi := mul_le_mul_of_nonneg_left hval hstep.le + rw [hmul] at hhi + have hlo := mul_nonneg hstep.le (Nat.cast_nonneg (ω (⟨j,hj⟩,i,t)).val) + constructor <;> linarith + · constructor <;> linarith [R.q_pos] + +lemma gridNoise_update (cap m : ℕ) (ω : GridSample (n := n) cap m) + (d : ℕ) (hd : d < cap) (c : Fin n) (s : Fin 3) (r : Fin (m + 1)) : + R.gridNoise cap m (Function.update ω (⟨d,hd⟩,c,s) r) = + replaceNoise (R.gridNoise cap m ω) d c s (R.q + R.q / m * r.val) := by + funext j i t + by_cases hj : j < cap + · by_cases he : (⟨j,hj⟩,i,t) = ((⟨d,hd⟩ : Fin cap),c,s) + · have hparts := Prod.mk.inj he + have hjd : j = d := congrArg Fin.val hparts.1 + obtain ⟨hic, hts⟩ := Prod.mk.inj hparts.2 + subst j + subst i + subst t + simp only [gridNoise, dite_eq_left hd, Function.update_self, replaceNoise_self] + · have hne : ¬ (j = d ∧ i = c ∧ t = s) := by + rintro ⟨hjd, hic, hts⟩ + exact he (by subst j; subst i; subst t; rfl) + rw [replaceNoise_other _ d j c i s t _ hne] + simp only [gridNoise, dite_eq_left hj, Function.update_of_ne he] + · have hne : ¬ (j = d ∧ i = c ∧ t = s) := fun h => hj (h.1 ▸ hd) + rw [replaceNoise_other _ d j c i s t _ hne] + simp only [gridNoise, dite_eq_right hj] + +/-- The radial profile has only finitely many values, one per reachable column. +This explicit cap bounds every node ever used by the pasted field. -/ +noncomputable def depthCap : ℕ := by + classical + exact 1 + ∑ i : Fin n, + if hi : (M.activeGraph J).Reachable root i then + ⌊dist R.base (⟨i, R.base.height, R.base.inBand, hi⟩ : M.Point J root) / R.δ⌋₊ else 0 + +lemma layerDepth_lt_cap (v : M.Point J root) : R.layerDepth v < R.depthCap := by + classical + let g : Fin n → ℕ := fun i => if hi : (M.activeGraph J).Reachable root i then + ⌊dist R.base (⟨i, R.base.height, R.base.inBand, hi⟩ : M.Point J root) / R.δ⌋₊ else 0 + have hsum := Finset.single_le_sum (s := Finset.univ) (f := g) (fun i _ => Nat.zero_le (g i)) + (Finset.mem_univ v.column) + have he : R.layerDepth v = g v.column := by + simp only [g, dite_eq_left v.reachable, layerDepth, withHeight] + dsimp only [depthCap] + change R.layerDepth v < 1 + ∑ i, g i + omega + +lemma depth_le_layerDepth {k : ℕ} (v : M.Point J root) + (hk : (k : ℝ) * R.δ ≤ dist R.base (v.withHeight R.base.height R.base.inBand)) : + k ≤ R.layerDepth v := by + apply Nat.le_floor + exact (le_div_iff₀ R.delta_pos).mpr hk + + +lemma chainPair_probability (p : M.Point J root → ℝ) {k : ℕ} (C : R.Node k) + (u u' : ChainIndex k) (hne : R.chainName C u ≠ R.chainName C u') + (v : M.Point J root) (cap m : ℕ) (hk : k < cap) (hm : 0 < m) + {t : ℝ} (ht : 0 ≤ t) : + FiniteRandom.prob (fun ω : GridSample (n := n) cap m => + |(R.chainAtom p (R.gridNoise cap m ω) C u v).value - + (R.chainAtom p (R.gridNoise cap m ω) C u' v).value| ≤ t) ≤ + (2 * t + R.q / m) / R.q := by + classical + obtain ⟨d, hd, c, s, hf⟩ := R.chainPair_fresh p C u u' hne v + have hdc : d < cap := hd.trans_lt hk + apply FiniteRandom.coordinate_probability (⟨d,hdc⟩,c,s) m hm R.q_pos ht + intro ω + obtain ⟨b, hb⟩ := hf (R.gridNoise cap m ω) + rcases hb with hb | hb + · refine ⟨b + R.q, Or.inl ?_⟩ + intro r + rw [R.gridNoise_update cap m ω d hdc c s r, hb] + ring + · refine ⟨b - R.q, Or.inr ?_⟩ + intro r + rw [R.gridNoise_update cap m ω d hdc c s r, hb] + ring + +lemma listedPair_probability (p : M.Point J root → ℝ) {k : ℕ} (C : R.Node k) + (L i j : ℕ) (hi : i ∈ R.recentNames C L) (hj : j ∈ R.recentNames C L) (hne : i ≠ j) + (v : M.Point J root) (cap m : ℕ) (hk : k < cap) (hm : 0 < m) + {t : ℝ} (ht : 0 ≤ t) : + FiniteRandom.prob (fun ω : GridSample (n := n) cap m => + |(R.listedAtom p (R.gridNoise cap m ω) C L i v).value - + (R.listedAtom p (R.gridNoise cap m ω) C L j v).value| ≤ t) ≤ + (2 * t + R.q / m) / R.q := by + have hn : R.chainName C (R.representative C L i hi) ≠ + R.chainName C (R.representative C L j hj) := by + simpa only [R.representative_name] using hne + simpa only [listedAtom, dite_eq_left hi, dite_eq_left hj] using + R.chainPair_probability p C _ _ hn v cap m hk hm ht + +/-- Actual finite-grid anti-concentration for a changed interpolation atom name +anywhere on the closed ball. Its list and depth cap were constructed strictly +from the geometry before sampling the fresh independent coordinates. -/ +lemma local_name_probability (p : M.Point J root → ℝ) (hp : R.InputLip p) + (x : M.Point J root) {ρ : ℝ} (hρ : 0 ≤ ρ) (hs : ρ ≤ R.radius) + (m : ℕ) (hm : 0 < m) : + FiniteRandom.prob (fun ω : GridSample (n := n) R.depthCap m => + ∃ z : M.Point J root, dist x z ≤ ρ ∧ + (R.pasted p (R.gridNoise R.depthCap m ω) z).name ≠ + (R.pasted p (R.gridNoise R.depthCap m ω) x).name) ≤ + (6 * (R.lookback + 1) : ℕ)^2 * ((4 * ρ + R.q / m) / R.q) := by + classical + obtain ⟨k, C, hlo, heq⟩ := R.common_formula x hρ hs + have hk : k < R.depthCap := + (R.depth_le_layerDepth x (hlo x (by simpa using hρ))).trans_lt (R.layerDepth_lt_cap x) + have hlist (ω : GridSample (n := n) R.depthCap m) (z : M.Point J root) (hz : dist x z ≤ ρ) : + (R.pasted p (R.gridNoise R.depthCap m ω) z).name ∈ R.recentNames C R.lookback ∧ + R.pasted p (R.gridNoise R.depthCap m ω) z = + R.listedAtom p (R.gridNoise R.depthCap m ω) C R.lookback + (R.pasted p (R.gridNoise R.depthCap m ω) z).name z := by + have hα := R.gridNoise_bounds R.depthCap m hm ω + have ha : |(R.formula p (R.gridNoise R.depthCap m ω) k C z).value - p z| ≤ 6 * R.δ := by + rw [← heq p _ hα z hz] + exact R.pasted_accuracy hp hα z + rw [heq p _ hα z hz] + exact ⟨R.formula_name_recent hp hα k C z (hlo z hz) ha, + R.formula_eq_listed hp hα k C z (hlo z hz) ha⟩ + have hsub : ∀ ω : GridSample (n := n) R.depthCap m, + (∃ z : M.Point J root, dist x z ≤ ρ ∧ + (R.pasted p (R.gridNoise R.depthCap m ω) z).name ≠ + (R.pasted p (R.gridNoise R.depthCap m ω) x).name) → + ∃ i ∈ R.recentNames C R.lookback, ∃ j ∈ R.recentNames C R.lookback, + i ≠ j ∧ |(R.listedAtom p (R.gridNoise R.depthCap m ω) C R.lookback i x).value - + (R.listedAtom p (R.gridNoise R.depthCap m ω) C R.lookback j x).value| ≤ 2 * ρ := by + intro ω hbad + by_contra hn + have hgap : ∀ i ∈ R.recentNames C R.lookback, ∀ j ∈ R.recentNames C R.lookback, i ≠ j → + 2 * ρ < |(R.listedAtom p (R.gridNoise R.depthCap m ω) C R.lookback i x).value - + (R.listedAtom p (R.gridNoise R.depthCap m ω) C R.lookback j x).value| := by + intro i hi j hj hij + exact lt_of_not_ge (fun ht => hn ⟨i,hi,j,hj,hij,ht⟩) + obtain ⟨z, hz, hne⟩ := hbad + exact hne (R.stable_names_of_no_tie x hρ C p _ (R.gridNoise_bounds _ _ hm ω) + (hlist ω) hgap z hz) + have hb : 0 ≤ (4 * ρ + R.q / m) / R.q := by + have hq := R.q_pos + positivity + have hprob := FiniteRandom.prob_pair_bound (R.recentNames C R.lookback) + (fun i j (ω : GridSample (n := n) R.depthCap m) => + |(R.listedAtom p (R.gridNoise R.depthCap m ω) C R.lookback i x).value - + (R.listedAtom p (R.gridNoise R.depthCap m ω) C R.lookback j x).value| ≤ 2 * ρ) hb + (fun i hi j hj hij => by + simpa only [show 2 * (2 * ρ) = 4 * ρ by ring] using + R.listedPair_probability p C R.lookback i j hi hj hij x R.depthCap m hk hm + (t := 2 * ρ) (by positivity)) + refine (FiniteRandom.prob_mono hsub).trans (hprob.trans ?_) + apply mul_le_mul_of_nonneg_right _ hb + exact pow_le_pow_left₀ (Nat.cast_nonneg _) (by exact_mod_cast R.recentNames_card C R.lookback) _ + +end RadialTree + + +end Point + +end Model +end Columns +end PlanarL1 + +end + +section + +namespace PlanarL1.Columns.Model.Point.RadialTree +open PlanarL1.Interpolation +variable {n : ℕ} {M : Model n} {J : Set ℝ} {root : Fin n} +variable (R : RadialTree (M := M) (J := J) (root := root)) + +/-- Comparison with a fixed old field uses the current atom's own offset, not +an unjustified independence assertion about its inherited intercept. -/ +lemma chainConstant_probability (p : M.Point J root → ℝ) {k : ℕ} + (C : R.Node k) (u : ChainIndex k) (v : M.Point J root) (c : ℝ) + (cap m : ℕ) (hk : k < cap) (hm : 0 < m) {t : ℝ} (ht : 0 ≤ t) : + FiniteRandom.prob (fun ω : GridSample (n := n) cap m => + |(R.chainAtom p (R.gridNoise cap m ω) C u v).value-c| ≤ t) ≤ + (2*t+R.q/m)/R.q := by + let D := R.ancestor C u.1 (Nat.le_of_lt_succ u.1.isLt) + have hd : u.1.val < cap := (Nat.le_of_lt_succ u.1.isLt).trans_lt hk + apply FiniteRandom.coordinate_probability + (⟨u.1,hd⟩,(R.portalAt D u.2.1).column,u.2.2) m hm R.q_pos ht + intro ω + by_cases hs : u.2.2 = 1 + · refine ⟨R.atomIntercept p (R.gridNoise cap m ω) D u.2.1 u.2.2 v-c-R.q,Or.inr ?_⟩ + intro r + rw [R.gridNoise_update cap m ω u.1 hd (R.portalAt D u.2.1).column u.2.2 r] + dsimp only [chainAtom] + rw [R.nodeAtom_replace_self p _ D _ _ v _,ite_eq_left hs] + ring + · refine ⟨R.atomIntercept p (R.gridNoise cap m ω) D u.2.1 u.2.2 v-c+R.q,Or.inl ?_⟩ + intro r + rw [R.gridNoise_update cap m ω u.1 hd (R.portalAt D u.2.1).column u.2.2 r] + dsimp only [chainAtom] + rw [R.nodeAtom_replace_self p _ D _ _ v _,ite_eq_right hs] + ring + +lemma listedConstant_probability (p : M.Point J root → ℝ) {k : ℕ} + (C : R.Node k) (L i : ℕ) (hi : i ∈ R.recentNames C L) + (v : M.Point J root) (c : ℝ) (cap m : ℕ) (hk : k < cap) (hm : 0 < m) + {t : ℝ} (ht : 0 ≤ t) : + FiniteRandom.prob (fun ω : GridSample (n := n) cap m => + |(R.listedAtom p (R.gridNoise cap m ω) C L i v).value-c| ≤ t) ≤ + (2*t+R.q/m)/R.q := by + simpa only [listedAtom,dite_eq_left hi] using + R.chainConstant_probability p C (R.representative C L i hi) v c cap m hk hm ht + +/-- Between independent interpolations, conditioning on the other full sample +still leaves the chosen atom's fresh coordinate available. -/ +lemma listedIndependent_probability {Ω : Type*} [Fintype Ω] [Nonempty Ω] + (p : M.Point J root → ℝ) {k : ℕ} (C : R.Node k) (L i : ℕ) + (hi : i ∈ R.recentNames C L) (v : M.Point J root) (other : Ω → ℝ) + (cap m : ℕ) (hk : k < cap) (hm : 0 < m) {t : ℝ} (ht : 0 ≤ t) : + FiniteRandom.prob (fun ω : GridSample (n := n) cap m × Ω => + |(R.listedAtom p (R.gridNoise cap m ω.1) C L i v).value-other ω.2| ≤ t) ≤ + (2*t+R.q/m)/R.q := by + apply FiniteRandom.prob_prod_bound_left + intro z + exact R.listedConstant_probability p C L i hi v (other z) cap m hk hm ht + +end PlanarL1.Columns.Model.Point.RadialTree + + + + +end + +end OAI diff --git a/lean/OAI/Combinatorics/PlanarL1/Retubing.lean b/lean/OAI/Combinatorics/PlanarL1/Retubing.lean new file mode 100644 index 0000000000000000000000000000000000000000..8050194e0fc0626a07c5fcda082dfc3480e8e8f9 --- /dev/null +++ b/lean/OAI/Combinatorics/PlanarL1/Retubing.lean @@ -0,0 +1,672 @@ +import OAI.Combinatorics.PlanarL1.Surgery + +namespace OAI + +section + + + +namespace PlanarL1.Topology +open Set Metric Filter + +lemma frontier_outward_segment {S : Set ℂ} (hS : Convex ℝ S) + (h0 : S∈nhds (0:ℂ)) {p : ℂ} (hp : p∈frontier S) {b : ℝ} (hb : 1≤b) + {z : ℂ} (hz : z∈segment ℝ p (b•p)) (hzS : z∈closure S) : z=p := by + rw [segment_eq_image' ℝ] at hz + obtain ⟨u,hu,rfl⟩ := hz + have he : p+u•(b•p-p)=(1+u*(b-1))•p := by module + dsimp only at hzS ⊢ + rw [he] at hzS ⊢ + have ht : 1≤1+u*(b-1) := by nlinarith [mul_nonneg hu.1 (sub_nonneg.mpr hb)] + have hg := (gauge_le_one_iff_mem_closure hS h0).mpr hzS + rw [gauge_smul_of_nonneg (by linarith : 0≤1+u*(b-1)), + (gauge_eq_one_iff_mem_frontier hS h0).mpr hp,smul_eq_mul,mul_one] at hg + rw [le_antisymm hg ht,one_smul] + +lemma scalar_segment (p : ℂ) {a b : ℝ} (hab : a≤b) {z : ℂ} + (hz : z∈segment ℝ (a•p) (b•p)) : + ∃ u∈Icc a b, z=u•p := by + rw [segment_eq_image' ℝ] at hz + obtain ⟨t,ht,rfl⟩ := hz + refine ⟨a+t*(b-a),⟨by nlinarith [mul_nonneg ht.1 (sub_nonneg.mpr hab)], + by nlinarith [mul_nonneg (sub_nonneg.mpr ht.2) (sub_nonneg.mpr hab)]⟩,?_⟩ + module + +lemma radial_outer_tail {S : Set ℂ} {p : ℂ} {t : ℝ} (ht : t≤1) + (hout : ∀ s : ℝ, t hout s h (he ▸ hzS))) hs.1 + simpa only [hst] using he + +namespace PLDrawing +variable {V : Type} [LinearOrder V] {G : SimpleGraph V} (P : PLDrawing G) + +noncomputable def retubePoint (B : Set V) (c : ℝ) (t : V → ℝ) (v : V) (q : ℂ) (w : V) : ℂ := + by classical exact if w=v then q else P.radialPoint B c t w + +def retubeRegion (B : Set V) (c : ℝ) (t : V → ℝ) (v : V) (q : ℂ) (d : ForwardDart G) : Set ℂ := + P.radialRegion B c t d ∪ {z | Incident d v ∧ z∈segment ℝ (P.point v) q} + +/-- Compress a genuine finite drawing into a new convex tube and extend one +leaf along a segment external to the old disk. Every other exposed leaf is +cut exactly at the new frontier. The exterior residual tails meet the new +closed disk only at their new ports. -/ +lemma retube_extend {S T : Set ℂ} {B : Set V} {v : V} {q : ℂ} + (hS : Convex ℝ S) (hS0 : S∈nhds (0:ℂ)) (hSb : Bornology.IsBounded S) + (hpoint : ∀ w, P.point w∈closure S) + (htrace : ∀ d, (P.chain d).trace ⊆ closure S) + (hport : ∀ w∈B, P.point w∈frontier S) + (hleaf : ∀ w∈B, ∀ a b, G.Adj w a → G.Adj w b → a=b) + (hv : v∈B) (hT : Convex ℝ T) (hTop : IsOpen T) (hT0 : (0:ℂ)∈T) + (hTv : P.point v∈T) (hqT : q∈closure T) + (hout : ∀ w∈B, w≠v → P.point w∉closure T) + (hext : ∀ z, z∈segment ℝ (P.point v) q → z∈closure S → z=P.point v) : + ∃ (c : ℝ) (t : V → ℝ) (Q : PLDrawing G), 0 h)) + have hpQ : Q.point=P.retubePoint B c t v q := by + rw [hQp]; funext w + simp only [movedPoint,retubePoint,hRpoint] + have hregQ (d : ForwardDart G) : (Q.chain d).trace ⊆ P.retubeRegion B c t v q d := by + intro z hz + rcases hQ d hz with hz|hz + · exact Or.inl (hR d hz) + · exact Or.inr hz + have hregT (d : ForwardDart G) : P.radialRegion B c t d ⊆ closure T := by + apply P.radialRegion_subset_convex hT.closure + · intro e z hz + exact subset_closure (hcore (Set.image_mono (htrace e) hz)) + · intro w hw + by_cases he : w=v + · subst w; simpa only [htv,one_smul] using subset_closure hTv + · exact frontier_subset_closure (hfront w hw he) + refine ⟨c,t,Q,hc,hc1,htv,ht,hpQ,hregQ,?_,?_,?_,?_⟩ + · intro d z hz + rcases hregQ d hz with hz|hz + · exact hregT d hz + · exact hT.closure.segment_subset (subset_closure hTv) hqT hz.2 + · intro w + rw [congrFun hpQ w] + simp only [retubePoint,radialPoint] + split_ifs with he hw + · exact hqT + · exact frontier_subset_closure (hfront w hw he) + · exact subset_closure (hcore ⟨P.point w,hpoint w,rfl⟩) + · intro w hw he + rw [congrFun hpQ w] + simpa only [retubePoint,ite_eq_right he,radialPoint,ite_eq_left hw] using hfront w hw he + · intro w hw he z hz hzT + have hpw : Q.point w=t w•P.point w := by + rw [congrFun hpQ w]; simp only [retubePoint,ite_eq_right he,radialPoint,ite_eq_left hw] + rw [hpw] at hz ⊢ + exact radial_outer_tail (ht w hw).2 (htail w hw he) hz hzT + +end PLDrawing +end PlanarL1.Topology + + + + +namespace PlanarL1.Topology +open Set Metric Filter + +namespace PLDrawing +variable {V : Type} [LinearOrder V] {G : SimpleGraph V} (P : PLDrawing G) + +lemma radialRegion_old {S : Set ℂ} {B : Set V} {c : ℝ} {t : V → ℝ} + (hS : Convex ℝ S) (h0 : S∈nhds (0:ℂ)) (hc : 0≤c) (hc1 : c≤1) + (hpoint : ∀ w, P.point w∈closure S) + (htrace : ∀ d, (P.chain d).trace ⊆ closure S) + (ht : ∀ w∈B, 0≤t w ∧ t w≤1) (d : ForwardDart G) : + P.radialRegion B c t d ⊆ closure S := by + apply P.radialRegion_subset_convex hS.closure + · intro e z hz + obtain ⟨z,hz,rfl⟩ := hz + have : c•z∈segment ℝ 0 z := by + rw [segment_eq_image' ℝ]; exact ⟨c,⟨hc,hc1⟩,by simp⟩ + exact hS.closure.segment_subset (subset_closure (mem_of_mem_nhds h0)) (htrace e hz) this + · intro w hw + have : t w•P.point w∈segment ℝ 0 (P.point w) := by + rw [segment_eq_image' ℝ]; exact ⟨t w,ht w hw,by simp⟩ + exact hS.closure.segment_subset (subset_closure (mem_of_mem_nhds h0)) (hpoint w) this + +/-- The exact geometric output needed when retubing a tree with exterior stems. +The old disk may be discarded, but no new curve leaves it except along the +selected stem segment. -/ +structure PortMove (p : V → ℂ) (Q : PLDrawing G) (B : Set V) (v : V) (q : ℂ) (S T : Set ℂ) : Prop where + selected : Q.point v=q + point_mem : ∀ w, Q.point w∈closure T + trace_mem : ∀ d, (Q.chain d).trace ⊆ closure T + point_control : ∀ w, Q.point w∈closure S ∪ segment ℝ (p v) q + trace_control : ∀ d, (Q.chain d).trace ⊆ closure S ∪ segment ℝ (p v) q + on_frontier : ∀ w∈B, w≠v → Q.point w∈frontier T + tail_old : ∀ w∈B, w≠v → segment ℝ (Q.point w) (p w) ⊆ closure S + tail_frontier : ∀ w∈B, w≠v → ∀ z∈segment ℝ (Q.point w) (p w), + z∈frontier S → z=p w + tail_new : ∀ w∈B, w≠v → ∀ z∈segment ℝ (Q.point w) (p w), + z∈closure T → z=Q.point w + tails_disjoint : ∀ w∈B, w≠v → ∀ u∈B, u≠v → w≠u → + Disjoint (segment ℝ (Q.point w) (p w)) (segment ℝ (Q.point u) (p u)) + +lemma retube_controlled {S T : Set ℂ} {B : Set V} {v : V} {q : ℂ} + (hS : Convex ℝ S) (hS0 : S∈nhds (0:ℂ)) (hSb : Bornology.IsBounded S) + (hpoint : ∀ w, P.point w∈closure S) + (htrace : ∀ d, (P.chain d).trace ⊆ closure S) + (hport : ∀ w∈B, P.point w∈frontier S) + (hleaf : ∀ w∈B, ∀ a b, G.Adj w a → G.Adj w b → a=b) + (hv : v∈B) (hT : Convex ℝ T) (hTop : IsOpen T) (hT0 : (0:ℂ)∈T) + (hTv : P.point v∈T) (hqT : q∈closure T) + (hout : ∀ w∈B, w≠v → P.point w∉closure T) + (hext : ∀ z, z∈segment ℝ (P.point v) q → z∈closure S → z=P.point v) : + ∃ Q : PLDrawing G, PortMove P.point Q B v q S T := by + classical + obtain ⟨c,t,Q,hc,hc1,htv,ht,hQ,hreg,hTQ,hpointT,hfront,htail⟩ := + P.retube_extend hS hS0 hSb hpoint htrace hport hleaf hv hT hTop hT0 hTv hqT hout hext + have hp (w : V) : Q.point w=P.retubePoint B c t v q w := congrFun hQ w + have hpv : Q.point v=q := by rw [hp]; simp [retubePoint] + have hpw (w : V) (hw : w∈B) (he : w≠v) : Q.point w=t w•P.point w := by + rw [hp]; simp only [retubePoint,ite_eq_right he,radialPoint,ite_eq_left hw] + have hscl (w : V) (hw : w≠v) : Q.point w∈closure S := by + rw [hp]; simp only [retubePoint,ite_eq_right hw,radialPoint] + split_ifs with hwB + · have : t w•P.point w∈segment ℝ 0 (P.point w) := by + rw [segment_eq_image' ℝ]; exact ⟨t w,⟨hc.le.trans (ht w hwB).1.le,(ht w hwB).2⟩,by simp⟩ + exact hS.closure.segment_subset (subset_closure (mem_of_mem_nhds hS0)) (hpoint w) this + · have : c•P.point w∈segment ℝ 0 (P.point w) := by + rw [segment_eq_image' ℝ]; exact ⟨c,⟨hc.le,hc1.le⟩,by simp⟩ + exact hS.closure.segment_subset (subset_closure (mem_of_mem_nhds hS0)) (hpoint w) this + have htail_subset (w : V) (hw : w∈B) (he : w≠v) : + segment ℝ (Q.point w) (P.point w) ⊆ segment ℝ 0 (P.point w) := by + apply (convex_segment 0 (P.point w)).segment_subset + · rw [hpw w hw he,segment_eq_image' ℝ] + exact ⟨t w,⟨hc.le.trans (ht w hw).1.le,(ht w hw).2⟩,by simp⟩ + · exact right_mem_segment ℝ _ _ + refine ⟨Q,⟨hpv,hpointT,hTQ,?_,?_,hfront,?_,?_,htail,?_⟩⟩ + · intro w + by_cases he : w=v + · subst w; exact Or.inr (hpv ▸ right_mem_segment ℝ (P.point v) q) + · exact Or.inl (hscl w he) + · intro d z hz + rcases hreg d hz with hz|hz + · exact Or.inl (P.radialRegion_old hS hS0 hc.le hc1.le hpoint htrace + (fun w hw => ⟨hc.le.trans (ht w hw).1.le,(ht w hw).2⟩) d hz) + · exact Or.inr hz.2 + · intro w hw he + exact hS.closure.segment_subset (hscl w he) (hpoint w) + · intro w hw he z hz hzfr + exact convex_frontier_segment hS hS0 (hport w hw) hzfr (htail_subset w hw he hz) + · intro w hw he u hu hue hwu + have hdisj := convex_frontier_tails_disjoint hS hS0 (hport w hw) (hport u hu) + (fun h => hwu (P.point_injective h)) hc hc1.le + apply hdisj.mono + · rw [hpw w hw he] + apply (convex_segment (c•P.point w) (P.point w)).segment_subset + · rw [segment_eq_image' ℝ] + refine ⟨(t w-c)/(1-c),?_,?_⟩ + · constructor + · exact div_nonneg (sub_nonneg.mpr (ht w hw).1.le) (sub_nonneg.mpr hc1.le) + · apply (div_le_one (sub_pos.mpr hc1)).mpr + linarith [(ht w hw).2] + · have hne : (1-c)≠0 := ne_of_gt (sub_pos.mpr hc1) + have hs : c+((t w-c)/(1-c))*(1-c)=t w := by field_simp; ring + calc c•P.point w+((t w-c)/(1-c))•(P.point w-c•P.point w) + = (c+((t w-c)/(1-c))*(1-c))•P.point w := by module + _ = t w•P.point w := by rw [hs] + · exact right_mem_segment ℝ _ _ + · rw [hpw u hu hue] + apply (convex_segment (c•P.point u) (P.point u)).segment_subset + · rw [segment_eq_image' ℝ] + refine ⟨(t u-c)/(1-c),?_,?_⟩ + · constructor + · exact div_nonneg (sub_nonneg.mpr (ht u hu).1.le) (sub_nonneg.mpr hc1.le) + · apply (div_le_one (sub_pos.mpr hc1)).mpr + linarith [(ht u hu).2] + · have hne : (1-c)≠0 := ne_of_gt (sub_pos.mpr hc1) + have hs : c+((t u-c)/(1-c))*(1-c)=t u := by field_simp; ring + calc c•P.point u+((t u-c)/(1-c))•(P.point u-c•P.point u) + = (c+((t u-c)/(1-c))*(1-c))•P.point u := by module + _ = t u•P.point u := by rw [hs] + · exact right_mem_segment ℝ _ _ + +end PLDrawing +end PlanarL1.Topology + + + + +namespace PlanarL1.Topology +open Set Metric Filter +namespace PLDrawing +variable {V : Type} [LinearOrder V] {G : SimpleGraph V} + +lemma affine_image_closure (f : ℂ ≃ᵃ[ℝ] ℂ) (S : Set ℂ) : + closure (f '' S)=f '' closure S := by + exact (f.toContinuousAffineEquiv.toHomeomorph.image_closure S).symm +lemma affine_image_frontier (f : ℂ ≃ᵃ[ℝ] ℂ) (S : Set ℂ) : + frontier (f '' S)=f '' frontier S := by + exact (f.toContinuousAffineEquiv.toHomeomorph.image_frontier S).symm + +lemma PortMove.affine {p : V → ℂ} {Q : PLDrawing G} {B : Set V} {v : V} {q : ℂ} {S T : Set ℂ} + (h : PortMove p Q B v q S T) (f : ℂ ≃ᵃ[ℝ] ℂ) : + PortMove (fun w => f (p w)) (Q.affine f) B v (f q) (f '' S) (f '' T) := by + have hseg (a b : ℂ) : segment ℝ (f a) (f b)=f '' segment ℝ a b := (image_segment ℝ f.toAffineMap a b).symm + constructor + · exact congrArg f h.selected + · intro w; rw [affine_point,affine_image_closure]; exact ⟨Q.point w,h.point_mem w,rfl⟩ + · intro d; rw [Q.affine_trace,affine_image_closure]; exact Set.image_mono (h.trace_mem d) + · intro w + rw [affine_point,affine_image_closure,hseg,← Set.image_union] + exact ⟨Q.point w,h.point_control w,rfl⟩ + · intro d + rw [Q.affine_trace,affine_image_closure,hseg,← Set.image_union] + exact Set.image_mono (h.trace_control d) + · intro w hw he + rw [affine_point,affine_image_frontier] + exact ⟨Q.point w,h.on_frontier w hw he,rfl⟩ + · intro w hw he + rw [affine_point,hseg,affine_image_closure] + exact Set.image_mono (h.tail_old w hw he) + · intro w hw he z hz hz' + rw [affine_point,hseg] at hz + rw [affine_image_frontier] at hz' + obtain ⟨z,hz,rfl⟩ := hz + obtain ⟨z',hz',hzz⟩ := hz' + have heq : z'=z := f.injective hzz + subst z' + exact congrArg f (h.tail_frontier w hw he z hz hz') + · intro w hw he z hz hz' + rw [affine_point,hseg] at hz + rw [affine_image_closure] at hz' + obtain ⟨z,hz,rfl⟩ := hz + obtain ⟨z',hz',hzz⟩ := hz' + have heq : z'=z := f.injective hzz + subst z' + exact congrArg f (h.tail_new w hw he z hz hz') + · intro w hw he u hu hue hwu + rw [affine_point,affine_point,hseg,hseg] + apply Set.disjoint_left.mpr + rintro z ⟨x,hx,rfl⟩ ⟨y,hy,hxy⟩ + have hxy' : y=x := f.injective hxy + subst y + exact Set.disjoint_left.mp (h.tails_disjoint w hw he u hu hue hwu) hx hy + +lemma retube_at (P : PLDrawing G) {S T : Set ℂ} {B : Set V} {v : V} {q a : ℂ} + (hS : Convex ℝ S) (hSopen : IsOpen S) (hSa : a∈S) (hSb : Bornology.IsBounded S) + (hpoint : ∀ w, P.point w∈closure S) + (htrace : ∀ d, (P.chain d).trace ⊆ closure S) + (hport : ∀ w∈B, P.point w∈frontier S) + (hleaf : ∀ w∈B, ∀ u w', G.Adj w u → G.Adj w w' → u=w') + (hv : v∈B) (hT : Convex ℝ T) (hTop : IsOpen T) (hTa : a∈T) + (hTv : P.point v∈T) (hqT : q∈closure T) + (hout : ∀ w∈B, w≠v → P.point w∉closure T) + (hext : ∀ z, z∈segment ℝ (P.point v) q → z∈closure S → z=P.point v) : + ∃ Q : PLDrawing G, PortMove P.point Q B v q S T := by + let f := AffineEquiv.constVAdd ℝ ℂ (-a) + let R := P.affine f + let S' := f '' S + let T' := f '' T + have hS' : Convex ℝ S' := hS.affine_image f.toAffineMap + have hT' : Convex ℝ T' := hT.affine_image f.toAffineMap + have hSop : IsOpen S' := f.toContinuousAffineEquiv.toHomeomorph.isOpenMap S hSopen + have hTop' : IsOpen T' := f.toContinuousAffineEquiv.toHomeomorph.isOpenMap T hTop + have h0S : (0:ℂ)∈S' := ⟨a,hSa,by simp [f]⟩ + have h0T : (0:ℂ)∈T' := ⟨a,hTa,by simp [f]⟩ + have hSb' : Bornology.IsBounded S' := by + apply ((isCompact_of_isClosed_isBounded isClosed_closure hSb.closure).image + f.toContinuousAffineEquiv.toHomeomorph.continuous).isBounded.subset + exact Set.image_mono subset_closure + have hcl (U : Set ℂ) : closure (f '' U)=f '' closure U := affine_image_closure f U + have hfr (U : Set ℂ) : frontier (f '' U)=f '' frontier U := affine_image_frontier f U + obtain ⟨Q,hQ⟩ := R.retube_controlled hS' (hSop.mem_nhds h0S) hSb' + (fun w => by rw [hcl]; exact ⟨P.point w,hpoint w,rfl⟩) + (fun d => by rw [show (R.chain d).trace=f '' (P.chain d).trace from P.affine_trace f d,hcl]; exact Set.image_mono (htrace d)) + (fun w hw => by rw [hfr]; exact ⟨P.point w,hport w hw,rfl⟩) + hleaf hv hT' hTop' h0T (show f (P.point v)∈T' from ⟨P.point v,hTv,rfl⟩) + (show f q∈closure T' from by rw [hcl]; exact ⟨q,hqT,rfl⟩) + (fun w hw he hp => by + rw [hcl] at hp + obtain ⟨z,hz,heq⟩ := hp + apply hout w hw he + have heq' : z=P.point w := f.injective heq + exact heq' ▸ hz) + (fun z hz hz' => by + change z∈segment ℝ (f (P.point v)) (f q) at hz + have hs : f '' segment ℝ (P.point v) q=segment ℝ (f (P.point v)) (f q) := image_segment ℝ f.toAffineMap _ _ + rw [← hs] at hz + rw [hcl] at hz' + obtain ⟨z,hz,rfl⟩ := hz + obtain ⟨z',hz',heq⟩ := hz' + have heq' : z'=z := f.injective heq + subst z' + exact congrArg f (hext z hz hz')) + have hh := hQ.affine f.symm + refine ⟨Q.affine f.symm,?_⟩ + change PortMove (fun w => f.symm (f (P.point w))) (Q.affine f.symm) + B v (f.symm (f q)) (f.symm '' (f '' S)) (f.symm '' (f '' T)) at hh + simpa only [AffineEquiv.symm_apply_apply,Set.image_image,Function.comp_def, + Set.image_id'] using hh + +end PLDrawing +end PlanarL1.Topology + + + + +namespace PlanarL1.Topology +open Set + +variable {V : Type} + +/-- Released radial port tails; unlike `PortMove` this does not prescribe the +selected route, which may already have passed through several bends. -/ +structure PortFrame (p a : V → ℂ) (B : Set V) (v : V) (q : ℂ) (S T : Set ℂ) : Prop where + selected : a v=q + on_frontier : ∀ w∈B, w≠v → a w∈frontier T + tail_old : ∀ w∈B, w≠v → segment ℝ (a w) (p w) ⊆ closure S + tail_frontier : ∀ w∈B, w≠v → ∀ z∈segment ℝ (a w) (p w), + z∈frontier S → z=p w + tail_new : ∀ w∈B, w≠v → ∀ z∈segment ℝ (a w) (p w), + z∈closure T → z=a w + tails_disjoint : ∀ w∈B, w≠v → ∀ u∈B, u≠v → w≠u → + Disjoint (segment ℝ (a w) (p w)) (segment ℝ (a u) (p u)) + +namespace PortFrame +lemma ofMove [LinearOrder V] {G : SimpleGraph V} {p : V → ℂ} {Q : PLDrawing G} {B : Set V} + {v : V} {q : ℂ} {S T : Set ℂ} (h : PLDrawing.PortMove p Q B v q S T) : + PortFrame p Q.point B v q S T := + ⟨h.selected,h.on_frontier,h.tail_old,h.tail_frontier,h.tail_new,h.tails_disjoint⟩ + +lemma repoint {p a b : V → ℂ} {B : Set V} {v : V} {q r : ℂ} {S T : Set ℂ} + (h : PortFrame p a B v q S T) (hv : b v=r) (he : ∀ w, w≠v → b w=a w) : + PortFrame p b B v r S T := by + constructor + · exact hv + · intro w hw hwv; rw [he w hwv]; exact h.on_frontier w hw hwv + · intro w hw hwv; rw [he w hwv]; exact h.tail_old w hw hwv + · intro w hw hwv; rw [he w hwv]; exact h.tail_frontier w hw hwv + · intro w hw hwv; rw [he w hwv]; exact h.tail_new w hw hwv + · intro w hw hwv u hu huv hwu + rw [he w hwv,he u huv]; exact h.tails_disjoint w hw hwv u hu huv hwu +end PortFrame + +/-- Actual disjoint exterior polygonal stems, not a promised contour order. -/ +structure ExteriorPorts (p target : V → ℂ) (B : Set V) (S : Set ℂ) where + region : V → Set ℂ + compact : ∀ w∈B, IsCompact (region w) + start : ∀ w∈B, p w∈region w + joined : ∀ w∈B, PolygonallyJoined (region w) (p w) (target w) + inside : ∀ w∈B, ∀ z∈region w, z∈closure S → z=p w + disjoint : ∀ w∈B, ∀ u∈B, w≠u → Disjoint (region w) (region u) + +namespace ExteriorPorts +variable {p target : V → ℂ} {B : Set V} {S : Set ℂ} (E : ExteriorPorts p target B S) + +lemma end_mem (w : V) (hw : w∈B) : target w∈E.region w := by + have hreach : ∀ y, PolygonallyJoined (E.region w) (p w) y → y∈E.region w := by + intro y hj + induction hj with + | refl => exact E.start w hw + | @tail y z h hz ih => exact hz (right_mem_segment ℝ _ _) + exact hreach _ (E.joined w hw) + +lemma tail_disjoint_region {a : V → ℂ} {v : V} {q : ℂ} {T : Set ℂ} + (h : PortFrame p a B v q S T) (hinj : Function.Injective p) + (hport : ∀ w∈B, p w∈frontier S) + {w u : V} (hw : w∈B) (he : w≠v) (hu : u∈B) (hwu : w≠u) : + Disjoint (segment ℝ (a w) (p w)) (E.region u) := by + apply Set.disjoint_left.mpr + intro z hz hz' + have heq := E.inside u hu z hz' (h.tail_old w hw he hz) + have heqw := h.tail_frontier w hw he z hz (heq ▸ hport u hu) + exact hwu (hinj (heqw.symm.trans heq)) + +noncomputable def updatedRegion (a : V → ℂ) (v : V) (U : Set ℂ) (w : V) : Set ℂ := by + classical exact if w=v then U else segment ℝ (a w) (p w) ∪ E.region w + +/-- Replacing one residual stem, and adjoining the released radial tails to +all other stems, preserves literal disjoint exterior routes. -/ +noncomputable def update {a : V → ℂ} {v : V} {q : ℂ} {T U : Set ℂ} + (h : PortFrame p a B v q S T) (hinj : Function.Injective p) + (hport : ∀ w∈B, p w∈frontier S) (hv : v∈B) + (hout : ∀ w∈B, w≠v → Disjoint (closure T) (E.region w)) + (hU : IsCompact U) (hqU : q∈U) (hUsub : U ⊆ E.region v) + (hUin : ∀ z∈U, z∈closure T → z=q) + (hUjoin : PolygonallyJoined U q (target v)) : ExteriorPorts a target B T where + region := E.updatedRegion a v U + compact w hw := by + classical + by_cases he : w=v + · simpa only [updatedRegion,ite_eq_left he] using hU + · simpa only [updatedRegion,ite_eq_right he] using (compact_segment_complex _ _).union (E.compact w hw) + start w hw := by + classical + by_cases he : w=v + · subst w; simpa only [updatedRegion,ite_true,h.selected] using hqU + · simp only [updatedRegion,ite_eq_right he]; exact Or.inl (left_mem_segment ℝ _ _) + joined w hw := by + classical + by_cases he : w=v + · subst w; simpa only [updatedRegion,ite_true,h.selected] using hUjoin + · simp only [updatedRegion,ite_eq_right he] + exact (Relation.ReflTransGen.single (fun z hz => Or.inl hz)).trans + ((E.joined w hw).mono Set.subset_union_right) + inside w hw z hz hz' := by + classical + by_cases he : w=v + · subst w + rw [h.selected] + exact hUin z (by simpa only [updatedRegion,ite_true] using hz) hz' + · simp only [updatedRegion,ite_eq_right he] at hz + rcases hz with hz|hz + · exact h.tail_new w hw he z hz hz' + · exact False.elim (Set.disjoint_left.mp (hout w hw he) hz' hz) + disjoint w hw u hu hwu := by + classical + by_cases hwv : w=v <;> by_cases huv : u=v + · exact False.elim (hwu (hwv.trans huv.symm)) + · subst w + simp only [updatedRegion,ite_true,ite_eq_right huv] + apply Disjoint.union_right + · exact (E.tail_disjoint_region h hinj hport hu huv hv huv).symm.mono_left hUsub + · exact (E.disjoint v hv u hu hwu).mono_left hUsub + · subst u + simp only [updatedRegion,ite_true,ite_eq_right hwv] + apply Disjoint.union_left + · exact (E.tail_disjoint_region h hinj hport hw hwv hv hwv).mono_right hUsub + · exact (E.disjoint w hw v hv hwu).mono_right hUsub + · simp only [updatedRegion,ite_eq_right hwv,ite_eq_right huv] + apply Disjoint.union_left + · apply Disjoint.union_right + · exact h.tails_disjoint w hw hwv u hu huv hwu + · exact E.tail_disjoint_region h hinj hport hw hwv hu hwu + · apply Disjoint.union_right + · exact (E.tail_disjoint_region h hinj hport hu huv hw (Ne.symm hwu)).symm + · exact E.disjoint w hw u hu hwu + +end ExteriorPorts +end PlanarL1.Topology + + + + +namespace PlanarL1.Topology +open Set +variable {E : Type*} [NormedAddCommGroup E] [NormedSpace ℝ E] +namespace SegmentChain +variable {S : Set E} {x y : E} {n : ℕ} (P : SegmentChain S x y (n+1)) + +noncomputable def tail : SegmentChain S (P.vertex 1) y n where + vertex i := P.vertex (i+1) + start := rfl + finish := P.finish + segment_mem i hi := P.segment_mem (i+1) (by omega) + +lemma tail_trace : P.trace=segment ℝ x (P.vertex 1) ∪ P.tail.trace := by + apply Set.Subset.antisymm + · rintro z (hz|hz) + · have he : z=x := hz; subst z; exact Or.inl (left_mem_segment ℝ _ _) + · obtain ⟨i,hi⟩ := Set.mem_iUnion.mp hz + by_cases he : (i:ℕ)=0 + · exact Or.inl (by simpa only [he,zero_add,P.start] using hi) + · apply Or.inr; apply Or.inr; apply Set.mem_iUnion.mpr + refine ⟨⟨i-1,by omega⟩,?_⟩ + simpa only [tail,show (i:ℕ)-1+1=i by omega] using hi + · rintro z (hz|hz) + · apply Or.inr; apply Set.mem_iUnion.mpr + exact ⟨⟨0,by omega⟩,by simpa only [zero_add,P.start] using hz⟩ + · rcases hz with hz|hz + · have he : z=P.vertex 1 := hz; subst z + exact Or.inr (Set.mem_iUnion.mpr ⟨⟨0,by omega⟩, + by simpa only [zero_add,P.start] using right_mem_segment ℝ x (P.vertex 1)⟩) + · obtain ⟨i,hi⟩ := Set.mem_iUnion.mp hz + exact Or.inr (Set.mem_iUnion.mpr ⟨⟨i+1,by omega⟩,hi⟩) + +lemma tail_simple (hP : P.IsSimple) : P.tail.IsSimple := by + constructor + · intro i hi j hj he + change i≤n at hi + change j≤n at hj + have he' := hP.1 (show i+1∈Iic (n+1) from Nat.add_le_add_right hi 1) + (show j+1∈Iic (n+1) from Nat.add_le_add_right hj 1) he + omega + · intro i j hij hjn z hz hz' + obtain ⟨he,hz⟩ := hP.2 (i+1) (j+1) (by omega) (by omega) z hz hz' + exact ⟨by omega,hz⟩ + +lemma head_tail_intersection (hP : P.IsSimple) {z : E} + (hz : z∈segment ℝ x (P.vertex 1)) (hz' : z∈P.tail.trace) : z=P.vertex 1 := by + rcases hz' with hz'|hz' + · exact hz' + · obtain ⟨i,hi⟩ := Set.mem_iUnion.mp hz' + obtain ⟨he,he'⟩ := hP.2 0 (i+1) (by omega) (by omega) z (by simpa only [P.start,zero_add] using hz) hi + simpa only [he,zero_add] using he' + +lemma first_ne (hP : P.IsSimple) : P.vertex 1≠x := by + intro he + have hh := hP.1 (show 1∈Iic (n+1) from Nat.le_add_left 1 n) (show 0∈Iic (n+1) from Nat.zero_le _) + (he.trans P.start.symm) + omega + +lemma start_not_tail (hP : P.IsSimple) : x∉P.tail.trace := by + intro hx + exact P.first_ne hP (P.head_tail_intersection hP (left_mem_segment ℝ _ _) hx).symm + +lemma finish_not_first (P : SegmentChain S x y (n+1+1)) (hP : P.IsSimple) : + y∉segment ℝ x (P.vertex 1) := by + intro hy + have hlast : y∈segment ℝ (P.vertex (n+1)) (P.vertex (n+1+1)) := by + rw [P.finish]; exact right_mem_segment ℝ _ _ + obtain ⟨he,he'⟩ := hP.2 0 (n+1) (by omega) (by omega) y + (by simpa only [P.start,zero_add] using hy) hlast + have hi := hP.1 (show n+1+1∈Iic (n+1+1) from by simp) + (show n+1∈Iic (n+1+1) from Nat.le_succ _) (P.finish.trans he') + omega + +noncomputable def cutFirst (z : E) (hz : z∈segment ℝ x (P.vertex 1)) : + SegmentChain S z y (n+1) where + vertex i := if i=0 then z else P.vertex i + start := by simp + finish := by simpa using P.finish + segment_mem i hi := by + by_cases he : i=0 + · subst i + simp only [ite_true,Nat.zero_add,one_ne_zero,ite_false] + apply (P.segment_mem 0 (by omega)).trans' -- rewrite the first endpoint + simpa only [P.start,zero_add] using (convex_segment x (P.vertex 1)).segment_subset hz (right_mem_segment ℝ _ _) + · simpa only [ite_eq_right he,Nat.succ_ne_zero,ite_false] using P.segment_mem i hi + +lemma cutFirst_trace (z : E) (hz : z∈segment ℝ x (P.vertex 1)) : + (P.cutFirst z hz).trace=segment ℝ z (P.vertex 1) ∪ P.tail.trace := by + rw [(P.cutFirst z hz).tail_trace] + rfl + +lemma cutFirst_subset (z : E) (hz : z∈segment ℝ x (P.vertex 1)) : (P.cutFirst z hz).trace ⊆ P.trace := by + rw [P.cutFirst_trace,P.tail_trace] + exact Set.union_subset_union ((convex_segment x (P.vertex 1)).segment_subset hz (right_mem_segment ℝ _ _)) Set.Subset.rfl + +lemma cutFirst_simple (hP : P.IsSimple) (z : E) (hz : z∈segment ℝ x (P.vertex 1)) + (hne : z≠P.vertex 1) : (P.cutFirst z hz).IsSimple := by + have hzhead : segment ℝ z (P.vertex 1) ⊆ segment ℝ x (P.vertex 1) := + (convex_segment x (P.vertex 1)).segment_subset hz (right_mem_segment ℝ _ _) + have hztail : z∉P.tail.trace := fun h => hne (P.head_tail_intersection hP hz h) + constructor + · intro i hi j hj he + by_cases hi0 : i=0 <;> by_cases hj0 : j=0 + · omega + · subst i + have he' : z=P.vertex j := by simpa only [cutFirst,ite_true,ite_eq_right hj0] using he + exfalso; apply hztail + rw [he'] + have hm := P.tail.vertex_mem_trace (j-1) (by change j≤n+1 at hj; omega) + simpa only [tail,show j-1+1=j by omega] using hm + · subst j + have he' : P.vertex i=z := by simpa only [cutFirst,ite_true,ite_eq_right hi0] using he + exfalso; apply hztail + rw [← he'] + have hm := P.tail.vertex_mem_trace (i-1) (by change i≤n+1 at hi; omega) + simpa only [tail,show i-1+1=i by omega] using hm + · exact hP.1 hi hj (by simpa only [cutFirst,ite_eq_right hi0,ite_eq_right hj0] using he) + · intro i j hij hjn w hw hw' + have hj0 : j≠0 := by omega + have hw₂ : w∈segment ℝ (P.vertex j) (P.vertex (j+1)) := by + simpa only [cutFirst,ite_eq_right hj0,Nat.succ_ne_zero,ite_false] using hw' + by_cases hi0 : i=0 + · subst i + have hw₁ : w∈segment ℝ x (P.vertex 1) := hzhead + (by simpa only [cutFirst,ite_true,zero_add,one_ne_zero,ite_false] using hw) + obtain ⟨he,hw⟩ := hP.2 0 j hij hjn w (by simpa only [P.start,zero_add] using hw₁) hw₂ + exact ⟨he,by simpa only [cutFirst,ite_eq_right hj0] using hw⟩ + · obtain ⟨he,hw⟩ := hP.2 i j hij hjn w + (by simpa only [cutFirst,ite_eq_right hi0,Nat.succ_ne_zero,ite_false] using hw) hw₂ + exact ⟨he,by simpa only [cutFirst,ite_eq_right hj0] using hw⟩ + +end SegmentChain +end PlanarL1.Topology + + + +end + +end OAI diff --git a/lean/OAI/Combinatorics/PlanarL1/ScaleHistory.lean b/lean/OAI/Combinatorics/PlanarL1/ScaleHistory.lean new file mode 100644 index 0000000000000000000000000000000000000000..f2effad11164098026e28cc833267156ffab0ba4 --- /dev/null +++ b/lean/OAI/Combinatorics/PlanarL1/ScaleHistory.lean @@ -0,0 +1,469 @@ +import OAI.Combinatorics.PlanarL1.SecondaryFamily +import OAI.Combinatorics.PlanarL1.Dilation + +namespace OAI + + +section + +namespace PlanarL1.Columns.Model +open MeasureTheory +open scoped NNReal +variable {k : ℕ} {M : Model (k+1)} {κ : ℝ} {lam : ℝ≥0} +variable {Ω : Type*} [MeasurableSpace Ω] {μ : Measure Ω} +variable (A : Ambient M) {c t : ℝ} (hc : 0 A.History c) (fun _ => Ambient.History.empty A c) H.history + older a := by + let P (Z : A.History c) : Prop := ∀ j, t≤Z.radius j + change P (Fin.addCases (m := m) (n := S.count+1) (motive := fun _ : Fin (m+(S.count+1)) => A.History c) (fun _ => Ambient.History.empty A c) H.history a) + refine Fin.addCases (m := m) (n := S.count+1) ?_ ?_ a + · intro i + rw [Fin.addCases_left] + exact fun j => Fin.elim0 j + · intro i + rw [Fin.addCases_right] + exact H.older i + recorded a := by + refine Fin.addCases (m := m) (n := S.count+1) ?_ ?_ a + · intro i + simpa only [BState.append, Fin.addCases_left] using hD i + · intro i + simpa only [BState.append, Fin.addCases_right] using H.recorded i + +noncomputable def increment (H : Histories A hc hcr S t) {r s : ℝ} + (sign : Fin (S.count+1) → Bool) (hr : 0 + intro j + simpa only [BData.incrementHistory] using ht.trans (H.older a j) + | ordered D => + intro j + cases j using Fin.lastCases with + | last => simpa only [BData.incrementHistory,Ambient.History.append,Fin.snoc_last] using hs + | cast j => simpa only [BData.incrementHistory,Ambient.History.append,Fin.snoc_castSucc] using ht.trans (H.older a j) + recorded a := S.increment_recorded A H.history sign hc hcr hr hcross H.recorded hk hsmall hlam hboundary a +end Histories +end BState + +namespace BState.SecondaryStep +variable {J : Set ℝ} {root : Fin (k+1)} {S : BState M κ lam Ω μ} +variable (U : SecondaryStep S J root) +lemma newData_recorded (a : Fin (3*(k+1)*U.tree.depthCap+2)) : + (U.newData a).Recorded (Ambient.History.empty A c) hc hcr := by + classical + unfold newData + split_ifs + · trivial + · intro i T + rw [Ambient.History.field_empty] + rfl + · trivial +end BState.SecondaryStep + +namespace BState.SecondaryLayer +variable {S : BState M κ lam Ω μ} (B : SecondaryLayer S) +noncomputable def histories [SFinite μ] (H : Histories A hc hcr S t) : + Histories A hc hcr B.apply t := by + unfold apply + apply H.lift.append + intro a + exact ((B.batch _).step _).newData_recorded A hc hcr _ +end BState.SecondaryLayer +end PlanarL1.Columns.Model + +end + + + +section + +open Set +namespace PlanarL1 +/-- The distance to a literal image scales under a surjective homothety, +including the empty set convention for `infDist`. -/ +lemma infDist_homothety {X Y : Type*} [PseudoMetricSpace X] [PseudoMetricSpace Y] + (f : X → Y) {q : ℝ} (hq : 0 intro h <;> nlinarith only [hq,h]] + split_ifs + · rw [show -(q*t)=q*(-t) by ring,positivePart_scale hq] + ring + · exact positivePart_scale hq a r t + +lemma taper_scale {X Y : Type*} [PseudoMetricSpace X] [PseudoMetricSpace Y] + (f : X → Y) (hd : ∀ x y, dist (f x) (f y)=q*dist x y) + (S : Set X) (r : ℝ) (x : X) : taper (f '' S) (q*r) (f x)=taper S r x := by + unfold taper + rw [Set.image_nonempty] + split_ifs + · rw [infDist_homothety f hq hd] + congr 1 + exact mul_div_mul_left _ _ hq.ne' + · rfl +end Increment +end PlanarL1 + +namespace PlanarL1.Columns.Model +variable {k : ℕ} {M : Model (k+1)} {q : ℝ} (hq : 0 q*T) '' Set.univ=Set.univ := by + ext T + simp only [mem_dilate_set q hq,Set.mem_univ] + +namespace Point +lemma dist_band_eq {J I : Set ℝ} {r s : Fin (k+1)} (h : J=I) + (x y : M.Point J r) (x' y' : M.Point I s) + (hx : x.column=x'.column) (hX : x.height=x'.height) + (hy : y.column=y'.column) (hY : y.height=y'.height) : dist x y=dist x' y' := by + subst I + exact Point.dist_coordinates x y x' y' hx hX hy hY +end Point +namespace Ambient +variable (A : Ambient M) +noncomputable def dilate : Ambient (M.dilate q hq) where + root := A.root + connected i := by + rw [← scale_univ hq,M.dilate_activeGraph] + exact A.connected i + +noncomputable def scaleEquiv : M.Point Set.univ A.root ≃ (M.dilate q hq).Point Set.univ (A.dilate hq).root where + toFun x := (A.dilate hq).point x.column (q*x.height) + invFun x := A.point x.column (x.height/q) + left_inv x := by cases x; simp only [point,mul_div_cancel_left₀ _ hq.ne'] + right_inv x := by cases x; simp only [point,mul_div_cancel₀ _ hq.ne'] + +lemma scaleEquiv_dist (x y : M.Point Set.univ A.root) : + dist (A.scaleEquiv hq x) (A.scaleEquiv hq y)=q*dist x y := by + rw [← Point.dist_band_eq (scale_univ hq) (x.dilate hq) (y.dilate hq) + (A.scaleEquiv hq x) (A.scaleEquiv hq y) rfl rfl rfl rfl] + exact x.dilate_dist hq y + +lemma scaleEquiv_point (i : Fin (k+1)) (T : ℝ) : + A.scaleEquiv hq (A.point i T)=(A.dilate hq).point i (q*T) := rfl + +namespace History +variable {A} {c : ℝ} +noncomputable def dilate (H : History A c) : History (A.dilate hq) c where + count := H.count + radius j := q*H.radius j + region j := A.scaleEquiv hq '' H.region j + sign := H.sign + positive j := mul_pos hq (H.positive j) + separated i j hij := by + rcases H.separated i j hij with h | h + · left; nlinarith only [hq,h] + · right; nlinarith only [hq,h] +end History +end Ambient +end PlanarL1.Columns.Model + +namespace PlanarL1.Columns.Model.Field +open scoped NNReal +variable {k : ℕ} {M : Model (k+1)} {q : ℝ} (hq : 0 q*T) '' J) : + (F.dilate hq).transverseValue a b i H= + q*F.transverseValue a b i ⟨H.val/q,(mem_dilate_set q hq).mp H.property⟩ := by + unfold transverseValue + rw [dilate_wall hq] + have he : ((F.dilate hq).value i H,H.val)= + coordinateScale q (F.value i ⟨H.val/q,(mem_dilate_set q hq).mp H.property⟩,H.val/q) := by + simp only [coordinateScale,dilate,mul_div_cancel₀ _ hq.ne'] + rw [he,PlanarL1.infDist_homothety _ hq (coordinateScale_dist hq)] + ring +end PlanarL1.Columns.Model.Field + +namespace PlanarL1.Columns.Model +open scoped NNReal +variable {k : ℕ} {M : Model (k+1)} {q : ℝ} (hq : 0 q*U) '' I) : + ((H.dilate hq).field (s.dilate hq) a b hc hcr).value i T= + q*(H.field s a b hc hcr).value i ⟨T.val/q,(mem_dilate_set q hq).mp T.property⟩ := by + classical + let U : I := ⟨T.val/q,(mem_dilate_set q hq).mp T.property⟩ + have ht : ((s.dilate hq).transverse (by norm_num) a b).value i T= + q*(s.transverse (by norm_num) a b).value i U := s.dilate_transverseValue hq a b i T + have hw (j : Fin H.count) : + Increment.taper ((A.scaleEquiv hq '' H.region j)ᶜ) (q*H.radius j) + ((A.dilate hq).point i T.val)=Increment.taper (H.region j)ᶜ (H.radius j) (A.point i U.val) := by + rw [← Equiv.image_compl] + have he : (A.dilate hq).point i T.val=A.scaleEquiv hq (A.point i U.val) := by + change (A.dilate hq).point i T.val=(A.dilate hq).point i (q*(T.val/q)) + rw [mul_div_cancel₀ _ hq.ne'] + rw [he] + exact Increment.taper_scale hq (A.scaleEquiv hq) (A.scaleEquiv_dist hq) _ _ _ + change (∑ j : Fin H.count, Increment.signedDamped (H.sign j) (c*(q*H.radius j)) (q*H.radius j) + (((s.dilate hq).transverse (by norm_num) a b).value i) + (fun W => Increment.taper (A.scaleEquiv hq '' H.region j)ᶜ (q*H.radius j) ((A.dilate hq).point i W.val)) T)= + q*∑ j : Fin H.count, Increment.signedDamped (H.sign j) (c*H.radius j) (H.radius j) + ((s.transverse (by norm_num) a b).value i) + (fun W => Increment.taper (H.region j)ᶜ (H.radius j) (A.point i W.val)) U + rw [Finset.mul_sum] + apply Finset.sum_congr rfl + intro j _ + unfold Increment.signedDamped Increment.damped + simp only [ht,hw,show c*(q*H.radius j)=q*(c*H.radius j) by ring,Increment.scalar_scale hq] + cases H.sign j <;> simp only [Bool.false_eq_true,ite_false,ite_true] <;> ring +end Ambient.History + +namespace BData +lemma dilate_recorded (D : BData M) (H : A.History c) (hc : 0 trivial + | ordered D => + intro i T + change q*D.auxiliary.value i ⟨T.val/q,(mem_dilate_set q hq).mp T.property⟩= + ((H.dilate hq).field (D.base.dilate hq) D.lower D.upper hc hcr).value i T + exact (congrArg (q*·) (h i _)).trans (H.dilate_field hq D.base D.lower D.upper hc hcr i T).symm +end BData + +namespace BState.Histories +open MeasureTheory +variable {κ : ℝ} {lam : ℝ≥0} {Ω : Type*} [MeasurableSpace Ω] {μ : Measure Ω} +variable {S : BState M κ lam Ω μ} {hc : 0 hi (h.symm.trans hs) + simp only [radialValue,dite_eq_right hi,dite_eq_right hs] +lemma radialField_reRoot (h : (M.activeGraph I).Reachable s r) (o : M.Point I r) : + (o.reRoot h).radialField=o.radialField := by + apply Field.ext_value + funext i H + exact radialValue_reRoot h o i H +end Point + +namespace Field +variable {F : M.Field I 1} {ε : ℝ} +@[simp] lemma eval_reRoot (F : M.Field I 1) (h : (M.activeGraph I).Reachable s r) + (x : M.Point I r) : F.eval (x.reRoot h)=F.eval x := rfl + +def BandDescent.reRoot (h : (M.activeGraph I).Reachable s r) {x : M.Point I r} + (D : F.BandDescent J x ε) : F.BandDescent J (x.reRoot h) ε where + start_in := D.start_in + target := D.target.reRoot h + target_in := D.target_in + path := D.path + shortest := D.shortest + lower := D.lower + upper := D.upper + drop := D.drop + +lemma NoLowCircular.reRoot (h : (M.activeGraph I).Reachable s r) + {x y : M.Point I r} {j : ℝ} (H : F.NoLowCircular x y J j) : + F.NoLowCircular (x.reRoot h) (y.reRoot h) J j := by + intro v b hv hs hn ht hd + have hd' : dist x (v.reRoot h.symm)≤1 ∨ dist y (v.reRoot h.symm)≤1 := by + have hx := Point.dist_coordinates (x.reRoot h) v x (v.reRoot h.symm) rfl rfl rfl rfl + have hy := Point.dist_coordinates (y.reRoot h) v y (v.reRoot h.symm) rfl rfl rfl rfl + simpa only [hx,hy] using hd + exact H (v.reRoot h.symm) b hv hs hn ht hd' + +lemma constant_no_descent (c ε : ℝ) (hε : ε < (1:ℝ)/100000) (x : M.Point I r) : + ¬Nonempty ((constant M I c).BandDescent J x ε) := by + rintro ⟨D⟩ + have hd := D.drop + change c≤c-D.path.length x.height D.target.height+ε at hd + linarith [D.lower] +end Field +namespace OrdinaryData +/-- Constant ordinary charts cannot survive the genuine descending-path test. +A surviving source is relocated to the bookkeeping root of the current band. -/ +lemma source_of_descent (D : OrdinaryData M) {root : Fin n} + (x : M.Point D.band root) (hx : D.Contains x.column x.height) + {ε : ℝ} (hε : ε < (1:ℝ)/100000) + (hd : Nonempty (D.comparison.BandDescent J x ε)) : + ∃ o : M.Point D.band root, D.comparison=o.radialField := by + cases ho : D.origin with + | none => + have hh : ¬Nonempty (D.comparison.BandDescent J x ε) := by + simpa only [comparison,ho] using Field.constant_no_descent (M := M) 0 ε hε x + exact (hh hd).elim + | some o => + have hr := x.reachable.trans (hx.2 o.1 o.2 ho).symm + refine ⟨o.2.reRoot hr,?_⟩ + rw [Point.radialField_reRoot] + simp only [comparison,ho] +end OrdinaryData +end PlanarL1.Columns.Model + +end + +end OAI diff --git a/lean/OAI/Combinatorics/PlanarL1/Schedule.lean b/lean/OAI/Combinatorics/PlanarL1/Schedule.lean new file mode 100644 index 0000000000000000000000000000000000000000..05a79398a4f56bd7b64119d606f92e37ff04a737 --- /dev/null +++ b/lean/OAI/Combinatorics/PlanarL1/Schedule.lean @@ -0,0 +1,523 @@ +import OAI.Combinatorics.PlanarL1.CutExtraction + +namespace OAI + + +section + +namespace PlanarL1.Parameters +open scoped NNReal +noncomputable def persistenceSlope : ℝ := + 2/a₁+2/a₂+(mainN:ℝ)^2*(4*(mainK:ℝ)/mainQ+4*(mainK:ℝ)/EA)+ + (1+Columns.Model.SurvivingGroups.packBound*secondaryN : ℕ)^2* + (4*(secondaryK:ℝ)/secondaryQ+4*(secondaryK:ℝ)/EB) +noncomputable def persistenceCount : ℝ := + 4+2*(mainN:ℝ)^2+2*(1+Columns.Model.SurvivingGroups.packBound*secondaryN : ℕ)^2 +lemma persistenceSlope_nonneg : 0 ≤ persistenceSlope := by + unfold persistenceSlope + apply add_nonneg + · apply add_nonneg + · exact add_nonneg (div_nonneg (by norm_num) interpolationA.2.1.le) (div_nonneg (by norm_num) interpolationB.2.1.le) + · apply mul_nonneg (sq_nonneg _) + exact add_nonneg (div_nonneg (mul_nonneg (by norm_num) (NNReal.coe_nonneg _)) mainQ_pos.le) + (div_nonneg (mul_nonneg (by norm_num) (NNReal.coe_nonneg _)) interpolationA.1.le) + · apply mul_nonneg (sq_nonneg _) + exact add_nonneg (div_nonneg (mul_nonneg (by norm_num) (NNReal.coe_nonneg _)) secondaryQ_pos.le) + (div_nonneg (mul_nonneg (by norm_num) (NNReal.coe_nonneg _)) interpolationB.1.le) +lemma persistenceCount_pos : 0 < persistenceCount := by + unfold persistenceCount + have h1 := sq_nonneg (mainN:ℝ) + have h2 := sq_nonneg ((1+Columns.Model.SurvivingGroups.packBound*secondaryN : ℕ):ℝ) + linarith +lemma persistenceLoss_eq (ρ : ℝ) {m : ℕ} (hm : 0 < m) : + persistenceLoss ρ m=persistenceSlope*ρ+persistenceCount/m := by + have hm' : (m:ℝ)≠0 := Nat.cast_ne_zero.mpr (Nat.ne_of_gt hm) + have hA := (interpolationA.2.1).ne' + have hB := (interpolationB.2.1).ne' + have heA := interpolationA.1.ne' + have heB := interpolationB.1.ne' + have hqA := mainQ_pos.ne' + have hqB := secondaryQ_pos.ne' + unfold persistenceLoss heightLoss mainLoss mainTestLoss secondaryLoss secondaryTestLoss persistenceSlope persistenceCount + field_simp + ring + +/-- A single universal integer spacing. It is independent of the graph, its +edge lengths, the number of scales, and every finite random grid. -/ +def GoodSpacing (Q : ℝ) : Prop := + 2 ≤ Q ∧ 10 ≤ (R/200)*Q ∧ 20/Q ≤ persistenceRadius ∧ + 20*persistenceSlope/(Q-1) ≤ 1/4 ∧ 3/(Q-1) ≤ successGain/2 +lemma exists_goodSpacing : ∃ q : ℕ, GoodSpacing q := by + obtain ⟨q,hq⟩ := exists_nat_gt (max 2 (max (2000/R) (max (20/persistenceRadius+1) + (max (80*persistenceSlope+1) (6/successGain+1))))) + have h2 : (2:ℝ) (F x).bind G) := by + induction E with + | pure x => rfl + | choose n E ih => simp only [bind]; congr; funext i; exact ih i + +def iterate (F : α → Execution α) (E : Execution α) : ℕ → Execution α + | 0 => E + | n+1 => (iterate F E n).bind F +lemma iterate_add (F : α → Execution α) (E : Execution α) (a b : ℕ) : + iterate F E (a+b)=iterate F (iterate F E a) b := by + induction b with + | zero => rfl + | succ b ih => + change (iterate F E (a+b)).bind F=(iterate F (iterate F E a) b).bind F + rw [ih] +lemma Holds.iterate {F : α → Execution α} {E : Execution α} {P : ℕ → α → Prop} + (hE : E.Holds (P 0)) (h : ∀ n x, P n x → (F x).Holds (P (n+1))) (n : ℕ) : + (iterate F E n).Holds (P n) := by + induction n with + | zero => exact hE + | succ n ih => exact ih.bind F (h n) +lemma Holds.and {E : Execution α} {P Q : α → Prop} (hP : E.Holds P) (hQ : E.Holds Q) : + E.Holds (fun x => P x ∧ Q x) := by + induction E with + | pure x => exact ⟨hP,hQ⟩ + | choose n E ih => exact fun i => ih i (hP i) (hQ i) +lemma prob_iterate_monotone (F : α → Execution α) (E : Execution α) (P : ℕ → α → Prop) + (h : ∀ n x, P n x → (F x).Holds (P (n+1))) (N : ℕ) : + E.prob (P 0) ≤ (iterate F E N).prob (P N) := by + induction N with + | zero => rfl + | succ N ih => + have hh := conditional_success (iterate F E N) F (P N) (P (N+1)) (p := 1) + (fun x hx => (h N x hx).prob_eq_one.ge) + simp only [one_mul] at hh + exact ih.trans hh +lemma iterate_loss (F : α → Execution α) (E : Execution α) (P : ℕ → α → Prop) + (ε : ℕ → ℝ) (N : ℕ) (hε : ∀ n ¬P (n+1) y) ≤ ε n) : + (iterate F E N).prob (fun x => ¬P N x) ≤ + E.prob (fun x => ¬P 0 x)+∑ n ∈ Finset.range N, ε n := by + induction N with + | zero => simp only [iterate,Finset.range_zero,Finset.sum_empty,add_zero,le_refl] + | succ N ih => + have hh := conditional_loss (iterate F E N) F (P N) (P (N+1)) + (hε N (Nat.lt_succ_self N)) (h N (Nat.lt_succ_self N)) + have ih' := ih (fun n hn => hε n (Nat.lt_succ_of_lt hn)) (fun n hn => h n (Nat.lt_succ_of_lt hn)) + simp only [iterate] at hh ⊢ + rw [Finset.sum_range_succ] + linarith +lemma Holds.prob_compl_zero {E : Execution α} {P : α → Prop} (h : E.Holds P) : E.prob (fun x => ¬P x)=0 := by + rw [E.prob_compl P,h.prob_eq_one,sub_self] +end PlanarL1.Execution + +end + + + +section + +namespace PlanarL1.Parameters +noncomputable def targetRadius (Q : ℝ) (f n : ℕ) : ℝ := 20*Q^n/Q^f +lemma targetRadius_nonneg {Q : ℝ} (hQ : 0 < Q) (f n : ℕ) : 0 ≤ targetRadius Q f n := by + unfold targetRadius + positivity +lemma targetRadius_self {Q : ℝ} (hQ : 0 < Q) (f : ℕ) : targetRadius Q f f=20 := by + unfold targetRadius + exact mul_div_cancel_right₀ _ (pow_ne_zero _ hQ.ne') +lemma targetRadius_succ (Q : ℝ) (f n : ℕ) : targetRadius Q f (n+1)=Q*targetRadius Q f n := by + unfold targetRadius + rw [pow_succ] + ring +lemma targetRadius_small {Q : ℝ} (hQ : 1 < Q) {f n : ℕ} (hn : n Z.step g.pos g.one g.gap hm) (.pure W) n + +def Distances (n : ℕ) (Z : World k V Q) : Prop := ∀ x y, Z.distance x y=Q^n*W.distance x y +omit [Fintype V] in +lemma distances_zero : W.Distances 0 W := by intro x y; simp [distance] +lemma next_distances {n : ℕ} {Z : World k V Q} (h : W.Distances n Z) : + (Z.step g.pos g.one g.gap hm).Holds (W.Distances (n+1)) := by + apply (Z.step_distances g.pos g.one g.gap hm).mono + intro T hT x y + rw [hT,h,pow_succ] + ring +lemma run_distances (n : ℕ) : (W.run g hm n).Holds (W.Distances n) := + Execution.Holds.iterate (E := .pure W) (P := W.Distances) W.distances_zero + (fun _ _ h => W.next_distances g hm h) n + +def TargetGood (f : ℕ) (x : V) (n : ℕ) (Z : World k V Q) : Prop := + W.Distances n Z ∧ Z.Coherent x (targetRadius Q f n) +lemma target_failure {f n : ℕ} (hn : n ¬W.TargetGood f x (n+1) T) ≤ + persistenceLoss (targetRadius Q f n) m := by + have hp := Z.step_persistence g.pos g.one g.gap hm (targetRadius_nonneg g.pos f n) + ((targetRadius_small g.gt_one hn).trans g.2.2.1) h.2 + rw [← targetRadius_succ] at hp + apply le_trans ?_ hp + apply Execution.Holds.prob_mono + apply (W.next_distances g hm h.1).mono + intro T ht hn + exact fun hc => hn ⟨ht,hc⟩ +lemma run_target_failure {f : ℕ} {x : V} (hstart : W.Coherent x (targetRadius Q f 0)) + (hmesh : (f:ℝ)*persistenceCount/m ≤ 1/4) : + (W.run g hm f).prob (fun Z => ¬W.TargetGood f x f Z) ≤ 1/2 := by + have h0 : (Execution.pure W).Holds (W.TargetGood f x 0) := ⟨W.distances_zero,hstart⟩ + have hh := Execution.iterate_loss (fun Z : World k V Q => Z.step g.pos g.one g.gap hm) + (.pure W) (W.TargetGood f x) (fun n => persistenceLoss (targetRadius Q f n) m) f + (fun n hn => by + rw [persistenceLoss_eq _ hm] + exact add_nonneg (mul_nonneg persistenceSlope_nonneg (targetRadius_nonneg g.pos f n)) + (div_nonneg persistenceCount_pos.le (Nat.cast_nonneg m))) + (fun n hn Z hZ => W.target_failure g hm hn hZ) + rw [h0.prob_compl_zero,zero_add] at hh + exact hh.trans (sum_persistenceLoss g hm f hmesh) +lemma run_success_probability {f : ℕ} {x y : V} (hstart : W.Coherent x (targetRadius Q f 0)) + (hmesh : (f:ℝ)*persistenceCount/m ≤ 1/4) (hmany : 10000 ≤ m) + (hlo : 1 ≤ Q^f*W.distance x y) (hhi : Q^f*W.distance x y < 2) : + successChance/2 ≤ (W.run g hm (f+1)).prob (fun Z => Z.Successful (Q*successGain) x y) := by + have hf := W.run_target_failure g hm hstart hmesh + rw [Execution.prob_compl] at hf + have hh := Execution.conditional_success (W.run g hm f) + (fun Z : World k V Q => Z.step g.pos g.one g.gap hm) (W.TargetGood f x f) + (fun Z => Z.Successful (Q*successGain) x y) (p := successChance) (by + intro Z hZ + apply Z.step_success g.pos g.one g.gap hm hmany + · simpa only [targetRadius_self g.pos] using hZ.2 + · rw [hZ.1]; exact hlo + · rw [hZ.1]; exact hhi) + have hp := mul_le_mul_of_nonneg_left (show 1/2≤(W.run g hm f).prob (W.TargetGood f x f) by linarith) successChance_pos.le + have hp' : successChance/2 ≤ successChance*(W.run g hm f).prob (W.TargetGood f x f) := by + nlinarith + exact hp'.trans hh +lemma run_add (a b : ℕ) : W.run g hm (a+b)= + Execution.iterate (fun Z : World k V Q => Z.step g.pos g.one g.gap hm) (W.run g hm a) b := + Execution.iterate_add _ _ _ _ +lemma run_survival_probability {f : ℕ} {x y : V} (hstart : W.Coherent x (targetRadius Q f 0)) + (hmesh : (f:ℝ)*persistenceCount/m ≤ 1/4) (hmany : 10000 ≤ m) + (hlo : 1 ≤ Q^f*W.distance x y) (hhi : Q^f*W.distance x y < 2) (t : ℕ) : + successChance/2 ≤ (W.run g hm (f+1+t)).prob (fun Z => Z.Successful (survivalBudget Q t) x y) := by + rw [W.run_add g hm] + apply le_trans (W.run_success_probability g hm hstart hmesh hmany hlo hhi) + have hh := Execution.prob_iterate_monotone (fun Z : World k V Q => Z.step g.pos g.one g.gap hm) + (W.run g hm (f+1)) (fun n Z => Z.Successful (survivalBudget Q n) x y) (by + intro n Z hZ + rw [survivalBudget_succ g.gt_one] + exact Z.step_survives g.pos g.one g.gap hm hZ) t + simpa only [survivalBudget_zero] using hh +end PlanarL1.Columns.Model.World + +end + + + +section + +namespace PlanarL1.Parameters +noncomputable def scheduleGain : ℝ := successChance*successGain/8 +lemma scheduleGain_pos : 0 < scheduleGain := div_pos (mul_pos successChance_pos successGain_pos) (by norm_num) +end PlanarL1.Parameters + +namespace PlanarL1.Columns.Model.World +open Parameters +variable {k : ℕ} {V : Type*} [Fintype V] {Q : ℝ} +variable (g : GoodSpacing Q) (W : World k V Q) {m : ℕ} (hm : 0 < m) +noncomputable def averagedCuts (N : ℕ) : FiniteL1.CutFamily V := + FiniteL1.CutFamily.average (W.run g hm N) World.cuts +lemma averagedCuts_upper (N : ℕ) (x y : V) : + (W.averagedCuts g hm N).distance x y ≤ 2*(Q^N*W.distance x y) := by + rw [averagedCuts,FiniteL1.CutFamily.distance_average,← Execution.mean_const (W.run g hm N) (2*(Q^N*W.distance x y))] + apply Execution.Holds.mean_mono + apply (W.run_distances g hm N).mono + intro Z hZ + exact (Z.cuts_upper x y).trans_eq (by rw [hZ]) +lemma averagedCuts_designated {f : ℕ} {x y : V} (hstart : W.Coherent x (targetRadius Q f 0)) + (hmesh : (f:ℝ)*persistenceCount/m ≤ 1/4) (hmany : 10000 ≤ m) + (hlo : 1 ≤ Q^f*W.distance x y) (hhi : Q^f*W.distance x y < 2) (t : ℕ) : + scheduleGain*(Q^(f+1+t)*W.distance x y) ≤ (W.averagedCuts g hm (f+1+t)).distance x y := by + have hQpos := g.pos + have hGain := successGain_pos + have hChance := successChance_pos + have hp := W.run_survival_probability g hm hstart hmesh hmany hlo hhi t + have hb := survivalBudget_lower g t + have hc : 0 ≤ Q^(t+1)*successGain/2 := by positivity + have hh := (W.run g hm (f+1+t)).mean_lower_of_event + (P := fun Z => Z.Successful (survivalBudget Q t) x y) + (f := fun Z => Z.cuts.distance x y) (c := Q^(t+1)*successGain/2) + (fun Z => FiniteL1.CutFamily.distance_nonneg _ _ _) (fun Z hZ => hb.trans hZ.cuts) + have hprod := mul_le_mul_of_nonneg_left hp hc + rw [averagedCuts,FiniteL1.CutFamily.distance_average] + apply le_trans ?_ (hprod.trans hh) + have he : Q^(f+1+t)=Q^(t+1)*Q^f := by + rw [← pow_add] + congr 1 + omega + rw [he] + calc + _ = (Q^(t+1)*successChance*successGain/8)*(Q^f*W.distance x y) := by unfold scheduleGain; ring + _ ≤ (Q^(t+1)*successChance*successGain/8)*2 := + mul_le_mul_of_nonneg_left hhi.le (by positivity) + _ = _ := by ring +lemma averagedCuts_lower {N f : ℕ} (hf : f A.scaleEquiv hσ (v x)) +omit [Fintype V] in +lemma startAt_distance (x y : V) : (startAt (Q := Q) A v hσ).distance x y=σ*dist (v x) (v y) := + A.scaleEquiv_dist hσ _ _ +omit [Fintype V] in +lemma startAt_coherent (x : V) (ρ : ℝ) : (startAt (Q := Q) A v hσ).Coherent x ρ := + initial_coherent _ _ _ _ +noncomputable def normalizedCuts (N : ℕ) : FiniteL1.CutFamily V := + FiniteL1.CutFamily.scale ((Q^N*σ)⁻¹) (inv_nonneg.mpr (mul_pos (pow_pos g.pos N) hσ).le) + ((startAt (Q := Q) A v hσ).averagedCuts g hm N) +omit [Fintype V] in +include g hσ in +lemma normalization_cancel (N : ℕ) (c d : ℝ) : + (Q^N*σ)⁻¹*(c*(Q^N*(σ*d)))=c*d := by + calc + _ = ((Q^N*σ)⁻¹*(Q^N*σ))*(c*d) := by ring + _ = _ := by rw [inv_mul_cancel₀ (mul_pos (pow_pos g.pos N) hσ).ne',one_mul] +lemma normalizedCuts_upper (N : ℕ) (x y : V) : + (normalizedCuts g A v hσ hm N).distance x y ≤ 2*dist (v x) (v y) := by + rw [normalizedCuts,FiniteL1.CutFamily.distance_scale] + have hh := (startAt (Q := Q) A v hσ).averagedCuts_upper g hm N x y + rw [startAt_distance] at hh + exact (mul_le_mul_of_nonneg_left hh (inv_nonneg.mpr (mul_pos (pow_pos g.pos N) hσ).le)).trans_eq + (normalization_cancel g hσ N 2 _) +lemma normalizedCuts_lower {N f : ℕ} (hf : f simp only [he,pow_zero,one_mul] at hf; linarith + | succ n => + have hn : n Finset.sum_nonneg (fun y _ => hd x y)) + have hb (x y : V) : d x y≤B := + (Finset.single_le_sum (fun z _ => hd x z) (Finset.mem_univ y)).trans + (Finset.single_le_sum (fun z _ => Finset.sum_nonneg (fun w _ => hd z w)) (Finset.mem_univ x)) + let ε : ℝ := 1/(B+1) + have hε : 0<ε := by unfold ε; positivity + have hsmall (x y : V) : ε*d x y<1 := by + change (1/(B+1))*d x y<1 + rw [one_div,mul_comm,← div_eq_mul_inv] + apply (div_lt_iff₀ (show 0 ?_⟩ + exact ((div_lt_iff₀ (mul_pos hε hp)).mp hn).le + · exact ⟨0,fun hh => (hp hh).elim⟩ + choose bound hbound using hex + let T : ℕ := ∑ x, ∑ y, bound x y + have ht (x y : V) : bound x y≤T := + (Finset.single_le_sum (fun z _ => Nat.zero_le _) (Finset.mem_univ y)).trans + (Finset.single_le_sum (f := fun z => ∑ w, bound z w) (fun z _ => Nat.zero_le _) (Finset.mem_univ x)) + refine ⟨ε,hε,T+1,?_⟩ + intro x y hxy + have hT : 1≤(q:ℝ)^T*(ε*d x y) := (hbound x y hxy).trans + (mul_le_mul_of_nonneg_right (pow_le_pow_right₀ hq.le (ht x y)) (mul_pos hε hxy).le) + obtain ⟨f,hf,hlo,hhi⟩ := first_scale hq (hsmall x y) hT + obtain ⟨i,hil,hih⟩ := integer_offset hlo hhi + refine ⟨i,f,Nat.lt_succ_of_le hf,?_,?_⟩ + · convert hil using 1; ring + · convert hih using 1; ring +end PlanarL1.Parameters + +end + +end OAI diff --git a/lean/OAI/Combinatorics/PlanarL1/SecondaryBatch.lean b/lean/OAI/Combinatorics/PlanarL1/SecondaryBatch.lean new file mode 100644 index 0000000000000000000000000000000000000000..9a45a1521dcab0feb367a6e3b16bd0b5aae31b26 --- /dev/null +++ b/lean/OAI/Combinatorics/PlanarL1/SecondaryBatch.lean @@ -0,0 +1,493 @@ +import OAI.Combinatorics.PlanarL1.SecondaryStep +import OAI.Combinatorics.PlanarL1.MainStep + +namespace OAI + +section + +namespace PlanarL1.Columns.Model.BState +open MeasureTheory Set +open scoped NNReal +open PlanarL1.Interpolation +attribute [local instance] Classical.propDecidable +variable {k : ℕ} {M : Model (k+1)} {κ : ℝ} {lam : ℝ≥0} + {Ω : Type*} [MeasurableSpace Ω] {μ : Measure Ω} + +/-- All kept groups with one old identifier and one common orientation. Their +closed domains may overlap in regions where several clippings act. -/ +structure SecondaryBatch (S : BState M κ lam Ω μ) where + index : Fin (S.count+1) + positive : Bool + lambda_bound : lam ≤ (1:ℝ≥0)/100 + count : ℕ + band : Fin count → Set ℝ + root : Fin count → Fin (k+1) + step : ∀ q, SecondaryStep S (band q) (root q) + same_index : ∀ q, (step q).index=index + same_positive : ∀ q, (step q).positive=positive + kappa_nonneg : 0 ≤ κ + kappa_five : κ*5 ≤ 1 + +namespace SecondaryBatch +variable {S : BState M κ lam Ω μ} (B : SecondaryBatch S) + +noncomputable def data : BData M := S.chart B.index +noncomputable def comparison : M.Field B.data.band 5 := B.data.comparison lam B.lambda_bound B.positive + +lemma step_data (q : Fin B.count) : (B.step q).data=B.data := by + simp only [SecondaryStep.data,data,B.same_index] + +noncomputable def groupHeight (q : Fin B.count) (H : B.data.band) : (B.step q).data.band := + ⟨H.val,by rw [B.step_data]; exact H.property⟩ + +lemma step_comparison (q : Fin B.count) (i : Fin (k+1)) (H : B.data.band) : + (B.step q).comparison.value i (B.groupHeight q H)=B.comparison.value i H := by + have transport (D E : BData M) (he : D=E) (p r : Bool) (hp : p=r) + (hl hl' : lam ≤ (1:ℝ≥0)/100) (T : E.band) : + (D.comparison lam hl p).value i ⟨T.val,by rw [he]; exact T.property⟩ = + (E.comparison lam hl' r).value i T := by + subst E + subst r + rfl + exact transport (B.step q).data B.data (B.step_data q) + (B.step q).positive B.positive (B.same_positive q) (B.step q).lambda_bound B.lambda_bound H + +noncomputable def groupNamed (q : Fin B.count) (i : Fin (k+1)) (H : B.data.band) : NamedValue := + ⟨((B.step q).fullNamed i (B.groupHeight q H)).name, + κ*((B.step q).fullNamed i (B.groupHeight q H)).value⟩ + +noncomputable def selected (i : Fin (k+1)) : B.data.band → NamedValue := + familySelection (fun H => κ*B.comparison.value i H) (fun q => B.groupNamed q i) + +lemma groupNamed_value (q : Fin B.count) (i : Fin (k+1)) (H : B.data.band) : + (B.groupNamed q i H).value=κ*(B.step q).fullReplacement i (B.groupHeight q H) := by + simp only [groupNamed,SecondaryStep.fullNamed_value] + +lemma comparison_scaled (i : Fin (k+1)) : + LipschitzWith 1 (fun H : B.data.band => κ*B.comparison.value i H) := by + apply LipschitzWith.of_dist_le_mul + intro H T + have h := (B.comparison.vertical i).dist_le_mul H T + rw [Real.dist_eq] at h ⊢ + rw [← mul_sub,abs_mul,abs_of_nonneg B.kappa_nonneg] + calc + _ ≤ κ*(5*dist H T) := mul_le_mul_of_nonneg_left h B.kappa_nonneg + _ = (κ*5)*dist H T := by ring + _ ≤ 1*dist H T := mul_le_mul_of_nonneg_right B.kappa_five dist_nonneg + _ = _ := by simp + +lemma groupNamed_vertical (q : Fin B.count) (i : Fin (k+1)) : + LipschitzWith 1 (fun H : B.data.band => (B.groupNamed q i H).value) := by + apply LipschitzWith.of_dist_le_mul + intro H T + simp only [B.groupNamed_value] + exact ((B.step q).fullReplacement_scaled_vertical i).dist_le_mul (B.groupHeight q H) (B.groupHeight q T) + +lemma selected_vertical (i : Fin (k+1)) : + LipschitzWith 1 (fun H : B.data.band => (B.selected i H).value) := + familySelection_lipschitz _ _ (B.comparison_scaled i) (fun q => B.groupNamed_vertical q i) + +lemma groupNamed_switch (q : Fin B.count) (i j : Fin (k+1)) (H : B.data.band) + (hs : H.val ∈ M.heights i j) : B.groupNamed q i H=B.groupNamed q j H := by + unfold groupNamed + rw [(B.step q).fullNamed_switch i j (B.groupHeight q H) hs] + +lemma selected_switch (i j : Fin (k+1)) (H : B.data.band) + (hs : H.val ∈ M.heights i j) : B.selected i H=B.selected j H := by + have hm (old : B.data.band → NamedValue) (L : List (B.data.band → NamedValue)) : + maxSelection old L H=(L.map (fun f => f H)).foldr maxNamed (old H) := by + induction L with + | nil => rfl + | cons f L ih => simp only [maxSelection,List.map_cons,List.foldr_cons,ih] + unfold selected familySelection + rw [hm,hm] + simp only [List.map_ofFn,Function.comp_def,B.comparison.switch i j H hs] + congr 2 + funext q + rw [B.groupNamed_switch q i j H hs] + +noncomputable def domain (i : Fin (k+1)) : Set ℝ := + ⋃ q : Fin B.count, SecondaryCell.domain (B.step q).seeds (B.step q).radius i + +lemma mem_domain {i : Fin (k+1)} {H : ℝ} : H ∈ B.domain i ↔ + ∃ q, H ∈ SecondaryCell.domain (B.step q).seeds (B.step q).radius i := mem_iUnion + +lemma domain_closed (i : Fin (k+1)) : IsClosed (B.domain i) := + isClosed_iUnion_of_finite (fun q => (SecondaryCell.compact_domain (B.step q).seeds + (B.step q).radius (B.step q).compact_band i).isClosed) + +lemma domain_band {i : Fin (k+1)} {H : ℝ} (hd : H ∈ B.domain i) : H ∈ B.data.band := by + obtain ⟨q,hq⟩ := B.mem_domain.mp hd + rw [← B.step_data q] + exact (B.step q).sub_old (SecondaryCell.inBand_of_mem _ _ hq) + +lemma domain_name {i : Fin (k+1)} {H : ℝ} (hd : H ∈ B.domain i) : S.name i H=B.index := by + obtain ⟨q,hq⟩ := B.mem_domain.mp hd + exact ((B.step q).same_name i H hq).trans (B.same_index q) + +lemma domain_switch {i j : Fin (k+1)} {H : ℝ} (hs : H ∈ M.heights i j) + (hd : H ∈ B.domain i) : H ∈ B.domain j := by + obtain ⟨q,hq⟩ := B.mem_domain.mp hd + exact B.mem_domain.mpr ⟨q,SecondaryCell.switch_mem _ _ hs hq⟩ + +lemma group_frontier {i : Fin (k+1)} {H : ℝ} (hf : H ∈ frontier (B.domain i)) + (q : Fin B.count) (hq : H ∈ SecondaryCell.domain (B.step q).seeds (B.step q).radius i) : + H ∈ frontier (SecondaryCell.domain (B.step q).seeds (B.step q).radius i) := by + refine ⟨subset_closure hq,?_⟩ + intro ht + exact hf.2 (interior_mono (subset_iUnion (fun q : Fin B.count => + SecondaryCell.domain (B.step q).seeds (B.step q).radius i) q) ht) + +lemma selected_same {i : Fin (k+1)} (H : B.data.band) + (h : ∀ q, (B.groupNamed q i H).value=κ*B.comparison.value i H) : + (B.selected i H).value=κ*B.comparison.value i H := by + rcases maxSelection_mem (fun H => ⟨0,κ*B.comparison.value i H⟩) + (List.ofFn (fun q => fun H => ⟨familyName q (B.groupNamed q i H).name,(B.groupNamed q i H).value⟩)) H with ho | ⟨F,hF,hFv⟩ + · exact congrArg NamedValue.value ho + · obtain ⟨q,rfl⟩ := List.mem_ofFn.mp hF + exact (congrArg NamedValue.value hFv).trans (h q) + +lemma selected_frontier {i : Fin (k+1)} {H : ℝ} (hf : H ∈ frontier (B.domain i)) : + (B.selected i ⟨H,B.domain_band ((B.domain_closed i).frontier_subset hf)⟩).value= + κ*B.comparison.value i ⟨H,B.domain_band ((B.domain_closed i).frontier_subset hf)⟩ := by + apply B.selected_same + intro q + rw [B.groupNamed_value] + by_cases hq : H ∈ SecondaryCell.domain (B.step q).seeds (B.step q).radius i + · rw [(B.step q).fullReplacement_inside _ _ hq] + change κ*(B.step q).replacement (SecondaryCell.point (B.step q).seeds (B.step q).radius i H hq)=_ + rw [(B.step q).replacement_frontier (B.group_frontier hf q hq) hq,(B.step q).point_old hq] + congr 1 + exact B.step_comparison q i ⟨H,B.domain_band ((B.domain_closed i).frontier_subset hf)⟩ + · rw [(B.step q).fullReplacement_outside _ _ hq,B.step_comparison] + +noncomputable def converted (i : Fin (k+1)) (H : ℝ) : ℝ := + if h : H ∈ B.data.band then κ*B.data.offset+B.data.orientation B.positive*(B.selected i ⟨H,h⟩).value else 0 + +lemma converted_on (i : Fin (k+1)) (H : ℝ) (h : H ∈ B.data.band) : + B.converted i H=κ*B.data.offset+B.data.orientation B.positive*(B.selected i ⟨H,h⟩).value := dite_eq_left h + +lemma converted_vertical (i : Fin (k+1)) : LipschitzOnWith 1 (B.converted i) (B.domain i) := by + apply LipschitzOnWith.of_dist_le_mul + intro H hH T hT + rw [B.converted_on i H (B.domain_band hH),B.converted_on i T (B.domain_band hT)] + have h := (B.selected_vertical i).dist_le_mul ⟨H,B.domain_band hH⟩ ⟨T,B.domain_band hT⟩ + rw [Real.dist_eq] at h ⊢ + simp only [add_sub_add_left_eq_sub,← mul_sub,abs_mul,B.data.orientation_unit,one_mul] + exact h + +noncomputable def patch : SetPatch S.lift.sets := by + apply Threshold.chartPatch S.lift.sets (S.labels B.index).lift B.domain B.domain_closed + B.converted B.converted_vertical + · intro ω i H hf + have hd := (B.domain_closed i).frontier_subset hf + have hb := B.domain_band hd + rw [B.converted_on i H hb,B.selected_frontier hf] + have he := B.data.comparison_convert lam B.lambda_bound B.positive i ⟨H,hb⟩ + have hr := S.represents_named ω.1 i H B.index (B.domain_name hd) hb + change Threshold.active (S.labels B.index) H _ ω.1 ↔ (S.sets.activity ω.1).active i H + have hv : κ*B.data.offset+B.data.orientation B.positive*(κ*B.comparison.value i ⟨H,hb⟩)= + κ*B.data.value lam i ⟨H,hb⟩ := by + rw [he] + change _=κ*(B.data.offset+B.data.orientation B.positive*B.comparison.value i ⟨H,hb⟩) + ring + rw [hv] + exact hr.symm + · intro i j H hs hi hj + rw [B.converted_on i H (B.domain_band hi),B.converted_on j H (B.domain_band hj),B.selected_switch i j _ hs] + · intro ω i j H hs hi hj + exact (hj (B.domain_switch hs hi)).elim + +lemma selected_cases (i : Fin (k+1)) (H : B.data.band) : + B.selected i H=⟨0,κ*B.comparison.value i H⟩ ∨ + ∃ q, B.selected i H=⟨familyName q (B.groupNamed q i H).name,(B.groupNamed q i H).value⟩ := by + rcases maxSelection_mem (fun H => ⟨0,κ*B.comparison.value i H⟩) + (List.ofFn (fun q => fun H => ⟨familyName q (B.groupNamed q i H).name,(B.groupNamed q i H).value⟩)) H with ho | ⟨F,hF,hFv⟩ + · exact Or.inl ho + · obtain ⟨q,rfl⟩ := List.mem_ofFn.mp hF + exact Or.inr ⟨q,hFv⟩ + +lemma selected_zero (i : Fin (k+1)) (H : B.data.band) (hz : (B.selected i H).name=0) : + (B.selected i H).value=κ*B.comparison.value i H := by + rcases B.selected_cases i H with ho | ⟨q,hq⟩ + · exact congrArg NamedValue.value ho + · have hn : (B.groupNamed q i H).name=0 := by + by_contra hn + exact familyName_ne_zero q hn ((congrArg NamedValue.name hq).symm.trans hz) + have hv := (B.step q).fullNamed_zero i (B.groupHeight q H) hn + have hm := congrArg NamedValue.value hq + change (B.selected i H).value=κ*((B.step q).fullNamed i (B.groupHeight q H)).value at hm + rw [hm,hv,B.step_comparison] + +abbrev NewIndex := Σ q : Fin B.count, Fin (3*(k+1)*(B.step q).tree.depthCap+2) +noncomputable instance : Fintype B.NewIndex := inferInstanceAs (Fintype (Sigma _)) + +noncomputable def chosen (i : Fin (k+1)) (H : ℝ) (a : B.NewIndex) : Prop := + ∃ hb : H ∈ B.data.band, (B.step a.1).choose i H=some a.2 ∧ + B.selected i ⟨H,hb⟩=⟨familyName a.1 (a.2.val+1),(B.groupNamed a.1 i ⟨H,hb⟩).value⟩ + +noncomputable def choose (i : Fin (k+1)) (H : ℝ) : Option B.NewIndex := + if h : ∃ a, B.chosen i H a then some h.choose else none + +lemma choose_some (i : Fin (k+1)) (H : ℝ) (a : B.NewIndex) + (ha : B.choose i H=some a) : B.chosen i H a := by + unfold choose at ha + split_ifs at ha with h + · have he : h.choose=a := Option.some.inj ha + exact he ▸ h.choose_spec + +lemma none_no_chosen (i : Fin (k+1)) (H : ℝ) (hn : B.choose i H=none) : + ¬∃ a, B.chosen i H a := by + intro h + simp only [choose,dite_eq_left h] at hn + cases hn + +lemma exists_chosen (i : Fin (k+1)) (H : B.data.band) (hn : (B.selected i H).name ≠ 0) : + ∃ a, B.chosen i H.val a := by + rcases B.selected_cases i H with ho | ⟨q,hq⟩ + · exact (hn (congrArg NamedValue.name ho)).elim + · have hqn : ((B.step q).fullNamed i (B.groupHeight q H)).name ≠ 0 := by + intro hz + have hn' := congrArg NamedValue.name hq + change (B.selected i H).name=familyName q ((B.step q).fullNamed i (B.groupHeight q H)).name at hn' + rw [hz,familyName_zero] at hn' + exact hn hn' + obtain ⟨a,ha,hname,hd⟩ := (B.step q).fullNamed_choice i (B.groupHeight q H) hqn + refine ⟨(⟨q,a⟩ : B.NewIndex),H.property,ha,?_⟩ + change B.selected i H=⟨familyName q (a.val+1),(B.groupNamed q i H).value⟩ + rw [hq] + change (NamedValue.mk (familyName q ((B.step q).fullNamed i (B.groupHeight q H)).name) + (B.groupNamed q i H).value)=_ + rw [hname] + +lemma chosen_switch (i j : Fin (k+1)) (H : ℝ) (hs : H ∈ M.heights i j) (a : B.NewIndex) : + B.chosen i H a ↔ B.chosen j H a := by + unfold chosen + apply exists_congr + intro hb + rw [(B.step a.1).choose_switch i j H hs,B.selected_switch i j ⟨H,hb⟩ hs, + B.groupNamed_switch a.1 i j ⟨H,hb⟩ hs] + +lemma choose_switch (i j : Fin (k+1)) (H : ℝ) (hs : H ∈ M.heights i j) : + B.choose i H=B.choose j H := by + have he : B.chosen i H=B.chosen j H := funext fun a => propext (B.chosen_switch i j H hs a) + unfold choose + simp only [he] + +noncomputable def newData (a : B.NewIndex) : BData M := (B.step a.1).newData a.2 +noncomputable def newLabels [SFinite μ] (a : B.NewIndex) : + Threshold.Variables (Ω × Bool) (μ.prod Threshold.fair) := (B.step a.1).newLabels a.2 + +lemma chosen_domain (i : Fin (k+1)) (H : ℝ) (a : B.NewIndex) (ha : B.chosen i H a) : + H ∈ SecondaryCell.domain (B.step a.1).seeds (B.step a.1).radius i := by + obtain ⟨hb,hc,he⟩ := ha + obtain ⟨hd,-⟩ := SecondaryCell.choose_spec (B.step a.1).tree (B.step a.1).seeds + (B.step a.1).old (B.step a.1).supportValue (B.step a.1).data.isOrdinary + (B.step a.1).pc (B.step a.1).radius (B.step a.1).ordered_offset (B.step a.1).shield_offset + (B.step a.1).lo (B.step a.1).noise i H a.2 hc + exact hd + +lemma converted_chosen (i : Fin (k+1)) (H : ℝ) (a : B.NewIndex) (ha : B.chosen i H a) : + B.converted i H=κ*((B.step a.1).data.offset+(B.step a.1).data.orientation (B.step a.1).positive* + (B.step a.1).replacement (SecondaryCell.point (B.step a.1).seeds (B.step a.1).radius i H + (B.chosen_domain i H a ha))) := by + obtain ⟨hb,hc,he⟩ := ha + have hv : (B.selected i ⟨H,hb⟩).value=κ*(B.step a.1).replacement + (SecondaryCell.point (B.step a.1).seeds (B.step a.1).radius i H + (B.chosen_domain i H a ⟨hb,hc,he⟩)) := by + calc + _ = (B.groupNamed a.1 i ⟨H,hb⟩).value := by + have h := congrArg NamedValue.value he + exact h + _ = κ*(B.step a.1).fullReplacement i (B.groupHeight a.1 ⟨H,hb⟩) := + B.groupNamed_value a.1 i ⟨H,hb⟩ + _ = _ := congrArg (κ*·) ((B.step a.1).fullReplacement_inside i + (B.groupHeight a.1 ⟨H,hb⟩) (B.chosen_domain i H a ⟨hb,hc,he⟩)) + simp only [B.converted_on i H hb,hv] + have hoff := congrArg BData.offset (B.step_data a.1) + have hor : (B.step a.1).data.orientation (B.step a.1).positive=B.data.orientation B.positive := by + rw [B.same_positive,B.step_data] + rw [hoff,hor] + change κ*B.data.offset+B.data.orientation B.positive*(κ*(B.step a.1).replacement _)=_ + ring + +lemma chosen_agreement (ω : Ω × Bool) (i : Fin (k+1)) (H : ℝ) (a : B.NewIndex) + (ha : B.chosen i H a) : + (B.patch.apply.activity ω).active i H ↔ ((B.step a.1).patch.apply.activity ω).active i H := by + have hd := B.chosen_domain i H a ha + apply (B.patch.inside (B.mem_domain.mpr ⟨a.1,hd⟩) ω).trans + change Threshold.active (S.labels B.index).lift H (B.converted i H) ω ↔ _ + rw [B.converted_chosen i H a ha] + have hp := (B.step a.1).patch_inside ω i H hd + rw [B.same_index] at hp + exact hp.symm + +lemma chosen_description [SFinite μ] (i : Fin (k+1)) (H : ℝ) (a : B.NewIndex) + (ha : B.chosen i H a) : + (H ∈ (B.newData a).band ∧ (B.newData a).Uses i) ∧ + ∀ (ω : Ω × Bool) (hi : H ∈ (B.newData a).band), + (B.patch.apply.activity ω).active i H ↔ + Threshold.active (B.newLabels a) H (κ*(B.newData a).value lam i ⟨H,hi⟩) ω := by + obtain ⟨hb,hc,he⟩ := ha + have h := (B.step a.1).chosen_description i H a.2 hc + refine ⟨h.1,fun ω hi => ?_⟩ + exact (B.chosen_agreement ω i H a ⟨hb,hc,he⟩).trans (h.2 ω hi) + +lemma unchosen (ω : Ω × Bool) (i : Fin (k+1)) (H : ℝ) (hn : B.choose i H=none) : + (B.patch.apply.activity ω).active i H ↔ (S.lift.sets.activity ω).active i H := by + by_cases hd : H ∈ B.domain i + · have hb := B.domain_band hd + have hz : (B.selected i ⟨H,hb⟩).name=0 := by + by_contra hz + exact B.none_no_chosen i H hn (B.exists_chosen i ⟨H,hb⟩ hz) + apply (B.patch.inside hd ω).trans + change Threshold.active (S.labels B.index).lift H (B.converted i H) ω ↔ _ + rw [B.converted_on i H hb,B.selected_zero i ⟨H,hb⟩ hz] + have he := B.data.comparison_convert lam B.lambda_bound B.positive i ⟨H,hb⟩ + have hr := S.represents_named ω.1 i H B.index (B.domain_name hd) hb + change Threshold.active (S.labels B.index) H _ ω.1 ↔ (S.sets.activity ω.1).active i H + have hv : κ*B.data.offset+B.data.orientation B.positive*(κ*B.comparison.value i ⟨H,hb⟩)= + κ*B.data.value lam i ⟨H,hb⟩ := by + rw [he] + change _=κ*(B.data.offset+B.data.orientation B.positive*B.comparison.value i ⟨H,hb⟩) + ring + rw [hv] + exact hr.symm + · exact B.patch.unchanged hd ω + +/-- Literal finite maximum of overlapping secondary proposals, with the exact +winning chart table and label variables. No sum over group movements is used. -/ +noncomputable def apply [SFinite μ] : BState M κ lam (Ω × Bool) (μ.prod Threshold.fair) := by + let e := Fintype.equivFin B.NewIndex + let pick : Fin (k+1) → ℝ → Option (Fin (Fintype.card B.NewIndex)) := + fun i H => (B.choose i H).map e + have hpick (i H a) (ha : pick i H=some a) : B.chosen i H (e.symm a) := by + obtain ⟨b,hb,hba⟩ := Option.map_eq_some_iff.mp ha + have he : b=e.symm a := by rw [← hba]; simp + exact he ▸ B.choose_some i H b hb + exact S.lift.append B.patch.apply (Fintype.card B.NewIndex) + (B.newData ∘ e.symm) (B.newLabels ∘ e.symm) pick + (fun i H a ha => (B.chosen_description i H (e.symm a) (hpick i H a ha)).1.1) + (fun i H a ha => (B.chosen_description i H (e.symm a) (hpick i H a ha)).1.2) + (fun i j H hs => congrArg (Option.map e) (B.choose_switch i j H hs)) + (fun ω i H ha => B.unchosen ω i H (Option.map_eq_none_iff.mp ha)) + (fun ω i H a ha => (B.chosen_description i H (e.symm a) (hpick i H a ha)).2 ω _) + +end SecondaryBatch +end PlanarL1.Columns.Model.BState + + +end + +section + +namespace PlanarL1.Columns.Model.BState +open MeasureTheory +open scoped NNReal +attribute [local instance] Classical.propDecidable +variable {k : ℕ} {M : Model (k+1)} {κ : ℝ} {lam : ℝ≥0} + {Ω : Type*} [MeasurableSpace Ω] {μ : Measure Ω} + +/-- The simultaneous secondary update, grouped by its actual old identifier. +Within an identifier we take a maximum, not disjoint patching. Distinct old +identifiers have disjoint domains because the old chart name is a function. -/ +structure SecondaryLayer (S : BState M κ lam Ω μ) where + batch : Fin (S.count+1) → SecondaryBatch S + same_index : ∀ q, (batch q).index=q + +namespace SecondaryLayer +variable {S : BState M κ lam Ω μ} (B : SecondaryLayer S) + +lemma overlap : (List.ofFn (fun q => (B.batch q).patch)).Pairwise SetPatch.UnchangedOverlap := by + apply List.pairwise_ofFn.mpr + intro q r hqr ω i H hq hr + have hq' := (B.batch q).domain_name hq + have hr' := (B.batch r).domain_name hr + rw [B.same_index] at hq' hr' + exact ((ne_of_lt hqr) (hq'.symm.trans hr')).elim + +abbrev NewIndex := Σ q : Fin (S.count+1), (B.batch q).NewIndex +noncomputable instance : Fintype B.NewIndex := inferInstanceAs (Fintype (Sigma _)) + +noncomputable def newData (a : B.NewIndex) : BData M := (B.batch a.1).newData a.2 +noncomputable def newLabels [SFinite μ] (a : B.NewIndex) : + Threshold.Variables (Ω × Bool) (μ.prod Threshold.fair) := (B.batch a.1).newLabels a.2 + +noncomputable def chosen (i : Fin (k+1)) (H : ℝ) (a : B.NewIndex) : Prop := + (B.batch a.1).choose i H=some a.2 + +noncomputable def choose (i : Fin (k+1)) (H : ℝ) : Option B.NewIndex := + if h : ∃ a, B.chosen i H a then some h.choose else none + +lemma choose_some (i : Fin (k+1)) (H : ℝ) (a : B.NewIndex) + (ha : B.choose i H=some a) : B.chosen i H a := by + unfold choose at ha + split_ifs at ha with h + · have he : h.choose=a := Option.some.inj ha + exact he ▸ h.choose_spec + +lemma choose_none (i : Fin (k+1)) (H : ℝ) (ha : B.choose i H=none) (q : Fin (S.count+1)) : + (B.batch q).choose i H=none := by + cases he : (B.batch q).choose i H with + | none => rfl + | some a => + have hex : ∃ a, B.chosen i H a := ⟨⟨q,a⟩,he⟩ + simp [choose,hex] at ha + +lemma choose_switch (i j : Fin (k+1)) (H : ℝ) (hs : H ∈ M.heights i j) : + B.choose i H=B.choose j H := by + have he : B.chosen i H=B.chosen j H := by + funext a + simp only [chosen,(B.batch a.1).choose_switch i j H hs] + unfold choose + simp only [he] + +noncomputable def sets : SetSystem M (Ω × Bool) (μ.prod Threshold.fair) := + SetPatch.batch (List.ofFn (fun q => (B.batch q).patch)) B.overlap + +lemma chosen_description [SFinite μ] (i : Fin (k+1)) (H : ℝ) (a : B.NewIndex) + (ha : B.chosen i H a) : + (H ∈ (B.newData a).band ∧ (B.newData a).Uses i) ∧ + ∀ (ω : Ω × Bool) (hi : H ∈ (B.newData a).band), + (B.sets.activity ω).active i H ↔ + Threshold.active (B.newLabels a) H (κ*(B.newData a).value lam i ⟨H,hi⟩) ω := by + have ha' := (B.batch a.1).choose_some i H a.2 ha + have hd := (B.batch a.1).chosen_domain i H a.2 ha' + have h := (B.batch a.1).chosen_description i H a.2 ha' + refine ⟨h.1,fun ω hi => ?_⟩ + apply (SetPatch.batch_inside _ B.overlap (List.mem_ofFn.mpr ⟨a.1,rfl⟩) ω i H + ((B.batch a.1).mem_domain.mpr ⟨a.2.1,hd⟩)).trans + exact h.2 ω hi + +lemma unchosen (ω : Ω × Bool) (i : Fin (k+1)) (H : ℝ) (ha : B.choose i H=none) : + (B.sets.activity ω).active i H ↔ (S.lift.sets.activity ω).active i H := by + apply SetPatch.batch_old _ B.overlap ω i H + intro P hP + obtain ⟨q,rfl⟩ := List.mem_ofFn.mp hP + exact (B.batch q).unchosen ω i H (B.choose_none i H ha q) + +/-- The actual simultaneous layer and selected ordinary/ordered chart table. -/ +noncomputable def apply [SFinite μ] : BState M κ lam (Ω × Bool) (μ.prod Threshold.fair) := by + let e := Fintype.equivFin B.NewIndex + let pick : Fin (k+1) → ℝ → Option (Fin (Fintype.card B.NewIndex)) := + fun i H => (B.choose i H).map e + have hpick (i H a) (ha : pick i H=some a) : B.chosen i H (e.symm a) := by + obtain ⟨b,hb,hba⟩ := Option.map_eq_some_iff.mp ha + have he : b=e.symm a := by rw [← hba]; simp + exact he ▸ B.choose_some i H b hb + exact S.lift.append B.sets (Fintype.card B.NewIndex) + (B.newData ∘ e.symm) (B.newLabels ∘ e.symm) pick + (fun i H a ha => (B.chosen_description i H (e.symm a) (hpick i H a ha)).1.1) + (fun i H a ha => (B.chosen_description i H (e.symm a) (hpick i H a ha)).1.2) + (fun i j H hs => congrArg (Option.map e) (B.choose_switch i j H hs)) + (fun ω i H ha => B.unchosen ω i H (Option.map_eq_none_iff.mp ha)) + (fun ω i H a ha => (B.chosen_description i H (e.symm a) (hpick i H a ha)).2 ω _) + +end SecondaryLayer +end PlanarL1.Columns.Model.BState + + + +end + +end OAI diff --git a/lean/OAI/Combinatorics/PlanarL1/SecondaryCells.lean b/lean/OAI/Combinatorics/PlanarL1/SecondaryCells.lean new file mode 100644 index 0000000000000000000000000000000000000000..60805fb9a70eab611ae1e729626b566351b5cce4 --- /dev/null +++ b/lean/OAI/Combinatorics/PlanarL1/SecondaryCells.lean @@ -0,0 +1,1031 @@ +import OAI.Combinatorics.PlanarL1.MainCells + +namespace OAI + +section + +namespace PlanarL1.Columns.Model.SecondaryCell +open scoped NNReal +open Metric + +variable {n : ℕ} {M : Model n} {J : Set ℝ} {root : Fin n} +variable (R : Point.RadialTree (M := M) (J := J) (root := root)) +variable (S : Finset (M.Point J root)) + +noncomputable def seedDistance (x : M.Point J root) : ℝ := infDist x (S : Set (M.Point J root)) + +lemma seedDistance_nonneg (x : M.Point J root) : 0 ≤ seedDistance S x := infDist_nonneg + +lemma seedDistance_lipschitz : LipschitzWith 1 (seedDistance S) := lipschitz_infDist_pt _ + +lemma seedDistance_seed {w : M.Point J root} (hw : w ∈ S) : seedDistance S w = 0 := + infDist_zero_of_mem hw + +lemma seedDistance_attained (hS : S.Nonempty) (x : M.Point J root) : + ∃ w ∈ S, seedDistance S x = dist x w := by + exact S.finite_toSet.isCompact.exists_infDist_eq_dist (by simpa using hS) x + +noncomputable def input (x : M.Point J root) : ℝ := (9/10:ℝ)*seedDistance S x + +lemma input_lipschitz (hζ : R.ζ = (1:ℝ)/10) : R.InputLip (input S) := by + intro x y + have h := (seedDistance_lipschitz S).dist_le_mul x y + rw [NNReal.coe_one,one_mul] at h + rw [input,input,← mul_sub,abs_mul,abs_of_pos (by norm_num : (0:ℝ) < 9/10),hζ] + rw [Real.dist_eq] at h + nlinarith + +noncomputable def approx (α : Point.RadialTree.Noise (n := n)) (x : M.Point J root) : ℝ := + (R.pasted (input S) α x).value + +noncomputable def shallow (pc radius : ℝ) (α : Point.RadialTree.Noise (n := n)) + (x : M.Point J root) : ℝ := pc+radius/20-approx R S α x + +lemma approx_accuracy (hζ : R.ζ = (1:ℝ)/10) {radius : ℝ} (hδ : R.δ = (radius/1000)/8) + {α : Point.RadialTree.Noise (n := n)} (hα : R.NoiseBounds α) (x : M.Point J root) : + |approx R S α x-(9/10:ℝ)*seedDistance S x| ≤ radius/1000 := by + have h := R.pasted_accuracy (input_lipschitz R S hζ) hα x + rw [hδ] at h + change |approx R S α x-(9/10:ℝ)*seedDistance S x| ≤ _ at h + have hp := R.delta_pos + rw [hδ] at hp + linarith + +lemma shallow_lipschitz (pc radius : ℝ) {α : Point.RadialTree.Noise (n := n)} + (hα : R.NoiseBounds α) : LipschitzWith 1 (shallow R S pc radius α) := by + apply LipschitzWith.of_dist_le_mul + intro x y + simpa only [shallow,approx,dist_sub_left] using (R.pasted_lipschitz (input S) hα).dist_le_mul x y + +lemma shallow_boundary (hζ : R.ζ = (1:ℝ)/10) {radius pc : ℝ} (hδ : R.δ = (radius/1000)/8) + {α : Point.RadialTree.Noise (n := n)} (hα : R.NoiseBounds α) {x : M.Point J root} + (hx : seedDistance S x = radius) : shallow R S pc radius α x ≤ pc-(849/1000:ℝ)*radius := by + have h := (abs_le.mp (approx_accuracy R S hζ hδ hα x)).1 + dsimp only [shallow] + rw [hx] at h + linarith + +lemma shallow_cap (hζ : R.ζ = (1:ℝ)/10) {radius pc : ℝ} (hδ : R.δ = (radius/1000)/8) + {α : Point.RadialTree.Noise (n := n)} (hα : R.NoiseBounds α) (x : M.Point J root) : + shallow R S pc radius α x ≤ pc+(51/1000:ℝ)*radius := by + have h := (abs_le.mp (approx_accuracy R S hζ hδ hα x)).1 + dsimp only [shallow] + linarith [seedDistance_nonneg S x] + +lemma shallow_seed (hζ : R.ζ = (1:ℝ)/10) {radius pc : ℝ} (hr : 0 < radius) + (hδ : R.δ = (radius/1000)/8) {α : Point.RadialTree.Noise (n := n)} + (hα : R.NoiseBounds α) {w : M.Point J root} (hw : w ∈ S) {p : ℝ} + (hp : |p-pc| ≤ (60/1000000:ℝ)*radius) : + p+radius/25 < shallow R S pc radius α w := by + have h := (abs_le.mp (approx_accuracy R S hζ hδ hα w)).2 + rw [seedDistance_seed S hw,mul_zero,sub_zero] at h + have hpc := (abs_le.mp hp).2 + dsimp only [shallow] + linarith + +end PlanarL1.Columns.Model.SecondaryCell + + +end + +section + +namespace PlanarL1.Columns.Model.Point +variable {n : ℕ} {M : Model n} {J : Set ℝ} {root : Fin n} +lemma height_lipschitz : LipschitzWith 1 (fun x : M.Point J root => x.height) := by + apply LipschitzWith.of_dist_le_mul + intro x y + rw [Real.dist_eq,NNReal.coe_one,one_mul] + exact x.height_change_le y +end PlanarL1.Columns.Model.Point + +namespace PlanarL1.Columns.Model.SecondaryCell +open Set Metric +open scoped NNReal +attribute [local instance] Classical.propDecidable +variable {n : ℕ} {M : Model n} {J : Set ℝ} {root : Fin n} +variable (S : Finset (M.Point J root)) (radius : ℝ) + +/-- The literal closed union of radius-R seed balls, on each vertical column. -/ +def domain (i : Fin n) : Set ℝ := + (fun x : M.Point J root => x.height) '' + {x | x.column = i ∧ seedDistance S x ≤ radius} + +lemma mem_domain {i : Fin n} {H : ℝ} : H ∈ domain S radius i ↔ + ∃ x : M.Point J root, x.column = i ∧ x.height = H ∧ seedDistance S x ≤ radius := by + constructor + · rintro ⟨x,⟨hi,hd⟩,hH⟩ + exact ⟨x,hi,hH,hd⟩ + · rintro ⟨x,hi,hH,hd⟩ + exact ⟨x,⟨hi,hd⟩,hH⟩ + +lemma compact_domain (hJ : IsCompact J) (i : Fin n) : IsCompact (domain S radius i) := by + have hc : IsCompact {x : M.Point J root | x.column = i} := by + simpa only [mem_singleton_iff] using Point.fullColumns_compact (M := M) (root := root) hJ {i} + have hd : IsClosed {x : M.Point J root | seedDistance S x ≤ radius} := + isClosed_le (seedDistance_lipschitz S).continuous continuous_const + exact (hc.inter_right hd).image Point.height_lipschitz.continuous + +noncomputable def point (i : Fin n) (H : ℝ) (h : H ∈ domain S radius i) : M.Point J root := + ((mem_domain S radius).mp h).choose + +lemma point_column {i : Fin n} {H : ℝ} (h : H ∈ domain S radius i) : + (point S radius i H h).column = i := ((mem_domain S radius).mp h).choose_spec.1 +lemma point_height {i : Fin n} {H : ℝ} (h : H ∈ domain S radius i) : + (point S radius i H h).height = H := ((mem_domain S radius).mp h).choose_spec.2.1 +lemma point_distance {i : Fin n} {H : ℝ} (h : H ∈ domain S radius i) : + seedDistance S (point S radius i H h) ≤ radius := ((mem_domain S radius).mp h).choose_spec.2.2 + +lemma inBand_of_mem {i : Fin n} {H : ℝ} (h : H ∈ domain S radius i) : H ∈ J := by + rw [← point_height S radius h] + exact (point S radius i H h).inBand + +lemma equal_radius_or_endpoint (hJ : IsCompact J) (lo a : ℝ) (_ha : 0 < a) + (hband : J = Icc lo (lo+a)) {i : Fin n} {H : ℝ} (h : H ∈ frontier (domain S radius i)) : + ∃ hd : H ∈ domain S radius i, + seedDistance S (point S radius i H hd) = radius ∨ H = lo ∨ H = lo+a := by + have hd : H ∈ domain S radius i := (compact_domain S radius hJ i).isClosed.frontier_subset h + refine ⟨hd,?_⟩ + let x := point S radius i H hd + by_cases hs : seedDistance S x = radius + · exact Or.inl hs + right + by_cases hl : H = lo + · exact Or.inl hl + right + by_contra hr + have hH : H ∈ Icc lo (lo+a) := hband ▸ inBand_of_mem S radius hd + have hlo : lo < H := lt_of_le_of_ne hH.1 (Ne.symm hl) + have hhi : H < lo+a := lt_of_le_of_ne hH.2 hr + have hdist : seedDistance S x < radius := lt_of_le_of_ne (point_distance S radius hd) hs + let ε := min (H-lo) (min (lo+a-H) (radius-seedDistance S x)) / 2 + have hε : 0 < ε := by dsimp only [ε]; positivity + have hεl : ε < H-lo := by + have hh := min_le_left (H-lo) (min (lo+a-H) (radius-seedDistance S x)) + dsimp only [ε] + linarith + have hεh : ε < lo+a-H := by + have hh := (min_le_right (H-lo) (min (lo+a-H) (radius-seedDistance S x))).trans (min_le_left _ _) + dsimp only [ε] + linarith + have hεd : ε < radius-seedDistance S x := by + have hh := (min_le_right (H-lo) (min (lo+a-H) (radius-seedDistance S x))).trans (min_le_right _ _) + dsimp only [ε] + linarith + have hb : Metric.ball H ε ⊆ domain S radius i := by + intro T hT + have ht := abs_lt.mp (by simpa only [Metric.mem_ball,Real.dist_eq] using hT : |T-H| < ε) + have hTJ : T ∈ J := by rw [hband]; constructor <;> linarith + let y := x.withHeight T hTJ + have hy : dist y x = |T-H| := by + rw [y.dist_same_column x rfl] + change |T-x.height| = |T-H| + rw [point_height S radius hd] + have hbnd := (seedDistance_lipschitz S).dist_le_mul y x + rw [Real.dist_eq,NNReal.coe_one,one_mul,hy] at hbnd + have hby := (abs_le.mp hbnd).2 + apply (mem_domain S radius).mpr + exact ⟨y,point_column S radius hd,rfl,by linarith [(by + simpa only [Metric.mem_ball,Real.dist_eq] using hT : |T-H| < ε)]⟩ + have hin : H ∈ interior (domain S radius i) := + mem_interior_iff_mem_nhds.mpr (Metric.mem_nhds_iff.mpr ⟨ε,hε,hb⟩) + exact h.2 hin + +/-- The seed-ball domain is saturated under the actual quotient switches. -/ +lemma switch_mem {i j : Fin n} {H : ℝ} (hs : H ∈ M.heights i j) + (hi : H ∈ domain S radius i) : H ∈ domain S radius j := by + let x := point S radius i H hi + have hHJ := inBand_of_mem S radius hi + have hadj : (M.activeGraph J).Adj i j := ⟨H,hHJ,hs⟩ + have hxi := point_column S radius hi + have hxH := point_height S radius hi + let y : M.Point J root := ⟨j,H,hHJ,(hxi ▸ x.reachable).trans hadj.reachable⟩ + have hd : dist x y = 0 := by + apply le_antisymm _ dist_nonneg + have hiCol : x.column = i := hxi + have hiHeight : x.height = H := hxH + have hjCol : y.column = j := rfl + have hjHeight : y.height = H := rfl + have h := x.dist_le_switch y hHJ (by rw [hiCol,hjCol]; exact hs) + simpa only [hiHeight,hjHeight,sub_self,abs_zero,add_zero] using h + have hf := (seedDistance_lipschitz S).dist_le_mul x y + rw [hd,mul_zero] at hf + have he : seedDistance S x = seedDistance S y := dist_le_zero.mp hf + exact (mem_domain S radius).mpr ⟨y,rfl,rfl,he ▸ point_distance S radius hi⟩ + +end PlanarL1.Columns.Model.SecondaryCell + + + +namespace PlanarL1.Columns.Model.SecondaryCell +open Set MeasureTheory +open scoped NNReal +attribute [local instance] Classical.propDecidable +variable {n : ℕ} {M : Model n} {J : Set ℝ} {root : Fin n} +variable (R : Point.RadialTree (M := M) (J := J) (root := root)) +variable (S : Finset (M.Point J root)) +variable (old L : M.Point J root → ℝ) (ordinary : Bool) + +noncomputable def spatial (pc radius αo : ℝ) (α : Point.RadialTree.Noise (n := n)) + (x : M.Point J root) : ℝ := + if ordinary then min (shallow R S pc radius α x) (Clipping.orderedBranch pc radius αo L x) + else shallow R S pc radius α x + +noncomputable def replacement (pc radius αo αh lo : ℝ) + (α : Point.RadialTree.Noise (n := n)) (x : M.Point J root) : ℝ := + max (old x) (min (spatial R S L ordinary pc radius αo α x) + (Clipping.heightShield lo R.a pc αh x.height)) + +noncomputable def replacementConstant : ℝ≥0 := max 5 ⟨3/(9*R.a/100),by positivity [R.width_pos]⟩ + +lemma spatial_lipschitz (pc radius αo : ℝ) {α : Point.RadialTree.Noise (n := n)} + (hα : R.NoiseBounds α) (hL : LipschitzWith 1 L) : + LipschitzWith 4 (spatial R S L ordinary pc radius αo α) := by + have hT := (shallow_lipschitz R S pc radius hα).weaken (by norm_num : (1:ℝ≥0) ≤ 4) + have hO : LipschitzWith 4 (Clipping.orderedBranch pc radius αo L) := by + apply LipschitzWith.of_dist_le_mul + intro x y + have h := hL.dist_le_mul x y + rw [Real.dist_eq,NNReal.coe_one,one_mul] at h + change dist _ _ ≤ (4:ℝ)*dist x y + rw [Real.dist_eq] + change |(pc+radius/20+4*(L x-pc)+αo)-(pc+radius/20+4*(L y-pc)+αo)| ≤ _ + rw [show (pc+radius/20+4*(L x-pc)+αo)-(pc+radius/20+4*(L y-pc)+αo) = + 4*(L x-L y) by ring, abs_mul,abs_of_pos (by norm_num : (0:ℝ)<4)] + linarith + cases ordinary + · convert hT using 1; funext x; simp only [spatial,Bool.false_eq_true,ite_false] + · convert hT.min hO using 1 + · exact (max_self _).symm + · funext x; simp only [spatial,ite_true] + +lemma replacement_lipschitz (hOld : LipschitzWith 5 old) (hL : LipschitzWith 1 L) + (pc radius αo αh lo : ℝ) {α : Point.RadialTree.Noise (n := n)} (hα : R.NoiseBounds α) : + LipschitzWith (replacementConstant R) (replacement R S old L ordinary pc radius αo αh lo α) := by + apply Clipping.clip_lipschitz + · exact hOld.weaken (le_max_left _ _) + · exact (spatial_lipschitz R S L ordinary pc radius αo hα hL).weaken + ((by norm_num : (4:ℝ≥0) ≤ 5).trans (le_max_left _ _)) + · apply LipschitzWith.of_dist_le_mul + intro x y + have h := (Clipping.heightShield_lipschitz lo pc αh R.width_pos).dist_le_mul x.height y.height + have hheight := x.height_change_le y + change |x.height-y.height| ≤ dist x y at hheight + change dist _ _ ≤ (replacementConstant R : ℝ)*dist x y + change dist _ _ ≤ (3/(9*R.a/100))*dist x.height y.height at h + rw [Real.dist_eq x.height y.height] at h + exact h.trans ((mul_le_mul_of_nonneg_left hheight (by positivity [R.width_pos])).trans + (mul_le_mul_of_nonneg_right (le_max_right (5:ℝ) (3/(9*R.a/100))) dist_nonneg)) + +lemma replacement_near (hS : S.Nonempty) (hOld : LipschitzWith 5 old) + {pc radius : ℝ} (hseed : ∀ w ∈ S, |old w-pc| ≤ (60/1000000:ℝ)*radius) + {x : M.Point J root} (hx : seedDistance S x ≤ radius) : + |old x-pc| ≤ 5*radius+(60/1000000:ℝ)*radius := by + obtain ⟨w,hw,hd⟩ := seedDistance_attained S hS x + have ho := hOld.dist_le_mul x w + rw [Real.dist_eq] at ho + have hs := hseed w hw + have hh := abs_sub_le (old x) (old w) pc + change |old x-old w| ≤ 5*dist x w at ho + linarith + +lemma spatial_boundary (hS : S.Nonempty) (hζ : R.ζ = (1:ℝ)/10) + {pc radius αo : ℝ} (hr : 0 ≤ radius) (hαo : αo ≤ radius/1000) + (hδ : R.δ = (radius/1000)/8) {α : Point.RadialTree.Noise (n := n)} (hα : R.NoiseBounds α) + (hord : ordinary = true → ∀ x, L x ≤ old x) + (hadmit : ordinary = false → ∀ w ∈ S, ∀ x, dist w x = radius → pc-(65/100:ℝ)*radius ≤ old x) + {x : M.Point J root} (hx : seedDistance S x = radius) : + spatial R S L ordinary pc radius αo α x ≤ old x-(199/1000:ℝ)*radius := by + have hT := shallow_boundary R S hζ hδ hα hx (pc := pc) + cases ordinary with + | false => + simp only [spatial,Bool.false_eq_true,ite_false] + obtain ⟨w,hw,hd⟩ := seedDistance_attained S hS x + have ha := hadmit rfl w hw x (by rw [dist_comm,← hd,hx]) + linarith + | true => + simp only [spatial,ite_true] + exact Clipping.ordinary_boundary_margin hr hαo (hord rfl x) hT + +lemma replacement_boundary (hS : S.Nonempty) (hζ : R.ζ = (1:ℝ)/10) + {pc radius αo : ℝ} (hr : 0 ≤ radius) (hαo : αo ≤ radius/1000) + (hδ : R.δ = (radius/1000)/8) {α : Point.RadialTree.Noise (n := n)} (hα : R.NoiseBounds α) + (hord : ordinary = true → ∀ x, L x ≤ old x) + (hadmit : ordinary = false → ∀ w ∈ S, ∀ x, dist w x = radius → pc-(65/100:ℝ)*radius ≤ old x) + (αh lo : ℝ) {x : M.Point J root} (hx : seedDistance S x = radius) : + replacement R S old L ordinary pc radius αo αh lo α x = old x := by + apply max_eq_left + have h := spatial_boundary R S old L ordinary hS hζ hr hαo hδ hα hord hadmit hx + exact (min_le_left _ _).trans (by linarith) + +lemma replacement_endpoint (hS : S.Nonempty) (hOld : LipschitzWith 5 old) + {pc radius αo αh lo : ℝ} (hr : radius ≤ (1:ℝ)/100) (hαh : αh ≤ radius/1000) + (hseed : ∀ w ∈ S, |old w-pc| ≤ (60/1000000:ℝ)*radius) + (α : Point.RadialTree.Noise (n := n)) {x : M.Point J root} + (hx : seedDistance S x ≤ radius) (he : x.height = lo ∨ x.height = lo+R.a) : + replacement R S old L ordinary pc radius αo αh lo α x = old x := by + apply max_eq_left + have h := (abs_le.mp (replacement_near S old hS hOld hseed hx)).1 + have hh : Clipping.heightShield lo R.a pc αh x.height = pc-1+αh := by + rcases he with he | he + · exact Clipping.heightShield_left (by rw [he]) + · exact Clipping.heightShield_right (by rw [he]) + apply (min_le_right _ _).trans + rw [hh] + linarith + +lemma scaled_replacement_constant (ha : R.a ≤ 1) : + (R.a/1000000) * (replacementConstant R : ℝ) ≤ 1 := by + change (R.a/1000000) * max 5 (3/(9*R.a/100)) ≤ 1 + rw [mul_max_of_nonneg (5:ℝ) (3/(9*R.a/100)) (by positivity [R.width_pos])] + apply max_le + · linarith + · have hpos : 0 < 9*R.a/100 := by positivity [R.width_pos] + rw [← mul_div_assoc] + apply (div_le_iff₀ hpos).mpr + nlinarith [R.width_pos] + +lemma point_dist {radius : ℝ} {i : Fin n} {H T : ℝ} + (hH : H ∈ domain S radius i) (hT : T ∈ domain S radius i) : + dist (point S radius i H hH) (point S radius i T hT) = |H-T| := by + rw [Point.dist_same_column _ _ (by rw [point_column S radius hH,point_column S radius hT])] + rw [point_height S radius hH,point_height S radius hT] + +lemma point_dist_switch {radius : ℝ} {i j : Fin n} {H : ℝ} + (hH : H ∈ domain S radius i) (hT : H ∈ domain S radius j) (hs : H ∈ M.heights i j) : + dist (point S radius i H hH) (point S radius j H hT) = 0 := by + apply le_antisymm _ dist_nonneg + have h := (point S radius i H hH).dist_le_switch (point S radius j H hT) + (inBand_of_mem S radius hH) (by rw [point_column S radius hH,point_column S radius hT]; exact hs) + simpa only [point_height S radius hH,point_height S radius hT,sub_self,abs_zero,add_zero] using h + +noncomputable def converted (pc radius αo αh lo c η κ : ℝ) + (α : Point.RadialTree.Noise (n := n)) (i : Fin n) (H : ℝ) : ℝ := + if h : H ∈ domain S radius i then + κ*(c+η*replacement R S old L ordinary pc radius αo αh lo α (point S radius i H h)) else 0 + +lemma converted_on (pc radius αo αh lo c η κ : ℝ) + (α : Point.RadialTree.Noise (n := n)) {i : Fin n} {H : ℝ} (h : H ∈ domain S radius i) : + converted R S old L ordinary pc radius αo αh lo c η κ α i H = + κ*(c+η*replacement R S old L ordinary pc radius αo αh lo α (point S radius i H h)) := by + simp only [converted,dite_eq_left h] + +lemma converted_lipschitz (hOld : LipschitzWith 5 old) (hL : LipschitzWith 1 L) + (pc radius αo αh lo c η κ : ℝ) {α : Point.RadialTree.Noise (n := n)} (hα : R.NoiseBounds α) + (hη : |η| = 1) (hκ : 0 ≤ κ) (hκK : κ*(replacementConstant R : ℝ) ≤ 1) (i : Fin n) : + LipschitzOnWith 1 (converted R S old L ordinary pc radius αo αh lo c η κ α i) (domain S radius i) := by + apply LipschitzOnWith.of_dist_le_mul + intro H hH T hT + rw [converted_on R S old L ordinary pc radius αo αh lo c η κ α hH, + converted_on R S old L ordinary pc radius αo αh lo c η κ α hT] + let x := point S radius i H hH + let y := point S radius i T hT + have h := (replacement_lipschitz R S old L ordinary hOld hL pc radius αo αh lo hα).dist_le_mul x y + rw [point_dist S hH hT,Real.dist_eq] at h + simp only [Real.dist_eq,NNReal.coe_one,one_mul] + change |κ*(c+η*replacement R S old L ordinary pc radius αo αh lo α x)- + κ*(c+η*replacement R S old L ordinary pc radius αo αh lo α y)| ≤ |H-T| + rw [show κ*(c+η*replacement R S old L ordinary pc radius αo αh lo α x)- + κ*(c+η*replacement R S old L ordinary pc radius αo αh lo α y) = + κ*η*(replacement R S old L ordinary pc radius αo αh lo α x- + replacement R S old L ordinary pc radius αo αh lo α y) by ring, + abs_mul,abs_mul,abs_of_nonneg hκ,hη,mul_one] + calc + _ ≤ κ*((replacementConstant R : ℝ)*|H-T|) := mul_le_mul_of_nonneg_left h hκ + _ = (κ*(replacementConstant R : ℝ))*|H-T| := by ring + _ ≤ 1*|H-T| := mul_le_mul_of_nonneg_right hκK (abs_nonneg _) + _ = _ := one_mul _ + +/-- Literal secondary clipping on the actual closed seed-ball union, in both +ordinary and admitted ordered orientations, is an invariant-preserving patch. -/ +noncomputable def patch {Ω : Type*} [MeasurableSpace Ω] {μ : Measure Ω} + (A : SetSystem M Ω μ) (Z : Threshold.Variables Ω μ) + (hJ : IsCompact J) (lo : ℝ) (hband : J = Icc lo (lo+R.a)) + (hS : S.Nonempty) (hOld : LipschitzWith 5 old) (hL : LipschitzWith 1 L) + (hζ : R.ζ = (1:ℝ)/10) (pc radius αo αh c η κ : ℝ) + (hr : 0 ≤ radius) (hrsmall : radius ≤ (1:ℝ)/100) (hαo : αo ≤ radius/1000) + (hαh : αh ≤ radius/1000) (hδ : R.δ = (radius/1000)/8) + {α : Point.RadialTree.Noise (n := n)} (hα : R.NoiseBounds α) + (hord : ordinary = true → ∀ x, L x ≤ old x) + (hadmit : ordinary = false → ∀ w ∈ S, ∀ x, dist w x = radius → pc-(65/100:ℝ)*radius ≤ old x) + (hseed : ∀ w ∈ S, |old w-pc| ≤ (60/1000000:ℝ)*radius) + (hη : |η| = 1) (hκ : 0 ≤ κ) (hκK : κ*(replacementConstant R : ℝ) ≤ 1) + (hchart : ∀ ω i H (h : H ∈ domain S radius i), + Threshold.active Z H (κ*(c+η*old (point S radius i H h))) ω ↔ (A.activity ω).active i H) : + SetPatch A := by + have hclosed := fun i => (compact_domain S radius hJ i).isClosed + apply Threshold.chartPatch A Z (domain S radius) hclosed + (converted R S old L ordinary pc radius αo αh lo c η κ α) + (converted_lipschitz R S old L ordinary hOld hL pc radius αo αh lo c η κ hα hη hκ hκK) + · intro ω i H hH + obtain ⟨hd,he⟩ := equal_radius_or_endpoint S radius hJ lo R.a R.width_pos hband hH + rw [converted_on R S old L ordinary pc radius αo αh lo c η κ α hd] + have heq : replacement R S old L ordinary pc radius αo αh lo α (point S radius i H hd) = + old (point S radius i H hd) := by + rcases he with he | he + · exact replacement_boundary R S old L ordinary hS hζ hr hαo hδ hα hord hadmit αh lo he + · exact replacement_endpoint R S old L ordinary hS hOld hrsmall hαh hseed α + (point_distance S radius hd) (by rw [point_height S radius hd]; exact he) + rw [heq] + exact hchart ω i H hd + · intro i j H hs hi hj + rw [converted_on R S old L ordinary pc radius αo αh lo c η κ α hi, + converted_on R S old L ordinary pc radius αo αh lo c η κ α hj] + have h := (replacement_lipschitz R S old L ordinary hOld hL pc radius αo αh lo hα).dist_le_mul + (point S radius i H hi) (point S radius j H hj) + rw [point_dist_switch S hi hj hs,mul_zero] at h + rw [dist_le_zero.mp h] + · intro ω i j H hs hi hj + exact (hj (switch_mem S radius hs hi)).elim + +lemma replacement_seed (hζ : R.ζ = (1:ℝ)/10) {pc radius αo αh lo : ℝ} + (hr : 0 < radius) (hrsmall : radius ≤ (1:ℝ)/100) (hαo : 0 ≤ αo) (hαh : 0 ≤ αh) + (hδ : R.δ = (radius/1000)/8) {α : Point.RadialTree.Noise (n := n)} (hα : R.NoiseBounds α) + {w : M.Point J root} (hw : w ∈ S) (hp : |old w-pc| ≤ (60/1000000:ℝ)*radius) + (hL : ordinary = true → |L w-pc| ≤ (10/1000000:ℝ)*radius) + (hl : lo+9*R.a/100 ≤ w.height) (hh : w.height ≤ lo+R.a-9*R.a/100) : + old w+radius/25 < replacement R S old L ordinary pc radius αo αh lo α w := by + apply lt_of_lt_of_le _ (le_max_right _ _) + apply lt_min + · have hT := shallow_seed R S hζ hr hδ hα hw hp + cases ordinary with + | false => exact hT + | true => exact lt_min hT (Clipping.orderedBranch_seed hr hαo (hL rfl) hp) + · rw [Clipping.heightShield_plateau R.width_pos hl hh] + have h := (abs_le.mp hp).2 + linarith + +lemma replacement_movement (hS : S.Nonempty) (hOld : LipschitzWith 5 old) + (hζ : R.ζ = (1:ℝ)/10) {pc radius αo αh lo : ℝ} (hr : 0 ≤ radius) + (hδ : R.δ = (radius/1000)/8) {α : Point.RadialTree.Noise (n := n)} (hα : R.NoiseBounds α) + (hseed : ∀ w ∈ S, |old w-pc| ≤ (60/1000000:ℝ)*radius) + {x : M.Point J root} (hx : seedDistance S x ≤ radius) : + |replacement R S old L ordinary pc radius αo αh lo α x-old x| ≤ (51/10:ℝ)*radius := by + have hold : old x ≤ replacement R S old L ordinary pc radius αo αh lo α x := le_max_left _ _ + rw [abs_of_nonneg (sub_nonneg.mpr hold)] + apply sub_le_iff_le_add.mpr + apply max_le + · linarith + · apply (min_le_left _ _).trans + have hsp : spatial R S L ordinary pc radius αo α x ≤ shallow R S pc radius α x := by + cases ordinary + · exact le_rfl + · exact min_le_left _ _ + have hcap := shallow_cap R S hζ hδ hα x (pc := pc) + have hnear := (abs_le.mp (replacement_near S old hS hOld hseed hx)).1 + linarith + +end PlanarL1.Columns.Model.SecondaryCell + + + + +end + +section + +namespace PlanarL1.Columns.Model.SecondaryCell +open PlanarL1.Interpolation +open scoped NNReal +variable {n : ℕ} {M : Model n} {J : Set ℝ} {root : Fin n} +variable (R : Point.RadialTree (M := M) (J := J) (root := root)) +variable (S : Finset (M.Point J root)) (old L : M.Point J root → ℝ) (ordinary : Bool) + +noncomputable def namedReplacement (pc radius αo αh lo : ℝ) + (α : Point.RadialTree.Noise (n := n)) : M.Point J root → NamedValue := + secondaryNamed (fun x => ⟨(R.pasted (input S) α x).name,shallow R S pc radius α x⟩) + old (Clipping.orderedBranch pc radius αo L) + (fun x => Clipping.heightShield lo R.a pc αh x.height) ordinary + +lemma namedReplacement_value (pc radius αo αh lo : ℝ) + (α : Point.RadialTree.Noise (n := n)) (x : M.Point J root) : + (namedReplacement R S old L ordinary pc radius αo αh lo α x).value = + replacement R S old L ordinary pc radius αo αh lo α x := by + rw [namedReplacement,secondaryNamed_value] + rfl + +noncomputable def localAtom {k : ℕ} (A : R.Node k) + (pc radius αo αh lo : ℝ) (α : Point.RadialTree.Noise (n := n)) : ℕ → M.Point J root → ℝ := + secondaryAtom (fun i x => pc+radius/20-(R.listedAtom (input S) α A R.lookback i x).value) + old (Clipping.orderedBranch pc radius αo L) + (fun x => Clipping.heightShield lo R.a pc αh x.height) + +lemma orderedBranch_lipschitz (hL : LipschitzWith 1 L) (pc radius αo : ℝ) : + LipschitzWith 4 (Clipping.orderedBranch pc radius αo L) := by + apply LipschitzWith.of_dist_le_mul + intro x y + have h := hL.dist_le_mul x y + simp only [Real.dist_eq,NNReal.coe_one,one_mul] at h + change |(pc+radius/20+4*(L x-pc)+αo)-(pc+radius/20+4*(L y-pc)+αo)| ≤ 4*dist x y + rw [show (pc+radius/20+4*(L x-pc)+αo)-(pc+radius/20+4*(L y-pc)+αo) = + 4*(L x-L y) by ring,abs_mul,abs_of_pos (by norm_num : (0:ℝ)<4)] + linarith + +lemma shield_lipschitz (pc αh lo : ℝ) : + LipschitzWith (replacementConstant R) + (fun x : M.Point J root => Clipping.heightShield lo R.a pc αh x.height) := by + apply LipschitzWith.of_dist_le_mul + intro x y + have h := (Clipping.heightShield_lipschitz lo pc αh R.width_pos).dist_le_mul x.height y.height + have hh := x.height_change_le y + change |x.height-y.height| ≤ dist x y at hh + change dist _ _ ≤ (replacementConstant R : ℝ)*dist x y + change dist _ _ ≤ (3/(9*R.a/100))*dist x.height y.height at h + rw [Real.dist_eq x.height y.height] at h + exact h.trans ((mul_le_mul_of_nonneg_left hh (by positivity [R.width_pos])).trans + (mul_le_mul_of_nonneg_right (le_max_right (5:ℝ) (3/(9*R.a/100))) dist_nonneg)) + +lemma localAtom_lipschitz (hOld : LipschitzWith 5 old) (hL : LipschitzWith 1 L) + {k : ℕ} (A : R.Node k) (pc radius αo αh lo : ℝ) + (α : Point.RadialTree.Noise (n := n)) (i : ℕ) : + LipschitzWith (replacementConstant R) (localAtom R S old L A pc radius αo αh lo α i) := by + apply secondaryAtom_lipschitz + · intro i + apply LipschitzWith.weaken _ (show (1:ℝ≥0) ≤ replacementConstant R from + (by norm_num : (1:ℝ≥0) ≤ 5).trans (le_max_left _ _)) + apply LipschitzWith.of_dist_le_mul + intro x y + simpa only [dist_sub_left] using (R.listedAtom_lipschitz (input S) α A R.lookback i).dist_le_mul x y + · exact hOld.weaken (le_max_left _ _) + · exact (orderedBranch_lipschitz L hL pc radius αo).weaken + ((by norm_num : (4:ℝ≥0) ≤ 5).trans (le_max_left _ _)) + · exact shield_lipschitz R pc αh lo + +lemma localAtomPair_probability_lt {k : ℕ} (A : R.Node k) (x : M.Point J root) + (pc radius lo B : ℝ) (hB : 0 < B) (cap m : ℕ) (hk : k < cap) (hm : 0 < m) + (i j : ℕ) (hi : i ∈ secondaryNames (R.recentNames A R.lookback)) + (hj : j ∈ secondaryNames (R.recentNames A R.lookback)) (hij : i < j) + {t : ℝ} (ht : 0 ≤ t) : + FiniteRandom.prob (fun ω : Point.RadialTree.GridSample (n := n) cap m × (Fin (m+1) × Fin (m+1)) => + |localAtom R S old L A pc radius (B/m*ω.2.1.val) (B/m*ω.2.2.val) lo (R.gridNoise cap m ω.1) i x- + localAtom R S old L A pc radius (B/m*ω.2.1.val) (B/m*ω.2.2.val) lo (R.gridNoise cap m ω.1) j x| ≤ t) ≤ + (2*t+R.q/m)/R.q + (2*t+B/m)/B := by + have hp : 0 ≤ (2*t+R.q/m)/R.q := by positivity [R.q_pos] + have hq : 0 ≤ (2*t+B/m)/B := by positivity + by_cases hj1 : j=1 + · have hi0 : i=0 := by omega + subst i; subst j + apply FiniteRandom.prob_prod_bound + intro ω + apply FiniteRandom.prob_prod_bound + intro r + let c := Clipping.heightShield lo R.a pc 0 x.height-old x + apply (FiniteRandom.prob_mono (fun s h => ?_)).trans + ((FiniteRandom.grid_probability m hm hB ht c).trans (le_add_of_nonneg_left hp)) + have he : c+B/m*s.val = + localAtom R S old L A pc radius (B/m*r.val) (B/m*s.val) lo (R.gridNoise cap m ω) 1 x- + localAtom R S old L A pc radius (B/m*r.val) (B/m*s.val) lo (R.gridNoise cap m ω) 0 x := by + simp only [localAtom,secondaryAtom, reduceCtorEq,ite_true,ite_false,c,Clipping.heightShield] + ring + rw [he,abs_sub_comm] + exact h + · by_cases hi1 : i=1 + · subst i + have hj0 : j ≠ 0 := by omega + apply FiniteRandom.prob_prod_bound + intro ω + apply FiniteRandom.prob_prod_bound + intro r + let c := Clipping.heightShield lo R.a pc 0 x.height- + localAtom R S old L A pc radius (B/m*r.val) 0 lo (R.gridNoise cap m ω) j x + apply (FiniteRandom.prob_mono (fun s h => ?_)).trans + ((FiniteRandom.grid_probability m hm hB ht c).trans (le_add_of_nonneg_left hp)) + have he : c+B/m*s.val = + localAtom R S old L A pc radius (B/m*r.val) (B/m*s.val) lo (R.gridNoise cap m ω) 1 x- + localAtom R S old L A pc radius (B/m*r.val) (B/m*s.val) lo (R.gridNoise cap m ω) j x := by + simp only [localAtom,secondaryAtom, reduceCtorEq,ite_true,ite_false,ite_eq_right hj0,ite_eq_right hj1,c,Clipping.heightShield] + split_ifs <;> ring + rwa [he] + · by_cases hj2 : j=2 + · have hi0 : i=0 := by omega + subst i; subst j + apply FiniteRandom.prob_prod_bound + intro ω + apply FiniteRandom.prob_prod_bound_left + intro s + let c := Clipping.orderedBranch pc radius 0 L x-old x + apply (FiniteRandom.prob_mono (fun r h => ?_)).trans + ((FiniteRandom.grid_probability m hm hB ht c).trans (le_add_of_nonneg_left hp)) + have he : c+B/m*r.val = + localAtom R S old L A pc radius (B/m*r.val) (B/m*s.val) lo (R.gridNoise cap m ω) 2 x- + localAtom R S old L A pc radius (B/m*r.val) (B/m*s.val) lo (R.gridNoise cap m ω) 0 x := by + simp only [localAtom,secondaryAtom, reduceCtorEq, show (2:ℕ) ≠ 1 by decide,ite_true,ite_false,c,Clipping.orderedBranch] + ring + rw [he,abs_sub_comm] + exact h + · have hj3 : 3 ≤ j := by omega + have hj0 : j ≠ 0 := by omega + have hjS : j-3 ∈ R.recentNames A R.lookback := by + rcases mem_secondaryNames.mp hj with h | h | h | h + · omega + · exact (hj1 h).elim + · exact (hj2 h).elim + · exact h.2 + by_cases hi2 : i=2 + · subst i + apply FiniteRandom.prob_prod_bound + intro ω + apply FiniteRandom.prob_prod_bound_left + intro s + let c := Clipping.orderedBranch pc radius 0 L x- + (pc+radius/20-(R.listedAtom (input S) (R.gridNoise cap m ω) A R.lookback (j-3) x).value) + apply (FiniteRandom.prob_mono (fun r h => ?_)).trans + ((FiniteRandom.grid_probability m hm hB ht c).trans (le_add_of_nonneg_left hp)) + have he : c+B/m*r.val = + localAtom R S old L A pc radius (B/m*r.val) (B/m*s.val) lo (R.gridNoise cap m ω) 2 x- + localAtom R S old L A pc radius (B/m*r.val) (B/m*s.val) lo (R.gridNoise cap m ω) j x := by + simp only [localAtom,secondaryAtom, reduceCtorEq, show (2:ℕ) ≠ 1 by decide,ite_true,ite_false,ite_eq_right hj0,ite_eq_right hj1,ite_eq_right hj2,c,Clipping.orderedBranch] + ring + rwa [he] + · by_cases hi0 : i=0 + · subst i + apply FiniteRandom.prob_prod_bound_left + intro rs + apply (FiniteRandom.prob_mono (fun ω h => ?_)).trans + ((R.listedConstant_probability (input S) A R.lookback (j-3) hjS x + (pc+radius/20-old x) cap m hk hm ht).trans (le_add_of_nonneg_right hq)) + have he : (R.listedAtom (input S) (R.gridNoise cap m ω) A R.lookback (j-3) x).value- + (pc+radius/20-old x) = + localAtom R S old L A pc radius (B/m*rs.1.val) (B/m*rs.2.val) lo (R.gridNoise cap m ω) 0 x- + localAtom R S old L A pc radius (B/m*rs.1.val) (B/m*rs.2.val) lo (R.gridNoise cap m ω) j x := by + simp only [localAtom,secondaryAtom, reduceCtorEq,ite_true,ite_false,ite_eq_right hj0,ite_eq_right hj1,ite_eq_right hj2] + ring + rwa [he] + · have hiS : i-3 ∈ R.recentNames A R.lookback := by + rcases mem_secondaryNames.mp hi with h | h | h | h + · exact (hi0 h).elim + · exact (hi1 h).elim + · exact (hi2 h).elim + · exact h.2 + have hi3 : 3 ≤ i := by omega + have hneq : i-3 ≠ j-3 := by omega + apply FiniteRandom.prob_prod_bound_left + intro rs + apply (FiniteRandom.prob_mono (fun ω h => ?_)).trans + ((R.listedPair_probability (input S) A R.lookback (i-3) (j-3) hiS hjS hneq x cap m hk hm ht).trans + (le_add_of_nonneg_right hq)) + have he : + localAtom R S old L A pc radius (B/m*rs.1.val) (B/m*rs.2.val) lo (R.gridNoise cap m ω) i x- + localAtom R S old L A pc radius (B/m*rs.1.val) (B/m*rs.2.val) lo (R.gridNoise cap m ω) j x = + (R.listedAtom (input S) (R.gridNoise cap m ω) A R.lookback (j-3) x).value- + (R.listedAtom (input S) (R.gridNoise cap m ω) A R.lookback (i-3) x).value := by + simp only [localAtom,secondaryAtom,ite_eq_right hi0,ite_eq_right hi1,ite_eq_right hi2,ite_eq_right hj0,ite_eq_right hj1,ite_eq_right hj2] + ring + rw [he,abs_sub_comm] at h + exact h + + +lemma localAtomPair_probability {k : ℕ} (A : R.Node k) (x : M.Point J root) + (pc radius lo B : ℝ) (hB : 0 < B) (cap m : ℕ) (hk : k < cap) (hm : 0 < m) + (i j : ℕ) (hi : i ∈ secondaryNames (R.recentNames A R.lookback)) + (hj : j ∈ secondaryNames (R.recentNames A R.lookback)) (hij : i ≠ j) + {t : ℝ} (ht : 0 ≤ t) : + FiniteRandom.prob (fun ω : Point.RadialTree.GridSample (n := n) cap m × (Fin (m+1) × Fin (m+1)) => + |localAtom R S old L A pc radius (B/m*ω.2.1.val) (B/m*ω.2.2.val) lo (R.gridNoise cap m ω.1) i x- + localAtom R S old L A pc radius (B/m*ω.2.1.val) (B/m*ω.2.2.val) lo (R.gridNoise cap m ω.1) j x| ≤ t) ≤ + (2*t+R.q/m)/R.q + (2*t+B/m)/B := by + rcases lt_or_gt_of_ne hij with hij | hji + · exact localAtomPair_probability_lt R S old L A x pc radius lo B hB cap m hk hm i j hi hj hij ht + · simpa only [abs_sub_comm] using + localAtomPair_probability_lt R S old L A x pc radius lo B hB cap m hk hm j i hj hi hji ht + +/-- Literal secondary proposal with all spatial, ordered and height branches. +The common atom list is determined before the fresh clipping parameters. -/ +lemma namedReplacement_probability (hOld : LipschitzWith 5 old) (hL : LipschitzWith 1 L) + (hζ : R.ζ = (1:ℝ)/10) (x : M.Point J root) + (pc radius lo B : ℝ) (hB : 0 < B) {ρ : ℝ} (hρ : 0 ≤ ρ) (hs : ρ ≤ R.radius) + (m : ℕ) (hm : 0 < m) : + FiniteRandom.prob (fun ω : Point.RadialTree.GridSample (n := n) R.depthCap m × (Fin (m+1) × Fin (m+1)) => + ∃ z : M.Point J root, dist x z ≤ ρ ∧ + (namedReplacement R S old L ordinary pc radius (B/m*ω.2.1.val) (B/m*ω.2.2.val) lo + (R.gridNoise R.depthCap m ω.1) z).name ≠ + (namedReplacement R S old L ordinary pc radius (B/m*ω.2.1.val) (B/m*ω.2.2.val) lo + (R.gridNoise R.depthCap m ω.1) x).name) ≤ + (6*(R.lookback+1)+3 : ℕ)^2 * + ((4*(replacementConstant R : ℝ)*ρ+R.q/m)/R.q + + (4*(replacementConstant R : ℝ)*ρ+B/m)/B) := by + classical + obtain ⟨k,A,hlo,heq⟩ := R.common_formula x hρ hs + have hk : k < R.depthCap := + (R.depth_le_layerDepth x (hlo x (by simpa using hρ))).trans_lt (R.layerDepth_lt_cap x) + have hlist (ω : Point.RadialTree.GridSample (n := n) R.depthCap m × (Fin (m+1) × Fin (m+1))) + (z : M.Point J root) (hz : dist x z ≤ ρ) : + (namedReplacement R S old L ordinary pc radius (B/m*ω.2.1.val) (B/m*ω.2.2.val) lo + (R.gridNoise R.depthCap m ω.1) z).name ∈ secondaryNames (R.recentNames A R.lookback) ∧ + (namedReplacement R S old L ordinary pc radius (B/m*ω.2.1.val) (B/m*ω.2.2.val) lo + (R.gridNoise R.depthCap m ω.1) z).value = + localAtom R S old L A pc radius (B/m*ω.2.1.val) (B/m*ω.2.2.val) lo (R.gridNoise R.depthCap m ω.1) + (namedReplacement R S old L ordinary pc radius (B/m*ω.2.1.val) (B/m*ω.2.2.val) lo + (R.gridNoise R.depthCap m ω.1) z).name z := by + let α := R.gridNoise R.depthCap m ω.1 + have hα := R.gridNoise_bounds R.depthCap m hm ω.1 + have hp := input_lipschitz R S hζ + have ha : |(R.formula (input S) α k A z).value-input S z| ≤ 6*R.δ := by + rw [← heq (input S) α hα z hz] + exact R.pasted_accuracy hp hα z + have hn : (R.pasted (input S) α z).name ∈ R.recentNames A R.lookback := by + rw [heq (input S) α hα z hz] + exact R.formula_name_recent hp hα k A z (hlo z hz) ha + have hv : R.pasted (input S) α z = R.listedAtom (input S) α A R.lookback (R.pasted (input S) α z).name z := by + rw [heq (input S) α hα z hz] + exact R.formula_eq_listed hp hα k A z (hlo z hz) ha + apply secondaryNamed_list + (fun z => ⟨(R.pasted (input S) α z).name,pc+radius/20-(R.pasted (input S) α z).value⟩) + (fun i z => pc+radius/20-(R.listedAtom (input S) α A R.lookback i z).value) + old (Clipping.orderedBranch pc radius (B/m*ω.2.1.val) L) + (fun z => Clipping.heightShield lo R.a pc (B/m*ω.2.2.val) z.height) + ordinary (R.recentNames A R.lookback) z hn + exact congrArg (fun Z : NamedValue => pc+radius/20-Z.value) hv + let b : ℝ := (4*(replacementConstant R : ℝ)*ρ+R.q/m)/R.q + + (4*(replacementConstant R : ℝ)*ρ+B/m)/B + have hb : 0 ≤ b := by dsimp [b]; positivity [R.q_pos] + have hF (ω : Point.RadialTree.GridSample (n := n) R.depthCap m × (Fin (m+1) × Fin (m+1))) : + LipschitzWith (replacementConstant R) + (fun z => (namedReplacement R S old L ordinary pc radius (B/m*ω.2.1.val) (B/m*ω.2.2.val) lo + (R.gridNoise R.depthCap m ω.1) z).value) := by + simp only [namedReplacement_value] + exact replacement_lipschitz R S old L ordinary hOld hL _ _ _ _ _ + (R.gridNoise_bounds R.depthCap m hm ω.1) + have hA (ω : Point.RadialTree.GridSample (n := n) R.depthCap m × (Fin (m+1) × Fin (m+1))) (i : ℕ) : + LipschitzWith (replacementConstant R) + (localAtom R S old L A pc radius (B/m*ω.2.1.val) (B/m*ω.2.2.val) lo (R.gridNoise R.depthCap m ω.1) i) := + localAtom_lipschitz R S old L hOld hL A _ _ _ _ _ _ i + have hp := selection_probability _ _ (secondaryNames (R.recentNames A R.lookback)) hF + (fun ω i _ => hA ω i) x hρ hb hlist + (fun i hi j hj hij => by + simpa only [show 2*(2*(replacementConstant R : ℝ)*ρ) = 4*(replacementConstant R : ℝ)*ρ by ring] using + localAtomPair_probability R S old L A x pc radius lo B hB R.depthCap m hk hm i j hi hj hij + (t := 2*(replacementConstant R : ℝ)*ρ) (by positivity)) + refine hp.trans ?_ + apply mul_le_mul_of_nonneg_right _ hb + apply pow_le_pow_left₀ (Nat.cast_nonneg _) + exact_mod_cast (secondaryNames_card (R.recentNames A R.lookback)).trans + (Nat.add_le_add_right (R.recentNames_card A R.lookback) 3) + +end PlanarL1.Columns.Model.SecondaryCell + + + +end + +section + +namespace PlanarL1.Columns.Model.SecondaryCell +open scoped NNReal +variable {n : ℕ} {M : Model n} {J : Set ℝ} {root : Fin n} +variable (R : Point.RadialTree (M := M) (J := J) (root := root)) +variable (S : Finset (M.Point J root)) (old L : M.Point J root → ℝ) (ordinary : Bool) + +include R in +/-- When a small ball meets the complement of the seed-ball domain, every +inside point is close to its actual distance frontier. -/ +lemma near_seed_frontier (x y z : M.Point J root) {ρ radius : ℝ} + (hy : dist x y ≤ ρ) (hz : dist x z ≤ ρ) + (hout : radius ≤ seedDistance S y) (hin : seedDistance S z ≤ radius) : + ∃ w : M.Point J root, seedDistance S w=radius ∧ dist z w ≤ 2*ρ := by + obtain ⟨w,hw,hd⟩ := Point.intermediate_between (seedDistance S) (seedDistance_lipschitz S) + R.closed_band R.interval_band z y hin hout + refine ⟨w,hw,?_⟩ + have hzy : dist z y ≤ 2*ρ := by linarith [dist_triangle z x y,dist_comm z x] + linarith [dist_nonneg (x := w) (y := y)] + +/-- The .199R spatial margin defeats the total 4+5 scalar slopes. Consequently +an entire ball touching outside is unchanged, without paying the much larger +height-shield Lipschitz constant. -/ +lemma replacement_boundary_ball (hS : S.Nonempty) (hOld : LipschitzWith 5 old) + (hL : LipschitzWith 1 L) (hζ : R.ζ = (1:ℝ)/10) + {pc radius αo : ℝ} (hr : 0 ≤ radius) (hαo : αo ≤ radius/1000) + (hδ : R.δ = (radius/1000)/8) {α : Point.RadialTree.Noise (n := n)} (hα : R.NoiseBounds α) + (hord : ordinary = true → ∀ x, L x ≤ old x) + (hadmit : ordinary = false → ∀ w ∈ S, ∀ x, dist w x = radius → pc-(65/100:ℝ)*radius ≤ old x) + (αh lo : ℝ) (x y : M.Point J root) {ρ : ℝ} + (hsmall : 18*ρ ≤ (199/1000:ℝ)*radius) + (hy : dist x y ≤ ρ) (hout : radius ≤ seedDistance S y) + (z : M.Point J root) (hz : dist x z ≤ ρ) (hin : seedDistance S z ≤ radius) : + replacement R S old L ordinary pc radius αo αh lo α z = old z := by + obtain ⟨w,hw,hd⟩ := near_seed_frontier R S x y z hy hz hout hin + have hb := spatial_boundary R S old L ordinary hS hζ hr hαo hδ hα hord hadmit hw + have hs := (spatial_lipschitz R S L ordinary pc radius αo hα hL).dist_le_mul z w + have ho := hOld.dist_le_mul z w + rw [Real.dist_eq] at hs ho + change |spatial R S L ordinary pc radius αo α z-spatial R S L ordinary pc radius αo α w| ≤ 4*dist z w at hs + change |old z-old w| ≤ 5*dist z w at ho + have hsz := (abs_le.mp hs).2 + have hoz := (abs_le.mp ho).1 + apply max_eq_left + exact (min_le_left _ _).trans (by linarith) + +end PlanarL1.Columns.Model.SecondaryCell + + + +end + +section + +namespace PlanarL1.Columns.Model.SecondaryCell +open PlanarL1.Interpolation +open scoped NNReal +variable {n : ℕ} {M : Model n} {J : Set ℝ} {root : Fin n} +variable (R : Point.RadialTree (M := M) (J := J) (root := root)) +variable (S : Finset (M.Point J root)) (old L : M.Point J root → ℝ) + +lemma localAtomConstant_probability {k : ℕ} (A : R.Node k) (x : M.Point J root) + (pc radius lo B : ℝ) (hB : 0 < B) (cap m : ℕ) (hk : k < cap) (hm : 0 < m) + (i : ℕ) (hi : i ∈ secondaryNames (R.recentNames A R.lookback)) (hi0 : i ≠ 0) + (c : ℝ) {t : ℝ} (ht : 0 ≤ t) : + FiniteRandom.prob (fun ω : Point.RadialTree.GridSample (n := n) cap m × (Fin (m+1) × Fin (m+1)) => + |localAtom R S old L A pc radius (B/m*ω.2.1.val) (B/m*ω.2.2.val) lo (R.gridNoise cap m ω.1) i x-c| ≤ t) ≤ + (2*t+R.q/m)/R.q+(2*t+B/m)/B := by + have hp : 0 ≤ (2*t+R.q/m)/R.q := by positivity [R.q_pos] + have hq : 0 ≤ (2*t+B/m)/B := by positivity + by_cases hi1 : i=1 + · subst i + apply FiniteRandom.prob_prod_bound + intro ω + apply FiniteRandom.prob_prod_bound + intro r + let d := Clipping.heightShield lo R.a pc 0 x.height-c + apply (FiniteRandom.prob_mono (fun s h => ?_)).trans + ((FiniteRandom.grid_probability m hm hB ht d).trans (le_add_of_nonneg_left hp)) + have he : d+B/m*s.val = + localAtom R S old L A pc radius (B/m*r.val) (B/m*s.val) lo (R.gridNoise cap m ω) 1 x-c := by + simp only [localAtom,secondaryAtom,reduceCtorEq,ite_true,ite_false,d,Clipping.heightShield] + ring + rwa [he] + · by_cases hi2 : i=2 + · subst i + apply FiniteRandom.prob_prod_bound + intro ω + apply FiniteRandom.prob_prod_bound_left + intro s + let d := Clipping.orderedBranch pc radius 0 L x-c + apply (FiniteRandom.prob_mono (fun r h => ?_)).trans + ((FiniteRandom.grid_probability m hm hB ht d).trans (le_add_of_nonneg_left hp)) + have he : d+B/m*r.val = + localAtom R S old L A pc radius (B/m*r.val) (B/m*s.val) lo (R.gridNoise cap m ω) 2 x-c := by + simp only [localAtom,secondaryAtom,reduceCtorEq,show (2:ℕ) ≠ 1 by decide, + ite_true,ite_false,d,Clipping.orderedBranch] + ring + rwa [he] + · have hiS : i-3 ∈ R.recentNames A R.lookback := by + rcases mem_secondaryNames.mp hi with h | h | h | h + · exact (hi0 h).elim + · exact (hi1 h).elim + · exact (hi2 h).elim + · exact h.2 + apply FiniteRandom.prob_prod_bound_left + intro rs + apply (FiniteRandom.prob_mono (fun ω h => ?_)).trans + ((R.listedConstant_probability (input S) A R.lookback (i-3) hiS x + (pc+radius/20-c) cap m hk hm ht).trans (le_add_of_nonneg_right hq)) + have he : (R.listedAtom (input S) (R.gridNoise cap m ω) A R.lookback (i-3) x).value-(pc+radius/20-c) = + -(localAtom R S old L A pc radius (B/m*rs.1.val) (B/m*rs.2.val) lo (R.gridNoise cap m ω) i x-c) := by + simp only [localAtom,secondaryAtom,ite_eq_right hi0,ite_eq_right hi1,ite_eq_right hi2] + ring + rwa [he,abs_neg] + +/-- All seed groups may use the same geometric radial hierarchy. The hierarchy +and the whole local list are chosen before their independent samples. -/ +lemma namedReplacement_local_list (hζ : R.ζ = (1:ℝ)/10) + {k : ℕ} (A : R.Node k) (x : M.Point J root) {ρ : ℝ} + (hlo : ∀ z : M.Point J root, dist x z ≤ ρ → + (k:ℝ)*R.δ ≤ dist R.base (z.withHeight R.base.height R.base.inBand)) + (heq : ∀ (p : M.Point J root → ℝ) (α : Point.RadialTree.Noise (n := n)), + R.NoiseBounds α → ∀ z : M.Point J root, dist x z ≤ ρ → + R.pasted p α z = R.formula p α k A z) + (ordinary : Bool) (pc radius αo αh lo : ℝ) + (α : Point.RadialTree.Noise (n := n)) (hα : R.NoiseBounds α) + (z : M.Point J root) (hz : dist x z ≤ ρ) : + (namedReplacement R S old L ordinary pc radius αo αh lo α z).name ∈ + secondaryNames (R.recentNames A R.lookback) ∧ + (namedReplacement R S old L ordinary pc radius αo αh lo α z).value = + localAtom R S old L A pc radius αo αh lo α + (namedReplacement R S old L ordinary pc radius αo αh lo α z).name z := by + have hp := input_lipschitz R S hζ + have ha : |(R.formula (input S) α k A z).value-input S z| ≤ 6*R.δ := by + rw [← heq (input S) α hα z hz] + exact R.pasted_accuracy hp hα z + have hn : (R.pasted (input S) α z).name ∈ R.recentNames A R.lookback := by + rw [heq (input S) α hα z hz] + exact R.formula_name_recent hp hα k A z (hlo z hz) ha + have hv : R.pasted (input S) α z = R.listedAtom (input S) α A R.lookback (R.pasted (input S) α z).name z := by + rw [heq (input S) α hα z hz] + exact R.formula_eq_listed hp hα k A z (hlo z hz) ha + apply secondaryNamed_list + (fun z => ⟨(R.pasted (input S) α z).name,pc+radius/20-(R.pasted (input S) α z).value⟩) + (fun i z => pc+radius/20-(R.listedAtom (input S) α A R.lookback i z).value) + old (Clipping.orderedBranch pc radius αo L) + (fun z => Clipping.heightShield lo R.a pc αh z.height) + ordinary (R.recentNames A R.lookback) z hn + exact congrArg (fun Z : NamedValue => pc+radius/20-Z.value) hv + + +noncomputable def simultaneousNamed {groups : ℕ} + (seeds : Fin groups → Finset (M.Point J root)) (old : M.Point J root → ℝ) + (supports : Fin groups → M.Point J root → ℝ) (ordinary : Bool) + (pc : Fin groups → ℝ) (radius lo B : ℝ) (cap m : ℕ) + (ω : Fin groups → Point.RadialTree.GridSample (n := n) cap m × (Fin (m+1) × Fin (m+1))) := + familySelection old (fun g => namedReplacement R (seeds g) old (supports g) ordinary + (pc g) radius (B/m*(ω g).2.1.val) (B/m*(ω g).2.2.val) lo (R.gridNoise cap m (ω g).1)) + +lemma sampledReplacement_lipschitz (ordinary : Bool) + (hOld : LipschitzWith 5 old) (hL : LipschitzWith 1 L) + (pc radius lo B : ℝ) (cap m : ℕ) (hm : 0 < m) + (ω : Point.RadialTree.GridSample (n := n) cap m × (Fin (m+1) × Fin (m+1))) : + LipschitzWith (replacementConstant R) (fun z => + (namedReplacement R S old L ordinary pc radius (B/m*ω.2.1.val) + (B/m*ω.2.2.val) lo (R.gridNoise cap m ω.1) z).value) := by + simp only [namedReplacement_value] + exact replacement_lipschitz R S old L ordinary hOld hL _ _ _ _ _ + (R.gridNoise_bounds cap m hm ω.1) + +lemma simultaneousNamed_local_probability {groups k : ℕ} (cap : ℕ) + (seeds : Fin groups → Finset (M.Point J root)) (old : M.Point J root → ℝ) + (supports : Fin groups → M.Point J root → ℝ) (ordinary : Bool) + (hOld : LipschitzWith 5 old) (hL : ∀ g, LipschitzWith 1 (supports g)) + (hζ : R.ζ = (1:ℝ)/10) (pc : Fin groups → ℝ) (radius lo B : ℝ) (hB : 0 < B) + (x : M.Point J root) {ρ : ℝ} (hρ : 0 ≤ ρ) + (A : R.Node k) (hk : k < cap) + (hlo : ∀ z : M.Point J root, dist x z ≤ ρ → + (k:ℝ)*R.δ ≤ dist R.base (z.withHeight R.base.height R.base.inBand)) + (heq : ∀ (p : M.Point J root → ℝ) (α : Point.RadialTree.Noise (n := n)), + R.NoiseBounds α → ∀ z : M.Point J root, dist x z ≤ ρ → + R.pasted p α z = R.formula p α k A z) + (m : ℕ) (hm : 0 < m) : + FiniteRandom.prob (fun ω : Fin groups → + Point.RadialTree.GridSample (n := n) cap m × (Fin (m+1) × Fin (m+1)) => + ∃ z : M.Point J root, dist x z ≤ ρ ∧ + (simultaneousNamed R seeds old supports ordinary pc radius lo B cap m ω z).name ≠ + (simultaneousNamed R seeds old supports ordinary pc radius lo B cap m ω x).name) ≤ + (1+groups*(6*(R.lookback+1)+3) : ℕ)^2 * + ((4*(replacementConstant R : ℝ)*ρ+R.q/m)/R.q+ + (4*(replacementConstant R : ℝ)*ρ+B/m)/B) := by + classical + let F := fun (g : Fin groups) + (ω : Point.RadialTree.GridSample (n := n) cap m × (Fin (m+1) × Fin (m+1))) => + namedReplacement R (seeds g) old (supports g) ordinary (pc g) radius (B/m*ω.2.1.val) + (B/m*ω.2.2.val) lo (R.gridNoise cap m ω.1) + let atom := fun (g : Fin groups) + (ω : Point.RadialTree.GridSample (n := n) cap m × (Fin (m+1) × Fin (m+1))) => + localAtom R (seeds g) old (supports g) A (pc g) radius (B/m*ω.2.1.val) + (B/m*ω.2.2.val) lo (R.gridNoise cap m ω.1) + let names : Fin groups → Finset ℕ := fun _ => secondaryNames (R.recentNames A R.lookback) + have hF g ω : LipschitzWith (replacementConstant R) (fun z => (F g ω z).value) := + sampledReplacement_lipschitz R (seeds g) old (supports g) ordinary hOld (hL g) + (pc g) radius lo B cap m hm ω + have hA g ω i : LipschitzWith (replacementConstant R) (atom g ω i) := + localAtom_lipschitz R (seeds g) old (supports g) hOld (hL g) A _ _ _ _ _ _ i + have h0 g ω z : atom g ω 0 z=old z := by simp [atom,localAtom,secondaryAtom] + have hcard g : (names g).card ≤ 6*(R.lookback+1)+3 := + (secondaryNames_card _).trans (Nat.add_le_add_right (R.recentNames_card A R.lookback) 3) + have hlist g ω z (hz : dist x z ≤ ρ) : (F g ω z).name ∈ names g ∧ + (F g ω z).value=atom g ω (F g ω z).name z := + namedReplacement_local_list R (seeds g) old (supports g) hζ A x hlo heq ordinary _ _ _ _ _ _ + (R.gridNoise_bounds cap m hm ω.1) z hz + have ht : 0 ≤ 2*(replacementConstant R : ℝ)*ρ := by positivity + change FiniteRandom.prob (fun ω : Fin groups → + Point.RadialTree.GridSample (n := n) cap m × (Fin (m+1) × Fin (m+1)) => ∃ z, dist x z ≤ ρ ∧ + (familySelection old (fun g => F g (ω g)) z).name ≠ + (familySelection old (fun g => F g (ω g)) x).name) ≤ _ + apply familySelection_probability (K := replacementConstant R) old F atom names (hOld.weaken (le_max_left _ _)) + hF hA h0 hcard x hρ (by positivity [R.q_pos]) hlist + · intro g i hi j hj hij + simpa only [atom, show 2*(2*(replacementConstant R : ℝ)*ρ)=4*(replacementConstant R : ℝ)*ρ by ring] using + localAtomPair_probability R (seeds g) old (supports g) A x (pc g) radius lo B hB cap m hk hm + i j hi hj hij ht + · intro g i hi hi0 c + simpa only [atom, show 2*(2*(replacementConstant R : ℝ)*ρ)=4*(replacementConstant R : ℝ)*ρ by ring] using + localAtomConstant_probability R (seeds g) old (supports g) A x (pc g) radius lo B hB cap m hk hm + i hi hi0 c ht + +/-- The actual simultaneous secondary finite maximum has a local name bound +independent of graph size once seed packing bounds the number of groups. -/ +theorem simultaneousNamed_probability {groups : ℕ} + (seeds : Fin groups → Finset (M.Point J root)) (old : M.Point J root → ℝ) + (supports : Fin groups → M.Point J root → ℝ) (ordinary : Bool) + (hOld : LipschitzWith 5 old) (hL : ∀ g, LipschitzWith 1 (supports g)) + (hζ : R.ζ = (1:ℝ)/10) (pc : Fin groups → ℝ) (radius lo B : ℝ) (hB : 0 < B) + (x : M.Point J root) {ρ : ℝ} (hρ : 0 ≤ ρ) (hs : ρ ≤ R.radius) + (m : ℕ) (hm : 0 < m) : + FiniteRandom.prob (fun ω : Fin groups → + Point.RadialTree.GridSample (n := n) R.depthCap m × (Fin (m+1) × Fin (m+1)) => + ∃ z : M.Point J root, dist x z ≤ ρ ∧ + (simultaneousNamed R seeds old supports ordinary pc radius lo B R.depthCap m ω z).name ≠ + (simultaneousNamed R seeds old supports ordinary pc radius lo B R.depthCap m ω x).name) ≤ + (1+groups*(6*(R.lookback+1)+3) : ℕ)^2 * + ((4*(replacementConstant R : ℝ)*ρ+R.q/m)/R.q+ + (4*(replacementConstant R : ℝ)*ρ+B/m)/B) := by + obtain ⟨k,A,hlo,heq⟩ := R.common_formula x hρ hs + have hk : k < R.depthCap := + (R.depth_le_layerDepth x (hlo x (by simpa using hρ))).trans_lt (R.layerDepth_lt_cap x) + exact simultaneousNamed_local_probability R R.depthCap seeds old supports ordinary hOld hL hζ pc radius lo B hB + x hρ A hk hlo heq m hm + +end PlanarL1.Columns.Model.SecondaryCell + + + +end + +end OAI diff --git a/lean/OAI/Combinatorics/PlanarL1/SecondaryFamily.lean b/lean/OAI/Combinatorics/PlanarL1/SecondaryFamily.lean new file mode 100644 index 0000000000000000000000000000000000000000..4d7f622cf9dc3b484b8dadacad224199225fdcdd --- /dev/null +++ b/lean/OAI/Combinatorics/PlanarL1/SecondaryFamily.lean @@ -0,0 +1,374 @@ +import OAI.Combinatorics.PlanarL1.MainFamily +import OAI.Combinatorics.PlanarL1.SecondaryBatch + +namespace OAI + + +section + +namespace PlanarL1.Columns.Model +open MeasureTheory Parameters +open scoped NNReal +attribute [local instance] Classical.propDecidable +variable {k : ℕ} {M : Model (k+1)} + +namespace BData +/-- A proved ordered support at the actual representative of a group. +The support is needed only in an ordinary chart; ordered charts use their +literal sphere admission test instead. -/ +lemma support_at (D : BData M) (lam : ℝ≥0) (hlam : lam≤(1:ℝ≥0)/100) + (positive : Bool) (i : Fin (k+1)) (H : ℝ) (hi : H ∈ D.band) (hu : D.Uses i) : + ∃ (F : M.Field D.band 1) (a b : Fin (k+1)), F.OrderedFrom a b ∧ + (D.isOrdinary=true → F.value i ⟨H,hi⟩=(D.comparison lam hlam positive).value i ⟨H,hi⟩) ∧ + ∀ (j : Fin (k+1)) (T : D.band), D.isOrdinary=true → D.Uses j → + F.value j T≤(D.comparison lam hlam positive).value j T := by + cases D with + | ordinary C => + obtain ⟨F,a,b,ho,he,hF⟩ := C.support_at i H ⟨hi,hu⟩ + refine ⟨F,a,b,ho,fun _ => he,?_⟩ + intro j T _ hj + exact hF j T.val ⟨T.property,hj⟩ + | ordered C => + exact ⟨Field.constant M C.band 0,0,0,Field.constant_ordered 0 0 0, + by simp [isOrdinary],by simp [isOrdinary]⟩ + +lemma uses_reachable (D : BData M) {i j : Fin (k+1)} (hi : D.Uses i) + (hr : (M.activeGraph D.band).Reachable i j) : D.Uses j := by + cases D with + | ordered _ => trivial + | ordinary C => exact fun r o ho => (hi r o ho).trans hr +end BData + +namespace SecondaryGeometry +variable {Ω : Type*} [MeasurableSpace Ω] {μ : Measure Ω} +variable (A : Ambient M) (S : BState M kappaB (⟨lambda,by norm_num [lambda,R]⟩) Ω μ) + +/-- The geometric information attached to one actual surviving g-cell group. +The seed collection is finite, lies in one broad component and one narrow +height band, and keeps its TWO chart identifiers through the surviving-pair +selection. The B half needed for its literal update is recorded here. -/ +structure Group where + index : Fin (S.count+1) + broad : Set ℝ + broad_root : Fin (k+1) + broad_closed : IsClosed broad + lower : ℝ + narrow_sub : BandTrees.band narrow lower ⊆ broad + sub_old : broad ⊆ (S.chart index).band + seeds : Finset (M.Point broad broad_root) + nonempty : seeds.Nonempty + height : ∀ w ∈ seeds, w.height ∈ BandTrees.band narrow lower + diameter : ∀ w ∈ seeds, ∀ v ∈ seeds, dist w v≤10*g + common : ∀ w ∈ seeds, A.Common S.name (A.point w.column w.height) 5 index + +namespace Group +variable {A S} (G : Group A S) +noncomputable def representative : M.Point G.broad G.broad_root := G.nonempty.choose +lemma representative_mem : G.representative ∈ G.seeds := G.nonempty.choose_spec +noncomputable abbrev data : BData M := S.chart G.index +noncomputable def lam : ℝ≥0 := ⟨lambda,by norm_num [lambda,R]⟩ +lemma lam_bound : lam≤(1:ℝ≥0)/100 := by + change lambda≤(1:ℝ)/100 + norm_num [lambda,R] +noncomputable def comparison (positive : Bool) : M.Field G.data.band 5 := + G.data.comparison lam lam_bound positive +noncomputable def value (positive : Bool) (x : M.Point G.broad G.broad_root) : ℝ := + (G.comparison positive).value x.column ⟨x.height,G.sub_old x.inBand⟩ +noncomputable def pc (positive : Bool) : ℝ := G.value positive G.representative + +lemma representative_uses : G.data.Uses G.representative.column := by + apply S.uses_named _ G.representative.height G.index + exact (G.common G.representative G.representative_mem).center A (by norm_num) + +lemma value_lipschitz (positive : Bool) : LipschitzWith 5 (G.value positive) := + ((G.comparison positive).restrict G.sub_old).lipschitz G.broad_closed G.broad_root + +lemma value_near (positive : Bool) (w : M.Point G.broad G.broad_root) (hw : w ∈ G.seeds) : + |G.value positive w-G.pc positive|≤50*g := by + have h := (G.value_lipschitz positive).dist_le_mul w G.representative + rw [Real.dist_eq] at h + have hd := G.diameter w hw G.representative G.representative_mem + change |G.value positive w-G.pc positive|≤5*dist w G.representative at h + linarith + +abbrev Component := BandTrees.Component M narrow G.lower +noncomputable abbrev root (C : G.Component) := BandTrees.root M narrow G.lower C +noncomputable abbrev tree (C : G.Component) := BandTrees.tree M narrow G.lower C + +noncomputable def inComponent (C : G.Component) : Finset (M.Point G.broad G.broad_root) := + G.seeds.filter (fun w => w.column ∈ C.supp) + +noncomputable def narrowPoint (C : G.Component) (w : G.inComponent C) : + M.Point (BandTrees.band narrow G.lower) (G.root C) := + ⟨w.val.column,w.val.height,G.height w.val (Finset.mem_filter.mp w.property).1, + C.reachable_of_mem_supp (BandTrees.root_mem M narrow G.lower C) (Finset.mem_filter.mp w.property).2⟩ + +noncomputable def allSeeds (C : G.Component) : Finset (M.Point (BandTrees.band narrow G.lower) (G.root C)) := + (G.inComponent C).attach.image (G.narrowPoint C) + +lemma allSeeds_description (C : G.Component) (x : M.Point (BandTrees.band narrow G.lower) (G.root C)) : + x ∈ G.allSeeds C ↔ ∃ w ∈ G.seeds, w.column=x.column ∧ w.height=x.height := by + constructor + · intro hx + obtain ⟨w,_,rfl⟩ := Finset.mem_image.mp hx + exact ⟨w.val,(Finset.mem_filter.mp w.property).1,rfl,rfl⟩ + · rintro ⟨w,hw,hc,hH⟩ + have hcol : w.column ∈ C.supp := hc ▸ BandTrees.reachable_mem M narrow G.lower C x.reachable + let w' : G.inComponent C := ⟨w,Finset.mem_filter.mpr ⟨hw,hcol⟩⟩ + refine Finset.mem_image.mpr ⟨w',Finset.mem_attach _ _,?_⟩ + obtain ⟨xc,xh,xi,xr⟩ := x + dsimp only at hc hH + cases hc + cases hH + rfl + +noncomputable def old (positive : Bool) (C : G.Component) + (x : M.Point (BandTrees.band narrow G.lower) (G.root C)) : ℝ := + (G.comparison positive).value x.column ⟨x.height,G.sub_old (G.narrow_sub x.inBand)⟩ + +/-- Literal admission; every ordinary seed is kept, and in an ordered chart +this tests all points on the intrinsic narrow-band sphere. -/ +def Admitted (positive : Bool) (C : G.Component) + (w : M.Point (BandTrees.band narrow G.lower) (G.root C)) : Prop := + G.data.isOrdinary=true ∨ ∀ x : M.Point (BandTrees.band narrow G.lower) (G.root C), + dist w x=R → G.pc positive-(65/100:ℝ)*R≤G.old positive C x + +noncomputable def admittedSeeds (positive : Bool) (C : G.Component) := + (G.allSeeds C).filter (G.Admitted positive C) + +lemma admitted_sphere (positive : Bool) (C : G.Component) (hord : G.data.isOrdinary=false) + (w : M.Point (BandTrees.band narrow G.lower) (G.root C)) (hw : w ∈ G.admittedSeeds positive C) : + ∀ x : M.Point (BandTrees.band narrow G.lower) (G.root C), + dist w x=R → G.pc positive-(65/100:ℝ)*R≤G.old positive C x := by + obtain ⟨_,ha⟩ := Finset.mem_filter.mp hw + exact ha.resolve_left (by simp [hord]) + +lemma ordinary_admits (positive : Bool) (C : G.Component) (hord : G.data.isOrdinary=true) : + G.admittedSeeds positive C=G.allSeeds C := by + apply Finset.filter_true_of_mem + intro w _ + exact Or.inl hord + +end Group +end SecondaryGeometry +end PlanarL1.Columns.Model + +end + + + +section + +namespace PlanarL1.Columns.Model.SecondaryGeometry.Group +open MeasureTheory Parameters +open scoped NNReal +attribute [local instance] Classical.propDecidable +variable {k : ℕ} {M : Model (k+1)} {Ω : Type*} [MeasurableSpace Ω] {μ : Measure Ω} +variable {A : Ambient M} {S : BState M kappaB (⟨lambda,by norm_num [lambda,R]⟩) Ω μ} +variable (G : SecondaryGeometry.Group A S) + +structure Support (positive : Bool) where + field : M.Field G.data.band 1 + lower : Fin (k+1) + upper : Fin (k+1) + ordered : field.OrderedFrom lower upper + at_center : G.data.isOrdinary=true → + field.value G.representative.column ⟨G.representative.height,G.sub_old G.representative.inBand⟩=G.pc positive + below : ∀ (i : Fin (k+1)) (H : G.data.band), G.data.isOrdinary=true → G.data.Uses i → + field.value i H≤(G.comparison positive).value i H + +noncomputable def support (positive : Bool) : G.Support positive := by + apply Classical.choice + obtain ⟨F,a,b,ho,he,hF⟩ := G.data.support_at lam lam_bound positive + G.representative.column G.representative.height (G.sub_old G.representative.inBand) G.representative_uses + exact ⟨⟨F,a,b,ho,he,hF⟩⟩ + +lemma old_eq (positive : Bool) (C : G.Component) (w : M.Point G.broad G.broad_root) + (x : M.Point (BandTrees.band narrow G.lower) (G.root C)) + (hc : w.column=x.column) (hH : w.height=x.height) : G.old positive C x=G.value positive w := by + dsimp only [old,value] + congr 1 + exacts [hc.symm,Subtype.ext hH.symm] + +lemma seed_common (C : G.Component) (x : M.Point (BandTrees.band narrow G.lower) (G.root C)) + (hx : x ∈ G.allSeeds C) : A.Common S.name (A.point x.column x.height) 5 G.index := by + obtain ⟨w,hw,hc,hH⟩ := (G.allSeeds_description C x).mp hx + rw [← hc,← hH] + exact G.common w hw + +lemma component_uses (C : G.Component) (hC : (G.allSeeds C).Nonempty) + (x : M.Point (BandTrees.band narrow G.lower) (G.root C)) : G.data.Uses x.column := by + obtain ⟨w,hw⟩ := hC + have hu : G.data.Uses w.column := S.uses_named w.column w.height G.index + ((G.seed_common C w hw).center A (by norm_num)) + obtain ⟨p,_,_⟩ := w.exists_shortest isClosed_Icc x + exact G.data.uses_reachable hu (p.widen (G.narrow_sub.trans G.sub_old)).word.reachable + +lemma seed_near (positive : Bool) (C : G.Component) + (x : M.Point (BandTrees.band narrow G.lower) (G.root C)) (hx : x ∈ G.allSeeds C) : + |G.old positive C x-G.pc positive|≤(60/1000000:ℝ)*R := by + obtain ⟨w,hw,hc,hH⟩ := (G.allSeeds_description C x).mp hx + rw [G.old_eq positive C w x hc hH] + exact (G.value_near positive w hw).trans (by norm_num [g,R]) + +lemma support_seed_near (positive : Bool) (C : G.Component) + (ho : G.data.isOrdinary=true) + (x : M.Point (BandTrees.band narrow G.lower) (G.root C)) (hx : x ∈ G.allSeeds C) : + |(G.support positive).field.value x.column ⟨x.height,G.sub_old (G.narrow_sub x.inBand)⟩- + G.pc positive|≤10*g := by + obtain ⟨w,hw,hc,hH⟩ := (G.allSeeds_description C x).mp hx + have h := (((G.support positive).field.restrict G.sub_old).lipschitz G.broad_closed + G.broad_root).dist_le_mul w G.representative + rw [Real.dist_eq,NNReal.coe_one,one_mul] at h + change |(G.support positive).field.value w.column ⟨w.height,G.sub_old w.inBand⟩- + (G.support positive).field.value G.representative.column + ⟨G.representative.height,G.sub_old G.representative.inBand⟩|≤dist w G.representative at h + rw [(G.support positive).at_center ho] at h + have he : (G.support positive).field.value w.column ⟨w.height,G.sub_old w.inBand⟩= + (G.support positive).field.value x.column ⟨x.height,G.sub_old (G.narrow_sub x.inBand)⟩ := by + exact congrArg₂ (G.support positive).field.value hc (Subtype.ext hH) + rw [he] at h + exact h.trans (G.diameter w hw G.representative G.representative_mem) + +lemma domain_name (positive : Bool) (C : G.Component) + (hC : (G.admittedSeeds positive C).Nonempty) (i : Fin (k+1)) (H : ℝ) + (hi : H ∈ SecondaryCell.domain (G.admittedSeeds positive C) R i) : S.name i H=G.index := by + obtain ⟨x,hx,hH,hd⟩ := (SecondaryCell.mem_domain _ _).mp hi + obtain ⟨w,hw,he⟩ := SecondaryCell.seedDistance_attained _ hC x + have hc := G.seed_common C w (Finset.mem_filter.mp hw).1 + have hdist : dist (A.point w.column w.height) (A.point i H)≤5 := by + rw [← hx,← hH] + have ha := MainFamily.ambient_dist_le A w x + rw [dist_comm w x,← he] at ha + exact ha.trans (hd.trans (by norm_num [R])) + exact hc (A.point i H) hdist + +/-- A nonempty admitted component now produces the literal, fully proved +secondary clipping operation. No admission, support, name-gluing or movement +conclusion is added as an assumption of the step. -/ +noncomputable def step (positive : Bool) (C : G.Component) + (hC : (G.admittedSeeds positive C).Nonempty) + (noise : Point.RadialTree.Noise (n := k+1)) (hn : (G.tree C).NoiseBounds noise) + (alpha beta : ℝ) (ha : alpha≤EB) (hb : beta≤EB) : + BState.SecondaryStep S (BandTrees.band narrow G.lower) (G.root C) where + index := G.index + positive := positive + lambda_bound := lam_bound + tree := G.tree C + lo := G.lower + band_eq := rfl + sub_old := G.narrow_sub.trans G.sub_old + seeds := G.admittedSeeds positive C + seeds_nonempty := hC + pc := G.pc positive + radius := R + radius_nonneg := by norm_num [R] + radius_small := by norm_num [R] + support := (G.support positive).field + lower := (G.support positive).lower + upper := (G.support positive).upper + support_ordered := (G.support positive).ordered + support_le := by + intro ho x + exact (G.support positive).below x.column _ ho + (G.component_uses C (hC.mono (Finset.filter_subset _ _)) x) + admitted := G.admitted_sphere positive C + seed_near := fun w hw => G.seed_near positive C w (Finset.mem_filter.mp hw).1 + zeta_eq := rfl + delta_eq := rfl + noise := noise + noise_bounds := hn + ordered_offset := alpha + shield_offset := beta + ordered_bound := ha + shield_bound := hb + same_name := G.domain_name positive C hC + kappa_nonneg := verticalB.1 + vertical_bound := verticalB.2.1 + shield_strict := verticalB.2.2.1 + +end PlanarL1.Columns.Model.SecondaryGeometry.Group + +end + + + +section + +namespace PlanarL1.Columns.Model.SecondaryGeometry +open MeasureTheory Parameters +attribute [local instance] Classical.propDecidable +variable {k : ℕ} {M : Model (k+1)} {Ω : Type*} [MeasurableSpace Ω] {μ : Measure Ω} +variable {A : Ambient M} {S : BState M kappaB Group.lam Ω μ} +variable {I : Type*} [Fintype I] (G : I → Group A S) + +/-- Offsets are fresh for each narrow component. The keep coin, by contrast, +is shared by all the components of one surviving group. -/ +abbrev ComponentSample (i : I) (C : (G i).Component) (m : ℕ) := + Point.RadialTree.GridSample (n := k+1) ((G i).tree C).depthCap m × Fin (m+1) × Fin (m+1) +abbrev Sample (m : ℕ) := + (Fin (S.count+1) → Bool) × (I → Bool) × (∀ i C, ComponentSample G i C m) +noncomputable instance (m : ℕ) : Fintype (Sample G m) := Fintype.ofFinite _ +instance (m : ℕ) : Nonempty (Sample G m) := inferInstanceAs (Nonempty (_ × _ × _)) + +variable {m : ℕ} (hm : 0 < m) (omega : Sample G m) + +def kept (i : I) : Prop := omega.2.1 i=true +abbrev Acting (a : Fin (S.count+1)) := + {q : Σ i, (G i).Component // (G q.1).index=a ∧ kept G omega q.1 ∧ + ((G q.1).admittedSeeds (omega.1 a) q.2).Nonempty} +noncomputable instance (a : Fin (S.count+1)) : Fintype (Acting G omega a) := Fintype.ofFinite _ + +include hm in +lemma offset_bound (t : Fin (m+1)) : + EB/(m:ℝ)*(t.val:ℝ)≤EB := by + have hmR : (0:ℝ) < m := by exact_mod_cast hm + have ht : (t.val:ℝ) ≤ m := by exact_mod_cast t.is_le + calc _ ≤ EB/m*m := mul_le_mul_of_nonneg_left ht (div_nonneg (by norm_num [EB,R]) hmR.le) + _ = EB := div_mul_cancel₀ _ hmR.ne' + +noncomputable def actingStep (a : Fin (S.count+1)) (q : Acting G omega a) := + (G q.val.1).step (omega.1 a) q.val.2 q.property.2.2 + (((G q.val.1).tree q.val.2).gridNoise _ m (omega.2.2 q.val.1 q.val.2).1) + (((G q.val.1).tree q.val.2).gridNoise_bounds _ _ hm (omega.2.2 q.val.1 q.val.2).1) + (EB/m*(omega.2.2 q.val.1 q.val.2).2.1.val) + (EB/m*(omega.2.2 q.val.1 q.val.2).2.2.val) + (offset_bound hm _) + (offset_bound hm _) + +/-- Literal maximum within an old B identifier. Neither disjoint domains nor +an assumed winning branch replaces the actual overlapping maximum. -/ +noncomputable def batch (a : Fin (S.count+1)) : BState.SecondaryBatch S where + index := a + positive := omega.1 a + lambda_bound := Group.lam_bound + count := Fintype.card (Acting G omega a) + band j := BandTrees.band narrow + (G ((Fintype.equivFin (Acting G omega a)).symm j).val.1).lower + root j := (G ((Fintype.equivFin (Acting G omega a)).symm j).val.1).root + ((Fintype.equivFin (Acting G omega a)).symm j).val.2 + step j := actingStep G hm omega a ((Fintype.equivFin (Acting G omega a)).symm j) + same_index j := ((Fintype.equivFin (Acting G omega a)).symm j).property.1 + same_positive _ := rfl + kappa_nonneg := verticalB.1 + kappa_five := verticalB.2.2.2 + +noncomputable def layer : BState.SecondaryLayer S where + batch := batch G hm omega + same_index _ := rfl + +noncomputable def result [SFinite μ] : + BState M kappaB Group.lam (Ω × Bool) (μ.prod Threshold.fair) := + (layer G hm omega).apply + +/-- Sampling all orientations, group coins, interpolation atoms and branches +is a finite execution determined from the old geometric groups. -/ +noncomputable def execution [SFinite μ] : + Execution (BState M kappaB Group.lam (Ω × Bool) (μ.prod Threshold.fair)) := + (Execution.uniform (α := Sample G m)).bind fun omega => .pure (result G hm omega) + +end PlanarL1.Columns.Model.SecondaryGeometry + +end + +end OAI diff --git a/lean/OAI/Combinatorics/PlanarL1/SecondaryGain.lean b/lean/OAI/Combinatorics/PlanarL1/SecondaryGain.lean new file mode 100644 index 0000000000000000000000000000000000000000..a6a85d55171fc014e37d7987a6d347e84d82cbf3 --- /dev/null +++ b/lean/OAI/Combinatorics/PlanarL1/SecondaryGain.lean @@ -0,0 +1,663 @@ +import OAI.Combinatorics.PlanarL1.MainGain + +namespace OAI + + +section + +namespace PlanarL1.Columns.Model.RetainedSelection +open Parameters +variable {k : ℕ} {M : Model (k+1)} {q p L U : ℝ} +namespace Block +variable (b : Block (M := M) q p L U) +lemma broad_eq : BandTrees.band broad b.lower=Tiling.band a₁ q b.1.1.val := by + ext H + simp only [BandTrees.band,lower,MainFamily.lower,Tiling.band,Set.mem_Icc] + change (_≤H ∧ H≤q+(b.1.1.val:ℝ)*a₁+a₁) ↔ (_≤H ∧ H≤q+((b.1.1.val:ℝ)+1)*a₁) + ring_nf +lemma narrow_eq : BandTrees.band narrow b.lower₂=Tiling.band a₂ p b.2.val.val := by + ext H + simp only [BandTrees.band,lower₂,Tiling.band,Set.mem_Icc] + change (_≤H ∧ H≤p+(b.2.val.val:ℝ)*a₂+a₂) ↔ (_≤H ∧ H≤p+((b.2.val.val:ℝ)+1)*a₂) + ring_nf + +/-- At a doubly height-interior point, a narrow-band path can reach a seed +only in this very processed broad/component/narrow block. -/ +lemma eq_of_path (d : Block (M := M) q p L U) + (c : M.Point (BandTrees.band broad b.lower) (BandTrees.root M broad b.lower b.1.2)) + (e : M.Point (BandTrees.band broad d.lower) (BandTrees.root M broad d.lower d.1.2)) + (hc : c.height ∈ BandTrees.band narrow b.lower₂) + (hd : c.height ∈ BandTrees.band narrow d.lower₂) + (hp : Tiling.Padded a₁ q c.height (a₁/10)) + (hn : Tiling.Padded a₂ p c.height (a₂/10)) + (path : M.Path (BandTrees.band narrow d.lower₂) c.column e.column) : b=d := by + have hNb : b.2.val.val=Tiling.index a₂ p c.height := + Tiling.unique_band_of_padded interpolationB.2.1 (by norm_num [a₂]) hn (b.narrow_eq ▸ hc) + have hNd : d.2.val.val=Tiling.index a₂ p c.height := + Tiling.unique_band_of_padded interpolationB.2.1 (by norm_num [a₂]) hn (d.narrow_eq ▸ hd) + have hBb : b.1.1.val=Tiling.index a₁ q c.height := + Tiling.unique_band_of_padded interpolationA.2.1 (by norm_num [a₁]) hp (b.broad_eq ▸ c.inBand) + have hBd : d.1.1.val=Tiling.index a₁ q c.height := + Tiling.unique_band_of_padded interpolationA.2.1 (by norm_num [a₁]) hp (d.broad_eq ▸ d.sub hd) + have hB : b.1.1=d.1.1 := Subtype.ext (hBb.trans hBd.symm) + rcases b with ⟨⟨bi,bC⟩,bn⟩ + rcases d with ⟨⟨di,dC⟩,dn⟩ + dsimp only at hB + subst di + have hC : bC=dC := by + have hr := c.reachable.trans ((path.widen (Block.sub ⟨⟨bi,dC⟩,dn⟩)).word.reachable.trans e.reachable.symm) + have hm := SimpleGraph.ConnectedComponent.sound hr + have hb : (M.activeGraph (BandTrees.band broad (MainFamily.lower q L U bi))).connectedComponentMk + (BandTrees.root M broad (MainFamily.lower q L U bi) bC)=bC := BandTrees.root_mem _ _ _ _ + have hd' : (M.activeGraph (BandTrees.band broad (MainFamily.lower q L U bi))).connectedComponentMk + (BandTrees.root M broad (MainFamily.lower q L U bi) dC)=dC := BandTrees.root_mem _ _ _ _ + exact hb.symm.trans (hm.trans hd') + subst dC + have hN : bn=dn := Subtype.ext (Subtype.ext (hNb.trans hNd.symm)) + subst dn + rfl +end Block +end PlanarL1.Columns.Model.RetainedSelection + +end + + + +section + +namespace PlanarL1.Columns.Model.RetainedSelection +open Parameters MeasureTheory +attribute [local instance] Classical.propDecidable +variable {k : ℕ} {M : Model (k+1)} {V Ω Ξ : Type*} +variable [Fintype V] [MeasurableSpace Ω] [MeasurableSpace Ξ] +variable {μ : Measure Ω} {ν : Measure Ξ} +variable (A : Ambient M) (SA : OrdinaryState M kappaA Ω μ) +variable (SB : BState M kappaB SecondaryGeometry.Group.lam Ξ ν) +variable (v : V → M.Point Set.univ A.root) +variable {L U : ℝ} (hv : ∀ x, (v x).height ∈ Set.Icc L U) +variable {q p : ℝ} {phaseD phaseG : MainFamily.BandComponent (M := M) q L U → ℝ} +variable (b : Block (M := M) q p L U) +variable (c : M.Point (BandTrees.band broad b.lower) (BandTrees.root M broad b.lower b.1.2)) + +/-- All actual processed groups that can affect this point through their +narrow-band geometry. It is not just the groups having a prescribed ID. -/ +def Touch (i : GroupIndex A SA SB v hv (p := p) (phaseD := phaseD) (phaseG := phaseG)) : Prop := + c.height ∈ BandTrees.band narrow i.1.lower₂ ∧ + ∃ w, SurvivingGroups.key (localSeeds A SA SB v hv (phaseD := phaseD) (phaseG := phaseG) i.1) w=i.2.val ∧ + ∃ path : M.Path (BandTrees.band narrow i.1.lower₂) c.column (localSeeds A SA SB v hv (phaseD := phaseD) (phaseG := phaseG) i.1 w).point.column, + path.length c.height (localSeeds A SA SB v hv (phaseD := phaseD) (phaseG := phaseG) i.1 w).point.height≤4*R +noncomputable abbrev Hits := + {i : GroupIndex A SA SB v hv (p := p) (phaseD := phaseD) (phaseG := phaseG) // Touch A SA SB v hv b c i} +noncomputable instance : Fintype (Hits A SA SB v hv b c (phaseD := phaseD) (phaseG := phaseG)) := + Fintype.ofFinite _ + +variable (hc : c.height ∈ BandTrees.band narrow b.lower₂) +variable (hp : Tiling.Padded a₁ q c.height (a₁/10)) (hn : Tiling.Padded a₂ p c.height (a₂/10)) +include hc hp hn + +lemma touch_block {i : GroupIndex A SA SB v hv (p := p) (phaseD := phaseD) (phaseG := phaseG)} + (h : Touch A SA SB v hv b c i) : i.1=b := by + obtain ⟨w,_,path,_⟩ := h.2 + exact (b.eq_of_path i.1 c (localSeeds A SA SB v hv (phaseD := phaseD) (phaseG := phaseG) i.1 w).point hc h.1 hp hn path).symm + +noncomputable def localHit (i : Hits A SA SB v hv b c (phaseD := phaseD) (phaseG := phaseG)) : + SurvivingGroups.Hits (localSeeds A SA SB v hv (phaseD := phaseD) (phaseG := phaseG) b) c := by + have he := touch_block A SA SB v hv b c hc hp hn i.property + rcases i with ⟨⟨d,j⟩,hi⟩ + dsimp only at he + subst d + exact ⟨j,hi.2⟩ + +lemma localHit_injective : Function.Injective + (localHit A SA SB v hv b c hc hp hn (phaseD := phaseD) (phaseG := phaseG)) := by + intro i j he + have hi := touch_block A SA SB v hv b c hc hp hn i.property + have hj := touch_block A SA SB v hv b c hc hp hn j.property + rcases i with ⟨⟨d,i⟩,hi'⟩ + rcases j with ⟨⟨e,j⟩,hj'⟩ + dsimp only at hi hj + subst d + subst e + have hraw : i=j := congrArg Subtype.val he + subst j + rfl + +/-- Universal packing for the whole actual, finitely selected family. Both +old identifiers are derived by the local packing theorem, not assumed. -/ +lemma touching_card : Fintype.card (Hits A SA SB v hv b c (phaseD := phaseD) (phaseG := phaseG))≤ + SurvivingGroups.packBound := by + let := SurvivingGroups.instFintypeHits + (localSeeds A SA SB v hv (phaseD := phaseD) (phaseG := phaseG) b) c + have hb := SurvivingGroups.touching_card + (localSeeds A SA SB v hv (phaseD := phaseD) (phaseG := phaseG) b) b.sub c hc + apply le_trans _ hb + exact Fintype.card_le_of_injective _ (localHit_injective A SA SB v hv b c hc hp hn) + +lemma touching_finset_card : + (Finset.univ.filter (Touch A SA SB v hv b c (phaseD := phaseD) (phaseG := phaseG))).card≤ + SurvivingGroups.packBound := by + simpa only [Hits,Fintype.card_subtype] using touching_card A SA SB v hv b c hc hp hn + +end PlanarL1.Columns.Model.RetainedSelection + +end + + + +section + +namespace PlanarL1.Columns.Model.SecondaryGeometry.Group +open MeasureTheory Parameters +open scoped NNReal +attribute [local instance] Classical.propDecidable +variable {k : ℕ} {M : Model (k+1)} {Ω : Type*} [MeasurableSpace Ω] {μ : Measure Ω} +variable {A : Ambient M} {S : BState M kappaB lam Ω μ} +variable (G : SecondaryGeometry.Group A S) + +lemma seed_domain (positive : Bool) (C : G.Component) + (x : M.Point (BandTrees.band narrow G.lower) (G.root C)) + (hx : x ∈ G.admittedSeeds positive C) : + x.height ∈ SecondaryCell.domain (G.admittedSeeds positive C) R x.column := by + apply (SecondaryCell.mem_domain _ _).mpr + exact ⟨x,rfl,rfl,by rw [SecondaryCell.seedDistance_seed _ hx]; norm_num [R]⟩ + +lemma seed_cellPoint (positive : Bool) (C : G.Component) + (x : M.Point (BandTrees.band narrow G.lower) (G.root C)) + (hx : x ∈ G.admittedSeeds positive C) : + SecondaryCell.point (G.admittedSeeds positive C) R x.column x.height (G.seed_domain positive C x hx)=x := by + have hc := SecondaryCell.point_column (G.admittedSeeds positive C) R (G.seed_domain positive C x hx) + have ht := SecondaryCell.point_height (G.admittedSeeds positive C) R (G.seed_domain positive C x hx) + generalize SecondaryCell.point (G.admittedSeeds positive C) R x.column x.height + (G.seed_domain positive C x hx) = y at hc ht ⊢ + cases x + cases y + cases hc + cases ht + rfl + +lemma step_gain (positive : Bool) (C : G.Component) + (hC : (G.admittedSeeds positive C).Nonempty) + (noise : Point.RadialTree.Noise (n := k+1)) (hnoise : (G.tree C).NoiseBounds noise) + (alpha beta : ℝ) (ha : alpha ≤ EB) (hb : beta ≤ EB) (ha0 : 0 ≤ alpha) (hb0 : 0 ≤ beta) + (x : M.Point (BandTrees.band narrow G.lower) (G.root C)) + (hx : x ∈ G.admittedSeeds positive C) + (hl : G.lower+9*a₂/100 ≤ x.height) (hu : x.height ≤ G.lower+a₂-9*a₂/100) : + G.old positive C x+R/25 < (G.step positive C hC noise hnoise alpha beta ha hb).replacement x := by + let U := G.step positive C hC noise hnoise alpha beta ha hb + apply SecondaryCell.replacement_seed U.tree U.seeds U.old U.supportValue U.data.isOrdinary + U.zeta_eq (show 0 < R by norm_num [R]) U.radius_small ha0 hb0 U.delta_eq U.noise_bounds hx + (U.seed_near x hx) _ hl hu + intro ho + exact (G.support_seed_near positive C ho x (Finset.mem_filter.mp hx).1).trans (show 10*g ≤ (10/1000000:ℝ)*R by norm_num [g,R]) + +lemma full_step_gain (positive : Bool) (C : G.Component) + (hC : (G.admittedSeeds positive C).Nonempty) + (noise : Point.RadialTree.Noise (n := k+1)) (hnoise : (G.tree C).NoiseBounds noise) + (alpha beta : ℝ) (ha : alpha ≤ EB) (hb : beta ≤ EB) (ha0 : 0 ≤ alpha) (hb0 : 0 ≤ beta) + (x : M.Point (BandTrees.band narrow G.lower) (G.root C)) + (hx : x ∈ G.admittedSeeds positive C) + (hl : G.lower+9*a₂/100 ≤ x.height) (hu : x.height ≤ G.lower+a₂-9*a₂/100) : + G.old positive C x+R/25 < (G.step positive C hC noise hnoise alpha beta ha hb).fullReplacement + x.column ⟨x.height,G.sub_old (G.narrow_sub x.inBand)⟩ := by + let U := G.step positive C hC noise hnoise alpha beta ha hb + change G.old positive C x+R/25 < U.fullReplacement x.column + ⟨x.height,G.sub_old (G.narrow_sub x.inBand)⟩ + rw [U.fullReplacement_inside x.column ⟨x.height,G.sub_old (G.narrow_sub x.inBand)⟩ + (show x.height ∈ SecondaryCell.domain U.seeds U.radius x.column from G.seed_domain positive C x hx)] + change G.old positive C x+R/25 < U.replacement + (SecondaryCell.point (G.admittedSeeds positive C) R x.column x.height (G.seed_domain positive C x hx)) + have he := G.seed_cellPoint positive C x hx + rw [he] + exact G.step_gain positive C hC noise hnoise alpha beta ha hb ha0 hb0 x hx hl hu + +end PlanarL1.Columns.Model.SecondaryGeometry.Group + +end + + + +section + +namespace PlanarL1.Columns.Model.SecondaryGeometry.Group +open Parameters MeasureTheory +attribute [local instance] Classical.propDecidable +variable {k : ℕ} {M : Model (k+1)} {Ω : Type*} [MeasurableSpace Ω] {μ : Measure Ω} +variable {A : Ambient M} {S : BState M kappaB (⟨lambda,by norm_num [lambda,R]⟩) Ω μ} +variable (G : SecondaryGeometry.Group A S) + +lemma domain_near (positive : Bool) (C : G.Component) + (hC : (G.admittedSeeds positive C).Nonempty) (i : Fin (k+1)) (H : ℝ) + (hx : H ∈ SecondaryCell.domain (G.admittedSeeds positive C) R i) : + H ∈ BandTrees.band narrow G.lower ∧ ∃ v ∈ G.seeds, + ∃ p : M.Path (BandTrees.band narrow G.lower) i v.column, p.length H v.height ≤ R := by + obtain ⟨x,hi,hH,hd⟩ := (SecondaryCell.mem_domain _ _).mp hx + obtain ⟨w,hw,he⟩ := SecondaryCell.seedDistance_attained _ hC x + obtain ⟨v,hv,hc,hvH⟩ := (G.allSeeds_description C w).mp (Finset.mem_filter.mp hw).1 + obtain ⟨p,_,hp⟩ := x.exists_shortest isClosed_Icc w + refine ⟨hH ▸ x.inBand,v,hv,?_⟩ + have hh := hp.le.trans (he.symm.le.trans hd) + refine ⟨p.cast hi hc.symm,?_⟩ + calc + _ = p.length H v.height := PlanarL1.Columns.Model.Path.length_cast p hi hc.symm H v.height + _ ≤ R := by simpa only [←hH,hvH] using hh + +end PlanarL1.Columns.Model.SecondaryGeometry.Group + +end + + + +section + +namespace PlanarL1.Columns.Model.RetainedSelection +open Parameters MeasureTheory +attribute [local instance] Classical.propDecidable +variable {k : ℕ} {M : Model (k+1)} {V Ω Ξ : Type*} +variable [Fintype V] [MeasurableSpace Ω] [MeasurableSpace Ξ] +variable {μ : Measure Ω} {ν : Measure Ξ} +variable (A : Ambient M) (SA : OrdinaryState M kappaA Ω μ) +variable (SB : BState M kappaB SecondaryGeometry.Group.lam Ξ ν) +variable (v : V → M.Point Set.univ A.root) +variable {L U : ℝ} (hv : ∀ x, (v x).height ∈ Set.Icc L U) +variable {q p : ℝ} {phaseD phaseG : MainFamily.BandComponent (M := M) q L U → ℝ} +variable (b : Block (M := M) q p L U) +variable (c : M.Point (BandTrees.band broad b.lower) (BandTrees.root M broad b.lower b.1.2)) + +lemma domain_touch (i : GroupIndex A SA SB v hv (p := p) (phaseD := phaseD) (phaseG := phaseG)) + (positive : Bool) (C : (group A SA SB v hv i).Component) + (hC : ((group A SA SB v hv i).admittedSeeds positive C).Nonempty) + (hd : c.height ∈ SecondaryCell.domain ((group A SA SB v hv i).admittedSeeds positive C) R c.column) : + Touch A SA SB v hv b c i := by + obtain ⟨hH,z,hz,path,hpath⟩ := (group A SA SB v hv i).domain_near positive C hC c.column c.height hd + obtain ⟨w,hw,he⟩ := (SurvivingGroups.seed_mem + (localSeeds A SA SB v hv (phaseD := phaseD) (phaseG := phaseG) i.1) i.2).mp hz + subst z + refine ⟨hH,w,hw,path,hpath.trans ?_⟩ + norm_num [R] + +end PlanarL1.Columns.Model.RetainedSelection + +end + + + +section + +namespace PlanarL1.Columns.Model.SecondaryGeometry.Group +open Parameters MeasureTheory +attribute [local instance] Classical.propDecidable +variable {k : ℕ} {M : Model (k+1)} {Ω : Type*} [MeasurableSpace Ω] {μ : Measure Ω} +variable {A : Ambient M} {S : BState M kappaB lam Ω μ} +variable (G : SecondaryGeometry.Group A S) + +/-- A whole secondary group, not only the selected narrow component, stays +away from the other endpoint of a distance-scale pair. -/ +lemma far_not_domain (x : M.Point G.broad G.broad_root) (hx : x ∈ G.seeds) + (j : Fin (k+1)) (T : ℝ) (hfar : 1 ≤ dist (A.point x.column x.height) (A.point j T)) + (positive : Bool) (C : G.Component) (hC : (G.admittedSeeds positive C).Nonempty) : + T ∉ SecondaryCell.domain (G.admittedSeeds positive C) R j := by + intro hy + obtain ⟨y,hj,hT,hd⟩ := (SecondaryCell.mem_domain _ _).mp hy + obtain ⟨w,hw,he⟩ := SecondaryCell.seedDistance_attained _ hC y + obtain ⟨v,hv,hc,hH⟩ := (G.allSeeds_description C w).mp (Finset.mem_filter.mp hw).1 + have hvw : A.point v.column v.height=A.point w.column w.height := by rw [hc,hH] + have h₁ := (MainFamily.ambient_dist_le A x v).trans (G.diameter x hx v hv) + have h₂ := MainFamily.ambient_dist_le A w y + rw [dist_comm w y,← he] at h₂ + have htri := dist_triangle (A.point x.column x.height) (A.point v.column v.height) (A.point j T) + rw [hvw] at h₁ + rw [hvw,←hj,←hT] at htri + have hsmall : 10*g+R < (1:ℝ) := by norm_num [g,R] + rw [←hj,←hT] at hfar + linarith + +end PlanarL1.Columns.Model.SecondaryGeometry.Group + +end + + + +section + +namespace PlanarL1.Interpolation +lemma maxSelection_ge_member {X : Type*} (old : X → NamedValue) + (Fs : List (X → NamedValue)) (F : X → NamedValue) (hF : F ∈ Fs) (x : X) : + (F x).value ≤ (maxSelection old Fs x).value := by + induction Fs with + | nil => simp at hF + | cons G gs ih => + rw [maxSelection,maxNamed_value] + rcases List.mem_cons.mp hF with rfl | h + · exact le_max_left _ _ + · exact (ih h).trans (le_max_right _ _) +lemma familySelection_ge {X : Type*} {n : ℕ} (old : X → ℝ) + (F : Fin n → X → NamedValue) (q : Fin n) (x : X) : + (F q x).value ≤ (familySelection old F x).value := + maxSelection_ge_member (fun x => ⟨0,old x⟩) + (List.ofFn (fun q => fun x => ⟨familyName q (F q x).name,(F q x).value⟩)) + (fun x => ⟨familyName q (F q x).name,(F q x).value⟩) + (List.mem_ofFn.mpr ⟨q,rfl⟩) x +end PlanarL1.Interpolation + +namespace PlanarL1.Columns.Model.BState.SecondaryBatch +open MeasureTheory +open scoped NNReal +open PlanarL1.Interpolation +attribute [local instance] Classical.propDecidable +variable {k : ℕ} {M : Model (k+1)} {κ : ℝ} {lam : ℝ≥0} +variable {Ω : Type*} [MeasurableSpace Ω] {μ : Measure Ω} {S : BState M κ lam Ω μ} +variable (B : SecondaryBatch S) + +lemma selected_ge (q : Fin B.count) (i : Fin (k+1)) (H : B.data.band) : + κ*(B.step q).fullReplacement i (B.groupHeight q H) ≤ (B.selected i H).value := by + rw [←B.groupNamed_value] + exact familySelection_ge (fun H => κ*B.comparison.value i H) (fun q => B.groupNamed q i) q H + +lemma indicator_inside (w : Ω × Bool) (i : Fin (k+1)) (H : ℝ) (h : H ∈ B.domain i) : + (B.patch.apply.activity w).indicator i H= + Threshold.chartValue H (B.converted i H) ((S.labels B.index).lift.value w) := by + simp only [Activity.indicator,B.patch.inside h w] + rfl + +lemma indicator_outside (w : Ω × Bool) (j : Fin (k+1)) (T : ℝ) + (hT : T ∈ B.data.band) (hy : T ∉ B.domain j) (hn : S.name j T=B.index) : + (B.patch.apply.activity w).indicator j T= + Threshold.chartValue T (κ*(B.data.offset+B.data.orientation B.positive* + B.comparison.value j ⟨T,hT⟩)) ((S.labels B.index).lift.value w) := by + have hr := S.represents_named w.1 j T B.index hn hT + have he := B.data.comparison_convert lam B.lambda_bound B.positive j ⟨T,hT⟩ + change (S.sets.activity w.1).active j T ↔ + Threshold.active (S.labels B.index) T (κ*B.data.value lam j ⟨T,hT⟩) w.1 at hr + rw [he] at hr + have hp := B.patch.unchanged hy w + simp only [Activity.indicator,Threshold.chartValue,Threshold.half,Threshold.active] at * + exact if_congr (hp.trans hr) rfl rfl + +lemma pair_separation_external (i j : Fin (k+1)) (H T : ℝ) + (hx : H ∈ B.domain i) (hT : T ∈ B.data.band) (hy : T ∉ B.domain j) + (hn : S.name j T=B.index) : + B.patch.apply.separation i H j T=max |H-T| + |(B.selected i ⟨H,B.domain_band hx⟩).value-κ*B.comparison.value j ⟨T,hT⟩| := by + unfold SetSystem.separation + simp_rw [B.indicator_inside _ i H hx,B.indicator_outside _ j T hT hy hn] + rw [(S.labels B.index).lift.distance,B.converted_on i H (B.domain_band hx)] + congr 1 + rw [show κ*B.data.offset+B.data.orientation B.positive*(B.selected i ⟨H,B.domain_band hx⟩).value- + κ*(B.data.offset+B.data.orientation B.positive*B.comparison.value j ⟨T,hT⟩)= + B.data.orientation B.positive*((B.selected i ⟨H,B.domain_band hx⟩).value- + κ*B.comparison.value j ⟨T,hT⟩) by ring, + abs_mul,B.data.orientation_unit,one_mul] + +/-- Overlapping proposals at the raised endpoint can only help. It is enough +for the other endpoint to stay outside all acting domains of its identifier. -/ +lemma gain_external (q : Fin B.count) (i j : Fin (k+1)) (H T : ℝ) + (hx : H ∈ SecondaryCell.domain (B.step q).seeds (B.step q).radius i) + (hT : T ∈ B.data.band) (hy : T ∉ B.domain j) (hn : S.name j T=B.index) + {r : ℝ} (hr : 0 < r) (hk : 0 < κ) + (hclose : |B.comparison.value i ⟨H,B.domain_band (B.mem_domain.mpr ⟨q,hx⟩)⟩- + B.comparison.value j ⟨T,hT⟩| ≤ r/10000) + (hgain : (B.step q).comparison.value i + (B.groupHeight q ⟨H,B.domain_band (B.mem_domain.mpr ⟨q,hx⟩)⟩)+r/25 < + (B.step q).fullReplacement i + (B.groupHeight q ⟨H,B.domain_band (B.mem_domain.mpr ⟨q,hx⟩)⟩)) : + κ*r/50 < B.patch.apply.separation i H j T := by + rw [B.pair_separation_external i j H T (B.mem_domain.mpr ⟨q,hx⟩) hT hy hn] + apply lt_of_lt_of_le _ (le_max_right _ _) + have hs := B.selected_ge q i ⟨H,B.domain_band (B.mem_domain.mpr ⟨q,hx⟩)⟩ + rw [B.step_comparison] at hgain + have hg := mul_lt_mul_of_pos_left hgain hk + have hc := mul_le_mul_of_nonneg_left (abs_le.mp hclose).1 hk.le + have ha := le_abs_self ((B.selected i ⟨H,B.domain_band (B.mem_domain.mpr ⟨q,hx⟩)⟩).value- + κ*B.comparison.value j ⟨T,hT⟩) + nlinarith [mul_pos hk hr] +end PlanarL1.Columns.Model.BState.SecondaryBatch + +end + + + +section + +namespace PlanarL1.Columns.Model.BState.SecondaryLayer +open MeasureTheory +open scoped NNReal +attribute [local instance] Classical.propDecidable +variable {k : ℕ} {M : Model (k+1)} {κ : ℝ} {lam : ℝ≥0} +variable {Ω : Type*} [MeasurableSpace Ω] {μ : Measure Ω} {S : BState M κ lam Ω μ} +variable (L : SecondaryLayer S) + +lemma inside (a : Fin (S.count+1)) (w : Ω × Bool) (i : Fin (k+1)) (H : ℝ) + (hi : H ∈ (L.batch a).domain i) : + (L.sets.activity w).active i H ↔ ((L.batch a).patch.apply.activity w).active i H := + SetPatch.batch_inside _ L.overlap (List.mem_ofFn.mpr ⟨a,rfl⟩) w i H hi + +lemma outside (a : Fin (S.count+1)) (w : Ω × Bool) (i : Fin (k+1)) (H : ℝ) + (hi : H ∉ (L.batch a).domain i) (hn : S.name i H=a) : + (L.sets.activity w).active i H ↔ ((L.batch a).patch.apply.activity w).active i H := by + apply Iff.trans _ ((L.batch a).patch.unchanged hi w).symm + apply SetPatch.batch_old _ L.overlap w i H + intro P hP + obtain ⟨q,rfl⟩ := List.mem_ofFn.mp hP + apply (L.batch q).patch.unchanged _ w + intro hq + have he := (L.batch q).domain_name hq + rw [L.same_index,hn] at he + exact hi (he ▸ hq) + +lemma pair_external (a : Fin (S.count+1)) (i j : Fin (k+1)) (H T : ℝ) + (hx : H ∈ (L.batch a).domain i) (hy : T ∉ (L.batch a).domain j) + (hn : S.name j T=a) : + L.sets.separation i H j T=(L.batch a).patch.apply.separation i H j T := by + unfold SetSystem.separation + congr 1 + funext w + simp only [Activity.indicator,L.inside a w i H hx,L.outside a w j T hy hn] + +end PlanarL1.Columns.Model.BState.SecondaryLayer + +end + + + +section + +namespace PlanarL1.Columns.Model.SecondaryGeometry +open Parameters MeasureTheory +open scoped NNReal +attribute [local instance] Classical.propDecidable +variable {k : ℕ} {M : Model (k+1)} {Ω : Type*} [MeasurableSpace Ω] {μ : Measure Ω} +variable {A : Ambient M} {S : BState M kappaB Group.lam Ω μ} +variable {I : Type*} [Fintype I] (G : I → Group A S) +variable {m : ℕ} (hm : 0 < m) (omega : Sample G m) + +omit [Fintype I] in +lemma actingStep_gain (a : Fin (S.count+1)) (q : Acting G omega a) + (x : M.Point (BandTrees.band narrow (G q.val.1).lower) ((G q.val.1).root q.val.2)) + (hx : x ∈ (G q.val.1).admittedSeeds (omega.1 a) q.val.2) + (hl : (G q.val.1).lower+9*a₂/100 ≤ x.height) + (hu : x.height ≤ (G q.val.1).lower+a₂-9*a₂/100) : + (actingStep G hm omega a q).comparison.value x.column + ⟨x.height,(G q.val.1).sub_old ((G q.val.1).narrow_sub x.inBand)⟩+R/25 < + (actingStep G hm omega a q).fullReplacement x.column + ⟨x.height,(G q.val.1).sub_old ((G q.val.1).narrow_sub x.inBand)⟩ := by + exact (G q.val.1).full_step_gain (omega.1 a) q.val.2 q.property.2.2 _ _ _ _ _ _ + (mul_nonneg (div_nonneg interpolationB.1.le (Nat.cast_nonneg _)) (Nat.cast_nonneg _)) + (mul_nonneg (div_nonneg interpolationB.1.le (Nat.cast_nonneg _)) (Nat.cast_nonneg _)) x hx hl hu + +lemma gain_external (a : Fin (S.count+1)) (q : Acting G omega a) + (x : M.Point (BandTrees.band narrow (G q.val.1).lower) ((G q.val.1).root q.val.2)) + (hx : x ∈ (G q.val.1).admittedSeeds (omega.1 a) q.val.2) + (hl : (G q.val.1).lower+9*a₂/100 ≤ x.height) + (hu : x.height ≤ (G q.val.1).lower+a₂-9*a₂/100) + (j : Fin (k+1)) (T : ℝ) (hT : T ∈ (S.chart a).band) + (hy : T ∉ (batch G hm omega a).domain j) (hn : S.name j T=a) + (hclose : ∀ hH : x.height ∈ (S.chart a).band, + |((S.chart a).comparison Group.lam Group.lam_bound (omega.1 a)).value x.column ⟨x.height,hH⟩- + ((S.chart a).comparison Group.lam Group.lam_bound (omega.1 a)).value j ⟨T,hT⟩| ≤ R/10000) : + kappaB*R/50 < (layer G hm omega).sets.separation x.column x.height j T := by + let e := @Fintype.equivFin (Acting G omega a) (instFintypeActing G omega a) + have hd : x.height ∈ SecondaryCell.domain ((batch G hm omega a).step (e q)).seeds + ((batch G hm omega a).step (e q)).radius x.column := by + change x.height ∈ SecondaryCell.domain + (G (e.symm (e q)).val.1 |>.admittedSeeds (omega.1 a) (e.symm (e q)).val.2) R x.column + rw [e.symm_apply_apply] + exact (G q.val.1).seed_domain (omega.1 a) q.val.2 x hx + have hdom := (batch G hm omega a).mem_domain.mpr ⟨e q,hd⟩ + rw [(layer G hm omega).pair_external a x.column j x.height T hdom hy hn] + apply (batch G hm omega a).gain_external (e q) x.column j x.height T hd hT hy hn + (by norm_num [R]) (by norm_num [kappaB,a₂]) (hclose _) + have gain (q' : Acting G omega a) (he : q'=q) + (H : (actingStep G hm omega a q').data.band) (hH : H.val=x.height) : + (actingStep G hm omega a q').comparison.value x.column H+R/25 < + (actingStep G hm omega a q').fullReplacement x.column H := by + subst q' + obtain ⟨T,hT⟩ := H + dsimp only at hH + subst T + exact actingStep_gain G hm omega a q x hx hl hu + exact gain (e.symm (e q)) (e.symm_apply_apply q) _ rfl + +end PlanarL1.Columns.Model.SecondaryGeometry + +end + + + +section + +namespace PlanarL1.Columns.Model.RetainedSelection +open Parameters MeasureTheory SecondaryGeometry +attribute [local instance] Classical.propDecidable +variable {k : ℕ} {M : Model (k+1)} {V Ω Ξ : Type*} +variable [Fintype V] [MeasurableSpace Ω] [MeasurableSpace Ξ] +variable {μ : Measure Ω} {ν : Measure Ξ} +variable (A : Ambient M) (SA : OrdinaryState M kappaA Ω μ) +variable (SB : BState M kappaB Group.lam Ξ ν) +variable (v : V → M.Point Set.univ A.root) +variable {L U : ℝ} (hv : ∀ x, (v x).height ∈ Set.Icc L U) +variable {q p : ℝ} {phaseD phaseG : MainFamily.BandComponent (M := M) q L U → ℝ} +variable (b : Block (M := M) q p L U) +variable (c : M.Point (BandTrees.band broad b.lower) (BandTrees.root M broad b.lower b.1.2)) +variable (i : GroupIndex A SA SB v hv (p := p) (phaseD := phaseD) (phaseG := phaseG)) +variable (x : M.Point (group A SA SB v hv i).broad (group A SA SB v hv i).broad_root) +variable (hx : x ∈ (group A SA SB v hv i).seeds) +variable (hfar : 1≤dist (A.point x.column x.height) (A.point c.column c.height)) +variable {m : ℕ} (hm : 0 < m) +variable (omega : Sample (group A SA SB v hv (p := p) (phaseD := phaseD) (phaseG := phaseG)) m) + +include hx hfar in +lemma batch_not_domain (a : Fin (SB.count+1)) + (hs : ∀ j, Touch A SA SB v hv b c j → j≠i → omega.2.1 j=false) : + c.height ∉ (batch (group A SA SB v hv) hm omega a).domain c.column := by + intro h + obtain ⟨n,hn⟩ := (batch (group A SA SB v hv) hm omega a).mem_domain.mp h + let e := @Fintype.equivFin (Acting (group A SA SB v hv) omega a) + (instFintypeActing (group A SA SB v hv) omega a) + let z := e.symm n + change c.height ∈ SecondaryCell.domain + ((group A SA SB v hv (e.symm n).val.1).admittedSeeds (omega.1 a) (e.symm n).val.2) R c.column at hn + change c.height ∈ SecondaryCell.domain + ((group A SA SB v hv z.val.1).admittedSeeds (omega.1 a) z.val.2) R c.column at hn + by_cases hz : z.val.1=i + · have haway (j : GroupIndex A SA SB v hv (p := p) (phaseD := phaseD) (phaseG := phaseG)) + (hj : j=i) (C : (group A SA SB v hv j).Component) + (hC : ((group A SA SB v hv j).admittedSeeds (omega.1 a) C).Nonempty) : + c.height ∉ SecondaryCell.domain ((group A SA SB v hv j).admittedSeeds (omega.1 a) C) R c.column := by + subst j + exact (group A SA SB v hv i).far_not_domain x hx c.column c.height hfar (omega.1 a) C hC + exact haway z.val.1 hz z.val.2 z.property.2.2 hn + · have ht := domain_touch A SA SB v hv b c z.val.1 (omega.1 a) z.val.2 z.property.2.2 hn + have hf := hs z.val.1 ht hz + have hk := z.property.2.1 + change omega.2.1 z.val.1=true at hk + rw [hf] at hk + contradiction +end PlanarL1.Columns.Model.RetainedSelection + +end + + + +section + +namespace PlanarL1.FiniteRandom +attribute [local instance] Classical.propDecidable + +lemma prob_mono_instances {Ω : Type*} (F F' : Fintype Ω) {P Q : Ω → Prop} + (h : ∀ w, P w → Q w) : @prob Ω F P ≤ @prob Ω F' Q := by + cases Subsingleton.elim F' F + exact @prob_mono Ω F P Q h + +lemma prob_true {Ω : Type*} [Fintype Ω] [Nonempty Ω] : prob (fun _ : Ω => True)=1 := by + simp [prob,event] + +lemma prob_first {Ω Λ : Type*} [Fintype Ω] [Fintype Λ] [Nonempty Λ] + (P : Ω → Prop) : prob (fun z : Ω × Λ => P z.1)=prob P := by + rw [←prob_equiv (Equiv.prodComm Λ Ω)] + exact prob_second P + +lemma prob_rectangle {Ω Λ : Type*} [Fintype Ω] [Fintype Λ] + (P : Ω → Prop) (Q : Λ → Prop) : + prob (fun z : Ω × Λ => P z.1 ∧ Q z.2)=prob P*prob Q := by + rw [prob_prod] + have he (w : Ω) : prob (fun z : Λ => P w ∧ Q z)=(if P w then (1:ℝ) else 0)*prob Q := by + by_cases h : P w + · simp only [h,true_and,ite_true,one_mul] + · simp only [h,false_and,ite_false,zero_mul,prob_false] + simp_rw [he] + rw [←Finset.sum_mul,prob_eq_sum P] + ring + +lemma prob_coin {I : Type*} [Fintype I] (i : I) (b : Bool) : + prob (fun f : I → Bool => f i=b)=1/2 := by + simpa using prob_prescribed ({i} : Finset I) (fun _ => b) + +lemma prob_keep_outside {I : Type*} [Fintype I] (i : I) (T : Finset I) {N : ℕ} + (hT : T.card≤N) : + 1/(2:ℝ)^(N+1) ≤ prob (fun f : I → Bool => f i=true ∧ ∀ j ∈ T, j≠i → f j=false) := by + apply prob_at_least_prescription (insert i T) (fun j => if j=i then true else false) + · exact (Finset.card_insert_le _ _).trans (by omega) + · intro f hf + refine ⟨?_,?_⟩ + · simpa using hf i (Finset.mem_insert_self _ _) + · intro j hj hji + simpa [hji] using hf j (Finset.mem_insert_of_mem hj) +end PlanarL1.FiniteRandom + +namespace PlanarL1.Columns.Model.SecondaryGeometry +open Parameters MeasureTheory FiniteRandom +attribute [local instance] Classical.propDecidable +variable {k : ℕ} {M : Model (k+1)} {Ω : Type*} [MeasurableSpace Ω] {μ : Measure Ω} +variable {A : Ambient M} {S : BState M kappaB (⟨lambda,by norm_num [lambda,R]⟩) Ω μ} +variable {I : Type*} [Fintype I] (G : I → Group A S) (m : ℕ) + +lemma prob_orientation_coins (P : (Fin (S.count+1) → Bool) → Prop) (Q : (I → Bool) → Prop) : + prob (fun omega : Sample G m => P omega.1 ∧ Q omega.2.1)=prob P*prob Q := by + let e := (Equiv.prodAssoc (Fin (S.count+1) → Bool) (I → Bool) + (∀ i C, ComponentSample G i C m)).symm + rw [←prob_equiv e.symm] + calc + _ = prob (fun z : (Fin (S.count+1) → Bool) × (I → Bool) => P z.1 ∧ Q z.2) := + prob_first _ + _ = _ := prob_rectangle P Q + +lemma prob_orient_keep_suppress (a : Fin (S.count+1)) (positive : Bool) (i : I) + (T : Finset I) {N : ℕ} (hT : T.card≤N) : + 1/(2:ℝ)^(N+2) ≤ prob (fun omega : Sample G m => + omega.1 a=positive ∧ omega.2.1 i=true ∧ ∀ j ∈ T, j≠i → omega.2.1 j=false) := by + rw [prob_orientation_coins G m (fun f => f a=positive) (fun f => f i=true ∧ ∀ j ∈ T, j≠i → f j=false)] + have hc : prob (fun f : Fin (S.count+1) → Bool => f a=positive)=(1/2:ℝ) := by + convert prob_coin a positive using 1 + exact congrArg (fun F : Fintype (Fin (S.count+1) → Bool) => + @prob _ F (fun f => f a=positive)) (Subsingleton.elim _ _) + have h := prob_keep_outside i T hT + calc + _ = (1/2:ℝ)*(1/2^(N+1)) := by rw [show N+2=(N+1)+1 by omega,pow_succ]; ring + _ ≤ (1/2:ℝ)*prob (fun f : I → Bool => f i=true ∧ ∀ j ∈ T, j≠i → f j=false) := + mul_le_mul_of_nonneg_left h (by norm_num) + _ = _ := congrArg (fun t => t*prob (fun f : I → Bool => f i=true ∧ ∀ j ∈ T, j≠i → f j=false)) hc.symm +end PlanarL1.Columns.Model.SecondaryGeometry + +end + +end OAI diff --git a/lean/OAI/Combinatorics/PlanarL1/SecondaryStep.lean b/lean/OAI/Combinatorics/PlanarL1/SecondaryStep.lean new file mode 100644 index 0000000000000000000000000000000000000000..9b06289025f8dca1e541d7e6a182a452a061234b --- /dev/null +++ b/lean/OAI/Combinatorics/PlanarL1/SecondaryStep.lean @@ -0,0 +1,733 @@ +import OAI.Combinatorics.PlanarL1.SecondaryCells +import OAI.Combinatorics.PlanarL1.Ambient + +namespace OAI + +section + +namespace PlanarL1.Columns.Model +open MeasureTheory +open scoped NNReal +attribute [local instance] Classical.propDecidable +variable {k : ℕ} {M : Model (k+1)} + +namespace BData +noncomputable def isOrdinary : BData M → Bool + | .ordinary _ => true + | .ordered _ => false + +noncomputable def comparison (D : BData M) (lam : ℝ≥0) (hlam : lam ≤ (1:ℝ≥0)/100) + (positive : Bool) : M.Field D.band 5 := + match D with + | .ordinary C => C.comparison.weaken (by norm_num) + | .ordered C => if positive then C.field lam hlam else (C.field lam hlam).negate + +noncomputable def offset : BData M → ℝ + | .ordinary C => C.constant + | .ordered _ => 0 + +noncomputable def orientation (positive : Bool) : BData M → ℝ + | .ordinary C => C.orientation + | .ordered _ => if positive then 1 else -1 + +lemma orientation_unit (positive : Bool) (D : BData M) : |D.orientation positive|=1 := by + cases D with + | ordinary C => exact C.unit_orientation + | ordered C => cases positive <;> norm_num [orientation] + +lemma comparison_convert (D : BData M) (lam : ℝ≥0) (hlam : lam ≤ (1:ℝ≥0)/100) + (positive : Bool) (i : Fin (k+1)) (H : D.band) : + D.value lam i H = D.offset+D.orientation positive*(D.comparison lam hlam positive).value i H := by + cases D with + | ordinary C => rfl + | ordered C => + cases positive + · change C.value lam i H = 0+(-1)*(-(C.field lam hlam).value i H) + erw [OrderedData.field_value]; ring + · change C.value lam i H = 0+1*(C.field lam hlam).value i H + erw [OrderedData.field_value]; ring +end BData + +namespace OrdinaryData +/-- The affine conversion constants, without manufacturing a point source. -/ +noncomputable def conversion (M : Model (k+1)) (c η : ℝ) (hη : |η|=1) : OrdinaryData M where + band := Set.univ + closed := isClosed_univ + convex := Set.ordConnected_univ + origin := none + constant := c + orientation := η + unit_orientation := hη +end OrdinaryData + +namespace Point.RadialTree +variable {J : Set ℝ} {root : Fin (k+1)} (R : RadialTree (M := M) (J := J) (root := root)) +namespace AtomSource +variable {R} {a : ℕ} +/-- Exact shallow-secondary ordinary chart: c+η(pc+R/20−Q_F). -/ +noncomputable def secondaryChart (A : R.AtomSource a) (c η : ℝ) (hη : |η|=1) + (p : M.Point J root → ℝ) (α : Noise (n := k+1)) (pc radius : ℝ) : OrdinaryData M := + (OrdinaryData.conversion M c η hη).atom J R.closed_band R.interval_band A.center + (pc+radius/20-A.intercept p α) (-A.sign) (by rw [abs_neg,A.sign_unit]) + +lemma secondaryChart_value (A : R.AtomSource a) (c η : ℝ) (hη : |η|=1) + (p : M.Point J root → ℝ) (α : Noise (n := k+1)) (pc radius : ℝ) (x : M.Point J root) : + (A.secondaryChart c η hη p α pc radius).value x.column ⟨x.height,x.inBand⟩ = + c+η*(pc+radius/20-(A.eval p α x).value) := by + change ((OrdinaryData.conversion M c η hη).atom J R.closed_band R.interval_band A.center + (pc+radius/20-A.intercept p α) (-A.sign) _).value x.column ⟨x.height,x.inBand⟩ = _ + rw [OrdinaryData.atom_value,A.eval_formula] + dsimp only [OrdinaryData.conversion] + ring +end AtomSource + +noncomputable def secondaryChart (c η : ℝ) (hη : |η|=1) + (p : M.Point J root → ℝ) (α : Noise (n := k+1)) (pc radius : ℝ) (a : ℕ) : OrdinaryData M := + if h : Nonempty (R.AtomSource a) then h.some.secondaryChart c η hη p α pc radius + else OrdinaryData.initial M + +lemma secondaryChart_value (c η : ℝ) (hη : |η|=1) + (p : M.Point J root → ℝ) (α : Noise (n := k+1)) (pc radius : ℝ) (x : M.Point J root) : + ∃ h : x.height ∈ (R.secondaryChart c η hη p α pc radius (R.pasted p α x).name).band, + (R.secondaryChart c η hη p α pc radius (R.pasted p α x).name).value x.column ⟨x.height,h⟩ = + c+η*(pc+radius/20-(R.pasted p α x).value) := by + have h := R.pasted_has_source p α x + let Q : OrdinaryData M → Prop := fun T => ∃ hi : x.height ∈ T.band, + T.value x.column ⟨x.height,hi⟩ = c+η*(pc+radius/20-(R.pasted p α x).value) + change Q (R.secondaryChart c η hη p α pc radius (R.pasted p α x).name) + rw [show R.secondaryChart c η hη p α pc radius (R.pasted p α x).name = + h.some.secondaryChart c η hη p α pc radius from dite_eq_left h] + exact ⟨x.inBand,(h.some.secondaryChart_value c η hη p α pc radius x).trans + (by rw [R.source_eval_pasted])⟩ + +lemma secondaryChart_contains (c η : ℝ) (hη : |η|=1) + (p : M.Point J root → ℝ) (α : Noise (n := k+1)) (pc radius : ℝ) (x : M.Point J root) : + (R.secondaryChart c η hη p α pc radius (R.pasted p α x).name).Contains x.column x.height := by + have h := R.pasted_has_source p α x + rw [show R.secondaryChart c η hη p α pc radius (R.pasted p α x).name = + h.some.secondaryChart c η hη p α pc radius from dite_eq_left h] + exact OrdinaryData.atom_contains _ _ _ _ _ x _ _ _ +end Point.RadialTree + +namespace OrderedData +/-- The source ordered-support branch, including the old affine chart +conversion. The auxiliary field is zero and the circular order reverses exactly +when η is negative. -/ +noncomputable def secondaryInstall {I : Set ℝ} (hI : IsClosed I) (hc : I.OrdConnected) + (L : M.Field I 1) (a b : Fin (k+1)) (ho : L.OrderedFrom a b) + (c η pc radius α : ℝ) (_hη : |η|=1) : OrderedData M := + install hI hc L a b ho (η*c+pc+radius/20-4*pc+α) (decide (η=1)) + +lemma secondaryInstall_value {I : Set ℝ} (hI : IsClosed I) (hc : I.OrdConnected) + (L : M.Field I 1) (a b : Fin (k+1)) (ho : L.OrderedFrom a b) + (c η pc radius α : ℝ) (hη : |η|=1) (lam : ℝ≥0) (i : Fin (k+1)) (H : I) : + (secondaryInstall hI hc L a b ho c η pc radius α hη).value lam i H = + c+η*(pc+radius/20+4*(L.value i H-pc)+α) := by + change (install hI hc L a b ho (η*c+pc+radius/20-4*pc+α) (decide (η=1))).value lam i H = _ + rw [install_value] + rcases (abs_eq (by norm_num : (0:ℝ) ≤ 1)).mp hη with he | he + · simp only [he,decide_true,ite_true]; ring + · norm_num [he]; ring +end OrderedData +end PlanarL1.Columns.Model + +namespace PlanarL1.Columns.Model.SecondaryCell +open PlanarL1.Interpolation +attribute [local instance] Classical.propDecidable +variable {n : ℕ} {M : Model n} {J : Set ℝ} {root : Fin n} +variable (R : Point.RadialTree (M := M) (J := J) (root := root)) +variable (S : Finset (M.Point J root)) +variable (old L : M.Point J root → ℝ) (ordinary : Bool) + +lemma namedReplacement_cases (pc radius αo αh lo : ℝ) + (α : Point.RadialTree.Noise (n := n)) (x : M.Point J root) : + namedReplacement R S old L ordinary pc radius αo αh lo α x=⟨0,old x⟩ ∨ + namedReplacement R S old L ordinary pc radius αo αh lo α x= + ⟨1,Clipping.heightShield lo R.a pc αh x.height⟩ ∨ + namedReplacement R S old L ordinary pc radius αo αh lo α x= + ⟨2,Clipping.orderedBranch pc radius αo L x⟩ ∨ + namedReplacement R S old L ordinary pc radius αo αh lo α x= + ⟨(R.pasted (input S) α x).name+3,shallow R S pc radius α x⟩ := + secondaryNamed_mem _ _ _ _ _ x + +lemma namedReplacement_bound (pc radius αo αh lo : ℝ) + (α : Point.RadialTree.Noise (n := n)) (x : M.Point J root) : + (namedReplacement R S old L ordinary pc radius αo αh lo α x).name < 3*n*R.depthCap+3 := by + rcases namedReplacement_cases R S old L ordinary pc radius αo αh lo α x with h | h | h | h + · rw [h]; simp only; omega + · rw [h]; simp only; omega + · rw [h]; simp only; omega + · rw [h] + exact Nat.add_lt_add_right (R.pasted_name_lt (input S) α x) 3 + +lemma namedReplacement_congr_zero (hOld : LipschitzWith 5 old) (hL : LipschitzWith 1 L) + (pc radius αo αh lo : ℝ) {α : Point.RadialTree.Noise (n := n)} (hα : R.NoiseBounds α) + (x y : M.Point J root) (hxy : dist x y=0) : + namedReplacement R S old L ordinary pc radius αo αh lo α x = + namedReplacement R S old L ordinary pc radius αo αh lo α y := by + have hp := R.pasted_congr_zero (input S) hα x y hxy + have ho : old x=old y := dist_le_zero.mp (by simpa only [hxy,mul_zero] using hOld.dist_le_mul x y) + have hl : L x=L y := dist_le_zero.mp (by simpa only [hxy,mul_zero] using hL.dist_le_mul x y) + have hh : x.height=y.height := by + have ht : |x.height-y.height| ≤ dist x y := x.height_change_le y + rw [hxy] at ht + exact sub_eq_zero.mp (abs_eq_zero.mp (le_antisymm ht (abs_nonneg _))) + simp only [namedReplacement,secondaryNamed,shallow,approx,hp,ho,hh,Clipping.orderedBranch,hl] + +noncomputable def choose (pc radius αo αh lo : ℝ) + (α : Point.RadialTree.Noise (n := n)) (i : Fin n) (H : ℝ) : + Option (Fin (3*n*R.depthCap+2)) := + if hd : H ∈ domain S radius i then + let t := namedReplacement R S old L ordinary pc radius αo αh lo α (point S radius i H hd) + if ht : t.name=0 then none else some ⟨t.name-1,by + have hb := namedReplacement_bound R S old L ordinary pc radius αo αh lo α (point S radius i H hd) + dsimp only [t] at ht ⊢ + omega⟩ + else none + +lemma choose_spec (pc radius αo αh lo : ℝ) (α : Point.RadialTree.Noise (n := n)) + (i : Fin n) (H : ℝ) (a : Fin (3*n*R.depthCap+2)) + (h : choose R S old L ordinary pc radius αo αh lo α i H=some a) : + ∃ hd : H ∈ domain S radius i, + (namedReplacement R S old L ordinary pc radius αo αh lo α (point S radius i H hd)).name=a.val+1 := by + by_cases hd : H ∈ domain S radius i + · simp only [choose,dite_eq_left hd] at h + split_ifs at h with ht + refine ⟨hd,?_⟩ + have he := congrArg Fin.val (Option.some.inj h) + dsimp only at he ht + omega + · simp only [choose,dite_eq_right hd] at h + cases h + +lemma choose_none (pc radius αo αh lo : ℝ) (α : Point.RadialTree.Noise (n := n)) + (i : Fin n) (H : ℝ) (hd : H ∈ domain S radius i) + (h : choose R S old L ordinary pc radius αo αh lo α i H=none) : + (namedReplacement R S old L ordinary pc radius αo αh lo α (point S radius i H hd)).name=0 := by + unfold choose at h + simp only [dite_eq_left hd] at h + split_ifs at h with ht + exact ht + +lemma choose_switch (hOld : LipschitzWith 5 old) (hL : LipschitzWith 1 L) + (pc radius αo αh lo : ℝ) {α : Point.RadialTree.Noise (n := n)} (hα : R.NoiseBounds α) + (i j : Fin n) (H : ℝ) (hs : H ∈ M.heights i j) : + choose R S old L ordinary pc radius αo αh lo α i H = + choose R S old L ordinary pc radius αo αh lo α j H := by + by_cases hi : H ∈ domain S radius i + · have hj := switch_mem S radius hs hi + have he := namedReplacement_congr_zero R S old L ordinary hOld hL pc radius αo αh lo hα + (point S radius i H hi) (point S radius j H hj) (point_dist_switch S hi hj hs) + simp only [choose,dite_eq_left hi,dite_eq_left hj] + simp only [he] + · have hj : H ∉ domain S radius j := fun hj => hi (switch_mem S radius (M.symm i j ▸ hs) hj) + simp only [choose,dite_eq_right hi,dite_eq_right hj] +end PlanarL1.Columns.Model.SecondaryCell + + +namespace PlanarL1.Columns.Model +open MeasureTheory +open scoped NNReal +attribute [local instance] Classical.propDecidable +variable {k : ℕ} {M : Model (k+1)} {κ : ℝ} {lam : ℝ≥0} + {Ω : Type*} [MeasurableSpace Ω] {μ : Measure Ω} + +namespace BState +lemma represents_named (S : BState M κ lam Ω μ) (ω : Ω) (i : Fin (k+1)) (H : ℝ) + (a : Fin (S.count+1)) (ha : S.name i H=a) (hi : H ∈ (S.chart a).band) : + (S.sets.activity ω).active i H ↔ Threshold.active (S.labels a) H + (κ*(S.chart a).value lam i ⟨H,hi⟩) ω := by + subst a + exact S.represents ω i H + +/-- One kept group's literal secondary clipping. Only the geometric admission, +seed and eligibility data enter; every new chart below is constructed from the +winning formula, not postulated. -/ +structure SecondaryStep (S : BState M κ lam Ω μ) (J : Set ℝ) (root : Fin (k+1)) where + index : Fin (S.count+1) + positive : Bool + lambda_bound : lam ≤ (1:ℝ≥0)/100 + tree : Point.RadialTree (M := M) (J := J) (root := root) + lo : ℝ + band_eq : J=Set.Icc lo (lo+tree.a) + sub_old : J ⊆ (S.chart index).band + seeds : Finset (M.Point J root) + seeds_nonempty : seeds.Nonempty + pc : ℝ + radius : ℝ + radius_nonneg : 0 ≤ radius + radius_small : radius ≤ (1:ℝ)/100 + support : M.Field (S.chart index).band 1 + lower : Fin (k+1) + upper : Fin (k+1) + support_ordered : support.OrderedFrom lower upper + support_le : (S.chart index).isOrdinary=true → ∀ x : M.Point J root, + support.value x.column ⟨x.height,sub_old x.inBand⟩ ≤ + ((S.chart index).comparison lam lambda_bound positive).value x.column ⟨x.height,sub_old x.inBand⟩ + admitted : (S.chart index).isOrdinary=false → ∀ w ∈ seeds, ∀ x : M.Point J root, + dist w x=radius → pc-(65/100:ℝ)*radius ≤ + ((S.chart index).comparison lam lambda_bound positive).value x.column ⟨x.height,sub_old x.inBand⟩ + seed_near : ∀ w ∈ seeds, + |((S.chart index).comparison lam lambda_bound positive).value w.column ⟨w.height,sub_old w.inBand⟩-pc| ≤ + (60/1000000:ℝ)*radius + zeta_eq : tree.ζ=(1:ℝ)/10 + delta_eq : tree.δ=(radius/1000)/8 + noise : Point.RadialTree.Noise (n := k+1) + noise_bounds : tree.NoiseBounds noise + ordered_offset : ℝ + shield_offset : ℝ + ordered_bound : ordered_offset ≤ radius/1000 + shield_bound : shield_offset ≤ radius/1000 + same_name : ∀ i H, H ∈ SecondaryCell.domain seeds radius i → S.name i H=index + kappa_nonneg : 0 ≤ κ + vertical_bound : κ*(SecondaryCell.replacementConstant tree : ℝ) ≤ 1 + shield_strict : κ*(3/(9*tree.a/100)) < 1 + +namespace SecondaryStep +variable {S : BState M κ lam Ω μ} {J : Set ℝ} {root : Fin (k+1)} +variable (U : SecondaryStep S J root) + +noncomputable def data : BData M := S.chart U.index +noncomputable def comparison : M.Field U.data.band 5 := U.data.comparison lam U.lambda_bound U.positive +noncomputable def old (x : M.Point J root) : ℝ := U.comparison.value x.column ⟨x.height,U.sub_old x.inBand⟩ +noncomputable def supportValue (x : M.Point J root) : ℝ := U.support.value x.column ⟨x.height,U.sub_old x.inBand⟩ + +lemma old_lipschitz : LipschitzWith 5 U.old := + (U.comparison.restrict U.sub_old).lipschitz U.tree.closed_band root +lemma support_lipschitz : LipschitzWith 1 U.supportValue := + (U.support.restrict U.sub_old).lipschitz U.tree.closed_band root +include U in +lemma compact_band : IsCompact J := by rw [U.band_eq]; exact isCompact_Icc + +lemma old_agreement (ω : Ω × Bool) (i : Fin (k+1)) (H : ℝ) + (hi : H ∈ SecondaryCell.domain U.seeds U.radius i) : + Threshold.active (S.labels U.index).lift H + (κ*(U.data.offset+U.data.orientation U.positive*U.old (SecondaryCell.point U.seeds U.radius i H hi))) ω ↔ + (S.lift.sets.activity ω).active i H := by + have he := U.data.comparison_convert lam U.lambda_bound U.positive i + ⟨H,U.sub_old (SecondaryCell.inBand_of_mem U.seeds U.radius hi)⟩ + have hr := S.represents_named ω.1 i H U.index (U.same_name i H hi) + (U.sub_old (SecondaryCell.inBand_of_mem U.seeds U.radius hi)) + dsimp only [data] at he + rw [he] at hr + change Threshold.active (S.labels U.index) H + (κ*(U.data.offset+U.data.orientation U.positive*U.old (SecondaryCell.point U.seeds U.radius i H hi))) ω.1 ↔ + (S.sets.activity ω.1).active i H + simpa only [old,comparison,data,SecondaryCell.point_column,SecondaryCell.point_height] using hr.symm + +noncomputable def patch : SetPatch S.lift.sets := + SecondaryCell.patch U.tree U.seeds U.old U.supportValue U.data.isOrdinary + S.lift.sets (S.labels U.index).lift U.compact_band U.lo U.band_eq + U.seeds_nonempty U.old_lipschitz U.support_lipschitz U.zeta_eq + U.pc U.radius U.ordered_offset U.shield_offset U.data.offset (U.data.orientation U.positive) κ + U.radius_nonneg U.radius_small U.ordered_bound U.shield_bound U.delta_eq U.noise_bounds + U.support_le U.admitted U.seed_near (U.data.orientation_unit U.positive) + U.kappa_nonneg U.vertical_bound U.old_agreement + +noncomputable def input : M.Point J root → ℝ := SecondaryCell.input U.seeds +noncomputable def replacement := SecondaryCell.replacement U.tree U.seeds U.old U.supportValue + U.data.isOrdinary U.pc U.radius U.ordered_offset U.shield_offset U.lo U.noise +noncomputable def named := SecondaryCell.namedReplacement U.tree U.seeds U.old U.supportValue + U.data.isOrdinary U.pc U.radius U.ordered_offset U.shield_offset U.lo U.noise +noncomputable def shield (H : ℝ) : ℝ := + κ*(U.data.offset+U.data.orientation U.positive*Clipping.heightShield U.lo U.tree.a U.pc U.shield_offset H) +noncomputable def shieldConstant : ℝ≥0 := + ⟨κ*(3/(9*U.tree.a/100)),mul_nonneg U.kappa_nonneg (by positivity [U.tree.width_pos])⟩ + +lemma shield_lipschitz : LipschitzWith U.shieldConstant U.shield := by + apply LipschitzWith.of_dist_le_mul + intro H T + have ht := (Clipping.heightShield_lipschitz U.lo U.pc U.shield_offset U.tree.width_pos).dist_le_mul H T + rw [Real.dist_eq] at ht + change |shield U H-shield U T| ≤ (κ*(3/(9*U.tree.a/100)))*dist H T + unfold shield + rw [show κ*(U.data.offset+U.data.orientation U.positive*Clipping.heightShield U.lo U.tree.a + U.pc U.shield_offset H)-κ*(U.data.offset+U.data.orientation U.positive*Clipping.heightShield U.lo U.tree.a + U.pc U.shield_offset T) = κ*U.data.orientation U.positive*(Clipping.heightShield U.lo U.tree.a + U.pc U.shield_offset H-Clipping.heightShield U.lo U.tree.a U.pc U.shield_offset T) by ring, + abs_mul,abs_mul,abs_of_nonneg U.kappa_nonneg,U.data.orientation_unit,mul_one] + exact (mul_le_mul_of_nonneg_left ht U.kappa_nonneg).trans_eq (mul_assoc _ _ _).symm + +noncomputable def orderedChart : OrderedData M := + OrderedData.secondaryInstall U.data.closed U.data.convex U.support U.lower U.upper U.support_ordered + U.data.offset (U.data.orientation U.positive) U.pc U.radius U.ordered_offset (U.data.orientation_unit U.positive) + +noncomputable def newData (a : Fin (3*(k+1)*U.tree.depthCap+2)) : BData M := + if a.val=0 then .ordinary (OrdinaryData.initial M) else + if a.val=1 then .ordered U.orderedChart else + .ordinary (U.tree.secondaryChart U.data.offset (U.data.orientation U.positive) + (U.data.orientation_unit U.positive) U.input U.noise U.pc U.radius (a.val-2)) + +noncomputable def newLabels [SFinite μ] (a : Fin (3*(k+1)*U.tree.depthCap+2)) : + Threshold.Variables (Ω × Bool) (μ.prod Threshold.fair) := + if a.val=0 then (S.labels U.index).rebase (K := U.shieldConstant) U.shield_strict U.shield_lipschitz + else (S.labels U.index).lift + +noncomputable def choose := SecondaryCell.choose U.tree U.seeds U.old U.supportValue + U.data.isOrdinary U.pc U.radius U.ordered_offset U.shield_offset U.lo U.noise + +lemma patch_inside (ω : Ω × Bool) (i : Fin (k+1)) (H : ℝ) + (hi : H ∈ SecondaryCell.domain U.seeds U.radius i) : + (U.patch.apply.activity ω).active i H ↔ Threshold.active (S.labels U.index).lift H + (κ*(U.data.offset+U.data.orientation U.positive*U.replacement (SecondaryCell.point U.seeds U.radius i H hi))) ω := by + apply (U.patch.inside hi ω).trans + change Threshold.active _ H (SecondaryCell.converted U.tree U.seeds U.old U.supportValue U.data.isOrdinary + U.pc U.radius U.ordered_offset U.shield_offset U.lo U.data.offset (U.data.orientation U.positive) κ U.noise i H) ω ↔ _ + rw [SecondaryCell.converted_on _ _ _ _ _ _ _ _ _ _ _ _ _ _ hi] + rfl + +lemma chosen_description [SFinite μ] (i : Fin (k+1)) (H : ℝ) + (a : Fin (3*(k+1)*U.tree.depthCap+2)) (hc : U.choose i H=some a) : + (H ∈ (U.newData a).band ∧ (U.newData a).Uses i) ∧ + ∀ (ω : Ω × Bool) (hi : H ∈ (U.newData a).band), + (U.patch.apply.activity ω).active i H ↔ + Threshold.active (U.newLabels a) H (κ*(U.newData a).value lam i ⟨H,hi⟩) ω := by + let Q (D : BData M) (Z : Threshold.Variables (Ω × Bool) (μ.prod Threshold.fair)) : Prop := + (H ∈ D.band ∧ D.Uses i) ∧ ∀ (ω : Ω × Bool) (hi : H ∈ D.band), + (U.patch.apply.activity ω).active i H ↔ Threshold.active Z H (κ*D.value lam i ⟨H,hi⟩) ω + change Q (U.newData a) (U.newLabels a) + obtain ⟨hd,hn⟩ := SecondaryCell.choose_spec U.tree U.seeds U.old U.supportValue U.data.isOrdinary + U.pc U.radius U.ordered_offset U.shield_offset U.lo U.noise i H a hc + let x := SecondaryCell.point U.seeds U.radius i H hd + have hcol : x.column=i := SecondaryCell.point_column _ _ hd + have hheight : x.height=H := SecondaryCell.point_height _ _ hd + change (SecondaryCell.namedReplacement U.tree U.seeds U.old U.supportValue U.data.isOrdinary + U.pc U.radius U.ordered_offset U.shield_offset U.lo U.noise x).name=a.val+1 at hn + rcases SecondaryCell.namedReplacement_cases U.tree U.seeds U.old U.supportValue U.data.isOrdinary + U.pc U.radius U.ordered_offset U.shield_offset U.lo U.noise x with ho | hh | hq | hp + · have hn' := congrArg PlanarL1.Interpolation.NamedValue.name ho + change _=0 at hn' + omega + · have hn' := congrArg PlanarL1.Interpolation.NamedValue.name hh + change _=1 at hn' + have ha0 : a.val=0 := by omega + simp only [newData,newLabels,ite_eq_left ha0] + refine ⟨OrdinaryData.initial_contains i H,?_⟩ + intro ω hi + have hv : U.replacement x=Clipping.heightShield U.lo U.tree.a U.pc U.shield_offset H := by + change SecondaryCell.replacement _ _ _ _ _ _ _ _ _ _ _ _ = _ + rw [← SecondaryCell.namedReplacement_value U.tree U.seeds U.old U.supportValue U.data.isOrdinary + U.pc U.radius U.ordered_offset U.shield_offset U.lo U.noise x,hh] + change Clipping.heightShield _ _ _ _ x.height = _ + rw [hheight] + have h0 := U.patch_inside ω i H hd + change _ ↔ Threshold.active _ H (κ*(U.data.offset+U.data.orientation U.positive*U.replacement x)) ω at h0 + rw [hv] at h0 + change _ ↔ Threshold.active _ H (κ*(OrdinaryData.initial M).value i ⟨H,hi⟩) ω + have hz : (OrdinaryData.initial M).value i ⟨H,hi⟩ = 0 := OrdinaryData.initial_value M i H + rw [hz,mul_zero] + exact h0.trans ((S.labels U.index).active_rebase (K := U.shieldConstant) U.shield_strict U.shield_lipschitz H ω) + · have hn' := congrArg PlanarL1.Interpolation.NamedValue.name hq + change _=2 at hn' + have ha0 : a.val≠0 := by omega + have ha1 : a.val=1 := by omega + simp only [newData,newLabels,ite_eq_right ha0,ite_eq_left ha1] + refine ⟨⟨U.sub_old (SecondaryCell.inBand_of_mem U.seeds U.radius hd),trivial⟩,?_⟩ + intro ω hi + have hv : U.replacement x=Clipping.orderedBranch U.pc U.radius U.ordered_offset U.supportValue x := by + change SecondaryCell.replacement _ _ _ _ _ _ _ _ _ _ _ _ = _ + rw [← SecondaryCell.namedReplacement_value U.tree U.seeds U.old U.supportValue U.data.isOrdinary + U.pc U.radius U.ordered_offset U.shield_offset U.lo U.noise x,hq] + have h0 := U.patch_inside ω i H hd + change _ ↔ Threshold.active _ H (κ*(U.data.offset+U.data.orientation U.positive*U.replacement x)) ω at h0 + rw [hv] at h0 + have he := OrderedData.secondaryInstall_value U.data.closed U.data.convex U.support U.lower U.upper + U.support_ordered U.data.offset (U.data.orientation U.positive) U.pc U.radius U.ordered_offset + (U.data.orientation_unit U.positive) lam i ⟨H,hi⟩ + change _ ↔ Threshold.active _ H (κ*U.orderedChart.value lam i ⟨H,hi⟩) ω + rw [show U.orderedChart.value lam i ⟨H,hi⟩ = _ from he] + have hs : U.supportValue x=U.support.value i ⟨H,hi⟩ := by + dsimp only [supportValue] + congr 1 + exact Subtype.ext hheight + simp only [Clipping.orderedBranch,hs] at h0 + exact h0 + · have hn' := congrArg PlanarL1.Interpolation.NamedValue.name hp + change _=(U.tree.pasted U.input U.noise x).name+3 at hn' + have ha0 : a.val≠0 := by omega + have ha1 : a.val≠1 := by omega + have ha2 : a.val-2=(U.tree.pasted U.input U.noise x).name := by omega + simp only [newData,newLabels,ite_eq_right ha0,ite_eq_right ha1,ha2] + refine ⟨?_,?_⟩ + · change (U.tree.secondaryChart _ _ _ _ _ _ _ _).Contains i H + simpa only [hcol,hheight] using U.tree.secondaryChart_contains U.data.offset + (U.data.orientation U.positive) (U.data.orientation_unit U.positive) U.input U.noise U.pc U.radius x + · intro ω hi + obtain ⟨hb,hvalue⟩ := U.tree.secondaryChart_value U.data.offset (U.data.orientation U.positive) + (U.data.orientation_unit U.positive) U.input U.noise U.pc U.radius x + have hv : U.replacement x=SecondaryCell.shallow U.tree U.seeds U.pc U.radius U.noise x := by + change SecondaryCell.replacement _ _ _ _ _ _ _ _ _ _ _ _ = _ + rw [← SecondaryCell.namedReplacement_value U.tree U.seeds U.old U.supportValue U.data.isOrdinary + U.pc U.radius U.ordered_offset U.shield_offset U.lo U.noise x,hp] + have h0 := U.patch_inside ω i H hd + change _ ↔ Threshold.active _ H (κ*(U.data.offset+U.data.orientation U.positive*U.replacement x)) ω at h0 + rw [hv] at h0 + simp only [hcol,hheight] at hvalue + exact h0.trans (Iff.of_eq (congrArg (fun p => Threshold.active (S.labels U.index).lift H (κ*p) ω) + hvalue.symm)) + +lemma unchosen (ω : Ω × Bool) (i : Fin (k+1)) (H : ℝ) (hc : U.choose i H=none) : + (U.patch.apply.activity ω).active i H ↔ (S.lift.sets.activity ω).active i H := by + by_cases hd : H ∈ SecondaryCell.domain U.seeds U.radius i + · have hn := SecondaryCell.choose_none U.tree U.seeds U.old U.supportValue U.data.isOrdinary + U.pc U.radius U.ordered_offset U.shield_offset U.lo U.noise i H hd hc + let x := SecondaryCell.point U.seeds U.radius i H hd + change (SecondaryCell.namedReplacement U.tree U.seeds U.old U.supportValue U.data.isOrdinary + U.pc U.radius U.ordered_offset U.shield_offset U.lo U.noise x).name=0 at hn + have hv : U.replacement x=U.old x := by + rcases SecondaryCell.namedReplacement_cases U.tree U.seeds U.old U.supportValue U.data.isOrdinary + U.pc U.radius U.ordered_offset U.shield_offset U.lo U.noise x with ho | hh | hq | hp + · change SecondaryCell.replacement _ _ _ _ _ _ _ _ _ _ _ _ = _ + rw [← SecondaryCell.namedReplacement_value U.tree U.seeds U.old U.supportValue U.data.isOrdinary + U.pc U.radius U.ordered_offset U.shield_offset U.lo U.noise x,ho] + · have he := congrArg PlanarL1.Interpolation.NamedValue.name hh + change _=1 at he + omega + · have he := congrArg PlanarL1.Interpolation.NamedValue.name hq + change _=2 at he + omega + · have he := congrArg PlanarL1.Interpolation.NamedValue.name hp + change _=_+3 at he + omega + have ht := U.patch_inside ω i H hd + change _ ↔ Threshold.active _ H (κ*(U.data.offset+U.data.orientation U.positive*U.replacement x)) ω at ht + rw [hv] at ht + exact ht.trans (U.old_agreement ω i H hd) + · exact U.patch.unchanged hd ω + +lemma choose_switch (i j : Fin (k+1)) (H : ℝ) (hs : H ∈ M.heights i j) : U.choose i H=U.choose j H := + SecondaryCell.choose_switch U.tree U.seeds U.old U.supportValue U.data.isOrdinary U.old_lipschitz + U.support_lipschitz U.pc U.radius U.ordered_offset U.shield_offset U.lo U.noise_bounds i j H hs + +/-- Actual one-group secondary installation with old identifiers retained and +fresh ordinary, ordered, and rebased height chart data supplied by their formulas. -/ +noncomputable def apply [SFinite μ] : BState M κ lam (Ω × Bool) (μ.prod Threshold.fair) := + S.lift.append U.patch.apply (3*(k+1)*U.tree.depthCap+2) U.newData U.newLabels U.choose + (fun i H a hc => (U.chosen_description i H a hc).1.1) + (fun i H a hc => (U.chosen_description i H a hc).1.2) + U.choose_switch U.unchosen + (fun ω i H a hc => (U.chosen_description i H a hc).2 ω _) + +lemma apply_sets [SFinite μ] : U.apply.sets=U.patch.apply := rfl + +end SecondaryStep +end BState +end PlanarL1.Columns.Model + +namespace PlanarL1.Columns.Model.BState.SecondaryStep +open MeasureTheory Set +open scoped NNReal +attribute [local instance] Classical.propDecidable +variable {k : ℕ} {M : Model (k+1)} {κ : ℝ} {lam : ℝ≥0} + {Ω : Type*} [MeasurableSpace Ω] {μ : Measure Ω} + {S : BState M κ lam Ω μ} {J : Set ℝ} {root : Fin (k+1)} +variable (U : SecondaryStep S J root) + +lemma point_old {i : Fin (k+1)} {H : ℝ} (hd : H ∈ SecondaryCell.domain U.seeds U.radius i) : + U.old (SecondaryCell.point U.seeds U.radius i H hd) = + U.comparison.value i ⟨H,U.sub_old (SecondaryCell.inBand_of_mem U.seeds U.radius hd)⟩ := by + simp only [old,SecondaryCell.point_column,SecondaryCell.point_height] + +lemma replacement_lipschitz : LipschitzWith (SecondaryCell.replacementConstant U.tree) U.replacement := + SecondaryCell.replacement_lipschitz U.tree U.seeds U.old U.supportValue U.data.isOrdinary + U.old_lipschitz U.support_lipschitz U.pc U.radius U.ordered_offset U.shield_offset U.lo U.noise_bounds + +lemma replacement_frontier {i : Fin (k+1)} {H : ℝ} + (hf : H ∈ frontier (SecondaryCell.domain U.seeds U.radius i)) + (hd : H ∈ SecondaryCell.domain U.seeds U.radius i) : + U.replacement (SecondaryCell.point U.seeds U.radius i H hd) = + U.old (SecondaryCell.point U.seeds U.radius i H hd) := by + obtain ⟨_,he⟩ := SecondaryCell.equal_radius_or_endpoint U.seeds U.radius U.compact_band U.lo U.tree.a + U.tree.width_pos U.band_eq hf + rcases he with he | he + · exact SecondaryCell.replacement_boundary U.tree U.seeds U.old U.supportValue U.data.isOrdinary + U.seeds_nonempty U.zeta_eq U.radius_nonneg U.ordered_bound U.delta_eq U.noise_bounds + U.support_le U.admitted U.shield_offset U.lo he + · exact SecondaryCell.replacement_endpoint U.tree U.seeds U.old U.supportValue U.data.isOrdinary + U.seeds_nonempty U.old_lipschitz U.radius_small U.shield_bound U.seed_near U.noise + (SecondaryCell.point_distance U.seeds U.radius hd) + (by rw [SecondaryCell.point_height U.seeds U.radius hd]; exact he) + +/-- The literal clamped proposal, extended by the old comparison on the rest +of the old band. This is the extension whose finite maximum is required for +simultaneous overlapping secondary groups. -/ +noncomputable def fullReplacement (i : Fin (k+1)) (H : U.data.band) : ℝ := + if hd : H.val ∈ SecondaryCell.domain U.seeds U.radius i then + U.replacement (SecondaryCell.point U.seeds U.radius i H.val hd) + else U.comparison.value i H + +lemma fullReplacement_inside (i : Fin (k+1)) (H : U.data.band) + (hd : H.val ∈ SecondaryCell.domain U.seeds U.radius i) : + U.fullReplacement i H=U.replacement (SecondaryCell.point U.seeds U.radius i H.val hd) := dite_eq_left hd + +lemma fullReplacement_outside (i : Fin (k+1)) (H : U.data.band) + (hd : H.val ∉ SecondaryCell.domain U.seeds U.radius i) : + U.fullReplacement i H=U.comparison.value i H := dite_eq_right hd + +lemma fullReplacement_ge (i : Fin (k+1)) (H : U.data.band) : + U.comparison.value i H ≤ U.fullReplacement i H := by + by_cases hd : H.val ∈ SecondaryCell.domain U.seeds U.radius i + · rw [U.fullReplacement_inside i H hd,← U.point_old hd] + exact le_max_left _ _ + · rw [U.fullReplacement_outside i H hd] + +lemma fullReplacement_vertical (i : Fin (k+1)) : + LipschitzWith (SecondaryCell.replacementConstant U.tree) (U.fullReplacement i) := by + let oldColumn (H : ℝ) := if h : H ∈ U.data.band then U.comparison.value i ⟨H,h⟩ else 0 + have ho : LipschitzOnWith 5 oldColumn U.data.band := by + apply LipschitzOnWith.of_dist_le_mul + intro H hH T hT + simpa only [oldColumn,dite_eq_left hH,dite_eq_left hT,Subtype.dist_eq] using + (U.comparison.vertical i).dist_le_mul ⟨H,hH⟩ ⟨T,hT⟩ + obtain ⟨g,hg,he⟩ := ho.extend_real + let proposal (H : ℝ) := if hd : H ∈ SecondaryCell.domain U.seeds U.radius i then + U.replacement (SecondaryCell.point U.seeds U.radius i H hd) else 0 + have hp : LipschitzOnWith (SecondaryCell.replacementConstant U.tree) proposal + (SecondaryCell.domain U.seeds U.radius i) := by + apply LipschitzOnWith.of_dist_le_mul + intro H hH T hT + have h := U.replacement_lipschitz.dist_le_mul + (SecondaryCell.point U.seeds U.radius i H hH) (SecondaryCell.point U.seeds U.radius i T hT) + simpa only [proposal,dite_eq_left hH,dite_eq_left hT,SecondaryCell.point_dist,Real.dist_eq] using h + have hb : EqOn proposal g (frontier (SecondaryCell.domain U.seeds U.radius i)) := by + intro H hH + have hd := (SecondaryCell.compact_domain U.seeds U.radius U.compact_band i).isClosed.frontier_subset hH + have hi := U.sub_old (SecondaryCell.inBand_of_mem U.seeds U.radius hd) + simp only [proposal,dite_eq_left hd,U.replacement_frontier hH hd,U.point_old hd] + have hv : oldColumn H = U.comparison.value i ⟨H,hi⟩ := dite_eq_left hi + exact hv.symm.trans (he hi) + have hl := PlanarL1.Gluing.lipschitz_piecewise + (SecondaryCell.compact_domain U.seeds U.radius U.compact_band i).isClosed + (hg.weaken (show (5:ℝ≥0) ≤ SecondaryCell.replacementConstant U.tree from le_max_left _ _)) hp hb + have hv (H : U.data.band) : U.fullReplacement i H= + (SecondaryCell.domain U.seeds U.radius i).piecewise proposal g H.val := by + by_cases hd : H.val ∈ SecondaryCell.domain U.seeds U.radius i + · simp only [fullReplacement,dite_eq_left hd,piecewise_eq_of_mem _ _ _ hd,proposal] + · rw [U.fullReplacement_outside i H hd,piecewise_eq_of_notMem _ _ _ hd] + simpa only [oldColumn,dite_eq_left H.property] using he H.property + apply LipschitzWith.of_dist_le_mul + intro H T + rw [hv H,hv T] + exact hl.dist_le_mul H.val T.val + +lemma fullReplacement_switch (i j : Fin (k+1)) (H : U.data.band) + (hs : H.val ∈ M.heights i j) : U.fullReplacement i H=U.fullReplacement j H := by + by_cases hi : H.val ∈ SecondaryCell.domain U.seeds U.radius i + · have hj := SecondaryCell.switch_mem U.seeds U.radius hs hi + rw [U.fullReplacement_inside i H hi,U.fullReplacement_inside j H hj] + apply dist_le_zero.mp + have h := U.replacement_lipschitz.dist_le_mul + (SecondaryCell.point U.seeds U.radius i H.val hi) (SecondaryCell.point U.seeds U.radius j H.val hj) + simpa only [SecondaryCell.point_dist_switch U.seeds hi hj hs,mul_zero] using h + · have hj : H.val ∉ SecondaryCell.domain U.seeds U.radius j := fun hj => hi + (SecondaryCell.switch_mem U.seeds U.radius (M.symm i j ▸ hs) hj) + rw [U.fullReplacement_outside i H hi,U.fullReplacement_outside j H hj] + exact U.comparison.switch i j H hs + +noncomputable def fullField : M.Field U.data.band (SecondaryCell.replacementConstant U.tree) where + value := U.fullReplacement + vertical := U.fullReplacement_vertical + switch := U.fullReplacement_switch + +end PlanarL1.Columns.Model.BState.SecondaryStep + +namespace PlanarL1.Columns.Model.BState.SecondaryStep +open MeasureTheory Set +open scoped NNReal +open PlanarL1.Interpolation +attribute [local instance] Classical.propDecidable +variable {k : ℕ} {M : Model (k+1)} {κ : ℝ} {lam : ℝ≥0} + {Ω : Type*} [MeasurableSpace Ω] {μ : Measure Ω} + {S : BState M κ lam Ω μ} {J : Set ℝ} {root : Fin (k+1)} +variable (U : SecondaryStep S J root) + +noncomputable def fullNamed (i : Fin (k+1)) (H : U.data.band) : NamedValue := + if hd : H.val ∈ SecondaryCell.domain U.seeds U.radius i then + U.named (SecondaryCell.point U.seeds U.radius i H.val hd) + else ⟨0,U.comparison.value i H⟩ + +lemma fullNamed_value (i : Fin (k+1)) (H : U.data.band) : + (U.fullNamed i H).value = U.fullReplacement i H := by + unfold fullNamed fullReplacement + split_ifs with hd + · exact SecondaryCell.namedReplacement_value _ _ _ _ _ _ _ _ _ _ _ _ + · rfl + +lemma fullNamed_switch (i j : Fin (k+1)) (H : U.data.band) + (hs : H.val ∈ M.heights i j) : U.fullNamed i H=U.fullNamed j H := by + by_cases hi : H.val ∈ SecondaryCell.domain U.seeds U.radius i + · have hj := SecondaryCell.switch_mem U.seeds U.radius hs hi + simp only [fullNamed,dite_eq_left hi,dite_eq_left hj] + exact SecondaryCell.namedReplacement_congr_zero U.tree U.seeds U.old U.supportValue U.data.isOrdinary + U.old_lipschitz U.support_lipschitz U.pc U.radius U.ordered_offset U.shield_offset U.lo U.noise_bounds + _ _ (SecondaryCell.point_dist_switch U.seeds hi hj hs) + · have hj : H.val ∉ SecondaryCell.domain U.seeds U.radius j := fun hj => hi + (SecondaryCell.switch_mem U.seeds U.radius (M.symm i j ▸ hs) hj) + simp only [fullNamed,dite_eq_right hi,dite_eq_right hj,U.comparison.switch i j H hs] + +lemma fullNamed_zero (i : Fin (k+1)) (H : U.data.band) + (h : (U.fullNamed i H).name=0) : + (U.fullNamed i H).value=U.comparison.value i H := by + by_cases hd : H.val ∈ SecondaryCell.domain U.seeds U.radius i + · simp only [fullNamed,dite_eq_left hd] at h ⊢ + rw [← U.point_old hd] + rcases SecondaryCell.namedReplacement_cases U.tree U.seeds U.old U.supportValue U.data.isOrdinary + U.pc U.radius U.ordered_offset U.shield_offset U.lo U.noise + (SecondaryCell.point U.seeds U.radius i H.val hd) with ho | hh | hq | hp + · exact congrArg NamedValue.value ho + · change (U.named _).name=0 at h + have hn := congrArg NamedValue.name hh + change (U.named _).name=1 at hn + omega + · have hn := congrArg NamedValue.name hq + change (U.named _).name=2 at hn + omega + · have hn := congrArg NamedValue.name hp + change (U.named _).name=_+3 at hn + omega + · simp only [fullNamed,dite_eq_right hd] + +lemma fullNamed_choice (i : Fin (k+1)) (H : U.data.band) + (h : (U.fullNamed i H).name ≠ 0) : + ∃ a, U.choose i H.val=some a ∧ (U.fullNamed i H).name=a.val+1 ∧ + H.val ∈ SecondaryCell.domain U.seeds U.radius i := by + have hd : H.val ∈ SecondaryCell.domain U.seeds U.radius i := by + by_contra hd + simp only [fullNamed,dite_eq_right hd] at h + exact h rfl + have ht : (U.named (SecondaryCell.point U.seeds U.radius i H.val hd)).name ≠ 0 := by + simpa only [fullNamed,dite_eq_left hd] using h + let a : Fin (3*(k+1)*U.tree.depthCap+2) := + ⟨(U.named (SecondaryCell.point U.seeds U.radius i H.val hd)).name-1,by + have hb := SecondaryCell.namedReplacement_bound U.tree U.seeds U.old U.supportValue U.data.isOrdinary + U.pc U.radius U.ordered_offset U.shield_offset U.lo U.noise + (SecondaryCell.point U.seeds U.radius i H.val hd) + change (U.named _).name < _ at hb + omega⟩ + refine ⟨a,?_,?_,hd⟩ + · change (SecondaryCell.namedReplacement _ _ _ _ _ _ _ _ _ _ _ _).name ≠ 0 at ht + simp only [choose,SecondaryCell.choose,dite_eq_left hd,dite_eq_right ht] + rfl + · simp only [fullNamed,dite_eq_left hd,a] + omega + +lemma fullReplacement_scaled_vertical (i : Fin (k+1)) : + LipschitzWith 1 (fun H : U.data.band => κ*U.fullReplacement i H) := by + apply LipschitzWith.of_dist_le_mul + intro H T + have h := (U.fullReplacement_vertical i).dist_le_mul H T + rw [Real.dist_eq] at h ⊢ + rw [← mul_sub,abs_mul,abs_of_nonneg U.kappa_nonneg] + calc + _ ≤ κ*((SecondaryCell.replacementConstant U.tree : ℝ)*dist H T) := + mul_le_mul_of_nonneg_left h U.kappa_nonneg + _ = (κ*(SecondaryCell.replacementConstant U.tree : ℝ))*dist H T := by ring + _ ≤ 1*dist H T := mul_le_mul_of_nonneg_right U.vertical_bound dist_nonneg + _ = _ := by simp + +end PlanarL1.Columns.Model.BState.SecondaryStep + + +end + +end OAI diff --git a/lean/OAI/Combinatorics/PlanarL1/SeedPacking.lean b/lean/OAI/Combinatorics/PlanarL1/SeedPacking.lean new file mode 100644 index 0000000000000000000000000000000000000000..efa228325ace3c618b5603a7afce168216bcafd6 --- /dev/null +++ b/lean/OAI/Combinatorics/PlanarL1/SeedPacking.lean @@ -0,0 +1,767 @@ +import OAI.Combinatorics.PlanarL1.Crossings + +namespace OAI + +section + +namespace PlanarL1 +/-! ## The metric counting step of the restricted packing bound +Padded surviving seeds lie near two short paths, giving a cardinality +estimate without a doubling assumption. +-/ +namespace Packing + +lemma same_bucket_close {t u ε : ℝ} (hε : 0 < ε) (ht : 0 ≤ t) (hu : 0 ≤ u) + (h : ⌊t / ε⌋₊ = ⌊u / ε⌋₊) : |t - u| < ε := by + have ht₀ := Nat.floor_le (div_nonneg ht hε.le) + have hu₀ := Nat.floor_le (div_nonneg hu hε.le) + have ht₁ := Nat.lt_floor_add_one (t / ε) + have hu₁ := Nat.lt_floor_add_one (u / ε) + rw [h] at ht₀ ht₁ + have htu : t / ε - u / ε < 1 := by linarith + have hut : u / ε - t / ε < 1 := by linarith + rw [← sub_div, div_lt_one hε] at htu hut + rw [abs_lt] + constructor <;> linarith + +/-- Points on two parameter intervals, separated by at least `ε` on each +interval, have cardinality at most `2 + 2*L/ε`. -/ +theorem two_intervals_count {S : Type*} [Fintype S] {L ε : ℝ} + (hε : 0 < ε) (hL : 0 ≤ L) (side : S → Fin 2) (time : S → ℝ) + (ht : ∀ i, 0 ≤ time i ∧ time i ≤ L) + (hsep : ∀ i j, i ≠ j → side i = side j → ε ≤ |time i - time j|) : + (Fintype.card S : ℝ) ≤ 2 + 2 * L / ε := by + let bucket : S → Fin 2 × Fin (⌊L / ε⌋₊ + 1) := fun i => + (side i, ⟨⌊time i / ε⌋₊, Nat.lt_succ_of_le + (Nat.floor_mono ((div_le_div_iff_of_pos_right hε).mpr (ht i).2))⟩) + have hinj : Function.Injective bucket := by + intro i j hij + have hs : side i = side j := congrArg Prod.fst hij + have hb : ⌊time i / ε⌋₊ = ⌊time j / ε⌋₊ := congrArg (fun x => x.2.val) hij + by_contra hne + exact (same_bucket_close hε (ht i).1 (ht j).1 hb).not_ge (hsep i j hne hs) + have hc := Fintype.card_le_of_injective bucket hinj + simp only [Fintype.card_prod, Fintype.card_fin] at hc + have hcreal : (Fintype.card S : ℝ) ≤ 2 * (⌊L / ε⌋₊ + 1) := by exact_mod_cast hc + have hf := Nat.floor_le (div_nonneg hL hε.le) + calc + (Fintype.card S : ℝ) ≤ 2 * (⌊L / ε⌋₊ + 1) := hcreal + _ ≤ 2 + 2 * L / ε := by nlinarith [mul_div_assoc (2 : ℝ) L ε] + +/-- The two-path packing calculation, valid in any metric space. No bound on +all cells or all balls is asserted: the hypotheses refer only to the selected, +padded seeds and their explicitly assigned nearby path points. -/ +theorem near_two_paths_count {X S : Type*} [PseudoMetricSpace X] [Fintype S] + {L b ρ : ℝ} (hb : 0 < b) (hL : 0 ≤ L) (hρ : ρ ≤ b / 4) + (seed : S → X) (path : Fin 2 → ℝ → X) (side : S → Fin 2) (time : S → ℝ) + (ht : ∀ i, 0 ≤ time i ∧ time i ≤ L) + (hne : ∀ i j, i ≠ j → b ≤ dist (seed i) (seed j)) + (hnear : ∀ i, dist (seed i) (path (side i) (time i)) ≤ ρ) + (hpath : ∀ a t u, dist (path a t) (path a u) ≤ |t - u|) : + (Fintype.card S : ℝ) ≤ 2 + 4 * L / b := by + have hsep : ∀ i j, i ≠ j → side i = side j → b / 2 ≤ |time i - time j| := by + intro i j hij hs + have htri := dist_triangle4 (seed i) (path (side i) (time i)) + (path (side j) (time j)) (seed j) + have hni := hnear i + rw [hs] at hni + have hnj := hnear j + have hmid := hpath (side j) (time i) (time j) + rw [hs, dist_comm (path (side j) (time j)) (seed j)] at htri + have hbij := hne i j hij + linarith + have hc := two_intervals_count (by positivity : 0 < b / 2) hL side time ht hsep + convert hc using 1 + ring + +/-- Substitution of the actual packing constants: each path has length `4R`, +padded seeds are `0.01g` separated, and the source's near-path radius is at most +one quarter of that separation. -/ +theorem surviving_seed_number {X S : Type*} [PseudoMetricSpace X] [Fintype S] + {R g ρ : ℝ} (hg : 0 < g) (hR : 0 ≤ R) (hρ : ρ ≤ (0.01 * g) / 4) + (seed : S → X) (path : Fin 2 → ℝ → X) (side : S → Fin 2) (time : S → ℝ) + (ht : ∀ i, 0 ≤ time i ∧ time i ≤ 4 * R) + (hne : ∀ i j, i ≠ j → 0.01 * g ≤ dist (seed i) (seed j)) + (hnear : ∀ i, dist (seed i) (path (side i) (time i)) ≤ ρ) + (hpath : ∀ a t u, dist (path a t) (path a u) ≤ |t - u|) : + Fintype.card S ≤ 2 + ⌈1600 * R / g⌉₊ := by + have hreal := near_two_paths_count (by positivity : 0 < 0.01 * g) + (by positivity : 0 ≤ 4 * R) hρ seed path side time ht hne hnear hpath + have hcalc : 4 * (4 * R) / (0.01 * g) = 1600 * R / g := by ring + rw [hcalc] at hreal + have hceil := Nat.le_ceil (1600 * R / g) + have : (Fintype.card S : ℝ) ≤ 2 + (⌈1600 * R / g⌉₊ : ℝ) := by linarith + exact_mod_cast this + +end Packing + + +end PlanarL1 + +end + +section + +namespace PlanarL1.Columns.Model.Path + +variable {n : ℕ} {M : Model n} {J I : Set ℝ} + +/-- A specified visit of a finite switching path, retaining its traveled +arclength. Multiple visits of the same representative are not identified. -/ +def AtTime : {i j : Fin n} → M.Path J i j → ℝ → ℝ → (Fin n × ℝ) → ℝ → Prop + | i, _, .nil _, a, b, z, t => z.1 = i ∧ z.2 ∈ Set.uIcc a b ∧ t = |a-z.2| + | i, _, .cons H _ _ p, a, b, z, t => + (z.1 = i ∧ z.2 ∈ Set.uIcc a H ∧ t = |a-z.2|) ∨ p.AtTime H b z (t-|a-H|) + +lemma trace_atTime {i j : Fin n} (p : M.Path J i j) {a b : ℝ} {z : Fin n × ℝ} + (hz : z ∈ p.trace a b) : ∃ t, p.AtTime a b z t := by + induction p generalizing a with + | nil i => exact ⟨|a-z.2|,hz.1,hz.2,rfl⟩ + | cons H hH hs p ih => + rcases hz with hz | hz + · exact ⟨|a-z.2|,Or.inl ⟨hz.1,hz.2,rfl⟩⟩ + · obtain ⟨t,ht⟩ := ih hz + exact ⟨|a-H|+t,Or.inr (by simpa only [add_sub_cancel_left] using ht)⟩ + +lemma atTime_split {i j : Fin n} (p : M.Path J i j) {a b t : ℝ} {z : Fin n × ℝ} + (hz : p.AtTime a b z t) : ∃ (q : M.Path J i z.1) (r : M.Path J z.1 j), + q.length a z.2 = t ∧ r.length z.2 b = p.length a b-t := by + induction p generalizing a t with + | nil i => + obtain ⟨hz,hs,ht⟩ := hz + subst i + exact ⟨.nil _,.nil _,ht.symm,by dsimp only [length]; linarith [abs_split hs]⟩ + | @cons i v j H hH hs p ih => + rcases hz with ⟨hz,hu,ht⟩ | hz + · subst i + refine ⟨.nil _,.cons H hH hs p,ht.symm,?_⟩ + dsimp only [length] + linarith [abs_split hu] + · obtain ⟨q,r,hq,hr⟩ := ih hz + refine ⟨.cons H hH hs q,r,?_,?_⟩ <;> dsimp only [length] <;> linarith + +lemma atTime_bounds {i j : Fin n} (p : M.Path J i j) {a b t : ℝ} {z : Fin n × ℝ} + (hz : p.AtTime a b z t) : 0 ≤ t ∧ t ≤ p.length a b := by + obtain ⟨q,r,hq,hr⟩ := p.atTime_split hz + constructor <;> linarith [q.length_nonneg a z.2,r.length_nonneg z.2 b] + +lemma vertical_offset {a b x y : ℝ} (hx : x ∈ Set.uIcc a b) (hy : y ∈ Set.uIcc a b) : + |x-y| = |(|a-x|)-(|a-y|)| := by + rcases le_total a b with hab | hab + · have hx' : a ≤ x := by rcases Set.mem_uIcc.mp hx with hx | hx <;> linarith + have hy' : a ≤ y := by rcases Set.mem_uIcc.mp hy with hy | hy <;> linarith + rw [abs_of_nonpos (sub_nonpos.mpr hx'),abs_of_nonpos (sub_nonpos.mpr hy')] + congr 1 + ring + · have hx' : x ≤ a := by rcases Set.mem_uIcc.mp hx with hx | hx <;> linarith + have hy' : y ≤ a := by rcases Set.mem_uIcc.mp hy with hy | hy <;> linarith + rw [abs_of_nonneg (sub_nonneg.mpr hx'),abs_of_nonneg (sub_nonneg.mpr hy')] + have he : a-x-(a-y) = y-x := by ring + rw [he,abs_sub_comm] + +/-- Subpaths between actual arclength visits have no greater length than the +arclength difference. This is proved on the finite words, without assuming an +unconstructed continuous parametrization. -/ +lemma between_atTime {i j : Fin n} (p : M.Path J i j) {a b t u : ℝ} {z w : Fin n × ℝ} + (hz : p.AtTime a b z t) (hw : p.AtTime a b w u) : + ∃ q : M.Path J z.1 w.1, q.length z.2 w.2 ≤ |t-u| := by + induction p generalizing a t u with + | nil i => + obtain ⟨hz,hs,ht⟩ := hz + obtain ⟨hw,hr,hu⟩ := hw + have he : z.1 = w.1 := hz.trans hw.symm + let q : M.Path J z.1 w.1 := he ▸ .nil z.1 + refine ⟨q,?_⟩ + have hlen : q.length z.2 w.2 = |z.2-w.2| := by + cases z with + | mk zi zh => + cases w with + | mk wi wh => + dsimp at he + subst wi + rfl + rw [hlen,ht,hu,vertical_offset hs hr] + | @cons i v j H hH hs p ih => + rcases hz with ⟨hz,hz',ht⟩ | hz <;> rcases hw with ⟨hw,hw',hu⟩ | hw + · have he : z.1 = w.1 := hz.trans hw.symm + let q : M.Path J z.1 w.1 := he ▸ .nil z.1 + refine ⟨q,?_⟩ + have hlen : q.length z.2 w.2 = |z.2-w.2| := by + cases z with + | mk zi zh => + cases w with + | mk wi wh => + dsimp at he + subst wi + rfl + rw [hlen,ht,hu,vertical_offset hz' hw'] + · obtain ⟨q,r,hq,_⟩ := p.atTime_split hw + subst i + refine ⟨.cons H hH hs q,?_⟩ + dsimp only [length] + rw [hq] + have he := abs_split hz' + have htu : t ≤ u := by linarith [p.atTime_bounds hw,abs_nonneg (z.2-H)] + rw [abs_of_nonpos (sub_nonpos.mpr htu)] + linarith + · obtain ⟨q,r,hq,_⟩ := p.atTime_split hz + subst i + let vq : M.Path J w.1 z.1 := .cons H hH hs q + refine ⟨vq.reverse,?_⟩ + rw [length_reverse] + change |w.2-H|+q.length H z.2 ≤ |t-u| + rw [hq] + have he := abs_split hw' + have hut : u ≤ t := by linarith [p.atTime_bounds hz,abs_nonneg (w.2-H)] + rw [abs_of_nonneg (sub_nonneg.mpr hut)] + linarith + · obtain ⟨q,hq⟩ := ih hz hw + refine ⟨q,?_⟩ + have he : t-|a-H|-(u-|a-H|) = t-u := by ring + rwa [he] at hq + +lemma dist_atTime {i j root : Fin n} (p : M.Path J i j) (hJI : J ⊆ I) + {a b t u : ℝ} (z w : M.Point I root) + (hz : p.AtTime a b (z.column,z.height) t) (hw : p.AtTime a b (w.column,w.height) u) : + dist z w ≤ |t-u| := by + obtain ⟨q,hq⟩ := p.between_atTime hz hw + exact (z.distance_le w (q.widen hJI)).trans (by simpa only [length_widen] using hq) + +end PlanarL1.Columns.Model.Path + +namespace PlanarL1.Columns.Model + +variable {n : ℕ} {M : Model n} {I J : Set ℝ} {root : Fin n} + +/-- The source's two-path packing bound for the actual finite switching paths, +including all their vertical representatives and repeated visits. -/ +theorem near_two_traces_count {S : Type*} [Fintype S] {L b ρ : ℝ} + (hJI : J ⊆ I) (hb : 0 < b) (hL : 0 ≤ L) (hρ : ρ ≤ b/4) + (start finish : Fin 2 → Fin n) (p : ∀ a, M.Path J (start a) (finish a)) + (A B : Fin 2 → ℝ) (hp : ∀ a, (p a).length (A a) (B a) ≤ L) + (seed near : S → M.Point I root) (side : S → Fin 2) + (htrace : ∀ i, ((near i).column,(near i).height) ∈ + (p (side i)).trace (A (side i)) (B (side i))) + (hne : ∀ i j, i ≠ j → b ≤ dist (seed i) (seed j)) + (hnear : ∀ i, dist (seed i) (near i) ≤ ρ) : + (Fintype.card S : ℝ) ≤ 2+4*L/b := by + classical + choose time htime using (fun i => (p (side i)).trace_atTime (htrace i)) + have ht : ∀ i, 0 ≤ time i ∧ time i ≤ L := by + intro i + exact ⟨((p (side i)).atTime_bounds (htime i)).1, + ((p (side i)).atTime_bounds (htime i)).2.trans (hp (side i))⟩ + have hsep : ∀ i j, i ≠ j → side i = side j → b/2 ≤ |time i-time j| := by + intro i j hij hs + have hi := htime i + rw [hs] at hi + have hmid := (p (side j)).dist_atTime hJI (near i) (near j) hi (htime j) + have htri := dist_triangle4 (seed i) (near i) (near j) (seed j) + rw [dist_comm (near j) (seed j)] at htri + linarith [hne i j hij,hnear i,hnear j] + have hc := Packing.two_intervals_count (by positivity : 0 < b/2) hL side time ht hsep + convert hc using 1 + ring + +/-- Direct substitution of the manuscript constants, with no abstract +Lipschitz path or externally supplied parametrization. -/ +theorem surviving_seed_traces_number {S : Type*} [Fintype S] {R g ρ : ℝ} + (hJI : J ⊆ I) (hg : 0 < g) (hR : 0 ≤ R) (hρ : ρ ≤ (0.01*g)/4) + (start finish : Fin 2 → Fin n) (p : ∀ a, M.Path J (start a) (finish a)) + (A B : Fin 2 → ℝ) (hp : ∀ a, (p a).length (A a) (B a) ≤ 4*R) + (seed near : S → M.Point I root) (side : S → Fin 2) + (htrace : ∀ i, ((near i).column,(near i).height) ∈ + (p (side i)).trace (A (side i)) (B (side i))) + (hne : ∀ i j, i ≠ j → 0.01*g ≤ dist (seed i) (seed j)) + (hnear : ∀ i, dist (seed i) (near i) ≤ ρ) : + Fintype.card S ≤ 2+⌈1600*R/g⌉₊ := by + have hc := near_two_traces_count hJI (by positivity : 0 < 0.01*g) + (by positivity : 0 ≤ 4*R) hρ start finish p A B hp seed near side htrace hne hnear + have he : 4*(4*R)/(0.01*g) = 1600*R/g := by ring + rw [he] at hc + have hceil := Nat.le_ceil (1600*R/g) + have : (Fintype.card S : ℝ) ≤ 2+(⌈1600*R/g⌉₊ : ℝ) := by linarith + exact_mod_cast this + +end PlanarL1.Columns.Model + +namespace PlanarL1.ColumnOrder + +/-- A connected low set lying on the far side of a chord has no vertex in +its open interval, provided neither endpoint belongs to that set. -/ +lemma gap_of_chord {n : ℕ} {G : SimpleGraph (Fin n)} (hnc : Noncrossing G) + {S : Set (Fin n)} (hS : (G.induce S).Preconnected) {a b c : Fin n} + (hab : G.Adj a b) (ha : a ∉ S) (hb : b ∉ S) (hc : c ∈ S) + (hcside : c < a ∨ b < c) : ∀ v ∈ S, v < a ∨ b < v := by + intro v hv + by_contra h + obtain ⟨p⟩ := hS ⟨v,hv⟩ ⟨c,hc⟩ + let q := p.map (SimpleGraph.Embedding.induce S).toHom + have hmem : ∀ t ∈ q.support, t ∈ S := by + intro t ht + obtain ⟨w,_,hw⟩ := List.mem_map.mp (by simpa only [q,SimpleGraph.Walk.support_map] using ht) + exact hw ▸ w.property + have hav : a ≠ v := fun he => ha (he ▸ hv) + have hbv : b ≠ v := fun he => hb (he ▸ hv) + have hvside : a < v ∧ v < b := by push Not at h; constructor <;> omega + rcases chord_separation hnc hab q hvside hcside with hm | hm + · exact ha (hmem a hm) + · exact hb (hmem b hm) + +end PlanarL1.ColumnOrder + +namespace PlanarL1.Columns + +lemma not_consecutive_of_between {n : ℕ} {a b w c : Fin n} + (hw : a < w ∧ w < b) (hc : c < a ∨ b < c) : ¬ Consecutive a b := by + intro h + rcases h with h | h | ⟨h,h'⟩ | ⟨h,h'⟩ <;> + rcases hc with hc | hc <;> simp only [Fin.lt_def] at hw hc <;> omega + +namespace Model.Path + +variable {n : ℕ} {M : Model n} {J : Set ℝ} + +lemma trace_start {i j : Fin n} (p : M.Path J i j) (a b : ℝ) : + (i,a) ∈ p.trace a b := by + cases p with + | nil => exact ⟨rfl,Set.left_mem_uIcc⟩ + | cons => exact Or.inl ⟨rfl,Set.left_mem_uIcc⟩ + +lemma trace_end {i j : Fin n} (p : M.Path J i j) (a b : ℝ) : + (j,b) ∈ p.trace a b := by + induction p generalizing a with + | nil => exact ⟨rfl,Set.right_mem_uIcc⟩ + | cons H _ _ p ih => exact Or.inr (ih H) + +lemma trace_on_column {i j : Fin n} (p : M.Path J i j) {a b : ℝ} + (ha : a ∈ J) {v : Fin n} (hv : v ∈ p.word.support) : + ∃ H ∈ J, (v,H) ∈ p.trace a b := by + induction p generalizing a with + | nil i => + have he : v = i := by simpa only [word,SimpleGraph.Walk.support_nil,List.mem_singleton] using hv + exact ⟨a,ha,he,Set.left_mem_uIcc⟩ + | @cons i z j H hH hs p ih => + rcases List.mem_cons.mp hv with hv | hv + · subst v + exact ⟨a,ha,Or.inl ⟨rfl,Set.left_mem_uIcc⟩⟩ + · obtain ⟨T,hT,ht⟩ := ih hH hv + exact ⟨T,hT,Or.inr ht⟩ + +/-- Every dart of the word is an actual switch at a height visited on both +of its representatives by the original path. -/ +lemma dart_on_trace {i j : Fin n} (p : M.Path J i j) (a b : ℝ) + (e : (M.activeGraph J).Dart) (he : e ∈ p.word.darts) : + ∃ H ∈ J, H ∈ M.heights e.fst e.snd ∧ + (e.fst,H) ∈ p.trace a b ∧ (e.snd,H) ∈ p.trace a b := by + induction p generalizing a with + | nil => simp only [word,SimpleGraph.Walk.darts_nil,List.not_mem_nil] at he + | @cons i z j H hH hs p ih => + rcases List.mem_cons.mp he with he | he + · subst e + exact ⟨H,hH,hs,Or.inl ⟨rfl,Set.right_mem_uIcc⟩,Or.inr (p.trace_start H b)⟩ + · obtain ⟨T,hT,ht,he₁,he₂⟩ := ih H he + exact ⟨T,hT,ht,Or.inr he₁,Or.inr he₂⟩ + +end Model.Path + +end PlanarL1.Columns + +namespace PlanarL1.Columns.Model + +variable {n : ℕ} {M : Model n} {J : Set ℝ} {root : Fin n} + +namespace Point + +/-- Vertical transfer to either representative of a switch costs at most the +width of the band, even if the two representatives are not equal as structures. -/ +lemma dist_to_tip (e v : M.Point J root) {b : Fin n} {a : ℝ} + (hs : e.height ∈ M.heights e.column b) + (hw : ∀ s ∈ J, ∀ t ∈ J, |s-t| ≤ a) (hv : v.column = e.column ∨ v.column = b) : + dist v e ≤ a := by + rcases hv with hv | hv + · rw [v.dist_same_column e hv] + exact hw v.height v.inBand e.height e.inBand + · have hs' : e.height ∈ M.heights v.column e.column := by rw [hv,M.symm]; exact hs + have hd := v.dist_le_switch e e.inBand hs' + simpa only [sub_self,abs_zero,add_zero] using hd.trans + (by simpa only [sub_self,abs_zero,add_zero] using hw v.height v.inBand e.height e.inBand) + +end Point + +namespace Field + +/-- Descending paths are actual attained shortest switching paths, with the +manuscript's length domain and endpoint deficit, not assumed rays in a quotient. -/ +structure Descent (F : M.Field J 1) (x : M.Point J root) (ε : ℝ) where + target : M.Point J root + path : M.Path J x.column target.column + shortest : path.length x.height target.height = dist x target + lower : (1:ℝ)/100000 ≤ path.length x.height target.height + upper : path.length x.height target.height ≤ (1:ℝ)/50 + drop : F.eval target ≤ F.eval x-path.length x.height target.height+ε + +namespace Descent + +variable {F : M.Field J 1} {x : M.Point J root} {ε : ℝ} + +/-- A visited column supplies an actual prefix point with both the total +length control and the almost-unit descending scalar estimate. -/ +lemma column_prefix (D : F.Descent x ε) {v : Fin n} (hv : v ∈ D.path.word.support) : + ∃ z : M.Point J root, z.column = v ∧ dist x z ≤ (1:ℝ)/50 ∧ + F.eval z ≤ F.eval x-dist x z+ε := by + obtain ⟨T,hT,q,r,hqr⟩ := D.path.split_at_column x.inBand D.target.inBand hv + let z : M.Point J root := ⟨v,T,hT,x.reachable.trans q.word.reachable⟩ + have hd := x.distance_le z q + have hn := r.length_nonneg T D.target.height + have hf := F.path_bound r ⟨T,hT⟩ ⟨D.target.height,D.target.inBand⟩ + norm_num only [NNReal.coe_one,one_mul] at hf + have hzval : F.eval z-F.eval D.target ≤ r.length T D.target.height := + (le_abs_self _).trans hf + have hshort := D.upper + have hdrop := D.drop + refine ⟨z,rfl,?_,?_⟩ <;> change dist x z ≤ q.length x.height T at hd <;> linarith + +/-- Basic reach-to-tip bound used to show that a witness partner cannot lie +on the skipped side of a chord. -/ +lemma near_tip (D : F.Descent x ε) (e : M.Point J root) {b : Fin n} {a : ℝ} + (hs : e.height ∈ M.heights e.column b) + (hw : ∀ s ∈ J, ∀ t ∈ J, |s-t| ≤ a) + (hx : e.column < x.column ∧ x.column < b) + (hz : D.target.column < e.column ∨ b < D.target.column) : + dist x e ≤ (1:ℝ)/50+a := by + have hadj : (M.activeGraph J).Adj e.column b := ⟨e.height,e.inBand,hs⟩ + obtain hv | hv := ColumnOrder.chord_separation (M.active_noncrossing J) hadj D.path.word hx hz + · obtain ⟨v,hv,hlen,_⟩ := D.column_prefix hv + have hd := e.dist_to_tip v hs hw (Or.inl hv) + linarith [dist_triangle x v e] + · obtain ⟨v,hv,hlen,_⟩ := D.column_prefix hv + have hd := e.dist_to_tip v hs hw (Or.inr hv) + linarith [dist_triangle x v e] + +/-- The quantitative skipped-seed estimate `pack:near-path`: the absence of a +low separating tip truncates the actual descending prefix at j+ε+a. -/ +lemma near_tip_of_not_low (D : F.Descent x ε) (hJ : IsClosed J) + (e : M.Point J root) {b : Fin n} {a j : ℝ} + (hs : e.height ∈ M.heights e.column b) + (hw : ∀ s ∈ J, ∀ t ∈ J, |s-t| ≤ a) + (hx : e.column < x.column ∧ x.column < b) + (hz : D.target.column < e.column ∨ b < D.target.column) + (hlow : F.eval x-j ≤ F.eval e) : dist x e ≤ j+ε+2*a := by + have hadj : (M.activeGraph J).Adj e.column b := ⟨e.height,e.inBand,hs⟩ + have hvis := ColumnOrder.chord_separation (M.active_noncrossing J) hadj D.path.word hx hz + have hcase {k : Fin n} (hk : k ∈ D.path.word.support) (he : k = e.column ∨ k = b) : + dist x e ≤ j+ε+2*a := by + obtain ⟨v,hv,_,hdrop⟩ := D.column_prefix hk + have hd := e.dist_to_tip v hs hw (hv ▸ he) + have hf := (F.lipschitz hJ root).dist_le_mul e v + change dist (F.eval e) (F.eval v) ≤ (1:NNReal)*dist e v at hf + rw [Real.dist_eq,NNReal.coe_one,one_mul,dist_comm e v] at hf + have hr : F.eval e-F.eval v ≤ a := (le_abs_self _).trans (hf.trans hd) + linarith [dist_triangle x v e] + exact hvis.elim (fun h => hcase h (Or.inl rfl)) (fun h => hcase h (Or.inr rfl)) + +end Descent + +/-- The partner of a seed skipped by an extreme short path must be strictly +outside the chord. Boundary representatives are also excluded quantitatively. -/ +lemma partner_outside_tip {F : M.Field J 1} {ε a A : ℝ} + (x y e : M.Point J root) (D : F.Descent y ε) {b : Fin n} + (hs : e.height ∈ M.heights e.column b) + (hw : ∀ s ∈ J, ∀ t ∈ J, |s-t| ≤ a) + (hz : D.target.column < e.column ∨ b < D.target.column) + (hxy : 1 ≤ dist x y) (hxe : dist x e ≤ A) (hsmall : (1:ℝ)/50+a+A < 1) : + y.column < e.column ∨ b < y.column := by + by_contra h + have hab : e.column < b := by + have hadj := M.permitted e.column b e.height hs + have hne := hadj.ne + by_contra hh + push Not at h + omega + have hle : e.column ≤ y.column ∧ y.column ≤ b := by push Not at h; exact h + have hd : dist y e ≤ (1:ℝ)/50+a := by + by_cases hy : y.column = e.column + · have := e.dist_to_tip y hs hw (Or.inl hy) + linarith + by_cases hy' : y.column = b + · have := e.dist_to_tip y hs hw (Or.inr hy') + linarith + exact D.near_tip e hs hw ⟨lt_of_le_of_ne hle.1 (Ne.symm hy),lt_of_le_of_ne hle.2 hy'⟩ hz + have ht := dist_triangle x e y + rw [dist_comm e y] at ht + linarith + +end Field + +end PlanarL1.Columns.Model + +namespace PlanarL1.ColumnOrder + +lemma visits_or_skips_left {n : ℕ} {G : SimpleGraph (Fin n)} {i x y : Fin n} + (p : G.Walk x y) (hx : i < x) (hy : y < i) : + i ∈ p.support ∨ JumpsAcross i p := by + induction p with + | nil => omega + | @cons x z y hxz p ih => + by_cases hz : z = i + · left + exact List.mem_cons_of_mem x (hz ▸ p.start_mem_support) + by_cases hzi : i < z + · rcases ih hzi hy with hm | ⟨e,he,hcross⟩ + · left + simp [hm] + · right + exact ⟨e,by simp [he],hcross⟩ + · right + refine ⟨⟨(x,z),hxz⟩,?_,Or.inr ⟨?_,hx⟩⟩ + · simp + · change z < i + omega + +/-- The two extremal words cover every intermediate column by a visit or a +strictly skipping dart. No connectedness of the seed set is asserted. -/ +lemma extreme_words {n : ℕ} {G : SimpleGraph (Fin n)} {l r c w : Fin n} + (p : G.Walk c l) (q : G.Walk c r) (hl : l ≤ w) (hr : w ≤ r) : + (w ∈ p.support ∨ JumpsAcross w p) ∨ (w ∈ q.support ∨ JumpsAcross w q) := by + rcases lt_trichotomy w c with h | h | h + · left + by_cases he : l = w + · exact Or.inl (he ▸ p.end_mem_support) + exact visits_or_skips_left p h (lt_of_le_of_ne hl he) + · left + left + exact h ▸ p.start_mem_support + · right + by_cases he : w = r + · exact Or.inl (he ▸ q.end_mem_support) + exact visits_or_skips q h (lt_of_le_of_ne hr he) + +end PlanarL1.ColumnOrder + +namespace PlanarL1.Columns.Model + +variable {n : ℕ} {M : Model n} {I J : Set ℝ} {root : Fin n} + +namespace Point + +lemma dist_le_trace_length (hJI : J ⊆ I) (c e : M.Point I root) {v : Fin n} + (p : M.Path J c.column v) {H : ℝ} (he : (e.column,e.height) ∈ p.trace c.height H) : + dist c e ≤ p.length c.height H := by + obtain ⟨q,r,hqr⟩ := p.trace_split he + have hd := c.distance_le e (q.widen hJI) + rw [Path.length_widen] at hd + have hn := r.length_nonneg e.height H + change dist c e ≤ q.length c.height e.height at hd + linarith + +/-- Every actual trace representative is an intrinsic point of the same +larger-band component as the start, not an assumed representative choice. -/ +lemma point_on_trace (hJI : J ⊆ I) (c : M.Point I root) {v k : Fin n} + (p : M.Path J c.column v) {H T : ℝ} (hT : T ∈ J) + (ht : (k,T) ∈ p.trace c.height H) : + ∃ e : M.Point I root, e.column = k ∧ e.height = T ∧ dist c e ≤ p.length c.height H := by + obtain ⟨q,_,_⟩ := p.trace_split ht + let e : M.Point I root := ⟨k,T,hJI hT,c.reachable.trans (q.widen hJI).word.reachable⟩ + exact ⟨e,rfl,rfl,c.dist_le_trace_length hJI e p ht⟩ + +end Point + +namespace Field + +/-- Strict separation of representatives by the chord, with an arbitrary +linear cut outside its first open arc. -/ +def TipSeparates (a b x y : Fin n) : Prop := + (a < x ∧ x < b ∧ (y < a ∨ b < y)) ∨ (a < y ∧ y < b ∧ (x < a ∨ b < x)) + +/-- Complement of the main procedure's barrier-drop exclusion. Both endpoint +thresholds are tested, exactly as in pack:barrier and pack:retained-data. -/ +def NoLowTip (F : M.Field I 1) (x y : M.Point I root) (J : Set ℝ) (j : ℝ) : Prop := + ∀ (e : M.Point I root) (b : Fin n), e.height ∈ J → + e.height ∈ M.heights e.column b → ¬ Consecutive e.column b → + TipSeparates e.column b x.column y.column → + (dist x e ≤ 1 ∨ dist y e ≤ 1) → + F.eval x-j ≤ F.eval e ∧ F.eval y-j ≤ F.eval e + +/-- A single skipping dart of an extreme path puts its seed near the actual +trace. Connected low columns, witness descent and the barrier exclusion are +used here, not replaced by the desired near-path conclusion. -/ +lemma skipped_seed_near_trace (F : M.Field I 1) (hI : IsClosed I) + {S : Set (Fin n)} (hS : (M.link.induce S).Preconnected) + {cut : Fin n} (hcut : cut ∈ S) (hmin : ∀ v, cut ≤ v) + (hJI : J ⊆ I) {a A j ε : ℝ} (hw : ∀ s ∈ I, ∀ t ∈ I, |s-t| ≤ a) + (c x y : M.Point I root) (Dx : F.Descent x ε) (Dy : F.Descent y ε) + (hxS : Dx.target.column ∈ S) (hyS : Dy.target.column ∈ S) + (hxy : 1 ≤ dist x y) (hcx : dist c x ≤ A) (hA : 2*A ≤ 1) + (hsmall : (1:ℝ)/50+a+2*A < 1) (hretain : F.NoLowTip x y J j) + {v : Fin n} (p : M.Path J c.column v) {H : ℝ} (hp : p.length c.height H ≤ A) + (havoid : ∀ k ∈ p.word.support, k ∉ S) (hskip : ColumnOrder.JumpsAcross x.column p.word) : + ∃ e : M.Point I root, (e.column,e.height) ∈ p.trace c.height H ∧ + dist x e ≤ j+ε+2*a := by + obtain ⟨d,hd,hcross⟩ := hskip + obtain ⟨T,hT,hs,ht₁,ht₂⟩ := p.dart_on_trace c.height H d hd + have hcase {l r : Fin n} (hlr : l < x.column ∧ x.column < r) + (hs : T ∈ M.heights l r) (htl : (l,T) ∈ p.trace c.height H) + (htr : (r,T) ∈ p.trace c.height H) : + ∃ e : M.Point I root, (e.column,e.height) ∈ p.trace c.height H ∧ dist x e ≤ j+ε+2*a := by + have hl : l ∉ S := havoid l (p.trace_column htl) + have hr : r ∉ S := havoid r (p.trace_column htr) + have hcl : cut < l := lt_of_le_of_ne (hmin l) (fun h => hl (h ▸ hcut)) + have hgap := ColumnOrder.gap_of_chord M.noncrossing hS + (M.permitted l r T hs) hl hr hcut (Or.inl hcl) + obtain ⟨e,hecol,heheight,helen⟩ := c.point_on_trace hJI p hT htl + have hetrace : (e.column,e.height) ∈ p.trace c.height H := by rwa [hecol,heheight] + have hxe : dist x e ≤ 2*A := by + have ht := dist_triangle x c e + rw [dist_comm x c] at ht + linarith + have hes : e.height ∈ M.heights e.column r := by rwa [hecol,heheight] + have hyp : y.column < e.column ∨ r < y.column := partner_outside_tip x y e Dy hes hw + (by simpa only [hecol] using hgap _ hyS) hxy hxe hsmall + have hnc : ¬ Consecutive e.column r := by + rw [hecol] + exact not_consecutive_of_between hlr (Or.inl hcl) + have hlow := (hretain e r (heheight ▸ hT) hes hnc + (Or.inl ⟨by simpa only [hecol] using hlr.1,hlr.2,hyp⟩) (Or.inl (hxe.trans hA))).1 + refine ⟨e,hetrace,Dx.near_tip_of_not_low hI e hes hw ?_ ?_ hlow⟩ + · simpa only [hecol] using hlr + · simpa only [hecol] using hgap _ hxS + rcases hcross with hc | hc + · exact hcase hc hs ht₁ ht₂ + · exact hcase hc (by rwa [M.symm]) ht₂ ht₁ + +end Field + +end PlanarL1.Columns.Model + +namespace PlanarL1.Columns.Model.Field + +variable {n : ℕ} {M : Model n} {I J : Set ℝ} {root : Fin n} + +/-- A visited seed column is vertically near a point of the original trace; +leaving the individual radial cell is allowed throughout. -/ +lemma visited_seed_near_trace (hJI : J ⊆ I) {a : ℝ} + (hw : ∀ s ∈ I, ∀ t ∈ I, |s-t| ≤ a) (c x : M.Point I root) + (hc : c.height ∈ J) {v : Fin n} (p : M.Path J c.column v) {H : ℝ} + (hx : x.column ∈ p.word.support) : + ∃ e : M.Point I root, (e.column,e.height) ∈ p.trace c.height H ∧ dist x e ≤ a := by + obtain ⟨T,hT,ht⟩ := p.trace_on_column hc hx + obtain ⟨e,hecol,heheight,_⟩ := c.point_on_trace hJI p hT ht + refine ⟨e,by rwa [hecol,heheight],?_⟩ + rw [x.dist_same_column e hecol.symm] + exact hw x.height x.inBand e.height e.inBand + +/-- The restricted packing geometry, before the final substitution of fixed +constants. The two extremal paths are selected from the actual center paths. +The low set may be absent from most columns; no doubling or ambient ball +packing hypothesis occurs. -/ +theorem restricted_packing {K : Type*} [Fintype K] + (F : M.Field I 1) (hI : IsClosed I) + {S : Set (Fin n)} (hS : (M.link.induce S).Preconnected) + {cut : Fin n} (hcut : cut ∈ S) (hmin : ∀ v, cut ≤ v) + (hJI : J ⊆ I) {a A j ε b : ℝ} (hw : ∀ s ∈ I, ∀ t ∈ I, |s-t| ≤ a) + (hA₀ : 0 ≤ A) (hA : 2*A ≤ 1) (hsmall : (1:ℝ)/50+a+2*A < 1) + (hb : 0 < b) (hpad : j+ε+2*a ≤ b/4) (hvisit : a ≤ j+ε+2*a) + (c : M.Point I root) (hc : c.height ∈ J) (hcS : c.column ∉ S) + (seed partner : K → M.Point I root) + (Dx : ∀ w, F.Descent (seed w) ε) (Dy : ∀ w, F.Descent (partner w) ε) + (hxS : ∀ w, (Dx w).target.column ∈ S) (hyS : ∀ w, (Dy w).target.column ∈ S) + (hxy : ∀ w, 1 ≤ dist (seed w) (partner w)) + (hretain : ∀ w, F.NoLowTip (seed w) (partner w) J j) + (cp : ∀ w, M.Path J c.column (seed w).column) + (hp : ∀ w, (cp w).length c.height (seed w).height ≤ A) + (havoid : ∀ w k, k ∈ (cp w).word.support → k ∉ S) + (hsep : ∀ w v, w ≠ v → b ≤ dist (seed w) (seed v)) : + (Fintype.card K : ℝ) ≤ 2+4*A/b := by + classical + let endpoint : Option K → M.Point I root := Option.elim' c seed + let path : ∀ w : Option K, M.Path J c.column (endpoint w).column := fun w => + Option.rec (.nil c.column) cp w + have hlen : ∀ w, (path w).length c.height (endpoint w).height ≤ A := by + intro w + cases w with + | none => simpa only [path,endpoint,Option.elim',Path.length,sub_self,abs_zero] using hA₀ + | some w => exact hp w + have hav : ∀ w k, k ∈ (path w).word.support → k ∉ S := by + intro w k hk + cases w with + | none => + have he : k = c.column := by + change k ∈ [c.column] at hk + exact List.mem_singleton.mp hk + exact he ▸ hcS + | some w => exact havoid w k hk + obtain ⟨l,_,hl⟩ := Finset.exists_min_image (Finset.univ : Finset (Option K)) + (fun w => (endpoint w).column) ⟨none,Finset.mem_univ _⟩ + obtain ⟨r,_,hr⟩ := Finset.exists_max_image (Finset.univ : Finset (Option K)) + (fun w => (endpoint w).column) ⟨none,Finset.mem_univ _⟩ + let select : Fin 2 → Option K := ![l,r] + let paths (s : Fin 2) := path (select s) + have hone (w : K) (v : Option K) + (hv : (seed w).column ∈ (path v).word.support ∨ + ColumnOrder.JumpsAcross (seed w).column (path v).word) : + ∃ e : M.Point I root, (e.column,e.height) ∈ (path v).trace c.height (endpoint v).height ∧ + dist (seed w) e ≤ j+ε+2*a := by + rcases hv with hv | hv + · obtain ⟨e,he,hnear⟩ := visited_seed_near_trace hJI hw c (seed w) hc (path v) hv + exact ⟨e,he,hnear.trans hvisit⟩ + · have hcs : dist c (seed w) ≤ A := by + have hd := c.distance_le (seed w) ((cp w).widen hJI) + rw [Path.length_widen] at hd + exact hd.trans (hp w) + exact F.skipped_seed_near_trace hI hS hcut hmin hJI hw c (seed w) (partner w) + (Dx w) (Dy w) (hxS w) (hyS w) (hxy w) hcs hA hsmall (hretain w) + (path v) (hlen v) (hav v) hv + have hprox : ∀ w : K, ∃ (s : Fin 2) (e : M.Point I root), + (e.column,e.height) ∈ (paths s).trace c.height (endpoint (select s)).height ∧ + dist (seed w) e ≤ j+ε+2*a := by + intro w + have h := ColumnOrder.extreme_words (path l).word (path r).word + (hl (some w) (Finset.mem_univ _)) (hr (some w) (Finset.mem_univ _)) + rcases h with h | h + · obtain ⟨e,he,hnear⟩ := hone w l h + exact ⟨0,e,by simpa only [paths,select,Matrix.cons_val_zero] using he,hnear⟩ + · obtain ⟨e,he,hnear⟩ := hone w r h + exact ⟨1,e,by simpa only [paths,select,Matrix.cons_val_one,Matrix.cons_val_zero] using he,hnear⟩ + choose side near htrace hnear using hprox + exact near_two_traces_count hJI hb hA₀ hpad (fun _ => c.column) + (fun s => (endpoint (select s)).column) paths (fun _ => c.height) + (fun s => (endpoint (select s)).height) (fun s => hlen (select s)) + seed near side htrace hsep hnear + +/-- The source packing number after the restricted geometric argument, +with A=4R and padded distinct cells separated by 0.01g. -/ +theorem restricted_packing_number {K : Type*} [Fintype K] + (F : M.Field I 1) (hI : IsClosed I) + {S : Set (Fin n)} (hS : (M.link.induce S).Preconnected) + {cut : Fin n} (hcut : cut ∈ S) (hmin : ∀ v, cut ≤ v) + (hJI : J ⊆ I) {a R j ε g : ℝ} (hw : ∀ s ∈ I, ∀ t ∈ I, |s-t| ≤ a) + (hR₀ : 0 ≤ R) (hR : 8*R ≤ 1) (hsmall : (1:ℝ)/50+a+8*R < 1) + (hg : 0 < g) (hpad : j+ε+2*a ≤ (0.01*g)/4) (hvisit : a ≤ j+ε+2*a) + (c : M.Point I root) (hc : c.height ∈ J) (hcS : c.column ∉ S) + (seed partner : K → M.Point I root) + (Dx : ∀ w, F.Descent (seed w) ε) (Dy : ∀ w, F.Descent (partner w) ε) + (hxS : ∀ w, (Dx w).target.column ∈ S) (hyS : ∀ w, (Dy w).target.column ∈ S) + (hxy : ∀ w, 1 ≤ dist (seed w) (partner w)) + (hretain : ∀ w, F.NoLowTip (seed w) (partner w) J j) + (cp : ∀ w, M.Path J c.column (seed w).column) + (hp : ∀ w, (cp w).length c.height (seed w).height ≤ 4*R) + (havoid : ∀ w k, k ∈ (cp w).word.support → k ∉ S) + (hsep : ∀ w v, w ≠ v → 0.01*g ≤ dist (seed w) (seed v)) : + Fintype.card K ≤ 2+⌈1600*R/g⌉₊ := by + have hc := F.restricted_packing hI hS hcut hmin hJI hw (by positivity : 0 ≤ 4*R) + (by linarith : 2*(4*R) ≤ 1) (by linarith : (1:ℝ)/50+a+2*(4*R) < 1) + (by positivity : 0 < 0.01*g) hpad hvisit c hc hcS seed partner Dx Dy hxS hyS hxy + hretain cp hp havoid hsep + have he : 4*(4*R)/(0.01*g) = 1600*R/g := by ring + rw [he] at hc + have hceil := Nat.le_ceil (1600*R/g) + have : (Fintype.card K : ℝ) ≤ 2+(⌈1600*R/g⌉₊ : ℝ) := by linarith + exact_mod_cast this + +end PlanarL1.Columns.Model.Field + + +end + +end OAI diff --git a/lean/OAI/Combinatorics/PlanarL1/SelectedGain.lean b/lean/OAI/Combinatorics/PlanarL1/SelectedGain.lean new file mode 100644 index 0000000000000000000000000000000000000000..394a1b3315b9e02e6525e8fd0a33c649ed4fc669 --- /dev/null +++ b/lean/OAI/Combinatorics/PlanarL1/SelectedGain.lean @@ -0,0 +1,600 @@ +import OAI.Combinatorics.PlanarL1.SecondaryGain + +namespace OAI + + +section + +namespace PlanarL1.Columns.Model.BData +open scoped NNReal +attribute [local instance] Classical.propDecidable +variable {k : ℕ} {M : Model (k+1)} + +lemma comparison_distance (D : BData M) (lam : ℝ≥0) (hlam : lam≤(1:ℝ≥0)/100) + (positive : Bool) (i j : Fin (k+1)) (H T : D.band) : + |(D.comparison lam hlam positive).value i H-(D.comparison lam hlam positive).value j T|= + |D.value lam i H-D.value lam j T| := by + rw [D.comparison_convert lam hlam positive i H,D.comparison_convert lam hlam positive j T] + rw [show D.offset+D.orientation positive*(D.comparison lam hlam positive).value i H- + (D.offset+D.orientation positive*(D.comparison lam hlam positive).value j T)= + D.orientation positive*((D.comparison lam hlam positive).value i H- + (D.comparison lam hlam positive).value j T) by ring, + abs_mul,D.orientation_unit,one_mul] +end PlanarL1.Columns.Model.BData + +end + + + +section + +namespace PlanarL1.Columns.Model.RetainedSelection +open Parameters MeasureTheory SecondaryGeometry FiniteRandom +attribute [local instance] Classical.propDecidable +attribute [local irreducible] FiniteRandom.prob +variable {k : ℕ} {M : Model (k+1)} {V Ω Ξ : Type*} +variable [Fintype V] [MeasurableSpace Ω] [MeasurableSpace Ξ] +variable {μ : Measure Ω} {ν : Measure Ξ} +variable (A : Ambient M) (SA : OrdinaryState M kappaA Ω μ) +variable (SB : BState M kappaB Group.lam Ξ ν) +variable (v : V → M.Point Set.univ A.root) +variable {L U : ℝ} (hv : ∀ x, (v x).height ∈ Set.Icc L U) +variable {q p : ℝ} {phaseD phaseG : MainFamily.BandComponent (M := M) q L U → ℝ} +variable (b : Block (M := M) q p L U) +variable (c : M.Point (BandTrees.band broad b.lower) (BandTrees.root M broad b.lower b.1.2)) +variable (i : GroupIndex A SA SB v hv (p := p) (phaseD := phaseD) (phaseG := phaseG)) +variable (w : M.Point (group A SA SB v hv i).broad (group A SA SB v hv i).broad_root) +variable (hw : w ∈ (group A SA SB v hv i).seeds) +variable (hfar : 1≤dist (A.point w.column w.height) (A.point c.column c.height)) +variable (C : (group A SA SB v hv i).Component) +variable (x : M.Point (BandTrees.band narrow (group A SA SB v hv i).lower) + ((group A SA SB v hv i).root C)) +variable (positive : Bool) (hx : x ∈ (group A SA SB v hv i).admittedSeeds positive C) +variable (hl : (group A SA SB v hv i).lower+9*a₂/100 ≤ x.height) +variable (hu : x.height ≤ (group A SA SB v hv i).lower+a₂-9*a₂/100) +variable (hT : c.height ∈ (group A SA SB v hv i).data.band) +variable (hn : SB.name c.column c.height=(group A SA SB v hv i).index) +variable (hclose : ∀ hH : x.height ∈ (group A SA SB v hv i).data.band, + |(group A SA SB v hv i).data.value Group.lam x.column ⟨x.height,hH⟩- + (group A SA SB v hv i).data.value Group.lam c.column ⟨c.height,hT⟩|≤R/10000) +variable {m : ℕ} (hm : 0 < m) + +include hw hfar hx hl hu hn hclose in +lemma gain_of_suppression + (omega : Sample (group A SA SB v hv (p := p) (phaseD := phaseD) (phaseG := phaseG)) m) + (ho : omega.1 (group A SA SB v hv i).index=positive) + (hk : omega.2.1 i=true) + (hs : ∀ j, Touch A SA SB v hv b c j → j≠i → omega.2.1 j=false) : + kappaB*R/50 < (layer (group A SA SB v hv) hm omega).sets.separation x.column x.height c.column c.height := by + let a := (group A SA SB v hv i).index + have hx' : x ∈ (group A SA SB v hv i).admittedSeeds (omega.1 a) C := by + rw [ho] + exact hx + let z : Acting (group A SA SB v hv) omega a := ⟨⟨i,C⟩,rfl,hk,⟨x,hx'⟩⟩ + have hy := batch_not_domain A SA SB v hv b c i w hw hfar hm omega a hs + apply gain_external (group A SA SB v hv) hm omega a z x hx' hl hu c.column c.height hT hy hn + intro hH + calc + _ = |(group A SA SB v hv i).data.value Group.lam x.column ⟨x.height,hH⟩- + (group A SA SB v hv i).data.value Group.lam c.column ⟨c.height,hT⟩| := + (group A SA SB v hv i).data.comparison_distance Group.lam Group.lam_bound _ _ _ _ _ + _ ≤ _ := hclose hH + +include hw hfar hx hl hu hn hclose in +lemma admitted_probability + (hc : c.height ∈ BandTrees.band narrow b.lower₂) + (hp : Tiling.Padded a₁ q c.height (a₁/10)) (hN : Tiling.Padded a₂ p c.height (a₂/10)) : + 1/(2:ℝ)^(SurvivingGroups.packBound+2) ≤ FiniteRandom.prob + (fun omega : Sample (group A SA SB v hv (p := p) (phaseD := phaseD) (phaseG := phaseG)) m => + kappaB*R/50 < (layer (group A SA SB v hv) hm omega).sets.separation x.column x.height c.column c.height) := by + let T := Finset.univ.filter (Touch A SA SB v hv b c (phaseD := phaseD) (phaseG := phaseG)) + have hcard : T.card≤SurvivingGroups.packBound := touching_finset_card A SA SB v hv b c hc hp hN + have hprob := prob_orient_keep_suppress (group A SA SB v hv) m (group A SA SB v hv i).index positive i T hcard + refine hprob.trans (@FiniteRandom.prob_mono_instances (Sample (group A SA SB v hv) m) _ _ _ _ ?_) + intro omega he + apply gain_of_suppression A SA SB v hv b c i w hw hfar C x positive hx hl hu hT hn hclose hm omega he.1 he.2.1 + intro j hj hji + exact he.2.2 j (Finset.mem_filter.mpr ⟨Finset.mem_univ _,hj⟩) hji +end PlanarL1.Columns.Model.RetainedSelection + +end + + + +section + +namespace PlanarL1.Columns.Model.SecondaryGeometry.Group +open Parameters MeasureTheory +attribute [local instance] Classical.propDecidable +variable {k : ℕ} {M : Model (k+1)} {Ω : Type*} [MeasurableSpace Ω] {μ : Measure Ω} +variable {A : Ambient M} {S : BState M kappaB (⟨lambda,by norm_num [lambda,R]⟩) Ω μ} +variable (G : SecondaryGeometry.Group A S) + +noncomputable def componentOf (w : M.Point G.broad G.broad_root) : G.Component := + (M.activeGraph (BandTrees.band narrow G.lower)).connectedComponentMk w.column + +noncomputable def endpoint (w : M.Point G.broad G.broad_root) (hw : w ∈ G.seeds) : + M.Point (BandTrees.band narrow G.lower) (G.root (G.componentOf w)) where + column := w.column + height := w.height + inBand := G.height w hw + reachable := (G.componentOf w).reachable_of_mem_supp (BandTrees.root_mem _ _ _ _) rfl + +lemma endpoint_mem (w : M.Point G.broad G.broad_root) (hw : w ∈ G.seeds) : + G.endpoint w hw ∈ G.allSeeds (G.componentOf w) := + (G.allSeeds_description _ _).mpr ⟨w,hw,rfl,rfl⟩ + +lemma endpoint_admitted (w : M.Point G.broad G.broad_root) (hw : w ∈ G.seeds) (positive : Bool) : + G.endpoint w hw ∈ G.admittedSeeds positive (G.componentOf w) ↔ + G.Admitted positive (G.componentOf w) (G.endpoint w hw) := by + simp only [admittedSeeds,Finset.mem_filter,G.endpoint_mem w hw,true_and] +end PlanarL1.Columns.Model.SecondaryGeometry.Group + +end + + + +section + +namespace PlanarL1.Columns.Model.RetainedSelection +open Parameters MeasureTheory SecondaryGeometry VertexTests +attribute [local instance] Classical.propDecidable +attribute [local irreducible] FiniteRandom.prob +variable {k : ℕ} {M : Model (k+1)} {V Ω Ξ : Type*} +variable [Fintype V] [MeasurableSpace Ω] [MeasurableSpace Ξ] +variable {μ : Measure Ω} {ν : Measure Ξ} +variable (A : Ambient M) (SA : OrdinaryState M kappaA Ω μ) +variable (SB : BState M kappaB Group.lam Ξ ν) +variable (v : V → M.Point Set.univ A.root) +variable {L U : ℝ} (hv : ∀ x, (v x).height ∈ Set.Icc L U) +variable {q p : ℝ} {phaseD phaseG : MainFamily.BandComponent (M := M) q L U → ℝ} +private lemma bvalue_transport {D E : BData M} (h : D=E) (j : Fin (k+1)) (H : ℝ) + (hD : H∈D.band) (hE : H∈E.band) : + D.value Group.lam j ⟨H,hD⟩=E.value Group.lam j ⟨H,hE⟩ := by subst E; rfl + +variable (w : Endpoint A SA SB v L U hv q p phaseD phaseG) + +lemma groupOf_index : (group A SA SB v hv (groupOf A SA SB v hv w)).index=indexB A SB v w.val := rfl +lemma groupOf_lower : (group A SA SB v hv (groupOf A SA SB v hv w)).lower=PairGeometry.narrowLower A v p w.val := rfl + +noncomputable def selectedComponent := + (group A SA SB v hv (groupOf A SA SB v hv w)).componentOf (rawSeed A SA SB v hv w).point +noncomputable def selectedPoint := + (group A SA SB v hv (groupOf A SA SB v hv w)).endpoint (rawSeed A SA SB v hv w).point + (groupOf_seed A SA SB v hv w) +lemma selectedPoint_column : (selectedPoint A SA SB v hv w).column=(v w.val).column := rfl +lemma selectedPoint_height : (selectedPoint A SA SB v hv w).height=(v w.val).height := rfl +lemma selectedPoint_mem : selectedPoint A SA SB v hv w ∈ + (group A SA SB v hv (groupOf A SA SB v hv w)).allSeeds (selectedComponent A SA SB v hv w) := + Group.endpoint_mem _ _ _ + +lemma selectedPoint_plateau : + (group A SA SB v hv (groupOf A SA SB v hv w)).lower+9*a₂/100≤(selectedPoint A SA SB v hv w).height ∧ + (selectedPoint A SA SB v hv w).height≤(group A SA SB v hv (groupOf A SA SB v hv w)).lower+a₂-9*a₂/100 := by + have h := (witness A SA SB v hv w).interior.2.1 + have hh := h + dsimp only [Tiling.Padded] at hh + change _≤(v w.val).height ∧ (v w.val).height≤_ + rw [groupOf_lower] + dsimp [PairGeometry.narrowLower] + have ha : 0 linarith [hh.1,hh.2] + +variable {y : V} +variable (hi : VertexBands.Interior A v (hv := hv) q p phaseD phaseG y) +noncomputable def blockFor : Block (M := M) q p L U := + ⟨VertexBands.bandComponent A v L U hv q y, + ⟨⟨Tiling.index a₂ p (v y).height, + (Tiling.mem_processed interpolationB.2.1 p L U _).mpr + ⟨(v y).height,Tiling.mem_band_index interpolationB.2.1 p _,hv y⟩⟩, + hi.narrow_sub A v⟩⟩ + +variable (he : Eligible A SA SB v w.val y) (ha : 1≤dist (v w.val) (v y)) +variable (hc : Cutoffs A SA SB v w.val y) +variable (positive : Bool) +variable (had : (group A SA SB v hv (groupOf A SA SB v hv w)).Admitted positive + (selectedComponent A SA SB v hv w) (selectedPoint A SA SB v hv w)) +variable {m : ℕ} (hm : 0 < m) + +include hi he ha hc had in +lemma selected_admitted_probability : + 1/(2:ℝ)^(SurvivingGroups.packBound+2) ≤ FiniteRandom.prob + (fun omega : Sample (group A SA SB v hv (p := p) (phaseD := phaseD) (phaseG := phaseG)) m => + kappaB*R/50 < (layer (group A SA SB v hv) hm omega).sets.separation + (v w.val).column (v w.val).height (v y).column (v y).height) := by + let b := blockFor A v hv hi + let c := VertexBands.point A v L U hv q y + let i := groupOf A SA SB v hv w + let G := group A SA SB v hv i + have hT : c.height∈G.data.band := by + change (v y).height∈(SB.chart (indexB A SB v w.val)).band + rw [←he.namesB A SA SB v] + exact SB.height_in _ _ + have hn : SB.name c.column c.height=G.index := he.namesB A SA SB v + have hfar : 1≤dist (A.point (rawSeed A SA SB v hv w).point.column (rawSeed A SA SB v hv w).point.height) + (A.point c.column c.height) := by + change 1≤dist (A.point (v w.val).column (v w.val).height) (A.point (v y).column (v y).height) + simpa only [A.coordinate_point] using ha + have had' : selectedPoint A SA SB v hv w ∈ G.admittedSeeds positive (selectedComponent A SA SB v hv w) := + (Group.endpoint_admitted _ _ _ _).mpr had + have hclose (hH : (selectedPoint A SA SB v hv w).height∈G.data.band) : + |G.data.value Group.lam (selectedPoint A SA SB v hv w).column ⟨(selectedPoint A SA SB v hv w).height,hH⟩- + G.data.value Group.lam c.column ⟨c.height,hT⟩|≤R/10000 := by + change |fullValue A SB v w.val-(SB.chart (indexB A SB v w.val)).value Group.lam (v y).column ⟨(v y).height,hT⟩|≤_ + have hh := bvalue_transport (congrArg SB.chart (he.namesB A SA SB v).symm) + (v y).column (v y).height hT (SB.height_in _ _) + rw [hh] + exact hc.2.2.le + exact admitted_probability A SA SB v hv b c i (rawSeed A SA SB v hv w).point + (groupOf_seed A SA SB v hv w) hfar (selectedComponent A SA SB v hv w) + (selectedPoint A SA SB v hv w) positive had' (selectedPoint_plateau A SA SB v hv w).1 + (selectedPoint_plateau A SA SB v hv w).2 hT hn hclose hm + (PairGeometry.narrow_height A v p y) hi.1 hi.2.1 +end PlanarL1.Columns.Model.RetainedSelection + +end + + + +section + +namespace PlanarL1.Columns.Model +open Parameters MeasureTheory +attribute [local instance] Classical.propDecidable +attribute [local irreducible] FiniteRandom.prob +variable {k : ℕ} {M : Model (k+1)} {Ω : Type*} [MeasurableSpace Ω] {μ : Measure Ω} + +namespace BData +variable {A : Ambient M} (H : A.History (R/200)) (region : Set (M.Point Set.univ A.root)) +variable (hcross : ∀ j, 10≤(R/200)*H.radius j) +noncomputable def normalizedIncrement (D : BData M) (e : Bool) : M.Field D.band 5 := + D.auxiliaryField (D.incrementAuxiliary H 1 region e (by norm_num [R]) + (by norm_num [R]) (by norm_num) (by simpa using hcross)) + SecondaryGeometry.Group.lam SecondaryGeometry.Group.lam_bound +lemma normalizedIncrement_coordinates {D E : BData M} (h : D=E) + {i j : Fin (k+1)} {s t : ℝ} (hi : i=j) (hs : s=t) + (hI : s∈D.band) (hJ : t∈E.band) (e : Bool) : + (normalizedIncrement H region hcross D e).value i ⟨s,hI⟩= + (normalizedIncrement H region hcross E e).value j ⟨t,hJ⟩ := by + subst E; subst j; subst t; rfl +end BData + +namespace IncrementStep +variable (A : Ambient M) (S : BState M kappaB SecondaryGeometry.Group.lam Ω μ) +variable (hist : Fin (S.count+1) → A.History (R/200)) +variable (hcross : ∀ a j, 10≤(R/200)*(hist a).radius j) +variable (hrec : ∀ a, (S.chart a).Recorded (hist a) (by norm_num [R]) (by norm_num [R])) + +noncomputable def update (sign : Fin (S.count+1) → Bool) : + BState M kappaB SecondaryGeometry.Group.lam Ω μ := + S.increment (r := 1) A hist sign (by norm_num [R]) (by norm_num [R]) (by norm_num) + (by simpa using hcross) hrec verticalB.1 (by norm_num [kappaB,a₂]) + SecondaryGeometry.Group.lam_bound (by change kappaB*lambda*10≤1/8; norm_num [kappaB,a₂,lambda,R]) + +lemma names (sign : Fin (S.count+1) → Bool) : + (update A S hist hcross hrec sign).name=S.name := rfl + +lemma separation_lower (sign : Fin (S.count+1) → Bool) (a : Fin (S.count+1)) + (i j : Fin (k+1)) (s t : ℝ) (hi : S.name i s=a) (hj : S.name j t=a) + (hs : s∈(S.chart a).band) (ht : t∈(S.chart a).band) : + kappaB*|(BData.normalizedIncrement (hist a) (S.region A a) (hcross a) (S.chart a) (sign a)).value i ⟨s,hs⟩- + (BData.normalizedIncrement (hist a) (S.region A a) (hcross a) (S.chart a) (sign a)).value j ⟨t,ht⟩|≤ + (update A S hist hcross hrec sign).sets.separation i s j t := by + let F := S.incrementFields A hist sign (by norm_num [R]) (by norm_num [R]) + (by norm_num : (0:ℝ)<1) (by simpa using hcross) SecondaryGeometry.Group.lam_bound + have he := S.fieldUpdate_separation F verticalB.1 (by norm_num [kappaB,a₂]) + SecondaryGeometry.Group.lam_bound + (S.increment_boundary (r := 1) A hist sign (by norm_num [R]) (by norm_num [R]) (by norm_num) + (by simpa using hcross) hrec verticalB.1 SecondaryGeometry.Group.lam_bound + (by change kappaB*lambda*10≤1/8; norm_num [kappaB,a₂,lambda,R])) i j s t a hi hj + change (update A S hist hcross hrec sign).sets.separation i s j t= + max |s-t| |S.newValue F i s-S.newValue F j t| at he + rw [he,S.newValue_eq F i s a hi,S.newValue_eq F j t a hj, + ←mul_sub,abs_mul,abs_of_nonneg verticalB.1] + exact le_max_right _ _ + +variable {a : Fin (S.count+1)} {D : OrderedData M} +variable (hD : S.chart a=.ordered D) {root : Fin (k+1)} (x y : M.Point D.band root) +variable (hx : A.Common S.name (A.point x.column x.height) 1 a) +variable (hy : A.Common S.name (A.point y.column y.height) 1 a) +variable (ho : (D.base.transverse (by norm_num) D.lower D.upper).eval x * + (D.base.transverse (by norm_num) D.lower D.upper).eval y<0) +variable (hlx : R/100≤|(D.base.transverse (by norm_num) D.lower D.upper).eval x|) +variable (hly : R/100≤|(D.base.transverse (by norm_num) D.lower D.upper).eval y|) +variable (hux : |(D.base.transverse (by norm_num) D.lower D.upper).eval x|≤8) +variable (huy : |(D.base.transverse (by norm_num) D.lower D.upper).eval y|≤8) + +include hD hx hy ho hlx hly hux huy in +/-- The actual simultaneous append of every old ordered history has at least +one favorable value of the common identifier's fair coin. -/ +lemma favorable_sign : ∃ e : Bool, ∀ sign : Fin (S.count+1) → Bool, sign a=e → + kappaB*lambda*R/50≤(update A S hist hcross hrec sign).sets.separation + x.column x.height y.column y.height := by + have hr : (BData.ordered D).Recorded (hist a) (by norm_num [R]) (by norm_num [R]) := by + rw [←hD] + exact hrec a + obtain ⟨e,he⟩ := D.exists_increment_gain (hist a) (S.region A a) (hcross a) hr x y hx hy + ho hlx hly hux huy + refine ⟨e,fun sign hs => ?_⟩ + have hxi : S.name x.column x.height=a := hx.center A (by norm_num) + have hyi : S.name y.column y.height=a := hy.center A (by norm_num) + have hi := S.height_named x.column x.height a hxi + have hj := S.height_named y.column y.height a hyi + have hb := separation_lower A S hist hcross hrec sign a x.column y.column x.height y.height hxi hyi hi hj + rw [hs] at hb + have ex := BData.normalizedIncrement_coordinates (hist a) (S.region A a) (hcross a) hD + (i := x.column) rfl (s := x.height) rfl hi x.inBand e + have ey := BData.normalizedIncrement_coordinates (hist a) (S.region A a) (hcross a) hD + (i := y.column) rfl (s := y.height) rfl hj y.inBand e + rw [ex,ey] at hb + have hh := mul_le_mul_of_nonneg_left he verticalB.1 + change kappaB*(lambda*R/50)≤kappaB*|_ - _| at hh + calc + kappaB*lambda*R/50 = kappaB*(lambda*R/50) := by ring + _ ≤ _ := hh + _ ≤ _ := hb + +include hD hx hy ho hlx hly hux huy in +lemma success_probability : 1/2≤FiniteRandom.prob (fun sign : Fin (S.count+1) → Bool => + kappaB*lambda*R/50≤(update A S hist hcross hrec sign).sets.separation + x.column x.height y.column y.height) := by + obtain ⟨e,he⟩ := favorable_sign A S hist hcross hrec hD x y hx hy ho hlx hly hux huy + rw [←FiniteRandom.prob_coin a e] + exact @FiniteRandom.prob_mono_instances (Fin (S.count+1) → Bool) _ _ _ _ he +end IncrementStep +end PlanarL1.Columns.Model + +end + + + +section + +namespace PlanarL1.Columns.Model.RetainedSelection +open Parameters MeasureTheory SecondaryGeometry VertexTests +attribute [local instance] Classical.propDecidable +variable {k : ℕ} {M : Model (k+1)} {V Ω Ξ : Type*} +variable [Fintype V] [MeasurableSpace Ω] [MeasurableSpace Ξ] +variable {μ : Measure Ω} {ν : Measure Ξ} +variable (A : Ambient M) (SA : OrdinaryState M kappaA Ω μ) +variable (SB : BState M kappaB Group.lam Ξ ν) +variable (v : V → M.Point Set.univ A.root) +variable {L U : ℝ} (hv : ∀ x, (v x).height ∈ Set.Icc L U) +variable {q p : ℝ} {phaseD phaseG : MainFamily.BandComponent (M := M) q L U → ℝ} + +noncomputable def ofWitness {x : V} (W : Witness A SA SB v L U hv q p phaseD phaseG x) : + Endpoint A SA SB v L U hv q p phaseD phaseG := + ⟨x,(mem_remaining A SA SB v hv x).mpr ⟨W⟩⟩ + +variable (w z : Endpoint A SA SB v L U hv q p phaseD phaseG) +variable (he : Eligible A SA SB v w.val z.val) (hc : Cutoffs A SA SB v w.val z.val) +variable (ha : 1≤dist (v w.val) (v z.val)) (hd : dist (v w.val) (v z.val)<2) + +lemma ordered_of_rejected + (hn : ¬(group A SA SB v hv (groupOf A SA SB v hv w)).Admitted true + (selectedComponent A SA SB v hv w) (selectedPoint A SA SB v hv w)) : + ∃ D : OrderedData M, SB.chart (indexB A SB v w.val)=.ordered D := by + cases hD : SB.chart (indexB A SB v w.val) with + | ordinary C => + apply False.elim + apply hn + left + change (SB.chart (indexB A SB v w.val)).isOrdinary=true + rw [hD] + rfl + | ordered D => exact ⟨D,rfl⟩ + +include he hc ha hd in +/-- The two actual retained endpoint groups, rather than hypothetical seeds, +force transverse values in their actual common old ordered chart. -/ +theorem transverse_of_rejected + (hwp : ¬(group A SA SB v hv (groupOf A SA SB v hv w)).Admitted true + (selectedComponent A SA SB v hv w) (selectedPoint A SA SB v hv w)) + (hwn : ¬(group A SA SB v hv (groupOf A SA SB v hv w)).Admitted false + (selectedComponent A SA SB v hv w) (selectedPoint A SA SB v hv w)) + (hzp : ¬(group A SA SB v hv (groupOf A SA SB v hv z)).Admitted true + (selectedComponent A SA SB v hv z) (selectedPoint A SA SB v hv z)) + (hzn : ¬(group A SA SB v hv (groupOf A SA SB v hv z)).Admitted false + (selectedComponent A SA SB v hv z) (selectedPoint A SA SB v hv z)) : + ∃ (D : OrderedData M) (_hD : SB.chart (indexB A SB v w.val)=.ordered D) + (x y : M.Point D.band (v w.val).column), + x.column=(v w.val).column ∧ x.height=(v w.val).height ∧ + y.column=(v z.val).column ∧ y.height=(v z.val).height ∧ + (D.base.transverse (by norm_num) D.lower D.upper).eval x * + (D.base.transverse (by norm_num) D.lower D.upper).eval y < 0 ∧ + R/100≤|(D.base.transverse (by norm_num) D.lower D.upper).eval x| ∧ + R/100≤|(D.base.transverse (by norm_num) D.lower D.upper).eval y| ∧ + |(D.base.transverse (by norm_num) D.lower D.upper).eval x|≤8 ∧ + |(D.base.transverse (by norm_num) D.lower D.upper).eval y|≤8 := by + obtain ⟨D,hD⟩ := ordered_of_rejected A SA SB v hv w hwp + have hband : (SB.chart (indexB A SB v w.val)).band=D.band := congrArg BData.band hD + let x : M.Point D.band (v w.val).column := + ⟨(v w.val).column,(v w.val).height,hband ▸ SB.height_in _ _,SimpleGraph.Reachable.refl _⟩ + have hsub : {H : ℝ | |H-(v w.val).height|≤2} ⊆ D.band := by + rw [←hband] + exact SB.ball_band A he.2.2.1 (fun H hH => by rw [abs_sub_comm]; exact hH.trans (by norm_num)) + obtain ⟨y,hyc,hyh,hdy⟩ := Point.local_point (v w.val) (v z.val) x rfl rfl + isClosed_univ (Set.subset_univ _) hsub hd.le + have hG : (group A SA SB v hv (groupOf A SA SB v hv w)).data=.ordered D := hD + have hH : (group A SA SB v hv (groupOf A SA SB v hv z)).data=.ordered D := by + change SB.chart (indexB A SB v z.val)=.ordered D + rw [he.namesB A SA SB v] + exact hD + have hl : (group A SA SB v hv (groupOf A SA SB v hv z)).lower= + (group A SA SB v hv (groupOf A SA SB v hv w)).lower := by + rw [groupOf_lower,groupOf_lower] + exact PairGeometry.narrow_lower_eq A SA SB v hv (witness A SA SB v hv w).interior hc + have hcut : |D.value Group.lam x.column ⟨x.height,x.inBand⟩- + D.value Group.lam y.column ⟨y.height,y.inBand⟩|≤R/10000 := by + have value_coordinates {D E : BData M} (h : D=E) + {i j : Fin (k+1)} {H T : ℝ} (hc : i=j) (hH : H=T) + (hI : H∈D.band) (hJ : T∈E.band) : + D.value Group.lam i ⟨H,hI⟩=E.value Group.lam j ⟨T,hJ⟩ := by + subst E; subst j; subst T; rfl + have hx : D.value Group.lam x.column ⟨x.height,x.inBand⟩=fullValue A SB v w.val := + value_coordinates hD.symm rfl rfl _ _ + have hy : D.value Group.lam y.column ⟨y.height,y.inBand⟩=fullValue A SB v z.val := + value_coordinates (hD.symm.trans (congrArg SB.chart (he.namesB A SA SB v).symm)) hyc hyh _ _ + rw [hx,hy] + exact hc.2.2.le + refine ⟨D,hD,x,y,rfl,rfl,hyc,hyh,?_⟩ + exact Group.two_side_of_rejected _ _ hG hH hl _ _ _ _ + (selectedPoint_mem A SA SB v hv w) (selectedPoint_mem A SA SB v hv z) + hwp hwn hzp hzn x y rfl rfl hyc hyh (by rw [hdy]; exact ha) + (by rw [hdy]; exact hd.le) hcut +end PlanarL1.Columns.Model.RetainedSelection + +end + + + +section + +namespace PlanarL1.Columns.Model.RetainedSelection +open Parameters MeasureTheory SecondaryGeometry VertexTests +attribute [local instance] Classical.propDecidable +attribute [local irreducible] FiniteRandom.prob +variable {k : ℕ} {M : Model (k+1)} {V Ω Ξ : Type*} +variable [Fintype V] [MeasurableSpace Ω] [MeasurableSpace Ξ] +variable {μ : Measure Ω} {ν : Measure Ξ} +variable (A : Ambient M) (SA : OrdinaryState M kappaA Ω μ) +variable (SB : BState M kappaB Group.lam Ξ ν) +variable (v : V → M.Point Set.univ A.root) +variable {L U : ℝ} (hv : ∀ x, (v x).height ∈ Set.Icc L U) +variable {q p : ℝ} {phaseD phaseG : MainFamily.BandComponent (M := M) q L U → ℝ} +variable (hist : Fin (SB.count+1) → A.History (R/200)) +variable (hcross : ∀ a j, 10≤(R/200)*(hist a).radius j) +variable (hrec : ∀ a, (SB.chart a).Recorded (hist a) (by norm_num [R]) (by norm_num [R])) +variable (w z : Endpoint A SA SB v L U hv q p phaseD phaseG) +variable (he : Eligible A SA SB v w.val z.val) (hc : Cutoffs A SA SB v w.val z.val) +variable (ha : 1≤dist (v w.val) (v z.val)) (hd : dist (v w.val) (v z.val)<2) + +include he hc ha hd in +/-- Both actual endpoint rejections force success of the genuine simultaneous +history increment with one favorable independent fair identifier coin. -/ +lemma rejected_increment_probability + (hwp : ¬(group A SA SB v hv (groupOf A SA SB v hv w)).Admitted true + (selectedComponent A SA SB v hv w) (selectedPoint A SA SB v hv w)) + (hwn : ¬(group A SA SB v hv (groupOf A SA SB v hv w)).Admitted false + (selectedComponent A SA SB v hv w) (selectedPoint A SA SB v hv w)) + (hzp : ¬(group A SA SB v hv (groupOf A SA SB v hv z)).Admitted true + (selectedComponent A SA SB v hv z) (selectedPoint A SA SB v hv z)) + (hzn : ¬(group A SA SB v hv (groupOf A SA SB v hv z)).Admitted false + (selectedComponent A SA SB v hv z) (selectedPoint A SA SB v hv z)) : + 1/2≤FiniteRandom.prob (fun sign : Fin (SB.count+1) → Bool => + kappaB*lambda*R/50≤(IncrementStep.update A SB hist hcross hrec sign).sets.separation + (v w.val).column (v w.val).height (v z.val).column (v z.val).height) := by + obtain ⟨D,hD,x,y,hxc,hxh,hyc,hyh,ho,hlx,hly,hux,huy⟩ := + transverse_of_rejected A SA SB v hv w z he hc ha hd hwp hwn hzp hzn + have hx : A.Common SB.name (A.point x.column x.height) 1 (indexB A SB v w.val) := by + rw [hxc,hxh,A.coordinate_point] + exact fun z hz => he.2.2.1 z (hz.trans (by norm_num)) + have hy : A.Common SB.name (A.point y.column y.height) 1 (indexB A SB v w.val) := by + rw [hyc,hyh,A.coordinate_point] + exact fun z hz => he.2.2.2 z (hz.trans (by norm_num)) + have h := IncrementStep.success_probability A SB hist hcross hrec hD x y hx hy ho hlx hly hux huy + simpa only [hxc,hxh,hyc,hyh] using h +end PlanarL1.Columns.Model.RetainedSelection + +end + + + +section + +namespace PlanarL1.Columns.Model.SetSystem +open MeasureTheory +variable {k : ℕ} {M : Model (k+1)} {Ω : Type*} [MeasurableSpace Ω] {μ : Measure Ω} +lemma separation_comm (S : SetSystem M Ω μ) (i : Fin (k+1)) (H : ℝ) (j : Fin (k+1)) (T : ℝ) : + S.separation i H j T=S.separation j T i H := by + unfold separation + congr 1 + funext ω + exact abs_sub_comm _ _ +end PlanarL1.Columns.Model.SetSystem + +namespace PlanarL1.Parameters +noncomputable def secondaryChance : ℝ := 1/(2:ℝ)^(Columns.Model.SurvivingGroups.packBound+2) +lemma secondaryChance_pos : 0 < secondaryChance := by unfold secondaryChance; positivity +lemma secondaryChance_le_quarter : secondaryChance≤1/4 := by + unfold secondaryChance + apply div_le_div_of_nonneg_left (by norm_num) (by norm_num) + calc + (4:ℝ) = 2^2 := by norm_num + _ ≤ _ := pow_le_pow_right₀ (by norm_num) (by omega) +end PlanarL1.Parameters + +namespace PlanarL1.Columns.Model.PairGeometry +open Parameters MeasureTheory SecondaryGeometry VertexTests RetainedSelection +attribute [local instance] Classical.propDecidable +attribute [local irreducible] FiniteRandom.prob +variable {k : ℕ} {M : Model (k+1)} {V Ω Ξ : Type*} +variable [Fintype V] [MeasurableSpace Ω] [MeasurableSpace Ξ] +variable {μ : Measure Ω} {ν : Measure Ξ} +variable (A : Ambient M) (SA : OrdinaryState M kappaA Ω μ) +variable (SB : BState M kappaB Group.lam Ξ ν) +variable (v : V → M.Point Set.univ A.root) +variable {L U : ℝ} (hv : ∀ x, (v x).height ∈ Set.Icc L U) +variable {q p : ℝ} {phaseD phaseG : MainFamily.BandComponent (M := M) q L U → ℝ} +variable {x y : V} (he : Eligible A SA SB v x y) +variable (hi : VertexBands.Interior A v (hv := hv) q p phaseD phaseG x) +variable (hj : VertexBands.Interior A v (hv := hv) q p phaseD phaseG y) +variable (hc : Cutoffs A SA SB v x y) (ha : 1≤dist (v x) (v y)) (hd : dist (v x) (v y)<2) +variable (hist : Fin (SB.count+1) → A.History (R/200)) +variable (hcross : ∀ a j, 10≤(R/200)*(hist a).radius j) +variable (hrec : ∀ a, (SB.chart a).Recorded (hist a) (by norm_num [R]) (by norm_num [R])) + +include hj hc ha in +lemma retained_alternative {m : ℕ} (hm : 0 < m) (hr : Retained A SA SB v hv he hi hd) : + secondaryChance ≤ FiniteRandom.prob + (fun omega : Sample (group A SA SB v hv (p := p) (phaseD := phaseD) (phaseG := phaseG)) m => + kappaB*R/50 < (layer (group A SA SB v hv) hm omega).sets.separation + (v x).column (v x).height (v y).column (v y).height) ∨ + 1/2 ≤ FiniteRandom.prob (fun sign : Fin (SB.count+1) → Bool => + kappaB*lambda*R/50 ≤ (IncrementStep.update A SB hist hcross hrec sign).sets.separation + (v x).column (v x).height (v y).column (v y).height) := by + have hxmem : x ∈ remaining A SA SB v L U hv q p phaseD phaseG := + (mem_remaining A SA SB v hv x).mpr ⟨⟨y,⟨ha,hd,he⟩,hc,hi,hj,hr⟩⟩ + have hymem : y ∈ remaining A SA SB v L U hv q p phaseD phaseG := + (mem_remaining A SA SB v hv y).mpr ⟨⟨x,⟨by simpa only [dist_comm] using ha, + by simpa only [dist_comm] using hd,he.symm A SA SB v⟩,hc.symm A SA SB v,hj,hi, + hr.symm A SA SB v hv he hi hj hc hd⟩⟩ + let w : Endpoint A SA SB v L U hv q p phaseD phaseG := ⟨x,hxmem⟩ + let z : Endpoint A SA SB v L U hv q p phaseD phaseG := ⟨y,hymem⟩ + have hw (positive : Bool) + (had : (group A SA SB v hv (groupOf A SA SB v hv w)).Admitted positive + (selectedComponent A SA SB v hv w) (selectedPoint A SA SB v hv w)) : + secondaryChance ≤ FiniteRandom.prob + (fun omega : Sample (group A SA SB v hv (p := p) (phaseD := phaseD) (phaseG := phaseG)) m => + kappaB*R/50 < (layer (group A SA SB v hv) hm omega).sets.separation + (v x).column (v x).height (v y).column (v y).height) := + selected_admitted_probability A SA SB v hv w hj he ha hc positive had hm + have hz (positive : Bool) + (had : (group A SA SB v hv (groupOf A SA SB v hv z)).Admitted positive + (selectedComponent A SA SB v hv z) (selectedPoint A SA SB v hv z)) : + secondaryChance ≤ FiniteRandom.prob + (fun omega : Sample (group A SA SB v hv (p := p) (phaseD := phaseD) (phaseG := phaseG)) m => + kappaB*R/50 < (layer (group A SA SB v hv) hm omega).sets.separation + (v x).column (v x).height (v y).column (v y).height) := by + have hh := selected_admitted_probability A SA SB v hv z hi (he.symm A SA SB v) + (by simpa only [dist_comm] using ha) (hc.symm A SA SB v) positive had hm + exact hh.trans (FiniteRandom.prob_mono (fun omega h => by + simpa only [SetSystem.separation_comm] using h)) + by_cases hwp : (group A SA SB v hv (groupOf A SA SB v hv w)).Admitted true + (selectedComponent A SA SB v hv w) (selectedPoint A SA SB v hv w) + · exact Or.inl (hw true hwp) + by_cases hwn : (group A SA SB v hv (groupOf A SA SB v hv w)).Admitted false + (selectedComponent A SA SB v hv w) (selectedPoint A SA SB v hv w) + · exact Or.inl (hw false hwn) + by_cases hzp : (group A SA SB v hv (groupOf A SA SB v hv z)).Admitted true + (selectedComponent A SA SB v hv z) (selectedPoint A SA SB v hv z) + · exact Or.inl (hz true hzp) + by_cases hzn : (group A SA SB v hv (groupOf A SA SB v hv z)).Admitted false + (selectedComponent A SA SB v hv z) (selectedPoint A SA SB v hv z) + · exact Or.inl (hz false hzn) + exact Or.inr (rejected_increment_probability A SA SB v hv hist hcross hrec w z he hc ha hd hwp hwn hzp hzn) +end PlanarL1.Columns.Model.PairGeometry + +end + +end OAI diff --git a/lean/OAI/Combinatorics/PlanarL1/Separation.lean b/lean/OAI/Combinatorics/PlanarL1/Separation.lean new file mode 100644 index 0000000000000000000000000000000000000000..9926a88469a1a36de83be833d58ef45cef371659 --- /dev/null +++ b/lean/OAI/Combinatorics/PlanarL1/Separation.lean @@ -0,0 +1,310 @@ +import OAI.Combinatorics.PlanarL1.SurvivingSeeds + +namespace OAI + + +section + +namespace PlanarL1.Columns.Model +open MeasureTheory Parameters +open scoped NNReal +attribute [local instance] Classical.propDecidable +variable {k : ℕ} {M : Model (k+1)} + +namespace Ambient +variable (A : Ambient M) +lemma taper_of_ball {region : Set (M.Point Set.univ A.root)} + (x : M.Point Set.univ A.root) + (hx : ∀ z, dist x z≤1 → z ∈ region) : Increment.taper regionᶜ 1 x=1 := by + apply Increment.taper_one (by norm_num) + intro hn + apply (Metric.le_infDist hn).mpr + intro z hz + exact le_of_not_gt (fun hd => hz (hx z hd.le)) +end Ambient + +namespace OrderedData +variable (D : OrderedData M) {A : Ambient M} +variable (H : A.History (R/200)) +variable (region : Set (M.Point Set.univ A.root)) +variable (hcross : ∀ j, 10≤(R/200)*H.radius j) +variable (hrec : (BData.ordered D).Recorded H (by norm_num [R]) (by norm_num [R])) + +noncomputable def incrementField (e : Bool) : M.Field D.band 5 := + (BData.ordered D).auxiliaryField + ((BData.ordered D).incrementAuxiliary H 1 region e (by norm_num [R]) + (by norm_num [R]) (by norm_num) (by simpa using hcross)) + SecondaryGeometry.Group.lam SecondaryGeometry.Group.lam_bound + +include hrec in +lemma incrementField_eq (e : Bool) {root : Fin (k+1)} (x : M.Point D.band root) + (hx : ∀ z, dist (A.point x.column x.height) z≤1 → z ∈ region) + (hl : R/100≤|(D.base.transverse (by norm_num) D.lower D.upper).eval x|) + (hu : |(D.base.transverse (by norm_num) D.lower D.upper).eval x|≤8) : + (D.incrementField H region hcross e).eval x = + D.value SecondaryGeometry.Group.lam x.column ⟨x.height,x.inBand⟩+ + (SecondaryGeometry.Group.lam:ℝ)* + (if e then (D.base.transverse (by norm_num) D.lower D.upper).eval x + else -(D.base.transverse (by norm_num) D.lower D.upper).eval x) := by + have hd := BData.increment_difference D H 1 region e (by norm_num [R]) + (by norm_num [R]) (by norm_num) (by simpa using hcross) hrec + SecondaryGeometry.Group.lam SecondaryGeometry.Group.lam_bound + x.column ⟨x.height,x.inBand⟩ + have ht := A.taper_of_ball (A.point x.column x.height) hx + have hs := Increment.scalar_plateau (a := R/200*1) (r := 1) + (t := (D.base.transverse (by norm_num) D.lower D.upper).eval x) + (by norm_num [R]) (by linarith) (by simpa using hu) + change (D.incrementField H region hcross e).eval x- + D.value SecondaryGeometry.Group.lam x.column ⟨x.height,x.inBand⟩ = _ at hd + simp only [Increment.signedDamped,Increment.damped,Field.eval] at hd hs ⊢ + rw [hs,ht,mul_one] at hd + linarith + +include hrec in +/-- Genuine append-only histories have a favorable fair sign. The old field +may be arbitrary and is not discarded in this difference calculation. -/ +lemma exists_increment_gain {root : Fin (k+1)} (x y : M.Point D.band root) + (hx : ∀ z, dist (A.point x.column x.height) z≤1 → z ∈ region) + (hy : ∀ z, dist (A.point y.column y.height) z≤1 → z ∈ region) + (ho : (D.base.transverse (by norm_num) D.lower D.upper).eval x * + (D.base.transverse (by norm_num) D.lower D.upper).eval y<0) + (hlx : R/100≤|(D.base.transverse (by norm_num) D.lower D.upper).eval x|) + (hly : R/100≤|(D.base.transverse (by norm_num) D.lower D.upper).eval y|) + (hux : |(D.base.transverse (by norm_num) D.lower D.upper).eval x|≤8) + (huy : |(D.base.transverse (by norm_num) D.lower D.upper).eval y|≤8) : + ∃ e : Bool, lambda*R/50 ≤ + |(D.incrementField H region hcross e).eval x-(D.incrementField H region hcross e).eval y| := by + let tx := (D.base.transverse (by norm_num) D.lower D.upper).eval x + let ty := (D.base.transverse (by norm_num) D.lower D.upper).eval y + let p := D.value SecondaryGeometry.Group.lam x.column ⟨x.height,x.inBand⟩- + D.value SecondaryGeometry.Group.lam y.column ⟨y.height,y.inBand⟩ + have hb : R/50≤|tx-ty| := by + rw [← Field.abs_add_eq_abs_sub_of_opposite ho] + linarith + have hgain : lambda*R/50≤|(SecondaryGeometry.Group.lam:ℝ)*(tx-ty)| := by + rw [abs_mul,abs_of_nonneg (NNReal.coe_nonneg _)] + change lambda*R/50≤lambda*|tx-ty| + have h := mul_le_mul_of_nonneg_left hb (by norm_num [lambda,R] : 0≤lambda) + linarith + rcases Increment.opposite_sign_gain p ((SecondaryGeometry.Group.lam:ℝ)*(tx-ty)) with h | h + · refine ⟨true,?_⟩ + rw [D.incrementField_eq H region hcross hrec true x hx hlx hux, + D.incrementField_eq H region hcross hrec true y hy hly huy] + simp only [ite_true] + convert hgain.trans h using 1 + try dsimp only [p,tx,ty] + try congr 1 + ring + · refine ⟨false,?_⟩ + rw [D.incrementField_eq H region hcross hrec false x hx hlx hux, + D.incrementField_eq H region hcross hrec false y hy hly huy] + simp only [Bool.false_eq_true,ite_false] + convert hgain.trans h using 1 + try dsimp only [p,tx,ty] + try congr 1 + ring + +end OrderedData +end PlanarL1.Columns.Model + +end + + + +section + +namespace PlanarL1.Columns.Model +open MeasureTheory Parameters +open scoped NNReal +attribute [local instance] Classical.propDecidable +variable {k : ℕ} {M : Model (k+1)} {Ω : Type*} [MeasurableSpace Ω] {μ : Measure Ω} + +namespace SetSystem +noncomputable def separation (S : SetSystem M Ω μ) (i : Fin (k+1)) (H : ℝ) + (j : Fin (k+1)) (T : ℝ) : ℝ := + ∫ ω, |(S.activity ω).indicator i H-(S.activity ω).indicator j T| ∂μ +lemma separation_nonneg (S : SetSystem M Ω μ) (i j : Fin (k+1)) (H T : ℝ) : + 0≤S.separation i H j T := integral_nonneg (fun _ => abs_nonneg _) +end SetSystem + +namespace BState +variable {κ : ℝ} {lam : ℝ≥0} (S : BState M κ lam Ω μ) + +lemma common_separation (i j : Fin (k+1)) (H T : ℝ) (a : Fin (S.count+1)) + (hi : S.name i H=a) (hj : S.name j T=a) : + S.sets.separation i H j T=max |H-T| |S.oldValue i H-S.oldValue j T| := by + unfold SetSystem.separation + simp_rw [S.old_indicator,hi,hj] + exact (S.labels a).distance _ _ _ _ + +lemma common_separation_height (i j : Fin (k+1)) (H T : ℝ) (a : Fin (S.count+1)) + (hi : S.name i H=a) (hj : S.name j T=a) : + |H-T|≤S.sets.separation i H j T := by + rw [S.common_separation i j H T a hi hj] + exact le_max_left _ _ + +lemma common_separation_field (i j : Fin (k+1)) (H T : ℝ) (a : Fin (S.count+1)) + (hi : S.name i H=a) (hj : S.name j T=a) (hκ : 0≤κ) + (hH : H ∈ (S.chart a).band) (hT : T ∈ (S.chart a).band) : + κ*|(S.chart a).value lam i ⟨H,hH⟩-(S.chart a).value lam j ⟨T,hT⟩|≤ + S.sets.separation i H j T := by + rw [S.common_separation i j H T a hi hj,S.oldValue_eq i H a hi,S.oldValue_eq j T a hj, + ←mul_sub,abs_mul,abs_of_nonneg hκ] + exact le_max_right _ _ + +lemma fieldUpdate_separation (F : ∀ a, M.Field (S.chart a).band 5) + (hk : 0≤κ) (hsmall : κ*5≤1/2) (hlam : lam≤(1:ℝ≥0)/100) + (hd : ∀ i H T, S.name i H≠S.name i T → |S.newValue F i H-S.oldValue i H|≤|H-T|/8) + (i j : Fin (k+1)) (H T : ℝ) (a : Fin (S.count+1)) + (hi : S.name i H=a) (hj : S.name j T=a) : + (S.fieldUpdate F hk hsmall hlam hd).separation i H j T= + max |H-T| |S.newValue F i H-S.newValue F j T| := by + unfold SetSystem.separation + change (∫ ω, |(S.fieldActivity F hk hsmall hlam hd ω).indicator i H- + (S.fieldActivity F hk hsmall hlam hd ω).indicator j T| ∂μ)=_ + simp_rw [S.field_indicator,hi,hj] + exact (S.labels a).distance _ _ _ _ +end BState + +namespace OrdinaryState +variable {κ : ℝ} (S : OrdinaryState M κ Ω μ) +lemma common_separation (i j : Fin (k+1)) (H T : ℝ) (a : Fin (S.count+1)) + (hi : S.name i H=a) (hj : S.name j T=a) (hκ : 0≤κ) + (hH : H ∈ (S.chart a).band) (hT : T ∈ (S.chart a).band) : + S.sets.separation i H j T=max |H-T| + (κ*|(S.chart a).comparison.value i ⟨H,hH⟩-(S.chart a).comparison.value j ⟨T,hT⟩|) := by + have h := (BState.ofOrdinary (lam := (0:ℝ≥0)) S).common_separation i j H T a hi hj + rw [BState.oldValue_eq _ i H a hi,BState.oldValue_eq _ j T a hj] at h + change S.sets.separation i H j T=max |H-T| + |κ*((S.chart a).constant+(S.chart a).orientation*(S.chart a).comparison.value i ⟨H,hH⟩)- + κ*((S.chart a).constant+(S.chart a).orientation*(S.chart a).comparison.value j ⟨T,hT⟩)| at h + rw [h] + congr 1 + rw [show κ*((S.chart a).constant+(S.chart a).orientation*(S.chart a).comparison.value i ⟨H,hH⟩)- + κ*((S.chart a).constant+(S.chart a).orientation*(S.chart a).comparison.value j ⟨T,hT⟩)= + κ*(S.chart a).orientation*((S.chart a).comparison.value i ⟨H,hH⟩- + (S.chart a).comparison.value j ⟨T,hT⟩) by ring, + abs_mul,abs_mul,abs_of_nonneg hκ,(S.chart a).unit_orientation,mul_one] +end OrdinaryState +end PlanarL1.Columns.Model + +end + + + +section + +namespace PlanarL1.Columns.Model.VertexTests +open MeasureTheory Parameters +open scoped NNReal +attribute [local instance] Classical.propDecidable +variable {k : ℕ} {M : Model (k+1)} {Ω Ξ V : Type*} +variable [MeasurableSpace Ω] [MeasurableSpace Ξ] {μ : Measure Ω} {ν : Measure Ξ} +variable (A : Ambient M) (SA : OrdinaryState M kappaA Ω μ) +variable (SB : BState M kappaB SecondaryGeometry.Group.lam Ξ ν) +variable (v : V → M.Point Set.univ A.root) + +noncomputable def indexA (x : V) := SA.name (v x).column (v x).height +noncomputable def indexB (x : V) := SB.name (v x).column (v x).height +noncomputable def ordinaryValue (x : V) : ℝ := + (SA.chart (indexA A SA v x)).comparison.value (v x).column ⟨(v x).height,SA.height_in _ _⟩ +noncomputable def fullValue (x : V) : ℝ := + (SB.chart (indexB A SB v x)).value SecondaryGeometry.Group.lam (v x).column + ⟨(v x).height,SB.height_in _ _⟩ + +private lemma ordinary_value_transport {D E : OrdinaryData M} (he : D=E) + (i : Fin (k+1)) (H : ℝ) (hD : H ∈ D.band) (hE : H ∈ E.band) : + D.comparison.value i ⟨H,hD⟩=E.comparison.value i ⟨H,hE⟩ := by subst E; rfl +private lemma full_value_transport {D E : BData M} (he : D=E) + (i : Fin (k+1)) (H : ℝ) (hD : H ∈ D.band) (hE : H ∈ E.band) : + D.value SecondaryGeometry.Group.lam i ⟨H,hD⟩= + E.value SecondaryGeometry.Group.lam i ⟨H,hE⟩ := by subst E; rfl + +/-- The actual eligibility test in : both unrestricted closed +radius-five balls, with one common identifier in each of the two systems. -/ +def Eligible (x y : V) : Prop := + A.Common SA.name (v x) 5 (indexA A SA v x) ∧ + A.Common SA.name (v y) 5 (indexA A SA v x) ∧ + A.Common SB.name (v x) 5 (indexB A SB v x) ∧ + A.Common SB.name (v y) 5 (indexB A SB v x) + +def PairTest (p : V×V) : Prop := + 1≤dist (v p.1) (v p.2) ∧ dist (v p.1) (v p.2)<2 ∧ Eligible A SA SB v p.1 p.2 + +def Cutoffs (x y : V) : Prop := + |(v x).height-(v y).height| ⟨k,hk.trans hm⟩ + +lemma NearBoundary.perturb {a q h x t : ℝ} (hn : NearBoundary a q x t) : + NearBoundary a q h (t+|x-h|) := by + obtain ⟨k,hk⟩ := hn + refine ⟨k,?_⟩ + have ht := abs_sub_le h x (q+k*a) + rw [abs_sub_comm h x] at ht + linarith + +lemma padded_of_avoid {a q h t : ℝ} (ha : 0 hn (hh.mono (by linarith))), + padded_of_avoid ha (fun hh => hn (hh.perturb.mono (by linarith)))⟩ + +lemma band_subset_of_padding {a b q p h t : ℝ} (_ha : 0 P ω ∨ Q ω)≤prob P+prob Q := by + classical + have h := prob_union_bound (Finset.univ : Finset Bool) (fun b => if b then P else Q) + simpa only [Finset.mem_univ,true_and,Bool.exists_bool,Bool.false_eq_true,ite_false,ite_true, + Fintype.sum_bool,or_comm] using h + +lemma prob_compl {Ω : Type*} [Fintype Ω] [Nonempty Ω] (P : Ω → Prop) : + prob (fun ω => ¬P ω)=1-prob P := by + rw [←Execution.prob_uniform,←Execution.prob_uniform] + exact Execution.prob_compl _ _ + +lemma prob_eval_bound {I Ω : Type*} [Fintype I] [DecidableEq I] [Fintype Ω] [Nonempty Ω] + (i : I) (P : Ω → Prop) {b : ℝ} (h : prob P≤b) : + prob (fun ω : I → Ω => P (ω i))≤b := by + classical + apply prob_update_bound i + intro α + simpa only [Function.update_self] using h + +end PlanarL1.FiniteRandom + +namespace PlanarL1.Tiling +open Parameters FiniteRandom + +/-- The two endpoint height tests use one shift, so their failures are bounded +by an enlarged interval, not by a union bound over the vertices or columns. -/ +lemma height_pair_probability (m : ℕ) (hm : 10000 ≤ m) {a h x : ℝ} (ha : 0 ¬(Padded a (a/m*i.val) h (a/10) ∧ + Padded a (a/m*i.val) x (a/10)))≤21/100 := by + classical + have hm0 : 0 < m := by omega + have hbad : prob (fun i : Fin (m+1) => ¬(Padded a (a/m*i.val) h (a/10) ∧ + Padded a (a/m*i.val) x (a/10))) ≤ + prob (fun i : Fin (m+1) => NearBoundary a (a/m*i.val) h (a/10+a₂/10000)) := by + apply prob_mono + intro i hi + by_contra hh + exact hi (padded_pair ha hd hh) + have hp := periodic_probability m hm0 ha (show 0≤a/10+a₂/10000 by have hb := interpolationB.2.1; positivity) h + apply hbad.trans (hp.trans _) + have hmR : (10000:ℝ) ≤ m := by exact_mod_cast hm + have hmesh : a/m≤a/10000 := div_le_div_of_nonneg_left ha.le (by norm_num) hmR + apply (div_le_iff₀ ha).mpr + rw [mul_div_assoc] + linarith + +lemma narrow_contained {q p h : ℝ} (hp : Padded a₁ q h (a₁/10)) : + band a₂ p (index a₂ p h) ⊆ band a₁ q (index a₁ q h) := + band_subset_of_padding interpolationA.2.1 interpolationB.2.1 hp (by norm_num [a₁,a₂]) + +end PlanarL1.Tiling + +end + + +section + +namespace PlanarL1.Tiling +lemma unique_band_of_padded {a q h t : ℝ} (ha : 0 exteriorToDisk (p t)) := by + apply Continuous.star + exact p.continuous.inv₀ (fun t => by + intro h + have := hp t + norm_num [h] at this) + +/-- The corresponding crossing theorem in the exterior of the unit disk. +Inversion fixes every endpoint and is injective; no simplicity assumption +on the two paths is needed. -/ +lemma exterior_cyclic_arcs_meet (a₀ a₁ a₂ a₃ : ℝ) + (h₀₁ : a₀ < a₁) (h₁₂ : a₁ < a₂) (h₂₃ : a₂ < a₃) + (hspan : a₃ < a₀ + 2 * π) + (f : Path (Circle.exp a₀ : ℂ) (Circle.exp a₂ : ℂ)) + (g : Path (Circle.exp a₁ : ℂ) (Circle.exp a₃ : ℂ)) + (hf : ∀ s, 1 ≤ ‖f s‖) (hg : ∀ s, 1 ≤ ‖g s‖) : + ∃ s t, f s = g t := by + let F : Path (Circle.exp a₀ : ℂ) (Circle.exp a₂ : ℂ) := + ⟨⟨fun s => exteriorToDisk (f s), exteriorToDisk_continuous_path f hf⟩, + by change exteriorToDisk (f 0) = _; rw [f.source, exteriorToDisk_circle], by change exteriorToDisk (f 1) = _; rw [f.target, exteriorToDisk_circle]⟩ + let G : Path (Circle.exp a₁ : ℂ) (Circle.exp a₃ : ℂ) := + ⟨⟨fun s => exteriorToDisk (g s), exteriorToDisk_continuous_path g hg⟩, + by change exteriorToDisk (g 0) = _; rw [g.source, exteriorToDisk_circle], by change exteriorToDisk (g 1) = _; rw [g.target, exteriorToDisk_circle]⟩ + obtain ⟨s,t,h⟩ := disk_cyclic_arcs_meet a₀ a₁ a₂ a₃ h₀₁ h₁₂ h₂₃ hspan F G + (fun s => exteriorToDisk_norm (hf s)) (fun t => exteriorToDisk_norm (hg t)) + exact ⟨s,t,exteriorToDisk_injective h⟩ + + +/-- Mutually disjoint exterior paths imply the literal noncrossing relation +on the finite cyclic list of their boundary ports. -/ +lemma noncrossing_of_exterior_arcs {n : ℕ} (G : SimpleGraph (Fin n)) + (angle : Fin n → ℝ) (horder : StrictMono angle) + (hspan : ∀ i j, angle j - angle i < 2 * π) + (arc : ∀ i j, G.Adj i j → Path (Circle.exp (angle i) : ℂ) + (Circle.exp (angle j) : ℂ)) + (hout : ∀ i j h t, 1 ≤ ‖arc i j h t‖) + (hdisjoint : ∀ i j h k l h', i ≠ k → i ≠ l → j ≠ k → j ≠ l → + Disjoint (range (arc i j h)) (range (arc k l h'))) : + PlanarL1.ColumnOrder.Noncrossing G := by + intro a b c d hab hbc hcd h + obtain ⟨s,t,hst⟩ := exterior_cyclic_arcs_meet + (angle a) (angle b) (angle c) (angle d) + (horder hab) (horder hbc) (horder hcd) (by linarith [hspan a d]) + (arc a c h.1) (arc b d h.2) (hout a c h.1) (hout b d h.2) + have hd := hdisjoint a c h.1 b d h.2 (ne_of_lt hab) + (ne_of_lt (hab.trans (hbc.trans hcd))) (ne_of_gt hbc) (ne_of_lt hcd) + exact Set.disjoint_left.mp hd (Set.mem_range_self s) (hst ▸ Set.mem_range_self t) + +lemma circle_exp_arg {z : ℂ} (hz : ‖z‖ = 1) : (Circle.exp (Complex.arg z) : ℂ) = z := by + simpa only [Circle.coe_exp, hz, Complex.ofReal_one, one_mul] + using Complex.norm_mul_exp_arg_mul_I z + +/-- A finite collection of distinct boundary ports supplies a cyclic list; +angles in a single half-open turn handle the wrap-around without choosing a +port as a special zero-angle endpoint. -/ +lemma finite_port_order {V : Type} [Fintype V] (port : V → ℂ) + (hnorm : ∀ v, ‖port v‖ = 1) (hinj : Function.Injective port) : + ∃ e : Fin (Fintype.card V) ≃ V, + StrictMono (fun i => Complex.arg (port (e i))) ∧ + (∀ i j, Complex.arg (port (e j)) - Complex.arg (port (e i)) < 2 * π) := by + classical + have ha : Function.Injective (fun v => Complex.arg (port v)) := by + intro a b hab + apply hinj + exact (circle_exp_arg (hnorm a)).symm.trans + ((congrArg (fun t => (Circle.exp t : ℂ)) hab).trans (circle_exp_arg (hnorm b))) + let : LinearOrder V := LinearOrder.lift' (fun v => Complex.arg (port v)) ha + let e := monoEquivOfFin V rfl + refine ⟨e.toEquiv, ?_, ?_⟩ + · exact e.strictMono + · intro i j + change Complex.arg (port (e j)) - Complex.arg (port (e i)) < 2 * π + linarith [Complex.arg_le_pi (port (e j)), Complex.neg_pi_lt_arg (port (e i))] + +/-- Any bounded convex neighborhood has an ambient disk coordinate in which +points outside its interior remain outside the open disk. -/ +lemma convex_disk_coordinates {S : Set ℂ} (hS : Convex ℝ S) + (hne : (interior S).Nonempty) (hb : Bornology.IsBounded S) : + ∃ h : ℂ ≃ₜ ℂ, + (∀ z, z ∈ frontier S → ‖h z‖ = 1) ∧ + (∀ z, z ∉ interior S → 1 ≤ ‖h z‖) := by + obtain ⟨h,hi,_,hf⟩ := exists_homeomorph_image_interior_closure_frontier_eq_unitBall hS hne hb + refine ⟨h, ?_, ?_⟩ + · intro z hz + have hm : h z ∈ Metric.sphere (0:ℂ) 1 := hf ▸ mem_image_of_mem h hz + simpa [Metric.mem_sphere, dist_zero_right] using hm + · intro z hz + by_contra! hn + have hm : h z ∈ Metric.ball (0:ℂ) 1 := by simpa [Metric.mem_ball, dist_zero_right] + rw [← hi] at hm + obtain ⟨w,hw,he⟩ := hm + exact hz (h.injective he ▸ hw) + + +/-- Complementary arcs outside an actual convex tree-merging neighborhood +produce a noncrossing cyclic order of its distinct leaf ports. All hypotheses +here concern the geometric sets and paths, not a promised column model. -/ +lemma convex_ports_noncrossing {V : Type} [Fintype V] (G : SimpleGraph V) + {S : Set ℂ} (hS : Convex ℝ S) (hne : (interior S).Nonempty) + (hb : Bornology.IsBounded S) (port : V → ℂ) + (hport : ∀ v, port v ∈ frontier S) (hinj : Function.Injective port) + (arc : ∀ i j, G.Adj i j → Path (port i) (port j)) + (hout : ∀ i j h t, arc i j h t ∉ interior S) + (hdisjoint : ∀ i j h k l h', i ≠ k → i ≠ l → j ≠ k → j ≠ l → + Disjoint (range (arc i j h)) (range (arc k l h'))) : + ∃ e : Fin (Fintype.card V) ≃ V, + PlanarL1.ColumnOrder.Noncrossing (SimpleGraph.comap e G) := by + obtain ⟨h,hf,ho⟩ := convex_disk_coordinates hS hne hb + have hn (v : V) : ‖h (port v)‖ = 1 := hf _ (hport v) + obtain ⟨e,he,hspan⟩ := finite_port_order (fun v => h (port v)) hn (h.injective.comp hinj) + let angle (i : Fin (Fintype.card V)) := Complex.arg (h (port (e i))) + let A : ∀ i j, (SimpleGraph.comap e G).Adj i j → + Path (Circle.exp (angle i) : ℂ) (Circle.exp (angle j) : ℂ) := + fun i j hij => ((arc (e i) (e j) hij).map h.continuous).cast + (circle_exp_arg (hn (e i))) (circle_exp_arg (hn (e j))) + refine ⟨e, noncrossing_of_exterior_arcs _ angle he hspan A ?_ ?_⟩ + · intro i j hij t + exact ho _ (hout (e i) (e j) hij t) + · intro i j hij k l hkl hik hil hjk hjl + rw [Set.disjoint_left] + rintro z ⟨s,hs⟩ ⟨t,ht⟩ + have hh : h (arc (e i) (e j) hij s) = h (arc (e k) (e l) hkl t) := hs.trans ht.symm + have hd := hdisjoint (e i) (e j) hij (e k) (e l) hkl + (e.injective.ne hik) (e.injective.ne hil) (e.injective.ne hjk) (e.injective.ne hjl) + exact Set.disjoint_left.mp hd (Set.mem_range_self s) + ((h.injective hh) ▸ Set.mem_range_self t) + +end PlanarL1.Topology + + + + +namespace PlanarL1.Columns +attribute [local instance] Classical.propDecidable + +/-- An interval of selected consecutive indices is connected without using the +wrap-around edge. -/ +lemma interval_reachable {n : ℕ} (G : SimpleGraph (Fin n)) (S : Set (Fin n)) + (he : ∀ i j, i.val+1=j.val → i∈S → j∈S → G.Adj i j) + {i j : Fin n} (hij : i≤j) (hS : ∀ k, i≤k → k≤j → k∈S) : + G.Reachable i j := by + have go (m : ℕ) : ∀ j : Fin n, j.val-i.val=m → i≤j → + (∀ k, i≤k → k≤j → k∈S) → G.Reachable i j := by + induction m with + | zero => + intro j hm hij _ + have : i=j := Fin.ext (by omega) + subst j + exact .rfl + | succ m ih => + intro j hm hij hS + have hj : 0 hS a ha (hb.trans hkj))).trans + ((he k j (by dsimp [k]; omega) (hS k hik hkj) (hS j hij le_rfl)).reachable) + exact go _ j rfl hij hS + +/-- The elementary circular-interval criterion: if a set and its complement +have no alternating four indices, consecutive selected indices connect it. -/ +lemma consecutive_connected {n : ℕ} (G : SimpleGraph (Fin n)) (S : Set (Fin n)) + (he : ∀ i j, i≠j → Consecutive i j → i∈S → j∈S → G.Adj i j) + (halt : ∀ a b c d : Fin n, a by subst b; omega) (Or.inl hab) ha hb + suffices h : ∀ a b : Fin n, a≤b → a∈S → b∈S → G.Reachable a b by + rcases le_total i j with hij | hji + · exact h i j hij hi hj + · exact (h j i hji hj hi).symm + intro a b hab ha hb + by_cases hwhole : ∀ k, a≤k → k≤b → k∈S + · exact interval_reachable G S edge hab hwhole + push Not at hwhole + obtain ⟨k,hak,hkb,hk⟩ := hwhole + have hak' : a hk (h ▸ ha)) + have hkb' : k hk (h.symm ▸ hb)) + have hlow (t : Fin n) (ht : t≤a) : t∈S := by + by_contra hn + have hta : t hn (h.symm ▸ ha)) + exact halt t a k b hta hak' hkb' (Or.inr ⟨hn,ha,hk,hb⟩) + have hhigh (t : Fin n) (ht : b≤t) : t∈S := by + by_contra hn + have hbt : b hn (h ▸ hb)) + exact halt a k b t hak' hkb' hbt (Or.inl ⟨ha,hk,hb,hn⟩) + let first : Fin n := ⟨0,by have := a.isLt; omega⟩ + let last : Fin n := ⟨n-1,by have := a.isLt; omega⟩ + have hfa : first≤a := by change 0≤a.val; omega + have hbl : b≤last := by change b.val≤n-1; omega + have hleft := interval_reachable G S edge hfa (fun t _ ht => hlow t ht) + have hright := interval_reachable G S edge hbl (fun t ht _ => hhigh t ht) + have hwrap : G.Reachable first last := by + by_cases hfl : first=last + · rw [hfl] + · apply SimpleGraph.Adj.reachable + apply he first last hfl + · exact Or.inr (Or.inr (Or.inl ⟨rfl,by dsimp [last]; omega⟩)) + · exact hlow first hfa + · exact hhigh last hbl + exact (hleft.symm.trans hwrap).trans hright.symm + +end PlanarL1.Columns + +namespace PlanarL1.Topology.Drawing +open Set +variable {V : Type} {G : SimpleGraph V} (D : Drawing G) + +def carrier (S : Set V) : Set ℂ := + {z | (∃ v∈S, z=D.point v) ∨ + (∃ u∈S, ∃ v∈S, ∃ h : G.Adj u v, z∈range (D.edge u v h))} + +lemma point_mem_carrier {S : Set V} {v : V} (hv : v∈S) : + D.point v ∈ D.carrier S := Or.inl ⟨v,hv,rfl⟩ + +lemma edge_mem_carrier {S : Set V} {u v : V} (h : G.Adj u v) + (hu : u∈S) (hv : v∈S) (t : unitInterval) : D.edge u v h t∈D.carrier S := + Or.inr ⟨u,hu,v,hv,h,mem_range_self t⟩ + +lemma carrier_disjoint {S T : Set V} (hst : Disjoint S T) : + Disjoint (D.carrier S) (D.carrier T) := by + have sep : ∀ u∈S, ∀ v∈T, u≠v := by + intro u hu v hv he + exact disjoint_left.mp hst hu (he ▸ hv) + have point_edge : ∀ u∈S, ∀ v∈T, ∀ w∈T, ∀ h : G.Adj v w, + ∀ t, D.point u≠D.edge v w h t := by + intro u hu v hv w hw h t he + rcases (D.point_on_edge_iff v w h u t).mp he.symm with ⟨_,he⟩ | ⟨_,he⟩ + · exact sep u hu v hv he + · exact sep u hu w hw he + rw [disjoint_left] + rintro z (⟨u,hu,rfl⟩ | ⟨u,hu,v,hv,h,s,rfl⟩) + (⟨w,hw,he⟩ | ⟨w,hw,x,hx,k,t,ht⟩) + · exact sep u hu w hw (D.point_injective he) + · exact point_edge u hu w hw x hx k t ht.symm + · rcases (D.point_on_edge_iff u v h w s).mp he with ⟨_,he⟩ | ⟨_,he⟩ + · exact sep u hu w hw he.symm + · exact sep v hv w hw he.symm + · by_cases hs0 : s=0 + · subst s + rw [Path.source] at ht + exact point_edge u hu w hw x hx k t ht.symm + by_cases hs1 : s=1 + · subst s + rw [Path.target] at ht + exact point_edge v hv w hw x hx k t ht.symm + by_cases ht0 : t=0 + · subst t + rw [Path.source] at ht + rcases (D.point_on_edge_iff u v h w s).mp ht.symm with ⟨he,_⟩ | ⟨he,_⟩ + · exact hs0 he + · exact hs1 he + by_cases ht1 : t=1 + · subst t + rw [Path.target] at ht + rcases (D.point_on_edge_iff u v h x s).mp ht.symm with ⟨he,_⟩ | ⟨he,_⟩ + · exact hs0 he + · exact hs1 he + have interior (r : unitInterval) (h0 : r≠0) (h1 : r≠1) : 0<(r:ℝ) ∧ (r:ℝ)<1 := + ⟨lt_of_le_of_ne r.2.1 (fun h => h0 (Subtype.ext h.symm)), + lt_of_le_of_ne r.2.2 (fun h => h1 (Subtype.ext h))⟩ + rcases D.interior_disjoint u v h w x k s t (interior s hs0 hs1).1 + (interior s hs0 hs1).2 (interior t ht0 ht1).1 (interior t ht0 ht1).2 ht.symm + with ⟨he,_⟩ | ⟨he,_⟩ + · exact sep u hu w hw he + · exact sep u hu x hx he + +end PlanarL1.Topology.Drawing + +namespace PlanarL1.HeightTree +open Set +attribute [local instance] Classical.propDecidable +variable {V : Type} (T : HeightTree V) + +def graph : SimpleGraph V where + Adj u v := T.Step u v ∨ T.Step v u + symm := ⟨fun _ _ => Or.symm⟩ + loopless := ⟨by + intro v h + rcases h with h | h <;> exact (lt_irrefl (T.depth v)) (T.step_depth h)⟩ + +lemma ancestor_path (D : Topology.Drawing T.graph) {u v : V} (h : T.Ancestor u v) + {S : Set V} (hS : ∀ w, T.Ancestor u w → T.Ancestor w v → w∈S) : + ∃ p : Path (D.point u) (D.point v), range p ⊆ D.carrier S := by + induction h with + | refl => + refine ⟨Path.refl _,?_⟩ + rintro z ⟨t,rfl⟩ + exact D.point_mem_carrier (hS _ .refl .refl) + | @tail v w huv hvw ih => + obtain ⟨p,hp⟩ := ih (fun a ha hb => hS a ha (hb.tail hvw)) + let q := D.edge v w (Or.inl hvw) + refine ⟨p.trans q,?_⟩ + rw [Path.trans_range] + apply union_subset hp + rintro z ⟨t,rfl⟩ + exact D.edge_mem_carrier _ (hS v huv (.single hvw)) + (hS w (huv.tail hvw) .refl) t + +lemma descendants_joined (D : Topology.Drawing T.graph) (a : V) {u v : V} + (hu : T.Ancestor a u) (hv : T.Ancestor a v) : + ∃ p : Path (D.point u) (D.point v), range p ⊆ D.carrier {w | T.Ancestor a w} := by + obtain ⟨p,hp⟩ := T.ancestor_path D hu (fun _ h _ => h) + obtain ⟨q,hq⟩ := T.ancestor_path D hv (fun _ h _ => h) + exact ⟨p.symm.trans q,by + rw [Path.trans_range,Path.symm_range] + intro z hz + exact hz.elim (fun h => hp h) (fun h => hq h)⟩ + +lemma nondescendants_joined (D : Topology.Drawing T.graph) (a : V) {u v : V} + (hu : ¬T.Ancestor a u) (hv : ¬T.Ancestor a v) : + ∃ p : Path (D.point u) (D.point v), range p ⊆ D.carrier {w | ¬T.Ancestor a w} := by + obtain ⟨p,hp⟩ := T.ancestor_path D (T.root_ancestor u) + (S := {w | ¬T.Ancestor a w}) (fun _ _ h ha => hu (ha.trans h)) + obtain ⟨q,hq⟩ := T.ancestor_path D (T.root_ancestor v) + (S := {w | ¬T.Ancestor a w}) (fun _ _ h ha => hv (ha.trans h)) + exact ⟨p.symm.trans q,by + rw [Path.trans_range,Path.symm_range] + intro z hz + exact hz.elim (fun h => hp h) (fun h => hq h)⟩ + +end PlanarL1.HeightTree + +namespace PlanarL1.HeightTree +open Set Real +attribute [local instance] Classical.propDecidable +variable {V : Type} (T : HeightTree V) + +lemma disk_prefix_connected {n : ℕ} (D : Topology.Drawing T.graph) + (hpoint : ∀ v, ‖D.point v‖≤1) + (hedge : ∀ u v h t, ‖D.edge u v h t‖≤1) + (leaf : Fin n → V) (angle : Fin n → ℝ) + (hend : ∀ i, D.point (leaf i)=(Circle.exp (angle i) : ℂ)) + (horder : StrictMono angle) (hspan : ∀ i j, angle j-angle i<2*π) + (a : V) {i j : Fin n} (hi : T.Ancestor a (leaf i)) (hj : T.Ancestor a (leaf j)) : + (T.prefixGraph leaf a).Reachable i j := by + have hcarrier (S : Set V) : ∀ z∈D.carrier S, ‖z‖≤1 := by + rintro z (⟨v,_,rfl⟩ | ⟨u,_,v,_,h,t,rfl⟩) + · exact hpoint v + · exact hedge u v h t + apply Columns.consecutive_connected (T.prefixGraph leaf a) {k | T.Ancestor a (leaf k)} + (fun _ _ hne hc ha hb => ⟨hne,hc,ha,hb⟩) _ hi hj + intro w x y z hwx hxy hyz hbad + suffices impossible : ∀ (S U : Set V), Disjoint S U → + (∃ p : Path (D.point (leaf w)) (D.point (leaf y)), range p⊆D.carrier S) → + (∃ q : Path (D.point (leaf x)) (D.point (leaf z)), range q⊆D.carrier U) → False by + rcases hbad with ⟨hw,hx,hy,hz⟩ | ⟨hw,hx,hy,hz⟩ + · exact impossible {v | T.Ancestor a v} {v | ¬T.Ancestor a v} + (disjoint_compl_right) (T.descendants_joined D a hw hy) + (T.nondescendants_joined D a hx hz) + · exact impossible {v | ¬T.Ancestor a v} {v | T.Ancestor a v} + (disjoint_compl_left) (T.nondescendants_joined D a hw hy) + (T.descendants_joined D a hx hz) + intro S U hdis ⟨p,hp⟩ ⟨q,hq⟩ + let p' := p.cast (hend w).symm (hend y).symm + let q' := q.cast (hend x).symm (hend z).symm + obtain ⟨s,t,hst⟩ := Topology.disk_cyclic_arcs_meet (angle w) (angle x) (angle y) (angle z) + (horder hwx) (horder hxy) (horder hyz) (by linarith [hspan w z]) p' q' + (fun t => hcarrier S _ (hp (mem_range_self t))) + (fun t => hcarrier U _ (hq (mem_range_self t))) + exact disjoint_left.mp (D.carrier_disjoint hdis) (hp (mem_range_self s)) + (hst ▸ hq (mem_range_self t)) + +/-- The exact leaf layout follows from a geometric disk drawing and disjoint +complementary paths. This lemma does not assert the still-required disk surgery +on the supplied planar drawing. -/ +lemma layout_of_disk [Fintype V] (D : Topology.Drawing T.graph) + (hpoint : ∀ v, ‖D.point v‖≤1) + (hedge : ∀ u v h t, ‖D.edge u v h t‖≤1) + (hleaf : ∀ v, T.IsLeaf v → ‖D.point v‖=1) + (P : SimpleGraph {v : V // T.IsLeaf v}) + (hheight : ∀ i j, P.Adj i j → T.height i.val=T.height j.val) + (hmatch : ∀ i j k, P.Adj i j → P.Adj i k → j=k) + (arc : ∀ i j, P.Adj i j → Path (D.point i.val) (D.point j.val)) + (hout : ∀ i j h t, 1≤‖arc i j h t‖) + (hdis : ∀ i j h k l h', i≠k → i≠l → j≠k → j≠l → + Disjoint (range (arc i j h)) (range (arc k l h'))) : + ∃ (L : T.Layout (Fintype.card {v : V // T.IsLeaf v})), + ∀ i j, L.pair.Adj i j ↔ P.Adj ⟨L.leaf i,L.isLeaf i⟩ ⟨L.leaf j,L.isLeaf j⟩ := by + obtain ⟨e,he,hspan⟩ := Topology.finite_port_order (fun v : {v : V // T.IsLeaf v} => D.point v.val) + (fun v => hleaf v.val v.property) (D.point_injective.comp Subtype.val_injective) + let angle (i : Fin (Fintype.card {v : V // T.IsLeaf v})) := Complex.arg (D.point (e i).val) + have hend i : D.point (e i).val=(Circle.exp (angle i) : ℂ) := + (Topology.circle_exp_arg (hleaf _ (e i).property)).symm + let A : ∀ i j, (SimpleGraph.comap e P).Adj i j → + Path (Circle.exp (angle i) : ℂ) (Circle.exp (angle j) : ℂ) := + fun i j h => (arc (e i) (e j) h).cast (hend i).symm (hend j).symm + have hnc : ColumnOrder.Noncrossing (SimpleGraph.comap e P) := by + apply Topology.noncrossing_of_exterior_arcs _ angle he hspan A + · intro i j h t; exact hout (e i) (e j) h t + · intro i j h k l h' hik hil hjk hjl + exact hdis (e i) (e j) h (e k) (e l) h' + (e.injective.ne hik) (e.injective.ne hil) (e.injective.ne hjk) (e.injective.ne hjl) + let L : T.Layout (Fintype.card {v : V // T.IsLeaf v}) := { + leaf := fun i => (e i).val + isLeaf := fun i => (e i).property + injective := Subtype.val_injective.comp e.injective + covers := fun v hv => ⟨e.symm ⟨v,hv⟩,by simp⟩ + prefix_connected := fun a i j hi hj => + T.disk_prefix_connected D hpoint hedge _ angle hend he hspan a hi hj + pair := SimpleGraph.comap e P + noncrossing := hnc + paired_height := fun i j h => hheight (e i) (e j) h + matching := fun i j k hij hik => e.injective (hmatch (e i) (e j) (e k) hij hik) } + exact ⟨L,fun _ _ => Iff.rfl⟩ + +end PlanarL1.HeightTree + + + +end + +end OAI diff --git a/lean/OAI/Combinatorics/PlanarL1/WeightedMetric.lean b/lean/OAI/Combinatorics/PlanarL1/WeightedMetric.lean new file mode 100644 index 0000000000000000000000000000000000000000..1ea9521fd35fda39f368f2f7e6a91c47f507f66e --- /dev/null +++ b/lean/OAI/Combinatorics/PlanarL1/WeightedMetric.lean @@ -0,0 +1,612 @@ +import OAI.Combinatorics.PlanarL1.Statement + +namespace OAI + +section + +namespace PlanarL1.WeightedGraph +open SimpleGraph +variable {V : Type} {G : SimpleGraph V} {ℓ : V → V → ℝ} + +lemma length_nonneg (hℓ : ∀ u v, G.Adj u v → 0 ≤ ℓ u v) {u v : V} (p : G.Walk u v) : + 0 ≤ walkLength ℓ p := by + induction p with + | nil => rfl + | cons h p ih => exact add_nonneg (hℓ _ _ h) ih + +lemma length_pos (hℓ : ∀ u v, G.Adj u v → 0 < ℓ u v) {u v : V} (p : G.Walk u v) + (hne : u ≠ v) : 0 < walkLength ℓ p := by + cases p with + | nil => exact False.elim (hne rfl) + | cons h p => exact add_pos_of_pos_of_nonneg (hℓ _ _ h) (length_nonneg (fun i j h => (hℓ i j h).le) p) + +lemma length_append {u v w : V} (p : G.Walk u v) (q : G.Walk v w) : + walkLength ℓ (p.append q) = walkLength ℓ p+walkLength ℓ q := by + induction p with + | nil => simp [walkLength] + | cons h p ih => simp [walkLength,ih,add_assoc] + +lemma length_darts {u v : V} (p : G.Walk u v) : + walkLength ℓ p = (p.darts.map (fun d => ℓ d.fst d.snd)).sum := by + induction p with + | nil => rfl + | cons h p ih => simp [walkLength,Walk.darts_cons,ih] + +lemma length_reverse (hs : ∀ u v, ℓ u v = ℓ v u) {u v : V} (p : G.Walk u v) : + walkLength ℓ p.reverse = walkLength ℓ p := by + rw [length_darts,length_darts,Walk.darts_reverse,List.map_reverse,List.sum_reverse,List.map_map] + congr 1 + apply List.map_congr_left + intro d _ + exact hs _ _ + +lemma length_bypass_le [DecidableEq V] (hℓ : ∀ u v, G.Adj u v → 0 ≤ ℓ u v) + {u v : V} (p : G.Walk u v) : walkLength ℓ p.bypass ≤ walkLength ℓ p := by + rw [length_darts,length_darts] + apply (p.darts_bypass_sublist_darts.map _).sum_le_sum + intro a ha + obtain ⟨d,_,rfl⟩ := List.mem_map.mp ha + exact hℓ _ _ d.adj + +lemma distance_nonneg (hℓ : ∀ u v, G.Adj u v → 0 ≤ ℓ u v) (u v : V) : + 0 ≤ graphDistance G ℓ u v := by + apply Real.sInf_nonneg + rintro _ ⟨p,rfl⟩ + exact length_nonneg hℓ p + +lemma distance_le_length (hℓ : ∀ u v, G.Adj u v → 0 ≤ ℓ u v) + {u v : V} (p : G.Walk u v) : graphDistance G ℓ u v ≤ walkLength ℓ p := by + apply csInf_le + · exact ⟨0,by rintro _ ⟨q,rfl⟩; exact length_nonneg hℓ q⟩ + · exact ⟨p,rfl⟩ + +lemma distance_self (hℓ : ∀ u v, G.Adj u v → 0 ≤ ℓ u v) (u : V) : + graphDistance G ℓ u u = 0 := by + apply le_antisymm _ (distance_nonneg hℓ u u) + exact distance_le_length hℓ Walk.nil + +lemma distance_attained [Finite V] (hG : G.Connected) + (hℓ : ∀ u v, G.Adj u v → 0 ≤ ℓ u v) (u v : V) : + ∃ p : G.Walk u v, p.IsPath ∧ graphDistance G ℓ u v = walkLength ℓ p := by + classical + let : Fintype V := Fintype.ofFinite V + let q := (hG u v).some.toPath + obtain ⟨p,_,hp⟩ := Finset.exists_min_image (Finset.univ : Finset (G.Path u v)) + (fun p => walkLength ℓ p.val) ⟨q,Finset.mem_univ q⟩ + refine ⟨p.val,p.property,le_antisymm (distance_le_length hℓ p.val) ?_⟩ + unfold graphDistance + apply le_csInf (show (Set.range (fun r : G.Walk u v => walkLength ℓ r)).Nonempty from ⟨walkLength ℓ p.val,⟨p.val,rfl⟩⟩) + rintro _ ⟨r,rfl⟩ + exact (hp r.toPath (Finset.mem_univ _)).trans (length_bypass_le hℓ r) + +lemma distance_symm [Finite V] (hG : G.Connected) (hs : ∀ u v, ℓ u v = ℓ v u) + (hℓ : ∀ u v, G.Adj u v → 0 ≤ ℓ u v) (u v : V) : + graphDistance G ℓ u v = graphDistance G ℓ v u := by + suffices h : ∀ a b, graphDistance G ℓ a b ≤ graphDistance G ℓ b a from + le_antisymm (h u v) (h v u) + intro a b + obtain ⟨p,_,hp⟩ := distance_attained hG hℓ b a + rw [hp] + exact (distance_le_length hℓ p.reverse).trans_eq (length_reverse hs p) + +lemma distance_triangle [Finite V] (hG : G.Connected) + (hℓ : ∀ u v, G.Adj u v → 0 ≤ ℓ u v) (u v w : V) : + graphDistance G ℓ u w ≤ graphDistance G ℓ u v+graphDistance G ℓ v w := by + obtain ⟨p,_,hp⟩ := distance_attained hG hℓ u v + obtain ⟨q,_,hq⟩ := distance_attained hG hℓ v w + rw [hp,hq,← length_append] + exact distance_le_length hℓ (p.append q) + +lemma distance_pos [Finite V] (hG : G.Connected) + (hℓ : ∀ u v, G.Adj u v → 0 < ℓ u v) {u v : V} (hne : u ≠ v) : + 0 < graphDistance G ℓ u v := by + obtain ⟨p,_,hp⟩ := distance_attained hG (fun i j h => (hℓ i j h).le) u v + rw [hp] + exact length_pos hℓ p hne + +@[instance_reducible] +noncomputable def metricSpace [Finite V] (hG : G.Connected) + (hs : ∀ u v, ℓ u v = ℓ v u) (hℓ : ∀ u v, G.Adj u v → 0 < ℓ u v) : + MetricSpace V where + dist := graphDistance G ℓ + dist_self := distance_self (fun i j h => (hℓ i j h).le) + dist_comm := distance_symm hG hs (fun i j h => (hℓ i j h).le) + dist_triangle := distance_triangle hG (fun i j h => (hℓ i j h).le) + eq_of_dist_eq_zero := by + intro x y he + by_contra hne + exact ne_of_gt (distance_pos hG hℓ hne) he + +lemma edge_bound (hℓ : ∀ u v, G.Adj u v → 0 ≤ ℓ u v) {u v : V} (h : G.Adj u v) : + graphDistance G ℓ u v ≤ ℓ u v := by + simpa only [walkLength,add_zero] using distance_le_length hℓ (Walk.cons h Walk.nil) + +/-- The literal predecessor used in the realization proof can be chosen with +strictly decreasing weighted root distance; no unit-edge shortcut is used. -/ +lemma predecessor [Finite V] (hG : G.Connected) (hs : ∀ u v, ℓ u v = ℓ v u) + (hℓ : ∀ u v, G.Adj u v → 0 < ℓ u v) (o v : V) (hne : v ≠ o) : + ∃ u, G.Adj u v ∧ graphDistance G ℓ o u+ℓ u v = graphDistance G ℓ o v ∧ + graphDistance G ℓ o u < graphDistance G ℓ o v := by + have hn := fun i j h => (hℓ i j h).le + obtain ⟨p,_,hp⟩ := distance_attained hG hn v o + cases p with + | nil => exact False.elim (hne rfl) + | @cons _ u _ h p => + have hpr := distance_le_length hn p + have htri := distance_triangle hG hn v u o + have hed := edge_bound hn h + have he : graphDistance G ℓ v o = ℓ v u+graphDistance G ℓ u o := by + change graphDistance G ℓ v o = ℓ v u+walkLength ℓ p at hp + linarith + rw [distance_symm hG hs hn v o,distance_symm hG hs hn u o,hs v u] at he + refine ⟨u,h.symm,by linarith,?_⟩ + linarith [hℓ u v h.symm] + + +section ParentTree +variable (o : V) (f : V → V) (h : V → ℝ) + (hf : ∀ v, v ≠ o → h (f v) < h v) + +def parentGraph : SimpleGraph V where + Adj u v := (v ≠ o ∧ f v = u) ∨ (u ≠ o ∧ f u = v) + symm := ⟨by intro u v h; exact h.symm⟩ + loopless := ⟨by + intro v hv + rcases hv with ⟨hne,he⟩ | ⟨hne,he⟩ <;> + have hi := hf v hne <;> rw [he] at hi <;> exact hi.false⟩ + +lemma parent_adj {v : V} (hv : v ≠ o) : (parentGraph o f h hf).Adj (f v) v := + Or.inl ⟨hv,rfl⟩ + +lemma parent_connected [Finite V] : (parentGraph o f h hf).Connected := by + classical + let : Fintype V := Fintype.ofFinite V + apply (connected_iff_exists_forall_reachable _).mpr + refine ⟨o,?_⟩ + intro v + by_contra hv + let S := Finset.univ.filter (fun x => ¬ (parentGraph o f h hf).Reachable o x) + have hvS : v ∈ S := by simpa [S] using hv + obtain ⟨w,hw,hm⟩ := Finset.exists_min_image S h ⟨v,hvS⟩ + have hnw : ¬ (parentGraph o f h hf).Reachable o w := (Finset.mem_filter.mp hw).2 + have hwo : w ≠ o := by rintro rfl; exact hnw (.refl _) + have hnf : ¬ (parentGraph o f h hf).Reachable o (f w) := by + intro hr + exact hnw (hr.trans (parent_adj o f h hf hwo).reachable) + have hfw : f w ∈ S := by simpa [S] using hnf + exact (hf w hwo).not_ge (hm (f w) hfw) + +lemma parent_tree [Finite V] : (parentGraph o f h hf).IsTree := by + classical + let : Fintype V := Fintype.ofFinite V + let T := parentGraph o f h hf + have hT : T.Connected := parent_connected o f h hf + let edge : {v : V // v ≠ o} → T.edgeSet := + fun v => ⟨s(f v.val,v.val),parent_adj o f h hf v.property⟩ + have he : Function.Surjective edge := by + rintro ⟨e,he⟩ + induction e using Sym2.inductionOn with + | hf u v => + rcases he with ⟨hv,hf⟩ | ⟨hu,hf⟩ + · refine ⟨⟨v,hv⟩,?_⟩ + apply Subtype.ext + change s(f v,v) = s(u,v) + rw [hf] + · refine ⟨⟨u,hu⟩,?_⟩ + apply Subtype.ext + change s(f u,u) = s(u,v) + rw [hf,Sym2.eq_swap] + have hc := Fintype.card_le_of_surjective edge he + have hh : Fintype.card {v : V // v ≠ o} = Fintype.card V-1 := by + rw [Fintype.card_subtype_compl] + simp + rw [hh] at hc + have hpos : 0 < Fintype.card V := Fintype.card_pos_iff.mpr ⟨o⟩ + have hlo := hT.card_vert_le_card_edgeSet_add_one + rw [Nat.card_eq_fintype_card,Nat.card_eq_fintype_card] at hlo + apply (isTree_iff_connected_and_card).mpr + refine ⟨hT,?_⟩ + rw [Nat.card_eq_fintype_card,Nat.card_eq_fintype_card] + change Fintype.card T.edgeSet + 1 = Fintype.card V + omega + +lemma parent_walk [Finite V] {ℓ : V → V → ℝ} (ho : h o = 0) + (hstep : ∀ v, v ≠ o → h (f v)+ℓ (f v) v = h v) (v : V) : + ∃ p : (parentGraph o f h hf).Walk o v, walkLength ℓ p = h v := by + classical + let : Fintype V := Fintype.ofFinite V + by_contra hv + let good := fun w => ∃ p : (parentGraph o f h hf).Walk o w, walkLength ℓ p = h w + let S := Finset.univ.filter (fun x => ¬good x) + have hvS : v ∈ S := by simpa [S,good] using hv + obtain ⟨w,hw,hm⟩ := Finset.exists_min_image S h ⟨v,hvS⟩ + have hnw : ¬good w := (Finset.mem_filter.mp hw).2 + have hwo : w ≠ o := by + rintro rfl + exact hnw ⟨Walk.nil,ho.symm⟩ + have hfg : good (f w) := by + by_contra hnf + have hfw : f w ∈ S := by simpa [S] using hnf + exact (hf w hwo).not_ge (hm (f w) hfw) + obtain ⟨p,hp⟩ := hfg + apply hnw + refine ⟨p.append (Walk.cons (parent_adj o f h hf hwo) Walk.nil),?_⟩ + rw [length_append,hp] + simpa only [walkLength,add_zero] using hstep w hwo + +end ParentTree + +/-- The weighted shortest-path spanning tree claimed at . +Its tree edges retain their arbitrary original positive lengths. -/ +lemma shortest_path_tree [Finite V] (hG : G.Connected) + (hs : ∀ u v, ℓ u v = ℓ v u) + (hℓ : ∀ u v, G.Adj u v → 0 < ℓ u v) (o : V) : + ∃ T : SimpleGraph V, T ≤ G ∧ T.IsTree ∧ + (∀ v, ∃ p : T.Walk o v, walkLength ℓ p = graphDistance G ℓ o v) ∧ + (∀ u v, T.Adj u v → |graphDistance G ℓ o v-graphDistance G ℓ o u| = ℓ u v) := by + classical + let f : V → V := fun v => if hv : v = o then o else (predecessor hG hs hℓ o v hv).choose + have hpred (v : V) (hv : v ≠ o) : G.Adj (f v) v ∧ + graphDistance G ℓ o (f v)+ℓ (f v) v = graphDistance G ℓ o v ∧ + graphDistance G ℓ o (f v) < graphDistance G ℓ o v := by + simpa only [f,dite_eq_right hv] using (predecessor hG hs hℓ o v hv).choose_spec + let h := graphDistance G ℓ o + have hf : ∀ v, v ≠ o → h (f v) < h v := fun v hv => (hpred v hv).2.2 + let T := parentGraph o f h hf + have hsub : T ≤ G := by + intro u v huv + rcases huv with ⟨hv,rfl⟩ | ⟨hu,rfl⟩ + · exact (hpred v hv).1 + · exact (hpred u hu).1.symm + refine ⟨T,hsub,parent_tree o f h hf,?_,?_⟩ + · exact fun v => parent_walk o f h hf (distance_self (fun i j hi => (hℓ i j hi).le) o) + (fun v hv => (hpred v hv).2.1) v + · intro u v huv + rcases huv with ⟨hv,rfl⟩ | ⟨hu,rfl⟩ + · rw [abs_of_pos (sub_pos.mpr (hpred v hv).2.2)] + linarith [(hpred v hv).2.1] + · rw [abs_of_neg (sub_neg.mpr (hpred u hu).2.2),hs u (f u)] + linarith [(hpred u hu).2.1] + +end PlanarL1.WeightedGraph + + + + +end + +section + +namespace PlanarL1 +namespace Weighted +variable {V : Type} {G : SimpleGraph V} {l : V → V → ℝ} + +lemma length_eq_sum_darts {u v : V} (p : G.Walk u v) : + walkLength l p = (p.darts.map (fun d => l d.fst d.snd)).sum := by + induction p with + | nil => rfl + | cons h p ih => simp only [walkLength,SimpleGraph.Walk.darts_cons,List.map_cons,List.sum_cons,ih] + +lemma length_nonneg (hl : ∀ u v, G.Adj u v → 0 ≤ l u v) {u v : V} (p : G.Walk u v) : + 0 ≤ walkLength l p := by + induction p with + | nil => exact le_rfl + | cons h p ih => exact add_nonneg (hl _ _ h) ih + +lemma length_append {u v w : V} (p : G.Walk u v) (q : G.Walk v w) : + walkLength l (p.append q) = walkLength l p+walkLength l q := by + simp only [length_eq_sum_darts,SimpleGraph.Walk.darts_append,List.map_append,List.sum_append] + +lemma length_reverse (hs : ∀ u v, l u v=l v u) {u v : V} (p : G.Walk u v) : + walkLength l p.reverse=walkLength l p := by + simp only [length_eq_sum_darts,SimpleGraph.Walk.darts_reverse,List.map_reverse,List.map_map,List.sum_reverse] + congr 2 + funext d + exact hs d.snd d.fst + +lemma length_bypass [DecidableEq V] (hl : ∀ u v, G.Adj u v → 0 ≤ l u v) + {u v : V} (p : G.Walk u v) : walkLength l p.bypass ≤ walkLength l p := by + rw [length_eq_sum_darts,length_eq_sum_darts] + apply (p.darts_bypass_sublist_darts.map _).sum_le_sum + intro a ha + obtain ⟨d,_,rfl⟩ := List.mem_map.mp ha + exact hl d.fst d.snd d.adj + +lemma length_eq_zero_iff (hl : ∀ u v, G.Adj u v → 0 < l u v) + {u v : V} (p : G.Walk u v) : walkLength l p=0 ↔ p.Nil := by + cases p with + | nil => simp [walkLength] + | cons h p => + have hpos : 0 < walkLength l (.cons h p) := + add_pos_of_pos_of_nonneg (hl _ _ h) (length_nonneg (fun u v h => (hl u v h).le) p) + simp only [SimpleGraph.Walk.not_nil_cons,iff_false] + exact ne_of_gt hpos + +/-- Positivity permits deletion of repetitions, so the literal walk-infimum +is achieved by one of finitely many simple paths. No integral edge lengths +or approximation of the metric is used. -/ +lemma exists_shortest [Fintype V] (hl : ∀ u v, G.Adj u v → 0 ≤ l u v) + {u v : V} (hc : G.Reachable u v) : + ∃ p : G.Path u v, ∀ q : G.Walk u v, walkLength l p.val ≤ walkLength l q := by + classical + obtain ⟨q⟩ := hc + have he : (Finset.univ : Finset (G.Path u v)).Nonempty := ⟨q.toPath,Finset.mem_univ _⟩ + obtain ⟨p,_,hp⟩ := Finset.univ.exists_min_image (fun p : G.Path u v => walkLength l p.val) he + refine ⟨p,fun q => ?_⟩ + exact (hp q.toPath (Finset.mem_univ _)).trans (length_bypass hl q) + +lemma distance_eq_length [Fintype V] (hl : ∀ u v, G.Adj u v → 0 ≤ l u v) + {u v : V} (hc : G.Reachable u v) : + ∃ p : G.Path u v, graphDistance G l u v=walkLength l p.val ∧ + ∀ q : G.Walk u v, walkLength l p.val ≤ walkLength l q := by + obtain ⟨p,hp⟩ := exists_shortest hl hc + refine ⟨p,?_,hp⟩ + apply le_antisymm + · exact csInf_le ⟨0,by rintro a ⟨q,rfl⟩; exact length_nonneg hl q⟩ ⟨p.val,rfl⟩ + · exact le_csInf ⟨walkLength l p.val,⟨p.val,rfl⟩⟩ (by rintro a ⟨q,rfl⟩; exact hp q) + +lemma distance_le_walk (hl : ∀ u v, G.Adj u v → 0 ≤ l u v) + {u v : V} (p : G.Walk u v) : graphDistance G l u v ≤ walkLength l p := + csInf_le ⟨0,by rintro a ⟨q,rfl⟩; exact length_nonneg hl q⟩ ⟨p,rfl⟩ + +lemma distance_nonneg (hl : ∀ u v, G.Adj u v → 0 ≤ l u v) + {u v : V} (hc : G.Reachable u v) : 0 ≤ graphDistance G l u v := by + obtain ⟨p⟩ := hc + exact le_csInf ⟨walkLength l p,⟨p,rfl⟩⟩ (by rintro a ⟨q,rfl⟩; exact length_nonneg hl q) + +lemma distance_self (hl : ∀ u v, G.Adj u v → 0 ≤ l u v) (u : V) : + graphDistance G l u u=0 := + le_antisymm (distance_le_walk hl .nil) (distance_nonneg hl (.refl u)) + +lemma distance_symm [Fintype V] (hl : ∀ u v, G.Adj u v → 0 ≤ l u v) + (hs : ∀ u v, l u v=l v u) {u v : V} (hc : G.Reachable u v) : + graphDistance G l u v=graphDistance G l v u := by + have hb {u v : V} (hc : G.Reachable u v) : graphDistance G l v u ≤ graphDistance G l u v := by + obtain ⟨p,he,_⟩ := distance_eq_length hl hc + rw [he,← length_reverse hs p.val] + exact distance_le_walk hl p.val.reverse + exact le_antisymm (hb hc.symm) (hb hc) + +lemma distance_triangle [Fintype V] (hl : ∀ u v, G.Adj u v → 0 ≤ l u v) + {u v w : V} (huv : G.Reachable u v) (hvw : G.Reachable v w) : + graphDistance G l u w ≤ graphDistance G l u v+graphDistance G l v w := by + obtain ⟨p,hp,_⟩ := distance_eq_length hl huv + obtain ⟨q,hq,_⟩ := distance_eq_length hl hvw + rw [hp,hq,← length_append] + exact distance_le_walk hl (p.val.append q.val) + +lemma distance_eq_zero [Fintype V] (hl : ∀ u v, G.Adj u v → 0 < l u v) + {u v : V} (hc : G.Reachable u v) : graphDistance G l u v=0 ↔ u=v := by + constructor + · intro hz + obtain ⟨p,he,_⟩ := distance_eq_length (fun u v h => (hl u v h).le) hc + have hp := (length_eq_zero_iff hl p.val).mp (he.symm.trans hz) + exact hp.eq + · rintro rfl + exact distance_self (fun u v h => (hl u v h).le) u + +/-- The exact source graph metric, on the original vertex type. -/ +@[instance_reducible] noncomputable def metricSpace [Fintype V] (hc : G.Connected) + (hs : ∀ u v, l u v=l v u) (hl : ∀ u v, G.Adj u v → 0 < l u v) : MetricSpace V where + dist := graphDistance G l + dist_self := distance_self (fun u v h => (hl u v h).le) + dist_comm u v := distance_symm (fun u v h => (hl u v h).le) hs (hc.preconnected u v) + dist_triangle u v w := distance_triangle (fun u v h => (hl u v h).le) + (hc.preconnected u v) (hc.preconnected v w) + eq_of_dist_eq_zero h := (distance_eq_zero hl (hc.preconnected _ _)).mp h + +lemma edge_bound (hl : ∀ u v, G.Adj u v → 0 ≤ l u v) + {u v : V} (h : G.Adj u v) : graphDistance G l u v ≤ l u v := by + simpa only [walkLength,add_zero] using distance_le_walk hl (.cons h .nil) + +lemma height_edge [Fintype V] (hc : G.Connected) + (hs : ∀ u v, l u v=l v u) (hl : ∀ u v, G.Adj u v → 0 ≤ l u v) + (o : V) {u v : V} (h : G.Adj u v) : + |graphDistance G l o u-graphDistance G l o v| ≤ l u v := by + apply abs_le.mpr + have h₁ := distance_triangle hl (hc.preconnected o u) (hc.preconnected u v) + have h₂ := distance_triangle hl (hc.preconnected o v) (hc.preconnected v u) + have h₃ := edge_bound hl h + have h₄ := edge_bound hl h.symm + rw [hs v u] at h₄ + constructor <;> linarith + +/-- Each non-root vertex has a strictly lower predecessor on a genuine +weighted shortest path. This is the input to the shortest-path spanning tree +in ; positivity, not integral weights, supplies the descent. -/ +lemma exists_predecessor [Fintype V] (hc : G.Connected) + (hs : ∀ u v, l u v=l v u) (hl : ∀ u v, G.Adj u v → 0 < l u v) + (o v : V) (hv : v ≠ o) : ∃ u, G.Adj u v ∧ + graphDistance G l o v=graphDistance G l o u+l u v ∧ + graphDistance G l o u < graphDistance G l o v := by + have hn : ∀ u v, G.Adj u v → 0 ≤ l u v := fun u v h => (hl u v h).le + obtain ⟨p,he,hp⟩ := distance_eq_length hn (hc.preconnected v o) + cases hw : p.val with + | nil => exact (hv rfl).elim + | @cons v u o h q => + have htail : graphDistance G l u o=walkLength l q := by + apply le_antisymm (distance_le_walk hn q) + obtain ⟨r,hr,_⟩ := distance_eq_length hn (hc.preconnected u o) + have hb := hp (.cons h r.val) + rw [hw] at hb + simp only [walkLength] at hb + rw [hr] + linarith + have heq : graphDistance G l o v=graphDistance G l o u+l u v := by + rw [distance_symm hn hs (hc.preconnected o v),he,hw,walkLength, + ← htail,distance_symm hn hs (hc.preconnected u o),hs v u] + ring + exact ⟨u,h.symm,heq,by linarith [hl v u h,hs v u]⟩ + +end Weighted +end PlanarL1 + + + +end + +section + +/-! ## Shortest-path spanning tree . -/ + +namespace PlanarL1.Weighted +open SimpleGraph +attribute [local instance] Classical.propDecidable +variable {V : Type} [Fintype V] {G : SimpleGraph V} {l : V → V → ℝ} + +/-- A predecessor system whose heights strictly decrease to its root. The +well-foundedness here uses finiteness, not any discretization of real lengths. -/ +structure DescendingParents (V : Type*) where + root : V + height : V → ℝ + parent : V → V + at_root : parent root=root + descent : ∀ v, v ≠ root → height (parent v) h.symm⟩ + loopless := ⟨by + intro v h + rcases h with h | h <;> exact D.parent_ne v h.1 h.2⟩ + +omit [Fintype V] in +lemma child_adj (v : V) (hv : v ≠ D.root) : D.graph.Adj v (D.parent v) := + Or.inl ⟨hv,rfl⟩ + +lemma wellFounded : WellFounded (fun u v : V => D.height u D.height u lt_trans⟩ + let : Std.Irrefl (fun u v => D.height u lt_irrefl _⟩ + exact Finite.wellFounded_of_trans_of_irrefl _ + +lemma reachable_root (v : V) : D.graph.Reachable v D.root := by + induction v using D.wellFounded.induction with + | h v ih => + by_cases hv : v=D.root + · rw [hv] + · exact (D.child_adj v hv).reachable.trans (ih (D.parent v) (D.descent v hv)) + +lemma connected : D.graph.Connected := by + let : Nonempty V := ⟨D.root⟩ + exact ⟨fun u v => (D.reachable_root u).trans (D.reachable_root v).symm⟩ + +omit [Fintype V] in +lemma edge_injective : Set.InjOn (fun v => s(v,D.parent v)) ({D.root}ᶜ : Set V) := by + intro u hu v hv he + rcases Sym2.eq_iff.mp he with h | h + · exact h.1 + · have hu' : u ≠ D.root := hu + have hv' : v ≠ D.root := hv + have hd₁ := D.descent u hu' + have hd₂ := D.descent v hv' + rw [h.2] at hd₁ + rw [← h.1] at hd₂ + exact False.elim ((not_lt_of_gt hd₁) hd₂) + +lemma edgeFinset_eq : D.graph.edgeFinset = (Finset.univ.erase D.root).image + (fun v => s(v,D.parent v)) := by + classical + ext e + induction e using Sym2.inductionOn with + | hf u v => + rw [SimpleGraph.mem_edgeFinset, SimpleGraph.mem_edgeSet] + simp only [graph,Finset.mem_image,Finset.mem_erase,Finset.mem_univ,and_true,Sym2.eq_iff] + constructor + · rintro (⟨hu,he⟩ | ⟨hv,he⟩) + · exact ⟨u,hu,Or.inl ⟨rfl,he⟩⟩ + · exact ⟨v,hv,Or.inr ⟨rfl,he⟩⟩ + · rintro ⟨w,hw,(⟨rfl,he⟩ | ⟨rfl,he⟩)⟩ + · exact Or.inl ⟨hw,he⟩ + · exact Or.inr ⟨hw,he⟩ + +lemma isTree : D.graph.IsTree := by + classical + apply SimpleGraph.isTree_iff_connected_and_card.mpr + refine ⟨D.connected,?_⟩ + rw [Nat.card_eq_fintype_card,← SimpleGraph.edgeFinset_card,D.edgeFinset_eq] + rw [Finset.card_image_iff.mpr (by + intro u hu v hv he + exact D.edge_injective (Finset.mem_erase.mp hu).1 (Finset.mem_erase.mp hv).1 he)] + rw [Finset.card_erase_add_one (Finset.mem_univ _),Finset.card_univ,Nat.card_eq_fintype_card] +end DescendingParents + +noncomputable def shortestParents (hc : G.Connected) (hs : ∀ u v, l u v=l v u) + (hl : ∀ u v, G.Adj u v → 0 + by_cases hv : v=o + · subst v + exact ⟨.nil,(distance_self (fun u v h => (hl u v h).le) o).symm⟩ + · obtain ⟨p,hp⟩ := ih (D.parent v) (D.descent v hv) + refine ⟨p.append (.cons (D.child_adj v hv).symm .nil),?_⟩ + rw [length_append,hp] + simpa only [walkLength,add_zero] using (parent_step hc hs hl o v hv).2.symm + +/-- The shortest-path spanning tree in : every root path has the +original weighted distance. No planarity or unit edge lengths is used. -/ +lemma root_distance (v : V) : + graphDistance (shortestParents hc hs hl o).graph l o v=graphDistance G l o v := by + let D := shortestParents hc hs hl o + have hn : ∀ u v, D.graph.Adj u v → 0 ≤ l u v := + fun u v h => (hl u v (graph_le hc hs hl o h)).le + obtain ⟨p,hp⟩ := exists_root_walk hc hs hl o v + apply le_antisymm + · exact (distance_le_walk hn p).trans_eq hp + · obtain ⟨q,hq,_⟩ := distance_eq_length hn (D.connected.preconnected o v) + rw [hq] + have hlen {u v : V} (q : D.graph.Walk u v) : + walkLength l (q.mapLe (graph_le hc hs hl o))=walkLength l q := by + induction q with + | nil => rfl + | cons h q ih => simpa only [Walk.mapLe,Walk.map,walkLength,SimpleGraph.Hom.ofLE_apply] using congrArg (l _ _ + ·) ih + rw [← hlen q.val] + exact distance_le_walk (fun u v h => (hl u v h).le) _ +end shortestParents +end PlanarL1.Weighted + + + +end + +end OAI diff --git a/lean/OAI/Combinatorics/PolynomialVacuum/Algebra/AllFinalCupZeros.lean b/lean/OAI/Combinatorics/PolynomialVacuum/Algebra/AllFinalCupZeros.lean new file mode 100644 index 0000000000000000000000000000000000000000..9954f821d507f88d5f6f08340e499efaf0f230a9 --- /dev/null +++ b/lean/OAI/Combinatorics/PolynomialVacuum/Algebra/AllFinalCupZeros.lean @@ -0,0 +1,54 @@ +import OAI.Combinatorics.PolynomialVacuum.Algebra.FinalCupZeros + +namespace OAI + +namespace PolynomialVacuumAlgebra +open MvPolynomial Classical + +theorem cupZero_transport_generic {D : NatSpectralTensor} {n i k : ℕ} + (hex : LowerExchange D n) (hik : i < k) (hk : k < n) + (hc : ∀ X, X (i+1)=T*X i → D X=0) + (X : ℕ → ℂ) (hX : X k=T*X i) + (hG : trainDenominator (T*X i) X (i+1) (k-i-1)≠0) : D X=0 := by + have he := braidTrain_pull_exchange hex (i+1) (k-i-1) (by omega) (T*X i) X + rw [show i+1+(k-i-1)=k by omega,← hX,Function.update_eq_self] at he + rw [hX] at he + rw [hc _ (by simp [pullSite_before (by omega : i < i+1)]),map_zero] at he + exact (smul_right_injective _ hG) (he.symm.trans (smul_zero _).symm) + +theorem exchangeDifference_spectatorCup {n i k : ℕ} (Ψ : State (n+2)) (ψ : State n) + (hex : LowerExchange (liftState Ψ) (n+1)) + (hexψ : LowerExchange (liftState ψ) n) + (hik : i < k) (hk : k < n) (hc : CupAt (liftState Ψ) (liftState ψ) n i) + (X : ℕ → ℂ) (hX : X k=T*X i) : exchangeDifference (liftState Ψ) n X=0 := by + funext s + have he : cupSpecialize i k (exchangeDiscrepancy Ψ n s)=cupSpecialize i k 0 := by + apply cupSurface_eq_of_generic i k (by omega) _ _ (partialTrainGuard k i) (partialTrainGuard_surface hik) + intro Y hY hG + have hz := cupZero_transport_generic (exchangeDifference_exchanges hex) hik hk + (exchangeDifference_adjacentCup (by omega) hexψ hc) Y hY (by simpa using hG) + simpa only [eval_exchangeDiscrepancy,map_zero,exchangeDifference,Pi.sub_apply,Pi.smul_apply,smul_eq_mul,Pi.zero_apply] using congrFun hz s + have he' := eval_eq_of_cupSurface_eq i k _ _ he X hX + simpa only [eval_exchangeDiscrepancy,map_zero,exchangeDifference,Pi.sub_apply,Pi.smul_apply,smul_eq_mul,Pi.zero_apply] using he' + + + +theorem exchangeDifference_cup_zero {n : ℕ} (Ψ : State (n+2)) (ψ : State n) + (hex : LowerExchange (liftState Ψ) (n+1)) + (hexψ : LowerExchange (liftState ψ) n) + (hnode : NaturalCupNodes (liftState Ψ) (liftState ψ) n) + (hc : ∀ i≤n, CupAt (liftState Ψ) (liftState ψ) n i) + (i k : ℕ) (hi : i < n) (hik : i < k) (hk : k < n+2) + (X : ℕ → ℂ) (hX : X k=T*X i) : exchangeDifference (liftState Ψ) n X=0 := by + by_cases h : k < n + · exact exchangeDifference_spectatorCup Ψ ψ hex hexψ hik h (hc i (by omega)) X hX + · by_cases h' : k=n + · subst k + exact finalDifference_penultimate Ψ ψ hex hnode hi (hc i (by omega)) X hX + · have h' : k=n+1 := by omega + subst k + exact finalDifference_last Ψ ψ hex hnode hi (hc i (by omega)) X hX + +end PolynomialVacuumAlgebra + +end OAI diff --git a/lean/OAI/Combinatorics/PolynomialVacuum/Algebra/AllSizeConstruction.lean b/lean/OAI/Combinatorics/PolynomialVacuum/Algebra/AllSizeConstruction.lean new file mode 100644 index 0000000000000000000000000000000000000000..187ef4b191e896fb798d2e503a2959b4f9bfae1f --- /dev/null +++ b/lean/OAI/Combinatorics/PolynomialVacuum/Algebra/AllSizeConstruction.lean @@ -0,0 +1,128 @@ +import OAI.Combinatorics.PolynomialVacuum.Algebra.HomogeneityStep +import OAI.Combinatorics.PolynomialVacuum.Algebra.ChargeStep +import OAI.Combinatorics.PolynomialVacuum.Algebra.BaseGrading +import OAI.Combinatorics.PolynomialVacuum.Algebra.BaseBounds +import OAI.Combinatorics.PolynomialVacuum.Algebra.BaseEndpoints + +namespace OAI + +namespace PolynomialVacuumAlgebra +open MvPolynomial Classical + + + +noncomputable def polynomialVacuum : Family + | 0 => vacuumZero + | 1 => vacuumOne + | 2 => vacuumTwo + | 3 => vacuumThree + | n+4 => interpolateState (polynomialVacuum (n+2)) (polynomialVacuum (n+3)) + +structure VacuumRegular {N : ℕ} (ψ : State N) : Prop where + charge : ChargeZero ψ + homogeneous : ∀ s, (ψ s).IsHomogeneous (N.choose 2) + degree : ∀ s i, (ψ s).degreeOf i≤N-1 + plus : ∀ s i, s i=Spin.plus → (ψ s).degreeOf i≤N-2 + minus : MinusZero ψ + exchange : LowerExchange (liftState ψ) N + +structure VacuumAt (f : Family) (N : ℕ) : Prop where + regular : VacuumRegular (f N) + cyclic : ∀ n, N=n+1 → NaturalCyclic n (liftState (f (n+1))) + nodes : ∀ n, N=n+2 → NaturalCupNodes (liftState (f (n+2))) (liftState (f n)) n + firstCup : ∀ n, N=n+2 → FirstCupReduction (liftState (f (n+2))) (liftState (f n)) n + cups : ∀ n, N=n+2 → ∀ i≤n, CupAt (liftState (f (n+2))) (liftState (f n)) n i + lastZero : ∀ n, N=n+1 → LastZeroReduction (liftState (f (n+1))) (liftState (f n)) n + +theorem vacuumZero_regular : VacuumRegular vacuumZero := by + constructor + · intro s hs; exact (hs (by simp)).elim + · intro s; simpa [vacuumZero] using (isHomogeneous_one _ _) + · intro s i; exact Fin.elim0 i + · intro s i; exact Fin.elim0 i + · intro s i; exact Fin.elim0 i + · intro j hj; omega + +theorem vacuumOne_regular : VacuumRegular vacuumOne := by + constructor + · intro s hs + cases h : s 0 <;> simp_all [vacuumOne,charge] + · intro s + unfold vacuumOne + split_ifs + · simpa [vacuumZero] using (isHomogeneous_one _ _) + · exact isHomogeneous_zero _ _ _ + · intro s i; unfold vacuumOne; split_ifs <;> simp + · intro s i hi; unfold vacuumOne; split_ifs <;> simp + · intro s i hi + have he : i=0 := Subsingleton.elim _ _ + subst i + simp [vacuumOne,hi] + · intro j hj; omega + +theorem vacuumTwo_regular : VacuumRegular vacuumTwo := by + exact ⟨vacuumTwo_charge,vacuumTwo_homogeneous,(fun s j => (vacuumTwo_degrees s j).1), + (fun s j => (vacuumTwo_degrees s j).2),vacuumTwo_minusZero,vacuumTwo_exchange⟩ + +theorem vacuumThree_regular : VacuumRegular vacuumThree := by + exact ⟨vacuumThree_charge,vacuumThree_homogeneous,(fun s j => (vacuumThree_degrees s j).1), + (fun s j => (vacuumThree_degrees s j).2),vacuumThree_minusZero,vacuumThree_exchange⟩ + +theorem vacuumOne_cyclic : NaturalCyclic 0 (liftState vacuumOne) := by + intro X; funext s + simp only [cyclicTransform,rotateTensor,lift_vacuumOne,natRotate_zero] + cases h : s 0 <;> simp [charge] + +theorem polynomialVacuum_at_zero : VacuumAt polynomialVacuum 0 := by + constructor + · exact vacuumZero_regular + all_goals intro n hn; omega + +theorem polynomialVacuum_at_one : VacuumAt polynomialVacuum 1 := by + constructor + · exact vacuumOne_regular + · intro n hn; have : n=0 := by omega + subst n; exact vacuumOne_cyclic + · intro n hn; omega + · intro n hn; omega + · intro n hn; omega + · intro n hn; have : n=0 := by omega + subst n; exact vacuumOne_lastZero + +theorem polynomialVacuum_at_two : VacuumAt polynomialVacuum 2 := by + constructor + · exact vacuumTwo_regular + · intro n hn; have : n=1 := by omega + subst n; exact vacuumTwo_cyclic + · intro n hn; have : n=0 := by omega + subst n; exact vacuumTwo_nodes + · intro n hn; have : n=0 := by omega + subst n; exact vacuumTwo_firstCup + · intro n hn i hi; have : n=0 := by omega + subst n + have : i=0 := by omega + subst i + exact vacuumTwo_firstCup + · intro n hn; have : n=1 := by omega + subst n; exact vacuumTwo_lastZero + +theorem polynomialVacuum_at_three : VacuumAt polynomialVacuum 3 := by + constructor + · exact vacuumThree_regular + · intro n hn; have : n=2 := by omega + subst n; exact vacuumThree_cyclic + · intro n hn; have : n=1 := by omega + subst n; exact vacuumThree_nodes + · intro n hn; have : n=1 := by omega + subst n; exact vacuumThree_firstCup + · intro n hn i hi; have : n=1 := by omega + subst n + interval_cases i + · exact vacuumThree_firstCup + · exact vacuumThree_lastCup + · intro n hn; have : n=2 := by omega + subst n; exact vacuumThree_lastZero + +end PolynomialVacuumAlgebra + +end OAI diff --git a/lean/OAI/Combinatorics/PolynomialVacuum/Algebra/AllSizeInduction.lean b/lean/OAI/Combinatorics/PolynomialVacuum/Algebra/AllSizeInduction.lean new file mode 100644 index 0000000000000000000000000000000000000000..7f3112411758adfde161e6cdd51741c4543962b8 --- /dev/null +++ b/lean/OAI/Combinatorics/PolynomialVacuum/Algebra/AllSizeInduction.lean @@ -0,0 +1,98 @@ +import OAI.Combinatorics.PolynomialVacuum.Algebra.AllSizeConstruction + +namespace OAI + +namespace PolynomialVacuumAlgebra +open MvPolynomial Classical + +theorem interpolateState_all_degrees {n : ℕ} (hn : 2≤n) + (ψ : State n) (χ : State (n+1)) (hψ : VacuumRegular ψ) (hχ : VacuumRegular χ) : + (∀ s i, (interpolateState ψ χ s).degreeOf i≤n+1) ∧ + (∀ s i, s i=Spin.plus → (interpolateState ψ χ s).degreeOf i≤n) := by + have hs := interpolateState_spectator_degrees hn ψ χ hψ.exchange hψ.degree hψ.plus + (fun s i => (hχ.degree s i).trans (by omega)) + (fun s i h => (hχ.plus s i h).trans (by omega)) + constructor + · intro s i + refine Fin.lastCases ?_ (fun j => ?_) i + · exact (interpolateState_last_degrees ψ χ s).1 + · exact (hs s j).1 + · intro s i + refine Fin.lastCases ?_ (fun j => ?_) i + · exact (interpolateState_last_degrees ψ χ s).2 + · exact (hs s j).2 + + + +theorem polynomialVacuum_at_step (n : ℕ) + (hψ : VacuumAt polynomialVacuum (n+2)) + (hχ : VacuumAt polynomialVacuum (n+3)) : VacuumAt polynomialVacuum (n+4) := by + let ψ := polynomialVacuum (n+2) + let χ := polynomialVacuum (n+3) + let Ψ := interpolateState ψ χ + have hdef : polynomialVacuum (n+4)=Ψ := by rw [polynomialVacuum] + have hfirst : FirstCupReduction (liftState Ψ) (liftState ψ) (n+2) := + interpolateState_firstCup ψ χ (liftState (polynomialVacuum n)) (liftState (polynomialVacuum (n+1))) + hψ.regular.exchange (hψ.nodes n rfl) (hψ.firstCup n rfl) (hψ.lastZero (n+1) rfl) + (hχ.firstCup (n+1) rfl) (fun s => hψ.regular.degree s _) + (fun s hs => by have:=hψ.regular.plus s _ hs; simpa using this) + have hnodes : NaturalCupNodes (liftState Ψ) (liftState ψ) (n+2) := + lift_interpolate_cupNodes ψ χ hψ.regular.exchange + have hcup : ∀ i≤n+2, CupAt (liftState Ψ) (liftState ψ) (n+2) i := + interpolateState_all_cups ψ χ hψ.regular.exchange hχ.regular.exchange hfirst + have hdg := interpolateState_all_degrees (by omega : 2≤n+2) ψ χ hψ.regular hχ.regular + have hd : ∀ s i, (Ψ s).degreeOf i≤n+3 := hdg.1 + have hp : ∀ s i, s i=Spin.plus → (Ψ s).degreeOf i≤n+2 := hdg.2 + have hz : MinusZero Ψ := interpolateState_minusZero ψ χ hψ.regular.exchange hψ.regular.minus hχ.regular.minus + have hex : LowerExchange (liftState Ψ) (n+4) := + fullExchange_of_cups (by omega : 2≤n+2) Ψ ψ + (interpolateState_first_exchanges ψ χ hψ.regular.exchange hχ.regular.exchange) + hψ.regular.exchange hnodes hcup hd hp hz + have hcy : NaturalCyclic (n+3) (liftState Ψ) := + cyclicity_of_cups Ψ ψ hex hcup (hψ.cyclic (n+1) rfl) hd hp hz + have hhom : ∀ s, (Ψ s).IsHomogeneous ((n+4).choose 2) := + homogeneity_of_cups Ψ ψ hex hcup hψ.regular.homogeneous hd hp hz + have hcharge : ChargeZero Ψ := chargeZero_of_cups Ψ ψ hex hcup hψ.regular.charge hd hp hz + constructor + · rw [hdef] + exact ⟨hcharge,hhom,(fun s i => (hd s i).trans (by omega)), + (fun s i hs => (hp s i hs).trans (by omega)),hz,hex⟩ + · intro k hk + have he : k=n+3 := by omega + subst k + rw [show n+3+1=n+4 by omega,hdef] + exact hcy + · intro k hk + have he : k=n+2 := by omega + subst k + rw [show n+2+2=n+4 by omega,hdef] + exact hnodes + · intro k hk + have he : k=n+2 := by omega + subst k + rw [show n+2+2=n+4 by omega,hdef] + exact hfirst + · intro k hk + have he : k=n+2 := by omega + subst k + rw [show n+2+2=n+4 by omega,hdef] + exact hcup + · intro k hk + have he : k=n+3 := by omega + subst k + rw [show n+3+1=n+4 by omega,hdef] + exact interpolateState_lastZero ψ χ + +theorem polynomialVacuum_at (N : ℕ) : VacuumAt polynomialVacuum N := by + induction N using Nat.strong_induction_on with + | h N ih => + rcases N with _|_|_|_|n + · exact polynomialVacuum_at_zero + · exact polynomialVacuum_at_one + · exact polynomialVacuum_at_two + · exact polynomialVacuum_at_three + · exact polynomialVacuum_at_step n (ih (n+2) (by omega)) (ih (n+3) (by omega)) + +end PolynomialVacuumAlgebra + +end OAI diff --git a/lean/OAI/Combinatorics/PolynomialVacuum/Algebra/AnalyticNormalization.lean b/lean/OAI/Combinatorics/PolynomialVacuum/Algebra/AnalyticNormalization.lean new file mode 100644 index 0000000000000000000000000000000000000000..d3e63a6f44085f69a2bd76cf34c3975ad27b6e14 --- /dev/null +++ b/lean/OAI/Combinatorics/PolynomialVacuum/Algebra/AnalyticNormalization.lean @@ -0,0 +1,50 @@ +import OAI.Combinatorics.PolynomialVacuum.Algebra.AnalyticResolvent +import OAI.Combinatorics.PolynomialVacuum.Algebra.EmptyNonzero +import OAI.Combinatorics.PolynomialVacuum.Pairing.PairingTarget + +namespace OAI + +namespace PolynomialVacuumAlgebra +namespace AnalyticVacuum +open Classical Filter +open scoped Topology + +theorem normalizedVacuum_homogeneous (N : ℕ) (s : Fin (N+1) → Spin) : + normalizedVacuum (N+1) (fun _=>1) s=physicalProjection N s (fun _=>.zero) := by + let v : (Fin (N+1) → Spin) → ℂ:=fun r=>physicalProjection N r (fun _=>.zero) + have hv : (spectralMatrix (N+1) (fun _=>1)).mulVec v=rowDenominator (N+1) (fun _=>1) • v := by + rw [spectralMatrix_one,rowDenominator_one,Matrix.smul_mulVec] + congr 1 + funext r + exact congrFun (congrFun (physicalProjection_left_fixed N) r) (fun _=>.zero) + have he:=normalizedVacuum_eq_ratio (N+1) (fun _=>1) v hv (vacuumResolvent_det_ne_zero _) (by simp [v]) s + simpa [v] using he + +@[simp] theorem normalizedVacuum_empty (N : ℕ) : normalizedVacuum N (fun _=>1) (fun _=>.zero)=1 := by + cases N with + | zero => + have hv : (spectralMatrix 0 (fun _=>1)).mulVec (fun _=>1)=rowDenominator 0 (fun _=>1) • (fun _=>1) := by + funext s + simp [spectralMatrix,transferMatrix,rowKernel,rowDenominator,trainDenominator, + Matrix.mulVec,dotProduct,sum_spin,charge,PolynomialVacuumCylinder.zeta_eq_I] + simpa using normalizedVacuum_eq_ratio 0 (fun _=>1) (fun _=>1) hv (vacuumResolvent_det_ne_zero 0) one_ne_zero (fun _=>.zero) + | succ N => rw [normalizedVacuum_homogeneous,physicalProjection_empty] + +theorem normalizedVacuum_eventually_ratio (N : ℕ) (s : Fin N → Spin) : + ∀ᶠ X in nhds (fun _ : Fin N => (1:ℂ)), + MvPolynomial.eval X (polynomialVacuum N (fun _=>Spin.zero))≠0 → + normalizedVacuum N X s=MvPolynomial.eval X (polynomialVacuum N s)/MvPolynomial.eval X (polynomialVacuum N (fun _=>Spin.zero)) := by + filter_upwards [fusion_eventually_ne_zero N,vacuumResolvent_eventually_ne_zero N] with X hf hd + intro h0 + exact normalizedVacuum_eq_ratio N X (spectralPolynomial N X) (spectralPolynomial_eigen N X hf) hd h0 s + + + +theorem actual_analytic_normalization : + PolynomialVacuumCylinder.AnalyticNormalization polynomialVacuum normalizedVacuum := + ⟨polynomialVacuum_empty_ne_zero,analytic_normalizedVacuum, + normalizedVacuum_eventually_ratio,normalizedVacuum_empty⟩ +end AnalyticVacuum +end PolynomialVacuumAlgebra + +end OAI diff --git a/lean/OAI/Combinatorics/PolynomialVacuum/Algebra/AnalyticResolvent.lean b/lean/OAI/Combinatorics/PolynomialVacuum/Algebra/AnalyticResolvent.lean new file mode 100644 index 0000000000000000000000000000000000000000..9c85966fd49dd084fd69916ad5283866dd9b82d0 --- /dev/null +++ b/lean/OAI/Combinatorics/PolynomialVacuum/Algebra/AnalyticResolvent.lean @@ -0,0 +1,74 @@ +import OAI.Combinatorics.PolynomialVacuum.Algebra.SpectralEigenvector +import OAI.Combinatorics.PolynomialVacuum.Cylinder.Resolvent + +namespace OAI + +namespace PolynomialVacuumAlgebra +namespace AnalyticVacuum +open Classical Filter +open scoped Topology + +noncomputable def vacuumResolvent (N : ℕ) (X : Fin N → ℂ) : Matrix (Fin N → Spin) (Fin N → Spin) ℂ := + rowDenominator N X • 1-spectralMatrix N X+emptyMatrix N +noncomputable def normalizedVacuum (N : ℕ) (X : Fin N → ℂ) (s : Fin N → Spin) : ℂ := + (vacuumResolvent N X).adjugate s (fun _=>.zero)/(vacuumResolvent N X).det + +theorem vacuumResolvent_one (N : ℕ) : vacuumResolvent (N+1) (fun _=>1)= + exchangeDenominator t 1^(N+1) • (1-physicalTransfer (N+1) zeta)+emptyMatrix (N+1) := by + simp only [vacuumResolvent,rowDenominator_one,spectralMatrix_one,smul_sub] + +theorem vacuumResolvent_det_ne_zero (N : ℕ) : (vacuumResolvent N (fun _=>1)).det≠0 := by + cases N with + | zero => + have he : vacuumResolvent 0 (fun _=>1)=1 := by + ext s r + have hs : s=(fun _=>Spin.zero) := Subsingleton.elim _ _ + have hr : r=(fun _=>Spin.zero) := Subsingleton.elim _ _ + subst s; subst r + simp [vacuumResolvent,rowDenominator,spectralMatrix,transferMatrix,rowKernel, + trainDenominator,emptyMatrix,sum_spin,charge,PolynomialVacuumCylinder.zeta_eq_I] + rw [he,Matrix.det_one]; exact one_ne_zero + | succ N => + rw [vacuumResolvent_one] + exact ((Matrix.isUnit_iff_isUnit_det _).mp + (physical_resolvent_isUnit N _ (pow_ne_zero _ honeycombDenominator_ne_zero))).ne_zero + +theorem analytic_vacuumResolvent (N : ℕ) (X : Fin N → ℂ) (s r : Fin N → Spin) : + AnalyticAt ℂ (fun Y=>vacuumResolvent N Y s r) X := by + have hd:=analytic_trainDenominator N 0 t (extendData N) (fun j=>analytic_extendData N j X) + have hm:=analytic_transferMatrix N zeta t (extendData N) (fun j=>analytic_extendData N j X) s r + change AnalyticAt ℂ (fun Y=>rowDenominator N Y*(1 : Matrix _ _ ℂ) s r-spectralMatrix N Y s r+emptyMatrix N s r) X + exact ((hd.mul analyticAt_const).sub hm).add analyticAt_const + +theorem analytic_normalizedVacuum (N : ℕ) (s : Fin N → Spin) : + AnalyticAt ℂ (fun X=>normalizedVacuum N X s) (fun _=>1) := + (analytic_matrix_adjugate _ (analytic_vacuumResolvent N _) s _).div + (analytic_matrix_det _ (analytic_vacuumResolvent N _)) (vacuumResolvent_det_ne_zero N) + +theorem vacuumResolvent_eventually_ne_zero (N : ℕ) : + ∀ᶠ X in nhds (fun _ : Fin N => (1:ℂ)),(vacuumResolvent N X).det≠0 := + (analytic_matrix_det _ (analytic_vacuumResolvent N _)).continuousAt.eventually_ne (vacuumResolvent_det_ne_zero N) + +theorem resolvent_fixed_relation (N : ℕ) (X : Fin N → ℂ) (v : (Fin N → Spin) → ℂ) + (hv : (spectralMatrix N X).mulVec v=rowDenominator N X • v) (s : Fin N → Spin) : + (vacuumResolvent N X).det*v s=(vacuumResolvent N X).adjugate s (fun _=>.zero)*v (fun _=>.zero) := by + have ha : (vacuumResolvent N X).mulVec v=Pi.single (fun _=>.zero) (v (fun _=>.zero)) := by + rw [vacuumResolvent,Matrix.add_mulVec,Matrix.sub_mulVec,Matrix.smul_mulVec,Matrix.one_mulVec,hv, + sub_self,zero_add,emptyMatrix_mulVec] + have he:=congrArg (vacuumResolvent N X).adjugate.mulVec ha + rw [Matrix.mulVec_mulVec,Matrix.adjugate_mul,Matrix.smul_mulVec,Matrix.one_mulVec] at he + have hh:=congrFun he s + simpa [Matrix.mulVec,dotProduct,Pi.single_apply] using hh + +theorem normalizedVacuum_eq_ratio (N : ℕ) (X : Fin N → ℂ) (v : (Fin N → Spin) → ℂ) + (hv : (spectralMatrix N X).mulVec v=rowDenominator N X • v) + (hd : (vacuumResolvent N X).det≠0) (h0 : v (fun _=>.zero)≠0) (s : Fin N → Spin) : + normalizedVacuum N X s=v s/v (fun _=>.zero) := by + unfold normalizedVacuum + apply (div_eq_div_iff hd h0).mpr + simpa [mul_comm] using (resolvent_fixed_relation N X v hv s).symm + +end AnalyticVacuum +end PolynomialVacuumAlgebra + +end OAI diff --git a/lean/OAI/Combinatorics/PolynomialVacuum/Algebra/BaseBounds.lean b/lean/OAI/Combinatorics/PolynomialVacuum/Algebra/BaseBounds.lean new file mode 100644 index 0000000000000000000000000000000000000000..aae7db7d58688f0ca01bee58e400901a8b934951 --- /dev/null +++ b/lean/OAI/Combinatorics/PolynomialVacuum/Algebra/BaseBounds.lean @@ -0,0 +1,670 @@ +import OAI.Combinatorics.PolynomialVacuum.Algebra.BasePolynomials + +namespace OAI + +namespace PolynomialVacuumAlgebra +open MvPolynomial Classical +theorem basePolyThree_bound_0_0 : + (basePolyThree (X (0:Fin 3)) (X 1) (X 2) .zero .zero .zero).degreeOf 0 ≤ 2 := by + have h0 : ((X (0:Fin 3) : MvPolynomial (Fin 3) ℂ)).degreeOf (0:Fin 3)≤1 := by simp + have h1 : (((X (0:Fin 3) : MvPolynomial (Fin 3) ℂ)^2)).degreeOf (0:Fin 3)≤2 := dpow h0 2 + have h2 : ((X (1:Fin 3) : MvPolynomial (Fin 3) ℂ)).degreeOf (0:Fin 3)≤0 := by simp [degreeOf_X] + have h3 : ((((X (0:Fin 3) : MvPolynomial (Fin 3) ℂ)^2)*(X (1:Fin 3) : MvPolynomial (Fin 3) ℂ))).degreeOf (0:Fin 3)≤2 := dmul h1 h2 + have h4 : ((X (2:Fin 3) : MvPolynomial (Fin 3) ℂ)).degreeOf (0:Fin 3)≤0 := by simp [degreeOf_X] + have h5 : ((((X (0:Fin 3) : MvPolynomial (Fin 3) ℂ)^2)*(X (2:Fin 3) : MvPolynomial (Fin 3) ℂ))).degreeOf (0:Fin 3)≤2 := dmul h1 h4 + have h6 : (((((X (0:Fin 3) : MvPolynomial (Fin 3) ℂ)^2)*(X (1:Fin 3) : MvPolynomial (Fin 3) ℂ))+(((X (0:Fin 3) : MvPolynomial (Fin 3) ℂ)^2)*(X (2:Fin 3) : MvPolynomial (Fin 3) ℂ)))).degreeOf (0:Fin 3)≤2 := dadd (h3.trans (by omega)) (h5.trans (by omega)) + have h7 : (((X (1:Fin 3) : MvPolynomial (Fin 3) ℂ)^2)).degreeOf (0:Fin 3)≤0 := dpow h2 2 + have h8 : ((((X (1:Fin 3) : MvPolynomial (Fin 3) ℂ)^2)*(X (0:Fin 3) : MvPolynomial (Fin 3) ℂ))).degreeOf (0:Fin 3)≤1 := dmul h7 h0 + have h9 : ((((((X (0:Fin 3) : MvPolynomial (Fin 3) ℂ)^2)*(X (1:Fin 3) : MvPolynomial (Fin 3) ℂ))+(((X (0:Fin 3) : MvPolynomial (Fin 3) ℂ)^2)*(X (2:Fin 3) : MvPolynomial (Fin 3) ℂ)))+(((X (1:Fin 3) : MvPolynomial (Fin 3) ℂ)^2)*(X (0:Fin 3) : MvPolynomial (Fin 3) ℂ)))).degreeOf (0:Fin 3)≤2 := dadd (h6.trans (by omega)) (h8.trans (by omega)) + have h10 : ((((X (1:Fin 3) : MvPolynomial (Fin 3) ℂ)^2)*(X (2:Fin 3) : MvPolynomial (Fin 3) ℂ))).degreeOf (0:Fin 3)≤0 := dmul h7 h4 + have h11 : (((((((X (0:Fin 3) : MvPolynomial (Fin 3) ℂ)^2)*(X (1:Fin 3) : MvPolynomial (Fin 3) ℂ))+(((X (0:Fin 3) : MvPolynomial (Fin 3) ℂ)^2)*(X (2:Fin 3) : MvPolynomial (Fin 3) ℂ)))+(((X (1:Fin 3) : MvPolynomial (Fin 3) ℂ)^2)*(X (0:Fin 3) : MvPolynomial (Fin 3) ℂ)))+(((X (1:Fin 3) : MvPolynomial (Fin 3) ℂ)^2)*(X (2:Fin 3) : MvPolynomial (Fin 3) ℂ)))).degreeOf (0:Fin 3)≤2 := dadd (h9.trans (by omega)) (h10.trans (by omega)) + have h12 : (((X (2:Fin 3) : MvPolynomial (Fin 3) ℂ)^2)).degreeOf (0:Fin 3)≤0 := dpow h4 2 + have h13 : ((((X (2:Fin 3) : MvPolynomial (Fin 3) ℂ)^2)*(X (0:Fin 3) : MvPolynomial (Fin 3) ℂ))).degreeOf (0:Fin 3)≤1 := dmul h12 h0 + have h14 : ((((((((X (0:Fin 3) : MvPolynomial (Fin 3) ℂ)^2)*(X (1:Fin 3) : MvPolynomial (Fin 3) ℂ))+(((X (0:Fin 3) : MvPolynomial (Fin 3) ℂ)^2)*(X (2:Fin 3) : MvPolynomial (Fin 3) ℂ)))+(((X (1:Fin 3) : MvPolynomial (Fin 3) ℂ)^2)*(X (0:Fin 3) : MvPolynomial (Fin 3) ℂ)))+(((X (1:Fin 3) : MvPolynomial (Fin 3) ℂ)^2)*(X (2:Fin 3) : MvPolynomial (Fin 3) ℂ)))+(((X (2:Fin 3) : MvPolynomial (Fin 3) ℂ)^2)*(X (0:Fin 3) : MvPolynomial (Fin 3) ℂ)))).degreeOf (0:Fin 3)≤2 := dadd (h11.trans (by omega)) (h13.trans (by omega)) + have h15 : ((((X (2:Fin 3) : MvPolynomial (Fin 3) ℂ)^2)*(X (1:Fin 3) : MvPolynomial (Fin 3) ℂ))).degreeOf (0:Fin 3)≤0 := dmul h12 h2 + have h16 : (((((((((X (0:Fin 3) : MvPolynomial (Fin 3) ℂ)^2)*(X (1:Fin 3) : MvPolynomial (Fin 3) ℂ))+(((X (0:Fin 3) : MvPolynomial (Fin 3) ℂ)^2)*(X (2:Fin 3) : MvPolynomial (Fin 3) ℂ)))+(((X (1:Fin 3) : MvPolynomial (Fin 3) ℂ)^2)*(X (0:Fin 3) : MvPolynomial (Fin 3) ℂ)))+(((X (1:Fin 3) : MvPolynomial (Fin 3) ℂ)^2)*(X (2:Fin 3) : MvPolynomial (Fin 3) ℂ)))+(((X (2:Fin 3) : MvPolynomial (Fin 3) ℂ)^2)*(X (0:Fin 3) : MvPolynomial (Fin 3) ℂ)))+(((X (2:Fin 3) : MvPolynomial (Fin 3) ℂ)^2)*(X (1:Fin 3) : MvPolynomial (Fin 3) ℂ)))).degreeOf (0:Fin 3)≤2 := dadd (h14.trans (by omega)) (h15.trans (by omega)) + have h17 : ((C (2*(q^2-q^6)) : MvPolynomial (Fin 3) ℂ)).degreeOf (0:Fin 3)≤0 := le_of_eq (degreeOf_C _ _) + have h18 : (((C (2*(q^2-q^6)) : MvPolynomial (Fin 3) ℂ)*(X (0:Fin 3) : MvPolynomial (Fin 3) ℂ))).degreeOf (0:Fin 3)≤1 := dmul h17 h0 + have h19 : ((((C (2*(q^2-q^6)) : MvPolynomial (Fin 3) ℂ)*(X (0:Fin 3) : MvPolynomial (Fin 3) ℂ))*(X (1:Fin 3) : MvPolynomial (Fin 3) ℂ))).degreeOf (0:Fin 3)≤1 := dmul h18 h2 + have h20 : (((((C (2*(q^2-q^6)) : MvPolynomial (Fin 3) ℂ)*(X (0:Fin 3) : MvPolynomial (Fin 3) ℂ))*(X (1:Fin 3) : MvPolynomial (Fin 3) ℂ))*(X (2:Fin 3) : MvPolynomial (Fin 3) ℂ))).degreeOf (0:Fin 3)≤1 := dmul h19 h4 + have h21 : ((((((((((X (0:Fin 3) : MvPolynomial (Fin 3) ℂ)^2)*(X (1:Fin 3) : MvPolynomial (Fin 3) ℂ))+(((X (0:Fin 3) : MvPolynomial (Fin 3) ℂ)^2)*(X (2:Fin 3) : MvPolynomial (Fin 3) ℂ)))+(((X (1:Fin 3) : MvPolynomial (Fin 3) ℂ)^2)*(X (0:Fin 3) : MvPolynomial (Fin 3) ℂ)))+(((X (1:Fin 3) : MvPolynomial (Fin 3) ℂ)^2)*(X (2:Fin 3) : MvPolynomial (Fin 3) ℂ)))+(((X (2:Fin 3) : MvPolynomial (Fin 3) ℂ)^2)*(X (0:Fin 3) : MvPolynomial (Fin 3) ℂ)))+(((X (2:Fin 3) : MvPolynomial (Fin 3) ℂ)^2)*(X (1:Fin 3) : MvPolynomial (Fin 3) ℂ)))+((((C (2*(q^2-q^6)) : MvPolynomial (Fin 3) ℂ)*(X (0:Fin 3) : MvPolynomial (Fin 3) ℂ))*(X (1:Fin 3) : MvPolynomial (Fin 3) ℂ))*(X (2:Fin 3) : MvPolynomial (Fin 3) ℂ)))).degreeOf (0:Fin 3)≤2 := dadd (h16.trans (by omega)) (h20.trans (by omega)) + simpa only [basePolyThree,basePolyThreeFactor,basePolyTwo] using h21 + +theorem basePolyThree_bound_0_1 : + (basePolyThree (X (0:Fin 3)) (X 1) (X 2) .zero .zero .zero).degreeOf 1 ≤ 2 := by + have h0 : ((X (0:Fin 3) : MvPolynomial (Fin 3) ℂ)).degreeOf (1:Fin 3)≤0 := by simp [degreeOf_X] + have h1 : (((X (0:Fin 3) : MvPolynomial (Fin 3) ℂ)^2)).degreeOf (1:Fin 3)≤0 := dpow h0 2 + have h2 : ((X (1:Fin 3) : MvPolynomial (Fin 3) ℂ)).degreeOf (1:Fin 3)≤1 := by simp + have h3 : ((((X (0:Fin 3) : MvPolynomial (Fin 3) ℂ)^2)*(X (1:Fin 3) : MvPolynomial (Fin 3) ℂ))).degreeOf (1:Fin 3)≤1 := dmul h1 h2 + have h4 : ((X (2:Fin 3) : MvPolynomial (Fin 3) ℂ)).degreeOf (1:Fin 3)≤0 := by simp [degreeOf_X] + have h5 : ((((X (0:Fin 3) : MvPolynomial (Fin 3) ℂ)^2)*(X (2:Fin 3) : MvPolynomial (Fin 3) ℂ))).degreeOf (1:Fin 3)≤0 := dmul h1 h4 + have h6 : (((((X (0:Fin 3) : MvPolynomial (Fin 3) ℂ)^2)*(X (1:Fin 3) : MvPolynomial (Fin 3) ℂ))+(((X (0:Fin 3) : MvPolynomial (Fin 3) ℂ)^2)*(X (2:Fin 3) : MvPolynomial (Fin 3) ℂ)))).degreeOf (1:Fin 3)≤1 := dadd (h3.trans (by omega)) (h5.trans (by omega)) + have h7 : (((X (1:Fin 3) : MvPolynomial (Fin 3) ℂ)^2)).degreeOf (1:Fin 3)≤2 := dpow h2 2 + have h8 : ((((X (1:Fin 3) : MvPolynomial (Fin 3) ℂ)^2)*(X (0:Fin 3) : MvPolynomial (Fin 3) ℂ))).degreeOf (1:Fin 3)≤2 := dmul h7 h0 + have h9 : ((((((X (0:Fin 3) : MvPolynomial (Fin 3) ℂ)^2)*(X (1:Fin 3) : MvPolynomial (Fin 3) ℂ))+(((X (0:Fin 3) : MvPolynomial (Fin 3) ℂ)^2)*(X (2:Fin 3) : MvPolynomial (Fin 3) ℂ)))+(((X (1:Fin 3) : MvPolynomial (Fin 3) ℂ)^2)*(X (0:Fin 3) : MvPolynomial (Fin 3) ℂ)))).degreeOf (1:Fin 3)≤2 := dadd (h6.trans (by omega)) (h8.trans (by omega)) + have h10 : ((((X (1:Fin 3) : MvPolynomial (Fin 3) ℂ)^2)*(X (2:Fin 3) : MvPolynomial (Fin 3) ℂ))).degreeOf (1:Fin 3)≤2 := dmul h7 h4 + have h11 : (((((((X (0:Fin 3) : MvPolynomial (Fin 3) ℂ)^2)*(X (1:Fin 3) : MvPolynomial (Fin 3) ℂ))+(((X (0:Fin 3) : MvPolynomial (Fin 3) ℂ)^2)*(X (2:Fin 3) : MvPolynomial (Fin 3) ℂ)))+(((X (1:Fin 3) : MvPolynomial (Fin 3) ℂ)^2)*(X (0:Fin 3) : MvPolynomial (Fin 3) ℂ)))+(((X (1:Fin 3) : MvPolynomial (Fin 3) ℂ)^2)*(X (2:Fin 3) : MvPolynomial (Fin 3) ℂ)))).degreeOf (1:Fin 3)≤2 := dadd (h9.trans (by omega)) (h10.trans (by omega)) + have h12 : (((X (2:Fin 3) : MvPolynomial (Fin 3) ℂ)^2)).degreeOf (1:Fin 3)≤0 := dpow h4 2 + have h13 : ((((X (2:Fin 3) : MvPolynomial (Fin 3) ℂ)^2)*(X (0:Fin 3) : MvPolynomial (Fin 3) ℂ))).degreeOf (1:Fin 3)≤0 := dmul h12 h0 + have h14 : ((((((((X (0:Fin 3) : MvPolynomial (Fin 3) ℂ)^2)*(X (1:Fin 3) : MvPolynomial (Fin 3) ℂ))+(((X (0:Fin 3) : MvPolynomial (Fin 3) ℂ)^2)*(X (2:Fin 3) : MvPolynomial (Fin 3) ℂ)))+(((X (1:Fin 3) : MvPolynomial (Fin 3) ℂ)^2)*(X (0:Fin 3) : MvPolynomial (Fin 3) ℂ)))+(((X (1:Fin 3) : MvPolynomial (Fin 3) ℂ)^2)*(X (2:Fin 3) : MvPolynomial (Fin 3) ℂ)))+(((X (2:Fin 3) : MvPolynomial (Fin 3) ℂ)^2)*(X (0:Fin 3) : MvPolynomial (Fin 3) ℂ)))).degreeOf (1:Fin 3)≤2 := dadd (h11.trans (by omega)) (h13.trans (by omega)) + have h15 : ((((X (2:Fin 3) : MvPolynomial (Fin 3) ℂ)^2)*(X (1:Fin 3) : MvPolynomial (Fin 3) ℂ))).degreeOf (1:Fin 3)≤1 := dmul h12 h2 + have h16 : (((((((((X (0:Fin 3) : MvPolynomial (Fin 3) ℂ)^2)*(X (1:Fin 3) : MvPolynomial (Fin 3) ℂ))+(((X (0:Fin 3) : MvPolynomial (Fin 3) ℂ)^2)*(X (2:Fin 3) : MvPolynomial (Fin 3) ℂ)))+(((X (1:Fin 3) : MvPolynomial (Fin 3) ℂ)^2)*(X (0:Fin 3) : MvPolynomial (Fin 3) ℂ)))+(((X (1:Fin 3) : MvPolynomial (Fin 3) ℂ)^2)*(X (2:Fin 3) : MvPolynomial (Fin 3) ℂ)))+(((X (2:Fin 3) : MvPolynomial (Fin 3) ℂ)^2)*(X (0:Fin 3) : MvPolynomial (Fin 3) ℂ)))+(((X (2:Fin 3) : MvPolynomial (Fin 3) ℂ)^2)*(X (1:Fin 3) : MvPolynomial (Fin 3) ℂ)))).degreeOf (1:Fin 3)≤2 := dadd (h14.trans (by omega)) (h15.trans (by omega)) + have h17 : ((C (2*(q^2-q^6)) : MvPolynomial (Fin 3) ℂ)).degreeOf (1:Fin 3)≤0 := le_of_eq (degreeOf_C _ _) + have h18 : (((C (2*(q^2-q^6)) : MvPolynomial (Fin 3) ℂ)*(X (0:Fin 3) : MvPolynomial (Fin 3) ℂ))).degreeOf (1:Fin 3)≤0 := dmul h17 h0 + have h19 : ((((C (2*(q^2-q^6)) : MvPolynomial (Fin 3) ℂ)*(X (0:Fin 3) : MvPolynomial (Fin 3) ℂ))*(X (1:Fin 3) : MvPolynomial (Fin 3) ℂ))).degreeOf (1:Fin 3)≤1 := dmul h18 h2 + have h20 : (((((C (2*(q^2-q^6)) : MvPolynomial (Fin 3) ℂ)*(X (0:Fin 3) : MvPolynomial (Fin 3) ℂ))*(X (1:Fin 3) : MvPolynomial (Fin 3) ℂ))*(X (2:Fin 3) : MvPolynomial (Fin 3) ℂ))).degreeOf (1:Fin 3)≤1 := dmul h19 h4 + have h21 : ((((((((((X (0:Fin 3) : MvPolynomial (Fin 3) ℂ)^2)*(X (1:Fin 3) : MvPolynomial (Fin 3) ℂ))+(((X (0:Fin 3) : MvPolynomial (Fin 3) ℂ)^2)*(X (2:Fin 3) : MvPolynomial (Fin 3) ℂ)))+(((X (1:Fin 3) : MvPolynomial (Fin 3) ℂ)^2)*(X (0:Fin 3) : MvPolynomial (Fin 3) ℂ)))+(((X (1:Fin 3) : MvPolynomial (Fin 3) ℂ)^2)*(X (2:Fin 3) : MvPolynomial (Fin 3) ℂ)))+(((X (2:Fin 3) : MvPolynomial (Fin 3) ℂ)^2)*(X (0:Fin 3) : MvPolynomial (Fin 3) ℂ)))+(((X (2:Fin 3) : MvPolynomial (Fin 3) ℂ)^2)*(X (1:Fin 3) : MvPolynomial (Fin 3) ℂ)))+((((C (2*(q^2-q^6)) : MvPolynomial (Fin 3) ℂ)*(X (0:Fin 3) : MvPolynomial (Fin 3) ℂ))*(X (1:Fin 3) : MvPolynomial (Fin 3) ℂ))*(X (2:Fin 3) : MvPolynomial (Fin 3) ℂ)))).degreeOf (1:Fin 3)≤2 := dadd (h16.trans (by omega)) (h20.trans (by omega)) + simpa only [basePolyThree,basePolyThreeFactor,basePolyTwo] using h21 + +theorem basePolyThree_bound_0_2 : + (basePolyThree (X (0:Fin 3)) (X 1) (X 2) .zero .zero .zero).degreeOf 2 ≤ 2 := by + have h0 : ((X (0:Fin 3) : MvPolynomial (Fin 3) ℂ)).degreeOf (2:Fin 3)≤0 := by simp [degreeOf_X] + have h1 : (((X (0:Fin 3) : MvPolynomial (Fin 3) ℂ)^2)).degreeOf (2:Fin 3)≤0 := dpow h0 2 + have h2 : ((X (1:Fin 3) : MvPolynomial (Fin 3) ℂ)).degreeOf (2:Fin 3)≤0 := by simp [degreeOf_X] + have h3 : ((((X (0:Fin 3) : MvPolynomial (Fin 3) ℂ)^2)*(X (1:Fin 3) : MvPolynomial (Fin 3) ℂ))).degreeOf (2:Fin 3)≤0 := dmul h1 h2 + have h4 : ((X (2:Fin 3) : MvPolynomial (Fin 3) ℂ)).degreeOf (2:Fin 3)≤1 := by simp + have h5 : ((((X (0:Fin 3) : MvPolynomial (Fin 3) ℂ)^2)*(X (2:Fin 3) : MvPolynomial (Fin 3) ℂ))).degreeOf (2:Fin 3)≤1 := dmul h1 h4 + have h6 : (((((X (0:Fin 3) : MvPolynomial (Fin 3) ℂ)^2)*(X (1:Fin 3) : MvPolynomial (Fin 3) ℂ))+(((X (0:Fin 3) : MvPolynomial (Fin 3) ℂ)^2)*(X (2:Fin 3) : MvPolynomial (Fin 3) ℂ)))).degreeOf (2:Fin 3)≤1 := dadd (h3.trans (by omega)) (h5.trans (by omega)) + have h7 : (((X (1:Fin 3) : MvPolynomial (Fin 3) ℂ)^2)).degreeOf (2:Fin 3)≤0 := dpow h2 2 + have h8 : ((((X (1:Fin 3) : MvPolynomial (Fin 3) ℂ)^2)*(X (0:Fin 3) : MvPolynomial (Fin 3) ℂ))).degreeOf (2:Fin 3)≤0 := dmul h7 h0 + have h9 : ((((((X (0:Fin 3) : MvPolynomial (Fin 3) ℂ)^2)*(X (1:Fin 3) : MvPolynomial (Fin 3) ℂ))+(((X (0:Fin 3) : MvPolynomial (Fin 3) ℂ)^2)*(X (2:Fin 3) : MvPolynomial (Fin 3) ℂ)))+(((X (1:Fin 3) : MvPolynomial (Fin 3) ℂ)^2)*(X (0:Fin 3) : MvPolynomial (Fin 3) ℂ)))).degreeOf (2:Fin 3)≤1 := dadd (h6.trans (by omega)) (h8.trans (by omega)) + have h10 : ((((X (1:Fin 3) : MvPolynomial (Fin 3) ℂ)^2)*(X (2:Fin 3) : MvPolynomial (Fin 3) ℂ))).degreeOf (2:Fin 3)≤1 := dmul h7 h4 + have h11 : (((((((X (0:Fin 3) : MvPolynomial (Fin 3) ℂ)^2)*(X (1:Fin 3) : MvPolynomial (Fin 3) ℂ))+(((X (0:Fin 3) : MvPolynomial (Fin 3) ℂ)^2)*(X (2:Fin 3) : MvPolynomial (Fin 3) ℂ)))+(((X (1:Fin 3) : MvPolynomial (Fin 3) ℂ)^2)*(X (0:Fin 3) : MvPolynomial (Fin 3) ℂ)))+(((X (1:Fin 3) : MvPolynomial (Fin 3) ℂ)^2)*(X (2:Fin 3) : MvPolynomial (Fin 3) ℂ)))).degreeOf (2:Fin 3)≤1 := dadd (h9.trans (by omega)) (h10.trans (by omega)) + have h12 : (((X (2:Fin 3) : MvPolynomial (Fin 3) ℂ)^2)).degreeOf (2:Fin 3)≤2 := dpow h4 2 + have h13 : ((((X (2:Fin 3) : MvPolynomial (Fin 3) ℂ)^2)*(X (0:Fin 3) : MvPolynomial (Fin 3) ℂ))).degreeOf (2:Fin 3)≤2 := dmul h12 h0 + have h14 : ((((((((X (0:Fin 3) : MvPolynomial (Fin 3) ℂ)^2)*(X (1:Fin 3) : MvPolynomial (Fin 3) ℂ))+(((X (0:Fin 3) : MvPolynomial (Fin 3) ℂ)^2)*(X (2:Fin 3) : MvPolynomial (Fin 3) ℂ)))+(((X (1:Fin 3) : MvPolynomial (Fin 3) ℂ)^2)*(X (0:Fin 3) : MvPolynomial (Fin 3) ℂ)))+(((X (1:Fin 3) : MvPolynomial (Fin 3) ℂ)^2)*(X (2:Fin 3) : MvPolynomial (Fin 3) ℂ)))+(((X (2:Fin 3) : MvPolynomial (Fin 3) ℂ)^2)*(X (0:Fin 3) : MvPolynomial (Fin 3) ℂ)))).degreeOf (2:Fin 3)≤2 := dadd (h11.trans (by omega)) (h13.trans (by omega)) + have h15 : ((((X (2:Fin 3) : MvPolynomial (Fin 3) ℂ)^2)*(X (1:Fin 3) : MvPolynomial (Fin 3) ℂ))).degreeOf (2:Fin 3)≤2 := dmul h12 h2 + have h16 : (((((((((X (0:Fin 3) : MvPolynomial (Fin 3) ℂ)^2)*(X (1:Fin 3) : MvPolynomial (Fin 3) ℂ))+(((X (0:Fin 3) : MvPolynomial (Fin 3) ℂ)^2)*(X (2:Fin 3) : MvPolynomial (Fin 3) ℂ)))+(((X (1:Fin 3) : MvPolynomial (Fin 3) ℂ)^2)*(X (0:Fin 3) : MvPolynomial (Fin 3) ℂ)))+(((X (1:Fin 3) : MvPolynomial (Fin 3) ℂ)^2)*(X (2:Fin 3) : MvPolynomial (Fin 3) ℂ)))+(((X (2:Fin 3) : MvPolynomial (Fin 3) ℂ)^2)*(X (0:Fin 3) : MvPolynomial (Fin 3) ℂ)))+(((X (2:Fin 3) : MvPolynomial (Fin 3) ℂ)^2)*(X (1:Fin 3) : MvPolynomial (Fin 3) ℂ)))).degreeOf (2:Fin 3)≤2 := dadd (h14.trans (by omega)) (h15.trans (by omega)) + have h17 : ((C (2*(q^2-q^6)) : MvPolynomial (Fin 3) ℂ)).degreeOf (2:Fin 3)≤0 := le_of_eq (degreeOf_C _ _) + have h18 : (((C (2*(q^2-q^6)) : MvPolynomial (Fin 3) ℂ)*(X (0:Fin 3) : MvPolynomial (Fin 3) ℂ))).degreeOf (2:Fin 3)≤0 := dmul h17 h0 + have h19 : ((((C (2*(q^2-q^6)) : MvPolynomial (Fin 3) ℂ)*(X (0:Fin 3) : MvPolynomial (Fin 3) ℂ))*(X (1:Fin 3) : MvPolynomial (Fin 3) ℂ))).degreeOf (2:Fin 3)≤0 := dmul h18 h2 + have h20 : (((((C (2*(q^2-q^6)) : MvPolynomial (Fin 3) ℂ)*(X (0:Fin 3) : MvPolynomial (Fin 3) ℂ))*(X (1:Fin 3) : MvPolynomial (Fin 3) ℂ))*(X (2:Fin 3) : MvPolynomial (Fin 3) ℂ))).degreeOf (2:Fin 3)≤1 := dmul h19 h4 + have h21 : ((((((((((X (0:Fin 3) : MvPolynomial (Fin 3) ℂ)^2)*(X (1:Fin 3) : MvPolynomial (Fin 3) ℂ))+(((X (0:Fin 3) : MvPolynomial (Fin 3) ℂ)^2)*(X (2:Fin 3) : MvPolynomial (Fin 3) ℂ)))+(((X (1:Fin 3) : MvPolynomial (Fin 3) ℂ)^2)*(X (0:Fin 3) : MvPolynomial (Fin 3) ℂ)))+(((X (1:Fin 3) : MvPolynomial (Fin 3) ℂ)^2)*(X (2:Fin 3) : MvPolynomial (Fin 3) ℂ)))+(((X (2:Fin 3) : MvPolynomial (Fin 3) ℂ)^2)*(X (0:Fin 3) : MvPolynomial (Fin 3) ℂ)))+(((X (2:Fin 3) : MvPolynomial (Fin 3) ℂ)^2)*(X (1:Fin 3) : MvPolynomial (Fin 3) ℂ)))+((((C (2*(q^2-q^6)) : MvPolynomial (Fin 3) ℂ)*(X (0:Fin 3) : MvPolynomial (Fin 3) ℂ))*(X (1:Fin 3) : MvPolynomial (Fin 3) ℂ))*(X (2:Fin 3) : MvPolynomial (Fin 3) ℂ)))).degreeOf (2:Fin 3)≤2 := dadd (h16.trans (by omega)) (h20.trans (by omega)) + simpa only [basePolyThree,basePolyThreeFactor,basePolyTwo] using h21 + +theorem basePolyThree_bound_1_0 : + (basePolyThree (X (0:Fin 3)) (X 1) (X 2) .plus .minus .zero).degreeOf 0 ≤ 1 := by + have h0 : ((C (q^5-q^7) : MvPolynomial (Fin 3) ℂ)).degreeOf (0:Fin 3)≤0 := le_of_eq (degreeOf_C _ _) + have h1 : ((X (1:Fin 3) : MvPolynomial (Fin 3) ℂ)).degreeOf (0:Fin 3)≤0 := by simp [degreeOf_X] + have h2 : (((C (q^5-q^7) : MvPolynomial (Fin 3) ℂ)*(X (1:Fin 3) : MvPolynomial (Fin 3) ℂ))).degreeOf (0:Fin 3)≤0 := dmul h0 h1 + have h3 : ((X (2:Fin 3) : MvPolynomial (Fin 3) ℂ)).degreeOf (0:Fin 3)≤0 := by simp [degreeOf_X] + have h4 : ((C (q^2) : MvPolynomial (Fin 3) ℂ)).degreeOf (0:Fin 3)≤0 := le_of_eq (degreeOf_C _ _) + have h5 : ((X (0:Fin 3) : MvPolynomial (Fin 3) ℂ)).degreeOf (0:Fin 3)≤1 := by simp + have h6 : (((C (q^2) : MvPolynomial (Fin 3) ℂ)*(X (0:Fin 3) : MvPolynomial (Fin 3) ℂ))).degreeOf (0:Fin 3)≤1 := dmul h4 h5 + have h7 : (((X (2:Fin 3) : MvPolynomial (Fin 3) ℂ)+((C (q^2) : MvPolynomial (Fin 3) ℂ)*(X (0:Fin 3) : MvPolynomial (Fin 3) ℂ)))).degreeOf (0:Fin 3)≤1 := dadd (h3.trans (by omega)) (h6.trans (by omega)) + have h8 : ((C (q^6) : MvPolynomial (Fin 3) ℂ)).degreeOf (0:Fin 3)≤0 := le_of_eq (degreeOf_C _ _) + have h9 : (((C (q^6) : MvPolynomial (Fin 3) ℂ)*(X (1:Fin 3) : MvPolynomial (Fin 3) ℂ))).degreeOf (0:Fin 3)≤0 := dmul h8 h1 + have h10 : (((X (2:Fin 3) : MvPolynomial (Fin 3) ℂ)-((C (q^6) : MvPolynomial (Fin 3) ℂ)*(X (1:Fin 3) : MvPolynomial (Fin 3) ℂ)))).degreeOf (0:Fin 3)≤0 := (degreeOf_sub_le _ _ _).trans (max_le (h3.trans (by omega)) (h9.trans (by omega))) + have h11 : ((((X (2:Fin 3) : MvPolynomial (Fin 3) ℂ)+((C (q^2) : MvPolynomial (Fin 3) ℂ)*(X (0:Fin 3) : MvPolynomial (Fin 3) ℂ)))*((X (2:Fin 3) : MvPolynomial (Fin 3) ℂ)-((C (q^6) : MvPolynomial (Fin 3) ℂ)*(X (1:Fin 3) : MvPolynomial (Fin 3) ℂ))))).degreeOf (0:Fin 3)≤1 := dmul h7 h10 + have h12 : ((((C (q^5-q^7) : MvPolynomial (Fin 3) ℂ)*(X (1:Fin 3) : MvPolynomial (Fin 3) ℂ))*(((X (2:Fin 3) : MvPolynomial (Fin 3) ℂ)+((C (q^2) : MvPolynomial (Fin 3) ℂ)*(X (0:Fin 3) : MvPolynomial (Fin 3) ℂ)))*((X (2:Fin 3) : MvPolynomial (Fin 3) ℂ)-((C (q^6) : MvPolynomial (Fin 3) ℂ)*(X (1:Fin 3) : MvPolynomial (Fin 3) ℂ)))))).degreeOf (0:Fin 3)≤1 := dmul h2 h11 + simpa only [basePolyThree,basePolyThreeFactor,basePolyTwo] using h12 + +theorem basePolyThree_bound_1_1 : + (basePolyThree (X (0:Fin 3)) (X 1) (X 2) .plus .minus .zero).degreeOf 1 ≤ 2 := by + have h0 : ((C (q^5-q^7) : MvPolynomial (Fin 3) ℂ)).degreeOf (1:Fin 3)≤0 := le_of_eq (degreeOf_C _ _) + have h1 : ((X (1:Fin 3) : MvPolynomial (Fin 3) ℂ)).degreeOf (1:Fin 3)≤1 := by simp + have h2 : (((C (q^5-q^7) : MvPolynomial (Fin 3) ℂ)*(X (1:Fin 3) : MvPolynomial (Fin 3) ℂ))).degreeOf (1:Fin 3)≤1 := dmul h0 h1 + have h3 : ((X (2:Fin 3) : MvPolynomial (Fin 3) ℂ)).degreeOf (1:Fin 3)≤0 := by simp [degreeOf_X] + have h4 : ((C (q^2) : MvPolynomial (Fin 3) ℂ)).degreeOf (1:Fin 3)≤0 := le_of_eq (degreeOf_C _ _) + have h5 : ((X (0:Fin 3) : MvPolynomial (Fin 3) ℂ)).degreeOf (1:Fin 3)≤0 := by simp [degreeOf_X] + have h6 : (((C (q^2) : MvPolynomial (Fin 3) ℂ)*(X (0:Fin 3) : MvPolynomial (Fin 3) ℂ))).degreeOf (1:Fin 3)≤0 := dmul h4 h5 + have h7 : (((X (2:Fin 3) : MvPolynomial (Fin 3) ℂ)+((C (q^2) : MvPolynomial (Fin 3) ℂ)*(X (0:Fin 3) : MvPolynomial (Fin 3) ℂ)))).degreeOf (1:Fin 3)≤0 := dadd (h3.trans (by omega)) (h6.trans (by omega)) + have h8 : ((C (q^6) : MvPolynomial (Fin 3) ℂ)).degreeOf (1:Fin 3)≤0 := le_of_eq (degreeOf_C _ _) + have h9 : (((C (q^6) : MvPolynomial (Fin 3) ℂ)*(X (1:Fin 3) : MvPolynomial (Fin 3) ℂ))).degreeOf (1:Fin 3)≤1 := dmul h8 h1 + have h10 : (((X (2:Fin 3) : MvPolynomial (Fin 3) ℂ)-((C (q^6) : MvPolynomial (Fin 3) ℂ)*(X (1:Fin 3) : MvPolynomial (Fin 3) ℂ)))).degreeOf (1:Fin 3)≤1 := (degreeOf_sub_le _ _ _).trans (max_le (h3.trans (by omega)) (h9.trans (by omega))) + have h11 : ((((X (2:Fin 3) : MvPolynomial (Fin 3) ℂ)+((C (q^2) : MvPolynomial (Fin 3) ℂ)*(X (0:Fin 3) : MvPolynomial (Fin 3) ℂ)))*((X (2:Fin 3) : MvPolynomial (Fin 3) ℂ)-((C (q^6) : MvPolynomial (Fin 3) ℂ)*(X (1:Fin 3) : MvPolynomial (Fin 3) ℂ))))).degreeOf (1:Fin 3)≤1 := dmul h7 h10 + have h12 : ((((C (q^5-q^7) : MvPolynomial (Fin 3) ℂ)*(X (1:Fin 3) : MvPolynomial (Fin 3) ℂ))*(((X (2:Fin 3) : MvPolynomial (Fin 3) ℂ)+((C (q^2) : MvPolynomial (Fin 3) ℂ)*(X (0:Fin 3) : MvPolynomial (Fin 3) ℂ)))*((X (2:Fin 3) : MvPolynomial (Fin 3) ℂ)-((C (q^6) : MvPolynomial (Fin 3) ℂ)*(X (1:Fin 3) : MvPolynomial (Fin 3) ℂ)))))).degreeOf (1:Fin 3)≤2 := dmul h2 h11 + simpa only [basePolyThree,basePolyThreeFactor,basePolyTwo] using h12 + +theorem basePolyThree_bound_1_2 : + (basePolyThree (X (0:Fin 3)) (X 1) (X 2) .plus .minus .zero).degreeOf 2 ≤ 2 := by + have h0 : ((C (q^5-q^7) : MvPolynomial (Fin 3) ℂ)).degreeOf (2:Fin 3)≤0 := le_of_eq (degreeOf_C _ _) + have h1 : ((X (1:Fin 3) : MvPolynomial (Fin 3) ℂ)).degreeOf (2:Fin 3)≤0 := by simp [degreeOf_X] + have h2 : (((C (q^5-q^7) : MvPolynomial (Fin 3) ℂ)*(X (1:Fin 3) : MvPolynomial (Fin 3) ℂ))).degreeOf (2:Fin 3)≤0 := dmul h0 h1 + have h3 : ((X (2:Fin 3) : MvPolynomial (Fin 3) ℂ)).degreeOf (2:Fin 3)≤1 := by simp + have h4 : ((C (q^2) : MvPolynomial (Fin 3) ℂ)).degreeOf (2:Fin 3)≤0 := le_of_eq (degreeOf_C _ _) + have h5 : ((X (0:Fin 3) : MvPolynomial (Fin 3) ℂ)).degreeOf (2:Fin 3)≤0 := by simp [degreeOf_X] + have h6 : (((C (q^2) : MvPolynomial (Fin 3) ℂ)*(X (0:Fin 3) : MvPolynomial (Fin 3) ℂ))).degreeOf (2:Fin 3)≤0 := dmul h4 h5 + have h7 : (((X (2:Fin 3) : MvPolynomial (Fin 3) ℂ)+((C (q^2) : MvPolynomial (Fin 3) ℂ)*(X (0:Fin 3) : MvPolynomial (Fin 3) ℂ)))).degreeOf (2:Fin 3)≤1 := dadd (h3.trans (by omega)) (h6.trans (by omega)) + have h8 : ((C (q^6) : MvPolynomial (Fin 3) ℂ)).degreeOf (2:Fin 3)≤0 := le_of_eq (degreeOf_C _ _) + have h9 : (((C (q^6) : MvPolynomial (Fin 3) ℂ)*(X (1:Fin 3) : MvPolynomial (Fin 3) ℂ))).degreeOf (2:Fin 3)≤0 := dmul h8 h1 + have h10 : (((X (2:Fin 3) : MvPolynomial (Fin 3) ℂ)-((C (q^6) : MvPolynomial (Fin 3) ℂ)*(X (1:Fin 3) : MvPolynomial (Fin 3) ℂ)))).degreeOf (2:Fin 3)≤1 := (degreeOf_sub_le _ _ _).trans (max_le (h3.trans (by omega)) (h9.trans (by omega))) + have h11 : ((((X (2:Fin 3) : MvPolynomial (Fin 3) ℂ)+((C (q^2) : MvPolynomial (Fin 3) ℂ)*(X (0:Fin 3) : MvPolynomial (Fin 3) ℂ)))*((X (2:Fin 3) : MvPolynomial (Fin 3) ℂ)-((C (q^6) : MvPolynomial (Fin 3) ℂ)*(X (1:Fin 3) : MvPolynomial (Fin 3) ℂ))))).degreeOf (2:Fin 3)≤2 := dmul h7 h10 + have h12 : ((((C (q^5-q^7) : MvPolynomial (Fin 3) ℂ)*(X (1:Fin 3) : MvPolynomial (Fin 3) ℂ))*(((X (2:Fin 3) : MvPolynomial (Fin 3) ℂ)+((C (q^2) : MvPolynomial (Fin 3) ℂ)*(X (0:Fin 3) : MvPolynomial (Fin 3) ℂ)))*((X (2:Fin 3) : MvPolynomial (Fin 3) ℂ)-((C (q^6) : MvPolynomial (Fin 3) ℂ)*(X (1:Fin 3) : MvPolynomial (Fin 3) ℂ)))))).degreeOf (2:Fin 3)≤2 := dmul h2 h11 + simpa only [basePolyThree,basePolyThreeFactor,basePolyTwo] using h12 + +theorem basePolyThree_bound_2_0 : + (basePolyThree (X (0:Fin 3)) (X 1) (X 2) .minus .plus .zero).degreeOf 0 ≤ 2 := by + have h0 : ((C (q-q^3) : MvPolynomial (Fin 3) ℂ)).degreeOf (0:Fin 3)≤0 := le_of_eq (degreeOf_C _ _) + have h1 : ((X (0:Fin 3) : MvPolynomial (Fin 3) ℂ)).degreeOf (0:Fin 3)≤1 := by simp + have h2 : (((C (q-q^3) : MvPolynomial (Fin 3) ℂ)*(X (0:Fin 3) : MvPolynomial (Fin 3) ℂ))).degreeOf (0:Fin 3)≤1 := dmul h0 h1 + have h3 : ((X (2:Fin 3) : MvPolynomial (Fin 3) ℂ)).degreeOf (0:Fin 3)≤0 := by simp [degreeOf_X] + have h4 : ((C (q^2) : MvPolynomial (Fin 3) ℂ)).degreeOf (0:Fin 3)≤0 := le_of_eq (degreeOf_C _ _) + have h5 : (((C (q^2) : MvPolynomial (Fin 3) ℂ)*(X (0:Fin 3) : MvPolynomial (Fin 3) ℂ))).degreeOf (0:Fin 3)≤1 := dmul h4 h1 + have h6 : (((X (2:Fin 3) : MvPolynomial (Fin 3) ℂ)+((C (q^2) : MvPolynomial (Fin 3) ℂ)*(X (0:Fin 3) : MvPolynomial (Fin 3) ℂ)))).degreeOf (0:Fin 3)≤1 := dadd (h3.trans (by omega)) (h5.trans (by omega)) + have h7 : ((C (q^6) : MvPolynomial (Fin 3) ℂ)).degreeOf (0:Fin 3)≤0 := le_of_eq (degreeOf_C _ _) + have h8 : ((X (1:Fin 3) : MvPolynomial (Fin 3) ℂ)).degreeOf (0:Fin 3)≤0 := by simp [degreeOf_X] + have h9 : (((C (q^6) : MvPolynomial (Fin 3) ℂ)*(X (1:Fin 3) : MvPolynomial (Fin 3) ℂ))).degreeOf (0:Fin 3)≤0 := dmul h7 h8 + have h10 : (((X (2:Fin 3) : MvPolynomial (Fin 3) ℂ)-((C (q^6) : MvPolynomial (Fin 3) ℂ)*(X (1:Fin 3) : MvPolynomial (Fin 3) ℂ)))).degreeOf (0:Fin 3)≤0 := (degreeOf_sub_le _ _ _).trans (max_le (h3.trans (by omega)) (h9.trans (by omega))) + have h11 : ((((X (2:Fin 3) : MvPolynomial (Fin 3) ℂ)+((C (q^2) : MvPolynomial (Fin 3) ℂ)*(X (0:Fin 3) : MvPolynomial (Fin 3) ℂ)))*((X (2:Fin 3) : MvPolynomial (Fin 3) ℂ)-((C (q^6) : MvPolynomial (Fin 3) ℂ)*(X (1:Fin 3) : MvPolynomial (Fin 3) ℂ))))).degreeOf (0:Fin 3)≤1 := dmul h6 h10 + have h12 : ((((C (q-q^3) : MvPolynomial (Fin 3) ℂ)*(X (0:Fin 3) : MvPolynomial (Fin 3) ℂ))*(((X (2:Fin 3) : MvPolynomial (Fin 3) ℂ)+((C (q^2) : MvPolynomial (Fin 3) ℂ)*(X (0:Fin 3) : MvPolynomial (Fin 3) ℂ)))*((X (2:Fin 3) : MvPolynomial (Fin 3) ℂ)-((C (q^6) : MvPolynomial (Fin 3) ℂ)*(X (1:Fin 3) : MvPolynomial (Fin 3) ℂ)))))).degreeOf (0:Fin 3)≤2 := dmul h2 h11 + simpa only [basePolyThree,basePolyThreeFactor,basePolyTwo] using h12 + +theorem basePolyThree_bound_2_1 : + (basePolyThree (X (0:Fin 3)) (X 1) (X 2) .minus .plus .zero).degreeOf 1 ≤ 1 := by + have h0 : ((C (q-q^3) : MvPolynomial (Fin 3) ℂ)).degreeOf (1:Fin 3)≤0 := le_of_eq (degreeOf_C _ _) + have h1 : ((X (0:Fin 3) : MvPolynomial (Fin 3) ℂ)).degreeOf (1:Fin 3)≤0 := by simp [degreeOf_X] + have h2 : (((C (q-q^3) : MvPolynomial (Fin 3) ℂ)*(X (0:Fin 3) : MvPolynomial (Fin 3) ℂ))).degreeOf (1:Fin 3)≤0 := dmul h0 h1 + have h3 : ((X (2:Fin 3) : MvPolynomial (Fin 3) ℂ)).degreeOf (1:Fin 3)≤0 := by simp [degreeOf_X] + have h4 : ((C (q^2) : MvPolynomial (Fin 3) ℂ)).degreeOf (1:Fin 3)≤0 := le_of_eq (degreeOf_C _ _) + have h5 : (((C (q^2) : MvPolynomial (Fin 3) ℂ)*(X (0:Fin 3) : MvPolynomial (Fin 3) ℂ))).degreeOf (1:Fin 3)≤0 := dmul h4 h1 + have h6 : (((X (2:Fin 3) : MvPolynomial (Fin 3) ℂ)+((C (q^2) : MvPolynomial (Fin 3) ℂ)*(X (0:Fin 3) : MvPolynomial (Fin 3) ℂ)))).degreeOf (1:Fin 3)≤0 := dadd (h3.trans (by omega)) (h5.trans (by omega)) + have h7 : ((C (q^6) : MvPolynomial (Fin 3) ℂ)).degreeOf (1:Fin 3)≤0 := le_of_eq (degreeOf_C _ _) + have h8 : ((X (1:Fin 3) : MvPolynomial (Fin 3) ℂ)).degreeOf (1:Fin 3)≤1 := by simp + have h9 : (((C (q^6) : MvPolynomial (Fin 3) ℂ)*(X (1:Fin 3) : MvPolynomial (Fin 3) ℂ))).degreeOf (1:Fin 3)≤1 := dmul h7 h8 + have h10 : (((X (2:Fin 3) : MvPolynomial (Fin 3) ℂ)-((C (q^6) : MvPolynomial (Fin 3) ℂ)*(X (1:Fin 3) : MvPolynomial (Fin 3) ℂ)))).degreeOf (1:Fin 3)≤1 := (degreeOf_sub_le _ _ _).trans (max_le (h3.trans (by omega)) (h9.trans (by omega))) + have h11 : ((((X (2:Fin 3) : MvPolynomial (Fin 3) ℂ)+((C (q^2) : MvPolynomial (Fin 3) ℂ)*(X (0:Fin 3) : MvPolynomial (Fin 3) ℂ)))*((X (2:Fin 3) : MvPolynomial (Fin 3) ℂ)-((C (q^6) : MvPolynomial (Fin 3) ℂ)*(X (1:Fin 3) : MvPolynomial (Fin 3) ℂ))))).degreeOf (1:Fin 3)≤1 := dmul h6 h10 + have h12 : ((((C (q-q^3) : MvPolynomial (Fin 3) ℂ)*(X (0:Fin 3) : MvPolynomial (Fin 3) ℂ))*(((X (2:Fin 3) : MvPolynomial (Fin 3) ℂ)+((C (q^2) : MvPolynomial (Fin 3) ℂ)*(X (0:Fin 3) : MvPolynomial (Fin 3) ℂ)))*((X (2:Fin 3) : MvPolynomial (Fin 3) ℂ)-((C (q^6) : MvPolynomial (Fin 3) ℂ)*(X (1:Fin 3) : MvPolynomial (Fin 3) ℂ)))))).degreeOf (1:Fin 3)≤1 := dmul h2 h11 + simpa only [basePolyThree,basePolyThreeFactor,basePolyTwo] using h12 + +theorem basePolyThree_bound_2_2 : + (basePolyThree (X (0:Fin 3)) (X 1) (X 2) .minus .plus .zero).degreeOf 2 ≤ 2 := by + have h0 : ((C (q-q^3) : MvPolynomial (Fin 3) ℂ)).degreeOf (2:Fin 3)≤0 := le_of_eq (degreeOf_C _ _) + have h1 : ((X (0:Fin 3) : MvPolynomial (Fin 3) ℂ)).degreeOf (2:Fin 3)≤0 := by simp [degreeOf_X] + have h2 : (((C (q-q^3) : MvPolynomial (Fin 3) ℂ)*(X (0:Fin 3) : MvPolynomial (Fin 3) ℂ))).degreeOf (2:Fin 3)≤0 := dmul h0 h1 + have h3 : ((X (2:Fin 3) : MvPolynomial (Fin 3) ℂ)).degreeOf (2:Fin 3)≤1 := by simp + have h4 : ((C (q^2) : MvPolynomial (Fin 3) ℂ)).degreeOf (2:Fin 3)≤0 := le_of_eq (degreeOf_C _ _) + have h5 : (((C (q^2) : MvPolynomial (Fin 3) ℂ)*(X (0:Fin 3) : MvPolynomial (Fin 3) ℂ))).degreeOf (2:Fin 3)≤0 := dmul h4 h1 + have h6 : (((X (2:Fin 3) : MvPolynomial (Fin 3) ℂ)+((C (q^2) : MvPolynomial (Fin 3) ℂ)*(X (0:Fin 3) : MvPolynomial (Fin 3) ℂ)))).degreeOf (2:Fin 3)≤1 := dadd (h3.trans (by omega)) (h5.trans (by omega)) + have h7 : ((C (q^6) : MvPolynomial (Fin 3) ℂ)).degreeOf (2:Fin 3)≤0 := le_of_eq (degreeOf_C _ _) + have h8 : ((X (1:Fin 3) : MvPolynomial (Fin 3) ℂ)).degreeOf (2:Fin 3)≤0 := by simp [degreeOf_X] + have h9 : (((C (q^6) : MvPolynomial (Fin 3) ℂ)*(X (1:Fin 3) : MvPolynomial (Fin 3) ℂ))).degreeOf (2:Fin 3)≤0 := dmul h7 h8 + have h10 : (((X (2:Fin 3) : MvPolynomial (Fin 3) ℂ)-((C (q^6) : MvPolynomial (Fin 3) ℂ)*(X (1:Fin 3) : MvPolynomial (Fin 3) ℂ)))).degreeOf (2:Fin 3)≤1 := (degreeOf_sub_le _ _ _).trans (max_le (h3.trans (by omega)) (h9.trans (by omega))) + have h11 : ((((X (2:Fin 3) : MvPolynomial (Fin 3) ℂ)+((C (q^2) : MvPolynomial (Fin 3) ℂ)*(X (0:Fin 3) : MvPolynomial (Fin 3) ℂ)))*((X (2:Fin 3) : MvPolynomial (Fin 3) ℂ)-((C (q^6) : MvPolynomial (Fin 3) ℂ)*(X (1:Fin 3) : MvPolynomial (Fin 3) ℂ))))).degreeOf (2:Fin 3)≤2 := dmul h6 h10 + have h12 : ((((C (q-q^3) : MvPolynomial (Fin 3) ℂ)*(X (0:Fin 3) : MvPolynomial (Fin 3) ℂ))*(((X (2:Fin 3) : MvPolynomial (Fin 3) ℂ)+((C (q^2) : MvPolynomial (Fin 3) ℂ)*(X (0:Fin 3) : MvPolynomial (Fin 3) ℂ)))*((X (2:Fin 3) : MvPolynomial (Fin 3) ℂ)-((C (q^6) : MvPolynomial (Fin 3) ℂ)*(X (1:Fin 3) : MvPolynomial (Fin 3) ℂ)))))).degreeOf (2:Fin 3)≤2 := dmul h2 h11 + simpa only [basePolyThree,basePolyThreeFactor,basePolyTwo] using h12 + +theorem basePolyThree_bound_3_0 : + (basePolyThree (X (0:Fin 3)) (X 1) (X 2) .zero .plus .minus).degreeOf 0 ≤ 2 := by + have h0 : ((C (q^5-q^7) : MvPolynomial (Fin 3) ℂ)).degreeOf (0:Fin 3)≤0 := le_of_eq (degreeOf_C _ _) + have h1 : ((X (2:Fin 3) : MvPolynomial (Fin 3) ℂ)).degreeOf (0:Fin 3)≤0 := by simp [degreeOf_X] + have h2 : (((C (q^5-q^7) : MvPolynomial (Fin 3) ℂ)*(X (2:Fin 3) : MvPolynomial (Fin 3) ℂ))).degreeOf (0:Fin 3)≤0 := dmul h0 h1 + have h3 : ((X (0:Fin 3) : MvPolynomial (Fin 3) ℂ)).degreeOf (0:Fin 3)≤1 := by simp + have h4 : ((C (q^2) : MvPolynomial (Fin 3) ℂ)).degreeOf (0:Fin 3)≤0 := le_of_eq (degreeOf_C _ _) + have h5 : ((X (1:Fin 3) : MvPolynomial (Fin 3) ℂ)).degreeOf (0:Fin 3)≤0 := by simp [degreeOf_X] + have h6 : (((C (q^2) : MvPolynomial (Fin 3) ℂ)*(X (1:Fin 3) : MvPolynomial (Fin 3) ℂ))).degreeOf (0:Fin 3)≤0 := dmul h4 h5 + have h7 : (((X (0:Fin 3) : MvPolynomial (Fin 3) ℂ)+((C (q^2) : MvPolynomial (Fin 3) ℂ)*(X (1:Fin 3) : MvPolynomial (Fin 3) ℂ)))).degreeOf (0:Fin 3)≤1 := dadd (h3.trans (by omega)) (h6.trans (by omega)) + have h8 : ((C (q^6) : MvPolynomial (Fin 3) ℂ)).degreeOf (0:Fin 3)≤0 := le_of_eq (degreeOf_C _ _) + have h9 : (((C (q^6) : MvPolynomial (Fin 3) ℂ)*(X (2:Fin 3) : MvPolynomial (Fin 3) ℂ))).degreeOf (0:Fin 3)≤0 := dmul h8 h1 + have h10 : (((X (0:Fin 3) : MvPolynomial (Fin 3) ℂ)-((C (q^6) : MvPolynomial (Fin 3) ℂ)*(X (2:Fin 3) : MvPolynomial (Fin 3) ℂ)))).degreeOf (0:Fin 3)≤1 := (degreeOf_sub_le _ _ _).trans (max_le (h3.trans (by omega)) (h9.trans (by omega))) + have h11 : ((((X (0:Fin 3) : MvPolynomial (Fin 3) ℂ)+((C (q^2) : MvPolynomial (Fin 3) ℂ)*(X (1:Fin 3) : MvPolynomial (Fin 3) ℂ)))*((X (0:Fin 3) : MvPolynomial (Fin 3) ℂ)-((C (q^6) : MvPolynomial (Fin 3) ℂ)*(X (2:Fin 3) : MvPolynomial (Fin 3) ℂ))))).degreeOf (0:Fin 3)≤2 := dmul h7 h10 + have h12 : ((((C (q^5-q^7) : MvPolynomial (Fin 3) ℂ)*(X (2:Fin 3) : MvPolynomial (Fin 3) ℂ))*(((X (0:Fin 3) : MvPolynomial (Fin 3) ℂ)+((C (q^2) : MvPolynomial (Fin 3) ℂ)*(X (1:Fin 3) : MvPolynomial (Fin 3) ℂ)))*((X (0:Fin 3) : MvPolynomial (Fin 3) ℂ)-((C (q^6) : MvPolynomial (Fin 3) ℂ)*(X (2:Fin 3) : MvPolynomial (Fin 3) ℂ)))))).degreeOf (0:Fin 3)≤2 := dmul h2 h11 + simpa only [basePolyThree,basePolyThreeFactor,basePolyTwo] using h12 + +theorem basePolyThree_bound_3_1 : + (basePolyThree (X (0:Fin 3)) (X 1) (X 2) .zero .plus .minus).degreeOf 1 ≤ 1 := by + have h0 : ((C (q^5-q^7) : MvPolynomial (Fin 3) ℂ)).degreeOf (1:Fin 3)≤0 := le_of_eq (degreeOf_C _ _) + have h1 : ((X (2:Fin 3) : MvPolynomial (Fin 3) ℂ)).degreeOf (1:Fin 3)≤0 := by simp [degreeOf_X] + have h2 : (((C (q^5-q^7) : MvPolynomial (Fin 3) ℂ)*(X (2:Fin 3) : MvPolynomial (Fin 3) ℂ))).degreeOf (1:Fin 3)≤0 := dmul h0 h1 + have h3 : ((X (0:Fin 3) : MvPolynomial (Fin 3) ℂ)).degreeOf (1:Fin 3)≤0 := by simp [degreeOf_X] + have h4 : ((C (q^2) : MvPolynomial (Fin 3) ℂ)).degreeOf (1:Fin 3)≤0 := le_of_eq (degreeOf_C _ _) + have h5 : ((X (1:Fin 3) : MvPolynomial (Fin 3) ℂ)).degreeOf (1:Fin 3)≤1 := by simp + have h6 : (((C (q^2) : MvPolynomial (Fin 3) ℂ)*(X (1:Fin 3) : MvPolynomial (Fin 3) ℂ))).degreeOf (1:Fin 3)≤1 := dmul h4 h5 + have h7 : (((X (0:Fin 3) : MvPolynomial (Fin 3) ℂ)+((C (q^2) : MvPolynomial (Fin 3) ℂ)*(X (1:Fin 3) : MvPolynomial (Fin 3) ℂ)))).degreeOf (1:Fin 3)≤1 := dadd (h3.trans (by omega)) (h6.trans (by omega)) + have h8 : ((C (q^6) : MvPolynomial (Fin 3) ℂ)).degreeOf (1:Fin 3)≤0 := le_of_eq (degreeOf_C _ _) + have h9 : (((C (q^6) : MvPolynomial (Fin 3) ℂ)*(X (2:Fin 3) : MvPolynomial (Fin 3) ℂ))).degreeOf (1:Fin 3)≤0 := dmul h8 h1 + have h10 : (((X (0:Fin 3) : MvPolynomial (Fin 3) ℂ)-((C (q^6) : MvPolynomial (Fin 3) ℂ)*(X (2:Fin 3) : MvPolynomial (Fin 3) ℂ)))).degreeOf (1:Fin 3)≤0 := (degreeOf_sub_le _ _ _).trans (max_le (h3.trans (by omega)) (h9.trans (by omega))) + have h11 : ((((X (0:Fin 3) : MvPolynomial (Fin 3) ℂ)+((C (q^2) : MvPolynomial (Fin 3) ℂ)*(X (1:Fin 3) : MvPolynomial (Fin 3) ℂ)))*((X (0:Fin 3) : MvPolynomial (Fin 3) ℂ)-((C (q^6) : MvPolynomial (Fin 3) ℂ)*(X (2:Fin 3) : MvPolynomial (Fin 3) ℂ))))).degreeOf (1:Fin 3)≤1 := dmul h7 h10 + have h12 : ((((C (q^5-q^7) : MvPolynomial (Fin 3) ℂ)*(X (2:Fin 3) : MvPolynomial (Fin 3) ℂ))*(((X (0:Fin 3) : MvPolynomial (Fin 3) ℂ)+((C (q^2) : MvPolynomial (Fin 3) ℂ)*(X (1:Fin 3) : MvPolynomial (Fin 3) ℂ)))*((X (0:Fin 3) : MvPolynomial (Fin 3) ℂ)-((C (q^6) : MvPolynomial (Fin 3) ℂ)*(X (2:Fin 3) : MvPolynomial (Fin 3) ℂ)))))).degreeOf (1:Fin 3)≤1 := dmul h2 h11 + simpa only [basePolyThree,basePolyThreeFactor,basePolyTwo] using h12 + +theorem basePolyThree_bound_3_2 : + (basePolyThree (X (0:Fin 3)) (X 1) (X 2) .zero .plus .minus).degreeOf 2 ≤ 2 := by + have h0 : ((C (q^5-q^7) : MvPolynomial (Fin 3) ℂ)).degreeOf (2:Fin 3)≤0 := le_of_eq (degreeOf_C _ _) + have h1 : ((X (2:Fin 3) : MvPolynomial (Fin 3) ℂ)).degreeOf (2:Fin 3)≤1 := by simp + have h2 : (((C (q^5-q^7) : MvPolynomial (Fin 3) ℂ)*(X (2:Fin 3) : MvPolynomial (Fin 3) ℂ))).degreeOf (2:Fin 3)≤1 := dmul h0 h1 + have h3 : ((X (0:Fin 3) : MvPolynomial (Fin 3) ℂ)).degreeOf (2:Fin 3)≤0 := by simp [degreeOf_X] + have h4 : ((C (q^2) : MvPolynomial (Fin 3) ℂ)).degreeOf (2:Fin 3)≤0 := le_of_eq (degreeOf_C _ _) + have h5 : ((X (1:Fin 3) : MvPolynomial (Fin 3) ℂ)).degreeOf (2:Fin 3)≤0 := by simp [degreeOf_X] + have h6 : (((C (q^2) : MvPolynomial (Fin 3) ℂ)*(X (1:Fin 3) : MvPolynomial (Fin 3) ℂ))).degreeOf (2:Fin 3)≤0 := dmul h4 h5 + have h7 : (((X (0:Fin 3) : MvPolynomial (Fin 3) ℂ)+((C (q^2) : MvPolynomial (Fin 3) ℂ)*(X (1:Fin 3) : MvPolynomial (Fin 3) ℂ)))).degreeOf (2:Fin 3)≤0 := dadd (h3.trans (by omega)) (h6.trans (by omega)) + have h8 : ((C (q^6) : MvPolynomial (Fin 3) ℂ)).degreeOf (2:Fin 3)≤0 := le_of_eq (degreeOf_C _ _) + have h9 : (((C (q^6) : MvPolynomial (Fin 3) ℂ)*(X (2:Fin 3) : MvPolynomial (Fin 3) ℂ))).degreeOf (2:Fin 3)≤1 := dmul h8 h1 + have h10 : (((X (0:Fin 3) : MvPolynomial (Fin 3) ℂ)-((C (q^6) : MvPolynomial (Fin 3) ℂ)*(X (2:Fin 3) : MvPolynomial (Fin 3) ℂ)))).degreeOf (2:Fin 3)≤1 := (degreeOf_sub_le _ _ _).trans (max_le (h3.trans (by omega)) (h9.trans (by omega))) + have h11 : ((((X (0:Fin 3) : MvPolynomial (Fin 3) ℂ)+((C (q^2) : MvPolynomial (Fin 3) ℂ)*(X (1:Fin 3) : MvPolynomial (Fin 3) ℂ)))*((X (0:Fin 3) : MvPolynomial (Fin 3) ℂ)-((C (q^6) : MvPolynomial (Fin 3) ℂ)*(X (2:Fin 3) : MvPolynomial (Fin 3) ℂ))))).degreeOf (2:Fin 3)≤1 := dmul h7 h10 + have h12 : ((((C (q^5-q^7) : MvPolynomial (Fin 3) ℂ)*(X (2:Fin 3) : MvPolynomial (Fin 3) ℂ))*(((X (0:Fin 3) : MvPolynomial (Fin 3) ℂ)+((C (q^2) : MvPolynomial (Fin 3) ℂ)*(X (1:Fin 3) : MvPolynomial (Fin 3) ℂ)))*((X (0:Fin 3) : MvPolynomial (Fin 3) ℂ)-((C (q^6) : MvPolynomial (Fin 3) ℂ)*(X (2:Fin 3) : MvPolynomial (Fin 3) ℂ)))))).degreeOf (2:Fin 3)≤2 := dmul h2 h11 + simpa only [basePolyThree,basePolyThreeFactor,basePolyTwo] using h12 + +theorem basePolyThree_bound_4_0 : + (basePolyThree (X (0:Fin 3)) (X 1) (X 2) .zero .minus .plus).degreeOf 0 ≤ 2 := by + have h0 : ((C (q-q^3) : MvPolynomial (Fin 3) ℂ)).degreeOf (0:Fin 3)≤0 := le_of_eq (degreeOf_C _ _) + have h1 : ((X (1:Fin 3) : MvPolynomial (Fin 3) ℂ)).degreeOf (0:Fin 3)≤0 := by simp [degreeOf_X] + have h2 : (((C (q-q^3) : MvPolynomial (Fin 3) ℂ)*(X (1:Fin 3) : MvPolynomial (Fin 3) ℂ))).degreeOf (0:Fin 3)≤0 := dmul h0 h1 + have h3 : ((X (0:Fin 3) : MvPolynomial (Fin 3) ℂ)).degreeOf (0:Fin 3)≤1 := by simp + have h4 : ((C (q^2) : MvPolynomial (Fin 3) ℂ)).degreeOf (0:Fin 3)≤0 := le_of_eq (degreeOf_C _ _) + have h5 : (((C (q^2) : MvPolynomial (Fin 3) ℂ)*(X (1:Fin 3) : MvPolynomial (Fin 3) ℂ))).degreeOf (0:Fin 3)≤0 := dmul h4 h1 + have h6 : (((X (0:Fin 3) : MvPolynomial (Fin 3) ℂ)+((C (q^2) : MvPolynomial (Fin 3) ℂ)*(X (1:Fin 3) : MvPolynomial (Fin 3) ℂ)))).degreeOf (0:Fin 3)≤1 := dadd (h3.trans (by omega)) (h5.trans (by omega)) + have h7 : ((C (q^6) : MvPolynomial (Fin 3) ℂ)).degreeOf (0:Fin 3)≤0 := le_of_eq (degreeOf_C _ _) + have h8 : ((X (2:Fin 3) : MvPolynomial (Fin 3) ℂ)).degreeOf (0:Fin 3)≤0 := by simp [degreeOf_X] + have h9 : (((C (q^6) : MvPolynomial (Fin 3) ℂ)*(X (2:Fin 3) : MvPolynomial (Fin 3) ℂ))).degreeOf (0:Fin 3)≤0 := dmul h7 h8 + have h10 : (((X (0:Fin 3) : MvPolynomial (Fin 3) ℂ)-((C (q^6) : MvPolynomial (Fin 3) ℂ)*(X (2:Fin 3) : MvPolynomial (Fin 3) ℂ)))).degreeOf (0:Fin 3)≤1 := (degreeOf_sub_le _ _ _).trans (max_le (h3.trans (by omega)) (h9.trans (by omega))) + have h11 : ((((X (0:Fin 3) : MvPolynomial (Fin 3) ℂ)+((C (q^2) : MvPolynomial (Fin 3) ℂ)*(X (1:Fin 3) : MvPolynomial (Fin 3) ℂ)))*((X (0:Fin 3) : MvPolynomial (Fin 3) ℂ)-((C (q^6) : MvPolynomial (Fin 3) ℂ)*(X (2:Fin 3) : MvPolynomial (Fin 3) ℂ))))).degreeOf (0:Fin 3)≤2 := dmul h6 h10 + have h12 : ((((C (q-q^3) : MvPolynomial (Fin 3) ℂ)*(X (1:Fin 3) : MvPolynomial (Fin 3) ℂ))*(((X (0:Fin 3) : MvPolynomial (Fin 3) ℂ)+((C (q^2) : MvPolynomial (Fin 3) ℂ)*(X (1:Fin 3) : MvPolynomial (Fin 3) ℂ)))*((X (0:Fin 3) : MvPolynomial (Fin 3) ℂ)-((C (q^6) : MvPolynomial (Fin 3) ℂ)*(X (2:Fin 3) : MvPolynomial (Fin 3) ℂ)))))).degreeOf (0:Fin 3)≤2 := dmul h2 h11 + simpa only [basePolyThree,basePolyThreeFactor,basePolyTwo] using h12 + +theorem basePolyThree_bound_4_1 : + (basePolyThree (X (0:Fin 3)) (X 1) (X 2) .zero .minus .plus).degreeOf 1 ≤ 2 := by + have h0 : ((C (q-q^3) : MvPolynomial (Fin 3) ℂ)).degreeOf (1:Fin 3)≤0 := le_of_eq (degreeOf_C _ _) + have h1 : ((X (1:Fin 3) : MvPolynomial (Fin 3) ℂ)).degreeOf (1:Fin 3)≤1 := by simp + have h2 : (((C (q-q^3) : MvPolynomial (Fin 3) ℂ)*(X (1:Fin 3) : MvPolynomial (Fin 3) ℂ))).degreeOf (1:Fin 3)≤1 := dmul h0 h1 + have h3 : ((X (0:Fin 3) : MvPolynomial (Fin 3) ℂ)).degreeOf (1:Fin 3)≤0 := by simp [degreeOf_X] + have h4 : ((C (q^2) : MvPolynomial (Fin 3) ℂ)).degreeOf (1:Fin 3)≤0 := le_of_eq (degreeOf_C _ _) + have h5 : (((C (q^2) : MvPolynomial (Fin 3) ℂ)*(X (1:Fin 3) : MvPolynomial (Fin 3) ℂ))).degreeOf (1:Fin 3)≤1 := dmul h4 h1 + have h6 : (((X (0:Fin 3) : MvPolynomial (Fin 3) ℂ)+((C (q^2) : MvPolynomial (Fin 3) ℂ)*(X (1:Fin 3) : MvPolynomial (Fin 3) ℂ)))).degreeOf (1:Fin 3)≤1 := dadd (h3.trans (by omega)) (h5.trans (by omega)) + have h7 : ((C (q^6) : MvPolynomial (Fin 3) ℂ)).degreeOf (1:Fin 3)≤0 := le_of_eq (degreeOf_C _ _) + have h8 : ((X (2:Fin 3) : MvPolynomial (Fin 3) ℂ)).degreeOf (1:Fin 3)≤0 := by simp [degreeOf_X] + have h9 : (((C (q^6) : MvPolynomial (Fin 3) ℂ)*(X (2:Fin 3) : MvPolynomial (Fin 3) ℂ))).degreeOf (1:Fin 3)≤0 := dmul h7 h8 + have h10 : (((X (0:Fin 3) : MvPolynomial (Fin 3) ℂ)-((C (q^6) : MvPolynomial (Fin 3) ℂ)*(X (2:Fin 3) : MvPolynomial (Fin 3) ℂ)))).degreeOf (1:Fin 3)≤0 := (degreeOf_sub_le _ _ _).trans (max_le (h3.trans (by omega)) (h9.trans (by omega))) + have h11 : ((((X (0:Fin 3) : MvPolynomial (Fin 3) ℂ)+((C (q^2) : MvPolynomial (Fin 3) ℂ)*(X (1:Fin 3) : MvPolynomial (Fin 3) ℂ)))*((X (0:Fin 3) : MvPolynomial (Fin 3) ℂ)-((C (q^6) : MvPolynomial (Fin 3) ℂ)*(X (2:Fin 3) : MvPolynomial (Fin 3) ℂ))))).degreeOf (1:Fin 3)≤1 := dmul h6 h10 + have h12 : ((((C (q-q^3) : MvPolynomial (Fin 3) ℂ)*(X (1:Fin 3) : MvPolynomial (Fin 3) ℂ))*(((X (0:Fin 3) : MvPolynomial (Fin 3) ℂ)+((C (q^2) : MvPolynomial (Fin 3) ℂ)*(X (1:Fin 3) : MvPolynomial (Fin 3) ℂ)))*((X (0:Fin 3) : MvPolynomial (Fin 3) ℂ)-((C (q^6) : MvPolynomial (Fin 3) ℂ)*(X (2:Fin 3) : MvPolynomial (Fin 3) ℂ)))))).degreeOf (1:Fin 3)≤2 := dmul h2 h11 + simpa only [basePolyThree,basePolyThreeFactor,basePolyTwo] using h12 + +theorem basePolyThree_bound_4_2 : + (basePolyThree (X (0:Fin 3)) (X 1) (X 2) .zero .minus .plus).degreeOf 2 ≤ 1 := by + have h0 : ((C (q-q^3) : MvPolynomial (Fin 3) ℂ)).degreeOf (2:Fin 3)≤0 := le_of_eq (degreeOf_C _ _) + have h1 : ((X (1:Fin 3) : MvPolynomial (Fin 3) ℂ)).degreeOf (2:Fin 3)≤0 := by simp [degreeOf_X] + have h2 : (((C (q-q^3) : MvPolynomial (Fin 3) ℂ)*(X (1:Fin 3) : MvPolynomial (Fin 3) ℂ))).degreeOf (2:Fin 3)≤0 := dmul h0 h1 + have h3 : ((X (0:Fin 3) : MvPolynomial (Fin 3) ℂ)).degreeOf (2:Fin 3)≤0 := by simp [degreeOf_X] + have h4 : ((C (q^2) : MvPolynomial (Fin 3) ℂ)).degreeOf (2:Fin 3)≤0 := le_of_eq (degreeOf_C _ _) + have h5 : (((C (q^2) : MvPolynomial (Fin 3) ℂ)*(X (1:Fin 3) : MvPolynomial (Fin 3) ℂ))).degreeOf (2:Fin 3)≤0 := dmul h4 h1 + have h6 : (((X (0:Fin 3) : MvPolynomial (Fin 3) ℂ)+((C (q^2) : MvPolynomial (Fin 3) ℂ)*(X (1:Fin 3) : MvPolynomial (Fin 3) ℂ)))).degreeOf (2:Fin 3)≤0 := dadd (h3.trans (by omega)) (h5.trans (by omega)) + have h7 : ((C (q^6) : MvPolynomial (Fin 3) ℂ)).degreeOf (2:Fin 3)≤0 := le_of_eq (degreeOf_C _ _) + have h8 : ((X (2:Fin 3) : MvPolynomial (Fin 3) ℂ)).degreeOf (2:Fin 3)≤1 := by simp + have h9 : (((C (q^6) : MvPolynomial (Fin 3) ℂ)*(X (2:Fin 3) : MvPolynomial (Fin 3) ℂ))).degreeOf (2:Fin 3)≤1 := dmul h7 h8 + have h10 : (((X (0:Fin 3) : MvPolynomial (Fin 3) ℂ)-((C (q^6) : MvPolynomial (Fin 3) ℂ)*(X (2:Fin 3) : MvPolynomial (Fin 3) ℂ)))).degreeOf (2:Fin 3)≤1 := (degreeOf_sub_le _ _ _).trans (max_le (h3.trans (by omega)) (h9.trans (by omega))) + have h11 : ((((X (0:Fin 3) : MvPolynomial (Fin 3) ℂ)+((C (q^2) : MvPolynomial (Fin 3) ℂ)*(X (1:Fin 3) : MvPolynomial (Fin 3) ℂ)))*((X (0:Fin 3) : MvPolynomial (Fin 3) ℂ)-((C (q^6) : MvPolynomial (Fin 3) ℂ)*(X (2:Fin 3) : MvPolynomial (Fin 3) ℂ))))).degreeOf (2:Fin 3)≤1 := dmul h6 h10 + have h12 : ((((C (q-q^3) : MvPolynomial (Fin 3) ℂ)*(X (1:Fin 3) : MvPolynomial (Fin 3) ℂ))*(((X (0:Fin 3) : MvPolynomial (Fin 3) ℂ)+((C (q^2) : MvPolynomial (Fin 3) ℂ)*(X (1:Fin 3) : MvPolynomial (Fin 3) ℂ)))*((X (0:Fin 3) : MvPolynomial (Fin 3) ℂ)-((C (q^6) : MvPolynomial (Fin 3) ℂ)*(X (2:Fin 3) : MvPolynomial (Fin 3) ℂ)))))).degreeOf (2:Fin 3)≤1 := dmul h2 h11 + simpa only [basePolyThree,basePolyThreeFactor,basePolyTwo] using h12 + +theorem basePolyThree_bound_5_0 : + (basePolyThree (X (0:Fin 3)) (X 1) (X 2) .plus .zero .minus).degreeOf 0 ≤ 1 := by + have h0 : ((C (q^5-q^7) : MvPolynomial (Fin 3) ℂ)).degreeOf (0:Fin 3)≤0 := le_of_eq (degreeOf_C _ _) + have h1 : ((X (2:Fin 3) : MvPolynomial (Fin 3) ℂ)).degreeOf (0:Fin 3)≤0 := by simp [degreeOf_X] + have h2 : (((C (q^5-q^7) : MvPolynomial (Fin 3) ℂ)*(X (2:Fin 3) : MvPolynomial (Fin 3) ℂ))).degreeOf (0:Fin 3)≤0 := dmul h0 h1 + have h3 : ((X (1:Fin 3) : MvPolynomial (Fin 3) ℂ)).degreeOf (0:Fin 3)≤0 := by simp [degreeOf_X] + have h4 : ((C (q^2) : MvPolynomial (Fin 3) ℂ)).degreeOf (0:Fin 3)≤0 := le_of_eq (degreeOf_C _ _) + have h5 : (((C (q^2) : MvPolynomial (Fin 3) ℂ)*(X (2:Fin 3) : MvPolynomial (Fin 3) ℂ))).degreeOf (0:Fin 3)≤0 := dmul h4 h1 + have h6 : (((X (1:Fin 3) : MvPolynomial (Fin 3) ℂ)+((C (q^2) : MvPolynomial (Fin 3) ℂ)*(X (2:Fin 3) : MvPolynomial (Fin 3) ℂ)))).degreeOf (0:Fin 3)≤0 := dadd (h3.trans (by omega)) (h5.trans (by omega)) + have h7 : ((C (q^6) : MvPolynomial (Fin 3) ℂ)).degreeOf (0:Fin 3)≤0 := le_of_eq (degreeOf_C _ _) + have h8 : ((X (0:Fin 3) : MvPolynomial (Fin 3) ℂ)).degreeOf (0:Fin 3)≤1 := by simp + have h9 : (((C (q^6) : MvPolynomial (Fin 3) ℂ)*(X (0:Fin 3) : MvPolynomial (Fin 3) ℂ))).degreeOf (0:Fin 3)≤1 := dmul h7 h8 + have h10 : (((X (1:Fin 3) : MvPolynomial (Fin 3) ℂ)-((C (q^6) : MvPolynomial (Fin 3) ℂ)*(X (0:Fin 3) : MvPolynomial (Fin 3) ℂ)))).degreeOf (0:Fin 3)≤1 := (degreeOf_sub_le _ _ _).trans (max_le (h3.trans (by omega)) (h9.trans (by omega))) + have h11 : ((((X (1:Fin 3) : MvPolynomial (Fin 3) ℂ)+((C (q^2) : MvPolynomial (Fin 3) ℂ)*(X (2:Fin 3) : MvPolynomial (Fin 3) ℂ)))*((X (1:Fin 3) : MvPolynomial (Fin 3) ℂ)-((C (q^6) : MvPolynomial (Fin 3) ℂ)*(X (0:Fin 3) : MvPolynomial (Fin 3) ℂ))))).degreeOf (0:Fin 3)≤1 := dmul h6 h10 + have h12 : ((((C (q^5-q^7) : MvPolynomial (Fin 3) ℂ)*(X (2:Fin 3) : MvPolynomial (Fin 3) ℂ))*(((X (1:Fin 3) : MvPolynomial (Fin 3) ℂ)+((C (q^2) : MvPolynomial (Fin 3) ℂ)*(X (2:Fin 3) : MvPolynomial (Fin 3) ℂ)))*((X (1:Fin 3) : MvPolynomial (Fin 3) ℂ)-((C (q^6) : MvPolynomial (Fin 3) ℂ)*(X (0:Fin 3) : MvPolynomial (Fin 3) ℂ)))))).degreeOf (0:Fin 3)≤1 := dmul h2 h11 + simpa only [basePolyThree,basePolyThreeFactor,basePolyTwo] using h12 + +theorem basePolyThree_bound_5_1 : + (basePolyThree (X (0:Fin 3)) (X 1) (X 2) .plus .zero .minus).degreeOf 1 ≤ 2 := by + have h0 : ((C (q^5-q^7) : MvPolynomial (Fin 3) ℂ)).degreeOf (1:Fin 3)≤0 := le_of_eq (degreeOf_C _ _) + have h1 : ((X (2:Fin 3) : MvPolynomial (Fin 3) ℂ)).degreeOf (1:Fin 3)≤0 := by simp [degreeOf_X] + have h2 : (((C (q^5-q^7) : MvPolynomial (Fin 3) ℂ)*(X (2:Fin 3) : MvPolynomial (Fin 3) ℂ))).degreeOf (1:Fin 3)≤0 := dmul h0 h1 + have h3 : ((X (1:Fin 3) : MvPolynomial (Fin 3) ℂ)).degreeOf (1:Fin 3)≤1 := by simp + have h4 : ((C (q^2) : MvPolynomial (Fin 3) ℂ)).degreeOf (1:Fin 3)≤0 := le_of_eq (degreeOf_C _ _) + have h5 : (((C (q^2) : MvPolynomial (Fin 3) ℂ)*(X (2:Fin 3) : MvPolynomial (Fin 3) ℂ))).degreeOf (1:Fin 3)≤0 := dmul h4 h1 + have h6 : (((X (1:Fin 3) : MvPolynomial (Fin 3) ℂ)+((C (q^2) : MvPolynomial (Fin 3) ℂ)*(X (2:Fin 3) : MvPolynomial (Fin 3) ℂ)))).degreeOf (1:Fin 3)≤1 := dadd (h3.trans (by omega)) (h5.trans (by omega)) + have h7 : ((C (q^6) : MvPolynomial (Fin 3) ℂ)).degreeOf (1:Fin 3)≤0 := le_of_eq (degreeOf_C _ _) + have h8 : ((X (0:Fin 3) : MvPolynomial (Fin 3) ℂ)).degreeOf (1:Fin 3)≤0 := by simp [degreeOf_X] + have h9 : (((C (q^6) : MvPolynomial (Fin 3) ℂ)*(X (0:Fin 3) : MvPolynomial (Fin 3) ℂ))).degreeOf (1:Fin 3)≤0 := dmul h7 h8 + have h10 : (((X (1:Fin 3) : MvPolynomial (Fin 3) ℂ)-((C (q^6) : MvPolynomial (Fin 3) ℂ)*(X (0:Fin 3) : MvPolynomial (Fin 3) ℂ)))).degreeOf (1:Fin 3)≤1 := (degreeOf_sub_le _ _ _).trans (max_le (h3.trans (by omega)) (h9.trans (by omega))) + have h11 : ((((X (1:Fin 3) : MvPolynomial (Fin 3) ℂ)+((C (q^2) : MvPolynomial (Fin 3) ℂ)*(X (2:Fin 3) : MvPolynomial (Fin 3) ℂ)))*((X (1:Fin 3) : MvPolynomial (Fin 3) ℂ)-((C (q^6) : MvPolynomial (Fin 3) ℂ)*(X (0:Fin 3) : MvPolynomial (Fin 3) ℂ))))).degreeOf (1:Fin 3)≤2 := dmul h6 h10 + have h12 : ((((C (q^5-q^7) : MvPolynomial (Fin 3) ℂ)*(X (2:Fin 3) : MvPolynomial (Fin 3) ℂ))*(((X (1:Fin 3) : MvPolynomial (Fin 3) ℂ)+((C (q^2) : MvPolynomial (Fin 3) ℂ)*(X (2:Fin 3) : MvPolynomial (Fin 3) ℂ)))*((X (1:Fin 3) : MvPolynomial (Fin 3) ℂ)-((C (q^6) : MvPolynomial (Fin 3) ℂ)*(X (0:Fin 3) : MvPolynomial (Fin 3) ℂ)))))).degreeOf (1:Fin 3)≤2 := dmul h2 h11 + simpa only [basePolyThree,basePolyThreeFactor,basePolyTwo] using h12 + +theorem basePolyThree_bound_5_2 : + (basePolyThree (X (0:Fin 3)) (X 1) (X 2) .plus .zero .minus).degreeOf 2 ≤ 2 := by + have h0 : ((C (q^5-q^7) : MvPolynomial (Fin 3) ℂ)).degreeOf (2:Fin 3)≤0 := le_of_eq (degreeOf_C _ _) + have h1 : ((X (2:Fin 3) : MvPolynomial (Fin 3) ℂ)).degreeOf (2:Fin 3)≤1 := by simp + have h2 : (((C (q^5-q^7) : MvPolynomial (Fin 3) ℂ)*(X (2:Fin 3) : MvPolynomial (Fin 3) ℂ))).degreeOf (2:Fin 3)≤1 := dmul h0 h1 + have h3 : ((X (1:Fin 3) : MvPolynomial (Fin 3) ℂ)).degreeOf (2:Fin 3)≤0 := by simp [degreeOf_X] + have h4 : ((C (q^2) : MvPolynomial (Fin 3) ℂ)).degreeOf (2:Fin 3)≤0 := le_of_eq (degreeOf_C _ _) + have h5 : (((C (q^2) : MvPolynomial (Fin 3) ℂ)*(X (2:Fin 3) : MvPolynomial (Fin 3) ℂ))).degreeOf (2:Fin 3)≤1 := dmul h4 h1 + have h6 : (((X (1:Fin 3) : MvPolynomial (Fin 3) ℂ)+((C (q^2) : MvPolynomial (Fin 3) ℂ)*(X (2:Fin 3) : MvPolynomial (Fin 3) ℂ)))).degreeOf (2:Fin 3)≤1 := dadd (h3.trans (by omega)) (h5.trans (by omega)) + have h7 : ((C (q^6) : MvPolynomial (Fin 3) ℂ)).degreeOf (2:Fin 3)≤0 := le_of_eq (degreeOf_C _ _) + have h8 : ((X (0:Fin 3) : MvPolynomial (Fin 3) ℂ)).degreeOf (2:Fin 3)≤0 := by simp [degreeOf_X] + have h9 : (((C (q^6) : MvPolynomial (Fin 3) ℂ)*(X (0:Fin 3) : MvPolynomial (Fin 3) ℂ))).degreeOf (2:Fin 3)≤0 := dmul h7 h8 + have h10 : (((X (1:Fin 3) : MvPolynomial (Fin 3) ℂ)-((C (q^6) : MvPolynomial (Fin 3) ℂ)*(X (0:Fin 3) : MvPolynomial (Fin 3) ℂ)))).degreeOf (2:Fin 3)≤0 := (degreeOf_sub_le _ _ _).trans (max_le (h3.trans (by omega)) (h9.trans (by omega))) + have h11 : ((((X (1:Fin 3) : MvPolynomial (Fin 3) ℂ)+((C (q^2) : MvPolynomial (Fin 3) ℂ)*(X (2:Fin 3) : MvPolynomial (Fin 3) ℂ)))*((X (1:Fin 3) : MvPolynomial (Fin 3) ℂ)-((C (q^6) : MvPolynomial (Fin 3) ℂ)*(X (0:Fin 3) : MvPolynomial (Fin 3) ℂ))))).degreeOf (2:Fin 3)≤1 := dmul h6 h10 + have h12 : ((((C (q^5-q^7) : MvPolynomial (Fin 3) ℂ)*(X (2:Fin 3) : MvPolynomial (Fin 3) ℂ))*(((X (1:Fin 3) : MvPolynomial (Fin 3) ℂ)+((C (q^2) : MvPolynomial (Fin 3) ℂ)*(X (2:Fin 3) : MvPolynomial (Fin 3) ℂ)))*((X (1:Fin 3) : MvPolynomial (Fin 3) ℂ)-((C (q^6) : MvPolynomial (Fin 3) ℂ)*(X (0:Fin 3) : MvPolynomial (Fin 3) ℂ)))))).degreeOf (2:Fin 3)≤2 := dmul h2 h11 + simpa only [basePolyThree,basePolyThreeFactor,basePolyTwo] using h12 + +theorem basePolyThree_bound_6_0 : + (basePolyThree (X (0:Fin 3)) (X 1) (X 2) .minus .zero .plus).degreeOf 0 ≤ 2 := by + have h0 : ((C (q-q^3) : MvPolynomial (Fin 3) ℂ)).degreeOf (0:Fin 3)≤0 := le_of_eq (degreeOf_C _ _) + have h1 : ((X (0:Fin 3) : MvPolynomial (Fin 3) ℂ)).degreeOf (0:Fin 3)≤1 := by simp + have h2 : (((C (q-q^3) : MvPolynomial (Fin 3) ℂ)*(X (0:Fin 3) : MvPolynomial (Fin 3) ℂ))).degreeOf (0:Fin 3)≤1 := dmul h0 h1 + have h3 : ((X (1:Fin 3) : MvPolynomial (Fin 3) ℂ)).degreeOf (0:Fin 3)≤0 := by simp [degreeOf_X] + have h4 : ((C (q^2) : MvPolynomial (Fin 3) ℂ)).degreeOf (0:Fin 3)≤0 := le_of_eq (degreeOf_C _ _) + have h5 : ((X (2:Fin 3) : MvPolynomial (Fin 3) ℂ)).degreeOf (0:Fin 3)≤0 := by simp [degreeOf_X] + have h6 : (((C (q^2) : MvPolynomial (Fin 3) ℂ)*(X (2:Fin 3) : MvPolynomial (Fin 3) ℂ))).degreeOf (0:Fin 3)≤0 := dmul h4 h5 + have h7 : (((X (1:Fin 3) : MvPolynomial (Fin 3) ℂ)+((C (q^2) : MvPolynomial (Fin 3) ℂ)*(X (2:Fin 3) : MvPolynomial (Fin 3) ℂ)))).degreeOf (0:Fin 3)≤0 := dadd (h3.trans (by omega)) (h6.trans (by omega)) + have h8 : ((C (q^6) : MvPolynomial (Fin 3) ℂ)).degreeOf (0:Fin 3)≤0 := le_of_eq (degreeOf_C _ _) + have h9 : (((C (q^6) : MvPolynomial (Fin 3) ℂ)*(X (0:Fin 3) : MvPolynomial (Fin 3) ℂ))).degreeOf (0:Fin 3)≤1 := dmul h8 h1 + have h10 : (((X (1:Fin 3) : MvPolynomial (Fin 3) ℂ)-((C (q^6) : MvPolynomial (Fin 3) ℂ)*(X (0:Fin 3) : MvPolynomial (Fin 3) ℂ)))).degreeOf (0:Fin 3)≤1 := (degreeOf_sub_le _ _ _).trans (max_le (h3.trans (by omega)) (h9.trans (by omega))) + have h11 : ((((X (1:Fin 3) : MvPolynomial (Fin 3) ℂ)+((C (q^2) : MvPolynomial (Fin 3) ℂ)*(X (2:Fin 3) : MvPolynomial (Fin 3) ℂ)))*((X (1:Fin 3) : MvPolynomial (Fin 3) ℂ)-((C (q^6) : MvPolynomial (Fin 3) ℂ)*(X (0:Fin 3) : MvPolynomial (Fin 3) ℂ))))).degreeOf (0:Fin 3)≤1 := dmul h7 h10 + have h12 : ((((C (q-q^3) : MvPolynomial (Fin 3) ℂ)*(X (0:Fin 3) : MvPolynomial (Fin 3) ℂ))*(((X (1:Fin 3) : MvPolynomial (Fin 3) ℂ)+((C (q^2) : MvPolynomial (Fin 3) ℂ)*(X (2:Fin 3) : MvPolynomial (Fin 3) ℂ)))*((X (1:Fin 3) : MvPolynomial (Fin 3) ℂ)-((C (q^6) : MvPolynomial (Fin 3) ℂ)*(X (0:Fin 3) : MvPolynomial (Fin 3) ℂ)))))).degreeOf (0:Fin 3)≤2 := dmul h2 h11 + simpa only [basePolyThree,basePolyThreeFactor,basePolyTwo] using h12 + +theorem basePolyThree_bound_6_1 : + (basePolyThree (X (0:Fin 3)) (X 1) (X 2) .minus .zero .plus).degreeOf 1 ≤ 2 := by + have h0 : ((C (q-q^3) : MvPolynomial (Fin 3) ℂ)).degreeOf (1:Fin 3)≤0 := le_of_eq (degreeOf_C _ _) + have h1 : ((X (0:Fin 3) : MvPolynomial (Fin 3) ℂ)).degreeOf (1:Fin 3)≤0 := by simp [degreeOf_X] + have h2 : (((C (q-q^3) : MvPolynomial (Fin 3) ℂ)*(X (0:Fin 3) : MvPolynomial (Fin 3) ℂ))).degreeOf (1:Fin 3)≤0 := dmul h0 h1 + have h3 : ((X (1:Fin 3) : MvPolynomial (Fin 3) ℂ)).degreeOf (1:Fin 3)≤1 := by simp + have h4 : ((C (q^2) : MvPolynomial (Fin 3) ℂ)).degreeOf (1:Fin 3)≤0 := le_of_eq (degreeOf_C _ _) + have h5 : ((X (2:Fin 3) : MvPolynomial (Fin 3) ℂ)).degreeOf (1:Fin 3)≤0 := by simp [degreeOf_X] + have h6 : (((C (q^2) : MvPolynomial (Fin 3) ℂ)*(X (2:Fin 3) : MvPolynomial (Fin 3) ℂ))).degreeOf (1:Fin 3)≤0 := dmul h4 h5 + have h7 : (((X (1:Fin 3) : MvPolynomial (Fin 3) ℂ)+((C (q^2) : MvPolynomial (Fin 3) ℂ)*(X (2:Fin 3) : MvPolynomial (Fin 3) ℂ)))).degreeOf (1:Fin 3)≤1 := dadd (h3.trans (by omega)) (h6.trans (by omega)) + have h8 : ((C (q^6) : MvPolynomial (Fin 3) ℂ)).degreeOf (1:Fin 3)≤0 := le_of_eq (degreeOf_C _ _) + have h9 : (((C (q^6) : MvPolynomial (Fin 3) ℂ)*(X (0:Fin 3) : MvPolynomial (Fin 3) ℂ))).degreeOf (1:Fin 3)≤0 := dmul h8 h1 + have h10 : (((X (1:Fin 3) : MvPolynomial (Fin 3) ℂ)-((C (q^6) : MvPolynomial (Fin 3) ℂ)*(X (0:Fin 3) : MvPolynomial (Fin 3) ℂ)))).degreeOf (1:Fin 3)≤1 := (degreeOf_sub_le _ _ _).trans (max_le (h3.trans (by omega)) (h9.trans (by omega))) + have h11 : ((((X (1:Fin 3) : MvPolynomial (Fin 3) ℂ)+((C (q^2) : MvPolynomial (Fin 3) ℂ)*(X (2:Fin 3) : MvPolynomial (Fin 3) ℂ)))*((X (1:Fin 3) : MvPolynomial (Fin 3) ℂ)-((C (q^6) : MvPolynomial (Fin 3) ℂ)*(X (0:Fin 3) : MvPolynomial (Fin 3) ℂ))))).degreeOf (1:Fin 3)≤2 := dmul h7 h10 + have h12 : ((((C (q-q^3) : MvPolynomial (Fin 3) ℂ)*(X (0:Fin 3) : MvPolynomial (Fin 3) ℂ))*(((X (1:Fin 3) : MvPolynomial (Fin 3) ℂ)+((C (q^2) : MvPolynomial (Fin 3) ℂ)*(X (2:Fin 3) : MvPolynomial (Fin 3) ℂ)))*((X (1:Fin 3) : MvPolynomial (Fin 3) ℂ)-((C (q^6) : MvPolynomial (Fin 3) ℂ)*(X (0:Fin 3) : MvPolynomial (Fin 3) ℂ)))))).degreeOf (1:Fin 3)≤2 := dmul h2 h11 + simpa only [basePolyThree,basePolyThreeFactor,basePolyTwo] using h12 + +theorem basePolyThree_bound_6_2 : + (basePolyThree (X (0:Fin 3)) (X 1) (X 2) .minus .zero .plus).degreeOf 2 ≤ 1 := by + have h0 : ((C (q-q^3) : MvPolynomial (Fin 3) ℂ)).degreeOf (2:Fin 3)≤0 := le_of_eq (degreeOf_C _ _) + have h1 : ((X (0:Fin 3) : MvPolynomial (Fin 3) ℂ)).degreeOf (2:Fin 3)≤0 := by simp [degreeOf_X] + have h2 : (((C (q-q^3) : MvPolynomial (Fin 3) ℂ)*(X (0:Fin 3) : MvPolynomial (Fin 3) ℂ))).degreeOf (2:Fin 3)≤0 := dmul h0 h1 + have h3 : ((X (1:Fin 3) : MvPolynomial (Fin 3) ℂ)).degreeOf (2:Fin 3)≤0 := by simp [degreeOf_X] + have h4 : ((C (q^2) : MvPolynomial (Fin 3) ℂ)).degreeOf (2:Fin 3)≤0 := le_of_eq (degreeOf_C _ _) + have h5 : ((X (2:Fin 3) : MvPolynomial (Fin 3) ℂ)).degreeOf (2:Fin 3)≤1 := by simp + have h6 : (((C (q^2) : MvPolynomial (Fin 3) ℂ)*(X (2:Fin 3) : MvPolynomial (Fin 3) ℂ))).degreeOf (2:Fin 3)≤1 := dmul h4 h5 + have h7 : (((X (1:Fin 3) : MvPolynomial (Fin 3) ℂ)+((C (q^2) : MvPolynomial (Fin 3) ℂ)*(X (2:Fin 3) : MvPolynomial (Fin 3) ℂ)))).degreeOf (2:Fin 3)≤1 := dadd (h3.trans (by omega)) (h6.trans (by omega)) + have h8 : ((C (q^6) : MvPolynomial (Fin 3) ℂ)).degreeOf (2:Fin 3)≤0 := le_of_eq (degreeOf_C _ _) + have h9 : (((C (q^6) : MvPolynomial (Fin 3) ℂ)*(X (0:Fin 3) : MvPolynomial (Fin 3) ℂ))).degreeOf (2:Fin 3)≤0 := dmul h8 h1 + have h10 : (((X (1:Fin 3) : MvPolynomial (Fin 3) ℂ)-((C (q^6) : MvPolynomial (Fin 3) ℂ)*(X (0:Fin 3) : MvPolynomial (Fin 3) ℂ)))).degreeOf (2:Fin 3)≤0 := (degreeOf_sub_le _ _ _).trans (max_le (h3.trans (by omega)) (h9.trans (by omega))) + have h11 : ((((X (1:Fin 3) : MvPolynomial (Fin 3) ℂ)+((C (q^2) : MvPolynomial (Fin 3) ℂ)*(X (2:Fin 3) : MvPolynomial (Fin 3) ℂ)))*((X (1:Fin 3) : MvPolynomial (Fin 3) ℂ)-((C (q^6) : MvPolynomial (Fin 3) ℂ)*(X (0:Fin 3) : MvPolynomial (Fin 3) ℂ))))).degreeOf (2:Fin 3)≤1 := dmul h7 h10 + have h12 : ((((C (q-q^3) : MvPolynomial (Fin 3) ℂ)*(X (0:Fin 3) : MvPolynomial (Fin 3) ℂ))*(((X (1:Fin 3) : MvPolynomial (Fin 3) ℂ)+((C (q^2) : MvPolynomial (Fin 3) ℂ)*(X (2:Fin 3) : MvPolynomial (Fin 3) ℂ)))*((X (1:Fin 3) : MvPolynomial (Fin 3) ℂ)-((C (q^6) : MvPolynomial (Fin 3) ℂ)*(X (0:Fin 3) : MvPolynomial (Fin 3) ℂ)))))).degreeOf (2:Fin 3)≤1 := dmul h2 h11 + simpa only [basePolyThree,basePolyThreeFactor,basePolyTwo] using h12 + +theorem basePolyTwo_bound_0_0 : + (basePolyTwo (X (0:Fin 2)) (X 1) .zero .zero).degreeOf 0 ≤ 1 := by + have h0 : ((X (0:Fin 2) : MvPolynomial (Fin 2) ℂ)).degreeOf (0:Fin 2)≤1 := by simp + have h1 : ((X (1:Fin 2) : MvPolynomial (Fin 2) ℂ)).degreeOf (0:Fin 2)≤0 := by simp [degreeOf_X] + have h2 : (((X (0:Fin 2) : MvPolynomial (Fin 2) ℂ)+(X (1:Fin 2) : MvPolynomial (Fin 2) ℂ))).degreeOf (0:Fin 2)≤1 := dadd (h0.trans (by omega)) (h1.trans (by omega)) + simpa only [basePolyThree,basePolyThreeFactor,basePolyTwo] using h2 + +theorem basePolyTwo_bound_0_1 : + (basePolyTwo (X (0:Fin 2)) (X 1) .zero .zero).degreeOf 1 ≤ 1 := by + have h0 : ((X (0:Fin 2) : MvPolynomial (Fin 2) ℂ)).degreeOf (1:Fin 2)≤0 := by simp [degreeOf_X] + have h1 : ((X (1:Fin 2) : MvPolynomial (Fin 2) ℂ)).degreeOf (1:Fin 2)≤1 := by simp + have h2 : (((X (0:Fin 2) : MvPolynomial (Fin 2) ℂ)+(X (1:Fin 2) : MvPolynomial (Fin 2) ℂ))).degreeOf (1:Fin 2)≤1 := dadd (h0.trans (by omega)) (h1.trans (by omega)) + simpa only [basePolyThree,basePolyThreeFactor,basePolyTwo] using h2 + +theorem basePolyTwo_bound_1_0 : + (basePolyTwo (X (0:Fin 2)) (X 1) .plus .minus).degreeOf 0 ≤ 0 := by + have h0 : ((C (q^5-q^7) : MvPolynomial (Fin 2) ℂ)).degreeOf (0:Fin 2)≤0 := le_of_eq (degreeOf_C _ _) + have h1 : ((X (1:Fin 2) : MvPolynomial (Fin 2) ℂ)).degreeOf (0:Fin 2)≤0 := by simp [degreeOf_X] + have h2 : (((C (q^5-q^7) : MvPolynomial (Fin 2) ℂ)*(X (1:Fin 2) : MvPolynomial (Fin 2) ℂ))).degreeOf (0:Fin 2)≤0 := dmul h0 h1 + simpa only [basePolyThree,basePolyThreeFactor,basePolyTwo] using h2 + +theorem basePolyTwo_bound_1_1 : + (basePolyTwo (X (0:Fin 2)) (X 1) .plus .minus).degreeOf 1 ≤ 1 := by + have h0 : ((C (q^5-q^7) : MvPolynomial (Fin 2) ℂ)).degreeOf (1:Fin 2)≤0 := le_of_eq (degreeOf_C _ _) + have h1 : ((X (1:Fin 2) : MvPolynomial (Fin 2) ℂ)).degreeOf (1:Fin 2)≤1 := by simp + have h2 : (((C (q^5-q^7) : MvPolynomial (Fin 2) ℂ)*(X (1:Fin 2) : MvPolynomial (Fin 2) ℂ))).degreeOf (1:Fin 2)≤1 := dmul h0 h1 + simpa only [basePolyThree,basePolyThreeFactor,basePolyTwo] using h2 + +theorem basePolyTwo_bound_2_0 : + (basePolyTwo (X (0:Fin 2)) (X 1) .minus .plus).degreeOf 0 ≤ 1 := by + have h0 : ((C (q-q^3) : MvPolynomial (Fin 2) ℂ)).degreeOf (0:Fin 2)≤0 := le_of_eq (degreeOf_C _ _) + have h1 : ((X (0:Fin 2) : MvPolynomial (Fin 2) ℂ)).degreeOf (0:Fin 2)≤1 := by simp + have h2 : (((C (q-q^3) : MvPolynomial (Fin 2) ℂ)*(X (0:Fin 2) : MvPolynomial (Fin 2) ℂ))).degreeOf (0:Fin 2)≤1 := dmul h0 h1 + simpa only [basePolyThree,basePolyThreeFactor,basePolyTwo] using h2 + +theorem basePolyTwo_bound_2_1 : + (basePolyTwo (X (0:Fin 2)) (X 1) .minus .plus).degreeOf 1 ≤ 0 := by + have h0 : ((C (q-q^3) : MvPolynomial (Fin 2) ℂ)).degreeOf (1:Fin 2)≤0 := le_of_eq (degreeOf_C _ _) + have h1 : ((X (0:Fin 2) : MvPolynomial (Fin 2) ℂ)).degreeOf (1:Fin 2)≤0 := by simp [degreeOf_X] + have h2 : (((C (q-q^3) : MvPolynomial (Fin 2) ℂ)*(X (0:Fin 2) : MvPolynomial (Fin 2) ℂ))).degreeOf (1:Fin 2)≤0 := dmul h0 h1 + simpa only [basePolyThree,basePolyThreeFactor,basePolyTwo] using h2 + +theorem vacuumThree_degrees (s : Fin 3 → Spin) (j : Fin 3) : + (vacuumThree s).degreeOf j≤2 ∧ (s j=Spin.plus → (vacuumThree s).degreeOf j≤1) := by + fin_cases j + · change (vacuumThree s).degreeOf (0:Fin 3)≤2 ∧ (s 0=Spin.plus → (vacuumThree s).degreeOf 0≤1) + cases h0 : s 0 <;> cases h1 : s 1 <;> cases h2 : s 2 + · have hb := basePolyThree_bound_0_0 + simp only [vacuumThree,h0,h1,h2] + constructor + · exact hb.trans (by omega) + · intro h; cases h + · simp [vacuumThree,h0,h1,h2,basePolyThree] + · simp [vacuumThree,h0,h1,h2,basePolyThree] + · simp [vacuumThree,h0,h1,h2,basePolyThree] + · simp [vacuumThree,h0,h1,h2,basePolyThree] + · have hb := basePolyThree_bound_3_0 + simp only [vacuumThree,h0,h1,h2] + constructor + · exact hb.trans (by omega) + · intro h; cases h + · simp [vacuumThree,h0,h1,h2,basePolyThree] + · have hb := basePolyThree_bound_4_0 + simp only [vacuumThree,h0,h1,h2] + constructor + · exact hb.trans (by omega) + · intro h; cases h + · simp [vacuumThree,h0,h1,h2,basePolyThree] + · simp [vacuumThree,h0,h1,h2,basePolyThree] + · simp [vacuumThree,h0,h1,h2,basePolyThree] + · have hb := basePolyThree_bound_5_0 + simp only [vacuumThree,h0,h1,h2] + constructor + · exact hb.trans (by omega) + · intro _; exact hb.trans (by omega) + · simp [vacuumThree,h0,h1,h2,basePolyThree] + · simp [vacuumThree,h0,h1,h2,basePolyThree] + · simp [vacuumThree,h0,h1,h2,basePolyThree] + · have hb := basePolyThree_bound_1_0 + simp only [vacuumThree,h0,h1,h2] + constructor + · exact hb.trans (by omega) + · intro _; exact hb.trans (by omega) + · simp [vacuumThree,h0,h1,h2,basePolyThree] + · simp [vacuumThree,h0,h1,h2,basePolyThree] + · simp [vacuumThree,h0,h1,h2,basePolyThree] + · have hb := basePolyThree_bound_6_0 + simp only [vacuumThree,h0,h1,h2] + constructor + · exact hb.trans (by omega) + · intro h; cases h + · simp [vacuumThree,h0,h1,h2,basePolyThree] + · have hb := basePolyThree_bound_2_0 + simp only [vacuumThree,h0,h1,h2] + constructor + · exact hb.trans (by omega) + · intro h; cases h + · simp [vacuumThree,h0,h1,h2,basePolyThree] + · simp [vacuumThree,h0,h1,h2,basePolyThree] + · simp [vacuumThree,h0,h1,h2,basePolyThree] + · simp [vacuumThree,h0,h1,h2,basePolyThree] + · simp [vacuumThree,h0,h1,h2,basePolyThree] + · change (vacuumThree s).degreeOf (1:Fin 3)≤2 ∧ (s 1=Spin.plus → (vacuumThree s).degreeOf 1≤1) + cases h0 : s 0 <;> cases h1 : s 1 <;> cases h2 : s 2 + · have hb := basePolyThree_bound_0_1 + simp only [vacuumThree,h0,h1,h2] + constructor + · exact hb.trans (by omega) + · intro h; cases h + · simp [vacuumThree,h0,h1,h2,basePolyThree] + · simp [vacuumThree,h0,h1,h2,basePolyThree] + · simp [vacuumThree,h0,h1,h2,basePolyThree] + · simp [vacuumThree,h0,h1,h2,basePolyThree] + · have hb := basePolyThree_bound_3_1 + simp only [vacuumThree,h0,h1,h2] + constructor + · exact hb.trans (by omega) + · intro _; exact hb.trans (by omega) + · simp [vacuumThree,h0,h1,h2,basePolyThree] + · have hb := basePolyThree_bound_4_1 + simp only [vacuumThree,h0,h1,h2] + constructor + · exact hb.trans (by omega) + · intro h; cases h + · simp [vacuumThree,h0,h1,h2,basePolyThree] + · simp [vacuumThree,h0,h1,h2,basePolyThree] + · simp [vacuumThree,h0,h1,h2,basePolyThree] + · have hb := basePolyThree_bound_5_1 + simp only [vacuumThree,h0,h1,h2] + constructor + · exact hb.trans (by omega) + · intro h; cases h + · simp [vacuumThree,h0,h1,h2,basePolyThree] + · simp [vacuumThree,h0,h1,h2,basePolyThree] + · simp [vacuumThree,h0,h1,h2,basePolyThree] + · have hb := basePolyThree_bound_1_1 + simp only [vacuumThree,h0,h1,h2] + constructor + · exact hb.trans (by omega) + · intro h; cases h + · simp [vacuumThree,h0,h1,h2,basePolyThree] + · simp [vacuumThree,h0,h1,h2,basePolyThree] + · simp [vacuumThree,h0,h1,h2,basePolyThree] + · have hb := basePolyThree_bound_6_1 + simp only [vacuumThree,h0,h1,h2] + constructor + · exact hb.trans (by omega) + · intro h; cases h + · simp [vacuumThree,h0,h1,h2,basePolyThree] + · have hb := basePolyThree_bound_2_1 + simp only [vacuumThree,h0,h1,h2] + constructor + · exact hb.trans (by omega) + · intro _; exact hb.trans (by omega) + · simp [vacuumThree,h0,h1,h2,basePolyThree] + · simp [vacuumThree,h0,h1,h2,basePolyThree] + · simp [vacuumThree,h0,h1,h2,basePolyThree] + · simp [vacuumThree,h0,h1,h2,basePolyThree] + · simp [vacuumThree,h0,h1,h2,basePolyThree] + · change (vacuumThree s).degreeOf (2:Fin 3)≤2 ∧ (s 2=Spin.plus → (vacuumThree s).degreeOf 2≤1) + cases h0 : s 0 <;> cases h1 : s 1 <;> cases h2 : s 2 + · have hb := basePolyThree_bound_0_2 + simp only [vacuumThree,h0,h1,h2] + constructor + · exact hb.trans (by omega) + · intro h; cases h + · simp [vacuumThree,h0,h1,h2,basePolyThree] + · simp [vacuumThree,h0,h1,h2,basePolyThree] + · simp [vacuumThree,h0,h1,h2,basePolyThree] + · simp [vacuumThree,h0,h1,h2,basePolyThree] + · have hb := basePolyThree_bound_3_2 + simp only [vacuumThree,h0,h1,h2] + constructor + · exact hb.trans (by omega) + · intro h; cases h + · simp [vacuumThree,h0,h1,h2,basePolyThree] + · have hb := basePolyThree_bound_4_2 + simp only [vacuumThree,h0,h1,h2] + constructor + · exact hb.trans (by omega) + · intro _; exact hb.trans (by omega) + · simp [vacuumThree,h0,h1,h2,basePolyThree] + · simp [vacuumThree,h0,h1,h2,basePolyThree] + · simp [vacuumThree,h0,h1,h2,basePolyThree] + · have hb := basePolyThree_bound_5_2 + simp only [vacuumThree,h0,h1,h2] + constructor + · exact hb.trans (by omega) + · intro h; cases h + · simp [vacuumThree,h0,h1,h2,basePolyThree] + · simp [vacuumThree,h0,h1,h2,basePolyThree] + · simp [vacuumThree,h0,h1,h2,basePolyThree] + · have hb := basePolyThree_bound_1_2 + simp only [vacuumThree,h0,h1,h2] + constructor + · exact hb.trans (by omega) + · intro h; cases h + · simp [vacuumThree,h0,h1,h2,basePolyThree] + · simp [vacuumThree,h0,h1,h2,basePolyThree] + · simp [vacuumThree,h0,h1,h2,basePolyThree] + · have hb := basePolyThree_bound_6_2 + simp only [vacuumThree,h0,h1,h2] + constructor + · exact hb.trans (by omega) + · intro _; exact hb.trans (by omega) + · simp [vacuumThree,h0,h1,h2,basePolyThree] + · have hb := basePolyThree_bound_2_2 + simp only [vacuumThree,h0,h1,h2] + constructor + · exact hb.trans (by omega) + · intro h; cases h + · simp [vacuumThree,h0,h1,h2,basePolyThree] + · simp [vacuumThree,h0,h1,h2,basePolyThree] + · simp [vacuumThree,h0,h1,h2,basePolyThree] + · simp [vacuumThree,h0,h1,h2,basePolyThree] + · simp [vacuumThree,h0,h1,h2,basePolyThree] +theorem vacuumThree_minusZero : MinusZero vacuumThree := by + intro s j h + fin_cases j + all_goals cases h0 : s 0 <;> cases h1 : s 1 <;> cases h2 : s 2 <;> + simp_all [vacuumThree,basePolyThree,basePolyThreeFactor,killSite_X,killSite_C] + +theorem vacuumTwo_degrees (s : Fin 2 → Spin) (j : Fin 2) : + (vacuumTwo s).degreeOf j≤1 ∧ (s j=Spin.plus → (vacuumTwo s).degreeOf j≤0) := by + fin_cases j + · change (vacuumTwo s).degreeOf (0:Fin 2)≤1 ∧ (s 0=Spin.plus → (vacuumTwo s).degreeOf 0≤0) + cases h0 : s 0 <;> cases h1 : s 1 + · have hb := basePolyTwo_bound_0_0 + simp only [vacuumTwo,h0,h1] + constructor + · exact hb.trans (by omega) + · intro h; cases h + · simp [vacuumTwo,h0,h1,basePolyTwo] + · simp [vacuumTwo,h0,h1,basePolyTwo] + · simp [vacuumTwo,h0,h1,basePolyTwo] + · simp [vacuumTwo,h0,h1,basePolyTwo] + · have hb := basePolyTwo_bound_1_0 + simp only [vacuumTwo,h0,h1] + constructor + · exact hb.trans (by omega) + · intro _; exact hb.trans (by omega) + · simp [vacuumTwo,h0,h1,basePolyTwo] + · have hb := basePolyTwo_bound_2_0 + simp only [vacuumTwo,h0,h1] + constructor + · exact hb.trans (by omega) + · intro h; cases h + · simp [vacuumTwo,h0,h1,basePolyTwo] + · change (vacuumTwo s).degreeOf (1:Fin 2)≤1 ∧ (s 1=Spin.plus → (vacuumTwo s).degreeOf 1≤0) + cases h0 : s 0 <;> cases h1 : s 1 + · have hb := basePolyTwo_bound_0_1 + simp only [vacuumTwo,h0,h1] + constructor + · exact hb.trans (by omega) + · intro h; cases h + · simp [vacuumTwo,h0,h1,basePolyTwo] + · simp [vacuumTwo,h0,h1,basePolyTwo] + · simp [vacuumTwo,h0,h1,basePolyTwo] + · simp [vacuumTwo,h0,h1,basePolyTwo] + · have hb := basePolyTwo_bound_1_1 + simp only [vacuumTwo,h0,h1] + constructor + · exact hb.trans (by omega) + · intro h; cases h + · simp [vacuumTwo,h0,h1,basePolyTwo] + · have hb := basePolyTwo_bound_2_1 + simp only [vacuumTwo,h0,h1] + constructor + · exact hb.trans (by omega) + · intro _; exact hb.trans (by omega) + · simp [vacuumTwo,h0,h1,basePolyTwo] +theorem vacuumTwo_minusZero : MinusZero vacuumTwo := by + intro s j h + fin_cases j + all_goals cases h0 : s 0 <;> cases h1 : s 1 <;> + simp_all [vacuumTwo,basePolyTwo,killSite_X,killSite_C] + +end PolynomialVacuumAlgebra + +end OAI diff --git a/lean/OAI/Combinatorics/PolynomialVacuum/Algebra/BaseEndpoints.lean b/lean/OAI/Combinatorics/PolynomialVacuum/Algebra/BaseEndpoints.lean new file mode 100644 index 0000000000000000000000000000000000000000..6cc06230a4c3cafef9a79884c2dd531c13d8be20 --- /dev/null +++ b/lean/OAI/Combinatorics/PolynomialVacuum/Algebra/BaseEndpoints.lean @@ -0,0 +1,57 @@ +import OAI.Combinatorics.PolynomialVacuum.Algebra.BaseNatural +import OAI.Combinatorics.PolynomialVacuum.Algebra.BaseThreeNode + +namespace OAI + +namespace PolynomialVacuumAlgebra +open MvPolynomial Classical + +theorem baseThree_lastCup (x y : ℂ) (a b c : Spin) : + baseThree x y (T*y) a b c = + (1+T)*y * (x-t^5*y)*(x-t^6*y) * cup (b,c) * (if a=Spin.zero then 1 else 0) := by + rw [← baseThree_rotation y (T*y) x a b c,baseThree_cup] + cases a <;> simp [charge] + +theorem vacuumThree_lastCup : CupAt (liftState vacuumThree) (liftState vacuumOne) 1 1 := by + intro X hX + funext s + simpa [naturalFusion,fusionProduct,fusionPair,cupLinear,skipTwo,hX,mul_assoc] using baseThree_lastCup (X 0) (X 1) (s 0) (s 1) (s 2) + +theorem vacuumTwo_nodes : NaturalCupNodes (liftState vacuumTwo) (liftState vacuumZero) 0 := by + intro X i hi hX + have : i=0 := by omega + subst i + rw [naturalPrescription_last_cup] + exact vacuumTwo_firstCup X hX + +theorem vacuumThree_nodes : NaturalCupNodes (liftState vacuumThree) (liftState vacuumOne) 1 := by + intro X i hi hX + interval_cases i + · funext s + simpa [naturalPrescription,leftFusion,braidTrain,cupLinear,siteR,pairLinear,pairAction, + replacePair,skipTwo,skipOne,hX,update_nat_decidable,mul_assoc] using baseThree_node (X 0) (X 1) (s 0) (s 1) (s 2) + · rw [naturalPrescription_last_cup] + exact vacuumThree_lastCup X hX + +theorem vacuumOne_lastZero : LastZeroReduction (liftState vacuumOne) (liftState vacuumZero) 0 := by + intro X s hX hs + simp [prefixProduct] + +theorem vacuumTwo_lastZero : LastZeroReduction (liftState vacuumTwo) (liftState vacuumOne) 1 := by + intro X s hX hs + cases h0 : s 0 <;> cases h1 : s 1 <;> + simp_all [baseTwo,prefixProduct] + +theorem baseThree_lastZero (x y : ℂ) (a b c : Spin) (hc : c≠Spin.plus) : + baseThree x y 0 a b c=(if c=Spin.zero then x*y*baseTwo x y a b else 0) := by + cases a <;> cases b <;> cases c <;> + simp_all [baseThree,baseThreeFactor,baseTwo] + all_goals vacuum_ring_finish + +theorem vacuumThree_lastZero : LastZeroReduction (liftState vacuumThree) (liftState vacuumTwo) 2 := by + intro X s hX hs + simpa [prefixProduct,hX,Finset.prod_range_succ] using baseThree_lastZero (X 0) (X 1) (s 0) (s 1) (s 2) hs + +end PolynomialVacuumAlgebra + +end OAI diff --git a/lean/OAI/Combinatorics/PolynomialVacuum/Algebra/BaseGrading.lean b/lean/OAI/Combinatorics/PolynomialVacuum/Algebra/BaseGrading.lean new file mode 100644 index 0000000000000000000000000000000000000000..f4f199c050b52a92e94066c5b27afedf625c66c1 --- /dev/null +++ b/lean/OAI/Combinatorics/PolynomialVacuum/Algebra/BaseGrading.lean @@ -0,0 +1,212 @@ +import OAI.Combinatorics.PolynomialVacuum.Algebra.BasePolynomials + +namespace OAI + +namespace PolynomialVacuumAlgebra +open MvPolynomial Classical +theorem basePolyTwo_homogeneous_0 : + (basePolyTwo (X (0:Fin 2)) (X (1:Fin 2)) .zero .zero).IsHomogeneous 1 := by + have h0 : ((X (0:Fin 2) : MvPolynomial (Fin 2) ℂ)).IsHomogeneous 1 := isHomogeneous_X _ _ + have h1 : ((X (1:Fin 2) : MvPolynomial (Fin 2) ℂ)).IsHomogeneous 1 := isHomogeneous_X _ _ + have h2 : (((X (0:Fin 2) : MvPolynomial (Fin 2) ℂ)+(X (1:Fin 2) : MvPolynomial (Fin 2) ℂ))).IsHomogeneous 1 := h0.add h1 + simpa only [basePolyThree,basePolyThreeFactor,basePolyTwo] using h2 + +theorem basePolyTwo_homogeneous_1 : + (basePolyTwo (X (0:Fin 2)) (X (1:Fin 2)) .plus .minus).IsHomogeneous 1 := by + have h0 : ((C (q^5-q^7) : MvPolynomial (Fin 2) ℂ)).IsHomogeneous 0 := isHomogeneous_C _ _ + have h1 : ((X (1:Fin 2) : MvPolynomial (Fin 2) ℂ)).IsHomogeneous 1 := isHomogeneous_X _ _ + have h2 : (((C (q^5-q^7) : MvPolynomial (Fin 2) ℂ)*(X (1:Fin 2) : MvPolynomial (Fin 2) ℂ))).IsHomogeneous 1 := h0.mul h1 + simpa only [basePolyThree,basePolyThreeFactor,basePolyTwo] using h2 + +theorem basePolyTwo_homogeneous_2 : + (basePolyTwo (X (0:Fin 2)) (X (1:Fin 2)) .minus .plus).IsHomogeneous 1 := by + have h0 : ((C (q-q^3) : MvPolynomial (Fin 2) ℂ)).IsHomogeneous 0 := isHomogeneous_C _ _ + have h1 : ((X (0:Fin 2) : MvPolynomial (Fin 2) ℂ)).IsHomogeneous 1 := isHomogeneous_X _ _ + have h2 : (((C (q-q^3) : MvPolynomial (Fin 2) ℂ)*(X (0:Fin 2) : MvPolynomial (Fin 2) ℂ))).IsHomogeneous 1 := h0.mul h1 + simpa only [basePolyThree,basePolyThreeFactor,basePolyTwo] using h2 + +theorem vacuumTwo_homogeneous (s : Fin 2 → Spin) : + (vacuumTwo s).IsHomogeneous ((2:ℕ).choose 2) := by + rw [show (2:ℕ).choose 2=1 from by decide] + cases h0 : s 0 <;> cases h1 : s 1 + · simpa only [vacuumTwo,h0,h1] using basePolyTwo_homogeneous_0 + · simp only [vacuumTwo,h0,h1,basePolyTwo]; exact isHomogeneous_zero _ _ _ + · simp only [vacuumTwo,h0,h1,basePolyTwo]; exact isHomogeneous_zero _ _ _ + · simp only [vacuumTwo,h0,h1,basePolyTwo]; exact isHomogeneous_zero _ _ _ + · simp only [vacuumTwo,h0,h1,basePolyTwo]; exact isHomogeneous_zero _ _ _ + · simpa only [vacuumTwo,h0,h1] using basePolyTwo_homogeneous_1 + · simp only [vacuumTwo,h0,h1,basePolyTwo]; exact isHomogeneous_zero _ _ _ + · simpa only [vacuumTwo,h0,h1] using basePolyTwo_homogeneous_2 + · simp only [vacuumTwo,h0,h1,basePolyTwo]; exact isHomogeneous_zero _ _ _ +theorem vacuumTwo_charge (s : Fin 2 → Spin) (h : (∑ j, charge (s j))≠0) : + vacuumTwo s=0 := by + cases h0 : s 0 <;> cases h1 : s 1 <;> + simp_all [vacuumTwo,basePolyTwo,Fin.sum_univ_succ,charge] + +theorem basePolyThree_homogeneous_0 : + (basePolyThree (X (0:Fin 3)) (X (1:Fin 3)) (X (2:Fin 3)) .zero .zero .zero).IsHomogeneous 3 := by + have h0 : ((X (0:Fin 3) : MvPolynomial (Fin 3) ℂ)).IsHomogeneous 1 := isHomogeneous_X _ _ + have h1 : (((X (0:Fin 3) : MvPolynomial (Fin 3) ℂ)^2)).IsHomogeneous 2 := h0.pow 2 + have h2 : ((X (1:Fin 3) : MvPolynomial (Fin 3) ℂ)).IsHomogeneous 1 := isHomogeneous_X _ _ + have h3 : ((((X (0:Fin 3) : MvPolynomial (Fin 3) ℂ)^2)*(X (1:Fin 3) : MvPolynomial (Fin 3) ℂ))).IsHomogeneous 3 := h1.mul h2 + have h4 : ((X (2:Fin 3) : MvPolynomial (Fin 3) ℂ)).IsHomogeneous 1 := isHomogeneous_X _ _ + have h5 : ((((X (0:Fin 3) : MvPolynomial (Fin 3) ℂ)^2)*(X (2:Fin 3) : MvPolynomial (Fin 3) ℂ))).IsHomogeneous 3 := h1.mul h4 + have h6 : (((((X (0:Fin 3) : MvPolynomial (Fin 3) ℂ)^2)*(X (1:Fin 3) : MvPolynomial (Fin 3) ℂ))+(((X (0:Fin 3) : MvPolynomial (Fin 3) ℂ)^2)*(X (2:Fin 3) : MvPolynomial (Fin 3) ℂ)))).IsHomogeneous 3 := h3.add h5 + have h7 : (((X (1:Fin 3) : MvPolynomial (Fin 3) ℂ)^2)).IsHomogeneous 2 := h2.pow 2 + have h8 : ((((X (1:Fin 3) : MvPolynomial (Fin 3) ℂ)^2)*(X (0:Fin 3) : MvPolynomial (Fin 3) ℂ))).IsHomogeneous 3 := h7.mul h0 + have h9 : ((((((X (0:Fin 3) : MvPolynomial (Fin 3) ℂ)^2)*(X (1:Fin 3) : MvPolynomial (Fin 3) ℂ))+(((X (0:Fin 3) : MvPolynomial (Fin 3) ℂ)^2)*(X (2:Fin 3) : MvPolynomial (Fin 3) ℂ)))+(((X (1:Fin 3) : MvPolynomial (Fin 3) ℂ)^2)*(X (0:Fin 3) : MvPolynomial (Fin 3) ℂ)))).IsHomogeneous 3 := h6.add h8 + have h10 : ((((X (1:Fin 3) : MvPolynomial (Fin 3) ℂ)^2)*(X (2:Fin 3) : MvPolynomial (Fin 3) ℂ))).IsHomogeneous 3 := h7.mul h4 + have h11 : (((((((X (0:Fin 3) : MvPolynomial (Fin 3) ℂ)^2)*(X (1:Fin 3) : MvPolynomial (Fin 3) ℂ))+(((X (0:Fin 3) : MvPolynomial (Fin 3) ℂ)^2)*(X (2:Fin 3) : MvPolynomial (Fin 3) ℂ)))+(((X (1:Fin 3) : MvPolynomial (Fin 3) ℂ)^2)*(X (0:Fin 3) : MvPolynomial (Fin 3) ℂ)))+(((X (1:Fin 3) : MvPolynomial (Fin 3) ℂ)^2)*(X (2:Fin 3) : MvPolynomial (Fin 3) ℂ)))).IsHomogeneous 3 := h9.add h10 + have h12 : (((X (2:Fin 3) : MvPolynomial (Fin 3) ℂ)^2)).IsHomogeneous 2 := h4.pow 2 + have h13 : ((((X (2:Fin 3) : MvPolynomial (Fin 3) ℂ)^2)*(X (0:Fin 3) : MvPolynomial (Fin 3) ℂ))).IsHomogeneous 3 := h12.mul h0 + have h14 : ((((((((X (0:Fin 3) : MvPolynomial (Fin 3) ℂ)^2)*(X (1:Fin 3) : MvPolynomial (Fin 3) ℂ))+(((X (0:Fin 3) : MvPolynomial (Fin 3) ℂ)^2)*(X (2:Fin 3) : MvPolynomial (Fin 3) ℂ)))+(((X (1:Fin 3) : MvPolynomial (Fin 3) ℂ)^2)*(X (0:Fin 3) : MvPolynomial (Fin 3) ℂ)))+(((X (1:Fin 3) : MvPolynomial (Fin 3) ℂ)^2)*(X (2:Fin 3) : MvPolynomial (Fin 3) ℂ)))+(((X (2:Fin 3) : MvPolynomial (Fin 3) ℂ)^2)*(X (0:Fin 3) : MvPolynomial (Fin 3) ℂ)))).IsHomogeneous 3 := h11.add h13 + have h15 : ((((X (2:Fin 3) : MvPolynomial (Fin 3) ℂ)^2)*(X (1:Fin 3) : MvPolynomial (Fin 3) ℂ))).IsHomogeneous 3 := h12.mul h2 + have h16 : (((((((((X (0:Fin 3) : MvPolynomial (Fin 3) ℂ)^2)*(X (1:Fin 3) : MvPolynomial (Fin 3) ℂ))+(((X (0:Fin 3) : MvPolynomial (Fin 3) ℂ)^2)*(X (2:Fin 3) : MvPolynomial (Fin 3) ℂ)))+(((X (1:Fin 3) : MvPolynomial (Fin 3) ℂ)^2)*(X (0:Fin 3) : MvPolynomial (Fin 3) ℂ)))+(((X (1:Fin 3) : MvPolynomial (Fin 3) ℂ)^2)*(X (2:Fin 3) : MvPolynomial (Fin 3) ℂ)))+(((X (2:Fin 3) : MvPolynomial (Fin 3) ℂ)^2)*(X (0:Fin 3) : MvPolynomial (Fin 3) ℂ)))+(((X (2:Fin 3) : MvPolynomial (Fin 3) ℂ)^2)*(X (1:Fin 3) : MvPolynomial (Fin 3) ℂ)))).IsHomogeneous 3 := h14.add h15 + have h17 : ((C (2*(q^2-q^6)) : MvPolynomial (Fin 3) ℂ)).IsHomogeneous 0 := isHomogeneous_C _ _ + have h18 : (((C (2*(q^2-q^6)) : MvPolynomial (Fin 3) ℂ)*(X (0:Fin 3) : MvPolynomial (Fin 3) ℂ))).IsHomogeneous 1 := h17.mul h0 + have h19 : ((((C (2*(q^2-q^6)) : MvPolynomial (Fin 3) ℂ)*(X (0:Fin 3) : MvPolynomial (Fin 3) ℂ))*(X (1:Fin 3) : MvPolynomial (Fin 3) ℂ))).IsHomogeneous 2 := h18.mul h2 + have h20 : (((((C (2*(q^2-q^6)) : MvPolynomial (Fin 3) ℂ)*(X (0:Fin 3) : MvPolynomial (Fin 3) ℂ))*(X (1:Fin 3) : MvPolynomial (Fin 3) ℂ))*(X (2:Fin 3) : MvPolynomial (Fin 3) ℂ))).IsHomogeneous 3 := h19.mul h4 + have h21 : ((((((((((X (0:Fin 3) : MvPolynomial (Fin 3) ℂ)^2)*(X (1:Fin 3) : MvPolynomial (Fin 3) ℂ))+(((X (0:Fin 3) : MvPolynomial (Fin 3) ℂ)^2)*(X (2:Fin 3) : MvPolynomial (Fin 3) ℂ)))+(((X (1:Fin 3) : MvPolynomial (Fin 3) ℂ)^2)*(X (0:Fin 3) : MvPolynomial (Fin 3) ℂ)))+(((X (1:Fin 3) : MvPolynomial (Fin 3) ℂ)^2)*(X (2:Fin 3) : MvPolynomial (Fin 3) ℂ)))+(((X (2:Fin 3) : MvPolynomial (Fin 3) ℂ)^2)*(X (0:Fin 3) : MvPolynomial (Fin 3) ℂ)))+(((X (2:Fin 3) : MvPolynomial (Fin 3) ℂ)^2)*(X (1:Fin 3) : MvPolynomial (Fin 3) ℂ)))+((((C (2*(q^2-q^6)) : MvPolynomial (Fin 3) ℂ)*(X (0:Fin 3) : MvPolynomial (Fin 3) ℂ))*(X (1:Fin 3) : MvPolynomial (Fin 3) ℂ))*(X (2:Fin 3) : MvPolynomial (Fin 3) ℂ)))).IsHomogeneous 3 := h16.add h20 + simpa only [basePolyThree,basePolyThreeFactor,basePolyTwo] using h21 + +theorem basePolyThree_homogeneous_1 : + (basePolyThree (X (0:Fin 3)) (X (1:Fin 3)) (X (2:Fin 3)) .plus .minus .zero).IsHomogeneous 3 := by + have h0 : ((C (q^5-q^7) : MvPolynomial (Fin 3) ℂ)).IsHomogeneous 0 := isHomogeneous_C _ _ + have h1 : ((X (1:Fin 3) : MvPolynomial (Fin 3) ℂ)).IsHomogeneous 1 := isHomogeneous_X _ _ + have h2 : (((C (q^5-q^7) : MvPolynomial (Fin 3) ℂ)*(X (1:Fin 3) : MvPolynomial (Fin 3) ℂ))).IsHomogeneous 1 := h0.mul h1 + have h3 : ((X (2:Fin 3) : MvPolynomial (Fin 3) ℂ)).IsHomogeneous 1 := isHomogeneous_X _ _ + have h4 : ((C (q^2) : MvPolynomial (Fin 3) ℂ)).IsHomogeneous 0 := isHomogeneous_C _ _ + have h5 : ((X (0:Fin 3) : MvPolynomial (Fin 3) ℂ)).IsHomogeneous 1 := isHomogeneous_X _ _ + have h6 : (((C (q^2) : MvPolynomial (Fin 3) ℂ)*(X (0:Fin 3) : MvPolynomial (Fin 3) ℂ))).IsHomogeneous 1 := h4.mul h5 + have h7 : (((X (2:Fin 3) : MvPolynomial (Fin 3) ℂ)+((C (q^2) : MvPolynomial (Fin 3) ℂ)*(X (0:Fin 3) : MvPolynomial (Fin 3) ℂ)))).IsHomogeneous 1 := h3.add h6 + have h8 : ((C (q^6) : MvPolynomial (Fin 3) ℂ)).IsHomogeneous 0 := isHomogeneous_C _ _ + have h9 : (((C (q^6) : MvPolynomial (Fin 3) ℂ)*(X (1:Fin 3) : MvPolynomial (Fin 3) ℂ))).IsHomogeneous 1 := h8.mul h1 + have h10 : (((X (2:Fin 3) : MvPolynomial (Fin 3) ℂ)-((C (q^6) : MvPolynomial (Fin 3) ℂ)*(X (1:Fin 3) : MvPolynomial (Fin 3) ℂ)))).IsHomogeneous 1 := h3.sub h9 + have h11 : ((((X (2:Fin 3) : MvPolynomial (Fin 3) ℂ)+((C (q^2) : MvPolynomial (Fin 3) ℂ)*(X (0:Fin 3) : MvPolynomial (Fin 3) ℂ)))*((X (2:Fin 3) : MvPolynomial (Fin 3) ℂ)-((C (q^6) : MvPolynomial (Fin 3) ℂ)*(X (1:Fin 3) : MvPolynomial (Fin 3) ℂ))))).IsHomogeneous 2 := h7.mul h10 + have h12 : ((((C (q^5-q^7) : MvPolynomial (Fin 3) ℂ)*(X (1:Fin 3) : MvPolynomial (Fin 3) ℂ))*(((X (2:Fin 3) : MvPolynomial (Fin 3) ℂ)+((C (q^2) : MvPolynomial (Fin 3) ℂ)*(X (0:Fin 3) : MvPolynomial (Fin 3) ℂ)))*((X (2:Fin 3) : MvPolynomial (Fin 3) ℂ)-((C (q^6) : MvPolynomial (Fin 3) ℂ)*(X (1:Fin 3) : MvPolynomial (Fin 3) ℂ)))))).IsHomogeneous 3 := h2.mul h11 + simpa only [basePolyThree,basePolyThreeFactor,basePolyTwo] using h12 + +theorem basePolyThree_homogeneous_2 : + (basePolyThree (X (0:Fin 3)) (X (1:Fin 3)) (X (2:Fin 3)) .minus .plus .zero).IsHomogeneous 3 := by + have h0 : ((C (q-q^3) : MvPolynomial (Fin 3) ℂ)).IsHomogeneous 0 := isHomogeneous_C _ _ + have h1 : ((X (0:Fin 3) : MvPolynomial (Fin 3) ℂ)).IsHomogeneous 1 := isHomogeneous_X _ _ + have h2 : (((C (q-q^3) : MvPolynomial (Fin 3) ℂ)*(X (0:Fin 3) : MvPolynomial (Fin 3) ℂ))).IsHomogeneous 1 := h0.mul h1 + have h3 : ((X (2:Fin 3) : MvPolynomial (Fin 3) ℂ)).IsHomogeneous 1 := isHomogeneous_X _ _ + have h4 : ((C (q^2) : MvPolynomial (Fin 3) ℂ)).IsHomogeneous 0 := isHomogeneous_C _ _ + have h5 : (((C (q^2) : MvPolynomial (Fin 3) ℂ)*(X (0:Fin 3) : MvPolynomial (Fin 3) ℂ))).IsHomogeneous 1 := h4.mul h1 + have h6 : (((X (2:Fin 3) : MvPolynomial (Fin 3) ℂ)+((C (q^2) : MvPolynomial (Fin 3) ℂ)*(X (0:Fin 3) : MvPolynomial (Fin 3) ℂ)))).IsHomogeneous 1 := h3.add h5 + have h7 : ((C (q^6) : MvPolynomial (Fin 3) ℂ)).IsHomogeneous 0 := isHomogeneous_C _ _ + have h8 : ((X (1:Fin 3) : MvPolynomial (Fin 3) ℂ)).IsHomogeneous 1 := isHomogeneous_X _ _ + have h9 : (((C (q^6) : MvPolynomial (Fin 3) ℂ)*(X (1:Fin 3) : MvPolynomial (Fin 3) ℂ))).IsHomogeneous 1 := h7.mul h8 + have h10 : (((X (2:Fin 3) : MvPolynomial (Fin 3) ℂ)-((C (q^6) : MvPolynomial (Fin 3) ℂ)*(X (1:Fin 3) : MvPolynomial (Fin 3) ℂ)))).IsHomogeneous 1 := h3.sub h9 + have h11 : ((((X (2:Fin 3) : MvPolynomial (Fin 3) ℂ)+((C (q^2) : MvPolynomial (Fin 3) ℂ)*(X (0:Fin 3) : MvPolynomial (Fin 3) ℂ)))*((X (2:Fin 3) : MvPolynomial (Fin 3) ℂ)-((C (q^6) : MvPolynomial (Fin 3) ℂ)*(X (1:Fin 3) : MvPolynomial (Fin 3) ℂ))))).IsHomogeneous 2 := h6.mul h10 + have h12 : ((((C (q-q^3) : MvPolynomial (Fin 3) ℂ)*(X (0:Fin 3) : MvPolynomial (Fin 3) ℂ))*(((X (2:Fin 3) : MvPolynomial (Fin 3) ℂ)+((C (q^2) : MvPolynomial (Fin 3) ℂ)*(X (0:Fin 3) : MvPolynomial (Fin 3) ℂ)))*((X (2:Fin 3) : MvPolynomial (Fin 3) ℂ)-((C (q^6) : MvPolynomial (Fin 3) ℂ)*(X (1:Fin 3) : MvPolynomial (Fin 3) ℂ)))))).IsHomogeneous 3 := h2.mul h11 + simpa only [basePolyThree,basePolyThreeFactor,basePolyTwo] using h12 + +theorem basePolyThree_homogeneous_3 : + (basePolyThree (X (0:Fin 3)) (X (1:Fin 3)) (X (2:Fin 3)) .zero .plus .minus).IsHomogeneous 3 := by + have h0 : ((C (q^5-q^7) : MvPolynomial (Fin 3) ℂ)).IsHomogeneous 0 := isHomogeneous_C _ _ + have h1 : ((X (2:Fin 3) : MvPolynomial (Fin 3) ℂ)).IsHomogeneous 1 := isHomogeneous_X _ _ + have h2 : (((C (q^5-q^7) : MvPolynomial (Fin 3) ℂ)*(X (2:Fin 3) : MvPolynomial (Fin 3) ℂ))).IsHomogeneous 1 := h0.mul h1 + have h3 : ((X (0:Fin 3) : MvPolynomial (Fin 3) ℂ)).IsHomogeneous 1 := isHomogeneous_X _ _ + have h4 : ((C (q^2) : MvPolynomial (Fin 3) ℂ)).IsHomogeneous 0 := isHomogeneous_C _ _ + have h5 : ((X (1:Fin 3) : MvPolynomial (Fin 3) ℂ)).IsHomogeneous 1 := isHomogeneous_X _ _ + have h6 : (((C (q^2) : MvPolynomial (Fin 3) ℂ)*(X (1:Fin 3) : MvPolynomial (Fin 3) ℂ))).IsHomogeneous 1 := h4.mul h5 + have h7 : (((X (0:Fin 3) : MvPolynomial (Fin 3) ℂ)+((C (q^2) : MvPolynomial (Fin 3) ℂ)*(X (1:Fin 3) : MvPolynomial (Fin 3) ℂ)))).IsHomogeneous 1 := h3.add h6 + have h8 : ((C (q^6) : MvPolynomial (Fin 3) ℂ)).IsHomogeneous 0 := isHomogeneous_C _ _ + have h9 : (((C (q^6) : MvPolynomial (Fin 3) ℂ)*(X (2:Fin 3) : MvPolynomial (Fin 3) ℂ))).IsHomogeneous 1 := h8.mul h1 + have h10 : (((X (0:Fin 3) : MvPolynomial (Fin 3) ℂ)-((C (q^6) : MvPolynomial (Fin 3) ℂ)*(X (2:Fin 3) : MvPolynomial (Fin 3) ℂ)))).IsHomogeneous 1 := h3.sub h9 + have h11 : ((((X (0:Fin 3) : MvPolynomial (Fin 3) ℂ)+((C (q^2) : MvPolynomial (Fin 3) ℂ)*(X (1:Fin 3) : MvPolynomial (Fin 3) ℂ)))*((X (0:Fin 3) : MvPolynomial (Fin 3) ℂ)-((C (q^6) : MvPolynomial (Fin 3) ℂ)*(X (2:Fin 3) : MvPolynomial (Fin 3) ℂ))))).IsHomogeneous 2 := h7.mul h10 + have h12 : ((((C (q^5-q^7) : MvPolynomial (Fin 3) ℂ)*(X (2:Fin 3) : MvPolynomial (Fin 3) ℂ))*(((X (0:Fin 3) : MvPolynomial (Fin 3) ℂ)+((C (q^2) : MvPolynomial (Fin 3) ℂ)*(X (1:Fin 3) : MvPolynomial (Fin 3) ℂ)))*((X (0:Fin 3) : MvPolynomial (Fin 3) ℂ)-((C (q^6) : MvPolynomial (Fin 3) ℂ)*(X (2:Fin 3) : MvPolynomial (Fin 3) ℂ)))))).IsHomogeneous 3 := h2.mul h11 + simpa only [basePolyThree,basePolyThreeFactor,basePolyTwo] using h12 + +theorem basePolyThree_homogeneous_4 : + (basePolyThree (X (0:Fin 3)) (X (1:Fin 3)) (X (2:Fin 3)) .zero .minus .plus).IsHomogeneous 3 := by + have h0 : ((C (q-q^3) : MvPolynomial (Fin 3) ℂ)).IsHomogeneous 0 := isHomogeneous_C _ _ + have h1 : ((X (1:Fin 3) : MvPolynomial (Fin 3) ℂ)).IsHomogeneous 1 := isHomogeneous_X _ _ + have h2 : (((C (q-q^3) : MvPolynomial (Fin 3) ℂ)*(X (1:Fin 3) : MvPolynomial (Fin 3) ℂ))).IsHomogeneous 1 := h0.mul h1 + have h3 : ((X (0:Fin 3) : MvPolynomial (Fin 3) ℂ)).IsHomogeneous 1 := isHomogeneous_X _ _ + have h4 : ((C (q^2) : MvPolynomial (Fin 3) ℂ)).IsHomogeneous 0 := isHomogeneous_C _ _ + have h5 : (((C (q^2) : MvPolynomial (Fin 3) ℂ)*(X (1:Fin 3) : MvPolynomial (Fin 3) ℂ))).IsHomogeneous 1 := h4.mul h1 + have h6 : (((X (0:Fin 3) : MvPolynomial (Fin 3) ℂ)+((C (q^2) : MvPolynomial (Fin 3) ℂ)*(X (1:Fin 3) : MvPolynomial (Fin 3) ℂ)))).IsHomogeneous 1 := h3.add h5 + have h7 : ((C (q^6) : MvPolynomial (Fin 3) ℂ)).IsHomogeneous 0 := isHomogeneous_C _ _ + have h8 : ((X (2:Fin 3) : MvPolynomial (Fin 3) ℂ)).IsHomogeneous 1 := isHomogeneous_X _ _ + have h9 : (((C (q^6) : MvPolynomial (Fin 3) ℂ)*(X (2:Fin 3) : MvPolynomial (Fin 3) ℂ))).IsHomogeneous 1 := h7.mul h8 + have h10 : (((X (0:Fin 3) : MvPolynomial (Fin 3) ℂ)-((C (q^6) : MvPolynomial (Fin 3) ℂ)*(X (2:Fin 3) : MvPolynomial (Fin 3) ℂ)))).IsHomogeneous 1 := h3.sub h9 + have h11 : ((((X (0:Fin 3) : MvPolynomial (Fin 3) ℂ)+((C (q^2) : MvPolynomial (Fin 3) ℂ)*(X (1:Fin 3) : MvPolynomial (Fin 3) ℂ)))*((X (0:Fin 3) : MvPolynomial (Fin 3) ℂ)-((C (q^6) : MvPolynomial (Fin 3) ℂ)*(X (2:Fin 3) : MvPolynomial (Fin 3) ℂ))))).IsHomogeneous 2 := h6.mul h10 + have h12 : ((((C (q-q^3) : MvPolynomial (Fin 3) ℂ)*(X (1:Fin 3) : MvPolynomial (Fin 3) ℂ))*(((X (0:Fin 3) : MvPolynomial (Fin 3) ℂ)+((C (q^2) : MvPolynomial (Fin 3) ℂ)*(X (1:Fin 3) : MvPolynomial (Fin 3) ℂ)))*((X (0:Fin 3) : MvPolynomial (Fin 3) ℂ)-((C (q^6) : MvPolynomial (Fin 3) ℂ)*(X (2:Fin 3) : MvPolynomial (Fin 3) ℂ)))))).IsHomogeneous 3 := h2.mul h11 + simpa only [basePolyThree,basePolyThreeFactor,basePolyTwo] using h12 + +theorem basePolyThree_homogeneous_5 : + (basePolyThree (X (0:Fin 3)) (X (1:Fin 3)) (X (2:Fin 3)) .plus .zero .minus).IsHomogeneous 3 := by + have h0 : ((C (q^5-q^7) : MvPolynomial (Fin 3) ℂ)).IsHomogeneous 0 := isHomogeneous_C _ _ + have h1 : ((X (2:Fin 3) : MvPolynomial (Fin 3) ℂ)).IsHomogeneous 1 := isHomogeneous_X _ _ + have h2 : (((C (q^5-q^7) : MvPolynomial (Fin 3) ℂ)*(X (2:Fin 3) : MvPolynomial (Fin 3) ℂ))).IsHomogeneous 1 := h0.mul h1 + have h3 : ((X (1:Fin 3) : MvPolynomial (Fin 3) ℂ)).IsHomogeneous 1 := isHomogeneous_X _ _ + have h4 : ((C (q^2) : MvPolynomial (Fin 3) ℂ)).IsHomogeneous 0 := isHomogeneous_C _ _ + have h5 : (((C (q^2) : MvPolynomial (Fin 3) ℂ)*(X (2:Fin 3) : MvPolynomial (Fin 3) ℂ))).IsHomogeneous 1 := h4.mul h1 + have h6 : (((X (1:Fin 3) : MvPolynomial (Fin 3) ℂ)+((C (q^2) : MvPolynomial (Fin 3) ℂ)*(X (2:Fin 3) : MvPolynomial (Fin 3) ℂ)))).IsHomogeneous 1 := h3.add h5 + have h7 : ((C (q^6) : MvPolynomial (Fin 3) ℂ)).IsHomogeneous 0 := isHomogeneous_C _ _ + have h8 : ((X (0:Fin 3) : MvPolynomial (Fin 3) ℂ)).IsHomogeneous 1 := isHomogeneous_X _ _ + have h9 : (((C (q^6) : MvPolynomial (Fin 3) ℂ)*(X (0:Fin 3) : MvPolynomial (Fin 3) ℂ))).IsHomogeneous 1 := h7.mul h8 + have h10 : (((X (1:Fin 3) : MvPolynomial (Fin 3) ℂ)-((C (q^6) : MvPolynomial (Fin 3) ℂ)*(X (0:Fin 3) : MvPolynomial (Fin 3) ℂ)))).IsHomogeneous 1 := h3.sub h9 + have h11 : ((((X (1:Fin 3) : MvPolynomial (Fin 3) ℂ)+((C (q^2) : MvPolynomial (Fin 3) ℂ)*(X (2:Fin 3) : MvPolynomial (Fin 3) ℂ)))*((X (1:Fin 3) : MvPolynomial (Fin 3) ℂ)-((C (q^6) : MvPolynomial (Fin 3) ℂ)*(X (0:Fin 3) : MvPolynomial (Fin 3) ℂ))))).IsHomogeneous 2 := h6.mul h10 + have h12 : ((((C (q^5-q^7) : MvPolynomial (Fin 3) ℂ)*(X (2:Fin 3) : MvPolynomial (Fin 3) ℂ))*(((X (1:Fin 3) : MvPolynomial (Fin 3) ℂ)+((C (q^2) : MvPolynomial (Fin 3) ℂ)*(X (2:Fin 3) : MvPolynomial (Fin 3) ℂ)))*((X (1:Fin 3) : MvPolynomial (Fin 3) ℂ)-((C (q^6) : MvPolynomial (Fin 3) ℂ)*(X (0:Fin 3) : MvPolynomial (Fin 3) ℂ)))))).IsHomogeneous 3 := h2.mul h11 + simpa only [basePolyThree,basePolyThreeFactor,basePolyTwo] using h12 + +theorem basePolyThree_homogeneous_6 : + (basePolyThree (X (0:Fin 3)) (X (1:Fin 3)) (X (2:Fin 3)) .minus .zero .plus).IsHomogeneous 3 := by + have h0 : ((C (q-q^3) : MvPolynomial (Fin 3) ℂ)).IsHomogeneous 0 := isHomogeneous_C _ _ + have h1 : ((X (0:Fin 3) : MvPolynomial (Fin 3) ℂ)).IsHomogeneous 1 := isHomogeneous_X _ _ + have h2 : (((C (q-q^3) : MvPolynomial (Fin 3) ℂ)*(X (0:Fin 3) : MvPolynomial (Fin 3) ℂ))).IsHomogeneous 1 := h0.mul h1 + have h3 : ((X (1:Fin 3) : MvPolynomial (Fin 3) ℂ)).IsHomogeneous 1 := isHomogeneous_X _ _ + have h4 : ((C (q^2) : MvPolynomial (Fin 3) ℂ)).IsHomogeneous 0 := isHomogeneous_C _ _ + have h5 : ((X (2:Fin 3) : MvPolynomial (Fin 3) ℂ)).IsHomogeneous 1 := isHomogeneous_X _ _ + have h6 : (((C (q^2) : MvPolynomial (Fin 3) ℂ)*(X (2:Fin 3) : MvPolynomial (Fin 3) ℂ))).IsHomogeneous 1 := h4.mul h5 + have h7 : (((X (1:Fin 3) : MvPolynomial (Fin 3) ℂ)+((C (q^2) : MvPolynomial (Fin 3) ℂ)*(X (2:Fin 3) : MvPolynomial (Fin 3) ℂ)))).IsHomogeneous 1 := h3.add h6 + have h8 : ((C (q^6) : MvPolynomial (Fin 3) ℂ)).IsHomogeneous 0 := isHomogeneous_C _ _ + have h9 : (((C (q^6) : MvPolynomial (Fin 3) ℂ)*(X (0:Fin 3) : MvPolynomial (Fin 3) ℂ))).IsHomogeneous 1 := h8.mul h1 + have h10 : (((X (1:Fin 3) : MvPolynomial (Fin 3) ℂ)-((C (q^6) : MvPolynomial (Fin 3) ℂ)*(X (0:Fin 3) : MvPolynomial (Fin 3) ℂ)))).IsHomogeneous 1 := h3.sub h9 + have h11 : ((((X (1:Fin 3) : MvPolynomial (Fin 3) ℂ)+((C (q^2) : MvPolynomial (Fin 3) ℂ)*(X (2:Fin 3) : MvPolynomial (Fin 3) ℂ)))*((X (1:Fin 3) : MvPolynomial (Fin 3) ℂ)-((C (q^6) : MvPolynomial (Fin 3) ℂ)*(X (0:Fin 3) : MvPolynomial (Fin 3) ℂ))))).IsHomogeneous 2 := h7.mul h10 + have h12 : ((((C (q-q^3) : MvPolynomial (Fin 3) ℂ)*(X (0:Fin 3) : MvPolynomial (Fin 3) ℂ))*(((X (1:Fin 3) : MvPolynomial (Fin 3) ℂ)+((C (q^2) : MvPolynomial (Fin 3) ℂ)*(X (2:Fin 3) : MvPolynomial (Fin 3) ℂ)))*((X (1:Fin 3) : MvPolynomial (Fin 3) ℂ)-((C (q^6) : MvPolynomial (Fin 3) ℂ)*(X (0:Fin 3) : MvPolynomial (Fin 3) ℂ)))))).IsHomogeneous 3 := h2.mul h11 + simpa only [basePolyThree,basePolyThreeFactor,basePolyTwo] using h12 + +theorem vacuumThree_homogeneous (s : Fin 3 → Spin) : + (vacuumThree s).IsHomogeneous ((3:ℕ).choose 2) := by + rw [show (3:ℕ).choose 2=3 from by decide] + cases h0 : s 0 <;> cases h1 : s 1 <;> cases h2 : s 2 + · simpa only [vacuumThree,h0,h1,h2] using basePolyThree_homogeneous_0 + · simp only [vacuumThree,h0,h1,h2,basePolyThree]; exact isHomogeneous_zero _ _ _ + · simp only [vacuumThree,h0,h1,h2,basePolyThree]; exact isHomogeneous_zero _ _ _ + · simp only [vacuumThree,h0,h1,h2,basePolyThree]; exact isHomogeneous_zero _ _ _ + · simp only [vacuumThree,h0,h1,h2,basePolyThree]; exact isHomogeneous_zero _ _ _ + · simpa only [vacuumThree,h0,h1,h2] using basePolyThree_homogeneous_3 + · simp only [vacuumThree,h0,h1,h2,basePolyThree]; exact isHomogeneous_zero _ _ _ + · simpa only [vacuumThree,h0,h1,h2] using basePolyThree_homogeneous_4 + · simp only [vacuumThree,h0,h1,h2,basePolyThree]; exact isHomogeneous_zero _ _ _ + · simp only [vacuumThree,h0,h1,h2,basePolyThree]; exact isHomogeneous_zero _ _ _ + · simp only [vacuumThree,h0,h1,h2,basePolyThree]; exact isHomogeneous_zero _ _ _ + · simpa only [vacuumThree,h0,h1,h2] using basePolyThree_homogeneous_5 + · simp only [vacuumThree,h0,h1,h2,basePolyThree]; exact isHomogeneous_zero _ _ _ + · simp only [vacuumThree,h0,h1,h2,basePolyThree]; exact isHomogeneous_zero _ _ _ + · simp only [vacuumThree,h0,h1,h2,basePolyThree]; exact isHomogeneous_zero _ _ _ + · simpa only [vacuumThree,h0,h1,h2] using basePolyThree_homogeneous_1 + · simp only [vacuumThree,h0,h1,h2,basePolyThree]; exact isHomogeneous_zero _ _ _ + · simp only [vacuumThree,h0,h1,h2,basePolyThree]; exact isHomogeneous_zero _ _ _ + · simp only [vacuumThree,h0,h1,h2,basePolyThree]; exact isHomogeneous_zero _ _ _ + · simpa only [vacuumThree,h0,h1,h2] using basePolyThree_homogeneous_6 + · simp only [vacuumThree,h0,h1,h2,basePolyThree]; exact isHomogeneous_zero _ _ _ + · simpa only [vacuumThree,h0,h1,h2] using basePolyThree_homogeneous_2 + · simp only [vacuumThree,h0,h1,h2,basePolyThree]; exact isHomogeneous_zero _ _ _ + · simp only [vacuumThree,h0,h1,h2,basePolyThree]; exact isHomogeneous_zero _ _ _ + · simp only [vacuumThree,h0,h1,h2,basePolyThree]; exact isHomogeneous_zero _ _ _ + · simp only [vacuumThree,h0,h1,h2,basePolyThree]; exact isHomogeneous_zero _ _ _ + · simp only [vacuumThree,h0,h1,h2,basePolyThree]; exact isHomogeneous_zero _ _ _ +theorem vacuumThree_charge (s : Fin 3 → Spin) (h : (∑ j, charge (s j))≠0) : + vacuumThree s=0 := by + cases h0 : s 0 <;> cases h1 : s 1 <;> cases h2 : s 2 <;> + simp_all [vacuumThree,basePolyThree,Fin.sum_univ_succ,charge] + +end PolynomialVacuumAlgebra + +end OAI diff --git a/lean/OAI/Combinatorics/PolynomialVacuum/Algebra/BaseNatural.lean b/lean/OAI/Combinatorics/PolynomialVacuum/Algebra/BaseNatural.lean new file mode 100644 index 0000000000000000000000000000000000000000..d28642f828e1d5bd0d2bbdb3dc814d0a8ef31bde --- /dev/null +++ b/lean/OAI/Combinatorics/PolynomialVacuum/Algebra/BaseNatural.lean @@ -0,0 +1,62 @@ +import OAI.Combinatorics.PolynomialVacuum.Algebra.BasePolynomials +import OAI.Combinatorics.PolynomialVacuum.Algebra.FullCyclicity + +namespace OAI + +namespace PolynomialVacuumAlgebra +open MvPolynomial Classical + +theorem baseThree_exchange_last (x y z : ℂ) (a b c : Spin) : + (∑ ab : Pair, exchangeNumerator y z (b,c) ab * baseThree x y z a ab.1 ab.2)= + exchangeDenominator y z * baseThree x z y a b c := by + simp_rw [← baseThree_rotation y z x a,← baseThree_rotation z y x a] + calc + _ = zeta^charge a * ∑ ab : Pair, exchangeNumerator y z (b,c) ab * baseThree y z x ab.1 ab.2 a := by + rw [Finset.mul_sum]; apply Finset.sum_congr rfl; intro k hk; ring + _ = _ := by rw [baseThree_exchange]; ring + +theorem vacuumTwo_exchange : LowerExchange (liftState vacuumTwo) 2 := by + intro j hj X + have : j=0 := by omega + subst j + funext s + simpa [siteR,pairLinear,pairAction,replacePair,swapSite,Equiv.swap_apply_def,update_nat_decidable] using baseTwo_exchange (X 0) (X 1) (s 0) (s 1) + +theorem vacuumThree_exchange : LowerExchange (liftState vacuumThree) 3 := by + intro j hj X + have : j=0 ∨ j=1 := by omega + rcases this with rfl|rfl + · funext s + simpa [siteR,pairLinear,pairAction,replacePair,swapSite,Equiv.swap_apply_def,update_nat_decidable] using baseThree_exchange (X 0) (X 1) (X 2) (s 0) (s 1) (s 2) + · funext s + simpa [siteR,pairLinear,pairAction,replacePair,swapSite,Equiv.swap_apply_def,update_nat_decidable] using baseThree_exchange_last (X 0) (X 1) (X 2) (s 0) (s 1) (s 2) + +theorem vacuumTwo_cyclic : NaturalCyclic 1 (liftState vacuumTwo) := by + intro X + funext s + simp only [cyclicTransform,rotateTensor,lift_vacuumTwo,natRotate_zero,natRotate_succ] + rw [← baseTwo_rotation (X 0) (X 1) (s 1) (s 0)] + rw [← mul_assoc,← zpow_add₀ (by exact pow_ne_zero _ (pow_ne_zero _ q_ne_zero) : zeta≠0)] + simp + +theorem vacuumThree_cyclic : NaturalCyclic 2 (liftState vacuumThree) := by + intro X + funext s + simp only [cyclicTransform,rotateTensor,lift_vacuumThree,natRotate_zero,natRotate_succ] + rw [← baseThree_rotation (X 0) (X 1) (X 2) (s 2) (s 0) (s 1)] + rw [← mul_assoc,← zpow_add₀ (by exact pow_ne_zero _ (pow_ne_zero _ q_ne_zero) : zeta≠0)] + simp + +theorem vacuumTwo_firstCup : FirstCupReduction (liftState vacuumTwo) (liftState vacuumZero) 0 := by + intro X hX + funext s + simpa [naturalFusion,fusionProduct,cupLinear,fusionPair,skipTwo,hX] using baseTwo_cup (X 0) (s 0) (s 1) + +theorem vacuumThree_firstCup : FirstCupReduction (liftState vacuumThree) (liftState vacuumOne) 1 := by + intro X hX + funext s + simpa [naturalFusion,fusionProduct,cupLinear,fusionPair,skipTwo,hX,mul_assoc] using baseThree_cup (X 0) (X 2) (s 0) (s 1) (s 2) + +end PolynomialVacuumAlgebra + +end OAI diff --git a/lean/OAI/Combinatorics/PolynomialVacuum/Algebra/BasePolynomials.lean b/lean/OAI/Combinatorics/PolynomialVacuum/Algebra/BasePolynomials.lean new file mode 100644 index 0000000000000000000000000000000000000000..bd57fe18063b3b2198b69192e68047fe27cb4f07 --- /dev/null +++ b/lean/OAI/Combinatorics/PolynomialVacuum/Algebra/BasePolynomials.lean @@ -0,0 +1,50 @@ +import OAI.Combinatorics.PolynomialVacuum.Algebra.BaseThree +import OAI.Combinatorics.PolynomialVacuum.Algebra.InterpolatedCups +import OAI.Combinatorics.PolynomialVacuum.Algebra.InterpolatedZero +import OAI.Combinatorics.PolynomialVacuum.Algebra.InterpolatedDegrees + +namespace OAI + +namespace PolynomialVacuumAlgebra +open MvPolynomial Classical + +noncomputable def basePolyTwo {ι : Type*} (x y : MvPolynomial ι ℂ) : Spin → Spin → MvPolynomial ι ℂ + | .zero,.zero => x+y + | .plus,.minus => C (q^5-q^7)*y + | .minus,.plus => C (q-q^3)*x + | _,_ => 0 + +noncomputable def basePolyThreeFactor {ι : Type*} (x y z : MvPolynomial ι ℂ) : MvPolynomial ι ℂ := + (z+C (q^2)*x)*(z-C (q^6)*y) + +noncomputable def basePolyThree {ι : Type*} (x y z : MvPolynomial ι ℂ) : Spin → Spin → Spin → MvPolynomial ι ℂ + | .zero,.zero,.zero => x^2*y+x^2*z+y^2*x+y^2*z+z^2*x+z^2*y+C (2*(q^2-q^6))*x*y*z + | .plus,.minus,.zero => C (q^5-q^7)*y*basePolyThreeFactor x y z + | .minus,.plus,.zero => C (q-q^3)*x*basePolyThreeFactor x y z + | .zero,.plus,.minus => C (q^5-q^7)*z*basePolyThreeFactor y z x + | .zero,.minus,.plus => C (q-q^3)*y*basePolyThreeFactor y z x + | .plus,.zero,.minus => C (q^5-q^7)*z*basePolyThreeFactor z x y + | .minus,.zero,.plus => C (q-q^3)*x*basePolyThreeFactor z x y + | _,_,_ => 0 + +noncomputable def vacuumZero : State 0 := fun _ => 1 +noncomputable def vacuumOne : State 1 := fun s => if s 0=Spin.zero then 1 else 0 +noncomputable def vacuumTwo : State 2 := fun s => basePolyTwo (X 0) (X 1) (s 0) (s 1) +noncomputable def vacuumThree : State 3 := fun s => basePolyThree (X 0) (X 1) (X 2) (s 0) (s 1) (s 2) + +@[simp] theorem eval_basePolyTwo {ι : Type*} (x y : MvPolynomial ι ℂ) (a b : Spin) (Y : ι → ℂ) : + eval Y (basePolyTwo x y a b)=baseTwo (eval Y x) (eval Y y) a b := by + cases a <;> cases b <;> simp [basePolyTwo,baseTwo] + +@[simp] theorem eval_basePolyThree {ι : Type*} (x y z : MvPolynomial ι ℂ) (a b c : Spin) (Y : ι → ℂ) : + eval Y (basePolyThree x y z a b c)=baseThree (eval Y x) (eval Y y) (eval Y z) a b c := by + cases a <;> cases b <;> cases c <;> simp [basePolyThree,basePolyThreeFactor,baseThree,baseThreeFactor] + +@[simp] theorem lift_vacuumZero (Y : ℕ → ℂ) (s : ℕ → Spin) : liftState vacuumZero Y s=1 := by simp [liftState,liftPolyTensor,vacuumZero] +@[simp] theorem lift_vacuumOne (Y : ℕ → ℂ) (s : ℕ → Spin) : liftState vacuumOne Y s=(if s 0=Spin.zero then 1 else 0) := by simp [liftState,liftPolyTensor,vacuumOne] +@[simp] theorem lift_vacuumTwo (Y : ℕ → ℂ) (s : ℕ → Spin) : liftState vacuumTwo Y s=baseTwo (Y 0) (Y 1) (s 0) (s 1) := by simp [liftState,liftPolyTensor,vacuumTwo] +@[simp] theorem lift_vacuumThree (Y : ℕ → ℂ) (s : ℕ → Spin) : liftState vacuumThree Y s=baseThree (Y 0) (Y 1) (Y 2) (s 0) (s 1) (s 2) := by simp [liftState,liftPolyTensor,vacuumThree] + +end PolynomialVacuumAlgebra + +end OAI diff --git a/lean/OAI/Combinatorics/PolynomialVacuum/Algebra/BaseThree.lean b/lean/OAI/Combinatorics/PolynomialVacuum/Algebra/BaseThree.lean new file mode 100644 index 0000000000000000000000000000000000000000..4dc4360b832020da2fbdfb36852079a6c02141d4 --- /dev/null +++ b/lean/OAI/Combinatorics/PolynomialVacuum/Algebra/BaseThree.lean @@ -0,0 +1,719 @@ +import OAI.Combinatorics.PolynomialVacuum.Algebra.Ring +import OAI.Combinatorics.PolynomialVacuum.Algebra.BaseTwo + +namespace OAI + +namespace PolynomialVacuumAlgebra + +theorem baseThree_exchange_0 (x y z : ℂ) : + (∑ ab : Pair, exchangeNumerator x y (.zero,.zero) ab * + baseThree x y z ab.1 ab.2 .zero) = + exchangeDenominator x y * baseThree y x z .zero .zero .zero := by + norm_num [baseTwo,baseThree,baseThreeFactor,sum_pair,sum_spin, + exchangeNumerator_eq_table,exchangeTable,exchangeDenominator,cup,charge,zpow_neg, + q_five_inv,q_four_inv,T,t,zeta,inv_pow,q_inv] + all_goals vacuum_ring_finish + +theorem baseThree_rotation_0 (x y z : ℂ) : + zeta ^ charge .zero * baseThree x y z .zero .zero .zero = + baseThree z x y .zero .zero .zero := by + norm_num [baseTwo,baseThree,baseThreeFactor,sum_pair,sum_spin, + exchangeNumerator_eq_table,exchangeTable,exchangeDenominator,cup,charge,zpow_neg, + q_five_inv,q_four_inv,T,t,zeta,inv_pow,q_inv] + all_goals vacuum_ring_finish + +theorem baseThree_cup_0 (x z : ℂ) : + baseThree x (T*x) z .zero .zero .zero = + (1+T)*x * (z-t^5*x)*(z-t^6*x) * cup (.zero,.zero) * (if .zero = Spin.zero then 1 else 0) := by + norm_num [baseTwo,baseThree,baseThreeFactor,sum_pair,sum_spin, + exchangeNumerator_eq_table,exchangeTable,exchangeDenominator,cup,charge,zpow_neg, + q_five_inv,q_four_inv,T,t,zeta,inv_pow,q_inv] + all_goals vacuum_ring_finish + +theorem baseThree_exchange_1 (x y z : ℂ) : + (∑ ab : Pair, exchangeNumerator x y (.zero,.zero) ab * + baseThree x y z ab.1 ab.2 .plus) = + exchangeDenominator x y * baseThree y x z .zero .zero .plus := by + norm_num [baseTwo,baseThree,baseThreeFactor,sum_pair,sum_spin, + exchangeNumerator_eq_table,exchangeTable,exchangeDenominator,cup,charge,zpow_neg, + q_five_inv,q_four_inv,T,t,zeta,inv_pow,q_inv] + +theorem baseThree_rotation_1 (x y z : ℂ) : + zeta ^ charge .zero * baseThree x y z .zero .plus .zero = + baseThree z x y .zero .zero .plus := by + norm_num [baseTwo,baseThree,baseThreeFactor,sum_pair,sum_spin, + exchangeNumerator_eq_table,exchangeTable,exchangeDenominator,cup,charge,zpow_neg, + q_five_inv,q_four_inv,T,t,zeta,inv_pow,q_inv] + +theorem baseThree_cup_1 (x z : ℂ) : + baseThree x (T*x) z .zero .zero .plus = + (1+T)*x * (z-t^5*x)*(z-t^6*x) * cup (.zero,.zero) * (if .plus = Spin.zero then 1 else 0) := by + norm_num [baseTwo,baseThree,baseThreeFactor,sum_pair,sum_spin, + exchangeNumerator_eq_table,exchangeTable,exchangeDenominator,cup,charge,zpow_neg, + q_five_inv,q_four_inv,T,t,zeta,inv_pow,q_inv] + +theorem baseThree_exchange_2 (x y z : ℂ) : + (∑ ab : Pair, exchangeNumerator x y (.zero,.zero) ab * + baseThree x y z ab.1 ab.2 .minus) = + exchangeDenominator x y * baseThree y x z .zero .zero .minus := by + norm_num [baseTwo,baseThree,baseThreeFactor,sum_pair,sum_spin, + exchangeNumerator_eq_table,exchangeTable,exchangeDenominator,cup,charge,zpow_neg, + q_five_inv,q_four_inv,T,t,zeta,inv_pow,q_inv] + +theorem baseThree_rotation_2 (x y z : ℂ) : + zeta ^ charge .zero * baseThree x y z .zero .minus .zero = + baseThree z x y .zero .zero .minus := by + norm_num [baseTwo,baseThree,baseThreeFactor,sum_pair,sum_spin, + exchangeNumerator_eq_table,exchangeTable,exchangeDenominator,cup,charge,zpow_neg, + q_five_inv,q_four_inv,T,t,zeta,inv_pow,q_inv] + +theorem baseThree_cup_2 (x z : ℂ) : + baseThree x (T*x) z .zero .zero .minus = + (1+T)*x * (z-t^5*x)*(z-t^6*x) * cup (.zero,.zero) * (if .minus = Spin.zero then 1 else 0) := by + norm_num [baseTwo,baseThree,baseThreeFactor,sum_pair,sum_spin, + exchangeNumerator_eq_table,exchangeTable,exchangeDenominator,cup,charge,zpow_neg, + q_five_inv,q_four_inv,T,t,zeta,inv_pow,q_inv] + +theorem baseThree_exchange_3 (x y z : ℂ) : + (∑ ab : Pair, exchangeNumerator x y (.zero,.plus) ab * + baseThree x y z ab.1 ab.2 .zero) = + exchangeDenominator x y * baseThree y x z .zero .plus .zero := by + norm_num [baseTwo,baseThree,baseThreeFactor,sum_pair,sum_spin, + exchangeNumerator_eq_table,exchangeTable,exchangeDenominator,cup,charge,zpow_neg, + q_five_inv,q_four_inv,T,t,zeta,inv_pow,q_inv] + +theorem baseThree_rotation_3 (x y z : ℂ) : + zeta ^ charge .zero * baseThree x y z .plus .zero .zero = + baseThree z x y .zero .plus .zero := by + norm_num [baseTwo,baseThree,baseThreeFactor,sum_pair,sum_spin, + exchangeNumerator_eq_table,exchangeTable,exchangeDenominator,cup,charge,zpow_neg, + q_five_inv,q_four_inv,T,t,zeta,inv_pow,q_inv] + +theorem baseThree_cup_3 (x z : ℂ) : + baseThree x (T*x) z .zero .plus .zero = + (1+T)*x * (z-t^5*x)*(z-t^6*x) * cup (.zero,.plus) * (if .zero = Spin.zero then 1 else 0) := by + norm_num [baseTwo,baseThree,baseThreeFactor,sum_pair,sum_spin, + exchangeNumerator_eq_table,exchangeTable,exchangeDenominator,cup,charge,zpow_neg, + q_five_inv,q_four_inv,T,t,zeta,inv_pow,q_inv] + +theorem baseThree_exchange_4 (x y z : ℂ) : + (∑ ab : Pair, exchangeNumerator x y (.zero,.plus) ab * + baseThree x y z ab.1 ab.2 .plus) = + exchangeDenominator x y * baseThree y x z .zero .plus .plus := by + norm_num [baseTwo,baseThree,baseThreeFactor,sum_pair,sum_spin, + exchangeNumerator_eq_table,exchangeTable,exchangeDenominator,cup,charge,zpow_neg, + q_five_inv,q_four_inv,T,t,zeta,inv_pow,q_inv] + +theorem baseThree_rotation_4 (x y z : ℂ) : + zeta ^ charge .zero * baseThree x y z .plus .plus .zero = + baseThree z x y .zero .plus .plus := by + norm_num [baseTwo,baseThree,baseThreeFactor,sum_pair,sum_spin, + exchangeNumerator_eq_table,exchangeTable,exchangeDenominator,cup,charge,zpow_neg, + q_five_inv,q_four_inv,T,t,zeta,inv_pow,q_inv] + +theorem baseThree_cup_4 (x z : ℂ) : + baseThree x (T*x) z .zero .plus .plus = + (1+T)*x * (z-t^5*x)*(z-t^6*x) * cup (.zero,.plus) * (if .plus = Spin.zero then 1 else 0) := by + norm_num [baseTwo,baseThree,baseThreeFactor,sum_pair,sum_spin, + exchangeNumerator_eq_table,exchangeTable,exchangeDenominator,cup,charge,zpow_neg, + q_five_inv,q_four_inv,T,t,zeta,inv_pow,q_inv] + +theorem baseThree_exchange_5 (x y z : ℂ) : + (∑ ab : Pair, exchangeNumerator x y (.zero,.plus) ab * + baseThree x y z ab.1 ab.2 .minus) = + exchangeDenominator x y * baseThree y x z .zero .plus .minus := by + norm_num [baseTwo,baseThree,baseThreeFactor,sum_pair,sum_spin, + exchangeNumerator_eq_table,exchangeTable,exchangeDenominator,cup,charge,zpow_neg, + q_five_inv,q_four_inv,T,t,zeta,inv_pow,q_inv] + all_goals vacuum_ring_finish + +theorem baseThree_rotation_5 (x y z : ℂ) : + zeta ^ charge .zero * baseThree x y z .plus .minus .zero = + baseThree z x y .zero .plus .minus := by + norm_num [baseTwo,baseThree,baseThreeFactor,sum_pair,sum_spin, + exchangeNumerator_eq_table,exchangeTable,exchangeDenominator,cup,charge,zpow_neg, + q_five_inv,q_four_inv,T,t,zeta,inv_pow,q_inv] + +theorem baseThree_cup_5 (x z : ℂ) : + baseThree x (T*x) z .zero .plus .minus = + (1+T)*x * (z-t^5*x)*(z-t^6*x) * cup (.zero,.plus) * (if .minus = Spin.zero then 1 else 0) := by + norm_num [baseTwo,baseThree,baseThreeFactor,sum_pair,sum_spin, + exchangeNumerator_eq_table,exchangeTable,exchangeDenominator,cup,charge,zpow_neg, + q_five_inv,q_four_inv,T,t,zeta,inv_pow,q_inv] + all_goals vacuum_ring_finish + +theorem baseThree_exchange_6 (x y z : ℂ) : + (∑ ab : Pair, exchangeNumerator x y (.zero,.minus) ab * + baseThree x y z ab.1 ab.2 .zero) = + exchangeDenominator x y * baseThree y x z .zero .minus .zero := by + norm_num [baseTwo,baseThree,baseThreeFactor,sum_pair,sum_spin, + exchangeNumerator_eq_table,exchangeTable,exchangeDenominator,cup,charge,zpow_neg, + q_five_inv,q_four_inv,T,t,zeta,inv_pow,q_inv] + +theorem baseThree_rotation_6 (x y z : ℂ) : + zeta ^ charge .zero * baseThree x y z .minus .zero .zero = + baseThree z x y .zero .minus .zero := by + norm_num [baseTwo,baseThree,baseThreeFactor,sum_pair,sum_spin, + exchangeNumerator_eq_table,exchangeTable,exchangeDenominator,cup,charge,zpow_neg, + q_five_inv,q_four_inv,T,t,zeta,inv_pow,q_inv] + +theorem baseThree_cup_6 (x z : ℂ) : + baseThree x (T*x) z .zero .minus .zero = + (1+T)*x * (z-t^5*x)*(z-t^6*x) * cup (.zero,.minus) * (if .zero = Spin.zero then 1 else 0) := by + norm_num [baseTwo,baseThree,baseThreeFactor,sum_pair,sum_spin, + exchangeNumerator_eq_table,exchangeTable,exchangeDenominator,cup,charge,zpow_neg, + q_five_inv,q_four_inv,T,t,zeta,inv_pow,q_inv] + +theorem baseThree_exchange_7 (x y z : ℂ) : + (∑ ab : Pair, exchangeNumerator x y (.zero,.minus) ab * + baseThree x y z ab.1 ab.2 .plus) = + exchangeDenominator x y * baseThree y x z .zero .minus .plus := by + norm_num [baseTwo,baseThree,baseThreeFactor,sum_pair,sum_spin, + exchangeNumerator_eq_table,exchangeTable,exchangeDenominator,cup,charge,zpow_neg, + q_five_inv,q_four_inv,T,t,zeta,inv_pow,q_inv] + all_goals vacuum_ring_finish + +theorem baseThree_rotation_7 (x y z : ℂ) : + zeta ^ charge .zero * baseThree x y z .minus .plus .zero = + baseThree z x y .zero .minus .plus := by + norm_num [baseTwo,baseThree,baseThreeFactor,sum_pair,sum_spin, + exchangeNumerator_eq_table,exchangeTable,exchangeDenominator,cup,charge,zpow_neg, + q_five_inv,q_four_inv,T,t,zeta,inv_pow,q_inv] + +theorem baseThree_cup_7 (x z : ℂ) : + baseThree x (T*x) z .zero .minus .plus = + (1+T)*x * (z-t^5*x)*(z-t^6*x) * cup (.zero,.minus) * (if .plus = Spin.zero then 1 else 0) := by + norm_num [baseTwo,baseThree,baseThreeFactor,sum_pair,sum_spin, + exchangeNumerator_eq_table,exchangeTable,exchangeDenominator,cup,charge,zpow_neg, + q_five_inv,q_four_inv,T,t,zeta,inv_pow,q_inv] + all_goals vacuum_ring_finish + +theorem baseThree_exchange_8 (x y z : ℂ) : + (∑ ab : Pair, exchangeNumerator x y (.zero,.minus) ab * + baseThree x y z ab.1 ab.2 .minus) = + exchangeDenominator x y * baseThree y x z .zero .minus .minus := by + norm_num [baseTwo,baseThree,baseThreeFactor,sum_pair,sum_spin, + exchangeNumerator_eq_table,exchangeTable,exchangeDenominator,cup,charge,zpow_neg, + q_five_inv,q_four_inv,T,t,zeta,inv_pow,q_inv] + +theorem baseThree_rotation_8 (x y z : ℂ) : + zeta ^ charge .zero * baseThree x y z .minus .minus .zero = + baseThree z x y .zero .minus .minus := by + norm_num [baseTwo,baseThree,baseThreeFactor,sum_pair,sum_spin, + exchangeNumerator_eq_table,exchangeTable,exchangeDenominator,cup,charge,zpow_neg, + q_five_inv,q_four_inv,T,t,zeta,inv_pow,q_inv] + +theorem baseThree_cup_8 (x z : ℂ) : + baseThree x (T*x) z .zero .minus .minus = + (1+T)*x * (z-t^5*x)*(z-t^6*x) * cup (.zero,.minus) * (if .minus = Spin.zero then 1 else 0) := by + norm_num [baseTwo,baseThree,baseThreeFactor,sum_pair,sum_spin, + exchangeNumerator_eq_table,exchangeTable,exchangeDenominator,cup,charge,zpow_neg, + q_five_inv,q_four_inv,T,t,zeta,inv_pow,q_inv] + +theorem baseThree_exchange_9 (x y z : ℂ) : + (∑ ab : Pair, exchangeNumerator x y (.plus,.zero) ab * + baseThree x y z ab.1 ab.2 .zero) = + exchangeDenominator x y * baseThree y x z .plus .zero .zero := by + norm_num [baseTwo,baseThree,baseThreeFactor,sum_pair,sum_spin, + exchangeNumerator_eq_table,exchangeTable,exchangeDenominator,cup,charge,zpow_neg, + q_five_inv,q_four_inv,T,t,zeta,inv_pow,q_inv] + +theorem baseThree_rotation_9 (x y z : ℂ) : + zeta ^ charge .plus * baseThree x y z .zero .zero .plus = + baseThree z x y .plus .zero .zero := by + norm_num [baseTwo,baseThree,baseThreeFactor,sum_pair,sum_spin, + exchangeNumerator_eq_table,exchangeTable,exchangeDenominator,cup,charge,zpow_neg, + q_five_inv,q_four_inv,T,t,zeta,inv_pow,q_inv] + +theorem baseThree_cup_9 (x z : ℂ) : + baseThree x (T*x) z .plus .zero .zero = + (1+T)*x * (z-t^5*x)*(z-t^6*x) * cup (.plus,.zero) * (if .zero = Spin.zero then 1 else 0) := by + norm_num [baseTwo,baseThree,baseThreeFactor,sum_pair,sum_spin, + exchangeNumerator_eq_table,exchangeTable,exchangeDenominator,cup,charge,zpow_neg, + q_five_inv,q_four_inv,T,t,zeta,inv_pow,q_inv] + +theorem baseThree_exchange_10 (x y z : ℂ) : + (∑ ab : Pair, exchangeNumerator x y (.plus,.zero) ab * + baseThree x y z ab.1 ab.2 .plus) = + exchangeDenominator x y * baseThree y x z .plus .zero .plus := by + norm_num [baseTwo,baseThree,baseThreeFactor,sum_pair,sum_spin, + exchangeNumerator_eq_table,exchangeTable,exchangeDenominator,cup,charge,zpow_neg, + q_five_inv,q_four_inv,T,t,zeta,inv_pow,q_inv] + +theorem baseThree_rotation_10 (x y z : ℂ) : + zeta ^ charge .plus * baseThree x y z .zero .plus .plus = + baseThree z x y .plus .zero .plus := by + norm_num [baseTwo,baseThree,baseThreeFactor,sum_pair,sum_spin, + exchangeNumerator_eq_table,exchangeTable,exchangeDenominator,cup,charge,zpow_neg, + q_five_inv,q_four_inv,T,t,zeta,inv_pow,q_inv] + +theorem baseThree_cup_10 (x z : ℂ) : + baseThree x (T*x) z .plus .zero .plus = + (1+T)*x * (z-t^5*x)*(z-t^6*x) * cup (.plus,.zero) * (if .plus = Spin.zero then 1 else 0) := by + norm_num [baseTwo,baseThree,baseThreeFactor,sum_pair,sum_spin, + exchangeNumerator_eq_table,exchangeTable,exchangeDenominator,cup,charge,zpow_neg, + q_five_inv,q_four_inv,T,t,zeta,inv_pow,q_inv] + +theorem baseThree_exchange_11 (x y z : ℂ) : + (∑ ab : Pair, exchangeNumerator x y (.plus,.zero) ab * + baseThree x y z ab.1 ab.2 .minus) = + exchangeDenominator x y * baseThree y x z .plus .zero .minus := by + norm_num [baseTwo,baseThree,baseThreeFactor,sum_pair,sum_spin, + exchangeNumerator_eq_table,exchangeTable,exchangeDenominator,cup,charge,zpow_neg, + q_five_inv,q_four_inv,T,t,zeta,inv_pow,q_inv] + all_goals vacuum_ring_finish + +theorem baseThree_rotation_11 (x y z : ℂ) : + zeta ^ charge .plus * baseThree x y z .zero .minus .plus = + baseThree z x y .plus .zero .minus := by + norm_num [baseTwo,baseThree,baseThreeFactor,sum_pair,sum_spin, + exchangeNumerator_eq_table,exchangeTable,exchangeDenominator,cup,charge,zpow_neg, + q_five_inv,q_four_inv,T,t,zeta,inv_pow,q_inv] + all_goals vacuum_ring_finish + +theorem baseThree_cup_11 (x z : ℂ) : + baseThree x (T*x) z .plus .zero .minus = + (1+T)*x * (z-t^5*x)*(z-t^6*x) * cup (.plus,.zero) * (if .minus = Spin.zero then 1 else 0) := by + norm_num [baseTwo,baseThree,baseThreeFactor,sum_pair,sum_spin, + exchangeNumerator_eq_table,exchangeTable,exchangeDenominator,cup,charge,zpow_neg, + q_five_inv,q_four_inv,T,t,zeta,inv_pow,q_inv] + all_goals vacuum_ring_finish + +theorem baseThree_exchange_12 (x y z : ℂ) : + (∑ ab : Pair, exchangeNumerator x y (.plus,.plus) ab * + baseThree x y z ab.1 ab.2 .zero) = + exchangeDenominator x y * baseThree y x z .plus .plus .zero := by + norm_num [baseTwo,baseThree,baseThreeFactor,sum_pair,sum_spin, + exchangeNumerator_eq_table,exchangeTable,exchangeDenominator,cup,charge,zpow_neg, + q_five_inv,q_four_inv,T,t,zeta,inv_pow,q_inv] + +theorem baseThree_rotation_12 (x y z : ℂ) : + zeta ^ charge .plus * baseThree x y z .plus .zero .plus = + baseThree z x y .plus .plus .zero := by + norm_num [baseTwo,baseThree,baseThreeFactor,sum_pair,sum_spin, + exchangeNumerator_eq_table,exchangeTable,exchangeDenominator,cup,charge,zpow_neg, + q_five_inv,q_four_inv,T,t,zeta,inv_pow,q_inv] + +theorem baseThree_cup_12 (x z : ℂ) : + baseThree x (T*x) z .plus .plus .zero = + (1+T)*x * (z-t^5*x)*(z-t^6*x) * cup (.plus,.plus) * (if .zero = Spin.zero then 1 else 0) := by + norm_num [baseTwo,baseThree,baseThreeFactor,sum_pair,sum_spin, + exchangeNumerator_eq_table,exchangeTable,exchangeDenominator,cup,charge,zpow_neg, + q_five_inv,q_four_inv,T,t,zeta,inv_pow,q_inv] + +theorem baseThree_exchange_13 (x y z : ℂ) : + (∑ ab : Pair, exchangeNumerator x y (.plus,.plus) ab * + baseThree x y z ab.1 ab.2 .plus) = + exchangeDenominator x y * baseThree y x z .plus .plus .plus := by + norm_num [baseTwo,baseThree,baseThreeFactor,sum_pair,sum_spin, + exchangeNumerator_eq_table,exchangeTable,exchangeDenominator,cup,charge,zpow_neg, + q_five_inv,q_four_inv,T,t,zeta,inv_pow,q_inv] + +theorem baseThree_rotation_13 (x y z : ℂ) : + zeta ^ charge .plus * baseThree x y z .plus .plus .plus = + baseThree z x y .plus .plus .plus := by + norm_num [baseTwo,baseThree,baseThreeFactor,sum_pair,sum_spin, + exchangeNumerator_eq_table,exchangeTable,exchangeDenominator,cup,charge,zpow_neg, + q_five_inv,q_four_inv,T,t,zeta,inv_pow,q_inv] + +theorem baseThree_cup_13 (x z : ℂ) : + baseThree x (T*x) z .plus .plus .plus = + (1+T)*x * (z-t^5*x)*(z-t^6*x) * cup (.plus,.plus) * (if .plus = Spin.zero then 1 else 0) := by + norm_num [baseTwo,baseThree,baseThreeFactor,sum_pair,sum_spin, + exchangeNumerator_eq_table,exchangeTable,exchangeDenominator,cup,charge,zpow_neg, + q_five_inv,q_four_inv,T,t,zeta,inv_pow,q_inv] + +theorem baseThree_exchange_14 (x y z : ℂ) : + (∑ ab : Pair, exchangeNumerator x y (.plus,.plus) ab * + baseThree x y z ab.1 ab.2 .minus) = + exchangeDenominator x y * baseThree y x z .plus .plus .minus := by + norm_num [baseTwo,baseThree,baseThreeFactor,sum_pair,sum_spin, + exchangeNumerator_eq_table,exchangeTable,exchangeDenominator,cup,charge,zpow_neg, + q_five_inv,q_four_inv,T,t,zeta,inv_pow,q_inv] + +theorem baseThree_rotation_14 (x y z : ℂ) : + zeta ^ charge .plus * baseThree x y z .plus .minus .plus = + baseThree z x y .plus .plus .minus := by + norm_num [baseTwo,baseThree,baseThreeFactor,sum_pair,sum_spin, + exchangeNumerator_eq_table,exchangeTable,exchangeDenominator,cup,charge,zpow_neg, + q_five_inv,q_four_inv,T,t,zeta,inv_pow,q_inv] + +theorem baseThree_cup_14 (x z : ℂ) : + baseThree x (T*x) z .plus .plus .minus = + (1+T)*x * (z-t^5*x)*(z-t^6*x) * cup (.plus,.plus) * (if .minus = Spin.zero then 1 else 0) := by + norm_num [baseTwo,baseThree,baseThreeFactor,sum_pair,sum_spin, + exchangeNumerator_eq_table,exchangeTable,exchangeDenominator,cup,charge,zpow_neg, + q_five_inv,q_four_inv,T,t,zeta,inv_pow,q_inv] + +theorem baseThree_exchange_15 (x y z : ℂ) : + (∑ ab : Pair, exchangeNumerator x y (.plus,.minus) ab * + baseThree x y z ab.1 ab.2 .zero) = + exchangeDenominator x y * baseThree y x z .plus .minus .zero := by + norm_num [baseTwo,baseThree,baseThreeFactor,sum_pair,sum_spin, + exchangeNumerator_eq_table,exchangeTable,exchangeDenominator,cup,charge,zpow_neg, + q_five_inv,q_four_inv,T,t,zeta,inv_pow,q_inv] + all_goals vacuum_ring_finish + +theorem baseThree_rotation_15 (x y z : ℂ) : + zeta ^ charge .plus * baseThree x y z .minus .zero .plus = + baseThree z x y .plus .minus .zero := by + norm_num [baseTwo,baseThree,baseThreeFactor,sum_pair,sum_spin, + exchangeNumerator_eq_table,exchangeTable,exchangeDenominator,cup,charge,zpow_neg, + q_five_inv,q_four_inv,T,t,zeta,inv_pow,q_inv] + all_goals vacuum_ring_finish + +theorem baseThree_cup_15 (x z : ℂ) : + baseThree x (T*x) z .plus .minus .zero = + (1+T)*x * (z-t^5*x)*(z-t^6*x) * cup (.plus,.minus) * (if .zero = Spin.zero then 1 else 0) := by + norm_num [baseTwo,baseThree,baseThreeFactor,sum_pair,sum_spin, + exchangeNumerator_eq_table,exchangeTable,exchangeDenominator,cup,charge,zpow_neg, + q_five_inv,q_four_inv,T,t,zeta,inv_pow,q_inv] + all_goals vacuum_ring_finish + +theorem baseThree_exchange_16 (x y z : ℂ) : + (∑ ab : Pair, exchangeNumerator x y (.plus,.minus) ab * + baseThree x y z ab.1 ab.2 .plus) = + exchangeDenominator x y * baseThree y x z .plus .minus .plus := by + norm_num [baseTwo,baseThree,baseThreeFactor,sum_pair,sum_spin, + exchangeNumerator_eq_table,exchangeTable,exchangeDenominator,cup,charge,zpow_neg, + q_five_inv,q_four_inv,T,t,zeta,inv_pow,q_inv] + +theorem baseThree_rotation_16 (x y z : ℂ) : + zeta ^ charge .plus * baseThree x y z .minus .plus .plus = + baseThree z x y .plus .minus .plus := by + norm_num [baseTwo,baseThree,baseThreeFactor,sum_pair,sum_spin, + exchangeNumerator_eq_table,exchangeTable,exchangeDenominator,cup,charge,zpow_neg, + q_five_inv,q_four_inv,T,t,zeta,inv_pow,q_inv] + +theorem baseThree_cup_16 (x z : ℂ) : + baseThree x (T*x) z .plus .minus .plus = + (1+T)*x * (z-t^5*x)*(z-t^6*x) * cup (.plus,.minus) * (if .plus = Spin.zero then 1 else 0) := by + norm_num [baseTwo,baseThree,baseThreeFactor,sum_pair,sum_spin, + exchangeNumerator_eq_table,exchangeTable,exchangeDenominator,cup,charge,zpow_neg, + q_five_inv,q_four_inv,T,t,zeta,inv_pow,q_inv] + +theorem baseThree_exchange_17 (x y z : ℂ) : + (∑ ab : Pair, exchangeNumerator x y (.plus,.minus) ab * + baseThree x y z ab.1 ab.2 .minus) = + exchangeDenominator x y * baseThree y x z .plus .minus .minus := by + norm_num [baseTwo,baseThree,baseThreeFactor,sum_pair,sum_spin, + exchangeNumerator_eq_table,exchangeTable,exchangeDenominator,cup,charge,zpow_neg, + q_five_inv,q_four_inv,T,t,zeta,inv_pow,q_inv] + +theorem baseThree_rotation_17 (x y z : ℂ) : + zeta ^ charge .plus * baseThree x y z .minus .minus .plus = + baseThree z x y .plus .minus .minus := by + norm_num [baseTwo,baseThree,baseThreeFactor,sum_pair,sum_spin, + exchangeNumerator_eq_table,exchangeTable,exchangeDenominator,cup,charge,zpow_neg, + q_five_inv,q_four_inv,T,t,zeta,inv_pow,q_inv] + +theorem baseThree_cup_17 (x z : ℂ) : + baseThree x (T*x) z .plus .minus .minus = + (1+T)*x * (z-t^5*x)*(z-t^6*x) * cup (.plus,.minus) * (if .minus = Spin.zero then 1 else 0) := by + norm_num [baseTwo,baseThree,baseThreeFactor,sum_pair,sum_spin, + exchangeNumerator_eq_table,exchangeTable,exchangeDenominator,cup,charge,zpow_neg, + q_five_inv,q_four_inv,T,t,zeta,inv_pow,q_inv] + +theorem baseThree_exchange_18 (x y z : ℂ) : + (∑ ab : Pair, exchangeNumerator x y (.minus,.zero) ab * + baseThree x y z ab.1 ab.2 .zero) = + exchangeDenominator x y * baseThree y x z .minus .zero .zero := by + norm_num [baseTwo,baseThree,baseThreeFactor,sum_pair,sum_spin, + exchangeNumerator_eq_table,exchangeTable,exchangeDenominator,cup,charge,zpow_neg, + q_five_inv,q_four_inv,T,t,zeta,inv_pow,q_inv] + +theorem baseThree_rotation_18 (x y z : ℂ) : + zeta ^ charge .minus * baseThree x y z .zero .zero .minus = + baseThree z x y .minus .zero .zero := by + norm_num [baseTwo,baseThree,baseThreeFactor,sum_pair,sum_spin, + exchangeNumerator_eq_table,exchangeTable,exchangeDenominator,cup,charge,zpow_neg, + q_five_inv,q_four_inv,T,t,zeta,inv_pow,q_inv] + +theorem baseThree_cup_18 (x z : ℂ) : + baseThree x (T*x) z .minus .zero .zero = + (1+T)*x * (z-t^5*x)*(z-t^6*x) * cup (.minus,.zero) * (if .zero = Spin.zero then 1 else 0) := by + norm_num [baseTwo,baseThree,baseThreeFactor,sum_pair,sum_spin, + exchangeNumerator_eq_table,exchangeTable,exchangeDenominator,cup,charge,zpow_neg, + q_five_inv,q_four_inv,T,t,zeta,inv_pow,q_inv] + +theorem baseThree_exchange_19 (x y z : ℂ) : + (∑ ab : Pair, exchangeNumerator x y (.minus,.zero) ab * + baseThree x y z ab.1 ab.2 .plus) = + exchangeDenominator x y * baseThree y x z .minus .zero .plus := by + norm_num [baseTwo,baseThree,baseThreeFactor,sum_pair,sum_spin, + exchangeNumerator_eq_table,exchangeTable,exchangeDenominator,cup,charge,zpow_neg, + q_five_inv,q_four_inv,T,t,zeta,inv_pow,q_inv] + all_goals vacuum_ring_finish + +theorem baseThree_rotation_19 (x y z : ℂ) : + zeta ^ charge .minus * baseThree x y z .zero .plus .minus = + baseThree z x y .minus .zero .plus := by + norm_num [baseTwo,baseThree,baseThreeFactor,sum_pair,sum_spin, + exchangeNumerator_eq_table,exchangeTable,exchangeDenominator,cup,charge,zpow_neg, + q_five_inv,q_four_inv,T,t,zeta,inv_pow,q_inv] + all_goals vacuum_ring_finish + +theorem baseThree_cup_19 (x z : ℂ) : + baseThree x (T*x) z .minus .zero .plus = + (1+T)*x * (z-t^5*x)*(z-t^6*x) * cup (.minus,.zero) * (if .plus = Spin.zero then 1 else 0) := by + norm_num [baseTwo,baseThree,baseThreeFactor,sum_pair,sum_spin, + exchangeNumerator_eq_table,exchangeTable,exchangeDenominator,cup,charge,zpow_neg, + q_five_inv,q_four_inv,T,t,zeta,inv_pow,q_inv] + all_goals vacuum_ring_finish + +theorem baseThree_exchange_20 (x y z : ℂ) : + (∑ ab : Pair, exchangeNumerator x y (.minus,.zero) ab * + baseThree x y z ab.1 ab.2 .minus) = + exchangeDenominator x y * baseThree y x z .minus .zero .minus := by + norm_num [baseTwo,baseThree,baseThreeFactor,sum_pair,sum_spin, + exchangeNumerator_eq_table,exchangeTable,exchangeDenominator,cup,charge,zpow_neg, + q_five_inv,q_four_inv,T,t,zeta,inv_pow,q_inv] + +theorem baseThree_rotation_20 (x y z : ℂ) : + zeta ^ charge .minus * baseThree x y z .zero .minus .minus = + baseThree z x y .minus .zero .minus := by + norm_num [baseTwo,baseThree,baseThreeFactor,sum_pair,sum_spin, + exchangeNumerator_eq_table,exchangeTable,exchangeDenominator,cup,charge,zpow_neg, + q_five_inv,q_four_inv,T,t,zeta,inv_pow,q_inv] + +theorem baseThree_cup_20 (x z : ℂ) : + baseThree x (T*x) z .minus .zero .minus = + (1+T)*x * (z-t^5*x)*(z-t^6*x) * cup (.minus,.zero) * (if .minus = Spin.zero then 1 else 0) := by + norm_num [baseTwo,baseThree,baseThreeFactor,sum_pair,sum_spin, + exchangeNumerator_eq_table,exchangeTable,exchangeDenominator,cup,charge,zpow_neg, + q_five_inv,q_four_inv,T,t,zeta,inv_pow,q_inv] + +theorem baseThree_exchange_21 (x y z : ℂ) : + (∑ ab : Pair, exchangeNumerator x y (.minus,.plus) ab * + baseThree x y z ab.1 ab.2 .zero) = + exchangeDenominator x y * baseThree y x z .minus .plus .zero := by + norm_num [baseTwo,baseThree,baseThreeFactor,sum_pair,sum_spin, + exchangeNumerator_eq_table,exchangeTable,exchangeDenominator,cup,charge,zpow_neg, + q_five_inv,q_four_inv,T,t,zeta,inv_pow,q_inv] + all_goals vacuum_ring_finish + +theorem baseThree_rotation_21 (x y z : ℂ) : + zeta ^ charge .minus * baseThree x y z .plus .zero .minus = + baseThree z x y .minus .plus .zero := by + norm_num [baseTwo,baseThree,baseThreeFactor,sum_pair,sum_spin, + exchangeNumerator_eq_table,exchangeTable,exchangeDenominator,cup,charge,zpow_neg, + q_five_inv,q_four_inv,T,t,zeta,inv_pow,q_inv] + all_goals vacuum_ring_finish + +theorem baseThree_cup_21 (x z : ℂ) : + baseThree x (T*x) z .minus .plus .zero = + (1+T)*x * (z-t^5*x)*(z-t^6*x) * cup (.minus,.plus) * (if .zero = Spin.zero then 1 else 0) := by + norm_num [baseTwo,baseThree,baseThreeFactor,sum_pair,sum_spin, + exchangeNumerator_eq_table,exchangeTable,exchangeDenominator,cup,charge,zpow_neg, + q_five_inv,q_four_inv,T,t,zeta,inv_pow,q_inv] + all_goals vacuum_ring_finish + +theorem baseThree_exchange_22 (x y z : ℂ) : + (∑ ab : Pair, exchangeNumerator x y (.minus,.plus) ab * + baseThree x y z ab.1 ab.2 .plus) = + exchangeDenominator x y * baseThree y x z .minus .plus .plus := by + norm_num [baseTwo,baseThree,baseThreeFactor,sum_pair,sum_spin, + exchangeNumerator_eq_table,exchangeTable,exchangeDenominator,cup,charge,zpow_neg, + q_five_inv,q_four_inv,T,t,zeta,inv_pow,q_inv] + +theorem baseThree_rotation_22 (x y z : ℂ) : + zeta ^ charge .minus * baseThree x y z .plus .plus .minus = + baseThree z x y .minus .plus .plus := by + norm_num [baseTwo,baseThree,baseThreeFactor,sum_pair,sum_spin, + exchangeNumerator_eq_table,exchangeTable,exchangeDenominator,cup,charge,zpow_neg, + q_five_inv,q_four_inv,T,t,zeta,inv_pow,q_inv] + +theorem baseThree_cup_22 (x z : ℂ) : + baseThree x (T*x) z .minus .plus .plus = + (1+T)*x * (z-t^5*x)*(z-t^6*x) * cup (.minus,.plus) * (if .plus = Spin.zero then 1 else 0) := by + norm_num [baseTwo,baseThree,baseThreeFactor,sum_pair,sum_spin, + exchangeNumerator_eq_table,exchangeTable,exchangeDenominator,cup,charge,zpow_neg, + q_five_inv,q_four_inv,T,t,zeta,inv_pow,q_inv] + +theorem baseThree_exchange_23 (x y z : ℂ) : + (∑ ab : Pair, exchangeNumerator x y (.minus,.plus) ab * + baseThree x y z ab.1 ab.2 .minus) = + exchangeDenominator x y * baseThree y x z .minus .plus .minus := by + norm_num [baseTwo,baseThree,baseThreeFactor,sum_pair,sum_spin, + exchangeNumerator_eq_table,exchangeTable,exchangeDenominator,cup,charge,zpow_neg, + q_five_inv,q_four_inv,T,t,zeta,inv_pow,q_inv] + +theorem baseThree_rotation_23 (x y z : ℂ) : + zeta ^ charge .minus * baseThree x y z .plus .minus .minus = + baseThree z x y .minus .plus .minus := by + norm_num [baseTwo,baseThree,baseThreeFactor,sum_pair,sum_spin, + exchangeNumerator_eq_table,exchangeTable,exchangeDenominator,cup,charge,zpow_neg, + q_five_inv,q_four_inv,T,t,zeta,inv_pow,q_inv] + +theorem baseThree_cup_23 (x z : ℂ) : + baseThree x (T*x) z .minus .plus .minus = + (1+T)*x * (z-t^5*x)*(z-t^6*x) * cup (.minus,.plus) * (if .minus = Spin.zero then 1 else 0) := by + norm_num [baseTwo,baseThree,baseThreeFactor,sum_pair,sum_spin, + exchangeNumerator_eq_table,exchangeTable,exchangeDenominator,cup,charge,zpow_neg, + q_five_inv,q_four_inv,T,t,zeta,inv_pow,q_inv] + +theorem baseThree_exchange_24 (x y z : ℂ) : + (∑ ab : Pair, exchangeNumerator x y (.minus,.minus) ab * + baseThree x y z ab.1 ab.2 .zero) = + exchangeDenominator x y * baseThree y x z .minus .minus .zero := by + norm_num [baseTwo,baseThree,baseThreeFactor,sum_pair,sum_spin, + exchangeNumerator_eq_table,exchangeTable,exchangeDenominator,cup,charge,zpow_neg, + q_five_inv,q_four_inv,T,t,zeta,inv_pow,q_inv] + +theorem baseThree_rotation_24 (x y z : ℂ) : + zeta ^ charge .minus * baseThree x y z .minus .zero .minus = + baseThree z x y .minus .minus .zero := by + norm_num [baseTwo,baseThree,baseThreeFactor,sum_pair,sum_spin, + exchangeNumerator_eq_table,exchangeTable,exchangeDenominator,cup,charge,zpow_neg, + q_five_inv,q_four_inv,T,t,zeta,inv_pow,q_inv] + +theorem baseThree_cup_24 (x z : ℂ) : + baseThree x (T*x) z .minus .minus .zero = + (1+T)*x * (z-t^5*x)*(z-t^6*x) * cup (.minus,.minus) * (if .zero = Spin.zero then 1 else 0) := by + norm_num [baseTwo,baseThree,baseThreeFactor,sum_pair,sum_spin, + exchangeNumerator_eq_table,exchangeTable,exchangeDenominator,cup,charge,zpow_neg, + q_five_inv,q_four_inv,T,t,zeta,inv_pow,q_inv] + +theorem baseThree_exchange_25 (x y z : ℂ) : + (∑ ab : Pair, exchangeNumerator x y (.minus,.minus) ab * + baseThree x y z ab.1 ab.2 .plus) = + exchangeDenominator x y * baseThree y x z .minus .minus .plus := by + norm_num [baseTwo,baseThree,baseThreeFactor,sum_pair,sum_spin, + exchangeNumerator_eq_table,exchangeTable,exchangeDenominator,cup,charge,zpow_neg, + q_five_inv,q_four_inv,T,t,zeta,inv_pow,q_inv] + +theorem baseThree_rotation_25 (x y z : ℂ) : + zeta ^ charge .minus * baseThree x y z .minus .plus .minus = + baseThree z x y .minus .minus .plus := by + norm_num [baseTwo,baseThree,baseThreeFactor,sum_pair,sum_spin, + exchangeNumerator_eq_table,exchangeTable,exchangeDenominator,cup,charge,zpow_neg, + q_five_inv,q_four_inv,T,t,zeta,inv_pow,q_inv] + +theorem baseThree_cup_25 (x z : ℂ) : + baseThree x (T*x) z .minus .minus .plus = + (1+T)*x * (z-t^5*x)*(z-t^6*x) * cup (.minus,.minus) * (if .plus = Spin.zero then 1 else 0) := by + norm_num [baseTwo,baseThree,baseThreeFactor,sum_pair,sum_spin, + exchangeNumerator_eq_table,exchangeTable,exchangeDenominator,cup,charge,zpow_neg, + q_five_inv,q_four_inv,T,t,zeta,inv_pow,q_inv] + +theorem baseThree_exchange_26 (x y z : ℂ) : + (∑ ab : Pair, exchangeNumerator x y (.minus,.minus) ab * + baseThree x y z ab.1 ab.2 .minus) = + exchangeDenominator x y * baseThree y x z .minus .minus .minus := by + norm_num [baseTwo,baseThree,baseThreeFactor,sum_pair,sum_spin, + exchangeNumerator_eq_table,exchangeTable,exchangeDenominator,cup,charge,zpow_neg, + q_five_inv,q_four_inv,T,t,zeta,inv_pow,q_inv] + +theorem baseThree_rotation_26 (x y z : ℂ) : + zeta ^ charge .minus * baseThree x y z .minus .minus .minus = + baseThree z x y .minus .minus .minus := by + norm_num [baseTwo,baseThree,baseThreeFactor,sum_pair,sum_spin, + exchangeNumerator_eq_table,exchangeTable,exchangeDenominator,cup,charge,zpow_neg, + q_five_inv,q_four_inv,T,t,zeta,inv_pow,q_inv] + +theorem baseThree_cup_26 (x z : ℂ) : + baseThree x (T*x) z .minus .minus .minus = + (1+T)*x * (z-t^5*x)*(z-t^6*x) * cup (.minus,.minus) * (if .minus = Spin.zero then 1 else 0) := by + norm_num [baseTwo,baseThree,baseThreeFactor,sum_pair,sum_spin, + exchangeNumerator_eq_table,exchangeTable,exchangeDenominator,cup,charge,zpow_neg, + q_five_inv,q_four_inv,T,t,zeta,inv_pow,q_inv] + +theorem baseThree_exchange (x y z : ℂ) (a b c : Spin) : + (∑ ab : Pair, exchangeNumerator x y (a,b) ab * baseThree x y z ab.1 ab.2 c) = + exchangeDenominator x y * baseThree y x z a b c := by + cases a <;> cases b <;> cases c + · exact baseThree_exchange_0 x y z + · exact baseThree_exchange_1 x y z + · exact baseThree_exchange_2 x y z + · exact baseThree_exchange_3 x y z + · exact baseThree_exchange_4 x y z + · exact baseThree_exchange_5 x y z + · exact baseThree_exchange_6 x y z + · exact baseThree_exchange_7 x y z + · exact baseThree_exchange_8 x y z + · exact baseThree_exchange_9 x y z + · exact baseThree_exchange_10 x y z + · exact baseThree_exchange_11 x y z + · exact baseThree_exchange_12 x y z + · exact baseThree_exchange_13 x y z + · exact baseThree_exchange_14 x y z + · exact baseThree_exchange_15 x y z + · exact baseThree_exchange_16 x y z + · exact baseThree_exchange_17 x y z + · exact baseThree_exchange_18 x y z + · exact baseThree_exchange_19 x y z + · exact baseThree_exchange_20 x y z + · exact baseThree_exchange_21 x y z + · exact baseThree_exchange_22 x y z + · exact baseThree_exchange_23 x y z + · exact baseThree_exchange_24 x y z + · exact baseThree_exchange_25 x y z + · exact baseThree_exchange_26 x y z + +theorem baseThree_rotation (x y z : ℂ) (a b c : Spin) : + zeta ^ charge a * baseThree x y z b c a = + baseThree z x y a b c := by + cases a <;> cases b <;> cases c + · exact baseThree_rotation_0 x y z + · exact baseThree_rotation_1 x y z + · exact baseThree_rotation_2 x y z + · exact baseThree_rotation_3 x y z + · exact baseThree_rotation_4 x y z + · exact baseThree_rotation_5 x y z + · exact baseThree_rotation_6 x y z + · exact baseThree_rotation_7 x y z + · exact baseThree_rotation_8 x y z + · exact baseThree_rotation_9 x y z + · exact baseThree_rotation_10 x y z + · exact baseThree_rotation_11 x y z + · exact baseThree_rotation_12 x y z + · exact baseThree_rotation_13 x y z + · exact baseThree_rotation_14 x y z + · exact baseThree_rotation_15 x y z + · exact baseThree_rotation_16 x y z + · exact baseThree_rotation_17 x y z + · exact baseThree_rotation_18 x y z + · exact baseThree_rotation_19 x y z + · exact baseThree_rotation_20 x y z + · exact baseThree_rotation_21 x y z + · exact baseThree_rotation_22 x y z + · exact baseThree_rotation_23 x y z + · exact baseThree_rotation_24 x y z + · exact baseThree_rotation_25 x y z + · exact baseThree_rotation_26 x y z + +theorem baseThree_cup (x z : ℂ) (a b c : Spin) : + baseThree x (T*x) z a b c = + (1+T)*x * (z-t^5*x)*(z-t^6*x) * cup (a,b) * (if c = Spin.zero then 1 else 0) := by + cases a <;> cases b <;> cases c + · exact baseThree_cup_0 x z + · exact baseThree_cup_1 x z + · exact baseThree_cup_2 x z + · exact baseThree_cup_3 x z + · exact baseThree_cup_4 x z + · exact baseThree_cup_5 x z + · exact baseThree_cup_6 x z + · exact baseThree_cup_7 x z + · exact baseThree_cup_8 x z + · exact baseThree_cup_9 x z + · exact baseThree_cup_10 x z + · exact baseThree_cup_11 x z + · exact baseThree_cup_12 x z + · exact baseThree_cup_13 x z + · exact baseThree_cup_14 x z + · exact baseThree_cup_15 x z + · exact baseThree_cup_16 x z + · exact baseThree_cup_17 x z + · exact baseThree_cup_18 x z + · exact baseThree_cup_19 x z + · exact baseThree_cup_20 x z + · exact baseThree_cup_21 x z + · exact baseThree_cup_22 x z + · exact baseThree_cup_23 x z + · exact baseThree_cup_24 x z + · exact baseThree_cup_25 x z + · exact baseThree_cup_26 x z + +end PolynomialVacuumAlgebra + +end OAI diff --git a/lean/OAI/Combinatorics/PolynomialVacuum/Algebra/BaseThreeNode.lean b/lean/OAI/Combinatorics/PolynomialVacuum/Algebra/BaseThreeNode.lean new file mode 100644 index 0000000000000000000000000000000000000000..2adea6523c6135d50c26e2a41871e278b3853024 --- /dev/null +++ b/lean/OAI/Combinatorics/PolynomialVacuum/Algebra/BaseThreeNode.lean @@ -0,0 +1,236 @@ +import OAI.Combinatorics.PolynomialVacuum.Algebra.BasePolynomials + +namespace OAI + +namespace PolynomialVacuumAlgebra +open MvPolynomial Classical +theorem baseThree_node_0 (x y : ℂ) : + baseThree x y (T*x) .zero .zero .zero = + (1+T)*x*(∑ ab : Pair, exchangeNumerator (T*x) y (.zero,.zero) ab * cup (.zero,ab.1) * (if ab.2=Spin.zero then 1 else 0)) := by + norm_num [baseTwo,baseThree,baseThreeFactor,sum_pair,sum_spin, + exchangeNumerator_eq_table,exchangeTable,exchangeDenominator,cup,charge,zpow_neg, + q_five_inv,q_four_inv,T,t,zeta,inv_pow,q_inv] + all_goals vacuum_ring_finish + +theorem baseThree_node_1 (x y : ℂ) : + baseThree x y (T*x) .zero .zero .plus = + (1+T)*x*(∑ ab : Pair, exchangeNumerator (T*x) y (.zero,.plus) ab * cup (.zero,ab.1) * (if ab.2=Spin.zero then 1 else 0)) := by + norm_num [baseTwo,baseThree,baseThreeFactor,sum_pair,sum_spin, + exchangeNumerator_eq_table,exchangeTable,exchangeDenominator,cup,charge,zpow_neg, + q_five_inv,q_four_inv,T,t,zeta,inv_pow,q_inv] + +theorem baseThree_node_2 (x y : ℂ) : + baseThree x y (T*x) .zero .zero .minus = + (1+T)*x*(∑ ab : Pair, exchangeNumerator (T*x) y (.zero,.minus) ab * cup (.zero,ab.1) * (if ab.2=Spin.zero then 1 else 0)) := by + norm_num [baseTwo,baseThree,baseThreeFactor,sum_pair,sum_spin, + exchangeNumerator_eq_table,exchangeTable,exchangeDenominator,cup,charge,zpow_neg, + q_five_inv,q_four_inv,T,t,zeta,inv_pow,q_inv] + +theorem baseThree_node_3 (x y : ℂ) : + baseThree x y (T*x) .zero .plus .zero = + (1+T)*x*(∑ ab : Pair, exchangeNumerator (T*x) y (.plus,.zero) ab * cup (.zero,ab.1) * (if ab.2=Spin.zero then 1 else 0)) := by + norm_num [baseTwo,baseThree,baseThreeFactor,sum_pair,sum_spin, + exchangeNumerator_eq_table,exchangeTable,exchangeDenominator,cup,charge,zpow_neg, + q_five_inv,q_four_inv,T,t,zeta,inv_pow,q_inv] + +theorem baseThree_node_4 (x y : ℂ) : + baseThree x y (T*x) .zero .plus .plus = + (1+T)*x*(∑ ab : Pair, exchangeNumerator (T*x) y (.plus,.plus) ab * cup (.zero,ab.1) * (if ab.2=Spin.zero then 1 else 0)) := by + norm_num [baseTwo,baseThree,baseThreeFactor,sum_pair,sum_spin, + exchangeNumerator_eq_table,exchangeTable,exchangeDenominator,cup,charge,zpow_neg, + q_five_inv,q_four_inv,T,t,zeta,inv_pow,q_inv] + +theorem baseThree_node_5 (x y : ℂ) : + baseThree x y (T*x) .zero .plus .minus = + (1+T)*x*(∑ ab : Pair, exchangeNumerator (T*x) y (.plus,.minus) ab * cup (.zero,ab.1) * (if ab.2=Spin.zero then 1 else 0)) := by + norm_num [baseTwo,baseThree,baseThreeFactor,sum_pair,sum_spin, + exchangeNumerator_eq_table,exchangeTable,exchangeDenominator,cup,charge,zpow_neg, + q_five_inv,q_four_inv,T,t,zeta,inv_pow,q_inv] + all_goals vacuum_ring_finish + +theorem baseThree_node_6 (x y : ℂ) : + baseThree x y (T*x) .zero .minus .zero = + (1+T)*x*(∑ ab : Pair, exchangeNumerator (T*x) y (.minus,.zero) ab * cup (.zero,ab.1) * (if ab.2=Spin.zero then 1 else 0)) := by + norm_num [baseTwo,baseThree,baseThreeFactor,sum_pair,sum_spin, + exchangeNumerator_eq_table,exchangeTable,exchangeDenominator,cup,charge,zpow_neg, + q_five_inv,q_four_inv,T,t,zeta,inv_pow,q_inv] + +theorem baseThree_node_7 (x y : ℂ) : + baseThree x y (T*x) .zero .minus .plus = + (1+T)*x*(∑ ab : Pair, exchangeNumerator (T*x) y (.minus,.plus) ab * cup (.zero,ab.1) * (if ab.2=Spin.zero then 1 else 0)) := by + norm_num [baseTwo,baseThree,baseThreeFactor,sum_pair,sum_spin, + exchangeNumerator_eq_table,exchangeTable,exchangeDenominator,cup,charge,zpow_neg, + q_five_inv,q_four_inv,T,t,zeta,inv_pow,q_inv] + all_goals vacuum_ring_finish + +theorem baseThree_node_8 (x y : ℂ) : + baseThree x y (T*x) .zero .minus .minus = + (1+T)*x*(∑ ab : Pair, exchangeNumerator (T*x) y (.minus,.minus) ab * cup (.zero,ab.1) * (if ab.2=Spin.zero then 1 else 0)) := by + norm_num [baseTwo,baseThree,baseThreeFactor,sum_pair,sum_spin, + exchangeNumerator_eq_table,exchangeTable,exchangeDenominator,cup,charge,zpow_neg, + q_five_inv,q_four_inv,T,t,zeta,inv_pow,q_inv] + +theorem baseThree_node_9 (x y : ℂ) : + baseThree x y (T*x) .plus .zero .zero = + (1+T)*x*(∑ ab : Pair, exchangeNumerator (T*x) y (.zero,.zero) ab * cup (.plus,ab.1) * (if ab.2=Spin.zero then 1 else 0)) := by + norm_num [baseTwo,baseThree,baseThreeFactor,sum_pair,sum_spin, + exchangeNumerator_eq_table,exchangeTable,exchangeDenominator,cup,charge,zpow_neg, + q_five_inv,q_four_inv,T,t,zeta,inv_pow,q_inv] + +theorem baseThree_node_10 (x y : ℂ) : + baseThree x y (T*x) .plus .zero .plus = + (1+T)*x*(∑ ab : Pair, exchangeNumerator (T*x) y (.zero,.plus) ab * cup (.plus,ab.1) * (if ab.2=Spin.zero then 1 else 0)) := by + norm_num [baseTwo,baseThree,baseThreeFactor,sum_pair,sum_spin, + exchangeNumerator_eq_table,exchangeTable,exchangeDenominator,cup,charge,zpow_neg, + q_five_inv,q_four_inv,T,t,zeta,inv_pow,q_inv] + +theorem baseThree_node_11 (x y : ℂ) : + baseThree x y (T*x) .plus .zero .minus = + (1+T)*x*(∑ ab : Pair, exchangeNumerator (T*x) y (.zero,.minus) ab * cup (.plus,ab.1) * (if ab.2=Spin.zero then 1 else 0)) := by + norm_num [baseTwo,baseThree,baseThreeFactor,sum_pair,sum_spin, + exchangeNumerator_eq_table,exchangeTable,exchangeDenominator,cup,charge,zpow_neg, + q_five_inv,q_four_inv,T,t,zeta,inv_pow,q_inv] + all_goals vacuum_ring_finish + +theorem baseThree_node_12 (x y : ℂ) : + baseThree x y (T*x) .plus .plus .zero = + (1+T)*x*(∑ ab : Pair, exchangeNumerator (T*x) y (.plus,.zero) ab * cup (.plus,ab.1) * (if ab.2=Spin.zero then 1 else 0)) := by + norm_num [baseTwo,baseThree,baseThreeFactor,sum_pair,sum_spin, + exchangeNumerator_eq_table,exchangeTable,exchangeDenominator,cup,charge,zpow_neg, + q_five_inv,q_four_inv,T,t,zeta,inv_pow,q_inv] + +theorem baseThree_node_13 (x y : ℂ) : + baseThree x y (T*x) .plus .plus .plus = + (1+T)*x*(∑ ab : Pair, exchangeNumerator (T*x) y (.plus,.plus) ab * cup (.plus,ab.1) * (if ab.2=Spin.zero then 1 else 0)) := by + norm_num [baseTwo,baseThree,baseThreeFactor,sum_pair,sum_spin, + exchangeNumerator_eq_table,exchangeTable,exchangeDenominator,cup,charge,zpow_neg, + q_five_inv,q_four_inv,T,t,zeta,inv_pow,q_inv] + +theorem baseThree_node_14 (x y : ℂ) : + baseThree x y (T*x) .plus .plus .minus = + (1+T)*x*(∑ ab : Pair, exchangeNumerator (T*x) y (.plus,.minus) ab * cup (.plus,ab.1) * (if ab.2=Spin.zero then 1 else 0)) := by + norm_num [baseTwo,baseThree,baseThreeFactor,sum_pair,sum_spin, + exchangeNumerator_eq_table,exchangeTable,exchangeDenominator,cup,charge,zpow_neg, + q_five_inv,q_four_inv,T,t,zeta,inv_pow,q_inv] + +theorem baseThree_node_15 (x y : ℂ) : + baseThree x y (T*x) .plus .minus .zero = + (1+T)*x*(∑ ab : Pair, exchangeNumerator (T*x) y (.minus,.zero) ab * cup (.plus,ab.1) * (if ab.2=Spin.zero then 1 else 0)) := by + norm_num [baseTwo,baseThree,baseThreeFactor,sum_pair,sum_spin, + exchangeNumerator_eq_table,exchangeTable,exchangeDenominator,cup,charge,zpow_neg, + q_five_inv,q_four_inv,T,t,zeta,inv_pow,q_inv] + all_goals vacuum_ring_finish + +theorem baseThree_node_16 (x y : ℂ) : + baseThree x y (T*x) .plus .minus .plus = + (1+T)*x*(∑ ab : Pair, exchangeNumerator (T*x) y (.minus,.plus) ab * cup (.plus,ab.1) * (if ab.2=Spin.zero then 1 else 0)) := by + norm_num [baseTwo,baseThree,baseThreeFactor,sum_pair,sum_spin, + exchangeNumerator_eq_table,exchangeTable,exchangeDenominator,cup,charge,zpow_neg, + q_five_inv,q_four_inv,T,t,zeta,inv_pow,q_inv] + +theorem baseThree_node_17 (x y : ℂ) : + baseThree x y (T*x) .plus .minus .minus = + (1+T)*x*(∑ ab : Pair, exchangeNumerator (T*x) y (.minus,.minus) ab * cup (.plus,ab.1) * (if ab.2=Spin.zero then 1 else 0)) := by + norm_num [baseTwo,baseThree,baseThreeFactor,sum_pair,sum_spin, + exchangeNumerator_eq_table,exchangeTable,exchangeDenominator,cup,charge,zpow_neg, + q_five_inv,q_four_inv,T,t,zeta,inv_pow,q_inv] + +theorem baseThree_node_18 (x y : ℂ) : + baseThree x y (T*x) .minus .zero .zero = + (1+T)*x*(∑ ab : Pair, exchangeNumerator (T*x) y (.zero,.zero) ab * cup (.minus,ab.1) * (if ab.2=Spin.zero then 1 else 0)) := by + norm_num [baseTwo,baseThree,baseThreeFactor,sum_pair,sum_spin, + exchangeNumerator_eq_table,exchangeTable,exchangeDenominator,cup,charge,zpow_neg, + q_five_inv,q_four_inv,T,t,zeta,inv_pow,q_inv] + +theorem baseThree_node_19 (x y : ℂ) : + baseThree x y (T*x) .minus .zero .plus = + (1+T)*x*(∑ ab : Pair, exchangeNumerator (T*x) y (.zero,.plus) ab * cup (.minus,ab.1) * (if ab.2=Spin.zero then 1 else 0)) := by + norm_num [baseTwo,baseThree,baseThreeFactor,sum_pair,sum_spin, + exchangeNumerator_eq_table,exchangeTable,exchangeDenominator,cup,charge,zpow_neg, + q_five_inv,q_four_inv,T,t,zeta,inv_pow,q_inv] + all_goals vacuum_ring_finish + +theorem baseThree_node_20 (x y : ℂ) : + baseThree x y (T*x) .minus .zero .minus = + (1+T)*x*(∑ ab : Pair, exchangeNumerator (T*x) y (.zero,.minus) ab * cup (.minus,ab.1) * (if ab.2=Spin.zero then 1 else 0)) := by + norm_num [baseTwo,baseThree,baseThreeFactor,sum_pair,sum_spin, + exchangeNumerator_eq_table,exchangeTable,exchangeDenominator,cup,charge,zpow_neg, + q_five_inv,q_four_inv,T,t,zeta,inv_pow,q_inv] + +theorem baseThree_node_21 (x y : ℂ) : + baseThree x y (T*x) .minus .plus .zero = + (1+T)*x*(∑ ab : Pair, exchangeNumerator (T*x) y (.plus,.zero) ab * cup (.minus,ab.1) * (if ab.2=Spin.zero then 1 else 0)) := by + norm_num [baseTwo,baseThree,baseThreeFactor,sum_pair,sum_spin, + exchangeNumerator_eq_table,exchangeTable,exchangeDenominator,cup,charge,zpow_neg, + q_five_inv,q_four_inv,T,t,zeta,inv_pow,q_inv] + all_goals vacuum_ring_finish + +theorem baseThree_node_22 (x y : ℂ) : + baseThree x y (T*x) .minus .plus .plus = + (1+T)*x*(∑ ab : Pair, exchangeNumerator (T*x) y (.plus,.plus) ab * cup (.minus,ab.1) * (if ab.2=Spin.zero then 1 else 0)) := by + norm_num [baseTwo,baseThree,baseThreeFactor,sum_pair,sum_spin, + exchangeNumerator_eq_table,exchangeTable,exchangeDenominator,cup,charge,zpow_neg, + q_five_inv,q_four_inv,T,t,zeta,inv_pow,q_inv] + +theorem baseThree_node_23 (x y : ℂ) : + baseThree x y (T*x) .minus .plus .minus = + (1+T)*x*(∑ ab : Pair, exchangeNumerator (T*x) y (.plus,.minus) ab * cup (.minus,ab.1) * (if ab.2=Spin.zero then 1 else 0)) := by + norm_num [baseTwo,baseThree,baseThreeFactor,sum_pair,sum_spin, + exchangeNumerator_eq_table,exchangeTable,exchangeDenominator,cup,charge,zpow_neg, + q_five_inv,q_four_inv,T,t,zeta,inv_pow,q_inv] + +theorem baseThree_node_24 (x y : ℂ) : + baseThree x y (T*x) .minus .minus .zero = + (1+T)*x*(∑ ab : Pair, exchangeNumerator (T*x) y (.minus,.zero) ab * cup (.minus,ab.1) * (if ab.2=Spin.zero then 1 else 0)) := by + norm_num [baseTwo,baseThree,baseThreeFactor,sum_pair,sum_spin, + exchangeNumerator_eq_table,exchangeTable,exchangeDenominator,cup,charge,zpow_neg, + q_five_inv,q_four_inv,T,t,zeta,inv_pow,q_inv] + +theorem baseThree_node_25 (x y : ℂ) : + baseThree x y (T*x) .minus .minus .plus = + (1+T)*x*(∑ ab : Pair, exchangeNumerator (T*x) y (.minus,.plus) ab * cup (.minus,ab.1) * (if ab.2=Spin.zero then 1 else 0)) := by + norm_num [baseTwo,baseThree,baseThreeFactor,sum_pair,sum_spin, + exchangeNumerator_eq_table,exchangeTable,exchangeDenominator,cup,charge,zpow_neg, + q_five_inv,q_four_inv,T,t,zeta,inv_pow,q_inv] + +theorem baseThree_node_26 (x y : ℂ) : + baseThree x y (T*x) .minus .minus .minus = + (1+T)*x*(∑ ab : Pair, exchangeNumerator (T*x) y (.minus,.minus) ab * cup (.minus,ab.1) * (if ab.2=Spin.zero then 1 else 0)) := by + norm_num [baseTwo,baseThree,baseThreeFactor,sum_pair,sum_spin, + exchangeNumerator_eq_table,exchangeTable,exchangeDenominator,cup,charge,zpow_neg, + q_five_inv,q_four_inv,T,t,zeta,inv_pow,q_inv] + +theorem baseThree_node (x y : ℂ) (a b c : Spin) : + baseThree x y (T*x) a b c = + (1+T)*x*(∑ ab : Pair, exchangeNumerator (T*x) y (b,c) ab * cup (a,ab.1) * (if ab.2=Spin.zero then 1 else 0)) := by + cases a <;> cases b <;> cases c + · exact baseThree_node_0 x y + · exact baseThree_node_1 x y + · exact baseThree_node_2 x y + · exact baseThree_node_3 x y + · exact baseThree_node_4 x y + · exact baseThree_node_5 x y + · exact baseThree_node_6 x y + · exact baseThree_node_7 x y + · exact baseThree_node_8 x y + · exact baseThree_node_9 x y + · exact baseThree_node_10 x y + · exact baseThree_node_11 x y + · exact baseThree_node_12 x y + · exact baseThree_node_13 x y + · exact baseThree_node_14 x y + · exact baseThree_node_15 x y + · exact baseThree_node_16 x y + · exact baseThree_node_17 x y + · exact baseThree_node_18 x y + · exact baseThree_node_19 x y + · exact baseThree_node_20 x y + · exact baseThree_node_21 x y + · exact baseThree_node_22 x y + · exact baseThree_node_23 x y + · exact baseThree_node_24 x y + · exact baseThree_node_25 x y + · exact baseThree_node_26 x y +end PolynomialVacuumAlgebra + +end OAI diff --git a/lean/OAI/Combinatorics/PolynomialVacuum/Algebra/BaseTwo.lean b/lean/OAI/Combinatorics/PolynomialVacuum/Algebra/BaseTwo.lean new file mode 100644 index 0000000000000000000000000000000000000000..1578bcaaf8acccbd07d5ba34e1cdc65dabea27fe --- /dev/null +++ b/lean/OAI/Combinatorics/PolynomialVacuum/Algebra/BaseTwo.lean @@ -0,0 +1,276 @@ +import OAI.Combinatorics.PolynomialVacuum.Algebra.Table +import OAI.Combinatorics.PolynomialVacuum.Algebra.Ring + +namespace OAI + +namespace PolynomialVacuumAlgebra + +noncomputable def baseTwo (x y : ℂ) : Spin → Spin → ℂ + | .zero,.zero => x+y + | .plus,.minus => (q^5-q^7)*y + | .minus,.plus => (q-q^3)*x + | _,_ => 0 + +noncomputable def baseThreeFactor (x y z : ℂ) : ℂ := (z+q^2*x)*(z-q^6*y) +noncomputable def baseThree (x y z : ℂ) : Spin → Spin → Spin → ℂ + | .zero,.zero,.zero => x^2*y+x^2*z+y^2*x+y^2*z+z^2*x+z^2*y+2*(q^2-q^6)*x*y*z + | .plus,.minus,.zero => (q^5-q^7)*y*baseThreeFactor x y z + | .minus,.plus,.zero => (q-q^3)*x*baseThreeFactor x y z + | .zero,.plus,.minus => (q^5-q^7)*z*baseThreeFactor y z x + | .zero,.minus,.plus => (q-q^3)*y*baseThreeFactor y z x + | .plus,.zero,.minus => (q^5-q^7)*z*baseThreeFactor z x y + | .minus,.zero,.plus => (q-q^3)*x*baseThreeFactor z x y + | _,_,_ => 0 + +theorem baseTwo_exchange_0 (x y : ℂ) : + (∑ ab : Pair, exchangeNumerator x y (.zero,.zero) ab * + baseTwo x y ab.1 ab.2 ) = + exchangeDenominator x y * baseTwo y x .zero .zero := by + norm_num [baseTwo,baseThree,baseThreeFactor,sum_pair,sum_spin, + exchangeNumerator_eq_table,exchangeTable,exchangeDenominator,cup,charge,zpow_neg, + q_five_inv,q_four_inv,T,t,zeta,inv_pow,q_inv] + all_goals vacuum_ring_finish + +theorem baseTwo_rotation_0 (x y : ℂ) : + zeta ^ charge .zero * baseTwo x y .zero .zero = + baseTwo y x .zero .zero := by + norm_num [baseTwo,baseThree,baseThreeFactor,sum_pair,sum_spin, + exchangeNumerator_eq_table,exchangeTable,exchangeDenominator,cup,charge,zpow_neg, + q_five_inv,q_four_inv,T,t,zeta,inv_pow,q_inv] + all_goals vacuum_ring_finish + +theorem baseTwo_cup_0 (x : ℂ) : + baseTwo x (T*x) .zero .zero = + (1+T)*x * cup (.zero,.zero) := by + norm_num [baseTwo,baseThree,baseThreeFactor,sum_pair,sum_spin, + exchangeNumerator_eq_table,exchangeTable,exchangeDenominator,cup,charge,zpow_neg, + q_five_inv,q_four_inv,T,t,zeta,inv_pow,q_inv] + all_goals vacuum_ring_finish + +theorem baseTwo_exchange_1 (x y : ℂ) : + (∑ ab : Pair, exchangeNumerator x y (.zero,.plus) ab * + baseTwo x y ab.1 ab.2 ) = + exchangeDenominator x y * baseTwo y x .zero .plus := by + norm_num [baseTwo,baseThree,baseThreeFactor,sum_pair,sum_spin, + exchangeNumerator_eq_table,exchangeTable,exchangeDenominator,cup,charge,zpow_neg, + q_five_inv,q_four_inv,T,t,zeta,inv_pow,q_inv] + +theorem baseTwo_rotation_1 (x y : ℂ) : + zeta ^ charge .zero * baseTwo x y .plus .zero = + baseTwo y x .zero .plus := by + norm_num [baseTwo,baseThree,baseThreeFactor,sum_pair,sum_spin, + exchangeNumerator_eq_table,exchangeTable,exchangeDenominator,cup,charge,zpow_neg, + q_five_inv,q_four_inv,T,t,zeta,inv_pow,q_inv] + +theorem baseTwo_cup_1 (x : ℂ) : + baseTwo x (T*x) .zero .plus = + (1+T)*x * cup (.zero,.plus) := by + norm_num [baseTwo,baseThree,baseThreeFactor,sum_pair,sum_spin, + exchangeNumerator_eq_table,exchangeTable,exchangeDenominator,cup,charge,zpow_neg, + q_five_inv,q_four_inv,T,t,zeta,inv_pow,q_inv] + +theorem baseTwo_exchange_2 (x y : ℂ) : + (∑ ab : Pair, exchangeNumerator x y (.zero,.minus) ab * + baseTwo x y ab.1 ab.2 ) = + exchangeDenominator x y * baseTwo y x .zero .minus := by + norm_num [baseTwo,baseThree,baseThreeFactor,sum_pair,sum_spin, + exchangeNumerator_eq_table,exchangeTable,exchangeDenominator,cup,charge,zpow_neg, + q_five_inv,q_four_inv,T,t,zeta,inv_pow,q_inv] + +theorem baseTwo_rotation_2 (x y : ℂ) : + zeta ^ charge .zero * baseTwo x y .minus .zero = + baseTwo y x .zero .minus := by + norm_num [baseTwo,baseThree,baseThreeFactor,sum_pair,sum_spin, + exchangeNumerator_eq_table,exchangeTable,exchangeDenominator,cup,charge,zpow_neg, + q_five_inv,q_four_inv,T,t,zeta,inv_pow,q_inv] + +theorem baseTwo_cup_2 (x : ℂ) : + baseTwo x (T*x) .zero .minus = + (1+T)*x * cup (.zero,.minus) := by + norm_num [baseTwo,baseThree,baseThreeFactor,sum_pair,sum_spin, + exchangeNumerator_eq_table,exchangeTable,exchangeDenominator,cup,charge,zpow_neg, + q_five_inv,q_four_inv,T,t,zeta,inv_pow,q_inv] + +theorem baseTwo_exchange_3 (x y : ℂ) : + (∑ ab : Pair, exchangeNumerator x y (.plus,.zero) ab * + baseTwo x y ab.1 ab.2 ) = + exchangeDenominator x y * baseTwo y x .plus .zero := by + norm_num [baseTwo,baseThree,baseThreeFactor,sum_pair,sum_spin, + exchangeNumerator_eq_table,exchangeTable,exchangeDenominator,cup,charge,zpow_neg, + q_five_inv,q_four_inv,T,t,zeta,inv_pow,q_inv] + +theorem baseTwo_rotation_3 (x y : ℂ) : + zeta ^ charge .plus * baseTwo x y .zero .plus = + baseTwo y x .plus .zero := by + norm_num [baseTwo,baseThree,baseThreeFactor,sum_pair,sum_spin, + exchangeNumerator_eq_table,exchangeTable,exchangeDenominator,cup,charge,zpow_neg, + q_five_inv,q_four_inv,T,t,zeta,inv_pow,q_inv] + +theorem baseTwo_cup_3 (x : ℂ) : + baseTwo x (T*x) .plus .zero = + (1+T)*x * cup (.plus,.zero) := by + norm_num [baseTwo,baseThree,baseThreeFactor,sum_pair,sum_spin, + exchangeNumerator_eq_table,exchangeTable,exchangeDenominator,cup,charge,zpow_neg, + q_five_inv,q_four_inv,T,t,zeta,inv_pow,q_inv] + +theorem baseTwo_exchange_4 (x y : ℂ) : + (∑ ab : Pair, exchangeNumerator x y (.plus,.plus) ab * + baseTwo x y ab.1 ab.2 ) = + exchangeDenominator x y * baseTwo y x .plus .plus := by + norm_num [baseTwo,baseThree,baseThreeFactor,sum_pair,sum_spin, + exchangeNumerator_eq_table,exchangeTable,exchangeDenominator,cup,charge,zpow_neg, + q_five_inv,q_four_inv,T,t,zeta,inv_pow,q_inv] + +theorem baseTwo_rotation_4 (x y : ℂ) : + zeta ^ charge .plus * baseTwo x y .plus .plus = + baseTwo y x .plus .plus := by + norm_num [baseTwo,baseThree,baseThreeFactor,sum_pair,sum_spin, + exchangeNumerator_eq_table,exchangeTable,exchangeDenominator,cup,charge,zpow_neg, + q_five_inv,q_four_inv,T,t,zeta,inv_pow,q_inv] + +theorem baseTwo_cup_4 (x : ℂ) : + baseTwo x (T*x) .plus .plus = + (1+T)*x * cup (.plus,.plus) := by + norm_num [baseTwo,baseThree,baseThreeFactor,sum_pair,sum_spin, + exchangeNumerator_eq_table,exchangeTable,exchangeDenominator,cup,charge,zpow_neg, + q_five_inv,q_four_inv,T,t,zeta,inv_pow,q_inv] + +theorem baseTwo_exchange_5 (x y : ℂ) : + (∑ ab : Pair, exchangeNumerator x y (.plus,.minus) ab * + baseTwo x y ab.1 ab.2 ) = + exchangeDenominator x y * baseTwo y x .plus .minus := by + norm_num [baseTwo,baseThree,baseThreeFactor,sum_pair,sum_spin, + exchangeNumerator_eq_table,exchangeTable,exchangeDenominator,cup,charge,zpow_neg, + q_five_inv,q_four_inv,T,t,zeta,inv_pow,q_inv] + all_goals vacuum_ring_finish + +theorem baseTwo_rotation_5 (x y : ℂ) : + zeta ^ charge .plus * baseTwo x y .minus .plus = + baseTwo y x .plus .minus := by + norm_num [baseTwo,baseThree,baseThreeFactor,sum_pair,sum_spin, + exchangeNumerator_eq_table,exchangeTable,exchangeDenominator,cup,charge,zpow_neg, + q_five_inv,q_four_inv,T,t,zeta,inv_pow,q_inv] + all_goals vacuum_ring_finish + +theorem baseTwo_cup_5 (x : ℂ) : + baseTwo x (T*x) .plus .minus = + (1+T)*x * cup (.plus,.minus) := by + norm_num [baseTwo,baseThree,baseThreeFactor,sum_pair,sum_spin, + exchangeNumerator_eq_table,exchangeTable,exchangeDenominator,cup,charge,zpow_neg, + q_five_inv,q_four_inv,T,t,zeta,inv_pow,q_inv] + all_goals vacuum_ring_finish + +theorem baseTwo_exchange_6 (x y : ℂ) : + (∑ ab : Pair, exchangeNumerator x y (.minus,.zero) ab * + baseTwo x y ab.1 ab.2 ) = + exchangeDenominator x y * baseTwo y x .minus .zero := by + norm_num [baseTwo,baseThree,baseThreeFactor,sum_pair,sum_spin, + exchangeNumerator_eq_table,exchangeTable,exchangeDenominator,cup,charge,zpow_neg, + q_five_inv,q_four_inv,T,t,zeta,inv_pow,q_inv] + +theorem baseTwo_rotation_6 (x y : ℂ) : + zeta ^ charge .minus * baseTwo x y .zero .minus = + baseTwo y x .minus .zero := by + norm_num [baseTwo,baseThree,baseThreeFactor,sum_pair,sum_spin, + exchangeNumerator_eq_table,exchangeTable,exchangeDenominator,cup,charge,zpow_neg, + q_five_inv,q_four_inv,T,t,zeta,inv_pow,q_inv] + +theorem baseTwo_cup_6 (x : ℂ) : + baseTwo x (T*x) .minus .zero = + (1+T)*x * cup (.minus,.zero) := by + norm_num [baseTwo,baseThree,baseThreeFactor,sum_pair,sum_spin, + exchangeNumerator_eq_table,exchangeTable,exchangeDenominator,cup,charge,zpow_neg, + q_five_inv,q_four_inv,T,t,zeta,inv_pow,q_inv] + +theorem baseTwo_exchange_7 (x y : ℂ) : + (∑ ab : Pair, exchangeNumerator x y (.minus,.plus) ab * + baseTwo x y ab.1 ab.2 ) = + exchangeDenominator x y * baseTwo y x .minus .plus := by + norm_num [baseTwo,baseThree,baseThreeFactor,sum_pair,sum_spin, + exchangeNumerator_eq_table,exchangeTable,exchangeDenominator,cup,charge,zpow_neg, + q_five_inv,q_four_inv,T,t,zeta,inv_pow,q_inv] + all_goals vacuum_ring_finish + +theorem baseTwo_rotation_7 (x y : ℂ) : + zeta ^ charge .minus * baseTwo x y .plus .minus = + baseTwo y x .minus .plus := by + norm_num [baseTwo,baseThree,baseThreeFactor,sum_pair,sum_spin, + exchangeNumerator_eq_table,exchangeTable,exchangeDenominator,cup,charge,zpow_neg, + q_five_inv,q_four_inv,T,t,zeta,inv_pow,q_inv] + all_goals vacuum_ring_finish + +theorem baseTwo_cup_7 (x : ℂ) : + baseTwo x (T*x) .minus .plus = + (1+T)*x * cup (.minus,.plus) := by + norm_num [baseTwo,baseThree,baseThreeFactor,sum_pair,sum_spin, + exchangeNumerator_eq_table,exchangeTable,exchangeDenominator,cup,charge,zpow_neg, + q_five_inv,q_four_inv,T,t,zeta,inv_pow,q_inv] + all_goals vacuum_ring_finish + +theorem baseTwo_exchange_8 (x y : ℂ) : + (∑ ab : Pair, exchangeNumerator x y (.minus,.minus) ab * + baseTwo x y ab.1 ab.2 ) = + exchangeDenominator x y * baseTwo y x .minus .minus := by + norm_num [baseTwo,baseThree,baseThreeFactor,sum_pair,sum_spin, + exchangeNumerator_eq_table,exchangeTable,exchangeDenominator,cup,charge,zpow_neg, + q_five_inv,q_four_inv,T,t,zeta,inv_pow,q_inv] + +theorem baseTwo_rotation_8 (x y : ℂ) : + zeta ^ charge .minus * baseTwo x y .minus .minus = + baseTwo y x .minus .minus := by + norm_num [baseTwo,baseThree,baseThreeFactor,sum_pair,sum_spin, + exchangeNumerator_eq_table,exchangeTable,exchangeDenominator,cup,charge,zpow_neg, + q_five_inv,q_four_inv,T,t,zeta,inv_pow,q_inv] + +theorem baseTwo_cup_8 (x : ℂ) : + baseTwo x (T*x) .minus .minus = + (1+T)*x * cup (.minus,.minus) := by + norm_num [baseTwo,baseThree,baseThreeFactor,sum_pair,sum_spin, + exchangeNumerator_eq_table,exchangeTable,exchangeDenominator,cup,charge,zpow_neg, + q_five_inv,q_four_inv,T,t,zeta,inv_pow,q_inv] + +theorem baseTwo_exchange (x y : ℂ) (a b : Spin) : + (∑ ab : Pair, exchangeNumerator x y (a,b) ab * baseTwo x y ab.1 ab.2 ) = + exchangeDenominator x y * baseTwo y x a b := by + cases a <;> cases b + · exact baseTwo_exchange_0 x y + · exact baseTwo_exchange_1 x y + · exact baseTwo_exchange_2 x y + · exact baseTwo_exchange_3 x y + · exact baseTwo_exchange_4 x y + · exact baseTwo_exchange_5 x y + · exact baseTwo_exchange_6 x y + · exact baseTwo_exchange_7 x y + · exact baseTwo_exchange_8 x y + +theorem baseTwo_rotation (x y : ℂ) (a b : Spin) : + zeta ^ charge a * baseTwo x y b a = + baseTwo y x a b := by + cases a <;> cases b + · exact baseTwo_rotation_0 x y + · exact baseTwo_rotation_1 x y + · exact baseTwo_rotation_2 x y + · exact baseTwo_rotation_3 x y + · exact baseTwo_rotation_4 x y + · exact baseTwo_rotation_5 x y + · exact baseTwo_rotation_6 x y + · exact baseTwo_rotation_7 x y + · exact baseTwo_rotation_8 x y + +theorem baseTwo_cup (x : ℂ) (a b : Spin) : + baseTwo x (T*x) a b = + (1+T)*x * cup (a,b) := by + cases a <;> cases b + · exact baseTwo_cup_0 x + · exact baseTwo_cup_1 x + · exact baseTwo_cup_2 x + · exact baseTwo_cup_3 x + · exact baseTwo_cup_4 x + · exact baseTwo_cup_5 x + · exact baseTwo_cup_6 x + · exact baseTwo_cup_7 x + · exact baseTwo_cup_8 x + +end PolynomialVacuumAlgebra + +end OAI diff --git a/lean/OAI/Combinatorics/PolynomialVacuum/Algebra/BilinearChannels.lean b/lean/OAI/Combinatorics/PolynomialVacuum/Algebra/BilinearChannels.lean new file mode 100644 index 0000000000000000000000000000000000000000..82ade854fe3d878b2024eeed65b3453297d64e15 --- /dev/null +++ b/lean/OAI/Combinatorics/PolynomialVacuum/Algebra/BilinearChannels.lean @@ -0,0 +1,94 @@ +import OAI.Combinatorics.PolynomialVacuum.Algebra.Ring +import OAI.Combinatorics.PolynomialVacuum.Algebra.Projectors + +namespace OAI + +namespace PolynomialVacuumAlgebra + +noncomputable def eigenZero (x y : ℂ) : ℂ := (t^2*y-x)*(T*x-y) +noncomputable def eigenOne (x y : ℂ) : ℂ := (T*y-x)*(t^2*x-y) +noncomputable def eigenTwo (x y : ℂ) : ℂ := (t^2*y-x)*(T*y-x) + +def ScalarBilinearExchange (e : ℂ → ℂ → ℂ) (a b c d : ℂ) : Prop := + ∀ x y, e x y*(a+x*b+y*c+x*y*d)=eigenOne x y*(a+y*b+x*c+x*y*d) + +theorem bilinearZero_a (a b c d : ℂ) (h : ScalarBilinearExchange eigenZero a b c d) : a=0 := by + have h0 := h (1) (0) + simp only [eigenZero,eigenOne,T,t] at h0 + have h1 := h (-1) (0) + simp only [eigenZero,eigenOne,T,t] at h1 + linear_combination (norm := skip) ((1/4:ℂ)+(1/4:ℂ)*q^2-(1/4:ℂ)*q^4-(1/4:ℂ)*q^6)*h0+((1/4:ℂ)+(1/4:ℂ)*q^2-(1/4:ℂ)*q^4-(1/4:ℂ)*q^6)*h1 + vacuum_ring_finish + +theorem bilinearZero_b (a b c d : ℂ) (h : ScalarBilinearExchange eigenZero a b c d) : b=0 := by + have h0 := h (1) (0) + simp only [eigenZero,eigenOne,T,t] at h0 + have h1 := h (-1) (0) + simp only [eigenZero,eigenOne,T,t] at h1 + have h4 := h (1) (2) + simp only [eigenZero,eigenOne,T,t] at h4 + have h5 := h (-1) (-2) + simp only [eigenZero,eigenOne,T,t] at h5 + linear_combination (norm := skip) (-(7/8:ℂ)+(1/4:ℂ)*q^2+(7/8:ℂ)*q^4+(7/8:ℂ)*q^6)*h0+((7/8:ℂ)-(1/4:ℂ)*q^2-(7/8:ℂ)*q^4-(7/8:ℂ)*q^6)*h1+(-(1/8:ℂ)+(1/8:ℂ)*q^4+(1/8:ℂ)*q^6)*h4+((1/8:ℂ)-(1/8:ℂ)*q^4-(1/8:ℂ)*q^6)*h5 + vacuum_ring_finish + +theorem bilinearZero_c (a b c d : ℂ) (h : ScalarBilinearExchange eigenZero a b c d) : c=0 := by + have h0 := h (1) (0) + simp only [eigenZero,eigenOne,T,t] at h0 + have h1 := h (-1) (0) + simp only [eigenZero,eigenOne,T,t] at h1 + have h4 := h (1) (2) + simp only [eigenZero,eigenOne,T,t] at h4 + have h5 := h (-1) (-2) + simp only [eigenZero,eigenOne,T,t] at h5 + linear_combination (norm := skip) (-(7/8:ℂ)-(7/8:ℂ)*q^2-(1/4:ℂ)*q^4+(7/8:ℂ)*q^6)*h0+((7/8:ℂ)+(7/8:ℂ)*q^2+(1/4:ℂ)*q^4-(7/8:ℂ)*q^6)*h1+(-(1/8:ℂ)-(1/8:ℂ)*q^2+(1/8:ℂ)*q^6)*h4+((1/8:ℂ)+(1/8:ℂ)*q^2-(1/8:ℂ)*q^6)*h5 + vacuum_ring_finish + +theorem bilinearZero_d (a b c d : ℂ) (h : ScalarBilinearExchange eigenZero a b c d) : d=0 := by + have h0 := h (1) (0) + simp only [eigenZero,eigenOne,T,t] at h0 + have h1 := h (-1) (0) + simp only [eigenZero,eigenOne,T,t] at h1 + have h4 := h (1) (2) + simp only [eigenZero,eigenOne,T,t] at h4 + have h5 := h (-1) (-2) + simp only [eigenZero,eigenOne,T,t] at h5 + linear_combination (norm := skip) (-(1/8:ℂ)-(1/8:ℂ)*q^2+(1/8:ℂ)*q^4+(1/8:ℂ)*q^6)*h0+(-(1/8:ℂ)-(1/8:ℂ)*q^2+(1/8:ℂ)*q^4+(1/8:ℂ)*q^6)*h1+(-(1/24:ℂ)-(1/24:ℂ)*q^2+(1/24:ℂ)*q^4+(1/24:ℂ)*q^6)*h4+(-(1/24:ℂ)-(1/24:ℂ)*q^2+(1/24:ℂ)*q^4+(1/24:ℂ)*q^6)*h5 + vacuum_ring_finish + +theorem bilinearOne_bc (a b c d : ℂ) (h : ScalarBilinearExchange eigenOne a b c d) : b=c := by + have h0 := h (1) (0) + simp only [eigenOne,eigenOne,T,t] at h0 + linear_combination (norm := skip) (q^4)*h0 + vacuum_ring_finish + +theorem bilinearTwo_a (a b c d : ℂ) (h : ScalarBilinearExchange eigenTwo a b c d) : a=0 := by + have h0 := h (1) (0) + simp only [eigenTwo,eigenOne,T,t] at h0 + have h1 := h (-1) (0) + simp only [eigenTwo,eigenOne,T,t] at h1 + linear_combination (norm := skip) ((1/4:ℂ)-(1/4:ℂ)*q^4)*h0+((1/4:ℂ)-(1/4:ℂ)*q^4)*h1 + vacuum_ring_finish + +theorem bilinearTwo_d (a b c d : ℂ) (h : ScalarBilinearExchange eigenTwo a b c d) : d=0 := by + have h0 := h (1) (0) + simp only [eigenTwo,eigenOne,T,t] at h0 + have h1 := h (-1) (0) + simp only [eigenTwo,eigenOne,T,t] at h1 + have h4 := h (1) (2) + simp only [eigenTwo,eigenOne,T,t] at h4 + linear_combination (norm := skip) (-(1/2:ℂ)+(1/2:ℂ)*q^4)*h0+((1/4:ℂ)-(1/4:ℂ)*q^4)*h1+((3/68:ℂ)-(5/34:ℂ)*q^2+(5/68:ℂ)*q^4+(3/34:ℂ)*q^6)*h4 + vacuum_ring_finish + +theorem bilinearTwo_bc (a b c d : ℂ) (h : ScalarBilinearExchange eigenTwo a b c d) : b= -(t^2)*c := by + have h0 := h (1) (0) + simp only [eigenTwo,eigenOne,T,t] at h0 + have h1 := h (-1) (0) + simp only [eigenTwo,eigenOne,T,t] at h1 + unfold t + linear_combination (norm := skip) ((1/2:ℂ))*h0+(-(1/2:ℂ))*h1 + vacuum_ring_finish + +end PolynomialVacuumAlgebra + +end OAI diff --git a/lean/OAI/Combinatorics/PolynomialVacuum/Algebra/BitCoefficients.lean b/lean/OAI/Combinatorics/PolynomialVacuum/Algebra/BitCoefficients.lean new file mode 100644 index 0000000000000000000000000000000000000000..f420ec1b7ac0449e30dd38d8335bedb5bd4ed3ff --- /dev/null +++ b/lean/OAI/Combinatorics/PolynomialVacuum/Algebra/BitCoefficients.lean @@ -0,0 +1,120 @@ +import OAI.Combinatorics.PolynomialVacuum.Algebra.PolynomialSlice + +namespace OAI + +namespace PolynomialVacuumAlgebra +open MvPolynomial Classical + +noncomputable def bitCoefficient {V : Type*} [Sub V] (b : Bool) (f : ℂ → V) : V := + if b then f 1-f 0 else f 0 + +noncomputable def biCoefficient {V : Type*} [Sub V] (f : ℂ → ℂ → V) (i j : Bool) : V := + bitCoefficient i (fun x => bitCoefficient j (f x)) + +noncomputable def triCoefficient {V : Type*} [Sub V] (f : ℂ → ℂ → ℂ → V) (i j k : Bool) : V := + bitCoefficient i (fun x => bitCoefficient j (fun y => bitCoefficient k (f x y))) + +variable {V W : Type*} [AddCommGroup V] [Module ℂ V] [AddCommGroup W] [Module ℂ W] + +def AffineFunction (f : ℂ → V) : Prop := ∀ x, f x=f 0+x • (f 1-f 0) + +omit [Module ℂ V] in +@[simp] theorem bitCoefficient_false (f : ℂ → V) : bitCoefficient false f=f 0 := rfl +omit [Module ℂ V] in +@[simp] theorem bitCoefficient_true (f : ℂ → V) : bitCoefficient true f=f 1-f 0 := rfl +omit [Module ℂ V] in +@[simp] theorem bitCoefficient_zero (b : Bool) : bitCoefficient b (fun _ : ℂ => (0:V))=0 := by cases b <;> simp [bitCoefficient] + +omit [Module ℂ V] in +theorem bitCoefficient_add (b : Bool) (f g : ℂ → V) : + bitCoefficient b (fun x => f x+g x)=bitCoefficient b f+bitCoefficient b g := by + cases b <;> simp only [bitCoefficient_true,bitCoefficient_false] + abel + +omit [Module ℂ V] in +theorem bitCoefficient_sub (b : Bool) (f g : ℂ → V) : + bitCoefficient b (fun x => f x-g x)=bitCoefficient b f-bitCoefficient b g := by + cases b <;> simp only [bitCoefficient_true,bitCoefficient_false] + abel + +theorem bitCoefficient_smul (b : Bool) (c : ℂ) (f : ℂ → V) : + bitCoefficient b (fun x => c • f x)=c • bitCoefficient b f := by + cases b <;> simp only [bitCoefficient_true,bitCoefficient_false,smul_sub] + +theorem bitCoefficient_linearMap (b : Bool) (L : V →ₗ[ℂ] W) (f : ℂ → V) : + bitCoefficient b (fun x => L (f x))=L (bitCoefficient b f) := by + cases b <;> simp only [bitCoefficient_true,bitCoefficient_false,map_sub] + +omit [Module ℂ V] in +theorem bitCoefficient_comm (i j : Bool) (f : ℂ → ℂ → V) : + bitCoefficient i (fun x => bitCoefficient j (f x))= + bitCoefficient j (fun y => bitCoefficient i (fun x => f x y)) := by + cases i <;> cases j <;> simp only [bitCoefficient_true,bitCoefficient_false] + abel + +theorem affine_sub {f g : ℂ → V} (hf : AffineFunction f) (hg : AffineFunction g) : + AffineFunction (fun x => f x-g x) := by + intro x + change f x-g x=(f 0-g 0)+x • ((f 1-g 1)-(f 0-g 0)) + rw [hf x,hg x] + module + +theorem affine_bitCoefficient (b : Bool) (f : ℂ → ℂ → V) + (hf : ∀ y, AffineFunction (fun x => f x y)) : AffineFunction (fun x => bitCoefficient b (f x)) := by + cases b + · exact hf 0 + · exact affine_sub (hf 1) (hf 0) + +theorem bilinear_expansion (f : ℂ → ℂ → V) + (hx : ∀ y, AffineFunction (fun x => f x y)) (hy : ∀ x, AffineFunction (f x)) (x y : ℂ) : + f x y=biCoefficient f false false+x • biCoefficient f true false+ + y • biCoefficient f false true+(x*y) • biCoefficient f true true := by + have hxx := hx y x + dsimp only at hxx + rw [hxx,hy 0 y,hy 1 y] + simp only [biCoefficient,bitCoefficient_false,bitCoefficient_true] + module + +theorem affine_zero {f : ℂ → V} (h : AffineFunction f) (hz : ∀ b, bitCoefficient b f=0) : f=0 := by + funext x + rw [h x] + change bitCoefficient false f+x • bitCoefficient true f=0 + rw [hz false,hz true,smul_zero,add_zero] + +theorem triaffine_zero (f : ℂ → ℂ → ℂ → V) + (hx : ∀ y z, AffineFunction (fun x => f x y z)) + (hy : ∀ x z, AffineFunction (fun y => f x y z)) + (hz : ∀ x y, AffineFunction (f x y)) + (h : ∀ i j k, triCoefficient f i j k=0) : ∀ x y z, f x y z=0 := by + have hc (k : Bool) (x y : ℂ) : bitCoefficient k (f x y)=0 := by + have he := bilinear_expansion (fun x y => bitCoefficient k (f x y)) + (fun y => affine_bitCoefficient k _ (fun z => hx y z)) + (fun x => affine_bitCoefficient k _ (fun z => hy x z)) x y + change bitCoefficient k (f x y)=triCoefficient f false false k+ + x • triCoefficient f true false k+y • triCoefficient f false true k+ + (x*y) • triCoefficient f true true k at he + simp only [h,smul_zero,add_zero] at he + exact he + intro x y z + have he := congrFun (affine_zero (hz x y) (fun k => hc k x y)) z + exact he + +theorem eval_update_affine {ι : Type*} (p : MvPolynomial ι ℂ) (i : ι) (Y : ι → ℂ) + (hd : p.degreeOf i ≤ 1) : AffineFunction (fun x => eval (Function.update Y i x) p) := by + have hnd := (polynomialSlice_natDegree i Y p).trans hd + obtain ⟨a,b,he⟩ := Polynomial.exists_eq_X_add_C_of_natDegree_le_one hnd + intro x + simp only [← eval_polynomialSlice,he,Polynomial.eval_add,Polynomial.eval_mul,Polynomial.eval_C,Polynomial.eval_X,smul_eq_mul] + ring + +theorem eval_update_constant {ι : Type*} (p : MvPolynomial ι ℂ) (i : ι) (Y : ι → ℂ) + (hd : p.degreeOf i ≤ 0) (x : ℂ) : eval (Function.update Y i x) p=eval (Function.update Y i 0) p := by + have hnd := (polynomialSlice_natDegree i Y p).trans hd + have he := Polynomial.eq_C_of_natDegree_eq_zero (Nat.eq_zero_of_le_zero hnd) + simp only [← eval_polynomialSlice] + rw [he] + simp only [Polynomial.eval_C] + +end PolynomialVacuumAlgebra + +end OAI diff --git a/lean/OAI/Combinatorics/PolynomialVacuum/Algebra/BitRigidity.lean b/lean/OAI/Combinatorics/PolynomialVacuum/Algebra/BitRigidity.lean new file mode 100644 index 0000000000000000000000000000000000000000..54ab5f41a38c4fa1f131699a69cb6069206e8df8 --- /dev/null +++ b/lean/OAI/Combinatorics/PolynomialVacuum/Algebra/BitRigidity.lean @@ -0,0 +1,74 @@ +import OAI.Combinatorics.PolynomialVacuum.Algebra.BitRigidityTarget +import OAI.Combinatorics.PolynomialVacuum.Algebra.TripleBitRigidity + +namespace OAI + +namespace PolynomialVacuumAlgebra +open Classical + +theorem Pzero_mulVec_eq_zero (v : Pair → ℂ) (h : ∑ ab : Pair, cup ab*v ab=0) : + Pzero.mulVec v=0 := by + ext ab + simp only [Matrix.mulVec,dotProduct,Pzero,div_eq_mul_inv] + have he : (∑ cd : Pair, -cup ab*cup cd*nZero⁻¹*v cd)= + (-cup ab*nZero⁻¹)*(∑ cd : Pair, cup cd*v cd) := by + rw [Finset.mul_sum] + apply Finset.sum_congr rfl + intro cd _; ring + rw [he,h,mul_zero] + rfl + +theorem bitSwap_inverse : (Pone-zeta⁻¹ • Ptwo)*bitSwap=1-Pzero := by + have hz : zeta≠0 := pow_ne_zero _ (pow_ne_zero _ q_ne_zero) + unfold bitSwap + rw [sub_mul,mul_sub,mul_sub,Matrix.mul_smul,Matrix.smul_mul, + Matrix.smul_mul,Matrix.mul_smul,smul_smul,Pone_idempotent,Pone_Ptwo, + Ptwo_Pone,Ptwo_idempotent,smul_zero,smul_zero,sub_zero,inv_mul_cancel₀ hz,one_smul] + rw [Ptwo] + abel + +theorem bitSwap_kernel (v : Pair → ℂ) (hcup : ∑ ab : Pair, cup ab*v ab=0) + (h : bitSwap.mulVec v=0) : v=0 := by + have hp := Pzero_mulVec_eq_zero v hcup + have hm := congrArg (Matrix.mulVec (Pone-zeta⁻¹ • Ptwo)) h + rw [Matrix.mulVec_mulVec,bitSwap_inverse,Matrix.sub_mulVec,Matrix.one_mulVec,hp] at hm + simpa using hm + + + +theorem bit_tensor_rigidity (W : BitTensorFamily) (hW : BitTensorEquations W) : W=0 := by + rcases hW with ⟨hs,hfirst,hlast,hcup1,hcup2,hmove⟩ + have hequal1 (i k : Bool) : ∀ a b c, W i i k a b c=0 := by + apply triple_bit_first_equal i k (W i i k) (hs i i k) (hfirst i k) + · intro h a; subst k; exact hlast i i a + · exact hcup2 i i k + have hequal2 (i k : Bool) : ∀ a b c, W i k k a b c=0 := by + apply triple_bit_last_equal k i (W i k k) (hs i k k) (hlast i k) + · intro h c; subst i; exact hfirst k k c + · exact hcup1 i k k + have halternating1 (a b c : Spin) : W false true false a b c=0 := by + have h := congrFun (hmove false a) (b,c) + simp only [hequal1] at h + change bitSwap.mulVec 0 (b,c)=W false true false a b c at h + simpa using h.symm + have halternating2 (a b c : Spin) : W true false true a b c=0 := by + have h := hmove true a + have hz : (fun bc : Pair => W true true false a bc.1 bc.2)=0 := by + funext bc; exact hequal1 true false _ _ _ + rw [hz] at h + exact congrFun (bitSwap_kernel _ (hcup2 true false true a) h) (b,c) + funext i j k a b c + change W i j k a b c=0 + cases i <;> cases j <;> cases k + · exact hequal1 _ _ _ _ _ + · exact hequal1 _ _ _ _ _ + · exact halternating1 _ _ _ + · exact hequal2 _ _ _ _ _ + · exact hequal2 _ _ _ _ _ + · exact halternating2 _ _ _ + · exact hequal1 _ _ _ _ _ + · exact hequal1 _ _ _ _ _ + +end PolynomialVacuumAlgebra + +end OAI diff --git a/lean/OAI/Combinatorics/PolynomialVacuum/Algebra/BitRigidityTarget.lean b/lean/OAI/Combinatorics/PolynomialVacuum/Algebra/BitRigidityTarget.lean new file mode 100644 index 0000000000000000000000000000000000000000..a8ed1114088d965ec2cefb60cf10aee7fb9dc0a9 --- /dev/null +++ b/lean/OAI/Combinatorics/PolynomialVacuum/Algebra/BitRigidityTarget.lean @@ -0,0 +1,23 @@ +import OAI.Combinatorics.PolynomialVacuum.Algebra.PairImage + +namespace OAI + +namespace PolynomialVacuumAlgebra + +abbrev BitTensorFamily := Bool → Bool → Bool → Spin → Spin → Spin → ℂ + +noncomputable def bitSwap : Matrix Pair Pair ℂ := Pone-zeta • Ptwo + + + +def BitTensorEquations (W : BitTensorFamily) : Prop := + (∀ i j k a b c, ¬(allowedSpin i a ∧ allowedSpin j b ∧ allowedSpin k c) → W i j k a b c=0) ∧ + (∀ i k c, Pone.mulVec (fun ab => W i i k ab.1 ab.2 c)=fun ab => W i i k ab.1 ab.2 c) ∧ + (∀ i k a, Pone.mulVec (fun bc => W i k k a bc.1 bc.2)=fun bc => W i k k a bc.1 bc.2) ∧ + (∀ i j k c, ∑ ab : Pair, cup ab*W i j k ab.1 ab.2 c=0) ∧ + (∀ i j k a, ∑ bc : Pair, cup bc*W i j k a bc.1 bc.2=0) ∧ + (∀ i a, bitSwap.mulVec (fun bc => W i false true a bc.1 bc.2)=fun bc => W i true false a bc.1 bc.2) + +end PolynomialVacuumAlgebra + +end OAI diff --git a/lean/OAI/Combinatorics/PolynomialVacuum/Algebra/BraidEndomorphisms.lean b/lean/OAI/Combinatorics/PolynomialVacuum/Algebra/BraidEndomorphisms.lean new file mode 100644 index 0000000000000000000000000000000000000000..52d7f91f7812108911a7a27b84edeac632f19ee0 --- /dev/null +++ b/lean/OAI/Combinatorics/PolynomialVacuum/Algebra/BraidEndomorphisms.lean @@ -0,0 +1,82 @@ +import OAI.Combinatorics.PolynomialVacuum.Algebra.TensorYangBaxter + +namespace OAI + +namespace PolynomialVacuumAlgebra +open Classical + +theorem Pzero_transpose : Pzero.transpose=Pzero := by + ext a b; simp only [Pzero,Matrix.transpose_apply]; ring + +theorem Pone_transpose : Pone.transpose=Pone := by + ext a b; simp only [Pone,Matrix.transpose_apply] + congr 1 + apply Finset.sum_congr rfl + intro h _; ring + +theorem Ptwo_transpose : Ptwo.transpose=Ptwo := by + simp [Ptwo,Matrix.transpose_sub,Pone_transpose,Pzero_transpose] + +theorem numerator_transpose (x y : ℂ) : (exchangeNumerator x y).transpose=exchangeNumerator x y := by + simp [exchangeNumerator,Matrix.transpose_add,Matrix.transpose_smul, + Pzero_transpose,Pone_transpose,Ptwo_transpose] + +theorem matrix12_transpose (A : Matrix Pair Pair ℂ) : (matrix12 A).transpose=matrix12 A.transpose := by + ext ⟨a,b,c⟩ ⟨d,e,f⟩ + simp [matrix12,Matrix.transpose_apply,eq_comm] + +theorem matrix23_transpose (A : Matrix Pair Pair ℂ) : (matrix23 A).transpose=matrix23 A.transpose := by + ext ⟨a,b,c⟩ ⟨d,e,f⟩ + simp [matrix23,Matrix.transpose_apply,eq_comm] + +theorem matrix_yang_baxter_reverse (x y z : ℂ) : + matrix12 (exchangeNumerator y z) * matrix23 (exchangeNumerator x z) * + matrix12 (exchangeNumerator x y) = + matrix23 (exchangeNumerator x y) * matrix12 (exchangeNumerator x z) * + matrix23 (exchangeNumerator y z) := by + have h := congrArg Matrix.transpose (matrix_yang_baxter x y z) + simpa only [Matrix.transpose_mul,matrix12_transpose,matrix23_transpose, + numerator_transpose,Matrix.mul_assoc] using h + +theorem tensor_yang_baxter_reverse {I : Type*} [DecidableEq I] {i j k : I} + (hij : i≠j) (hik : i≠k) (hjk : j≠k) (x y z : ℂ) (W : SpinTensor I ℂ) : + pairAction i j (exchangeNumerator y z) + (pairAction j k (exchangeNumerator x z) (pairAction i j (exchangeNumerator x y) W)) = + pairAction j k (exchangeNumerator x y) + (pairAction i j (exchangeNumerator x z) (pairAction j k (exchangeNumerator y z) W)) := by + rw [← tripleAction_matrix12 hik hjk, ← tripleAction_matrix23 i j k, + ← tripleAction_matrix12 hik hjk, ← tripleAction_matrix23 i j k, + ← tripleAction_matrix12 hik hjk, ← tripleAction_matrix23 i j k] + simp only [tripleAction_mul hij hik hjk,← Matrix.mul_assoc,matrix_yang_baxter_reverse] + +noncomputable def pairLinear {I : Type*} [DecidableEq I] (i j : I) (A : Matrix Pair Pair ℂ) : + Module.End ℂ (SpinTensor I ℂ) where + toFun := pairAction i j A + map_add' W V := by + funext s + simp [pairAction,mul_add,Finset.sum_add_distrib] + map_smul' c W := by + funext s + simp only [pairAction,Pi.smul_apply,smul_eq_mul,Finset.mul_sum,RingHom.id_apply] + apply Finset.sum_congr rfl + intro ab _; ring + +noncomputable def siteR (i : ℕ) (x y : ℂ) : Module.End ℂ (SpinTensor ℕ ℂ) := + pairLinear i (i+1) (exchangeNumerator x y) + +theorem siteR_far_comm {i j : ℕ} (h : i + 1 < j ∨ j + 1 < i) (x y u v : ℂ) : + siteR i x y*siteR j u v=siteR j u v*siteR i x y := by + ext W s + exact congrFun (pairAction_comm (by omega : i≠j) (by omega : i≠j+1) + (by omega : i+1≠j) (by omega : i+1≠j+1) _ _ W) s + +theorem siteR_yang_baxter (i : ℕ) (x y z : ℂ) : + siteR i y z*siteR (i+1) x z*siteR i x y = + siteR (i+1) x y*siteR i x z*siteR (i+1) y z := by + ext W s + exact congrFun (tensor_yang_baxter_reverse (by omega : i≠i+1) (by omega : i≠i+1+1) + (by omega : i+1≠i+1+1) x y z W) s + +end PolynomialVacuumAlgebra + +end OAI diff --git a/lean/OAI/Combinatorics/PolynomialVacuum/Algebra/BraidTrain.lean b/lean/OAI/Combinatorics/PolynomialVacuum/Algebra/BraidTrain.lean new file mode 100644 index 0000000000000000000000000000000000000000..41323736b0f964408c1cee90190798609ce1df78 --- /dev/null +++ b/lean/OAI/Combinatorics/PolynomialVacuum/Algebra/BraidTrain.lean @@ -0,0 +1,78 @@ +import OAI.Combinatorics.PolynomialVacuum.Algebra.BraidEndomorphisms + +namespace OAI + +namespace PolynomialVacuumAlgebra +open Classical + +noncomputable def braidTrain (c : ℂ) (X : ℕ → ℂ) (k : ℕ) : + ℕ → Module.End ℂ (SpinTensor ℕ ℂ) + | 0 => 1 + | m+1 => braidTrain c X (k+1) m * siteR k c (X k) + +def swapSite {α : Type*} (j : ℕ) (X : ℕ → α) : ℕ → α := X ∘ Equiv.swap j (j+1) + +@[simp] theorem swapSite_left {α : Type*} (j : ℕ) (X : ℕ → α) : swapSite j X j=X (j+1) := by + simp [swapSite] +@[simp] theorem swapSite_right {α : Type*} (j : ℕ) (X : ℕ → α) : swapSite j X (j+1)=X j := by + simp [swapSite] +theorem swapSite_other {α : Type*} {i j : ℕ} (hij : i≠j) (hij' : i≠j+1) (X : ℕ → α) : + swapSite j X i=X i := by simp [swapSite,Equiv.swap_apply_of_ne_of_ne hij hij'] + +theorem braidTrain_congr (c : ℂ) {X Y : ℕ → ℂ} (k m : ℕ) + (h : ∀ i, k ≤ i → i < k+m → X i=Y i) : braidTrain c X k m=braidTrain c Y k m := by + induction m generalizing k with + | zero => rfl + | succ m ih => + simp only [braidTrain] + rw [ih (k+1) (fun i hi hi' => h i (by omega) (by omega)),h k (by omega) (by omega)] + +theorem braidTrain_far_left (c : ℂ) (X : ℕ → ℂ) (j k m : ℕ) (hjk : j+1 < k) (x y : ℂ) : + siteR j x y*braidTrain c X k m=braidTrain c X k m*siteR j x y := by + induction m generalizing k with + | zero => simp [braidTrain] + | succ m ih => + simp only [braidTrain] + rw [← mul_assoc,ih (k+1) (by omega),mul_assoc, + siteR_far_comm (Or.inl hjk),← mul_assoc] + + + +theorem braidTrain_spectator_swap (c : ℂ) (X : ℕ → ℂ) (k d m : ℕ) : + siteR (k+d) (X (k+d)) (X (k+d+1)) * braidTrain c X k (d+(m+2)) = + braidTrain c (swapSite (k+d) X) k (d+(m+2)) * + siteR (k+d+1) (X (k+d)) (X (k+d+1)) := by + induction d generalizing k with + | zero => + simp only [Nat.add_zero,Nat.zero_add] + have hc := braidTrain_far_left c X k (k+1+1) m (by omega) (X k) (X (k+1)) + have ht : braidTrain c (swapSite k X) (k+1+1) m=braidTrain c X (k+1+1) m := by + apply braidTrain_congr + intro i hi hi' + exact swapSite_other (by omega) (by omega) X + simp only [braidTrain,swapSite_left,swapSite_right,ht] + calc + siteR k (X k) (X (k+1)) * + (braidTrain c X (k+1+1) m * siteR (k+1) c (X (k+1)) * siteR k c (X k)) = + braidTrain c X (k+1+1) m * + (siteR k (X k) (X (k+1))*siteR (k+1) c (X (k+1))*siteR k c (X k)) := by + rw [← mul_assoc,← mul_assoc,hc]; simp only [mul_assoc] + _ = _ := by rw [siteR_yang_baxter]; simp only [mul_assoc] + | succ d ih => + have hp : k+(d+1)=(k+1)+d := by omega + have hl : (d+1)+(m+2)=(d+(m+2))+1 := by omega + have ho : swapSite (k+(d+1)) X k=X k := swapSite_other (by omega) (by omega) X + rw [hl,braidTrain,braidTrain] + simp only [ho] + calc + siteR (k+(d+1)) (X (k+(d+1))) (X (k+(d+1)+1)) * + (braidTrain c X (k+1) (d+(m+2))*siteR k c (X k)) = + (braidTrain c (swapSite (k+(d+1)) X) (k+1) (d+(m+2))* + siteR (k+(d+1)+1) (X (k+(d+1))) (X (k+(d+1)+1)))*siteR k c (X k) := by + rw [← mul_assoc,hp,ih (k+1)] + _ = _ := by + rw [mul_assoc,siteR_far_comm (Or.inr (by omega)),← mul_assoc] + +end PolynomialVacuumAlgebra + +end OAI diff --git a/lean/OAI/Combinatorics/PolynomialVacuum/Algebra/Candidate.lean b/lean/OAI/Combinatorics/PolynomialVacuum/Algebra/Candidate.lean new file mode 100644 index 0000000000000000000000000000000000000000..a1367fe0ee4048174d04114c43ae1ff564609cf5 --- /dev/null +++ b/lean/OAI/Combinatorics/PolynomialVacuum/Algebra/Candidate.lean @@ -0,0 +1,73 @@ +import OAI.Combinatorics.PolynomialVacuum.Algebra.PrescriptionDegree +import OAI.Combinatorics.PolynomialVacuum.Algebra.RegularInterpolation + +namespace OAI + +namespace PolynomialVacuumAlgebra +open MvPolynomial Classical PolynomialVacuumInterpolation + +noncomputable def dividedCupPrescription {n : ℕ} (ψ : State n) (i : Fin (n+1)) + (s : Fin (n+2) → Spin) : MvPolynomial (Fin (n+1)) ℂ := + C (1+T)*leftFusionFactors i*transportCup i (rightSpectators i) (initialCup ψ i) s + +theorem cupPrescription_factor {n : ℕ} (ψ : State n) (i : Fin (n+1)) + (s : Fin (n+2) → Spin) : cupPrescription ψ i s=X i*dividedCupPrescription ψ i s := by + unfold cupPrescription dividedCupPrescription + ring + +def CollisionCompatible {m : ℕ} (V : Fin m → MvPolynomial (Fin m) ℂ) : Prop := + ∀ i j, mergeVariable i j (V i)=mergeVariable i j (V j) + +noncomputable def canonicalInterpolant {m : ℕ} (V : Fin m → MvPolynomial (Fin m) ℂ) : + Polynomial (MvPolynomial (Fin m) ℂ) := + if h : CollisionCompatible V then + (regular_lagrange_exists Finset.univ V (fun i _ j _ => h i j)).choose + else 0 + +theorem canonicalInterpolant_degree {m : ℕ} (V : Fin m → MvPolynomial (Fin m) ℂ) : + (canonicalInterpolant V).degree < (m : WithBot ℕ) := by + unfold canonicalInterpolant + split_ifs with h + · simpa using (regular_lagrange_exists Finset.univ V (fun i _ j _ => h i j)).choose_spec.1 + · simp + +theorem canonicalInterpolant_eval {m : ℕ} (V : Fin m → MvPolynomial (Fin m) ℂ) + (h : CollisionCompatible V) (i : Fin m) : (canonicalInterpolant V).eval (X i)=V i := by + unfold canonicalInterpolant + rw [dite_eq_left h] + exact (regular_lagrange_exists Finset.univ V (fun i _ j _ => h i j)).choose_spec.2 i (Finset.mem_univ _) + + + +noncomputable def reinsertLast {m : ℕ} (p : Polynomial (MvPolynomial (Fin m) ℂ)) : + MvPolynomial (Fin (m+1)) ℂ := + p.eval₂ (rename Fin.castSucc).toRingHom (C T⁻¹*X (Fin.last m)) + +noncomputable def interpolateState {n : ℕ} (ψ : State n) (χ : State (n+1)) : State (n+2) := + fun s => + let V := fun i => cupPrescription ψ i s + let W := fun i => dividedCupPrescription ψ i s + let z : MvPolynomial (Fin (n+2)) ℂ := C T⁻¹*X (Fin.last (n+1)) + if s (Fin.last (n+1))=Spin.plus then reinsertLast (canonicalInterpolant V) + else z*reinsertLast (canonicalInterpolant W) + + if s (Fin.last (n+1))=Spin.zero then + (∏ i : Fin (n+1), (X i.castSucc-z))*rename Fin.castSucc (χ (s ∘ Fin.castSucc)) + else 0 + +noncomputable def vacuumCandidate : Family + | 0 => fun _ => 1 + | 1 => fun s => if s 0=Spin.zero then 1 else 0 + | n+2 => interpolateState (vacuumCandidate n) (vacuumCandidate (n+1)) + + + +def CandidateCollisionObligation : Prop := + ∀ n (s : Fin (n+2) → Spin), + CollisionCompatible (fun i => cupPrescription (vacuumCandidate n) i s) + + +def CandidateVacuumObligation : Prop := IsPolynomialVacuum vacuumCandidate + +end PolynomialVacuumAlgebra + +end OAI diff --git a/lean/OAI/Combinatorics/PolynomialVacuum/Algebra/CandidateEndpoints.lean b/lean/OAI/Combinatorics/PolynomialVacuum/Algebra/CandidateEndpoints.lean new file mode 100644 index 0000000000000000000000000000000000000000..6e48d9da942c4b560b597de0c8d22527433235c6 --- /dev/null +++ b/lean/OAI/Combinatorics/PolynomialVacuum/Algebra/CandidateEndpoints.lean @@ -0,0 +1,54 @@ +import OAI.Combinatorics.PolynomialVacuum.Algebra.Candidate + +namespace OAI + +namespace PolynomialVacuumAlgebra +open MvPolynomial Classical + +theorem interpolateState_minus_zero {n : ℕ} (ψ : State n) (χ : State (n+1)) + (s : Fin (n+2) → Spin) (Xv : Fin (n+2) → ℂ) + (hs : s (Fin.last (n+1))=Spin.minus) (hz : Xv (Fin.last (n+1))=0) : + eval Xv (interpolateState ψ χ s)=0 := by + simp [interpolateState,hs,hz] + +theorem interpolateState_zero_reduction {n : ℕ} (ψ : State n) (χ : State (n+1)) + (s : Fin (n+2) → Spin) (Xv : Fin (n+2) → ℂ) + (hs : s (Fin.last (n+1))=Spin.zero) (hz : Xv (Fin.last (n+1))=0) : + eval Xv (interpolateState ψ χ s)= + (∏ j : Fin (n+1), Xv j.castSucc)*eval (Xv ∘ Fin.castSucc) (χ (s ∘ Fin.castSucc)) := by + simp [interpolateState,hs,hz,eval_rename] + +theorem vacuumCandidate_zero_reduction (n : ℕ) + (s : Fin (n+1) → Spin) (Xv : Fin (n+1) → ℂ) + (hs : s (Fin.last n)=Spin.zero) (hz : Xv (Fin.last n)=0) : + eval Xv (vacuumCandidate (n+1) s)= + (∏ j : Fin n, Xv j.castSucc)*eval (Xv ∘ Fin.castSucc) (vacuumCandidate n (s ∘ Fin.castSucc)) := by + cases n with + | zero => simpa [vacuumCandidate] using hs + | succ n => exact interpolateState_zero_reduction _ _ _ _ hs hz + +theorem degreeOf_rename_last {m : ℕ} (p : MvPolynomial (Fin m) ℂ) : + (rename Fin.castSucc p).degreeOf (Fin.last m)=0 := by + by_contra h + obtain ⟨i,hi,he⟩ := mem_vars_rename Fin.castSucc p (mem_vars_iff_degreeOf_ne_zero.mpr h) + exact Fin.castSucc_ne_last i he + +theorem reinsertLast_degree {m : ℕ} (p : Polynomial (MvPolynomial (Fin m) ℂ)) : + (reinsertLast p).degreeOf (Fin.last m) ≤ p.natDegree := by + unfold reinsertLast + rw [Polynomial.eval₂_eq_sum,Polynomial.sum_def] + apply (degreeOf_sum_le _ _ _).trans + apply Finset.sup_le + intro i hi + apply (degreeOf_mul_le _ _ _).trans + change (rename Fin.castSucc (p.coeff i)).degreeOf (Fin.last m) + + ((C T⁻¹*X (Fin.last m))^i : MvPolynomial (Fin (m+1)) ℂ).degreeOf (Fin.last m) ≤ p.natDegree + rw [degreeOf_rename_last,zero_add] + apply (degreeOf_pow_le _ _ _).trans + have hz : (C T⁻¹*X (Fin.last m) : MvPolynomial (Fin (m+1)) ℂ).degreeOf (Fin.last m) ≤ 1 := by + exact (degreeOf_C_mul_le _ _ _).trans (by simp) + exact (Nat.mul_le_mul_left i hz).trans (by simpa using Polynomial.le_natDegree_of_mem_supp i hi) + +end PolynomialVacuumAlgebra + +end OAI diff --git a/lean/OAI/Combinatorics/PolynomialVacuum/Algebra/ChargeCombinatorics.lean b/lean/OAI/Combinatorics/PolynomialVacuum/Algebra/ChargeCombinatorics.lean new file mode 100644 index 0000000000000000000000000000000000000000..d86e8690046368796d9c9b7f741c96536b16daf1 --- /dev/null +++ b/lean/OAI/Combinatorics/PolynomialVacuum/Algebra/ChargeCombinatorics.lean @@ -0,0 +1,57 @@ +import OAI.Combinatorics.PolynomialVacuum.Algebra.FullCyclicity + +namespace OAI + +namespace PolynomialVacuumAlgebra +open Classical + +def natCharge (N : ℕ) (s : ℕ → Spin) : ℤ := ∑ j ∈ Finset.range N, charge (s j) + +theorem natCharge_removePair (n i : ℕ) (hi : i≤n) (s : ℕ → Spin) : + natCharge (n+2) s=charge (s i)+charge (s (i+1))+natCharge n (skipTwo i s) := by + have hn : n=i+(n-i) := by omega + have hN : n+2=(i+2)+(n-i) := by omega + have hr : ∑ j ∈ Finset.range i, charge (skipTwo i s j)=∑ j ∈ Finset.range i, charge (s j) := by + apply Finset.sum_congr rfl + intro j hj; simp [skipTwo,Finset.mem_range.mp hj] + have ht : ∑ j ∈ Finset.range (n-i), charge (skipTwo i s (i+j))= + ∑ j ∈ Finset.range (n-i), charge (s (i+2+j)) := by + apply Finset.sum_congr rfl + intro j hj + have hjj : ¬ i + j < i := by omega + simp only [skipTwo,ite_eq_right hjj] + congr 2 + omega + unfold natCharge + conv_lhs => rw [hN,Finset.sum_range_add,Finset.sum_range_succ,Finset.sum_range_succ] + conv_rhs => arg 2; rw [hn,Finset.sum_range_add] + rw [hr,ht] + ring + +theorem skipTwo_replacePair (i : ℕ) (s : ℕ → Spin) (ab : Pair) : + skipTwo i (replacePair s i (i+1) ab)=skipTwo i s := by + funext k + unfold skipTwo + split_ifs with h + · exact replacePair_other s (by omega) (by omega) ab + · exact replacePair_other s (by omega) (by omega) ab + +theorem natCharge_replacePair {N i : ℕ} (hi : i+1 cases b <;> cases c <;> cases d <;> + simp_all [charge,exchangeNumerator_eq_table,exchangeTable] + +end PolynomialVacuumAlgebra + +end OAI diff --git a/lean/OAI/Combinatorics/PolynomialVacuum/Algebra/ChargeStep.lean b/lean/OAI/Combinatorics/PolynomialVacuum/Algebra/ChargeStep.lean new file mode 100644 index 0000000000000000000000000000000000000000..6027872804313075216c4cade3b790fd1a59bb6c --- /dev/null +++ b/lean/OAI/Combinatorics/PolynomialVacuum/Algebra/ChargeStep.lean @@ -0,0 +1,104 @@ +import OAI.Combinatorics.PolynomialVacuum.Algebra.ChargeCombinatorics + +namespace OAI + +namespace PolynomialVacuumAlgebra +open MvPolynomial Classical + +def ChargeZero {N : ℕ} (ψ : State N) : Prop := + ∀ s, (∑ j, charge (s j))≠0 → ψ s=0 + +@[simp] theorem natCharge_eq_fin (N : ℕ) (s : ℕ → Spin) : + natCharge N s=∑ j : Fin N, charge (s j.val) := by + exact (Fin.sum_univ_eq_sum_range (fun j => charge (s j)) N).symm + +noncomputable def chargeSector {N : ℕ} (ψ : State N) : NatPolyTensor := + fun s => if natCharge N s≠0 then coordinatePolynomial ψ s else 0 + +@[simp] theorem eval_chargeSector {N : ℕ} (ψ : State N) (X : ℕ → ℂ) (s : ℕ → Spin) : + evalNatPolyTensor (chargeSector ψ) X s=if natCharge N s≠0 then liftState ψ X s else 0 := by + simp only [evalNatPolyTensor,chargeSector]; split_ifs <;> simp only [eval_coordinatePolynomial,map_zero] + +theorem chargeSector_exchange {N : ℕ} (ψ : State N) + (hex : LowerExchange (liftState ψ) N) : + LowerExchange (evalNatPolyTensor (chargeSector ψ)) N := by + intro j hj X + funext s + change (∑ ab : Pair, exchangeNumerator (X j) (X (j+1)) (s j,s (j+1)) ab * + evalNatPolyTensor (chargeSector ψ) X (replacePair s j (j+1) ab)) = + exchangeDenominator (X j) (X (j+1)) * evalNatPolyTensor (chargeSector ψ) (swapSite j X) s + have hterm (ab : Pair) : exchangeNumerator (X j) (X (j+1)) (s j,s (j+1)) ab * + evalNatPolyTensor (chargeSector ψ) X (replacePair s j (j+1) ab) = + if natCharge N s≠0 then exchangeNumerator (X j) (X (j+1)) (s j,s (j+1)) ab * + liftState ψ X (replacePair s j (j+1) ab) else 0 := by + by_cases hab : charge (s j)+charge (s (j+1))=charge ab.1+charge ab.2 + · have hc : natCharge N (replacePair s j (j+1) ab)=natCharge N s := by + rw [natCharge_replacePair hj]; omega + simp only [eval_chargeSector,hc]; split_ifs <;> simp + · rw [exchange_charge_conservation _ _ _ _ hab] + split_ifs <;> simp + simp only [hterm] + rw [eval_chargeSector] + split_ifs with hs + · exact congrFun (hex j hj X) s + · simp + +theorem liftState_charge_zero {N : ℕ} (ψ : State N) (h : ChargeZero ψ) + (X : ℕ → ℂ) (s : ℕ → Spin) (hs : natCharge N s≠0) : liftState ψ X s=0 := by + simp only [liftState,liftPolyTensor,h _ (by simpa only [natCharge_eq_fin] using hs),map_zero] + +theorem chargeSector_cup {n : ℕ} (Ψ : State (n+2)) (ψ : State n) + (hc : ∀ i≤n, CupAt (liftState Ψ) (liftState ψ) n i) (hz : ChargeZero ψ) + (i : ℕ) (hi : i≤n) (X : ℕ → ℂ) (hX : X (i+1)=T*X i) : + evalNatPolyTensor (chargeSector Ψ) X=0 := by + funext s + rw [eval_chargeSector] + split_ifs with hs + · have he := congrFun (hc i hi X hX) s + change liftState Ψ X s=naturalFusion n i X*(cup (s i,s (i+1))*liftState ψ (skipTwo i X) (skipTwo i s)) at he + rw [he] + by_cases hp : charge (s i)+charge (s (i+1))=0 + · have ht : natCharge n (skipTwo i s)≠0 := by rw [natCharge_removePair n i hi,hp,zero_add] at hs; exact hs + rw [liftState_charge_zero ψ hz _ _ ht,mul_zero,mul_zero] + rfl + · simp only [cup,hp,ite_false,mul_zero,zero_mul,Pi.zero_apply] + · rfl + +theorem chargeSector_degree {N b : ℕ} (Ψ : State N) (s : ℕ → Spin) (j : Fin N) + (h : (Ψ (fun a => s a.val)).degreeOf j≤b) : (chargeSector Ψ s).degreeOf j.val≤b := by + unfold chargeSector; split_ifs + · rw [coordinatePolynomial_degree]; exact h + · simp + +theorem chargeSector_minusZero {N : ℕ} (Ψ : State N) (hz : MinusZero Ψ) + (s : ℕ → Spin) (j : Fin N) (hs : s j.val=Spin.minus) : killSite j.val (chargeSector Ψ s)=0 := by + unfold chargeSector; split_ifs + · rw [coordinatePolynomial,killSite_rename_injective _ Fin.val_injective,hz _ _ hs,map_zero] + · exact map_zero _ + +theorem ChargeZero_of_sector {N : ℕ} (Ψ : State N) (h : ∀ s, chargeSector Ψ s=0) : ChargeZero Ψ := by + intro s hs + apply MvPolynomial.funext + intro X + have he := congrArg (eval (extendFinite 0 X)) (h (extendFinite Spin.zero s)) + have ht : natCharge N (extendFinite Spin.zero s)≠0 := by simpa only [natCharge_eq_fin,extendFinite_fin] using hs + simpa only [chargeSector,ite_eq_left ht,map_zero,eval_coordinatePolynomial,liftState,liftPolyTensor,extendFinite_fin] using he + +theorem chargeZero_of_cups {n : ℕ} (Ψ : State (n+4)) (ψ : State (n+2)) + (hex : LowerExchange (liftState Ψ) (n+4)) + (hc : ∀ i≤n+2, CupAt (liftState Ψ) (liftState ψ) (n+2) i) + (hh : ChargeZero ψ) (hd : ∀ s i, (Ψ s).degreeOf i≤n+3) + (hp : ∀ s i, s i=Spin.plus → (Ψ s).degreeOf i≤n+2) + (hz : MinusZero Ψ) : ChargeZero Ψ := by + apply ChargeZero_of_sector + apply cup_vanishing_rigidity (m:=n+3) (by omega) + · exact fun j hj => chargeSector_exchange Ψ hex j (by omega) + · intro i hi X hX; exact chargeSector_cup Ψ ψ hc hh i (by omega) X hX + · intro s j hj; exact chargeSector_degree Ψ s ⟨j,by omega⟩ (hd _ _) + · intro s j hj hs + exact (chargeSector_degree Ψ s ⟨j,by omega⟩ (hp _ ⟨j,by omega⟩ hs)).trans (by omega) + · intro s j hj hs; exact chargeSector_minusZero Ψ hz s ⟨j,by omega⟩ hs + +end PolynomialVacuumAlgebra + +end OAI diff --git a/lean/OAI/Combinatorics/PolynomialVacuum/Algebra/CupDivisibility.lean b/lean/OAI/Combinatorics/PolynomialVacuum/Algebra/CupDivisibility.lean new file mode 100644 index 0000000000000000000000000000000000000000..28f8ad7a0314127311084a92ada2d7a05f16b660 --- /dev/null +++ b/lean/OAI/Combinatorics/PolynomialVacuum/Algebra/CupDivisibility.lean @@ -0,0 +1,111 @@ +import OAI.Combinatorics.PolynomialVacuum.Algebra.CupSurface + +namespace OAI + +namespace PolynomialVacuumAlgebra +open MvPolynomial Classical + +noncomputable def cupFactor (i k : ℕ) : MvPolynomial ℕ ℂ := X k-C T*X i + +theorem substitution_factor_dvd (a b : ℕ) (p : MvPolynomial ℕ ℂ) : + cupFactor a b ∣ p-cupSpecialize a b p := by + induction p using MvPolynomial.induction_on with + | C c => simp + | add p r hp hr => + rw [map_add,show p+r-(cupSpecialize a b p+cupSpecialize a b r)= + (p-cupSpecialize a b p)+(r-cupSpecialize a b r) by ring] + exact dvd_add hp hr + | mul_X p i hp => + rw [map_mul] + have hx : cupFactor a b ∣ X i-cupSpecialize a b (X i) := by + by_cases hi : i=b + · subst i; simp [cupFactor] + · simp [hi] + rw [show p*X i-cupSpecialize a b p*cupSpecialize a b (X i)= + (p-cupSpecialize a b p)*X i+cupSpecialize a b p*(X i-cupSpecialize a b (X i)) by ring] + exact dvd_add (dvd_mul_of_dvd_left hp _) (dvd_mul_of_dvd_right hx _) + +theorem cupFactor_dvd_of_specialize_zero (a b : ℕ) (p : MvPolynomial ℕ ℂ) + (h : cupSpecialize a b p=0) : cupFactor a b ∣ p := by + simpa only [h,sub_zero] using substitution_factor_dvd a b p + +theorem X_sub_scaled_X_ne_zero {i j : ℕ} (hij : i≠j) (c : ℂ) : + (X i-C c*X j : MvPolynomial ℕ ℂ)≠0 := by + intro h + have he := congrArg (eval (fun k : ℕ => if k=i then (1:ℂ) else 0)) h + simp [Ne.symm hij] at he + +theorem cupFactor_ne_zero {a b : ℕ} (hab : a hia (X_injective he).symm)) + · simp only [ite_eq_right hk] + by_cases hi : i=b + · subst i + simp only [ite_true] + rw [← mul_assoc,← map_mul] + exact X_sub_scaled_X_ne_zero (by omega) (T*T) + · simp only [ite_eq_right hi] + exact X_sub_scaled_X_ne_zero (by omega) T + +theorem cupProduct_dvd (S : Finset (ℕ × ℕ)) + (hs : ∀ ab∈S, ab.1 simp + | @insert ab S hab ih => + have hab' := hs ab (Finset.mem_insert_self _ _) + obtain ⟨r,hr⟩ := ih (fun cd h => hs cd (Finset.mem_insert_of_mem h)) p + (fun cd h => hz cd (Finset.mem_insert_of_mem h)) + have hprod : cupSpecialize ab.1 ab.2 (∏ cd∈S, cupFactor cd.1 cd.2)≠0 := by + rw [map_prod] + apply Finset.prod_ne_zero_iff.mpr + intro cd hcd + apply cupSpecialize_cupFactor_ne_zero hab' (hs cd (Finset.mem_insert_of_mem hcd)) + intro he + have he' : cd=ab := Prod.ext (congrArg Prod.fst he) (congrArg Prod.snd he) + exact hab (he' ▸ hcd) + have hr0 : cupSpecialize ab.1 ab.2 r=0 := by + have hh := hz ab (Finset.mem_insert_self _ _) + rw [hr,map_mul] at hh + exact (mul_eq_zero.mp hh).resolve_left hprod + obtain ⟨u,hu⟩ := cupFactor_dvd_of_specialize_zero ab.1 ab.2 r hr0 + refine ⟨u,?_⟩ + rw [Finset.prod_insert hab,hr,hu] + ring + +noncomputable def cupPairs (m : ℕ) : Finset (ℕ × ℕ) := + ((Finset.range m) ×ˢ (Finset.range m)).filter (fun ab => ab.1 congr 1 <;> omega + +theorem cupAt_step_generic {Ψ ψ : NatSpectralTensor} {n i : ℕ} + (hΨ : LowerExchange Ψ (n+1)) (hi : i+2 < n+1) (hc : CupAt Ψ ψ n i) + (Y : ℕ → ℂ) (hY : Y (i+2)=T*Y (i+1)) + (hD : exchangeDenominator (Y (i+1)) (Y i)*exchangeDenominator (T*Y (i+1)) (Y i)≠0) : + Ψ Y=naturalFusion n (i+1) Y • cupLinear (i+1) (ψ (skipTwo (i+1) Y)) := by + let X := swapSite (i+1) (swapSite i Y) + have hx0 : X i=Y (i+1) := by simp [X,swapSite_other (by omega : i≠i+1) (by omega : i≠i+1+1),swapSite_left] + have hx1 : X (i+1)=T*Y (i+1) := by + simp only [X,swapSite_left,swapSite_other (by omega : i+1+1≠i) (by omega : i+1+1≠i+1)] + simpa only [show i+1+1=i+2 by omega] using hY + have hx2 : X (i+2)=Y i := by + simp only [X,show i+2=i+1+1 by omega,swapSite_right] + have hskip : skipTwo i X=skipTwo (i+1) Y := skipTwo_cup_slide i Y + have hf : naturalFusion n i X=naturalFusion n (i+1) Y := by + simp only [naturalFusion,hx0,hskip] + have he1 := hΨ (i+1) (by omega) X + have he2 := hΨ i (by omega) (swapSite (i+1) X) + have hback : swapSite i (swapSite (i+1) X)=Y := by simp only [X,swapSite_twice] + rw [hback] at he2 + have hd0 : swapSite (i+1) X i=Y (i+1) := by simpa only [swapSite_other (by omega : i≠i+1) (by omega : i≠i+1+1)] using hx0 + have hd1 : swapSite (i+1) X (i+1)=Y i := by simpa only [swapSite_left,show i+1+1=i+2 by omega] using hx2 + rw [hd0,hd1] at he2 + simp only [show i+1+1=i+2 by omega,hx1,hx2] at he1 + have he := congrArg (siteR i (Y (i+1)) (Y i)) he1 + rw [map_smul,he2,smul_smul] at he + rw [hc X (hx1.trans (congrArg (T*·) hx0.symm)),map_smul,map_smul,← Module.End.mul_apply, + ← Module.End.mul_apply,siteR_cup_slide] at he + simp only [LinearMap.smul_apply,hf,hskip,smul_smul] at he + have hs : (exchangeDenominator (Y (i+1)) (Y i)*exchangeDenominator (T*Y (i+1)) (Y i)) • Ψ Y= + (exchangeDenominator (Y (i+1)) (Y i)*exchangeDenominator (T*Y (i+1)) (Y i)) • + (naturalFusion n (i+1) Y • cupLinear (i+1) (ψ (skipTwo (i+1) Y))) := by + rw [smul_smul] + simpa only [mul_comm,mul_left_comm,mul_assoc] using he.symm + exact (smul_right_injective _ hD) hs + +end PolynomialVacuumAlgebra + +end OAI diff --git a/lean/OAI/Combinatorics/PolynomialVacuum/Algebra/CupPrescriptions.lean b/lean/OAI/Combinatorics/PolynomialVacuum/Algebra/CupPrescriptions.lean new file mode 100644 index 0000000000000000000000000000000000000000..1251e373e5805a85ec0b0bf9e7cae90440560d7c --- /dev/null +++ b/lean/OAI/Combinatorics/PolynomialVacuum/Algebra/CupPrescriptions.lean @@ -0,0 +1,124 @@ +import OAI.Combinatorics.PolynomialVacuum.Algebra.Table + +namespace OAI + +namespace PolynomialVacuumAlgebra +open MvPolynomial +open Classical + +noncomputable def polyExchangeNumerator {ι : Type*} (x y : MvPolynomial ι ℂ) + (a b : Pair) : MvPolynomial ι ℂ := + (C (t^2)*y-x)*(C T*x-y)*C (Pzero a b) + + (C T*y-x)*(C (t^2)*x-y)*C (Pone a b) + + (C (t^2)*y-x)*(C T*y-x)*C (Ptwo a b) + +@[simp] theorem eval_polyExchangeNumerator {ι : Type*} (X : ι → ℂ) + (x y : MvPolynomial ι ℂ) (a b : Pair) : + eval X (polyExchangeNumerator x y a b) = + exchangeNumerator (eval X x) (eval X y) a b := by + simp [polyExchangeNumerator,exchangeNumerator,Matrix.add_apply,Matrix.smul_apply] + +theorem polyExchangeNumerator_homogeneous {ι : Type*} {x y : MvPolynomial ι ℂ} + (hx : x.IsHomogeneous 1) (hy : y.IsHomogeneous 1) (a b : Pair) : + (polyExchangeNumerator x y a b).IsHomogeneous 2 := by + have h (u v : ℂ) : ((C u*y-x)*(C v*x-y)).IsHomogeneous 2 := + (hy.C_mul u |>.sub hx).mul (hx.C_mul v |>.sub hy) + have h' (u v : ℂ) : ((C u*y-x)*(C v*y-x)).IsHomogeneous 2 := + (hy.C_mul u |>.sub hx).mul (hy.C_mul v |>.sub hx) + unfold polyExchangeNumerator + apply IsHomogeneous.add + · apply IsHomogeneous.add + · simpa only [mul_comm] using (h (t^2) T).C_mul (Pzero a b) + · simpa only [mul_comm] using (h T (t^2)).C_mul (Pone a b) + · simpa only [mul_comm] using (h' (t^2) T).C_mul (Ptwo a b) + +abbrev PolynomialTensor (N : ℕ) (ι : Type*) := (Fin N → Spin) → MvPolynomial ι ℂ + +noncomputable def tensorExchange {N : ℕ} {ι : Type*} (i j : Fin N) + (x y : MvPolynomial ι ℂ) (W : PolynomialTensor N ι) : PolynomialTensor N ι := + fun s => ∑ ab : Pair, polyExchangeNumerator x y (s i,s j) ab * + W (Function.update (Function.update s i ab.1) j ab.2) + +theorem tensorExchange_mul {N : ℕ} {ι : Type*} (i j : Fin N) + (x y c : MvPolynomial ι ℂ) (W : PolynomialTensor N ι) : + tensorExchange i j x y (fun s => c*W s) = fun s => c*tensorExchange i j x y W s := by + funext s + simp only [tensorExchange,Finset.mul_sum] + apply Finset.sum_congr rfl + intro ab _ + ring + +theorem tensorExchange_homogeneous {N d : ℕ} {ι : Type*} (i j : Fin N) + {x y : MvPolynomial ι ℂ} (hx : x.IsHomogeneous 1) (hy : y.IsHomogeneous 1) + {W : PolynomialTensor N ι} (hW : ∀ s, (W s).IsHomogeneous d) (s : Fin N → Spin) : + (tensorExchange i j x y W s).IsHomogeneous (d+2) := by + apply IsHomogeneous.sum + intro ab _ + simpa only [Nat.add_comm] using (polyExchangeNumerator_homogeneous hx hy (s i,s j) ab).mul (hW _) + + +noncomputable def transportCup {n : ℕ} (i : Fin (n+1)) + (ks : List (Fin (n+1))) (W : PolynomialTensor (n+2) (Fin (n+1))) : + PolynomialTensor (n+2) (Fin (n+1)) := + ks.foldl (fun A k => tensorExchange (pairLeft k) (pairRight k) (C T*X i) (X k) A) W + +noncomputable def rightSpectators {n : ℕ} (i : Fin (n+1)) : List (Fin (n+1)) := + (List.finRange (n+1)).filter (fun k => i + C (cup (s (pairLeft i),s (pairRight i))) * + rename i.succAbove (ψ (s ∘ omitPair i)) + + + +noncomputable def leftFusionFactors {n : ℕ} (i : Fin (n+1)) : MvPolynomial (Fin (n+1)) ℂ := + ∏ k ∈ Finset.univ.filter (fun k => k < i), (X k-C (t^5)*X i)*(X k-C (t^6)*X i) + +noncomputable def cupPrescription {n : ℕ} (ψ : State n) (i : Fin (n+1)) : + PolynomialTensor (n+2) (Fin (n+1)) := fun s => + C (1+T)*X i*leftFusionFactors i * transportCup i (rightSpectators i) (initialCup ψ i) s + + + +theorem marked_variable_dvd_cupPrescription {n : ℕ} (ψ : State n) (i : Fin (n+1)) + (s : Fin (n+2) → Spin) : X i ∣ cupPrescription ψ i s := by + refine ⟨C (1+T)*leftFusionFactors i*transportCup i (rightSpectators i) (initialCup ψ i) s,?_⟩ + unfold cupPrescription + ring + +theorem transportCup_homogeneous {n d : ℕ} (i : Fin (n+1)) (ks : List (Fin (n+1))) + (W : PolynomialTensor (n+2) (Fin (n+1))) (hW : ∀ s, (W s).IsHomogeneous d) + (s : Fin (n+2) → Spin) : + (transportCup i ks W s).IsHomogeneous (d+2*ks.length) := by + induction ks generalizing W d with + | nil => simpa [transportCup] using hW s + | cons k ks ih => + have hj := ih (tensorExchange (pairLeft k) (pairRight k) (C T*X i) (X k) W) + (fun v => tensorExchange_homogeneous _ _ (isHomogeneous_C_mul_X T i) + (isHomogeneous_X _ _) hW v) + simpa [transportCup,Nat.mul_add,Nat.add_assoc,Nat.add_comm,Nat.add_left_comm] using hj + +theorem cupPrescription_homogeneous {n d : ℕ} (ψ : State n) + (hψ : ∀ s, (ψ s).IsHomogeneous d) (i : Fin (n+1)) (s : Fin (n+2) → Spin) : + (cupPrescription ψ i s).IsHomogeneous + (1+2*(Finset.univ.filter (fun k : Fin (n+1) => k < i)).card + d+2*(rightSpectators i).length) := by + have hinit (v) : (initialCup ψ i v).IsHomogeneous d := by + exact ((hψ _).rename_isHomogeneous).C_mul _ + have hleft : (leftFusionFactors i).IsHomogeneous + (2*(Finset.univ.filter (fun k : Fin (n+1) => k < i)).card) := by + unfold leftFusionFactors + rw [show 2*(Finset.univ.filter (fun k : Fin (n+1) => k < i)).card = + ∑ k ∈ Finset.univ.filter (fun k : Fin (n+1) => k < i), (2 : ℕ) by + simp [Nat.mul_comm]] + apply IsHomogeneous.prod + intro k hk + exact ((isHomogeneous_X _ k).sub (isHomogeneous_C_mul_X _ i)).mul + ((isHomogeneous_X _ k).sub (isHomogeneous_C_mul_X _ i)) + have h := ((isHomogeneous_C_mul_X (1+T) i).mul hleft).mul + (transportCup_homogeneous i (rightSpectators i) (initialCup ψ i) hinit s) + simpa only [cupPrescription,Nat.add_assoc] using h + +end PolynomialVacuumAlgebra + +end OAI diff --git a/lean/OAI/Combinatorics/PolynomialVacuum/Algebra/CupProductSwap.lean b/lean/OAI/Combinatorics/PolynomialVacuum/Algebra/CupProductSwap.lean new file mode 100644 index 0000000000000000000000000000000000000000..156359845e13dd4f63026a8bdc8539d9cf44336e --- /dev/null +++ b/lean/OAI/Combinatorics/PolynomialVacuum/Algebra/CupProductSwap.lean @@ -0,0 +1,71 @@ +import OAI.Combinatorics.PolynomialVacuum.Algebra.CupDivisibility +import OAI.Combinatorics.PolynomialVacuum.Algebra.ExchangeDiscrepancy + +namespace OAI + +namespace PolynomialVacuumAlgebra +open MvPolynomial Classical + +theorem adjacentSwap_lt {j i k : ℕ} (hik : i omega + +theorem adjacentSwap_bound {m j i : ℕ} (hj : j+1 < m) : + Equiv.swap j (j+1) i < m ↔ i < m := by + simp only [Equiv.swap_apply_def] + split_ifs <;> omega + +noncomputable def exceptCupVandermonde (m j : ℕ) : MvPolynomial ℕ ℂ := + ∏ ab∈(cupPairs m).erase (j,j+1), cupFactor ab.1 ab.2 + +theorem rename_exceptCupVandermonde {m j : ℕ} (hj : j+1 < m) : + rename (Equiv.swap j (j+1)) (exceptCupVandermonde m j)=exceptCupVandermonde m j := by + simp only [exceptCupVandermonde,map_prod] + apply Finset.prod_equiv (Equiv.prodCongr (Equiv.swap j (j+1)) (Equiv.swap j (j+1))) + · rintro ⟨a,b⟩ + simp only [Equiv.prodCongr_apply,Prod.map_apply,Finset.mem_erase,mem_cupPairs] + constructor + · intro ⟨hne,hab,hbm⟩ + refine ⟨?_,adjacentSwap_lt hab hne,(adjacentSwap_bound hj).mpr hbm⟩ + intro he + have ha := congrArg Prod.fst he + have hb := congrArg Prod.snd he + have ha' := congrArg (Equiv.swap j (j+1)) ha + have hb' := congrArg (Equiv.swap j (j+1)) hb + simp only [Equiv.swap_apply_self,Equiv.swap_apply_left,Equiv.swap_apply_right] at ha' hb' + omega + · intro ⟨hne,hab,hbm⟩ + have ht := adjacentSwap_lt hab hne + simp only [Equiv.swap_apply_self] at ht + refine ⟨?_,ht,(adjacentSwap_bound hj).mp hbm⟩ + intro he + have ha : a=j := congrArg Prod.fst he + have hb : b=j+1 := congrArg Prod.snd he + rw [ha,hb,Equiv.swap_apply_left,Equiv.swap_apply_right] at hab + omega + · rintro ⟨a,b⟩ hab + simp only [cupFactor,map_sub,map_mul,rename_X,rename_C,Equiv.prodCongr_apply,Prod.map_apply] + +theorem cupVandermonde_factor {m j : ℕ} (hj : j+1 < m) : + cupVandermonde m=cupFactor j (j+1)*exceptCupVandermonde m j := by + exact (Finset.mul_prod_erase _ _ ((mem_cupPairs _ _ _).mpr ⟨by omega,hj⟩)).symm + +theorem cupVandermonde_swap_polynomial {m j : ℕ} (hj : j+1 < m) : + cupFactor j (j+1)*rename (Equiv.swap j (j+1)) (cupVandermonde m)= + rename (Equiv.swap j (j+1)) (cupFactor j (j+1))*cupVandermonde m := by + rw [cupVandermonde_factor hj,map_mul,rename_exceptCupVandermonde hj] + ring + +theorem eval_cupVandermonde_swap {m j : ℕ} (hj : j+1 < m) (Y : ℕ → ℂ) : + (Y (j+1)-T*Y j)*eval (swapSite j Y) (cupVandermonde m)= + (Y j-T*Y (j+1))*eval Y (cupVandermonde m) := by + have he := congrArg (eval Y) (cupVandermonde_swap_polynomial hj) + simpa only [map_mul,cupFactor,map_sub,eval_X,eval_C,eval_rename,swapSite, + Function.comp_def,Equiv.swap_apply_left,Equiv.swap_apply_right] using he + +end PolynomialVacuumAlgebra + +end OAI diff --git a/lean/OAI/Combinatorics/PolynomialVacuum/Algebra/CupQuotientBounds.lean b/lean/OAI/Combinatorics/PolynomialVacuum/Algebra/CupQuotientBounds.lean new file mode 100644 index 0000000000000000000000000000000000000000..04d23e455238d7a743250bc175c6324d20ddd934 --- /dev/null +++ b/lean/OAI/Combinatorics/PolynomialVacuum/Algebra/CupQuotientBounds.lean @@ -0,0 +1,103 @@ +import OAI.Combinatorics.PolynomialVacuum.Algebra.CupDivisibility +import OAI.Combinatorics.PolynomialVacuum.Algebra.LagrangeDegree +import OAI.Combinatorics.PolynomialVacuum.Algebra.KillSite + +namespace OAI + +namespace PolynomialVacuumAlgebra +open MvPolynomial Classical + +theorem cupFactor_degree {a b : ℕ} (hab : a ab.1=j ∨ ab.2=j)).card=m-1 := by + have he : ((cupPairs m).filter (fun ab => ab.1=j ∨ ab.2=j)).card= + ((Finset.range m).erase j).card := by + apply Finset.card_bij (fun ab _ => if ab.1=j then ab.2 else ab.1) + · intro ab hab + obtain ⟨hab,hi⟩ := Finset.mem_filter.mp hab + have ht := (mem_cupPairs _ _ _).mp hab + simp only [Finset.mem_erase,Finset.mem_range] + split_ifs <;> rcases hi with hi|hi <;> omega + · intro ab hab cd hcd he + obtain ⟨hab,hi⟩ := Finset.mem_filter.mp hab + obtain ⟨hcd,hi'⟩ := Finset.mem_filter.mp hcd + have ht := (mem_cupPairs _ _ _).mp hab + have ht' := (mem_cupPairs _ _ _).mp hcd + apply Prod.ext <;> split_ifs at he <;> rcases hi with hi|hi <;> rcases hi' with hi'|hi' <;> omega + · intro k hk + obtain ⟨hkj,hk⟩ := Finset.mem_erase.mp hk + have hkm := Finset.mem_range.mp hk + by_cases h : k congr 1 <;> omega + +theorem skipTwo_insertOne_after {α : Type*} (j : ℕ) (c : α) (X : ℕ → α) : + skipTwo 0 (insertOne (j+2) c X)=insertOne j c (skipTwo 0 X) := by + funext k + simp only [skipTwo_zero_apply,insertOne] + split_ifs <;> congr 1 <;> omega + +theorem fusionProduct_insertLast (a c : ℂ) (X : ℕ → ℂ) (m : ℕ) : + fusionProduct a (insertOne m c X) (m+1)=fusionProduct a X m*fusionPair a c := by + simp only [fusionProduct,Finset.prod_range_succ,insertOne_self] + congr 1 + apply Finset.prod_congr rfl + intro k hk + simp only [insertOne,ite_eq_left (Finset.mem_range.mp hk)] + +theorem leftFusion_dropTwo (j : ℕ) (X : ℕ → ℂ) : + leftFusion (j+2) X=fusionPair (X (j+2)) (X 0)*fusionPair (X (j+2)) (X 1)* + leftFusion j (skipTwo 0 X) := by + simp only [leftFusion,skipTwo_zero_apply] + rw [show j+2=2+j by omega,Finset.prod_range_add] + simp only [Finset.prod_range_succ,Finset.range_zero,Finset.prod_empty,one_mul] + congr 1 + apply Finset.prod_congr rfl + intro k hk + rw [Nat.add_comm 2 k] + + + +theorem firstCup_scalar_compatibility (m j : ℕ) (hj : j ≤ m) (X : ℕ → ℂ) + (hX : X 1=T*X 0) : + ((1+T)*X (j+2)*leftFusion (j+2) X)*naturalFusion m 0 (skipOne (j+2) X)= + naturalFusion (m+2) 0 (insertOne (m+3) (T*X (j+2)) X)* + ((1+T)*skipTwo 0 X j*leftFusion j (skipTwo 0 X)) := by + have hx : skipOne (j+2) X 0=X 0 := by simp [skipOne] + have hy : insertOne (m+3) (T*X (j+2)) X 0=X 0 := by simp [insertOne] + have hs := fusionProduct_skipOne (X 0) (skipTwo 0 X) m j hj + have hf := fusionPair_four_point (X 0) (X (j+2)) + simp only [skipTwo_zero_apply] at hs + simp only [naturalFusion,hx,hy,skipTwo_skipOne_after,leftFusion_dropTwo,hX, + show m+3=(m+1)+2 by omega,skipTwo_insertOne_after,fusionProduct_insertLast, + skipTwo_zero_apply] + rw [← hs] + linear_combination (1+T)^2 * X 0 * X (j+2) * leftFusion j (skipTwo 0 X) * + fusionProduct (X 0) (skipOne j (skipTwo 0 X)) m * hf + +end PolynomialVacuumAlgebra + +end OAI diff --git a/lean/OAI/Combinatorics/PolynomialVacuum/Algebra/CupSlide.lean b/lean/OAI/Combinatorics/PolynomialVacuum/Algebra/CupSlide.lean new file mode 100644 index 0000000000000000000000000000000000000000..2243f6e3806bcc3eaa785eb34829362644f0e121 --- /dev/null +++ b/lean/OAI/Combinatorics/PolynomialVacuum/Algebra/CupSlide.lean @@ -0,0 +1,586 @@ +import OAI.Combinatorics.PolynomialVacuum.Algebra.Table + +namespace OAI + +namespace PolynomialVacuumAlgebra + +noncomputable def insertionTable : Pair → Spin → ℂ + | (.zero,.zero), .zero => 1 + | (.zero,.plus), .plus => (1/2:ℂ)-(1/2:ℂ)*q^2+(1/2:ℂ)*q^4-(1/2:ℂ)*q^6 + | (.zero,.minus), .minus => (1/2:ℂ)+(1/2:ℂ)*q^2-(1/2:ℂ)*q^4+(1/2:ℂ)*q^6 + | (.plus,.zero), .plus => (1/2:ℂ)+(1/2:ℂ)*q^2-(1/2:ℂ)*q^4+(1/2:ℂ)*q^6 + | (.plus,.minus), .zero => -(1/2:ℂ)*q+(1/2:ℂ)*q^3+(1/2:ℂ)*q^5-(1/2:ℂ)*q^7 + | (.minus,.zero), .minus => (1/2:ℂ)-(1/2:ℂ)*q^2+(1/2:ℂ)*q^4-(1/2:ℂ)*q^6 + | (.minus,.plus), .zero => (1/2:ℂ)*q-(1/2:ℂ)*q^3-(1/2:ℂ)*q^5+(1/2:ℂ)*q^7 + | _, _ => 0 + +theorem insertion_eq_table (a : Pair) (h : Spin) : insertion a h = insertionTable a h := by + rcases a with ⟨a,b⟩ + cases a <;> cases b <;> cases h <;> + norm_num [insertion,insertionTable,charge,zpow_neg,q_inv,q_four_inv,xStar_polynomial] + all_goals ring_nf + all_goals try simp only [q_pow_eight,q_pow_9,q_pow_10,q_pow_11,q_pow_12,q_pow_14] + all_goals ring + + +noncomputable def cupSlideLeft (x : ℂ) (a b c h : Spin) : ℂ := + ∑ i : Spin, ∑ j : Spin, ∑ k : Spin, + exchangeNumerator x 1 (a,b) (i,j) * + exchangeNumerator (T*x) 1 (j,c) (k,h) * cup (i,k) + +noncomputable def cupSlideRight (x : ℂ) (a b c h : Spin) : ℂ := + exchangeDenominator x 1 * exchangeDenominator (T*x) 1 * + (if a=h then cup (b,c) else 0) + +theorem cup_slide_entry_0_0 (x : ℂ) : + cupSlideLeft x .zero .zero .zero .zero = cupSlideRight x .zero .zero .zero .zero := by + norm_num [cupSlideLeft,cupSlideRight,sum_spin,exchangeNumerator_eq_table,exchangeTable, + exchangeDenominator,cup,charge,zpow_neg,q_five_inv,T,t] + all_goals ring_nf + all_goals try simp only [q_pow_eight,q_pow_10,q_pow_12,q_pow_14,q_pow_16,q_pow_18,q_pow_20,q_pow_22,q_pow_24,q_pow_26,q_pow_28,q_pow_32] + all_goals ring + +theorem cup_slide_entry_0_1 (x : ℂ) : + cupSlideLeft x .zero .zero .zero .plus = cupSlideRight x .zero .zero .zero .plus := by + norm_num [cupSlideLeft,cupSlideRight,sum_spin,exchangeNumerator_eq_table,exchangeTable, + exchangeDenominator,cup,charge,zpow_neg,q_five_inv,T,t] + +theorem cup_slide_entry_0_2 (x : ℂ) : + cupSlideLeft x .zero .zero .zero .minus = cupSlideRight x .zero .zero .zero .minus := by + norm_num [cupSlideLeft,cupSlideRight,sum_spin,exchangeNumerator_eq_table,exchangeTable, + exchangeDenominator,cup,charge,zpow_neg,q_five_inv,T,t] + +theorem cup_slide_entry_1_0 (x : ℂ) : + cupSlideLeft x .zero .zero .plus .zero = cupSlideRight x .zero .zero .plus .zero := by + norm_num [cupSlideLeft,cupSlideRight,sum_spin,exchangeNumerator_eq_table,exchangeTable, + exchangeDenominator,cup,charge,zpow_neg,q_five_inv,T,t] + +theorem cup_slide_entry_1_1 (x : ℂ) : + cupSlideLeft x .zero .zero .plus .plus = cupSlideRight x .zero .zero .plus .plus := by + norm_num [cupSlideLeft,cupSlideRight,sum_spin,exchangeNumerator_eq_table,exchangeTable, + exchangeDenominator,cup,charge,zpow_neg,q_five_inv,T,t] + all_goals ring_nf + all_goals try simp only [q_pow_eight,q_pow_10,q_pow_12,q_pow_14,q_pow_16,q_pow_18,q_pow_20] + all_goals ring + +theorem cup_slide_entry_1_2 (x : ℂ) : + cupSlideLeft x .zero .zero .plus .minus = cupSlideRight x .zero .zero .plus .minus := by + norm_num [cupSlideLeft,cupSlideRight,sum_spin,exchangeNumerator_eq_table,exchangeTable, + exchangeDenominator,cup,charge,zpow_neg,q_five_inv,T,t] + +theorem cup_slide_entry_2_0 (x : ℂ) : + cupSlideLeft x .zero .zero .minus .zero = cupSlideRight x .zero .zero .minus .zero := by + norm_num [cupSlideLeft,cupSlideRight,sum_spin,exchangeNumerator_eq_table,exchangeTable, + exchangeDenominator,cup,charge,zpow_neg,q_five_inv,T,t] + +theorem cup_slide_entry_2_1 (x : ℂ) : + cupSlideLeft x .zero .zero .minus .plus = cupSlideRight x .zero .zero .minus .plus := by + norm_num [cupSlideLeft,cupSlideRight,sum_spin,exchangeNumerator_eq_table,exchangeTable, + exchangeDenominator,cup,charge,zpow_neg,q_five_inv,T,t] + +theorem cup_slide_entry_2_2 (x : ℂ) : + cupSlideLeft x .zero .zero .minus .minus = cupSlideRight x .zero .zero .minus .minus := by + norm_num [cupSlideLeft,cupSlideRight,sum_spin,exchangeNumerator_eq_table,exchangeTable, + exchangeDenominator,cup,charge,zpow_neg,q_five_inv,T,t] + all_goals ring_nf + all_goals try simp only [q_pow_eight,q_pow_10,q_pow_12,q_pow_14,q_pow_16,q_pow_18,q_pow_20,q_pow_22,q_pow_24,q_pow_26] + all_goals ring + +theorem cup_slide_entry_3_0 (x : ℂ) : + cupSlideLeft x .zero .plus .zero .zero = cupSlideRight x .zero .plus .zero .zero := by + norm_num [cupSlideLeft,cupSlideRight,sum_spin,exchangeNumerator_eq_table,exchangeTable, + exchangeDenominator,cup,charge,zpow_neg,q_five_inv,T,t] + +theorem cup_slide_entry_3_1 (x : ℂ) : + cupSlideLeft x .zero .plus .zero .plus = cupSlideRight x .zero .plus .zero .plus := by + norm_num [cupSlideLeft,cupSlideRight,sum_spin,exchangeNumerator_eq_table,exchangeTable, + exchangeDenominator,cup,charge,zpow_neg,q_five_inv,T,t] + all_goals ring_nf + all_goals try simp only [q_pow_eight,q_pow_10,q_pow_12,q_pow_14,q_pow_16,q_pow_18,q_pow_20] + all_goals ring + +theorem cup_slide_entry_3_2 (x : ℂ) : + cupSlideLeft x .zero .plus .zero .minus = cupSlideRight x .zero .plus .zero .minus := by + norm_num [cupSlideLeft,cupSlideRight,sum_spin,exchangeNumerator_eq_table,exchangeTable, + exchangeDenominator,cup,charge,zpow_neg,q_five_inv,T,t] + +theorem cup_slide_entry_4_0 (x : ℂ) : + cupSlideLeft x .zero .plus .plus .zero = cupSlideRight x .zero .plus .plus .zero := by + norm_num [cupSlideLeft,cupSlideRight,sum_spin,exchangeNumerator_eq_table,exchangeTable, + exchangeDenominator,cup,charge,zpow_neg,q_five_inv,T,t] + +theorem cup_slide_entry_4_1 (x : ℂ) : + cupSlideLeft x .zero .plus .plus .plus = cupSlideRight x .zero .plus .plus .plus := by + norm_num [cupSlideLeft,cupSlideRight,sum_spin,exchangeNumerator_eq_table,exchangeTable, + exchangeDenominator,cup,charge,zpow_neg,q_five_inv,T,t] + +theorem cup_slide_entry_4_2 (x : ℂ) : + cupSlideLeft x .zero .plus .plus .minus = cupSlideRight x .zero .plus .plus .minus := by + norm_num [cupSlideLeft,cupSlideRight,sum_spin,exchangeNumerator_eq_table,exchangeTable, + exchangeDenominator,cup,charge,zpow_neg,q_five_inv,T,t] + +theorem cup_slide_entry_5_0 (x : ℂ) : + cupSlideLeft x .zero .plus .minus .zero = cupSlideRight x .zero .plus .minus .zero := by + norm_num [cupSlideLeft,cupSlideRight,sum_spin,exchangeNumerator_eq_table,exchangeTable, + exchangeDenominator,cup,charge,zpow_neg,q_five_inv,T,t] + all_goals ring_nf + all_goals try simp only [q_pow_9,q_pow_11,q_pow_13,q_pow_15,q_pow_17,q_pow_19,q_pow_21,q_pow_23,q_pow_25,q_pow_27,q_pow_31,q_pow_33,q_pow_37] + all_goals ring + +theorem cup_slide_entry_5_1 (x : ℂ) : + cupSlideLeft x .zero .plus .minus .plus = cupSlideRight x .zero .plus .minus .plus := by + norm_num [cupSlideLeft,cupSlideRight,sum_spin,exchangeNumerator_eq_table,exchangeTable, + exchangeDenominator,cup,charge,zpow_neg,q_five_inv,T,t] + +theorem cup_slide_entry_5_2 (x : ℂ) : + cupSlideLeft x .zero .plus .minus .minus = cupSlideRight x .zero .plus .minus .minus := by + norm_num [cupSlideLeft,cupSlideRight,sum_spin,exchangeNumerator_eq_table,exchangeTable, + exchangeDenominator,cup,charge,zpow_neg,q_five_inv,T,t] + +theorem cup_slide_entry_6_0 (x : ℂ) : + cupSlideLeft x .zero .minus .zero .zero = cupSlideRight x .zero .minus .zero .zero := by + norm_num [cupSlideLeft,cupSlideRight,sum_spin,exchangeNumerator_eq_table,exchangeTable, + exchangeDenominator,cup,charge,zpow_neg,q_five_inv,T,t] + +theorem cup_slide_entry_6_1 (x : ℂ) : + cupSlideLeft x .zero .minus .zero .plus = cupSlideRight x .zero .minus .zero .plus := by + norm_num [cupSlideLeft,cupSlideRight,sum_spin,exchangeNumerator_eq_table,exchangeTable, + exchangeDenominator,cup,charge,zpow_neg,q_five_inv,T,t] + +theorem cup_slide_entry_6_2 (x : ℂ) : + cupSlideLeft x .zero .minus .zero .minus = cupSlideRight x .zero .minus .zero .minus := by + norm_num [cupSlideLeft,cupSlideRight,sum_spin,exchangeNumerator_eq_table,exchangeTable, + exchangeDenominator,cup,charge,zpow_neg,q_five_inv,T,t] + all_goals ring_nf + all_goals try simp only [q_pow_eight,q_pow_10,q_pow_14,q_pow_16,q_pow_18,q_pow_20,q_pow_22] + all_goals ring + +theorem cup_slide_entry_7_0 (x : ℂ) : + cupSlideLeft x .zero .minus .plus .zero = cupSlideRight x .zero .minus .plus .zero := by + norm_num [cupSlideLeft,cupSlideRight,sum_spin,exchangeNumerator_eq_table,exchangeTable, + exchangeDenominator,cup,charge,zpow_neg,q_five_inv,T,t] + all_goals ring_nf + all_goals try simp only [q_pow_9,q_pow_11,q_pow_13,q_pow_15,q_pow_17,q_pow_19,q_pow_21,q_pow_23,q_pow_25,q_pow_29,q_pow_31,q_pow_35] + all_goals ring + +theorem cup_slide_entry_7_1 (x : ℂ) : + cupSlideLeft x .zero .minus .plus .plus = cupSlideRight x .zero .minus .plus .plus := by + norm_num [cupSlideLeft,cupSlideRight,sum_spin,exchangeNumerator_eq_table,exchangeTable, + exchangeDenominator,cup,charge,zpow_neg,q_five_inv,T,t] + +theorem cup_slide_entry_7_2 (x : ℂ) : + cupSlideLeft x .zero .minus .plus .minus = cupSlideRight x .zero .minus .plus .minus := by + norm_num [cupSlideLeft,cupSlideRight,sum_spin,exchangeNumerator_eq_table,exchangeTable, + exchangeDenominator,cup,charge,zpow_neg,q_five_inv,T,t] + +theorem cup_slide_entry_8_0 (x : ℂ) : + cupSlideLeft x .zero .minus .minus .zero = cupSlideRight x .zero .minus .minus .zero := by + norm_num [cupSlideLeft,cupSlideRight,sum_spin,exchangeNumerator_eq_table,exchangeTable, + exchangeDenominator,cup,charge,zpow_neg,q_five_inv,T,t] + +theorem cup_slide_entry_8_1 (x : ℂ) : + cupSlideLeft x .zero .minus .minus .plus = cupSlideRight x .zero .minus .minus .plus := by + norm_num [cupSlideLeft,cupSlideRight,sum_spin,exchangeNumerator_eq_table,exchangeTable, + exchangeDenominator,cup,charge,zpow_neg,q_five_inv,T,t] + +theorem cup_slide_entry_8_2 (x : ℂ) : + cupSlideLeft x .zero .minus .minus .minus = cupSlideRight x .zero .minus .minus .minus := by + norm_num [cupSlideLeft,cupSlideRight,sum_spin,exchangeNumerator_eq_table,exchangeTable, + exchangeDenominator,cup,charge,zpow_neg,q_five_inv,T,t] + +theorem cup_slide_entry_9_0 (x : ℂ) : + cupSlideLeft x .plus .zero .zero .zero = cupSlideRight x .plus .zero .zero .zero := by + norm_num [cupSlideLeft,cupSlideRight,sum_spin,exchangeNumerator_eq_table,exchangeTable, + exchangeDenominator,cup,charge,zpow_neg,q_five_inv,T,t] + +theorem cup_slide_entry_9_1 (x : ℂ) : + cupSlideLeft x .plus .zero .zero .plus = cupSlideRight x .plus .zero .zero .plus := by + norm_num [cupSlideLeft,cupSlideRight,sum_spin,exchangeNumerator_eq_table,exchangeTable, + exchangeDenominator,cup,charge,zpow_neg,q_five_inv,T,t] + all_goals ring_nf + all_goals try simp only [q_pow_eight,q_pow_10,q_pow_12,q_pow_14,q_pow_16,q_pow_18,q_pow_20,q_pow_22,q_pow_26,q_pow_28,q_pow_32] + all_goals ring + +theorem cup_slide_entry_9_2 (x : ℂ) : + cupSlideLeft x .plus .zero .zero .minus = cupSlideRight x .plus .zero .zero .minus := by + norm_num [cupSlideLeft,cupSlideRight,sum_spin,exchangeNumerator_eq_table,exchangeTable, + exchangeDenominator,cup,charge,zpow_neg,q_five_inv,T,t] + +theorem cup_slide_entry_10_0 (x : ℂ) : + cupSlideLeft x .plus .zero .plus .zero = cupSlideRight x .plus .zero .plus .zero := by + norm_num [cupSlideLeft,cupSlideRight,sum_spin,exchangeNumerator_eq_table,exchangeTable, + exchangeDenominator,cup,charge,zpow_neg,q_five_inv,T,t] + +theorem cup_slide_entry_10_1 (x : ℂ) : + cupSlideLeft x .plus .zero .plus .plus = cupSlideRight x .plus .zero .plus .plus := by + norm_num [cupSlideLeft,cupSlideRight,sum_spin,exchangeNumerator_eq_table,exchangeTable, + exchangeDenominator,cup,charge,zpow_neg,q_five_inv,T,t] + +theorem cup_slide_entry_10_2 (x : ℂ) : + cupSlideLeft x .plus .zero .plus .minus = cupSlideRight x .plus .zero .plus .minus := by + norm_num [cupSlideLeft,cupSlideRight,sum_spin,exchangeNumerator_eq_table,exchangeTable, + exchangeDenominator,cup,charge,zpow_neg,q_five_inv,T,t] + +theorem cup_slide_entry_11_0 (x : ℂ) : + cupSlideLeft x .plus .zero .minus .zero = cupSlideRight x .plus .zero .minus .zero := by + norm_num [cupSlideLeft,cupSlideRight,sum_spin,exchangeNumerator_eq_table,exchangeTable, + exchangeDenominator,cup,charge,zpow_neg,q_five_inv,T,t] + all_goals ring_nf + all_goals try simp only [q_pow_9,q_pow_11,q_pow_13,q_pow_15,q_pow_19,q_pow_21,q_pow_23,q_pow_25] + all_goals ring + +theorem cup_slide_entry_11_1 (x : ℂ) : + cupSlideLeft x .plus .zero .minus .plus = cupSlideRight x .plus .zero .minus .plus := by + norm_num [cupSlideLeft,cupSlideRight,sum_spin,exchangeNumerator_eq_table,exchangeTable, + exchangeDenominator,cup,charge,zpow_neg,q_five_inv,T,t] + +theorem cup_slide_entry_11_2 (x : ℂ) : + cupSlideLeft x .plus .zero .minus .minus = cupSlideRight x .plus .zero .minus .minus := by + norm_num [cupSlideLeft,cupSlideRight,sum_spin,exchangeNumerator_eq_table,exchangeTable, + exchangeDenominator,cup,charge,zpow_neg,q_five_inv,T,t] + +theorem cup_slide_entry_12_0 (x : ℂ) : + cupSlideLeft x .plus .plus .zero .zero = cupSlideRight x .plus .plus .zero .zero := by + norm_num [cupSlideLeft,cupSlideRight,sum_spin,exchangeNumerator_eq_table,exchangeTable, + exchangeDenominator,cup,charge,zpow_neg,q_five_inv,T,t] + +theorem cup_slide_entry_12_1 (x : ℂ) : + cupSlideLeft x .plus .plus .zero .plus = cupSlideRight x .plus .plus .zero .plus := by + norm_num [cupSlideLeft,cupSlideRight,sum_spin,exchangeNumerator_eq_table,exchangeTable, + exchangeDenominator,cup,charge,zpow_neg,q_five_inv,T,t] + +theorem cup_slide_entry_12_2 (x : ℂ) : + cupSlideLeft x .plus .plus .zero .minus = cupSlideRight x .plus .plus .zero .minus := by + norm_num [cupSlideLeft,cupSlideRight,sum_spin,exchangeNumerator_eq_table,exchangeTable, + exchangeDenominator,cup,charge,zpow_neg,q_five_inv,T,t] + +theorem cup_slide_entry_13_0 (x : ℂ) : + cupSlideLeft x .plus .plus .plus .zero = cupSlideRight x .plus .plus .plus .zero := by + norm_num [cupSlideLeft,cupSlideRight,sum_spin,exchangeNumerator_eq_table,exchangeTable, + exchangeDenominator,cup,charge,zpow_neg,q_five_inv,T,t] + +theorem cup_slide_entry_13_1 (x : ℂ) : + cupSlideLeft x .plus .plus .plus .plus = cupSlideRight x .plus .plus .plus .plus := by + norm_num [cupSlideLeft,cupSlideRight,sum_spin,exchangeNumerator_eq_table,exchangeTable, + exchangeDenominator,cup,charge,zpow_neg,q_five_inv,T,t] + +theorem cup_slide_entry_13_2 (x : ℂ) : + cupSlideLeft x .plus .plus .plus .minus = cupSlideRight x .plus .plus .plus .minus := by + norm_num [cupSlideLeft,cupSlideRight,sum_spin,exchangeNumerator_eq_table,exchangeTable, + exchangeDenominator,cup,charge,zpow_neg,q_five_inv,T,t] + +theorem cup_slide_entry_14_0 (x : ℂ) : + cupSlideLeft x .plus .plus .minus .zero = cupSlideRight x .plus .plus .minus .zero := by + norm_num [cupSlideLeft,cupSlideRight,sum_spin,exchangeNumerator_eq_table,exchangeTable, + exchangeDenominator,cup,charge,zpow_neg,q_five_inv,T,t] + +theorem cup_slide_entry_14_1 (x : ℂ) : + cupSlideLeft x .plus .plus .minus .plus = cupSlideRight x .plus .plus .minus .plus := by + norm_num [cupSlideLeft,cupSlideRight,sum_spin,exchangeNumerator_eq_table,exchangeTable, + exchangeDenominator,cup,charge,zpow_neg,q_five_inv,T,t] + all_goals ring_nf + all_goals try (apply Or.inl) + all_goals try simp only [q_pow_eight,q_pow_10,q_pow_12,q_pow_14,q_pow_16,q_pow_18,q_pow_20,q_pow_22,q_pow_26,q_pow_28,q_pow_32] + all_goals ring + +theorem cup_slide_entry_14_2 (x : ℂ) : + cupSlideLeft x .plus .plus .minus .minus = cupSlideRight x .plus .plus .minus .minus := by + norm_num [cupSlideLeft,cupSlideRight,sum_spin,exchangeNumerator_eq_table,exchangeTable, + exchangeDenominator,cup,charge,zpow_neg,q_five_inv,T,t] + +theorem cup_slide_entry_15_0 (x : ℂ) : + cupSlideLeft x .plus .minus .zero .zero = cupSlideRight x .plus .minus .zero .zero := by + norm_num [cupSlideLeft,cupSlideRight,sum_spin,exchangeNumerator_eq_table,exchangeTable, + exchangeDenominator,cup,charge,zpow_neg,q_five_inv,T,t] + all_goals ring_nf + all_goals try simp only [q_pow_9,q_pow_11,q_pow_13,q_pow_15,q_pow_17,q_pow_19,q_pow_21,q_pow_23,q_pow_25] + all_goals ring + +theorem cup_slide_entry_15_1 (x : ℂ) : + cupSlideLeft x .plus .minus .zero .plus = cupSlideRight x .plus .minus .zero .plus := by + norm_num [cupSlideLeft,cupSlideRight,sum_spin,exchangeNumerator_eq_table,exchangeTable, + exchangeDenominator,cup,charge,zpow_neg,q_five_inv,T,t] + +theorem cup_slide_entry_15_2 (x : ℂ) : + cupSlideLeft x .plus .minus .zero .minus = cupSlideRight x .plus .minus .zero .minus := by + norm_num [cupSlideLeft,cupSlideRight,sum_spin,exchangeNumerator_eq_table,exchangeTable, + exchangeDenominator,cup,charge,zpow_neg,q_five_inv,T,t] + +theorem cup_slide_entry_16_0 (x : ℂ) : + cupSlideLeft x .plus .minus .plus .zero = cupSlideRight x .plus .minus .plus .zero := by + norm_num [cupSlideLeft,cupSlideRight,sum_spin,exchangeNumerator_eq_table,exchangeTable, + exchangeDenominator,cup,charge,zpow_neg,q_five_inv,T,t] + +theorem cup_slide_entry_16_1 (x : ℂ) : + cupSlideLeft x .plus .minus .plus .plus = cupSlideRight x .plus .minus .plus .plus := by + norm_num [cupSlideLeft,cupSlideRight,sum_spin,exchangeNumerator_eq_table,exchangeTable, + exchangeDenominator,cup,charge,zpow_neg,q_five_inv,T,t] + all_goals ring_nf + all_goals try simp only [q_pow_9,q_pow_11,q_pow_13,q_pow_15,q_pow_17,q_pow_19,q_pow_21,q_pow_23,q_pow_25,q_pow_29,q_pow_31,q_pow_35] + all_goals ring + +theorem cup_slide_entry_16_2 (x : ℂ) : + cupSlideLeft x .plus .minus .plus .minus = cupSlideRight x .plus .minus .plus .minus := by + norm_num [cupSlideLeft,cupSlideRight,sum_spin,exchangeNumerator_eq_table,exchangeTable, + exchangeDenominator,cup,charge,zpow_neg,q_five_inv,T,t] + +theorem cup_slide_entry_17_0 (x : ℂ) : + cupSlideLeft x .plus .minus .minus .zero = cupSlideRight x .plus .minus .minus .zero := by + norm_num [cupSlideLeft,cupSlideRight,sum_spin,exchangeNumerator_eq_table,exchangeTable, + exchangeDenominator,cup,charge,zpow_neg,q_five_inv,T,t] + +theorem cup_slide_entry_17_1 (x : ℂ) : + cupSlideLeft x .plus .minus .minus .plus = cupSlideRight x .plus .minus .minus .plus := by + norm_num [cupSlideLeft,cupSlideRight,sum_spin,exchangeNumerator_eq_table,exchangeTable, + exchangeDenominator,cup,charge,zpow_neg,q_five_inv,T,t] + +theorem cup_slide_entry_17_2 (x : ℂ) : + cupSlideLeft x .plus .minus .minus .minus = cupSlideRight x .plus .minus .minus .minus := by + norm_num [cupSlideLeft,cupSlideRight,sum_spin,exchangeNumerator_eq_table,exchangeTable, + exchangeDenominator,cup,charge,zpow_neg,q_five_inv,T,t] + all_goals ring_nf + all_goals try simp only [q_pow_9,q_pow_11,q_pow_13,q_pow_15,q_pow_17,q_pow_19,q_pow_21,q_pow_23,q_pow_25,q_pow_27] + all_goals ring + +theorem cup_slide_entry_18_0 (x : ℂ) : + cupSlideLeft x .minus .zero .zero .zero = cupSlideRight x .minus .zero .zero .zero := by + norm_num [cupSlideLeft,cupSlideRight,sum_spin,exchangeNumerator_eq_table,exchangeTable, + exchangeDenominator,cup,charge,zpow_neg,q_five_inv,T,t] + +theorem cup_slide_entry_18_1 (x : ℂ) : + cupSlideLeft x .minus .zero .zero .plus = cupSlideRight x .minus .zero .zero .plus := by + norm_num [cupSlideLeft,cupSlideRight,sum_spin,exchangeNumerator_eq_table,exchangeTable, + exchangeDenominator,cup,charge,zpow_neg,q_five_inv,T,t] + +theorem cup_slide_entry_18_2 (x : ℂ) : + cupSlideLeft x .minus .zero .zero .minus = cupSlideRight x .minus .zero .zero .minus := by + norm_num [cupSlideLeft,cupSlideRight,sum_spin,exchangeNumerator_eq_table,exchangeTable, + exchangeDenominator,cup,charge,zpow_neg,q_five_inv,T,t] + all_goals ring_nf + all_goals try simp only [q_pow_eight,q_pow_10,q_pow_12,q_pow_14,q_pow_16,q_pow_18,q_pow_20,q_pow_22,q_pow_24,q_pow_26,q_pow_28,q_pow_32] + all_goals ring + +theorem cup_slide_entry_19_0 (x : ℂ) : + cupSlideLeft x .minus .zero .plus .zero = cupSlideRight x .minus .zero .plus .zero := by + norm_num [cupSlideLeft,cupSlideRight,sum_spin,exchangeNumerator_eq_table,exchangeTable, + exchangeDenominator,cup,charge,zpow_neg,q_five_inv,T,t] + all_goals ring_nf + all_goals try simp only [q_pow_9,q_pow_11,q_pow_13,q_pow_15,q_pow_17,q_pow_19,q_pow_21,q_pow_23] + all_goals ring + +theorem cup_slide_entry_19_1 (x : ℂ) : + cupSlideLeft x .minus .zero .plus .plus = cupSlideRight x .minus .zero .plus .plus := by + norm_num [cupSlideLeft,cupSlideRight,sum_spin,exchangeNumerator_eq_table,exchangeTable, + exchangeDenominator,cup,charge,zpow_neg,q_five_inv,T,t] + +theorem cup_slide_entry_19_2 (x : ℂ) : + cupSlideLeft x .minus .zero .plus .minus = cupSlideRight x .minus .zero .plus .minus := by + norm_num [cupSlideLeft,cupSlideRight,sum_spin,exchangeNumerator_eq_table,exchangeTable, + exchangeDenominator,cup,charge,zpow_neg,q_five_inv,T,t] + +theorem cup_slide_entry_20_0 (x : ℂ) : + cupSlideLeft x .minus .zero .minus .zero = cupSlideRight x .minus .zero .minus .zero := by + norm_num [cupSlideLeft,cupSlideRight,sum_spin,exchangeNumerator_eq_table,exchangeTable, + exchangeDenominator,cup,charge,zpow_neg,q_five_inv,T,t] + +theorem cup_slide_entry_20_1 (x : ℂ) : + cupSlideLeft x .minus .zero .minus .plus = cupSlideRight x .minus .zero .minus .plus := by + norm_num [cupSlideLeft,cupSlideRight,sum_spin,exchangeNumerator_eq_table,exchangeTable, + exchangeDenominator,cup,charge,zpow_neg,q_five_inv,T,t] + +theorem cup_slide_entry_20_2 (x : ℂ) : + cupSlideLeft x .minus .zero .minus .minus = cupSlideRight x .minus .zero .minus .minus := by + norm_num [cupSlideLeft,cupSlideRight,sum_spin,exchangeNumerator_eq_table,exchangeTable, + exchangeDenominator,cup,charge,zpow_neg,q_five_inv,T,t] + +theorem cup_slide_entry_21_0 (x : ℂ) : + cupSlideLeft x .minus .plus .zero .zero = cupSlideRight x .minus .plus .zero .zero := by + norm_num [cupSlideLeft,cupSlideRight,sum_spin,exchangeNumerator_eq_table,exchangeTable, + exchangeDenominator,cup,charge,zpow_neg,q_five_inv,T,t] + all_goals ring_nf + all_goals try simp only [q_pow_11,q_pow_13,q_pow_15,q_pow_17,q_pow_19,q_pow_21,q_pow_23,q_pow_25] + all_goals ring + +theorem cup_slide_entry_21_1 (x : ℂ) : + cupSlideLeft x .minus .plus .zero .plus = cupSlideRight x .minus .plus .zero .plus := by + norm_num [cupSlideLeft,cupSlideRight,sum_spin,exchangeNumerator_eq_table,exchangeTable, + exchangeDenominator,cup,charge,zpow_neg,q_five_inv,T,t] + +theorem cup_slide_entry_21_2 (x : ℂ) : + cupSlideLeft x .minus .plus .zero .minus = cupSlideRight x .minus .plus .zero .minus := by + norm_num [cupSlideLeft,cupSlideRight,sum_spin,exchangeNumerator_eq_table,exchangeTable, + exchangeDenominator,cup,charge,zpow_neg,q_five_inv,T,t] + +theorem cup_slide_entry_22_0 (x : ℂ) : + cupSlideLeft x .minus .plus .plus .zero = cupSlideRight x .minus .plus .plus .zero := by + norm_num [cupSlideLeft,cupSlideRight,sum_spin,exchangeNumerator_eq_table,exchangeTable, + exchangeDenominator,cup,charge,zpow_neg,q_five_inv,T,t] + +theorem cup_slide_entry_22_1 (x : ℂ) : + cupSlideLeft x .minus .plus .plus .plus = cupSlideRight x .minus .plus .plus .plus := by + norm_num [cupSlideLeft,cupSlideRight,sum_spin,exchangeNumerator_eq_table,exchangeTable, + exchangeDenominator,cup,charge,zpow_neg,q_five_inv,T,t] + all_goals ring_nf + all_goals try simp only [q_pow_9,q_pow_11,q_pow_13,q_pow_15,q_pow_17,q_pow_19,q_pow_21] + all_goals ring + +theorem cup_slide_entry_22_2 (x : ℂ) : + cupSlideLeft x .minus .plus .plus .minus = cupSlideRight x .minus .plus .plus .minus := by + norm_num [cupSlideLeft,cupSlideRight,sum_spin,exchangeNumerator_eq_table,exchangeTable, + exchangeDenominator,cup,charge,zpow_neg,q_five_inv,T,t] + +theorem cup_slide_entry_23_0 (x : ℂ) : + cupSlideLeft x .minus .plus .minus .zero = cupSlideRight x .minus .plus .minus .zero := by + norm_num [cupSlideLeft,cupSlideRight,sum_spin,exchangeNumerator_eq_table,exchangeTable, + exchangeDenominator,cup,charge,zpow_neg,q_five_inv,T,t] + +theorem cup_slide_entry_23_1 (x : ℂ) : + cupSlideLeft x .minus .plus .minus .plus = cupSlideRight x .minus .plus .minus .plus := by + norm_num [cupSlideLeft,cupSlideRight,sum_spin,exchangeNumerator_eq_table,exchangeTable, + exchangeDenominator,cup,charge,zpow_neg,q_five_inv,T,t] + +theorem cup_slide_entry_23_2 (x : ℂ) : + cupSlideLeft x .minus .plus .minus .minus = cupSlideRight x .minus .plus .minus .minus := by + norm_num [cupSlideLeft,cupSlideRight,sum_spin,exchangeNumerator_eq_table,exchangeTable, + exchangeDenominator,cup,charge,zpow_neg,q_five_inv,T,t] + all_goals ring_nf + all_goals try simp only [q_pow_9,q_pow_11,q_pow_13,q_pow_15,q_pow_17,q_pow_19,q_pow_21,q_pow_23,q_pow_25,q_pow_27,q_pow_31,q_pow_33,q_pow_37] + all_goals ring + +theorem cup_slide_entry_24_0 (x : ℂ) : + cupSlideLeft x .minus .minus .zero .zero = cupSlideRight x .minus .minus .zero .zero := by + norm_num [cupSlideLeft,cupSlideRight,sum_spin,exchangeNumerator_eq_table,exchangeTable, + exchangeDenominator,cup,charge,zpow_neg,q_five_inv,T,t] + +theorem cup_slide_entry_24_1 (x : ℂ) : + cupSlideLeft x .minus .minus .zero .plus = cupSlideRight x .minus .minus .zero .plus := by + norm_num [cupSlideLeft,cupSlideRight,sum_spin,exchangeNumerator_eq_table,exchangeTable, + exchangeDenominator,cup,charge,zpow_neg,q_five_inv,T,t] + +theorem cup_slide_entry_24_2 (x : ℂ) : + cupSlideLeft x .minus .minus .zero .minus = cupSlideRight x .minus .minus .zero .minus := by + norm_num [cupSlideLeft,cupSlideRight,sum_spin,exchangeNumerator_eq_table,exchangeTable, + exchangeDenominator,cup,charge,zpow_neg,q_five_inv,T,t] + +theorem cup_slide_entry_25_0 (x : ℂ) : + cupSlideLeft x .minus .minus .plus .zero = cupSlideRight x .minus .minus .plus .zero := by + norm_num [cupSlideLeft,cupSlideRight,sum_spin,exchangeNumerator_eq_table,exchangeTable, + exchangeDenominator,cup,charge,zpow_neg,q_five_inv,T,t] + +theorem cup_slide_entry_25_1 (x : ℂ) : + cupSlideLeft x .minus .minus .plus .plus = cupSlideRight x .minus .minus .plus .plus := by + norm_num [cupSlideLeft,cupSlideRight,sum_spin,exchangeNumerator_eq_table,exchangeTable, + exchangeDenominator,cup,charge,zpow_neg,q_five_inv,T,t] + +theorem cup_slide_entry_25_2 (x : ℂ) : + cupSlideLeft x .minus .minus .plus .minus = cupSlideRight x .minus .minus .plus .minus := by + norm_num [cupSlideLeft,cupSlideRight,sum_spin,exchangeNumerator_eq_table,exchangeTable, + exchangeDenominator,cup,charge,zpow_neg,q_five_inv,T,t] + all_goals ring_nf + all_goals try (apply Or.inl) + all_goals try simp only [q_pow_eight,q_pow_10,q_pow_12,q_pow_14,q_pow_16,q_pow_18,q_pow_20,q_pow_22,q_pow_26,q_pow_28,q_pow_32] + all_goals ring + +theorem cup_slide_entry_26_0 (x : ℂ) : + cupSlideLeft x .minus .minus .minus .zero = cupSlideRight x .minus .minus .minus .zero := by + norm_num [cupSlideLeft,cupSlideRight,sum_spin,exchangeNumerator_eq_table,exchangeTable, + exchangeDenominator,cup,charge,zpow_neg,q_five_inv,T,t] + +theorem cup_slide_entry_26_1 (x : ℂ) : + cupSlideLeft x .minus .minus .minus .plus = cupSlideRight x .minus .minus .minus .plus := by + norm_num [cupSlideLeft,cupSlideRight,sum_spin,exchangeNumerator_eq_table,exchangeTable, + exchangeDenominator,cup,charge,zpow_neg,q_five_inv,T,t] + +theorem cup_slide_entry_26_2 (x : ℂ) : + cupSlideLeft x .minus .minus .minus .minus = cupSlideRight x .minus .minus .minus .minus := by + norm_num [cupSlideLeft,cupSlideRight,sum_spin,exchangeNumerator_eq_table,exchangeTable, + exchangeDenominator,cup,charge,zpow_neg,q_five_inv,T,t] + +theorem cup_slide_coefficients (x : ℂ) (a b c h : Spin) : + cupSlideLeft x a b c h = cupSlideRight x a b c h := by + cases a <;> cases b <;> cases c <;> cases h + · exact cup_slide_entry_0_0 x + · exact cup_slide_entry_0_1 x + · exact cup_slide_entry_0_2 x + · exact cup_slide_entry_1_0 x + · exact cup_slide_entry_1_1 x + · exact cup_slide_entry_1_2 x + · exact cup_slide_entry_2_0 x + · exact cup_slide_entry_2_1 x + · exact cup_slide_entry_2_2 x + · exact cup_slide_entry_3_0 x + · exact cup_slide_entry_3_1 x + · exact cup_slide_entry_3_2 x + · exact cup_slide_entry_4_0 x + · exact cup_slide_entry_4_1 x + · exact cup_slide_entry_4_2 x + · exact cup_slide_entry_5_0 x + · exact cup_slide_entry_5_1 x + · exact cup_slide_entry_5_2 x + · exact cup_slide_entry_6_0 x + · exact cup_slide_entry_6_1 x + · exact cup_slide_entry_6_2 x + · exact cup_slide_entry_7_0 x + · exact cup_slide_entry_7_1 x + · exact cup_slide_entry_7_2 x + · exact cup_slide_entry_8_0 x + · exact cup_slide_entry_8_1 x + · exact cup_slide_entry_8_2 x + · exact cup_slide_entry_9_0 x + · exact cup_slide_entry_9_1 x + · exact cup_slide_entry_9_2 x + · exact cup_slide_entry_10_0 x + · exact cup_slide_entry_10_1 x + · exact cup_slide_entry_10_2 x + · exact cup_slide_entry_11_0 x + · exact cup_slide_entry_11_1 x + · exact cup_slide_entry_11_2 x + · exact cup_slide_entry_12_0 x + · exact cup_slide_entry_12_1 x + · exact cup_slide_entry_12_2 x + · exact cup_slide_entry_13_0 x + · exact cup_slide_entry_13_1 x + · exact cup_slide_entry_13_2 x + · exact cup_slide_entry_14_0 x + · exact cup_slide_entry_14_1 x + · exact cup_slide_entry_14_2 x + · exact cup_slide_entry_15_0 x + · exact cup_slide_entry_15_1 x + · exact cup_slide_entry_15_2 x + · exact cup_slide_entry_16_0 x + · exact cup_slide_entry_16_1 x + · exact cup_slide_entry_16_2 x + · exact cup_slide_entry_17_0 x + · exact cup_slide_entry_17_1 x + · exact cup_slide_entry_17_2 x + · exact cup_slide_entry_18_0 x + · exact cup_slide_entry_18_1 x + · exact cup_slide_entry_18_2 x + · exact cup_slide_entry_19_0 x + · exact cup_slide_entry_19_1 x + · exact cup_slide_entry_19_2 x + · exact cup_slide_entry_20_0 x + · exact cup_slide_entry_20_1 x + · exact cup_slide_entry_20_2 x + · exact cup_slide_entry_21_0 x + · exact cup_slide_entry_21_1 x + · exact cup_slide_entry_21_2 x + · exact cup_slide_entry_22_0 x + · exact cup_slide_entry_22_1 x + · exact cup_slide_entry_22_2 x + · exact cup_slide_entry_23_0 x + · exact cup_slide_entry_23_1 x + · exact cup_slide_entry_23_2 x + · exact cup_slide_entry_24_0 x + · exact cup_slide_entry_24_1 x + · exact cup_slide_entry_24_2 x + · exact cup_slide_entry_25_0 x + · exact cup_slide_entry_25_1 x + · exact cup_slide_entry_25_2 x + · exact cup_slide_entry_26_0 x + · exact cup_slide_entry_26_1 x + · exact cup_slide_entry_26_2 x + +end PolynomialVacuumAlgebra + +end OAI diff --git a/lean/OAI/Combinatorics/PolynomialVacuum/Algebra/CupSlidePolynomial.lean b/lean/OAI/Combinatorics/PolynomialVacuum/Algebra/CupSlidePolynomial.lean new file mode 100644 index 0000000000000000000000000000000000000000..ea5d9c4dcf28333f4443112ab4d5c0fce2cdd984 --- /dev/null +++ b/lean/OAI/Combinatorics/PolynomialVacuum/Algebra/CupSlidePolynomial.lean @@ -0,0 +1,85 @@ +import OAI.Combinatorics.PolynomialVacuum.Algebra.FirstCupInterpolation +import OAI.Combinatorics.PolynomialVacuum.Algebra.CupPointwiseSlide +import OAI.Combinatorics.PolynomialVacuum.Algebra.InterpolatedExchanges + +namespace OAI + +namespace PolynomialVacuumAlgebra +open MvPolynomial Classical + +noncomputable def cupPolynomial {n : ℕ} (ψ : State n) (i : ℕ) (s : ℕ → Spin) : + MvPolynomial ℕ ℂ := + C ((1+T)*cup (s i,s (i+1)))*X i * + (∏ k ∈ Finset.range n, + (X (if k < i then k else k+2)-C (t^5)*X i)*(X (if k < i then k else k+2)-C (t^6)*X i)) * + rename (fun j : Fin n => if j.val < i then j.val else j.val+2) + (ψ (fun j => skipTwo i s j.val)) + +@[simp] theorem eval_cupPolynomial {n : ℕ} (ψ : State n) (i : ℕ) (s : ℕ → Spin) (Y : ℕ → ℂ) : + eval Y (cupPolynomial ψ i s)=(naturalFusion n i Y • cupLinear i (liftState ψ (skipTwo i Y))) s := by + simp only [cupPolynomial,map_mul,map_prod,map_sub,eval_C,eval_X,eval_rename, + liftState,liftPolyTensor,naturalFusion,fusionProduct,fusionPair,Pi.smul_apply,smul_eq_mul, + cupLinear,LinearMap.coe_mk,AddHom.coe_mk,Function.comp_def,skipTwo] + have h1 : (fun j : Fin n => Y (if j.val < i then j.val else j.val+2))= + (fun j : Fin n => if j.val < i then Y j.val else Y (j.val+2)) := by funext j; split_ifs <;> rfl + have h2 (k : ℕ) : Y (if k < i then k else k+2)=if k < i then Y k else Y (k+2) := by split_ifs <;> rfl + simp only [h2] + ring + +noncomputable def cupSlideGuard (i : ℕ) : MvPolynomial ℕ ℂ := + ((C (t^2)*X (i+1)-X i)*(C T*X (i+1)-X i))* + ((C (t^2)*(C T*X (i+1))-X i)*(C T*(C T*X (i+1))-X i)) + +@[simp] theorem eval_cupSlideGuard (i : ℕ) (Y : ℕ → ℂ) : + eval Y (cupSlideGuard i)=exchangeDenominator (Y (i+1)) (Y i)* + exchangeDenominator (T*Y (i+1)) (Y i) := by + simp [cupSlideGuard,exchangeDenominator] + +theorem cupSlideGuard_surface_ne_zero (i : ℕ) : + cupSpecialize (i+1) (i+2) (cupSlideGuard i)≠0 := by + intro he + have hv := congrArg (eval (fun j : ℕ => if j=i then (1:ℂ) else 0)) he + simp only [map_zero,eval_cupSpecialize,eval_cupSlideGuard] at hv + have h0 : i≠i+2 := by omega + have h1 : i+1≠i+2 := by omega + norm_num [Function.update_of_ne h0,Function.update_of_ne h1, + show i+1≠i by omega,exchangeDenominator] at hv + +theorem cupSurface_eq_of_generic (a b : ℕ) (hab : a≠b) (p r G : MvPolynomial ℕ ℂ) + (hG : cupSpecialize a b G≠0) + (h : ∀ Y, Y b=T*Y a → eval Y G≠0 → eval Y p=eval Y r) : + cupSpecialize a b p=cupSpecialize a b r := by + apply polynomial_eq_on_generic hG + intro X hX + simp only [eval_cupSpecialize] at hX ⊢ + apply h _ _ hX + simp [hab] + +theorem cupAt_step {n : ℕ} (Ψ : State (n+2)) (ψ : State n) (i : ℕ) + (hΨ : LowerExchange (liftState Ψ) (n+1)) (hi : i+2 < n+1) + (hc : CupAt (liftState Ψ) (liftState ψ) n i) : + CupAt (liftState Ψ) (liftState ψ) n (i+1) := by + intro Y hY + funext s + have he : cupSpecialize (i+1) (i+2) (coordinatePolynomial Ψ s)= + cupSpecialize (i+1) (i+2) (cupPolynomial ψ (i+1) s) := by + apply cupSurface_eq_of_generic _ _ (by omega) _ _ (cupSlideGuard i) (cupSlideGuard_surface_ne_zero i) + intro X hX hG + simp only [eval_coordinatePolynomial,eval_cupPolynomial] + exact congrFun (cupAt_step_generic hΨ hi hc X hX (by simpa using hG)) s + simpa using eval_eq_of_cupSurface_eq (i+1) (i+2) _ _ he Y hY + + + +theorem cupAt_of_first {n : ℕ} (Ψ : State (n+2)) (ψ : State n) + (hΨ : LowerExchange (liftState Ψ) (n+1)) + (hc : FirstCupReduction (liftState Ψ) (liftState ψ) n) : + ∀ i, i < n → CupAt (liftState Ψ) (liftState ψ) n i := by + intro i hi + induction i with + | zero => exact hc + | succ i ih => exact cupAt_step Ψ ψ i hΨ (by omega) (ih (by omega)) + +end PolynomialVacuumAlgebra + +end OAI diff --git a/lean/OAI/Combinatorics/PolynomialVacuum/Algebra/CupSurface.lean b/lean/OAI/Combinatorics/PolynomialVacuum/Algebra/CupSurface.lean new file mode 100644 index 0000000000000000000000000000000000000000..803219184f44403cbbccfca24ea75e63364eb7b4 --- /dev/null +++ b/lean/OAI/Combinatorics/PolynomialVacuum/Algebra/CupSurface.lean @@ -0,0 +1,92 @@ +import OAI.Combinatorics.PolynomialVacuum.Algebra.PolynomialGenericity + +namespace OAI + +namespace PolynomialVacuumAlgebra +open MvPolynomial Classical + +noncomputable def cupSpecialize {ι : Type*} (a b : ι) : + MvPolynomial ι ℂ →+* MvPolynomial ι ℂ := + eval₂Hom C (fun i => if i=b then C T*X a else X i) + +@[simp] theorem cupSpecialize_C {ι : Type*} (a b : ι) (z : ℂ) : + cupSpecialize a b (C z)=C z := by simp [cupSpecialize] +@[simp] theorem cupSpecialize_X {ι : Type*} (a b i : ι) : + cupSpecialize a b (X i)=if i=b then C T*X a else X i := by simp [cupSpecialize] + +@[simp] theorem eval_cupSpecialize {ι : Type*} (a b : ι) (Y : ι → ℂ) (p : MvPolynomial ι ℂ) : + eval Y (cupSpecialize a b p)=eval (Function.update Y b (T*Y a)) p := by + change eval Y (eval₂ C (fun i => if i=b then C T*X a else X i) p)=_ + rw [eval_eval₂] + have hc : (eval Y).comp C=RingHom.id ℂ := by ext z; simp + rw [hc] + congr 2 + funext i + split_ifs <;> simp_all + +theorem T_ne_one : T≠1 := by + intro h + have hh := congrArg (fun z : ℂ => z^4) h + norm_num [T,t,← pow_mul,q_pow_24] at hh + +theorem cupSpecialize_X_ne_zero {ι : Type*} (a b i : ι) : cupSpecialize a b (X i)≠0 := by + rw [cupSpecialize_X] + split_ifs + · exact mul_ne_zero (C_ne_zero.mpr T_ne_zero) (X_ne_zero a) + · exact X_ne_zero i + +theorem scaled_X_ne_X {ι : Type*} (a k : ι) : (C T*X a : MvPolynomial ι ℂ)≠X k := by + by_cases h : k=a + · subst k + intro he + have hh := congrArg (eval (fun _ => (1:ℂ))) he + simp only [map_mul,eval_C,eval_X,mul_one] at hh + exact T_ne_one hh + · intro he + have hh := congrArg (eval (fun i => if i=k then (1:ℂ) else 0)) he + simp only [map_mul,eval_C,eval_X,ite_eq_right (Ne.symm h),ite_true,mul_zero] at hh + exact zero_ne_one hh + +theorem cupSpecialize_difference_ne_zero {ι : Type*} (a b : ι) {i j : ι} + (hij : i≠j) : cupSpecialize a b (X i-X j)≠0 := by + rw [map_sub,cupSpecialize_X,cupSpecialize_X,sub_ne_zero] + by_cases hi : i=b + · subst i + simp only [ite_true,ite_eq_right (Ne.symm hij)] + exact scaled_X_ne_X a j + · by_cases hj : j=b + · subst j + simp only [ite_true,ite_eq_right hi] + exact Ne.symm (scaled_X_ne_X a i) + · simp only [ite_eq_right hi,ite_eq_right hj] + exact fun h => hij (X_injective h) + +noncomputable def distinctGuard {ι : Type*} (S : Finset ι) : MvPolynomial ι ℂ := + (∏ i ∈ S, X i) * ∏ i ∈ S, ∏ j ∈ S.erase i, (X i-X j) + +theorem cupSpecialize_distinctGuard_ne_zero {ι : Type*} (a b : ι) (S : Finset ι) : + cupSpecialize a b (distinctGuard S)≠0 := by + simp only [distinctGuard,map_mul,map_prod] + apply mul_ne_zero + · exact Finset.prod_ne_zero_iff.mpr (fun i _ => cupSpecialize_X_ne_zero a b i) + · apply Finset.prod_ne_zero_iff.mpr + intro i hi + apply Finset.prod_ne_zero_iff.mpr + intro j hj + exact cupSpecialize_difference_ne_zero a b (Ne.symm (Finset.mem_erase.mp hj).1) + +theorem eval_distinctGuard_good {ι : Type*} (S : Finset ι) (Y : ι → ℂ) + (h : eval Y (distinctGuard S)≠0) : + (∀ i ∈ S, Y i≠0) ∧ Set.InjOn Y (S : Set ι) := by + simp only [distinctGuard,map_mul,map_prod,map_sub,eval_X] at h + obtain ⟨h0,h1⟩:=mul_ne_zero_iff.mp h + refine ⟨fun i hi => Finset.prod_ne_zero_iff.mp h0 i hi,?_⟩ + intro i hi j hj he + by_contra hij + have hn := Finset.prod_ne_zero_iff.mp (Finset.prod_ne_zero_iff.mp h1 i hi) j + (Finset.mem_erase.mpr ⟨Ne.symm hij,hj⟩) + exact hn (sub_eq_zero.mpr he) + +end PolynomialVacuumAlgebra + +end OAI diff --git a/lean/OAI/Combinatorics/PolynomialVacuum/Algebra/CupSurfaceInterpolation.lean b/lean/OAI/Combinatorics/PolynomialVacuum/Algebra/CupSurfaceInterpolation.lean new file mode 100644 index 0000000000000000000000000000000000000000..5159ace01cbb22959180e244437dfc233ded12e7 --- /dev/null +++ b/lean/OAI/Combinatorics/PolynomialVacuum/Algebra/CupSurfaceInterpolation.lean @@ -0,0 +1,97 @@ +import OAI.Combinatorics.PolynomialVacuum.Algebra.CupSurface +import OAI.Combinatorics.PolynomialVacuum.Algebra.PolynomialSlice + +namespace OAI + +namespace PolynomialVacuumAlgebra +open MvPolynomial Classical + +theorem polynomial_eq_on_scaled_nodes {ι : Type*} (S : Finset ι) (Y : ι → ℂ) + (hY : Set.InjOn Y (S : Set ι)) (p r : Polynomial ℂ) + (hp : p.natDegree < S.card) (hr : r.natDegree < S.card) + (h : ∀ i ∈ S, p.eval (T*Y i)=r.eval (T*Y i)) : p=r := by + apply Polynomial.eq_of_degrees_lt_of_eval_index_eq S + (fun i hi j hj he => hY hi hj (mul_left_cancel₀ T_ne_zero he)) + · exact Polynomial.degree_le_natDegree.trans_lt (WithBot.coe_lt_coe.mpr hp) + · exact Polynomial.degree_le_natDegree.trans_lt (WithBot.coe_lt_coe.mpr hr) + · exact h + +theorem polynomial_eq_on_scaled_nodes_zero {ι : Type*} (S : Finset ι) (Y : ι → ℂ) + (hY : Set.InjOn Y (S : Set ι)) (h0 : ∀ i ∈ S, Y i≠0) (p r : Polynomial ℂ) + (hp : p.natDegree ≤ S.card) (hr : r.natDegree ≤ S.card) + (hz : p.eval 0=r.eval 0) (h : ∀ i ∈ S, p.eval (T*Y i)=r.eval (T*Y i)) : p=r := by + let Z : Option ι → ℂ := fun i => i.elim 0 (fun j => T*Y j) + let E : Finset (Option ι) := insert none (S.map ⟨some,Option.some_injective _⟩) + have hi : Set.InjOn Z (E : Set (Option ι)) := by + intro i hi j hj he + cases i with + | none => + cases j with + | none => rfl + | some j => + have hj' : j∈S := by simpa [E] using hj + exact False.elim ((mul_ne_zero T_ne_zero (h0 j hj')) he.symm) + | some i => + have hi' : i∈S := by simpa [E] using hi + cases j with + | none => exact False.elim ((mul_ne_zero T_ne_zero (h0 i hi')) he) + | some j => + have hj' : j∈S := by simpa [E] using hj + exact congrArg some (hY hi' hj' (mul_left_cancel₀ T_ne_zero he)) + have hc : E.card=S.card+1 := by simp [E] + apply Polynomial.eq_of_degrees_lt_of_eval_index_eq E hi + · rw [hc] + exact Polynomial.degree_le_natDegree.trans_lt (WithBot.coe_lt_coe.mpr (show p.natDegree < S.card+1 from by omega)) + · rw [hc] + exact Polynomial.degree_le_natDegree.trans_lt (WithBot.coe_lt_coe.mpr (show r.natDegree < S.card+1 from by omega)) + · intro i hi + cases i with + | none => exact hz + | some i => exact h i (by simpa [E] using hi) + +theorem cupSurface_eq_of_nodes {ι : Type*} (a b c : ι) (hab : a≠b) + (S : Finset ι) (p r : MvPolynomial ι ℂ) + (hp : p.degreeOf c < S.card) (hr : r.degreeOf c < S.card) + (h : ∀ Y, Y b=T*Y a → ∀ i ∈ S, + eval (Function.update Y c (T*Y i)) p=eval (Function.update Y c (T*Y i)) r) : + cupSpecialize a b p=cupSpecialize a b r := by + apply polynomial_eq_on_generic (cupSpecialize_distinctGuard_ne_zero a b S) + intro X hX + simp only [eval_cupSpecialize] at hX ⊢ + let Y := Function.update X b (T*X a) + have hY : Y b=T*Y a := by simp [Y,hab] + obtain ⟨h0,hi⟩ := eval_distinctGuard_good S Y hX + have he := polynomial_eq_on_scaled_nodes S Y hi (polynomialSlice c Y p) (polynomialSlice c Y r) + ((polynomialSlice_natDegree c Y p).trans_lt hp) ((polynomialSlice_natDegree c Y r).trans_lt hr) + (by intro i hi; simpa using h Y hY i hi) + have he' := congrArg (fun P : Polynomial ℂ => P.eval (Y c)) he + simpa only [eval_polynomialSlice,Function.update_eq_self] using he' + +theorem cupSurface_eq_of_nodes_zero {ι : Type*} (a b c : ι) (hab : a≠b) + (S : Finset ι) (p r : MvPolynomial ι ℂ) + (hp : p.degreeOf c ≤ S.card) (hr : r.degreeOf c ≤ S.card) + (hz : ∀ Y, Y b=T*Y a → eval (Function.update Y c 0) p=eval (Function.update Y c 0) r) + (h : ∀ Y, Y b=T*Y a → ∀ i ∈ S, + eval (Function.update Y c (T*Y i)) p=eval (Function.update Y c (T*Y i)) r) : + cupSpecialize a b p=cupSpecialize a b r := by + apply polynomial_eq_on_generic (cupSpecialize_distinctGuard_ne_zero a b S) + intro X hX + simp only [eval_cupSpecialize] at hX ⊢ + let Y := Function.update X b (T*X a) + have hY : Y b=T*Y a := by simp [Y,hab] + obtain ⟨h0,hi⟩ := eval_distinctGuard_good S Y hX + have he := polynomial_eq_on_scaled_nodes_zero S Y hi h0 (polynomialSlice c Y p) (polynomialSlice c Y r) + ((polynomialSlice_natDegree c Y p).trans hp) ((polynomialSlice_natDegree c Y r).trans hr) + (by simpa using hz Y hY) (by intro i hi; simpa using h Y hY i hi) + have he' := congrArg (fun P : Polynomial ℂ => P.eval (Y c)) he + simpa only [eval_polynomialSlice,Function.update_eq_self] using he' + +theorem eval_eq_of_cupSurface_eq {ι : Type*} (a b : ι) (p r : MvPolynomial ι ℂ) + (h : cupSpecialize a b p=cupSpecialize a b r) (Y : ι → ℂ) (hY : Y b=T*Y a) : + eval Y p=eval Y r := by + have he := congrArg (eval Y) h + simpa only [eval_cupSpecialize,← hY,Function.update_eq_self] using he + +end PolynomialVacuumAlgebra + +end OAI diff --git a/lean/OAI/Combinatorics/PolynomialVacuum/Algebra/CupTransport.lean b/lean/OAI/Combinatorics/PolynomialVacuum/Algebra/CupTransport.lean new file mode 100644 index 0000000000000000000000000000000000000000..bd59d14e9618103ecffb36787227939857d0c6bf --- /dev/null +++ b/lean/OAI/Combinatorics/PolynomialVacuum/Algebra/CupTransport.lean @@ -0,0 +1,71 @@ +import OAI.Combinatorics.PolynomialVacuum.Algebra.NaturalCovariance + +namespace OAI + +namespace PolynomialVacuumAlgebra +open Classical + +def insertOne {α : Type*} (i : ℕ) (a : α) (X : ℕ → α) : ℕ → α := + fun j => if j < i then X j else if j=i then a else X (j-1) + +@[simp] theorem insertOne_self {α : Type*} (i : ℕ) (a : α) (X : ℕ → α) : + insertOne i a X i=a := by simp [insertOne] +@[simp] theorem insertOne_next {α : Type*} (i : ℕ) (a : α) (X : ℕ → α) : + insertOne i a X (i+1)=X i := by simp [insertOne] + +theorem swapSite_insertOne {α : Type*} (i : ℕ) (a : α) (X : ℕ → α) : + swapSite i (insertOne i a X)=insertOne (i+1) a X := by + funext j + simp only [swapSite,Function.comp_apply,Equiv.swap_apply_def,insertOne] + split_ifs <;> congr 1 <;> omega + +noncomputable def trainDenominator (c : ℂ) (X : ℕ → ℂ) (k : ℕ) : ℕ → ℂ + | 0 => 1 + | m+1 => trainDenominator c X (k+1) m * exchangeDenominator c (X k) + + +theorem braidTrain_exchange {ψ : NatSpectralTensor} {n : ℕ} + (hψ : LowerExchange ψ n) (c : ℂ) (X : ℕ → ℂ) (k m : ℕ) (hkm : k+m < n) : + braidTrain c X k m (ψ (insertOne k c X))= + trainDenominator c X k m • ψ (insertOne (k+m) c X) := by + induction m generalizing k with + | zero => simp [braidTrain,trainDenominator] + | succ m ih => + have he := hψ k (by omega) (insertOne k c X) + simp only [insertOne_self,insertOne_next,swapSite_insertOne] at he + simp only [braidTrain,Module.End.mul_apply,he,map_smul,trainDenominator] + rw [ih (k+1) (by omega),smul_smul] + congr 1 <;> ring_nf + +theorem braidTrain_cup_after (i k m : ℕ) (hik : i+2 ≤ k) (c : ℂ) (X : ℕ → ℂ) : + braidTrain c X k m * cupLinear i = + cupLinear i * braidTrain c (skipTwo i X) (k-2) m := by + induction m generalizing k with + | zero => simp [braidTrain] + | succ m ih => + simp only [braidTrain,mul_assoc] + rw [siteR_cup_after hik,← mul_assoc,ih (k+1) (by omega)] + have hk : skipTwo i X (k-2)=X k := by + simp [skipTwo,show ¬k-2 < i by omega,show k-2+2=k by omega] + rw [show k+1-2=k-2+1 by omega,hk,mul_assoc] + +theorem skipTwo_skipTwo {α : Type*} {i j : ℕ} (hij : i+2 ≤ j) (X : ℕ → α) : + skipTwo (j-2) (skipTwo i X)=skipTwo i (skipTwo j X) := by + funext k + simp only [skipTwo] + split_ifs <;> congr 1 <;> omega + +theorem cupLinear_cup_after {i j : ℕ} (hij : i+2 ≤ j) : + cupLinear j * cupLinear i = cupLinear i * cupLinear (j-2) := by + ext W s + simp only [Module.End.mul_apply,cupLinear,LinearMap.coe_mk,AddHom.coe_mk] + have h0 : skipTwo j s i=s i := by simp [skipTwo,show i < j by omega] + have h1 : skipTwo j s (i+1)=s (i+1) := by simp [skipTwo,show i+1 < j by omega] + have h2 : skipTwo i s (j-2)=s j := by simp [skipTwo,show ¬j-2 < i by omega,show j-2+2=j by omega] + have h3 : skipTwo i s (j-2+1)=s (j+1) := by simp [skipTwo,show ¬j-2+1 < i by omega,show j-2+1+2=j+1 by omega] + rw [h0,h1,h2,h3,skipTwo_skipTwo hij] + ring + +end PolynomialVacuumAlgebra + +end OAI diff --git a/lean/OAI/Combinatorics/PolynomialVacuum/Algebra/CyclicBounds.lean b/lean/OAI/Combinatorics/PolynomialVacuum/Algebra/CyclicBounds.lean new file mode 100644 index 0000000000000000000000000000000000000000..a3d9116feb9d843886cab714d41a73ad4f2669ce --- /dev/null +++ b/lean/OAI/Combinatorics/PolynomialVacuum/Algebra/CyclicBounds.lean @@ -0,0 +1,53 @@ +import OAI.Combinatorics.PolynomialVacuum.Algebra.NaturalRotation + +namespace OAI + +namespace PolynomialVacuumAlgebra +open MvPolynomial Classical + +theorem rotatedPolynomial_degree {n : ℕ} (Ψ : State (n+1)) (s : ℕ → Spin) (j : ℕ) (hj : j natRotate n s a.val)).degreeOf ⟨j+1,by omega⟩ := by + have he := degreeOf_rename_of_injective (rotationIndex_injective n) + ⟨j+1,by omega⟩ (p := Ψ (fun a => natRotate n s a.val)) + simpa only [rotatedPolynomial,rotationIndex,Nat.add_eq_zero_iff,one_ne_zero,and_false,ite_false,Nat.add_sub_cancel] using he + +theorem cyclicDiscrepancy_degree {n : ℕ} (Ψ : State (n+1)) (d : ℕ) + (hd : ∀ s i, (Ψ s).degreeOf i ≤ d) (s : ℕ → Spin) (j : ℕ) (hj : j s a.val)).degreeOf ⟨j,by omega⟩ from + coordinatePolynomial_degree Ψ s ⟨j,by omega⟩] + exact hd _ _ + +theorem cyclicDiscrepancy_plus_degree {n : ℕ} (Ψ : State (n+1)) (d : ℕ) + (hd : ∀ s i, s i=Spin.plus → (Ψ s).degreeOf i ≤ d) + (s : ℕ → Spin) (j : ℕ) (hj : j s a.val)).degreeOf ⟨j,by omega⟩ from + coordinatePolynomial_degree Ψ s ⟨j,by omega⟩] + exact hd _ _ hs + +theorem cyclicDiscrepancy_minus_zero {n : ℕ} (Ψ : State (n+1)) (hz : MinusZero Ψ) + (s : ℕ → Spin) (j : ℕ) (hj : j fusionPair a (X j.val)) + +theorem naturalFusion_rotate {n j : ℕ} (hj : j simp [T_ne_zero] + +theorem exchangeDiscrepancy_root {n j : ℕ} (Ψ : State (n+2)) (ψ : State n) + (hex : LowerExchange (liftState Ψ) (n+1)) + (hexψ : LowerExchange (liftState ψ) n) + (hnode : NaturalCupNodes (liftState Ψ) (liftState ψ) n) + (hc : ∀ i≤n, CupAt (liftState Ψ) (liftState ψ) n i) + (hj : j < n) (s : ℕ → Spin) (Y : ℕ → ℂ) (k : ℕ) + (hk : k∈(Finset.range (n+2)).erase j) : + eval (Function.update Y j (cupRootScale j k*Y k)) (exchangeDiscrepancy Ψ n s)=0 := by + obtain ⟨hkj,hk⟩ := Finset.mem_erase.mp hk + have hk' := Finset.mem_range.mp hk + let Z := Function.update Y j (cupRootScale j k*Y k) + have hkZ : Z k=Y k := Function.update_of_ne hkj _ _ + have hjZ : Z j=cupRootScale j k*Y k := by simp [Z] + have he : exchangeDifference (liftState Ψ) n Z=0 := by + by_cases h : k hp u ⟨j,by omega⟩ (hu.trans hs)) + have hcard : ((Finset.range (n+2)).erase j).card=n+1 := by + rw [Finset.card_erase_of_mem (Finset.mem_range.mpr (by omega)),Finset.card_range] + omega + rw [hcard] + omega + · exact exchangeDiscrepancy_root Ψ ψ hex hexψ hnode hc hj s + +theorem exchangeDiscrepancy_minus_zero {n j : ℕ} (Ψ : State (n+2)) (ψ : State n) + (hex : LowerExchange (liftState Ψ) (n+1)) + (hexψ : LowerExchange (liftState ψ) n) + (hnode : NaturalCupNodes (liftState Ψ) (liftState ψ) n) + (hc : ∀ i≤n, CupAt (liftState Ψ) (liftState ψ) n i) + (hd : ∀ s i, (Ψ s).degreeOf i≤n+1) (hz : MinusZero Ψ) + (hj : j hd u _) + have hcard : ((Finset.range (n+2)).erase j).card=n+1 := by + rw [Finset.card_erase_of_mem (Finset.mem_range.mpr (by omega)),Finset.card_range] + omega + rwa [hcard] + · intro Y + exact exchangeDiscrepancy_spectator_minus_zero Ψ hj hz s hs _ (by simp) + · exact exchangeDiscrepancy_root Ψ ψ hex hexψ hnode hc hj s + +end PolynomialVacuumAlgebra + +end OAI diff --git a/lean/OAI/Combinatorics/PolynomialVacuum/Algebra/EmptyNonzero.lean b/lean/OAI/Combinatorics/PolynomialVacuum/Algebra/EmptyNonzero.lean new file mode 100644 index 0000000000000000000000000000000000000000..f1b0224a2b1b45b173d041f1a91acc60b8505bfb --- /dev/null +++ b/lean/OAI/Combinatorics/PolynomialVacuum/Algebra/EmptyNonzero.lean @@ -0,0 +1,32 @@ +import OAI.Combinatorics.PolynomialVacuum.Algebra.AllSizeInduction +import OAI.Combinatorics.PolynomialVacuum.Algebra.FiniteTranslation + +namespace OAI + +namespace PolynomialVacuumAlgebra +open MvPolynomial Classical + + + +theorem polynomialVacuum_empty_ne_zero (N : ℕ) : + polynomialVacuum N (fun _ => Spin.zero)≠0 := by + induction N with + | zero => simp [polynomialVacuum,vacuumZero] + | succ n ih => + intro hz + have hp : (∏ j : Fin n, (X j : MvPolynomial (Fin n) ℂ)) * + polynomialVacuum n (fun _ => Spin.zero)=0 := by + apply MvPolynomial.funext + intro Y + have he := finite_lastZero (polynomialVacuum (n+1)) (polynomialVacuum n) + ((polynomialVacuum_at (n+1)).lastZero n rfl) + (fun _ => Spin.zero) (Fin.snoc Y 0) rfl (by simp) + rw [hz,map_zero] at he + simpa [Function.comp_def] using he.symm + have hprod : (∏ j : Fin n, (X j : MvPolynomial (Fin n) ℂ))≠0 := + Finset.prod_ne_zero_iff.mpr (fun j _ => X_ne_zero j) + exact ih ((mul_eq_zero.mp hp).resolve_left hprod) + +end PolynomialVacuumAlgebra + +end OAI diff --git a/lean/OAI/Combinatorics/PolynomialVacuum/Algebra/ExchangeDegrees.lean b/lean/OAI/Combinatorics/PolynomialVacuum/Algebra/ExchangeDegrees.lean new file mode 100644 index 0000000000000000000000000000000000000000..4b6354522a978ca8881152a812ae85d798f53a2d --- /dev/null +++ b/lean/OAI/Combinatorics/PolynomialVacuum/Algebra/ExchangeDegrees.lean @@ -0,0 +1,72 @@ +import OAI.Combinatorics.PolynomialVacuum.Algebra.Triangularity + +namespace OAI + +namespace PolynomialVacuumAlgebra +open MvPolynomial Classical + +section Degrees +variable {ι : Type*} {i : ι} {p r : MvPolynomial ι ℂ} {a b : ℕ} + +theorem dadd (hp : p.degreeOf i ≤ a) (hr : r.degreeOf i ≤ a) : + (p+r).degreeOf i ≤ a := (degreeOf_add_le _ _ _).trans (max_le hp hr) + +theorem dmul (hp : p.degreeOf i ≤ a) (hr : r.degreeOf i ≤ b) : + (p*r).degreeOf i ≤ a+b := (degreeOf_mul_le _ _ _).trans (Nat.add_le_add hp hr) + +theorem dpow (hp : p.degreeOf i ≤ a) (k : ℕ) : + (p^k).degreeOf i ≤ k*a := (degreeOf_pow_le _ _ _).trans (Nat.mul_le_mul_left _ hp) + +theorem dconst_mul (c : ℂ) (hp : p.degreeOf i ≤ a) : + (C c*p).degreeOf i ≤ a := (degreeOf_C_mul_le _ _ _).trans hp + +theorem dmul_const (c : ℂ) (hp : p.degreeOf i ≤ a) : + (p*C c).degreeOf i ≤ a := (degreeOf_mul_C_le _ _ _).trans hp + +end Degrees + +theorem polyExchange_degree {ι : Type*} (x y : MvPolynomial ι ℂ) (a b : Pair) + (i : ι) (d : ℕ) (hx : x.degreeOf i ≤ d) (hy : y.degreeOf i ≤ d) : + (polyExchangeNumerator x y a b).degreeOf i ≤ 2*d := by + rw [polyExchange_split] + apply dadd + · apply dadd + · exact dmul_const _ (dpow hx 2) + · simpa only [two_mul] using dmul_const (middleExchange a b) (dmul hx hy) + · exact dmul_const _ (dpow hy 2) + +theorem polyExchange_carried_loss {ι : Type*} (x y : MvPolynomial ι ℂ) (a b : Pair) + (i : ι) (hx : x.degreeOf i ≤ 1) (hy : y.degreeOf i=0) + (h : charge b.1 < charge a.2) : (polyExchangeNumerator x y a b).degreeOf i ≤ 1 := by + rw [polyExchange_split,exchange_top_carried a b h,map_zero,mul_zero,zero_add] + apply dadd + · simpa using dmul_const (middleExchange a b) (dmul hx (le_of_eq hy)) + · exact (dmul_const _ (dpow (le_of_eq hy) 2)).trans (by norm_num) + +theorem polyExchange_spectator_loss {ι : Type*} (x y : MvPolynomial ι ℂ) (a b : Pair) + (i : ι) (hx : x.degreeOf i=0) (hy : y.degreeOf i ≤ 1) + (h : charge b.2 < charge a.1) : (polyExchangeNumerator x y a b).degreeOf i ≤ 1 := by + rw [polyExchange_split,exchange_top_spectator a b h,map_zero,mul_zero,add_zero] + apply dadd + · exact (dmul_const _ (dpow (le_of_eq hx) 2)).trans (by norm_num) + · simpa using dmul_const (middleExchange a b) (dmul (le_of_eq hx) hy) + +theorem degreeOf_rename_missing {ι κ : Type*} (f : ι → κ) (p : MvPolynomial ι ℂ) + (j : κ) (h : ∀ i, f i≠j) : (rename f p).degreeOf j=0 := by + by_contra hn + obtain ⟨i,hi,he⟩ := mem_vars_rename f p (mem_vars_iff_degreeOf_ne_zero.mpr hn) + exact h i he + +theorem tensorExchange_degree {N : ℕ} {ι : Type*} (i j : Fin N) + (x y : MvPolynomial ι ℂ) (W : PolynomialTensor N ι) + (v : ι) (d k : ℕ) (hx : x.degreeOf v ≤ k) (hy : y.degreeOf v ≤ k) + (hW : ∀ s, (W s).degreeOf v ≤ d) (s : Fin N → Spin) : + (tensorExchange i j x y W s).degreeOf v ≤ d+2*k := by + apply (degreeOf_sum_le _ _ _).trans + apply Finset.sup_le + intro ab _ + exact (dmul (polyExchange_degree x y (s i,s j) ab v k hx hy) (hW _)).trans (by omega) + +end PolynomialVacuumAlgebra + +end OAI diff --git a/lean/OAI/Combinatorics/PolynomialVacuum/Algebra/ExchangeDifference.lean b/lean/OAI/Combinatorics/PolynomialVacuum/Algebra/ExchangeDifference.lean new file mode 100644 index 0000000000000000000000000000000000000000..f3612d4fc6964b879fcd7261d8f3727c7179ef86 --- /dev/null +++ b/lean/OAI/Combinatorics/PolynomialVacuum/Algebra/ExchangeDifference.lean @@ -0,0 +1,67 @@ +import OAI.Combinatorics.PolynomialVacuum.Algebra.ExchangeDiscrepancy + +namespace OAI + +namespace PolynomialVacuumAlgebra +open Classical + +noncomputable def exchangeDifference (Ψ : NatSpectralTensor) (n : ℕ) : NatSpectralTensor := + fun X => siteR n (X n) (X (n+1)) (Ψ X)- + exchangeDenominator (X n) (X (n+1)) • Ψ (swapSite n X) + +theorem swapSite_comm {α : Type*} {i j : ℕ} (h : i+1 < j) (X : ℕ → α) : + swapSite i (swapSite j X)=swapSite j (swapSite i X) := by + funext k + simp only [swapSite,Function.comp_apply,Equiv.swap_apply_def] + split_ifs <;> congr 1 <;> omega + +theorem exchangeDifference_exchanges {Ψ : NatSpectralTensor} {n : ℕ} + (hΨ : LowerExchange Ψ (n+1)) : LowerExchange (exchangeDifference Ψ n) n := by + intro j hj X + have h0 : swapSite j X n=X n := swapSite_other (by omega) (by omega) X + have h1 : swapSite j X (n+1)=X (n+1) := swapSite_other (by omega) (by omega) X + have h2 : swapSite n X j=X j := swapSite_other (by omega) (by omega) X + have h3 : swapSite n X (j+1)=X (j+1) := swapSite_other (by omega) (by omega) X + have he := hΨ j (by omega) (swapSite n X) + rw [h2,h3,swapSite_comm hj X] at he + simp only [exchangeDifference,map_sub,map_smul,h0,h1] + rw [← Module.End.mul_apply,siteR_far_comm (Or.inl hj),Module.End.mul_apply, + hΨ j (by omega) X,map_smul,he,smul_sub,smul_smul,smul_smul] + rw [mul_comm (exchangeDenominator (X n) (X (n+1)))] + +theorem skipTwo_swap_after {α : Type*} {i j : ℕ} (h : i+2 ≤ j) (X : ℕ → α) : + skipTwo i (swapSite j X)=swapSite (j-2) (skipTwo i X) := by + funext k + simp only [skipTwo,swapSite,Function.comp_apply,Equiv.swap_apply_def] + split_ifs <;> congr 1 <;> omega + +theorem fusionProduct_swap {j m : ℕ} (hj : j+1 < m) (a : ℂ) (X : ℕ → ℂ) : + fusionProduct a (swapSite j X) m=fusionProduct a X m := by + unfold fusionProduct + apply Finset.prod_equiv (Equiv.swap j (j+1)) + · intro k + simp only [Finset.mem_range,Equiv.swap_apply_def] + split_ifs <;> omega + · intro k hk + rfl + +theorem exchangeDifference_adjacentCup {Ψ ψ : NatSpectralTensor} {n i : ℕ} + (hi : i+1 < n) (hexψ : LowerExchange ψ n) + (hc : CupAt Ψ ψ n i) (X : ℕ → ℂ) (hX : X (i+1)=T*X i) : + exchangeDifference Ψ n X=0 := by + have h0 : swapSite n X i=X i := swapSite_other (by omega) (by omega) X + have h1 : swapSite n X (i+1)=X (i+1) := swapSite_other (by omega) (by omega) X + have hs : skipTwo i (swapSite n X)=swapSite (n-2) (skipTwo i X) := skipTwo_swap_after (by omega) X + have hf : naturalFusion n i (swapSite n X)=naturalFusion n i X := by + simp only [naturalFusion,h0,hs,fusionProduct_swap (by omega : n-2+1 < n)] + have he := hexψ (n-2) (by omega) (skipTwo i X) + have hy0 : skipTwo i X (n-2)=X n := by simp [skipTwo,show ¬n-2 < i by omega,show n-2+2=n by omega] + have hy1 : skipTwo i X (n-2+1)=X (n+1) := by simp [skipTwo,show ¬n-2+1 < i by omega,show n-2+1+2=n+1 by omega] + rw [hy0,hy1] at he + rw [exchangeDifference,hc X hX,hc (swapSite n X) (by simpa only [h0,h1] using hX),hf,map_smul, + ← Module.End.mul_apply,siteR_cup_after (by omega),Module.End.mul_apply,he,map_smul,hs] + simp only [smul_smul,mul_comm,sub_self] + +end PolynomialVacuumAlgebra + +end OAI diff --git a/lean/OAI/Combinatorics/PolynomialVacuum/Algebra/ExchangeDiscrepancy.lean b/lean/OAI/Combinatorics/PolynomialVacuum/Algebra/ExchangeDiscrepancy.lean new file mode 100644 index 0000000000000000000000000000000000000000..35b09e248bc77931aaba1ed7927c88bb89728197 --- /dev/null +++ b/lean/OAI/Combinatorics/PolynomialVacuum/Algebra/ExchangeDiscrepancy.lean @@ -0,0 +1,48 @@ +import OAI.Combinatorics.PolynomialVacuum.Algebra.CupSlidePolynomial + +namespace OAI + +namespace PolynomialVacuumAlgebra +open MvPolynomial Classical + +noncomputable def polyExchangeDenominator {ι : Type*} (x y : MvPolynomial ι ℂ) : + MvPolynomial ι ℂ := (C (t^2)*x-y)*(C T*x-y) + +@[simp] theorem eval_polyExchangeDenominator {ι : Type*} (Y : ι → ℂ) + (x y : MvPolynomial ι ℂ) : eval Y (polyExchangeDenominator x y)= + exchangeDenominator (eval Y x) (eval Y y) := by + simp [polyExchangeDenominator,exchangeDenominator] + +noncomputable def exchangeDiscrepancy {N : ℕ} (Ψ : State N) (j : ℕ) (s : ℕ → Spin) : + MvPolynomial ℕ ℂ := + (∑ ab : Pair, polyExchangeNumerator (X j) (X (j+1)) (s j,s (j+1)) ab * + coordinatePolynomial Ψ (replacePair s j (j+1) ab))- + polyExchangeDenominator (X j) (X (j+1))*rename (Equiv.swap j (j+1)) (coordinatePolynomial Ψ s) + +@[simp] theorem eval_exchangeDiscrepancy {N : ℕ} (Ψ : State N) (j : ℕ) (s : ℕ → Spin) + (Y : ℕ → ℂ) : eval Y (exchangeDiscrepancy Ψ j s)= + (siteR j (Y j) (Y (j+1)) (liftState Ψ Y)) s- + exchangeDenominator (Y j) (Y (j+1))*liftState Ψ (swapSite j Y) s := by + simp [exchangeDiscrepancy,siteR,pairLinear,pairAction,eval_rename,swapSite] + +theorem exchangeDiscrepancy_zero_iff {N : ℕ} (Ψ : State N) (j : ℕ) : + (∀ s, exchangeDiscrepancy Ψ j s=0) ↔ + ∀ Y, siteR j (Y j) (Y (j+1)) (liftState Ψ Y)= + exchangeDenominator (Y j) (Y (j+1)) • liftState Ψ (swapSite j Y) := by + constructor + · intro h Y + funext s + have he := congrArg (eval Y) (h s) + simpa only [eval_exchangeDiscrepancy,map_zero,sub_eq_zero,Pi.smul_apply,smul_eq_mul] using he + · intro h s + apply MvPolynomial.funext + intro Y + simp only [map_zero,eval_exchangeDiscrepancy] + exact sub_eq_zero.mpr (congrFun (h Y) s) + +noncomputable def partialTrainGuard (n i : ℕ) : MvPolynomial ℕ ℂ := + ∏ j ∈ Finset.range (n-i-1), polyExchangeDenominator (C T*X i) (X (i+1+j)) + +end PolynomialVacuumAlgebra + +end OAI diff --git a/lean/OAI/Combinatorics/PolynomialVacuum/Algebra/ExchangeDiscrepancyBounds.lean b/lean/OAI/Combinatorics/PolynomialVacuum/Algebra/ExchangeDiscrepancyBounds.lean new file mode 100644 index 0000000000000000000000000000000000000000..1624222c80a2e04d44815764287725446a5e254b --- /dev/null +++ b/lean/OAI/Combinatorics/PolynomialVacuum/Algebra/ExchangeDiscrepancyBounds.lean @@ -0,0 +1,70 @@ +import OAI.Combinatorics.PolynomialVacuum.Algebra.ExchangeDifference +import OAI.Combinatorics.PolynomialVacuum.Algebra.LastDegrees +import OAI.Combinatorics.PolynomialVacuum.Algebra.InterpolatedZero + +namespace OAI + +namespace PolynomialVacuumAlgebra +open MvPolynomial Classical + +theorem exchangeDiscrepancy_spectator_degree {n d j : ℕ} (Ψ : State (n+2)) + (hj : j < n) (s : ℕ → Spin) + (hd : ∀ u : Fin (n+2) → Spin, u ⟨j,by omega⟩=s j → (Ψ u).degreeOf ⟨j,by omega⟩ ≤ d) : + (exchangeDiscrepancy Ψ n s).degreeOf j ≤ d := by + have hdeg (u : ℕ → Spin) (hu : u j=s j) : (coordinatePolynomial Ψ u).degreeOf j ≤ d := by + rw [coordinatePolynomial_degree Ψ u ⟨j,by omega⟩] + exact hd _ hu + have hx : (X n : MvPolynomial ℕ ℂ).degreeOf j ≤ 0 := by simp [degreeOf_X_of_ne (by omega : j≠n)] + have hy : (X (n+1) : MvPolynomial ℕ ℂ).degreeOf j ≤ 0 := by simp [degreeOf_X_of_ne (by omega : j≠n+1)] + have hden : (polyExchangeDenominator (X n) (X (n+1)) : MvPolynomial ℕ ℂ).degreeOf j ≤ 0 := by + unfold polyExchangeDenominator + have hb (a : ℂ) : (C a*X n-X (n+1) : MvPolynomial ℕ ℂ).degreeOf j ≤ 0 := by + exact (degreeOf_sub_le _ _ _).trans (max_le (dconst_mul a hx) hy) + simpa only [Nat.zero_add] using dmul (hb (t^2)) (hb T) + unfold exchangeDiscrepancy + apply (degreeOf_sub_le _ _ _).trans + apply max_le + · apply (degreeOf_sum_le _ _ _).trans + apply Finset.sup_le + intro ab _ + exact (dmul (polyExchange_degree _ _ _ ab j 0 hx hy) + (hdeg _ (replacePair_other s (by omega) (by omega) ab))).trans (by omega) + · have hr : (rename (Equiv.swap n (n+1)) (coordinatePolynomial Ψ s)).degreeOf j= + (coordinatePolynomial Ψ s).degreeOf j := by + simpa only [Equiv.swap_apply_of_ne_of_ne (by omega : j≠n) (by omega : j≠n+1)] using + (degreeOf_rename_of_injective (Equiv.swap n (n+1)).injective j (p:=coordinatePolynomial Ψ s)) + exact (dmul hden (hr ▸ hdeg s rfl)).trans (by omega) + +theorem eval_liftState_minusZero {N : ℕ} (Ψ : State N) (hz : MinusZero Ψ) + (j : ℕ) (hj : j < N) (s : ℕ → Spin) (X : ℕ → ℂ) + (hs : s j=Spin.minus) (hX : X j=0) : liftState Ψ X s=0 := by + have he := congrArg (eval (fun k : Fin N => X k.val)) (hz (fun k => s k.val) ⟨j,hj⟩ hs) + simp only [eval_killSite,map_zero] at he + have hh : Function.update (fun k : Fin N => X k.val) ⟨j,hj⟩ 0=(fun k : Fin N => X k.val) := by + rw [← hX] + exact Function.update_eq_self _ _ + have hh' : @Function.update (Fin N) (fun _ => ℂ) (Classical.decEq _) (fun k => X k.val) ⟨j,hj⟩ 0=(fun k => X k.val) := by + funext k + by_cases h : k=⟨j,hj⟩ + · subst k; simp [hX] + · simp [h] + simpa only [hh',liftState,liftPolyTensor] using he + +theorem exchangeDiscrepancy_spectator_minus_zero {n j : ℕ} (Ψ : State (n+2)) + (hj : j < n) (hz : MinusZero Ψ) (s : ℕ → Spin) (hs : s j=Spin.minus) + (X : ℕ → ℂ) (hX : X j=0) : eval X (exchangeDiscrepancy Ψ n s)=0 := by + rw [eval_exchangeDiscrepancy] + have hr : liftState Ψ (swapSite n X) s=0 := + eval_liftState_minusZero Ψ hz j (by omega) s _ hs + (by simpa only [swapSite_other (by omega : j≠n) (by omega : j≠n+1)] using hX) + rw [hr,mul_zero,sub_zero] + change (∑ ab : Pair, exchangeNumerator (X n) (X (n+1)) (s n,s (n+1)) ab * + liftState Ψ X (replacePair s n (n+1) ab))=0 + apply Finset.sum_eq_zero + intro ab _ + rw [eval_liftState_minusZero Ψ hz j (by omega) _ X + (by simpa only [replacePair_other _ (by omega : j≠n) (by omega : j≠n+1)] using hs) hX,mul_zero] + +end PolynomialVacuumAlgebra + +end OAI diff --git a/lean/OAI/Combinatorics/PolynomialVacuum/Algebra/Existence.lean b/lean/OAI/Combinatorics/PolynomialVacuum/Algebra/Existence.lean new file mode 100644 index 0000000000000000000000000000000000000000..2afc3a97f8a67b3e7db74e32d4bbf289f95cc78b --- /dev/null +++ b/lean/OAI/Combinatorics/PolynomialVacuum/Algebra/Existence.lean @@ -0,0 +1,33 @@ +import OAI.Combinatorics.PolynomialVacuum.Algebra.FiniteTranslation + +namespace OAI + +namespace PolynomialVacuumAlgebra + + + +theorem polynomial_vacuum_is_vacuum : IsPolynomialVacuum polynomialVacuum := by + refine ⟨?_, ?_, ?_, ?_, ?_, ?_, ?_, ?_, ?_, ?_, ?_⟩ + · intro s; rfl + · intro s; rfl + · intro N s hs; exact (polynomialVacuum_at N).regular.charge s hs + · intro N s; exact (polynomialVacuum_at N).regular.homogeneous s + · intro N s i; exact (polynomialVacuum_at N).regular.degree s i + · intro N s i hi; exact (polynomialVacuum_at N).regular.plus s i hi + · intro N s i X hi hX + exact finite_minus_zero _ (polynomialVacuum_at N).regular.minus s i X hi hX + · intro n i s X + exact finite_exchange _ (polynomialVacuum_at (n+2)).regular.exchange i s X + · intro n s X + exact finite_cyclic _ ((polynomialVacuum_at (n+1)).cyclic n rfl) s X + · intro n i s X hX + exact finite_cup _ _ ((polynomialVacuum_at (n+2)).cups n rfl) i s X hX + · intro n s X hs hX + exact finite_lastZero _ _ ((polynomialVacuum_at (n+1)).lastZero n rfl) s X hs hX + +theorem polynomial_vacuum_exists : PolynomialVacuumExists := + ⟨polynomialVacuum, polynomial_vacuum_is_vacuum⟩ + +end PolynomialVacuumAlgebra + +end OAI diff --git a/lean/OAI/Combinatorics/PolynomialVacuum/Algebra/FinalCupZeros.lean b/lean/OAI/Combinatorics/PolynomialVacuum/Algebra/FinalCupZeros.lean new file mode 100644 index 0000000000000000000000000000000000000000..96cb3b24b0411a340d0e35297326d35f87a8deef --- /dev/null +++ b/lean/OAI/Combinatorics/PolynomialVacuum/Algebra/FinalCupZeros.lean @@ -0,0 +1,96 @@ +import OAI.Combinatorics.PolynomialVacuum.Algebra.PenultimateCup +import OAI.Combinatorics.PolynomialVacuum.Algebra.ExchangeDifference +import OAI.Combinatorics.PolynomialVacuum.Algebra.FirstCupInterpolation + +namespace OAI + +namespace PolynomialVacuumAlgebra +open MvPolynomial Classical + +@[simp] theorem eval_partialTrainGuard (n i : ℕ) (Y : ℕ → ℂ) : + eval Y (partialTrainGuard n i)=trainDenominator (T*Y i) Y (i+1) (n-i-1) := by + simp [partialTrainGuard,trainDenominator_prod] + +theorem partialTrainGuard_surface {n i : ℕ} (hi : i < n) : + cupSpecialize i n (partialTrainGuard n i)≠0 := by + intro he + have hv := congrArg (eval (fun j : ℕ => if j=i then (0:ℂ) else 1)) he + simp only [map_zero,eval_cupSpecialize,eval_partialTrainGuard,trainDenominator_prod] at hv + have hprod : (∏ j ∈ Finset.range (n-i-1), exchangeDenominator + (T*Function.update (fun k : ℕ => if k=i then (0:ℂ) else 1) n + (T*(if i=i then (0:ℂ) else 1)) i) + (Function.update (fun k : ℕ => if k=i then (0:ℂ) else 1) n + (T*(if i=i then (0:ℂ) else 1)) (i+1+j)))=1 := by + apply Finset.prod_eq_one + intro j hj + have hj' := Finset.mem_range.mp hj + simp [Function.update_of_ne (by omega : i≠n),Function.update_of_ne (by omega : i+1+j≠n), + show i+1+j≠i by omega,exchangeDenominator] + simp only [ite_true,update_nat_decidable] at hprod hv + rw [hprod] at hv + exact one_ne_zero hv + +theorem finalDifference_penultimate_generic {n i : ℕ} {Ψ ψ : NatSpectralTensor} + (hex : LowerExchange Ψ (n+1)) (hnode : NaturalCupNodes Ψ ψ n) + (hi : i < n) (hc : CupAt Ψ ψ n i) (X : ℕ → ℂ) (hX : X n=T*X i) + (hD : trainDenominator (T*X i) X (i+1) (n-i-1)≠0) + (hcross : siteR n (T*X i) (X (n+1)) (penultimatePrescription ψ n i X)= + exchangeDenominator (T*X i) (X (n+1)) • naturalPrescription ψ n i (swapSite n X)) : + exchangeDifference Ψ n X=0 := by + have hs : swapSite n X i=X i := swapSite_other (by omega) (by omega) X + unfold exchangeDifference + rw [penultimateCup_generic hex hi hc X hX hD,hX,hcross] + rw [hnode (swapSite n X) i (by omega) (by simpa only [swapSite_right,hs] using hX)] + exact sub_self _ + +theorem finalDifference_penultimate {n i : ℕ} (Ψ : State (n+2)) (ψ : State n) + (hex : LowerExchange (liftState Ψ) (n+1)) + (hnode : NaturalCupNodes (liftState Ψ) (liftState ψ) n) + (hi : i < n) (hc : CupAt (liftState Ψ) (liftState ψ) n i) + (X : ℕ → ℂ) (hX : X n=T*X i) : exchangeDifference (liftState Ψ) n X=0 := by + funext s + have he : cupSpecialize i n (exchangeDiscrepancy Ψ n s)=cupSpecialize i n 0 := by + apply cupSurface_eq_of_generic i n (by omega) _ _ (partialTrainGuard n i) (partialTrainGuard_surface hi) + intro Y hY hG + simp only [eval_exchangeDiscrepancy,map_zero] + exact congrFun (finalDifference_penultimate_generic hex hnode hi hc Y hY + (by simpa using hG) (penultimatePrescription_last_crossing ψ hi Y)) s + have he' := eval_eq_of_cupSurface_eq i n _ _ he X hX + simpa only [eval_exchangeDiscrepancy,map_zero,exchangeDifference,Pi.sub_apply,Pi.smul_apply,smul_eq_mul,Pi.zero_apply] using he' + +theorem reverseExchangeGuard_surface {n i : ℕ} (hi : i < n) : + cupSpecialize i (n+1) (polyExchangeDenominator (X (n+1)) (X n))≠0 := by + intro he + have hv := congrArg (eval (fun j : ℕ => if j=i then (0:ℂ) else 1)) he + simp [eval_cupSpecialize,show n≠i by omega,exchangeDenominator] at hv + +theorem finalDifference_last {n i : ℕ} (Ψ : State (n+2)) (ψ : State n) + (hex : LowerExchange (liftState Ψ) (n+1)) + (hnode : NaturalCupNodes (liftState Ψ) (liftState ψ) n) + (hi : i < n) (hc : CupAt (liftState Ψ) (liftState ψ) n i) + (X : ℕ → ℂ) (hX : X (n+1)=T*X i) : exchangeDifference (liftState Ψ) n X=0 := by + funext s + have he : cupSpecialize i (n+1) (exchangeDiscrepancy Ψ n s)=cupSpecialize i (n+1) 0 := by + apply cupSurface_eq_of_generic i (n+1) (by omega) _ _ + (polyExchangeDenominator (MvPolynomial.X (n+1)) (MvPolynomial.X n)) (reverseExchangeGuard_surface hi) + intro Y hY hG + simp only [eval_polyExchangeDenominator,eval_X] at hG + have hh := finalDifference_penultimate Ψ ψ hex hnode hi hc (swapSite n Y) + (by simpa only [swapSite_left,swapSite_other (by omega : i≠n) (by omega : i≠n+1)] using hY) + simp only [exchangeDifference,swapSite_left,swapSite_right,swapSite_twice,sub_eq_zero] at hh + have hh' := congrArg (siteR n (Y n) (Y (n+1))) hh + rw [siteR_unitary,map_smul] at hh' + have hs : exchangeDenominator (Y (n+1)) (Y n) • + (siteR n (Y n) (Y (n+1)) (liftState Ψ Y))= + exchangeDenominator (Y (n+1)) (Y n) • + (exchangeDenominator (Y n) (Y (n+1)) • liftState Ψ (swapSite n Y)) := by + simpa only [smul_smul,mul_comm] using hh'.symm + have hf := (smul_right_injective _ hG) hs + simp only [eval_exchangeDiscrepancy,map_zero] + exact sub_eq_zero.mpr (congrFun hf s) + have he' := eval_eq_of_cupSurface_eq i (n+1) _ _ he X hX + simpa only [eval_exchangeDiscrepancy,map_zero,exchangeDifference,Pi.sub_apply,Pi.smul_apply,smul_eq_mul,Pi.zero_apply] using he' + +end PolynomialVacuumAlgebra + +end OAI diff --git a/lean/OAI/Combinatorics/PolynomialVacuum/Algebra/FinalExchange.lean b/lean/OAI/Combinatorics/PolynomialVacuum/Algebra/FinalExchange.lean new file mode 100644 index 0000000000000000000000000000000000000000..c599cf57bc74440cd5d244a6865f417f84bc351a --- /dev/null +++ b/lean/OAI/Combinatorics/PolynomialVacuum/Algebra/FinalExchange.lean @@ -0,0 +1,57 @@ +import OAI.Combinatorics.PolynomialVacuum.Algebra.DiscrepancyRoots +import OAI.Combinatorics.PolynomialVacuum.Algebra.ZeroSpectatorPair + +namespace OAI + +namespace PolynomialVacuumAlgebra +open MvPolynomial Classical + + + +theorem finalExchange_of_cups {n : ℕ} (hn : 2≤n) (Ψ : State (n+2)) (ψ : State n) + (hex : LowerExchange (liftState Ψ) (n+1)) + (hexψ : LowerExchange (liftState ψ) n) + (hnode : NaturalCupNodes (liftState Ψ) (liftState ψ) n) + (hc : ∀ i≤n, CupAt (liftState Ψ) (liftState ψ) n i) + (hd : ∀ s i, (Ψ s).degreeOf i≤n+1) + (hp : ∀ s i, s i=Spin.plus → (Ψ s).degreeOf i≤n) (hz : MinusZero Ψ) : + ∀ Y, siteR n (Y n) (Y (n+1)) (liftState Ψ Y)= + exchangeDenominator (Y n) (Y (n+1)) • liftState Ψ (swapSite n Y) := by + apply (exchangeDiscrepancy_zero_iff Ψ n).mp + apply polynomial_zero_of_two_zero_spins + · have hf (j : ℕ) (hj : j exact (hs he).elim + | plus => exact exchangeDiscrepancy_plus_zero Ψ ψ hex hexψ hnode hc hp hj s he + | minus => exact exchangeDiscrepancy_minus_zero Ψ ψ hex hexψ hnode hc hd hz hj s he + intro s hs + rcases hs with hs|hs + · exact hf 0 (by omega) s hs + · exact hf 1 (by omega) s hs + · intro Y + have he := exchangeDifference_exchanges hex 0 (by omega) Y + have heval (X : ℕ → ℂ) : (fun s => eval X (exchangeDiscrepancy Ψ n s))= + exchangeDifference (liftState Ψ) n X := by + funext s + exact eval_exchangeDiscrepancy Ψ n s X + simpa only [heval] using he + +theorem fullExchange_of_cups {n : ℕ} (hn : 2≤n) (Ψ : State (n+2)) (ψ : State n) + (hex : LowerExchange (liftState Ψ) (n+1)) + (hexψ : LowerExchange (liftState ψ) n) + (hnode : NaturalCupNodes (liftState Ψ) (liftState ψ) n) + (hc : ∀ i≤n, CupAt (liftState Ψ) (liftState ψ) n i) + (hd : ∀ s i, (Ψ s).degreeOf i≤n+1) + (hp : ∀ s i, s i=Spin.plus → (Ψ s).degreeOf i≤n) (hz : MinusZero Ψ) : + LowerExchange (liftState Ψ) (n+2) := by + intro j hj + by_cases h : j+1 eval (fun j : Fin m => X j.val) (W (fun j : Fin N => s j.val)) + +noncomputable def liftState {n : ℕ} (ψ : State n) : NatSpectralTensor := + liftPolyTensor ψ + +theorem replacePair_restrict {N : ℕ} (i j : Fin N) (s : ℕ → Spin) (ab : Pair) : + (fun k : Fin N => replacePair s i.val j.val ab k.val) = + Function.update (Function.update (fun k : Fin N => s k.val) i ab.1) j ab.2 := by + funext k + simp only [replacePair,Function.update_apply,Fin.ext_iff] + +theorem liftPolyTensor_exchange {N m : ℕ} (i j : Fin N) + (x y : MvPolynomial (Fin m) ℂ) (W : PolynomialTensor N (Fin m)) (X : ℕ → ℂ) : + liftPolyTensor (tensorExchange i j x y W) X = + pairAction i.val j.val (exchangeNumerator (eval (fun k : Fin m => X k.val) x) + (eval (fun k : Fin m => X k.val) y)) (liftPolyTensor W X) := by + funext s + simp only [liftPolyTensor,tensorExchange,map_sum,map_mul,eval_polyExchangeNumerator,pairAction, + replacePair_restrict] + +theorem liftPolyTensor_initialCup {n : ℕ} (ψ : State n) (i : Fin (n+1)) (X : ℕ → ℂ) : + liftPolyTensor (initialCup ψ i) X=cupLinear i.val (liftState ψ (skipOne i.val X)) := by + funext s + simp only [liftPolyTensor,initialCup,map_mul,eval_C,eval_rename,cupLinear, + LinearMap.coe_mk,AddHom.coe_mk,liftState,pairLeft,pairRight] + congr 2 + apply congrArg eval + funext k + simp only [Function.comp_apply,skipOne,Fin.succAbove,Fin.lt_def,Fin.val_castSucc] + split_ifs <;> rfl + +end PolynomialVacuumAlgebra + +end OAI diff --git a/lean/OAI/Combinatorics/PolynomialVacuum/Algebra/FiniteTranslation.lean b/lean/OAI/Combinatorics/PolynomialVacuum/Algebra/FiniteTranslation.lean new file mode 100644 index 0000000000000000000000000000000000000000..8e42561f7e71aec914a6a35cbddf54df4f0e3a1e --- /dev/null +++ b/lean/OAI/Combinatorics/PolynomialVacuum/Algebra/FiniteTranslation.lean @@ -0,0 +1,141 @@ +import OAI.Combinatorics.PolynomialVacuum.Algebra.AllSizeInduction + +namespace OAI + +namespace PolynomialVacuumAlgebra +open MvPolynomial Classical + +@[simp] theorem liftState_extend {N : ℕ} (ψ : State N) (X : Fin N → ℂ) (s : Fin N → Spin) : + liftState ψ (extendFinite 0 X) (extendFinite Spin.zero s)=eval X (ψ s) := by + simp only [liftState,liftPolyTensor,extendFinite_fin] + +theorem finite_minus_zero {N : ℕ} (ψ : State N) (hz : MinusZero ψ) + (s : Fin N → Spin) (i : Fin N) (X : Fin N → ℂ) (hs : s i=Spin.minus) (hX : X i=0) : + eval X (ψ s)=0 := by + have he := congrArg (eval X) (hz s i hs) + have hsub : @Function.update (Fin N) (fun _ => ℂ) (Classical.decEq _) X i 0=X := by + funext j + simp only [Function.update_apply] + split_ifs with h + · subst j; exact hX.symm + · rfl + simpa only [eval_killSite,hsub,map_zero] using he + +theorem finite_exchange {n : ℕ} (ψ : State (n+2)) (hex : LowerExchange (liftState ψ) (n+2)) + (i : Fin (n+1)) (s : Fin (n+2) → Spin) (X : Fin (n+2) → ℂ) : + (∑ ab : Pair, exchangeNumerator (X (pairLeft i)) (X (pairRight i)) (s (pairLeft i),s (pairRight i)) ab * + eval X (ψ (Function.update (Function.update s (pairLeft i) ab.1) (pairRight i) ab.2))) = + exchangeDenominator (X (pairLeft i)) (X (pairRight i)) * + eval (X ∘ Equiv.swap (pairLeft i) (pairRight i)) (ψ s) := by + have he := congrFun (hex i.val (by have:=i.isLt; omega) (extendFinite 0 X)) (extendFinite Spin.zero s) + change (∑ ab : Pair, exchangeNumerator (extendFinite 0 X i.val) (extendFinite 0 X (i.val+1)) + (extendFinite Spin.zero s i.val,extendFinite Spin.zero s (i.val+1)) ab * + liftState ψ (extendFinite 0 X) (replacePair (extendFinite Spin.zero s) i.val (i.val+1) ab)) = + exchangeDenominator (extendFinite 0 X i.val) (extendFinite 0 X (i.val+1))* + liftState ψ (swapSite i.val (extendFinite 0 X)) (extendFinite Spin.zero s) at he + have hswap : (fun j : Fin (n+2) => swapSite i.val (extendFinite 0 X) j.val)=X ∘ Equiv.swap (pairLeft i) (pairRight i) := by + funext j + simp only [swapSite,Function.comp_apply,Equiv.swap_apply_def,Fin.ext_iff,pairLeft,pairRight,Fin.val_castSucc,Fin.val_succ] + split_ifs + · exact extendFinite_fin 0 X i.succ + · exact extendFinite_fin 0 X i.castSucc + · exact extendFinite_fin 0 X j + change (∑ ab : Pair, exchangeNumerator (extendFinite 0 X (pairLeft i).val) (extendFinite 0 X (pairRight i).val) + (extendFinite Spin.zero s (pairLeft i).val,extendFinite Spin.zero s (pairRight i).val) ab * + eval (fun j : Fin (n+2) => extendFinite 0 X j.val) + (ψ (fun j : Fin (n+2) => replacePair (extendFinite Spin.zero s) (pairLeft i).val (pairRight i).val ab j.val))) = + exchangeDenominator (extendFinite 0 X (pairLeft i).val) (extendFinite 0 X (pairRight i).val)* + eval (fun j : Fin (n+2) => swapSite i.val (extendFinite 0 X) j.val) + (ψ (fun j : Fin (n+2) => extendFinite Spin.zero s j.val)) at he + simpa only [replacePair_restrict,extendFinite_fin,hswap] using he + +theorem rotationIndex_finite (n : ℕ) (j : Fin (n+1)) : + rotationIndex n j.val=((finRotate (n+1)).symm j).val := by + by_cases hj : j=0 + · subst j + have h : (finRotate (n+1)).symm 0=Fin.last n := (Equiv.symm_apply_eq _).mpr finRotate_last.symm + rw [h]; simp [rotationIndex] + · rw [coe_finRotate_symm_of_ne_zero hj] + simp [rotationIndex,show j.val≠0 from by intro h; exact hj (Fin.ext h)] + +theorem natRotate_extend {α : Type*} {n : ℕ} (a : α) (X : Fin (n+1) → α) : + (fun j : Fin (n+1) => natRotate n (extendFinite a X) j.val)=X ∘ (finRotate (n+1)).symm := by + funext j + simp only [natRotate,Function.comp_apply,rotationIndex_finite,extendFinite_fin] + +theorem finite_cyclic {n : ℕ} (ψ : State (n+1)) (hcy : NaturalCyclic n (liftState ψ)) + (s : Fin (n+1) → Spin) (X : Fin (n+1) → ℂ) : + zeta^charge (s 0)*eval X (ψ (s ∘ finRotate (n+1))) = + eval (X ∘ (finRotate (n+1)).symm) (ψ s) := by + have he := congrFun (hcy (extendFinite 0 X)) (extendFinite Spin.zero (s ∘ finRotate (n+1))) + change zeta ^ (-charge (extendFinite Spin.zero (s ∘ finRotate (n+1)) n))* + liftState ψ (natRotate n (extendFinite 0 X)) (natRotate n (extendFinite Spin.zero (s ∘ finRotate (n+1)))) = + liftState ψ (extendFinite 0 X) (extendFinite Spin.zero (s ∘ finRotate (n+1))) at he + have hlast : extendFinite Spin.zero (s ∘ finRotate (n+1)) n=s 0 := by + change extendFinite Spin.zero (s ∘ finRotate (n+1)) (Fin.last n).val=s 0 + simp only [extendFinite_fin,Function.comp_apply,finRotate_last] + rw [hlast] at he + simp only [liftState,liftPolyTensor,natRotate_extend,extendFinite_fin, + Function.comp_assoc,Equiv.self_comp_symm,Function.comp_id] at he + change zeta ^ (-charge (s 0))*eval (X ∘ (finRotate (n+1)).symm) (ψ s)=eval X (ψ (s ∘ finRotate (n+1))) at he + rw [← he,← mul_assoc,← zpow_add₀ (by exact pow_ne_zero _ (pow_ne_zero _ q_ne_zero) : zeta≠0)] + simp + +theorem skipTwo_extend {α : Type*} {n : ℕ} (a : α) (X : Fin (n+2) → α) (i : Fin (n+1)) : + (fun j : Fin n => skipTwo i.val (extendFinite a X) j.val)=X ∘ omitPair i := by + funext j + simp only [skipTwo,Function.comp_apply,omitPair] + have hj : j.val simp [extendFinite,hj,hj2] + +theorem naturalFusion_finite {n : ℕ} (X : Fin (n+2) → ℂ) (i : Fin (n+1)) : + naturalFusion n i.val (extendFinite 0 X)=fusionScalar (X (pairLeft i)) (X ∘ omitPair i) := by + unfold naturalFusion fusionProduct fusionScalar + rw [← Fin.prod_univ_eq_prod_range] + have hi : i.val=(pairLeft i).val := rfl + simp only [hi,extendFinite_fin] + congr 1 + apply Finset.prod_congr rfl + intro j hj + have he := congrFun (skipTwo_extend 0 X i) j + change (skipTwo i.val (extendFinite 0 X) j.val-t^5*X (pairLeft i))* + (skipTwo i.val (extendFinite 0 X) j.val-t^6*X (pairLeft i))=_ + rw [he] + +theorem finite_cup {n : ℕ} (Ψ : State (n+2)) (ψ : State n) + (hc : ∀ i≤n, CupAt (liftState Ψ) (liftState ψ) n i) + (i : Fin (n+1)) (s : Fin (n+2) → Spin) (X : Fin (n+2) → ℂ) + (hX : X (pairRight i)=T*X (pairLeft i)) : + eval X (Ψ s)=fusionScalar (X (pairLeft i)) (X ∘ omitPair i)* + cup (s (pairLeft i),s (pairRight i))*eval (X ∘ omitPair i) (ψ (s ∘ omitPair i)) := by + have hXi : extendFinite 0 X (i.val+1)=T*extendFinite 0 X i.val := by + change extendFinite 0 X (pairRight i).val=T*extendFinite 0 X (pairLeft i).val + simpa only [extendFinite_fin] using hX + have he := congrFun (hc i.val (by have:=i.isLt; omega) (extendFinite 0 X) hXi) (extendFinite Spin.zero s) + change liftState Ψ (extendFinite 0 X) (extendFinite Spin.zero s)= + naturalFusion n i.val (extendFinite 0 X)*(cup (extendFinite Spin.zero s (pairLeft i).val, + extendFinite Spin.zero s (pairRight i).val)*liftState ψ (skipTwo i.val (extendFinite 0 X)) + (skipTwo i.val (extendFinite Spin.zero s))) at he + simpa only [liftState_extend,naturalFusion_finite,extendFinite_fin,liftState,liftPolyTensor,skipTwo_extend,mul_assoc] using he + +theorem finite_lastZero {n : ℕ} (Ψ : State (n+1)) (ψ : State n) + (hz : LastZeroReduction (liftState Ψ) (liftState ψ) n) + (s : Fin (n+1) → Spin) (X : Fin (n+1) → ℂ) + (hs : s (Fin.last n)=Spin.zero) (hX : X (Fin.last n)=0) : + eval X (Ψ s)=(∏ j : Fin n, X j.castSucc)*eval (X ∘ Fin.castSucc) (ψ (s ∘ Fin.castSucc)) := by + have hsn : extendFinite Spin.zero s n=Spin.zero := by + change extendFinite Spin.zero s (Fin.last n).val=Spin.zero + simpa only [extendFinite_fin] using hs + have hXn : extendFinite 0 X n=0 := by + change extendFinite 0 X (Fin.last n).val=0 + simpa only [extendFinite_fin] using hX + have he := hz (extendFinite 0 X) (extendFinite Spin.zero s) hXn (by rw [hsn]; decide) + rw [hsn,ite_eq_left rfl,liftState_extend] at he + simp only [prefixProduct,← Fin.prod_univ_eq_prod_range,liftState,liftPolyTensor] at he + simpa only [Function.comp_def, show ∀ j : Fin n, extendFinite 0 X j.val=X j.castSucc from fun j => extendFinite_fin 0 X j.castSucc, + show ∀ j : Fin n, extendFinite Spin.zero s j.val=s j.castSucc from fun j => extendFinite_fin Spin.zero s j.castSucc] using he + +end PolynomialVacuumAlgebra + +end OAI diff --git a/lean/OAI/Combinatorics/PolynomialVacuum/Algebra/FirstCupInterpolation.lean b/lean/OAI/Combinatorics/PolynomialVacuum/Algebra/FirstCupInterpolation.lean new file mode 100644 index 0000000000000000000000000000000000000000..dfbd1b190bd181fe3d9591c2eac7a34437265400 --- /dev/null +++ b/lean/OAI/Combinatorics/PolynomialVacuum/Algebra/FirstCupInterpolation.lean @@ -0,0 +1,83 @@ +import OAI.Combinatorics.PolynomialVacuum.Algebra.FirstCupPolynomial +import OAI.Combinatorics.PolynomialVacuum.Algebra.FirstCupNodeAssembly + +namespace OAI + +namespace PolynomialVacuumAlgebra +open MvPolynomial Classical + +theorem update_nat_decidable (Y : ℕ → ℂ) (c : ℕ) (v : ℂ) : + @Function.update ℕ (fun _ => ℂ) (fun a b => Classical.propDecidable (a=b)) Y c v= + @Function.update ℕ (fun _ => ℂ) instDecidableEqNat Y c v := by + funext k + by_cases h : k=c <;> simp [h] + +noncomputable def coordinatePolynomial {n : ℕ} (ψ : State n) (s : ℕ → Spin) : + MvPolynomial ℕ ℂ := rename Fin.val (ψ (fun j => s j.val)) + +@[simp] theorem eval_coordinatePolynomial {n : ℕ} (ψ : State n) (s : ℕ → Spin) (X : ℕ → ℂ) : + eval X (coordinatePolynomial ψ s)=liftState ψ X s := by + simp [coordinatePolynomial,eval_rename,liftState,liftPolyTensor,Function.comp_def] + +theorem coordinatePolynomial_degree {n : ℕ} (ψ : State n) (s : ℕ → Spin) (i : Fin n) : + (coordinatePolynomial ψ s).degreeOf i.val=(ψ (fun j => s j.val)).degreeOf i := by + exact degreeOf_rename_of_injective Fin.val_injective _ + + + +theorem firstCup_of_nodes {n : ℕ} (Ψ : State (n+4)) (ψ : State (n+2)) + (hd : ∀ s, (Ψ s).degreeOf (Fin.last (n+3)) ≤ n+3) + (hf : ∀ s, s (Fin.last (n+3))=Spin.plus → (Ψ s).degreeOf (Fin.last (n+3)) ≤ n+2) + (hψd : ∀ s, (ψ s).degreeOf (Fin.last (n+1)) ≤ n+1) + (hψf : ∀ s, s (Fin.last (n+1))=Spin.plus → (ψ s).degreeOf (Fin.last (n+1)) ≤ n) + (hnode : ∀ X, X 1=T*X 0 → ∀ i ≤ n+2, X (n+3)=T*X i → + liftState Ψ X=naturalFusion (n+2) 0 X • cupLinear 0 (liftState ψ (skipTwo 0 X))) + (hz : ∀ X s, X 1=T*X 0 → X (n+3)=0 → s (n+3)≠Spin.plus → + liftState Ψ X s=(naturalFusion (n+2) 0 X • cupLinear 0 (liftState ψ (skipTwo 0 X))) s) : + FirstCupReduction (liftState Ψ) (liftState ψ) (n+2) := by + classical + intro X hX + rw [← lift_firstCupState] + funext s + let p := coordinatePolynomial Ψ s + let r := coordinatePolynomial (firstCupState ψ) s + have hp : p.degreeOf (n+3) ≤ n+3 := by + rw [show p.degreeOf (n+3)=(Ψ (fun j => s j.val)).degreeOf (Fin.last (n+3)) from + coordinatePolynomial_degree Ψ s (Fin.last (n+3))] + exact hd _ + have hr (d : ℕ) (h : (ψ (fun j => s (j.val+2))).degreeOf (Fin.last (n+1)) ≤ d) : + r.degreeOf (n+3) ≤ d+2 := by + rw [show r.degreeOf (n+3)=(firstCupState ψ (fun j => s j.val)).degreeOf (Fin.last (n+3)) from + coordinatePolynomial_degree (firstCupState ψ) s (Fin.last (n+3))] + exact firstCupState_last_degree ψ _ _ (by simpa only [Fin.val_succ,Nat.add_assoc,Nat.reduceAdd] using h) + have hn : ∀ Y, Y 1=T*Y 0 → ∀ i ∈ Finset.range (n+3), + eval (Function.update Y (n+3) (T*Y i)) p=eval (Function.update Y (n+3) (T*Y i)) r := by + intro Y hY i hi + let Z := Function.update Y (n+3) (T*Y i) + have hZi : Z i=Y i := by simp [Z,Function.update_of_ne (by have:=Finset.mem_range.mp hi; omega : i≠n+3)] + have he := congrFun (hnode Z (by simpa [Z] using hY) i (by have:=Finset.mem_range.mp hi; omega) + (by simp [Z,hZi])) s + simpa only [p,r,eval_coordinatePolynomial,lift_firstCupState,update_nat_decidable] using he + have he : cupSpecialize 0 1 p=cupSpecialize 0 1 r := by + by_cases hs : s (n+3)=Spin.plus + · apply cupSurface_eq_of_nodes 0 1 (n+3) (by omega) (Finset.range (n+3)) p r + · simpa only [Finset.card_range] using (show p.degreeOf (n+3) s j.val) hs + rw [← coordinatePolynomial_degree Ψ s (Fin.last (n+3))] at hh + exact hh.trans_lt (by omega)) + · simpa only [Finset.card_range] using (hr n (hψf _ hs)).trans_lt (by omega : n+2 + C ((1+T)*cup (s 0,s 1))*X 0 * + (∏ j : Fin n, (X j.succ.succ-C (t^5)*X 0)*(X j.succ.succ-C (t^6)*X 0)) * + rename (fun j : Fin n => j.succ.succ) (ψ (fun j => s j.succ.succ)) + +theorem lift_firstCupState {n : ℕ} (ψ : State n) (Xv : ℕ → ℂ) : + liftState (firstCupState ψ) Xv= + naturalFusion n 0 Xv • cupLinear 0 (liftState ψ (skipTwo 0 Xv)) := by + funext s + simp only [liftState,liftPolyTensor,firstCupState,map_mul,map_prod,map_sub,eval_C, + eval_X,eval_rename,Fin.val_succ,naturalFusion,fusionProduct, + fusionPair,skipTwo_zero_apply,Pi.smul_apply,smul_eq_mul,cupLinear,LinearMap.coe_mk, + AddHom.coe_mk] + simp only [Function.comp_def,Fin.val_succ,Fin.val_zero,Fin.val_one,Nat.add_assoc,Nat.reduceAdd,Nat.zero_add] + rw [Fin.prod_univ_eq_prod_range (fun k => (Xv (k+2)-t^5*Xv 0)*(Xv (k+2)-t^6*Xv 0)) n] + ring + +theorem firstCupState_last_degree {n : ℕ} (ψ : State (n+1)) (s : Fin (n+3) → Spin) + (d : ℕ) (hd : (ψ (fun j => s j.succ.succ)).degreeOf (Fin.last n) ≤ d) : + (firstCupState ψ s).degreeOf (Fin.last (n+2)) ≤ d+2 := by + have hh : ((Fin.last n).succ.succ : Fin (n+3))=Fin.last (n+2) := rfl + have hr : (rename (fun j : Fin (n+1) => j.succ.succ) + (ψ (fun j => s j.succ.succ))).degreeOf (Fin.last (n+2)) ≤ d := by + rw [← hh,degreeOf_rename_of_injective (fun _ _ h => (Fin.succ_injective _) ((Fin.succ_injective _) h))] + exact hd + have h0 : (X (0 : Fin (n+3)) : MvPolynomial (Fin (n+3)) ℂ).degreeOf (Fin.last (n+2)) ≤ 0 := by + exact le_of_eq (degreeOf_X_of_ne (by intro h; have:=congrArg Fin.val h; simp at this)) + have hc (k : ℕ) : (C (t^k)*X (0 : Fin (n+3)) : MvPolynomial (Fin (n+3)) ℂ).degreeOf (Fin.last (n+2)) ≤ 0 := + dconst_mul _ h0 + have hf (j : Fin (n+1)) : + ((X j.succ.succ-C (t^5)*X 0)*(X j.succ.succ-C (t^6)*X 0) : MvPolynomial (Fin (n+3)) ℂ).degreeOf (Fin.last (n+2)) ≤ if j=Fin.last n then 2 else 0 := by + by_cases hj : j=Fin.last n + · subst j + simp only [ite_true] + apply (dmul (a:=1) (b:=1) ?_ ?_).trans (by omega) + all_goals rw [sub_eq_add_neg]; apply dadd (by simp); rw [degreeOf_neg]; exact (hc _).trans (by omega) + · simp only [ite_eq_right hj] + have hx : (X j.succ.succ : MvPolynomial (Fin (n+3)) ℂ).degreeOf (Fin.last (n+2)) ≤ 0 := by + exact le_of_eq (degreeOf_X_of_ne (by + intro he + have hv : n+2=j.val+1+1 := congrArg Fin.val he + exact hj (Fin.ext (show j.val=n from by omega)))) + apply dmul (a:=0) (b:=0) + all_goals rw [sub_eq_add_neg]; exact dadd hx (by rw [degreeOf_neg]; exact hc _) + have hp : (∏ j : Fin (n+1), (X j.succ.succ-C (t^5)*X 0)*(X j.succ.succ-C (t^6)*X 0) : MvPolynomial (Fin (n+3)) ℂ).degreeOf (Fin.last (n+2)) ≤ 2 := by + apply (degreeOf_prod_le _ _ _).trans + exact (Finset.sum_le_sum (fun j _ => hf j)).trans (by simp) + exact (dmul (dmul (dconst_mul _ h0) hp) hr).trans (by omega) + +end PolynomialVacuumAlgebra + +end OAI diff --git a/lean/OAI/Combinatorics/PolynomialVacuum/Algebra/FirstCupRegularNode.lean b/lean/OAI/Combinatorics/PolynomialVacuum/Algebra/FirstCupRegularNode.lean new file mode 100644 index 0000000000000000000000000000000000000000..34ff927dd48f37209b0dc8ac3e5034670149f6e6 --- /dev/null +++ b/lean/OAI/Combinatorics/PolynomialVacuum/Algebra/FirstCupRegularNode.lean @@ -0,0 +1,50 @@ +import OAI.Combinatorics.PolynomialVacuum.Algebra.CupScalarCompatibility +import OAI.Combinatorics.PolynomialVacuum.Algebra.NaturalUnitary + +namespace OAI + +namespace PolynomialVacuumAlgebra +open Classical + +theorem trainDenominator_fusionProduct (a : ℂ) (X : ℕ → ℂ) (k m : ℕ) : + trainDenominator (T*a) X k m=fusionProduct a (fun r => X (k+r)) m := by + induction m generalizing k with + | zero => simp [trainDenominator,fusionProduct] + | succ m ih => + simp only [trainDenominator,ih,← fusionPair_denominator,fusionProduct, + Finset.prod_range_succ',Nat.add_zero] + congr 1 + apply Finset.prod_congr rfl + intro r hr + rw [show k+1+r=k+(r+1) by omega] + +theorem skipOne_eq_insertOne {α : Type*} (X : ℕ → α) : + skipOne 0 X=insertOne 0 (X 1) (skipTwo 0 X) := by + funext j + simp only [skipOne,insertOne,skipTwo_zero_apply,Nat.not_lt_zero,ite_false] + split_ifs <;> congr 1 <;> omega + + + +theorem naturalPrescription_firstCup_regular {ψ : NatSpectralTensor} {m : ℕ} + (hψ : LowerExchange ψ (m+1)) (X : ℕ → ℂ) (hX : X 1=T*X 0) : + naturalPrescription ψ (m+1) 0 X= + naturalFusion (m+1) 0 (insertOne (m+2) (T*X 0) X) • + cupLinear 0 (ψ (skipTwo 0 (insertOne (m+2) (T*X 0) X))) := by + have hx : insertOne (m+2) (T*X 0) X 0=X 0 := by simp [insertOne] + have he := braidTrain_exchange hψ (T*X 0) (skipTwo 0 X) 0 m (by omega) + simp only [Nat.zero_add] at he + have ho : braidTrain (T*X 0) X 2 m * cupLinear 0= + cupLinear 0 * braidTrain (T*X 0) (skipTwo 0 X) 0 m := by + exact braidTrain_cup_after 0 2 m (by omega) _ _ + simp only [naturalPrescription,leftFusion,Finset.range_zero,Finset.prod_empty, + mul_one,Nat.zero_add,Nat.sub_zero,braidTrain,Module.End.mul_apply,hX,siteR_regular,map_smul] + rw [← Module.End.mul_apply,ho,Module.End.mul_apply,skipOne_eq_insertOne,hX,he,map_smul] + simp only [naturalFusion,hx,skipTwo_insertOne_after,fusionProduct_insertLast, + trainDenominator_fusionProduct,Nat.zero_add,← fusionPair_denominator,smul_smul] + congr 1 + ring + +end PolynomialVacuumAlgebra + +end OAI diff --git a/lean/OAI/Combinatorics/PolynomialVacuum/Algebra/FirstCupZeroNode.lean b/lean/OAI/Combinatorics/PolynomialVacuum/Algebra/FirstCupZeroNode.lean new file mode 100644 index 0000000000000000000000000000000000000000..f719308c6a9d5c90f002db52de6ecfd28a7bc2a0 --- /dev/null +++ b/lean/OAI/Combinatorics/PolynomialVacuum/Algebra/FirstCupZeroNode.lean @@ -0,0 +1,55 @@ +import OAI.Combinatorics.PolynomialVacuum.Algebra.FirstCupNodes + +namespace OAI + +namespace PolynomialVacuumAlgebra +open Classical + +noncomputable def prefixProduct (n : ℕ) (X : ℕ → ℂ) : ℂ := ∏ k ∈ Finset.range n, X k + +def LastZeroReduction (Ψ ψ : NatSpectralTensor) (n : ℕ) : Prop := + ∀ X s, X n=0 → s n≠Spin.plus → Ψ X s= + if s n=Spin.zero then prefixProduct n X*ψ X s else 0 + +theorem fusionPair_zero (a : ℂ) : fusionPair a 0=T*a^2 := by + simp only [fusionPair,T,t] + vacuum_ring_finish + +theorem prefixProduct_dropTwo (n : ℕ) (X : ℕ → ℂ) : + prefixProduct (n+2) X=X 0*X 1*prefixProduct n (skipTwo 0 X) := by + simp only [prefixProduct,skipTwo_zero_apply] + rw [show n+2=2+n by omega,Finset.prod_range_add] + simp only [Finset.prod_range_succ,Finset.range_zero,Finset.prod_empty,one_mul] + congr 1 + apply Finset.prod_congr rfl + intro k hk + rw [Nat.add_comm 2 k] + +theorem firstCup_zero_scalar (n : ℕ) (X : ℕ → ℂ) (hX : X 1=T*X 0) (h0 : X (n+2)=0) : + prefixProduct (n+2) X*naturalFusion n 0 X= + naturalFusion (n+1) 0 X*prefixProduct n (skipTwo 0 X) := by + simp only [prefixProduct_dropTwo,naturalFusion,fusionProduct,Finset.prod_range_succ, + skipTwo_zero_apply,h0,fusionPair_zero,hX] + ring + + + +theorem firstCup_zeroNode {Ψ ψ χ φ : NatSpectralTensor} {n : ℕ} + (hΨ : LastZeroReduction Ψ χ (n+2)) (hψ : LastZeroReduction ψ φ n) + (hχ : FirstCupReduction χ φ n) + (X : ℕ → ℂ) (s : ℕ → Spin) (hX : X 1=T*X 0) (h0 : X (n+2)=0) + (hs : s (n+2)≠Spin.plus) : + Ψ X s=(naturalFusion (n+1) 0 X • cupLinear 0 (ψ (skipTwo 0 X))) s := by + rw [hΨ X s h0 hs,hχ X hX] + have hz := hψ (skipTwo 0 X) (skipTwo 0 s) (by simpa using h0) (by simpa using hs) + simp only [Pi.smul_apply,smul_eq_mul,cupLinear,LinearMap.coe_mk,AddHom.coe_mk] + rw [hz] + simp only [skipTwo_zero_apply] + split_ifs + · have he := firstCup_zero_scalar n X hX h0 + linear_combination he * cup (s 0,s 1) * φ (skipTwo 0 X) (skipTwo 0 s) + · simp + +end PolynomialVacuumAlgebra + +end OAI diff --git a/lean/OAI/Combinatorics/PolynomialVacuum/Algebra/FirstExchanges.lean b/lean/OAI/Combinatorics/PolynomialVacuum/Algebra/FirstExchanges.lean new file mode 100644 index 0000000000000000000000000000000000000000..fe84e0d35214974bf3eef65a64e71be5461f0b27 --- /dev/null +++ b/lean/OAI/Combinatorics/PolynomialVacuum/Algebra/FirstExchanges.lean @@ -0,0 +1,117 @@ +import OAI.Combinatorics.PolynomialVacuum.Algebra.NodesUniqueness +import OAI.Combinatorics.PolynomialVacuum.Algebra.PrescriptionCovariance + +namespace OAI + +namespace PolynomialVacuumAlgebra +open MvPolynomial Classical PolynomialVacuumInterpolation + +theorem replacePair_last {n : ℕ} (j : Fin n) (s : Fin (n+2) → Spin) (ab : Pair) : + replacePair s (pairLeft j.castSucc) (pairRight j.castSucc) ab (Fin.last (n+1))= + s (Fin.last (n+1)) := by + apply replacePair_other + · intro h + have hv:=congrArg Fin.val h + simp only [pairLeft,Fin.val_last,Fin.val_castSucc] at hv + have hj:=j.isLt; omega + · intro h + have hv:=congrArg Fin.val h + simp only [pairRight,Fin.val_last,Fin.val_succ,Fin.val_castSucc] at hv + have hj:=j.isLt; omega + +theorem replacePair_castSucc {n : ℕ} (j : Fin n) (s : Fin (n+2) → Spin) (ab : Pair) : + (replacePair s (pairLeft j.castSucc) (pairRight j.castSucc) ab) ∘ Fin.castSucc= + replacePair (s ∘ Fin.castSucc) j.castSucc j.succ ab := by + funext k + simp only [Function.comp_apply,replacePair,Function.update_apply,pairLeft,pairRight, + Fin.ext_iff,Fin.val_castSucc,Fin.val_succ] + +theorem rename_prod_X {m : ℕ} (e : Equiv.Perm (Fin m)) : + rename e (∏ i : Fin m, X i : MvPolynomial (Fin m) ℂ)=∏ i : Fin m, X i := by + simp only [map_prod,rename_X] + exact Equiv.prod_comp e (fun i => (X i : MvPolynomial (Fin m) ℂ)) + + + +theorem lastPolynomial_first_exchange {n : ℕ} (ψ : State n) (χ : State (n+1)) + (hψ : LowerExchange (liftState ψ) n) (hχ : LowerExchange (liftState χ) (n+1)) + (j : Fin n) (s : Fin (n+2) → Spin) : + (∑ ab : Pair, Polynomial.C (polyExchangeNumerator (X j.castSucc) (X j.succ) + (s (pairLeft j.castSucc),s (pairRight j.castSucc)) ab)* + lastPolynomial ψ χ (replacePair s (pairLeft j.castSucc) (pairRight j.castSucc) ab))= + Polynomial.C ((C (t^2)*X j.castSucc-X j.succ)*(C T*X j.castSucc-X j.succ))* + (lastPolynomial ψ χ s).map (rename (Equiv.swap j.castSucc j.succ)).toRingHom := by + let a:=pairLeft j.castSucc + let b:=pairRight j.castSucc + let A := ∑ ab : Pair, Polynomial.C (polyExchangeNumerator (X j.castSucc) (X j.succ) + (s a,s b) ab)*lastPolynomial ψ χ (replacePair s a b ab) + let B := Polynomial.C ((C (t^2)*X j.castSucc-X j.succ)*(C T*X j.castSucc-X j.succ))* + (lastPolynomial ψ χ s).map (rename (Equiv.swap j.castSucc j.succ)).toRingHom + change A=B + have hnode (i : Fin (n+1)) : A.eval (X i)=B.eval (X i) := by + simp only [A,B,Polynomial.eval_finsetSum,Polynomial.eval_mul,Polynomial.eval_C, + lastPolynomial_node ψ χ hψ,eval_map_rename_swap] + exact congrFun (cupPrescription_covariance ψ hψ i j) s + have hdegA (d : ℕ) (hd : ∀ ab : Pair, (lastPolynomial ψ χ (replacePair s a b ab)).natDegree ≤ d) : + A.natDegree ≤ d := by + apply Polynomial.natDegree_sum_le_of_forall_le + intro ab hab + exact (Polynomial.natDegree_C_mul_le _ _).trans (hd ab) + have hdegB (d : ℕ) (hd : (lastPolynomial ψ χ s).natDegree ≤ d) : B.natDegree ≤ d := by + exact (Polynomial.natDegree_C_mul_le _ _).trans (Polynomial.natDegree_map_le.trans hd) + by_cases hs : s (Fin.last (n+1))=Spin.plus + · apply regular_lagrange_unique (Finset.univ : Finset (Fin (n+1))) + · have hd := hdegA n (by + intro ab + have he : replacePair s a b ab (Fin.last (n+1))=Spin.plus := (replacePair_last j s ab).trans hs + simpa only [lastPolynomial,ite_eq_left he] using + canonicalInterpolant_natDegree (fun i => cupPrescription ψ i (replacePair s a b ab))) + simp only [Finset.card_univ,Fintype.card_fin] + change A.degree < ((n+1 : ℕ) : WithBot ℕ) + calc + A.degree ≤ (A.natDegree : WithBot ℕ) := Polynomial.degree_le_natDegree + _ ≤ (n : WithBot ℕ) := WithBot.coe_le_coe.mpr hd + _ < ((n+1 : ℕ) : WithBot ℕ) := by exact_mod_cast (Nat.lt_succ_self n) + · have hd := hdegB n (by + simpa only [lastPolynomial,ite_eq_left hs] using + canonicalInterpolant_natDegree (fun i => cupPrescription ψ i s)) + simp only [Finset.card_univ,Fintype.card_fin] + change B.degree < ((n+1 : ℕ) : WithBot ℕ) + calc + B.degree ≤ (B.natDegree : WithBot ℕ) := Polynomial.degree_le_natDegree + _ ≤ (n : WithBot ℕ) := WithBot.coe_le_coe.mpr hd + _ < ((n+1 : ℕ) : WithBot ℕ) := by exact_mod_cast (Nat.lt_succ_self n) + · intro i hi; exact hnode i + · apply polynomial_eq_on_nodes_zero A B (hdegA (n+1) (fun _ => lastPolynomial_natDegree _ _ _)) + (hdegB (n+1) (lastPolynomial_natDegree _ _ _)) + · have he (ab : Pair) : replacePair s a b ab (Fin.last (n+1))≠Spin.plus := by + simpa only [a,b,replacePair_last] using hs + simp only [A,B,Polynomial.eval_finsetSum,Polynomial.eval_mul,Polynomial.eval_C, + Polynomial.eval_zero_map,lastPolynomial_zero _ _ _ hs,lastPolynomial_zero _ _ _ (he _)] + simp only [a,b,replacePair_last,replacePair_castSucc] + split_ifs with hz + · simp only [map_mul,AlgHom.toRingHom_eq_coe, RingHom.coe_coe, rename_prod_X] + have h := congrFun (state_exchange_of_lower χ hχ j) (s ∘ Fin.castSucc) + simp only [tensorExchange,Function.comp_apply] at h + simp only [← mul_assoc] + calc + _ = (∏ i : Fin (n+1), X i)* + ∑ ab : Pair, polyExchangeNumerator (X j.castSucc) (X j.succ) + (s a,s b) ab*χ (replacePair (s ∘ Fin.castSucc) j.castSucc j.succ ab) := by + rw [Finset.mul_sum] + apply Finset.sum_congr rfl + intro ab hab + ring + _ = _ := by + have hh : (∑ ab : Pair, polyExchangeNumerator (X j.castSucc) (X j.succ) + (s a,s b) ab*χ (replacePair (s ∘ Fin.castSucc) j.castSucc j.succ ab)) = + (C (t^2)*X j.castSucc-X j.succ)*(C T*X j.castSucc-X j.succ)* + rename (Equiv.swap j.castSucc j.succ) (χ (s ∘ Fin.castSucc)) := by + simpa only [a,b,pairLeft,pairRight,Fin.succ_castSucc,replacePair] using h + rw [hh]; ring + · simp + · exact hnode + +end PolynomialVacuumAlgebra + +end OAI diff --git a/lean/OAI/Combinatorics/PolynomialVacuum/Algebra/FullCyclicity.lean b/lean/OAI/Combinatorics/PolynomialVacuum/Algebra/FullCyclicity.lean new file mode 100644 index 0000000000000000000000000000000000000000..61e8e4513a2073f8d01eb212572f9f2d7455cb17 --- /dev/null +++ b/lean/OAI/Combinatorics/PolynomialVacuum/Algebra/FullCyclicity.lean @@ -0,0 +1,32 @@ +import OAI.Combinatorics.PolynomialVacuum.Algebra.CyclicBounds +import OAI.Combinatorics.PolynomialVacuum.Algebra.CyclicCups + +namespace OAI + +namespace PolynomialVacuumAlgebra +open MvPolynomial Classical + + + +theorem cyclicity_of_cups {n : ℕ} (Ψ : State (n+4)) (ψ : State (n+2)) + (hex : LowerExchange (liftState Ψ) (n+4)) + (hc : ∀ i≤n+2, CupAt (liftState Ψ) (liftState ψ) (n+2) i) + (hcy : NaturalCyclic (n+1) (liftState ψ)) + (hd : ∀ s i, (Ψ s).degreeOf i ≤ n+3) + (hp : ∀ s i, s i=Spin.plus → (Ψ s).degreeOf i ≤ n+2) + (hz : MinusZero Ψ) : NaturalCyclic (n+3) (liftState Ψ) := by + have he : ∀ s, cyclicDiscrepancy Ψ s=0 := by + apply cup_vanishing_rigidity (m:=n+3) (by omega) _ (cyclicDiscrepancy_exchange Ψ hex) + · exact cyclicDiscrepancy_cup Ψ ψ hc hcy + · intro s j hj; exact cyclicDiscrepancy_degree Ψ _ hd s j hj + · intro s j hj hs; exact cyclicDiscrepancy_plus_degree Ψ _ hp s j hj hs + · intro s j hj hs; exact cyclicDiscrepancy_minus_zero Ψ hz s j hj hs + intro X + apply sub_eq_zero.mp + rw [← eval_cyclicDiscrepancy] + funext s + simp only [evalNatPolyTensor,he,map_zero,Pi.zero_apply] + +end PolynomialVacuumAlgebra + +end OAI diff --git a/lean/OAI/Combinatorics/PolynomialVacuum/Algebra/FusionScalars.lean b/lean/OAI/Combinatorics/PolynomialVacuum/Algebra/FusionScalars.lean new file mode 100644 index 0000000000000000000000000000000000000000..93ebe1a749c9400a2b0e683457ecfd00b43018f3 --- /dev/null +++ b/lean/OAI/Combinatorics/PolynomialVacuum/Algebra/FusionScalars.lean @@ -0,0 +1,40 @@ +import OAI.Combinatorics.PolynomialVacuum.Algebra.NaturalCovariance +import OAI.Combinatorics.PolynomialVacuum.Algebra.Ring + +namespace OAI + +namespace PolynomialVacuumAlgebra +open Classical + +theorem fusionPair_four_point (a b : ℂ) : + fusionPair b a * fusionPair b (T*a) = fusionPair a b * fusionPair a (T*b) := by + simp only [fusionPair,T,t] + vacuum_ring_finish + +theorem fusionPair_successor_zero (a : ℂ) : fusionPair (T*a) a=0 := by + simp only [fusionPair,T,t] + vacuum_ring_finish + +theorem fusionPair_second_successor_zero (a : ℂ) : fusionPair a (T*(T*a))=0 := by + simp only [fusionPair,T] + ring + +noncomputable def fusionProduct (a : ℂ) (X : ℕ → ℂ) (m : ℕ) : ℂ := + ∏ k ∈ Finset.range m, fusionPair a (X k) + +noncomputable def naturalFusion (n i : ℕ) (X : ℕ → ℂ) : ℂ := + (1+T)*X i*fusionProduct (X i) (skipTwo i X) n + +theorem fusionProduct_skipOne (a : ℂ) (X : ℕ → ℂ) (m i : ℕ) (hi : i ≤ m) : + fusionProduct a (skipOne i X) m * fusionPair a (X i)=fusionProduct a X (m+1) := by + let j : Fin (m+1) := ⟨i,by omega⟩ + have hv (k : Fin m) : (j.succAbove k).val=if k.val < i then k.val else k.val+1 := by + simp only [Fin.succAbove,Fin.lt_def,j,Fin.val_castSucc] + split_ifs <;> rfl + have h := Fin.prod_univ_succAbove (fun k : Fin (m+1) => fusionPair a (X k.val)) j + simp only [fusionProduct,← Fin.prod_univ_eq_prod_range,skipOne,← hv] + simpa only [j,Fin.val_mk,mul_comm] using h.symm + +end PolynomialVacuumAlgebra + +end OAI diff --git a/lean/OAI/Combinatorics/PolynomialVacuum/Algebra/Gram.lean b/lean/OAI/Combinatorics/PolynomialVacuum/Algebra/Gram.lean new file mode 100644 index 0000000000000000000000000000000000000000..caf2832905515faa9ac0e4d78760f670a520bd10 --- /dev/null +++ b/lean/OAI/Combinatorics/PolynomialVacuum/Algebra/Gram.lean @@ -0,0 +1,87 @@ +import OAI.Combinatorics.PolynomialVacuum.Algebra.Scalars + +namespace OAI + +namespace PolynomialVacuumAlgebra + +@[simp] theorem spin_zero_ne_plus : Spin.zero ≠ Spin.plus := by decide +@[simp] theorem spin_zero_ne_minus : Spin.zero ≠ Spin.minus := by decide +@[simp] theorem spin_plus_ne_zero : Spin.plus ≠ Spin.zero := by decide +@[simp] theorem spin_plus_ne_minus : Spin.plus ≠ Spin.minus := by decide +@[simp] theorem spin_minus_ne_zero : Spin.minus ≠ Spin.zero := by decide +@[simp] theorem spin_minus_ne_plus : Spin.minus ≠ Spin.plus := by decide + +theorem sum_spin {R : Type*} [AddCommMonoid R] (f : Spin → R) : + (∑ h : Spin, f h) = f Spin.zero + f Spin.plus + f Spin.minus := by + have hu : (Finset.univ : Finset Spin) = {Spin.zero,Spin.plus,Spin.minus} := by + ext h; cases h <;> simp + rw [hu] + simp [add_assoc] + +theorem sum_pair {R : Type*} [AddCommMonoid R] (f : Pair → R) : + (∑ a : Pair, f a) = + (f (.zero,.zero)+f (.zero,.plus)+f (.zero,.minus))+ + (f (.plus,.zero)+f (.plus,.plus)+f (.plus,.minus))+ + (f (.minus,.zero)+f (.minus,.plus)+f (.minus,.minus)) := by + rw [Fintype.sum_prod_type] + simp only [sum_spin] + +@[simp] theorem cup_zero_zero : cup (.zero,.zero)=1 := by norm_num [cup,charge] +@[simp] theorem cup_plus_minus : cup (.plus,.minus)=q^5 := by norm_num [cup,charge] +@[simp] theorem cup_minus_plus : cup (.minus,.plus)= -q^3 := by + norm_num [cup,charge,zpow_neg,q_five_inv] + +theorem cup_norm : (∑ a : Pair, cup a * cup a) = -nZero := by + rw [sum_pair] + norm_num [cup,charge,zpow_neg,q_five_inv] + rw [nZero,← q_two_sum] + linear_combination q^2 * q_pow_eight + +theorem cup_insertion_zero : (∑ a : Pair, cup a * insertion a Spin.zero) = 0 := by + rw [sum_pair] + norm_num [cup,insertion,charge,zpow_neg,q_five_inv,q_four_inv] + have hx := xStar_mul_q_sum + rw [q_inv] at hx + linear_combination -hx + xStar*q*q_pow_eight + +theorem cup_insertion (h : Spin) : (∑ a : Pair, cup a * insertion a h) = 0 := by + cases h with + | zero => exact cup_insertion_zero + | plus => rw [sum_pair]; norm_num [cup,insertion,charge] + | minus => rw [sum_pair]; norm_num [cup,insertion,charge] + +theorem insertion_zero_norm : (∑ a : Pair, insertion a Spin.zero * insertion a Spin.zero) = nZero := by + rw [sum_pair] + norm_num [insertion,charge,zpow_neg,q_four_inv] + linear_combination xStar_sq_twice + 2*xStar^2*q_pow_eight + +theorem insertion_plus_norm : (∑ a : Pair, insertion a Spin.plus * insertion a Spin.plus) = nZero := by + rw [sum_pair] + norm_num [insertion,charge,zpow_neg,q_inv] + have h := xStar_sq_mul_sqrt_two + rw [← q_two_sum] at h + linear_combination h + xStar^2*q^6*q_pow_eight + +theorem insertion_minus_norm : (∑ a : Pair, insertion a Spin.minus * insertion a Spin.minus) = nZero := by + rw [sum_pair] + norm_num [insertion,charge,zpow_neg,q_inv] + have h := xStar_sq_mul_sqrt_two + rw [← q_two_sum] at h + linear_combination h + xStar^2*q^6*q_pow_eight + +theorem insertion_gram (h k : Spin) : + (∑ a : Pair, insertion a h * insertion a k) = if h=k then nZero else 0 := by + cases h <;> cases k + · simpa using insertion_zero_norm + · rw [sum_pair]; norm_num [insertion,charge] + · rw [sum_pair]; norm_num [insertion,charge] + · rw [sum_pair]; norm_num [insertion,charge] + · simpa using insertion_plus_norm + · rw [sum_pair]; norm_num [insertion,charge] + · rw [sum_pair]; norm_num [insertion,charge] + · rw [sum_pair]; norm_num [insertion,charge] + · simpa using insertion_minus_norm + +end PolynomialVacuumAlgebra + +end OAI diff --git a/lean/OAI/Combinatorics/PolynomialVacuum/Algebra/HomogeneityStep.lean b/lean/OAI/Combinatorics/PolynomialVacuum/Algebra/HomogeneityStep.lean new file mode 100644 index 0000000000000000000000000000000000000000..8cb46d82e46de171b2efe3dcca34c6a8d5bf4e21 --- /dev/null +++ b/lean/OAI/Combinatorics/PolynomialVacuum/Algebra/HomogeneityStep.lean @@ -0,0 +1,77 @@ +import OAI.Combinatorics.PolynomialVacuum.Algebra.ScalingTensors +import OAI.Combinatorics.PolynomialVacuum.Algebra.FullCyclicity + +namespace OAI + +namespace PolynomialVacuumAlgebra +open MvPolynomial Classical + +theorem scalingDiscrepancy_cup {n d : ℕ} (Ψ : State (n+2)) (ψ : State n) + (hc : ∀ i≤n, CupAt (liftState Ψ) (liftState ψ) n i) + (hh : ∀ s, (ψ s).IsHomogeneous d) (i : ℕ) (hi : i≤n) + (X : ℕ → ℂ) (hX : X (i+1)=T*X i) : + evalNatPolyTensor (scalingDiscrepancy Ψ (2*n+1+d)) X=0 := by + have hs : (2:ℂ)*X (i+1)=T*(2*X i) := by rw [hX]; ring + rw [eval_scalingDiscrepancy,hc i hi _ hs,hc i hi _ hX,naturalFusion_scale] + funext s + simp only [Pi.sub_apply,Pi.smul_apply,smul_eq_mul,cupLinear] + change (2:ℂ)^(2*n+1)*naturalFusion n i X*(cup (s i,s (i+1))*liftState ψ (fun j => 2*skipTwo i X j) (skipTwo i s)) - + (2:ℂ)^(2*n+1+d)*(naturalFusion n i X*(cup (s i,s (i+1))*liftState ψ (skipTwo i X) (skipTwo i s)))=0 + rw [liftState_homogeneous_scale ψ hh,pow_add] + ring + +theorem scalingDiscrepancy_degree {N d b : ℕ} (Ψ : State N) (s : ℕ → Spin) (j : Fin N) + (h : (Ψ (fun a => s a.val)).degreeOf j≤b) : + (scalingDiscrepancy Ψ d s).degreeOf j.val≤b := by + have hd : (coordinatePolynomial Ψ s).degreeOf j.val≤b := by rw [coordinatePolynomial_degree]; exact h + exact (degreeOf_sub_le _ _ _).trans (max_le ((degreeOf_scalePolynomial_le _ _ _).trans hd) (dconst_mul _ hd)) + +theorem scalingDiscrepancy_minusZero {N d : ℕ} (Ψ : State N) (hz : MinusZero Ψ) + (s : ℕ → Spin) (j : Fin N) (hs : s j.val=Spin.minus) : + killSite j.val (scalingDiscrepancy Ψ d s)=0 := by + have h : killSite j.val (coordinatePolynomial Ψ s)=0 := by + rw [coordinatePolynomial,killSite_rename_injective _ Fin.val_injective,hz _ _ hs,map_zero] + simp only [scalingDiscrepancy,map_sub,map_mul,killSite_C,killSite_scalePolynomial,h,map_zero,mul_zero,sub_zero] + +theorem homogeneous_of_scalingDiscrepancy {N d : ℕ} (Ψ : State N) + (h : ∀ s, scalingDiscrepancy Ψ d s=0) (s : Fin N → Spin) : + (Ψ s).IsHomogeneous d := by + apply homogeneous_of_scale_two + apply MvPolynomial.funext + intro X + have he := congrArg (eval (extendFinite 0 X)) (h (extendFinite Spin.zero s)) + simp only [scalingDiscrepancy,map_sub,map_zero,eval_scalePolynomial,map_mul,eval_C, + eval_coordinatePolynomial,liftState,liftPolyTensor,extendFinite_fin] at he + simpa only [eval_scalePolynomial,map_mul,eval_C] using sub_eq_zero.mp he + +theorem homogDegree_step (n : ℕ) : (n+2).choose 2=2*n+1+n.choose 2 := by + have h1 := Nat.choose_succ_succ n 1 + have h2 := Nat.choose_succ_succ (n+1) 1 + simp only [Nat.choose_one_right,Nat.succ_eq_add_one,Nat.reduceAdd,Nat.add_assoc] at h1 h2 + omega + +theorem homogeneity_of_cups {n : ℕ} (Ψ : State (n+4)) (ψ : State (n+2)) + (hex : LowerExchange (liftState Ψ) (n+4)) + (hc : ∀ i≤n+2, CupAt (liftState Ψ) (liftState ψ) (n+2) i) + (hh : ∀ s, (ψ s).IsHomogeneous ((n+2).choose 2)) + (hd : ∀ s i, (Ψ s).degreeOf i≤n+3) + (hp : ∀ s i, s i=Spin.plus → (Ψ s).degreeOf i≤n+2) + (hz : MinusZero Ψ) : ∀ s, (Ψ s).IsHomogeneous ((n+4).choose 2) := by + apply homogeneous_of_scalingDiscrepancy + apply cup_vanishing_rigidity (m:=n+3) (by omega) + · exact scalingDiscrepancy_exchange Ψ (fun j hj => hex j (by omega)) + · intro i hi X hX + have heq : (n+4).choose 2=2*(n+2)+1+(n+2).choose 2 := homogDegree_step (n+2) + rw [heq] + exact scalingDiscrepancy_cup Ψ ψ hc hh i (by omega) X hX + · intro s j hj + exact scalingDiscrepancy_degree Ψ s ⟨j,by omega⟩ (hd _ _) + · intro s j hj hs + have he := scalingDiscrepancy_degree (d:=(n+4).choose 2) Ψ s ⟨j,by omega⟩ (hp _ ⟨j,by omega⟩ hs) + exact he.trans (by omega) + · intro s j hj hs + exact scalingDiscrepancy_minusZero Ψ hz s ⟨j,by omega⟩ hs + +end PolynomialVacuumAlgebra + +end OAI diff --git a/lean/OAI/Combinatorics/PolynomialVacuum/Algebra/HomogeneousCupSlide.lean b/lean/OAI/Combinatorics/PolynomialVacuum/Algebra/HomogeneousCupSlide.lean new file mode 100644 index 0000000000000000000000000000000000000000..ee940a63401495eff407d761d2085ddac7e1a90b --- /dev/null +++ b/lean/OAI/Combinatorics/PolynomialVacuum/Algebra/HomogeneousCupSlide.lean @@ -0,0 +1,443 @@ +import OAI.Combinatorics.PolynomialVacuum.Algebra.Table +import OAI.Combinatorics.PolynomialVacuum.Algebra.Ring + +namespace OAI + +namespace PolynomialVacuumAlgebra +noncomputable def homogeneousCupLeft (x y : ℂ) (a b c h : Spin) : ℂ := + ∑ i : Spin, ∑ j : Spin, ∑ k : Spin, + exchangeNumerator x y (a,b) (i,j) * + exchangeNumerator (T*x) y (j,c) (k,h) * cup (i,k) +noncomputable def homogeneousCupRight (x y : ℂ) (a b c h : Spin) : ℂ := + exchangeDenominator x y * exchangeDenominator (T*x) y * + (if a=h then cup (b,c) else 0) +theorem homogeneous_cup_entry_0_0 (x y : ℂ) : + homogeneousCupLeft x y .zero .zero .zero .zero = homogeneousCupRight x y .zero .zero .zero .zero := by + norm_num [homogeneousCupLeft,homogeneousCupRight,sum_spin,exchangeNumerator_eq_table,exchangeTable, + exchangeDenominator,cup,charge,zpow_neg,q_five_inv,T,t] + all_goals vacuum_ring_finish +theorem homogeneous_cup_entry_0_1 (x y : ℂ) : + homogeneousCupLeft x y .zero .zero .zero .plus = homogeneousCupRight x y .zero .zero .zero .plus := by + norm_num [homogeneousCupLeft,homogeneousCupRight,sum_spin,exchangeNumerator_eq_table,exchangeTable, + exchangeDenominator,cup,charge,zpow_neg,q_five_inv,T,t] +theorem homogeneous_cup_entry_0_2 (x y : ℂ) : + homogeneousCupLeft x y .zero .zero .zero .minus = homogeneousCupRight x y .zero .zero .zero .minus := by + norm_num [homogeneousCupLeft,homogeneousCupRight,sum_spin,exchangeNumerator_eq_table,exchangeTable, + exchangeDenominator,cup,charge,zpow_neg,q_five_inv,T,t] +theorem homogeneous_cup_entry_1_0 (x y : ℂ) : + homogeneousCupLeft x y .zero .zero .plus .zero = homogeneousCupRight x y .zero .zero .plus .zero := by + norm_num [homogeneousCupLeft,homogeneousCupRight,sum_spin,exchangeNumerator_eq_table,exchangeTable, + exchangeDenominator,cup,charge,zpow_neg,q_five_inv,T,t] +theorem homogeneous_cup_entry_1_1 (x y : ℂ) : + homogeneousCupLeft x y .zero .zero .plus .plus = homogeneousCupRight x y .zero .zero .plus .plus := by + norm_num [homogeneousCupLeft,homogeneousCupRight,sum_spin,exchangeNumerator_eq_table,exchangeTable, + exchangeDenominator,cup,charge,zpow_neg,q_five_inv,T,t] + all_goals vacuum_ring_finish +theorem homogeneous_cup_entry_1_2 (x y : ℂ) : + homogeneousCupLeft x y .zero .zero .plus .minus = homogeneousCupRight x y .zero .zero .plus .minus := by + norm_num [homogeneousCupLeft,homogeneousCupRight,sum_spin,exchangeNumerator_eq_table,exchangeTable, + exchangeDenominator,cup,charge,zpow_neg,q_five_inv,T,t] +theorem homogeneous_cup_entry_2_0 (x y : ℂ) : + homogeneousCupLeft x y .zero .zero .minus .zero = homogeneousCupRight x y .zero .zero .minus .zero := by + norm_num [homogeneousCupLeft,homogeneousCupRight,sum_spin,exchangeNumerator_eq_table,exchangeTable, + exchangeDenominator,cup,charge,zpow_neg,q_five_inv,T,t] +theorem homogeneous_cup_entry_2_1 (x y : ℂ) : + homogeneousCupLeft x y .zero .zero .minus .plus = homogeneousCupRight x y .zero .zero .minus .plus := by + norm_num [homogeneousCupLeft,homogeneousCupRight,sum_spin,exchangeNumerator_eq_table,exchangeTable, + exchangeDenominator,cup,charge,zpow_neg,q_five_inv,T,t] +theorem homogeneous_cup_entry_2_2 (x y : ℂ) : + homogeneousCupLeft x y .zero .zero .minus .minus = homogeneousCupRight x y .zero .zero .minus .minus := by + norm_num [homogeneousCupLeft,homogeneousCupRight,sum_spin,exchangeNumerator_eq_table,exchangeTable, + exchangeDenominator,cup,charge,zpow_neg,q_five_inv,T,t] + all_goals vacuum_ring_finish +theorem homogeneous_cup_entry_3_0 (x y : ℂ) : + homogeneousCupLeft x y .zero .plus .zero .zero = homogeneousCupRight x y .zero .plus .zero .zero := by + norm_num [homogeneousCupLeft,homogeneousCupRight,sum_spin,exchangeNumerator_eq_table,exchangeTable, + exchangeDenominator,cup,charge,zpow_neg,q_five_inv,T,t] +theorem homogeneous_cup_entry_3_1 (x y : ℂ) : + homogeneousCupLeft x y .zero .plus .zero .plus = homogeneousCupRight x y .zero .plus .zero .plus := by + norm_num [homogeneousCupLeft,homogeneousCupRight,sum_spin,exchangeNumerator_eq_table,exchangeTable, + exchangeDenominator,cup,charge,zpow_neg,q_five_inv,T,t] + all_goals vacuum_ring_finish +theorem homogeneous_cup_entry_3_2 (x y : ℂ) : + homogeneousCupLeft x y .zero .plus .zero .minus = homogeneousCupRight x y .zero .plus .zero .minus := by + norm_num [homogeneousCupLeft,homogeneousCupRight,sum_spin,exchangeNumerator_eq_table,exchangeTable, + exchangeDenominator,cup,charge,zpow_neg,q_five_inv,T,t] +theorem homogeneous_cup_entry_4_0 (x y : ℂ) : + homogeneousCupLeft x y .zero .plus .plus .zero = homogeneousCupRight x y .zero .plus .plus .zero := by + norm_num [homogeneousCupLeft,homogeneousCupRight,sum_spin,exchangeNumerator_eq_table,exchangeTable, + exchangeDenominator,cup,charge,zpow_neg,q_five_inv,T,t] +theorem homogeneous_cup_entry_4_1 (x y : ℂ) : + homogeneousCupLeft x y .zero .plus .plus .plus = homogeneousCupRight x y .zero .plus .plus .plus := by + norm_num [homogeneousCupLeft,homogeneousCupRight,sum_spin,exchangeNumerator_eq_table,exchangeTable, + exchangeDenominator,cup,charge,zpow_neg,q_five_inv,T,t] +theorem homogeneous_cup_entry_4_2 (x y : ℂ) : + homogeneousCupLeft x y .zero .plus .plus .minus = homogeneousCupRight x y .zero .plus .plus .minus := by + norm_num [homogeneousCupLeft,homogeneousCupRight,sum_spin,exchangeNumerator_eq_table,exchangeTable, + exchangeDenominator,cup,charge,zpow_neg,q_five_inv,T,t] +theorem homogeneous_cup_entry_5_0 (x y : ℂ) : + homogeneousCupLeft x y .zero .plus .minus .zero = homogeneousCupRight x y .zero .plus .minus .zero := by + norm_num [homogeneousCupLeft,homogeneousCupRight,sum_spin,exchangeNumerator_eq_table,exchangeTable, + exchangeDenominator,cup,charge,zpow_neg,q_five_inv,T,t] + all_goals vacuum_ring_finish +theorem homogeneous_cup_entry_5_1 (x y : ℂ) : + homogeneousCupLeft x y .zero .plus .minus .plus = homogeneousCupRight x y .zero .plus .minus .plus := by + norm_num [homogeneousCupLeft,homogeneousCupRight,sum_spin,exchangeNumerator_eq_table,exchangeTable, + exchangeDenominator,cup,charge,zpow_neg,q_five_inv,T,t] +theorem homogeneous_cup_entry_5_2 (x y : ℂ) : + homogeneousCupLeft x y .zero .plus .minus .minus = homogeneousCupRight x y .zero .plus .minus .minus := by + norm_num [homogeneousCupLeft,homogeneousCupRight,sum_spin,exchangeNumerator_eq_table,exchangeTable, + exchangeDenominator,cup,charge,zpow_neg,q_five_inv,T,t] +theorem homogeneous_cup_entry_6_0 (x y : ℂ) : + homogeneousCupLeft x y .zero .minus .zero .zero = homogeneousCupRight x y .zero .minus .zero .zero := by + norm_num [homogeneousCupLeft,homogeneousCupRight,sum_spin,exchangeNumerator_eq_table,exchangeTable, + exchangeDenominator,cup,charge,zpow_neg,q_five_inv,T,t] +theorem homogeneous_cup_entry_6_1 (x y : ℂ) : + homogeneousCupLeft x y .zero .minus .zero .plus = homogeneousCupRight x y .zero .minus .zero .plus := by + norm_num [homogeneousCupLeft,homogeneousCupRight,sum_spin,exchangeNumerator_eq_table,exchangeTable, + exchangeDenominator,cup,charge,zpow_neg,q_five_inv,T,t] +theorem homogeneous_cup_entry_6_2 (x y : ℂ) : + homogeneousCupLeft x y .zero .minus .zero .minus = homogeneousCupRight x y .zero .minus .zero .minus := by + norm_num [homogeneousCupLeft,homogeneousCupRight,sum_spin,exchangeNumerator_eq_table,exchangeTable, + exchangeDenominator,cup,charge,zpow_neg,q_five_inv,T,t] + all_goals vacuum_ring_finish +theorem homogeneous_cup_entry_7_0 (x y : ℂ) : + homogeneousCupLeft x y .zero .minus .plus .zero = homogeneousCupRight x y .zero .minus .plus .zero := by + norm_num [homogeneousCupLeft,homogeneousCupRight,sum_spin,exchangeNumerator_eq_table,exchangeTable, + exchangeDenominator,cup,charge,zpow_neg,q_five_inv,T,t] + all_goals vacuum_ring_finish +theorem homogeneous_cup_entry_7_1 (x y : ℂ) : + homogeneousCupLeft x y .zero .minus .plus .plus = homogeneousCupRight x y .zero .minus .plus .plus := by + norm_num [homogeneousCupLeft,homogeneousCupRight,sum_spin,exchangeNumerator_eq_table,exchangeTable, + exchangeDenominator,cup,charge,zpow_neg,q_five_inv,T,t] +theorem homogeneous_cup_entry_7_2 (x y : ℂ) : + homogeneousCupLeft x y .zero .minus .plus .minus = homogeneousCupRight x y .zero .minus .plus .minus := by + norm_num [homogeneousCupLeft,homogeneousCupRight,sum_spin,exchangeNumerator_eq_table,exchangeTable, + exchangeDenominator,cup,charge,zpow_neg,q_five_inv,T,t] +theorem homogeneous_cup_entry_8_0 (x y : ℂ) : + homogeneousCupLeft x y .zero .minus .minus .zero = homogeneousCupRight x y .zero .minus .minus .zero := by + norm_num [homogeneousCupLeft,homogeneousCupRight,sum_spin,exchangeNumerator_eq_table,exchangeTable, + exchangeDenominator,cup,charge,zpow_neg,q_five_inv,T,t] +theorem homogeneous_cup_entry_8_1 (x y : ℂ) : + homogeneousCupLeft x y .zero .minus .minus .plus = homogeneousCupRight x y .zero .minus .minus .plus := by + norm_num [homogeneousCupLeft,homogeneousCupRight,sum_spin,exchangeNumerator_eq_table,exchangeTable, + exchangeDenominator,cup,charge,zpow_neg,q_five_inv,T,t] +theorem homogeneous_cup_entry_8_2 (x y : ℂ) : + homogeneousCupLeft x y .zero .minus .minus .minus = homogeneousCupRight x y .zero .minus .minus .minus := by + norm_num [homogeneousCupLeft,homogeneousCupRight,sum_spin,exchangeNumerator_eq_table,exchangeTable, + exchangeDenominator,cup,charge,zpow_neg,q_five_inv,T,t] +theorem homogeneous_cup_entry_9_0 (x y : ℂ) : + homogeneousCupLeft x y .plus .zero .zero .zero = homogeneousCupRight x y .plus .zero .zero .zero := by + norm_num [homogeneousCupLeft,homogeneousCupRight,sum_spin,exchangeNumerator_eq_table,exchangeTable, + exchangeDenominator,cup,charge,zpow_neg,q_five_inv,T,t] +theorem homogeneous_cup_entry_9_1 (x y : ℂ) : + homogeneousCupLeft x y .plus .zero .zero .plus = homogeneousCupRight x y .plus .zero .zero .plus := by + norm_num [homogeneousCupLeft,homogeneousCupRight,sum_spin,exchangeNumerator_eq_table,exchangeTable, + exchangeDenominator,cup,charge,zpow_neg,q_five_inv,T,t] + all_goals vacuum_ring_finish +theorem homogeneous_cup_entry_9_2 (x y : ℂ) : + homogeneousCupLeft x y .plus .zero .zero .minus = homogeneousCupRight x y .plus .zero .zero .minus := by + norm_num [homogeneousCupLeft,homogeneousCupRight,sum_spin,exchangeNumerator_eq_table,exchangeTable, + exchangeDenominator,cup,charge,zpow_neg,q_five_inv,T,t] +theorem homogeneous_cup_entry_10_0 (x y : ℂ) : + homogeneousCupLeft x y .plus .zero .plus .zero = homogeneousCupRight x y .plus .zero .plus .zero := by + norm_num [homogeneousCupLeft,homogeneousCupRight,sum_spin,exchangeNumerator_eq_table,exchangeTable, + exchangeDenominator,cup,charge,zpow_neg,q_five_inv,T,t] +theorem homogeneous_cup_entry_10_1 (x y : ℂ) : + homogeneousCupLeft x y .plus .zero .plus .plus = homogeneousCupRight x y .plus .zero .plus .plus := by + norm_num [homogeneousCupLeft,homogeneousCupRight,sum_spin,exchangeNumerator_eq_table,exchangeTable, + exchangeDenominator,cup,charge,zpow_neg,q_five_inv,T,t] +theorem homogeneous_cup_entry_10_2 (x y : ℂ) : + homogeneousCupLeft x y .plus .zero .plus .minus = homogeneousCupRight x y .plus .zero .plus .minus := by + norm_num [homogeneousCupLeft,homogeneousCupRight,sum_spin,exchangeNumerator_eq_table,exchangeTable, + exchangeDenominator,cup,charge,zpow_neg,q_five_inv,T,t] +theorem homogeneous_cup_entry_11_0 (x y : ℂ) : + homogeneousCupLeft x y .plus .zero .minus .zero = homogeneousCupRight x y .plus .zero .minus .zero := by + norm_num [homogeneousCupLeft,homogeneousCupRight,sum_spin,exchangeNumerator_eq_table,exchangeTable, + exchangeDenominator,cup,charge,zpow_neg,q_five_inv,T,t] + all_goals vacuum_ring_finish +theorem homogeneous_cup_entry_11_1 (x y : ℂ) : + homogeneousCupLeft x y .plus .zero .minus .plus = homogeneousCupRight x y .plus .zero .minus .plus := by + norm_num [homogeneousCupLeft,homogeneousCupRight,sum_spin,exchangeNumerator_eq_table,exchangeTable, + exchangeDenominator,cup,charge,zpow_neg,q_five_inv,T,t] +theorem homogeneous_cup_entry_11_2 (x y : ℂ) : + homogeneousCupLeft x y .plus .zero .minus .minus = homogeneousCupRight x y .plus .zero .minus .minus := by + norm_num [homogeneousCupLeft,homogeneousCupRight,sum_spin,exchangeNumerator_eq_table,exchangeTable, + exchangeDenominator,cup,charge,zpow_neg,q_five_inv,T,t] +theorem homogeneous_cup_entry_12_0 (x y : ℂ) : + homogeneousCupLeft x y .plus .plus .zero .zero = homogeneousCupRight x y .plus .plus .zero .zero := by + norm_num [homogeneousCupLeft,homogeneousCupRight,sum_spin,exchangeNumerator_eq_table,exchangeTable, + exchangeDenominator,cup,charge,zpow_neg,q_five_inv,T,t] +theorem homogeneous_cup_entry_12_1 (x y : ℂ) : + homogeneousCupLeft x y .plus .plus .zero .plus = homogeneousCupRight x y .plus .plus .zero .plus := by + norm_num [homogeneousCupLeft,homogeneousCupRight,sum_spin,exchangeNumerator_eq_table,exchangeTable, + exchangeDenominator,cup,charge,zpow_neg,q_five_inv,T,t] +theorem homogeneous_cup_entry_12_2 (x y : ℂ) : + homogeneousCupLeft x y .plus .plus .zero .minus = homogeneousCupRight x y .plus .plus .zero .minus := by + norm_num [homogeneousCupLeft,homogeneousCupRight,sum_spin,exchangeNumerator_eq_table,exchangeTable, + exchangeDenominator,cup,charge,zpow_neg,q_five_inv,T,t] +theorem homogeneous_cup_entry_13_0 (x y : ℂ) : + homogeneousCupLeft x y .plus .plus .plus .zero = homogeneousCupRight x y .plus .plus .plus .zero := by + norm_num [homogeneousCupLeft,homogeneousCupRight,sum_spin,exchangeNumerator_eq_table,exchangeTable, + exchangeDenominator,cup,charge,zpow_neg,q_five_inv,T,t] +theorem homogeneous_cup_entry_13_1 (x y : ℂ) : + homogeneousCupLeft x y .plus .plus .plus .plus = homogeneousCupRight x y .plus .plus .plus .plus := by + norm_num [homogeneousCupLeft,homogeneousCupRight,sum_spin,exchangeNumerator_eq_table,exchangeTable, + exchangeDenominator,cup,charge,zpow_neg,q_five_inv,T,t] +theorem homogeneous_cup_entry_13_2 (x y : ℂ) : + homogeneousCupLeft x y .plus .plus .plus .minus = homogeneousCupRight x y .plus .plus .plus .minus := by + norm_num [homogeneousCupLeft,homogeneousCupRight,sum_spin,exchangeNumerator_eq_table,exchangeTable, + exchangeDenominator,cup,charge,zpow_neg,q_five_inv,T,t] +theorem homogeneous_cup_entry_14_0 (x y : ℂ) : + homogeneousCupLeft x y .plus .plus .minus .zero = homogeneousCupRight x y .plus .plus .minus .zero := by + norm_num [homogeneousCupLeft,homogeneousCupRight,sum_spin,exchangeNumerator_eq_table,exchangeTable, + exchangeDenominator,cup,charge,zpow_neg,q_five_inv,T,t] +theorem homogeneous_cup_entry_14_1 (x y : ℂ) : + homogeneousCupLeft x y .plus .plus .minus .plus = homogeneousCupRight x y .plus .plus .minus .plus := by + norm_num [homogeneousCupLeft,homogeneousCupRight,sum_spin,exchangeNumerator_eq_table,exchangeTable, + exchangeDenominator,cup,charge,zpow_neg,q_five_inv,T,t] + all_goals vacuum_ring_finish +theorem homogeneous_cup_entry_14_2 (x y : ℂ) : + homogeneousCupLeft x y .plus .plus .minus .minus = homogeneousCupRight x y .plus .plus .minus .minus := by + norm_num [homogeneousCupLeft,homogeneousCupRight,sum_spin,exchangeNumerator_eq_table,exchangeTable, + exchangeDenominator,cup,charge,zpow_neg,q_five_inv,T,t] +theorem homogeneous_cup_entry_15_0 (x y : ℂ) : + homogeneousCupLeft x y .plus .minus .zero .zero = homogeneousCupRight x y .plus .minus .zero .zero := by + norm_num [homogeneousCupLeft,homogeneousCupRight,sum_spin,exchangeNumerator_eq_table,exchangeTable, + exchangeDenominator,cup,charge,zpow_neg,q_five_inv,T,t] + all_goals vacuum_ring_finish +theorem homogeneous_cup_entry_15_1 (x y : ℂ) : + homogeneousCupLeft x y .plus .minus .zero .plus = homogeneousCupRight x y .plus .minus .zero .plus := by + norm_num [homogeneousCupLeft,homogeneousCupRight,sum_spin,exchangeNumerator_eq_table,exchangeTable, + exchangeDenominator,cup,charge,zpow_neg,q_five_inv,T,t] +theorem homogeneous_cup_entry_15_2 (x y : ℂ) : + homogeneousCupLeft x y .plus .minus .zero .minus = homogeneousCupRight x y .plus .minus .zero .minus := by + norm_num [homogeneousCupLeft,homogeneousCupRight,sum_spin,exchangeNumerator_eq_table,exchangeTable, + exchangeDenominator,cup,charge,zpow_neg,q_five_inv,T,t] +theorem homogeneous_cup_entry_16_0 (x y : ℂ) : + homogeneousCupLeft x y .plus .minus .plus .zero = homogeneousCupRight x y .plus .minus .plus .zero := by + norm_num [homogeneousCupLeft,homogeneousCupRight,sum_spin,exchangeNumerator_eq_table,exchangeTable, + exchangeDenominator,cup,charge,zpow_neg,q_five_inv,T,t] +theorem homogeneous_cup_entry_16_1 (x y : ℂ) : + homogeneousCupLeft x y .plus .minus .plus .plus = homogeneousCupRight x y .plus .minus .plus .plus := by + norm_num [homogeneousCupLeft,homogeneousCupRight,sum_spin,exchangeNumerator_eq_table,exchangeTable, + exchangeDenominator,cup,charge,zpow_neg,q_five_inv,T,t] + all_goals vacuum_ring_finish +theorem homogeneous_cup_entry_16_2 (x y : ℂ) : + homogeneousCupLeft x y .plus .minus .plus .minus = homogeneousCupRight x y .plus .minus .plus .minus := by + norm_num [homogeneousCupLeft,homogeneousCupRight,sum_spin,exchangeNumerator_eq_table,exchangeTable, + exchangeDenominator,cup,charge,zpow_neg,q_five_inv,T,t] +theorem homogeneous_cup_entry_17_0 (x y : ℂ) : + homogeneousCupLeft x y .plus .minus .minus .zero = homogeneousCupRight x y .plus .minus .minus .zero := by + norm_num [homogeneousCupLeft,homogeneousCupRight,sum_spin,exchangeNumerator_eq_table,exchangeTable, + exchangeDenominator,cup,charge,zpow_neg,q_five_inv,T,t] +theorem homogeneous_cup_entry_17_1 (x y : ℂ) : + homogeneousCupLeft x y .plus .minus .minus .plus = homogeneousCupRight x y .plus .minus .minus .plus := by + norm_num [homogeneousCupLeft,homogeneousCupRight,sum_spin,exchangeNumerator_eq_table,exchangeTable, + exchangeDenominator,cup,charge,zpow_neg,q_five_inv,T,t] +theorem homogeneous_cup_entry_17_2 (x y : ℂ) : + homogeneousCupLeft x y .plus .minus .minus .minus = homogeneousCupRight x y .plus .minus .minus .minus := by + norm_num [homogeneousCupLeft,homogeneousCupRight,sum_spin,exchangeNumerator_eq_table,exchangeTable, + exchangeDenominator,cup,charge,zpow_neg,q_five_inv,T,t] + all_goals vacuum_ring_finish +theorem homogeneous_cup_entry_18_0 (x y : ℂ) : + homogeneousCupLeft x y .minus .zero .zero .zero = homogeneousCupRight x y .minus .zero .zero .zero := by + norm_num [homogeneousCupLeft,homogeneousCupRight,sum_spin,exchangeNumerator_eq_table,exchangeTable, + exchangeDenominator,cup,charge,zpow_neg,q_five_inv,T,t] +theorem homogeneous_cup_entry_18_1 (x y : ℂ) : + homogeneousCupLeft x y .minus .zero .zero .plus = homogeneousCupRight x y .minus .zero .zero .plus := by + norm_num [homogeneousCupLeft,homogeneousCupRight,sum_spin,exchangeNumerator_eq_table,exchangeTable, + exchangeDenominator,cup,charge,zpow_neg,q_five_inv,T,t] +theorem homogeneous_cup_entry_18_2 (x y : ℂ) : + homogeneousCupLeft x y .minus .zero .zero .minus = homogeneousCupRight x y .minus .zero .zero .minus := by + norm_num [homogeneousCupLeft,homogeneousCupRight,sum_spin,exchangeNumerator_eq_table,exchangeTable, + exchangeDenominator,cup,charge,zpow_neg,q_five_inv,T,t] + all_goals vacuum_ring_finish +theorem homogeneous_cup_entry_19_0 (x y : ℂ) : + homogeneousCupLeft x y .minus .zero .plus .zero = homogeneousCupRight x y .minus .zero .plus .zero := by + norm_num [homogeneousCupLeft,homogeneousCupRight,sum_spin,exchangeNumerator_eq_table,exchangeTable, + exchangeDenominator,cup,charge,zpow_neg,q_five_inv,T,t] + all_goals vacuum_ring_finish +theorem homogeneous_cup_entry_19_1 (x y : ℂ) : + homogeneousCupLeft x y .minus .zero .plus .plus = homogeneousCupRight x y .minus .zero .plus .plus := by + norm_num [homogeneousCupLeft,homogeneousCupRight,sum_spin,exchangeNumerator_eq_table,exchangeTable, + exchangeDenominator,cup,charge,zpow_neg,q_five_inv,T,t] +theorem homogeneous_cup_entry_19_2 (x y : ℂ) : + homogeneousCupLeft x y .minus .zero .plus .minus = homogeneousCupRight x y .minus .zero .plus .minus := by + norm_num [homogeneousCupLeft,homogeneousCupRight,sum_spin,exchangeNumerator_eq_table,exchangeTable, + exchangeDenominator,cup,charge,zpow_neg,q_five_inv,T,t] +theorem homogeneous_cup_entry_20_0 (x y : ℂ) : + homogeneousCupLeft x y .minus .zero .minus .zero = homogeneousCupRight x y .minus .zero .minus .zero := by + norm_num [homogeneousCupLeft,homogeneousCupRight,sum_spin,exchangeNumerator_eq_table,exchangeTable, + exchangeDenominator,cup,charge,zpow_neg,q_five_inv,T,t] +theorem homogeneous_cup_entry_20_1 (x y : ℂ) : + homogeneousCupLeft x y .minus .zero .minus .plus = homogeneousCupRight x y .minus .zero .minus .plus := by + norm_num [homogeneousCupLeft,homogeneousCupRight,sum_spin,exchangeNumerator_eq_table,exchangeTable, + exchangeDenominator,cup,charge,zpow_neg,q_five_inv,T,t] +theorem homogeneous_cup_entry_20_2 (x y : ℂ) : + homogeneousCupLeft x y .minus .zero .minus .minus = homogeneousCupRight x y .minus .zero .minus .minus := by + norm_num [homogeneousCupLeft,homogeneousCupRight,sum_spin,exchangeNumerator_eq_table,exchangeTable, + exchangeDenominator,cup,charge,zpow_neg,q_five_inv,T,t] +theorem homogeneous_cup_entry_21_0 (x y : ℂ) : + homogeneousCupLeft x y .minus .plus .zero .zero = homogeneousCupRight x y .minus .plus .zero .zero := by + norm_num [homogeneousCupLeft,homogeneousCupRight,sum_spin,exchangeNumerator_eq_table,exchangeTable, + exchangeDenominator,cup,charge,zpow_neg,q_five_inv,T,t] + all_goals vacuum_ring_finish +theorem homogeneous_cup_entry_21_1 (x y : ℂ) : + homogeneousCupLeft x y .minus .plus .zero .plus = homogeneousCupRight x y .minus .plus .zero .plus := by + norm_num [homogeneousCupLeft,homogeneousCupRight,sum_spin,exchangeNumerator_eq_table,exchangeTable, + exchangeDenominator,cup,charge,zpow_neg,q_five_inv,T,t] +theorem homogeneous_cup_entry_21_2 (x y : ℂ) : + homogeneousCupLeft x y .minus .plus .zero .minus = homogeneousCupRight x y .minus .plus .zero .minus := by + norm_num [homogeneousCupLeft,homogeneousCupRight,sum_spin,exchangeNumerator_eq_table,exchangeTable, + exchangeDenominator,cup,charge,zpow_neg,q_five_inv,T,t] +theorem homogeneous_cup_entry_22_0 (x y : ℂ) : + homogeneousCupLeft x y .minus .plus .plus .zero = homogeneousCupRight x y .minus .plus .plus .zero := by + norm_num [homogeneousCupLeft,homogeneousCupRight,sum_spin,exchangeNumerator_eq_table,exchangeTable, + exchangeDenominator,cup,charge,zpow_neg,q_five_inv,T,t] +theorem homogeneous_cup_entry_22_1 (x y : ℂ) : + homogeneousCupLeft x y .minus .plus .plus .plus = homogeneousCupRight x y .minus .plus .plus .plus := by + norm_num [homogeneousCupLeft,homogeneousCupRight,sum_spin,exchangeNumerator_eq_table,exchangeTable, + exchangeDenominator,cup,charge,zpow_neg,q_five_inv,T,t] + all_goals vacuum_ring_finish +theorem homogeneous_cup_entry_22_2 (x y : ℂ) : + homogeneousCupLeft x y .minus .plus .plus .minus = homogeneousCupRight x y .minus .plus .plus .minus := by + norm_num [homogeneousCupLeft,homogeneousCupRight,sum_spin,exchangeNumerator_eq_table,exchangeTable, + exchangeDenominator,cup,charge,zpow_neg,q_five_inv,T,t] +theorem homogeneous_cup_entry_23_0 (x y : ℂ) : + homogeneousCupLeft x y .minus .plus .minus .zero = homogeneousCupRight x y .minus .plus .minus .zero := by + norm_num [homogeneousCupLeft,homogeneousCupRight,sum_spin,exchangeNumerator_eq_table,exchangeTable, + exchangeDenominator,cup,charge,zpow_neg,q_five_inv,T,t] +theorem homogeneous_cup_entry_23_1 (x y : ℂ) : + homogeneousCupLeft x y .minus .plus .minus .plus = homogeneousCupRight x y .minus .plus .minus .plus := by + norm_num [homogeneousCupLeft,homogeneousCupRight,sum_spin,exchangeNumerator_eq_table,exchangeTable, + exchangeDenominator,cup,charge,zpow_neg,q_five_inv,T,t] +theorem homogeneous_cup_entry_23_2 (x y : ℂ) : + homogeneousCupLeft x y .minus .plus .minus .minus = homogeneousCupRight x y .minus .plus .minus .minus := by + norm_num [homogeneousCupLeft,homogeneousCupRight,sum_spin,exchangeNumerator_eq_table,exchangeTable, + exchangeDenominator,cup,charge,zpow_neg,q_five_inv,T,t] + all_goals vacuum_ring_finish +theorem homogeneous_cup_entry_24_0 (x y : ℂ) : + homogeneousCupLeft x y .minus .minus .zero .zero = homogeneousCupRight x y .minus .minus .zero .zero := by + norm_num [homogeneousCupLeft,homogeneousCupRight,sum_spin,exchangeNumerator_eq_table,exchangeTable, + exchangeDenominator,cup,charge,zpow_neg,q_five_inv,T,t] +theorem homogeneous_cup_entry_24_1 (x y : ℂ) : + homogeneousCupLeft x y .minus .minus .zero .plus = homogeneousCupRight x y .minus .minus .zero .plus := by + norm_num [homogeneousCupLeft,homogeneousCupRight,sum_spin,exchangeNumerator_eq_table,exchangeTable, + exchangeDenominator,cup,charge,zpow_neg,q_five_inv,T,t] +theorem homogeneous_cup_entry_24_2 (x y : ℂ) : + homogeneousCupLeft x y .minus .minus .zero .minus = homogeneousCupRight x y .minus .minus .zero .minus := by + norm_num [homogeneousCupLeft,homogeneousCupRight,sum_spin,exchangeNumerator_eq_table,exchangeTable, + exchangeDenominator,cup,charge,zpow_neg,q_five_inv,T,t] +theorem homogeneous_cup_entry_25_0 (x y : ℂ) : + homogeneousCupLeft x y .minus .minus .plus .zero = homogeneousCupRight x y .minus .minus .plus .zero := by + norm_num [homogeneousCupLeft,homogeneousCupRight,sum_spin,exchangeNumerator_eq_table,exchangeTable, + exchangeDenominator,cup,charge,zpow_neg,q_five_inv,T,t] +theorem homogeneous_cup_entry_25_1 (x y : ℂ) : + homogeneousCupLeft x y .minus .minus .plus .plus = homogeneousCupRight x y .minus .minus .plus .plus := by + norm_num [homogeneousCupLeft,homogeneousCupRight,sum_spin,exchangeNumerator_eq_table,exchangeTable, + exchangeDenominator,cup,charge,zpow_neg,q_five_inv,T,t] +theorem homogeneous_cup_entry_25_2 (x y : ℂ) : + homogeneousCupLeft x y .minus .minus .plus .minus = homogeneousCupRight x y .minus .minus .plus .minus := by + norm_num [homogeneousCupLeft,homogeneousCupRight,sum_spin,exchangeNumerator_eq_table,exchangeTable, + exchangeDenominator,cup,charge,zpow_neg,q_five_inv,T,t] + all_goals vacuum_ring_finish +theorem homogeneous_cup_entry_26_0 (x y : ℂ) : + homogeneousCupLeft x y .minus .minus .minus .zero = homogeneousCupRight x y .minus .minus .minus .zero := by + norm_num [homogeneousCupLeft,homogeneousCupRight,sum_spin,exchangeNumerator_eq_table,exchangeTable, + exchangeDenominator,cup,charge,zpow_neg,q_five_inv,T,t] +theorem homogeneous_cup_entry_26_1 (x y : ℂ) : + homogeneousCupLeft x y .minus .minus .minus .plus = homogeneousCupRight x y .minus .minus .minus .plus := by + norm_num [homogeneousCupLeft,homogeneousCupRight,sum_spin,exchangeNumerator_eq_table,exchangeTable, + exchangeDenominator,cup,charge,zpow_neg,q_five_inv,T,t] +theorem homogeneous_cup_entry_26_2 (x y : ℂ) : + homogeneousCupLeft x y .minus .minus .minus .minus = homogeneousCupRight x y .minus .minus .minus .minus := by + norm_num [homogeneousCupLeft,homogeneousCupRight,sum_spin,exchangeNumerator_eq_table,exchangeTable, + exchangeDenominator,cup,charge,zpow_neg,q_five_inv,T,t] +theorem homogeneous_cup_slide (x y : ℂ) (a b c h : Spin) : + homogeneousCupLeft x y a b c h = homogeneousCupRight x y a b c h := by + cases a <;> cases b <;> cases c <;> cases h + · exact homogeneous_cup_entry_0_0 x y + · exact homogeneous_cup_entry_0_1 x y + · exact homogeneous_cup_entry_0_2 x y + · exact homogeneous_cup_entry_1_0 x y + · exact homogeneous_cup_entry_1_1 x y + · exact homogeneous_cup_entry_1_2 x y + · exact homogeneous_cup_entry_2_0 x y + · exact homogeneous_cup_entry_2_1 x y + · exact homogeneous_cup_entry_2_2 x y + · exact homogeneous_cup_entry_3_0 x y + · exact homogeneous_cup_entry_3_1 x y + · exact homogeneous_cup_entry_3_2 x y + · exact homogeneous_cup_entry_4_0 x y + · exact homogeneous_cup_entry_4_1 x y + · exact homogeneous_cup_entry_4_2 x y + · exact homogeneous_cup_entry_5_0 x y + · exact homogeneous_cup_entry_5_1 x y + · exact homogeneous_cup_entry_5_2 x y + · exact homogeneous_cup_entry_6_0 x y + · exact homogeneous_cup_entry_6_1 x y + · exact homogeneous_cup_entry_6_2 x y + · exact homogeneous_cup_entry_7_0 x y + · exact homogeneous_cup_entry_7_1 x y + · exact homogeneous_cup_entry_7_2 x y + · exact homogeneous_cup_entry_8_0 x y + · exact homogeneous_cup_entry_8_1 x y + · exact homogeneous_cup_entry_8_2 x y + · exact homogeneous_cup_entry_9_0 x y + · exact homogeneous_cup_entry_9_1 x y + · exact homogeneous_cup_entry_9_2 x y + · exact homogeneous_cup_entry_10_0 x y + · exact homogeneous_cup_entry_10_1 x y + · exact homogeneous_cup_entry_10_2 x y + · exact homogeneous_cup_entry_11_0 x y + · exact homogeneous_cup_entry_11_1 x y + · exact homogeneous_cup_entry_11_2 x y + · exact homogeneous_cup_entry_12_0 x y + · exact homogeneous_cup_entry_12_1 x y + · exact homogeneous_cup_entry_12_2 x y + · exact homogeneous_cup_entry_13_0 x y + · exact homogeneous_cup_entry_13_1 x y + · exact homogeneous_cup_entry_13_2 x y + · exact homogeneous_cup_entry_14_0 x y + · exact homogeneous_cup_entry_14_1 x y + · exact homogeneous_cup_entry_14_2 x y + · exact homogeneous_cup_entry_15_0 x y + · exact homogeneous_cup_entry_15_1 x y + · exact homogeneous_cup_entry_15_2 x y + · exact homogeneous_cup_entry_16_0 x y + · exact homogeneous_cup_entry_16_1 x y + · exact homogeneous_cup_entry_16_2 x y + · exact homogeneous_cup_entry_17_0 x y + · exact homogeneous_cup_entry_17_1 x y + · exact homogeneous_cup_entry_17_2 x y + · exact homogeneous_cup_entry_18_0 x y + · exact homogeneous_cup_entry_18_1 x y + · exact homogeneous_cup_entry_18_2 x y + · exact homogeneous_cup_entry_19_0 x y + · exact homogeneous_cup_entry_19_1 x y + · exact homogeneous_cup_entry_19_2 x y + · exact homogeneous_cup_entry_20_0 x y + · exact homogeneous_cup_entry_20_1 x y + · exact homogeneous_cup_entry_20_2 x y + · exact homogeneous_cup_entry_21_0 x y + · exact homogeneous_cup_entry_21_1 x y + · exact homogeneous_cup_entry_21_2 x y + · exact homogeneous_cup_entry_22_0 x y + · exact homogeneous_cup_entry_22_1 x y + · exact homogeneous_cup_entry_22_2 x y + · exact homogeneous_cup_entry_23_0 x y + · exact homogeneous_cup_entry_23_1 x y + · exact homogeneous_cup_entry_23_2 x y + · exact homogeneous_cup_entry_24_0 x y + · exact homogeneous_cup_entry_24_1 x y + · exact homogeneous_cup_entry_24_2 x y + · exact homogeneous_cup_entry_25_0 x y + · exact homogeneous_cup_entry_25_1 x y + · exact homogeneous_cup_entry_25_2 x y + · exact homogeneous_cup_entry_26_0 x y + · exact homogeneous_cup_entry_26_1 x y + · exact homogeneous_cup_entry_26_2 x y +end PolynomialVacuumAlgebra + +end OAI diff --git a/lean/OAI/Combinatorics/PolynomialVacuum/Algebra/HomogeneousCupUnslide.lean b/lean/OAI/Combinatorics/PolynomialVacuum/Algebra/HomogeneousCupUnslide.lean new file mode 100644 index 0000000000000000000000000000000000000000..bb93dcf33ccd8c45168164a3759b898faf9a7908 --- /dev/null +++ b/lean/OAI/Combinatorics/PolynomialVacuum/Algebra/HomogeneousCupUnslide.lean @@ -0,0 +1,442 @@ +import OAI.Combinatorics.PolynomialVacuum.Algebra.Table +import OAI.Combinatorics.PolynomialVacuum.Algebra.Ring + +namespace OAI + +namespace PolynomialVacuumAlgebra +noncomputable def homogeneousUncupLeft (x y : ℂ) (a b c h : Spin) : ℂ := + exchangeDenominator (T*x) y * ∑ k : Spin, + exchangeNumerator y x (a,b) (h,k) * cup (k,c) +noncomputable def homogeneousUncupRight (x y : ℂ) (a b c h : Spin) : ℂ := + exchangeDenominator y x * ∑ k : Spin, + exchangeNumerator (T*x) y (b,c) (k,h) * cup (a,k) +theorem homogeneous_uncup_entry_0_0 (x y : ℂ) : + homogeneousUncupLeft x y .zero .zero .zero .zero = homogeneousUncupRight x y .zero .zero .zero .zero := by + norm_num [homogeneousUncupLeft,homogeneousUncupRight,sum_spin,exchangeNumerator_eq_table,exchangeTable, + exchangeDenominator,cup,charge,zpow_neg,q_five_inv,T,t] + all_goals vacuum_ring_finish +theorem homogeneous_uncup_entry_0_1 (x y : ℂ) : + homogeneousUncupLeft x y .zero .zero .zero .plus = homogeneousUncupRight x y .zero .zero .zero .plus := by + norm_num [homogeneousUncupLeft,homogeneousUncupRight,sum_spin,exchangeNumerator_eq_table,exchangeTable, + exchangeDenominator,cup,charge,zpow_neg,q_five_inv,T,t] +theorem homogeneous_uncup_entry_0_2 (x y : ℂ) : + homogeneousUncupLeft x y .zero .zero .zero .minus = homogeneousUncupRight x y .zero .zero .zero .minus := by + norm_num [homogeneousUncupLeft,homogeneousUncupRight,sum_spin,exchangeNumerator_eq_table,exchangeTable, + exchangeDenominator,cup,charge,zpow_neg,q_five_inv,T,t] +theorem homogeneous_uncup_entry_1_0 (x y : ℂ) : + homogeneousUncupLeft x y .zero .zero .plus .zero = homogeneousUncupRight x y .zero .zero .plus .zero := by + norm_num [homogeneousUncupLeft,homogeneousUncupRight,sum_spin,exchangeNumerator_eq_table,exchangeTable, + exchangeDenominator,cup,charge,zpow_neg,q_five_inv,T,t] +theorem homogeneous_uncup_entry_1_1 (x y : ℂ) : + homogeneousUncupLeft x y .zero .zero .plus .plus = homogeneousUncupRight x y .zero .zero .plus .plus := by + norm_num [homogeneousUncupLeft,homogeneousUncupRight,sum_spin,exchangeNumerator_eq_table,exchangeTable, + exchangeDenominator,cup,charge,zpow_neg,q_five_inv,T,t] + all_goals vacuum_ring_finish +theorem homogeneous_uncup_entry_1_2 (x y : ℂ) : + homogeneousUncupLeft x y .zero .zero .plus .minus = homogeneousUncupRight x y .zero .zero .plus .minus := by + norm_num [homogeneousUncupLeft,homogeneousUncupRight,sum_spin,exchangeNumerator_eq_table,exchangeTable, + exchangeDenominator,cup,charge,zpow_neg,q_five_inv,T,t] +theorem homogeneous_uncup_entry_2_0 (x y : ℂ) : + homogeneousUncupLeft x y .zero .zero .minus .zero = homogeneousUncupRight x y .zero .zero .minus .zero := by + norm_num [homogeneousUncupLeft,homogeneousUncupRight,sum_spin,exchangeNumerator_eq_table,exchangeTable, + exchangeDenominator,cup,charge,zpow_neg,q_five_inv,T,t] +theorem homogeneous_uncup_entry_2_1 (x y : ℂ) : + homogeneousUncupLeft x y .zero .zero .minus .plus = homogeneousUncupRight x y .zero .zero .minus .plus := by + norm_num [homogeneousUncupLeft,homogeneousUncupRight,sum_spin,exchangeNumerator_eq_table,exchangeTable, + exchangeDenominator,cup,charge,zpow_neg,q_five_inv,T,t] +theorem homogeneous_uncup_entry_2_2 (x y : ℂ) : + homogeneousUncupLeft x y .zero .zero .minus .minus = homogeneousUncupRight x y .zero .zero .minus .minus := by + norm_num [homogeneousUncupLeft,homogeneousUncupRight,sum_spin,exchangeNumerator_eq_table,exchangeTable, + exchangeDenominator,cup,charge,zpow_neg,q_five_inv,T,t] + all_goals vacuum_ring_finish +theorem homogeneous_uncup_entry_3_0 (x y : ℂ) : + homogeneousUncupLeft x y .zero .plus .zero .zero = homogeneousUncupRight x y .zero .plus .zero .zero := by + norm_num [homogeneousUncupLeft,homogeneousUncupRight,sum_spin,exchangeNumerator_eq_table,exchangeTable, + exchangeDenominator,cup,charge,zpow_neg,q_five_inv,T,t] +theorem homogeneous_uncup_entry_3_1 (x y : ℂ) : + homogeneousUncupLeft x y .zero .plus .zero .plus = homogeneousUncupRight x y .zero .plus .zero .plus := by + norm_num [homogeneousUncupLeft,homogeneousUncupRight,sum_spin,exchangeNumerator_eq_table,exchangeTable, + exchangeDenominator,cup,charge,zpow_neg,q_five_inv,T,t] + all_goals vacuum_ring_finish +theorem homogeneous_uncup_entry_3_2 (x y : ℂ) : + homogeneousUncupLeft x y .zero .plus .zero .minus = homogeneousUncupRight x y .zero .plus .zero .minus := by + norm_num [homogeneousUncupLeft,homogeneousUncupRight,sum_spin,exchangeNumerator_eq_table,exchangeTable, + exchangeDenominator,cup,charge,zpow_neg,q_five_inv,T,t] +theorem homogeneous_uncup_entry_4_0 (x y : ℂ) : + homogeneousUncupLeft x y .zero .plus .plus .zero = homogeneousUncupRight x y .zero .plus .plus .zero := by + norm_num [homogeneousUncupLeft,homogeneousUncupRight,sum_spin,exchangeNumerator_eq_table,exchangeTable, + exchangeDenominator,cup,charge,zpow_neg,q_five_inv,T,t] +theorem homogeneous_uncup_entry_4_1 (x y : ℂ) : + homogeneousUncupLeft x y .zero .plus .plus .plus = homogeneousUncupRight x y .zero .plus .plus .plus := by + norm_num [homogeneousUncupLeft,homogeneousUncupRight,sum_spin,exchangeNumerator_eq_table,exchangeTable, + exchangeDenominator,cup,charge,zpow_neg,q_five_inv,T,t] +theorem homogeneous_uncup_entry_4_2 (x y : ℂ) : + homogeneousUncupLeft x y .zero .plus .plus .minus = homogeneousUncupRight x y .zero .plus .plus .minus := by + norm_num [homogeneousUncupLeft,homogeneousUncupRight,sum_spin,exchangeNumerator_eq_table,exchangeTable, + exchangeDenominator,cup,charge,zpow_neg,q_five_inv,T,t] +theorem homogeneous_uncup_entry_5_0 (x y : ℂ) : + homogeneousUncupLeft x y .zero .plus .minus .zero = homogeneousUncupRight x y .zero .plus .minus .zero := by + norm_num [homogeneousUncupLeft,homogeneousUncupRight,sum_spin,exchangeNumerator_eq_table,exchangeTable, + exchangeDenominator,cup,charge,zpow_neg,q_five_inv,T,t] + all_goals vacuum_ring_finish +theorem homogeneous_uncup_entry_5_1 (x y : ℂ) : + homogeneousUncupLeft x y .zero .plus .minus .plus = homogeneousUncupRight x y .zero .plus .minus .plus := by + norm_num [homogeneousUncupLeft,homogeneousUncupRight,sum_spin,exchangeNumerator_eq_table,exchangeTable, + exchangeDenominator,cup,charge,zpow_neg,q_five_inv,T,t] +theorem homogeneous_uncup_entry_5_2 (x y : ℂ) : + homogeneousUncupLeft x y .zero .plus .minus .minus = homogeneousUncupRight x y .zero .plus .minus .minus := by + norm_num [homogeneousUncupLeft,homogeneousUncupRight,sum_spin,exchangeNumerator_eq_table,exchangeTable, + exchangeDenominator,cup,charge,zpow_neg,q_five_inv,T,t] +theorem homogeneous_uncup_entry_6_0 (x y : ℂ) : + homogeneousUncupLeft x y .zero .minus .zero .zero = homogeneousUncupRight x y .zero .minus .zero .zero := by + norm_num [homogeneousUncupLeft,homogeneousUncupRight,sum_spin,exchangeNumerator_eq_table,exchangeTable, + exchangeDenominator,cup,charge,zpow_neg,q_five_inv,T,t] +theorem homogeneous_uncup_entry_6_1 (x y : ℂ) : + homogeneousUncupLeft x y .zero .minus .zero .plus = homogeneousUncupRight x y .zero .minus .zero .plus := by + norm_num [homogeneousUncupLeft,homogeneousUncupRight,sum_spin,exchangeNumerator_eq_table,exchangeTable, + exchangeDenominator,cup,charge,zpow_neg,q_five_inv,T,t] +theorem homogeneous_uncup_entry_6_2 (x y : ℂ) : + homogeneousUncupLeft x y .zero .minus .zero .minus = homogeneousUncupRight x y .zero .minus .zero .minus := by + norm_num [homogeneousUncupLeft,homogeneousUncupRight,sum_spin,exchangeNumerator_eq_table,exchangeTable, + exchangeDenominator,cup,charge,zpow_neg,q_five_inv,T,t] + all_goals vacuum_ring_finish +theorem homogeneous_uncup_entry_7_0 (x y : ℂ) : + homogeneousUncupLeft x y .zero .minus .plus .zero = homogeneousUncupRight x y .zero .minus .plus .zero := by + norm_num [homogeneousUncupLeft,homogeneousUncupRight,sum_spin,exchangeNumerator_eq_table,exchangeTable, + exchangeDenominator,cup,charge,zpow_neg,q_five_inv,T,t] + all_goals vacuum_ring_finish +theorem homogeneous_uncup_entry_7_1 (x y : ℂ) : + homogeneousUncupLeft x y .zero .minus .plus .plus = homogeneousUncupRight x y .zero .minus .plus .plus := by + norm_num [homogeneousUncupLeft,homogeneousUncupRight,sum_spin,exchangeNumerator_eq_table,exchangeTable, + exchangeDenominator,cup,charge,zpow_neg,q_five_inv,T,t] +theorem homogeneous_uncup_entry_7_2 (x y : ℂ) : + homogeneousUncupLeft x y .zero .minus .plus .minus = homogeneousUncupRight x y .zero .minus .plus .minus := by + norm_num [homogeneousUncupLeft,homogeneousUncupRight,sum_spin,exchangeNumerator_eq_table,exchangeTable, + exchangeDenominator,cup,charge,zpow_neg,q_five_inv,T,t] +theorem homogeneous_uncup_entry_8_0 (x y : ℂ) : + homogeneousUncupLeft x y .zero .minus .minus .zero = homogeneousUncupRight x y .zero .minus .minus .zero := by + norm_num [homogeneousUncupLeft,homogeneousUncupRight,sum_spin,exchangeNumerator_eq_table,exchangeTable, + exchangeDenominator,cup,charge,zpow_neg,q_five_inv,T,t] +theorem homogeneous_uncup_entry_8_1 (x y : ℂ) : + homogeneousUncupLeft x y .zero .minus .minus .plus = homogeneousUncupRight x y .zero .minus .minus .plus := by + norm_num [homogeneousUncupLeft,homogeneousUncupRight,sum_spin,exchangeNumerator_eq_table,exchangeTable, + exchangeDenominator,cup,charge,zpow_neg,q_five_inv,T,t] +theorem homogeneous_uncup_entry_8_2 (x y : ℂ) : + homogeneousUncupLeft x y .zero .minus .minus .minus = homogeneousUncupRight x y .zero .minus .minus .minus := by + norm_num [homogeneousUncupLeft,homogeneousUncupRight,sum_spin,exchangeNumerator_eq_table,exchangeTable, + exchangeDenominator,cup,charge,zpow_neg,q_five_inv,T,t] +theorem homogeneous_uncup_entry_9_0 (x y : ℂ) : + homogeneousUncupLeft x y .plus .zero .zero .zero = homogeneousUncupRight x y .plus .zero .zero .zero := by + norm_num [homogeneousUncupLeft,homogeneousUncupRight,sum_spin,exchangeNumerator_eq_table,exchangeTable, + exchangeDenominator,cup,charge,zpow_neg,q_five_inv,T,t] +theorem homogeneous_uncup_entry_9_1 (x y : ℂ) : + homogeneousUncupLeft x y .plus .zero .zero .plus = homogeneousUncupRight x y .plus .zero .zero .plus := by + norm_num [homogeneousUncupLeft,homogeneousUncupRight,sum_spin,exchangeNumerator_eq_table,exchangeTable, + exchangeDenominator,cup,charge,zpow_neg,q_five_inv,T,t] + all_goals vacuum_ring_finish +theorem homogeneous_uncup_entry_9_2 (x y : ℂ) : + homogeneousUncupLeft x y .plus .zero .zero .minus = homogeneousUncupRight x y .plus .zero .zero .minus := by + norm_num [homogeneousUncupLeft,homogeneousUncupRight,sum_spin,exchangeNumerator_eq_table,exchangeTable, + exchangeDenominator,cup,charge,zpow_neg,q_five_inv,T,t] +theorem homogeneous_uncup_entry_10_0 (x y : ℂ) : + homogeneousUncupLeft x y .plus .zero .plus .zero = homogeneousUncupRight x y .plus .zero .plus .zero := by + norm_num [homogeneousUncupLeft,homogeneousUncupRight,sum_spin,exchangeNumerator_eq_table,exchangeTable, + exchangeDenominator,cup,charge,zpow_neg,q_five_inv,T,t] +theorem homogeneous_uncup_entry_10_1 (x y : ℂ) : + homogeneousUncupLeft x y .plus .zero .plus .plus = homogeneousUncupRight x y .plus .zero .plus .plus := by + norm_num [homogeneousUncupLeft,homogeneousUncupRight,sum_spin,exchangeNumerator_eq_table,exchangeTable, + exchangeDenominator,cup,charge,zpow_neg,q_five_inv,T,t] +theorem homogeneous_uncup_entry_10_2 (x y : ℂ) : + homogeneousUncupLeft x y .plus .zero .plus .minus = homogeneousUncupRight x y .plus .zero .plus .minus := by + norm_num [homogeneousUncupLeft,homogeneousUncupRight,sum_spin,exchangeNumerator_eq_table,exchangeTable, + exchangeDenominator,cup,charge,zpow_neg,q_five_inv,T,t] +theorem homogeneous_uncup_entry_11_0 (x y : ℂ) : + homogeneousUncupLeft x y .plus .zero .minus .zero = homogeneousUncupRight x y .plus .zero .minus .zero := by + norm_num [homogeneousUncupLeft,homogeneousUncupRight,sum_spin,exchangeNumerator_eq_table,exchangeTable, + exchangeDenominator,cup,charge,zpow_neg,q_five_inv,T,t] + all_goals vacuum_ring_finish +theorem homogeneous_uncup_entry_11_1 (x y : ℂ) : + homogeneousUncupLeft x y .plus .zero .minus .plus = homogeneousUncupRight x y .plus .zero .minus .plus := by + norm_num [homogeneousUncupLeft,homogeneousUncupRight,sum_spin,exchangeNumerator_eq_table,exchangeTable, + exchangeDenominator,cup,charge,zpow_neg,q_five_inv,T,t] +theorem homogeneous_uncup_entry_11_2 (x y : ℂ) : + homogeneousUncupLeft x y .plus .zero .minus .minus = homogeneousUncupRight x y .plus .zero .minus .minus := by + norm_num [homogeneousUncupLeft,homogeneousUncupRight,sum_spin,exchangeNumerator_eq_table,exchangeTable, + exchangeDenominator,cup,charge,zpow_neg,q_five_inv,T,t] +theorem homogeneous_uncup_entry_12_0 (x y : ℂ) : + homogeneousUncupLeft x y .plus .plus .zero .zero = homogeneousUncupRight x y .plus .plus .zero .zero := by + norm_num [homogeneousUncupLeft,homogeneousUncupRight,sum_spin,exchangeNumerator_eq_table,exchangeTable, + exchangeDenominator,cup,charge,zpow_neg,q_five_inv,T,t] +theorem homogeneous_uncup_entry_12_1 (x y : ℂ) : + homogeneousUncupLeft x y .plus .plus .zero .plus = homogeneousUncupRight x y .plus .plus .zero .plus := by + norm_num [homogeneousUncupLeft,homogeneousUncupRight,sum_spin,exchangeNumerator_eq_table,exchangeTable, + exchangeDenominator,cup,charge,zpow_neg,q_five_inv,T,t] +theorem homogeneous_uncup_entry_12_2 (x y : ℂ) : + homogeneousUncupLeft x y .plus .plus .zero .minus = homogeneousUncupRight x y .plus .plus .zero .minus := by + norm_num [homogeneousUncupLeft,homogeneousUncupRight,sum_spin,exchangeNumerator_eq_table,exchangeTable, + exchangeDenominator,cup,charge,zpow_neg,q_five_inv,T,t] +theorem homogeneous_uncup_entry_13_0 (x y : ℂ) : + homogeneousUncupLeft x y .plus .plus .plus .zero = homogeneousUncupRight x y .plus .plus .plus .zero := by + norm_num [homogeneousUncupLeft,homogeneousUncupRight,sum_spin,exchangeNumerator_eq_table,exchangeTable, + exchangeDenominator,cup,charge,zpow_neg,q_five_inv,T,t] +theorem homogeneous_uncup_entry_13_1 (x y : ℂ) : + homogeneousUncupLeft x y .plus .plus .plus .plus = homogeneousUncupRight x y .plus .plus .plus .plus := by + norm_num [homogeneousUncupLeft,homogeneousUncupRight,sum_spin,exchangeNumerator_eq_table,exchangeTable, + exchangeDenominator,cup,charge,zpow_neg,q_five_inv,T,t] +theorem homogeneous_uncup_entry_13_2 (x y : ℂ) : + homogeneousUncupLeft x y .plus .plus .plus .minus = homogeneousUncupRight x y .plus .plus .plus .minus := by + norm_num [homogeneousUncupLeft,homogeneousUncupRight,sum_spin,exchangeNumerator_eq_table,exchangeTable, + exchangeDenominator,cup,charge,zpow_neg,q_five_inv,T,t] +theorem homogeneous_uncup_entry_14_0 (x y : ℂ) : + homogeneousUncupLeft x y .plus .plus .minus .zero = homogeneousUncupRight x y .plus .plus .minus .zero := by + norm_num [homogeneousUncupLeft,homogeneousUncupRight,sum_spin,exchangeNumerator_eq_table,exchangeTable, + exchangeDenominator,cup,charge,zpow_neg,q_five_inv,T,t] +theorem homogeneous_uncup_entry_14_1 (x y : ℂ) : + homogeneousUncupLeft x y .plus .plus .minus .plus = homogeneousUncupRight x y .plus .plus .minus .plus := by + norm_num [homogeneousUncupLeft,homogeneousUncupRight,sum_spin,exchangeNumerator_eq_table,exchangeTable, + exchangeDenominator,cup,charge,zpow_neg,q_five_inv,T,t] + all_goals vacuum_ring_finish +theorem homogeneous_uncup_entry_14_2 (x y : ℂ) : + homogeneousUncupLeft x y .plus .plus .minus .minus = homogeneousUncupRight x y .plus .plus .minus .minus := by + norm_num [homogeneousUncupLeft,homogeneousUncupRight,sum_spin,exchangeNumerator_eq_table,exchangeTable, + exchangeDenominator,cup,charge,zpow_neg,q_five_inv,T,t] +theorem homogeneous_uncup_entry_15_0 (x y : ℂ) : + homogeneousUncupLeft x y .plus .minus .zero .zero = homogeneousUncupRight x y .plus .minus .zero .zero := by + norm_num [homogeneousUncupLeft,homogeneousUncupRight,sum_spin,exchangeNumerator_eq_table,exchangeTable, + exchangeDenominator,cup,charge,zpow_neg,q_five_inv,T,t] + all_goals vacuum_ring_finish +theorem homogeneous_uncup_entry_15_1 (x y : ℂ) : + homogeneousUncupLeft x y .plus .minus .zero .plus = homogeneousUncupRight x y .plus .minus .zero .plus := by + norm_num [homogeneousUncupLeft,homogeneousUncupRight,sum_spin,exchangeNumerator_eq_table,exchangeTable, + exchangeDenominator,cup,charge,zpow_neg,q_five_inv,T,t] +theorem homogeneous_uncup_entry_15_2 (x y : ℂ) : + homogeneousUncupLeft x y .plus .minus .zero .minus = homogeneousUncupRight x y .plus .minus .zero .minus := by + norm_num [homogeneousUncupLeft,homogeneousUncupRight,sum_spin,exchangeNumerator_eq_table,exchangeTable, + exchangeDenominator,cup,charge,zpow_neg,q_five_inv,T,t] +theorem homogeneous_uncup_entry_16_0 (x y : ℂ) : + homogeneousUncupLeft x y .plus .minus .plus .zero = homogeneousUncupRight x y .plus .minus .plus .zero := by + norm_num [homogeneousUncupLeft,homogeneousUncupRight,sum_spin,exchangeNumerator_eq_table,exchangeTable, + exchangeDenominator,cup,charge,zpow_neg,q_five_inv,T,t] +theorem homogeneous_uncup_entry_16_1 (x y : ℂ) : + homogeneousUncupLeft x y .plus .minus .plus .plus = homogeneousUncupRight x y .plus .minus .plus .plus := by + norm_num [homogeneousUncupLeft,homogeneousUncupRight,sum_spin,exchangeNumerator_eq_table,exchangeTable, + exchangeDenominator,cup,charge,zpow_neg,q_five_inv,T,t] + all_goals vacuum_ring_finish +theorem homogeneous_uncup_entry_16_2 (x y : ℂ) : + homogeneousUncupLeft x y .plus .minus .plus .minus = homogeneousUncupRight x y .plus .minus .plus .minus := by + norm_num [homogeneousUncupLeft,homogeneousUncupRight,sum_spin,exchangeNumerator_eq_table,exchangeTable, + exchangeDenominator,cup,charge,zpow_neg,q_five_inv,T,t] +theorem homogeneous_uncup_entry_17_0 (x y : ℂ) : + homogeneousUncupLeft x y .plus .minus .minus .zero = homogeneousUncupRight x y .plus .minus .minus .zero := by + norm_num [homogeneousUncupLeft,homogeneousUncupRight,sum_spin,exchangeNumerator_eq_table,exchangeTable, + exchangeDenominator,cup,charge,zpow_neg,q_five_inv,T,t] +theorem homogeneous_uncup_entry_17_1 (x y : ℂ) : + homogeneousUncupLeft x y .plus .minus .minus .plus = homogeneousUncupRight x y .plus .minus .minus .plus := by + norm_num [homogeneousUncupLeft,homogeneousUncupRight,sum_spin,exchangeNumerator_eq_table,exchangeTable, + exchangeDenominator,cup,charge,zpow_neg,q_five_inv,T,t] +theorem homogeneous_uncup_entry_17_2 (x y : ℂ) : + homogeneousUncupLeft x y .plus .minus .minus .minus = homogeneousUncupRight x y .plus .minus .minus .minus := by + norm_num [homogeneousUncupLeft,homogeneousUncupRight,sum_spin,exchangeNumerator_eq_table,exchangeTable, + exchangeDenominator,cup,charge,zpow_neg,q_five_inv,T,t] + all_goals vacuum_ring_finish +theorem homogeneous_uncup_entry_18_0 (x y : ℂ) : + homogeneousUncupLeft x y .minus .zero .zero .zero = homogeneousUncupRight x y .minus .zero .zero .zero := by + norm_num [homogeneousUncupLeft,homogeneousUncupRight,sum_spin,exchangeNumerator_eq_table,exchangeTable, + exchangeDenominator,cup,charge,zpow_neg,q_five_inv,T,t] +theorem homogeneous_uncup_entry_18_1 (x y : ℂ) : + homogeneousUncupLeft x y .minus .zero .zero .plus = homogeneousUncupRight x y .minus .zero .zero .plus := by + norm_num [homogeneousUncupLeft,homogeneousUncupRight,sum_spin,exchangeNumerator_eq_table,exchangeTable, + exchangeDenominator,cup,charge,zpow_neg,q_five_inv,T,t] +theorem homogeneous_uncup_entry_18_2 (x y : ℂ) : + homogeneousUncupLeft x y .minus .zero .zero .minus = homogeneousUncupRight x y .minus .zero .zero .minus := by + norm_num [homogeneousUncupLeft,homogeneousUncupRight,sum_spin,exchangeNumerator_eq_table,exchangeTable, + exchangeDenominator,cup,charge,zpow_neg,q_five_inv,T,t] + all_goals vacuum_ring_finish +theorem homogeneous_uncup_entry_19_0 (x y : ℂ) : + homogeneousUncupLeft x y .minus .zero .plus .zero = homogeneousUncupRight x y .minus .zero .plus .zero := by + norm_num [homogeneousUncupLeft,homogeneousUncupRight,sum_spin,exchangeNumerator_eq_table,exchangeTable, + exchangeDenominator,cup,charge,zpow_neg,q_five_inv,T,t] + all_goals vacuum_ring_finish +theorem homogeneous_uncup_entry_19_1 (x y : ℂ) : + homogeneousUncupLeft x y .minus .zero .plus .plus = homogeneousUncupRight x y .minus .zero .plus .plus := by + norm_num [homogeneousUncupLeft,homogeneousUncupRight,sum_spin,exchangeNumerator_eq_table,exchangeTable, + exchangeDenominator,cup,charge,zpow_neg,q_five_inv,T,t] +theorem homogeneous_uncup_entry_19_2 (x y : ℂ) : + homogeneousUncupLeft x y .minus .zero .plus .minus = homogeneousUncupRight x y .minus .zero .plus .minus := by + norm_num [homogeneousUncupLeft,homogeneousUncupRight,sum_spin,exchangeNumerator_eq_table,exchangeTable, + exchangeDenominator,cup,charge,zpow_neg,q_five_inv,T,t] +theorem homogeneous_uncup_entry_20_0 (x y : ℂ) : + homogeneousUncupLeft x y .minus .zero .minus .zero = homogeneousUncupRight x y .minus .zero .minus .zero := by + norm_num [homogeneousUncupLeft,homogeneousUncupRight,sum_spin,exchangeNumerator_eq_table,exchangeTable, + exchangeDenominator,cup,charge,zpow_neg,q_five_inv,T,t] +theorem homogeneous_uncup_entry_20_1 (x y : ℂ) : + homogeneousUncupLeft x y .minus .zero .minus .plus = homogeneousUncupRight x y .minus .zero .minus .plus := by + norm_num [homogeneousUncupLeft,homogeneousUncupRight,sum_spin,exchangeNumerator_eq_table,exchangeTable, + exchangeDenominator,cup,charge,zpow_neg,q_five_inv,T,t] +theorem homogeneous_uncup_entry_20_2 (x y : ℂ) : + homogeneousUncupLeft x y .minus .zero .minus .minus = homogeneousUncupRight x y .minus .zero .minus .minus := by + norm_num [homogeneousUncupLeft,homogeneousUncupRight,sum_spin,exchangeNumerator_eq_table,exchangeTable, + exchangeDenominator,cup,charge,zpow_neg,q_five_inv,T,t] +theorem homogeneous_uncup_entry_21_0 (x y : ℂ) : + homogeneousUncupLeft x y .minus .plus .zero .zero = homogeneousUncupRight x y .minus .plus .zero .zero := by + norm_num [homogeneousUncupLeft,homogeneousUncupRight,sum_spin,exchangeNumerator_eq_table,exchangeTable, + exchangeDenominator,cup,charge,zpow_neg,q_five_inv,T,t] + all_goals vacuum_ring_finish +theorem homogeneous_uncup_entry_21_1 (x y : ℂ) : + homogeneousUncupLeft x y .minus .plus .zero .plus = homogeneousUncupRight x y .minus .plus .zero .plus := by + norm_num [homogeneousUncupLeft,homogeneousUncupRight,sum_spin,exchangeNumerator_eq_table,exchangeTable, + exchangeDenominator,cup,charge,zpow_neg,q_five_inv,T,t] +theorem homogeneous_uncup_entry_21_2 (x y : ℂ) : + homogeneousUncupLeft x y .minus .plus .zero .minus = homogeneousUncupRight x y .minus .plus .zero .minus := by + norm_num [homogeneousUncupLeft,homogeneousUncupRight,sum_spin,exchangeNumerator_eq_table,exchangeTable, + exchangeDenominator,cup,charge,zpow_neg,q_five_inv,T,t] +theorem homogeneous_uncup_entry_22_0 (x y : ℂ) : + homogeneousUncupLeft x y .minus .plus .plus .zero = homogeneousUncupRight x y .minus .plus .plus .zero := by + norm_num [homogeneousUncupLeft,homogeneousUncupRight,sum_spin,exchangeNumerator_eq_table,exchangeTable, + exchangeDenominator,cup,charge,zpow_neg,q_five_inv,T,t] +theorem homogeneous_uncup_entry_22_1 (x y : ℂ) : + homogeneousUncupLeft x y .minus .plus .plus .plus = homogeneousUncupRight x y .minus .plus .plus .plus := by + norm_num [homogeneousUncupLeft,homogeneousUncupRight,sum_spin,exchangeNumerator_eq_table,exchangeTable, + exchangeDenominator,cup,charge,zpow_neg,q_five_inv,T,t] + all_goals vacuum_ring_finish +theorem homogeneous_uncup_entry_22_2 (x y : ℂ) : + homogeneousUncupLeft x y .minus .plus .plus .minus = homogeneousUncupRight x y .minus .plus .plus .minus := by + norm_num [homogeneousUncupLeft,homogeneousUncupRight,sum_spin,exchangeNumerator_eq_table,exchangeTable, + exchangeDenominator,cup,charge,zpow_neg,q_five_inv,T,t] +theorem homogeneous_uncup_entry_23_0 (x y : ℂ) : + homogeneousUncupLeft x y .minus .plus .minus .zero = homogeneousUncupRight x y .minus .plus .minus .zero := by + norm_num [homogeneousUncupLeft,homogeneousUncupRight,sum_spin,exchangeNumerator_eq_table,exchangeTable, + exchangeDenominator,cup,charge,zpow_neg,q_five_inv,T,t] +theorem homogeneous_uncup_entry_23_1 (x y : ℂ) : + homogeneousUncupLeft x y .minus .plus .minus .plus = homogeneousUncupRight x y .minus .plus .minus .plus := by + norm_num [homogeneousUncupLeft,homogeneousUncupRight,sum_spin,exchangeNumerator_eq_table,exchangeTable, + exchangeDenominator,cup,charge,zpow_neg,q_five_inv,T,t] +theorem homogeneous_uncup_entry_23_2 (x y : ℂ) : + homogeneousUncupLeft x y .minus .plus .minus .minus = homogeneousUncupRight x y .minus .plus .minus .minus := by + norm_num [homogeneousUncupLeft,homogeneousUncupRight,sum_spin,exchangeNumerator_eq_table,exchangeTable, + exchangeDenominator,cup,charge,zpow_neg,q_five_inv,T,t] + all_goals vacuum_ring_finish +theorem homogeneous_uncup_entry_24_0 (x y : ℂ) : + homogeneousUncupLeft x y .minus .minus .zero .zero = homogeneousUncupRight x y .minus .minus .zero .zero := by + norm_num [homogeneousUncupLeft,homogeneousUncupRight,sum_spin,exchangeNumerator_eq_table,exchangeTable, + exchangeDenominator,cup,charge,zpow_neg,q_five_inv,T,t] +theorem homogeneous_uncup_entry_24_1 (x y : ℂ) : + homogeneousUncupLeft x y .minus .minus .zero .plus = homogeneousUncupRight x y .minus .minus .zero .plus := by + norm_num [homogeneousUncupLeft,homogeneousUncupRight,sum_spin,exchangeNumerator_eq_table,exchangeTable, + exchangeDenominator,cup,charge,zpow_neg,q_five_inv,T,t] +theorem homogeneous_uncup_entry_24_2 (x y : ℂ) : + homogeneousUncupLeft x y .minus .minus .zero .minus = homogeneousUncupRight x y .minus .minus .zero .minus := by + norm_num [homogeneousUncupLeft,homogeneousUncupRight,sum_spin,exchangeNumerator_eq_table,exchangeTable, + exchangeDenominator,cup,charge,zpow_neg,q_five_inv,T,t] +theorem homogeneous_uncup_entry_25_0 (x y : ℂ) : + homogeneousUncupLeft x y .minus .minus .plus .zero = homogeneousUncupRight x y .minus .minus .plus .zero := by + norm_num [homogeneousUncupLeft,homogeneousUncupRight,sum_spin,exchangeNumerator_eq_table,exchangeTable, + exchangeDenominator,cup,charge,zpow_neg,q_five_inv,T,t] +theorem homogeneous_uncup_entry_25_1 (x y : ℂ) : + homogeneousUncupLeft x y .minus .minus .plus .plus = homogeneousUncupRight x y .minus .minus .plus .plus := by + norm_num [homogeneousUncupLeft,homogeneousUncupRight,sum_spin,exchangeNumerator_eq_table,exchangeTable, + exchangeDenominator,cup,charge,zpow_neg,q_five_inv,T,t] +theorem homogeneous_uncup_entry_25_2 (x y : ℂ) : + homogeneousUncupLeft x y .minus .minus .plus .minus = homogeneousUncupRight x y .minus .minus .plus .minus := by + norm_num [homogeneousUncupLeft,homogeneousUncupRight,sum_spin,exchangeNumerator_eq_table,exchangeTable, + exchangeDenominator,cup,charge,zpow_neg,q_five_inv,T,t] + all_goals vacuum_ring_finish +theorem homogeneous_uncup_entry_26_0 (x y : ℂ) : + homogeneousUncupLeft x y .minus .minus .minus .zero = homogeneousUncupRight x y .minus .minus .minus .zero := by + norm_num [homogeneousUncupLeft,homogeneousUncupRight,sum_spin,exchangeNumerator_eq_table,exchangeTable, + exchangeDenominator,cup,charge,zpow_neg,q_five_inv,T,t] +theorem homogeneous_uncup_entry_26_1 (x y : ℂ) : + homogeneousUncupLeft x y .minus .minus .minus .plus = homogeneousUncupRight x y .minus .minus .minus .plus := by + norm_num [homogeneousUncupLeft,homogeneousUncupRight,sum_spin,exchangeNumerator_eq_table,exchangeTable, + exchangeDenominator,cup,charge,zpow_neg,q_five_inv,T,t] +theorem homogeneous_uncup_entry_26_2 (x y : ℂ) : + homogeneousUncupLeft x y .minus .minus .minus .minus = homogeneousUncupRight x y .minus .minus .minus .minus := by + norm_num [homogeneousUncupLeft,homogeneousUncupRight,sum_spin,exchangeNumerator_eq_table,exchangeTable, + exchangeDenominator,cup,charge,zpow_neg,q_five_inv,T,t] +theorem homogeneous_cup_unslide (x y : ℂ) (a b c h : Spin) : + homogeneousUncupLeft x y a b c h = homogeneousUncupRight x y a b c h := by + cases a <;> cases b <;> cases c <;> cases h + · exact homogeneous_uncup_entry_0_0 x y + · exact homogeneous_uncup_entry_0_1 x y + · exact homogeneous_uncup_entry_0_2 x y + · exact homogeneous_uncup_entry_1_0 x y + · exact homogeneous_uncup_entry_1_1 x y + · exact homogeneous_uncup_entry_1_2 x y + · exact homogeneous_uncup_entry_2_0 x y + · exact homogeneous_uncup_entry_2_1 x y + · exact homogeneous_uncup_entry_2_2 x y + · exact homogeneous_uncup_entry_3_0 x y + · exact homogeneous_uncup_entry_3_1 x y + · exact homogeneous_uncup_entry_3_2 x y + · exact homogeneous_uncup_entry_4_0 x y + · exact homogeneous_uncup_entry_4_1 x y + · exact homogeneous_uncup_entry_4_2 x y + · exact homogeneous_uncup_entry_5_0 x y + · exact homogeneous_uncup_entry_5_1 x y + · exact homogeneous_uncup_entry_5_2 x y + · exact homogeneous_uncup_entry_6_0 x y + · exact homogeneous_uncup_entry_6_1 x y + · exact homogeneous_uncup_entry_6_2 x y + · exact homogeneous_uncup_entry_7_0 x y + · exact homogeneous_uncup_entry_7_1 x y + · exact homogeneous_uncup_entry_7_2 x y + · exact homogeneous_uncup_entry_8_0 x y + · exact homogeneous_uncup_entry_8_1 x y + · exact homogeneous_uncup_entry_8_2 x y + · exact homogeneous_uncup_entry_9_0 x y + · exact homogeneous_uncup_entry_9_1 x y + · exact homogeneous_uncup_entry_9_2 x y + · exact homogeneous_uncup_entry_10_0 x y + · exact homogeneous_uncup_entry_10_1 x y + · exact homogeneous_uncup_entry_10_2 x y + · exact homogeneous_uncup_entry_11_0 x y + · exact homogeneous_uncup_entry_11_1 x y + · exact homogeneous_uncup_entry_11_2 x y + · exact homogeneous_uncup_entry_12_0 x y + · exact homogeneous_uncup_entry_12_1 x y + · exact homogeneous_uncup_entry_12_2 x y + · exact homogeneous_uncup_entry_13_0 x y + · exact homogeneous_uncup_entry_13_1 x y + · exact homogeneous_uncup_entry_13_2 x y + · exact homogeneous_uncup_entry_14_0 x y + · exact homogeneous_uncup_entry_14_1 x y + · exact homogeneous_uncup_entry_14_2 x y + · exact homogeneous_uncup_entry_15_0 x y + · exact homogeneous_uncup_entry_15_1 x y + · exact homogeneous_uncup_entry_15_2 x y + · exact homogeneous_uncup_entry_16_0 x y + · exact homogeneous_uncup_entry_16_1 x y + · exact homogeneous_uncup_entry_16_2 x y + · exact homogeneous_uncup_entry_17_0 x y + · exact homogeneous_uncup_entry_17_1 x y + · exact homogeneous_uncup_entry_17_2 x y + · exact homogeneous_uncup_entry_18_0 x y + · exact homogeneous_uncup_entry_18_1 x y + · exact homogeneous_uncup_entry_18_2 x y + · exact homogeneous_uncup_entry_19_0 x y + · exact homogeneous_uncup_entry_19_1 x y + · exact homogeneous_uncup_entry_19_2 x y + · exact homogeneous_uncup_entry_20_0 x y + · exact homogeneous_uncup_entry_20_1 x y + · exact homogeneous_uncup_entry_20_2 x y + · exact homogeneous_uncup_entry_21_0 x y + · exact homogeneous_uncup_entry_21_1 x y + · exact homogeneous_uncup_entry_21_2 x y + · exact homogeneous_uncup_entry_22_0 x y + · exact homogeneous_uncup_entry_22_1 x y + · exact homogeneous_uncup_entry_22_2 x y + · exact homogeneous_uncup_entry_23_0 x y + · exact homogeneous_uncup_entry_23_1 x y + · exact homogeneous_uncup_entry_23_2 x y + · exact homogeneous_uncup_entry_24_0 x y + · exact homogeneous_uncup_entry_24_1 x y + · exact homogeneous_uncup_entry_24_2 x y + · exact homogeneous_uncup_entry_25_0 x y + · exact homogeneous_uncup_entry_25_1 x y + · exact homogeneous_uncup_entry_25_2 x y + · exact homogeneous_uncup_entry_26_0 x y + · exact homogeneous_uncup_entry_26_1 x y + · exact homogeneous_uncup_entry_26_2 x y +end PolynomialVacuumAlgebra + +end OAI diff --git a/lean/OAI/Combinatorics/PolynomialVacuum/Algebra/HomogeneousYangBaxter.lean b/lean/OAI/Combinatorics/PolynomialVacuum/Algebra/HomogeneousYangBaxter.lean new file mode 100644 index 0000000000000000000000000000000000000000..a5c37bdfae4a1946cad4ddf662f5b8d0763bb541 --- /dev/null +++ b/lean/OAI/Combinatorics/PolynomialVacuum/Algebra/HomogeneousYangBaxter.lean @@ -0,0 +1,4891 @@ +import OAI.Combinatorics.PolynomialVacuum.Algebra.Table + +namespace OAI + +namespace PolynomialVacuumAlgebra + + +noncomputable def hybLeft (x y z : ℂ) (a b c d e f : Spin) : ℂ := + ∑ i : Spin, ∑ j : Spin, ∑ k : Spin, + exchangeNumerator x y (a,b) (i,j) * + exchangeNumerator x z (j,c) (k,f) * + exchangeNumerator y z (i,k) (d,e) + + +noncomputable def hybRight (x y z : ℂ) (a b c d e f : Spin) : ℂ := + ∑ i : Spin, ∑ j : Spin, ∑ k : Spin, + exchangeNumerator y z (b,c) (j,k) * + exchangeNumerator x z (a,j) (d,i) * + exchangeNumerator x y (i,k) (e,f) + +theorem hyb_entry_0_0 (x y z : ℂ) : + hybLeft x y z .zero .zero .zero .zero .zero .zero = hybRight x y z .zero .zero .zero .zero .zero .zero := by + simp only [hybLeft,hybRight,sum_spin,exchangeNumerator_eq_table,exchangeTable, + mul_zero,zero_mul,zero_add,add_zero] + all_goals ring_nf + +theorem hyb_entry_0_1 (x y z : ℂ) : + hybLeft x y z .zero .zero .zero .zero .zero .plus = hybRight x y z .zero .zero .zero .zero .zero .plus := by + simp only [hybLeft,hybRight,sum_spin,exchangeNumerator_eq_table,exchangeTable, + mul_zero,zero_mul,zero_add,add_zero] + +theorem hyb_entry_0_2 (x y z : ℂ) : + hybLeft x y z .zero .zero .zero .zero .zero .minus = hybRight x y z .zero .zero .zero .zero .zero .minus := by + simp only [hybLeft,hybRight,sum_spin,exchangeNumerator_eq_table,exchangeTable, + mul_zero,zero_mul,zero_add,add_zero] + +theorem hyb_entry_0_3 (x y z : ℂ) : + hybLeft x y z .zero .zero .zero .zero .plus .zero = hybRight x y z .zero .zero .zero .zero .plus .zero := by + simp only [hybLeft,hybRight,sum_spin,exchangeNumerator_eq_table,exchangeTable, + mul_zero,zero_mul,zero_add,add_zero] + +theorem hyb_entry_0_4 (x y z : ℂ) : + hybLeft x y z .zero .zero .zero .zero .plus .plus = hybRight x y z .zero .zero .zero .zero .plus .plus := by + simp only [hybLeft,hybRight,sum_spin,exchangeNumerator_eq_table,exchangeTable, + mul_zero,zero_mul,zero_add,add_zero] + +theorem hyb_entry_0_5 (x y z : ℂ) : + hybLeft x y z .zero .zero .zero .zero .plus .minus = hybRight x y z .zero .zero .zero .zero .plus .minus := by + simp only [hybLeft,hybRight,sum_spin,exchangeNumerator_eq_table,exchangeTable, + mul_zero,zero_mul,zero_add,add_zero] + all_goals ring_nf + all_goals try simp only [q_pow_9,q_pow_11,q_pow_13,q_pow_15,q_pow_17] + all_goals ring + +theorem hyb_entry_0_6 (x y z : ℂ) : + hybLeft x y z .zero .zero .zero .zero .minus .zero = hybRight x y z .zero .zero .zero .zero .minus .zero := by + simp only [hybLeft,hybRight,sum_spin,exchangeNumerator_eq_table,exchangeTable, + mul_zero,zero_mul,zero_add,add_zero] + +theorem hyb_entry_0_7 (x y z : ℂ) : + hybLeft x y z .zero .zero .zero .zero .minus .plus = hybRight x y z .zero .zero .zero .zero .minus .plus := by + simp only [hybLeft,hybRight,sum_spin,exchangeNumerator_eq_table,exchangeTable, + mul_zero,zero_mul,zero_add,add_zero] + all_goals ring_nf + all_goals try simp only [q_pow_9,q_pow_11,q_pow_13,q_pow_15,q_pow_17] + all_goals ring + +theorem hyb_entry_0_8 (x y z : ℂ) : + hybLeft x y z .zero .zero .zero .zero .minus .minus = hybRight x y z .zero .zero .zero .zero .minus .minus := by + simp only [hybLeft,hybRight,sum_spin,exchangeNumerator_eq_table,exchangeTable, + mul_zero,zero_mul,zero_add,add_zero] + +theorem hyb_entry_0_9 (x y z : ℂ) : + hybLeft x y z .zero .zero .zero .plus .zero .zero = hybRight x y z .zero .zero .zero .plus .zero .zero := by + simp only [hybLeft,hybRight,sum_spin,exchangeNumerator_eq_table,exchangeTable, + mul_zero,zero_mul,zero_add,add_zero] + +theorem hyb_entry_0_10 (x y z : ℂ) : + hybLeft x y z .zero .zero .zero .plus .zero .plus = hybRight x y z .zero .zero .zero .plus .zero .plus := by + simp only [hybLeft,hybRight,sum_spin,exchangeNumerator_eq_table,exchangeTable, + mul_zero,zero_mul,zero_add,add_zero] + +theorem hyb_entry_0_11 (x y z : ℂ) : + hybLeft x y z .zero .zero .zero .plus .zero .minus = hybRight x y z .zero .zero .zero .plus .zero .minus := by + simp only [hybLeft,hybRight,sum_spin,exchangeNumerator_eq_table,exchangeTable, + mul_zero,zero_mul,zero_add,add_zero] + all_goals ring_nf + +theorem hyb_entry_0_12 (x y z : ℂ) : + hybLeft x y z .zero .zero .zero .plus .plus .zero = hybRight x y z .zero .zero .zero .plus .plus .zero := by + simp only [hybLeft,hybRight,sum_spin,exchangeNumerator_eq_table,exchangeTable, + mul_zero,zero_mul,zero_add,add_zero] + +theorem hyb_entry_0_13 (x y z : ℂ) : + hybLeft x y z .zero .zero .zero .plus .plus .plus = hybRight x y z .zero .zero .zero .plus .plus .plus := by + simp only [hybLeft,hybRight,sum_spin,exchangeNumerator_eq_table,exchangeTable, + mul_zero,zero_mul,zero_add,add_zero] + +theorem hyb_entry_0_14 (x y z : ℂ) : + hybLeft x y z .zero .zero .zero .plus .plus .minus = hybRight x y z .zero .zero .zero .plus .plus .minus := by + simp only [hybLeft,hybRight,sum_spin,exchangeNumerator_eq_table,exchangeTable, + mul_zero,zero_mul,zero_add,add_zero] + +theorem hyb_entry_0_15 (x y z : ℂ) : + hybLeft x y z .zero .zero .zero .plus .minus .zero = hybRight x y z .zero .zero .zero .plus .minus .zero := by + simp only [hybLeft,hybRight,sum_spin,exchangeNumerator_eq_table,exchangeTable, + mul_zero,zero_mul,zero_add,add_zero] + all_goals ring_nf + all_goals try simp only [q_pow_9,q_pow_11,q_pow_13,q_pow_15,q_pow_17] + all_goals ring + +theorem hyb_entry_0_16 (x y z : ℂ) : + hybLeft x y z .zero .zero .zero .plus .minus .plus = hybRight x y z .zero .zero .zero .plus .minus .plus := by + simp only [hybLeft,hybRight,sum_spin,exchangeNumerator_eq_table,exchangeTable, + mul_zero,zero_mul,zero_add,add_zero] + +theorem hyb_entry_0_17 (x y z : ℂ) : + hybLeft x y z .zero .zero .zero .plus .minus .minus = hybRight x y z .zero .zero .zero .plus .minus .minus := by + simp only [hybLeft,hybRight,sum_spin,exchangeNumerator_eq_table,exchangeTable, + mul_zero,zero_mul,zero_add,add_zero] + +theorem hyb_entry_0_18 (x y z : ℂ) : + hybLeft x y z .zero .zero .zero .minus .zero .zero = hybRight x y z .zero .zero .zero .minus .zero .zero := by + simp only [hybLeft,hybRight,sum_spin,exchangeNumerator_eq_table,exchangeTable, + mul_zero,zero_mul,zero_add,add_zero] + +theorem hyb_entry_0_19 (x y z : ℂ) : + hybLeft x y z .zero .zero .zero .minus .zero .plus = hybRight x y z .zero .zero .zero .minus .zero .plus := by + simp only [hybLeft,hybRight,sum_spin,exchangeNumerator_eq_table,exchangeTable, + mul_zero,zero_mul,zero_add,add_zero] + all_goals ring_nf + +theorem hyb_entry_0_20 (x y z : ℂ) : + hybLeft x y z .zero .zero .zero .minus .zero .minus = hybRight x y z .zero .zero .zero .minus .zero .minus := by + simp only [hybLeft,hybRight,sum_spin,exchangeNumerator_eq_table,exchangeTable, + mul_zero,zero_mul,zero_add,add_zero] + +theorem hyb_entry_0_21 (x y z : ℂ) : + hybLeft x y z .zero .zero .zero .minus .plus .zero = hybRight x y z .zero .zero .zero .minus .plus .zero := by + simp only [hybLeft,hybRight,sum_spin,exchangeNumerator_eq_table,exchangeTable, + mul_zero,zero_mul,zero_add,add_zero] + all_goals ring_nf + all_goals try simp only [q_pow_9,q_pow_11,q_pow_13,q_pow_15,q_pow_17] + all_goals ring + +theorem hyb_entry_0_22 (x y z : ℂ) : + hybLeft x y z .zero .zero .zero .minus .plus .plus = hybRight x y z .zero .zero .zero .minus .plus .plus := by + simp only [hybLeft,hybRight,sum_spin,exchangeNumerator_eq_table,exchangeTable, + mul_zero,zero_mul,zero_add,add_zero] + +theorem hyb_entry_0_23 (x y z : ℂ) : + hybLeft x y z .zero .zero .zero .minus .plus .minus = hybRight x y z .zero .zero .zero .minus .plus .minus := by + simp only [hybLeft,hybRight,sum_spin,exchangeNumerator_eq_table,exchangeTable, + mul_zero,zero_mul,zero_add,add_zero] + +theorem hyb_entry_0_24 (x y z : ℂ) : + hybLeft x y z .zero .zero .zero .minus .minus .zero = hybRight x y z .zero .zero .zero .minus .minus .zero := by + simp only [hybLeft,hybRight,sum_spin,exchangeNumerator_eq_table,exchangeTable, + mul_zero,zero_mul,zero_add,add_zero] + +theorem hyb_entry_0_25 (x y z : ℂ) : + hybLeft x y z .zero .zero .zero .minus .minus .plus = hybRight x y z .zero .zero .zero .minus .minus .plus := by + simp only [hybLeft,hybRight,sum_spin,exchangeNumerator_eq_table,exchangeTable, + mul_zero,zero_mul,zero_add,add_zero] + +theorem hyb_entry_0_26 (x y z : ℂ) : + hybLeft x y z .zero .zero .zero .minus .minus .minus = hybRight x y z .zero .zero .zero .minus .minus .minus := by + simp only [hybLeft,hybRight,sum_spin,exchangeNumerator_eq_table,exchangeTable, + mul_zero,zero_mul,zero_add,add_zero] + +theorem hyb_entry_1_0 (x y z : ℂ) : + hybLeft x y z .zero .zero .plus .zero .zero .zero = hybRight x y z .zero .zero .plus .zero .zero .zero := by + simp only [hybLeft,hybRight,sum_spin,exchangeNumerator_eq_table,exchangeTable, + mul_zero,zero_mul,zero_add,add_zero] + +theorem hyb_entry_1_1 (x y z : ℂ) : + hybLeft x y z .zero .zero .plus .zero .zero .plus = hybRight x y z .zero .zero .plus .zero .zero .plus := by + simp only [hybLeft,hybRight,sum_spin,exchangeNumerator_eq_table,exchangeTable, + mul_zero,zero_mul,zero_add,add_zero] + all_goals ring_nf + all_goals try simp only [q_pow_eight,q_pow_10,q_pow_12,q_pow_14,q_pow_16,q_pow_18] + all_goals ring + +theorem hyb_entry_1_2 (x y z : ℂ) : + hybLeft x y z .zero .zero .plus .zero .zero .minus = hybRight x y z .zero .zero .plus .zero .zero .minus := by + simp only [hybLeft,hybRight,sum_spin,exchangeNumerator_eq_table,exchangeTable, + mul_zero,zero_mul,zero_add,add_zero] + +theorem hyb_entry_1_3 (x y z : ℂ) : + hybLeft x y z .zero .zero .plus .zero .plus .zero = hybRight x y z .zero .zero .plus .zero .plus .zero := by + simp only [hybLeft,hybRight,sum_spin,exchangeNumerator_eq_table,exchangeTable, + mul_zero,zero_mul,zero_add,add_zero] + all_goals ring_nf + all_goals try simp only [q_pow_eight,q_pow_10,q_pow_12,q_pow_14] + all_goals ring + +theorem hyb_entry_1_4 (x y z : ℂ) : + hybLeft x y z .zero .zero .plus .zero .plus .plus = hybRight x y z .zero .zero .plus .zero .plus .plus := by + simp only [hybLeft,hybRight,sum_spin,exchangeNumerator_eq_table,exchangeTable, + mul_zero,zero_mul,zero_add,add_zero] + +theorem hyb_entry_1_5 (x y z : ℂ) : + hybLeft x y z .zero .zero .plus .zero .plus .minus = hybRight x y z .zero .zero .plus .zero .plus .minus := by + simp only [hybLeft,hybRight,sum_spin,exchangeNumerator_eq_table,exchangeTable, + mul_zero,zero_mul,zero_add,add_zero] + +theorem hyb_entry_1_6 (x y z : ℂ) : + hybLeft x y z .zero .zero .plus .zero .minus .zero = hybRight x y z .zero .zero .plus .zero .minus .zero := by + simp only [hybLeft,hybRight,sum_spin,exchangeNumerator_eq_table,exchangeTable, + mul_zero,zero_mul,zero_add,add_zero] + +theorem hyb_entry_1_7 (x y z : ℂ) : + hybLeft x y z .zero .zero .plus .zero .minus .plus = hybRight x y z .zero .zero .plus .zero .minus .plus := by + simp only [hybLeft,hybRight,sum_spin,exchangeNumerator_eq_table,exchangeTable, + mul_zero,zero_mul,zero_add,add_zero] + +theorem hyb_entry_1_8 (x y z : ℂ) : + hybLeft x y z .zero .zero .plus .zero .minus .minus = hybRight x y z .zero .zero .plus .zero .minus .minus := by + simp only [hybLeft,hybRight,sum_spin,exchangeNumerator_eq_table,exchangeTable, + mul_zero,zero_mul,add_zero] + +theorem hyb_entry_1_9 (x y z : ℂ) : + hybLeft x y z .zero .zero .plus .plus .zero .zero = hybRight x y z .zero .zero .plus .plus .zero .zero := by + simp only [hybLeft,hybRight,sum_spin,exchangeNumerator_eq_table,exchangeTable, + mul_zero,zero_mul,zero_add,add_zero] + all_goals ring_nf + +theorem hyb_entry_1_10 (x y z : ℂ) : + hybLeft x y z .zero .zero .plus .plus .zero .plus = hybRight x y z .zero .zero .plus .plus .zero .plus := by + simp only [hybLeft,hybRight,sum_spin,exchangeNumerator_eq_table,exchangeTable, + mul_zero,zero_mul,zero_add,add_zero] + +theorem hyb_entry_1_11 (x y z : ℂ) : + hybLeft x y z .zero .zero .plus .plus .zero .minus = hybRight x y z .zero .zero .plus .plus .zero .minus := by + simp only [hybLeft,hybRight,sum_spin,exchangeNumerator_eq_table,exchangeTable, + mul_zero,zero_mul,zero_add,add_zero] + +theorem hyb_entry_1_12 (x y z : ℂ) : + hybLeft x y z .zero .zero .plus .plus .plus .zero = hybRight x y z .zero .zero .plus .plus .plus .zero := by + simp only [hybLeft,hybRight,sum_spin,exchangeNumerator_eq_table,exchangeTable, + mul_zero,zero_mul,zero_add,add_zero] + +theorem hyb_entry_1_13 (x y z : ℂ) : + hybLeft x y z .zero .zero .plus .plus .plus .plus = hybRight x y z .zero .zero .plus .plus .plus .plus := by + simp only [hybLeft,hybRight,sum_spin,exchangeNumerator_eq_table,exchangeTable, + mul_zero,zero_mul,zero_add,add_zero] + +theorem hyb_entry_1_14 (x y z : ℂ) : + hybLeft x y z .zero .zero .plus .plus .plus .minus = hybRight x y z .zero .zero .plus .plus .plus .minus := by + simp only [hybLeft,hybRight,sum_spin,exchangeNumerator_eq_table,exchangeTable, + mul_zero,zero_mul,zero_add,add_zero] + all_goals ring_nf + all_goals try simp only [q_pow_9,q_pow_11,q_pow_13,q_pow_15,q_pow_17] + all_goals ring + +theorem hyb_entry_1_15 (x y z : ℂ) : + hybLeft x y z .zero .zero .plus .plus .minus .zero = hybRight x y z .zero .zero .plus .plus .minus .zero := by + simp only [hybLeft,hybRight,sum_spin,exchangeNumerator_eq_table,exchangeTable, + mul_zero,zero_mul,zero_add,add_zero] + +theorem hyb_entry_1_16 (x y z : ℂ) : + hybLeft x y z .zero .zero .plus .plus .minus .plus = hybRight x y z .zero .zero .plus .plus .minus .plus := by + simp only [hybLeft,hybRight,sum_spin,exchangeNumerator_eq_table,exchangeTable, + mul_zero,zero_mul,zero_add,add_zero] + all_goals ring_nf + all_goals try simp only [q_pow_9,q_pow_11,q_pow_13,q_pow_15,q_pow_17] + all_goals ring + +theorem hyb_entry_1_17 (x y z : ℂ) : + hybLeft x y z .zero .zero .plus .plus .minus .minus = hybRight x y z .zero .zero .plus .plus .minus .minus := by + simp only [hybLeft,hybRight,sum_spin,exchangeNumerator_eq_table,exchangeTable, + mul_zero,zero_mul,zero_add,add_zero] + +theorem hyb_entry_1_18 (x y z : ℂ) : + hybLeft x y z .zero .zero .plus .minus .zero .zero = hybRight x y z .zero .zero .plus .minus .zero .zero := by + simp only [hybLeft,hybRight,sum_spin,exchangeNumerator_eq_table,exchangeTable, + mul_zero,zero_mul,zero_add,add_zero] + +theorem hyb_entry_1_19 (x y z : ℂ) : + hybLeft x y z .zero .zero .plus .minus .zero .plus = hybRight x y z .zero .zero .plus .minus .zero .plus := by + simp only [hybLeft,hybRight,sum_spin,exchangeNumerator_eq_table,exchangeTable, + mul_zero,zero_mul,zero_add,add_zero] + +theorem hyb_entry_1_20 (x y z : ℂ) : + hybLeft x y z .zero .zero .plus .minus .zero .minus = hybRight x y z .zero .zero .plus .minus .zero .minus := by + simp only [hybLeft,hybRight,sum_spin,exchangeNumerator_eq_table,exchangeTable, + mul_zero,zero_mul,add_zero] + +theorem hyb_entry_1_21 (x y z : ℂ) : + hybLeft x y z .zero .zero .plus .minus .plus .zero = hybRight x y z .zero .zero .plus .minus .plus .zero := by + simp only [hybLeft,hybRight,sum_spin,exchangeNumerator_eq_table,exchangeTable, + mul_zero,zero_mul,zero_add,add_zero] + +theorem hyb_entry_1_22 (x y z : ℂ) : + hybLeft x y z .zero .zero .plus .minus .plus .plus = hybRight x y z .zero .zero .plus .minus .plus .plus := by + simp only [hybLeft,hybRight,sum_spin,exchangeNumerator_eq_table,exchangeTable, + mul_zero,zero_mul,zero_add,add_zero] + all_goals ring_nf + all_goals try simp only [q_pow_9,q_pow_11,q_pow_13,q_pow_15,q_pow_17] + all_goals ring + +theorem hyb_entry_1_23 (x y z : ℂ) : + hybLeft x y z .zero .zero .plus .minus .plus .minus = hybRight x y z .zero .zero .plus .minus .plus .minus := by + simp only [hybLeft,hybRight,sum_spin,exchangeNumerator_eq_table,exchangeTable, + mul_zero,zero_mul,zero_add,add_zero] + +theorem hyb_entry_1_24 (x y z : ℂ) : + hybLeft x y z .zero .zero .plus .minus .minus .zero = hybRight x y z .zero .zero .plus .minus .minus .zero := by + simp only [hybLeft,hybRight,sum_spin,exchangeNumerator_eq_table,exchangeTable, + mul_zero,zero_mul,add_zero] + +theorem hyb_entry_1_25 (x y z : ℂ) : + hybLeft x y z .zero .zero .plus .minus .minus .plus = hybRight x y z .zero .zero .plus .minus .minus .plus := by + simp only [hybLeft,hybRight,sum_spin,exchangeNumerator_eq_table,exchangeTable, + mul_zero,zero_mul,zero_add,add_zero] + +theorem hyb_entry_1_26 (x y z : ℂ) : + hybLeft x y z .zero .zero .plus .minus .minus .minus = hybRight x y z .zero .zero .plus .minus .minus .minus := by + simp only [hybLeft,hybRight,sum_spin,exchangeNumerator_eq_table,exchangeTable, + mul_zero,zero_mul,add_zero] + +theorem hyb_entry_2_0 (x y z : ℂ) : + hybLeft x y z .zero .zero .minus .zero .zero .zero = hybRight x y z .zero .zero .minus .zero .zero .zero := by + simp only [hybLeft,hybRight,sum_spin,exchangeNumerator_eq_table,exchangeTable, + mul_zero,zero_mul,zero_add,add_zero] + +theorem hyb_entry_2_1 (x y z : ℂ) : + hybLeft x y z .zero .zero .minus .zero .zero .plus = hybRight x y z .zero .zero .minus .zero .zero .plus := by + simp only [hybLeft,hybRight,sum_spin,exchangeNumerator_eq_table,exchangeTable, + mul_zero,zero_mul,zero_add,add_zero] + +theorem hyb_entry_2_2 (x y z : ℂ) : + hybLeft x y z .zero .zero .minus .zero .zero .minus = hybRight x y z .zero .zero .minus .zero .zero .minus := by + simp only [hybLeft,hybRight,sum_spin,exchangeNumerator_eq_table,exchangeTable, + mul_zero,zero_mul,zero_add,add_zero] + all_goals ring_nf + all_goals try simp only [q_pow_eight,q_pow_10,q_pow_12,q_pow_14,q_pow_16,q_pow_18] + all_goals ring + +theorem hyb_entry_2_3 (x y z : ℂ) : + hybLeft x y z .zero .zero .minus .zero .plus .zero = hybRight x y z .zero .zero .minus .zero .plus .zero := by + simp only [hybLeft,hybRight,sum_spin,exchangeNumerator_eq_table,exchangeTable, + mul_zero,zero_mul,zero_add,add_zero] + +theorem hyb_entry_2_4 (x y z : ℂ) : + hybLeft x y z .zero .zero .minus .zero .plus .plus = hybRight x y z .zero .zero .minus .zero .plus .plus := by + simp only [hybLeft,hybRight,sum_spin,exchangeNumerator_eq_table,exchangeTable, + mul_zero,zero_mul,add_zero] + +theorem hyb_entry_2_5 (x y z : ℂ) : + hybLeft x y z .zero .zero .minus .zero .plus .minus = hybRight x y z .zero .zero .minus .zero .plus .minus := by + simp only [hybLeft,hybRight,sum_spin,exchangeNumerator_eq_table,exchangeTable, + mul_zero,zero_mul,zero_add,add_zero] + +theorem hyb_entry_2_6 (x y z : ℂ) : + hybLeft x y z .zero .zero .minus .zero .minus .zero = hybRight x y z .zero .zero .minus .zero .minus .zero := by + simp only [hybLeft,hybRight,sum_spin,exchangeNumerator_eq_table,exchangeTable, + mul_zero,zero_mul,zero_add,add_zero] + all_goals ring_nf + all_goals try simp only [q_pow_eight,q_pow_10,q_pow_12,q_pow_14] + all_goals ring + +theorem hyb_entry_2_7 (x y z : ℂ) : + hybLeft x y z .zero .zero .minus .zero .minus .plus = hybRight x y z .zero .zero .minus .zero .minus .plus := by + simp only [hybLeft,hybRight,sum_spin,exchangeNumerator_eq_table,exchangeTable, + mul_zero,zero_mul,zero_add,add_zero] + +theorem hyb_entry_2_8 (x y z : ℂ) : + hybLeft x y z .zero .zero .minus .zero .minus .minus = hybRight x y z .zero .zero .minus .zero .minus .minus := by + simp only [hybLeft,hybRight,sum_spin,exchangeNumerator_eq_table,exchangeTable, + mul_zero,zero_mul,zero_add,add_zero] + +theorem hyb_entry_2_9 (x y z : ℂ) : + hybLeft x y z .zero .zero .minus .plus .zero .zero = hybRight x y z .zero .zero .minus .plus .zero .zero := by + simp only [hybLeft,hybRight,sum_spin,exchangeNumerator_eq_table,exchangeTable, + mul_zero,zero_mul,zero_add,add_zero] + +theorem hyb_entry_2_10 (x y z : ℂ) : + hybLeft x y z .zero .zero .minus .plus .zero .plus = hybRight x y z .zero .zero .minus .plus .zero .plus := by + simp only [hybLeft,hybRight,sum_spin,exchangeNumerator_eq_table,exchangeTable, + mul_zero,zero_mul,add_zero] + +theorem hyb_entry_2_11 (x y z : ℂ) : + hybLeft x y z .zero .zero .minus .plus .zero .minus = hybRight x y z .zero .zero .minus .plus .zero .minus := by + simp only [hybLeft,hybRight,sum_spin,exchangeNumerator_eq_table,exchangeTable, + mul_zero,zero_mul,zero_add,add_zero] + +theorem hyb_entry_2_12 (x y z : ℂ) : + hybLeft x y z .zero .zero .minus .plus .plus .zero = hybRight x y z .zero .zero .minus .plus .plus .zero := by + simp only [hybLeft,hybRight,sum_spin,exchangeNumerator_eq_table,exchangeTable, + mul_zero,zero_mul,add_zero] + +theorem hyb_entry_2_13 (x y z : ℂ) : + hybLeft x y z .zero .zero .minus .plus .plus .plus = hybRight x y z .zero .zero .minus .plus .plus .plus := by + simp only [hybLeft,hybRight,sum_spin,exchangeNumerator_eq_table,exchangeTable, + mul_zero,zero_mul,add_zero] + +theorem hyb_entry_2_14 (x y z : ℂ) : + hybLeft x y z .zero .zero .minus .plus .plus .minus = hybRight x y z .zero .zero .minus .plus .plus .minus := by + simp only [hybLeft,hybRight,sum_spin,exchangeNumerator_eq_table,exchangeTable, + mul_zero,zero_mul,zero_add,add_zero] + +theorem hyb_entry_2_15 (x y z : ℂ) : + hybLeft x y z .zero .zero .minus .plus .minus .zero = hybRight x y z .zero .zero .minus .plus .minus .zero := by + simp only [hybLeft,hybRight,sum_spin,exchangeNumerator_eq_table,exchangeTable, + mul_zero,zero_mul,zero_add,add_zero] + +theorem hyb_entry_2_16 (x y z : ℂ) : + hybLeft x y z .zero .zero .minus .plus .minus .plus = hybRight x y z .zero .zero .minus .plus .minus .plus := by + simp only [hybLeft,hybRight,sum_spin,exchangeNumerator_eq_table,exchangeTable, + mul_zero,zero_mul,zero_add,add_zero] + +theorem hyb_entry_2_17 (x y z : ℂ) : + hybLeft x y z .zero .zero .minus .plus .minus .minus = hybRight x y z .zero .zero .minus .plus .minus .minus := by + simp only [hybLeft,hybRight,sum_spin,exchangeNumerator_eq_table,exchangeTable, + mul_zero,zero_mul,zero_add,add_zero] + all_goals ring_nf + all_goals try simp only [q_pow_9,q_pow_11,q_pow_13,q_pow_15,q_pow_17] + all_goals ring + +theorem hyb_entry_2_18 (x y z : ℂ) : + hybLeft x y z .zero .zero .minus .minus .zero .zero = hybRight x y z .zero .zero .minus .minus .zero .zero := by + simp only [hybLeft,hybRight,sum_spin,exchangeNumerator_eq_table,exchangeTable, + mul_zero,zero_mul,zero_add,add_zero] + all_goals ring_nf + +theorem hyb_entry_2_19 (x y z : ℂ) : + hybLeft x y z .zero .zero .minus .minus .zero .plus = hybRight x y z .zero .zero .minus .minus .zero .plus := by + simp only [hybLeft,hybRight,sum_spin,exchangeNumerator_eq_table,exchangeTable, + mul_zero,zero_mul,zero_add,add_zero] + +theorem hyb_entry_2_20 (x y z : ℂ) : + hybLeft x y z .zero .zero .minus .minus .zero .minus = hybRight x y z .zero .zero .minus .minus .zero .minus := by + simp only [hybLeft,hybRight,sum_spin,exchangeNumerator_eq_table,exchangeTable, + mul_zero,zero_mul,zero_add,add_zero] + +theorem hyb_entry_2_21 (x y z : ℂ) : + hybLeft x y z .zero .zero .minus .minus .plus .zero = hybRight x y z .zero .zero .minus .minus .plus .zero := by + simp only [hybLeft,hybRight,sum_spin,exchangeNumerator_eq_table,exchangeTable, + mul_zero,zero_mul,zero_add,add_zero] + +theorem hyb_entry_2_22 (x y z : ℂ) : + hybLeft x y z .zero .zero .minus .minus .plus .plus = hybRight x y z .zero .zero .minus .minus .plus .plus := by + simp only [hybLeft,hybRight,sum_spin,exchangeNumerator_eq_table,exchangeTable, + mul_zero,zero_mul,zero_add,add_zero] + +theorem hyb_entry_2_23 (x y z : ℂ) : + hybLeft x y z .zero .zero .minus .minus .plus .minus = hybRight x y z .zero .zero .minus .minus .plus .minus := by + simp only [hybLeft,hybRight,sum_spin,exchangeNumerator_eq_table,exchangeTable, + mul_zero,zero_mul,zero_add,add_zero] + all_goals ring_nf + all_goals try simp only [q_pow_9,q_pow_11,q_pow_13,q_pow_15,q_pow_17] + all_goals ring + +theorem hyb_entry_2_24 (x y z : ℂ) : + hybLeft x y z .zero .zero .minus .minus .minus .zero = hybRight x y z .zero .zero .minus .minus .minus .zero := by + simp only [hybLeft,hybRight,sum_spin,exchangeNumerator_eq_table,exchangeTable, + mul_zero,zero_mul,zero_add,add_zero] + +theorem hyb_entry_2_25 (x y z : ℂ) : + hybLeft x y z .zero .zero .minus .minus .minus .plus = hybRight x y z .zero .zero .minus .minus .minus .plus := by + simp only [hybLeft,hybRight,sum_spin,exchangeNumerator_eq_table,exchangeTable, + mul_zero,zero_mul,zero_add,add_zero] + all_goals ring_nf + all_goals try simp only [q_pow_9,q_pow_11,q_pow_13,q_pow_15,q_pow_17] + all_goals ring + +theorem hyb_entry_2_26 (x y z : ℂ) : + hybLeft x y z .zero .zero .minus .minus .minus .minus = hybRight x y z .zero .zero .minus .minus .minus .minus := by + simp only [hybLeft,hybRight,sum_spin,exchangeNumerator_eq_table,exchangeTable, + mul_zero,zero_mul,zero_add,add_zero] + +theorem hyb_entry_3_0 (x y z : ℂ) : + hybLeft x y z .zero .plus .zero .zero .zero .zero = hybRight x y z .zero .plus .zero .zero .zero .zero := by + simp only [hybLeft,hybRight,sum_spin,exchangeNumerator_eq_table,exchangeTable, + mul_zero,zero_mul,zero_add,add_zero] + +theorem hyb_entry_3_1 (x y z : ℂ) : + hybLeft x y z .zero .plus .zero .zero .zero .plus = hybRight x y z .zero .plus .zero .zero .zero .plus := by + simp only [hybLeft,hybRight,sum_spin,exchangeNumerator_eq_table,exchangeTable, + mul_zero,zero_mul,zero_add,add_zero] + all_goals ring_nf + all_goals try simp only [q_pow_eight,q_pow_10,q_pow_12,q_pow_14] + all_goals ring + +theorem hyb_entry_3_2 (x y z : ℂ) : + hybLeft x y z .zero .plus .zero .zero .zero .minus = hybRight x y z .zero .plus .zero .zero .zero .minus := by + simp only [hybLeft,hybRight,sum_spin,exchangeNumerator_eq_table,exchangeTable, + mul_zero,zero_mul,zero_add,add_zero] + +theorem hyb_entry_3_3 (x y z : ℂ) : + hybLeft x y z .zero .plus .zero .zero .plus .zero = hybRight x y z .zero .plus .zero .zero .plus .zero := by + simp only [hybLeft,hybRight,sum_spin,exchangeNumerator_eq_table,exchangeTable, + mul_zero,zero_mul,zero_add,add_zero] + all_goals ring_nf + +theorem hyb_entry_3_4 (x y z : ℂ) : + hybLeft x y z .zero .plus .zero .zero .plus .plus = hybRight x y z .zero .plus .zero .zero .plus .plus := by + simp only [hybLeft,hybRight,sum_spin,exchangeNumerator_eq_table,exchangeTable, + mul_zero,zero_mul,zero_add,add_zero] + +theorem hyb_entry_3_5 (x y z : ℂ) : + hybLeft x y z .zero .plus .zero .zero .plus .minus = hybRight x y z .zero .plus .zero .zero .plus .minus := by + simp only [hybLeft,hybRight,sum_spin,exchangeNumerator_eq_table,exchangeTable, + mul_zero,zero_mul,zero_add,add_zero] + +theorem hyb_entry_3_6 (x y z : ℂ) : + hybLeft x y z .zero .plus .zero .zero .minus .zero = hybRight x y z .zero .plus .zero .zero .minus .zero := by + simp only [hybLeft,hybRight,sum_spin,exchangeNumerator_eq_table,exchangeTable, + mul_zero,zero_mul,zero_add,add_zero] + +theorem hyb_entry_3_7 (x y z : ℂ) : + hybLeft x y z .zero .plus .zero .zero .minus .plus = hybRight x y z .zero .plus .zero .zero .minus .plus := by + simp only [hybLeft,hybRight,sum_spin,exchangeNumerator_eq_table,exchangeTable, + mul_zero,zero_mul,zero_add,add_zero] + +theorem hyb_entry_3_8 (x y z : ℂ) : + hybLeft x y z .zero .plus .zero .zero .minus .minus = hybRight x y z .zero .plus .zero .zero .minus .minus := by + simp only [hybLeft,hybRight,sum_spin,exchangeNumerator_eq_table,exchangeTable, + mul_zero,zero_mul,add_zero] + +theorem hyb_entry_3_9 (x y z : ℂ) : + hybLeft x y z .zero .plus .zero .plus .zero .zero = hybRight x y z .zero .plus .zero .plus .zero .zero := by + simp only [hybLeft,hybRight,sum_spin,exchangeNumerator_eq_table,exchangeTable, + mul_zero,zero_mul,zero_add,add_zero] + all_goals ring_nf + all_goals try simp only [q_pow_eight,q_pow_10,q_pow_12,q_pow_14] + all_goals ring + +theorem hyb_entry_3_10 (x y z : ℂ) : + hybLeft x y z .zero .plus .zero .plus .zero .plus = hybRight x y z .zero .plus .zero .plus .zero .plus := by + simp only [hybLeft,hybRight,sum_spin,exchangeNumerator_eq_table,exchangeTable, + mul_zero,zero_mul,zero_add,add_zero] + +theorem hyb_entry_3_11 (x y z : ℂ) : + hybLeft x y z .zero .plus .zero .plus .zero .minus = hybRight x y z .zero .plus .zero .plus .zero .minus := by + simp only [hybLeft,hybRight,sum_spin,exchangeNumerator_eq_table,exchangeTable, + mul_zero,zero_mul,zero_add,add_zero] + +theorem hyb_entry_3_12 (x y z : ℂ) : + hybLeft x y z .zero .plus .zero .plus .plus .zero = hybRight x y z .zero .plus .zero .plus .plus .zero := by + simp only [hybLeft,hybRight,sum_spin,exchangeNumerator_eq_table,exchangeTable, + mul_zero,zero_mul,zero_add,add_zero] + +theorem hyb_entry_3_13 (x y z : ℂ) : + hybLeft x y z .zero .plus .zero .plus .plus .plus = hybRight x y z .zero .plus .zero .plus .plus .plus := by + simp only [hybLeft,hybRight,sum_spin,exchangeNumerator_eq_table,exchangeTable, + mul_zero,zero_mul,zero_add,add_zero] + +theorem hyb_entry_3_14 (x y z : ℂ) : + hybLeft x y z .zero .plus .zero .plus .plus .minus = hybRight x y z .zero .plus .zero .plus .plus .minus := by + simp only [hybLeft,hybRight,sum_spin,exchangeNumerator_eq_table,exchangeTable, + mul_zero,zero_mul,zero_add,add_zero] + all_goals ring_nf + all_goals try simp only [q_pow_9,q_pow_11,q_pow_13] + all_goals ring + +theorem hyb_entry_3_15 (x y z : ℂ) : + hybLeft x y z .zero .plus .zero .plus .minus .zero = hybRight x y z .zero .plus .zero .plus .minus .zero := by + simp only [hybLeft,hybRight,sum_spin,exchangeNumerator_eq_table,exchangeTable, + mul_zero,zero_mul,zero_add,add_zero] + +theorem hyb_entry_3_16 (x y z : ℂ) : + hybLeft x y z .zero .plus .zero .plus .minus .plus = hybRight x y z .zero .plus .zero .plus .minus .plus := by + simp only [hybLeft,hybRight,sum_spin,exchangeNumerator_eq_table,exchangeTable, + mul_zero,zero_mul,zero_add,add_zero] + all_goals ring_nf + all_goals try simp only [q_pow_9,q_pow_11,q_pow_13] + all_goals ring + +theorem hyb_entry_3_17 (x y z : ℂ) : + hybLeft x y z .zero .plus .zero .plus .minus .minus = hybRight x y z .zero .plus .zero .plus .minus .minus := by + simp only [hybLeft,hybRight,sum_spin,exchangeNumerator_eq_table,exchangeTable, + mul_zero,zero_mul,zero_add,add_zero] + +theorem hyb_entry_3_18 (x y z : ℂ) : + hybLeft x y z .zero .plus .zero .minus .zero .zero = hybRight x y z .zero .plus .zero .minus .zero .zero := by + simp only [hybLeft,hybRight,sum_spin,exchangeNumerator_eq_table,exchangeTable, + mul_zero,zero_mul,zero_add,add_zero] + +theorem hyb_entry_3_19 (x y z : ℂ) : + hybLeft x y z .zero .plus .zero .minus .zero .plus = hybRight x y z .zero .plus .zero .minus .zero .plus := by + simp only [hybLeft,hybRight,sum_spin,exchangeNumerator_eq_table,exchangeTable, + mul_zero,zero_mul,zero_add,add_zero] + +theorem hyb_entry_3_20 (x y z : ℂ) : + hybLeft x y z .zero .plus .zero .minus .zero .minus = hybRight x y z .zero .plus .zero .minus .zero .minus := by + simp only [hybLeft,hybRight,sum_spin,exchangeNumerator_eq_table,exchangeTable, + mul_zero,zero_mul,add_zero] + +theorem hyb_entry_3_21 (x y z : ℂ) : + hybLeft x y z .zero .plus .zero .minus .plus .zero = hybRight x y z .zero .plus .zero .minus .plus .zero := by + simp only [hybLeft,hybRight,sum_spin,exchangeNumerator_eq_table,exchangeTable, + mul_zero,zero_mul,zero_add,add_zero] + +theorem hyb_entry_3_22 (x y z : ℂ) : + hybLeft x y z .zero .plus .zero .minus .plus .plus = hybRight x y z .zero .plus .zero .minus .plus .plus := by + simp only [hybLeft,hybRight,sum_spin,exchangeNumerator_eq_table,exchangeTable, + mul_zero,zero_mul,zero_add,add_zero] + all_goals ring_nf + all_goals try simp only [q_pow_9,q_pow_11,q_pow_13] + all_goals ring + +theorem hyb_entry_3_23 (x y z : ℂ) : + hybLeft x y z .zero .plus .zero .minus .plus .minus = hybRight x y z .zero .plus .zero .minus .plus .minus := by + simp only [hybLeft,hybRight,sum_spin,exchangeNumerator_eq_table,exchangeTable, + mul_zero,zero_mul,zero_add,add_zero] + +theorem hyb_entry_3_24 (x y z : ℂ) : + hybLeft x y z .zero .plus .zero .minus .minus .zero = hybRight x y z .zero .plus .zero .minus .minus .zero := by + simp only [hybLeft,hybRight,sum_spin,exchangeNumerator_eq_table,exchangeTable, + mul_zero,zero_mul,zero_add,add_zero] + +theorem hyb_entry_3_25 (x y z : ℂ) : + hybLeft x y z .zero .plus .zero .minus .minus .plus = hybRight x y z .zero .plus .zero .minus .minus .plus := by + simp only [hybLeft,hybRight,sum_spin,exchangeNumerator_eq_table,exchangeTable, + mul_zero,zero_mul,zero_add,add_zero] + +theorem hyb_entry_3_26 (x y z : ℂ) : + hybLeft x y z .zero .plus .zero .minus .minus .minus = hybRight x y z .zero .plus .zero .minus .minus .minus := by + simp only [hybLeft,hybRight,sum_spin,exchangeNumerator_eq_table,exchangeTable, + mul_zero,zero_mul,add_zero] + +theorem hyb_entry_4_0 (x y z : ℂ) : + hybLeft x y z .zero .plus .plus .zero .zero .zero = hybRight x y z .zero .plus .plus .zero .zero .zero := by + simp only [hybLeft,hybRight,sum_spin,exchangeNumerator_eq_table,exchangeTable, + mul_zero,zero_mul,zero_add,add_zero] + +theorem hyb_entry_4_1 (x y z : ℂ) : + hybLeft x y z .zero .plus .plus .zero .zero .plus = hybRight x y z .zero .plus .plus .zero .zero .plus := by + simp only [hybLeft,hybRight,sum_spin,exchangeNumerator_eq_table,exchangeTable, + mul_zero,zero_mul,zero_add,add_zero] + +theorem hyb_entry_4_2 (x y z : ℂ) : + hybLeft x y z .zero .plus .plus .zero .zero .minus = hybRight x y z .zero .plus .plus .zero .zero .minus := by + simp only [hybLeft,hybRight,sum_spin,exchangeNumerator_eq_table,exchangeTable, + mul_zero,zero_mul,zero_add,add_zero] + +theorem hyb_entry_4_3 (x y z : ℂ) : + hybLeft x y z .zero .plus .plus .zero .plus .zero = hybRight x y z .zero .plus .plus .zero .plus .zero := by + simp only [hybLeft,hybRight,sum_spin,exchangeNumerator_eq_table,exchangeTable, + mul_zero,zero_mul,zero_add,add_zero] + +theorem hyb_entry_4_4 (x y z : ℂ) : + hybLeft x y z .zero .plus .plus .zero .plus .plus = hybRight x y z .zero .plus .plus .zero .plus .plus := by + simp only [hybLeft,hybRight,sum_spin,exchangeNumerator_eq_table,exchangeTable, + mul_zero,zero_mul,zero_add,add_zero] + all_goals ring_nf + all_goals try simp only [q_pow_eight,q_pow_10,q_pow_12,q_pow_14,q_pow_16,q_pow_18] + all_goals ring + +theorem hyb_entry_4_5 (x y z : ℂ) : + hybLeft x y z .zero .plus .plus .zero .plus .minus = hybRight x y z .zero .plus .plus .zero .plus .minus := by + simp only [hybLeft,hybRight,sum_spin,exchangeNumerator_eq_table,exchangeTable, + mul_zero,zero_mul,zero_add,add_zero] + +theorem hyb_entry_4_6 (x y z : ℂ) : + hybLeft x y z .zero .plus .plus .zero .minus .zero = hybRight x y z .zero .plus .plus .zero .minus .zero := by + simp only [hybLeft,hybRight,sum_spin,exchangeNumerator_eq_table,exchangeTable, + mul_zero,zero_mul,add_zero] + +theorem hyb_entry_4_7 (x y z : ℂ) : + hybLeft x y z .zero .plus .plus .zero .minus .plus = hybRight x y z .zero .plus .plus .zero .minus .plus := by + simp only [hybLeft,hybRight,sum_spin,exchangeNumerator_eq_table,exchangeTable, + mul_zero,zero_mul,zero_add,add_zero] + +theorem hyb_entry_4_8 (x y z : ℂ) : + hybLeft x y z .zero .plus .plus .zero .minus .minus = hybRight x y z .zero .plus .plus .zero .minus .minus := by + simp only [hybLeft,hybRight,sum_spin,exchangeNumerator_eq_table,exchangeTable, + mul_zero,zero_mul,add_zero] + +theorem hyb_entry_4_9 (x y z : ℂ) : + hybLeft x y z .zero .plus .plus .plus .zero .zero = hybRight x y z .zero .plus .plus .plus .zero .zero := by + simp only [hybLeft,hybRight,sum_spin,exchangeNumerator_eq_table,exchangeTable, + mul_zero,zero_mul,zero_add,add_zero] + +theorem hyb_entry_4_10 (x y z : ℂ) : + hybLeft x y z .zero .plus .plus .plus .zero .plus = hybRight x y z .zero .plus .plus .plus .zero .plus := by + simp only [hybLeft,hybRight,sum_spin,exchangeNumerator_eq_table,exchangeTable, + mul_zero,zero_mul,zero_add,add_zero] + all_goals ring_nf + all_goals try simp only [q_pow_eight,q_pow_10,q_pow_12,q_pow_14] + all_goals ring + +theorem hyb_entry_4_11 (x y z : ℂ) : + hybLeft x y z .zero .plus .plus .plus .zero .minus = hybRight x y z .zero .plus .plus .plus .zero .minus := by + simp only [hybLeft,hybRight,sum_spin,exchangeNumerator_eq_table,exchangeTable, + mul_zero,zero_mul,zero_add,add_zero] + +theorem hyb_entry_4_12 (x y z : ℂ) : + hybLeft x y z .zero .plus .plus .plus .plus .zero = hybRight x y z .zero .plus .plus .plus .plus .zero := by + simp only [hybLeft,hybRight,sum_spin,exchangeNumerator_eq_table,exchangeTable, + mul_zero,zero_mul,zero_add,add_zero] + all_goals ring_nf + +theorem hyb_entry_4_13 (x y z : ℂ) : + hybLeft x y z .zero .plus .plus .plus .plus .plus = hybRight x y z .zero .plus .plus .plus .plus .plus := by + simp only [hybLeft,hybRight,sum_spin,exchangeNumerator_eq_table,exchangeTable, + mul_zero,zero_mul,zero_add,add_zero] + +theorem hyb_entry_4_14 (x y z : ℂ) : + hybLeft x y z .zero .plus .plus .plus .plus .minus = hybRight x y z .zero .plus .plus .plus .plus .minus := by + simp only [hybLeft,hybRight,sum_spin,exchangeNumerator_eq_table,exchangeTable, + mul_zero,zero_mul,zero_add,add_zero] + +theorem hyb_entry_4_15 (x y z : ℂ) : + hybLeft x y z .zero .plus .plus .plus .minus .zero = hybRight x y z .zero .plus .plus .plus .minus .zero := by + simp only [hybLeft,hybRight,sum_spin,exchangeNumerator_eq_table,exchangeTable, + mul_zero,zero_mul,zero_add,add_zero] + +theorem hyb_entry_4_16 (x y z : ℂ) : + hybLeft x y z .zero .plus .plus .plus .minus .plus = hybRight x y z .zero .plus .plus .plus .minus .plus := by + simp only [hybLeft,hybRight,sum_spin,exchangeNumerator_eq_table,exchangeTable, + mul_zero,zero_mul,zero_add,add_zero] + +theorem hyb_entry_4_17 (x y z : ℂ) : + hybLeft x y z .zero .plus .plus .plus .minus .minus = hybRight x y z .zero .plus .plus .plus .minus .minus := by + simp only [hybLeft,hybRight,sum_spin,exchangeNumerator_eq_table,exchangeTable, + mul_zero,zero_mul,zero_add,add_zero] + +theorem hyb_entry_4_18 (x y z : ℂ) : + hybLeft x y z .zero .plus .plus .minus .zero .zero = hybRight x y z .zero .plus .plus .minus .zero .zero := by + simp only [hybLeft,hybRight,sum_spin,exchangeNumerator_eq_table,exchangeTable, + mul_zero,zero_mul,zero_add,add_zero] + +theorem hyb_entry_4_19 (x y z : ℂ) : + hybLeft x y z .zero .plus .plus .minus .zero .plus = hybRight x y z .zero .plus .plus .minus .zero .plus := by + simp only [hybLeft,hybRight,sum_spin,exchangeNumerator_eq_table,exchangeTable, + mul_zero,zero_mul,zero_add,add_zero] + +theorem hyb_entry_4_20 (x y z : ℂ) : + hybLeft x y z .zero .plus .plus .minus .zero .minus = hybRight x y z .zero .plus .plus .minus .zero .minus := by + simp only [hybLeft,hybRight,sum_spin,exchangeNumerator_eq_table,exchangeTable, + mul_zero,zero_mul,add_zero] + +theorem hyb_entry_4_21 (x y z : ℂ) : + hybLeft x y z .zero .plus .plus .minus .plus .zero = hybRight x y z .zero .plus .plus .minus .plus .zero := by + simp only [hybLeft,hybRight,sum_spin,exchangeNumerator_eq_table,exchangeTable, + mul_zero,zero_mul,zero_add,add_zero] + +theorem hyb_entry_4_22 (x y z : ℂ) : + hybLeft x y z .zero .plus .plus .minus .plus .plus = hybRight x y z .zero .plus .plus .minus .plus .plus := by + simp only [hybLeft,hybRight,sum_spin,exchangeNumerator_eq_table,exchangeTable, + mul_zero,zero_mul,zero_add,add_zero] + +theorem hyb_entry_4_23 (x y z : ℂ) : + hybLeft x y z .zero .plus .plus .minus .plus .minus = hybRight x y z .zero .plus .plus .minus .plus .minus := by + simp only [hybLeft,hybRight,sum_spin,exchangeNumerator_eq_table,exchangeTable, + mul_zero,zero_mul,zero_add,add_zero] + +theorem hyb_entry_4_24 (x y z : ℂ) : + hybLeft x y z .zero .plus .plus .minus .minus .zero = hybRight x y z .zero .plus .plus .minus .minus .zero := by + simp only [hybLeft,hybRight,sum_spin,exchangeNumerator_eq_table,exchangeTable, + mul_zero,zero_mul,add_zero] + +theorem hyb_entry_4_25 (x y z : ℂ) : + hybLeft x y z .zero .plus .plus .minus .minus .plus = hybRight x y z .zero .plus .plus .minus .minus .plus := by + simp only [hybLeft,hybRight,sum_spin,exchangeNumerator_eq_table,exchangeTable, + mul_zero,zero_mul,zero_add,add_zero] + +theorem hyb_entry_4_26 (x y z : ℂ) : + hybLeft x y z .zero .plus .plus .minus .minus .minus = hybRight x y z .zero .plus .plus .minus .minus .minus := by + simp only [hybLeft,hybRight,sum_spin,exchangeNumerator_eq_table,exchangeTable, + mul_zero,zero_mul,add_zero] + +theorem hyb_entry_5_0 (x y z : ℂ) : + hybLeft x y z .zero .plus .minus .zero .zero .zero = hybRight x y z .zero .plus .minus .zero .zero .zero := by + simp only [hybLeft,hybRight,sum_spin,exchangeNumerator_eq_table,exchangeTable, + mul_zero,zero_mul,zero_add,add_zero] + all_goals ring_nf + all_goals try simp only [q_pow_9,q_pow_11,q_pow_13,q_pow_15,q_pow_17] + all_goals ring + +theorem hyb_entry_5_1 (x y z : ℂ) : + hybLeft x y z .zero .plus .minus .zero .zero .plus = hybRight x y z .zero .plus .minus .zero .zero .plus := by + simp only [hybLeft,hybRight,sum_spin,exchangeNumerator_eq_table,exchangeTable, + mul_zero,zero_mul,zero_add,add_zero] + +theorem hyb_entry_5_2 (x y z : ℂ) : + hybLeft x y z .zero .plus .minus .zero .zero .minus = hybRight x y z .zero .plus .minus .zero .zero .minus := by + simp only [hybLeft,hybRight,sum_spin,exchangeNumerator_eq_table,exchangeTable, + mul_zero,zero_mul,zero_add,add_zero] + +theorem hyb_entry_5_3 (x y z : ℂ) : + hybLeft x y z .zero .plus .minus .zero .plus .zero = hybRight x y z .zero .plus .minus .zero .plus .zero := by + simp only [hybLeft,hybRight,sum_spin,exchangeNumerator_eq_table,exchangeTable, + mul_zero,zero_mul,zero_add,add_zero] + +theorem hyb_entry_5_4 (x y z : ℂ) : + hybLeft x y z .zero .plus .minus .zero .plus .plus = hybRight x y z .zero .plus .minus .zero .plus .plus := by + simp only [hybLeft,hybRight,sum_spin,exchangeNumerator_eq_table,exchangeTable, + mul_zero,zero_mul,zero_add,add_zero] + +theorem hyb_entry_5_5 (x y z : ℂ) : + hybLeft x y z .zero .plus .minus .zero .plus .minus = hybRight x y z .zero .plus .minus .zero .plus .minus := by + simp only [hybLeft,hybRight,sum_spin,exchangeNumerator_eq_table,exchangeTable, + mul_zero,zero_mul,zero_add,add_zero] + all_goals ring_nf + all_goals try simp only [q_pow_eight,q_pow_10,q_pow_12,q_pow_14,q_pow_16,q_pow_18] + all_goals ring + +theorem hyb_entry_5_6 (x y z : ℂ) : + hybLeft x y z .zero .plus .minus .zero .minus .zero = hybRight x y z .zero .plus .minus .zero .minus .zero := by + simp only [hybLeft,hybRight,sum_spin,exchangeNumerator_eq_table,exchangeTable, + mul_zero,zero_mul,zero_add,add_zero] + +theorem hyb_entry_5_7 (x y z : ℂ) : + hybLeft x y z .zero .plus .minus .zero .minus .plus = hybRight x y z .zero .plus .minus .zero .minus .plus := by + simp only [hybLeft,hybRight,sum_spin,exchangeNumerator_eq_table,exchangeTable, + mul_zero,zero_mul,zero_add,add_zero] + all_goals ring_nf + all_goals try simp only [q_pow_eight,q_pow_10,q_pow_12,q_pow_14,q_pow_16,q_pow_18] + all_goals ring + +theorem hyb_entry_5_8 (x y z : ℂ) : + hybLeft x y z .zero .plus .minus .zero .minus .minus = hybRight x y z .zero .plus .minus .zero .minus .minus := by + simp only [hybLeft,hybRight,sum_spin,exchangeNumerator_eq_table,exchangeTable, + mul_zero,zero_mul,zero_add,add_zero] + +theorem hyb_entry_5_9 (x y z : ℂ) : + hybLeft x y z .zero .plus .minus .plus .zero .zero = hybRight x y z .zero .plus .minus .plus .zero .zero := by + simp only [hybLeft,hybRight,sum_spin,exchangeNumerator_eq_table,exchangeTable, + mul_zero,zero_mul,zero_add,add_zero] + +theorem hyb_entry_5_10 (x y z : ℂ) : + hybLeft x y z .zero .plus .minus .plus .zero .plus = hybRight x y z .zero .plus .minus .plus .zero .plus := by + simp only [hybLeft,hybRight,sum_spin,exchangeNumerator_eq_table,exchangeTable, + mul_zero,zero_mul,add_zero] + +theorem hyb_entry_5_11 (x y z : ℂ) : + hybLeft x y z .zero .plus .minus .plus .zero .minus = hybRight x y z .zero .plus .minus .plus .zero .minus := by + simp only [hybLeft,hybRight,sum_spin,exchangeNumerator_eq_table,exchangeTable, + mul_zero,zero_mul,zero_add,add_zero] + all_goals ring_nf + all_goals try simp only [q_pow_eight,q_pow_10,q_pow_12,q_pow_14] + all_goals ring + +theorem hyb_entry_5_12 (x y z : ℂ) : + hybLeft x y z .zero .plus .minus .plus .plus .zero = hybRight x y z .zero .plus .minus .plus .plus .zero := by + simp only [hybLeft,hybRight,sum_spin,exchangeNumerator_eq_table,exchangeTable, + mul_zero,zero_mul,add_zero] + +theorem hyb_entry_5_13 (x y z : ℂ) : + hybLeft x y z .zero .plus .minus .plus .plus .plus = hybRight x y z .zero .plus .minus .plus .plus .plus := by + simp only [hybLeft,hybRight,sum_spin,exchangeNumerator_eq_table,exchangeTable, + mul_zero,zero_mul,zero_add,add_zero] + +theorem hyb_entry_5_14 (x y z : ℂ) : + hybLeft x y z .zero .plus .minus .plus .plus .minus = hybRight x y z .zero .plus .minus .plus .plus .minus := by + simp only [hybLeft,hybRight,sum_spin,exchangeNumerator_eq_table,exchangeTable, + mul_zero,zero_mul,zero_add,add_zero] + +theorem hyb_entry_5_15 (x y z : ℂ) : + hybLeft x y z .zero .plus .minus .plus .minus .zero = hybRight x y z .zero .plus .minus .plus .minus .zero := by + simp only [hybLeft,hybRight,sum_spin,exchangeNumerator_eq_table,exchangeTable, + mul_zero,zero_mul,zero_add,add_zero] + all_goals ring_nf + +theorem hyb_entry_5_16 (x y z : ℂ) : + hybLeft x y z .zero .plus .minus .plus .minus .plus = hybRight x y z .zero .plus .minus .plus .minus .plus := by + simp only [hybLeft,hybRight,sum_spin,exchangeNumerator_eq_table,exchangeTable, + mul_zero,zero_mul,zero_add,add_zero] + +theorem hyb_entry_5_17 (x y z : ℂ) : + hybLeft x y z .zero .plus .minus .plus .minus .minus = hybRight x y z .zero .plus .minus .plus .minus .minus := by + simp only [hybLeft,hybRight,sum_spin,exchangeNumerator_eq_table,exchangeTable, + mul_zero,zero_mul,zero_add,add_zero] + +theorem hyb_entry_5_18 (x y z : ℂ) : + hybLeft x y z .zero .plus .minus .minus .zero .zero = hybRight x y z .zero .plus .minus .minus .zero .zero := by + simp only [hybLeft,hybRight,sum_spin,exchangeNumerator_eq_table,exchangeTable, + mul_zero,zero_mul,zero_add,add_zero] + +theorem hyb_entry_5_19 (x y z : ℂ) : + hybLeft x y z .zero .plus .minus .minus .zero .plus = hybRight x y z .zero .plus .minus .minus .zero .plus := by + simp only [hybLeft,hybRight,sum_spin,exchangeNumerator_eq_table,exchangeTable, + mul_zero,zero_mul,zero_add,add_zero] + all_goals ring_nf + all_goals try simp only [q_pow_eight,q_pow_10,q_pow_12,q_pow_14] + all_goals ring + +theorem hyb_entry_5_20 (x y z : ℂ) : + hybLeft x y z .zero .plus .minus .minus .zero .minus = hybRight x y z .zero .plus .minus .minus .zero .minus := by + simp only [hybLeft,hybRight,sum_spin,exchangeNumerator_eq_table,exchangeTable, + mul_zero,zero_mul,add_zero] + +theorem hyb_entry_5_21 (x y z : ℂ) : + hybLeft x y z .zero .plus .minus .minus .plus .zero = hybRight x y z .zero .plus .minus .minus .plus .zero := by + simp only [hybLeft,hybRight,sum_spin,exchangeNumerator_eq_table,exchangeTable, + mul_zero,zero_mul,zero_add,add_zero] + all_goals ring_nf + +theorem hyb_entry_5_22 (x y z : ℂ) : + hybLeft x y z .zero .plus .minus .minus .plus .plus = hybRight x y z .zero .plus .minus .minus .plus .plus := by + simp only [hybLeft,hybRight,sum_spin,exchangeNumerator_eq_table,exchangeTable, + mul_zero,zero_mul,zero_add,add_zero] + +theorem hyb_entry_5_23 (x y z : ℂ) : + hybLeft x y z .zero .plus .minus .minus .plus .minus = hybRight x y z .zero .plus .minus .minus .plus .minus := by + simp only [hybLeft,hybRight,sum_spin,exchangeNumerator_eq_table,exchangeTable, + mul_zero,zero_mul,zero_add,add_zero] + +theorem hyb_entry_5_24 (x y z : ℂ) : + hybLeft x y z .zero .plus .minus .minus .minus .zero = hybRight x y z .zero .plus .minus .minus .minus .zero := by + simp only [hybLeft,hybRight,sum_spin,exchangeNumerator_eq_table,exchangeTable, + mul_zero,zero_mul,zero_add,add_zero] + +theorem hyb_entry_5_25 (x y z : ℂ) : + hybLeft x y z .zero .plus .minus .minus .minus .plus = hybRight x y z .zero .plus .minus .minus .minus .plus := by + simp only [hybLeft,hybRight,sum_spin,exchangeNumerator_eq_table,exchangeTable, + mul_zero,zero_mul,zero_add,add_zero] + +theorem hyb_entry_5_26 (x y z : ℂ) : + hybLeft x y z .zero .plus .minus .minus .minus .minus = hybRight x y z .zero .plus .minus .minus .minus .minus := by + simp only [hybLeft,hybRight,sum_spin,exchangeNumerator_eq_table,exchangeTable, + mul_zero,zero_mul,zero_add,add_zero] + +theorem hyb_entry_6_0 (x y z : ℂ) : + hybLeft x y z .zero .minus .zero .zero .zero .zero = hybRight x y z .zero .minus .zero .zero .zero .zero := by + simp only [hybLeft,hybRight,sum_spin,exchangeNumerator_eq_table,exchangeTable, + mul_zero,zero_mul,zero_add,add_zero] + +theorem hyb_entry_6_1 (x y z : ℂ) : + hybLeft x y z .zero .minus .zero .zero .zero .plus = hybRight x y z .zero .minus .zero .zero .zero .plus := by + simp only [hybLeft,hybRight,sum_spin,exchangeNumerator_eq_table,exchangeTable, + mul_zero,zero_mul,zero_add,add_zero] + +theorem hyb_entry_6_2 (x y z : ℂ) : + hybLeft x y z .zero .minus .zero .zero .zero .minus = hybRight x y z .zero .minus .zero .zero .zero .minus := by + simp only [hybLeft,hybRight,sum_spin,exchangeNumerator_eq_table,exchangeTable, + mul_zero,zero_mul,zero_add,add_zero] + all_goals ring_nf + all_goals try simp only [q_pow_eight,q_pow_10,q_pow_12,q_pow_14] + all_goals ring + +theorem hyb_entry_6_3 (x y z : ℂ) : + hybLeft x y z .zero .minus .zero .zero .plus .zero = hybRight x y z .zero .minus .zero .zero .plus .zero := by + simp only [hybLeft,hybRight,sum_spin,exchangeNumerator_eq_table,exchangeTable, + mul_zero,zero_mul,zero_add,add_zero] + +theorem hyb_entry_6_4 (x y z : ℂ) : + hybLeft x y z .zero .minus .zero .zero .plus .plus = hybRight x y z .zero .minus .zero .zero .plus .plus := by + simp only [hybLeft,hybRight,sum_spin,exchangeNumerator_eq_table,exchangeTable, + mul_zero,zero_mul,add_zero] + +theorem hyb_entry_6_5 (x y z : ℂ) : + hybLeft x y z .zero .minus .zero .zero .plus .minus = hybRight x y z .zero .minus .zero .zero .plus .minus := by + simp only [hybLeft,hybRight,sum_spin,exchangeNumerator_eq_table,exchangeTable, + mul_zero,zero_mul,zero_add,add_zero] + +theorem hyb_entry_6_6 (x y z : ℂ) : + hybLeft x y z .zero .minus .zero .zero .minus .zero = hybRight x y z .zero .minus .zero .zero .minus .zero := by + simp only [hybLeft,hybRight,sum_spin,exchangeNumerator_eq_table,exchangeTable, + mul_zero,zero_mul,zero_add,add_zero] + all_goals ring_nf + +theorem hyb_entry_6_7 (x y z : ℂ) : + hybLeft x y z .zero .minus .zero .zero .minus .plus = hybRight x y z .zero .minus .zero .zero .minus .plus := by + simp only [hybLeft,hybRight,sum_spin,exchangeNumerator_eq_table,exchangeTable, + mul_zero,zero_mul,zero_add,add_zero] + +theorem hyb_entry_6_8 (x y z : ℂ) : + hybLeft x y z .zero .minus .zero .zero .minus .minus = hybRight x y z .zero .minus .zero .zero .minus .minus := by + simp only [hybLeft,hybRight,sum_spin,exchangeNumerator_eq_table,exchangeTable, + mul_zero,zero_mul,zero_add,add_zero] + +theorem hyb_entry_6_9 (x y z : ℂ) : + hybLeft x y z .zero .minus .zero .plus .zero .zero = hybRight x y z .zero .minus .zero .plus .zero .zero := by + simp only [hybLeft,hybRight,sum_spin,exchangeNumerator_eq_table,exchangeTable, + mul_zero,zero_mul,zero_add,add_zero] + +theorem hyb_entry_6_10 (x y z : ℂ) : + hybLeft x y z .zero .minus .zero .plus .zero .plus = hybRight x y z .zero .minus .zero .plus .zero .plus := by + simp only [hybLeft,hybRight,sum_spin,exchangeNumerator_eq_table,exchangeTable, + mul_zero,zero_mul,add_zero] + +theorem hyb_entry_6_11 (x y z : ℂ) : + hybLeft x y z .zero .minus .zero .plus .zero .minus = hybRight x y z .zero .minus .zero .plus .zero .minus := by + simp only [hybLeft,hybRight,sum_spin,exchangeNumerator_eq_table,exchangeTable, + mul_zero,zero_mul,zero_add,add_zero] + +theorem hyb_entry_6_12 (x y z : ℂ) : + hybLeft x y z .zero .minus .zero .plus .plus .zero = hybRight x y z .zero .minus .zero .plus .plus .zero := by + simp only [hybLeft,hybRight,sum_spin,exchangeNumerator_eq_table,exchangeTable, + mul_zero,zero_mul,zero_add,add_zero] + +theorem hyb_entry_6_13 (x y z : ℂ) : + hybLeft x y z .zero .minus .zero .plus .plus .plus = hybRight x y z .zero .minus .zero .plus .plus .plus := by + simp only [hybLeft,hybRight,sum_spin,exchangeNumerator_eq_table,exchangeTable, + mul_zero,zero_mul,add_zero] + +theorem hyb_entry_6_14 (x y z : ℂ) : + hybLeft x y z .zero .minus .zero .plus .plus .minus = hybRight x y z .zero .minus .zero .plus .plus .minus := by + simp only [hybLeft,hybRight,sum_spin,exchangeNumerator_eq_table,exchangeTable, + mul_zero,zero_mul,zero_add,add_zero] + +theorem hyb_entry_6_15 (x y z : ℂ) : + hybLeft x y z .zero .minus .zero .plus .minus .zero = hybRight x y z .zero .minus .zero .plus .minus .zero := by + simp only [hybLeft,hybRight,sum_spin,exchangeNumerator_eq_table,exchangeTable, + mul_zero,zero_mul,zero_add,add_zero] + +theorem hyb_entry_6_16 (x y z : ℂ) : + hybLeft x y z .zero .minus .zero .plus .minus .plus = hybRight x y z .zero .minus .zero .plus .minus .plus := by + simp only [hybLeft,hybRight,sum_spin,exchangeNumerator_eq_table,exchangeTable, + mul_zero,zero_mul,zero_add,add_zero] + +theorem hyb_entry_6_17 (x y z : ℂ) : + hybLeft x y z .zero .minus .zero .plus .minus .minus = hybRight x y z .zero .minus .zero .plus .minus .minus := by + simp only [hybLeft,hybRight,sum_spin,exchangeNumerator_eq_table,exchangeTable, + mul_zero,zero_mul,zero_add,add_zero] + all_goals ring_nf + all_goals try simp only [q_pow_9,q_pow_11,q_pow_13] + all_goals ring + +theorem hyb_entry_6_18 (x y z : ℂ) : + hybLeft x y z .zero .minus .zero .minus .zero .zero = hybRight x y z .zero .minus .zero .minus .zero .zero := by + simp only [hybLeft,hybRight,sum_spin,exchangeNumerator_eq_table,exchangeTable, + mul_zero,zero_mul,zero_add,add_zero] + all_goals ring_nf + all_goals try simp only [q_pow_eight,q_pow_10,q_pow_12,q_pow_14] + all_goals ring + +theorem hyb_entry_6_19 (x y z : ℂ) : + hybLeft x y z .zero .minus .zero .minus .zero .plus = hybRight x y z .zero .minus .zero .minus .zero .plus := by + simp only [hybLeft,hybRight,sum_spin,exchangeNumerator_eq_table,exchangeTable, + mul_zero,zero_mul,zero_add,add_zero] + +theorem hyb_entry_6_20 (x y z : ℂ) : + hybLeft x y z .zero .minus .zero .minus .zero .minus = hybRight x y z .zero .minus .zero .minus .zero .minus := by + simp only [hybLeft,hybRight,sum_spin,exchangeNumerator_eq_table,exchangeTable, + mul_zero,zero_mul,zero_add,add_zero] + +theorem hyb_entry_6_21 (x y z : ℂ) : + hybLeft x y z .zero .minus .zero .minus .plus .zero = hybRight x y z .zero .minus .zero .minus .plus .zero := by + simp only [hybLeft,hybRight,sum_spin,exchangeNumerator_eq_table,exchangeTable, + mul_zero,zero_mul,zero_add,add_zero] + +theorem hyb_entry_6_22 (x y z : ℂ) : + hybLeft x y z .zero .minus .zero .minus .plus .plus = hybRight x y z .zero .minus .zero .minus .plus .plus := by + simp only [hybLeft,hybRight,sum_spin,exchangeNumerator_eq_table,exchangeTable, + mul_zero,zero_mul,zero_add,add_zero] + +theorem hyb_entry_6_23 (x y z : ℂ) : + hybLeft x y z .zero .minus .zero .minus .plus .minus = hybRight x y z .zero .minus .zero .minus .plus .minus := by + simp only [hybLeft,hybRight,sum_spin,exchangeNumerator_eq_table,exchangeTable, + mul_zero,zero_mul,zero_add,add_zero] + all_goals ring_nf + all_goals try simp only [q_pow_9,q_pow_11,q_pow_13] + all_goals ring + +theorem hyb_entry_6_24 (x y z : ℂ) : + hybLeft x y z .zero .minus .zero .minus .minus .zero = hybRight x y z .zero .minus .zero .minus .minus .zero := by + simp only [hybLeft,hybRight,sum_spin,exchangeNumerator_eq_table,exchangeTable, + mul_zero,zero_mul,zero_add,add_zero] + +theorem hyb_entry_6_25 (x y z : ℂ) : + hybLeft x y z .zero .minus .zero .minus .minus .plus = hybRight x y z .zero .minus .zero .minus .minus .plus := by + simp only [hybLeft,hybRight,sum_spin,exchangeNumerator_eq_table,exchangeTable, + mul_zero,zero_mul,zero_add,add_zero] + all_goals ring_nf + all_goals try simp only [q_pow_9,q_pow_11,q_pow_13] + all_goals ring + +theorem hyb_entry_6_26 (x y z : ℂ) : + hybLeft x y z .zero .minus .zero .minus .minus .minus = hybRight x y z .zero .minus .zero .minus .minus .minus := by + simp only [hybLeft,hybRight,sum_spin,exchangeNumerator_eq_table,exchangeTable, + mul_zero,zero_mul,zero_add,add_zero] + +theorem hyb_entry_7_0 (x y z : ℂ) : + hybLeft x y z .zero .minus .plus .zero .zero .zero = hybRight x y z .zero .minus .plus .zero .zero .zero := by + simp only [hybLeft,hybRight,sum_spin,exchangeNumerator_eq_table,exchangeTable, + mul_zero,zero_mul,zero_add,add_zero] + all_goals ring_nf + all_goals try simp only [q_pow_9,q_pow_11,q_pow_13,q_pow_15,q_pow_17] + all_goals ring + +theorem hyb_entry_7_1 (x y z : ℂ) : + hybLeft x y z .zero .minus .plus .zero .zero .plus = hybRight x y z .zero .minus .plus .zero .zero .plus := by + simp only [hybLeft,hybRight,sum_spin,exchangeNumerator_eq_table,exchangeTable, + mul_zero,zero_mul,zero_add,add_zero] + +theorem hyb_entry_7_2 (x y z : ℂ) : + hybLeft x y z .zero .minus .plus .zero .zero .minus = hybRight x y z .zero .minus .plus .zero .zero .minus := by + simp only [hybLeft,hybRight,sum_spin,exchangeNumerator_eq_table,exchangeTable, + mul_zero,zero_mul,zero_add,add_zero] + +theorem hyb_entry_7_3 (x y z : ℂ) : + hybLeft x y z .zero .minus .plus .zero .plus .zero = hybRight x y z .zero .minus .plus .zero .plus .zero := by + simp only [hybLeft,hybRight,sum_spin,exchangeNumerator_eq_table,exchangeTable, + mul_zero,zero_mul,zero_add,add_zero] + +theorem hyb_entry_7_4 (x y z : ℂ) : + hybLeft x y z .zero .minus .plus .zero .plus .plus = hybRight x y z .zero .minus .plus .zero .plus .plus := by + simp only [hybLeft,hybRight,sum_spin,exchangeNumerator_eq_table,exchangeTable, + mul_zero,zero_mul,zero_add,add_zero] + +theorem hyb_entry_7_5 (x y z : ℂ) : + hybLeft x y z .zero .minus .plus .zero .plus .minus = hybRight x y z .zero .minus .plus .zero .plus .minus := by + simp only [hybLeft,hybRight,sum_spin,exchangeNumerator_eq_table,exchangeTable, + mul_zero,zero_mul,zero_add,add_zero] + all_goals ring_nf + all_goals try simp only [q_pow_eight,q_pow_10,q_pow_12,q_pow_14,q_pow_16,q_pow_18] + all_goals ring + +theorem hyb_entry_7_6 (x y z : ℂ) : + hybLeft x y z .zero .minus .plus .zero .minus .zero = hybRight x y z .zero .minus .plus .zero .minus .zero := by + simp only [hybLeft,hybRight,sum_spin,exchangeNumerator_eq_table,exchangeTable, + mul_zero,zero_mul,zero_add,add_zero] + +theorem hyb_entry_7_7 (x y z : ℂ) : + hybLeft x y z .zero .minus .plus .zero .minus .plus = hybRight x y z .zero .minus .plus .zero .minus .plus := by + simp only [hybLeft,hybRight,sum_spin,exchangeNumerator_eq_table,exchangeTable, + mul_zero,zero_mul,zero_add,add_zero] + all_goals ring_nf + all_goals try simp only [q_pow_eight,q_pow_10,q_pow_12,q_pow_14,q_pow_16,q_pow_18] + all_goals ring + +theorem hyb_entry_7_8 (x y z : ℂ) : + hybLeft x y z .zero .minus .plus .zero .minus .minus = hybRight x y z .zero .minus .plus .zero .minus .minus := by + simp only [hybLeft,hybRight,sum_spin,exchangeNumerator_eq_table,exchangeTable, + mul_zero,zero_mul,zero_add,add_zero] + +theorem hyb_entry_7_9 (x y z : ℂ) : + hybLeft x y z .zero .minus .plus .plus .zero .zero = hybRight x y z .zero .minus .plus .plus .zero .zero := by + simp only [hybLeft,hybRight,sum_spin,exchangeNumerator_eq_table,exchangeTable, + mul_zero,zero_mul,zero_add,add_zero] + +theorem hyb_entry_7_10 (x y z : ℂ) : + hybLeft x y z .zero .minus .plus .plus .zero .plus = hybRight x y z .zero .minus .plus .plus .zero .plus := by + simp only [hybLeft,hybRight,sum_spin,exchangeNumerator_eq_table,exchangeTable, + mul_zero,zero_mul,add_zero] + +theorem hyb_entry_7_11 (x y z : ℂ) : + hybLeft x y z .zero .minus .plus .plus .zero .minus = hybRight x y z .zero .minus .plus .plus .zero .minus := by + simp only [hybLeft,hybRight,sum_spin,exchangeNumerator_eq_table,exchangeTable, + mul_zero,zero_mul,zero_add,add_zero] + all_goals ring_nf + all_goals try simp only [q_pow_eight,q_pow_10,q_pow_12,q_pow_14] + all_goals ring + +theorem hyb_entry_7_12 (x y z : ℂ) : + hybLeft x y z .zero .minus .plus .plus .plus .zero = hybRight x y z .zero .minus .plus .plus .plus .zero := by + simp only [hybLeft,hybRight,sum_spin,exchangeNumerator_eq_table,exchangeTable, + mul_zero,zero_mul,zero_add,add_zero] + +theorem hyb_entry_7_13 (x y z : ℂ) : + hybLeft x y z .zero .minus .plus .plus .plus .plus = hybRight x y z .zero .minus .plus .plus .plus .plus := by + simp only [hybLeft,hybRight,sum_spin,exchangeNumerator_eq_table,exchangeTable, + mul_zero,zero_mul,zero_add,add_zero] + +theorem hyb_entry_7_14 (x y z : ℂ) : + hybLeft x y z .zero .minus .plus .plus .plus .minus = hybRight x y z .zero .minus .plus .plus .plus .minus := by + simp only [hybLeft,hybRight,sum_spin,exchangeNumerator_eq_table,exchangeTable, + mul_zero,zero_mul,zero_add,add_zero] + +theorem hyb_entry_7_15 (x y z : ℂ) : + hybLeft x y z .zero .minus .plus .plus .minus .zero = hybRight x y z .zero .minus .plus .plus .minus .zero := by + simp only [hybLeft,hybRight,sum_spin,exchangeNumerator_eq_table,exchangeTable, + mul_zero,zero_mul,zero_add,add_zero] + all_goals ring_nf + +theorem hyb_entry_7_16 (x y z : ℂ) : + hybLeft x y z .zero .minus .plus .plus .minus .plus = hybRight x y z .zero .minus .plus .plus .minus .plus := by + simp only [hybLeft,hybRight,sum_spin,exchangeNumerator_eq_table,exchangeTable, + mul_zero,zero_mul,zero_add,add_zero] + +theorem hyb_entry_7_17 (x y z : ℂ) : + hybLeft x y z .zero .minus .plus .plus .minus .minus = hybRight x y z .zero .minus .plus .plus .minus .minus := by + simp only [hybLeft,hybRight,sum_spin,exchangeNumerator_eq_table,exchangeTable, + mul_zero,zero_mul,zero_add,add_zero] + +theorem hyb_entry_7_18 (x y z : ℂ) : + hybLeft x y z .zero .minus .plus .minus .zero .zero = hybRight x y z .zero .minus .plus .minus .zero .zero := by + simp only [hybLeft,hybRight,sum_spin,exchangeNumerator_eq_table,exchangeTable, + mul_zero,zero_mul,zero_add,add_zero] + +theorem hyb_entry_7_19 (x y z : ℂ) : + hybLeft x y z .zero .minus .plus .minus .zero .plus = hybRight x y z .zero .minus .plus .minus .zero .plus := by + simp only [hybLeft,hybRight,sum_spin,exchangeNumerator_eq_table,exchangeTable, + mul_zero,zero_mul,zero_add,add_zero] + all_goals ring_nf + all_goals try simp only [q_pow_eight,q_pow_10,q_pow_12,q_pow_14] + all_goals ring + +theorem hyb_entry_7_20 (x y z : ℂ) : + hybLeft x y z .zero .minus .plus .minus .zero .minus = hybRight x y z .zero .minus .plus .minus .zero .minus := by + simp only [hybLeft,hybRight,sum_spin,exchangeNumerator_eq_table,exchangeTable, + mul_zero,zero_mul,add_zero] + +theorem hyb_entry_7_21 (x y z : ℂ) : + hybLeft x y z .zero .minus .plus .minus .plus .zero = hybRight x y z .zero .minus .plus .minus .plus .zero := by + simp only [hybLeft,hybRight,sum_spin,exchangeNumerator_eq_table,exchangeTable, + mul_zero,zero_mul,zero_add,add_zero] + all_goals ring_nf + +theorem hyb_entry_7_22 (x y z : ℂ) : + hybLeft x y z .zero .minus .plus .minus .plus .plus = hybRight x y z .zero .minus .plus .minus .plus .plus := by + simp only [hybLeft,hybRight,sum_spin,exchangeNumerator_eq_table,exchangeTable, + mul_zero,zero_mul,zero_add,add_zero] + +theorem hyb_entry_7_23 (x y z : ℂ) : + hybLeft x y z .zero .minus .plus .minus .plus .minus = hybRight x y z .zero .minus .plus .minus .plus .minus := by + simp only [hybLeft,hybRight,sum_spin,exchangeNumerator_eq_table,exchangeTable, + mul_zero,zero_mul,zero_add,add_zero] + +theorem hyb_entry_7_24 (x y z : ℂ) : + hybLeft x y z .zero .minus .plus .minus .minus .zero = hybRight x y z .zero .minus .plus .minus .minus .zero := by + simp only [hybLeft,hybRight,sum_spin,exchangeNumerator_eq_table,exchangeTable, + mul_zero,zero_mul,add_zero] + +theorem hyb_entry_7_25 (x y z : ℂ) : + hybLeft x y z .zero .minus .plus .minus .minus .plus = hybRight x y z .zero .minus .plus .minus .minus .plus := by + simp only [hybLeft,hybRight,sum_spin,exchangeNumerator_eq_table,exchangeTable, + mul_zero,zero_mul,zero_add,add_zero] + +theorem hyb_entry_7_26 (x y z : ℂ) : + hybLeft x y z .zero .minus .plus .minus .minus .minus = hybRight x y z .zero .minus .plus .minus .minus .minus := by + simp only [hybLeft,hybRight,sum_spin,exchangeNumerator_eq_table,exchangeTable, + mul_zero,zero_mul,zero_add,add_zero] + +theorem hyb_entry_8_0 (x y z : ℂ) : + hybLeft x y z .zero .minus .minus .zero .zero .zero = hybRight x y z .zero .minus .minus .zero .zero .zero := by + simp only [hybLeft,hybRight,sum_spin,exchangeNumerator_eq_table,exchangeTable, + mul_zero,zero_mul,zero_add,add_zero] + +theorem hyb_entry_8_1 (x y z : ℂ) : + hybLeft x y z .zero .minus .minus .zero .zero .plus = hybRight x y z .zero .minus .minus .zero .zero .plus := by + simp only [hybLeft,hybRight,sum_spin,exchangeNumerator_eq_table,exchangeTable, + mul_zero,zero_mul,zero_add,add_zero] + +theorem hyb_entry_8_2 (x y z : ℂ) : + hybLeft x y z .zero .minus .minus .zero .zero .minus = hybRight x y z .zero .minus .minus .zero .zero .minus := by + simp only [hybLeft,hybRight,sum_spin,exchangeNumerator_eq_table,exchangeTable, + mul_zero,zero_mul,zero_add,add_zero] + +theorem hyb_entry_8_3 (x y z : ℂ) : + hybLeft x y z .zero .minus .minus .zero .plus .zero = hybRight x y z .zero .minus .minus .zero .plus .zero := by + simp only [hybLeft,hybRight,sum_spin,exchangeNumerator_eq_table,exchangeTable, + mul_zero,zero_mul,add_zero] + +theorem hyb_entry_8_4 (x y z : ℂ) : + hybLeft x y z .zero .minus .minus .zero .plus .plus = hybRight x y z .zero .minus .minus .zero .plus .plus := by + simp only [hybLeft,hybRight,sum_spin,exchangeNumerator_eq_table,exchangeTable, + mul_zero,zero_mul,add_zero] + +theorem hyb_entry_8_5 (x y z : ℂ) : + hybLeft x y z .zero .minus .minus .zero .plus .minus = hybRight x y z .zero .minus .minus .zero .plus .minus := by + simp only [hybLeft,hybRight,sum_spin,exchangeNumerator_eq_table,exchangeTable, + mul_zero,zero_mul,zero_add,add_zero] + +theorem hyb_entry_8_6 (x y z : ℂ) : + hybLeft x y z .zero .minus .minus .zero .minus .zero = hybRight x y z .zero .minus .minus .zero .minus .zero := by + simp only [hybLeft,hybRight,sum_spin,exchangeNumerator_eq_table,exchangeTable, + mul_zero,zero_mul,zero_add,add_zero] + +theorem hyb_entry_8_7 (x y z : ℂ) : + hybLeft x y z .zero .minus .minus .zero .minus .plus = hybRight x y z .zero .minus .minus .zero .minus .plus := by + simp only [hybLeft,hybRight,sum_spin,exchangeNumerator_eq_table,exchangeTable, + mul_zero,zero_mul,zero_add,add_zero] + +theorem hyb_entry_8_8 (x y z : ℂ) : + hybLeft x y z .zero .minus .minus .zero .minus .minus = hybRight x y z .zero .minus .minus .zero .minus .minus := by + simp only [hybLeft,hybRight,sum_spin,exchangeNumerator_eq_table,exchangeTable, + mul_zero,zero_mul,zero_add,add_zero] + all_goals ring_nf + all_goals try simp only [q_pow_eight,q_pow_10,q_pow_12,q_pow_14,q_pow_16,q_pow_18] + all_goals ring + +theorem hyb_entry_8_9 (x y z : ℂ) : + hybLeft x y z .zero .minus .minus .plus .zero .zero = hybRight x y z .zero .minus .minus .plus .zero .zero := by + simp only [hybLeft,hybRight,sum_spin,exchangeNumerator_eq_table,exchangeTable, + mul_zero,zero_mul,zero_add,add_zero] + +theorem hyb_entry_8_10 (x y z : ℂ) : + hybLeft x y z .zero .minus .minus .plus .zero .plus = hybRight x y z .zero .minus .minus .plus .zero .plus := by + simp only [hybLeft,hybRight,sum_spin,exchangeNumerator_eq_table,exchangeTable, + mul_zero,zero_mul,add_zero] + +theorem hyb_entry_8_11 (x y z : ℂ) : + hybLeft x y z .zero .minus .minus .plus .zero .minus = hybRight x y z .zero .minus .minus .plus .zero .minus := by + simp only [hybLeft,hybRight,sum_spin,exchangeNumerator_eq_table,exchangeTable, + mul_zero,zero_mul,zero_add,add_zero] + +theorem hyb_entry_8_12 (x y z : ℂ) : + hybLeft x y z .zero .minus .minus .plus .plus .zero = hybRight x y z .zero .minus .minus .plus .plus .zero := by + simp only [hybLeft,hybRight,sum_spin,exchangeNumerator_eq_table,exchangeTable, + mul_zero,zero_mul,add_zero] + +theorem hyb_entry_8_13 (x y z : ℂ) : + hybLeft x y z .zero .minus .minus .plus .plus .plus = hybRight x y z .zero .minus .minus .plus .plus .plus := by + simp only [hybLeft,hybRight,sum_spin,exchangeNumerator_eq_table,exchangeTable, + mul_zero,zero_mul,add_zero] + +theorem hyb_entry_8_14 (x y z : ℂ) : + hybLeft x y z .zero .minus .minus .plus .plus .minus = hybRight x y z .zero .minus .minus .plus .plus .minus := by + simp only [hybLeft,hybRight,sum_spin,exchangeNumerator_eq_table,exchangeTable, + mul_zero,zero_mul,zero_add,add_zero] + +theorem hyb_entry_8_15 (x y z : ℂ) : + hybLeft x y z .zero .minus .minus .plus .minus .zero = hybRight x y z .zero .minus .minus .plus .minus .zero := by + simp only [hybLeft,hybRight,sum_spin,exchangeNumerator_eq_table,exchangeTable, + mul_zero,zero_mul,zero_add,add_zero] + +theorem hyb_entry_8_16 (x y z : ℂ) : + hybLeft x y z .zero .minus .minus .plus .minus .plus = hybRight x y z .zero .minus .minus .plus .minus .plus := by + simp only [hybLeft,hybRight,sum_spin,exchangeNumerator_eq_table,exchangeTable, + mul_zero,zero_mul,zero_add,add_zero] + +theorem hyb_entry_8_17 (x y z : ℂ) : + hybLeft x y z .zero .minus .minus .plus .minus .minus = hybRight x y z .zero .minus .minus .plus .minus .minus := by + simp only [hybLeft,hybRight,sum_spin,exchangeNumerator_eq_table,exchangeTable, + mul_zero,zero_mul,zero_add,add_zero] + +theorem hyb_entry_8_18 (x y z : ℂ) : + hybLeft x y z .zero .minus .minus .minus .zero .zero = hybRight x y z .zero .minus .minus .minus .zero .zero := by + simp only [hybLeft,hybRight,sum_spin,exchangeNumerator_eq_table,exchangeTable, + mul_zero,zero_mul,zero_add,add_zero] + +theorem hyb_entry_8_19 (x y z : ℂ) : + hybLeft x y z .zero .minus .minus .minus .zero .plus = hybRight x y z .zero .minus .minus .minus .zero .plus := by + simp only [hybLeft,hybRight,sum_spin,exchangeNumerator_eq_table,exchangeTable, + mul_zero,zero_mul,zero_add,add_zero] + +theorem hyb_entry_8_20 (x y z : ℂ) : + hybLeft x y z .zero .minus .minus .minus .zero .minus = hybRight x y z .zero .minus .minus .minus .zero .minus := by + simp only [hybLeft,hybRight,sum_spin,exchangeNumerator_eq_table,exchangeTable, + mul_zero,zero_mul,zero_add,add_zero] + all_goals ring_nf + all_goals try simp only [q_pow_eight,q_pow_10,q_pow_12,q_pow_14] + all_goals ring + +theorem hyb_entry_8_21 (x y z : ℂ) : + hybLeft x y z .zero .minus .minus .minus .plus .zero = hybRight x y z .zero .minus .minus .minus .plus .zero := by + simp only [hybLeft,hybRight,sum_spin,exchangeNumerator_eq_table,exchangeTable, + mul_zero,zero_mul,zero_add,add_zero] + +theorem hyb_entry_8_22 (x y z : ℂ) : + hybLeft x y z .zero .minus .minus .minus .plus .plus = hybRight x y z .zero .minus .minus .minus .plus .plus := by + simp only [hybLeft,hybRight,sum_spin,exchangeNumerator_eq_table,exchangeTable, + mul_zero,zero_mul,zero_add,add_zero] + +theorem hyb_entry_8_23 (x y z : ℂ) : + hybLeft x y z .zero .minus .minus .minus .plus .minus = hybRight x y z .zero .minus .minus .minus .plus .minus := by + simp only [hybLeft,hybRight,sum_spin,exchangeNumerator_eq_table,exchangeTable, + mul_zero,zero_mul,zero_add,add_zero] + +theorem hyb_entry_8_24 (x y z : ℂ) : + hybLeft x y z .zero .minus .minus .minus .minus .zero = hybRight x y z .zero .minus .minus .minus .minus .zero := by + simp only [hybLeft,hybRight,sum_spin,exchangeNumerator_eq_table,exchangeTable, + mul_zero,zero_mul,zero_add,add_zero] + all_goals ring_nf + +theorem hyb_entry_8_25 (x y z : ℂ) : + hybLeft x y z .zero .minus .minus .minus .minus .plus = hybRight x y z .zero .minus .minus .minus .minus .plus := by + simp only [hybLeft,hybRight,sum_spin,exchangeNumerator_eq_table,exchangeTable, + mul_zero,zero_mul,zero_add,add_zero] + +theorem hyb_entry_8_26 (x y z : ℂ) : + hybLeft x y z .zero .minus .minus .minus .minus .minus = hybRight x y z .zero .minus .minus .minus .minus .minus := by + simp only [hybLeft,hybRight,sum_spin,exchangeNumerator_eq_table,exchangeTable, + mul_zero,zero_mul,zero_add,add_zero] + +theorem hyb_entry_9_0 (x y z : ℂ) : + hybLeft x y z .plus .zero .zero .zero .zero .zero = hybRight x y z .plus .zero .zero .zero .zero .zero := by + simp only [hybLeft,hybRight,sum_spin,exchangeNumerator_eq_table,exchangeTable, + mul_zero,zero_mul,zero_add,add_zero] + +theorem hyb_entry_9_1 (x y z : ℂ) : + hybLeft x y z .plus .zero .zero .zero .zero .plus = hybRight x y z .plus .zero .zero .zero .zero .plus := by + simp only [hybLeft,hybRight,sum_spin,exchangeNumerator_eq_table,exchangeTable, + mul_zero,zero_mul,zero_add,add_zero] + all_goals ring_nf + +theorem hyb_entry_9_2 (x y z : ℂ) : + hybLeft x y z .plus .zero .zero .zero .zero .minus = hybRight x y z .plus .zero .zero .zero .zero .minus := by + simp only [hybLeft,hybRight,sum_spin,exchangeNumerator_eq_table,exchangeTable, + mul_zero,zero_mul,zero_add,add_zero] + +theorem hyb_entry_9_3 (x y z : ℂ) : + hybLeft x y z .plus .zero .zero .zero .plus .zero = hybRight x y z .plus .zero .zero .zero .plus .zero := by + simp only [hybLeft,hybRight,sum_spin,exchangeNumerator_eq_table,exchangeTable, + mul_zero,zero_mul,zero_add,add_zero] + all_goals ring_nf + all_goals try simp only [q_pow_eight,q_pow_10,q_pow_12,q_pow_14] + all_goals ring + +theorem hyb_entry_9_4 (x y z : ℂ) : + hybLeft x y z .plus .zero .zero .zero .plus .plus = hybRight x y z .plus .zero .zero .zero .plus .plus := by + simp only [hybLeft,hybRight,sum_spin,exchangeNumerator_eq_table,exchangeTable, + mul_zero,zero_mul,zero_add,add_zero] + +theorem hyb_entry_9_5 (x y z : ℂ) : + hybLeft x y z .plus .zero .zero .zero .plus .minus = hybRight x y z .plus .zero .zero .zero .plus .minus := by + simp only [hybLeft,hybRight,sum_spin,exchangeNumerator_eq_table,exchangeTable, + mul_zero,zero_mul,zero_add,add_zero] + +theorem hyb_entry_9_6 (x y z : ℂ) : + hybLeft x y z .plus .zero .zero .zero .minus .zero = hybRight x y z .plus .zero .zero .zero .minus .zero := by + simp only [hybLeft,hybRight,sum_spin,exchangeNumerator_eq_table,exchangeTable, + mul_zero,zero_mul,add_zero] + +theorem hyb_entry_9_7 (x y z : ℂ) : + hybLeft x y z .plus .zero .zero .zero .minus .plus = hybRight x y z .plus .zero .zero .zero .minus .plus := by + simp only [hybLeft,hybRight,sum_spin,exchangeNumerator_eq_table,exchangeTable, + mul_zero,zero_mul,zero_add,add_zero] + +theorem hyb_entry_9_8 (x y z : ℂ) : + hybLeft x y z .plus .zero .zero .zero .minus .minus = hybRight x y z .plus .zero .zero .zero .minus .minus := by + simp only [hybLeft,hybRight,sum_spin,exchangeNumerator_eq_table,exchangeTable, + mul_zero,zero_mul,zero_add,add_zero] + +theorem hyb_entry_9_9 (x y z : ℂ) : + hybLeft x y z .plus .zero .zero .plus .zero .zero = hybRight x y z .plus .zero .zero .plus .zero .zero := by + simp only [hybLeft,hybRight,sum_spin,exchangeNumerator_eq_table,exchangeTable, + mul_zero,zero_mul,zero_add,add_zero] + all_goals ring_nf + all_goals try simp only [q_pow_eight,q_pow_10,q_pow_12,q_pow_14,q_pow_16,q_pow_18] + all_goals ring + +theorem hyb_entry_9_10 (x y z : ℂ) : + hybLeft x y z .plus .zero .zero .plus .zero .plus = hybRight x y z .plus .zero .zero .plus .zero .plus := by + simp only [hybLeft,hybRight,sum_spin,exchangeNumerator_eq_table,exchangeTable, + mul_zero,zero_mul,zero_add,add_zero] + +theorem hyb_entry_9_11 (x y z : ℂ) : + hybLeft x y z .plus .zero .zero .plus .zero .minus = hybRight x y z .plus .zero .zero .plus .zero .minus := by + simp only [hybLeft,hybRight,sum_spin,exchangeNumerator_eq_table,exchangeTable, + mul_zero,zero_mul,zero_add,add_zero] + +theorem hyb_entry_9_12 (x y z : ℂ) : + hybLeft x y z .plus .zero .zero .plus .plus .zero = hybRight x y z .plus .zero .zero .plus .plus .zero := by + simp only [hybLeft,hybRight,sum_spin,exchangeNumerator_eq_table,exchangeTable, + mul_zero,zero_mul,zero_add,add_zero] + +theorem hyb_entry_9_13 (x y z : ℂ) : + hybLeft x y z .plus .zero .zero .plus .plus .plus = hybRight x y z .plus .zero .zero .plus .plus .plus := by + simp only [hybLeft,hybRight,sum_spin,exchangeNumerator_eq_table,exchangeTable, + mul_zero,zero_mul,zero_add,add_zero] + +theorem hyb_entry_9_14 (x y z : ℂ) : + hybLeft x y z .plus .zero .zero .plus .plus .minus = hybRight x y z .plus .zero .zero .plus .plus .minus := by + simp only [hybLeft,hybRight,sum_spin,exchangeNumerator_eq_table,exchangeTable, + mul_zero,zero_mul,zero_add,add_zero] + all_goals ring_nf + all_goals try simp only [q_pow_9,q_pow_11,q_pow_13,q_pow_15,q_pow_17] + all_goals ring + +theorem hyb_entry_9_15 (x y z : ℂ) : + hybLeft x y z .plus .zero .zero .plus .minus .zero = hybRight x y z .plus .zero .zero .plus .minus .zero := by + simp only [hybLeft,hybRight,sum_spin,exchangeNumerator_eq_table,exchangeTable, + mul_zero,zero_mul,zero_add,add_zero] + +theorem hyb_entry_9_16 (x y z : ℂ) : + hybLeft x y z .plus .zero .zero .plus .minus .plus = hybRight x y z .plus .zero .zero .plus .minus .plus := by + simp only [hybLeft,hybRight,sum_spin,exchangeNumerator_eq_table,exchangeTable, + mul_zero,zero_mul,zero_add,add_zero] + all_goals ring_nf + all_goals try simp only [q_pow_9,q_pow_11,q_pow_13,q_pow_15,q_pow_17] + all_goals ring + +theorem hyb_entry_9_17 (x y z : ℂ) : + hybLeft x y z .plus .zero .zero .plus .minus .minus = hybRight x y z .plus .zero .zero .plus .minus .minus := by + simp only [hybLeft,hybRight,sum_spin,exchangeNumerator_eq_table,exchangeTable, + mul_zero,zero_mul,zero_add,add_zero] + +theorem hyb_entry_9_18 (x y z : ℂ) : + hybLeft x y z .plus .zero .zero .minus .zero .zero = hybRight x y z .plus .zero .zero .minus .zero .zero := by + simp only [hybLeft,hybRight,sum_spin,exchangeNumerator_eq_table,exchangeTable, + mul_zero,zero_mul,zero_add,add_zero] + +theorem hyb_entry_9_19 (x y z : ℂ) : + hybLeft x y z .plus .zero .zero .minus .zero .plus = hybRight x y z .plus .zero .zero .minus .zero .plus := by + simp only [hybLeft,hybRight,sum_spin,exchangeNumerator_eq_table,exchangeTable, + mul_zero,zero_mul,zero_add,add_zero] + +theorem hyb_entry_9_20 (x y z : ℂ) : + hybLeft x y z .plus .zero .zero .minus .zero .minus = hybRight x y z .plus .zero .zero .minus .zero .minus := by + simp only [hybLeft,hybRight,sum_spin,exchangeNumerator_eq_table,exchangeTable, + mul_zero,zero_mul,add_zero] + +theorem hyb_entry_9_21 (x y z : ℂ) : + hybLeft x y z .plus .zero .zero .minus .plus .zero = hybRight x y z .plus .zero .zero .minus .plus .zero := by + simp only [hybLeft,hybRight,sum_spin,exchangeNumerator_eq_table,exchangeTable, + mul_zero,zero_mul,zero_add,add_zero] + +theorem hyb_entry_9_22 (x y z : ℂ) : + hybLeft x y z .plus .zero .zero .minus .plus .plus = hybRight x y z .plus .zero .zero .minus .plus .plus := by + simp only [hybLeft,hybRight,sum_spin,exchangeNumerator_eq_table,exchangeTable, + mul_zero,zero_mul,zero_add,add_zero] + all_goals ring_nf + all_goals try simp only [q_pow_9,q_pow_11,q_pow_13,q_pow_15,q_pow_17] + all_goals ring + +theorem hyb_entry_9_23 (x y z : ℂ) : + hybLeft x y z .plus .zero .zero .minus .plus .minus = hybRight x y z .plus .zero .zero .minus .plus .minus := by + simp only [hybLeft,hybRight,sum_spin,exchangeNumerator_eq_table,exchangeTable, + mul_zero,zero_mul,zero_add,add_zero] + +theorem hyb_entry_9_24 (x y z : ℂ) : + hybLeft x y z .plus .zero .zero .minus .minus .zero = hybRight x y z .plus .zero .zero .minus .minus .zero := by + simp only [hybLeft,hybRight,sum_spin,exchangeNumerator_eq_table,exchangeTable, + mul_zero,zero_mul,zero_add,add_zero] + +theorem hyb_entry_9_25 (x y z : ℂ) : + hybLeft x y z .plus .zero .zero .minus .minus .plus = hybRight x y z .plus .zero .zero .minus .minus .plus := by + simp only [hybLeft,hybRight,sum_spin,exchangeNumerator_eq_table,exchangeTable, + mul_zero,zero_mul,zero_add,add_zero] + +theorem hyb_entry_9_26 (x y z : ℂ) : + hybLeft x y z .plus .zero .zero .minus .minus .minus = hybRight x y z .plus .zero .zero .minus .minus .minus := by + simp only [hybLeft,hybRight,sum_spin,exchangeNumerator_eq_table,exchangeTable, + mul_zero,zero_mul,zero_add,add_zero] + +theorem hyb_entry_10_0 (x y z : ℂ) : + hybLeft x y z .plus .zero .plus .zero .zero .zero = hybRight x y z .plus .zero .plus .zero .zero .zero := by + simp only [hybLeft,hybRight,sum_spin,exchangeNumerator_eq_table,exchangeTable, + mul_zero,zero_mul,zero_add,add_zero] + +theorem hyb_entry_10_1 (x y z : ℂ) : + hybLeft x y z .plus .zero .plus .zero .zero .plus = hybRight x y z .plus .zero .plus .zero .zero .plus := by + simp only [hybLeft,hybRight,sum_spin,exchangeNumerator_eq_table,exchangeTable, + mul_zero,zero_mul,zero_add,add_zero] + +theorem hyb_entry_10_2 (x y z : ℂ) : + hybLeft x y z .plus .zero .plus .zero .zero .minus = hybRight x y z .plus .zero .plus .zero .zero .minus := by + simp only [hybLeft,hybRight,sum_spin,exchangeNumerator_eq_table,exchangeTable, + mul_zero,zero_mul,zero_add,add_zero] + +theorem hyb_entry_10_3 (x y z : ℂ) : + hybLeft x y z .plus .zero .plus .zero .plus .zero = hybRight x y z .plus .zero .plus .zero .plus .zero := by + simp only [hybLeft,hybRight,sum_spin,exchangeNumerator_eq_table,exchangeTable, + mul_zero,zero_mul,zero_add,add_zero] + +theorem hyb_entry_10_4 (x y z : ℂ) : + hybLeft x y z .plus .zero .plus .zero .plus .plus = hybRight x y z .plus .zero .plus .zero .plus .plus := by + simp only [hybLeft,hybRight,sum_spin,exchangeNumerator_eq_table,exchangeTable, + mul_zero,zero_mul,zero_add,add_zero] + all_goals ring_nf + all_goals try simp only [q_pow_eight,q_pow_10,q_pow_12,q_pow_14] + all_goals ring + +theorem hyb_entry_10_5 (x y z : ℂ) : + hybLeft x y z .plus .zero .plus .zero .plus .minus = hybRight x y z .plus .zero .plus .zero .plus .minus := by + simp only [hybLeft,hybRight,sum_spin,exchangeNumerator_eq_table,exchangeTable, + mul_zero,zero_mul,zero_add,add_zero] + +theorem hyb_entry_10_6 (x y z : ℂ) : + hybLeft x y z .plus .zero .plus .zero .minus .zero = hybRight x y z .plus .zero .plus .zero .minus .zero := by + simp only [hybLeft,hybRight,sum_spin,exchangeNumerator_eq_table,exchangeTable, + mul_zero,zero_mul,add_zero] + +theorem hyb_entry_10_7 (x y z : ℂ) : + hybLeft x y z .plus .zero .plus .zero .minus .plus = hybRight x y z .plus .zero .plus .zero .minus .plus := by + simp only [hybLeft,hybRight,sum_spin,exchangeNumerator_eq_table,exchangeTable, + mul_zero,zero_mul,zero_add,add_zero] + +theorem hyb_entry_10_8 (x y z : ℂ) : + hybLeft x y z .plus .zero .plus .zero .minus .minus = hybRight x y z .plus .zero .plus .zero .minus .minus := by + simp only [hybLeft,hybRight,sum_spin,exchangeNumerator_eq_table,exchangeTable, + mul_zero,zero_mul,add_zero] + +theorem hyb_entry_10_9 (x y z : ℂ) : + hybLeft x y z .plus .zero .plus .plus .zero .zero = hybRight x y z .plus .zero .plus .plus .zero .zero := by + simp only [hybLeft,hybRight,sum_spin,exchangeNumerator_eq_table,exchangeTable, + mul_zero,zero_mul,zero_add,add_zero] + +theorem hyb_entry_10_10 (x y z : ℂ) : + hybLeft x y z .plus .zero .plus .plus .zero .plus = hybRight x y z .plus .zero .plus .plus .zero .plus := by + simp only [hybLeft,hybRight,sum_spin,exchangeNumerator_eq_table,exchangeTable, + mul_zero,zero_mul,zero_add,add_zero] + all_goals ring_nf + +theorem hyb_entry_10_11 (x y z : ℂ) : + hybLeft x y z .plus .zero .plus .plus .zero .minus = hybRight x y z .plus .zero .plus .plus .zero .minus := by + simp only [hybLeft,hybRight,sum_spin,exchangeNumerator_eq_table,exchangeTable, + mul_zero,zero_mul,zero_add,add_zero] + +theorem hyb_entry_10_12 (x y z : ℂ) : + hybLeft x y z .plus .zero .plus .plus .plus .zero = hybRight x y z .plus .zero .plus .plus .plus .zero := by + simp only [hybLeft,hybRight,sum_spin,exchangeNumerator_eq_table,exchangeTable, + mul_zero,zero_mul,zero_add,add_zero] + all_goals ring_nf + all_goals try simp only [q_pow_eight,q_pow_10,q_pow_12,q_pow_14] + all_goals ring + +theorem hyb_entry_10_13 (x y z : ℂ) : + hybLeft x y z .plus .zero .plus .plus .plus .plus = hybRight x y z .plus .zero .plus .plus .plus .plus := by + simp only [hybLeft,hybRight,sum_spin,exchangeNumerator_eq_table,exchangeTable, + mul_zero,zero_mul,zero_add,add_zero] + +theorem hyb_entry_10_14 (x y z : ℂ) : + hybLeft x y z .plus .zero .plus .plus .plus .minus = hybRight x y z .plus .zero .plus .plus .plus .minus := by + simp only [hybLeft,hybRight,sum_spin,exchangeNumerator_eq_table,exchangeTable, + mul_zero,zero_mul,zero_add,add_zero] + +theorem hyb_entry_10_15 (x y z : ℂ) : + hybLeft x y z .plus .zero .plus .plus .minus .zero = hybRight x y z .plus .zero .plus .plus .minus .zero := by + simp only [hybLeft,hybRight,sum_spin,exchangeNumerator_eq_table,exchangeTable, + mul_zero,zero_mul,zero_add,add_zero] + +theorem hyb_entry_10_16 (x y z : ℂ) : + hybLeft x y z .plus .zero .plus .plus .minus .plus = hybRight x y z .plus .zero .plus .plus .minus .plus := by + simp only [hybLeft,hybRight,sum_spin,exchangeNumerator_eq_table,exchangeTable, + mul_zero,zero_mul,zero_add,add_zero] + +theorem hyb_entry_10_17 (x y z : ℂ) : + hybLeft x y z .plus .zero .plus .plus .minus .minus = hybRight x y z .plus .zero .plus .plus .minus .minus := by + simp only [hybLeft,hybRight,sum_spin,exchangeNumerator_eq_table,exchangeTable, + mul_zero,zero_mul,zero_add,add_zero] + +theorem hyb_entry_10_18 (x y z : ℂ) : + hybLeft x y z .plus .zero .plus .minus .zero .zero = hybRight x y z .plus .zero .plus .minus .zero .zero := by + simp only [hybLeft,hybRight,sum_spin,exchangeNumerator_eq_table,exchangeTable, + mul_zero,zero_mul,add_zero] + +theorem hyb_entry_10_19 (x y z : ℂ) : + hybLeft x y z .plus .zero .plus .minus .zero .plus = hybRight x y z .plus .zero .plus .minus .zero .plus := by + simp only [hybLeft,hybRight,sum_spin,exchangeNumerator_eq_table,exchangeTable, + mul_zero,zero_mul,add_zero] + +theorem hyb_entry_10_20 (x y z : ℂ) : + hybLeft x y z .plus .zero .plus .minus .zero .minus = hybRight x y z .plus .zero .plus .minus .zero .minus := by + simp only [hybLeft,hybRight,sum_spin,exchangeNumerator_eq_table,exchangeTable, + mul_zero,zero_mul,add_zero] + +theorem hyb_entry_10_21 (x y z : ℂ) : + hybLeft x y z .plus .zero .plus .minus .plus .zero = hybRight x y z .plus .zero .plus .minus .plus .zero := by + simp only [hybLeft,hybRight,sum_spin,exchangeNumerator_eq_table,exchangeTable, + mul_zero,zero_mul,zero_add,add_zero] + +theorem hyb_entry_10_22 (x y z : ℂ) : + hybLeft x y z .plus .zero .plus .minus .plus .plus = hybRight x y z .plus .zero .plus .minus .plus .plus := by + simp only [hybLeft,hybRight,sum_spin,exchangeNumerator_eq_table,exchangeTable, + mul_zero,zero_mul,zero_add,add_zero] + +theorem hyb_entry_10_23 (x y z : ℂ) : + hybLeft x y z .plus .zero .plus .minus .plus .minus = hybRight x y z .plus .zero .plus .minus .plus .minus := by + simp only [hybLeft,hybRight,sum_spin,exchangeNumerator_eq_table,exchangeTable, + mul_zero,zero_mul,zero_add,add_zero] + +theorem hyb_entry_10_24 (x y z : ℂ) : + hybLeft x y z .plus .zero .plus .minus .minus .zero = hybRight x y z .plus .zero .plus .minus .minus .zero := by + simp only [hybLeft,hybRight,sum_spin,exchangeNumerator_eq_table,exchangeTable, + mul_zero,zero_mul,add_zero] + +theorem hyb_entry_10_25 (x y z : ℂ) : + hybLeft x y z .plus .zero .plus .minus .minus .plus = hybRight x y z .plus .zero .plus .minus .minus .plus := by + simp only [hybLeft,hybRight,sum_spin,exchangeNumerator_eq_table,exchangeTable, + mul_zero,zero_mul,zero_add,add_zero] + +theorem hyb_entry_10_26 (x y z : ℂ) : + hybLeft x y z .plus .zero .plus .minus .minus .minus = hybRight x y z .plus .zero .plus .minus .minus .minus := by + simp only [hybLeft,hybRight,sum_spin,exchangeNumerator_eq_table,exchangeTable, + mul_zero,zero_mul,add_zero] + +theorem hyb_entry_11_0 (x y z : ℂ) : + hybLeft x y z .plus .zero .minus .zero .zero .zero = hybRight x y z .plus .zero .minus .zero .zero .zero := by + simp only [hybLeft,hybRight,sum_spin,exchangeNumerator_eq_table,exchangeTable, + mul_zero,zero_mul,zero_add,add_zero] + all_goals ring_nf + +theorem hyb_entry_11_1 (x y z : ℂ) : + hybLeft x y z .plus .zero .minus .zero .zero .plus = hybRight x y z .plus .zero .minus .zero .zero .plus := by + simp only [hybLeft,hybRight,sum_spin,exchangeNumerator_eq_table,exchangeTable, + mul_zero,zero_mul,zero_add,add_zero] + +theorem hyb_entry_11_2 (x y z : ℂ) : + hybLeft x y z .plus .zero .minus .zero .zero .minus = hybRight x y z .plus .zero .minus .zero .zero .minus := by + simp only [hybLeft,hybRight,sum_spin,exchangeNumerator_eq_table,exchangeTable, + mul_zero,zero_mul,zero_add,add_zero] + +theorem hyb_entry_11_3 (x y z : ℂ) : + hybLeft x y z .plus .zero .minus .zero .plus .zero = hybRight x y z .plus .zero .minus .zero .plus .zero := by + simp only [hybLeft,hybRight,sum_spin,exchangeNumerator_eq_table,exchangeTable, + mul_zero,zero_mul,zero_add,add_zero] + +theorem hyb_entry_11_4 (x y z : ℂ) : + hybLeft x y z .plus .zero .minus .zero .plus .plus = hybRight x y z .plus .zero .minus .zero .plus .plus := by + simp only [hybLeft,hybRight,sum_spin,exchangeNumerator_eq_table,exchangeTable, + mul_zero,zero_mul,add_zero] + +theorem hyb_entry_11_5 (x y z : ℂ) : + hybLeft x y z .plus .zero .minus .zero .plus .minus = hybRight x y z .plus .zero .minus .zero .plus .minus := by + simp only [hybLeft,hybRight,sum_spin,exchangeNumerator_eq_table,exchangeTable, + mul_zero,zero_mul,zero_add,add_zero] + all_goals ring_nf + all_goals try simp only [q_pow_eight,q_pow_10,q_pow_12,q_pow_14] + all_goals ring + +theorem hyb_entry_11_6 (x y z : ℂ) : + hybLeft x y z .plus .zero .minus .zero .minus .zero = hybRight x y z .plus .zero .minus .zero .minus .zero := by + simp only [hybLeft,hybRight,sum_spin,exchangeNumerator_eq_table,exchangeTable, + mul_zero,zero_mul,zero_add,add_zero] + +theorem hyb_entry_11_7 (x y z : ℂ) : + hybLeft x y z .plus .zero .minus .zero .minus .plus = hybRight x y z .plus .zero .minus .zero .minus .plus := by + simp only [hybLeft,hybRight,sum_spin,exchangeNumerator_eq_table,exchangeTable, + mul_zero,zero_mul,zero_add,add_zero] + all_goals ring_nf + all_goals try simp only [q_pow_eight,q_pow_10,q_pow_12,q_pow_14] + all_goals ring + +theorem hyb_entry_11_8 (x y z : ℂ) : + hybLeft x y z .plus .zero .minus .zero .minus .minus = hybRight x y z .plus .zero .minus .zero .minus .minus := by + simp only [hybLeft,hybRight,sum_spin,exchangeNumerator_eq_table,exchangeTable, + mul_zero,zero_mul,zero_add,add_zero] + +theorem hyb_entry_11_9 (x y z : ℂ) : + hybLeft x y z .plus .zero .minus .plus .zero .zero = hybRight x y z .plus .zero .minus .plus .zero .zero := by + simp only [hybLeft,hybRight,sum_spin,exchangeNumerator_eq_table,exchangeTable, + mul_zero,zero_mul,zero_add,add_zero] + +theorem hyb_entry_11_10 (x y z : ℂ) : + hybLeft x y z .plus .zero .minus .plus .zero .plus = hybRight x y z .plus .zero .minus .plus .zero .plus := by + simp only [hybLeft,hybRight,sum_spin,exchangeNumerator_eq_table,exchangeTable, + mul_zero,zero_mul,zero_add,add_zero] + +theorem hyb_entry_11_11 (x y z : ℂ) : + hybLeft x y z .plus .zero .minus .plus .zero .minus = hybRight x y z .plus .zero .minus .plus .zero .minus := by + simp only [hybLeft,hybRight,sum_spin,exchangeNumerator_eq_table,exchangeTable, + mul_zero,zero_mul,zero_add,add_zero] + all_goals ring_nf + +theorem hyb_entry_11_12 (x y z : ℂ) : + hybLeft x y z .plus .zero .minus .plus .plus .zero = hybRight x y z .plus .zero .minus .plus .plus .zero := by + simp only [hybLeft,hybRight,sum_spin,exchangeNumerator_eq_table,exchangeTable, + mul_zero,zero_mul,zero_add,add_zero] + +theorem hyb_entry_11_13 (x y z : ℂ) : + hybLeft x y z .plus .zero .minus .plus .plus .plus = hybRight x y z .plus .zero .minus .plus .plus .plus := by + simp only [hybLeft,hybRight,sum_spin,exchangeNumerator_eq_table,exchangeTable, + mul_zero,zero_mul,add_zero] + +theorem hyb_entry_11_14 (x y z : ℂ) : + hybLeft x y z .plus .zero .minus .plus .plus .minus = hybRight x y z .plus .zero .minus .plus .plus .minus := by + simp only [hybLeft,hybRight,sum_spin,exchangeNumerator_eq_table,exchangeTable, + mul_zero,zero_mul,zero_add,add_zero] + +theorem hyb_entry_11_15 (x y z : ℂ) : + hybLeft x y z .plus .zero .minus .plus .minus .zero = hybRight x y z .plus .zero .minus .plus .minus .zero := by + simp only [hybLeft,hybRight,sum_spin,exchangeNumerator_eq_table,exchangeTable, + mul_zero,zero_mul,zero_add,add_zero] + all_goals ring_nf + all_goals try simp only [q_pow_eight,q_pow_10,q_pow_12,q_pow_14] + all_goals ring + +theorem hyb_entry_11_16 (x y z : ℂ) : + hybLeft x y z .plus .zero .minus .plus .minus .plus = hybRight x y z .plus .zero .minus .plus .minus .plus := by + simp only [hybLeft,hybRight,sum_spin,exchangeNumerator_eq_table,exchangeTable, + mul_zero,zero_mul,zero_add,add_zero] + +theorem hyb_entry_11_17 (x y z : ℂ) : + hybLeft x y z .plus .zero .minus .plus .minus .minus = hybRight x y z .plus .zero .minus .plus .minus .minus := by + simp only [hybLeft,hybRight,sum_spin,exchangeNumerator_eq_table,exchangeTable, + mul_zero,zero_mul,zero_add,add_zero] + +theorem hyb_entry_11_18 (x y z : ℂ) : + hybLeft x y z .plus .zero .minus .minus .zero .zero = hybRight x y z .plus .zero .minus .minus .zero .zero := by + simp only [hybLeft,hybRight,sum_spin,exchangeNumerator_eq_table,exchangeTable, + mul_zero,zero_mul,zero_add,add_zero] + +theorem hyb_entry_11_19 (x y z : ℂ) : + hybLeft x y z .plus .zero .minus .minus .zero .plus = hybRight x y z .plus .zero .minus .minus .zero .plus := by + simp only [hybLeft,hybRight,sum_spin,exchangeNumerator_eq_table,exchangeTable, + mul_zero,zero_mul,zero_add,add_zero] + all_goals ring_nf + +theorem hyb_entry_11_20 (x y z : ℂ) : + hybLeft x y z .plus .zero .minus .minus .zero .minus = hybRight x y z .plus .zero .minus .minus .zero .minus := by + simp only [hybLeft,hybRight,sum_spin,exchangeNumerator_eq_table,exchangeTable, + mul_zero,zero_mul,zero_add,add_zero] + +theorem hyb_entry_11_21 (x y z : ℂ) : + hybLeft x y z .plus .zero .minus .minus .plus .zero = hybRight x y z .plus .zero .minus .minus .plus .zero := by + simp only [hybLeft,hybRight,sum_spin,exchangeNumerator_eq_table,exchangeTable, + mul_zero,zero_mul,zero_add,add_zero] + all_goals ring_nf + all_goals try simp only [q_pow_eight,q_pow_10,q_pow_12,q_pow_14] + all_goals ring + +theorem hyb_entry_11_22 (x y z : ℂ) : + hybLeft x y z .plus .zero .minus .minus .plus .plus = hybRight x y z .plus .zero .minus .minus .plus .plus := by + simp only [hybLeft,hybRight,sum_spin,exchangeNumerator_eq_table,exchangeTable, + mul_zero,zero_mul,zero_add,add_zero] + +theorem hyb_entry_11_23 (x y z : ℂ) : + hybLeft x y z .plus .zero .minus .minus .plus .minus = hybRight x y z .plus .zero .minus .minus .plus .minus := by + simp only [hybLeft,hybRight,sum_spin,exchangeNumerator_eq_table,exchangeTable, + mul_zero,zero_mul,zero_add,add_zero] + +theorem hyb_entry_11_24 (x y z : ℂ) : + hybLeft x y z .plus .zero .minus .minus .minus .zero = hybRight x y z .plus .zero .minus .minus .minus .zero := by + simp only [hybLeft,hybRight,sum_spin,exchangeNumerator_eq_table,exchangeTable, + mul_zero,zero_mul,zero_add,add_zero] + +theorem hyb_entry_11_25 (x y z : ℂ) : + hybLeft x y z .plus .zero .minus .minus .minus .plus = hybRight x y z .plus .zero .minus .minus .minus .plus := by + simp only [hybLeft,hybRight,sum_spin,exchangeNumerator_eq_table,exchangeTable, + mul_zero,zero_mul,zero_add,add_zero] + +theorem hyb_entry_11_26 (x y z : ℂ) : + hybLeft x y z .plus .zero .minus .minus .minus .minus = hybRight x y z .plus .zero .minus .minus .minus .minus := by + simp only [hybLeft,hybRight,sum_spin,exchangeNumerator_eq_table,exchangeTable, + mul_zero,zero_mul,zero_add,add_zero] + +theorem hyb_entry_12_0 (x y z : ℂ) : + hybLeft x y z .plus .plus .zero .zero .zero .zero = hybRight x y z .plus .plus .zero .zero .zero .zero := by + simp only [hybLeft,hybRight,sum_spin,exchangeNumerator_eq_table,exchangeTable, + mul_zero,zero_mul,zero_add,add_zero] + +theorem hyb_entry_12_1 (x y z : ℂ) : + hybLeft x y z .plus .plus .zero .zero .zero .plus = hybRight x y z .plus .plus .zero .zero .zero .plus := by + simp only [hybLeft,hybRight,sum_spin,exchangeNumerator_eq_table,exchangeTable, + mul_zero,zero_mul,zero_add,add_zero] + +theorem hyb_entry_12_2 (x y z : ℂ) : + hybLeft x y z .plus .plus .zero .zero .zero .minus = hybRight x y z .plus .plus .zero .zero .zero .minus := by + simp only [hybLeft,hybRight,sum_spin,exchangeNumerator_eq_table,exchangeTable, + mul_zero,zero_mul,add_zero] + +theorem hyb_entry_12_3 (x y z : ℂ) : + hybLeft x y z .plus .plus .zero .zero .plus .zero = hybRight x y z .plus .plus .zero .zero .plus .zero := by + simp only [hybLeft,hybRight,sum_spin,exchangeNumerator_eq_table,exchangeTable, + mul_zero,zero_mul,zero_add,add_zero] + +theorem hyb_entry_12_4 (x y z : ℂ) : + hybLeft x y z .plus .plus .zero .zero .plus .plus = hybRight x y z .plus .plus .zero .zero .plus .plus := by + simp only [hybLeft,hybRight,sum_spin,exchangeNumerator_eq_table,exchangeTable, + mul_zero,zero_mul,zero_add,add_zero] + all_goals ring_nf + +theorem hyb_entry_12_5 (x y z : ℂ) : + hybLeft x y z .plus .plus .zero .zero .plus .minus = hybRight x y z .plus .plus .zero .zero .plus .minus := by + simp only [hybLeft,hybRight,sum_spin,exchangeNumerator_eq_table,exchangeTable, + mul_zero,zero_mul,zero_add,add_zero] + +theorem hyb_entry_12_6 (x y z : ℂ) : + hybLeft x y z .plus .plus .zero .zero .minus .zero = hybRight x y z .plus .plus .zero .zero .minus .zero := by + simp only [hybLeft,hybRight,sum_spin,exchangeNumerator_eq_table,exchangeTable, + mul_zero,zero_mul,add_zero] + +theorem hyb_entry_12_7 (x y z : ℂ) : + hybLeft x y z .plus .plus .zero .zero .minus .plus = hybRight x y z .plus .plus .zero .zero .minus .plus := by + simp only [hybLeft,hybRight,sum_spin,exchangeNumerator_eq_table,exchangeTable, + mul_zero,zero_mul,zero_add,add_zero] + +theorem hyb_entry_12_8 (x y z : ℂ) : + hybLeft x y z .plus .plus .zero .zero .minus .minus = hybRight x y z .plus .plus .zero .zero .minus .minus := by + simp only [hybLeft,hybRight,sum_spin,exchangeNumerator_eq_table,exchangeTable, + mul_zero,zero_mul,add_zero] + +theorem hyb_entry_12_9 (x y z : ℂ) : + hybLeft x y z .plus .plus .zero .plus .zero .zero = hybRight x y z .plus .plus .zero .plus .zero .zero := by + simp only [hybLeft,hybRight,sum_spin,exchangeNumerator_eq_table,exchangeTable, + mul_zero,zero_mul,zero_add,add_zero] + +theorem hyb_entry_12_10 (x y z : ℂ) : + hybLeft x y z .plus .plus .zero .plus .zero .plus = hybRight x y z .plus .plus .zero .plus .zero .plus := by + simp only [hybLeft,hybRight,sum_spin,exchangeNumerator_eq_table,exchangeTable, + mul_zero,zero_mul,zero_add,add_zero] + all_goals ring_nf + all_goals try simp only [q_pow_eight,q_pow_10,q_pow_12,q_pow_14] + all_goals ring + +theorem hyb_entry_12_11 (x y z : ℂ) : + hybLeft x y z .plus .plus .zero .plus .zero .minus = hybRight x y z .plus .plus .zero .plus .zero .minus := by + simp only [hybLeft,hybRight,sum_spin,exchangeNumerator_eq_table,exchangeTable, + mul_zero,zero_mul,zero_add,add_zero] + +theorem hyb_entry_12_12 (x y z : ℂ) : + hybLeft x y z .plus .plus .zero .plus .plus .zero = hybRight x y z .plus .plus .zero .plus .plus .zero := by + simp only [hybLeft,hybRight,sum_spin,exchangeNumerator_eq_table,exchangeTable, + mul_zero,zero_mul,zero_add,add_zero] + all_goals ring_nf + all_goals try simp only [q_pow_eight,q_pow_10,q_pow_12,q_pow_14,q_pow_16,q_pow_18] + all_goals ring + +theorem hyb_entry_12_13 (x y z : ℂ) : + hybLeft x y z .plus .plus .zero .plus .plus .plus = hybRight x y z .plus .plus .zero .plus .plus .plus := by + simp only [hybLeft,hybRight,sum_spin,exchangeNumerator_eq_table,exchangeTable, + mul_zero,zero_mul,zero_add,add_zero] + +theorem hyb_entry_12_14 (x y z : ℂ) : + hybLeft x y z .plus .plus .zero .plus .plus .minus = hybRight x y z .plus .plus .zero .plus .plus .minus := by + simp only [hybLeft,hybRight,sum_spin,exchangeNumerator_eq_table,exchangeTable, + mul_zero,zero_mul,zero_add,add_zero] + +theorem hyb_entry_12_15 (x y z : ℂ) : + hybLeft x y z .plus .plus .zero .plus .minus .zero = hybRight x y z .plus .plus .zero .plus .minus .zero := by + simp only [hybLeft,hybRight,sum_spin,exchangeNumerator_eq_table,exchangeTable, + mul_zero,zero_mul,zero_add,add_zero] + +theorem hyb_entry_12_16 (x y z : ℂ) : + hybLeft x y z .plus .plus .zero .plus .minus .plus = hybRight x y z .plus .plus .zero .plus .minus .plus := by + simp only [hybLeft,hybRight,sum_spin,exchangeNumerator_eq_table,exchangeTable, + mul_zero,zero_mul,zero_add,add_zero] + +theorem hyb_entry_12_17 (x y z : ℂ) : + hybLeft x y z .plus .plus .zero .plus .minus .minus = hybRight x y z .plus .plus .zero .plus .minus .minus := by + simp only [hybLeft,hybRight,sum_spin,exchangeNumerator_eq_table,exchangeTable, + mul_zero,zero_mul,add_zero] + +theorem hyb_entry_12_18 (x y z : ℂ) : + hybLeft x y z .plus .plus .zero .minus .zero .zero = hybRight x y z .plus .plus .zero .minus .zero .zero := by + simp only [hybLeft,hybRight,sum_spin,exchangeNumerator_eq_table,exchangeTable, + mul_zero,zero_mul,add_zero] + +theorem hyb_entry_12_19 (x y z : ℂ) : + hybLeft x y z .plus .plus .zero .minus .zero .plus = hybRight x y z .plus .plus .zero .minus .zero .plus := by + simp only [hybLeft,hybRight,sum_spin,exchangeNumerator_eq_table,exchangeTable, + mul_zero,zero_mul,zero_add,add_zero] + +theorem hyb_entry_12_20 (x y z : ℂ) : + hybLeft x y z .plus .plus .zero .minus .zero .minus = hybRight x y z .plus .plus .zero .minus .zero .minus := by + simp only [hybLeft,hybRight,sum_spin,exchangeNumerator_eq_table,exchangeTable, + mul_zero,zero_mul,add_zero] + +theorem hyb_entry_12_21 (x y z : ℂ) : + hybLeft x y z .plus .plus .zero .minus .plus .zero = hybRight x y z .plus .plus .zero .minus .plus .zero := by + simp only [hybLeft,hybRight,sum_spin,exchangeNumerator_eq_table,exchangeTable, + mul_zero,zero_mul,zero_add,add_zero] + +theorem hyb_entry_12_22 (x y z : ℂ) : + hybLeft x y z .plus .plus .zero .minus .plus .plus = hybRight x y z .plus .plus .zero .minus .plus .plus := by + simp only [hybLeft,hybRight,sum_spin,exchangeNumerator_eq_table,exchangeTable, + mul_zero,zero_mul,zero_add,add_zero] + +theorem hyb_entry_12_23 (x y z : ℂ) : + hybLeft x y z .plus .plus .zero .minus .plus .minus = hybRight x y z .plus .plus .zero .minus .plus .minus := by + simp only [hybLeft,hybRight,sum_spin,exchangeNumerator_eq_table,exchangeTable, + mul_zero,zero_mul,add_zero] + +theorem hyb_entry_12_24 (x y z : ℂ) : + hybLeft x y z .plus .plus .zero .minus .minus .zero = hybRight x y z .plus .plus .zero .minus .minus .zero := by + simp only [hybLeft,hybRight,sum_spin,exchangeNumerator_eq_table,exchangeTable, + mul_zero,zero_mul,zero_add,add_zero] + +theorem hyb_entry_12_25 (x y z : ℂ) : + hybLeft x y z .plus .plus .zero .minus .minus .plus = hybRight x y z .plus .plus .zero .minus .minus .plus := by + simp only [hybLeft,hybRight,sum_spin,exchangeNumerator_eq_table,exchangeTable, + mul_zero,zero_mul,zero_add,add_zero] + +theorem hyb_entry_12_26 (x y z : ℂ) : + hybLeft x y z .plus .plus .zero .minus .minus .minus = hybRight x y z .plus .plus .zero .minus .minus .minus := by + simp only [hybLeft,hybRight,sum_spin,exchangeNumerator_eq_table,exchangeTable, + mul_zero,zero_mul,add_zero] + +theorem hyb_entry_13_0 (x y z : ℂ) : + hybLeft x y z .plus .plus .plus .zero .zero .zero = hybRight x y z .plus .plus .plus .zero .zero .zero := by + simp only [hybLeft,hybRight,sum_spin,exchangeNumerator_eq_table,exchangeTable, + mul_zero,zero_mul,zero_add,add_zero] + +theorem hyb_entry_13_1 (x y z : ℂ) : + hybLeft x y z .plus .plus .plus .zero .zero .plus = hybRight x y z .plus .plus .plus .zero .zero .plus := by + simp only [hybLeft,hybRight,sum_spin,exchangeNumerator_eq_table,exchangeTable, + mul_zero,zero_mul,zero_add,add_zero] + +theorem hyb_entry_13_2 (x y z : ℂ) : + hybLeft x y z .plus .plus .plus .zero .zero .minus = hybRight x y z .plus .plus .plus .zero .zero .minus := by + simp only [hybLeft,hybRight,sum_spin,exchangeNumerator_eq_table,exchangeTable, + mul_zero,zero_mul,zero_add,add_zero] + +theorem hyb_entry_13_3 (x y z : ℂ) : + hybLeft x y z .plus .plus .plus .zero .plus .zero = hybRight x y z .plus .plus .plus .zero .plus .zero := by + simp only [hybLeft,hybRight,sum_spin,exchangeNumerator_eq_table,exchangeTable, + mul_zero,zero_mul,zero_add,add_zero] + +theorem hyb_entry_13_4 (x y z : ℂ) : + hybLeft x y z .plus .plus .plus .zero .plus .plus = hybRight x y z .plus .plus .plus .zero .plus .plus := by + simp only [hybLeft,hybRight,sum_spin,exchangeNumerator_eq_table,exchangeTable, + mul_zero,zero_mul,zero_add,add_zero] + +theorem hyb_entry_13_5 (x y z : ℂ) : + hybLeft x y z .plus .plus .plus .zero .plus .minus = hybRight x y z .plus .plus .plus .zero .plus .minus := by + simp only [hybLeft,hybRight,sum_spin,exchangeNumerator_eq_table,exchangeTable, + mul_zero,zero_mul,zero_add,add_zero] + +theorem hyb_entry_13_6 (x y z : ℂ) : + hybLeft x y z .plus .plus .plus .zero .minus .zero = hybRight x y z .plus .plus .plus .zero .minus .zero := by + simp only [hybLeft,hybRight,sum_spin,exchangeNumerator_eq_table,exchangeTable, + mul_zero,zero_mul,add_zero] + +theorem hyb_entry_13_7 (x y z : ℂ) : + hybLeft x y z .plus .plus .plus .zero .minus .plus = hybRight x y z .plus .plus .plus .zero .minus .plus := by + simp only [hybLeft,hybRight,sum_spin,exchangeNumerator_eq_table,exchangeTable, + mul_zero,zero_mul,zero_add,add_zero] + +theorem hyb_entry_13_8 (x y z : ℂ) : + hybLeft x y z .plus .plus .plus .zero .minus .minus = hybRight x y z .plus .plus .plus .zero .minus .minus := by + simp only [hybLeft,hybRight,sum_spin,exchangeNumerator_eq_table,exchangeTable, + mul_zero,zero_mul,add_zero] + +theorem hyb_entry_13_9 (x y z : ℂ) : + hybLeft x y z .plus .plus .plus .plus .zero .zero = hybRight x y z .plus .plus .plus .plus .zero .zero := by + simp only [hybLeft,hybRight,sum_spin,exchangeNumerator_eq_table,exchangeTable, + mul_zero,zero_mul,zero_add,add_zero] + +theorem hyb_entry_13_10 (x y z : ℂ) : + hybLeft x y z .plus .plus .plus .plus .zero .plus = hybRight x y z .plus .plus .plus .plus .zero .plus := by + simp only [hybLeft,hybRight,sum_spin,exchangeNumerator_eq_table,exchangeTable, + mul_zero,zero_mul,zero_add,add_zero] + +theorem hyb_entry_13_11 (x y z : ℂ) : + hybLeft x y z .plus .plus .plus .plus .zero .minus = hybRight x y z .plus .plus .plus .plus .zero .minus := by + simp only [hybLeft,hybRight,sum_spin,exchangeNumerator_eq_table,exchangeTable, + mul_zero,zero_mul,zero_add,add_zero] + +theorem hyb_entry_13_12 (x y z : ℂ) : + hybLeft x y z .plus .plus .plus .plus .plus .zero = hybRight x y z .plus .plus .plus .plus .plus .zero := by + simp only [hybLeft,hybRight,sum_spin,exchangeNumerator_eq_table,exchangeTable, + mul_zero,zero_mul,zero_add,add_zero] + +theorem hyb_entry_13_13 (x y z : ℂ) : + hybLeft x y z .plus .plus .plus .plus .plus .plus = hybRight x y z .plus .plus .plus .plus .plus .plus := by + simp only [hybLeft,hybRight,sum_spin,exchangeNumerator_eq_table,exchangeTable, + mul_zero,zero_mul,zero_add,add_zero] + all_goals ring_nf + +theorem hyb_entry_13_14 (x y z : ℂ) : + hybLeft x y z .plus .plus .plus .plus .plus .minus = hybRight x y z .plus .plus .plus .plus .plus .minus := by + simp only [hybLeft,hybRight,sum_spin,exchangeNumerator_eq_table,exchangeTable, + mul_zero,zero_mul,zero_add,add_zero] + +theorem hyb_entry_13_15 (x y z : ℂ) : + hybLeft x y z .plus .plus .plus .plus .minus .zero = hybRight x y z .plus .plus .plus .plus .minus .zero := by + simp only [hybLeft,hybRight,sum_spin,exchangeNumerator_eq_table,exchangeTable, + mul_zero,zero_mul,add_zero] + +theorem hyb_entry_13_16 (x y z : ℂ) : + hybLeft x y z .plus .plus .plus .plus .minus .plus = hybRight x y z .plus .plus .plus .plus .minus .plus := by + simp only [hybLeft,hybRight,sum_spin,exchangeNumerator_eq_table,exchangeTable, + mul_zero,zero_mul,zero_add,add_zero] + +theorem hyb_entry_13_17 (x y z : ℂ) : + hybLeft x y z .plus .plus .plus .plus .minus .minus = hybRight x y z .plus .plus .plus .plus .minus .minus := by + simp only [hybLeft,hybRight,sum_spin,exchangeNumerator_eq_table,exchangeTable, + mul_zero,zero_mul,zero_add,add_zero] + +theorem hyb_entry_13_18 (x y z : ℂ) : + hybLeft x y z .plus .plus .plus .minus .zero .zero = hybRight x y z .plus .plus .plus .minus .zero .zero := by + simp only [hybLeft,hybRight,sum_spin,exchangeNumerator_eq_table,exchangeTable, + mul_zero,zero_mul,zero_add,add_zero] + +theorem hyb_entry_13_19 (x y z : ℂ) : + hybLeft x y z .plus .plus .plus .minus .zero .plus = hybRight x y z .plus .plus .plus .minus .zero .plus := by + simp only [hybLeft,hybRight,sum_spin,exchangeNumerator_eq_table,exchangeTable, + mul_zero,zero_mul,zero_add,add_zero] + +theorem hyb_entry_13_20 (x y z : ℂ) : + hybLeft x y z .plus .plus .plus .minus .zero .minus = hybRight x y z .plus .plus .plus .minus .zero .minus := by + simp only [hybLeft,hybRight,sum_spin,exchangeNumerator_eq_table,exchangeTable, + mul_zero,zero_mul,add_zero] + +theorem hyb_entry_13_21 (x y z : ℂ) : + hybLeft x y z .plus .plus .plus .minus .plus .zero = hybRight x y z .plus .plus .plus .minus .plus .zero := by + simp only [hybLeft,hybRight,sum_spin,exchangeNumerator_eq_table,exchangeTable, + mul_zero,zero_mul,zero_add,add_zero] + +theorem hyb_entry_13_22 (x y z : ℂ) : + hybLeft x y z .plus .plus .plus .minus .plus .plus = hybRight x y z .plus .plus .plus .minus .plus .plus := by + simp only [hybLeft,hybRight,sum_spin,exchangeNumerator_eq_table,exchangeTable, + mul_zero,zero_mul,zero_add,add_zero] + +theorem hyb_entry_13_23 (x y z : ℂ) : + hybLeft x y z .plus .plus .plus .minus .plus .minus = hybRight x y z .plus .plus .plus .minus .plus .minus := by + simp only [hybLeft,hybRight,sum_spin,exchangeNumerator_eq_table,exchangeTable, + mul_zero,zero_mul,zero_add,add_zero] + +theorem hyb_entry_13_24 (x y z : ℂ) : + hybLeft x y z .plus .plus .plus .minus .minus .zero = hybRight x y z .plus .plus .plus .minus .minus .zero := by + simp only [hybLeft,hybRight,sum_spin,exchangeNumerator_eq_table,exchangeTable, + mul_zero,zero_mul,add_zero] + +theorem hyb_entry_13_25 (x y z : ℂ) : + hybLeft x y z .plus .plus .plus .minus .minus .plus = hybRight x y z .plus .plus .plus .minus .minus .plus := by + simp only [hybLeft,hybRight,sum_spin,exchangeNumerator_eq_table,exchangeTable, + mul_zero,zero_mul,zero_add,add_zero] + +theorem hyb_entry_13_26 (x y z : ℂ) : + hybLeft x y z .plus .plus .plus .minus .minus .minus = hybRight x y z .plus .plus .plus .minus .minus .minus := by + simp only [hybLeft,hybRight,sum_spin,exchangeNumerator_eq_table,exchangeTable, + mul_zero,zero_mul,add_zero] + +theorem hyb_entry_14_0 (x y z : ℂ) : + hybLeft x y z .plus .plus .minus .zero .zero .zero = hybRight x y z .plus .plus .minus .zero .zero .zero := by + simp only [hybLeft,hybRight,sum_spin,exchangeNumerator_eq_table,exchangeTable, + mul_zero,zero_mul,zero_add,add_zero] + +theorem hyb_entry_14_1 (x y z : ℂ) : + hybLeft x y z .plus .plus .minus .zero .zero .plus = hybRight x y z .plus .plus .minus .zero .zero .plus := by + simp only [hybLeft,hybRight,sum_spin,exchangeNumerator_eq_table,exchangeTable, + mul_zero,zero_mul,zero_add,add_zero] + all_goals ring_nf + all_goals try simp only [q_pow_9,q_pow_11,q_pow_13,q_pow_15,q_pow_17] + all_goals ring + +theorem hyb_entry_14_2 (x y z : ℂ) : + hybLeft x y z .plus .plus .minus .zero .zero .minus = hybRight x y z .plus .plus .minus .zero .zero .minus := by + simp only [hybLeft,hybRight,sum_spin,exchangeNumerator_eq_table,exchangeTable, + mul_zero,zero_mul,zero_add,add_zero] + +theorem hyb_entry_14_3 (x y z : ℂ) : + hybLeft x y z .plus .plus .minus .zero .plus .zero = hybRight x y z .plus .plus .minus .zero .plus .zero := by + simp only [hybLeft,hybRight,sum_spin,exchangeNumerator_eq_table,exchangeTable, + mul_zero,zero_mul,zero_add,add_zero] + all_goals ring_nf + all_goals try simp only [q_pow_9,q_pow_11,q_pow_13] + all_goals ring + +theorem hyb_entry_14_4 (x y z : ℂ) : + hybLeft x y z .plus .plus .minus .zero .plus .plus = hybRight x y z .plus .plus .minus .zero .plus .plus := by + simp only [hybLeft,hybRight,sum_spin,exchangeNumerator_eq_table,exchangeTable, + mul_zero,zero_mul,zero_add,add_zero] + +theorem hyb_entry_14_5 (x y z : ℂ) : + hybLeft x y z .plus .plus .minus .zero .plus .minus = hybRight x y z .plus .plus .minus .zero .plus .minus := by + simp only [hybLeft,hybRight,sum_spin,exchangeNumerator_eq_table,exchangeTable, + mul_zero,zero_mul,zero_add,add_zero] + +theorem hyb_entry_14_6 (x y z : ℂ) : + hybLeft x y z .plus .plus .minus .zero .minus .zero = hybRight x y z .plus .plus .minus .zero .minus .zero := by + simp only [hybLeft,hybRight,sum_spin,exchangeNumerator_eq_table,exchangeTable, + mul_zero,zero_mul,zero_add,add_zero] + +theorem hyb_entry_14_7 (x y z : ℂ) : + hybLeft x y z .plus .plus .minus .zero .minus .plus = hybRight x y z .plus .plus .minus .zero .minus .plus := by + simp only [hybLeft,hybRight,sum_spin,exchangeNumerator_eq_table,exchangeTable, + mul_zero,zero_mul,zero_add,add_zero] + +theorem hyb_entry_14_8 (x y z : ℂ) : + hybLeft x y z .plus .plus .minus .zero .minus .minus = hybRight x y z .plus .plus .minus .zero .minus .minus := by + simp only [hybLeft,hybRight,sum_spin,exchangeNumerator_eq_table,exchangeTable, + mul_zero,zero_mul,zero_add,add_zero] + +theorem hyb_entry_14_9 (x y z : ℂ) : + hybLeft x y z .plus .plus .minus .plus .zero .zero = hybRight x y z .plus .plus .minus .plus .zero .zero := by + simp only [hybLeft,hybRight,sum_spin,exchangeNumerator_eq_table,exchangeTable, + mul_zero,zero_mul,zero_add,add_zero] + all_goals ring_nf + all_goals try simp only [q_pow_9,q_pow_11,q_pow_13,q_pow_15,q_pow_17] + all_goals ring + +theorem hyb_entry_14_10 (x y z : ℂ) : + hybLeft x y z .plus .plus .minus .plus .zero .plus = hybRight x y z .plus .plus .minus .plus .zero .plus := by + simp only [hybLeft,hybRight,sum_spin,exchangeNumerator_eq_table,exchangeTable, + mul_zero,zero_mul,zero_add,add_zero] + +theorem hyb_entry_14_11 (x y z : ℂ) : + hybLeft x y z .plus .plus .minus .plus .zero .minus = hybRight x y z .plus .plus .minus .plus .zero .minus := by + simp only [hybLeft,hybRight,sum_spin,exchangeNumerator_eq_table,exchangeTable, + mul_zero,zero_mul,zero_add,add_zero] + +theorem hyb_entry_14_12 (x y z : ℂ) : + hybLeft x y z .plus .plus .minus .plus .plus .zero = hybRight x y z .plus .plus .minus .plus .plus .zero := by + simp only [hybLeft,hybRight,sum_spin,exchangeNumerator_eq_table,exchangeTable, + mul_zero,zero_mul,zero_add,add_zero] + +theorem hyb_entry_14_13 (x y z : ℂ) : + hybLeft x y z .plus .plus .minus .plus .plus .plus = hybRight x y z .plus .plus .minus .plus .plus .plus := by + simp only [hybLeft,hybRight,sum_spin,exchangeNumerator_eq_table,exchangeTable, + mul_zero,zero_mul,zero_add,add_zero] + +theorem hyb_entry_14_14 (x y z : ℂ) : + hybLeft x y z .plus .plus .minus .plus .plus .minus = hybRight x y z .plus .plus .minus .plus .plus .minus := by + simp only [hybLeft,hybRight,sum_spin,exchangeNumerator_eq_table,exchangeTable, + mul_zero,zero_mul,zero_add,add_zero] + all_goals ring_nf + all_goals try simp only [q_pow_eight,q_pow_10,q_pow_12,q_pow_14,q_pow_16,q_pow_18] + all_goals ring + +theorem hyb_entry_14_15 (x y z : ℂ) : + hybLeft x y z .plus .plus .minus .plus .minus .zero = hybRight x y z .plus .plus .minus .plus .minus .zero := by + simp only [hybLeft,hybRight,sum_spin,exchangeNumerator_eq_table,exchangeTable, + mul_zero,zero_mul,zero_add,add_zero] + +theorem hyb_entry_14_16 (x y z : ℂ) : + hybLeft x y z .plus .plus .minus .plus .minus .plus = hybRight x y z .plus .plus .minus .plus .minus .plus := by + simp only [hybLeft,hybRight,sum_spin,exchangeNumerator_eq_table,exchangeTable, + mul_zero,zero_mul,zero_add,add_zero] + all_goals ring_nf + all_goals try simp only [q_pow_eight,q_pow_10,q_pow_12,q_pow_14,q_pow_16,q_pow_18] + all_goals ring + +theorem hyb_entry_14_17 (x y z : ℂ) : + hybLeft x y z .plus .plus .minus .plus .minus .minus = hybRight x y z .plus .plus .minus .plus .minus .minus := by + simp only [hybLeft,hybRight,sum_spin,exchangeNumerator_eq_table,exchangeTable, + mul_zero,zero_mul,zero_add,add_zero] + +theorem hyb_entry_14_18 (x y z : ℂ) : + hybLeft x y z .plus .plus .minus .minus .zero .zero = hybRight x y z .plus .plus .minus .minus .zero .zero := by + simp only [hybLeft,hybRight,sum_spin,exchangeNumerator_eq_table,exchangeTable, + mul_zero,zero_mul,zero_add,add_zero] + +theorem hyb_entry_14_19 (x y z : ℂ) : + hybLeft x y z .plus .plus .minus .minus .zero .plus = hybRight x y z .plus .plus .minus .minus .zero .plus := by + simp only [hybLeft,hybRight,sum_spin,exchangeNumerator_eq_table,exchangeTable, + mul_zero,zero_mul,zero_add,add_zero] + +theorem hyb_entry_14_20 (x y z : ℂ) : + hybLeft x y z .plus .plus .minus .minus .zero .minus = hybRight x y z .plus .plus .minus .minus .zero .minus := by + simp only [hybLeft,hybRight,sum_spin,exchangeNumerator_eq_table,exchangeTable, + mul_zero,zero_mul,add_zero] + +theorem hyb_entry_14_21 (x y z : ℂ) : + hybLeft x y z .plus .plus .minus .minus .plus .zero = hybRight x y z .plus .plus .minus .minus .plus .zero := by + simp only [hybLeft,hybRight,sum_spin,exchangeNumerator_eq_table,exchangeTable, + mul_zero,zero_mul,zero_add,add_zero] + +theorem hyb_entry_14_22 (x y z : ℂ) : + hybLeft x y z .plus .plus .minus .minus .plus .plus = hybRight x y z .plus .plus .minus .minus .plus .plus := by + simp only [hybLeft,hybRight,sum_spin,exchangeNumerator_eq_table,exchangeTable, + mul_zero,zero_mul,zero_add,add_zero] + all_goals ring_nf + +theorem hyb_entry_14_23 (x y z : ℂ) : + hybLeft x y z .plus .plus .minus .minus .plus .minus = hybRight x y z .plus .plus .minus .minus .plus .minus := by + simp only [hybLeft,hybRight,sum_spin,exchangeNumerator_eq_table,exchangeTable, + mul_zero,zero_mul,zero_add,add_zero] + +theorem hyb_entry_14_24 (x y z : ℂ) : + hybLeft x y z .plus .plus .minus .minus .minus .zero = hybRight x y z .plus .plus .minus .minus .minus .zero := by + simp only [hybLeft,hybRight,sum_spin,exchangeNumerator_eq_table,exchangeTable, + mul_zero,zero_mul,zero_add,add_zero] + +theorem hyb_entry_14_25 (x y z : ℂ) : + hybLeft x y z .plus .plus .minus .minus .minus .plus = hybRight x y z .plus .plus .minus .minus .minus .plus := by + simp only [hybLeft,hybRight,sum_spin,exchangeNumerator_eq_table,exchangeTable, + mul_zero,zero_mul,zero_add,add_zero] + +theorem hyb_entry_14_26 (x y z : ℂ) : + hybLeft x y z .plus .plus .minus .minus .minus .minus = hybRight x y z .plus .plus .minus .minus .minus .minus := by + simp only [hybLeft,hybRight,sum_spin,exchangeNumerator_eq_table,exchangeTable, + mul_zero,zero_mul,zero_add,add_zero] + +theorem hyb_entry_15_0 (x y z : ℂ) : + hybLeft x y z .plus .minus .zero .zero .zero .zero = hybRight x y z .plus .minus .zero .zero .zero .zero := by + simp only [hybLeft,hybRight,sum_spin,exchangeNumerator_eq_table,exchangeTable, + mul_zero,zero_mul,zero_add,add_zero] + all_goals ring_nf + all_goals try simp only [q_pow_9,q_pow_11,q_pow_13,q_pow_15,q_pow_17] + all_goals ring + +theorem hyb_entry_15_1 (x y z : ℂ) : + hybLeft x y z .plus .minus .zero .zero .zero .plus = hybRight x y z .plus .minus .zero .zero .zero .plus := by + simp only [hybLeft,hybRight,sum_spin,exchangeNumerator_eq_table,exchangeTable, + mul_zero,zero_mul,zero_add,add_zero] + +theorem hyb_entry_15_2 (x y z : ℂ) : + hybLeft x y z .plus .minus .zero .zero .zero .minus = hybRight x y z .plus .minus .zero .zero .zero .minus := by + simp only [hybLeft,hybRight,sum_spin,exchangeNumerator_eq_table,exchangeTable, + mul_zero,zero_mul,zero_add,add_zero] + +theorem hyb_entry_15_3 (x y z : ℂ) : + hybLeft x y z .plus .minus .zero .zero .plus .zero = hybRight x y z .plus .minus .zero .zero .plus .zero := by + simp only [hybLeft,hybRight,sum_spin,exchangeNumerator_eq_table,exchangeTable, + mul_zero,zero_mul,zero_add,add_zero] + +theorem hyb_entry_15_4 (x y z : ℂ) : + hybLeft x y z .plus .minus .zero .zero .plus .plus = hybRight x y z .plus .minus .zero .zero .plus .plus := by + simp only [hybLeft,hybRight,sum_spin,exchangeNumerator_eq_table,exchangeTable, + mul_zero,zero_mul,zero_add,add_zero] + +theorem hyb_entry_15_5 (x y z : ℂ) : + hybLeft x y z .plus .minus .zero .zero .plus .minus = hybRight x y z .plus .minus .zero .zero .plus .minus := by + simp only [hybLeft,hybRight,sum_spin,exchangeNumerator_eq_table,exchangeTable, + mul_zero,zero_mul,zero_add,add_zero] + all_goals ring_nf + +theorem hyb_entry_15_6 (x y z : ℂ) : + hybLeft x y z .plus .minus .zero .zero .minus .zero = hybRight x y z .plus .minus .zero .zero .minus .zero := by + simp only [hybLeft,hybRight,sum_spin,exchangeNumerator_eq_table,exchangeTable, + mul_zero,zero_mul,zero_add,add_zero] + +theorem hyb_entry_15_7 (x y z : ℂ) : + hybLeft x y z .plus .minus .zero .zero .minus .plus = hybRight x y z .plus .minus .zero .zero .minus .plus := by + simp only [hybLeft,hybRight,sum_spin,exchangeNumerator_eq_table,exchangeTable, + mul_zero,zero_mul,zero_add,add_zero] + all_goals ring_nf + +theorem hyb_entry_15_8 (x y z : ℂ) : + hybLeft x y z .plus .minus .zero .zero .minus .minus = hybRight x y z .plus .minus .zero .zero .minus .minus := by + simp only [hybLeft,hybRight,sum_spin,exchangeNumerator_eq_table,exchangeTable, + mul_zero,zero_mul,zero_add,add_zero] + +theorem hyb_entry_15_9 (x y z : ℂ) : + hybLeft x y z .plus .minus .zero .plus .zero .zero = hybRight x y z .plus .minus .zero .plus .zero .zero := by + simp only [hybLeft,hybRight,sum_spin,exchangeNumerator_eq_table,exchangeTable, + mul_zero,zero_mul,zero_add,add_zero] + +theorem hyb_entry_15_10 (x y z : ℂ) : + hybLeft x y z .plus .minus .zero .plus .zero .plus = hybRight x y z .plus .minus .zero .plus .zero .plus := by + simp only [hybLeft,hybRight,sum_spin,exchangeNumerator_eq_table,exchangeTable, + mul_zero,zero_mul,zero_add,add_zero] + +theorem hyb_entry_15_11 (x y z : ℂ) : + hybLeft x y z .plus .minus .zero .plus .zero .minus = hybRight x y z .plus .minus .zero .plus .zero .minus := by + simp only [hybLeft,hybRight,sum_spin,exchangeNumerator_eq_table,exchangeTable, + mul_zero,zero_mul,zero_add,add_zero] + all_goals ring_nf + all_goals try simp only [q_pow_eight,q_pow_10,q_pow_12,q_pow_14] + all_goals ring + +theorem hyb_entry_15_12 (x y z : ℂ) : + hybLeft x y z .plus .minus .zero .plus .plus .zero = hybRight x y z .plus .minus .zero .plus .plus .zero := by + simp only [hybLeft,hybRight,sum_spin,exchangeNumerator_eq_table,exchangeTable, + mul_zero,zero_mul,zero_add,add_zero] + +theorem hyb_entry_15_13 (x y z : ℂ) : + hybLeft x y z .plus .minus .zero .plus .plus .plus = hybRight x y z .plus .minus .zero .plus .plus .plus := by + simp only [hybLeft,hybRight,sum_spin,exchangeNumerator_eq_table,exchangeTable, + mul_zero,zero_mul,add_zero] + +theorem hyb_entry_15_14 (x y z : ℂ) : + hybLeft x y z .plus .minus .zero .plus .plus .minus = hybRight x y z .plus .minus .zero .plus .plus .minus := by + simp only [hybLeft,hybRight,sum_spin,exchangeNumerator_eq_table,exchangeTable, + mul_zero,zero_mul,zero_add,add_zero] + +theorem hyb_entry_15_15 (x y z : ℂ) : + hybLeft x y z .plus .minus .zero .plus .minus .zero = hybRight x y z .plus .minus .zero .plus .minus .zero := by + simp only [hybLeft,hybRight,sum_spin,exchangeNumerator_eq_table,exchangeTable, + mul_zero,zero_mul,zero_add,add_zero] + all_goals ring_nf + all_goals try simp only [q_pow_eight,q_pow_10,q_pow_12,q_pow_14,q_pow_16,q_pow_18] + all_goals ring + +theorem hyb_entry_15_16 (x y z : ℂ) : + hybLeft x y z .plus .minus .zero .plus .minus .plus = hybRight x y z .plus .minus .zero .plus .minus .plus := by + simp only [hybLeft,hybRight,sum_spin,exchangeNumerator_eq_table,exchangeTable, + mul_zero,zero_mul,zero_add,add_zero] + +theorem hyb_entry_15_17 (x y z : ℂ) : + hybLeft x y z .plus .minus .zero .plus .minus .minus = hybRight x y z .plus .minus .zero .plus .minus .minus := by + simp only [hybLeft,hybRight,sum_spin,exchangeNumerator_eq_table,exchangeTable, + mul_zero,zero_mul,zero_add,add_zero] + +theorem hyb_entry_15_18 (x y z : ℂ) : + hybLeft x y z .plus .minus .zero .minus .zero .zero = hybRight x y z .plus .minus .zero .minus .zero .zero := by + simp only [hybLeft,hybRight,sum_spin,exchangeNumerator_eq_table,exchangeTable, + mul_zero,zero_mul,zero_add,add_zero] + +theorem hyb_entry_15_19 (x y z : ℂ) : + hybLeft x y z .plus .minus .zero .minus .zero .plus = hybRight x y z .plus .minus .zero .minus .zero .plus := by + simp only [hybLeft,hybRight,sum_spin,exchangeNumerator_eq_table,exchangeTable, + mul_zero,zero_mul,zero_add,add_zero] + all_goals ring_nf + all_goals try simp only [q_pow_eight,q_pow_10,q_pow_12,q_pow_14] + all_goals ring + +theorem hyb_entry_15_20 (x y z : ℂ) : + hybLeft x y z .plus .minus .zero .minus .zero .minus = hybRight x y z .plus .minus .zero .minus .zero .minus := by + simp only [hybLeft,hybRight,sum_spin,exchangeNumerator_eq_table,exchangeTable, + mul_zero,zero_mul,zero_add,add_zero] + +theorem hyb_entry_15_21 (x y z : ℂ) : + hybLeft x y z .plus .minus .zero .minus .plus .zero = hybRight x y z .plus .minus .zero .minus .plus .zero := by + simp only [hybLeft,hybRight,sum_spin,exchangeNumerator_eq_table,exchangeTable, + mul_zero,zero_mul,zero_add,add_zero] + all_goals ring_nf + all_goals try simp only [q_pow_eight,q_pow_10,q_pow_12,q_pow_14,q_pow_16,q_pow_18] + all_goals ring + +theorem hyb_entry_15_22 (x y z : ℂ) : + hybLeft x y z .plus .minus .zero .minus .plus .plus = hybRight x y z .plus .minus .zero .minus .plus .plus := by + simp only [hybLeft,hybRight,sum_spin,exchangeNumerator_eq_table,exchangeTable, + mul_zero,zero_mul,zero_add,add_zero] + +theorem hyb_entry_15_23 (x y z : ℂ) : + hybLeft x y z .plus .minus .zero .minus .plus .minus = hybRight x y z .plus .minus .zero .minus .plus .minus := by + simp only [hybLeft,hybRight,sum_spin,exchangeNumerator_eq_table,exchangeTable, + mul_zero,zero_mul,zero_add,add_zero] + +theorem hyb_entry_15_24 (x y z : ℂ) : + hybLeft x y z .plus .minus .zero .minus .minus .zero = hybRight x y z .plus .minus .zero .minus .minus .zero := by + simp only [hybLeft,hybRight,sum_spin,exchangeNumerator_eq_table,exchangeTable, + mul_zero,zero_mul,zero_add,add_zero] + +theorem hyb_entry_15_25 (x y z : ℂ) : + hybLeft x y z .plus .minus .zero .minus .minus .plus = hybRight x y z .plus .minus .zero .minus .minus .plus := by + simp only [hybLeft,hybRight,sum_spin,exchangeNumerator_eq_table,exchangeTable, + mul_zero,zero_mul,zero_add,add_zero] + +theorem hyb_entry_15_26 (x y z : ℂ) : + hybLeft x y z .plus .minus .zero .minus .minus .minus = hybRight x y z .plus .minus .zero .minus .minus .minus := by + simp only [hybLeft,hybRight,sum_spin,exchangeNumerator_eq_table,exchangeTable, + mul_zero,zero_mul,zero_add,add_zero] + +theorem hyb_entry_16_0 (x y z : ℂ) : + hybLeft x y z .plus .minus .plus .zero .zero .zero = hybRight x y z .plus .minus .plus .zero .zero .zero := by + simp only [hybLeft,hybRight,sum_spin,exchangeNumerator_eq_table,exchangeTable, + mul_zero,zero_mul,zero_add,add_zero] + +theorem hyb_entry_16_1 (x y z : ℂ) : + hybLeft x y z .plus .minus .plus .zero .zero .plus = hybRight x y z .plus .minus .plus .zero .zero .plus := by + simp only [hybLeft,hybRight,sum_spin,exchangeNumerator_eq_table,exchangeTable, + mul_zero,zero_mul,zero_add,add_zero] + all_goals ring_nf + all_goals try simp only [q_pow_9,q_pow_11,q_pow_13,q_pow_15,q_pow_17] + all_goals ring + +theorem hyb_entry_16_2 (x y z : ℂ) : + hybLeft x y z .plus .minus .plus .zero .zero .minus = hybRight x y z .plus .minus .plus .zero .zero .minus := by + simp only [hybLeft,hybRight,sum_spin,exchangeNumerator_eq_table,exchangeTable, + mul_zero,zero_mul,zero_add,add_zero] + +theorem hyb_entry_16_3 (x y z : ℂ) : + hybLeft x y z .plus .minus .plus .zero .plus .zero = hybRight x y z .plus .minus .plus .zero .plus .zero := by + simp only [hybLeft,hybRight,sum_spin,exchangeNumerator_eq_table,exchangeTable, + mul_zero,zero_mul,zero_add,add_zero] + all_goals ring_nf + all_goals try simp only [q_pow_9,q_pow_11,q_pow_13] + all_goals ring + +theorem hyb_entry_16_4 (x y z : ℂ) : + hybLeft x y z .plus .minus .plus .zero .plus .plus = hybRight x y z .plus .minus .plus .zero .plus .plus := by + simp only [hybLeft,hybRight,sum_spin,exchangeNumerator_eq_table,exchangeTable, + mul_zero,zero_mul,zero_add,add_zero] + +theorem hyb_entry_16_5 (x y z : ℂ) : + hybLeft x y z .plus .minus .plus .zero .plus .minus = hybRight x y z .plus .minus .plus .zero .plus .minus := by + simp only [hybLeft,hybRight,sum_spin,exchangeNumerator_eq_table,exchangeTable, + mul_zero,zero_mul,zero_add,add_zero] + +theorem hyb_entry_16_6 (x y z : ℂ) : + hybLeft x y z .plus .minus .plus .zero .minus .zero = hybRight x y z .plus .minus .plus .zero .minus .zero := by + simp only [hybLeft,hybRight,sum_spin,exchangeNumerator_eq_table,exchangeTable, + mul_zero,zero_mul,zero_add,add_zero] + +theorem hyb_entry_16_7 (x y z : ℂ) : + hybLeft x y z .plus .minus .plus .zero .minus .plus = hybRight x y z .plus .minus .plus .zero .minus .plus := by + simp only [hybLeft,hybRight,sum_spin,exchangeNumerator_eq_table,exchangeTable, + mul_zero,zero_mul,zero_add,add_zero] + +theorem hyb_entry_16_8 (x y z : ℂ) : + hybLeft x y z .plus .minus .plus .zero .minus .minus = hybRight x y z .plus .minus .plus .zero .minus .minus := by + simp only [hybLeft,hybRight,sum_spin,exchangeNumerator_eq_table,exchangeTable, + mul_zero,zero_mul,zero_add,add_zero] + +theorem hyb_entry_16_9 (x y z : ℂ) : + hybLeft x y z .plus .minus .plus .plus .zero .zero = hybRight x y z .plus .minus .plus .plus .zero .zero := by + simp only [hybLeft,hybRight,sum_spin,exchangeNumerator_eq_table,exchangeTable, + mul_zero,zero_mul,zero_add,add_zero] + all_goals ring_nf + all_goals try simp only [q_pow_9,q_pow_11,q_pow_13,q_pow_15,q_pow_17] + all_goals ring + +theorem hyb_entry_16_10 (x y z : ℂ) : + hybLeft x y z .plus .minus .plus .plus .zero .plus = hybRight x y z .plus .minus .plus .plus .zero .plus := by + simp only [hybLeft,hybRight,sum_spin,exchangeNumerator_eq_table,exchangeTable, + mul_zero,zero_mul,zero_add,add_zero] + +theorem hyb_entry_16_11 (x y z : ℂ) : + hybLeft x y z .plus .minus .plus .plus .zero .minus = hybRight x y z .plus .minus .plus .plus .zero .minus := by + simp only [hybLeft,hybRight,sum_spin,exchangeNumerator_eq_table,exchangeTable, + mul_zero,zero_mul,zero_add,add_zero] + +theorem hyb_entry_16_12 (x y z : ℂ) : + hybLeft x y z .plus .minus .plus .plus .plus .zero = hybRight x y z .plus .minus .plus .plus .plus .zero := by + simp only [hybLeft,hybRight,sum_spin,exchangeNumerator_eq_table,exchangeTable, + mul_zero,zero_mul,zero_add,add_zero] + +theorem hyb_entry_16_13 (x y z : ℂ) : + hybLeft x y z .plus .minus .plus .plus .plus .plus = hybRight x y z .plus .minus .plus .plus .plus .plus := by + simp only [hybLeft,hybRight,sum_spin,exchangeNumerator_eq_table,exchangeTable, + mul_zero,zero_mul,zero_add,add_zero] + +theorem hyb_entry_16_14 (x y z : ℂ) : + hybLeft x y z .plus .minus .plus .plus .plus .minus = hybRight x y z .plus .minus .plus .plus .plus .minus := by + simp only [hybLeft,hybRight,sum_spin,exchangeNumerator_eq_table,exchangeTable, + mul_zero,zero_mul,zero_add,add_zero] + all_goals ring_nf + all_goals try simp only [q_pow_eight,q_pow_10,q_pow_12,q_pow_14,q_pow_16,q_pow_18] + all_goals ring + +theorem hyb_entry_16_15 (x y z : ℂ) : + hybLeft x y z .plus .minus .plus .plus .minus .zero = hybRight x y z .plus .minus .plus .plus .minus .zero := by + simp only [hybLeft,hybRight,sum_spin,exchangeNumerator_eq_table,exchangeTable, + mul_zero,zero_mul,zero_add,add_zero] + +theorem hyb_entry_16_16 (x y z : ℂ) : + hybLeft x y z .plus .minus .plus .plus .minus .plus = hybRight x y z .plus .minus .plus .plus .minus .plus := by + simp only [hybLeft,hybRight,sum_spin,exchangeNumerator_eq_table,exchangeTable, + mul_zero,zero_mul,zero_add,add_zero] + all_goals ring_nf + all_goals try simp only [q_pow_eight,q_pow_10,q_pow_12,q_pow_14,q_pow_16,q_pow_18] + all_goals ring + +theorem hyb_entry_16_17 (x y z : ℂ) : + hybLeft x y z .plus .minus .plus .plus .minus .minus = hybRight x y z .plus .minus .plus .plus .minus .minus := by + simp only [hybLeft,hybRight,sum_spin,exchangeNumerator_eq_table,exchangeTable, + mul_zero,zero_mul,zero_add,add_zero] + +theorem hyb_entry_16_18 (x y z : ℂ) : + hybLeft x y z .plus .minus .plus .minus .zero .zero = hybRight x y z .plus .minus .plus .minus .zero .zero := by + simp only [hybLeft,hybRight,sum_spin,exchangeNumerator_eq_table,exchangeTable, + mul_zero,zero_mul,zero_add,add_zero] + +theorem hyb_entry_16_19 (x y z : ℂ) : + hybLeft x y z .plus .minus .plus .minus .zero .plus = hybRight x y z .plus .minus .plus .minus .zero .plus := by + simp only [hybLeft,hybRight,sum_spin,exchangeNumerator_eq_table,exchangeTable, + mul_zero,zero_mul,zero_add,add_zero] + +theorem hyb_entry_16_20 (x y z : ℂ) : + hybLeft x y z .plus .minus .plus .minus .zero .minus = hybRight x y z .plus .minus .plus .minus .zero .minus := by + simp only [hybLeft,hybRight,sum_spin,exchangeNumerator_eq_table,exchangeTable, + mul_zero,zero_mul,add_zero] + +theorem hyb_entry_16_21 (x y z : ℂ) : + hybLeft x y z .plus .minus .plus .minus .plus .zero = hybRight x y z .plus .minus .plus .minus .plus .zero := by + simp only [hybLeft,hybRight,sum_spin,exchangeNumerator_eq_table,exchangeTable, + mul_zero,zero_mul,zero_add,add_zero] + +theorem hyb_entry_16_22 (x y z : ℂ) : + hybLeft x y z .plus .minus .plus .minus .plus .plus = hybRight x y z .plus .minus .plus .minus .plus .plus := by + simp only [hybLeft,hybRight,sum_spin,exchangeNumerator_eq_table,exchangeTable, + mul_zero,zero_mul,zero_add,add_zero] + all_goals ring_nf + all_goals try simp only [q_pow_eight,q_pow_10,q_pow_12,q_pow_14,q_pow_16,q_pow_18] + all_goals ring + +theorem hyb_entry_16_23 (x y z : ℂ) : + hybLeft x y z .plus .minus .plus .minus .plus .minus = hybRight x y z .plus .minus .plus .minus .plus .minus := by + simp only [hybLeft,hybRight,sum_spin,exchangeNumerator_eq_table,exchangeTable, + mul_zero,zero_mul,zero_add,add_zero] + +theorem hyb_entry_16_24 (x y z : ℂ) : + hybLeft x y z .plus .minus .plus .minus .minus .zero = hybRight x y z .plus .minus .plus .minus .minus .zero := by + simp only [hybLeft,hybRight,sum_spin,exchangeNumerator_eq_table,exchangeTable, + mul_zero,zero_mul,add_zero] + +theorem hyb_entry_16_25 (x y z : ℂ) : + hybLeft x y z .plus .minus .plus .minus .minus .plus = hybRight x y z .plus .minus .plus .minus .minus .plus := by + simp only [hybLeft,hybRight,sum_spin,exchangeNumerator_eq_table,exchangeTable, + mul_zero,zero_mul,zero_add,add_zero] + +theorem hyb_entry_16_26 (x y z : ℂ) : + hybLeft x y z .plus .minus .plus .minus .minus .minus = hybRight x y z .plus .minus .plus .minus .minus .minus := by + simp only [hybLeft,hybRight,sum_spin,exchangeNumerator_eq_table,exchangeTable, + mul_zero,zero_mul,zero_add,add_zero] + +theorem hyb_entry_17_0 (x y z : ℂ) : + hybLeft x y z .plus .minus .minus .zero .zero .zero = hybRight x y z .plus .minus .minus .zero .zero .zero := by + simp only [hybLeft,hybRight,sum_spin,exchangeNumerator_eq_table,exchangeTable, + mul_zero,zero_mul,zero_add,add_zero] + +theorem hyb_entry_17_1 (x y z : ℂ) : + hybLeft x y z .plus .minus .minus .zero .zero .plus = hybRight x y z .plus .minus .minus .zero .zero .plus := by + simp only [hybLeft,hybRight,sum_spin,exchangeNumerator_eq_table,exchangeTable, + mul_zero,zero_mul,zero_add,add_zero] + +theorem hyb_entry_17_2 (x y z : ℂ) : + hybLeft x y z .plus .minus .minus .zero .zero .minus = hybRight x y z .plus .minus .minus .zero .zero .minus := by + simp only [hybLeft,hybRight,sum_spin,exchangeNumerator_eq_table,exchangeTable, + mul_zero,zero_mul,zero_add,add_zero] + all_goals ring_nf + all_goals try simp only [q_pow_9,q_pow_11,q_pow_13,q_pow_15,q_pow_17] + all_goals ring + +theorem hyb_entry_17_3 (x y z : ℂ) : + hybLeft x y z .plus .minus .minus .zero .plus .zero = hybRight x y z .plus .minus .minus .zero .plus .zero := by + simp only [hybLeft,hybRight,sum_spin,exchangeNumerator_eq_table,exchangeTable, + mul_zero,zero_mul,zero_add,add_zero] + +theorem hyb_entry_17_4 (x y z : ℂ) : + hybLeft x y z .plus .minus .minus .zero .plus .plus = hybRight x y z .plus .minus .minus .zero .plus .plus := by + simp only [hybLeft,hybRight,sum_spin,exchangeNumerator_eq_table,exchangeTable, + mul_zero,zero_mul,add_zero] + +theorem hyb_entry_17_5 (x y z : ℂ) : + hybLeft x y z .plus .minus .minus .zero .plus .minus = hybRight x y z .plus .minus .minus .zero .plus .minus := by + simp only [hybLeft,hybRight,sum_spin,exchangeNumerator_eq_table,exchangeTable, + mul_zero,zero_mul,zero_add,add_zero] + +theorem hyb_entry_17_6 (x y z : ℂ) : + hybLeft x y z .plus .minus .minus .zero .minus .zero = hybRight x y z .plus .minus .minus .zero .minus .zero := by + simp only [hybLeft,hybRight,sum_spin,exchangeNumerator_eq_table,exchangeTable, + mul_zero,zero_mul,zero_add,add_zero] + all_goals ring_nf + all_goals try simp only [q_pow_9,q_pow_11,q_pow_13] + all_goals ring + +theorem hyb_entry_17_7 (x y z : ℂ) : + hybLeft x y z .plus .minus .minus .zero .minus .plus = hybRight x y z .plus .minus .minus .zero .minus .plus := by + simp only [hybLeft,hybRight,sum_spin,exchangeNumerator_eq_table,exchangeTable, + mul_zero,zero_mul,zero_add,add_zero] + +theorem hyb_entry_17_8 (x y z : ℂ) : + hybLeft x y z .plus .minus .minus .zero .minus .minus = hybRight x y z .plus .minus .minus .zero .minus .minus := by + simp only [hybLeft,hybRight,sum_spin,exchangeNumerator_eq_table,exchangeTable, + mul_zero,zero_mul,zero_add,add_zero] + +theorem hyb_entry_17_9 (x y z : ℂ) : + hybLeft x y z .plus .minus .minus .plus .zero .zero = hybRight x y z .plus .minus .minus .plus .zero .zero := by + simp only [hybLeft,hybRight,sum_spin,exchangeNumerator_eq_table,exchangeTable, + mul_zero,zero_mul,zero_add,add_zero] + +theorem hyb_entry_17_10 (x y z : ℂ) : + hybLeft x y z .plus .minus .minus .plus .zero .plus = hybRight x y z .plus .minus .minus .plus .zero .plus := by + simp only [hybLeft,hybRight,sum_spin,exchangeNumerator_eq_table,exchangeTable, + mul_zero,zero_mul,add_zero] + +theorem hyb_entry_17_11 (x y z : ℂ) : + hybLeft x y z .plus .minus .minus .plus .zero .minus = hybRight x y z .plus .minus .minus .plus .zero .minus := by + simp only [hybLeft,hybRight,sum_spin,exchangeNumerator_eq_table,exchangeTable, + mul_zero,zero_mul,zero_add,add_zero] + +theorem hyb_entry_17_12 (x y z : ℂ) : + hybLeft x y z .plus .minus .minus .plus .plus .zero = hybRight x y z .plus .minus .minus .plus .plus .zero := by + simp only [hybLeft,hybRight,sum_spin,exchangeNumerator_eq_table,exchangeTable, + mul_zero,zero_mul,add_zero] + +theorem hyb_entry_17_13 (x y z : ℂ) : + hybLeft x y z .plus .minus .minus .plus .plus .plus = hybRight x y z .plus .minus .minus .plus .plus .plus := by + simp only [hybLeft,hybRight,sum_spin,exchangeNumerator_eq_table,exchangeTable, + mul_zero,zero_mul,add_zero] + +theorem hyb_entry_17_14 (x y z : ℂ) : + hybLeft x y z .plus .minus .minus .plus .plus .minus = hybRight x y z .plus .minus .minus .plus .plus .minus := by + simp only [hybLeft,hybRight,sum_spin,exchangeNumerator_eq_table,exchangeTable, + mul_zero,zero_mul,zero_add,add_zero] + +theorem hyb_entry_17_15 (x y z : ℂ) : + hybLeft x y z .plus .minus .minus .plus .minus .zero = hybRight x y z .plus .minus .minus .plus .minus .zero := by + simp only [hybLeft,hybRight,sum_spin,exchangeNumerator_eq_table,exchangeTable, + mul_zero,zero_mul,zero_add,add_zero] + +theorem hyb_entry_17_16 (x y z : ℂ) : + hybLeft x y z .plus .minus .minus .plus .minus .plus = hybRight x y z .plus .minus .minus .plus .minus .plus := by + simp only [hybLeft,hybRight,sum_spin,exchangeNumerator_eq_table,exchangeTable, + mul_zero,zero_mul,zero_add,add_zero] + +theorem hyb_entry_17_17 (x y z : ℂ) : + hybLeft x y z .plus .minus .minus .plus .minus .minus = hybRight x y z .plus .minus .minus .plus .minus .minus := by + simp only [hybLeft,hybRight,sum_spin,exchangeNumerator_eq_table,exchangeTable, + mul_zero,zero_mul,zero_add,add_zero] + all_goals ring_nf + all_goals try simp only [q_pow_eight,q_pow_10,q_pow_12,q_pow_14,q_pow_16,q_pow_18] + all_goals ring + +theorem hyb_entry_17_18 (x y z : ℂ) : + hybLeft x y z .plus .minus .minus .minus .zero .zero = hybRight x y z .plus .minus .minus .minus .zero .zero := by + simp only [hybLeft,hybRight,sum_spin,exchangeNumerator_eq_table,exchangeTable, + mul_zero,zero_mul,zero_add,add_zero] + all_goals ring_nf + all_goals try simp only [q_pow_9,q_pow_11,q_pow_13,q_pow_15,q_pow_17] + all_goals ring + +theorem hyb_entry_17_19 (x y z : ℂ) : + hybLeft x y z .plus .minus .minus .minus .zero .plus = hybRight x y z .plus .minus .minus .minus .zero .plus := by + simp only [hybLeft,hybRight,sum_spin,exchangeNumerator_eq_table,exchangeTable, + mul_zero,zero_mul,zero_add,add_zero] + +theorem hyb_entry_17_20 (x y z : ℂ) : + hybLeft x y z .plus .minus .minus .minus .zero .minus = hybRight x y z .plus .minus .minus .minus .zero .minus := by + simp only [hybLeft,hybRight,sum_spin,exchangeNumerator_eq_table,exchangeTable, + mul_zero,zero_mul,zero_add,add_zero] + +theorem hyb_entry_17_21 (x y z : ℂ) : + hybLeft x y z .plus .minus .minus .minus .plus .zero = hybRight x y z .plus .minus .minus .minus .plus .zero := by + simp only [hybLeft,hybRight,sum_spin,exchangeNumerator_eq_table,exchangeTable, + mul_zero,zero_mul,zero_add,add_zero] + +theorem hyb_entry_17_22 (x y z : ℂ) : + hybLeft x y z .plus .minus .minus .minus .plus .plus = hybRight x y z .plus .minus .minus .minus .plus .plus := by + simp only [hybLeft,hybRight,sum_spin,exchangeNumerator_eq_table,exchangeTable, + mul_zero,zero_mul,zero_add,add_zero] + +theorem hyb_entry_17_23 (x y z : ℂ) : + hybLeft x y z .plus .minus .minus .minus .plus .minus = hybRight x y z .plus .minus .minus .minus .plus .minus := by + simp only [hybLeft,hybRight,sum_spin,exchangeNumerator_eq_table,exchangeTable, + mul_zero,zero_mul,zero_add,add_zero] + all_goals ring_nf + all_goals try simp only [q_pow_eight,q_pow_10,q_pow_12,q_pow_14,q_pow_16,q_pow_18] + all_goals ring + +theorem hyb_entry_17_24 (x y z : ℂ) : + hybLeft x y z .plus .minus .minus .minus .minus .zero = hybRight x y z .plus .minus .minus .minus .minus .zero := by + simp only [hybLeft,hybRight,sum_spin,exchangeNumerator_eq_table,exchangeTable, + mul_zero,zero_mul,zero_add,add_zero] + +theorem hyb_entry_17_25 (x y z : ℂ) : + hybLeft x y z .plus .minus .minus .minus .minus .plus = hybRight x y z .plus .minus .minus .minus .minus .plus := by + simp only [hybLeft,hybRight,sum_spin,exchangeNumerator_eq_table,exchangeTable, + mul_zero,zero_mul,zero_add,add_zero] + all_goals ring_nf + +theorem hyb_entry_17_26 (x y z : ℂ) : + hybLeft x y z .plus .minus .minus .minus .minus .minus = hybRight x y z .plus .minus .minus .minus .minus .minus := by + simp only [hybLeft,hybRight,sum_spin,exchangeNumerator_eq_table,exchangeTable, + mul_zero,zero_mul,zero_add,add_zero] + +theorem hyb_entry_18_0 (x y z : ℂ) : + hybLeft x y z .minus .zero .zero .zero .zero .zero = hybRight x y z .minus .zero .zero .zero .zero .zero := by + simp only [hybLeft,hybRight,sum_spin,exchangeNumerator_eq_table,exchangeTable, + mul_zero,zero_mul,zero_add,add_zero] + +theorem hyb_entry_18_1 (x y z : ℂ) : + hybLeft x y z .minus .zero .zero .zero .zero .plus = hybRight x y z .minus .zero .zero .zero .zero .plus := by + simp only [hybLeft,hybRight,sum_spin,exchangeNumerator_eq_table,exchangeTable, + mul_zero,zero_mul,zero_add,add_zero] + +theorem hyb_entry_18_2 (x y z : ℂ) : + hybLeft x y z .minus .zero .zero .zero .zero .minus = hybRight x y z .minus .zero .zero .zero .zero .minus := by + simp only [hybLeft,hybRight,sum_spin,exchangeNumerator_eq_table,exchangeTable, + mul_zero,zero_mul,zero_add,add_zero] + all_goals ring_nf + +theorem hyb_entry_18_3 (x y z : ℂ) : + hybLeft x y z .minus .zero .zero .zero .plus .zero = hybRight x y z .minus .zero .zero .zero .plus .zero := by + simp only [hybLeft,hybRight,sum_spin,exchangeNumerator_eq_table,exchangeTable, + mul_zero,zero_mul,add_zero] + +theorem hyb_entry_18_4 (x y z : ℂ) : + hybLeft x y z .minus .zero .zero .zero .plus .plus = hybRight x y z .minus .zero .zero .zero .plus .plus := by + simp only [hybLeft,hybRight,sum_spin,exchangeNumerator_eq_table,exchangeTable, + mul_zero,zero_mul,zero_add,add_zero] + +theorem hyb_entry_18_5 (x y z : ℂ) : + hybLeft x y z .minus .zero .zero .zero .plus .minus = hybRight x y z .minus .zero .zero .zero .plus .minus := by + simp only [hybLeft,hybRight,sum_spin,exchangeNumerator_eq_table,exchangeTable, + mul_zero,zero_mul,zero_add,add_zero] + +theorem hyb_entry_18_6 (x y z : ℂ) : + hybLeft x y z .minus .zero .zero .zero .minus .zero = hybRight x y z .minus .zero .zero .zero .minus .zero := by + simp only [hybLeft,hybRight,sum_spin,exchangeNumerator_eq_table,exchangeTable, + mul_zero,zero_mul,zero_add,add_zero] + all_goals ring_nf + all_goals try simp only [q_pow_eight,q_pow_10,q_pow_12,q_pow_14] + all_goals ring + +theorem hyb_entry_18_7 (x y z : ℂ) : + hybLeft x y z .minus .zero .zero .zero .minus .plus = hybRight x y z .minus .zero .zero .zero .minus .plus := by + simp only [hybLeft,hybRight,sum_spin,exchangeNumerator_eq_table,exchangeTable, + mul_zero,zero_mul,zero_add,add_zero] + +theorem hyb_entry_18_8 (x y z : ℂ) : + hybLeft x y z .minus .zero .zero .zero .minus .minus = hybRight x y z .minus .zero .zero .zero .minus .minus := by + simp only [hybLeft,hybRight,sum_spin,exchangeNumerator_eq_table,exchangeTable, + mul_zero,zero_mul,zero_add,add_zero] + +theorem hyb_entry_18_9 (x y z : ℂ) : + hybLeft x y z .minus .zero .zero .plus .zero .zero = hybRight x y z .minus .zero .zero .plus .zero .zero := by + simp only [hybLeft,hybRight,sum_spin,exchangeNumerator_eq_table,exchangeTable, + mul_zero,zero_mul,zero_add,add_zero] + +theorem hyb_entry_18_10 (x y z : ℂ) : + hybLeft x y z .minus .zero .zero .plus .zero .plus = hybRight x y z .minus .zero .zero .plus .zero .plus := by + simp only [hybLeft,hybRight,sum_spin,exchangeNumerator_eq_table,exchangeTable, + mul_zero,zero_mul,add_zero] + +theorem hyb_entry_18_11 (x y z : ℂ) : + hybLeft x y z .minus .zero .zero .plus .zero .minus = hybRight x y z .minus .zero .zero .plus .zero .minus := by + simp only [hybLeft,hybRight,sum_spin,exchangeNumerator_eq_table,exchangeTable, + mul_zero,zero_mul,zero_add,add_zero] + +theorem hyb_entry_18_12 (x y z : ℂ) : + hybLeft x y z .minus .zero .zero .plus .plus .zero = hybRight x y z .minus .zero .zero .plus .plus .zero := by + simp only [hybLeft,hybRight,sum_spin,exchangeNumerator_eq_table,exchangeTable, + mul_zero,zero_mul,zero_add,add_zero] + +theorem hyb_entry_18_13 (x y z : ℂ) : + hybLeft x y z .minus .zero .zero .plus .plus .plus = hybRight x y z .minus .zero .zero .plus .plus .plus := by + simp only [hybLeft,hybRight,sum_spin,exchangeNumerator_eq_table,exchangeTable, + mul_zero,zero_mul,zero_add,add_zero] + +theorem hyb_entry_18_14 (x y z : ℂ) : + hybLeft x y z .minus .zero .zero .plus .plus .minus = hybRight x y z .minus .zero .zero .plus .plus .minus := by + simp only [hybLeft,hybRight,sum_spin,exchangeNumerator_eq_table,exchangeTable, + mul_zero,zero_mul,zero_add,add_zero] + +theorem hyb_entry_18_15 (x y z : ℂ) : + hybLeft x y z .minus .zero .zero .plus .minus .zero = hybRight x y z .minus .zero .zero .plus .minus .zero := by + simp only [hybLeft,hybRight,sum_spin,exchangeNumerator_eq_table,exchangeTable, + mul_zero,zero_mul,zero_add,add_zero] + +theorem hyb_entry_18_16 (x y z : ℂ) : + hybLeft x y z .minus .zero .zero .plus .minus .plus = hybRight x y z .minus .zero .zero .plus .minus .plus := by + simp only [hybLeft,hybRight,sum_spin,exchangeNumerator_eq_table,exchangeTable, + mul_zero,zero_mul,zero_add,add_zero] + +theorem hyb_entry_18_17 (x y z : ℂ) : + hybLeft x y z .minus .zero .zero .plus .minus .minus = hybRight x y z .minus .zero .zero .plus .minus .minus := by + simp only [hybLeft,hybRight,sum_spin,exchangeNumerator_eq_table,exchangeTable, + mul_zero,zero_mul,zero_add,add_zero] + all_goals ring_nf + all_goals try simp only [q_pow_9,q_pow_11,q_pow_13,q_pow_15,q_pow_17] + all_goals ring + +theorem hyb_entry_18_18 (x y z : ℂ) : + hybLeft x y z .minus .zero .zero .minus .zero .zero = hybRight x y z .minus .zero .zero .minus .zero .zero := by + simp only [hybLeft,hybRight,sum_spin,exchangeNumerator_eq_table,exchangeTable, + mul_zero,zero_mul,zero_add,add_zero] + all_goals ring_nf + all_goals try simp only [q_pow_eight,q_pow_10,q_pow_12,q_pow_14,q_pow_16,q_pow_18] + all_goals ring + +theorem hyb_entry_18_19 (x y z : ℂ) : + hybLeft x y z .minus .zero .zero .minus .zero .plus = hybRight x y z .minus .zero .zero .minus .zero .plus := by + simp only [hybLeft,hybRight,sum_spin,exchangeNumerator_eq_table,exchangeTable, + mul_zero,zero_mul,zero_add,add_zero] + +theorem hyb_entry_18_20 (x y z : ℂ) : + hybLeft x y z .minus .zero .zero .minus .zero .minus = hybRight x y z .minus .zero .zero .minus .zero .minus := by + simp only [hybLeft,hybRight,sum_spin,exchangeNumerator_eq_table,exchangeTable, + mul_zero,zero_mul,zero_add,add_zero] + +theorem hyb_entry_18_21 (x y z : ℂ) : + hybLeft x y z .minus .zero .zero .minus .plus .zero = hybRight x y z .minus .zero .zero .minus .plus .zero := by + simp only [hybLeft,hybRight,sum_spin,exchangeNumerator_eq_table,exchangeTable, + mul_zero,zero_mul,zero_add,add_zero] + +theorem hyb_entry_18_22 (x y z : ℂ) : + hybLeft x y z .minus .zero .zero .minus .plus .plus = hybRight x y z .minus .zero .zero .minus .plus .plus := by + simp only [hybLeft,hybRight,sum_spin,exchangeNumerator_eq_table,exchangeTable, + mul_zero,zero_mul,zero_add,add_zero] + +theorem hyb_entry_18_23 (x y z : ℂ) : + hybLeft x y z .minus .zero .zero .minus .plus .minus = hybRight x y z .minus .zero .zero .minus .plus .minus := by + simp only [hybLeft,hybRight,sum_spin,exchangeNumerator_eq_table,exchangeTable, + mul_zero,zero_mul,zero_add,add_zero] + all_goals ring_nf + all_goals try simp only [q_pow_9,q_pow_11,q_pow_13,q_pow_15,q_pow_17] + all_goals ring + +theorem hyb_entry_18_24 (x y z : ℂ) : + hybLeft x y z .minus .zero .zero .minus .minus .zero = hybRight x y z .minus .zero .zero .minus .minus .zero := by + simp only [hybLeft,hybRight,sum_spin,exchangeNumerator_eq_table,exchangeTable, + mul_zero,zero_mul,zero_add,add_zero] + +theorem hyb_entry_18_25 (x y z : ℂ) : + hybLeft x y z .minus .zero .zero .minus .minus .plus = hybRight x y z .minus .zero .zero .minus .minus .plus := by + simp only [hybLeft,hybRight,sum_spin,exchangeNumerator_eq_table,exchangeTable, + mul_zero,zero_mul,zero_add,add_zero] + all_goals ring_nf + all_goals try simp only [q_pow_9,q_pow_11,q_pow_13,q_pow_15,q_pow_17] + all_goals ring + +theorem hyb_entry_18_26 (x y z : ℂ) : + hybLeft x y z .minus .zero .zero .minus .minus .minus = hybRight x y z .minus .zero .zero .minus .minus .minus := by + simp only [hybLeft,hybRight,sum_spin,exchangeNumerator_eq_table,exchangeTable, + mul_zero,zero_mul,zero_add,add_zero] + +theorem hyb_entry_19_0 (x y z : ℂ) : + hybLeft x y z .minus .zero .plus .zero .zero .zero = hybRight x y z .minus .zero .plus .zero .zero .zero := by + simp only [hybLeft,hybRight,sum_spin,exchangeNumerator_eq_table,exchangeTable, + mul_zero,zero_mul,zero_add,add_zero] + all_goals ring_nf + +theorem hyb_entry_19_1 (x y z : ℂ) : + hybLeft x y z .minus .zero .plus .zero .zero .plus = hybRight x y z .minus .zero .plus .zero .zero .plus := by + simp only [hybLeft,hybRight,sum_spin,exchangeNumerator_eq_table,exchangeTable, + mul_zero,zero_mul,zero_add,add_zero] + +theorem hyb_entry_19_2 (x y z : ℂ) : + hybLeft x y z .minus .zero .plus .zero .zero .minus = hybRight x y z .minus .zero .plus .zero .zero .minus := by + simp only [hybLeft,hybRight,sum_spin,exchangeNumerator_eq_table,exchangeTable, + mul_zero,zero_mul,zero_add,add_zero] + +theorem hyb_entry_19_3 (x y z : ℂ) : + hybLeft x y z .minus .zero .plus .zero .plus .zero = hybRight x y z .minus .zero .plus .zero .plus .zero := by + simp only [hybLeft,hybRight,sum_spin,exchangeNumerator_eq_table,exchangeTable, + mul_zero,zero_mul,zero_add,add_zero] + +theorem hyb_entry_19_4 (x y z : ℂ) : + hybLeft x y z .minus .zero .plus .zero .plus .plus = hybRight x y z .minus .zero .plus .zero .plus .plus := by + simp only [hybLeft,hybRight,sum_spin,exchangeNumerator_eq_table,exchangeTable, + mul_zero,zero_mul,zero_add,add_zero] + +theorem hyb_entry_19_5 (x y z : ℂ) : + hybLeft x y z .minus .zero .plus .zero .plus .minus = hybRight x y z .minus .zero .plus .zero .plus .minus := by + simp only [hybLeft,hybRight,sum_spin,exchangeNumerator_eq_table,exchangeTable, + mul_zero,zero_mul,zero_add,add_zero] + all_goals ring_nf + all_goals try simp only [q_pow_eight,q_pow_10,q_pow_12,q_pow_14] + all_goals ring + +theorem hyb_entry_19_6 (x y z : ℂ) : + hybLeft x y z .minus .zero .plus .zero .minus .zero = hybRight x y z .minus .zero .plus .zero .minus .zero := by + simp only [hybLeft,hybRight,sum_spin,exchangeNumerator_eq_table,exchangeTable, + mul_zero,zero_mul,zero_add,add_zero] + +theorem hyb_entry_19_7 (x y z : ℂ) : + hybLeft x y z .minus .zero .plus .zero .minus .plus = hybRight x y z .minus .zero .plus .zero .minus .plus := by + simp only [hybLeft,hybRight,sum_spin,exchangeNumerator_eq_table,exchangeTable, + mul_zero,zero_mul,zero_add,add_zero] + all_goals ring_nf + all_goals try simp only [q_pow_eight,q_pow_10,q_pow_12,q_pow_14] + all_goals ring + +theorem hyb_entry_19_8 (x y z : ℂ) : + hybLeft x y z .minus .zero .plus .zero .minus .minus = hybRight x y z .minus .zero .plus .zero .minus .minus := by + simp only [hybLeft,hybRight,sum_spin,exchangeNumerator_eq_table,exchangeTable, + mul_zero,zero_mul,add_zero] + +theorem hyb_entry_19_9 (x y z : ℂ) : + hybLeft x y z .minus .zero .plus .plus .zero .zero = hybRight x y z .minus .zero .plus .plus .zero .zero := by + simp only [hybLeft,hybRight,sum_spin,exchangeNumerator_eq_table,exchangeTable, + mul_zero,zero_mul,zero_add,add_zero] + +theorem hyb_entry_19_10 (x y z : ℂ) : + hybLeft x y z .minus .zero .plus .plus .zero .plus = hybRight x y z .minus .zero .plus .plus .zero .plus := by + simp only [hybLeft,hybRight,sum_spin,exchangeNumerator_eq_table,exchangeTable, + mul_zero,zero_mul,zero_add,add_zero] + +theorem hyb_entry_19_11 (x y z : ℂ) : + hybLeft x y z .minus .zero .plus .plus .zero .minus = hybRight x y z .minus .zero .plus .plus .zero .minus := by + simp only [hybLeft,hybRight,sum_spin,exchangeNumerator_eq_table,exchangeTable, + mul_zero,zero_mul,zero_add,add_zero] + all_goals ring_nf + +theorem hyb_entry_19_12 (x y z : ℂ) : + hybLeft x y z .minus .zero .plus .plus .plus .zero = hybRight x y z .minus .zero .plus .plus .plus .zero := by + simp only [hybLeft,hybRight,sum_spin,exchangeNumerator_eq_table,exchangeTable, + mul_zero,zero_mul,zero_add,add_zero] + +theorem hyb_entry_19_13 (x y z : ℂ) : + hybLeft x y z .minus .zero .plus .plus .plus .plus = hybRight x y z .minus .zero .plus .plus .plus .plus := by + simp only [hybLeft,hybRight,sum_spin,exchangeNumerator_eq_table,exchangeTable, + mul_zero,zero_mul,zero_add,add_zero] + +theorem hyb_entry_19_14 (x y z : ℂ) : + hybLeft x y z .minus .zero .plus .plus .plus .minus = hybRight x y z .minus .zero .plus .plus .plus .minus := by + simp only [hybLeft,hybRight,sum_spin,exchangeNumerator_eq_table,exchangeTable, + mul_zero,zero_mul,zero_add,add_zero] + +theorem hyb_entry_19_15 (x y z : ℂ) : + hybLeft x y z .minus .zero .plus .plus .minus .zero = hybRight x y z .minus .zero .plus .plus .minus .zero := by + simp only [hybLeft,hybRight,sum_spin,exchangeNumerator_eq_table,exchangeTable, + mul_zero,zero_mul,zero_add,add_zero] + all_goals ring_nf + all_goals try simp only [q_pow_eight,q_pow_10,q_pow_12,q_pow_14] + all_goals ring + +theorem hyb_entry_19_16 (x y z : ℂ) : + hybLeft x y z .minus .zero .plus .plus .minus .plus = hybRight x y z .minus .zero .plus .plus .minus .plus := by + simp only [hybLeft,hybRight,sum_spin,exchangeNumerator_eq_table,exchangeTable, + mul_zero,zero_mul,zero_add,add_zero] + +theorem hyb_entry_19_17 (x y z : ℂ) : + hybLeft x y z .minus .zero .plus .plus .minus .minus = hybRight x y z .minus .zero .plus .plus .minus .minus := by + simp only [hybLeft,hybRight,sum_spin,exchangeNumerator_eq_table,exchangeTable, + mul_zero,zero_mul,zero_add,add_zero] + +theorem hyb_entry_19_18 (x y z : ℂ) : + hybLeft x y z .minus .zero .plus .minus .zero .zero = hybRight x y z .minus .zero .plus .minus .zero .zero := by + simp only [hybLeft,hybRight,sum_spin,exchangeNumerator_eq_table,exchangeTable, + mul_zero,zero_mul,zero_add,add_zero] + +theorem hyb_entry_19_19 (x y z : ℂ) : + hybLeft x y z .minus .zero .plus .minus .zero .plus = hybRight x y z .minus .zero .plus .minus .zero .plus := by + simp only [hybLeft,hybRight,sum_spin,exchangeNumerator_eq_table,exchangeTable, + mul_zero,zero_mul,zero_add,add_zero] + all_goals ring_nf + +theorem hyb_entry_19_20 (x y z : ℂ) : + hybLeft x y z .minus .zero .plus .minus .zero .minus = hybRight x y z .minus .zero .plus .minus .zero .minus := by + simp only [hybLeft,hybRight,sum_spin,exchangeNumerator_eq_table,exchangeTable, + mul_zero,zero_mul,zero_add,add_zero] + +theorem hyb_entry_19_21 (x y z : ℂ) : + hybLeft x y z .minus .zero .plus .minus .plus .zero = hybRight x y z .minus .zero .plus .minus .plus .zero := by + simp only [hybLeft,hybRight,sum_spin,exchangeNumerator_eq_table,exchangeTable, + mul_zero,zero_mul,zero_add,add_zero] + all_goals ring_nf + all_goals try simp only [q_pow_eight,q_pow_10,q_pow_12,q_pow_14] + all_goals ring + +theorem hyb_entry_19_22 (x y z : ℂ) : + hybLeft x y z .minus .zero .plus .minus .plus .plus = hybRight x y z .minus .zero .plus .minus .plus .plus := by + simp only [hybLeft,hybRight,sum_spin,exchangeNumerator_eq_table,exchangeTable, + mul_zero,zero_mul,zero_add,add_zero] + +theorem hyb_entry_19_23 (x y z : ℂ) : + hybLeft x y z .minus .zero .plus .minus .plus .minus = hybRight x y z .minus .zero .plus .minus .plus .minus := by + simp only [hybLeft,hybRight,sum_spin,exchangeNumerator_eq_table,exchangeTable, + mul_zero,zero_mul,zero_add,add_zero] + +theorem hyb_entry_19_24 (x y z : ℂ) : + hybLeft x y z .minus .zero .plus .minus .minus .zero = hybRight x y z .minus .zero .plus .minus .minus .zero := by + simp only [hybLeft,hybRight,sum_spin,exchangeNumerator_eq_table,exchangeTable, + mul_zero,zero_mul,zero_add,add_zero] + +theorem hyb_entry_19_25 (x y z : ℂ) : + hybLeft x y z .minus .zero .plus .minus .minus .plus = hybRight x y z .minus .zero .plus .minus .minus .plus := by + simp only [hybLeft,hybRight,sum_spin,exchangeNumerator_eq_table,exchangeTable, + mul_zero,zero_mul,zero_add,add_zero] + +theorem hyb_entry_19_26 (x y z : ℂ) : + hybLeft x y z .minus .zero .plus .minus .minus .minus = hybRight x y z .minus .zero .plus .minus .minus .minus := by + simp only [hybLeft,hybRight,sum_spin,exchangeNumerator_eq_table,exchangeTable, + mul_zero,zero_mul,add_zero] + +theorem hyb_entry_20_0 (x y z : ℂ) : + hybLeft x y z .minus .zero .minus .zero .zero .zero = hybRight x y z .minus .zero .minus .zero .zero .zero := by + simp only [hybLeft,hybRight,sum_spin,exchangeNumerator_eq_table,exchangeTable, + mul_zero,zero_mul,zero_add,add_zero] + +theorem hyb_entry_20_1 (x y z : ℂ) : + hybLeft x y z .minus .zero .minus .zero .zero .plus = hybRight x y z .minus .zero .minus .zero .zero .plus := by + simp only [hybLeft,hybRight,sum_spin,exchangeNumerator_eq_table,exchangeTable, + mul_zero,zero_mul,zero_add,add_zero] + +theorem hyb_entry_20_2 (x y z : ℂ) : + hybLeft x y z .minus .zero .minus .zero .zero .minus = hybRight x y z .minus .zero .minus .zero .zero .minus := by + simp only [hybLeft,hybRight,sum_spin,exchangeNumerator_eq_table,exchangeTable, + mul_zero,zero_mul,zero_add,add_zero] + +theorem hyb_entry_20_3 (x y z : ℂ) : + hybLeft x y z .minus .zero .minus .zero .plus .zero = hybRight x y z .minus .zero .minus .zero .plus .zero := by + simp only [hybLeft,hybRight,sum_spin,exchangeNumerator_eq_table,exchangeTable, + mul_zero,zero_mul,add_zero] + +theorem hyb_entry_20_4 (x y z : ℂ) : + hybLeft x y z .minus .zero .minus .zero .plus .plus = hybRight x y z .minus .zero .minus .zero .plus .plus := by + simp only [hybLeft,hybRight,sum_spin,exchangeNumerator_eq_table,exchangeTable, + mul_zero,zero_mul,add_zero] + +theorem hyb_entry_20_5 (x y z : ℂ) : + hybLeft x y z .minus .zero .minus .zero .plus .minus = hybRight x y z .minus .zero .minus .zero .plus .minus := by + simp only [hybLeft,hybRight,sum_spin,exchangeNumerator_eq_table,exchangeTable, + mul_zero,zero_mul,zero_add,add_zero] + +theorem hyb_entry_20_6 (x y z : ℂ) : + hybLeft x y z .minus .zero .minus .zero .minus .zero = hybRight x y z .minus .zero .minus .zero .minus .zero := by + simp only [hybLeft,hybRight,sum_spin,exchangeNumerator_eq_table,exchangeTable, + mul_zero,zero_mul,zero_add,add_zero] + +theorem hyb_entry_20_7 (x y z : ℂ) : + hybLeft x y z .minus .zero .minus .zero .minus .plus = hybRight x y z .minus .zero .minus .zero .minus .plus := by + simp only [hybLeft,hybRight,sum_spin,exchangeNumerator_eq_table,exchangeTable, + mul_zero,zero_mul,zero_add,add_zero] + +theorem hyb_entry_20_8 (x y z : ℂ) : + hybLeft x y z .minus .zero .minus .zero .minus .minus = hybRight x y z .minus .zero .minus .zero .minus .minus := by + simp only [hybLeft,hybRight,sum_spin,exchangeNumerator_eq_table,exchangeTable, + mul_zero,zero_mul,zero_add,add_zero] + all_goals ring_nf + all_goals try simp only [q_pow_eight,q_pow_10,q_pow_12,q_pow_14] + all_goals ring + +theorem hyb_entry_20_9 (x y z : ℂ) : + hybLeft x y z .minus .zero .minus .plus .zero .zero = hybRight x y z .minus .zero .minus .plus .zero .zero := by + simp only [hybLeft,hybRight,sum_spin,exchangeNumerator_eq_table,exchangeTable, + mul_zero,zero_mul,add_zero] + +theorem hyb_entry_20_10 (x y z : ℂ) : + hybLeft x y z .minus .zero .minus .plus .zero .plus = hybRight x y z .minus .zero .minus .plus .zero .plus := by + simp only [hybLeft,hybRight,sum_spin,exchangeNumerator_eq_table,exchangeTable, + mul_zero,zero_mul,add_zero] + +theorem hyb_entry_20_11 (x y z : ℂ) : + hybLeft x y z .minus .zero .minus .plus .zero .minus = hybRight x y z .minus .zero .minus .plus .zero .minus := by + simp only [hybLeft,hybRight,sum_spin,exchangeNumerator_eq_table,exchangeTable, + mul_zero,zero_mul,add_zero] + +theorem hyb_entry_20_12 (x y z : ℂ) : + hybLeft x y z .minus .zero .minus .plus .plus .zero = hybRight x y z .minus .zero .minus .plus .plus .zero := by + simp only [hybLeft,hybRight,sum_spin,exchangeNumerator_eq_table,exchangeTable, + mul_zero,zero_mul,add_zero] + +theorem hyb_entry_20_13 (x y z : ℂ) : + hybLeft x y z .minus .zero .minus .plus .plus .plus = hybRight x y z .minus .zero .minus .plus .plus .plus := by + simp only [hybLeft,hybRight,sum_spin,exchangeNumerator_eq_table,exchangeTable, + mul_zero,zero_mul,add_zero] + +theorem hyb_entry_20_14 (x y z : ℂ) : + hybLeft x y z .minus .zero .minus .plus .plus .minus = hybRight x y z .minus .zero .minus .plus .plus .minus := by + simp only [hybLeft,hybRight,sum_spin,exchangeNumerator_eq_table,exchangeTable, + mul_zero,zero_mul,zero_add,add_zero] + +theorem hyb_entry_20_15 (x y z : ℂ) : + hybLeft x y z .minus .zero .minus .plus .minus .zero = hybRight x y z .minus .zero .minus .plus .minus .zero := by + simp only [hybLeft,hybRight,sum_spin,exchangeNumerator_eq_table,exchangeTable, + mul_zero,zero_mul,zero_add,add_zero] + +theorem hyb_entry_20_16 (x y z : ℂ) : + hybLeft x y z .minus .zero .minus .plus .minus .plus = hybRight x y z .minus .zero .minus .plus .minus .plus := by + simp only [hybLeft,hybRight,sum_spin,exchangeNumerator_eq_table,exchangeTable, + mul_zero,zero_mul,zero_add,add_zero] + +theorem hyb_entry_20_17 (x y z : ℂ) : + hybLeft x y z .minus .zero .minus .plus .minus .minus = hybRight x y z .minus .zero .minus .plus .minus .minus := by + simp only [hybLeft,hybRight,sum_spin,exchangeNumerator_eq_table,exchangeTable, + mul_zero,zero_mul,zero_add,add_zero] + +theorem hyb_entry_20_18 (x y z : ℂ) : + hybLeft x y z .minus .zero .minus .minus .zero .zero = hybRight x y z .minus .zero .minus .minus .zero .zero := by + simp only [hybLeft,hybRight,sum_spin,exchangeNumerator_eq_table,exchangeTable, + mul_zero,zero_mul,zero_add,add_zero] + +theorem hyb_entry_20_19 (x y z : ℂ) : + hybLeft x y z .minus .zero .minus .minus .zero .plus = hybRight x y z .minus .zero .minus .minus .zero .plus := by + simp only [hybLeft,hybRight,sum_spin,exchangeNumerator_eq_table,exchangeTable, + mul_zero,zero_mul,zero_add,add_zero] + +theorem hyb_entry_20_20 (x y z : ℂ) : + hybLeft x y z .minus .zero .minus .minus .zero .minus = hybRight x y z .minus .zero .minus .minus .zero .minus := by + simp only [hybLeft,hybRight,sum_spin,exchangeNumerator_eq_table,exchangeTable, + mul_zero,zero_mul,zero_add,add_zero] + all_goals ring_nf + +theorem hyb_entry_20_21 (x y z : ℂ) : + hybLeft x y z .minus .zero .minus .minus .plus .zero = hybRight x y z .minus .zero .minus .minus .plus .zero := by + simp only [hybLeft,hybRight,sum_spin,exchangeNumerator_eq_table,exchangeTable, + mul_zero,zero_mul,zero_add,add_zero] + +theorem hyb_entry_20_22 (x y z : ℂ) : + hybLeft x y z .minus .zero .minus .minus .plus .plus = hybRight x y z .minus .zero .minus .minus .plus .plus := by + simp only [hybLeft,hybRight,sum_spin,exchangeNumerator_eq_table,exchangeTable, + mul_zero,zero_mul,zero_add,add_zero] + +theorem hyb_entry_20_23 (x y z : ℂ) : + hybLeft x y z .minus .zero .minus .minus .plus .minus = hybRight x y z .minus .zero .minus .minus .plus .minus := by + simp only [hybLeft,hybRight,sum_spin,exchangeNumerator_eq_table,exchangeTable, + mul_zero,zero_mul,zero_add,add_zero] + +theorem hyb_entry_20_24 (x y z : ℂ) : + hybLeft x y z .minus .zero .minus .minus .minus .zero = hybRight x y z .minus .zero .minus .minus .minus .zero := by + simp only [hybLeft,hybRight,sum_spin,exchangeNumerator_eq_table,exchangeTable, + mul_zero,zero_mul,zero_add,add_zero] + all_goals ring_nf + all_goals try simp only [q_pow_eight,q_pow_10,q_pow_12,q_pow_14] + all_goals ring + +theorem hyb_entry_20_25 (x y z : ℂ) : + hybLeft x y z .minus .zero .minus .minus .minus .plus = hybRight x y z .minus .zero .minus .minus .minus .plus := by + simp only [hybLeft,hybRight,sum_spin,exchangeNumerator_eq_table,exchangeTable, + mul_zero,zero_mul,zero_add,add_zero] + +theorem hyb_entry_20_26 (x y z : ℂ) : + hybLeft x y z .minus .zero .minus .minus .minus .minus = hybRight x y z .minus .zero .minus .minus .minus .minus := by + simp only [hybLeft,hybRight,sum_spin,exchangeNumerator_eq_table,exchangeTable, + mul_zero,zero_mul,zero_add,add_zero] + +theorem hyb_entry_21_0 (x y z : ℂ) : + hybLeft x y z .minus .plus .zero .zero .zero .zero = hybRight x y z .minus .plus .zero .zero .zero .zero := by + simp only [hybLeft,hybRight,sum_spin,exchangeNumerator_eq_table,exchangeTable, + mul_zero,zero_mul,zero_add,add_zero] + all_goals ring_nf + all_goals try simp only [q_pow_9,q_pow_11,q_pow_13,q_pow_15,q_pow_17] + all_goals ring + +theorem hyb_entry_21_1 (x y z : ℂ) : + hybLeft x y z .minus .plus .zero .zero .zero .plus = hybRight x y z .minus .plus .zero .zero .zero .plus := by + simp only [hybLeft,hybRight,sum_spin,exchangeNumerator_eq_table,exchangeTable, + mul_zero,zero_mul,zero_add,add_zero] + +theorem hyb_entry_21_2 (x y z : ℂ) : + hybLeft x y z .minus .plus .zero .zero .zero .minus = hybRight x y z .minus .plus .zero .zero .zero .minus := by + simp only [hybLeft,hybRight,sum_spin,exchangeNumerator_eq_table,exchangeTable, + mul_zero,zero_mul,zero_add,add_zero] + +theorem hyb_entry_21_3 (x y z : ℂ) : + hybLeft x y z .minus .plus .zero .zero .plus .zero = hybRight x y z .minus .plus .zero .zero .plus .zero := by + simp only [hybLeft,hybRight,sum_spin,exchangeNumerator_eq_table,exchangeTable, + mul_zero,zero_mul,zero_add,add_zero] + +theorem hyb_entry_21_4 (x y z : ℂ) : + hybLeft x y z .minus .plus .zero .zero .plus .plus = hybRight x y z .minus .plus .zero .zero .plus .plus := by + simp only [hybLeft,hybRight,sum_spin,exchangeNumerator_eq_table,exchangeTable, + mul_zero,zero_mul,zero_add,add_zero] + +theorem hyb_entry_21_5 (x y z : ℂ) : + hybLeft x y z .minus .plus .zero .zero .plus .minus = hybRight x y z .minus .plus .zero .zero .plus .minus := by + simp only [hybLeft,hybRight,sum_spin,exchangeNumerator_eq_table,exchangeTable, + mul_zero,zero_mul,zero_add,add_zero] + all_goals ring_nf + +theorem hyb_entry_21_6 (x y z : ℂ) : + hybLeft x y z .minus .plus .zero .zero .minus .zero = hybRight x y z .minus .plus .zero .zero .minus .zero := by + simp only [hybLeft,hybRight,sum_spin,exchangeNumerator_eq_table,exchangeTable, + mul_zero,zero_mul,zero_add,add_zero] + +theorem hyb_entry_21_7 (x y z : ℂ) : + hybLeft x y z .minus .plus .zero .zero .minus .plus = hybRight x y z .minus .plus .zero .zero .minus .plus := by + simp only [hybLeft,hybRight,sum_spin,exchangeNumerator_eq_table,exchangeTable, + mul_zero,zero_mul,zero_add,add_zero] + all_goals ring_nf + +theorem hyb_entry_21_8 (x y z : ℂ) : + hybLeft x y z .minus .plus .zero .zero .minus .minus = hybRight x y z .minus .plus .zero .zero .minus .minus := by + simp only [hybLeft,hybRight,sum_spin,exchangeNumerator_eq_table,exchangeTable, + mul_zero,zero_mul,zero_add,add_zero] + +theorem hyb_entry_21_9 (x y z : ℂ) : + hybLeft x y z .minus .plus .zero .plus .zero .zero = hybRight x y z .minus .plus .zero .plus .zero .zero := by + simp only [hybLeft,hybRight,sum_spin,exchangeNumerator_eq_table,exchangeTable, + mul_zero,zero_mul,zero_add,add_zero] + +theorem hyb_entry_21_10 (x y z : ℂ) : + hybLeft x y z .minus .plus .zero .plus .zero .plus = hybRight x y z .minus .plus .zero .plus .zero .plus := by + simp only [hybLeft,hybRight,sum_spin,exchangeNumerator_eq_table,exchangeTable, + mul_zero,zero_mul,zero_add,add_zero] + +theorem hyb_entry_21_11 (x y z : ℂ) : + hybLeft x y z .minus .plus .zero .plus .zero .minus = hybRight x y z .minus .plus .zero .plus .zero .minus := by + simp only [hybLeft,hybRight,sum_spin,exchangeNumerator_eq_table,exchangeTable, + mul_zero,zero_mul,zero_add,add_zero] + all_goals ring_nf + all_goals try simp only [q_pow_eight,q_pow_10,q_pow_12,q_pow_14] + all_goals ring + +theorem hyb_entry_21_12 (x y z : ℂ) : + hybLeft x y z .minus .plus .zero .plus .plus .zero = hybRight x y z .minus .plus .zero .plus .plus .zero := by + simp only [hybLeft,hybRight,sum_spin,exchangeNumerator_eq_table,exchangeTable, + mul_zero,zero_mul,zero_add,add_zero] + +theorem hyb_entry_21_13 (x y z : ℂ) : + hybLeft x y z .minus .plus .zero .plus .plus .plus = hybRight x y z .minus .plus .zero .plus .plus .plus := by + simp only [hybLeft,hybRight,sum_spin,exchangeNumerator_eq_table,exchangeTable, + mul_zero,zero_mul,zero_add,add_zero] + +theorem hyb_entry_21_14 (x y z : ℂ) : + hybLeft x y z .minus .plus .zero .plus .plus .minus = hybRight x y z .minus .plus .zero .plus .plus .minus := by + simp only [hybLeft,hybRight,sum_spin,exchangeNumerator_eq_table,exchangeTable, + mul_zero,zero_mul,zero_add,add_zero] + +theorem hyb_entry_21_15 (x y z : ℂ) : + hybLeft x y z .minus .plus .zero .plus .minus .zero = hybRight x y z .minus .plus .zero .plus .minus .zero := by + simp only [hybLeft,hybRight,sum_spin,exchangeNumerator_eq_table,exchangeTable, + mul_zero,zero_mul,zero_add,add_zero] + all_goals ring_nf + all_goals try simp only [q_pow_eight,q_pow_10,q_pow_12,q_pow_14,q_pow_16,q_pow_18] + all_goals ring + +theorem hyb_entry_21_16 (x y z : ℂ) : + hybLeft x y z .minus .plus .zero .plus .minus .plus = hybRight x y z .minus .plus .zero .plus .minus .plus := by + simp only [hybLeft,hybRight,sum_spin,exchangeNumerator_eq_table,exchangeTable, + mul_zero,zero_mul,zero_add,add_zero] + +theorem hyb_entry_21_17 (x y z : ℂ) : + hybLeft x y z .minus .plus .zero .plus .minus .minus = hybRight x y z .minus .plus .zero .plus .minus .minus := by + simp only [hybLeft,hybRight,sum_spin,exchangeNumerator_eq_table,exchangeTable, + mul_zero,zero_mul,zero_add,add_zero] + +theorem hyb_entry_21_18 (x y z : ℂ) : + hybLeft x y z .minus .plus .zero .minus .zero .zero = hybRight x y z .minus .plus .zero .minus .zero .zero := by + simp only [hybLeft,hybRight,sum_spin,exchangeNumerator_eq_table,exchangeTable, + mul_zero,zero_mul,zero_add,add_zero] + +theorem hyb_entry_21_19 (x y z : ℂ) : + hybLeft x y z .minus .plus .zero .minus .zero .plus = hybRight x y z .minus .plus .zero .minus .zero .plus := by + simp only [hybLeft,hybRight,sum_spin,exchangeNumerator_eq_table,exchangeTable, + mul_zero,zero_mul,zero_add,add_zero] + all_goals ring_nf + all_goals try simp only [q_pow_eight,q_pow_10,q_pow_12,q_pow_14] + all_goals ring + +theorem hyb_entry_21_20 (x y z : ℂ) : + hybLeft x y z .minus .plus .zero .minus .zero .minus = hybRight x y z .minus .plus .zero .minus .zero .minus := by + simp only [hybLeft,hybRight,sum_spin,exchangeNumerator_eq_table,exchangeTable, + mul_zero,zero_mul,zero_add,add_zero] + +theorem hyb_entry_21_21 (x y z : ℂ) : + hybLeft x y z .minus .plus .zero .minus .plus .zero = hybRight x y z .minus .plus .zero .minus .plus .zero := by + simp only [hybLeft,hybRight,sum_spin,exchangeNumerator_eq_table,exchangeTable, + mul_zero,zero_mul,zero_add,add_zero] + all_goals ring_nf + all_goals try simp only [q_pow_eight,q_pow_10,q_pow_12,q_pow_14,q_pow_16,q_pow_18] + all_goals ring + +theorem hyb_entry_21_22 (x y z : ℂ) : + hybLeft x y z .minus .plus .zero .minus .plus .plus = hybRight x y z .minus .plus .zero .minus .plus .plus := by + simp only [hybLeft,hybRight,sum_spin,exchangeNumerator_eq_table,exchangeTable, + mul_zero,zero_mul,zero_add,add_zero] + +theorem hyb_entry_21_23 (x y z : ℂ) : + hybLeft x y z .minus .plus .zero .minus .plus .minus = hybRight x y z .minus .plus .zero .minus .plus .minus := by + simp only [hybLeft,hybRight,sum_spin,exchangeNumerator_eq_table,exchangeTable, + mul_zero,zero_mul,zero_add,add_zero] + +theorem hyb_entry_21_24 (x y z : ℂ) : + hybLeft x y z .minus .plus .zero .minus .minus .zero = hybRight x y z .minus .plus .zero .minus .minus .zero := by + simp only [hybLeft,hybRight,sum_spin,exchangeNumerator_eq_table,exchangeTable, + mul_zero,zero_mul,zero_add,add_zero] + +theorem hyb_entry_21_25 (x y z : ℂ) : + hybLeft x y z .minus .plus .zero .minus .minus .plus = hybRight x y z .minus .plus .zero .minus .minus .plus := by + simp only [hybLeft,hybRight,sum_spin,exchangeNumerator_eq_table,exchangeTable, + mul_zero,zero_mul,zero_add,add_zero] + +theorem hyb_entry_21_26 (x y z : ℂ) : + hybLeft x y z .minus .plus .zero .minus .minus .minus = hybRight x y z .minus .plus .zero .minus .minus .minus := by + simp only [hybLeft,hybRight,sum_spin,exchangeNumerator_eq_table,exchangeTable, + mul_zero,zero_mul,add_zero] + +theorem hyb_entry_22_0 (x y z : ℂ) : + hybLeft x y z .minus .plus .plus .zero .zero .zero = hybRight x y z .minus .plus .plus .zero .zero .zero := by + simp only [hybLeft,hybRight,sum_spin,exchangeNumerator_eq_table,exchangeTable, + mul_zero,zero_mul,zero_add,add_zero] + +theorem hyb_entry_22_1 (x y z : ℂ) : + hybLeft x y z .minus .plus .plus .zero .zero .plus = hybRight x y z .minus .plus .plus .zero .zero .plus := by + simp only [hybLeft,hybRight,sum_spin,exchangeNumerator_eq_table,exchangeTable, + mul_zero,zero_mul,zero_add,add_zero] + all_goals ring_nf + all_goals try simp only [q_pow_9,q_pow_11,q_pow_13,q_pow_15,q_pow_17] + all_goals ring + +theorem hyb_entry_22_2 (x y z : ℂ) : + hybLeft x y z .minus .plus .plus .zero .zero .minus = hybRight x y z .minus .plus .plus .zero .zero .minus := by + simp only [hybLeft,hybRight,sum_spin,exchangeNumerator_eq_table,exchangeTable, + mul_zero,zero_mul,zero_add,add_zero] + +theorem hyb_entry_22_3 (x y z : ℂ) : + hybLeft x y z .minus .plus .plus .zero .plus .zero = hybRight x y z .minus .plus .plus .zero .plus .zero := by + simp only [hybLeft,hybRight,sum_spin,exchangeNumerator_eq_table,exchangeTable, + mul_zero,zero_mul,zero_add,add_zero] + all_goals ring_nf + all_goals try simp only [q_pow_9,q_pow_11,q_pow_13] + all_goals ring + +theorem hyb_entry_22_4 (x y z : ℂ) : + hybLeft x y z .minus .plus .plus .zero .plus .plus = hybRight x y z .minus .plus .plus .zero .plus .plus := by + simp only [hybLeft,hybRight,sum_spin,exchangeNumerator_eq_table,exchangeTable, + mul_zero,zero_mul,zero_add,add_zero] + +theorem hyb_entry_22_5 (x y z : ℂ) : + hybLeft x y z .minus .plus .plus .zero .plus .minus = hybRight x y z .minus .plus .plus .zero .plus .minus := by + simp only [hybLeft,hybRight,sum_spin,exchangeNumerator_eq_table,exchangeTable, + mul_zero,zero_mul,zero_add,add_zero] + +theorem hyb_entry_22_6 (x y z : ℂ) : + hybLeft x y z .minus .plus .plus .zero .minus .zero = hybRight x y z .minus .plus .plus .zero .minus .zero := by + simp only [hybLeft,hybRight,sum_spin,exchangeNumerator_eq_table,exchangeTable, + mul_zero,zero_mul,zero_add,add_zero] + +theorem hyb_entry_22_7 (x y z : ℂ) : + hybLeft x y z .minus .plus .plus .zero .minus .plus = hybRight x y z .minus .plus .plus .zero .minus .plus := by + simp only [hybLeft,hybRight,sum_spin,exchangeNumerator_eq_table,exchangeTable, + mul_zero,zero_mul,zero_add,add_zero] + +theorem hyb_entry_22_8 (x y z : ℂ) : + hybLeft x y z .minus .plus .plus .zero .minus .minus = hybRight x y z .minus .plus .plus .zero .minus .minus := by + simp only [hybLeft,hybRight,sum_spin,exchangeNumerator_eq_table,exchangeTable, + mul_zero,zero_mul,add_zero] + +theorem hyb_entry_22_9 (x y z : ℂ) : + hybLeft x y z .minus .plus .plus .plus .zero .zero = hybRight x y z .minus .plus .plus .plus .zero .zero := by + simp only [hybLeft,hybRight,sum_spin,exchangeNumerator_eq_table,exchangeTable, + mul_zero,zero_mul,zero_add,add_zero] + all_goals ring_nf + all_goals try simp only [q_pow_9,q_pow_11,q_pow_13,q_pow_15,q_pow_17] + all_goals ring + +theorem hyb_entry_22_10 (x y z : ℂ) : + hybLeft x y z .minus .plus .plus .plus .zero .plus = hybRight x y z .minus .plus .plus .plus .zero .plus := by + simp only [hybLeft,hybRight,sum_spin,exchangeNumerator_eq_table,exchangeTable, + mul_zero,zero_mul,zero_add,add_zero] + +theorem hyb_entry_22_11 (x y z : ℂ) : + hybLeft x y z .minus .plus .plus .plus .zero .minus = hybRight x y z .minus .plus .plus .plus .zero .minus := by + simp only [hybLeft,hybRight,sum_spin,exchangeNumerator_eq_table,exchangeTable, + mul_zero,zero_mul,zero_add,add_zero] + +theorem hyb_entry_22_12 (x y z : ℂ) : + hybLeft x y z .minus .plus .plus .plus .plus .zero = hybRight x y z .minus .plus .plus .plus .plus .zero := by + simp only [hybLeft,hybRight,sum_spin,exchangeNumerator_eq_table,exchangeTable, + mul_zero,zero_mul,zero_add,add_zero] + +theorem hyb_entry_22_13 (x y z : ℂ) : + hybLeft x y z .minus .plus .plus .plus .plus .plus = hybRight x y z .minus .plus .plus .plus .plus .plus := by + simp only [hybLeft,hybRight,sum_spin,exchangeNumerator_eq_table,exchangeTable, + mul_zero,zero_mul,zero_add,add_zero] + +theorem hyb_entry_22_14 (x y z : ℂ) : + hybLeft x y z .minus .plus .plus .plus .plus .minus = hybRight x y z .minus .plus .plus .plus .plus .minus := by + simp only [hybLeft,hybRight,sum_spin,exchangeNumerator_eq_table,exchangeTable, + mul_zero,zero_mul,zero_add,add_zero] + all_goals ring_nf + +theorem hyb_entry_22_15 (x y z : ℂ) : + hybLeft x y z .minus .plus .plus .plus .minus .zero = hybRight x y z .minus .plus .plus .plus .minus .zero := by + simp only [hybLeft,hybRight,sum_spin,exchangeNumerator_eq_table,exchangeTable, + mul_zero,zero_mul,zero_add,add_zero] + +theorem hyb_entry_22_16 (x y z : ℂ) : + hybLeft x y z .minus .plus .plus .plus .minus .plus = hybRight x y z .minus .plus .plus .plus .minus .plus := by + simp only [hybLeft,hybRight,sum_spin,exchangeNumerator_eq_table,exchangeTable, + mul_zero,zero_mul,zero_add,add_zero] + all_goals ring_nf + all_goals try simp only [q_pow_eight,q_pow_10,q_pow_12,q_pow_14,q_pow_16,q_pow_18] + all_goals ring + +theorem hyb_entry_22_17 (x y z : ℂ) : + hybLeft x y z .minus .plus .plus .plus .minus .minus = hybRight x y z .minus .plus .plus .plus .minus .minus := by + simp only [hybLeft,hybRight,sum_spin,exchangeNumerator_eq_table,exchangeTable, + mul_zero,zero_mul,zero_add,add_zero] + +theorem hyb_entry_22_18 (x y z : ℂ) : + hybLeft x y z .minus .plus .plus .minus .zero .zero = hybRight x y z .minus .plus .plus .minus .zero .zero := by + simp only [hybLeft,hybRight,sum_spin,exchangeNumerator_eq_table,exchangeTable, + mul_zero,zero_mul,zero_add,add_zero] + +theorem hyb_entry_22_19 (x y z : ℂ) : + hybLeft x y z .minus .plus .plus .minus .zero .plus = hybRight x y z .minus .plus .plus .minus .zero .plus := by + simp only [hybLeft,hybRight,sum_spin,exchangeNumerator_eq_table,exchangeTable, + mul_zero,zero_mul,zero_add,add_zero] + +theorem hyb_entry_22_20 (x y z : ℂ) : + hybLeft x y z .minus .plus .plus .minus .zero .minus = hybRight x y z .minus .plus .plus .minus .zero .minus := by + simp only [hybLeft,hybRight,sum_spin,exchangeNumerator_eq_table,exchangeTable, + mul_zero,zero_mul,add_zero] + +theorem hyb_entry_22_21 (x y z : ℂ) : + hybLeft x y z .minus .plus .plus .minus .plus .zero = hybRight x y z .minus .plus .plus .minus .plus .zero := by + simp only [hybLeft,hybRight,sum_spin,exchangeNumerator_eq_table,exchangeTable, + mul_zero,zero_mul,zero_add,add_zero] + +theorem hyb_entry_22_22 (x y z : ℂ) : + hybLeft x y z .minus .plus .plus .minus .plus .plus = hybRight x y z .minus .plus .plus .minus .plus .plus := by + simp only [hybLeft,hybRight,sum_spin,exchangeNumerator_eq_table,exchangeTable, + mul_zero,zero_mul,zero_add,add_zero] + all_goals ring_nf + all_goals try simp only [q_pow_eight,q_pow_10,q_pow_12,q_pow_14,q_pow_16,q_pow_18] + all_goals ring + +theorem hyb_entry_22_23 (x y z : ℂ) : + hybLeft x y z .minus .plus .plus .minus .plus .minus = hybRight x y z .minus .plus .plus .minus .plus .minus := by + simp only [hybLeft,hybRight,sum_spin,exchangeNumerator_eq_table,exchangeTable, + mul_zero,zero_mul,zero_add,add_zero] + +theorem hyb_entry_22_24 (x y z : ℂ) : + hybLeft x y z .minus .plus .plus .minus .minus .zero = hybRight x y z .minus .plus .plus .minus .minus .zero := by + simp only [hybLeft,hybRight,sum_spin,exchangeNumerator_eq_table,exchangeTable, + mul_zero,zero_mul,add_zero] + +theorem hyb_entry_22_25 (x y z : ℂ) : + hybLeft x y z .minus .plus .plus .minus .minus .plus = hybRight x y z .minus .plus .plus .minus .minus .plus := by + simp only [hybLeft,hybRight,sum_spin,exchangeNumerator_eq_table,exchangeTable, + mul_zero,zero_mul,zero_add,add_zero] + +theorem hyb_entry_22_26 (x y z : ℂ) : + hybLeft x y z .minus .plus .plus .minus .minus .minus = hybRight x y z .minus .plus .plus .minus .minus .minus := by + simp only [hybLeft,hybRight,sum_spin,exchangeNumerator_eq_table,exchangeTable, + mul_zero,zero_mul,add_zero] + +theorem hyb_entry_23_0 (x y z : ℂ) : + hybLeft x y z .minus .plus .minus .zero .zero .zero = hybRight x y z .minus .plus .minus .zero .zero .zero := by + simp only [hybLeft,hybRight,sum_spin,exchangeNumerator_eq_table,exchangeTable, + mul_zero,zero_mul,zero_add,add_zero] + +theorem hyb_entry_23_1 (x y z : ℂ) : + hybLeft x y z .minus .plus .minus .zero .zero .plus = hybRight x y z .minus .plus .minus .zero .zero .plus := by + simp only [hybLeft,hybRight,sum_spin,exchangeNumerator_eq_table,exchangeTable, + mul_zero,zero_mul,zero_add,add_zero] + +theorem hyb_entry_23_2 (x y z : ℂ) : + hybLeft x y z .minus .plus .minus .zero .zero .minus = hybRight x y z .minus .plus .minus .zero .zero .minus := by + simp only [hybLeft,hybRight,sum_spin,exchangeNumerator_eq_table,exchangeTable, + mul_zero,zero_mul,zero_add,add_zero] + all_goals ring_nf + all_goals try simp only [q_pow_9,q_pow_11,q_pow_13,q_pow_15,q_pow_17] + all_goals ring + +theorem hyb_entry_23_3 (x y z : ℂ) : + hybLeft x y z .minus .plus .minus .zero .plus .zero = hybRight x y z .minus .plus .minus .zero .plus .zero := by + simp only [hybLeft,hybRight,sum_spin,exchangeNumerator_eq_table,exchangeTable, + mul_zero,zero_mul,zero_add,add_zero] + +theorem hyb_entry_23_4 (x y z : ℂ) : + hybLeft x y z .minus .plus .minus .zero .plus .plus = hybRight x y z .minus .plus .minus .zero .plus .plus := by + simp only [hybLeft,hybRight,sum_spin,exchangeNumerator_eq_table,exchangeTable, + mul_zero,zero_mul,zero_add,add_zero] + +theorem hyb_entry_23_5 (x y z : ℂ) : + hybLeft x y z .minus .plus .minus .zero .plus .minus = hybRight x y z .minus .plus .minus .zero .plus .minus := by + simp only [hybLeft,hybRight,sum_spin,exchangeNumerator_eq_table,exchangeTable, + mul_zero,zero_mul,zero_add,add_zero] + +theorem hyb_entry_23_6 (x y z : ℂ) : + hybLeft x y z .minus .plus .minus .zero .minus .zero = hybRight x y z .minus .plus .minus .zero .minus .zero := by + simp only [hybLeft,hybRight,sum_spin,exchangeNumerator_eq_table,exchangeTable, + mul_zero,zero_mul,zero_add,add_zero] + all_goals ring_nf + all_goals try simp only [q_pow_9,q_pow_11,q_pow_13] + all_goals ring + +theorem hyb_entry_23_7 (x y z : ℂ) : + hybLeft x y z .minus .plus .minus .zero .minus .plus = hybRight x y z .minus .plus .minus .zero .minus .plus := by + simp only [hybLeft,hybRight,sum_spin,exchangeNumerator_eq_table,exchangeTable, + mul_zero,zero_mul,zero_add,add_zero] + +theorem hyb_entry_23_8 (x y z : ℂ) : + hybLeft x y z .minus .plus .minus .zero .minus .minus = hybRight x y z .minus .plus .minus .zero .minus .minus := by + simp only [hybLeft,hybRight,sum_spin,exchangeNumerator_eq_table,exchangeTable, + mul_zero,zero_mul,zero_add,add_zero] + +theorem hyb_entry_23_9 (x y z : ℂ) : + hybLeft x y z .minus .plus .minus .plus .zero .zero = hybRight x y z .minus .plus .minus .plus .zero .zero := by + simp only [hybLeft,hybRight,sum_spin,exchangeNumerator_eq_table,exchangeTable, + mul_zero,zero_mul,zero_add,add_zero] + +theorem hyb_entry_23_10 (x y z : ℂ) : + hybLeft x y z .minus .plus .minus .plus .zero .plus = hybRight x y z .minus .plus .minus .plus .zero .plus := by + simp only [hybLeft,hybRight,sum_spin,exchangeNumerator_eq_table,exchangeTable, + mul_zero,zero_mul,add_zero] + +theorem hyb_entry_23_11 (x y z : ℂ) : + hybLeft x y z .minus .plus .minus .plus .zero .minus = hybRight x y z .minus .plus .minus .plus .zero .minus := by + simp only [hybLeft,hybRight,sum_spin,exchangeNumerator_eq_table,exchangeTable, + mul_zero,zero_mul,zero_add,add_zero] + +theorem hyb_entry_23_12 (x y z : ℂ) : + hybLeft x y z .minus .plus .minus .plus .plus .zero = hybRight x y z .minus .plus .minus .plus .plus .zero := by + simp only [hybLeft,hybRight,sum_spin,exchangeNumerator_eq_table,exchangeTable, + mul_zero,zero_mul,add_zero] + +theorem hyb_entry_23_13 (x y z : ℂ) : + hybLeft x y z .minus .plus .minus .plus .plus .plus = hybRight x y z .minus .plus .minus .plus .plus .plus := by + simp only [hybLeft,hybRight,sum_spin,exchangeNumerator_eq_table,exchangeTable, + mul_zero,zero_mul,zero_add,add_zero] + +theorem hyb_entry_23_14 (x y z : ℂ) : + hybLeft x y z .minus .plus .minus .plus .plus .minus = hybRight x y z .minus .plus .minus .plus .plus .minus := by + simp only [hybLeft,hybRight,sum_spin,exchangeNumerator_eq_table,exchangeTable, + mul_zero,zero_mul,zero_add,add_zero] + +theorem hyb_entry_23_15 (x y z : ℂ) : + hybLeft x y z .minus .plus .minus .plus .minus .zero = hybRight x y z .minus .plus .minus .plus .minus .zero := by + simp only [hybLeft,hybRight,sum_spin,exchangeNumerator_eq_table,exchangeTable, + mul_zero,zero_mul,zero_add,add_zero] + +theorem hyb_entry_23_16 (x y z : ℂ) : + hybLeft x y z .minus .plus .minus .plus .minus .plus = hybRight x y z .minus .plus .minus .plus .minus .plus := by + simp only [hybLeft,hybRight,sum_spin,exchangeNumerator_eq_table,exchangeTable, + mul_zero,zero_mul,zero_add,add_zero] + +theorem hyb_entry_23_17 (x y z : ℂ) : + hybLeft x y z .minus .plus .minus .plus .minus .minus = hybRight x y z .minus .plus .minus .plus .minus .minus := by + simp only [hybLeft,hybRight,sum_spin,exchangeNumerator_eq_table,exchangeTable, + mul_zero,zero_mul,zero_add,add_zero] + all_goals ring_nf + all_goals try simp only [q_pow_eight,q_pow_10,q_pow_12,q_pow_14,q_pow_16,q_pow_18] + all_goals ring + +theorem hyb_entry_23_18 (x y z : ℂ) : + hybLeft x y z .minus .plus .minus .minus .zero .zero = hybRight x y z .minus .plus .minus .minus .zero .zero := by + simp only [hybLeft,hybRight,sum_spin,exchangeNumerator_eq_table,exchangeTable, + mul_zero,zero_mul,zero_add,add_zero] + all_goals ring_nf + all_goals try simp only [q_pow_9,q_pow_11,q_pow_13,q_pow_15,q_pow_17] + all_goals ring + +theorem hyb_entry_23_19 (x y z : ℂ) : + hybLeft x y z .minus .plus .minus .minus .zero .plus = hybRight x y z .minus .plus .minus .minus .zero .plus := by + simp only [hybLeft,hybRight,sum_spin,exchangeNumerator_eq_table,exchangeTable, + mul_zero,zero_mul,zero_add,add_zero] + +theorem hyb_entry_23_20 (x y z : ℂ) : + hybLeft x y z .minus .plus .minus .minus .zero .minus = hybRight x y z .minus .plus .minus .minus .zero .minus := by + simp only [hybLeft,hybRight,sum_spin,exchangeNumerator_eq_table,exchangeTable, + mul_zero,zero_mul,zero_add,add_zero] + +theorem hyb_entry_23_21 (x y z : ℂ) : + hybLeft x y z .minus .plus .minus .minus .plus .zero = hybRight x y z .minus .plus .minus .minus .plus .zero := by + simp only [hybLeft,hybRight,sum_spin,exchangeNumerator_eq_table,exchangeTable, + mul_zero,zero_mul,zero_add,add_zero] + +theorem hyb_entry_23_22 (x y z : ℂ) : + hybLeft x y z .minus .plus .minus .minus .plus .plus = hybRight x y z .minus .plus .minus .minus .plus .plus := by + simp only [hybLeft,hybRight,sum_spin,exchangeNumerator_eq_table,exchangeTable, + mul_zero,zero_mul,zero_add,add_zero] + +theorem hyb_entry_23_23 (x y z : ℂ) : + hybLeft x y z .minus .plus .minus .minus .plus .minus = hybRight x y z .minus .plus .minus .minus .plus .minus := by + simp only [hybLeft,hybRight,sum_spin,exchangeNumerator_eq_table,exchangeTable, + mul_zero,zero_mul,zero_add,add_zero] + all_goals ring_nf + all_goals try simp only [q_pow_eight,q_pow_10,q_pow_12,q_pow_14,q_pow_16,q_pow_18] + all_goals ring + +theorem hyb_entry_23_24 (x y z : ℂ) : + hybLeft x y z .minus .plus .minus .minus .minus .zero = hybRight x y z .minus .plus .minus .minus .minus .zero := by + simp only [hybLeft,hybRight,sum_spin,exchangeNumerator_eq_table,exchangeTable, + mul_zero,zero_mul,zero_add,add_zero] + +theorem hyb_entry_23_25 (x y z : ℂ) : + hybLeft x y z .minus .plus .minus .minus .minus .plus = hybRight x y z .minus .plus .minus .minus .minus .plus := by + simp only [hybLeft,hybRight,sum_spin,exchangeNumerator_eq_table,exchangeTable, + mul_zero,zero_mul,zero_add,add_zero] + all_goals ring_nf + all_goals try simp only [q_pow_eight,q_pow_10,q_pow_12,q_pow_14,q_pow_16,q_pow_18] + all_goals ring + +theorem hyb_entry_23_26 (x y z : ℂ) : + hybLeft x y z .minus .plus .minus .minus .minus .minus = hybRight x y z .minus .plus .minus .minus .minus .minus := by + simp only [hybLeft,hybRight,sum_spin,exchangeNumerator_eq_table,exchangeTable, + mul_zero,zero_mul,zero_add,add_zero] + +theorem hyb_entry_24_0 (x y z : ℂ) : + hybLeft x y z .minus .minus .zero .zero .zero .zero = hybRight x y z .minus .minus .zero .zero .zero .zero := by + simp only [hybLeft,hybRight,sum_spin,exchangeNumerator_eq_table,exchangeTable, + mul_zero,zero_mul,zero_add,add_zero] + +theorem hyb_entry_24_1 (x y z : ℂ) : + hybLeft x y z .minus .minus .zero .zero .zero .plus = hybRight x y z .minus .minus .zero .zero .zero .plus := by + simp only [hybLeft,hybRight,sum_spin,exchangeNumerator_eq_table,exchangeTable, + mul_zero,zero_mul,add_zero] + +theorem hyb_entry_24_2 (x y z : ℂ) : + hybLeft x y z .minus .minus .zero .zero .zero .minus = hybRight x y z .minus .minus .zero .zero .zero .minus := by + simp only [hybLeft,hybRight,sum_spin,exchangeNumerator_eq_table,exchangeTable, + mul_zero,zero_mul,zero_add,add_zero] + +theorem hyb_entry_24_3 (x y z : ℂ) : + hybLeft x y z .minus .minus .zero .zero .plus .zero = hybRight x y z .minus .minus .zero .zero .plus .zero := by + simp only [hybLeft,hybRight,sum_spin,exchangeNumerator_eq_table,exchangeTable, + mul_zero,zero_mul,add_zero] + +theorem hyb_entry_24_4 (x y z : ℂ) : + hybLeft x y z .minus .minus .zero .zero .plus .plus = hybRight x y z .minus .minus .zero .zero .plus .plus := by + simp only [hybLeft,hybRight,sum_spin,exchangeNumerator_eq_table,exchangeTable, + mul_zero,zero_mul,add_zero] + +theorem hyb_entry_24_5 (x y z : ℂ) : + hybLeft x y z .minus .minus .zero .zero .plus .minus = hybRight x y z .minus .minus .zero .zero .plus .minus := by + simp only [hybLeft,hybRight,sum_spin,exchangeNumerator_eq_table,exchangeTable, + mul_zero,zero_mul,zero_add,add_zero] + +theorem hyb_entry_24_6 (x y z : ℂ) : + hybLeft x y z .minus .minus .zero .zero .minus .zero = hybRight x y z .minus .minus .zero .zero .minus .zero := by + simp only [hybLeft,hybRight,sum_spin,exchangeNumerator_eq_table,exchangeTable, + mul_zero,zero_mul,zero_add,add_zero] + +theorem hyb_entry_24_7 (x y z : ℂ) : + hybLeft x y z .minus .minus .zero .zero .minus .plus = hybRight x y z .minus .minus .zero .zero .minus .plus := by + simp only [hybLeft,hybRight,sum_spin,exchangeNumerator_eq_table,exchangeTable, + mul_zero,zero_mul,zero_add,add_zero] + +theorem hyb_entry_24_8 (x y z : ℂ) : + hybLeft x y z .minus .minus .zero .zero .minus .minus = hybRight x y z .minus .minus .zero .zero .minus .minus := by + simp only [hybLeft,hybRight,sum_spin,exchangeNumerator_eq_table,exchangeTable, + mul_zero,zero_mul,zero_add,add_zero] + all_goals ring_nf + +theorem hyb_entry_24_9 (x y z : ℂ) : + hybLeft x y z .minus .minus .zero .plus .zero .zero = hybRight x y z .minus .minus .zero .plus .zero .zero := by + simp only [hybLeft,hybRight,sum_spin,exchangeNumerator_eq_table,exchangeTable, + mul_zero,zero_mul,add_zero] + +theorem hyb_entry_24_10 (x y z : ℂ) : + hybLeft x y z .minus .minus .zero .plus .zero .plus = hybRight x y z .minus .minus .zero .plus .zero .plus := by + simp only [hybLeft,hybRight,sum_spin,exchangeNumerator_eq_table,exchangeTable, + mul_zero,zero_mul,add_zero] + +theorem hyb_entry_24_11 (x y z : ℂ) : + hybLeft x y z .minus .minus .zero .plus .zero .minus = hybRight x y z .minus .minus .zero .plus .zero .minus := by + simp only [hybLeft,hybRight,sum_spin,exchangeNumerator_eq_table,exchangeTable, + mul_zero,zero_mul,zero_add,add_zero] + +theorem hyb_entry_24_12 (x y z : ℂ) : + hybLeft x y z .minus .minus .zero .plus .plus .zero = hybRight x y z .minus .minus .zero .plus .plus .zero := by + simp only [hybLeft,hybRight,sum_spin,exchangeNumerator_eq_table,exchangeTable, + mul_zero,zero_mul,zero_add,add_zero] + +theorem hyb_entry_24_13 (x y z : ℂ) : + hybLeft x y z .minus .minus .zero .plus .plus .plus = hybRight x y z .minus .minus .zero .plus .plus .plus := by + simp only [hybLeft,hybRight,sum_spin,exchangeNumerator_eq_table,exchangeTable, + mul_zero,zero_mul,add_zero] + +theorem hyb_entry_24_14 (x y z : ℂ) : + hybLeft x y z .minus .minus .zero .plus .plus .minus = hybRight x y z .minus .minus .zero .plus .plus .minus := by + simp only [hybLeft,hybRight,sum_spin,exchangeNumerator_eq_table,exchangeTable, + mul_zero,zero_mul,zero_add,add_zero] + +theorem hyb_entry_24_15 (x y z : ℂ) : + hybLeft x y z .minus .minus .zero .plus .minus .zero = hybRight x y z .minus .minus .zero .plus .minus .zero := by + simp only [hybLeft,hybRight,sum_spin,exchangeNumerator_eq_table,exchangeTable, + mul_zero,zero_mul,zero_add,add_zero] + +theorem hyb_entry_24_16 (x y z : ℂ) : + hybLeft x y z .minus .minus .zero .plus .minus .plus = hybRight x y z .minus .minus .zero .plus .minus .plus := by + simp only [hybLeft,hybRight,sum_spin,exchangeNumerator_eq_table,exchangeTable, + mul_zero,zero_mul,add_zero] + +theorem hyb_entry_24_17 (x y z : ℂ) : + hybLeft x y z .minus .minus .zero .plus .minus .minus = hybRight x y z .minus .minus .zero .plus .minus .minus := by + simp only [hybLeft,hybRight,sum_spin,exchangeNumerator_eq_table,exchangeTable, + mul_zero,zero_mul,zero_add,add_zero] + +theorem hyb_entry_24_18 (x y z : ℂ) : + hybLeft x y z .minus .minus .zero .minus .zero .zero = hybRight x y z .minus .minus .zero .minus .zero .zero := by + simp only [hybLeft,hybRight,sum_spin,exchangeNumerator_eq_table,exchangeTable, + mul_zero,zero_mul,zero_add,add_zero] + +theorem hyb_entry_24_19 (x y z : ℂ) : + hybLeft x y z .minus .minus .zero .minus .zero .plus = hybRight x y z .minus .minus .zero .minus .zero .plus := by + simp only [hybLeft,hybRight,sum_spin,exchangeNumerator_eq_table,exchangeTable, + mul_zero,zero_mul,zero_add,add_zero] + +theorem hyb_entry_24_20 (x y z : ℂ) : + hybLeft x y z .minus .minus .zero .minus .zero .minus = hybRight x y z .minus .minus .zero .minus .zero .minus := by + simp only [hybLeft,hybRight,sum_spin,exchangeNumerator_eq_table,exchangeTable, + mul_zero,zero_mul,zero_add,add_zero] + all_goals ring_nf + all_goals try simp only [q_pow_eight,q_pow_10,q_pow_12,q_pow_14] + all_goals ring + +theorem hyb_entry_24_21 (x y z : ℂ) : + hybLeft x y z .minus .minus .zero .minus .plus .zero = hybRight x y z .minus .minus .zero .minus .plus .zero := by + simp only [hybLeft,hybRight,sum_spin,exchangeNumerator_eq_table,exchangeTable, + mul_zero,zero_mul,zero_add,add_zero] + +theorem hyb_entry_24_22 (x y z : ℂ) : + hybLeft x y z .minus .minus .zero .minus .plus .plus = hybRight x y z .minus .minus .zero .minus .plus .plus := by + simp only [hybLeft,hybRight,sum_spin,exchangeNumerator_eq_table,exchangeTable, + mul_zero,zero_mul,add_zero] + +theorem hyb_entry_24_23 (x y z : ℂ) : + hybLeft x y z .minus .minus .zero .minus .plus .minus = hybRight x y z .minus .minus .zero .minus .plus .minus := by + simp only [hybLeft,hybRight,sum_spin,exchangeNumerator_eq_table,exchangeTable, + mul_zero,zero_mul,zero_add,add_zero] + +theorem hyb_entry_24_24 (x y z : ℂ) : + hybLeft x y z .minus .minus .zero .minus .minus .zero = hybRight x y z .minus .minus .zero .minus .minus .zero := by + simp only [hybLeft,hybRight,sum_spin,exchangeNumerator_eq_table,exchangeTable, + mul_zero,zero_mul,zero_add,add_zero] + all_goals ring_nf + all_goals try simp only [q_pow_eight,q_pow_10,q_pow_12,q_pow_14,q_pow_16,q_pow_18] + all_goals ring + +theorem hyb_entry_24_25 (x y z : ℂ) : + hybLeft x y z .minus .minus .zero .minus .minus .plus = hybRight x y z .minus .minus .zero .minus .minus .plus := by + simp only [hybLeft,hybRight,sum_spin,exchangeNumerator_eq_table,exchangeTable, + mul_zero,zero_mul,zero_add,add_zero] + +theorem hyb_entry_24_26 (x y z : ℂ) : + hybLeft x y z .minus .minus .zero .minus .minus .minus = hybRight x y z .minus .minus .zero .minus .minus .minus := by + simp only [hybLeft,hybRight,sum_spin,exchangeNumerator_eq_table,exchangeTable, + mul_zero,zero_mul,zero_add,add_zero] + +theorem hyb_entry_25_0 (x y z : ℂ) : + hybLeft x y z .minus .minus .plus .zero .zero .zero = hybRight x y z .minus .minus .plus .zero .zero .zero := by + simp only [hybLeft,hybRight,sum_spin,exchangeNumerator_eq_table,exchangeTable, + mul_zero,zero_mul,zero_add,add_zero] + +theorem hyb_entry_25_1 (x y z : ℂ) : + hybLeft x y z .minus .minus .plus .zero .zero .plus = hybRight x y z .minus .minus .plus .zero .zero .plus := by + simp only [hybLeft,hybRight,sum_spin,exchangeNumerator_eq_table,exchangeTable, + mul_zero,zero_mul,zero_add,add_zero] + +theorem hyb_entry_25_2 (x y z : ℂ) : + hybLeft x y z .minus .minus .plus .zero .zero .minus = hybRight x y z .minus .minus .plus .zero .zero .minus := by + simp only [hybLeft,hybRight,sum_spin,exchangeNumerator_eq_table,exchangeTable, + mul_zero,zero_mul,zero_add,add_zero] + all_goals ring_nf + all_goals try simp only [q_pow_9,q_pow_11,q_pow_13,q_pow_15,q_pow_17] + all_goals ring + +theorem hyb_entry_25_3 (x y z : ℂ) : + hybLeft x y z .minus .minus .plus .zero .plus .zero = hybRight x y z .minus .minus .plus .zero .plus .zero := by + simp only [hybLeft,hybRight,sum_spin,exchangeNumerator_eq_table,exchangeTable, + mul_zero,zero_mul,zero_add,add_zero] + +theorem hyb_entry_25_4 (x y z : ℂ) : + hybLeft x y z .minus .minus .plus .zero .plus .plus = hybRight x y z .minus .minus .plus .zero .plus .plus := by + simp only [hybLeft,hybRight,sum_spin,exchangeNumerator_eq_table,exchangeTable, + mul_zero,zero_mul,zero_add,add_zero] + +theorem hyb_entry_25_5 (x y z : ℂ) : + hybLeft x y z .minus .minus .plus .zero .plus .minus = hybRight x y z .minus .minus .plus .zero .plus .minus := by + simp only [hybLeft,hybRight,sum_spin,exchangeNumerator_eq_table,exchangeTable, + mul_zero,zero_mul,zero_add,add_zero] + +theorem hyb_entry_25_6 (x y z : ℂ) : + hybLeft x y z .minus .minus .plus .zero .minus .zero = hybRight x y z .minus .minus .plus .zero .minus .zero := by + simp only [hybLeft,hybRight,sum_spin,exchangeNumerator_eq_table,exchangeTable, + mul_zero,zero_mul,zero_add,add_zero] + all_goals ring_nf + all_goals try simp only [q_pow_9,q_pow_11,q_pow_13] + all_goals ring + +theorem hyb_entry_25_7 (x y z : ℂ) : + hybLeft x y z .minus .minus .plus .zero .minus .plus = hybRight x y z .minus .minus .plus .zero .minus .plus := by + simp only [hybLeft,hybRight,sum_spin,exchangeNumerator_eq_table,exchangeTable, + mul_zero,zero_mul,zero_add,add_zero] + +theorem hyb_entry_25_8 (x y z : ℂ) : + hybLeft x y z .minus .minus .plus .zero .minus .minus = hybRight x y z .minus .minus .plus .zero .minus .minus := by + simp only [hybLeft,hybRight,sum_spin,exchangeNumerator_eq_table,exchangeTable, + mul_zero,zero_mul,zero_add,add_zero] + +theorem hyb_entry_25_9 (x y z : ℂ) : + hybLeft x y z .minus .minus .plus .plus .zero .zero = hybRight x y z .minus .minus .plus .plus .zero .zero := by + simp only [hybLeft,hybRight,sum_spin,exchangeNumerator_eq_table,exchangeTable, + mul_zero,zero_mul,zero_add,add_zero] + +theorem hyb_entry_25_10 (x y z : ℂ) : + hybLeft x y z .minus .minus .plus .plus .zero .plus = hybRight x y z .minus .minus .plus .plus .zero .plus := by + simp only [hybLeft,hybRight,sum_spin,exchangeNumerator_eq_table,exchangeTable, + mul_zero,zero_mul,add_zero] + +theorem hyb_entry_25_11 (x y z : ℂ) : + hybLeft x y z .minus .minus .plus .plus .zero .minus = hybRight x y z .minus .minus .plus .plus .zero .minus := by + simp only [hybLeft,hybRight,sum_spin,exchangeNumerator_eq_table,exchangeTable, + mul_zero,zero_mul,zero_add,add_zero] + +theorem hyb_entry_25_12 (x y z : ℂ) : + hybLeft x y z .minus .minus .plus .plus .plus .zero = hybRight x y z .minus .minus .plus .plus .plus .zero := by + simp only [hybLeft,hybRight,sum_spin,exchangeNumerator_eq_table,exchangeTable, + mul_zero,zero_mul,zero_add,add_zero] + +theorem hyb_entry_25_13 (x y z : ℂ) : + hybLeft x y z .minus .minus .plus .plus .plus .plus = hybRight x y z .minus .minus .plus .plus .plus .plus := by + simp only [hybLeft,hybRight,sum_spin,exchangeNumerator_eq_table,exchangeTable, + mul_zero,zero_mul,zero_add,add_zero] + +theorem hyb_entry_25_14 (x y z : ℂ) : + hybLeft x y z .minus .minus .plus .plus .plus .minus = hybRight x y z .minus .minus .plus .plus .plus .minus := by + simp only [hybLeft,hybRight,sum_spin,exchangeNumerator_eq_table,exchangeTable, + mul_zero,zero_mul,zero_add,add_zero] + +theorem hyb_entry_25_15 (x y z : ℂ) : + hybLeft x y z .minus .minus .plus .plus .minus .zero = hybRight x y z .minus .minus .plus .plus .minus .zero := by + simp only [hybLeft,hybRight,sum_spin,exchangeNumerator_eq_table,exchangeTable, + mul_zero,zero_mul,zero_add,add_zero] + +theorem hyb_entry_25_16 (x y z : ℂ) : + hybLeft x y z .minus .minus .plus .plus .minus .plus = hybRight x y z .minus .minus .plus .plus .minus .plus := by + simp only [hybLeft,hybRight,sum_spin,exchangeNumerator_eq_table,exchangeTable, + mul_zero,zero_mul,zero_add,add_zero] + +theorem hyb_entry_25_17 (x y z : ℂ) : + hybLeft x y z .minus .minus .plus .plus .minus .minus = hybRight x y z .minus .minus .plus .plus .minus .minus := by + simp only [hybLeft,hybRight,sum_spin,exchangeNumerator_eq_table,exchangeTable, + mul_zero,zero_mul,zero_add,add_zero] + all_goals ring_nf + +theorem hyb_entry_25_18 (x y z : ℂ) : + hybLeft x y z .minus .minus .plus .minus .zero .zero = hybRight x y z .minus .minus .plus .minus .zero .zero := by + simp only [hybLeft,hybRight,sum_spin,exchangeNumerator_eq_table,exchangeTable, + mul_zero,zero_mul,zero_add,add_zero] + all_goals ring_nf + all_goals try simp only [q_pow_9,q_pow_11,q_pow_13,q_pow_15,q_pow_17] + all_goals ring + +theorem hyb_entry_25_19 (x y z : ℂ) : + hybLeft x y z .minus .minus .plus .minus .zero .plus = hybRight x y z .minus .minus .plus .minus .zero .plus := by + simp only [hybLeft,hybRight,sum_spin,exchangeNumerator_eq_table,exchangeTable, + mul_zero,zero_mul,zero_add,add_zero] + +theorem hyb_entry_25_20 (x y z : ℂ) : + hybLeft x y z .minus .minus .plus .minus .zero .minus = hybRight x y z .minus .minus .plus .minus .zero .minus := by + simp only [hybLeft,hybRight,sum_spin,exchangeNumerator_eq_table,exchangeTable, + mul_zero,zero_mul,zero_add,add_zero] + +theorem hyb_entry_25_21 (x y z : ℂ) : + hybLeft x y z .minus .minus .plus .minus .plus .zero = hybRight x y z .minus .minus .plus .minus .plus .zero := by + simp only [hybLeft,hybRight,sum_spin,exchangeNumerator_eq_table,exchangeTable, + mul_zero,zero_mul,zero_add,add_zero] + +theorem hyb_entry_25_22 (x y z : ℂ) : + hybLeft x y z .minus .minus .plus .minus .plus .plus = hybRight x y z .minus .minus .plus .minus .plus .plus := by + simp only [hybLeft,hybRight,sum_spin,exchangeNumerator_eq_table,exchangeTable, + mul_zero,zero_mul,zero_add,add_zero] + +theorem hyb_entry_25_23 (x y z : ℂ) : + hybLeft x y z .minus .minus .plus .minus .plus .minus = hybRight x y z .minus .minus .plus .minus .plus .minus := by + simp only [hybLeft,hybRight,sum_spin,exchangeNumerator_eq_table,exchangeTable, + mul_zero,zero_mul,zero_add,add_zero] + all_goals ring_nf + all_goals try simp only [q_pow_eight,q_pow_10,q_pow_12,q_pow_14,q_pow_16,q_pow_18] + all_goals ring + +theorem hyb_entry_25_24 (x y z : ℂ) : + hybLeft x y z .minus .minus .plus .minus .minus .zero = hybRight x y z .minus .minus .plus .minus .minus .zero := by + simp only [hybLeft,hybRight,sum_spin,exchangeNumerator_eq_table,exchangeTable, + mul_zero,zero_mul,zero_add,add_zero] + +theorem hyb_entry_25_25 (x y z : ℂ) : + hybLeft x y z .minus .minus .plus .minus .minus .plus = hybRight x y z .minus .minus .plus .minus .minus .plus := by + simp only [hybLeft,hybRight,sum_spin,exchangeNumerator_eq_table,exchangeTable, + mul_zero,zero_mul,zero_add,add_zero] + all_goals ring_nf + all_goals try simp only [q_pow_eight,q_pow_10,q_pow_12,q_pow_14,q_pow_16,q_pow_18] + all_goals ring + +theorem hyb_entry_25_26 (x y z : ℂ) : + hybLeft x y z .minus .minus .plus .minus .minus .minus = hybRight x y z .minus .minus .plus .minus .minus .minus := by + simp only [hybLeft,hybRight,sum_spin,exchangeNumerator_eq_table,exchangeTable, + mul_zero,zero_mul,zero_add,add_zero] + +theorem hyb_entry_26_0 (x y z : ℂ) : + hybLeft x y z .minus .minus .minus .zero .zero .zero = hybRight x y z .minus .minus .minus .zero .zero .zero := by + simp only [hybLeft,hybRight,sum_spin,exchangeNumerator_eq_table,exchangeTable, + mul_zero,zero_mul,zero_add,add_zero] + +theorem hyb_entry_26_1 (x y z : ℂ) : + hybLeft x y z .minus .minus .minus .zero .zero .plus = hybRight x y z .minus .minus .minus .zero .zero .plus := by + simp only [hybLeft,hybRight,sum_spin,exchangeNumerator_eq_table,exchangeTable, + mul_zero,zero_mul,zero_add,add_zero] + +theorem hyb_entry_26_2 (x y z : ℂ) : + hybLeft x y z .minus .minus .minus .zero .zero .minus = hybRight x y z .minus .minus .minus .zero .zero .minus := by + simp only [hybLeft,hybRight,sum_spin,exchangeNumerator_eq_table,exchangeTable, + mul_zero,zero_mul,zero_add,add_zero] + +theorem hyb_entry_26_3 (x y z : ℂ) : + hybLeft x y z .minus .minus .minus .zero .plus .zero = hybRight x y z .minus .minus .minus .zero .plus .zero := by + simp only [hybLeft,hybRight,sum_spin,exchangeNumerator_eq_table,exchangeTable, + mul_zero,zero_mul,add_zero] + +theorem hyb_entry_26_4 (x y z : ℂ) : + hybLeft x y z .minus .minus .minus .zero .plus .plus = hybRight x y z .minus .minus .minus .zero .plus .plus := by + simp only [hybLeft,hybRight,sum_spin,exchangeNumerator_eq_table,exchangeTable, + mul_zero,zero_mul,add_zero] + +theorem hyb_entry_26_5 (x y z : ℂ) : + hybLeft x y z .minus .minus .minus .zero .plus .minus = hybRight x y z .minus .minus .minus .zero .plus .minus := by + simp only [hybLeft,hybRight,sum_spin,exchangeNumerator_eq_table,exchangeTable, + mul_zero,zero_mul,zero_add,add_zero] + +theorem hyb_entry_26_6 (x y z : ℂ) : + hybLeft x y z .minus .minus .minus .zero .minus .zero = hybRight x y z .minus .minus .minus .zero .minus .zero := by + simp only [hybLeft,hybRight,sum_spin,exchangeNumerator_eq_table,exchangeTable, + mul_zero,zero_mul,zero_add,add_zero] + +theorem hyb_entry_26_7 (x y z : ℂ) : + hybLeft x y z .minus .minus .minus .zero .minus .plus = hybRight x y z .minus .minus .minus .zero .minus .plus := by + simp only [hybLeft,hybRight,sum_spin,exchangeNumerator_eq_table,exchangeTable, + mul_zero,zero_mul,zero_add,add_zero] + +theorem hyb_entry_26_8 (x y z : ℂ) : + hybLeft x y z .minus .minus .minus .zero .minus .minus = hybRight x y z .minus .minus .minus .zero .minus .minus := by + simp only [hybLeft,hybRight,sum_spin,exchangeNumerator_eq_table,exchangeTable, + mul_zero,zero_mul,zero_add,add_zero] + +theorem hyb_entry_26_9 (x y z : ℂ) : + hybLeft x y z .minus .minus .minus .plus .zero .zero = hybRight x y z .minus .minus .minus .plus .zero .zero := by + simp only [hybLeft,hybRight,sum_spin,exchangeNumerator_eq_table,exchangeTable, + mul_zero,zero_mul,zero_add,add_zero] + +theorem hyb_entry_26_10 (x y z : ℂ) : + hybLeft x y z .minus .minus .minus .plus .zero .plus = hybRight x y z .minus .minus .minus .plus .zero .plus := by + simp only [hybLeft,hybRight,sum_spin,exchangeNumerator_eq_table,exchangeTable, + mul_zero,zero_mul,add_zero] + +theorem hyb_entry_26_11 (x y z : ℂ) : + hybLeft x y z .minus .minus .minus .plus .zero .minus = hybRight x y z .minus .minus .minus .plus .zero .minus := by + simp only [hybLeft,hybRight,sum_spin,exchangeNumerator_eq_table,exchangeTable, + mul_zero,zero_mul,zero_add,add_zero] + +theorem hyb_entry_26_12 (x y z : ℂ) : + hybLeft x y z .minus .minus .minus .plus .plus .zero = hybRight x y z .minus .minus .minus .plus .plus .zero := by + simp only [hybLeft,hybRight,sum_spin,exchangeNumerator_eq_table,exchangeTable, + mul_zero,zero_mul,add_zero] + +theorem hyb_entry_26_13 (x y z : ℂ) : + hybLeft x y z .minus .minus .minus .plus .plus .plus = hybRight x y z .minus .minus .minus .plus .plus .plus := by + simp only [hybLeft,hybRight,sum_spin,exchangeNumerator_eq_table,exchangeTable, + mul_zero,zero_mul,add_zero] + +theorem hyb_entry_26_14 (x y z : ℂ) : + hybLeft x y z .minus .minus .minus .plus .plus .minus = hybRight x y z .minus .minus .minus .plus .plus .minus := by + simp only [hybLeft,hybRight,sum_spin,exchangeNumerator_eq_table,exchangeTable, + mul_zero,zero_mul,zero_add,add_zero] + +theorem hyb_entry_26_15 (x y z : ℂ) : + hybLeft x y z .minus .minus .minus .plus .minus .zero = hybRight x y z .minus .minus .minus .plus .minus .zero := by + simp only [hybLeft,hybRight,sum_spin,exchangeNumerator_eq_table,exchangeTable, + mul_zero,zero_mul,zero_add,add_zero] + +theorem hyb_entry_26_16 (x y z : ℂ) : + hybLeft x y z .minus .minus .minus .plus .minus .plus = hybRight x y z .minus .minus .minus .plus .minus .plus := by + simp only [hybLeft,hybRight,sum_spin,exchangeNumerator_eq_table,exchangeTable, + mul_zero,zero_mul,zero_add,add_zero] + +theorem hyb_entry_26_17 (x y z : ℂ) : + hybLeft x y z .minus .minus .minus .plus .minus .minus = hybRight x y z .minus .minus .minus .plus .minus .minus := by + simp only [hybLeft,hybRight,sum_spin,exchangeNumerator_eq_table,exchangeTable, + mul_zero,zero_mul,zero_add,add_zero] + +theorem hyb_entry_26_18 (x y z : ℂ) : + hybLeft x y z .minus .minus .minus .minus .zero .zero = hybRight x y z .minus .minus .minus .minus .zero .zero := by + simp only [hybLeft,hybRight,sum_spin,exchangeNumerator_eq_table,exchangeTable, + mul_zero,zero_mul,zero_add,add_zero] + +theorem hyb_entry_26_19 (x y z : ℂ) : + hybLeft x y z .minus .minus .minus .minus .zero .plus = hybRight x y z .minus .minus .minus .minus .zero .plus := by + simp only [hybLeft,hybRight,sum_spin,exchangeNumerator_eq_table,exchangeTable, + mul_zero,zero_mul,zero_add,add_zero] + +theorem hyb_entry_26_20 (x y z : ℂ) : + hybLeft x y z .minus .minus .minus .minus .zero .minus = hybRight x y z .minus .minus .minus .minus .zero .minus := by + simp only [hybLeft,hybRight,sum_spin,exchangeNumerator_eq_table,exchangeTable, + mul_zero,zero_mul,zero_add,add_zero] + +theorem hyb_entry_26_21 (x y z : ℂ) : + hybLeft x y z .minus .minus .minus .minus .plus .zero = hybRight x y z .minus .minus .minus .minus .plus .zero := by + simp only [hybLeft,hybRight,sum_spin,exchangeNumerator_eq_table,exchangeTable, + mul_zero,zero_mul,add_zero] + +theorem hyb_entry_26_22 (x y z : ℂ) : + hybLeft x y z .minus .minus .minus .minus .plus .plus = hybRight x y z .minus .minus .minus .minus .plus .plus := by + simp only [hybLeft,hybRight,sum_spin,exchangeNumerator_eq_table,exchangeTable, + mul_zero,zero_mul,zero_add,add_zero] + +theorem hyb_entry_26_23 (x y z : ℂ) : + hybLeft x y z .minus .minus .minus .minus .plus .minus = hybRight x y z .minus .minus .minus .minus .plus .minus := by + simp only [hybLeft,hybRight,sum_spin,exchangeNumerator_eq_table,exchangeTable, + mul_zero,zero_mul,zero_add,add_zero] + +theorem hyb_entry_26_24 (x y z : ℂ) : + hybLeft x y z .minus .minus .minus .minus .minus .zero = hybRight x y z .minus .minus .minus .minus .minus .zero := by + simp only [hybLeft,hybRight,sum_spin,exchangeNumerator_eq_table,exchangeTable, + mul_zero,zero_mul,zero_add,add_zero] + +theorem hyb_entry_26_25 (x y z : ℂ) : + hybLeft x y z .minus .minus .minus .minus .minus .plus = hybRight x y z .minus .minus .minus .minus .minus .plus := by + simp only [hybLeft,hybRight,sum_spin,exchangeNumerator_eq_table,exchangeTable, + mul_zero,zero_mul,zero_add,add_zero] + +theorem hyb_entry_26_26 (x y z : ℂ) : + hybLeft x y z .minus .minus .minus .minus .minus .minus = hybRight x y z .minus .minus .minus .minus .minus .minus := by + simp only [hybLeft,hybRight,sum_spin,exchangeNumerator_eq_table,exchangeTable, + mul_zero,zero_mul,zero_add,add_zero] + all_goals ring_nf + +theorem hyb_output_0 (x y z : ℂ) (d e f : Spin) : + hybLeft x y z .zero .zero .zero d e f = hybRight x y z .zero .zero .zero d e f := by + cases d <;> cases e <;> cases f + · exact hyb_entry_0_0 x y z + · exact hyb_entry_0_1 x y z + · exact hyb_entry_0_2 x y z + · exact hyb_entry_0_3 x y z + · exact hyb_entry_0_4 x y z + · exact hyb_entry_0_5 x y z + · exact hyb_entry_0_6 x y z + · exact hyb_entry_0_7 x y z + · exact hyb_entry_0_8 x y z + · exact hyb_entry_0_9 x y z + · exact hyb_entry_0_10 x y z + · exact hyb_entry_0_11 x y z + · exact hyb_entry_0_12 x y z + · exact hyb_entry_0_13 x y z + · exact hyb_entry_0_14 x y z + · exact hyb_entry_0_15 x y z + · exact hyb_entry_0_16 x y z + · exact hyb_entry_0_17 x y z + · exact hyb_entry_0_18 x y z + · exact hyb_entry_0_19 x y z + · exact hyb_entry_0_20 x y z + · exact hyb_entry_0_21 x y z + · exact hyb_entry_0_22 x y z + · exact hyb_entry_0_23 x y z + · exact hyb_entry_0_24 x y z + · exact hyb_entry_0_25 x y z + · exact hyb_entry_0_26 x y z + +theorem hyb_output_1 (x y z : ℂ) (d e f : Spin) : + hybLeft x y z .zero .zero .plus d e f = hybRight x y z .zero .zero .plus d e f := by + cases d <;> cases e <;> cases f + · exact hyb_entry_1_0 x y z + · exact hyb_entry_1_1 x y z + · exact hyb_entry_1_2 x y z + · exact hyb_entry_1_3 x y z + · exact hyb_entry_1_4 x y z + · exact hyb_entry_1_5 x y z + · exact hyb_entry_1_6 x y z + · exact hyb_entry_1_7 x y z + · exact hyb_entry_1_8 x y z + · exact hyb_entry_1_9 x y z + · exact hyb_entry_1_10 x y z + · exact hyb_entry_1_11 x y z + · exact hyb_entry_1_12 x y z + · exact hyb_entry_1_13 x y z + · exact hyb_entry_1_14 x y z + · exact hyb_entry_1_15 x y z + · exact hyb_entry_1_16 x y z + · exact hyb_entry_1_17 x y z + · exact hyb_entry_1_18 x y z + · exact hyb_entry_1_19 x y z + · exact hyb_entry_1_20 x y z + · exact hyb_entry_1_21 x y z + · exact hyb_entry_1_22 x y z + · exact hyb_entry_1_23 x y z + · exact hyb_entry_1_24 x y z + · exact hyb_entry_1_25 x y z + · exact hyb_entry_1_26 x y z + +theorem hyb_output_2 (x y z : ℂ) (d e f : Spin) : + hybLeft x y z .zero .zero .minus d e f = hybRight x y z .zero .zero .minus d e f := by + cases d <;> cases e <;> cases f + · exact hyb_entry_2_0 x y z + · exact hyb_entry_2_1 x y z + · exact hyb_entry_2_2 x y z + · exact hyb_entry_2_3 x y z + · exact hyb_entry_2_4 x y z + · exact hyb_entry_2_5 x y z + · exact hyb_entry_2_6 x y z + · exact hyb_entry_2_7 x y z + · exact hyb_entry_2_8 x y z + · exact hyb_entry_2_9 x y z + · exact hyb_entry_2_10 x y z + · exact hyb_entry_2_11 x y z + · exact hyb_entry_2_12 x y z + · exact hyb_entry_2_13 x y z + · exact hyb_entry_2_14 x y z + · exact hyb_entry_2_15 x y z + · exact hyb_entry_2_16 x y z + · exact hyb_entry_2_17 x y z + · exact hyb_entry_2_18 x y z + · exact hyb_entry_2_19 x y z + · exact hyb_entry_2_20 x y z + · exact hyb_entry_2_21 x y z + · exact hyb_entry_2_22 x y z + · exact hyb_entry_2_23 x y z + · exact hyb_entry_2_24 x y z + · exact hyb_entry_2_25 x y z + · exact hyb_entry_2_26 x y z + +theorem hyb_output_3 (x y z : ℂ) (d e f : Spin) : + hybLeft x y z .zero .plus .zero d e f = hybRight x y z .zero .plus .zero d e f := by + cases d <;> cases e <;> cases f + · exact hyb_entry_3_0 x y z + · exact hyb_entry_3_1 x y z + · exact hyb_entry_3_2 x y z + · exact hyb_entry_3_3 x y z + · exact hyb_entry_3_4 x y z + · exact hyb_entry_3_5 x y z + · exact hyb_entry_3_6 x y z + · exact hyb_entry_3_7 x y z + · exact hyb_entry_3_8 x y z + · exact hyb_entry_3_9 x y z + · exact hyb_entry_3_10 x y z + · exact hyb_entry_3_11 x y z + · exact hyb_entry_3_12 x y z + · exact hyb_entry_3_13 x y z + · exact hyb_entry_3_14 x y z + · exact hyb_entry_3_15 x y z + · exact hyb_entry_3_16 x y z + · exact hyb_entry_3_17 x y z + · exact hyb_entry_3_18 x y z + · exact hyb_entry_3_19 x y z + · exact hyb_entry_3_20 x y z + · exact hyb_entry_3_21 x y z + · exact hyb_entry_3_22 x y z + · exact hyb_entry_3_23 x y z + · exact hyb_entry_3_24 x y z + · exact hyb_entry_3_25 x y z + · exact hyb_entry_3_26 x y z + +theorem hyb_output_4 (x y z : ℂ) (d e f : Spin) : + hybLeft x y z .zero .plus .plus d e f = hybRight x y z .zero .plus .plus d e f := by + cases d <;> cases e <;> cases f + · exact hyb_entry_4_0 x y z + · exact hyb_entry_4_1 x y z + · exact hyb_entry_4_2 x y z + · exact hyb_entry_4_3 x y z + · exact hyb_entry_4_4 x y z + · exact hyb_entry_4_5 x y z + · exact hyb_entry_4_6 x y z + · exact hyb_entry_4_7 x y z + · exact hyb_entry_4_8 x y z + · exact hyb_entry_4_9 x y z + · exact hyb_entry_4_10 x y z + · exact hyb_entry_4_11 x y z + · exact hyb_entry_4_12 x y z + · exact hyb_entry_4_13 x y z + · exact hyb_entry_4_14 x y z + · exact hyb_entry_4_15 x y z + · exact hyb_entry_4_16 x y z + · exact hyb_entry_4_17 x y z + · exact hyb_entry_4_18 x y z + · exact hyb_entry_4_19 x y z + · exact hyb_entry_4_20 x y z + · exact hyb_entry_4_21 x y z + · exact hyb_entry_4_22 x y z + · exact hyb_entry_4_23 x y z + · exact hyb_entry_4_24 x y z + · exact hyb_entry_4_25 x y z + · exact hyb_entry_4_26 x y z + +theorem hyb_output_5 (x y z : ℂ) (d e f : Spin) : + hybLeft x y z .zero .plus .minus d e f = hybRight x y z .zero .plus .minus d e f := by + cases d <;> cases e <;> cases f + · exact hyb_entry_5_0 x y z + · exact hyb_entry_5_1 x y z + · exact hyb_entry_5_2 x y z + · exact hyb_entry_5_3 x y z + · exact hyb_entry_5_4 x y z + · exact hyb_entry_5_5 x y z + · exact hyb_entry_5_6 x y z + · exact hyb_entry_5_7 x y z + · exact hyb_entry_5_8 x y z + · exact hyb_entry_5_9 x y z + · exact hyb_entry_5_10 x y z + · exact hyb_entry_5_11 x y z + · exact hyb_entry_5_12 x y z + · exact hyb_entry_5_13 x y z + · exact hyb_entry_5_14 x y z + · exact hyb_entry_5_15 x y z + · exact hyb_entry_5_16 x y z + · exact hyb_entry_5_17 x y z + · exact hyb_entry_5_18 x y z + · exact hyb_entry_5_19 x y z + · exact hyb_entry_5_20 x y z + · exact hyb_entry_5_21 x y z + · exact hyb_entry_5_22 x y z + · exact hyb_entry_5_23 x y z + · exact hyb_entry_5_24 x y z + · exact hyb_entry_5_25 x y z + · exact hyb_entry_5_26 x y z + +theorem hyb_output_6 (x y z : ℂ) (d e f : Spin) : + hybLeft x y z .zero .minus .zero d e f = hybRight x y z .zero .minus .zero d e f := by + cases d <;> cases e <;> cases f + · exact hyb_entry_6_0 x y z + · exact hyb_entry_6_1 x y z + · exact hyb_entry_6_2 x y z + · exact hyb_entry_6_3 x y z + · exact hyb_entry_6_4 x y z + · exact hyb_entry_6_5 x y z + · exact hyb_entry_6_6 x y z + · exact hyb_entry_6_7 x y z + · exact hyb_entry_6_8 x y z + · exact hyb_entry_6_9 x y z + · exact hyb_entry_6_10 x y z + · exact hyb_entry_6_11 x y z + · exact hyb_entry_6_12 x y z + · exact hyb_entry_6_13 x y z + · exact hyb_entry_6_14 x y z + · exact hyb_entry_6_15 x y z + · exact hyb_entry_6_16 x y z + · exact hyb_entry_6_17 x y z + · exact hyb_entry_6_18 x y z + · exact hyb_entry_6_19 x y z + · exact hyb_entry_6_20 x y z + · exact hyb_entry_6_21 x y z + · exact hyb_entry_6_22 x y z + · exact hyb_entry_6_23 x y z + · exact hyb_entry_6_24 x y z + · exact hyb_entry_6_25 x y z + · exact hyb_entry_6_26 x y z + +theorem hyb_output_7 (x y z : ℂ) (d e f : Spin) : + hybLeft x y z .zero .minus .plus d e f = hybRight x y z .zero .minus .plus d e f := by + cases d <;> cases e <;> cases f + · exact hyb_entry_7_0 x y z + · exact hyb_entry_7_1 x y z + · exact hyb_entry_7_2 x y z + · exact hyb_entry_7_3 x y z + · exact hyb_entry_7_4 x y z + · exact hyb_entry_7_5 x y z + · exact hyb_entry_7_6 x y z + · exact hyb_entry_7_7 x y z + · exact hyb_entry_7_8 x y z + · exact hyb_entry_7_9 x y z + · exact hyb_entry_7_10 x y z + · exact hyb_entry_7_11 x y z + · exact hyb_entry_7_12 x y z + · exact hyb_entry_7_13 x y z + · exact hyb_entry_7_14 x y z + · exact hyb_entry_7_15 x y z + · exact hyb_entry_7_16 x y z + · exact hyb_entry_7_17 x y z + · exact hyb_entry_7_18 x y z + · exact hyb_entry_7_19 x y z + · exact hyb_entry_7_20 x y z + · exact hyb_entry_7_21 x y z + · exact hyb_entry_7_22 x y z + · exact hyb_entry_7_23 x y z + · exact hyb_entry_7_24 x y z + · exact hyb_entry_7_25 x y z + · exact hyb_entry_7_26 x y z + +theorem hyb_output_8 (x y z : ℂ) (d e f : Spin) : + hybLeft x y z .zero .minus .minus d e f = hybRight x y z .zero .minus .minus d e f := by + cases d <;> cases e <;> cases f + · exact hyb_entry_8_0 x y z + · exact hyb_entry_8_1 x y z + · exact hyb_entry_8_2 x y z + · exact hyb_entry_8_3 x y z + · exact hyb_entry_8_4 x y z + · exact hyb_entry_8_5 x y z + · exact hyb_entry_8_6 x y z + · exact hyb_entry_8_7 x y z + · exact hyb_entry_8_8 x y z + · exact hyb_entry_8_9 x y z + · exact hyb_entry_8_10 x y z + · exact hyb_entry_8_11 x y z + · exact hyb_entry_8_12 x y z + · exact hyb_entry_8_13 x y z + · exact hyb_entry_8_14 x y z + · exact hyb_entry_8_15 x y z + · exact hyb_entry_8_16 x y z + · exact hyb_entry_8_17 x y z + · exact hyb_entry_8_18 x y z + · exact hyb_entry_8_19 x y z + · exact hyb_entry_8_20 x y z + · exact hyb_entry_8_21 x y z + · exact hyb_entry_8_22 x y z + · exact hyb_entry_8_23 x y z + · exact hyb_entry_8_24 x y z + · exact hyb_entry_8_25 x y z + · exact hyb_entry_8_26 x y z + +theorem hyb_output_9 (x y z : ℂ) (d e f : Spin) : + hybLeft x y z .plus .zero .zero d e f = hybRight x y z .plus .zero .zero d e f := by + cases d <;> cases e <;> cases f + · exact hyb_entry_9_0 x y z + · exact hyb_entry_9_1 x y z + · exact hyb_entry_9_2 x y z + · exact hyb_entry_9_3 x y z + · exact hyb_entry_9_4 x y z + · exact hyb_entry_9_5 x y z + · exact hyb_entry_9_6 x y z + · exact hyb_entry_9_7 x y z + · exact hyb_entry_9_8 x y z + · exact hyb_entry_9_9 x y z + · exact hyb_entry_9_10 x y z + · exact hyb_entry_9_11 x y z + · exact hyb_entry_9_12 x y z + · exact hyb_entry_9_13 x y z + · exact hyb_entry_9_14 x y z + · exact hyb_entry_9_15 x y z + · exact hyb_entry_9_16 x y z + · exact hyb_entry_9_17 x y z + · exact hyb_entry_9_18 x y z + · exact hyb_entry_9_19 x y z + · exact hyb_entry_9_20 x y z + · exact hyb_entry_9_21 x y z + · exact hyb_entry_9_22 x y z + · exact hyb_entry_9_23 x y z + · exact hyb_entry_9_24 x y z + · exact hyb_entry_9_25 x y z + · exact hyb_entry_9_26 x y z + +theorem hyb_output_10 (x y z : ℂ) (d e f : Spin) : + hybLeft x y z .plus .zero .plus d e f = hybRight x y z .plus .zero .plus d e f := by + cases d <;> cases e <;> cases f + · exact hyb_entry_10_0 x y z + · exact hyb_entry_10_1 x y z + · exact hyb_entry_10_2 x y z + · exact hyb_entry_10_3 x y z + · exact hyb_entry_10_4 x y z + · exact hyb_entry_10_5 x y z + · exact hyb_entry_10_6 x y z + · exact hyb_entry_10_7 x y z + · exact hyb_entry_10_8 x y z + · exact hyb_entry_10_9 x y z + · exact hyb_entry_10_10 x y z + · exact hyb_entry_10_11 x y z + · exact hyb_entry_10_12 x y z + · exact hyb_entry_10_13 x y z + · exact hyb_entry_10_14 x y z + · exact hyb_entry_10_15 x y z + · exact hyb_entry_10_16 x y z + · exact hyb_entry_10_17 x y z + · exact hyb_entry_10_18 x y z + · exact hyb_entry_10_19 x y z + · exact hyb_entry_10_20 x y z + · exact hyb_entry_10_21 x y z + · exact hyb_entry_10_22 x y z + · exact hyb_entry_10_23 x y z + · exact hyb_entry_10_24 x y z + · exact hyb_entry_10_25 x y z + · exact hyb_entry_10_26 x y z + +theorem hyb_output_11 (x y z : ℂ) (d e f : Spin) : + hybLeft x y z .plus .zero .minus d e f = hybRight x y z .plus .zero .minus d e f := by + cases d <;> cases e <;> cases f + · exact hyb_entry_11_0 x y z + · exact hyb_entry_11_1 x y z + · exact hyb_entry_11_2 x y z + · exact hyb_entry_11_3 x y z + · exact hyb_entry_11_4 x y z + · exact hyb_entry_11_5 x y z + · exact hyb_entry_11_6 x y z + · exact hyb_entry_11_7 x y z + · exact hyb_entry_11_8 x y z + · exact hyb_entry_11_9 x y z + · exact hyb_entry_11_10 x y z + · exact hyb_entry_11_11 x y z + · exact hyb_entry_11_12 x y z + · exact hyb_entry_11_13 x y z + · exact hyb_entry_11_14 x y z + · exact hyb_entry_11_15 x y z + · exact hyb_entry_11_16 x y z + · exact hyb_entry_11_17 x y z + · exact hyb_entry_11_18 x y z + · exact hyb_entry_11_19 x y z + · exact hyb_entry_11_20 x y z + · exact hyb_entry_11_21 x y z + · exact hyb_entry_11_22 x y z + · exact hyb_entry_11_23 x y z + · exact hyb_entry_11_24 x y z + · exact hyb_entry_11_25 x y z + · exact hyb_entry_11_26 x y z + +theorem hyb_output_12 (x y z : ℂ) (d e f : Spin) : + hybLeft x y z .plus .plus .zero d e f = hybRight x y z .plus .plus .zero d e f := by + cases d <;> cases e <;> cases f + · exact hyb_entry_12_0 x y z + · exact hyb_entry_12_1 x y z + · exact hyb_entry_12_2 x y z + · exact hyb_entry_12_3 x y z + · exact hyb_entry_12_4 x y z + · exact hyb_entry_12_5 x y z + · exact hyb_entry_12_6 x y z + · exact hyb_entry_12_7 x y z + · exact hyb_entry_12_8 x y z + · exact hyb_entry_12_9 x y z + · exact hyb_entry_12_10 x y z + · exact hyb_entry_12_11 x y z + · exact hyb_entry_12_12 x y z + · exact hyb_entry_12_13 x y z + · exact hyb_entry_12_14 x y z + · exact hyb_entry_12_15 x y z + · exact hyb_entry_12_16 x y z + · exact hyb_entry_12_17 x y z + · exact hyb_entry_12_18 x y z + · exact hyb_entry_12_19 x y z + · exact hyb_entry_12_20 x y z + · exact hyb_entry_12_21 x y z + · exact hyb_entry_12_22 x y z + · exact hyb_entry_12_23 x y z + · exact hyb_entry_12_24 x y z + · exact hyb_entry_12_25 x y z + · exact hyb_entry_12_26 x y z + +theorem hyb_output_13 (x y z : ℂ) (d e f : Spin) : + hybLeft x y z .plus .plus .plus d e f = hybRight x y z .plus .plus .plus d e f := by + cases d <;> cases e <;> cases f + · exact hyb_entry_13_0 x y z + · exact hyb_entry_13_1 x y z + · exact hyb_entry_13_2 x y z + · exact hyb_entry_13_3 x y z + · exact hyb_entry_13_4 x y z + · exact hyb_entry_13_5 x y z + · exact hyb_entry_13_6 x y z + · exact hyb_entry_13_7 x y z + · exact hyb_entry_13_8 x y z + · exact hyb_entry_13_9 x y z + · exact hyb_entry_13_10 x y z + · exact hyb_entry_13_11 x y z + · exact hyb_entry_13_12 x y z + · exact hyb_entry_13_13 x y z + · exact hyb_entry_13_14 x y z + · exact hyb_entry_13_15 x y z + · exact hyb_entry_13_16 x y z + · exact hyb_entry_13_17 x y z + · exact hyb_entry_13_18 x y z + · exact hyb_entry_13_19 x y z + · exact hyb_entry_13_20 x y z + · exact hyb_entry_13_21 x y z + · exact hyb_entry_13_22 x y z + · exact hyb_entry_13_23 x y z + · exact hyb_entry_13_24 x y z + · exact hyb_entry_13_25 x y z + · exact hyb_entry_13_26 x y z + +theorem hyb_output_14 (x y z : ℂ) (d e f : Spin) : + hybLeft x y z .plus .plus .minus d e f = hybRight x y z .plus .plus .minus d e f := by + cases d <;> cases e <;> cases f + · exact hyb_entry_14_0 x y z + · exact hyb_entry_14_1 x y z + · exact hyb_entry_14_2 x y z + · exact hyb_entry_14_3 x y z + · exact hyb_entry_14_4 x y z + · exact hyb_entry_14_5 x y z + · exact hyb_entry_14_6 x y z + · exact hyb_entry_14_7 x y z + · exact hyb_entry_14_8 x y z + · exact hyb_entry_14_9 x y z + · exact hyb_entry_14_10 x y z + · exact hyb_entry_14_11 x y z + · exact hyb_entry_14_12 x y z + · exact hyb_entry_14_13 x y z + · exact hyb_entry_14_14 x y z + · exact hyb_entry_14_15 x y z + · exact hyb_entry_14_16 x y z + · exact hyb_entry_14_17 x y z + · exact hyb_entry_14_18 x y z + · exact hyb_entry_14_19 x y z + · exact hyb_entry_14_20 x y z + · exact hyb_entry_14_21 x y z + · exact hyb_entry_14_22 x y z + · exact hyb_entry_14_23 x y z + · exact hyb_entry_14_24 x y z + · exact hyb_entry_14_25 x y z + · exact hyb_entry_14_26 x y z + +theorem hyb_output_15 (x y z : ℂ) (d e f : Spin) : + hybLeft x y z .plus .minus .zero d e f = hybRight x y z .plus .minus .zero d e f := by + cases d <;> cases e <;> cases f + · exact hyb_entry_15_0 x y z + · exact hyb_entry_15_1 x y z + · exact hyb_entry_15_2 x y z + · exact hyb_entry_15_3 x y z + · exact hyb_entry_15_4 x y z + · exact hyb_entry_15_5 x y z + · exact hyb_entry_15_6 x y z + · exact hyb_entry_15_7 x y z + · exact hyb_entry_15_8 x y z + · exact hyb_entry_15_9 x y z + · exact hyb_entry_15_10 x y z + · exact hyb_entry_15_11 x y z + · exact hyb_entry_15_12 x y z + · exact hyb_entry_15_13 x y z + · exact hyb_entry_15_14 x y z + · exact hyb_entry_15_15 x y z + · exact hyb_entry_15_16 x y z + · exact hyb_entry_15_17 x y z + · exact hyb_entry_15_18 x y z + · exact hyb_entry_15_19 x y z + · exact hyb_entry_15_20 x y z + · exact hyb_entry_15_21 x y z + · exact hyb_entry_15_22 x y z + · exact hyb_entry_15_23 x y z + · exact hyb_entry_15_24 x y z + · exact hyb_entry_15_25 x y z + · exact hyb_entry_15_26 x y z + +theorem hyb_output_16 (x y z : ℂ) (d e f : Spin) : + hybLeft x y z .plus .minus .plus d e f = hybRight x y z .plus .minus .plus d e f := by + cases d <;> cases e <;> cases f + · exact hyb_entry_16_0 x y z + · exact hyb_entry_16_1 x y z + · exact hyb_entry_16_2 x y z + · exact hyb_entry_16_3 x y z + · exact hyb_entry_16_4 x y z + · exact hyb_entry_16_5 x y z + · exact hyb_entry_16_6 x y z + · exact hyb_entry_16_7 x y z + · exact hyb_entry_16_8 x y z + · exact hyb_entry_16_9 x y z + · exact hyb_entry_16_10 x y z + · exact hyb_entry_16_11 x y z + · exact hyb_entry_16_12 x y z + · exact hyb_entry_16_13 x y z + · exact hyb_entry_16_14 x y z + · exact hyb_entry_16_15 x y z + · exact hyb_entry_16_16 x y z + · exact hyb_entry_16_17 x y z + · exact hyb_entry_16_18 x y z + · exact hyb_entry_16_19 x y z + · exact hyb_entry_16_20 x y z + · exact hyb_entry_16_21 x y z + · exact hyb_entry_16_22 x y z + · exact hyb_entry_16_23 x y z + · exact hyb_entry_16_24 x y z + · exact hyb_entry_16_25 x y z + · exact hyb_entry_16_26 x y z + +theorem hyb_output_17 (x y z : ℂ) (d e f : Spin) : + hybLeft x y z .plus .minus .minus d e f = hybRight x y z .plus .minus .minus d e f := by + cases d <;> cases e <;> cases f + · exact hyb_entry_17_0 x y z + · exact hyb_entry_17_1 x y z + · exact hyb_entry_17_2 x y z + · exact hyb_entry_17_3 x y z + · exact hyb_entry_17_4 x y z + · exact hyb_entry_17_5 x y z + · exact hyb_entry_17_6 x y z + · exact hyb_entry_17_7 x y z + · exact hyb_entry_17_8 x y z + · exact hyb_entry_17_9 x y z + · exact hyb_entry_17_10 x y z + · exact hyb_entry_17_11 x y z + · exact hyb_entry_17_12 x y z + · exact hyb_entry_17_13 x y z + · exact hyb_entry_17_14 x y z + · exact hyb_entry_17_15 x y z + · exact hyb_entry_17_16 x y z + · exact hyb_entry_17_17 x y z + · exact hyb_entry_17_18 x y z + · exact hyb_entry_17_19 x y z + · exact hyb_entry_17_20 x y z + · exact hyb_entry_17_21 x y z + · exact hyb_entry_17_22 x y z + · exact hyb_entry_17_23 x y z + · exact hyb_entry_17_24 x y z + · exact hyb_entry_17_25 x y z + · exact hyb_entry_17_26 x y z + +theorem hyb_output_18 (x y z : ℂ) (d e f : Spin) : + hybLeft x y z .minus .zero .zero d e f = hybRight x y z .minus .zero .zero d e f := by + cases d <;> cases e <;> cases f + · exact hyb_entry_18_0 x y z + · exact hyb_entry_18_1 x y z + · exact hyb_entry_18_2 x y z + · exact hyb_entry_18_3 x y z + · exact hyb_entry_18_4 x y z + · exact hyb_entry_18_5 x y z + · exact hyb_entry_18_6 x y z + · exact hyb_entry_18_7 x y z + · exact hyb_entry_18_8 x y z + · exact hyb_entry_18_9 x y z + · exact hyb_entry_18_10 x y z + · exact hyb_entry_18_11 x y z + · exact hyb_entry_18_12 x y z + · exact hyb_entry_18_13 x y z + · exact hyb_entry_18_14 x y z + · exact hyb_entry_18_15 x y z + · exact hyb_entry_18_16 x y z + · exact hyb_entry_18_17 x y z + · exact hyb_entry_18_18 x y z + · exact hyb_entry_18_19 x y z + · exact hyb_entry_18_20 x y z + · exact hyb_entry_18_21 x y z + · exact hyb_entry_18_22 x y z + · exact hyb_entry_18_23 x y z + · exact hyb_entry_18_24 x y z + · exact hyb_entry_18_25 x y z + · exact hyb_entry_18_26 x y z + +theorem hyb_output_19 (x y z : ℂ) (d e f : Spin) : + hybLeft x y z .minus .zero .plus d e f = hybRight x y z .minus .zero .plus d e f := by + cases d <;> cases e <;> cases f + · exact hyb_entry_19_0 x y z + · exact hyb_entry_19_1 x y z + · exact hyb_entry_19_2 x y z + · exact hyb_entry_19_3 x y z + · exact hyb_entry_19_4 x y z + · exact hyb_entry_19_5 x y z + · exact hyb_entry_19_6 x y z + · exact hyb_entry_19_7 x y z + · exact hyb_entry_19_8 x y z + · exact hyb_entry_19_9 x y z + · exact hyb_entry_19_10 x y z + · exact hyb_entry_19_11 x y z + · exact hyb_entry_19_12 x y z + · exact hyb_entry_19_13 x y z + · exact hyb_entry_19_14 x y z + · exact hyb_entry_19_15 x y z + · exact hyb_entry_19_16 x y z + · exact hyb_entry_19_17 x y z + · exact hyb_entry_19_18 x y z + · exact hyb_entry_19_19 x y z + · exact hyb_entry_19_20 x y z + · exact hyb_entry_19_21 x y z + · exact hyb_entry_19_22 x y z + · exact hyb_entry_19_23 x y z + · exact hyb_entry_19_24 x y z + · exact hyb_entry_19_25 x y z + · exact hyb_entry_19_26 x y z + +theorem hyb_output_20 (x y z : ℂ) (d e f : Spin) : + hybLeft x y z .minus .zero .minus d e f = hybRight x y z .minus .zero .minus d e f := by + cases d <;> cases e <;> cases f + · exact hyb_entry_20_0 x y z + · exact hyb_entry_20_1 x y z + · exact hyb_entry_20_2 x y z + · exact hyb_entry_20_3 x y z + · exact hyb_entry_20_4 x y z + · exact hyb_entry_20_5 x y z + · exact hyb_entry_20_6 x y z + · exact hyb_entry_20_7 x y z + · exact hyb_entry_20_8 x y z + · exact hyb_entry_20_9 x y z + · exact hyb_entry_20_10 x y z + · exact hyb_entry_20_11 x y z + · exact hyb_entry_20_12 x y z + · exact hyb_entry_20_13 x y z + · exact hyb_entry_20_14 x y z + · exact hyb_entry_20_15 x y z + · exact hyb_entry_20_16 x y z + · exact hyb_entry_20_17 x y z + · exact hyb_entry_20_18 x y z + · exact hyb_entry_20_19 x y z + · exact hyb_entry_20_20 x y z + · exact hyb_entry_20_21 x y z + · exact hyb_entry_20_22 x y z + · exact hyb_entry_20_23 x y z + · exact hyb_entry_20_24 x y z + · exact hyb_entry_20_25 x y z + · exact hyb_entry_20_26 x y z + +theorem hyb_output_21 (x y z : ℂ) (d e f : Spin) : + hybLeft x y z .minus .plus .zero d e f = hybRight x y z .minus .plus .zero d e f := by + cases d <;> cases e <;> cases f + · exact hyb_entry_21_0 x y z + · exact hyb_entry_21_1 x y z + · exact hyb_entry_21_2 x y z + · exact hyb_entry_21_3 x y z + · exact hyb_entry_21_4 x y z + · exact hyb_entry_21_5 x y z + · exact hyb_entry_21_6 x y z + · exact hyb_entry_21_7 x y z + · exact hyb_entry_21_8 x y z + · exact hyb_entry_21_9 x y z + · exact hyb_entry_21_10 x y z + · exact hyb_entry_21_11 x y z + · exact hyb_entry_21_12 x y z + · exact hyb_entry_21_13 x y z + · exact hyb_entry_21_14 x y z + · exact hyb_entry_21_15 x y z + · exact hyb_entry_21_16 x y z + · exact hyb_entry_21_17 x y z + · exact hyb_entry_21_18 x y z + · exact hyb_entry_21_19 x y z + · exact hyb_entry_21_20 x y z + · exact hyb_entry_21_21 x y z + · exact hyb_entry_21_22 x y z + · exact hyb_entry_21_23 x y z + · exact hyb_entry_21_24 x y z + · exact hyb_entry_21_25 x y z + · exact hyb_entry_21_26 x y z + +theorem hyb_output_22 (x y z : ℂ) (d e f : Spin) : + hybLeft x y z .minus .plus .plus d e f = hybRight x y z .minus .plus .plus d e f := by + cases d <;> cases e <;> cases f + · exact hyb_entry_22_0 x y z + · exact hyb_entry_22_1 x y z + · exact hyb_entry_22_2 x y z + · exact hyb_entry_22_3 x y z + · exact hyb_entry_22_4 x y z + · exact hyb_entry_22_5 x y z + · exact hyb_entry_22_6 x y z + · exact hyb_entry_22_7 x y z + · exact hyb_entry_22_8 x y z + · exact hyb_entry_22_9 x y z + · exact hyb_entry_22_10 x y z + · exact hyb_entry_22_11 x y z + · exact hyb_entry_22_12 x y z + · exact hyb_entry_22_13 x y z + · exact hyb_entry_22_14 x y z + · exact hyb_entry_22_15 x y z + · exact hyb_entry_22_16 x y z + · exact hyb_entry_22_17 x y z + · exact hyb_entry_22_18 x y z + · exact hyb_entry_22_19 x y z + · exact hyb_entry_22_20 x y z + · exact hyb_entry_22_21 x y z + · exact hyb_entry_22_22 x y z + · exact hyb_entry_22_23 x y z + · exact hyb_entry_22_24 x y z + · exact hyb_entry_22_25 x y z + · exact hyb_entry_22_26 x y z + +theorem hyb_output_23 (x y z : ℂ) (d e f : Spin) : + hybLeft x y z .minus .plus .minus d e f = hybRight x y z .minus .plus .minus d e f := by + cases d <;> cases e <;> cases f + · exact hyb_entry_23_0 x y z + · exact hyb_entry_23_1 x y z + · exact hyb_entry_23_2 x y z + · exact hyb_entry_23_3 x y z + · exact hyb_entry_23_4 x y z + · exact hyb_entry_23_5 x y z + · exact hyb_entry_23_6 x y z + · exact hyb_entry_23_7 x y z + · exact hyb_entry_23_8 x y z + · exact hyb_entry_23_9 x y z + · exact hyb_entry_23_10 x y z + · exact hyb_entry_23_11 x y z + · exact hyb_entry_23_12 x y z + · exact hyb_entry_23_13 x y z + · exact hyb_entry_23_14 x y z + · exact hyb_entry_23_15 x y z + · exact hyb_entry_23_16 x y z + · exact hyb_entry_23_17 x y z + · exact hyb_entry_23_18 x y z + · exact hyb_entry_23_19 x y z + · exact hyb_entry_23_20 x y z + · exact hyb_entry_23_21 x y z + · exact hyb_entry_23_22 x y z + · exact hyb_entry_23_23 x y z + · exact hyb_entry_23_24 x y z + · exact hyb_entry_23_25 x y z + · exact hyb_entry_23_26 x y z + +theorem hyb_output_24 (x y z : ℂ) (d e f : Spin) : + hybLeft x y z .minus .minus .zero d e f = hybRight x y z .minus .minus .zero d e f := by + cases d <;> cases e <;> cases f + · exact hyb_entry_24_0 x y z + · exact hyb_entry_24_1 x y z + · exact hyb_entry_24_2 x y z + · exact hyb_entry_24_3 x y z + · exact hyb_entry_24_4 x y z + · exact hyb_entry_24_5 x y z + · exact hyb_entry_24_6 x y z + · exact hyb_entry_24_7 x y z + · exact hyb_entry_24_8 x y z + · exact hyb_entry_24_9 x y z + · exact hyb_entry_24_10 x y z + · exact hyb_entry_24_11 x y z + · exact hyb_entry_24_12 x y z + · exact hyb_entry_24_13 x y z + · exact hyb_entry_24_14 x y z + · exact hyb_entry_24_15 x y z + · exact hyb_entry_24_16 x y z + · exact hyb_entry_24_17 x y z + · exact hyb_entry_24_18 x y z + · exact hyb_entry_24_19 x y z + · exact hyb_entry_24_20 x y z + · exact hyb_entry_24_21 x y z + · exact hyb_entry_24_22 x y z + · exact hyb_entry_24_23 x y z + · exact hyb_entry_24_24 x y z + · exact hyb_entry_24_25 x y z + · exact hyb_entry_24_26 x y z + +theorem hyb_output_25 (x y z : ℂ) (d e f : Spin) : + hybLeft x y z .minus .minus .plus d e f = hybRight x y z .minus .minus .plus d e f := by + cases d <;> cases e <;> cases f + · exact hyb_entry_25_0 x y z + · exact hyb_entry_25_1 x y z + · exact hyb_entry_25_2 x y z + · exact hyb_entry_25_3 x y z + · exact hyb_entry_25_4 x y z + · exact hyb_entry_25_5 x y z + · exact hyb_entry_25_6 x y z + · exact hyb_entry_25_7 x y z + · exact hyb_entry_25_8 x y z + · exact hyb_entry_25_9 x y z + · exact hyb_entry_25_10 x y z + · exact hyb_entry_25_11 x y z + · exact hyb_entry_25_12 x y z + · exact hyb_entry_25_13 x y z + · exact hyb_entry_25_14 x y z + · exact hyb_entry_25_15 x y z + · exact hyb_entry_25_16 x y z + · exact hyb_entry_25_17 x y z + · exact hyb_entry_25_18 x y z + · exact hyb_entry_25_19 x y z + · exact hyb_entry_25_20 x y z + · exact hyb_entry_25_21 x y z + · exact hyb_entry_25_22 x y z + · exact hyb_entry_25_23 x y z + · exact hyb_entry_25_24 x y z + · exact hyb_entry_25_25 x y z + · exact hyb_entry_25_26 x y z + +theorem hyb_output_26 (x y z : ℂ) (d e f : Spin) : + hybLeft x y z .minus .minus .minus d e f = hybRight x y z .minus .minus .minus d e f := by + cases d <;> cases e <;> cases f + · exact hyb_entry_26_0 x y z + · exact hyb_entry_26_1 x y z + · exact hyb_entry_26_2 x y z + · exact hyb_entry_26_3 x y z + · exact hyb_entry_26_4 x y z + · exact hyb_entry_26_5 x y z + · exact hyb_entry_26_6 x y z + · exact hyb_entry_26_7 x y z + · exact hyb_entry_26_8 x y z + · exact hyb_entry_26_9 x y z + · exact hyb_entry_26_10 x y z + · exact hyb_entry_26_11 x y z + · exact hyb_entry_26_12 x y z + · exact hyb_entry_26_13 x y z + · exact hyb_entry_26_14 x y z + · exact hyb_entry_26_15 x y z + · exact hyb_entry_26_16 x y z + · exact hyb_entry_26_17 x y z + · exact hyb_entry_26_18 x y z + · exact hyb_entry_26_19 x y z + · exact hyb_entry_26_20 x y z + · exact hyb_entry_26_21 x y z + · exact hyb_entry_26_22 x y z + · exact hyb_entry_26_23 x y z + · exact hyb_entry_26_24 x y z + · exact hyb_entry_26_25 x y z + · exact hyb_entry_26_26 x y z + + + +theorem homogeneous_yang_baxter_coefficients (x y z : ℂ) (a b c d e f : Spin) : + hybLeft x y z a b c d e f = hybRight x y z a b c d e f := by + cases a <;> cases b <;> cases c + · exact hyb_output_0 x y z d e f + · exact hyb_output_1 x y z d e f + · exact hyb_output_2 x y z d e f + · exact hyb_output_3 x y z d e f + · exact hyb_output_4 x y z d e f + · exact hyb_output_5 x y z d e f + · exact hyb_output_6 x y z d e f + · exact hyb_output_7 x y z d e f + · exact hyb_output_8 x y z d e f + · exact hyb_output_9 x y z d e f + · exact hyb_output_10 x y z d e f + · exact hyb_output_11 x y z d e f + · exact hyb_output_12 x y z d e f + · exact hyb_output_13 x y z d e f + · exact hyb_output_14 x y z d e f + · exact hyb_output_15 x y z d e f + · exact hyb_output_16 x y z d e f + · exact hyb_output_17 x y z d e f + · exact hyb_output_18 x y z d e f + · exact hyb_output_19 x y z d e f + · exact hyb_output_20 x y z d e f + · exact hyb_output_21 x y z d e f + · exact hyb_output_22 x y z d e f + · exact hyb_output_23 x y z d e f + · exact hyb_output_24 x y z d e f + · exact hyb_output_25 x y z d e f + · exact hyb_output_26 x y z d e f + +end PolynomialVacuumAlgebra + +end OAI diff --git a/lean/OAI/Combinatorics/PolynomialVacuum/Algebra/InhomogeneousCircuit.lean b/lean/OAI/Combinatorics/PolynomialVacuum/Algebra/InhomogeneousCircuit.lean new file mode 100644 index 0000000000000000000000000000000000000000..771be0dcdceaa906e1a1d964a005701838033ed2 --- /dev/null +++ b/lean/OAI/Combinatorics/PolynomialVacuum/Algebra/InhomogeneousCircuit.lean @@ -0,0 +1,102 @@ +import OAI.Combinatorics.PolynomialVacuum.Algebra.RowEigenvector + +namespace OAI + +namespace PolynomialVacuumAlgebra +namespace Inhomogeneous +open Classical + +noncomputable def spectralVector (N : ℕ) (X : ℕ → ℂ) : SpinTensor ℕ ℂ := + liftState (polynomialVacuum N) X + +noncomputable def frontCupData (X : ℕ → ℂ) (a : ℂ) : ℕ → ℂ := fun j => if j=0 then a else if j=1 then T*a else X (j-2) +noncomputable def finalCupData (N : ℕ) (X : ℕ → ℂ) (a : ℂ) : ℕ → ℂ := fun j => if j if j=0 then a else X (j-1) + +noncomputable def cupRowCircuit (N : ℕ) (X : ℕ → ℂ) (a : ℂ) (W : SpinTensor ℕ ℂ) : SpinTensor ℕ ℂ := + siteR N (T*a) a (rotateTensor (N+1) (braidTrain (T*a) (frontFirstData X a) 1 N (cupLinear 0 W))) + +noncomputable def spectralFusion (N : ℕ) (X : ℕ → ℂ) (a : ℂ) : ℂ := (1+T)*a*fusionProduct a X N + +@[simp] theorem frontCupData_zero (X : ℕ → ℂ) (a : ℂ) : frontCupData X a 0=a := by simp [frontCupData] +@[simp] theorem frontCupData_one (X : ℕ → ℂ) (a : ℂ) : frontCupData X a 1=T*a := by simp [frontCupData] +@[simp] theorem finalCupData_left (N : ℕ) (X : ℕ → ℂ) (a : ℂ) : finalCupData N X a N=a := by simp [finalCupData] +@[simp] theorem finalCupData_right (N : ℕ) (X : ℕ → ℂ) (a : ℂ) : finalCupData N X a (N+1)=T*a := by simp [finalCupData] + +@[simp] theorem front_skip (X : ℕ → ℂ) (a : ℂ) : skipTwo 0 (frontCupData X a)=X := by + funext j; simp [skipTwo,frontCupData] +@[simp] theorem final_skip (N : ℕ) (X : ℕ → ℂ) (a : ℂ) : skipTwo N (finalCupData N X a)=X := by + funext j + simp only [skipTwo,finalCupData] + split_ifs <;> first | rfl | omega + +@[simp] theorem front_fusion (N : ℕ) (X : ℕ → ℂ) (a : ℂ) : naturalFusion N 0 (frontCupData X a)=spectralFusion N X a := by + simp only [naturalFusion,frontCupData_zero,front_skip] + simp [fusionProduct,spectralFusion] +@[simp] theorem final_fusion (N : ℕ) (X : ℕ → ℂ) (a : ℂ) : naturalFusion N N (finalCupData N X a)=spectralFusion N X a := by + simp [naturalFusion,final_skip,fusionProduct,spectralFusion] + +theorem front_insert (X : ℕ → ℂ) (a : ℂ) : insertOne 1 (T*a) (frontFirstData X a)=frontCupData X a := by + funext j + simp only [insertOne,frontFirstData,frontCupData] + split_ifs <;> first | rfl | omega + + + +theorem final_insert_rotation (N : ℕ) (X : ℕ → ℂ) (a : ℂ) : + liftState (polynomialVacuum (N+2)) (natRotate (N+1) (reversedFinalData N X a))= + liftState (polynomialVacuum (N+2)) (insertOne (1+N) (T*a) (frontFirstData X a)) := by + apply liftState_params_congr + intro j hj + simp only [natRotate,rotationIndex,Function.comp_apply,reversedFinalData,swapSite, + Equiv.swap_apply_def,finalCupData,insertOne,frontFirstData] + split_ifs <;> first | rfl | omega + +theorem rotateTensor_smul (N : ℕ) (c : ℂ) (W : SpinTensor ℕ ℂ) : + rotateTensor N (c • W)=c • rotateTensor N W := by + funext s + simp [rotateTensor,smul_eq_mul,mul_left_comm] + + + +theorem polynomialVacuum_cupRow (N : ℕ) (X : ℕ → ℂ) (a : ℂ) + (hs : spectralFusion N X a≠0) : + cupRowCircuit N X a (spectralVector N X)= + (exchangeDenominator (T*a) a * trainDenominator (T*a) (frontFirstData X a) 1 N) • + cupLinear N (spectralVector N X) := by + let Ψ := liftState (polynomialVacuum (N+2)) + have hf := (polynomialVacuum_at (N+2)).cups N rfl 0 (by omega) (frontCupData X a) (by simp) + have hl := (polynomialVacuum_at (N+2)).cups N rfl N le_rfl (finalCupData N X a) (by simp) + simp only [front_fusion,front_skip] at hf + simp only [final_fusion,final_skip] at hl + have htrain := braidTrain_exchange (polynomialVacuum_at (N+2)).regular.exchange + (T*a) (frontFirstData X a) 1 N (by omega) + rw [front_insert,hf,map_smul] at htrain + have hcy := (polynomialVacuum_at (N+2)).cyclic (N+1) (by omega) (reversedFinalData N X a) + change rotateTensor (N+1) (liftState (polynomialVacuum (N+2)) (natRotate (N+1) (reversedFinalData N X a)))=Ψ (reversedFinalData N X a) at hcy + rw [final_insert_rotation] at hcy + have hrot := congrArg (rotateTensor (N+1)) htrain + rw [rotateTensor_smul,rotateTensor_smul,hcy] at hrot + have hex := (polynomialVacuum_at (N+2)).regular.exchange N (by omega) (reversedFinalData N X a) + have hrl : reversedFinalData N X a N=T*a := by simp [reversedFinalData] + have hrr : reversedFinalData N X a (N+1)=a := by simp [reversedFinalData] + rw [hrl,hrr,show swapSite N (reversedFinalData N X a)=finalCupData N X a from swapSite_twice N _,hl] at hex + have he := congrArg (siteR N (T*a) a) hrot + rw [map_smul,map_smul,hex,smul_smul,smul_smul] at he + change spectralFusion N X a • cupRowCircuit N X a (spectralVector N X)=_ at he + funext s + apply mul_left_cancel₀ hs + have he' := congrFun he s + change spectralFusion N X a * cupRowCircuit N X a (spectralVector N X) s= + (trainDenominator (T*a) (frontFirstData X a) 1 N * exchangeDenominator (T*a) a * spectralFusion N X a) * + cupLinear N (spectralVector N X) s at he' + change spectralFusion N X a * cupRowCircuit N X a (spectralVector N X) s= + spectralFusion N X a * ((exchangeDenominator (T*a) a * trainDenominator (T*a) (frontFirstData X a) 1 N) * cupLinear N (spectralVector N X) s) + rw [he'] + ring + +end Inhomogeneous +end PolynomialVacuumAlgebra + +end OAI diff --git a/lean/OAI/Combinatorics/PolynomialVacuum/Algebra/InhomogeneousRow.lean b/lean/OAI/Combinatorics/PolynomialVacuum/Algebra/InhomogeneousRow.lean new file mode 100644 index 0000000000000000000000000000000000000000..70868597774a25a284389eeae699eca1697c31d6 --- /dev/null +++ b/lean/OAI/Combinatorics/PolynomialVacuum/Algebra/InhomogeneousRow.lean @@ -0,0 +1,67 @@ +import OAI.Combinatorics.PolynomialVacuum.Algebra.InhomogeneousCircuit + +namespace OAI + +namespace PolynomialVacuumAlgebra +namespace Inhomogeneous +open Classical + + +theorem cupRow_trace (N : ℕ) (X : ℕ → ℂ) (a : ℂ) (W : SpinTensor ℕ ℂ) (hW : DependsBefore N W) (s : ℕ → Spin) : + cupRowCircuit N X a W (padCup N s)= + exchangeDenominator (T*a) a * tracedTrain N (T*a) X W s := by + have hX : skipOne 0 (frontFirstData X a)=X := by + funext j; simp [skipOne,frontFirstData] + have hv (ab : Pair) : + braidTrain (T*a) (frontFirstData X a) 1 N (cupLinear 0 W) + (natRotate (N+1) (replacePair (padCup N s) N (N+1) ab))= + ∑ h : Spin,cup (ab.2,h)* + braidTrain (T*a) X 0 N (auxiliaryInput h W) (insertOne N ab.1 s) := by + rw [braidTrain_head_evaluate,rotate_padCup_head,hX,cup_headFiber,map_sum] + simp only [map_smul,Finset.sum_apply,Pi.smul_apply,smul_eq_mul] + apply Finset.sum_congr rfl + intro h _ + congr 1 + apply braidTrain_depends (auxiliaryInput_depends hW h) (by omega) + exact rotate_padCup_tail N s ab + simp only [cupRowCircuit,siteR,pairLinear,LinearMap.coe_mk,AddHom.coe_mk,pairAction, + padCup_left,padCup_right,numerator_cup_zero,rotateTensor, + replacePair_right,hv,tracedTrain,mul_assoc] + rw [← Finset.mul_sum] + congr 1 + simpa only [mul_assoc] using cup_trace_identity (fun h b => + braidTrain (T*a) X 0 N (auxiliaryInput h W) (insertOne N b s)) + +theorem spectralVector_depends (N : ℕ) (X : ℕ → ℂ) : DependsBefore N (spectralVector N X) := by + intro s r h + unfold spectralVector liftState liftPolyTensor + congr 2 + funext j + exact h j.val j.isLt + +theorem front_trainDenominator (N : ℕ) (X : ℕ → ℂ) (a : ℂ) : + trainDenominator (T*a) (frontFirstData X a) 1 N=trainDenominator (T*a) X 0 N := by + have hh : ∀ k, trainDenominator (T*a) (frontFirstData X a) (k+1) N= + trainDenominator (T*a) X k N := by + induction N with + | zero => intros; rfl + | succ N ih => + intro k + simp [trainDenominator,frontFirstData,ih] + exact hh 0 + +theorem polynomialVacuum_tracedRow (N : ℕ) (X : ℕ → ℂ) (a : ℂ) + (hs : spectralFusion N X a≠0) (hd : exchangeDenominator (T*a) a≠0) : + tracedTrain N (T*a) X (spectralVector N X)= + trainDenominator (T*a) X 0 N • spectralVector N X := by + funext s + have he:=congrFun (polynomialVacuum_cupRow N X a hs) (padCup N s) + rw [cupRow_trace N X a _ (spectralVector_depends N X),front_trainDenominator] at he + simp only [Pi.smul_apply,smul_eq_mul,cupLinear,LinearMap.coe_mk,AddHom.coe_mk, + padCup_left,padCup_right,padCup_skip,cup,charge,add_zero,mul_zero,ite_true,zpow_zero,one_mul] at he + apply mul_left_cancel₀ hd + simpa only [Pi.smul_apply,smul_eq_mul,mul_assoc] using he +end Inhomogeneous +end PolynomialVacuumAlgebra + +end OAI diff --git a/lean/OAI/Combinatorics/PolynomialVacuum/Algebra/InsertionSlide.lean b/lean/OAI/Combinatorics/PolynomialVacuum/Algebra/InsertionSlide.lean new file mode 100644 index 0000000000000000000000000000000000000000..0b4ec5f9503bf9357356e765eb00afb9ca75844a --- /dev/null +++ b/lean/OAI/Combinatorics/PolynomialVacuum/Algebra/InsertionSlide.lean @@ -0,0 +1,1534 @@ +import OAI.Combinatorics.PolynomialVacuum.Algebra.CupSlide +import OAI.Combinatorics.PolynomialVacuum.Algebra.Ring + +namespace OAI + +namespace PolynomialVacuumAlgebra + + +noncomputable def insertionSlideLeft (x : ℂ) (a b c h k : Spin) : ℂ := + exchangeDenominator (t*x) 1 * + ∑ i : Spin, ∑ j : Spin, ∑ l : Spin, + exchangeNumerator x 1 (a,b) (i,j) * + exchangeNumerator (t^2*x) 1 (j,c) (l,k) * insertion (i,l) h + +noncomputable def insertionSlideRight (x : ℂ) (a b c h k : Spin) : ℂ := + exchangeDenominator x 1 * exchangeDenominator (t^2*x) 1 * + ∑ g : Spin, insertion (b,c) g * exchangeNumerator (t*x) 1 (a,g) (h,k) + +theorem insertion_slide_entry_0_0 (x : ℂ) : + insertionSlideLeft x .zero .zero .zero .zero .zero = insertionSlideRight x .zero .zero .zero .zero .zero := by + norm_num [insertionSlideLeft,insertionSlideRight,sum_spin,exchangeNumerator_eq_table,exchangeTable, + exchangeDenominator,insertion_eq_table,insertionTable,T,t] + all_goals vacuum_ring_finish + +theorem insertion_slide_entry_0_1 (x : ℂ) : + insertionSlideLeft x .zero .zero .zero .zero .plus = insertionSlideRight x .zero .zero .zero .zero .plus := by + norm_num [insertionSlideLeft,insertionSlideRight,sum_spin,exchangeNumerator_eq_table,exchangeTable, + exchangeDenominator,insertion_eq_table,insertionTable,T,t] + +theorem insertion_slide_entry_0_2 (x : ℂ) : + insertionSlideLeft x .zero .zero .zero .zero .minus = insertionSlideRight x .zero .zero .zero .zero .minus := by + norm_num [insertionSlideLeft,insertionSlideRight,sum_spin,exchangeNumerator_eq_table,exchangeTable, + exchangeDenominator,insertion_eq_table,insertionTable,T,t] + +theorem insertion_slide_entry_0_3 (x : ℂ) : + insertionSlideLeft x .zero .zero .zero .plus .zero = insertionSlideRight x .zero .zero .zero .plus .zero := by + norm_num [insertionSlideLeft,insertionSlideRight,sum_spin,exchangeNumerator_eq_table,exchangeTable, + exchangeDenominator,insertion_eq_table,insertionTable,T,t] + +theorem insertion_slide_entry_0_4 (x : ℂ) : + insertionSlideLeft x .zero .zero .zero .plus .plus = insertionSlideRight x .zero .zero .zero .plus .plus := by + norm_num [insertionSlideLeft,insertionSlideRight,sum_spin,exchangeNumerator_eq_table,exchangeTable, + exchangeDenominator,insertion_eq_table,insertionTable,T,t] + +theorem insertion_slide_entry_0_5 (x : ℂ) : + insertionSlideLeft x .zero .zero .zero .plus .minus = insertionSlideRight x .zero .zero .zero .plus .minus := by + norm_num [insertionSlideLeft,insertionSlideRight,sum_spin,exchangeNumerator_eq_table,exchangeTable, + exchangeDenominator,insertion_eq_table,insertionTable,T,t] + all_goals vacuum_ring_finish + +theorem insertion_slide_entry_0_6 (x : ℂ) : + insertionSlideLeft x .zero .zero .zero .minus .zero = insertionSlideRight x .zero .zero .zero .minus .zero := by + norm_num [insertionSlideLeft,insertionSlideRight,sum_spin,exchangeNumerator_eq_table,exchangeTable, + exchangeDenominator,insertion_eq_table,insertionTable,T,t] + +theorem insertion_slide_entry_0_7 (x : ℂ) : + insertionSlideLeft x .zero .zero .zero .minus .plus = insertionSlideRight x .zero .zero .zero .minus .plus := by + norm_num [insertionSlideLeft,insertionSlideRight,sum_spin,exchangeNumerator_eq_table,exchangeTable, + exchangeDenominator,insertion_eq_table,insertionTable,T,t] + all_goals vacuum_ring_finish + +theorem insertion_slide_entry_0_8 (x : ℂ) : + insertionSlideLeft x .zero .zero .zero .minus .minus = insertionSlideRight x .zero .zero .zero .minus .minus := by + norm_num [insertionSlideLeft,insertionSlideRight,sum_spin,exchangeNumerator_eq_table,exchangeTable, + exchangeDenominator,insertion_eq_table,insertionTable,T,t] + +theorem insertion_slide_entry_1_0 (x : ℂ) : + insertionSlideLeft x .zero .zero .plus .zero .zero = insertionSlideRight x .zero .zero .plus .zero .zero := by + norm_num [insertionSlideLeft,insertionSlideRight,sum_spin,exchangeNumerator_eq_table,exchangeTable, + exchangeDenominator,insertion_eq_table,insertionTable,T,t] + +theorem insertion_slide_entry_1_1 (x : ℂ) : + insertionSlideLeft x .zero .zero .plus .zero .plus = insertionSlideRight x .zero .zero .plus .zero .plus := by + norm_num [insertionSlideLeft,insertionSlideRight,sum_spin,exchangeNumerator_eq_table,exchangeTable, + exchangeDenominator,insertion_eq_table,insertionTable,T,t] + all_goals vacuum_ring_finish + +theorem insertion_slide_entry_1_2 (x : ℂ) : + insertionSlideLeft x .zero .zero .plus .zero .minus = insertionSlideRight x .zero .zero .plus .zero .minus := by + norm_num [insertionSlideLeft,insertionSlideRight,sum_spin,exchangeNumerator_eq_table,exchangeTable, + exchangeDenominator,insertion_eq_table,insertionTable,T,t] + +theorem insertion_slide_entry_1_3 (x : ℂ) : + insertionSlideLeft x .zero .zero .plus .plus .zero = insertionSlideRight x .zero .zero .plus .plus .zero := by + norm_num [insertionSlideLeft,insertionSlideRight,sum_spin,exchangeNumerator_eq_table,exchangeTable, + exchangeDenominator,insertion_eq_table,insertionTable,T,t] + all_goals vacuum_ring_finish + +theorem insertion_slide_entry_1_4 (x : ℂ) : + insertionSlideLeft x .zero .zero .plus .plus .plus = insertionSlideRight x .zero .zero .plus .plus .plus := by + norm_num [insertionSlideLeft,insertionSlideRight,sum_spin,exchangeNumerator_eq_table,exchangeTable, + exchangeDenominator,insertion_eq_table,insertionTable,T,t] + +theorem insertion_slide_entry_1_5 (x : ℂ) : + insertionSlideLeft x .zero .zero .plus .plus .minus = insertionSlideRight x .zero .zero .plus .plus .minus := by + norm_num [insertionSlideLeft,insertionSlideRight,sum_spin,exchangeNumerator_eq_table,exchangeTable, + exchangeDenominator,insertion_eq_table,insertionTable,T,t] + +theorem insertion_slide_entry_1_6 (x : ℂ) : + insertionSlideLeft x .zero .zero .plus .minus .zero = insertionSlideRight x .zero .zero .plus .minus .zero := by + norm_num [insertionSlideLeft,insertionSlideRight,sum_spin,exchangeNumerator_eq_table,exchangeTable, + exchangeDenominator,insertion_eq_table,insertionTable,T,t] + +theorem insertion_slide_entry_1_7 (x : ℂ) : + insertionSlideLeft x .zero .zero .plus .minus .plus = insertionSlideRight x .zero .zero .plus .minus .plus := by + norm_num [insertionSlideLeft,insertionSlideRight,sum_spin,exchangeNumerator_eq_table,exchangeTable, + exchangeDenominator,insertion_eq_table,insertionTable,T,t] + +theorem insertion_slide_entry_1_8 (x : ℂ) : + insertionSlideLeft x .zero .zero .plus .minus .minus = insertionSlideRight x .zero .zero .plus .minus .minus := by + norm_num [insertionSlideLeft,insertionSlideRight,sum_spin,exchangeNumerator_eq_table,exchangeTable, + exchangeDenominator,insertion_eq_table,insertionTable,T,t] + +theorem insertion_slide_entry_2_0 (x : ℂ) : + insertionSlideLeft x .zero .zero .minus .zero .zero = insertionSlideRight x .zero .zero .minus .zero .zero := by + norm_num [insertionSlideLeft,insertionSlideRight,sum_spin,exchangeNumerator_eq_table,exchangeTable, + exchangeDenominator,insertion_eq_table,insertionTable,T,t] + +theorem insertion_slide_entry_2_1 (x : ℂ) : + insertionSlideLeft x .zero .zero .minus .zero .plus = insertionSlideRight x .zero .zero .minus .zero .plus := by + norm_num [insertionSlideLeft,insertionSlideRight,sum_spin,exchangeNumerator_eq_table,exchangeTable, + exchangeDenominator,insertion_eq_table,insertionTable,T,t] + +theorem insertion_slide_entry_2_2 (x : ℂ) : + insertionSlideLeft x .zero .zero .minus .zero .minus = insertionSlideRight x .zero .zero .minus .zero .minus := by + norm_num [insertionSlideLeft,insertionSlideRight,sum_spin,exchangeNumerator_eq_table,exchangeTable, + exchangeDenominator,insertion_eq_table,insertionTable,T,t] + all_goals vacuum_ring_finish + +theorem insertion_slide_entry_2_3 (x : ℂ) : + insertionSlideLeft x .zero .zero .minus .plus .zero = insertionSlideRight x .zero .zero .minus .plus .zero := by + norm_num [insertionSlideLeft,insertionSlideRight,sum_spin,exchangeNumerator_eq_table,exchangeTable, + exchangeDenominator,insertion_eq_table,insertionTable,T,t] + +theorem insertion_slide_entry_2_4 (x : ℂ) : + insertionSlideLeft x .zero .zero .minus .plus .plus = insertionSlideRight x .zero .zero .minus .plus .plus := by + norm_num [insertionSlideLeft,insertionSlideRight,sum_spin,exchangeNumerator_eq_table,exchangeTable, + exchangeDenominator,insertion_eq_table,insertionTable,T,t] + +theorem insertion_slide_entry_2_5 (x : ℂ) : + insertionSlideLeft x .zero .zero .minus .plus .minus = insertionSlideRight x .zero .zero .minus .plus .minus := by + norm_num [insertionSlideLeft,insertionSlideRight,sum_spin,exchangeNumerator_eq_table,exchangeTable, + exchangeDenominator,insertion_eq_table,insertionTable,T,t] + +theorem insertion_slide_entry_2_6 (x : ℂ) : + insertionSlideLeft x .zero .zero .minus .minus .zero = insertionSlideRight x .zero .zero .minus .minus .zero := by + norm_num [insertionSlideLeft,insertionSlideRight,sum_spin,exchangeNumerator_eq_table,exchangeTable, + exchangeDenominator,insertion_eq_table,insertionTable,T,t] + all_goals vacuum_ring_finish + +theorem insertion_slide_entry_2_7 (x : ℂ) : + insertionSlideLeft x .zero .zero .minus .minus .plus = insertionSlideRight x .zero .zero .minus .minus .plus := by + norm_num [insertionSlideLeft,insertionSlideRight,sum_spin,exchangeNumerator_eq_table,exchangeTable, + exchangeDenominator,insertion_eq_table,insertionTable,T,t] + +theorem insertion_slide_entry_2_8 (x : ℂ) : + insertionSlideLeft x .zero .zero .minus .minus .minus = insertionSlideRight x .zero .zero .minus .minus .minus := by + norm_num [insertionSlideLeft,insertionSlideRight,sum_spin,exchangeNumerator_eq_table,exchangeTable, + exchangeDenominator,insertion_eq_table,insertionTable,T,t] + +theorem insertion_slide_entry_3_0 (x : ℂ) : + insertionSlideLeft x .zero .plus .zero .zero .zero = insertionSlideRight x .zero .plus .zero .zero .zero := by + norm_num [insertionSlideLeft,insertionSlideRight,sum_spin,exchangeNumerator_eq_table,exchangeTable, + exchangeDenominator,insertion_eq_table,insertionTable,T,t] + +theorem insertion_slide_entry_3_1 (x : ℂ) : + insertionSlideLeft x .zero .plus .zero .zero .plus = insertionSlideRight x .zero .plus .zero .zero .plus := by + norm_num [insertionSlideLeft,insertionSlideRight,sum_spin,exchangeNumerator_eq_table,exchangeTable, + exchangeDenominator,insertion_eq_table,insertionTable,T,t] + all_goals vacuum_ring_finish + +theorem insertion_slide_entry_3_2 (x : ℂ) : + insertionSlideLeft x .zero .plus .zero .zero .minus = insertionSlideRight x .zero .plus .zero .zero .minus := by + norm_num [insertionSlideLeft,insertionSlideRight,sum_spin,exchangeNumerator_eq_table,exchangeTable, + exchangeDenominator,insertion_eq_table,insertionTable,T,t] + +theorem insertion_slide_entry_3_3 (x : ℂ) : + insertionSlideLeft x .zero .plus .zero .plus .zero = insertionSlideRight x .zero .plus .zero .plus .zero := by + norm_num [insertionSlideLeft,insertionSlideRight,sum_spin,exchangeNumerator_eq_table,exchangeTable, + exchangeDenominator,insertion_eq_table,insertionTable,T,t] + all_goals vacuum_ring_finish + +theorem insertion_slide_entry_3_4 (x : ℂ) : + insertionSlideLeft x .zero .plus .zero .plus .plus = insertionSlideRight x .zero .plus .zero .plus .plus := by + norm_num [insertionSlideLeft,insertionSlideRight,sum_spin,exchangeNumerator_eq_table,exchangeTable, + exchangeDenominator,insertion_eq_table,insertionTable,T,t] + +theorem insertion_slide_entry_3_5 (x : ℂ) : + insertionSlideLeft x .zero .plus .zero .plus .minus = insertionSlideRight x .zero .plus .zero .plus .minus := by + norm_num [insertionSlideLeft,insertionSlideRight,sum_spin,exchangeNumerator_eq_table,exchangeTable, + exchangeDenominator,insertion_eq_table,insertionTable,T,t] + +theorem insertion_slide_entry_3_6 (x : ℂ) : + insertionSlideLeft x .zero .plus .zero .minus .zero = insertionSlideRight x .zero .plus .zero .minus .zero := by + norm_num [insertionSlideLeft,insertionSlideRight,sum_spin,exchangeNumerator_eq_table,exchangeTable, + exchangeDenominator,insertion_eq_table,insertionTable,T,t] + +theorem insertion_slide_entry_3_7 (x : ℂ) : + insertionSlideLeft x .zero .plus .zero .minus .plus = insertionSlideRight x .zero .plus .zero .minus .plus := by + norm_num [insertionSlideLeft,insertionSlideRight,sum_spin,exchangeNumerator_eq_table,exchangeTable, + exchangeDenominator,insertion_eq_table,insertionTable,T,t] + +theorem insertion_slide_entry_3_8 (x : ℂ) : + insertionSlideLeft x .zero .plus .zero .minus .minus = insertionSlideRight x .zero .plus .zero .minus .minus := by + norm_num [insertionSlideLeft,insertionSlideRight,sum_spin,exchangeNumerator_eq_table,exchangeTable, + exchangeDenominator,insertion_eq_table,insertionTable,T,t] + +theorem insertion_slide_entry_4_0 (x : ℂ) : + insertionSlideLeft x .zero .plus .plus .zero .zero = insertionSlideRight x .zero .plus .plus .zero .zero := by + norm_num [insertionSlideLeft,insertionSlideRight,sum_spin,exchangeNumerator_eq_table,exchangeTable, + exchangeDenominator,insertion_eq_table,insertionTable,T,t] + +theorem insertion_slide_entry_4_1 (x : ℂ) : + insertionSlideLeft x .zero .plus .plus .zero .plus = insertionSlideRight x .zero .plus .plus .zero .plus := by + norm_num [insertionSlideLeft,insertionSlideRight,sum_spin,exchangeNumerator_eq_table,exchangeTable, + exchangeDenominator,insertion_eq_table,insertionTable,T,t] + +theorem insertion_slide_entry_4_2 (x : ℂ) : + insertionSlideLeft x .zero .plus .plus .zero .minus = insertionSlideRight x .zero .plus .plus .zero .minus := by + norm_num [insertionSlideLeft,insertionSlideRight,sum_spin,exchangeNumerator_eq_table,exchangeTable, + exchangeDenominator,insertion_eq_table,insertionTable,T,t] + +theorem insertion_slide_entry_4_3 (x : ℂ) : + insertionSlideLeft x .zero .plus .plus .plus .zero = insertionSlideRight x .zero .plus .plus .plus .zero := by + norm_num [insertionSlideLeft,insertionSlideRight,sum_spin,exchangeNumerator_eq_table,exchangeTable, + exchangeDenominator,insertion_eq_table,insertionTable,T,t] + +theorem insertion_slide_entry_4_4 (x : ℂ) : + insertionSlideLeft x .zero .plus .plus .plus .plus = insertionSlideRight x .zero .plus .plus .plus .plus := by + norm_num [insertionSlideLeft,insertionSlideRight,sum_spin,exchangeNumerator_eq_table,exchangeTable, + exchangeDenominator,insertion_eq_table,insertionTable,T,t] + all_goals vacuum_ring_finish + +theorem insertion_slide_entry_4_5 (x : ℂ) : + insertionSlideLeft x .zero .plus .plus .plus .minus = insertionSlideRight x .zero .plus .plus .plus .minus := by + norm_num [insertionSlideLeft,insertionSlideRight,sum_spin,exchangeNumerator_eq_table,exchangeTable, + exchangeDenominator,insertion_eq_table,insertionTable,T,t] + +theorem insertion_slide_entry_4_6 (x : ℂ) : + insertionSlideLeft x .zero .plus .plus .minus .zero = insertionSlideRight x .zero .plus .plus .minus .zero := by + norm_num [insertionSlideLeft,insertionSlideRight,sum_spin,exchangeNumerator_eq_table,exchangeTable, + exchangeDenominator,insertion_eq_table,insertionTable,T,t] + +theorem insertion_slide_entry_4_7 (x : ℂ) : + insertionSlideLeft x .zero .plus .plus .minus .plus = insertionSlideRight x .zero .plus .plus .minus .plus := by + norm_num [insertionSlideLeft,insertionSlideRight,sum_spin,exchangeNumerator_eq_table,exchangeTable, + exchangeDenominator,insertion_eq_table,insertionTable,T,t] + +theorem insertion_slide_entry_4_8 (x : ℂ) : + insertionSlideLeft x .zero .plus .plus .minus .minus = insertionSlideRight x .zero .plus .plus .minus .minus := by + norm_num [insertionSlideLeft,insertionSlideRight,sum_spin,exchangeNumerator_eq_table,exchangeTable, + exchangeDenominator,insertion_eq_table,insertionTable,T,t] + +theorem insertion_slide_entry_5_0 (x : ℂ) : + insertionSlideLeft x .zero .plus .minus .zero .zero = insertionSlideRight x .zero .plus .minus .zero .zero := by + norm_num [insertionSlideLeft,insertionSlideRight,sum_spin,exchangeNumerator_eq_table,exchangeTable, + exchangeDenominator,insertion_eq_table,insertionTable,T,t] + all_goals vacuum_ring_finish + +theorem insertion_slide_entry_5_1 (x : ℂ) : + insertionSlideLeft x .zero .plus .minus .zero .plus = insertionSlideRight x .zero .plus .minus .zero .plus := by + norm_num [insertionSlideLeft,insertionSlideRight,sum_spin,exchangeNumerator_eq_table,exchangeTable, + exchangeDenominator,insertion_eq_table,insertionTable,T,t] + +theorem insertion_slide_entry_5_2 (x : ℂ) : + insertionSlideLeft x .zero .plus .minus .zero .minus = insertionSlideRight x .zero .plus .minus .zero .minus := by + norm_num [insertionSlideLeft,insertionSlideRight,sum_spin,exchangeNumerator_eq_table,exchangeTable, + exchangeDenominator,insertion_eq_table,insertionTable,T,t] + +theorem insertion_slide_entry_5_3 (x : ℂ) : + insertionSlideLeft x .zero .plus .minus .plus .zero = insertionSlideRight x .zero .plus .minus .plus .zero := by + norm_num [insertionSlideLeft,insertionSlideRight,sum_spin,exchangeNumerator_eq_table,exchangeTable, + exchangeDenominator,insertion_eq_table,insertionTable,T,t] + +theorem insertion_slide_entry_5_4 (x : ℂ) : + insertionSlideLeft x .zero .plus .minus .plus .plus = insertionSlideRight x .zero .plus .minus .plus .plus := by + norm_num [insertionSlideLeft,insertionSlideRight,sum_spin,exchangeNumerator_eq_table,exchangeTable, + exchangeDenominator,insertion_eq_table,insertionTable,T,t] + +theorem insertion_slide_entry_5_5 (x : ℂ) : + insertionSlideLeft x .zero .plus .minus .plus .minus = insertionSlideRight x .zero .plus .minus .plus .minus := by + norm_num [insertionSlideLeft,insertionSlideRight,sum_spin,exchangeNumerator_eq_table,exchangeTable, + exchangeDenominator,insertion_eq_table,insertionTable,T,t] + all_goals vacuum_ring_finish + +theorem insertion_slide_entry_5_6 (x : ℂ) : + insertionSlideLeft x .zero .plus .minus .minus .zero = insertionSlideRight x .zero .plus .minus .minus .zero := by + norm_num [insertionSlideLeft,insertionSlideRight,sum_spin,exchangeNumerator_eq_table,exchangeTable, + exchangeDenominator,insertion_eq_table,insertionTable,T,t] + +theorem insertion_slide_entry_5_7 (x : ℂ) : + insertionSlideLeft x .zero .plus .minus .minus .plus = insertionSlideRight x .zero .plus .minus .minus .plus := by + norm_num [insertionSlideLeft,insertionSlideRight,sum_spin,exchangeNumerator_eq_table,exchangeTable, + exchangeDenominator,insertion_eq_table,insertionTable,T,t] + all_goals vacuum_ring_finish + +theorem insertion_slide_entry_5_8 (x : ℂ) : + insertionSlideLeft x .zero .plus .minus .minus .minus = insertionSlideRight x .zero .plus .minus .minus .minus := by + norm_num [insertionSlideLeft,insertionSlideRight,sum_spin,exchangeNumerator_eq_table,exchangeTable, + exchangeDenominator,insertion_eq_table,insertionTable,T,t] + +theorem insertion_slide_entry_6_0 (x : ℂ) : + insertionSlideLeft x .zero .minus .zero .zero .zero = insertionSlideRight x .zero .minus .zero .zero .zero := by + norm_num [insertionSlideLeft,insertionSlideRight,sum_spin,exchangeNumerator_eq_table,exchangeTable, + exchangeDenominator,insertion_eq_table,insertionTable,T,t] + +theorem insertion_slide_entry_6_1 (x : ℂ) : + insertionSlideLeft x .zero .minus .zero .zero .plus = insertionSlideRight x .zero .minus .zero .zero .plus := by + norm_num [insertionSlideLeft,insertionSlideRight,sum_spin,exchangeNumerator_eq_table,exchangeTable, + exchangeDenominator,insertion_eq_table,insertionTable,T,t] + +theorem insertion_slide_entry_6_2 (x : ℂ) : + insertionSlideLeft x .zero .minus .zero .zero .minus = insertionSlideRight x .zero .minus .zero .zero .minus := by + norm_num [insertionSlideLeft,insertionSlideRight,sum_spin,exchangeNumerator_eq_table,exchangeTable, + exchangeDenominator,insertion_eq_table,insertionTable,T,t] + all_goals vacuum_ring_finish + +theorem insertion_slide_entry_6_3 (x : ℂ) : + insertionSlideLeft x .zero .minus .zero .plus .zero = insertionSlideRight x .zero .minus .zero .plus .zero := by + norm_num [insertionSlideLeft,insertionSlideRight,sum_spin,exchangeNumerator_eq_table,exchangeTable, + exchangeDenominator,insertion_eq_table,insertionTable,T,t] + +theorem insertion_slide_entry_6_4 (x : ℂ) : + insertionSlideLeft x .zero .minus .zero .plus .plus = insertionSlideRight x .zero .minus .zero .plus .plus := by + norm_num [insertionSlideLeft,insertionSlideRight,sum_spin,exchangeNumerator_eq_table,exchangeTable, + exchangeDenominator,insertion_eq_table,insertionTable,T,t] + +theorem insertion_slide_entry_6_5 (x : ℂ) : + insertionSlideLeft x .zero .minus .zero .plus .minus = insertionSlideRight x .zero .minus .zero .plus .minus := by + norm_num [insertionSlideLeft,insertionSlideRight,sum_spin,exchangeNumerator_eq_table,exchangeTable, + exchangeDenominator,insertion_eq_table,insertionTable,T,t] + +theorem insertion_slide_entry_6_6 (x : ℂ) : + insertionSlideLeft x .zero .minus .zero .minus .zero = insertionSlideRight x .zero .minus .zero .minus .zero := by + norm_num [insertionSlideLeft,insertionSlideRight,sum_spin,exchangeNumerator_eq_table,exchangeTable, + exchangeDenominator,insertion_eq_table,insertionTable,T,t] + all_goals vacuum_ring_finish + +theorem insertion_slide_entry_6_7 (x : ℂ) : + insertionSlideLeft x .zero .minus .zero .minus .plus = insertionSlideRight x .zero .minus .zero .minus .plus := by + norm_num [insertionSlideLeft,insertionSlideRight,sum_spin,exchangeNumerator_eq_table,exchangeTable, + exchangeDenominator,insertion_eq_table,insertionTable,T,t] + +theorem insertion_slide_entry_6_8 (x : ℂ) : + insertionSlideLeft x .zero .minus .zero .minus .minus = insertionSlideRight x .zero .minus .zero .minus .minus := by + norm_num [insertionSlideLeft,insertionSlideRight,sum_spin,exchangeNumerator_eq_table,exchangeTable, + exchangeDenominator,insertion_eq_table,insertionTable,T,t] + +theorem insertion_slide_entry_7_0 (x : ℂ) : + insertionSlideLeft x .zero .minus .plus .zero .zero = insertionSlideRight x .zero .minus .plus .zero .zero := by + norm_num [insertionSlideLeft,insertionSlideRight,sum_spin,exchangeNumerator_eq_table,exchangeTable, + exchangeDenominator,insertion_eq_table,insertionTable,T,t] + all_goals vacuum_ring_finish + +theorem insertion_slide_entry_7_1 (x : ℂ) : + insertionSlideLeft x .zero .minus .plus .zero .plus = insertionSlideRight x .zero .minus .plus .zero .plus := by + norm_num [insertionSlideLeft,insertionSlideRight,sum_spin,exchangeNumerator_eq_table,exchangeTable, + exchangeDenominator,insertion_eq_table,insertionTable,T,t] + +theorem insertion_slide_entry_7_2 (x : ℂ) : + insertionSlideLeft x .zero .minus .plus .zero .minus = insertionSlideRight x .zero .minus .plus .zero .minus := by + norm_num [insertionSlideLeft,insertionSlideRight,sum_spin,exchangeNumerator_eq_table,exchangeTable, + exchangeDenominator,insertion_eq_table,insertionTable,T,t] + +theorem insertion_slide_entry_7_3 (x : ℂ) : + insertionSlideLeft x .zero .minus .plus .plus .zero = insertionSlideRight x .zero .minus .plus .plus .zero := by + norm_num [insertionSlideLeft,insertionSlideRight,sum_spin,exchangeNumerator_eq_table,exchangeTable, + exchangeDenominator,insertion_eq_table,insertionTable,T,t] + +theorem insertion_slide_entry_7_4 (x : ℂ) : + insertionSlideLeft x .zero .minus .plus .plus .plus = insertionSlideRight x .zero .minus .plus .plus .plus := by + norm_num [insertionSlideLeft,insertionSlideRight,sum_spin,exchangeNumerator_eq_table,exchangeTable, + exchangeDenominator,insertion_eq_table,insertionTable,T,t] + +theorem insertion_slide_entry_7_5 (x : ℂ) : + insertionSlideLeft x .zero .minus .plus .plus .minus = insertionSlideRight x .zero .minus .plus .plus .minus := by + norm_num [insertionSlideLeft,insertionSlideRight,sum_spin,exchangeNumerator_eq_table,exchangeTable, + exchangeDenominator,insertion_eq_table,insertionTable,T,t] + all_goals vacuum_ring_finish + +theorem insertion_slide_entry_7_6 (x : ℂ) : + insertionSlideLeft x .zero .minus .plus .minus .zero = insertionSlideRight x .zero .minus .plus .minus .zero := by + norm_num [insertionSlideLeft,insertionSlideRight,sum_spin,exchangeNumerator_eq_table,exchangeTable, + exchangeDenominator,insertion_eq_table,insertionTable,T,t] + +theorem insertion_slide_entry_7_7 (x : ℂ) : + insertionSlideLeft x .zero .minus .plus .minus .plus = insertionSlideRight x .zero .minus .plus .minus .plus := by + norm_num [insertionSlideLeft,insertionSlideRight,sum_spin,exchangeNumerator_eq_table,exchangeTable, + exchangeDenominator,insertion_eq_table,insertionTable,T,t] + all_goals vacuum_ring_finish + +theorem insertion_slide_entry_7_8 (x : ℂ) : + insertionSlideLeft x .zero .minus .plus .minus .minus = insertionSlideRight x .zero .minus .plus .minus .minus := by + norm_num [insertionSlideLeft,insertionSlideRight,sum_spin,exchangeNumerator_eq_table,exchangeTable, + exchangeDenominator,insertion_eq_table,insertionTable,T,t] + +theorem insertion_slide_entry_8_0 (x : ℂ) : + insertionSlideLeft x .zero .minus .minus .zero .zero = insertionSlideRight x .zero .minus .minus .zero .zero := by + norm_num [insertionSlideLeft,insertionSlideRight,sum_spin,exchangeNumerator_eq_table,exchangeTable, + exchangeDenominator,insertion_eq_table,insertionTable,T,t] + +theorem insertion_slide_entry_8_1 (x : ℂ) : + insertionSlideLeft x .zero .minus .minus .zero .plus = insertionSlideRight x .zero .minus .minus .zero .plus := by + norm_num [insertionSlideLeft,insertionSlideRight,sum_spin,exchangeNumerator_eq_table,exchangeTable, + exchangeDenominator,insertion_eq_table,insertionTable,T,t] + +theorem insertion_slide_entry_8_2 (x : ℂ) : + insertionSlideLeft x .zero .minus .minus .zero .minus = insertionSlideRight x .zero .minus .minus .zero .minus := by + norm_num [insertionSlideLeft,insertionSlideRight,sum_spin,exchangeNumerator_eq_table,exchangeTable, + exchangeDenominator,insertion_eq_table,insertionTable,T,t] + +theorem insertion_slide_entry_8_3 (x : ℂ) : + insertionSlideLeft x .zero .minus .minus .plus .zero = insertionSlideRight x .zero .minus .minus .plus .zero := by + norm_num [insertionSlideLeft,insertionSlideRight,sum_spin,exchangeNumerator_eq_table,exchangeTable, + exchangeDenominator,insertion_eq_table,insertionTable,T,t] + +theorem insertion_slide_entry_8_4 (x : ℂ) : + insertionSlideLeft x .zero .minus .minus .plus .plus = insertionSlideRight x .zero .minus .minus .plus .plus := by + norm_num [insertionSlideLeft,insertionSlideRight,sum_spin,exchangeNumerator_eq_table,exchangeTable, + exchangeDenominator,insertion_eq_table,insertionTable,T,t] + +theorem insertion_slide_entry_8_5 (x : ℂ) : + insertionSlideLeft x .zero .minus .minus .plus .minus = insertionSlideRight x .zero .minus .minus .plus .minus := by + norm_num [insertionSlideLeft,insertionSlideRight,sum_spin,exchangeNumerator_eq_table,exchangeTable, + exchangeDenominator,insertion_eq_table,insertionTable,T,t] + +theorem insertion_slide_entry_8_6 (x : ℂ) : + insertionSlideLeft x .zero .minus .minus .minus .zero = insertionSlideRight x .zero .minus .minus .minus .zero := by + norm_num [insertionSlideLeft,insertionSlideRight,sum_spin,exchangeNumerator_eq_table,exchangeTable, + exchangeDenominator,insertion_eq_table,insertionTable,T,t] + +theorem insertion_slide_entry_8_7 (x : ℂ) : + insertionSlideLeft x .zero .minus .minus .minus .plus = insertionSlideRight x .zero .minus .minus .minus .plus := by + norm_num [insertionSlideLeft,insertionSlideRight,sum_spin,exchangeNumerator_eq_table,exchangeTable, + exchangeDenominator,insertion_eq_table,insertionTable,T,t] + +theorem insertion_slide_entry_8_8 (x : ℂ) : + insertionSlideLeft x .zero .minus .minus .minus .minus = insertionSlideRight x .zero .minus .minus .minus .minus := by + norm_num [insertionSlideLeft,insertionSlideRight,sum_spin,exchangeNumerator_eq_table,exchangeTable, + exchangeDenominator,insertion_eq_table,insertionTable,T,t] + all_goals vacuum_ring_finish + +theorem insertion_slide_entry_9_0 (x : ℂ) : + insertionSlideLeft x .plus .zero .zero .zero .zero = insertionSlideRight x .plus .zero .zero .zero .zero := by + norm_num [insertionSlideLeft,insertionSlideRight,sum_spin,exchangeNumerator_eq_table,exchangeTable, + exchangeDenominator,insertion_eq_table,insertionTable,T,t] + +theorem insertion_slide_entry_9_1 (x : ℂ) : + insertionSlideLeft x .plus .zero .zero .zero .plus = insertionSlideRight x .plus .zero .zero .zero .plus := by + norm_num [insertionSlideLeft,insertionSlideRight,sum_spin,exchangeNumerator_eq_table,exchangeTable, + exchangeDenominator,insertion_eq_table,insertionTable,T,t] + all_goals vacuum_ring_finish + +theorem insertion_slide_entry_9_2 (x : ℂ) : + insertionSlideLeft x .plus .zero .zero .zero .minus = insertionSlideRight x .plus .zero .zero .zero .minus := by + norm_num [insertionSlideLeft,insertionSlideRight,sum_spin,exchangeNumerator_eq_table,exchangeTable, + exchangeDenominator,insertion_eq_table,insertionTable,T,t] + +theorem insertion_slide_entry_9_3 (x : ℂ) : + insertionSlideLeft x .plus .zero .zero .plus .zero = insertionSlideRight x .plus .zero .zero .plus .zero := by + norm_num [insertionSlideLeft,insertionSlideRight,sum_spin,exchangeNumerator_eq_table,exchangeTable, + exchangeDenominator,insertion_eq_table,insertionTable,T,t] + all_goals vacuum_ring_finish + +theorem insertion_slide_entry_9_4 (x : ℂ) : + insertionSlideLeft x .plus .zero .zero .plus .plus = insertionSlideRight x .plus .zero .zero .plus .plus := by + norm_num [insertionSlideLeft,insertionSlideRight,sum_spin,exchangeNumerator_eq_table,exchangeTable, + exchangeDenominator,insertion_eq_table,insertionTable,T,t] + +theorem insertion_slide_entry_9_5 (x : ℂ) : + insertionSlideLeft x .plus .zero .zero .plus .minus = insertionSlideRight x .plus .zero .zero .plus .minus := by + norm_num [insertionSlideLeft,insertionSlideRight,sum_spin,exchangeNumerator_eq_table,exchangeTable, + exchangeDenominator,insertion_eq_table,insertionTable,T,t] + +theorem insertion_slide_entry_9_6 (x : ℂ) : + insertionSlideLeft x .plus .zero .zero .minus .zero = insertionSlideRight x .plus .zero .zero .minus .zero := by + norm_num [insertionSlideLeft,insertionSlideRight,sum_spin,exchangeNumerator_eq_table,exchangeTable, + exchangeDenominator,insertion_eq_table,insertionTable,T,t] + +theorem insertion_slide_entry_9_7 (x : ℂ) : + insertionSlideLeft x .plus .zero .zero .minus .plus = insertionSlideRight x .plus .zero .zero .minus .plus := by + norm_num [insertionSlideLeft,insertionSlideRight,sum_spin,exchangeNumerator_eq_table,exchangeTable, + exchangeDenominator,insertion_eq_table,insertionTable,T,t] + +theorem insertion_slide_entry_9_8 (x : ℂ) : + insertionSlideLeft x .plus .zero .zero .minus .minus = insertionSlideRight x .plus .zero .zero .minus .minus := by + norm_num [insertionSlideLeft,insertionSlideRight,sum_spin,exchangeNumerator_eq_table,exchangeTable, + exchangeDenominator,insertion_eq_table,insertionTable,T,t] + +theorem insertion_slide_entry_10_0 (x : ℂ) : + insertionSlideLeft x .plus .zero .plus .zero .zero = insertionSlideRight x .plus .zero .plus .zero .zero := by + norm_num [insertionSlideLeft,insertionSlideRight,sum_spin,exchangeNumerator_eq_table,exchangeTable, + exchangeDenominator,insertion_eq_table,insertionTable,T,t] + +theorem insertion_slide_entry_10_1 (x : ℂ) : + insertionSlideLeft x .plus .zero .plus .zero .plus = insertionSlideRight x .plus .zero .plus .zero .plus := by + norm_num [insertionSlideLeft,insertionSlideRight,sum_spin,exchangeNumerator_eq_table,exchangeTable, + exchangeDenominator,insertion_eq_table,insertionTable,T,t] + +theorem insertion_slide_entry_10_2 (x : ℂ) : + insertionSlideLeft x .plus .zero .plus .zero .minus = insertionSlideRight x .plus .zero .plus .zero .minus := by + norm_num [insertionSlideLeft,insertionSlideRight,sum_spin,exchangeNumerator_eq_table,exchangeTable, + exchangeDenominator,insertion_eq_table,insertionTable,T,t] + +theorem insertion_slide_entry_10_3 (x : ℂ) : + insertionSlideLeft x .plus .zero .plus .plus .zero = insertionSlideRight x .plus .zero .plus .plus .zero := by + norm_num [insertionSlideLeft,insertionSlideRight,sum_spin,exchangeNumerator_eq_table,exchangeTable, + exchangeDenominator,insertion_eq_table,insertionTable,T,t] + +theorem insertion_slide_entry_10_4 (x : ℂ) : + insertionSlideLeft x .plus .zero .plus .plus .plus = insertionSlideRight x .plus .zero .plus .plus .plus := by + norm_num [insertionSlideLeft,insertionSlideRight,sum_spin,exchangeNumerator_eq_table,exchangeTable, + exchangeDenominator,insertion_eq_table,insertionTable,T,t] + all_goals vacuum_ring_finish + +theorem insertion_slide_entry_10_5 (x : ℂ) : + insertionSlideLeft x .plus .zero .plus .plus .minus = insertionSlideRight x .plus .zero .plus .plus .minus := by + norm_num [insertionSlideLeft,insertionSlideRight,sum_spin,exchangeNumerator_eq_table,exchangeTable, + exchangeDenominator,insertion_eq_table,insertionTable,T,t] + +theorem insertion_slide_entry_10_6 (x : ℂ) : + insertionSlideLeft x .plus .zero .plus .minus .zero = insertionSlideRight x .plus .zero .plus .minus .zero := by + norm_num [insertionSlideLeft,insertionSlideRight,sum_spin,exchangeNumerator_eq_table,exchangeTable, + exchangeDenominator,insertion_eq_table,insertionTable,T,t] + +theorem insertion_slide_entry_10_7 (x : ℂ) : + insertionSlideLeft x .plus .zero .plus .minus .plus = insertionSlideRight x .plus .zero .plus .minus .plus := by + norm_num [insertionSlideLeft,insertionSlideRight,sum_spin,exchangeNumerator_eq_table,exchangeTable, + exchangeDenominator,insertion_eq_table,insertionTable,T,t] + +theorem insertion_slide_entry_10_8 (x : ℂ) : + insertionSlideLeft x .plus .zero .plus .minus .minus = insertionSlideRight x .plus .zero .plus .minus .minus := by + norm_num [insertionSlideLeft,insertionSlideRight,sum_spin,exchangeNumerator_eq_table,exchangeTable, + exchangeDenominator,insertion_eq_table,insertionTable,T,t] + +theorem insertion_slide_entry_11_0 (x : ℂ) : + insertionSlideLeft x .plus .zero .minus .zero .zero = insertionSlideRight x .plus .zero .minus .zero .zero := by + norm_num [insertionSlideLeft,insertionSlideRight,sum_spin,exchangeNumerator_eq_table,exchangeTable, + exchangeDenominator,insertion_eq_table,insertionTable,T,t] + all_goals vacuum_ring_finish + +theorem insertion_slide_entry_11_1 (x : ℂ) : + insertionSlideLeft x .plus .zero .minus .zero .plus = insertionSlideRight x .plus .zero .minus .zero .plus := by + norm_num [insertionSlideLeft,insertionSlideRight,sum_spin,exchangeNumerator_eq_table,exchangeTable, + exchangeDenominator,insertion_eq_table,insertionTable,T,t] + +theorem insertion_slide_entry_11_2 (x : ℂ) : + insertionSlideLeft x .plus .zero .minus .zero .minus = insertionSlideRight x .plus .zero .minus .zero .minus := by + norm_num [insertionSlideLeft,insertionSlideRight,sum_spin,exchangeNumerator_eq_table,exchangeTable, + exchangeDenominator,insertion_eq_table,insertionTable,T,t] + +theorem insertion_slide_entry_11_3 (x : ℂ) : + insertionSlideLeft x .plus .zero .minus .plus .zero = insertionSlideRight x .plus .zero .minus .plus .zero := by + norm_num [insertionSlideLeft,insertionSlideRight,sum_spin,exchangeNumerator_eq_table,exchangeTable, + exchangeDenominator,insertion_eq_table,insertionTable,T,t] + +theorem insertion_slide_entry_11_4 (x : ℂ) : + insertionSlideLeft x .plus .zero .minus .plus .plus = insertionSlideRight x .plus .zero .minus .plus .plus := by + norm_num [insertionSlideLeft,insertionSlideRight,sum_spin,exchangeNumerator_eq_table,exchangeTable, + exchangeDenominator,insertion_eq_table,insertionTable,T,t] + +theorem insertion_slide_entry_11_5 (x : ℂ) : + insertionSlideLeft x .plus .zero .minus .plus .minus = insertionSlideRight x .plus .zero .minus .plus .minus := by + norm_num [insertionSlideLeft,insertionSlideRight,sum_spin,exchangeNumerator_eq_table,exchangeTable, + exchangeDenominator,insertion_eq_table,insertionTable,T,t] + all_goals vacuum_ring_finish + +theorem insertion_slide_entry_11_6 (x : ℂ) : + insertionSlideLeft x .plus .zero .minus .minus .zero = insertionSlideRight x .plus .zero .minus .minus .zero := by + norm_num [insertionSlideLeft,insertionSlideRight,sum_spin,exchangeNumerator_eq_table,exchangeTable, + exchangeDenominator,insertion_eq_table,insertionTable,T,t] + +theorem insertion_slide_entry_11_7 (x : ℂ) : + insertionSlideLeft x .plus .zero .minus .minus .plus = insertionSlideRight x .plus .zero .minus .minus .plus := by + norm_num [insertionSlideLeft,insertionSlideRight,sum_spin,exchangeNumerator_eq_table,exchangeTable, + exchangeDenominator,insertion_eq_table,insertionTable,T,t] + all_goals vacuum_ring_finish + +theorem insertion_slide_entry_11_8 (x : ℂ) : + insertionSlideLeft x .plus .zero .minus .minus .minus = insertionSlideRight x .plus .zero .minus .minus .minus := by + norm_num [insertionSlideLeft,insertionSlideRight,sum_spin,exchangeNumerator_eq_table,exchangeTable, + exchangeDenominator,insertion_eq_table,insertionTable,T,t] + +theorem insertion_slide_entry_12_0 (x : ℂ) : + insertionSlideLeft x .plus .plus .zero .zero .zero = insertionSlideRight x .plus .plus .zero .zero .zero := by + norm_num [insertionSlideLeft,insertionSlideRight,sum_spin,exchangeNumerator_eq_table,exchangeTable, + exchangeDenominator,insertion_eq_table,insertionTable,T,t] + +theorem insertion_slide_entry_12_1 (x : ℂ) : + insertionSlideLeft x .plus .plus .zero .zero .plus = insertionSlideRight x .plus .plus .zero .zero .plus := by + norm_num [insertionSlideLeft,insertionSlideRight,sum_spin,exchangeNumerator_eq_table,exchangeTable, + exchangeDenominator,insertion_eq_table,insertionTable,T,t] + +theorem insertion_slide_entry_12_2 (x : ℂ) : + insertionSlideLeft x .plus .plus .zero .zero .minus = insertionSlideRight x .plus .plus .zero .zero .minus := by + norm_num [insertionSlideLeft,insertionSlideRight,sum_spin,exchangeNumerator_eq_table,exchangeTable, + exchangeDenominator,insertion_eq_table,insertionTable,T,t] + +theorem insertion_slide_entry_12_3 (x : ℂ) : + insertionSlideLeft x .plus .plus .zero .plus .zero = insertionSlideRight x .plus .plus .zero .plus .zero := by + norm_num [insertionSlideLeft,insertionSlideRight,sum_spin,exchangeNumerator_eq_table,exchangeTable, + exchangeDenominator,insertion_eq_table,insertionTable,T,t] + +theorem insertion_slide_entry_12_4 (x : ℂ) : + insertionSlideLeft x .plus .plus .zero .plus .plus = insertionSlideRight x .plus .plus .zero .plus .plus := by + norm_num [insertionSlideLeft,insertionSlideRight,sum_spin,exchangeNumerator_eq_table,exchangeTable, + exchangeDenominator,insertion_eq_table,insertionTable,T,t] + all_goals vacuum_ring_finish + +theorem insertion_slide_entry_12_5 (x : ℂ) : + insertionSlideLeft x .plus .plus .zero .plus .minus = insertionSlideRight x .plus .plus .zero .plus .minus := by + norm_num [insertionSlideLeft,insertionSlideRight,sum_spin,exchangeNumerator_eq_table,exchangeTable, + exchangeDenominator,insertion_eq_table,insertionTable,T,t] + +theorem insertion_slide_entry_12_6 (x : ℂ) : + insertionSlideLeft x .plus .plus .zero .minus .zero = insertionSlideRight x .plus .plus .zero .minus .zero := by + norm_num [insertionSlideLeft,insertionSlideRight,sum_spin,exchangeNumerator_eq_table,exchangeTable, + exchangeDenominator,insertion_eq_table,insertionTable,T,t] + +theorem insertion_slide_entry_12_7 (x : ℂ) : + insertionSlideLeft x .plus .plus .zero .minus .plus = insertionSlideRight x .plus .plus .zero .minus .plus := by + norm_num [insertionSlideLeft,insertionSlideRight,sum_spin,exchangeNumerator_eq_table,exchangeTable, + exchangeDenominator,insertion_eq_table,insertionTable,T,t] + +theorem insertion_slide_entry_12_8 (x : ℂ) : + insertionSlideLeft x .plus .plus .zero .minus .minus = insertionSlideRight x .plus .plus .zero .minus .minus := by + norm_num [insertionSlideLeft,insertionSlideRight,sum_spin,exchangeNumerator_eq_table,exchangeTable, + exchangeDenominator,insertion_eq_table,insertionTable,T,t] + +theorem insertion_slide_entry_13_0 (x : ℂ) : + insertionSlideLeft x .plus .plus .plus .zero .zero = insertionSlideRight x .plus .plus .plus .zero .zero := by + norm_num [insertionSlideLeft,insertionSlideRight,sum_spin,exchangeNumerator_eq_table,exchangeTable, + exchangeDenominator,insertion_eq_table,insertionTable,T,t] + +theorem insertion_slide_entry_13_1 (x : ℂ) : + insertionSlideLeft x .plus .plus .plus .zero .plus = insertionSlideRight x .plus .plus .plus .zero .plus := by + norm_num [insertionSlideLeft,insertionSlideRight,sum_spin,exchangeNumerator_eq_table,exchangeTable, + exchangeDenominator,insertion_eq_table,insertionTable,T,t] + +theorem insertion_slide_entry_13_2 (x : ℂ) : + insertionSlideLeft x .plus .plus .plus .zero .minus = insertionSlideRight x .plus .plus .plus .zero .minus := by + norm_num [insertionSlideLeft,insertionSlideRight,sum_spin,exchangeNumerator_eq_table,exchangeTable, + exchangeDenominator,insertion_eq_table,insertionTable,T,t] + +theorem insertion_slide_entry_13_3 (x : ℂ) : + insertionSlideLeft x .plus .plus .plus .plus .zero = insertionSlideRight x .plus .plus .plus .plus .zero := by + norm_num [insertionSlideLeft,insertionSlideRight,sum_spin,exchangeNumerator_eq_table,exchangeTable, + exchangeDenominator,insertion_eq_table,insertionTable,T,t] + +theorem insertion_slide_entry_13_4 (x : ℂ) : + insertionSlideLeft x .plus .plus .plus .plus .plus = insertionSlideRight x .plus .plus .plus .plus .plus := by + norm_num [insertionSlideLeft,insertionSlideRight,sum_spin,exchangeNumerator_eq_table,exchangeTable, + exchangeDenominator,insertion_eq_table,insertionTable,T,t] + +theorem insertion_slide_entry_13_5 (x : ℂ) : + insertionSlideLeft x .plus .plus .plus .plus .minus = insertionSlideRight x .plus .plus .plus .plus .minus := by + norm_num [insertionSlideLeft,insertionSlideRight,sum_spin,exchangeNumerator_eq_table,exchangeTable, + exchangeDenominator,insertion_eq_table,insertionTable,T,t] + +theorem insertion_slide_entry_13_6 (x : ℂ) : + insertionSlideLeft x .plus .plus .plus .minus .zero = insertionSlideRight x .plus .plus .plus .minus .zero := by + norm_num [insertionSlideLeft,insertionSlideRight,sum_spin,exchangeNumerator_eq_table,exchangeTable, + exchangeDenominator,insertion_eq_table,insertionTable,T,t] + +theorem insertion_slide_entry_13_7 (x : ℂ) : + insertionSlideLeft x .plus .plus .plus .minus .plus = insertionSlideRight x .plus .plus .plus .minus .plus := by + norm_num [insertionSlideLeft,insertionSlideRight,sum_spin,exchangeNumerator_eq_table,exchangeTable, + exchangeDenominator,insertion_eq_table,insertionTable,T,t] + +theorem insertion_slide_entry_13_8 (x : ℂ) : + insertionSlideLeft x .plus .plus .plus .minus .minus = insertionSlideRight x .plus .plus .plus .minus .minus := by + norm_num [insertionSlideLeft,insertionSlideRight,sum_spin,exchangeNumerator_eq_table,exchangeTable, + exchangeDenominator,insertion_eq_table,insertionTable,T,t] + +theorem insertion_slide_entry_14_0 (x : ℂ) : + insertionSlideLeft x .plus .plus .minus .zero .zero = insertionSlideRight x .plus .plus .minus .zero .zero := by + norm_num [insertionSlideLeft,insertionSlideRight,sum_spin,exchangeNumerator_eq_table,exchangeTable, + exchangeDenominator,insertion_eq_table,insertionTable,T,t] + +theorem insertion_slide_entry_14_1 (x : ℂ) : + insertionSlideLeft x .plus .plus .minus .zero .plus = insertionSlideRight x .plus .plus .minus .zero .plus := by + norm_num [insertionSlideLeft,insertionSlideRight,sum_spin,exchangeNumerator_eq_table,exchangeTable, + exchangeDenominator,insertion_eq_table,insertionTable,T,t] + all_goals vacuum_ring_finish + +theorem insertion_slide_entry_14_2 (x : ℂ) : + insertionSlideLeft x .plus .plus .minus .zero .minus = insertionSlideRight x .plus .plus .minus .zero .minus := by + norm_num [insertionSlideLeft,insertionSlideRight,sum_spin,exchangeNumerator_eq_table,exchangeTable, + exchangeDenominator,insertion_eq_table,insertionTable,T,t] + +theorem insertion_slide_entry_14_3 (x : ℂ) : + insertionSlideLeft x .plus .plus .minus .plus .zero = insertionSlideRight x .plus .plus .minus .plus .zero := by + norm_num [insertionSlideLeft,insertionSlideRight,sum_spin,exchangeNumerator_eq_table,exchangeTable, + exchangeDenominator,insertion_eq_table,insertionTable,T,t] + all_goals vacuum_ring_finish + +theorem insertion_slide_entry_14_4 (x : ℂ) : + insertionSlideLeft x .plus .plus .minus .plus .plus = insertionSlideRight x .plus .plus .minus .plus .plus := by + norm_num [insertionSlideLeft,insertionSlideRight,sum_spin,exchangeNumerator_eq_table,exchangeTable, + exchangeDenominator,insertion_eq_table,insertionTable,T,t] + +theorem insertion_slide_entry_14_5 (x : ℂ) : + insertionSlideLeft x .plus .plus .minus .plus .minus = insertionSlideRight x .plus .plus .minus .plus .minus := by + norm_num [insertionSlideLeft,insertionSlideRight,sum_spin,exchangeNumerator_eq_table,exchangeTable, + exchangeDenominator,insertion_eq_table,insertionTable,T,t] + +theorem insertion_slide_entry_14_6 (x : ℂ) : + insertionSlideLeft x .plus .plus .minus .minus .zero = insertionSlideRight x .plus .plus .minus .minus .zero := by + norm_num [insertionSlideLeft,insertionSlideRight,sum_spin,exchangeNumerator_eq_table,exchangeTable, + exchangeDenominator,insertion_eq_table,insertionTable,T,t] + +theorem insertion_slide_entry_14_7 (x : ℂ) : + insertionSlideLeft x .plus .plus .minus .minus .plus = insertionSlideRight x .plus .plus .minus .minus .plus := by + norm_num [insertionSlideLeft,insertionSlideRight,sum_spin,exchangeNumerator_eq_table,exchangeTable, + exchangeDenominator,insertion_eq_table,insertionTable,T,t] + +theorem insertion_slide_entry_14_8 (x : ℂ) : + insertionSlideLeft x .plus .plus .minus .minus .minus = insertionSlideRight x .plus .plus .minus .minus .minus := by + norm_num [insertionSlideLeft,insertionSlideRight,sum_spin,exchangeNumerator_eq_table,exchangeTable, + exchangeDenominator,insertion_eq_table,insertionTable,T,t] + +theorem insertion_slide_entry_15_0 (x : ℂ) : + insertionSlideLeft x .plus .minus .zero .zero .zero = insertionSlideRight x .plus .minus .zero .zero .zero := by + norm_num [insertionSlideLeft,insertionSlideRight,sum_spin,exchangeNumerator_eq_table,exchangeTable, + exchangeDenominator,insertion_eq_table,insertionTable,T,t] + all_goals vacuum_ring_finish + +theorem insertion_slide_entry_15_1 (x : ℂ) : + insertionSlideLeft x .plus .minus .zero .zero .plus = insertionSlideRight x .plus .minus .zero .zero .plus := by + norm_num [insertionSlideLeft,insertionSlideRight,sum_spin,exchangeNumerator_eq_table,exchangeTable, + exchangeDenominator,insertion_eq_table,insertionTable,T,t] + +theorem insertion_slide_entry_15_2 (x : ℂ) : + insertionSlideLeft x .plus .minus .zero .zero .minus = insertionSlideRight x .plus .minus .zero .zero .minus := by + norm_num [insertionSlideLeft,insertionSlideRight,sum_spin,exchangeNumerator_eq_table,exchangeTable, + exchangeDenominator,insertion_eq_table,insertionTable,T,t] + +theorem insertion_slide_entry_15_3 (x : ℂ) : + insertionSlideLeft x .plus .minus .zero .plus .zero = insertionSlideRight x .plus .minus .zero .plus .zero := by + norm_num [insertionSlideLeft,insertionSlideRight,sum_spin,exchangeNumerator_eq_table,exchangeTable, + exchangeDenominator,insertion_eq_table,insertionTable,T,t] + +theorem insertion_slide_entry_15_4 (x : ℂ) : + insertionSlideLeft x .plus .minus .zero .plus .plus = insertionSlideRight x .plus .minus .zero .plus .plus := by + norm_num [insertionSlideLeft,insertionSlideRight,sum_spin,exchangeNumerator_eq_table,exchangeTable, + exchangeDenominator,insertion_eq_table,insertionTable,T,t] + +theorem insertion_slide_entry_15_5 (x : ℂ) : + insertionSlideLeft x .plus .minus .zero .plus .minus = insertionSlideRight x .plus .minus .zero .plus .minus := by + norm_num [insertionSlideLeft,insertionSlideRight,sum_spin,exchangeNumerator_eq_table,exchangeTable, + exchangeDenominator,insertion_eq_table,insertionTable,T,t] + all_goals vacuum_ring_finish + +theorem insertion_slide_entry_15_6 (x : ℂ) : + insertionSlideLeft x .plus .minus .zero .minus .zero = insertionSlideRight x .plus .minus .zero .minus .zero := by + norm_num [insertionSlideLeft,insertionSlideRight,sum_spin,exchangeNumerator_eq_table,exchangeTable, + exchangeDenominator,insertion_eq_table,insertionTable,T,t] + +theorem insertion_slide_entry_15_7 (x : ℂ) : + insertionSlideLeft x .plus .minus .zero .minus .plus = insertionSlideRight x .plus .minus .zero .minus .plus := by + norm_num [insertionSlideLeft,insertionSlideRight,sum_spin,exchangeNumerator_eq_table,exchangeTable, + exchangeDenominator,insertion_eq_table,insertionTable,T,t] + all_goals vacuum_ring_finish + +theorem insertion_slide_entry_15_8 (x : ℂ) : + insertionSlideLeft x .plus .minus .zero .minus .minus = insertionSlideRight x .plus .minus .zero .minus .minus := by + norm_num [insertionSlideLeft,insertionSlideRight,sum_spin,exchangeNumerator_eq_table,exchangeTable, + exchangeDenominator,insertion_eq_table,insertionTable,T,t] + +theorem insertion_slide_entry_16_0 (x : ℂ) : + insertionSlideLeft x .plus .minus .plus .zero .zero = insertionSlideRight x .plus .minus .plus .zero .zero := by + norm_num [insertionSlideLeft,insertionSlideRight,sum_spin,exchangeNumerator_eq_table,exchangeTable, + exchangeDenominator,insertion_eq_table,insertionTable,T,t] + +theorem insertion_slide_entry_16_1 (x : ℂ) : + insertionSlideLeft x .plus .minus .plus .zero .plus = insertionSlideRight x .plus .minus .plus .zero .plus := by + norm_num [insertionSlideLeft,insertionSlideRight,sum_spin,exchangeNumerator_eq_table,exchangeTable, + exchangeDenominator,insertion_eq_table,insertionTable,T,t] + all_goals vacuum_ring_finish + +theorem insertion_slide_entry_16_2 (x : ℂ) : + insertionSlideLeft x .plus .minus .plus .zero .minus = insertionSlideRight x .plus .minus .plus .zero .minus := by + norm_num [insertionSlideLeft,insertionSlideRight,sum_spin,exchangeNumerator_eq_table,exchangeTable, + exchangeDenominator,insertion_eq_table,insertionTable,T,t] + +theorem insertion_slide_entry_16_3 (x : ℂ) : + insertionSlideLeft x .plus .minus .plus .plus .zero = insertionSlideRight x .plus .minus .plus .plus .zero := by + norm_num [insertionSlideLeft,insertionSlideRight,sum_spin,exchangeNumerator_eq_table,exchangeTable, + exchangeDenominator,insertion_eq_table,insertionTable,T,t] + all_goals vacuum_ring_finish + +theorem insertion_slide_entry_16_4 (x : ℂ) : + insertionSlideLeft x .plus .minus .plus .plus .plus = insertionSlideRight x .plus .minus .plus .plus .plus := by + norm_num [insertionSlideLeft,insertionSlideRight,sum_spin,exchangeNumerator_eq_table,exchangeTable, + exchangeDenominator,insertion_eq_table,insertionTable,T,t] + +theorem insertion_slide_entry_16_5 (x : ℂ) : + insertionSlideLeft x .plus .minus .plus .plus .minus = insertionSlideRight x .plus .minus .plus .plus .minus := by + norm_num [insertionSlideLeft,insertionSlideRight,sum_spin,exchangeNumerator_eq_table,exchangeTable, + exchangeDenominator,insertion_eq_table,insertionTable,T,t] + +theorem insertion_slide_entry_16_6 (x : ℂ) : + insertionSlideLeft x .plus .minus .plus .minus .zero = insertionSlideRight x .plus .minus .plus .minus .zero := by + norm_num [insertionSlideLeft,insertionSlideRight,sum_spin,exchangeNumerator_eq_table,exchangeTable, + exchangeDenominator,insertion_eq_table,insertionTable,T,t] + +theorem insertion_slide_entry_16_7 (x : ℂ) : + insertionSlideLeft x .plus .minus .plus .minus .plus = insertionSlideRight x .plus .minus .plus .minus .plus := by + norm_num [insertionSlideLeft,insertionSlideRight,sum_spin,exchangeNumerator_eq_table,exchangeTable, + exchangeDenominator,insertion_eq_table,insertionTable,T,t] + +theorem insertion_slide_entry_16_8 (x : ℂ) : + insertionSlideLeft x .plus .minus .plus .minus .minus = insertionSlideRight x .plus .minus .plus .minus .minus := by + norm_num [insertionSlideLeft,insertionSlideRight,sum_spin,exchangeNumerator_eq_table,exchangeTable, + exchangeDenominator,insertion_eq_table,insertionTable,T,t] + +theorem insertion_slide_entry_17_0 (x : ℂ) : + insertionSlideLeft x .plus .minus .minus .zero .zero = insertionSlideRight x .plus .minus .minus .zero .zero := by + norm_num [insertionSlideLeft,insertionSlideRight,sum_spin,exchangeNumerator_eq_table,exchangeTable, + exchangeDenominator,insertion_eq_table,insertionTable,T,t] + +theorem insertion_slide_entry_17_1 (x : ℂ) : + insertionSlideLeft x .plus .minus .minus .zero .plus = insertionSlideRight x .plus .minus .minus .zero .plus := by + norm_num [insertionSlideLeft,insertionSlideRight,sum_spin,exchangeNumerator_eq_table,exchangeTable, + exchangeDenominator,insertion_eq_table,insertionTable,T,t] + +theorem insertion_slide_entry_17_2 (x : ℂ) : + insertionSlideLeft x .plus .minus .minus .zero .minus = insertionSlideRight x .plus .minus .minus .zero .minus := by + norm_num [insertionSlideLeft,insertionSlideRight,sum_spin,exchangeNumerator_eq_table,exchangeTable, + exchangeDenominator,insertion_eq_table,insertionTable,T,t] + all_goals vacuum_ring_finish + +theorem insertion_slide_entry_17_3 (x : ℂ) : + insertionSlideLeft x .plus .minus .minus .plus .zero = insertionSlideRight x .plus .minus .minus .plus .zero := by + norm_num [insertionSlideLeft,insertionSlideRight,sum_spin,exchangeNumerator_eq_table,exchangeTable, + exchangeDenominator,insertion_eq_table,insertionTable,T,t] + +theorem insertion_slide_entry_17_4 (x : ℂ) : + insertionSlideLeft x .plus .minus .minus .plus .plus = insertionSlideRight x .plus .minus .minus .plus .plus := by + norm_num [insertionSlideLeft,insertionSlideRight,sum_spin,exchangeNumerator_eq_table,exchangeTable, + exchangeDenominator,insertion_eq_table,insertionTable,T,t] + +theorem insertion_slide_entry_17_5 (x : ℂ) : + insertionSlideLeft x .plus .minus .minus .plus .minus = insertionSlideRight x .plus .minus .minus .plus .minus := by + norm_num [insertionSlideLeft,insertionSlideRight,sum_spin,exchangeNumerator_eq_table,exchangeTable, + exchangeDenominator,insertion_eq_table,insertionTable,T,t] + +theorem insertion_slide_entry_17_6 (x : ℂ) : + insertionSlideLeft x .plus .minus .minus .minus .zero = insertionSlideRight x .plus .minus .minus .minus .zero := by + norm_num [insertionSlideLeft,insertionSlideRight,sum_spin,exchangeNumerator_eq_table,exchangeTable, + exchangeDenominator,insertion_eq_table,insertionTable,T,t] + all_goals vacuum_ring_finish + +theorem insertion_slide_entry_17_7 (x : ℂ) : + insertionSlideLeft x .plus .minus .minus .minus .plus = insertionSlideRight x .plus .minus .minus .minus .plus := by + norm_num [insertionSlideLeft,insertionSlideRight,sum_spin,exchangeNumerator_eq_table,exchangeTable, + exchangeDenominator,insertion_eq_table,insertionTable,T,t] + +theorem insertion_slide_entry_17_8 (x : ℂ) : + insertionSlideLeft x .plus .minus .minus .minus .minus = insertionSlideRight x .plus .minus .minus .minus .minus := by + norm_num [insertionSlideLeft,insertionSlideRight,sum_spin,exchangeNumerator_eq_table,exchangeTable, + exchangeDenominator,insertion_eq_table,insertionTable,T,t] + +theorem insertion_slide_entry_18_0 (x : ℂ) : + insertionSlideLeft x .minus .zero .zero .zero .zero = insertionSlideRight x .minus .zero .zero .zero .zero := by + norm_num [insertionSlideLeft,insertionSlideRight,sum_spin,exchangeNumerator_eq_table,exchangeTable, + exchangeDenominator,insertion_eq_table,insertionTable,T,t] + +theorem insertion_slide_entry_18_1 (x : ℂ) : + insertionSlideLeft x .minus .zero .zero .zero .plus = insertionSlideRight x .minus .zero .zero .zero .plus := by + norm_num [insertionSlideLeft,insertionSlideRight,sum_spin,exchangeNumerator_eq_table,exchangeTable, + exchangeDenominator,insertion_eq_table,insertionTable,T,t] + +theorem insertion_slide_entry_18_2 (x : ℂ) : + insertionSlideLeft x .minus .zero .zero .zero .minus = insertionSlideRight x .minus .zero .zero .zero .minus := by + norm_num [insertionSlideLeft,insertionSlideRight,sum_spin,exchangeNumerator_eq_table,exchangeTable, + exchangeDenominator,insertion_eq_table,insertionTable,T,t] + all_goals vacuum_ring_finish + +theorem insertion_slide_entry_18_3 (x : ℂ) : + insertionSlideLeft x .minus .zero .zero .plus .zero = insertionSlideRight x .minus .zero .zero .plus .zero := by + norm_num [insertionSlideLeft,insertionSlideRight,sum_spin,exchangeNumerator_eq_table,exchangeTable, + exchangeDenominator,insertion_eq_table,insertionTable,T,t] + +theorem insertion_slide_entry_18_4 (x : ℂ) : + insertionSlideLeft x .minus .zero .zero .plus .plus = insertionSlideRight x .minus .zero .zero .plus .plus := by + norm_num [insertionSlideLeft,insertionSlideRight,sum_spin,exchangeNumerator_eq_table,exchangeTable, + exchangeDenominator,insertion_eq_table,insertionTable,T,t] + +theorem insertion_slide_entry_18_5 (x : ℂ) : + insertionSlideLeft x .minus .zero .zero .plus .minus = insertionSlideRight x .minus .zero .zero .plus .minus := by + norm_num [insertionSlideLeft,insertionSlideRight,sum_spin,exchangeNumerator_eq_table,exchangeTable, + exchangeDenominator,insertion_eq_table,insertionTable,T,t] + +theorem insertion_slide_entry_18_6 (x : ℂ) : + insertionSlideLeft x .minus .zero .zero .minus .zero = insertionSlideRight x .minus .zero .zero .minus .zero := by + norm_num [insertionSlideLeft,insertionSlideRight,sum_spin,exchangeNumerator_eq_table,exchangeTable, + exchangeDenominator,insertion_eq_table,insertionTable,T,t] + all_goals vacuum_ring_finish + +theorem insertion_slide_entry_18_7 (x : ℂ) : + insertionSlideLeft x .minus .zero .zero .minus .plus = insertionSlideRight x .minus .zero .zero .minus .plus := by + norm_num [insertionSlideLeft,insertionSlideRight,sum_spin,exchangeNumerator_eq_table,exchangeTable, + exchangeDenominator,insertion_eq_table,insertionTable,T,t] + +theorem insertion_slide_entry_18_8 (x : ℂ) : + insertionSlideLeft x .minus .zero .zero .minus .minus = insertionSlideRight x .minus .zero .zero .minus .minus := by + norm_num [insertionSlideLeft,insertionSlideRight,sum_spin,exchangeNumerator_eq_table,exchangeTable, + exchangeDenominator,insertion_eq_table,insertionTable,T,t] + +theorem insertion_slide_entry_19_0 (x : ℂ) : + insertionSlideLeft x .minus .zero .plus .zero .zero = insertionSlideRight x .minus .zero .plus .zero .zero := by + norm_num [insertionSlideLeft,insertionSlideRight,sum_spin,exchangeNumerator_eq_table,exchangeTable, + exchangeDenominator,insertion_eq_table,insertionTable,T,t] + all_goals vacuum_ring_finish + +theorem insertion_slide_entry_19_1 (x : ℂ) : + insertionSlideLeft x .minus .zero .plus .zero .plus = insertionSlideRight x .minus .zero .plus .zero .plus := by + norm_num [insertionSlideLeft,insertionSlideRight,sum_spin,exchangeNumerator_eq_table,exchangeTable, + exchangeDenominator,insertion_eq_table,insertionTable,T,t] + +theorem insertion_slide_entry_19_2 (x : ℂ) : + insertionSlideLeft x .minus .zero .plus .zero .minus = insertionSlideRight x .minus .zero .plus .zero .minus := by + norm_num [insertionSlideLeft,insertionSlideRight,sum_spin,exchangeNumerator_eq_table,exchangeTable, + exchangeDenominator,insertion_eq_table,insertionTable,T,t] + +theorem insertion_slide_entry_19_3 (x : ℂ) : + insertionSlideLeft x .minus .zero .plus .plus .zero = insertionSlideRight x .minus .zero .plus .plus .zero := by + norm_num [insertionSlideLeft,insertionSlideRight,sum_spin,exchangeNumerator_eq_table,exchangeTable, + exchangeDenominator,insertion_eq_table,insertionTable,T,t] + +theorem insertion_slide_entry_19_4 (x : ℂ) : + insertionSlideLeft x .minus .zero .plus .plus .plus = insertionSlideRight x .minus .zero .plus .plus .plus := by + norm_num [insertionSlideLeft,insertionSlideRight,sum_spin,exchangeNumerator_eq_table,exchangeTable, + exchangeDenominator,insertion_eq_table,insertionTable,T,t] + +theorem insertion_slide_entry_19_5 (x : ℂ) : + insertionSlideLeft x .minus .zero .plus .plus .minus = insertionSlideRight x .minus .zero .plus .plus .minus := by + norm_num [insertionSlideLeft,insertionSlideRight,sum_spin,exchangeNumerator_eq_table,exchangeTable, + exchangeDenominator,insertion_eq_table,insertionTable,T,t] + all_goals vacuum_ring_finish + +theorem insertion_slide_entry_19_6 (x : ℂ) : + insertionSlideLeft x .minus .zero .plus .minus .zero = insertionSlideRight x .minus .zero .plus .minus .zero := by + norm_num [insertionSlideLeft,insertionSlideRight,sum_spin,exchangeNumerator_eq_table,exchangeTable, + exchangeDenominator,insertion_eq_table,insertionTable,T,t] + +theorem insertion_slide_entry_19_7 (x : ℂ) : + insertionSlideLeft x .minus .zero .plus .minus .plus = insertionSlideRight x .minus .zero .plus .minus .plus := by + norm_num [insertionSlideLeft,insertionSlideRight,sum_spin,exchangeNumerator_eq_table,exchangeTable, + exchangeDenominator,insertion_eq_table,insertionTable,T,t] + all_goals vacuum_ring_finish + +theorem insertion_slide_entry_19_8 (x : ℂ) : + insertionSlideLeft x .minus .zero .plus .minus .minus = insertionSlideRight x .minus .zero .plus .minus .minus := by + norm_num [insertionSlideLeft,insertionSlideRight,sum_spin,exchangeNumerator_eq_table,exchangeTable, + exchangeDenominator,insertion_eq_table,insertionTable,T,t] + +theorem insertion_slide_entry_20_0 (x : ℂ) : + insertionSlideLeft x .minus .zero .minus .zero .zero = insertionSlideRight x .minus .zero .minus .zero .zero := by + norm_num [insertionSlideLeft,insertionSlideRight,sum_spin,exchangeNumerator_eq_table,exchangeTable, + exchangeDenominator,insertion_eq_table,insertionTable,T,t] + +theorem insertion_slide_entry_20_1 (x : ℂ) : + insertionSlideLeft x .minus .zero .minus .zero .plus = insertionSlideRight x .minus .zero .minus .zero .plus := by + norm_num [insertionSlideLeft,insertionSlideRight,sum_spin,exchangeNumerator_eq_table,exchangeTable, + exchangeDenominator,insertion_eq_table,insertionTable,T,t] + +theorem insertion_slide_entry_20_2 (x : ℂ) : + insertionSlideLeft x .minus .zero .minus .zero .minus = insertionSlideRight x .minus .zero .minus .zero .minus := by + norm_num [insertionSlideLeft,insertionSlideRight,sum_spin,exchangeNumerator_eq_table,exchangeTable, + exchangeDenominator,insertion_eq_table,insertionTable,T,t] + +theorem insertion_slide_entry_20_3 (x : ℂ) : + insertionSlideLeft x .minus .zero .minus .plus .zero = insertionSlideRight x .minus .zero .minus .plus .zero := by + norm_num [insertionSlideLeft,insertionSlideRight,sum_spin,exchangeNumerator_eq_table,exchangeTable, + exchangeDenominator,insertion_eq_table,insertionTable,T,t] + +theorem insertion_slide_entry_20_4 (x : ℂ) : + insertionSlideLeft x .minus .zero .minus .plus .plus = insertionSlideRight x .minus .zero .minus .plus .plus := by + norm_num [insertionSlideLeft,insertionSlideRight,sum_spin,exchangeNumerator_eq_table,exchangeTable, + exchangeDenominator,insertion_eq_table,insertionTable,T,t] + +theorem insertion_slide_entry_20_5 (x : ℂ) : + insertionSlideLeft x .minus .zero .minus .plus .minus = insertionSlideRight x .minus .zero .minus .plus .minus := by + norm_num [insertionSlideLeft,insertionSlideRight,sum_spin,exchangeNumerator_eq_table,exchangeTable, + exchangeDenominator,insertion_eq_table,insertionTable,T,t] + +theorem insertion_slide_entry_20_6 (x : ℂ) : + insertionSlideLeft x .minus .zero .minus .minus .zero = insertionSlideRight x .minus .zero .minus .minus .zero := by + norm_num [insertionSlideLeft,insertionSlideRight,sum_spin,exchangeNumerator_eq_table,exchangeTable, + exchangeDenominator,insertion_eq_table,insertionTable,T,t] + +theorem insertion_slide_entry_20_7 (x : ℂ) : + insertionSlideLeft x .minus .zero .minus .minus .plus = insertionSlideRight x .minus .zero .minus .minus .plus := by + norm_num [insertionSlideLeft,insertionSlideRight,sum_spin,exchangeNumerator_eq_table,exchangeTable, + exchangeDenominator,insertion_eq_table,insertionTable,T,t] + +theorem insertion_slide_entry_20_8 (x : ℂ) : + insertionSlideLeft x .minus .zero .minus .minus .minus = insertionSlideRight x .minus .zero .minus .minus .minus := by + norm_num [insertionSlideLeft,insertionSlideRight,sum_spin,exchangeNumerator_eq_table,exchangeTable, + exchangeDenominator,insertion_eq_table,insertionTable,T,t] + all_goals vacuum_ring_finish + +theorem insertion_slide_entry_21_0 (x : ℂ) : + insertionSlideLeft x .minus .plus .zero .zero .zero = insertionSlideRight x .minus .plus .zero .zero .zero := by + norm_num [insertionSlideLeft,insertionSlideRight,sum_spin,exchangeNumerator_eq_table,exchangeTable, + exchangeDenominator,insertion_eq_table,insertionTable,T,t] + all_goals vacuum_ring_finish + +theorem insertion_slide_entry_21_1 (x : ℂ) : + insertionSlideLeft x .minus .plus .zero .zero .plus = insertionSlideRight x .minus .plus .zero .zero .plus := by + norm_num [insertionSlideLeft,insertionSlideRight,sum_spin,exchangeNumerator_eq_table,exchangeTable, + exchangeDenominator,insertion_eq_table,insertionTable,T,t] + +theorem insertion_slide_entry_21_2 (x : ℂ) : + insertionSlideLeft x .minus .plus .zero .zero .minus = insertionSlideRight x .minus .plus .zero .zero .minus := by + norm_num [insertionSlideLeft,insertionSlideRight,sum_spin,exchangeNumerator_eq_table,exchangeTable, + exchangeDenominator,insertion_eq_table,insertionTable,T,t] + +theorem insertion_slide_entry_21_3 (x : ℂ) : + insertionSlideLeft x .minus .plus .zero .plus .zero = insertionSlideRight x .minus .plus .zero .plus .zero := by + norm_num [insertionSlideLeft,insertionSlideRight,sum_spin,exchangeNumerator_eq_table,exchangeTable, + exchangeDenominator,insertion_eq_table,insertionTable,T,t] + +theorem insertion_slide_entry_21_4 (x : ℂ) : + insertionSlideLeft x .minus .plus .zero .plus .plus = insertionSlideRight x .minus .plus .zero .plus .plus := by + norm_num [insertionSlideLeft,insertionSlideRight,sum_spin,exchangeNumerator_eq_table,exchangeTable, + exchangeDenominator,insertion_eq_table,insertionTable,T,t] + +theorem insertion_slide_entry_21_5 (x : ℂ) : + insertionSlideLeft x .minus .plus .zero .plus .minus = insertionSlideRight x .minus .plus .zero .plus .minus := by + norm_num [insertionSlideLeft,insertionSlideRight,sum_spin,exchangeNumerator_eq_table,exchangeTable, + exchangeDenominator,insertion_eq_table,insertionTable,T,t] + all_goals vacuum_ring_finish + +theorem insertion_slide_entry_21_6 (x : ℂ) : + insertionSlideLeft x .minus .plus .zero .minus .zero = insertionSlideRight x .minus .plus .zero .minus .zero := by + norm_num [insertionSlideLeft,insertionSlideRight,sum_spin,exchangeNumerator_eq_table,exchangeTable, + exchangeDenominator,insertion_eq_table,insertionTable,T,t] + +theorem insertion_slide_entry_21_7 (x : ℂ) : + insertionSlideLeft x .minus .plus .zero .minus .plus = insertionSlideRight x .minus .plus .zero .minus .plus := by + norm_num [insertionSlideLeft,insertionSlideRight,sum_spin,exchangeNumerator_eq_table,exchangeTable, + exchangeDenominator,insertion_eq_table,insertionTable,T,t] + all_goals vacuum_ring_finish + +theorem insertion_slide_entry_21_8 (x : ℂ) : + insertionSlideLeft x .minus .plus .zero .minus .minus = insertionSlideRight x .minus .plus .zero .minus .minus := by + norm_num [insertionSlideLeft,insertionSlideRight,sum_spin,exchangeNumerator_eq_table,exchangeTable, + exchangeDenominator,insertion_eq_table,insertionTable,T,t] + +theorem insertion_slide_entry_22_0 (x : ℂ) : + insertionSlideLeft x .minus .plus .plus .zero .zero = insertionSlideRight x .minus .plus .plus .zero .zero := by + norm_num [insertionSlideLeft,insertionSlideRight,sum_spin,exchangeNumerator_eq_table,exchangeTable, + exchangeDenominator,insertion_eq_table,insertionTable,T,t] + +theorem insertion_slide_entry_22_1 (x : ℂ) : + insertionSlideLeft x .minus .plus .plus .zero .plus = insertionSlideRight x .minus .plus .plus .zero .plus := by + norm_num [insertionSlideLeft,insertionSlideRight,sum_spin,exchangeNumerator_eq_table,exchangeTable, + exchangeDenominator,insertion_eq_table,insertionTable,T,t] + all_goals vacuum_ring_finish + +theorem insertion_slide_entry_22_2 (x : ℂ) : + insertionSlideLeft x .minus .plus .plus .zero .minus = insertionSlideRight x .minus .plus .plus .zero .minus := by + norm_num [insertionSlideLeft,insertionSlideRight,sum_spin,exchangeNumerator_eq_table,exchangeTable, + exchangeDenominator,insertion_eq_table,insertionTable,T,t] + +theorem insertion_slide_entry_22_3 (x : ℂ) : + insertionSlideLeft x .minus .plus .plus .plus .zero = insertionSlideRight x .minus .plus .plus .plus .zero := by + norm_num [insertionSlideLeft,insertionSlideRight,sum_spin,exchangeNumerator_eq_table,exchangeTable, + exchangeDenominator,insertion_eq_table,insertionTable,T,t] + all_goals vacuum_ring_finish + +theorem insertion_slide_entry_22_4 (x : ℂ) : + insertionSlideLeft x .minus .plus .plus .plus .plus = insertionSlideRight x .minus .plus .plus .plus .plus := by + norm_num [insertionSlideLeft,insertionSlideRight,sum_spin,exchangeNumerator_eq_table,exchangeTable, + exchangeDenominator,insertion_eq_table,insertionTable,T,t] + +theorem insertion_slide_entry_22_5 (x : ℂ) : + insertionSlideLeft x .minus .plus .plus .plus .minus = insertionSlideRight x .minus .plus .plus .plus .minus := by + norm_num [insertionSlideLeft,insertionSlideRight,sum_spin,exchangeNumerator_eq_table,exchangeTable, + exchangeDenominator,insertion_eq_table,insertionTable,T,t] + +theorem insertion_slide_entry_22_6 (x : ℂ) : + insertionSlideLeft x .minus .plus .plus .minus .zero = insertionSlideRight x .minus .plus .plus .minus .zero := by + norm_num [insertionSlideLeft,insertionSlideRight,sum_spin,exchangeNumerator_eq_table,exchangeTable, + exchangeDenominator,insertion_eq_table,insertionTable,T,t] + +theorem insertion_slide_entry_22_7 (x : ℂ) : + insertionSlideLeft x .minus .plus .plus .minus .plus = insertionSlideRight x .minus .plus .plus .minus .plus := by + norm_num [insertionSlideLeft,insertionSlideRight,sum_spin,exchangeNumerator_eq_table,exchangeTable, + exchangeDenominator,insertion_eq_table,insertionTable,T,t] + +theorem insertion_slide_entry_22_8 (x : ℂ) : + insertionSlideLeft x .minus .plus .plus .minus .minus = insertionSlideRight x .minus .plus .plus .minus .minus := by + norm_num [insertionSlideLeft,insertionSlideRight,sum_spin,exchangeNumerator_eq_table,exchangeTable, + exchangeDenominator,insertion_eq_table,insertionTable,T,t] + +theorem insertion_slide_entry_23_0 (x : ℂ) : + insertionSlideLeft x .minus .plus .minus .zero .zero = insertionSlideRight x .minus .plus .minus .zero .zero := by + norm_num [insertionSlideLeft,insertionSlideRight,sum_spin,exchangeNumerator_eq_table,exchangeTable, + exchangeDenominator,insertion_eq_table,insertionTable,T,t] + +theorem insertion_slide_entry_23_1 (x : ℂ) : + insertionSlideLeft x .minus .plus .minus .zero .plus = insertionSlideRight x .minus .plus .minus .zero .plus := by + norm_num [insertionSlideLeft,insertionSlideRight,sum_spin,exchangeNumerator_eq_table,exchangeTable, + exchangeDenominator,insertion_eq_table,insertionTable,T,t] + +theorem insertion_slide_entry_23_2 (x : ℂ) : + insertionSlideLeft x .minus .plus .minus .zero .minus = insertionSlideRight x .minus .plus .minus .zero .minus := by + norm_num [insertionSlideLeft,insertionSlideRight,sum_spin,exchangeNumerator_eq_table,exchangeTable, + exchangeDenominator,insertion_eq_table,insertionTable,T,t] + all_goals vacuum_ring_finish + +theorem insertion_slide_entry_23_3 (x : ℂ) : + insertionSlideLeft x .minus .plus .minus .plus .zero = insertionSlideRight x .minus .plus .minus .plus .zero := by + norm_num [insertionSlideLeft,insertionSlideRight,sum_spin,exchangeNumerator_eq_table,exchangeTable, + exchangeDenominator,insertion_eq_table,insertionTable,T,t] + +theorem insertion_slide_entry_23_4 (x : ℂ) : + insertionSlideLeft x .minus .plus .minus .plus .plus = insertionSlideRight x .minus .plus .minus .plus .plus := by + norm_num [insertionSlideLeft,insertionSlideRight,sum_spin,exchangeNumerator_eq_table,exchangeTable, + exchangeDenominator,insertion_eq_table,insertionTable,T,t] + +theorem insertion_slide_entry_23_5 (x : ℂ) : + insertionSlideLeft x .minus .plus .minus .plus .minus = insertionSlideRight x .minus .plus .minus .plus .minus := by + norm_num [insertionSlideLeft,insertionSlideRight,sum_spin,exchangeNumerator_eq_table,exchangeTable, + exchangeDenominator,insertion_eq_table,insertionTable,T,t] + +theorem insertion_slide_entry_23_6 (x : ℂ) : + insertionSlideLeft x .minus .plus .minus .minus .zero = insertionSlideRight x .minus .plus .minus .minus .zero := by + norm_num [insertionSlideLeft,insertionSlideRight,sum_spin,exchangeNumerator_eq_table,exchangeTable, + exchangeDenominator,insertion_eq_table,insertionTable,T,t] + all_goals vacuum_ring_finish + +theorem insertion_slide_entry_23_7 (x : ℂ) : + insertionSlideLeft x .minus .plus .minus .minus .plus = insertionSlideRight x .minus .plus .minus .minus .plus := by + norm_num [insertionSlideLeft,insertionSlideRight,sum_spin,exchangeNumerator_eq_table,exchangeTable, + exchangeDenominator,insertion_eq_table,insertionTable,T,t] + +theorem insertion_slide_entry_23_8 (x : ℂ) : + insertionSlideLeft x .minus .plus .minus .minus .minus = insertionSlideRight x .minus .plus .minus .minus .minus := by + norm_num [insertionSlideLeft,insertionSlideRight,sum_spin,exchangeNumerator_eq_table,exchangeTable, + exchangeDenominator,insertion_eq_table,insertionTable,T,t] + +theorem insertion_slide_entry_24_0 (x : ℂ) : + insertionSlideLeft x .minus .minus .zero .zero .zero = insertionSlideRight x .minus .minus .zero .zero .zero := by + norm_num [insertionSlideLeft,insertionSlideRight,sum_spin,exchangeNumerator_eq_table,exchangeTable, + exchangeDenominator,insertion_eq_table,insertionTable,T,t] + +theorem insertion_slide_entry_24_1 (x : ℂ) : + insertionSlideLeft x .minus .minus .zero .zero .plus = insertionSlideRight x .minus .minus .zero .zero .plus := by + norm_num [insertionSlideLeft,insertionSlideRight,sum_spin,exchangeNumerator_eq_table,exchangeTable, + exchangeDenominator,insertion_eq_table,insertionTable,T,t] + +theorem insertion_slide_entry_24_2 (x : ℂ) : + insertionSlideLeft x .minus .minus .zero .zero .minus = insertionSlideRight x .minus .minus .zero .zero .minus := by + norm_num [insertionSlideLeft,insertionSlideRight,sum_spin,exchangeNumerator_eq_table,exchangeTable, + exchangeDenominator,insertion_eq_table,insertionTable,T,t] + +theorem insertion_slide_entry_24_3 (x : ℂ) : + insertionSlideLeft x .minus .minus .zero .plus .zero = insertionSlideRight x .minus .minus .zero .plus .zero := by + norm_num [insertionSlideLeft,insertionSlideRight,sum_spin,exchangeNumerator_eq_table,exchangeTable, + exchangeDenominator,insertion_eq_table,insertionTable,T,t] + +theorem insertion_slide_entry_24_4 (x : ℂ) : + insertionSlideLeft x .minus .minus .zero .plus .plus = insertionSlideRight x .minus .minus .zero .plus .plus := by + norm_num [insertionSlideLeft,insertionSlideRight,sum_spin,exchangeNumerator_eq_table,exchangeTable, + exchangeDenominator,insertion_eq_table,insertionTable,T,t] + +theorem insertion_slide_entry_24_5 (x : ℂ) : + insertionSlideLeft x .minus .minus .zero .plus .minus = insertionSlideRight x .minus .minus .zero .plus .minus := by + norm_num [insertionSlideLeft,insertionSlideRight,sum_spin,exchangeNumerator_eq_table,exchangeTable, + exchangeDenominator,insertion_eq_table,insertionTable,T,t] + +theorem insertion_slide_entry_24_6 (x : ℂ) : + insertionSlideLeft x .minus .minus .zero .minus .zero = insertionSlideRight x .minus .minus .zero .minus .zero := by + norm_num [insertionSlideLeft,insertionSlideRight,sum_spin,exchangeNumerator_eq_table,exchangeTable, + exchangeDenominator,insertion_eq_table,insertionTable,T,t] + +theorem insertion_slide_entry_24_7 (x : ℂ) : + insertionSlideLeft x .minus .minus .zero .minus .plus = insertionSlideRight x .minus .minus .zero .minus .plus := by + norm_num [insertionSlideLeft,insertionSlideRight,sum_spin,exchangeNumerator_eq_table,exchangeTable, + exchangeDenominator,insertion_eq_table,insertionTable,T,t] + +theorem insertion_slide_entry_24_8 (x : ℂ) : + insertionSlideLeft x .minus .minus .zero .minus .minus = insertionSlideRight x .minus .minus .zero .minus .minus := by + norm_num [insertionSlideLeft,insertionSlideRight,sum_spin,exchangeNumerator_eq_table,exchangeTable, + exchangeDenominator,insertion_eq_table,insertionTable,T,t] + all_goals vacuum_ring_finish + +theorem insertion_slide_entry_25_0 (x : ℂ) : + insertionSlideLeft x .minus .minus .plus .zero .zero = insertionSlideRight x .minus .minus .plus .zero .zero := by + norm_num [insertionSlideLeft,insertionSlideRight,sum_spin,exchangeNumerator_eq_table,exchangeTable, + exchangeDenominator,insertion_eq_table,insertionTable,T,t] + +theorem insertion_slide_entry_25_1 (x : ℂ) : + insertionSlideLeft x .minus .minus .plus .zero .plus = insertionSlideRight x .minus .minus .plus .zero .plus := by + norm_num [insertionSlideLeft,insertionSlideRight,sum_spin,exchangeNumerator_eq_table,exchangeTable, + exchangeDenominator,insertion_eq_table,insertionTable,T,t] + +theorem insertion_slide_entry_25_2 (x : ℂ) : + insertionSlideLeft x .minus .minus .plus .zero .minus = insertionSlideRight x .minus .minus .plus .zero .minus := by + norm_num [insertionSlideLeft,insertionSlideRight,sum_spin,exchangeNumerator_eq_table,exchangeTable, + exchangeDenominator,insertion_eq_table,insertionTable,T,t] + all_goals vacuum_ring_finish + +theorem insertion_slide_entry_25_3 (x : ℂ) : + insertionSlideLeft x .minus .minus .plus .plus .zero = insertionSlideRight x .minus .minus .plus .plus .zero := by + norm_num [insertionSlideLeft,insertionSlideRight,sum_spin,exchangeNumerator_eq_table,exchangeTable, + exchangeDenominator,insertion_eq_table,insertionTable,T,t] + +theorem insertion_slide_entry_25_4 (x : ℂ) : + insertionSlideLeft x .minus .minus .plus .plus .plus = insertionSlideRight x .minus .minus .plus .plus .plus := by + norm_num [insertionSlideLeft,insertionSlideRight,sum_spin,exchangeNumerator_eq_table,exchangeTable, + exchangeDenominator,insertion_eq_table,insertionTable,T,t] + +theorem insertion_slide_entry_25_5 (x : ℂ) : + insertionSlideLeft x .minus .minus .plus .plus .minus = insertionSlideRight x .minus .minus .plus .plus .minus := by + norm_num [insertionSlideLeft,insertionSlideRight,sum_spin,exchangeNumerator_eq_table,exchangeTable, + exchangeDenominator,insertion_eq_table,insertionTable,T,t] + +theorem insertion_slide_entry_25_6 (x : ℂ) : + insertionSlideLeft x .minus .minus .plus .minus .zero = insertionSlideRight x .minus .minus .plus .minus .zero := by + norm_num [insertionSlideLeft,insertionSlideRight,sum_spin,exchangeNumerator_eq_table,exchangeTable, + exchangeDenominator,insertion_eq_table,insertionTable,T,t] + all_goals vacuum_ring_finish + +theorem insertion_slide_entry_25_7 (x : ℂ) : + insertionSlideLeft x .minus .minus .plus .minus .plus = insertionSlideRight x .minus .minus .plus .minus .plus := by + norm_num [insertionSlideLeft,insertionSlideRight,sum_spin,exchangeNumerator_eq_table,exchangeTable, + exchangeDenominator,insertion_eq_table,insertionTable,T,t] + +theorem insertion_slide_entry_25_8 (x : ℂ) : + insertionSlideLeft x .minus .minus .plus .minus .minus = insertionSlideRight x .minus .minus .plus .minus .minus := by + norm_num [insertionSlideLeft,insertionSlideRight,sum_spin,exchangeNumerator_eq_table,exchangeTable, + exchangeDenominator,insertion_eq_table,insertionTable,T,t] + +theorem insertion_slide_entry_26_0 (x : ℂ) : + insertionSlideLeft x .minus .minus .minus .zero .zero = insertionSlideRight x .minus .minus .minus .zero .zero := by + norm_num [insertionSlideLeft,insertionSlideRight,sum_spin,exchangeNumerator_eq_table,exchangeTable, + exchangeDenominator,insertion_eq_table,insertionTable,T,t] + +theorem insertion_slide_entry_26_1 (x : ℂ) : + insertionSlideLeft x .minus .minus .minus .zero .plus = insertionSlideRight x .minus .minus .minus .zero .plus := by + norm_num [insertionSlideLeft,insertionSlideRight,sum_spin,exchangeNumerator_eq_table,exchangeTable, + exchangeDenominator,insertion_eq_table,insertionTable,T,t] + +theorem insertion_slide_entry_26_2 (x : ℂ) : + insertionSlideLeft x .minus .minus .minus .zero .minus = insertionSlideRight x .minus .minus .minus .zero .minus := by + norm_num [insertionSlideLeft,insertionSlideRight,sum_spin,exchangeNumerator_eq_table,exchangeTable, + exchangeDenominator,insertion_eq_table,insertionTable,T,t] + +theorem insertion_slide_entry_26_3 (x : ℂ) : + insertionSlideLeft x .minus .minus .minus .plus .zero = insertionSlideRight x .minus .minus .minus .plus .zero := by + norm_num [insertionSlideLeft,insertionSlideRight,sum_spin,exchangeNumerator_eq_table,exchangeTable, + exchangeDenominator,insertion_eq_table,insertionTable,T,t] + +theorem insertion_slide_entry_26_4 (x : ℂ) : + insertionSlideLeft x .minus .minus .minus .plus .plus = insertionSlideRight x .minus .minus .minus .plus .plus := by + norm_num [insertionSlideLeft,insertionSlideRight,sum_spin,exchangeNumerator_eq_table,exchangeTable, + exchangeDenominator,insertion_eq_table,insertionTable,T,t] + +theorem insertion_slide_entry_26_5 (x : ℂ) : + insertionSlideLeft x .minus .minus .minus .plus .minus = insertionSlideRight x .minus .minus .minus .plus .minus := by + norm_num [insertionSlideLeft,insertionSlideRight,sum_spin,exchangeNumerator_eq_table,exchangeTable, + exchangeDenominator,insertion_eq_table,insertionTable,T,t] + +theorem insertion_slide_entry_26_6 (x : ℂ) : + insertionSlideLeft x .minus .minus .minus .minus .zero = insertionSlideRight x .minus .minus .minus .minus .zero := by + norm_num [insertionSlideLeft,insertionSlideRight,sum_spin,exchangeNumerator_eq_table,exchangeTable, + exchangeDenominator,insertion_eq_table,insertionTable,T,t] + +theorem insertion_slide_entry_26_7 (x : ℂ) : + insertionSlideLeft x .minus .minus .minus .minus .plus = insertionSlideRight x .minus .minus .minus .minus .plus := by + norm_num [insertionSlideLeft,insertionSlideRight,sum_spin,exchangeNumerator_eq_table,exchangeTable, + exchangeDenominator,insertion_eq_table,insertionTable,T,t] + +theorem insertion_slide_entry_26_8 (x : ℂ) : + insertionSlideLeft x .minus .minus .minus .minus .minus = insertionSlideRight x .minus .minus .minus .minus .minus := by + norm_num [insertionSlideLeft,insertionSlideRight,sum_spin,exchangeNumerator_eq_table,exchangeTable, + exchangeDenominator,insertion_eq_table,insertionTable,T,t] + +theorem insertion_slide_coefficients (x : ℂ) (a b c h k : Spin) : + insertionSlideLeft x a b c h k = insertionSlideRight x a b c h k := by + cases a <;> cases b <;> cases c <;> cases h <;> cases k + · exact insertion_slide_entry_0_0 x + · exact insertion_slide_entry_0_1 x + · exact insertion_slide_entry_0_2 x + · exact insertion_slide_entry_0_3 x + · exact insertion_slide_entry_0_4 x + · exact insertion_slide_entry_0_5 x + · exact insertion_slide_entry_0_6 x + · exact insertion_slide_entry_0_7 x + · exact insertion_slide_entry_0_8 x + · exact insertion_slide_entry_1_0 x + · exact insertion_slide_entry_1_1 x + · exact insertion_slide_entry_1_2 x + · exact insertion_slide_entry_1_3 x + · exact insertion_slide_entry_1_4 x + · exact insertion_slide_entry_1_5 x + · exact insertion_slide_entry_1_6 x + · exact insertion_slide_entry_1_7 x + · exact insertion_slide_entry_1_8 x + · exact insertion_slide_entry_2_0 x + · exact insertion_slide_entry_2_1 x + · exact insertion_slide_entry_2_2 x + · exact insertion_slide_entry_2_3 x + · exact insertion_slide_entry_2_4 x + · exact insertion_slide_entry_2_5 x + · exact insertion_slide_entry_2_6 x + · exact insertion_slide_entry_2_7 x + · exact insertion_slide_entry_2_8 x + · exact insertion_slide_entry_3_0 x + · exact insertion_slide_entry_3_1 x + · exact insertion_slide_entry_3_2 x + · exact insertion_slide_entry_3_3 x + · exact insertion_slide_entry_3_4 x + · exact insertion_slide_entry_3_5 x + · exact insertion_slide_entry_3_6 x + · exact insertion_slide_entry_3_7 x + · exact insertion_slide_entry_3_8 x + · exact insertion_slide_entry_4_0 x + · exact insertion_slide_entry_4_1 x + · exact insertion_slide_entry_4_2 x + · exact insertion_slide_entry_4_3 x + · exact insertion_slide_entry_4_4 x + · exact insertion_slide_entry_4_5 x + · exact insertion_slide_entry_4_6 x + · exact insertion_slide_entry_4_7 x + · exact insertion_slide_entry_4_8 x + · exact insertion_slide_entry_5_0 x + · exact insertion_slide_entry_5_1 x + · exact insertion_slide_entry_5_2 x + · exact insertion_slide_entry_5_3 x + · exact insertion_slide_entry_5_4 x + · exact insertion_slide_entry_5_5 x + · exact insertion_slide_entry_5_6 x + · exact insertion_slide_entry_5_7 x + · exact insertion_slide_entry_5_8 x + · exact insertion_slide_entry_6_0 x + · exact insertion_slide_entry_6_1 x + · exact insertion_slide_entry_6_2 x + · exact insertion_slide_entry_6_3 x + · exact insertion_slide_entry_6_4 x + · exact insertion_slide_entry_6_5 x + · exact insertion_slide_entry_6_6 x + · exact insertion_slide_entry_6_7 x + · exact insertion_slide_entry_6_8 x + · exact insertion_slide_entry_7_0 x + · exact insertion_slide_entry_7_1 x + · exact insertion_slide_entry_7_2 x + · exact insertion_slide_entry_7_3 x + · exact insertion_slide_entry_7_4 x + · exact insertion_slide_entry_7_5 x + · exact insertion_slide_entry_7_6 x + · exact insertion_slide_entry_7_7 x + · exact insertion_slide_entry_7_8 x + · exact insertion_slide_entry_8_0 x + · exact insertion_slide_entry_8_1 x + · exact insertion_slide_entry_8_2 x + · exact insertion_slide_entry_8_3 x + · exact insertion_slide_entry_8_4 x + · exact insertion_slide_entry_8_5 x + · exact insertion_slide_entry_8_6 x + · exact insertion_slide_entry_8_7 x + · exact insertion_slide_entry_8_8 x + · exact insertion_slide_entry_9_0 x + · exact insertion_slide_entry_9_1 x + · exact insertion_slide_entry_9_2 x + · exact insertion_slide_entry_9_3 x + · exact insertion_slide_entry_9_4 x + · exact insertion_slide_entry_9_5 x + · exact insertion_slide_entry_9_6 x + · exact insertion_slide_entry_9_7 x + · exact insertion_slide_entry_9_8 x + · exact insertion_slide_entry_10_0 x + · exact insertion_slide_entry_10_1 x + · exact insertion_slide_entry_10_2 x + · exact insertion_slide_entry_10_3 x + · exact insertion_slide_entry_10_4 x + · exact insertion_slide_entry_10_5 x + · exact insertion_slide_entry_10_6 x + · exact insertion_slide_entry_10_7 x + · exact insertion_slide_entry_10_8 x + · exact insertion_slide_entry_11_0 x + · exact insertion_slide_entry_11_1 x + · exact insertion_slide_entry_11_2 x + · exact insertion_slide_entry_11_3 x + · exact insertion_slide_entry_11_4 x + · exact insertion_slide_entry_11_5 x + · exact insertion_slide_entry_11_6 x + · exact insertion_slide_entry_11_7 x + · exact insertion_slide_entry_11_8 x + · exact insertion_slide_entry_12_0 x + · exact insertion_slide_entry_12_1 x + · exact insertion_slide_entry_12_2 x + · exact insertion_slide_entry_12_3 x + · exact insertion_slide_entry_12_4 x + · exact insertion_slide_entry_12_5 x + · exact insertion_slide_entry_12_6 x + · exact insertion_slide_entry_12_7 x + · exact insertion_slide_entry_12_8 x + · exact insertion_slide_entry_13_0 x + · exact insertion_slide_entry_13_1 x + · exact insertion_slide_entry_13_2 x + · exact insertion_slide_entry_13_3 x + · exact insertion_slide_entry_13_4 x + · exact insertion_slide_entry_13_5 x + · exact insertion_slide_entry_13_6 x + · exact insertion_slide_entry_13_7 x + · exact insertion_slide_entry_13_8 x + · exact insertion_slide_entry_14_0 x + · exact insertion_slide_entry_14_1 x + · exact insertion_slide_entry_14_2 x + · exact insertion_slide_entry_14_3 x + · exact insertion_slide_entry_14_4 x + · exact insertion_slide_entry_14_5 x + · exact insertion_slide_entry_14_6 x + · exact insertion_slide_entry_14_7 x + · exact insertion_slide_entry_14_8 x + · exact insertion_slide_entry_15_0 x + · exact insertion_slide_entry_15_1 x + · exact insertion_slide_entry_15_2 x + · exact insertion_slide_entry_15_3 x + · exact insertion_slide_entry_15_4 x + · exact insertion_slide_entry_15_5 x + · exact insertion_slide_entry_15_6 x + · exact insertion_slide_entry_15_7 x + · exact insertion_slide_entry_15_8 x + · exact insertion_slide_entry_16_0 x + · exact insertion_slide_entry_16_1 x + · exact insertion_slide_entry_16_2 x + · exact insertion_slide_entry_16_3 x + · exact insertion_slide_entry_16_4 x + · exact insertion_slide_entry_16_5 x + · exact insertion_slide_entry_16_6 x + · exact insertion_slide_entry_16_7 x + · exact insertion_slide_entry_16_8 x + · exact insertion_slide_entry_17_0 x + · exact insertion_slide_entry_17_1 x + · exact insertion_slide_entry_17_2 x + · exact insertion_slide_entry_17_3 x + · exact insertion_slide_entry_17_4 x + · exact insertion_slide_entry_17_5 x + · exact insertion_slide_entry_17_6 x + · exact insertion_slide_entry_17_7 x + · exact insertion_slide_entry_17_8 x + · exact insertion_slide_entry_18_0 x + · exact insertion_slide_entry_18_1 x + · exact insertion_slide_entry_18_2 x + · exact insertion_slide_entry_18_3 x + · exact insertion_slide_entry_18_4 x + · exact insertion_slide_entry_18_5 x + · exact insertion_slide_entry_18_6 x + · exact insertion_slide_entry_18_7 x + · exact insertion_slide_entry_18_8 x + · exact insertion_slide_entry_19_0 x + · exact insertion_slide_entry_19_1 x + · exact insertion_slide_entry_19_2 x + · exact insertion_slide_entry_19_3 x + · exact insertion_slide_entry_19_4 x + · exact insertion_slide_entry_19_5 x + · exact insertion_slide_entry_19_6 x + · exact insertion_slide_entry_19_7 x + · exact insertion_slide_entry_19_8 x + · exact insertion_slide_entry_20_0 x + · exact insertion_slide_entry_20_1 x + · exact insertion_slide_entry_20_2 x + · exact insertion_slide_entry_20_3 x + · exact insertion_slide_entry_20_4 x + · exact insertion_slide_entry_20_5 x + · exact insertion_slide_entry_20_6 x + · exact insertion_slide_entry_20_7 x + · exact insertion_slide_entry_20_8 x + · exact insertion_slide_entry_21_0 x + · exact insertion_slide_entry_21_1 x + · exact insertion_slide_entry_21_2 x + · exact insertion_slide_entry_21_3 x + · exact insertion_slide_entry_21_4 x + · exact insertion_slide_entry_21_5 x + · exact insertion_slide_entry_21_6 x + · exact insertion_slide_entry_21_7 x + · exact insertion_slide_entry_21_8 x + · exact insertion_slide_entry_22_0 x + · exact insertion_slide_entry_22_1 x + · exact insertion_slide_entry_22_2 x + · exact insertion_slide_entry_22_3 x + · exact insertion_slide_entry_22_4 x + · exact insertion_slide_entry_22_5 x + · exact insertion_slide_entry_22_6 x + · exact insertion_slide_entry_22_7 x + · exact insertion_slide_entry_22_8 x + · exact insertion_slide_entry_23_0 x + · exact insertion_slide_entry_23_1 x + · exact insertion_slide_entry_23_2 x + · exact insertion_slide_entry_23_3 x + · exact insertion_slide_entry_23_4 x + · exact insertion_slide_entry_23_5 x + · exact insertion_slide_entry_23_6 x + · exact insertion_slide_entry_23_7 x + · exact insertion_slide_entry_23_8 x + · exact insertion_slide_entry_24_0 x + · exact insertion_slide_entry_24_1 x + · exact insertion_slide_entry_24_2 x + · exact insertion_slide_entry_24_3 x + · exact insertion_slide_entry_24_4 x + · exact insertion_slide_entry_24_5 x + · exact insertion_slide_entry_24_6 x + · exact insertion_slide_entry_24_7 x + · exact insertion_slide_entry_24_8 x + · exact insertion_slide_entry_25_0 x + · exact insertion_slide_entry_25_1 x + · exact insertion_slide_entry_25_2 x + · exact insertion_slide_entry_25_3 x + · exact insertion_slide_entry_25_4 x + · exact insertion_slide_entry_25_5 x + · exact insertion_slide_entry_25_6 x + · exact insertion_slide_entry_25_7 x + · exact insertion_slide_entry_25_8 x + · exact insertion_slide_entry_26_0 x + · exact insertion_slide_entry_26_1 x + · exact insertion_slide_entry_26_2 x + · exact insertion_slide_entry_26_3 x + · exact insertion_slide_entry_26_4 x + · exact insertion_slide_entry_26_5 x + · exact insertion_slide_entry_26_6 x + · exact insertion_slide_entry_26_7 x + · exact insertion_slide_entry_26_8 x + +end PolynomialVacuumAlgebra + +end OAI diff --git a/lean/OAI/Combinatorics/PolynomialVacuum/Algebra/InterpolatedCups.lean b/lean/OAI/Combinatorics/PolynomialVacuum/Algebra/InterpolatedCups.lean new file mode 100644 index 0000000000000000000000000000000000000000..a3cbd3be3e2fad8e5009b612c268e8455a17c027 --- /dev/null +++ b/lean/OAI/Combinatorics/PolynomialVacuum/Algebra/InterpolatedCups.lean @@ -0,0 +1,58 @@ +import OAI.Combinatorics.PolynomialVacuum.Algebra.CupSlidePolynomial +import OAI.Combinatorics.PolynomialVacuum.Algebra.LastDegrees + +namespace OAI + +namespace PolynomialVacuumAlgebra +open Classical + + + +theorem interpolateState_firstCup {n : ℕ} (ψ : State (n+2)) (χ : State (n+3)) + (φ δ : NatSpectralTensor) + (hex : LowerExchange (liftState ψ) (n+2)) + (hnode : NaturalCupNodes (liftState ψ) φ n) + (hcψ : FirstCupReduction (liftState ψ) φ n) + (hzψ : LastZeroReduction (liftState ψ) δ (n+1)) + (hcχ : FirstCupReduction (liftState χ) δ (n+1)) + (hdψ : ∀ s, (ψ s).degreeOf (Fin.last (n+1)) ≤ n+1) + (hfψ : ∀ s, s (Fin.last (n+1))=Spin.plus → (ψ s).degreeOf (Fin.last (n+1)) ≤ n) : + FirstCupReduction (liftState (interpolateState ψ χ)) (liftState ψ) (n+2) := by + apply firstCup_of_nodes + · intro s + exact (interpolateState_last_degrees ψ χ s).1 + · intro s + exact (interpolateState_last_degrees ψ χ s).2 + · exact hdψ + · exact hfψ + · exact firstCup_node_equality _ ψ φ (lift_interpolate_cupNodes ψ χ hex) hnode hex hcψ + · exact firstCup_zeroNode (interpolateState_lastZero ψ χ) hzψ hcχ + +theorem naturalPrescription_last_cup {n : ℕ} (ψ : State n) (X : ℕ → ℂ) : + naturalPrescription (liftState ψ) n n X= + naturalFusion n n X • cupLinear n (liftState ψ (skipTwo n X)) := by + have hp : liftState ψ (skipOne n X)=liftState ψ (skipTwo n X) := by + apply liftState_params_congr + intro j hj + simp [skipOne,skipTwo,hj] + have hf : leftFusion n X=fusionProduct (X n) (skipTwo n X) n := by + apply Finset.prod_congr rfl + intro j hj + simp [skipTwo,Finset.mem_range.mp hj] + simp only [naturalPrescription,Nat.sub_self,braidTrain,one_mul,hp,naturalFusion,hf] + +theorem interpolateState_all_cups {n : ℕ} (ψ : State n) (χ : State (n+1)) + (hexψ : LowerExchange (liftState ψ) n) + (hexχ : LowerExchange (liftState χ) (n+1)) + (hc : FirstCupReduction (liftState (interpolateState ψ χ)) (liftState ψ) n) : + ∀ i, i≤n → CupAt (liftState (interpolateState ψ χ)) (liftState ψ) n i := by + intro i hi + rcases lt_or_eq_of_le hi with hi | he + · exact cupAt_of_first _ ψ (interpolateState_first_exchanges ψ χ hexψ hexχ) hc i hi + · subst i + intro X hX + rw [interpolateState_node_natural ψ χ hexψ n le_rfl X hX,naturalPrescription_last_cup] + +end PolynomialVacuumAlgebra + +end OAI diff --git a/lean/OAI/Combinatorics/PolynomialVacuum/Algebra/InterpolatedDegrees.lean b/lean/OAI/Combinatorics/PolynomialVacuum/Algebra/InterpolatedDegrees.lean new file mode 100644 index 0000000000000000000000000000000000000000..f28afa04a3b8131d5b24bfcee4404df1a86c7cac --- /dev/null +++ b/lean/OAI/Combinatorics/PolynomialVacuum/Algebra/InterpolatedDegrees.lean @@ -0,0 +1,91 @@ +import OAI.Combinatorics.PolynomialVacuum.Algebra.SpectatorDegree +import OAI.Combinatorics.PolynomialVacuum.Algebra.LagrangeDegree +import OAI.Combinatorics.PolynomialVacuum.Algebra.LastPolynomial + +namespace OAI + +namespace PolynomialVacuumAlgebra +open MvPolynomial Classical + +theorem zeroNodeProduct_spectator_degree {m : ℕ} (j : Fin m) : + (∏ i : Fin m, (X i.castSucc-C T⁻¹*X (Fin.last m)) : MvPolynomial (Fin (m+1)) ℂ).degreeOf j.castSucc ≤ 1 := by + apply (degreeOf_prod_le _ _ _).trans + calc + _ ≤ ∑ i : Fin m, if i=j then 1 else 0 := by + apply Finset.sum_le_sum + intro i hi + have hz : (-(C T⁻¹*X (Fin.last m)) : MvPolynomial (Fin (m+1)) ℂ).degreeOf j.castSucc≤0 := by + rw [degreeOf_neg] + exact dconst_mul _ (le_of_eq (degreeOf_X_of_ne (Fin.castSucc_ne_last j))) + rw [sub_eq_add_neg] + by_cases h : i=j + · subst i; simp only [ite_true]; exact dadd (by simp) (hz.trans (by omega)) + · simp only [ite_eq_right h] + exact dadd (le_of_eq (degreeOf_X_of_ne (by + intro he; exact h (Fin.castSucc_injective _ he.symm)))) hz + _ = 1 := by simp + + + +theorem interpolateState_spectator_degrees {n : ℕ} (hn : 2≤n) + (ψ : State n) (χ : State (n+1)) (hψ : LowerExchange (liftState ψ) n) + (hd : ∀ s l, (ψ s).degreeOf l≤n-1) + (hf : ∀ s l, s l=Spin.plus → (ψ s).degreeOf l≤n-2) + (hχd : ∀ s l, (χ s).degreeOf l≤n) + (hχf : ∀ s l, s l=Spin.plus → (χ s).degreeOf l≤n-1) + (s : Fin (n+2) → Spin) (j : Fin (n+1)) : + (interpolateState ψ χ s).degreeOf j.castSucc≤n+1 ∧ + (s j.castSucc=Spin.plus → (interpolateState ψ χ s).degreeOf j.castSucc≤n) := by + have hlo : ∀ s l, (ψ s).degreeOf l≤(n-2)+1 := by + intro s l; have:=hd s l; omega + have hc (i) (hi : i≠j) := cupPrescription_spectator_degrees ψ hlo hf i j (Ne.symm hi) s + have hm := cupPrescription_marked_degrees ψ j s + have hzm : (C T⁻¹*X (Fin.last (n+1)) : MvPolynomial (Fin (n+2)) ℂ).degreeOf j.castSucc≤0 := + dconst_mul _ (le_of_eq (degreeOf_X_of_ne (Fin.castSucc_ne_last j))) + have hχ (d : ℕ) (h : (χ (s ∘ Fin.castSucc)).degreeOf j≤d) : + ((∏ i : Fin (n+1), (X i.castSucc-C T⁻¹*X (Fin.last (n+1))))* + rename Fin.castSucc (χ (s ∘ Fin.castSucc))).degreeOf j.castSucc≤d+1 := by + have hh : (rename Fin.castSucc (χ (s ∘ Fin.castSucc))).degreeOf j.castSucc≤d := by + rw [degreeOf_rename_of_injective (Fin.castSucc_injective _)]; exact h + exact (dmul (zeroNodeProduct_spectator_degree j) hh).trans (by omega) + unfold interpolateState + dsimp only + split_ifs with hs hs0 + · have hcan (d : ℕ) (hmark : (cupPrescription ψ j s).degreeOf j≤d+n) + (ho : ∀ i, i≠j → (cupPrescription ψ i s).degreeOf j≤d) := + canonicalInterpolant_spectator_degree _ (cupPrescription_collision ψ hψ s) j d hmark ho + constructor + · exact hcan (n+1) (hm.1.trans (by omega)) (by + intro i hi; exact (hc i hi).1.trans (by omega)) + · intro hj + apply hcan n + · exact (hm.2 hj (by simp [hs,charge])).trans (by omega) + · intro i hi; exact ((hc i hi).2 hj).trans (by omega) + · have hcan (d : ℕ) (hmark : (dividedCupPrescription ψ j s).degreeOf j≤d+n) + (ho : ∀ i, i≠j → (cupPrescription ψ i s).degreeOf j≤d) := + canonicalInterpolant_spectator_degree _ (dividedCupPrescription_collision ψ hψ s) j d hmark + (fun i hi => by rw [dividedCupPrescription_spectator_degree_eq ψ i j (Ne.symm hi)]; exact ho i hi) + constructor + · apply dadd + · exact (dmul hzm (hcan (n+1) ((dividedCupPrescription_marked_degree ψ j s).trans (by omega)) + (by intro i hi; exact (hc i hi).1.trans (by omega)))).trans (by omega) + · exact hχ n (hχd _ _) + · intro hj + apply dadd + · exact (dmul hzm (hcan n ((dividedCupPrescription_marked_degree ψ j s).trans (by omega)) + (by intro i hi; exact ((hc i hi).2 hj).trans (by omega)))).trans (by omega) + · exact (hχ (n-1) (hχf _ _ hj)).trans (by omega) + · simp only [add_zero] + have hcan (d : ℕ) (hdn : 2*n≤d+n) + (ho : ∀ i, i≠j → (cupPrescription ψ i s).degreeOf j≤d) := + canonicalInterpolant_spectator_degree _ (dividedCupPrescription_collision ψ hψ s) j d + ((dividedCupPrescription_marked_degree ψ j s).trans hdn) + (fun i hi => by rw [dividedCupPrescription_spectator_degree_eq ψ i j (Ne.symm hi)]; exact ho i hi) + constructor + · exact (dmul hzm (hcan (n+1) (by omega) (by intro i hi; exact (hc i hi).1.trans (by omega)))).trans (by omega) + · intro hj + exact (dmul hzm (hcan n (by omega) (by intro i hi; exact ((hc i hi).2 hj).trans (by omega)))).trans (by omega) + +end PolynomialVacuumAlgebra + +end OAI diff --git a/lean/OAI/Combinatorics/PolynomialVacuum/Algebra/InterpolatedExchanges.lean b/lean/OAI/Combinatorics/PolynomialVacuum/Algebra/InterpolatedExchanges.lean new file mode 100644 index 0000000000000000000000000000000000000000..26a894e867d9cf0bd0364e4c870117616d08e2c1 --- /dev/null +++ b/lean/OAI/Combinatorics/PolynomialVacuum/Algebra/InterpolatedExchanges.lean @@ -0,0 +1,61 @@ +import OAI.Combinatorics.PolynomialVacuum.Algebra.FirstExchanges +import OAI.Combinatorics.PolynomialVacuum.Algebra.NaturalCandidateEndpoints + +namespace OAI + +namespace PolynomialVacuumAlgebra +open MvPolynomial Classical + +theorem eval_interpolateState {n : ℕ} (ψ : State n) (χ : State (n+1)) + (s : Fin (n+2) → Spin) (Z : Fin (n+2) → ℂ) : + eval Z (interpolateState ψ χ s)= + (lastPolynomial ψ χ s).eval₂ (eval (Z ∘ Fin.castSucc)) (T⁻¹*Z (Fin.last (n+1))) := by + rw [interpolateState_eq_reinsert,eval_reinsertLast] + +theorem eval₂_lastPolynomial_swap {n : ℕ} (p : Polynomial (MvPolynomial (Fin (n+1)) ℂ)) + (j : Fin n) (Xv : ℕ → ℂ) : + (p.map (rename (Equiv.swap j.castSucc j.succ)).toRingHom).eval₂ + (eval (fun k : Fin (n+1) => Xv k.val)) (T⁻¹*Xv (n+1))= + p.eval₂ (eval (fun k : Fin (n+1) => swapSite j.val Xv k.val)) + (T⁻¹*swapSite j.val Xv (n+1)) := by + have hl : swapSite j.val Xv (n+1)=Xv (n+1) := + swapSite_other (by have:=j.isLt; omega) (by have:=j.isLt; omega) Xv + rw [hl] + induction p using Polynomial.induction_on' with + | add p q hp hq => simpa only [Polynomial.map_add,Polynomial.eval₂_add] using congrArg₂ (·+·) hp hq + | monomial k a => + simp only [Polynomial.map_monomial,Polynomial.eval₂_monomial] + change eval (fun k => Xv k.val) (rename (Equiv.swap j.castSucc j.succ) a) * _=_ + rw [eval_rename] + congr 2 + apply congrArg eval + funext i + simp only [Function.comp_apply,swapSite,Equiv.swap_apply_def,Fin.ext_iff, + Fin.val_castSucc,Fin.val_succ] + split_ifs <;> rfl + +theorem interpolateState_first_exchanges {n : ℕ} (ψ : State n) (χ : State (n+1)) + (hψ : LowerExchange (liftState ψ) n) (hχ : LowerExchange (liftState χ) (n+1)) : + LowerExchange (liftState (interpolateState ψ χ)) (n+1) := by + intro j hj Xv + let jf : Fin n := ⟨j,by omega⟩ + funext s + have he := congrArg (fun p : Polynomial (MvPolynomial (Fin (n+1)) ℂ) => + p.eval₂ (eval (fun k => Xv k.val)) (T⁻¹*Xv (n+1))) + (lastPolynomial_first_exchange ψ χ hψ hχ jf (fun k => s k.val)) + simp only [Polynomial.eval₂_finsetSum,Polynomial.eval₂_mul,Polynomial.eval₂_C,Polynomial.eval₂_sub, + eval_polyExchangeNumerator,map_mul,map_sub,eval_C,eval_X,eval₂_lastPolynomial_swap] at he + change (siteR j (Xv j) (Xv (j+1)) (liftState (interpolateState ψ χ) Xv)) s=_ + simp only [siteR,pairLinear,LinearMap.coe_mk,AddHom.coe_mk,pairAction,Pi.smul_apply,smul_eq_mul, + liftState,liftPolyTensor,eval_interpolateState] + convert he using 1 + · apply Finset.sum_congr rfl + intro ab hab + congr 2 + congr 1 + exact replacePair_restrict (pairLeft jf.castSucc) (pairRight jf.castSucc) s ab + · rfl + +end PolynomialVacuumAlgebra + +end OAI diff --git a/lean/OAI/Combinatorics/PolynomialVacuum/Algebra/InterpolatedZero.lean b/lean/OAI/Combinatorics/PolynomialVacuum/Algebra/InterpolatedZero.lean new file mode 100644 index 0000000000000000000000000000000000000000..ccbfec39b06145368ab892ab33b0d0f084fa0253 --- /dev/null +++ b/lean/OAI/Combinatorics/PolynomialVacuum/Algebra/InterpolatedZero.lean @@ -0,0 +1,73 @@ +import OAI.Combinatorics.PolynomialVacuum.Algebra.ZeroFiltration +import OAI.Combinatorics.PolynomialVacuum.Algebra.LastPolynomial + +namespace OAI + +namespace PolynomialVacuumAlgebra +open MvPolynomial Classical + +def MinusZero {n : ℕ} (ψ : State n) : Prop := + ∀ s i, s i=Spin.minus → killSite i (ψ s)=0 + +theorem initialCup_spectator_zero {n : ℕ} (ψ : State n) (hz : MinusZero ψ) + (i j : Fin (n+1)) (hji : j≠i) (s : Fin (n+2) → Spin) + (hs : s (spectatorSlot j (pairRight i))=Spin.minus) : killSite j (initialCup ψ i s)=0 := by + obtain ⟨l,rfl⟩:=Fin.exists_succAbove_eq hji + rw [omitPair_spectatorSlot] at hs + simp only [initialCup,map_mul,killSite_C] + rw [killSite_rename_injective _ Fin.succAbove_right_injective,hz _ _ hs,map_zero,mul_zero] + +theorem cupPrescription_spectator_zero {n : ℕ} (ψ : State n) (hz : MinusZero ψ) + (i j : Fin (n+1)) (hji : j≠i) (s : Fin (n+2) → Spin) + (hs : s j.castSucc=Spin.minus) : killSite j (cupPrescription ψ i s)=0 := by + have ht:=transportCup_spectator_zero i j (rightSpectators i) _ _ (rightSpectators_path i) + (initialCup ψ i) (fun s hs => initialCup_spectator_zero ψ hz i j hji s hs) s + (by simpa only [spectatorSlot_last] using hs) + simp only [cupPrescription,map_mul,ht,mul_zero] + +theorem dividedCupPrescription_spectator_zero {n : ℕ} (ψ : State n) (hz : MinusZero ψ) + (i j : Fin (n+1)) (hji : j≠i) (s : Fin (n+2) → Spin) + (hs : s j.castSucc=Spin.minus) : killSite j (dividedCupPrescription ψ i s)=0 := by + have h := cupPrescription_spectator_zero ψ hz i j hji s hs + rw [cupPrescription_factor,map_mul,killSite_X,ite_eq_right (Ne.symm hji)] at h + exact (mul_eq_zero.mp h).resolve_left (X_ne_zero i) + +theorem interpolateState_spectator_zero {n : ℕ} (ψ : State n) (χ : State (n+1)) + (hψ : LowerExchange (liftState ψ) n) (hz : MinusZero ψ) (hχ : MinusZero χ) + (s : Fin (n+2) → Spin) (j : Fin (n+1)) (hs : s j.castSucc=Spin.minus) : + killSite j.castSucc (interpolateState ψ χ s)=0 := by + have hv : ∀ i, killSite j (cupPrescription ψ i s)=0 := by + intro i + by_cases hij : i=j + · subst i; simp [cupPrescription_factor] + · exact cupPrescription_spectator_zero ψ hz i j (Ne.symm hij) s hs + by_cases hl : s (Fin.last (n+1))=Spin.plus + · simp only [interpolateState,ite_eq_left hl] + exact canonicalInterpolant_killSite _ (cupPrescription_collision ψ hψ s) j hv + · have hw : ∀ i, killSite j (dividedCupPrescription ψ i s)=0 := by + intro i + by_cases hij : i=j + · subst i; exact dividedCupPrescription_marked_zero ψ j s hs hl + · exact dividedCupPrescription_spectator_zero ψ hz i j (Ne.symm hij) s hs + have hc := canonicalInterpolant_killSite _ (dividedCupPrescription_collision ψ hψ s) j hw + simp only [interpolateState,ite_eq_right hl,map_add,map_mul,hc,mul_zero,zero_add] + split_ifs + · rw [map_mul,killSite_rename,hχ _ _ hs,map_zero,mul_zero] + · exact map_zero _ + +theorem interpolateState_last_minus_zero {n : ℕ} (ψ : State n) (χ : State (n+1)) + (s : Fin (n+2) → Spin) (hs : s (Fin.last (n+1))=Spin.minus) : + killSite (Fin.last (n+1)) (interpolateState ψ χ s)=0 := by + simp [interpolateState,hs] + +theorem interpolateState_minusZero {n : ℕ} (ψ : State n) (χ : State (n+1)) + (hψ : LowerExchange (liftState ψ) n) (hz : MinusZero ψ) (hχ : MinusZero χ) : + MinusZero (interpolateState ψ χ) := by + intro s j hs + refine Fin.lastCases ?_ (fun k hk => ?_) j hs + · exact interpolateState_last_minus_zero ψ χ s + · exact interpolateState_spectator_zero ψ χ hψ hz hχ s k hk + +end PolynomialVacuumAlgebra + +end OAI diff --git a/lean/OAI/Combinatorics/PolynomialVacuum/Algebra/Interpolation.lean b/lean/OAI/Combinatorics/PolynomialVacuum/Algebra/Interpolation.lean new file mode 100644 index 0000000000000000000000000000000000000000..a6294cac45a3969d36d4f15139fa6e577f02569e --- /dev/null +++ b/lean/OAI/Combinatorics/PolynomialVacuum/Algebra/Interpolation.lean @@ -0,0 +1,63 @@ +import OAI.Combinatorics.PolynomialVacuum.Algebra.InterpolationDefinitions + +namespace OAI + +namespace PolynomialVacuumInterpolation +open Polynomial + + + +theorem integral_interpolation {R ι : Type*} [CommRing R] [IsDomain R] [DecompositionMonoid R] + (s : Finset ι) (a v : ι → R) + (hrel : ∀ i ∈ s, ∀ j ∈ s, ∀ k ∈ s, i ≠ j → i ≠ k → j ≠ k → + IsRelPrime (a i-a j) (a i-a k)) + (hcompat : ∀ i ∈ s, ∀ j ∈ s, a i-a j ∣ v i-v j) : + ∃ p : R[X], p.degree < (s.card : WithBot ℕ) ∧ ∀ i ∈ s, p.eval (a i)=v i := by + classical + induction s using Finset.induction_on with + | empty => + exact ⟨0,by simp,by simp⟩ + | @insert b s hb ih => + obtain ⟨p,hdeg,heval⟩ := ih + (fun i hi j hj k hk hij hik hjk => hrel i (by simp [hi]) j (by simp [hj]) + k (by simp [hk]) hij hik hjk) + (fun i hi j hj => hcompat i (by simp [hi]) j (by simp [hj])) + have hdvd : (∏ i ∈ s, (a b-a i)) ∣ v b-p.eval (a b) := by + apply Finset.prod_dvd_of_isRelPrime + · intro i hi j hj hij + exact hrel b (Finset.mem_insert_self b s) i (Finset.mem_insert_of_mem hi) j (Finset.mem_insert_of_mem hj) + (by rintro rfl; exact hb hi) (by rintro rfl; exact hb hj) hij + · intro i hi + have h1 := hcompat b (by simp) i (by simp [hi]) + have h2 := Polynomial.sub_dvd_eval_sub (a b) (a i) p + have hh : v b-p.eval (a b) = (v b-v i)-(p.eval (a b)-p.eval (a i)) := by + rw [heval i hi]; ring + rw [hh] + exact dvd_sub h1 h2 + obtain ⟨c,hc⟩ := hdvd + let q : R[X] := ∏ i ∈ s, (X-C (a i)) + have hqeval (r : R) : q.eval r = ∏ i ∈ s, (r-a i) := by + simp [q,Polynomial.eval_prod] + have hqzero (i : ι) (hi : i ∈ s) : q.eval (a i)=0 := by + rw [hqeval] + exact Finset.prod_eq_zero hi (sub_self _) + have hqdeg : q.degree ≤ (s.card : WithBot ℕ) := by + calc q.degree ≤ ∑ i ∈ s, (X-C (a i) : R[X]).degree := Polynomial.degree_prod_le s _ + _ = (s.card : WithBot ℕ) := by simp + refine ⟨p+C c*q,?_,?_⟩ + · rw [Finset.card_insert_of_notMem hb] + apply lt_of_le_of_lt (Polynomial.degree_add_le p (C c*q)) + apply max_lt + · exact lt_trans hdeg (by exact_mod_cast Nat.lt_succ_self s.card) + · apply lt_of_le_of_lt (show (C c*q).degree ≤ q.degree from by + rw [← Polynomial.smul_eq_C_mul]; exact Polynomial.degree_smul_le c q) + exact lt_of_le_of_lt hqdeg (by exact_mod_cast Nat.lt_succ_self s.card) + · intro i hi + rcases Finset.mem_insert.mp hi with rfl | hi + · simp only [Polynomial.eval_add,Polynomial.eval_mul,Polynomial.eval_C,hqeval] + linear_combination -hc + · simp [heval i hi,hqzero i hi] + +end PolynomialVacuumInterpolation + +end OAI diff --git a/lean/OAI/Combinatorics/PolynomialVacuum/Algebra/InterpolationDefinitions.lean b/lean/OAI/Combinatorics/PolynomialVacuum/Algebra/InterpolationDefinitions.lean new file mode 100644 index 0000000000000000000000000000000000000000..943050e799d75e62d2b48ef584fe90f02ac917ec --- /dev/null +++ b/lean/OAI/Combinatorics/PolynomialVacuum/Algebra/InterpolationDefinitions.lean @@ -0,0 +1,17 @@ +import Mathlib + +namespace OAI + +namespace PolynomialVacuumInterpolation +open Classical + +noncomputable def mergeVariable {ι : Type*} (i j : ι) : + MvPolynomial ι ℂ →+* MvPolynomial ι ℂ := + MvPolynomial.eval₂Hom MvPolynomial.C (fun k => if k=i then MvPolynomial.X j else MvPolynomial.X k) + +noncomputable def nodeFactor {ι : Type*} (i j : ι) : MvPolynomial ι ℂ := + MvPolynomial.X i - MvPolynomial.X j + +end PolynomialVacuumInterpolation + +end OAI diff --git a/lean/OAI/Combinatorics/PolynomialVacuum/Algebra/InterpolationNodes.lean b/lean/OAI/Combinatorics/PolynomialVacuum/Algebra/InterpolationNodes.lean new file mode 100644 index 0000000000000000000000000000000000000000..35c7af86c5a7a72e2c65963d8c63998e9a186196 --- /dev/null +++ b/lean/OAI/Combinatorics/PolynomialVacuum/Algebra/InterpolationNodes.lean @@ -0,0 +1,52 @@ +import OAI.Combinatorics.PolynomialVacuum.Algebra.PrescriptionCollision +import OAI.Combinatorics.PolynomialVacuum.Algebra.CandidateEndpoints + +namespace OAI + +namespace PolynomialVacuumAlgebra +open MvPolynomial Classical + + +theorem eval_reinsertLast {m : ℕ} (p : Polynomial (MvPolynomial (Fin m) ℂ)) + (Z : Fin (m+1) → ℂ) : + eval Z (reinsertLast p)=p.eval₂ (eval (Z ∘ Fin.castSucc)) (T⁻¹*Z (Fin.last m)) := by + unfold reinsertLast + induction p using Polynomial.induction_on' with + | add p r hp hr => simp only [Polynomial.eval₂_add,map_add,hp,hr] + | monomial k a => simp [Polynomial.eval₂_monomial,eval_rename] + +theorem eval_reinsertLast_node {m : ℕ} (p : Polynomial (MvPolynomial (Fin m) ℂ)) + (Z : Fin (m+1) → ℂ) (i : Fin m) (hZ : Z (Fin.last m)=T*Z i.castSucc) : + eval Z (reinsertLast p)=eval (Z ∘ Fin.castSucc) (p.eval (X i)) := by + rw [eval_reinsertLast] + have hx : T⁻¹*Z (Fin.last m)=eval (Z ∘ Fin.castSucc) (X i) := by + simp [hZ,T_ne_zero,Function.comp_apply] + rw [hx,Polynomial.eval₂_at_apply] + + + +theorem interpolateState_node {n : ℕ} (ψ : State n) (χ : State (n+1)) + (hψ : LowerExchange (liftState ψ) n) (s : Fin (n+2) → Spin) + (Z : Fin (n+2) → ℂ) (i : Fin (n+1)) + (hZ : Z (Fin.last (n+1))=T*Z i.castSucc) : + eval Z (interpolateState ψ χ s)=eval (Z ∘ Fin.castSucc) (cupPrescription ψ i s) := by + have hzero : (∏ j : Fin (n+1), (Z j.castSucc-T⁻¹*Z (Fin.last (n+1))))=0 := by + apply Finset.prod_eq_zero (Finset.mem_univ i) + simp [hZ,T_ne_zero] + unfold interpolateState + split_ifs with hs hs' + · rw [eval_reinsertLast_node _ _ i hZ, + canonicalInterpolant_eval _ (cupPrescription_collision ψ hψ s)] + · simp only [map_add,map_mul,map_prod,map_sub,eval_C,eval_X,eval_rename] + rw [eval_reinsertLast_node _ _ i hZ, + canonicalInterpolant_eval _ (dividedCupPrescription_collision ψ hψ s),hzero,zero_mul,add_zero] + rw [cupPrescription_factor,map_mul,eval_X] + simp [hZ,T_ne_zero,Function.comp_apply] + · simp only [map_mul,add_zero,eval_C,eval_X] + rw [eval_reinsertLast_node _ _ i hZ, + canonicalInterpolant_eval _ (dividedCupPrescription_collision ψ hψ s),cupPrescription_factor,map_mul,eval_X] + simp [hZ,T_ne_zero,Function.comp_apply] + +end PolynomialVacuumAlgebra + +end OAI diff --git a/lean/OAI/Combinatorics/PolynomialVacuum/Algebra/KillSite.lean b/lean/OAI/Combinatorics/PolynomialVacuum/Algebra/KillSite.lean new file mode 100644 index 0000000000000000000000000000000000000000..6decb707a3ed19bdab7bddb1246988424ee3567d --- /dev/null +++ b/lean/OAI/Combinatorics/PolynomialVacuum/Algebra/KillSite.lean @@ -0,0 +1,90 @@ +import OAI.Combinatorics.PolynomialVacuum.Algebra.LagrangeDegree + +namespace OAI + +namespace PolynomialVacuumAlgebra +open MvPolynomial Classical + +noncomputable def killSite {ι : Type*} (j : ι) : MvPolynomial ι ℂ →+* MvPolynomial ι ℂ := + eval₂Hom C (fun i => if i=j then 0 else X i) + +@[simp] theorem killSite_C {ι : Type*} (j : ι) (c : ℂ) : killSite j (C c)=C c := by + simp [killSite] +@[simp] theorem killSite_X {ι : Type*} (i j : ι) : killSite j (X i)=if i=j then 0 else X i := by + simp [killSite] + +theorem killSite_rename_injective {ι κ : Type*} (f : ι → κ) (hf : Function.Injective f) + (j : ι) (p : MvPolynomial ι ℂ) : + killSite (f j) (rename f p)=rename f (killSite j p) := by + have he : (killSite (f j)).comp (rename f).toRingHom = + (rename f).toRingHom.comp (killSite j) := by + apply MvPolynomial.ringHom_ext + · intro c; simp + · intro i + simp only [RingHom.comp_apply,AlgHom.toRingHom_eq_coe,RingHom.coe_coe,rename_X,killSite_X] + by_cases h : i=j + · simp [h] + · simp [h,hf.ne h] + exact congrArg (fun g : MvPolynomial ι ℂ →+* MvPolynomial κ ℂ => g p) he + +theorem killSite_rename {m : ℕ} (j : Fin m) (p : MvPolynomial (Fin m) ℂ) : + killSite j.castSucc (rename Fin.castSucc p)=rename Fin.castSucc (killSite j p) := + killSite_rename_injective Fin.castSucc (Fin.castSucc_injective _) j p + +theorem killSite_difference_ne_zero {m : ℕ} (j : Fin m) {i k : Fin m} (hik : i≠k) : + killSite j (X i-X k)≠0 := by + rw [map_sub,killSite_X,killSite_X] + by_cases hi : i=j + · subst i + simp only [ite_true,ite_eq_right (Ne.symm hik),zero_sub,neg_ne_zero] + exact X_ne_zero k + · by_cases hk : k=j + · subst k + simp only [ite_eq_right hi,ite_true,sub_zero] + exact X_ne_zero i + · simp only [ite_eq_right hi,ite_eq_right hk] + exact sub_ne_zero.mpr (fun h => hik (X_injective h)) + +theorem killSite_denominators_ne_zero {m : ℕ} (j : Fin m) : + killSite j (allNodeDenominators m)≠0 := by + simp only [allNodeDenominators,nodeDenominator,map_prod] + apply Finset.prod_ne_zero_iff.mpr + intro i hi + apply Finset.prod_ne_zero_iff.mpr + intro k hk + exact killSite_difference_ne_zero j (Ne.symm (Finset.mem_erase.mp hk).1) + + + +theorem canonicalInterpolant_killSite {n : ℕ} + (V : Fin (n+1) → MvPolynomial (Fin (n+1)) ℂ) (hV : CollisionCompatible V) + (j : Fin (n+1)) (hz : ∀ i, killSite j (V i)=0) : + killSite j.castSucc (reinsertLast (canonicalInterpolant V))=0 := by + have h := congrArg (fun p => killSite j.castSucc (reinsertLast p)) + (canonicalInterpolant_cleared V hV) + have he (p r : Polynomial (MvPolynomial (Fin (n+1)) ℂ)) : + reinsertLast (p+r)=reinsertLast p+reinsertLast r := by simp [reinsertLast,Polynomial.eval₂_add] + have hs (f : Fin (n+1) → Polynomial (MvPolynomial (Fin (n+1)) ℂ)) : + reinsertLast (∑ i, f i)=∑ i, reinsertLast (f i) := by simp [reinsertLast,Polynomial.eval₂_finsetSum] + simp only [reinsertLast_mul,reinsertLast_C,hs,map_mul,map_sum,killSite_rename,map_mul,hz,mul_zero, + map_zero,zero_mul,Finset.sum_const_zero] at h + have hn : rename Fin.castSucc (killSite j (allNodeDenominators (n+1)))≠0 := by + intro h0 + exact killSite_denominators_ne_zero j ((rename_injective Fin.castSucc (Fin.castSucc_injective _)) (by simpa using h0)) + exact (mul_eq_zero.mp h).resolve_left hn + +@[simp] theorem eval_killSite {ι : Type*} (j : ι) (Y : ι → ℂ) (p : MvPolynomial ι ℂ) : + eval Y (killSite j p)=eval (Function.update Y j 0) p := by + change eval Y (eval₂ C (fun i => if i=j then 0 else X i) p)=_ + rw [eval_eval₂] + have he : (eval Y).comp C=RingHom.id ℂ := by ext c; simp + rw [he] + change eval (fun i => eval Y (if i=j then 0 else X i)) p=_ + congr 2 + funext i + simp only [Function.update_apply] + split_ifs <;> simp + +end PolynomialVacuumAlgebra + +end OAI diff --git a/lean/OAI/Combinatorics/PolynomialVacuum/Algebra/LagrangeClearing.lean b/lean/OAI/Combinatorics/PolynomialVacuum/Algebra/LagrangeClearing.lean new file mode 100644 index 0000000000000000000000000000000000000000..bf2539ba854dd5ee69bc11373a03863841f2339c --- /dev/null +++ b/lean/OAI/Combinatorics/PolynomialVacuum/Algebra/LagrangeClearing.lean @@ -0,0 +1,84 @@ +import OAI.Combinatorics.PolynomialVacuum.Algebra.LastPolynomial +import OAI.Combinatorics.PolynomialVacuum.Algebra.ExchangeDegrees + +namespace OAI + +namespace PolynomialVacuumAlgebra +open MvPolynomial Classical PolynomialVacuumInterpolation + +noncomputable def nodeDenominator {m : ℕ} (i : Fin m) : MvPolynomial (Fin m) ℂ := + ∏ j ∈ Finset.univ.erase i, (X i-X j) +noncomputable def allNodeDenominators (m : ℕ) : MvPolynomial (Fin m) ℂ := + ∏ i, nodeDenominator i +noncomputable def exceptNodeDenominator {m : ℕ} (i : Fin m) : MvPolynomial (Fin m) ℂ := + ∏ j ∈ Finset.univ.erase i, nodeDenominator j +noncomputable def nodeNumerator {m : ℕ} (i : Fin m) : Polynomial (MvPolynomial (Fin m) ℂ) := + ∏ j ∈ Finset.univ.erase i, (Polynomial.X-Polynomial.C (X j)) + +theorem nodeDenominator_ne_zero {m : ℕ} (i : Fin m) : nodeDenominator i≠0 := by + apply Finset.prod_ne_zero_iff.mpr + intro j hj + apply sub_ne_zero.mpr + exact fun he => (Finset.mem_erase.mp hj).1 (MvPolynomial.X_injective he).symm + +theorem allNodeDenominators_ne_zero (m : ℕ) : allNodeDenominators m≠0 := by + apply Finset.prod_ne_zero_iff.mpr + intro i _; exact nodeDenominator_ne_zero i + +theorem allNodeDenominators_factor {m : ℕ} (i : Fin m) : + allNodeDenominators m=exceptNodeDenominator i*nodeDenominator i := by + exact (Finset.prod_erase_mul _ _ (Finset.mem_univ i)).symm + +theorem nodeNumerator_self {m : ℕ} (i : Fin m) : + (nodeNumerator i).eval (X i)=nodeDenominator i := by + simp [nodeNumerator,nodeDenominator,Polynomial.eval_prod] + +theorem nodeNumerator_other {m : ℕ} {i k : Fin m} (h : i≠k) : + (nodeNumerator i).eval (X k)=0 := by + simp only [nodeNumerator,Polynomial.eval_prod,Polynomial.eval_sub,Polynomial.eval_X,Polynomial.eval_C] + apply Finset.prod_eq_zero (by simp [h.symm] : k ∈ Finset.univ.erase i) + simp + +theorem nodeNumerator_natDegree {n : ℕ} (i : Fin (n+1)) : (nodeNumerator i).natDegree ≤ n := by + apply (Polynomial.natDegree_prod_le _ _).trans + calc + _ ≤ ∑ _j ∈ Finset.univ.erase i, 1 := by + apply Finset.sum_le_sum + intro j hj + exact (Polynomial.natDegree_sub_le _ _).trans (by simp) + _ = n := by simp + + + +theorem canonicalInterpolant_cleared {n : ℕ} + (V : Fin (n+1) → MvPolynomial (Fin (n+1)) ℂ) (hV : CollisionCompatible V) : + Polynomial.C (allNodeDenominators (n+1))*canonicalInterpolant V = + ∑ i, Polynomial.C (exceptNodeDenominator i*V i)*nodeNumerator i := by + apply regular_lagrange_unique (Finset.univ : Finset (Fin (n+1))) + · have hn := (Polynomial.natDegree_C_mul_le (allNodeDenominators (n+1)) (canonicalInterpolant V)).trans + (canonicalInterpolant_natDegree V) + have hh : (Polynomial.C (allNodeDenominators (n+1))*canonicalInterpolant V).degree < + ((n+1 : ℕ) : WithBot ℕ) := + (Polynomial.degree_le_natDegree.trans (WithBot.coe_le_coe.mpr hn)).trans_lt + (WithBot.coe_lt_coe.mpr (Nat.lt_succ_self n)) + simpa using hh + · have hn : (∑ i : Fin (n+1), Polynomial.C (exceptNodeDenominator i*V i)*nodeNumerator i).natDegree ≤ n := by + apply Polynomial.natDegree_sum_le_of_forall_le + intro i hi + exact (Polynomial.natDegree_C_mul_le _ _).trans (nodeNumerator_natDegree i) + have hh : (∑ i : Fin (n+1), Polynomial.C (exceptNodeDenominator i*V i)*nodeNumerator i).degree < + ((n+1 : ℕ) : WithBot ℕ) := + (Polynomial.degree_le_natDegree.trans (WithBot.coe_le_coe.mpr hn)).trans_lt + (WithBot.coe_lt_coe.mpr (Nat.lt_succ_self n)) + simpa using hh + · intro k hk + simp only [Polynomial.eval_mul,Polynomial.eval_C,canonicalInterpolant_eval V hV, + Polynomial.eval_finsetSum] + rw [Finset.sum_eq_single k] + · rw [nodeNumerator_self,allNodeDenominators_factor k]; ring + · intro i hi hik; rw [nodeNumerator_other hik,mul_zero] + · simp + +end PolynomialVacuumAlgebra + +end OAI diff --git a/lean/OAI/Combinatorics/PolynomialVacuum/Algebra/LagrangeDegree.lean b/lean/OAI/Combinatorics/PolynomialVacuum/Algebra/LagrangeDegree.lean new file mode 100644 index 0000000000000000000000000000000000000000..bde83c6ea94c82b7d0ca08b694f1266aa76d7e45 --- /dev/null +++ b/lean/OAI/Combinatorics/PolynomialVacuum/Algebra/LagrangeDegree.lean @@ -0,0 +1,119 @@ +import OAI.Combinatorics.PolynomialVacuum.Algebra.LagrangeClearing + +namespace OAI + +namespace PolynomialVacuumAlgebra +open MvPolynomial Classical + +theorem difference_degree_self {m : ℕ} {i k : Fin m} (hik : i≠k) : + (X i-X k : MvPolynomial (Fin m) ℂ).degreeOf i=1 := by + rw [sub_eq_add_neg,degreeOf_add_eq_of_degreeOf_lt] + · simp + · simp [degreeOf_X_of_ne hik] + +theorem nodeDenominator_marked_degree {n : ℕ} (i : Fin (n+1)) : + (nodeDenominator i).degreeOf i=n := by + rw [nodeDenominator,degreeOf_prod_eq _ _] + · have h (k) (hk : k ∈ Finset.univ.erase i) : + (X i-X k : MvPolynomial (Fin (n+1)) ℂ).degreeOf i=1 := + difference_degree_self ((Finset.mem_erase.mp hk).1.symm) + simp_rw [Finset.sum_congr rfl h] + simp + · intro k hk + exact sub_ne_zero.mpr (fun h => (Finset.mem_erase.mp hk).1 (X_injective h).symm) + +theorem nodeDenominator_spectator_degree {n : ℕ} (i j : Fin (n+1)) (hji : j≠i) : + (nodeDenominator i).degreeOf j=1 := by + rw [nodeDenominator,degreeOf_prod_eq _ _] + · rw [Finset.sum_eq_single j] + · have he : (X i-X j : MvPolynomial (Fin (n+1)) ℂ)=-(X j-X i) := by ring + rw [he,degreeOf_neg,difference_degree_self hji] + · intro k hk hkj + apply Nat.eq_zero_of_le_zero + rw [sub_eq_add_neg] + exact dadd (le_of_eq (degreeOf_X_of_ne hji)) (by simpa using + (le_of_eq (degreeOf_X_of_ne hkj.symm) : (X k : MvPolynomial (Fin (n+1)) ℂ).degreeOf j≤0)) + · simp [hji] + · intro k hk + exact sub_ne_zero.mpr (fun h => (Finset.mem_erase.mp hk).1 (X_injective h).symm) + +theorem exceptNodeDenominator_ne_zero {m : ℕ} (i : Fin m) : exceptNodeDenominator i≠0 := by + apply Finset.prod_ne_zero_iff.mpr + intro k hk; exact nodeDenominator_ne_zero k + +@[simp] theorem reinsertLast_C {m : ℕ} (p : MvPolynomial (Fin m) ℂ) : + reinsertLast (Polynomial.C p)=rename Fin.castSucc p := by simp [reinsertLast] +@[simp] theorem reinsertLast_mul {m : ℕ} (p r : Polynomial (MvPolynomial (Fin m) ℂ)) : + reinsertLast (p*r)=reinsertLast p*reinsertLast r := by simp [reinsertLast,Polynomial.eval₂_mul] + +theorem reinsert_nodeNumerator_degree {n : ℕ} (i j : Fin (n+1)) : + (reinsertLast (nodeNumerator i)).degreeOf j.castSucc ≤ if i=j then 0 else 1 := by + unfold nodeNumerator reinsertLast + simp only [Polynomial.eval₂_finsetProd,Polynomial.eval₂_sub,Polynomial.eval₂_X, + Polynomial.eval₂_C,AlgHom.toRingHom_eq_coe,RingHom.coe_coe,rename_X] + apply (degreeOf_prod_le _ _ _).trans + calc + _ ≤ ∑ k ∈ Finset.univ.erase i, if k=j then 1 else 0 := by + apply Finset.sum_le_sum + intro k hk + have hz : (C T⁻¹*X (Fin.last (n+1)) : MvPolynomial (Fin (n+2)) ℂ).degreeOf j.castSucc≤0 := + dconst_mul _ (le_of_eq (degreeOf_X_of_ne (Fin.castSucc_ne_last j))) + rw [sub_eq_add_neg] + by_cases hkj : k=j + · subst k + simp only + exact dadd (hz.trans (by omega)) (by simp) + · simp only [ite_eq_right hkj] + exact dadd hz (by rw [degreeOf_neg]; exact le_of_eq (degreeOf_X_of_ne (by + intro h; exact hkj (Fin.castSucc_injective _ h.symm)))) + _ = if i=j then 0 else 1 := by + by_cases h : i=j + · subst i; simp + · simp [h,Ne.symm h] + + + +theorem canonicalInterpolant_spectator_degree {n : ℕ} + (V : Fin (n+1) → MvPolynomial (Fin (n+1)) ℂ) (hV : CollisionCompatible V) + (j : Fin (n+1)) (d : ℕ) + (hmark : (V j).degreeOf j ≤ d+n) + (hother : ∀ i, i≠j → (V i).degreeOf j ≤ d) : + (reinsertLast (canonicalInterpolant V)).degreeOf j.castSucc ≤ d := by + let p:=reinsertLast (canonicalInterpolant V) + by_cases hp : p=0 + · simp only [← show p=reinsertLast (canonicalInterpolant V) from rfl,hp,degreeOf_zero,Nat.zero_le] + have hcleared := congrArg (reinsertLast (m:=n+1)) (canonicalInterpolant_cleared V hV) + have hsum : rename Fin.castSucc (allNodeDenominators (n+1))*p = + ∑ i, rename Fin.castSucc (exceptNodeDenominator i*V i)*reinsertLast (nodeNumerator i) := by + simpa only [p,reinsertLast,Polynomial.eval₂_finsetSum,Polynomial.eval₂_mul,Polynomial.eval₂_C,AlgHom.toRingHom_eq_coe,RingHom.coe_coe] using hcleared + have hD : rename Fin.castSucc (allNodeDenominators (n+1))≠0 := by + exact fun h => allNodeDenominators_ne_zero (n+1) ((rename_injective Fin.castSucc (Fin.castSucc_injective _)) (by simpa using h)) + have hbound : (rename Fin.castSucc (allNodeDenominators (n+1))*p).degreeOf j.castSucc ≤ + (allNodeDenominators (n+1)).degreeOf j+d := by + rw [hsum] + apply (degreeOf_sum_le _ _ _).trans + apply Finset.sup_le + intro i hi + have hf : (allNodeDenominators (n+1)).degreeOf j= + (exceptNodeDenominator i).degreeOf j+(nodeDenominator i).degreeOf j := by + rw [allNodeDenominators_factor i,degreeOf_mul_eq (exceptNodeDenominator_ne_zero i) (nodeDenominator_ne_zero i)] + have hv : (rename Fin.castSucc (exceptNodeDenominator i*V i)).degreeOf j.castSucc ≤ + (exceptNodeDenominator i).degreeOf j+(V i).degreeOf j := by + rw [degreeOf_rename_of_injective (Fin.castSucc_injective _)] + exact degreeOf_mul_le _ _ _ + have hh:=dmul hv (reinsert_nodeNumerator_degree i j) + by_cases hij : i=j + · subst i + rw [nodeDenominator_marked_degree] at hf + simp only [ite_true,add_zero] at hh + exact hh.trans (by omega) + · rw [nodeDenominator_spectator_degree i j (Ne.symm hij)] at hf + simp only [ite_eq_right hij] at hh + exact hh.trans (by have ho:=hother i hij; omega) + rw [degreeOf_mul_eq hD hp,degreeOf_rename_of_injective (Fin.castSucc_injective _)] at hbound + change p.degreeOf j.castSucc ≤ d + omega + +end PolynomialVacuumAlgebra + +end OAI diff --git a/lean/OAI/Combinatorics/PolynomialVacuum/Algebra/LastDegrees.lean b/lean/OAI/Combinatorics/PolynomialVacuum/Algebra/LastDegrees.lean new file mode 100644 index 0000000000000000000000000000000000000000..7a3d0cc673be27fef012bfbe0df49cc118ec2442 --- /dev/null +++ b/lean/OAI/Combinatorics/PolynomialVacuum/Algebra/LastDegrees.lean @@ -0,0 +1,21 @@ +import OAI.Combinatorics.PolynomialVacuum.Algebra.InterpolatedDegrees + +namespace OAI + +namespace PolynomialVacuumAlgebra +open MvPolynomial Classical + +theorem interpolateState_last_degrees {n : ℕ} (ψ : State n) (χ : State (n+1)) + (s : Fin (n+2) → Spin) : + (interpolateState ψ χ s).degreeOf (Fin.last (n+1))≤n+1 ∧ + (s (Fin.last (n+1))=Spin.plus → (interpolateState ψ χ s).degreeOf (Fin.last (n+1))≤n) := by + rw [interpolateState_eq_reinsert] + constructor + · exact (reinsertLast_degree _).trans (lastPolynomial_natDegree ψ χ s) + · intro hs + simp only [lastPolynomial,ite_eq_left hs] + exact (reinsertLast_degree _).trans (canonicalInterpolant_natDegree _) + +end PolynomialVacuumAlgebra + +end OAI diff --git a/lean/OAI/Combinatorics/PolynomialVacuum/Algebra/LastPolynomial.lean b/lean/OAI/Combinatorics/PolynomialVacuum/Algebra/LastPolynomial.lean new file mode 100644 index 0000000000000000000000000000000000000000..78ce987281f2dad2ee97f5da73d43195fe99a6a2 --- /dev/null +++ b/lean/OAI/Combinatorics/PolynomialVacuum/Algebra/LastPolynomial.lean @@ -0,0 +1,85 @@ +import OAI.Combinatorics.PolynomialVacuum.Algebra.InterpolationNodes + +namespace OAI + +namespace PolynomialVacuumAlgebra +open MvPolynomial Classical + +noncomputable def lastPolynomial {n : ℕ} (ψ : State n) (χ : State (n+1)) + (s : Fin (n+2) → Spin) : Polynomial (MvPolynomial (Fin (n+1)) ℂ) := + if s (Fin.last (n+1))=Spin.plus then canonicalInterpolant (fun i => cupPrescription ψ i s) + else Polynomial.X*canonicalInterpolant (fun i => dividedCupPrescription ψ i s) + + if s (Fin.last (n+1))=Spin.zero then + (∏ i : Fin (n+1), (Polynomial.C (X i)-Polynomial.X))*Polynomial.C (χ (s ∘ Fin.castSucc)) + else 0 + +theorem interpolateState_eq_reinsert {n : ℕ} (ψ : State n) (χ : State (n+1)) + (s : Fin (n+2) → Spin) : + interpolateState ψ χ s=reinsertLast (lastPolynomial ψ χ s) := by + unfold interpolateState lastPolynomial + split_ifs <;> simp [reinsertLast,Polynomial.eval₂_mul,Polynomial.eval₂_add,Polynomial.eval₂_finsetProd, + Polynomial.eval₂_sub] + +theorem canonicalInterpolant_natDegree {n : ℕ} (V : Fin (n+1) → MvPolynomial (Fin (n+1)) ℂ) : + (canonicalInterpolant V).natDegree ≤ n := by + by_cases h : canonicalInterpolant V=0 + · simp [h] + · exact Nat.le_of_lt_succ ((Polynomial.natDegree_lt_iff_degree_lt h).mpr (canonicalInterpolant_degree V)) + +theorem lastPolynomial_degree_plus {n : ℕ} (ψ : State n) (χ : State (n+1)) + (s : Fin (n+2) → Spin) (hs : s (Fin.last (n+1))=Spin.plus) : + (lastPolynomial ψ χ s).degree < ((n+1 : ℕ) : WithBot ℕ) := by + simpa only [lastPolynomial,ite_eq_left hs] using canonicalInterpolant_degree (fun i => cupPrescription ψ i s) + +theorem lastPolynomial_natDegree {n : ℕ} (ψ : State n) (χ : State (n+1)) + (s : Fin (n+2) → Spin) : (lastPolynomial ψ χ s).natDegree ≤ n+1 := by + have hprod : (∏ i : Fin (n+1), (Polynomial.C (X i)-Polynomial.X) : + Polynomial (MvPolynomial (Fin (n+1)) ℂ)).natDegree ≤ n+1 := by + apply (Polynomial.natDegree_prod_le _ _).trans + calc + _ ≤ ∑ _i : Fin (n+1), 1 := by + apply Finset.sum_le_sum + intro i hi + exact (Polynomial.natDegree_sub_le _ _).trans (by simp) + _ = n+1 := by simp + unfold lastPolynomial + split_ifs with hs hs' + · exact (canonicalInterpolant_natDegree _).trans (by omega) + · apply Polynomial.natDegree_add_le_of_degree_le + · exact Polynomial.natDegree_mul_le.trans (by + simpa only [Polynomial.natDegree_X,Nat.add_comm] using + Nat.add_le_add_right (canonicalInterpolant_natDegree + (fun i => dividedCupPrescription ψ i s)) 1) + · exact Polynomial.natDegree_mul_le.trans (by simpa using hprod) + · simp only [add_zero] + exact Polynomial.natDegree_mul_le.trans (by + simpa only [Polynomial.natDegree_X,Nat.add_comm] using + Nat.add_le_add_right (canonicalInterpolant_natDegree + (fun i => dividedCupPrescription ψ i s)) 1) + +theorem lastPolynomial_node {n : ℕ} (ψ : State n) (χ : State (n+1)) + (hψ : LowerExchange (liftState ψ) n) (s : Fin (n+2) → Spin) (i : Fin (n+1)) : + (lastPolynomial ψ χ s).eval (X i)=cupPrescription ψ i s := by + have hz : (∏ j : Fin (n+1), (X j-X i) : MvPolynomial (Fin (n+1)) ℂ)=0 := by + apply Finset.prod_eq_zero (Finset.mem_univ i) + simp + unfold lastPolynomial + split_ifs with hs hs' + · exact canonicalInterpolant_eval _ (cupPrescription_collision ψ hψ s) i + · simp only [Polynomial.eval_add,Polynomial.eval_mul,Polynomial.eval_prod,Polynomial.eval_sub, + Polynomial.eval_C,Polynomial.eval_X,hz,zero_mul,add_zero] + rw [canonicalInterpolant_eval _ (dividedCupPrescription_collision ψ hψ s),cupPrescription_factor] + · simp only [Polynomial.eval_mul,Polynomial.eval_X,add_zero] + rw [canonicalInterpolant_eval _ (dividedCupPrescription_collision ψ hψ s),cupPrescription_factor] + +theorem lastPolynomial_zero {n : ℕ} (ψ : State n) (χ : State (n+1)) + (s : Fin (n+2) → Spin) (hs : s (Fin.last (n+1))≠Spin.plus) : + (lastPolynomial ψ χ s).eval 0= + if s (Fin.last (n+1))=Spin.zero then (∏ i : Fin (n+1), X i)*χ (s ∘ Fin.castSucc) else 0 := by + unfold lastPolynomial + rw [ite_eq_right hs] + split_ifs <;> simp [Polynomial.eval_prod] + +end PolynomialVacuumAlgebra + +end OAI diff --git a/lean/OAI/Combinatorics/PolynomialVacuum/Algebra/MarkedDegree.lean b/lean/OAI/Combinatorics/PolynomialVacuum/Algebra/MarkedDegree.lean new file mode 100644 index 0000000000000000000000000000000000000000..ee49584c8e556d93a842f4a9b259c4375d86a3a5 --- /dev/null +++ b/lean/OAI/Combinatorics/PolynomialVacuum/Algebra/MarkedDegree.lean @@ -0,0 +1,80 @@ +import OAI.Combinatorics.PolynomialVacuum.Algebra.TransportFiltration +import OAI.Combinatorics.PolynomialVacuum.Algebra.Candidate + +namespace OAI + +namespace PolynomialVacuumAlgebra +open MvPolynomial Classical + +theorem transportCup_mul {n : ℕ} (i : Fin (n+1)) (ks : List (Fin (n+1))) + (f : MvPolynomial (Fin (n+1)) ℂ) (W : PolynomialTensor (n+2) (Fin (n+1))) : + transportCup i ks (fun s => f*W s)=fun s => f*transportCup i ks W s := by + induction ks generalizing W with + | nil => rfl + | cons k ks ih => + simp only [transportCup,List.foldl_cons,tensorExchange_mul] + exact ih _ + +theorem initialCup_marked_degree {n : ℕ} (ψ : State n) (i : Fin (n+1)) + (s : Fin (n+2) → Spin) : (initialCup ψ i s).degreeOf i=0 := by + apply Nat.eq_zero_of_le_zero + exact (degreeOf_C_mul_le _ _ _).trans (le_of_eq + (degreeOf_rename_missing i.succAbove _ i (fun j => Fin.succAbove_ne i j))) + +theorem leftFusionFactors_marked_degree {n : ℕ} (i : Fin (n+1)) : + (leftFusionFactors i).degreeOf i ≤ 2*i.val := by + apply (degreeOf_prod_le _ _ _).trans + calc + _ ≤ ∑ _k ∈ Finset.univ.filter (fun k : Fin (n+1) => k < i), 2 := by + apply Finset.sum_le_sum + intro k hk + have hd (c : ℂ) : (X k-C c*X i : MvPolynomial (Fin (n+1)) ℂ).degreeOf i ≤ 1 := by + rw [sub_eq_add_neg] + apply dadd + · exact (by rw [degreeOf_X]; split_ifs <;> omega) + · rw [degreeOf_neg]; exact dconst_mul _ (by simp) + exact dmul (hd _) (hd _) + _ = 2*i.val := by simp [leftSpectators_card,Nat.mul_comm] + +theorem cup_plus_carried (s : Spin) (h : -1 < charge s) : cup (Spin.plus,s)=0 := by + cases s <;> norm_num [charge] at h <;> norm_num [charge,cup] + + + +theorem cupPrescription_marked_degrees {n : ℕ} (ψ : State n) (i : Fin (n+1)) + (s : Fin (n+2) → Spin) : + (cupPrescription ψ i s).degreeOf i ≤ 2*n+1 ∧ + (s (pairLeft i)=Spin.plus → -1 < charge (s (Fin.last (n+1))) → + (cupPrescription ψ i s).degreeOf i ≤ 2*n) := by + let W : PolynomialTensor (n+2) (Fin (n+1)) := fun s => X i*initialCup ψ i s + have hd (v) : (W v).degreeOf i ≤ 0+1 := by + dsimp [W] + exact (dmul (by simp : (X i : MvPolynomial (Fin (n+1)) ℂ).degreeOf i≤1) + (le_of_eq (initialCup_marked_degree ψ i v))).trans (by omega) + have hf (v) (hv : v (pairLeft i)=Spin.plus) (hc : -1 < charge (v (pairRight i))) : + (W v).degreeOf i ≤ 0 := by + simp [W,initialCup,hv,cup_plus_carried _ hc] + have ht := transportCup_marked_filtration i (rightSpectators i) _ _ (rightSpectators_path i) + (by intro k hk; simpa [rightSpectators] using (List.mem_filter.mp hk).2) 0 W hd hf + have he : cupPrescription ψ i s=C (1+T)*leftFusionFactors i*transportCup i (rightSpectators i) W s := by + simp only [W,transportCup_mul,cupPrescription] + ring + rw [he] + have hi:=i.isLt + rw [rightSpectators_length] at ht + constructor + · exact (dmul (dconst_mul _ (leftFusionFactors_marked_degree i)) (ht.1 s)).trans (by omega) + · intro hs hl + exact (dmul (dconst_mul _ (leftFusionFactors_marked_degree i)) (ht.2 s hs hl)).trans (by omega) + +theorem dividedCupPrescription_marked_degree {n : ℕ} (ψ : State n) (i : Fin (n+1)) + (s : Fin (n+2) → Spin) : (dividedCupPrescription ψ i s).degreeOf i ≤ 2*n := by + by_cases hz : dividedCupPrescription ψ i s=0 + · simp [hz] + · have h := (cupPrescription_marked_degrees ψ i s).1 + rw [cupPrescription_factor,degreeOf_mul_eq (X_ne_zero _) hz,degreeOf_X_self] at h + omega + +end PolynomialVacuumAlgebra + +end OAI diff --git a/lean/OAI/Combinatorics/PolynomialVacuum/Algebra/NaturalCandidateEndpoints.lean b/lean/OAI/Combinatorics/PolynomialVacuum/Algebra/NaturalCandidateEndpoints.lean new file mode 100644 index 0000000000000000000000000000000000000000..7ed0198e05b1d9cf7c8210c1c87f4f04b51b0a90 --- /dev/null +++ b/lean/OAI/Combinatorics/PolynomialVacuum/Algebra/NaturalCandidateEndpoints.lean @@ -0,0 +1,40 @@ +import OAI.Combinatorics.PolynomialVacuum.Algebra.InterpolationNodes +import OAI.Combinatorics.PolynomialVacuum.Algebra.FirstCupZeroNode + +namespace OAI + +namespace PolynomialVacuumAlgebra +open MvPolynomial Classical + +theorem liftState_params_congr {n : ℕ} (ψ : State n) (X Y : ℕ → ℂ) + (h : ∀ j < n, X j=Y j) : liftState ψ X=liftState ψ Y := by + have he : (fun j : Fin n => X j.val)=(fun j : Fin n => Y j.val) := by + funext j; exact h j j.isLt + funext s + simp only [liftState,liftPolyTensor,he] + +theorem interpolateState_node_natural {n : ℕ} (ψ : State n) (χ : State (n+1)) + (hψ : LowerExchange (liftState ψ) n) (i : ℕ) (hi : i ≤ n) + (X : ℕ → ℂ) (hX : X (n+1)=T*X i) : + liftState (interpolateState ψ χ) X=naturalPrescription (liftState ψ) n i X := by + rw [← cupPrescription_evaluation ψ ⟨i,by omega⟩ X] + funext s + exact interpolateState_node ψ χ hψ (fun j => s j.val) (fun j => X j.val) + ⟨i,by omega⟩ hX + +theorem interpolateState_lastZero {n : ℕ} (ψ : State n) (χ : State (n+1)) : + LastZeroReduction (liftState (interpolateState ψ χ)) (liftState χ) (n+1) := by + intro X s hX hs + cases he : s (n+1) with + | plus => exact False.elim (hs he) + | minus => + change eval (fun j : Fin (n+2) => X j.val) (interpolateState ψ χ (fun j => s j.val))=0 + exact interpolateState_minus_zero ψ χ (fun j => s j.val) (fun j => X j.val) he hX + | zero => + simp only [ite_true] + simpa [prefixProduct,Fin.prod_univ_eq_prod_range,liftState,liftPolyTensor,Function.comp_def] using + interpolateState_zero_reduction ψ χ (fun j => s j.val) (fun j => X j.val) he hX + +end PolynomialVacuumAlgebra + +end OAI diff --git a/lean/OAI/Combinatorics/PolynomialVacuum/Algebra/NaturalCollision.lean b/lean/OAI/Combinatorics/PolynomialVacuum/Algebra/NaturalCollision.lean new file mode 100644 index 0000000000000000000000000000000000000000..22f48ebf6311fda91b05bac1459005591b768380 --- /dev/null +++ b/lean/OAI/Combinatorics/PolynomialVacuum/Algebra/NaturalCollision.lean @@ -0,0 +1,69 @@ +import OAI.Combinatorics.PolynomialVacuum.Algebra.NaturalCovariance +import OAI.Combinatorics.PolynomialVacuum.Algebra.NaturalUnitary + +namespace OAI + +namespace PolynomialVacuumAlgebra +open Classical + +def GenericParameters (n : ℕ) (X : ℕ → ℂ) : Prop := + ∀ a b, a ≤ n → b ≤ n → exchangeDenominator (X a) (X b)≠0 + +theorem genericParameters_swap {n i : ℕ} (hi : i < n) {X : ℕ → ℂ} + (hG : GenericParameters n X) : GenericParameters n (swapSite i X) := by + intro a b ha hb + apply hG + · simp only [Equiv.swap_apply_def] + split_ifs <;> omega + · simp only [Equiv.swap_apply_def] + split_ifs <;> omega + +theorem swapSite_eq_of_equal {α : Type*} (i : ℕ) (X : ℕ → α) + (he : X i=X (i+1)) : swapSite i X=X := by + funext k + by_cases h0 : k=i + · subst k; simp [he] + by_cases h1 : k=i+1 + · subst k; simp [he] + exact swapSite_other h0 h1 X + +theorem naturalPrescription_collision_forward {ψ : NatSpectralTensor} {n : ℕ} + (hψ : LowerExchange ψ n) (d : ℕ) : + ∀ (i : ℕ) (_hi : i+d ≤ n) (X : ℕ → ℂ), GenericParameters n X → + X i=X (i+d) → naturalPrescription ψ n i X=naturalPrescription ψ n (i+d) X := by + induction d with + | zero => intro i hi X hG he; simp + | succ d ih => + intro i hi X hG he + apply siteR_injective i (X i) (X (i+1)) (hG _ _ (by omega) (by omega)) + (hG _ _ (by omega) (by omega)) + rw [naturalPrescription_mark_right (by omega)] + by_cases hd : d=0 + · subst d + simp only [Nat.zero_add] at he ⊢ + rw [swapSite_eq_of_equal i X he,he,siteR_regular] + · have hbefore := naturalPrescription_swap_before (ψ:=ψ) (i:=i+(d+1)) (j:=i) + hi (by omega) hψ X + rw [hbefore] + congr 1 + have h := ih (i+1) (by omega) (swapSite i X) (genericParameters_swap (by omega) hG) + have hj : swapSite i X (i+1+d)=X (i+(d+1)) := by + rw [swapSite_other (by omega : i+1+d≠i) (by omega : i+1+d≠i+1)] + congr 1; omega + rw [swapSite_right,hj] at h + simpa only [show i+1+d=i+(d+1) by omega] using h he + +theorem naturalPrescription_collision_generic {ψ : NatSpectralTensor} {n i j : ℕ} + (hψ : LowerExchange ψ n) (hi : i ≤ n) (hj : j ≤ n) + (X : ℕ → ℂ) (hG : GenericParameters n X) (he : X i=X j) : + naturalPrescription ψ n i X=naturalPrescription ψ n j X := by + rcases le_total i j with h|h + · have h' := naturalPrescription_collision_forward hψ (j-i) i (by omega) X hG + simpa only [Nat.add_sub_of_le h] using h' (by simpa only [Nat.add_sub_of_le h] using he) + · have h' := naturalPrescription_collision_forward hψ (i-j) j (by omega) X hG + symm + simpa only [Nat.add_sub_of_le h] using h' (by simpa only [Nat.add_sub_of_le h] using he.symm) + +end PolynomialVacuumAlgebra + +end OAI diff --git a/lean/OAI/Combinatorics/PolynomialVacuum/Algebra/NaturalCovariance.lean b/lean/OAI/Combinatorics/PolynomialVacuum/Algebra/NaturalCovariance.lean new file mode 100644 index 0000000000000000000000000000000000000000..f2f2807ca355f037bb62e99cdaa10e60294f670e --- /dev/null +++ b/lean/OAI/Combinatorics/PolynomialVacuum/Algebra/NaturalCovariance.lean @@ -0,0 +1,96 @@ +import OAI.Combinatorics.PolynomialVacuum.Algebra.NaturalParameters +import OAI.Combinatorics.PolynomialVacuum.Algebra.NaturalUncup + +namespace OAI + +namespace PolynomialVacuumAlgebra +open Classical + +abbrev NatSpectralTensor := (ℕ → ℂ) → SpinTensor ℕ ℂ + +def LowerExchange (ψ : NatSpectralTensor) (n : ℕ) : Prop := + ∀ j, j+1 < n → ∀ X, + siteR j (X j) (X (j+1)) (ψ X)=exchangeDenominator (X j) (X (j+1)) • ψ (swapSite j X) + +noncomputable def naturalPrescription (ψ : NatSpectralTensor) (n i : ℕ) + (X : ℕ → ℂ) : SpinTensor ℕ ℂ := + ((1+T)*X i*leftFusion i X) • + (braidTrain (T*X i) X (i+1) (n-i)*cupLinear i) (ψ (skipOne i X)) + +theorem naturalPrescription_swap_before {ψ : NatSpectralTensor} {n i j : ℕ} + (hi : i ≤ n) (hji : j+1 < i) (hψ : LowerExchange ψ n) (X : ℕ → ℂ) : + siteR j (X j) (X (j+1)) (naturalPrescription ψ n i X)= + exchangeDenominator (X j) (X (j+1)) • naturalPrescription ψ n i (swapSite j X) := by + have ht : braidTrain (T*X i) (swapSite j X) (i+1) (n-i)= + braidTrain (T*X i) X (i+1) (n-i) := by + apply braidTrain_congr + intro k hk hk' + exact swapSite_other (by omega) (by omega) X + have he := hψ j (by omega) (skipOne i X) + have hj0 : skipOne i X j=X j := by simp [skipOne,show j < i by omega] + have hj1 : skipOne i X (j+1)=X (j+1) := by simp [skipOne,hji] + rw [hj0,hj1] at he + simp only [naturalPrescription,swapSite_other (by omega : i≠j) (by omega : i≠j+1), + leftFusion_swap_before hji,skipOne_swap_before hji,ht,map_smul] + have ho : siteR j (X j) (X (j+1)) * + (braidTrain (T*X i) X (i+1) (n-i)*cupLinear i) = + (braidTrain (T*X i) X (i+1) (n-i)*cupLinear i)*siteR j (X j) (X (j+1)) := by + rw [← mul_assoc,braidTrain_far_left _ _ j (i+1) (n-i) (by omega), + mul_assoc,siteR_cup_before hji,← mul_assoc] + rw [← Module.End.mul_apply,ho,Module.End.mul_apply,he] + simp only [map_smul,smul_smul] + congr 1 + ring + +theorem naturalPrescription_swap_after {ψ : NatSpectralTensor} {n i j : ℕ} + (hij : i < j) (hj : j < n) (hψ : LowerExchange ψ n) (X : ℕ → ℂ) : + siteR j (X j) (X (j+1)) (naturalPrescription ψ n i X)= + exchangeDenominator (X j) (X (j+1)) • naturalPrescription ψ n i (swapSite j X) := by + have he := hψ (j-1) (by omega) (skipOne i X) + have hj0 : skipOne i X (j-1)=X j := by simp [skipOne,show ¬j-1 < i by omega,show j-1+1=j by omega] + have hj1 : skipOne i X (j-1+1)=X (j+1) := by simp [skipOne,show ¬j-1+1 < i by omega,show j-1+1+1=j+1 by omega] + rw [hj0,hj1] at he + have ht := braidTrain_spectator_swap (T*X i) X (i+1) (j-i-1) (n-j-1) + have hp : i+1+(j-i-1)=j := by omega + have hlen : (j-i-1)+(n-j-1+2)=n-i := by omega + rw [hp,hlen] at ht + simp only [naturalPrescription,swapSite_other (by omega : i≠j) (by omega : i≠j+1), + leftFusion_swap_after hij,skipOne_swap_after hij,map_smul] + have ho : siteR j (X j) (X (j+1)) * + (braidTrain (T*X i) X (i+1) (n-i)*cupLinear i) = + (braidTrain (T*X i) (swapSite j X) (i+1) (n-i)*cupLinear i)*siteR (j-1) (X j) (X (j+1)) := by + rw [← mul_assoc,ht,mul_assoc,siteR_cup_after (by omega : i+2 ≤ j+1), + show j+1-2=j-1 by omega,← mul_assoc] + rw [← Module.End.mul_apply,ho,Module.End.mul_apply,he] + simp only [map_smul,smul_smul] + congr 1 + ring + +theorem naturalPrescription_mark_right {ψ : NatSpectralTensor} {n i : ℕ} + (hi : i < n) (X : ℕ → ℂ) : + siteR i (X i) (X (i+1)) (naturalPrescription ψ n i X)= + exchangeDenominator (X i) (X (i+1)) • naturalPrescription ψ n (i+1) (swapSite i X) := by + have hlen : n-i=(n-(i+1))+1 := by omega + have ht : braidTrain (T*X i) (swapSite i X) (i+1+1) (n-(i+1))= + braidTrain (T*X i) X (i+1+1) (n-(i+1)) := by + apply braidTrain_congr + intro k hk hk' + exact swapSite_other (by omega) (by omega) X + have ho : siteR i (X i) (X (i+1)) * + (braidTrain (T*X i) X (i+1) (n-i)*cupLinear i) = + (exchangeDenominator (X i) (X (i+1))*exchangeDenominator (T*X i) (X (i+1))) • + (braidTrain (T*X i) X (i+1+1) (n-(i+1))*cupLinear (i+1)) := by + rw [hlen,braidTrain,← mul_assoc,← mul_assoc, + braidTrain_far_left _ _ i (i+1+1) (n-(i+1)) (by omega),mul_assoc,mul_assoc] + rw [← mul_assoc (siteR i _ _) (siteR (i+1) _ _) (cupLinear i),siteR_cup_slide,mul_smul] + simp only [mul_smul_comm,smul_smul] + simp only [naturalPrescription,swapSite_right,leftFusion_mark_right,skipOne_mark_right, + ht,map_smul] + rw [← Module.End.mul_apply,ho] + simp only [LinearMap.smul_apply,smul_smul,fusionPair_denominator] + congr 1 + ring + +end PolynomialVacuumAlgebra + +end OAI diff --git a/lean/OAI/Combinatorics/PolynomialVacuum/Algebra/NaturalCup.lean b/lean/OAI/Combinatorics/PolynomialVacuum/Algebra/NaturalCup.lean new file mode 100644 index 0000000000000000000000000000000000000000..67370ae0be29a861d88553870bc9bbbbb3bec1ba --- /dev/null +++ b/lean/OAI/Combinatorics/PolynomialVacuum/Algebra/NaturalCup.lean @@ -0,0 +1,118 @@ +import OAI.Combinatorics.PolynomialVacuum.Algebra.BraidTrain +import OAI.Combinatorics.PolynomialVacuum.Algebra.HomogeneousCupSlide + +namespace OAI + +namespace PolynomialVacuumAlgebra +open Classical + +def skipTwo {α : Type*} (i : ℕ) (s : ℕ → α) : ℕ → α := + fun j => s (if j < i then j else j+2) + +def skipOne {α : Type*} (i : ℕ) (s : ℕ → α) : ℕ → α := + fun j => s (if j < i then j else j+1) + +noncomputable def cupLinear (i : ℕ) : Module.End ℂ (SpinTensor ℕ ℂ) where + toFun W s := cup (s i,s (i+1))*W (skipTwo i s) + map_add' W V := by ext s; simp [mul_add] + map_smul' c W := by ext s; simp [mul_left_comm] + +theorem skipTwo_before {i j : ℕ} (h : j+1 < i) (s : ℕ → Spin) (ab : Pair) : + skipTwo i (replacePair s j (j+1) ab)=replacePair (skipTwo i s) j (j+1) ab := by + funext k + simp only [skipTwo,replacePair,Function.update_apply] + split_ifs <;> congr 1 <;> omega + +theorem skipTwo_after {i j : ℕ} (h : i+2 ≤ j) (s : ℕ → Spin) (ab : Pair) : + skipTwo i (replacePair s j (j+1) ab)=replacePair (skipTwo i s) (j-2) (j-1) ab := by + funext k + simp only [skipTwo,replacePair,Function.update_apply] + split_ifs <;> congr 1 <;> omega + +theorem skipTwo_sliding (i : ℕ) (s : ℕ → Spin) (ab cd : Pair) : + skipTwo i (replacePair (replacePair s i (i+1) ab) (i+1) (i+1+1) cd)= + Function.update (skipTwo i s) i cd.2 := by + funext k + simp only [skipTwo,replacePair,Function.update_apply] + split_ifs <;> congr 1 <;> omega + +theorem skipTwo_slide_end (i : ℕ) (s : ℕ → Spin) : + Function.update (skipTwo i s) i (s i)=skipTwo (i+1) s := by + funext k + simp only [skipTwo,Function.update_apply] + split_ifs <;> congr 1 <;> omega + +theorem siteR_cup_before {i j : ℕ} (h : j+1 < i) (x y : ℂ) : + siteR j x y*cupLinear i=cupLinear i*siteR j x y := by + ext W s + simp only [siteR,pairLinear,cupLinear,Module.End.mul_apply,LinearMap.coe_mk, + AddHom.coe_mk,pairAction] + simp only [replacePair_other s (by omega : i≠j) (by omega : i≠j+1), + replacePair_other s (by omega : i+1≠j) (by omega : i+1≠j+1), + skipTwo_before h,Finset.mul_sum] + apply Finset.sum_congr rfl + intro ab _ + have hs1 : skipTwo i s j=s j := by simp [skipTwo,show j < i by omega] + have hs2 : skipTwo i s (j+1)=s (j+1) := by simp [skipTwo,h] + rw [hs1,hs2] + ring + +theorem siteR_cup_after {i j : ℕ} (h : i+2 ≤ j) (x y : ℂ) : + siteR j x y*cupLinear i=cupLinear i*siteR (j-2) x y := by + ext W s + simp only [siteR,pairLinear,cupLinear,Module.End.mul_apply,LinearMap.coe_mk, + AddHom.coe_mk,pairAction] + simp only [replacePair_other s (by omega : i≠j) (by omega : i≠j+1), + replacePair_other s (by omega : i+1≠j) (by omega : i+1≠j+1), + skipTwo_after h,Finset.mul_sum] + have hp : j-2+1=j-1 := by omega + rw [hp] + apply Finset.sum_congr rfl + intro ab _ + have hs1 : skipTwo i s (j-2)=s j := by simp [skipTwo,show ¬j-2 < i by omega,show j-2+2=j by omega] + have hs2 : skipTwo i s (j-1)=s (j+1) := by simp [skipTwo,show ¬j-1 < i by omega,show j-1+2=j+1 by omega] + rw [hs1,hs2] + ring + +theorem siteR_cup_slide (i : ℕ) (x y : ℂ) : + siteR i x y*siteR (i+1) (T*x) y*cupLinear i = + (exchangeDenominator x y*exchangeDenominator (T*x) y) • cupLinear (i+1) := by + ext W s + simp only [siteR,pairLinear,cupLinear,Module.End.mul_apply,LinearMap.coe_mk, + AddHom.coe_mk,pairAction,LinearMap.smul_apply] + simp only [replacePair_right, + replacePair_other s (by omega : i+1+1≠i) (by omega : i+1+1≠i+1)] + have hl (ab cd : Pair) : replacePair (replacePair s i (i+1) ab) (i+1) (i+1+1) cd i=ab.1 := by + rw [replacePair_other _ (by omega) (by omega),replacePair_left _ (by omega)] + simp only [hl,skipTwo_sliding,Finset.mul_sum,Fintype.sum_prod_type] + have hr (ab cd : Pair) : replacePair (replacePair s i (i+1) ab) (i+1) (i+1+1) cd (i+1)=cd.1 := + replacePair_left _ (by omega) _ + + simp only [hr] + let w : Spin → ℂ := fun h => W (Function.update (skipTwo i s) i h) + have hh : (∑ a : Spin, ∑ b : Spin, ∑ c : Spin, ∑ h : Spin, + exchangeNumerator x y (s i,s (i+1)) (a,b)* + (exchangeNumerator (T*x) y (b,s (i+1+1)) (c,h)*(cup (a,c)*w h))) = + ∑ h : Spin, homogeneousCupLeft x y (s i) (s (i+1)) (s (i+1+1)) h*w h := by + simp only [homogeneousCupLeft,Finset.sum_mul] + symm + rw [Finset.sum_comm] + apply Finset.sum_congr rfl; intro a _ + rw [Finset.sum_comm] + apply Finset.sum_congr rfl; intro b _ + rw [Finset.sum_comm] + apply Finset.sum_congr rfl; intro c _ + apply Finset.sum_congr rfl; intro h _; ring + change (∑ a : Spin, ∑ b : Spin, ∑ c : Spin, ∑ h : Spin, + exchangeNumerator x y (s i,s (i+1)) (a,b)* + (exchangeNumerator (T*x) y (b,s (i+1+1)) (c,h)*(cup (a,c)*w h))) = _ + rw [hh] + simp only [homogeneous_cup_slide,homogeneousCupRight,ite_mul, + mul_ite,zero_mul,mul_zero] + simp only [Finset.sum_ite_eq,Finset.mem_univ,ite_true] + simp only [w,skipTwo_slide_end,Pi.smul_apply,smul_eq_mul] + ring + +end PolynomialVacuumAlgebra + +end OAI diff --git a/lean/OAI/Combinatorics/PolynomialVacuum/Algebra/NaturalMarkLeft.lean b/lean/OAI/Combinatorics/PolynomialVacuum/Algebra/NaturalMarkLeft.lean new file mode 100644 index 0000000000000000000000000000000000000000..e08d5339b3a0eee22c5dbd284eb2d7a6f9547479 --- /dev/null +++ b/lean/OAI/Combinatorics/PolynomialVacuum/Algebra/NaturalMarkLeft.lean @@ -0,0 +1,53 @@ +import OAI.Combinatorics.PolynomialVacuum.Algebra.NaturalCovariance + +namespace OAI + +namespace PolynomialVacuumAlgebra +open Classical + +@[simp] theorem swapSite_swap {α : Type*} (i : ℕ) (X : ℕ → α) : + swapSite i (swapSite i X)=X := by + funext k + simp [swapSite] + +theorem leftFusion_mark_left (i : ℕ) (X : ℕ → ℂ) : + leftFusion (i+1) X=leftFusion i (swapSite i X)*fusionPair (X (i+1)) (X i) := by + simpa only [swapSite_swap,swapSite_left,swapSite_right] using leftFusion_mark_right i (swapSite i X) + +theorem skipOne_mark_left {α : Type*} (i : ℕ) (X : ℕ → α) : + skipOne i (swapSite i X)=skipOne (i+1) X := by + simpa only [swapSite_swap] using (skipOne_mark_right i (swapSite i X)).symm + +theorem naturalPrescription_mark_left {ψ : NatSpectralTensor} {n i : ℕ} + (hi : i < n) (X : ℕ → ℂ) : + siteR i (X i) (X (i+1)) (naturalPrescription ψ n (i+1) X)= + exchangeDenominator (X i) (X (i+1)) • naturalPrescription ψ n i (swapSite i X) := by + have hlen : n-i=(n-(i+1))+1 := by omega + have ht : braidTrain (T*X (i+1)) (swapSite i X) (i+1+1) (n-(i+1))= + braidTrain (T*X (i+1)) X (i+1+1) (n-(i+1)) := by + apply braidTrain_congr + intro k hk hk' + exact swapSite_other (by omega) (by omega) X + let B := braidTrain (T*X (i+1)) X (i+1+1) (n-(i+1)) + have ho : exchangeDenominator (T*X (i+1)) (X i) • + (siteR i (X i) (X (i+1)) * (B*cupLinear (i+1))) = + exchangeDenominator (X i) (X (i+1)) • + (B*siteR (i+1) (T*X (i+1)) (X i)*cupLinear i) := by + rw [← mul_assoc,braidTrain_far_left _ _ i (i+1+1) (n-(i+1)) (by omega),mul_assoc, + ← mul_smul_comm,siteR_cup_unslide,mul_smul_comm,← mul_assoc] + have hv := congrArg (fun A : Module.End ℂ (SpinTensor ℕ ℂ) => A (ψ (skipOne (i+1) X))) ho + simp only [LinearMap.smul_apply,Module.End.mul_apply] at hv + simp only [naturalPrescription,leftFusion_mark_left,swapSite_left,skipOne_mark_left, + hlen,braidTrain,swapSite_right,ht,map_smul,fusionPair_denominator] + change ((1+T)*X (i+1)*(leftFusion i (swapSite i X)*exchangeDenominator (T*X (i+1)) (X i))) • + siteR i (X i) (X (i+1)) ((B*cupLinear (i+1)) (ψ (skipOne (i+1) X))) = _ + rw [← mul_assoc ((1+T)*X (i+1)) _ _,mul_smul] + simp only [Module.End.mul_apply] + rw [hv] + simp only [smul_smul] + congr 1 + ring + +end PolynomialVacuumAlgebra + +end OAI diff --git a/lean/OAI/Combinatorics/PolynomialVacuum/Algebra/NaturalParameters.lean b/lean/OAI/Combinatorics/PolynomialVacuum/Algebra/NaturalParameters.lean new file mode 100644 index 0000000000000000000000000000000000000000..110e29b0934dbd12830609711f0b1c9c45959a20 --- /dev/null +++ b/lean/OAI/Combinatorics/PolynomialVacuum/Algebra/NaturalParameters.lean @@ -0,0 +1,75 @@ +import OAI.Combinatorics.PolynomialVacuum.Algebra.NaturalCup + +namespace OAI + +namespace PolynomialVacuumAlgebra +open Classical + +theorem skipOne_mark_right {α : Type*} (i : ℕ) (X : ℕ → α) : + skipOne (i+1) (swapSite i X)=skipOne i X := by + funext k + simp only [skipOne,swapSite,Function.comp_apply,Equiv.swap_apply_def] + split_ifs <;> congr 1 <;> omega + +theorem skipOne_swap_before {α : Type*} {i j : ℕ} (h : j+1 < i) (X : ℕ → α) : + skipOne i (swapSite j X)=swapSite j (skipOne i X) := by + funext k + simp only [skipOne,swapSite,Function.comp_apply,Equiv.swap_apply_def] + split_ifs <;> congr 1 <;> omega + +theorem skipOne_swap_after {α : Type*} {i j : ℕ} (h : i < j) (X : ℕ → α) : + skipOne i (swapSite j X)=swapSite (j-1) (skipOne i X) := by + funext k + simp only [skipOne,swapSite,Function.comp_apply,Equiv.swap_apply_def] + split_ifs <;> congr 1 <;> omega + +noncomputable def fusionPair (x y : ℂ) : ℂ := (y-t^5*x)*(y-t^6*x) +noncomputable def leftFusion (i : ℕ) (X : ℕ → ℂ) : ℂ := + ∏ k ∈ Finset.range i, fusionPair (X i) (X k) + +theorem fusionPair_denominator (x y : ℂ) : fusionPair x y=exchangeDenominator (T*x) y := by + simp only [fusionPair,exchangeDenominator,T] + ring + +theorem leftFusion_succ (i : ℕ) (X : ℕ → ℂ) : + leftFusion (i+1) X=(∏ k ∈ Finset.range i, fusionPair (X (i+1)) (X k))*fusionPair (X (i+1)) (X i) := by + exact Finset.prod_range_succ _ i + +theorem leftFusion_swap_before {i j : ℕ} (h : j+1 < i) (X : ℕ → ℂ) : + leftFusion i (swapSite j X)=leftFusion i X := by + unfold leftFusion + rw [swapSite_other (by omega : i≠j) (by omega : i≠j+1)] + have hm (k : ℕ) (hk : k ∈ Finset.range i) : Equiv.swap j (j+1) k ∈ Finset.range i := by + simp only [Finset.mem_range] at hk ⊢ + simp only [Equiv.swap_apply_def] + split_ifs <;> omega + apply Finset.prod_bij (fun k _ => Equiv.swap j (j+1) k) hm + · intro a ha b hb hab + exact (Equiv.swap j (j+1)).injective hab + · intro k hk + exact ⟨Equiv.swap j (j+1) k,hm k hk,by simp⟩ + · intro k hk + rfl + +theorem leftFusion_swap_after {i j : ℕ} (h : i < j) (X : ℕ → ℂ) : + leftFusion i (swapSite j X)=leftFusion i X := by + unfold leftFusion + rw [swapSite_other (by omega : i≠j) (by omega : i≠j+1)] + apply Finset.prod_congr rfl + intro k hk + have hk' := Finset.mem_range.mp hk + rw [swapSite_other (by omega : k≠j) (by omega : k≠j+1)] + +theorem leftFusion_mark_right (i : ℕ) (X : ℕ → ℂ) : + leftFusion (i+1) (swapSite i X)=leftFusion i X*fusionPair (X i) (X (i+1)) := by + rw [leftFusion_succ] + simp only [swapSite_right,swapSite_left] + congr 1 + apply Finset.prod_congr rfl + intro k hk + have hk' := Finset.mem_range.mp hk + rw [swapSite_other (by omega : k≠i) (by omega : k≠i+1)] + +end PolynomialVacuumAlgebra + +end OAI

(Q x y).q a b/(p x a.1*p y a.2))≤e) + (hr : ∀ i,i∈base → tv (imageLaw (refresh i)) (p i)≤e) (k : ℕ) (s : I → Ω) : + tv (imageLaw (sampleScan guides base hb pair refresh k s)) + (FiniteChain.kernel (density p) (scanFlow p guides base Q) s)≤ + 2*(1+updateCount guides base)/(2:ℝ)^k+e := by + have ht := WeightedOptions.drawThen_tv_on (scanChoice guides base hb) (localSampler pair refresh s) + k (updateKernel p Q s) e (fun u hu=> + localSampler_tv_on p Q guides base pair refresh e he hpr hr s u (scanChoice_support guides base hb u hu)) + have hl : Variation.bind (fun u=>((scanChoice guides base hb).law u:ℝ)) (updateKernel p Q s)= + FiniteChain.kernel (density p) (scanFlow p guides base Q) s := by + funext t + rw [scanChoice_law,localScan_kernel p hp hs guides hself base Q] + rw [hl,scanChoice_size] at ht + simpa only [Nat.cast_add,Nat.cast_one,sampleScan] using ht + + + +open Finset + +variable {Ω : Type*} [Fintype Ω] [DecidableEq Ω] + +lemma metropolis_normalize (P : SymmetricProposal Ω) (u : Ω → ℝ) (hu : ∀ a,0u x/c) a b=metropolis P u a b := by + have huc : ∀ x,0div_pos (hu x) hc + have hf := WeightedOptions.row_eq_of_off _ _ (metropolis_row P _ huc a) + (metropolis_row P _ hu a) a (fun b hab=>?_) + · exact congrFun hf b + rw [metropolis_acceptance _ _ huc _ _ hab,metropolis_acceptance _ _ hu _ _ hab] + congr 2 + field_simp + +end MatchingFPRAS.Replica + +namespace MatchingFPRAS.Transport.Sparse + +open Finset Replica Variation + +variable {V E : Type*} [Fintype V] [DecidableEq V] [Fintype E] [LinearOrder E] + +variable (ends : E → Sym2 V) + +attribute [local instance] finsetOrder pmOrder + +def rationalWeight (w : E → ℚ) (A : PM (fun e v=>v∈ends e)) : ℚ := ∏ e∈A.val,w e + +omit [DecidableEq V] [Fintype E] [LinearOrder E] in +lemma rationalWeight_pos [DecidableEq V] [Fintype E] [LinearOrder E] + (w : E → ℚ) (hw : ∀ e,0v∈ends e)) : + 0hw e) + +omit [DecidableEq V] [Fintype E] [LinearOrder E] in +lemma rationalWeight_cast [DecidableEq V] [Fintype E] [LinearOrder E] + (w : E → ℚ) (A : PM (fun e v=>v∈ends e)) : + (rationalWeight ends w A:ℝ)=matchingWeight (fun e=>(w e:ℝ)) A := by + simp [rationalWeight,matchingWeight] + +def rationalPairWeight (w z : E → ℚ) (a : PM (fun e v=>v∈ends e) × PM (fun e v=>v∈ends e)) : ℚ := + rationalWeight ends w a.1*rationalWeight ends z a.2 + +lemma rationalPairWeight_pos (w z : E → ℚ) (hw : ∀ e,0v∈ends e) × PM (fun e v=>v∈ends e)) : 0ends f=ends e)).card≤2) + (w z : E → ℚ) (hw : ∀ e,0v∈ends e) × PM (fun e v=>v∈ends e)) := + (pairTable ends hloop hpar a).metropolisChoice (rationalPairWeight ends w z) + (rationalPairWeight_pos ends w z hw hz) a + +theorem pairStepTable_law (hloop : ∀ e,¬(ends e).IsDiag) + (hpar : ∀ e,(univ.filter (fun f=>ends f=ends e)).card≤2) + (w z : E → ℚ) (hw : ∀ e,0v∈ends e) × PM (fun e v=>v∈ends e)) : + ((pairStepTable ends hloop hpar w z hw hz a).law b:ℝ)= + metropolis (pairProposal ends hloop hpar) (pairLaw ends (fun e=>(w e:ℝ)) (fun e=>(z e:ℝ))) a b := by + rw [pairStepTable,WeightedOptions.metropolisChoice_law (pairProposal ends hloop hpar) + (pairTable ends hloop hpar) (pairTable_law ends hloop hpar)] + have hw' : ∀ e,(0:ℝ)by exact_mod_cast hw e + have hz' : ∀ e,(0:ℝ)by exact_mod_cast hz e + let c:=partition (inc:=fun e v=>v∈ends e) (fun e=>(w e:ℝ))* + partition (inc:=fun e v=>v∈ends e) (fun e=>(z e:ℝ)) + have hc : 0(w e:ℝ)) (fun e=>(z e:ℝ))= + (fun x=>(rationalPairWeight ends w z x:ℝ)/c) := by + funext x + simp only [pairLaw,gibbs,rationalPairWeight,Rat.cast_mul,rationalWeight_cast,c] + exact div_mul_div_comm _ _ _ _ + rw [he,metropolis_normalize _ _ (fun x=>by exact_mod_cast rationalPairWeight_pos ends w z hw hz x) c hc] + +theorem pairStepTable_tv (hloop : ∀ e,¬(ends e).IsDiag) + (hpar : ∀ e,(univ.filter (fun f=>ends f=ends e)).card≤2) + (w z : E → ℚ) (hw : ∀ e,0v∈ends e) × PM (fun e v=>v∈ends e)) (k : ℕ) : + tv (imageLaw ((pairStepTable ends hloop hpar w z hw hz a).draw k)) + (metropolis (pairProposal ends hloop hpar) (pairLaw ends (fun e=>(w e:ℝ)) (fun e=>(z e:ℝ))) a) ≤ + 4*(8*a.1.val.card.choose 2+2*a.1.val.card+(a.1.val.card+a.2.val.card)+3)/(2:ℝ)^k := by + have ht := (pairStepTable ends hloop hpar w z hw hz a).draw_tv k + have hl : (fun b=>((pairStepTable ends hloop hpar w z hw hz a).law b:ℝ))= + metropolis (pairProposal ends hloop hpar) (pairLaw ends (fun e=>(w e:ℝ)) (fun e=>(z e:ℝ))) a := + funext (pairStepTable_law ends hloop hpar w z hw hz a) + rw [hl] at ht + apply ht.trans + rw [pairStepTable,WeightedOptions.metropolisChoice_size] + apply div_le_div_of_nonneg_right _ (by positivity) + have hs := pairTable_size ends hloop hpar a + have hs' : ((pairTable ends hloop hpar a).size:ℝ)≤ + 8*a.1.val.card.choose 2+2*a.1.val.card+(a.1.val.card+a.2.val.card)+3 := by exact_mod_cast hs + push_cast + nlinarith + +end MatchingFPRAS.Transport.Sparse + +namespace MatchingFPRAS.FiniteChoice + +lemma choose_pos {r K : ℕ} (p : Fin r → ℚ) (hs : ∑ i,p i=1) + (hK : 0 c * pairingCount (a+k)) + map_zero' := Polynomial.sum_zero_index _ + map_add' p q := Polynomial.sum_add_index p q _ (by simp) (by intros; exact Nat.add_mul ..) + +@[simp] lemma completion_monomial (a k c : ℕ) : + completionSum a (monomial k c)=c*pairingCount (a+k) := by + change (monomial k c : ℕ[X]).sum (fun j d => d * pairingCount (a+j)) = _ + exact Polynomial.sum_monomial_index c _ (Nat.zero_mul _) + +noncomputable def interfacePolynomial (s : ℕ) (F : Fin (s+1) → ℕ) : ℕ[X] := + ∑ l : Fin (s+1), monomial (s-l.val) (s.choose l.val * F l) + +variable {I : Type*} [Fintype I] [DecidableEq I] + +noncomputable def convolution (s : I → ℕ) (F : ∀ i, Fin (s i+1) → ℕ) : ℕ[X] := + ∏ i, interfacePolynomial (s i) (F i) + +omit [Fintype I] in +lemma prod_monomials (t : Finset I) (n c : I → ℕ) : + (∏ i ∈ t, monomial (n i) (c i) : ℕ[X]) = monomial (∑ i ∈ t,n i) (∏ i ∈ t,c i) := by + induction t using Finset.induction_on with + | empty => simp + | @insert i t hi ih => simp [hi,ih,Polynomial.monomial_mul_monomial] + +theorem convolution_recurrence (s : I → ℕ) (F : ∀ i, Fin (s i+1) → ℕ) (u k : ℕ) : + completionSum (u+k) (convolution s F) = + ∑ l : ∀ i, Fin (s i+1), + pairingCount (u+k+(∑ i, (s i - (l i).val))) * (∏ i, ((s i).choose (l i).val * F i (l i))) := by + classical + unfold convolution interfacePolynomial + rw [Fintype.prod_sum,map_sum] + apply Finset.sum_congr rfl + intro l hl + rw [prod_monomials,completion_monomial,Nat.mul_comm] + + + +open Finset Polynomial + +lemma interface_natDegree (s : ℕ) (F : Fin (s+1) → ℕ) : + (interfacePolynomial s F).natDegree ≤ s := by + apply Polynomial.natDegree_sum_le_of_forall_le + intro l hl + exact (Polynomial.natDegree_monomial_le _).trans (Nat.sub_le _ _) + +variable {I : Type*} [Fintype I] [DecidableEq I] + +omit [DecidableEq I] in +lemma convolution_natDegree (s : I → ℕ) (F : ∀ i, Fin (s i+1) → ℕ) : + (convolution s F).natDegree ≤ ∑ i,s i := by + apply (Polynomial.natDegree_prod_le _ _).trans + exact Finset.sum_le_sum fun i _ => interface_natDegree (s i) (F i) + +omit [DecidableEq I] in +theorem convolution_finite_evaluation (s : I → ℕ) (F : ∀ i, Fin (s i+1) → ℕ) + (N u k : ℕ) (hN : (∑ i,s i) ≤ N) : + completionSum (u+k) (convolution s F) = + ∑ a ∈ Finset.range (N+1), (convolution s F).coeff a * pairingCount (u+k+a) := by + change (convolution s F).sum (fun a c => c * pairingCount (u+k+a)) = _ + apply Polynomial.sum_eq_of_subset + · simp + · intro a ha + apply Finset.mem_range.mpr + by_contra hn + have hz := Polynomial.coeff_eq_zero_of_natDegree_lt + (lt_of_le_of_lt (convolution_natDegree s F |>.trans hN) (by omega : N exact congrArg (Sigma.mk l) ((p l).involutive x) + no_fixed x h := by + have he : (p x.1).mate x.2=x.2 := eq_of_heq (Sigma.mk.inj_iff.mp h).2 + exact (p x.1).no_fixed x.2 he + +variable {V L : Type*} [Fintype V] [Fintype L] [DecidableEq V] [DecidableEq L] + +structure ColoredPairing (bags : V → Finset L) where + pair : Pairing V + color : V → L + allowed : ∀ x, color x ∈ bags x + same_color : ∀ x, color (pair.mate x)=color x + +omit [Fintype V] [Fintype L] [DecidableEq V] [DecidableEq L] in +@[ext] lemma ColoredPairing.ext {bags : V → Finset L} {p q : ColoredPairing bags} + (hp : p.pair=q.pair) (hc : p.color=q.color) : p=q := by + cases p; cases q; simp_all + +instance (bags : V → Finset L) : Finite (ColoredPairing bags) := + Finite.of_injective (fun p : ColoredPairing bags => (p.pair,p.color)) (by + intro p q h + exact ColoredPairing.ext (congrArg Prod.fst h) (congrArg Prod.snd h)) + +noncomputable instance (bags : V → Finset L) : Fintype (ColoredPairing bags) := Fintype.ofFinite _ + +abbrev Assignment (bags : V → Finset L) := {f : V → L // ∀ x, f x ∈ bags x} + +def ColoredPairing.fiber {bags : V → Finset L} (p : ColoredPairing bags) (l : L) : + Pairing {x : V // p.color x=l} where + mate x := ⟨p.pair.mate x,(p.same_color x).trans x.property⟩ + involutive x := Subtype.ext (p.pair.involutive x) + no_fixed x h := p.pair.no_fixed x (congrArg Subtype.val h) + +def ColoredPairing.glue (bags : V → Finset L) (f : Assignment bags) + (p : ∀ l,Pairing {x : V // f.val x=l}) : ColoredPairing bags where + pair := (Pairing.sigma p).map (Equiv.sigmaFiberEquiv f.val) + color := f.val + allowed := f.property + same_color x := (p (f.val x)).mate ⟨x,rfl⟩ |>.property + +def assignmentPairingEquiv (bags : V → Finset L) : + ColoredPairing bags ≃ Σ f : Assignment bags, ∀ l, Pairing {x : V // f.val x=l} where + toFun p := ⟨⟨p.color,p.allowed⟩,p.fiber⟩ + invFun q := ColoredPairing.glue bags q.1 q.2 + left_inv p := by + apply ColoredPairing.ext + · ext x; rfl + · rfl + right_inv q := by + rcases q with ⟨f,p⟩ + change (⟨f,(ColoredPairing.glue bags f p).fiber⟩ : + Σ f : Assignment bags, ∀ l, Pairing {x : V // f.val x=l}) = ⟨f,p⟩ + apply congrArg (fun q : ∀ l, Pairing {x : V // f.val x=l} => + (⟨f,q⟩ : Σ f : Assignment bags, ∀ l, Pairing {x : V // f.val x=l})) + funext l + ext x + change ((p (f.val x)).mate ⟨x,rfl⟩).val = ((p l).mate x).val + obtain ⟨x,hx⟩ := x + dsimp at hx ⊢ + subst l + rfl + +theorem coloredPairing_card (bags : V → Finset L) : + Fintype.card (ColoredPairing bags) = + ∑ f : Assignment bags, ∏ l : L, pairingCount (Fintype.card {x : V // f.val x=l}) := by + classical + rw [Fintype.card_congr (assignmentPairingEquiv bags),Fintype.card_sigma] + apply Finset.sum_congr rfl + intro f hf + rw [Fintype.card_pi] + apply Finset.prod_congr rfl + intro l hl + exact pairing_card + +end MatchingFPRAS.UnitRefresh + +end OAI diff --git a/lean/OAI/Combinatorics/MatchingCount/Graphs/ArcData.lean b/lean/OAI/Combinatorics/MatchingCount/Graphs/ArcData.lean new file mode 100644 index 0000000000000000000000000000000000000000..a8a5918bcf2c9c845f7b7fae4107441898d3d7d4 --- /dev/null +++ b/lean/OAI/Combinatorics/MatchingCount/Graphs/ArcData.lean @@ -0,0 +1,376 @@ +import Mathlib + +namespace OAI + +namespace MatchingFPRAS.Cells + +open SimpleGraph + +variable {L : Type*} {G : SimpleGraph L} + +lemma exists_walk_on_trace (a : ℕ → L) (n : ℕ) + (ha : ∀ i < n, a i = a (i + 1) ∨ G.Adj (a i) (a (i + 1))) : + ∃ w : G.Walk (a 0) (a n), ∀ v ∈ w.support, ∃ i ≤ n, a i = v := by + induction n with + | zero => + refine ⟨.nil, ?_⟩ + intro v hv + have hv' : v = a 0 := by simpa using hv + exact ⟨0, le_rfl, hv'.symm⟩ + | succ n ih => + obtain ⟨w, hw⟩ := ih (fun i hi => ha i (by omega)) + rcases ha n (by omega) with heq | hadj + · refine ⟨w.copy rfl heq, ?_⟩ + intro v hv + obtain ⟨i, hi, hiv⟩ := hw v (by simpa using hv) + exact ⟨i, by omega, hiv⟩ + · refine ⟨w.concat hadj, ?_⟩ + intro v hv + have hv' : v ∈ w.support ∨ v = a (n + 1) := by simpa using hv + rcases hv' with hv' | hv' + · obtain ⟨i, hi, hiv⟩ := hw v hv' + exact ⟨i, by omega, hiv⟩ + · exact ⟨n + 1, le_rfl, hv'.symm⟩ + +lemma neighbor_return (hG : G.IsAcyclic) (a : ℕ → L) (n : ℕ) (P : L) + (ha : ∀ i < n, a i = a (i + 1) ∨ G.Adj (a i) (a (i + 1))) + (havoid : ∀ i ≤ n, a i ≠ P) (hfirst : G.Adj P (a 0)) + (hlast : G.Adj P (a n)) : a 0 = a n := by + classical + obtain ⟨w, hw⟩ := exists_walk_on_trace a n ha + have hnot : P ∉ w.toPath.val.support := by + intro hP + obtain ⟨i, hi, hiP⟩ := hw P (w.support_toPath_subset_support hP) + exact havoid i hi hiP + have hp : (Walk.cons hfirst w.toPath.val).IsPath := w.toPath.isPath.cons hnot + have hv := hG.eq_snd_of_adj_start hp hlast (Walk.cons hfirst w.toPath.val).end_mem_support + simpa using hv.symm + +structure ArcData (G : SimpleGraph L) (s : ℕ) where + labels : ℕ → L + sets : ℕ → Finset L + left_mem : ∀ i < s, labels i ∈ sets i + right_mem : ∀ i < s, labels i ∈ sets (i + 1) + clique : ∀ i ≤ s, ∀ u ∈ sets i, ∀ v ∈ sets i, u = v ∨ G.Adj u v + +namespace ArcData + +variable {s : ℕ} (A : ArcData G s) + +def Admissible (x y : ℕ) : Prop := ∃ l, l ∈ A.sets x ∧ l ∈ A.sets y + +def Good (x y : ℕ) : Prop := y = x + 1 ∨ A.Admissible (x + 1) (y - 1) + +structure Split (exteriorGood : Prop) where + p₁ : ℕ + p₂ : ℕ + positive : 0 < p₁ + ordered : p₁ < p₂ + inside : p₂ < s + odd₁ : p₁ % 2 = 1 + even₂ : p₂ % 2 = 0 + first : A.Admissible 0 p₁ + middle : A.Admissible p₁ p₂ + third : A.Admissible p₂ s + some_good : (A.Good 0 p₁ ∧ A.Good p₂ s) ∨ (A.Good p₁ p₂ ∧ exteriorGood) + outer_long : 1 < p₁ → 1 < s - p₂ → A.Good p₁ p₂ ∧ exteriorGood + middle_long : 1 < p₂ - p₁ → A.Good 0 p₁ ∧ A.Good p₂ s + +lemma trace (i : ℕ) (hi : i + 1 < s) : + A.labels i = A.labels (i + 1) ∨ G.Adj (A.labels i) (A.labels (i + 1)) := + A.clique (i + 1) (by omega) _ (A.right_mem i (by omega)) _ (A.left_mem (i + 1) hi) + +lemma edge_admissible (i : ℕ) (hi : i < s) : A.Admissible i (i + 1) := + ⟨A.labels i, A.left_mem i hi, A.right_mem i hi⟩ + +lemma last_mem (hs : 0 < s) : A.labels (s - 1) ∈ A.sets s := by + convert A.right_mem (s - 1) (by omega) using 1 + congr 1 + omega + +lemma good_of_same_boundary (x y : ℕ) (hxy : x < y) (hy : y ≤ s) + (heq : A.labels x = A.labels (y - 1)) : A.Good x y := by + right + refine ⟨A.labels x, A.right_mem x (by omega), ?_⟩ + rw [heq] + exact A.left_mem (y - 1) (by omega) + +lemma neighbor_return_between (hG : G.IsAcyclic) (P : L) + (lo hi : ℕ) (hlo : lo ≤ hi) (hhi : hi < s) + (havoid : ∀ i, lo ≤ i → i ≤ hi → A.labels i ≠ P) + (hfirst : G.Adj P (A.labels lo)) (hlast : G.Adj P (A.labels hi)) : + A.labels lo = A.labels hi := by + have hf : G.Adj P ((fun i => A.labels (lo + i)) 0) := by simpa using hfirst + have hl : G.Adj P ((fun i => A.labels (lo + i)) (hi - lo)) := by + simpa only [Nat.add_sub_of_le hlo] using hlast + have h := neighbor_return hG (fun i => A.labels (lo + i)) (hi - lo) P + (fun i hi' => by + have := A.trace (lo + i) (by omega) + simpa only [Nat.add_assoc] using this) + (fun i hi' => havoid (lo + i) (by omega) (by omega)) hf hl + simpa only [Nat.add_zero, Nat.add_sub_of_le hlo] using h + +lemma split_short_middle {exteriorGood : Prop} (hext : exteriorGood) + (p : ℕ) (hp : 0 < p) (hps : p + 1 < s) (hodd : p % 2 = 1) + (hfirst : A.Admissible 0 p) (hthird : A.Admissible (p + 1) s) : + Nonempty (A.Split exteriorGood) := by + refine ⟨⟨p, p + 1, hp, by omega, hps, hodd, by omega, + hfirst, A.edge_admissible p (by omega), hthird, ?_, ?_, ?_⟩⟩ + · exact Or.inr ⟨Or.inl rfl, hext⟩ + · exact fun _ _ => ⟨Or.inl rfl, hext⟩ + · intro h + omega + +lemma split_short_outer (exteriorGood : Prop) (hs : 3 ≤ s) (hsodd : s % 2 = 1) + (heq : A.labels 0 = A.labels (s - 1)) : Nonempty (A.Split exteriorGood) := by + have hg₁ : A.Good 0 1 := Or.inl rfl + have hg₃ : A.Good (s - 1) s := Or.inl (by omega) + have ha₃ : A.Admissible (s - 1) s := + ⟨A.labels (s - 1), A.left_mem (s - 1) (by omega), A.last_mem (by omega)⟩ + have ha₂ : A.Admissible 1 (s - 1) := by + refine ⟨A.labels 0, A.right_mem 0 (by omega), ?_⟩ + rw [heq] + exact A.left_mem (s - 1) (by omega) + refine ⟨⟨1, s - 1, by omega, by omega, by omega, by omega, by omega, + A.edge_admissible 0 (by omega), ha₂, ha₃, Or.inl ⟨hg₁, hg₃⟩, + ?_, fun _ => ⟨hg₁, hg₃⟩⟩⟩ + intro h + omega + +lemma split_good_exterior (hG : G.IsAcyclic) {exteriorGood : Prop} (hext : exteriorGood) + (hs : 3 ≤ s) (hsodd : s % 2 = 1) (P : L) + (hP₀ : P ∈ A.sets 0) (hPₛ : P ∈ A.sets s) : Nonempty (A.Split exteriorGood) := by + classical + by_cases hboundary : A.labels 0 = A.labels (s - 1) + · exact A.split_short_outer exteriorGood hs hsodd hboundary + by_cases hodd : ∃ i, i < s ∧ i % 2 = 1 ∧ A.labels i = P + · obtain ⟨i, his, hi, hiP⟩ := hodd + refine A.split_short_middle hext i (by omega) (by omega) hi ?_ ?_ + · exact ⟨P, hP₀, by simpa only [hiP] using A.left_mem i his⟩ + · exact ⟨P, by simpa only [hiP] using A.right_mem i his, hPₛ⟩ + have heven : ∀ i < s, A.labels i = P → i % 2 = 0 := by + intro i his hiP + have hm := Nat.mod_lt i (by omega : 0 < 2) + by_contra hn + exact hodd ⟨i, his, by omega, hiP⟩ + have hex : ∃ i, i < s ∧ A.labels i = P := by + by_contra hnone + push Not at hnone + have hav : ∀ i, 0 ≤ i → i ≤ s - 1 → A.labels i ≠ P := + fun i _ hi => hnone i (by omega) + have hadj₀ : G.Adj P (A.labels 0) := + (A.clique 0 (by omega) P hP₀ _ (A.left_mem 0 (by omega))).resolve_left + (fun h => hnone 0 (by omega) h.symm) + have hadjₛ : G.Adj P (A.labels (s - 1)) := + (A.clique s le_rfl P hPₛ _ (A.last_mem (by omega))).resolve_left + (fun h => hnone (s - 1) (by omega) h.symm) + exact hboundary (A.neighbor_return_between hG P 0 (s - 1) (by omega) (by omega) + hav hadj₀ hadjₛ) + by_cases hzero : A.labels 0 = P + · let j := Nat.findGreatest (fun i => A.labels i = P) (s - 1) + have hjle : j ≤ s - 1 := Nat.findGreatest_le _ + have hjP : A.labels j = P := Nat.findGreatest_spec (P := fun i => A.labels i = P) (by omega : 0 ≤ s - 1) hzero + have hlast : A.labels (s - 1) ≠ P := fun h => hboundary (hzero.trans h.symm) + have hjlt : j < s - 1 := by + by_contra h + have : j = s - 1 := by omega + exact hlast (this ▸ hjP) + have hjEven : j % 2 = 0 := heven j (by omega) hjP + have hav : ∀ i, j + 1 ≤ i → i ≤ s - 1 → A.labels i ≠ P := by + intro i hi his + exact Nat.findGreatest_is_greatest (P := fun k => A.labels k = P) (by omega : j < i) his + have hPa : P ∈ A.sets (j + 1) := by + simpa only [hjP] using A.right_mem j (by omega) + have hadjFirst : G.Adj P (A.labels (j + 1)) := + (A.clique (j + 1) (by omega) P hPa _ (A.left_mem (j + 1) (by omega))).resolve_left + (fun h => hav (j + 1) le_rfl (by omega) h.symm) + have hadjLast : G.Adj P (A.labels (s - 1)) := + (A.clique s le_rfl P hPₛ _ (A.last_mem (by omega))).resolve_left + (fun h => hlast h.symm) + have hQ := A.neighbor_return_between hG P (j + 1) (s - 1) + (by omega) (by omega) hav hadjFirst hadjLast + refine A.split_short_middle hext (j + 1) (by omega) (by omega) (by omega) + ⟨P, hP₀, hPa⟩ ?_ + refine ⟨A.labels (j + 1), A.right_mem (j + 1) (by omega), ?_⟩ + rw [hQ] + exact A.last_mem (by omega) + · let i := Nat.find hex + have hi : i < s := (Nat.find_spec hex).1 + have hiP : A.labels i = P := (Nat.find_spec hex).2 + have hiPos : 0 < i := by + by_contra h + have hi0 : i = 0 := by omega + exact hzero (hi0 ▸ hiP) + have hiEven : i % 2 = 0 := heven i hi hiP + have hia : i - 1 + 1 = i := by omega + have hav : ∀ k, 0 ≤ k → k ≤ i - 1 → A.labels k ≠ P := by + intro k _ hk hkP + have hkmin := Nat.find_min' hex (show k < s ∧ A.labels k = P from ⟨by omega, hkP⟩) + change i ≤ k at hkmin + omega + have hPi : P ∈ A.sets i := by simpa only [hiP] using A.left_mem i hi + have hprev : A.labels (i - 1) ∈ A.sets i := by + simpa only [hia] using A.right_mem (i - 1) (by omega) + have hadjFirst : G.Adj P (A.labels 0) := + (A.clique 0 (by omega) P hP₀ _ (A.left_mem 0 (by omega))).resolve_left + (fun h => hzero h.symm) + have hadjLast : G.Adj P (A.labels (i - 1)) := + (A.clique i (by omega) P hPi _ hprev).resolve_left + (fun h => hav (i - 1) (by omega) le_rfl h.symm) + have hQ := A.neighbor_return_between hG P 0 (i - 1) (by omega) (by omega) + hav hadjFirst hadjLast + refine A.split_short_middle hext (i - 1) (by omega) (by omega) (by omega) ?_ ?_ + · refine ⟨A.labels 0, A.left_mem 0 (by omega), ?_⟩ + rw [hQ] + exact A.left_mem (i - 1) (by omega) + · rw [hia] + exact ⟨P, hPi, hPₛ⟩ + +lemma split_left_boundary (hG : G.IsAcyclic) (exteriorGood : Prop) + (hs : 3 ≤ s) (hsodd : s % 2 = 1) (P : L) + (hP₀ : P ∈ A.sets 0) (hPₛ : P ∈ A.sets s) (hzero : A.labels 0 = P) : + Nonempty (A.Split exteriorGood) := by + classical + by_cases hlast : A.labels (s - 1) = P + · exact A.split_short_outer exteriorGood hs hsodd (hzero.trans hlast.symm) + let j := Nat.findGreatest (fun i => A.labels i = P) (s - 1) + have hjle : j ≤ s - 1 := Nat.findGreatest_le _ + have hjP : A.labels j = P := + Nat.findGreatest_spec (P := fun i => A.labels i = P) (by omega : 0 ≤ s - 1) hzero + have hjlt : j < s - 1 := by + by_contra h + have : j = s - 1 := by omega + exact hlast (this ▸ hjP) + have hav : ∀ i, j + 1 ≤ i → i ≤ s - 1 → A.labels i ≠ P := by + intro i hi his + exact Nat.findGreatest_is_greatest (P := fun k => A.labels k = P) (by omega : j < i) his + have hPt : P ∈ A.sets (j + 1) := by + simpa only [hjP] using A.right_mem j (by omega) + have hadjFirst : G.Adj P (A.labels (j + 1)) := + (A.clique (j + 1) (by omega) P hPt _ (A.left_mem (j + 1) (by omega))).resolve_left + (fun h => hav (j + 1) le_rfl (by omega) h.symm) + have hadjLast : G.Adj P (A.labels (s - 1)) := + (A.clique s le_rfl P hPₛ _ (A.last_mem (by omega))).resolve_left + (fun h => hlast h.symm) + have hQ := A.neighbor_return_between hG P (j + 1) (s - 1) + (by omega) (by omega) hav hadjFirst hadjLast + by_cases htEven : (j + 1) % 2 = 0 + · have hg₁ : A.Good 0 1 := Or.inl rfl + have hg₃ : A.Good (j + 1) s := A.good_of_same_boundary _ _ (by omega) le_rfl hQ + have ha₂ : A.Admissible 1 (j + 1) := + ⟨P, by simpa only [hzero] using A.right_mem 0 (by omega), hPt⟩ + have ha₃ : A.Admissible (j + 1) s := by + refine ⟨A.labels (j + 1), A.left_mem (j + 1) (by omega), ?_⟩ + rw [hQ] + exact A.last_mem (by omega) + refine ⟨⟨1, j + 1, by omega, by omega, by omega, by omega, htEven, + A.edge_admissible 0 (by omega), ha₂, ha₃, Or.inl ⟨hg₁, hg₃⟩, + ?_, fun _ => ⟨hg₁, hg₃⟩⟩⟩ + intro h + omega + · have htOdd : (j + 1) % 2 = 1 := by omega + have hg₁ : A.Good 0 (j + 1) := by + apply A.good_of_same_boundary _ _ (by omega) (by omega) + simpa only [Nat.add_sub_cancel, hzero] using hjP.symm + have hg₃ : A.Good (s - 1) s := Or.inl (by omega) + have ha₁ : A.Admissible 0 (j + 1) := ⟨P, hP₀, hPt⟩ + have ha₂ : A.Admissible (j + 1) (s - 1) := by + refine ⟨A.labels (j + 1), A.left_mem (j + 1) (by omega), ?_⟩ + rw [hQ] + exact A.left_mem (s - 1) (by omega) + have ha₃ : A.Admissible (s - 1) s := + ⟨A.labels (s - 1), A.left_mem (s - 1) (by omega), A.last_mem (by omega)⟩ + refine ⟨⟨j + 1, s - 1, by omega, by omega, by omega, htOdd, by omega, + ha₁, ha₂, ha₃, Or.inl ⟨hg₁, hg₃⟩, ?_, fun _ => ⟨hg₁, hg₃⟩⟩⟩ + intro _ h + omega + +def reverse : ArcData G s where + labels i := A.labels (s - 1 - i) + sets i := A.sets (s - i) + left_mem i hi := by + have hj : s - 1 - i < s := by omega + have heq : s - 1 - i + 1 = s - i := by omega + simpa only [heq] using A.right_mem (s - 1 - i) hj + right_mem i hi := by + have hj : s - 1 - i < s := by omega + have heq : s - 1 - i = s - (i + 1) := by omega + simpa only [← heq] using A.left_mem (s - 1 - i) hj + clique i hi := A.clique (s - i) (by omega) + +lemma admissible_symm {x y : ℕ} (h : A.Admissible x y) : A.Admissible y x := by + obtain ⟨l, hl₁, hl₂⟩ := h + exact ⟨l, hl₂, hl₁⟩ + +lemma good_reverse {x y : ℕ} (hxy : x < y) (hy : y ≤ s) + (h : A.reverse.Good x y) : A.Good (s - y) (s - x) := by + rcases h with hshort | ⟨l, hl₁, hl₂⟩ + · left + omega + · right + change l ∈ A.sets (s - (x + 1)) at hl₁ + change l ∈ A.sets (s - (y - 1)) at hl₂ + have h₁ : s - (x + 1) = s - x - 1 := by omega + have h₂ : s - (y - 1) = s - y + 1 := by omega + exact ⟨l, by simpa only [h₂] using hl₂, by simpa only [h₁] using hl₁⟩ + +def Split.unreverse {exteriorGood : Prop} (hsodd : s % 2 = 1) + (T : A.reverse.Split exteriorGood) : A.Split exteriorGood := by + have h₁ := T.positive + have h₂ := T.ordered + have h₃ := T.inside + have ho := T.odd₁ + have he := T.even₂ + have ha₁ : A.Admissible 0 (s - T.p₂) := by + have h := A.admissible_symm T.third + simpa only [reverse, Nat.sub_self] using h + have ha₂ : A.Admissible (s - T.p₂) (s - T.p₁) := A.admissible_symm T.middle + have ha₃ : A.Admissible (s - T.p₁) s := by + have h := A.admissible_symm T.first + simpa only [reverse, Nat.sub_zero] using h + have g₁ : A.reverse.Good T.p₂ s → A.Good 0 (s - T.p₂) := by + intro h + simpa only [Nat.sub_self] using A.good_reverse h₃ le_rfl h + have g₂ : A.reverse.Good T.p₁ T.p₂ → A.Good (s - T.p₂) (s - T.p₁) := + A.good_reverse h₂ (by omega) + have g₃ : A.reverse.Good 0 T.p₁ → A.Good (s - T.p₁) s := by + intro h + simpa only [Nat.sub_zero] using A.good_reverse h₁ (by omega) h + refine ⟨s - T.p₂, s - T.p₁, by omega, by omega, by omega, by omega, by omega, + ha₁, ha₂, ha₃, ?_, ?_, ?_⟩ + · rcases T.some_good with ⟨hf, ht⟩ | ⟨hm, hg⟩ + · exact Or.inl ⟨g₁ ht, g₃ hf⟩ + · exact Or.inr ⟨g₂ hm, hg⟩ + · intro hf ht + obtain ⟨hm, hg⟩ := T.outer_long (by omega) (by omega) + exact ⟨g₂ hm, hg⟩ + · intro hm + obtain ⟨hf, ht⟩ := T.middle_long (by omega) + exact ⟨g₁ ht, g₃ hf⟩ + +theorem split (hG : G.IsAcyclic) (exteriorGood : Prop) + (hs : 3 ≤ s) (hsodd : s % 2 = 1) (P : L) + (hP₀ : P ∈ A.sets 0) (hPₛ : P ∈ A.sets s) + (hbad : ¬exteriorGood → A.labels 0 = P ∨ A.labels (s - 1) = P) : + Nonempty (A.Split exteriorGood) := by + classical + by_cases hext : exteriorGood + · exact A.split_good_exterior hG hext hs hsodd P hP₀ hPₛ + rcases hbad hext with hleft | hright + · exact A.split_left_boundary hG exteriorGood hs hsodd P hP₀ hPₛ hleft + · have hP₀' : P ∈ A.reverse.sets 0 := by simpa only [reverse, Nat.sub_zero] using hPₛ + have hPₛ' : P ∈ A.reverse.sets s := by simpa only [reverse, Nat.sub_self] using hP₀ + have hzero : A.reverse.labels 0 = P := by simpa only [reverse, Nat.sub_zero] using hright + obtain ⟨T⟩ := A.reverse.split_left_boundary hG exteriorGood hs hsodd P hP₀' hPₛ' hzero + exact ⟨T.unreverse A hsodd⟩ + +end ArcData + +structure CycleData (G : SimpleGraph L) (m : ℕ) where + labels : ℤ → L + periodic : ∀ i, labels (i + m) = labels i + adjacent : ∀ i, labels (i - 1) = labels i ∨ G.Adj (labels (i - 1)) (labels i) + +end MatchingFPRAS.Cells + +end OAI diff --git a/lean/OAI/Combinatorics/MatchingCount/Graphs/ColoredEdge.lean b/lean/OAI/Combinatorics/MatchingCount/Graphs/ColoredEdge.lean new file mode 100644 index 0000000000000000000000000000000000000000..dc93aa00276dd9627039dcb16c8c2e2a1d84eeea --- /dev/null +++ b/lean/OAI/Combinatorics/MatchingCount/Graphs/ColoredEdge.lean @@ -0,0 +1,500 @@ +import Mathlib + +namespace OAI + +namespace MatchingFPRAS.Transport + +variable {V L : Type*} + +abbrev ColoredEdge (V L : Type*) := {e : Sym2 V × L // ¬ e.1.IsDiag} + +namespace ColoredEdge + +variable (e : ColoredEdge V L) + +def Incident (v : V) : Prop := v ∈ e.val.1 + +def color : L := e.val.2 + +lemma exists_incident : ∃ v, e.Incident v := by + change ∃ v, v ∈ e.val.1 + exact Sym2.inductionOn e.val.1 fun a b => ⟨a, by simp⟩ + +end ColoredEdge + +def Allowed (bags : V → Finset L) (e : ColoredEdge V L) : Prop := + ∀ v, e.Incident v → e.color ∈ bags v + +abbrev BagEdge (bags : V → Finset L) := {e : ColoredEdge V L // Allowed bags e} + +namespace BagEdge + +variable {bags : V → Finset L} + +def Incident (e : BagEdge bags) (v : V) : Prop := e.val.Incident v + +lemma exists_incident (e : BagEdge bags) : ∃ v, e.Incident v := e.val.exists_incident + +end BagEdge + +variable {E : Type*} [DecidableEq V] [DecidableEq E] (inc : E → V → Prop) + +def MatchingOn (M : Finset E) (U : Finset V) : Prop := + (∀ e ∈ M, ∀ v, inc e v → v ∈ U) ∧ + (∀ v ∈ U, ∃! e, e ∈ M ∧ inc e v) + +namespace MatchingOn + +variable {inc} {M P Q : Finset E} {U W : Finset V} + +omit [DecidableEq V] [DecidableEq E] in +lemma unique (hM : MatchingOn inc M U) {v : V} (hv : v ∈ U) + {e f : E} (he : e ∈ M) (hev : inc e v) (hf : f ∈ M) (hfv : inc f v) : e = f := by + obtain ⟨g, _, hg⟩ := hM.2 v hv + exact (hg e ⟨he, hev⟩).trans (hg f ⟨hf, hfv⟩).symm + +omit [DecidableEq V] [DecidableEq E] in +lemma edge_mem_of_incident (hM : MatchingOn inc M U) (hP : MatchingOn inc P W) + (hsub : P ⊆ M) {e : E} (he : e ∈ M) {v : V} (hv : v ∈ W) (hev : inc e v) : e ∈ P := by + obtain ⟨f, ⟨hf, hfv⟩, _⟩ := hP.2 v hv + have eq : e = f := hM.unique (hM.1 e he v hev) he hev (hsub hf) hfv + exact eq ▸ hf + +omit [DecidableEq V] [DecidableEq E] in +lemma disjoint_edges (hM : MatchingOn inc M U) (hP : MatchingOn inc P W) + (hinc : ∀ e, ∃ v, inc e v) (hdis : Disjoint U W) : Disjoint M P := by + apply Finset.disjoint_left.mpr + intro e he hf + obtain ⟨v, hv⟩ := hinc e + exact Finset.disjoint_left.mp hdis (hM.1 e he v hv) (hP.1 e hf v hv) + +lemma union (hM : MatchingOn inc M U) (hP : MatchingOn inc P W) + (hdis : Disjoint U W) : MatchingOn inc (M ∪ P) (U ∪ W) := by + refine ⟨?_, ?_⟩ + · intro e he v hev + rcases Finset.mem_union.mp he with he | he + · exact Finset.mem_union_left _ (hM.1 e he v hev) + · exact Finset.mem_union_right _ (hP.1 e he v hev) + · intro v hv + rcases Finset.mem_union.mp hv with hv | hv + · obtain ⟨e, ⟨he, hev⟩, hu⟩ := hM.2 v hv + refine ⟨e, ⟨Finset.mem_union_left _ he, hev⟩, ?_⟩ + intro f hf + rcases Finset.mem_union.mp hf.1 with hfM | hfP + · exact hu f ⟨hfM, hf.2⟩ + · exact False.elim (Finset.disjoint_left.mp hdis hv (hP.1 f hfP v hf.2)) + · obtain ⟨e, ⟨he, hev⟩, hu⟩ := hP.2 v hv + refine ⟨e, ⟨Finset.mem_union_right _ he, hev⟩, ?_⟩ + intro f hf + rcases Finset.mem_union.mp hf.1 with hfM | hfP + · exact False.elim (Finset.disjoint_left.mp hdis (hM.1 f hfM v hf.2) hv) + · exact hu f ⟨hfP, hf.2⟩ + +lemma sdiff (hM : MatchingOn inc M U) (hP : MatchingOn inc P W) (hsub : P ⊆ M) : + MatchingOn inc (M \ P) (U \ W) := by + refine ⟨?_, ?_⟩ + · intro e he v hev + obtain ⟨heM, heP⟩ := Finset.mem_sdiff.mp he + refine Finset.mem_sdiff.mpr ⟨hM.1 e heM v hev, ?_⟩ + intro hv + exact heP (hM.edge_mem_of_incident hP hsub heM hv hev) + · intro v hv + obtain ⟨hvU, hvW⟩ := Finset.mem_sdiff.mp hv + obtain ⟨e, ⟨he, hev⟩, hu⟩ := hM.2 v hvU + have heP : e ∉ P := fun hp => hvW (hP.1 e hp v hev) + refine ⟨e, ⟨Finset.mem_sdiff.mpr ⟨he, heP⟩, hev⟩, ?_⟩ + intro f hf + exact hu f ⟨(Finset.mem_sdiff.mp hf.1).1, hf.2⟩ + +lemma replace (hM : MatchingOn inc M U) (hP : MatchingOn inc P W) + (hQ : MatchingOn inc Q W) (hsub : P ⊆ M) (hWU : W ⊆ U) : + MatchingOn inc ((M \ P) ∪ Q) U := by + have h := (hM.sdiff hP hsub).union hQ Finset.sdiff_disjoint + simpa only [Finset.sdiff_union_of_subset hWU] using h + +lemma context_disjoint (hM : MatchingOn inc M U) (hP : MatchingOn inc P W) + (hQ : MatchingOn inc Q W) (hsub : P ⊆ M) + (hinc : ∀ e, ∃ v, inc e v) : Disjoint (M \ P) Q := + (hM.sdiff hP hsub).disjoint_edges hQ hinc Finset.sdiff_disjoint + +lemma replace_context (hM : MatchingOn inc M U) (hP : MatchingOn inc P W) + (hQ : MatchingOn inc Q W) (hsub : P ⊆ M) + (hinc : ∀ e, ∃ v, inc e v) : ((M \ P) ∪ Q) \ Q = M \ P := by + have hd := hM.context_disjoint hP hQ hsub hinc + ext e + simp only [Finset.mem_sdiff, Finset.mem_union] + constructor + · rintro ⟨h | h, hn⟩ + · exact h + · exact (hn h).elim + · intro h + exact ⟨Or.inl h, fun he => Finset.disjoint_left.mp hd (Finset.mem_sdiff.mpr h) he⟩ + +end MatchingOn + +lemma union_val_add {F G : Finset E} (h : Disjoint F G) : + (F ∪ G).val = F.val + G.val := by + rw [← Finset.disjUnion_eq_union F G h, Finset.disjUnion_val] + +lemma sdiff_val_add {F G : Finset E} (h : G ⊆ F) : + (F \ G).val + G.val = F.val := by + rw [← union_val_add Finset.sdiff_disjoint, Finset.sdiff_union_of_subset h] + +lemma pattern_interchange {M N P Q : Finset E} {U W : Finset V} + (hM : MatchingOn inc M U) (hN : MatchingOn inc N U) + (hP : MatchingOn inc P W) (hQ : MatchingOn inc Q W) + (hPM : P ⊆ M) (hQN : Q ⊆ N) (hWU : W ⊆ U) + (hinc : ∀ e, ∃ v, inc e v) : + MatchingOn inc ((M \ P) ∪ Q) U ∧ + MatchingOn inc ((N \ Q) ∪ P) U ∧ + ((M \ P) ∪ Q).val + ((N \ Q) ∪ P).val = M.val + N.val := by + refine ⟨hM.replace hP hQ hPM hWU, hN.replace hQ hP hQN hWU, ?_⟩ + rw [union_val_add (hM.context_disjoint hP hQ hPM hinc), + union_val_add (hN.context_disjoint hQ hP hQN hinc)] + calc + _ = ((M \ P).val + P.val) + ((N \ Q).val + Q.val) := by ac_rfl + _ = _ := by rw [sdiff_val_add hPM, sdiff_val_add hQN] + +lemma pattern_interchange_weight {R : Type*} [CommMonoid R] (w : E → R) + {M N P Q : Finset E} {U W : Finset V} + (hM : MatchingOn inc M U) (hN : MatchingOn inc N U) + (hP : MatchingOn inc P W) (hQ : MatchingOn inc Q W) + (hPM : P ⊆ M) (hQN : Q ⊆ N) (hinc : ∀ e, ∃ v, inc e v) : + (∏ e ∈ (M \ P) ∪ Q, w e) * (∏ e ∈ (N \ Q) ∪ P, w e) = + (∏ e ∈ M, w e) * (∏ e ∈ N, w e) := by + rw [Finset.prod_union (hM.context_disjoint hP hQ hPM hinc), + Finset.prod_union (hN.context_disjoint hQ hP hQN hinc)] + calc + _ = ((∏ e ∈ M \ P, w e) * ∏ e ∈ P, w e) * + ((∏ e ∈ N \ Q, w e) * ∏ e ∈ Q, w e) := by ac_rfl + _ = _ := by rw [Finset.prod_sdiff hPM, Finset.prod_sdiff hQN] + +lemma pattern_interchange_inverse {M P Q : Finset E} {U W : Finset V} + (hM : MatchingOn inc M U) (hP : MatchingOn inc P W) (hQ : MatchingOn inc Q W) + (hPM : P ⊆ M) (hinc : ∀ e, ∃ v, inc e v) : + ((((M \ P) ∪ Q) \ Q) ∪ P) = M := by + rw [hM.replace_context hP hQ hPM hinc, Finset.sdiff_union_of_subset hPM] + +def pathPattern (edges : ℕ → E) (lo hi : ℕ) : Finset E := + ((Finset.Ico lo hi).filter (fun i => i % 2 = lo % 2)).image edges + +lemma pathPattern_matching (vertices : ℕ → V) (edges : ℕ → E) (lo hi : ℕ) + (hlohi : lo < hi) (hodd : (hi - lo) % 2 = 1) + (hinj : Set.InjOn vertices (Set.Icc lo hi)) + (hedges : ∀ i, lo ≤ i → i < hi → + ∀ v, inc (edges i) v ↔ v = vertices i ∨ v = vertices (i + 1)) : + MatchingOn inc (pathPattern edges lo hi) ((Finset.Icc lo hi).image vertices) := by + classical + refine ⟨?_, ?_⟩ + · intro e he v hv + obtain ⟨i, hi', rfl⟩ := Finset.mem_image.mp he + obtain ⟨hirange, hiParity⟩ := Finset.mem_filter.mp hi' + obtain ⟨hil, hih⟩ := Finset.mem_Ico.mp hirange + rcases (hedges i hil hih v).mp hv with rfl | rfl + · exact Finset.mem_image.mpr ⟨i, Finset.mem_Icc.mpr ⟨hil, by omega⟩, rfl⟩ + · exact Finset.mem_image.mpr ⟨i + 1, Finset.mem_Icc.mpr ⟨by omega, by omega⟩, rfl⟩ + · intro v hv + obtain ⟨k, hkrange, rfl⟩ := Finset.mem_image.mp hv + obtain ⟨hkl, hkh⟩ := Finset.mem_Icc.mp hkrange + have hex : ∃ i, lo ≤ i ∧ i < hi ∧ i % 2 = lo % 2 ∧ (k = i ∨ k = i + 1) := by + by_cases hk : k % 2 = lo % 2 + · exact ⟨k, hkl, by omega, hk, Or.inl rfl⟩ + · exact ⟨k - 1, by omega, by omega, by omega, Or.inr (by omega)⟩ + obtain ⟨i, hil, hih, hip, hki⟩ := hex + have hem : edges i ∈ pathPattern edges lo hi := + Finset.mem_image.mpr ⟨i, Finset.mem_filter.mpr ⟨Finset.mem_Ico.mpr ⟨hil, hih⟩, hip⟩, rfl⟩ + have hev : inc (edges i) (vertices k) := by + apply (hedges i hil hih _).mpr + exact hki.imp (congrArg vertices) (congrArg vertices) + refine ⟨edges i, ⟨hem, hev⟩, ?_⟩ + intro f hf + obtain ⟨j, hj', rfl⟩ := Finset.mem_image.mp hf.1 + obtain ⟨hjrange, hjp⟩ := Finset.mem_filter.mp hj' + obtain ⟨hjl, hjh⟩ := Finset.mem_Ico.mp hjrange + have hkj : k = j ∨ k = j + 1 := by + rcases (hedges j hjl hjh _).mp hf.2 with h | h + · exact Or.inl (hinj ⟨hkl, hkh⟩ ⟨hjl, by omega⟩ h) + · exact Or.inr (hinj ⟨hkl, hkh⟩ ⟨by omega, by omega⟩ h) + have hji : j = i := by omega + exact congrArg edges hji + +omit [DecidableEq E] in +lemma singleton_matching (e : E) (a b : V) + (he : ∀ v, inc e v ↔ v = a ∨ v = b) : MatchingOn inc {e} {a, b} := by + classical + refine ⟨?_, ?_⟩ + · intro f hf v hv + have hf' : f = e := Finset.mem_singleton.mp hf + subst f + simpa only [Finset.mem_insert, Finset.mem_singleton] using (he v).mp hv + · intro v hv + refine ⟨e, ⟨Finset.mem_singleton_self _, ?_⟩, ?_⟩ + · apply (he v).mpr + simpa only [Finset.mem_insert, Finset.mem_singleton] using hv + · intro f hf + exact Finset.mem_singleton.mp hf.1 + +omit [DecidableEq V] [DecidableEq E] in +lemma empty_matching : MatchingOn inc ∅ ∅ := by simp [MatchingOn] + +lemma closedPattern_matching (vertices : ℕ → V) (edges : ℕ → E) (lo hi : ℕ) + (hlong : lo + 3 ≤ hi) (hodd : (hi - lo) % 2 = 1) + (hinj : Set.InjOn vertices (Set.Icc lo hi)) + (hedges : ∀ i, lo ≤ i → i < hi → + ∀ v, inc (edges i) v ↔ v = vertices i ∨ v = vertices (i + 1)) + (chord : E) (hchord : ∀ v, inc chord v ↔ v = vertices lo ∨ v = vertices hi) : + MatchingOn inc (pathPattern edges (lo + 1) (hi - 1) ∪ {chord}) + ((Finset.Icc lo hi).image vertices) := by + have hT : MatchingOn inc (pathPattern edges (lo + 1) (hi - 1)) + ((Finset.Icc (lo + 1) (hi - 1)).image vertices) := by + apply pathPattern_matching inc vertices edges (lo + 1) (hi - 1) + · omega + · omega + · intro i hi' j hj' heq + simp only [Set.mem_Icc] at hi' hj' + exact hinj ⟨by omega, by omega⟩ ⟨by omega, by omega⟩ heq + · intro i hi' hi'' v + exact hedges i (by omega) (by omega) v + have hc := singleton_matching inc chord (vertices lo) (vertices hi) hchord + have hd : Disjoint ((Finset.Icc (lo + 1) (hi - 1)).image vertices) + {vertices lo, vertices hi} := by + apply Finset.disjoint_left.mpr + intro v hv hw + obtain ⟨i, hi', rfl⟩ := Finset.mem_image.mp hv + have hir := Finset.mem_Icc.mp hi' + rcases Finset.mem_insert.mp hw with h | h + · have heq := hinj ⟨by omega, by omega⟩ ⟨le_rfl, by omega⟩ h + omega + · have heq := hinj ⟨by omega, by omega⟩ ⟨by omega, le_rfl⟩ + (Finset.mem_singleton.mp h) + omega + have hs : ((Finset.Icc (lo + 1) (hi - 1)).image vertices) ∪ + {vertices lo, vertices hi} = (Finset.Icc lo hi).image vertices := by + ext v + simp only [Finset.mem_union, Finset.mem_image, Finset.mem_Icc, + Finset.mem_insert, Finset.mem_singleton] + constructor + · rintro (⟨i, hi', rfl⟩ | h | h) + · exact ⟨i, ⟨by omega, by omega⟩, rfl⟩ + · exact ⟨lo, ⟨le_rfl, by omega⟩, h.symm⟩ + · exact ⟨hi, ⟨by omega, le_rfl⟩, h.symm⟩ + · rintro ⟨i, hi', rfl⟩ + by_cases hl : i = lo + · exact Or.inr (Or.inl (congrArg vertices hl)) + by_cases hh : i = hi + · exact Or.inr (Or.inr (congrArg vertices hh)) + exact Or.inl ⟨i, ⟨by omega, by omega⟩, rfl⟩ + simpa only [hs] using hT.union hc hd + +lemma pathPattern_boundary (edges : ℕ → E) (lo hi : ℕ) + (hlong : lo + 3 ≤ hi) (hodd : (hi - lo) % 2 = 1) : + pathPattern edges lo hi = pathPattern edges (lo + 2) (hi - 2) ∪ + {edges lo, edges (hi - 1)} := by + have hidx : (Finset.Ico lo hi).filter (fun i => i % 2 = lo % 2) = + ((Finset.Ico (lo + 2) (hi - 2)).filter (fun i => i % 2 = (lo + 2) % 2)) ∪ + {lo, hi - 1} := by + ext i + simp only [Finset.mem_filter, Finset.mem_Ico, Finset.mem_union, + Finset.mem_insert, Finset.mem_singleton] + omega + unfold pathPattern + rw [hidx, Finset.image_union] + simp only [Finset.image_insert, Finset.image_singleton] + +lemma repairedThrough_matching (vertices : ℕ → V) (edges : ℕ → E) (lo hi : ℕ) + (hlong : lo + 3 ≤ hi) (hodd : (hi - lo) % 2 = 1) + (hinj : Set.InjOn vertices (Set.Icc lo hi)) + (hedges : ∀ i, lo ≤ i → i < hi → + ∀ v, inc (edges i) v ↔ v = vertices i ∨ v = vertices (i + 1)) + (repair : E) + (hrepair : ∀ v, inc repair v ↔ v = vertices (lo + 1) ∨ v = vertices (hi - 1)) : + MatchingOn inc (pathPattern edges (lo + 2) (hi - 2) ∪ {repair}) + ((Finset.Icc (lo + 1) (hi - 1)).image vertices) := by + have hT : MatchingOn inc (pathPattern edges (lo + 2) (hi - 2)) + ((Finset.Icc (lo + 2) (hi - 2)).image vertices) := by + by_cases h : lo + 2 < hi - 2 + · apply pathPattern_matching inc vertices edges (lo + 2) (hi - 2) h + · omega + · intro i hi' j hj' heq + simp only [Set.mem_Icc] at hi' hj' + exact hinj ⟨by omega, by omega⟩ ⟨by omega, by omega⟩ heq + · intro i hi' hi'' v + exact hedges i (by omega) (by omega) v + · have hl : hi - 2 < lo + 2 := by omega + have he : Finset.Ico (lo + 2) (hi - 2) = ∅ := Finset.Ico_eq_empty_of_le (by omega) + have he' : Finset.Icc (lo + 2) (hi - 2) = ∅ := Finset.Icc_eq_empty_of_lt hl + simpa [pathPattern, he, he'] using (empty_matching (V := V) (E := E) inc) + have hc := singleton_matching inc repair (vertices (lo + 1)) (vertices (hi - 1)) hrepair + have hd : Disjoint ((Finset.Icc (lo + 2) (hi - 2)).image vertices) + {vertices (lo + 1), vertices (hi - 1)} := by + apply Finset.disjoint_left.mpr + intro v hv hw + obtain ⟨i, hi', rfl⟩ := Finset.mem_image.mp hv + have hir := Finset.mem_Icc.mp hi' + rcases Finset.mem_insert.mp hw with h | h + · have heq := hinj ⟨by omega, by omega⟩ ⟨by omega, by omega⟩ h + omega + · have heq := hinj ⟨by omega, by omega⟩ ⟨by omega, by omega⟩ + (Finset.mem_singleton.mp h) + omega + have hs : ((Finset.Icc (lo + 2) (hi - 2)).image vertices) ∪ + {vertices (lo + 1), vertices (hi - 1)} = + (Finset.Icc (lo + 1) (hi - 1)).image vertices := by + ext v + simp only [Finset.mem_union, Finset.mem_image, Finset.mem_Icc, + Finset.mem_insert, Finset.mem_singleton] + constructor + · rintro (⟨i, hi', rfl⟩ | h | h) + · exact ⟨i, ⟨by omega, by omega⟩, rfl⟩ + · exact ⟨lo + 1, ⟨le_rfl, by omega⟩, h.symm⟩ + · exact ⟨hi - 1, ⟨by omega, le_rfl⟩, h.symm⟩ + · rintro ⟨i, hi', rfl⟩ + by_cases hl : i = lo + 1 + · exact Or.inr (Or.inl (congrArg vertices hl)) + by_cases hh : i = hi - 1 + · exact Or.inr (Or.inr (congrArg vertices hh)) + exact Or.inl ⟨i, ⟨by omega, by omega⟩, rfl⟩ + simpa only [hs] using hT.union hc hd + +def overlayLineGraph (S : Finset E) : SimpleGraph E where + Adj e f := e ≠ f ∧ e ∈ S ∧ f ∈ S ∧ ∃ v, inc e v ∧ inc f v + symm := ⟨by + intro e f h + rcases h with ⟨h, he, hf, v, hev, hfv⟩ + exact ⟨h.symm, hf, he, v, hfv, hev⟩⟩ + loopless := ⟨by intro e h; exact h.1 rfl⟩ + +lemma union_eq_of_multiset_union_eq {M N A B : Finset E} + (h : M.val + N.val = A.val + B.val) : M ∪ N = A ∪ B := by + ext e + have he := congrArg (fun s : Multiset E => e ∈ s) h + simpa only [Multiset.mem_add, Finset.mem_val, Finset.mem_union] using (iff_of_eq he) + +omit [DecidableEq V] in +lemma layer_agreement_adj {M N A B : Finset E} {U : Finset V} + (hM : MatchingOn inc M U) (hN : MatchingOn inc N U) + (hA : MatchingOn inc A U) (hB : MatchingOn inc B U) + (hu : M ∪ N = A ∪ B) {e f : E} + (hadj : (overlayLineGraph inc (M ∪ N)).Adj e f) + (he : e ∈ M ↔ e ∈ A) : f ∈ M ↔ f ∈ A := by + obtain ⟨hne, heu, hfu, v, hev, hfv⟩ := hadj + by_cases heM : e ∈ M + · have heA := he.mp heM + have hfM : f ∉ M := fun hf => + hne (hM.unique (hM.1 e heM v hev) heM hev hf hfv) + have hfA : f ∉ A := fun hf => + hne (hA.unique (hA.1 e heA v hev) heA hev hf hfv) + exact iff_of_false hfM hfA + · have heA : e ∉ A := fun h => heM (he.mpr h) + have heN : e ∈ N := (Finset.mem_union.mp heu).resolve_left heM + have heB : e ∈ B := (Finset.mem_union.mp (hu ▸ heu)).resolve_left heA + have hfN : f ∉ N := fun hf => + hne (hN.unique (hN.1 e heN v hev) heN hev hf hfv) + have hfB : f ∉ B := fun hf => + hne (hB.unique (hB.1 e heB v hev) heB hev hf hfv) + exact iff_of_true ((Finset.mem_union.mp hfu).resolve_right hfN) + ((Finset.mem_union.mp (hu ▸ hfu)).resolve_right hfB) + +omit [DecidableEq V] in +lemma layer_agreement_reachable {M N A B : Finset E} {U : Finset V} + (hM : MatchingOn inc M U) (hN : MatchingOn inc N U) + (hA : MatchingOn inc A U) (hB : MatchingOn inc B U) + (hu : M ∪ N = A ∪ B) {e f : E} + (hr : (overlayLineGraph inc (M ∪ N)).Reachable e f) + (he : e ∈ M ↔ e ∈ A) : f ∈ M ↔ f ∈ A := by + have hrel := (SimpleGraph.reachable_iff_reflTransGen _ _).mp hr + clear hr + induction hrel with + | refl => exact he + | tail hpath hadj ih => exact layer_agreement_adj inc hM hN hA hB hu hadj ih + +omit [DecidableEq V] in +lemma pair_reconstruction {M N A B : Finset E} {U : Finset V} + (hM : MatchingOn inc M U) (hN : MatchingOn inc N U) + (hA : MatchingOn inc A U) (hB : MatchingOn inc B U) + (hu : M.val + N.val = A.val + B.val) (anchor : E) + (hbit : anchor ∈ M ↔ anchor ∈ A) + (hout : ∀ e ∈ M ∪ N, ¬ (overlayLineGraph inc (M ∪ N)).Reachable anchor e → + (e ∈ M ↔ e ∈ A)) : M = A ∧ N = B := by + have hset := union_eq_of_multiset_union_eq hu + have hMA : M = A := by + ext e + by_cases hr : (overlayLineGraph inc (M ∪ N)).Reachable anchor e + · exact layer_agreement_reachable inc hM hN hA hB hset hr hbit + · by_cases he : e ∈ M ∪ N + · exact hout e he hr + · have heM : e ∉ M := fun hm => he (Finset.mem_union_left _ hm) + have heA : e ∉ A := fun ha => he (hset.symm ▸ Finset.mem_union_left B ha) + exact iff_of_false heM heA + refine ⟨hMA, Finset.val_injective ?_⟩ + rw [hMA] at hu + exact add_left_cancel hu + +omit [DecidableEq E] in +lemma multiset_product_comparison (w : E → ℝ) (hw : ∀ e, 0 < w e) + (A : ℝ) (hA : 0 ≤ A) (drop add : Multiset E) (hcard : drop.card = add.card) + (hcompare : ∀ e ∈ drop, ∀ f ∈ add, w e ≤ A * w f) : + (drop.map w).prod ≤ A ^ drop.card * (add.map w).prod := by + induction drop using Multiset.induction_on generalizing add with + | empty => + have ha : add = 0 := Multiset.card_eq_zero.mp (by simpa using hcard.symm) + subst add + simp + | @cons e drop ih => + obtain ⟨f, hf⟩ := Multiset.card_pos_iff_exists_mem.mp + (show 0 < add.card by simp only [Multiset.card_cons] at hcard; omega) + obtain ⟨add', rfl⟩ := Multiset.exists_cons_of_mem hf + have hcard' : drop.card = add'.card := by simpa using hcard + have hi := ih add' hcard' (fun a ha b hb => + hcompare a (Multiset.mem_cons_of_mem ha) b (Multiset.mem_cons_of_mem hb)) + have he := hcompare e (Multiset.mem_cons_self _ _) f (Multiset.mem_cons_self _ _) + have hp : 0 ≤ (drop.map w).prod := le_of_lt <| Multiset.prod_pos (by + intro z hz + obtain ⟨a, _, rfl⟩ := Multiset.mem_map.mp hz + exact hw a) + have hb : 0 ≤ A * w f := mul_nonneg hA (le_of_lt (hw f)) + simpa only [Multiset.map_cons, Multiset.prod_cons, Multiset.card_cons, pow_succ, + mul_assoc, mul_left_comm, mul_comm] using mul_le_mul he hi hp hb + +omit [DecidableEq E] in +lemma four_edge_weight_bound (w : E → ℝ) (hw : ∀ e, 0 < w e) + (A : ℝ) (hA : 1 ≤ A) (input output drop add : Multiset E) + (hcons : input + add = output + drop) + (hcard : drop.card = add.card) (hfour : drop.card ≤ 4) + (hcompare : ∀ e ∈ drop, ∀ f ∈ add, w e ≤ A * w f) : + (input.map w).prod ≤ A ^ 4 * (output.map w).prod := by + have hnonneg : 0 ≤ A := by linarith + have hc := multiset_product_comparison w hw A hnonneg drop add hcard hcompare + have ha : 0 < (add.map w).prod := Multiset.prod_pos (by + intro z hz + obtain ⟨e, _, rfl⟩ := Multiset.mem_map.mp hz + exact hw e) + have ho : 0 ≤ (output.map w).prod := le_of_lt <| Multiset.prod_pos (by + intro z hz + obtain ⟨e, _, rfl⟩ := Multiset.mem_map.mp hz + exact hw e) + have hweight := congrArg (fun s : Multiset E => (s.map w).prod) hcons + simp only [Multiset.map_add, Multiset.prod_add] at hweight + have hpow : A ^ drop.card ≤ A ^ 4 := pow_le_pow_right₀ hA hfour + have hc' : (drop.map w).prod ≤ A ^ 4 * (add.map w).prod := + hc.trans (mul_le_mul_of_nonneg_right hpow (le_of_lt ha)) + apply (mul_le_mul_iff_left₀ ha).mp + calc + _ = (output.map w).prod * (drop.map w).prod := hweight + _ ≤ (output.map w).prod * (A ^ 4 * (add.map w).prod) := + mul_le_mul_of_nonneg_left hc' ho + _ = _ := by ring + +structure OddPath where + length : ℕ + positive : 0 < length + odd : length % 2 = 1 + vertex : ℕ → V + edge : ℕ → E + simple : Set.InjOn vertex (Set.Icc 0 length) + incidence : ∀ i, i < length → ∀ v, + inc (edge i) v ↔ v = vertex i ∨ v = vertex (i + 1) + +end MatchingFPRAS.Transport + +end OAI diff --git a/lean/OAI/Combinatorics/MatchingCount/Graphs/CompleteGraph.lean b/lean/OAI/Combinatorics/MatchingCount/Graphs/CompleteGraph.lean new file mode 100644 index 0000000000000000000000000000000000000000..22f7d10be366ce39c18e8573fc8948276f6c954f --- /dev/null +++ b/lean/OAI/Combinatorics/MatchingCount/Graphs/CompleteGraph.lean @@ -0,0 +1,358 @@ +import Mathlib +import OAI.Combinatorics.MatchingCount.Model + +namespace OAI + +namespace MatchingFPRAS + +@[reducible] noncomputable def completeGraph (n : ℕ) : GraphInput where + n := n + edges := by + classical + exact Finset.univ.filter (fun e => e.1 < e.2) + increasing := by + classical + intro e he + exact (Finset.mem_filter.mp he).2 + +noncomputable def rawWeight (G : GraphInput) (x : ℚ) (M : Finset (Fin G.n × Fin G.n)) : ℚ := + ∏ e ∈ M, if e ∈ G.edges then 1 else x + +noncomputable def rawPartition (G : GraphInput) (x : ℚ) : ℚ := + ∑ M ∈ perfectMatchings (completeGraph G.n), rawWeight G x M + + + +lemma graph_edges_subset_complete (G : GraphInput) : G.edges ⊆ (completeGraph G.n).edges := by + classical + intro e he + exact Finset.mem_filter.mpr ⟨Finset.mem_univ _, G.increasing e he⟩ + +lemma mem_perfectMatchings (G : GraphInput) (M) : M ∈ perfectMatchings G ↔ Perfect G M := by + classical + simp only [perfectMatchings, Finset.mem_filter, Finset.mem_powerset] + exact ⟨fun h => h.2, fun h => ⟨h.1,h⟩⟩ + +lemma pm_subset_complete (G : GraphInput) : perfectMatchings G ⊆ perfectMatchings (completeGraph G.n) := by + intro M hM + apply (mem_perfectMatchings _ _).mpr + have h := (mem_perfectMatchings _ _).mp hM + exact ⟨h.1.trans (graph_edges_subset_complete G), h.2⟩ + +lemma rawWeight_nonneg (G : GraphInput) (x : ℚ) (hx : 0 ≤ x) (M) : 0 ≤ rawWeight G x M := by + classical + apply Finset.prod_nonneg + intro e he + split_ifs <;> positivity + +lemma rawWeight_one (G : GraphInput) (x : ℚ) (M) (hM : M ⊆ G.edges) : rawWeight G x M = 1 := by + classical + apply Finset.prod_eq_one + intro e he + simp [hM he] + +lemma rawWeight_bad (G : GraphInput) (x : ℚ) (hx : 0 ≤ x) (hx1 : x ≤ 1) (M) + (hM : ¬ M ⊆ G.edges) : rawWeight G x M ≤ x := by + classical + obtain ⟨e, he, hbad⟩ := Finset.not_subset.mp hM + have hp : (∏ f ∈ M.erase e, if f ∈ G.edges then (1:ℚ) else x) ≤ 1 := by + apply Finset.prod_le_one₀ (fun f _ => by split_ifs <;> positivity) + intro f hf + split_ifs <;> simp_all + change (∏ f ∈ M, if f ∈ G.edges then (1:ℚ) else x) ≤ x + rw [← Finset.mul_prod_erase M _ he, ite_eq_right hbad] + simpa using mul_le_mul_of_nonneg_left hp hx + + + +theorem raw_padding_bound (G : GraphInput) (x : ℚ) (hx : 0 ≤ x) (hx1 : x ≤ 1) : + (Z G : ℚ) ≤ rawPartition G x ∧ + rawPartition G x ≤ (Z G : ℚ) + (Z (completeGraph G.n) : ℚ)*x := by + classical + let full := perfectMatchings (completeGraph G.n) + let good := perfectMatchings G + let indicator : Finset (Fin G.n × Fin G.n) → ℚ := fun M => if M ∈ good then 1 else 0 + have hind : (∑ M ∈ full, indicator M) = (Z G : ℚ) := by + have heq := Finset.sum_subset (f := indicator) (pm_subset_complete G) + (fun M _ hnot => ite_eq_right hnot) + change (∑ M ∈ good, indicator M) = ∑ M ∈ full, indicator M at heq + rw [← heq] + simp [indicator,good,Z] + have hlo (M : Finset (Fin G.n × Fin G.n)) (hMF : M ∈ full) : indicator M ≤ rawWeight G x M := by + by_cases hM : M ∈ good + · have hsub := ((mem_perfectMatchings G M).mp hM).1 + have hi : indicator M = 1 := ite_eq_left hM + rw [hi, rawWeight_one G x M hsub] + · have hi : indicator M = 0 := ite_eq_right hM + rw [hi] + exact rawWeight_nonneg G x hx M + have hup (M : Finset (Fin G.n × Fin G.n)) (hMF : M ∈ full) : rawWeight G x M ≤ indicator M+x := by + by_cases hM : M ∈ good + · have hsub := ((mem_perfectMatchings G M).mp hM).1 + have hi : indicator M = 1 := ite_eq_left hM + rw [hi, rawWeight_one G x M hsub] + linarith + · have hsub : ¬ M ⊆ G.edges := by + intro hh + apply hM + apply (mem_perfectMatchings G M).mpr + exact ⟨hh, ((mem_perfectMatchings (completeGraph G.n) M).mp hMF).2⟩ + have hi : indicator M = 0 := ite_eq_right hM + rw [hi, zero_add] + exact rawWeight_bad G x hx hx1 M hsub + constructor + · rw [← hind] + exact Finset.sum_le_sum hlo + · calc + rawPartition G x ≤ ∑ M ∈ full, (indicator M+x) := Finset.sum_le_sum hup + _ = (Z G : ℚ) + (Z (completeGraph G.n) : ℚ)*x := by + rw [Finset.sum_add_distrib, hind] + simp [Z,full] + + + +theorem perfect_vertex_factor (G : GraphInput) (M : Finset (Fin G.n × Fin G.n)) + (hM : Perfect G M) (s : Fin G.n → ℚ) : + (∏ e ∈ M, s e.1*s e.2) = ∏ v, s v := by + classical + let ends : Fin G.n × Fin G.n → Finset (Fin G.n) := fun e => {e.1,e.2} + have hends (e : Fin G.n × Fin G.n) (v) : v ∈ ends e ↔ e.1=v ∨ e.2=v := by + simp [ends, eq_comm] + have hpair : (M : Set (Fin G.n × Fin G.n)).PairwiseDisjoint ends := by + intro e he f hf hne + apply Finset.disjoint_left.mpr + intro v hv hw + have hve : e ∈ M ∧ (e.1=v ∨ e.2=v) := ⟨he,(hends e v).mp hv⟩ + have hvf : f ∈ M ∧ (f.1=v ∨ f.2=v) := ⟨hf,(hends f v).mp hw⟩ + exact hne ((hM.2 v).unique hve hvf) + have hall : M.biUnion ends = Finset.univ := by + ext v + simp only [Finset.mem_univ, iff_true] + obtain ⟨e,he,_⟩ := hM.2 v + exact Finset.mem_biUnion.mpr ⟨e,he.1,(hends e v).mpr he.2⟩ + calc + (∏ e ∈ M, s e.1*s e.2) = ∏ e ∈ M, ∏ v ∈ ends e, s v := by + apply Finset.prod_congr rfl + intro e he + have hne : e.1 ≠ e.2 := (G.increasing e (hM.1 he)).ne + simp [ends,hne] + _ = ∏ v ∈ M.biUnion ends, s v := (Finset.prod_biUnion hpair).symm + _ = ∏ v, s v := by rw [hall] + + + +noncomputable def weightedPartition (G : GraphInput) (w : Fin G.n × Fin G.n → ℚ) : ℚ := + ∑ M ∈ perfectMatchings G, ∏ e ∈ M, w e + +theorem vertex_scaled_partition (G : GraphInput) (w : Fin G.n × Fin G.n → ℚ) + (s : Fin G.n → ℚ) : + weightedPartition G (fun e => w e*s e.1*s e.2) = + weightedPartition G w * ∏ v, s v := by + classical + unfold weightedPartition + rw [Finset.sum_mul] + apply Finset.sum_congr rfl + intro M hM + have hp : Perfect G M := (Finset.mem_filter.mp hM).2 + calc + (∏ e ∈ M, w e*s e.1*s e.2) = ∏ e ∈ M, w e*(s e.1*s e.2) := by + apply Finset.prod_congr rfl + intro e he + ring + _ = (∏ e ∈ M, w e)*(∏ e ∈ M, s e.1*s e.2) := Finset.prod_mul_distrib + _ = (∏ e ∈ M, w e)*(∏ v, s v) := by rw [perfect_vertex_factor G M hp s] + + + +def NearPerfect (G : GraphInput) (i j : Fin G.n) + (M : Finset (Fin G.n × Fin G.n)) : Prop := + M ⊆ G.edges ∧ (∀ e ∈ M, e.1 ≠ i ∧ e.2 ≠ i ∧ e.1 ≠ j ∧ e.2 ≠ j) ∧ + ∀ v, v ≠ i → v ≠ j → ∃! e, e ∈ M ∧ (e.1=v ∨ e.2=v) + +noncomputable def holePartition (G : GraphInput) (i j : Fin G.n) + (w : Fin G.n × Fin G.n → ℚ) : ℚ := by + classical + exact ∑ M ∈ G.edges.powerset.filter (NearPerfect G i j), ∏ e ∈ M, w e + +noncomputable def holeRatio (G : GraphInput) (i j : Fin G.n) + (w : Fin G.n × Fin G.n → ℚ) : ℚ := + holePartition G i j w / weightedPartition G w + + + +theorem near_vertex_factor (G : GraphInput) (i j : Fin G.n) (hij : i ≠ j) + (M : Finset (Fin G.n × Fin G.n)) (hM : NearPerfect G i j M) (s : Fin G.n → ℚ) : + (∏ e ∈ M, s e.1*s e.2) * (s i*s j) = ∏ v, s v := by + classical + let ends : Fin G.n × Fin G.n → Finset (Fin G.n) := fun e => {e.1,e.2} + have hends (e : Fin G.n × Fin G.n) (v) : v ∈ ends e ↔ e.1=v ∨ e.2=v := by + simp [ends, eq_comm] + have hpair : (M : Set (Fin G.n × Fin G.n)).PairwiseDisjoint ends := by + intro e he f hf hne + apply Finset.disjoint_left.mpr + intro v hv hw + have hve : e ∈ M ∧ (e.1=v ∨ e.2=v) := ⟨he,(hends e v).mp hv⟩ + have hvf : f ∈ M ∧ (f.1=v ∨ f.2=v) := ⟨hf,(hends f v).mp hw⟩ + have hvi : v ≠ i := by + rcases hve.2 with h | h <;> subst v + · exact (hM.2.1 e he).1 + · exact (hM.2.1 e he).2.1 + have hvj : v ≠ j := by + rcases hve.2 with h | h <;> subst v + · exact (hM.2.1 e he).2.2.1 + · exact (hM.2.1 e he).2.2.2 + exact hne ((hM.2.2 v hvi hvj).unique hve hvf) + have hall : M.biUnion ends = (Finset.univ.erase i).erase j := by + ext v + simp only [Finset.mem_biUnion, Finset.mem_erase, Finset.mem_univ, and_true] + constructor + · rintro ⟨e,he,hv⟩ + rcases (hends e v).mp hv with h | h <;> subst v + · exact ⟨(hM.2.1 e he).2.2.1,(hM.2.1 e he).1⟩ + · exact ⟨(hM.2.1 e he).2.2.2,(hM.2.1 e he).2.1⟩ + · rintro ⟨hvj,hvi⟩ + obtain ⟨e,he,_⟩ := hM.2.2 v hvi hvj + exact ⟨e,he.1,(hends e v).mpr he.2⟩ + have hfactor : (∏ e ∈ M, s e.1*s e.2) = ∏ v ∈ (Finset.univ.erase i).erase j, s v := by + calc + (∏ e ∈ M, s e.1*s e.2) = ∏ e ∈ M, ∏ v ∈ ends e, s v := by + apply Finset.prod_congr rfl + intro e he + have hne : e.1 ≠ e.2 := (G.increasing e (hM.1 he)).ne + simp [ends,hne] + _ = ∏ v ∈ M.biUnion ends, s v := (Finset.prod_biUnion hpair).symm + _ = _ := by rw [hall] + rw [hfactor] + calc + (∏ v ∈ (Finset.univ.erase i).erase j, s v)*(s i*s j) = + ((∏ v ∈ (Finset.univ.erase i).erase j, s v)*s j)*s i := by ring + _ = (∏ v ∈ Finset.univ.erase i, s v)*s i := by + rw [Finset.prod_erase_mul _ _ (by simp [hij.symm])] + _ = ∏ v, s v := Finset.prod_erase_mul _ _ (Finset.mem_univ _) + +theorem hole_partition_vertex_scaling (G : GraphInput) (i j : Fin G.n) (hij : i ≠ j) + (w : Fin G.n × Fin G.n → ℚ) (s : Fin G.n → ℚ) : + holePartition G i j (fun e => w e*s e.1*s e.2)*(s i*s j) = + holePartition G i j w * ∏ v, s v := by + classical + unfold holePartition + rw [Finset.sum_mul,Finset.sum_mul] + apply Finset.sum_congr rfl + intro M hM + have hp : NearPerfect G i j M := (Finset.mem_filter.mp hM).2 + calc + (∏ e ∈ M, w e*s e.1*s e.2)*(s i*s j) = + ((∏ e ∈ M, w e)*(∏ e ∈ M, s e.1*s e.2))*(s i*s j) := by + congr 1 + rw [← Finset.prod_mul_distrib] + apply Finset.prod_congr rfl + intro e he + ring + _ = (∏ e ∈ M, w e)*((∏ e ∈ M, s e.1*s e.2)*(s i*s j)) := by ring + _ = (∏ e ∈ M, w e)*(∏ v, s v) := by rw [near_vertex_factor G i j hij M hp s] + + + +theorem hole_ratio_vertex_scaling (G : GraphInput) (i j : Fin G.n) (hij : i ≠ j) + (w : Fin G.n × Fin G.n → ℚ) (s : Fin G.n → ℚ) (hs : ∀ v, 0 < s v) : + holeRatio G i j (fun e => w e*s e.1*s e.2) = + holeRatio G i j w / (s i*s j) := by + classical + have hsij : s i*s j ≠ 0 := mul_ne_zero (hs i).ne' (hs j).ne' + have hsall : (∏ v, s v) ≠ 0 := Finset.prod_ne_zero_iff.mpr (fun v _ => (hs v).ne') + have hp := hole_partition_vertex_scaling G i j hij w s + have hscaled : holePartition G i j (fun e => w e*s e.1*s e.2) = + (holePartition G i j w * ∏ v, s v)/(s i*s j) := (eq_div_iff hsij).mpr hp + unfold holeRatio + rw [hscaled, vertex_scaled_partition] + by_cases hw : weightedPartition G w = 0 + · simp [hw] + · field_simp + +end MatchingFPRAS + +namespace MatchingFPRAS.Counting + +def scheduleAdmissible (n : ℕ) (epsilon : ℚ) (k : ℕ) : Prop := + 1 ≤ k ∧ (n:ℚ)^(n/2)/(1+1/(n:ℚ))^k ≤ epsilon/32 + + + +theorem counting_schedule_exists (n : ℕ) (hn : 2 ≤ n) (epsilon : ℚ) + (he : 0 < epsilon) (he1 : epsilon < 1) : + ∃ K : ℕ, scheduleAdmissible n epsilon K ∧ + (∀ k, scheduleAdmissible n epsilon k → K ≤ k) ∧ + (K:ℝ) ≤ 1+2*n*((n/2:ℕ)*Real.log n+Real.log (32/(epsilon:ℝ))) := by + classical + have hnr : (2:ℝ) ≤ n := by exact_mod_cast hn + have hn0 : (0:ℝ) < n := by linarith + have her : (0:ℝ) < epsilon := by exact_mod_cast he + have he1r : (epsilon:ℝ) < 1 := by exact_mod_cast he1 + let b : ℝ := 1+1/(n:ℝ) + have hb : 1 < b := by + dsimp [b] + have ht : 0 < 1/(n:ℝ) := by positivity + linarith + have hb0 : 0 < b := by linarith + have hlog : 1/(2*(n:ℝ)) ≤ Real.log b := by + have h := Real.one_sub_inv_le_log_of_pos hb0 + have hcalc : 1/(2*(n:ℝ)) ≤ 1-b⁻¹ := by + dsimp [b] + field_simp + nlinarith + exact hcalc.trans h + let L : ℝ := (n/2:ℕ)*Real.log n+Real.log (32/(epsilon:ℝ)) + have hratio : 1 < 32/(epsilon:ℝ) := (lt_div_iff₀ her).mpr (by linarith) + have hL : 0 < L := by + have ha : 0 ≤ (n/2:ℕ)*Real.log (n:ℝ) := mul_nonneg (Nat.cast_nonneg _) (Real.log_nonneg (by linarith)) + have hb := Real.log_pos hratio + dsimp [L] + linarith + let C : ℝ := 2*n*L + have hC : 0 ≤ C := by dsimp [C]; positivity + let k : ℕ := ⌊C⌋₊+1 + have hk1 : 1 ≤ k := by dsimp [k]; omega + have hkt : C < (k:ℝ) := by + dsimp [k] + exact_mod_cast Nat.lt_floor_add_one C + have hku : (k:ℝ) ≤ C+1 := by + dsimp [k] + push_cast + linarith [Nat.floor_le hC] + have hkl : L ≤ (k:ℝ)*Real.log b := by + have hk0 : (0:ℝ) ≤ k := Nat.cast_nonneg _ + have hm := mul_le_mul_of_nonneg_left hlog hk0 + have hsmall : L ≤ (k:ℝ)*(1/(2*(n:ℝ))) := by + rw [mul_one_div] + apply (le_div_iff₀ (by positivity : 0 < 2*(n:ℝ))).mpr + dsimp [C] at hkt + nlinarith + exact hsmall.trans hm + have ha0 : (0:ℝ) < (n:ℝ)^(n/2)/b^k := by positivity + have ht0 : (0:ℝ) < (epsilon:ℝ)/32 := by positivity + have hlogratio : Real.log ((n:ℝ)^(n/2)/b^k) ≤ Real.log ((epsilon:ℝ)/32) := by + rw [Real.log_div (by positivity) (by positivity),Real.log_pow,Real.log_pow] + have hcancel : Real.log ((epsilon:ℝ)/32) = -Real.log (32/(epsilon:ℝ)) := by + rw [Real.log_div (by positivity) (by norm_num),Real.log_div (by norm_num) (by positivity)] + ring + rw [hcancel] + dsimp [L] at hkl + linarith + have hreal : (n:ℝ)^(n/2)/(1+1/(n:ℝ))^k ≤ (epsilon:ℝ)/32 := + (Real.log_le_log_iff ha0 ht0).mp hlogratio + have hrat : (n:ℚ)^(n/2)/(1+1/(n:ℚ))^k ≤ epsilon/32 := by + apply (Rat.cast_le (K := ℝ)).mp + push_cast + exact hreal + have hex : ∃ k, scheduleAdmissible n epsilon k := ⟨k,hk1,hrat⟩ + refine ⟨Nat.find hex, Nat.find_spec hex, ?_, ?_⟩ + · intro j hj + exact Nat.find_min' hex hj + · have hleast : Nat.find hex ≤ k := Nat.find_min' hex ⟨hk1,hrat⟩ + have hlr : (Nat.find hex:ℝ) ≤ k := by exact_mod_cast hleast + change (Nat.find hex:ℝ) ≤ 1+C + linarith + +end MatchingFPRAS.Counting + +end OAI diff --git a/lean/OAI/Combinatorics/MatchingCount/Graphs/Cumulative.lean b/lean/OAI/Combinatorics/MatchingCount/Graphs/Cumulative.lean new file mode 100644 index 0000000000000000000000000000000000000000..6fca7af470f23d7cb90cff533ae902f5eb208ebb --- /dev/null +++ b/lean/OAI/Combinatorics/MatchingCount/Graphs/Cumulative.lean @@ -0,0 +1,407 @@ +import Mathlib +import OAI.Combinatorics.MatchingCount.Sampling.PM + +namespace OAI + +namespace MatchingFPRAS.Transport + +open Finset + +variable {V J : Type*} [Fintype V] [DecidableEq V] [Fintype J] [DecidableEq J] + +variable {bags : V → Finset J} {G : SimpleGraph J} + +noncomputable local instance cumulativeBagEdgeFintype : Fintype (BagEdge bags) := + Fintype.ofFinite _ + +noncomputable local instance cumulativeBagEdgePMDecidableEq : + DecidableEq (PM (BagEdge.Incident (bags := bags))) := Classical.decEq _ + +end MatchingFPRAS.Transport + +namespace MatchingFPRAS.FiniteChoice + +open Finset + +def cumulative {r : ℕ} (p : Fin r → ℚ) (i : ℕ) : ℚ := ∑ j, if j.val < i then p j else 0 + +lemma cumulative_zero {r : ℕ} (p : Fin r → ℚ) : cumulative p 0 = 0 := by simp [cumulative] + +lemma cumulative_total {r : ℕ} (p : Fin r → ℚ) (hs : ∑ j, p j = 1) : cumulative p r = 1 := by + simp only [cumulative,Fin.isLt,ite_true]; exact hs + +lemma options_pos {r : ℕ} (p : Fin r → ℚ) (hs : ∑ j, p j = 1) : 0 < r := by + by_contra h + have hr : r=0 := by omega + subst r + simp at hs + +lemma cumulative_mono {r : ℕ} (p : Fin r → ℚ) (hp : ∀ j, 0 ≤ p j) : Monotone (cumulative p) := by + intro a b hab + apply Finset.sum_le_sum + intro j _ + by_cases ha : j.val [exact hp j; exact le_refl _] + +def candidates {r K : ℕ} (p : Fin r → ℚ) (J : Fin K) : Finset (Fin r) := + Finset.univ.filter (fun i => (J.val:ℚ)/K < cumulative p (i.val+1)) + +lemma candidates_nonempty {r K : ℕ} (p : Fin r → ℚ) (hs : ∑ j, p j = 1) + (hK : 0 < K) (J : Fin K) : (candidates p J).Nonempty := by + have hr := options_pos p hs + refine ⟨⟨r-1,by omega⟩,?_⟩ + simp only [candidates,Finset.mem_filter,Finset.mem_univ,true_and] + have he : r-1+1=r := by omega + rw [he,cumulative_total p hs] + apply (div_lt_one (by exact_mod_cast hK : (0:ℚ) choose p hs hK J=i)).card:ℚ)/K + + + + +def gridInterval (K : ℕ) (a b : ℚ) : Finset ℕ := + (Finset.range K).filter (fun j => a ≤ (j:ℚ)/K ∧ (j:ℚ)/K < b) + +lemma gridInterval_eq (K : ℕ) (hK : 0 < K) (a b : ℚ) (hb : b ≤ 1) : + gridInterval K a b = Finset.Ico ⌈(K:ℚ)*a⌉₊ ⌈(K:ℚ)*b⌉₊ := by + have hKr : (0:ℚ) [exact hp j; exact le_rfl] + +lemma cumulative_le_one {r : ℕ} (p : Fin r → ℚ) (hp : ∀ j, 0 ≤ p j) + (hs : ∑ j, p j = 1) (i : ℕ) (hi : i ≤ r) : cumulative p i ≤ 1 := by + rw [← cumulative_total p hs]; exact cumulative_mono p hp hi + +lemma cumulative_step {r : ℕ} (p : Fin r → ℚ) (i : Fin r) : + cumulative p (i.val+1)-cumulative p i.val = p i := by + unfold cumulative + rw [← Finset.sum_sub_distrib] + have he (j : Fin r) : (if j.val < i.val+1 then p j else 0)-(if j.val < i.val then p j else 0) = + if j=i then p j else 0 := by + by_cases h : j=i + · subst j; simp + · have hn : j.val ≠ i.val := fun hval => h (Fin.ext hval) + by_cases hj : j.val < i.val + · simp [h,hj,show j.val < i.val+1 by omega] + · simp [h,hj,show ¬j.val < i.val+1 by omega] + simp_rw [he] + simp + +lemma choose_upper {r K : ℕ} (p : Fin r → ℚ) (hs : ∑ j, p j = 1) + (hK : 0 < K) (J : Fin K) : + (J.val:ℚ)/K < cumulative p ((choose p hs hK J).val+1) := by + have hm := Finset.min'_mem (candidates p J) (candidates_nonempty p hs hK J) + exact (Finset.mem_filter.mp hm).2 + +lemma choose_le {r K : ℕ} (p : Fin r → ℚ) (hs : ∑ j, p j = 1) + (hK : 0 < K) (J : Fin K) (i : Fin r) + (hi : (J.val:ℚ)/K < cumulative p (i.val+1)) : choose p hs hK J ≤ i := by + exact Finset.min'_le (candidates p J) i (Finset.mem_filter.mpr ⟨Finset.mem_univ _,hi⟩) + +lemma choose_lower {r K : ℕ} (p : Fin r → ℚ) (hs : ∑ j, p j = 1) + (hK : 0 < K) (J : Fin K) : + cumulative p (choose p hs hK J).val ≤ (J.val:ℚ)/K := by + let i := choose p hs hK J + by_cases hi : i.val=0 + · rw [show (choose p hs hK J).val=0 from hi,cumulative_zero] + positivity + · by_contra hh + have hx : (J.val:ℚ)/K < cumulative p i.val := lt_of_not_ge hh + let j : Fin r := ⟨i.val-1,by have := i.isLt; omega⟩ + have he : j.val+1=i.val := by dsimp [j]; omega + have hj : (J.val:ℚ)/K < cumulative p (j.val+1) := by rw [he]; exact hx + have hm := choose_le p hs hK J j hj + have hv : i.val ≤ j.val := hm + dsimp [j] at hv + omega + +lemma choose_eq_iff {r K : ℕ} (p : Fin r → ℚ) (hp : ∀ j, 0 ≤ p j) + (hs : ∑ j, p j = 1) (hK : 0 < K) (J : Fin K) (i : Fin r) : + choose p hs hK J=i ↔ cumulative p i.val ≤ (J.val:ℚ)/K ∧ + (J.val:ℚ)/K < cumulative p (i.val+1) := by + constructor + · intro he + have hl := choose_lower p hs hK J + have hu := choose_upper p hs hK J + rw [he] at hl hu + exact ⟨hl,hu⟩ + · rintro ⟨hl,hu⟩ + apply le_antisymm (choose_le p hs hK J i hu) + by_contra h + have hlt : (choose p hs hK J).val+1 ≤ i.val := by + have hh : choose p hs hK J < i := lt_of_not_ge h + exact hh + have hm := cumulative_mono p hp hlt + have hh := choose_upper p hs hK J + linarith + +lemma outputLaw_grid {r K : ℕ} (p : Fin r → ℚ) (hp : ∀ j, 0 ≤ p j) + (hs : ∑ j, p j = 1) (hK : 0 < K) (i : Fin r) : + outputLaw p hs hK i = ((gridInterval K (cumulative p i.val) (cumulative p (i.val+1))).card:ℚ)/K := by + unfold outputLaw + congr 2 + apply Finset.card_bij (fun J _ => J.val) + · intro J hJ + have he := (Finset.mem_filter.mp hJ).2 + have hc := (choose_eq_iff p hp hs hK J i).mp he + exact Finset.mem_filter.mpr ⟨Finset.mem_range.mpr J.isLt,hc⟩ + · intro J _ J' _ h; exact Fin.ext h + · intro j hj + have hh := Finset.mem_filter.mp hj + let J : Fin K := ⟨j,Finset.mem_range.mp hh.1⟩ + refine ⟨J,Finset.mem_filter.mpr ⟨Finset.mem_univ _,?_⟩,rfl⟩ + exact (choose_eq_iff p hp hs hK J i).mpr hh.2 + +lemma outputLaw_error {r K : ℕ} (p : Fin r → ℚ) (hp : ∀ j, 0 ≤ p j) + (hs : ∑ j, p j = 1) (hK : 0 < K) (i : Fin r) : + |outputLaw p hs hK i-p i| ≤ 2/(K:ℚ) := by + rw [outputLaw_grid p hp hs hK i,← cumulative_step p i] + exact gridInterval_error K hK _ _ (cumulative_nonneg p hp i.val) + (cumulative_mono p hp (by omega)) (cumulative_le_one p hp hs _ (by have := i.isLt; omega)) + + + + +theorem fixed_bit_choice {r : ℕ} (p : Fin r → ℚ) (hp : ∀ i, 0 ≤ p i) + (hs : ∑ i, p i = 1) (k : ℕ) : + (∑ i, |outputLaw p hs (pow_pos (by norm_num : 0 < (2:ℕ)) k) i-p i|)/2 ≤ + 2*r/(2:ℚ)^k := by + have hK : 0 < (2:ℕ)^k := pow_pos (by norm_num) k + have hh := Finset.sum_le_sum (fun i (_ : i ∈ Finset.univ) => outputLaw_error p hp hs hK i) + simp only [Finset.sum_const,Finset.card_fin,nsmul_eq_mul,Nat.cast_pow,Nat.cast_ofNat] at hh + have hr : (0:ℚ) ≤ r := Nat.cast_nonneg r + have hpow : (0:ℚ) < 2^k := pow_pos (by norm_num) k + have hz : 0 ≤ r/(2:ℚ)^k := div_nonneg hr hpow.le + calc + (∑ i, |outputLaw p hs hK i-p i|)/2 ≤ ((r:ℚ)*(2/(2:ℚ)^k))/2 := + div_le_div_of_nonneg_right hh (by norm_num) + _ = (r:ℚ)/(2:ℚ)^k := by ring + _ ≤ 2*r/(2:ℚ)^k := div_le_div_of_nonneg_right (by linarith) hpow.le + + + + +lemma outputLaw_nonneg {r K : ℕ} (p : Fin r → ℚ) (hs : ∑ j, p j = 1) + (hK : 0 < K) (i : Fin r) : 0 ≤ outputLaw p hs hK i := by unfold outputLaw; positivity + +lemma outputLaw_sum {r K : ℕ} (p : Fin r → ℚ) (hs : ∑ j, p j = 1) + (hK : 0 < K) : ∑ i, outputLaw p hs hK i = 1 := by + have hc (i : Fin r) : ((univ.filter (fun J : Fin K => choose p hs hK J=i)).card:ℚ) = + ∑ J : Fin K, if choose p hs hK J=i then (1:ℚ) else 0 := by simp + simp only [outputLaw,hc,← Finset.sum_div] + rw [Finset.sum_comm] + simp only [Finset.sum_ite_eq,Finset.mem_univ,ite_true,Finset.sum_const,Finset.card_fin,nsmul_eq_mul,mul_one] + exact div_self (by exact_mod_cast hK.ne' : (K:ℚ) ≠ 0) + + + + +lemma fixed_bit_l1 {r : ℕ} (p : Fin r → ℚ) (hp : ∀ i, 0 ≤ p i) + (hs : ∑ i, p i = 1) (k : ℕ) : + ∑ i, |outputLaw p hs (pow_pos (by norm_num : 0 < (2:ℕ)) k) i-p i| ≤ 4*r/(2:ℚ)^k := by + have h := fixed_bit_choice p hp hs k + calc + _ = 2 * ((∑ i, |outputLaw p hs (pow_pos (by norm_num : 0 < (2:ℕ)) k) i-p i|) / 2) := by ring + _ ≤ 2 * (2 * (r:ℚ) / 2^k) := mul_le_mul_of_nonneg_left h (by norm_num) + _ = _ := by ring + +end MatchingFPRAS.FiniteChoice + +namespace MatchingFPRAS.BoundedSimulation + +open Finset + +variable {Ω : Type*} [Fintype Ω] [DecidableEq Ω] + +def categoricalStep {r : ℕ} (μ : Ω → ℚ) (p : Ω → Fin r → ℚ) + (next : Ω → Fin r → Ω) (t : Ω) : ℚ := + ∑ s, μ s * ∑ i, if next s i=t then p s i else 0 + +def idealRun {r : ℕ} (μ : Ω → ℚ) (p : ℕ → Ω → Fin r → ℚ) + (next : ℕ → Ω → Fin r → Ω) : ℕ → Ω → ℚ + | 0 => μ + | n+1 => categoricalStep (idealRun μ p next n) (p n) (next n) + +def bitRun {r : ℕ} (μ : Ω → ℚ) (p : ℕ → Ω → Fin r → ℚ) + (hs : ∀ n s, ∑ i, p n s i = 1) (next : ℕ → Ω → Fin r → Ω) (k : ℕ) : ℕ → Ω → ℚ + | 0 => μ + | n+1 => categoricalStep (bitRun μ p hs next k n) + (fun s => MatchingFPRAS.FiniteChoice.outputLaw (p n s) (hs n s) (pow_pos (by norm_num : 0 < (2:ℕ)) k)) (next n) + + + + +omit [Fintype Ω] in +lemma row_nonneg [Fintype Ω] {r : ℕ} (p : Fin r → ℚ) (hp : ∀ i, 0 ≤ p i) + (next : Fin r → Ω) (t) : 0 ≤ ∑ i, if next i=t then p i else 0 := by + apply sum_nonneg; intro i _; split_ifs <;> simp_all + +lemma row_sum {r : ℕ} (p : Fin r → ℚ) (hs : ∑ i, p i = 1) + (next : Fin r → Ω) : (∑ t, ∑ i, if next i=t then p i else 0) = 1 := by + rw [sum_comm]; simp only [sum_ite_eq,mem_univ,ite_true]; exact hs + +lemma step_nonneg {r : ℕ} (μ : Ω → ℚ) (hμ : ∀ s, 0 ≤ μ s) + (p : Ω → Fin r → ℚ) (hp : ∀ s i, 0 ≤ p s i) (next : Ω → Fin r → Ω) (t) : + 0 ≤ categoricalStep μ p next t := + sum_nonneg (fun s _ => mul_nonneg (hμ s) (row_nonneg _ (hp s) _ _)) + +lemma step_sum {r : ℕ} (μ : Ω → ℚ) (hμs : ∑ s, μ s=1) + (p : Ω → Fin r → ℚ) (hs : ∀ s, ∑ i, p s i=1) (next : Ω → Fin r → Ω) : + ∑ t, categoricalStep μ p next t=1 := by + unfold categoricalStep + rw [sum_comm] + simp_rw [← mul_sum,row_sum _ (hs _),mul_one] + exact hμs + +lemma row_l1 {r : ℕ} (p q : Fin r → ℚ) (next : Fin r → Ω) : + ∑ t, |(∑ i, if next i=t then p i else 0)-(∑ i, if next i=t then q i else 0)| ≤ + ∑ i, |p i-q i| := by + calc + _ = ∑ t, |∑ i, if next i=t then p i-q i else 0| := by + apply sum_congr rfl; intro t _; congr 1 + rw [← sum_sub_distrib]; apply sum_congr rfl; intro i _; split_ifs <;> simp + _ ≤ ∑ t, ∑ i, |if next i=t then p i-q i else 0| := + sum_le_sum (fun t _ => abs_sum_le_sum_abs _ _) + _ = _ := by rw [sum_comm]; simp only [apply_ite abs,abs_zero,sum_ite_eq,mem_univ,ite_true] + +lemma step_l1 {r : ℕ} (μ ν : Ω → ℚ) (hν : ∀ s, 0 ≤ ν s) (hνs : ∑ s, ν s=1) + (p q : Ω → Fin r → ℚ) (hp : ∀ s i, 0 ≤ p s i) (hps : ∀ s, ∑ i, p s i=1) + (next : Ω → Fin r → Ω) (ε : ℚ) + (he : ∀ s, ∑ i, |p s i-q s i| ≤ ε) : + ∑ t, |categoricalStep μ p next t-categoricalStep ν q next t| ≤ (∑ s, |μ s-ν s|)+ε := by + let P (s t : Ω) := ∑ i, if next s i=t then p s i else 0 + let Q (s t : Ω) := ∑ i, if next s i=t then q s i else 0 + have hb (s t) : |μ s*P s t-ν s*Q s t| ≤ |μ s-ν s| *P s t+ν s*|P s t-Q s t| := by + have heq : μ s*P s t-ν s*Q s t=(μ s-ν s)*P s t+ν s*(P s t-Q s t) := by ring + rw [heq] + have h := abs_add_le ((μ s-ν s)*P s t) (ν s*(P s t-Q s t)) + have hP0 : 0 ≤ P s t := row_nonneg _ (hp s) (next s) t + simpa only [abs_mul,abs_of_nonneg (hν s),abs_of_nonneg hP0] using h + calc + _ = ∑ t, |∑ s, (μ s*P s t-ν s*Q s t)| := by simp only [categoricalStep,P,Q,sum_sub_distrib] + _ ≤ ∑ t, ∑ s, |μ s*P s t-ν s*Q s t| := sum_le_sum (fun t _ => abs_sum_le_sum_abs _ _) + _ ≤ ∑ t, ∑ s, (|μ s-ν s| *P s t+ν s*|P s t-Q s t|) := sum_le_sum (fun t _ => sum_le_sum (fun s _ => hb s t)) + _ = (∑ s, |μ s-ν s|)+(∑ s, ν s*∑ t, |P s t-Q s t|) := by + rw [sum_comm]; simp only [sum_add_distrib,← mul_sum,P,row_sum _ (hps _),mul_one] + _ ≤ (∑ s, |μ s-ν s|)+(∑ s, ν s*ε) := by + apply add_le_add le_rfl + apply sum_le_sum; intro s _ + exact mul_le_mul_of_nonneg_left ((row_l1 (p s) (q s) (next s)).trans (he s)) (hν s) + _ = _ := by rw [← sum_mul,hνs,one_mul] + +lemma idealRun_prob {r : ℕ} (μ : Ω → ℚ) (hμ : ∀ s, 0 ≤ μ s) (hμs : ∑ s, μ s=1) + (p : ℕ → Ω → Fin r → ℚ) (hp : ∀ n s i, 0 ≤ p n s i) + (hs : ∀ n s, ∑ i, p n s i=1) (next : ℕ → Ω → Fin r → Ω) (n : ℕ) : + (∀ s, 0 ≤ idealRun μ p next n s) ∧ ∑ s, idealRun μ p next n s=1 := by + induction n with + | zero => exact ⟨hμ,hμs⟩ + | succ n ih => exact ⟨step_nonneg _ ih.1 _ (hp n) _, step_sum _ ih.2 _ (hs n) _⟩ + + + + +lemma bitRun_step_l1 {r : ℕ} (μ : Ω → ℚ) (hμ : ∀ s, 0 ≤ μ s) + (hμs : ∑ s, μ s = 1) (p : ℕ → Ω → Fin r → ℚ) + (hp : ∀ n s i, 0 ≤ p n s i) (hs : ∀ n s, ∑ i, p n s i = 1) + (next : ℕ → Ω → Fin r → Ω) (k n : ℕ) : + (∑ s, |bitRun μ p hs next k (n+1) s-idealRun μ p next (n+1) s|) ≤ + (∑ s, |bitRun μ p hs next k n s-idealRun μ p next n s|)+4*r/(2:ℚ)^k := by + have hν := idealRun_prob μ hμ hμs p hp hs next n + exact step_l1 (bitRun μ p hs next k n) (idealRun μ p next n) hν.1 hν.2 + (fun s => MatchingFPRAS.FiniteChoice.outputLaw (p n s) (hs n s) (pow_pos (by norm_num : 0 < (2:ℕ)) k)) + (p n) (fun s i => MatchingFPRAS.FiniteChoice.outputLaw_nonneg _ _ _ _) + (fun s => MatchingFPRAS.FiniteChoice.outputLaw_sum _ _ _) (next n) (4*r/(2:ℚ)^k) + (fun s => MatchingFPRAS.FiniteChoice.fixed_bit_l1 (p n s) (hp n s) (hs n s) k) + + + + +theorem finite_bit_simulation {r : ℕ} (μ : Ω → ℚ) (hμ : ∀ s, 0 ≤ μ s) + (hμs : ∑ s, μ s = 1) (p : ℕ → Ω → Fin r → ℚ) + (hp : ∀ n s i, 0 ≤ p n s i) (hs : ∀ n s, ∑ i, p n s i = 1) + (next : ℕ → Ω → Fin r → Ω) (k n : ℕ) : + (∑ s, |bitRun μ p hs next k n s-idealRun μ p next n s|)/2 ≤ + 2*n*r/(2:ℚ)^k := by + have hmain : ∑ s, |bitRun μ p hs next k n s-idealRun μ p next n s| ≤ + 4*n*r/(2:ℚ)^k := by + induction n with + | zero => simp [bitRun,idealRun] + | succ n ih => + have hh := bitRun_step_l1 μ hμ hμs p hp hs next k n + calc + _ ≤ (∑ s, |bitRun μ p hs next k n s-idealRun μ p next n s|)+4*r/(2:ℚ)^k := hh + _ ≤ 4*n*r/(2:ℚ)^k+4*r/(2:ℚ)^k := add_le_add ih le_rfl + _ = _ := by push_cast; ring + calc + _ ≤ (4*n*r/(2:ℚ)^k)/2 := div_le_div_of_nonneg_right hmain (by norm_num) + _ = _ := by ring + +end MatchingFPRAS.BoundedSimulation + +namespace MatchingFPRAS.FiniteChoice + +open Finset + +def tapeIndex (k : ℕ) : (Fin k → Bool) ≃ Fin (2^k) := + (Equiv.piCongrRight (fun _ : Fin k => finTwoEquiv.symm)).trans finFunctionFinEquiv + +def chooseBits {r : ℕ} (p : Fin r → ℚ) (hs : ∑ i, p i = 1) (k : ℕ) + (bits : Fin k → Bool) : Fin r := + choose p hs (pow_pos (by norm_num : 0 < (2:ℕ)) k) (tapeIndex k bits) + +def tapeLaw {r : ℕ} (p : Fin r → ℚ) (hs : ∑ i, p i = 1) (k : ℕ) (i : Fin r) : ℚ := + ((univ.filter (fun bits : Fin k → Bool => chooseBits p hs k bits=i)).card:ℚ)/(2:ℚ)^k + +end MatchingFPRAS.FiniteChoice + +end OAI diff --git a/lean/OAI/Combinatorics/MatchingCount/Graphs/Cycle.lean b/lean/OAI/Combinatorics/MatchingCount/Graphs/Cycle.lean new file mode 100644 index 0000000000000000000000000000000000000000..78afbacd92e5fd9cdffbcc9716281de17e3f8020 --- /dev/null +++ b/lean/OAI/Combinatorics/MatchingCount/Graphs/Cycle.lean @@ -0,0 +1,420 @@ +import Mathlib +import OAI.Combinatorics.MatchingCount.Sampling.ChosenChord + +namespace OAI + +namespace MatchingFPRAS.Transport.CellDemands +variable {V L : Type*} [Fintype V] [DecidableEq V] [Fintype L] [DecidableEq L] +variable {bags : V → Finset L} +variable {G : SimpleGraph L} +variable (hbags : ∀ v, ∀ a ∈ bags v, ∀ b ∈ bags v, a = b ∨ G.Adj a b) +variable (hG : G.IsAcyclic) +namespace Demand + +variable {hbags hG} (d : Demand hbags hG) + +noncomputable def cycle := d.2.1.cycle + +omit [Fintype L] in +lemma cell : (d.cycle.labelCycle hbags).Cell d.2.2.val.x d.2.2.val.p d.2.2.val.q d.2.2.val.y := + ((d.2.1.cycle.subdivision hbags hG).mem_cellList (List.mem_toFinset.mp d.2.2.property)).2.2 + +omit [Fintype L] in +lemma last_lt : d.2.2.val.y < d.cycle.size := by + have hy := ((d.2.1.cycle.subdivision hbags hG).mem_cellList (List.mem_toFinset.mp d.2.2.property)).2.1 + have hsize := d.cycle.four_le + change d.2.2.val.y ≤ d.cycle.size-1 at hy + omega + +noncomputable def corners : d.cycle.Corners := d.cycle.cellCorners hbags d.cell d.last_lt + +noncomputable def raw (flags : Fin 64) : RawDemand (BagEdge.Incident (bags := bags)) := + d.corners.rawDemand d.1.1 d.1.2 flags + +omit [Fintype L] in +theorem raw_injective (flags : Fin 64) : Function.Injective (fun d : Demand hbags hG => d.raw flags) := by + intro d e h + obtain ⟨p,S,a⟩ := d + obtain ⟨q,T,b⟩ := e + have heq : p = q := by + apply Prod.ext + · exact congrArg RawDemand.first h + · exact congrArg RawDemand.second h + subst q + have hanc : S.cycle.edgeAt 0 = T.cycle.edgeAt 0 := congrArg RawDemand.anchor h + have hST : S = T := S.anchor_recovers hanc + subst T + have hcorn := congrArg RawDemand.corners h + have ha := ((S.cycle.subdivision hbags hG).mem_cellList (List.mem_toFinset.mp a.property)) + have hb := ((S.cycle.subdivision hbags hG).mem_cellList (List.mem_toFinset.mp b.property)) + have hsize := S.cycle.four_le + have hax := ha.2.2.first_pos + have hap := ha.2.2.middle_pos + have haq := ha.2.2.third_pos + have hbx := hb.2.2.first_pos + have hbp := hb.2.2.middle_pos + have hbq := hb.2.2.third_pos + have hidx (i : Fin 4) := congrFun hcorn i + have hpos : 0 < S.cycle.size := by omega + have hinj {i j : ℕ} (hi : i < S.cycle.size) (hj : j < S.cycle.size) + (hh : S.cycle.vertexAt i = S.cycle.vertexAt j) : i = j := + (S.cycle.vertexAt_eq_iff hpos ⟨by omega,by omega⟩ ⟨by omega,by omega⟩).mp hh + have hab : a = b := by + apply Subtype.ext + apply MatchingFPRAS.Cells.CycleData.CellIndex.ext + · apply hinj (by omega) (by omega) + exact hidx 0 + · apply hinj (by omega) (by omega) + exact hidx 1 + · apply hinj (by omega) (by omega) + exact hidx 2 + · apply hinj (by omega) (by omega) + exact hidx 3 + subst b + rfl + +end Demand + +end MatchingFPRAS.Transport.CellDemands + +namespace MatchingFPRAS.Transport + +variable {V E : Type*} [Fintype V] [DecidableEq V] [DecidableEq E] + +variable {inc : E → V → Prop} + +omit [Fintype V] [DecidableEq V] in +lemma OddPath.closed_eq_through_of_short (p : OddPath inc) (chord : E) + (hl : p.length = 1) (he : chord = p.edge 0) : p.closed chord = p.through := by + simp [OddPath.closed,OddPath.through,OddPath.interior,pathPattern,hl,he,Finset.filter_singleton] + +end MatchingFPRAS.Transport + +namespace MatchingFPRAS.Transport.IndexedCycle + +variable {V L : Type*} [Fintype V] [DecidableEq V] [Fintype L] [DecidableEq L] + +variable {bags : V → Finset L} (c : IndexedCycle (BagEdge.Incident (bags := bags))) + +variable {G : SimpleGraph L} + +variable (hbags : ∀ v, ∀ a ∈ bags v, ∀ b ∈ bags v, a = b ∨ G.Adj a b) + +omit [Fintype V] [Fintype L] in +lemma cellShort_chord {x p q y : ℕ} (hc : (c.labelCycle hbags).Cell x p q y) + (hy : y < c.size) (i : Fin 4) (hl : ((c.pathsOfCell hbags hc hy).side i).length = 1) : + (c.pathsOfCell hbags hc hy).chord i = ((c.pathsOfCell hbags hc hy).side i).edge 0 := by + have hxp := hc.first_pos + have hpq := hc.middle_pos + have hqy := hc.third_pos + change (c.cellChords hbags hc hy) i = ((c.cellCorners hbags hc hy).side i).edge 0 + change (c.cellCorners hbags hc hy).length i = 1 at hl + fin_cases i + · simp only [Corners.length,Corners.start,Corners.stop,cellCorners] at hl + have h : p = x+1 := by simp at hl; omega + simpa [cellChords,Corners.side,arc,Corners.start,cellCorners] using c.chord_short hbags x p _ _ hc.first h + · simp only [Corners.length,Corners.start,Corners.stop,cellCorners] at hl + have h : q = p+1 := by simp at hl; omega + simpa [cellChords,Corners.side,arc,Corners.start,cellCorners] using c.chord_short hbags p q _ _ hc.middle h + · simp only [Corners.length,Corners.start,Corners.stop,cellCorners] at hl + have h : y = q+1 := by simp at hl; omega + simpa [cellChords,Corners.side,arc,Corners.start,cellCorners] using c.chord_short hbags q y _ _ hc.third h + · simp only [Corners.length,Corners.start,Corners.stop,cellCorners] at hl + have h : x = 0 ∧ y+1=c.size := by simp at hl; omega + simpa [cellChords,Corners.side,arc,Corners.start,cellCorners] using c.chord_wrap hbags x y _ _ _ h + +omit [Fintype V] [Fintype L] in +lemma cellShort_pattern {x p q y : ℕ} (hc : (c.labelCycle hbags).Cell x p q y) + (hy : y < c.size) (i : Fin 4) (hl : ((c.pathsOfCell hbags hc hy).side i).length = 1) : + ((c.pathsOfCell hbags hc hy).side i).closed ((c.pathsOfCell hbags hc hy).chord i) = + ((c.pathsOfCell hbags hc hy).side i).through := + OddPath.closed_eq_through_of_short _ _ hl (c.cellShort_chord hbags hc hy i hl) + +end MatchingFPRAS.Transport.IndexedCycle + +namespace MatchingFPRAS.Transport.CellDemands + +variable {V L : Type*} [Fintype V] [DecidableEq V] [Fintype L] [DecidableEq L] + +variable {bags : V → Finset L} {G : SimpleGraph L} + +noncomputable local instance : Fintype (BagEdge bags) := Fintype.ofFinite _ + +variable {hbags : ∀ v, ∀ a ∈ bags v, ∀ b ∈ bags v, a = b ∨ G.Adj a b} + +variable {hG : G.IsAcyclic} + +noncomputable instance : Fintype (Demand hbags hG) := Fintype.ofFinite _ + +namespace Demand + +noncomputable def paths (d : Demand hbags hG) := d.cycle.pathsOfCell hbags d.cell d.last_lt + +noncomputable def outside (d : Demand hbags hG) := d.1.1.val \ d.cycle.edgeSet + +end Demand + +abbrev ErrorDemand (hbags : ∀ v, ∀ a ∈ bags v, ∀ b ∈ bags v, a = b ∨ G.Adj a b) + (hG : G.IsAcyclic) := + {e : Bool × Demand hbags hG // ∀ i : Fin 4, CellPaths.sideBit i = e.1 → + (e.2.paths.side i).length ≠ 1} + +noncomputable instance : Fintype (ErrorDemand hbags hG) := Fintype.ofFinite _ + +namespace ErrorDemand + +variable (e : ErrorDemand hbags hG) + +def bit : Bool := e.val.1 + +def demand : Demand hbags hG := e.val.2 + +def X : Fin 4 := if e.bit then 2 else 3 + +def Y : Fin 4 := if e.bit then 0 else 1 + +omit [Fintype L] in +lemma X_bit : CellPaths.sideBit e.X = e.bit := by cases hb : e.bit <;> simp [X,hb,CellPaths.sideBit] + +omit [Fintype L] in +lemma Y_bit : CellPaths.sideBit e.Y = e.bit := by cases hb : e.bit <;> simp [Y,hb,CellPaths.sideBit] + +omit [Fintype L] in +lemma X_ne_Y : e.X ≠ e.Y := by cases hb : e.bit <;> simp [X,Y,hb] + +def flags : Fin 64 := if e.bit then 2 else 1 + +noncomputable def raw := e.demand.raw e.flags + +omit [Fintype L] in +lemma raw_injective : Function.Injective (raw (hbags := hbags) (hG := hG)) := by + intro e f h + have hf : e.flags = f.flags := congrArg RawDemand.flags h + have hb : e.bit = f.bit := by + cases he : e.bit <;> cases hh : f.bit <;> simp_all [flags] + have hd : e.demand = f.demand := by + apply Demand.raw_injective e.flags + simpa only [raw,hf] using h + apply Subtype.ext + exact Prod.ext hb hd + +end ErrorDemand + +variable (height : L → ℝ) (hheight : ∀ l, 0 < height l) + +variable (hstep : ∀ a b, G.Adj a b → height a ≤ 2 * height b) + +variable (D : ℝ) (hD : 1 ≤ D) (w : BagEdge bags → ℝ) + +variable (hw : ∀ e, height e.color / D ≤ w e ∧ w e ≤ 3 * height e.color) + +variable (lo hi : ℝ) (hlo : 0 < lo) (hlohi : lo ≤ hi) + +namespace Demand + +variable (d : Demand hbags hG) + +include hheight hstep hD hw hlo hlohi in +lemma exists_switch : ∃ enc : DemandEncoding BagEdge.Incident (d.raw 0), + enc.first.val = d.outside ∪ d.paths.switched true ∧ + gibbs (fun e => max lo (min hi (w e))) d.1.1 * gibbs (fun e => max lo (min hi (w e))) d.1.2 ≤ + (1000*D)^4 * gibbs (fun e => max lo (min hi (w e))) enc.first * + gibbs (fun e => max lo (min hi (w e))) enc.second := by + obtain ⟨enc,he,hw⟩ := d.cycle.actual_switch_encoding hbags height hheight hstep + d.1.1 d.1.2 d.2.1.cycle_union d.cell d.last_lt 0 true D hD w hw lo hi hlo hlohi + refine ⟨enc,?_,hw⟩ + exact he.trans (congrArg (fun R => R ∪ d.paths.switched true) + (d.corners.embeddedPair_outside d.1.1 d.1.2 d.2.1.cycle_union d.paths.chord d.paths.chord_incidence 0)) + +noncomputable def switchChoice : DemandEncoding BagEdge.Incident (d.raw 0) := + (d.exists_switch height hheight hstep D hD w hw lo hi hlo hlohi).choose + +lemma switchChoice_spec : + (d.switchChoice height hheight hstep D hD w hw lo hi hlo hlohi).first.val = + d.outside ∪ d.paths.switched true ∧ + gibbs (fun e => max lo (min hi (w e))) d.1.1 * gibbs (fun e => max lo (min hi (w e))) d.1.2 ≤ + (1000*D)^4 * gibbs (fun e => max lo (min hi (w e))) + (d.switchChoice height hheight hstep D hD w hw lo hi hlo hlohi).first * + gibbs (fun e => max lo (min hi (w e))) + (d.switchChoice height hheight hstep D hD w hw lo hi hlo hlohi).second := + (d.exists_switch height hheight hstep D hD w hw lo hi hlo hlohi).choose_spec + +lemma switchChoice_injective : Function.Injective (fun d : Demand hbags hG => + (d.switchChoice height hheight hstep D hD w hw lo hi hlo hlohi).finiteCode) := by + intro d e h + exact Demand.raw_injective 0 (DemandEncoding.finiteCode_recovers _ _ h) + +end Demand + +namespace ErrorDemand + +variable (e : ErrorDemand hbags hG) + +include hheight hstep hD hw hlo hlohi in +lemma exists_errors : ∃ enc₀ enc₁ : DemandEncoding BagEdge.Incident e.raw, + enc₀.first.val = e.demand.outside ∪ e.demand.paths.orientation e.bit ∧ + enc₁.first.val = e.demand.outside ∪ e.demand.paths.contextOne e.bit e.Y ∧ + (e.demand.paths.side e.X).closed (e.demand.paths.chord e.X) ⊆ enc₀.second.val ∧ + (e.demand.paths.side e.X).closed (e.demand.paths.chord e.X) ⊆ enc₁.second.val ∧ + gibbs (fun e => max lo (min hi (w e))) e.demand.1.1 * + gibbs (fun e => max lo (min hi (w e))) e.demand.1.2 ≤ + (1000*D)^4 * gibbs (fun e => max lo (min hi (w e))) enc₀.first * + gibbs (fun e => max lo (min hi (w e))) enc₀.second ∧ + gibbs (fun e => max lo (min hi (w e))) e.demand.1.1 * + gibbs (fun e => max lo (min hi (w e))) e.demand.1.2 ≤ + (1000*D)^4 * gibbs (fun e => max lo (min hi (w e))) enc₁.first * + gibbs (fun e => max lo (min hi (w e))) enc₁.second := by + obtain ⟨enc₀,enc₁,h₀,h₁,hr⟩ := e.demand.cycle.actual_error_encodings hbags height hheight hstep + e.demand.1.1 e.demand.1.2 e.demand.2.1.cycle_union e.demand.cell e.demand.last_lt + e.flags e.bit e.X e.Y e.X_bit e.Y_bit e.X_ne_Y e.property D hD w hw lo hi hlo hlohi + refine ⟨enc₀,enc₁,?_,?_,hr⟩ + · exact h₀.trans (congrArg (fun R => R ∪ e.demand.paths.orientation e.bit) + (e.demand.corners.embeddedPair_outside e.demand.1.1 e.demand.1.2 e.demand.2.1.cycle_union + e.demand.paths.chord e.demand.paths.chord_incidence e.flags)) + · exact h₁.trans (congrArg (fun R => R ∪ e.demand.paths.contextOne e.bit e.Y) + (e.demand.corners.embeddedPair_outside e.demand.1.1 e.demand.1.2 e.demand.2.1.cycle_union + e.demand.paths.chord e.demand.paths.chord_incidence e.flags)) + +noncomputable def errorZero : DemandEncoding BagEdge.Incident e.raw := + (e.exists_errors height hheight hstep D hD w hw lo hi hlo hlohi).choose + +noncomputable def errorOne : DemandEncoding BagEdge.Incident e.raw := + (e.exists_errors height hheight hstep D hD w hw lo hi hlo hlohi).choose_spec.choose + +lemma errorZero_injective : Function.Injective (fun e : ErrorDemand hbags hG => + (e.errorZero height hheight hstep D hD w hw lo hi hlo hlohi).finiteCode) := by + intro e f h + exact raw_injective (DemandEncoding.finiteCode_recovers _ _ h) + +lemma errorOne_injective : Function.Injective (fun e : ErrorDemand hbags hG => + (e.errorOne height hheight hstep D hD w hw lo hi hlo hlohi).finiteCode) := by + intro e f h + exact raw_injective (DemandEncoding.finiteCode_recovers _ _ h) + +end ErrorDemand + +end MatchingFPRAS.Transport.CellDemands + +namespace MatchingFPRAS.Transport.OddPath + +variable {V E : Type*} [Fintype V] [DecidableEq V] [DecidableEq E] + +variable {inc : E → V → Prop} (p : OddPath inc) (chord : E) + +variable (hlong : 3 ≤ p.length) + +variable (hc : ∀ v, inc chord v ↔ v = p.vertex 0 ∨ v = p.vertex p.length) + +def closedCycle : IndexedCycle inc where + size := p.length + 1 + four_le := by omega + even := by have := p.odd; omega + vertex i := p.vertex i + simple := by + intro i j h + exact Fin.ext (p.simple ⟨by omega,by omega⟩ ⟨by omega,by omega⟩ h) + edge i := if i.val < p.length then p.edge i else chord + incidence := by + intro i v + by_cases hi : i.val < p.length + · rw [ite_eq_left hi,p.incidence i hi] + have hm : (i.val + 1) % (p.length + 1) = i.val + 1 := Nat.mod_eq_of_lt (by omega) + simp only [hm] + · have hil : i.val = p.length := by omega + rw [ite_eq_right hi,hc] + simp only [hil,Nat.mod_self] + exact or_comm + +omit [Fintype V] [DecidableEq V] [DecidableEq E] in +lemma closedCycle_edgeAt (i : ℕ) (hi : i < p.length) : + (p.closedCycle chord hlong hc).edgeAt i = p.edge i := by + simp only [IndexedCycle.edgeAt,IndexedCycle.index,closedCycle] + rw [Nat.mod_eq_of_lt (by omega),ite_eq_left hi] + +omit [Fintype V] [DecidableEq V] [DecidableEq E] in +lemma closedCycle_chord : + (p.closedCycle chord hlong hc).edgeAt p.length = chord := by + simp [IndexedCycle.edgeAt,IndexedCycle.index,closedCycle,Nat.mod_eq_of_lt (by omega : p.length < p.length+1)] + +omit [Fintype V] [DecidableEq V] in +lemma closedCycle_parity_zero : + (p.closedCycle chord hlong hc).parityPattern 0 = p.through := by + ext e + simp only [IndexedCycle.parityPattern,IndexedCycle.mem_intervalPattern,through, + pathPattern,Finset.mem_image,Finset.mem_filter,Finset.mem_Ico] + constructor + · rintro ⟨i,hi,hj,hp,he⟩ + have hil : i < p.length := by + change i < p.length + 1 at hj + have := p.odd + omega + exact ⟨i,⟨⟨by omega,hil⟩,by simpa using hp⟩, + (p.closedCycle_edgeAt chord hlong hc i hil).symm.trans he⟩ + · rintro ⟨i,⟨hi,hp⟩,he⟩ + refine ⟨i,by omega,by change i < p.length+1; omega,?_,?_⟩ + · simpa using hp + · exact (p.closedCycle_edgeAt chord hlong hc i hi.2).trans he + +omit [Fintype V] [DecidableEq V] in +lemma closedCycle_parity_one : + (p.closedCycle chord hlong hc).parityPattern 1 = p.closed chord := by + ext e + simp only [IndexedCycle.parityPattern,IndexedCycle.mem_intervalPattern,closed, + interior,pathPattern,Finset.mem_union,Finset.mem_image,Finset.mem_filter, + Finset.mem_Ico,Finset.mem_singleton] + constructor + · rintro ⟨i,hi,hj,hp,he⟩ + change i < p.length+1 at hj + by_cases hil : i < p.length + · left + refine ⟨i,⟨⟨by omega,?_⟩,?_⟩, (p.closedCycle_edgeAt chord hlong hc i hil).symm.trans he⟩ + · have := p.odd; omega + · omega + · right + have hie : i = p.length := by omega + subst i + exact he.symm.trans (p.closedCycle_chord chord hlong hc) + · rintro (⟨i,⟨hi,hp⟩,he⟩ | he) + · refine ⟨i,by omega,by change i < p.length+1; omega,by omega,?_⟩ + exact (p.closedCycle_edgeAt chord hlong hc i (by omega)).trans he + · exact ⟨p.length,by omega,by change p.length < p.length+1; omega, + p.odd,(p.closedCycle_chord chord hlong hc).trans he.symm⟩ + +end MatchingFPRAS.Transport.OddPath + +namespace MatchingFPRAS.Transport + +variable {V E : Type*} [Fintype V] [DecidableEq V] [DecidableEq E] + +variable {inc : E → V → Prop} + +namespace IndexedCycle + +variable (c : IndexedCycle inc) + +omit [Fintype V] [DecidableEq V] in +lemma edgeSet_eq_parity_union : c.edgeSet = c.parityPattern 0 ∪ c.parityPattern 1 := by + ext e + simp only [mem_edgeSet,parityPattern,mem_intervalPattern,Finset.mem_union] + constructor + · rintro ⟨i,hi,he⟩ + have hp : i % 2 = 0 ∨ i % 2 = 1 := by omega + rcases hp with hp | hp + · exact Or.inl ⟨i,by omega,hi,hp,he⟩ + · exact Or.inr ⟨i,by omega,hi,hp,he⟩ + · rintro (⟨i,_,hi,_,he⟩ | ⟨i,_,hi,_,he⟩) <;> exact ⟨i,hi,he⟩ + +omit [Fintype V] [DecidableEq V] in +lemma zero_mem_parity : c.edgeAt 0 ∈ c.parityPattern 0 := by + apply (c.mem_intervalPattern _ _ _ _).mpr + exact ⟨0,le_rfl,by have := c.four_le; omega,rfl,rfl⟩ + +end IndexedCycle + +abbrev PatternCode (inc : E → V → Prop) := + {s : Finset E × Finset E // ∃ c : IndexedCycle inc, + c.parityPattern 0 = s.1 ∧ c.parityPattern 1 = s.2} + +end MatchingFPRAS.Transport + +end OAI diff --git a/lean/OAI/Combinatorics/MatchingCount/Graphs/Density.lean b/lean/OAI/Combinatorics/MatchingCount/Graphs/Density.lean new file mode 100644 index 0000000000000000000000000000000000000000..e8886f99153eaf29d1d23a07e45337cbcb27ef5d --- /dev/null +++ b/lean/OAI/Combinatorics/MatchingCount/Graphs/Density.lean @@ -0,0 +1,416 @@ +import Mathlib + +namespace OAI + +namespace MatchingFPRAS.Replica + +section + +open Finset + +variable {I Ω : Type*} [Fintype I] [DecidableEq I] [Fintype Ω] + +noncomputable def density (p : I → Ω → ℝ) (s : I → Ω) : ℝ := ∏ i, p i (s i) + +noncomputable def dot (p : I → Ω → ℝ) (f g : (I → Ω) → ℝ) : ℝ := + ∑ s, density p s * f s * g s + +noncomputable def average (p : I → Ω → ℝ) (i : I) : + (((I → Ω) → ℝ) →ₗ[ℝ] ((I → Ω) → ℝ)) where + toFun f s := ∑ a, p i a * f (Function.update s i a) + map_add' f g := by funext s; simp [mul_add, Finset.sum_add_distrib] + map_smul' c f := by funext s; simp [Finset.mul_sum,mul_left_comm] + +omit [Fintype I] in +lemma average_apply (p : I → Ω → ℝ) (i : I) (f : (I → Ω) → ℝ) (s : I → Ω) : + average p i f s = ∑ a, p i a * f (Function.update s i a) := rfl + +omit [Fintype I] in +lemma average_idem (p : I → Ω → ℝ) (hp : ∀ i, ∑ a, p i a = 1) (i : I) + (f : (I → Ω) → ℝ) : average p i (average p i f) = average p i f := by + funext s + simp only [average_apply, Function.update_idem] + rw [← Finset.sum_mul, hp i, one_mul] + +omit [Fintype I] in +lemma average_comm (p : I → Ω → ℝ) (i j : I) (f : (I → Ω) → ℝ) : + average p i (average p j f) = average p j (average p i f) := by + classical + by_cases h : i = j + · subst j; rfl + funext s + simp only [average_apply, Finset.mul_sum] + rw [Finset.sum_comm] + apply Finset.sum_congr rfl + intro b _ + apply Finset.sum_congr rfl + intro a _ + rw [Function.update_comm h] + ring + +noncomputable def swapDraw (i : I) : ((I → Ω) × Ω) ≃ ((I → Ω) × Ω) where + toFun z := (Function.update z.1 i z.2, z.1 i) + invFun z := (Function.update z.1 i z.2, z.1 i) + left_inv z := by simp [Function.update_idem] + right_inv z := by simp [Function.update_idem] + +omit [Fintype Ω] in +lemma density_swap (p : I → Ω → ℝ) (i : I) (s : I → Ω) (a : Ω) : + density p s * p i a = density p (Function.update s i a) * p i (s i) := by + classical + unfold density + rw [← Finset.mul_prod_erase _ _ (Finset.mem_univ i), + ← Finset.mul_prod_erase _ _ (Finset.mem_univ i)] + simp only [Function.update_self] + have he : (∏ j ∈ Finset.univ.erase i, p j (Function.update s i a j)) = + ∏ j ∈ Finset.univ.erase i, p j (s j) := by + apply Finset.prod_congr rfl + intro j hj + rw [Function.update_of_ne (Finset.ne_of_mem_erase hj)] + rw [he] + ring + +lemma average_adjoint (p : I → Ω → ℝ) (i : I) (f g : (I → Ω) → ℝ) : + dot p (average p i f) g = dot p f (average p i g) := by + classical + unfold dot + simp only [average_apply, Finset.mul_sum, Finset.sum_mul] + rw [← Fintype.sum_prod_type', ← Fintype.sum_prod_type'] + have h := Equiv.sum_comp (swapDraw (Ω := Ω) i) + (fun z : (I → Ω) × Ω => density p z.1 * f z.1 * (p i z.2 * g (Function.update z.1 i z.2))) + rw [← h] + apply Finset.sum_congr rfl + intro z _ + simp only [swapDraw, Equiv.coe_fn_mk, Function.update_idem, + Function.update_eq_self] + have hz := density_swap p i z.1 z.2 + nlinarith [congrArg (fun t : ℝ => t * f (Function.update z.1 i z.2) * g z.1) hz] + +variable (p : I → Ω → ℝ) + +lemma dot_comm (f g : (I → Ω) → ℝ) : dot p f g = dot p g f := by + unfold dot; apply Finset.sum_congr rfl; intro s _; ring + +lemma dot_zero_left (f : (I → Ω) → ℝ) : dot p 0 f = 0 := by simp [dot] + +lemma dot_zero_right (f : (I → Ω) → ℝ) : dot p f 0 = 0 := by simp [dot] + +lemma dot_add_left (f g h : (I → Ω) → ℝ) : + dot p (f+g) h = dot p f h + dot p g h := by + simp [dot, mul_add, add_mul, Finset.sum_add_distrib] + +lemma dot_add_right (f g h : (I → Ω) → ℝ) : + dot p f (g+h) = dot p f g + dot p f h := by + simp [dot, mul_add, Finset.sum_add_distrib] + +lemma dot_sub_left (f g h : (I → Ω) → ℝ) : + dot p (f-g) h = dot p f h - dot p g h := by + simp [dot, mul_sub, sub_mul, Finset.sum_sub_distrib] + +lemma dot_sub_right (f g h : (I → Ω) → ℝ) : + dot p f (g-h) = dot p f g - dot p f h := by + simp [dot, mul_sub, Finset.sum_sub_distrib] + +lemma dot_const_left (c : ℝ) (g : (I → Ω) → ℝ) : + dot p (fun _ => c) g = c * dot p (fun _ => 1) g := by + simp only [dot, mul_one, Finset.mul_sum] + apply Finset.sum_congr rfl; intro s _; ring + +lemma dot_nonneg (hp : ∀ i a, 0 ≤ p i a) (f : (I → Ω) → ℝ) : 0 ≤ dot p f f := by + apply Finset.sum_nonneg + intro s _ + have hh : 0 ≤ density p s := Finset.prod_nonneg (fun i _ => hp i (s i)) + nlinarith [mul_nonneg hh (sq_nonneg (f s))] + +structure Projection where + op : (((I → Ω) → ℝ) →ₗ[ℝ] ((I → Ω) → ℝ)) + idem : ∀ f, op (op f) = op f + adj : ∀ f g, dot p (op f) g = dot p f (op g) + +namespace Projection + +variable {p} + +noncomputable def identity : Projection p where + op := LinearMap.id + idem _ := rfl + adj _ _ := rfl + +noncomputable def complement (P : Projection p) : Projection p where + op := LinearMap.id - P.op + idem f := by + change f-P.op f-P.op (f-P.op f) = f-P.op f + rw [map_sub, P.idem] + abel + adj f g := by + change dot p (f-P.op f) g = dot p f (g-P.op g) + rw [dot_sub_left, dot_sub_right, P.adj] + +noncomputable def comp (P Q : Projection p) + (hc : ∀ f, P.op (Q.op f) = Q.op (P.op f)) : Projection p where + op := P.op.comp Q.op + idem f := by + change P.op (Q.op (P.op (Q.op f))) = P.op (Q.op f) + rw [← hc, Q.idem, P.idem] + adj f g := by + change dot p (P.op (Q.op f)) g = dot p f (P.op (Q.op g)) + rw [P.adj, Q.adj, hc] + +lemma dot_image (P : Projection p) (f : (I → Ω) → ℝ) : + dot p f (P.op f) = dot p (P.op f) (P.op f) := by + rw [P.adj, P.idem] + +end Projection + +noncomputable def avgProjection (hp : ∀ i, ∑ a, p i a = 1) (i : I) : Projection p where + op := average p i + idem := average_idem p hp i + adj := average_adjoint p i + +noncomputable def avgList : List I → (((I → Ω) → ℝ) →ₗ[ℝ] ((I → Ω) → ℝ)) + | [] => LinearMap.id + | i::l => (average p i).comp (avgList l) + +omit [Fintype I] in +lemma avgList_nil (f : (I → Ω) → ℝ) : avgList p [] f = f := rfl + +omit [Fintype I] in +lemma avgList_cons (i : I) (l : List I) (f : (I → Ω) → ℝ) : + avgList p (i::l) f = average p i (avgList p l f) := rfl + +omit [Fintype I] in +lemma average_comm_list (i : I) (l : List I) (f : (I → Ω) → ℝ) : + average p i (avgList p l f) = avgList p l (average p i f) := by + induction l with + | nil => rfl + | cons j l ih => + rw [avgList_cons, average_comm, ih, avgList_cons] + +omit [Fintype I] in +lemma avgList_idem (hp : ∀ i, ∑ a, p i a = 1) (l : List I) (f : (I → Ω) → ℝ) : + avgList p l (avgList p l f) = avgList p l f := by + induction l with + | nil => rfl + | cons i l ih => + simp only [avgList_cons] + rw [← average_comm_list, ih, average_idem p hp] + +lemma avgList_adjoint (l : List I) (f g : (I → Ω) → ℝ) : + dot p (avgList p l f) g = dot p f (avgList p l g) := by + induction l generalizing g with + | nil => rfl + | cons i l ih => + rw [avgList_cons, average_adjoint, ih, ← average_comm_list, avgList_cons] + +noncomputable def listProjection (hp : ∀ i, ∑ a, p i a = 1) (l : List I) : Projection p where + op := avgList p l + idem := avgList_idem p hp l + adj := avgList_adjoint p l + +omit [Fintype I] in +lemma average_list_mem (hp : ∀ i, ∑ a, p i a = 1) (l : List I) (i : I) (hi : i ∈ l) + (f : (I → Ω) → ℝ) : average p i (avgList p l f) = avgList p l f := by + induction l with + | nil => simp at hi + | cons j l ih => + rcases List.mem_cons.mp hi with rfl | hi + · simpa only [avgList_cons] using average_idem p hp i (avgList p l f) + · rw [avgList_cons, average_comm, ih hi] + +end + +section + +open Finset + +variable {I Ω : Type*} [Fintype I] [DecidableEq I] [LinearOrder I] + [Fintype Ω] + +variable (p : I → Ω → ℝ) + +noncomputable def outside (x y : I) : List I := + (Finset.univ.filter (fun i => x < i ∧ i ≠ y)).toList + +noncomputable def pairCondition (x y : I) : + (((I → Ω) → ℝ) →ₗ[ℝ] ((I → Ω) → ℝ)) := avgList p (outside x y) + +noncomputable def residual (x y : I) : + (((I → Ω) → ℝ) →ₗ[ℝ] ((I → Ω) → ℝ)) := + (LinearMap.id-average p x).comp + ((LinearMap.id-average p y).comp (pairCondition p x y)) + +lemma residual_apply (x y : I) (f : (I → Ω) → ℝ) : + residual p x y f = + pairCondition p x y f - average p y (pairCondition p x y f) - + average p x (pairCondition p x y f - average p y (pairCondition p x y f)) := rfl + +lemma residual_formula (x y : I) (f : (I → Ω) → ℝ) : + residual p x y f = pairCondition p x y f - + average p x (pairCondition p x y f) - average p y (pairCondition p x y f) + + average p x (average p y (pairCondition p x y f)) := by + rw [residual_apply, map_sub]; abel + +lemma average_condition_comm (i x y : I) (f : (I → Ω) → ℝ) : + average p i (pairCondition p x y f) = pairCondition p x y (average p i f) := + average_comm_list p i (outside x y) f + +lemma average_residual_comm (i x y : I) (f : (I → Ω) → ℝ) : + average p i (residual p x y f) = residual p x y (average p i f) := by + simp only [residual_apply, map_sub] + simp_rw [average_comm p i x, average_comm p i y, average_condition_comm p i x y] + +lemma residual_center_x (hp : ∀ i, ∑ a, p i a = 1) (x y : I) (f : (I → Ω) → ℝ) : + average p x (residual p x y f) = 0 := by + rw [residual_apply, map_sub, average_idem p hp, sub_self] + +lemma residual_center_y (hp : ∀ i, ∑ a, p i a = 1) (x y : I) (f : (I → Ω) → ℝ) : + average p y (residual p x y f) = 0 := by + simp only [residual_apply, map_sub] + rw [average_idem p hp, average_comm p y x, average_comm p y x, + average_idem p hp] + simp + +lemma condition_invariant (hp : ∀ i, ∑ a, p i a = 1) (i x y : I) + (hix : x < i) (hiy : i ≠ y) (f : (I → Ω) → ℝ) : + average p i (pairCondition p x y f) = pairCondition p x y f := by + apply average_list_mem p hp + simp [outside, hix, hiy] + +lemma residual_invariant (hp : ∀ i, ∑ a, p i a = 1) (i x y : I) + (hix : x < i) (hiy : i ≠ y) (f : (I → Ω) → ℝ) : + average p i (residual p x y f) = residual p x y f := by + simp only [residual_apply, map_sub] + simp_rw [average_comm p i x, average_comm p i y, + condition_invariant p hp i x y hix hiy] + +lemma residual_projection (hp : ∀ i, ∑ a, p i a = 1) (x y : I) : + ∃ P : Projection p, P.op = residual p x y := by + let X := (avgProjection p hp x).complement + let Y := (avgProjection p hp y).complement + let C := listProjection p hp (outside x y) + have hyc : ∀ f, Y.op (C.op f) = C.op (Y.op f) := by + intro f + change pairCondition p x y f-average p y (pairCondition p x y f) = + pairCondition p x y (f-average p y f) + rw [map_sub, average_condition_comm] + have hxc : ∀ f, X.op ((Y.comp C hyc).op f) = (Y.comp C hyc).op (X.op f) := by + intro f + change (pairCondition p x y f-average p y (pairCondition p x y f)) - + average p x (pairCondition p x y f-average p y (pairCondition p x y f)) = + pairCondition p x y (f-average p x f) - + average p y (pairCondition p x y (f-average p x f)) + simp only [map_sub] + rw [← average_condition_comm, average_comm p x y] + abel + exact ⟨X.comp (Y.comp C hyc) hxc, rfl⟩ + +lemma residual_dot (hp : ∀ i, ∑ a, p i a = 1) (x y : I) (f : (I → Ω) → ℝ) : + dot p f (residual p x y f) = dot p (residual p x y f) (residual p x y f) := by + obtain ⟨P,hP⟩ := residual_projection p hp x y + rw [← hP] + exact P.dot_image f + +omit [LinearOrder I] in +lemma centered_invariant_orthogonal (i : I) (f g : (I → Ω) → ℝ) + (hf : average p i f = 0) (hg : average p i g = g) : dot p f g = 0 := by + rw [← hg, ← average_adjoint, hf, dot_zero_left] + +lemma residual_orthogonal (hp : ∀ i, ∑ a, p i a = 1) (x y u v : I) + (hxy : x < y) (huv : u < v) (hd : (x,y) ≠ (u,v)) (f : (I → Ω) → ℝ) : + dot p (residual p x y f) (residual p u v f) = 0 := by + rcases lt_trichotomy y v with hyv | rfl | hvy + · rw [dot_comm] + exact centered_invariant_orthogonal p v _ _ (residual_center_y p hp u v f) + (residual_invariant p hp v x y (lt_trans hxy hyv) (ne_of_gt hyv) f) + · rcases lt_trichotomy x u with hxu | rfl | hux + · rw [dot_comm] + exact centered_invariant_orthogonal p u _ _ (residual_center_x p hp u y f) + (residual_invariant p hp u x y hxu (ne_of_lt huv) f) + · exact (hd rfl).elim + · exact centered_invariant_orthogonal p x _ _ (residual_center_x p hp x y f) + (residual_invariant p hp x u y hux (ne_of_lt hxy) f) + · exact centered_invariant_orthogonal p y _ _ (residual_center_y p hp x y f) + (residual_invariant p hp y u v (lt_trans huv hvy) (ne_of_gt hvy) f) + +omit [Fintype I] [LinearOrder I] in +lemma average_one (hp : ∀ i, ∑ a, p i a = 1) (i : I) : + average p i (fun _ => 1) = (fun _ => 1) := by + funext s; simpa [average_apply] using hp i + +lemma residual_mean_zero (hp : ∀ i, ∑ a, p i a = 1) (x y : I) (f : (I → Ω) → ℝ) : + dot p (fun _ => 1) (residual p x y f) = 0 := by + rw [dot_comm] + exact centered_invariant_orthogonal p x _ _ (residual_center_x p hp x y f) + (average_one p hp x) + +end + +section + +open Finset + +variable {I Ω J : Type*} [Fintype I] [DecidableEq I] [Fintype Ω] + +variable (p : I → Ω → ℝ) + +lemma dot_sum_right (S : Finset J) (f : (I → Ω) → ℝ) (r : J → (I → Ω) → ℝ) : + dot p f (∑ j ∈ S, r j) = ∑ j ∈ S, dot p f (r j) := by + unfold dot + simp only [Finset.sum_apply, Finset.mul_sum] + rw [Finset.sum_comm] + +lemma dot_sum_left (S : Finset J) (r : J → (I → Ω) → ℝ) (f : (I → Ω) → ℝ) : + dot p (∑ j ∈ S, r j) f = ∑ j ∈ S, dot p (r j) f := by + rw [dot_comm, dot_sum_right] + exact Finset.sum_congr rfl (fun j _ => dot_comm p f (r j)) + +end + +open Finset + +variable {I Ω : Type*} [Fintype I] [DecidableEq I] [LinearOrder I] + [Fintype Ω] + +theorem residual_sum (p : I → Ω → ℝ) (hp : ∀ i a, 0 ≤ p i a) + (hs : ∀ i, ∑ a, p i a = 1) (pairs : Finset (I × I)) + (hpair : ∀ z ∈ pairs, z.1 < z.2) (f : (I → Ω) → ℝ) : + (∑ z ∈ pairs, dot p (residual p z.1 z.2 f) (residual p z.1 z.2 f)) ≤ + ∑ s, density p s * (f s - ∑ t, density p t * f t)^2 := by + classical + let r : (I × I) → (I → Ω) → ℝ := fun z => residual p z.1 z.2 f + let R := ∑ z ∈ pairs, r z + let m := ∑ t, density p t * f t + let F := f - (fun _ => m) + have hd (z) : dot p F (r z) = dot p (r z) (r z) := by + change dot p (f-(fun _ => m)) (residual p z.1 z.2 f) = _ + rw [dot_sub_left, dot_const_left, residual_mean_zero p hs, mul_zero, sub_zero] + exact residual_dot p hs z.1 z.2 f + have hFR : dot p F R = ∑ z ∈ pairs, dot p (r z) (r z) := by + rw [dot_sum_right] + exact Finset.sum_congr rfl (fun z _ => hd z) + have hRR : dot p R R = ∑ z ∈ pairs, dot p (r z) (r z) := by + rw [dot_sum_left] + apply Finset.sum_congr rfl + intro z hz + rw [dot_sum_right] + apply Finset.sum_eq_single z + · intro w hw hwz + apply residual_orthogonal p hs z.1 z.2 w.1 w.2 (hpair z hz) (hpair w hw) + simpa only [Prod.mk.eta] using Ne.symm hwz + · exact fun hn => (hn hz).elim + have hn := dot_nonneg p hp (F-R) + rw [dot_sub_left p F R (F-R), dot_sub_right p F F R, + dot_sub_right p R F R, dot_comm p R F, hFR, hRR] at hn + have hff : dot p F F = ∑ s, density p s * (f s-∑ t, density p t*f t)^2 := by + unfold dot + apply Finset.sum_congr rfl + intro s _ + change density p s * (f s-m) * (f s-m) = density p s * (f s-m)^2 + ring + rw [← hff] + change (∑ z ∈ pairs, dot p (r z) (r z)) ≤ dot p F F + linarith + +end MatchingFPRAS.Replica + +end OAI diff --git a/lean/OAI/Combinatorics/MatchingCount/Graphs/Edge.lean b/lean/OAI/Combinatorics/MatchingCount/Graphs/Edge.lean new file mode 100644 index 0000000000000000000000000000000000000000..c7e4ed55d9a8308b07bf8cba959daabe1556fe94 --- /dev/null +++ b/lean/OAI/Combinatorics/MatchingCount/Graphs/Edge.lean @@ -0,0 +1,419 @@ +import Mathlib +import OAI.Combinatorics.MatchingCount.Graphs.Mate + +namespace OAI + +namespace MatchingFPRAS.Switching +open Finset +open scoped Classical symmDiff + +variable {V : Type*} +theorem switched_holes [Fintype V] [DecidableEq V] + (m n : Mate V) (S T : Finset V) (hm : HasHoles m S) (hn : HasHoles n T) + (a : V) (ha : a ∈ S) (hTa : a ∉ T) : + ∃ b, b ≠ a ∧ b ∈ S ∆ T ∧ + HasHoles (switched m n a) (S ∆ {a, b}) ∧ + HasHoles (switched n m a) (T ∆ {a, b}) := by + classical + have hma : m.1 a = a := (hm a).mpr ha + have hna : n.1 a ≠ a := fun h => hTa ((hn a).mp h) + have ham : m.1 a ≠ n.1 a := by rw [hma]; exact Ne.symm hna + obtain ⟨b, hba, hab, he⟩ := active_component_endpoints m n a hma hna + have hnBoth : ∀ v, (overlay m n).Reachable a v → ¬(v ∈ S ∧ v ∈ T) := by + intro v hv ⟨hs, ht⟩ + exact mates_ne_of_reachable m n hv ham (((hm v).mpr hs).trans ((hn v).mpr ht).symm) + have hb : b ∈ S ∨ b ∈ T := by + simpa only [hm b, hn b] using (he b hab).mpr (Or.inr rfl) + refine ⟨b, hba, ?_, ?_, ?_⟩ + · simp only [Finset.mem_symmDiff] + have := hnBoth b hab + tauto + · intro v + by_cases hv : (overlay m n).Reachable a v + · have hvEnd : (v ∈ S ∨ v ∈ T) ↔ (v = a ∨ v = b) := by + simpa only [hm v, hn v] using he v hv + have hnb := hnBoth v hv + simp only [switched_apply, ite_eq_left hv, hn v, Finset.mem_symmDiff, + Finset.mem_insert, Finset.mem_singleton] + tauto + · have hva : v ≠ a := by rintro rfl; exact hv .rfl + have hvb : v ≠ b := by rintro rfl; exact hv hab + simp [switched_apply, hv, hm v, Finset.mem_symmDiff, hva, hvb] + · intro v + by_cases hv : (overlay m n).Reachable a v + · have hvEnd : (v ∈ S ∨ v ∈ T) ↔ (v = a ∨ v = b) := by + simpa only [hm v, hn v] using he v hv + have hnb := hnBoth v hv + simp only [switched_apply, overlay_comm n m, ite_eq_left hv, hm v, + Finset.mem_symmDiff, Finset.mem_insert, Finset.mem_singleton] + tauto + · have hva : v ≠ a := by rintro rfl; exact hv .rfl + have hvb : v ≠ b := by rintro rfl; exact hv hab + simp [switched_apply, overlay_comm n m, hv, hn v, Finset.mem_symmDiff, hva, hvb] + +theorem mixed_hole_partition_comparison [Fintype V] [LinearOrder V] + (w : V → V → ℝ) (hw : ∀ v z, 0 ≤ w v z) (S T : Finset V) + (a : V) (ha : a ∈ S) (hTa : a ∉ T) : + partition w S * partition w T ≤ + ∑ b ∈ (S ∆ T).erase a, + partition w (S ∆ {a, b}) * partition w (T ∆ {a, b}) := by + classical + let H := (S ∆ T).erase a + let inputs := (matchings S) ×ˢ (matchings T) + let Q := fun b : V => (matchings (S ∆ {a, b})) ×ˢ (matchings (T ∆ {a, b})) + let f := fun p : Mate V × Mate V => (switched p.1 p.2 a, switched p.2 p.1 a) + let W := fun p : Mate V × Mate V => weight w p.1 * weight w p.2 + have hi : Function.Injective f := switch_injective a + have hd : (↑H : Set V).PairwiseDisjoint Q := by + intro b hb c hc hbc + apply Finset.disjoint_left.mpr + intro p hp hq + have hpb : HasHoles p.1 (S ∆ {a, b}) := + (mem_matchings p.1 _).mp (Finset.mem_product.mp hp).1 + have hpc : HasHoles p.1 (S ∆ {a, c}) := + (mem_matchings p.1 _).mp (Finset.mem_product.mp hq).1 + have heq : (S ∆ {a, b}) = (S ∆ {a, c}) := hasHoles_unique p.1 hpb hpc + have habc : ({a, b} : Finset V) = {a, c} := symmDiff_right_injective S heq + have hbm : b ∈ ({a, c} : Finset V) := by rw [← habc]; simp + have hba : b ≠ a := (Finset.mem_erase.mp hb).1 + simp only [Finset.mem_insert, Finset.mem_singleton] at hbm + exact hbc (hbm.resolve_left hba) + have himage : inputs.image f ⊆ H.biUnion Q := by + intro p hp + obtain ⟨⟨m, n⟩, hmn, rfl⟩ := Finset.mem_image.mp hp + obtain ⟨hm, hn⟩ := Finset.mem_product.mp hmn + obtain ⟨b, hba, hb, hmb, hnb⟩ := switched_holes m n S T + ((mem_matchings m S).mp hm) ((mem_matchings n T).mp hn) a ha hTa + exact Finset.mem_biUnion.mpr ⟨b, Finset.mem_erase.mpr ⟨hba, hb⟩, + Finset.mem_product.mpr ⟨(mem_matchings _ _).mpr hmb, (mem_matchings _ _).mpr hnb⟩⟩ + calc + partition w S * partition w T = ∑ p ∈ inputs, W p := by + simp only [inputs, W, partition, Finset.sum_product, Finset.sum_mul_sum] + _ = ∑ p ∈ inputs.image f, W p := by + rw [Finset.sum_image hi.injOn] + apply Finset.sum_congr rfl + intro p _ + exact (switched_weight w p.1 p.2 a).symm + _ ≤ ∑ p ∈ H.biUnion Q, W p := + Finset.sum_le_sum_of_subset_of_nonneg himage + (fun p _ _ => mul_nonneg (weight_nonneg w hw p.1) (weight_nonneg w hw p.2)) + _ = _ := by + rw [Finset.sum_biUnion hd] + apply Finset.sum_congr rfl + intro b _ + simp only [Q, W, partition, Finset.sum_product, Finset.sum_mul_sum] + +noncomputable def withEdge (m : Mate V) (a b : V) : Mate V := by + classical + by_cases h : m.1 a = a ∧ m.1 b = b + · refine ⟨fun v => if v = a then b else if v = b then a else m.1 v, ?_⟩ + intro v + by_cases hva : v = a + · subst v + by_cases hab : a = b <;> simp [hab] + by_cases hvb : v = b + · subst v + by_cases hab : a = b <;> simp [hab, hva] + have hma : m.1 v ≠ a := by + intro hv + have he := congrArg m.1 hv + rw [mate_mate, h.1] at he + exact hva he + have hmb : m.1 v ≠ b := by + intro hv + have he := congrArg m.1 hv + rw [mate_mate, h.2] at he + exact hvb he + simp [hva, hvb, hma, hmb] + · exact m + +@[simp] theorem withEdge_apply (m : Mate V) (a b v : V) + (ha : m.1 a = a) (hb : m.1 b = b) : + (withEdge m a b).1 v = if v = a then b else if v = b then a else m.1 v := by + classical + simp [withEdge, ha, hb] + +theorem withEdge_holes [DecidableEq V] (m : Mate V) (S : Finset V) + (hm : HasHoles m S) (a b : V) (ha : a ∈ S) (hb : b ∈ S) (hab : a ≠ b) : + HasHoles (withEdge m a b) (S \ {a, b}) := by + classical + intro v + rw [withEdge_apply m a b v ((hm a).mpr ha) ((hm b).mpr hb)] + by_cases hva : v = a + · subst v + simp [hab, Ne.symm hab] + by_cases hvb : v = b + · subst v + simp [hab, Ne.symm hab] + simp [hva, hvb, hm v] + +theorem withEdge_injOn [Fintype V] (S : Finset V) (a b : V) + (ha : a ∈ S) (hb : b ∈ S) : + Set.InjOn (fun m : Mate V => withEdge m a b) (matchings S) := by + classical + intro m hm n hn he + have hm := (mem_matchings m S).mp hm + have hn := (mem_matchings n S).mp hn + apply Subtype.ext + funext v + by_cases hva : v = a + · subst v + exact ((hm a).mpr ha).trans ((hn a).mpr ha).symm + by_cases hvb : v = b + · subst v + exact ((hm b).mpr hb).trans ((hn b).mpr hb).symm + have hv := congrArg (fun p : Mate V => p.1 v) he + simpa [withEdge_apply, (hm a).mpr ha, (hm b).mpr hb, + (hn a).mpr ha, (hn b).mpr hb, hva, hvb] using hv + +def edgeActivity [LinearOrder V] (w : V → V → ℝ) (a b : V) : ℝ := + if a < b then w a b else w b a + +theorem edgeActivity_comm [LinearOrder V] (w : V → V → ℝ) (a b : V) : + edgeActivity w a b = edgeActivity w b a := by + rcases lt_trichotomy a b with h | rfl | h + · simp [edgeActivity, h, h.not_gt] + · rfl + · simp [edgeActivity, h, h.not_gt] + +theorem withEdge_comm (m : Mate V) (a b : V) : withEdge m a b = withEdge m b a := by + classical + by_cases h : m.1 a = a ∧ m.1 b = b + · apply Subtype.ext + funext v + simp only [withEdge_apply, h.1, h.2] + by_cases hv : v = a + · subst v + by_cases hab : a = b <;> simp [hab] + · simp [hv] + · have h' : ¬(m.1 b = b ∧ m.1 a = a) := by tauto + simp [withEdge, h, h'] + +theorem withEdge_weight_of_lt [Fintype V] [LinearOrder V] + (w : V → V → ℝ) (m : Mate V) (a b : V) + (ha : m.1 a = a) (hb : m.1 b = b) (hab : a < b) : + weight w (withEdge m a b) = w a b * weight w m := by + classical + have hf : ∀ v : V, + (if v < (withEdge m a b).1 v then w v ((withEdge m a b).1 v) else 1) = + (if v = a then w a b else 1) * (if v < m.1 v then w v (m.1 v) else 1) := by + intro v + by_cases hva : v = a + · subst v + simp [withEdge_apply, ha, hb, hab] + by_cases hvb : v = b + · subst v + simp [withEdge_apply, ha, hb, hab.ne', hab.not_gt] + simp [withEdge_apply, ha, hb, hva, hvb] + simp only [weight, hf, Finset.prod_mul_distrib] + simp + +theorem withEdge_weight [Fintype V] [LinearOrder V] + (w : V → V → ℝ) (m : Mate V) (a b : V) + (ha : m.1 a = a) (hb : m.1 b = b) (hab : a ≠ b) : + weight w (withEdge m a b) = edgeActivity w a b * weight w m := by + rcases lt_or_gt_of_ne hab with h | h + · simpa [edgeActivity, h] using withEdge_weight_of_lt w m a b ha hb h + · rw [withEdge_comm, edgeActivity_comm] + simpa [edgeActivity, h] using withEdge_weight_of_lt w m b a hb ha h + +theorem edge_fill_partition [Fintype V] [LinearOrder V] + (w : V → V → ℝ) (hw : ∀ v z, 0 ≤ w v z) (S : Finset V) + (a b : V) (ha : a ∈ S) (hb : b ∈ S) (hab : a ≠ b) : + edgeActivity w a b * partition w S ≤ partition w (S \ {a, b}) := by + classical + let f := fun m : Mate V => withEdge m a b + have hi := withEdge_injOn S a b ha hb + have hsub : (matchings S).image f ⊆ matchings (S \ {a, b}) := by + intro m hm + obtain ⟨n, hn, rfl⟩ := Finset.mem_image.mp hm + exact (mem_matchings _ _).mpr + (withEdge_holes n S ((mem_matchings n S).mp hn) a b ha hb hab) + calc + edgeActivity w a b * partition w S = ∑ m ∈ matchings S, weight w (f m) := by + rw [partition, Finset.mul_sum] + apply Finset.sum_congr rfl + intro m hm + have hh := (mem_matchings m S).mp hm + exact (withEdge_weight w m a b ((hh a).mpr ha) ((hh b).mpr hb) hab).symm + _ = ∑ m ∈ (matchings S).image f, weight w m := (Finset.sum_image hi).symm + _ ≤ partition w (S \ {a, b}) := + Finset.sum_le_sum_of_subset_of_nonneg hsub (fun m _ _ => weight_nonneg w hw m) + +noncomputable def holeRatio [Fintype V] [LinearOrder V] + (w : V → V → ℝ) (U : Finset V) : ℝ := partition w U / partition w ∅ + +theorem holeRatio_nonneg [Fintype V] [LinearOrder V] + (w : V → V → ℝ) (hw : ∀ v z, 0 ≤ w v z) (U : Finset V) : + 0 ≤ holeRatio w U := div_nonneg (partition_nonneg w hw U) (partition_nonneg w hw ∅) + +theorem holeRatio_empty [Fintype V] [LinearOrder V] + (w : V → V → ℝ) (hz : 0 < partition w ∅) : holeRatio w ∅ = 1 := div_self hz.ne' + +theorem holeRatio_pair_comm [Fintype V] [LinearOrder V] + (w : V → V → ℝ) (a b : V) : holeRatio w {a, b} = holeRatio w {b, a} := by + rw [Finset.pair_comm] + +theorem holeRatio_comparison [Fintype V] [LinearOrder V] + (w : V → V → ℝ) (hw : ∀ v z, 0 ≤ w v z) (hz : 0 < partition w ∅) + (U : Finset V) (a : V) (ha : a ∈ U) : + holeRatio w U ≤ ∑ b ∈ U.erase a, holeRatio w (U \ {a, b}) * holeRatio w {a, b} := by + have h := hole_partition_comparison w hw U a ha + have hzz : 0 ≤ partition w ∅ * partition w ∅ := mul_nonneg hz.le hz.le + calc + holeRatio w U = (partition w U * partition w ∅) / (partition w ∅ * partition w ∅) := by + unfold holeRatio + field_simp + _ ≤ (∑ b ∈ U.erase a, partition w (U \ {a, b}) * partition w {a, b}) / + (partition w ∅ * partition w ∅) := div_le_div_of_nonneg_right h hzz + _ = _ := by + rw [Finset.sum_div] + apply Finset.sum_congr rfl + intro b _ + exact mul_div_mul_comm _ _ _ _ + +theorem four_holes [Fintype V] [LinearOrder V] + (w : V → V → ℝ) (hw : ∀ v z, 0 ≤ w v z) (hz : 0 < partition w ∅) + (a b c d : V) (hab : a ≠ b) (hac : a ≠ c) (had : a ≠ d) + (hbc : b ≠ c) (hbd : b ≠ d) (hcd : c ≠ d) : + holeRatio w {a, b, c, d} ≤ + holeRatio w {a, b} * holeRatio w {c, d} + + holeRatio w {a, c} * holeRatio w {b, d} + + holeRatio w {a, d} * holeRatio w {b, c} := by + classical + have h := holeRatio_comparison w hw hz {a,b,c,d} a (by simp) + have he : ({a,b,c,d} : Finset V).erase a = {b,c,d} := by + ext v + simp only [Finset.mem_erase, Finset.mem_insert, Finset.mem_singleton] + grind + have hab' : ({a,b,c,d} : Finset V) \ {a,b} = {c,d} := by + ext v + simp only [Finset.mem_sdiff, Finset.mem_insert, Finset.mem_singleton] + grind + have hac' : ({a,b,c,d} : Finset V) \ {a,c} = {b,d} := by + ext v + simp only [Finset.mem_sdiff, Finset.mem_insert, Finset.mem_singleton] + grind + have had' : ({a,b,c,d} : Finset V) \ {a,d} = {b,c} := by + ext v + simp only [Finset.mem_sdiff, Finset.mem_insert, Finset.mem_singleton] + grind + rw [he, Finset.sum_insert (by simp [hbc, hbd]), + Finset.sum_insert (by simp [hcd]), Finset.sum_singleton, + hab', hac', had'] at h + nlinarith only [h] + +theorem mixed_holeRatio_comparison [Fintype V] [LinearOrder V] + (w : V → V → ℝ) (hw : ∀ v z, 0 ≤ w v z) (hz : 0 < partition w ∅) + (S T : Finset V) (a : V) (ha : a ∈ S) (hTa : a ∉ T) : + holeRatio w S * holeRatio w T ≤ + ∑ b ∈ (S ∆ T).erase a, + holeRatio w (S ∆ {a, b}) * holeRatio w (T ∆ {a, b}) := by + have h := mixed_hole_partition_comparison w hw S T a ha hTa + have hzz : 0 ≤ partition w ∅ * partition w ∅ := mul_nonneg hz.le hz.le + calc + holeRatio w S * holeRatio w T = + (partition w S * partition w T) / (partition w ∅ * partition w ∅) := + (mul_div_mul_comm _ _ _ _).symm + _ ≤ (∑ b ∈ (S ∆ T).erase a, + partition w (S ∆ {a, b}) * partition w (T ∆ {a, b})) / + (partition w ∅ * partition w ∅) := div_le_div_of_nonneg_right h hzz + _ = _ := by + rw [Finset.sum_div] + apply Finset.sum_congr rfl + intro b _ + exact mul_div_mul_comm _ _ _ _ + +theorem edge_fill_holeRatio [Fintype V] [LinearOrder V] + (w : V → V → ℝ) (hw : ∀ v z, 0 ≤ w v z) (hz : 0 < partition w ∅) + (S : Finset V) (a b : V) (ha : a ∈ S) (hb : b ∈ S) (hab : a ≠ b) : + edgeActivity w a b * holeRatio w S ≤ holeRatio w (S \ {a, b}) := by + simpa only [holeRatio, mul_div_assoc] using + div_le_div_of_nonneg_right (edge_fill_partition w hw S a b ha hb hab) hz.le + +noncomputable def rowMax [Fintype V] [LinearOrder V] + (hcard : 2 ≤ Fintype.card V) (w : V → V → ℝ) (a : V) : ℝ := + ((Finset.univ.erase a).sup' (by + apply Finset.card_pos.mp + rw [Finset.card_erase_of_mem (Finset.mem_univ a), Finset.card_univ] + omega) fun b => holeRatio w {a,b}) + +theorem holeRatio_le_rowMax [Fintype V] [LinearOrder V] + (hcard : 2 ≤ Fintype.card V) (w : V → V → ℝ) (a b : V) (hab : a ≠ b) : + holeRatio w {a,b} ≤ rowMax hcard w a := by + exact Finset.le_sup' (fun b => holeRatio w {a,b}) (by simp [Ne.symm hab]) + +theorem rowMax_attained [Fintype V] [LinearOrder V] + (hcard : 2 ≤ Fintype.card V) (w : V → V → ℝ) (a : V) : + ∃ b, b ≠ a ∧ holeRatio w {a,b} = rowMax hcard w a := by + unfold rowMax + obtain ⟨b,hb,he⟩ := Finset.exists_mem_eq_sup' + (show (Finset.univ.erase a).Nonempty by + apply Finset.card_pos.mp + rw [Finset.card_erase_of_mem (Finset.mem_univ a), Finset.card_univ] + omega) (fun b => holeRatio w {a,b}) + exact ⟨b,(Finset.mem_erase.mp hb).1,he.symm⟩ + +theorem two_holes_le_four [Fintype V] [LinearOrder V] + (hcard : 2 ≤ Fintype.card V) (w : V → V → ℝ) + (hr : ∀ a, rowMax hcard w a ≤ 4) (U : Finset V) (hU : U.card = 2) : + holeRatio w U ≤ 4 := by + obtain ⟨a,b,hab,rfl⟩ := Finset.card_eq_two.mp hU + exact (holeRatio_le_rowMax hcard w a b hab).trans (hr a) + +theorem four_holes_le_fortyeight [Fintype V] [LinearOrder V] + (hcard : 2 ≤ Fintype.card V) (w : V → V → ℝ) + (hw : ∀ v z, 0 ≤ w v z) (hz : 0 < partition w ∅) + (hr : ∀ a, rowMax hcard w a ≤ 4) (U : Finset V) (hU : U.card = 4) : + holeRatio w U ≤ 48 := by + obtain ⟨a,b,c,d,hab,hac,had,hbc,hbd,hcd,rfl⟩ := Finset.card_eq_four.mp hU + have hpair : ∀ a b : V, a ≠ b → holeRatio w {a,b} ≤ 4 := + fun a b hab => (holeRatio_le_rowMax hcard w a b hab).trans (hr a) + have hmul : ∀ (a b c d : V), a ≠ b → c ≠ d → + holeRatio w {a,b} * holeRatio w {c,d} ≤ 16 := by + intro a b c d hab hcd + have h := mul_le_mul (hpair a b hab) (hpair c d hcd) + (holeRatio_nonneg w hw {c,d}) (by norm_num : (0:ℝ) ≤ 4) + norm_num at h ⊢ + exact h + have hf := four_holes w hw hz a b c d hab hac had hbc hbd hcd + have h1 := hmul a b c d hab hcd + have h2 := hmul a c b d hac hbd + have h3 := hmul a d b c had hbc + linarith + +theorem zero_or_two_holes_le_four [Fintype V] [LinearOrder V] + (hcard : 2 ≤ Fintype.card V) (w : V → V → ℝ) (hz : 0 < partition w ∅) + (hr : ∀ a, rowMax hcard w a ≤ 4) (U : Finset V) + (hU : U.card = 0 ∨ U.card = 2) : holeRatio w U ≤ 4 := by + rcases hU with h | h + · have he : U = ∅ := Finset.card_eq_zero.mp h + rw [he, holeRatio_empty w hz] + norm_num + · exact two_holes_le_four hcard w hr U h + +theorem small_holes_le_fortyeight [Fintype V] [LinearOrder V] + (hcard : 2 ≤ Fintype.card V) (w : V → V → ℝ) + (hw : ∀ v z, 0 ≤ w v z) (hz : 0 < partition w ∅) + (hr : ∀ a, rowMax hcard w a ≤ 4) (U : Finset V) + (hU : U.card = 0 ∨ U.card = 2 ∨ U.card = 4) : holeRatio w U ≤ 48 := by + rcases hU with h | h | h + · exact (zero_or_two_holes_le_four hcard w hz hr U (Or.inl h)).trans (by norm_num) + · exact (two_holes_le_four hcard w hr U h).trans (by norm_num) + · exact four_holes_le_fortyeight hcard w hw hz hr U h + +theorem symmDiff_pair_of_mem_mem [DecidableEq V] (S : Finset V) (a b : V) + (ha : a ∈ S) (hb : b ∈ S) : S ∆ {a,b} = S \ {a,b} := by + ext v + simp only [Finset.mem_symmDiff, Finset.mem_sdiff, Finset.mem_insert, Finset.mem_singleton] + grind + +theorem symmDiff_pair_of_mem_notMem [DecidableEq V] (S : Finset V) (a b : V) + (ha : a ∈ S) (hb : b ∉ S) : S ∆ {a,b} = insert b (S.erase a) := by + ext v + simp only [Finset.mem_symmDiff, Finset.mem_erase, Finset.mem_insert, Finset.mem_singleton] + grind + +end MatchingFPRAS.Switching + +end OAI diff --git a/lean/OAI/Combinatorics/MatchingCount/Graphs/Edge2.lean b/lean/OAI/Combinatorics/MatchingCount/Graphs/Edge2.lean new file mode 100644 index 0000000000000000000000000000000000000000..fd7ce2d1efe02184d003be39b1211a98a0d6bc9f --- /dev/null +++ b/lean/OAI/Combinatorics/MatchingCount/Graphs/Edge2.lean @@ -0,0 +1,335 @@ +import Mathlib +import OAI.Combinatorics.MatchingCount.Graphs.Admissible + +namespace OAI + +namespace MatchingFPRAS.UnitRefresh + +open Finset MatchingFPRAS.Transport + +variable {V L : Type*} [Fintype V] [Fintype L] [DecidableEq V] [DecidableEq L] + +variable {bags : V → Finset L} + +noncomputable local instance : Fintype (BagEdge bags) := Fintype.ofFinite _ + +noncomputable local instance : Fintype (PM (BagEdge.Incident (bags := bags))) := Fintype.ofFinite _ + +def ColoredPairing.edgeAt (p : ColoredPairing bags) (x : V) : BagEdge bags := + ⟨⟨(s(x,p.pair.mate x),p.color x),by + simp only [Sym2.mk_isDiag_iff] + exact (p.pair.no_fixed x).symm⟩,by + intro y hy + change p.color x ∈ bags y + rcases Sym2.mem_iff.mp hy with h | h <;> subst y + · exact p.allowed x + · rw [←p.same_color x] + exact p.allowed (p.pair.mate x)⟩ + +omit [Fintype V] [Fintype L] [DecidableEq V] [DecidableEq L] in +lemma ColoredPairing.edgeAt_incident (p : ColoredPairing bags) (x y : V) : + (p.edgeAt x).Incident y ↔ y=x ∨ y=p.pair.mate x := Sym2.mem_iff + +omit [Fintype V] [Fintype L] [DecidableEq V] [DecidableEq L] in +lemma ColoredPairing.edgeAt_mate (p : ColoredPairing bags) (x : V) : + p.edgeAt (p.pair.mate x)=p.edgeAt x := by + apply Subtype.ext + apply Subtype.ext + change (s(p.pair.mate x,p.pair.mate (p.pair.mate x)),p.color (p.pair.mate x)) = _ + rw [p.pair.involutive,p.same_color,Sym2.eq_swap] + rfl + +omit [Fintype V] [Fintype L] [DecidableEq V] [DecidableEq L] in +lemma ColoredPairing.edgeAt_of_incident (p : ColoredPairing bags) (x y : V) + (h : (p.edgeAt x).Incident y) : p.edgeAt y=p.edgeAt x := by + rcases (p.edgeAt_incident x y).mp h with rfl | rfl + · rfl + · exact p.edgeAt_mate x + +noncomputable def ColoredPairing.toPM (p : ColoredPairing bags) : PM (BagEdge.Incident (bags := bags)) := + ⟨Finset.univ.image p.edgeAt,by + constructor + · intros; exact Finset.mem_univ _ + · intro x hx + refine ⟨p.edgeAt x,⟨Finset.mem_image.mpr ⟨x,Finset.mem_univ _,rfl⟩,?_⟩,?_⟩ + · exact (p.edgeAt_incident x x).mpr (Or.inl rfl) + · intro e he + obtain ⟨y,hy,rfl⟩ := Finset.mem_image.mp he.1 + exact (p.edgeAt_of_incident y x he.2).symm⟩ + +noncomputable def chosenEdge (M : PM (BagEdge.Incident (bags := bags))) (x : V) : BagEdge bags := + Classical.choose (M.property.2 x (Finset.mem_univ x)) + +omit [Fintype L] [DecidableEq V] [DecidableEq L] in +lemma chosenEdge_spec [Fintype L] [DecidableEq V] [DecidableEq L] + (M : PM (BagEdge.Incident (bags := bags))) (x : V) : + chosenEdge M x ∈ M.val ∧ (chosenEdge M x).Incident x := + (Classical.choose_spec (M.property.2 x (Finset.mem_univ x))).1 + +omit [Fintype L] [DecidableEq V] [DecidableEq L] in +lemma chosenEdge_unique [Fintype L] [DecidableEq V] [DecidableEq L] + (M : PM (BagEdge.Incident (bags := bags))) (x : V) (e : BagEdge bags) + (he : e ∈ M.val) (hx : e.Incident x) : e=chosenEdge M x := + (Classical.choose_spec (M.property.2 x (Finset.mem_univ x))).2 e ⟨he,hx⟩ + +noncomputable def chosenMate (M : PM (BagEdge.Incident (bags := bags))) (x : V) : V := + Sym2.Mem.other (chosenEdge_spec M x).2 + +lemma chosenMate_pair (M : PM (BagEdge.Incident (bags := bags))) (x : V) : + s(x,chosenMate M x)=(chosenEdge M x).val.val.1 := Sym2.other_spec _ + +lemma chosenMate_ne (M : PM (BagEdge.Incident (bags := bags))) (x : V) : chosenMate M x ≠ x := + Sym2.other_ne (chosenEdge M x).val.property _ + +lemma chosenEdge_chosenMate (M : PM (BagEdge.Incident (bags := bags))) (x : V) : + chosenEdge M (chosenMate M x)=chosenEdge M x := by + symm + apply chosenEdge_unique M _ _ (chosenEdge_spec M x).1 + exact Sym2.other_mem (chosenEdge_spec M x).2 + +lemma chosenMate_involutive (M : PM (BagEdge.Incident (bags := bags))) : + Function.Involutive (chosenMate M) := by + intro x + have h := chosenMate_pair M (chosenMate M x) + rw [chosenEdge_chosenMate,←chosenMate_pair M x] at h + rcases Sym2.eq_iff.mp h with h | h + · exact False.elim (chosenMate_ne M x h.1) + · exact h.2 + +noncomputable def fromPM (M : PM (BagEdge.Incident (bags := bags))) : ColoredPairing bags where + pair := ⟨chosenMate M,chosenMate_involutive M,chosenMate_ne M⟩ + color x := (chosenEdge M x).val.color + allowed x := (chosenEdge M x).property x (chosenEdge_spec M x).2 + same_color x := congrArg (fun e : BagEdge bags => e.val.color) (chosenEdge_chosenMate M x) + +lemma fromPM_edgeAt (M : PM (BagEdge.Incident (bags := bags))) (x : V) : + (fromPM M).edgeAt x=chosenEdge M x := by + apply Subtype.ext + apply Subtype.ext + exact Prod.ext (chosenMate_pair M x) rfl + +lemma chosenEdge_toPM (p : ColoredPairing bags) (x : V) : chosenEdge p.toPM x=p.edgeAt x := by + symm + apply chosenEdge_unique + · exact Finset.mem_image.mpr ⟨x,Finset.mem_univ _,rfl⟩ + · exact (p.edgeAt_incident x x).mpr (Or.inl rfl) + +noncomputable def coloredPMEquiv : PM (BagEdge.Incident (bags := bags)) ≃ ColoredPairing bags where + toFun := fromPM + invFun := ColoredPairing.toPM + left_inv M := by + apply Subtype.ext + ext e + constructor + · intro he + obtain ⟨x,hx,rfl⟩ := Finset.mem_image.mp he + rw [fromPM_edgeAt] + exact (chosenEdge_spec M x).1 + · intro he + obtain ⟨x,hx⟩ := e.exists_incident + apply Finset.mem_image.mpr + exact ⟨x,Finset.mem_univ _,(fromPM_edgeAt M x).trans (chosenEdge_unique M x e he hx).symm⟩ + right_inv p := by + apply ColoredPairing.ext + · ext x + change chosenMate p.toPM x=p.pair.mate x + have h := chosenMate_pair p.toPM x + rw [chosenEdge_toPM] at h + change s(x,chosenMate p.toPM x)=s(x,p.pair.mate x) at h + exact Sym2.congr_right.mp h + · funext x + change (chosenEdge p.toPM x).val.color=p.color x + rw [chosenEdge_toPM] + rfl + +theorem unit_partition_assignments : + Fintype.card (PM (BagEdge.Incident (bags := bags))) = + ∑ f : Assignment bags, ∏ l : L, pairingCount (Fintype.card {x : V // f.val x=l}) := by + classical + rw [Fintype.card_congr (coloredPMEquiv (bags := bags)),coloredPairing_card] + + + +open Finset + +variable {U S W L : Type*} [Fintype U] [Fintype S] [Fintype W] [Fintype L] + [DecidableEq U] [DecidableEq S] [DecidableEq W] [DecidableEq L] + +def leafBags (l p : L) (b : W → Finset L) : U ⊕ S ⊕ W → Finset L + | Sum.inl _ => {l} + | Sum.inr (Sum.inl _) => {l,p} + | Sum.inr (Sum.inr x) => b x + +noncomputable def fiberCount {V : Type*} [Fintype V] (f : V → L) (l : L) : ℕ := + Fintype.card {x : V // f x=l} + +noncomputable def assignmentPartition {V : Type*} [Fintype V] [DecidableEq V] + (b : V → Finset L) (w : L → ℕ → ℕ) : ℕ := + by classical exact ∑ f : Assignment b, ∏ l,w l (fiberCount f.val l) + +def leafAssignment (l p : L) (b : W → Finset L) (T : Finset S) (f : Assignment b) : + Assignment (leafBags (U := U) (S := S) l p b) := + ⟨Sum.elim (fun _ => l) (Sum.elim (fun x => if x∈T then l else p) f.val),by + intro x + rcases x with x | (x | x) + · simp [leafBags] + · by_cases hx : x∈T <;> simp [leafBags,hx] + · exact f.property x⟩ + +noncomputable def leafAssignmentEquiv (l p : L) (hlp : l≠p) (b : W → Finset L) : + Assignment (leafBags (U := U) (S := S) l p b) ≃ (Finset S) × Assignment b where + toFun f := (univ.filter fun x => f.val (Sum.inr (Sum.inl x))=l, + ⟨fun x => f.val (Sum.inr (Sum.inr x)),fun x => f.property _⟩) + invFun q := leafAssignment l p b q.1 q.2 + left_inv f := by + apply Subtype.ext + funext x + rcases x with x | (x | x) + · have hf := f.property (Sum.inl x) + have hfl : f.val (Sum.inl x)=l := by simpa [leafBags] using hf + simpa [leafAssignment] using hfl.symm + · by_cases h : f.val (Sum.inr (Sum.inl x))=l + · simp [leafAssignment,h] + · have hf := f.property (Sum.inr (Sum.inl x)) + simp only [leafBags,mem_insert,mem_singleton] at hf + simp [leafAssignment,hf.resolve_left h,hlp.symm] + · rfl + right_inv q := by + apply Prod.ext + · ext x + by_cases hx : x∈q.1 <;> simp [leafAssignment,hx,hlp.symm] + · rfl + +omit [Fintype L] in +lemma fiberCount_sum [Fintype L] {A B : Type*} [Fintype A] [Fintype B] (f : A ⊕ B → L) (l : L) : + fiberCount f l = fiberCount (fun x : A => f (Sum.inl x)) l + + fiberCount (fun x : B => f (Sum.inr x)) l := by + unfold fiberCount + rw [Fintype.card_congr Equiv.subtypeSum,Fintype.card_sum] + +omit [Fintype L] [DecidableEq U] in +lemma fiberCount_const [Fintype L] [DecidableEq U] + (a l : L) : fiberCount (fun _ : U => a) l = if a=l then Fintype.card U else 0 := by + classical + by_cases h : a=l <;> simp [fiberCount,h] + +omit [Fintype L] in +lemma fiberCount_zero [Fintype L] {A : Type*} [Fintype A] (f : A → L) (l : L) (h : ∀ x,f x≠l) : + fiberCount f l=0 := by + classical + simp [fiberCount,h] + +omit [DecidableEq W] in +lemma fiberCount_leaf [DecidableEq W] (l p : L) (hlp : l≠p) (b : W → Finset L) + (hb : ∀ x,l∉b x) (T : Finset S) (f : Assignment b) : + fiberCount (leafAssignment (U := U) l p b T f).val l = Fintype.card U+T.card := by + rw [fiberCount_sum,fiberCount_sum] + have hz : fiberCount f.val l=0 := fiberCount_zero _ _ (fun x h => hb x (h ▸ f.property x)) + change fiberCount (fun _ : U => l) l + + (fiberCount (fun x : S => if x∈T then l else p) l + fiberCount f.val l)=_ + rw [fiberCount_const,ite_eq_left rfl,hz,Nat.add_zero] + congr 1 + unfold fiberCount + rw [Fintype.card_congr (Equiv.subtypeEquivRight (q := fun x => x∈T) (fun x => by simp [hlp.symm]))] + exact Fintype.card_coe T + +omit [DecidableEq W] in +lemma fiberCount_parent [DecidableEq W] (l p : L) (hlp : l≠p) (b : W → Finset L) + (T : Finset S) (f : Assignment b) : + fiberCount (leafAssignment (U := U) l p b T f).val p = + Fintype.card S-T.card+fiberCount f.val p := by + rw [fiberCount_sum,fiberCount_sum] + change fiberCount (fun _ : U => l) p + + (fiberCount (fun x : S => if x∈T then l else p) p + fiberCount f.val p)=_ + rw [fiberCount_const,ite_eq_right hlp,Nat.zero_add] + congr 1 + unfold fiberCount + rw [Fintype.card_congr (Equiv.subtypeEquivRight (q := fun x => x∉T) (fun x => by simp [hlp]))] + rw [Fintype.card_subtype_compl,Fintype.card_coe] + +omit [DecidableEq W] in +lemma fiberCount_other [DecidableEq W] (l p a : L) (hal : a≠l) (hap : a≠p) (b : W → Finset L) + (T : Finset S) (f : Assignment b) : + fiberCount (leafAssignment (U := U) l p b T f).val a = fiberCount f.val a := by + rw [fiberCount_sum,fiberCount_sum] + change fiberCount (fun _ : U => l) a + + (fiberCount (fun x : S => if x∈T then l else p) a + fiberCount f.val a)=_ + rw [fiberCount_const,ite_eq_right hal.symm] + have hz : fiberCount (fun x : S => if x∈T then l else p) a=0 := by + apply fiberCount_zero + intro x + split_ifs + · exact hal.symm + · exact hap.symm + simp [hz] + +lemma prod_split_two (l p : L) (hlp : l≠p) (f : L → ℕ) : + (∏ a,f a)=f l*f p*(∏ a∈(univ.erase l).erase p,f a) := by + rw [←prod_erase_mul univ f (mem_univ l), + ←prod_erase_mul (univ.erase l) f (mem_erase.mpr ⟨hlp.symm,mem_univ p⟩)] + ac_rfl + +lemma leaf_assignment_weight (l p : L) (hlp : l≠p) (b : W → Finset L) + (hb : ∀ x,l∉b x) (w : L → ℕ → ℕ) (T : Finset S) (f : Assignment b) : + (∏ a,w a (fiberCount (leafAssignment (U := U) l p b T f).val a)) = + w l (Fintype.card U+T.card) * w p (Fintype.card S-T.card+fiberCount f.val p) * + (∏ a∈(univ.erase l).erase p,w a (fiberCount f.val a)) := by + rw [prod_split_two l p hlp,fiberCount_leaf l p hlp b hb,fiberCount_parent l p hlp] + congr 1 + apply prod_congr rfl + intro a ha + rw [fiberCount_other _ _ _ (mem_erase.mp (mem_erase.mp ha).2).1 (mem_erase.mp ha).1] + +omit [DecidableEq S] in +lemma sum_finset_card [DecidableEq S] (g : ℕ → ℕ) : + (∑ T : Finset S,g T.card)=∑ k∈range (Fintype.card S+1),(Fintype.card S).choose k*g k := by + classical + have hu : (univ : Finset (Finset S))=(univ : Finset S).powerset := by ext T; simp + rw [hu,sum_powerset] + apply sum_congr rfl + intro k hk + simpa using (sum_powersetCard k (univ : Finset S) g) + +noncomputable def leafUpdate (u s : ℕ) (l p : L) (w : L → ℕ → ℕ) : L → ℕ → ℕ := + fun a r => if a=l then 1 else if a=p then + ∑ k∈range (s+1),s.choose k*w l (u+k)*w p (s-k+r) else w a r + +theorem leaf_elimination (l p : L) (hlp : l≠p) (b : W → Finset L) + (hb : ∀ x,l∉b x) (w : L → ℕ → ℕ) : + assignmentPartition (leafBags (U := U) (S := S) l p b) w = + assignmentPartition b (leafUpdate (Fintype.card U) (Fintype.card S) l p w) := by + classical + unfold assignmentPartition + calc + _ = ∑ q : Finset S × Assignment b, + ∏ a,w a (fiberCount (leafAssignment (U := U) l p b q.1 q.2).val a) := by + apply Fintype.sum_equiv (leafAssignmentEquiv l p hlp b) + intro f + exact congrArg (fun q : Assignment (leafBags (U := U) (S := S) l p b) => + ∏ a,w a (fiberCount q.val a)) ((leafAssignmentEquiv l p hlp b).left_inv f).symm + _ = _ := by + rw [Fintype.sum_prod_type,sum_comm] + apply sum_congr rfl + intro f hf + simp_rw [leaf_assignment_weight l p hlp b hb w] + rw [sum_finset_card (S:=S) (fun k => + w l (Fintype.card U+k)*w p (Fintype.card S-k+fiberCount f.val p)* + (∏ a∈(univ.erase l).erase p,w a (fiberCount f.val a)))] + rw [prod_split_two l p hlp] + have he : (∏ a∈(univ.erase l).erase p, + leafUpdate (Fintype.card U) (Fintype.card S) l p w a (fiberCount f.val a)) = + ∏ a∈(univ.erase l).erase p,w a (fiberCount f.val a) := by + apply prod_congr rfl + intro a ha + simp only [leafUpdate,ite_eq_right (mem_erase.mp (mem_erase.mp ha).2).1, + ite_eq_right (mem_erase.mp ha).1] + rw [he] + simp only [leafUpdate,ite_true,ite_eq_right hlp.symm,one_mul] + rw [sum_mul] + apply sum_congr rfl + intro k hk + ac_rfl + +end MatchingFPRAS.UnitRefresh + +end OAI diff --git a/lean/OAI/Combinatorics/MatchingCount/Graphs/EdgeLow.lean b/lean/OAI/Combinatorics/MatchingCount/Graphs/EdgeLow.lean new file mode 100644 index 0000000000000000000000000000000000000000..cbfc53f2bccb247f0665fe73282fc70ab150a8a6 --- /dev/null +++ b/lean/OAI/Combinatorics/MatchingCount/Graphs/EdgeLow.lean @@ -0,0 +1,517 @@ +import Mathlib +import OAI.Combinatorics.MatchingCount.Graphs.Incident +import OAI.Combinatorics.MatchingCount.Graphs.Height + +namespace OAI + +namespace MatchingFPRAS.Transport + +section + +open Finset MatchingFPRAS.Switching + +variable {V E : Type*} [Fintype V] [LinearOrder V] + +variable (edge : E → Sym2 V) (hnd : ∀ e, ¬(edge e).IsDiag) + +local notation "inc" => (fun (e : E) (x : V) => x ∈ edge e) + +noncomputable def edgeLow (s : Sym2 V) : V := Sym2.lift ⟨min,min_comm⟩ s + +noncomputable def edgeHigh (s : Sym2 V) : V := Sym2.lift ⟨max,max_comm⟩ s + +omit [Fintype V] in +@[simp] lemma edgeLow_mk (x y : V) : edgeLow s(x,y)=min x y := rfl + +omit [Fintype V] in +@[simp] lemma edgeHigh_mk (x y : V) : edgeHigh s(x,y)=max x y := rfl + +omit [Fintype V] in +lemma edgeLow_mem (s : Sym2 V) : edgeLow s ∈ s := by + induction s using Sym2.inductionOn with + | hf x y => by_cases h : x≤y <;> simp [min_def,h] + +omit [Fintype V] in +lemma edgeHigh_mem (s : Sym2 V) : edgeHigh s ∈ s := by + induction s using Sym2.inductionOn with + | hf x y => by_cases h : x≤y <;> simp [max_def,h] + +omit [Fintype V] in +lemma edge_low_high (s : Sym2 V) : s(edgeLow s,edgeHigh s)=s := by + induction s using Sym2.inductionOn with + | hf x y => by_cases h : x≤y <;> simp [min_def,max_def,h,Sym2.eq_swap] + +omit [Fintype V] in +lemma edgeLow_lt_high (s : Sym2 V) (hs : ¬s.IsDiag) : edgeLow s < edgeHigh s := by + induction s using Sym2.inductionOn with + | hf x y => + have hxy : x ≠ y := by simpa using hs + rcases hxy.lt_or_gt with h | h <;> simp [h.le,h] + +variable (Q : Partial (fun (e : E) (x : V) => x ∈ edge e)) + +omit [Fintype V] in +lemma edgeLow_ne_high (s : Sym2 V) (hs : ¬s.IsDiag) : edgeLow s ≠ edgeHigh s := + (edgeLow_lt_high s hs).ne + +noncomputable def pickedEdge (x : V) (hx : x ∈ support inc Q.val) : E := + Classical.choose (Q.property.2 x hx) + +omit [LinearOrder V] in +lemma pickedEdge_spec (x : V) (hx : x ∈ support inc Q.val) : + pickedEdge edge Q x hx ∈ Q.val ∧ x ∈ edge (pickedEdge edge Q x hx) := + (Classical.choose_spec (Q.property.2 x hx)).1 + +omit [LinearOrder V] in +lemma pickedEdge_unique (x : V) (hx : x ∈ support inc Q.val) (e : E) + (he : e∈Q.val) (hxe : x ∈ edge e) : e=pickedEdge edge Q x hx := + (Classical.choose_spec (Q.property.2 x hx)).2 e ⟨he,hxe⟩ + +noncomputable def partialMateFun (x : V) : V := + if hx : x∈support inc Q.val then Sym2.Mem.other (pickedEdge_spec edge Q x hx).2 else x + +lemma partialMateFun_out (x : V) (hx : x∉support inc Q.val) : partialMateFun edge Q x=x := by + simp [partialMateFun,hx] + +include hnd in +lemma partialMateFun_ne (x : V) (hx : x∈support inc Q.val) : partialMateFun edge Q x≠x := by + simp only [partialMateFun,dite_eq_left hx] + exact Sym2.other_ne (hnd _) _ + +lemma partialMateFun_pair (x : V) (hx : x∈support inc Q.val) : + s(x,partialMateFun edge Q x)=edge (pickedEdge edge Q x hx) := by + simp only [partialMateFun,dite_eq_left hx] + exact Sym2.other_spec _ + +lemma partialMateFun_incident (e : E) (he : e∈Q.val) (x : V) (hx : x∈edge e) : + s(x,partialMateFun edge Q x)=edge e := by + have hxQ := (mem_support inc Q.val x).mpr ⟨e,he,hx⟩ + rw [partialMateFun_pair edge Q x hxQ,←pickedEdge_unique edge Q x hxQ e he hx] + +lemma partialMateFun_covered (x : V) (hx : x∈support inc Q.val) : + partialMateFun edge Q x ∈ support inc Q.val := by + apply (mem_support inc Q.val _).mpr + refine ⟨pickedEdge edge Q x hx,(pickedEdge_spec edge Q x hx).1,?_⟩ + rw [←partialMateFun_pair edge Q x hx] + simp + +include hnd in +lemma partialMateFun_involutive : Function.Involutive (partialMateFun edge Q) := by + intro x + by_cases hx : x∈support inc Q.val + · have h₁ := partialMateFun_pair edge Q x hx + have hi : partialMateFun edge Q x ∈ edge (pickedEdge edge Q x hx) := by rw [←h₁]; simp + have h₂ := partialMateFun_incident edge Q (pickedEdge edge Q x hx) + (pickedEdge_spec edge Q x hx).1 _ hi + rcases Sym2.eq_iff.mp (h₂.trans h₁.symm) with h | h + · exact False.elim (partialMateFun_ne edge hnd Q x hx h.1) + · exact h.2 + · rw [partialMateFun_out edge Q x hx,partialMateFun_out edge Q x hx] + +noncomputable def partialMate : Mate V := ⟨partialMateFun edge Q,partialMateFun_involutive edge hnd Q⟩ + +lemma partialMate_holes : HasHoles (partialMate edge hnd Q) (support inc Q.val)ᶜ := by + intro x + change partialMateFun edge Q x=x ↔ _ + rw [Finset.mem_compl] + constructor + · intro h hx; exact partialMateFun_ne edge hnd Q x hx h + · exact partialMateFun_out edge Q x + +lemma partialMate_low (e : E) (he : e∈Q.val) : + partialMateFun edge Q (edgeLow (edge e))=edgeHigh (edge e) := by + have h := partialMateFun_incident edge Q e he _ (edgeLow_mem _) + exact Sym2.congr_right.mp (h.trans (edge_low_high (edge e)).symm) + +lemma partial_low_mem (e : E) (he : e∈Q.val) : + edgeLow (edge e) ∈ univ.filter (fun x => x < (partialMate edge hnd Q).val x) := by + simp only [Finset.mem_filter,Finset.mem_univ,true_and] + change edgeLow (edge e) < partialMateFun edge Q (edgeLow (edge e)) + rw [partialMate_low edge Q e he] + exact edgeLow_lt_high _ (hnd e) + +lemma partial_low_injective (e : E) (he : e∈Q.val) (f : E) (hf : f∈Q.val) + (h : edgeLow (edge e)=edgeLow (edge f)) : e=f := by + have hx := edgeLow_mem (edge e) + exact Q.property.unique (Q.property.1 e he _ hx) he hx hf (h.symm ▸ edgeLow_mem (edge f)) + +lemma partial_low_surjective (x : V) + (hx : x ∈ univ.filter (fun x => x < (partialMate edge hnd Q).val x)) : + ∃ e, ∃ _ : e∈Q.val, edgeLow (edge e)=x := by + have hx' : x < partialMateFun edge Q x := (Finset.mem_filter.mp hx).2 + have hcov : x∈support inc Q.val := by + by_contra hn + rw [partialMateFun_out edge Q x hn] at hx' + exact lt_irrefl _ hx' + refine ⟨pickedEdge edge Q x hcov,(pickedEdge_spec edge Q x hcov).1,?_⟩ + rw [←partialMateFun_pair edge Q x hcov,edgeLow_mk,min_eq_left hx'.le] + +include hnd in +lemma partial_card : (support inc Q.val).card=2*Q.val.card := by + have hcard := Finset.card_bij (fun e _ => edgeLow (edge e)) + (partial_low_mem edge hnd Q) (partial_low_injective edge Q) + (partial_low_surjective edge hnd Q) + have hmate := mate_edge_count (partialMate edge hnd Q) (support inc Q.val) + (partialMate_holes edge hnd Q) + omega + +include hnd in +lemma partial_even : Even (support inc Q.val).card := by + rw [partial_card edge hnd Q] + exact even_two_mul _ + +lemma partial_weight (B : V → V → ℝ) : + (∏ e ∈ Q.val, B (edgeLow (edge e)) (edgeHigh (edge e)))=weight B (partialMate edge hnd Q) := by + classical + unfold weight + rw [←Finset.prod_filter] + apply Finset.prod_bij (fun e _ => edgeLow (edge e)) + (partial_low_mem edge hnd Q) (partial_low_injective edge Q) + (partial_low_surjective edge hnd Q) + intro e he + change B _ _ = B _ (partialMateFun edge Q _) + rw [partialMate_low edge Q e he] + +theorem partial_height_le_capacity (B : V → V → ℝ) (height : E → ℝ) + (h0 : ∀ e, 0≤height e) + (hh : ∀ e, height e ≤ B (edgeLow (edge e)) (edgeHigh (edge e))) : + (∏ e ∈ Q.val, height e) ≤ pairingCapacity B (support inc Q.val) (partial_even edge hnd Q) := by + calc + _ ≤ ∏ e ∈ Q.val, B (edgeLow (edge e)) (edgeHigh (edge e)) := + Finset.prod_le_prod₀ (fun e _ => h0 e) (fun e _ => hh e) + _ = weight B (partialMate edge hnd Q) := partial_weight edge hnd Q B + _ ≤ _ := Finset.le_sup' (f := weight B) ((mem_matchings _ _).mpr (partialMate_holes edge hnd Q)) + +end + +section + +open Finset + +variable {V L : Type*} [Fintype V] [Fintype L] [LinearOrder V] [DecidableEq L] + +variable (bags : V → Finset L) + +noncomputable local instance edgeLowCardinalityBagEdgeFintype : Fintype (BagEdge bags) := + Fintype.ofFinite _ + +noncomputable def bagEdgeSigmaEquiv : BagEdge bags ≃ + Σ s : {s : Sym2 V // ¬s.IsDiag}, {l : L // ∀ x, x∈s.val → l∈bags x} where + toFun e := ⟨⟨e.val.val.1,e.val.property⟩,⟨e.val.val.2,e.property⟩⟩ + invFun a := ⟨⟨(a.1.val,a.2.val),a.1.property⟩,a.2.property⟩ + left_inv _ := rfl + right_inv _ := rfl + +lemma bag_color_card_le_two (hb : ∀ x,(bags x).card≤2) (s : {s : Sym2 V // ¬s.IsDiag}) : + Fintype.card {l : L // ∀ x, x∈s.val → l∈bags x} ≤ 2 := by + let f : {l : L // ∀ x, x∈s.val → l∈bags x} → {l : L // l∈bags (edgeLow s.val)} := + fun l => ⟨l.val,l.property _ (edgeLow_mem _)⟩ + have hi : Function.Injective f := by + intro a b h + apply Subtype.ext + exact congrArg (fun z : {l : L // l∈bags (edgeLow s.val)} => z.val) h + have := Fintype.card_le_of_injective f hi + rw [Fintype.card_coe] at this + exact this.trans (hb _) + +theorem bagEdge_card_le_square (hb : ∀ x,(bags x).card≤2) : + Fintype.card (BagEdge bags) ≤ (Fintype.card V)^2 := by + classical + rw [Fintype.card_congr (bagEdgeSigmaEquiv bags),Fintype.card_sigma] + calc + _ ≤ ∑ _s : {s : Sym2 V // ¬s.IsDiag}, 2 := + Finset.sum_le_sum (fun s _ => bag_color_card_le_two bags hb s) + _ = 2*(Fintype.card V).choose 2 := by + rw [Finset.sum_const,Finset.card_univ,smul_eq_mul,Sym2.card_subtype_not_diag,mul_comm] + _ ≤ Fintype.card V*(Fintype.card V-1) := by rw [Nat.choose_two_right]; omega + _ ≤ (Fintype.card V)^2 := by + rw [pow_two] + exact Nat.mul_le_mul_left _ (Nat.sub_le _ _) + +end + +open Finset MatchingFPRAS.Switching + +variable {V L : Type*} [Fintype V] [Fintype L] [LinearOrder V] [DecidableEq L] + +variable (bags : V → Finset L) + +noncomputable local instance edgeLowInflationBagEdgeFintype : Fintype (BagEdge bags) := + Fintype.ofFinite _ + +def inflationScale (D₀ : ℝ) : ℝ := 100*(Fintype.card V : ℝ)^2*D₀ + +theorem bag_inflation_of_hole_estimate (hN : 0 r e+height e.val.val.2/D) univ / + partitionWeight BagEdge.Incident r univ ∧ + partitionWeight BagEdge.Incident (fun e => r e+height e.val.val.2/D) univ / + partitionWeight BagEdge.Incident r univ ≤ 2 := by + classical + let D := inflationScale (V := V) D₀ + have hNp : 0<(Fintype.card V:ℝ) := Nat.cast_pos.mpr hN + have hD : 0 height e.val.val.2/D) hr + (fun e => div_nonneg (hheight _) hD.le) + (fun e => ⟨edgeLow e.val.val.1,edgeLow_mem _⟩) hz (D₀/D) (div_nonneg hD₀.le hD.le) + · have hcard : (Fintype.card (BagEdge bags):ℝ) ≤ (Fintype.card V:ℝ)^2 := by + exact_mod_cast bagEdge_card_le_square bags hb + rw [←mul_div_assoc] + apply (div_le_iff₀ hD).mpr + change (Fintype.card (BagEdge bags):ℝ)*D₀ ≤ 1/100*D + dsimp [D,inflationScale] + nlinarith [mul_le_mul_of_nonneg_right hcard hD₀.le] + · intro Q _ + let edge : BagEdge bags → Sym2 V := fun e => e.val.val.1 + have hnd : ∀ e,¬(edge e).IsDiag := fun e => e.val.property + have heven := partial_even edge hnd Q + let g := partitionWeight BagEdge.Incident r (univ \ support BagEdge.Incident Q.val) / + partitionWeight BagEdge.Incident r univ + have hg : 0≤g := div_nonneg (partitionWeight_nonneg _ r hr _) hz.le + have hc := partial_height_le_capacity edge hnd Q B (fun e => height e.val.val.2) + (fun e => hheight _) hcommon + have hh := hhole _ heven + have hcard := partial_card edge hnd Q + change (support BagEdge.Incident Q.val).card=2*Q.val.card at hcard + change g * pairingCapacity B (support BagEdge.Incident Q.val) heven ≤ 2*D₀^((support BagEdge.Incident Q.val).card/2) at hh + have hpow : (support BagEdge.Incident Q.val).card/2=Q.val.card := by omega + rw [hpow] at hh + rw [Finset.prod_div_distrib,Finset.prod_const] + change (∏ e∈Q.val,height e.val.val.2) / D^Q.val.card * + partitionWeight BagEdge.Incident r (univ \ support BagEdge.Incident Q.val) / + partitionWeight BagEdge.Incident r univ ≤ _ + calc + _ = g*(∏ e∈Q.val,height e.val.val.2) / D^Q.val.card := by dsimp [g]; ring + _ ≤ g*pairingCapacity B (support BagEdge.Incident Q.val) heven / D^Q.val.card := + div_le_div_of_nonneg_right (mul_le_mul_of_nonneg_left hc hg) (pow_nonneg hD.le _) + _ ≤ (2*D₀^Q.val.card)/D^Q.val.card := div_le_div_of_nonneg_right hh (pow_nonneg hD.le _) + _ = 2*(D₀/D)^Q.val.card := by rw [div_pow]; ring + +end MatchingFPRAS.Transport + +namespace MatchingFPRAS.RealGeometry + +open Finset MatchingFPRAS.Subdivision MatchingFPRAS.Transport + +variable {V E : Type*} [Fintype V] [Fintype E] [DecidableEq V] [DecidableEq E] + +variable (u v : E → V) (m : ℕ) + +omit [Fintype V] [Fintype E] [DecidableEq V] [DecidableEq E] in +lemma edge_incident_internal (q : E × Fin (m+1)) (e : E) (i : Fin m) : + Sum.inr (e,i) ∈ edge u v m q.1 q.2 ↔ q=(e,i.castSucc) ∨ q=(e,i.succ) := by + simp only [edge,Sym2.mem_iff,eq_comm (a := Sum.inr _) ] + rw [atVertex_eq_inr_iff,atVertex_eq_inr_iff] + simp only [Fin.val_castSucc,Fin.val_succ,Prod.ext_iff] + constructor + · rintro (⟨h,h'⟩|⟨h,h'⟩) + · exact Or.inr ⟨h,Fin.ext h'⟩ + · exact Or.inl ⟨h,Fin.ext (show q.2.val=i.val by omega)⟩ + · rintro (⟨h,h'⟩|⟨h,h'⟩) + · exact Or.inr ⟨h,by have := congrArg Fin.val h'; simpa using this⟩ + · exact Or.inl ⟨h,by have := congrArg Fin.val h'; simpa using this⟩ + +omit [Fintype V] [Fintype E] [DecidableEq V] [DecidableEq E] in +lemma edge_incident_terminal (q : E × Fin (m+1)) (x : V) : + Sum.inl x ∈ edge u v m q.1 q.2 ↔ + (q.2=0 ∧ u q.1=x) ∨ (q.2=Fin.last m ∧ v q.1=x) := by + simp only [edge,Sym2.mem_iff,eq_comm (a := Sum.inl _)] + rw [first_vertex_terminal,second_vertex_terminal] + simp only [Fin.ext_iff,Fin.val_zero,Fin.val_last] + +noncomputable def selectedSet (b : E → Selection m) : Finset (E × Fin (m+1)) := by + classical + exact univ.filter fun q => b q.1 q.2=true + +omit [DecidableEq E] in +@[simp] lemma mem_selectedSet (b : E → Selection m) (q : E × Fin (m+1)) : + q∈selectedSet m b ↔ b q.1 q.2=true := by + simp [selectedSet] + +noncomputable def survivors (R : Finset V) (U : E → Finset (Fin m)) : Finset (Vertex V E m) := by + classical + exact univ.filter fun x => match x with + | Sum.inl x => x∉R + | Sum.inr (e,i) => i∉U e + +omit [DecidableEq V] [DecidableEq E] in +@[simp] lemma mem_survivors_terminal (R : Finset V) (U : E → Finset (Fin m)) (x : V) : + Sum.inl x ∈ survivors m R U ↔ x∉R := by simp [survivors] + +omit [DecidableEq V] [DecidableEq E] in +@[simp] lemma mem_survivors_internal (R : Finset V) (U : E → Finset (Fin m)) (e : E) (i : Fin m) : + Sum.inr (e,i) ∈ survivors m R U ↔ i∉U e := by simp [survivors] + +omit [Fintype V] [DecidableEq V] [DecidableEq E] in +lemma internal_unique_iff (b : E → Selection m) (e : E) (i : Fin m) : + (∃! q, q∈selectedSet m b ∧ Sum.inr (e,i)∈edge u v m q.1 q.2) ↔ + b e i.castSucc ≠ b e i.succ := by + simp only [mem_selectedSet,edge_incident_internal] + have hne : i.castSucc≠i.succ := by intro h; have := congrArg Fin.val h; simp at this + cases h₁ : b e i.castSucc <;> cases h₂ : b e i.succ <;> simp only [ne_eq,Bool.false_eq_true, + not_false_eq_true,Bool.true_eq_false,not_true_eq_false,iff_false,iff_true] + · rintro ⟨q,hq,_⟩; rcases hq.2 with rfl|rfl <;> simp_all + · refine ⟨(e,i.succ),⟨h₂,Or.inr rfl⟩,?_⟩ + rintro ⟨f,j⟩ ⟨hs,hq⟩ + rcases hq with hq|hq + · cases hq; simp_all + · exact hq + · refine ⟨(e,i.castSucc),⟨h₁,Or.inl rfl⟩,?_⟩ + rintro ⟨f,j⟩ ⟨hs,hq⟩ + rcases hq with hq|hq + · exact hq + · cases hq; simp_all + · rintro ⟨q,hq,hu⟩ + have h := (hu (e,i.castSucc) ⟨h₁,Or.inl rfl⟩).trans (hu (e,i.succ) ⟨h₂,Or.inr rfl⟩).symm + exact hne (congrArg Prod.snd h) + +omit [Fintype V] [DecidableEq V] [DecidableEq E] in +lemma terminal_selected_iff (b : E → Selection m) (q : E × Fin (m+1)) (x : V) : + q∈selectedSet m b ∧ Sum.inl x∈edge u v m q.1 q.2 ↔ + (q.2=0 ∧ b q.1 0=true ∧ u q.1=x) ∨ + (q.2=Fin.last m ∧ b q.1 (Fin.last m)=true ∧ v q.1=x) := by + rw [mem_selectedSet,edge_incident_terminal] + constructor + · rintro ⟨hs, (⟨h₀,hu⟩|⟨hm,hv⟩)⟩ + · exact Or.inl ⟨h₀,h₀ ▸ hs,hu⟩ + · exact Or.inr ⟨hm,hm ▸ hs,hv⟩ + · rintro (⟨h₀,hs,hu⟩|⟨hm,hs,hv⟩) + · exact ⟨h₀ ▸ hs,Or.inl ⟨h₀,hu⟩⟩ + · exact ⟨hm ▸ hs,Or.inr ⟨hm,hv⟩⟩ + +omit [Fintype V] [DecidableEq V] [DecidableEq E] in +lemma terminal_unique_iff (huv : ∀ e,u e≠v e) (b : E → Selection m) (x : V) : + (∃! q, q∈selectedSet m b ∧ Sum.inl x∈edge u v m q.1 q.2) ↔ + (∃! e, Uses u v b e x) := by + constructor + · rintro ⟨q,hq,hunique⟩ + rw [terminal_selected_iff] at hq + have huse : Uses u v b q.1 x := by rcases hq with h|h; exact Or.inl h.2; exact Or.inr h.2 + refine ⟨q.1,huse,?_⟩ + intro f hf + rcases hf with hf|hf + · exact congrArg Prod.fst (hunique (f,0) ((terminal_selected_iff _ _ _ _ _ _).mpr (Or.inl ⟨rfl,hf⟩))) + · exact congrArg Prod.fst (hunique (f,Fin.last m) ((terminal_selected_iff _ _ _ _ _ _).mpr (Or.inr ⟨rfl,hf⟩))) + · rintro ⟨e,he,hu⟩ + have uniq (i : Fin (m+1)) (hi : (e,i)∈selectedSet m b ∧ Sum.inl x∈edge u v m e i) + (q : E × Fin (m+1)) (hq : q∈selectedSet m b ∧ Sum.inl x∈edge u v m q.1 q.2) : q=(e,i) := by + rw [terminal_selected_iff] at hi hq + have hf : q.1=e := hu q.1 (by rcases hq with h|h; exact Or.inl h.2; exact Or.inr h.2) + apply Prod.ext hf + rcases hi with hi|hi <;> rcases hq with hq|hq + · exact hq.1.trans hi.1.symm + · exact False.elim (huv e (hi.2.2.trans (hf ▸ hq.2.2).symm)) + · exact False.elim (huv e ((hf ▸ hq.2.2).trans hi.2.2.symm)) + · exact hq.1.trans hi.1.symm + rcases he with he|he + · have hi := (terminal_selected_iff u v m b (e,0) x).mpr (Or.inl ⟨rfl,he⟩) + exact ⟨(e,0),hi,uniq 0 hi⟩ + · have hi := (terminal_selected_iff u v m b (e,Fin.last m) x).mpr (Or.inr ⟨rfl,he⟩) + exact ⟨(e,Fin.last m),hi,uniq _ hi⟩ + +omit [DecidableEq V] [DecidableEq E] in +theorem family_iff_matching (huv : ∀ e,u e≠v e) (R : Finset V) + (U : E → Finset (Fin m)) (b : E → Selection m) : + FamilyHoles u v m R U b ↔ + MatchingOn (fun (q : E × Fin (m+1)) x => x∈edge u v m q.1 q.2) (selectedSet m b) (survivors m R U) := by + constructor + · intro hb + constructor + · intro q hq x hx + cases x with + | inl x => + rw [mem_survivors_terminal] + intro hr + have huse : Uses u v b q.1 x := by + rcases (terminal_selected_iff u v m b q x).mp ⟨hq,hx⟩ with h|h + · exact Or.inl h.2 + · exact Or.inr h.2 + exact hb.2.1 x hr q.1 huse + | inr ei => + rcases ei with ⟨e,i⟩ + rw [mem_survivors_internal] + intro hi + have hd := hb.1 e i + simp only [hi,ite_eq_left] at hd + rcases (edge_incident_internal u v m q e i).mp hx with rfl|rfl + · have h := (mem_selectedSet m b _).mp hq; simp_all + · have h := (mem_selectedSet m b _).mp hq; simp_all + · intro x hx + cases x with + | inl x => exact (terminal_unique_iff u v m huv b x).mpr (hb.2.2 x ((mem_survivors_terminal m R U x).mp hx)) + | inr ei => + rcases ei with ⟨e,i⟩ + apply (internal_unique_iff u v m b e i).mpr + simpa only [Valid,ite_eq_right ((mem_survivors_internal m R U e i).mp hx)] using hb.1 e i + · intro hM + refine ⟨?_,?_,?_⟩ + · intro e i + split_ifs with hi + · constructor + · cases h : b e i.castSucc + · rfl + · have hx := hM.1 (e,i.castSucc) ((mem_selectedSet m b _).mpr h) (Sum.inr (e,i)) + ((edge_incident_internal u v m _ e i).mpr (Or.inl rfl)) + exact False.elim (((mem_survivors_internal m R U e i).mp hx) hi) + · cases h : b e i.succ + · rfl + · have hx := hM.1 (e,i.succ) ((mem_selectedSet m b _).mpr h) (Sum.inr (e,i)) + ((edge_incident_internal u v m _ e i).mpr (Or.inr rfl)) + exact False.elim (((mem_survivors_internal m R U e i).mp hx) hi) + · exact (internal_unique_iff u v m b e i).mp (hM.2 (Sum.inr (e,i)) ((mem_survivors_internal m R U e i).mpr hi)) + · intro x hx e he + have hq : ∃ q, q∈selectedSet m b ∧ Sum.inl x∈edge u v m q.1 q.2 := by + rcases he with he|he + · exact ⟨(e,0),(terminal_selected_iff u v m b _ x).mpr (Or.inl ⟨rfl,he⟩)⟩ + · exact ⟨(e,Fin.last m),(terminal_selected_iff u v m b _ x).mpr (Or.inr ⟨rfl,he⟩)⟩ + obtain ⟨q,hq,hqx⟩ := hq + exact ((mem_survivors_terminal m R U x).mp (hM.1 q hq _ hqx)) hx + · intro x hx + exact (terminal_unique_iff u v m huv b x).mp (hM.2 (Sum.inl x) ((mem_survivors_terminal m R U x).mpr hx)) + +noncomputable def selectionEquiv : (E → Selection m) ≃ Finset (E × Fin (m+1)) where + toFun := selectedSet m + invFun S e i := decide ((e,i)∈S) + left_inv b := by + funext e i + simp [mem_selectedSet] + right_inv S := by + ext ⟨e,i⟩ + simp + +noncomputable def realMatchingEquiv (huv : ∀ e,u e≠v e) (R : Finset V) (U : E → Finset (Fin m)) : + {b : E → Selection m // FamilyHoles u v m R U b} ≃ + Matchings (fun (q : E × Fin (m+1)) x => x∈edge u v m q.1 q.2) (survivors m R U) := + (selectionEquiv (E := E) m).subtypeEquiv (family_iff_matching u v m huv R U) + +omit [DecidableEq E] in +lemma selectedSet_weight (w : E → Fin (m+1) → ℝ) (b : E → Selection m) : + (∏ q ∈ selectedSet m b,w q.1 q.2)=∏ e,selectedWeight (w e) (b e) := by + classical + simp only [selectedSet,Finset.prod_filter,selectedWeight,Fintype.prod_prod_type] + +omit [DecidableEq V] in +theorem realMatching_partition (huv : ∀ e,u e≠v e) (R : Finset V) (U : E → Finset (Fin m)) + (w : E → Fin (m+1) → ℝ) : + partitionWeight (fun (q : E × Fin (m+1)) x => x∈edge u v m q.1 q.2) (fun q => w q.1 q.2) (survivors m R U)= + realHolePartition u v m R U w := by + classical + let := Fintype.ofFinite {b : E → Selection m // FamilyHoles u v m R U b} + unfold partitionWeight realHolePartition + rw [←(realMatchingEquiv u v m huv R U).sum_comp] + apply Finset.sum_congr rfl + intro b _ + exact selectedSet_weight m w b.val + +end MatchingFPRAS.RealGeometry + +end OAI diff --git a/lean/OAI/Combinatorics/MatchingCount/Graphs/EnlargementRun.lean b/lean/OAI/Combinatorics/MatchingCount/Graphs/EnlargementRun.lean new file mode 100644 index 0000000000000000000000000000000000000000..b003ce477483562f02144d63d07a8328f5ee53ce --- /dev/null +++ b/lean/OAI/Combinatorics/MatchingCount/Graphs/EnlargementRun.lean @@ -0,0 +1,471 @@ +import Mathlib +import OAI.Combinatorics.MatchingCount.Probability.Tv + +namespace OAI + +namespace MatchingFPRAS.Transport + +open Finset MatchingFPRAS.Replica MatchingFPRAS.Replica.Ladder + +variable {V J : Type*} [Fintype V] [DecidableEq V] [Fintype J] [DecidableEq J] + +variable {bags : V → Finset J} {G : SimpleGraph J} + +noncomputable local instance : Fintype (BagEdge bags) := Fintype.ofFinite _ + +noncomputable local instance : DecidableEq (PM (BagEdge.Incident (bags := bags))) := Classical.decEq _ + +variable (hb : ∀ v,∀ a∈bags v,∀ b∈bags v,a=b ∨ G.Adj a b) (hg : G.IsAcyclic) + +omit [DecidableEq V] [DecidableEq J] in +lemma ladderLaw_pos (w : BagEdge bags → ℝ) (T q : ℕ) + (s : Slot T q → PM (BagEdge.Incident (bags := bags))) : 0 (slotLaw_pos w i a).le) + guides (base T q) (treeLadderCapacity hb hg w) + +lemma ladderWalk_sum (w : BagEdge bags → ℝ) (T q : ℕ) (hq : 0 slotLaw_sum w i (z (topSlot T q hq))) + guides (base T q) (Finset.card_pos.mp (by rwa [base_card])) (treeLadderCapacity hb hg w) s + +end MatchingFPRAS.Transport + +namespace MatchingFPRAS.Enlargement + +open MatchingFPRAS.Switching MatchingFPRAS.Subdivision MatchingFPRAS.RealGeometry +open MatchingFPRAS.Hierarchy MatchingFPRAS.Transport Finset +open MatchingFPRAS.Replica MatchingFPRAS.Replica.Ladder +open scoped Classical + +variable {V : Type*} [Fintype V] [LinearOrder V] [Nontrivial V] + +noncomputable local instance (w : V → V → ℝ) (K : ℕ) : DecidableEq (SourceLabel w K) := Classical.decEq _ + +noncomputable local instance (w : V → V → ℝ) (K : ℕ) : Fintype (BagEdge (sourceBags w K)) := Fintype.ofFinite _ + +noncomputable local instance (w : V → V → ℝ) (K : ℕ) : DecidableEq (SourcePM w K) := Classical.decEq _ + +lemma revealLaw_nonneg (w : V → V → ℝ) (hw : ∀ x y,0 sourceBag_tree_adjacent w K hK x a b ha hb) + (sourceTree_isTree w K).2 (sourceBagWeight w K (sourceD (V:=V) K)) T q) z t) + (fun a => a (topSlot T q hq))) + +lemma sourceRun_nonneg (w : V → V → ℝ) (hw : ∀ x y,0 propext (hPQ x) + subst Q + apply heq_of_eq + ext x + exact h x x rfl + +variable [DecidableEq α] + +def Pairing.remove (p : Pairing α) (a : α) : Pairing {x : α // x≠a ∧ x≠p.mate a} where + mate x := ⟨p.mate x,by + constructor + · intro h + have := congrArg p.mate h + exact x.property.2 (by rw [p.involutive] at this; exact this) + · intro h + exact x.property.1 (p.involutive.injective h)⟩ + involutive x := Subtype.ext (p.involutive x) + no_fixed x h := p.no_fixed x (congrArg Subtype.val h) + +def Pairing.insert (a b : α) (hab : b≠a) + (p : Pairing {x : α // x≠a ∧ x≠b}) : Pairing α where + mate x := if hx : x=a then b else if hy : x=b then a else (p.mate ⟨x,hx,hy⟩).val + involutive x := by + by_cases hx : x=a + · subst x; simp [hab] + by_cases hy : x=b + · subst x; simp [hab] + simp only [dite_eq_right hx,dite_eq_right hy] + rw [dite_eq_right (p.mate ⟨x,hx,hy⟩).property.1,dite_eq_right (p.mate ⟨x,hx,hy⟩).property.2] + exact congrArg Subtype.val (p.involutive ⟨x,hx,hy⟩) + no_fixed x := by + by_cases hx : x=a + · subst x; simpa using hab + by_cases hy : x=b + · subst x; simpa [hx] using hab.symm + simp only [dite_eq_right hx,dite_eq_right hy] + intro h + exact p.no_fixed ⟨x,hx,hy⟩ (Subtype.ext h) + +@[simp] lemma Pairing.insert_at (a b : α) (hab : b≠a) + (p : Pairing {x : α // x≠a ∧ x≠b}) : (p.insert a b hab).mate a=b := by + simp [Pairing.insert] + +@[simp] lemma Pairing.insert_other (a b : α) (hab : b≠a) + (p : Pairing {x : α // x≠a ∧ x≠b}) (x : {x : α // x≠a ∧ x≠b}) : + (p.insert a b hab).mate x=(p.mate x).val := by + simp [Pairing.insert,x.property.1,x.property.2] + +noncomputable def Pairing.split (a : α) : + Pairing α ≃ Σ b : {x : α // x≠a}, Pairing {x : α // x≠a ∧ x≠b.val} where + toFun p := ⟨⟨p.mate a,p.no_fixed a⟩,p.remove a⟩ + invFun q := q.2.insert a q.1.val q.1.property + left_inv p := by + ext x + by_cases hx : x=a + · subst x; simp + by_cases hy : x=p.mate a + · subst x + simp [Pairing.insert,p.no_fixed a,p.involutive a] + · simp [Pairing.insert,hx,hy,Pairing.remove] + right_inv q := by + rcases q with ⟨⟨b,hb⟩,p⟩ + apply Sigma.ext (Subtype.ext (by simp)) + apply Pairing.subtype_hext + · intro x; simp only [Pairing.insert_at] + · intro x y hxy + change (p.insert a b hb).mate x = (p.mate y).val + rw [hxy] + exact Pairing.insert_other a b hb p y + +def pairingCount : ℕ → ℕ + | 0 => 1 + | 1 => 0 + | n+2 => (n+1)*pairingCount n + +@[simp] lemma pairingCount_zero : pairingCount 0=1 := rfl + +@[simp] lemma pairingCount_one : pairingCount 1=0 := rfl + +@[simp] lemma pairingCount_add_two (n : ℕ) : pairingCount (n+2)=(n+1)*pairingCount n := rfl + +lemma pairingCount_pos_recurrence {n : ℕ} (hn : 0 omega + | 1 => rfl + | n+2 => simp only [pairingCount_add_two,Nat.add_sub_cancel,show n+2-1=n+1 by omega] + +lemma card_except_two [Fintype α] (a b : α) (hab : b≠a) : + Fintype.card {x : α // x≠a ∧ x≠b}=Fintype.card α-2 := by + classical + calc + _ = Fintype.card {x : α // ¬ (x=a ∨ x=b)} := + Fintype.card_congr (Equiv.subtypeEquivRight fun x => not_or.symm) + _ = Fintype.card α-Fintype.card {x : α // x=a ∨ x=b} := Fintype.card_subtype_compl _ + _ = _ := by rw [Fintype.card_subtype_eq_or_eq_of_ne hab.symm] + +universe u + +private theorem pairing_card_aux (n : ℕ) : ∀ (α : Type u) [Fintype α], + Fintype.card α=n → Fintype.card (Pairing α)=pairingCount n := by + induction n using Nat.strong_induction_on with + | h n ih => + intro α inst hcard + classical + by_cases hn : n=0 + · have hzero : Fintype.card α=0 := hcard.trans hn + let : IsEmpty α := Fintype.card_eq_zero_iff.mp hzero + let p : Pairing α := ⟨id,fun x => rfl,fun x => isEmptyElim x⟩ + let : Unique (Pairing α) := ⟨⟨p⟩,fun q => by ext x; exact isEmptyElim x⟩ + simp [hn] + · have hnpos : 0 he b) + _ = (n-1)*pairingCount (n-2) := by + simp [Fintype.card_subtype_compl,hcard] + _ = pairingCount n := (pairingCount_pos_recurrence hnpos).symm + +omit [DecidableEq α] in +theorem pairing_card [Fintype α] : Fintype.card (Pairing α)=pairingCount (Fintype.card α) := + pairing_card_aux (Fintype.card α) α rfl + +end MatchingFPRAS.UnitRefresh + +namespace MatchingFPRAS.Initializer + +open Finset MatchingFPRAS.Switching MatchingFPRAS.UnitRefresh + +variable {V : Type*} [Fintype V] [LinearOrder V] + +noncomputable def restrictHoles (R : Finset V) (m : {m : Mate V // HasHoles m R}) : + Pairing {x : V // x∉R} where + mate x := ⟨m.val.val x.val,fun h => x.property ((mate_mem_holes_iff m.val R m.property x.val).mp h)⟩ + involutive x := Subtype.ext (m.val.property x.val) + no_fixed x h := x.property ((m.property x.val).mp (congrArg Subtype.val h)) + +noncomputable def fillFixed (R : Finset V) (p : Pairing {x : V // x∉R}) : Mate V := by + classical + refine ⟨fun x => if hx : x∉R then (p.mate ⟨x,hx⟩).val else x,?_⟩ + intro x + by_cases hx : x∉R + · simp only [dite_eq_left hx] + rw [dite_eq_left (p.mate ⟨x,hx⟩).property] + exact congrArg Subtype.val (p.involutive ⟨x,hx⟩) + · simp only [dite_eq_right hx] + +omit [Fintype V] in +lemma fillFixed_holes (R : Finset V) (p : Pairing {x : V // x∉R}) : HasHoles (fillFixed R p) R := by + classical + intro x + by_cases hx : x∉R + · simp only [fillFixed,iff_false,hx] + intro h + exact p.no_fixed ⟨x,hx⟩ (Subtype.ext h) + · simp only [fillFixed,dite_eq_right hx] + exact iff_of_true trivial (not_not.mp hx) + +noncomputable def holesPairingEquiv (R : Finset V) : + {m : Mate V // HasHoles m R} ≃ Pairing {x : V // x∉R} where + toFun := restrictHoles R + invFun p := ⟨fillFixed R p,fillFixed_holes R p⟩ + left_inv m := by + apply Subtype.ext + apply Subtype.ext + funext x + by_cases hx : x∉R + · change (if hy : x∉R then (restrictHoles R m).mate ⟨x,hy⟩ |>.val else x)=m.val.val x + rw [dite_eq_left hx] + rfl + · change (if hy : x∉R then (restrictHoles R m).mate ⟨x,hy⟩ |>.val else x)=m.val.val x + rw [dite_eq_right hx] + exact ((m.property x).mpr (not_not.mp hx)).symm + right_inv p := by + apply Pairing.ext + intro x + apply Subtype.ext + change (fillFixed R p).val x.val=(p.mate x).val + simp only [fillFixed,dite_eq_left x.property] + +lemma matchings_card (R : Finset V) : + (matchings R).card=pairingCount (Fintype.card V-R.card) := by + classical + calc + _ = Fintype.card {m : Mate V // HasHoles m R} := by + rw [Fintype.card_subtype] + apply congrArg Finset.card + ext m + simp [matchings] + _ = Fintype.card (Pairing {x : V // x∉R}) := Fintype.card_congr (holesPairingEquiv R) + _ = _ := by rw [pairing_card,Fintype.card_subtype_compl,Fintype.card_coe] + +lemma uniform_weight (c : ℝ) (R : Finset V) (m : Mate V) (hm : HasHoles m R) : + weight (fun _ _ => c) m=c^((Fintype.card V-R.card)/2) := by + classical + have hmc : HasHoles m Rᶜᶜ := by simpa using hm + have hc := mate_edge_count m Rᶜ hmc + rw [Finset.card_compl] at hc + have he : (univ.filter fun v => v < m.val v).card=(Fintype.card V-R.card)/2 := by omega + unfold weight + rw [←Finset.prod_filter (s:=univ) (fun v : V => v < m.val v) (fun _ : V => c)] + simp only [Finset.prod_const,he] + +theorem uniform_partition (c : ℝ) (R : Finset V) : + partition (fun _ _ : V => c) R= + (pairingCount (Fintype.card V-R.card):ℝ)*c^((Fintype.card V-R.card)/2) := by + unfold partition + simp_rw [Finset.sum_congr rfl (fun m hm => uniform_weight c R m ((mem_matchings m R).mp hm))] + simp only [Finset.sum_const,nsmul_eq_mul,matchings_card] + +lemma pairingCount_pos_of_even (n : ℕ) (h : Even n) : 0 < pairingCount n := by + obtain ⟨k,rfl⟩ := h + induction k with + | zero => norm_num + | succ k ih => + rw [show k+1+(k+1)=(k+k)+2 by omega,pairingCount_add_two] + exact Nat.mul_pos (by omega) ih + +lemma uniform_hole_ratio (hn : 2 ≤ Fintype.card V) (he : Even (Fintype.card V)) + (c : ℝ) (hc : 0 < c) (a b : V) (hab : a≠b) : + holeRatio (fun _ _ : V => c) {a,b}=1/((Fintype.card V-1)*c) := by + have h2 : ({a,b} : Finset V).card=2 := by simp [hab] + have hc2 : Fintype.card V-2+2=Fintype.card V := by omega + have he2 : Even (Fintype.card V-2) := by obtain ⟨k,hk⟩ := he; exact ⟨k-1,by omega⟩ + have hp : (pairingCount (Fintype.card V-2):ℝ)≠0 := by + exact_mod_cast (pairingCount_pos_of_even _ he2).ne' + have hpow : c^((Fintype.card V-2)/2)≠0 := pow_ne_zero _ hc.ne' + unfold holeRatio + rw [uniform_partition,uniform_partition,h2,Finset.card_empty,Nat.sub_zero] + have hnrec : pairingCount (Fintype.card V)= + (Fintype.card V-1)*pairingCount (Fintype.card V-2) := + pairingCount_pos_recurrence (by omega) + have hexp : Fintype.card V/2=(Fintype.card V-2)/2+1 := by omega + rw [hnrec,hexp,pow_succ,Nat.cast_mul,Nat.cast_sub (by omega : 1≤Fintype.card V),Nat.cast_one] + field_simp + +def initialScale (n : ℕ) : ℚ := 1/(Nat.sqrt (n-1):ℚ) + +lemma sqrt_square_bounds (n : ℕ) (hn : 2 ≤ n) : + (n-1:ℝ)/4 ≤ (Nat.sqrt (n-1):ℝ)^2 ∧ (Nat.sqrt (n-1):ℝ)^2 ≤ n-1 := by + have hpos : 1 ≤ Nat.sqrt (n-1) := Nat.le_sqrt.mpr (by omega) + have hlow := Nat.lt_succ_sqrt' (n-1) + have hup := Nat.sqrt_le' (n-1) + have hncast : ((n-1:ℕ):ℝ)=(n:ℝ)-1 := by rw [Nat.cast_sub (by omega : 1≤n),Nat.cast_one] + have hlow' : (n:ℝ)-1 < ((Nat.sqrt (n-1):ℝ)+1)^2 := by + rw [←hncast] + exact_mod_cast hlow + have hup' : (Nat.sqrt (n-1):ℝ)^2 ≤ (n:ℝ)-1 := by + rw [←hncast] + exact_mod_cast hup + have hs : (1:ℝ) ≤ Nat.sqrt (n-1) := by exact_mod_cast hpos + constructor + · nlinarith [sq_nonneg ((Nat.sqrt (n-1):ℝ)-1)] + · exact hup' + +lemma initialScale_pos (n : ℕ) (hn : 2 ≤ n) : 0 < initialScale n := by + unfold initialScale + have hs : 0 < Nat.sqrt (n-1) := by have := Nat.le_sqrt.mpr (by omega : 1*1≤n-1); omega + positivity + +theorem initial_balanced (hn : 2 ≤ Fintype.card V) (he : Even (Fintype.card V)) : + let w := fun _ _ : V => ((initialScale (Fintype.card V):ℚ):ℝ)^2 + (0 < partition w ∅) ∧ + (∀ a,(1:ℝ)/4 ≤ rowMax hn w a) ∧ (∀ a,rowMax hn w a ≤ 1) := by + dsimp only + let n := Fintype.card V + have hs : 0 < ((initialScale n:ℚ):ℝ) := by exact_mod_cast initialScale_pos n hn + have hsq : 0 < ((initialScale n:ℚ):ℝ)^2 := sq_pos_of_pos hs + have hr (a b : V) (hab : a≠b) : + holeRatio (fun _ _ : V => ((initialScale n:ℚ):ℝ)^2) {a,b}= + (Nat.sqrt (n-1):ℝ)^2/(n-1) := by + rw [uniform_hole_ratio hn he _ hsq a b hab] + unfold initialScale + push_cast + change 1/((n-1)*((1:ℝ)/Nat.sqrt (n-1))^2)=_ + have hp : (Nat.sqrt (n-1):ℝ)≠0 := by + have h := initialScale_pos n hn + simp only [initialScale,one_div,inv_pos] at h + exact_mod_cast h.ne' + field_simp + have hnreal : (2:ℝ) ≤ n := by exact_mod_cast hn + have hden : (0:ℝ) < n-1 := by linarith + refine ⟨?_,?_,?_⟩ + · rw [uniform_partition,Finset.card_empty,Nat.sub_zero] + exact mul_pos (by exact_mod_cast pairingCount_pos_of_even n he) (pow_pos hsq _) + · intro a + obtain ⟨b,hba,hb⟩ := rowMax_attained hn (fun _ _ : V => ((initialScale n:ℚ):ℝ)^2) a + rw [←hb,hr a b hba.symm] + have hbnd := (sqrt_square_bounds n hn).1 + apply (le_div_iff₀ hden).mpr + linarith + · intro a + obtain ⟨b,hba,hb⟩ := rowMax_attained hn (fun _ _ : V => ((initialScale n:ℚ):ℝ)^2) a + rw [←hb,hr a b hba.symm] + exact (div_le_one hden).mpr + (sqrt_square_bounds n hn).2 + +end MatchingFPRAS.Initializer + +end OAI diff --git a/lean/OAI/Combinatorics/MatchingCount/Graphs/Evolve.lean b/lean/OAI/Combinatorics/MatchingCount/Graphs/Evolve.lean new file mode 100644 index 0000000000000000000000000000000000000000..6863cb96606c987e4f996c0bc25d291b0eb402dc --- /dev/null +++ b/lean/OAI/Combinatorics/MatchingCount/Graphs/Evolve.lean @@ -0,0 +1,438 @@ +import Mathlib +import OAI.Combinatorics.MatchingCount.Machines.TreePairProposal +import OAI.Combinatorics.MatchingCount.Graphs.PushedFlow + +namespace OAI + +namespace MatchingFPRAS.FiniteChain + +open Finset MatchingFPRAS.Replica + +variable {Ω : Type*} [Fintype Ω] [DecidableEq Ω] + +noncomputable def evolve (π : Ω → ℝ) (C : Ω → Ω → ℝ) : ℕ → (Ω → ℝ) → (Ω → ℝ) + | 0, f => f + | n+1, f => stepDensity π C (evolve π C n f) + +omit [DecidableEq Ω] in +lemma evolve_mean (π : Ω → ℝ) (hp : ∀ a, 0 < π a) (C : Ω → Ω → ℝ) + (hrow : ∀ a, ∑ b, C a b = π a) (n : ℕ) (f : Ω → ℝ) : + massMean π (evolve π C n f) = massMean π f := by + induction n with + | zero => rfl + | succ n ih => rw [evolve,stepDensity_mean π hp C hrow,ih] + +omit [DecidableEq Ω] in +lemma evolve_center (π : Ω → ℝ) (hp : ∀ a, 0 < π a) (C : Ω → Ω → ℝ) + (hcol : ∀ b, ∑ a, C a b = π b) (n : ℕ) (f : Ω → ℝ) : + evolve π C n (fun a => f a-1) = fun a => evolve π C n f a-1 := by + induction n with + | zero => rfl + | succ n ih => + simp only [evolve,ih] + have he : (fun a => evolve π C n f a-1) = fun a => 1*evolve π C n f a+(-1)*(1:ℝ) := by funext a; ring + rw [he,stepDensity_linear,stepDensity_one π hp C hcol] + funext a; ring + +lemma lazy_decay (π : Ω → ℝ) (hp : ∀ a, 0 < π a) (C : Ω → Ω → ℝ) + (hC : ∀ a b, 0 ≤ C a b) (hrow : ∀ a, ∑ b, C a b = π a) + (hcol : ∀ b, ∑ a, C a b = π b) (hlazy : ∀ a, π a/2 ≤ C a a) + (γ : ℝ) (hγ : γ ≤ 1) + (hgap : ∀ f, massMean π f = 0 → γ*sqNorm π f ≤ localEnergy C f) + (f : Ω → ℝ) (hf : massMean π f = 0) (n : ℕ) : + sqNorm π (evolve π C n f) ≤ (1-γ)^n*sqNorm π f := by + induction n with + | zero => simp [evolve] + | succ n ih => + have hm : massMean π (evolve π C n f) = 0 := (evolve_mean π hp C hrow n f).trans hf + have hl := lazy_l2 π hp C hC hrow hcol hlazy (evolve π C n f) + have hg := hgap (evolve π C n f) hm + have hh := mul_le_mul_of_nonneg_left ih (sub_nonneg.mpr hγ) + rw [evolve,pow_succ] + nlinarith + +noncomputable def deltaDensity (π : Ω → ℝ) (z a : Ω) : ℝ := if a=z then (π z)⁻¹ else 0 + +lemma deltaDensity_mean (π : Ω → ℝ) (hp : ∀ a, 0 < π a) (z : Ω) : + massMean π (deltaDensity π z) = 1 := by + simp [massMean,deltaDensity,mul_ite,ne_of_gt (hp z)] + +omit [DecidableEq Ω] in +lemma sqNorm_center (π f : Ω → ℝ) (hs : ∑ a, π a = 1) : + sqNorm π (fun a => f a-1) = sqNorm π f-2*massMean π f+1 := by + have he (a : Ω) : π a*(f a-1)^2 = π a*(f a)^2-2*(π a*f a)+π a := by ring + simp only [sqNorm,massMean,he,Finset.sum_add_distrib,Finset.sum_sub_distrib,← Finset.mul_sum,hs] + +lemma deltaDensity_sqNorm (π : Ω → ℝ) (_hp : ∀ a, 0 < π a) (z : Ω) : + sqNorm π (deltaDensity π z) = (π z)⁻¹ := by + simp only [sqNorm,deltaDensity,ite_pow,zero_pow (by decide : (2:ℕ) ≠ 0),mul_ite,mul_zero, + Finset.sum_ite_eq',Finset.mem_univ,ite_true] + field_simp + +lemma deltaDensity_center_norm (π : Ω → ℝ) (hp : ∀ a, 0 < π a) (hs : ∑ a, π a = 1) (z : Ω) : + sqNorm π (fun a => deltaDensity π z a-1) = (π z)⁻¹-1 := by + rw [sqNorm_center π _ hs,deltaDensity_sqNorm π hp,deltaDensity_mean π hp] + ring + +omit [DecidableEq Ω] in +lemma abs_sum_sq_le (π f : Ω → ℝ) (hp : ∀ a, 0 ≤ π a) (hs : ∑ a, π a = 1) : + (∑ a, |π a*f a|)^2 ≤ sqNorm π f := by + have hh := square_average π hp hs (fun a => |f a|) + simpa only [abs_mul,abs_of_nonneg (hp _),sq_abs,sqNorm] using hh + +noncomputable def kernel (π : Ω → ℝ) (C : Ω → Ω → ℝ) (a b : Ω) : ℝ := C a b/π a + +noncomputable def walk (π : Ω → ℝ) (C : Ω → Ω → ℝ) (z : Ω) : ℕ → Ω → ℝ + | 0, a => if a=z then 1 else 0 + | n+1, b => ∑ a, walk π C z n a*kernel π C a b + +lemma walk_density (π : Ω → ℝ) (hp : ∀ a, 0 < π a) (C : Ω → Ω → ℝ) (z : Ω) (n : ℕ) (a : Ω) : + walk π C z n a = π a*evolve π C n (deltaDensity π z) a := by + induction n generalizing a with + | zero => + by_cases h : a=z + · subst a; simp [walk,evolve,deltaDensity,ne_of_gt (hp z)] + · simp [walk,evolve,deltaDensity,h] + | succ n ih => + simp only [walk,ih,kernel,evolve,stepDensity,mul_div_cancel₀ _ (ne_of_gt (hp a))] + apply Finset.sum_congr rfl + intro b _ + field_simp [ne_of_gt (hp b)] + +lemma meeting_bound (π : Ω → ℝ) (hp : ∀ a, 0 < π a) (hs : ∑ a, π a = 1) + (C : Ω → Ω → ℝ) (hC : ∀ a b, 0 ≤ C a b) + (hrow : ∀ a, ∑ b, C a b = π a) (hcol : ∀ b, ∑ a, C a b = π b) + (hlazy : ∀ a, π a/2 ≤ C a a) (γ : ℝ) (hγ : γ ≤ 1) + (hgap : ∀ f, massMean π f = 0 → γ*sqNorm π f ≤ localEnergy C f) + (z : Ω) (n : ℕ) : + (∑ a, |walk π C z n a-π a|)^2 ≤ (1-γ)^n*((π z)⁻¹-1) := by + let f : Ω → ℝ := fun a => deltaDensity π z a-1 + have hf : massMean π f = 0 := by + simp only [f,massMean,mul_sub,mul_one,Finset.sum_sub_distrib,hs] + change massMean π (deltaDensity π z)-1=0 + rw [deltaDensity_mean π hp]; ring + have hb := lazy_decay π hp C hC hrow hcol hlazy γ hγ hgap f hf n + have ha := abs_sum_sq_le π (evolve π C n f) (fun a => (hp a).le) hs + have he : (fun a => π a*evolve π C n f a) = fun a => walk π C z n a-π a := by + funext a + dsimp only [f] + rw [evolve_center π hp C hcol,walk_density π hp C z n] + ring + have hh : (∑ a, |π a*evolve π C n f a|) = ∑ a, |walk π C z n a-π a| := by + exact congrArg (fun g : Ω → ℝ => ∑ a, |g a|) he + rw [hh] at ha + have hn : sqNorm π f = (π z)⁻¹-1 := deltaDensity_center_norm π hp hs z + rw [hn] at hb + exact ha.trans hb + +end MatchingFPRAS.FiniteChain + +namespace MatchingFPRAS.Transport + +section + +open Finset MatchingFPRAS.Replica MatchingFPRAS.Replica.Ladder + +variable {V J : Type*} [Fintype V] [DecidableEq V] [Fintype J] [DecidableEq J] + +variable {bags : V → Finset J} {G : SimpleGraph J} + +noncomputable local instance : Fintype (BagEdge bags) := Fintype.ofFinite _ + +noncomputable local instance : DecidableEq (PM (BagEdge.Incident (bags := bags))) := Classical.decEq _ + +noncomputable def ladderLaw (w : BagEdge bags → ℝ) (T q : ℕ) : + (Slot T q → PM (BagEdge.Incident (bags := bags))) → ℝ := density (slotLaw w) + +noncomputable def ladderFlow + (hbags : ∀ v, ∀ a ∈ bags v, ∀ b ∈ bags v, a = b ∨ G.Adj a b) + (hG : G.IsAcyclic) (w : BagEdge bags → ℝ) (T q : ℕ) : + (Slot T q → PM (BagEdge.Incident (bags := bags))) → + (Slot T q → PM (BagEdge.Incident (bags := bags))) → ℝ := + scanFlow (slotLaw w) guides (base T q) (treeLadderCapacity hbags hG w) + +noncomputable local instance : Fintype (BagEdge bags) := Fintype.ofFinite _ + +noncomputable local instance : DecidableEq (PM (BagEdge.Incident (bags := bags))) := Classical.decEq _ + +variable {hbags : ∀ v, ∀ a ∈ bags v, ∀ b ∈ bags v, a = b ∨ G.Adj a b} + +variable {hG : G.IsAcyclic} + +variable (height : J → ℝ) (hheight : ∀ l, 0 < height l) + +variable (hstep : ∀ a b, G.Adj a b → height a ≤ 2 * height b) + +variable (D : ℕ) (hD : 1 ≤ D) (w : BagEdge bags → ℝ) + +variable (hw : ∀ e, height e.color / D ≤ w e ∧ w e ≤ 3 * height e.color) + +include hheight hstep hD hw hbags hG + +theorem concrete_ladder_mixing (hN : 2 ≤ Fintype.card V) + (M₀ : PM (BagEdge.Incident (bags := bags))) (T : ℕ) + (z : Slot T (32*(10^4*Fintype.card V*D)^100) → PM (BagEdge.Incident (bags := bags))) + (n : ℕ) : + let q := 32*(10^4*Fintype.card V*D)^100 + let ν := ladderLaw w T q + let C := ladderFlow hbags hG w T q + (∑ s, |MatchingFPRAS.FiniteChain.walk ν C z n s-ν s|)^2 ≤ + (1-3/((8*(T*q^2+q):ℕ):ℝ))^n*((ν z)⁻¹-1) := by + classical + dsimp only + let q : ℕ := 32*(10^4*Fintype.card V*D)^100 + let ν := ladderLaw w T q + let C := ladderFlow hbags hG w T q + have hq : 0 < q := by + have hV : 0 < Fintype.card V := lt_of_lt_of_le (by norm_num) hN + have hd : 0 < D := lt_of_lt_of_le (by norm_num) hD + dsimp [q]; positivity + have hM : 0 < ((8*(T*q^2+q):ℕ):ℝ) := by exact_mod_cast (by omega : 0 < 8*(T*q^2+q)) + have hp (s) : 0 < ν s := by + apply Finset.prod_pos; intro i _; exact slotLaw_pos w i (s i) + have hs : (∑ s, ν s) = 1 := density_sum (slotLaw w) (fun i => slotLaw_sum w i M₀) + have hbase : (base T q).Nonempty := Finset.card_pos.mp (by rw [base_card]; exact hq) + have hC (s t) : 0 ≤ C s t := scanFlow_nonneg (slotLaw w) (fun i a => (slotLaw_pos w i a).le) + guides (base T q) (treeLadderCapacity hbags hG w) s t + have hrow (s) : (∑ t, C s t) = ν s := scanFlow_row (slotLaw w) (fun i => slotLaw_sum w i M₀) + guides (base T q) hbase (treeLadderCapacity hbags hG w) s + have hcol (t) : (∑ s, C s t) = ν t := scanFlow_col (slotLaw w) (fun i => slotLaw_sum w i M₀) + guides (base T q) hbase (treeLadderCapacity hbags hG w) t + have hlazy (s) : ν s/2 ≤ C s s := scanFlow_lazy (slotLaw w) (fun i a => (slotLaw_pos w i a).le) + guides (base T q) (treeLadderCapacity hbags hG w) s + have hγ : 3/((8*(T*q^2+q):ℕ):ℝ) ≤ 1 := by + apply (div_le_one hM).mpr + exact_mod_cast (by omega : 3 ≤ 8*(T*q^2+q)) + have hgap (f) (hf : MatchingFPRAS.FiniteChain.massMean ν f = 0) : + (3/((8*(T*q^2+q):ℕ):ℝ))*MatchingFPRAS.FiniteChain.sqNorm ν f ≤ localEnergy C f := by + have hh := concrete_ladder_poincare (hbags := hbags) (hG := hG) height hheight hstep D hD w hw hN M₀ T f + dsimp only at hh + have hv : MatchingFPRAS.Replica.variance (slotLaw w) f = MatchingFPRAS.FiniteChain.sqNorm ν f := by + have hm : MatchingFPRAS.Replica.mean (slotLaw w) f = 0 := hf + unfold MatchingFPRAS.Replica.variance MatchingFPRAS.Replica.dot + simp only [hm,Pi.sub_apply,sub_zero] + unfold MatchingFPRAS.FiniteChain.sqNorm + apply Finset.sum_congr rfl + intro s _; change ν s*f s*f s=ν s*(f s)^2; ring + rw [hv] at hh + have he : localEnergy C f = scanEnergy (slotLaw w) guides (base T q) (treeLadderCapacity hbags hG w) f := + scanFlow_energy (slotLaw w) (fun i => slotLaw_sum w i M₀) guides (base T q) (treeLadderCapacity hbags hG w) f + rw [← he] at hh + change MatchingFPRAS.FiniteChain.sqNorm ν f ≤ ((8*(T*q^2+q):ℕ):ℝ)/3*localEnergy C f at hh + rw [div_mul_eq_mul_div] + apply (div_le_iff₀ hM).mpr + linarith + + exact MatchingFPRAS.FiniteChain.meeting_bound ν hp hs C hC hrow hcol hlazy + (3/((8*(T*q^2+q):ℕ):ℝ)) hγ hgap z n + +end + +section + +open Finset + +variable {V E : Type*} [Fintype V] [DecidableEq V] [Fintype E] [DecidableEq E] + +variable {inc : E → V → Prop} + +noncomputable def chosenEdge (A : PM inc) (v : V) : E := + Classical.choose (A.property.2 v (mem_univ v)) + +omit [DecidableEq V] [Fintype E] [DecidableEq E] in +lemma chosenEdge_mem (A : PM inc) (v : V) : chosenEdge A v ∈ A.val := + (Classical.choose_spec (A.property.2 v (mem_univ v))).1.1 + +omit [DecidableEq V] [Fintype E] [DecidableEq E] in +lemma chosenEdge_incident (A : PM inc) (v : V) : inc (chosenEdge A v) v := + (Classical.choose_spec (A.property.2 v (mem_univ v))).1.2 + +omit [DecidableEq V] [Fintype E] [DecidableEq E] in +lemma chosenEdge_injective (hinc : ∀ e, ∃ v, inc e v) : + Function.Injective (chosenEdge (inc := inc)) := by + intro A B h + apply Subtype.ext; ext e + have hh (A B : PM inc) (h : chosenEdge A = chosenEdge B) : e ∈ A.val → e ∈ B.val := by + intro he + obtain ⟨v,hv⟩ := hinc e + have heq : e = chosenEdge A v := A.property.unique (mem_univ v) he hv + (chosenEdge_mem A v) (chosenEdge_incident A v) + rw [heq,congrFun h v] + exact chosenEdge_mem B v + exact ⟨hh A B h,hh B A h.symm⟩ + +omit [DecidableEq E] in +lemma pm_card_le (hinc : ∀ e, ∃ v, inc e v) : + Fintype.card (PM inc) ≤ Fintype.card E ^ Fintype.card V := by + classical + simpa only [Fintype.card_fun] using Fintype.card_le_of_injective chosenEdge (chosenEdge_injective hinc) + +omit [DecidableEq V] [DecidableEq E] in +lemma gibbs_mass_lower (hinc : ∀ e, ∃ v, inc e v) (w : E → ℝ) + (D B : ℝ) (hD : 1 ≤ D) (hB : 1 ≤ B) + (hw : ∀ e, D⁻¹ ≤ w e ∧ w e ≤ B) (A : PM inc) : + (Fintype.card (PM inc)*(D*B)^Fintype.card V)⁻¹ ≤ gibbs w A := by + classical + have hD0 : 0 < D := by linarith + have hB0 : 0 < B := by linarith + have hw0 : ∀ e, 0 < w e := fun e => (inv_pos.mpr hD0).trans_le (hw e).1 + have lower (M : PM inc) : (D^Fintype.card V)⁻¹ ≤ matchingWeight w M := by + have hh : (D⁻¹)^M.val.card ≤ matchingWeight w M := by + simpa only [matchingWeight,Finset.prod_const] using Finset.prod_le_prod₀ + (fun e (_ : e ∈ M.val) => (inv_pos.mpr hD0).le) (fun e _ => (hw e).1) + rw [inv_pow] at hh + exact (inv_anti₀ (pow_pos hD0 _) (pow_le_pow_right₀ hD (PM.card_le_vertices hinc M))).trans hh + have upper (M : PM inc) : matchingWeight w M ≤ B^Fintype.card V := by + have hh : matchingWeight w M ≤ B^M.val.card := by + simpa only [matchingWeight,Finset.prod_const] using Finset.prod_le_prod₀ + (fun e (_ : e ∈ M.val) => (hw0 e).le) (fun e _ => (hw e).2) + exact hh.trans (pow_le_pow_right₀ hB (PM.card_le_vertices hinc M)) + have hc : 0 < (Fintype.card (PM inc):ℝ) := by + have : Nonempty (PM inc) := ⟨A⟩ + exact_mod_cast Fintype.card_pos + have hz : partition (inc := inc) w ≤ Fintype.card (PM inc)*B^Fintype.card V := by + have he : partition (inc := inc) w = ∑ M : PM inc, matchingWeight w M := by + unfold partition + congr + exact Subsingleton.elim _ _ + rw [he] + calc + _ ≤ ∑ _M : PM inc, B^Fintype.card V := Finset.sum_le_sum (fun M _ => upper M) + _ = _ := by simp only [Finset.sum_const,Finset.card_univ,nsmul_eq_mul] + have hp := partition_pos w hw0 A + have hden : 0 < (Fintype.card (PM inc):ℝ)*B^Fintype.card V := mul_pos hc (pow_pos hB0 _) + calc + _ = (D^Fintype.card V)⁻¹/(Fintype.card (PM inc)*B^Fintype.card V) := by + rw [mul_pow]; field_simp + _ ≤ matchingWeight w A/partition (inc := inc) w := + div_le_div₀ (matchingWeight_pos w hw0 A).le (lower A) hp hz + _ = _ := rfl + +end + +section + +open Finset MatchingFPRAS.Replica MatchingFPRAS.Replica.Ladder + +variable {V J : Type*} [Fintype V] [DecidableEq V] [Fintype J] [DecidableEq J] + +variable {bags : V → Finset J} {G : SimpleGraph J} + +noncomputable local instance : Fintype (BagEdge bags) := Fintype.ofFinite _ + +lemma tierClamp_range {c lo hi w : ℝ} (hc : 1 ≤ c) (hlo : lo ≤ 1) (hhi : 1 ≤ hi) + (hw : lo ≤ w ∧ w ≤ hi) (t : ℕ) : lo ≤ tierClamp c t w ∧ tierClamp c t w ≤ hi := by + have hp : 1 ≤ c^t := one_le_pow₀ hc + have hip : (c^t)⁻¹ ≤ 1 := inv_le_one_of_one_le₀ hp + constructor + · exact le_trans (le_min (hlo.trans hp) hw.1) (le_max_right _ _) + · exact max_le (hip.trans hhi) ((min_le_right _ _).trans hw.2) + +omit [DecidableEq V] [Fintype J] [DecidableEq J] in +lemma slotWeight_range (D K : ℕ) (hD : 1 ≤ D) (w : BagEdge bags → ℝ) + (hw : ∀ e, (D:ℝ)⁻¹ ≤ w e ∧ w e ≤ 3*4^K) {T q : ℕ} (x : Slot T q) (e : BagEdge bags) : + (D:ℝ)⁻¹ ≤ slotWeight w x e ∧ slotWeight w x e ≤ 3*4^K := by + apply tierClamp_range + · unfold tierBase; exact le_add_of_nonneg_right (by positivity) + · apply inv_le_one_of_one_le₀; exact_mod_cast hD + · have h : (1:ℝ) ≤ 4^K := one_le_pow₀ (by norm_num) + linarith + · exact hw e + +omit [DecidableEq J] in +lemma bag_pm_card_le + (hbags : ∀ v, ∀ a ∈ bags v, ∀ b ∈ bags v, a = b ∨ G.Adj a b) + (hG : G.IsAcyclic) : + Fintype.card (PM (BagEdge.Incident (bags := bags))) ≤ (2*Fintype.card V^2)^Fintype.card V := by + apply (pm_card_le BagEdge.exists_incident).trans + exact Nat.pow_le_pow_left (bag_edges_card_le hbags hG) _ + +lemma denominator_power_bound (N D K : ℕ) (hN : 2 ≤ N) (hD : 1 ≤ D) : + ((2*(N:ℝ)^2)^N)*((D:ℝ)*(3*4^K))^N ≤ + (2:ℝ)^(10*N*(K+Nat.clog 2 (N*D+2)+1)) := by + let a := Nat.clog 2 (N*D+2) + have hp : (N*D+2:ℝ) ≤ (2:ℝ)^a := by exact_mod_cast Nat.le_pow_clog (by decide : 1 < 2) (N*D+2) + have hn : (N:ℝ) ≤ 2^a := by + have hd : (1:ℝ) ≤ D := by exact_mod_cast hD + have hn0 : (0:ℝ) ≤ N := Nat.cast_nonneg N + have hnd : (N:ℝ) ≤ N*D := by nlinarith + exact hnd.trans (le_trans (by linarith) hp) + have hd : (D:ℝ) ≤ 2^a := by + have hn2 : (2:ℝ) ≤ N := by exact_mod_cast hN + have hd0 : (0:ℝ) ≤ D := Nat.cast_nonneg D + have hnd : (D:ℝ) ≤ N*D := by nlinarith + exact hnd.trans (le_trans (by linarith) hp) + have hfour : (4:ℝ)^K = 2^(2*K) := by rw [pow_mul]; norm_num + have hb : 2*(N:ℝ)^2*((D:ℝ)*(3*4^K)) ≤ 2^(3+3*a+2*K) := by + calc + _ ≤ 2*(2^a)^2*((2^a)*(3*4^K)) := mul_le_mul + (mul_le_mul_of_nonneg_left (pow_le_pow_left₀ (Nat.cast_nonneg N) hn 2) (by norm_num)) + (mul_le_mul_of_nonneg_right hd (by positivity)) (by positivity) (by positivity) + _ ≤ 2*(2^a)^2*((2^a)*(4*4^K)) := by + apply mul_le_mul_of_nonneg_left _ (by positivity) + apply mul_le_mul_of_nonneg_left _ (by positivity) + exact mul_le_mul_of_nonneg_right (by norm_num : (3:ℝ) ≤ 4) (by positivity) + _ = _ := by + rw [hfour] + calc + _ = (2:ℝ)^3*2^(a*2)*2^a*2^(2*K) := by rw [pow_mul]; norm_num; ring + _ = _ := by simp only [← pow_add]; congr 1; omega + calc + _ = (2*(N:ℝ)^2*((D:ℝ)*(3*4^K)))^N := (mul_pow _ _ _).symm + _ ≤ (2^(3+3*a+2*K))^N := pow_le_pow_left₀ (by positivity) hb N + _ = (2:ℝ)^((3+3*a+2*K)*N) := (pow_mul _ _ _).symm + _ ≤ _ := pow_le_pow_right₀ (by norm_num) (by dsimp only [a]; nlinarith) + +end + +open Finset MatchingFPRAS.Replica MatchingFPRAS.Replica.Ladder + +variable {V J : Type*} [Fintype V] [DecidableEq V] [Fintype J] [DecidableEq J] + +variable {bags : V → Finset J} {G : SimpleGraph J} + +noncomputable local instance : Fintype (BagEdge bags) := Fintype.ofFinite _ + +omit [DecidableEq J] in +lemma slotLaw_minimum_mass + (hbags : ∀ v, ∀ a ∈ bags v, ∀ b ∈ bags v, a = b ∨ G.Adj a b) + (hG : G.IsAcyclic) (D K : ℕ) (hD : 1 ≤ D) (hN : 2 ≤ Fintype.card V) + (w : BagEdge bags → ℝ) (hw : ∀ e, (D:ℝ)⁻¹ ≤ w e ∧ w e ≤ 3*4^K) + {T q : ℕ} (x : Slot T q) (A : PM (BagEdge.Incident (bags := bags))) : + ((2:ℝ)^(10*Fintype.card V*(K+Nat.clog 2 (Fintype.card V*D+2)+1)))⁻¹ ≤ slotLaw w x A := by + have hl := gibbs_mass_lower BagEdge.exists_incident (slotWeight w x) D (3*4^K) + (by exact_mod_cast hD) (by + have hh : (1:ℝ) ≤ 4^K := one_le_pow₀ (by norm_num) + linarith) + (slotWeight_range D K hD w hw x) A + have hc : (Fintype.card (PM (BagEdge.Incident (bags := bags))):ℝ) ≤ + (2*Fintype.card V^2:ℝ)^Fintype.card V := by exact_mod_cast bag_pm_card_le hbags hG + have hd := (mul_le_mul_of_nonneg_right hc (by positivity : (0:ℝ) ≤ ((D:ℝ)*(3*4^K))^Fintype.card V)).trans + (denominator_power_bound (Fintype.card V) D K hN hD) + have hp : 0 < (Fintype.card (PM (BagEdge.Incident (bags := bags))):ℝ)* + ((D:ℝ)*(3*4^K))^Fintype.card V := by + have : Nonempty (PM (BagEdge.Incident (bags := bags))) := ⟨A⟩ + have hc0 : (0:ℝ) < Fintype.card (PM (BagEdge.Incident (bags := bags))) := by exact_mod_cast Fintype.card_pos + have hd0 : (0:ℝ) < D := by exact_mod_cast (by omega : 0 < D) + positivity + exact (inv_anti₀ hp hd).trans hl + +omit [DecidableEq J] in +lemma ladderLaw_power_lower + (hbags : ∀ v, ∀ a ∈ bags v, ∀ b ∈ bags v, a = b ∨ G.Adj a b) + (hG : G.IsAcyclic) (D K : ℕ) (hD : 1 ≤ D) (hN : 2 ≤ Fintype.card V) + (w : BagEdge bags → ℝ) (hw : ∀ e, (D:ℝ)⁻¹ ≤ w e ∧ w e ≤ 3*4^K) (T q : ℕ) + (z : Slot T q → PM (BagEdge.Incident (bags := bags))) : + ((2:ℝ)^(10*Fintype.card V*q*(T+1)*(K+Nat.clog 2 (Fintype.card V*D+2)+1)))⁻¹ ≤ ladderLaw w T q z := by + have hh := Finset.prod_le_prod₀ (s := Finset.univ) + (fun (x : Slot T q) _ => (by positivity : (0:ℝ) ≤ ((2:ℝ)^(10*Fintype.card V*(K+Nat.clog 2 (Fintype.card V*D+2)+1)))⁻¹)) + (fun x _ => slotLaw_minimum_mass hbags hG D K hD hN w hw x (z x)) + simp only [prod_const,card_univ,slots_card,← inv_pow,← pow_mul] at hh + have he : 10*Fintype.card V*(K+Nat.clog 2 (Fintype.card V*D+2)+1)*((T+1)*q) = + 10*Fintype.card V*q*(T+1)*(K+Nat.clog 2 (Fintype.card V*D+2)+1) := by ring + rw [he] at hh + simpa only [inv_pow,ladderLaw,density] using hh + +end MatchingFPRAS.Transport + +end OAI diff --git a/lean/OAI/Combinatorics/MatchingCount/Graphs/ExperimentSupport.lean b/lean/OAI/Combinatorics/MatchingCount/Graphs/ExperimentSupport.lean new file mode 100644 index 0000000000000000000000000000000000000000..2d4a0fa42414ddd0f18f4408d6fa716047cc57f9 --- /dev/null +++ b/lean/OAI/Combinatorics/MatchingCount/Graphs/ExperimentSupport.lean @@ -0,0 +1,91 @@ +import Mathlib +import OAI.Combinatorics.MatchingCount.Graphs.AdaptiveStream + +namespace OAI + +namespace MatchingFPRAS.PhysicalStream.Experiment +variable {α β : Type} +def All : Experiment α → (α → Prop) → Prop + | .done a,P => P a + | .read f,P => All (f false) P ∧ All (f true) P + | .delay _ p,P => All p P +lemma All.mono {p : Experiment α} {P Q : α → Prop} (h : All p P) (hPQ : ∀ a,P a→Q a) : All p Q := by + induction p with + | done a => exact hPQ a h + | read p ih => exact ⟨ih false h.1,ih true h.2⟩ + | delay n p ih => exact ih h +lemma all_run (p : Experiment α) (P : α → Prop) (h : All p P) (b : Stream) : P (p.run b).1 := by + induction p generalizing b with + | done a => exact h + | read p ih => + cases hb : b 0 <;> simp only [run,hb] <;> apply ih <;> first | exact h.1 | exact h.2 + | delay n p ih => exact ih h (shift n b) +lemma mean_nonneg (p : Experiment α) (f : α → ℚ) (h : All p (fun a=>0≤f a)) : 0≤p.mean f := by + induction p with + | done a => exact h + | read p ih => exact div_nonneg (add_nonneg (ih false h.1) (ih true h.2)) (by norm_num) + | delay n p ih => exact ih h +lemma all_true (p : Experiment α) : All p (fun _=>True) := by + induction p with + | done a => trivial + | read p ih => exact ⟨ih false,ih true⟩ + | delay n p ih => exact ih +lemma all_indicator (p : Experiment α) (P : α → Prop) [DecidablePred P] : + All p P ↔ p.mean (fun a=>if P a then 0 else 1)=0 := by + induction p with + | done a => simp [All,mean] + | delay n p ih => exact ih + | read p ih => + have hz (b : Bool) : 0≤(p b).mean (fun a=>if P a then 0 else 1) := + mean_nonneg _ _ ((all_true _).mono (by intro a _; split <;> norm_num)) + simp only [All,mean,ih] + constructor + · rintro ⟨h0,h1⟩; rw [h0,h1]; norm_num + · intro h + have h0:=hz false + have h1:=hz true + constructor <;> linarith +lemma all_of_mean_eq {p q : Experiment α} (h : ∀ f : α → ℚ,q.mean f=p.mean f) + (P : α → Prop) (hp : All p P) : All q P := by + classical + rw [all_indicator,h,←all_indicator] + exact hp +lemma cost_bind_le_of_all (p : Experiment α) (q : α → Experiment β) (N : ℕ) + (h : All p (fun a=>(q a).cost≤N)) : (p.bind q).cost≤p.cost+N := by + induction p with + | done a => simpa only [All,bind,cost,Nat.zero_add] using h + | read p ih => + have h0:=ih false h.1 + have h1:=ih true h.2 + simp only [cost,bind] + omega + | delay n p ih => simpa only [bind,cost,Nat.add_assoc] using Nat.add_le_add_left (ih h) n +lemma all_bind (p : Experiment α) (q : α → Experiment β) (P : β → Prop) : + All (p.bind q) P ↔ All p (fun a=>All (q a) P) := by + induction p with + | done a => rfl + | read p ih => simp only [bind,All,ih] + | delay n p ih => exact ih +lemma all_map (p : Experiment α) (f : α → β) (P : β → Prop) : + All (p.map f) P ↔ All p (fun a=>P (f a)) := by + rw [map,all_bind]; rfl + +variable {α : Type} +def worst : Experiment α → (α → ℕ) → ℕ + | .done a,f => f a + | .read p,f => max (worst (p false) f) (worst (p true) f) + | .delay _ p,f => worst p f +lemma all_worst (p : Experiment α) (f : α → ℕ) : All p (fun a=>f a≤p.worst f) := by + induction p with + | done a => exact le_rfl + | read p ih => exact ⟨(ih false).mono (fun a ha=>ha.trans (le_max_left _ _)), + (ih true).mono (fun a ha=>ha.trans (le_max_right _ _))⟩ + | delay n p ih => exact ih +lemma worst_le (p : Experiment α) (f : α → ℕ) (N : ℕ) (h : All p (fun a=>f a≤N)) : p.worst f≤N := by + induction p with + | done a => exact h + | read p ih => exact max_le (ih false h.1) (ih true h.2) + | delay n p ih => exact ih h +end MatchingFPRAS.PhysicalStream.Experiment + +end OAI diff --git a/lean/OAI/Combinatorics/MatchingCount/Graphs/FillHoles.lean b/lean/OAI/Combinatorics/MatchingCount/Graphs/FillHoles.lean new file mode 100644 index 0000000000000000000000000000000000000000..6b18d9cd9a5b6521ef92a03691bc402a38755aaa --- /dev/null +++ b/lean/OAI/Combinatorics/MatchingCount/Graphs/FillHoles.lean @@ -0,0 +1,259 @@ +import Mathlib +import OAI.Combinatorics.MatchingCount.Algorithm.AffineWeights + +namespace OAI + +namespace MatchingFPRAS.Switching +open Finset +open scoped Classical symmDiff + +variable {V : Type*} +theorem mate_mem_holes_iff [DecidableEq V] (m : Mate V) (S : Finset V) + (hm : HasHoles m S) (v : V) : m.1 v ∈ S ↔ v ∈ S := by + rw [← hm (m.1 v), ← hm v, mate_mate] + exact eq_comm + +noncomputable def fillHoles [Fintype V] [DecidableEq V] (m q : Mate V) (S : Finset V) + (hm : HasHoles m S) (hq : HasHoles q Sᶜ) : Mate V := by + classical + refine ⟨fun v => if v ∈ S then q.1 v else m.1 v, ?_⟩ + intro v + by_cases hv : v ∈ S + · have hqv : q.1 v ∈ S := by + have h := mate_mem_holes_iff q Sᶜ hq v + have he : q.1 v ∈ S ↔ v ∈ S := by + simpa only [Finset.mem_compl, not_iff_not] using h + exact he.mpr hv + simp [hv,hqv,mate_mate] + · have hmv : m.1 v ∉ S := fun h => hv ((mate_mem_holes_iff m S hm v).mp h) + simp [hv,hmv,mate_mate] + +@[simp] theorem fillHoles_apply [Fintype V] [DecidableEq V] (m q : Mate V) (S : Finset V) + (hm : HasHoles m S) (hq : HasHoles q Sᶜ) (v : V) : + (fillHoles m q S hm hq).1 v = if v ∈ S then q.1 v else m.1 v := rfl + +theorem fillHoles_perfect [Fintype V] [DecidableEq V] (m q : Mate V) (S : Finset V) + (hm : HasHoles m S) (hq : HasHoles q Sᶜ) : HasHoles (fillHoles m q S hm hq) ∅ := by + classical + intro v + simp only [fillHoles_apply, Finset.notMem_empty, iff_false] + by_cases hv : v ∈ S + · rw [ite_eq_left hv] + intro he + exact (Finset.mem_compl.mp ((hq v).mp he)) hv + · rw [ite_eq_right hv] + intro he + exact hv ((hm v).mp he) + +theorem fillHoles_injective [Fintype V] [DecidableEq V] (q : Mate V) (S : Finset V) + (hq : HasHoles q Sᶜ) : Function.Injective + (fun m : {m : Mate V // HasHoles m S} => fillHoles m.1 q S m.2 hq) := by + classical + intro m n he + apply Subtype.ext + apply Subtype.ext + funext v + by_cases hv : v ∈ S + · exact ((m.2 v).mpr hv).trans ((n.2 v).mpr hv).symm + · have h := congrArg (fun r : Mate V => r.1 v) he + simpa [hv] using h + +theorem fillHoles_weight_le [Fintype V] [LinearOrder V] + (w d u : V → V → ℝ) (hw : ∀ a b, 0 ≤ w a b) (hd : ∀ a b, 0 ≤ d a b) + (hwu : ∀ a b, w a b ≤ u a b) (hdu : ∀ a b, d a b ≤ u a b) + (m q : Mate V) (S : Finset V) (hm : HasHoles m S) (hq : HasHoles q Sᶜ) : + weight w m * weight d q ≤ weight u (fillHoles m q S hm hq) := by + classical + unfold weight + rw [← Finset.prod_mul_distrib] + apply Finset.prod_le_prod₀ + · intro v _ + exact mul_nonneg (by split_ifs; exact hw _ _; norm_num) + (by split_ifs; exact hd _ _; norm_num) + · intro v _ + rw [fillHoles_apply] + by_cases hv : v ∈ S + · have hmfix := (hm v).mpr hv + simp only [hv, ite_true, hmfix, lt_self_iff_false, ite_false, one_mul] + split_ifs + · exact hdu _ _ + · rfl + · have hqfix := (hq v).mpr (Finset.mem_compl.mpr hv) + simp only [hv, ite_false, hqfix, lt_self_iff_false, mul_one] + split_ifs + · exact hwu _ _ + · rfl + +theorem fillHoles_partition_le [Fintype V] [LinearOrder V] + (w d u : V → V → ℝ) (hw : ∀ a b, 0 ≤ w a b) (hd : ∀ a b, 0 ≤ d a b) + (hwu : ∀ a b, w a b ≤ u a b) (hdu : ∀ a b, d a b ≤ u a b) + (q : Mate V) (S : Finset V) (hq : HasHoles q Sᶜ) : + partition w S * weight d q ≤ partition u ∅ := by + classical + let f : Mate V → Mate V := fun m => + if hm : HasHoles m S then fillHoles m q S hm hq else m + have hi : Set.InjOn f (matchings S) := by + intro m hm n hn he + have hm' := (mem_matchings m S).mp hm + have hn' := (mem_matchings n S).mp hn + have h : (⟨m,hm'⟩ : {m : Mate V // HasHoles m S}) = ⟨n,hn'⟩ := + fillHoles_injective q S hq (by simpa [f,hm',hn'] using he) + exact congrArg Subtype.val h + have hsub : (matchings S).image f ⊆ matchings ∅ := by + intro m hm + obtain ⟨n,hn,rfl⟩ := Finset.mem_image.mp hm + have hn' := (mem_matchings n S).mp hn + simp only [f,dite_eq_left hn',mem_matchings] + exact fillHoles_perfect n q S hn' hq + calc + partition w S * weight d q = ∑ m ∈ matchings S, weight w m * weight d q := + Finset.sum_mul _ _ _ + _ ≤ ∑ m ∈ matchings S, weight u (f m) := by + apply Finset.sum_le_sum + intro m hm + have hm' := (mem_matchings m S).mp hm + simpa [f,hm'] using fillHoles_weight_le w d u hw hd hwu hdu m q S hm' hq + _ = ∑ m ∈ (matchings S).image f, weight u m := (Finset.sum_image hi).symm + _ ≤ partition u ∅ := Finset.sum_le_sum_of_subset_of_nonneg hsub + (fun m _ _ => weight_nonneg u (fun a b => (hw a b).trans (hwu a b)) m) + +theorem mate_edge_count [Fintype V] [LinearOrder V] (q : Mate V) (S : Finset V) + (hq : HasHoles q Sᶜ) : + 2 * (Finset.univ.filter (fun v => v < q.1 v)).card = S.card := by + let L := Finset.univ.filter (fun v => v < q.1 v) + let R := Finset.univ.filter (fun v => q.1 v < v) + have himg : L.image q.1 = R := by + ext v + simp only [Finset.mem_image, L,R,Finset.mem_filter,Finset.mem_univ,true_and] + constructor + · rintro ⟨a,ha,rfl⟩ + simpa using ha + · intro hv + exact ⟨q.1 v,by simpa using hv,mate_mate q v⟩ + have hcard : L.card = R.card := by + rw [← himg] + exact (Finset.card_image_of_injective L q.2.injective).symm + have hdis : Disjoint L R := by + apply Finset.disjoint_left.mpr + intro v hl hr + have hl' : v < q.1 v := (Finset.mem_filter.mp hl).2 + have hr' : q.1 v < v := (Finset.mem_filter.mp hr).2 + exact (lt_asymm hl' hr') + have hunion : L ∪ R = S := by + ext v + simp only [L,R,Finset.mem_union,Finset.mem_filter,Finset.mem_univ,true_and] + rw [← ne_iff_lt_or_gt] + have h := hq v + simp only [Finset.mem_compl] at h + simpa only [ne_eq, eq_comm, not_not] using (not_congr h) + have hc := Finset.card_union_of_disjoint hdis + rw [hunion,← hcard] at hc + change 2 * L.card = S.card + omega + +theorem weight_div_const [Fintype V] [LinearOrder V] + (w : V → V → ℝ) (c : ℝ) (q : Mate V) (S : Finset V) (hq : HasHoles q Sᶜ) : + weight (fun a b => w a b / c) q = weight w q / c^(S.card/2) := by + have hc : (Finset.univ.filter (fun v => v < q.1 v)).card = S.card/2 := by + have := mate_edge_count q S hq + omega + unfold weight + rw [← Finset.prod_filter, ← Finset.prod_filter, Finset.prod_div_distrib] + simp only [Finset.prod_const, hc] + +theorem pairing_exists [Fintype V] [DecidableEq V] (S : Finset V) (hS : Even S.card) : + ∃ q : Mate V, HasHoles q Sᶜ := by + classical + induction S using Finset.strongInductionOn with + | _ S ih => + by_cases hEmpty : S = ∅ + · subst S + refine ⟨⟨id,fun _ => rfl⟩,?_⟩ + intro v + simp + · obtain ⟨a,ha⟩ := Finset.nonempty_iff_ne_empty.mpr hEmpty + have hcardpos := Finset.card_pos.mpr (show S.Nonempty from ⟨a,ha⟩) + have hcard2 : 2 ≤ S.card := by obtain ⟨k,hk⟩ := hS; omega + have herase : (S.erase a).Nonempty := by + apply Finset.card_pos.mp + rw [Finset.card_erase_of_mem ha] + omega + obtain ⟨b,hb⟩ := herase + have hba := (Finset.mem_erase.mp hb).1 + have hbS := (Finset.mem_erase.mp hb).2 + let T := S \ {a,b} + have hTcard : T.card + 2 = S.card := by + have h := sdiff_pair_card S a b ha hbS hba.symm + change T.card = S.card - 2 at h + omega + have hTeven : Even T.card := by + obtain ⟨k,hk⟩ := hS + refine ⟨k-1,?_⟩ + omega + have hTsub : T ⊂ S := Finset.ssubset_iff_subset_ne.mpr + ⟨Finset.sdiff_subset,by intro he; have := congrArg Finset.card he; omega⟩ + obtain ⟨q,hq⟩ := ih T hTsub hTeven + have haT : a ∈ Tᶜ := by simp [T] + have hbT : b ∈ Tᶜ := by simp [T] + refine ⟨withEdge q a b,?_⟩ + have hh := withEdge_holes q Tᶜ hq a b haT hbT hba.symm + have he : Tᶜ \ {a,b} = Sᶜ := by + ext v + simp only [T,Finset.mem_sdiff,Finset.mem_compl,Finset.mem_insert,Finset.mem_singleton] + have hsub : ({a,b} : Finset V) ⊆ S := by + intro x hx + simp only [Finset.mem_insert,Finset.mem_singleton] at hx + rcases hx with rfl | rfl <;> assumption + constructor + · intro h + tauto + · intro hv + constructor + · tauto + · intro hvp + exact hv (hsub (by simpa using hvp)) + rwa [he] at hh + +noncomputable def pairingCapacity [Fintype V] [LinearOrder V] + (B : V → V → ℝ) (S : Finset V) (hS : Even S.card) : ℝ := + (matchings Sᶜ).sup' (by + obtain ⟨q,hq⟩ := pairing_exists S hS + exact ⟨q,(mem_matchings q Sᶜ).mpr hq⟩) (weight B) + +theorem logical_hole_bound [Fintype V] [LinearOrder V] + (hn : 2 ≤ Fintype.card V) (w : V → V → ℝ) + (hw : ∀ a b, 0 ≤ w a b) (hz : 0 < partition w ∅) + (hrlo : ∀ a, (1:ℝ)/4 ≤ rowMax hn w a) (hrhi : ∀ a, rowMax hn w a ≤ 1) + (S : Finset V) (hS : Even S.card) : + holeRatio w S * pairingCapacity (bottleneck w) S hS ≤ + 2 * holeScale V ^ (S.card / 2) := by + classical + obtain ⟨q,hq,hmax⟩ := Finset.exists_mem_eq_sup' + (show (matchings Sᶜ).Nonempty from by + obtain ⟨q,hq⟩ := pairing_exists S hS + exact ⟨q,(mem_matchings _ _).mpr hq⟩) (weight (bottleneck w)) + have hq' := (mem_matchings q Sᶜ).mp hq + have hc : pairingCapacity (bottleneck w) S hS = weight (bottleneck w) q := hmax + let d := holeAugmentation w + let u := affineWeights w d 1 + have hd : ∀ a b, 0 ≤ d a b := holeAugmentation_nonneg w + have hfill := fillHoles_partition_le w d u hw hd + (fun a b => by change w a b ≤ w a b + 1*d a b; linarith [hd a b]) + (fun a b => by change d a b ≤ w a b + 1*d a b; linarith [hw a b]) q S hq' + have hinfl := logical_inflation hn w hw hz hrlo hrhi + have hdiv : weight d q = weight (bottleneck w) q / holeScale V ^ (S.card/2) := + weight_div_const (bottleneck w) (holeScale V) q S hq' + rw [hdiv] at hfill + rw [hc,holeRatio] + have hpow : 0 < holeScale V ^ (S.card/2) := pow_pos holeScale_pos _ + have hmain : partition w S * weight (bottleneck w) q ≤ + 2 * partition w ∅ * holeScale V ^ (S.card/2) := by + have h' := hfill.trans hinfl.le + rw [← mul_div_assoc, div_le_iff₀ hpow] at h' + exact h' + rw [div_mul_eq_mul_div, div_le_iff₀ hz] + nlinarith only [hmain] + +end MatchingFPRAS.Switching + +end OAI diff --git a/lean/OAI/Combinatorics/MatchingCount/Graphs/FirstHoleSortedCons.lean b/lean/OAI/Combinatorics/MatchingCount/Graphs/FirstHoleSortedCons.lean new file mode 100644 index 0000000000000000000000000000000000000000..1e5df392a61d189c314aa68b056b814ccdb379d8 --- /dev/null +++ b/lean/OAI/Combinatorics/MatchingCount/Graphs/FirstHoleSortedCons.lean @@ -0,0 +1,229 @@ +import Mathlib +import OAI.Combinatorics.MatchingCount.Graphs.HoleBlocks + +namespace OAI + +namespace MatchingFPRAS.Subdivision + +section + +open Finset + +lemma first_hole_of_sorted_cons {m : ℕ} {U : Finset (Fin m)} {b : Selection m} + (hb : Valid U b) (j : Fin m) (xs : List (Fin m)) (he : U.sort (· ≤ ·)=j::xs) : + b 0=true ↔ j.val%2=1 := by + apply first_hole_terminal hb j + · exact (Finset.mem_sort (· ≤ ·)).mp (he ▸ List.mem_cons_self) + · intro i hi + have hmem : i ∈ j::xs := he ▸ (Finset.mem_sort (· ≤ ·)).mpr hi + have hsort := U.pairwise_sort (· ≤ ·) + rw [he] at hsort + rcases List.mem_cons.mp hmem with rfl | hmem + · rfl + · exact (List.pairwise_cons.mp hsort).1 i hmem + +lemma last_hole_of_sorted_append {m : ℕ} (hm : Even m) {U : Finset (Fin m)} {b : Selection m} + (hb : Valid U b) (j : Fin m) (xs : List (Fin m)) (he : U.sort (· ≤ ·)=xs++[j]) : + b (Fin.last m)=true ↔ j.val%2=0 := by + apply last_hole_terminal hm hb j + · exact (Finset.mem_sort (· ≤ ·)).mp (he ▸ (by simp)) + · intro i hi + have hmem : i ∈ xs++[j] := he ▸ (Finset.mem_sort (· ≤ ·)).mpr hi + have hsort := U.pairwise_sort (· ≤ ·) + rw [he] at hsort + rcases List.mem_append.mp hmem with hmem | hmem + · exact (List.pairwise_append.mp hsort).2.2 i hmem j (by simp) + · have hij : i=j := by simpa using hmem + exact hij.le + +theorem HoleBlocks.left_uses {m : ℕ} {U : Finset (Fin m)} {b : Selection m} + (hb : Valid U b) (hU : U.Nonempty) (d : HoleBlocks m) + (he : d.flatten=U.sort (· ≤ ·)) (hp : d.Parity) : + b 0=true ↔ d.left.isSome := by + cases hl : d.left with + | some j => + have hs : U.sort (· ≤ ·)=j::(d.neutral.flatMap (fun q => [q.1,q.2])++d.right.toList) := by + simpa [HoleBlocks.flatten,hl,List.append_assoc] using he.symm + have hj := hp.1 j (by simp [hl]) + simpa [hl,hj] using first_hole_of_sorted_cons hb j _ hs + | none => + cases hn : d.neutral with + | cons q xs => + have hs : U.sort (· ≤ ·)=q.1::(q.2::(xs.flatMap (fun q => [q.1,q.2])++d.right.toList)) := by + simpa [HoleBlocks.flatten,hl,hn,List.append_assoc] using he.symm + have hj := (hp.2.1 q (by simp [hn])).1 + simpa [hl,hj] using first_hole_of_sorted_cons hb q.1 _ hs + | nil => + cases hr : d.right with + | some j => + have hs : U.sort (· ≤ ·)=[j] := by simpa [HoleBlocks.flatten,hl,hn,hr] using he.symm + have hj := hp.2.2 j (by simp [hr]) + simpa [hl,hj] using first_hole_of_sorted_cons hb j [] hs + | none => + have hs : U.sort (· ≤ ·)=[] := by simpa [HoleBlocks.flatten,hl,hn,hr] using he.symm + obtain ⟨j,hj⟩ := hU + have : j ∈ U.sort (· ≤ ·) := (Finset.mem_sort (· ≤ ·)).mpr hj + simp [hs] at this + +theorem HoleBlocks.right_uses {m : ℕ} (hm : Even m) {U : Finset (Fin m)} {b : Selection m} + (hb : Valid U b) (hU : U.Nonempty) (d : HoleBlocks m) + (he : d.flatten=U.sort (· ≤ ·)) (hp : d.Parity) : + b (Fin.last m)=true ↔ d.right.isSome := by + cases hr : d.right with + | some j => + have hs : U.sort (· ≤ ·)=(d.left.toList++d.neutral.flatMap (fun q => [q.1,q.2]))++[j] := by + simpa [HoleBlocks.flatten,hr] using he.symm + have hj := hp.2.2 j (by simp [hr]) + simpa [hr,hj] using last_hole_of_sorted_append hm hb j _ hs + | none => + generalize hn : d.neutral=xs at hp he + cases xs using List.reverseRecOn with + | nil => + cases hl : d.left with + | some j => + have hs : U.sort (· ≤ ·)=[]++[j] := by simpa [HoleBlocks.flatten,hl,hn,hr] using he.symm + have hj := hp.1 j (by simp [hl]) + simpa [hr,hj] using last_hole_of_sorted_append hm hb j [] hs + | none => + have hs : U.sort (· ≤ ·)=[] := by simpa [HoleBlocks.flatten,hl,hn,hr] using he.symm + obtain ⟨j,hj⟩ := hU + have : j ∈ U.sort (· ≤ ·) := (Finset.mem_sort (· ≤ ·)).mpr hj + simp [hs] at this + | append_singleton xs q => + have hs : U.sort (· ≤ ·)=(d.left.toList++xs.flatMap (fun q => [q.1,q.2])++[q.1])++[q.2] := by + simpa [HoleBlocks.flatten,hr,hn,List.flatMap_append,List.append_assoc] using he.symm + have hj := (hp.2.1 q (by simp [hn])).2 + simpa [hr,hj] using last_hole_of_sorted_append hm hb q.2 _ hs + +theorem HoleBlocks.neutral_lt {m : ℕ} {U : Finset (Fin m)} (d : HoleBlocks m) + (he : d.flatten=U.sort (· ≤ ·)) (q : Fin m × Fin m) (hq : q ∈ d.neutral) : + q.1.val < q.2.val := by + have hp : d.flatten.Pairwise (· < ·) := he ▸ U.sortedLT_sort.pairwise + have hn : (d.neutral.flatMap (fun q => [q.1,q.2])).Pairwise (· < ·) := + (List.pairwise_append.mp (List.pairwise_append.mp hp).1).2.1 + have hq' := (List.pairwise_flatMap.mp hn).1 q hq + simpa using hq' + +lemma HoleBlocks.flatten_nodup {m : ℕ} {U : Finset (Fin m)} (d : HoleBlocks m) + (he : d.flatten=U.sort (· ≤ ·)) : d.flatten.Nodup := he ▸ U.sort_nodup (· ≤ ·) + +lemma HoleBlocks.left_mem {m : ℕ} {U : Finset (Fin m)} (d : HoleBlocks m) + (he : d.flatten=U.sort (· ≤ ·)) {j : Fin m} (hj : j ∈ d.left) : j ∈ U := by + apply (Finset.mem_sort (· ≤ ·)).mp + rw [← he] + simp only [HoleBlocks.flatten,List.mem_append,Option.mem_toList] + exact Or.inl (Or.inl hj) + +lemma HoleBlocks.right_mem {m : ℕ} {U : Finset (Fin m)} (d : HoleBlocks m) + (he : d.flatten=U.sort (· ≤ ·)) {j : Fin m} (hj : j ∈ d.right) : j ∈ U := by + apply (Finset.mem_sort (· ≤ ·)).mp + rw [← he] + simp only [HoleBlocks.flatten,List.mem_append,Option.mem_toList] + exact Or.inr hj + +lemma HoleBlocks.neutral_mem {m : ℕ} {U : Finset (Fin m)} (d : HoleBlocks m) + (he : d.flatten=U.sort (· ≤ ·)) {q : Fin m × Fin m} (hq : q ∈ d.neutral) : + q.1 ∈ U ∧ q.2 ∈ U := by + have h (j : Fin m) (hj : j ∈ [q.1,q.2]) : j ∈ U := by + apply (Finset.mem_sort (· ≤ ·)).mp + rw [← he] + have hn : j ∈ d.neutral.flatMap (fun q => [q.1,q.2]) := List.mem_flatMap.mpr ⟨q,hq,hj⟩ + simp only [HoleBlocks.flatten,List.mem_append] + tauto + exact ⟨h _ (by simp),h _ (by simp)⟩ + +lemma HoleBlocks.reorder {m : ℕ} (d : HoleBlocks m) : + d.flatten.Perm (d.neutral.flatMap (fun q => [q.1,q.2]) ++ (d.left.toList++d.right.toList)) := by + unfold HoleBlocks.flatten + exact (List.perm_append_comm.append_right _).trans (by rw [List.append_assoc]) + +lemma HoleBlocks.reordered_nodup {m : ℕ} {U : Finset (Fin m)} (d : HoleBlocks m) + (he : d.flatten=U.sort (· ≤ ·)) : + (d.neutral.flatMap (fun q => [q.1,q.2]) ++ (d.left.toList++d.right.toList)).Nodup := + d.reorder.nodup_iff.mp (d.flatten_nodup he) + +end + +variable {V E : Type*} [Fintype V] [Fintype E] + +omit [Fintype V] [Fintype E] in +lemma uses_not_hole [Fintype V] [Fintype E] + {m : ℕ} {u v : E → V} {R₀ : Finset V} {U : E → Finset (Fin m)} + {b : E → Selection m} (hb : FamilyHoles u v m R₀ U b) {e : E} {x : V} + (he : Uses u v b e x) : x ∉ R₀ := fun hx => hb.2.1 x hx e he + +lemma uses_unique {m : ℕ} {u v : E → V} {R₀ : Finset V} {U : E → Finset (Fin m)} + {b : E → Selection m} (hb : FamilyHoles u v m R₀ U b) {e e' : E} {x : V} + (he : Uses u v b e x) (he' : Uses u v b e' x) : e=e' := + (hb.2.2 x (uses_not_hole hb he)).unique he he' + +omit [Fintype V] [Fintype E] in +lemma left_consumes [Fintype V] [Fintype E] + {m : ℕ} {u v : E → V} {R₀ : Finset V} {U : E → Finset (Fin m)} + {b : E → Selection m} (hb : FamilyHoles u v m R₀ U b) + (d : E → HoleBlocks m) (he : ∀ e, (d e).flatten=(U e).sort (· ≤ ·)) + (hp : ∀ e, (d e).Parity) (e : E) {j : Fin m} (hj : j ∈ (d e).left) : + Uses u v b e (u e) := by + have hU : (U e).Nonempty := ⟨j,(d e).left_mem (he e) hj⟩ + have hs : (d e).left.isSome := by cases h : (d e).left <;> simp [h] at hj ⊢ + exact Or.inl ⟨((d e).left_uses (hb.1 e) hU (he e) (hp e)).mpr hs,rfl⟩ + +omit [Fintype V] [Fintype E] in +lemma right_consumes [Fintype V] [Fintype E] + {m : ℕ} (hm : Even m) {u v : E → V} {R₀ : Finset V} {U : E → Finset (Fin m)} + {b : E → Selection m} (hb : FamilyHoles u v m R₀ U b) + (d : E → HoleBlocks m) (he : ∀ e, (d e).flatten=(U e).sort (· ≤ ·)) + (hp : ∀ e, (d e).Parity) (e : E) {j : Fin m} (hj : j ∈ (d e).right) : + Uses u v b e (v e) := by + have hU : (U e).Nonempty := ⟨j,(d e).right_mem (he e) hj⟩ + have hs : (d e).right.isSome := by cases h : (d e).right <;> simp [h] at hj ⊢ + exact Or.inr ⟨((d e).right_uses hm (hb.1 e) hU (he e) (hp e)).mpr hs,rfl⟩ + +lemma internalStrength_le_twice_incident (p : ℕ) (hp : 1≤p) (B Hu Hv : ℝ) + (hB : 0≤B) (hHu : 0≤Hu) (hHv : 0≤Hv) + (hinnerL : max B (Hu/2^(p-1))=B) (hinnerR : max B (Hv/2^(p-1))=B) + (j : Fin (4*p)) : + internalStrength p B Hu Hv j ≤ 2*profileActivity p B Hu Hv B j.castSucc ∧ + internalStrength p B Hu Hv j ≤ 2*profileActivity p B Hu Hv B j.succ := by + have two_self (x : ℝ) (hx : B≤x) : x≤2*x := by linarith + by_cases hj : j.val<2*p + · rw [internalStrength,ite_eq_left hj] + constructor + · rw [profile_left _ _ _ _ _ _ hj] + exact two_self _ (le_max_left _ _) + · by_cases hk : j.val+1<2*p + · rw [profile_left _ _ _ _ _ _ hk] + calc + _ ≤ 2*max B (Hu/2^(j.val/2+1)) := legValue_step B Hu hB _ + _ ≤ _ := mul_le_mul_of_nonneg_left + (legValue_antitone B Hu hHu (by simp only [Fin.val_succ]; omega)) (by norm_num) + · have he : j.succ=⟨2*p,by omega⟩ := Fin.ext (by simp only [Fin.val_succ]; omega) + rw [he,profile_center,show j.val/2=p-1 by omega,hinnerL] + exact two_self _ le_rfl + · rw [internalStrength,ite_eq_right hj] + constructor + · by_cases hk : 2*p sourceHeight_bound w K hw x) + +noncomputable def sourceLevels (w : V → V → ℝ) (K : ℕ) : ℕ := + (dyadicLevel (2*K) (maxSourceHeight w)).val + +lemma sourceLevels_le (w : V → V → ℝ) (K : ℕ) : sourceLevels w K ≤ 2*K := by + have := (dyadicLevel (2*K) (maxSourceHeight w)).isLt + dsimp [sourceLevels]; omega + +lemma maxSourceHeight_lt (w : V → V → ℝ) (K : ℕ) + (hw : ∀ x y, x ≠ y → edgeActivity w x y ≤ (4:ℝ)^K) : + maxSourceHeight w < (2:ℝ)^(sourceLevels w K+1) := by + apply dyadic_upper + convert maxSourceHeight_bound w K hw using 1 + rw [pow_mul]; norm_num + +abbrev SourceVertex (V : Type*) [LinearOrder V] (K : ℕ) := Vertex V (LogicalEdge V) (4*(2*K+2)) + +abbrev SourceRealEdge (V : Type*) [LinearOrder V] (K : ℕ) := LogicalEdge V × Fin (4*(2*K+2)+1) + +def realLeft (K : ℕ) (e : SourceRealEdge V K) : SourceVertex V K := + atVertex source target (4*(2*K+2)) e.1 e.2.castSucc + +def realRight (K : ℕ) (e : SourceRealEdge V K) : SourceVertex V K := + atVertex source target (4*(2*K+2)) e.1 e.2.succ + +noncomputable def sourceRealB (w : V → V → ℝ) (K : ℕ) : SourceVertex V K → SourceVertex V K → ℝ := + realBottleneck source target (2*K+2) (fun e => bottleneck w (source e) (target e)) + (fun e => sourceHeight w (source e)) (fun e => sourceHeight w (target e)) (logicalActivity w) + +lemma source_profile_strength (w : V → V → ℝ) (K : ℕ) + (hw : ∀ x y, x ≠ y → edgeActivity w x y ≤ (4:ℝ)^K) (e : SourceRealEdge V K) : + sourceRealB w K (realLeft K e) (realRight K e) = + profileActivity (2*K+2) (bottleneck w (source e.1) (target e.1)) + (sourceHeight w (source e.1)) (sourceHeight w (target e.1)) + (bottleneck w (source e.1) (target e.1)) e.2 := by + apply source_effective_profile + · omega + · intro e; exact sourceHeight_nonneg w _ + · intro e; exact sourceHeight_nonneg w _ + · intro f + rw [show 2*K+2-1=2*K+1 by omega] + exact profile_innermost K _ _ (one_le_bottleneck _ _ _) (sourceHeight_bound w K hw _) + +lemma source_strength_incident_near (w : V → V → ℝ) (K : ℕ) + (hw : ∀ x y, x ≠ y → edgeActivity w x y ≤ (4:ℝ)^K) + (x : SourceVertex V K) (e f : SourceRealEdge V K) + (he : Incident (realLeft K) (realRight K) e x) + (hf : Incident (realLeft K) (realRight K) f x) : + sourceRealB w K (realLeft K e) (realRight K e) ≤ 2*sourceRealB w K (realLeft K f) (realRight K f) := by + simp only [source_profile_strength w K hw] + apply effective_profile_incident_near source target (2*K+2) (by omega) + (fun e => bottleneck w (source e) (target e)) (sourceHeight w) + · intro e; exact zero_le_one.trans (one_le_bottleneck _ _ _) + · exact sourceHeight_nonneg w + · intro e + exact ⟨bottleneck_le_sourceHeight w (source_ne_target e),by + rw [bottleneck_comm]; exact bottleneck_le_sourceHeight w (source_ne_target e).symm⟩ + · intro e + rw [show 2*K+2-1=2*K+1 by omega] + exact profile_innermost K _ _ (one_le_bottleneck _ _ _) (sourceHeight_bound w K hw _) + · intro e + rw [show 2*K+2-1=2*K+1 by omega] + exact profile_innermost K _ _ (one_le_bottleneck _ _ _) (sourceHeight_bound w K hw _) + · exact he + · exact hf + +lemma profile_upper (p : ℕ) (B HU HV lam T : ℝ) (hB : B ≤ T) (hU : HU ≤ T) (hV : HV ≤ T) + (hU0 : 0 ≤ HU) (hV0 : 0 ≤ HV) (hlam : lam ≤ T) (i : Fin (4*p+1)) : + profileActivity p B HU HV lam i ≤ T := by + rcases lt_trichotomy i.val (2*p) with h | h | h + · rw [profile_left _ _ _ _ _ _ h] + exact max_le hB ((div_le_self hU0 (one_le_pow₀ (by norm_num))).trans hU) + · have hi : i=⟨2*p,by omega⟩ := Fin.ext h + rw [hi,profile_center]; exact hlam + · rw [profile_right _ _ _ _ _ _ h] + exact max_le hB ((div_le_self hV0 (one_le_pow₀ (by norm_num))).trans hV) + +lemma source_strength_le_max (w : V → V → ℝ) (K : ℕ) + (hw : ∀ x y, x ≠ y → edgeActivity w x y ≤ (4:ℝ)^K) (e : SourceRealEdge V K) : + sourceRealB w K (realLeft K e) (realRight K e) ≤ maxSourceHeight w := by + rw [source_profile_strength w K hw] + have hb := (bottleneck_le_sourceHeight w (source_ne_target e.1)).trans (sourceHeight_le_max w _) + exact profile_upper _ _ _ _ _ _ hb (sourceHeight_le_max w _) (sourceHeight_le_max w _) + (sourceHeight_nonneg w _) (sourceHeight_nonneg w _) hb _ + +lemma sourceRealB_comm (w : V → V → ℝ) (K : ℕ) (x y : SourceVertex V K) : + sourceRealB w K x y = sourceRealB w K y x := bottleneck_comm _ _ _ + +lemma sourceRealB_tri (w : V → V → ℝ) (K : ℕ) (x y z : SourceVertex V K) + (hxy : x ≠ y) (hxz : x ≠ z) (hyz : y ≠ z) : + min (sourceRealB w K x z) (sourceRealB w K z y) ≤ sourceRealB w K x y := + bottleneck_ultrametric _ _ _ _ hxy hxz hyz + +lemma sourceRealB_floor (w : V → V → ℝ) (K : ℕ) (x y : SourceVertex V K) : + 1 ≤ sourceRealB w K x y := one_le_bottleneck _ _ _ + +abbrev SourceLabel (w : V → V → ℝ) (K : ℕ) := + Label (sourceRealB w K) (sourceRealB_comm w K) (sourceRealB_tri w K) (sourceLevels w K) + +noncomputable def sourceBags (w : V → V → ℝ) (K : ℕ) (x : SourceVertex V K) : + Finset (SourceLabel w K) := + memberships (sourceRealB w K) (sourceRealB_comm w K) (sourceRealB_tri w K) + (realLeft K) (realRight K) (sourceLevels w K) x + +noncomputable abbrev sourceTree (w : V → V → ℝ) (K : ℕ) : SimpleGraph (SourceLabel w K) := + tree (sourceRealB w K) (sourceRealB_comm w K) (sourceRealB_tri w K) + +lemma sourceTree_isTree (w : V → V → ℝ) (K : ℕ) : (sourceTree w K).IsTree := by + exact ⟨tree_connected _ _ _ (sourceRealB_floor w K) _,tree_acyclic _ _ _ _⟩ + +lemma sourceBag_card_le_two (w : V → V → ℝ) (K : ℕ) + (hw : ∀ x y, x ≠ y → edgeActivity w x y ≤ (4:ℝ)^K) (x : SourceVertex V K) : + (sourceBags w K x).card ≤ 2 := by + apply membership_count + · exact sourceRealB_floor w K + · intro e + exact (source_strength_le_max w K hw e).trans_lt (maxSourceHeight_lt w K hw) + · exact source_strength_incident_near w K hw + +lemma sourceBag_tree_adjacent (w : V → V → ℝ) (K : ℕ) + (hw : ∀ x y, x ≠ y → edgeActivity w x y ≤ (4:ℝ)^K) + (x : SourceVertex V K) (a b : SourceLabel w K) + (ha : a ∈ sourceBags w K x) (hb : b ∈ sourceBags w K x) : + a=b ∨ (sourceTree w K).Adj a b := by + apply memberships_tree_bags _ _ _ (sourceRealB_floor w K) (realLeft K) (realRight K) + (sourceLevels w K) (fun e => (source_strength_le_max w K hw e).trans_lt + (maxSourceHeight_lt w K hw)) (source_strength_incident_near w K hw) x a b ha hb + +lemma sourceBag_height (w : V → V → ℝ) (K : ℕ) {x y : SourceVertex V K} + (hxy : x ≠ y) (l : SourceLabel w K) (hx : l ∈ sourceBags w K x) + (hy : l ∈ sourceBags w K y) : (2:ℝ)^l.1.val ≤ sourceRealB w K x y := by + exact common_height_le _ _ _ (sourceRealB_floor w K) (realLeft K) (realRight K) + (sourceLevels w K) hxy hx hy + +end MatchingFPRAS.Enlargement + +namespace MatchingFPRAS.Transport + +section + +open Finset + +variable {V E : Type*} [Fintype V] [Fintype E] [DecidableEq V] [DecidableEq E] + +variable (inc : E → V → Prop) + +noncomputable def support (Q : Finset E) : Finset V := by + classical + exact Finset.univ.filter fun v => ∃ e ∈ Q, inc e v + +omit [Fintype E] [DecidableEq V] [DecidableEq E] in +lemma mem_support (Q : Finset E) (v : V) : v ∈ support inc Q ↔ ∃ e ∈ Q, inc e v := by + classical + simp [support] + +omit [Fintype E] [DecidableEq V] [DecidableEq E] in +lemma support_eq_of_matching {Q : Finset E} {U : Finset V} (h : MatchingOn inc Q U) : + support inc Q=U := by + ext v + rw [mem_support] + constructor + · rintro ⟨e,he,hv⟩; exact h.1 e he v hv + · intro hv + obtain ⟨e,he,_⟩ := h.2 v hv + exact ⟨e,he⟩ + +abbrev Partial := {Q : Finset E // MatchingOn inc Q (support inc Q)} + +abbrev Matchings (U : Finset V) := {M : Finset E // MatchingOn inc M U} + +noncomputable instance partialFintype : Fintype (Partial inc) := Fintype.ofFinite _ + +noncomputable instance matchingsFintype (U : Finset V) : Fintype (Matchings inc U) := Fintype.ofFinite _ + +omit [Fintype E] [DecidableEq V] [DecidableEq E] in +lemma submatching {M Q : Finset E} {U : Finset V} (hM : MatchingOn inc M U) (hQ : Q⊆M) : + MatchingOn inc Q (support inc Q) := by + refine ⟨?_,?_⟩ + · intro e he v hv; exact (mem_support inc Q v).mpr ⟨e,he,hv⟩ + · intro v hv + obtain ⟨e,he,hev⟩ := (mem_support inc Q v).mp hv + refine ⟨e,⟨he,hev⟩,?_⟩ + intro f hf + exact hM.unique (hM.1 e (hQ he) v hev) (hQ hf.1) hf.2 (hQ he) hev + +omit [Fintype E] [DecidableEq E] in +lemma support_sdiff_disjoint (Q : Finset E) : Disjoint (support inc Q) (univ \ support inc Q) := by + exact Finset.disjoint_left.mpr (fun x hx hy => (Finset.mem_sdiff.mp hy).2 hx) + +noncomputable def expansionEquiv (hinc : ∀ e, ∃ v, inc e v) : + (Σ M : Matchings inc univ, {Q : Finset E // Q⊆M.val}) ≃ + Σ Q : Partial inc, Matchings inc (univ \ support inc Q.val) where + toFun a := ⟨⟨a.2.val,submatching inc a.1.property a.2.property⟩, + ⟨a.1.val \ a.2.val,a.1.property.sdiff + (submatching inc a.1.property a.2.property) a.2.property⟩⟩ + invFun a := ⟨⟨a.1.val ∪ a.2.val,by + have h := a.1.property.union a.2.property (support_sdiff_disjoint inc a.1.val) + rw [Finset.union_sdiff_of_subset (Finset.subset_univ _)] at h + exact h⟩,⟨a.1.val,Finset.subset_union_left⟩⟩ + left_inv a := by + rcases a with ⟨M,Q,hQ⟩ + have h : Q ∪ (M.val \ Q)=M.val := Finset.union_sdiff_of_subset hQ + apply Sigma.ext (Subtype.ext h) + change HEq (⟨Q,Finset.subset_union_left⟩ : {R : Finset E // R ⊆ Q ∪ (M.val \ Q)}) + (⟨Q,hQ⟩ : {R : Finset E // R ⊆ M.val}) + exact (Subtype.heq_iff_coe_eq (fun R => by rw [h])).mpr rfl + right_inv a := by + rcases a with ⟨Q,M⟩ + have hd : Disjoint Q.val M.val := Q.property.disjoint_edges M.property hinc + (support_sdiff_disjoint inc Q.val) + change (⟨Q,⟨(Q.val ∪ M.val) \ Q.val,_⟩⟩ : + Σ Q : Partial inc, Matchings inc (univ \ support inc Q.val)) = ⟨Q,M⟩ + apply congrArg (fun R : Matchings inc (univ \ support inc Q.val) => + (⟨Q,R⟩ : Σ Q : Partial inc, Matchings inc (univ \ support inc Q.val))) + exact Subtype.ext (Finset.union_sdiff_cancel_left hd) + +noncomputable def partitionWeight {R : Type*} [CommSemiring R] (w : E → R) (U : Finset V) : R := + ∑ M : Matchings inc U, ∏ e ∈ M.val, w e + +theorem partition_add {R : Type*} [CommSemiring R] (r v : E → R) + (hinc : ∀ e, ∃ x, inc e x) : + partitionWeight inc (fun e => r e+v e) univ = + ∑ Q : Partial inc, (∏ e ∈ Q.val, v e) * partitionWeight inc r (univ \ support inc Q.val) := by + classical + unfold partitionWeight + have hex (M : Matchings inc univ) : + (∏ e ∈ M.val, (r e+v e)) = + ∑ Q : {Q : Finset E // Q⊆M.val}, (∏ e ∈ Q.val, v e) * ∏ e ∈ M.val \ Q.val, r e := by + rw [show (∏ e ∈ M.val, (r e+v e))=(∏ e ∈ M.val, (v e+r e)) by + apply Finset.prod_congr rfl; intro e he; exact add_comm _ _] + rw [Finset.prod_add] + exact Finset.sum_subtype _ (fun Q => Finset.mem_powerset) + (fun Q => (∏ e ∈ Q, v e) * ∏ e ∈ M.val \ Q, r e) + simp_rw [hex,Finset.mul_sum] + have h := (expansionEquiv inc hinc).sum_comp + (fun a => (∏ e ∈ a.1.val, v e) * ∏ e ∈ a.2.val, r e) + rw [Fintype.sum_sigma,Fintype.sum_sigma] at h + exact h + +end + +open Finset + +variable {V E : Type*} [Fintype V] [Fintype E] [DecidableEq V] [DecidableEq E] + +variable (inc : E → V → Prop) + +omit [Fintype E] [DecidableEq V] [DecidableEq E] in +@[simp] lemma support_empty : support inc ∅=∅ := by + ext x; simp [support] + +noncomputable def emptyPartial : Partial inc := ⟨∅,by simp [MatchingOn]⟩ + +omit [Fintype E] [DecidableEq V] [DecidableEq E] in +lemma partial_eq_empty_iff (Q : Partial inc) : Q=emptyPartial inc ↔ Q.val=∅ := by + exact Subtype.ext_iff + +omit [Fintype V] [DecidableEq V] [DecidableEq E] in +lemma partitionWeight_nonneg (r : E → ℝ) (hr : ∀ e,0≤r e) (U : Finset V) : + 0≤partitionWeight inc r U := Finset.sum_nonneg (fun _ _ => Finset.prod_nonneg (fun e _ => hr e)) + +omit [Fintype V] [DecidableEq V] [DecidableEq E] in +lemma partitionWeight_mono (r w : E → ℝ) (hr : ∀ e,0≤r e) (hrw : ∀ e,r e≤w e) + (U : Finset V) : partitionWeight inc r U≤partitionWeight inc w U := + Finset.sum_le_sum (fun _ _ => Finset.prod_le_prod₀ (fun e _ => hr e) (fun e _ => hrw e)) + +lemma pow_mul_linear_le_one (x : ℝ) (hx : 0≤x) (m : ℕ) : + (1+x)^m * (1-(m:ℝ)*x) ≤ 1 := by + induction m with + | zero => simp + | succ m ih => + rw [pow_succ,Nat.cast_succ] + have hp : 0≤(1+x)^m := pow_nonneg (by linarith) _ + have h : (1+x) * (1-((m:ℝ)+1)*x) ≤ 1-(m:ℝ)*x := by + have hm : 0≤(m:ℝ) := Nat.cast_nonneg _ + nlinarith [sq_nonneg x,mul_nonneg hm (sq_nonneg x)] + calc + _ = (1+x)^m * ((1+x) * (1-((m:ℝ)+1)*x)) := by ring + _ ≤ (1+x)^m * (1-(m:ℝ)*x) := mul_le_mul_of_nonneg_left h hp + _ ≤ 1 := ih + +lemma pow_small_le (x : ℝ) (hx : 0≤x) (m : ℕ) (hm : (m:ℝ)*x≤1/100) : + (1+x)^m≤100/99 := by + have hp : 0≤(1+x)^m := pow_nonneg (by linarith) _ + have h := pow_mul_linear_le_one x hx m + nlinarith [mul_nonneg hp (show 0≤1/100-(m:ℝ)*x by linarith)] + +lemma all_subsets_pow (x : ℝ) : + (∑ Q : Finset E, x^Q.card)=(1+x)^Fintype.card E := by + classical + have h := Finset.prod_add (fun _ : E => x) (fun _ => (1:ℝ)) univ + simpa [Finset.prod_const,Finset.prod_const_one,add_comm] using h.symm + +omit [DecidableEq V] in +lemma partial_pow_sum_le (x : ℝ) (hx : 0≤x) : + (∑ Q : Partial inc, x^Q.val.card) ≤ (1+x)^Fintype.card E := by + classical + rw [←all_subsets_pow] + calc + _ = ∑ Q ∈ univ.image (Subtype.val : Partial inc → Finset E), x^Q.card := + (Finset.sum_image (fun a _ b _ h => Subtype.ext h)).symm + _ ≤ _ := Finset.sum_le_sum_of_subset_of_nonneg (Finset.subset_univ _) + (fun Q _ _ => pow_nonneg hx _) + +theorem finite_inflation (r v : E → ℝ) (hr : ∀ e,0≤r e) (hv : ∀ e,0≤v e) + (hinc : ∀ e,∃ x,inc e x) (hz : 0 r e+v e) univ / partitionWeight inc r univ ∧ + partitionWeight inc (fun e => r e+v e) univ / partitionWeight inc r univ ≤ 2 := by + classical + constructor + · apply (le_div_iff₀ hz).mpr + simpa using partitionWeight_mono inc r (fun e => r e+v e) hr (fun e => le_add_of_nonneg_right (hv e)) univ + · let mass (Q : Partial inc) := (∏ e ∈ Q.val, v e) * + partitionWeight inc r (univ \ support inc Q.val) / partitionWeight inc r univ + have hmass : ∀ Q : Partial inc, mass Q+(if Q=emptyPartial inc then 1 else 0)≤2*x^Q.val.card := by + intro Q + by_cases he : Q=emptyPartial inc + · subst Q + norm_num [mass,emptyPartial,hz.ne'] + · simpa only [ite_eq_right he,add_zero] using hlocal Q (fun h => he ((partial_eq_empty_iff inc Q).mpr h)) + have hs := Finset.sum_le_sum (s := (univ : Finset (Partial inc))) (fun Q _ => hmass Q) + simp only [Finset.sum_add_distrib,Finset.sum_ite_eq',Finset.mem_univ,ite_true, + ←Finset.mul_sum] at hs + have hsum := partial_pow_sum_le inc x hx + have hpow := pow_small_le x hx (Fintype.card E) hm + rw [partition_add inc r v hinc,Finset.sum_div] + change (∑ Q : Partial inc, mass Q) ≤ 2 + linarith + +end MatchingFPRAS.Transport + +end OAI diff --git a/lean/OAI/Combinatorics/MatchingCount/Graphs/HoleBlocks.lean b/lean/OAI/Combinatorics/MatchingCount/Graphs/HoleBlocks.lean new file mode 100644 index 0000000000000000000000000000000000000000..b82fcb4e46455b71f588913c7ab7c1d9c0d33fd9 --- /dev/null +++ b/lean/OAI/Combinatorics/MatchingCount/Graphs/HoleBlocks.lean @@ -0,0 +1,496 @@ +import Mathlib +import OAI.Combinatorics.MatchingCount.Graphs.Profile + +namespace OAI + +namespace MatchingFPRAS.Subdivision +open Finset + +theorem last_hole_terminal {m : ℕ} (hm : Even m) {U : Finset (Fin m)} + {b : Selection m} (hb : Valid U b) (j : Fin m) (hj : j ∈ U) + (hlast : ∀ i ∈ U, i ≤ j) : + b (Fin.last m) = true ↔ j.val % 2 = 0 := by + have hv := valid_interval hb (j.val+1) (m-(j.val+1)) (by omega) (by + intro i hi hij him + have hh := hlast i him + have : i.val ≤ j.val := hh + omega) + have hz : b j.succ = false := by + have h := hb j + simp only [hj,↓reduceIte] at h + exact h.2 + have he : b (Fin.last m) = alternating false (m-(j.val+1)) := by + have e1 : (⟨j.val+1+(m-(j.val+1)),by omega⟩ : Fin (m+1)) = Fin.last m := by + apply Fin.ext; dsimp; omega + have e2 : (⟨j.val+1,by omega⟩ : Fin (m+1)) = j.succ := rfl + rw [e1,e2,hz] at hv + exact hv + have hme := Nat.even_iff.mp hm + by_cases h : j.val%2=0 + · have hk : (m-(j.val+1))%2=1 := by omega + simp [he,alternating,h,hk] + · have hk : (m-(j.val+1))%2=0 := by omega + simp [he,alternating,h,hk] + +theorem successive_holes_parity {m : ℕ} {U : Finset (Fin m)} {b : Selection m} + (hb : Valid U b) (i j : Fin m) (hi : i ∈ U) (hj : j ∈ U) (hij : i < j) + (hbetween : ∀ k ∈ U, ¬ (i < k ∧ k < j)) : + i.val % 2 ≠ j.val % 2 := by + have hv := valid_interval hb (i.val+1) (j.val-(i.val+1)) (by omega) (by + intro k hk hkj hku + apply hbetween k hku + constructor <;> omega) + have hi0 : b i.succ = false := by + have h := hb i + simp only [hi,↓reduceIte] at h + exact h.2 + have hj0 : b j.castSucc = false := by + have h := hb j + simp only [hj,↓reduceIte] at h + exact h.1 + have he : false = alternating false (j.val-(i.val+1)) := by + convert hv using 1 + · rw [show (⟨i.val+1+(j.val-(i.val+1)),by omega⟩ : Fin (m+1)) = j.castSucc + by apply Fin.ext; dsimp; omega,hj0] + · rw [show (⟨i.val+1,by omega⟩ : Fin (m+1)) = i.succ by rfl,hi0] + have heven : (j.val-(i.val+1))%2=0 := by + by_contra h + simp [alternating,h] at he + omega + +theorem sorted_holes_alternate {m : ℕ} {U : Finset (Fin m)} {b : Selection m} + (hb : Valid U b) : + (U.sort (· ≤ ·)).IsChain (fun i j => i.val%2 ≠ j.val%2) := by + let xs := U.sort (· ≤ ·) + have hsort : xs.Pairwise (· < ·) := (Finset.sortedLT_sort U).pairwise + rw [List.isChain_iff_getElem] + intro r hr + have hri : r < xs.length := by exact Nat.lt_trans (Nat.lt_succ_self r) hr + have him : xs[r] ∈ U := (Finset.mem_sort _).mp (List.getElem_mem hri) + have hjm : xs[r+1] ∈ U := (Finset.mem_sort _).mp (List.getElem_mem hr) + have hij : xs[r] < xs[r+1] := + (List.pairwise_iff_getElem.mp hsort) r (r+1) hri hr (by omega) + apply successive_holes_parity hb (xs[r]) (xs[r+1]) him hjm hij + intro k hk hbet + have hkm : k ∈ xs := (Finset.mem_sort _).mpr hk + obtain ⟨s,hs,hks⟩ := List.mem_iff_getElem.mp hkm + by_cases hsr : s ≤ r + · by_cases heq : s=r + · subst s; rw [hks] at hbet; exact lt_irrefl _ hbet.1 + · have hlt := (List.pairwise_iff_getElem.mp hsort) s r hs hri (by omega) + rw [hks] at hlt + exact (not_lt_of_ge hlt.le) hbet.1 + · by_cases heq : s=r+1 + · subst s; rw [hks] at hbet; exact lt_irrefl _ hbet.2 + · have hlt := (List.pairwise_iff_getElem.mp hsort) (r+1) s hr hs (by omega) + rw [hks] at hlt + exact (not_lt_of_ge hlt.le) hbet.2 + +theorem neutral_blocks {m : ℕ} (xs : List (Fin m)) + (ha : xs.IsChain (fun i j => i.val%2 ≠ j.val%2)) + (hh : ∀ i ∈ xs.head?, i.val%2=0) : + ∃ (pairs : List (Fin m × Fin m)) (right : Option (Fin m)), + xs = pairs.flatMap (fun q => [q.1,q.2]) ++ right.toList ∧ + (∀ q ∈ pairs, q.1.val%2=0 ∧ q.2.val%2=1) ∧ + (∀ j ∈ right, j.val%2=0) := by + induction xs using List.twoStepInduction with + | nil => exact ⟨[],none,by simp⟩ + | singleton j => exact ⟨[],some j,by simpa using hh⟩ + | cons_cons j k xs ih ih' => + have hj : j.val%2=0 := hh j (by simp) + have hne := (List.isChain_cons_cons.mp ha).1 + have hk : k.val%2=1 := by omega + have htail := (List.isChain_cons_cons.mp ha).2 + have hh' : ∀ i ∈ xs.head?, i.val%2=0 := by + intro i hi + have hki : k.val%2 ≠ i.val%2 := (List.isChain_cons.mp htail).1 i hi + omega + obtain ⟨pairs,right,he,hp,hr⟩ := ih htail.tail hh' + refine ⟨(j,k)::pairs,right,?_,?_,hr⟩ + · simp [he] + · intro q hq + rcases List.mem_cons.mp hq with rfl | hq + · exact ⟨hj,hk⟩ + · exact hp q hq + +structure HoleBlocks (m : ℕ) where + left : Option (Fin m) + neutral : List (Fin m × Fin m) + right : Option (Fin m) + +def HoleBlocks.flatten {m : ℕ} (d : HoleBlocks m) : List (Fin m) := + d.left.toList ++ d.neutral.flatMap (fun q => [q.1,q.2]) ++ d.right.toList + +def HoleBlocks.Parity {m : ℕ} (d : HoleBlocks m) : Prop := + (∀ j ∈ d.left, j.val%2=1) ∧ + (∀ q ∈ d.neutral, q.1.val%2=0 ∧ q.2.val%2=1) ∧ + (∀ j ∈ d.right, j.val%2=0) + +theorem hole_blocks_exist {m : ℕ} {U : Finset (Fin m)} {b : Selection m} + (hb : Valid U b) : + ∃ d : HoleBlocks m, d.flatten = U.sort (· ≤ ·) ∧ d.Parity := by + have ha := sorted_holes_alternate hb + generalize he : U.sort (· ≤ ·)=xs at ha ⊢ + cases xs with + | nil => exact ⟨⟨none,[],none⟩,rfl,by simp [HoleBlocks.Parity]⟩ + | cons j xs => + by_cases hj : j.val%2=0 + · obtain ⟨pairs,right,heq,hp,hr⟩ := neutral_blocks (j::xs) ha (by simpa using hj) + exact ⟨⟨none,pairs,right⟩,by simpa [HoleBlocks.flatten] using heq.symm, + by simpa [HoleBlocks.Parity] using And.intro hp hr⟩ + · have hj1 : j.val%2=1 := by omega + have hh : ∀ i ∈ xs.head?, i.val%2=0 := by + intro i hi + have hji := (List.isChain_cons.mp ha).1 i hi + omega + obtain ⟨pairs,right,heq,hp,hr⟩ := neutral_blocks xs ha.tail hh + refine ⟨⟨some j,pairs,right⟩,?_,?_⟩ + · simp [HoleBlocks.flatten,heq] + · simpa [HoleBlocks.Parity] using And.intro hj1 (And.intro hp hr) + +theorem selectedWeight_hole_product {m : ℕ} (hm : Even m) + (U : Finset (Fin m)) (b : Selection m) (hb : Valid U b) (z : Fin (m+2) → ℝ) : + selectedWeight (fun i => z i.castSucc * z i.succ) b * + (∏ j ∈ U, z j.succ.castSucc) = + selectedWeight (fun i => z i.castSucc * z i.succ) + (fun i => alternating false i.val) * + (if b 0 then z 0 else 1) * (if b (Fin.last m) then z (Fin.last (m+1)) else 1) := by + classical + rw [selectedWeight_vertex_factor U b hb z, + selectedWeight_vertex_factor ∅ _ (alternating_valid m false) z] + have hbool : alternating false (Fin.last m).val = false := by + simp [alternating,Nat.even_iff.mp hm] + simp only [Fin.val_zero,alternating_zero,Bool.false_eq_true,↓reduceIte, + hbool,Finset.notMem_empty,one_mul] + have hp : (∏ i : Fin m, if i ∈ U then 1 else z i.succ.castSucc) * + (∏ j ∈ U, z j.succ.castSucc) = ∏ i : Fin m, z i.succ.castSucc := by + have hU : (∏ j ∈ U, z j.succ.castSucc) = + ∏ i : Fin m, if i ∈ U then z i.succ.castSucc else 1 := by + rw [← Finset.prod_filter] + simp + rw [hU,← Finset.prod_mul_distrib] + apply Finset.prod_congr rfl + intro i hi + by_cases him : i ∈ U <;> simp [him] + calc + _ = (if b 0 then z 0 else 1) * (if b (Fin.last m) then z (Fin.last (m+1)) else 1) * + ((∏ i : Fin m, if i ∈ U then 1 else z i.succ.castSucc) * + (∏ j ∈ U, z j.succ.castSucc)) := by ring + _ = _ := by rw [hp]; ring + +def adjacentProducts : List ℝ → List ℝ + | a::b::xs => a*b :: adjacentProducts (b::xs) + | _ => [] + +@[simp] lemma adjacentProducts_length (xs : List ℝ) : + (adjacentProducts xs).length = xs.length-1 := by + induction xs using List.twoStepInduction with + | nil => rfl + | singleton => rfl + | cons_cons a b xs ih ih' => simp [adjacentProducts,ih'] + +lemma adjacentProducts_zip (xs : List ℝ) : + adjacentProducts xs = List.zipWith (· * ·) xs xs.tail := by + induction xs using List.twoStepInduction with + | nil => rfl + | singleton => rfl + | cons_cons a b xs ih ih' => simpa [adjacentProducts] using congrArg (a*b :: ·) (ih' b) + +noncomputable def armPotentials (c : ℝ) (xs : List ℝ) : List ℝ := + xs.flatMap (fun x => [x/c,c]) + +@[simp] lemma armPotentials_length (c : ℝ) (xs : List ℝ) : + (armPotentials c xs).length = 2*xs.length := by + induction xs with + | nil => simp [armPotentials] + | cons x xs ih => simp [armPotentials] at ih ⊢; omega + +lemma adjacentProducts_arm (c : ℝ) (hc : c ≠ 0) (xs ys : List ℝ) : + adjacentProducts (c :: (armPotentials c xs ++ ys)) = + duplicate xs ++ adjacentProducts (c::ys) := by + induction xs with + | nil => simp [armPotentials] + | cons x xs ih => + have hmul : c*(x/c)=x := by field_simp + have hmul' : (x/c)*c=x := by field_simp + simpa [armPotentials,adjacentProducts,hmul,hmul',duplicate] using + congrArg (x::x::·) ih + +noncomputable def pairedPotentials (left right : List ℝ) (lam : ℝ) : List ℝ := + 1 :: (armPotentials 1 left ++ lam :: armPotentials lam right) + +@[simp] lemma pairedPotentials_length (left right : List ℝ) (lam : ℝ) : + (pairedPotentials left right lam).length = 2*left.length+2*right.length+2 := by + simp [pairedPotentials]; omega + +theorem pairedPotentials_activities (left right : List ℝ) (lam : ℝ) (hlam : lam ≠ 0) : + adjacentProducts (pairedPotentials left right lam) = + duplicate left ++ [lam] ++ duplicate right := by + unfold pairedPotentials + rw [adjacentProducts_arm 1 one_ne_zero] + simp only [adjacentProducts,one_mul] + have hr := adjacentProducts_arm lam hlam right [] + simp only [List.append_nil,adjacentProducts,List.append_nil] at hr + rw [hr] + simp + +noncomputable def profilePotentials (p : ℕ) (B Hu Hv lam : ℝ) : List ℝ := + pairedPotentials (List.ofFn fun r : Fin p => max B (Hu/2^r.val)) + ((List.ofFn fun r : Fin p => max B (Hv/2^r.val)).reverse) lam + +@[simp] lemma profilePotentials_length (p : ℕ) (B Hu Hv lam : ℝ) : + (profilePotentials p B Hu Hv lam).length = 4*p+2 := by + simp [profilePotentials]; omega + +noncomputable def profilePotential (p : ℕ) (B Hu Hv lam : ℝ) (i : Fin (4*p+2)) : ℝ := + (profilePotentials p B Hu Hv lam).get + (i.cast (profilePotentials_length p B Hu Hv lam).symm) + +theorem profileActivity_vertex_factor (p : ℕ) (B Hu Hv lam : ℝ) (hlam : lam ≠ 0) + (i : Fin (4*p+1)) : + profileActivity p B Hu Hv lam i = + profilePotential p B Hu Hv lam i.castSucc * profilePotential p B Hu Hv lam i.succ := by + have he : adjacentProducts (profilePotentials p B Hu Hv lam) = profile p B Hu Hv lam := + pairedPotentials_activities _ _ _ hlam + have hi : i.val < (adjacentProducts (profilePotentials p B Hu Hv lam)).length := by + simp only [adjacentProducts_length,profilePotentials_length] + omega + have hget := congrArg (fun xs : List ℝ => xs[i.val]?) he + have hi' : i.val < (profile p B Hu Hv lam).length := by simp; omega + rw [List.getElem?_eq_getElem hi,List.getElem?_eq_getElem hi',Option.some.injEq] at hget + simp only [adjacentProducts_zip,List.getElem_zipWith] at hget + simpa only [profileActivity,profilePotential,List.get_eq_getElem,Fin.val_cast, + Fin.val_castSucc,Fin.val_succ,List.getElem_tail] using hget.symm + +lemma duplicate_getElem (xs : List ℝ) (i : ℕ) (hi : i < (duplicate xs).length) : + (duplicate xs)[i] = xs[i/2]'(by simp only [duplicate_length] at hi; omega) := by + induction xs generalizing i with + | nil => simp [duplicate] at hi + | cons x xs ih => + cases i with + | zero => simp [duplicate] + | succ i => + cases i with + | zero => simp [duplicate] + | succ i => + have hi' : i < (duplicate xs).length := by simp only [duplicate_cons,List.length_cons] at hi; omega + have hh := ih i hi' + simpa only [duplicate_cons,List.getElem_cons_succ,Nat.succ_eq_add_one, + show (i+1+1)/2=i/2+1 by omega] using hh + +lemma profile_left (p : ℕ) (B Hu Hv lam : ℝ) (i : Fin (4*p+1)) + (hi : i.val < 2*p) : + profileActivity p B Hu Hv lam i = max B (Hu/2^(i.val/2)) := by + unfold profileActivity profile + simp only [List.get_eq_getElem,Fin.cast] + have hl : i.val < (duplicate (List.ofFn fun r : Fin p => max B (Hu/2^r.val))).length := by + simpa using hi + rw [List.getElem_append_left (by simpa only [List.length_append,List.length_singleton] using + (show i.val < (duplicate (List.ofFn fun r : Fin p => max B (Hu/2^r.val))).length+1 by omega))] + rw [List.getElem_append_left hl,duplicate_getElem] + simp + +@[simp] lemma profile_center (p : ℕ) (B Hu Hv lam : ℝ) : + profileActivity p B Hu Hv lam ⟨2*p,by omega⟩ = lam := by + unfold profileActivity profile + simp only [List.get_eq_getElem,Fin.cast] + rw [List.getElem_append_left (by simp)] + rw [List.getElem_append_right (by simp)] + simp + +lemma profile_right (p : ℕ) (B Hu Hv lam : ℝ) (i : Fin (4*p+1)) + (hi : 2*p < i.val) : + profileActivity p B Hu Hv lam i = max B (Hv/2^((4*p-i.val)/2)) := by + unfold profileActivity profile + simp only [List.get_eq_getElem,Fin.cast] + rw [List.getElem_append_right (by simp; omega),duplicate_getElem] + simp only [duplicate_length,List.length_ofFn,List.length_append,List.length_singleton, + List.getElem_reverse,List.getElem_ofFn] + congr 3 + omega + +theorem profile_lower (p : ℕ) (B Hu Hv lam : ℝ) (hlam : lam ≤ B) + (i : Fin (4*p+1)) : lam ≤ profileActivity p B Hu Hv lam i := by + rcases lt_trichotomy i.val (2*p) with hi | hi | hi + · rw [profile_left _ _ _ _ _ _ hi]; exact hlam.trans (le_max_left _ _) + · have he : i=⟨2*p,by omega⟩ := Fin.ext hi + rw [he]; simp + · rw [profile_right _ _ _ _ _ _ hi]; exact hlam.trans (le_max_left _ _) + +lemma profile_noncentral_lower (p : ℕ) (B Hu Hv lam : ℝ) + (i : Fin (4*p+1)) (hi : i.val ≠ 2*p) : B ≤ profileActivity p B Hu Hv lam i := by + rcases lt_or_gt_of_ne hi with hi | hi + · rw [profile_left _ _ _ _ _ _ hi]; exact le_max_left _ _ + · rw [profile_right _ _ _ _ _ _ hi]; exact le_max_left _ _ + +lemma legValue_antitone (B H : ℝ) (hH : 0 ≤ H) : + Antitone (fun r : ℕ => max B (H/(2:ℝ)^r)) := by + intro i j hij + apply max_le_max_left + exact div_le_div_of_nonneg_left hH (by positivity) + (pow_le_pow_right₀ (by norm_num : (1:ℝ) ≤ 2) hij) + +lemma legValue_step (B H : ℝ) (hB : 0 ≤ B) (r : ℕ) : + max B (H/(2:ℝ)^r) ≤ 2*max B (H/(2:ℝ)^(r+1)) := by + apply max_le + · exact (le_max_left B (H/2^(r+1))).trans + (by have hh := (le_max_left B (H/2^(r+1))); nlinarith) + · have he : H/(2:ℝ)^r = 2*(H/(2:ℝ)^(r+1)) := by rw [pow_succ]; field_simp + rw [he] + exact mul_le_mul_of_nonneg_left (le_max_right _ _) (by norm_num) + +lemma profile_innermost (K : ℕ) (B H : ℝ) (hB : 1 ≤ B) (hH : H ≤ 4^K) : + max B (H/(2:ℝ)^(2*K+1)) = B := by + apply max_eq_left + have hp : (2:ℝ)^(2*K+1) = 2*4^K := by + rw [pow_succ,pow_mul]; norm_num; ring + rw [hp] + apply (div_le_iff₀ (by positivity)).mpr + have h4 : (0:ℝ) ≤ 4^K := by positivity + nlinarith + +noncomputable def vertexPotential (p : ℕ) (B Hu Hv lam : ℝ) (k : ℕ) : ℝ := + if k ≤ 2*p then + if Even k then 1 else max B (Hu/2^(k/2)) + else if Even k then max B (Hv/2^((4*p+1-k)/2))/lam else lam + +@[simp] lemma vertexPotential_zero (p : ℕ) (B Hu Hv lam : ℝ) : + vertexPotential p B Hu Hv lam 0 = 1 := by simp [vertexPotential] + +@[simp] lemma vertexPotential_last (p : ℕ) (B Hu Hv lam : ℝ) : + vertexPotential p B Hu Hv lam (4*p+1) = lam := by + have hn : ¬ Even (4*p+1) := by simp [Nat.even_iff]; omega + simp [vertexPotential,show ¬ 4*p+1 ≤ 2*p by omega,hn] + +theorem profile_vertexPotential (p : ℕ) (B Hu Hv lam : ℝ) (hlam : lam ≠ 0) + (i : Fin (4*p+1)) : profileActivity p B Hu Hv lam i = + vertexPotential p B Hu Hv lam i.val * vertexPotential p B Hu Hv lam (i.val+1) := by + have hi := i.isLt + rcases lt_trichotomy i.val (2*p) with hleft | hcenter | hright + · rw [profile_left _ _ _ _ _ _ hleft] + have hi0 : i.val ≤ 2*p := by omega + have hi1 : i.val+1 ≤ 2*p := by omega + simp only [vertexPotential,ite_eq_left hi0,ite_eq_left hi1] + by_cases he : Even i.val + · have hn : ¬ Even (i.val+1) := by simpa [Nat.even_add_one] using he + have hdiv : (i.val+1)/2=i.val/2 := by have := Nat.even_iff.mp he; omega + simp [he,hn,hdiv] + · have hn : Even (i.val+1) := by simpa [Nat.even_add_one] using he + simp [he,hn] + · have hic : i=⟨2*p,by omega⟩ := Fin.ext hcenter + rw [hic] + simp [vertexPotential,show ¬ 2*p+1 ≤ 2*p by omega] + · rw [profile_right _ _ _ _ _ _ hright] + have hi0 : ¬ i.val ≤ 2*p := by omega + have hi1 : ¬ i.val+1 ≤ 2*p := by omega + simp only [vertexPotential,ite_eq_right hi0,ite_eq_right hi1] + by_cases he : Even i.val + · have hn : ¬ Even (i.val+1) := by simpa [Nat.even_add_one] using he + have hdiv : (4*p+1-i.val)/2=(4*p-i.val)/2 := by have := Nat.even_iff.mp he; omega + simp [he,hn,hdiv,hlam] + · have hn : Even (i.val+1) := by simpa [Nat.even_add_one] using he + have hdiv : 4*p+1-(i.val+1)=4*p-i.val := by omega + simp [he,hn,hdiv,hlam,mul_div_cancel₀] + +noncomputable def internalStrength (p : ℕ) (B Hu Hv : ℝ) (j : Fin (4*p)) : ℝ := + if j.val < 2*p then max B (Hu/2^(j.val/2)) + else max B (Hv/2^((4*p-(j.val+1))/2)) + +lemma le_internalStrength (p : ℕ) (B Hu Hv : ℝ) (j : Fin (4*p)) : + B ≤ internalStrength p B Hu Hv j := by + unfold internalStrength; split_ifs <;> exact le_max_left _ _ + +theorem internalStrength_incident (p : ℕ) (B Hu Hv lam : ℝ) + (hHu : 0 ≤ Hu) (hHv : 0 ≤ Hv) (hlam : lam ≤ B) (j : Fin (4*p)) : + profileActivity p B Hu Hv lam j.castSucc ≤ internalStrength p B Hu Hv j ∧ + profileActivity p B Hu Hv lam j.succ ≤ internalStrength p B Hu Hv j := by + by_cases hj : j.val < 2*p + · have hs : internalStrength p B Hu Hv j=max B (Hu/2^(j.val/2)) := by simp [internalStrength,hj] + rw [hs] + constructor + · rw [profile_left _ _ _ _ _ _ hj] + exact le_rfl + · by_cases hj' : j.val+1 < 2*p + · rw [profile_left _ _ _ _ _ _ hj'] + exact legValue_antitone B Hu hHu (by simp only [Fin.val_succ]; omega) + · have hc : j.succ=⟨2*p,by omega⟩ := Fin.ext (by simp only [Fin.val_succ]; omega) + rw [hc,profile_center] + exact hlam.trans (le_max_left _ _) + · have hs : internalStrength p B Hu Hv j=max B (Hv/2^((4*p-(j.val+1))/2)) := by + simp [internalStrength,hj] + rw [hs] + constructor + · by_cases hj' : 2*p < j.val + · rw [profile_right _ _ _ _ _ _ hj'] + exact legValue_antitone B Hv hHv (by simp only [Fin.val_castSucc]; omega) + · have hc : j.castSucc=⟨2*p,by omega⟩ := Fin.ext (by simp only [Fin.val_castSucc]; omega) + rw [hc,profile_center] + exact hlam.trans (le_max_left _ _) + · rw [profile_right _ _ _ _ _ _ (by simp only [Fin.val_succ]; omega)] + exact le_rfl + +theorem internalStrength_left_leg (p : ℕ) (B Hu Hv lam : ℝ) (hHu : 0 ≤ Hu) + (j : Fin (4*p)) (hj : j.val < 2*p) (i : Fin (4*p+1)) (hi : i.val ≤ j.val) : + internalStrength p B Hu Hv j ≤ profileActivity p B Hu Hv lam i := by + rw [profile_left _ _ _ _ _ _ (by omega)] + simp only [internalStrength,ite_eq_left hj] + exact legValue_antitone B Hu hHu (by omega) + +theorem internalStrength_right_leg (p : ℕ) (B Hu Hv lam : ℝ) (hHv : 0 ≤ Hv) + (j : Fin (4*p)) (hj : ¬ j.val < 2*p) (i : Fin (4*p+1)) (hi : j.val+1 ≤ i.val) : + internalStrength p B Hu Hv j ≤ profileActivity p B Hu Hv lam i := by + rw [profile_right _ _ _ _ _ _ (by omega)] + simp only [internalStrength,ite_eq_right hj] + exact legValue_antitone B Hv hHv (by omega) + +lemma internalStrength_left_antitone (p : ℕ) (B Hu Hv : ℝ) (hHu : 0 ≤ Hu) + (j k : Fin (4*p)) (hjk : j.val ≤ k.val) (hk : k.val < 2*p) : + internalStrength p B Hu Hv k ≤ internalStrength p B Hu Hv j := by + have hj : j.val < 2*p := by omega + simp only [internalStrength,ite_eq_left hj,ite_eq_left hk] + exact legValue_antitone B Hu hHu (by omega) + +lemma internalStrength_right_monotone (p : ℕ) (B Hu Hv : ℝ) (hHv : 0 ≤ Hv) + (j k : Fin (4*p)) (hjk : j.val ≤ k.val) (hj : ¬ j.val < 2*p) : + internalStrength p B Hu Hv j ≤ internalStrength p B Hu Hv k := by + have hk : ¬ k.val < 2*p := by omega + simp only [internalStrength,ite_eq_right hj,ite_eq_right hk] + exact legValue_antitone B Hv hHv (by omega) + +lemma vertexPotential_pos (p : ℕ) (B Hu Hv lam : ℝ) (hB : 0 < B) (hlam : 0 < lam) + (i : ℕ) : 0 < vertexPotential p B Hu Hv lam i := by + unfold vertexPotential + split_ifs + · norm_num + · exact hB.trans_le (le_max_left _ _) + · exact div_pos (hB.trans_le (le_max_left _ _)) hlam + · exact hlam + +lemma consumed_left_potential (p : ℕ) (B Hu Hv lam : ℝ) (j : Fin (4*p)) + (hj : j.val%2=1) : + vertexPotential p B Hu Hv lam (j.val+1) = + if j.val < 2*p then 1 else internalStrength p B Hu Hv j/lam := by + have he : Even (j.val+1) := Nat.even_iff.mpr (by omega) + have hi : j.val+1 ≤ 2*p ↔ j.val < 2*p := by omega + simp only [vertexPotential,he,↓reduceIte,hi] + by_cases hs : j.val < 2*p + · simp [hs] + · have hd : (4*p-j.val)/2=(4*p-(j.val+1))/2 := by + have := j.isLt; omega + simp [hs,internalStrength,hd] + +lemma consumed_right_potential (p : ℕ) (B Hu Hv lam : ℝ) (j : Fin (4*p)) + (hj : j.val%2=0) : + vertexPotential p B Hu Hv lam (j.val+1) = + if j.val < 2*p then internalStrength p B Hu Hv j else lam := by + have he : ¬ Even (j.val+1) := by rw [Nat.even_iff]; omega + have hi : j.val+1 ≤ 2*p ↔ j.val < 2*p := by omega + have hd : (j.val+1)/2=j.val/2 := by omega + simp only [vertexPotential,he,↓reduceIte,hi,hd] + by_cases hs : j.val < 2*p + · simp [hs,internalStrength] + · simp [hs] + +end MatchingFPRAS.Subdivision + +end OAI diff --git a/lean/OAI/Combinatorics/MatchingCount/Graphs/HoleStrength.lean b/lean/OAI/Combinatorics/MatchingCount/Graphs/HoleStrength.lean new file mode 100644 index 0000000000000000000000000000000000000000..8a87fed5112964d77512582c97231ca0b38af717 --- /dev/null +++ b/lean/OAI/Combinatorics/MatchingCount/Graphs/HoleStrength.lean @@ -0,0 +1,414 @@ +import Mathlib +import OAI.Combinatorics.MatchingCount.Graphs.PathActivity + +namespace OAI + +namespace MatchingFPRAS.Enlargement + +open MatchingFPRAS.Switching MatchingFPRAS.Subdivision MatchingFPRAS.RealGeometry +open Finset + +variable {V E : Type*} [Fintype V] [LinearOrder V] [Fintype E] [LinearOrder E] + +lemma consumed_destination_injective {m : ℕ} (hm : Even m) (u v : E → V) + (huv : ∀ e, u e ≠ v e) (R₀ : Finset V) (U : E → Finset (Fin m)) + (b : E → Selection m) (hb : FamilyHoles u v m R₀ U b) + (d : E → HoleBlocks m) (he : ∀ e, (d e).flatten=(U e).sort (· ≤ ·)) (hp : ∀ e, (d e).Parity) + (q : Vertex V E m × Vertex V E m) (hq : q ∈ consumedPairs u v m d) + (q' : Vertex V E m × Vertex V E m) (hq' : q' ∈ consumedPairs u v m d) + (hqq : q.2=q'.2) : q=q' := by + obtain ⟨e,j,h | h⟩ := (mem_consumedPairs u v d q).mp hq + · obtain ⟨hj,rfl⟩ := h + obtain ⟨e',j',h' | h'⟩ := (mem_consumedPairs u v d q').mp hq' + · obtain ⟨hj',rfl⟩ := h' + have hx : u e=u e' := Sum.inl_injective hqq + have hee := uses_unique hb (left_consumes hb d he hp e hj) + (hx.symm ▸ left_consumes hb d he hp e' hj') + subst e' + have hjj := Option.mem_unique hj hj' + subst j' + rfl + · obtain ⟨hj',rfl⟩ := h' + have hx : u e=v e' := Sum.inl_injective hqq + have hee := uses_unique hb (left_consumes hb d he hp e hj) + (hx.symm ▸ right_consumes hm hb d he hp e' hj') + subst e' + exact (huv e hx).elim + · obtain ⟨hj,rfl⟩ := h + obtain ⟨e',j',h' | h'⟩ := (mem_consumedPairs u v d q').mp hq' + · obtain ⟨hj',rfl⟩ := h' + have hx : v e=u e' := Sum.inl_injective hqq + have hee := uses_unique hb (right_consumes hm hb d he hp e hj) + (hx.symm ▸ left_consumes hb d he hp e' hj') + subst e' + exact (huv e hx.symm).elim + · obtain ⟨hj',rfl⟩ := h' + have hx : v e=v e' := Sum.inl_injective hqq + have hee := uses_unique hb (right_consumes hm hb d he hp e hj) + (hx.symm ▸ right_consumes hm hb d he hp e' hj') + subst e' + have hjj := Option.mem_unique hj hj' + subst j' + rfl + +lemma destination_nodup {m : ℕ} (hm : Even m) (u v : E → V) + (huv : ∀ e, u e ≠ v e) (R₀ : Finset V) (U : E → Finset (Fin m)) + (b : E → Selection m) (hb : FamilyHoles u v m R₀ U b) + (d : E → HoleBlocks m) (he : ∀ e, (d e).flatten=(U e).sort (· ≤ ·)) (hp : ∀ e, (d e).Parity) : + ((consumedPairs u v m d).map Prod.snd).Nodup := by + have hn := (List.nodup_append.mp (source_lists_nodup u v U d he)).2.1 + have hnd : (consumedPairs u v m d).Nodup := List.Nodup.of_map Prod.fst hn + exact List.Nodup.map_on (consumed_destination_injective hm u v huv R₀ U b hb d he hp) hnd + +lemma consumed_fresh {m : ℕ} (hm : Even m) (u v : E → V) + (R₀ : Finset V) (U : E → Finset (Fin m)) (b : E → Selection m) + (hb : FamilyHoles u v m R₀ U b) (d : E → HoleBlocks m) + (he : ∀ e, (d e).flatten=(U e).sort (· ≤ ·)) (hp : ∀ e, (d e).Parity) + (q : Vertex V E m × Vertex V E m) (hq : q ∈ consumedPairs u v m d) : + q.2 ∉ enlargedHoles m R₀ U := by + obtain ⟨e,j,h | h⟩ := (mem_consumedPairs u v d q).mp hq + · obtain ⟨hj,rfl⟩ := h + simpa using uses_not_hole hb (left_consumes hb d he hp e hj) + · obtain ⟨hj,rfl⟩ := h + simpa using uses_not_hole hb (right_consumes hm hb d he hp e hj) + +@[simp] lemma mem_neutral_vertex_left (m : ℕ) (d : E → HoleBlocks m) (x : V) : + Sum.inl x ∉ pairVertices (neutralPairs m d) := by + rw [pairVertices_neutral] + simp + +@[simp] lemma mem_neutral_vertex_right (m : ℕ) (d : E → HoleBlocks m) (e : E) (j : Fin m) : + Sum.inr (e,j) ∈ pairVertices (neutralPairs (V := V) m d) ↔ + j ∈ (d e).neutral.flatMap (fun q => [q.1,q.2]) := by + rw [pairVertices_neutral] + simp only [List.mem_flatMap,Finset.mem_toList,Finset.mem_univ,true_and,List.mem_map, + Sum.inr.injEq,Prod.mk.injEq] + constructor + · rintro ⟨e',j',hj,hee,hjj⟩ + subst e'; subst j'; exact hj + · intro hj; exact ⟨e,j,hj,rfl,rfl⟩ + +@[simp] lemma mem_consumed_source_left (u v : E → V) (m : ℕ) (d : E → HoleBlocks m) (x : V) : + Sum.inl x ∉ (consumedPairs u v m d).map Prod.fst := by + rw [consumed_sources] + simp + +@[simp] lemma mem_consumed_source_right (u v : E → V) (m : ℕ) (d : E → HoleBlocks m) + (e : E) (j : Fin m) : Sum.inr (e,j) ∈ (consumedPairs u v m d).map Prod.fst ↔ + j ∈ (d e).left ∨ j ∈ (d e).right := by + rw [consumed_sources] + simp only [List.mem_flatMap,Finset.mem_toList,Finset.mem_univ,true_and,List.mem_map, + Sum.inr.injEq,Prod.mk.injEq,List.mem_append,Option.mem_toList] + constructor + · rintro ⟨e',j',hj,hee,hjj⟩ + subst e'; subst j'; exact hj + · intro hj; exact ⟨e,j,hj,rfl,rfl⟩ + +omit [Fintype V] [LinearOrder V] [LinearOrder E] in +@[simp] lemma mem_consumed_destination_right [Fintype V] [LinearOrder V] [LinearOrder E] + (u v : E → V) (m : ℕ) (d : E → HoleBlocks m) + (e : E) (j : Fin m) : Sum.inr (e,j) ∉ (consumedPairs u v m d).map Prod.snd := by + simp [consumedPairs,List.map_flatMap,List.map_append,List.map_map,Function.comp_def] + + + + +lemma mem_consumed_destination_left {m : ℕ} (hm : Even m) (u v : E → V) + (R₀ : Finset V) (U : E → Finset (Fin m)) (b : E → Selection m) + (hb : FamilyHoles u v m R₀ U b) (d : E → HoleBlocks m) + (he : ∀ e, (d e).flatten=(U e).sort (· ≤ ·)) (hp : ∀ e, (d e).Parity) (x : V) : + Sum.inl x ∈ (consumedPairs u v m d).map Prod.snd ↔ + ∃ e ∈ broken U, Uses u v b e x := by + constructor + · rintro h + obtain ⟨q,hq,hqx⟩ := List.mem_map.mp h + obtain ⟨e,j,h | h⟩ := (mem_consumedPairs u v d q).mp hq + · obtain ⟨hj,rfl⟩ := h + have hx : u e=x := Sum.inl_injective hqx + refine ⟨e,(mem_broken U e).mpr ⟨j,(d e).left_mem (he e) hj⟩,?_⟩ + exact hx ▸ left_consumes hb d he hp e hj + · obtain ⟨hj,rfl⟩ := h + have hx : v e=x := Sum.inl_injective hqx + refine ⟨e,(mem_broken U e).mpr ⟨j,(d e).right_mem (he e) hj⟩,?_⟩ + exact hx ▸ right_consumes hm hb d he hp e hj + · rintro ⟨e,hbr,hus⟩ + have hU : (U e).Nonempty := (mem_broken U e).mp hbr + rcases hus with ⟨hleft,hx⟩ | ⟨hright,hx⟩ + · have hsome := ((d e).left_uses (hb.1 e) hU (he e) (hp e)).mp hleft + obtain ⟨j,hj⟩ := Option.isSome_iff_exists.mp hsome + apply List.mem_map.mpr + refine ⟨(Sum.inr (e,j),Sum.inl (u e)),?_,by simp only [hx]⟩ + apply (mem_consumedPairs u v d _).mpr + exact ⟨e,j,Or.inl ⟨hj,rfl⟩⟩ + · have hsome := ((d e).right_uses hm (hb.1 e) hU (he e) (hp e)).mp hright + obtain ⟨j,hj⟩ := Option.isSome_iff_exists.mp hsome + apply List.mem_map.mpr + refine ⟨(Sum.inr (e,j),Sum.inl (v e)),?_,by simp only [hx]⟩ + apply (mem_consumedPairs u v d _).mpr + exact ⟨e,j,Or.inr ⟨hj,rfl⟩⟩ + +lemma internal_covered {m : ℕ} (u v : E → V) (U : E → Finset (Fin m)) + (d : E → HoleBlocks m) (he : ∀ e, (d e).flatten=(U e).sort (· ≤ ·)) (e : E) (j : Fin m) : + j ∈ U e ↔ Sum.inr (e,j) ∈ pairVertices (neutralPairs (V := V) m d) ∨ + Sum.inr (e,j) ∈ (consumedPairs u v m d).map Prod.fst := by + rw [mem_neutral_vertex_right,mem_consumed_source_right,← Finset.mem_sort (· ≤ ·),← he e] + simp only [HoleBlocks.flatten,List.mem_append,Option.mem_toList] + tauto + +theorem charged_set_eq {m : ℕ} (hm : Even m) (u v : E → V) + (R₀ : Finset V) (U : E → Finset (Fin m)) (b : E → Selection m) + (hb : FamilyHoles u v m R₀ U b) (d : E → HoleBlocks m) + (he : ∀ e, (d e).flatten=(U e).sort (· ≤ ·)) (hp : ∀ e, (d e).Parity) : + ((enlargedHoles m R₀ U \ (pairVertices (neutralPairs m d)).toFinset) \ + ((consumedPairs u v m d).map Prod.fst).toFinset) ∪ + ((consumedPairs u v m d).map Prod.snd).toFinset = + (residualHoles u v R₀ U b).map ⟨Sum.inl,Sum.inl_injective⟩ := by + classical + ext a + cases a with + | inl x => + simp only [Finset.mem_union,Finset.mem_sdiff,List.mem_toFinset,mem_enlargedHoles_left, + mem_neutral_vertex_left,mem_consumed_source_left,not_false_eq_true,and_true, + Finset.mem_map,Function.Embedding.coeFn_mk,Sum.inl.injEq,exists_eq_right, + mem_residualHoles,mem_consumed_destination_left hm u v R₀ U b hb d he hp] + | inr a => + obtain ⟨e,j⟩ := a + simp only [Finset.mem_union,Finset.mem_sdiff,List.mem_toFinset,mem_enlargedHoles_right, + mem_consumed_destination_right,or_false,Finset.mem_map,Function.Embedding.coeFn_mk, + Sum.inl_ne_inr,and_false,exists_false] + have hc := (internal_covered u v U d he e j).mp + tauto + +noncomputable def holeStrength (p : ℕ) (B Hu Hv : E → ℝ) : Vertex V E (4*p) → ℝ + | Sum.inl _ => 1 + | Sum.inr (e,j) => internalStrength p (B e) (Hu e) (Hv e) j + +noncomputable def neutralCharge (p : ℕ) (B Hu Hv lam : E → ℝ) : + Vertex V E (4*p) × Vertex V E (4*p) → ℝ + | (Sum.inr (e,j),Sum.inr (_,k)) => neutralFactor p (B e) (Hu e) (Hv e) (lam e) j k + | _ => 0 + +noncomputable def consumedCharge (u : E → V) (p : ℕ) (B Hu Hv lam : E → ℝ) : + Vertex V E (4*p) × Vertex V E (4*p) → ℝ + | (Sum.inr (e,j),Sum.inl x) => if x=u e then leftFactor p (B e) (Hu e) (Hv e) (lam e) j + else rightFactor p (B e) (Hu e) (Hv e) (lam e) j + | _ => 0 + +noncomputable def totalDeletionCharge (u v : E → V) (p : ℕ) (B Hu Hv lam : E → ℝ) + (d : E → HoleBlocks (4*p)) : ℝ := + ((neutralPairs (V := V) (4*p) d).map (neutralCharge p B Hu Hv lam)).prod * + ((consumedPairs u v (4*p) d).map (consumedCharge u p B Hu Hv lam)).prod + +theorem deletion_charge_trace (u v : E → V) (huv : ∀ e, u e ≠ v e) + (p : ℕ) (hp : 1 ≤ p) (B Hu Hv lam : E → ℝ) (hB : ∀ e, 1 ≤ B e) + (hHu : ∀ e, 0 ≤ Hu e) (hHv : ∀ e, 0 ≤ Hv e) (hlam0 : ∀ e, 0 ≤ lam e) + (hlam : ∀ e, lam e ≤ B e) (R₀ : Finset V) (U : E → Finset (Fin (4*p))) + (b : E → Selection (4*p)) (hb : FamilyHoles u v (4*p) R₀ U b) + (d : E → HoleBlocks (4*p)) (he : ∀ e, (d e).flatten=(U e).sort (· ≤ ·)) + (hpar : ∀ e, (d e).Parity) : + ChargeTrace (realBottleneck u v p B Hu Hv lam) (enlargedHoles (4*p) R₀ U) + ((residualHoles u v R₀ U b).map ⟨Sum.inl,Sum.inl_injective⟩) + (totalDeletionCharge u v p B Hu Hv lam d) := by + classical + have hm : Even (4*p) := ⟨2*p,by omega⟩ + have hB0 : ∀ e, 0 < B e := fun e => lt_of_lt_of_le zero_lt_one (hB e) + have hs := source_lists_nodup u v U d he + let N := neutralPairs (V := V) (4*p) d + let C := consumedPairs u v (4*p) d + let H := enlargedHoles (4*p) R₀ U + let BB := realBottleneck u v p B Hu Hv lam + let T := holeStrength (V := V) p B Hu Hv + let fN := neutralCharge (V := V) p B Hu Hv lam + let fC := consumedCharge u p B Hu Hv lam + have hsubN : ∀ a ∈ pairVertices N, a ∈ H := by + intro a ha + cases a with + | inl x => exact (mem_neutral_vertex_left (4*p) d x ha).elim + | inr a => + obtain ⟨e,j⟩ := a + exact (mem_enlargedHoles_right (4*p) R₀ U e j).mpr + ((internal_covered u v U d he e j).mpr (Or.inl ha)) + have hlocalN : ∀ q ∈ N, 0 < T q.1 ∧ 0 < T q.2 ∧ 0 ≤ fN q ∧ + (∀ a, a ≠ q.1 → BB q.1 a ≤ T q.1) ∧ + (∀ a, a ≠ q.2 → BB q.2 a ≤ T q.2) ∧ fN q*T q.1*T q.2 ≤ BB q.1 q.2 := by + intro q hq + obtain ⟨e,r,hr,rfl⟩ := (mem_neutralPairs d q).mp hq + refine ⟨(hB0 e).trans_le (le_internalStrength _ _ _ _ _), + (hB0 e).trans_le (le_internalStrength _ _ _ _ _), + neutralFactor_nonneg p _ _ _ _ (hB0 e) (hlam0 e) _ _,?_,?_,?_⟩ + · intro a _; exact realBottleneck_internal_cap u v p hp B Hu Hv lam hB hHu hHv hlam e r.1 a + · intro a _; exact realBottleneck_internal_cap u v p hp B Hu Hv lam hB hHu hHv hlam e r.2 a + · exact neutral_local_charge u v huv p hp B Hu Hv lam hB0 hHu hHv hlam e r.1 r.2 + ((d e).neutral_lt (he e) r hr) + have hsubC : ∀ q ∈ C, q.1 ∈ H \ (pairVertices N).toFinset := by + intro q hq + have hq' : q.1 ∈ C.map Prod.fst := List.mem_map.mpr ⟨q,hq,rfl⟩ + refine Finset.mem_sdiff.mpr ⟨?_,?_⟩ + · cases hqa : q.1 with + | inl x => exact (mem_consumed_source_left u v (4*p) d x (hqa ▸ hq')).elim + | inr a => + obtain ⟨e,j⟩ := a + rw [mem_enlargedHoles_right] + exact (internal_covered u v U d he e j).mpr (Or.inr (hqa ▸ hq')) + · intro hn + exact (List.nodup_append.mp hs).2.2 q.1 (List.mem_toFinset.mp hn) q.1 hq' rfl + have hfresh : ∀ q ∈ C, q.2 ∉ H \ (pairVertices N).toFinset := by + intro q hq hmem + exact consumed_fresh hm u v R₀ U b hb d he hpar q hq (Finset.mem_sdiff.mp hmem).1 + have hlocalC : ∀ q ∈ C, 0 < T q.1 ∧ 0 ≤ fC q ∧ + (∀ a, a ≠ q.1 → BB q.1 a ≤ T q.1) ∧ fC q*T q.1 ≤ BB q.1 q.2 := by + intro q hq + obtain ⟨e,j,h | h⟩ := (mem_consumedPairs u v d q).mp hq + · obtain ⟨hj,rfl⟩ := h + have hc : fC (Sum.inr (e,j),Sum.inl (u e))=leftFactor p (B e) (Hu e) (Hv e) (lam e) j := by + simp [fC,consumedCharge] + rw [hc] + refine ⟨(hB0 e).trans_le (le_internalStrength _ _ _ _ _), + leftFactor_nonneg p _ _ _ _ (hB0 e) (hlam0 e) _,?_,?_⟩ + · intro a _; exact realBottleneck_internal_cap u v p hp B Hu Hv lam hB hHu hHv hlam e j a + · exact left_local_charge u v huv p hp B Hu Hv lam hB0 hHu hlam e j + · obtain ⟨hj,rfl⟩ := h + have hc : fC (Sum.inr (e,j),Sum.inl (v e))=rightFactor p (B e) (Hu e) (Hv e) (lam e) j := by + simp [fC,consumedCharge,(huv e).symm] + rw [hc] + refine ⟨(hB0 e).trans_le (le_internalStrength _ _ _ _ _), + rightFactor_nonneg p _ _ _ _ (hB0 e) (hlam0 e) _,?_,?_⟩ + · intro a _; exact realBottleneck_internal_cap u v p hp B Hu Hv lam hB hHu hHv hlam e j a + · exact right_local_charge u v huv p hp B Hu Hv lam hB0 hHv hlam e j + have htN := charge_remove_list BB T fN N H (List.nodup_append.mp hs).1 hsubN hlocalN + have htC := charge_replace_list BB T fC C (H \ (pairVertices N).toFinset) + (List.nodup_append.mp hs).2.1 (destination_nodup hm u v huv R₀ U b hb d he hpar) hsubC hfresh hlocalC + have hC0 : 0 ≤ (C.map fC).prod := by + apply List.prod_nonneg + intro a ha + obtain ⟨q,hq,rfl⟩ := List.mem_map.mp ha + exact (hlocalC q hq).2.1 + have htrace := htN.trans htC hC0 + change ChargeTrace _ _ _ (totalDeletionCharge u v p B Hu Hv lam d) at htrace + simpa only [N,C,H,charged_set_eq hm u v R₀ U b hb d he hpar] using htrace + +theorem deletion_capacity_bound (w : V → V → ℝ) (hw : ∀ a b, 0 < w a b) + (p : ℕ) (hp : 1 ≤ p) (Hu Hv : LogicalEdge V → ℝ) + (hHu : ∀ e, 0 ≤ Hu e) (hHv : ∀ e, 0 ≤ Hv e) + (R₀ : Finset V) (U : LogicalEdge V → Finset (Fin (4*p))) + (b : LogicalEdge V → Selection (4*p)) (hb : FamilyHoles source target (4*p) R₀ U b) + (d : LogicalEdge V → HoleBlocks (4*p)) (he : ∀ e, (d e).flatten=(U e).sort (· ≤ ·)) + (hpar : ∀ e, (d e).Parity) (hH : Even (enlargedHoles (4*p) R₀ U).card) : + ∃ hR : Even (residualHoles source target R₀ U b).card, + pairingCapacity (realBottleneck source target p + (fun e => bottleneck w (source e) (target e)) Hu Hv (logicalActivity w)) + (enlargedHoles (4*p) R₀ U) hH * + totalDeletionCharge source target p (fun e => bottleneck w (source e) (target e)) + Hu Hv (logicalActivity w) d ≤ + pairingCapacity (bottleneck w) (residualHoles source target R₀ U b) hR := by + classical + have ht := deletion_charge_trace source target source_ne_target p hp + (fun e => bottleneck w (source e) (target e)) Hu Hv (logicalActivity w) + (fun e => one_le_bottleneck w _ _) hHu hHv + (fun e => by unfold logicalActivity edgeActivity; split_ifs <;> exact (hw _ _).le) + (fun e => edgeActivity_le_bottleneck w _ _ (source_ne_target e)) R₀ U b hb d he hpar + obtain ⟨hR,hle⟩ := ChargeTrace.capacity_bound_decidable _ + (fun a b => bottleneck_comm _ a b) + (fun a b => zero_le_one.trans (one_le_bottleneck _ a b)) + (fun a b c hab hac hbc => bottleneck_ultrametric _ a b c hab hac hbc) ht hH + have hR' : Even (residualHoles source target R₀ U b).card := by simpa using hR + refine ⟨hR',?_⟩ + have hx := pairingCapacity_sum_inl (terminal_lt_iff (4*p)) (bottleneck w) _ + (terminal_bottleneck w p hp Hu Hv) _ hR' hR + apply hle.trans_eq + convert hx using 1 + rfl + +noncomputable def blockCharge (p : ℕ) (B Hu Hv lam : ℝ) (d : HoleBlocks (4*p)) : ℝ := + (d.left.toList.map (leftFactor p B Hu Hv lam)).prod * + (d.neutral.map (fun q => neutralFactor p B Hu Hv lam q.1 q.2)).prod * + (d.right.toList.map (rightFactor p B Hu Hv lam)).prod + +lemma blockCharge_potential (p : ℕ) (B Hu Hv lam : ℝ) (hlam : lam ≠ 0) + (U : Finset (Fin (4*p))) (d : HoleBlocks (4*p)) + (he : d.flatten=U.sort (· ≤ ·)) (hp : d.Parity) : + blockCharge p B Hu Hv lam d = + (if d.right.isSome then lam else 1) * + ((d.flatten.map (fun j => vertexPotential p B Hu Hv lam (j.val+1))).prod)⁻¹ := by + let z := fun j : Fin (4*p) => vertexPotential p B Hu Hv lam (j.val+1) + have hleft : (d.left.toList.map (leftFactor p B Hu Hv lam)).prod = + ((d.left.toList.map z).prod)⁻¹ := by + cases hl : d.left with + | none => simp + | some j => + have hj := hp.1 j (by simp [hl]) + simpa [hl,z] using leftFactor_eq_potential p B Hu Hv lam j hj + have hright : (d.right.toList.map (rightFactor p B Hu Hv lam)).prod = + (if d.right.isSome then lam else 1) * ((d.right.toList.map z).prod)⁻¹ := by + cases hr : d.right with + | none => simp + | some j => + have hj := hp.2.2 j (by simp [hr]) + simpa [hr,z,div_eq_mul_inv] using rightFactor_eq_potential p B Hu Hv lam hlam j hj + have hneutral : (d.neutral.map (fun q => neutralFactor p B Hu Hv lam q.1 q.2)).prod = + (((d.neutral.flatMap (fun q => [q.1,q.2])).map z).prod)⁻¹ := by + have hh : d.neutral.map (fun q => neutralFactor p B Hu Hv lam q.1 q.2)= + d.neutral.map (fun q => (z q.1*z q.2)⁻¹) := by + apply List.map_congr_left + intro q hq + exact neutralFactor_eq_potential p B Hu Hv lam hlam q.1 q.2 + (d.neutral_lt he q hq) (hp.2.1 q hq).1 (hp.2.1 q hq).2 + rw [hh] + simp only [List.flatMap_def] + simp [List.prod_inv,Function.comp_def] + unfold blockCharge + rw [hleft,hright,hneutral] + simp only [HoleBlocks.flatten,List.map_append,List.prod_append,mul_inv_rev] + change _ = (if d.right.isSome then lam else 1) * _ + ring + +noncomputable def pathConstant (p : ℕ) (B Hu Hv : ℝ) : ℝ := + (∏ r : Fin p, max B (Hu/2^r.val)) * (∏ r : Fin p, max B (Hv/2^r.val)) + +lemma forcing_weight_charge (p : ℕ) (B Hu Hv lam : ℝ) (hB : 0 < B) (hlam : 0 < lam) + (U : Finset (Fin (4*p))) (b : Selection (4*p)) (hb : Valid U b) + (d : HoleBlocks (4*p)) (he : d.flatten=U.sort (· ≤ ·)) (hp : d.Parity) : + (if U.Nonempty then selectedWeight (profileActivity p B Hu Hv lam) b else pathConstant p B Hu Hv) = + pathConstant p B Hu Hv * blockCharge p B Hu Hv lam d := by + classical + rw [blockCharge_potential p B Hu Hv lam hlam.ne' U d he hp] + by_cases hU : U.Nonempty + · rw [ite_eq_left hU] + let z : Fin (4*p+2) → ℝ := fun i => vertexPotential p B Hu Hv lam i.val + have hprof : (fun i : Fin (4*p+1) => z i.castSucc*z i.succ)=profileActivity p B Hu Hv lam := by + funext i + exact (profile_vertexPotential p B Hu Hv lam hlam.ne' i).symm + have hh := selectedWeight_hole_product (show Even (4*p) from ⟨2*p,by omega⟩) U b hb z + rw [hprof,exact_profile_weight] at hh + have hprod : (d.flatten.map (fun j => vertexPotential p B Hu Hv lam (j.val+1))).prod = + ∏ j ∈ U, z j.succ.castSucc := by + rw [he,((Finset.sort_perm_toList U (· ≤ ·)).map _).prod_eq,Finset.prod_map_toList] + rfl + have hz0 : z 0=1 := vertexPotential_zero p B Hu Hv lam + have hzlast : z (Fin.last (4*p+1))=lam := vertexPotential_last p B Hu Hv lam + have hr : (b (Fin.last (4*p))=true) ↔ d.right.isSome := + d.right_uses ⟨2*p,by omega⟩ hb hU he hp + have hl : (if b 0 then z 0 else 1)=1 := by rw [hz0]; split_ifs <;> rfl + simp only [Bool.false_eq_true,ite_false,mul_one,hl,hzlast] at hh + simp only [hr] at hh + have hz : (∏ j ∈ U, z j.succ.castSucc) ≠ 0 := by + apply ne_of_gt + apply Finset.prod_pos + intro j hj + exact vertexPotential_pos p B Hu Hv lam hB hlam _ + rw [hprod] + change _=pathConstant p B Hu Hv * ((if d.right.isSome then lam else 1)*_) + apply (mul_right_cancel₀ hz) + rw [mul_assoc,mul_assoc,inv_mul_cancel₀ hz,mul_one] + exact hh + · rw [ite_eq_right hU] + have hh : d.flatten=[] := by rw [he,Finset.not_nonempty_iff_eq_empty.mp hU]; simp + have hr : d.right=none := by + have he' := hh + simp only [HoleBlocks.flatten,List.append_eq_nil_iff] at he' + cases hr : d.right <;> simp_all + simp [hh,hr] + +end MatchingFPRAS.Enlargement + +end OAI diff --git a/lean/OAI/Combinatorics/MatchingCount/Graphs/Incident.lean b/lean/OAI/Combinatorics/MatchingCount/Graphs/Incident.lean new file mode 100644 index 0000000000000000000000000000000000000000..19fb2566fb8bf82ac9bd84e2645c2deafd588e96 --- /dev/null +++ b/lean/OAI/Combinatorics/MatchingCount/Graphs/Incident.lean @@ -0,0 +1,469 @@ +import Mathlib +import OAI.Combinatorics.MatchingCount.Graphs.HoleStrength + +namespace OAI + +namespace MatchingFPRAS.Enlargement + +open MatchingFPRAS.Switching MatchingFPRAS.Subdivision MatchingFPRAS.RealGeometry +open Finset + +variable {V E : Type*} [Fintype V] [LinearOrder V] [Fintype E] [LinearOrder E] + +omit [Fintype V] [LinearOrder E] in +lemma totalDeletionCharge_eq_blocks [Fintype V] [LinearOrder E] + (u v : E → V) (huv : ∀ e, u e ≠ v e) + (p : ℕ) (B Hu Hv lam : E → ℝ) (d : E → HoleBlocks (4*p)) : + totalDeletionCharge u v p B Hu Hv lam d = + ∏ e, blockCharge p (B e) (Hu e) (Hv e) (lam e) (d e) := by + classical + simp only [totalDeletionCharge,neutralPairs,consumedPairs, + List.flatMap_def,List.map_flatten,List.prod_flatten,List.map_map,Function.comp_def, + List.map_append,List.prod_append] + simp only [neutralCharge,consumedCharge,ite_true,(huv _).symm,ite_false] + simp only [Finset.prod_map_toList,blockCharge,Finset.prod_mul_distrib] + ring + +theorem deletionConstant_eq_charge (u v : E → V) (huv : ∀ e, u e ≠ v e) + (p : ℕ) (B Hu Hv lam : E → ℝ) (hB : ∀ e, 0 < B e) (hlam : ∀ e, 0 < lam e) + (R₀ : Finset V) (U : E → Finset (Fin (4*p))) (b : E → Selection (4*p)) + (hb : FamilyHoles u v (4*p) R₀ U b) + (d : E → HoleBlocks (4*p)) (he : ∀ e, (d e).flatten=(U e).sort (· ≤ ·)) + (hpar : ∀ e, (d e).Parity) : + deletionConstant U b (pathActivity p B Hu Hv lam) (fun e => pathConstant p (B e) (Hu e) (Hv e)) = + (∏ e, pathConstant p (B e) (Hu e) (Hv e)) * totalDeletionCharge u v p B Hu Hv lam d := by + rw [totalDeletionCharge_eq_blocks u v huv,← Finset.prod_mul_distrib] + unfold deletionConstant + apply Finset.prod_congr rfl + intro e _ + exact forcing_weight_charge p (B e) (Hu e) (Hv e) (lam e) (hB e) (hlam e) + (U e) (b e) (hb.1 e) (d e) (he e) (hpar e) + +theorem real_partition_charge_identity (u v : E → V) (huv : ∀ e, u e ≠ v e) + (p : ℕ) (B Hu Hv lam : E → ℝ) (hB : ∀ e, 0 < B e) (hlam : ∀ e, 0 < lam e) + (R₀ : Finset V) (U : E → Finset (Fin (4*p))) (b : E → Selection (4*p)) + (hb : FamilyHoles u v (4*p) R₀ U b) + (d : E → HoleBlocks (4*p)) (he : ∀ e, (d e).flatten=(U e).sort (· ≤ ·)) + (hpar : ∀ e, (d e).Parity) : + realHolePartition u v (4*p) R₀ U (pathActivity p B Hu Hv lam) = + (∏ e, pathConstant p (B e) (Hu e) (Hv e)) * totalDeletionCharge u v p B Hu Hv lam d * + logicalHolePartition u v (residualHoles u v R₀ U b) (broken U) lam := by + classical + have hid := deletion_partition_identity (show Even (4*p) from ⟨2*p,by omega⟩) + u v R₀ U b hb (pathActivity p B Hu Hv lam) + (fun e => List.ofFn fun r : Fin p => max (B e) (Hu e/2^r.val)) + (fun e => (List.ofFn fun r : Fin p => max (B e) (Hv e/2^r.val)).reverse) lam + (fun e => profileActivity_ofFn p (B e) (Hu e) (Hv e) (lam e)) + simp only [List.prod_reverse,List.prod_ofFn] at hid + change realHolePartition _ _ _ _ _ _ = + deletionConstant U b (pathActivity p B Hu Hv lam) + (fun e => pathConstant p (B e) (Hu e) (Hv e)) * _ at hid + rw [hid,deletionConstant_eq_charge u v huv p B Hu Hv lam hB hlam R₀ U b hb d he hpar] + +end MatchingFPRAS.Enlargement + +namespace MatchingFPRAS.Representation + +open MatchingFPRAS.Switching MatchingFPRAS.Subdivision MatchingFPRAS.Enlargement +open Finset + +variable {V : Type*} [Fintype V] [LinearOrder V] + +abbrev Incident (e : LogicalEdge V) (x : V) := source e=x ∨ target e=x + +noncomputable def other (e : LogicalEdge V) (x : V) : V := + if source e=x then target e else source e + +omit [Fintype V] in +@[simp] lemma other_source (e : LogicalEdge V) : other e (source e)=target e := by simp [other] +@[simp] lemma other_target (e : LogicalEdge V) : other e (target e)=source e := by + simp [other,source_ne_target e] + +lemma other_incident (e : LogicalEdge V) (x : V) (hx : Incident e x) : + Incident e (other e x) := by + rcases hx with rfl | rfl <;> simp only [other_source,other_target] <;> tauto + +lemma other_ne (e : LogicalEdge V) (x : V) (hx : Incident e x) : other e x ≠ x := by + rcases hx with rfl | rfl <;> simp [source_ne_target e,(source_ne_target e).symm] + +lemma other_other (e : LogicalEdge V) (x : V) (hx : Incident e x) : + other e (other e x)=x := by rcases hx with rfl | rfl <;> simp + +lemma edge_eq_of_inc_other {e f : LogicalEdge V} (h : Incident f (source e)) + (ho : other f (source e)=target e) : f=e := by + rcases h with h | h + · have ht : target f=target e := by simpa only [← h,other_source] using ho + exact Subtype.ext (Prod.ext h ht) + · have hs : source f=target e := by simpa only [← h,other_target] using ho + have hf := f.property + have he := e.property + change source f < target f at hf + change source e < target e at he + rw [hs,h] at hf + exact False.elim ((lt_asymm he hf)) + +variable (R : Finset V) (s : LogicalEdge V → Bool) + (hs : LogicalHoles source target R ∅ s) + +include hs in +omit [Fintype V] in +lemma selected_not_hole [Fintype V] (e : LogicalEdge V) (he : s e=true) (x : V) (hx : Incident e x) : + x ∉ R := by + intro hxR + exact hs.2.1 x hxR e ⟨he,hx⟩ + +noncomputable def chosen (x : V) (hx : x ∉ R) : LogicalEdge V := + (hs.2.2 x hx).exists.choose + +omit [Fintype V] in +lemma chosen_spec [Fintype V] (x : V) (hx : x ∉ R) : + s (chosen R s hs x hx)=true ∧ Incident (chosen R s hs x hx) x := + (hs.2.2 x hx).exists.choose_spec + +lemma chosen_eq (x : V) (hx : x ∉ R) (e : LogicalEdge V) + (he : s e=true) (hi : Incident e x) : chosen R s hs x hx=e := by + exact (hs.2.2 x hx).unique (chosen_spec R s hs x hx) ⟨he,hi⟩ + +noncomputable def mateFun (x : V) : V := + if h : x ∈ R then x else other (chosen R s hs x h) x + +omit [Fintype V] in +lemma mateFun_hole [Fintype V] (x : V) (hx : x ∈ R) : mateFun R s hs x=x := by simp [mateFun,hx] + +lemma mateFun_selected (e : LogicalEdge V) (he : s e=true) (x : V) (hx : Incident e x) : + mateFun R s hs x=other e x := by + have hn := selected_not_hole R s hs e he x hx + simp only [mateFun,dite_eq_right hn] + rw [chosen_eq R s hs x hn e he hx] + +lemma mateFun_involutive : Function.Involutive (mateFun R s hs) := by + intro x + by_cases hx : x ∈ R + · rw [mateFun_hole R s hs x hx,mateFun_hole R s hs x hx] + · let e := chosen R s hs x hx + have he := chosen_spec R s hs x hx + have hx' : mateFun R s hs x=other e x := mateFun_selected R s hs e he.1 x he.2 + rw [hx',mateFun_selected R s hs e he.1 _ (other_incident e x he.2),other_other e x he.2] + +noncomputable def asMate : Mate V := ⟨mateFun R s hs,mateFun_involutive R s hs⟩ + +lemma asMate_holes : HasHoles (asMate R s hs) R := by + intro x + change mateFun R s hs x=x ↔ x ∈ R + by_cases hx : x ∈ R + · simp [hx,mateFun_hole R s hs x hx] + · simp only [hx,iff_false] + change mateFun R s hs x ≠ x + rw [mateFun_selected R s hs _ (chosen_spec R s hs x hx).1 x (chosen_spec R s hs x hx).2] + exact other_ne _ x (chosen_spec R s hs x hx).2 + +lemma asMate_selected (e : LogicalEdge V) : + (asMate R s hs).val (source e)=target e ↔ s e=true := by + constructor + · intro hm + have hx : source e ∉ R := by + intro hx + have hh := mateFun_hole R s hs _ hx + change mateFun R s hs (source e)=target e at hm + exact source_ne_target e (hh.symm.trans hm) + let f := chosen R s hs (source e) hx + have hf := chosen_spec R s hs (source e) hx + have ho : other f (source e)=target e := by + rw [← mateFun_selected R s hs f hf.1 _ hf.2] + exact hm + have hfe : f=e := edge_eq_of_inc_other hf.2 ho + exact hfe ▸ hf.1 + · intro he + exact (mateFun_selected R s hs e he (source e) (Or.inl rfl)).trans (other_source e) + +variable {R s hs} + +noncomputable def select (m : Mate V) (e : LogicalEdge V) : Bool := + decide (m.val (source e)=target e) + +omit [Fintype V] in +@[simp] lemma select_eq_true [Fintype V] (m : Mate V) (e : LogicalEdge V) : + select m e=true ↔ m.val (source e)=target e := by simp [select] + +lemma select_mate_other (m : Mate V) (e : LogicalEdge V) + (he : select m e=true) (x : V) (hx : Incident e x) : m.val x=other e x := by + have ht := (select_eq_true m e).mp he + rcases hx with rfl | rfl + · simpa only [other_source] using ht + · simp only [other_target] + rw [← ht,mate_mate] + +lemma edge_eq_of_selected_inc (m : Mate V) {e f : LogicalEdge V} + (he : select m e=true) (hf : select m f=true) + (x : V) (hex : Incident e x) (hfx : Incident f x) : e=f := by + have hh : other e x=other f x := (select_mate_other m e he x hex).symm.trans + (select_mate_other m f hf x hfx) + rcases hex with rfl | rfl + · exact (edge_eq_of_inc_other hfx (hh.symm.trans (other_source e))).symm + · have hy : Incident f (source e) := by + rw [other_target] at hh + rw [hh] + exact other_incident f _ hfx + apply (edge_eq_of_inc_other hy ?_).symm + rw [other_target] at hh + rw [hh,other_other f _ hfx] + +lemma select_holes (m : Mate V) (hm : HasHoles m R) : + LogicalHoles source target R ∅ (select m) := by + classical + refine ⟨by simp,?_,?_⟩ + · intro x hx e he + have hh := select_mate_other m e he.1 x he.2 + rw [(hm x).mpr hx] at hh + exact other_ne e x he.2 hh.symm + · intro x hx + have hmx : m.val x ≠ x := fun h => hx ((hm x).mp h) + have hex : ∃ e : LogicalEdge V, select m e=true ∧ Incident e x := by + rcases lt_or_gt_of_ne hmx.symm with h | h + · exact ⟨⟨(x,m.val x),h⟩,by simp [select,source,target],Or.inl rfl⟩ + · exact ⟨⟨(m.val x,x),h⟩,by simp [select,source,target],Or.inr rfl⟩ + obtain ⟨e,he⟩ := hex + refine ⟨e,he,?_⟩ + intro f hf + exact edge_eq_of_selected_inc m hf.1 he.1 x hf.2 he.2 + +@[simp] lemma select_asMate : select (asMate R s hs)=s := by + funext e + apply Bool.eq_iff_iff.mpr + exact (select_eq_true _ e).trans (asMate_selected R s hs e) + +lemma asMate_select (m : Mate V) (hm : HasHoles m R) : + asMate R (select m) (select_holes m hm)=m := by + apply Subtype.ext + funext x + by_cases hx : x ∈ R + · exact (mateFun_hole R _ _ x hx).trans ((hm x).mpr hx).symm + · let h := select_holes m hm + let e := chosen R (select m) h x hx + have he := chosen_spec R (select m) h x hx + exact (mateFun_selected R _ h e he.1 x he.2).trans + (select_mate_other m e he.1 x he.2).symm + +noncomputable def matchingEquiv (R : Finset V) : + {s : LogicalEdge V → Bool // LogicalHoles source target R ∅ s} ≃ + {m : Mate V // HasHoles m R} where + toFun s := ⟨asMate R s.val s.property,asMate_holes R s.val s.property⟩ + invFun m := ⟨select m.val,select_holes m.val m.property⟩ + left_inv _selection := Subtype.ext select_asMate + right_inv m := Subtype.ext (asMate_select m.val m.property) + +lemma selection_weight (w : V → V → ℝ) (m : Mate V) : + (∏ e : LogicalEdge V, if select m e then logicalActivity w e else 1)=weight w m := by + classical + unfold weight + rw [← Finset.prod_filter,← Finset.prod_filter] + apply Finset.prod_bij (fun e _ => source e) + · intro e he + have hh := (select_eq_true m e).mp (Finset.mem_filter.mp he).2 + simp only [Finset.mem_filter,Finset.mem_univ,true_and] + rw [hh] + exact e.property + · intro e he f hf h + have he' := (select_eq_true m e).mp (Finset.mem_filter.mp he).2 + have hf' := (select_eq_true m f).mp (Finset.mem_filter.mp hf).2 + exact Subtype.ext (Prod.ext h (he'.symm.trans ((congrArg m.val h).trans hf'))) + · intro x hx + have hx' := (Finset.mem_filter.mp hx).2 + refine ⟨⟨(x,m.val x),hx'⟩,?_,rfl⟩ + exact Finset.mem_filter.mpr ⟨Finset.mem_univ _,by simp [select,source,target]⟩ + · intro e he + have he' := (select_eq_true m e).mp (Finset.mem_filter.mp he).2 + simp only [logicalActivity,edgeActivity,show source e < target e from e.property,ite_true,he'] + +lemma asMate_weight (w : V → V → ℝ) : + (∏ e : LogicalEdge V, if s e then logicalActivity w e else 1)=weight w (asMate R s hs) := by + rw [← selection_weight,select_asMate] + +theorem logical_partition_eq (w : V → V → ℝ) (R : Finset V) : + logicalHolePartition source target R ∅ (logicalActivity w)=partition w R := by + classical + let := Fintype.ofFinite {s : LogicalEdge V → Bool // LogicalHoles source target R ∅ s} + let := Fintype.ofFinite {m : Mate V // HasHoles m R} + unfold logicalHolePartition partition + rw [Finset.sum_subtype (matchings R) (fun m => mem_matchings m R)] + apply Fintype.sum_equiv (matchingEquiv R) + intro s + exact asMate_weight w + +theorem logical_partition_forbidden_le (w : V → V → ℝ) (hw : ∀ a b, 0 ≤ w a b) + (R : Finset V) (forbidden : Finset (LogicalEdge V)) : + logicalHolePartition source target R forbidden (logicalActivity w) ≤ partition w R := by + classical + let := Fintype.ofFinite {s : LogicalEdge V → Bool // LogicalHoles source target R forbidden s} + let := Fintype.ofFinite {s : LogicalEdge V → Bool // LogicalHoles source target R ∅ s} + rw [← logical_partition_eq] + unfold logicalHolePartition + let f : {s : LogicalEdge V → Bool // LogicalHoles source target R forbidden s} → + {s : LogicalEdge V → Bool // LogicalHoles source target R ∅ s} := + fun s => ⟨s.val,⟨by simp,s.property.2⟩⟩ + have hf : Function.Injective f := by + intro a b hab + exact Subtype.ext (congrArg + (fun z : {s : LogicalEdge V → Bool // LogicalHoles source target R ∅ s} => z.val) hab) + let g := fun s : {s : LogicalEdge V → Bool // LogicalHoles source target R ∅ s} => + ∏ e, if s.val e then logicalActivity w e else 1 + calc + _ = ∑ y ∈ Finset.univ.image f, g y := by + rw [Finset.sum_image hf.injOn] + _ ≤ ∑ y, g y := by + apply Finset.sum_le_sum_of_subset_of_nonneg (Finset.subset_univ _) + intro s _ _ + apply Finset.prod_nonneg + intro e _ + split_ifs + · unfold logicalActivity edgeActivity + split_ifs <;> exact hw _ _ + · norm_num + +end MatchingFPRAS.Representation + +namespace MatchingFPRAS.Enlargement + +open MatchingFPRAS.Switching MatchingFPRAS.Subdivision MatchingFPRAS.RealGeometry +open MatchingFPRAS.Representation +open Finset + +variable {V : Type*} [Fintype V] [LinearOrder V] + +lemma pathConstant_pos (p : ℕ) (B Hu Hv : ℝ) (hB : 0 < B) : + 0 < pathConstant p B Hu Hv := by + apply mul_pos <;> apply Finset.prod_pos <;> intro i hi <;> exact hB.trans_le (le_max_left _ _) + +lemma intact_family (p : ℕ) (m : Mate V) (hm : HasHoles m ∅) : + FamilyHoles source target (4*p) ∅ (fun _ => ∅) + (fun e i => alternating (select m e) i.val) := by + have hs := select_holes m hm + refine ⟨fun e => alternating_valid _ _,by simp,?_⟩ + intro x hx + have hi (e : LogicalEdge V) : + Uses source target (fun (e : LogicalEdge V) (i : Fin (4*p+1)) => alternating (select m e) i.val) e x ↔ + select m e=true ∧ Incident e x := by + rw [intact_uses (show Even (4*p) from ⟨2*p,by omega⟩) source target _ e x + (alternating_valid _ _)] + simp only [Fin.val_zero,alternating,Nat.zero_mod,ite_true] + simpa only [hi] using hs.2.2 x hx + +theorem intact_partition_identity (w : V → V → ℝ) (hz : 0 < partition w ∅) + (p : ℕ) (B Hu Hv : LogicalEdge V → ℝ) : + realHolePartition source target (4*p) ∅ (fun _ => ∅) + (pathActivity p B Hu Hv (logicalActivity w)) = + (∏ e, pathConstant p (B e) (Hu e) (Hv e)) * partition w ∅ := by + classical + have hn : (matchings (∅ : Finset V)).Nonempty := by + by_contra hn + have hz0 : partition w ∅=0 := by + simp [partition,Finset.not_nonempty_iff_eq_empty.mp hn] + linarith + obtain ⟨m,hm⟩ := hn + let b := fun (e : LogicalEdge V) (i : Fin (4*p+1)) => alternating (select m e) i.val + have hb := intact_family p m ((mem_matchings m ∅).mp hm) + have hid := deletion_partition_identity (show Even (4*p) from ⟨2*p,by omega⟩) + source target ∅ (fun _ => ∅) b hb (pathActivity p B Hu Hv (logicalActivity w)) + (fun e => List.ofFn fun r : Fin p => max (B e) (Hu e/2^r.val)) + (fun e => (List.ofFn fun r : Fin p => max (B e) (Hv e/2^r.val)).reverse) _ + (fun e => profileActivity_ofFn p (B e) (Hu e) (Hv e) (logicalActivity w e)) + simpa [residualHoles,broken,deletionConstant,List.prod_ofFn,pathConstant, + logical_partition_eq] using hid + +theorem lifted_hole_bound_feasible (hn : 2 ≤ Fintype.card V) + (w : V → V → ℝ) (hw : ∀ a b, 0 < w a b) (hz : 0 < partition w ∅) + (hrlo : ∀ a, (1:ℝ)/4 ≤ rowMax hn w a) (hrhi : ∀ a, rowMax hn w a ≤ 1) + (p : ℕ) (hp : 1 ≤ p) (Hu Hv : LogicalEdge V → ℝ) + (hHu : ∀ e, 0 ≤ Hu e) (hHv : ∀ e, 0 ≤ Hv e) + (R₀ : Finset V) (U : LogicalEdge V → Finset (Fin (4*p))) + (b : LogicalEdge V → Selection (4*p)) (hb : FamilyHoles source target (4*p) R₀ U b) + (hH : Even (enlargedHoles (4*p) R₀ U).card) : + realHolePartition source target (4*p) R₀ U + (pathActivity p (fun e => bottleneck w (source e) (target e)) Hu Hv (logicalActivity w)) / + realHolePartition source target (4*p) ∅ (fun _ => ∅) + (pathActivity p (fun e => bottleneck w (source e) (target e)) Hu Hv (logicalActivity w)) * + pairingCapacity (realBottleneck source target p + (fun e => bottleneck w (source e) (target e)) Hu Hv (logicalActivity w)) + (enlargedHoles (4*p) R₀ U) hH ≤ + 2 * holeScale V ^ ((enlargedHoles (4*p) R₀ U).card/2) := by + classical + choose d he hpar using (fun e => hole_blocks_exist (hb.1 e)) + let B := fun e : LogicalEdge V => bottleneck w (source e) (target e) + let R := residualHoles source target R₀ U b + let F := totalDeletionCharge source target p B Hu Hv (logicalActivity w) d + let C := ∏ e, pathConstant p (B e) (Hu e) (Hv e) + let Zf := logicalHolePartition source target R (broken U) (logicalActivity w) + have hB : ∀ e, 0 < B e := fun e => lt_of_lt_of_le zero_lt_one (one_le_bottleneck _ _ _) + have hlam : ∀ e, 0 < logicalActivity w e := by + intro e + unfold logicalActivity edgeActivity + split_ifs <;> exact hw _ _ + have hC : 0 < C := Finset.prod_pos (fun e _ => pathConstant_pos p _ _ _ (hB e)) + have htrace := deletion_charge_trace source target source_ne_target p hp B Hu Hv (logicalActivity w) + (fun e => one_le_bottleneck w _ _) hHu hHv (fun e => (hlam e).le) + (fun e => edgeActivity_le_bottleneck w _ _ (source_ne_target e)) R₀ U b hb d he hpar + have hF : 0 ≤ F := htrace.factor_nonneg + have hcard : R.card ≤ (enlargedHoles (4*p) R₀ U).card := by + simpa using htrace.card_le + obtain ⟨hR,hcap⟩ := deletion_capacity_bound w hw p hp Hu Hv hHu hHv R₀ U b hb d he hpar hH + have hZf : 0 ≤ Zf := by + unfold Zf logicalHolePartition + apply Finset.sum_nonneg + intro s _ + apply Finset.prod_nonneg + intro e _ + split_ifs <;> first | exact (hlam e).le | norm_num + have hZf_le : Zf ≤ partition w R := logical_partition_forbidden_le w (fun a b => (hw a b).le) R _ + rw [real_partition_charge_identity source target source_ne_target p B Hu Hv (logicalActivity w) + hB hlam R₀ U b hb d he hpar,intact_partition_identity w hz p B Hu Hv] + change (C * F * Zf) / (C * partition w ∅) * _ ≤ _ + calc + _ = (Zf / partition w ∅) * (pairingCapacity (realBottleneck source target p B Hu Hv (logicalActivity w)) + (enlargedHoles (4*p) R₀ U) hH * F) := by field_simp [hC.ne',hz.ne']; ring + _ ≤ (Zf / partition w ∅) * pairingCapacity (bottleneck w) R hR := + mul_le_mul_of_nonneg_left hcap (div_nonneg hZf hz.le) + _ ≤ (partition w R / partition w ∅) * pairingCapacity (bottleneck w) R hR := + mul_le_mul_of_nonneg_right (div_le_div_of_nonneg_right hZf_le hz.le) + (pairingCapacity_nonneg _ (fun a b => zero_le_one.trans (one_le_bottleneck w a b)) R hR) + _ ≤ 2 * holeScale V ^ (R.card/2) := logical_hole_bound hn w (fun a b => (hw a b).le) hz hrlo hrhi R hR + _ ≤ _ := by + apply mul_le_mul_of_nonneg_left _ (by norm_num) + apply pow_le_pow_right₀ _ (Nat.div_le_div_right hcard) + unfold holeScale + have hN : (1:ℝ) ≤ (Fintype.card V : ℝ)+1 := by have := Nat.cast_nonneg (α := ℝ) (Fintype.card V); linarith + have hp4 := one_le_pow₀ hN (n := 4) + linarith + +theorem lifted_hole_bound (hn : 2 ≤ Fintype.card V) + (w : V → V → ℝ) (hw : ∀ a b, 0 < w a b) (hz : 0 < partition w ∅) + (hrlo : ∀ a, (1:ℝ)/4 ≤ rowMax hn w a) (hrhi : ∀ a, rowMax hn w a ≤ 1) + (p : ℕ) (hp : 1 ≤ p) (Hu Hv : LogicalEdge V → ℝ) + (hHu : ∀ e, 0 ≤ Hu e) (hHv : ∀ e, 0 ≤ Hv e) + (R₀ : Finset V) (U : LogicalEdge V → Finset (Fin (4*p))) + (hH : Even (enlargedHoles (4*p) R₀ U).card) : + realHolePartition source target (4*p) R₀ U + (pathActivity p (fun e => bottleneck w (source e) (target e)) Hu Hv (logicalActivity w)) / + realHolePartition source target (4*p) ∅ (fun _ => ∅) + (pathActivity p (fun e => bottleneck w (source e) (target e)) Hu Hv (logicalActivity w)) * + pairingCapacity (realBottleneck source target p + (fun e => bottleneck w (source e) (target e)) Hu Hv (logicalActivity w)) + (enlargedHoles (4*p) R₀ U) hH ≤ + 2 * holeScale V ^ ((enlargedHoles (4*p) R₀ U).card/2) := by + classical + by_cases h : ∃ b, FamilyHoles source target (4*p) R₀ U b + · obtain ⟨b,hb⟩ := h + exact lifted_hole_bound_feasible hn w hw hz hrlo hrhi p hp Hu Hv hHu hHv R₀ U b hb hH + · have hempty : IsEmpty {b : LogicalEdge V → Selection (4*p) // + FamilyHoles source target (4*p) R₀ U b} := ⟨fun b => h ⟨b.val,b.property⟩⟩ + have hzero : realHolePartition source target (4*p) R₀ U + (pathActivity p (fun e => bottleneck w (source e) (target e)) Hu Hv (logicalActivity w)) = 0 := by + let := hempty + unfold realHolePartition + exact Finset.sum_eq_zero (fun b _ => isEmptyElim b) + rw [hzero,zero_div,zero_mul] + unfold holeScale + positivity + +end MatchingFPRAS.Enlargement + +end OAI diff --git a/lean/OAI/Combinatorics/MatchingCount/Graphs/IndexedCycle.lean b/lean/OAI/Combinatorics/MatchingCount/Graphs/IndexedCycle.lean new file mode 100644 index 0000000000000000000000000000000000000000..ad9504b56058617acd3f19b0a8ef7274da55fd4d --- /dev/null +++ b/lean/OAI/Combinatorics/MatchingCount/Graphs/IndexedCycle.lean @@ -0,0 +1,439 @@ +import Mathlib +import OAI.Combinatorics.MatchingCount.Sampling.Corner + +namespace OAI + +namespace MatchingFPRAS.Transport + +section + +variable {V E : Type*} + +variable (inc : E → V → Prop) + +structure IndexedCycle where + size : ℕ + four_le : 4 ≤ size + even : size % 2 = 0 + vertex : Fin size → V + simple : Function.Injective vertex + edge : Fin size → E + incidence : ∀ i v, inc (edge i) v ↔ v = vertex i ∨ v = vertex ⟨(i.val + 1) % size, Nat.mod_lt _ (by omega)⟩ + +namespace IndexedCycle + +variable {inc} (c : IndexedCycle inc) + +def index (i : ℕ) : Fin c.size := ⟨i % c.size, Nat.mod_lt i (by have := c.four_le; omega)⟩ + +def vertexAt (i : ℕ) : V := c.vertex (c.index i) + +def edgeAt (i : ℕ) : E := c.edge (c.index i) + +lemma index_succ (i : ℕ) : c.index (i + 1) = ⟨((c.index i).val + 1) % c.size, Nat.mod_lt _ (by have := c.four_le; omega)⟩ := by + apply Fin.ext + simp only [index, Nat.add_mod, Nat.mod_mod] + +lemma vertexAt_mod (i : ℕ) : c.vertexAt (i % c.size) = c.vertexAt i := by + exact congrArg c.vertex (Fin.ext (Nat.mod_mod i c.size)) + +lemma vertexAt_periodic (i : ℕ) : c.vertexAt (i + c.size) = c.vertexAt i := by + simp [vertexAt, index] + +lemma edgeAt_incidence (i : ℕ) (v : V) : + inc (c.edgeAt i) v ↔ v = c.vertexAt i ∨ v = c.vertexAt (i + 1) := by + simpa [edgeAt, vertexAt, c.index_succ] using c.incidence (c.index i) v + +lemma mod_of_lt_twice {m x : ℕ} (hx : x < 2 * m) : + x % m = if x < m then x else x - m := by + split_ifs with h + · exact Nat.mod_eq_of_lt h + · rw [Nat.mod_eq_sub_mod (by omega), Nat.mod_eq_of_lt (by omega)] + +lemma vertexAt_eq_iff {a x y : ℕ} (ha : a < c.size) + (hx : a ≤ x ∧ x < a + c.size) (hy : a ≤ y ∧ y < a + c.size) : + c.vertexAt x = c.vertexAt y ↔ x = y := by + constructor + · intro h + have hm : x % c.size = y % c.size := congrArg Fin.val (c.simple h) + rw [mod_of_lt_twice (by omega), mod_of_lt_twice (by omega)] at hm + split_ifs at hm <;> omega + · exact congrArg c.vertexAt + +def arc (start length : ℕ) (hstart : start < c.size) (hpos : 0 < length) + (hlt : length < c.size) (hodd : length % 2 = 1) : OddPath inc where + length := length + positive := hpos + odd := hodd + vertex i := c.vertexAt (start + i) + edge i := c.edgeAt (start + i) + simple := by + intro i hi j hj h + change 0 ≤ i ∧ i ≤ length at hi + change 0 ≤ j ∧ j ≤ length at hj + have := (c.vertexAt_eq_iff hstart + (x := start + i) (y := start + j) (by constructor <;> omega) + (by constructor <;> omega)).mp h + omega + incidence := by + intro i hi v + simpa [Nat.add_assoc] using c.edgeAt_incidence (start + i) v + +structure Corners where + a₀ : ℕ + a₁ : ℕ + a₂ : ℕ + a₃ : ℕ + lt₀ : a₀ < a₁ + lt₁ : a₁ < a₂ + lt₂ : a₂ < a₃ + lt₃ : a₃ < c.size + odd₀ : (a₁ - a₀) % 2 = 1 + odd₁ : (a₂ - a₁) % 2 = 1 + odd₂ : (a₃ - a₂) % 2 = 1 + odd₃ : (c.size + a₀ - a₃) % 2 = 1 + +namespace Corners + +variable {c} (k : c.Corners) + +def start : Fin 4 → ℕ := ![k.a₀, k.a₁, k.a₂, k.a₃] + +def stop : Fin 4 → ℕ := ![k.a₁, k.a₂, k.a₃, c.size + k.a₀] + +def length (i : Fin 4) : ℕ := k.stop i - k.start i + +lemma bounds (i : Fin 4) : + k.a₀ ≤ k.start i ∧ k.start i < c.size ∧ + k.start i < k.stop i ∧ k.stop i ≤ k.a₀ + c.size ∧ + k.stop i < k.start i + c.size := by + have h₀ := k.lt₀ + have h₁ := k.lt₁ + have h₂ := k.lt₂ + have h₃ := k.lt₃ + fin_cases i <;> simp [start, stop] <;> omega + +lemma length_pos (i : Fin 4) : 0 < k.length i := by + have := k.bounds i + dsimp [length] + omega + +lemma length_lt (i : Fin 4) : k.length i < c.size := by + have := k.bounds i + dsimp [length] + omega + +lemma length_odd (i : Fin 4) : k.length i % 2 = 1 := by + fin_cases i + · exact k.odd₀ + · exact k.odd₁ + · exact k.odd₂ + · exact k.odd₃ + +def side (i : Fin 4) : OddPath inc := + c.arc (k.start i) (k.length i) (k.bounds i).2.1 (k.length_pos i) + (k.length_lt i) (k.length_odd i) + +lemma side_vertex (i : Fin 4) (j : ℕ) : + (k.side i).vertex j = c.vertexAt (k.start i + j) := rfl + +lemma side_length (i : Fin 4) : (k.side i).length = k.length i := rfl + +lemma side_first (i : Fin 4) : (k.side i).vertex 0 = c.vertexAt (k.start i) := by + simp [side_vertex] + +lemma side_last (i : Fin 4) : (k.side i).vertex (k.side i).length = + c.vertexAt (k.stop i) := by + rw [side_vertex, side_length] + congr 1 + dsimp [length] + have := k.bounds i + omega + +lemma joins (i : Fin 4) : (k.side i).vertex (k.side i).length = + (k.side (i + 1)).vertex 0 := by + rw [side_last, side_first] + fin_cases i <;> simp [start, stop] + simpa only [Nat.add_comm] using c.vertexAt_periodic k.a₀ + +lemma starts_injective : Function.Injective k.start := by + have h₀ := k.lt₀ + have h₁ := k.lt₁ + have h₂ := k.lt₂ + intro i j h + fin_cases i <;> fin_cases j <;> simp_all [start] <;> omega + +lemma corners_injective : Function.Injective fun i => (k.side i).vertex 0 := by + intro i j h + simp only [side_first] at h + have hi := k.bounds i + have hj := k.bounds j + have ha : k.a₀ < c.size := by have := k.lt₀; omega + apply k.starts_injective + exact (c.vertexAt_eq_iff ha ⟨hi.1, by omega⟩ ⟨hj.1, by omega⟩).mp h + +variable [DecidableEq V] + +lemma inside_iff (i : Fin 4) (v : V) : + v ∈ (k.side i).inside ↔ + ∃ t, k.start i < t ∧ t < k.stop i ∧ c.vertexAt t = v := by + simp only [OddPath.inside, Finset.mem_image, Finset.mem_Icc, side_length, side_vertex] + constructor + · rintro ⟨j, hj, h⟩ + refine ⟨k.start i + j, by omega, ?_, h⟩ + have := k.bounds i + dsimp [length] at hj + omega + · rintro ⟨t, hlow, hhigh, h⟩ + refine ⟨t - k.start i, ?_, ?_⟩ + · dsimp [length] + constructor <;> omega + · have he : k.start i + (t - k.start i) = t := by omega + simpa [he] using h + +omit [DecidableEq V] in +lemma interior_ranges_disjoint (i j : Fin 4) (hij : i ≠ j) (t : ℕ) + (hi : k.start i < t ∧ t < k.stop i) : + ¬ (k.start j < t ∧ t < k.stop j) := by + have h₀ := k.lt₀ + have h₁ := k.lt₁ + have h₂ := k.lt₂ + have h₃ := k.lt₃ + fin_cases i <;> fin_cases j <;> simp_all [start, stop] <;> omega + +lemma interiors_disjoint : Pairwise fun i j => Disjoint (k.side i).inside (k.side j).inside := by + intro i j hij + apply Finset.disjoint_left.mpr + intro v hv hw + obtain ⟨x, hx₁, hx₂, hx⟩ := (k.inside_iff i v).mp hv + obtain ⟨y, hy₁, hy₂, hy⟩ := (k.inside_iff j v).mp hw + have hi := k.bounds i + have hj := k.bounds j + have ha : k.a₀ < c.size := by have := k.lt₀; omega + have hxy := (c.vertexAt_eq_iff ha (x := x) (y := y) + ⟨by omega, by omega⟩ ⟨by omega, by omega⟩).mp (hx.trans hy.symm) + subst y + exact k.interior_ranges_disjoint i j hij x ⟨hx₁, hx₂⟩ ⟨hy₁, hy₂⟩ + +omit [DecidableEq V] in +lemma interior_not_corner_index (i j : Fin 4) (t : ℕ) + (ht : k.start i < t ∧ t < k.stop i) : t ≠ k.start j := by + have h₀ := k.lt₀ + have h₁ := k.lt₁ + have h₂ := k.lt₂ + have h₃ := k.lt₃ + fin_cases i <;> fin_cases j <;> simp_all [start, stop] <;> omega + +lemma interior_ne_corner (i j : Fin 4) {v : V} (hv : v ∈ (k.side i).inside) : + v ≠ (k.side j).vertex 0 := by + intro heq + obtain ⟨t, ht₁, ht₂, ht⟩ := (k.inside_iff i v).mp hv + have hi := k.bounds i + have hj := k.bounds j + have ha : k.a₀ < c.size := by have := k.lt₀; omega + have h := (c.vertexAt_eq_iff ha (x := t) (y := k.start j) + ⟨by omega, by omega⟩ ⟨hj.1, by omega⟩).mp (ht.trans (by simpa [side_first] using heq)) + exact k.interior_not_corner_index i j t ⟨ht₁, ht₂⟩ h + +lemma interior_ends_disjoint (i j : Fin 4) : Disjoint (k.side i).inside (k.side j).ends := by + apply Finset.disjoint_left.mpr + intro v hv hw + simp only [OddPath.ends, Finset.mem_insert, Finset.mem_singleton, k.joins] at hw + exact hw.elim (k.interior_ne_corner i j hv) (k.interior_ne_corner i (j+1) hv) + +def cellPaths (chord : Fin 4 → E) + (hchord : ∀ i v, inc (chord i) v ↔ + v = (k.side i).vertex 0 ∨ v = (k.side i).vertex (k.side i).length) : CellPaths inc where + side := k.side + joins := k.joins + corners_injective := k.corners_injective + interiors_disjoint := k.interiors_disjoint + interior_ends_disjoint := k.interior_ends_disjoint + chord := chord + chord_incidence := hchord + +end Corners + +end IndexedCycle + +end + +variable {V E : Type*} + +variable {inc : E → V → Prop} + +namespace IndexedCycle + +variable (c : IndexedCycle inc) + +lemma edgeAt_mod (i : ℕ) : c.edgeAt (i % c.size) = c.edgeAt i := by + exact congrArg c.edge (Fin.ext (Nat.mod_mod i c.size)) + +lemma consecutive_ne (i : ℕ) (hi : i < c.size) : c.edgeAt i ≠ c.edgeAt (i+1) := by + intro he + have hm : inc (c.edgeAt (i+1)) (c.vertexAt i) := he ▸ + (c.edgeAt_incidence i _).mpr (Or.inl rfl) + rcases (c.edgeAt_incidence (i+1) _).mp hm with h | h + · have := (c.vertexAt_eq_iff hi (x := i) (y := i+1) + (by have := c.four_le; omega) (by have := c.four_le; omega)).mp h + omega + · have := (c.vertexAt_eq_iff hi (x := i) (y := i+1+1) + (by have := c.four_le; omega) (by have := c.four_le; omega)).mp h + omega + +lemma edges_reachable (U : Finset E) (hU : ∀ i, c.edgeAt i ∈ U) (i : ℕ) : + (overlayLineGraph inc U).Reachable (c.edgeAt 0) (c.edgeAt i) := by + suffices hs : ∀ j, j < c.size → + (overlayLineGraph inc U).Reachable (c.edgeAt 0) (c.edgeAt j) by + simpa only [c.edgeAt_mod] using hs (i % c.size) + (Nat.mod_lt i (by have := c.four_le; omega)) + intro j hj + induction j with + | zero => exact SimpleGraph.Reachable.refl _ + | succ j ih => + apply (ih (by omega)).trans + apply SimpleGraph.Adj.reachable + refine ⟨c.consecutive_ne j (by omega), hU j, hU (j+1), ?_⟩ + exact ⟨c.vertexAt (j+1), (c.edgeAt_incidence j _).mpr (Or.inr rfl), + (c.edgeAt_incidence (j+1) _).mpr (Or.inl rfl)⟩ + +section + +variable [Fintype V] [DecidableEq E] + +lemma adjacent_mem_complement {M N : Finset E} + (hM : MatchingOn inc M Finset.univ) (hN : MatchingOn inc N Finset.univ) + (hU : ∀ i, c.edgeAt i ∈ M ∪ N) (i : ℕ) (hi : i < c.size) : + c.edgeAt (i+1) ∈ M ↔ c.edgeAt i ∉ M := by + have hein := (c.edgeAt_incidence i (c.vertexAt (i+1))).mpr (Or.inr rfl) + have hfin := (c.edgeAt_incidence (i+1) (c.vertexAt (i+1))).mpr (Or.inl rfl) + constructor + · intro hf he + exact c.consecutive_ne i hi (hM.unique (Finset.mem_univ _) he hein hf hfin) + · intro he + have heN := (Finset.mem_union.mp (hU i)).resolve_left he + rcases Finset.mem_union.mp (hU (i+1)) with hf | hf + · exact hf + · exact False.elim (c.consecutive_ne i hi (hN.unique (Finset.mem_univ _) heN hein hf hfin)) + +lemma cycle_edge_mem_complement {M N : Finset E} + (hM : MatchingOn inc M Finset.univ) (hN : MatchingOn inc N Finset.univ) + (hU : ∀ i, c.edgeAt i ∈ M ∪ N) (i : ℕ) : + c.edgeAt i ∈ N ↔ c.edgeAt i ∉ M := by + have hm : i % c.size < c.size := Nat.mod_lt i (by have := c.four_le; omega) + have heq := c.edgeAt_mod i + have h := c.adjacent_mem_complement hM hN hU (i % c.size) hm + have hn := c.adjacent_mem_complement hN hM + (fun j => by rw [Finset.union_comm]; exact hU j) (i % c.size) hm + constructor + · intro hiN hiM + have hjM : c.edgeAt (i % c.size + 1) ∉ M := fun hj => (h.mp hj) (heq.symm ▸ hiM) + have hjN : c.edgeAt (i % c.size + 1) ∉ N := fun hj => (hn.mp hj) (heq.symm ▸ hiN) + exact (Finset.mem_union.mp (hU _)).elim hjM hjN + · intro hiM + exact (Finset.mem_union.mp (hU i)).resolve_left hiM + +lemma cycle_edge_mem_parity {M N : Finset E} + (hM : MatchingOn inc M Finset.univ) (hN : MatchingOn inc N Finset.univ) + (hU : ∀ i, c.edgeAt i ∈ M ∪ N) (i : ℕ) : + c.edgeAt i ∈ M ↔ if i % 2 = 0 then c.edgeAt 0 ∈ M else c.edgeAt 0 ∉ M := by + have hb : ∀ j, j < c.size → + (c.edgeAt j ∈ M ↔ if j % 2 = 0 then c.edgeAt 0 ∈ M else c.edgeAt 0 ∉ M) := by + intro j hj + induction j with + | zero => simp + | succ j ih => + rw [c.adjacent_mem_complement hM hN hU j (by omega), ih (by omega)] + split_ifs <;> first | omega | tauto + have hh := hb (i % c.size) (Nat.mod_lt i (by have := c.four_le; omega)) + have hdiv : 2 ∣ c.size := Nat.dvd_of_mod_eq_zero c.even + have hmod : (i % c.size) % 2 = i % 2 := Nat.mod_mod_of_dvd i hdiv + simpa only [c.edgeAt_mod, hmod] using hh + +end + +namespace Corners + +variable {c} (k : c.Corners) + +lemma parity_start (i : Fin 4) : + k.start i % 2 = if CellPaths.sideBit i then k.a₀ % 2 else 1 - k.a₀ % 2 := by + have h₀ := k.lt₀ + have h₁ := k.lt₁ + have h₂ := k.lt₂ + have ho₀ := k.odd₀ + have ho₁ := k.odd₁ + have ho₂ := k.odd₂ + fin_cases i <;> simp [start, CellPaths.sideBit] <;> omega + +variable [DecidableEq V] [DecidableEq E] + +lemma cell_orientation_subset (chord : Fin 4 → E) + (hc : ∀ i v, inc (chord i) v ↔ + v = (k.side i).vertex 0 ∨ v = (k.side i).vertex (k.side i).length) + (S : Finset E) (a : ℕ) (ha : a < 2) + (hS : ∀ t, t % 2 = a → c.edgeAt t ∈ S) : + (k.cellPaths chord hc).orientation (decide (k.a₀ % 2 = a)) ⊆ S := by + have hh : ∀ i, (k.cellPaths chord hc).orientationPieces (decide (k.a₀ % 2 = a)) i ⊆ S := by + intro i e he + simp only [CellPaths.orientationPieces, CellPaths.pieces] at he + split_ifs at he with hi + · obtain ⟨j, hj, rfl⟩ := Finset.mem_image.mp he + obtain ⟨hb, hp⟩ := Finset.mem_filter.mp hj + obtain ⟨hjl, hjr⟩ := Finset.mem_Ico.mp hb + apply hS + have hs := k.parity_start i + have hp' : j % 2 = 0 := hp + change CellPaths.sideBit i = decide (k.a₀ % 2 = a) at hi + change (k.start i + j) % 2 = a + rw [Nat.add_mod, hs, hp'] + cases hbit : CellPaths.sideBit i <;> simp_all + omega + · obtain ⟨j, hj, rfl⟩ := Finset.mem_image.mp he + obtain ⟨hb, hp⟩ := Finset.mem_filter.mp hj + obtain ⟨hjl, hjr⟩ := Finset.mem_Ico.mp hb + apply hS + have hs := k.parity_start i + have hp' : j % 2 = 1 := hp + change CellPaths.sideBit i ≠ decide (k.a₀ % 2 = a) at hi + change (k.start i + j) % 2 = a + rw [Nat.add_mod, hs, hp'] + cases hbit : CellPaths.sideBit i <;> simp_all <;> omega + intro e he + change e ∈ CellPaths.assemble _ at he + simp only [CellPaths.assemble, Finset.mem_union] at he + rcases he with (he | he) | (he | he) + · exact hh 0 he + · exact hh 2 he + · exact hh 1 he + · exact hh 3 he + +lemma cell_orientation_reachable (chord : Fin 4 → E) + (hc : ∀ i v, inc (chord i) v ↔ + v = (k.side i).vertex 0 ∨ v = (k.side i).vertex (k.side i).length) + (U : Finset E) (hU : ∀ i, c.edgeAt i ∈ U) (b : Bool) : + ∀ e ∈ (k.cellPaths chord hc).orientation b, + (overlayLineGraph inc U).Reachable (c.edgeAt 0) e := by + have hh : ∀ i e, e ∈ (k.cellPaths chord hc).orientationPieces b i → + (overlayLineGraph inc U).Reachable (c.edgeAt 0) e := by + intro i e he + simp only [CellPaths.orientationPieces, CellPaths.pieces] at he + split_ifs at he <;> + obtain ⟨j, _, rfl⟩ := Finset.mem_image.mp he <;> + exact c.edges_reachable U hU (k.start i + j) + intro e he + change e ∈ CellPaths.assemble _ at he + simp only [CellPaths.assemble, Finset.mem_union] at he + rcases he with (he | he) | (he | he) + · exact hh 0 e he + · exact hh 2 e he + · exact hh 1 e he + · exact hh 3 e he + +end Corners + +end IndexedCycle + +end MatchingFPRAS.Transport + +end OAI diff --git a/lean/OAI/Combinatorics/MatchingCount/Graphs/LabelCycle.lean b/lean/OAI/Combinatorics/MatchingCount/Graphs/LabelCycle.lean new file mode 100644 index 0000000000000000000000000000000000000000..4b9fec9df0f5bc673b17aed3c321c790dbfa5de8 --- /dev/null +++ b/lean/OAI/Combinatorics/MatchingCount/Graphs/LabelCycle.lean @@ -0,0 +1,492 @@ +import Mathlib +import OAI.Combinatorics.MatchingCount.Graphs.Sets + +namespace OAI + +namespace MatchingFPRAS.Transport +variable {V E L : Type*} +namespace IndexedCycle + +variable {bags : V → Finset L} + +variable (c : IndexedCycle (BagEdge.Incident (bags := bags))) + +variable {G : SimpleGraph L} + +variable (hbags : ∀ v, ∀ a ∈ bags v, ∀ b ∈ bags v, a = b ∨ G.Adj a b) + +lemma current_color_mem (i : ℤ) : (c.edgeAtZ i).color ∈ bags (c.vertexAtZ i) := + BagEdge.color_mem _ ((c.edgeAtZ_incidence i _).mpr (Or.inl rfl)) + +lemma previous_color_mem (i : ℤ) : (c.edgeAtZ (i-1)).color ∈ bags (c.vertexAtZ i) := by + apply BagEdge.color_mem + apply (c.edgeAtZ_incidence (i-1) _).mpr + right + congr 1 + omega + +def labelCycle : MatchingFPRAS.Cells.CycleData G c.size where + labels i := (c.edgeAtZ i).color + periodic i := by rw [c.edgeAtZ_periodic] + adjacent i := hbags (c.vertexAtZ i) _ (c.previous_color_mem i) _ (c.current_color_mem i) + +variable [DecidableEq L] + +lemma labelCycle_sets_subset (i : ℤ) : (c.labelCycle hbags).sets i ⊆ bags (c.vertexAtZ i) := by + intro l hl + simp only [MatchingFPRAS.Cells.CycleData.sets, labelCycle, + Finset.mem_insert, Finset.mem_singleton] at hl + rcases hl with rfl | rfl + · exact c.previous_color_mem i + · exact c.current_color_mem i + +lemma admissible_common_bag {x y : ℕ} (h : (c.labelCycle hbags).Admissible x y) : + ∃ l, l ∈ bags (c.vertexAt x) ∧ l ∈ bags (c.vertexAt y) := by + obtain ⟨l, hlx, hly⟩ := h + refine ⟨l, ?_, ?_⟩ + · simpa [c.vertexAtZ_nat] using c.labelCycle_sets_subset hbags x hlx + · simpa [c.vertexAtZ_nat] using c.labelCycle_sets_subset hbags y hly + +lemma labelSets_periodic (i : ℤ) : + (c.labelCycle hbags).sets (i+c.size) = (c.labelCycle hbags).sets i := by + have h : i + (c.size : ℤ) - 1 = (i-1) + c.size := by ring + simp only [MatchingFPRAS.Cells.CycleData.sets, labelCycle, h, c.edgeAtZ_periodic] + +lemma edge_color_fixed (i : ℕ) : + (c.edgeAt i).color ∈ (c.labelCycle hbags).sets i ∧ + (c.edgeAt i).color ∈ (c.labelCycle hbags).sets (i+1) := by + have h : (c.edgeAtZ (i : ℤ)).color ∈ (c.labelCycle hbags).sets (i : ℤ) ∧ + (c.edgeAtZ (i : ℤ)).color ∈ (c.labelCycle hbags).sets ((i : ℤ)+1) := by + simp [MatchingFPRAS.Cells.CycleData.sets, labelCycle] + simpa only [c.edgeAtZ_nat] using h + +noncomputable def chord (x y : ℕ) (hxy : x < y) (hy : y < c.size) + (ha : (c.labelCycle hbags).Admissible x y) : BagEdge bags := by + classical + exact if hshort : y = x+1 then c.edgeAt x + else if hwrap : x = 0 ∧ y+1 = c.size then c.edgeAt y + else + let l := ha.choose + BagEdge.ofEndpoints (c.vertexAt x) (c.vertexAt y) + (fun h => by + have := (c.vertexAt_eq_iff (a := 0) (by have := c.four_le; omega) + ⟨by omega, by omega⟩ ⟨by omega, by omega⟩).mp h + omega) l + (by simpa [c.vertexAtZ_nat] using c.labelCycle_sets_subset hbags x ha.choose_spec.1) + (by simpa [c.vertexAtZ_nat] using c.labelCycle_sets_subset hbags y ha.choose_spec.2) + +lemma chord_incidence (x y : ℕ) (hxy : x < y) (hy : y < c.size) + (ha : (c.labelCycle hbags).Admissible x y) (v : V) : + (c.chord hbags x y hxy hy ha).Incident v ↔ v = c.vertexAt x ∨ v = c.vertexAt y := by + classical + dsimp only [chord] + split_ifs with hshort hwrap + · simpa [hshort] using c.edgeAt_incidence x v + · rw [c.edgeAt_incidence] + have he : c.vertexAt (y+1) = c.vertexAt x := by + rw [hwrap.2, hwrap.1] + simpa using c.vertexAt_periodic 0 + rw [he] + tauto + · exact BagEdge.ofEndpoints_incidence _ _ _ _ _ _ _ + +lemma chord_short (x y : ℕ) (hxy : x < y) (hy : y < c.size) + (ha : (c.labelCycle hbags).Admissible x y) (h : y = x+1) : + c.chord hbags x y hxy hy ha = c.edgeAt x := by + simp only [chord, dite_eq_left h] + +lemma chord_wrap (x y : ℕ) (hxy : x < y) (hy : y < c.size) + (ha : (c.labelCycle hbags).Admissible x y) (h : x = 0 ∧ y+1 = c.size) : + c.chord hbags x y hxy hy ha = c.edgeAt y := by + have hn : y ≠ x+1 := by have := c.four_le; omega + simp only [chord, dite_eq_right hn, dite_eq_left h] + +lemma chord_color_fixed (x y : ℕ) (hxy : x < y) (hy : y < c.size) + (ha : (c.labelCycle hbags).Admissible x y) : + (c.chord hbags x y hxy hy ha).color ∈ (c.labelCycle hbags).sets x ∧ + (c.chord hbags x y hxy hy ha).color ∈ (c.labelCycle hbags).sets y := by + classical + dsimp only [chord] + split_ifs with hs hw + · simpa only [hs, Nat.cast_add, Nat.cast_one] using c.edge_color_fixed hbags x + · have hb := c.edge_color_fixed hbags y + refine ⟨?_, hb.1⟩ + have he : (y : ℤ)+1 = (0 : ℤ)+c.size := by omega + rw [he, c.labelSets_periodic hbags] at hb + simpa only [hw.1, Nat.cast_zero] using hb.2 + · exact ha.choose_spec + +def cellCorners {x p q y : ℕ} (hc : (c.labelCycle hbags).Cell x p q y) + (hy : y < c.size) : c.Corners where + a₀ := x + a₁ := p + a₂ := q + a₃ := y + lt₀ := hc.first_pos + lt₁ := hc.middle_pos + lt₂ := hc.third_pos + lt₃ := hy + odd₀ := hc.odd_first + odd₁ := hc.odd_middle + odd₂ := hc.odd_third + odd₃ := by + have he : c.size + x - y = c.size - (y-x) := by have := hc.first_pos; have := hc.middle_pos; have := hc.third_pos; omega + rw [he] + exact hc.odd_exterior + +noncomputable def cellChords {x p q y : ℕ} (hc : (c.labelCycle hbags).Cell x p q y) + (hy : y < c.size) : Fin 4 → BagEdge bags := + ![c.chord hbags x p hc.first_pos (by have := hc.middle_pos; have := hc.third_pos; omega) hc.first, + c.chord hbags p q hc.middle_pos (by have := hc.third_pos; omega) hc.middle, + c.chord hbags q y hc.third_pos hy hc.third, + c.chord hbags x y (by have := hc.first_pos; have := hc.middle_pos; have := hc.third_pos; omega) + hy (by obtain ⟨l, hly, hlx⟩ := hc.exterior; exact ⟨l,hlx,hly⟩)] + +lemma cellChords_incidence {x p q y : ℕ} (hc : (c.labelCycle hbags).Cell x p q y) + (hy : y < c.size) (i : Fin 4) (v : V) : + (c.cellChords hbags hc hy i).Incident v ↔ + v = ((c.cellCorners hbags hc hy).side i).vertex 0 ∨ + v = ((c.cellCorners hbags hc hy).side i).vertex + ((c.cellCorners hbags hc hy).side i).length := by + simp only [Corners.side_first, Corners.side_last] + have hper : c.vertexAt (c.size+x) = c.vertexAt x := by + simpa only [Nat.add_comm] using c.vertexAt_periodic x + fin_cases i <;> simp [cellChords, chord_incidence, cellCorners, Corners.start, + Corners.stop, hper, or_comm] + +noncomputable def pathsOfCell [DecidableEq V] {x p q y : ℕ} (hc : (c.labelCycle hbags).Cell x p q y) + (hy : y < c.size) : CellPaths (BagEdge.Incident (bags := bags)) := + (c.cellCorners hbags hc hy).cellPaths (c.cellChords hbags hc hy) + (c.cellChords_incidence hbags hc hy) + +def sideGood (k : c.Corners) (i : Fin 4) : Prop := + k.length i = 1 ∨ ∃ l, l ∈ (c.labelCycle hbags).sets (k.start i+1) ∧ + l ∈ (c.labelCycle hbags).sets ((k.stop i : ℤ)-1) + +lemma cell_sideGood {x p q y : ℕ} (hc : (c.labelCycle hbags).Cell x p q y) + (hy : y < c.size) (i : Fin 4) : + c.sideGood hbags (c.cellCorners hbags hc hy) i ↔ + ![(c.labelCycle hbags).Good x p, (c.labelCycle hbags).Good p q, + (c.labelCycle hbags).Good q y, (c.labelCycle hbags).ExteriorGood x y] i := by + have hxp := hc.first_pos + have hpq := hc.middle_pos + have hqy := hc.third_pos + have cast_sub (a : ℕ) (ha : 1 ≤ a) : ((a-1 : ℕ) : ℤ) = (a : ℤ)-1 := by omega + have he : ((c.size : ℤ)+(x : ℤ))-1 = ((x : ℤ)-1) + c.size := by ring + fin_cases i <;> simp only [sideGood, cellCorners, Corners.length, Corners.start, + Corners.stop] + · simp [MatchingFPRAS.Cells.CycleData.Good, MatchingFPRAS.Cells.CycleData.Admissible, + cast_sub p (by omega), Nat.cast_add, Nat.cast_one, show p-x=1 ↔ p=x+1 by omega] + · simp [MatchingFPRAS.Cells.CycleData.Good, MatchingFPRAS.Cells.CycleData.Admissible, + cast_sub q (by omega), Nat.cast_add, Nat.cast_one, show q-p=1 ↔ q=p+1 by omega] + · simp [MatchingFPRAS.Cells.CycleData.Good, MatchingFPRAS.Cells.CycleData.Admissible, + cast_sub y (by omega), Nat.cast_add, Nat.cast_one, show y-q=1 ↔ y=q+1 by omega] + · simp [MatchingFPRAS.Cells.CycleData.ExteriorGood, Nat.cast_add, he, + c.labelSets_periodic hbags, show c.size+x-y=1 ↔ y+1=x+c.size by omega] + +noncomputable def leafRepair (k : c.Corners) (i : Fin 4) : BagEdge bags := by + classical + exact if hg : c.sideGood hbags k i ∧ k.length i ≠ 1 then + let hl := hg.1.resolve_left hg.2 + BagEdge.ofEndpoints ((k.side i).vertex 1) ((k.side i).vertex ((k.side i).length-1)) + (by + have hp := (k.side i).positive + have ho := (k.side i).odd + have hn : (k.side i).length ≠ 1 := hg.2 + intro he + have hh := (k.side i).simple ⟨by omega, by omega⟩ ⟨by omega, by omega⟩ he + omega) + hl.choose + (by + have hm := c.labelCycle_sets_subset hbags (k.start i+1) hl.choose_spec.1 + have hv : c.vertexAtZ ((k.start i : ℤ)+1) = (k.side i).vertex 1 := by + simpa only [Corners.side_vertex, Nat.cast_add, Nat.cast_one] using c.vertexAtZ_nat (k.start i+1) + exact (congrArg (fun v => hl.choose ∈ bags v) hv).mp hm) + (by + have hm := c.labelCycle_sets_subset hbags ((k.stop i : ℤ)-1) hl.choose_spec.2 + have hb := k.bounds i + have he : ((k.stop i : ℤ)-1) = ((k.start i + ((k.side i).length-1) : ℕ) : ℤ) := by + rw [Corners.side_length] + dsimp [Corners.length] + omega + have hv : c.vertexAtZ ((k.stop i : ℤ)-1) = (k.side i).vertex ((k.side i).length-1) := by + rw [he, c.vertexAtZ_nat] + rfl + exact (congrArg (fun v => hl.choose ∈ bags v) hv).mp hm) + else c.edgeAt (k.start i) + +lemma leafRepair_incidence (k : c.Corners) (i : Fin 4) + (hg : c.sideGood hbags k i) (hl : k.length i ≠ 1) (v : V) : + (c.leafRepair hbags k i).Incident v ↔ + v = (k.side i).vertex 1 ∨ v = (k.side i).vertex ((k.side i).length-1) := by + simp only [leafRepair, dite_eq_left (And.intro hg hl), BagEdge.ofEndpoints_incidence] + +lemma leafRepair_color_fixed (k : c.Corners) (i : Fin 4) + (hg : c.sideGood hbags k i) (hl : k.length i ≠ 1) : + (c.leafRepair hbags k i).color ∈ (c.labelCycle hbags).sets (k.start i+1) ∧ + (c.leafRepair hbags k i).color ∈ (c.labelCycle hbags).sets ((k.stop i : ℤ)-1) := by + simp only [leafRepair, dite_eq_left (And.intro hg hl), BagEdge.ofEndpoints_color] + exact (hg.resolve_left hl).choose_spec + +lemma cell_has_good_pair {x p q y : ℕ} (hc : (c.labelCycle hbags).Cell x p q y) + (hy : y < c.size) : + ∃ b : Bool, ∀ i : Fin 4, CellPaths.sideBit i ≠ b → + c.sideGood hbags (c.cellCorners hbags hc hy) i := by + rcases hc.some_good with ⟨hf,ht⟩ | ⟨hm,he⟩ + · refine ⟨false, ?_⟩ + intro i hi + rw [c.cell_sideGood hbags hc hy] + fin_cases i <;> simp_all [CellPaths.sideBit] + · refine ⟨true, ?_⟩ + intro i hi + rw [c.cell_sideGood hbags hc hy] + fin_cases i <;> simp_all [CellPaths.sideBit] + +lemma cell_actual_repairs [DecidableEq V] {x p q y : ℕ} (hc : (c.labelCycle hbags).Cell x p q y) + (hy : y < c.size) (b : Bool) + (hg : ∀ i : Fin 4, CellPaths.sideBit i ≠ b → + c.sideGood hbags (c.cellCorners hbags hc hy) i) : + (c.pathsOfCell hbags hc hy).Repairs b + (c.leafRepair hbags (c.cellCorners hbags hc hy)) := by + intro i hi hl v + exact c.leafRepair_incidence hbags _ i (hg i hi) hl v + +lemma cell_long_opposite_good {x p q y : ℕ} (hc : (c.labelCycle hbags).Cell x p q y) + (hy : y < c.size) (b : Bool) + (hl : ∀ i : Fin 4, CellPaths.sideBit i = b → + (c.cellCorners hbags hc hy).length i ≠ 1) : + ∀ i : Fin 4, CellPaths.sideBit i ≠ b → + c.sideGood hbags (c.cellCorners hbags hc hy) i := by + have hxp := hc.first_pos + have hpq := hc.middle_pos + have hqy := hc.third_pos + cases b + · have h₁ := hl 1 (by decide) + have h₃ := hl 3 (by decide) + simp only [Corners.length, Corners.start, Corners.stop, cellCorners] at h₁ h₃ + have hg := hc.middle_exterior_long (by dsimp at h₁; omega) (by dsimp at h₃; omega) + intro i hi + rw [c.cell_sideGood hbags hc hy] + fin_cases i <;> simp_all [CellPaths.sideBit] + · have h₀ := hl 0 (by decide) + have h₂ := hl 2 (by decide) + simp only [Corners.length, Corners.start, Corners.stop, cellCorners] at h₀ h₂ + have hg := hc.outer_long (by dsimp at h₀; omega) (by dsimp at h₂; omega) + intro i hi + rw [c.cell_sideGood hbags hc hy] + fin_cases i <;> simp_all [CellPaths.sideBit] + +lemma cellChords_fixed {x p q y : ℕ} (hc : (c.labelCycle hbags).Cell x p q y) + (hy : y < c.size) (i : Fin 4) : + (c.cellChords hbags hc hy i).color ∈ + (c.labelCycle hbags).sets ((c.cellCorners hbags hc hy).start i) ∧ + (c.cellChords hbags hc hy i).color ∈ + (c.labelCycle hbags).sets ((c.cellCorners hbags hc hy).stop i) := by + fin_cases i + · exact c.chord_color_fixed hbags x p hc.first_pos + (by have := hc.middle_pos; have := hc.third_pos; omega) hc.first + · exact c.chord_color_fixed hbags p q hc.middle_pos + (by have := hc.third_pos; omega) hc.middle + · exact c.chord_color_fixed hbags q y hc.third_pos hy hc.third + · have hb := c.chord_color_fixed hbags x y + (by have := hc.first_pos; have := hc.middle_pos; have := hc.third_pos; omega) hy + (by obtain ⟨l,hly,hlx⟩ := hc.exterior; exact ⟨l,hlx,hly⟩) + change _ ∈ (c.labelCycle hbags).sets y ∧ _ ∈ (c.labelCycle hbags).sets (c.size+x) + rw [add_comm, c.labelSets_periodic hbags] + exact ⟨hb.2,hb.1⟩ + +lemma cellChords_previous_fixed {x p q y : ℕ} (hc : (c.labelCycle hbags).Cell x p q y) + (hy : y < c.size) (i : Fin 4) : + (c.cellChords hbags hc hy (i+1)).color ∈ + (c.labelCycle hbags).sets ((c.cellCorners hbags hc hy).stop i) := by + have h := (c.cellChords_fixed hbags hc hy (i+1)).1 + fin_cases i + · exact h + · exact h + · exact h + · change _ ∈ (c.labelCycle hbags).sets (c.size+x) + rw [add_comm, c.labelSets_periodic hbags] + exact h + +variable (height : L → ℝ) (hheight : ∀ l, 0 < height l) + +variable (hstep : ∀ a b, G.Adj a b → height a ≤ 2 * height b) + +include hheight hstep in +lemma fixed_height_ratio (i : ℤ) {a b : L} + (ha : a ∈ (c.labelCycle hbags).sets i) (hb : b ∈ (c.labelCycle hbags).sets i) : + height a ≤ 2 * height b := by + rcases (c.labelCycle hbags).sets_clique i a ha b hb with rfl | hab + · linarith [hheight a] + · exact hstep a b hab + +include hheight hstep in +lemma cellChords_height_ratio {x p q y : ℕ} (hc : (c.labelCycle hbags).Cell x p q y) + (hy : y < c.size) (i j : Fin 4) : + height (c.cellChords hbags hc hy i).color ≤ 4 * height (c.cellChords hbags hc hy j).color := by + have hn (i : Fin 4) : + height (c.cellChords hbags hc hy i).color ≤ 2 * height (c.cellChords hbags hc hy (i+1)).color ∧ + height (c.cellChords hbags hc hy (i+1)).color ≤ 2 * height (c.cellChords hbags hc hy i).color := by + exact ⟨c.fixed_height_ratio hbags height hheight hstep _ + (c.cellChords_fixed hbags hc hy i).2 (c.cellChords_previous_fixed hbags hc hy i), + c.fixed_height_ratio hbags height hheight hstep _ + (c.cellChords_previous_fixed hbags hc hy i) (c.cellChords_fixed hbags hc hy i).2⟩ + have h₀ := hn 0 + have h₁ := hn 1 + have h₂ := hn 2 + have h₃ := hn 3 + change height (c.cellChords hbags hc hy 0).color ≤ 2 * height (c.cellChords hbags hc hy 1).color ∧ + height (c.cellChords hbags hc hy 1).color ≤ 2 * height (c.cellChords hbags hc hy 0).color at h₀ + change height (c.cellChords hbags hc hy 1).color ≤ 2 * height (c.cellChords hbags hc hy 2).color ∧ + height (c.cellChords hbags hc hy 2).color ≤ 2 * height (c.cellChords hbags hc hy 1).color at h₁ + change height (c.cellChords hbags hc hy 2).color ≤ 2 * height (c.cellChords hbags hc hy 3).color ∧ + height (c.cellChords hbags hc hy 3).color ≤ 2 * height (c.cellChords hbags hc hy 2).color at h₂ + change height (c.cellChords hbags hc hy 3).color ≤ 2 * height (c.cellChords hbags hc hy 0).color ∧ + height (c.cellChords hbags hc hy 0).color ≤ 2 * height (c.cellChords hbags hc hy 3).color at h₃ + have hp₀ := hheight (c.cellChords hbags hc hy 0).color + have hp₁ := hheight (c.cellChords hbags hc hy 1).color + have hp₂ := hheight (c.cellChords hbags hc hy 2).color + have hp₃ := hheight (c.cellChords hbags hc hy 3).color + rcases h₀ with ⟨h₀,h₀'⟩ + rcases h₁ with ⟨h₁,h₁'⟩ + rcases h₂ with ⟨h₂,h₂'⟩ + rcases h₃ with ⟨h₃,h₃'⟩ + have hi : i = 0 ∨ i = 1 ∨ i = 2 ∨ i = 3 := by omega + have hj : j = 0 ∨ j = 1 ∨ j = 2 ∨ j = 3 := by omega + rcases hi with rfl | rfl | rfl | rfl <;> + rcases hj with rfl | rfl | rfl | rfl <;> linarith + +def LocalEdge {x p q y : ℕ} (hc : (c.labelCycle hbags).Cell x p q y) + (hy : y < c.size) (e : BagEdge bags) : Prop := + ∃ i : Fin 4, e = c.cellChords hbags hc hy i ∨ + e = ((c.cellCorners hbags hc hy).side i).edge 0 ∨ + e = ((c.cellCorners hbags hc hy).side i).edge + (((c.cellCorners hbags hc hy).side i).length-1) ∨ + (c.sideGood hbags (c.cellCorners hbags hc hy) i ∧ + (c.cellCorners hbags hc hy).length i ≠ 1 ∧ + e = c.leafRepair hbags (c.cellCorners hbags hc hy) i) + +lemma side_boundaries_fixed (k : c.Corners) (i : Fin 4) : + ((k.side i).edge 0).color ∈ (c.labelCycle hbags).sets (k.start i) ∧ + ((k.side i).edge 0).color ∈ (c.labelCycle hbags).sets (k.start i+1) ∧ + ((k.side i).edge ((k.side i).length-1)).color ∈ (c.labelCycle hbags).sets ((k.stop i : ℤ)-1) ∧ + ((k.side i).edge ((k.side i).length-1)).color ∈ (c.labelCycle hbags).sets (k.stop i) := by + have hb := k.bounds i + have he : k.start i + (k.length i-1) = k.stop i-1 := by dsimp [Corners.length]; omega + change (c.edgeAt (k.start i+0)).color ∈ _ ∧ (c.edgeAt (k.start i+0)).color ∈ _ ∧ + (c.edgeAt (k.start i + (k.length i-1))).color ∈ _ ∧ + (c.edgeAt (k.start i + (k.length i-1))).color ∈ _ + rw [Nat.add_zero, he] + have hs := c.edge_color_fixed hbags (k.start i) + have ht := c.edge_color_fixed hbags (k.stop i-1) + have hcast : ((k.stop i-1 : ℕ) : ℤ) = (k.stop i : ℤ)-1 := by omega + have hcast' : ((k.stop i-1 : ℕ) : ℤ)+1 = (k.stop i : ℤ) := by omega + exact ⟨hs.1, hs.2, by simpa only [hcast] using ht.1, by simpa only [hcast'] using ht.2⟩ + +include hheight hstep in +lemma localEdge_height_ratio {x p q y : ℕ} (hc : (c.labelCycle hbags).Cell x p q y) + (hy : y < c.size) {e : BagEdge bags} (he : c.LocalEdge hbags hc hy e) : + ∃ i : Fin 4, + height e.color ≤ 4 * height (c.cellChords hbags hc hy i).color ∧ + height (c.cellChords hbags hc hy i).color ≤ 4 * height e.color := by + obtain ⟨i,he⟩ := he + refine ⟨i,?_⟩ + have hh := hheight e.color + have hch := hheight (c.cellChords hbags hc hy i).color + have hbc := c.side_boundaries_fixed hbags (c.cellCorners hbags hc hy) i + have hc' := c.cellChords_fixed hbags hc hy i + rcases he with rfl | rfl | rfl | ⟨hg,hl,rfl⟩ + · constructor <;> linarith + · have h₁ := c.fixed_height_ratio hbags height hheight hstep _ hbc.1 hc'.1 + have h₂ := c.fixed_height_ratio hbags height hheight hstep _ hc'.1 hbc.1 + constructor <;> linarith + · have h₁ := c.fixed_height_ratio hbags height hheight hstep _ hbc.2.2.2 hc'.2 + have h₂ := c.fixed_height_ratio hbags height hheight hstep _ hc'.2 hbc.2.2.2 + constructor <;> linarith + · have hrc := c.leafRepair_color_fixed hbags _ i hg hl + have h₁ := c.fixed_height_ratio hbags height hheight hstep _ hrc.1 hbc.2.1 + have h₂ := c.fixed_height_ratio hbags height hheight hstep _ hbc.2.1 hrc.1 + have h₃ := c.fixed_height_ratio hbags height hheight hstep _ hbc.1 hc'.1 + have h₄ := c.fixed_height_ratio hbags height hheight hstep _ hc'.1 hbc.1 + constructor <;> linarith + +include hheight hstep in + +theorem cell_comparability {x p q y : ℕ} (hc : (c.labelCycle hbags).Cell x p q y) + (hy : y < c.size) (D : ℝ) (hD : 1 ≤ D) (w : BagEdge bags → ℝ) + (hw : ∀ e, height e.color / D ≤ w e ∧ w e ≤ 3 * height e.color) + {e f : BagEdge bags} (he : c.LocalEdge hbags hc hy e) (hf : c.LocalEdge hbags hc hy f) : + w e ≤ (1000 * D) * w f := by + obtain ⟨i,hei,hie⟩ := c.localEdge_height_ratio hbags height hheight hstep hc hy he + obtain ⟨j,hfj,hjf⟩ := c.localEdge_height_ratio hbags height hheight hstep hc hy hf + have hij := c.cellChords_height_ratio hbags height hheight hstep hc hy i j + have hh : height e.color ≤ 64 * height f.color := by linarith + have hDpos : 0 < D := by linarith + have hfpos : 0 < w f := lt_of_lt_of_le (div_pos (hheight f.color) hDpos) (hw f).1 + have hlo : height f.color ≤ w f * D := (div_le_iff₀ hDpos).mp (hw f).1 + have h192 : w e ≤ 192 * D * w f := by nlinarith [(hw e).2] + nlinarith [mul_pos hDpos hfpos] + +lemma common_clamp_ratio {lo hi A x y : ℝ} (hlo : 0 ≤ lo) (hA : 1 ≤ A) + (hxy : x ≤ A * y) : + max lo (min hi x) ≤ A * max lo (min hi y) := by + have hnonneg : 0 ≤ max lo (min hi y) := le_trans hlo (le_max_left _ _) + have hupper : max lo (min hi y) ≤ A * max lo (min hi y) := by nlinarith + apply max_le + · exact le_trans (le_max_left _ _) hupper + · by_cases hy : y ≤ hi + · have hm : y ≤ max lo (min hi y) := by rw [min_eq_right hy]; exact le_max_right _ _ + exact le_trans (min_le_right _ _) (le_trans hxy (mul_le_mul_of_nonneg_left hm (by linarith))) + · have hm : hi ≤ max lo (min hi y) := by rw [min_eq_left (le_of_not_ge hy)]; exact le_max_right _ _ + exact le_trans (min_le_left _ _) (le_trans hm hupper) + +include hheight hstep in +lemma cell_clamp_comparability {x p q y : ℕ} (hc : (c.labelCycle hbags).Cell x p q y) + (hy : y < c.size) (D : ℝ) (hD : 1 ≤ D) (w : BagEdge bags → ℝ) + (hw : ∀ e, height e.color / D ≤ w e ∧ w e ≤ 3 * height e.color) + (lo hi : ℝ) (hlo : 0 ≤ lo) + {e f : BagEdge bags} (he : c.LocalEdge hbags hc hy e) (hf : c.LocalEdge hbags hc hy f) : + max lo (min hi (w e)) ≤ (1000 * D) * max lo (min hi (w f)) := + common_clamp_ratio hlo (by linarith) (c.cell_comparability hbags height hheight hstep hc hy D hD w hw he hf) + +lemma drops_local [DecidableEq V] {x p q y : ℕ} (hc : (c.labelCycle hbags).Cell x p q y) + (hy : y < c.size) (r : Bool) {e : BagEdge bags} + (he : e ∈ (c.pathsOfCell hbags hc hy).drops r) : c.LocalEdge hbags hc hy e := by + obtain ⟨i, _, hi⟩ := Multiset.mem_sum.mp he + by_cases h : CellPaths.sideBit i = r + · simp only [ite_eq_left h, Multiset.notMem_zero] at hi + · simp only [ite_eq_right h, Finset.mem_val] at hi + refine ⟨i, Or.inr ?_⟩ + change e ∈ ((c.cellCorners hbags hc hy).side i).boundary at hi + by_cases hl : ((c.cellCorners hbags hc hy).side i).length = 1 + · simp only [OddPath.boundary, ite_eq_left hl, Finset.mem_singleton] at hi + exact Or.inl hi + · simp only [OddPath.boundary, ite_eq_right hl, Finset.mem_insert, Finset.mem_singleton] at hi + exact hi.imp_right Or.inl + +lemma additions_local [DecidableEq V] {x p q y : ℕ} (hc : (c.labelCycle hbags).Cell x p q y) + (hy : y < c.size) (b r : Bool) + (hg : ∀ i, CellPaths.sideBit i ≠ r → c.sideGood hbags (c.cellCorners hbags hc hy) i) + {e : BagEdge bags} (he : e ∈ (c.pathsOfCell hbags hc hy).additions b r + (c.leafRepair hbags (c.cellCorners hbags hc hy))) : c.LocalEdge hbags hc hy e := by + rcases Multiset.mem_add.mp he with he | he + · obtain ⟨i, _, hi⟩ := Multiset.mem_sum.mp he + by_cases h : CellPaths.sideBit i = b + · simp only [ite_eq_left h, Multiset.mem_singleton] at hi + exact ⟨i, Or.inl hi⟩ + · simp only [ite_eq_right h, Multiset.notMem_zero] at hi + · obtain ⟨i, _, hi⟩ := Multiset.mem_sum.mp he + by_cases h : CellPaths.sideBit i = r + · simp only [ite_eq_left h, Multiset.notMem_zero] at hi + · simp only [ite_eq_right h] at hi + change e ∈ ((c.cellCorners hbags hc hy).side i).repairAdded (c.leafRepair hbags (c.cellCorners hbags hc hy) i) at hi + by_cases hl : ((c.cellCorners hbags hc hy).side i).length = 1 + · simp only [OddPath.repairAdded, ite_eq_left hl, Multiset.notMem_zero] at hi + · simp only [OddPath.repairAdded, ite_eq_right hl, Multiset.mem_singleton] at hi + exact ⟨i, Or.inr (Or.inr (Or.inr ⟨hg i h, hl, hi⟩))⟩ + +end IndexedCycle + +end MatchingFPRAS.Transport + +end OAI diff --git a/lean/OAI/Combinatorics/MatchingCount/Graphs/LabelOrder.lean b/lean/OAI/Combinatorics/MatchingCount/Graphs/LabelOrder.lean new file mode 100644 index 0000000000000000000000000000000000000000..763d76284012ddf36482a3ce9f3bfd0d8d4f82c3 --- /dev/null +++ b/lean/OAI/Combinatorics/MatchingCount/Graphs/LabelOrder.lean @@ -0,0 +1,494 @@ +import Mathlib +import OAI.Combinatorics.MatchingCount.Graphs.Related2 + +namespace OAI + +namespace MatchingFPRAS.NumberedHierarchy + +open Finset MatchingFPRAS.UnitRefresh + +variable {V : Type*} [Fintype V] [LinearOrder V] + +variable (B : V → V → ℚ) (hsym : ∀ x y,B x y=B y x) + +variable (htri : ∀ x y z,x≠y → x≠z → y≠z → min (B x z) (B z y)≤B x y) + +@[instance_reducible] def labelOrder (H : ℕ) : LinearOrder (Label B H) := + LinearOrder.lift' (fun l : Label B H=>toLex (l.1,l.2.val)) (by + intro a b h + have h' := toLex.injective h + obtain ⟨k,a⟩:=a + obtain ⟨j,b⟩:=b + have hk : k=j:=congrArg Prod.fst h' + cases hk + exact congrArg (Sigma.mk k) (Subtype.ext (congrArg Prod.snd h'))) + +attribute [local instance] labelOrder + +noncomputable def abstractTree (H : ℕ) : SimpleGraph (Label B H) := + (Hierarchy.tree (fun x y=>(B x y:ℝ)) (symmetric B hsym) (triangular B htri)).comap + (labelEquiv B hsym htri H).symm + +lemma abstractTree_acyclic (H : ℕ) : (abstractTree B hsym htri H).IsAcyclic := by + exact SimpleGraph.IsAcyclic.of_comap (labelEquiv B hsym htri H).symm.toEmbedding + (Hierarchy.tree_acyclic _ _ _ _) + +lemma abstractTree_adj (H : ℕ) (a b : Label B H) : + (abstractTree B hsym htri H).Adj a b ↔ + parent B hsym htri b=some a ∨ parent B hsym htri a=some b := by + change (Hierarchy.Parent _ _ _ ((labelEquiv B hsym htri H).symm a) ((labelEquiv B hsym htri H).symm b) ∨ + Hierarchy.Parent _ _ _ ((labelEquiv B hsym htri H).symm b) ((labelEquiv B hsym htri H).symm a)) ↔ _ + have ha:=parent_equiv_iff B hsym htri ((labelEquiv B hsym htri H).symm b) ((labelEquiv B hsym htri H).symm a) + have hb:=parent_equiv_iff B hsym htri ((labelEquiv B hsym htri H).symm a) ((labelEquiv B hsym htri H).symm b) + simpa only [Equiv.apply_symm_apply] using or_congr ha.symm hb.symm + +def tree (H : ℕ) : SimpleGraph (Label B H) where + Adj a b := parent B hsym htri b=some a ∨ parent B hsym htri a=some b + symm := ⟨fun _ _ h=>Or.symm h⟩ + loopless := ⟨by intro a h; rcases h with h|h <;> exact (Nat.lt_irrefl _ (parent_rank B hsym htri h))⟩ + +instance treeDec (H : ℕ) : DecidableRel (tree B hsym htri H).Adj := by + intro a b + exact inferInstanceAs (Decidable (parent B hsym htri b=some a ∨ parent B hsym htri a=some b)) + +lemma tree_adj (H : ℕ) (a b : Label B H) : + (tree B hsym htri H).Adj a b ↔ + parent B hsym htri b=some a ∨ parent B hsym htri a=some b := Iff.rfl + +lemma tree_eq (H : ℕ) : tree B hsym htri H=abstractTree B hsym htri H := by + ext a b + exact (abstractTree_adj B hsym htri H a b).symm + +lemma tree_acyclic (H : ℕ) : (tree B hsym htri H).IsAcyclic := by + rw [tree_eq] + exact abstractTree_acyclic B hsym htri H + +variable {E : Type*} [Fintype E] [DecidableEq E] (left right : E → V) + +lemma bags_nonempty (H : ℕ) (hx : ∀ x,∃ e,x=left e ∨ x=right e) (x : V) : + (bags B hsym htri left right H x).Nonempty := by + obtain ⟨e,he⟩:=hx x + exact ⟨_,(mem_bags _ _ _ _ _ _ _ _).mpr ⟨e,he,rfl⟩⟩ + +lemma bags_adjacent (H : ℕ) (hfloor : ∀ x y,1≤B x y) + (hmax : ∀ e,B (left e) (right e)<(2:ℚ)^(H+1)) + (hnear : ∀ x e f,Hierarchy.Incident left right e x → Hierarchy.Incident left right f x → + B (left e) (right e)≤2*B (left f) (right f)) : + ∀ x a,a∈bags B hsym htri left right H x → ∀ b∈bags B hsym htri left right H x, + a=b ∨ (tree B hsym htri H).Adj a b := by + intro x a ha b hb + rw [←bags_equiv] at ha hb + obtain ⟨a',ha',rfl⟩:=mem_image.mp ha + obtain ⟨b',hb',rfl⟩:=mem_image.mp hb + have hf : ∀ x y,1≤(B x y:ℝ) := by intro x y; exact_mod_cast hfloor x y + have hm : ∀ e,(B (left e) (right e):ℝ)<(2:ℝ)^(H+1) := by + intro e; exact_mod_cast hmax e + have hn : ∀ x e f,Hierarchy.Incident left right e x → Hierarchy.Incident left right f x → + (B (left e) (right e):ℝ)≤2*(B (left f) (right f):ℝ) := by + intro x e f he hf; exact_mod_cast hnear x e f he hf + have h:=Hierarchy.memberships_tree_bags (fun x y=>(B x y:ℝ)) (symmetric B hsym) + (triangular B htri) hf left right H hm hn x a' b' ha' hb' + rcases h with h|h + · exact Or.inl (congrArg _ h) + · exact Or.inr (by simpa only [tree_eq,abstractTree,SimpleGraph.comap_adj,Equiv.symm_apply_apply] using h) + +lemma bags_ranked (H : ℕ) (hfloor : ∀ x y,1≤B x y) + (hmax : ∀ e,B (left e) (right e)<(2:ℚ)^(H+1)) + (hnear : ∀ x e f,Hierarchy.Incident left right e x → Hierarchy.Incident left right f x → + B (left e) (right e)≤2*B (left f) (right f)) : + RankedBags (bags B hsym htri left right H) (fun l=>l.1.val) (parent B hsym htri) := by + intro x a ha b hb hab + rcases bags_adjacent B hsym htri left right H hfloor hmax hnear x a ha b hb with h|h + · exact (hab h).elim + · rcases (tree_adj B hsym htri H a b).mp h with h|h + · exact Or.inl ⟨parent_rank B hsym htri h,h⟩ + · exact Or.inr ⟨parent_rank B hsym htri h,h⟩ + +omit [Fintype E] [DecidableEq E] in +lemma height_step (H : ℕ) (a b : Label B H) (h : (tree B hsym htri H).Adj a b) : + (2:ℝ)^a.1.val ≤ 2*(2:ℝ)^b.1.val := by + rcases (tree_adj B hsym htri H a b).mp h with h|h + · have hh:=((parent_iff B hsym htri b a).mp h).1 + rw [←hh,pow_succ] + have hp : 0≤(2:ℝ)^a.1.val := by positivity + nlinarith + · have hh:=((parent_iff B hsym htri a b).mp h).1 + rw [←hh,pow_succ] + ring_nf + exact le_rfl + +end MatchingFPRAS.NumberedHierarchy + +namespace MatchingFPRAS.RationalSource + +open Finset MatchingFPRAS.Switching MatchingFPRAS.Subdivision MatchingFPRAS.RealGeometry +open MatchingFPRAS.Hierarchy MatchingFPRAS.Transport MatchingFPRAS.Enlargement + +variable {V : Type*} [Fintype V] [LinearOrder V] [Nontrivial V] + +attribute [local instance] NumberedHierarchy.labelOrder sym2Order bagEdgeOrder bagEdgeFintype + +attribute [local instance] UnitRefresh.Computable.allowedDec + +def parent (w : V → V → ℚ) (K : ℕ) : Label w K → Option (Label w K) := + NumberedHierarchy.parent (realB w K) (realB_symm w K) (realB_tri w K) + +def tree (w : V → V → ℚ) (K : ℕ) : SimpleGraph (Label w K) := + NumberedHierarchy.tree (realB w K) (realB_symm w K) (realB_tri w K) (levels w K) + +lemma tree_acyclic (w : V → V → ℚ) (K : ℕ) : (tree w K).IsAcyclic := + NumberedHierarchy.tree_acyclic _ _ _ _ + +lemma parent_rank (w : V → V → ℚ) (K : ℕ) (l p : Label w K) + (h : parent w K l=some p) : p.1.val(w x y:ℝ)) x y≤(4:ℝ)^K := by + intro x y hxy + have he : ((BottleneckAlgorithm.edge w x y:ℚ):ℝ)=edgeActivity (fun x y=>(w x y:ℝ)) x y := by + unfold BottleneckAlgorithm.edge edgeActivity + split_ifs <;> rfl + simpa only [he,Rat.cast_pow,Rat.cast_ofNat] using (Rat.cast_le (K:=ℝ)).mpr (h x y hxy) + +lemma realB_floor (w : V → V → ℚ) (K : ℕ) (x y : SourceVertex V K) : 1≤realB w K x y := by + apply (Rat.cast_le (K:=ℝ)).mp + simpa only [Rat.cast_one,realB_cast] using sourceRealB_floor (fun x y=>(w x y:ℝ)) K x y + +lemma realB_upper (w : V → V → ℚ) (K : ℕ) + (h : ∀ x y,x≠y → BottleneckAlgorithm.edge w x y≤(4:ℚ)^K) (e : SourceRealEdge V K) : + realB w K (realLeft K e) (realRight K e)<(2:ℚ)^(levels w K+1) := by + apply (Rat.cast_lt (K:=ℝ)).mp + simpa only [realB_cast,levels_eq,Rat.cast_pow,Rat.cast_ofNat] using + (source_strength_le_max (fun x y=>(w x y:ℝ)) K (raw_cast w K h) e).trans_lt + (maxSourceHeight_lt (fun x y=>(w x y:ℝ)) K (raw_cast w K h)) + +lemma realB_near (w : V → V → ℚ) (K : ℕ) + (h : ∀ x y,x≠y → BottleneckAlgorithm.edge w x y≤(4:ℚ)^K) + (x : SourceVertex V K) (e f : SourceRealEdge V K) + (he : Hierarchy.Incident (realLeft K) (realRight K) e x) + (hf : Hierarchy.Incident (realLeft K) (realRight K) f x) : + realB w K (realLeft K e) (realRight K e)≤2*realB w K (realLeft K f) (realRight K f) := by + apply (Rat.cast_le (K:=ℝ)).mp + simpa only [realB_cast,Rat.cast_mul,Rat.cast_ofNat] using + source_strength_incident_near (fun x y=>(w x y:ℝ)) K (raw_cast w K h) x e f he hf + +lemma bags_adjacent (w : V → V → ℚ) (K : ℕ) + (h : ∀ x y,x≠y → BottleneckAlgorithm.edge w x y≤(4:ℚ)^K) : + ∀ x a,a∈bags w K x → ∀ b∈bags w K x,a=b ∨ (tree w K).Adj a b := + NumberedHierarchy.bags_adjacent _ _ _ _ _ _ (realB_floor w K) (realB_upper w K h) (realB_near w K h) + +lemma bags_ranked (w : V → V → ℚ) (K : ℕ) + (h : ∀ x y,x≠y → BottleneckAlgorithm.edge w x y≤(4:ℚ)^K) : + UnitRefresh.RankedBags (bags w K) (fun l=>l.1.val) (parent w K) := + NumberedHierarchy.bags_ranked _ _ _ _ _ _ (realB_floor w K) (realB_upper w K h) (realB_near w K h) + +omit [Fintype V] in +lemma incident_exists [Fintype V] (K : ℕ) (x : SourceVertex V K) : + ∃ e,Hierarchy.Incident (realLeft K) (realRight K) e x := by + cases x with + | inl x => + obtain ⟨y,hy⟩ := exists_ne x + rcases lt_or_gt_of_ne hy with h | h + · let e : LogicalEdge V := ⟨(y,x),h⟩ + refine ⟨(e,Fin.last (4*(2*K+2))),Or.inr ?_⟩ + simp [realRight,atVertex_last,target,e] + · let e : LogicalEdge V := ⟨(x,y),h⟩ + refine ⟨(e,0),Or.inl ?_⟩ + simp [realLeft,atVertex_zero,source,e] + | inr q => + obtain ⟨e,i⟩ := q + refine ⟨(e,i.castSucc),Or.inr ?_⟩ + change Sum.inr (e,i)=atVertex source target _ e i.castSucc.succ + have he : i.castSucc.succ=i.succ.castSucc := Fin.ext rfl + rw [he,atVertex_internal] + +lemma bags_nonempty (w : V → V → ℚ) (K : ℕ) (x : SourceVertex V K) : + (bags w K x).Nonempty := + NumberedHierarchy.bags_nonempty _ _ _ _ _ _ (incident_exists K) x + +def realLabel (w : V → V → ℚ) (K : ℕ) (e : SourceRealEdge V K) : Label w K := + NumberedHierarchy.edgeLabel (realB w K) (realB_symm w K) (realB_tri w K) + (realLeft K) (realRight K) (levels w K) e + +omit [Nontrivial V] in +lemma real_not_diag [Nontrivial V] (K : ℕ) (e : SourceRealEdge V K) : + ¬(edge source target (4*(2*K+2)) e.1 e.2).IsDiag := by + rw [edge,Sym2.mk_isDiag_iff] + intro he + have hi := atVertex_injective source target (4*(2*K+2)) e.1 (source_ne_target e.1) he + have := congrArg Fin.val hi + simp at this + +def coloredReal (w : V → V → ℚ) (K : ℕ) (e : SourceRealEdge V K) : BagEdge (bags w K) := + ⟨⟨(edge source target (4*(2*K+2)) e.1 e.2,realLabel w K e),real_not_diag K e⟩,by + intro x hx + apply (NumberedHierarchy.mem_bags _ _ _ (realLeft K) (realRight K) (levels w K) x _).mpr + refine ⟨e,?_,rfl⟩ + simpa [ColoredEdge.Incident,realLeft,realRight,edge] using hx⟩ + +lemma coloredReal_injective (w : V → V → ℚ) (K : ℕ) : Function.Injective (coloredReal w K) := by + intro e f h + apply edge_injective source target (4*(2*K+2)) (by omega) + exact congrArg (fun q : BagEdge (bags w K)=>q.val.val.1) h + +def realPortion (w : V → V → ℚ) (K : ℕ) (e : BagEdge (bags w K)) : ℚ := + ∑ q : SourceRealEdge V K,if coloredReal w K q=e then pathActivity w K q.1 q.2 else 0 + +lemma realPortion_on (w : V → V → ℚ) (K : ℕ) (q : SourceRealEdge V K) : + realPortion w K (coloredReal w K q)=pathActivity w K q.1 q.2 := by + simp only [realPortion,(coloredReal_injective w K).eq_iff,sum_ite_eq',mem_univ,ite_true] + +lemma realPortion_off (w : V → V → ℚ) (K : ℕ) (e : BagEdge (bags w K)) + (he : ¬∃ q,coloredReal w K q=e) : realPortion w K e=0 := by + apply sum_eq_zero + intro q _ + exact ite_eq_right (fun h=>he ⟨q,h⟩) + +lemma pathActivity_pos (w : V → V → ℚ) (hw : ∀ x y,0 exact hw _ _ + · exact hb.trans_le (le_max_left _ _) + +lemma pathActivity_le_realB (w : V → V → ℚ) (K : ℕ) (e : SourceRealEdge V K) : + pathActivity w K e.1 e.2≤realB w K (realLeft K e) (realRight K e) := by + apply (Rat.cast_le (K:=ℝ)).mp + rw [pathActivity_cast,realB_cast] + exact edge_activity_le_realBottleneck source target source_ne_target (2*K+2) (by omega) _ _ _ _ e.1 e.2 + +def bagHeight (w : V → V → ℚ) (K : ℕ) (l : Label w K) : ℚ := 2^l.1.val + +lemma realPortion_nonneg (w : V → V → ℚ) (hw : ∀ x y,0 exact_mod_cast (by assumption) + +lemma bagHeight_one (w : V → V → ℚ) (K : ℕ) (l : Label w K) : 1≤bagHeight w K l := by + exact one_le_pow₀ (by norm_num) + +lemma bagHeight_le (w : V → V → ℚ) (K : ℕ) (l : Label w K) : bagHeight w K l≤(4:ℚ)^K := by + have hl : l.1.val≤2*K := (Nat.le_of_lt_succ l.1.isLt).trans (by rw [levels_eq]; exact sourceLevels_le _ _) + calc + _ ≤ (2:ℚ)^(2*K) := pow_le_pow_right₀ (by norm_num) hl + _ = _ := by rw [pow_mul]; norm_num + +lemma bagHeight_step (w : V → V → ℚ) (K : ℕ) (a b : Label w K) (h : (tree w K).Adj a b) : + (bagHeight w K a:ℝ)≤2*(bagHeight w K b:ℝ) := by + simpa only [bagHeight,Rat.cast_pow,Rat.cast_ofNat] using + NumberedHierarchy.height_step (realB w K) (realB_symm w K) (realB_tri w K) (levels w K) a b h + +lemma bagWeight_global (w : V → V → ℚ) (hw : ∀ x y,0l.1.val) (parent w K) + (bags_ranked w K h) (bags_nonempty w K) (parent_rank w K) D K T m hq (bagWeight w K D) M η s + +noncomputable local instance (w : V → V → ℚ) (K : ℕ) : Fintype (BagPM (bags w K)) := Fintype.ofFinite _ + +theorem sampler_tv (w : V → V → ℚ) (hw : ∀ x y,0(bagWeight w K D e:ℝ)) T (ladderQ (Fintype.card (SourceVertex V K)) D))≤ + (η:ℝ)+(m:ℝ)⁻¹ := by + apply finiteLadder_tv (bags_adjacent w K h) (tree_acyclic w K) (fun l=>l.1.val) (parent w K) + (bags_ranked w K h) (bags_nonempty w K) (parent_rank w K) (fun l=>(bagHeight w K l:ℝ)) + (fun l=>by have hh : (1:ℝ)≤(bagHeight w K l:ℝ) := by exact_mod_cast bagHeight_one w K l + linarith) + (bagHeight_step w K) D K hD hN (bagWeight w K D) (bagWeight_range w hw K D hD h) + (bagWeight_global w hw K D hD h) M T m hm η hη hq s + +end MatchingFPRAS.RationalSource + +namespace MatchingFPRAS.Transport + +open Finset MatchingFPRAS.Replica MatchingFPRAS.Replica.Ladder + +variable {V J : Type*} [Fintype V] [DecidableEq V] [Fintype J] [DecidableEq J] + +variable {bags : V → Finset J} + +noncomputable local instance : Fintype (BagEdge bags) := Fintype.ofFinite _ + +noncomputable local instance : DecidableEq (PM (BagEdge.Incident (bags := bags))) := Classical.decEq _ + +omit [DecidableEq V] in +lemma gibbs_instances [DecidableEq V] {E : Type*} (F₁ F₂ : Fintype E) (inc : E → V → Prop) + (w : E → ℝ) : @gibbs V E _ inc F₁ w = @gibbs V E _ inc F₂ w := by + cases Subsingleton.elim F₁ F₂ + rfl + +omit [DecidableEq J] in +lemma slotLaw_of_weight [DecidableEq J] {T q : ℕ} (F : Fintype (BagEdge bags)) + (w : BagEdge bags → ℝ) (i : Slot T q) + (he : slotWeight w i=w) : slotLaw w i=@gibbs V (BagEdge bags) _ BagEdge.Incident F w := by + change @gibbs V (BagEdge bags) _ BagEdge.Incident (instFintypeBagEdge_5 (bags:=bags)) + (slotWeight w i)=_ + rw [he] + exact gibbs_instances _ _ _ _ + +lemma top_marginal_tv {A : Type*} [Fintype A] {T q : ℕ} (F : Fintype (BagEdge bags)) + (hq : 0f a (topSlot T q hq))) + (@gibbs V (BagEdge bags) _ BagEdge.Incident F w)≤ + Variation.tv (Variation.imageLaw f) (ladderLaw w T q) := by + have ht:=Variation.push_contraction (Variation.imageLaw f) (ladderLaw w T q) + (fun x=>x (topSlot T q hq)) + rw [ladder_top_marginal w T q hq M,slotLaw_of_weight F _ _ he] at ht + change Variation.tv (Variation.imageLaw ((fun x=>x (topSlot T q hq)) ∘ f)) _≤_ + rw [Variation.imageLaw_comp] + exact ht + + + +open Finset Replica Replica.Ladder Variation + +def rationalBase (N : ℕ) : ℚ := 1+((N:ℚ)^2)⁻¹ + +lemma rationalBase_cast (N : ℕ) : (rationalBase N:ℝ)=1+((N:ℝ)^2)⁻¹ := by + simp [rationalBase] + +private lemma reaches_cast (N D K t : ℕ) : + max (D:ℚ) (3*4^K)≤(rationalBase N)^t ↔ + max (D:ℝ) (3*4^K)≤(1+((N:ℝ)^2)⁻¹)^t := by + rw [←rationalBase_cast] + exact_mod_cast (Iff.rfl : max (D:ℚ) (3*4^K)≤(rationalBase N)^t ↔ _) + +def endpoint (N D K : ℕ) (hN : 0 max (D:ℚ) (3*4^K)≤(rationalBase N)^t)).min' + (by refine ⟨tierBound N D K,mem_filter.mpr ⟨mem_range.mpr (by omega),?_⟩⟩ + exact (reaches_cast _ _ _ _).mpr (tierBound_reaches N D K hN)) + +lemma endpoint_eq (N D K : ℕ) (hN : 0 max (D:ℚ) (3*4^K)≤(rationalBase N)^t)) _)).2 + unfold ladderTier + exact Nat.find_min' _ he + +lemma endpoint_reaches (N D K : ℕ) (hN : 0 sampler w K D (endpoint (Fintype.card (SourceVertex V K)) D K hN) m h hq M η + (fun _=>M) bits (topSlot _ _ hq) + +theorem topSampler_tv (w : V → V → ℚ) (hw : ∀ x y,0(bagWeight w K D e:ℝ)))≤(η:ℝ)+(m:ℝ)⁻¹ := by + let T:=endpoint (Fintype.card (SourceVertex V K)) D K (by omega) + have hs:=sampler_tv w hw K D T m hD hN hm h hq M η hη (fun _=>M) + have he:=slotWeight_top (fun e=>(bagWeight w K D e:ℝ)) D K T _ (by omega) hq + (bagWeight_global w hw K D hD h) (endpoint_reaches _ _ _ (by omega)) + exact (top_marginal_tv (bagEdgeFintype (bags:=bags w K)) hq (fun e=>(bagWeight w K D e:ℝ)) M + (sampler w K D T m h hq M η (fun _=>M)) he).trans hs + +end MatchingFPRAS.RationalSource + +end OAI diff --git a/lean/OAI/Combinatorics/MatchingCount/Graphs/Marked.lean b/lean/OAI/Combinatorics/MatchingCount/Graphs/Marked.lean new file mode 100644 index 0000000000000000000000000000000000000000..c7a60003c54660f740aa2b006699b0fa98ad79d6 --- /dev/null +++ b/lean/OAI/Combinatorics/MatchingCount/Graphs/Marked.lean @@ -0,0 +1,514 @@ +import Mathlib +import OAI.Combinatorics.MatchingCount.Graphs.PM + +namespace OAI + +namespace MatchingFPRAS.Marking + +open Finset MatchingFPRAS.Transport + +variable {V E I : Type*} [Fintype V] [Fintype E] [Fintype I] + +variable [DecidableEq V] [DecidableEq E] [DecidableEq I] + +variable (inc : E → V → Prop) + +abbrev Marked := Σ M : Matchings inc univ, (↥M.val → I) + +noncomputable def mass (part : E → I → ℝ) (a : Marked (I:=I) inc) : ℝ := + ∏ e : a.1.val, part e.val (a.2 e) + +def collapse (part : E → I → ℝ) (e : E) : ℝ := ∑ i,part e i + +omit [Fintype E] [DecidableEq V] [DecidableEq I] in +lemma sum_marks (part : E → I → ℝ) (M : Matchings inc univ) : + (∑ m : (↥M.val → I),mass inc part ⟨M,m⟩)=∏ e ∈ M.val,collapse part e := by + classical + rw [Finset.prod_subtype M.val (fun _ => Iff.rfl)] + exact (Fintype.prod_sum (fun e : M.val => part e.val)).symm + +omit [DecidableEq V] [DecidableEq I] in +theorem total_mass (part : E → I → ℝ) : + (∑ a : Marked (I:=I) inc,mass inc part a)=partitionWeight inc (collapse part) univ := by + rw [Fintype.sum_sigma] + exact Finset.sum_congr rfl fun M _ => sum_marks inc part M + +omit [Fintype E] [Fintype I] [DecidableEq V] [DecidableEq E] [DecidableEq I] in +lemma mass_nonneg (part : E → I → ℝ) (hp : ∀ e i,0 ≤ part e i) (a : Marked (I:=I) inc) : + 0 ≤ mass inc part a := Finset.prod_nonneg fun _ _ => hp _ _ + +noncomputable def law (part : E → I → ℝ) (a : Marked (I:=I) inc) : ℝ := + mass inc part a/partitionWeight inc (collapse part) univ + +omit [DecidableEq V] [DecidableEq I] in +lemma law_nonneg (part : E → I → ℝ) (hp : ∀ e i,0 ≤ part e i) (a : Marked (I:=I) inc) : + 0 ≤ law inc part a := by + apply div_nonneg (mass_nonneg inc part hp a) + rw [←total_mass inc part] + exact Finset.sum_nonneg fun a _ => mass_nonneg inc part hp a + +omit [DecidableEq V] [DecidableEq I] in +lemma law_sum (part : E → I → ℝ) (hz : partitionWeight inc (collapse part) univ ≠ 0) : + ∑ a : Marked (I:=I) inc,law inc part a=1 := by + simp only [law,←Finset.sum_div,total_mass,div_self hz] + +omit [DecidableEq V] [DecidableEq I] in +lemma law_marginal (part : E → I → ℝ) (M : Matchings inc univ) : + (∑ m : (↥M.val → I),law inc part ⟨M,m⟩)= + (∏ e ∈ M.val,collapse part e)/partitionWeight inc (collapse part) univ := by + simp only [law,←Finset.sum_div,sum_marks] + +omit [DecidableEq V] in +lemma pattern_sum (part : E → I → ℝ) + (pattern : (M : Matchings inc univ) → ↥M.val → I) + (u : Matchings inc univ → ℝ) : + (∑ a : Marked (I:=I) inc, if a.2=pattern a.1 then mass inc part a*u a.1 else 0)= + ∑ M : Matchings inc univ,(∏ e : M.val,part e.val (pattern M e))*u M := by + classical + rw [Fintype.sum_sigma] + apply Finset.sum_congr rfl + intro M _ + simp only [Finset.sum_ite_eq',mem_univ,ite_true,mass] + +omit [DecidableEq V] in +lemma allReal_mean (part : E → I → ℝ) (real : I) (u : E → ℝ) : + (∑ a : Marked (I:=I) inc,law inc part a * + (if a.2=(fun _ => real) then ∏ e ∈ a.1.val,u e else 0))= + partitionWeight inc (fun e => part e real*u e) univ / + partitionWeight inc (collapse part) univ := by + classical + calc + _ = (∑ a : Marked (I:=I) inc, + if a.2=(fun _ => real) then mass inc part a*(∏ e ∈ a.1.val,u e) else 0) / + partitionWeight inc (collapse part) univ := by + rw [Finset.sum_div] + apply Finset.sum_congr rfl + intro a _ + split_ifs <;> simp only [law,mul_zero,zero_div,div_mul_eq_mul_div] + _ = _ := by + congr 1 + rw [pattern_sum inc part (fun _ _ => real) (fun M => ∏ e ∈ M.val,u e)] + unfold partitionWeight + apply Finset.sum_congr rfl + intro M _ + rw [←Finset.prod_subtype M.val (fun _ => Iff.rfl) (fun e => part e real), + ←Finset.prod_mul_distrib] + +noncomputable def completionEquiv (hinc : ∀ e,∃ x,inc e x) (Q : Partial inc) : + {M : Matchings inc univ // Q.val⊆M.val} ≃ Matchings inc (univ \ support inc Q.val) where + toFun M := ⟨M.val.val \ Q.val,M.val.property.sdiff Q.property M.property⟩ + invFun M := ⟨⟨Q.val∪M.val,by + have h := Q.property.union M.property (support_sdiff_disjoint inc Q.val) + rw [Finset.union_sdiff_of_subset (Finset.subset_univ _)] at h + exact h⟩,Finset.subset_union_left⟩ + left_inv M := by + apply Subtype.ext + exact Subtype.ext (Finset.union_sdiff_of_subset M.property) + right_inv M := by + have hd := Q.property.disjoint_edges M.property hinc (support_sdiff_disjoint inc Q.val) + exact Subtype.ext (Finset.union_sdiff_cancel_left hd) + +lemma completion_sum (hinc : ∀ e,∃ x,inc e x) (Q : Partial inc) (r : E → ℝ) : + (∑ M : {M : Matchings inc univ // Q.val⊆M.val},∏ e ∈ M.val.val \ Q.val,r e)= + partitionWeight inc r (univ \ support inc Q.val) := by + exact Fintype.sum_equiv (completionEquiv inc hinc Q) _ _ (fun _ => rfl) + +noncomputable def conditional (part : E → I → ℝ) (M : Matchings inc univ) + (m : ↥M.val → I) : ℝ := ∏ e : M.val,part e.val (m e)/collapse part e.val + +omit [Fintype E] [DecidableEq V] [DecidableEq I] in +lemma conditional_sum (part : E → I → ℝ) (hc : ∀ e,collapse part e≠0) + (M : Matchings inc univ) : ∑ m : (↥M.val → I),conditional inc part M m=1 := by + unfold conditional + rw [←Fintype.prod_sum (fun e : M.val => fun i : I => part e.val i / collapse part e.val)] + apply Finset.prod_eq_one + intro e _ + rw [←Finset.sum_div] + exact div_self (hc _) + +omit [DecidableEq V] [DecidableEq E] [DecidableEq I] in +lemma law_from_reveal (part : E → I → ℝ) (hc : ∀ e,collapse part e≠0) + (a : Marked (I:=I) inc) : + ((∏ e ∈ a.1.val,collapse part e)/partitionWeight inc (collapse part) univ) * + conditional inc part a.1 a.2 = law inc part a := by + classical + rw [conditional,Finset.prod_div_distrib,←Finset.prod_subtype a.1.val (fun _ => Iff.rfl)] + have hn : (∏ e ∈ a.1.val,collapse part e)≠0 := Finset.prod_ne_zero_iff.mpr (fun e _ => hc e) + unfold law mass + field_simp + +omit [Fintype E] [Fintype I] [DecidableEq V] [DecidableEq I] in +lemma fixed_pattern_mass (part : E → I → ℝ) (real probe : I) + (Q : Finset E) (M : Matchings inc univ) (hQ : Q⊆M.val) : + (∏ e : M.val,part e.val (if e.val∈Q then probe else real))= + (∏ e ∈ Q,part e probe)*(∏ e ∈ M.val \ Q,part e real) := by + classical + rw [←Finset.prod_subtype M.val (fun _ => Iff.rfl) + (fun e : E => part e (if e∈Q then probe else real))] + calc + _ = (∏ e ∈ Q,part e (if e∈Q then probe else real))* + (∏ e ∈ M.val \ Q,part e (if e∈Q then probe else real)) := by + rw [←Finset.prod_union (Finset.disjoint_left.mpr (fun e he hf => (Finset.mem_sdiff.mp hf).2 he)),Finset.union_sdiff_of_subset hQ] + _ = _ := by + congr 1 + · apply Finset.prod_congr rfl; intro e he; simp only [ite_eq_left he] + · apply Finset.prod_congr rfl; intro e he; simp only [ite_eq_right (mem_sdiff.mp he).2] + +lemma sum_if_subtype {A : Type*} [Fintype A] (P : A → Prop) [DecidablePred P] + (f : A → ℝ) : + (∑ a,if P a then f a else 0)=∑ a : {a // P a},f a.val := by + classical + rw [←Finset.sum_filter] + exact Finset.sum_subtype _ (by simp) f + +omit [Fintype I] [DecidableEq I] in +lemma fixed_pattern_sum (hinc : ∀ e,∃ x,inc e x) + (part : E → I → ℝ) (real probe : I) (Q : Partial inc) (u : E → ℝ) : + (∑ M : Matchings inc univ, + (∏ e : M.val,part e.val (if e.val∈Q.val then probe else real))* + (if Q.val⊆M.val then ∏ e ∈ M.val \ Q.val,u e else 0))= + (∏ e ∈ Q.val,part e probe)*partitionWeight inc (fun e => part e real*u e) + (univ \ support inc Q.val) := by + classical + have he (M : Matchings inc univ) : + (∏ e : M.val,part e.val (if e.val∈Q.val then probe else real))* + (if Q.val⊆M.val then ∏ e ∈ M.val \ Q.val,u e else 0)= + (∏ e ∈ Q.val,part e probe)* + (if Q.val⊆M.val then ∏ e ∈ M.val \ Q.val,part e real*u e else 0) := by + by_cases hs : Q.val⊆M.val + · simp only [ite_eq_left hs,fixed_pattern_mass inc part real probe Q.val M hs] + rw [mul_assoc,←Finset.prod_mul_distrib] + · simp only [ite_eq_right hs,mul_zero] + simp_rw [he] + rw [←Finset.mul_sum,sum_if_subtype] + rw [completion_sum inc hinc Q] + +theorem fixed_probe_mean (hinc : ∀ e,∃ x,inc e x) + (part : E → I → ℝ) (real probe : I) (Q : Partial inc) (u : E → ℝ) : + (∑ a : Marked (I:=I) inc,law inc part a * + (if Q.val⊆a.1.val ∧ a.2=(fun e => if e.val∈Q.val then probe else real) + then ∏ e ∈ a.1.val \ Q.val,u e else 0))= + ((∏ e ∈ Q.val,part e probe)*partitionWeight inc (fun e => part e real*u e) + (univ \ support inc Q.val))/partitionWeight inc (collapse part) univ := by + classical + calc + _ = (∑ a : Marked (I:=I) inc, + if a.2=(fun e => if e.val∈Q.val then probe else real) then + mass inc part a*(if Q.val⊆a.1.val then ∏ e ∈ a.1.val \ Q.val,u e else 0) + else 0)/partitionWeight inc (collapse part) univ := by + rw [Finset.sum_div] + apply Finset.sum_congr rfl + intro a _ + by_cases hQ : Q.val⊆a.1.val <;> + by_cases hm : a.2=(fun e => if e.val∈Q.val then probe else real) <;> + simp only [hQ,hm,and_true,and_false,ite_true,ite_false, + law,mul_zero,zero_div,div_mul_eq_mul_div] + _ = _ := by + congr 1 + rw [pattern_sum inc part (fun M e => if e.val∈Q.val then probe else real) + (fun M => if Q.val⊆M.val then ∏ e ∈ M.val \ Q.val,u e else 0)] + exact fixed_pattern_sum inc hinc part real probe Q u + +end MatchingFPRAS.Marking + +namespace MatchingFPRAS.Enlargement + +open MatchingFPRAS.Switching MatchingFPRAS.Subdivision MatchingFPRAS.RealGeometry +open MatchingFPRAS.Hierarchy MatchingFPRAS.Transport MatchingFPRAS.Representation Finset + +variable {V : Type*} [Fintype V] [LinearOrder V] [Nontrivial V] + +noncomputable local instance (w : V → V → ℝ) (K : ℕ) : DecidableEq (SourceLabel w K) := Classical.decEq _ + +noncomputable local instance (w : V → V → ℝ) (K : ℕ) : Fintype (BagEdge (sourceBags w K)) := Fintype.ofFinite _ + +noncomputable def frozenActivity (w w₁ : V → V → ℝ) (K : ℕ) + (e : SourceRealEdge V K) : ℝ := + pathActivity (2*K+2) (fun e => bottleneck w (source e) (target e)) + (fun e => sourceHeight w (source e)) (fun e => sourceHeight w (target e)) + (logicalActivity w₁) e.1 e.2 + +noncomputable def frozenPortion (w w₁ : V → V → ℝ) (K : ℕ) : BagEdge (sourceBags w K) → ℝ := + by classical exact edgeExtension (sourceRealEmbedding w K) (frozenActivity w w₁ K) + +noncomputable def sourceC (w : V → V → ℝ) (K : ℕ) : ℝ := + ∏ e : LogicalEdge V,pathConstant (2*K+2) (bottleneck w (source e) (target e)) + (sourceHeight w (source e)) (sourceHeight w (target e)) + +lemma sourceC_pos (w : V → V → ℝ) (K : ℕ) : 0 < sourceC w K := by + exact Finset.prod_pos fun e _ => pathConstant_pos _ _ _ _ + (zero_lt_one.trans_le (one_le_bottleneck _ _ _)) + +lemma frozenPortion_partition (w w₁ : V → V → ℝ) (K : ℕ) + (R : Finset V) (U : LogicalEdge V → Finset (Fin (4*(2*K+2)))) : + partitionWeight BagEdge.Incident (frozenPortion w w₁ K) (survivors (4*(2*K+2)) R U)= + realHolePartition source target (4*(2*K+2)) R U + (pathActivity (2*K+2) (fun e => bottleneck w (source e) (target e)) + (fun e => sourceHeight w (source e)) (fun e => sourceHeight w (target e)) (logicalActivity w₁)) := by + classical + rw [show frozenPortion w w₁ K=edgeExtension (sourceRealEmbedding w K) (frozenActivity w w₁ K) from rfl] + rw [partition_embedding (fun (q : SourceRealEdge V K) x => x∈edge source target (4*(2*K+2)) q.1 q.2) + BagEdge.Incident (sourceRealEmbedding w K) (fun _ _ => Iff.rfl)] + exact realMatching_partition source target (4*(2*K+2)) source_ne_target R U _ + +lemma frozenPortion_full (w w₁ : V → V → ℝ) (hz : 0 < partition w₁ ∅) (K : ℕ) : + partitionWeight BagEdge.Incident (frozenPortion w w₁ K) univ=sourceC w K*partition w₁ ∅ := by + rw [←survivors_empty (V:=V) K,frozenPortion_partition,intact_partition_identity w₁ hz] + rfl + +lemma frozenPortion_probe (w w₁ : V → V → ℝ) (K : ℕ) (e₀ : LogicalEdge V) : + partitionWeight BagEdge.Incident (frozenPortion w w₁ K) + (survivors (4*(2*K+2)) ∅ (singleProbeHoles (2*K+2) (by omega) e₀))= + sourceC w K*partition w₁ {source e₀,target e₀} := by + rw [frozenPortion_partition] + change realHolePartition source target (4*(2*K+2)) ∅ + (singleProbeHoles (2*K+2) (by omega) e₀) + (fun e => profileActivity (2*K+2) (bottleneck w (source e) (target e)) + (sourceHeight w (source e)) (sourceHeight w (target e)) (logicalActivity w₁ e))=_ + rw [singleProbe_partition _ _ _ _ _ (source_ne_target e₀), + logical_partition_redundant w₁ _ e₀ (by simp)] + rfl + +lemma profile_reweight (p : ℕ) (B Hu Hv lam r : ℝ) (i : Fin (4*p+1)) : + profileActivity p B Hu Hv (lam*r) i = + profileActivity p B Hu Hv lam i*(if i.val=2*p then r else 1) := by + rcases lt_trichotomy i.val (2*p) with hi|hi|hi + · rw [profile_left _ _ _ _ _ _ hi,profile_left _ _ _ _ _ _ hi,ite_eq_right (ne_of_lt hi),mul_one] + · have he : i=⟨2*p,by omega⟩ := Fin.ext hi + rw [he]; simp + · rw [profile_right _ _ _ _ _ _ hi,profile_right _ _ _ _ _ _ hi,ite_eq_right (ne_of_gt hi),mul_one] + +noncomputable def rawReweight (w w₁ : V → V → ℝ) (K : ℕ) (e : SourceRealEdge V K) : ℝ := + if e.2.val=2*(2*K+2) then logicalActivity w₁ e.1/logicalActivity w e.1 else 1 + +noncomputable def bagReweight (w w₁ : V → V → ℝ) (K : ℕ) (q : BagEdge (sourceBags w K)) : ℝ := by + classical + exact if h : ∃ e,sourceRealEmbedding w K e=q then rawReweight w w₁ K h.choose else 1 + +lemma bagReweight_on (w w₁ : V → V → ℝ) (K : ℕ) (e : SourceRealEdge V K) : + bagReweight w w₁ K (sourceRealEmbedding w K e)=rawReweight w w₁ K e := by + classical + unfold bagReweight + rw [dite_eq_left ⟨e,rfl⟩] + exact congrArg (rawReweight w w₁ K) ((sourceRealEmbedding w K).injective + (Exists.choose_spec (show ∃ e',sourceRealEmbedding w K e'=sourceRealEmbedding w K e from ⟨e,rfl⟩))) + +lemma bagReweight_identity (w w₁ : V → V → ℝ) (hw : ∀ x y,0 < w x y) (K : ℕ) : + (fun e => sourceRealPortion w K e*bagReweight w w₁ K e)=frozenPortion w w₁ K := by + classical + funext e + by_cases he : ∃ q,sourceRealEmbedding w K q=e + · obtain ⟨q,rfl⟩ := he + rw [sourceRealPortion,frozenPortion,edgeExtension_on,edgeExtension_on,bagReweight_on] + have hl : logicalActivity w q.1≠0 := by + unfold logicalActivity edgeActivity + split_ifs <;> exact (hw _ _).ne' + dsimp only [sourceRealActivity,frozenActivity,pathActivity,rawReweight] + rw [←profile_reweight,mul_div_cancel₀ _ hl] + · rw [sourceRealPortion,frozenPortion,edgeExtension_off _ _ _ he,edgeExtension_off _ _ _ he,zero_mul] + +lemma bagReweight_range (w w₁ : V → V → ℝ) (hw : ∀ x y,0 < w x y) + (hw₁ : ∀ x y,0 ≤ w₁ x y) (hle : ∀ x y,w₁ x y ≤ w x y) (K : ℕ) + (e : BagEdge (sourceBags w K)) : 0 ≤ bagReweight w w₁ K e ∧ bagReweight w w₁ K e ≤ 1 := by + classical + unfold bagReweight + split_ifs with he + · unfold rawReweight + split_ifs + · have h₀ : 0 < logicalActivity w he.choose.1 := by + unfold logicalActivity edgeActivity; split_ifs <;> exact hw _ _ + have h₁ : 0 ≤ logicalActivity w₁ he.choose.1 := by + unfold logicalActivity edgeActivity; split_ifs <;> exact hw₁ _ _ + have h₂ : logicalActivity w₁ he.choose.1 ≤ logicalActivity w he.choose.1 := by + unfold logicalActivity edgeActivity; split_ifs <;> exact hle _ _ + exact ⟨div_nonneg h₁ h₀.le,(div_le_one h₀).mpr h₂⟩ + · norm_num + · norm_num + +noncomputable def centralEdge (w : V → V → ℝ) (K : ℕ) (e : LogicalEdge V) : BagEdge (sourceBags w K) := + sourceRealEmbedding w K (e,⟨2*(2*K+2),by omega⟩) + +lemma centralEdge_injective (w : V → V → ℝ) (K : ℕ) : Function.Injective (centralEdge w K) := by + intro e f h + exact congrArg Prod.fst ((sourceRealEmbedding w K).injective h) + +noncomputable def probePortion (w : V → V → ℝ) (K D : ℕ) (q : BagEdge (sourceBags w K)) : ℝ := by + classical + exact if ∃ e,centralEdge w K e=q then 1/(D:ℝ) else 0 + +lemma probePortion_on (w : V → V → ℝ) (K D : ℕ) (e : LogicalEdge V) : + probePortion w K D (centralEdge w K e)=1/(D:ℝ) := by + classical + simp [probePortion] + +noncomputable def sourcePortions (w : V → V → ℝ) (K D : ℕ) + (e : BagEdge (sourceBags w K)) : Fin 3 → ℝ := + ![sourceRealPortion w K e,bagHeight w K e.val.val.2/D-probePortion w K D e,probePortion w K D e] + +lemma sourcePortions_collapse (w : V → V → ℝ) (K D : ℕ) : + Marking.collapse (sourcePortions w K D)=sourceBagWeight w K D := by + funext e + simp [Marking.collapse,sourcePortions,Fin.sum_univ_succ,sourceBagWeight] + +lemma sourcePortions_nonneg (w : V → V → ℝ) (hw : ∀ x y,0 < w x y) (K D : ℕ) + (e : BagEdge (sourceBags w K)) (i : Fin 3) : 0 ≤ sourcePortions w K D e i := by + classical + fin_cases i + · exact sourceRealPortion_nonneg w hw K e + · change 0 ≤ bagHeight w K e.val.val.2/D-probePortion w K D e + apply sub_nonneg.mpr + unfold probePortion + split_ifs + · exact div_le_div_of_nonneg_right (bagHeight_one w K _) (Nat.cast_nonneg D) + · exact div_nonneg (bagHeight_pos w K _).le (Nat.cast_nonneg D) + · change 0 ≤ probePortion w K D e + unfold probePortion + split_ifs <;> positivity + +lemma centralEdge_ends (w : V → V → ℝ) (K : ℕ) (e : LogicalEdge V) : + (centralEdge w K e).val.val.1 = + s((Sum.inr (e,(⟨2*(2*K+2)-1,by omega⟩ : Fin (4*(2*K+2)))) : SourceVertex V K), + Sum.inr (e,⟨2*(2*K+2),by omega⟩)) := by + change edge source target (4*(2*K+2)) e ⟨2*(2*K+2),by omega⟩=_ + simp only [edge,atVertex,Fin.val_castSucc,Fin.val_succ] + simp only [show 2*(2*K+2)≠0 by omega,show 2*(2*K+2)≠4*(2*K+2)+1 by omega, + show 2*(2*K+2)+1≠0 by omega, show 2*(2*K+2)+1≠4*(2*K+2)+1 by omega, + dite_false,Nat.add_sub_cancel] + +lemma probe_support (w : V → V → ℝ) (K : ℕ) (e₀ : LogicalEdge V) : + support BagEdge.Incident {centralEdge w K e₀}= + enlargedHoles (4*(2*K+2)) ∅ (singleProbeHoles (2*K+2) (by omega) e₀) := by + classical + ext x + rw [mem_support] + simp only [mem_singleton,exists_eq_left,BagEdge.Incident,ColoredEdge.Incident,centralEdge_ends,Sym2.mem_iff] + cases x with + | inl x => simp + | inr ei => + rcases ei with ⟨e,i⟩ + by_cases he : e=e₀ + · subst e + simp [singleProbeHoles,probeHoles] + · simp [singleProbeHoles,he] + +lemma probe_survivors (w : V → V → ℝ) (K : ℕ) (e₀ : LogicalEdge V) : + univ \ support BagEdge.Incident {centralEdge w K e₀}= + survivors (4*(2*K+2)) ∅ (singleProbeHoles (2*K+2) (by omega) e₀) := by + rw [probe_support] + ext x + cases x with + | inl x => simp + | inr ei => rcases ei with ⟨e,i⟩; simp + +noncomputable def probePartial (w : V → V → ℝ) (K : ℕ) (e₀ : LogicalEdge V) : + Partial (BagEdge.Incident (bags:=sourceBags w K)) := by + classical + refine ⟨{centralEdge w K e₀},?_,?_⟩ + · intro e he x hx + exact (mem_support _ _ _).mpr ⟨e,he,hx⟩ + · intro x hx + obtain ⟨e,he,hex⟩ := (mem_support _ _ _).mp hx + refine ⟨e,⟨he,hex⟩,?_⟩ + intro f hf + exact (mem_singleton.mp hf.1).trans (mem_singleton.mp he).symm + +open scoped Classical + +abbrev SourceMarked (w : V → V → ℝ) (K : ℕ) := + Marking.Marked (I:=Fin 3) (BagEdge.Incident (bags:=sourceBags w K)) + +noncomputable def sourceLaw (w : V → V → ℝ) (K D : ℕ) : SourceMarked w K → ℝ := + Marking.law BagEdge.Incident (sourcePortions w K D) + +noncomputable def observableA (w : V → V → ℝ) (K : ℕ) (a : SourceMarked w K) : ℝ := by + classical exact if a.2=(fun _ => 0) then 1 else 0 + +noncomputable def observableD (w w₁ : V → V → ℝ) (K : ℕ) (a : SourceMarked w K) : ℝ := by + classical exact if a.2=(fun _ => 0) then ∏ e ∈ a.1.val,bagReweight w w₁ K e else 0 + +noncomputable def observableProbe (w w₁ : V → V → ℝ) (K : ℕ) (e₀ : LogicalEdge V) + (a : SourceMarked w K) : ℝ := by + classical exact if {centralEdge w K e₀}⊆a.1.val ∧ + a.2=(fun e => if e.val∈({centralEdge w K e₀} : Finset _) then 2 else 0) + then ∏ e ∈ a.1.val \ {centralEdge w K e₀},bagReweight w w₁ K e else 0 + +noncomputable def sourceBagZ (w : V → V → ℝ) (K D : ℕ) : ℝ := + partitionWeight BagEdge.Incident (sourceBagWeight w K D) univ + +lemma sourceLaw_sum (w : V → V → ℝ) (K D : ℕ) (hz : sourceBagZ w K D≠0) : + ∑ a : SourceMarked w K,sourceLaw w K D a=1 := by + apply Marking.law_sum + simpa only [sourcePortions_collapse,sourceBagZ] using hz + +lemma sourceLaw_nonneg (w : V → V → ℝ) (hw : ∀ x y,0 < w x y) (K D : ℕ) + (hz : 0 ≤ sourceBagZ w K D) (a : SourceMarked w K) : 0 ≤ sourceLaw w K D a := by + unfold sourceLaw Marking.law + rw [sourcePortions_collapse] + exact div_nonneg (Marking.mass_nonneg _ _ (sourcePortions_nonneg w hw K D) a) hz + +theorem observableA_mean (w : V → V → ℝ) (hz : 0 < partition w ∅) (K D : ℕ) : + (∑ a : SourceMarked w K,sourceLaw w K D a*observableA w K a)= + sourceC w K*partition w ∅/sourceBagZ w K D := by + classical + have h := Marking.allReal_mean BagEdge.Incident (sourcePortions w K D) (0 : Fin 3) (fun _ => 1) + simpa only [sourceLaw,observableA,Finset.prod_const_one,sourcePortions,Matrix.cons_val_zero, + mul_one,sourcePortions_collapse,sourceRealPortion_full w hz,sourceC,sourceBagZ] using h + +theorem observableD_mean (w w₁ : V → V → ℝ) (hw : ∀ x y,0 < w x y) + (hz₁ : 0 < partition w₁ ∅) (K D : ℕ) : + (∑ a : SourceMarked w K,sourceLaw w K D a*observableD w w₁ K a)= + sourceC w K*partition w₁ ∅/sourceBagZ w K D := by + classical + have h := Marking.allReal_mean BagEdge.Incident (sourcePortions w K D) (0 : Fin 3) (bagReweight w w₁ K) + simp only [sourcePortions,Matrix.cons_val_zero] at h + rw [bagReweight_identity w w₁ hw K,frozenPortion_full w w₁ hz₁] at h + simpa only [sourceLaw,observableD,sourcePortions_collapse,sourceBagZ] using h + +theorem observableProbe_mean (w w₁ : V → V → ℝ) (hw : ∀ x y,0 < w x y) + (K D : ℕ) (e₀ : LogicalEdge V) : + (∑ a : SourceMarked w K,sourceLaw w K D a*observableProbe w w₁ K e₀ a)= + (sourceC w K*partition w₁ {source e₀,target e₀}/D)/sourceBagZ w K D := by + classical + have h := Marking.fixed_probe_mean BagEdge.Incident BagEdge.exists_incident + (sourcePortions w K D) (0 : Fin 3) 2 (probePartial w K e₀) (bagReweight w w₁ K) + simp only [sourcePortions,Matrix.cons_val_zero,Matrix.cons_val_two, + probePartial,Finset.prod_singleton,probePortion_on] at h + rw [bagReweight_identity w w₁ hw K,probe_survivors,frozenPortion_probe] at h + calc + _ = ((1/(D:ℝ))*(sourceC w K*partition w₁ {source e₀,target e₀}))/sourceBagZ w K D := by + simpa [sourceLaw,observableProbe,sourcePortions_collapse,sourceBagZ,Matrix.vecHead,Matrix.vecTail] using h + _ = _ := by ring + +lemma observableA_range (w : V → V → ℝ) (K : ℕ) (a : SourceMarked w K) : + 0 ≤ observableA w K a ∧ observableA w K a ≤ 1 := by + classical + unfold observableA + split_ifs <;> norm_num + +lemma observableD_range (w w₁ : V → V → ℝ) (hw : ∀ x y,0 < w x y) + (hw₁ : ∀ x y,0 ≤ w₁ x y) (hle : ∀ x y,w₁ x y ≤ w x y) + (K : ℕ) (a : SourceMarked w K) : + 0 ≤ observableD w w₁ K a ∧ observableD w w₁ K a ≤ 1 := by + classical + unfold observableD + split_ifs + · exact ⟨Finset.prod_nonneg (fun e _ => (bagReweight_range w w₁ hw hw₁ hle K e).1), + Finset.prod_le_one₀ (fun e _ => (bagReweight_range w w₁ hw hw₁ hle K e).1) + (fun e _ => (bagReweight_range w w₁ hw hw₁ hle K e).2)⟩ + · norm_num + +lemma observableProbe_range (w w₁ : V → V → ℝ) (hw : ∀ x y,0 < w x y) + (hw₁ : ∀ x y,0 ≤ w₁ x y) (hle : ∀ x y,w₁ x y ≤ w x y) + (K : ℕ) (e₀ : LogicalEdge V) (a : SourceMarked w K) : + 0 ≤ observableProbe w w₁ K e₀ a ∧ observableProbe w w₁ K e₀ a ≤ 1 := by + classical + unfold observableProbe + split_ifs + · exact ⟨Finset.prod_nonneg (fun e _ => (bagReweight_range w w₁ hw hw₁ hle K e).1), + Finset.prod_le_one₀ (fun e _ => (bagReweight_range w w₁ hw hw₁ hle K e).1) + (fun e _ => (bagReweight_range w w₁ hw hw₁ hle K e).2)⟩ + · norm_num + +end MatchingFPRAS.Enlargement + +end OAI diff --git a/lean/OAI/Combinatorics/MatchingCount/Graphs/MatchingMap.lean b/lean/OAI/Combinatorics/MatchingCount/Graphs/MatchingMap.lean new file mode 100644 index 0000000000000000000000000000000000000000..bc687b5025517e807665b6eb0c1ff3e2bc9d07ec --- /dev/null +++ b/lean/OAI/Combinatorics/MatchingCount/Graphs/MatchingMap.lean @@ -0,0 +1,390 @@ +import Mathlib +import OAI.Combinatorics.MatchingCount.Probability.Variance +import OAI.Combinatorics.MatchingCount.Graphs.EdgeLow + +namespace OAI + +namespace MatchingFPRAS.Transport + +open Finset + +variable {V E F : Type*} [Fintype V] [Fintype E] [Fintype F] + +variable [DecidableEq V] [DecidableEq E] [DecidableEq F] + +variable (inc : E → V → Prop) (inc' : F → V → Prop) (f : E ↪ F) + +variable (hinc : ∀ e x,inc' (f e) x ↔ inc e x) + +include hinc in +omit [Fintype V] [Fintype E] [Fintype F] [DecidableEq V] [DecidableEq E] [DecidableEq F] in +lemma matching_map_iff [Fintype V] [Fintype E] [Fintype F] + [DecidableEq V] [DecidableEq E] [DecidableEq F] (S : Finset E) (U : Finset V) : + MatchingOn inc' (S.map f) U ↔ MatchingOn inc S U := by + constructor + · intro hM + refine ⟨fun e he x hx => hM.1 (f e) (Finset.mem_map.mpr ⟨e,he,rfl⟩) x ((hinc e x).mpr hx),?_⟩ + intro x hx + obtain ⟨q,⟨hq,hqx⟩,hu⟩ := hM.2 x hx + obtain ⟨e,he,rfl⟩ := Finset.mem_map.mp hq + refine ⟨e,⟨he,(hinc e x).mp hqx⟩,?_⟩ + intro e' he' + apply f.injective + exact hu (f e') ⟨Finset.mem_map.mpr ⟨e',he'.1,rfl⟩,(hinc e' x).mpr he'.2⟩ + · intro hM + constructor + · intro q hq x hx + obtain ⟨e,he,rfl⟩ := Finset.mem_map.mp hq + exact hM.1 e he x ((hinc e x).mp hx) + · intro x hx + obtain ⟨e,⟨he,hex⟩,hu⟩ := hM.2 x hx + refine ⟨f e,⟨Finset.mem_map.mpr ⟨e,he,rfl⟩,(hinc e x).mpr hex⟩,?_⟩ + intro q hq + obtain ⟨e',he',rfl⟩ := Finset.mem_map.mp hq.1 + exact congrArg f (hu e' ⟨he',(hinc e' x).mp hq.2⟩) + +noncomputable def matchingMap (U : Finset V) (M : Matchings inc U) : Matchings inc' U := + ⟨M.val.map f,(matching_map_iff inc inc' f hinc M.val U).mpr M.property⟩ + +lemma matchingMap_injective (U : Finset V) : Function.Injective (matchingMap inc inc' f hinc U) := by + intro a b h + apply Subtype.ext + exact Finset.map_injective f (congrArg Subtype.val h) + +noncomputable def edgeExtension (w : E → ℝ) (q : F) : ℝ := by + classical + exact if h : ∃ e,f e=q then w h.choose else 0 + +omit [Fintype F] [DecidableEq E] in +lemma edgeExtension_on [Fintype F] [DecidableEq E] (w : E → ℝ) (e : E) : edgeExtension f w (f e)=w e := by + classical + unfold edgeExtension + rw [dite_eq_left ⟨e,rfl⟩] + exact congrArg w (f.injective (Exists.choose_spec (show ∃ e',f e'=f e from ⟨e,rfl⟩))) + +omit [Fintype F] [DecidableEq E] in +lemma edgeExtension_off [Fintype F] [DecidableEq E] (w : E → ℝ) (q : F) (hq : ¬∃ e,f e=q) : edgeExtension f w q=0 := by + classical + simp [edgeExtension,hq] + +omit [Fintype F] [DecidableEq E] in +lemma edgeExtension_nonneg [Fintype F] [DecidableEq E] (w : E → ℝ) (hw : ∀ e,0≤w e) (q : F) : 0≤edgeExtension f w q := by + classical + unfold edgeExtension + split_ifs <;> first | exact hw _ | norm_num + +lemma matchingMap_weight (w : E → ℝ) (U : Finset V) (M : Matchings inc U) : + (∏ q∈(matchingMap inc inc' f hinc U M).val,edgeExtension f w q)=∏ e∈M.val,w e := by + dsimp [matchingMap] + rw [Finset.prod_map] + simp_rw [edgeExtension_on] + +include hinc in + +theorem partition_embedding (w : E → ℝ) (U : Finset V) : + partitionWeight inc' (edgeExtension f w) U=partitionWeight inc w U := by + classical + unfold partitionWeight + symm + apply Finset.sum_bij_ne_zero (fun M _ _ => matchingMap inc inc' f hinc U M) + · intros; exact Finset.mem_univ _ + · intro a _ _ b _ _ h + exact matchingMap_injective inc inc' f hinc U h + · intro N _ hN + have hr : ∀ q∈N.val,∃ e,f e=q := by + intro q hq + by_contra hn + apply hN + exact Finset.prod_eq_zero hq (edgeExtension_off f w q hn) + let S := univ.filter fun e : E => f e∈N.val + have hS : S.map f=N.val := by + ext q + constructor + · intro hq + obtain ⟨e,he,rfl⟩ := Finset.mem_map.mp hq + exact (Finset.mem_filter.mp he).2 + · intro hq + obtain ⟨e,rfl⟩ := hr q hq + exact Finset.mem_map.mpr ⟨e,by simp [S,hq],rfl⟩ + let M : Matchings inc U := ⟨S,(matching_map_iff inc inc' f hinc S U).mp (hS.symm ▸ N.property)⟩ + have hM : matchingMap inc inc' f hinc U M=N := Subtype.ext hS + refine ⟨M,Finset.mem_univ _,?_,hM⟩ + rw [←matchingMap_weight inc inc' f hinc w U M,hM] + exact hN + · intro M _ _ + exact (matchingMap_weight inc inc' f hinc w U M).symm + +end MatchingFPRAS.Transport + +namespace MatchingFPRAS.Enlargement + +open MatchingFPRAS.Switching MatchingFPRAS.Subdivision MatchingFPRAS.RealGeometry +open MatchingFPRAS.Hierarchy MatchingFPRAS.Transport Finset + +variable {V : Type*} [Fintype V] [LinearOrder V] [Nontrivial V] + +noncomputable local instance (w : V → V → ℝ) (K : ℕ) : DecidableEq (SourceLabel w K) := Classical.decEq _ + +noncomputable local instance (w : V → V → ℝ) (K : ℕ) : Fintype (BagEdge (sourceBags w K)) := Fintype.ofFinite _ + +noncomputable def sourceRealLabel (w : V → V → ℝ) (K : ℕ) (e : SourceRealEdge V K) : SourceLabel w K := + edgeLabel (sourceRealB w K) (sourceRealB_comm w K) (sourceRealB_tri w K) + (realLeft K) (realRight K) (sourceLevels w K) e + +omit [Nontrivial V] in +lemma real_edge_not_diag [Nontrivial V] (K : ℕ) (e : SourceRealEdge V K) : + ¬(edge source target (4*(2*K+2)) e.1 e.2).IsDiag := by + rw [edge,Sym2.mk_isDiag_iff] + intro he + have hi := atVertex_injective source target (4*(2*K+2)) e.1 (source_ne_target e.1) he + have := congrArg Fin.val hi + simp at this + +noncomputable def sourceColoredReal (w : V → V → ℝ) (K : ℕ) (e : SourceRealEdge V K) : + BagEdge (sourceBags w K) := + ⟨⟨(edge source target (4*(2*K+2)) e.1 e.2,sourceRealLabel w K e),real_edge_not_diag K e⟩,by + intro x hx + apply (mem_memberships _ _ _ (realLeft K) (realRight K) (sourceLevels w K) x _).mpr + refine ⟨e,?_,rfl⟩ + simpa [ColoredEdge.Incident,Incident,realLeft,realRight,edge] using hx⟩ + +lemma sourceColoredReal_injective (w : V → V → ℝ) (K : ℕ) : + Function.Injective (sourceColoredReal w K) := by + intro e f h + apply edge_injective source target (4*(2*K+2)) (by omega) + exact congrArg (fun q : BagEdge (sourceBags w K) => q.val.val.1) h + +noncomputable def sourceRealEmbedding (w : V → V → ℝ) (K : ℕ) : + SourceRealEdge V K ↪ BagEdge (sourceBags w K) := + ⟨sourceColoredReal w K,sourceColoredReal_injective w K⟩ + +noncomputable def sourceRealActivity (w : V → V → ℝ) (K : ℕ) (e : SourceRealEdge V K) : ℝ := + pathActivity (2*K+2) (fun e => bottleneck w (source e) (target e)) + (fun e => sourceHeight w (source e)) (fun e => sourceHeight w (target e)) (logicalActivity w) e.1 e.2 + +noncomputable def sourceRealPortion (w : V → V → ℝ) (K : ℕ) : BagEdge (sourceBags w K) → ℝ := + by classical exact edgeExtension (sourceRealEmbedding w K) (sourceRealActivity w K) + +lemma sourceRealPortion_partition (w : V → V → ℝ) (K : ℕ) + (R : Finset V) (U : LogicalEdge V → Finset (Fin (4*(2*K+2)))) : + partitionWeight BagEdge.Incident (sourceRealPortion w K) (survivors (4*(2*K+2)) R U)= + realHolePartition source target (4*(2*K+2)) R U + (pathActivity (2*K+2) (fun e => bottleneck w (source e) (target e)) + (fun e => sourceHeight w (source e)) (fun e => sourceHeight w (target e)) (logicalActivity w)) := by + classical + rw [show sourceRealPortion w K=edgeExtension (sourceRealEmbedding w K) (sourceRealActivity w K) from rfl] + rw [partition_embedding (fun (q : SourceRealEdge V K) x => x∈edge source target (4*(2*K+2)) q.1 q.2) + BagEdge.Incident (sourceRealEmbedding w K) (fun _ _ => Iff.rfl)] + exact realMatching_partition source target (4*(2*K+2)) source_ne_target R U _ + +noncomputable def holeTerminals (K : ℕ) (H : Finset (SourceVertex V K)) : Finset V := + by classical exact univ.filter fun x => Sum.inl x∈H + +noncomputable def holeInternals (K : ℕ) (H : Finset (SourceVertex V K)) (e : LogicalEdge V) : + Finset (Fin (4*(2*K+2))) := by classical exact univ.filter fun i => Sum.inr (e,i)∈H + +omit [Nontrivial V] in +lemma hole_decomposition [Nontrivial V] (K : ℕ) (H : Finset (SourceVertex V K)) : + enlargedHoles (4*(2*K+2)) (holeTerminals K H) (holeInternals K H)=H := by + ext x + cases x with + | inl x => simp [holeTerminals] + | inr ei => rcases ei with ⟨e,i⟩; simp [holeInternals] + +omit [Nontrivial V] in +lemma survivors_decomposition [Nontrivial V] (K : ℕ) (H : Finset (SourceVertex V K)) : + survivors (4*(2*K+2)) (holeTerminals K H) (holeInternals K H)=univ \ H := by + ext x + cases x with + | inl x => simp [holeTerminals] + | inr ei => rcases ei with ⟨e,i⟩; simp [holeInternals] + +omit [Nontrivial V] in +lemma survivors_empty [Nontrivial V] (K : ℕ) : survivors (V := V) (E := LogicalEdge V) (4*(2*K+2)) ∅ (fun _ => ∅)=univ := by + ext x + cases x with + | inl x => simp + | inr ei => rcases ei with ⟨e,i⟩; simp + +lemma sourceRealActivity_pos (w : V → V → ℝ) (hw : ∀ x y,0 exact hw _ _ + exact hl.trans_le (profile_lower _ _ _ _ _ + (edgeActivity_le_bottleneck w _ _ (source_ne_target e.1)) e.2) + +lemma sourceRealPortion_nonneg (w : V → V → ℝ) (hw : ∀ x y,0 (sourceRealActivity_pos w hw K q).le) e + +lemma sourceRealPortion_full (w : V → V → ℝ) (hz : 0 pathConstant_pos _ _ _ _ + (zero_lt_one.trans_le (one_le_bottleneck w _ _)) + +lemma sourceRealPortion_hole_bound (hn : 2≤Fintype.card V) + (w : V → V → ℝ) (hw : ∀ x y,0 sourceHeight w (source e)) (fun e => sourceHeight w (target e)) + (fun e => sourceHeight_nonneg w _) (fun e => sourceHeight_nonneg w _) + (holeTerminals K H) (holeInternals K H) heven + rw [←sourceRealPortion_partition w K,←sourceRealPortion_partition w K, + survivors_empty,survivors_decomposition] at ht + simpa only [hole_decomposition, sourceRealB] using ht + +theorem source_bag_inflation (hn : 2≤Fintype.card V) + (w : V → V → ℝ) (hw : ∀ x y,0 sourceRealPortion w K e+(2:ℝ)^e.val.val.2.1.val/D) univ + 1≤bagZ/realZ ∧ bagZ/realZ≤2 := by + classical + apply bag_inflation_of_hole_estimate (sourceBags w K) (Fintype.card_pos) + (sourceBag_card_le_two w K hK) (sourceRealB w K) + (fun l => (2:ℝ)^l.1.val) (fun _ => by positivity) + · intro e + apply sourceBag_height w K (edgeLow_ne_high e.val.val.1 e.val.property) + · exact e.property _ (edgeLow_mem _) + · exact e.property _ (edgeHigh_mem _) + · exact sourceRealPortion_nonneg w hw K + · exact sourceRealPortion_full_pos w hz K + · exact holeScale_pos + · intro H hH + convert sourceRealPortion_hole_bound hn w hw hz hrlo hrhi K H hH using 1 + congr 3 + ext x + simp + + + +open MatchingFPRAS.Switching MatchingFPRAS.Subdivision MatchingFPRAS.RealGeometry +open MatchingFPRAS.Hierarchy MatchingFPRAS.Transport Finset + +variable {V : Type*} [Fintype V] [LinearOrder V] [Nontrivial V] + +noncomputable local instance (w : V → V → ℝ) (K : ℕ) : DecidableEq (SourceLabel w K) := Classical.decEq _ + +noncomputable local instance (w : V → V → ℝ) (K : ℕ) : Fintype (BagEdge (sourceBags w K)) := Fintype.ofFinite _ + +noncomputable def bagHeight (w : V → V → ℝ) (K : ℕ) (l : SourceLabel w K) : ℝ := (2:ℝ)^l.1.val + +lemma bagHeight_one (w : V → V → ℝ) (K : ℕ) (l : SourceLabel w K) : 1 ≤ bagHeight w K l := by + exact one_le_pow₀ (by norm_num) + +lemma bagHeight_pos (w : V → V → ℝ) (K : ℕ) (l : SourceLabel w K) : 0 < bagHeight w K l := + zero_lt_one.trans_le (bagHeight_one w K l) + +lemma bagHeight_le (w : V → V → ℝ) (K : ℕ) (l : SourceLabel w K) : bagHeight w K l ≤ 4^K := by + have hl : l.1.val ≤ 2*K := (Nat.le_of_lt_succ l.1.isLt).trans (sourceLevels_le w K) + calc + _ ≤ (2:ℝ)^(2*K) := pow_le_pow_right₀ (by norm_num) hl + _ = _ := by rw [pow_mul]; norm_num + +lemma bagHeight_adjacent (w : V → V → ℝ) (K : ℕ) (a b : SourceLabel w K) + (hab : (sourceTree w K).Adj a b) : bagHeight w K a ≤ 2*bagHeight w K b := by + change Hierarchy.Parent _ _ _ a b ∨ Hierarchy.Parent _ _ _ b a at hab + rcases hab with hab|hab + · have he : b.1.val=a.1.val+1 := by have := hab.1; omega + change (2:ℝ)^a.1.val ≤ 2*2^b.1.val + rw [he,pow_succ] + have hz : 0 ≤ (2:ℝ)^a.1.val := by positivity + nlinarith + · have he : a.1.val=b.1.val+1 := by have := hab.1; omega + change (2:ℝ)^a.1.val ≤ 2*2^b.1.val + rw [he,pow_succ] + nlinarith + +lemma sourceRealActivity_le_strength (w : V → V → ℝ) (K : ℕ) (e : SourceRealEdge V K) : + sourceRealActivity w K e ≤ sourceRealB w K (realLeft K e) (realRight K e) := by + exact edge_activity_le_realBottleneck source target source_ne_target (2*K+2) (by omega) _ _ _ _ e.1 e.2 + +lemma sourceRealActivity_le_height (w : V → V → ℝ) (K : ℕ) + (hw : ∀ x y,x≠y → edgeActivity w x y ≤ (4:ℝ)^K) (e : SourceRealEdge V K) : + sourceRealActivity w K e ≤ 2*bagHeight w K (sourceRealLabel w K e) := by + apply (sourceRealActivity_le_strength w K e).trans + have hh := dyadic_upper_of_lt (sourceLevels w K) + (sourceRealB w K (realLeft K e) (realRight K e)) + ((source_strength_le_max w K hw e).trans_lt (maxSourceHeight_lt w K hw)) + change _ ≤ 2*(2:ℝ)^(dyadicLevel (sourceLevels w K) (sourceRealB w K (realLeft K e) (realRight K e))).val + rw [pow_succ,mul_comm] at hh + exact hh.le + +lemma sourceRealPortion_le_height (w : V → V → ℝ) (K : ℕ) + (hw : ∀ x y,x≠y → edgeActivity w x y ≤ (4:ℝ)^K) (e : BagEdge (sourceBags w K)) : + sourceRealPortion w K e ≤ 2*bagHeight w K e.val.val.2 := by + classical + by_cases he : ∃ q,sourceRealEmbedding w K q=e + · obtain ⟨q,rfl⟩ := he + rw [sourceRealPortion,edgeExtension_on] + exact sourceRealActivity_le_height w K hw q + · rw [sourceRealPortion,edgeExtension_off _ _ _ he] + exact mul_nonneg (by norm_num) (bagHeight_pos _ _ _).le + +noncomputable def sourceBagWeight (w : V → V → ℝ) (K D : ℕ) + (e : BagEdge (sourceBags w K)) : ℝ := + sourceRealPortion w K e+bagHeight w K e.val.val.2/D + +lemma sourceBagWeight_range (w : V → V → ℝ) (K D : ℕ) (hD : 1 ≤ D) + (hw : ∀ x y,0 < w x y) (hK : ∀ x y,x≠y → edgeActivity w x y ≤ (4:ℝ)^K) + (e : BagEdge (sourceBags w K)) : + bagHeight w K e.val.val.2/D ≤ sourceBagWeight w K D e ∧ + sourceBagWeight w K D e ≤ 3*bagHeight w K e.val.val.2 := by + have hr := sourceRealPortion_nonneg w hw K e + have hu := sourceRealPortion_le_height w K hK e + have hq : bagHeight w K e.val.val.2/(D:ℝ) ≤ bagHeight w K e.val.val.2 := + div_le_self (bagHeight_pos _ _ _).le (by exact_mod_cast hD) + dsimp [sourceBagWeight] + constructor <;> linarith + +lemma sourceBagWeight_global (w : V → V → ℝ) (K D : ℕ) (hD : 1 ≤ D) + (hw : ∀ x y,0 < w x y) (hK : ∀ x y,x≠y → edgeActivity w x y ≤ (4:ℝ)^K) + (e : BagEdge (sourceBags w K)) : + (D:ℝ)⁻¹ ≤ sourceBagWeight w K D e ∧ sourceBagWeight w K D e ≤ 3*4^K := by + have hh := sourceBagWeight_range w K D hD hw hK e + constructor + · calc + (D:ℝ)⁻¹ = 1/(D:ℝ) := (one_div _).symm + _ ≤ bagHeight w K e.val.val.2/(D:ℝ) := + div_le_div_of_nonneg_right (bagHeight_one w K e.val.val.2) (Nat.cast_nonneg D) + _ ≤ _ := hh.1 + · exact hh.2.trans (mul_le_mul_of_nonneg_left (bagHeight_le w K _) (by norm_num)) + +noncomputable def sourceD (K : ℕ) : ℕ := + 100*Fintype.card (SourceVertex V K)^2*(100000000*(Fintype.card V+1)^4) + +lemma sourceD_one (K : ℕ) : 1 ≤ sourceD (V:=V) K := by + have hn : 0 < Fintype.card (SourceVertex V K) := Fintype.card_pos + have hp : 0 < sourceD (V:=V) K := by + dsimp [sourceD] + positivity + omega + +omit [Nontrivial V] in +lemma sourceD_cast [Nontrivial V] (K : ℕ) : + (sourceD (V:=V) K:ℝ)=inflationScale (V:=SourceVertex V K) (holeScale V) := by + simp only [sourceD,inflationScale,holeScale,Nat.cast_mul,Nat.cast_pow,Nat.cast_add,Nat.cast_one,Nat.cast_ofNat] + +end MatchingFPRAS.Enlargement + +end OAI diff --git a/lean/OAI/Combinatorics/MatchingCount/Graphs/Mate.lean b/lean/OAI/Combinatorics/MatchingCount/Graphs/Mate.lean new file mode 100644 index 0000000000000000000000000000000000000000..7eb07f9ac610f51a7ac106100bc52b0d5f1b3aa2 --- /dev/null +++ b/lean/OAI/Combinatorics/MatchingCount/Graphs/Mate.lean @@ -0,0 +1,392 @@ +import Mathlib + +namespace OAI + +namespace MatchingFPRAS.Switching + +open Finset +open scoped Classical symmDiff + +theorem degree_one_card_le_two {V : Type*} [Fintype V] + (G : SimpleGraph V) [DecidableRel G.Adj] + (hc : G.Connected) (hd : ∀ v, G.degree v ≤ 2) : + (Finset.univ.filter fun v => G.degree v = 1).card ≤ 2 := by + classical + have hv := hc.card_vert_le_card_edgeSet_add_one + rw [Nat.card_eq_fintype_card, Nat.card_eq_fintype_card, + ← G.edgeFinset_card] at hv + have hs : (∑ v, G.degree v) + + (Finset.univ.filter fun v => G.degree v = 1).card ≤ 2 * Fintype.card V := by + calc + _ = ∑ v, (G.degree v + if G.degree v = 1 then 1 else 0) := by + simp [Finset.sum_add_distrib] + _ ≤ ∑ _v : V, 2 := by + apply Finset.sum_le_sum + intro v _ + split_ifs with h + · omega + · simp only [add_zero] + exact hd v + _ = _ := by simp [mul_comm] + rw [G.sum_degrees_eq_twice_card_edges] at hs + omega + +theorem degree_one_pair {V : Type*} [Fintype V] + (G : SimpleGraph V) [DecidableRel G.Adj] + (hc : G.Connected) (hd : ∀ v, G.degree v ≤ 2) + (a : V) (ha : G.degree a = 1) : + ∃ b, b ≠ a ∧ ∀ v, G.degree v = 1 ↔ v = a ∨ v = b := by + classical + let s := Finset.univ.filter fun v => G.degree v = 1 + have he : Even s.card := by + convert G.even_card_odd_degree_vertices using 2 + ext v + simp only [s, Finset.mem_filter, Finset.mem_univ, true_and] + have := hd v + interval_cases hdeg : G.degree v <;> norm_num + have hle : s.card ≤ 2 := degree_one_card_le_two G hc hd + have hpos : 0 < s.card := Finset.card_pos.mpr ⟨a, by simp [s, ha]⟩ + have hcard : s.card = 2 := by obtain ⟨k, hk⟩ := he; omega + obtain ⟨x, y, hxy, hs⟩ := Finset.card_eq_two.mp hcard + have ham : a = x ∨ a = y := by simpa [hs] using (show a ∈ s by simp [s, ha]) + rcases ham with rfl | rfl + · refine ⟨y, Ne.symm hxy, ?_⟩ + intro v + have hm : v ∈ s ↔ G.degree v = 1 := by simp [s] + rw [← hm, hs] + simp + · refine ⟨x, hxy, ?_⟩ + intro v + have hm : v ∈ s ↔ G.degree v = 1 := by simp [s] + rw [← hm, hs] + simp [or_comm] + +abbrev Mate (V : Type*) := {m : V → V // Function.Involutive m} + +variable {V : Type*} + +@[simp] theorem mate_mate (m : Mate V) (v : V) : m.1 (m.1 v) = v := m.2 v + +def overlay (m n : Mate V) : SimpleGraph V where + Adj v w := (m.1 v = w ∧ v ≠ w) ∨ (n.1 v = w ∧ v ≠ w) + symm := ⟨by + intro v w h + rcases h with ⟨h, hne⟩ | ⟨h, hne⟩ + · exact Or.inl ⟨by rw [← h, mate_mate], Ne.symm hne⟩ + · exact Or.inr ⟨by rw [← h, mate_mate], Ne.symm hne⟩⟩ + loopless := ⟨by intro v; simp⟩ + +@[simp] theorem overlay_adj (m n : Mate V) (v w : V) : + (overlay m n).Adj v w ↔ (m.1 v = w ∧ v ≠ w) ∨ (n.1 v = w ∧ v ≠ w) := Iff.rfl + +theorem overlay_comm (m n : Mate V) : overlay m n = overlay n m := by + ext v w + exact or_comm + +theorem reachable_mate_left (m n : Mate V) (v : V) : + (overlay m n).Reachable v (m.1 v) := by + by_cases hv : m.1 v = v + · rw [hv] + · exact (show (overlay m n).Adj v (m.1 v) from Or.inl ⟨rfl, Ne.symm hv⟩).reachable + +theorem reachable_mate_right (m n : Mate V) (v : V) : + (overlay m n).Reachable v (n.1 v) := by + rw [overlay_comm] + exact reachable_mate_left n m v + +theorem reachable_mate_left_iff (m n : Mate V) (a v : V) : + (overlay m n).Reachable a (m.1 v) ↔ (overlay m n).Reachable a v := by + constructor + · intro h + exact h.trans (reachable_mate_left m n v).symm + · intro h + exact h.trans (reachable_mate_left m n v) + +theorem reachable_mate_right_iff (m n : Mate V) (a v : V) : + (overlay m n).Reachable a (n.1 v) ↔ (overlay m n).Reachable a v := by + rw [overlay_comm] + exact reachable_mate_left_iff n m a v + +noncomputable def switched (m n : Mate V) (a : V) : Mate V := by + classical + refine ⟨fun v => if (overlay m n).Reachable a v then n.1 v else m.1 v, ?_⟩ + intro v + by_cases h : (overlay m n).Reachable a v + · simp [h, reachable_mate_right_iff] + · simp [h, reachable_mate_left_iff] + +@[simp] theorem switched_apply (m n : Mate V) (a v : V) : + (switched m n a).1 v = + if (overlay m n).Reachable a v then n.1 v else m.1 v := by + classical + rfl + +theorem overlay_switched (m n : Mate V) (a : V) : + overlay (switched m n a) (switched n m a) = overlay m n := by + classical + ext v w + by_cases h : (overlay m n).Reachable a v <;> + simp [overlay_adj, switched_apply, overlay_comm n m, h, or_comm] + +@[simp] theorem switched_twice (m n : Mate V) (a : V) : + switched (switched m n a) (switched n m a) a = m := by + classical + apply Subtype.ext + funext v + by_cases h : (overlay m n).Reachable a v <;> + simp [overlay_switched, overlay_comm n m, h] + +theorem switch_injective (a : V) : Function.Injective + (fun p : Mate V × Mate V => (switched p.1 p.2 a, switched p.2 p.1 a)) := by + intro p q h + have h' := congrArg + (fun p : Mate V × Mate V => (switched p.1 p.2 a, switched p.2 p.1 a)) h + simpa using h' + +theorem mates_equal_of_adj (m n : Mate V) {v w : V} + (hvw : (overlay m n).Adj v w) (hv : m.1 v = n.1 v) : m.1 w = n.1 w := by + rcases hvw with ⟨rfl, _⟩ | ⟨rfl, _⟩ + · rw [mate_mate, hv, mate_mate] + · rw [← hv, mate_mate, hv, mate_mate] + +theorem mates_equal_of_reachable (m n : Mate V) {v w : V} + (hvw : (overlay m n).Reachable v w) (hv : m.1 v = n.1 v) : m.1 w = n.1 w := by + rw [SimpleGraph.reachable_iff_reflTransGen] at hvw + induction hvw with + | refl => exact hv + | tail h hAdj ih => exact mates_equal_of_adj m n hAdj ih + +theorem mates_ne_of_reachable (m n : Mate V) {a v : V} + (hav : (overlay m n).Reachable a v) (ha : m.1 a ≠ n.1 a) : m.1 v ≠ n.1 v := + fun hv => ha (mates_equal_of_reachable m n hav.symm hv) + +theorem overlay_degree_le_two [Fintype V] (m n : Mate V) (v : V) : + (overlay m n).degree v ≤ 2 := by + classical + have hs : (overlay m n).neighborFinset v ⊆ {m.1 v, n.1 v} := by + intro w hw + rw [SimpleGraph.mem_neighborFinset, overlay_adj] at hw + rcases hw with ⟨h, _⟩ | ⟨h, _⟩ <;> simp [← h] + calc + _ ≤ ({m.1 v, n.1 v} : Finset V).card := Finset.card_mono hs + _ ≤ 2 := by + calc + _ ≤ ({n.1 v} : Finset V).card + 1 := Finset.card_insert_le _ _ + _ = 2 := by simp + +theorem overlay_degree_one_iff [Fintype V] (m n : Mate V) (v : V) + (hne : m.1 v ≠ n.1 v) : + (overlay m n).degree v = 1 ↔ m.1 v = v ∨ n.1 v = v := by + classical + rw [SimpleGraph.degree_eq_one_iff_existsUnique_adj] + constructor + · intro h + by_contra hn + push Not at hn + have hm : (overlay m n).Adj v (m.1 v) := Or.inl ⟨rfl, Ne.symm hn.1⟩ + have ht : (overlay m n).Adj v (n.1 v) := Or.inr ⟨rfl, Ne.symm hn.2⟩ + exact hne (h.unique hm ht) + · intro h + rcases h with hm | hn + · have hn : n.1 v ≠ v := by intro h; exact hne (hm.trans h.symm) + refine ⟨n.1 v, Or.inr ⟨rfl, Ne.symm hn⟩, ?_⟩ + intro w hw + rcases hw with ⟨he, hne'⟩ | ⟨he, _⟩ + · exact (hne' (hm.symm.trans he)).elim + · exact he.symm + · have hm : m.1 v ≠ v := by intro h; exact hne (h.trans hn.symm) + refine ⟨m.1 v, Or.inl ⟨rfl, Ne.symm hm⟩, ?_⟩ + intro w hw + rcases hw with ⟨he, _⟩ | ⟨he, hne'⟩ + · exact he.symm + · exact (hne' (hn.symm.trans he)).elim + +def restrictMate (m : Mate V) (S : Set V) + (hS : ∀ v, m.1 v ∈ S ↔ v ∈ S) : Mate S := + ⟨fun v => ⟨m.1 v.1, (hS v.1).mpr v.2⟩, + by intro v; apply Subtype.ext; exact m.2 v.1⟩ + +@[simp] theorem restrictMate_apply (m : Mate V) (S : Set V) + (hS : ∀ v, m.1 v ∈ S ↔ v ∈ S) (v : S) : + ((restrictMate m S hS).1 v).1 = m.1 v.1 := rfl + +theorem overlay_restrict (m n : Mate V) (S : Set V) + (hm : ∀ v, m.1 v ∈ S ↔ v ∈ S) (hn : ∀ v, n.1 v ∈ S ↔ v ∈ S) : + overlay (restrictMate m S hm) (restrictMate n S hn) = (overlay m n).induce S := by + ext v w + simp [overlay_adj, SimpleGraph.induce, SimpleGraph.comap, Subtype.ext_iff] + +@[simp] theorem component_mem_iff (m n : Mate V) (a v : V) : + v ∈ ((overlay m n).connectedComponentMk a).supp ↔ (overlay m n).Reachable a v := by + rw [SimpleGraph.ConnectedComponent.mem_supp_iff, SimpleGraph.ConnectedComponent.eq, + SimpleGraph.reachable_comm] + +theorem active_component_endpoints [Fintype V] (m n : Mate V) (a : V) + (hma : m.1 a = a) (hna : n.1 a ≠ a) : + ∃ b : V, b ≠ a ∧ (overlay m n).Reachable a b ∧ + ∀ v, (overlay m n).Reachable a v → + ((m.1 v = v ∨ n.1 v = v) ↔ v = a ∨ v = b) := by + classical + let C := (overlay m n).connectedComponentMk a + have hm : ∀ v, m.1 v ∈ C.supp ↔ v ∈ C.supp := by + intro v + change m.1 v ∈ ((overlay m n).connectedComponentMk a).supp ↔ + v ∈ ((overlay m n).connectedComponentMk a).supp + rw [component_mem_iff, component_mem_iff, reachable_mate_left_iff] + have hn : ∀ v, n.1 v ∈ C.supp ↔ v ∈ C.supp := by + intro v + change n.1 v ∈ ((overlay m n).connectedComponentMk a).supp ↔ + v ∈ ((overlay m n).connectedComponentMk a).supp + rw [component_mem_iff, component_mem_iff, reachable_mate_right_iff] + let mC := restrictMate m C.supp hm + let nC := restrictMate n C.supp hn + let aC : C.supp := ⟨a, by change (overlay m n).connectedComponentMk a = C; rfl⟩ + have hco : (overlay mC nC).Connected := by + dsimp only [mC, nC] + rw [overlay_restrict] + exact C.connected_toSimpleGraph + have hdiff : ∀ v : C.supp, mC.1 v ≠ nC.1 v := by + intro v he + have hval := congrArg Subtype.val he + have hav : (overlay m n).Reachable a v.1 := (component_mem_iff m n a v.1).mp v.2 + have han : m.1 a ≠ n.1 a := by rw [hma]; exact Ne.symm hna + exact mates_ne_of_reachable m n hav han hval + have hda : (overlay mC nC).degree aC = 1 := by + rw [overlay_degree_one_iff mC nC aC (hdiff aC)] + left + apply Subtype.ext + exact hma + obtain ⟨bC, hba, hb⟩ := degree_one_pair (overlay mC nC) hco + (overlay_degree_le_two mC nC) aC hda + refine ⟨bC.1, ?_, (component_mem_iff m n a _).mp bC.2, ?_⟩ + · intro he + exact hba (Subtype.ext he) + · intro v hv + let vC : C.supp := ⟨v, (component_mem_iff m n a v).mpr hv⟩ + have hh := hb vC + rw [overlay_degree_one_iff mC nC vC (hdiff vC)] at hh + simpa only [mC, nC, vC, aC, Subtype.ext_iff, restrictMate_apply] using hh + +noncomputable def weight [Fintype V] [LinearOrder V] (w : V → V → ℝ) + (m : Mate V) : ℝ := ∏ v, if v < m.1 v then w v (m.1 v) else 1 + +theorem weight_nonneg [Fintype V] [LinearOrder V] (w : V → V → ℝ) + (hw : ∀ v z, 0 ≤ w v z) (m : Mate V) : 0 ≤ weight w m := by + apply Finset.prod_nonneg + intro v _ + split_ifs + · exact hw _ _ + · norm_num + +theorem switched_weight [Fintype V] [LinearOrder V] (w : V → V → ℝ) + (m n : Mate V) (a : V) : + weight w (switched m n a) * weight w (switched n m a) = weight w m * weight w n := by + classical + simp only [weight, ← Finset.prod_mul_distrib] + apply Finset.prod_congr rfl + intro v _ + by_cases h : (overlay m n).Reachable a v <;> + simp [switched_apply, overlay_comm n m, h, mul_comm] + +def HasHoles (m : Mate V) (U : Finset V) : Prop := ∀ v, m.1 v = v ↔ v ∈ U + +theorem hasHoles_unique (m : Mate V) {U W : Finset V} + (hU : HasHoles m U) (hW : HasHoles m W) : U = W := by + ext v + exact (hU v).symm.trans (hW v) + +theorem no_holes_iff (m : Mate V) : HasHoles m ∅ ↔ ∀ v, m.1 v ≠ v := by + simp [HasHoles] + +theorem switched_holes_perfect [Fintype V] [DecidableEq V] (m n : Mate V) (U : Finset V) + (hm : HasHoles m U) (hn : HasHoles n ∅) (a : V) (ha : a ∈ U) : + ∃ b ∈ U.erase a, + HasHoles (switched m n a) (U \ {a, b}) ∧ + HasHoles (switched n m a) {a, b} := by + classical + have hnn : ∀ v, n.1 v ≠ v := (no_holes_iff n).mp hn + obtain ⟨b, hba, hab, he⟩ := active_component_endpoints m n a ((hm a).mpr ha) (hnn a) + have he' : ∀ v, (overlay m n).Reachable a v → (m.1 v = v ↔ v = a ∨ v = b) := by + intro v hv + simpa only [hnn v, or_false] using he v hv + have hb : b ∈ U := (hm b).mp ((he' b hab).mpr (Or.inr rfl)) + refine ⟨b, Finset.mem_erase.mpr ⟨hba, hb⟩, ?_, ?_⟩ + · intro v + by_cases hv : (overlay m n).Reachable a v + · have hu : v ∈ U ↔ v = a ∨ v = b := (hm v).symm.trans (he' v hv) + simp [switched_apply, hv, hnn v, hu] + tauto + · have hva : v ≠ a := by rintro rfl; exact hv .rfl + have hvb : v ≠ b := by rintro rfl; exact hv hab + simpa [switched_apply, hv, hva, hvb] using hm v + · intro v + by_cases hv : (overlay m n).Reachable a v + · simpa [switched_apply, overlay_comm n m, hv] using he' v hv + · have hva : v ≠ a := by rintro rfl; exact hv .rfl + have hvb : v ≠ b := by rintro rfl; exact hv hab + simp [switched_apply, overlay_comm n m, hv, hnn v, hva, hvb] + +noncomputable def matchings [Fintype V] (U : Finset V) : Finset (Mate V) := + Finset.univ.filter (fun m => HasHoles m U) + +@[simp] theorem mem_matchings [Fintype V] (m : Mate V) (U : Finset V) : + m ∈ matchings U ↔ HasHoles m U := by simp [matchings] + +noncomputable def partition [Fintype V] [LinearOrder V] + (w : V → V → ℝ) (U : Finset V) : ℝ := ∑ m ∈ matchings U, weight w m + +theorem partition_nonneg [Fintype V] [LinearOrder V] + (w : V → V → ℝ) (hw : ∀ v z, 0 ≤ w v z) (U : Finset V) : 0 ≤ partition w U := + Finset.sum_nonneg (fun _ _ => weight_nonneg w hw _) + +theorem hole_partition_comparison [Fintype V] [LinearOrder V] + (w : V → V → ℝ) (hw : ∀ v z, 0 ≤ w v z) (U : Finset V) + (a : V) (ha : a ∈ U) : + partition w U * partition w ∅ ≤ + ∑ b ∈ U.erase a, partition w (U \ {a, b}) * partition w {a, b} := by + classical + let S := (matchings U) ×ˢ (matchings (∅ : Finset V)) + let Q := fun b : V => (matchings (U \ {a, b})) ×ˢ (matchings {a, b}) + let f := fun p : Mate V × Mate V => (switched p.1 p.2 a, switched p.2 p.1 a) + let W := fun p : Mate V × Mate V => weight w p.1 * weight w p.2 + have hi : Function.Injective f := switch_injective a + have hd : (↑(U.erase a) : Set V).PairwiseDisjoint Q := by + intro b hb c hc hbc + apply Finset.disjoint_left.mpr + intro p hp hq + have hpb : HasHoles p.2 {a, b} := + (mem_matchings p.2 _).mp (Finset.mem_product.mp hp).2 + have hpc : HasHoles p.2 {a, c} := + (mem_matchings p.2 _).mp (Finset.mem_product.mp hq).2 + have hbm : b ∈ ({a, c} : Finset V) := (hpc b).mp ((hpb b).mpr (by simp)) + have hba : b ≠ a := (Finset.mem_erase.mp hb).1 + simp only [Finset.mem_insert, Finset.mem_singleton] at hbm + exact hbc (hbm.resolve_left hba) + have himage : S.image f ⊆ (U.erase a).biUnion Q := by + intro p hp + obtain ⟨⟨m, n⟩, hmn, rfl⟩ := Finset.mem_image.mp hp + obtain ⟨hm, hn⟩ := Finset.mem_product.mp hmn + obtain ⟨b, hb, hmb, hnb⟩ := switched_holes_perfect m n U + ((mem_matchings m U).mp hm) ((mem_matchings n ∅).mp hn) a ha + exact Finset.mem_biUnion.mpr ⟨b, hb, + Finset.mem_product.mpr ⟨(mem_matchings _ _).mpr hmb, (mem_matchings _ _).mpr hnb⟩⟩ + calc + partition w U * partition w ∅ = ∑ p ∈ S, W p := by + simp only [S, W, partition, Finset.sum_product, Finset.sum_mul_sum] + _ = ∑ p ∈ S.image f, W p := by + rw [Finset.sum_image hi.injOn] + apply Finset.sum_congr rfl + intro p _ + exact (switched_weight w p.1 p.2 a).symm + _ ≤ ∑ p ∈ (U.erase a).biUnion Q, W p := + Finset.sum_le_sum_of_subset_of_nonneg himage + (fun p _ _ => mul_nonneg (weight_nonneg w hw p.1) (weight_nonneg w hw p.2)) + _ = _ := by + rw [Finset.sum_biUnion hd] + apply Finset.sum_congr rfl + intro b _ + simp only [Q, W, partition, Finset.sum_product, Finset.sum_mul_sum] + +end MatchingFPRAS.Switching + +end OAI diff --git a/lean/OAI/Combinatorics/MatchingCount/Graphs/OnlineGraphInvariant.lean b/lean/OAI/Combinatorics/MatchingCount/Graphs/OnlineGraphInvariant.lean new file mode 100644 index 0000000000000000000000000000000000000000..4326611f3eacc1584ed31e9d28e7ce6462850507 --- /dev/null +++ b/lean/OAI/Combinatorics/MatchingCount/Graphs/OnlineGraphInvariant.lean @@ -0,0 +1,133 @@ +import Mathlib +import OAI.Combinatorics.MatchingCount.Algorithm.OnlineInitial + +namespace OAI + +namespace MatchingFPRAS.OnlineGraph +open TreeTyped TreeFraction ExecutableAdaptive ExecutableScaling ExecutableSource +open PhysicalStream OnlineSchedule + +abbrev Edges := List (ℕ×ℕ) +variable (f : Edges→Edges) (hf : ∀ es e,e∈f es↔e∈es) +def graph (g : GraphData) : GraphData := (g.1,f g.2) +def data (x : SparseStageData) : SparseStageData := + (((graph f x.1.1.1,x.1.1.2),x.1.2),x.2) +def request (x : RequestInput) : RequestInput := (data f x.1,x.2) +def state (x : OnlineTrial.State) : OnlineTrial.State := (request f x.1,x.2) +def seed (x : OnlineInitial.Seed) : OnlineInitial.Seed := (graph f x.1,x.2) +include hf +lemma stageCell (es : Edges) (q : Fraction) (v : Vector) (ij : (ℕ×ℕ)) : + ExecutableAdaptive.stageCell (((f es,q),v),ij)=ExecutableAdaptive.stageCell (((es,q),v),ij) := by + simp only [ExecutableAdaptive.stageCell,rawCell,hf] +lemma stageRow (es : Edges) (q : Fraction) (v : Vector) (vs : List ℕ) (i : ℕ) : + ExecutableAdaptive.stageRow ((((f es,q),v),vs),i)=ExecutableAdaptive.stageRow ((((es,q),v),vs),i) := by + unfold ExecutableAdaptive.stageRow + simp only [stageCell f hf] +lemma stageMatrix (g : GraphData) (fuel : List Bool) (v : Vector) : + ExecutableAdaptive.stageMatrix ((graph f g,fuel),v)=ExecutableAdaptive.stageMatrix ((g,fuel),v) := by + unfold ExecutableAdaptive.stageMatrix cellData graph + simp only [stageRow f hf] +lemma current (x : SparseStageData) : sparseCurrentMatrix (data f x)=sparseCurrentMatrix x := by + exact stageMatrix f hf x.1.1.1 x.1.1.2 x.2 +lemma next (x : SparseStageData) : sparseNextMatrix (data f x)=sparseNextMatrix x := by + exact stageMatrix f hf x.1.1.1 (false::x.1.1.2) x.2 +lemma bag (x : SparseStageData) : sparseBagInput (data f x)=sparseBagInput x := by + unfold sparseBagInput + rw [current f hf] + rfl +lemma generated (x : SparseStageData) : sparseGeneratedInput (data f x)=sparseGeneratedInput x := by + unfold sparseGeneratedInput + rw [bag f hf] + rfl +lemma update (x : SparseStageData) : sparseUpdateData (data f x)=sparseUpdateData x := by + unfold sparseUpdateData + rw [generated f hf,next f hf] + rfl +lemma stage (x : SparseStageData) (bs : List NumericMarking.SampleBits) : + sparseStage (data f x,bs)=sparseStage (x,bs) := by + unfold sparseStage + rw [update f hf] +lemma certificateMatrix (g : GraphData) (v : Vector) : + ExecutableSource.certificateMatrix (graph f g,v)=ExecutableSource.certificateMatrix (g,v) := by + unfold ExecutableSource.certificateMatrix certificateCellData graph + simp only [stageRow f hf] +lemma certificate (x : SparseStageData) (b : NumericMarking.SampleBits) : + sparseCertificate (data f x,b)=sparseCertificate (x,b) := by + unfold sparseCertificate sparseCertificateData sparseCertificateMatrixArg + rw [generated f hf] + change generatedCertificate ((_,ExecutableSource.certificateMatrix (graph f x.1.1.1,x.2)),b)=_ + rw [certificateMatrix f hf] +lemma sourcePrecision (x : RequestInput) : OnlineSchedule.sourcePrecision (request f x)=OnlineSchedule.sourcePrecision x := by + unfold OnlineSchedule.sourcePrecision request + rw [bag f hf] + rfl +lemma sourceRequest (x : RequestInput) : OnlineSchedule.sourceRequest (request f x)=OnlineSchedule.sourceRequest x := by + unfold OnlineSchedule.sourceRequest + rw [sourcePrecision f hf] + change (_,(_,List.range ((sourceTables (sparseBagInput (data f x.1))).1.length)))=_ + rw [bag f hf] + +omit hf in +lemma carry (_ : ∀ edges edge,edge∈f edges↔edge∈edges) + (x : OnlineTrial.State) (y : Fraction×Vector) : + OnlineTrial.carry (state f x,y)=state f (OnlineTrial.carry (x,y)) := rfl +lemma step_mean (x : OnlineTrial.State) (h : OnlineTrial.State→ℚ) : + (OnlineTrial.step (state f x)).mean h=(OnlineTrial.step x).mean (h ∘ state f) := by + unfold OnlineTrial.step OnlineTrial.prepare OnlineStage.execute + simp only [Experiment.mean_map] + change (OnlineSample.many (x.1.2,OnlineSchedule.sourceRequest (request f x.1))).mean + (fun bs=>h (OnlineTrial.carry (state f x,sparseStage (data f x.1.1,bs))))=_ + rw [sourceRequest f hf] + simp only [stage f hf,carry f hf,Function.comp_apply] +lemma fold_mean (as : List Bool) (x : OnlineTrial.State) (h : OnlineTrial.State→ℚ) : + (OnlineTree.foldM OnlineTrial.body as (state f x)).mean h= + (OnlineTree.foldM OnlineTrial.body as x).mean (h ∘ state f) := by + induction as generalizing x h with + | nil => rfl + | cons a as ih => + simp only [OnlineTree.foldM,OnlineTrial.body,Experiment.mean_bind] + rw [step_mean f hf] + change (OnlineTrial.step x).mean (fun y=>(OnlineTree.foldM OnlineTrial.body as (state f y)).mean h)=_ + simp_rw [ih] +lemma checked_mean (x : OnlineTrial.State) (h : Fraction→ℚ) : + (OnlineGuard.checked (state f x)).mean h=(OnlineGuard.checked x).mean h := by + unfold OnlineGuard.checked OnlineGuard.test + simp only [Experiment.mean_map] + change (OnlineSample.many (16,OnlineSchedule.sourceRequest (request f x.1))).mean + (fun bs=>h (OnlineGuard.finish (x.2,OnlineGuard.accept (data f x.1.1,bs))))=_ + rw [sourceRequest f hf] + unfold OnlineGuard.accept + simp only [certificate f hf] +lemma trial_mean (as : List Bool) (x : OnlineTrial.State) (h : Fraction→ℚ) : + (OnlineGuard.trial (as,state f x)).mean h=(OnlineGuard.trial (as,x)).mean h := by + unfold OnlineGuard.trial OnlineTrial.sweep + simp only [Experiment.mean_bind] + rw [fold_mean f hf] + change (OnlineTree.foldM OnlineTrial.body as x).mean (fun y=>(OnlineGuard.checked (state f y)).mean h)=_ + simp_rw [checked_mean f hf] +lemma trials_mean (r : ℕ) (as : List Bool) (x : OnlineTrial.State) (h : List Fraction→ℚ) : + (OnlineAmplification.trials (r,(as,state f x))).mean h=(OnlineAmplification.trials (r,(as,x))).mean h := by + unfold OnlineAmplification.trials + induction r generalizing h with + | zero => rfl + | succ r ih => + simp only [List.replicate_succ,OnlineTree.traverseM,Experiment.mean_bind,Experiment.mean_map] + rw [trial_mean f hf] + simp_rw [ih] +lemma run_mean (r : ℕ) (as : List Bool) (x : OnlineTrial.State) (h : Fraction→ℚ) : + (OnlineAmplification.run (r,(as,state f x))).mean h=(OnlineAmplification.run (r,(as,x))).mean h := by + unfold OnlineAmplification.run + simp only [Experiment.mean_map] + exact trials_mean f hf r as x _ +omit hf in +lemma initialize_eq (x : OnlineInitial.Seed) : + OnlineInitial.initializeInput (seed f x)= + ((OnlineInitial.initializeInput x).1,((OnlineInitial.initializeInput x).2.1,state f (OnlineInitial.initializeInput x).2.2)) := rfl +lemma initialize_mean (x : OnlineInitial.Seed) (h : Fraction→ℚ) : + (OnlineAmplification.run (OnlineInitial.initializeInput (seed f x))).mean h= + (OnlineAmplification.run (OnlineInitial.initializeInput x)).mean h := by + rw [initialize_eq] + exact run_mean f hf _ _ _ h +end MatchingFPRAS.OnlineGraph + +end OAI diff --git a/lean/OAI/Combinatorics/MatchingCount/Graphs/Output.lean b/lean/OAI/Combinatorics/MatchingCount/Graphs/Output.lean new file mode 100644 index 0000000000000000000000000000000000000000..b128090d0aebec531bbd0d25f0b79b40a41f1541 --- /dev/null +++ b/lean/OAI/Combinatorics/MatchingCount/Graphs/Output.lean @@ -0,0 +1,127 @@ +import Mathlib +import OAI.Combinatorics.MatchingCount.Complexity.GuardMachineBase + +namespace OAI + +namespace MatchingFPRAS.ZeroOutput +open Turing MachineCost + +def program (s : Fin 3) : TM1.Stmt Symbol (Fin 3) Unit := + if s=0 then .move .left (.write (fun _ _=>6) (.move .right (.goto (fun _ _=>1)))) + else if s=1 then .branch (fun a _=>a==0) (.goto (fun _ _=>2)) + (.write (fun _ _=>0) (.move .right (.goto (fun _ _=>1)))) + else .branch (fun a _=>a==6) + (.write (fun _ _=>0) (.move .right + (.write (fun _ _=>4) (.move .right + (.write (fun _ _=>3) (.move .right + (.write (fun _ _=>2) (.move .right + (.write (fun _ _=>3) (.move .left (.move .left (.move .left .halt)))))))))))) + (.move .left (.goto (fun _ _=>2))) +abbrev cfg (s : Option (Fin 3)) (L R : List Symbol) : TM1.Cfg Symbol (Fin 3) Unit := + ⟨s,(),Tape.mk₂ L R⟩ +lemma zero_blank : ListBlank.mk [(0:Symbol)]=ListBlank.mk [] := by + apply Quotient.sound + exact Or.inr ⟨1,rfl⟩ +lemma start (input : List Symbol) : + advance (TM1.step program) (TM1.init input)=cfg (some 1) [6] input := by + simp [advance,TM1.step,program,TM1.stepAux,TM1.init,cfg,Tape.mk₁,Tape.mk₂,Tape.mk',Tape.move,Tape.write] +lemma erase_step (a : Symbol) (L R : List Symbol) (ha : a≠0) : + advance (TM1.step program) (cfg (some 1) L (a::R))=cfg (some 1) (0::L) R := by + have hb : (a==0)=false := by simpa using ha + simp [advance,TM1.step,program,TM1.stepAux,cfg,Tape.mk₂,Tape.mk',Tape.move,Tape.write,hb] +lemma erase_run (input : List Symbol) (L : List Symbol) (h : ∀ a∈input,a≠0) : + MachineCost.run (TM1.step program) input.length (cfg (some 1) L input)= + cfg (some 1) (List.replicate input.length 0++L) [] := by + induction input generalizing L with + | nil => rfl + | cons a input ih => + have ha : a≠0:=h a (by simp) + have hi : ∀ b∈input,b≠0:=fun b hb=>h b (by simp [hb]) + rw [List.length_cons,MachineCost.run,erase_step a L input ha,ih (0::L) hi] + simp only [List.replicate_succ',List.append_assoc,List.singleton_append] +lemma switch (L : List Symbol) : + advance (TM1.step program) (cfg (some 1) L [])=cfg (some 2) L [] := by + simp [advance,TM1.step,program,TM1.stepAux,cfg,Tape.mk₂,Tape.mk'] +lemma return_step (L : List Symbol) : + advance (TM1.step program) (cfg (some 2) (0::L) [])=cfg (some 2) L [] := by + simp [advance,TM1.step,program,TM1.stepAux,cfg,Tape.mk₂,Tape.mk',Tape.move] + exact zero_blank +lemma return_run (n : ℕ) : + MachineCost.run (TM1.step program) n (cfg (some 2) (List.replicate n 0++[6]) [])= + cfg (some 2) [6] [] := by + induction n with + | zero => rfl + | succ n ih => + rw [List.replicate_succ,List.cons_append,MachineCost.run,return_step,ih] +lemma return_finish : + MachineCost.run (TM1.step program) 2 (cfg (some 2) [6] [])= + cfg none [] (encodeRat 0) := by + simp [MachineCost.run,advance,TM1.step,program,TM1.stepAux,cfg,Tape.mk₂,Tape.mk',Tape.move,Tape.write, + encodeRat,encodeInt,encodeNat,Nat.bits] + exact zero_blank + +theorem run_zero (input : List Symbol) (h : ∀ a∈input,a≠0) : + MachineCost.run (TM1.step program) (2*input.length+4) (TM1.init input)= + cfg none [] (encodeRat 0) := by + have heq : 2*input.length+4=1+input.length+1+(input.length+2) := by omega + rw [heq,run_add _ (1+input.length+1) (input.length+2),run_add _ (1+input.length) 1, + run_add _ 1 input.length] + change MachineCost.run (TM1.step program) (input.length+2) (advance (TM1.step program) + (MachineCost.run (TM1.step program) input.length (advance (TM1.step program) (TM1.init input)))) = _ + rw [start,erase_run input [6] h,switch,run_add,return_run,return_finish] +lemma cost_bound : programCost program ≤ 13 := by + apply Finset.sup_le + intro s _ + fin_cases s <;> decide + +theorem post_zero (input : List Symbol) (h : ∀ a∈input,a≠0) + (bits : Fin (26*input.length+54) → Bool) : + Outputs (PostCompiler.compiled program) input bits 0 := by + have he:=run_zero input h + apply PostCompiler.compiled_outputs program input (2*input.length+4) + · rw [he] + · rw [he] + exact Tape.mk'_right₀ _ _ + · calc + programCost program*(2*input.length+4)+2 ≤ 13*(2*input.length+4)+2 := + Nat.add_le_add_right (Nat.mul_le_mul_right _ cost_bound) 2 + _ = 26*input.length+54 := by ring +lemma encodeNat_nonblank (n : ℕ) : ∀ a ∈ encodeNat n,a ≠ 0 := by + intro a ha + rcases List.mem_append.mp ha with ha | ha + · obtain ⟨b,hb,rfl⟩:=List.mem_map.mp ha + split <;> decide + · simp only [List.mem_singleton] at ha + subst a + decide +lemma encodeInt_nonblank (z : ℤ) : ∀ a ∈ encodeInt z,a ≠ 0 := by + intro a ha + rcases List.mem_append.mp ha with ha | ha + · split_ifs at ha <;> simp only [List.mem_singleton] at ha <;> subst a <;> decide + · exact encodeNat_nonblank _ a ha +lemma encodeRat_nonblank (q : ℚ) : ∀ a ∈ encodeRat q,a ≠ 0 := by + intro a ha + rcases List.mem_append.mp ha with ha | ha + · exact encodeInt_nonblank _ a ha + · exact encodeNat_nonblank _ a ha +lemma encodeInput_nonblank (G : GraphInput) (ε δ : ℚ) : + ∀ a ∈ encodeInput G ε δ,a ≠ 0 := by + intro a ha + simp only [encodeInput,List.mem_append] at ha + rcases ha with (((ha|ha)|ha)|ha)|ha + · exact encodeNat_nonblank _ a ha + · exact encodeNat_nonblank _ a ha + · obtain ⟨e,he,ha⟩:=List.mem_flatMap.mp ha + rcases List.mem_append.mp ha with ha | ha + · exact encodeNat_nonblank _ a ha + · exact encodeNat_nonblank _ a ha + · exact encodeRat_nonblank _ a ha + · exact encodeRat_nonblank _ a ha + +theorem post_zero_input (G : GraphInput) (ε δ : ℚ) + (bits : Fin (26*(encodeInput G ε δ).length+54) → Bool) : + Outputs (PostCompiler.compiled program) (encodeInput G ε δ) bits 0 := + post_zero _ (encodeInput_nonblank G ε δ) bits +end MatchingFPRAS.ZeroOutput + +end OAI diff --git a/lean/OAI/Combinatorics/MatchingCount/Graphs/PM.lean b/lean/OAI/Combinatorics/MatchingCount/Graphs/PM.lean new file mode 100644 index 0000000000000000000000000000000000000000..078a7e24db7d7c9a326c66ee139f2e24f5f2cef6 --- /dev/null +++ b/lean/OAI/Combinatorics/MatchingCount/Graphs/PM.lean @@ -0,0 +1,310 @@ +import Mathlib +import OAI.Combinatorics.MatchingCount.Sampling.LadderL +import OAI.Combinatorics.MatchingCount.Graphs.MatchingMap + +namespace OAI + +namespace MatchingFPRAS.Enlargement + +open MatchingFPRAS.Switching MatchingFPRAS.Subdivision MatchingFPRAS.RealGeometry +open MatchingFPRAS.Hierarchy MatchingFPRAS.Transport Finset +open MatchingFPRAS.Replica MatchingFPRAS.Replica.Ladder + +variable {V : Type*} [Fintype V] [LinearOrder V] [Nontrivial V] + +noncomputable local instance (w : V → V → ℝ) (K : ℕ) : DecidableEq (SourceLabel w K) := Classical.decEq _ + +noncomputable local instance (w : V → V → ℝ) (K : ℕ) : Fintype (BagEdge (sourceBags w K)) := Fintype.ofFinite _ + +abbrev SourcePM (w : V → V → ℝ) (K : ℕ) := PM (BagEdge.Incident (bags:=sourceBags w K)) + +noncomputable local instance (w : V → V → ℝ) (K : ℕ) : DecidableEq (SourcePM w K) := Classical.decEq _ + +omit [Nontrivial V] in +lemma sourceVertex_card_ge (K : ℕ) : Fintype.card V ≤ Fintype.card (SourceVertex V K) := by + exact Fintype.card_le_of_injective (Sum.inl : V → SourceVertex V K) Sum.inl_injective + +theorem source_ladder_sampling (hn : 2 ≤ Fintype.card V) + (w : V → V → ℝ) (hw : ∀ x y, 0 < w x y) (K : ℕ) + (hK : ∀ x y, x ≠ y → edgeActivity w x y ≤ (4:ℝ)^K) + (M₀ : SourcePM w K) (T : ℕ) + (z : Slot T (ladderQ (Fintype.card (SourceVertex V K)) (sourceD (V:=V) K)) → SourcePM w K) + (ξ : ℝ) (hξ : 0 < ξ) (hξ1 : ξ < 1) : + let D := sourceD (V:=V) K + let N := Fintype.card (SourceVertex V K) + let wt := sourceBagWeight w K D + let ν := ladderLaw wt T (ladderQ N D) + let C := ladderFlow (fun x a ha b hb => sourceBag_tree_adjacent w K hK x a b ha hb) (sourceTree_isTree w K).2 wt T (ladderQ N D) + (∑ s, |MatchingFPRAS.FiniteChain.walk ν C z (ladderSteps N D K T ξ) s-ν s|)/2 ≤ ξ := by + classical + dsimp only + apply ideal_ladder_sampling (fun x a ha b hb => sourceBag_tree_adjacent w K hK x a b ha hb) (sourceTree_isTree w K).2 + (bagHeight w K) (bagHeight_pos w K) (bagHeight_adjacent w K) + (sourceD (V:=V) K) K (sourceD_one K) (hn.trans (sourceVertex_card_ge K)) + (sourceBagWeight w K (sourceD (V:=V) K)) + (sourceBagWeight_range w K _ (sourceD_one K) hw hK) + (sourceBagWeight_global w K _ (sourceD_one K) hw hK) M₀ T z ξ hξ hξ1 + +end MatchingFPRAS.Enlargement + +namespace MatchingFPRAS.Subdivision + +open Finset + +def probeHoles (p : ℕ) (hp : 1≤p) : Finset (Fin (4*p)) := + {⟨2*p-1,by omega⟩,⟨2*p,by omega⟩} + +def probeWord (p : ℕ) : Selection (4*p) := + fun i => if i.val=2*p then false else alternating true i.val + +lemma probeWord_valid (p : ℕ) (hp : 1≤p) : Valid (probeHoles p hp) (probeWord p) := by + intro i + by_cases h : i.val=2*p-1 ∨ i.val=2*p + · have hm : i∈probeHoles p hp := by simpa [probeHoles,Fin.ext_iff] using h + rw [ite_eq_left hm] + rcases h with h | h + · have _hm : i.val%2=1 := by omega + simp [probeWord,Fin.val_castSucc,Fin.val_succ,h,show 2*p-1+1=2*p by omega, + alternating,show (2*p-1)%2=1 by omega,show 2*p-1≠2*p by omega] + · simp [probeWord,Fin.val_castSucc,Fin.val_succ,h,alternating,Nat.add_mod] + · have hm : i∉probeHoles p hp := by simpa [probeHoles,Fin.ext_iff] using h + rw [ite_eq_right hm] + have h₁ : i.val≠2*p := by omega + have h₂ : i.val+1≠2*p := by omega + simp only [probeWord,Fin.val_castSucc,Fin.val_succ,ite_eq_right h₁,ite_eq_right h₂,alternating_succ] + cases alternating true i.val <;> decide + +@[simp] lemma probeWord_first (p : ℕ) (hp : 1≤p) : probeWord p 0=true := by + simp [probeWord,show 0≠2*p by omega] + +@[simp] lemma probeWord_last (p : ℕ) (hp : 1≤p) : probeWord p (Fin.last (4*p))=true := by + simp [probeWord,show 4*p≠2*p by omega,alternating,Nat.mul_mod] + +lemma probeHoles_nonempty (p : ℕ) (hp : 1≤p) : (probeHoles p hp).Nonempty := by + simp [probeHoles] + +lemma probeWord_unique (p : ℕ) (hp : 1≤p) (b : Selection (4*p)) + (hb : Valid (probeHoles p hp) b) : b=probeWord p := + broken_unique (probeHoles_nonempty p hp) hb (probeWord_valid p hp) + +lemma probe_weight (p : ℕ) (B Hu Hv lam : ℝ) : + selectedWeight (profileActivity p B Hu Hv lam) (probeWord p)= + (∏ r : Fin p,max B (Hu/2^r.val))*(∏ r : Fin p,max B (Hv/2^r.val)) := by + have he : selectedWeight (profileActivity p B Hu Hv lam) (probeWord p)= + selectedWeight (profileActivity p B Hu Hv 1) (fun i => alternating true i.val) := by + unfold selectedWeight + apply Finset.prod_congr rfl + intro i _ + by_cases hi : i.val=2*p + · have hfi : i=⟨2*p,by omega⟩ := Fin.ext hi + rw [hfi] + simp [probeWord,alternating] + · simp only [probeWord,ite_eq_right hi] + congr 1 + rcases lt_or_gt_of_ne hi with h | h + · rw [profile_left _ _ _ _ _ _ h,profile_left _ _ _ _ _ _ h] + · rw [profile_right _ _ _ _ _ _ h,profile_right _ _ _ _ _ _ h] + rw [he,exact_profile_weight] + simp + + +variable {V E : Type*} [Fintype V] [Fintype E] [DecidableEq V] [DecidableEq E] + +variable (u v : E → V) (p : ℕ) (hp : 1≤p) (e₀ : E) + +def singleProbeHoles (e : E) : Finset (Fin (4*p)) := + if e=e₀ then probeHoles p hp else ∅ + +@[simp] lemma broken_singleProbe : broken (singleProbeHoles p hp e₀)={e₀} := by + ext e + by_cases he : e=e₀ <;> simp [singleProbeHoles,he,probeHoles_nonempty] + +omit [Fintype V] [Fintype E] [DecidableEq V] in +lemma singleProbe_word (b : E → Selection (4*p)) + (hb : FamilyHoles u v (4*p) ∅ (singleProbeHoles p hp e₀) b) : b e₀=probeWord p := by + exact probeWord_unique p hp (b e₀) (by simpa [singleProbeHoles] using hb.1 e₀) + +lemma residual_singleProbe (b : E → Selection (4*p)) + (hb : FamilyHoles u v (4*p) ∅ (singleProbeHoles p hp e₀) b) : + residualHoles u v ∅ (singleProbeHoles p hp e₀) b={u e₀,v e₀} := by + ext x + simp only [mem_residualHoles,notMem_empty,broken_singleProbe,mem_singleton, + exists_eq_left,false_or,Uses,singleProbe_word u v p hp e₀ b hb, + probeWord_first p hp,probeWord_last p hp,true_and,mem_insert,mem_singleton] + exact or_congr eq_comm eq_comm + +def insertProbe (s : E → Bool) (e : E) : Selection (4*p) := + if e=e₀ then probeWord p else fun i => alternating (s e) i.val + +include hp in +omit [Fintype V] [Fintype E] [DecidableEq V] in +lemma insertProbe_uses (s : E → Bool) (e : E) (x : V) : + Uses u v (insertProbe p e₀ s) e x ↔ + if e=e₀ then u e₀=x ∨ v e₀=x else s e=true ∧ (u e=x ∨ v e=x) := by + by_cases he : e=e₀ + · subst e; simp [Uses,insertProbe,probeWord_first p hp,probeWord_last p hp] + · simp [Uses,insertProbe,he,alternating,and_or_left,Nat.mul_mod] + +omit [Fintype V] [Fintype E] in +lemma insertProbe_family (_hne : u e₀≠v e₀) (s : E → Bool) + (hs : LogicalHoles u v {u e₀,v e₀} {e₀} s) : + FamilyHoles u v (4*p) ∅ (singleProbeHoles p hp e₀) (insertProbe p e₀ s) := by + refine ⟨?_,by simp,?_⟩ + · intro e + by_cases he : e=e₀ + · subst e; simpa [singleProbeHoles,insertProbe] using probeWord_valid p hp + · simpa [singleProbeHoles,insertProbe,he] using alternating_valid (4*p) (s e) + · intro x _ + by_cases hx : x∈({u e₀,v e₀} : Finset V) + · refine ⟨e₀,?_,?_⟩ + · change Uses u v (insertProbe p e₀ s) e₀ x + rw [insertProbe_uses u v p hp e₀,ite_eq_left rfl] + simpa only [mem_insert,mem_singleton,eq_comm] using hx + · intro e he + by_contra hen + rw [insertProbe_uses u v p hp e₀,ite_eq_right hen] at he + exact hs.2.1 x hx e he + · obtain ⟨e,he,hu⟩ := hs.2.2 x hx + have he₀ : e≠e₀ := by + intro h + subst e + exact (Bool.noConfusion (he.1.symm.trans (hs.1 e₀ (mem_singleton_self _)))) + refine ⟨e,(insertProbe_uses u v p hp e₀ s e x).mpr (by simpa [he₀] using he),?_⟩ + intro f hf + by_cases hf₀ : f=e₀ + · subst f + rw [insertProbe_uses u v p hp e₀,ite_eq_left rfl] at hf + exact False.elim (hx (by simpa only [mem_insert,mem_singleton,eq_comm] using hf)) + · rw [insertProbe_uses u v p hp e₀,ite_eq_right hf₀] at hf + exact hu f hf + +omit [Fintype V] [DecidableEq V] in +lemma singleProbe_deletionConstant (b : E → Selection (4*p)) + (hb : FamilyHoles u v (4*p) ∅ (singleProbeHoles p hp e₀) b) + (B Hu Hv lam : E → ℝ) : + deletionConstant (singleProbeHoles p hp e₀) b + (fun e => profileActivity p (B e) (Hu e) (Hv e) (lam e)) + (fun e => (∏ r : Fin p,max (B e) (Hu e/2^r.val))*(∏ r : Fin p,max (B e) (Hv e/2^r.val))) = + ∏ e,(∏ r : Fin p,max (B e) (Hu e/2^r.val))*(∏ r : Fin p,max (B e) (Hv e/2^r.val)) := by + unfold deletionConstant + apply Finset.prod_congr rfl + intro e _ + by_cases he : e=e₀ + · subst e + simp only [singleProbeHoles,probeHoles_nonempty,ite_true, + singleProbe_word u v p hp e₀ b hb,probe_weight] + · simp [singleProbeHoles,he] + +theorem singleProbe_partition (hne : u e₀≠v e₀) (B Hu Hv lam : E → ℝ) : + realHolePartition u v (4*p) ∅ (singleProbeHoles p hp e₀) + (fun e => profileActivity p (B e) (Hu e) (Hv e) (lam e)) = + (∏ e,(∏ r : Fin p,max (B e) (Hu e/2^r.val))*(∏ r : Fin p,max (B e) (Hv e/2^r.val))) * + logicalHolePartition u v {u e₀,v e₀} {e₀} lam := by + classical + by_cases h : ∃ b,FamilyHoles u v (4*p) ∅ (singleProbeHoles p hp e₀) b + · obtain ⟨b,hb⟩ := h + have hid := deletion_partition_identity (show Even (4*p) from ⟨2*p,by omega⟩) + u v ∅ (singleProbeHoles p hp e₀) b hb + (fun e => profileActivity p (B e) (Hu e) (Hv e) (lam e)) + (fun e => List.ofFn fun r : Fin p => max (B e) (Hu e/2^r.val)) + (fun e => (List.ofFn fun r : Fin p => max (B e) (Hv e/2^r.val)).reverse) lam + (fun e => profileActivity_ofFn p (B e) (Hu e) (Hv e) (lam e)) + simp only [List.prod_reverse,List.prod_ofFn] at hid + rw [singleProbe_deletionConstant u v p hp e₀ b hb,residual_singleProbe u v p hp e₀ b hb, + broken_singleProbe] at hid + exact hid + · have hl : ¬∃ s,LogicalHoles u v {u e₀,v e₀} {e₀} s := by + rintro ⟨s,hs⟩ + exact h ⟨insertProbe p e₀ s,insertProbe_family u v p hp e₀ hne s hs⟩ + have hz : realHolePartition u v (4*p) ∅ (singleProbeHoles p hp e₀) + (fun e => profileActivity p (B e) (Hu e) (Hv e) (lam e))=0 := by + unfold realHolePartition + apply Finset.sum_eq_zero + intro b _ + exact False.elim (h ⟨b.val,b.property⟩) + have hz' : logicalHolePartition u v {u e₀,v e₀} {e₀} lam=0 := by + unfold logicalHolePartition + apply Finset.sum_eq_zero + intro s _ + exact False.elim (hl ⟨s.val,s.property⟩) + rw [hz,hz',mul_zero] + + +end MatchingFPRAS.Subdivision + +namespace MatchingFPRAS.Representation + +open MatchingFPRAS.Switching MatchingFPRAS.Subdivision MatchingFPRAS.Enlargement Finset + +variable {V : Type*} [Fintype V] [LinearOrder V] + +omit [Fintype V] in +lemma forbidden_endpoint_redundant (R : Finset V) (e₀ : LogicalEdge V) + (he : source e₀∈R) (s : LogicalEdge V → Bool) : + LogicalHoles source target R {e₀} s ↔ LogicalHoles source target R ∅ s := by + constructor + · intro h; exact ⟨by simp,h.2⟩ + · intro h + refine ⟨?_,h.2⟩ + intro e hem + have heq : e=e₀ := mem_singleton.mp hem + subst e + cases hs : s e₀ with + | false => rfl + | true => exact False.elim (h.2.1 (source e₀) he e₀ ⟨hs,Or.inl rfl⟩) + +lemma logical_partition_redundant (w : V → V → ℝ) (R : Finset V) (e₀ : LogicalEdge V) + (he : source e₀∈R) : + logicalHolePartition source target R {e₀} (logicalActivity w)=partition w R := by + classical + let := Fintype.ofFinite {s : LogicalEdge V → Bool // LogicalHoles source target R {e₀} s} + let := Fintype.ofFinite {s : LogicalEdge V → Bool // LogicalHoles source target R ∅ s} + rw [← logical_partition_eq] + unfold logicalHolePartition + apply Fintype.sum_equiv (Equiv.subtypeEquivRight (forbidden_endpoint_redundant R e₀ he)) + intro s + rfl + +end MatchingFPRAS.Representation + +namespace MatchingFPRAS.Enlargement + +open MatchingFPRAS.Switching MatchingFPRAS.Subdivision MatchingFPRAS.RealGeometry +open MatchingFPRAS.Transport MatchingFPRAS.Representation Finset + +variable {V : Type*} [Fintype V] [LinearOrder V] [Nontrivial V] + +noncomputable local instance (w : V → V → ℝ) (K : ℕ) : Fintype (BagEdge (sourceBags w K)) := Fintype.ofFinite _ + +theorem source_probe_partition (w : V → V → ℝ) (K : ℕ) (e₀ : LogicalEdge V) : + partitionWeight BagEdge.Incident (sourceRealPortion w K) + (survivors (4*(2*K+2)) ∅ (singleProbeHoles (2*K+2) (by omega) e₀)) = + (∏ e, pathConstant (2*K+2) (bottleneck w (source e) (target e)) + (sourceHeight w (source e)) (sourceHeight w (target e))) * + partition w {source e₀,target e₀} := by + rw [sourceRealPortion_partition] + change realHolePartition source target (4*(2*K+2)) ∅ + (singleProbeHoles (2*K+2) (by omega) e₀) + (fun e => profileActivity (2*K+2) (bottleneck w (source e) (target e)) + (sourceHeight w (source e)) (sourceHeight w (target e)) (logicalActivity w e)) = _ + rw [singleProbe_partition _ _ _ _ _ (source_ne_target e₀)] + rw [logical_partition_redundant w _ e₀ (by simp)] + rfl + +theorem source_probe_ratio (w : V → V → ℝ) (hz : 0 pathConstant_pos _ _ _ _ + (zero_lt_one.trans_le (one_le_bottleneck w _ _))) + unfold holeRatio + field_simp + +end MatchingFPRAS.Enlargement + +end OAI diff --git a/lean/OAI/Combinatorics/MatchingCount/Graphs/PathActivity.lean b/lean/OAI/Combinatorics/MatchingCount/Graphs/PathActivity.lean new file mode 100644 index 0000000000000000000000000000000000000000..4b216777d7ed4e7d75f0ecb43bc7ca5b8487f11e --- /dev/null +++ b/lean/OAI/Combinatorics/MatchingCount/Graphs/PathActivity.lean @@ -0,0 +1,417 @@ +import Mathlib +import OAI.Combinatorics.MatchingCount.Graphs.FirstHoleSortedCons +import OAI.Combinatorics.MatchingCount.Graphs.Vertex + +namespace OAI + +namespace MatchingFPRAS.Enlargement + +open MatchingFPRAS.Switching MatchingFPRAS.Subdivision MatchingFPRAS.RealGeometry +open Finset + +variable {V E : Type*} [Fintype V] [LinearOrder V] [Fintype E] [LinearOrder E] + +instance vertexLinearOrder (m : ℕ) : LinearOrder (Vertex V E m) := by + letI : LinearOrder (E × Fin m) := LinearOrder.lift' (toLex : E × Fin m → E ×ₗ Fin m) (fun _ _ h => h) + exact LinearOrder.lift' (toLex : V ⊕ (E × Fin m) → V ⊕ₗ (E × Fin m)) (fun _ _ h => h) + +omit [Fintype V] [Fintype E] in +@[simp] lemma terminal_lt_iff (m : ℕ) (a b : V) : + @LT.lt (Vertex V E m) (vertexLinearOrder (V := V) (E := E) m).toLT (Sum.inl a) (Sum.inl b) ↔ a < b := by + change Sum.Lex (· < · : V → V → Prop) _ (Sum.inl a) (Sum.inl b) ↔ a < b + exact Sum.lex_inl_inl + +omit [Fintype V] in +lemma real_threshold_eq [Fintype V] (u v : E → V) (m : ℕ) (hm : 2 ≤ m) + (t : E → Fin (m+1) → ℝ) (τ : ℝ) (hτ : 0 < τ) : + thresholdGraph (activity u v m t) τ=realThreshold u v m t τ := by + ext a b + rw [realThreshold_adj_iff u v m hm t τ hτ] + change (a ≠ b ∧ τ ≤ edgeActivity (activity u v m t) a b) ↔ _ + rw [edgeActivity_of_symmetric _ (activity_symm u v m t)] + +theorem interval_le_bottleneck (u v : E → V) (m : ℕ) (hm : 2 ≤ m) + (huv : ∀ e, u e ≠ v e) (t : E → Fin (m+1) → ℝ) (e : E) + (i j : Fin (m+2)) (hij : i.val < j.val) (T : ℝ) + (ht : ∀ k : Fin (m+1), i.val ≤ k.val → k.val < j.val → T ≤ t e k) : + T ≤ bottleneck (activity u v m t) (atVertex u v m e i) (atVertex u v m e j) := by + by_cases hT : 1 < T + · apply (bottleneck_threshold _ _ _ ?_ T hT).mpr + · rw [real_threshold_eq u v m hm t T (by linarith)] + exact path_interval_reachable u v m t T e i j hij.le ht + · intro he + have := congrArg Fin.val (atVertex_injective u v m e (huv e) he) + omega + · exact (le_of_not_gt hT).trans (one_le_bottleneck _ _ _) + +noncomputable def pathActivity (p : ℕ) (B Hu Hv lam : E → ℝ) : E → Fin (4*p+1) → ℝ := + fun e => profileActivity p (B e) (Hu e) (Hv e) (lam e) + +noncomputable def realBottleneck (u v : E → V) (p : ℕ) (B Hu Hv lam : E → ℝ) : + Vertex V E (4*p) → Vertex V E (4*p) → ℝ := + bottleneck (activity u v (4*p) (pathActivity p B Hu Hv lam)) + +theorem realBottleneck_internal_cap (u v : E → V) (p : ℕ) (hp : 1 ≤ p) + (B Hu Hv lam : E → ℝ) (hB : ∀ e, 1 ≤ B e) (hHu : ∀ e, 0 ≤ Hu e) + (hHv : ∀ e, 0 ≤ Hv e) (hlam : ∀ e, lam e ≤ B e) (e : E) (j : Fin (4*p)) + (a : Vertex V E (4*p)) : + realBottleneck u v p B Hu Hv lam (Sum.inr (e,j)) a ≤ + internalStrength p (B e) (Hu e) (Hv e) j := by + apply bottleneck_le_row_bound + · exact (hB e).trans (le_internalStrength _ _ _ _ _) + · intro b hb + rw [edgeActivity_of_symmetric _ (activity_symm _ _ _ _)] + apply internal_activity_le u v (4*p) (by omega) + · exact (zero_le_one.trans (hB e)).trans (le_internalStrength _ _ _ _ _) + · exact (internalStrength_incident p (B e) (Hu e) (Hv e) (lam e) + (hHu e) (hHv e) (hlam e) j).1 + · exact (internalStrength_incident p (B e) (Hu e) (Hv e) (lam e) + (hHu e) (hHv e) (hlam e) j).2 + +theorem realBottleneck_left_home (u v : E → V) (huv : ∀ e, u e ≠ v e) + (p : ℕ) (hp : 1 ≤ p) (B Hu Hv lam : E → ℝ) (hHu : ∀ e, 0 ≤ Hu e) + (e : E) (j : Fin (4*p)) (hj : j.val < 2*p) : + internalStrength p (B e) (Hu e) (Hv e) j ≤ + realBottleneck u v p B Hu Hv lam (Sum.inr (e,j)) (Sum.inl (u e)) := by + rw [realBottleneck,bottleneck_comm] + have h := interval_le_bottleneck u v (4*p) (by omega) huv + (pathActivity p B Hu Hv lam) e 0 j.succ.castSucc (by simp) _ + (fun k _ hk => internalStrength_left_leg p (B e) (Hu e) (Hv e) (lam e) + (hHu e) j hj k (by simp only [Fin.val_castSucc,Fin.val_succ] at hk; omega)) + simpa only [atVertex_zero,atVertex_internal,atVertex_last,realBottleneck] using h + + theorem realBottleneck_right_home (u v : E → V) (huv : ∀ e, u e ≠ v e) + (p : ℕ) (hp : 1 ≤ p) (B Hu Hv lam : E → ℝ) (hHv : ∀ e, 0 ≤ Hv e) + (e : E) (j : Fin (4*p)) (hj : ¬ j.val < 2*p) : + internalStrength p (B e) (Hu e) (Hv e) j ≤ + realBottleneck u v p B Hu Hv lam (Sum.inr (e,j)) (Sum.inl (v e)) := by + have h := interval_le_bottleneck u v (4*p) (by omega) huv + (pathActivity p B Hu Hv lam) e j.succ.castSucc (Fin.last (4*p+1)) + (by simp only [Fin.val_castSucc,Fin.val_succ,Fin.val_last]; omega) _ + (fun k hk _ => internalStrength_right_leg p (B e) (Hu e) (Hv e) (lam e) + (hHv e) j hj k (by simpa only [Fin.val_castSucc,Fin.val_succ] using hk)) + simpa only [atVertex_zero,atVertex_internal,atVertex_last,realBottleneck] using h + +theorem realBottleneck_path_lower (u v : E → V) (huv : ∀ e, u e ≠ v e) + (p : ℕ) (hp : 1 ≤ p) (B Hu Hv lam : E → ℝ) (hlam : ∀ e, lam e ≤ B e) + (e : E) (i j : Fin (4*p+2)) : + lam e ≤ realBottleneck u v p B Hu Hv lam (atVertex u v (4*p) e i) + (atVertex u v (4*p) e j) ∨ i=j := by + rcases lt_trichotomy i.val j.val with hij | hij | hij + · left + exact interval_le_bottleneck u v (4*p) (by omega) huv (pathActivity p B Hu Hv lam) e i j hij _ + (fun k _ _ => profile_lower p (B e) (Hu e) (Hv e) (lam e) (hlam e) k) + · exact Or.inr (Fin.ext hij) + · left + rw [realBottleneck,bottleneck_comm] + exact interval_le_bottleneck u v (4*p) (by omega) huv (pathActivity p B Hu Hv lam) e j i hij _ + (fun k _ _ => profile_lower p (B e) (Hu e) (Hv e) (lam e) (hlam e) k) + +noncomputable def leftFactor (p : ℕ) (B Hu Hv lam : ℝ) (j : Fin (4*p)) : ℝ := + if j.val < 2*p then 1 else lam / internalStrength p B Hu Hv j + +noncomputable def rightFactor (p : ℕ) (B Hu Hv lam : ℝ) (j : Fin (4*p)) : ℝ := + if j.val < 2*p then lam / internalStrength p B Hu Hv j else 1 + +noncomputable def neutralFactor (p : ℕ) (B Hu Hv lam : ℝ) (j k : Fin (4*p)) : ℝ := + if k.val < 2*p then (internalStrength p B Hu Hv j)⁻¹ + else if j.val < 2*p then lam / (internalStrength p B Hu Hv j * internalStrength p B Hu Hv k) + else (internalStrength p B Hu Hv k)⁻¹ + +lemma leftFactor_eq_potential (p : ℕ) (B Hu Hv lam : ℝ) (j : Fin (4*p)) + (hj : j.val%2=1) : + leftFactor p B Hu Hv lam j = (vertexPotential p B Hu Hv lam (j.val+1))⁻¹ := by + rw [consumed_left_potential p B Hu Hv lam j hj] + unfold leftFactor + split_ifs <;> simp + +lemma rightFactor_eq_potential (p : ℕ) (B Hu Hv lam : ℝ) (hlam : lam ≠ 0) + (j : Fin (4*p)) (hj : j.val%2=0) : + rightFactor p B Hu Hv lam j = lam / vertexPotential p B Hu Hv lam (j.val+1) := by + rw [consumed_right_potential p B Hu Hv lam j hj] + unfold rightFactor + split_ifs <;> simp [hlam] + +lemma neutralFactor_eq_potential (p : ℕ) (B Hu Hv lam : ℝ) (hlam : lam ≠ 0) + (j k : Fin (4*p)) (hjk : j.val < k.val) (hj : j.val%2=0) (hk : k.val%2=1) : + neutralFactor p B Hu Hv lam j k = + (vertexPotential p B Hu Hv lam (j.val+1) * vertexPotential p B Hu Hv lam (k.val+1))⁻¹ := by + rw [consumed_right_potential p B Hu Hv lam j hj,consumed_left_potential p B Hu Hv lam k hk] + unfold neutralFactor + by_cases hk' : k.val < 2*p + · have hj' : j.val < 2*p := by omega + simp [hk',hj'] + · by_cases hj' : j.val < 2*p + · simp [hk',hj',div_eq_mul_inv,mul_inv_rev,inv_inv] + ring + · simp only [ite_eq_right hk',ite_eq_right hj'] + have he : lam * (internalStrength p B Hu Hv k / lam) = internalStrength p B Hu Hv k := by + field_simp [hlam] + rw [he] + +lemma leftFactor_nonneg (p : ℕ) (B Hu Hv lam : ℝ) (hB : 0 < B) (hlam : 0 ≤ lam) + (j : Fin (4*p)) : 0 ≤ leftFactor p B Hu Hv lam j := by + unfold leftFactor + split_ifs + · norm_num + · exact div_nonneg hlam ((hB.trans_le (le_internalStrength _ _ _ _ _)).le) + +lemma rightFactor_nonneg (p : ℕ) (B Hu Hv lam : ℝ) (hB : 0 < B) (hlam : 0 ≤ lam) + (j : Fin (4*p)) : 0 ≤ rightFactor p B Hu Hv lam j := by + unfold rightFactor + split_ifs + · exact div_nonneg hlam ((hB.trans_le (le_internalStrength _ _ _ _ _)).le) + · norm_num + +lemma neutralFactor_nonneg (p : ℕ) (B Hu Hv lam : ℝ) (hB : 0 < B) (hlam : 0 ≤ lam) + (j k : Fin (4*p)) : 0 ≤ neutralFactor p B Hu Hv lam j k := by + have hj := (hB.trans_le (le_internalStrength p B Hu Hv j)).le + have hk := (hB.trans_le (le_internalStrength p B Hu Hv k)).le + unfold neutralFactor + split_ifs + · exact inv_nonneg.mpr hj + · exact div_nonneg hlam (mul_nonneg hj hk) + · exact inv_nonneg.mpr hk + +theorem neutral_local_charge (u v : E → V) (huv : ∀ e, u e ≠ v e) + (p : ℕ) (hp : 1 ≤ p) (B Hu Hv lam : E → ℝ) (hB : ∀ e, 0 < B e) + (hHu : ∀ e, 0 ≤ Hu e) (hHv : ∀ e, 0 ≤ Hv e) (hlam : ∀ e, lam e ≤ B e) + (e : E) (j k : Fin (4*p)) (hjk : j.val < k.val) : + neutralFactor p (B e) (Hu e) (Hv e) (lam e) j k * + internalStrength p (B e) (Hu e) (Hv e) j * internalStrength p (B e) (Hu e) (Hv e) k ≤ + realBottleneck u v p B Hu Hv lam (Sum.inr (e,j)) (Sum.inr (e,k)) := by + have hj0 := hB e |>.trans_le (le_internalStrength p (B e) (Hu e) (Hv e) j) + have hk0 := hB e |>.trans_le (le_internalStrength p (B e) (Hu e) (Hv e) k) + unfold neutralFactor + by_cases hk : k.val < 2*p + · rw [ite_eq_left hk,inv_mul_cancel₀ hj0.ne',one_mul] + have h := interval_le_bottleneck u v (4*p) (by omega) huv + (pathActivity p B Hu Hv lam) e j.succ.castSucc k.succ.castSucc + (by simpa only [Fin.val_castSucc,Fin.val_succ,Nat.add_lt_add_iff_right] using hjk) _ + (fun i _ hi => internalStrength_left_leg p (B e) (Hu e) (Hv e) (lam e) + (hHu e) k hk i (by simp only [Fin.val_castSucc,Fin.val_succ] at hi; omega)) + simpa only [atVertex_zero,atVertex_internal,atVertex_last,realBottleneck] using h + · rw [ite_eq_right hk] + by_cases hj : j.val < 2*p + · rw [ite_eq_left hj] + have heq : lam e / (internalStrength p (B e) (Hu e) (Hv e) j * + internalStrength p (B e) (Hu e) (Hv e) k) * + internalStrength p (B e) (Hu e) (Hv e) j * internalStrength p (B e) (Hu e) (Hv e) k=lam e := by + field_simp [hj0.ne',hk0.ne'] + rw [heq] + have h := interval_le_bottleneck u v (4*p) (by omega) huv + (pathActivity p B Hu Hv lam) e j.succ.castSucc k.succ.castSucc + (by simpa only [Fin.val_castSucc,Fin.val_succ,Nat.add_lt_add_iff_right] using hjk) _ + (fun i _ _ => profile_lower p (B e) (Hu e) (Hv e) (lam e) (hlam e) i) + simpa only [atVertex_zero,atVertex_internal,atVertex_last,realBottleneck] using h + · rw [ite_eq_right hj] + have heq : (internalStrength p (B e) (Hu e) (Hv e) k)⁻¹ * + internalStrength p (B e) (Hu e) (Hv e) j * internalStrength p (B e) (Hu e) (Hv e) k= + internalStrength p (B e) (Hu e) (Hv e) j := by field_simp [hk0.ne'] + rw [heq] + have h := interval_le_bottleneck u v (4*p) (by omega) huv + (pathActivity p B Hu Hv lam) e j.succ.castSucc k.succ.castSucc + (by simpa only [Fin.val_castSucc,Fin.val_succ,Nat.add_lt_add_iff_right] using hjk) _ + (fun i hi _ => internalStrength_right_leg p (B e) (Hu e) (Hv e) (lam e) + (hHv e) j hj i (by simpa only [Fin.val_castSucc,Fin.val_succ] using hi)) + simpa only [atVertex_zero,atVertex_internal,atVertex_last,realBottleneck] using h + +theorem left_local_charge (u v : E → V) (huv : ∀ e, u e ≠ v e) + (p : ℕ) (hp : 1 ≤ p) (B Hu Hv lam : E → ℝ) (hB : ∀ e, 0 < B e) + (hHu : ∀ e, 0 ≤ Hu e) (hlam : ∀ e, lam e ≤ B e) (e : E) (j : Fin (4*p)) : + leftFactor p (B e) (Hu e) (Hv e) (lam e) j * internalStrength p (B e) (Hu e) (Hv e) j ≤ + realBottleneck u v p B Hu Hv lam (Sum.inr (e,j)) (Sum.inl (u e)) := by + have hj0 := hB e |>.trans_le (le_internalStrength p (B e) (Hu e) (Hv e) j) + unfold leftFactor + by_cases hj : j.val < 2*p + · rw [ite_eq_left hj,one_mul] + exact realBottleneck_left_home u v huv p hp B Hu Hv lam hHu e j hj + · rw [ite_eq_right hj,div_mul_cancel₀ _ hj0.ne'] + rw [realBottleneck,bottleneck_comm] + have h := interval_le_bottleneck u v (4*p) (by omega) huv + (pathActivity p B Hu Hv lam) e 0 j.succ.castSucc (by simp) _ + (fun i _ _ => profile_lower p (B e) (Hu e) (Hv e) (lam e) (hlam e) i) + simpa only [atVertex_zero,atVertex_internal] using h + +theorem right_local_charge (u v : E → V) (huv : ∀ e, u e ≠ v e) + (p : ℕ) (hp : 1 ≤ p) (B Hu Hv lam : E → ℝ) (hB : ∀ e, 0 < B e) + (hHv : ∀ e, 0 ≤ Hv e) (hlam : ∀ e, lam e ≤ B e) (e : E) (j : Fin (4*p)) : + rightFactor p (B e) (Hu e) (Hv e) (lam e) j * internalStrength p (B e) (Hu e) (Hv e) j ≤ + realBottleneck u v p B Hu Hv lam (Sum.inr (e,j)) (Sum.inl (v e)) := by + have hj0 := hB e |>.trans_le (le_internalStrength p (B e) (Hu e) (Hv e) j) + unfold rightFactor + by_cases hj : j.val < 2*p + · rw [ite_eq_left hj,div_mul_cancel₀ _ hj0.ne'] + have h := interval_le_bottleneck u v (4*p) (by omega) huv + (pathActivity p B Hu Hv lam) e j.succ.castSucc (Fin.last (4*p+1)) + (by simp only [Fin.val_castSucc,Fin.val_succ,Fin.val_last]; omega) _ + (fun i _ _ => profile_lower p (B e) (Hu e) (Hv e) (lam e) (hlam e) i) + simpa only [atVertex_internal,atVertex_last,realBottleneck] using h + · rw [ite_eq_right hj,one_mul] + exact realBottleneck_right_home u v huv p hp B Hu Hv lam hHv e j hj + +abbrev LogicalEdge (V : Type*) [LinearOrder V] := {q : V × V // q.1 < q.2} + +instance logicalEdgeLinearOrder : LinearOrder (LogicalEdge V) := + LinearOrder.lift' (fun e => toLex e.val) (fun _ _ h => Subtype.ext h) + +def source (e : LogicalEdge V) : V := e.val.1 + +def target (e : LogicalEdge V) : V := e.val.2 + +omit [Fintype V] in +lemma source_ne_target [Fintype V] (e : LogicalEdge V) : source e ≠ target e := e.property.ne + +def logicalActivity (w : V → V → ℝ) (e : LogicalEdge V) : ℝ := + edgeActivity w (source e) (target e) + +omit [Fintype V] in +lemma logical_threshold_eq [Fintype V] (w : V → V → ℝ) (τ : ℝ) : + logicalThreshold source target (logicalActivity w) τ=thresholdGraph w τ := by + ext a b + change (a ≠ b ∧ ∃ e : LogicalEdge V, s(source e,target e)=s(a,b) ∧ τ ≤ logicalActivity w e) ↔ + (a ≠ b ∧ τ ≤ edgeActivity w a b) + constructor + · rintro ⟨hne,e,he,ht⟩ + refine ⟨hne,?_⟩ + rcases Sym2.eq_iff.mp he with he | he + · simpa only [logicalActivity,he.1,he.2] using ht + · simpa only [logicalActivity,he.1,he.2,edgeActivity_comm w b a] using ht + · rintro ⟨hne,ht⟩ + refine ⟨hne,?_⟩ + rcases lt_or_gt_of_ne hne with hab | hab + · exact ⟨⟨(a,b),hab⟩,rfl,ht⟩ + · exact ⟨⟨(b,a),hab⟩,Sym2.eq_swap,by simpa [logicalActivity,source,target,edgeActivity_comm w b a] using ht⟩ + +theorem terminal_bottleneck (w : V → V → ℝ) (p : ℕ) (hp : 1 ≤ p) + (Hu Hv : LogicalEdge V → ℝ) (a b : V) : + realBottleneck source target p (fun e => bottleneck w (source e) (target e)) + Hu Hv (logicalActivity w) (Sum.inl a) (Sum.inl b) = bottleneck w a b := by + by_cases hab : a=b + · subst b; simp [realBottleneck,bottleneck] + apply bottleneck_eq_of_threshold_iff _ w _ _ a b (Sum.inl_injective.ne hab) hab + intro τ hτ + rw [real_threshold_eq source target (4*p) (by omega) _ τ (by linarith)] + rw [terminal_threshold_iff source target (4*p) ⟨2*p,by omega⟩ + (logicalActivity w) (pathActivity p (fun e => bottleneck w (source e) (target e)) Hu Hv (logicalActivity w)) + (fun e => profile_center p _ _ _ _) ?_ τ a b] + · rw [logical_threshold_eq] + · intro e i + exact profile_lower p _ _ _ _ (edgeActivity_le_bottleneck w (source e) (target e) + (source_ne_target e)) i + +noncomputable def enlargedHoles (m : ℕ) (R₀ : Finset V) (U : E → Finset (Fin m)) : + Finset (Vertex V E m) := + R₀.map ⟨Sum.inl,Sum.inl_injective⟩ ∪ + Finset.univ.biUnion (fun e => (U e).map ⟨fun j => Sum.inr (e,j),fun _ _ h => congrArg Prod.snd (Sum.inr_injective h)⟩) + +omit [Fintype V] in +@[simp] lemma mem_enlargedHoles_left [Fintype V] (m : ℕ) (R₀ : Finset V) (U : E → Finset (Fin m)) (x : V) : + Sum.inl x ∈ enlargedHoles m R₀ U ↔ x ∈ R₀ := by + classical + simp [enlargedHoles] + +omit [Fintype V] in +@[simp] lemma mem_enlargedHoles_right [Fintype V] (m : ℕ) (R₀ : Finset V) (U : E → Finset (Fin m)) + (e : E) (j : Fin m) : Sum.inr (e,j) ∈ enlargedHoles m R₀ U ↔ j ∈ U e := by + classical + simp only [enlargedHoles,Finset.mem_union,Finset.mem_map,Finset.mem_biUnion, + Finset.mem_univ,true_and] + constructor + · rintro (⟨x,hx,hxx⟩ | ⟨e',j',hj,hjj⟩) + · change (Sum.inl x : Vertex V E m)=Sum.inr (e,j) at hxx + cases hxx + · have hh := Prod.mk.inj (Sum.inr_injective hjj) + rcases hh with ⟨hee,hjj⟩ + subst e'; subst j'; exact hj + · intro hj; exact Or.inr ⟨e,j,hj,rfl⟩ + +noncomputable def neutralPairs (m : ℕ) (d : E → HoleBlocks m) : + List (Vertex V E m × Vertex V E m) := + Finset.univ.toList.flatMap (fun e => (d e).neutral.map + (fun q => (Sum.inr (e,q.1),Sum.inr (e,q.2)))) + +noncomputable def consumedPairs (u v : E → V) (m : ℕ) (d : E → HoleBlocks m) : + List (Vertex V E m × Vertex V E m) := + Finset.univ.toList.flatMap (fun e => + (d e).left.toList.map (fun j => (Sum.inr (e,j),Sum.inl (u e))) ++ + (d e).right.toList.map (fun j => (Sum.inr (e,j),Sum.inl (v e)))) + +omit [Fintype V] [LinearOrder V] [LinearOrder E] in +lemma tagged_nodup [Fintype V] [LinearOrder V] [LinearOrder E] + {m : ℕ} (xs : E → List (Fin m)) (hx : ∀ e, (xs e).Nodup) : + (Finset.univ.toList.flatMap (fun e => (xs e).map (fun j => (Sum.inr (e,j) : Vertex V E m)))).Nodup := by + apply List.nodup_flatMap.mpr + refine ⟨fun e _ => (hx e).map (fun _ _ h => congrArg Prod.snd (Sum.inr_injective h)),?_⟩ + apply (Finset.nodup_toList _).imp + intro e e' hne + apply List.disjoint_left.mpr + intro a ha ha' + obtain ⟨j,hj,rfl⟩ := List.mem_map.mp ha + obtain ⟨j',hj',he⟩ := List.mem_map.mp ha' + exact hne (congrArg Prod.fst (Sum.inr_injective he)).symm + +omit [Fintype V] [LinearOrder V] [LinearOrder E] in +lemma pairVertices_neutral [Fintype V] [LinearOrder V] [LinearOrder E] + (m : ℕ) (d : E → HoleBlocks m) : + pairVertices (neutralPairs (V := V) m d)= + Finset.univ.toList.flatMap (fun e => + ((d e).neutral.flatMap (fun q => [q.1,q.2])).map (fun j => Sum.inr (e,j))) := by + simp [pairVertices,neutralPairs,List.flatMap_assoc,List.flatMap_map,List.map_flatMap] + +omit [Fintype V] [LinearOrder V] [LinearOrder E] in +lemma consumed_sources [Fintype V] [LinearOrder V] [LinearOrder E] + (u v : E → V) (m : ℕ) (d : E → HoleBlocks m) : + (consumedPairs u v m d).map Prod.fst= + Finset.univ.toList.flatMap (fun e => + ((d e).left.toList++(d e).right.toList).map (fun j => Sum.inr (e,j))) := by + simp [consumedPairs,List.map_flatMap,List.map_append,List.map_map,Function.comp_def] + +theorem source_lists_nodup {m : ℕ} (u v : E → V) (U : E → Finset (Fin m)) + (d : E → HoleBlocks m) (he : ∀ e, (d e).flatten=(U e).sort (· ≤ ·)) : + (pairVertices (neutralPairs (V := V) m d) ++ (consumedPairs u v m d).map Prod.fst).Nodup := by + rw [pairVertices_neutral,consumed_sources] + apply List.nodup_append.mpr + refine ⟨tagged_nodup _ (fun e => (List.nodup_append.mp ((d e).reordered_nodup (he e))).1), + tagged_nodup _ (fun e => (List.nodup_append.mp ((d e).reordered_nodup (he e))).2.1),?_⟩ + intro a ha b hb hab + subst b + obtain ⟨e,he',ha⟩ := List.mem_flatMap.mp ha + obtain ⟨j,hj,rfl⟩ := List.mem_map.mp ha + obtain ⟨e',he'',hb⟩ := List.mem_flatMap.mp hb + obtain ⟨j',hj',heq⟩ := List.mem_map.mp hb + have heq' := Sum.inr_injective heq + cases heq' + exact (List.nodup_append.mp ((d e).reordered_nodup (he e))).2.2 j hj j hj' rfl + +omit [Fintype V] [LinearOrder V] [LinearOrder E] in +@[simp] lemma mem_neutralPairs [Fintype V] [LinearOrder V] [LinearOrder E] + {m : ℕ} (d : E → HoleBlocks m) (q : Vertex V E m × Vertex V E m) : + q ∈ neutralPairs m d ↔ ∃ e r, r ∈ (d e).neutral ∧ q=(Sum.inr (e,r.1),Sum.inr (e,r.2)) := by + classical + simp only [neutralPairs,List.mem_flatMap,Finset.mem_toList,Finset.mem_univ,true_and,List.mem_map] + constructor + · rintro ⟨e,r,hr,he⟩; exact ⟨e,r,hr,he.symm⟩ + · rintro ⟨e,r,hr,rfl⟩; exact ⟨e,r,hr,rfl⟩ + +omit [Fintype V] [LinearOrder V] [LinearOrder E] in +@[simp] lemma mem_consumedPairs [Fintype V] [LinearOrder V] [LinearOrder E] + {m : ℕ} (u v : E → V) (d : E → HoleBlocks m) + (q : Vertex V E m × Vertex V E m) : + q ∈ consumedPairs u v m d ↔ ∃ e j, + (j ∈ (d e).left ∧ q=(Sum.inr (e,j),Sum.inl (u e))) ∨ + (j ∈ (d e).right ∧ q=(Sum.inr (e,j),Sum.inl (v e))) := by + classical + simp only [consumedPairs,List.mem_flatMap,Finset.mem_toList,Finset.mem_univ,true_and, + List.mem_append,List.mem_map,Option.mem_toList] + constructor + · rintro ⟨e,h | h⟩ + · obtain ⟨j,hj,he⟩ := h; exact ⟨e,j,Or.inl ⟨hj,he.symm⟩⟩ + · obtain ⟨j,hj,he⟩ := h; exact ⟨e,j,Or.inr ⟨hj,he.symm⟩⟩ + · rintro ⟨e,j,h | h⟩ + · exact ⟨e,Or.inl ⟨j,h.1,h.2.symm⟩⟩ + · exact ⟨e,Or.inr ⟨j,h.1,h.2.symm⟩⟩ + +end MatchingFPRAS.Enlargement + +end OAI diff --git a/lean/OAI/Combinatorics/MatchingCount/Graphs/PathStrength.lean b/lean/OAI/Combinatorics/MatchingCount/Graphs/PathStrength.lean new file mode 100644 index 0000000000000000000000000000000000000000..34dc7b51c98bbbabc40a5f4f84a53cb4ec01815e --- /dev/null +++ b/lean/OAI/Combinatorics/MatchingCount/Graphs/PathStrength.lean @@ -0,0 +1,432 @@ +import Mathlib +import OAI.Combinatorics.MatchingCount.Graphs.Edge + +namespace OAI + +namespace MatchingFPRAS.Switching +open Finset +open scoped Classical symmDiff + +variable {V : Type*} +theorem sdiff_pair_card [DecidableEq V] (S : Finset V) (a b : V) + (ha : a ∈ S) (hb : b ∈ S) (hab : a ≠ b) : + (S \ {a,b}).card = S.card - 2 := by + have hsub : ({a,b} : Finset V) ⊆ S := by + intro x hx + rcases Finset.mem_insert.mp hx with h | h + · subst x + exact ha + · have he := Finset.mem_singleton.mp h + subst x + exact hb + rw [Finset.card_sdiff_of_subset hsub, Finset.card_pair hab] + +theorem relocated_card [DecidableEq V] (S : Finset V) (a b : V) + (ha : a ∈ S) (hb : b ∉ S) : (insert b (S.erase a)).card = S.card := by + have hba : b ∉ S.erase a := fun h => hb (Finset.mem_of_mem_erase h) + rw [Finset.card_insert_of_notMem hba, Finset.card_erase_add_one ha] + +theorem pair_fill_holeRatio [Fintype V] [LinearOrder V] + (w : V → V → ℝ) (hw : ∀ v z, 0 ≤ w v z) (hz : 0 < partition w ∅) + (a b : V) (hab : a ≠ b) : + edgeActivity w a b * holeRatio w {a,b} ≤ 1 := by + have h := edge_fill_holeRatio w hw hz {a,b} a b (by simp) (by simp) hab + simpa [holeRatio_empty w hz] using h + +theorem adjacent_hole_fill [Fintype V] [LinearOrder V] + (hcard : 2 ≤ Fintype.card V) (w : V → V → ℝ) + (hw : ∀ v z, 0 ≤ w v z) (hz : 0 < partition w ∅) + (hrlo : ∀ a, (1:ℝ)/8 ≤ rowMax hcard w a) + (hrhi : ∀ a, rowMax hcard w a ≤ 4) + (S : Finset V) (hS : S.card = 2 ∨ S.card = 4) + (a b : V) (ha : a ∈ S) (hb : b ∈ S) (hab : a ≠ b) + (B : ℝ) (hB : 0 < B) (hBa : B ≤ edgeActivity w a b) : + holeRatio w S / rowMax hcard w a ≤ 32 / B := by + have hfill := edge_fill_holeRatio w hw hz S a b ha hb hab + have hhole := holeRatio_nonneg w hw S + have hp : B * holeRatio w S ≤ holeRatio w (S \ {a,b}) := + (mul_le_mul_of_nonneg_right hBa hhole).trans hfill + have hs : (S \ {a,b}).card = 0 ∨ (S \ {a,b}).card = 2 := by + rw [sdiff_pair_card S a b ha hb hab] + omega + have hg := zero_or_two_holes_le_four hcard w hz hrhi (S \ {a,b}) hs + have hra := hrlo a + have hrap : 0 < rowMax hcard w a := by linarith + apply (div_le_iff₀ hrap).mpr + rw [div_mul_eq_mul_div] + apply (le_div_iff₀ hB).mpr + nlinarith only [hp,hg,hra] + +theorem toggle_small_holes_card [DecidableEq V] (S : Finset V) (a b : V) + (ha : a ∈ S) (hab : a ≠ b) (hS : S.card = 2 ∨ S.card = 4) : + (S ∆ {a,b}).card = 0 ∨ (S ∆ {a,b}).card = 2 ∨ (S ∆ {a,b}).card = 4 := by + by_cases hb : b ∈ S + · rw [symmDiff_pair_of_mem_mem S a b ha hb, sdiff_pair_card S a b ha hb hab] + omega + · rw [symmDiff_pair_of_mem_notMem S a b ha hb, relocated_card S a b ha hb] + omega + +theorem normalized_relocation [Fintype V] [LinearOrder V] + (hcard : 2 ≤ Fintype.card V) (w : V → V → ℝ) + (hw : ∀ v z, 0 ≤ w v z) (hz : 0 < partition w ∅) + (hrlo : ∀ a, (1:ℝ)/8 ≤ rowMax hcard w a) + (hrhi : ∀ a, rowMax hcard w a ≤ 4) + (S : Finset V) (hS : S.card = 2 ∨ S.card = 4) + (a z : V) (ha : a ∈ S) (hzS : z ∉ S) + (B : ℝ) (hB8 : 8 < B) (hBa : B ≤ edgeActivity w a z) : + holeRatio w S / rowMax hcard w a ≤ + holeRatio w (insert z (S.erase a)) / rowMax hcard w z + 6144 / B := by + have hB : 0 < B := by linarith + have haz : a ≠ z := fun h => hzS (h ▸ ha) + have hrap : ∀ v, 0 < rowMax hcard w v := fun v => by linarith [hrlo v] + obtain ⟨p,hpz,hpr⟩ := rowMax_attained hcard w z + have hfill := pair_fill_holeRatio w hw hz a z haz + have hpair : B * holeRatio w {a,z} ≤ 1 := + (mul_le_mul_of_nonneg_right hBa (holeRatio_nonneg w hw {a,z})).trans hfill + have hpa : p ≠ a := by + intro h + subst p + rw [holeRatio_pair_comm w z a] at hpr + have hlo := hrlo z + rw [← hpr] at hlo + nlinarith + let R := S \ {a,p} + let F := fun b => holeRatio w (S ∆ {a,b}) * holeRatio w ({z,p} ∆ {a,b}) + have hF : ∀ b, 0 ≤ F b := fun b => mul_nonneg + (holeRatio_nonneg w hw _) (holeRatio_nonneg w hw _) + have hcmp := mixed_holeRatio_comparison w hw hz S {z,p} a ha + (by simp [haz, Ne.symm hpa]) + change holeRatio w S * holeRatio w {z,p} ≤ + ∑ b ∈ (S ∆ {z,p}).erase a, F b at hcmp + rw [hpr] at hcmp + have hsub : (S ∆ {z,p}).erase a ⊆ insert z (insert p R) := by + intro x hx + simp only [Finset.mem_erase, Finset.mem_symmDiff, Finset.mem_insert, + Finset.mem_singleton, R, Finset.mem_sdiff] at hx ⊢ + grind + have hcmp' : holeRatio w S * rowMax hcard w z ≤ ∑ b ∈ insert z (insert p R), F b := + hcmp.trans (Finset.sum_le_sum_of_subset_of_nonneg hsub (fun b _ _ => hF b)) + have hzR : z ∉ R := fun h => hzS (Finset.mem_sdiff.mp h).1 + have hpR : p ∉ R := by simp [R] + rw [Finset.sum_insert (by simp [hpz.symm, hzR]), Finset.sum_insert hpR] at hcmp' + have htz : ({z,p} : Finset V) ∆ {a,z} = {a,p} := by + ext v + simp only [Finset.mem_symmDiff, Finset.mem_insert, Finset.mem_singleton] + grind + have htp : ({z,p} : Finset V) ∆ {a,p} = {a,z} := by + ext v + simp only [Finset.mem_symmDiff, Finset.mem_insert, Finset.mem_singleton] + grind + have hFz : F z ≤ holeRatio w (insert z (S.erase a)) * rowMax hcard w a := by + dsimp [F] + rw [symmDiff_pair_of_mem_notMem S a z ha hzS, htz] + exact mul_le_mul_of_nonneg_left (holeRatio_le_rowMax hcard w a p hpa.symm) + (holeRatio_nonneg w hw _) + have hFp : B * F p ≤ 48 := by + have hh := small_holes_le_fortyeight hcard w hw hz hrhi (S ∆ {a,p}) + (toggle_small_holes_card S a p ha hpa.symm hS) + have hn := holeRatio_nonneg w hw (S ∆ {a,p}) + dsimp [F] + rw [htp] + nlinarith only [hpair, hh, hn] + have hFx : ∀ x ∈ R, B * F x ≤ 16 := by + intro x hx + have hxS := (Finset.mem_sdiff.mp hx).1 + have hxa : x ≠ a := by + intro h + exact (Finset.mem_sdiff.mp hx).2 (by simp [h]) + have hxp : x ≠ p := by + intro h + exact (Finset.mem_sdiff.mp hx).2 (by simp [h]) + have hxz : x ≠ z := fun h => hzS (h ▸ hxS) + have ht : ({z,p} : Finset V) ∆ {a,x} = {z,p,a,x} := by + ext v + simp only [Finset.mem_symmDiff, Finset.mem_insert, Finset.mem_singleton] + grind + have hs : (S \ {a,x}).card = 0 ∨ (S \ {a,x}).card = 2 := by + rw [sdiff_pair_card S a x ha hxS hxa.symm] + omega + have hs4 := zero_or_two_holes_le_four hcard w hz hrhi (S \ {a,x}) hs + have hs0 := holeRatio_nonneg w hw (S \ {a,x}) + have hf := edge_fill_holeRatio w hw hz {z,p,a,x} a z (by simp) (by simp) haz + have he : ({z,p,a,x} : Finset V) \ {a,z} = {p,x} := by + ext v + simp only [Finset.mem_sdiff, Finset.mem_insert, Finset.mem_singleton] + grind + rw [he] at hf + have hf' : B * holeRatio w {z,p,a,x} ≤ 4 := by + exact ((mul_le_mul_of_nonneg_right hBa (holeRatio_nonneg w hw _)).trans hf).trans + ((holeRatio_le_rowMax hcard w p x hxp.symm).trans (hrhi p)) + dsimp [F] + rw [ht, symmDiff_pair_of_mem_mem S a x ha hxS] + have hm := mul_le_mul hs4 hf' (mul_nonneg hB.le (holeRatio_nonneg w hw _)) + (by norm_num : (0:ℝ) ≤ 4) + nlinarith only [hm] + have hRsub : R ⊆ S.erase a := by + intro x hx + dsimp [R] at hx + simp only [Finset.mem_sdiff, Finset.mem_insert, Finset.mem_singleton] at hx + simp only [Finset.mem_erase] + grind + have hRcard : R.card ≤ 3 := by + have h := Finset.card_le_card hRsub + have hc := Finset.card_erase_add_one ha + omega + have hsum : B * ∑ x ∈ R, F x ≤ 48 := by + rw [Finset.mul_sum] + calc + ∑ x ∈ R, B * F x ≤ ∑ _x ∈ R, (16:ℝ) := Finset.sum_le_sum hFx + _ = (R.card:ℝ) * 16 := by simp + _ ≤ 48 := by exact_mod_cast (by omega : R.card * 16 ≤ 48) + have hmain : B * holeRatio w S * rowMax hcard w z ≤ + B * holeRatio w (insert z (S.erase a)) * rowMax hcard w a + 96 := by + have hm := mul_le_mul_of_nonneg_left hcmp' hB.le + have hmz := mul_le_mul_of_nonneg_left hFz hB.le + nlinarith only [hm, hmz, hFp, hsum] + have hprod := mul_le_mul (hrlo a) (hrlo z) (by norm_num : (0:ℝ) ≤ 1/8) + (le_of_lt (hrap a)) + apply (div_le_iff₀ (hrap a)).mpr + apply (mul_le_mul_iff_left₀ (mul_pos hB (hrap z))).mp + have he : + ((holeRatio w (insert z (S.erase a)) / rowMax hcard w z + 6144 / B) * + rowMax hcard w a) * (B * rowMax hcard w z) = + B * holeRatio w (insert z (S.erase a)) * rowMax hcard w a + + 6144 * rowMax hcard w a * rowMax hcard w z := by + field_simp [ne_of_gt (hrap z), ne_of_gt hB] + rw [he] + nlinarith only [hmain, hprod] + +theorem normalized_path_relocation [Fintype V] [LinearOrder V] + (hcard : 2 ≤ Fintype.card V) (w : V → V → ℝ) + (hw : ∀ v z, 0 ≤ w v z) (hz : 0 < partition w ∅) + (hrlo : ∀ a, (1:ℝ)/8 ≤ rowMax hcard w a) + (hrhi : ∀ a, rowMax hcard w a ≤ 4) + (B : ℝ) (hB8 : 8 < B) (L : List V) (a : V) + (S : Finset V) (hS : S.card = 2 ∨ S.card = 4) (ha : a ∈ S) + (hpath : List.IsChain (fun x y => B ≤ edgeActivity w x y) (a :: L)) + (hnodup : (a :: L).Nodup) (hend : ∃ j ∈ L, j ∈ S) : + holeRatio w S / rowMax hcard w a ≤ 6144 * L.length / B := by + have hB : 0 < B := by linarith + induction L generalizing a S with + | nil => simp at hend + | cons z L ih => + obtain ⟨hazL, hnd⟩ := List.nodup_cons.mp hnodup + have haz : a ≠ z := fun h => hazL (by simp [h]) + obtain ⟨hBa, hp⟩ := List.isChain_cons_cons.mp hpath + by_cases hzS : z ∈ S + · have hf := adjacent_hole_fill hcard w hw hz hrlo hrhi S hS a z ha hzS haz B hB hBa + apply hf.trans + apply (div_le_div_iff_of_pos_right hB).mpr + simp only [List.length_cons, Nat.cast_add, Nat.cast_one] + have hlen : (0:ℝ) ≤ L.length := Nat.cast_nonneg _ + linarith + · let T := insert z (S.erase a) + have hT : T.card = 2 ∨ T.card = 4 := by + dsimp [T] + rw [relocated_card S a z ha hzS] + exact hS + have he : ∃ j ∈ L, j ∈ T := by + obtain ⟨j,hj,hjS⟩ := hend + have hjz : j ≠ z := fun h => hzS (h ▸ hjS) + have hja : j ≠ a := fun h => hazL (h ▸ hj) + refine ⟨j, ?_, ?_⟩ + · simpa [hjz] using hj + · simp [T, hja, hjS] + have hi := ih z T hT (by simp [T]) hp hnd he + have hs := normalized_relocation hcard w hw hz hrlo hrhi S hS a z ha hzS B hB8 hBa + calc + holeRatio w S / rowMax hcard w a ≤ + holeRatio w T / rowMax hcard w z + 6144 / B := hs + _ ≤ 6144 * (L.length:ℝ) / B + 6144 / B := add_le_add hi le_rfl + _ = 6144 * ((z :: L).length:ℝ) / B := by + simp only [List.length_cons, Nat.cast_add, Nat.cast_one] + ring + +theorem hole_relocation_of_strong_path [Fintype V] [LinearOrder V] + (hcard : 2 ≤ Fintype.card V) (w : V → V → ℝ) + (hw : ∀ v z, 0 ≤ w v z) (hz : 0 < partition w ∅) + (hrlo : ∀ a, (1:ℝ)/8 ≤ rowMax hcard w a) + (hrhi : ∀ a, rowMax hcard w a ≤ 4) + (B : ℝ) (hB : 0 < B) (S : Finset V) (hS : S.card = 2 ∨ S.card = 4) + (a : V) (ha : a ∈ S) + (hpath : 8 < B → ∃ L : List V, + List.IsChain (fun x y => B ≤ edgeActivity w x y) (a :: L) ∧ + (a :: L).Nodup ∧ ∃ j ∈ L, j ∈ S) : + holeRatio w S ≤ 100000 * Fintype.card V / B := by + by_cases hB8 : 8 < B + · obtain ⟨L,hp,hn,he⟩ := hpath hB8 + have hb := normalized_path_relocation hcard w hw hz hrlo hrhi B hB8 L a S hS ha hp hn he + have hra : 0 < rowMax hcard w a := by linarith [hrlo a] + have hb' := (div_le_iff₀ hra).mp hb + have hlen : L.length ≤ Fintype.card V := by + have h := Finset.card_le_card (Finset.subset_univ (a :: L).toFinset) + rw [List.toFinset_card_of_nodup hn, Finset.card_univ] at h + simpa using Nat.le_trans (Nat.le_succ L.length) h + have hlenR : (L.length:ℝ) ≤ Fintype.card V := by exact_mod_cast hlen + apply (le_div_iff₀ hB).mpr + have hmul := mul_le_mul_of_nonneg_right hb' hB.le + have heq : (6144 * (L.length:ℝ) / B * rowMax hcard w a) * B = + 6144 * (L.length:ℝ) * rowMax hcard w a := by field_simp + rw [heq] at hmul + have hm := mul_le_mul_of_nonneg_left (hrhi a) + (by positivity : (0:ℝ) ≤ 6144 * (L.length:ℝ)) + have hn0 : (0:ℝ) ≤ Fintype.card V := Nat.cast_nonneg _ + nlinarith only [hmul,hm,hlenR,hn0] + · have hc := small_holes_le_fortyeight hcard w hw hz hrhi S (by omega) + have hn : (2:ℝ) ≤ Fintype.card V := by exact_mod_cast hcard + have hg0 := holeRatio_nonneg w hw S + apply (le_div_iff₀ hB).mpr + have hm := mul_le_mul_of_nonneg_right (le_of_not_gt hB8) hg0 + nlinarith only [hc,hm,hn] + +noncomputable def pathStrength [LinearOrder V] (w : V → V → ℝ) {a b : V} + (hab : a ≠ b) (p : (⊤ : SimpleGraph V).Path a b) : ℝ := + p.val.darts.toFinset.inf' (by + obtain ⟨d,hd⟩ := List.exists_mem_of_ne_nil p.val.darts + (fun h => hab ((SimpleGraph.Walk.darts_eq_nil.mp h).eq)) + exact ⟨d,List.mem_toFinset.mpr hd⟩) + (fun d => edgeActivity w d.fst d.snd) + +noncomputable def bottleneck [Fintype V] [LinearOrder V] + (w : V → V → ℝ) (a b : V) : ℝ := + if hab : a = b then 1 else + max 1 ((Finset.univ : Finset ((⊤ : SimpleGraph V).Path a b)).sup' + (by exact ⟨SimpleGraph.Path.singleton (by simpa using hab), Finset.mem_univ _⟩) + (pathStrength w hab)) + +theorem one_le_bottleneck [Fintype V] [LinearOrder V] + (w : V → V → ℝ) (a b : V) : 1 ≤ bottleneck w a b := by + unfold bottleneck + split_ifs + · rfl + · exact le_max_left _ _ + +theorem walk_isChain_of_darts [LinearOrder V] {G : SimpleGraph V} + (w : V → V → ℝ) (B : ℝ) {a b : V} (p : G.Walk a b) + (h : ∀ d ∈ p.darts, B ≤ edgeActivity w d.fst d.snd) : + List.IsChain (fun x y => B ≤ edgeActivity w x y) p.support := by + induction p with + | nil => simp + | @cons a c b hadj p ih => + rw [SimpleGraph.Walk.support_cons, ← p.cons_tail_support] + apply List.isChain_cons_cons.mpr + constructor + · exact h ⟨(a,c),hadj⟩ (by simp) + · rw [p.cons_tail_support] + apply ih + intro d hd + exact h d (by simp [hd]) + +theorem bottleneck_path [Fintype V] [LinearOrder V] + (w : V → V → ℝ) (a b : V) (hab : a ≠ b) (hB : 1 < bottleneck w a b) : + ∃ L : List V, + List.IsChain (fun x y => bottleneck w a b ≤ edgeActivity w x y) (a :: L) ∧ + (a :: L).Nodup ∧ b ∈ L := by + obtain ⟨p,hp,hmax⟩ := Finset.exists_mem_eq_sup' + (show (Finset.univ : Finset ((⊤ : SimpleGraph V).Path a b)).Nonempty from + ⟨SimpleGraph.Path.singleton (by simpa using hab), Finset.mem_univ _⟩) + (pathStrength w hab) + have he : bottleneck w a b = pathStrength w hab p := by + unfold bottleneck at hB ⊢ + rw [dite_eq_right hab, hmax] at hB ⊢ + exact max_eq_right ((lt_max_iff.mp hB).resolve_left (lt_irrefl 1)).le + have hd : ∀ d ∈ p.val.darts, bottleneck w a b ≤ edgeActivity w d.fst d.snd := by + intro d hd + rw [he] + exact Finset.inf'_le _ (List.mem_toFinset.mpr hd) + refine ⟨p.val.support.tail, ?_, ?_, ?_⟩ + · rw [p.val.cons_tail_support] + exact walk_isChain_of_darts w _ p.val hd + · rw [p.val.cons_tail_support] + exact p.property.support_nodup + · exact p.val.end_mem_tail_support_of_ne hab + +theorem edgeActivity_mono [LinearOrder V] (w u : V → V → ℝ) + (h : ∀ a b, w a b ≤ u a b) (a b : V) : edgeActivity w a b ≤ edgeActivity u a b := by + unfold edgeActivity + split_ifs <;> apply h + +theorem hole_relocation [Fintype V] [LinearOrder V] + (hcard : 2 ≤ Fintype.card V) (w u : V → V → ℝ) + (hu : ∀ v z, 0 ≤ u v z) (hz : 0 < partition u ∅) + (hwu : ∀ a b, w a b ≤ u a b) + (hrlo : ∀ a, (1:ℝ)/8 ≤ rowMax hcard u a) + (hrhi : ∀ a, rowMax hcard u a ≤ 4) + (S : Finset V) (hS : S.card = 2 ∨ S.card = 4) + (a b : V) (ha : a ∈ S) (hb : b ∈ S) (hab : a ≠ b) : + holeRatio u S ≤ 100000 * Fintype.card V / bottleneck w a b := by + apply hole_relocation_of_strong_path hcard u hu hz hrlo hrhi + (bottleneck w a b) (lt_of_lt_of_le (by norm_num) (one_le_bottleneck w a b)) S hS a ha + intro hs + obtain ⟨L,hp,hn,hbL⟩ := bottleneck_path w a b hab (by linarith) + refine ⟨L, ?_,hn,b,hbL,hb⟩ + exact hp.imp fun {x y} h => h.trans (edgeActivity_mono w u hwu x y) + +noncomputable def erasePair (m : Mate V) (a b : V) : Mate V := by + classical + by_cases h : m.1 a = b + · refine ⟨fun v => if v = a ∨ v = b then v else m.1 v, ?_⟩ + intro v + have hba : m.1 b = a := by rw [← h, mate_mate] + by_cases hv : v = a ∨ v = b + · simp [hv] + · have hma : m.1 v ≠ a := by + intro he + have hh := congrArg m.1 he + rw [mate_mate, h] at hh + exact hv (Or.inr hh) + have hmb : m.1 v ≠ b := by + intro he + have hh := congrArg m.1 he + rw [mate_mate, hba] at hh + exact hv (Or.inl hh) + simp [hv, hma, hmb, mate_mate] + · exact m + +@[simp] theorem erasePair_apply (m : Mate V) (a b v : V) (h : m.1 a = b) : + (erasePair m a b).1 v = if v = a ∨ v = b then v else m.1 v := by + classical + simp [erasePair, h] + +theorem erasePair_holes [DecidableEq V] (m : Mate V) (S : Finset V) + (hm : HasHoles m S) (a b : V) (h : m.1 a = b) : + HasHoles (erasePair m a b) (insert a (insert b S)) := by + intro v + rw [erasePair_apply m a b v h] + by_cases hv : v = a ∨ v = b + · rcases hv with rfl | rfl <;> simp + · have hva := (not_or.mp hv).1 + have hvb := (not_or.mp hv).2 + simp [hva, hvb, hm v] + +theorem withEdge_erasePair (m : Mate V) (a b : V) (h : m.1 a = b) : + withEdge (erasePair m a b) a b = m := by + have hba : m.1 b = a := by rw [← h, mate_mate] + apply Subtype.ext + funext v + rw [withEdge_apply _ _ _ _ (by simp [h]) (by simp [h])] + by_cases hva : v = a + · subst v + simp [h] + by_cases hvb : v = b + · subst v + simp [hba, hva] + simp [hva, hvb, h] + +theorem erasePair_withEdge (m : Mate V) (a b : V) + (ha : m.1 a = a) (hb : m.1 b = b) : + erasePair (withEdge m a b) a b = m := by + apply Subtype.ext + funext v + rw [erasePair_apply _ _ _ _ (by simp [ha,hb]), withEdge_apply m a b v ha hb] + by_cases hva : v = a + · subst v + simp [ha] + by_cases hvb : v = b + · subst v + simp [hb] + simp [hva, hvb] + +end MatchingFPRAS.Switching + +end OAI diff --git a/lean/OAI/Combinatorics/MatchingCount/Graphs/Profile.lean b/lean/OAI/Combinatorics/MatchingCount/Graphs/Profile.lean new file mode 100644 index 0000000000000000000000000000000000000000..3b6f16ffd8a544ce5407348323dabf9b4b731333 --- /dev/null +++ b/lean/OAI/Combinatorics/MatchingCount/Graphs/Profile.lean @@ -0,0 +1,409 @@ +import Mathlib +import OAI.Combinatorics.MatchingCount.Graphs.SumLiftMate + +namespace OAI + +namespace MatchingFPRAS.Subdivision + +open Finset + +lemma valid_step_eq_iff {m : ℕ} {U : Finset (Fin m)} {b c : Selection m} + (hb : Valid U b) (hc : Valid U c) (i : Fin m) : + b i.castSucc = c i.castSucc ↔ b i.succ = c i.succ := by + by_cases hi : i ∈ U + · have hb' := hb i + have hc' := hc i + simp only [hi, ↓reduceIte] at hb' hc' + simp [hb'.1,hb'.2,hc'.1,hc'.2] + · have hb' : b i.succ = !(b i.castSucc) := by + apply (bool_ne_iff_eq_not _ _).mp + simpa only [hi, ↓reduceIte] using hb i + have hc' : c i.succ = !(c i.castSucc) := by + apply (bool_ne_iff_eq_not _ _).mp + simpa only [hi, ↓reduceIte] using hc i + rw [hb',hc'] + simp + +lemma valid_eq_iff_zero {m : ℕ} {U : Finset (Fin m)} {b c : Selection m} + (hb : Valid U b) (hc : Valid U c) (i : Fin (m+1)) : + b i = c i ↔ b 0 = c 0 := by + have aux (k : ℕ) (hk : k < m+1) : b ⟨k,hk⟩ = c ⟨k,hk⟩ ↔ b 0 = c 0 := by + induction k with + | zero => rfl + | succ k ih => + have hk' : k < m := by omega + exact ((valid_step_eq_iff hb hc ⟨k,hk'⟩).symm).trans (ih (by omega)) + exact aux i.val i.isLt + +theorem broken_unique {m : ℕ} {U : Finset (Fin m)} (hU : U.Nonempty) + {b c : Selection m} (hb : Valid U b) (hc : Valid U c) : b = c := by + obtain ⟨j,hj⟩ := hU + have hb' := hb j + have hc' := hc j + simp only [hj, ↓reduceIte] at hb' hc' + have hzero := (valid_eq_iff_zero hb hc j.castSucc).mp (hb'.1.trans hc'.1.symm) + funext i + exact (valid_eq_iff_zero hb hc i).mpr hzero + +noncomputable def profile (p : ℕ) (B Hu Hv lam : ℝ) : List ℝ := + duplicate (List.ofFn fun r : Fin p => max B (Hu / 2^r.val)) ++ [lam] ++ + duplicate ((List.ofFn fun r : Fin p => max B (Hv / 2^r.val)).reverse) + +@[simp] theorem profile_length (p : ℕ) (B Hu Hv lam : ℝ) : + (profile p B Hu Hv lam).length = 4*p+1 := by simp [profile]; omega + +noncomputable def profileActivity (p : ℕ) (B Hu Hv lam : ℝ) (i : Fin (4*p+1)) : ℝ := + (profile p B Hu Hv lam).get (i.cast (profile_length p B Hu Hv lam).symm) + + theorem profileActivity_ofFn (p : ℕ) (B Hu Hv lam : ℝ) : + List.ofFn (profileActivity p B Hu Hv lam) = profile p B Hu Hv lam := by + apply List.ext_getElem + · simp + · intro i hi hj + simp only [List.getElem_ofFn, profileActivity, List.get_eq_getElem, Fin.val_cast] + + theorem exact_profile_weight (p : ℕ) (B Hu Hv lam : ℝ) (a : Bool) : + selectedWeight (profileActivity p B Hu Hv lam) + (fun i => alternating a i.val) = + ((∏ r : Fin p, max B (Hu / 2^r.val)) * + (∏ r : Fin p, max B (Hv / 2^r.val))) * (if a then lam else 1) := by + rw [intact_weight _ _ (alternating_valid _ _),profileActivity_ofFn] + simpa [profile,List.prod_ofFn] using + profile_weight a (List.ofFn fun r : Fin p => max B (Hu / 2^r.val)) + ((List.ofFn fun r : Fin p => max B (Hv / 2^r.val)).reverse) lam + +section Deletion + +variable {V E : Type*} [Fintype V] [Fintype E] + +def Uses {m : ℕ} (u v : E → V) (b : E → Selection m) (e : E) (x : V) : Prop := + (b e 0 = true ∧ u e = x) ∨ (b e (Fin.last m) = true ∧ v e = x) + +def FamilyHoles (u v : E → V) (m : ℕ) (R₀ : Finset V) (U : E → Finset (Fin m)) + (b : E → Selection m) : Prop := + (∀ e, Valid (U e) (b e)) ∧ + (∀ x ∈ R₀, ∀ e, ¬ Uses u v b e x) ∧ + (∀ x ∉ R₀, ∃! e, Uses u v b e x) + +noncomputable def broken {m : ℕ} (U : E → Finset (Fin m)) : Finset E := by + classical + exact Finset.univ.filter fun e => (U e).Nonempty + +@[simp] lemma mem_broken {m : ℕ} (U : E → Finset (Fin m)) (e : E) : + e ∈ broken U ↔ (U e).Nonempty := by + classical + simp [broken] + +noncomputable def residualHoles {m : ℕ} (u v : E → V) (R₀ : Finset V) + (U : E → Finset (Fin m)) (b : E → Selection m) : Finset V := by + classical + exact R₀ ∪ Finset.univ.filter (fun x => ∃ e ∈ broken U, Uses u v b e x) + +@[simp] lemma mem_residualHoles {m : ℕ} (u v : E → V) (R₀ : Finset V) + (U : E → Finset (Fin m)) (b : E → Selection m) (x : V) : + x ∈ residualHoles u v R₀ U b ↔ x ∈ R₀ ∨ ∃ e ∈ broken U, Uses u v b e x := by + classical + simp [residualHoles] + +theorem residualHoles_independent {m : ℕ} (u v : E → V) (R₀ : Finset V) + (U : E → Finset (Fin m)) {b c : E → Selection m} + (hb : FamilyHoles u v m R₀ U b) (hc : FamilyHoles u v m R₀ U c) : + residualHoles u v R₀ U b = residualHoles u v R₀ U c := by + classical + have he (e) (h : e ∈ broken U) : b e = c e := + broken_unique ((mem_broken U e).mp h) (hb.1 e) (hc.1 e) + ext x + simp only [mem_residualHoles] + apply or_congr Iff.rfl + apply exists_congr + intro e + constructor <;> rintro ⟨h,hx⟩ <;> refine ⟨h,?_⟩ + · simpa only [Uses,he e h] using hx + · simpa only [Uses,he e h] using hx + +def LogicalHoles (u v : E → V) (R : Finset V) (forbidden : Finset E) + (s : E → Bool) : Prop := + (∀ e ∈ forbidden, s e = false) ∧ + (∀ x ∈ R, ∀ e, ¬ (s e = true ∧ (u e = x ∨ v e = x))) ∧ + (∀ x ∉ R, ∃! e, s e = true ∧ (u e = x ∨ v e = x)) + +noncomputable def extract {m : ℕ} (U : E → Finset (Fin m)) + (b : E → Selection m) (e : E) : Bool := + if (U e).Nonempty then false else b e 0 + +omit [Fintype V] [Fintype E] in +lemma intact_uses {m : ℕ} (hm : Even m) (u v : E → V) (b : E → Selection m) + (e : E) (x : V) (hb : Valid ∅ (b e)) : + Uses u v b e x ↔ b e 0 = true ∧ (u e = x ∨ v e = x) := by + rw [Uses,intact_terminals hm _ hb] + exact and_or_left.symm + + theorem extract_legal {m : ℕ} (hm : Even m) (u v : E → V) (R₀ : Finset V) + (U : E → Finset (Fin m)) (b : E → Selection m) + (hb : FamilyHoles u v m R₀ U b) : + LogicalHoles u v (residualHoles u v R₀ U b) (broken U) (extract U b) := by + classical + have he (e x) : extract U b e = true ∧ (u e = x ∨ v e = x) ↔ + e ∉ broken U ∧ Uses u v b e x := by + by_cases h : (U e).Nonempty + · simp [extract,h] + · have hu : U e = ∅ := Finset.not_nonempty_iff_eq_empty.mp h + simp only [extract,h,↓reduceIte,mem_broken,not_false_eq_true,true_and] + exact (intact_uses hm u v b e x (by simpa [hu] using hb.1 e)).symm + refine ⟨?_,?_,?_⟩ + · intro e he' + simp [extract,(mem_broken U e).mp he'] + · intro x hx e hxe + rw [he] at hxe + rcases (mem_residualHoles u v R₀ U b x).mp hx with hx | ⟨f,hf,hfx⟩ + · exact hb.2.1 x hx e hxe.2 + · have hx0 : x ∉ R₀ := by intro hx0; exact hb.2.1 x hx0 f hfx + obtain ⟨a,ha,hu⟩ := hb.2.2 x hx0 + have hef : e = f := (hu e hxe.2).trans (hu f hfx).symm + exact hxe.1 (hef.symm ▸ hf) + · intro x hx + have hx0 : x ∉ R₀ := by intro h; exact hx ((mem_residualHoles _ _ _ _ _ _).mpr (Or.inl h)) + obtain ⟨e,he',hu⟩ := hb.2.2 x hx0 + have hn : e ∉ broken U := by + intro h + exact hx ((mem_residualHoles _ _ _ _ _ _).mpr (Or.inr ⟨e,h,he'⟩)) + refine ⟨e,(he e x).mpr ⟨hn,he'⟩,?_⟩ + intro f hf + exact hu f ((he f x).mp hf).2 + +noncomputable def rebuild {m : ℕ} (U : E → Finset (Fin m)) + (base : E → Selection m) (s : E → Bool) (e : E) : Selection m := + if (U e).Nonempty then base e else fun i => alternating (s e) i.val + +omit [Fintype V] in +lemma rebuild_uses {m : ℕ} (hm : Even m) (u v : E → V) + (U : E → Finset (Fin m)) (base : E → Selection m) (s : E → Bool) (e : E) (x : V) : + Uses u v (rebuild U base s) e x ↔ + (e ∈ broken U ∧ Uses u v base e x) ∨ + (e ∉ broken U ∧ s e = true ∧ (u e = x ∨ v e = x)) := by + classical + by_cases h : (U e).Nonempty + · simp [rebuild,h,Uses] + · simp [rebuild,h,Uses,alternating,Nat.even_iff.mp hm,and_or_left] + + theorem rebuild_legal {m : ℕ} (hm : Even m) (u v : E → V) (R₀ : Finset V) + (U : E → Finset (Fin m)) (base : E → Selection m) + (hb : FamilyHoles u v m R₀ U base) (s : E → Bool) + (hs : LogicalHoles u v (residualHoles u v R₀ U base) (broken U) s) : + FamilyHoles u v m R₀ U (rebuild U base s) := by + classical + let R := residualHoles u v R₀ U base + have hu (e x) := rebuild_uses hm u v U base s e x + refine ⟨?_,?_,?_⟩ + · intro e + by_cases he : (U e).Nonempty + · simpa [rebuild,he] using hb.1 e + · have he' : U e = ∅ := Finset.not_nonempty_iff_eq_empty.mp he + simpa [rebuild,he,he'] using alternating_valid m (s e) + · intro x hx e he + have hxR : x ∈ R := (mem_residualHoles _ _ _ _ _ _).mpr (Or.inl hx) + rcases (hu e x).mp he with ⟨_,he⟩ | ⟨_,he⟩ + · exact hb.2.1 x hx e he + · exact hs.2.1 x hxR e he + · intro x hx + by_cases hxR : x ∈ R + · obtain hx0 | ⟨e,he,hxe⟩ := (mem_residualHoles _ _ _ _ _ _).mp hxR + · exact (hx hx0).elim + obtain ⟨a,ha,hauniq⟩ := hb.2.2 x hx + refine ⟨e,(hu e x).mpr (Or.inl ⟨he,hxe⟩),?_⟩ + intro f hf + rcases (hu f x).mp hf with ⟨_,hf⟩ | ⟨_,hf⟩ + · exact (hauniq f hf).trans (hauniq e hxe).symm + · exact (hs.2.1 x hxR f hf).elim + · obtain ⟨e,he,heuniq⟩ := hs.2.2 x hxR + have hen : e ∉ broken U := by + intro he' + have := hs.1 e he' + simp [this] at he + refine ⟨e,(hu e x).mpr (Or.inr ⟨hen,he⟩),?_⟩ + intro f hf + rcases (hu f x).mp hf with ⟨hfb,hf⟩ | ⟨_,hf⟩ + · exact (hxR ((mem_residualHoles _ _ _ _ _ _).mpr (Or.inr ⟨f,hfb,hf⟩))).elim + · exact heuniq f hf + +omit [Fintype V] [Fintype E] in + theorem rebuild_extract [Fintype V] [Fintype E] {m : ℕ} (u v : E → V) (R₀ : Finset V) + (U : E → Finset (Fin m)) (base b : E → Selection m) + (hb0 : FamilyHoles u v m R₀ U base) (hb : FamilyHoles u v m R₀ U b) : + rebuild U base (extract U b) = b := by + classical + funext e i + by_cases he : (U e).Nonempty + · have hbe := broken_unique he (hb0.1 e) (hb.1 e) + simp [rebuild,he,hbe] + · have he' : U e = ∅ := Finset.not_nonempty_iff_eq_empty.mp he + have hl := (intact_iff (b e)).mp (by simpa [he'] using hb.1 e) i + simpa [rebuild,extract,he] using hl.symm + +omit [Fintype V] [Fintype E] in + theorem extract_rebuild [Fintype V] [Fintype E] {m : ℕ} (u v : E → V) (R : Finset V) + (U : E → Finset (Fin m)) (base : E → Selection m) (s : E → Bool) + (hs : LogicalHoles u v R (broken U) s) : + extract U (rebuild U base s) = s := by + classical + funext e + by_cases he : (U e).Nonempty + · have hs' := hs.1 e ((mem_broken U e).mpr he) + simp [extract,he,hs'] + · simp [extract,rebuild,he] + +noncomputable def deletionEquiv {m : ℕ} (hm : Even m) (u v : E → V) (R₀ : Finset V) + (U : E → Finset (Fin m)) (base : E → Selection m) + (hb : FamilyHoles u v m R₀ U base) : + {b : E → Selection m // FamilyHoles u v m R₀ U b} ≃ + {s : E → Bool // LogicalHoles u v (residualHoles u v R₀ U base) (broken U) s} where + toFun b := ⟨extract U b.val, by + have h := extract_legal hm u v R₀ U b.val b.property + rwa [residualHoles_independent u v R₀ U b.property hb] at h⟩ + invFun s := ⟨rebuild U base s.val,rebuild_legal hm u v R₀ U base hb s.val s.property⟩ + left_inv b := Subtype.ext (rebuild_extract u v R₀ U base b.val hb b.property) + right_inv s := Subtype.ext (extract_rebuild u v _ U base s.val s.property) + +noncomputable def realHolePartition (u v : E → V) (m : ℕ) (R₀ : Finset V) + (U : E → Finset (Fin m)) (w : E → Fin (m+1) → ℝ) : ℝ := by + classical + letI := Fintype.ofFinite {b : E → Selection m // FamilyHoles u v m R₀ U b} + exact ∑ b : {b : E → Selection m // FamilyHoles u v m R₀ U b}, + ∏ e, selectedWeight (w e) (b.val e) + +noncomputable def logicalHolePartition (u v : E → V) (R : Finset V) + (forbidden : Finset E) (lam : E → ℝ) : ℝ := by + classical + letI := Fintype.ofFinite {s : E → Bool // LogicalHoles u v R forbidden s} + exact ∑ s : {s : E → Bool // LogicalHoles u v R forbidden s}, + ∏ e, if s.val e then lam e else 1 + +noncomputable def deletionConstant {m : ℕ} (U : E → Finset (Fin m)) + (base : E → Selection m) (w : E → Fin (m+1) → ℝ) (C : E → ℝ) : ℝ := + ∏ e, if (U e).Nonempty then selectedWeight (w e) (base e) else C e + +omit [Fintype V] [Fintype E] in + theorem deletion_weight [Fintype V] [Fintype E] {m : ℕ} (u v : E → V) (R₀ : Finset V) + (U : E → Finset (Fin m)) (base b : E → Selection m) + (hb0 : FamilyHoles u v m R₀ U base) (hb : FamilyHoles u v m R₀ U b) + (w : E → Fin (m+1) → ℝ) (left right : E → List ℝ) (lam : E → ℝ) + (hw : ∀ e, List.ofFn (w e) = duplicate (left e) ++ [lam e] ++ duplicate (right e)) : + (∏ e, selectedWeight (w e) (b e)) = + deletionConstant U base w (fun e => (left e).prod * (right e).prod) * + ∏ e, if extract U b e then lam e else 1 := by + classical + unfold deletionConstant + rw [← Finset.prod_mul_distrib] + apply Finset.prod_congr rfl + intro e _ + by_cases he : (U e).Nonempty + · have heq := broken_unique he (hb0.1 e) (hb.1 e) + simp [extract,he,heq] + · have he' : U e = ∅ := Finset.not_nonempty_iff_eq_empty.mp he + simp only [extract,he,↓reduceIte] + rw [intact_weight _ _ (by simpa [he'] using hb.1 e),hw e,profile_weight] + +theorem deletion_partition_identity {m : ℕ} (hm : Even m) (u v : E → V) (R₀ : Finset V) + (U : E → Finset (Fin m)) (base : E → Selection m) + (hb : FamilyHoles u v m R₀ U base) + (w : E → Fin (m+1) → ℝ) (left right : E → List ℝ) (lam : E → ℝ) + (hw : ∀ e, List.ofFn (w e) = duplicate (left e) ++ [lam e] ++ duplicate (right e)) : + realHolePartition u v m R₀ U w = + deletionConstant U base w (fun e => (left e).prod * (right e).prod) * + logicalHolePartition u v (residualHoles u v R₀ U base) (broken U) lam := by + classical + let := Fintype.ofFinite {b : E → Selection m // FamilyHoles u v m R₀ U b} + let := Fintype.ofFinite {s : E → Bool // + LogicalHoles u v (residualHoles u v R₀ U base) (broken U) s} + unfold realHolePartition logicalHolePartition + rw [Finset.mul_sum] + apply Fintype.sum_equiv (deletionEquiv hm u v R₀ U base hb) + intro b + exact deletion_weight u v R₀ U base b.val hb b.property w left right lam hw + +end Deletion + +theorem selectedWeight_vertex_factor {m : ℕ} (U : Finset (Fin m)) + (b : Selection m) (hb : Valid U b) (z : Fin (m+2) → ℝ) : + selectedWeight (fun i => z i.castSucc * z i.succ) b = + (if b 0 then z 0 else 1) * (if b (Fin.last m) then z (Fin.last (m+1)) else 1) * + ∏ i : Fin m, if i ∈ U then 1 else z i.succ.castSucc := by + classical + unfold selectedWeight + have hsplit (i : Fin (m+1)) : + (if b i then z i.castSucc * z i.succ else 1) = + (if b i then z i.castSucc else 1) * (if b i then z i.succ else 1) := by + cases b i <;> simp + simp_rw [hsplit] + rw [Finset.prod_mul_distrib, + Fin.prod_univ_succ (fun i : Fin (m+1) => if b i then z i.castSucc else 1), + Fin.prod_univ_castSucc (fun i : Fin (m+1) => if b i then z i.succ else 1)] + have he : ∀ i : Fin m, + (if b i.succ then z i.succ.castSucc else 1) * + (if b i.castSucc then z i.castSucc.succ else 1) = + if i ∈ U then 1 else z i.succ.castSucc := by + intro i + have hz : i.castSucc.succ = i.succ.castSucc := rfl + rw [hz] + have h := hb i + by_cases hi : i ∈ U + · simp only [hi,↓reduceIte] at h ⊢ + simp [h.1,h.2] + · simp only [hi,↓reduceIte] at h ⊢ + cases h₁ : b i.castSucc <;> cases h₂ : b i.succ <;> simp_all + calc + _ = (if b 0 then z 0 else 1) * (if b (Fin.last m) then z (Fin.last (m+1)) else 1) * + ∏ i : Fin m, ((if b i.succ then z i.succ.castSucc else 1) * + (if b i.castSucc then z i.castSucc.succ else 1)) := by + rw [Finset.prod_mul_distrib] + simp only [Fin.castSucc_zero, Fin.succ_last] + ring + _ = _ := by simp_rw [he] + +theorem valid_interval {m : ℕ} {U : Finset (Fin m)} {b : Selection m} + (hb : Valid U b) (a k : ℕ) (hak : a+k ≤ m) + (hfree : ∀ i : Fin m, a ≤ i.val → i.val < a+k → i ∉ U) : + b ⟨a+k,by omega⟩ = alternating (b ⟨a,by omega⟩) k := by + induction k with + | zero => simp + | succ k ih => + have hai : a+k < m := by omega + have hf := hb ⟨a+k,hai⟩ + simp only [hfree ⟨a+k,hai⟩ (by dsimp; omega) (by dsimp; omega),↓reduceIte] at hf + have he := (bool_ne_iff_eq_not _ _).mp hf + have hi := ih (by omega) (fun i hi hj => hfree i hi (by omega)) + simpa only [Fin.succ_mk, Fin.castSucc_mk, Nat.add_assoc, + alternating_succ, hi] using he + +theorem first_hole_terminal {m : ℕ} {U : Finset (Fin m)} {b : Selection m} + (hb : Valid U b) (j : Fin m) (hj : j ∈ U) + (hfirst : ∀ i ∈ U, j ≤ i) : + b 0 = true ↔ j.val % 2 = 1 := by + have hv := valid_interval hb 0 j.val (by omega) (by + intro i hi hij him + have hh := hfirst i him + have : j.val ≤ i.val := hh + omega) + have hz : b j.castSucc = false := by + have h := hb j + simp only [hj,↓reduceIte] at h + exact h.1 + have he : b j.castSucc = alternating (b 0) j.val := by + have ez : (⟨0,by omega⟩ : Fin (m+1)) = 0 := Fin.ext rfl + have ee : (⟨0+j.val,by omega⟩ : Fin (m+1)) = j.castSucc := by + apply Fin.ext; dsimp; omega + rw [ee,ez] at hv + exact hv + rw [hz] at he + by_cases h : j.val%2=0 + · simp only [alternating,h,↓reduceIte] at he + simp [← he,h] + · have h1 : j.val%2=1 := by omega + simp only [alternating,h,↓reduceIte] at he + cases hbool : b 0 + · rw [hbool] at he; contradiction + · simp only [h1] + +end MatchingFPRAS.Subdivision + +end OAI diff --git a/lean/OAI/Combinatorics/MatchingCount/Graphs/PushedFlow.lean b/lean/OAI/Combinatorics/MatchingCount/Graphs/PushedFlow.lean new file mode 100644 index 0000000000000000000000000000000000000000..ac8846809aa122f2a7c9792c8bcf53a811cfc30b --- /dev/null +++ b/lean/OAI/Combinatorics/MatchingCount/Graphs/PushedFlow.lean @@ -0,0 +1,416 @@ +import Mathlib +import OAI.Combinatorics.MatchingCount.Probability.LocalVariance + +namespace OAI + +namespace MatchingFPRAS.Replica + +section + +open Finset + +variable {R A S : Type*} [Fintype R] [Fintype A] [Fintype S] [DecidableEq S] + +noncomputable def pushedFlow (ρ : R → ℝ) (F : R → A → S) (q : A → A → ℝ) (s t : S) : ℝ := + ∑ z : R × (A × A), if (F z.1 z.2.1,F z.1 z.2.2) = (s,t) then ρ z.1*q z.2.1 z.2.2 else 0 + +omit [Fintype S] in +lemma pushedFlow_nonneg (ρ : R → ℝ) (F : R → A → S) (q : A → A → ℝ) + (hρ : ∀ r, 0 ≤ ρ r) (hq : ∀ a b, 0 ≤ q a b) (s t : S) : + 0 ≤ pushedFlow ρ F q s t := by + apply Finset.sum_nonneg; intro z _ + split_ifs <;> [exact mul_nonneg (hρ _) (hq _ _); exact le_refl _] + +lemma pushedFlow_test (ρ : R → ℝ) (F : R → A → S) (q : A → A → ℝ) + (g : S → S → ℝ) : + (∑ s, ∑ t, pushedFlow ρ F q s t*g s t) = + ∑ r, ρ r*∑ a, ∑ b, q a b*g (F r a) (F r b) := by + classical + calc + _ = ∑ st : S × S, (∑ z : R × (A × A), + if (F z.1 z.2.1,F z.1 z.2.2) = st then ρ z.1*q z.2.1 z.2.2 else 0)*g st.1 st.2 := by + rw [Fintype.sum_prod_type]; rfl + _ = ∑ z : R × (A × A), ρ z.1*q z.2.1 z.2.2*g (F z.1 z.2.1) (F z.1 z.2.2) := by + simp_rw [Finset.sum_mul] + rw [Finset.sum_comm] + apply Finset.sum_congr rfl; intro z _ + simp only [ite_mul,zero_mul] + simp + _ = _ := by + simp only [Fintype.sum_prod_type,Finset.mul_sum] + apply Finset.sum_congr rfl; intro r _ + apply Finset.sum_congr rfl; intro a _ + apply Finset.sum_congr rfl; intro b _ + ring + +lemma pushedFlow_row_test (ρ : R → ℝ) (F : R → A → S) (q : A → A → ℝ) + (μ : A → ℝ) (hrow : ∀ a, ∑ b, q a b = μ a) (g : S → ℝ) : + (∑ s, ∑ t, pushedFlow ρ F q s t*g s) = ∑ r, ρ r*∑ a, μ a*g (F r a) := by + rw [pushedFlow_test] + apply Finset.sum_congr rfl; intro r _ + congr 1 + apply Finset.sum_congr rfl; intro a _ + rw [← Finset.sum_mul,hrow] + +lemma pushedFlow_col_test (ρ : R → ℝ) (F : R → A → S) (q : A → A → ℝ) + (μ : A → ℝ) (hcol : ∀ b, ∑ a, q a b = μ b) (g : S → ℝ) : + (∑ s, ∑ t, pushedFlow ρ F q s t*g t) = ∑ r, ρ r*∑ b, μ b*g (F r b) := by + rw [pushedFlow_test] + apply Finset.sum_congr rfl; intro r _ + congr 1 + rw [Finset.sum_comm] + apply Finset.sum_congr rfl; intro b _ + rw [← Finset.sum_mul,hcol] + +lemma pushedFlow_energy (ρ : R → ℝ) (F : R → A → S) (q : A → A → ℝ) + (f : S → ℝ) : localEnergy (pushedFlow ρ F q) f = + ∑ r, ρ r*localEnergy q (fun a => f (F r a)) := by + unfold localEnergy + rw [pushedFlow_test] + simp only [mul_div_assoc,Finset.sum_div] + +end + +section + +open Finset + +variable {I Ω : Type*} [Fintype I] [DecidableEq I] [Fintype Ω] [DecidableEq Ω] + +variable (p : I → Ω → ℝ) + +noncomputable def pairFlow (x y : I) (Q : PairCapacity p x y) : (I → Ω) → (I → Ω) → ℝ := + pushedFlow (density p) (replacePair x y) Q.q + +omit [DecidableEq Ω] in +lemma slice_mean (hs : ∀ i, ∑ a, p i a = 1) (x y : I) (f : (I → Ω) → ℝ) : + mean p (fun s => ∑ a : Ω × Ω, p x a.1*p y a.2*f (replacePair x y s a)) = mean p f := by + have he (s : I → Ω) : (∑ a : Ω × Ω, p x a.1*p y a.2*f (replacePair x y s a)) = + average p x (average p y f) s := by + rw [Fintype.sum_prod_type] + simp only [average_apply,Finset.mul_sum] + apply Finset.sum_congr rfl; intro a _ + apply Finset.sum_congr rfl; intro b _ + unfold replacePair; ring + simp_rw [he] + rw [mean_average p hs,mean_average p hs] + +lemma pairFlow_row (hs : ∀ i, ∑ a, p i a = 1) (x y : I) (Q : PairCapacity p x y) (s : I → Ω) : + (∑ t, pairFlow p x y Q s t) = density p s := by + have h := pushedFlow_row_test (density p) (replacePair x y) Q.q + (fun a => p x a.1*p y a.2) Q.row (fun t => if t=s then 1 else 0) + change (∑ r, ∑ t, pairFlow p x y Q r t*(if r=s then 1 else 0)) = + mean p (fun r => ∑ a : Ω × Ω, p x a.1*p y a.2*(if replacePair x y r a=s then 1 else 0)) at h + rw [slice_mean p hs x y (fun t => if t=s then 1 else 0)] at h + simpa [mean,mul_ite,Finset.sum_ite_irrel] using h + +lemma pairFlow_col (hs : ∀ i, ∑ a, p i a = 1) (x y : I) (Q : PairCapacity p x y) (t : I → Ω) : + (∑ s, pairFlow p x y Q s t) = density p t := by + have h := pushedFlow_col_test (density p) (replacePair x y) Q.q + (fun a => p x a.1*p y a.2) Q.col (fun s => if s=t then 1 else 0) + change (∑ r, ∑ s, pairFlow p x y Q r s*(if s=t then 1 else 0)) = + mean p (fun r => ∑ a : Ω × Ω, p x a.1*p y a.2*(if replacePair x y r a=t then 1 else 0)) at h + rw [slice_mean p hs x y (fun s => if s=t then 1 else 0)] at h + simpa [mean,mul_ite] using h + +lemma pairFlow_nonneg (hp : ∀ i a, 0 ≤ p i a) (x y : I) (Q : PairCapacity p x y) (s t : I → Ω) : + 0 ≤ pairFlow p x y Q s t := pushedFlow_nonneg _ _ _ (density_nonneg p hp) Q.nonneg s t + +lemma pairFlow_energy (x y : I) (Q : PairCapacity p x y) (f : (I → Ω) → ℝ) : + localEnergy (pairFlow p x y Q) f = pairEnergy p x y Q f := + pushedFlow_energy _ _ _ f + +noncomputable def baseFlow (i : I) : (I → Ω) → (I → Ω) → ℝ := + pushedFlow (density p) (fun s a => Function.update s i a) (fun a b => p i a*p i b) + +lemma baseFlow_nonneg (hp : ∀ i a, 0 ≤ p i a) (i : I) (s t : I → Ω) : + 0 ≤ baseFlow p i s t := pushedFlow_nonneg _ _ _ (density_nonneg p hp) + (fun a b => mul_nonneg (hp i a) (hp i b)) s t + +lemma baseFlow_row (hs : ∀ i, ∑ a, p i a = 1) (i : I) (s : I → Ω) : + (∑ t, baseFlow p i s t) = density p s := by + have h := pushedFlow_row_test (density p) (fun r a => Function.update r i a) + (fun a b => p i a*p i b) (p i) (fun a => by rw [← Finset.mul_sum,hs, mul_one]) + (fun t => if t=s then 1 else 0) + change (∑ r, ∑ t, baseFlow p i r t*(if r=s then 1 else 0)) = + mean p (average p i (fun t => if t=s then 1 else 0)) at h + rw [mean_average p hs] at h + simpa [mean,mul_ite,Finset.sum_ite_irrel] using h + +lemma baseFlow_col (hs : ∀ i, ∑ a, p i a = 1) (i : I) (t : I → Ω) : + (∑ s, baseFlow p i s t) = density p t := by + have h := pushedFlow_col_test (density p) (fun r a => Function.update r i a) + (fun a b => p i a*p i b) (p i) (fun b => by rw [← Finset.sum_mul,hs, one_mul]) + (fun s => if s=t then 1 else 0) + change (∑ r, ∑ s, baseFlow p i r s*(if s=t then 1 else 0)) = + mean p (average p i (fun s => if s=t then 1 else 0)) at h + rw [mean_average p hs] at h + simpa [mean,mul_ite] using h + +lemma baseFlow_energy (hs : ∀ i, ∑ a, p i a = 1) (i : I) (f : (I → Ω) → ℝ) : + localEnergy (baseFlow p i) f = baseEnergy p i f := by + rw [baseFlow,pushedFlow_energy] + have he (s : I → Ω) : localEnergy (fun a b => p i a*p i b) (fun a => f (Function.update s i a)) = + average p i (fun r => (f r-average p i f r)^2) s := by + have h := FiniteVariance.variance_eq_pair (p i) (fun a => f (Function.update s i a)) (hs i) + rw [Fintype.sum_prod_type] at h + unfold localEnergy + rw [← h] + simp only [FiniteVariance.variance,average_apply,Function.update_idem] + simp_rw [he] + change mean p (average p i (fun r => (f r-average p i f r)^2)) = _ + rw [mean_average p hs] + exact mean_square p (f-average p i f) + + + + +noncomputable def updateCount (guides : I → Finset I) (base : Finset I) : ℕ := + (∑ x, (guides x).card)+base.card + +noncomputable def scanFlow (guides : I → Finset I) (base : Finset I) + (Q : ∀ x y, PairCapacity p x y) (s t : I → Ω) : ℝ := + (if s=t then density p s else 0)/2+ + ((∑ x, ∑ y ∈ guides x, pairFlow p x y (Q x y) s t)+ + ∑ i ∈ base, baseFlow p i s t)/(2*(updateCount guides base:ℝ)) + +end + +section + +open Finset + +variable {Ω J : Type*} [Fintype Ω] + +lemma localEnergy_add (q r : Ω → Ω → ℝ) (f : Ω → ℝ) : + localEnergy (fun a b => q a b+r a b) f = localEnergy q f+localEnergy r f := by + simp only [localEnergy,add_mul,Finset.sum_add_distrib,add_div] + +lemma localEnergy_div (q : Ω → Ω → ℝ) (c : ℝ) (f : Ω → ℝ) : + localEnergy (fun a b => q a b/c) f = localEnergy q f/c := by + simp only [localEnergy,div_mul_eq_mul_div,← Finset.sum_div] + ring + +lemma localEnergy_sum (s : Finset J) (q : J → Ω → Ω → ℝ) (f : Ω → ℝ) : + localEnergy (fun a b => ∑ i ∈ s, q i a b) f = ∑ i ∈ s, localEnergy (q i) f := by + classical + induction s using Finset.induction_on with + | empty => simp [localEnergy] + | @insert i s hi ih => + simp only [Finset.sum_insert hi] + rw [localEnergy_add,ih] + +lemma localEnergy_diag [DecidableEq Ω] (π : Ω → ℝ) (f : Ω → ℝ) : + localEnergy (fun a b => if a=b then π a else 0) f = 0 := by + unfold localEnergy + have h (a b : Ω) : (if a=b then π a else 0)*(f a-f b)^2 = 0 := by + by_cases hh : a=b <;> simp [hh] + simp_rw [h]; simp + +end + +open Finset + +variable {I Ω : Type*} [Fintype I] [DecidableEq I] [Fintype Ω] [DecidableEq Ω] + +variable (p : I → Ω → ℝ) + +omit [DecidableEq I] in +lemma updateCount_pos (guides : I → Finset I) (base : Finset I) (hb : base.Nonempty) : + 0 < updateCount guides base := Nat.add_pos_right _ (Finset.card_pos.mpr hb) + +lemma scanFlow_nonneg (hp : ∀ i a, 0 ≤ p i a) (guides : I → Finset I) (base : Finset I) + (Q : ∀ x y, PairCapacity p x y) (s t : I → Ω) : 0 ≤ scanFlow p guides base Q s t := by + unfold scanFlow + apply add_nonneg + · apply div_nonneg _ (by norm_num) + split_ifs <;> [exact density_nonneg p hp s; exact le_refl _] + · apply div_nonneg _ (by positivity) + exact add_nonneg (Finset.sum_nonneg (fun x _ => Finset.sum_nonneg + (fun y _ => pairFlow_nonneg p hp x y (Q x y) s t))) + (Finset.sum_nonneg (fun i _ => baseFlow_nonneg p hp i s t)) + +lemma scanFlow_lazy (hp : ∀ i a, 0 ≤ p i a) (guides : I → Finset I) (base : Finset I) + (Q : ∀ x y, PairCapacity p x y) (s : I → Ω) : density p s/2 ≤ scanFlow p guides base Q s s := by + unfold scanFlow + simp only [ite_true,le_add_iff_nonneg_right] + apply div_nonneg _ (by positivity) + exact add_nonneg (Finset.sum_nonneg (fun x _ => Finset.sum_nonneg + (fun y _ => pairFlow_nonneg p hp x y (Q x y) s s))) + (Finset.sum_nonneg (fun i _ => baseFlow_nonneg p hp i s s)) + +lemma scanFlow_row (hs : ∀ i, ∑ a, p i a = 1) (guides : I → Finset I) (base : Finset I) + (hb : base.Nonempty) (Q : ∀ x y, PairCapacity p x y) (s : I → Ω) : + (∑ t, scanFlow p guides base Q s t) = density p s := by + have hm : (updateCount guides base:ℝ) ≠ 0 := by exact_mod_cast (ne_of_gt (updateCount_pos guides base hb)) + unfold scanFlow + rw [Finset.sum_add_distrib,← Finset.sum_div,← Finset.sum_div] + simp only [Finset.sum_ite_eq,Finset.mem_univ,ite_true] + rw [Finset.sum_add_distrib,Finset.sum_comm] + simp_rw [Finset.sum_comm (s := Finset.univ) (t := guides _)] + simp_rw [pairFlow_row p hs] + rw [Finset.sum_comm] + simp only [baseFlow_row p hs,Finset.sum_const,nsmul_eq_mul] + simp only [← Finset.sum_mul] + have hc : (∑ x, ((guides x).card:ℝ))+(base.card:ℝ) = (updateCount guides base:ℝ) := by + simp [updateCount,Nat.cast_sum] + rw [← add_mul,hc] + field_simp + ring + +lemma scanFlow_col (hs : ∀ i, ∑ a, p i a = 1) (guides : I → Finset I) (base : Finset I) + (hb : base.Nonempty) (Q : ∀ x y, PairCapacity p x y) (t : I → Ω) : + (∑ s, scanFlow p guides base Q s t) = density p t := by + have hm : (updateCount guides base:ℝ) ≠ 0 := by exact_mod_cast (ne_of_gt (updateCount_pos guides base hb)) + unfold scanFlow + rw [Finset.sum_add_distrib,← Finset.sum_div,← Finset.sum_div] + simp only [Finset.sum_ite_eq',Finset.mem_univ,ite_true] + rw [Finset.sum_add_distrib,Finset.sum_comm] + simp_rw [Finset.sum_comm (s := Finset.univ) (t := guides _)] + simp_rw [pairFlow_col p hs] + rw [Finset.sum_comm] + simp only [baseFlow_col p hs,Finset.sum_const,nsmul_eq_mul] + simp only [← Finset.sum_mul] + have hc : (∑ x, ((guides x).card:ℝ))+(base.card:ℝ) = (updateCount guides base:ℝ) := by + simp [updateCount,Nat.cast_sum] + rw [← add_mul,hc] + field_simp + ring + +lemma scanFlow_energy (hs : ∀ i, ∑ a, p i a = 1) (guides : I → Finset I) (base : Finset I) + (Q : ∀ x y, PairCapacity p x y) (f : (I → Ω) → ℝ) : + localEnergy (scanFlow p guides base Q) f = scanEnergy p guides base Q f := by + unfold scanFlow + rw [localEnergy_add,localEnergy_div,localEnergy_diag,zero_div,zero_add, + localEnergy_div,localEnergy_add] + simp_rw [localEnergy_sum,pairFlow_energy,baseFlow_energy p hs] + rfl + +end MatchingFPRAS.Replica + +namespace MatchingFPRAS.FiniteChain + +open Finset MatchingFPRAS.Replica + +variable {Ω : Type*} [Fintype Ω] [DecidableEq Ω] + +noncomputable def sqNorm (π f : Ω → ℝ) : ℝ := ∑ a, π a*(f a)^2 + +noncomputable def massMean (π f : Ω → ℝ) : ℝ := ∑ a, π a*f a + +noncomputable def stepDensity (π : Ω → ℝ) (C : Ω → Ω → ℝ) (f : Ω → ℝ) (b : Ω) : ℝ := + (∑ a, C a b*f a)/π b + +omit [DecidableEq Ω] in +lemma stepDensity_mean (π : Ω → ℝ) (hp : ∀ a, 0 < π a) (C : Ω → Ω → ℝ) + (hrow : ∀ a, ∑ b, C a b = π a) (f : Ω → ℝ) : + massMean π (stepDensity π C f) = massMean π f := by + unfold massMean stepDensity + simp only [mul_div_cancel₀ _ (ne_of_gt (hp _))] + rw [Finset.sum_comm] + simp_rw [← Finset.sum_mul,hrow] + +omit [DecidableEq Ω] in +lemma stepDensity_one (π : Ω → ℝ) (hp : ∀ a, 0 < π a) (C : Ω → Ω → ℝ) + (hcol : ∀ b, ∑ a, C a b = π b) : stepDensity π C (fun _ => 1) = (fun _ => 1) := by + funext b; simp only [stepDensity,mul_one,hcol,div_self (ne_of_gt (hp b))] + +omit [DecidableEq Ω] in +lemma stepDensity_linear (π : Ω → ℝ) (C : Ω → Ω → ℝ) (f g : Ω → ℝ) (c d : ℝ) : + stepDensity π C (fun a => c*f a+d*g a) = + fun b => c*stepDensity π C f b+d*stepDensity π C g b := by + funext b + have hc (a : Ω) : C a b*(c*f a) = c*(C a b*f a) := by ring + have hd (a : Ω) : C a b*(d*g a) = d*(C a b*g a) := by ring + simp only [stepDensity,mul_add,Finset.sum_add_distrib,hc,hd,← Finset.mul_sum, + add_div,mul_div_assoc] + +omit [DecidableEq Ω] in +lemma stepDensity_jensen (π : Ω → ℝ) (hp : ∀ a, 0 < π a) (C : Ω → Ω → ℝ) + (hC : ∀ a b, 0 ≤ C a b) (hrow : ∀ a, ∑ b, C a b = π a) + (hcol : ∀ b, ∑ a, C a b = π b) (f : Ω → ℝ) : + sqNorm π (stepDensity π C f) ≤ sqNorm π f := by + have h (b : Ω) : π b*(stepDensity π C f b)^2 ≤ ∑ a, C a b*(f a)^2 := by + have hh := square_average (fun a => C a b/π b) (fun a => div_nonneg (hC a b) (hp b).le) + (by rw [← Finset.sum_div,hcol,div_self (ne_of_gt (hp b))]) f + have he : (∑ a, (C a b/π b)*f a) = stepDensity π C f b := by + simp only [stepDensity,div_mul_eq_mul_div,Finset.sum_div] + rw [he] at hh + have hh := mul_le_mul_of_nonneg_left hh (hp b).le + simp only [div_mul_eq_mul_div,← Finset.sum_div,mul_div_cancel₀ _ (ne_of_gt (hp b))] at hh + exact hh + have hh := Finset.sum_le_sum (fun b (_ : b ∈ Finset.univ) => h b) + rw [Finset.sum_comm] at hh + simp_rw [← Finset.sum_mul,hrow] at hh + exact hh + +omit [DecidableEq Ω] in +lemma energy_norm_cross (π : Ω → ℝ) (C : Ω → Ω → ℝ) + (hrow : ∀ a, ∑ b, C a b = π a) (hcol : ∀ b, ∑ a, C a b = π b) + (f : Ω → ℝ) : localEnergy C f = sqNorm π f-(∑ a, ∑ b, C a b*f a*f b) := by + have he (a b : Ω) : C a b*(f a-f b)^2 = C a b*(f a)^2+C a b*(f b)^2-2*(C a b*f a*f b) := by ring + unfold localEnergy + simp_rw [he,Finset.sum_sub_distrib,Finset.sum_add_distrib] + have hl : (∑ a, ∑ b, C a b*(f a)^2) = sqNorm π f := by + simp_rw [← Finset.sum_mul,hrow]; rfl + have hr : (∑ a, ∑ b, C a b*(f b)^2) = sqNorm π f := by + rw [Finset.sum_comm]; simp_rw [← Finset.sum_mul,hcol]; rfl + simp_rw [← Finset.mul_sum] + rw [hl,hr]; ring + +noncomputable def unlazyFlow (π : Ω → ℝ) (C : Ω → Ω → ℝ) (a b : Ω) : ℝ := + 2*C a b-(if a=b then π a else 0) + +omit [Fintype Ω] in +lemma unlazyFlow_nonneg (π : Ω → ℝ) (C : Ω → Ω → ℝ) + (hC : ∀ a b, 0 ≤ C a b) (hlazy : ∀ a, π a/2 ≤ C a a) : + ∀ a b, 0 ≤ unlazyFlow π C a b := by + intro a b; unfold unlazyFlow + by_cases h : a=b + · subst b; simp only [ite_true]; linarith [hlazy a] + · simp only [ite_eq_right h,sub_zero]; exact mul_nonneg (by norm_num) (hC a b) + +lemma unlazyFlow_row (π : Ω → ℝ) (C : Ω → Ω → ℝ) (hrow : ∀ a, ∑ b, C a b = π a) (a : Ω) : + (∑ b, unlazyFlow π C a b) = π a := by + simp only [unlazyFlow,Finset.sum_sub_distrib,← Finset.mul_sum,hrow, + Finset.sum_ite_eq,Finset.mem_univ,ite_true] + ring + +lemma unlazyFlow_col (π : Ω → ℝ) (C : Ω → Ω → ℝ) (hcol : ∀ b, ∑ a, C a b = π b) (b : Ω) : + (∑ a, unlazyFlow π C a b) = π b := by + simp only [unlazyFlow,Finset.sum_sub_distrib,← Finset.mul_sum,hcol, + Finset.sum_ite_eq',Finset.mem_univ,ite_true] + ring + +lemma unlazyFlow_step (π : Ω → ℝ) (hp : ∀ a, 0 < π a) (C : Ω → Ω → ℝ) (f : Ω → ℝ) : + stepDensity π (unlazyFlow π C) f = fun b => 2*stepDensity π C f b-f b := by + funext b + simp only [stepDensity,unlazyFlow,sub_mul,Finset.sum_sub_distrib,ite_mul,zero_mul, + Finset.sum_ite_eq',Finset.mem_univ,ite_true,sub_div, + mul_div_cancel_left₀ (f b) (ne_of_gt (hp b))] + simp_rw [mul_assoc,← Finset.mul_sum] + ring + +lemma lazy_l2 (π : Ω → ℝ) (hp : ∀ a, 0 < π a) (C : Ω → Ω → ℝ) + (hC : ∀ a b, 0 ≤ C a b) (hrow : ∀ a, ∑ b, C a b = π a) + (hcol : ∀ b, ∑ a, C a b = π b) (hlazy : ∀ a, π a/2 ≤ C a a) + (f : Ω → ℝ) : sqNorm π (stepDensity π C f) ≤ sqNorm π f-localEnergy C f := by + have hj := stepDensity_jensen π hp (unlazyFlow π C) (unlazyFlow_nonneg π C hC hlazy) + (unlazyFlow_row π C hrow) (unlazyFlow_col π C hcol) f + rw [unlazyFlow_step π hp] at hj + have he : sqNorm π (fun b => 2*stepDensity π C f b-f b) = + 4*sqNorm π (stepDensity π C f)-4*(∑ a, ∑ b, C a b*f a*f b)+sqNorm π f := by + have ht (b : Ω) : π b*(2*stepDensity π C f b-f b)^2 = + 4*(π b*(stepDensity π C f b)^2)-4*(π b*stepDensity π C f b*f b)+π b*(f b)^2 := by ring + unfold sqNorm + simp_rw [ht,Finset.sum_add_distrib,Finset.sum_sub_distrib,← Finset.mul_sum] + congr 2 + simp only [stepDensity,mul_div_cancel₀ _ (ne_of_gt (hp _)),Finset.sum_mul] + rw [Finset.sum_comm] + rw [he] at hj + rw [energy_norm_cross π C hrow hcol] + linarith + +end MatchingFPRAS.FiniteChain + +end OAI diff --git a/lean/OAI/Combinatorics/MatchingCount/Graphs/RatWeight.lean b/lean/OAI/Combinatorics/MatchingCount/Graphs/RatWeight.lean new file mode 100644 index 0000000000000000000000000000000000000000..4b15f85310a8c1c7a84935ae2a863323eaf7f879 --- /dev/null +++ b/lean/OAI/Combinatorics/MatchingCount/Graphs/RatWeight.lean @@ -0,0 +1,432 @@ +import Mathlib +import OAI.Combinatorics.MatchingCount.Graphs.EnlargementRun + +namespace OAI + +namespace MatchingFPRAS.StageAnalysis + +open Finset MatchingFPRAS.Switching MatchingFPRAS.Initializer + +variable {V : Type*} [Fintype V] [LinearOrder V] + +noncomputable def ratWeight (w : V → V → ℚ) (m : Mate V) : ℚ := + ∏ x, if x < m.val x then w x (m.val x) else 1 + +noncomputable def ratPartition (w : V → V → ℚ) (R : Finset V) : ℚ := + ∑ m ∈ matchings R,ratWeight w m + +lemma ratWeight_cast (w : V → V → ℚ) (m : Mate V) : + (ratWeight w m:ℝ)=weight (fun x y => (w x y:ℝ)) m := by + unfold ratWeight weight + push_cast + apply prod_congr rfl + intro x _ + split_ifs <;> simp + +lemma ratPartition_cast (w : V → V → ℚ) (R : Finset V) : + (ratPartition w R:ℝ)=partition (fun x y => (w x y:ℝ)) R := by + unfold ratPartition partition + push_cast + exact sum_congr rfl fun m _ => ratWeight_cast w m + +lemma partition_pos_of_even (w : V → V → ℝ) (hw : ∀ x y,0 < w x y) + (R : Finset V) (he : Even (Fintype.card V-R.card)) : 0 < partition w R := by + have hm : 0 < (matchings R).card := by rw [matchings_card]; exact pairingCount_pos_of_even _ he + apply Finset.sum_pos + · intro m _ + unfold weight + apply Finset.prod_pos + intro x _ + split_ifs <;> first | exact hw _ _ | norm_num + · exact Finset.card_pos.mp hm + +lemma selected_card (m : Mate V) (R : Finset V) (hm : HasHoles m R) : + (univ.filter fun x => x < m.val x).card=(Fintype.card V-R.card)/2 := by + have hh : HasHoles m Rᶜᶜ := by simpa using hm + have hc := mate_edge_count m Rᶜ hh + rw [Finset.card_compl] at hc + omega + +lemma weight_factor (t : ℝ) (w : V → V → ℝ) (m : Mate V) (R : Finset V) (hm : HasHoles m R) : + weight (fun x y => t*w x y) m=t^((Fintype.card V-R.card)/2)*weight w m := by + unfold weight + rw [←prod_filter (fun x => x < m.val x) (fun x => t*w x (m.val x)), + ←prod_filter (fun x => x < m.val x) (fun x => w x (m.val x)), + prod_mul_distrib,prod_const,selected_card m R hm] + +lemma weight_mono (w w₁ : V → V → ℝ) (hw : ∀ x y,0 ≤ w x y) + (hle : ∀ x y,x≠y → w x y ≤ w₁ x y) (m : Mate V) : weight w m ≤ weight w₁ m := by + apply Finset.prod_le_prod₀ + · intro x _ + split_ifs <;> first | exact hw _ _ | norm_num + · intro x _ + split_ifs with h + · exact hle _ _ h.ne + · rfl + +theorem partition_reweight (w w₁ : V → V → ℝ) (hw : ∀ x y,0 ≤ w x y) + (t : ℝ) (ht : 0 ≤ t) (ht1 : t ≤ 1) + (hlo : ∀ x y,x≠y → t*w x y ≤ w₁ x y) + (hhi : ∀ x y,x≠y → w₁ x y ≤ w x y) (R : Finset V) : + t^(Fintype.card V/2)*partition w R ≤ partition w₁ R ∧ + partition w₁ R ≤ partition w R := by + have hw₁ : ∀ m : Mate V,0 ≤ weight w₁ m := by + intro m + unfold weight + apply prod_nonneg + intro x _ + split_ifs with h + · exact (mul_nonneg ht (hw _ _)).trans (hlo _ _ h.ne) + · norm_num + constructor + · rw [partition,mul_sum] + apply sum_le_sum + intro m hm + have hcard : (Fintype.card V-R.card)/2 ≤ Fintype.card V/2 := Nat.div_le_div_right (Nat.sub_le _ _) + calc + _ ≤ t^((Fintype.card V-R.card)/2)*weight w m := + mul_le_mul_of_nonneg_right (pow_le_pow_of_le_one ht ht1 hcard) (weight_nonneg w hw m) + _ = weight (fun x y => t*w x y) m := (weight_factor t w m R ((mem_matchings _ _).mp hm)).symm + _ ≤ weight w₁ m := weight_mono _ _ (fun x y => mul_nonneg ht (hw x y)) hlo m + · apply sum_le_sum + intro m _ + apply Finset.prod_le_prod₀ + · intro x _ + split_ifs with h + · exact (mul_nonneg ht (hw _ _)).trans (hlo _ _ h.ne) + · norm_num + · intro x _ + split_ifs with h + · exact hhi _ _ h.ne + · rfl + +lemma cooling_half (n : ℕ) (hn : 2 ≤ n) : + (1:ℝ)/2 ≤ ((1+1/(n:ℝ))⁻¹)^(n/2) := by + have hnp : (0:ℝ) x < m.val x),s x*s (m.val x))=∏ x ∈ Rᶜ,s x := by + let L := univ.filter fun x => x < m.val x + let H := univ.filter fun x => m.val x < x + have himg : L.image m.val=H := by + ext x + simp only [L,H,mem_image,mem_filter,mem_univ,true_and] + constructor + · rintro ⟨a,ha,rfl⟩ + simpa using ha + · intro hx + exact ⟨m.val x,by simpa using hx,mate_mate m x⟩ + have hdis : Disjoint L H := by + apply disjoint_left.mpr + intro x hx hy + exact lt_asymm (mem_filter.mp hx).2 (mem_filter.mp hy).2 + have hunion : L∪H=Rᶜ := by + ext x + simp only [L,H,mem_union,mem_filter,mem_univ,true_and,mem_compl] + rw [←ne_iff_lt_or_gt] + simpa only [ne_eq,eq_comm] using not_congr (hm x) + have hp : (∏ x ∈ L,s (m.val x))=∏ x ∈ H,s x := by + rw [←himg] + exact (prod_image m.property.injective.injOn).symm + change (∏ x ∈ L,s x*s (m.val x))=_ + rw [prod_mul_distrib,hp,←prod_union hdis,hunion] + +theorem weight_vertex_scaling (w : V → V → ℝ) (s : V → ℝ) + (m : Mate V) (R : Finset V) (hm : HasHoles m R) : + weight (fun x y => w x y*s x*s y) m=weight w m*(∏ x ∈ Rᶜ,s x) := by + unfold weight + rw [←prod_filter (fun x => x < m.val x) (fun x => w x (m.val x)*s x*s (m.val x)), + ←prod_filter (fun x => x < m.val x) (fun x => w x (m.val x))] + calc + _ = (∏ x ∈ univ.filter (fun x => x < m.val x),w x (m.val x)*(s x*s (m.val x))) := by + apply prod_congr rfl + intro x _ + ring + _ = _ := by rw [prod_mul_distrib,mate_vertex_product s m R hm] + +theorem partition_vertex_scaling (w : V → V → ℝ) (s : V → ℝ) (R : Finset V) : + partition (fun x y => w x y*s x*s y) R=partition w R*(∏ x ∈ Rᶜ,s x) := by + unfold partition + rw [sum_mul] + exact sum_congr rfl fun m hm => weight_vertex_scaling w s m R ((mem_matchings _ _).mp hm) + +theorem holeRatio_vertex_scaling (w : V → V → ℝ) (s : V → ℝ) (hs : ∀ x,0 < s x) (R : Finset V) : + Switching.holeRatio (fun x y => w x y*s x*s y) R=Switching.holeRatio w R/(∏ x ∈ R,s x) := by + have hp : (∏ x : V,s x)≠0 := prod_ne_zero_iff.mpr (fun x _ => (hs x).ne') + have hR : (∏ x ∈ R,s x)≠0 := prod_ne_zero_iff.mpr (fun x _ => (hs x).ne') + have hc : (∏ x ∈ Rᶜ,s x)≠0 := prod_ne_zero_iff.mpr (fun x _ => (hs x).ne') + have he : (∏ x ∈ R,s x)*(∏ x ∈ Rᶜ,s x)=∏ x,s x := prod_mul_prod_compl R s + unfold Switching.holeRatio + rw [partition_vertex_scaling,partition_vertex_scaling,compl_empty] + by_cases hz : partition w ∅=0 + · simp [hz] + · rw [←he] + field_simp + +end MatchingFPRAS.StageAnalysis + +namespace MatchingFPRAS.Enlargement + +open MatchingFPRAS.Switching MatchingFPRAS.Subdivision MatchingFPRAS.RealGeometry +open MatchingFPRAS.Hierarchy MatchingFPRAS.Transport MatchingFPRAS.StageAnalysis Finset + +variable {V : Type*} [Fintype V] [LinearOrder V] [Nontrivial V] + +noncomputable local instance (w : V → V → ℝ) (K : ℕ) : DecidableEq (SourceLabel w K) := Classical.decEq _ + +noncomputable local instance (w : V → V → ℝ) (K : ℕ) : Fintype (BagEdge (sourceBags w K)) := Fintype.ofFinite _ + +open scoped Classical + +lemma sourceBagZ_pos (w : V → V → ℝ) (hw : ∀ x y,0 < w x y) + (hz : 0 < partition w ∅) (K D : ℕ) : 0 < sourceBagZ w K D := by + apply (sourceRealPortion_full_pos w hz K).trans_le + apply partitionWeight_mono BagEdge.Incident _ _ (sourceRealPortion_nonneg w hw K) + intro e + exact le_add_of_nonneg_right (div_nonneg (bagHeight_pos w K _).le (Nat.cast_nonneg D)) + +lemma sourceBagZ_bounds (hn : 2 ≤ Fintype.card V) (w : V → V → ℝ) + (hw : ∀ x y,0 < w x y) (hz : 0 < partition w ∅) + (hrlo : ∀ x,(1:ℝ)/4 ≤ rowMax hn w x) (hrhi : ∀ x,rowMax hn w x ≤ 1) + (K : ℕ) (hK : ∀ x y,x≠y → edgeActivity w x y ≤ (4:ℝ)^K) : + sourceC w K*partition w ∅ ≤ sourceBagZ w K (sourceD (V:=V) K) ∧ + sourceBagZ w K (sourceD (V:=V) K) ≤ 2*(sourceC w K*partition w ∅) := by + have h := source_bag_inflation hn w hw hz hrlo hrhi K hK + change 1 ≤ _ / _ ∧ _ / _ ≤ 2 at h + have he : partitionWeight BagEdge.Incident (sourceRealPortion w K) univ=sourceC w K*partition w ∅ := + sourceRealPortion_full w hz K + have hb : sourceBagZ w K (sourceD (V:=V) K)= + partitionWeight BagEdge.Incident (fun e : BagEdge (sourceBags w K) => + sourceRealPortion w K e+(2:ℝ)^e.val.val.2.1.val/inflationScale (V:=SourceVertex V K) (holeScale V)) univ := by + unfold sourceBagZ sourceBagWeight bagHeight + rw [sourceD_cast] + rw [←hb,he] at h + have hp := mul_pos (sourceC_pos w K) hz + exact ⟨by simpa using (le_div_iff₀ hp).mp h.1,(div_le_iff₀ hp).mp h.2⟩ + +theorem source_observable_means (hn : 2 ≤ Fintype.card V) (w w₁ : V → V → ℝ) + (hw : ∀ x y,0 < w x y) (hz : 0 < partition w ∅) + (hrlo : ∀ x,(1:ℝ)/4 ≤ rowMax hn w x) (hrhi : ∀ x,rowMax hn w x ≤ 1) + (hlo : ∀ x y,x≠y → (1+1/(Fintype.card V:ℝ))⁻¹*w x y ≤ w₁ x y) + (hhi : ∀ x y,x≠y → w₁ x y ≤ w x y) + (K : ℕ) (hK : ∀ x y,x≠y → edgeActivity w x y ≤ (4:ℝ)^K) : + let D := sourceD (V:=V) K + let a := ∑ q : SourceMarked w K,sourceLaw w K D q*observableA w K q + let d := ∑ q : SourceMarked w K,sourceLaw w K D q*observableD w w₁ K q + (∑ q : SourceMarked w K,sourceLaw w K D q)=1 ∧ + (∀ q : SourceMarked w K,0 ≤ sourceLaw w K D q) ∧ + (1:ℝ)/2 ≤ a ∧ (1:ℝ)/4 ≤ d ∧ + d/a=partition w₁ ∅/partition w ∅ ∧ (1:ℝ)/2 ≤ d/a ∧ d/a ≤ 1 ∧ + (∀ e : LogicalEdge V, + (D:ℝ)*(∑ q : SourceMarked w K,sourceLaw w K D q*observableProbe w w₁ K e q)/d= + Switching.holeRatio w₁ {source e,target e}) := by + dsimp only + let D := sourceD (V:=V) K + have hp := sourceBagZ_pos w hw hz K D + have hb := sourceBagZ_bounds hn w hw hz hrlo hrhi K hK + have hc := partition_cooling hn w w₁ (fun x y => (hw x y).le) hlo hhi ∅ + have hz₁ : 0 < partition w₁ ∅ := (half_pos hz).trans_le hc.1 + have hC := sourceC_pos w K + have hDn : (D:ℝ)≠0 := by exact_mod_cast (Nat.ne_of_gt (sourceD_one (V:=V) K)) + refine ⟨sourceLaw_sum w K D hp.ne',sourceLaw_nonneg w hw K D hp.le,?_,?_,?_,?_,?_,?_⟩ + · rw [observableA_mean w hz] + apply (le_div_iff₀ hp).mpr + nlinarith [hb.2] + · rw [observableD_mean w w₁ hw hz₁] + apply (le_div_iff₀ hp).mpr + nlinarith [mul_le_mul_of_nonneg_left hc.1 hC.le,hb.2] + · rw [observableD_mean w w₁ hw hz₁,observableA_mean w hz] + field_simp [hC.ne',hz.ne',hp.ne'] + simpa only [D] using div_self hp.ne' + · rw [observableD_mean w w₁ hw hz₁,observableA_mean w hz] + have he : (sourceC w K*partition w₁ ∅/sourceBagZ w K D)/ + (sourceC w K*partition w ∅/sourceBagZ w K D)=partition w₁ ∅/partition w ∅ := by + field_simp [hC.ne',hz.ne',hp.ne'] + rw [he] + exact (le_div_iff₀ hz).mpr (by linarith) + · rw [observableD_mean w w₁ hw hz₁,observableA_mean w hz] + have he : (sourceC w K*partition w₁ ∅/sourceBagZ w K D)/ + (sourceC w K*partition w ∅/sourceBagZ w K D)=partition w₁ ∅/partition w ∅ := by + field_simp [hC.ne',hz.ne',hp.ne'] + rw [he] + exact (div_le_one hz).mpr hc.2 + · intro e + rw [observableProbe_mean w w₁ hw,observableD_mean w w₁ hw hz₁] + unfold Switching.holeRatio + dsimp only [D] at hDn hp ⊢ + field_simp [hC.ne',hz₁.ne',hp.ne',hDn] + +end MatchingFPRAS.Enlargement + +noncomputable section + +namespace MatchingFPRAS.RealStage + +open Finset + +abbrev alpha : ℝ := 1/100000 + +lemma others_nonempty {n : ℕ} (hn : 2 ≤ n) (i : Fin n) : (univ.erase i).Nonempty := by + let j : Fin n := ⟨if i.val=0 then 1 else 0, by split_ifs <;> omega⟩ + refine ⟨j,mem_erase.mpr ⟨?_,mem_univ _⟩⟩ + apply Fin.ne_of_val_ne + dsimp [j]; split_ifs <;> omega + +def rowMaximum {n : ℕ} (hn : 2 ≤ n) (G : Fin n → Fin n → ℝ) (v : Fin n → ℝ) (i : Fin n) : ℝ := + (univ.erase i).sup' (others_nonempty hn i) (fun j => G i j / v j) + +def scaleUpdate {n : ℕ} (hn : 2 ≤ n) (G : Fin n → Fin n → ℝ) (v : Fin n → ℝ) (i : Fin n) : Fin n → ℝ := + Function.update v i (rowMaximum hn G v i) + +def scalingTrace {n : ℕ} (hn : 2 ≤ n) (G : Fin n → Fin n → ℝ) : ℕ → Fin n → ℝ + | 0 => fun _ => 2 + | k+1 => if hk : k G i j/v j) (mem_erase.mpr ⟨hji,mem_univ _⟩) + +lemma rowMaximum_lower (hn : 2 ≤ n) (G : Fin n → Fin n → ℝ) (v : Fin n → ℝ) + (hG : ∀ i j, i≠j → alpha ≤ G i j) (hv : ScaleInvariant G v) (i) : + alpha/2 ≤ rowMaximum hn G v i := by + obtain ⟨j,hj⟩ := others_nonempty hn i + have hji := (mem_erase.mp hj).1 + apply le_trans _ (ratio_le_rowMaximum hn G v i j hji) + apply (le_div_iff₀ (hv.pos j)).mpr + have hGi := hG i j hji.symm + have hvi := hv.upper j + norm_num [alpha] at * + linarith + +lemma scaleUpdate_le (hn : 2 ≤ n) (G : Fin n → Fin n → ℝ) (v : Fin n → ℝ) + (hv : ScaleInvariant G v) (i j) : scaleUpdate hn G v i j ≤ v j := by + by_cases hji : j=i + · subst j; simpa [scaleUpdate] using rowMaximum_le hn G v hv i + · simp [scaleUpdate,Function.update_of_ne hji] + +lemma scaleUpdate_invariant (hn : 2 ≤ n) (G : Fin n → Fin n → ℝ) (v : Fin n → ℝ) + (hsym : ∀ i j, G i j=G j i) (hG : ∀ i j, i≠j → alpha ≤ G i j) + (hv : ScaleInvariant G v) (i) : ScaleInvariant G (scaleUpdate hn G v i) := by + constructor + · intro j + by_cases hji : j=i + · subst j; simpa [scaleUpdate] using rowMaximum_lower hn G v hG hv i + · simpa [scaleUpdate,Function.update_of_ne hji] using hv.lower j + · intro j; exact (scaleUpdate_le hn G v hv i j).trans (hv.upper j) + · intro a b hab + by_cases hai : a=i + · subst a + have hb := (div_le_iff₀ (hv.pos b)).mp (ratio_le_rowMaximum hn G v i b hab.symm) + simpa [scaleUpdate,Function.update_of_ne hab.symm] using hb + · by_cases hbi : b=i + · subst b + have ha := (div_le_iff₀ (hv.pos a)).mp (ratio_le_rowMaximum hn G v i a hai) + simpa [scaleUpdate,Function.update_of_ne hai,hsym i a,mul_comm] using ha + · simpa [scaleUpdate,Function.update_of_ne hai,Function.update_of_ne hbi] using hv.feasible a b hab + +lemma scaleUpdate_tight (hn : 2 ≤ n) (G : Fin n → Fin n → ℝ) (v : Fin n → ℝ) + (hv : ScaleInvariant G v) (i) : + ∃ j, j≠i ∧ scaleUpdate hn G v i i*scaleUpdate hn G v i j=G i j := by + obtain ⟨j,hj,heq⟩ := Finset.exists_mem_eq_sup' (others_nonempty hn i) (fun j => G i j/v j) + have hji := (mem_erase.mp hj).1 + refine ⟨j,hji,?_⟩ + change rowMaximum hn G v i = G i j/v j at heq + simp only [scaleUpdate,Function.update_self,Function.update_of_ne hji] + rw [heq] + exact div_mul_cancel₀ _ (hv.pos j).ne' + +lemma tight_persists (G : Fin n → Fin n → ℝ) (v v' : Fin n → ℝ) + (hv : ScaleInvariant G v) (hv' : ScaleInvariant G v') (hdown : ∀ i, v' i ≤ v i) + (i j) (hji : j≠i) (hij : v i*v j=G i j) : v' i*v' j=G i j := by + apply le_antisymm + · calc + _ ≤ v i*v j := mul_le_mul (hdown i) (hdown j) (hv'.pos j).le (hv.pos i).le + _ = _ := hij + · exact hv'.feasible i j hji.symm + +end MatchingFPRAS.RealStage + +end + +end OAI diff --git a/lean/OAI/Combinatorics/MatchingCount/Graphs/RelabelMore.lean b/lean/OAI/Combinatorics/MatchingCount/Graphs/RelabelMore.lean new file mode 100644 index 0000000000000000000000000000000000000000..312751635d0a8ca6b58bb91d161a317a94bbde3d --- /dev/null +++ b/lean/OAI/Combinatorics/MatchingCount/Graphs/RelabelMore.lean @@ -0,0 +1,51 @@ +import Mathlib +import OAI.Combinatorics.MatchingCount.Sampling.Relabel + +namespace OAI + +namespace MatchingFPRAS.RationalSource + +open MatchingFPRAS Switching Subdivision RealGeometry Hierarchy Enlargement Transport Finset + +variable {V : Type*} [Fintype V] [LinearOrder V] [Nontrivial V] + +attribute [local instance] NumberedHierarchy.labelOrder sym2Order bagEdgeOrder bagEdgeFintype + +attribute [local instance] UnitRefresh.Computable.allowedDec prodOrder sumOrder + +lemma labelCast_level {X : Type*} [Fintype X] {B B' : X → X → ℝ} + (s : ∀ x y,B x y=B y x) + (t : ∀ x y z,x≠y → x≠z → y≠z → min (B x z) (B z y)≤B x y) + (s' : ∀ x y,B' x y=B' y x) + (t' : ∀ x y z,x≠y → x≠z → y≠z → min (B' x z) (B' z y)≤B' x y) + {H H' : ℕ} (hB : B=B') (hH : H=H') (l : Hierarchy.Label B s t H) : + (labelCast s t s' t' hB hH l).1.val=l.1.val := by + cases hB;cases hH;rfl + +lemma labelCast_edgeLabel {X E : Type*} [Fintype X] [DecidableEq X] [Fintype E] + {B B' : X → X → ℝ} + (s : ∀ x y,B x y=B y x) + (t : ∀ x y z,x≠y → x≠z → y≠z → min (B x z) (B z y)≤B x y) + (s' : ∀ x y,B' x y=B' y x) + (t' : ∀ x y z,x≠y → x≠z → y≠z → min (B' x z) (B' z y)≤B' x y) + (u v : E → X) {H H' : ℕ} (hB : B=B') (hH : H=H') (e : E) : + labelCast s t s' t' hB hH (Hierarchy.edgeLabel B s t u v H e)= + Hierarchy.edgeLabel B' s' t' u v H' e := by + cases hB;cases hH;rfl + +lemma labelsEquiv_level (w : V → V → ℚ) (K : ℕ) + (l : SourceLabel (fun x y=>(w x y:ℝ)) K) : + (labelsEquiv w K l).1.val=l.1.val := by + unfold labelsEquiv + simp only [Equiv.trans_apply,NumberedHierarchy.labelEquiv_level,labelCast_level] + +lemma labelsEquiv_edgeLabel (w : V → V → ℚ) (K : ℕ) (q : SourceRealEdge V K) : + labelsEquiv w K (Hierarchy.edgeLabel (sourceRealB (fun x y=>(w x y:ℝ)) K) + (sourceRealB_comm _ _) (sourceRealB_tri _ _) (realLeft K) (realRight K) + (sourceLevels (fun x y=>(w x y:ℝ)) K) q)=realLabel w K q := by + unfold labelsEquiv + simp only [Equiv.trans_apply,labelCast_edgeLabel,NumberedHierarchy.edgeLabel_equiv,realLabel] + +end MatchingFPRAS.RationalSource + +end OAI diff --git a/lean/OAI/Combinatorics/MatchingCount/Graphs/Related.lean b/lean/OAI/Combinatorics/MatchingCount/Graphs/Related.lean new file mode 100644 index 0000000000000000000000000000000000000000..5accb2fb0eafc25a178e19696ec498c57719a146 --- /dev/null +++ b/lean/OAI/Combinatorics/MatchingCount/Graphs/Related.lean @@ -0,0 +1,570 @@ +import Mathlib +import OAI.Combinatorics.MatchingCount.Graphs.PathActivity + +namespace OAI + +namespace MatchingFPRAS.Enlargement + +open MatchingFPRAS.Switching MatchingFPRAS.Subdivision MatchingFPRAS.RealGeometry +open Finset + +variable {V E : Type*} [Fintype V] [LinearOrder V] [Fintype E] [LinearOrder E] + +lemma edge_activity_le_realBottleneck (u v : E → V) (huv : ∀ e, u e ≠ v e) + (p : ℕ) (hp : 1 ≤ p) (B Hu Hv lam : E → ℝ) (e : E) (i : Fin (4*p+1)) : + pathActivity p B Hu Hv lam e i ≤ realBottleneck u v p B Hu Hv lam + (atVertex u v (4*p) e i.castSucc) (atVertex u v (4*p) e i.succ) := by + apply interval_le_bottleneck u v (4*p) (by omega) huv (pathActivity p B Hu Hv lam) e + i.castSucc i.succ (by simp) + intro k hk hk' + have he : k=i := Fin.ext (by simp only [Fin.val_castSucc,Fin.val_succ] at hk hk'; omega) + subst k + exact le_rfl + +theorem realBottleneck_noncentral_edge (u v : E → V) (huv : ∀ e, u e ≠ v e) + (p : ℕ) (hp : 1 ≤ p) (B Hu Hv lam : E → ℝ) (hB : ∀ e, 1 ≤ B e) + (hHu : ∀ e, 0 ≤ Hu e) (hHv : ∀ e, 0 ≤ Hv e) (hlam : ∀ e, lam e ≤ B e) + (e : E) (i : Fin (4*p+1)) (hi : i.val ≠ 2*p) : + realBottleneck u v p B Hu Hv lam (atVertex u v (4*p) e i.castSucc) + (atVertex u v (4*p) e i.succ) = pathActivity p B Hu Hv lam e i := by + apply le_antisymm _ (edge_activity_le_realBottleneck u v huv p hp B Hu Hv lam e i) + rcases lt_or_gt_of_ne hi with hi | hi + · let j : Fin (4*p) := ⟨i.val,by omega⟩ + have hv : atVertex u v (4*p) e i.succ=Sum.inr (e,j) := + (atVertex_eq_inr_iff u v (4*p) e e i.succ j).mpr ⟨rfl,rfl⟩ + rw [hv,realBottleneck,bottleneck_comm] + have hc := realBottleneck_internal_cap u v p hp B Hu Hv lam hB hHu hHv hlam e j + (atVertex u v (4*p) e i.castSucc) + simpa [realBottleneck,pathActivity,internalStrength,show j.val<2*p from hi, + profile_left p (B e) (Hu e) (Hv e) (lam e) i hi,j] using hc + · let j : Fin (4*p) := ⟨i.val-1,by have := i.isLt; omega⟩ + have hv : atVertex u v (4*p) e i.castSucc=Sum.inr (e,j) := + (atVertex_eq_inr_iff u v (4*p) e e i.castSucc j).mpr ⟨rfl,by dsimp [j]; omega⟩ + rw [hv] + have hc := realBottleneck_internal_cap u v p hp B Hu Hv lam hB hHu hHv hlam e j + (atVertex u v (4*p) e i.succ) + have hj : ¬ j.val < 2*p := by dsimp [j]; omega + have he : j.val+1=i.val := by dsimp [j]; omega + simpa only [pathActivity,profile_right p (B e) (Hu e) (Hv e) (lam e) i hi, + internalStrength,ite_eq_right hj,he] using hc + +variable {V : Type*} [Fintype V] [LinearOrder V] + +theorem realBottleneck_central_edge (w : V → V → ℝ) (p : ℕ) (hp : 1 ≤ p) + (Hu Hv : LogicalEdge V → ℝ) (hHu : ∀ e, 0 ≤ Hu e) (hHv : ∀ e, 0 ≤ Hv e) + (hinner : ∀ e, max (bottleneck w (source e) (target e)) (Hu e/2^(p-1)) = + bottleneck w (source e) (target e)) (e : LogicalEdge V) : + realBottleneck source target p (fun e => bottleneck w (source e) (target e)) + Hu Hv (logicalActivity w) + (atVertex source target (4*p) e ⟨2*p,by omega⟩) + (atVertex source target (4*p) e ⟨2*p+1,by omega⟩) = + bottleneck w (source e) (target e) := by + let B := fun e : LogicalEdge V => bottleneck w (source e) (target e) + let j : Fin (4*p) := ⟨2*p-1,by omega⟩ + let k : Fin (4*p) := ⟨2*p,by omega⟩ + have hj : j.val < 2*p := by dsimp [j]; omega + have hk : ¬ k.val < 2*p := by simp [k] + have hjk : j≠k := by intro h; have := congrArg Fin.val h; dsimp [j,k] at this; omega + have hjv : atVertex source target (4*p) e ⟨2*p,by omega⟩ = Sum.inr (e,j) := + (atVertex_eq_inr_iff _ _ _ _ _ _ _).mpr ⟨rfl,by dsimp [j]; omega⟩ + have hkv : atVertex source target (4*p) e ⟨2*p+1,by omega⟩ = Sum.inr (e,k) := + (atVertex_eq_inr_iff _ _ _ _ _ _ _).mpr ⟨rfl,rfl⟩ + rw [hjv,hkv] + have hsj : internalStrength p (B e) (Hu e) (Hv e) j=B e := by + rw [internalStrength,ite_eq_left hj] + have hdiv : j.val/2=p-1 := by dsimp [j]; omega + rw [hdiv] + exact hinner e + apply le_antisymm + · have hc := realBottleneck_internal_cap source target p hp B Hu Hv (logicalActivity w) + (fun e => one_le_bottleneck w _ _) hHu hHv + (fun e => edgeActivity_le_bottleneck w _ _ (source_ne_target e)) e j (Sum.inr (e,k)) + exact (hc.trans_eq hsj) + · let t := activity source target (4*p) (pathActivity p B Hu Hv (logicalActivity w)) + have hleft : B e ≤ bottleneck t (Sum.inr (e,j)) (Sum.inl (source e)) := + (le_internalStrength p (B e) (Hu e) (Hv e) j).trans + (realBottleneck_left_home source target source_ne_target p hp B Hu Hv (logicalActivity w) hHu e j hj) + have hright : B e ≤ bottleneck t (Sum.inr (e,k)) (Sum.inl (target e)) := + (le_internalStrength p (B e) (Hu e) (Hv e) k).trans + (realBottleneck_right_home source target source_ne_target p hp B Hu Hv (logicalActivity w) hHv e k hk) + have hterm : bottleneck t (Sum.inl (source e)) (Sum.inl (target e))=B e := + terminal_bottleneck w p hp Hu Hv _ _ + have hx : B e ≤ bottleneck t (Sum.inr (e,j)) (Sum.inl (target e)) := by + have ht := bottleneck_ultrametric t (Sum.inr (e,j)) (Sum.inl (target e)) (Sum.inl (source e)) + (by simp) (by simp) (by simpa using (source_ne_target e).symm) + exact ((le_min hleft hterm.ge).trans ht) + have htri := bottleneck_ultrametric t (Sum.inr (e,j)) (Sum.inr (e,k)) (Sum.inl (target e)) + (by simpa using hjk) (by simp) (by simp) + rw [bottleneck_comm t (Sum.inl (target e)) (Sum.inr (e,k))] at htri + exact (le_min hx hright).trans htri + +theorem source_effective_profile (w : V → V → ℝ) (p : ℕ) (hp : 1≤p) + (Hu Hv : LogicalEdge V → ℝ) (hHu : ∀ e, 0≤Hu e) (hHv : ∀ e, 0≤Hv e) + (hinner : ∀ e, max (bottleneck w (source e) (target e)) (Hu e/2^(p-1)) = + bottleneck w (source e) (target e)) (e : LogicalEdge V) (i : Fin (4*p+1)) : + realBottleneck source target p (fun e => bottleneck w (source e) (target e)) Hu Hv + (logicalActivity w) (atVertex source target (4*p) e i.castSucc) + (atVertex source target (4*p) e i.succ) = + profileActivity p (bottleneck w (source e) (target e)) (Hu e) (Hv e) + (bottleneck w (source e) (target e)) i := by + by_cases hi : i.val=2*p + · have he : i=⟨2*p,by omega⟩ := Fin.ext hi + rw [he,profile_center] + exact realBottleneck_central_edge w p hp Hu Hv hHu hHv hinner e + · rw [realBottleneck_noncentral_edge source target source_ne_target p hp _ Hu Hv + (logicalActivity w) (fun _ => one_le_bottleneck _ _ _) hHu hHv + (fun e => edgeActivity_le_bottleneck w _ _ (source_ne_target e)) e i hi] + rcases lt_or_gt_of_ne hi with hi | hi + · simp only [pathActivity,profile_left _ _ _ _ _ _ hi] + · simp only [pathActivity,profile_right _ _ _ _ _ _ hi] + +omit [Fintype V] [LinearOrder V] in +theorem effective_profile_incident_near {E : Type*} (u v : E → V) + (p : ℕ) (hp : 1≤p) (B : E → ℝ) (H : V → ℝ) + (hB : ∀ e, 0≤B e) (hH : ∀ x, 0≤H x) + (hdom : ∀ e, B e≤H (u e) ∧ B e≤H (v e)) + (hinnerL : ∀ e, max (B e) (H (u e)/2^(p-1))=B e) + (hinnerR : ∀ e, max (B e) (H (v e)/2^(p-1))=B e) + (x : Vertex V E (4*p)) (e f : E) (i j : Fin (4*p+1)) + (he : x=atVertex u v (4*p) e i.castSucc ∨ x=atVertex u v (4*p) e i.succ) + (hf : x=atVertex u v (4*p) f j.castSucc ∨ x=atVertex u v (4*p) f j.succ) : + profileActivity p (B e) (H (u e)) (H (v e)) (B e) i ≤ + 2*profileActivity p (B f) (H (u f)) (H (v f)) (B f) j := by + cases x with + | inl x => + have ht (g : E) (k : Fin (4*p+1)) + (hg : Sum.inl x=atVertex u v (4*p) g k.castSucc ∨ Sum.inl x=atVertex u v (4*p) g k.succ) : + profileActivity p (B g) (H (u g)) (H (v g)) (B g) k=H x := by + rcases hg with hg | hg + · obtain ⟨hk,hx⟩ := (first_vertex_terminal u v (4*p) g k x).mp hg.symm + rw [profile_left _ _ _ _ _ _ (by omega),hk] + simp only [Nat.zero_div,pow_zero,div_one,max_eq_right (hdom g).1] + exact congrArg H hx + · obtain ⟨hk,hx⟩ := (second_vertex_terminal u v (4*p) g k x).mp hg.symm + rw [profile_right _ _ _ _ _ _ (by omega),hk] + simp only [Nat.sub_self,Nat.zero_div,pow_zero,div_one,max_eq_right (hdom g).2] + exact congrArg H hx + rw [ht e i he,ht f j hf] + linarith [hH x] + | inr z => + rcases z with ⟨g,k⟩ + have hi : e=g ∧ (i.val=k.val ∨ i.val=k.val+1) := by + rcases he with he | he + · have hh := (atVertex_eq_inr_iff u v (4*p) e g i.castSucc k).mp he.symm + exact ⟨hh.1,Or.inr hh.2⟩ + · have hh := (atVertex_eq_inr_iff u v (4*p) e g i.succ k).mp he.symm + exact ⟨hh.1,Or.inl (by simpa using hh.2)⟩ + have hj : f=g ∧ (j.val=k.val ∨ j.val=k.val+1) := by + rcases hf with hf | hf + · have hh := (atVertex_eq_inr_iff u v (4*p) f g j.castSucc k).mp hf.symm + exact ⟨hh.1,Or.inr hh.2⟩ + · have hh := (atVertex_eq_inr_iff u v (4*p) f g j.succ k).mp hf.symm + exact ⟨hh.1,Or.inl (by simpa using hh.2)⟩ + obtain ⟨rfl,hi⟩ := hi + obtain ⟨rfl,hj⟩ := hj + have hnear := profile_adjacent_near p hp (B f) (H (u f)) (H (v f)) + (hB f) (hH _) (hH _) (hinnerL f) (hinnerR f) k + rcases hi with hi | hi <;> rcases hj with hj | hj + · have heq : i=j := Fin.ext (hi.trans hj.symm) + rw [heq] + have hn := (hB f).trans (profile_lower p (B f) (H (u f)) (H (v f)) (B f) le_rfl j) + linarith + · have hi' : i=k.castSucc := Fin.ext hi + have hj' : j=k.succ := Fin.ext hj + simpa [hi',hj'] using hnear.1 + · have hi' : i=k.succ := Fin.ext hi + have hj' : j=k.castSucc := Fin.ext hj + simpa [hi',hj'] using hnear.2 + · have heq : i=j := Fin.ext (hi.trans hj.symm) + rw [heq] + have hn := (hB f).trans (profile_lower p (B f) (H (u f)) (H (v f)) (B f) le_rfl j) + linarith + +end MatchingFPRAS.Enlargement + +namespace MatchingFPRAS.Hierarchy + +theorem acyclic_of_unique_lower {L : Type*} (G : SimpleGraph L) (rank : L → ℕ) + (hdiff : ∀ {a b}, G.Adj a b → rank a ≠ rank b) + (hparent : ∀ a b c, G.Adj a b → G.Adj a c → rank b < rank a → rank c < rank a → b=c) : + G.IsAcyclic := by + classical + intro a p hp + obtain ⟨b,hb,hmax⟩ := p.support.toFinset.exists_max_image rank + ⟨a,by simp⟩ + have hb' : b ∈ p.support := List.mem_toFinset.mp hb + let q := p.rotate b hb' + have hq : q.IsCycle := hp.rotate hb' + have hqs : q.snd ∈ p.support := (p.mem_support_rotate_iff b hb').mp (q.getVert_mem_support 1) + have hqt : q.penultimate ∈ p.support := + (p.mem_support_rotate_iff b hb').mp (q.getVert_mem_support (q.length-1)) + have hs : rank q.snd < rank b := lt_of_le_of_ne + (hmax q.snd (List.mem_toFinset.mpr hqs)) (hdiff (q.adj_snd hq.not_nil)).symm + have ht : rank q.penultimate < rank b := lt_of_le_of_ne + (hmax q.penultimate (List.mem_toFinset.mpr hqt)) (hdiff (q.adj_penultimate hq.not_nil)) + exact hq.snd_ne_penultimate (hparent b q.snd q.penultimate (q.adj_snd hq.not_nil) + (q.adj_penultimate hq.not_nil).symm hs ht) + +variable {V : Type*} [Fintype V] + +variable (B : V → V → ℝ) + +variable (hsym : ∀ a b, B a b = B b a) + +variable (htri : ∀ a b c, a ≠ b → a ≠ c → b ≠ c → min (B a c) (B c b) ≤ B a b) + +def Related (t : ℝ) (a b : V) : Prop := a=b ∨ t ≤ B a b + +omit [Fintype V] in +include hsym in +lemma related_symm (t : ℝ) {a b : V} (h : Related B t a b) : Related B t b a := by + rcases h with h | h + · exact Or.inl h.symm + · exact Or.inr (by rwa [hsym]) + +omit [Fintype V] in +include htri in +lemma related_trans (t : ℝ) {a b c : V} (hab : Related B t a b) (hbc : Related B t b c) : + Related B t a c := by + rcases hab with rfl | hab + · exact hbc + rcases hbc with rfl | hbc + · exact Or.inr hab + by_cases hac : a=c + · exact Or.inl hac + by_cases hab' : a=b + · subst b; exact Or.inr hbc + by_cases hbc' : c=b + · subst c; exact Or.inr hab + exact Or.inr ((le_min hab hbc).trans (htri a c b hac hab' hbc')) + +def thresholdSetoid (t : ℝ) : Setoid V where + r := Related B t + iseqv := ⟨fun _ => Or.inl rfl,related_symm B hsym t,related_trans B htri t⟩ + +abbrev Component (t : ℝ) := Quotient (thresholdSetoid B hsym htri t) + +abbrev Label (H : ℕ) := (k : Fin (H+1)) × Component B hsym htri (2^k.val) + +def labelAt {H : ℕ} (k : Fin (H+1)) (x : V) : Label B hsym htri H := + ⟨k,Quotient.mk _ x⟩ + +def Mem {H : ℕ} (l : Label B hsym htri H) (x : V) : Prop := Quotient.mk _ x = l.2 + +omit [Fintype V] in +lemma mem_labelAt {H : ℕ} (k : Fin (H+1)) (x : V) : Mem B hsym htri (labelAt B hsym htri k x) x := rfl + +omit [Fintype V] in +lemma mem_class_iff {H : ℕ} (k : Fin (H+1)) (x y : V) : + Mem B hsym htri (labelAt B hsym htri k x) y ↔ Related B (2^k.val) y x := + Quotient.eq + +omit [Fintype V] in +lemma exists_mem {H : ℕ} (l : Label B hsym htri H) : ∃ x, Mem B hsym htri l x := + Quotient.exists_rep l.2 + +omit [Fintype V] in +lemma eq_of_level_of_mem {H : ℕ} (a b : Label B hsym htri H) (hlev : a.1=b.1) + {x : V} (ha : Mem B hsym htri a x) (hb : Mem B hsym htri b x) : a=b := by + cases a with + | mk k a => + cases b with + | mk j b => + dsimp at hlev + subst j + exact congrArg (Sigma.mk k) (ha.symm.trans hb) + +omit [Fintype V] in +lemma related_of_mem {H : ℕ} (l : Label B hsym htri H) {x y : V} + (hx : Mem B hsym htri l x) (hy : Mem B hsym htri l y) : Related B (2^l.1.val) x y := + Quotient.exact (hx.trans hy.symm) + +omit [Fintype V] in +lemma mem_of_related {H : ℕ} (l : Label B hsym htri H) {x y : V} + (hx : Mem B hsym htri l x) (hxy : Related B (2^l.1.val) y x) : Mem B hsym htri l y := + (Quotient.sound hxy).trans hx + +omit [Fintype V] in +lemma related_mono {s t : ℝ} (hst : s ≤ t) {a b : V} (h : Related B t a b) : + Related B s a b := h.imp id (fun hb => hst.trans hb) + +def Parent {H : ℕ} (a b : Label B hsym htri H) : Prop := + a.1.val+1=b.1.val ∧ ∃ x, Mem B hsym htri a x ∧ Mem B hsym htri b x + +def tree {H : ℕ} : SimpleGraph (Label B hsym htri H) where + Adj a b := Parent B hsym htri a b ∨ Parent B hsym htri b a + symm := ⟨fun _ _ h => h.symm⟩ + loopless := ⟨by intro a h; rcases h with h|h <;> have := h.1 <;> omega⟩ + +omit [Fintype V] in +lemma parent_mem {H : ℕ} {a b : Label B hsym htri H} (h : Parent B hsym htri a b) + {x : V} (hx : Mem B hsym htri b x) : Mem B hsym htri a x := by + obtain ⟨hlev,y,hy,hby⟩ := h + have hpow : (2:ℝ)^a.1.val ≤ 2^b.1.val := pow_le_pow_right₀ (by norm_num) (by omega) + exact mem_of_related B hsym htri a hy + (related_mono B hpow (related_of_mem B hsym htri b hx hby)) + +omit [Fintype V] in +lemma parent_unique {H : ℕ} {a b c : Label B hsym htri H} + (ha : Parent B hsym htri a c) (hb : Parent B hsym htri b c) : a=b := by + obtain ⟨x,hx⟩ := exists_mem B hsym htri c + apply eq_of_level_of_mem B hsym htri a b _ + (parent_mem B hsym htri ha hx) (parent_mem B hsym htri hb hx) + apply Fin.ext + have := ha.1 + have := hb.1 + omega + +omit [Fintype V] in +theorem tree_acyclic (H : ℕ) : (tree B hsym htri (H := H)).IsAcyclic := by + apply acyclic_of_unique_lower _ (fun l => l.1.val) + · intro a b hab + rcases hab with h | h <;> have := h.1 <;> omega + · intro a b c hab hac hb hc + have hp : Parent B hsym htri b a := by + rcases hab with h | h + · have := h.1; omega + · exact h + have hq : Parent B hsym htri c a := by + rcases hac with h | h + · have := h.1; omega + · exact h + exact parent_unique B hsym htri hp hq + +omit [Fintype V] in +lemma parent_exists {H : ℕ} (a : Label B hsym htri H) (ha : 0 + by_cases hn : n=0 + · exact ⟨a,h.trans hn,SimpleGraph.Reachable.refl a⟩ + · obtain ⟨b,hb⟩ := parent_exists B hsym htri a (by omega) + obtain ⟨c,hc,hbc⟩ := ih b.1.val (by have := hb.1; omega) b rfl + exact ⟨c,hc,(SimpleGraph.Adj.reachable (show (tree B hsym htri).Adj a b from Or.inr hb)).trans hbc⟩ + +omit [Fintype V] in +include hfloor in +theorem tree_connected [Nonempty V] (H : ℕ) : (tree B hsym htri (H := H)).Connected := by + classical + let : Nonempty (Label B hsym htri H) := ⟨labelAt B hsym htri 0 (Classical.choice inferInstance)⟩ + refine ⟨?_⟩ + intro a b + obtain ⟨a₀,ha₀,ha⟩ := reaches_level_zero B hsym htri a + obtain ⟨b₀,hb₀,hb⟩ := reaches_level_zero B hsym htri b + have he := level_zero_unique B hsym htri hfloor a₀ b₀ ha₀ hb₀ + subst b₀ + exact ha.trans hb.symm + +noncomputable instance labelFintype (H : ℕ) : Fintype (Label B hsym htri H) := Fintype.ofFinite _ + +theorem label_card_le (H : ℕ) : Fintype.card (Label B hsym htri H) ≤ (H+1)*Fintype.card V := by + classical + have hs : Function.Surjective (fun z : Fin (H+1) × V => labelAt B hsym htri z.1 z.2) := by + intro a + obtain ⟨x,hx⟩ := exists_mem B hsym htri a + exact ⟨(a.1,x),Sigma.ext rfl (heq_of_eq hx)⟩ + simpa only [Fintype.card_prod,Fintype.card_fin] using Fintype.card_le_of_surjective _ hs + +noncomputable def dyadicLevel (H : ℕ) (x : ℝ) : Fin (H+1) := by + classical + exact ⟨Nat.findGreatest (fun k => (2:ℝ)^k ≤ x) H, + Nat.lt_succ_of_le (Nat.findGreatest_le H)⟩ + +lemma dyadic_lower (H : ℕ) (x : ℝ) (hx : 1 ≤ x) : + (2:ℝ)^(dyadicLevel H x).val ≤ x := by + classical + exact Nat.findGreatest_spec (P := fun k => (2:ℝ)^k ≤ x) (Nat.zero_le H) (by simpa using hx) + +lemma dyadic_upper (H : ℕ) (x : ℝ) (hx : x ≤ (2:ℝ)^H) : + x < (2:ℝ)^((dyadicLevel H x).val+1) := by + classical + by_cases he : (dyadicLevel H x).val=H + · rw [he,pow_succ] + have : 0 < (2:ℝ)^H := by positivity + linarith + · by_contra hn + have hle : (dyadicLevel H x).val+1 ≤ H := by have := (dyadicLevel H x).isLt; omega + have hg := Nat.le_findGreatest (P := fun k => (2:ℝ)^k ≤ x) hle (le_of_not_gt hn) + change (dyadicLevel H x).val+1 ≤ (dyadicLevel H x).val at hg + omega + +lemma dyadic_near (H : ℕ) (x y : ℝ) (hxlo : 1 ≤ x) (hyhi : y ≤ (2:ℝ)^H) + (hxy : x ≤ 2*y) : (dyadicLevel H x).val ≤ (dyadicLevel H y).val+1 := by + by_contra hn + have hpow : (2:ℝ)^((dyadicLevel H y).val+2) ≤ 2^(dyadicLevel H x).val := + pow_le_pow_right₀ (by norm_num) (by omega) + have hx := dyadic_lower H x hxlo + have hy := dyadic_upper H y hyhi + rw [show (dyadicLevel H y).val+2=((dyadicLevel H y).val+1)+1 by omega,pow_succ] at hpow + linarith + +lemma dyadic_upper_of_lt (H : ℕ) (x : ℝ) (hx : x < (2:ℝ)^(H+1)) : + x < (2:ℝ)^((dyadicLevel H x).val+1) := by + classical + by_cases he : (dyadicLevel H x).val=H + · simpa [he] using hx + · by_contra hn + have hle : (dyadicLevel H x).val+1 ≤ H := by have := (dyadicLevel H x).isLt; omega + have hg := Nat.le_findGreatest (P := fun k => (2:ℝ)^k ≤ x) hle (le_of_not_gt hn) + change (dyadicLevel H x).val+1 ≤ (dyadicLevel H x).val at hg + omega + +lemma dyadic_near_of_lt (H : ℕ) (x y : ℝ) (hxlo : 1≤x) (hyhi : y < (2:ℝ)^(H+1)) + (hxy : x≤2*y) : (dyadicLevel H x).val ≤ (dyadicLevel H y).val+1 := by + by_contra hn + have hpow : (2:ℝ)^((dyadicLevel H y).val+2) ≤ 2^(dyadicLevel H x).val := + pow_le_pow_right₀ (by norm_num) (by omega) + have hx := dyadic_lower H x hxlo + have hy := dyadic_upper_of_lt H y hyhi + rw [show (dyadicLevel H y).val+2=((dyadicLevel H y).val+1)+1 by omega,pow_succ] at hpow + linarith + +omit [Fintype V] in +lemma common_vertex_adjacent {H : ℕ} (a b : Label B hsym htri H) {x : V} + (ha : Mem B hsym htri a x) (hb : Mem B hsym htri b x) + (hab : a.1.val ≤ b.1.val+1) (hba : b.1.val ≤ a.1.val+1) : + a=b ∨ (tree B hsym htri).Adj a b := by + rcases lt_trichotomy a.1.val b.1.val with h | h | h + · exact Or.inr (Or.inl ⟨by omega,x,ha,hb⟩) + · exact Or.inl (eq_of_level_of_mem B hsym htri a b (Fin.ext h) ha hb) + · exact Or.inr (Or.inr ⟨by omega,x,hb,ha⟩) + +omit [Fintype V] in +lemma memberships_card_le_two {H : ℕ} (S : Finset (Label B hsym htri H)) (x : V) + (hmem : ∀ a ∈ S, Mem B hsym htri a x) + (hsep : ∀ a ∈ S, ∀ b ∈ S, a.1.val ≤ b.1.val+1) : S.card ≤ 2 := by + classical + by_cases hne : S.Nonempty + · obtain ⟨a,ha,hmin⟩ := S.exists_min_image (fun a => a.1.val) hne + have hinj : Set.InjOn (fun a : Label B hsym htri H => a.1.val) S := by + intro b hb c hc he + exact eq_of_level_of_mem B hsym htri b c (Fin.ext he) (hmem b hb) (hmem c hc) + have hsub : S.image (fun a => a.1.val) ⊆ {a.1.val,a.1.val+1} := by + intro k hk + obtain ⟨b,hb,rfl⟩ := Finset.mem_image.mp hk + have h₁ := hmin b hb + have h₂ := hsep b hb a ha + simp only [Finset.mem_insert,Finset.mem_singleton] + omega + calc + S.card = (S.image (fun a => a.1.val)).card := (Finset.card_image_of_injOn hinj).symm + _ ≤ ({a.1.val,a.1.val+1} : Finset ℕ).card := Finset.card_le_card hsub + _ ≤ 2 := by simp + · simp [Finset.not_nonempty_iff_eq_empty.mp hne] + +variable {E : Type*} [Fintype E] (left right : E → V) (H : ℕ) + +def Incident (e : E) (x : V) : Prop := x=left e ∨ x=right e + +noncomputable def edgeLabel (e : E) : Label B hsym htri H := + labelAt B hsym htri (dyadicLevel H (B (left e) (right e))) (left e) + +noncomputable def memberships (x : V) : Finset (Label B hsym htri H) := by + classical + exact (Finset.univ.filter (fun e => Incident left right e x)).image + (edgeLabel B hsym htri left right H) + +omit [Fintype V] in +lemma mem_memberships (x : V) (l : Label B hsym htri H) : + l ∈ memberships B hsym htri left right H x ↔ + ∃ e, Incident left right e x ∧ edgeLabel B hsym htri left right H e=l := by + classical + simp [memberships] + +omit [Fintype V] [Fintype E] in +include hfloor in +lemma incident_mem_label (e : E) {x : V} (hx : Incident left right e x) : + Mem B hsym htri (edgeLabel B hsym htri left right H e) x := by + rcases hx with rfl | rfl + · rfl + · apply (mem_class_iff B hsym htri _ _ _).mpr + exact Or.inr (by rw [hsym]; exact dyadic_lower H _ (hfloor _ _)) + +omit [Fintype V] in +include hfloor in +lemma membership_mem {x : V} {l : Label B hsym htri H} + (hl : l ∈ memberships B hsym htri left right H x) : Mem B hsym htri l x := by + obtain ⟨e,he,rfl⟩ := (mem_memberships B hsym htri left right H x l).mp hl + exact incident_mem_label B hsym htri hfloor left right H e he + +variable (hupper : ∀ e, B (left e) (right e) < (2:ℝ)^(H+1)) + +variable (hnear : ∀ x e f, Incident left right e x → Incident left right f x → + B (left e) (right e) ≤ 2*B (left f) (right f)) + +omit [Fintype V] in +include hfloor hupper hnear in +lemma memberships_level_near {x : V} {a b : Label B hsym htri H} + (ha : a ∈ memberships B hsym htri left right H x) + (hb : b ∈ memberships B hsym htri left right H x) : a.1.val ≤ b.1.val+1 := by + obtain ⟨e,he,rfl⟩ := (mem_memberships B hsym htri left right H x a).mp ha + obtain ⟨f,hf,rfl⟩ := (mem_memberships B hsym htri left right H x b).mp hb + exact dyadic_near_of_lt H _ _ (hfloor _ _) (hupper f) (hnear x e f he hf) + +omit [Fintype V] in +include hfloor hupper hnear in + +theorem memberships_tree_bags (x : V) (a b : Label B hsym htri H) + (ha : a ∈ memberships B hsym htri left right H x) + (hb : b ∈ memberships B hsym htri left right H x) : + a=b ∨ (tree B hsym htri).Adj a b := by + exact common_vertex_adjacent B hsym htri a b + (membership_mem B hsym htri hfloor left right H ha) + (membership_mem B hsym htri hfloor left right H hb) + (memberships_level_near B hsym htri hfloor left right H hupper hnear ha hb) + (memberships_level_near B hsym htri hfloor left right H hupper hnear hb ha) + +omit [Fintype V] in +include hfloor hupper hnear in +lemma membership_count (x : V) : (memberships B hsym htri left right H x).card ≤ 2 := by + apply memberships_card_le_two B hsym htri _ x + · intro a ha; exact membership_mem B hsym htri hfloor left right H ha + · intro a ha b hb + exact memberships_level_near B hsym htri hfloor left right H hupper hnear ha hb + +omit [Fintype V] in +include hfloor in +lemma common_height_le {x y : V} {l : Label B hsym htri H} (hxy : x≠y) + (hx : l ∈ memberships B hsym htri left right H x) + (hy : l ∈ memberships B hsym htri left right H y) : (2:ℝ)^l.1.val ≤ B x y := by + exact (related_of_mem B hsym htri l + (membership_mem B hsym htri hfloor left right H hx) + (membership_mem B hsym htri hfloor left right H hy)).resolve_left hxy + +omit [Fintype V] [Fintype E] in +include hupper in +lemma edge_strength_lt_twice_height (e : E) : + B (left e) (right e) < 2*(2:ℝ)^(edgeLabel B hsym htri left right H e).1.val := by + simpa [edgeLabel,labelAt,pow_succ,mul_comm] using dyadic_upper_of_lt H _ (hupper e) + +omit [Fintype V] in +lemma adjacent_heights {a b : Label B hsym htri H} (hab : (tree B hsym htri).Adj a b) : + (2:ℝ)^a.1.val ≤ 2*(2:ℝ)^b.1.val ∧ (2:ℝ)^b.1.val ≤ 2*(2:ℝ)^a.1.val := by + rcases hab with h | h <;> have he := h.1 + · have hpow : (2:ℝ)^b.1.val=2*2^a.1.val := by rw [←he,pow_succ]; ring + rw [hpow]; constructor <;> nlinarith [pow_pos (by norm_num : (0:ℝ)<2) a.1.val] + · have hpow : (2:ℝ)^a.1.val=2*2^b.1.val := by rw [←he,pow_succ]; ring + rw [hpow]; constructor <;> nlinarith [pow_pos (by norm_num : (0:ℝ)<2) b.1.val] + +end MatchingFPRAS.Hierarchy + +end OAI diff --git a/lean/OAI/Combinatorics/MatchingCount/Graphs/Related2.lean b/lean/OAI/Combinatorics/MatchingCount/Graphs/Related2.lean new file mode 100644 index 0000000000000000000000000000000000000000..46cc58e24944a5126f7ea4a5df28d809c52752a3 --- /dev/null +++ b/lean/OAI/Combinatorics/MatchingCount/Graphs/Related2.lean @@ -0,0 +1,466 @@ +import Mathlib +import OAI.Combinatorics.MatchingCount.Sampling.DiscreteLadderSteps + +namespace OAI + +namespace MatchingFPRAS.NumberedHierarchy + +open Finset + +variable {V : Type*} [Fintype V] [LinearOrder V] + +variable (B : V → V → ℚ) + +def related (t : ℚ) (x y : V) : Prop := x=y ∨ t≤B x y + +instance relatedDec (t : ℚ) (x y : V) : Decidable (related B t x y) := + inferInstanceAs (Decidable (x=y ∨ t≤B x y)) + +def component (t : ℚ) (x : V) : Finset V := univ.filter (related B t x) + +lemma component_self (t : ℚ) (x : V) : x∈component B t x := by simp [component,related] + +def root (t : ℚ) (x : V) : V := (component B t x).min' ⟨x,component_self B t x⟩ + +lemma root_mem (t : ℚ) (x : V) : root B t x ∈ component B t x := min'_mem _ _ + +lemma related_root (t : ℚ) (x : V) : related B t x (root B t x) := by + simpa [component] using root_mem B t x + +omit [Fintype V] [LinearOrder V] in +lemma cast_related [Fintype V] [LinearOrder V] (t : ℚ) (x y : V) : + related B t x y ↔ Hierarchy.Related (fun x y=>(B x y:ℝ)) (t:ℝ) x y := by + simp only [related,Hierarchy.Related,Rat.cast_le] + +variable (hsym : ∀ x y,B x y=B y x) + +variable (htri : ∀ x y z,x≠y → x≠z → y≠z → min (B x z) (B z y)≤B x y) + +include hsym in +omit [Fintype V] [LinearOrder V] in +lemma symmetric [Fintype V] [LinearOrder V] : ∀ x y,(B x y:ℝ)=(B y x:ℝ) := by intro x y; rw [hsym] + +include htri in +omit [Fintype V] [LinearOrder V] in +lemma triangular [Fintype V] [LinearOrder V] : ∀ x y z,x≠y → x≠z → y≠z → + min (B x z:ℝ) (B z y:ℝ)≤(B x y:ℝ) := by + intro x y z hxy hxz hyz + exact_mod_cast htri x y z hxy hxz hyz + +lemma related_trans (_hsym : ∀ x y,B x y=B y x) + (htri : ∀ x y z,x≠y → x≠z → y≠z → min (B x z) (B z y)≤B x y) + (t : ℚ) {x y z : V} (hxy : related B t x y) (hyz : related B t y z) : + related B t x z := by + rw [cast_related] at * + exact Hierarchy.related_trans _ (triangular B htri) _ hxy hyz + +include hsym in +omit [Fintype V] [LinearOrder V] in +lemma related_symm [Fintype V] [LinearOrder V] (t : ℚ) {x y : V} + (hxy : related B t x y) : related B t y x := by + rcases hxy with rfl|h + · exact Or.inl rfl + · exact Or.inr (by rwa [hsym]) + +include hsym htri in +lemma component_eq_iff (t : ℚ) (x y : V) : component B t x=component B t y ↔ related B t x y := by + constructor + · intro h + have := component_self B t y + rw [←h] at this + simpa [component] using this + · intro h + ext z + simp only [component,mem_filter,mem_univ,true_and] + exact ⟨fun hx=>related_trans B hsym htri t (related_symm B hsym t h) hx, + fun hy=>related_trans B hsym htri t h hy⟩ + +include hsym htri in +lemma root_eq_iff (t : ℚ) (x y : V) : root B t x=root B t y ↔ related B t x y := by + constructor + · intro h + have hx := related_root B t x + rw [h] at hx + exact related_trans B hsym htri t hx (related_symm B hsym t (related_root B t y)) + · intro h + unfold root + congr 1 + exact (component_eq_iff B hsym htri t x y).mpr h + +include hsym htri in +lemma root_idem (t : ℚ) (x : V) : root B t (root B t x)=root B t x := + (root_eq_iff B hsym htri t _ _).mpr (related_symm B hsym t (related_root B t x)) + +abbrev NumberedComponent (t : ℚ) := {x : V // root B t x=x} + +def classOf (t : ℚ) (x : V) : NumberedComponent B t := ⟨root B t x,root_idem B hsym htri t x⟩ + +def quotientEquiv (t : ℚ) : + Hierarchy.Component (fun x y=>(B x y:ℝ)) (symmetric B hsym) (triangular B htri) (t:ℝ) ≃ + NumberedComponent B t where + toFun := Quotient.lift (classOf B hsym htri t) (by + intro x y h + apply Subtype.ext + exact (root_eq_iff B hsym htri t x y).mpr ((cast_related B t x y).mpr h)) + invFun x := Quotient.mk _ x.val + left_inv := by + intro x + induction x using Quotient.inductionOn with | h x => + apply Quotient.sound + exact (cast_related B t _ _).mp (related_symm B hsym t (related_root B t x)) + right_inv := by intro x; apply Subtype.ext; exact x.property + +def level (H : ℕ) (x : ℚ) : Fin (H+1) := + ⟨Nat.findGreatest (fun k => (2:ℚ)^k≤x) H,Nat.lt_succ_of_le (Nat.findGreatest_le H)⟩ + +lemma level_cast (H : ℕ) (x : ℚ) : level H x=Hierarchy.dyadicLevel H (x:ℝ) := by + apply Fin.ext + change Nat.findGreatest (fun k => (2:ℚ)^k≤x) H = Nat.findGreatest (fun k => (2:ℝ)^k≤(x:ℝ)) H + have h : (fun k => (2:ℚ)^k≤x) = (fun k => (2:ℝ)^k≤(x:ℝ)) := by + funext k + apply propext + norm_cast + simp only [h] + +abbrev Label (H : ℕ) := (k : Fin (H+1)) × NumberedComponent B ((2:ℚ)^k.val) + +def labelAt {H : ℕ} (k : Fin (H+1)) (x : V) : Label B H := + ⟨k,classOf B hsym htri _ x⟩ + +def member {H : ℕ} (l : Label B H) (x : V) : Prop := root B ((2:ℚ)^l.1.val) x=l.2.val + +instance memberDec {H : ℕ} (l : Label B H) (x : V) : Decidable (member B l x) := + inferInstanceAs (Decidable (root B _ x=l.2.val)) + +lemma member_self {H : ℕ} (l : Label B H) : member B l l.2.val := l.2.property + +def parent {H : ℕ} (l : Label B H) : Option (Label B H) := + if h : 0Fintype.card_subtype_le _) + _ = _ := by simp + +def componentEquiv (k : ℕ) : + Hierarchy.Component (fun x y=>(B x y:ℝ)) (symmetric B hsym) (triangular B htri) ((2:ℝ)^k) ≃ + NumberedComponent B ((2:ℚ)^k) where + toFun := Quotient.lift (classOf B hsym htri ((2:ℚ)^k)) (by + intro x y h + apply Subtype.ext + apply (root_eq_iff B hsym htri _ x y).mpr + apply (cast_related B ((2:ℚ)^k) x y).mpr + change Hierarchy.Related (fun x y=>(B x y:ℝ)) ((2:ℝ)^k) x y at h + simpa only [Rat.cast_pow,Rat.cast_ofNat] using h) + invFun x := Quotient.mk _ x.val + left_inv := by + intro x + induction x using Quotient.inductionOn with | h x => + apply Quotient.sound + change Hierarchy.Related (fun x y=>(B x y:ℝ)) ((2:ℝ)^k) (root B ((2:ℚ)^k) x) x + have h := (cast_related B ((2:ℚ)^k) _ _).mp + (related_symm B hsym ((2:ℚ)^k) (related_root B ((2:ℚ)^k) x)) + simpa only [Rat.cast_pow,Rat.cast_ofNat] using h + right_inv := by intro x; apply Subtype.ext; exact x.property + +def labelEquiv (H : ℕ) : + Hierarchy.Label (fun x y=>(B x y:ℝ)) (symmetric B hsym) (triangular B htri) H ≃ Label B H := + Equiv.sigmaCongrRight (fun k=>componentEquiv B hsym htri k.val) + +lemma componentEquiv_mk (k : ℕ) (x : V) : + componentEquiv B hsym htri k (Quotient.mk _ x)=classOf B hsym htri ((2:ℚ)^k) x := by + rfl + +lemma labelEquiv_at {H : ℕ} (k : Fin (H+1)) (x : V) : + labelEquiv B hsym htri H (Hierarchy.labelAt _ _ _ k x)=labelAt B hsym htri k x := by + simp [labelEquiv,Hierarchy.labelAt,labelAt,componentEquiv_mk] + +lemma labelEquiv_level {H : ℕ} (l : Hierarchy.Label (fun x y=>(B x y:ℝ)) + (symmetric B hsym) (triangular B htri) H) : + (labelEquiv B hsym htri H l).1=l.1 := rfl + +lemma member_labelAt {H : ℕ} (k : Fin (H+1)) (x y : V) : + member B (labelAt B hsym htri k x) y ↔ related B ((2:ℚ)^k.val) y x := by + exact root_eq_iff B hsym htri _ y x + +lemma member_equiv {H : ℕ} (l : Hierarchy.Label (fun x y=>(B x y:ℝ)) + (symmetric B hsym) (triangular B htri) H) (x : V) : + member B (labelEquiv B hsym htri H l) x ↔ + Hierarchy.Mem (fun x y=>(B x y:ℝ)) (symmetric B hsym) (triangular B htri) l x := by + obtain ⟨k,l⟩:=l + induction l using Quotient.inductionOn with | h y => + change member B (labelEquiv B hsym htri H (Hierarchy.labelAt _ _ _ k y)) x ↔ _ + rw [labelEquiv_at,member_labelAt] + change related B ((2:ℚ)^k.val) x y ↔ Hierarchy.Mem _ _ _ (Hierarchy.labelAt _ _ _ k y) x + rw [Hierarchy.mem_class_iff] + simpa only [Rat.cast_pow,Rat.cast_ofNat] using cast_related B ((2:ℚ)^k.val) x y + +lemma parent_iff {H : ℕ} (l p : Label B H) : parent B hsym htri l=some p ↔ + p.1.val+1=l.1.val ∧ member B p l.2.val := by + obtain ⟨k,l⟩:=l + obtain ⟨j,p⟩:=p + unfold parent + split_ifs with hl + · change 0 l.1.val) he + constructor + · change j.val+1=k.val + change k.val-1=j.val at hk + omega + · rw [←he] + rfl + · rintro ⟨hp,hm⟩ + change j.val+1=k.val at hp + have hj : j=(⟨k.val-1,Nat.lt_of_le_of_lt (Nat.sub_le _ _) k.isLt⟩ : Fin (H+1)) := by + apply Fin.ext + change j.val=k.val-1 + omega + cases hj + congr 1 + apply congrArg (Sigma.mk _) + exact Subtype.ext hm + · constructor + · intro h; cases h + · rintro ⟨hp,_⟩ + change j.val+1=k.val at hp + change ¬0(B x y:ℝ)) (symmetric B hsym) (triangular B htri) H) : + parent B hsym htri (labelEquiv B hsym htri H l)=some (labelEquiv B hsym htri H p) ↔ + Hierarchy.Parent (fun x y=>(B x y:ℝ)) (symmetric B hsym) (triangular B htri) p l := by + rw [parent_iff] + change (p.1.val+1=l.1.val ∧ _) ↔ _ + let v := (labelEquiv B hsym htri H l).2.val + have hl : Hierarchy.Mem _ (symmetric B hsym) (triangular B htri) l v := + (member_equiv B hsym htri l v).mp (member_self B _) + constructor + · rintro ⟨hp,hm⟩ + exact ⟨hp,v,(member_equiv B hsym htri p v).mp hm,hl⟩ + · intro h + exact ⟨h.1,(member_equiv B hsym htri p v).mpr (Hierarchy.parent_mem _ _ _ h hl)⟩ + +variable {E : Type*} [Fintype E] [DecidableEq E] (left right : E → V) + +def edgeLabel (H : ℕ) (e : E) : Label B H := + labelAt B hsym htri (level H (B (left e) (right e))) (left e) + +def bags (H : ℕ) (x : V) : Finset (Label B H) := + (univ.filter (fun e=>x=left e ∨ x=right e)).image (edgeLabel B hsym htri left right H) + +omit [Fintype E] [DecidableEq E] in +lemma edgeLabel_equiv [Fintype E] [DecidableEq E] (H : ℕ) (e : E) : + labelEquiv B hsym htri H (Hierarchy.edgeLabel (fun x y=>(B x y:ℝ)) + (symmetric B hsym) (triangular B htri) left right H e)=edgeLabel B hsym htri left right H e := by + unfold Hierarchy.edgeLabel edgeLabel + rw [←level_cast] + exact labelEquiv_at B hsym htri _ _ + +omit [DecidableEq E] in +lemma mem_bags [DecidableEq E] (H : ℕ) (x : V) (l : Label B H) : + l∈bags B hsym htri left right H x ↔ + ∃ e,(x=left e ∨ x=right e) ∧ edgeLabel B hsym htri left right H e=l := by + simp [bags] + +lemma bags_equiv (H : ℕ) (x : V) : + (Hierarchy.memberships (fun x y=>(B x y:ℝ)) (symmetric B hsym) (triangular B htri) + left right H x).image (labelEquiv B hsym htri H)=bags B hsym htri left right H x := by + classical + ext l + simp only [mem_image,mem_bags,Hierarchy.mem_memberships,Hierarchy.Incident] + constructor + · rintro ⟨a,⟨e,he,hea⟩,hal⟩ + refine ⟨e,he,?_⟩ + rw [←edgeLabel_equiv,hea,hal] + · rintro ⟨e,he,hel⟩ + refine ⟨_,⟨e,he,rfl⟩,?_⟩ + rwa [edgeLabel_equiv] + +omit [DecidableEq E] in +lemma bags_card_edges [DecidableEq E] (H : ℕ) (x : V) : + (bags B hsym htri left right H x).card≤Fintype.card E := by + exact card_image_le.trans ((card_filter_le _ _).trans_eq (card_univ)) + +end MatchingFPRAS.NumberedHierarchy + +namespace MatchingFPRAS.RationalSource + +open MatchingFPRAS Switching Subdivision RealGeometry Enlargement Finset + +variable {V : Type*} [Fintype V] [LinearOrder V] [Nontrivial V] + +def logicalB (w : V → V → ℚ) : V → V → ℚ := + BottleneckAlgorithm.close w (Fintype.card V) + +omit [Nontrivial V] in +lemma logicalB_cast [Nontrivial V] (w : V → V → ℚ) (x y : V) : + (logicalB w x y:ℝ)=bottleneck (fun x y=>(w x y:ℝ)) x y := + BottleneckAlgorithm.rational_close_eq w x y + +def height (w : V → V → ℚ) (x : V) : ℚ := + (univ.erase x).sup' (row_nonempty x) (logicalB w x) + +lemma height_cast (w : V → V → ℚ) (x : V) : + (height w x:ℝ)=sourceHeight (fun x y=>(w x y:ℝ)) x := by + unfold height sourceHeight + rw [Finset.apply_sup'_eq_sup'_comp _ (fun x:ℚ=>(x:ℝ)) (by intro x y; exact Rat.cast_max x y)] + apply Finset.sup'_congr _ rfl + intro y _ + exact logicalB_cast w x y + +def maxHeight (w : V → V → ℚ) : ℚ := univ.sup' univ_nonempty (height w) + +lemma maxHeight_cast (w : V → V → ℚ) : + (maxHeight w:ℝ)=maxSourceHeight (fun x y=>(w x y:ℝ)) := by + unfold maxHeight maxSourceHeight + rw [Finset.apply_sup'_eq_sup'_comp _ (fun x:ℚ=>(x:ℝ)) (by intro x y; exact Rat.cast_max x y)] + apply Finset.sup'_congr _ rfl + intro x _ + exact height_cast w x + +def levels (w : V → V → ℚ) (K : ℕ) : ℕ := + (NumberedHierarchy.level (2*K) (maxHeight w)).val + +lemma levels_eq (w : V → V → ℚ) (K : ℕ) : + levels w K=sourceLevels (fun x y=>(w x y:ℝ)) K := by + simp only [levels,NumberedHierarchy.level_cast,maxHeight_cast,sourceLevels] + +def profile (p : ℕ) (B Hu Hv lam : ℚ) (i : Fin (4*p+1)) : ℚ := + if i.val<2*p then max B (Hu/2^(i.val/2)) + else if i.val=2*p then lam else max B (Hv/2^((4*p-i.val)/2)) + +lemma profile_cast (p : ℕ) (B Hu Hv lam : ℚ) (i : Fin (4*p+1)) : + (profile p B Hu Hv lam i:ℝ)=profileActivity p B Hu Hv lam i := by + rcases lt_trichotomy i.val (2*p) with h|h|h + · rw [profile,ite_eq_left h,profile_left _ _ _ _ _ _ h] + norm_cast + · have he : i=⟨2*p,by omega⟩:=Fin.ext h + rw [he] + simp [profile] + · rw [profile,ite_eq_right (by omega),ite_eq_right (by omega),profile_right _ _ _ _ _ _ h] + norm_cast + +def pathActivity (w : V → V → ℚ) (K : ℕ) (e : LogicalEdge V) : Fin (4*(2*K+2)+1) → ℚ := + profile (2*K+2) (logicalB w (source e) (target e)) (height w (source e)) + (height w (target e)) (BottleneckAlgorithm.edge w (source e) (target e)) + +lemma pathActivity_cast (w : V → V → ℚ) (K : ℕ) (e : LogicalEdge V) (i : Fin (4*(2*K+2)+1)) : + (pathActivity w K e i:ℝ) = Enlargement.pathActivity (2*K+2) + (fun e=>bottleneck (fun x y=>(w x y:ℝ)) (source e) (target e)) + (fun e=>sourceHeight (fun x y=>(w x y:ℝ)) (source e)) + (fun e=>sourceHeight (fun x y=>(w x y:ℝ)) (target e)) + (logicalActivity (fun x y=>(w x y:ℝ))) e i := by + rw [pathActivity,profile_cast,logicalB_cast,height_cast,height_cast] + congr 1 + have he : source ebottleneck (fun x y=>(w x y:ℝ)) (source e) (target e)) + (fun e=>sourceHeight (fun x y=>(w x y:ℝ)) (source e)) + (fun e=>sourceHeight (fun x y=>(w x y:ℝ)) (target e)) + (logicalActivity (fun x y=>(w x y:ℝ)))) x y := by + unfold activity RealGeometry.activity + push_cast + apply sum_congr rfl + intro q _ + split_ifs + · exact pathActivity_cast w K q.1 q.2 + · norm_cast + +def realB (w : V → V → ℚ) (K : ℕ) : SourceVertex V K → SourceVertex V K → ℚ := + BottleneckAlgorithm.close (activity w K) (Fintype.card (SourceVertex V K)) + +lemma realB_cast (w : V → V → ℚ) (K : ℕ) (x y : SourceVertex V K) : + (realB w K x y:ℝ)=sourceRealB (fun x y=>(w x y:ℝ)) K x y := by + rw [realB,BottleneckAlgorithm.rational_close_eq] + unfold sourceRealB realBottleneck + congr 2 + funext a b + exact activity_cast w K a b + +lemma realB_symm (w : V → V → ℚ) (K : ℕ) (x y : SourceVertex V K) : + realB w K x y=realB w K y x := by + apply Rat.cast_injective (α:=ℝ) + simp only [realB_cast,sourceRealB_comm] + +lemma realB_tri (w : V → V → ℚ) (K : ℕ) (x y z : SourceVertex V K) + (hxy : x≠y) (hxz : x≠z) (hyz : y≠z) : + min (realB w K x z) (realB w K z y)≤realB w K x y := by + apply (Rat.cast_le (K:=ℝ)).mp + simp only [Rat.cast_min,realB_cast] + exact sourceRealB_tri _ _ _ _ _ hxy hxz hyz + +abbrev Label (w : V → V → ℚ) (K : ℕ) := NumberedHierarchy.Label (realB w K) (levels w K) + +def bags (w : V → V → ℚ) (K : ℕ) : SourceVertex V K → Finset (Label w K) := + NumberedHierarchy.bags (realB w K) (realB_symm w K) (realB_tri w K) + (realLeft K) (realRight K) (levels w K) + +theorem label_card (w : V → V → ℚ) (K : ℕ) : + Fintype.card (Label w K)≤(2*K+1)*Fintype.card (SourceVertex V K) := by + calc + _ ≤ (levels w K+1)*Fintype.card (SourceVertex V K) := by + rw [Fintype.card_sigma] + calc + _ ≤ ∑ k : Fin (levels w K+1),Fintype.card (SourceVertex V K) := + sum_le_sum (fun k _=>Fintype.card_subtype_le _) + _ = _ := by simp + _ ≤ _ := by + apply Nat.mul_le_mul_right + rw [levels_eq] + exact Nat.add_le_add_right (sourceLevels_le _ _) 1 + +noncomputable def sourceLabelsEquiv (w : V → V → ℚ) (K : ℕ) : + SourceLabel (fun x y=>(w x y:ℝ)) K ≃ Label w K := by + simpa only [SourceLabel,Label,realB_cast,levels_eq] using + (NumberedHierarchy.labelEquiv (realB w K) (realB_symm w K) (realB_tri w K) (levels w K)) + +lemma bags_card_le_two (w : V → V → ℚ) (K : ℕ) + (hw : ∀ x y,x≠y → BottleneckAlgorithm.edge w x y ≤ (4:ℚ)^K) (x : SourceVertex V K) : + (bags w K x).card≤2 := by + have he := NumberedHierarchy.bags_equiv (realB w K) (realB_symm w K) (realB_tri w K) + (realLeft K) (realRight K) (levels w K) x + rw [bags,←he] + apply Finset.card_image_le.trans + have hw' : ∀ x y,x≠y → edgeActivity (fun x y=>(w x y:ℝ)) x y ≤ (4:ℝ)^K := by + intro a b hab + have ha:=hw a b hab + have hec : ((BottleneckAlgorithm.edge w a b:ℚ):ℝ)=edgeActivity (fun x y=>(w x y:ℝ)) a b := by + unfold BottleneckAlgorithm.edge edgeActivity + split_ifs <;> norm_cast + simpa only [hec,Rat.cast_pow,Rat.cast_ofNat] using (Rat.cast_le (K:=ℝ)).mpr ha + apply Hierarchy.membership_count + · intro a b + rw [realB_cast] + exact sourceRealB_floor _ _ a b + · intro e + simpa only [realB_cast,levels_eq] using + (source_strength_le_max (fun x y=>(w x y:ℝ)) K hw' e).trans_lt + (maxSourceHeight_lt (fun x y=>(w x y:ℝ)) K hw') + · intro a e f he hf + simpa only [realB_cast] using source_strength_incident_near + (fun x y=>(w x y:ℝ)) K hw' a e f he hf + +end MatchingFPRAS.RationalSource + +end OAI diff --git a/lean/OAI/Combinatorics/MatchingCount/Graphs/RemainingBags.lean b/lean/OAI/Combinatorics/MatchingCount/Graphs/RemainingBags.lean new file mode 100644 index 0000000000000000000000000000000000000000..a65ba87ca4c0a32a36f54b84106f4d857c8f331e --- /dev/null +++ b/lean/OAI/Combinatorics/MatchingCount/Graphs/RemainingBags.lean @@ -0,0 +1,373 @@ +import Mathlib +import OAI.Combinatorics.MatchingCount.Sampling.Plan + +namespace OAI + +namespace MatchingFPRAS.UnitRefresh.Materialized + +open Finset MatchingFPRAS.FiniteChoice MatchingFPRAS.Variation +open scoped Classical + +variable {n m : ℕ} + +def remainingBags (bags : Fin (n+2) → Finset (Fin m)) (a : Fin (n+2)) + (c : Partner bags a) : Fin n → Finset (Fin m) := + fun x=>bags (removePairEquiv a c.val.1 c.property.1 x).val + +lemma remainingRanked (bags : Fin (n+2) → Finset (Fin m)) (rank : Fin m → ℕ) + (parent : Fin m → Option (Fin m)) (hb : RankedBags bags rank parent) + (a : Fin (n+2)) (c : Partner bags a) : RankedBags (remainingBags bags a c) rank parent := by + intro x l hl r hr + exact hb _ l hl r hr + +lemma remainingNonempty (bags : Fin (n+2) → Finset (Fin m)) + (hne : ∀ x,(bags x).Nonempty) (a : Fin (n+2)) (c : Partner bags a) : + ∀ x,(remainingBags bags a c x).Nonempty := fun _=>hne _ + +lemma remainingCard (bags : Fin (n+2) → Finset (Fin m)) (rank : Fin m → ℕ) + (parent : Fin m → Option (Fin m)) (hb : RankedBags bags rank parent) + (hne : ∀ x,(bags x).Nonempty) (hp : ∀ l p,parent l=some p → rank pbits i.castSucc.castSucc) := rfl + +noncomputable def renumberedSplitEquiv (bags : Fin (n+2) → Finset (Fin m)) (rank : Fin m → ℕ) + (parent : Fin m → Option (Fin m)) (hb : RankedBags bags rank parent) + (hne : ∀ x,(bags x).Nonempty) (hp : ∀ l p,parent l=some p → rank p + ColoredPairing.equiv (residualBags bags a c.val.val.1) + (removePairEquiv a c.val.val.1 c.val.property.1))).trans + (positiveSplitEquiv bags rank parent hb hne hp a) + +lemma renumberedSplitEquiv_apply (bags : Fin (n+2) → Finset (Fin m)) (rank : Fin m → ℕ) + (parent : Fin m → Option (Fin m)) (hb : RankedBags bags rank parent) + (hne : ∀ x,(bags x).Nonempty) (hp : ∀ l p,parent l=some p → rank pimageLaw (residualSampler k bags rank parent hb hne hp (Fin.last (n+1)) c)) := by + exact imageLaw_fin_skip n _ _ _ (sampleUnit_step k bags rank parent hb hne hp hz) + +lemma exact_unit_step (bags : Fin (n+2) → Finset (Fin m)) (rank : Fin m → ℕ) + (parent : Fin m → Option (Fin m)) (hb : RankedBags bags rank parent) + (hne : ∀ x,(bags x).Nonempty) (hp : ∀ l p,parent l=some p → rank p + (branchCount bags rank parent a c.val.val.1:ℝ)/count bags parent (plan rank)) + (fun c : PositivePartner bags rank parent a=> + push (uniform (ColoredPairing (remainingBags bags a c.val))) (assembleEdge bags a c.val))= + uniform (ColoredPairing bags) := by + let : Nonempty (ColoredPairing bags) := Fintype.card_pos_iff.mp (by + rwa [←computable_count_eq bags rank parent hb hne hp]) + have h := funext (uniform_sigma (renumberedSplitEquiv bags rank parent hb hne hp a)) + rw [push_sigmaLift] at h + simpa only [remainingCard bags rank parent hb hne hp,←computable_count_eq bags rank parent hb hne hp, + renumberedSplitEquiv_apply] using h + +open Finset MatchingFPRAS.Variation +open scoped Classical + +variable {m n : ℕ} + +lemma residualSampler_law (k : ℕ) (bags : Fin (n+2) → Finset (Fin m)) (rank : Fin m → ℕ) + (parent : Fin m → Option (Fin m)) (hb : RankedBags bags rank parent) + (hne : ∀ x,(bags x).Nonempty) (hp : ∀ l p,parent l=some p → rank p + let : Subsingleton (ColoredPairing bags) := ⟨fun p q=>ColoredPairing.ext + (Pairing.ext (fun x=>Fin.elim0 x)) (funext (fun x=>Fin.elim0 x))⟩ + rw [imageLaw_subsingleton,tv_self] + simp + | one => + rw [singleton_count_zero bags rank parent hb hne hp] at hz + omega + | more n ih _ => + let a : Fin (n+2) := Fin.last (n+1) + let p := imageLaw (drawEdge bags rank parent hb hne hp a hz k) + let q : PositivePartner bags rank parent a → ℝ := fun c=> + (branchCount bags rank parent a c.val.val.1:ℝ)/count bags parent (plan rank) + let u : PositivePartner bags rank parent a → ColoredPairing bags → ℝ := fun c=> + imageLaw (residualSampler k bags rank parent hb hne hp a c) + let v : PositivePartner bags rank parent a → ColoredPairing bags → ℝ := fun c=> + push (uniform (ColoredPairing (remainingBags bags a c.val))) (assembleEdge bags a c.val) + have hvn (c : PositivePartner bags rank parent a) (y : ColoredPairing bags) : 0 ≤ v c y := + push_nonneg _ uniform_nonneg _ _ + have hvs (c : PositivePartner bags rank parent a) : ∑ y,v c y=1 := by + let : Nonempty (ColoredPairing (remainingBags bags a c.val)) := + Fintype.card_pos_iff.mp (by rw [remainingCard bags rank parent hb hne hp]; exact c.property) + exact push_sum _ uniform_sum _ + have huv (c : PositivePartner bags rank parent a) : tv (u c) (v c) ≤ 2*(n:ℝ)^2*m/(2:ℝ)^k := by + dsimp only [u,v] + rw [residualSampler_law] + exact (push_contraction _ _ _).trans (ih (remainingBags bags a c.val) + (remainingRanked bags rank parent hb a c.val) (remainingNonempty bags hne a c.val) + (remainingPositive bags rank parent hb hne hp a c)) + have hpv := bind_perturbation p u v (imageLaw_nonneg _) (imageLaw_sum _) + (2*(n:ℝ)^2*m/(2:ℝ)^k) huv + have hpq := bind_contraction p q v hvn hvs + have hd := drawEdge_positive_tv bags rank parent hb hne hp a hz k + rw [sampleUnit_step_law,←exact_unit_step bags rank parent hb hne hp a hz] + change tv (bind p u) (bind q v)≤_ + calc + _ ≤ tv (bind p u) (bind p v)+tv (bind p v) (bind q v) := tv_triangle _ _ _ + _ ≤ (2*(n:ℝ)^2*m/(2:ℝ)^k)+(2*((n:ℝ)+2)*m/(2:ℝ)^k) := by + apply add_le_add hpv + exact hpq.trans (by simpa only [Nat.cast_add,Nat.cast_ofNat] using hd) + _ ≤ _ := by + rw [←add_div] + push_cast + apply div_le_div_of_nonneg_right _ (by positivity) + nlinarith [show (0:ℝ)≤n*m by positivity] + +end MatchingFPRAS.UnitRefresh.Materialized + +namespace MatchingFPRAS.UnitRefresh.Computable + +open Finset MatchingFPRAS.Transport + +variable {V L : Type*} [Fintype V] [Fintype L] [DecidableEq V] [DecidableEq L] + +variable {bags : V → Finset L} + +instance edgeDec (e : BagEdge bags) (x : V) : Decidable (e.Incident x) := + inferInstanceAs (Decidable (x∈e.val.val.1)) + +instance allowedDec (e : ColoredEdge V L) : Decidable (Allowed bags e) := + inferInstanceAs (Decidable (∀ x,x∈e.val.1 → e.val.2∈bags x)) + +def edge (M : PM (BagEdge.Incident (bags := bags))) (x : V) : BagEdge bags := + M.val.choose (fun e=>e.Incident x) (M.property.2 x (mem_univ x)) + +omit [Fintype L] [DecidableEq L] in +lemma edge_spec [DecidableEq L] (M : PM (BagEdge.Incident (bags := bags))) (x : V) : + edge M x∈M.val ∧ (edge M x).Incident x := + M.val.choose_spec _ (M.property.2 x (mem_univ x)) + +lemma edge_eq (M : PM (BagEdge.Incident (bags := bags))) (x : V) : edge M x=chosenEdge M x := + chosenEdge_unique M x _ (edge_spec M x).1 (edge_spec M x).2 + +def mate (M : PM (BagEdge.Incident (bags := bags))) (x : V) : V := + Sym2.Mem.other' (edge_spec M x).2 + +lemma mate_eq (M : PM (BagEdge.Incident (bags := bags))) (x : V) : mate M x=chosenMate M x := by + have hp : s(x,mate M x)=(edge M x).val.val.1 := Sym2.other_spec' (edge_spec M x).2 + apply (Sym2.congr_right (a:=x)).mp + exact hp.trans (by rw [edge_eq,←chosenMate_pair]) + +def fromMatching (M : PM (BagEdge.Incident (bags := bags))) : ColoredPairing bags where + pair := ⟨mate M,(fun x=>by simpa only [mate_eq] using chosenMate_involutive M x), + fun x=>by simpa only [mate_eq] using chosenMate_ne M x⟩ + color x := (edge M x).val.color + allowed x := (edge M x).property x (edge_spec M x).2 + same_color x := by + simp only [mate_eq,edge_eq] + exact congrArg (fun e : BagEdge bags=>e.val.color) (chosenEdge_chosenMate M x) + +lemma from_eq (M : PM (BagEdge.Incident (bags := bags))) : fromMatching M=fromPM M := by + apply ColoredPairing.ext + · apply Pairing.ext; intro x; exact mate_eq M x + · funext x; exact congrArg (fun e : BagEdge bags=>e.val.color) (edge_eq M x) + +def toMatching (p : ColoredPairing bags) : PM (BagEdge.Incident (bags := bags)) := + ⟨Finset.univ.image p.edgeAt,by exact p.toPM.property⟩ + +omit [Fintype L] in +lemma to_eq [Fintype L] (p : ColoredPairing bags) : toMatching p=p.toPM := rfl + +def pairingEquiv : PM (BagEdge.Incident (bags := bags)) ≃ ColoredPairing bags where + toFun := fromMatching + invFun := toMatching + left_inv M := by + rw [from_eq,to_eq] + exact (coloredPMEquiv (bags:=bags)).left_inv M + right_inv p := by + rw [to_eq,from_eq] + exact (coloredPMEquiv (bags:=bags)).right_inv p + +end MatchingFPRAS.UnitRefresh.Computable + +namespace MatchingFPRAS.UnitRefresh + +open Finset MatchingFPRAS.Variation + +def orderedEnum (α : Type*) [Fintype α] [LinearOrder α] : Fin (Fintype.card α) ≃ α := + ((univ : Finset α).orderIsoOfFin (card_univ)).toEquiv.trans + (Equiv.subtypeUnivEquiv (fun _=>mem_univ _)) + +variable {V L J : Type*} [Fintype V] [DecidableEq V] [Fintype L] [Fintype J] [DecidableEq L] [DecidableEq J] + +def ColoredPairing.colorEquiv (bags : V → Finset L) (e : L ≃ J) : + ColoredPairing bags ≃ ColoredPairing (fun x=>(bags x).map e.toEmbedding) where + toFun p := { + pair:=p.pair + color:=fun x=>e (p.color x) + allowed:=fun x=>by simpa using p.allowed x + same_color:=fun x=>congrArg e (p.same_color x) } + invFun p := { + pair:=p.pair + color:=fun x=>e.symm (p.color x) + allowed:=fun x=>by + obtain ⟨l,hl,he⟩:=mem_map.mp (p.allowed x) + simpa only [←he,Equiv.toEmbedding_apply,Equiv.symm_apply_apply] using hl + same_color:=fun x=>congrArg e.symm (p.same_color x) } + left_inv p := by + apply ColoredPairing.ext + · rfl + · funext x; exact e.symm_apply_apply _ + right_inv p := by + apply ColoredPairing.ext + · rfl + · funext x; exact e.apply_symm_apply _ + +open Finset MatchingFPRAS.Variation + +variable {V L : Type*} [Fintype V] [LinearOrder V] [Fintype L] [LinearOrder L] + +def numberedBags (bags : V → Finset L) : Fin (Fintype.card V) → Finset (Fin (Fintype.card L)) := + fun x=>(bags (orderedEnum V x)).map (orderedEnum L).symm.toEmbedding + +lemma mem_numberedBags (bags : V → Finset L) (x : Fin (Fintype.card V)) (l : Fin (Fintype.card L)) : + l∈numberedBags bags x ↔ orderedEnum L l∈bags (orderedEnum V x) := by + simp [numberedBags] + +def numberedRank (rank : L → ℕ) : Fin (Fintype.card L) → ℕ := fun l=>rank (orderedEnum L l) + +def numberedParent (parent : L → Option L) : Fin (Fintype.card L) → Option (Fin (Fintype.card L)) := + fun l=>(parent (orderedEnum L l)).map (orderedEnum L).symm + +lemma numberedParent_iff (parent : L → Option L) (l p : Fin (Fintype.card L)) : + numberedParent parent l=some p ↔ parent (orderedEnum L l)=some (orderedEnum L p) := by + simp [numberedParent,Equiv.symm_apply_eq] + +lemma numberedRanked (bags : V → Finset L) (rank : L → ℕ) (parent : L → Option L) + (hb : RankedBags bags rank parent) : + RankedBags (numberedBags bags) (numberedRank rank) (numberedParent parent) := by + intro x a ha b hb' hab + rcases hb (orderedEnum V x) (orderedEnum L a) ((mem_numberedBags bags x a).mp ha) + (orderedEnum L b) ((mem_numberedBags bags x b).mp hb') + (fun h=>hab ((orderedEnum L).injective h)) with ⟨hlt,hp⟩|⟨hlt,hp⟩ + · exact Or.inl ⟨hlt,(numberedParent_iff parent b a).mpr hp⟩ + · exact Or.inr ⟨hlt,(numberedParent_iff parent a b).mpr hp⟩ + +lemma numberedNonempty (bags : V → Finset L) (hne : ∀ x,(bags x).Nonempty) : + ∀ x,(numberedBags bags x).Nonempty := fun x=>(hne (orderedEnum V x)).map + +lemma numberedDecreasing (rank : L → ℕ) (parent : L → Option L) + (hp : ∀ l p,parent l=some p → rank pbags (orderedEnum V x)) (orderedEnum L).symm).symm.trans + (ColoredPairing.equiv bags (orderedEnum V)) + +lemma numbered_count_pos (bags : V → Finset L) (rank : L → ℕ) (parent : L → Option L) + (hb : RankedBags bags rank parent) (hne : ∀ x,(bags x).Nonempty) + (hp : ∀ l p,parent l=some p → rank p + constructor + · constructor + · intro i; norm_num [scalingTrace,alpha] + · intro i; simp [scalingTrace] + · intro i j h; have := (hG i j h).2; simp only [scalingTrace]; linarith + · intro i hi; omega + | succ k ih => + by_cases hk : k (hG i j h).1) ih.1 i + have htrace : scalingTrace hn G (k+1)=scaleUpdate hn G (scalingTrace hn G k) i := by + simp [scalingTrace,hk,i] + rw [htrace] + refine ⟨hinv,?_⟩ + intro a ha + by_cases hak : a.val fun h => ?_⟩ + · intro k i + by_cases hk : k ⟨h i,(htrace n).1.upper i⟩,(htrace n).1.feasible,?_⟩ + intro i + exact (htrace n).2 i i.isLt + + + + +def rowPeak {n : ℕ} (hn : 2 ≤ n) (g : Fin n → Fin n → ℝ) (i : Fin n) : ℝ := + (univ.erase i).sup' (others_nonempty hn i) (g i) + +def scaledHoleMatrix {n : ℕ} (g : Fin n → Fin n → ℝ) (v : Fin n → ℝ) (i j : Fin n) : ℝ := + g i j/(v i*v j) + +def BalancedRows {n : ℕ} (hn : 2 ≤ n) (g : Fin n → Fin n → ℝ) : Prop := + ∀ i, (1:ℝ)/4 ≤ rowPeak hn g i ∧ rowPeak hn g i ≤ 1 + + + + +theorem one_pass_restores_balance {n : ℕ} (hn : 2 ≤ n) (g G : Fin n → Fin n → ℝ) + (hGsym : ∀ i j, G i j=G j i) + (hG : ∀ i j, i≠j → alpha ≤ G i j ∧ G i j ≤ 3) + (hpre : ∀ i, (1:ℝ)/8 ≤ rowPeak hn g i) + (haccuracy : ∀ i j, i≠j → g i j ≤ G i j ∧ G i j ≤ g i j+2*alpha) : + (∀ i, (1:ℝ)/16 ≤ scalingTrace hn G n i) ∧ + BalancedRows hn (scaledHoleMatrix g (scalingTrace hn G n)) := by + let v := scalingTrace hn G n + have hv := (scalingTrace_invariant hn G hGsym hG n).1 + have hlow (i : Fin n) : (1:ℝ)/16 ≤ v i := by + obtain ⟨j,hj,heq⟩ := Finset.exists_mem_eq_sup' (others_nonempty hn i) (g i) + have hji := (mem_erase.mp hj).1 + change rowPeak hn g i=g i j at heq + have hgij : (1:ℝ)/8 ≤ g i j := by rw [← heq]; exact hpre i + have hGi := (haccuracy i j hji.symm).1 + have hfeas := hv.feasible i j hji.symm + have hup := mul_le_mul_of_nonneg_left (hv.upper j) (hv.pos i).le + dsimp [v] + linarith + refine ⟨hlow,?_⟩ + intro i + constructor + · obtain ⟨j,hji,heq⟩ := (one_pass_scaling hn G hGsym hG).2.2.2 i + have hprod : (1:ℝ)/256 ≤ v i*v j := by + calc + (1:ℝ)/256 = ((1:ℝ)/16)*((1:ℝ)/16) := by norm_num + _ ≤ v i*v j := mul_le_mul (hlow i) (hlow j) (by norm_num) (hv.pos i).le + have hacc := (haccuracy i j hji.symm).2 + have hg : (1:ℝ)/4 ≤ scaledHoleMatrix g v i j := by + apply (le_div_iff₀ (mul_pos (hv.pos i) (hv.pos j))).mpr + change v i*v j=G i j at heq + norm_num [alpha] at hacc + nlinarith + apply hg.trans + exact Finset.le_sup' (scaledHoleMatrix g v i) (mem_erase.mpr ⟨hji,mem_univ _⟩) + · apply Finset.sup'_le + intro j hj + have hji := (mem_erase.mp hj).1 + apply (div_le_one (mul_pos (hv.pos i) (hv.pos j))).mpr + exact ((haccuracy i j hji.symm).1).trans (hv.feasible i j hji.symm) + + + +def sigma (D K : ℕ) (epsilon : ℝ) : ℝ := min (alpha/(100*D)) (epsilon/(1000*K)) + +def ratioEstimate (abar dbar : ℝ) : ℝ := if 0 Switching.holeRatio w {i,j}) i= + rowMax (by simpa using hn) w i := rfl + +structure StageData (n K T : ℕ) where + hn : 2 ≤ n + w : Fin n → Fin n → ℝ + next : Fin n → Fin n → ℝ + positive : ∀ i j,0 < w i j + next_positive : ∀ i j,0 < next i j + partition_positive : 0 < partition w ∅ + lower : ∀ i,(1:ℝ)/4 ≤ rowMax (by simpa using hn) w i + upper : ∀ i,rowMax (by simpa using hn) w i ≤ 1 + cool_lower : ∀ i j,i≠j → (1+1/(n:ℝ))⁻¹*w i j ≤ next i j + cool_upper : ∀ i j,i≠j → next i j ≤ w i j + cap : ∀ i j,i≠j → edgeActivity w i j ≤ (4:ℝ)^K + stages : 1 ≤ T + epsilon : ℝ + epsilon_positive : 0 < epsilon + epsilon_lt_one : epsilon < 1 + +variable {K T : ℕ} + +structure EmpiricalData (c : StageData n K T) where + abar : ℝ + dbar : ℝ + zbar : LogicalEdge (Fin n) → ℝ + errorA : |abar-meanA c.w K| ≤ RealStage.sigma (sourceD (V:=Fin n) K) T c.epsilon + errorD : |dbar-meanD c.w c.next K| ≤ RealStage.sigma (sourceD (V:=Fin n) K) T c.epsilon + errorProbe : ∀ e,|zbar e-meanProbe c.w c.next K e| ≤ RealStage.sigma (sourceD (V:=Fin n) K) T c.epsilon + +omit [Nontrivial (Fin n)] in +lemma StageData.cooling (c : StageData n K T) (R : Finset (Fin n)) : + partition c.w R/2 ≤ partition c.next R ∧ partition c.next R ≤ partition c.w R := by + apply partition_cooling (by simpa using c.hn) c.w c.next (fun i j => (c.positive i j).le) + · simpa using c.cool_lower + · exact c.cool_upper + +lemma StageData.mean_bounds (c : StageData n K T) : + (1:ℝ)/2 ≤ meanA c.w K ∧ (1:ℝ)/4 ≤ meanD c.w c.next K ∧ + meanD c.w c.next K/meanA c.w K=partition c.next ∅/partition c.w ∅ ∧ + (1:ℝ)/2 ≤ meanD c.w c.next K/meanA c.w K ∧ meanD c.w c.next K/meanA c.w K ≤ 1 ∧ + (∀ e,(sourceD (V:=Fin n) K:ℝ)*meanProbe c.w c.next K e/meanD c.w c.next K= + Switching.holeRatio c.next {source e,target e}) := by + have h := source_observable_means (V:=Fin n) (by simpa using c.hn) c.w c.next c.positive c.partition_positive + c.lower c.upper (by simpa using c.cool_lower) c.cool_upper K c.cap + unfold meanA meanD meanProbe + exact h.2.2 + +omit [Nontrivial (Fin n)] in +lemma StageData.hole_upper (c : StageData n K T) (i j : Fin n) (hij : i≠j) : + Switching.holeRatio c.next {i,j} ≤ 2 := by + have h := (holeRatio_cooling c.w c.next (fun i j => (c.positive i j).le) + c.partition_positive c.cooling {i,j}).2 + have hr := (holeRatio_le_rowMax (by simpa using c.hn) c.w i j hij).trans (c.upper i) + linarith + +theorem actual_stage_statistics (c : StageData n K T) (b : EmpiricalData c) (i j : Fin n) (hij : i≠j) : + let G := estimateMatrix (sourceD (V:=Fin n) K) b.dbar b.zbar + 0 < b.abar ∧ 0 < b.dbar ∧ + |RealStage.ratioEstimate b.abar b.dbar/(partition c.next ∅/partition c.w ∅)-1| ≤ c.epsilon/(100*T) ∧ + RealStage.alpha ≤ G i j ∧ G i j ≤ 3 ∧ + Switching.holeRatio c.next {i,j} ≤ G i j ∧ + G i j ≤ Switching.holeRatio c.next {i,j}+2*RealStage.alpha := by + dsimp only + have hm := c.mean_bounds + have hem := hm.2.2.2.2.2 (pairEdge i j hij) + rw [pairEdge_holes] at hem + have hg0 := holeRatio_nonneg c.next (fun x y => (c.next_positive x y).le) {i,j} + have h := RealStage.successful_stage_estimates (sourceD (V:=Fin n) K) T (sourceD_one K) + c.stages c.epsilon c.epsilon_positive c.epsilon_lt_one + (meanA c.w K) (meanD c.w c.next K) (meanProbe c.w c.next K (pairEdge i j hij)) + b.abar b.dbar (b.zbar (pairEdge i j hij)) hm.1 hm.2.1 + ⟨hm.2.2.2.1,hm.2.2.2.2.1⟩ + ⟨by rw [hem]; exact hg0,by rw [hem]; exact c.hole_upper i j hij⟩ + b.errorA b.errorD (b.errorProbe _) + refine ⟨h.1,h.2.1,?_,?_⟩ + · have he := h.2.2.1.trans h.2.2.2.1 + rwa [hm.2.2.1] at he + · simpa only [estimateMatrix,probeMatrix_off _ _ _ hij,hem] using h.2.2.2.2 + +theorem actual_successful_stage (c : StageData n K T) (b : EmpiricalData c) : + let G := estimateMatrix (sourceD (V:=Fin n) K) b.dbar b.zbar + let v := RealStage.scalingTrace c.hn G n + (∀ i,(1:ℝ)/16 ≤ v i ∧ v i ≤ 2) ∧ + (∀ i,(1:ℝ)/4 ≤ rowMax (by simpa using c.hn) (fun x y => c.next x y*v x*v y) i ∧ + rowMax (by simpa using c.hn) (fun x y => c.next x y*v x*v y) i ≤ 1) ∧ + |RealStage.ratioEstimate b.abar b.dbar/(partition c.next ∅/partition c.w ∅)-1| ≤ c.epsilon/(100*T) := by + dsimp only + let G := estimateMatrix (sourceD (V:=Fin n) K) b.dbar b.zbar + let g := fun i j => Switching.holeRatio c.next {i,j} + have hest := actual_stage_statistics c b + have hGs := estimateMatrix_symm (sourceD (V:=Fin n) K) b.dbar b.zbar + have hGb : ∀ i j,i≠j → RealStage.alpha ≤ G i j ∧ G i j ≤ 3 := by + intro i j hij + exact ⟨(hest i j hij).2.2.2.1,(hest i j hij).2.2.2.2.1⟩ + have hGa : ∀ i j,i≠j → g i j ≤ G i j ∧ G i j ≤ g i j+2*RealStage.alpha := by + intro i j hij + exact (hest i j hij).2.2.2.2.2 + have hpre : ∀ i,(1:ℝ)/8 ≤ RealStage.rowPeak c.hn g i := by + intro i + rw [show g=(fun i j => Switching.holeRatio c.next {i,j}) from rfl,rowPeak_holeMatrix] + exact rowMax_cooling_lower (by simpa using c.hn) c.w c.next (fun x y => (c.positive x y).le) + c.partition_positive c.lower c.cooling i + have hb := RealStage.one_pass_restores_balance c.hn g G hGs hGb hpre hGa + let v := RealStage.scalingTrace c.hn G n + have hv := (RealStage.scalingTrace_invariant c.hn G hGs hGb n).1 + have heq (i j : Fin n) (hij : i≠j) : + Switching.holeRatio (fun x y => c.next x y*v x*v y) {i,j}=RealStage.scaledHoleMatrix g v i j := by + rw [holeRatio_vertex_scaling c.next v (fun x => hv.pos x),Finset.prod_pair hij] + rfl + have hb' (i : Fin n) : (1:ℝ)/4 ≤ rowMax (by simpa using c.hn) (fun x y => c.next x y*v x*v y) i ∧ + rowMax (by simpa using c.hn) (fun x y => c.next x y*v x*v y) i ≤ 1 := by + have he : rowMax (by simpa using c.hn) (fun x y => c.next x y*v x*v y) i= + RealStage.rowPeak c.hn (RealStage.scaledHoleMatrix g v) i := by + unfold rowMax RealStage.rowPeak + apply Finset.sup'_congr _ rfl + intro j hj + exact heq i j (Finset.mem_erase.mp hj).1.symm + rw [he] + exact hb.2 i + refine ⟨fun i => ⟨hb.1 i,hv.upper i⟩,hb',?_⟩ + let i : Fin n := ⟨0,by have := c.hn; omega⟩ + let j : Fin n := ⟨1,by have := c.hn; omega⟩ + have hij : i≠j := by intro h; have := Fin.val_eq_of_eq h; dsimp [i,j] at this; omega + exact (hest i j hij).2.2.1 + +end MatchingFPRAS.Enlargement + +end OAI diff --git a/lean/OAI/Combinatorics/MatchingCount/Graphs/SafeSwitch.lean b/lean/OAI/Combinatorics/MatchingCount/Graphs/SafeSwitch.lean new file mode 100644 index 0000000000000000000000000000000000000000..c5b8d2c993145c06ef6d6ddeb1708c37711f35d0 --- /dev/null +++ b/lean/OAI/Combinatorics/MatchingCount/Graphs/SafeSwitch.lean @@ -0,0 +1,451 @@ +import Mathlib +import OAI.Combinatorics.MatchingCount.Sampling.Through + +namespace OAI + +namespace MatchingFPRAS.Transport.IndexedCycle + +variable {V E : Type*} [Fintype V] [DecidableEq V] [DecidableEq E] + +variable {inc : E → V → Prop} + +omit [Fintype V] [DecidableEq V] in +lemma parityPattern_subset_edgeSet (c : IndexedCycle inc) (a : ℕ) : c.parityPattern a ⊆ c.edgeSet := by + intro e he + obtain ⟨i,_,hi,_,rfl⟩ := (c.mem_intervalPattern e 0 c.size a).mp he + exact c.edgeAt_mem_edgeSet i + +end MatchingFPRAS.Transport.IndexedCycle + +namespace MatchingFPRAS.Transport.CellDemands + +variable {V L : Type*} [Fintype V] [DecidableEq V] [Fintype L] [DecidableEq L] + +variable {bags : V → Finset L} {G : SimpleGraph L} + +noncomputable local instance : Fintype (BagEdge bags) := Fintype.ofFinite _ + +variable {hbags : ∀ v, ∀ a ∈ bags v, ∀ b ∈ bags v, a = b ∨ G.Adj a b} + +variable {hG : G.IsAcyclic} + +namespace Demand + +variable (d : Demand hbags hG) + +omit [Fintype L] in +lemma outside_disjoint_through (i : Fin 4) : Disjoint d.outside (d.paths.side i).through := by + have hp := d.corners.cell_orientation_parity d.paths.chord d.paths.chord_incidence (CellPaths.sideBit i) + have hsub : (d.paths.side i).through ⊆ d.cycle.edgeSet := by + apply Finset.Subset.trans (d.paths.through_subset_orientation (CellPaths.sideBit i) i rfl) + exact hp ▸ d.cycle.parityPattern_subset_edgeSet _ + exact Finset.disjoint_left.mpr fun _ he hi => (Finset.mem_sdiff.mp he).2 (hsub hi) + +omit [Fintype L] in +lemma short_error_zero (f : Finset (BagEdge bags) → ℝ) (b : Bool) + (hh : ¬ ∀ i : Fin 4, CellPaths.sideBit i = b → (d.paths.side i).length ≠ 1) : + d.paths.contextError d.outside f b (if b then 2 else 3) (if b then 0 else 1) = 0 := by + classical + push Not at hh + obtain ⟨i,hib,hil⟩ := hh + have he := d.cycle.cellShort_pattern hbags d.cell d.last_lt i hil + cases b <;> fin_cases i <;> simp_all [CellPaths.sideBit] + · exact d.paths.contextError_short_right d.outside f false 3 1 (by decide) he + · exact d.paths.contextError_short_left d.outside f false 3 1 (by decide) (by decide) + (by decide) BagEdge.exists_incident he + · exact d.paths.contextError_short_right d.outside f true 2 0 (by decide) he + · exact d.paths.contextError_short_left d.outside f true 2 0 (by decide) (by decide) + (by decide) BagEdge.exists_incident he + +end Demand + +namespace ErrorDemand + +variable (height : L → ℝ) (hheight : ∀ l, 0 < height l) + +variable (hstep : ∀ a b, G.Adj a b → height a ≤ 2 * height b) + +variable (D : ℝ) (hD : 1 ≤ D) (w : BagEdge bags → ℝ) + +variable (hw : ∀ e, height e.color / D ≤ w e ∧ w e ≤ 3 * height e.color) + +variable (lo hi : ℝ) (hlo : 0 < lo) (hlohi : lo ≤ hi) + +variable (f g : Finset (BagEdge bags) → ℝ) + +variable (e : ErrorDemand hbags hG) + +lemma literal_error : + e.demand.paths.contextError e.demand.outside f e.bit e.X e.Y = + PatternCode.firstDerivative f e.pattern + (e.choice height hheight hstep D hD w hw lo hi hlo hlohi true).first - + PatternCode.firstDerivative f e.pattern + (e.choice height hheight hstep D hD w hw lo hi hlo hlohi false).first := by + simp only [PatternCode.firstDerivative, + (e.choice_spec height hheight hstep D hD w hw lo hi hlo hlohi true).1, + (e.choice_spec height hheight hstep D hD w hw lo hi hlo hlohi false).1, + Bool.false_eq_true,ite_false,ite_true] + exact e.demand.paths.contextError_derivative e.demand.outside f e.bit e.X e.Y + (e.demand.outside_disjoint_through e.X) + +include hheight hstep hD hw hlohi + +theorem error_load_bound (M : PM (BagEdge.Incident (bags := bags))) : + let wt := fun e => max lo (min hi (w e)) + let π := gibbsLaw wt (fun _ => lt_of_lt_of_le hlo (le_max_left _ _)) M + (∑ e : ErrorDemand hbags hG, π.weight e.demand.1.1 * π.weight e.demand.1.2 * + (e.demand.paths.contextError e.demand.outside f e.bit e.X e.Y)^2) ≤ + 4 * ((1000*D)^4 * Fintype.card (DemandTag (V := V) (E := BagEdge bags))) * + MatchingFPRAS.PairEnergy.swapSum π PatternCode.throughStates PatternCode.closedStates + (PatternCode.firstDerivative f) (PatternCode.secondDerivative g) := by + classical + dsimp only + let wt := fun e => max lo (min hi (w e)) + let π := gibbsLaw wt (fun _ => lt_of_lt_of_le hlo (le_max_left _ _)) M + let ρ := fun e : ErrorDemand hbags hG => π.weight e.demand.1.1 * π.weight e.demand.1.2 + let enc := fun j (e : ErrorDemand hbags hG) => e.choice height hheight hstep D hD w hw lo hi hlo hlohi j + have h := MatchingFPRAS.PairEnergy.error_demand_load π PatternCode.throughStates + PatternCode.closedStates (PatternCode.firstDerivative f) (PatternCode.secondDerivative g) + ρ pattern (fun e => (enc false e).first) (fun e => (enc true e).first) + ((1000*D)^4 * Fintype.card (DemandTag (V := V) (E := BagEdge bags))) + (fun e => mul_nonneg (π.nonneg _) (π.nonneg _)) (by positivity) + (fun e => e.choice_through height hheight hstep D hD w hw lo hi hlo hlohi false) + (fun e => e.choice_through height hheight hstep D hD w hw lo hi hlo hlohi true) + (context_load height hheight hstep D hD w hw lo hi hlo hlohi M false) + (context_load height hheight hstep D hD w hw lo hi hlo hlohi M true) + convert h using 1 + apply Finset.sum_congr rfl + intro e _ + rw [e.literal_error height hheight hstep D hD w hw lo hi hlo hlohi f] + +end ErrorDemand + +end MatchingFPRAS.Transport.CellDemands + +namespace MatchingFPRAS.Transport.PatternCode + +variable {V E : Type*} [Fintype V] [DecidableEq V] [Fintype E] [DecidableEq E] + +variable {inc : E → V → Prop} + +variable (π : MatchingFPRAS.PairEnergy.Law (PM inc)) (f g : Finset E → ℝ) + +omit [DecidableEq V] in +lemma statewise_swap_bound (A B : PM inc) : + (∑ x : PatternCode inc, if x.through ⊆ A.val ∧ x.closed ⊆ B.val then + (firstDerivative f x A - secondDerivative g x B)^2 else 0) ≤ + ∑ S ∈ components (inc := inc) (A.val ∪ B.val), + ((f A.val + g B.val) - (f (exchange A.val B.val S) + g (exchange B.val A.val S)))^2 := by + have h := activated_sum_le A.property B.property f g + convert h using 1 + apply Finset.sum_congr rfl + intro x _ + split_ifs with hx + · rw [Finset.sdiff_union_of_subset hx.1,Finset.sdiff_union_of_subset hx.2] + rfl + · rfl + +omit [DecidableEq V] in +theorem weighted_swap_bound : + MatchingFPRAS.PairEnergy.swapSum π throughStates closedStates + (firstDerivative f) (secondDerivative g) ≤ + ∑ A : PM inc, ∑ B : PM inc, π.weight A * π.weight B * + ∑ S ∈ components (inc := inc) (A.val ∪ B.val), + ((f A.val + g B.val) - (f (exchange A.val B.val S) + g (exchange B.val A.val S)))^2 := by + classical + let cost := fun (x : PatternCode inc) (A B : PM inc) => + if x.through ⊆ A.val ∧ x.closed ⊆ B.val then + (firstDerivative f x A - secondDerivative g x B)^2 else 0 + have hsum : MatchingFPRAS.PairEnergy.swapSum π throughStates closedStates + (firstDerivative f) (secondDerivative g) = + ∑ A : PM inc, ∑ B : PM inc, π.weight A * π.weight B * ∑ x : PatternCode inc, cost x A B := by + unfold MatchingFPRAS.PairEnergy.swapSum + calc + _ = ∑ x : PatternCode inc, ∑ A : PM inc, ∑ B : PM inc, + π.weight A * π.weight B * cost x A B := by + apply Finset.sum_congr rfl + intro x _ + simp only [throughStates,closedStates,Finset.sum_filter] + apply Finset.sum_congr rfl + intro A _ + by_cases ht : x.through ⊆ A.val + · simp only [ht,ite_true] + apply Finset.sum_congr rfl + intro B _ + by_cases hc : x.closed ⊆ B.val <;> simp [cost,ht,hc] + · simp [cost,ht] + _ = ∑ A : PM inc, ∑ B : PM inc, ∑ x : PatternCode inc, + π.weight A * π.weight B * cost x A B := by + rw [Finset.sum_comm] + apply Finset.sum_congr rfl + intro A _ + rw [Finset.sum_comm] + _ = _ := by simp only [Finset.mul_sum] + rw [hsum] + apply Finset.sum_le_sum + intro A _ + apply Finset.sum_le_sum + intro B _ + exact mul_le_mul_of_nonneg_left (statewise_swap_bound f g A B) + (mul_nonneg (π.nonneg A) (π.nonneg B)) + +end MatchingFPRAS.Transport.PatternCode + +namespace MatchingFPRAS.Transport + +variable {V E : Type*} [Fintype V] [DecidableEq V] [Fintype E] [DecidableEq E] + +variable {inc : E → V → Prop} + +def SafeSwitch (w : E → ℝ) (K : ℝ) (A B : PM inc) : Prop := + ∃ (v : Fin 4 → V) (e : Fin 4 → E) (R : Finset E), + Function.Injective v ∧ + (∀ i x, inc (e i) x ↔ x = v i ∨ x = v (i+1)) ∧ + A.val = R ∪ {e 0,e 2} ∧ B.val = R ∪ {e 1,e 3} ∧ + (∀ i j, w (e i) ≤ K * w (e j)) + +noncomputable def safeDestinations (w : E → ℝ) (K : ℝ) (A : PM inc) : Finset (PM inc) := by + classical + exact Finset.univ.filter (SafeSwitch w K A) + +namespace CellPaths + +variable (c : CellPaths inc) + +def commonInterior : Finset E := assemble fun i => (c.side i).interior + +omit [Fintype V] [Fintype E] in +lemma switched_true_common : c.switched true = c.commonInterior ∪ {c.chord 0,c.chord 2} := by + ext e + simp [switched,switchPieces,pieces,assemble,sideBit,OddPath.closed,commonInterior] + tauto + +omit [Fintype V] [Fintype E] in +lemma switched_false_common : c.switched false = c.commonInterior ∪ {c.chord 1,c.chord 3} := by + ext e + simp [switched,switchPieces,pieces,assemble,sideBit,OddPath.closed,commonInterior] + tauto + +omit [Fintype E] in +lemma safe_switch (w : E → ℝ) (K : ℝ) (hw : ∀ i j, w (c.chord i) ≤ K*w (c.chord j)) + (R : Finset E) (A B : PM inc) + (hA : A.val = R ∪ c.switched true) (hB : B.val = R ∪ c.switched false) : + SafeSwitch w K A B := by + refine ⟨fun i => (c.side i).vertex 0,c.chord,R ∪ c.commonInterior, + c.corners_injective,?_,?_,?_,hw⟩ + · intro i x + rw [c.chord_incidence,c.joins] + · rw [hA,c.switched_true_common,Finset.union_assoc] + · rw [hB,c.switched_false_common,Finset.union_assoc] + +end CellPaths + +end MatchingFPRAS.Transport + +namespace MatchingFPRAS.Transport.CellDemands + +section + +variable {V L : Type*} [Fintype V] [DecidableEq V] [Fintype L] [DecidableEq L] + +variable {bags : V → Finset L} {G : SimpleGraph L} + +noncomputable local instance : Fintype (BagEdge bags) := Fintype.ofFinite _ + +variable {hbags : ∀ v, ∀ a ∈ bags v, ∀ b ∈ bags v, a = b ∨ G.Adj a b} + +variable {hG : G.IsAcyclic} + +namespace Demand + +variable (d : Demand hbags hG) + +noncomputable def switchState (b : Bool) : PM (BagEdge.Incident (bags := bags)) := + let emb := d.corners.embeddedPair d.1.1 d.1.2 d.2.1.cycle_union + d.paths.chord d.paths.chord_incidence 0 + emb.attachFirst (d.paths.switched b) (d.paths.switched_matching b) + +omit [Fintype L] in +lemma switchState_val (b : Bool) : (d.switchState b).val = d.outside ∪ d.paths.switched b := by + exact congrArg (fun R => R ∪ d.paths.switched b) + (d.corners.embeddedPair_outside d.1.1 d.1.2 d.2.1.cycle_union + d.paths.chord d.paths.chord_incidence 0) + +variable (height : L → ℝ) (hheight : ∀ l, 0 < height l) + +variable (hstep : ∀ a b, G.Adj a b → height a ≤ 2 * height b) + +variable (D : ℝ) (hD : 1 ≤ D) (w : BagEdge bags → ℝ) + +variable (hw : ∀ e, height e.color / D ≤ w e ∧ w e ≤ 3 * height e.color) + +variable (lo hi : ℝ) (hlo : 0 < lo) (hlohi : lo ≤ hi) + +include hheight hstep hD hw hlo in +omit [Fintype L] in +lemma switchState_safe : SafeSwitch (fun e => max lo (min hi (w e))) (1000*D) + (d.switchState true) (d.switchState false) := by + apply d.paths.safe_switch _ _ _ d.outside _ _ (d.switchState_val true) (d.switchState_val false) + intro i j + exact d.cycle.cell_clamp_comparability hbags height hheight hstep d.cell d.last_lt D hD w hw + lo hi (le_of_lt hlo) ⟨i,Or.inl rfl⟩ ⟨j,Or.inl rfl⟩ + +lemma switchChoice_first : + (d.switchChoice height hheight hstep D hD w hw lo hi hlo hlohi).first = d.switchState true := by + apply Subtype.ext + exact (d.switchChoice_spec height hheight hstep D hD w hw lo hi hlo hlohi).1.trans + (d.switchState_val true).symm + +include hheight hstep hD hw hlohi + +theorem switch_load_bound (M : PM (BagEdge.Incident (bags := bags))) + (f : Finset (BagEdge bags) → ℝ) : + let wt := fun e => max lo (min hi (w e)) + let π := gibbsLaw wt (fun _ => lt_of_lt_of_le hlo (le_max_left _ _)) M + (∑ d : Demand hbags hG, π.weight d.1.1 * π.weight d.1.2 * + (f (d.outside ∪ d.paths.switched true) - f (d.outside ∪ d.paths.switched false))^2) ≤ + ((1000*D)^4 * Fintype.card (DemandTag (V := V) (E := BagEdge bags))) * + ∑ A : PM BagEdge.Incident, π.weight A * + ∑ B ∈ safeDestinations wt (1000*D) A, (f A.val-f B.val)^2 := by + classical + dsimp only + let wt := fun e => max lo (min hi (w e)) + let π := gibbsLaw wt (fun _ => lt_of_lt_of_le hlo (le_max_left _ _)) M + let ρ := fun d : Demand hbags hG => π.weight d.1.1 * π.weight d.1.2 + let enc := fun d : Demand hbags hG => d.switchChoice height hheight hstep D hD w hw lo hi hlo hlohi + let C := (1000*D)^4 * Fintype.card (DemandTag (V := V) (E := BagEdge bags)) + let cost := fun A : PM BagEdge.Incident => + ∑ B ∈ safeDestinations wt (1000*D) A, (f A.val-f B.val)^2 + have hc (A) : 0 ≤ cost A := Finset.sum_nonneg fun _ _ => sq_nonneg _ + have hload (A : PM BagEdge.Incident) : + MatchingFPRAS.PairEnergy.contextMass ρ (fun _ => ()) (fun d => (enc d).first) () A ≤ C*π.weight A := by + have h := MatchingFPRAS.PairEnergy.tagged_context_bound π (fun _ : Unit => Finset.univ) ρ + (fun _ => ()) (fun d => (enc d).first) (fun d => (enc d).second) (fun d => (enc d).tag) + ((1000*D)^4) (by positivity) (fun _ => Finset.mem_univ _) + (switchChoice_injective height hheight hstep D hD w hw lo hi hlo hlohi) + (fun d => (d.switchChoice_spec height hheight hstep D hD w hw lo hi hlo hlohi).2) () A + simpa only [MatchingFPRAS.PairEnergy.guideMass,π.total,mul_one] using h + have hd (d : Demand hbags hG) : + (f (d.outside ∪ d.paths.switched true)-f (d.outside ∪ d.paths.switched false))^2 ≤ + cost (enc d).first := by + have he := d.switchChoice_first height hheight hstep D hD w hw lo hi hlo hlohi + change _ ≤ cost _ + rw [he,← d.switchState_val true,← d.switchState_val false] + exact Finset.single_le_sum (fun (B : PM (BagEdge.Incident (bags := bags))) _ => + sq_nonneg (f (d.switchState true).val-f B.val)) (Finset.mem_filter.mpr + ⟨Finset.mem_univ _,d.switchState_safe height hheight hstep D hD w hw lo hi hlo⟩) + calc + _ ≤ ∑ d : Demand hbags hG, ρ d * cost (enc d).first := + Finset.sum_le_sum fun d _ => mul_le_mul_of_nonneg_left (hd d) + (mul_nonneg (π.nonneg _) (π.nonneg _)) + _ = ∑ A : PM BagEdge.Incident, + MatchingFPRAS.PairEnergy.contextMass ρ (fun _ => ()) (fun d => (enc d).first) () A * cost A := by + simpa using MatchingFPRAS.PairEnergy.sum_contextMass ρ (fun _ => ()) (fun d => (enc d).first) + (fun _ : Unit => Finset.univ) (fun _ => Finset.mem_univ _) (fun _ => cost) + _ ≤ ∑ A : PM BagEdge.Incident, C*π.weight A*cost A := + Finset.sum_le_sum fun A _ => mul_le_mul_of_nonneg_right (hload A) (hc A) + _ = _ := by simp only [C,cost,π,wt,Finset.mul_sum,mul_assoc] + +end Demand + +end + +variable {V L : Type*} [Fintype V] [DecidableEq V] [Fintype L] [DecidableEq L] + +variable {bags : V → Finset L} {G : SimpleGraph L} + +noncomputable local instance : Fintype (BagEdge bags) := Fintype.ofFinite _ + +variable {hbags : ∀ v, ∀ a ∈ bags v, ∀ b ∈ bags v, a = b ∨ G.Adj a b} + +variable {hG : G.IsAcyclic} + +namespace Demand + +noncomputable def cellError (d : Demand hbags hG) (f : Finset (BagEdge bags) → ℝ) (b : Bool) : ℝ := + d.paths.contextError d.outside f b (if b then 2 else 3) (if b then 0 else 1) + +noncomputable def cellSwitch (d : Demand hbags hG) (f : Finset (BagEdge bags) → ℝ) : ℝ := + f (d.outside ∪ d.paths.switched true)-f (d.outside ∪ d.paths.switched false) + +noncomputable def cellCost (d : Demand hbags hG) (f : Finset (BagEdge bags) → ℝ) : ℝ := + (d.cellSwitch f)^2+(d.cellError f true)^2+(d.cellError f false)^2 + +end Demand + +lemma sum_errorDemands (ρ : Demand hbags hG → ℝ) (f : Finset (BagEdge bags) → ℝ) : + (∑ e : ErrorDemand hbags hG, ρ e.demand * (e.demand.cellError f e.bit)^2) = + ∑ d : Demand hbags hG, ρ d * ((d.cellError f true)^2+(d.cellError f false)^2) := by + classical + let p := fun e : Bool × Demand hbags hG => + ∀ i : Fin 4, CellPaths.sideBit i = e.1 → (e.2.paths.side i).length ≠ 1 + let H := fun e : Bool × Demand hbags hG => ρ e.2 * (e.2.cellError f e.1)^2 + have hzero (e : Bool × Demand hbags hG) (he : ¬ p e) : H e = 0 := by + have h := e.2.short_error_zero f e.1 he + simp only [H,Demand.cellError,h,zero_pow (by decide : 2≠0),mul_zero] + calc + _ = ∑ e ∈ Finset.univ.filter p, H e := (Finset.sum_subtype (p := p) _ + (fun _ => by simp only [Finset.mem_filter,Finset.mem_univ,true_and]) H).symm + _ = ∑ e : Bool × Demand hbags hG, H e := + Finset.sum_subset (Finset.filter_subset _ _) (by + intro e _ he + exact hzero e (fun hp => he (Finset.mem_filter.mpr ⟨Finset.mem_univ _,hp⟩))) + _ = _ := by + rw [Fintype.sum_prod_type] + simp only [H,Fintype.sum_bool,← Finset.sum_add_distrib,mul_add] + +variable (height : L → ℝ) (hheight : ∀ l, 0 < height l) + +variable (hstep : ∀ a b, G.Adj a b → height a ≤ 2 * height b) + +variable (D : ℝ) (hD : 1 ≤ D) (w : BagEdge bags → ℝ) + +variable (hw : ∀ e, height e.color / D ≤ w e ∧ w e ≤ 3 * height e.color) + +variable (lo hi : ℝ) (hlo : 0 < lo) (hlohi : lo ≤ hi) + +include hheight hstep hD hw hlohi + +theorem total_cell_demand_load (M : PM (BagEdge.Incident (bags := bags))) + (f g : Finset (BagEdge bags) → ℝ) : + let wt := fun e => max lo (min hi (w e)) + let π := gibbsLaw wt (fun _ => lt_of_lt_of_le hlo (le_max_left _ _)) M + (∑ d : Demand hbags hG, π.weight d.1.1 * π.weight d.1.2 * d.cellCost f) ≤ + ((1000*D)^4 * Fintype.card (DemandTag (V := V) (E := BagEdge bags))) * + ((∑ A : PM BagEdge.Incident, π.weight A * + ∑ B ∈ safeDestinations wt (1000*D) A, (f A.val-f B.val)^2) + + 4 * ∑ A : PM BagEdge.Incident, ∑ B : PM BagEdge.Incident, π.weight A * π.weight B * + ∑ S ∈ components (inc := BagEdge.Incident) (A.val ∪ B.val), + ((f A.val+g B.val)-(f (exchange A.val B.val S)+g (exchange B.val A.val S)))^2) := by + classical + dsimp only + let wt := fun e => max lo (min hi (w e)) + let π := gibbsLaw wt (fun _ => lt_of_lt_of_le hlo (le_max_left _ _)) M + let C := (1000*D)^4 * Fintype.card (DemandTag (V := V) (E := BagEdge bags)) + have hC : 0 ≤ C := by positivity + have hs := Demand.switch_load_bound (hbags := hbags) (hG := hG) height hheight hstep D hD w hw lo hi hlo hlohi M f + have he := ErrorDemand.error_load_bound (hbags := hbags) (hG := hG) height hheight hstep D hD w hw lo hi hlo hlohi f g M + have hsw := PatternCode.weighted_swap_bound π f g + have herr := mul_le_mul_of_nonneg_left hsw (mul_nonneg (by norm_num : (0:ℝ)≤4) hC) + have hsum := sum_errorDemands (hbags := hbags) (hG := hG) + (fun d => π.weight d.1.1 * π.weight d.1.2) f + change (∑ e : ErrorDemand hbags hG, π.weight e.demand.1.1 * π.weight e.demand.1.2 * + (e.demand.cellError f e.bit)^2) ≤ _ at he + rw [hsum] at he + have hsplit : (∑ d : Demand hbags hG, π.weight d.1.1 * π.weight d.1.2 * d.cellCost f) = + (∑ d : Demand hbags hG, π.weight d.1.1 * π.weight d.1.2 * (d.cellSwitch f)^2) + + (∑ d : Demand hbags hG, π.weight d.1.1 * π.weight d.1.2 * + ((d.cellError f true)^2+(d.cellError f false)^2)) := by + simp only [Demand.cellCost,mul_add,Finset.sum_add_distrib] + ring + change (∑ d : Demand hbags hG, π.weight d.1.1 * π.weight d.1.2 * d.cellCost f) ≤ _ + rw [hsplit] + change (∑ d : Demand hbags hG, π.weight d.1.1 * π.weight d.1.2 * (d.cellSwitch f)^2) ≤ _ at hs + have h := add_le_add hs (he.trans herr) + calc + _ ≤ _ := h + _ = _ := by dsimp only [C,π,wt]; ring + +end MatchingFPRAS.Transport.CellDemands + +end OAI diff --git a/lean/OAI/Combinatorics/MatchingCount/Graphs/SafeTrace.lean b/lean/OAI/Combinatorics/MatchingCount/Graphs/SafeTrace.lean new file mode 100644 index 0000000000000000000000000000000000000000..bbf55dc744b0b867fb5f8e92b2c75049b31d242c --- /dev/null +++ b/lean/OAI/Combinatorics/MatchingCount/Graphs/SafeTrace.lean @@ -0,0 +1,95 @@ +import Mathlib +import OAI.Combinatorics.MatchingCount.Machines.CoinTM1 + +namespace OAI + +namespace MatchingFPRAS.SafeTrace +open Turing MachineCost PhysicalStream + +variable {Γ Λ σ : Type} [Inhabited Γ] + +inductive Path (M : Λ → TM1.Stmt Γ Λ σ) (safe : Λ → Prop) : + ℕ → TM1.Cfg Γ Λ σ → TM1.Cfg Γ Λ σ → Prop + | refl (c) : Path M safe 0 c c + | cons {n c d} (hc : ∀ l,c.l=some l→safe l) + (rest : Path M safe n (advance (TM1.step M) c) d) : Path M safe (n+1) c d + +namespace Path +variable {M : Λ → TM1.Stmt Γ Λ σ} {safe : Λ → Prop} +lemma single (c : TM1.Cfg Γ Λ σ) (hc : ∀ l,c.l=some l→safe l) : + Path M safe 1 c (advance (TM1.step M) c) := .cons hc (.refl _) +lemma trans {n m : ℕ} {a b c : TM1.Cfg Γ Λ σ} + (h : Path M safe n a b) (g : Path M safe m b c) : Path M safe (n+m) a c := by + induction h with + | refl a => simpa only [Nat.zero_add] using g + | @cons n a b ha hr ih => simpa only [Nat.succ_add] using Path.cons ha (ih g) +lemma run_eq {n : ℕ} {a b : TM1.Cfg Γ Λ σ} (h : Path M safe n a b) : + MachineCost.run (TM1.step M) n a=b := by + induction h with + | refl a => rfl + | cons ha hr ih => exact ih +lemma monotone {n : ℕ} {a b : TM1.Cfg Γ Λ σ} (h : Path M safe n a b) + {safe' : Λ → Prop} (hs : ∀ l,safe l→safe' l) : Path M safe' n a b := by + induction h with + | refl a => exact .refl _ + | cons ha hr ih => exact .cons (fun l hl=>hs l (ha l hl)) ih +lemma of_run (n : ℕ) (c : TM1.Cfg Γ Λ σ) + (h : ∀ i,i exact .refl _ + | succ n ih => + refine .cons (h 0 (by omega)) (ih _ ?_) + intro i hi l hl + exact h (i+1) (by omega) l hl + +theorem physical {n : ℕ} {a b : TM1.Cfg Γ Λ σ} (h : Path M safe n a b) + (coin : CoinTM1.Coins Λ) (hcoin : ∀ l,safe l→coin l=none) + (C : ℕ) (hC : ∀ l,safe l→statementCost (M l)≤C) : + ∃ k,k≤n*C ∧ ∀ bits : Stream, + PhysicalPost.execute (CoinTM1.table M coin) k (CoinTM1.trCfg a) bits=CoinTM1.trCfg b := by + induction h with + | refl a => exact ⟨0,by simp,fun _=>rfl⟩ + | @cons n c d hc hr ih => + obtain ⟨k,hk,he⟩:=ih + rcases c with ⟨l,v,T⟩ + cases l with + | none => + refine ⟨k,le_trans hk ?_,he⟩ + exact Nat.mul_le_mul_right C (by omega) + | some l => + have hs:=hc l rfl + obtain ⟨j,hj,hjc,hje⟩:=CoinTM1.entry_ticks M coin l v T (hcoin l hs) + refine ⟨j+k,?_,fun bits=>?_⟩ + · have hb:=hC l hs + calc j+k≤C+n*C := Nat.add_le_add (hjc.trans hb) hk + _=(n+1)*C := by ring + · rw [PhysicalPost.execute_add,hje] + exact he (shift j bits) +end Path +end MatchingFPRAS.SafeTrace + +namespace MatchingFPRAS.SafeTrace.Path +open Turing MachineCost + +variable {Γ Λ σ : Type} [Inhabited Γ] [Inhabited Λ] +lemma with_support {M : Λ → TM1.Stmt Γ Λ σ} {safe : Λ → Prop} {S : Finset Λ} + (hS : TM1.Supports M S) {n : ℕ} {a b : TM1.Cfg Γ Λ σ} + (h : Path M safe n a b) (ha : ∀ l,a.l=some l→l∈S) : + Path M (fun l=>safe l ∧ l∈S) n a b := by + induction h with + | refl c => exact .refl _ + | @cons n c d hc hr ih => + refine .cons (fun l hl=>⟨hc l hl,ha l hl⟩) (ih ?_) + intro l hl + rcases c with ⟨lc,v,T⟩ + cases lc with + | none => simp [advance,TM1.step] at hl + | some lc => + have hs:=TM1.step_supports M hS (c:=⟨some lc,v,T⟩) (c':=TM1.stepAux (M lc) v T) rfl (by + simp only [Finset.some_mem_insertNone]; exact ha lc rfl) + simp only [advance,TM1.step,Option.getD_some] at hl + exact Finset.some_mem_insertNone.mp (hl ▸ hs) +end MatchingFPRAS.SafeTrace.Path + +end OAI diff --git a/lean/OAI/Combinatorics/MatchingCount/Graphs/Sets.lean b/lean/OAI/Combinatorics/MatchingCount/Graphs/Sets.lean new file mode 100644 index 0000000000000000000000000000000000000000..95be5240e50621f92de24286949c0ad181c59879 --- /dev/null +++ b/lean/OAI/Combinatorics/MatchingCount/Graphs/Sets.lean @@ -0,0 +1,338 @@ +import Mathlib +import OAI.Combinatorics.MatchingCount.Graphs.IndexedCycle +import OAI.Combinatorics.MatchingCount.Graphs.ArcData + +namespace OAI + +namespace MatchingFPRAS.Cells +open SimpleGraph + +variable {L : Type*} {G : SimpleGraph L} +namespace CycleData + +variable [DecidableEq L] {m : ℕ} (C : CycleData G m) + +def sets (i : ℤ) : Finset L := {C.labels (i - 1), C.labels i} + +def Admissible (x y : ℕ) : Prop := ∃ l, l ∈ C.sets x ∧ l ∈ C.sets y + +def Good (x y : ℕ) : Prop := y = x + 1 ∨ C.Admissible (x + 1) (y - 1) + +def ExteriorGood (x y : ℕ) : Prop := + y + 1 = x + m ∨ ∃ l, l ∈ C.sets ((y : ℤ) + 1) ∧ l ∈ C.sets ((x : ℤ) - 1) + +lemma sets_clique (i : ℤ) : ∀ u ∈ C.sets i, ∀ v ∈ C.sets i, u = v ∨ G.Adj u v := by + intro u hu v hv + simp only [sets, Finset.mem_insert, Finset.mem_singleton] at hu hv + rcases hu with rfl | rfl <;> rcases hv with rfl | rfl + · exact Or.inl rfl + · exact C.adjacent i + · exact (C.adjacent i).imp Eq.symm (fun h => h.symm) + · exact Or.inl rfl + +def arc (x s : ℕ) : ArcData G s where + labels i := C.labels ((x : ℤ) + i) + sets i := C.sets ((x : ℤ) + i) + left_mem i _ := by simp [sets] + right_mem i _ := by + simp only [sets, Finset.mem_insert, Finset.mem_singleton] + left + congr 1 + push_cast + omega + clique i _ := C.sets_clique ((x : ℤ) + i) + +lemma arc_admissible (x s u v : ℕ) : + (C.arc x s).Admissible u v ↔ C.Admissible (x + u) (x + v) := by + simp only [ArcData.Admissible, Admissible, arc, Nat.cast_add] + +lemma arc_good (x s u v : ℕ) (huv : u < v) : + (C.arc x s).Good u v ↔ C.Good (x + u) (x + v) := by + have hv : 1 ≤ v := by omega + have h₁ : x + u + 1 = x + (u + 1) := by omega + have h₂ : x + v - 1 = x + (v - 1) := by omega + simp only [ArcData.Good, Good, h₁, h₂, ← C.arc_admissible x s] + constructor + · rintro (h | h) + · exact Or.inl (by omega) + · exact Or.inr h + · rintro (h | h) + · exact Or.inl (by omega) + · exact Or.inr h + +lemma bad_exterior_boundary (x s : ℕ) (hs : 0 < s) (P : L) + (hP₀ : P ∈ (C.arc x s).sets 0) (hPₛ : P ∈ (C.arc x s).sets s) + (hbad : ¬ C.ExteriorGood x (x + s)) : + (C.arc x s).labels 0 = P ∨ (C.arc x s).labels (s - 1) = P := by + by_contra h + push Not at h + rcases h with ⟨hleft, hright⟩ + have hcast : (↑(s - 1) : ℤ) = (s : ℤ) - 1 := by omega + simp only [arc, Nat.cast_zero, add_zero] at hleft hP₀ + simp only [arc, hcast] at hright + have h₀ : P = C.labels ((x : ℤ) - 1) := by + simpa only [sets, Finset.mem_insert, Finset.mem_singleton, or_iff_left hleft.symm] using hP₀ + have hₛ : P = C.labels ((x : ℤ) + s) := by + have hne : P ≠ C.labels ((x : ℤ) + s - 1) := by + intro hh + apply hright + convert hh.symm using 1 + congr 1 + omega + simpa only [arc, sets, Finset.mem_insert, Finset.mem_singleton, or_iff_right hne] using hPₛ + apply hbad + right + refine ⟨P, ?_, ?_⟩ + · simp only [sets, Finset.mem_insert, Finset.mem_singleton] + left + convert hₛ using 1 + congr 1 + push_cast + omega + · simp only [sets, Finset.mem_insert, Finset.mem_singleton] + exact Or.inr h₀ + +structure Cell (x p q y : ℕ) : Prop where + first_pos : x < p + middle_pos : p < q + third_pos : q < y + odd_first : (p - x) % 2 = 1 + odd_middle : (q - p) % 2 = 1 + odd_third : (y - q) % 2 = 1 + odd_exterior : (m - (y - x)) % 2 = 1 + first : C.Admissible x p + middle : C.Admissible p q + third : C.Admissible q y + exterior : C.Admissible y x + some_good : (C.Good x p ∧ C.Good q y) ∨ (C.Good p q ∧ C.ExteriorGood x y) + outer_long : 1 < p - x → 1 < y - q → C.Good p q ∧ C.ExteriorGood x y + middle_exterior_long : 1 < q - p → 1 < m - (y - x) → C.Good x p ∧ C.Good q y + +inductive Subdivision (C : CycleData G m) : ℕ → ℕ → Type _ where + | edge {x y} (short : y = x + 1) : Subdivision C x y + | node {x p q y} (cell : C.Cell x p q y) + (first : Subdivision C x p) (middle : Subdivision C p q) + (third : Subdivision C q y) : Subdivision C x y + +lemma cell_of_split (x s : ℕ) (hm : m % 2 = 0) (hs : s % 2 = 1) + (hbound : x + s < m) (hadm : C.Admissible x (x + s)) + (T : (C.arc x s).Split (C.ExteriorGood x (x + s))) : + C.Cell x (x + T.p₁) (x + T.p₂) (x + s) := by + have h₁ := T.positive + have h₂ := T.ordered + have h₃ := T.inside + have ho := T.odd₁ + have he := T.even₂ + have ha₁ : C.Admissible x (x + T.p₁) := by + simpa only [Nat.add_zero] using (C.arc_admissible x s 0 T.p₁).mp T.first + have ha₂ := (C.arc_admissible x s T.p₁ T.p₂).mp T.middle + have ha₃ := (C.arc_admissible x s T.p₂ s).mp T.third + have hae : C.Admissible (x + s) x := by + obtain ⟨l, hl₁, hl₂⟩ := hadm + exact ⟨l, hl₂, hl₁⟩ + have g₁ : (C.arc x s).Good 0 T.p₁ → C.Good x (x + T.p₁) := by + intro h + simpa only [Nat.add_zero] using (C.arc_good x s 0 T.p₁ h₁).mp h + have g₂ := (C.arc_good x s T.p₁ T.p₂ h₂).mp + have g₃ := (C.arc_good x s T.p₂ s h₃).mp + refine ⟨by omega, by omega, by omega, by omega, by omega, by omega, by omega, + ha₁, ha₂, ha₃, hae, ?_, ?_, ?_⟩ + · rcases T.some_good with ⟨hf, ht⟩ | ⟨hm, hg⟩ + · exact Or.inl ⟨g₁ hf, g₃ ht⟩ + · exact Or.inr ⟨g₂ hm, hg⟩ + · intro hf ht + obtain ⟨hm, hg⟩ := T.outer_long (by omega) (by omega) + exact ⟨g₂ hm, hg⟩ + · intro hmiddle _ + obtain ⟨hf, ht⟩ := T.middle_long (by omega) + exact ⟨g₁ hf, g₃ ht⟩ + +theorem quadrangulate_arc (hG : G.IsAcyclic) (heven : m % 2 = 0) + (s : ℕ) : ∀ x, 0 < s → s % 2 = 1 → x + s < m → + C.Admissible x (x + s) → Nonempty (Subdivision C x (x + s)) := by + induction s using Nat.strong_induction_on with + | h s ih => + intro x hs hsodd hbound hadm + by_cases hshort : s = 1 + · exact ⟨.edge (by omega)⟩ + have hslarge : 3 ≤ s := by omega + obtain ⟨P, hP₀, hPₛ⟩ := hadm + have hP₀' : P ∈ (C.arc x s).sets 0 := by simpa only [arc, Nat.cast_zero, add_zero] using hP₀ + have hPₛ' : P ∈ (C.arc x s).sets s := by simpa only [arc, Nat.cast_add] using hPₛ + obtain ⟨T⟩ := (C.arc x s).split hG (C.ExteriorGood x (x + s)) hslarge hsodd P + hP₀' hPₛ' (C.bad_exterior_boundary x s hs P hP₀' hPₛ') + have h₁ := T.positive + have h₂ := T.ordered + have h₃ := T.inside + have ho := T.odd₁ + have he := T.even₂ + have cell := C.cell_of_split x s heven hsodd hbound ⟨P, hP₀, hPₛ⟩ T + obtain ⟨Q₁⟩ := ih T.p₁ (by omega) x h₁ ho (by omega) cell.first + have eq₂ : x + T.p₁ + (T.p₂ - T.p₁) = x + T.p₂ := by omega + have eq₃ : x + T.p₂ + (s - T.p₂) = x + s := by omega + obtain ⟨Q₂⟩ := ih (T.p₂ - T.p₁) (by omega) (x + T.p₁) (by omega) (by omega) + (by omega) (by simpa only [eq₂] using cell.middle) + obtain ⟨Q₃⟩ := ih (s - T.p₂) (by omega) (x + T.p₂) (by omega) (by omega) + (by omega) (by simpa only [eq₃] using cell.third) + rw [eq₂] at Q₂ + rw [eq₃] at Q₃ + exact ⟨.node cell Q₁ Q₂ Q₃⟩ + +theorem quadrangulate (hG : G.IsAcyclic) (hm : 4 ≤ m) (heven : m % 2 = 0) : + Nonempty (Subdivision C 0 (m - 1)) := by + have hclose : C.labels ((m : ℤ) - 1) = C.labels (-1) := by + calc + C.labels ((m : ℤ) - 1) = C.labels (-1 + (m : ℤ)) := congrArg C.labels (by omega) + _ = C.labels (-1) := C.periodic (-1) + have hadm : C.Admissible 0 (0 + (m - 1)) := by + refine ⟨C.labels (-1), ?_, ?_⟩ + · simp [sets] + · simp only [Nat.zero_add, sets, Finset.mem_insert, Finset.mem_singleton] + right + rw [← hclose] + congr 1 + omega + simpa only [Nat.zero_add] using + C.quadrangulate_arc hG heven (m - 1) 0 (by omega) (by omega) (by omega) hadm + +namespace Subdivision + +variable {C} {x y : ℕ} + +def cells : {x y : ℕ} → Subdivision C x y → ℕ + | _, _, .edge _ => 0 + | _, _, .node _ Q₁ Q₂ Q₃ => 1 + Q₁.cells + Q₂.cells + Q₃.cells + +def leaves : {x y : ℕ} → Subdivision C x y → ℕ + | _, _, .edge _ => 1 + | _, _, .node _ Q₁ Q₂ Q₃ => Q₁.leaves + Q₂.leaves + Q₃.leaves + +lemma cells_length (Q : Subdivision C x y) : 2 * Q.cells + 1 + x = y := by + induction Q with + | edge h => simp only [cells]; omega + | node cell Q₁ Q₂ Q₃ h₁ h₂ h₃ => simp only [cells]; omega + +lemma leaves_length (Q : Subdivision C x y) : Q.leaves + x = y := by + induction Q with + | edge h => simp only [leaves]; omega + | node cell Q₁ Q₂ Q₃ h₁ h₂ h₃ => simp only [leaves]; omega + +def interiorDiagonals (Q : Subdivision C x y) : ℕ := Q.cells - 1 + +lemma counts (hm : 4 ≤ m) (Q : Subdivision C 0 (m - 1)) : + Q.cells = (m - 2) / 2 ∧ Q.interiorDiagonals = (m - 4) / 2 ∧ + Q.leaves = m - 1 := by + have hc := Q.cells_length + have hl := Q.leaves_length + simp only [interiorDiagonals] + omega + +def sumCells : {x y : ℕ} → Subdivision C x y → (ℕ → ℕ → ℕ → ℕ → ℝ) → ℝ + | _, _, .edge _, _ => 0 + | x, y, .node (p := p) (q := q) _ Q₁ Q₂ Q₃, localTerm => + localTerm x p q y + Q₁.sumCells localTerm + Q₂.sumCells localTerm + Q₃.sumCells localTerm + +lemma signed_cancellation (Q : Subdivision C x y) + (gain : ℕ → ℕ → ℝ) (localTerm : ℕ → ℕ → ℕ → ℕ → ℝ) + (hshort : ∀ x, gain x (x + 1) = 0) + (hcell : ∀ x p q y, C.Cell x p q y → + gain x y = localTerm x p q y + gain x p + gain p q + gain q y) : + gain x y = Q.sumCells localTerm := by + induction Q with + | edge h => simpa only [h, sumCells] using hshort _ + | node cell Q₁ Q₂ Q₃ h₁ h₂ h₃ => + simpa only [sumCells, h₁, h₂, h₃] using hcell _ _ _ _ cell + +end Subdivision + +end CycleData + +end MatchingFPRAS.Cells + +namespace MatchingFPRAS.Transport + +variable {V E L : Type*} + +namespace IndexedCycle + +variable {inc : E → V → Prop} (c : IndexedCycle inc) + +def zindex (i : ℤ) : Fin c.size := + ⟨(i % (c.size : ℤ)).toNat, (Int.toNat_lt (Int.emod_nonneg _ (by + have := c.four_le; omega))).mpr (Int.emod_lt_of_pos _ (by have := c.four_le; omega))⟩ + +def vertexAtZ (i : ℤ) : V := c.vertex (c.zindex i) + +def edgeAtZ (i : ℤ) : E := c.edge (c.zindex i) + +lemma zindex_nat (i : ℕ) : c.zindex i = c.index i := by + apply Fin.ext + change ((i : ℤ) % (c.size : ℤ)).toNat = i % c.size + rw [← Int.natCast_emod, Int.toNat_natCast] + +lemma zindex_periodic (i : ℤ) : c.zindex (i + c.size) = c.zindex i := by + apply Fin.ext + simp [zindex] + +lemma vertexAtZ_nat (i : ℕ) : c.vertexAtZ i = c.vertexAt i := by + simp [vertexAtZ, vertexAt, c.zindex_nat] + +lemma edgeAtZ_nat (i : ℕ) : c.edgeAtZ i = c.edgeAt i := by + simp [edgeAtZ, edgeAt, c.zindex_nat] + +lemma vertexAtZ_periodic (i : ℤ) : c.vertexAtZ (i + c.size) = c.vertexAtZ i := by + simp [vertexAtZ, c.zindex_periodic] + +lemma edgeAtZ_periodic (i : ℤ) : c.edgeAtZ (i + c.size) = c.edgeAtZ i := by + simp [edgeAtZ, c.zindex_periodic] + +lemma zindex_succ (i : ℤ) : c.zindex (i + 1) = + ⟨((c.zindex i).val + 1) % c.size, Nat.mod_lt _ (by have := c.four_le; omega)⟩ := by + have hsz : (c.size : ℤ) ≠ 0 := by have := c.four_le; omega + apply Fin.ext + apply Int.natCast_inj.mp + change (((i + 1) % (c.size : ℤ)).toNat : ℤ) = + (((((i % (c.size : ℤ)).toNat + 1) % c.size) : ℕ) : ℤ) + rw [Int.toNat_of_nonneg (Int.emod_nonneg _ hsz), Int.natCast_emod, + Nat.cast_add, Nat.cast_one, Int.toNat_of_nonneg (Int.emod_nonneg _ hsz)] + simp only [Int.add_emod, Int.emod_emod] + +lemma edgeAtZ_incidence (i : ℤ) (v : V) : + inc (c.edgeAtZ i) v ↔ v = c.vertexAtZ i ∨ v = c.vertexAtZ (i+1) := by + simpa [edgeAtZ, vertexAtZ, c.zindex_succ] using c.incidence (c.zindex i) v + +end IndexedCycle + +namespace BagEdge + +variable {bags : V → Finset L} + +def color (e : BagEdge bags) : L := e.val.color + +lemma color_mem (e : BagEdge bags) {v : V} (hv : e.Incident v) : e.color ∈ bags v := + e.property v hv + +def ofEndpoints (v w : V) (hvw : v ≠ w) (l : L) + (hlv : l ∈ bags v) (hlw : l ∈ bags w) : BagEdge bags := + ⟨⟨(s(v,w),l), by simpa using hvw⟩, by + intro u hu + change u ∈ s(v,w) at hu + change l ∈ bags u + rcases Sym2.mem_iff.mp hu with rfl | rfl + · exact hlv + · exact hlw⟩ + +lemma ofEndpoints_incidence (v w : V) (hvw : v ≠ w) (l : L) + (hlv : l ∈ bags v) (hlw : l ∈ bags w) (u : V) : + (ofEndpoints v w hvw l hlv hlw).Incident u ↔ u = v ∨ u = w := + Sym2.mem_iff + +lemma ofEndpoints_color (v w : V) (hvw : v ≠ w) (l : L) + (hlv : l ∈ bags v) (hlw : l ∈ bags w) : + (ofEndpoints v w hvw l hlv hlw).color = l := rfl + +end BagEdge + +end MatchingFPRAS.Transport + +end OAI diff --git a/lean/OAI/Combinatorics/MatchingCount/Graphs/SumLiftMate.lean b/lean/OAI/Combinatorics/MatchingCount/Graphs/SumLiftMate.lean new file mode 100644 index 0000000000000000000000000000000000000000..f2e9754ac6e1c0ec5a754613a9cf2188bdee6db9 --- /dev/null +++ b/lean/OAI/Combinatorics/MatchingCount/Graphs/SumLiftMate.lean @@ -0,0 +1,352 @@ +import Mathlib +import OAI.Combinatorics.MatchingCount.Graphs.ThresholdGraph + +namespace OAI + +namespace MatchingFPRAS.Switching + +section + +open Finset + +variable {V W : Type*} + +def sumLiftMate (m : Mate V) : Mate (V ⊕ W) := + ⟨Sum.map m.val id,by intro x; cases x <;> simp⟩ + +@[simp] lemma sumLiftMate_inl (m : Mate V) (a : V) : + (sumLiftMate (W := W) m).val (Sum.inl a)=Sum.inl (m.val a) := rfl + +@[simp] lemma sumLiftMate_inr (m : Mate V) (a : W) : + (sumLiftMate m).val (Sum.inr a)=(Sum.inr a : V ⊕ W) := rfl + +def sumRetractMate (q : Mate (V ⊕ W)) (hfix : ∀ w, q.val (Sum.inr w)=Sum.inr w) : Mate V := by + let f : V → V := fun a => Sum.elim id (fun _ => a) (q.val (Sum.inl a)) + have hf : ∀ a, Sum.inl (f a)=q.val (Sum.inl a) := by + intro a + cases he : q.val (Sum.inl a) with + | inl b => simp [f,he] + | inr w => + have hh := q.property (Sum.inl a) + rw [he,hfix] at hh + contradiction + refine ⟨f,?_⟩ + intro a + apply Sum.inl_injective (β := W) + rw [hf,hf,q.property] + +lemma sumRetractMate_inl (q : Mate (V ⊕ W)) (hfix : ∀ w, q.val (Sum.inr w)=Sum.inr w) (a : V) : + Sum.inl ((sumRetractMate q hfix).val a)=q.val (Sum.inl a) := by + cases he : q.val (Sum.inl a) with + | inl b => simp [sumRetractMate,he] + | inr w => + have hh := q.property (Sum.inl a) + rw [he,hfix] at hh + contradiction + +lemma sumLift_retract (q : Mate (V ⊕ W)) (hfix : ∀ w, q.val (Sum.inr w)=Sum.inr w) : + sumLiftMate (sumRetractMate q hfix)=q := by + apply Subtype.ext; funext a + cases a with + | inl a => exact sumRetractMate_inl q hfix a + | inr w => exact (hfix w).symm + +lemma sumLift_holes [Fintype V] [Fintype W] [DecidableEq V] [DecidableEq (V ⊕ W)] + (m : Mate V) (R : Finset V) : + HasHoles (sumLiftMate (W := W) m) (R.map ⟨Sum.inl,Sum.inl_injective⟩)ᶜ ↔ HasHoles m Rᶜ := by + constructor + · intro h a + simpa using h (Sum.inl a) + · intro h a + cases a with + | inl a => simpa using h a + | inr w => simp + +lemma internal_fixed_of_terminal_holes [Fintype V] [Fintype W] [DecidableEq V] [DecidableEq (V ⊕ W)] + (q : Mate (V ⊕ W)) (R : Finset V) + (hq : HasHoles q (R.map ⟨Sum.inl,Sum.inl_injective⟩)ᶜ) (w : W) : + q.val (Sum.inr w)=Sum.inr w := (hq (Sum.inr w)).mpr (by simp) + +lemma sumLift_weight [Fintype V] [Fintype W] [LinearOrder V] [LinearOrder (V ⊕ W)] + (hord : ∀ a b : V, ((Sum.inl a : V ⊕ W) < Sum.inl b) ↔ a < b) + (B : V → V → ℝ) (B' : (V ⊕ W) → (V ⊕ W) → ℝ) + (hB : ∀ a b, B' (Sum.inl a) (Sum.inl b)=B a b) (m : Mate V) : + weight B' (sumLiftMate m)=weight B m := by + simp [weight,Fintype.prod_sum_type,hord,hB] + +theorem pairingCapacity_sum_inl [Fintype V] [Fintype W] [LinearOrder V] [LinearOrder (V ⊕ W)] + (hord : ∀ a b : V, ((Sum.inl a : V ⊕ W) < Sum.inl b) ↔ a < b) + (B : V → V → ℝ) (B' : (V ⊕ W) → (V ⊕ W) → ℝ) + (hB : ∀ a b, B' (Sum.inl a) (Sum.inl b)=B a b) + (R : Finset V) (hR : Even R.card) + (hR' : Even (R.map ⟨Sum.inl,Sum.inl_injective (β := W)⟩).card) : + pairingCapacity B' (R.map ⟨Sum.inl,Sum.inl_injective⟩) hR'=pairingCapacity B R hR := by + classical + apply le_antisymm + · apply Finset.sup'_le + intro q hq + have hholes := (mem_matchings q _).mp hq + have hfix : ∀ w, q.val (Sum.inr w)=Sum.inr w := by + intro w + exact (hholes (Sum.inr w)).mpr (by simp) + let m := sumRetractMate q hfix + have hqm : sumLiftMate m=q := sumLift_retract q hfix + have hm : HasHoles m Rᶜ := by + intro a + have hh := hholes (Sum.inl a) + rw [← hqm] at hh + simpa using hh + rw [← hqm,sumLift_weight hord B B' hB] + exact weight_le_pairingCapacity B R hR m hm + · apply Finset.sup'_le + intro m hm + have hholes := (mem_matchings m _).mp hm + rw [← sumLift_weight hord B B' hB] + apply weight_le_pairingCapacity B' _ hR' (sumLiftMate m) + intro a + cases a with + | inl a => simpa using hholes a + | inr a => simp + +theorem ChargeTrace.capacity_bound_decidable [Fintype V] [LinearOrder V] + (dec : DecidableEq V) {B : V → V → ℝ} + (hB : ∀ a b, B a b = B b a) (hB0 : ∀ a b, 0 ≤ B a b) + (htri : ∀ a b c, a ≠ b → a ≠ c → b ≠ c → min (B a c) (B c b) ≤ B a b) + {U W : Finset V} {F : ℝ} (h : @ChargeTrace V dec B U W F) (hU : Even U.card) : + ∃ hW : Even W.card, pairingCapacity B U hU * F ≤ pairingCapacity B W hW := by + have he : dec = (inferInstance : LinearOrder V).toDecidableEq := Subsingleton.elim _ _ + subst dec + exact h.capacity_bound hB hB0 htri hU + +end + +variable {V : Type*} + +lemma ChargeTrace.factor_nonneg [DecidableEq V] {B : V → V → ℝ} + {U W : Finset V} {F : ℝ} (h : ChargeTrace B U W F) : 0 ≤ F := by + cases h with + | done => norm_num + | remove _ _ _ _ _ _ _ _ _ _ _ _ _ hf hF => exact mul_nonneg hf hF + | replace _ _ _ _ _ _ _ _ _ _ hf hF => exact mul_nonneg hf hF + +end MatchingFPRAS.Switching + +namespace MatchingFPRAS.Subdivision + +open Finset + +abbrev Selection (m : ℕ) := Fin (m+1) → Bool + +def Valid {m : ℕ} (holes : Finset (Fin m)) (b : Selection m) : Prop := + ∀ i : Fin m, if i ∈ holes then b i.castSucc = false ∧ b i.succ = false + else b i.castSucc ≠ b i.succ + +def alternating (a : Bool) (i : ℕ) : Bool := if i % 2 = 0 then a else !a + +@[simp] theorem alternating_zero (a : Bool) : alternating a 0 = a := by + simp [alternating] + +@[simp] theorem alternating_succ (a : Bool) (i : ℕ) : + alternating a (i+1) = !(alternating a i) := by + by_cases h : i % 2 = 0 + · have hs : (i+1)%2 = 1 := by omega + simp [alternating,h,hs] + · have hs : i%2=1 := by omega + have ht : (i+1)%2=0 := by omega + simp [alternating,hs,ht] + +@[simp] theorem alternating_add_two (a : Bool) (i : ℕ) : + alternating a (i+2) = alternating a i := by + rw [show i+2=(i+1)+1 by omega, alternating_succ, alternating_succ] + simp + +lemma bool_ne_iff_eq_not (a b : Bool) : a ≠ b ↔ b = !a := by + cases a <;> cases b <;> simp + +theorem intact_iff {m : ℕ} (b : Selection m) : + Valid ∅ b ↔ ∀ i : Fin (m+1), b i = alternating (b 0) i.val := by + constructor + · intro h i + have hstep (j : Fin m) : b j.succ = !(b j.castSucc) := by + apply (bool_ne_iff_eq_not _ _).mp + simpa [Valid] using h j + have aux (k : ℕ) (hk : k < m+1) : b ⟨k,hk⟩ = alternating (b 0) k := by + induction k with + | zero => simp + | succ k ih => + rw [alternating_succ] + have hk' : k < m := by omega + have he := hstep ⟨k,hk'⟩ + simpa only [Fin.succ_mk, Fin.castSucc_mk, ih (by omega)] using he + exact aux i.val i.isLt + · intro h i + simp only [Finset.notMem_empty, ↓reduceIte] + rw [h i.castSucc, h i.succ] + simp only [Fin.val_castSucc, Fin.val_succ, alternating_succ] + cases alternating (b 0) i.val <;> decide + +theorem intact_terminals {m : ℕ} (hm : Even m) (b : Selection m) + (h : Valid ∅ b) : b (Fin.last m) = b 0 := by + rw [(intact_iff b).mp h] + simp [alternating, Nat.even_iff.mp hm] + +theorem alternating_valid (m : ℕ) (a : Bool) : + Valid ∅ (fun i : Fin (m+1) => alternating a i.val) := by + apply (intact_iff _).mpr + intro i + simp + +@[simp] theorem alternating_not (a : Bool) (i : ℕ) : + alternating (!a) i = !(alternating a i) := by + unfold alternating + split_ifs <;> simp + +def wordWeight (a : Bool) : List ℝ → ℝ + | [] => 1 + | x::xs => (if a then x else 1) * wordWeight (!a) xs + +@[simp] theorem wordWeight_nil (a : Bool) : wordWeight a [] = 1 := rfl + +@[simp] theorem wordWeight_pair (a : Bool) (x : ℝ) (xs : List ℝ) : + wordWeight a (x::x::xs) = x * wordWeight a xs := by + cases a <;> simp [wordWeight] + +def duplicate (xs : List ℝ) : List ℝ := xs.flatMap (fun x => [x,x]) + +@[simp] theorem duplicate_nil : duplicate [] = [] := rfl + +@[simp] theorem duplicate_cons (x : ℝ) (xs : List ℝ) : + duplicate (x::xs) = x::x::duplicate xs := by simp [duplicate] + +@[simp] theorem duplicate_length (xs : List ℝ) : + (duplicate xs).length = 2*xs.length := by + induction xs with + | nil => simp + | cons x xs ih => simp [ih]; omega + + theorem paired_prefix_weight (a : Bool) (xs ys : List ℝ) : + wordWeight a (duplicate xs ++ ys) = xs.prod * wordWeight a ys := by + induction xs with + | nil => simp + | cons x xs ih => simp [ih, mul_assoc] + +theorem profile_weight (a : Bool) (left right : List ℝ) (lam : ℝ) : + wordWeight a (duplicate left ++ [lam] ++ duplicate right) = + left.prod * right.prod * (if a then lam else 1) := by + rw [List.append_assoc, paired_prefix_weight] + simp only [List.singleton_append, wordWeight] + have h := paired_prefix_weight (!a) right [] + simp only [List.append_nil, wordWeight_nil, mul_one] at h + rw [h] + ring + +theorem wordWeight_ofFn (n : ℕ) (w : Fin n → ℝ) (a : Bool) : + wordWeight a (List.ofFn w) = ∏ i, (if alternating a i.val then w i else 1) := by + induction n generalizing a with + | zero => simp [List.ofFn_zero] + | succ n ih => + rw [List.ofFn_succ, Fin.prod_univ_succ] + simp only [wordWeight, Fin.val_zero, alternating_zero] + rw [ih] + congr 1 + apply Finset.prod_congr rfl + intro i _ + simp + +noncomputable def selectedWeight {m : ℕ} (w : Fin (m+1) → ℝ) (b : Selection m) : ℝ := + ∏ i, if b i then w i else 1 + + theorem intact_weight {m : ℕ} (w : Fin (m+1) → ℝ) (b : Selection m) + (h : Valid ∅ b) : selectedWeight w b = wordWeight (b 0) (List.ofFn w) := by + rw [wordWeight_ofFn] + unfold selectedWeight + apply Finset.prod_congr rfl + intro i _ + rw [(intact_iff b).mp h] + +variable {V E : Type*} [Fintype V] [Fintype E] + +def LogicalPerfect (u v : E → V) (s : E → Bool) : Prop := + ∀ x, ∃! e, s e = true ∧ (u e = x ∨ v e = x) + +def FamilyPerfect (u v : E → V) (m : ℕ) (b : E → Selection m) : Prop := + (∀ e, Valid ∅ (b e)) ∧ + ∀ x, ∃! e, (b e 0 = true ∧ u e = x) ∨ + (b e (Fin.last m) = true ∧ v e = x) + +omit [Fintype V] [Fintype E] in + theorem family_iff [Fintype V] [Fintype E] + {u v : E → V} {m : ℕ} (hm : Even m) (b : E → Selection m) : + FamilyPerfect u v m b ↔ + (∀ e, Valid ∅ (b e)) ∧ LogicalPerfect u v (fun e => b e 0) := by + unfold FamilyPerfect LogicalPerfect + constructor + · rintro ⟨hp,ht⟩ + refine ⟨hp,?_⟩ + have he (e) := intact_terminals hm (b e) (hp e) + simpa only [he, ← and_or_left] using ht + · rintro ⟨hp,ht⟩ + refine ⟨hp,?_⟩ + have he (e) := intact_terminals hm (b e) (hp e) + simpa only [he, ← and_or_left] using ht + +def familyEquiv (u v : E → V) (m : ℕ) (hm : Even m) : + {b : E → Selection m // FamilyPerfect u v m b} ≃ + {s : E → Bool // LogicalPerfect u v s} where + toFun b := ⟨fun e => b.val e 0, ((family_iff hm b.val).mp b.property).2⟩ + invFun s := ⟨fun e i => alternating (s.val e) i.val, + (family_iff hm _).mpr ⟨fun e => alternating_valid m (s.val e), by + simpa only [Fin.val_zero, alternating_zero] using s.property⟩⟩ + left_inv b := by + apply Subtype.ext + funext e i + exact ((intact_iff (b.val e)).mp (b.property.1 e) i).symm + right_inv s := by + apply Subtype.ext + funext e + simp + +noncomputable def logicalPartition (u v : E → V) (lam : E → ℝ) : ℝ := by + classical + letI := Fintype.ofFinite {s : E → Bool // LogicalPerfect u v s} + exact ∑ s : {s : E → Bool // LogicalPerfect u v s}, + ∏ e, if s.val e then lam e else 1 + +noncomputable def realPartition (u v : E → V) (m : ℕ) + (w : E → Fin (m+1) → ℝ) : ℝ := by + classical + letI := Fintype.ofFinite {b : E → Selection m // FamilyPerfect u v m b} + exact ∑ b : {b : E → Selection m // FamilyPerfect u v m b}, + ∏ e, selectedWeight (w e) (b.val e) + +omit [Fintype V] [Fintype E] in +theorem family_weight [Fintype V] [Fintype E] (u v : E → V) (m : ℕ) (_hm : Even m) + (w : E → Fin (m+1) → ℝ) (left right : E → List ℝ) (lam : E → ℝ) + (hw : ∀ e, List.ofFn (w e) = duplicate (left e) ++ [lam e] ++ duplicate (right e)) + (b : E → Selection m) (hb : FamilyPerfect u v m b) : + (∏ e, selectedWeight (w e) (b e)) = + (∏ e, (left e).prod * (right e).prod) * + ∏ e, if b e 0 then lam e else 1 := by + classical + rw [← Finset.prod_mul_distrib] + apply Finset.prod_congr rfl + intro e _ + rw [intact_weight _ _ (hb.1 e), hw e, profile_weight] + +theorem real_partition_identity (u v : E → V) (m : ℕ) (hm : Even m) + (w : E → Fin (m+1) → ℝ) (left right : E → List ℝ) (lam : E → ℝ) + (hw : ∀ e, List.ofFn (w e) = duplicate (left e) ++ [lam e] ++ duplicate (right e)) : + realPartition u v m w = + (∏ e, (left e).prod * (right e).prod) * logicalPartition u v lam := by + classical + let := Fintype.ofFinite {s : E → Bool // LogicalPerfect u v s} + let := Fintype.ofFinite {b : E → Selection m // FamilyPerfect u v m b} + unfold realPartition logicalPartition + rw [Finset.mul_sum] + apply Fintype.sum_equiv (familyEquiv u v m hm) + intro b + exact family_weight u v m hm w left right lam hw b.val b.property + +end MatchingFPRAS.Subdivision + +end OAI diff --git a/lean/OAI/Combinatorics/MatchingCount/Graphs/ThresholdGraph.lean b/lean/OAI/Combinatorics/MatchingCount/Graphs/ThresholdGraph.lean new file mode 100644 index 0000000000000000000000000000000000000000..3a55ec1b6af98375b5f3474b81ed4debb889ecab --- /dev/null +++ b/lean/OAI/Combinatorics/MatchingCount/Graphs/ThresholdGraph.lean @@ -0,0 +1,623 @@ +import Mathlib +import OAI.Combinatorics.MatchingCount.Graphs.FillHoles + +namespace OAI + +namespace MatchingFPRAS.Switching + +open Finset + +variable {V : Type*} + +lemma edgeActivity_of_symmetric [LinearOrder V] (B : V → V → ℝ) + (hB : ∀ a b, B a b = B b a) (a b : V) : edgeActivity B a b = B a b := by + unfold edgeActivity + split_ifs + · rfl + · exact hB b a + +theorem erasePair_factor [Fintype V] [LinearOrder V] (B : V → V → ℝ) + (hB : ∀ a b, B a b = B b a) (q : Mate V) (a b : V) + (hq : q.val a = b) (hab : a ≠ b) : + weight B q = B a b * weight B (erasePair q a b) := by + have ha : (erasePair q a b).val a = a := by simp [hq] + have hb : (erasePair q a b).val b = b := by simp [hq] + have hw := withEdge_weight B (erasePair q a b) a b ha hb hab + rw [withEdge_erasePair q a b hq,edgeActivity_of_symmetric B hB] at hw + exact hw + +lemma ultrametric_vertex_charge {A C D T : ℝ} (hA : 0 ≤ A) (hC : 0 ≤ C) + (hD : 0 ≤ D) (hAT : A ≤ T) (hCT : C ≤ T) (htri : min A C ≤ D) : + A*C ≤ T*D := by + rcases le_total A C with h | h + · rw [min_eq_left h] at htri + exact (mul_le_mul htri hCT hC hD).trans_eq (mul_comm D T) + · rw [min_eq_right h] at htri + exact mul_le_mul hAT htri hC (hA.trans hAT) + +lemma ultrametric_pair_charge {A B C D Tj Tk : ℝ} + (hA : 0 ≤ A) (hB : 0 ≤ B) (hC : 0 ≤ C) (hD : 0 ≤ D) + (hAj : A ≤ Tj) (hBk : B ≤ Tk) (hCj : C ≤ Tj) (hCk : C ≤ Tk) + (htri : min A (min C B) ≤ D) : A*B*C ≤ Tj*Tk*D := by + have hj0 := hA.trans hAj + have hk0 := hB.trans hBk + rcases le_total A (min C B) with h | h + · rw [min_eq_left h] at htri + calc + A*B*C ≤ D*Tk*Tj := by gcongr + _ = Tj*Tk*D := by ring + · rw [min_eq_right h] at htri + rcases le_total C B with hcb | hbc + · rw [min_eq_left hcb] at htri + gcongr + · rw [min_eq_right hbc] at htri + calc + A*B*C ≤ Tj*D*Tk := by gcongr + _ = Tj*Tk*D := by ring + +lemma pairing_mate_mem [Fintype V] [DecidableEq V] (q : Mate V) (U : Finset V) + (hq : HasHoles q Uᶜ) (v : V) : q.val v ∈ U ↔ v ∈ U := by + have h := mate_mem_holes_iff q Uᶜ hq v + simpa only [Finset.mem_compl, not_iff_not] using h + +theorem pairing_replace_vertex [Fintype V] [LinearOrder V] + (B : V → V → ℝ) (hB : ∀ a b, B a b = B b a) + (hB0 : ∀ a b, 0 ≤ B a b) + (htri : ∀ a b c, a ≠ b → a ≠ c → b ≠ c → min (B a c) (B c b) ≤ B a b) + (U : Finset V) (j u : V) (hj : j ∈ U) (hu : u ∉ U) + (T : ℝ) (hT : ∀ a, a ≠ j → B j a ≤ T) + (q : Mate V) (hq : HasHoles q Uᶜ) : + ∃ q' : Mate V, HasHoles q' (insert u (U.erase j))ᶜ ∧ + weight B q * B j u ≤ T * weight B q' := by + classical + let a := q.val j + have hja : j ≠ a := by + intro h + exact (Finset.mem_compl.mp ((hq j).mp h.symm)) hj + have haU : a ∈ U := (pairing_mate_mem q U hq j).mpr hj + have hua : u ≠ a := fun h => hu (h ▸ haU) + have huj : u ≠ j := fun h => hu (h ▸ hj) + have hqj : q.val j = a := rfl + have hqa : q.val a = j := mate_mate q j + have hqu : q.val u = u := (hq u).mpr (Finset.mem_compl.mpr hu) + let r := erasePair q j a + have hra : r.val a = a := by simp [r,hqj] + have hru : r.val u = u := by simp [r,hqj,huj,hua,hqu] + let q' := withEdge r u a + have he (v) : q'.val v = if v = u then a else if v = a then u + else if v = j ∨ v = a then v else q.val v := by + rw [show q'.val v = (withEdge r u a).val v from rfl, + withEdge_apply r u a v hru hra,erasePair_apply q j a v hqj] + split_ifs <;> rfl + refine ⟨q',?_,?_⟩ + · intro v + rw [he] + by_cases hvu : v = u + · subst v + simp [hua.symm] + by_cases hva : v = a + · subst v + simp [hvu,hua,haU,hja.symm] + by_cases hvj : v = j + · subst v + simp [hvu,hva] + simp only [hvu,hva,hvj,false_or,↓reduceIte] + rw [hq] + simp [hvu,hvj] + · have hwq := erasePair_factor B hB q j a hqj hja + have hwq' : weight B q' = B u a * weight B r := by + simpa only [q',edgeActivity_of_symmetric B hB] using withEdge_weight B r u a hru hra hua + have ht : min (B j a) (B j u) ≤ B u a := by + have hh := htri u a j hua huj hja.symm + simpa only [hB u j,min_comm] using hh + have hh := ultrametric_vertex_charge (hB0 j a) (hB0 j u) (hB0 u a) + (hT a hja.symm) (hT u huj) ht + have hr0 := weight_nonneg B hB0 r + have hf := mul_le_mul_of_nonneg_right hh hr0 + rw [hwq,hwq'] + dsimp only [r] at hf + nlinarith only [hf] + +theorem pairing_remove_pair [Fintype V] [LinearOrder V] + (B : V → V → ℝ) (hB : ∀ a b, B a b = B b a) + (hB0 : ∀ a b, 0 ≤ B a b) + (htri : ∀ a b c, a ≠ b → a ≠ c → b ≠ c → min (B a c) (B c b) ≤ B a b) + (U : Finset V) (j k : V) (hj : j ∈ U) (hk : k ∈ U) (hjk : j ≠ k) + (Tj Tk : ℝ) (hTj : ∀ a, a ≠ j → B j a ≤ Tj) + (hTk : ∀ a, a ≠ k → B k a ≤ Tk) + (q : Mate V) (hq : HasHoles q Uᶜ) : + ∃ q' : Mate V, HasHoles q' (U \ {j,k})ᶜ ∧ + weight B q * B j k ≤ Tj * Tk * weight B q' := by + classical + have hcj : B j k ≤ Tj := hTj k hjk.symm + have hck : B j k ≤ Tk := (hB j k).trans_le (hTk j hjk) + by_cases hqjk : q.val j = k + · let q' := erasePair q j k + refine ⟨q',?_,?_⟩ + · have hh := erasePair_holes q Uᶜ hq j k hqjk + have he : insert j (insert k Uᶜ) = (U \ {j,k})ᶜ := by ext v; simp; tauto + rwa [he] at hh + · rw [erasePair_factor B hB q j k hqjk hjk] + have hv := weight_nonneg B hB0 q' + change (B j k * weight B q') * B j k ≤ _ + calc + _ = (B j k * B j k) * weight B q' := by ring + _ ≤ (Tj*Tk) * weight B q' := by + exact mul_le_mul_of_nonneg_right (mul_le_mul hcj hck (hB0 j k) ((hB0 j k).trans hcj)) hv + · let a := q.val j + let b := q.val k + have hqj : q.val j = a := rfl + have hqk : q.val k = b := rfl + have hqa : q.val a = j := mate_mate q j + have hqb : q.val b = k := mate_mate q k + have hja : j ≠ a := by + intro h + exact (Finset.mem_compl.mp ((hq j).mp h.symm)) hj + have hkb : k ≠ b := by + intro h + exact (Finset.mem_compl.mp ((hq k).mp h.symm)) hk + have hak : a ≠ k := hqjk + have hbj : b ≠ j := by + intro h + have hh := congrArg q.val h + rw [hqb,hqj] at hh + exact hak hh.symm + have hab : a ≠ b := by + intro h + have hh := congrArg q.val h + rw [hqa,hqb] at hh + exact hjk hh + have haU : a ∈ U := (pairing_mate_mem q U hq j).mpr hj + have hbU : b ∈ U := (pairing_mate_mem q U hq k).mpr hk + let r := erasePair q j a + have hrk : r.val k = b := by simp [r,hqj,hjk.symm,hak.symm,hqk] + let z := erasePair r k b + have hza : z.val a = a := by + rw [show z.val a = (erasePair r k b).val a from rfl, erasePair_apply r k b a hrk] + simp [hak,hab,r,hqj] + have hzb : z.val b = b := by simp [z,hrk] + let q' := withEdge z a b + have he (v) : q'.val v = if v = a then b else if v = b then a + else if v = k ∨ v = b then v else if v = j ∨ v = a then v else q.val v := by + rw [show q'.val v = (withEdge z a b).val v from rfl, + withEdge_apply z a b v hza hzb,erasePair_apply r k b v hrk, + erasePair_apply q j a v hqj] + split_ifs <;> rfl + refine ⟨q',?_,?_⟩ + · intro v + rw [he] + by_cases hva : v = a + · subst v + simp [hab.symm,haU,hja.symm,hak] + by_cases hvb : v = b + · subst v + simp [hva,hab,hbU,hbj,hkb.symm] + by_cases hvj : v = j + · subst v + simp [hva,hvb] + by_cases hvk : v = k + · subst v + simp [hva,hvb] + simp only [hva,hvb,hvj,hvk,false_or,↓reduceIte] + rw [hq] + simp [hvj,hvk] + · have hwq := erasePair_factor B hB q j a hqj hja + have hwr := erasePair_factor B hB r k b hrk hkb + have hwq' : weight B q' = B a b * weight B z := by + simpa only [q',edgeActivity_of_symmetric B hB] using withEdge_weight B z a b hza hzb hab + have ht : min (B j a) (min (B j k) (B k b)) ≤ B a b := by + calc + _ ≤ min (B j a) (B j b) := + min_le_min_left _ (htri j b k hbj.symm hjk hkb.symm) + _ = min (B a j) (B j b) := by rw [hB j a] + _ ≤ _ := htri a b j hab hja.symm hbj + have hh := ultrametric_pair_charge (hB0 j a) (hB0 k b) (hB0 j k) (hB0 a b) + (hTj a hja.symm) (hTk b hkb.symm) hcj hck ht + have hz0 := weight_nonneg B hB0 z + have hf := mul_le_mul_of_nonneg_right hh hz0 + rw [hwq,show weight B (erasePair q j a) = weight B r from rfl,hwr,hwq'] + change (B j a * (B k b * weight B z)) * B j k ≤ Tj*Tk*(B a b*weight B z) + nlinarith only [hf] + +lemma weight_le_pairingCapacity [Fintype V] [LinearOrder V] + (B : V → V → ℝ) (U : Finset V) (hU : Even U.card) + (q : Mate V) (hq : HasHoles q Uᶜ) : weight B q ≤ pairingCapacity B U hU := by + exact Finset.le_sup' _ ((mem_matchings q Uᶜ).mpr hq) + +lemma pairingCapacity_nonneg [Fintype V] [LinearOrder V] + (B : V → V → ℝ) (hB : ∀ a b, 0 ≤ B a b) + (U : Finset V) (hU : Even U.card) : 0 ≤ pairingCapacity B U hU := by + obtain ⟨q,hq⟩ := pairing_exists U hU + exact (weight_nonneg B hB q).trans (weight_le_pairingCapacity B U hU q hq) + +theorem capacity_replace_vertex [Fintype V] [LinearOrder V] + (B : V → V → ℝ) (hB : ∀ a b, B a b = B b a) + (hB0 : ∀ a b, 0 ≤ B a b) + (htri : ∀ a b c, a ≠ b → a ≠ c → b ≠ c → min (B a c) (B c b) ≤ B a b) + (U : Finset V) (hU : Even U.card) (j u : V) (hj : j ∈ U) (hu : u ∉ U) + (hU' : Even (insert u (U.erase j)).card) + (T : ℝ) (hT0 : 0 ≤ T) (hT : ∀ a, a ≠ j → B j a ≤ T) : + pairingCapacity B U hU * B j u ≤ T * pairingCapacity B (insert u (U.erase j)) hU' := by + classical + obtain ⟨q,hq,hmax⟩ := Finset.exists_mem_eq_sup' + (show (matchings Uᶜ).Nonempty from by + obtain ⟨q,hq⟩ := pairing_exists U hU + exact ⟨q,(mem_matchings _ _).mpr hq⟩) (weight B) + have hcap : pairingCapacity B U hU = weight B q := hmax + obtain ⟨q',hq',hle⟩ := pairing_replace_vertex B hB hB0 htri U j u hj hu T hT q + ((mem_matchings _ _).mp hq) + rw [hcap] + exact hle.trans (mul_le_mul_of_nonneg_left + (weight_le_pairingCapacity B _ hU' q' hq') hT0) + +theorem capacity_remove_pair [Fintype V] [LinearOrder V] + (B : V → V → ℝ) (hB : ∀ a b, B a b = B b a) + (hB0 : ∀ a b, 0 ≤ B a b) + (htri : ∀ a b c, a ≠ b → a ≠ c → b ≠ c → min (B a c) (B c b) ≤ B a b) + (U : Finset V) (hU : Even U.card) (j k : V) (hj : j ∈ U) (hk : k ∈ U) (hjk : j ≠ k) + (hU' : Even (U \ {j,k}).card) + (Tj Tk : ℝ) (hj0 : 0 ≤ Tj) (hk0 : 0 ≤ Tk) + (hTj : ∀ a, a ≠ j → B j a ≤ Tj) (hTk : ∀ a, a ≠ k → B k a ≤ Tk) : + pairingCapacity B U hU * B j k ≤ Tj * Tk * pairingCapacity B (U \ {j,k}) hU' := by + classical + obtain ⟨q,hq,hmax⟩ := Finset.exists_mem_eq_sup' + (show (matchings Uᶜ).Nonempty from by + obtain ⟨q,hq⟩ := pairing_exists U hU + exact ⟨q,(mem_matchings _ _).mpr hq⟩) (weight B) + have hcap : pairingCapacity B U hU = weight B q := hmax + obtain ⟨q',hq',hle⟩ := pairing_remove_pair B hB hB0 htri U j k hj hk hjk Tj Tk hTj hTk q + ((mem_matchings _ _).mp hq) + rw [hcap] + exact hle.trans (mul_le_mul_of_nonneg_left + (weight_le_pairingCapacity B _ hU' q' hq') (mul_nonneg hj0 hk0)) + +def thresholdGraph [LinearOrder V] (w : V → V → ℝ) (t : ℝ) : SimpleGraph V where + Adj a b := a ≠ b ∧ t ≤ edgeActivity w a b + symm := ⟨by + intro a b h + exact ⟨h.1.symm,by simpa only [edgeActivity_comm w b a] using h.2⟩⟩ + loopless := ⟨by intro a h; exact h.1 rfl⟩ + +lemma strong_walk_reachable [LinearOrder V] (w : V → V → ℝ) (t : ℝ) + {a b : V} (p : (⊤ : SimpleGraph V).Walk a b) + (hp : ∀ d ∈ p.darts, t ≤ edgeActivity w d.fst d.snd) : + (thresholdGraph w t).Reachable a b := by + induction p with + | nil => exact SimpleGraph.Reachable.refl _ + | @cons a c b hac p ih => + have he : t ≤ edgeActivity w a c := hp ⟨(a,c),hac⟩ (by simp) + have htail : ∀ d ∈ p.darts, t ≤ edgeActivity w d.fst d.snd := by + intro d hd + exact hp d (by simp [hd]) + exact (SimpleGraph.Adj.reachable (G := thresholdGraph w t) + ⟨by simpa using hac,he⟩).trans (ih htail) + +lemma threshold_map_strong [LinearOrder V] (w : V → V → ℝ) (t : ℝ) + {a b : V} (p : (thresholdGraph w t).Walk a b) : + ∀ d ∈ (p.map (SimpleGraph.Hom.ofLE le_top)).darts, + t ≤ edgeActivity w d.fst d.snd := by + intro d hd + rw [SimpleGraph.Walk.darts_map] at hd + obtain ⟨e,he,rfl⟩ := List.mem_map.mp hd + exact e.adj.2 + +theorem bottleneck_threshold [Fintype V] [LinearOrder V] + (w : V → V → ℝ) (a b : V) (hab : a ≠ b) (t : ℝ) (ht : 1 < t) : + t ≤ bottleneck w a b ↔ (thresholdGraph w t).Reachable a b := by + classical + constructor + · intro h + obtain ⟨p,hp,hmax⟩ := Finset.exists_mem_eq_sup' + (show (Finset.univ : Finset ((⊤ : SimpleGraph V).Path a b)).Nonempty from + ⟨SimpleGraph.Path.singleton (by simpa using hab), Finset.mem_univ _⟩) + (pathStrength w hab) + have he : t ≤ pathStrength w hab p := by + unfold bottleneck at h + rw [dite_eq_right hab,hmax] at h + exact (le_max_iff.mp h).resolve_left (not_le_of_gt ht) + apply strong_walk_reachable w t p.val + intro d hd + exact he.trans (Finset.inf'_le _ (List.mem_toFinset.mpr hd)) + · intro h + obtain ⟨p,hp⟩ := h.exists_isPath + let q : (⊤ : SimpleGraph V).Path a b := + ⟨p.map (SimpleGraph.Hom.ofLE le_top),hp.map Function.injective_id⟩ + have hstr : t ≤ pathStrength w hab q := by + apply Finset.le_inf' + intro d hd + exact threshold_map_strong w t p d (List.mem_toFinset.mp hd) + unfold bottleneck + rw [dite_eq_right hab] + exact hstr.trans ((Finset.le_sup' _ (Finset.mem_univ q)).trans (le_max_right _ _)) + +theorem bottleneck_comm [Fintype V] [LinearOrder V] (w : V → V → ℝ) (a b : V) : + bottleneck w a b = bottleneck w b a := by + by_cases hab : a = b + · subst b; rfl + apply le_antisymm + · by_cases h : 1 < bottleneck w a b + · exact (bottleneck_threshold w b a (Ne.symm hab) _ h).mpr + (((bottleneck_threshold w a b hab _ h).mp le_rfl).symm) + · exact (le_of_not_gt h).trans (one_le_bottleneck w b a) + · by_cases h : 1 < bottleneck w b a + · exact (bottleneck_threshold w a b hab _ h).mpr + (((bottleneck_threshold w b a (Ne.symm hab) _ h).mp le_rfl).symm) + · exact (le_of_not_gt h).trans (one_le_bottleneck w a b) + +theorem bottleneck_ultrametric [Fintype V] [LinearOrder V] + (w : V → V → ℝ) (a b c : V) (hab : a ≠ b) (hac : a ≠ c) (hbc : b ≠ c) : + min (bottleneck w a c) (bottleneck w c b) ≤ bottleneck w a b := by + let t := min (bottleneck w a c) (bottleneck w c b) + by_cases ht : 1 < t + · apply (bottleneck_threshold w a b hab t ht).mpr + exact ((bottleneck_threshold w a c hac t ht).mp (min_le_left _ _)).trans + ((bottleneck_threshold w c b hbc.symm t ht).mp (min_le_right _ _)) + · exact (le_of_not_gt ht).trans (one_le_bottleneck w a b) + +theorem capacity_charged_remove [Fintype V] [LinearOrder V] + (B : V → V → ℝ) (hB : ∀ a b, B a b = B b a) (hB0 : ∀ a b, 0 ≤ B a b) + (htri : ∀ a b c, a ≠ b → a ≠ c → b ≠ c → min (B a c) (B c b) ≤ B a b) + (U : Finset V) (hU : Even U.card) (j k : V) (hj : j ∈ U) (hk : k ∈ U) + (hjk : j ≠ k) (hU' : Even (U \ {j,k}).card) (Tj Tk f : ℝ) + (hj0 : 0 < Tj) (hk0 : 0 < Tk) (hTj : ∀ a, a ≠ j → B j a ≤ Tj) + (hTk : ∀ a, a ≠ k → B k a ≤ Tk) (hf : f*Tj*Tk ≤ B j k) : + pairingCapacity B U hU * f ≤ pairingCapacity B (U \ {j,k}) hU' := by + have hc := capacity_remove_pair B hB hB0 htri U hU j k hj hk hjk hU' + Tj Tk hj0.le hk0.le hTj hTk + have hs := mul_le_mul_of_nonneg_left hf (pairingCapacity_nonneg B hB0 U hU) + have hprod : 0 < Tj*Tk := mul_pos hj0 hk0 + apply (mul_le_mul_iff_of_pos_right hprod).mp + calc + _ = pairingCapacity B U hU * (f*Tj*Tk) := by ring + _ ≤ pairingCapacity B U hU * B j k := hs + _ ≤ _ := by nlinarith only [hc] + +theorem capacity_charged_replace [Fintype V] [LinearOrder V] + (B : V → V → ℝ) (hB : ∀ a b, B a b = B b a) (hB0 : ∀ a b, 0 ≤ B a b) + (htri : ∀ a b c, a ≠ b → a ≠ c → b ≠ c → min (B a c) (B c b) ≤ B a b) + (U : Finset V) (hU : Even U.card) (j u : V) (hj : j ∈ U) (hu : u ∉ U) + (hU' : Even (insert u (U.erase j)).card) (T f : ℝ) + (hT0 : 0 < T) (hT : ∀ a, a ≠ j → B j a ≤ T) (hf : f*T ≤ B j u) : + pairingCapacity B U hU * f ≤ pairingCapacity B (insert u (U.erase j)) hU' := by + have hc := capacity_replace_vertex B hB hB0 htri U hU j u hj hu hU' T hT0.le hT + have hs := mul_le_mul_of_nonneg_left hf (pairingCapacity_nonneg B hB0 U hU) + apply (mul_le_mul_iff_of_pos_right hT0).mp + calc + _ = pairingCapacity B U hU * (f*T) := by ring + _ ≤ pairingCapacity B U hU * B j u := hs + _ ≤ _ := by nlinarith only [hc] + +inductive ChargeTrace [DecidableEq V] (B : V → V → ℝ) : + Finset V → Finset V → ℝ → Prop + | done (U) : ChargeTrace B U U 1 + | remove (U W : Finset V) (j k : V) (hj : j ∈ U) (hk : k ∈ U) (hjk : j ≠ k) + (Tj Tk f F : ℝ) (hj0 : 0 < Tj) (hk0 : 0 < Tk) (hf0 : 0 ≤ f) (hF0 : 0 ≤ F) + (hTj : ∀ a, a ≠ j → B j a ≤ Tj) (hTk : ∀ a, a ≠ k → B k a ≤ Tk) + (hf : f*Tj*Tk ≤ B j k) (next : ChargeTrace B (U \ {j,k}) W F) : + ChargeTrace B U W (f*F) + | replace (U W : Finset V) (j u : V) (hj : j ∈ U) (hu : u ∉ U) + (T f F : ℝ) (hT0 : 0 < T) (hf0 : 0 ≤ f) (hF0 : 0 ≤ F) + (hT : ∀ a, a ≠ j → B j a ≤ T) (hf : f*T ≤ B j u) + (next : ChargeTrace B (insert u (U.erase j)) W F) : + ChargeTrace B U W (f*F) + +lemma ChargeTrace.card_le [DecidableEq V] {B : V → V → ℝ} + {U W : Finset V} {F : ℝ} (h : ChargeTrace B U W F) : W.card ≤ U.card := by + induction h with + | done => rfl + | remove U W j k hj hk hjk Tj Tk f F hj0 hk0 hf0 hF0 hTj hTk hf next ih => + exact ih.trans (Finset.card_le_card Finset.sdiff_subset) + | replace U W j u hj hu T f F hT0 hf0 hF0 hT hf next ih => + have hnu : u ∉ U.erase j := fun h => hu (Finset.mem_of_mem_erase h) + rw [Finset.card_insert_of_notMem hnu,Finset.card_erase_of_mem hj] at ih + have : 0 < U.card := Finset.card_pos.mpr ⟨j,hj⟩ + omega + +lemma even_remove_two [DecidableEq V] (U : Finset V) (hU : Even U.card) + (j k : V) (hj : j ∈ U) (hk : k ∈ U) (hjk : j ≠ k) : + Even (U \ {j,k}).card := by + have he : U \ {j,k} = (U.erase j).erase k := by ext a; simp; tauto + have hk' : k ∈ U.erase j := Finset.mem_erase.mpr ⟨hjk.symm,hk⟩ + rw [he,Finset.card_erase_of_mem hk',Finset.card_erase_of_mem hj] + have h2 : 2 ≤ U.card := by + apply (Finset.card_pair hjk).symm.trans_le + apply Finset.card_le_card + intro a ha + simp only [Finset.mem_insert,Finset.mem_singleton] at ha + rcases ha with rfl | rfl <;> assumption + exact (Nat.even_iff.mpr (by have := Nat.even_iff.mp hU; omega)) + +lemma even_replace_one [DecidableEq V] (U : Finset V) (hU : Even U.card) + (j u : V) (hj : j ∈ U) (hu : u ∉ U) : Even (insert u (U.erase j)).card := by + have hnu : u ∉ U.erase j := fun h => hu (Finset.mem_of_mem_erase h) + rw [Finset.card_insert_of_notMem hnu,Finset.card_erase_of_mem hj] + have : 0 < U.card := Finset.card_pos.mpr ⟨j,hj⟩ + simpa only [Nat.sub_add_cancel (by omega : 1 ≤ U.card)] using hU + +theorem ChargeTrace.capacity_bound [Fintype V] [LinearOrder V] + {B : V → V → ℝ} (hB : ∀ a b, B a b = B b a) (hB0 : ∀ a b, 0 ≤ B a b) + (htri : ∀ a b c, a ≠ b → a ≠ c → b ≠ c → min (B a c) (B c b) ≤ B a b) + {U W : Finset V} {F : ℝ} (h : ChargeTrace B U W F) (hU : Even U.card) : + ∃ hW : Even W.card, pairingCapacity B U hU * F ≤ pairingCapacity B W hW := by + induction h with + | done U => exact ⟨hU,by simp⟩ + | remove U W j k hj hk hjk Tj Tk f F hj0 hk0 hf0 hF0 hTj hTk hf next ih => + have he := even_remove_two U hU j k hj hk hjk + obtain ⟨hW,hWb⟩ := ih he + refine ⟨hW,?_⟩ + calc + _ = (pairingCapacity B U hU * f) * F := by ring + _ ≤ pairingCapacity B (U \ {j,k}) he * F := mul_le_mul_of_nonneg_right + (capacity_charged_remove B hB hB0 htri U hU j k hj hk hjk he Tj Tk f + hj0 hk0 hTj hTk hf) hF0 + _ ≤ _ := hWb + | replace U W j u hj hu T f F hT0 hf0 hF0 hT hf next ih => + have he := even_replace_one U hU j u hj hu + obtain ⟨hW,hWb⟩ := ih he + refine ⟨hW,?_⟩ + calc + _ = (pairingCapacity B U hU * f) * F := by ring + _ ≤ pairingCapacity B (insert u (U.erase j)) he * F := mul_le_mul_of_nonneg_right + (capacity_charged_replace B hB hB0 htri U hU j u hj hu he T f hT0 hT hf) hF0 + _ ≤ _ := hWb + +theorem edgeActivity_le_bottleneck [Fintype V] [LinearOrder V] + (w : V → V → ℝ) (a b : V) (hab : a ≠ b) : + edgeActivity w a b ≤ bottleneck w a b := by + by_cases h : 1 < edgeActivity w a b + · exact (bottleneck_threshold w a b hab _ h).mpr + (SimpleGraph.Adj.reachable (G := thresholdGraph w _) ⟨hab,le_rfl⟩) + · exact (le_of_not_gt h).trans (one_le_bottleneck w a b) + +theorem bottleneck_le_row_bound [Fintype V] [LinearOrder V] + (w : V → V → ℝ) (a : V) (T : ℝ) (hT : 1 ≤ T) + (hrow : ∀ b, a ≠ b → edgeActivity w a b ≤ T) (b : V) : + bottleneck w a b ≤ T := by + by_cases hab : a = b + · subst b; simpa [bottleneck] using hT + by_cases hB : 1 < bottleneck w a b + · obtain ⟨L,hL,hnd,hb⟩ := bottleneck_path w a b hab hB + cases L with + | nil => simp at hb + | cons c L => + have hne : a ≠ c := by + have h := (List.nodup_cons.mp hnd).1 + simp only [List.mem_cons,not_or] at h + exact h.1 + have he := (List.isChain_cons_cons.mp hL).1 + exact he.trans (hrow c hne) + · exact (le_of_not_gt hB).trans hT + +theorem bottleneck_eq_of_threshold_iff + {W : Type*} [Fintype V] [LinearOrder V] [Fintype W] [LinearOrder W] + (w : V → V → ℝ) (w' : W → W → ℝ) (a b : V) (a' b' : W) + (hab : a ≠ b) (hab' : a' ≠ b') + (h : ∀ t : ℝ, 1 < t → + ((thresholdGraph w t).Reachable a b ↔ (thresholdGraph w' t).Reachable a' b')) : + bottleneck w a b = bottleneck w' a' b' := by + apply le_antisymm + · by_cases ht : 1 < bottleneck w a b + · exact (bottleneck_threshold w' a' b' hab' _ ht).mpr + ((h _ ht).mp ((bottleneck_threshold w a b hab _ ht).mp le_rfl)) + · exact (le_of_not_gt ht).trans (one_le_bottleneck w' a' b') + · by_cases ht : 1 < bottleneck w' a' b' + · exact (bottleneck_threshold w a b hab _ ht).mpr + ((h _ ht).mpr ((bottleneck_threshold w' a' b' hab' _ ht).mp le_rfl)) + · exact (le_of_not_gt ht).trans (one_le_bottleneck w a b) + +def pairVertices (xs : List (V × V)) : List V := xs.flatMap (fun q => [q.1,q.2]) + +lemma ChargeTrace.trans [DecidableEq V] {B : V → V → ℝ} + {U W X : Finset V} {F G : ℝ} (h : ChargeTrace B U W F) + (h' : ChargeTrace B W X G) (hG : 0 ≤ G) : ChargeTrace B U X (F*G) := by + induction h with + | done U => simpa using h' + | remove U W j k hj hk hjk Tj Tk f F hj0 hk0 hf0 hF0 hTj hTk hf next ih => + have ht := ChargeTrace.remove U X j k hj hk hjk Tj Tk f (F*G) hj0 hk0 hf0 + (mul_nonneg hF0 hG) hTj hTk hf (ih h') + simpa [mul_assoc] using ht + | replace U W j u hj hu T f F hT0 hf0 hF0 hT hf next ih => + have ht := ChargeTrace.replace U X j u hj hu T f (F*G) hT0 hf0 + (mul_nonneg hF0 hG) hT hf (ih h') + simpa [mul_assoc] using ht + +theorem charge_remove_list [DecidableEq V] (B : V → V → ℝ) (T : V → ℝ) + (f : V × V → ℝ) (xs : List (V × V)) (U : Finset V) + (hnd : (pairVertices xs).Nodup) (hsub : ∀ a ∈ pairVertices xs, a ∈ U) + (hlocal : ∀ q ∈ xs, + 0 < T q.1 ∧ 0 < T q.2 ∧ 0 ≤ f q ∧ + (∀ a, a ≠ q.1 → B q.1 a ≤ T q.1) ∧ + (∀ a, a ≠ q.2 → B q.2 a ≤ T q.2) ∧ f q*T q.1*T q.2 ≤ B q.1 q.2) : + ChargeTrace B U (U \ (pairVertices xs).toFinset) (xs.map f).prod := by + induction xs generalizing U with + | nil => simpa [pairVertices] using ChargeTrace.done (B := B) U + | cons q xs ih => + obtain ⟨j,k⟩ := q + have hn : j ≠ k ∧ j ∉ pairVertices xs ∧ k ∉ pairVertices xs ∧ (pairVertices xs).Nodup := by + simpa [pairVertices,List.nodup_cons,and_assoc] using hnd + have hj : j ∈ U := hsub j (by simp [pairVertices]) + have hk : k ∈ U := hsub k (by simp [pairVertices]) + have hs : ∀ a ∈ pairVertices xs, a ∈ U \ {j,k} := by + intro a ha + have haj : a ≠ j := fun he => hn.2.1 (he ▸ ha) + have hak : a ≠ k := fun he => hn.2.2.1 (he ▸ ha) + simp only [Finset.mem_sdiff,Finset.mem_insert,Finset.mem_singleton,not_or] + exact ⟨hsub a (by simp [pairVertices] at ha ⊢; exact Or.inr (Or.inr ha)),haj,hak⟩ + have hl : ∀ q ∈ xs, + 0 < T q.1 ∧ 0 < T q.2 ∧ 0 ≤ f q ∧ + (∀ a, a ≠ q.1 → B q.1 a ≤ T q.1) ∧ + (∀ a, a ≠ q.2 → B q.2 a ≤ T q.2) ∧ f q*T q.1*T q.2 ≤ B q.1 q.2 := + fun q hq => hlocal q (List.mem_cons_of_mem _ hq) + have ht := ih (U \ {j,k}) hn.2.2.2 hs hl + have hp : 0 ≤ (xs.map f).prod := by + apply List.prod_nonneg + intro a ha + obtain ⟨q,hq,rfl⟩ := List.mem_map.mp ha + exact (hl q hq).2.2.1 + have he : (U \ {j,k}) \ (pairVertices xs).toFinset = + U \ (pairVertices ((j,k)::xs)).toFinset := by + ext a + simp [pairVertices] + tauto + obtain ⟨hTj,hTk,hf,hjrow,hkrow,hbound⟩ := hlocal (j,k) (by simp) + have hr := ChargeTrace.remove U _ j k hj hk hn.1 (T j) (T k) (f (j,k)) + (xs.map f).prod hTj hTk hf hp hjrow hkrow hbound ht + simpa only [List.map_cons,List.prod_cons,he] using hr + +theorem charge_replace_list [DecidableEq V] (B : V → V → ℝ) (T : V → ℝ) + (f : V × V → ℝ) (xs : List (V × V)) (U : Finset V) + (hsrc : (xs.map Prod.fst).Nodup) (hdst : (xs.map Prod.snd).Nodup) + (hsub : ∀ q ∈ xs, q.1 ∈ U) (hfresh : ∀ q ∈ xs, q.2 ∉ U) + (hlocal : ∀ q ∈ xs, 0 < T q.1 ∧ 0 ≤ f q ∧ + (∀ a, a ≠ q.1 → B q.1 a ≤ T q.1) ∧ f q*T q.1 ≤ B q.1 q.2) : + ChargeTrace B U ((U \ (xs.map Prod.fst).toFinset) ∪ (xs.map Prod.snd).toFinset) + (xs.map f).prod := by + induction xs generalizing U with + | nil => simpa using ChargeTrace.done (B := B) U + | cons q xs ih => + obtain ⟨j,u⟩ := q + have hsrc' : j ∉ xs.map Prod.fst ∧ (xs.map Prod.fst).Nodup := by simpa using hsrc + have hdst' : u ∉ xs.map Prod.snd ∧ (xs.map Prod.snd).Nodup := by simpa using hdst + have hj : j ∈ U := hsub (j,u) (by simp) + have hu : u ∉ U := hfresh (j,u) (by simp) + have hs : ∀ q ∈ xs, q.1 ∈ insert u (U.erase j) := by + intro q hq + have hn : q.1 ≠ j := by + intro he; exact hsrc'.1 (he ▸ List.mem_map.mpr ⟨q,hq,rfl⟩) + simp only [Finset.mem_insert,Finset.mem_erase] + exact Or.inr ⟨hn,hsub q (by simp [hq])⟩ + have hf : ∀ q ∈ xs, q.2 ∉ insert u (U.erase j) := by + intro q hq + have hn : q.2 ≠ u := by + intro he; exact hdst'.1 (he ▸ List.mem_map.mpr ⟨q,hq,rfl⟩) + simp only [Finset.mem_insert,Finset.mem_erase,not_or,not_and] + exact ⟨hn,fun _ => hfresh q (by simp [hq])⟩ + have hl : ∀ q ∈ xs, 0 < T q.1 ∧ 0 ≤ f q ∧ + (∀ a, a ≠ q.1 → B q.1 a ≤ T q.1) ∧ f q*T q.1 ≤ B q.1 q.2 := + fun q hq => hlocal q (List.mem_cons_of_mem _ hq) + have ht := ih (insert u (U.erase j)) hsrc'.2 hdst'.2 hs hf hl + have hp : 0 ≤ (xs.map f).prod := by + apply List.prod_nonneg + intro a ha + obtain ⟨q,hq,rfl⟩ := List.mem_map.mp ha + exact (hl q hq).2.1 + have hus : u ∉ xs.map Prod.fst := by + rintro h + obtain ⟨q,hq,he⟩ := List.mem_map.mp h + exact hu (he ▸ hsub q (by simp [hq])) + have he : ((insert u (U.erase j)) \ (xs.map Prod.fst).toFinset) ∪ (xs.map Prod.snd).toFinset = + (U \ (((j,u)::xs).map Prod.fst).toFinset) ∪ (((j,u)::xs).map Prod.snd).toFinset := by + ext a + by_cases hau : a=u + · subst a; simp [hus] + · simp only [List.map_cons,List.toFinset_cons,Finset.mem_union,Finset.mem_sdiff, + Finset.mem_insert,Finset.mem_erase,List.mem_toFinset,hau,false_or] + tauto + obtain ⟨hT,hf0,hrow,hbound⟩ := hlocal (j,u) (by simp) + have hr := ChargeTrace.replace U _ j u hj hu (T j) (f (j,u)) (xs.map f).prod + hT hf0 hp hrow hbound ht + simpa only [List.map_cons,List.prod_cons,he] using hr + +end MatchingFPRAS.Switching + +end OAI diff --git a/lean/OAI/Combinatorics/MatchingCount/Graphs/TreeBagBuild.lean b/lean/OAI/Combinatorics/MatchingCount/Graphs/TreeBagBuild.lean new file mode 100644 index 0000000000000000000000000000000000000000..ea0c7a6b2a1dae7da2337d9d391465b9aeb828ae --- /dev/null +++ b/lean/OAI/Combinatorics/MatchingCount/Graphs/TreeBagBuild.lean @@ -0,0 +1,128 @@ +import Mathlib +import OAI.Combinatorics.MatchingCount.Machines.TreePostRealization +import OAI.Combinatorics.MatchingCount.Machines.TreeBuild +import OAI.Combinatorics.MatchingCount.Graphs.TreeBags + +namespace OAI + +namespace MatchingFPRAS.ExecutableSource +open TreeTyped TreeFraction TreeTyped.Numbered ExecutableBottleneck ExecutableHierarchy Enlargement RealGeometry + +attribute [local instance] NumberedHierarchy.labelOrder +local instance : BEq RawVertex := ⟨fun a b=>decide (a=b)⟩ +local instance : LawfulBEq RawVertex where + eq_of_beq := by intro a b h; exact of_decide_eq_true h + rfl := by intro a; exact decide_eq_true rfl + +def endpointEntry (x : (GeometryInput×List RawVertex)×RawReal) : ℕ×ℕ := + (x.1.2.idxOf (left (x.1.1,x.2)),x.1.2.idxOf (right (x.1.1,x.2))) +def endpointEntryRealizer : Realizer endpointEntry := (pair + (composition (pair (composition (pair first.fst second) leftRealizer) first.snd) (indexOf vertexEqual)) + (composition (pair (composition (pair first.fst second) rightRealizer) first.snd) (indexOf vertexEqual))).congr (fun _=>rfl) +lemma polynomial_endpointEntry : PolynomialTime endpointEntryRealizer := by + unfold endpointEntryRealizer + apply polynomial_congr + have := polynomial_indexOf polynomial_vertexEqual + have := polynomial_left + have := polynomial_right + dsimp only [Realizer.fst,Realizer.snd] + tree_cost + +def endpointList (x : GeometryInput) : List (ℕ×ℕ) := + (realEdges x).map (fun e=>endpointEntry ((x,vertices x),e)) +def endpointListRealizer : Realizer endpointList := composition + (pair (pair identity verticesRealizer) realEdgesRealizer) (mapWith endpointEntryRealizer) +lemma polynomial_endpointList : PolynomialTime endpointListRealizer := by + unfold endpointListRealizer + exact polynomial_composition (polynomial_pair (polynomial_pair polynomial_identity + polynomial_vertices) polynomial_realEdges) (polynomial_mapWith polynomial_endpointEntry) + +lemma index_vertices {n : ℕ} (K : ℕ) (fuel : List Bool) (hf : fuel.length=2*K+2) + (v : SourceVertex (Fin n) K) : (vertices (List.range n,fuel)).idxOf (vertexRepr v)=index v := by + rw [vertices_eq_ofFn_length n fuel _ (by rw [hf])] + let e:=UnitRefresh.orderedEnum (SourceVertex (Fin n) K) + let i:=e.symm v + have hn : (List.ofFn (fun j=>vertexRepr (e j))).Nodup := + List.nodup_ofFn.mpr (vertexRepr_injective.comp e.injective) + have hi : i.val<(List.ofFn (fun j=>vertexRepr (e j))).length := by simpa only [List.length_ofFn] using i.isLt + have he:=@List.Nodup.idxOf_getElem RawVertex _ _ _ hn i.val hi + simpa only [List.getElem_ofFn,Fin.eta,i,Equiv.apply_symm_apply,e,index] using he + +lemma endpointEntry_source {n : ℕ} (K : ℕ) (fuel : List Bool) (hf : fuel.length=2*K+2) + (e : SourceRealEdge (Fin n) K) : + endpointEntry (((List.range n,fuel),vertices (List.range n,fuel)),realRepr e)= + (index (realLeft K e),index (realRight K e)) := by + have h:=ends_source_repr K fuel hf e + have hl:=congrArg Prod.fst h + have hr:=congrArg Prod.snd h + unfold endpointEntry + dsimp only at hl hr ⊢ + rw [hl,hr,index_vertices K fuel hf,index_vertices K fuel hf] + rfl + +lemma endpointList_members {n : ℕ} (K : ℕ) (fuel : List Bool) (hf : fuel.length=2*K+2) + (p : ℕ×ℕ) : p∈endpointList (List.range n,fuel) ↔ + ∃ e : SourceRealEdge (Fin n) K,(index (realLeft K e),index (realRight K e))=p := by + have hm (e : RawReal) : e∈realEdges (List.range n,fuel) ↔ + ∃ a : SourceRealEdge (Fin n) K,realRepr a=e := by + rw [←List.mem_toFinset,realEdges_finset n K fuel hf] + simp only [Finset.mem_image,Finset.mem_univ,true_and] + simp only [endpointList,List.mem_map,hm] + constructor + · rintro ⟨e,⟨a,rfl⟩,hp⟩ + exact ⟨a,(endpointEntry_source K fuel hf a).symm.trans hp⟩ + · rintro ⟨e,he⟩ + exact ⟨realRepr e,⟨e,rfl⟩,(endpointEntry_source K fuel hf e).trans he⟩ + +abbrev BagBuildInput := BuildInput×List Bool +def buildBags (x : BagBuildInput) : ExecutableDP.Bags := + bagTable ((buildClosure x.1,x.2),endpointList (x.1.2,x.1.1.2)) +def buildBagsRealizer : Realizer buildBags := (composition + (pair (pair (composition first buildClosureRealizer) second) + (composition (pair first.snd first.fst.snd) endpointListRealizer)) bagTableRealizer).congr (fun _=>rfl) +lemma polynomial_buildBags : PolynomialTime buildBagsRealizer := by + unfold buildBagsRealizer + apply polynomial_congr + have := polynomial_buildClosure + have := polynomial_endpointList + have := polynomial_bagTable + dsimp only [Realizer.fst,Realizer.snd] + tree_cost + +lemma source_bagTable {n : ℕ} [Nontrivial (Fin n)] + (w : Fin n→Fin n→ℚ) (K : ℕ) : + List.Forall₂ List.Perm + (bagTable ((matrixRep (fun i j=>RationalSource.realB w K + (UnitRefresh.orderedEnum (SourceVertex (Fin n) K) i) + (UnitRefresh.orderedEnum (SourceVertex (Fin n) K) j)), + List.replicate (RationalSource.levels w K) false), + endpointList (List.range n,List.replicate (2*K+2) false))) + (ExecutableDP.orderedRep (UnitRefresh.numberedBags (RationalSource.bags w K))) := by + exact arbitrary_bagTable_fintype (RationalSource.realB w K) + (fun a b=>(by norm_num : (0:ℚ)≤1).trans (RationalSource.realB_floor w K a b)) + (RationalSource.realB_symm w K) (RationalSource.realB_tri w K) + (List.replicate (RationalSource.levels w K) false) (realLeft K) (realRight K) + (endpointList (List.range n,List.replicate (2*K+2) false)) + (endpointList_members K _ (List.length_replicate ..)) + (RationalSource.levels w K) (List.length_replicate ..) + (inferInstance : Fintype (RationalSource.Label w K)) + +lemma buildBags_source {n : ℕ} [Nontrivial (Fin n)] (hn : 2≤n) + (w : Fin n→Fin n→ℚ) (hw : ∀ i j,0≤w i j) (K : ℕ) : + List.Forall₂ List.Perm + (buildBags (((matrixRep w,List.replicate (2*K+2) false),List.range n), + List.replicate (RationalSource.levels w K) false)) + (ExecutableDP.orderedRep (UnitRefresh.numberedBags (RationalSource.bags w K))) := by + unfold buildBags + rw [buildClosure_repr hn w hw K] + exact source_bagTable w K + +theorem buildBags_post : ∃ p : Polynomial ℕ,∀ x : BagBuildInput,∀ t : ℕ, + p.eval (TreePost.packed x).length≤t → ∀ coins : Fin t→Bool, + (run (TreePost.machine buildBagsRealizer.program) (TreePost.packed x) coins).state=none ∧ + (run (TreePost.machine buildBagsRealizer.program) (TreePost.packed x) coins).tape.right₀= + Turing.ListBlank.mk (TreePost.packed (buildBags x)) := + TreePost.polynomial_compiles buildBagsRealizer polynomial_buildBags +end MatchingFPRAS.ExecutableSource + +end OAI diff --git a/lean/OAI/Combinatorics/MatchingCount/Graphs/TreeBagCorrect.lean b/lean/OAI/Combinatorics/MatchingCount/Graphs/TreeBagCorrect.lean new file mode 100644 index 0000000000000000000000000000000000000000..6a0cc36e0d4f4780c2dca0b39a67d9393b218655 --- /dev/null +++ b/lean/OAI/Combinatorics/MatchingCount/Graphs/TreeBagCorrect.lean @@ -0,0 +1,72 @@ +import Mathlib +import OAI.Combinatorics.MatchingCount.Sampling.TreeDPRepresentation +import OAI.Combinatorics.MatchingCount.Graphs.TreeBagTable + +namespace OAI + +namespace MatchingFPRAS.ExecutableHierarchy +open TreeTyped TreeFraction ExecutableBottleneck + +local instance {n H : ℕ} (B : Fin n→Fin n→ℚ) : LinearOrder (NumberedHierarchy.Label B H) := NumberedHierarchy.labelOrder B H +local instance (priority := 2000) {n H : ℕ} (B : Fin n→Fin n→ℚ) : LE (NumberedHierarchy.Label B H) := (NumberedHierarchy.labelOrder B H).toLE + +variable {n : ℕ} (B : Fin n→Fin n→ℚ) (hB : ∀ a b,0 ≤ B a b) + (hsym : ∀ a b,B a b=B b a) + (htri : ∀ x y z,x≠y → x≠z → y≠z → min (B x z) (B z y)≤B x y) + (xs : List Bool) {E : Type} [Fintype E] [DecidableEq E] (left right : E→Fin n) + (es : List (ℕ×ℕ)) + (hes : ∀ p,p∈es ↔ ∃ e,((left e).val,(right e).val)=p) + +include hB hes +omit [DecidableEq E] in +lemma bag_members [DecidableEq E] (v : Fin n) (i : ℕ) : + i∈bag (((matrixRep B,xs),es),v.val) ↔ ∃ e,(v=left e ∨ v=right e) ∧ + ((UnitRefresh.orderedEnum (NumberedHierarchy.Label B xs.length)).symm + (NumberedHierarchy.edgeLabel B hsym htri left right xs.length e)).val=i := by + simp only [bag,List.mem_dedup,List.mem_map,List.mem_filter] + constructor + · rintro ⟨p,⟨hp,hv⟩,hi⟩ + obtain ⟨e,rfl⟩ := (hes p).mp hp + refine ⟨e,?_,?_⟩ + · simpa only [incident,decide_eq_true_eq,Fin.val_inj] using hv + · rw [edgeIndex_eq B hB hsym htri xs left right e] at hi + exact hi + · rintro ⟨e,hv,hi⟩ + refine ⟨((left e).val,(right e).val),⟨(hes _).mpr ⟨e,rfl⟩,?_⟩,?_⟩ + · simpa only [incident,decide_eq_true_eq,Fin.val_inj] using hv + · rw [edgeIndex_eq B hB hsym htri xs left right e] + exact hi + +noncomputable def colorNumberedBags (v : Fin n) : Finset (Fin (Fintype.card (NumberedHierarchy.Label B xs.length))) := + (NumberedHierarchy.bags B hsym htri left right xs.length v).map + (UnitRefresh.orderedEnum (NumberedHierarchy.Label B xs.length)).symm.toEmbedding + +lemma bag_perm (v : Fin n) : + (bag (((matrixRep B,xs),es),v.val)).Perm + (ExecutableDP.bagRep (colorNumberedBags B hsym htri xs left right v)) := by + apply (List.perm_ext_iff_of_nodup (List.nodup_dedup _) ((Finset.nodup_toList _).map Fin.val_injective)).mpr + intro i + change i∈bag (((matrixRep B,xs),es),v.val) ↔ i∈ExecutableDP.bagRep (colorNumberedBags B hsym htri xs left right v) + rw [bag_members B hB hsym htri xs left right es hes] + simp only [ExecutableDP.bagRep,List.mem_map,Finset.mem_toList,colorNumberedBags,Finset.mem_map, + Equiv.toEmbedding_apply,NumberedHierarchy.mem_bags] + constructor + · rintro ⟨e,he,hi⟩ + exact ⟨_,⟨_,⟨e,he,rfl⟩,rfl⟩,hi⟩ + · rintro ⟨a,⟨l,⟨e,he,hel⟩,hla⟩,hai⟩ + subst l + subst a + exact ⟨e,he,hai⟩ +lemma bagTable_represented : + List.Forall₂ List.Perm (bagTable ((matrixRep B,xs),es)) + (ExecutableDP.orderedRep (colorNumberedBags B hsym htri xs left right)) := by + unfold bagTable ExecutableDP.orderedRep + rw [matrixRep_length,ExecutableDP.map_range_ofFn] + apply List.forall₂_iff_get.mpr + refine ⟨by simp, ?_⟩ + intro i hi _hi' + simpa only [List.get_eq_getElem,List.getElem_ofFn] using bag_perm B hB hsym htri xs left right es hes ⟨i,by simpa using hi⟩ + +end MatchingFPRAS.ExecutableHierarchy + +end OAI diff --git a/lean/OAI/Combinatorics/MatchingCount/Graphs/TreeBagTable.lean b/lean/OAI/Combinatorics/MatchingCount/Graphs/TreeBagTable.lean new file mode 100644 index 0000000000000000000000000000000000000000..d6f8a2aaaa805e19c76468b0432b0e6f18f3a57b --- /dev/null +++ b/lean/OAI/Combinatorics/MatchingCount/Graphs/TreeBagTable.lean @@ -0,0 +1,98 @@ +import Mathlib +import OAI.Combinatorics.MatchingCount.Machines.TreeParentTable + +namespace OAI + +namespace MatchingFPRAS.ExecutableHierarchy +open TreeTyped TreeFraction ExecutableBottleneck Polynomial + +abbrev BagInput := HierarchyInput×List (ℕ×ℕ) + +def edgeKey (x : HierarchyInput×(ℕ×ℕ)) : LabelKey := + let k:=level (x.1.2.length,cell (x.1.1,x.2)) + (k,labelRoot (x.1,(k,x.2.1))) +def edgeKeyRealizer : Realizer edgeKey := by + let k : Realizer (fun x : HierarchyInput×(ℕ×ℕ)=>level (x.1.2.length,cell (x.1.1,x.2))) := + composition (pair (composition first.snd listLength) (composition (pair first.fst second) cellRealizer)) levelRealizer + exact (pair k (composition (pair first (pair k second.fst)) labelRootRealizer)).congr (fun _=>rfl) +lemma polynomial_edgeKey : PolynomialTime edgeKeyRealizer := by + unfold edgeKeyRealizer + dsimp only [Realizer.fst,Realizer.snd] + apply polynomial_congr + have := polynomial_labelRoot + have := polynomial_level + have := polynomial_cell + tree_cost + +def incident (x : ℕ×(ℕ×ℕ)) : Bool := decide (x.1=x.2.1 ∨ x.1=x.2.2) +def incidentRealizer : Realizer incident := + (composition (pair (composition (pair first second.fst) natEqual) + (composition (pair first second.snd) natEqual)) boolOr).congr (fun _=>by simp only [incident,Bool.decide_or,Function.comp_apply]) +lemma polynomial_incident : PolynomialTime incidentRealizer := by + unfold incidentRealizer + dsimp only [Realizer.fst,Realizer.snd] + apply polynomial_congr + tree_cost + +def edgeIndex (x : (HierarchyInput×List LabelKey)×(ℕ×ℕ)) : ℕ := + x.1.2.idxOf (edgeKey (x.1.1,x.2)) +def edgeIndexRealizer : Realizer edgeIndex := composition + (pair (composition (pair first.fst second) edgeKeyRealizer) first.snd) (indexOf (pairEqual natEqual natEqual)) +lemma polynomial_edgeIndex : PolynomialTime edgeIndexRealizer := by + unfold edgeIndexRealizer + exact polynomial_composition (polynomial_pair + (polynomial_composition (polynomial_pair (polynomial_fst polynomial_first) polynomial_second) polynomial_edgeKey) + (polynomial_snd polynomial_first)) (polynomial_indexOf (polynomial_pairEqual polynomial_natEqual polynomial_natEqual)) + +def bag (x : BagInput×ℕ) : List ℕ := + ((x.1.2.filter fun e=>incident (x.2,e)).map fun e=>edgeIndex ((x.1.1,labels x.1.1),e)).dedup +def bagRealizer : Realizer bag := + (composition (composition (pair (pair first.fst (composition first.fst labelsRealizer)) + (composition (pair second first.snd) (filterWith incidentRealizer))) (mapWith edgeIndexRealizer)) (dedup natEqual)).congr (fun _=>rfl) +lemma polynomial_bag : PolynomialTime bagRealizer := by + unfold bagRealizer + dsimp only [Realizer.fst,Realizer.snd] + apply polynomial_congr + have := polynomial_labels + have := polynomial_filterWithList polynomial_incident + have := polynomial_mapWith polynomial_edgeIndex + have := polynomial_dedup polynomial_natEqual + tree_cost + +def bagTable (x : BagInput) : ExecutableDP.Bags := (List.range x.1.1.length).map fun v=>bag (x,v) +def bagTableRealizer : Realizer bagTable := composition + (pair identity (composition (composition first.fst listLength) range)) (mapWith bagRealizer) +lemma polynomial_bagTable : PolynomialTime bagTableRealizer := by + have hr : PolynomialTime (composition (composition (first (A:=HierarchyInput) (B:=List (ℕ×ℕ))).fst listLength) range) := by + apply polynomial_boundedRange (polynomial_composition (polynomial_fst polynomial_first) polynomial_listLength) X + intro x + simpa using (list_length_le_weight x.1.1).trans ((weight_fst x.1).trans (weight_fst x)) + exact polynomial_composition (polynomial_pair polynomial_identity hr) (polynomial_mapWith polynomial_bag) + +local instance {n H : ℕ} (B : Fin n→Fin n→ℚ) : LinearOrder (NumberedHierarchy.Label B H) := NumberedHierarchy.labelOrder B H +local instance (priority := 2000) {n H : ℕ} (B : Fin n→Fin n→ℚ) : LE (NumberedHierarchy.Label B H) := (NumberedHierarchy.labelOrder B H).toLE +lemma edgeKey_eq {n : ℕ} (B : Fin n→Fin n→ℚ) (hB : ∀ a b,0 ≤ B a b) + (hsym : ∀ a b,B a b=B b a) + (htri : ∀ x y z,x≠y → x≠z → y≠z → min (B x z) (B z y)≤B x y) + (xs : List Bool) {E : Type} [Fintype E] (left right : E→Fin n) (e : E) : + edgeKey ((matrixRep B,xs),((left e).val,(right e).val))= + key (NumberedHierarchy.edgeLabel B hsym htri left right xs.length e) := by + unfold edgeKey + rw [cell_matrixRep,level_repr _ _ (hB _ _)] + apply Prod.ext + · rfl + exact labelRoot_matrixRep B hB xs (NumberedHierarchy.level xs.length (B (left e) (right e))) (left e) +lemma edgeIndex_eq {n : ℕ} (B : Fin n→Fin n→ℚ) (hB : ∀ a b,0 ≤ B a b) + (hsym : ∀ a b,B a b=B b a) + (htri : ∀ x y z,x≠y → x≠z → y≠z → min (B x z) (B z y)≤B x y) + (xs : List Bool) {E : Type} [Fintype E] (left right : E→Fin n) (e : E) : + edgeIndex (((matrixRep B,xs),labels (matrixRep B,xs)),((left e).val,(right e).val))= + ((UnitRefresh.orderedEnum (NumberedHierarchy.Label B xs.length)).symm + (NumberedHierarchy.edgeLabel B hsym htri left right xs.length e)).val := by + unfold edgeIndex + rw [edgeKey_eq B hB hsym htri xs left right e] + exact index_key B hB xs (NumberedHierarchy.edgeLabel B hsym htri left right xs.length e) + +end MatchingFPRAS.ExecutableHierarchy + +end OAI diff --git a/lean/OAI/Combinatorics/MatchingCount/Graphs/TreeBags.lean b/lean/OAI/Combinatorics/MatchingCount/Graphs/TreeBags.lean new file mode 100644 index 0000000000000000000000000000000000000000..27a6d6b5982e7808d183d25579de5c65690a8d45 --- /dev/null +++ b/lean/OAI/Combinatorics/MatchingCount/Graphs/TreeBags.lean @@ -0,0 +1,117 @@ +import Mathlib +import OAI.Combinatorics.MatchingCount.Graphs.TreeBagCorrect +import OAI.Combinatorics.MatchingCount.Graphs.TreeHierarchyReindex + +namespace OAI + +namespace MatchingFPRAS.ExecutableHierarchy +open TreeTyped TreeFraction TreeTyped.Numbered ExecutableBottleneck NumberedHierarchy + +variable {V : Type} [Fintype V] [LinearOrder V] +variable (B : V→V→ℚ) (hB : ∀ a b,0 ≤ B a b) + (hsym : ∀ a b,B a b=B b a) + (htri : ∀ x y z,x≠y → x≠z → y≠z → min (B x z) (B z y)≤B x y) +attribute [local instance] NumberedHierarchy.labelOrder +local instance (priority := 2000) treeBagsLabelLE {U : Type} [Fintype U] [LinearOrder U] {H : ℕ} + (C : U→U→ℚ) : LE (Label C H) := (labelOrder C H).toLE +variable (xs : List Bool) {E : Type} [Fintype E] [DecidableEq E] (left right : E→V) + (es : List (ℕ×ℕ)) + (hes : ∀ p,p∈es ↔ ∃ e,(index (left e),index (right e))=p) + +include hB hes in +lemma arbitrary_bag_members (v : V) (i : ℕ) : + i∈bag (((matrixRep (reindex B (orderedIso V)),xs),es),index v) ↔ + ∃ e,(v=left e ∨ v=right e) ∧ index (edgeLabel B hsym htri left right xs.length e)=i := by + let f:=orderedIso V + have hh:=bag_members (reindex B f) (fun a b=>hB (f a) (f b)) + (reindex_symm B f hsym) (reindex_tri B f htri) xs (f.symm ∘ left) (f.symm ∘ right) + es hes (f.symm v) i + change i∈bag (((matrixRep (reindex B f),xs),es),index v) ↔ _ at hh + rw [hh] + apply exists_congr + intro a + have he:=labelReindex_index B f xs.length (edgeLabel (reindex B f) + (reindex_symm B f hsym) (reindex_tri B f htri) + (f.symm ∘ left) (f.symm ∘ right) xs.length a) + rw [edgeLabel_reindex B f hsym htri] at he + change (f.symm v=f.symm (left a) ∨ f.symm v=f.symm (right a)) ∧ _ ↔ _ + simp only [f.symm.injective.eq_iff] + simpa only [index] using iff_of_eq (congrArg (fun j=>(v=left a ∨ v=right a) ∧ j=i) he.symm) + +noncomputable def arbitraryNumberedBags (v : V) : + Finset (Fin (Fintype.card (Label B xs.length))) := + (NumberedHierarchy.bags B hsym htri left right xs.length v).map + (UnitRefresh.orderedEnum (Label B xs.length)).symm.toEmbedding + +include hB hes in +lemma arbitrary_bag_perm (v : V) : + (bag (((matrixRep (reindex B (orderedIso V)),xs),es),index v)).Perm + (ExecutableDP.bagRep (arbitraryNumberedBags B hsym htri xs left right v)) := by + apply (List.perm_ext_iff_of_nodup (List.nodup_dedup _) ((Finset.nodup_toList _).map Fin.val_injective)).mpr + intro i + change i∈bag (((matrixRep (reindex B (orderedIso V)),xs),es),index v) ↔ _ + rw [arbitrary_bag_members B hB hsym htri xs left right es hes] + simp only [List.mem_map,Finset.mem_toList,arbitraryNumberedBags, + Finset.mem_map,Equiv.toEmbedding_apply,NumberedHierarchy.mem_bags] + constructor + · rintro ⟨e,he,hi⟩ + exact ⟨_,⟨_,⟨e,he,rfl⟩,rfl⟩,hi⟩ + · rintro ⟨a,⟨l,⟨e,he,hel⟩,hla⟩,hai⟩ + subst l + subst a + exact ⟨e,he,hai⟩ + +include hB hes in +lemma arbitrary_bagTable : + List.Forall₂ List.Perm (bagTable ((matrixRep (reindex B (orderedIso V)),xs),es)) + (List.ofFn (fun i=>ExecutableDP.bagRep + (arbitraryNumberedBags B hsym htri xs left right (UnitRefresh.orderedEnum V i)))) := by + unfold bagTable + rw [matrixRep_length,ExecutableDP.map_range_ofFn] + apply List.forall₂_iff_get.mpr + refine ⟨by simp,?_⟩ + intro i hi _right_bound + have hh:=arbitrary_bag_perm B hB hsym htri xs left right es hes + (UnitRefresh.orderedEnum V ⟨i,by simpa using hi⟩) + simpa only [List.get_eq_getElem,List.getElem_ofFn,index,Equiv.symm_apply_apply] using hh +include hB hes in +lemma arbitrary_bagTable_length (H : ℕ) (h : xs.length=H) : + List.Forall₂ List.Perm (bagTable ((matrixRep (reindex B (orderedIso V)),xs),es)) + (List.ofFn (fun i=>ExecutableDP.bagRep + ((NumberedHierarchy.bags B hsym htri left right H (UnitRefresh.orderedEnum V i)).map + (UnitRefresh.orderedEnum (Label B H)).symm.toEmbedding))) := by + subst H + exact arbitrary_bagTable B hB hsym htri xs left right es hes + +include hB hes in +lemma arbitrary_bagTable_numbered (H : ℕ) (h : xs.length=H) : + List.Forall₂ List.Perm (bagTable ((matrixRep (reindex B (orderedIso V)),xs),es)) + (ExecutableDP.orderedRep (UnitRefresh.numberedBags + (NumberedHierarchy.bags B hsym htri left right H))) := + arbitrary_bagTable_length B hB hsym htri xs left right es hes H h + +include hB hes in +lemma arbitrary_bagTable_enumerated (H : ℕ) (h : xs.length=H) : + List.Forall₂ List.Perm + (bagTable ((matrixRep (fun i j=>B (UnitRefresh.orderedEnum V i) (UnitRefresh.orderedEnum V j)),xs),es)) + (ExecutableDP.orderedRep (UnitRefresh.numberedBags + (NumberedHierarchy.bags B hsym htri left right H))) := + arbitrary_bagTable_numbered B hB hsym htri xs left right es hes H h + +@[instance_reducible] def ordinaryLabelFintype (H : ℕ) : Fintype (Label B H) := inferInstance + +include hB hes in +lemma arbitrary_bagTable_fintype (H : ℕ) (h : xs.length=H) + (F : Fintype (Label B H)) : + letI := F + List.Forall₂ List.Perm + (bagTable ((matrixRep (fun i j=>B (UnitRefresh.orderedEnum V i) (UnitRefresh.orderedEnum V j)),xs),es)) + (ExecutableDP.orderedRep (UnitRefresh.numberedBags + (NumberedHierarchy.bags B hsym htri left right H))) := by + have hf : F=ordinaryLabelFintype B H := Subsingleton.elim _ _ + subst F + exact arbitrary_bagTable_enumerated B hB hsym htri xs left right es hes H h + +end MatchingFPRAS.ExecutableHierarchy + +end OAI diff --git a/lean/OAI/Combinatorics/MatchingCount/Graphs/TreeCycleTable.lean b/lean/OAI/Combinatorics/MatchingCount/Graphs/TreeCycleTable.lean new file mode 100644 index 0000000000000000000000000000000000000000..e1068d84c854a457d6da60c7ae945adf29fce6d5 --- /dev/null +++ b/lean/OAI/Combinatorics/MatchingCount/Graphs/TreeCycleTable.lean @@ -0,0 +1,105 @@ +import Mathlib +import OAI.Combinatorics.MatchingCount.Tapes.TreeSparseComponents +import OAI.Combinatorics.MatchingCount.Sampling.TreeOptionsFinite + +namespace OAI + +namespace MatchingFPRAS.TreeTyped.SparseProgram +open TreeTyped ExecutableOptions + +variable {E C : Type} [Codec E] [Codec C] [LinearOrder E] +attribute [local instance] Transport.Sparse.finsetOrder +abbrev PairState (E : Type) := Finset E×Finset E +abbrev CycleInput (C E : Type) := (C×Finset E)×PairState E + +def exchange (x : PairState E×Finset E) : Finset E := (x.1.1\x.2)∪(x.1.2∩x.2) +def exchangeRealizer (Eq : Realizer (fun x : E×E=>decide (x.1=x.2))) + (Le : Realizer (fun x : E×E=>decide (x.1≤x.2))) : Realizer (exchange (E:=E)) := + (composition (pair (composition (pair first.fst second) (finsetSDiff Eq)) + (composition (pair first.snd second) (finsetInter Eq))) (finsetUnion Eq Le)).congr (fun _=>rfl) +lemma polynomial_exchange {Eq : Realizer (fun x : E×E=>decide (x.1=x.2))} + {Le : Realizer (fun x : E×E=>decide (x.1≤x.2))} (hE : PolynomialTime Eq) (hL : PolynomialTime Le) : + PolynomialTime (exchangeRealizer Eq Le) := by + unfold exchangeRealizer Realizer.fst Realizer.snd + apply polynomial_congr + tree_cost + +def cycle (p : C×(E×E)→Bool) (x : CycleInput C E×Finset E) : PairState E := + if x.2∈allComponents (p:=p) (x.1.1,x.1.2.1∪x.1.2.2) then + (exchange (x.1.2,x.2),exchange ((x.1.2.2,x.1.2.1),x.2)) else x.1.2 + +def cycleRealizer {p : C×(E×E)→Bool} (P : Realizer p) + (Eq : Realizer (fun x : E×E=>decide (x.1=x.2))) + (Le : Realizer (fun x : E×E=>decide (x.1≤x.2))) : Realizer (cycle p) := + (choose (composition (pair second (composition (pair first.fst + (composition first.snd (finsetUnion Eq Le))) (allComponentsRealizer P Eq Le))) + (finsetMember (orderedSetEqual Eq))) + (pair (composition (pair first.snd second) (exchangeRealizer Eq Le)) + (composition (pair (pair first.snd.snd first.snd.fst) second) (exchangeRealizer Eq Le))) + first.snd).congr (by intro x; simp only [Function.comp_apply,decide_eq_true_eq,cycle]) +lemma polynomial_cycle {p : C×(E×E)→Bool} {P : Realizer p} + {Eq : Realizer (fun x : E×E=>decide (x.1=x.2))} + {Le : Realizer (fun x : E×E=>decide (x.1≤x.2))} + (hP : PolynomialTime P) (hE : PolynomialTime Eq) (hL : PolynomialTime Le) : + PolynomialTime (cycleRealizer P Eq Le) := by + unfold cycleRealizer Realizer.fst Realizer.snd + apply polynomial_congr + have := polynomial_allComponents hP hE hL + have := polynomial_orderedSetEqual hE + have := polynomial_exchange hE hL + tree_cost + +def cycleTable (p : C×(E×E)→Bool) (x : CycleInput C E) : Options (PairState E) := + if (discrepancies (p:=p) x).card=0 then pure x.2 else + ExecutableOptions.map (cycle p) (x,uniform (discrepancies (p:=p) x)) +def cycleTableRealizer {p : C×(E×E)→Bool} (P : Realizer p) + (Eq : Realizer (fun x : E×E=>decide (x.1=x.2))) + (Le : Realizer (fun x : E×E=>decide (x.1≤x.2))) : Realizer (cycleTable p) := + (choose (composition (pair (composition (discrepanciesRealizer P Eq Le) finsetCard) (constant 0)) natEqual) + (composition second pureRealizer) + (composition (pair identity (composition (discrepanciesRealizer P Eq Le) uniformRealizer)) + (mapRealizer (cycleRealizer P Eq Le)))).congr (by intro x; simp only [Function.comp_apply,decide_eq_true_eq,cycleTable,id_eq]) +lemma polynomial_cycleTable {p : C×(E×E)→Bool} {P : Realizer p} + {Eq : Realizer (fun x : E×E=>decide (x.1=x.2))} + {Le : Realizer (fun x : E×E=>decide (x.1≤x.2))} + (hP : PolynomialTime P) (hE : PolynomialTime Eq) (hL : PolynomialTime Le) : + PolynomialTime (cycleTableRealizer P Eq Le) := by + unfold cycleTableRealizer + apply polynomial_congr + have := polynomial_discrepancies hP hE hL + have := ExecutableOptions.polynomial_pure (A:=PairState E) + have := ExecutableOptions.polynomial_uniform (A:=Finset E) + have := ExecutableOptions.polynomial_map (polynomial_cycle hP hE hL) + tree_cost + +variable [Fintype E] {V : Type} [Fintype V] [DecidableEq V] +variable (ends : E→Sym2 V) (p : C×(E×E)→Bool) (c : C) +variable (hp : ∀ a b,p (c,(a,b))=decide (∃ v,v∈ends a ∧ v∈ends b)) +def pairRepr (a : Transport.PM (fun e v=>v∈ends e)×Transport.PM (fun e v=>v∈ends e)) : PairState E := + (a.1.val,a.2.val) +omit [Codec E] [Codec C] in +include hp in +lemma cycle_eq (a : Transport.PM (fun e v=>v∈ends e)×Transport.PM (fun e v=>v∈ends e)) (s : Finset E) : + cycle p (((c,Finset.univ),pairRepr ends a),s)=pairRepr ends (Transport.Sparse.cycle ends a s) := by + unfold cycle pairRepr + rw [allComponents_eq ends c hp] + unfold Transport.Sparse.cycle + split_ifs <;> rfl +omit [Codec E] [Codec C] in +include hp in +lemma cycleTable_eq (a : Transport.PM (fun e v=>v∈ends e)×Transport.PM (fun e v=>v∈ends e)) : + cycleTable p ((c,Finset.univ),pairRepr ends a)=repr (pairRepr ends) (Transport.Sparse.cycleTable ends a) := by + unfold cycleTable + rw [show discrepancies (p:=p) ((c,Finset.univ),pairRepr ends a)=Transport.Sparse.discrepancies ends a.1 a.2 from + discrepancies_eq ends c hp a.1 a.2] + unfold Transport.Sparse.cycleTable + split_ifs with h hn hn + · exact False.elim (Finset.card_pos.mpr hn |>.ne' h) + · exact pure_repr _ _ + · rw [uniform_repr _ hn] + exact map_repr id (pairRepr ends) _ _ ((c,Finset.univ),pairRepr ends a) (cycle_eq ends p c hp a) _ + · exfalso + exact h (Finset.card_eq_zero.mpr (Finset.not_nonempty_iff_eq_empty.mp hn)) +end MatchingFPRAS.TreeTyped.SparseProgram + +end OAI diff --git a/lean/OAI/Combinatorics/MatchingCount/Graphs/TreeGeometry.lean b/lean/OAI/Combinatorics/MatchingCount/Graphs/TreeGeometry.lean new file mode 100644 index 0000000000000000000000000000000000000000..fbb89c4bda8162845d00476b416c5fbb88fa3364 --- /dev/null +++ b/lean/OAI/Combinatorics/MatchingCount/Graphs/TreeGeometry.lean @@ -0,0 +1,179 @@ +import Mathlib +import OAI.Combinatorics.MatchingCount.Complexity.TreePolynomialGrid +import OAI.Combinatorics.MatchingCount.Machines.TreeQuad +import OAI.Combinatorics.MatchingCount.Machines.TreeSum + +namespace OAI + +namespace MatchingFPRAS.ExecutableSource +open TreeTyped Polynomial Enlargement RealGeometry + +abbrev RawLogical := ℕ×ℕ +abbrev RawReal := RawLogical×ℕ +abbrev RawVertex := ℕ⊕RawReal +abbrev GeometryInput := List ℕ×List Bool + +def logicalEdges (vs : List ℕ) : List RawLogical := + (vs.product vs).filter (fun e=>decide (e.1rfl) +lemma polynomial_logicalEdges : PolynomialTime logicalEdgesRealizer := by + unfold logicalEdgesRealizer + apply polynomial_congr + exact polynomial_composition (polynomial_composition + (polynomial_pair polynomial_identity polynomial_identity) polynomial_listProduct) + (polynomial_filter polynomial_less) + +def internalCount (x : GeometryInput) : ℕ := 4*x.2.length +def internalCountRealizer : Realizer internalCount := + (composition (pair (constant 4) (composition second listLength)) multiply).congr (fun _=>rfl) +lemma polynomial_internalCount : PolynomialTime internalCountRealizer := by + unfold internalCountRealizer; apply polynomial_congr; tree_cost +lemma internalCount_bound (x : GeometryInput) : internalCount x≤(4*X).eval (weight x) := by + have h: x.2.length≤weight x := (list_length_le_weight x.2).trans (weight_snd x) + simpa [internalCount] using Nat.mul_le_mul_left 4 h + +def realEdges (x : GeometryInput) : List RawReal := + (logicalEdges x.1).product (List.range (internalCount x+1)) +def realEdgesRealizer : Realizer realEdges := (composition + (pair (composition first logicalEdgesRealizer) + (composition (composition internalCountRealizer successor) range)) listProduct).congr (fun _=>rfl) +lemma polynomial_realEdges : PolynomialTime realEdgesRealizer := by + have hr:PolynomialTime (composition (composition internalCountRealizer successor) range) := by + apply polynomial_boundedRange (polynomial_composition polynomial_internalCount polynomial_successor) (4*X+1) + intro x + simp only [eval_add,eval_mul,eval_ofNat,eval_X,eval_one,Function.comp_apply] + have h:=internalCount_bound x + simpa only [eval_mul,eval_ofNat,eval_X] using Nat.add_le_add_right h 1 + unfold realEdgesRealizer + apply polynomial_congr + exact polynomial_composition (polynomial_pair + (polynomial_composition polynomial_first polynomial_logicalEdges) hr) polynomial_listProduct + +def vertices (x : GeometryInput) : List RawVertex := + x.1.map Sum.inl ++ ((logicalEdges x.1).product (List.range (internalCount x))).map Sum.inr +def verticesRealizer : Realizer vertices := (composition (pair + (composition first (map inl)) + (composition (composition (pair (composition first logicalEdgesRealizer) + (composition internalCountRealizer range)) listProduct) (map inr))) append).congr (fun _=>rfl) +lemma polynomial_vertices : PolynomialTime verticesRealizer := by + have hr:=polynomial_boundedRange polynomial_internalCount (4*X) internalCount_bound + unfold verticesRealizer + apply polynomial_congr + have := polynomial_logicalEdges + have := polynomial_listProduct (A:=RawLogical) (B:=ℕ) + have := polynomial_inl (A:=ℕ) (B:=RawReal) + have := polynomial_inr (A:=ℕ) (B:=RawReal) + have := polynomial_successor + have := polynomial_predecessor + tree_cost + +def position (x : ℕ×RawReal) : RawVertex := + if x.2.2=0 then .inl x.2.1.1 + else if x.2.2=x.1+1 then .inl x.2.1.2 + else .inr (x.2.1,x.2.2-1) +def atRealizer : Realizer position := + (choose (composition (pair second.snd (constant 0)) natEqual) + (composition second.fst.fst inl) + (choose (composition (pair second.snd (composition first successor)) natEqual) + (composition second.fst.snd inl) + (composition (pair second.fst (composition second.snd predecessor)) inr))).congr (by + intro x; simp [position]) +lemma polynomial_at : PolynomialTime atRealizer := by + unfold atRealizer Realizer.fst Realizer.snd + apply polynomial_congr + have := polynomial_inl (A:=ℕ) (B:=RawReal) + have := polynomial_inr (A:=ℕ) (B:=RawReal) + have := polynomial_successor + have := polynomial_predecessor + tree_cost + +def left (x : GeometryInput×RawReal) : RawVertex := position (internalCount x.1,x.2) +def right (x : GeometryInput×RawReal) : RawVertex := position (internalCount x.1,(x.2.1,x.2.2+1)) +def leftRealizer : Realizer left := (composition (pair (composition first internalCountRealizer) second) atRealizer).congr (fun _=>rfl) +def rightRealizer : Realizer right := (composition (pair (composition first internalCountRealizer) + (pair second.fst (composition second.snd successor))) atRealizer).congr (fun _=>rfl) +lemma polynomial_left : PolynomialTime leftRealizer := by + unfold leftRealizer + apply polynomial_congr + exact polynomial_composition (polynomial_pair (polynomial_composition polynomial_first polynomial_internalCount) + polynomial_second) polynomial_at +lemma polynomial_right : PolynomialTime rightRealizer := by + unfold rightRealizer Realizer.fst Realizer.snd + apply polynomial_congr + have := polynomial_successor + have := polynomial_internalCount + have := polynomial_at + tree_cost + +variable {n m : ℕ} +def logicalRepr (e : LogicalEdge (Fin n)) : RawLogical := (e.val.1.val,e.val.2.val) +def realRepr (e : LogicalEdge (Fin n)×Fin (m+1)) : RawReal := (logicalRepr e.1,e.2.val) +def vertexRepr : Vertex (Fin n) (LogicalEdge (Fin n)) m→RawVertex + | .inl v => .inl v.val + | .inr (e,i) => .inr (logicalRepr e,i.val) +lemma logicalRepr_injective : Function.Injective (logicalRepr (n:=n)) := by + intro a b h + apply Subtype.ext + exact Prod.ext (Fin.ext (congrArg Prod.fst h)) (Fin.ext (congrArg Prod.snd h)) +lemma vertexRepr_injective : Function.Injective (vertexRepr (n:=n) (m:=m)) := by + intro a b h + cases a with + | inl a => cases b with + | inl b => exact congrArg Sum.inl (Fin.ext (Sum.inl.inj h)) + | inr b => cases h + | inr a => cases b with + | inl b => cases h + | inr b => + have h':(logicalRepr a.1,a.2.val)=(logicalRepr b.1,b.2.val):=Sum.inr.inj h + exact congrArg Sum.inr (Prod.ext (logicalRepr_injective (congrArg Prod.fst h')) + (Fin.ext (congrArg Prod.snd h'))) +lemma at_repr (e : LogicalEdge (Fin n)) (i : Fin (m+2)) : + position (m,(logicalRepr e,i.val))=vertexRepr (atVertex source target m e i) := by + unfold position atVertex + split_ifs <;> rfl +lemma left_repr (vs : List ℕ) (fuel : List Bool) (e : LogicalEdge (Fin n)×Fin (4*fuel.length+1)) : + left ((vs,fuel),realRepr e)=vertexRepr (atVertex source target (4*fuel.length) e.1 e.2.castSucc) := by + exact at_repr e.1 e.2.castSucc +lemma right_repr (vs : List ℕ) (fuel : List Bool) (e : LogicalEdge (Fin n)×Fin (4*fuel.length+1)) : + right ((vs,fuel),realRepr e)=vertexRepr (atVertex source target (4*fuel.length) e.1 e.2.succ) := by + exact at_repr e.1 e.2.succ + +lemma mem_logicalEdges (vs : List ℕ) (e : RawLogical) : + e∈logicalEdges vs ↔ e.1∈vs ∧ e.2∈vs ∧ e.1 simp only [vertices,List.mem_append,List.mem_map]; exact Or.inl ⟨v.val,List.mem_range.mpr v.isLt,rfl⟩ + | inr q => + apply List.mem_append_right + apply List.mem_map.mpr + exact ⟨(logicalRepr q.1,q.2.val),List.mem_product.mpr ⟨logicalRepr_mem q.1,List.mem_range.mpr q.2.isLt⟩,rfl⟩ +lemma vertices_complete (fuel : List Bool) (v : RawVertex) (h : v∈vertices (List.range n,fuel)) : + ∃ a : Vertex (Fin n) (LogicalEdge (Fin n)) (4*fuel.length),vertexRepr a=v := by + simp only [vertices,List.mem_append,List.mem_map] at h + rcases h with ⟨i,hi,rfl⟩|⟨⟨e,i⟩,hi,rfl⟩ + · exact ⟨.inl ⟨i,List.mem_range.mp hi⟩,rfl⟩ + · obtain ⟨he,hj⟩:=List.mem_product.mp hi + obtain ⟨a,rfl⟩:=logicalEdges_complete e he + exact ⟨.inr (a,⟨i,List.mem_range.mp hj⟩),rfl⟩ +lemma realRepr_mem (fuel : List Bool) (e : LogicalEdge (Fin n)×Fin (4*fuel.length+1)) : + realRepr e∈realEdges (List.range n,fuel) := by + exact List.mem_product.mpr ⟨logicalRepr_mem e.1,List.mem_range.mpr e.2.isLt⟩ +lemma realEdges_complete (fuel : List Bool) (e : RawReal) (h : e∈realEdges (List.range n,fuel)) : + ∃ a : LogicalEdge (Fin n)×Fin (4*fuel.length+1),realRepr a=e := by + obtain ⟨he,hi⟩:=List.mem_product.mp h + obtain ⟨a,ha⟩:=logicalEdges_complete e.1 he + exact ⟨(a,⟨e.2,List.mem_range.mp hi⟩),Prod.ext ha rfl⟩ +end MatchingFPRAS.ExecutableSource + +end OAI diff --git a/lean/OAI/Combinatorics/MatchingCount/Graphs/TreeHeight.lean b/lean/OAI/Combinatorics/MatchingCount/Graphs/TreeHeight.lean new file mode 100644 index 0000000000000000000000000000000000000000..80820ef0b3050dd3cdece34853a0f4af7fd9a180 --- /dev/null +++ b/lean/OAI/Combinatorics/MatchingCount/Graphs/TreeHeight.lean @@ -0,0 +1,100 @@ +import Mathlib +import OAI.Combinatorics.MatchingCount.Graphs.TreeBagBuild + +namespace OAI + +namespace MatchingFPRAS.ExecutableSource +open TreeTyped TreeFraction ExecutableBottleneck ExecutableHierarchy Enlargement RealGeometry + +lemma logicalB_nonneg {n : ℕ} (w : Fin n→Fin n→ℚ) (a b : Fin n) : + 0≤RationalSource.logicalB w a b := + (by norm_num : (0:ℚ)≤1).trans (BottleneckAlgorithm.close_one w _ a b) +lemma sourceHeight_nonneg {n : ℕ} [Nontrivial (Fin n)] (hn : 2≤n) + (w : Fin n→Fin n→ℚ) (a : Fin n) : 0≤RationalSource.height w a := by + obtain ⟨b,hb⟩:=Counting.others_nonempty hn a + exact (logicalB_nonneg w a b).trans (Finset.le_sup' _ hb) +lemma sourceMaxHeight_nonneg {n : ℕ} [Nontrivial (Fin n)] (hn : 2≤n) + (w : Fin n→Fin n→ℚ) : 0≤RationalSource.maxHeight w := by + exact (sourceHeight_nonneg hn w ⟨0,by omega⟩).trans (Finset.le_sup' _ (Finset.mem_univ _)) + +lemma maxHeight_source {n : ℕ} [Nontrivial (Fin n)] (hn : 2≤n) + (w : Fin n→Fin n→ℚ) (hw : ∀ a b,0≤w a b) : + maxHeight (close (matrixRep w))=TreeFraction.repr (RationalSource.maxHeight w) := by + rw [close_matrixRep w hw] + have hc : BottleneckAlgorithm.close w n=RationalSource.logicalB w := by + simp only [RationalSource.logicalB,Fintype.card_fin] + rw [hc] + unfold maxHeight + have he : (List.range (matrixRep (RationalSource.logicalB w)).length).map + (fun i=>height (matrixRep (RationalSource.logicalB w),i))= + (List.ofFn (RationalSource.height w)).map TreeFraction.repr := by + rw [matrixRep_length,ExecutableDP.map_range_ofFn,List.map_ofFn] + congr 1 + funext i + exact height_rep hn _ (logicalB_nonneg w) i + rw [he] + change ((List.ofFn (RationalSource.height w)).map TreeFraction.repr).foldl _ (TreeFraction.repr 0)=_ + rw [maximum_fold_repr _ 0 le_rfl (by + intro x hx + obtain ⟨a,rfl⟩:=List.mem_ofFn.mp hx + exact sourceHeight_nonneg hn w a)] + rw [fold_max_ofFn _ 0 ⟨0,by omega⟩] + congr 1 + exact max_eq_right (sourceMaxHeight_nonneg hn w) + +def hierarchyFuel (x : Matrix×List Bool) : List Bool := + x.2.take (ExecutableHierarchy.level (x.2.length,maxHeight (close x.1))) +def hierarchyFuelRealizer : Realizer hierarchyFuel := (composition + (pair second (composition (pair (composition second listLength) + (composition (composition first closeRealizer) maxHeightRealizer)) levelRealizer)) takeFast).congr (fun _=>rfl) +lemma polynomial_hierarchyFuel : PolynomialTime hierarchyFuelRealizer := by + unfold hierarchyFuelRealizer + apply polynomial_congr + have := polynomial_close + have := polynomial_maxHeight + have := polynomial_level + have := polynomial_takeFast (A:=Bool) + tree_cost +lemma hierarchyFuel_source {n : ℕ} [Nontrivial (Fin n)] (hn : 2≤n) + (w : Fin n→Fin n→ℚ) (hw : ∀ a b,0≤w a b) (K : ℕ) : + hierarchyFuel (matrixRep w,List.replicate (2*K) false)= + List.replicate (RationalSource.levels w K) false := by + unfold hierarchyFuel + dsimp only + rw [maxHeight_source hn w hw,List.length_replicate,level_repr _ _ (sourceMaxHeight_nonneg hn w)] + rw [List.take_replicate] + congr 1 + exact min_eq_left (Nat.findGreatest_le _) + +def setupBags (x : BagBuildInput) : ExecutableDP.Bags := + buildBags (x.1,hierarchyFuel (x.1.1.1,x.2)) +def setupBagsRealizer : Realizer setupBags := (composition + (pair first (composition (pair first.fst.fst second) hierarchyFuelRealizer)) buildBagsRealizer).congr (fun _=>rfl) +lemma polynomial_setupBags : PolynomialTime setupBagsRealizer := by + unfold setupBagsRealizer + apply polynomial_congr + have := polynomial_hierarchyFuel + have := polynomial_buildBags + dsimp only [Realizer.fst,Realizer.snd] + tree_cost + +attribute [local instance] NumberedHierarchy.labelOrder +lemma setupBags_source {n : ℕ} [Nontrivial (Fin n)] (hn : 2≤n) + (w : Fin n→Fin n→ℚ) (hw : ∀ i j,0≤w i j) (K : ℕ) : + List.Forall₂ List.Perm + (setupBags (((matrixRep w,List.replicate (2*K+2) false),List.range n),List.replicate (2*K) false)) + (ExecutableDP.orderedRep (UnitRefresh.numberedBags (RationalSource.bags w K))) := by + unfold setupBags + dsimp only + rw [hierarchyFuel_source hn w hw K] + exact buildBags_source hn w hw K + +theorem setupBags_post : ∃ p : Polynomial ℕ,∀ x : BagBuildInput,∀ t : ℕ, + p.eval (TreePost.packed x).length≤t → ∀ coins : Fin t→Bool, + (run (TreePost.machine setupBagsRealizer.program) (TreePost.packed x) coins).state=none ∧ + (run (TreePost.machine setupBagsRealizer.program) (TreePost.packed x) coins).tape.right₀= + Turing.ListBlank.mk (TreePost.packed (setupBags x)) := + TreePost.polynomial_compiles setupBagsRealizer polynomial_setupBags +end MatchingFPRAS.ExecutableSource + +end OAI diff --git a/lean/OAI/Combinatorics/MatchingCount/Graphs/TreeHierarchyReindex.lean b/lean/OAI/Combinatorics/MatchingCount/Graphs/TreeHierarchyReindex.lean new file mode 100644 index 0000000000000000000000000000000000000000..27b24ba5fcea955ee66c5cfa87499eff3c798fec --- /dev/null +++ b/lean/OAI/Combinatorics/MatchingCount/Graphs/TreeHierarchyReindex.lean @@ -0,0 +1,100 @@ +import Mathlib +import OAI.Combinatorics.MatchingCount.Graphs.LabelOrder +import OAI.Combinatorics.MatchingCount.Tapes.TreeNumberedCodec + +namespace OAI + +namespace MatchingFPRAS.TreeTyped.Numbered +variable {A B : Type} [Fintype A] [Fintype B] [LinearOrder A] [LinearOrder B] +def orderedIso (A : Type) [Fintype A] [LinearOrder A] : Fin (Fintype.card A)≃o A where + toEquiv:=UnitRefresh.orderedEnum A + map_rel_iff' := by intro a b; rw [←not_lt,←not_lt,UnitRefresh.orderedEnum_lt] +lemma index_orderIso (e : A≃o B) (a : A) : index (e a)=index a := by + let h := Fintype.card_congr e.toEquiv + have he : (orderedIso A).trans e=(Fin.castOrderIso h).trans (orderedIso B) := Subsingleton.elim _ _ + have hh:=congrArg (fun f : Fin (Fintype.card A)≃o B=> + ((UnitRefresh.orderedEnum B).symm (f ((UnitRefresh.orderedEnum A).symm a))).val) he + change ((UnitRefresh.orderedEnum B).symm + (e (UnitRefresh.orderedEnum A ((UnitRefresh.orderedEnum A).symm a)))).val= + ((UnitRefresh.orderedEnum B).symm + (UnitRefresh.orderedEnum B (Fin.cast h ((UnitRefresh.orderedEnum A).symm a)))).val at hh + simpa only [Equiv.apply_symm_apply,Equiv.symm_apply_apply,Fin.val_cast,index] using hh +end MatchingFPRAS.TreeTyped.Numbered + +namespace MatchingFPRAS.NumberedHierarchy +open Finset + +variable {V W : Type} [Fintype V] [Fintype W] [LinearOrder V] [LinearOrder W] +variable (B : W→W→ℚ) (e : V≃o W) +abbrev reindex : V→V→ℚ := fun i j=>B (e i) (e j) +lemma component_reindex (t : ℚ) (x y : V) : + y∈component (reindex B e) t x ↔ e y∈component B t (e x) := by + simp only [component,mem_filter,mem_univ,true_and,related,reindex,e.injective.eq_iff] +lemma root_reindex (t : ℚ) (x : V) : e (root (reindex B e) t x)=root B t (e x) := by + apply le_antisymm + · have hm : e.symm (root B t (e x)) ∈ component (reindex B e) t x := by + rw [component_reindex,OrderIso.apply_symm_apply] + exact root_mem B t (e x) + have hle := Finset.min'_le (component (reindex B e) t x) _ hm + have hh:=e.monotone hle + simpa only [OrderIso.apply_symm_apply,root] using hh + · exact Finset.min'_le (component B t (e x)) _ + ((component_reindex B e t x _).mp (root_mem (reindex B e) t x)) + +def componentReindex (t : ℚ) : NumberedComponent (reindex B e) t≃NumberedComponent B t where + toFun x:=⟨e x.val,by rw [←root_reindex B e t x.val,x.property]⟩ + invFun x:=⟨e.symm x.val,by + apply e.injective + rw [root_reindex,OrderIso.apply_symm_apply,x.property]⟩ + left_inv x:=Subtype.ext (e.symm_apply_apply x.val) + right_inv x:=Subtype.ext (e.apply_symm_apply x.val) +def labelReindex (H : ℕ) : Label (reindex B e) H≃Label B H := + Equiv.sigmaCongrRight (fun k=>componentReindex B e ((2:ℚ)^k.val)) + +attribute [local instance] labelOrder +local instance (priority := 2000) {U : Type} [Fintype U] [LinearOrder U] {H : ℕ} + (C : U→U→ℚ) : LE (Label C H) := (labelOrder C H).toLE + +def labelOrderReindex (H : ℕ) : Label (reindex B e) H≃o Label B H where + toEquiv:=labelReindex B e H + map_rel_iff' := by + intro a b + change toLex (a.1,e a.2.val)≤toLex (b.1,e b.2.val) ↔ + toLex (a.1,a.2.val)≤toLex (b.1,b.2.val) + simp only [Prod.Lex.le_iff,ofLex_toLex,e.le_iff_le] + +lemma labelReindex_index (H : ℕ) (l : Label (reindex B e) H) : + TreeTyped.Numbered.index (labelReindex B e H l)=TreeTyped.Numbered.index l := + TreeTyped.Numbered.index_orderIso (labelOrderReindex B e H) l + +open Finset + +variable {V W : Type} [Fintype V] [Fintype W] [LinearOrder V] [LinearOrder W] +variable (B : W→W→ℚ) (e : V≃o W) +variable (hsym : ∀ a b,B a b=B b a) +variable (htri : ∀ x y z,x≠y → x≠z → y≠z → min (B x z) (B z y)≤B x y) +omit [Fintype V] [Fintype W] in +include hsym in +lemma reindex_symm : ∀ a b,reindex B e a b=reindex B e b a := fun a b=>hsym (e a) (e b) +omit [Fintype V] [Fintype W] in +include htri in +lemma reindex_tri : ∀ x y z,x≠y → x≠z → y≠z → + min (reindex B e x z) (reindex B e z y)≤reindex B e x y := + fun x y z hxy hxz hyz=>htri (e x) (e y) (e z) (e.injective.ne hxy) (e.injective.ne hxz) (e.injective.ne hyz) +lemma labelAt_reindex {H : ℕ} (k : Fin (H+1)) (x : V) : + labelReindex B e H (labelAt (reindex B e) (reindex_symm B e hsym) + (reindex_tri B e htri) k x)=labelAt B hsym htri k (e x) := by + apply congrArg (Sigma.mk k) + apply Subtype.ext + exact root_reindex B e _ x +lemma edgeLabel_reindex {E : Type} [Fintype E] [DecidableEq E] + (left right : E→W) (H : ℕ) (a : E) : + labelReindex B e H (edgeLabel (reindex B e) (reindex_symm B e hsym) + (reindex_tri B e htri) (e.symm ∘ left) (e.symm ∘ right) H a)= + edgeLabel B hsym htri left right H a := by + unfold edgeLabel + simp only [reindex,Function.comp_apply,OrderIso.apply_symm_apply] + rw [labelAt_reindex,OrderIso.apply_symm_apply] +end MatchingFPRAS.NumberedHierarchy + +end OAI diff --git a/lean/OAI/Combinatorics/MatchingCount/Graphs/TreeHierarchyRoot.lean b/lean/OAI/Combinatorics/MatchingCount/Graphs/TreeHierarchyRoot.lean new file mode 100644 index 0000000000000000000000000000000000000000..801ca4efbe2b33da11ba51a8942524b4582306d0 --- /dev/null +++ b/lean/OAI/Combinatorics/MatchingCount/Graphs/TreeHierarchyRoot.lean @@ -0,0 +1,87 @@ +import Mathlib +import OAI.Combinatorics.MatchingCount.Graphs.Related2 +import OAI.Combinatorics.MatchingCount.Machines.TreeBottleneckCorrect +import OAI.Combinatorics.MatchingCount.Complexity.TreeCostTactic + +namespace OAI + +namespace MatchingFPRAS.ExecutableHierarchy +open TreeTyped TreeFraction ExecutableBottleneck Polynomial + +abbrev RootInput := (Matrix×Fraction)×ℕ + +def related (x : RootInput×ℕ) : Bool := + decide (x.1.2=x.2) || !(TreeFraction.less (cell (x.1.1.1,(x.1.2,x.2)),x.1.1.2)) +def relatedRealizer : Realizer related := + composition (pair (composition (pair first.snd second) natEqual) + (composition (composition (pair + (composition (pair first.fst.fst (pair first.snd second)) cellRealizer) first.fst.snd) + lessRealizer) boolNot)) boolOr +lemma polynomial_related : PolynomialTime relatedRealizer := by + unfold relatedRealizer Realizer.fst Realizer.snd + have hc:=polynomial_cell + have hl:=TreeFraction.polynomial_less + apply polynomial_composition _ polynomial_boolOr + apply polynomial_pair + · apply polynomial_composition _ polynomial_natEqual + tree_cost + · apply polynomial_composition _ polynomial_boolNot + apply polynomial_composition _ hl + apply polynomial_pair + · apply polynomial_composition _ hc + tree_cost + · tree_cost + +def component (x : RootInput) : List ℕ := (List.range x.1.1.length).filter (fun y=>related (x,y)) +def componentRealizer : Realizer component := composition + (pair identity (composition (composition first.fst listLength) range)) (filterWith relatedRealizer) +lemma polynomial_component : PolynomialTime componentRealizer := by + have hr : PolynomialTime (composition (composition (first (A:=Matrix×Fraction) (B:=ℕ)).fst listLength) range) := by + apply polynomial_boundedRange (by unfold Realizer.fst; tree_cost) X + intro x + simpa using (list_length_le_weight x.1.1).trans ((weight_fst x.1).trans (weight_fst x)) + unfold componentRealizer + have:=polynomial_related + apply polynomial_composition _ (polynomial_filterWith this) + exact polynomial_pair polynomial_identity hr + +def root (x : RootInput) : ℕ := listMin (component x,x.1.1.length) +def rootRealizer : Realizer root := composition (pair componentRealizer + (composition first.fst listLength)) listMinRealizer +lemma polynomial_root : PolynomialTime rootRealizer := by + unfold rootRealizer + apply polynomial_composition _ polynomial_listMin + exact polynomial_pair polynomial_component (polynomial_composition (polynomial_fst polynomial_first) polynomial_listLength) + +lemma related_matrixRep {n : ℕ} (B : Fin n→Fin n→ℚ) (hB : ∀ a b,0≤B a b) + (t : ℚ) (ht : 0≤t) (a b : Fin n) : + related (((matrixRep B,TreeFraction.repr t),a.val),b.val)=decide (NumberedHierarchy.related B t a b) := by + unfold related NumberedHierarchy.related + rw [cell_matrixRep,TreeFraction.less_val _ _ (B a b).pos t.pos, + TreeFraction.val_repr (hB a b),TreeFraction.val_repr ht] + apply Bool.eq_iff_iff.mpr + simp [Fin.ext_iff,not_lt] +lemma component_mem_matrixRep {n : ℕ} (B : Fin n→Fin n→ℚ) (hB : ∀ a b,0≤B a b) + (t : ℚ) (ht : 0≤t) (a b : Fin n) : + b.val∈component ((matrixRep B,TreeFraction.repr t),a.val) ↔ b∈NumberedHierarchy.component B t a := by + simp only [component,List.mem_filter,List.mem_range,matrixRep_length, + related_matrixRep B hB t ht,decide_eq_true_eq,NumberedHierarchy.component, + Finset.mem_filter,Finset.mem_univ,true_and] + exact and_iff_right b.isLt +lemma root_matrixRep {n : ℕ} (B : Fin n→Fin n→ℚ) (hB : ∀ a b,0≤B a b) + (t : ℚ) (ht : 0≤t) (a : Fin n) : + root ((matrixRep B,TreeFraction.repr t),a.val)=(NumberedHierarchy.root B t a).val := by + apply le_antisymm + · apply listMin_le + exact (component_mem_matrixRep B hB t ht a _).mpr (NumberedHierarchy.root_mem B t a) + · unfold root + apply le_listMin (by rw [matrixRep_length]; exact Nat.le_of_lt (NumberedHierarchy.root B t a).isLt) + intro v hv + have hvlt : v([] : List Bool))) +def initialRealizer : Realizer initial := (composition + (pair identity (composition second.fst.fst (map (constant ([] : List Bool))))) + refreshRealizer).congr (fun _=>rfl) +lemma polynomial_initial : PolynomialTime initialRealizer := by + unfold initialRealizer + apply polynomial_congr + dsimp only [Realizer.fst, Realizer.snd] + have := polynomial_refresh + tree_cost + +attribute [local instance] Transport.sym2Order Transport.bagEdgeOrder Transport.bagEdgeFintype +variable {V L : Type} [Fintype V] [LinearOrder V] [Fintype L] [LinearOrder L] +lemma initial_valid (bags : V→Finset L) (rank : L→ℕ) (parent : L→Option L) + (hb : RankedBags bags rank parent) (hne : ∀ v,(bags v).Nonempty) + (hp : ∀ l p,parent l=some p → rank pFin.elim0 i + refine ⟨sampleMatching 0 bags rank parent hb hne hp M bits,?_⟩ + unfold initial + have haLen : a.length=Fintype.card V := by + simpa only [orderedRep,List.length_ofFn] using ha.length_eq + have he : a.map (fun _=>([] : List Bool))=List.ofFn (fun i=>List.ofFn (bits i)) := by + simp only [List.map_const',List.ofFn_zero] + rw [haLen] + exact (List.ofFn_const _ _).symm + dsimp only + rw [he] + exact refresh_sampleMatching bags rank parent hb hne hp M a ha bits + +open TreePost Turing + +theorem initial_post : ∃ p : Polynomial ℕ,∀ x : InitialInput,∀ t : ℕ, + p.eval (packed x).length≤t → ∀ coins : Fin t→Bool, + (run (machine initialRealizer.program) (packed x) coins).state=none ∧ + (run (machine initialRealizer.program) (packed x) coins).tape.right₀= + ListBlank.mk (packed (initial x)) := + polynomial_compiles initialRealizer polynomial_initial +end MatchingFPRAS.ExecutableRefresh + +end OAI diff --git a/lean/OAI/Combinatorics/MatchingCount/Graphs/TreeMatchingCheck.lean b/lean/OAI/Combinatorics/MatchingCount/Graphs/TreeMatchingCheck.lean new file mode 100644 index 0000000000000000000000000000000000000000..877c753482793f8382461be8fc5dfa078bc90b6e --- /dev/null +++ b/lean/OAI/Combinatorics/MatchingCount/Graphs/TreeMatchingCheck.lean @@ -0,0 +1,50 @@ +import Mathlib +import OAI.Combinatorics.MatchingCount.Complexity.TreeCostTactic + +namespace OAI + +namespace MatchingFPRAS.TreeTyped.SparseProgram +open TreeTyped + +variable {E V C : Type} [Codec E] [Codec V] [Codec C] [LinearOrder E] [LinearOrder V] + +def matchingCheck (p : C×(E×V)→Bool) (x : (C×Finset V)×Finset E) : Bool := + decide (∀ v∈x.1.2,(x.2.filter (fun e=>p (x.1.1,(e,v))=true)).card=1) +def matchingCheckRealizer {p : C×(E×V)→Bool} (P : Realizer p) : + Realizer (matchingCheck p) := by + let incident : Realizer (fun x : (C×V)×E=>p (x.1.1,(x.2,x.1.2))) := + composition (pair first.fst (pair second first.snd)) P + let degree : Realizer (fun x : (C×Finset E)×V=> + (x.1.2.filter (fun e=>p (x.1.1,(e,x.2))=true)).card) := + (composition (composition (pair (pair first.fst second) first.snd) + (finsetFilterWith incident)) finsetCard).congr (fun _=>rfl) + exact (composition (pair (pair first.fst second) first.snd) + (finsetAll (composition (pair degree (constant 1)) natEqual))).congr (by + intro x; simp only [Function.comp_apply,decide_eq_true_eq]; rfl) +lemma polynomial_matchingCheck {p : C×(E×V)→Bool} {P : Realizer p} (hP : PolynomialTime P) : + PolynomialTime (matchingCheckRealizer P) := by + unfold matchingCheckRealizer + dsimp only [Realizer.fst,Realizer.snd] + apply polynomial_congr + tree_cost + +instance decideMatchingOn [Fintype E] [Fintype V] (inc : E→V→Prop) [DecidableRel inc] (M : Finset E) : + Decidable (Transport.MatchingOn inc M Finset.univ) := by + unfold Transport.MatchingOn ExistsUnique + infer_instance + +omit [Codec E] [Codec V] [Codec C] in +lemma matchingCheck_eq [Fintype E] [Fintype V] (p : C×(E×V)→Bool) (c : C) (inc : E→V→Prop) + [DecidableRel inc] (hp : ∀ e v,p (c,(e,v))=decide (inc e v)) (M : Finset E) : + matchingCheck p ((c,Finset.univ),M)=decide (Transport.MatchingOn inc M Finset.univ) := by + apply Bool.eq_iff_iff.mpr + simp only [matchingCheck,decide_eq_true_eq,Finset.mem_univ,forall_const,hp] + unfold Transport.MatchingOn + simp only [Finset.mem_univ,implies_true,true_and] + apply forall_congr' + intro v + rw [Finset.card_eq_one_iff_existsUnique] + simp +end MatchingFPRAS.TreeTyped.SparseProgram + +end OAI diff --git a/lean/OAI/Combinatorics/MatchingCount/Graphs/TreeProfile.lean b/lean/OAI/Combinatorics/MatchingCount/Graphs/TreeProfile.lean new file mode 100644 index 0000000000000000000000000000000000000000..af59da87824c95af3b2bd3304e61e3512904a8cf --- /dev/null +++ b/lean/OAI/Combinatorics/MatchingCount/Graphs/TreeProfile.lean @@ -0,0 +1,95 @@ +import Mathlib +import OAI.Combinatorics.MatchingCount.Sampling.TreeDPCount +import OAI.Combinatorics.MatchingCount.Algorithm.TreeScalingCorrect + +namespace OAI + +namespace MatchingFPRAS.ExecutableSource +open TreeTyped TreeFraction ExecutableBottleneck ExecutableHierarchy Polynomial + +abbrev ProfileData := List Bool×(Fraction×(Fraction×(Fraction×Fraction))) +def profile (x : ProfileData×ℕ) : Fraction := + let p:=x.1.1.length + let v:=x.1.2 + if x.2<2*p then maximum (v.1,div (v.2.1,threshold (x.1.1++x.1.1,x.2/2))) + else if x.2=2*p then v.2.2.2 + else maximum (v.1,div (v.2.2.1,threshold (x.1.1++x.1.1,(4*p-x.2)/2))) +def profileRealizer : Realizer profile := by + let p : Realizer (fun x : ProfileData×ℕ=>x.1.1.length) := composition first.fst listLength + let twoP := composition (pair (constant 2) p) multiply + let fourP := composition (pair (constant 4) p) multiply + let fuel : Realizer (fun x : ProfileData×ℕ=>x.1.1++x.1.1) := composition (pair first.fst first.fst) append + let lpow := composition (pair fuel (composition (pair second (constant 2)) quotient)) thresholdRealizer + let rpow := composition (pair fuel (composition (pair (composition (pair fourP second) subtract) (constant 2)) quotient)) thresholdRealizer + exact (choose (composition (pair second twoP) less) + (composition (pair first.snd.fst (composition (pair first.snd.snd.fst lpow) divRealizer)) maximumRealizer) + (choose (composition (pair second twoP) natEqual) first.snd.snd.snd.snd + (composition (pair first.snd.fst (composition (pair first.snd.snd.snd.fst rpow) divRealizer)) maximumRealizer))).congr (by intro x; simp [profile]) +lemma polynomial_profile : PolynomialTime profileRealizer := by + unfold profileRealizer + dsimp only + apply polynomial_congr + have := polynomial_threshold + have := polynomial_quotient + have := polynomial_div + have := polynomial_maximum + dsimp only [Realizer.fst,Realizer.snd] + tree_cost +lemma profile_repr (fuel : List Bool) (B Hu Hv lam : ℚ) + (hB : 0≤B) (hHu : 0≤Hu) (hHv : 0≤Hv) (_hlam : 0≤lam) + (i : Fin (4*fuel.length+1)) : + profile ((fuel,(TreeFraction.repr B,(TreeFraction.repr Hu,(TreeFraction.repr Hv,TreeFraction.repr lam)))),i.val)= + TreeFraction.repr (RationalSource.profile fuel.length B Hu Hv lam i) := by + unfold profile RationalSource.profile + dsimp only + split_ifs with h h' + · have hi : i.val/2≤(fuel++fuel).length := by simp only [List.length_append]; omega + rw [threshold_repr _ _ hi,div_repr hHu (by positivity),maximum_repr hB (by positivity)] + · rfl + · have hi : (4*fuel.length-i.val)/2≤(fuel++fuel).length := by simp only [List.length_append]; omega + rw [threshold_repr _ _ hi,div_repr hHv (by positivity),maximum_repr hB (by positivity)] + +def height (x : Matrix×ℕ) : Fraction := + ExecutableScaling.rowMax ((x.1,(List.range x.1.length).map (fun i=>(i,(1,1)))),x.2) +def heightRealizer : Realizer height := + composition (pair (pair first (composition (composition (composition first listLength) range) + (map (pair identity (constant (1,1)))))) second) ExecutableScaling.rowMaxRealizer +lemma polynomial_height : PolynomialTime heightRealizer := by + unfold heightRealizer + have hh : PolynomialTime (composition (composition (first (A:=Matrix) (B:=ℕ)) listLength) range) := by + apply polynomial_boundedRange (by tree_cost) X + intro x + simpa only [eval_X,Function.comp_apply] using (list_length_le_weight x.1).trans (weight_fst x) + apply polynomial_composition _ ExecutableScaling.polynomial_rowMax + tree_cost +lemma height_rep {n : ℕ} (hn : 2≤n) (B : Fin n→Fin n→ℚ) (hB : ∀ i j,0≤B i j) (i : Fin n) : + height (matrixRep B,i.val)=TreeFraction.repr + ((Finset.univ.erase i).sup' (Counting.others_nonempty hn i) (B i)) := by + have he : (List.range (matrixRep B).length).map (fun i=>(i,((1,1) : Fraction)))= + ExecutableScaling.vectorRep (fun _ : Fin n=>(1:ℚ)) := by + rw [matrixRep_length] + unfold ExecutableScaling.vectorRep + rw [ExecutableDP.map_range_ofFn] + rfl + unfold height + dsimp only + rw [he,ExecutableScaling.rowMax_rep hn B (fun _=>1) (fun i j _=>hB i j) (by intro j; norm_num) i] + simp only [Counting.rowMaximum,div_one] + +def maxHeight (M : Matrix) : Fraction := + ((List.range M.length).map (fun i=>height (M,i))).foldl (fun a b=>maximum (b,a)) (0,1) +def maxHeightRealizer : Realizer maxHeight := (composition + (pair (composition (pair identity (composition listLength range)) (mapWith heightRealizer)) (constant (0,1))) + (fold maximumRealizer)).congr (fun _=>rfl) +lemma polynomial_maxHeight : PolynomialTime maxHeightRealizer := by + unfold maxHeightRealizer + apply polynomial_congr + have hr:PolynomialTime (composition (listLength (A:=List Fraction)) range) := by + apply polynomial_boundedRange polynomial_listLength X + intro M; simpa only [eval_X] using list_length_le_weight M + have := polynomial_height + have := polynomial_maximumFold + tree_cost +end MatchingFPRAS.ExecutableSource + +end OAI diff --git a/lean/OAI/Combinatorics/MatchingCount/Graphs/TreeRankPlan.lean b/lean/OAI/Combinatorics/MatchingCount/Graphs/TreeRankPlan.lean new file mode 100644 index 0000000000000000000000000000000000000000..fa85262b558762338385691ef41ff8864f24ad24 --- /dev/null +++ b/lean/OAI/Combinatorics/MatchingCount/Graphs/TreeRankPlan.lean @@ -0,0 +1,94 @@ +import Mathlib +import OAI.Combinatorics.MatchingCount.Sampling.Plan +import OAI.Combinatorics.MatchingCount.Sampling.TreeDPCount +import OAI.Combinatorics.MatchingCount.Machines.TreeFastLookup +import OAI.Combinatorics.MatchingCount.Complexity.TreeCostMeasure +import OAI.Combinatorics.MatchingCount.Complexity.TreeCostTactic + +namespace OAI + +namespace MatchingFPRAS.ExecutableHierarchy +open TreeTyped ExecutableDP Polynomial + +def rankLe (a b : ℕ×ℕ) : Prop := b.1inferInstanceAs (Decidable (b.1 omega⟩ + +def rankLeRealizer : Realizer (fun x : (ℕ×ℕ)×(ℕ×ℕ)=>decide (rankLe x.1 x.2)) := + (composition (pair (composition (pair second.fst first.fst) less) + (composition (pair (composition (pair first.fst second.fst) natEqual) + (composition (pair first.snd second.snd) leNat)) boolAnd)) boolOr).congr (by + intro x + apply Bool.eq_iff_iff.mpr + simp only [Function.comp_apply,Bool.or_eq_true,Bool.and_eq_true,decide_eq_true_eq] + rfl) +lemma polynomial_rankLe : PolynomialTime rankLeRealizer := by + unfold rankLeRealizer Realizer.fst Realizer.snd + apply polynomial_congr + tree_cost + +def rankEntries (rs : List ℕ) : List (ℕ×ℕ) := (List.range rs.length).map fun i=>(rs.getD i 0,i) +def rankEntriesRealizer : Realizer rankEntries := (composition (pair identity (composition listLength range)) + (mapWith (pair (getDFast 0) second))).congr (fun _=>rfl) +lemma polynomial_rankEntries : PolynomialTime rankEntriesRealizer := by + unfold rankEntriesRealizer + apply polynomial_congr + have hr : PolynomialTime (composition (listLength (A:=ℕ)) range) := + polynomial_boundedRange polynomial_listLength X (fun x=>by simpa using list_length_le_weight x) + exact polynomial_composition (polynomial_pair polynomial_identity hr) + (polynomial_mapWith (polynomial_pair (polynomial_getDFast 0) polynomial_second)) +def rankPlan (rs : List ℕ) : List ℕ := ((rankEntries rs).insertionSort rankLe).map Prod.snd +def rankPlanRealizer : Realizer rankPlan := composition (composition rankEntriesRealizer (insertionSort rankLe rankLeRealizer)) (map second) +lemma polynomial_rankPlan : PolynomialTime rankPlanRealizer := + polynomial_composition (polynomial_composition polynomial_rankEntries (polynomial_insertionSort rankLe polynomial_rankLe)) (polynomial_map polynomial_second) + +lemma rankEntries_ofFn {m : ℕ} (rank : Fin m→ℕ) : + rankEntries (List.ofFn rank)=List.ofFn (fun i=>(rank i,i.val)) := by + unfold rankEntries + rw [List.length_ofFn,map_range_ofFn] + apply List.ofFn_inj.mpr + funext i + simp [List.getD] +lemma zipIdx_rankLE {m : ℕ} (rank : Fin m→ℕ) (a b : Fin m×ℕ) : + List.zipIdxLE (fun x y=>decide (rank y≤rank x)) a b= + decide (rankLe (rank a.1,a.2) (rank b.1,b.2)) := by + apply Bool.eq_iff_iff.mpr + by_cases hab : rank b.1≤rank a.1 <;> by_cases hba : rank a.1≤rank b.1 <;> + simp only [List.zipIdxLE,decide_eq_true_eq,ite_true,ite_false,hab,hba] + all_goals simp only [rankLe,Bool.false_eq_true] + all_goals try simp only [true_iff,false_iff] + all_goals omega +lemma zipIdx_ofFn_id (m : ℕ) : + (List.ofFn (fun i : Fin m=>i)).zipIdx=List.ofFn (fun i : Fin m=>(i,i.val)) := by + apply List.ext_getElem + · simp + · intro i hi hi' + simp only [List.getElem_zipIdx,List.getElem_ofFn,Nat.zero_add] +lemma rankPlan_eq {m : ℕ} (rank : Fin m→ℕ) : + rankPlan (List.ofFn rank)=(UnitRefresh.Materialized.plan rank).map Fin.val := by + let xs := List.ofFn (fun i : Fin m=>i) + let le := fun a b : Fin m=>decide (rank b≤rank a) + let f := fun a : Fin m×ℕ=>(rank a.1,a.2) + have hm := List.map_mergeSort (l:=xs.zipIdx) (r:=List.zipIdxLE le) (s:=fun a b=>decide (rankLe a b)) + (f:=f) (fun a _ha b _hb=>zipIdx_rankLE rank a b) + have hz : xs.zipIdx.map f=List.ofFn (fun i=>(rank i,i.val)) := by + rw [zipIdx_ofFn_id,List.map_ofFn] + rfl + have hfirst : ((xs.zipIdx).mergeSort (List.zipIdxLE le)).map (fun a=>a.1.val)= + ((xs.zipIdx).mergeSort (List.zipIdxLE le)).map Prod.snd := by + apply List.map_congr_left + intro a ha + rw [List.mem_mergeSort,zipIdx_ofFn_id,List.mem_ofFn] at ha + obtain ⟨i,rfl⟩:=ha + rfl + unfold rankPlan + rw [rankEntries_ofFn,←List.mergeSort_eq_insertionSort,←hz,←hm, List.map_map] + change _=(xs.mergeSort le).map Fin.val + have hm2 := congrArg (List.map Fin.val) (List.mergeSort_zipIdx (l:=xs) (le:=le)) + rw [List.map_map] at hm2 + simpa only [Function.comp_def,f] using hfirst.symm.trans hm2 +end MatchingFPRAS.ExecutableHierarchy + +end OAI diff --git a/lean/OAI/Combinatorics/MatchingCount/Graphs/TreeSwitchRaw.lean b/lean/OAI/Combinatorics/MatchingCount/Graphs/TreeSwitchRaw.lean new file mode 100644 index 0000000000000000000000000000000000000000..0c01dbe475d268e6de40542c9ef4c1008b3f4376 --- /dev/null +++ b/lean/OAI/Combinatorics/MatchingCount/Graphs/TreeSwitchRaw.lean @@ -0,0 +1,115 @@ +import Mathlib +import OAI.Combinatorics.MatchingCount.Tapes.TreeSparseComponents +import OAI.Combinatorics.MatchingCount.Machines.TreeLabelTable +import OAI.Combinatorics.MatchingCount.Graphs.TreeSwitchValid + +namespace OAI + +namespace MatchingFPRAS.TreeTyped.SparseProgram +open TreeTyped + +variable {E V C : Type} [Codec E] [Codec V] [Codec C] [LinearOrder E] [LinearOrder V] +attribute [local instance] Transport.Sparse.finsetOrder + +def pairSet (x : E×E) : Finset E := {x.1,x.2} +def pairSetRealizer (Eq : Realizer (fun x : E×E=>decide (x.1=x.2))) + (Le : Realizer (fun x : E×E=>decide (x.1≤x.2))) : Realizer (pairSet (E:=E)) := + (composition (pair first (composition second finsetSingleton)) (finsetInsert Eq Le)).congr (fun _=>rfl) +lemma polynomial_pairSet {Eq : Realizer (fun x : E×E=>decide (x.1=x.2))} + {Le : Realizer (fun x : E×E=>decide (x.1≤x.2))} (hEq : PolynomialTime Eq) (hLe : PolynomialTime Le) : + PolynomialTime (pairSetRealizer Eq Le) := by + unfold pairSetRealizer + apply polynomial_congr + tree_cost + +def switchEdit (x : Finset E×Quad E) : Finset E := + (x.1\pairSet (x.2.1.1,x.2.2.1))∪pairSet (x.2.1.2,x.2.2.2) +def switchEditRealizer (Eq : Realizer (fun x : E×E=>decide (x.1=x.2))) + (Le : Realizer (fun x : E×E=>decide (x.1≤x.2))) : Realizer (switchEdit (E:=E)) := + (composition (pair (composition (pair first (composition (pair second.fst.fst second.snd.fst) + (pairSetRealizer Eq Le))) (finsetSDiff Eq)) + (composition (pair second.fst.snd second.snd.snd) (pairSetRealizer Eq Le))) (finsetUnion Eq Le)).congr (fun _=>rfl) +lemma polynomial_switchEdit {Eq : Realizer (fun x : E×E=>decide (x.1=x.2))} + {Le : Realizer (fun x : E×E=>decide (x.1≤x.2))} (hEq : PolynomialTime Eq) (hLe : PolynomialTime Le) : + PolynomialTime (switchEditRealizer Eq Le) := by + unfold switchEditRealizer Realizer.fst Realizer.snd + apply polynomial_congr + have := polynomial_pairSet hEq hLe + tree_cost + +abbrev RawSwitchInput (C E V : Type) := (C×(Finset V×Finset E))×Finset E +def switchList (p : C×(E×(V×V))→Bool) (x : RawSwitchInput C E V) : List (Quad V×Quad E) := + ((quads (x.1.2.1.sort (·≤·))).product (quads (x.1.2.2.sort (·≤·)))).filter + (fun q=>switchValid p ((x.1.1,x.2),q)) +def switchListRealizer {p : C×(E×(V×V))→Bool} (P : Realizer p) + (EqE : Realizer (fun x : E×E=>decide (x.1=x.2))) + (EqV : Realizer (fun x : V×V=>decide (x.1=x.2))) + (LeV : Realizer (fun x : V×V=>decide (x.1≤x.2))) : Realizer (switchList p) := + (composition (pair (pair first.fst second) + (composition (pair (composition (composition first.snd.fst finsetList) quadsRealizer) + (composition (composition first.snd.snd finsetList) quadsRealizer)) listProduct)) + (filterWith (switchValidRealizer P EqE EqV LeV))).congr (fun _=>rfl) +lemma polynomial_switchList {p : C×(E×(V×V))→Bool} {P : Realizer p} + {EqE : Realizer (fun x : E×E=>decide (x.1=x.2))} + {EqV : Realizer (fun x : V×V=>decide (x.1=x.2))} + {LeV : Realizer (fun x : V×V=>decide (x.1≤x.2))} + (hP : PolynomialTime P) (hE : PolynomialTime EqE) (hV : PolynomialTime EqV) (hlV : PolynomialTime LeV) : + PolynomialTime (switchListRealizer P EqE EqV LeV) := by + unfold switchListRealizer Realizer.fst Realizer.snd + apply polynomial_congr + have := polynomial_quads (A:=E) + have := polynomial_quads (A:=V) + have := polynomial_listProduct (A:=Quad V) (B:=Quad E) + have hh := polynomial_filterWithList (polynomial_switchValid hP hE hV hlV) + apply polynomial_composition _ hh + tree_cost + +def switchRaw (p : C×(E×(V×V))→Bool) (x : RawSwitchInput C E V) : Finset (Finset E) := + ((switchList p x).map fun q=>switchEdit (x.2,q.2)).toFinset + +def switchRawRealizer {p : C×(E×(V×V))→Bool} (P : Realizer p) + (EqE : Realizer (fun x : E×E=>decide (x.1=x.2))) + (LeE : Realizer (fun x : E×E=>decide (x.1≤x.2))) + (EqV : Realizer (fun x : V×V=>decide (x.1=x.2))) + (LeV : Realizer (fun x : V×V=>decide (x.1≤x.2))) : Realizer (switchRaw p) := + (composition (composition (pair second (switchListRealizer P EqE EqV LeV)) + (mapWith (composition (pair first second.snd) (switchEditRealizer EqE LeE)))) + (listFinset (orderedSetEqual EqE) (colexLe EqE LeE))).congr (by + intro x; ext a; simp only [Function.comp_apply, List.mem_toFinset, switchRaw]) +lemma polynomial_switchRaw {p : C×(E×(V×V))→Bool} {P : Realizer p} + {EqE : Realizer (fun x : E×E=>decide (x.1=x.2))} + {LeE : Realizer (fun x : E×E=>decide (x.1≤x.2))} + {EqV : Realizer (fun x : V×V=>decide (x.1=x.2))} + {LeV : Realizer (fun x : V×V=>decide (x.1≤x.2))} + (hP : PolynomialTime P) (hE : PolynomialTime EqE) (hlE : PolynomialTime LeE) + (hV : PolynomialTime EqV) (hlV : PolynomialTime LeV) : + PolynomialTime (switchRawRealizer P EqE LeE EqV LeV) := by + unfold switchRawRealizer Realizer.snd + apply polynomial_congr + have := polynomial_switchList hP hE hV hlV + have := polynomial_switchEdit hE hlE + have := polynomial_listFinset (polynomial_orderedSetEqual hE) (polynomial_colexLe hE hlE) + tree_cost + +omit [Codec E] [Codec V] [Codec C] in +lemma switchRaw_eq [Fintype E] [Fintype V] (ends : E→Sym2 V) + (p : C×(E×(V×V))→Bool) (c : C) + (hp : ∀ e v w,p (c,(e,(v,w)))=decide (ends e=s(v,w))) (M : Finset E) : + switchRaw p ((c,(Finset.univ,Finset.univ)),M)=Transport.Sparse.switchRaw ends M := by + ext B + simp only [switchRaw,List.mem_toFinset,List.mem_map,switchList,List.mem_filter] + constructor + · rintro ⟨⟨v,e⟩,⟨_,hv⟩,rfl⟩ + apply Finset.mem_image.mpr + refine ⟨(quadFn v,quadFn e),(switchValid_eq ends p c hp M (v,e)).mp hv,?_⟩ + rfl + · intro h + obtain ⟨⟨v,e⟩,hpatt,rfl⟩:=Finset.mem_image.mp h + refine ⟨(quadOfFn v,quadOfFn e),⟨?_,?_⟩,rfl⟩ + · rw [mem_listProduct,mem_quads,mem_quads] + simp only [Finset.mem_sort,Finset.mem_univ,implies_true,and_self] + · apply (switchValid_eq ends p c hp M (quadOfFn v,quadOfFn e)).mpr + simpa only [quadFn_ofFn] using hpatt +end MatchingFPRAS.TreeTyped.SparseProgram + +end OAI diff --git a/lean/OAI/Combinatorics/MatchingCount/Graphs/TreeSwitchValid.lean b/lean/OAI/Combinatorics/MatchingCount/Graphs/TreeSwitchValid.lean new file mode 100644 index 0000000000000000000000000000000000000000..3d68d019e59da58d3e163bd1bead4794c9b72b03 --- /dev/null +++ b/lean/OAI/Combinatorics/MatchingCount/Graphs/TreeSwitchValid.lean @@ -0,0 +1,78 @@ +import Mathlib +import OAI.Combinatorics.MatchingCount.Machines.TreeQuadDistinct + +namespace OAI + +namespace MatchingFPRAS.TreeTyped.SparseProgram +open TreeTyped + +variable {E V C : Type} [Codec E] [Codec V] [Codec C] [LinearOrder E] [LinearOrder V] +abbrev SwitchInput (C E V : Type) := (C×Finset E)×(Quad V×Quad E) +def switchValid (p : C×(E×(V×V))→Bool) (x : SwitchInput C E V) : Bool := + decide (Function.Injective (quadFn x.2.1) ∧ + (∀ i : Fin 4,p (x.1.1,(quadFn x.2.2 i,(quadFn x.2.1 i,quadFn x.2.1 (i+1))))=true) ∧ + x.2.2.1.1≠x.2.2.2.1 ∧ x.2.2.1.1∈x.1.2 ∧ x.2.2.2.1∈x.1.2) + +def switchValidRealizer {p : C×(E×(V×V))→Bool} (P : Realizer p) + (EqE : Realizer (fun x : E×E=>decide (x.1=x.2))) + (EqV : Realizer (fun x : V×V=>decide (x.1=x.2))) + (LeV : Realizer (fun x : V×V=>decide (x.1≤x.2))) : Realizer (switchValid p) := by + let V0 : Realizer (fun x : SwitchInput C E V=>x.2.1.1.1) := second.fst.fst.fst + let V1 : Realizer (fun x : SwitchInput C E V=>x.2.1.1.2) := second.fst.fst.snd + let V2 : Realizer (fun x : SwitchInput C E V=>x.2.1.2.1) := second.fst.snd.fst + let V3 : Realizer (fun x : SwitchInput C E V=>x.2.1.2.2) := second.fst.snd.snd + let E0 : Realizer (fun x : SwitchInput C E V=>x.2.2.1.1) := second.snd.fst.fst + let E1 : Realizer (fun x : SwitchInput C E V=>x.2.2.1.2) := second.snd.fst.snd + let E2 : Realizer (fun x : SwitchInput C E V=>x.2.2.2.1) := second.snd.snd.fst + let E3 : Realizer (fun x : SwitchInput C E V=>x.2.2.2.2) := second.snd.snd.snd + let T0 := composition (pair first.fst (pair E0 (pair V0 V1))) P + let T1 := composition (pair first.fst (pair E1 (pair V1 V2))) P + let T2 := composition (pair first.fst (pair E2 (pair V2 V3))) P + let T3 := composition (pair first.fst (pair E3 (pair V3 V0))) P + let allFits := composition (pair (composition (pair T0 T1) boolAnd) (composition (pair T2 T3) boolAnd)) boolAnd + let distinctEdges := composition (composition (pair E0 E2) EqE) boolNot + let membership := composition (pair (composition (pair E0 first.snd) (finsetMember EqE)) + (composition (pair E2 first.snd) (finsetMember EqE))) boolAnd + exact (composition (pair (composition second.fst (quadInjective EqV LeV)) + (composition (pair allFits (composition (pair distinctEdges membership) boolAnd)) boolAnd)) boolAnd).congr (by + intro x + apply Bool.eq_iff_iff.mpr + simp only [Function.comp_apply,Bool.and_eq_true,Bool.not_eq_true',decide_eq_false_iff_not, + decide_eq_true_eq,switchValid] + apply and_congr_right' + apply and_congr_left' + constructor + · rintro ⟨⟨h0,h1⟩,⟨h2,h3⟩⟩ i + fin_cases i <;> assumption + · intro h + exact ⟨⟨h 0,h 1⟩,⟨h 2,h 3⟩⟩) +lemma polynomial_switchValid {p : C×(E×(V×V))→Bool} {P : Realizer p} + {EqE : Realizer (fun x : E×E=>decide (x.1=x.2))} + {EqV : Realizer (fun x : V×V=>decide (x.1=x.2))} + {LeV : Realizer (fun x : V×V=>decide (x.1≤x.2))} + (hP : PolynomialTime P) (hE : PolynomialTime EqE) (hV : PolynomialTime EqV) (hlV : PolynomialTime LeV) : + PolynomialTime (switchValidRealizer P EqE EqV LeV) := by + unfold switchValidRealizer Realizer.fst Realizer.snd + dsimp only + have := polynomial_quadInjective hV hlV + apply polynomial_congr + tree_cost + +omit [Codec E] [Codec V] [Codec C] in +lemma switchValid_eq [Fintype E] [Fintype V] (ends : E→Sym2 V) + (p : C×(E×(V×V))→Bool) (c : C) + (hp : ∀ e v w,p (c,(e,(v,w)))=decide (ends e=s(v,w))) (M : Finset E) (q : Quad V×Quad E) : + switchValid p ((c,M),q)=true ↔ (quadFn q.1,quadFn q.2)∈Transport.Sparse.switchPatterns ends M := by + have he (e : E) (v w : V) : ends e=s(v,w) ↔ ∀ x,x∈ends e ↔ x=v ∨ x=w := by + constructor + · intro h; simp [h] + · intro h; apply Sym2.ext; intro x; simpa using h x + simp only [switchValid,decide_eq_true_eq,Transport.Sparse.switchPatterns, + Finset.mem_filter,Finset.mem_univ,true_and,hp,Finset.insert_subset_iff, + Finset.singleton_subset_iff] + change (_ ∧ (∀ i,ends (quadFn q.2 i)=s(quadFn q.1 i,quadFn q.1 (i+1))) ∧ _ ∧ _ ∧ _) ↔ _ + simp_rw [he] + rfl +end MatchingFPRAS.TreeTyped.SparseProgram + +end OAI diff --git a/lean/OAI/Combinatorics/MatchingCount/Graphs/Vertex.lean b/lean/OAI/Combinatorics/MatchingCount/Graphs/Vertex.lean new file mode 100644 index 0000000000000000000000000000000000000000..e38ad6c5102e1a65bdb6458f4a3909268855e815 --- /dev/null +++ b/lean/OAI/Combinatorics/MatchingCount/Graphs/Vertex.lean @@ -0,0 +1,423 @@ +import Mathlib + +namespace OAI + +namespace MatchingFPRAS.RealGeometry + +variable {V E : Type*} + +abbrev Vertex (V E : Type*) (m : ℕ) := V ⊕ (E × Fin m) + +def atVertex (u v : E → V) (m : ℕ) (e : E) (i : Fin (m+2)) : Vertex V E m := + if h0 : i.val=0 then Sum.inl (u e) + else if h1 : i.val=m+1 then Sum.inl (v e) + else Sum.inr (e,⟨i.val-1,by omega⟩) + +@[simp] lemma atVertex_zero (u v : E → V) (m : ℕ) (e : E) : + atVertex u v m e 0 = Sum.inl (u e) := by simp [atVertex] + +@[simp] lemma atVertex_last (u v : E → V) (m : ℕ) (e : E) : + atVertex u v m e (Fin.last (m+1)) = Sum.inl (v e) := by simp [atVertex] + +@[simp] lemma atVertex_internal (u v : E → V) (m : ℕ) (e : E) (i : Fin m) : + atVertex u v m e i.succ.castSucc = Sum.inr (e,i) := by + simp only [atVertex,Fin.val_castSucc,Fin.val_succ,Nat.add_eq_zero_iff,one_ne_zero, + and_false,↓reduceDIte] + rw [dite_eq_right (by have := i.isLt; omega)] + rfl + +lemma atVertex_eq_inr_iff (u v : E → V) (m : ℕ) (e f : E) + (i : Fin (m+2)) (j : Fin m) : + atVertex u v m e i = Sum.inr (f,j) ↔ e=f ∧ i.val=j.val+1 := by + unfold atVertex + split_ifs with h0 h1 + · simp only [false_iff,not_and] + intro h + have := j.isLt + omega + · simp only [false_iff,not_and] + intro h + have := j.isLt + omega + · simp only [Sum.inr.injEq,Prod.mk.injEq,Fin.ext_iff] + constructor + · rintro ⟨rfl,h⟩; exact ⟨rfl,by omega⟩ + · rintro ⟨rfl,h⟩; exact ⟨rfl,by omega⟩ + +lemma atVertex_eq_inl_iff (u v : E → V) (m : ℕ) (e : E) + (i : Fin (m+2)) (x : V) : + atVertex u v m e i = Sum.inl x ↔ + (i.val=0 ∧ u e=x) ∨ (i.val=m+1 ∧ v e=x) := by + unfold atVertex + split_ifs with h0 h1 + · simp [h0] + · simp [h1] + · simp [h0,h1] + +theorem atVertex_injective (u v : E → V) (m : ℕ) (e : E) (huv : u e ≠ v e) : + Function.Injective (atVertex u v m e) := by + intro i j h + by_cases hi0 : i.val=0 + · have he : atVertex u v m e i = Sum.inl (u e) := by simp [atVertex,hi0] + have hj := (atVertex_eq_inl_iff u v m e j (u e)).mp (h.symm.trans he) + rcases hj with hj | hj + · apply Fin.ext; omega + · exact False.elim (huv hj.2.symm) + · by_cases hi1 : i.val=m+1 + · have he : atVertex u v m e i = Sum.inl (v e) := by simp [atVertex,hi1] + have hj := (atVertex_eq_inl_iff u v m e j (v e)).mp (h.symm.trans he) + rcases hj with hj | hj + · exact False.elim (huv hj.2) + · apply Fin.ext; omega + · let k : Fin m := ⟨i.val-1,by omega⟩ + have he : atVertex u v m e i = Sum.inr (e,k) := by simp [atVertex,hi0,hi1,k] + have hj := (atVertex_eq_inr_iff u v m e e j k).mp (h.symm.trans he) + apply Fin.ext + dsimp [k] at hj + omega + +theorem internal_private (u v : E → V) (m : ℕ) (e f : E) (i : Fin m) + (j : Fin (m+2)) : + atVertex u v m e i.succ.castSucc = atVertex u v m f j ↔ + e=f ∧ i.val+1=j.val := by + rw [atVertex_internal,eq_comm,atVertex_eq_inr_iff] + exact and_congr eq_comm eq_comm + +def edge (u v : E → V) (m : ℕ) (e : E) (i : Fin (m+1)) : Sym2 (Vertex V E m) := + s(atVertex u v m e i.castSucc,atVertex u v m e i.succ) + +lemma first_vertex_terminal (u v : E → V) (m : ℕ) (e : E) + (i : Fin (m+1)) (x : V) : + atVertex u v m e i.castSucc = Sum.inl x ↔ i.val=0 ∧ u e=x := by + rw [atVertex_eq_inl_iff] + have h : i.val ≠ m+1 := by omega + simp [h] + +lemma second_vertex_terminal (u v : E → V) (m : ℕ) (e : E) + (i : Fin (m+1)) (x : V) : + atVertex u v m e i.succ = Sum.inl x ↔ i.val=m ∧ v e=x := by + rw [atVertex_eq_inl_iff] + simp only [Fin.val_succ,Nat.add_eq_zero_iff,one_ne_zero,and_false,false_and,false_or, + Nat.add_right_cancel_iff] + +lemma edge_ordered_injective (u v : E → V) (m : ℕ) (hm : 1 ≤ m) + (e f : E) (i j : Fin (m+1)) + (h0 : atVertex u v m e i.castSucc = atVertex u v m f j.castSucc) + (h1 : atVertex u v m e i.succ = atVertex u v m f j.succ) : e=f ∧ i=j := by + by_cases hi : i.val=0 + · have hz : atVertex u v m e i.castSucc = Sum.inl (u e) := by + apply (first_vertex_terminal _ _ _ _ _ _).mpr; exact ⟨hi,rfl⟩ + have hj : j.val=0 := ((first_vertex_terminal _ _ _ _ _ _).mp (h0.symm.trans hz)).1 + let k : Fin m := ⟨0,by omega⟩ + have hki : i.succ = k.succ.castSucc := by apply Fin.ext; simp only [Fin.val_succ,Fin.val_castSucc]; dsimp only [k]; omega + have hkj : j.succ = k.succ.castSucc := by apply Fin.ext; simp only [Fin.val_succ,Fin.val_castSucc]; dsimp only [k]; omega + rw [hki,hkj,atVertex_internal,atVertex_internal] at h1 + have hef : e=f := congrArg Prod.fst (Sum.inr.inj h1) + exact ⟨hef,Fin.ext (by omega)⟩ + · let k : Fin m := ⟨i.val-1,by omega⟩ + have hki : i.castSucc = k.succ.castSucc := by apply Fin.ext; simp only [Fin.val_succ,Fin.val_castSucc]; dsimp only [k]; omega + rw [hki] at h0 + have hh := (internal_private u v m e f k j.castSucc).mp h0 + refine ⟨hh.1,Fin.ext ?_⟩ + dsimp [k] at hh + omega + +lemma edge_ordered_not_reverse (u v : E → V) (m : ℕ) (hm : 2 ≤ m) + (e f : E) (i j : Fin (m+1)) : + ¬ (atVertex u v m e i.castSucc = atVertex u v m f j.succ ∧ + atVertex u v m e i.succ = atVertex u v m f j.castSucc) := by + rintro ⟨h0,h1⟩ + by_cases hi : i.val=0 + · have hz : atVertex u v m e i.castSucc = Sum.inl (u e) := by + apply (first_vertex_terminal _ _ _ _ _ _).mpr; exact ⟨hi,rfl⟩ + have hj : j.val=m := ((second_vertex_terminal _ _ _ _ _ _).mp (h0.symm.trans hz)).1 + let k : Fin m := ⟨0,by omega⟩ + have hki : i.succ = k.succ.castSucc := by apply Fin.ext; simp only [Fin.val_succ,Fin.val_castSucc]; dsimp only [k]; omega + rw [hki] at h1 + have hh := (internal_private u v m e f k j.castSucc).mp h1 + dsimp [k] at hh + omega + · let k : Fin m := ⟨i.val-1,by omega⟩ + have hki : i.castSucc = k.succ.castSucc := by apply Fin.ext; simp only [Fin.val_succ,Fin.val_castSucc]; dsimp only [k]; omega + rw [hki] at h0 + have hh := (internal_private u v m e f k j.succ).mp h0 + have hij : i.val=j.val+1 := by dsimp [k] at hh; omega + by_cases him : i.val=m + · have hz : atVertex u v m e i.succ = Sum.inl (v e) := by + apply (second_vertex_terminal _ _ _ _ _ _).mpr; exact ⟨him,rfl⟩ + have hj : j.val=0 := ((first_vertex_terminal _ _ _ _ _ _).mp (h1.symm.trans hz)).1 + omega + · let l : Fin m := ⟨i.val,by omega⟩ + have hli : i.succ = l.succ.castSucc := rfl + rw [hli] at h1 + have hh' := (internal_private u v m e f l j.castSucc).mp h1 + dsimp [l] at hh' + omega + +theorem edge_injective (u v : E → V) (m : ℕ) (hm : 2 ≤ m) : + Function.Injective (fun q : E × Fin (m+1) => edge u v m q.1 q.2) := by + rintro ⟨e,i⟩ ⟨f,j⟩ h + have he := Sym2.eq_iff.mp h + rcases he with h | h + · have hh := edge_ordered_injective u v m (by omega) e f i j h.1 h.2 + exact Prod.ext hh.1 hh.2 + · exact False.elim (edge_ordered_not_reverse u v m hm e f i j h) + +noncomputable def activity [Fintype E] (u v : E → V) (m : ℕ) + (t : E → Fin (m+1) → ℝ) (x y : Vertex V E m) : ℝ := by + classical + exact ∑ q : E × Fin (m+1), if edge u v m q.1 q.2 = s(x,y) then t q.1 q.2 else 0 + +lemma activity_symm [Fintype E] (u v : E → V) (m : ℕ) + (t : E → Fin (m+1) → ℝ) (x y : Vertex V E m) : + activity u v m t x y = activity u v m t y x := by + classical + simp only [activity,Sym2.eq_swap] + +lemma activity_nonneg [Fintype E] (u v : E → V) (m : ℕ) + (t : E → Fin (m+1) → ℝ) (ht : ∀ e i, 0 ≤ t e i) (x y : Vertex V E m) : + 0 ≤ activity u v m t x y := by + classical + unfold activity + apply Finset.sum_nonneg + intro q _ + split_ifs <;> simp [ht] + +theorem activity_on_edge [Fintype E] (u v : E → V) (m : ℕ) (hm : 2 ≤ m) + (t : E → Fin (m+1) → ℝ) (e : E) (i : Fin (m+1)) : + activity u v m t (atVertex u v m e i.castSucc) (atVertex u v m e i.succ) = t e i := by + classical + unfold activity + rw [Finset.sum_eq_single (e,i)] + · simp [edge] + · intro q hq hne + have hnot : edge u v m q.1 q.2 ≠ edge u v m e i := by + intro he + exact hne (edge_injective u v m hm he) + exact ite_eq_right hnot + · simp + +lemma activity_eq_zero_of_not_edge [Fintype E] (u v : E → V) (m : ℕ) + (t : E → Fin (m+1) → ℝ) (x y : Vertex V E m) + (h : ∀ e i, edge u v m e i ≠ s(x,y)) : activity u v m t x y = 0 := by + classical + apply Finset.sum_eq_zero + intro q hq + exact ite_eq_right (h q.1 q.2) + +theorem activity_eq_edge_or_zero [Fintype E] (u v : E → V) (m : ℕ) (hm : 2 ≤ m) + (t : E → Fin (m+1) → ℝ) (x y : Vertex V E m) : + activity u v m t x y = 0 ∨ + ∃ e i, edge u v m e i = s(x,y) ∧ activity u v m t x y = t e i := by + classical + by_cases hex : ∃ e i, edge u v m e i = s(x,y) + · obtain ⟨e,i,he⟩ := hex + refine Or.inr ⟨e,i,he,?_⟩ + rcases Sym2.eq_iff.mp he with he | he + · rw [← he.1,← he.2] + exact activity_on_edge u v m hm t e i + · rw [← he.2,← he.1,activity_symm] + exact activity_on_edge u v m hm t e i + · left + exact activity_eq_zero_of_not_edge u v m t x y (by simpa only [not_exists] using hex) + +theorem internal_incident_iff (u v : E → V) (m : ℕ) (e f : E) + (i : Fin (m+1)) (j : Fin m) : + Sum.inr (f,j) ∈ edge u v m e i ↔ + e=f ∧ (i.val=j.val ∨ i.val=j.val+1) := by + rw [edge,Sym2.mem_iff] + simp only [eq_comm (a := Sum.inr (f,j)),atVertex_eq_inr_iff,Fin.val_castSucc,Fin.val_succ] + constructor + · rintro (⟨he,hi⟩ | ⟨he,hi⟩) + · exact ⟨he,Or.inr hi⟩ + · exact ⟨he,Or.inl (by omega)⟩ + · rintro ⟨he,hi | hi⟩ + · exact Or.inr ⟨he,by omega⟩ + · exact Or.inl ⟨he,hi⟩ + +theorem internal_activity_le [Fintype E] (u v : E → V) (m : ℕ) (hm : 2 ≤ m) + (t : E → Fin (m+1) → ℝ) (e : E) (j : Fin m) (T : ℝ) (hT : 0 ≤ T) + (hleft : t e j.castSucc ≤ T) (hright : t e j.succ ≤ T) (y : Vertex V E m) : + activity u v m t (Sum.inr (e,j)) y ≤ T := by + rcases activity_eq_edge_or_zero u v m hm t (Sum.inr (e,j)) y with hzero | ⟨f,i,he,hw⟩ + · simpa [hzero] using hT + · have hin : Sum.inr (e,j) ∈ edge u v m f i := by rw [he]; exact Sym2.mem_mk_left _ _ + obtain ⟨rfl,hi | hi⟩ := (internal_incident_iff u v m f e i j).mp hin + · have hij : i=j.castSucc := Fin.ext hi + simpa [hw,hij] using hleft + · have hij : i=j.succ := Fin.ext hi + simpa [hw,hij] using hright + +lemma edge_not_diag (u v : E → V) (m : ℕ) (e : E) (hue : u e ≠ v e) + (i : Fin (m+1)) : ¬ (edge u v m e i).IsDiag := by + rw [edge,Sym2.mk_isDiag_iff] + intro h + have he := atVertex_injective u v m e hue h + have hv := congrArg Fin.val he + simp only [Fin.val_succ,Fin.val_castSucc] at hv + omega + +def realThreshold (u v : E → V) (m : ℕ) (t : E → Fin (m+1) → ℝ) + (τ : ℝ) : SimpleGraph (Vertex V E m) where + Adj a b := a ≠ b ∧ ∃ e i, edge u v m e i = s(a,b) ∧ τ ≤ t e i + symm := ⟨by rintro a b ⟨hne,e,i,he,ht⟩; exact ⟨hne.symm,e,i,by simpa only [Sym2.eq_swap] using he,ht⟩⟩ + loopless := ⟨by rintro a ⟨hne,_⟩; exact hne rfl⟩ + +def logicalThreshold (u v : E → V) (lam : E → ℝ) (τ : ℝ) : SimpleGraph V where + Adj a b := a ≠ b ∧ ∃ e, s(u e,v e)=s(a,b) ∧ τ ≤ lam e + symm := ⟨by rintro a b ⟨hne,e,he,ht⟩; exact ⟨hne.symm,e,by simpa only [Sym2.eq_swap] using he,ht⟩⟩ + loopless := ⟨by rintro a ⟨hne,_⟩; exact hne rfl⟩ + +def contract (u v : E → V) (m : ℕ) (c : Fin (m+1)) : Vertex V E m → V + | Sum.inl a => a + | Sum.inr (e,j) => if j.val < c.val then u e else v e + +@[simp] lemma contract_terminal (u v : E → V) (m : ℕ) (c : Fin (m+1)) (a : V) : + contract u v m c (Sum.inl a) = a := rfl + +lemma contract_atVertex (u v : E → V) (m : ℕ) (c : Fin (m+1)) (e : E) + (i : Fin (m+2)) : contract u v m c (atVertex u v m e i) = + if i.val ≤ c.val then u e else v e := by + by_cases h0 : i.val=0 + · simp [atVertex,h0,contract] + by_cases hlast : i.val=m+1 + · have hn : ¬ i.val ≤ c.val := by omega + simp only [atVertex,dite_eq_right h0,dite_eq_left hlast,contract,ite_eq_right hn] + · have he : i.val-1 < c.val ↔ i.val ≤ c.val := by omega + simp [atVertex,h0,hlast,contract,he] + +lemma contracted_edge (u v : E → V) (m : ℕ) (c : Fin (m+1)) (e : E) + (i : Fin (m+1)) : + contract u v m c (atVertex u v m e i.castSucc) = + contract u v m c (atVertex u v m e i.succ) ∨ + (i=c ∧ contract u v m c (atVertex u v m e i.castSucc)=u e ∧ + contract u v m c (atVertex u v m e i.succ)=v e) := by + rw [contract_atVertex,contract_atVertex] + simp only [Fin.val_castSucc,Fin.val_succ] + by_cases hi : i.val < c.val + · left; simp [show i.val ≤ c.val by omega,show i.val+1 ≤ c.val by omega] + by_cases hi' : c.val < i.val + · left; simp [show ¬ i.val ≤ c.val by omega,show ¬ i.val+1 ≤ c.val by omega] + · have hic : i=c := Fin.ext (by omega) + right; subst i; simp + +lemma reachable_of_edge_reachable {W : Type*} (G : SimpleGraph V) (H : SimpleGraph W) + (f : V → W) (hf : ∀ a b, G.Adj a b → H.Reachable (f a) (f b)) + {a b : V} (h : G.Reachable a b) : H.Reachable (f a) (f b) := by + rw [SimpleGraph.reachable_iff_reflTransGen] at h ⊢ + induction h with + | refl => exact Relation.ReflTransGen.refl + | tail h he ih => + exact ih.trans ((SimpleGraph.reachable_iff_reflTransGen _ _).mp (hf _ _ he)) + +theorem threshold_contract (u v : E → V) (m : ℕ) (c : Fin (m+1)) + (lam : E → ℝ) (t : E → Fin (m+1) → ℝ) (hc : ∀ e, t e c=lam e) + (τ : ℝ) {a b : Vertex V E m} (h : (realThreshold u v m t τ).Reachable a b) : + (logicalThreshold u v lam τ).Reachable (contract u v m c a) (contract u v m c b) := by + apply reachable_of_edge_reachable (realThreshold u v m t τ) + (logicalThreshold u v lam τ) (contract u v m c) _ h + rintro a b ⟨hab,e,i,he,ht⟩ + rcases Sym2.eq_iff.mp he with he | he + · rw [← he.1,← he.2] + rcases contracted_edge u v m c e i with heq | ⟨rfl,hleft,hright⟩ + · rw [heq] + · rw [hleft,hright] + by_cases huv : u e=v e + · rw [huv] + · exact SimpleGraph.Adj.reachable ⟨huv,e,rfl,by simpa [hc e] using ht⟩ + · rw [← he.2,← he.1] + apply SimpleGraph.Reachable.symm + rcases contracted_edge u v m c e i with heq | ⟨rfl,hleft,hright⟩ + · rw [heq] + · rw [hleft,hright] + by_cases huv : u e=v e + · rw [huv] + · exact SimpleGraph.Adj.reachable ⟨huv,e,rfl,by simpa [hc e] using ht⟩ + +lemma positions_reachable (G : SimpleGraph V) (m : ℕ) (f : Fin (m+2) → V) + (hf : ∀ i : Fin (m+1), G.Reachable (f i.castSucc) (f i.succ)) + (i : Fin (m+2)) : G.Reachable (f 0) (f i) := by + obtain ⟨i,hi⟩ := i + induction i with + | zero => exact SimpleGraph.Reachable.refl _ + | succ i ih => + have hi' : i < m+2 := by omega + have hi'' : i < m+1 := by omega + exact (ih hi').trans (hf ⟨i,hi''⟩) + +theorem threshold_lift_edge (u v : E → V) (m : ℕ) (lam : E → ℝ) + (t : E → Fin (m+1) → ℝ) (hm : ∀ e i, lam e ≤ t e i) + (τ : ℝ) (e : E) (he : τ ≤ lam e) : + (realThreshold u v m t τ).Reachable (Sum.inl (u e)) (Sum.inl (v e)) := by + have h := positions_reachable (realThreshold u v m t τ) m (atVertex u v m e) + (fun i => ?_) (Fin.last (m+1)) + · simpa using h + by_cases hn : atVertex u v m e i.castSucc = atVertex u v m e i.succ + · rw [hn] + · exact SimpleGraph.Adj.reachable ⟨hn,e,i,rfl,he.trans (hm e i)⟩ + +theorem terminal_threshold_iff (u v : E → V) (m : ℕ) (c : Fin (m+1)) + (lam : E → ℝ) (t : E → Fin (m+1) → ℝ) (hc : ∀ e, t e c=lam e) + (hm : ∀ e i, lam e ≤ t e i) (τ : ℝ) (a b : V) : + (realThreshold u v m t τ).Reachable (Sum.inl a) (Sum.inl b) ↔ + (logicalThreshold u v lam τ).Reachable a b := by + constructor + · exact threshold_contract u v m c lam t hc τ + · apply reachable_of_edge_reachable (logicalThreshold u v lam τ) + (realThreshold u v m t τ) Sum.inl + rintro a b ⟨hne,e,he,ht⟩ + rcases Sym2.eq_iff.mp he with he | he + · rw [← he.1,← he.2]; exact threshold_lift_edge u v m lam t hm τ e ht + · rw [← he.2,← he.1]; exact (threshold_lift_edge u v m lam t hm τ e ht).symm + +lemma activity_on_eq [Fintype E] (u v : E → V) (m : ℕ) (hm : 2 ≤ m) + (t : E → Fin (m+1) → ℝ) (e : E) (i : Fin (m+1)) (a b : Vertex V E m) + (he : edge u v m e i=s(a,b)) : activity u v m t a b=t e i := by + rcases Sym2.eq_iff.mp he with he | he + · rw [← he.1,← he.2]; exact activity_on_edge u v m hm t e i + · rw [← he.2,← he.1,activity_symm]; exact activity_on_edge u v m hm t e i + +theorem realThreshold_adj_iff [Fintype E] (u v : E → V) (m : ℕ) (hm : 2 ≤ m) + (t : E → Fin (m+1) → ℝ) (τ : ℝ) (hτ : 0 < τ) (a b : Vertex V E m) : + (realThreshold u v m t τ).Adj a b ↔ a ≠ b ∧ τ ≤ activity u v m t a b := by + constructor + · rintro ⟨hne,e,i,he,ht⟩ + exact ⟨hne,by rwa [activity_on_eq u v m hm t e i a b he]⟩ + · rintro ⟨hne,ht⟩ + rcases activity_eq_edge_or_zero u v m hm t a b with hzero | ⟨e,i,he,hw⟩ + · rw [hzero] at ht; exact False.elim (not_le_of_gt hτ ht) + · exact ⟨hne,e,i,he,by rwa [hw] at ht⟩ + +theorem path_interval_reachable (u v : E → V) (m : ℕ) + (t : E → Fin (m+1) → ℝ) (τ : ℝ) (e : E) + (i j : Fin (m+2)) (hij : i.val ≤ j.val) + (ht : ∀ k : Fin (m+1), i.val ≤ k.val → k.val < j.val → τ ≤ t e k) : + (realThreshold u v m t τ).Reachable (atVertex u v m e i) (atVertex u v m e j) := by + have aux : ∀ (k : ℕ) (hk : k < m+2), i.val ≤ k → + (∀ q : Fin (m+1), i.val ≤ q.val → q.val < k → τ ≤ t e q) → + (realThreshold u v m t τ).Reachable (atVertex u v m e i) + (atVertex u v m e ⟨k,hk⟩) := by + intro k + induction k with + | zero => + intro hk hik hq + have he : i=⟨0,hk⟩ := Fin.ext (by change i.val = 0; omega) + rw [he] + | succ k ih => + intro hk hik hq + by_cases he : i.val=k+1 + · have hei : i=⟨k+1,hk⟩ := Fin.ext he + rw [hei] + have hki : i.val ≤ k := by omega + have hk' : k < m+2 := by omega + have hk'' : k < m+1 := by omega + have hprior := ih hk' hki (fun q hiq hqk => hq q hiq (by omega)) + apply hprior.trans + by_cases hn : atVertex u v m e ⟨k,hk'⟩ = atVertex u v m e ⟨k+1,hk⟩ + · rw [hn] + · exact SimpleGraph.Adj.reachable ⟨hn,e,⟨k,hk''⟩,rfl,hq ⟨k,hk''⟩ hki (Nat.lt_succ_self k)⟩ + exact aux j.val j.isLt hij ht + +end MatchingFPRAS.RealGeometry + +end OAI diff --git a/lean/OAI/Combinatorics/MatchingCount/Machines/BoolPostCompiler.lean b/lean/OAI/Combinatorics/MatchingCount/Machines/BoolPostCompiler.lean new file mode 100644 index 0000000000000000000000000000000000000000..1167eb87aad2ffdf83cd961efd0f23ab2b959eb4 --- /dev/null +++ b/lean/OAI/Combinatorics/MatchingCount/Machines/BoolPostCompiler.lean @@ -0,0 +1,80 @@ +import Mathlib +import OAI.Combinatorics.MatchingCount.Complexity.GuardMachineBase + +namespace OAI + +namespace MatchingFPRAS.BoolPostCompiler +open Turing MachineCost +open scoped Classical + +def up : PointedMap Bool Symbol := ⟨fun b=>if b then 1 else 0,rfl⟩ +def down : PointedMap Symbol Bool := ⟨fun a=>decide (a=1),rfl⟩ +lemma down_up (b : Bool) : down (up b)=b := by cases b <;> decide +variable {Λ : Type*} [Inhabited Λ] +variable (M : TM0.Machine Bool Λ) (S : Finset Λ) (hS : TM0.Supports M (S : Set Λ)) +def lift : TM0.Machine Symbol Λ := TM0.Machine.map M up down id id +include hS +lemma lift_supported : TM0.Supports (lift M) (S : Set Λ) := by + refine ⟨hS.1,?_⟩ + intro q a q' s he hq + change (q',s) ∈ (M q (down a)).map (Prod.map id (TM0.Stmt.map up)) at he + obtain ⟨⟨r,t⟩,hr,heq⟩:=Option.map_eq_some_iff.mp he + have hqr : r=q' := congrArg Prod.fst heq + subst r + exact hS.2 hr hq +omit hS in +lemma step_map (c : TM0.Cfg Bool Λ) : + (TM0.step M c).map (TM0.Cfg.map up id)= + TM0.step (lift M) (TM0.Cfg.map up id c) := + TM0.Machine.map_step M up down id id (S:=Set.univ) down_up (fun _ _=>rfl) c trivial +omit hS in +lemma advance_map (c : TM0.Cfg Bool Λ) : + advance (TM0.step (lift M)) (TM0.Cfg.map up id c)= + TM0.Cfg.map up id (advance (TM0.step M) c) := by + unfold advance + rw [←step_map] + cases TM0.step M c <;> rfl +omit hS in +lemma run_map (c : TM0.Cfg Bool Λ) (n : ℕ) : + MachineCost.run (TM0.step (lift M)) n (TM0.Cfg.map up id c)= + TM0.Cfg.map up id (MachineCost.run (TM0.step M) n c) := by + induction n generalizing c with + | zero => rfl + | succ n ih => rw [MachineCost.run,advance_map,ih]; rfl +omit hS in +lemma init_map (input : List Bool) : + TM0.Cfg.map (Λ:=Λ) up id (TM0.init input)=TM0.init (input.map up) := by + exact TM0.map_init up ⟨id,rfl⟩ input +noncomputable def compiled : RandomMachine := PostCompiler.sealedMachine (lift M) S + (lift_supported M S hS) + +theorem compiled_words (input output : List Bool) (n t : ℕ) + (hhalt : TM0.step M (MachineCost.run (TM0.step M) n (TM0.init input))=none) + (hout : (MachineCost.run (TM0.step M) n (TM0.init input)).Tape.right₀= + ListBlank.mk output) + (ht : n+2 ≤ t) (bits : Fin t → Bool) : + (MatchingFPRAS.run (compiled M S hS) (input.map up) bits).state=none ∧ + (MatchingFPRAS.run (compiled M S hS) (input.map up) bits).tape.right₀= + ListBlank.mk (output.map up) := by + have he : MachineCost.run (TM0.step (lift M)) n (TM0.init (input.map up))= + TM0.Cfg.map up id (MachineCost.run (TM0.step M) n (TM0.init input)) := by + rw [←init_map,run_map] + have hh : TM0.step (lift M) (MachineCost.run (TM0.step (lift M)) n + (TM0.init (input.map up)))=none := by + rw [he,←step_map,hhalt] + rfl + have ho : (MachineCost.run (TM0.step (lift M)) n + (TM0.init (input.map up))).Tape.right₀=ListBlank.mk (output.map up) := by + rw [he] + change ((MachineCost.run (TM0.step M) n (TM0.init input)).Tape.map up).right₀=_ + have hm : ∀ T : Tape Bool,(T.map up).right₀=T.right₀.map up := by + intro T + obtain ⟨L,R,rfl⟩:=T.exists_mk' + simp only [Tape.map_mk',Tape.mk'_right₀] + rw [hm,hout,ListBlank.map_mk] + exact PostCompiler.words_extend (compiled M S hS) (input.map up) (output.map up) ht bits + (PostCompiler.seal_words (lift M) S (lift_supported M S hS) (input.map up) + (output.map up) n hh ho _) +end MatchingFPRAS.BoolPostCompiler + +end OAI diff --git a/lean/OAI/Combinatorics/MatchingCount/Machines/CoinTM1.lean b/lean/OAI/Combinatorics/MatchingCount/Machines/CoinTM1.lean new file mode 100644 index 0000000000000000000000000000000000000000..ba0d5c9520315125f42df7d3a914fd6ec5966cec --- /dev/null +++ b/lean/OAI/Combinatorics/MatchingCount/Machines/CoinTM1.lean @@ -0,0 +1,100 @@ +import Mathlib +import OAI.Combinatorics.MatchingCount.Complexity.GuardMachineBase +import OAI.Combinatorics.MatchingCount.Machines.PhysicalPost + +namespace OAI + +namespace MatchingFPRAS.CoinTM1 +open Turing MachineCost PhysicalStream + +variable {Γ Λ σ : Type} [Inhabited Γ] + +abbrev Node (Γ Λ σ : Type) := Λ ⊕ TM1.Stmt Γ Λ σ +abbrev State (Γ Λ σ : Type) := Node Γ Λ σ × σ +abbrev Coins (Λ : Type) := Λ → Option (Bool → Λ) + +def aux (a : Γ) : TM1.Stmt Γ Λ σ → σ → Option (State Γ Λ σ × TM0.Stmt Γ) + | .move d q,v => some ((.inr q,v),.move d) + | .write f q,v => some ((.inr q,v),.write (f a v)) + | .load f q,v => aux a q (f a v) + | .branch f q r,v => if f a v then aux a q v else aux a r v + | .goto f,v => some ((.inl (f a v),v),.write a) + | .halt,_ => none + +def table (M : Λ → TM1.Stmt Γ Λ σ) (coin : Coins Λ) : PhysicalPost.Table Γ (State Γ Λ σ) + | (.inl l,v),a,b => match coin l with + | none => aux a (M l) v + | some f => some ((.inl (f b),v),.write a) + | (.inr q,v),a,_ => aux a q v + +def pending (q : TM1.Stmt Γ Λ σ) (v : σ) (T : Tape Γ) : PhysicalPost.Cfg Γ (State Γ Λ σ) := + ⟨some (.inr q,v),T⟩ + +def trCfg (c : TM1.Cfg Γ Λ σ) : PhysicalPost.Cfg Γ (State Γ Λ σ) := + ⟨c.l.map (fun l=>(Sum.inl l,c.var)),c.Tape⟩ + +lemma execute_first_eq (M : PhysicalPost.Table Γ (State Γ Λ σ)) + (x y : PhysicalPost.Cfg Γ (State Γ Λ σ)) (h : ∀ b,PhysicalPost.tick M x b=PhysicalPost.tick M y b) + {n : ℕ} (hn : 0 < n) (b : Stream) : PhysicalPost.execute M n x b=PhysicalPost.execute M n y b := by + cases n with + | zero => omega + | succ n => simp only [PhysicalPost.execute,h] + +theorem statement_ticks (M : Λ → TM1.Stmt Γ Λ σ) (coin : Coins Λ) + (q : TM1.Stmt Γ Λ σ) (v : σ) (T : Tape Γ) : + ∃ k,0 < k ∧ k ≤ statementCost q ∧ ∀ b : Stream, + PhysicalPost.execute (table M coin) k (pending q v T) b=trCfg (TM1.stepAux q v T) := by + induction q generalizing v T with + | move d q ih => + obtain ⟨k,hk,hc,he⟩:=ih v (T.move d) + refine ⟨k+1,by omega,by simp only [statementCost]; omega,fun b=>?_⟩ + simpa only [PhysicalPost.execute,PhysicalPost.tick,pending,table,aux,TM1.stepAux] using he (shift 1 b) + | write f q ih => + obtain ⟨k,hk,hc,he⟩:=ih v (T.write (f T.head v)) + refine ⟨k+1,by omega,by simp only [statementCost]; omega,fun b=>?_⟩ + simpa only [PhysicalPost.execute,PhysicalPost.tick,pending,table,aux,TM1.stepAux] using he (shift 1 b) + | load f q ih => + obtain ⟨k,hk,hc,he⟩:=ih (f T.head v) T + refine ⟨k,hk,hc,fun b=>?_⟩ + rw [execute_first_eq (table M coin) (pending (.load f q) v T) (pending q (f T.head v) T) (fun _=>rfl) hk] + exact he b + | branch f q r ihq ihr => + cases h:f T.head v with + | false => + obtain ⟨k,hk,hc,he⟩:=ihr v T + refine ⟨k,hk,hc.trans (le_max_right _ _),fun b=>?_⟩ + rw [execute_first_eq (table M coin) (pending (.branch f q r) v T) (pending r v T) (fun _=>by + simp only [PhysicalPost.tick,pending,table,aux,h,Bool.false_eq_true,ite_false]) hk] + simpa only [TM1.stepAux,h,Bool.cond_false] using he b + | true => + obtain ⟨k,hk,hc,he⟩:=ihq v T + refine ⟨k,hk,hc.trans (le_max_left _ _),fun b=>?_⟩ + rw [execute_first_eq (table M coin) (pending (.branch f q r) v T) (pending q v T) (fun _=>by + simp only [PhysicalPost.tick,pending,table,aux,h,ite_true]) hk] + simpa only [TM1.stepAux,h,Bool.cond_true] using he b + | goto f => + refine ⟨1,by omega,le_rfl,fun b=>?_⟩ + simp only [PhysicalPost.execute,PhysicalPost.tick,pending,table,aux,TM1.stepAux,trCfg,Option.map_some,Tape.write_self] + | halt => + refine ⟨1,by omega,le_rfl,fun b=>?_⟩ + rfl + +lemma entry_ticks (M : Λ → TM1.Stmt Γ Λ σ) (coin : Coins Λ) + (l : Λ) (v : σ) (T : Tape Γ) (hl : coin l=none) : + ∃ k,0 < k ∧ k ≤ statementCost (M l) ∧ ∀ b : Stream, + PhysicalPost.execute (table M coin) k (trCfg ⟨some l,v,T⟩) b= + trCfg (TM1.stepAux (M l) v T) := by + obtain ⟨k,hk,hc,he⟩:=statement_ticks M coin (M l) v T + refine ⟨k,hk,hc,fun b=>?_⟩ + rw [execute_first_eq (table M coin) (trCfg ⟨some l,v,T⟩) (pending (M l) v T) (fun _=>by + simp only [PhysicalPost.tick,trCfg,Option.map_some,table,hl,pending]) hk] + exact he b + +lemma coin_tick (M : Λ → TM1.Stmt Γ Λ σ) (coin : Coins Λ) + (l : Λ) (v : σ) (T : Tape Γ) (f : Bool → Λ) (hl : coin l=some f) (b : Bool) : + PhysicalPost.tick (table M coin) (trCfg ⟨some l,v,T⟩) b=trCfg ⟨some (f b),v,T⟩ := by + simp only [PhysicalPost.tick,trCfg,Option.map_some,table,hl,Tape.write_self] + +end MatchingFPRAS.CoinTM1 + +end OAI diff --git a/lean/OAI/Combinatorics/MatchingCount/Machines/CoinTM1Finite.lean b/lean/OAI/Combinatorics/MatchingCount/Machines/CoinTM1Finite.lean new file mode 100644 index 0000000000000000000000000000000000000000..ee4a931e0c7bcd72599b2366a412656bffc2d4df --- /dev/null +++ b/lean/OAI/Combinatorics/MatchingCount/Machines/CoinTM1Finite.lean @@ -0,0 +1,85 @@ +import Mathlib +import OAI.Combinatorics.MatchingCount.Machines.CoinTM1 +import OAI.Combinatorics.MatchingCount.Machines.PhysicalRestriction + +namespace OAI + +namespace MatchingFPRAS.CoinTM1 +open Turing +open scoped Classical + +variable {Γ Λ σ : Type} [Inhabited Λ] [Fintype σ] + +noncomputable def nodes (M : Λ → TM1.Stmt Γ Λ σ) (S : Finset Λ) : Finset (Node Γ Λ σ) := + S.disjSum (S.biUnion (fun l=>TM1.stmts₁ (M l))) +noncomputable def states (M : Λ → TM1.Stmt Γ Λ σ) (S : Finset Λ) : Finset (State Γ Λ σ) := + (nodes M S) ×ˢ Finset.univ + +omit [Inhabited Λ] [Fintype σ] in +lemma node_entry {M : Λ → TM1.Stmt Γ Λ σ} {S : Finset Λ} {l : Λ} (h : l∈S) : + Sum.inl l∈nodes M S := by simp only [nodes,Finset.inl_mem_disjSum]; exact h +omit [Inhabited Λ] [Fintype σ] in +lemma node_pending {M : Λ → TM1.Stmt Γ Λ σ} {S : Finset Λ} {q : TM1.Stmt Γ Λ σ} + (h : some q∈TM1.stmts M S) : Sum.inr q∈nodes M S := by + simpa only [nodes,Finset.inr_mem_disjSum,TM1.stmts,Finset.some_mem_insertNone] using h +omit [Inhabited Λ] in +lemma state_mem {M : Λ → TM1.Stmt Γ Λ σ} {S : Finset Λ} {q : Node Γ Λ σ} {v : σ} + (h : q∈nodes M S) : (q,v)∈states M S := by + simp only [states,Finset.mem_product,Finset.mem_univ,and_true]; exact h + +lemma aux_supported {M : Λ → TM1.Stmt Γ Λ σ} {S : Finset Λ} + (hs : TM1.Supports M S) (a : Γ) (q : TM1.Stmt Γ Λ σ) + (hq : some q∈TM1.stmts M S) (v : σ) (q' : State Γ Λ σ) (act : TM0.Stmt Γ) + (he : aux a q v=some (q',act)) : q'∈states M S := by + classical + induction q generalizing v q' act with + | move d q ih => + simp only [aux,Option.some.injEq,Prod.mk.injEq] at he + rcases he with ⟨rfl,rfl⟩ + apply state_mem + apply node_pending + exact TM1.stmts_trans (by simp only [TM1.stmts₁,Finset.mem_insert]; exact Or.inr TM1.stmts₁_self) hq + | write f q ih => + simp only [aux,Option.some.injEq,Prod.mk.injEq] at he + rcases he with ⟨rfl,rfl⟩ + apply state_mem + apply node_pending + exact TM1.stmts_trans (by simp only [TM1.stmts₁,Finset.mem_insert]; exact Or.inr TM1.stmts₁_self) hq + | load f q ih => + exact ih (TM1.stmts_trans (by simp only [TM1.stmts₁,Finset.mem_insert]; exact Or.inr TM1.stmts₁_self) hq) _ _ _ he + | branch f q r ihq ihr => + simp only [aux] at he + split_ifs at he with hf + · exact ihq (TM1.stmts_trans (by simp only [TM1.stmts₁,Finset.mem_insert,Finset.mem_union]; exact Or.inr (Or.inl TM1.stmts₁_self)) hq) _ _ _ he + · exact ihr (TM1.stmts_trans (by simp only [TM1.stmts₁,Finset.mem_insert,Finset.mem_union]; exact Or.inr (Or.inr TM1.stmts₁_self)) hq) _ _ _ he + | goto f => + simp only [aux,Option.some.injEq,Prod.mk.injEq] at he + rcases he with ⟨rfl,rfl⟩ + exact state_mem (node_entry (TM1.stmts_supportsStmt hs hq a v)) + | halt => simp [aux] at he + +theorem table_supported (M : Λ → TM1.Stmt Γ Λ σ) (S : Finset Λ) (hs : TM1.Supports M S) + (coin : Coins Λ) (hc : ∀ l∈S,∀ f,coin l=some f→∀ b,f b∈S) : + PhysicalPost.Supported (table M coin) (states M S) := by + intro q hq a b q' act he + have hn : q.1∈nodes M S := (Finset.mem_product.mp hq).1 + rcases q with ⟨l,v⟩ + cases l with + | inl l => + have hl : l∈S := by simpa only [nodes,Finset.inl_mem_disjSum] using hn + simp only [table] at he + split at he + · apply aux_supported hs a (M l) _ v q' act he + simp only [TM1.stmts,Finset.some_mem_insertNone,Finset.mem_biUnion] + exact ⟨l,hl,TM1.stmts₁_self⟩ + · rename_i f hf + simp only [Option.some.injEq,Prod.mk.injEq] at he + rcases he with ⟨rfl,rfl⟩ + exact state_mem (node_entry (hc l hl f hf b)) + | inr q => + apply aux_supported hs a q _ v q' act he + simpa only [nodes,Finset.inr_mem_disjSum,TM1.stmts,Finset.some_mem_insertNone] using hn + +end MatchingFPRAS.CoinTM1 + +end OAI diff --git a/lean/OAI/Combinatorics/MatchingCount/Machines/FiniteStore.lean b/lean/OAI/Combinatorics/MatchingCount/Machines/FiniteStore.lean new file mode 100644 index 0000000000000000000000000000000000000000..5afa6431a2851c19165ce1e6420750147bd6f565 --- /dev/null +++ b/lean/OAI/Combinatorics/MatchingCount/Machines/FiniteStore.lean @@ -0,0 +1,82 @@ +import Mathlib +import OAI.Combinatorics.MatchingCount.Machines.RegisterProc + +namespace OAI + +namespace MatchingFPRAS.FiniteStore +open Turing MachineCost RegisterProc + +variable {K Λ σ : Type} [DecidableEq K] + +def stmt : TM2.Stmt (fun _ : K=>Bool) Λ σ → σ → + TM2.Stmt (fun _ : K=>Bool) (Λ×σ) (Option Bool) + | .push k f q,v => .push k (fun _=>f v) (stmt q v) + | .peek k f q,v => .peek k (fun _ x=>x) + (.branch Option.isNone (stmt q (f v none)) + (.branch (fun x=>x.getD false) (stmt q (f v (some true))) (stmt q (f v (some false))))) + | .pop k f q,v => .pop k (fun _ x=>x) + (.branch Option.isNone (stmt q (f v none)) + (.branch (fun x=>x.getD false) (stmt q (f v (some true))) (stmt q (f v (some false))))) + | .load f q,v => stmt q (f v) + | .branch f q r,v => if f v then stmt q v else stmt r v + | .goto f,v => .load (fun _=>none) (.goto (fun _=>(f v,v))) + | .halt,_ => .load (fun _=>none) .halt + +def cfg (c : TM2.Cfg (fun _ : K=>Bool) Λ σ) : + TM2.Cfg (fun _ : K=>Bool) (Λ×σ) (Option Bool) := + ⟨c.l.map (fun l=>(l,c.var)),none,c.stk⟩ + +theorem stmt_eval (q : TM2.Stmt (fun _ : K=>Bool) Λ σ) (v : σ) (u : Option Bool) + (S : K→List Bool) : TM2.stepAux (stmt q v) u S=cfg (TM2.stepAux q v S) := by + induction q generalizing v u S with + | push k f q ih => simpa only [stmt,TM2.stepAux] using ih v u (Function.update S k (f v::S k)) + | peek k f q ih => + cases hh : (S k).head? with + | none => simpa only [stmt,TM2.stepAux,hh,Option.isNone_none,Bool.cond_true] using ih (f v none) none S + | some b => cases b <;> simpa only [stmt,TM2.stepAux,hh,Option.isNone_some,Bool.cond_false, + Option.getD_some,Bool.cond_true] using ih (f v (S k).head?) (S k).head? S + | pop k f q ih => + cases hh : (S k).head? with + | none => simpa only [stmt,TM2.stepAux,hh,Option.isNone_none,Bool.cond_true] using ih (f v none) none (Function.update S k (S k).tail) + | some b => cases b <;> simpa only [stmt,TM2.stepAux,hh,Option.isNone_some,Bool.cond_false, + Option.getD_some,Bool.cond_true] using ih (f v (S k).head?) (S k).head? (Function.update S k (S k).tail) + | load f q ih => exact ih (f v) u S + | branch f q r ihq ihr => + cases hh : f v with + | false => simpa only [stmt,TM2.stepAux,hh,Bool.false_eq_true,↓reduceIte,Bool.cond_false] using ihr v u S + | true => simpa only [stmt,TM2.stepAux,hh,↓reduceIte,Bool.cond_true] using ihq v u S + | goto f => rfl + | halt => rfl + +def program (M : Λ→TM2.Stmt (fun _ : K=>Bool) Λ σ) : + Λ×σ→TM2.Stmt (fun _ : K=>Bool) (Λ×σ) (Option Bool) := fun p=>stmt (M p.1) p.2 +lemma advance_cfg (M : Λ→TM2.Stmt (fun _ : K=>Bool) Λ σ) + (c : TM2.Cfg (fun _ : K=>Bool) Λ σ) : + advance (TM2.step (program M)) (cfg c)=cfg (advance (TM2.step M) c) := by + rcases c with ⟨l,v,S⟩ + cases l with + | none => rfl + | some l => exact stmt_eval (M l) v none S +lemma run_cfg (M : Λ→TM2.Stmt (fun _ : K=>Bool) Λ σ) (n : ℕ) + (c : TM2.Cfg (fun _ : K=>Bool) Λ σ) : + MachineCost.run (TM2.step (program M)) n (cfg c)=cfg (MachineCost.run (TM2.step M) n c) := by + induction n generalizing c with + | zero => rfl + | succ n ih => rw [MachineCost.run,advance_cfg,ih,MachineCost.run] + +def procedure [Fintype Λ] [DecidableEq Λ] [Inhabited Λ] [Fintype σ] [DecidableEq σ] + (M : Λ→TM2.Stmt (fun _ : K=>Bool) Λ σ) (v : σ) : Proc K := + { Label := Λ×σ + labels := inferInstance + entry := ⟨(default,v)⟩ + code := program M } + +theorem exec [Fintype Λ] [DecidableEq Λ] [Inhabited Λ] [Fintype σ] [DecidableEq σ] + (M : Λ→TM2.Stmt (fun _ : K=>Bool) Λ σ) (v w : σ) (A B : Stack K) (n : ℕ) + (h : MachineCost.run (TM2.step M) n ⟨some default,v,A⟩=⟨none,w,B⟩) : + Exec (procedure M v) A B n := by + refine ⟨n,le_rfl,?_⟩ + exact (run_cfg M n ⟨some default,v,A⟩).trans (congrArg cfg h) +end MatchingFPRAS.FiniteStore + +end OAI diff --git a/lean/OAI/Combinatorics/MatchingCount/Machines/OnlineBounds.lean b/lean/OAI/Combinatorics/MatchingCount/Machines/OnlineBounds.lean new file mode 100644 index 0000000000000000000000000000000000000000..05c3225b93b328d1a11450ddc353881cb5aba0b0 --- /dev/null +++ b/lean/OAI/Combinatorics/MatchingCount/Machines/OnlineBounds.lean @@ -0,0 +1,69 @@ +import Mathlib +import OAI.Combinatorics.MatchingCount.Algorithm.OnlineInitialLaw +import OAI.Combinatorics.MatchingCount.Complexity.OnlineInitialCost +import OAI.Combinatorics.MatchingCount.Algorithm.OnlineHistorySize + +namespace OAI + +namespace MatchingFPRAS.OnlineSourceBounds +open BitComplexity Transport Polynomial TreeTyped + +def normBound (x : ℕ) : ℕ := + 2*x+boundK x+boundN x+boundD x+boundS x+ + tierPolynomial (boundN x) (boundD x) (boundK x)+ + ladderQ (boundN x) (boundD x)+(2*x)^2+3 +lemma normBound_polynomial : PolynomiallyBounded normBound := by + have hn := (PolynomiallyBounded.const 2).mul PolynomiallyBounded.id + exact ((((((((hn.add boundK_polynomial).add boundN_polynomial).add boundD_polynomial).add boundS_polynomial).add + (tier_polynomial boundN_polynomial boundD_polynomial boundK_polynomial)).add + (ladderQ_polynomial boundN_polynomial boundD_polynomial)).add (hn.pow 2)).add (PolynomiallyBounded.const 3)) +lemma polynomial_bound {f : ℕ→ℕ} (h : PolynomiallyBounded f) : + ∃ q : Polynomial ℕ,∀ x,1≤x→f x≤q.eval x := by + obtain ⟨C,d,h⟩:=h + exact ⟨Polynomial.C C*Polynomial.X^d,fun x hx=>by simpa using h x hx⟩ +variable {G : GraphInput} [Nontrivial (Fin G.n)] +lemma norm_le (hn : 2≤G.n) (hev : Even G.n) (ε : ℚ) (he : 0<ε) (he1 : ε<1) + (x : ℕ) (hnx : G.n≤2*x) (hex : ⌈ε⁻¹⌉₊≤x) (g : ExecutableAdaptive.GraphData) : + OnlineTrial.sizeNorm (FiniteTrial.parameters G hn hev ε he he1) g≤normBound x+weight g := by + let p:=FiniteTrial.parameters G hn hev ε he he1 + have hk:=parameters_K_le hn hev ε he he1 x hnx hex + have hN:=parameters_N_le p x hnx hk + have hD:=parameters_D_le p x hnx hN + have hS:=parameters_S_le p x hnx hk hD hex + have hT : p.T≤tierPolynomial (boundN x) (boundD x) (boundK x) := by + have ht := endpoint_le_polynomial p.N p.D p.K p.N_pos + rw [endpoint_eq] at ht + apply ht.trans + unfold tierPolynomial + gcongr + have hq : p.q≤ladderQ (boundN x) (boundD x) := by + change ladderQ p.N p.D≤_ + unfold ladderQ ladderL + gcongr + have hz : (Z (completeGraph G.n)+1).size≤(2*x)^2+3 := by + apply (BitArithmetic.complete_count_size G.n).trans + have hs : G.n.size≤G.n := Nat.size_le.mpr Nat.lt_two_pow_self + have hd : G.n/2≤G.n := Nat.div_le_self _ _ + calc + _≤G.n*G.n+3 := by gcongr + _≤(2*x)^2+3 := by rw [pow_two];gcongr + unfold OnlineTrial.sizeNorm normBound + dsimp only [p] at * + omega + +lemma numeric_le (hn : 2≤G.n) (hev : Even G.n) (ε δ : ℚ) (he : 0<ε) (he1 : ε<1) + (x : ℕ) (hnx : G.n≤2*x) (hex : ⌈ε⁻¹⌉₊≤x) : + OnlineInitial.configNumeric (OnlineInitial.config (OnlineInitial.sourceSeed (G:=G) ε δ))≤normBound x := by + let p:=FiniteTrial.parameters G hn hev ε he he1 + rw [OnlineInitial.config_source hn hev ε δ he he1] + dsimp only [OnlineInitial.configNumeric,OnlineInitial.sourceSeed] + have hl : (ExecutableAdaptive.graphRep G).1.length=G.n := by simp [ExecutableAdaptive.graphRep] + rw [hl,OnlineSchedule.ladderSchedule_eq _ _ _ p.N_pos,endpoint_eq,FiniteTrial.sourceD_eq] + have hs:=norm_le hn hev ε he he1 x hnx hex (ExecutableAdaptive.graphRep G) + unfold OnlineTrial.sizeNorm at hs + change G.n+p.K+p.N+p.D+p.T+p.q≤normBound x + dsimp only [p] at * + omega +end MatchingFPRAS.OnlineSourceBounds + +end OAI diff --git a/lean/OAI/Combinatorics/MatchingCount/Machines/OnlineCase.lean b/lean/OAI/Combinatorics/MatchingCount/Machines/OnlineCase.lean new file mode 100644 index 0000000000000000000000000000000000000000..9a95f14ac14a45e60c33b802df2e4966a990a3ef --- /dev/null +++ b/lean/OAI/Combinatorics/MatchingCount/Machines/OnlineCase.lean @@ -0,0 +1,84 @@ +import Mathlib +import OAI.Combinatorics.MatchingCount.Machines.OnlineTree +import OAI.Combinatorics.MatchingCount.Machines.OnlineControl + +namespace OAI + +namespace MatchingFPRAS.OnlineTree +open TreeData TreeMachine RegisterProc TreeFunction TreeTyped +open Turing MachineCost PhysicalStream OnlineStack + +variable {A B : Type} [Codec A] [Codec B] +namespace Case +open OnlineControl + +inductive Point where | split | test | yesClear | noClear | yes | no | halt + deriving DecidableEq, Inhabited +instance : Fintype Point := ⟨{.split,.test,.yesClear,.noClear,.yes,.no,.halt},by intro p;cases p <;>simp⟩ +def code (P Q : OnlineProc.Proc (K Reg)) : Point→OnlineControl.Instr Reg Point + | .split => .call (OnlineProc.deterministic (TreeFunction.split 1 0 (by decide))) .test + | .test => .branch 1 .noClear .yesClear + | .yesClear => .call (OnlineProc.deterministic (TreeFunction.clear 1)) .yes + | .noClear => .call (OnlineProc.deterministic (TreeFunction.clear 1)) .no + | .yes => .call P .halt + | .no => .call Q .halt + | .halt => .halt +lemma runs {f g : A→Experiment B} (F : Realizer f) (G : Realizer g) (b : Bool) (a : A) (s : Data) : + ∃ q,At (code F.program G.program) (fun y=>env (encode y) .nil s) (Option.some Point.split) + (env (encode (b,a)) .nil s) q ∧ + (∀ h : B→ℚ,q.mean h=(if b then f a else g a).mean h) ∧ + q.cost≤(if b then F.cost a else G.cost a)+30 := by + let M:=code F.program G.program + let out:=fun y : B=>env (encode y) .nil s + have hend y:=OnlineControl.halt M out Point.halt rfl y + cases b with + | false => + obtain ⟨r,hr,hm,hc⟩:=G.correct a s + have hb:=call M out Point.no Point.halt G.program rfl (env (encode a) .nil s) + (fun y=>env (encode y) .nil s) r hr (fun y=>.delay 1 (.done y)) hend + obtain ⟨q,hq,hqm,hqc⟩:=deterministicCall M out Point.noClear Point.no + (TreeFunction.clear 1) rfl _ _ _ (clear1 (encode a) (encode false) s) _ hb + have ht:=nilBranch M out Point.test Point.noClear Point.yesClear 1 rfl _ rfl _ hq + obtain ⟨v,hv,hvm,hvc⟩:=deterministicCall M out Point.split Point.test + (TreeFunction.split 1 0 (by decide)) rfl _ _ _ (split10 (encode false) (encode a) .nil s) _ ht + refine ⟨v,hv,?_,?_⟩ + · intro h + rw [hvm,Experiment.mean,hqm,Experiment.mean,Experiment.mean_bind] + exact hm h + · have hh:=Experiment.cost_bind_le r (fun y=>.delay 1 (.done y)) 1 (fun _=>by rfl) + simp only [Experiment.cost] at hqc hvc + change v.cost≤G.cost a+30 + change q.cost≤1+2+1+(1+(r.bind (fun y=>.delay 1 (.done y))).cost) at hqc + change v.cost≤1+2*1+4+1+(1+q.cost) at hvc + omega + | true => + obtain ⟨r,hr,hm,hc⟩:=F.correct a s + have hb:=call M out Point.yes Point.halt F.program rfl (env (encode a) .nil s) + (fun y=>env (encode y) .nil s) r hr (fun y=>.delay 1 (.done y)) hend + obtain ⟨q,hq,hqm,hqc⟩:=deterministicCall M out Point.yesClear Point.yes + (TreeFunction.clear 1) rfl _ _ _ (clear1 (encode a) (encode true) s) _ hb + have ht:=consBranch M out Point.test Point.noClear Point.yesClear 1 rfl _ .nil .nil rfl _ hq + obtain ⟨v,hv,hvm,hvc⟩:=deterministicCall M out Point.split Point.test + (TreeFunction.split 1 0 (by decide)) rfl _ _ _ (split10 (encode true) (encode a) .nil s) _ ht + refine ⟨v,hv,?_,?_⟩ + · intro h + rw [hvm,Experiment.mean,hqm,Experiment.mean,Experiment.mean_bind] + exact hm h + · have hh:=Experiment.cost_bind_le r (fun y=>.delay 1 (.done y)) 1 (fun _=>by rfl) + simp only [Experiment.cost] at hqc hvc + change v.cost≤F.cost a+30 + change q.cost≤3+2+1+(1+(r.bind (fun y=>.delay 1 (.done y))).cost) at hqc + change v.cost≤1+2*3+4+1+(1+q.cost) at hvc + omega +end Case +noncomputable def caseBool {f g : A→Experiment B} (F : Realizer f) (G : Realizer g) : + Realizer (fun x : Bool×A=>if x.1 then f x.2 else g x.2) where + program := OnlineControl.compile (Case.code F.program G.program) + cost := fun x=>(if x.1 then F.cost x.2 else G.cost x.2)+30 + correct := fun x s=>Case.runs F G x.1 x.2 s +noncomputable def conditional {p : A→Bool} {f g : A→Experiment B} (P : TreeTyped.Realizer p) + (F : Realizer f) (G : Realizer g) : Realizer (fun a=>if p a then f a else g a) := + (composition (deterministic (TreeTyped.pair P TreeTyped.identity)) (caseBool F G)).congr (fun _ _=>rfl) +end MatchingFPRAS.OnlineTree + +end OAI diff --git a/lean/OAI/Combinatorics/MatchingCount/Machines/OnlineControl.lean b/lean/OAI/Combinatorics/MatchingCount/Machines/OnlineControl.lean new file mode 100644 index 0000000000000000000000000000000000000000..aa3b405dec04ef484cfca9348ac5bffefec979a4 --- /dev/null +++ b/lean/OAI/Combinatorics/MatchingCount/Machines/OnlineControl.lean @@ -0,0 +1,106 @@ +import Mathlib +import OAI.Combinatorics.MatchingCount.Machines.TreeCompiler +import OAI.Combinatorics.MatchingCount.Tapes.OnlineComposition + +namespace OAI + +namespace MatchingFPRAS.OnlineControl +open TreeData TreeMachine RegisterProc Turing MachineCost PhysicalStream OnlineStack + +variable {R Λ α : Type} [DecidableEq R] +inductive Instr (R Λ : Type) where + | halt + | go (next : Λ) + | branch (i : R) (nil cons : Λ) + | call (P : OnlineProc.Proc (K R)) (next : Λ) + +def procedure : Instr R Λ → OnlineProc.Proc (K R) + | .call P _ => P + | _ => OnlineProc.deterministic (atom .halt) +def successor : Instr R Λ → Option Λ + | .call _ l => some l + | _ => none +abbrev Label (M : Λ → Instr R Λ) := Λ ⊕ ((l : Λ) × (procedure (M l)).Label) +instance (M : Λ → Instr R Λ) [Fintype Λ] : Fintype (Label M) := by unfold Label; infer_instance + +def code (M : Λ → Instr R Λ) : Label M → TM2.Stmt (fun _ : K R=>Bool) (Label M) Store + | .inl l => match M l with + | .halt => .halt + | .go k => .goto (fun _=>.inl k) + | .branch i a b => .peek (.inl i) (fun _ x=>x) (.branch (fun x=>x.getD false) + (.load (fun _=>none) (.goto (fun _=>.inl b))) + (.load (fun _=>none) (.goto (fun _=>.inl a)))) + | .call _ _ => .goto (fun _=>.inr ⟨l,default⟩) + | .inr ⟨l,u⟩ => StackComposition.relabel (fun u=>.inr ⟨l,u⟩) + ((successor (M l)).map Sum.inl) ((procedure (M l)).code u) +def coins (M : Λ → Instr R Λ) : CoinTM1.Coins (Label M) + | .inl _ => none + | .inr ⟨l,u⟩ => ((procedure (M l)).coin u).map (fun g b=>.inr ⟨l,g b⟩) +def compile [Fintype Λ] [Inhabited Λ] (M : Λ → Instr R Λ) : OnlineProc.Proc (K R) := + { toProc := { Label := Label M, entry := ⟨.inl default⟩, code := code M }, coin := coins M } +def cfg (M : Λ → Instr R Λ) (l : Option Λ) (E : Env R) : TM2.Cfg (fun _ : K R=>Bool) (Label M) Store := + ⟨l.map Sum.inl,none,encodeEnv E⟩ +def At (M : Λ → Instr R Λ) (out : α → Env R) (l : Option Λ) (E : Env R) (p : Experiment α) : Prop := + Executes (code M) (coins M) (fun a=>cfg M none (out a)) (cfg M l E) p + +lemma done (M : Λ → Instr R Λ) (out : α → Env R) (a : α) : + At M out none (out a) (.done a) := .done a +lemma halt (M : Λ → Instr R Λ) (out : α → Env R) (l : Λ) (h : M l=.halt) (a : α) : + At M out (some l) (out a) (.delay 1 (.done a)) := by + apply Executes.step _ _ _ _ rfl + simpa only [At,code,h,TM2.stepAux,cfg,Option.map_none] using done M out a +lemma go (M : Λ → Instr R Λ) (out : α → Env R) (l k : Λ) (h : M l=.go k) + (E : Env R) (p : Experiment α) (hp : At M out (some k) E p) : + At M out (some l) E (.delay 1 p) := by + apply Executes.step _ _ _ _ rfl + simpa only [At,code,h,TM2.stepAux,cfg,Option.map_some] using hp +lemma nilBranch (M : Λ → Instr R Λ) (out : α → Env R) (l a b : Λ) (i : R) + (h : M l=.branch i a b) (E : Env R) (hi : E i=.nil) + (p : Experiment α) (hp : At M out (some a) E p) : + At M out (some l) E (.delay 1 p) := by + apply Executes.step _ _ _ _ rfl + simpa only [At,code,h,TM2.stepAux,encodeEnv,hi,encode,List.head?_cons,Option.getD_some,Bool.cond_false, + cfg,Option.map_some] using hp +lemma consBranch (M : Λ → Instr R Λ) (out : α → Env R) (l a b : Λ) (i : R) + (h : M l=.branch i a b) (E : Env R) (x y : Data) (hi : E i=.cons x y) + (p : Experiment α) (hp : At M out (some b) E p) : + At M out (some l) E (.delay 1 p) := by + apply Executes.step _ _ _ _ rfl + simpa only [At,code,h,TM2.stepAux,encodeEnv,hi,encode,List.head?_cons,Option.getD_some,Bool.cond_true, + cfg,Option.map_some] using hp + +lemma call {β : Type} (M : Λ → Instr R Λ) (out : α → Env R) (l next : Λ) + (P : OnlineProc.Proc (K R)) (h : M l=.call P next) + (E : Env R) (F : β → Env R) (q : Experiment β) + (hq : Executes P.code P.coin (fun b=>⟨none,none,encodeEnv (F b)⟩) + ⟨some default,none,encodeEnv E⟩ q) + (p : β → Experiment α) (hp : ∀ b,At M out (some next) (F b) (p b)) : + At M out (some l) E (.delay 1 (q.bind p)) := by + have hq' : Executes (procedure (M l)).code (procedure (M l)).coin + (fun b=>⟨none,none,encodeEnv (F b)⟩) ⟨some default,none,encodeEnv E⟩ q := by + rw [show procedure (M l)=P by rw [h]; rfl] + exact hq + have hh := hq'.relabel (code M) (coins M) (fun u=>Sum.inr ⟨l,u⟩) + ((successor (M l)).map Sum.inl) (fun _=>rfl) (fun _=>rfl) + apply Executes.step _ _ _ _ rfl + have hb := hh.bind p (fun a=>cfg M none (out a)) (fun b=>by + simpa only [At,cfg,Option.map_none,StackComposition.mapCfg_none,h,successor,Option.map_some] using hp b) + simpa only [code,h,TM2.stepAux,StackComposition.mapCfg_some] using hb + +lemma deterministicCall (M : Λ → Instr R Λ) (out : α → Env R) (l next : Λ) + (P : RegisterProc.Proc (K R)) (h : M l=.call (OnlineProc.deterministic P) next) + (E F : Env R) (n : ℕ) (he : RegisterProc.Exec P (encodeEnv E) (encodeEnv F) n) + (p : Experiment α) (hp : At M out (some next) F p) : + ∃ q,At M out (some l) E q ∧ (∀ f : α → ℚ,q.mean f=p.mean f) ∧ q.cost ≤ n+1+p.cost := by + obtain ⟨k,hk,he⟩:=he + obtain ⟨r,hr,hm,hc⟩:=Executes.of_run P.code k _ _ _ he + refine ⟨.delay 1 (r.bind (fun _=>p)),call M out l next (OnlineProc.deterministic P) h E (fun _ : Unit=>F) + r hr (fun _=>p) (fun _=>hp),?_,?_⟩ + · intro f + simpa only [Experiment.mean,Experiment.mean_bind] using hm (fun _=>p.mean f) + · have hh:=Experiment.cost_bind_le r (fun _=>p) p.cost (fun _=>le_rfl) + simp only [Experiment.cost] + omega +end MatchingFPRAS.OnlineControl + +end OAI diff --git a/lean/OAI/Combinatorics/MatchingCount/Machines/OnlineFold.lean b/lean/OAI/Combinatorics/MatchingCount/Machines/OnlineFold.lean new file mode 100644 index 0000000000000000000000000000000000000000..2d5f214a19af3402090840b240c683dc355a8e15 --- /dev/null +++ b/lean/OAI/Combinatorics/MatchingCount/Machines/OnlineFold.lean @@ -0,0 +1,116 @@ +import Mathlib +import OAI.Combinatorics.MatchingCount.Machines.OnlineTree +import OAI.Combinatorics.MatchingCount.Machines.OnlineControl + +namespace OAI + +namespace MatchingFPRAS.OnlineTree +open TreeData TreeMachine RegisterProc TreeFunction TreeTyped +open Turing MachineCost PhysicalStream OnlineStack + +variable {A B : Type} [Codec A] [Codec B] + +def foldM (f : A×B → Experiment B) : List A → B → Experiment B + | [],b => .done b + | a::as,b => (f (a,b)).bind (foldM f as) +namespace Fold +open OnlineControl +open TreeTyped.Fold (Point) + +def code (P : OnlineProc.Proc (K Reg)) : Point → OnlineControl.Instr Reg Point + | .loop => .call (OnlineProc.deterministic (TreeFunction.split 1 0 (by decide))) .check + | .check => .branch 1 .halt .splitHead + | .splitHead => .call (OnlineProc.deterministic (TreeFunction.split 3 1 (by decide))) .pushTail + | .pushTail => .call (OnlineProc.deterministic (TreeFunction.cons 1 2 (by decide))) .pushArgs + | .pushArgs => .call (OnlineProc.deterministic (TreeFunction.cons 3 0 (by decide))) .body + | .body => .call P .popTail + | .popTail => .call (OnlineProc.deterministic (TreeFunction.split 1 2 (by decide))) .rebuild + | .rebuild => .call (OnlineProc.deterministic (TreeFunction.cons 1 0 (by decide))) .loop + | .halt => .halt +noncomputable def cost (f : A×B → Experiment B) (t : A×B → ℕ) : List A → B → ℕ + | [],_ => 10 + | a::as,b => t (a,b)+6*TreeFunction.size (encode a)+8*TreeFunction.size (encode as)+34+ + (f (a,b)).worst (cost f t as) + +lemma runs {f : A×B → Experiment B} (F : Realizer f) (as : List A) (b : B) (s : Data) : + ∃ q,At (code F.program) (fun b=>env (encode b) .nil s) (Option.some Point.loop) + (env (encode (as,b)) .nil s) q ∧ + (∀ g : B → ℚ,q.mean g=(foldM f as b).mean g) ∧ q.cost ≤ cost f F.cost as b := by + induction as generalizing b with + | nil => + have hh := OnlineControl.halt (code F.program) (fun b=>env (encode b) .nil s) Point.halt rfl b + have hc := OnlineControl.nilBranch (code F.program) (fun b=>env (encode b) .nil s) + Point.check Point.halt Point.splitHead 1 rfl _ rfl _ hh + obtain ⟨q,hq,hm,hcost⟩:=deterministicCall (code F.program) (fun b=>env (encode b) .nil s) + Point.loop Point.check (TreeFunction.split 1 0 (by decide)) rfl _ _ _ + (split10 .nil (encode b) .nil s) _ hc + refine ⟨q,hq,?_,?_⟩ + · intro g; simpa only [Experiment.mean,foldM] using hm g + · simpa only [cost,size_nil,Experiment.cost] using hcost + | cons a as ih => + choose q hq hm hcost using ih + let out := fun b : B=>env (encode b) .nil s + let M := code F.program + let sr := TreeFunction.size (encode as) + let sa := TreeFunction.size (encode a) + have hreb v := deterministicCall M out Point.rebuild Point.loop + (TreeFunction.cons 1 0 (by decide)) rfl _ _ _ + (cons10 (encode v) (encode as) s) (q v) (hq v) + choose qr hr hmr hcr using hreb + have hpop v := deterministicCall M out Point.popTail Point.rebuild + (TreeFunction.split 1 2 (by decide)) rfl _ _ _ + (split12 (encode v) .nil (encode as) s) (qr v) (hr v) + choose qp hp hmp hcp using hpop + obtain ⟨r,hrf,hrm,hrc⟩:=F.correct (a,b) (.cons (encode as) s) + have hbody := call M out Point.body Point.popTail F.program rfl + (env (encode (a,b)) .nil (.cons (encode as) s)) + (fun v=>env (encode v) .nil (.cons (encode as) s)) r hrf qp hp + have h4 := TreeTyped.Fold.pushArgs (encode a) (encode b) (encode as) s + obtain ⟨p4,hp4,hm4,hc4⟩:=deterministicCall M out Point.pushArgs Point.body + (TreeFunction.cons 3 0 (by decide)) rfl _ _ _ h4 _ hbody + have h5 := TreeTyped.Fold.pushTail (encode a) (encode b) (encode as) s + obtain ⟨p5,hp5,hm5,hc5⟩:=deterministicCall M out Point.pushTail Point.pushArgs + (TreeFunction.cons 1 2 (by decide)) rfl _ _ _ h5 _ hp4 + have h6 := TreeTyped.Fold.splitHeads (encode a) (encode b) (encode as) s + obtain ⟨p6,hp6,hm6,hc6⟩:=deterministicCall M out Point.splitHead Point.pushTail + (TreeFunction.split 3 1 (by decide)) rfl _ _ _ h6 _ hp5 + have hc := OnlineControl.consBranch M out Point.check Point.halt Point.splitHead + 1 rfl (env (encode b) (encode (a::as)) s) (encode a) (encode as) rfl p6 hp6 + obtain ⟨p7,hp7,hm7,hc7⟩:=deterministicCall M out Point.loop Point.check + (TreeFunction.split 1 0 (by decide)) rfl _ _ _ + (split10 (encode (a::as)) (encode b) .nil s) _ hc + refine ⟨p7,hp7,?_,?_⟩ + · intro g + rw [hm7,Experiment.mean,hm6,hm5,hm4,Experiment.mean,Experiment.mean_bind] + simp_rw [hmp,hmr,hm] + simpa only [foldM,Experiment.mean_bind] using hrm (fun v=>(foldM f as v).mean g) + · have hcq : ∀ v,(qp v).cost ≤ 4*sr+10+cost f F.cost as v := by + intro v + have hr':=(hcr v) + have hp':=(hcp v) + have ht:=hcost v + simp only [size_nil] at hp' + dsimp [sr] at * + omega + have ha : r.All (fun v=>(qp v).cost ≤ 4*sr+10+(f (a,b)).worst (cost f F.cost as)) := by + apply (Experiment.all_of_mean_eq hrm _ (Experiment.all_worst (f (a,b)) (cost f F.cost as))).mono + intro v hv + exact (hcq v).trans (Nat.add_le_add_left hv _) + have hbind:=Experiment.cost_bind_le_of_all r qp _ ha + simp only [Experiment.cost,size_nil,encode_list_cons,size_cons] at hc4 hc7 + simp only [cost] + dsimp [sr,sa] at * + omega +end Fold + +noncomputable def fold {f : A×B → Experiment B} (F : Realizer f) : + Realizer (fun ab : List A×B=>foldM f ab.1 ab.2) where + program := OnlineControl.compile (Fold.code F.program) + cost := fun ab=>Fold.cost f F.cost ab.1 ab.2 + correct := by + intro ab s + obtain ⟨q,hq,hm,hc⟩:=Fold.runs F ab.1 ab.2 s + exact ⟨q,hq,hm,hc⟩ +end MatchingFPRAS.OnlineTree + +end OAI diff --git a/lean/OAI/Combinatorics/MatchingCount/Machines/OnlineFrame.lean b/lean/OAI/Combinatorics/MatchingCount/Machines/OnlineFrame.lean new file mode 100644 index 0000000000000000000000000000000000000000..2fe8d79039ab163a5d6a7eed7b289cf8756f9d24 --- /dev/null +++ b/lean/OAI/Combinatorics/MatchingCount/Machines/OnlineFrame.lean @@ -0,0 +1,83 @@ +import Mathlib +import OAI.Combinatorics.MatchingCount.Machines.OnlineTree +import OAI.Combinatorics.MatchingCount.Machines.OnlineControl + +namespace OAI + +namespace MatchingFPRAS.OnlineTree +open TreeData TreeMachine RegisterProc TreeFunction TreeTyped +open Turing MachineCost PhysicalStream OnlineStack + +variable {A B C D : Type} [Codec A] [Codec B] [Codec C] [Codec D] +namespace Second +open OnlineControl + +inductive Point where | split | save | body | pop | cons | halt + deriving DecidableEq, Inhabited +instance : Fintype Point := ⟨{.split,.save,.body,.pop,.cons,.halt},by intro p; cases p <;> simp⟩ +def code (P : OnlineProc.Proc (K Reg)) : Point → OnlineControl.Instr Reg Point + | .split => .call (OnlineProc.deterministic (TreeFunction.split 1 0 (by decide))) .save + | .save => .call (OnlineProc.deterministic (TreeFunction.cons 1 2 (by decide))) .body + | .body => .call P .pop + | .pop => .call (OnlineProc.deterministic (TreeFunction.split 1 2 (by decide))) .cons + | .cons => .call (OnlineProc.deterministic (TreeFunction.cons 1 0 (by decide))) .halt + | .halt => .halt +lemma runs {f : B → Experiment C} (F : Realizer f) (a : A) (b : B) (s : Data) : + ∃ q,At (code F.program) (fun ac : A×C=>env (encode ac) .nil s) (Option.some Point.split) + (env (encode (a,b)) .nil s) q ∧ + (∀ g : A×C → ℚ,q.mean g=(f b).mean (fun c=>g (a,c))) ∧ + q.cost ≤ F.cost b+8*TreeFunction.size (encode a)+22 := by + let M:=code F.program + let out:=fun ac : A×C=>env (encode ac) .nil s + have hend c:=OnlineControl.halt M out Point.halt rfl (a,c) + have hcons c:=deterministicCall M out Point.cons Point.halt + (TreeFunction.cons 1 0 (by decide)) rfl _ _ _ (cons10 (encode c) (encode a) s) _ (hend c) + choose pc hc hmc hcc using hcons + have hpop c:=deterministicCall M out Point.pop Point.cons + (TreeFunction.split 1 2 (by decide)) rfl _ _ _ (split12 (encode c) .nil (encode a) s) _ (hc c) + choose pp hp hmp hcp using hpop + obtain ⟨r,hr,hmr,hcr⟩:=F.correct b (.cons (encode a) s) + have hbody:=call M out Point.body Point.pop F.program rfl + (env (encode b) .nil (.cons (encode a) s)) (fun c=>env (encode c) .nil (.cons (encode a) s)) + r hr pp hp + obtain ⟨p2,hp2,hm2,hc2⟩:=deterministicCall M out Point.save Point.body + (TreeFunction.cons 1 2 (by decide)) rfl _ _ _ (cons12 (encode b) (encode a) s) _ hbody + obtain ⟨p1,hp1,hm1,hc1⟩:=deterministicCall M out Point.split Point.save + (TreeFunction.split 1 0 (by decide)) rfl _ _ _ (split10 (encode a) (encode b) .nil s) _ hp2 + refine ⟨p1,hp1,?_,?_⟩ + · intro g + rw [hm1,hm2,Experiment.mean,Experiment.mean_bind] + simp_rw [hmp,hmc,Experiment.mean] + exact hmr _ + · have hb : ∀ c,(pp c).cost ≤ 4*TreeFunction.size (encode a)+11 := by + intro c + have h1:=hcc c + have h2:=hcp c + simp only [Experiment.cost,size_nil] at h1 h2 + omega + have hbind:=Experiment.cost_bind_le r pp _ hb + simp only [Experiment.cost,size_nil] at hc1 hc2 + omega +end Second + +noncomputable def mapSecond {f : B → Experiment C} (F : Realizer f) : + Realizer (fun ab : A×B=>(f ab.2).map (Prod.mk ab.1)) where + program := OnlineControl.compile (Second.code F.program) + cost := fun ab=>F.cost ab.2+8*TreeFunction.size (encode ab.1)+22 + correct := by + intro ab s + obtain ⟨q,hq,hm,hc⟩:=Second.runs F ab.1 ab.2 s + exact ⟨q,hq,fun g=>by rw [Experiment.mean_map]; exact hm g,hc⟩ + +noncomputable def pair {f : A → Experiment B} {g : A → Experiment C} + (F : Realizer f) (G : Realizer g) : + Realizer (fun a=>(f a).bind (fun b=>(g a).map (Prod.mk b))) := + (composition (deterministic (TreeTyped.pair (TreeTyped.identity (A:=A)) TreeTyped.identity)) + (composition (mapSecond F) + (composition (deterministic (TreeTyped.pair (TreeTyped.second (A:=A) (B:=B)) TreeTyped.first)) + (mapSecond G)))).congr (by + intro a h + simp only [Experiment.mean_bind,Experiment.mean,Experiment.mean_map,id_eq]) +end MatchingFPRAS.OnlineTree + +end OAI diff --git a/lean/OAI/Combinatorics/MatchingCount/Machines/OnlinePhysicalProgram.lean b/lean/OAI/Combinatorics/MatchingCount/Machines/OnlinePhysicalProgram.lean new file mode 100644 index 0000000000000000000000000000000000000000..7880bcb6130b0fb3a5e990e43b7573b7d3e0a139 --- /dev/null +++ b/lean/OAI/Combinatorics/MatchingCount/Machines/OnlinePhysicalProgram.lean @@ -0,0 +1,60 @@ +import Mathlib +import OAI.Combinatorics.MatchingCount.Machines.TreePostRealization +import OAI.Combinatorics.MatchingCount.Machines.PhysicalProgram +import OAI.Combinatorics.MatchingCount.Machines.OnlineTree + +namespace OAI + +namespace MatchingFPRAS.OnlineTree +open Turing TreeTyped TreeData TreeFunction TreeMachine TreePost PhysicalPost PhysicalStream + +lemma input_height {A : Type} [Codec A] (a : A) : OnlineStack.height (inputStacks a)=weight a := by + apply le_antisymm + · exact Finset.sup_le (fun k _=>inputStacks_bound a k) + · have h:=OnlineStack.height_bound (inputStacks a) (Sum.inl (0 : Reg)) + simpa only [inputStacks,encodeEnv,env,ite_true,weight,TreeFunction.size] using h + +lemma cfg_packed {A : Type} [Codec A] (P : OnlineProc.Proc (K Reg)) (a : A) (l : Option P.Label) : + upCfg (OnlineStack.cfg (⟨l,none,inputStacks a⟩ : StoreCfg P))= + ⟨l.map (fun u=>(Sum.inl (TM1to1.Λ'.normal (TM2to1.Λ'.normal u)),none)),Tape.mk₁ (packed a)⟩ := by + simp only [upCfg,OnlineStack.cfg,OnlineStack.stackCfg,input_height,CoinTM1.trCfg, + TM1to1.trCfg,TM1to1.trTape,TM1to1.trTape',Tape.mk₁,Tape.mk₂,Tape.mk'_left,Tape.mk'_right₀, + ListBlank.flatMap_mk,List.flatMap_nil,Option.map_map] + rw [Tape.map_mk'] + rfl + +noncomputable def physicalProgram {A B : Type} [Codec A] [Codec B] + {f : A→Experiment B} (F : Realizer f) : Program where + State := OnlineStack.Q (K Reg) (fun _=>Bool) F.program.Label RegisterProc.Store + table := liftBool (OnlineStack.table F.program.code F.program.coin) + states := OnlineStack.states F.program.code + supported := liftBool_supported _ _ (OnlineStack.table_supported F.program.code F.program.coin) + entry := OnlineStack.initialState + entry_mem := OnlineStack.initialState_mem F.program.code + +noncomputable def physicalCost {A B : Type} [Codec A] [Codec B] + {f : A→Experiment B} (F : Realizer f) (a : A) : ℕ := + F.cost a*OnlineStack.Executes.factor F.program.code (weight a) (F.cost a) + +lemma physical_realizes {A B : Type} [Codec A] [Codec B] + {f : A→Experiment B} (F : Realizer f) (a : A) : + (physicalProgram F).Realizes (Tape.mk₁ (packed a)) + ((f a).map (fun b=>Tape.mk₁ (packed b))) (physicalCost F a) := by + obtain ⟨p,hp,hm,hc⟩:=F.correct a .nil + obtain ⟨q,hq,hqm,hqc⟩:=hp.compile (weight a) (inputStacks_bound a) + have he:=hq.up + have hi : upCfg (OnlineStack.cfg (initial F.program (encode a) .nil))= + (physicalProgram F).initial (Tape.mk₁ (packed a)) := cfg_packed F.program a (some default) + have ho (b : B) : upCfg (OnlineStack.cfg (final F.program (encode b) .nil))= + (physicalProgram F).final (Tape.mk₁ (packed b)) := cfg_packed F.program b none + rw [hi] at he + simp_rw [ho] at he + refine ⟨q.map (fun b=>Tape.mk₁ (packed b)),?_,?_,?_⟩ + · exact he.map_all _ _ (Experiment.all_true _ |>.mono (fun _ _=>rfl)) + · intro w + rw [Experiment.mean_map,hqm,hm,Experiment.mean_map] + · rw [Experiment.cost_map] + exact hqc.trans (Nat.mul_le_mul hc (OnlineStack.Executes.factor_mono _ _ _ _ le_rfl hc)) +end MatchingFPRAS.OnlineTree + +end OAI diff --git a/lean/OAI/Combinatorics/MatchingCount/Machines/OnlineTraverse.lean b/lean/OAI/Combinatorics/MatchingCount/Machines/OnlineTraverse.lean new file mode 100644 index 0000000000000000000000000000000000000000..b29ffe122247f2877b37d5cff19b0566c56b0be3 --- /dev/null +++ b/lean/OAI/Combinatorics/MatchingCount/Machines/OnlineTraverse.lean @@ -0,0 +1,65 @@ +import Mathlib +import OAI.Combinatorics.MatchingCount.Machines.OnlineFold +import OAI.Combinatorics.MatchingCount.Machines.OnlineFrame + +namespace OAI + +namespace MatchingFPRAS.OnlineTree +open PhysicalStream TreeTyped + +variable {A B C : Type} [Codec A] [Codec B] [Codec C] + +def traverseM (f : A → Experiment B) : List A → Experiment (List B) + | [] => .done [] + | a::as => (f a).bind (fun b=>(traverseM f as).map (List.cons b)) +def collectStep (f : A → Experiment B) (x : A×List B) : Experiment (List B) := + (f x.1).map (fun b=>b::x.2) +noncomputable def collectStepRealizer {f : A → Experiment B} (F : Realizer f) : + Realizer (collectStep f) := + (composition (pair (composition (deterministic TreeTyped.first) F) + (deterministic TreeTyped.second)) (deterministic TreeTyped.listCons)).congr (by + intro x h; simp only [Experiment.mean_bind,Experiment.mean_map,Experiment.mean,collectStep]) +omit [Codec A] [Codec B] in +lemma mean_fold_collect (f : A → Experiment B) (as : List A) (bs : List B) (h : List B → ℚ) : + (foldM (collectStep f) as bs).mean h=(traverseM f as).mean (fun cs=>h (cs.reverse++bs)) := by + induction as generalizing bs with + | nil => simp only [foldM,traverseM,Experiment.mean,List.reverse_nil,List.nil_append] + | cons a as ih => + simp only [foldM,traverseM,collectStep,Experiment.mean_bind,Experiment.mean_map,ih] + congr 1; funext b + congr 1; funext cs + simp only [List.reverse_cons,List.append_assoc,List.singleton_append] +noncomputable def traverse {f : A → Experiment B} (F : Realizer f) : Realizer (traverseM f) := + (composition (composition (deterministic (TreeTyped.pair TreeTyped.identity (TreeTyped.constant ([] : List B)))) + (fold (collectStepRealizer F))) (deterministic TreeTyped.reverse)).congr (by + intro as h + simp only [Experiment.mean_bind,Experiment.mean] + rw [mean_fold_collect] + simp only [List.append_nil,List.reverse_reverse,id_eq]) +omit [Codec A] [Codec B] in +lemma all_traverse (f : A → Experiment B) (as : List A) (P : B → Prop) + (hf : ∀ a∈as,(f a).All P) : (traverseM f as).All (fun bs=>∀ b∈bs,P b) := by + induction as with + | nil => simp [traverseM,Experiment.All] + | cons a as ih => + rw [traverseM,Experiment.all_bind] + exact (hf a (by simp)).mono (fun b hb=>by + rw [Experiment.all_map] + exact (ih (fun a ha=>hf a (by simp [ha]))).mono (fun bs hbs=>by + intro c hc + rcases List.mem_cons.mp hc with rfl|hc + · exact hb + · exact hbs c hc)) +omit [Codec A] [Codec B] in +lemma all_traverse_length (f : A → Experiment B) (as : List A) : + (traverseM f as).All (fun bs=>bs.length=as.length) := by + induction as with + | nil => rfl + | cons a as ih => + rw [traverseM,Experiment.all_bind] + exact (Experiment.all_true (f a)).mono (fun b _=>by + rw [Experiment.all_map] + exact ih.mono (fun bs hb=>by simpa only [List.length_cons] using congrArg Nat.succ hb)) +end MatchingFPRAS.OnlineTree + +end OAI diff --git a/lean/OAI/Combinatorics/MatchingCount/Machines/OnlineTree.lean b/lean/OAI/Combinatorics/MatchingCount/Machines/OnlineTree.lean new file mode 100644 index 0000000000000000000000000000000000000000..6becca873866fcd68290b1c2767db7728b18d7f5 --- /dev/null +++ b/lean/OAI/Combinatorics/MatchingCount/Machines/OnlineTree.lean @@ -0,0 +1,109 @@ +import Mathlib +import OAI.Combinatorics.MatchingCount.Machines.TreeSum +import OAI.Combinatorics.MatchingCount.Graphs.ExperimentSupport +import OAI.Combinatorics.MatchingCount.Tapes.OnlineComposition + +namespace OAI + +namespace MatchingFPRAS.OnlineTree +open Turing MachineCost PhysicalStream OnlineStack TreeData TreeMachine TreeFunction TreeTyped + +abbrev StoreCfg (P : OnlineProc.Proc (K Reg)) := TM2.Cfg (fun _ : K Reg=>Bool) P.Label RegisterProc.Store +def initial (P : OnlineProc.Proc (K Reg)) (x s : Data) : StoreCfg P := + ⟨some default,none,encodeEnv (env x .nil s)⟩ +def final (P : OnlineProc.Proc (K Reg)) (x s : Data) : StoreCfg P := + ⟨none,none,encodeEnv (env x .nil s)⟩ +structure Realizer {A B : Type} [Codec A] [Codec B] (f : A → Experiment B) where + program : OnlineProc.Proc (K Reg) + cost : A → ℕ + correct : ∀ a s,∃ q : Experiment B, + Executes program.code program.coin (fun b=>final program (encode b) s) + (initial program (encode a) s) q ∧ + (∀ g : B → ℚ,q.mean g=(f a).mean g) ∧ q.cost≤cost a +variable {A B C : Type} [Codec A] [Codec B] [Codec C] + +def deterministic {f : A → B} (F : TreeTyped.Realizer f) : Realizer (fun a=>.done (f a)) where + program := OnlineProc.deterministic F.program + cost := F.cost + correct := by + intro a s + obtain ⟨n,hn,he⟩:=F.correct a s + obtain ⟨p,hp,hm,hc⟩:=Executes.of_run F.program.code n _ _ _ he + refine ⟨p.map (fun _=>f a),?_,?_,?_⟩ + · exact hp.bind (fun _=>.done (f a)) _ (fun _=>.done (f a)) + · intro g + rw [Experiment.mean_map,hm]; rfl + · rw [Experiment.cost_map] + exact hc.trans hn + +noncomputable def composition {f : A → Experiment B} {g : B → Experiment C} + (F : Realizer f) (G : Realizer g) : Realizer (fun a=>(f a).bind g) where + program := OnlineProc.seq F.program G.program + cost := fun a=>F.cost a+(f a).worst G.cost + correct := by + intro a s + obtain ⟨p,hp,hm,hc⟩:=F.correct a s + choose q hq hqm hqc using fun b=>G.correct b s + have hp':=hp.relabel (OnlineProc.seq F.program G.program).code (OnlineProc.seq F.program G.program).coin + Sum.inl (some (Sum.inr default)) (fun _=>rfl) (fun _=>rfl) + have hq' b := (hq b).relabel (OnlineProc.seq F.program G.program).code (OnlineProc.seq F.program G.program).coin + Sum.inr none (fun _=>rfl) (fun _=>rfl) + refine ⟨p.bind q,hp'.bind q _ hq',?_,?_⟩ + · intro h + simp_rw [Experiment.mean_bind,hqm] + exact hm _ + · apply (Experiment.cost_bind_le_of_all p q ((f a).worst G.cost) ?_).trans (Nat.add_le_add_right hc _) + exact (Experiment.all_of_mean_eq hm _ (Experiment.all_worst (f a) G.cost)).mono + (fun b hb=>(hqc b).trans hb) + +def Realizer.congr {f g : A → Experiment B} (F : Realizer f) + (h : ∀ a w,(f a).mean w=(g a).mean w) : Realizer g where + program := F.program + cost := F.cost + correct := by + intro a s + obtain ⟨q,hq,hm,hc⟩:=F.correct a s + exact ⟨q,hq,fun w=>(hm w).trans (h a w),hc⟩ + +def chooseProgram (P Q : OnlineProc.Proc (K Reg)) : OnlineProc.Proc (K Reg) where + toProc := { + Label := Unit ⊕ (P.Label ⊕ Q.Label) + entry := ⟨.inl ()⟩ + code := fun l=>match l with + | .inl _ => .halt + | .inr (.inl l) => StackComposition.relabel (fun u=>Sum.inr (Sum.inl u)) none (P.code l) + | .inr (.inr l) => StackComposition.relabel (fun u=>Sum.inr (Sum.inr u)) none (Q.code l) } + coin := fun l=>match l with + | .inl _ => some (fun b=>if b then .inr (.inr default) else .inr (.inl default)) + | .inr (.inl l) => (P.coin l).map (fun f b=>.inr (.inl (f b))) + | .inr (.inr l) => (Q.coin l).map (fun f b=>.inr (.inr (f b))) + +noncomputable def choose {f g : A → Experiment B} (F : Realizer f) (G : Realizer g) : + Realizer (fun a=>.read (fun b=>if b then g a else f a)) where + program := chooseProgram F.program G.program + cost := fun a=>1+max (F.cost a) (G.cost a) + correct := by + intro a s + obtain ⟨p,hp,hm,hc⟩:=F.correct a s + obtain ⟨q,hq,hqm,hqc⟩:=G.correct a s + have hp':=hp.relabel (chooseProgram F.program G.program).code (chooseProgram F.program G.program).coin + (fun u=>Sum.inr (Sum.inl u)) none (fun _=>rfl) (fun _=>rfl) + have hq':=hq.relabel (chooseProgram F.program G.program).code (chooseProgram F.program G.program).coin + (fun u=>Sum.inr (Sum.inr u)) none (fun _=>rfl) (fun _=>rfl) + refine ⟨.read (fun b=>if b then q else p),?_,?_,?_⟩ + · apply Executes.read _ _ _ _ _ rfl + intro b + cases b + · exact hp' + · exact hq' + · intro h + simp only [Experiment.mean,Bool.false_eq_true,↓reduceIte,hm,hqm] + · simp only [Experiment.cost,Bool.false_eq_true,↓reduceIte] + omega + +noncomputable def randomBit : Realizer (fun _ : A=>.read (fun b=>.done b)) := + (choose (deterministic (TreeTyped.constant false)) (deterministic (TreeTyped.constant true))).congr + (by intro a f; rfl) +end MatchingFPRAS.OnlineTree + +end OAI diff --git a/lean/OAI/Combinatorics/MatchingCount/Machines/OnlineUniform.lean b/lean/OAI/Combinatorics/MatchingCount/Machines/OnlineUniform.lean new file mode 100644 index 0000000000000000000000000000000000000000..2f4a6c7269947821d009c65cc4b135de17132d4b --- /dev/null +++ b/lean/OAI/Combinatorics/MatchingCount/Machines/OnlineUniform.lean @@ -0,0 +1,69 @@ +import Mathlib +import OAI.Combinatorics.MatchingCount.Machines.OnlineTraverse +import OAI.Combinatorics.MatchingCount.Tapes.OnlineWord + +namespace OAI + +namespace MatchingFPRAS.PhysicalStream +open Finset + +variable {A B C : Type} [Fintype A] [Fintype B] +noncomputable def qaverage (f : A → ℚ) : ℚ := (∑ a,f a)/Fintype.card A +omit [Fintype A] [Fintype B] in +lemma qaverage_bits {n : ℕ} (f : Bits n → ℚ) : qaverage f=average f := by + simp [qaverage,average,Bits] +lemma qaverage_equiv (e : A ≃ B) (f : B → ℚ) : qaverage (f ∘ e)=qaverage f := by + unfold qaverage + simp only [Function.comp_apply] + rw [Fintype.card_congr e,e.sum_comp] +lemma qaverage_prod (f : A×B → ℚ) : + qaverage f=qaverage (fun a=>qaverage (fun b=>f (a,b))) := by + simp only [qaverage,Fintype.card_prod,Nat.cast_mul,Fintype.sum_prod_type,←sum_div,div_div] + congr 1 + ring +omit [Fintype B] in +lemma qaverage_congr (f g : A → ℚ) (h : ∀ a,f a=g a) : qaverage f=qaverage g := by + rw [show f=g from funext h] +omit [Fintype B] in +lemma qaverage_unit (f : (Fin 0 → A) → ℚ) : qaverage f=f Fin.elim0 := by + simp only [qaverage,Fintype.sum_unique,Fintype.card_fun,Fintype.card_fin,pow_zero,Nat.cast_one,div_one] + congr 1 +def splitFunction (n : ℕ) (A : Type) : (Fin (n+1) → A) ≃ A×(Fin n → A) where + toFun f := (f 0,fun i=>f i.succ) + invFun f := Fin.cons f.1 f.2 + left_inv f := by funext i; refine Fin.cases ?_ ?_ i <;> simp + right_inv f := by rcases f with ⟨a,f⟩; rfl +omit [Fintype B] in +lemma qaverage_succ (n : ℕ) (f : (Fin (n+1) → A) → ℚ) : + qaverage f=qaverage (fun a : A=>qaverage (fun as : Fin n → A=>f (Fin.cons a as))) := by + rw [←qaverage_equiv (splitFunction n A).symm f,qaverage_prod] + rfl + +omit [Fintype A] [Fintype B] in +lemma mean_word_qaverage (n : ℕ) (f : List Bool → ℚ) : + (OnlineWord.prepend n []).mean f=qaverage (fun w : Bits n=>f (List.ofFn w)) := by + rw [OnlineWord.mean_prepend_nil,qaverage_bits] + +omit [Fintype A] [Fintype B] in +lemma mean_traverse_ofFn {X Y Ω : Type} [Fintype Ω] + (f : X → Experiment Y) (n : ℕ) (xs : Fin n → X) (draw : Fin n → Ω → Y) + (hf : ∀ i h,(f (xs i)).mean h=qaverage (fun u=>h (draw i u))) + (h : List Y → ℚ) : + (OnlineTree.traverseM f (List.ofFn xs)).mean h= + qaverage (fun us : Fin n → Ω=>h (List.ofFn (fun i=>draw i (us i)))) := by + induction n generalizing h with + | zero => simp only [List.ofFn_zero,OnlineTree.traverseM,Experiment.mean,qaverage_unit] + | succ n ih => + rw [List.ofFn_succ,OnlineTree.traverseM,Experiment.mean_bind,hf 0,qaverage_succ] + apply qaverage_congr + intro u + simp only [Experiment.mean_map] + rw [ih (fun i=>xs i.succ) (fun i=>draw i.succ) (fun i=>hf i.succ)] + apply qaverage_congr + intro us + congr 1 + rw [List.ofFn_succ] + rfl +end MatchingFPRAS.PhysicalStream + +end OAI diff --git a/lean/OAI/Combinatorics/MatchingCount/Machines/PhysicalPost.lean b/lean/OAI/Combinatorics/MatchingCount/Machines/PhysicalPost.lean new file mode 100644 index 0000000000000000000000000000000000000000..6175e1ef54686f19a35b74e42fc89b1c513c5414 --- /dev/null +++ b/lean/OAI/Combinatorics/MatchingCount/Machines/PhysicalPost.lean @@ -0,0 +1,149 @@ +import Mathlib +import OAI.Combinatorics.MatchingCount.Probability.Variance +import OAI.Combinatorics.MatchingCount.Graphs.AdaptiveStream + +namespace OAI + +namespace MatchingFPRAS.PhysicalPost +open Turing PhysicalStream + +variable {Γ Q R : Type} [Inhabited Γ] + +structure Cfg (Γ Q : Type) [Inhabited Γ] where + state : Option Q + tape : Tape Γ + +abbrev Table (Γ Q : Type) := Q → Γ → Bool → Option (Q × TM0.Stmt Γ) + +def tick (M : Table Γ Q) (c : Cfg Γ Q) (b : Bool) : Cfg Γ Q := + match c.state with + | none => c + | some q => match M q c.tape.head b with + | none => ⟨none,c.tape⟩ + | some (q',a) => ⟨some q',match a with + | .move d => c.tape.move d + | .write s => c.tape.write s⟩ + +def execute (M : Table Γ Q) : ℕ → Cfg Γ Q → Stream → Cfg Γ Q + | 0,c,_ => c + | n+1,c,b => execute M n (tick M c (b 0)) (shift 1 b) + +lemma execute_add (M : Table Γ Q) (n m : ℕ) (c : Cfg Γ Q) (b : Stream) : + execute M (n+m) c b=execute M m (execute M n c b) (shift n b) := by + induction n generalizing c b with + | zero => simp only [execute,Nat.zero_add,shift_zero] + | succ n ih => + rw [Nat.succ_add,execute,ih,execute] + congr 1 + funext i + simp only [shift] + congr 1 + omega + +lemma execute_halted (M : Table Γ Q) (n : ℕ) (T : Tape Γ) (b : Stream) : + execute M n ⟨none,T⟩ b=⟨none,T⟩ := by + induction n generalizing b with + | zero => rfl + | succ n ih => exact ih (shift 1 b) + +def experiment (M : Table Γ Q) : ℕ → Cfg Γ Q → Experiment (Cfg Γ Q) + | 0,c => .done c + | n+1,c => .read (fun b=>experiment M n (tick M c b)) + +lemma experiment_cost (M : Table Γ Q) (n : ℕ) (c : Cfg Γ Q) : + (experiment M n c).cost=n := by + induction n generalizing c with + | zero => rfl + | succ n ih => simp only [experiment,Experiment.cost,ih,max_self]; omega + +lemma experiment_run (M : Table Γ Q) (n : ℕ) (c : Cfg Γ Q) (b : Stream) : + (experiment M n c).run b=(execute M n c b,n) := by + induction n generalizing c b with + | zero => rfl + | succ n ih => simp only [experiment,Experiment.run,ih,execute]; congr 1; omega + +theorem physical_law (M : Table Γ Q) (n : ℕ) (c : Cfg Γ Q) (f : Cfg Γ Q → ℚ) : + average (fun b : Bits n=>f (execute M n c (extend b)))=(experiment M n c).mean f := by + have h:=Experiment.average_run (experiment M n c) f n (by rw [experiment_cost]) + simpa only [experiment_run] using h + +variable [Fintype Q] [Inhabited Q] + +noncomputable def enumeration : Q ≃ Fin (Fintype.card Q-1+1) := by + let e : Q ≃ Fin (Fintype.card Q-1+1) := Fintype.equivFinOfCardEq + (Nat.sub_add_cancel Fintype.card_pos).symm + exact e.trans (Equiv.swap (e default) 0) + +@[simp] lemma enumeration_default : enumeration (Q:=Q) default=0 := by + classical + simp only [enumeration,Equiv.trans_apply,Equiv.swap_apply_left] + +noncomputable def machine (M : Table Symbol Q) : RandomMachine where + states := Fintype.card Q-1 + transition q a b := (M ((enumeration (Q:=Q)).symm q) a b).map + (fun qa=>(enumeration qa.1,qa.2)) + +noncomputable def sealCfg (M : Table Symbol Q) (c : Cfg Symbol Q) : Configuration (machine M) := + ⟨c.state.map enumeration,c.tape⟩ + +lemma tick_seal (M : Table Symbol Q) (c : Cfg Symbol Q) (b : Bool) : + MatchingFPRAS.tick (machine M) (sealCfg M c) b=sealCfg M (tick M c b) := by + cases c with + | mk s T => cases s with + | none => rfl + | some q => + simp only [MatchingFPRAS.tick,sealCfg,machine,Option.map_some,Equiv.symm_apply_apply,tick] + cases h:M q T.head b with + | none => rfl + | some qa => rcases qa with ⟨q',a⟩; cases a <;> rfl + +omit [Fintype Q] [Inhabited Q] in +lemma execute_list (M : Table Γ Q) (n : ℕ) (c : Cfg Γ Q) (b : Bits n) : + execute M n c (extend b)=(List.ofFn b).foldl (tick M) c := by + induction n generalizing c with + | zero => simp [execute] + | succ n ih => + rw [execute,List.ofFn_succ,List.foldl_cons] + have h0 : extend b 0=b 0 := by simp [extend] + rw [h0,←ih] + have he : ∀ i, ib j.succ) i := by + intro i hi + simp only [shift,extend,dite_eq_left hi,dite_eq_left (by omega : 1+i intros; rfl + | succ k hk => + intro a d had c + simp only [execute,had 0 (by omega)] + apply hk + intro i hi + exact had (1+i) (by omega) + exact hc n _ _ he _ + +lemma foldl_seal (M : Table Symbol Q) (bs : List Bool) (c : Cfg Symbol Q) : + bs.foldl (MatchingFPRAS.tick (machine M)) (sealCfg M c)=sealCfg M (bs.foldl (tick M) c) := by + induction bs generalizing c with + | nil => rfl + | cons b bs ih => rw [List.foldl_cons,tick_seal,ih,List.foldl_cons] + +lemma initial_seal (M : Table Symbol Q) (input : List Symbol) : + sealCfg M ⟨some default,Tape.mk₁ input⟩=MatchingFPRAS.initial (machine M) input := by + change (⟨some (enumeration default),Tape.mk₁ input⟩ : Configuration (machine M))=⟨some 0,Tape.mk₁ input⟩ + rw [enumeration_default] + rfl + +theorem run_seal (M : Table Symbol Q) (input : List Symbol) (n : ℕ) (b : Bits n) : + MatchingFPRAS.run (machine M) input b= + sealCfg M (execute M n ⟨some default,Tape.mk₁ input⟩ (extend b)) := by + unfold MatchingFPRAS.run + rw [←initial_seal,foldl_seal,execute_list] + +end MatchingFPRAS.PhysicalPost + +end OAI diff --git a/lean/OAI/Combinatorics/MatchingCount/Machines/PhysicalProcess.lean b/lean/OAI/Combinatorics/MatchingCount/Machines/PhysicalProcess.lean new file mode 100644 index 0000000000000000000000000000000000000000..a4b3dec35c520e158f0c8912cdcdaeec246358a7 --- /dev/null +++ b/lean/OAI/Combinatorics/MatchingCount/Machines/PhysicalProcess.lean @@ -0,0 +1,67 @@ +import Mathlib +import OAI.Combinatorics.MatchingCount.Machines.PhysicalPost + +namespace OAI + +namespace MatchingFPRAS.PhysicalPost +open Turing PhysicalStream + +variable {Γ Q α β : Type} [Inhabited Γ] + +inductive Implements (M : Table Γ Q) (out : α → Cfg Γ Q) : + Cfg Γ Q → Experiment α → Prop + | done (a) : Implements M out (out a) (.done a) + | read (c) (f : Bool → Experiment α) + (h : ∀ b,Implements M out (tick M c b) (f b)) : Implements M out c (.read f) + | delay (c d) (n : ℕ) (p : Experiment α) + (step : ∀ b : Stream,execute M n c b=d) + (rest : Implements M out d p) : Implements M out c (.delay n p) + +namespace Implements +variable {M : Table Γ Q} {out : α → Cfg Γ Q} {c : Cfg Γ Q} {p : Experiment α} + +lemma execution (h : Implements M out c p) (b : Stream) : + execute M (p.run b).2 c b=out (p.run b).1 := by + induction h generalizing b with + | done a => rfl + | read c f h ih => + simp only [Experiment.run,execute_add] + exact ih (b 0) (shift 1 b) + | delay c d n p hs hr ih => + simp only [Experiment.run,execute_add,hs] + exact ih (shift n b) + +lemma bind (h : Implements M out c p) (q : α → Experiment β) + (out' : β → Cfg Γ Q) (hq : ∀ a,Implements M out' (out a) (q a)) : + Implements M out' c (p.bind q) := by + induction h with + | done a => exact hq a + | read c f h ih => exact .read c _ ih + | delay c d n p hs hr ih => exact .delay c d n _ hs ih + +lemma padded_execution (h : Implements M out c p) (halt : ∀ a,(out a).state=none) + (n : ℕ) (hn : p.cost ≤ n) (b : Stream) : + execute M n c b=out (p.run b).1 := by + have hb : (p.run b).2 ≤ n:=(Experiment.run_cost p b).trans hn + obtain ⟨k,hk⟩:=Nat.exists_eq_add_of_le hb + rw [hk,execute_add,h.execution b] + have he : out (p.run b).1=⟨none,(out (p.run b).1).tape⟩ := by + cases e:out (p.run b).1 with + | mk state tape => + have hstate := halt (p.run b).1 + rw [e] at hstate + change state = none at hstate + subst state + rfl + rw [he,execute_halted] + +theorem fair_law (h : Implements M out c p) (halt : ∀ a,(out a).state=none) + (n : ℕ) (hn : p.cost ≤ n) (f : Cfg Γ Q → ℚ) : + average (fun b : Bits n=>f (execute M n c (extend b)))=p.mean (fun a=>f (out a)) := by + simp_rw [h.padded_execution halt n hn] + exact Experiment.average_run p (fun a=>f (out a)) n hn + +end Implements +end MatchingFPRAS.PhysicalPost + +end OAI diff --git a/lean/OAI/Combinatorics/MatchingCount/Machines/PhysicalProgram.lean b/lean/OAI/Combinatorics/MatchingCount/Machines/PhysicalProgram.lean new file mode 100644 index 0000000000000000000000000000000000000000..c40e1393089de97391d29093539eebbd1d10fcb4 --- /dev/null +++ b/lean/OAI/Combinatorics/MatchingCount/Machines/PhysicalProgram.lean @@ -0,0 +1,131 @@ +import Mathlib +import OAI.Combinatorics.MatchingCount.Graphs.ExperimentSupport +import OAI.Combinatorics.MatchingCount.Machines.PhysicalSequential +import OAI.Combinatorics.MatchingCount.Tapes.Physical + +namespace OAI + +namespace MatchingFPRAS.PhysicalStream.Experiment +variable {A : Type} +lemma mean_congr_all (p : Experiment A) (f g : A→ℚ) (h : p.All (fun a=>f a=g a)) : p.mean f=p.mean g := by + induction p with + | done a => exact h + | delay n p ih => exact ih h + | read p ih => simp only [mean,ih false h.1,ih true h.2] +end MatchingFPRAS.PhysicalStream.Experiment + +namespace MatchingFPRAS.PhysicalPost +open Turing PhysicalStream + +variable {Γ Q A B : Type} [Inhabited Γ] +lemma Implements.map_all {M : Table Γ Q} {out : A→Cfg Γ Q} {c : Cfg Γ Q} + {p : Experiment A} (h : Implements M out c p) (f : A→B) (out' : B→Cfg Γ Q) + (he : p.All (fun a=>out a=out' (f a))) : Implements M out' c (p.map f) := by + induction h with + | done a => rw [he];exact .done (f a) + | read c p h ih => exact .read _ _ (fun b=>by cases b;exact ih false he.1;exact ih true he.2) + | delay c d n p hs hr ih => exact .delay _ _ n _ hs (ih he) +lemma early_implements (M : Table Γ Q) (n : ℕ) (c : Cfg Γ Q) : Implements M id c (early M n c) := by + induction n generalizing c with + | zero => exact .done c + | succ n ih => + rcases c with ⟨s,T⟩ + cases s with + | none => exact .done _ + | some q => exact .read _ _ (fun b=>ih _) +lemma Implements.early_all {M : Table Γ Q} {out : A→Cfg Γ Q} {c : Cfg Γ Q} + {p : Experiment A} (h : Implements M out c p) (halt : ∀ a,(out a).state=none) + (n : ℕ) (hn : p.cost≤n) : (early M n c).All (fun d=>d.state=none) := by + apply Experiment.all_of_mean_eq (p:=(p.map out)) (fun f=>by rw [Experiment.mean_map];exact h.early_mean halt n hn f) + rw [Experiment.all_map] + exact (Experiment.all_true _).mono (fun a _=>halt a) + +structure Program where + State : Type + table : Table Symbol State + states : Finset State + supported : Supported table states + entry : State + entry_mem : entry∈states +namespace Program +noncomputable def seq (P R : Program) : Program where + State := P.State⊕R.State + table := PhysicalPost.seq P.table R.table R.entry + states := P.states.disjSum R.states + supported := seq_supported _ _ _ _ _ P.supported R.supported R.entry_mem + entry := .inl P.entry + entry_mem := Finset.inl_mem_disjSum.mpr P.entry_mem +noncomputable def machine (P : Program) : RandomMachine := + restrictedMachine P.table P.states P.supported P.entry P.entry_mem + +def initial (P : Program) (T : Tape Symbol) : Cfg Symbol P.State := ⟨some P.entry,T⟩ +def final (P : Program) (T : Tape Symbol) : Cfg Symbol P.State := ⟨none,T⟩ +def Realizes (P : Program) (input : Tape Symbol) (f : Experiment (Tape Symbol)) (N : ℕ) : Prop := + ∃ p : Experiment (Tape Symbol),Implements P.table P.final (P.initial input) p ∧ + (∀ h,p.mean h=f.mean h) ∧ p.cost≤N + +def earlyTapes (P : Program) (n : ℕ) (T : Tape Symbol) : Experiment (Tape Symbol) := + (early P.table n (P.initial T)).map Cfg.tape +lemma earlyTapes_cost (P : Program) (n : ℕ) (T : Tape Symbol) : (P.earlyTapes n T).cost≤n := by + rw [earlyTapes,Experiment.cost_map];exact early_cost _ _ _ +lemma Realizes.early {P : Program} {input : Tape Symbol} {f : Experiment (Tape Symbol)} {N : ℕ} + (h : P.Realizes input f N) : + Implements P.table P.final (P.initial input) (P.earlyTapes N input) ∧ + (∀ w,(P.earlyTapes N input).mean w=f.mean w) := by + obtain ⟨p,hp,hm,hc⟩:=h + refine ⟨?_,fun w=>?_⟩ + · apply (early_implements P.table N (P.initial input)).map_all Cfg.tape P.final + exact (hp.early_all (fun _=>rfl) N hc).mono (by intro d hd;cases d; simp only [id_eq,final] at *;cases hd;rfl) + · rw [earlyTapes,Experiment.mean_map,hp.early_mean (fun _=>rfl) N hc] + exact hm w +lemma seq_realizes (P R : Program) (input : Tape Symbol) (f : Experiment (Tape Symbol)) + (g : Tape Symbol→Experiment (Tape Symbol)) (N S : ℕ) + (hP : P.Realizes input f N) (hR : f.All (fun T=>R.Realizes T (g T) S)) : + (P.seq R).Realizes input (f.bind g) (N+S) := by + let p:=early P.table N (P.initial input) + let q:=fun c : Cfg Symbol P.State=>R.earlyTapes S c.tape + have hmean (h : Cfg Symbol P.State→ℚ) : p.mean h=f.mean (fun T=>h (P.final T)) := by + obtain ⟨v,hv,hm,hc⟩:=hP + rw [hv.early_mean (fun _=>rfl) N hc] + exact hm _ + have hall : p.All (fun c=>c.state=none ∧ R.Realizes c.tape (g c.tape) S) := by + apply Experiment.all_of_mean_eq (p:=f.map P.final) (fun h=>by rw [Experiment.mean_map];exact hmean h) + rw [Experiment.all_map] + exact hR.mono (fun T hT=>⟨rfl,hT⟩) + have himpl : Implements (P.seq R).table (fun T=>rightCfg (R.final T)) + ((P.seq R).initial input) (p.bind q) := by + apply (early_left P.table R.table R.entry N (P.initial input)).bind_all q _ + exact hall.mono (by + intro c hc + have hq:=(hc.2.early).1.right (M:=P.table) R.entry + have he:leftCfg R.entry c=rightCfg (R.initial c.tape) := by + rcases c with ⟨s,T⟩;simp only at hc;cases hc.1;rfl + rw [he] + exact hq) + refine ⟨p.bind q,himpl,?_,?_⟩ + · intro w + rw [Experiment.mean_bind,hmean,Experiment.mean_bind] + apply Experiment.mean_congr_all + exact hR.mono (fun T hT=>hT.early.2 w) + · exact (Experiment.cost_bind_le p q S (fun c=>earlyTapes_cost R S c.tape)).trans + (Nat.add_le_add_right (early_cost _ N _) S) + +noncomputable def ofTM1 {Λ σ : Type} [Inhabited Λ] [Fintype Λ] [Inhabited σ] [Fintype σ] + (M : Λ→TM1.Stmt Symbol Λ σ) (l : Λ) (v : σ) : Program where + State := CoinTM1.State Symbol Λ σ + table := LiteralTape.table M + states := LiteralTape.states M + supported := LiteralTape.supported M + entry := (.inl l,v) + entry_mem := LiteralTape.entry_mem M l v +lemma realizes_TM1 {Λ σ : Type} [Inhabited Λ] [Fintype Λ] [Inhabited σ] [Fintype σ] + (M : Λ→TM1.Stmt Symbol Λ σ) (l : Λ) (v v' : σ) (input output : Tape Symbol) (n : ℕ) + (he : LiteralTape.Exec M ⟨some l,v,input⟩ ⟨none,v',output⟩ n) : + (ofTM1 M l v).Realizes input (.done output) (n*MachineCost.programCost M) := by + obtain ⟨k,hk,hb⟩:=he.physical + refine ⟨.delay k (.done output),?_,fun _=>rfl,by simpa only [Experiment.cost,Nat.add_zero] using hk⟩ + exact .delay _ _ k _ hb (.done output) +end Program +end MatchingFPRAS.PhysicalPost + +end OAI diff --git a/lean/OAI/Combinatorics/MatchingCount/Machines/PhysicalProgramMap.lean b/lean/OAI/Combinatorics/MatchingCount/Machines/PhysicalProgramMap.lean new file mode 100644 index 0000000000000000000000000000000000000000..5a8465c9e00c3ee789f77239c99d6aa6a78be539 --- /dev/null +++ b/lean/OAI/Combinatorics/MatchingCount/Machines/PhysicalProgramMap.lean @@ -0,0 +1,31 @@ +import Mathlib +import OAI.Combinatorics.MatchingCount.Machines.PhysicalProgram +import OAI.Combinatorics.MatchingCount.Tapes.Codec + +namespace OAI + +namespace MatchingFPRAS.PhysicalPost.Program +open Turing PhysicalStream + +lemma Realizes.congr {P : Program} {input : Tape Symbol} {f g : Experiment (Tape Symbol)} {N : ℕ} + (h : P.Realizes input f N) (he : ∀ w,f.mean w=g.mean w) : P.Realizes input g N := by + obtain ⟨p,hp,hm,hc⟩:=h + exact ⟨p,hp,fun w=>(hm w).trans (he w),hc⟩ +lemma Realizes.mono {P : Program} {input : Tape Symbol} {f : Experiment (Tape Symbol)} {N S : ℕ} + (h : P.Realizes input f N) (hn : N≤S) : P.Realizes input f S := by + obtain ⟨p,hp,hm,hc⟩:=h + exact ⟨p,hp,hm,hc.trans hn⟩ +lemma seq_realizes_map {A : Type} (P R : Program) (input : Tape Symbol) (f : Experiment A) + (enc : A→Tape Symbol) (g : A→Experiment (Tape Symbol)) (N S : ℕ) + (hP : P.Realizes input (f.map enc) N) (hR : f.All (fun a=>R.Realizes (enc a) (g a) S)) : + (P.seq R).Realizes input (f.bind g) (N+S) := by + have hR' : (f.map enc).All (fun T=>R.Realizes T (R.earlyTapes S T) S) := by + rw [Experiment.all_map] + exact hR.mono (fun a ha=>⟨R.earlyTapes S (enc a),ha.early.1,fun _=>rfl,earlyTapes_cost R S (enc a)⟩) + apply (seq_realizes P R input (f.map enc) (R.earlyTapes S) N S hP hR').congr + intro w + rw [Experiment.mean_bind,Experiment.mean_map,Experiment.mean_bind] + exact f.mean_congr_all _ _ (hR.mono (fun a ha=>ha.early.2 w)) +end MatchingFPRAS.PhysicalPost.Program + +end OAI diff --git a/lean/OAI/Combinatorics/MatchingCount/Machines/PhysicalProgramSeal.lean b/lean/OAI/Combinatorics/MatchingCount/Machines/PhysicalProgramSeal.lean new file mode 100644 index 0000000000000000000000000000000000000000..76eaf1239017024d5569778043e8a44ac3debb9a --- /dev/null +++ b/lean/OAI/Combinatorics/MatchingCount/Machines/PhysicalProgramSeal.lean @@ -0,0 +1,51 @@ +import Mathlib +import OAI.Combinatorics.MatchingCount.Machines.PhysicalProgram +import OAI.Combinatorics.MatchingCount.Tapes.Codec + +namespace OAI + +namespace MatchingFPRAS.PhysicalPost.Program +open Turing PhysicalStream + +lemma run_tape (P : Program) (input : List Symbol) (n : ℕ) (b : Bits n) : + (MatchingFPRAS.run P.machine input b).tape= + (execute P.table n (P.initial (Tape.mk₁ input)) (extend b)).tape := by + let : Inhabited {q //q∈P.states}:=⟨⟨P.entry,P.entry_mem⟩⟩ + rw [machine,restrictedMachine_run] + exact (congrArg Cfg.tape (execute_lift P.table P.states P.supported n + ⟨some default,Tape.mk₁ input⟩ (extend b))).symm +lemma run_halted (P : Program) (input : List Symbol) (n : ℕ) (b : Bits n) + (h : (execute P.table n (P.initial (Tape.mk₁ input)) (extend b)).state=none) : + (MatchingFPRAS.run P.machine input b).state=none := by + let : Inhabited {q //q∈P.states}:=⟨⟨P.entry,P.entry_mem⟩⟩ + have he:=congrArg Cfg.state (execute_lift P.table P.states P.supported n + ⟨some default,Tape.mk₁ input⟩ (extend b)) + have hs : (execute (restrict P.table P.states P.supported) n + ⟨some default,Tape.mk₁ input⟩ (extend b)).state=none := by + exact Option.map_eq_none_iff.mp (he.symm.trans h) + rw [machine,restrictedMachine_run] + change ((execute (restrict P.table P.states P.supported) n + ⟨some default,Tape.mk₁ input⟩ (extend b)).state.map enumeration)=none + rw [hs,Option.map_none] +lemma Realizes.run_all {P : Program} {input : List Symbol} {f : Experiment (Tape Symbol)} {N : ℕ} + (hP : P.Realizes (Tape.mk₁ input) f N) (R : Tape Symbol→Prop) (hf : f.All R) + (n : ℕ) (hn : N≤n) (b : Bits n) : + (MatchingFPRAS.run P.machine input b).state=none ∧ + R (MatchingFPRAS.run P.machine input b).tape := by + obtain ⟨p,hp,hm,hc⟩:=hP + have hex:=hp.padded_execution (fun _=>rfl) n (hc.trans hn) (extend b) + have ht : (MatchingFPRAS.run P.machine input b).tape=(p.run (extend b)).1 := by + rw [run_tape,hex];rfl + refine ⟨run_halted P input n b (by rw [hex];rfl),?_⟩ + rw [ht] + exact p.all_run R (Experiment.all_of_mean_eq hm R hf) (extend b) +lemma Realizes.run_mean {P : Program} {input : List Symbol} {f : Experiment (Tape Symbol)} {N : ℕ} + (hP : P.Realizes (Tape.mk₁ input) f N) (w : Tape Symbol→ℚ) + (n : ℕ) (hn : N≤n) : + average (fun b : Bits n=>w (MatchingFPRAS.run P.machine input b).tape)=f.mean w := by + obtain ⟨p,hp,hm,hc⟩:=hP + simp_rw [run_tape] + exact (hp.fair_law (fun _=>rfl) n (hc.trans hn) (fun c=>w c.tape)).trans (hm w) +end MatchingFPRAS.PhysicalPost.Program + +end OAI diff --git a/lean/OAI/Combinatorics/MatchingCount/Machines/PhysicalRestriction.lean b/lean/OAI/Combinatorics/MatchingCount/Machines/PhysicalRestriction.lean new file mode 100644 index 0000000000000000000000000000000000000000..1614782b1ffe68cfb0aa2f9ed2a02de7f7a0892f --- /dev/null +++ b/lean/OAI/Combinatorics/MatchingCount/Machines/PhysicalRestriction.lean @@ -0,0 +1,62 @@ +import Mathlib +import OAI.Combinatorics.MatchingCount.Machines.PhysicalPost + +namespace OAI + +namespace MatchingFPRAS.PhysicalPost +open Turing PhysicalStream + +variable {Γ Q : Type} [Inhabited Γ] + +def Supported (M : Table Γ Q) (S : Finset Q) : Prop := + ∀ q ∈ S, ∀ a b q' act,M q a b=some (q',act) → q'∈S + +noncomputable def restrict (M : Table Γ Q) (S : Finset Q) (_h : Supported M S) : + Table Γ {q // q∈S} := by + classical + exact fun q a b=>(M q.val a b).map (fun qa=> + ((if hm:qa.1∈S then ⟨qa.1,hm⟩ else q),qa.2)) + +def liftCfg (S : Finset Q) (c : Cfg Γ {q // q∈S}) : Cfg Γ Q := + ⟨c.state.map Subtype.val,c.tape⟩ + +lemma tick_lift (M : Table Γ Q) (S : Finset Q) (h : Supported M S) + (c : Cfg Γ {q // q∈S}) (b : Bool) : + tick M (liftCfg S c) b=liftCfg S (tick (restrict M S h) c b) := by + cases c with + | mk state T => cases state with + | none => rfl + | some q => + cases e:M q.val T.head b with + | none => simp only [tick,liftCfg,Option.map_some,restrict,e,Option.map_none] + | some qa => + rcases qa with ⟨q',act⟩ + have hq' : q'∈S:=h q.val q.property T.head b q' act e + simp only [tick,liftCfg,Option.map_some,restrict,e,dite_eq_left hq'] + +lemma execute_lift (M : Table Γ Q) (S : Finset Q) (h : Supported M S) + (n : ℕ) (c : Cfg Γ {q // q∈S}) (b : Stream) : + execute M n (liftCfg S c) b=liftCfg S (execute (restrict M S h) n c b) := by + induction n generalizing c b with + | zero => rfl + | succ n ih => rw [execute,tick_lift,ih,execute] + +noncomputable def restrictedMachine (M : Table Symbol Q) (S : Finset Q) + (h : Supported M S) (q₀ : Q) (hq₀ : q₀∈S) : RandomMachine := + letI : Inhabited {q //q∈S}:=⟨⟨q₀,hq₀⟩⟩ + machine (restrict M S h) + +lemma restrictedMachine_run (M : Table Symbol Q) (S : Finset Q) + (h : Supported M S) (q₀ : Q) (hq₀ : q₀∈S) + (input : List Symbol) (n : ℕ) (b : Bits n) : + letI : Inhabited {q //q∈S}:=⟨⟨q₀,hq₀⟩⟩ + MatchingFPRAS.run (restrictedMachine M S h q₀ hq₀) input b= + sealCfg (restrict M S h) + (execute (restrict M S h) n ⟨some default,Tape.mk₁ input⟩ (extend b)) := +by + let : Inhabited {q //q∈S}:=⟨⟨q₀,hq₀⟩⟩ + exact run_seal (restrict M S h) input n b + +end MatchingFPRAS.PhysicalPost + +end OAI diff --git a/lean/OAI/Combinatorics/MatchingCount/Machines/PhysicalSequential.lean b/lean/OAI/Combinatorics/MatchingCount/Machines/PhysicalSequential.lean new file mode 100644 index 0000000000000000000000000000000000000000..e6cddf28e38200f110b7bc53cf3899075348c219 --- /dev/null +++ b/lean/OAI/Combinatorics/MatchingCount/Machines/PhysicalSequential.lean @@ -0,0 +1,122 @@ +import Mathlib +import OAI.Combinatorics.MatchingCount.Machines.PhysicalRestriction +import OAI.Combinatorics.MatchingCount.Machines.PhysicalProcess +import OAI.Combinatorics.MatchingCount.Graphs.ExperimentSupport + +namespace OAI + +namespace MatchingFPRAS.PhysicalPost +open Turing PhysicalStream + +variable {Γ Q R α β : Type} [Inhabited Γ] + +def seq (M : Table Γ Q) (N : Table Γ R) (r₀ : R) : Table Γ (Q⊕R) + | .inl q,a,b => match M q a b with + | none => some (.inr r₀,.write a) + | some (q',act) => some (.inl q',act) + | .inr r,a,b => (N r a b).map (fun ra=>(Sum.inr ra.1,ra.2)) +def leftCfg (r₀ : R) (c : Cfg Γ Q) : Cfg Γ (Q⊕R) := + ⟨some (c.state.elim (Sum.inr r₀) Sum.inl),c.tape⟩ +def rightCfg (c : Cfg Γ R) : Cfg Γ (Q⊕R) := ⟨c.state.map Sum.inr,c.tape⟩ +lemma tick_left (M : Table Γ Q) (N : Table Γ R) (r₀ : R) (q : Q) (T : Tape Γ) (b : Bool) : + tick (seq M N r₀) (leftCfg r₀ ⟨some q,T⟩) b=leftCfg r₀ (tick M ⟨some q,T⟩ b) := by + cases h : M q T.head b with + | none => simp only [tick,leftCfg,seq,h,Option.elim_some,Option.elim_none,Tape.write_self] + | some qa => rcases qa with ⟨q',act⟩;cases act <;> simp only [tick,leftCfg,seq,h,Option.elim_some] +lemma tick_right (M : Table Γ Q) (N : Table Γ R) (r₀ : R) (c : Cfg Γ R) (b : Bool) : + tick (seq M N r₀) (rightCfg c) b=rightCfg (tick N c b) := by + rcases c with ⟨s,T⟩ + cases s with + | none => rfl + | some r => + cases h:N r T.head b with + | none => simp only [tick,rightCfg,Option.map_some,seq,h,Option.map_none] + | some ra => rcases ra with ⟨r',act⟩;cases act <;> simp only [tick,rightCfg,seq,h,Option.map_some] +lemma execute_right (M : Table Γ Q) (N : Table Γ R) (r₀ : R) (n : ℕ) (c : Cfg Γ R) (b : Stream) : + execute (seq M N r₀) n (rightCfg c) b=rightCfg (execute N n c b) := by + induction n generalizing c b with + | zero => rfl + | succ n ih => rw [execute,tick_right,ih,execute] +lemma Implements.right {M : Table Γ Q} {N : Table Γ R} (r₀ : R) {out : α→Cfg Γ R} + {c : Cfg Γ R} {p : Experiment α} (h : Implements N out c p) : + Implements (seq M N r₀) (rightCfg ∘ out) (rightCfg c) p := by + induction h with + | done a => exact .done a + | read c f h ih => apply Implements.read;intro b;rw [tick_right];exact ih b + | delay c d n p hs hr ih => + exact .delay _ _ n _ (fun b=>by rw [execute_right,hs]) ih + +def early (M : Table Γ Q) : ℕ→Cfg Γ Q→Experiment (Cfg Γ Q) + | 0,c => .done c + | n+1,c => match c.state with + | none => .done c + | some _ => .read (fun b=>early M n (tick M c b)) +lemma early_cost (M : Table Γ Q) (n : ℕ) (c : Cfg Γ Q) : (early M n c).cost≤n := by + induction n generalizing c with + | zero => exact le_rfl + | succ n ih => + cases h:c.state <;> simp only [early,h,Experiment.cost] + · omega + · have h0:=ih (tick M c false); have h1:=ih (tick M c true); omega +lemma early_run (M : Table Γ Q) (n : ℕ) (c : Cfg Γ Q) (b : Stream) : + ((early M n c).run b).1=execute M n c b := by + induction n generalizing c b with + | zero => rfl + | succ n ih => + rcases c with ⟨s,T⟩ + cases s with + | none => rw [execute_halted];rfl + | some q => simp only [early,Experiment.run,execute];exact ih _ _ +lemma early_mean (M : Table Γ Q) (n : ℕ) (c : Cfg Γ Q) (f : Cfg Γ Q→ℚ) : + (early M n c).mean f=average (fun b : Bits n=>f (execute M n c (extend b))) := by + simpa only [early_run] using (Experiment.average_run (early M n c) f n (early_cost M n c)).symm +lemma early_left (M : Table Γ Q) (N : Table Γ R) (r₀ : R) (n : ℕ) (c : Cfg Γ Q) : + Implements (seq M N r₀) (leftCfg r₀) (leftCfg r₀ c) (early M n c) := by + induction n generalizing c with + | zero => exact .done c + | succ n ih => + rcases c with ⟨s,T⟩ + cases s with + | none => exact .done _ + | some q => + apply Implements.read + intro b + rw [tick_left] + exact ih _ +lemma Implements.early_mean {M : Table Γ Q} {out : α→Cfg Γ Q} {c : Cfg Γ Q} + {p : Experiment α} (h : Implements M out c p) (halt : ∀ a,(out a).state=none) + (n : ℕ) (hn : p.cost≤n) (f : Cfg Γ Q→ℚ) : + (early M n c).mean f=p.mean (fun a=>f (out a)) := by + rw [PhysicalPost.early_mean] + exact h.fair_law halt n hn f +lemma Implements.bind_all {M : Table Γ Q} {out : α→Cfg Γ Q} {c : Cfg Γ Q} + {p : Experiment α} (h : Implements M out c p) (q : α→Experiment β) (out' : β→Cfg Γ Q) + (hq : p.All (fun a=>Implements M out' (out a) (q a))) : + Implements M out' c (p.bind q) := by + induction h with + | done a => exact hq + | read c f h ih => exact .read c _ (fun b=>by cases b;exact ih false hq.1;exact ih true hq.2) + | delay c d n p hs hr ih => exact .delay c d n _ hs (ih hq) +omit [Inhabited Γ] in +lemma seq_supported [Inhabited Γ] (M : Table Γ Q) (N : Table Γ R) (r₀ : R) + (S : Finset Q) (T : Finset R) (hM : Supported M S) (hN : Supported N T) (hr : r₀∈T) : + Supported (seq M N r₀) (S.disjSum T) := by + intro q hq a b q' act he + cases q with + | inl q => + have hq':q∈S := Finset.inl_mem_disjSum.mp hq + cases h:M q a b with + | none => simp only [seq,h,Option.some.injEq,Prod.mk.injEq] at he;rcases he with ⟨rfl,rfl⟩;exact Finset.inr_mem_disjSum.mpr hr + | some x => + rcases x with ⟨v,ac⟩ + simp only [seq,h,Option.some.injEq,Prod.mk.injEq] at he + rcases he with ⟨rfl,rfl⟩ + exact Finset.inl_mem_disjSum.mpr (hM q hq' a b v ac h) + | inr r => + simp only [seq,Option.map_eq_some_iff] at he + obtain ⟨⟨r',ac⟩,hh,e⟩:=he + cases e + exact Finset.inr_mem_disjSum.mpr (hN r (Finset.inr_mem_disjSum.mp hq) a b r' ac hh) +end MatchingFPRAS.PhysicalPost + +end OAI diff --git a/lean/OAI/Combinatorics/MatchingCount/Machines/ProgramComposition.lean b/lean/OAI/Combinatorics/MatchingCount/Machines/ProgramComposition.lean new file mode 100644 index 0000000000000000000000000000000000000000..a4f283b7840196888111dbe4e348616e53fc045e --- /dev/null +++ b/lean/OAI/Combinatorics/MatchingCount/Machines/ProgramComposition.lean @@ -0,0 +1,104 @@ +import Mathlib +import OAI.Combinatorics.MatchingCount.Complexity.GuardMachineBase + +namespace OAI + +namespace MatchingFPRAS.ProgramComposition +open Turing MachineCost + +variable {Γ Λ Κ σ : Type*} [Inhabited Γ] + +def relabel (f : Λ → Κ) (h : Option Κ) : TM1.Stmt Γ Λ σ → TM1.Stmt Γ Κ σ + | .move d q => .move d (relabel f h q) + | .write a q => .write a (relabel f h q) + | .load a q => .load a (relabel f h q) + | .branch p q r => .branch p (relabel f h q) (relabel f h r) + | .goto l => .goto (fun a v=>f (l a v)) + | .halt => match h with | none=>.halt | some k=>.goto (fun _ _=>k) +def mapCfg (f : Λ → Κ) (h : Option Κ) (c : TM1.Cfg Γ Λ σ) : TM1.Cfg Γ Κ σ := + ⟨c.l.bind (fun l=>some (f l)) |>.or h,c.var,c.Tape⟩ +lemma mapCfg_some (f : Λ → Κ) (h : Option Κ) (l : Λ) (v : σ) (T : Tape Γ) : + mapCfg f h ⟨some l,v,T⟩=⟨some (f l),v,T⟩ := rfl +lemma mapCfg_none (f : Λ → Κ) (h : Option Κ) (v : σ) (T : Tape Γ) : + mapCfg f h ⟨none,v,T⟩=⟨h,v,T⟩ := rfl +lemma relabel_eval (f : Λ → Κ) (h : Option Κ) (q : TM1.Stmt Γ Λ σ) (v : σ) (T : Tape Γ) : + TM1.stepAux (relabel f h q) v T=mapCfg f h (TM1.stepAux q v T) := by + induction q generalizing v T with + | move d q ih => exact ih v (T.move d) + | write a q ih => exact ih v (T.write (a T.head v)) + | load a q ih => exact ih (a T.head v) T + | branch p q r ihq ihr => cases hp:p T.head v <;> simp only [relabel,TM1.stepAux,hp,Bool.cond_false,Bool.cond_true] <;> first | apply ihr | apply ihq + | goto l => rfl + | halt => cases h <;> rfl +omit [Inhabited Γ] in +lemma relabel_cost (f : Λ → Κ) (h : Option Κ) (q : TM1.Stmt Γ Λ σ) : + statementCost (relabel f h q)=statementCost q := by + induction q with + | move d q ih | write d q ih | load d q ih => simp only [relabel,statementCost,ih] + | branch p q r ihq ihr => simp only [relabel,statementCost,ihq,ihr] + | goto l => rfl + | halt => cases h <;> rfl +lemma run_halted (M : Λ → TM1.Stmt Γ Λ σ) (n : ℕ) (v : σ) (T : Tape Γ) : + MachineCost.run (TM1.step M) n ⟨none,v,T⟩=⟨none,v,T⟩ := by + induction n with + | zero => rfl + | succ n ih => simpa only [MachineCost.run,advance,TM1.step,Option.getD_none] using ih + +lemma run_relabel_to_halt (M : Λ → TM1.Stmt Γ Λ σ) (N : Κ → TM1.Stmt Γ Κ σ) + (f : Λ → Κ) (h : Option Κ) (hN : ∀ l,N (f l)=relabel f h (M l)) + (n : ℕ) (c : TM1.Cfg Γ Λ σ) (v : σ) (T : Tape Γ) + (he : MachineCost.run (TM1.step M) n c=⟨none,v,T⟩) : + ∃ k≤n,MachineCost.run (TM1.step N) k (mapCfg f h c)=⟨h,v,T⟩ := by + induction n generalizing c with + | zero => + have hc : c=⟨none,v,T⟩:=he + subst c + exact ⟨0,le_rfl,rfl⟩ + | succ n ih => + rcases c with ⟨l,v',T'⟩ + cases l with + | none => + rw [run_halted] at he + cases he + exact ⟨0,Nat.zero_le _,rfl⟩ + | some l => + have he' : MachineCost.run (TM1.step M) n (TM1.stepAux (M l) v' T')=⟨none,v,T⟩ := he + obtain ⟨k,hk,hh⟩:=ih _ he' + refine ⟨k+1,by omega,?_⟩ + rw [MachineCost.run,mapCfg_some] + have hs : advance (TM1.step N) ⟨some (f l),v',T'⟩= + mapCfg f h (TM1.stepAux (M l) v' T') := by + simp only [advance,TM1.step,Option.getD_some,hN,relabel_eval] + rw [hs,hh] +variable [Inhabited Λ] [Inhabited Κ] + +def sequence (M : Λ → TM1.Stmt Γ Λ σ) (N : Κ → TM1.Stmt Γ Κ σ) : + Λ⊕Κ → TM1.Stmt Γ (Λ⊕Κ) σ + | .inl l => relabel Sum.inl (some (Sum.inr default)) (M l) + | .inr k => relabel Sum.inr none (N k) +omit [Inhabited Λ] in +lemma sequence_run (M : Λ → TM1.Stmt Γ Λ σ) (N : Κ → TM1.Stmt Γ Κ σ) + (c : TM1.Cfg Γ Λ σ) (m n : ℕ) (v v' : σ) (T T' : Tape Γ) + (hM : MachineCost.run (TM1.step M) m c=⟨none,v,T⟩) + (hN : MachineCost.run (TM1.step N) n ⟨some default,v,T⟩=⟨none,v',T'⟩) : + ∃ k ≤ m+n,MachineCost.run (TM1.step (sequence M N)) k + (mapCfg Sum.inl (some (Sum.inr default)) c)=⟨none,v',T'⟩ := by + obtain ⟨i,hi,hei⟩:=run_relabel_to_halt M (sequence M N) Sum.inl + (some (Sum.inr default)) (fun _=>rfl) m c v T hM + obtain ⟨j,hj,hej⟩:=run_relabel_to_halt N (sequence M N) Sum.inr + none (fun _=>rfl) n ⟨some default,v,T⟩ v' T' hN + refine ⟨i+j,by omega,?_⟩ + rw [run_add,hei] + exact hej +omit [Inhabited Γ] [Inhabited Λ] in +lemma sequence_cost [Inhabited σ] [Fintype Λ] [Fintype Κ] + (M : Λ → TM1.Stmt Γ Λ σ) (N : Κ → TM1.Stmt Γ Κ σ) : + programCost (sequence M N) ≤ max (programCost M) (programCost N) := by + apply Finset.sup_le + intro l _ + cases l with + | inl l => exact (by rw [sequence,relabel_cost]; exact (statementCost_le_programCost M l).trans (le_max_left _ _)) + | inr k => exact (by rw [sequence,relabel_cost]; exact (statementCost_le_programCost N k).trans (le_max_right _ _)) +end MatchingFPRAS.ProgramComposition + +end OAI diff --git a/lean/OAI/Combinatorics/MatchingCount/Machines/RegisterControl.lean b/lean/OAI/Combinatorics/MatchingCount/Machines/RegisterControl.lean new file mode 100644 index 0000000000000000000000000000000000000000..53d7d125af72bbd711fa755d3dc84697f0fda3be --- /dev/null +++ b/lean/OAI/Combinatorics/MatchingCount/Machines/RegisterControl.lean @@ -0,0 +1,104 @@ +import Mathlib +import OAI.Combinatorics.MatchingCount.Machines.TreeCompiler + +namespace OAI + +namespace MatchingFPRAS.RegisterControl +open TreeData TreeMachine RegisterProc Turing MachineCost + +variable {R Λ : Type} [DecidableEq R] +inductive Instr (R Λ : Type) where + | halt + | go (next : Λ) + | branch (i : R) (nil cons : Λ) + | call (P : Proc (K R)) (next : Λ) + +def procedure : Instr R Λ → Proc (K R) + | .call P _ => P + | _ => atom .halt +def successor : Instr R Λ → Option Λ + | .call _ l => some l + | _ => none +abbrev Label (M : Λ → Instr R Λ) := Λ ⊕ ((l : Λ) × (procedure (M l)).Label) +instance (M : Λ → Instr R Λ) [Fintype Λ] : Fintype (Label M) := by unfold Label; infer_instance + +def code (M : Λ → Instr R Λ) : Label M → TM2.Stmt (fun _ : K R=>Bool) (Label M) Store + | .inl l => match M l with + | .halt => .halt + | .go k => .goto (fun _=>.inl k) + | .branch i a b => .peek (.inl i) (fun _ x=>x) (.branch (fun x=>x.getD false) + (.load (fun _=>none) (.goto (fun _=>.inl b))) + (.load (fun _=>none) (.goto (fun _=>.inl a)))) + | .call _ _ => .goto (fun _=>.inr ⟨l,default⟩) + | .inr ⟨l,u⟩ => StackComposition.relabel (fun u=>.inr ⟨l,u⟩) + ((successor (M l)).map Sum.inl) ((procedure (M l)).code u) +def compile [Fintype Λ] [Inhabited Λ] (M : Λ → Instr R Λ) : Proc (K R) := + { Label := Label M + entry := ⟨.inl default⟩ + code := code M } +def cfg (M : Λ → Instr R Λ) (l : Option Λ) (E : Env R) : TM2.Cfg (fun _ : K R=>Bool) (Label M) Store := + ⟨l.map Sum.inl,none,encodeEnv E⟩ + +inductive Effect : Instr R Λ → Env R → Option Λ → Env R → ℕ → Prop + | halt (E) : Effect .halt E none E 1 + | go (E l) : Effect (.go l) E (some l) E 1 + | nilBranch (E i l r) (h : E i=.nil) : Effect (.branch i l r) E (some l) E 1 + | consBranch (E i l r x y) (h : E i=.cons x y) : Effect (.branch i l r) E (some r) E 1 + | call (P E F l n) (h : Exec P (encodeEnv E) (encodeEnv F) n) : Effect (.call P l) E (some l) F (n+1) + +lemma effect_compiles (M : Λ → Instr R Λ) (l : Λ) (I : Instr R Λ) (hI : M l=I) + (E F : Env R) (next : Option Λ) (n : ℕ) (h : Effect I E next F n) : + ∃ k≤n,MachineCost.run (TM2.step (code M)) k (cfg M (some l) E)=cfg M next F := by + cases h with + | halt E => + refine ⟨1,le_rfl,?_⟩ + simp only [MachineCost.run,advance,TM2.step,cfg,Option.map_some,code,hI,TM2.stepAux, + Option.getD_some,Option.map_none] + | go E a => + refine ⟨1,le_rfl,?_⟩ + simp only [MachineCost.run,advance,TM2.step,cfg,Option.map_some,code,hI,TM2.stepAux,Option.getD_some] + | nilBranch E i a b hi => + refine ⟨1,le_rfl,?_⟩ + simp only [MachineCost.run,advance,TM2.step,cfg,Option.map_some,code,hI,TM2.stepAux, + encodeEnv,hi,encode,List.head?_cons,Option.getD_some,Bool.cond_false] + | consBranch E i a b x y hi => + refine ⟨1,le_rfl,?_⟩ + simp only [MachineCost.run,advance,TM2.step,cfg,Option.map_some,code,hI,TM2.stepAux, + encodeEnv,hi,encode,List.head?_cons,Option.getD_some,Bool.cond_true] + | call P E F a n hp => + have hp' : Exec (procedure (M l)) (encodeEnv E) (encodeEnv F) n := by simpa only [hI,procedure] using hp + obtain ⟨j,hj,he⟩:=hp' + obtain ⟨k,hk,hs⟩:=StackComposition.run_relabel_to_halt (procedure (M l)).code (code M) + (fun u=>Sum.inr ⟨l,u⟩) ((successor (M l)).map Sum.inl) (fun _=>rfl) + j ⟨some default,none,encodeEnv E⟩ none (encodeEnv F) he + refine ⟨k+1,by omega,?_⟩ + rw [MachineCost.run] + have ha : advance (TM2.step (code M)) (cfg M (some l) E)= + StackComposition.mapCfg (fun u=>Sum.inr ⟨l,u⟩) ((successor (M l)).map Sum.inl) + ⟨some default,none,encodeEnv E⟩ := by + simp only [advance,TM2.step,cfg,Option.map_some,code,hI,TM2.stepAux,Option.getD_some, + StackComposition.mapCfg_some] + rw [ha,hs] + simp only [cfg,hI,successor,Option.map_some] + +inductive Runs (M : Λ → Instr R Λ) : Option Λ → Env R → Env R → ℕ → Prop + | done (E) : Runs M none E E 0 + | step (l E next F G n k) (h : Effect (M l) E next F k) + (rest : Runs M next F G n) : Runs M (some l) E G (k+n) + | weaken (l : Option Λ) (E F : Env R) (n b : ℕ) (h : Runs M l E F n) (hn : n ≤ b) : Runs M l E F b +lemma runs_compiles (M : Λ → Instr R Λ) (n : ℕ) (l : Option Λ) (E F : Env R) + (h : Runs M l E F n) : + ∃ k≤n,MachineCost.run (TM2.step (code M)) k (cfg M l E)=cfg M none F := by + induction h with + | done E => exact ⟨0,le_rfl,rfl⟩ + | step l E next F G n k h rest ih => + obtain ⟨i,hi,he⟩:=effect_compiles M l (M l) rfl E F next k h + obtain ⟨j,hj,hf⟩:=ih + exact ⟨i+j,Nat.add_le_add hi hj,by rw [run_add,he,hf]⟩ + | weaken l E F n m h hnm ih => obtain ⟨k,hk,he⟩:=ih; exact ⟨k,hk.trans hnm,he⟩ +lemma compile_exec [Fintype Λ] [Inhabited Λ] (M : Λ → Instr R Λ) (n : ℕ) (E F : Env R) + (h : Runs M (some default) E F n) : Exec (compile M) (encodeEnv E) (encodeEnv F) n := + runs_compiles M n (some default) E F h +end MatchingFPRAS.RegisterControl + +end OAI diff --git a/lean/OAI/Combinatorics/MatchingCount/Machines/RegisterProc.lean b/lean/OAI/Combinatorics/MatchingCount/Machines/RegisterProc.lean new file mode 100644 index 0000000000000000000000000000000000000000..83ed7f1b71bacedc6acb03517b1dfc9b8b82da75 --- /dev/null +++ b/lean/OAI/Combinatorics/MatchingCount/Machines/RegisterProc.lean @@ -0,0 +1,115 @@ +import Mathlib +import OAI.Combinatorics.MatchingCount.Arithmetic.ArithmeticSize +import OAI.Combinatorics.MatchingCount.Tapes.StackLens +import OAI.Combinatorics.MatchingCount.Tapes.WordOps + +namespace OAI + +namespace MatchingFPRAS.RegisterProc +open Turing MachineCost + +abbrev Store := Option Bool +abbrev Stack (K : Type) := K → List Bool +structure Proc (K : Type) where + Label : Type + [labels : Fintype Label] + [entry : Inhabited Label] + code : Label → TM2.Stmt (fun _ : K=>Bool) Label Store +attribute [instance] Proc.labels Proc.entry +variable {K : Type} [DecidableEq K] + +def Exec (P : Proc K) (S T : Stack K) (bound : ℕ) : Prop := + ∃ n≤bound,MachineCost.run (TM2.step P.code) n ⟨some default,none,S⟩=⟨none,none,T⟩ +lemma Exec.mono {P : Proc K} {S T : Stack K} {n m : ℕ} + (h : Exec P S T n) (hn : n ≤ m) : Exec P S T m := by + obtain ⟨k,hk,he⟩:=h; exact ⟨k,hk.trans hn,he⟩ + +def seq (P Q : Proc K) : Proc K := + { Label := P.Label ⊕ Q.Label + entry := ⟨Sum.inl default⟩ + code := StackComposition.sequence P.code Q.code } +lemma Exec.seq {P Q : Proc K} {S T U : Stack K} {n m : ℕ} + (hP : Exec P S T n) (hQ : Exec Q T U m) : Exec (seq P Q) S U (n+m) := by + obtain ⟨i,hi,he⟩:=hP + obtain ⟨j,hj,hf⟩:=hQ + obtain ⟨k,hk,hg⟩:=StackComposition.sequence_run P.code Q.code + ⟨some default,none,S⟩ i j none none T U he hf + exact ⟨k,hk.trans (Nat.add_le_add hi hj),hg⟩ + +def atom (s : TM2.Stmt (fun _ : K=>Bool) Unit Store) : Proc K := ⟨Unit,fun _=>s⟩ +lemma exec_atom (s : TM2.Stmt (fun _ : K=>Bool) Unit Store) (S T : Stack K) + (h : TM2.stepAux s none S=⟨none,none,T⟩) : Exec (atom s) S T 1 := ⟨1,le_rfl,h⟩ + +def reindex (P : Proc (Fin 3)) (e : Fin 3 ↪ K) : Proc K := + ⟨P.Label,StackLens.program e (StackLens.Lens.identity Store) P.code⟩ +noncomputable def frame (e : Fin 3 ↪ K) (A B C : List Bool) (S : Stack K) : Stack K := + StackEmbedding.extend e ![A,B,C] S +lemma exec_reindex (P : Proc (Fin 3)) (e : Fin 3 ↪ K) (S : Stack K) + (A B C A' B' C' : List Bool) (n : ℕ) + (h : Exec P ![A,B,C] ![A',B',C'] n) : + Exec (reindex P e) (frame e A B C S) (frame e A' B' C' S) n := by + obtain ⟨k,hk,he⟩:=h + refine ⟨k,hk,?_⟩ + have hh := StackLens.run_cfg e (StackLens.Lens.identity Store) P.code S none k + ⟨some default,none,![A,B,C]⟩ + rw [he] at hh + exact hh + +def triple (a b c : K) (hab : a≠b) (hac : a≠c) (hbc : b≠c) : Fin 3 ↪ K := + ⟨![a,b,c],by intro i j h; fin_cases i <;> fin_cases j <;> simp_all⟩ +omit [DecidableEq K] in +@[simp] lemma triple_zero (a b c : K) (hab : a≠b) (hac : a≠c) (hbc : b≠c) : + triple a b c hab hac hbc 0=a := rfl +omit [DecidableEq K] in +@[simp] lemma triple_one (a b c : K) (hab : a≠b) (hac : a≠c) (hbc : b≠c) : + triple a b c hab hac hbc 1=b := rfl +omit [DecidableEq K] in +@[simp] lemma triple_two (a b c : K) (hab : a≠b) (hac : a≠c) (hbc : b≠c) : + triple a b c hab hac hbc 2=c := rfl + +def put3 (S : Stack K) (a b c : K) (A B C : List Bool) : Stack K := + Function.update (Function.update (Function.update S a A) b B) c C +lemma frame_triple (S : Stack K) (a b c : K) (hab : a≠b) (hac : a≠c) (hbc : b≠c) + (A B C : List Bool) : frame (triple a b c hab hac hbc) A B C S=put3 S a b c A B C := by + funext j + by_cases hja : j=a + · subst j + have hh:=StackEmbedding.extend_on (triple a b c hab hac hbc) ![A,B,C] S 0 + simpa [frame,put3,hab,hac,hbc,hab.symm,hac.symm,hbc.symm] using hh + by_cases hjb : j=b + · subst j + have hh:=StackEmbedding.extend_on (triple a b c hab hac hbc) ![A,B,C] S 1 + simpa [frame,put3,hab,hac,hbc,hab.symm,hac.symm,hbc.symm] using hh + by_cases hjc : j=c + · subst j + have hh:=StackEmbedding.extend_on (triple a b c hab hac hbc) ![A,B,C] S 2 + simpa [frame,put3] using hh + have he : ¬∃ k,triple a b c hab hac hbc k=j := by + rintro ⟨k,hk⟩; fin_cases k <;> simp_all + rw [frame,StackEmbedding.extend_off _ _ _ j he] + simp [put3,hja,hjb,hjc] +lemma put3_same (S : Stack K) (a b c : K) (_ : a≠b) (hac : a≠c) (hbc : b≠c) : + put3 S a b c (S a) (S b) (S c)=S := by + funext j + by_cases hja : j=a <;> by_cases hjb : j=b <;> by_cases hjc : j=c <;> simp_all [put3] + +def clearRaw : Proc (Fin 3) := ⟨Unit,WordOps.clear⟩ +def reverseRaw : Proc (Fin 3) := ⟨Unit,StackReverse.program⟩ +def duplicateRaw : Proc (Fin 3) := ⟨Unit,WordOps.duplicate⟩ +def transferRaw : Proc (Fin 3) := ⟨Unit,TreeTransfer.program⟩ +lemma clearRaw_exec (A B C : List Bool) : + Exec clearRaw ![A,B,C] ![[],B,C] (A.length+1) := + ⟨_,le_rfl,WordOps.run_clear A B C none⟩ +lemma reverseRaw_exec (A B C : List Bool) : + Exec reverseRaw ![A,B,C] ![[],A.reverse++B,C] (A.length+1) := + ⟨_,le_rfl,StackReverse.run_reverse A B C none⟩ +lemma duplicateRaw_exec (A B C : List Bool) : + Exec duplicateRaw ![A,B,C] ![[],A.reverse++B,A.reverse++C] (A.length+1) := + ⟨_,le_rfl,WordOps.run_duplicate A B C none⟩ +lemma transferRaw_exec (x : TreeData.Data) (A B : List Bool) : + Exec transferRaw ![TreeData.encode x++A,B,[false]] ![A,(TreeData.encode x).reverse++B,[]] + ((TreeData.encode x).length+1) := + ⟨_,le_rfl,TreeTransfer.run_transfer x A B none⟩ +end MatchingFPRAS.RegisterProc + +end OAI diff --git a/lean/OAI/Combinatorics/MatchingCount/Machines/RegisterStructured.lean b/lean/OAI/Combinatorics/MatchingCount/Machines/RegisterStructured.lean new file mode 100644 index 0000000000000000000000000000000000000000..c6f24c38340c44f28bdee06631bcb501d2a2a13d --- /dev/null +++ b/lean/OAI/Combinatorics/MatchingCount/Machines/RegisterStructured.lean @@ -0,0 +1,80 @@ +import Mathlib +import OAI.Combinatorics.MatchingCount.Machines.RegisterControl + +namespace OAI + +namespace MatchingFPRAS.RegisterStructured +open RegisterProc TreeData TreeMachine RegisterControl + +variable {R : Type} [DecidableEq R] + +inductive Select where | test | left | right | halt deriving DecidableEq, Inhabited +instance : Fintype Select := ⟨{.test,.left,.right,.halt},by intro s; cases s <;> simp⟩ +def selectCode (i : R) (P Q : Proc (K R)) : Select → RegisterControl.Instr R Select + | .test => .branch i .left .right + | .left => .call P .halt + | .right => .call Q .halt + | .halt => .halt +def select (i : R) (P Q : Proc (K R)) : Proc (K R) := compile (selectCode i P Q) +lemma select_nil (i : R) (P Q : Proc (K R)) (E F : Env R) (n : ℕ) + (hi : E i=.nil) (h : Exec P (encodeEnv E) (encodeEnv F) n) : + Exec (select i P Q) (encodeEnv E) (encodeEnv F) (n+3) := by + have hh : RegisterControl.Runs (selectCode i P Q) (some Select.halt) F F 1 := + Runs.step _ _ _ _ _ 0 1 (Effect.halt _) (Runs.done _) + have hl : RegisterControl.Runs (selectCode i P Q) (some Select.left) E F ((n+1)+1) := + Runs.step _ _ _ _ _ _ _ (Effect.call _ _ _ _ n h) hh + have ht : RegisterControl.Runs (selectCode i P Q) (some Select.test) E F (1+((n+1)+1)) := + Runs.step _ _ _ _ _ _ _ (Effect.nilBranch E i _ _ hi) hl + exact (compile_exec _ _ _ _ ht).mono (by omega) +lemma select_cons (i : R) (P Q : Proc (K R)) (E F : Env R) (n : ℕ) (x y : Data) + (hi : E i=.cons x y) (h : Exec Q (encodeEnv E) (encodeEnv F) n) : + Exec (select i P Q) (encodeEnv E) (encodeEnv F) (n+3) := by + have hh : RegisterControl.Runs (selectCode i P Q) (some Select.halt) F F 1 := + Runs.step _ _ _ _ _ 0 1 (Effect.halt _) (Runs.done _) + have hr : RegisterControl.Runs (selectCode i P Q) (some Select.right) E F ((n+1)+1) := + Runs.step _ _ _ _ _ _ _ (Effect.call _ _ _ _ n h) hh + have ht : RegisterControl.Runs (selectCode i P Q) (some Select.test) E F (1+((n+1)+1)) := + Runs.step _ _ _ _ _ _ _ (Effect.consBranch E i _ _ x y hi) hr + exact (compile_exec _ _ _ _ ht).mono (by omega) + +inductive Loop where | test | body | halt deriving DecidableEq, Inhabited +instance : Fintype Loop := ⟨{.test,.body,.halt},by intro l; cases l <;> simp⟩ +def loopCode (i : R) (P : Proc (K R)) : Loop → RegisterControl.Instr R Loop + | .test => .branch i .halt .body + | .body => .call P .test + | .halt => .halt +def loop (i : R) (P : Proc (K R)) : Proc (K R) := compile (loopCode i P) + +lemma loop_exec (i : R) (P : Proc (K R)) (E : ℕ → Env R) (n B : ℕ) + (hc : ∀ k + intro E _nonempty _body he + have hh : RegisterControl.Runs (loopCode i P) (some Loop.halt) (E 0) (E 0) 1 := + Runs.step _ _ _ _ _ 0 1 (Effect.halt _) (Runs.done _) + simpa only [Nat.zero_mul,Nat.zero_add] using RegisterControl.Runs.step (M:=loopCode i P) Loop.test (E 0) (some Loop.halt) (E 0) (E 0) 1 1 (Effect.nilBranch _ i Loop.halt Loop.body he) hh + | succ n ih => + intro E hc hb he + have ht := ih (fun k=>E (k+1)) (fun k hk=>hc (k+1) (by omega)) + (fun k hk=>hb (k+1) (by omega)) he + have hr : RegisterControl.Runs (loopCode i P) (some Loop.body) (E 0) (E (n+1)) + ((B+1)+(n*(B+2)+2)) := + Runs.step _ _ _ _ _ _ _ (Effect.call _ _ _ _ B (hb 0 (by omega))) ht + cases hx : E 0 i with + | nil => exact False.elim (hc 0 (by omega) hx) + | cons x y => + have hh : RegisterControl.Runs (loopCode i P) (some Loop.test) (E 0) (E (n+1)) + (1+((B+1)+(n*(B+2)+2))) := + Runs.step _ _ _ _ _ _ _ (Effect.consBranch _ i _ _ x y hx) hr + convert hh using 1; ring + exact compile_exec _ _ _ _ (aux n E hc hb he) +end MatchingFPRAS.RegisterStructured + +end OAI diff --git a/lean/OAI/Combinatorics/MatchingCount/Machines/RegisterTree.lean b/lean/OAI/Combinatorics/MatchingCount/Machines/RegisterTree.lean new file mode 100644 index 0000000000000000000000000000000000000000..a9915d889b3aea186c35ec8e165d3fb17e320d7d --- /dev/null +++ b/lean/OAI/Combinatorics/MatchingCount/Machines/RegisterTree.lean @@ -0,0 +1,125 @@ +import Mathlib +import OAI.Combinatorics.MatchingCount.Machines.RegisterProc + +namespace OAI + +namespace MatchingFPRAS.RegisterProc +open Turing MachineCost TreeData + +lemma exec_perm (P : Proc (Fin 3)) (e : Fin 3 ≃ Fin 3) (S T : Stack (Fin 3)) + (n : ℕ) (h : Exec P (S ∘ e) (T ∘ e) n) : Exec (reindex P e.toEmbedding) S T n := by + have hf (S : Stack (Fin 3)) : frame e.toEmbedding (S (e 0)) (S (e 1)) (S (e 2)) S=S := by + funext j + obtain ⟨i,rfl⟩:=e.surjective j + have hh:=StackEmbedding.extend_on e.toEmbedding ![S (e 0),S (e 1),S (e 2)] S i + fin_cases i <;> exact hh + have hs : S ∘ e=![S (e 0),S (e 1),S (e 2)] := by funext i; fin_cases i <;> rfl + have ht : T ∘ e=![T (e 0),T (e 1),T (e 2)] := by funext i; fin_cases i <;> rfl + rw [hs,ht] at h + have hh:=exec_reindex P e.toEmbedding S _ _ _ _ _ _ n h + rw [hf] at hh + have hf' : frame e.toEmbedding (T (e 0)) (T (e 1)) (T (e 2)) S=T := by + funext j + obtain ⟨i,rfl⟩:=e.surjective j + have he:=StackEmbedding.extend_on e.toEmbedding ![T (e 0),T (e 1),T (e 2)] S i + fin_cases i <;> exact he + rwa [hf'] at hh + +def p02 : Fin 3 ≃ Fin 3 := Equiv.swap 0 2 +def p01 : Fin 3 ≃ Fin 3 := Equiv.swap 0 1 +def p12 : Fin 3 ≃ Fin 3 := Equiv.swap 1 2 +def p201 : Fin 3 ≃ Fin 3 := p02.trans p01 + +def p120 : Fin 3 ≃ Fin 3 := p201.symm +@[simp] lemma vector_p01 (A B C : List Bool) : ![A,B,C] ∘ p01=![B,A,C] := by + funext i; fin_cases i <;> rfl +@[simp] lemma vector_p02 (A B C : List Bool) : ![A,B,C] ∘ p02=![C,B,A] := by + funext i; fin_cases i <;> rfl +@[simp] lemma vector_p12 (A B C : List Bool) : ![A,B,C] ∘ p12=![A,C,B] := by + funext i; fin_cases i <;> rfl +@[simp] lemma vector_p201 (A B C : List Bool) : ![A,B,C] ∘ p201=![C,A,B] := by + funext i; fin_cases i <;> rfl +@[simp] lemma vector_p120 (A B C : List Bool) : ![A,B,C] ∘ p120=![B,C,A] := by + funext i; fin_cases i <;> rfl + +def reverse02 : Proc (Fin 3) := reindex reverseRaw p12.toEmbedding +def reverse10 : Proc (Fin 3) := reindex reverseRaw p01.toEmbedding +def reverse20 : Proc (Fin 3) := reindex reverseRaw p201.toEmbedding +def reverse21 : Proc (Fin 3) := reindex reverseRaw p02.toEmbedding +lemma reverse02_exec (A B C : List Bool) : + Exec reverse02 ![A,B,C] ![[],B,A.reverse++C] (A.length+1) := by + apply exec_perm + simpa only [vector_p12] using reverseRaw_exec A C B +lemma reverse10_exec (A B C : List Bool) : + Exec reverse10 ![A,B,C] ![B.reverse++A,[],C] (B.length+1) := by + apply exec_perm + simpa only [vector_p01] using reverseRaw_exec B A C +lemma reverse20_exec (A B C : List Bool) : + Exec reverse20 ![A,B,C] ![C.reverse++A,B,[]] (C.length+1) := by + apply exec_perm + simpa only [vector_p201] using reverseRaw_exec C A B +lemma reverse21_exec (A B C : List Bool) : + Exec reverse21 ![A,B,C] ![A,C.reverse++B,[]] (C.length+1) := by + apply exec_perm + simpa only [vector_p02] using reverseRaw_exec C B A + +def finishCons : Proc (Fin 3) := atom (.push 0 (fun _=>false) (.push 1 (fun _=>true) .halt)) +lemma finishCons_exec (A : List Bool) : Exec finishCons ![[],A,[]] ![[false],true::A,[]] 1 := by + apply exec_atom + simp only [TM2.stepAux] + congr 1 + funext i; fin_cases i <;> simp + +def cons : Proc (Fin 3) := seq reverse02 (seq reverse21 finishCons) +lemma cons_exec (x y : Data) : + Exec cons ![encode x,encode y,[]] ![encode .nil,encode (.cons x y),[]] + (2*(encode x).length+3) := by + have h₁:=reverse02_exec (encode x) (encode y) [] + have h₂:=reverse21_exec [] (encode y) (encode x).reverse + simp only [List.append_nil,List.reverse_reverse,List.length_reverse] at h₁ h₂ + have hh:=h₁.seq (h₂.seq (finishCons_exec (encode x++encode y))) + exact hh.mono (by omega) + +def clear1 : Proc (Fin 3) := reindex clearRaw p01.toEmbedding +lemma clear1_exec (A B C : List Bool) : Exec clear1 ![A,B,C] ![A,[],C] (B.length+1) := by + apply exec_perm + simpa only [vector_p01] using clearRaw_exec B A C + +def copy : Proc (Fin 3) := seq clear1 (seq duplicateRaw (seq reverse10 reverse21)) +lemma copy_exec (A B : List Bool) : Exec copy ![A,B,[]] ![A,A,[]] + (B.length+3*A.length+4) := by + have h₁:=clear1_exec A B [] + have h₂:=duplicateRaw_exec A [] [] + have h₃:=reverse10_exec [] A.reverse A.reverse + have h₄:=reverse21_exec A [] A.reverse + simp only [List.reverse_reverse,List.append_nil,List.length_reverse] at h₂ h₃ h₄ + have hh:=h₁.seq (h₂.seq (h₃.seq h₄)) + exact hh.mono (by omega) + +def startSplit : Proc (Fin 3) := atom (.pop 1 (fun v _=>v) (.push 0 (fun _=>false) .halt)) +lemma startSplit_exec (A : List Bool) : Exec startSplit ![[],true::A,[]] ![[false],A,[]] 1 := by + apply exec_atom + simp only [TM2.stepAux] + congr 1 + funext i; fin_cases i <;> simp +def transfer12 : Proc (Fin 3) := reindex transferRaw p120.toEmbedding +lemma transfer12_exec (x : Data) (A B : List Bool) : + Exec transfer12 ![[false],encode x++A,B] ![[],A,(encode x).reverse++B] + ((encode x).length+1) := by + apply exec_perm + simpa only [vector_p120] using transferRaw_exec x A B + +def split : Proc (Fin 3) := seq clearRaw (seq startSplit (seq transfer12 reverse20)) +lemma split_exec (A : List Bool) (x y : Data) : + Exec split ![A,encode (.cons x y),[]] ![encode x,encode y,[]] + (A.length+2*(encode x).length+4) := by + have h₁:=clearRaw_exec A (encode (.cons x y)) [] + have h₂:=startSplit_exec (encode x++encode y) + have h₃:=transfer12_exec x (encode y) [] + have h₄:=reverse20_exec [] (encode y) (encode x).reverse + simp only [List.reverse_reverse,List.append_nil,List.length_reverse] at h₃ h₄ + have hh:=h₁.seq (h₂.seq (h₃.seq h₄)) + exact hh.mono (by omega) +end MatchingFPRAS.RegisterProc + +end OAI diff --git a/lean/OAI/Combinatorics/MatchingCount/Machines/SupportedCompiler.lean b/lean/OAI/Combinatorics/MatchingCount/Machines/SupportedCompiler.lean new file mode 100644 index 0000000000000000000000000000000000000000..6ebb4e9d4b0bba0f1b3cc677f2ecbe220cae9476 --- /dev/null +++ b/lean/OAI/Combinatorics/MatchingCount/Machines/SupportedCompiler.lean @@ -0,0 +1,109 @@ +import Mathlib +import OAI.Combinatorics.MatchingCount.Complexity.AlphabetCompilerCost + +namespace OAI + +namespace MatchingFPRAS.SupportedCompiler +open Turing MachineCost +open scoped Classical + +variable {Γ Λ σ : Type*} [Inhabited Γ] [Inhabited Λ] [Inhabited σ] +variable (M : Λ → TM1.Stmt Γ Λ σ) (S : Finset Λ) (hS : TM1.Supports M S) +noncomputable def cost : ℕ := S.sup (fun l=>statementCost (M l)) +omit [Inhabited Γ] [Inhabited Λ] [Inhabited σ] in +lemma cost_le {l : Λ} (hl : l ∈ S) : statementCost (M l) ≤ cost M S := Finset.le_sup (f:=fun l=>statementCost (M l)) hl +include hS +omit [Inhabited σ] in +lemma advance_supported {c : TM1.Cfg Γ Λ σ} (hc : c.l ∈ S.insertNone) : + (advance (TM1.step M) c).l ∈ S.insertNone := by + cases he:TM1.step M c with + | none => simpa only [advance,he,Option.getD_none] using hc + | some c' => + simpa only [advance,he,Option.getD_some] using TM1.step_supports M hS he hc +omit [Inhabited σ] in +lemma run_supported {c : TM1.Cfg Γ Λ σ} (hc : c.l ∈ S.insertNone) (n : ℕ) : + (MachineCost.run (TM1.step M) n c).l ∈ S.insertNone := by + induction n generalizing c with + | zero => exact hc + | succ n ih => exact ih (advance_supported M S hS hc) + +theorem post_time {c : TM1.Cfg Γ Λ σ} (hc : c.l ∈ S.insertNone) (n : ℕ) : + ∃ k ≤ cost M S*n, + MachineCost.run (TM0.step (TM1to0.tr M)) k (TM1to0.trCfg M c)= + TM1to0.trCfg M (MachineCost.run (TM1.step M) n c) := by + induction n generalizing c with + | zero => exact ⟨0,by simp,rfl⟩ + | succ n ih => + rcases c with ⟨l,v,T⟩ + cases l with + | none => + have he : ∀ j,MachineCost.run (TM1.step M) j ⟨none,v,T⟩=⟨none,v,T⟩ := by + intro j + induction j with + | zero => rfl + | succ j hj => exact hj + exact ⟨0,Nat.zero_le _,by rw [MachineCost.run,he]⟩ + | some l => + have hl : l ∈ S:=Finset.some_mem_insertNone.mp hc + obtain ⟨j,hj,hjc,hje⟩:=statement_translation_time M (M l) v T + have hc' : (TM1.stepAux (M l) v T).l ∈ S.insertNone := + advance_supported M S hS hc + obtain ⟨k,hk,hke⟩:=ih hc' + refine ⟨j+k,?_,?_⟩ + · have hj' := hjc.trans (cost_le M S hl) + calc + j+k ≤ cost M S+cost M S*n:=Nat.add_le_add hj' hk + _=cost M S*(n+1):=by ring + · rw [run_add] + change MachineCost.run (TM0.step (TM1to0.tr M)) k + (MachineCost.run (TM0.step (TM1to0.tr M)) j ⟨(some (M l),v),T⟩)=_ + rw [hje,hke] + rfl +end MatchingFPRAS.SupportedCompiler + +namespace MatchingFPRAS.AlphabetCost +open Turing MachineCost SupportedCompiler +open scoped Classical + +variable {Γ Λ σ : Type*} [Inhabited Γ] [Inhabited Λ] [Inhabited σ] +variable {n : ℕ} (enc : Γ → List.Vector Bool n) (dec : List.Vector Bool n → Γ) + (enc0 : enc default = List.Vector.replicate n false) + (encdec : ∀ a,dec (enc a)=a) (M : Λ → TM1.Stmt Γ Λ σ) + (S : Finset Λ) (hS : TM1.Supports M S) +include encdec hS +noncomputable def supportedWrites : ℕ := S.sup (fun l=>writesCount (M l)) +omit [Inhabited σ] hS in +lemma one_step_supported (_hS : TM1.Supports M S) {c : TM1.Cfg Γ Λ σ} (hc : c.l ∈ S.insertNone) : + ∃ t : ℕ,t ≤ supportedWrites M S+1 ∧ + MachineCost.run (TM1.step (TM1to1.tr enc dec M)) t (TM1to1.trCfg enc enc0 c)= + TM1to1.trCfg enc enc0 (advance (TM1.step M) c) := by + rcases c with ⟨l,v,T⟩ + obtain ⟨L,R,rfl⟩:=T.exists_mk' + cases l with + | none => exact ⟨0,Nat.zero_le _,rfl⟩ + | some l => + obtain ⟨t,ht,he⟩:=statement_time enc dec enc0 encdec M (M l) v L R + have hh : writesCount (M l) ≤ supportedWrites M S:= + Finset.le_sup (f:=fun l=>writesCount (M l)) (Finset.some_mem_insertNone.mp hc) + refine ⟨t+1,by omega,?_⟩ + simpa only [MachineCost.run,advance,TM1.step,Option.map_some,TM1to1.trCfg,TM1to1.tr, + Option.getD_some,TM1to1.trTape_mk'] using he + +omit [Inhabited σ] in +theorem execution_supported {c : TM1.Cfg Γ Λ σ} (hc : c.l ∈ S.insertNone) (k : ℕ) : + ∃ t : ℕ,t ≤ k*(supportedWrites M S+1) ∧ + MachineCost.run (TM1.step (TM1to1.tr enc dec M)) t (TM1to1.trCfg enc enc0 c)= + TM1to1.trCfg enc enc0 (MachineCost.run (TM1.step M) k c) := by + induction k generalizing c with + | zero => exact ⟨0,by simp,rfl⟩ + | succ k ih => + obtain ⟨t₁,ht₁,he₁⟩:=one_step_supported enc dec enc0 encdec M S hS hc + obtain ⟨t₂,ht₂,he₂⟩:=ih (advance_supported M S hS hc) + refine ⟨t₁+t₂,?_,?_⟩ + · calc + t₁+t₂ ≤ (supportedWrites M S+1)+k*(supportedWrites M S+1) := Nat.add_le_add ht₁ ht₂ + _=(k+1)*(supportedWrites M S+1) := by ring + · rw [run_add,he₁,he₂]; rfl +end MatchingFPRAS.AlphabetCost + +end OAI diff --git a/lean/OAI/Combinatorics/MatchingCount/Machines/TableLookup.lean b/lean/OAI/Combinatorics/MatchingCount/Machines/TableLookup.lean new file mode 100644 index 0000000000000000000000000000000000000000..817d0c2a7d3e0a7283c848fe9363b34c5ab48d21 --- /dev/null +++ b/lean/OAI/Combinatorics/MatchingCount/Machines/TableLookup.lean @@ -0,0 +1,100 @@ +import Mathlib +import OAI.Combinatorics.MatchingCount.Sampling.RankOrder +import OAI.Combinatorics.MatchingCount.Machines.TreeLookup + +namespace OAI + +namespace MatchingFPRAS.TreeData +open Data + +def bit (b : Bool) : Data := if b then .cons .nil .nil else .nil +def nat (n : ℕ) : Data := ofList (n.bits.map bit) +def row (xs : List ℕ) : Data := ofList (xs.map nat) +def table (xs : List (List ℕ)) : Data := ofList (xs.map row) +@[simp] lemma nat_zero : nat 0=.nil := by simp [nat,Nat.bits,ofList] +@[simp] lemma row_nil : row []=.nil := rfl +lemma map_getD {α β : Type} (f : α→β) (xs : List α) (n : ℕ) (d : α) : + (xs.map f).getD n (f d)=f (xs.getD n d) := by + induction xs generalizing n with + | nil => simp + | cons _ _ ih => + cases n with + | zero => rfl + | succ index => exact ih index +lemma row_getD (xs : List ℕ) (n : ℕ) : + (xs.map nat).getD n .nil=nat (xs.getD n 0) := by + simpa only [nat_zero] using map_getD nat xs n 0 +lemma table_getD (xs : List (List ℕ)) (n : ℕ) : + (xs.map row).getD n .nil=row (xs.getD n []) := by + simpa only [row_nil] using map_getD row xs n [] +end MatchingFPRAS.TreeData + +namespace MatchingFPRAS.TreeLookup +open TreeData TreeMachine RegisterProc + +lemma result_frame (E : Env R) (n : ℕ) (xs : List Data) : result E n xs 3=E 3 := by + induction n generalizing E xs with + | zero => cases xs <;> simp [result,putPair] + | succ n ih => cases xs with + | nil => simp [result] + | cons x xs => simpa [result,putPair] using ih (putPair (putPair E 2 0 .nil (unary n)) 2 1 x (ofList xs)) xs +end MatchingFPRAS.TreeLookup + +namespace MatchingFPRAS.TableLookup +open TreeData TreeMachine RegisterProc + +abbrev R := TreeLookup.R +abbrev first (E : Env R) (a : ℕ) (t : UnitRefresh.Materialized.Table) := + TreeLookup.result E a (t.map row) +def middle (E : Env R) (a : ℕ) (t : UnitRefresh.Materialized.Table) : Env R := + let F:=first E a t + let G:=putPair F 2 1 (F 2) (F 2) + putPair G 3 0 (G 3) (G 3) +def result (E : Env R) (a r : ℕ) (t : UnitRefresh.Materialized.Table) : Env R := + TreeLookup.result (middle E a t) r ((t.getD a []).map nat) + +def program : Proc (K R) := + seq (compile TreeLookup.program) + (seq (procedure (Instr.copy (Λ:=Unit) 2 1 (by decide) ())) + (seq (procedure (Instr.copy (Λ:=Unit) 3 0 (by decide) ())) (compile TreeLookup.program))) + +lemma output (E : Env R) (a r : ℕ) (t : UnitRefresh.Materialized.Table) : + result E a r t 2=nat (UnitRefresh.Materialized.read t a r) := by + rw [result,TreeLookup.output,row_getD] + rfl +lemma middle_zero (E : Env R) (a : ℕ) (t : UnitRefresh.Materialized.Table) : + middle E a t 0=E 3 := by simp [middle,putPair,TreeLookup.result_frame] +lemma middle_one (E : Env R) (a : ℕ) (t : UnitRefresh.Materialized.Table) : + middle E a t 1=row (t.getD a []) := by + change (putPair (putPair (first E a t) 2 1 (first E a t 2) (first E a t 2)) 3 0 + ((putPair (first E a t) 2 1 (first E a t 2) (first E a t 2)) 3) + ((putPair (first E a t) 2 1 (first E a t 2) (first E a t 2)) 3)) 1=_ + simp only [putPair,Function.update_of_ne (by decide : (1 : R)≠0), + Function.update_of_ne (by decide : (1 : R)≠3),Function.update_self] + exact (TreeLookup.output E a (t.map row)).trans (table_getD t a) + +theorem stack_exec (E : Env R) (a r : ℕ) (t : UnitRefresh.Materialized.Table) (B : ℕ) + (h : SizeBound E B) (ha : E 0=unary a) (ht : E 1=table t) (hr : E 3=unary r) : + Exec program (encodeEnv E) (encodeEnv (result E a r t)) + ((20*(a+r+2)+8)*(B+1)) ∧ SizeBound (result E a r t) B := by + let F:=first E a t + let G:=putPair F 2 1 (F 2) (F 2) + have hF : SizeBound F B := (TreeLookup.runs a (t.map row) E B h ha ht).2 + have hG : SizeBound G B := hF.putPair 2 1 (F 2) (F 2) (hF 2) (hF 2) + have hH : SizeBound (middle E a t) B := hG.putPair 3 0 (G 3) (G 3) (hG 3) (hG 3) + have h₁:=TreeLookup.stack_exec a (t.map row) E B h ha ht + have h₂:=copy_exec F 2 1 (by decide) () + have h₃:=copy_exec G 3 0 (by decide) () + have h₄:=TreeLookup.stack_exec r ((t.getD a []).map nat) (middle E a t) B hH + ((middle_zero E a t).trans hr) (middle_one E a t) + constructor + · have he:=h₁.seq (h₂.seq (h₃.seq h₄)) + apply he.mono + have hF1:=hF 1; have hF2:=hF 2 + have hG0:=hG 0; have hG3:=hG 3 + nlinarith + · exact (TreeLookup.runs r ((t.getD a []).map nat) (middle E a t) B hH + ((middle_zero E a t).trans hr) (middle_one E a t)).2 +end MatchingFPRAS.TableLookup + +end OAI diff --git a/lean/OAI/Combinatorics/MatchingCount/Machines/TreeBindings.lean b/lean/OAI/Combinatorics/MatchingCount/Machines/TreeBindings.lean new file mode 100644 index 0000000000000000000000000000000000000000..cfa0efe40a67cf11880ec94d0ebecfef1e54e145 --- /dev/null +++ b/lean/OAI/Combinatorics/MatchingCount/Machines/TreeBindings.lean @@ -0,0 +1,101 @@ +import Mathlib +import OAI.Combinatorics.MatchingCount.Algorithm.TreeGeneratedStage +import OAI.Combinatorics.MatchingCount.Machines.TreeScaleStateUpdate + +namespace OAI + +namespace MatchingFPRAS.ExecutableSource +open TreeTyped TreeFraction TreeTyped.Numbered ExecutableBottleneck ExecutableHierarchy ExecutableRefresh Enlargement RealGeometry NumericLadder ExecutableLadder NumericMarking + +attribute [local instance] NumberedHierarchy.labelOrder +attribute [local instance] Transport.sym2Order Transport.bagEdgeOrder Transport.bagEdgeFintype +attribute [local instance] UnitRefresh.Computable.allowedDec Transport.prodOrder Transport.sumOrder +local instance (priority := 2000) {A B : Type} [LinearOrder A] [LinearOrder B] : LE (A×B) := Transport.prodOrder.toLE +local instance (priority := 2000) {A B : Type} [LinearOrder A] [LinearOrder B] : LT (A×B) := Transport.prodOrder.toLT +local instance (priority := 2000) {A B : Type} [LinearOrder A] [LinearOrder B] : Preorder (A×B) := Transport.prodOrder.toPreorder + +lemma logicalEdges_eq_ofFn (n : ℕ) : logicalEdges (List.range n)= + (List.ofFn (UnitRefresh.orderedEnum (LogicalEdge (Fin n)))).map logicalRepr := by + classical + rw [UnitRefresh.ofFn_orderedEnum] + have ha : (logicalEdges (List.range n)).Pairwise (· ≤ ·) := + (logicalEdges_pairwise n).imp (fun h=>le_of_lt h) + have hb : (((Finset.univ : Finset (LogicalEdge (Fin n))).sort (· ≤ ·)).map logicalRepr).Pairwise (· ≤ ·) := by + apply List.pairwise_map.mpr + exact (Finset.pairwise_sort _ _).imp (fun h=>(logicalRepr_le _ _).mpr h) + have hn : (logicalEdges (List.range n)).Nodup := (logicalEdges_pairwise n).imp (fun h=>h.ne) + have hm := (Finset.sort_nodup (Finset.univ : Finset (LogicalEdge (Fin n))) (· ≤ ·)).map logicalRepr_injective + have hp : (logicalEdges (List.range n)).Perm + (((Finset.univ : Finset (LogicalEdge (Fin n))).sort (· ≤ ·)).map logicalRepr) := by + apply List.perm_of_nodup_nodup_toFinset_eq hn hm + ext e + simp only [List.mem_toFinset,List.mem_map,Finset.mem_sort,Finset.mem_univ,true_and] + constructor + · exact logicalEdges_complete e + · rintro ⟨a,rfl⟩; exact logicalRepr_mem a + exact hp.eq_of_pairwise (fun _ _ _ _ h₁ h₂=>@le_antisymm _ Transport.prodOrder.toPartialOrder _ _ h₁ h₂) ha hb + +def centralIndexArg : Realizer (fun x : BagBuildInput×RawLogical=>(x.1,centralKey x)) := + (TreeTyped.pair (first (A:=BagBuildInput) (B:=RawLogical)) centralKeyRealizer).congr (fun _=>rfl) +lemma polynomial_centralIndexArg : PolynomialTime centralIndexArg := + polynomial_congr _ (TreeTyped.polynomial_pair polynomial_first polynomial_centralKey) +def centralIndex (x : BagBuildInput×RawLogical) : ℕ := tableIndex (x.1,centralKey x) +def centralIndexRealizer : Realizer centralIndex := + (composition (f:=fun x : BagBuildInput×RawLogical=>(x.1,centralKey x)) (g:=tableIndex) + centralIndexArg tableIndexRealizer).congr (by intro x; simp only [Function.comp_apply,centralIndex]) +lemma polynomial_centralIndex : PolynomialTime centralIndexRealizer := + polynomial_congr _ (polynomial_composition polynomial_centralIndexArg polynomial_tableIndex) +def centralBinding (x : BagBuildInput×RawLogical) : RawLogical×ℕ := + (x.2,centralIndex x) +def centralBindingRealizer : Realizer centralBinding := + (TreeTyped.pair (second (A:=BagBuildInput) (B:=RawLogical)) centralIndexRealizer).congr (fun _=>rfl) +lemma polynomial_centralBinding : PolynomialTime centralBindingRealizer := + polynomial_congr _ (TreeTyped.polynomial_pair polynomial_second polynomial_centralIndex) + +def sourceBindings (x : BagBuildInput) : Bindings := + (logicalEdges x.1.2).map (fun e=>centralBinding (x,e)) +def sourceBindingsRealizer : Realizer sourceBindings := (rowsWith centralBindingRealizer + (composition (first (A:=BuildInput) (B:=List Bool)).snd logicalEdgesRealizer)).congr (fun _=>rfl) +lemma polynomial_sourceBindings : PolynomialTime sourceBindingsRealizer := + polynomial_congr _ (polynomial_rowsWith polynomial_centralBinding + (polynomial_composition (polynomial_snd polynomial_first) polynomial_logicalEdges)) + +lemma sourceBindings_source {n : ℕ} [Nontrivial (Fin n)] (hn : 2≤n) + (w : Fin n→Fin n→ℚ) (hw : ∀ i j,0≤w i j) (K : ℕ) : + sourceBindings (((matrixRep w,List.replicate (2*K+2) false),List.range n),List.replicate (2*K) false)= + (List.ofFn (UnitRefresh.orderedEnum (LogicalEdge (Fin n)))).map + (fun e=>(logicalRepr e,index (RationalSource.centralEdge w K e))) := by + unfold sourceBindings + rw [logicalEdges_eq_ofFn,List.map_map] + apply List.map_congr_left + intro e _he + dsimp only [Function.comp_def,centralBinding,centralIndex] + rw [centralKey_source hn w hw K] + unfold tableIndex + dsimp only + rw [sourceTables_catalog hn w hw K,sourceCatalog_index] + +abbrev GeneratedUpdateConfig := (BagBuildInput×ℕ)×ExecutableScaling.Vector +def generatedUpdateConfig (x : GeneratedUpdateConfig) : UpdateConfig := + ((x.1.2,x.1.1.1.2),(sourceBindings x.1.1,x.2)) +def generatedUpdateConfigRealizer : Realizer generatedUpdateConfig := (pair + (pair first.snd first.fst.fst.snd) + (pair (composition first.fst sourceBindingsRealizer) second)).congr (fun _=>rfl) +lemma polynomial_generatedUpdateConfig : PolynomialTime generatedUpdateConfigRealizer := by + unfold generatedUpdateConfigRealizer + apply polynomial_congr + dsimp only [Realizer.fst, Realizer.snd] + have := polynomial_sourceBindings + tree_cost + +lemma generatedUpdateConfig_source {G : GraphInput} [Nontrivial (Fin G.n)] (hn : 2≤G.n) + {j : ℕ} (s : FiniteTrial.ScaleState G j) (K : ℕ) : + generatedUpdateConfig (((((matrixRep s.activity,List.replicate (2*K+2) false),List.range G.n), + List.replicate (2*K) false),FiniteTrial.sourceD (G:=G) K),ExecutableScaling.vectorRep s.scale)= + sourceUpdateConfig s K := by + unfold generatedUpdateConfig sourceUpdateConfig + dsimp only + rw [sourceBindings_source hn s.activity (fun i j=>(s.activity_pos i j).le) K] +end MatchingFPRAS.ExecutableSource + +end OAI diff --git a/lean/OAI/Combinatorics/MatchingCount/Machines/TreeBottleneck.lean b/lean/OAI/Combinatorics/MatchingCount/Machines/TreeBottleneck.lean new file mode 100644 index 0000000000000000000000000000000000000000..9a0fa0d67dfe49bc3ec4e92e4b682280a8e2057c --- /dev/null +++ b/lean/OAI/Combinatorics/MatchingCount/Machines/TreeBottleneck.lean @@ -0,0 +1,263 @@ +import Mathlib +import OAI.Combinatorics.MatchingCount.Complexity.TreeChoiceCosts + +namespace OAI + +namespace MatchingFPRAS.TreeFraction +open TreeTyped + +def maximum (x : Fraction×Fraction) : Fraction := if less x then x.2 else x.1 +def minimum (x : Fraction×Fraction) : Fraction := if less x then x.1 else x.2 +def maximumRealizer : Realizer maximum := (choose lessRealizer second first).congr (fun _=>rfl) +def minimumRealizer : Realizer minimum := (choose lessRealizer first second).congr (fun _=>rfl) +lemma polynomial_maximum : PolynomialTime maximumRealizer := by + exact polynomial_congr _ (polynomial_choose polynomial_less polynomial_second polynomial_first) +lemma polynomial_minimum : PolynomialTime minimumRealizer := by + exact polynomial_congr _ (polynomial_choose polynomial_less polynomial_first polynomial_second) +lemma maximum_eq (x y : Fraction) : maximum (x,y)=x ∨ maximum (x,y)=y := by + unfold maximum; split_ifs <;> simp +lemma minimum_eq (x y : Fraction) : minimum (x,y)=x ∨ minimum (x,y)=y := by + unfold minimum; split_ifs <;> simp +lemma maximum_repr {x y : ℚ} (hx : 0≤x) (hy : 0≤y) : + maximum (repr x,repr y)=repr (max x y) := by + unfold maximum + rw [less_val _ _ x.pos y.pos,val_repr hx,val_repr hy] + simp only [decide_eq_true_eq] + split_ifs with h + · rw [max_eq_right (le_of_lt h)] + · rw [max_eq_left (le_of_not_gt h)] +lemma minimum_repr {x y : ℚ} (hx : 0≤x) (hy : 0≤y) : + minimum (repr x,repr y)=repr (min x y) := by + unfold minimum + rw [less_val _ _ x.pos y.pos,val_repr hx,val_repr hy] + simp only [decide_eq_true_eq] + split_ifs with h + · rw [min_eq_left (le_of_lt h)] + · rw [min_eq_right (le_of_not_gt h)] +lemma maximum_weight (x y : Fraction) : weight (maximum (x,y))≤ max (weight x) (weight y) := by + rcases maximum_eq x y with h|h <;> rw [h] + · exact le_max_left _ _ + · exact le_max_right _ _ +lemma minimum_weight (x y : Fraction) : weight (minimum (x,y))≤ max (weight x) (weight y) := by + rcases minimum_eq x y with h|h <;> rw [h] + · exact le_max_left _ _ + · exact le_max_right _ _ +lemma maximum_fold_weight (xs : List Fraction) (z : Fraction) (B : ℕ) + (hz : weight z≤B) (hx : ∀ x∈xs,weight x≤B) : + weight (xs.foldl (fun z x=>maximum (x,z)) z)≤B := by + induction xs generalizing z with + | nil => exact hz + | cons x xs ih => + apply ih _ ((maximum_weight x z).trans (max_le (hx x (by simp)) hz)) + intro x hx'; exact hx x (by simp [hx']) +lemma polynomial_maximumFold : PolynomialTime (fold maximumRealizer) := by + apply polynomial_fold polynomial_maximum Polynomial.X + intro xs z pre post he + simp only [Polynomial.eval_X] + apply maximum_fold_weight pre z _ (weight_snd (xs,z)) + intro x hx + exact (weight_mem hx).trans ((weight_prefix he).trans (weight_fst (xs,z))) +end MatchingFPRAS.TreeFraction + +namespace MatchingFPRAS.ExecutableBottleneck +open TreeTyped TreeFraction Polynomial + +abbrev Matrix := List (List Fraction) +def one : Fraction := (1,1) +def cell (x : Matrix×(ℕ×ℕ)) : Fraction := (x.1.getD x.2.1 []).getD x.2.2 one +def cellRealizer : Realizer cell := composition + (pair (composition (pair first second.fst) (getDFast [])) second.snd) (getDFast one) +lemma polynomial_cell : PolynomialTime cellRealizer := by + unfold cellRealizer + have h₁:=polynomial_getDFast ([] : List Fraction) + have h₂:=polynomial_getDFast one + exact polynomial_composition (polynomial_pair (polynomial_composition + (polynomial_pair polynomial_first (polynomial_fst polynomial_second)) h₁) + (polynomial_snd polynomial_second)) h₂ + +def square {A B : Type} (n : ℕ) (a : A) (f : A×(ℕ×ℕ)→B) : List (List B) := + (List.range n).map fun i=>(List.range n).map fun j=>f (a,(i,j)) +def squareRealizer {A B : Type} [Codec A] [Codec B] {n : A→ℕ} {f : A×(ℕ×ℕ)→B} + (N : Realizer n) (F : Realizer f) : Realizer (fun a=>square (n a) a f) := by + let rs:=composition N range + let e:=composition (pair first.fst (pair first.snd second)) F + let row:=composition (pair identity (composition first rs)) (mapWith e) + exact composition (pair identity rs) (mapWith row) +lemma polynomial_square {A B : Type} [Codec A] [Codec B] {n : A→ℕ} {f : A×(ℕ×ℕ)→B} + {N : Realizer n} {F : Realizer f} (hN : PolynomialTime N) (hF : PolynomialTime F) + (p : Polynomial ℕ) (hn : ∀ a,n a≤p.eval (weight a)) : PolynomialTime (squareRealizer N F) := by + have hR:=polynomial_boundedRange hN p hn + unfold squareRealizer + dsimp only + exact polynomial_composition (polynomial_pair polynomial_identity hR) + (polynomial_mapWith (polynomial_composition + (polynomial_pair polynomial_identity (polynomial_composition polynomial_first hR)) + (polynomial_mapWith (polynomial_composition + (polynomial_pair (polynomial_fst polynomial_first) + (polynomial_pair (polynomial_snd polynomial_first) polynomial_second)) hF)))) + +lemma cell_weight {M : Matrix} {B : ℕ} (h₁ : weight one≤B) + (hM : ∀ r∈M,∀ x∈r,weight x≤B) (i j : ℕ) : weight (cell (M,(i,j)))≤B := by + unfold cell + dsimp only + by_cases hi : ivia (x,c)).foldl (fun z v=>maximum (v,z)) (cell x) +def entryRealizer : Realizer entry := by + let vals:=composition (pair identity (composition (composition first listLength) range)) (mapWith viaRealizer) + exact (choose (composition second natEqual) (constant one) + (composition (pair vals cellRealizer) (fold maximumRealizer))).congr (by + intro x; simp only [entry,Function.comp_apply,decide_eq_true_eq,id_eq]) +lemma polynomial_entry : PolynomialTime entryRealizer := by + have hR : PolynomialTime (composition (composition (first (A:=Matrix) (B:=ℕ×ℕ)) listLength) range) := by + apply polynomial_boundedRange (by tree_poly) X + intro x; simpa using (list_length_le_weight x.1).trans (weight_fst x) + unfold entryRealizer + dsimp only + apply polynomial_congr + apply polynomial_choose (polynomial_composition polynomial_second polynomial_natEqual) (polynomial_constant one) + apply polynomial_composition _ polynomial_maximumFold + apply polynomial_pair _ polynomial_cell + exact polynomial_composition (polynomial_pair polynomial_identity hR) (polynomial_mapWith polynomial_via) + +def advance (M : Matrix) : Matrix := square M.length M entry +def advanceRealizer : Realizer advance := squareRealizer listLength entryRealizer +lemma polynomial_advance : PolynomialTime advanceRealizer := by + exact polynomial_square polynomial_listLength polynomial_entry X (fun a=>by simpa using list_length_le_weight a) +lemma advance_length (M : Matrix) : (advance M).length=M.length := by + simp [advance,square] +lemma entry_weight {M : Matrix} {B : ℕ} (h₁ : weight one≤B) + (hM : ∀ r∈M,∀ x∈r,weight x≤B) (i j : ℕ) : weight (entry (M,(i,j)))≤B := by + unfold entry + dsimp only + split_ifs + · exact h₁ + · apply maximum_fold_weight _ _ _ (cell_weight h₁ hM i j) + intro x hx + obtain ⟨c,hc,rfl⟩:=List.mem_map.mp hx + exact (minimum_weight _ _).trans (max_le (cell_weight h₁ hM i c) (cell_weight h₁ hM c j)) +lemma advance_entries {M : Matrix} {B : ℕ} (h₁ : weight one≤B) + (hM : ∀ r∈M,∀ x∈r,weight x≤B) : ∀ r∈advance M,∀ x∈r,weight x≤B := by + intro r hr x hx + obtain ⟨i,hi,rfl⟩:=List.mem_map.mp hr + obtain ⟨j,hj,rfl⟩:=List.mem_map.mp hx + exact entry_weight h₁ hM i j +lemma advance_weight {M : Matrix} {B : ℕ} (h₁ : weight one≤B) + (hM : ∀ r∈M,∀ x∈r,weight x≤B) : weight (advance M)≤1+M.length*(2+M.length*(B+1)) := by + unfold advance square + have h:=weight_map_bound (as:=List.range M.length) + (N:=1+M.length*(B+1)) (f:=fun i=>(List.range M.length).map fun j=>entry (M,(i,j))) (by + intro i _ + simpa [List.length_range,Nat.add_comm] using weight_map_bound (as:=List.range M.length) + (f:=fun j=>entry (M,(i,j))) (fun j _=>entry_weight h₁ hM i j)) + simp only [List.length_range] at h + exact h.trans_eq (by ring) + +def seedEntry (x : Matrix×(ℕ×ℕ)) : Fraction := if x.2.1=x.2.2 then one + else maximum (one,cell (x.1,(min x.2.1 x.2.2,max x.2.1 x.2.2))) +def seedEntryRealizer : Realizer seedEntry := by + let inds : Realizer (fun x : Matrix×(ℕ×ℕ)=>if x.2.1by simpa using list_length_le_weight a) + +def close (M : Matrix) : Matrix := M.foldl (fun z _=>advance z) (seed M) +def closeRealizer : Realizer close := composition (pair identity seedRealizer) + (fold (composition second advanceRealizer)) +lemma fold_advance_invariant (ls : List (List Fraction)) (M : Matrix) (B : ℕ) + (h₁ : weight one≤B) (hM : ∀ r∈M,∀ x∈r,weight x≤B) : + let R:=ls.foldl (fun z _=>advance z) M + R.length=M.length ∧ (∀ r∈R,∀ x∈r,weight x≤B) ∧ + weight R≤weight M+1+M.length*(2+M.length*(B+1)) := by + have hInv : ∀ (ls : List (List Fraction)) (M : Matrix), + (∀ r∈M,∀ x∈r,weight x≤B) → + (ls.foldl (fun z _=>advance z) M).length=M.length ∧ + (∀ r∈ls.foldl (fun z _=>advance z) M,∀ x∈r,weight x≤B) := by + intro ls + induction ls with + | nil => intro M hm; exact ⟨rfl,hm⟩ + | cons r ls ih => + intro M hm + obtain ⟨hl,hR⟩:=ih (advance M) (advance_entries h₁ hm) + exact ⟨hl.trans (advance_length M),hR⟩ + refine ⟨(hInv ls M hM).1,(hInv ls M hM).2,?_⟩ + cases ls using List.reverseRecOn with + | nil => simpa only [List.foldl_nil,Nat.add_assoc] using (Nat.le_add_right (weight M) (1+M.length*(2+M.length*(B+1)))) + | append_singleton ls r ih => + rw [List.foldl_append] + dsimp only [List.foldl] + have hw:=advance_weight h₁ (hInv ls M hM).2 + rw [(hInv ls M hM).1] at hw + omega + +lemma polynomial_closeFold : PolynomialTime (fold (composition (second (A:=List Fraction)) advanceRealizer)) := by + apply polynomial_fold (polynomial_composition polynomial_second polynomial_advance) + (X+1+X*(2+X*(X+C (weight one)+1))) + intro ls M pre _ _ + let S:=weight (ls,M) + have hM : weight M≤S := weight_snd (ls,M) + have hn : M.length≤S := (list_length_le_weight M).trans hM + have hi:=fold_advance_invariant pre M (S+weight one) (by omega) (by + intro r hr x hx + exact ((weight_mem hx).trans ((weight_mem hr).trans hM)).trans (Nat.le_add_right _ _)) + have hb := hi.2.2 + simp only [Polynomial.eval_add,Polynomial.eval_mul,Polynomial.eval_X,Polynomial.eval_one, + Polynomial.eval_ofNat,Polynomial.eval_C] + change weight (pre.foldl (fun z _=>advance z) M)≤S+1+S*(2+S*(S+weight one+1)) + have hp:=Nat.mul_le_mul hn (Nat.add_le_add_left (Nat.mul_le_mul_right (S+weight one+1) hn) 2) + omega +lemma polynomial_close : PolynomialTime closeRealizer := + polynomial_composition (polynomial_pair polynomial_identity polynomial_seed) polynomial_closeFold + +end MatchingFPRAS.ExecutableBottleneck + +end OAI diff --git a/lean/OAI/Combinatorics/MatchingCount/Machines/TreeBottleneckCorrect.lean b/lean/OAI/Combinatorics/MatchingCount/Machines/TreeBottleneckCorrect.lean new file mode 100644 index 0000000000000000000000000000000000000000..51b40046d496ba3c7b79c2d6aa77759de35d5683 --- /dev/null +++ b/lean/OAI/Combinatorics/MatchingCount/Machines/TreeBottleneckCorrect.lean @@ -0,0 +1,151 @@ +import Mathlib +import OAI.Combinatorics.MatchingCount.Sampling.DiscreteLadderSteps +import OAI.Combinatorics.MatchingCount.Machines.TreeBottleneck + +namespace OAI + +namespace MatchingFPRAS.TreeFraction +open TreeTyped + +lemma maximum_fold_repr (xs : List ℚ) (z : ℚ) (hz : 0≤z) (hx : ∀ x∈xs,0≤x) : + (xs.map TreeFraction.repr).foldl (fun z x=>maximum (x,z)) (TreeFraction.repr z)= + TreeFraction.repr (xs.foldl (fun z x=>max x z) z) := by + induction xs generalizing z with + | nil => rfl + | cons x xs ih => + simp only [List.map_cons,List.foldl_cons] + rw [maximum_repr (hx x (by simp)) hz] + exact ih _ (hz.trans (le_max_right _ _)) (fun x h=>hx x (by simp [h])) +lemma le_fold_max (xs : List ℚ) (z : ℚ) : z≤xs.foldl (fun z x=>max x z) z := by + induction xs generalizing z with + | nil => exact le_rfl + | cons x xs ih => exact (le_max_right x z).trans (ih _) +lemma mem_le_fold_max (xs : List ℚ) (z v : ℚ) (hv : v∈xs) : v≤xs.foldl (fun z x=>max x z) z := by + induction xs generalizing z with + | nil => simp at hv + | cons x xs ih => + rcases List.mem_cons.mp hv with rfl|hv + · exact (le_max_left _ _).trans (le_fold_max xs _) + · exact ih _ hv +lemma fold_max_le (xs : List ℚ) (z B : ℚ) (hz : z≤B) (hx : ∀ x∈xs,x≤B) : + xs.foldl (fun z x=>max x z) z≤B := by + induction xs generalizing z with + | nil => exact hz + | cons x xs ih => + exact ih _ (max_le (hx x (by simp)) hz) (fun x h=>hx x (by simp [h])) +lemma fold_max_ofFn {n : ℕ} (w : Fin n→ℚ) (z : ℚ) (a : Fin n) : + (List.ofFn w).foldl (fun z x=>max x z) z=max z (Finset.univ.sup' ⟨a,Finset.mem_univ a⟩ w) := by + apply le_antisymm + · apply fold_max_le _ _ _ (le_max_left _ _) + intro x hx + obtain ⟨i,rfl⟩:=List.mem_ofFn.mp hx + exact (Finset.le_sup' w (Finset.mem_univ i)).trans (le_max_right _ _) + · apply max_le (le_fold_max _ _) + apply Finset.sup'_le + intro i _ + exact mem_le_fold_max _ _ _ (List.mem_ofFn.mpr ⟨i,rfl⟩) +end MatchingFPRAS.TreeFraction + +namespace MatchingFPRAS.ExecutableBottleneck +open TreeTyped TreeFraction + +def matrixRep {n : ℕ} (w : Fin n→Fin n→ℚ) : Matrix := + List.ofFn fun i=>List.ofFn fun j=>TreeFraction.repr (w i j) +lemma matrixRep_length {n : ℕ} (w : Fin n→Fin n→ℚ) : (matrixRep w).length=n := by + simp [matrixRep] +lemma cell_matrixRep {n : ℕ} (w : Fin n→Fin n→ℚ) (a b : Fin n) : + cell (matrixRep w,(a.val,b.val))=TreeFraction.repr (w a b) := by + simp [cell,matrixRep,List.getD_eq_getElem?_getD,a.isLt,b.isLt] + +lemma square_eq_ofFn {A B : Type} (n : ℕ) (x : A) (f : A×(ℕ×ℕ)→B) : + square n x f=List.ofFn fun i : Fin n=>List.ofFn fun j : Fin n=>f (x,(i.val,j.val)) := by + apply List.ext_getElem + · simp [square] + · intro i hi hi' + simp only [square,List.getElem_map,List.getElem_range,List.getElem_ofFn] + apply List.ext_getElem + · simp + · intro j hj hj' + simp +lemma one_repr : one=TreeFraction.repr (1:ℚ) := rfl +lemma seedEntry_matrixRep {n : ℕ} (w : Fin n→Fin n→ℚ) (hw : ∀ a b,0≤w a b) (a b : Fin n) : + seedEntry (matrixRep w,(a.val,b.val))=TreeFraction.repr (BottleneckAlgorithm.seed w a b) := by + unfold seedEntry BottleneckAlgorithm.seed BottleneckAlgorithm.edge + dsimp only + by_cases hab : a=b + · subst b; simp only [↓reduceIte,one_repr] + · have hv : a.val≠b.val := fun he=>hab (Fin.ext he) + rw [ite_eq_right hv,ite_eq_right hab] + by_cases hlt : ahab (Fin.ext he) + rw [ite_eq_right hv,ite_eq_right hab,cell_matrixRep,matrixRep_length] + have he : (List.range n).map (fun c=>via ((matrixRep w,(a.val,b.val)),c))= + (List.ofFn fun c : Fin n=>min (w a c) (w c b)).map TreeFraction.repr := by + apply List.ext_getElem + · simp + · intro i hi hi' + have hi0 : iadvance z) (matrixRep (BottleneckAlgorithm.close w k))= + matrixRep (BottleneckAlgorithm.close w (k+ls.length)) := by + induction ls generalizing k with + | nil => simp + | cons r ls ih => + rw [List.foldl_cons,advance_matrixRep _ (fun a b=> + (show (0:ℚ)≤1 by norm_num).trans (BottleneckAlgorithm.close_one w k a b))] + change ls.foldl (fun z _=>advance z) (matrixRep (BottleneckAlgorithm.close w (k+1)))=_ + rw [ih] + congr 2 + simp only [List.length_cons]; omega + +theorem close_matrixRep {n : ℕ} (w : Fin n→Fin n→ℚ) (hw : ∀ a b,0≤w a b) : + close (matrixRep w)=matrixRep (BottleneckAlgorithm.close w n) := by + unfold close + rw [seed_matrixRep w hw] + change (matrixRep w).foldl (fun z _=>advance z) (matrixRep (BottleneckAlgorithm.close w 0))=_ + rw [fold_advance_matrixRep _ hw,matrixRep_length,Nat.zero_add] +end MatchingFPRAS.ExecutableBottleneck + +end OAI diff --git a/lean/OAI/Combinatorics/MatchingCount/Machines/TreeBuild.lean b/lean/OAI/Combinatorics/MatchingCount/Machines/TreeBuild.lean new file mode 100644 index 0000000000000000000000000000000000000000..5bb6e2c6b6ff74cd60f51f6e3f822c8fbe2b6a52 --- /dev/null +++ b/lean/OAI/Combinatorics/MatchingCount/Machines/TreeBuild.lean @@ -0,0 +1,82 @@ +import Mathlib +import OAI.Combinatorics.MatchingCount.Machines.TreeMatrix +import OAI.Combinatorics.MatchingCount.Machines.TreeEnumeration +import OAI.Combinatorics.MatchingCount.Machines.TreeClosureReindex + +namespace OAI + +namespace MatchingFPRAS.ExecutableSource +open TreeTyped TreeFraction ExecutableBottleneck Enlargement RealGeometry + +attribute [local instance] Transport.prodOrder Transport.sumOrder + +lemma vertices_eq_ofFn_length (n : ℕ) (fuel : List Bool) (m : ℕ) (h : 4*fuel.length=m) : + vertices (List.range n,fuel)=List.ofFn (fun i=>vertexRepr + (UnitRefresh.orderedEnum (Vertex (Fin n) (LogicalEdge (Fin n)) m) i)) := by + subst m + exact vertices_eq_ofFn n fuel + +abbrev BuildInput := (Matrix×List Bool)×List Nat + +def prepare (x : BuildInput) : PathTableInput := (((x.1.1,close x.1.1),x.1.2),x.2) +def prepareRealizer : Realizer prepare := (pair (pair (pair first.fst + (composition first.fst closeRealizer)) first.snd) second).congr (fun _=>rfl) +lemma polynomial_prepare : PolynomialTime prepareRealizer := by + unfold prepareRealizer + apply polynomial_congr + have := polynomial_close + dsimp only [Realizer.fst,Realizer.snd] + tree_cost + +def buildMatrix (x : BuildInput) : Matrix := materialize (prepare x) +def buildMatrixRealizer : Realizer buildMatrix := composition prepareRealizer materializeRealizer +lemma polynomial_buildMatrix : PolynomialTime buildMatrixRealizer := + polynomial_composition polynomial_prepare polynomial_materialize + +def buildClosure (x : BuildInput) : Matrix := close (buildMatrix x) +def buildClosureRealizer : Realizer buildClosure := composition buildMatrixRealizer closeRealizer +lemma polynomial_buildClosure : PolynomialTime buildClosureRealizer := + polynomial_composition polynomial_buildMatrix polynomial_close + +lemma source_activity_nonneg {n : ℕ} [Nontrivial (Fin n)] (hn : 2≤n) (w : Fin n→Fin n→ℚ) + (hw : ∀ i j,0≤w i j) (K : ℕ) (a b : SourceVertex (Fin n) K) : + 0≤RationalSource.activity w K a b := by + unfold RationalSource.activity + apply Finset.sum_nonneg + intro q _ + split_ifs + · exact pathActivity_nonneg hn w hw K q.1 q.2 + · exact le_rfl + +lemma buildMatrix_repr {n : ℕ} [Nontrivial (Fin n)] (hn : 2≤n) + (w : Fin n→Fin n→ℚ) (hw : ∀ i j,0≤w i j) (K : ℕ) : + buildMatrix ((matrixRep w,List.replicate (2*K+2) false),List.range n)= + matrixRep (fun i j=>RationalSource.activity w K + (UnitRefresh.orderedEnum (SourceVertex (Fin n) K) i) + (UnitRefresh.orderedEnum (SourceVertex (Fin n) K) j)) := by + unfold buildMatrix prepare materialize + rw [close_matrixRep w hw] + rw [show BottleneckAlgorithm.close w n=RationalSource.logicalB w by simp [RationalSource.logicalB]] + change activityMatrix (pathTable (((matrixRep w,matrixRep (RationalSource.logicalB w)), + List.replicate (2*K+2) false),List.range n), + vertices (List.range n,List.replicate (2*K+2) false))=_ + have hv : vertices (List.range n,List.replicate (2*K+2) false)= + List.ofFn (fun i=>vertexRepr (UnitRefresh.orderedEnum (SourceVertex (Fin n) K) i)) := by + exact vertices_eq_ofFn_length n _ _ (by simp) + rw [hv] + exact activityMatrix_source_repr hn w hw K _ (List.length_replicate ..) _ + +lemma buildClosure_repr {n : ℕ} [Nontrivial (Fin n)] (hn : 2≤n) + (w : Fin n→Fin n→ℚ) (hw : ∀ i j,0≤w i j) (K : ℕ) : + buildClosure ((matrixRep w,List.replicate (2*K+2) false),List.range n)= + matrixRep (fun i j=>RationalSource.realB w K + (UnitRefresh.orderedEnum (SourceVertex (Fin n) K) i) + (UnitRefresh.orderedEnum (SourceVertex (Fin n) K) j)) := by + unfold buildClosure + rw [buildMatrix_repr hn w hw K,close_matrixRep _ (fun _ _=>source_activity_nonneg hn w hw K _ _)] + rw [BottleneckAlgorithm.close_reindex (UnitRefresh.orderedEnum (SourceVertex (Fin n) K)) + UnitRefresh.orderedEnum_lt] + rfl +end MatchingFPRAS.ExecutableSource + +end OAI diff --git a/lean/OAI/Combinatorics/MatchingCount/Machines/TreeCanonical.lean b/lean/OAI/Combinatorics/MatchingCount/Machines/TreeCanonical.lean new file mode 100644 index 0000000000000000000000000000000000000000..f108465f5ac04a013e840ac2f9a0a5b2937e5f21 --- /dev/null +++ b/lean/OAI/Combinatorics/MatchingCount/Machines/TreeCanonical.lean @@ -0,0 +1,202 @@ +import Mathlib +import OAI.Combinatorics.MatchingCount.Complexity.TreePolynomialCollections + +namespace OAI + +namespace MatchingFPRAS.TreeTyped +open Polynomial + +variable {A : Type} [Codec A] + +def contains [DecidableEq A] (E : Realizer (fun x : A×A=>decide (x.1=x.2))) : + Realizer (fun x : A×List A=>decide (x.1∈x.2)) := + (composition (mapWith E) any).congr (by + intro x + apply Bool.eq_iff_iff.mpr + simp only [Function.comp_apply,List.any_map,List.any_eq_true,id_eq,decide_eq_true_eq] + constructor + · rintro ⟨a,ha,he⟩; simpa [he] using ha + · intro h; exact ⟨x.1,h,rfl⟩) +lemma polynomial_contains [DecidableEq A] {E : Realizer (fun x : A×A=>decide (x.1=x.2))} + (hE : PolynomialTime E) : PolynomialTime (contains E) := by + unfold contains + exact polynomial_congr _ (polynomial_composition (polynomial_mapWith hE) polynomial_any) + +def dedupStep [DecidableEq A] (x : A×List A) : List A := if x.1∈x.2 then x.2 else x.1::x.2 +def dedupStepRealizer [DecidableEq A] (E : Realizer (fun x : A×A=>decide (x.1=x.2))) : + Realizer (dedupStep (A:=A)) := + (choose (contains E) second listCons).congr (by intro x; simp [dedupStep]) +omit [Codec A] in +lemma dedup_fold [DecidableEq A] (as : List A) : + as.reverse.foldl (fun bs a=>dedupStep (a,bs)) []=as.dedup := by + induction as with + | nil => rfl + | cons a as ih => + rw [List.reverse_cons,List.foldl_append,List.foldl_cons,List.foldl_nil,ih] + exact (List.dedup_cons' a as).symm +def dedup [DecidableEq A] (E : Realizer (fun x : A×A=>decide (x.1=x.2))) : Realizer (List.dedup (α:=A)) := + (composition (pair reverse (constant [])) (fold (dedupStepRealizer E))).congr dedup_fold +lemma weight_dedupFold [DecidableEq A] (as bs : List A) : + weight (as.foldl (fun bs a=>dedupStep (a,bs)) bs)≤weight as+weight bs := by + induction as generalizing bs with + | nil => simp + | cons a as ih => + rw [List.foldl_cons] + have hh:=ih (dedupStep (a,bs)) + simp only [weight_cons] + have hs : weight (dedupStep (a,bs))≤1+weight a+weight bs := by + change weight (if a∈bs then bs else a::bs)≤_ + split_ifs + · omega + · rw [weight_cons] + omega +lemma polynomial_dedup [DecidableEq A] {E : Realizer (fun x : A×A=>decide (x.1=x.2))} + (hE : PolynomialTime E) : PolynomialTime (dedup E) := by + unfold dedup + apply polynomial_congr + apply polynomial_composition (polynomial_pair polynomial_reverse (polynomial_constant [])) + apply polynomial_fold (polynomial_congr _ (polynomial_choose (polynomial_contains hE) polynomial_second polynomial_listCons)) (2*X+1) + intro as bs pre post he + have hh:=weight_dedupFold pre bs + have hp:=weight_prefix he + simp only [Polynomial.eval_add,Polynomial.eval_mul,Polynomial.eval_ofNat,Polynomial.eval_X,weight_prod] + omega + +variable (r : A → A → Prop) [DecidableRel r] +def insertStep (x : A×(A×(List A×List A))) : A×(List A×List A) := + (x.2.1,(x.1::x.2.2.1,if r x.2.1 x.1 then x.2.1::x.1::x.2.2.1 else x.1::x.2.2.2)) +def insertStepRealizer (R : Realizer (fun x : A×A=>decide (r x.1 x.2))) : Realizer (insertStep r) := + (pair (composition second first) (pair (composition (pair first (composition (composition second second) first)) listCons) + (choose (composition (pair (composition second first) first) R) + (composition (pair (composition second first) (composition (pair first (composition (composition second second) first)) listCons)) listCons) + (composition (pair first (composition (composition second second) second)) listCons)))).congr (by intro x; simp [insertStep]) +omit [Codec A] in +lemma insert_fold (as bs : List A) (a : A) : + as.reverse.foldl (fun z b=>insertStep r (b,z)) (a,(bs,List.orderedInsert r a bs))= + (a,(as++bs,List.orderedInsert r a (as++bs))) := by + induction as with + | nil => rfl + | cons b as ih => + rw [List.reverse_cons,List.foldl_append,List.foldl_cons,List.foldl_nil,ih] + rfl +def orderedInsert (R : Realizer (fun x : A×A=>decide (r x.1 x.2))) : + Realizer (fun x : A×List A=>List.orderedInsert r x.1 x.2) := + (composition (composition (pair (composition second reverse) + (pair first (pair (constant []) (composition (pair first (constant [])) listCons)))) + (fold (insertStepRealizer r R))) (composition second second)).congr (by + intro x + change (x.2.reverse.foldl (fun z b=>insertStep r (b,z)) (x.1,([],[x.1]))).2.2=_ + have h:=insert_fold r x.2 [] x.1 + simpa only [List.append_nil,List.orderedInsert_nil] using congrArg (fun x=>x.2.2) h) +lemma weight_perm {as bs : List A} (h : as.Perm bs) : weight as=weight bs := by + simp only [weight,size_encode_list,h.length_eq,(h.map (fun a=>TreeFunction.size (encode a))).sum_eq] +lemma weight_orderedInsert (a : A) (as : List A) : + weight (List.orderedInsert r a as)=1+weight a+weight as := by + rw [weight_perm (List.perm_orderedInsert r a as),weight_cons] +lemma polynomial_insertStep {R : Realizer (fun x : A×A=>decide (r x.1 x.2))} + (hR : PolynomialTime R) : PolynomialTime (insertStepRealizer r R) := by + unfold insertStepRealizer + apply polynomial_congr + apply polynomial_pair (polynomial_fst polynomial_second) + apply polynomial_pair (polynomial_composition (polynomial_pair polynomial_first (polynomial_fst (polynomial_snd polynomial_second))) polynomial_listCons) + exact polynomial_choose (polynomial_composition (polynomial_pair (polynomial_fst polynomial_second) polynomial_first) hR) + (polynomial_composition (polynomial_pair (polynomial_fst polynomial_second) + (polynomial_composition (polynomial_pair polynomial_first (polynomial_fst (polynomial_snd polynomial_second))) polynomial_listCons)) polynomial_listCons) + (polynomial_composition (polynomial_pair polynomial_first (polynomial_snd (polynomial_snd polynomial_second))) polynomial_listCons) +lemma insert_fold_bound (as bs cs : List A) (a : A) : + weight ((as.foldl (fun z b=>insertStep r (b,z)) (a,(bs,cs))).2.1)≤weight as+weight bs ∧ + weight ((as.foldl (fun z b=>insertStep r (b,z)) (a,(bs,cs))).2.2)≤2*weight as+weight bs+weight cs+weight a+1 ∧ + (as.foldl (fun z b=>insertStep r (b,z)) (a,(bs,cs))).1=a := by + induction as generalizing bs cs with + | nil => + change weight bs≤1+weight bs ∧ weight cs≤2+weight bs+weight cs+weight a+1 ∧ a=a + exact ⟨by omega,by omega,rfl⟩ + | cons b as ih => + rw [List.foldl_cons] + by_cases h : r a b + · have hs : insertStep r (b,(a,(bs,cs)))=(a,(b::bs,a::b::bs)) := by simp [insertStep,h] + rw [hs] + have he:=insert_fold r as.reverse (b::bs) a + simp only [List.reverse_reverse] at he + have ho : List.orderedInsert r a (b::bs)=a::b::bs := by simp [h] + rw [ho] at he + rw [he] + have hw:=weight_append as.reverse (b::bs) + rw [weight_reverse,weight_cons] at hw + simp only [weight_orderedInsert,weight_cons] + exact ⟨by omega,by omega,trivial⟩ + · have hs : insertStep r (b,(a,(bs,cs)))=(a,(b::bs,b::cs)) := by simp [insertStep,h] + rw [hs] + have hh:=ih (b::bs) (b::cs) + simp only [weight_cons] at hh ⊢ + exact ⟨by omega,by omega,hh.2.2⟩ +lemma polynomial_orderedInsert {R : Realizer (fun x : A×A=>decide (r x.1 x.2))} + (hR : PolynomialTime R) : PolynomialTime (orderedInsert r R) := by + unfold orderedInsert + apply polynomial_congr + apply polynomial_composition _ (polynomial_snd polynomial_second) + apply polynomial_composition (polynomial_pair (polynomial_composition polynomial_second polynomial_reverse) + (polynomial_pair polynomial_first (polynomial_pair (polynomial_constant []) + (polynomial_composition (polynomial_pair polynomial_first (polynomial_constant [])) polynomial_listCons)))) + apply polynomial_fold (polynomial_insertStep r hR) (5*X+10) + rintro as ⟨a,bs,cs⟩ pre post he + have hh:=insert_fold_bound r pre bs cs a + have hp:=weight_prefix he + rw [weight_prod,hh.2.2,weight_prod] + calc + _ ≤ 1+weight a+(1+(weight pre+weight bs)+(2*weight pre+weight bs+weight cs+weight a+1)) := by + gcongr + · exact hh.1 + · exact hh.2.1 + _ ≤ _ := by + simp only [Polynomial.eval_add,Polynomial.eval_mul,Polynomial.eval_ofNat,Polynomial.eval_X,weight_prod] + omega + +def insertionSort (R : Realizer (fun x : A×A=>decide (r x.1 x.2))) : + Realizer (List.insertionSort r) := + (composition (pair reverse (constant [])) (fold (orderedInsert r R))).congr (by + intro as + change as.reverse.foldl (fun bs a=>List.orderedInsert r a bs) []=as.insertionSort r + rw [List.foldl_reverse] + rfl) +lemma weight_insertFold (as bs : List A) : + weight (as.foldl (fun bs a=>List.orderedInsert r a bs) bs)+1=weight as+weight bs := by + induction as generalizing bs with + | nil => simp only [List.foldl_nil,weight_nil]; omega + | cons a as ih => + rw [List.foldl_cons] + have hh:=ih (List.orderedInsert r a bs) + rw [weight_orderedInsert] at hh + rw [weight_cons] + omega +lemma polynomial_insertionSort {R : Realizer (fun x : A×A=>decide (r x.1 x.2))} + (hR : PolynomialTime R) : PolynomialTime (insertionSort r R) := by + unfold insertionSort + apply polynomial_congr + apply polynomial_composition (polynomial_pair polynomial_reverse (polynomial_constant [])) + apply polynomial_fold (polynomial_orderedInsert r hR) (2*X+1) + intro as bs pre post he + have hh:=weight_insertFold r pre bs + have hp:=weight_prefix he + simp only [Polynomial.eval_add,Polynomial.eval_mul,Polynomial.eval_ofNat,Polynomial.eval_X,weight_prod] + omega + +variable [DecidableEq A] +def canonical (E : Realizer (fun x : A×A=>decide (x.1=x.2))) + (R : Realizer (fun x : A×A=>decide (r x.1 x.2))) : + Realizer (fun as : List A=>as.dedup.insertionSort r) := composition (dedup E) (insertionSort r R) +lemma polynomial_canonical {E : Realizer (fun x : A×A=>decide (x.1=x.2))} + {R : Realizer (fun x : A×A=>decide (r x.1 x.2))} + (hE : PolynomialTime E) (hR : PolynomialTime R) : PolynomialTime (canonical r E R) := + polynomial_composition (polynomial_dedup hE) (polynomial_insertionSort r hR) +omit [Codec A] in +lemma canonical_eq_sort [IsTrans A r] [Std.Total r] [Std.Antisymm r] (as : List A) : + as.dedup.insertionSort r=as.toFinset.sort r := by + have hn:=(List.perm_insertionSort r as.dedup).nodup_iff.mpr (List.nodup_dedup as) + have hh:=(List.toFinset_sort (r:=r) hn).mpr (List.pairwise_insertionSort r as.dedup) + have he : (as.dedup.insertionSort r).toFinset=as.toFinset := by ext a; simp + rw [he] at hh + exact hh.symm +end MatchingFPRAS.TreeTyped + +end OAI diff --git a/lean/OAI/Combinatorics/MatchingCount/Machines/TreeCappedAssembly.lean b/lean/OAI/Combinatorics/MatchingCount/Machines/TreeCappedAssembly.lean new file mode 100644 index 0000000000000000000000000000000000000000..8159c9cf49f92c3b00117e0ff51a01590c58882d --- /dev/null +++ b/lean/OAI/Combinatorics/MatchingCount/Machines/TreeCappedAssembly.lean @@ -0,0 +1,171 @@ +import Mathlib +import OAI.Combinatorics.MatchingCount.Sampling.TreeUnitAssemble +import OAI.Combinatorics.MatchingCount.Sampling.TreeFastUnit + +namespace OAI + +namespace MatchingFPRAS.ExecutableUnit +open TreeTyped ExecutableDP Polynomial + +def assembleAtFast : Realizer assembleAt := by + let n : Realizer (fun x : (Frame×Result)×ℕ=>x.1.1.1) := first.fst.fst + let b : Realizer (fun x : (Frame×Result)×ℕ=>x.1.1.2.1) := first.fst.snd.fst + let c : Realizer (fun x : (Frame×Result)×ℕ=>x.1.1.2.2) := first.fst.snd.snd + let i : Realizer (fun x : (Frame×Result)×ℕ=>x.2) := second + let a := composition n successor + let j := composition (pair i b) unskipRealizer + let z := composition (pair first.snd j) (getDFast (0,0)) + let r := pair (composition (pair z.fst b) skipFast) z.snd + exact (choose (composition (pair i a) natEqual) (pair b c) + (choose (composition (pair i b) natEqual) (pair a c) r)).congr (by intro x; simp [assembleAt]) +lemma polynomial_assembleAtFast : PolynomialTime assembleAtFast := by + unfold assembleAtFast Realizer.fst Realizer.snd + dsimp only + apply polynomial_congr + have : PolynomialTime unskipRealizer := by + unfold unskipRealizer + apply polynomial_congr + exact polynomial_choose polynomial_less polynomial_first (polynomial_composition polynomial_first polynomial_predecessor) + have := polynomial_successor + have := polynomial_getDFast ((0,0) : ℕ×ℕ) + have := polynomial_skipFast + tree_poly + +def capacity (x : Context) : ℕ := x.1.1.length+x.1.2.length+2 +def capacityRealizer : Realizer capacity := + (composition (pair (composition (pair (composition first.fst listLength) + (composition first.snd listLength)) add) (constant 2)) add).congr (fun _=>rfl) +lemma polynomial_capacity : PolynomialTime capacityRealizer := by + unfold capacityRealizer Realizer.fst Realizer.snd + apply polynomial_congr + tree_poly + +def clippedAt (x : (Context×(Frame×Result))×ℕ) : ℕ×ℕ := + let r:=assembleAt (x.1.2,x.2) + (min r.1 (capacity x.1.1),min r.2 (capacity x.1.1)) +def clippedAtRealizer : Realizer clippedAt := by + let r : Realizer (fun x : (Context×(Frame×Result))×ℕ=>assembleAt (x.1.2,x.2)) := (composition (pair first.snd second) assembleAtFast).congr (fun _=>rfl) + let cap : Realizer (fun x : (Context×(Frame×Result))×ℕ=>capacity x.1.1) := (composition first.fst capacityRealizer).congr (fun _=>rfl) + exact (pair (composition (pair r.fst cap) minNat) (composition (pair r.snd cap) minNat)).congr (fun _=>rfl) +lemma polynomial_clippedAt : PolynomialTime clippedAtRealizer := by + unfold clippedAtRealizer Realizer.fst Realizer.snd + dsimp only + apply polynomial_congr + have := polynomial_assembleAtFast + have := polynomial_capacity + have := polynomial_minNat + tree_poly + +def clippedAssemble (x : Context×(Frame×Result)) : Result := + (List.range (min (x.2.1.1+2) (x.1.1.1.length+2))).map (fun i=>clippedAt (x,i)) +def clippedAssembleRealizer : Realizer clippedAssemble := by + let n : Realizer (fun x : Context×(Frame×Result)=>x.2.1.1+2) := (composition (pair second.fst.fst (constant 2)) add).congr (fun _=>rfl) + let m : Realizer (fun x : Context×(Frame×Result)=>x.1.1.1.length+2) := (composition (pair (composition first.fst.fst listLength) (constant 2)) add).congr (fun _=>rfl) + let rs := composition (composition (pair n m) minNat) range + exact (composition (pair identity rs) (mapWith clippedAtRealizer)).congr (fun _=>rfl) +lemma polynomial_clippedAssemble : PolynomialTime clippedAssembleRealizer := by + unfold clippedAssembleRealizer Realizer.fst + dsimp only + apply polynomial_congr + apply polynomial_composition _ (polynomial_mapWith polynomial_clippedAt) + apply polynomial_pair polynomial_identity + apply polynomial_boundedRange (by have := polynomial_minNat; tree_poly) (X+2) + intro x + simpa only [Function.comp_apply,Polynomial.eval_add,Polynomial.eval_X,Polynomial.eval_ofNat] using + (min_le_right (x.2.1.1+2) (x.1.1.1.length+2)).trans + (Nat.add_le_add_right ((list_length_le_weight _).trans ((weight_fst x.1.1).trans ((weight_fst x.1).trans (weight_fst x)))) 2) +lemma clippedAssemble_weight (ctx : Context) (f : Frame) (r : Result) : + weight (clippedAssemble (ctx,(f,r)))≤64*(weight ctx+1)^2 := by + have hh :=weight_map_bound (as:=List.range (min (f.1+2) (ctx.1.1.length+2))) + (f:=fun i=>clippedAt ((ctx,(f,r)),i)) (N:=8*capacity ctx+3) (by + intro i hi + let z:=assembleAt ((f,r),i) + have h1:=weight_nat_numeric (min z.1 (capacity ctx)) + have h2:=weight_nat_numeric (min z.2 (capacity ctx)) + have h3:=min_le_right z.1 (capacity ctx) + have h4:=min_le_right z.2 (capacity ctx) + change weight (min z.1 (capacity ctx),min z.2 (capacity ctx))≤_ + rw [weight_prod] + omega) + have hn : ctx.1.1.length≤weight ctx := (list_length_le_weight _).trans ((weight_fst ctx.1).trans (weight_fst ctx)) + have hm : ctx.1.2.length≤weight ctx := (list_length_le_weight _).trans ((weight_snd ctx.1).trans (weight_fst ctx)) + have hc : capacity ctx≤2*weight ctx+2 := by unfold capacity; omega + have hl : min (f.1+2) (ctx.1.1.length+2)≤weight ctx+2 := (min_le_right _ _).trans (by omega) + simp only [List.length_range] at hh + have hp :=Nat.mul_le_mul hl (show 8*capacity ctx+3+1≤16*weight ctx+20 by omega) + change weight (clippedAssemble (ctx,(f,r)))≤_ at hh + nlinarith + +def assemblyFoldStep (x : Frame×(Context×Result)) : Context×Result := + (x.2.1,clippedAssemble (x.2.1,(x.1,x.2.2))) +def assemblyFoldStepRealizer : Realizer assemblyFoldStep := + (pair second.fst (composition (pair second.fst (pair first second.snd)) clippedAssembleRealizer)).congr (fun _=>rfl) +lemma polynomial_assemblyFoldStep : PolynomialTime assemblyFoldStepRealizer := by + unfold assemblyFoldStepRealizer Realizer.fst Realizer.snd + apply polynomial_congr + have := polynomial_clippedAssemble + tree_poly +lemma assemblyFold_fst (pre : List Frame) (ctx : Context) (r : Result) : + (pre.foldl (fun z f=>assemblyFoldStep (f,z)) (ctx,r)).1=ctx := by + induction pre generalizing r with + | nil => rfl + | cons f pre ih => exact ih _ +lemma assemblyFold_weight (pre : List Frame) (ctx : Context) (r : Result) : + weight (pre.foldl (fun z f=>assemblyFoldStep (f,z)) (ctx,r)).2 ≤ + weight r+pre.length*(64*(weight ctx+1)^2) := by + induction pre generalizing r with + | nil => simp + | cons f pre ih => + have hh:=ih (clippedAssemble (ctx,(f,r))) + have hw:=clippedAssemble_weight ctx f r + change weight (pre.foldl _ (ctx,clippedAssemble (ctx,(f,r)))).2≤_ + simp only [List.length_cons] + nlinarith +lemma polynomial_assemblyFold : PolynomialTime (fold assemblyFoldStepRealizer) := by + apply polynomial_fold polynomial_assemblyFoldStep (70*(X+1)^3) + rintro fs ⟨ctx,r⟩ pre post he + let S:=weight (fs,(ctx,r)) + have hp:pre.length≤S := (list_length_le_weight _).trans ((weight_prefix he).trans (weight_fst (fs,(ctx,r)))) + have hc:weight ctx≤S := (weight_fst (ctx,r)).trans (weight_snd (fs,(ctx,r))) + have hr:weight r≤S := (weight_snd (ctx,r)).trans (weight_snd (fs,(ctx,r))) + have hh:=assemblyFold_weight pre ctx r + have hf:=assemblyFold_fst pre ctx r + rw [←Prod.eta (pre.foldl (fun z f=>assemblyFoldStep (f,z)) (ctx,r)),weight_prod,hf] + have hm:= Nat.mul_le_mul hp (show 64*(weight ctx+1)^2 ≤64*(S+1)^2 by gcongr) + simp only [Polynomial.eval_mul,Polynomial.eval_ofNat,Polynomial.eval_pow,Polynomial.eval_add,Polynomial.eval_X,Polynomial.eval_one] + change _≤70*(S+1)^3 + nlinarith + +lemma resultRep_mem {n m : ℕ} {bags : Fin n → Finset (Fin m)} + (p : UnitRefresh.ColoredPairing bags) {z : ℕ×ℕ} (hz : z∈resultRep p) : z.1 < n ∧ z.2 < m := by + simp only [resultRep,List.mem_ofFn] at hz + obtain ⟨i,rfl⟩:=hz + exact ⟨(p.pair.mate i).isLt,(p.color i).isLt⟩ + +lemma clippedAssemble_eq {n m : ℕ} (ctx : Context) (hn : n+2≤ctx.1.1.length) (hm : m≤ctx.1.2.length) + (bags : Fin (n+2) → Finset (Fin m)) + (c : UnitRefresh.Partner bags (Fin.last (n+1))) + (p : UnitRefresh.ColoredPairing (fun i=>bags (UnitRefresh.removePairEquiv (Fin.last (n+1)) c.val.1 c.property.1 i).val)) : + clippedAssemble (ctx,((n,(c.val.1.val,c.val.2.val)),resultRep p))= + resultRep ((UnitRefresh.ColoredPairing.map (UnitRefresh.residualBags bags (Fin.last (n+1)) c.val.1) + (UnitRefresh.removePairEquiv (Fin.last (n+1)) c.val.1 c.property.1) p).insert (Fin.last (n+1)) c) := by + let f : Frame := (n,(c.val.1.val,c.val.2.val)) + have he :=assemble_eq bags c p + change assemble (f,resultRep p)=_ at he + unfold clippedAssemble + dsimp only + rw [min_eq_left (show n+2 ≤ ctx.1.1.length+2 by omega)] + trans assemble (f,resultRep p) + · unfold assemble + apply List.map_congr_left + intro i hi + have hz : assembleAt ((f,resultRep p),i)∈assemble (f,resultRep p) := List.mem_map.mpr ⟨i,hi,rfl⟩ + rw [he] at hz + obtain ⟨h1,h2⟩:=resultRep_mem _ hz + have hc1 :(assembleAt ((f,resultRep p),i)).1≤capacity ctx := by unfold capacity; omega + have hc2 :(assembleAt ((f,resultRep p),i)).2≤capacity ctx := by unfold capacity; omega + exact Prod.ext (min_eq_left hc1) (min_eq_left hc2) + · exact he +end MatchingFPRAS.ExecutableUnit + +end OAI diff --git a/lean/OAI/Combinatorics/MatchingCount/Machines/TreeCertify.lean b/lean/OAI/Combinatorics/MatchingCount/Machines/TreeCertify.lean new file mode 100644 index 0000000000000000000000000000000000000000..dbd76b863c708a0f3d3a54004e48042975064836 --- /dev/null +++ b/lean/OAI/Combinatorics/MatchingCount/Machines/TreeCertify.lean @@ -0,0 +1,43 @@ +import Mathlib +import OAI.Combinatorics.MatchingCount.Graphs.TreeMatchingCheck + +namespace OAI + +namespace MatchingFPRAS.TreeTyped.SparseProgram +open TreeTyped + +variable {E V C : Type} [Codec E] [Codec V] [Codec C] [LinearOrder E] [LinearOrder V] +attribute [local instance] Transport.Sparse.finsetOrder + +def certify (p : C×(E×V)→Bool) (x : (C×Finset V)×Finset (Finset E)) : Finset (Finset E) := + x.2.filter (fun a=>matchingCheck p (x.1,a)=true) +def certifyRealizer {p : C×(E×V)→Bool} (P : Realizer p) : Realizer (certify p) := + (finsetFilterWith (matchingCheckRealizer P)).congr (fun _=>rfl) +lemma polynomial_certify {p : C×(E×V)→Bool} {P : Realizer p} (hP : PolynomialTime P) : + PolynomialTime (certifyRealizer P) := + polynomial_congr _ (polynomial_finsetFilterWith (polynomial_matchingCheck hP)) + +variable [Fintype E] [Fintype V] (ends : E→Sym2 V) +attribute [local instance] Transport.Sparse.pmOrder + +def pmEmbedding : @OrderEmbedding (Transport.PM (fun e v=>v∈ends e)) (Finset E) + (Transport.Sparse.pmOrder ends).toLE (Transport.Sparse.finsetOrder (E:=E)).toLE := + { toFun := Subtype.val + inj' := Subtype.val_injective + map_rel_iff' := Iff.rfl } + +omit [Codec E] [Codec V] [Codec C] in +lemma certify_eq (p : C×(E×V)→Bool) (c : C) + (hp : ∀ e v,p (c,(e,v))=decide (v∈ends e)) (s : Finset (Finset E)) : + certify p ((c,Finset.univ),s)=(Transport.Sparse.certify ends s).map (pmEmbedding ends).toEmbedding := by + ext a + simp only [certify,Finset.mem_filter,matchingCheck_eq p c _ hp,decide_eq_true_eq, + Finset.mem_map,pmEmbedding] + constructor + · rintro ⟨ha,hm⟩ + exact ⟨⟨a,hm⟩,by simpa using ha,rfl⟩ + · rintro ⟨b,hb,rfl⟩ + exact ⟨by simpa using hb,b.property⟩ +end MatchingFPRAS.TreeTyped.SparseProgram + +end OAI diff --git a/lean/OAI/Combinatorics/MatchingCount/Machines/TreeChoice.lean b/lean/OAI/Combinatorics/MatchingCount/Machines/TreeChoice.lean new file mode 100644 index 0000000000000000000000000000000000000000..e60f65c0a6463bb7ffd9ee42ab8eef1e4f668d5c --- /dev/null +++ b/lean/OAI/Combinatorics/MatchingCount/Machines/TreeChoice.lean @@ -0,0 +1,87 @@ +import Mathlib +import OAI.Combinatorics.MatchingCount.Arithmetic.TreeCompare +import OAI.Combinatorics.MatchingCount.Machines.RegisterStructured +import OAI.Combinatorics.MatchingCount.Machines.TreeTyped + +namespace OAI + +namespace MatchingFPRAS.TreeFunction +open TreeData TreeMachine RegisterProc + +lemma split02 (x y a s : Data) : + Exec (split 0 2 (by decide)) (encodeEnv (env x y (.cons a s))) + (encodeEnv (env a y s)) (size x+2*size a+4) := by + simpa only [putPair,env_update0,env_update2,env0,env2,size,split] using + split_exec (env x y (.cons a s)) 0 2 (by decide) () a s rfl +end MatchingFPRAS.TreeFunction + +namespace MatchingFPRAS.TreeTyped +open TreeData TreeMachine RegisterProc TreeFunction + +variable {A B C : Type} [Codec A] [Codec B] [Codec C] + +def choose {f : A → Bool} {g h : A → B} (F : Realizer f) (G : Realizer g) (H : Realizer h) : + Realizer (fun a=>if f a then g a else h a) where + program := seq (TreeFunction.copy 0 1 (by decide)) (seq (TreeFunction.cons 1 2 (by decide)) + (seq F.program (RegisterStructured.select 0 + (seq (TreeFunction.split 0 2 (by decide)) H.program) + (seq (TreeFunction.split 0 2 (by decide)) G.program)))) + cost := fun a=>F.cost a+(if f a then G.cost a else H.cost a)+7*TreeFunction.size (encode a)+18 + correct := by + intro a s + have h1:=copy01 (encode a) .nil s + have h2:=cons12 (encode a) (encode a) s + have h3:=F.correct a (.cons (encode a) s) + have h4:=split02 (encode (f a)) .nil (encode a) s + have hs : TreeFunction.size (encode (f a)) ≤ 3 := by + cases f a <;> simp [Codec.encode,bit] + cases hf : f a + · have h5:=H.correct a s + have hh:=RegisterStructured.select_nil 0 _ (seq (TreeFunction.split 0 2 (by decide)) G.program) (env (encode (f a)) .nil (.cons (encode a) s)) + (env (encode (h a)) .nil s) _ (by simp [hf,Codec.encode,bit]) (h4.seq h5) + simp only [hf,Bool.false_eq_true,↓reduceIte] + apply (h1.seq (h2.seq (h3.seq hh))).mono + simp only [hf] + simp only [size_nil] + rw [hf] at hs + omega + · have h5:=G.correct a s + have hh:=RegisterStructured.select_cons 0 (seq (TreeFunction.split 0 2 (by decide)) H.program) _ (env (encode (f a)) .nil (.cons (encode a) s)) + (env (encode (g a)) .nil s) _ .nil .nil (by simp [hf,Codec.encode,bit]) (h4.seq h5) + simp only [hf,↓reduceIte] + apply (h1.seq (h2.seq (h3.seq hh))).mono + simp only [hf] + simp only [size_nil] + rw [hf] at hs + omega + +def less : Realizer (fun ab : ℕ×ℕ=>decide (ab.12*TreeFunction.size (nat ab.1)+3*(ab.1.bits.length+ab.2.bits.length)+31 + correct := by + intro ⟨a,b⟩ s + have h1:=split10 (nat a) (nat b) .nil s + have h2:=TreeArithmetic.less_exec (env (nat b) (nat a) s) 1 0 (by decide) a b rfl rfl + simp only [putPair,env_update0,env_update1] at h2 + have h3:=copy10 .nil (bit (decide (a simp [bit] + simp only [size_nil]; omega + +def constantData (x : Data) : Realizer (fun _ : A => x) := + match x with + | .nil => ⟨TreeFunction.clear 0,fun a=>TreeFunction.size (encode a)+2,fun a s=>clear0 (encode a) .nil s⟩ + | .cons x y => + let P : Realizer (fun _ : A => (x,y)) := pair (constantData x) (constantData y) + ⟨P.program,P.cost,P.correct⟩ + +def constant (b : B) : Realizer (fun _ : A=>b) := + let P : Realizer (fun _ : A=>encode b) := constantData (encode b) + ⟨P.program,P.cost,P.correct⟩ +end MatchingFPRAS.TreeTyped + +end OAI diff --git a/lean/OAI/Combinatorics/MatchingCount/Machines/TreeClippedCorrect.lean b/lean/OAI/Combinatorics/MatchingCount/Machines/TreeClippedCorrect.lean new file mode 100644 index 0000000000000000000000000000000000000000..812218dc2ab35882ef924dd8007e64f119aac750 --- /dev/null +++ b/lean/OAI/Combinatorics/MatchingCount/Machines/TreeClippedCorrect.lean @@ -0,0 +1,136 @@ +import Mathlib +import OAI.Combinatorics.MatchingCount.Sampling.TreeDPRepresentation +import OAI.Combinatorics.MatchingCount.Machines.TreeClippedRun +import OAI.Combinatorics.MatchingCount.Sampling.ClippedEnvelope + +namespace OAI + +namespace MatchingFPRAS.ExecutableDP +open TreeTyped Finset + +def runCapped (o : CountInput) : List ℕ → Bags → Table → Bags×Table + | [],bs,t => (bs,t) + | l::ls,bs,t => runCapped o ls (trim bs l) + (cappedUpdate ((o,((bs,o.1.2),(l,t))),ls.length)) +lemma cappedStep_fold (o : CountInput) (ls : List ℕ) (bs : Bags) (t : Table) : + ls.foldl (fun z l=>cappedStep (l,z)) (o,(ls.length,(bs,t)))=(o,(0,runCapped o ls bs t)) := by + induction ls generalizing bs t with + | nil => rfl + | cons l ls ih => + simp only [List.foldl_cons,List.length_cons,cappedStep,Nat.add_sub_cancel] + exact ih _ _ +lemma cappedCount_run (o : CountInput) : + cappedCount o=finish ((runCapped o o.2 o.1.1 (initial (nLabels o,BInitial o))).2,nLabels o) := by + unfold cappedCount + rw [cappedStep_fold] + +variable {V : Type} [Fintype V] [DecidableEq V] {m : ℕ} +variable (bags : V → Finset (Fin m)) (parent : Fin m → Option (Fin m)) +lemma rawEntry_source (R : Finset V) (l a : Fin m) (r : ℕ) (t : Table) (bs : Bags) + (hbs : bs.Perm (activeRep bags R)) : + rawEntry (((bs,parentRep parent),(l.val,t)),(a.val,r))=UnitRefresh.Materialized.entry bags R parent l a t r := by + unfold rawEntry + rw [context_perm hbs] + unfold context + rw [parentRep_getD] + simp only [privateNumber_activeRep,sharedNumber_activeRep,totalNumber_activeRep] + exact entry_eq bags R parent l a t r + +lemma cappedUpdate_source (o : CountInput) (hps : o.1.2=parentRep parent) + (hn : nVertices o=Fintype.card V) (R : Finset V) (l : Fin m) (B : ℕ) + (hB : B≤nPlan o) (t : Table) (bs : Bags) (hbs : bs.Perm (activeRep bags R)) + (hsize : ∀ (a : Fin m) r,(UnitRefresh.Materialized.entry bags R parent l a t r).size≤capBits o) : + cappedUpdate ((o,((bs,o.1.2),(l.val,t))),B)=UnitRefresh.Materialized.update bags R parent l (Fintype.card V*B) t := by + have hm : nLabels o=m := by simp only [nLabels,hps,parentRep_length] + unfold cappedUpdate updateRows updateColumns + dsimp only + rw [hm,hn,Nat.min_eq_left hB] + rw [tabulate_materialized] + unfold UnitRefresh.Materialized.update + congr 1 + funext a r + unfold cappedEntry + dsimp only + rw [hps,rawEntry_source bags parent R l a r t bs hbs] + exact clip_eq _ _ (hsize a r) + +lemma runCapped_source (o : CountInput) (hps : o.1.2=parentRep parent) + (hn : nVertices o=Fintype.card V) + (hp : ∀ l p,parent l=some p → p≠l) (ls : List (Fin m)) (R : Finset V) + (t : Table) (bs : Bags) (hbs : bs.Perm (activeRep bags R)) + (w : Fin m → ℕ) (hw : ∀ a,1≤w a) (ht : UnitRefresh.Materialized.RowBound t w) + (E : ℕ) (he : (∏ a,w a)≤2^E) + (hL : ls.length≤nPlan o) (hK : Fintype.card V*ls.length+E+1≤capBits o) : + (runCapped o (ls.map Fin.val) bs t).2=UnitRefresh.Materialized.run bags parent ls R t := by + induction ls generalizing R bs t w E with + | nil => rfl + | cons l ls ih => + have hlen : ls.length≤nPlan o := by rw [List.length_cons] at hL; omega + have hstepK : E+Fintype.card V+1≤capBits o := by + rw [List.length_cons,Nat.mul_add,Nat.mul_one] at hK + omega + have hsize := UnitRefresh.Materialized.entry_size_budget bags R parent l t w hw ht (hp l) E (capBits o) he hstepK + have hup:=cappedUpdate_source bags parent o hps hn R l ls.length hlen t bs hbs hsize + simp only [List.map_cons,runCapped,List.length_map,UnitRefresh.Materialized.run] + rw [hup] + let v:=UnitRefresh.Materialized.nextEnvelope bags R parent l w + have hv : ∀ a,1≤v a := UnitRefresh.Materialized.nextEnvelope_pos bags R parent l w hw + have hvt : UnitRefresh.Materialized.RowBound (UnitRefresh.Materialized.update bags R parent l (Fintype.card V*ls.length) t) v := + UnitRefresh.Materialized.update_rowBound bags R parent l _ t w hw ht + have hvp : (∏ a,v a)≤2^(E+Fintype.card V) := UnitRefresh.Materialized.nextEnvelope_power bags R parent l w (hp l) E he + apply ih (UnitRefresh.trim bags R l) _ (trim bs l) ((hbs.filter _).trans (trim_activeRep bags R l)) v hv hvt + (E+Fintype.card V) hvp hlen + rw [List.length_cons,Nat.mul_add,Nat.mul_one] at hK + omega + +lemma cappedCount_rep (ls : List (Fin m)) (bs : Bags) (hbs : bs.Perm (activeRep bags univ)) + (hp : ∀ l p,parent l=some p → p≠l) : + cappedCount ((bs,parentRep parent),ls.map Fin.val)=UnitRefresh.Materialized.count bags parent ls := by + let o : CountInput := ((bs,parentRep parent),ls.map Fin.val) + have hn : nVertices o=Fintype.card V := by + dsimp only [o,nVertices] + rw [hbs.length_eq] + simp [activeRep] + have hm : nLabels o=m := by simp [o,nLabels] + have hL : nPlan o=ls.length := by simp [o,nPlan] + rw [cappedCount_run] + change finish ((runCapped o (ls.map Fin.val) (bs) (initial (nLabels o,BInitial o))).2,nLabels o)=_ + rw [hm,initial_eq] + let B:=BInitial o + let E:=B*B*m + have hw : ∀ a : Fin m,1≤2^(B*B) := fun _=>Nat.one_le_iff_ne_zero.mpr (by positivity) + have he : (∏ a : Fin m,2^(B*B))≤2^E := by + simp only [prod_const,card_univ,Fintype.card_fin,←pow_mul,E] + exact le_rfl + have hK : Fintype.card V*ls.length+E+1≤capBits o := by + unfold capBits + rw [hn,hL] + dsimp only [E,B] + rw [hm,pow_two] + rw [runCapped_source bags parent o rfl hn hp ls univ (UnitRefresh.Materialized.initial m B) (bs) + hbs (fun _=>2^(B*B)) hw (UnitRefresh.Materialized.initial_rowBound B) E he (by rw [hL]) hK] + rw [finish_eq] + unfold UnitRefresh.Materialized.count + rw [show B=Fintype.card V*m by dsimp only [B,BInitial]; rw [hn,hm]] + +lemma cappedCount_source (ls : List (Fin m)) + (hp : ∀ l p,parent l=some p → p≠l) : + cappedCount ((activeRep bags Finset.univ,parentRep parent),ls.map Fin.val)=UnitRefresh.Materialized.count bags parent ls := + cappedCount_rep bags parent ls _ (List.Perm.refl _) hp + +omit [Fintype V] [DecidableEq V] in +lemma cappedCount_ordered {n : ℕ} (bags : Fin n → Finset (Fin m)) (ls : List (Fin m)) + (hp : ∀ l p,parent l=some p → p≠l) : + cappedCount ((orderedRep bags,parentRep parent),ls.map Fin.val)=UnitRefresh.Materialized.count bags parent ls := + cappedCount_rep bags parent ls _ (orderedRep_perm bags) hp + +theorem cappedCount_coloredPairings (rank : Fin m → ℕ) + (hb : UnitRefresh.RankedBags bags rank parent) (hne : ∀ x,(bags x).Nonempty) + (hp : ∀ l p,parent l=some p → rank px.2.1) := second.fst + let st : Realizer (fun x : ℕ×CappedState=>x.2.2) := second.snd + let rem := composition st.fst predecessor + let bs := composition (pair st.snd.fst first) trimRealizer + let inp := pair (pair o (pair (pair st.snd.fst o.fst.snd) (pair first st.snd.snd))) rem + exact (pair o (pair rem (pair bs (composition inp cappedUpdateRealizer)))).congr (fun _=>rfl) +lemma polynomial_cappedStep : PolynomialTime cappedStepRealizer := by + unfold cappedStepRealizer Realizer.fst Realizer.snd + dsimp only + apply polynomial_congr + have := polynomial_predecessor + have := polynomial_trim + have := polynomial_cappedUpdate + tree_poly + +def tableWeightBound (o : CountInput) : ℕ := + 1+nLabels o*(2+(nVertices o*nPlan o+1)*(4*capBits o+2)) +lemma cappedUpdate_weight (x : UpdateInput) : weight (cappedUpdate x)≤tableWeightBound x.1.1 := by + unfold cappedUpdate tabulate + have hw:=weight_map_bound (as:=List.range (updateRows x)) + (f:=fun a=>(List.range (updateColumns x+1)).map fun r=>cappedEntry (x,(a,r))) + (N:=1+(nVertices x.1.1*nPlan x.1.1+1)*(4*capBits x.1.1+2)) (by + intro a _ + have hh:=weight_map_bound (as:=List.range (updateColumns x+1)) + (f:=fun r=>cappedEntry (x,(a,r))) (N:=4*capBits x.1.1+1) (by + intro r _ + have hb:=clip_size (capBits x.1.1) (rawEntry (x.1.2,(a,r))) + have hw:=weight_nat_le (cappedEntry (x,(a,r))) + change (cappedEntry (x,(a,r))).size≤capBits x.1.1 at hb + omega) + simp only [List.length_range] at hh + simp only [Nat.add_assoc, Nat.reduceAdd] at hh + have hdim : updateColumns x≤nVertices x.1.1*nPlan x.1.1 := Nat.mul_le_mul_left _ (min_le_right _ _) + have hm:=Nat.mul_le_mul_right (4*capBits x.1.1+2) (Nat.add_le_add_right hdim 1) + exact hh.trans (by omega)) + simp only [List.length_range,updateRows] at hw + unfold tableWeightBound + dsimp only + exact hw.trans_eq (by ring) +lemma tableWeightBound_polynomial (o : CountInput) : + tableWeightBound o≤1+weight o*(2+((weight o)^2+1)*(4*((weight o)^2+(weight o)^5+1)+2)) := by + obtain ⟨hn,hm,hL⟩:=input_lengths o + have hb:=capBits_bound o + have hprod : nVertices o*nPlan o≤(weight o)^2 := by simpa only [pow_two] using Nat.mul_le_mul hn hL + unfold tableWeightBound + exact Nat.add_le_add_left (Nat.mul_le_mul hm (Nat.add_le_add_left (Nat.mul_le_mul + (Nat.add_le_add_right hprod 1) (by omega)) 2)) 1 + +lemma cappedFold_invariant (ls : List ℕ) (z : CappedState) : + let r:=ls.foldl (fun z l=>cappedStep (l,z)) z + r.1=z.1 ∧ r.2.1≤z.2.1 ∧ r.2.2.1.Sublist z.2.2.1 ∧ + weight r.2.2.2≤weight z.2.2.2+tableWeightBound z.1 := by + induction ls generalizing z with + | nil => exact ⟨rfl,le_rfl,List.Sublist.refl _,Nat.le_add_right _ _⟩ + | cons l ls ih => + have h:=ih (cappedStep (l,z)) + dsimp only at h ⊢ + simp only [List.foldl_cons] + refine ⟨h.1,h.2.1.trans (Nat.sub_le _ _),h.2.2.1.trans (List.filter_sublist (p:=fun b=>!(totalFlag (l,b))) (l:=z.2.2.1)),?_⟩ + + cases ls with + | nil => + change weight (cappedUpdate _)≤_ + exact (cappedUpdate_weight _).trans (Nat.le_add_left _ _) + | cons l' ls => + + clear ih h + have hs : ∀ (as : List ℕ) (v : CappedState) (j : ℕ), + weight ((as.foldl (fun z l=>cappedStep (l,z)) (cappedStep (j,v))).2.2.2)≤tableWeightBound v.1 := by + intro as + induction as with + | nil => intro v j; exact cappedUpdate_weight _ + | cons a as ih => + intro v j + simp only [List.foldl_cons] + exact ih (cappedStep (j,v)) a + exact (hs ls (cappedStep (l,z)) l').trans (Nat.le_add_left _ _) + +lemma weight_cappedState (z : CappedState) : weight z=3+weight z.1+weight z.2.1+weight z.2.2.1+weight z.2.2.2 := by + rcases z with ⟨o,k,bs,t⟩ + simp only [weight_prod] + omega + +lemma polynomial_cappedFold : PolynomialTime (fold cappedStepRealizer) := by + let P : Polynomial ℕ := 1+X*(2+(X^2+1)*(4*(X^2+X^5+1)+2)) + apply polynomial_fold polynomial_cappedStep (8*X+10+P) + intro ls z pre _ _ + let S:=weight (ls,z) + let r:=pre.foldl (fun z l=>cappedStep (l,z)) z + have hi:=cappedFold_invariant pre z + change r.1=z.1 ∧ r.2.1≤z.2.1 ∧ r.2.2.1.Sublist z.2.2.1 ∧ weight r.2.2.2≤weight z.2.2.2+tableWeightBound z.1 at hi + have hz : weight z≤S := weight_snd (ls,z) + have ho : weight z.1≤S := (weight_fst z).trans hz + have hr : weight z.2.1≤S := (weight_fst z.2).trans ((weight_snd z).trans hz) + have hb : weight z.2.2.1≤S := (weight_fst z.2.2).trans ((weight_snd z.2).trans ((weight_snd z).trans hz)) + have ht : weight z.2.2.2≤S := (weight_snd z.2.2).trans ((weight_snd z.2).trans ((weight_snd z).trans hz)) + have h0 : weight r.1≤S := by rw [hi.1]; exact ho + have h1 : weight r.2.1≤4*S+1 := by + have hh:=weight_nat_le r.2.1 + have hh':=(Nat.size_le_size hi.2.1).trans (size_le_weight z.2.1) + omega + have h2 : weight r.2.2.1≤S := (weight_sublist hi.2.2.1).trans hb + have htable:tableWeightBound z.1≤P.eval S := by + apply (tableWeightBound_polynomial z.1).trans + simpa only [P, Polynomial.eval_add, Polynomial.eval_mul, Polynomial.eval_one, Polynomial.eval_ofNat, Polynomial.eval_pow, Polynomial.eval_X] using polynomial_eval_monotone P ho + change weight r≤_ + rw [weight_cappedState r] + simp only [Polynomial.eval_add,Polynomial.eval_mul,Polynomial.eval_ofNat,Polynomial.eval_X] + change _≤8*S+10+P.eval S + omega + +def finishFast : Realizer (fun x : CountInput×Table=>finish (x.2,nLabels x.1)) := + composition (composition (pair second (composition (composition first nLabelsRealizer) range)) + (mapWith (composition (pair first (pair second (constant 0))) readFast))) listProd +lemma polynomial_finishFast : PolynomialTime finishFast := by + unfold finishFast + apply polynomial_composition _ polynomial_listProd + apply polynomial_composition + · apply polynomial_pair polynomial_second + apply polynomial_boundedRange (polynomial_composition polynomial_first polynomial_nLabels) X + intro x + simp only [Function.comp_apply,Polynomial.eval_X] + exact (input_lengths x.1).2.1.trans (weight_fst x) + · apply polynomial_mapWith + apply polynomial_composition _ polynomial_readFast + tree_poly + +def cappedCount (o : CountInput) : ℕ := + finish ((o.2.foldl (fun z l=>cappedStep (l,z)) (o,(o.2.length,(o.1.1,initial (nLabels o,BInitial o))))).2.2.2,nLabels o) +def cappedCountRealizer : Realizer cappedCount := by + let init : Realizer (fun o : CountInput=>(o.2,(o,(o.2.length,(o.1.1,initial (nLabels o,BInitial o)))))) := + pair second (pair identity (pair nPlanRealizer (pair first.fst initialFast))) + exact (composition (pair identity (composition (composition init (fold cappedStepRealizer)) second.snd.snd)) finishFast).congr (fun _=>rfl) +lemma polynomial_cappedCount : PolynomialTime cappedCountRealizer := by + unfold cappedCountRealizer + dsimp only + apply polynomial_congr + apply polynomial_composition _ polynomial_finishFast + apply polynomial_pair polynomial_identity + apply polynomial_composition _ (polynomial_snd (polynomial_snd polynomial_second)) + apply polynomial_composition _ polynomial_cappedFold + apply polynomial_pair polynomial_second + apply polynomial_pair polynomial_identity + apply polynomial_pair polynomial_nPlan + exact polynomial_pair (polynomial_fst polynomial_first) polynomial_initialFast +end MatchingFPRAS.ExecutableDP + +end OAI diff --git a/lean/OAI/Combinatorics/MatchingCount/Machines/TreeClosureReindex.lean b/lean/OAI/Combinatorics/MatchingCount/Machines/TreeClosureReindex.lean new file mode 100644 index 0000000000000000000000000000000000000000..274c4997d878cb160d4746ccaed4df0b01a00f47 --- /dev/null +++ b/lean/OAI/Combinatorics/MatchingCount/Machines/TreeClosureReindex.lean @@ -0,0 +1,48 @@ +import Mathlib +import OAI.Combinatorics.MatchingCount.Sampling.DiscreteLadderSteps + +namespace OAI + +namespace MatchingFPRAS.UnitRefresh +lemma orderedEnum_lt {A : Type} [Fintype A] [LinearOrder A] + (i j : Fin (Fintype.card A)) : orderedEnum A i < orderedEnum A j ↔ i < j := by + change ((Finset.univ : Finset A).orderIsoOfFin (Finset.card_univ) i).val < + ((Finset.univ : Finset A).orderIsoOfFin (Finset.card_univ) j).val ↔ _ + exact ((Finset.univ : Finset A).orderIsoOfFin (Finset.card_univ)).lt_iff_lt +end MatchingFPRAS.UnitRefresh + +namespace MatchingFPRAS.BottleneckAlgorithm +open Finset + +variable {V W α : Type} [Fintype V] [Fintype W] [LinearOrder V] [LinearOrder W] + [LinearOrder α] [OfNat α 1] +omit [Fintype V] [Fintype W] in +lemma seed_reindex (e : V≃W) (he : ∀ a b,e aw (e i) (e j)) a b=seed w (e a) (e b) := by + simp only [seed,edge,e.injective.eq_iff,he] +lemma advance_reindex (e : V≃W) (w : W→W→α) (a b : V) : + advance (fun i j=>w (e i) (e j)) a b=advance w (e a) (e b) := by + unfold advance + simp only [e.injective.eq_iff] + split_ifs + · rfl + · congr 1 + apply le_antisymm + · apply Finset.sup'_le + intro c _ + exact Finset.le_sup' (fun k=>min (w (e a) k) (w k (e b))) (Finset.mem_univ (e c)) + · apply Finset.sup'_le + intro c _ + obtain ⟨d,rfl⟩:=e.surjective c + exact Finset.le_sup' (fun k=>min (w (e a) (e k)) (w (e k) (e b))) (Finset.mem_univ d) +lemma close_reindex (e : V≃W) (he : ∀ a b,e aw (e i) (e j)) k=fun i j=>close w k (e i) (e j) := by + induction k with + | zero=>funext a b; exact seed_reindex e he w a b + | succ k ih=> + simp only [close,ih] + funext a b + exact advance_reindex e _ a b +end MatchingFPRAS.BottleneckAlgorithm + +end OAI diff --git a/lean/OAI/Combinatorics/MatchingCount/Machines/TreeColex.lean b/lean/OAI/Combinatorics/MatchingCount/Machines/TreeColex.lean new file mode 100644 index 0000000000000000000000000000000000000000..6f1fea500f934ecb7ffe0b4a64784fb7f98e76c3 --- /dev/null +++ b/lean/OAI/Combinatorics/MatchingCount/Machines/TreeColex.lean @@ -0,0 +1,78 @@ +import Mathlib +import OAI.Combinatorics.MatchingCount.Machines.TreeFiniteOps + +namespace OAI + +namespace MatchingFPRAS.TreeTyped +variable {A B : Type} [Codec A] [Codec B] [LinearOrder A] [LinearOrder B] + +def boolOr : Realizer (fun x : Bool×Bool=>x.1 || x.2) := + (choose first (constant true) second).congr (by intro x; cases x.1 <;> rfl) +lemma polynomial_boolOr : PolynomialTime boolOr := by + unfold boolOr + exact polynomial_congr _ (polynomial_choose polynomial_first (polynomial_constant true) polynomial_second) + +def colexLe (E : Realizer (fun x : A×A=>decide (x.1=x.2))) + (R : Realizer (fun x : A×A=>decide (x.1≤x.2))) : + Realizer (fun x : Finset A×Finset A=>decide (toColex x.1≤toColex x.2)) := + (composition (pair (composition (pair second first) (finsetSDiff E)) (finsetSDiff E)) + (finsetAll (composition (pair second first) (finsetAny R)))).congr (by + intro x + apply Bool.eq_iff_iff.mpr + simp only [Function.comp_apply,decide_eq_true_eq,Finset.mem_sdiff] + rw [Finset.Colex.toColex_le_toColex] + constructor + · intro h a ha hn + obtain ⟨b,⟨hb,hbn⟩,hab⟩:=h a ⟨ha,hn⟩ + exact ⟨b,hb,hbn,hab⟩ + · intro h a ⟨ha,hn⟩ + obtain ⟨b,hb,hbn,hab⟩:=h ha hn + exact ⟨b,⟨hb,hbn⟩,hab⟩) +lemma polynomial_colexLe {E : Realizer (fun x : A×A=>decide (x.1=x.2))} + {R : Realizer (fun x : A×A=>decide (x.1≤x.2))} + (hE : PolynomialTime E) (hR : PolynomialTime R) : PolynomialTime (colexLe E R) := by + unfold colexLe + apply polynomial_congr + exact polynomial_composition (polynomial_pair + (polynomial_composition (polynomial_pair polynomial_second polynomial_first) (polynomial_finsetSDiff hE)) + (polynomial_finsetSDiff hE)) + (polynomial_finsetAll (polynomial_composition (polynomial_pair polynomial_second polynomial_first) + (polynomial_finsetAny hR))) + +def lexLe (E : Realizer (fun x : A×A=>decide (x.1=x.2))) + (R : Realizer (fun x : A×A=>decide (x.1≤x.2))) + (S : Realizer (fun x : B×B=>decide (x.1≤x.2))) : + Realizer (fun x : (A×B)×(A×B)=>decide (toLex x.1≤toLex x.2)) := + (composition (pair (composition (pair first.fst second.fst) R) + (composition (pair (composition (composition (pair first.fst second.fst) E) boolNot) + (composition (pair first.snd second.snd) S)) boolOr)) boolAnd).congr (by + intro x + apply Bool.eq_iff_iff.mpr + simp only [Function.comp_apply,Bool.and_eq_true,Bool.or_eq_true,Bool.not_eq_true', + decide_eq_true_eq,decide_eq_false_iff_not,Prod.Lex.le_iff] + rcases x with ⟨⟨a,b⟩,⟨c,d⟩⟩ + dsimp only + constructor + · rintro ⟨h,h'⟩ + rcases lt_or_eq_of_le h with h | h + · exact Or.inl h + · exact Or.inr ⟨h,h'.resolve_left (not_not.mpr h)⟩ + · rintro (h|⟨h,h'⟩) + · exact ⟨h.le,Or.inl (ne_of_lt h)⟩ + · exact ⟨h.le,Or.inr h'⟩) +lemma polynomial_lexLe {E : Realizer (fun x : A×A=>decide (x.1=x.2))} + {R : Realizer (fun x : A×A=>decide (x.1≤x.2))} + {S : Realizer (fun x : B×B=>decide (x.1≤x.2))} + (hE : PolynomialTime E) (hR : PolynomialTime R) (hS : PolynomialTime S) : + PolynomialTime (lexLe E R S) := by + unfold lexLe + exact polynomial_congr _ (polynomial_composition (polynomial_pair + (polynomial_composition (polynomial_pair (polynomial_fst polynomial_first) (polynomial_fst polynomial_second)) hR) + (polynomial_composition (polynomial_pair + (polynomial_composition (polynomial_composition + (polynomial_pair (polynomial_fst polynomial_first) (polynomial_fst polynomial_second)) hE) polynomial_boolNot) + (polynomial_composition (polynomial_pair (polynomial_snd polynomial_first) (polynomial_snd polynomial_second)) hS)) polynomial_boolOr)) + polynomial_boolAnd) +end MatchingFPRAS.TreeTyped + +end OAI diff --git a/lean/OAI/Combinatorics/MatchingCount/Machines/TreeColor.lean b/lean/OAI/Combinatorics/MatchingCount/Machines/TreeColor.lean new file mode 100644 index 0000000000000000000000000000000000000000..ae947a9f760d8a34c3fbfff3199b687a17a36919 --- /dev/null +++ b/lean/OAI/Combinatorics/MatchingCount/Machines/TreeColor.lean @@ -0,0 +1,113 @@ +import Mathlib +import OAI.Combinatorics.MatchingCount.Machines.TreeColoredIndex +import OAI.Combinatorics.MatchingCount.Machines.TreeInitial + +namespace OAI + +namespace MatchingFPRAS.ExecutableSource +open TreeTyped TreeFraction TreeTyped.Numbered ExecutableBottleneck ExecutableHierarchy ExecutableRefresh Enlargement RealGeometry + +attribute [local instance] NumberedHierarchy.labelOrder +attribute [local instance] Transport.sym2Order Transport.bagEdgeOrder Transport.bagEdgeFintype + +lemma sourceTables_catalog {n : ℕ} [Nontrivial (Fin n)] (hn : 2≤n) + (w : Fin n→Fin n→ℚ) (hw : ∀ i j,0≤w i j) (K : ℕ) : + (sourceTables (((matrixRep w,List.replicate (2*K+2) false),List.range n),List.replicate (2*K) false)).1= + sourceCatalog (RationalSource.bags w K) := by + rw [sourceTables,refreshTables,setupHierarchy, + buildClosure_repr hn w hw K,hierarchyFuel_source hn w hw K] + dsimp only + rw [arbitrary_labelIndices_fintype (RationalSource.realB w K) + (fun a b=>(by norm_num : (0:ℚ)≤1).trans (RationalSource.realB_floor w K a b)) + (List.replicate (RationalSource.levels w K) false) (RationalSource.levels w K) + (List.length_replicate ..) (inferInstance : Fintype (RationalSource.Label w K))] + have catalog := storedCatalog_source (bags:=RationalSource.bags w K) _ (source_bagTable w K) + exact catalog + +def coloredKey (x : HierarchyInput×(ℕ×ℕ)) : Key := + ((min x.2.1 x.2.2,max x.2.1 x.2.2),edgeIndex ((x.1,labels x.1),x.2)) +def coloredKeyRealizer : Realizer coloredKey := (pair + (pair (composition second TreeTyped.minimum) (composition second TreeTyped.maximum)) + (composition (pair (pair first (composition first labelsRealizer)) second) edgeIndexRealizer)).congr (fun _=>rfl) +lemma polynomial_coloredKey : PolynomialTime coloredKeyRealizer := by + unfold coloredKeyRealizer + apply polynomial_congr + have := polynomial_labels + have := polynomial_edgeIndex + have hmax : PolynomialTime TreeTyped.maximum := by + unfold TreeTyped.maximum + exact polynomial_congr _ (polynomial_choose polynomial_less polynomial_second polynomial_first) + have hmin := TreeTyped.polynomial_minimum + tree_cost + +def sourceRealKey (x : BagBuildInput×RawReal) : Key := + coloredKey ((setupHierarchy x.1).1, + endpointEntry (((x.1.1.2,x.1.1.1.2),vertices (x.1.1.2,x.1.1.1.2)),x.2)) +def sourceRealKeyRealizer : Realizer sourceRealKey := (composition + (pair (composition first setupHierarchyRealizer).fst + (composition (pair (pair (pair first.fst.snd first.fst.fst.snd) + (composition (pair first.fst.snd first.fst.fst.snd) verticesRealizer)) second) endpointEntryRealizer)) coloredKeyRealizer).congr (fun _=>rfl) +lemma polynomial_sourceRealKey : PolynomialTime sourceRealKeyRealizer := by + unfold sourceRealKeyRealizer + dsimp only [Realizer.fst,Realizer.snd] + apply polynomial_congr + have := polynomial_setupHierarchy + have := polynomial_vertices + have := polynomial_endpointEntry + have := polynomial_coloredKey + tree_cost + +lemma sourceRealKey_source {n : ℕ} [Nontrivial (Fin n)] (hn : 2≤n) + (w : Fin n→Fin n→ℚ) (hw : ∀ i j,0≤w i j) (K : ℕ) + (e : SourceRealEdge (Fin n) K) : + sourceRealKey ((((matrixRep w,List.replicate (2*K+2) false),List.range n),List.replicate (2*K) false),realRepr e)= + sourceKey (RationalSource.coloredReal w K e) := by + unfold sourceRealKey setupHierarchy coloredKey + dsimp only + rw [buildClosure_repr hn w hw K,hierarchyFuel_source hn w hw K, + endpointEntry_source K _ (List.length_replicate ..) e] + dsimp only + rw [arbitrary_edgeIndex_fintype (RationalSource.realB w K) + (fun a b=>(by norm_num : (0:ℚ)≤1).trans (RationalSource.realB_floor w K a b)) + (RationalSource.realB_symm w K) (RationalSource.realB_tri w K) + (List.replicate (RationalSource.levels w K) false) (realLeft K) (realRight K) + (RationalSource.levels w K) (List.length_replicate ..) + (inferInstance : Fintype (RationalSource.Label w K)) e] + exact (sourceKey_mk (RationalSource.coloredReal w K e) (realLeft K e) (realRight K e) + (RationalSource.realLabel w K e) rfl).symm + +def sourceRealIndex (x : BagBuildInput×RawReal) : ℕ := + (sourceTables x.1).1.idxOf (sourceRealKey x) +def keyLookup {A : Type} [Codec A] {f : A→Key} {g : A→List Key} + (F : Realizer f) (G : Realizer g) : Realizer (fun x=>(g x).idxOf (f x)) := + composition (pair F G) (indexOf (pairEqual (pairEqual natEqual natEqual) natEqual)) +lemma polynomial_keyLookup {A : Type} [Codec A] {f : A→Key} {g : A→List Key} + {F : Realizer f} {G : Realizer g} (hF : PolynomialTime F) (hG : PolynomialTime G) : + PolynomialTime (keyLookup F G) := + polynomial_composition (polynomial_pair hF hG) + (polynomial_indexOf (polynomial_pairEqual (polynomial_pairEqual polynomial_natEqual polynomial_natEqual) polynomial_natEqual)) +def sourceRealIndexRealizer : Realizer sourceRealIndex := + keyLookup sourceRealKeyRealizer (composition (first (A:=BagBuildInput) (B:=RawReal)) sourceTablesRealizer).fst +lemma polynomial_sourceRealIndex : PolynomialTime sourceRealIndexRealizer := + polynomial_keyLookup polynomial_sourceRealKey + (polynomial_fst (polynomial_composition polynomial_first polynomial_sourceTables)) +lemma sourceRealIndex_source {n : ℕ} [Nontrivial (Fin n)] (hn : 2≤n) + (w : Fin n→Fin n→ℚ) (hw : ∀ i j,0≤w i j) (K : ℕ) + (e : SourceRealEdge (Fin n) K) : + sourceRealIndex ((((matrixRep w,List.replicate (2*K+2) false),List.range n),List.replicate (2*K) false),realRepr e)= + index (RationalSource.coloredReal w K e) := by + unfold sourceRealIndex + rw [sourceTables_catalog hn w hw K,sourceRealKey_source hn w hw K,sourceCatalog_index] + +open TreePost Turing + +theorem sourceRealIndex_post : ∃ p : Polynomial ℕ,∀ x : BagBuildInput×RawReal,∀ t : ℕ, + p.eval (packed x).length≤t → ∀ coins : Fin t→Bool, + (run (machine sourceRealIndexRealizer.program) (packed x) coins).state=none ∧ + (run (machine sourceRealIndexRealizer.program) (packed x) coins).tape.right₀= + ListBlank.mk (packed (sourceRealIndex x)) := + polynomial_compiles sourceRealIndexRealizer polynomial_sourceRealIndex + +end MatchingFPRAS.ExecutableSource + +end OAI diff --git a/lean/OAI/Combinatorics/MatchingCount/Machines/TreeColorRaw.lean b/lean/OAI/Combinatorics/MatchingCount/Machines/TreeColorRaw.lean new file mode 100644 index 0000000000000000000000000000000000000000..5185476a9aecb5692aca133757ed1dd0847c1f73 --- /dev/null +++ b/lean/OAI/Combinatorics/MatchingCount/Machines/TreeColorRaw.lean @@ -0,0 +1,52 @@ +import Mathlib +import OAI.Combinatorics.MatchingCount.Tapes.TreeSparseComponents +import OAI.Combinatorics.MatchingCount.Complexity.TreeCostTactic + +namespace OAI + +namespace MatchingFPRAS.TreeTyped.SparseProgram +open TreeTyped + +variable {E C : Type} [Codec E] [Codec C] [LinearOrder E] +attribute [local instance] Transport.Sparse.finsetOrder + +def colorRaw (p : C×(E×E)→Bool) (x : (C×Finset E)×Finset E) : Finset (Finset E) := + x.2.biUnion fun e=>(x.1.2.filter (fun f=>p (x.1.1,(f,e))=true)).image fun f=>insert f (x.2.erase e) +def colorRawRealizer {p : C×(E×E)→Bool} (P : Realizer p) + (Eq : Realizer (fun x : E×E=>decide (x.1=x.2))) + (Le : Realizer (fun x : E×E=>decide (x.1≤x.2))) : Realizer (colorRaw p) := by + let choices : Realizer (fun x : ((C×Finset E)×Finset E)×E=> + x.1.1.2.filter (fun f=>p (x.1.1.1,(f,x.2))=true)) := + (composition (pair (pair first.fst.fst second) first.fst.snd) + (finsetFilterWith (composition (pair first.fst (pair second first.snd)) P))).congr (fun _=>rfl) + let edit : Realizer (fun x : (((C×Finset E)×Finset E)×E)×E=> + insert x.2 (x.1.1.2.erase x.1.2)) := + (composition (pair second (composition (pair first.snd first.fst.snd) (finsetErase Eq))) (finsetInsert Eq Le)).congr (fun _=>rfl) + let neighbors : Realizer (fun x : ((C×Finset E)×Finset E)×E=> + (x.1.1.2.filter (fun f=>p (x.1.1.1,(f,x.2))=true)).image fun f=>insert f (x.1.2.erase x.2)) := + (composition (pair identity choices) (finsetImageWith edit (orderedSetEqual Eq) (colexLe Eq Le))).congr (by + intro x; ext a; simp only [Function.comp_apply,id_eq,Finset.mem_image]) + exact (composition (pair identity second) + (finsetBiUnion neighbors (orderedSetEqual Eq) (colexLe Eq Le))).congr (by + intro x; ext a; simp only [Function.comp_apply,id_eq,colorRaw,Finset.mem_biUnion,Finset.mem_image]) +lemma polynomial_colorRaw {p : C×(E×E)→Bool} {P : Realizer p} + {Eq : Realizer (fun x : E×E=>decide (x.1=x.2))} + {Le : Realizer (fun x : E×E=>decide (x.1≤x.2))} + (hP : PolynomialTime P) (hEq : PolynomialTime Eq) (hLe : PolynomialTime Le) : + PolynomialTime (colorRawRealizer P Eq Le) := by + unfold colorRawRealizer + dsimp only [Realizer.fst,Realizer.snd] + have := polynomial_orderedSetEqual hEq + have := polynomial_colexLe hEq hLe + apply polynomial_congr + tree_cost + all_goals apply polynomial_finsetImageWith <;> tree_cost + +omit [Codec E] [Codec C] in +lemma colorRaw_eq [Codec E] [Codec C] [Fintype E] {V : Type} [DecidableEq V] (ends : E→Sym2 V) + (p : C×(E×E)→Bool) (c : C) (hp : ∀ e f,p (c,(e,f))=decide (ends e=ends f)) (M : Finset E) : + colorRaw p ((c,Finset.univ),M)=Transport.Sparse.colorRaw ends M := by + simp only [colorRaw,Transport.Sparse.colorRaw,hp,decide_eq_true_eq] +end MatchingFPRAS.TreeTyped.SparseProgram + +end OAI diff --git a/lean/OAI/Combinatorics/MatchingCount/Machines/TreeColoredIndex.lean b/lean/OAI/Combinatorics/MatchingCount/Machines/TreeColoredIndex.lean new file mode 100644 index 0000000000000000000000000000000000000000..ee453310fbdfc5c15033f17413442b8c4810dac3 --- /dev/null +++ b/lean/OAI/Combinatorics/MatchingCount/Machines/TreeColoredIndex.lean @@ -0,0 +1,73 @@ +import Mathlib +import OAI.Combinatorics.MatchingCount.Machines.TreeRefreshTables + +namespace OAI + +namespace MatchingFPRAS.ExecutableHierarchy +open TreeTyped TreeTyped.Numbered ExecutableBottleneck NumberedHierarchy + +attribute [local instance] NumberedHierarchy.labelOrder +variable {V : Type} [Fintype V] [LinearOrder V] +variable (B : V→V→ℚ) (hB : ∀ a b,0≤B a b) + (hsym : ∀ a b,B a b=B b a) + (htri : ∀ x y z,x≠y → x≠z → y≠z → min (B x z) (B z y)≤B x y) +variable (xs : List Bool) {E : Type} [Fintype E] [DecidableEq E] (left right : E→V) +include hB in +lemma arbitrary_edgeIndex (a : E) : + edgeIndex (((matrixRep (reindex B (orderedIso V)),xs), + labels (matrixRep (reindex B (orderedIso V)),xs)),(index (left a),index (right a)))= + index (edgeLabel B hsym htri left right xs.length a) := by + let e:=orderedIso V + have h:=edgeIndex_eq (reindex B e) (fun a b=>hB (e a) (e b)) + (reindex_symm B e hsym) (reindex_tri B e htri) xs (e.symm ∘ left) (e.symm ∘ right) a + change edgeIndex (((matrixRep (reindex B e),xs),labels (matrixRep (reindex B e),xs)), + (index (left a),index (right a)))=index (edgeLabel (reindex B e) + (reindex_symm B e hsym) (reindex_tri B e htri) (e.symm ∘ left) (e.symm ∘ right) xs.length a) at h + rw [h,←labelReindex_index B e xs.length,edgeLabel_reindex B e hsym htri] + +include hB in +lemma arbitrary_edgeIndex_fintype (H : ℕ) (hH : xs.length=H) + (F : Fintype (Label B H)) (a : E) : + letI := F + edgeIndex (((matrixRep (fun i j=>B (UnitRefresh.orderedEnum V i) (UnitRefresh.orderedEnum V j)),xs), + labels (matrixRep (fun i j=>B (UnitRefresh.orderedEnum V i) (UnitRefresh.orderedEnum V j)),xs)), + (index (left a),index (right a)))=index (edgeLabel B hsym htri left right H a) := by + subst H + have hF : F=ordinaryLabelFintype B xs.length := Subsingleton.elim _ _ + subst F + exact arbitrary_edgeIndex B hB hsym htri xs left right a + +omit [Fintype E] [DecidableEq E] in +include hB in +lemma arbitrary_labelIndices_fintype (H : ℕ) (hH : xs.length=H) + (F : Fintype (Label B H)) : + letI := F + labelIndices (matrixRep (fun i j=>B (UnitRefresh.orderedEnum V i) + (UnitRefresh.orderedEnum V j)),xs)=List.range (Fintype.card (Label B H)) := by + subst H + have hF : F=ordinaryLabelFintype B xs.length := Subsingleton.elim _ _ + subst F + exact arbitrary_labelIndices B hB xs + +end MatchingFPRAS.ExecutableHierarchy + +namespace MatchingFPRAS.ExecutableRefresh +open TreeTyped TreeTyped.Numbered UnitRefresh Transport + +attribute [local instance] Transport.sym2Order Transport.bagEdgeOrder Transport.bagEdgeFintype +variable {V L : Type} [Fintype V] [LinearOrder V] [Fintype L] [LinearOrder L] +variable {bags : V→Finset L} +lemma sourceKey_mk (e : BagEdge bags) (a b : V) (l : L) + (he : e.val.val=(s(a,b),l)) : + sourceKey e=((min (index a) (index b),max (index a) (index b)),index l) := by + unfold sourceKey + rw [he] + simp only [Sym2.inf_mk,Sym2.sup_mk,index_min,index_max] + +lemma storedCatalog_source (a : ExecutableDP.Bags) + (ha : List.Forall₂ List.Perm a (ExecutableDP.orderedRep (numberedBags bags))) : + storedCatalog (a,List.range (Fintype.card L))=sourceCatalog bags := by + rw [storedCatalog_eq ha,sourceCatalog_eq] +end MatchingFPRAS.ExecutableRefresh + +end OAI diff --git a/lean/OAI/Combinatorics/MatchingCount/Machines/TreeCompiler.lean b/lean/OAI/Combinatorics/MatchingCount/Machines/TreeCompiler.lean new file mode 100644 index 0000000000000000000000000000000000000000..ff1b1fe66978c259672070a29032624e1cab175a --- /dev/null +++ b/lean/OAI/Combinatorics/MatchingCount/Machines/TreeCompiler.lean @@ -0,0 +1,140 @@ +import Mathlib +import OAI.Combinatorics.MatchingCount.Machines.TreeMachine + +namespace OAI + +namespace MatchingFPRAS.TreeMachine +open TreeData RegisterProc Turing MachineCost + +variable {R Λ : Type} [DecidableEq R] + +inductive Effect : Instr R Λ → Env R → Option Λ → Env R → Prop + | halt (E) : Effect .halt E none E + | go (E l) : Effect (.go l) E (some l) E + | nilBranch (E i l r) (h : E i=.nil) : Effect (.branch i l r) E (some l) E + | consBranch (E i l r x y) (h : E i=.cons x y) : Effect (.branch i l r) E (some r) E + | nil (E i l) : Effect (.nil i l) E (some l) (Function.update E i .nil) + | copy (E i j h l) : Effect (.copy i j h l) E (some l) (putPair E i j (E i) (E i)) + | cons (E i j h l) : Effect (.cons i j h l) E (some l) (putPair E i j .nil (.cons (E i) (E j))) + | split (E i j h l x y) (he : E j=.cons x y) : Effect (.split i j h l) E (some l) (putPair E i j x y) + +abbrev Label (M : Λ → Instr R Λ) := Λ ⊕ ((l : Λ) × (procedure (M l)).Label) +instance (M : Λ → Instr R Λ) [Fintype Λ] : Fintype (Label M) := by unfold Label; infer_instance + +def code (M : Λ → Instr R Λ) : Label M → TM2.Stmt (fun _ : K R=>Bool) (Label M) Store + | .inl l => match M l with + | .halt => .halt + | .go k => .goto (fun _=>.inl k) + | .branch i a b => .peek (.inl i) (fun _ x=>x) (.branch (fun x=>x.getD false) + (.load (fun _=>none) (.goto (fun _=>.inl b))) + (.load (fun _=>none) (.goto (fun _=>.inl a)))) + | _ => .goto (fun _=>.inr ⟨l,default⟩) + | .inr ⟨l,u⟩ => StackComposition.relabel (fun u=>.inr ⟨l,u⟩) + ((successor (M l)).map Sum.inl) ((procedure (M l)).code u) + +def compile [Fintype Λ] [Inhabited Λ] (M : Λ → Instr R Λ) : Proc (K R) := + { Label := Label M + entry := ⟨.inl default⟩ + code := code M } + +def cfg (M : Λ → Instr R Λ) (l : Option Λ) (E : Env R) : TM2.Cfg (fun _ : K R=>Bool) (Label M) Store := + ⟨l.map Sum.inl,none,encodeEnv E⟩ + +def SizeBound (E : Env R) (B : ℕ) : Prop := ∀ i,(encode (E i)).length≤B + +lemma run_procedure (M : Λ → Instr R Λ) (l : Λ) (E F : Env R) (n : ℕ) + (h : Exec (procedure (M l)) (encodeEnv E) (encodeEnv F) n) + (hd : code M (.inl l)=.goto (fun _=>.inr ⟨l,default⟩)) : + ∃ k≤n+1,MachineCost.run (TM2.step (code M)) k (cfg M (some l) E)= + cfg M (successor (M l)) F := by + obtain ⟨j,hj,he⟩:=h + obtain ⟨k,hk,hs⟩:=StackComposition.run_relabel_to_halt (procedure (M l)).code (code M) + (fun u=>Sum.inr ⟨l,u⟩) ((successor (M l)).map Sum.inl) (fun _=>rfl) + j ⟨some default,none,encodeEnv E⟩ none (encodeEnv F) he + refine ⟨k+1,by omega,?_⟩ + rw [MachineCost.run] + have ha : advance (TM2.step (code M)) (cfg M (some l) E)= + StackComposition.mapCfg (fun u=>Sum.inr ⟨l,u⟩) ((successor (M l)).map Sum.inl) + ⟨some default,none,encodeEnv E⟩ := by + simp only [advance,TM2.step,cfg,Option.map_some,hd,TM2.stepAux,Option.getD_some, + StackComposition.mapCfg_some] + rw [ha,hs] + rfl + +theorem effect_compiles (M : Λ → Instr R Λ) (l : Λ) (I : Instr R Λ) (hI : M l=I) + (E F : Env R) (next : Option Λ) (h : Effect I E next F) (B : ℕ) (hB : SizeBound E B) : + ∃ k≤5*(B+1),MachineCost.run (TM2.step (code M)) k (cfg M (some l) E)=cfg M next F := by + cases h with + | halt E => + refine ⟨1,by omega,?_⟩ + simp only [MachineCost.run,advance,TM2.step,cfg,Option.map_some,code,hI,TM2.stepAux, + Option.getD_some,Option.map_none] + | go E a => + refine ⟨1,by omega,?_⟩ + simp only [MachineCost.run,advance,TM2.step,cfg,Option.map_some,code,hI,TM2.stepAux,Option.getD_some] + | nilBranch E i a b hi => + refine ⟨1,by omega,?_⟩ + simp only [MachineCost.run,advance,TM2.step,cfg,Option.map_some,code,hI,TM2.stepAux, + encodeEnv,hi,encode,List.head?_cons,Option.getD_some,Bool.cond_false] + | consBranch E i a b x y hi => + refine ⟨1,by omega,?_⟩ + simp only [MachineCost.run,advance,TM2.step,cfg,Option.map_some,code,hI,TM2.stepAux, + encodeEnv,hi,encode,List.head?_cons,Option.getD_some,Bool.cond_true] + | nil E i a => + have hp:=nil_exec E i a + rw [←hI] at hp + obtain ⟨k,hk,he⟩:=run_procedure M l E _ _ hp (by simp only [code,hI]) + refine ⟨k,?_,?_⟩ + · have hi:=hB i; omega + · simpa only [hI,successor] using he + | copy E i j hij a => + have hp:=copy_exec E i j hij a + rw [←hI] at hp + obtain ⟨k,hk,he⟩:=run_procedure M l E _ _ hp (by simp only [code,hI]) + refine ⟨k,?_,?_⟩ + · have hi:=hB i; have hj:=hB j; omega + · simpa only [hI,successor] using he + | cons E i j hij a => + have hp:=cons_exec E i j hij a + rw [←hI] at hp + obtain ⟨k,hk,he⟩:=run_procedure M l E _ _ hp (by simp only [code,hI]) + refine ⟨k,?_,?_⟩ + · have hi:=hB i; omega + · simpa only [hI,successor] using he + | split E i j hij a x y hy => + have hp:=split_exec E i j hij a x y hy + rw [←hI] at hp + obtain ⟨k,hk,he⟩:=run_procedure M l E _ _ hp (by simp only [code,hI]) + refine ⟨k,?_,?_⟩ + · have hi:=hB i; have hj:=hB j + rw [hy] at hj + simp only [encode,List.length_cons,List.length_append] at hj + omega + · simpa only [hI,successor] using he + +inductive Runs (M : Λ → Instr R Λ) (B : ℕ) : Option Λ → Env R → Env R → ℕ → Prop + | done (E) : Runs M B none E E 0 + | step (l E next F G n) (hB : SizeBound E B) (h : Effect (M l) E next F) + (rest : Runs M B next F G n) : Runs M B (some l) E G (n+1) + +theorem runs_compiles (M : Λ → Instr R Λ) (B n : ℕ) (l : Option Λ) (E F : Env R) + (h : Runs M B l E F n) : + ∃ k≤n*(5*(B+1)),MachineCost.run (TM2.step (code M)) k (cfg M l E)=cfg M none F := by + induction h with + | done E => exact ⟨0,by simp,rfl⟩ + | step l E next F G n hB h rest ih => + obtain ⟨i,hi,he⟩:=effect_compiles M l (M l) rfl E F next h B hB + obtain ⟨j,hj,hf⟩:=ih + refine ⟨i+j,?_,?_⟩ + · calc + i+j≤5*(B+1)+n*(5*(B+1)) := Nat.add_le_add hi hj + _=(n+1)*(5*(B+1)) := by ring + · rw [run_add,he,hf] + +theorem compile_exec [Fintype Λ] [Inhabited Λ] (M : Λ → Instr R Λ) (B n : ℕ) (E F : Env R) + (h : Runs M B (some default) E F n) : + Exec (compile M) (encodeEnv E) (encodeEnv F) (n*(5*(B+1))) := + runs_compiles M B n (some default) E F h +end MatchingFPRAS.TreeMachine + +end OAI diff --git a/lean/OAI/Combinatorics/MatchingCount/Machines/TreeEnumeration.lean b/lean/OAI/Combinatorics/MatchingCount/Machines/TreeEnumeration.lean new file mode 100644 index 0000000000000000000000000000000000000000..228faec924634e401fa5f37394c8dc467150f773 --- /dev/null +++ b/lean/OAI/Combinatorics/MatchingCount/Machines/TreeEnumeration.lean @@ -0,0 +1,105 @@ +import Mathlib +import OAI.Combinatorics.MatchingCount.Graphs.TreeGeometry +import OAI.Combinatorics.MatchingCount.Machines.TreeLabelCorrect + +namespace OAI + +namespace MatchingFPRAS.ExecutableSource +open TreeTyped TreeFraction ExecutableBottleneck Enlargement RealGeometry + +attribute [local instance] Transport.prodOrder Transport.sumOrder +local instance (priority := 2000) {A B : Type} [LinearOrder A] [LinearOrder B] : LE (A×B) := Transport.prodOrder.toLE +local instance (priority := 2000) {A B : Type} [LinearOrder A] [LinearOrder B] : LT (A×B) := Transport.prodOrder.toLT +local instance (priority := 2000) {A B : Type} [LinearOrder A] [LinearOrder B] : Preorder (A×B) := Transport.prodOrder.toPreorder +local instance (priority := 2000) {A B : Type} [LinearOrder A] [LinearOrder B] : LE (A⊕B) := Transport.sumOrder.toLE +local instance (priority := 2000) {A B : Type} [LinearOrder A] [LinearOrder B] : LT (A⊕B) := Transport.sumOrder.toLT +local instance (priority := 2000) {A B : Type} [LinearOrder A] [LinearOrder B] : Preorder (A⊕B) := Transport.sumOrder.toPreorder + +lemma pairwise_product {A B : Type} [LinearOrder A] [LinearOrder B] + {as : List A} {bs : List B} (ha : as.Pairwise (· < ·)) (hb : bs.Pairwise (· < ·)) : + (as.product bs).Pairwise (· < ·) := by + apply List.pairwise_flatMap.mpr + constructor + · intro a _ + apply List.pairwise_map.mpr + exact hb.imp (fun h=>Prod.Lex.right _ h) + · apply ha.imp + intro a b hab x hx y hy + obtain ⟨u,hu,rfl⟩:=List.mem_map.mp hx + obtain ⟨v,hv,rfl⟩:=List.mem_map.mp hy + exact Prod.Lex.left _ _ hab + +lemma logicalEdges_pairwise (n : ℕ) : + (logicalEdges (List.range n)).Pairwise (· < ·) := + List.Pairwise.filter _ (pairwise_product (List.pairwise_lt_range) (List.pairwise_lt_range)) +lemma vertices_pairwise (n : ℕ) (fuel : List Bool) : + (vertices (List.range n,fuel)).Pairwise (· < ·) := by + unfold vertices + apply List.pairwise_append.mpr + refine ⟨?_,?_,?_⟩ + · apply List.pairwise_map.mpr + exact (List.pairwise_lt_range (n:=n)).imp (fun h=>Sum.Lex.inl h) + · apply List.pairwise_map.mpr + exact (pairwise_product (logicalEdges_pairwise n) List.pairwise_lt_range).imp + (fun h=>Sum.Lex.inr h) + · intro a ha b hb + obtain ⟨i,hi,rfl⟩:=List.mem_map.mp ha + obtain ⟨e,he,rfl⟩:=List.mem_map.mp hb + exact Sum.Lex.sep _ _ + +lemma logicalRepr_le {n : ℕ} (a b : LogicalEdge (Fin n)) : + logicalRepr a ≤ logicalRepr b ↔ a ≤ b := by + change toLex (logicalRepr a) ≤ toLex (logicalRepr b) ↔ toLex a.val ≤ toLex b.val + simp only [Prod.Lex.le_iff,logicalRepr,ofLex_toLex,Fin.lt_def,Fin.le_def,Fin.val_inj] +lemma vertexRepr_le {n m : ℕ} (a b : Vertex (Fin n) (LogicalEdge (Fin n)) m) : + vertexRepr a ≤ vertexRepr b ↔ a ≤ b := by + cases a with + | inl a => cases b with + | inl b => + change toLex (Sum.inl a.val : ℕ⊕RawReal) ≤ toLex (Sum.inl b.val : ℕ⊕RawReal) ↔ + toLex (Sum.inl a : Fin n⊕LogicalEdge (Fin n)×Fin m) ≤ toLex (Sum.inl b : Fin n⊕LogicalEdge (Fin n)×Fin m) + simp only [Sum.Lex.inl_le_inl_iff,Fin.le_def] + | inr b => + change toLex (Sum.inl a.val : ℕ⊕RawReal) ≤ toLex (Sum.inr (logicalRepr b.1,b.2.val) : ℕ⊕RawReal) ↔ + toLex (Sum.inl a : Fin n⊕LogicalEdge (Fin n)×Fin m) ≤ toLex (Sum.inr b : Fin n⊕LogicalEdge (Fin n)×Fin m) + simp + | inr a => cases b with + | inl b => + change toLex (Sum.inr (logicalRepr a.1,a.2.val) : ℕ⊕RawReal) ≤ toLex (Sum.inl b.val : ℕ⊕RawReal) ↔ + toLex (Sum.inr a : Fin n⊕LogicalEdge (Fin n)×Fin m) ≤ toLex (Sum.inl b : Fin n⊕LogicalEdge (Fin n)×Fin m) + simp + | inr b => + change toLex (Sum.inr (logicalRepr a.1,a.2.val) : ℕ⊕RawReal) ≤ toLex (Sum.inr (logicalRepr b.1,b.2.val) : ℕ⊕RawReal) ↔ + toLex (Sum.inr a : Fin n⊕LogicalEdge (Fin n)×Fin m) ≤ toLex (Sum.inr b : Fin n⊕LogicalEdge (Fin n)×Fin m) + simp only [Sum.Lex.inr_le_inr_iff] + change toLex (logicalRepr a.1,a.2.val) ≤ toLex (logicalRepr b.1,b.2.val) ↔ toLex a ≤ toLex b + simp only [Prod.Lex.le_iff,ofLex_toLex,Fin.le_def,logicalRepr_injective.eq_iff] + have hlt : logicalRepr a.1 < logicalRepr b.1 ↔ a.1 < b.1 := by + rw [lt_iff_not_ge,lt_iff_not_ge,logicalRepr_le] + rw [hlt] + +lemma vertices_eq_ofFn (n : ℕ) (fuel : List Bool) : + vertices (List.range n,fuel)=List.ofFn (fun i=>vertexRepr + (UnitRefresh.orderedEnum (Vertex (Fin n) (LogicalEdge (Fin n)) (4*fuel.length)) i)) := by + classical + let V:=Vertex (Fin n) (LogicalEdge (Fin n)) (4*fuel.length) + rw [show (fun i=>vertexRepr (UnitRefresh.orderedEnum V i))=vertexRepr ∘ UnitRefresh.orderedEnum V from rfl, + ←List.map_ofFn,UnitRefresh.ofFn_orderedEnum] + have ha : (vertices (List.range n,fuel)).Pairwise (· ≤ ·) := + (vertices_pairwise n fuel).imp (fun h=>le_of_lt h) + have hb : (((Finset.univ : Finset V).sort (· ≤ ·)).map vertexRepr).Pairwise (· ≤ ·) := by + apply List.pairwise_map.mpr + exact (Finset.pairwise_sort _ _).imp (fun h=>(vertexRepr_le _ _).mpr h) + have hn : (vertices (List.range n,fuel)).Nodup := (vertices_pairwise n fuel).imp (fun h=>h.ne) + have hm := (Finset.sort_nodup (Finset.univ : Finset V) (· ≤ ·)).map vertexRepr_injective + have hp : (vertices (List.range n,fuel)).Perm (((Finset.univ : Finset V).sort (· ≤ ·)).map vertexRepr) := by + apply List.perm_of_nodup_nodup_toFinset_eq hn hm + ext v + simp only [List.mem_toFinset,List.mem_map,Finset.mem_sort,Finset.mem_univ,true_and] + constructor + · exact vertices_complete fuel v + · rintro ⟨a,rfl⟩; exact vertexRepr_mem fuel a + apply hp.eq_of_pairwise (fun _ _ _ _ h₁ h₂=>@le_antisymm _ Transport.sumOrder.toPartialOrder _ _ h₁ h₂) ha hb +end MatchingFPRAS.ExecutableSource + +end OAI diff --git a/lean/OAI/Combinatorics/MatchingCount/Machines/TreeFastChoose.lean b/lean/OAI/Combinatorics/MatchingCount/Machines/TreeFastChoose.lean new file mode 100644 index 0000000000000000000000000000000000000000..bc5bdfb46a8a66df54ca871b8bba4f77035c3a3a --- /dev/null +++ b/lean/OAI/Combinatorics/MatchingCount/Machines/TreeFastChoose.lean @@ -0,0 +1,51 @@ +import Mathlib +import OAI.Combinatorics.MatchingCount.Machines.TreeFiniteOps +import OAI.Combinatorics.MatchingCount.Complexity.TreeNumericCosts + +namespace OAI + +namespace MatchingFPRAS.TreeTyped +open Polynomial + +def fastChoose : Realizer (fun x : ℕ×ℕ=>x.1.choose x.2) := + (choose (composition (pair second first) leNat) natChoose (constant 0)).congr (by + intro x + simp only [Function.comp_apply,decide_eq_true_eq] + split_ifs with h + · rfl + · exact (Nat.choose_eq_zero_of_lt (by omega)).symm) +lemma fastChoose_work : WorkBound fastChoose (fun x=>x.1+weight x) := by + obtain ⟨p,hp⟩:=natChoose_numeric_work + let F := composition (pair (second (A:=ℕ) (B:=ℕ)) first) leNat + have hF : PolynomialTime F := polynomial_composition (polynomial_pair polynomial_second polynomial_first) polynomial_leNat + obtain ⟨q,hq⟩:=hF + obtain ⟨r,hr⟩:=polynomial_constant (A:=ℕ×ℕ) (0:ℕ) + refine ⟨p.comp (2*X)+q+r+7*X+18,fun x=>?_⟩ + have hq':=(hq x).trans (polynomial_eval_monotone q (show weight x≤x.1+weight x by omega)) + have hr':=(hr x).trans (polynomial_eval_monotone r (show weight x≤x.1+weight x by omega)) + simp only [Polynomial.eval_add,Polynomial.eval_comp,Polynomial.eval_mul,Polynomial.eval_ofNat,Polynomial.eval_X] + change F.cost x+(if decide (x.2≤x.1) then natChoose.cost x else (constant (A:=ℕ×ℕ) (0:ℕ)).cost x)+ + 7*weight x+18+weight (x.1.choose x.2)≤_ + simp only [decide_eq_true_eq] + by_cases h : x.2≤x.1 + · rw [ite_eq_left h] + have hp':=(hp x).trans (polynomial_eval_monotone p (show x.1+x.2≤2*(x.1+weight x) by omega)) + dsimp only at hq' hr' hp' + omega + · rw [ite_eq_right h,Nat.choose_eq_zero_of_lt (show x.1min x.1 x.2) := + (choose leNat first second).congr (by intro x; simp only [decide_eq_true_eq]; exact (min_def x.1 x.2).symm) +lemma polynomial_minNat : PolynomialTime minNat := + polynomial_congr _ (polynomial_choose polynomial_leNat polynomial_first polynomial_second) + +def dropInit : Realizer (fun x : List A×ℕ=>(min x.2 x.1.length,x.1)) := + pair (composition (pair second (composition first listLength)) minNat) first +lemma polynomial_dropInit : PolynomialTime (dropInit (A:=A)) := by + unfold dropInit + exact polynomial_pair (polynomial_composition (polynomial_pair polynomial_second + (polynomial_composition polynomial_first polynomial_listLength)) polynomial_minNat) polynomial_first + +def dropFast : Realizer (fun x : List A×ℕ=>x.1.drop x.2) := + (composition dropInit (iterateDown (composition second tail))).congr (by + intro x + change countDown dropStep (min x.2 x.1.length) x.1=x.1.drop x.2 + rw [countDown_drop] + by_cases h : x.2≤x.1.length + · rw [min_eq_left h] + · rw [min_eq_right (by omega),List.drop_length,List.drop_eq_nil_of_le (by omega)]) +lemma polynomial_dropFast : PolynomialTime (dropFast (A:=A)) := by + unfold dropFast + apply polynomial_congr + apply polynomial_boundedRepeat polynomial_dropInit + (polynomial_composition polynomial_second polynomial_tail) X X + (fun x _ z=>z.Sublist x.1) + · intro x + simp only [Polynomial.eval_X] + exact (min_le_right _ _).trans ((list_length_le_weight x.1).trans (by rw [weight_prod]; omega)) + · intro x; exact List.Sublist.refl _ + · intro x k hk z hz + exact (List.tail_sublist z).trans hz + · intro x k z hz + simp only [Polynomial.eval_X] + exact (weight_sublist hz).trans (by rw [weight_prod]; omega) + +def getDFast (d : A) : Realizer (fun x : List A×ℕ=>x.1.getD x.2 d) := + (composition dropFast (head d)).congr (by + intro x + simp only [Function.comp_apply, List.headD_eq_head?_getD, List.head?_drop, + List.getD_eq_getElem?_getD]) +lemma polynomial_getDFast (d : A) : PolynomialTime (getDFast d) := + polynomial_congr _ (polynomial_composition polynomial_dropFast (polynomial_head d)) + +end MatchingFPRAS.TreeTyped + +end OAI diff --git a/lean/OAI/Combinatorics/MatchingCount/Machines/TreeFinite.lean b/lean/OAI/Combinatorics/MatchingCount/Machines/TreeFinite.lean new file mode 100644 index 0000000000000000000000000000000000000000..bc926ddd596c2674c7e30a392fd591fcd648fd06 --- /dev/null +++ b/lean/OAI/Combinatorics/MatchingCount/Machines/TreeFinite.lean @@ -0,0 +1,129 @@ +import Mathlib +import OAI.Combinatorics.MatchingCount.Sampling.TreeDPCounts +import OAI.Combinatorics.MatchingCount.Machines.TreeCanonical + +namespace OAI + +namespace MatchingFPRAS.TreeTyped +open Polynomial + +variable {A B C D : Type} [Codec A] [Codec B] [Codec C] [Codec D] + +def Realizer.recode {f : C → D} (F : Realizer f) (i : A → C) (g : A → B) + (hi : ∀ a,encode (i a)=encode a) (ho : ∀ a,encode (f (i a))=encode (g a)) : Realizer g where + program := F.program + cost := fun a=>F.cost (i a) + correct := by + intro a s + have h:=F.correct (i a) s + rw [hi,ho] at h + exact h +lemma polynomial_recode {f : C → D} {F : Realizer f} (i : A → C) (g : A → B) + (hi : ∀ a,encode (i a)=encode a) (ho : ∀ a,encode (f (i a))=encode (g a)) + (hF : PolynomialTime F) : PolynomialTime (F.recode i g hi ho) := by + obtain ⟨p,hp⟩:=hF + refine ⟨p,fun a=>?_⟩ + have h:=hp (i a) + change F.cost (i a)+weight (g a)≤_ + simpa only [weight,hi,ho] using h + +instance finsetCodec [LinearOrder A] : Codec (Finset A) := ⟨fun s=>encode (s.sort (·≤·))⟩ +@[simp] lemma encode_finset [LinearOrder A] (s : Finset A) : encode s=encode (s.sort (·≤·)) := rfl +@[simp] lemma weight_finset [LinearOrder A] (s : Finset A) : weight s=weight (s.sort (·≤·)) := rfl +variable [LinearOrder A] + +def finsetList : Realizer (fun s : Finset A=>s.sort (·≤·)) := + (identity (A:=List A)).recode (fun s : Finset A=>s.sort (·≤·)) (fun s=>s.sort (·≤·)) (fun _=>rfl) (fun _=>rfl) +lemma polynomial_finsetList : PolynomialTime (finsetList (A:=A)) := by + unfold finsetList + exact polynomial_recode _ _ _ _ polynomial_identity + +def listFinset (E : Realizer (fun x : A×A=>decide (x.1=x.2))) + (R : Realizer (fun x : A×A=>decide (x.1≤x.2))) : Realizer (List.toFinset (α:=A)) := + (canonical (·≤·) E R).recode id List.toFinset (fun _=>rfl) (fun as=>by + change encode (as.dedup.insertionSort (·≤·))=encode (as.toFinset.sort (·≤·)) + rw [canonical_eq_sort]) +lemma polynomial_listFinset {E : Realizer (fun x : A×A=>decide (x.1=x.2))} + {R : Realizer (fun x : A×A=>decide (x.1≤x.2))} + (hE : PolynomialTime E) (hR : PolynomialTime R) : PolynomialTime (listFinset E R) := by + unfold listFinset + exact polynomial_recode _ _ _ _ (polynomial_canonical _ hE hR) + +def finsetMember (E : Realizer (fun x : A×A=>decide (x.1=x.2))) : + Realizer (fun x : A×Finset A=>decide (x.1∈x.2)) := + (contains E).recode (fun x=>(x.1,x.2.sort (·≤·))) _ (fun _=>rfl) (fun x=>by simp) +lemma polynomial_finsetMember {E : Realizer (fun x : A×A=>decide (x.1=x.2))} + (hE : PolynomialTime E) : PolynomialTime (finsetMember E) := by + unfold finsetMember + exact polynomial_recode _ _ _ _ (polynomial_contains hE) + +def finsetCard : Realizer (Finset.card (α:=A)) := + (composition finsetList listLength).congr (by intro s; simp) +lemma polynomial_finsetCard : PolynomialTime (finsetCard (A:=A)) := by + unfold finsetCard + exact polynomial_congr _ (polynomial_composition polynomial_finsetList polynomial_listLength) + +def finsetUnion (E : Realizer (fun x : A×A=>decide (x.1=x.2))) + (R : Realizer (fun x : A×A=>decide (x.1≤x.2))) : + Realizer (fun x : Finset A×Finset A=>x.1∪x.2) := + (composition (composition (pair (composition first finsetList) (composition second finsetList)) append) + (listFinset E R)).congr (by intro x; simp) +lemma polynomial_finsetUnion {E : Realizer (fun x : A×A=>decide (x.1=x.2))} + {R : Realizer (fun x : A×A=>decide (x.1≤x.2))} + (hE : PolynomialTime E) (hR : PolynomialTime R) : PolynomialTime (finsetUnion E R) := by + unfold finsetUnion + exact polynomial_congr _ (polynomial_composition + (polynomial_composition (polynomial_pair (polynomial_composition polynomial_first polynomial_finsetList) + (polynomial_composition polynomial_second polynomial_finsetList)) polynomial_append) + (polynomial_listFinset hE hR)) + +def finsetImage [LinearOrder B] {f : A → B} (F : Realizer f) + (E : Realizer (fun x : B×B=>decide (x.1=x.2))) + (R : Realizer (fun x : B×B=>decide (x.1≤x.2))) : + Realizer (Finset.image f) := + (composition (composition finsetList (map F)) (listFinset E R)).congr (by intro s; ext a; simp) +lemma polynomial_finsetImage [LinearOrder B] {f : A → B} {F : Realizer f} + {E : Realizer (fun x : B×B=>decide (x.1=x.2))} + {R : Realizer (fun x : B×B=>decide (x.1≤x.2))} + (hF : PolynomialTime F) (hE : PolynomialTime E) (hR : PolynomialTime R) : PolynomialTime (finsetImage F E R) := by + unfold finsetImage + exact polynomial_congr _ (polynomial_composition + (polynomial_composition polynomial_finsetList (polynomial_map hF)) (polynomial_listFinset hE hR)) + +omit [Codec A] in +lemma sort_filter (p : A → Bool) (s : Finset A) : + (s.sort (·≤·)).filter p=(s.filter fun a=>p a).sort (·≤·) := by + have hh := (List.toFinset_sort (r:=(·≤·)) ((Finset.sort_nodup s (·≤·)).filter p)).mpr + ((Finset.pairwise_sort s (·≤·)).filter p) + simpa only [List.toFinset_filter,Finset.sort_toFinset] using hh.symm + +def finsetFilter {p : A → Bool} (P : Realizer p) : Realizer (fun s : Finset A=>s.filter fun a=>p a) := + (filter P).recode (fun s=>s.sort (·≤·)) _ (fun _=>rfl) (fun s=>by + change encode ((s.sort (·≤·)).filter p)=encode ((s.filter fun a=>p a).sort (·≤·)) + rw [sort_filter]) +lemma polynomial_finsetFilter {p : A → Bool} {P : Realizer p} (hP : PolynomialTime P) : + PolynomialTime (finsetFilter P) := by + unfold finsetFilter + exact polynomial_recode _ _ _ _ (polynomial_filter hP) + +def finsetFilterWith {p : B×A → Bool} (P : Realizer p) : + Realizer (fun x : B×Finset A=>x.2.filter fun a=>p (x.1,a)) := + (filterWith P).recode (fun x=>(x.1,x.2.sort (·≤·))) _ (fun _=>rfl) (fun x=>by + change encode ((x.2.sort (·≤·)).filter fun a=>p (x.1,a))=encode ((x.2.filter fun a=>p (x.1,a)).sort (·≤·)) + rw [sort_filter]) + +omit [LinearOrder A] in +lemma polynomial_filterWith {p : B×A → Bool} {P : Realizer p} (hP : PolynomialTime P) : + PolynomialTime (filterWith P) := by + unfold filterWith + exact polynomial_congr _ (polynomial_composition + (polynomial_composition (polynomial_mapWith (polynomial_pair polynomial_second hP)) + (polynomial_filter polynomial_second)) (polynomial_map polynomial_first)) +lemma polynomial_finsetFilterWith {p : B×A → Bool} {P : Realizer p} (hP : PolynomialTime P) : + PolynomialTime (finsetFilterWith P) := by + unfold finsetFilterWith + exact polynomial_recode _ _ _ _ (polynomial_filterWith hP) + +end MatchingFPRAS.TreeTyped + +end OAI diff --git a/lean/OAI/Combinatorics/MatchingCount/Machines/TreeFiniteCollections.lean b/lean/OAI/Combinatorics/MatchingCount/Machines/TreeFiniteCollections.lean new file mode 100644 index 0000000000000000000000000000000000000000..ab7bae490769ac8bcd6c92dec31d11b3a018967e --- /dev/null +++ b/lean/OAI/Combinatorics/MatchingCount/Machines/TreeFiniteCollections.lean @@ -0,0 +1,97 @@ +import Mathlib +import OAI.Combinatorics.MatchingCount.Machines.TreeFinite + +namespace OAI + +namespace MatchingFPRAS.TreeTyped +open Polynomial + +variable {A B C : Type} [Codec A] [Codec B] [Codec C] +omit [Codec A] [Codec B] [Codec C] in +lemma fold_prepend (as : List (List A)) (bs : List A) : + as.foldl (fun bs a=>a++bs) bs=as.reverse.flatten++bs := by + induction as generalizing bs with + | nil => rfl + | cons a as ih => simp [List.foldl_cons,ih,List.flatten_append,List.append_assoc] +lemma weight_flatten (as : List (List A)) : weight as.flatten≤weight as := by + induction as with + | nil => rfl + | cons a as ih => + simp only [List.flatten_cons,weight_cons] + have h:=weight_append a as.flatten + omega + +def flatten : Realizer (List.flatten (α:=A)) := + (composition (pair reverse (constant ([] : List A))) (fold append)).congr (by + intro as + change as.reverse.foldl (fun bs a=>a++bs) []=as.flatten + rw [fold_prepend,List.reverse_reverse,List.append_nil]) +lemma polynomial_flatten : PolynomialTime (flatten (A:=A)) := by + unfold flatten + apply polynomial_congr + apply polynomial_composition (polynomial_pair polynomial_reverse (polynomial_constant [])) + apply polynomial_fold polynomial_append (2*X+1) + intro as bs pre post he + rw [fold_prepend] + have h1:=weight_append pre.reverse.flatten bs + have h2:=weight_flatten pre.reverse + rw [weight_reverse] at h2 + have h3:=weight_prefix he + simp only [eval_add,eval_mul,eval_ofNat,eval_X,weight_prod] + omega + +def flatMapPoly {f : A → List B} (F : Realizer f) : Realizer (List.flatMap f) := + (composition (map F) flatten).congr (by intro as; rfl) +lemma polynomial_flatMapPoly {f : A → List B} {F : Realizer f} (hF : PolynomialTime F) : + PolynomialTime (flatMapPoly F) := + polynomial_congr _ (polynomial_composition (polynomial_map hF) polynomial_flatten) + +variable [LinearOrder A] +def finsetSingleton : Realizer (fun a : A=>({a} : Finset A)) := + (composition (pair identity (constant ([] : List A))) listCons).recode id + (fun a=>({a} : Finset A)) (fun _=>rfl) (by intro a; simp only [Function.comp_apply,encode_finset,Finset.sort_singleton]; rfl) +lemma polynomial_finsetSingleton : PolynomialTime (finsetSingleton (A:=A)) := by + unfold finsetSingleton + exact polynomial_recode _ _ _ _ (polynomial_composition + (polynomial_pair polynomial_identity (polynomial_constant [])) polynomial_listCons) + +def finsetInsert (E : Realizer (fun x : A×A=>decide (x.1=x.2))) + (R : Realizer (fun x : A×A=>decide (x.1≤x.2))) : Realizer (fun x : A×Finset A=>insert x.1 x.2) := + (composition (pair (composition first finsetSingleton) second) (finsetUnion E R)).congr (by intro x; simp) +lemma polynomial_finsetInsert {E : Realizer (fun x : A×A=>decide (x.1=x.2))} + {R : Realizer (fun x : A×A=>decide (x.1≤x.2))} + (hE : PolynomialTime E) (hR : PolynomialTime R) : PolynomialTime (finsetInsert E R) := + polynomial_congr _ (polynomial_composition + (polynomial_pair (polynomial_composition polynomial_first polynomial_finsetSingleton) polynomial_second) + (polynomial_finsetUnion hE hR)) + +variable [LinearOrder B] +def finsetBiUnion {f : C×A → Finset B} (F : Realizer f) + (E : Realizer (fun x : B×B=>decide (x.1=x.2))) + (R : Realizer (fun x : B×B=>decide (x.1≤x.2))) : + Realizer (fun x : C×Finset A=>x.2.biUnion (fun a=>f (x.1,a))) := + (composition (composition (composition (pair first (composition second finsetList)) + (mapWith (composition F finsetList))) flatten) (listFinset E R)).congr (by + intro x + ext b + simp only [Function.comp_apply,List.mem_toFinset,List.mem_flatten,List.mem_map, + Finset.mem_biUnion,Finset.mem_sort] + constructor + · rintro ⟨bs,⟨a,ha,rfl⟩,hb⟩ + exact ⟨a,ha,(Finset.mem_sort (r:=fun x y : B=>x≤y)).mp hb⟩ + · rintro ⟨a,ha,hb⟩ + exact ⟨(f (x.1,a)).sort (·≤·),⟨a,ha,rfl⟩,(Finset.mem_sort (r:=fun x y : B=>x≤y)).mpr hb⟩) +lemma polynomial_finsetBiUnion {f : C×A → Finset B} {F : Realizer f} + {E : Realizer (fun x : B×B=>decide (x.1=x.2))} + {R : Realizer (fun x : B×B=>decide (x.1≤x.2))} + (hF : PolynomialTime F) (hE : PolynomialTime E) (hR : PolynomialTime R) : + PolynomialTime (finsetBiUnion F E R) := by + unfold finsetBiUnion + apply polynomial_congr + exact polynomial_composition (polynomial_composition (polynomial_composition + (polynomial_pair polynomial_first (polynomial_composition polynomial_second polynomial_finsetList)) + (polynomial_mapWith (polynomial_composition hF polynomial_finsetList))) polynomial_flatten) + (polynomial_listFinset hE hR) +end MatchingFPRAS.TreeTyped + +end OAI diff --git a/lean/OAI/Combinatorics/MatchingCount/Machines/TreeFiniteOps.lean b/lean/OAI/Combinatorics/MatchingCount/Machines/TreeFiniteOps.lean new file mode 100644 index 0000000000000000000000000000000000000000..a5c232779ab112dbb747efb2496d71aa1d29e2ec --- /dev/null +++ b/lean/OAI/Combinatorics/MatchingCount/Machines/TreeFiniteOps.lean @@ -0,0 +1,136 @@ +import Mathlib +import OAI.Combinatorics.MatchingCount.Machines.TreeFinite + +namespace OAI + +namespace MatchingFPRAS.TreeTyped +open Polynomial + +variable {A B C : Type} [Codec A] [Codec B] [Codec C] + +def all : Realizer (fun bs : List Bool=>bs.all id) := + (composition (composition (map boolNot) any) boolNot).congr (by + intro bs + change (!((bs.map Bool.not).any id))=bs.all id + induction bs with + | nil => rfl + | cons b bs ih => cases b <;> simp_all) +lemma polynomial_all : PolynomialTime all := by + unfold all + exact polynomial_congr _ (polynomial_composition + (polynomial_composition (polynomial_map polynomial_boolNot) polynomial_any) polynomial_boolNot) + +def pairEqual [DecidableEq A] [DecidableEq B] + (E : Realizer (fun x : A×A=>decide (x.1=x.2))) + (F : Realizer (fun x : B×B=>decide (x.1=x.2))) : + Realizer (fun x : (A×B)×(A×B)=>decide (x.1=x.2)) := + (composition (pair (composition (pair first.fst second.fst) E) + (composition (pair first.snd second.snd) F)) boolAnd).congr (by + intro x + apply Bool.eq_iff_iff.mpr + simp only [Function.comp_apply,Bool.and_eq_true,decide_eq_true_eq,Prod.ext_iff]) +lemma polynomial_pairEqual [DecidableEq A] [DecidableEq B] + {E : Realizer (fun x : A×A=>decide (x.1=x.2))} + {F : Realizer (fun x : B×B=>decide (x.1=x.2))} + (hE : PolynomialTime E) (hF : PolynomialTime F) : PolynomialTime (pairEqual E F) := by + unfold pairEqual + exact polynomial_congr _ (polynomial_composition (polynomial_pair + (polynomial_composition (polynomial_pair (polynomial_fst polynomial_first) (polynomial_fst polynomial_second)) hE) + (polynomial_composition (polynomial_pair (polynomial_snd polynomial_first) (polynomial_snd polynomial_second)) hF)) polynomial_boolAnd) + +def leNat : Realizer (fun x : ℕ×ℕ=>decide (x.1≤x.2)) := + (composition (composition (pair second first) less) boolNot).congr (by + intro x + apply Bool.eq_iff_iff.mpr + simp only [Function.comp_apply,Bool.not_eq_true',decide_eq_false_iff_not,decide_eq_true_eq,not_lt]) +lemma polynomial_leNat : PolynomialTime leNat := by + unfold leNat + exact polynomial_congr _ (polynomial_composition + (polynomial_composition (polynomial_pair polynomial_second polynomial_first) polynomial_less) polynomial_boolNot) + +variable [LinearOrder A] +def finsetAny {p : B×A → Bool} (P : Realizer p) : + Realizer (fun x : B×Finset A=>decide (∃ a∈x.2,p (x.1,a)=true)) := + (composition (composition (pair first (composition second finsetList)) (mapWith P)) any).congr (by + intro x + apply Bool.eq_iff_iff.mpr + simp only [Function.comp_apply,List.any_map,List.any_eq_true,id_eq,decide_eq_true_eq,Finset.mem_sort]) +lemma polynomial_finsetAny {p : B×A → Bool} {P : Realizer p} (hP : PolynomialTime P) : + PolynomialTime (finsetAny P) := by + unfold finsetAny + exact polynomial_congr _ (polynomial_composition (polynomial_composition + (polynomial_pair polynomial_first (polynomial_composition polynomial_second polynomial_finsetList)) + (polynomial_mapWith hP)) polynomial_any) + +def finsetAll {p : B×A → Bool} (P : Realizer p) : + Realizer (fun x : B×Finset A=>decide (∀ a∈x.2,p (x.1,a)=true)) := + (composition (composition (pair first (composition second finsetList)) (mapWith P)) all).congr (by + intro x + apply Bool.eq_iff_iff.mpr + simp only [Function.comp_apply,List.all_map,List.all_eq_true,id_eq,decide_eq_true_eq,Finset.mem_sort]) +lemma polynomial_finsetAll {p : B×A → Bool} {P : Realizer p} (hP : PolynomialTime P) : + PolynomialTime (finsetAll P) := by + unfold finsetAll + exact polynomial_congr _ (polynomial_composition (polynomial_composition + (polynomial_pair polynomial_first (polynomial_composition polynomial_second polynomial_finsetList)) + (polynomial_mapWith hP)) polynomial_all) + +def finsetSubset (E : Realizer (fun x : A×A=>decide (x.1=x.2))) : + Realizer (fun x : Finset A×Finset A=>decide (x.1⊆x.2)) := + (composition (pair second first) (finsetAll (composition (pair second first) (finsetMember E)))).congr (by + intro x; simp only [Function.comp_apply,decide_eq_true_eq]; rfl) +lemma polynomial_finsetSubset {E : Realizer (fun x : A×A=>decide (x.1=x.2))} + (hE : PolynomialTime E) : PolynomialTime (finsetSubset E) := by + unfold finsetSubset + exact polynomial_congr _ (polynomial_composition (polynomial_pair polynomial_second polynomial_first) + (polynomial_finsetAll (polynomial_composition (polynomial_pair polynomial_second polynomial_first) (polynomial_finsetMember hE)))) + +def finsetEqual (E : Realizer (fun x : A×A=>decide (x.1=x.2))) : + Realizer (fun x : Finset A×Finset A=>decide (x.1=x.2)) := + (composition (pair (finsetSubset E) (composition (pair second first) (finsetSubset E))) boolAnd).congr (by + intro x + apply Bool.eq_iff_iff.mpr + simp only [Function.comp_apply,Bool.and_eq_true,decide_eq_true_eq,Finset.Subset.antisymm_iff]) +lemma polynomial_finsetEqual {E : Realizer (fun x : A×A=>decide (x.1=x.2))} + (hE : PolynomialTime E) : PolynomialTime (finsetEqual E) := by + unfold finsetEqual + exact polynomial_congr _ (polynomial_composition (polynomial_pair (polynomial_finsetSubset hE) + (polynomial_composition (polynomial_pair polynomial_second polynomial_first) (polynomial_finsetSubset hE))) polynomial_boolAnd) + +def finsetSDiff (E : Realizer (fun x : A×A=>decide (x.1=x.2))) : + Realizer (fun x : Finset A×Finset A=>x.1\x.2) := + (composition (pair second first) (finsetFilterWith (composition + (composition (pair second first) (finsetMember E)) boolNot))).congr (by intro x; ext a; simp) +lemma polynomial_finsetSDiff {E : Realizer (fun x : A×A=>decide (x.1=x.2))} + (hE : PolynomialTime E) : PolynomialTime (finsetSDiff E) := by + unfold finsetSDiff + exact polynomial_congr _ (polynomial_composition (polynomial_pair polynomial_second polynomial_first) + (polynomial_finsetFilterWith (polynomial_composition + (polynomial_composition (polynomial_pair polynomial_second polynomial_first) (polynomial_finsetMember hE)) polynomial_boolNot))) + +def finsetInter (E : Realizer (fun x : A×A=>decide (x.1=x.2))) : + Realizer (fun x : Finset A×Finset A=>x.1∩x.2) := + (composition (pair second first) (finsetFilterWith (composition + (pair second first) (finsetMember E)))).congr (by + intro x; ext a + simp only [Function.comp_apply,Finset.mem_filter,decide_eq_true_eq,Finset.mem_inter]) +lemma polynomial_finsetInter {E : Realizer (fun x : A×A=>decide (x.1=x.2))} + (hE : PolynomialTime E) : PolynomialTime (finsetInter E) := by + unfold finsetInter + exact polynomial_congr _ (polynomial_composition (polynomial_pair polynomial_second polynomial_first) + (polynomial_finsetFilterWith (polynomial_composition + (polynomial_pair polynomial_second polynomial_first) (polynomial_finsetMember hE)))) + +def finsetErase (E : Realizer (fun x : A×A=>decide (x.1=x.2))) : + Realizer (fun x : A×Finset A=>x.2.erase x.1) := + (finsetFilterWith (composition E boolNot)).congr (by + intro x; ext a + simp only [Function.comp_apply,Finset.mem_filter,Bool.not_eq_true',decide_eq_false_iff_not,Finset.mem_erase] + tauto) +lemma polynomial_finsetErase {E : Realizer (fun x : A×A=>decide (x.1=x.2))} + (hE : PolynomialTime E) : PolynomialTime (finsetErase E) := by + unfold finsetErase + exact polynomial_congr _ (polynomial_finsetFilterWith (polynomial_composition hE polynomial_boolNot)) +end MatchingFPRAS.TreeTyped + +end OAI diff --git a/lean/OAI/Combinatorics/MatchingCount/Machines/TreeFold.lean b/lean/OAI/Combinatorics/MatchingCount/Machines/TreeFold.lean new file mode 100644 index 0000000000000000000000000000000000000000..1011c82b4158687951b46b62983ca4edf07b9275 --- /dev/null +++ b/lean/OAI/Combinatorics/MatchingCount/Machines/TreeFold.lean @@ -0,0 +1,133 @@ +import Mathlib +import OAI.Combinatorics.MatchingCount.Machines.RegisterControl +import OAI.Combinatorics.MatchingCount.Machines.TreeTyped + +namespace OAI + +namespace MatchingFPRAS.TreeTyped +open TreeData TreeMachine RegisterProc TreeFunction + +variable {A B : Type} [Codec A] [Codec B] +namespace Fold +open RegisterControl (Instr Runs Effect) + +inductive Point where | loop | check | splitHead | pushTail | pushArgs | body | popTail | rebuild | halt + deriving DecidableEq, Inhabited +instance : Fintype Point := ⟨{.loop,.check,.splitHead,.pushTail,.pushArgs,.body,.popTail,.rebuild,.halt},by + intro p; cases p <;> simp⟩ +def code (P : Proc (K Reg)) : Point → RegisterControl.Instr Reg Point + | .loop => .call (TreeFunction.split 1 0 (by decide)) .check + | .check => .branch 1 .halt .splitHead + | .splitHead => .call (TreeFunction.split 3 1 (by decide)) .pushTail + | .pushTail => .call (TreeFunction.cons 1 2 (by decide)) .pushArgs + | .pushArgs => .call (TreeFunction.cons 3 0 (by decide)) .body + | .body => .call P .popTail + | .popTail => .call (TreeFunction.split 1 2 (by decide)) .rebuild + | .rebuild => .call (TreeFunction.cons 1 0 (by decide)) .loop + | .halt => .halt + +def heads (a b r s : Data) : Env Reg := Function.update (env b r s) 3 a +lemma splitHeads (a b r s : Data) : + Exec (TreeFunction.split 3 1 (by decide)) (encodeEnv (env b (.cons a r) s)) (encodeEnv (heads a b r s)) + (2*TreeFunction.size a+5) := by + have hh := split_exec (env b (.cons a r) s) 3 1 (by decide) () a r rfl + have he : putPair (env b (.cons a r) s) 3 1 a r=heads a b r s := by + funext i; fin_cases i <;> simp [heads,putPair,env] + rw [he] at hh + convert hh using 1 + all_goals try rfl + simp [TreeFunction.size,env,TreeData.encode] + omega +lemma pushTail (a b r s : Data) : + Exec (TreeFunction.cons 1 2 (by decide)) (encodeEnv (heads a b r s)) (encodeEnv (heads a b .nil (.cons r s))) + (2*TreeFunction.size r+3) := by + have hh := cons_exec (heads a b r s) 1 2 (by decide) () + have he : putPair (heads a b r s) 1 2 .nil (.cons (heads a b r s 1) (heads a b r s 2))= + heads a b .nil (.cons r s) := by + funext i; fin_cases i <;> simp [heads,putPair,env] + rw [he] at hh + exact hh +lemma pushArgs (a b r s : Data) : + Exec (TreeFunction.cons 3 0 (by decide)) (encodeEnv (heads a b .nil (.cons r s))) + (encodeEnv (env (.cons a b) .nil (.cons r s))) (2*TreeFunction.size a+3) := by + have hh := cons_exec (heads a b .nil (.cons r s)) 3 0 (by decide) () + have he : putPair (heads a b .nil (.cons r s)) 3 0 .nil + (.cons (heads a b .nil (.cons r s) 3) (heads a b .nil (.cons r s) 0))= + env (.cons a b) .nil (.cons r s) := by + funext i; fin_cases i <;> simp [heads,putPair,env] + rw [he] at hh + exact hh + +def cost (f : A×B → B) (t : A×B → ℕ) : List A → B → ℕ + | [],_ => 10 + | a::as,b => t (a,b)+6*TreeFunction.size (encode a)+8*TreeFunction.size (encode as)+34+cost f t as (f (a,b)) + +lemma runs {f : A×B → B} (F : Realizer f) (as : List A) (b : B) (s : Data) : + Runs (code F.program) (some Point.loop) (env (encode (as,b)) .nil s) + (env (encode (as.foldl (fun b a=>f (a,b)) b)) .nil s) (cost f F.cost as b) := by + induction as generalizing b with + | nil => + have hh : Runs (code F.program) (some Point.halt) (env (encode b) .nil s) (env (encode b) .nil s) 1 := + Runs.step _ _ _ _ _ 0 1 (Effect.halt _) (Runs.done _) + have hc : Runs (code F.program) (some Point.check) (env (encode b) .nil s) (env (encode b) .nil s) 2 := + Runs.step _ _ _ _ _ 1 1 (Effect.nilBranch _ 1 _ _ rfl) hh + have hs:=split10 .nil (encode b) .nil s + have hs' : Exec (TreeFunction.split 1 0 (by decide)) (encodeEnv (env (encode (([] : List A),b)) .nil s)) + (encodeEnv (env (encode b) .nil s)) 7 := by simpa [size_nil,encode_prod,encode_list_nil] using hs + exact Runs.step _ _ _ _ _ 2 8 (Effect.call _ _ _ _ 7 hs') hc + | cons a as ih => + let z:=as.foldl (fun b a=>f (a,b)) (f (a,b)) + let sa:=TreeFunction.size (encode a) + let sr:=TreeFunction.size (encode as) + let rest:=cost f F.cost as (f (a,b)) + have hr := ih (f (a,b)) + have h1:=cons10 (encode (f (a,b))) (encode as) s + have hreb : Runs (code F.program) (some Point.rebuild) (env (encode (f (a,b))) (encode as) s) + (env (encode z) .nil s) ((2*sr+4)+rest) := + Runs.step _ _ _ _ _ _ _ (Effect.call _ _ _ _ _ h1) hr + have h2 := (split12 (encode (f (a,b))) .nil (encode as) s).mono + (show TreeFunction.size Data.nil+2*TreeFunction.size (encode as)+4 ≤ 2*sr+5 by + change 1+2*sr+4 ≤ 2*sr+5 + omega) + have hpop : Runs (code F.program) (some Point.popTail) (env (encode (f (a,b))) .nil (.cons (encode as) s)) + (env (encode z) .nil s) ((2*sr+6)+((2*sr+4)+rest)) := + Runs.step _ _ _ _ _ _ _ (Effect.call _ _ _ _ _ h2) hreb + have h3:=F.correct (a,b) (.cons (encode as) s) + have hbody : Runs (code F.program) (some Point.body) (env (encode (a,b)) .nil (.cons (encode as) s)) + (env (encode z) .nil s) ((F.cost (a,b)+1)+((2*sr+6)+((2*sr+4)+rest))) := + Runs.step _ _ _ _ _ _ _ (Effect.call _ _ _ _ _ h3) hpop + have h4:=pushArgs (encode a) (encode b) (encode as) s + have ha : Runs (code F.program) (some Point.pushArgs) (heads (encode a) (encode b) .nil (.cons (encode as) s)) + (env (encode z) .nil s) ((2*sa+4)+((F.cost (a,b)+1)+((2*sr+6)+((2*sr+4)+rest)))) := + Runs.step _ _ _ _ _ _ _ (Effect.call _ _ _ _ _ h4) hbody + have h5:=pushTail (encode a) (encode b) (encode as) s + have ht : Runs (code F.program) (some Point.pushTail) (heads (encode a) (encode b) (encode as) s) + (env (encode z) .nil s) ((2*sr+4)+((2*sa+4)+((F.cost (a,b)+1)+((2*sr+6)+((2*sr+4)+rest))))) := + Runs.step _ _ _ _ _ _ _ (Effect.call _ _ _ _ _ h5) ha + have h6:=splitHeads (encode a) (encode b) (encode as) s + have hsh : Runs (code F.program) (some Point.splitHead) (env (encode b) (encode (a::as)) s) + (env (encode z) .nil s) ((2*sa+6)+((2*sr+4)+((2*sa+4)+((F.cost (a,b)+1)+((2*sr+6)+((2*sr+4)+rest)))))) := + Runs.step _ _ _ _ _ _ _ (Effect.call _ _ _ _ _ h6) ht + have hc : Runs (code F.program) (some Point.check) (env (encode b) (encode (a::as)) s) + (env (encode z) .nil s) (1+((2*sa+6)+((2*sr+4)+((2*sa+4)+((F.cost (a,b)+1)+((2*sr+6)+((2*sr+4)+rest))))))) := + Runs.step _ _ _ _ _ _ 1 (Effect.consBranch _ 1 _ _ (encode a) (encode as) rfl) hsh + have h7 := (split10 (encode (a::as)) (encode b) .nil s).mono + (show TreeFunction.size Data.nil+2*TreeFunction.size (encode (a::as))+4 ≤ 2*TreeFunction.size (encode (a::as))+5 by + change 1+2*TreeFunction.size (encode (a::as))+4 ≤ 2*TreeFunction.size (encode (a::as))+5 + omega) + have hl : Runs (code F.program) (some Point.loop) (env (encode (a::as,b)) .nil s) + (env (encode z) .nil s) ((2*TreeFunction.size (encode (a::as))+6)+(1+((2*sa+6)+((2*sr+4)+((2*sa+4)+((F.cost (a,b)+1)+((2*sr+6)+((2*sr+4)+rest)))))))) := + Runs.step _ _ _ _ _ _ _ (Effect.call _ _ _ _ _ h7) hc + convert hl using 1 + all_goals try rfl + simp only [cost,encode_list_cons,size_cons,sa,sr,rest] + ring +end Fold + +def fold {f : A×B → B} (F : Realizer f) : Realizer (fun ab : List A×B=>ab.1.foldl (fun b a=>f (a,b)) ab.2) where + program := RegisterControl.compile (Fold.code F.program) + cost := fun ab=>Fold.cost f F.cost ab.1 ab.2 + correct := fun ab s=>RegisterControl.compile_exec _ _ _ _ (Fold.runs F ab.1 ab.2 s) +end MatchingFPRAS.TreeTyped + +end OAI diff --git a/lean/OAI/Combinatorics/MatchingCount/Machines/TreeFrame.lean b/lean/OAI/Combinatorics/MatchingCount/Machines/TreeFrame.lean new file mode 100644 index 0000000000000000000000000000000000000000..1b3619c0c4222da1c54381fdf39c1c866ef29d96 --- /dev/null +++ b/lean/OAI/Combinatorics/MatchingCount/Machines/TreeFrame.lean @@ -0,0 +1,84 @@ +import Mathlib +import OAI.Combinatorics.MatchingCount.Machines.TreeMachine + +namespace OAI + +namespace MatchingFPRAS.RegisterProc +open Turing + +variable {J K : Type} [DecidableEq J] [DecidableEq K] +def map (P : Proc J) (e : J ↪ K) : Proc K := + ⟨P.Label,StackLens.program e (StackLens.Lens.identity Store) P.code⟩ +lemma exec_map (P : Proc J) (e : J ↪ K) (S T : Stack J) (F : Stack K) (n : ℕ) + (h : Exec P S T n) : + Exec (map P e) (StackEmbedding.extend e S F) (StackEmbedding.extend e T F) n := by + obtain ⟨k,hk,he⟩:=h + refine ⟨k,hk,?_⟩ + have hh := StackLens.run_cfg e (StackLens.Lens.identity Store) P.code F none k + ⟨some default,none,S⟩ + rw [he] at hh + exact hh +end MatchingFPRAS.RegisterProc + +namespace MatchingFPRAS.TreeMachine +open TreeData RegisterProc + +variable {R S : Type} [DecidableEq R] [DecidableEq S] +def mapStack (e : R ↪ S) : K R ↪ K S := e.sumMap (Function.Embedding.refl _) +noncomputable def extendEnv (e : R ↪ S) (E : Env R) (F : Env S) : Env S := + by + classical + exact fun s=>if h : ∃ r,e r=s then E h.choose else F s +omit [DecidableEq R] [DecidableEq S] in +lemma extend_on [DecidableEq R] [DecidableEq S] (e : R ↪ S) (E : Env R) (F : Env S) (r : R) : + extendEnv e E F (e r)=E r := by + classical + have h : ∃ a,e a=e r:=⟨r,rfl⟩ + simp only [extendEnv,dite_eq_left h] + rw [e.injective h.choose_spec] +omit [DecidableEq R] [DecidableEq S] in +lemma extend_off [DecidableEq R] [DecidableEq S] (e : R ↪ S) (E : Env R) (F : Env S) (s : S) + (h : ¬∃ r,e r=s) : extendEnv e E F s=F s := by + classical + simp only [extendEnv,dite_eq_right h] +lemma encode_extend (e : R ↪ S) (E : Env R) (F : Env S) : + StackEmbedding.extend (mapStack e) (encodeEnv E) (encodeEnv F)=encodeEnv (extendEnv e E F) := by + funext k + cases k with + | inr k => + have hh:=StackEmbedding.extend_on (mapStack e) (encodeEnv E) (encodeEnv F) (.inr k) + simpa [mapStack,encodeEnv] using hh + | inl k => + by_cases h : ∃ r,e r=k + · obtain ⟨r,rfl⟩:=h + rw [show Sum.inl (e r)=mapStack e (.inl r) from rfl, + StackEmbedding.extend_on] + change encode (E r)=encode (extendEnv e E F (e r)) + rw [extend_on] + · have ho : ¬∃ r,mapStack e r=Sum.inl k := by + rintro ⟨r,hr⟩ + cases r with + | inl r => exact h ⟨r,Sum.inl.inj hr⟩ + | inr r => cases hr + rw [StackEmbedding.extend_off _ _ _ _ ho] + simp only [encodeEnv,extend_off e E F k h] + +def mapProc (P : Proc (K R)) (e : R ↪ S) : Proc (K S) := RegisterProc.map P (mapStack e) +lemma mapProc_exec (P : Proc (K R)) (e : R ↪ S) (E E' : Env R) (F : Env S) (n : ℕ) + (h : Exec P (encodeEnv E) (encodeEnv E') n) : + Exec (mapProc P e) (encodeEnv (extendEnv e E F)) (encodeEnv (extendEnv e E' F)) n := by + have hh:=RegisterProc.exec_map P (mapStack e) (encodeEnv E) (encodeEnv E') (encodeEnv F) n h + simpa only [encode_extend,mapProc] using hh +lemma extend_same (e : R ↪ S) (F : Env S) : extendEnv e (F ∘ e) F=F := by + funext k + by_cases h : ∃ r,e r=k + · obtain ⟨r,rfl⟩:=h + exact extend_on e (F ∘ e) F r + · exact extend_off e (F ∘ e) F k h +lemma mapProc_exec_on (P : Proc (K R)) (e : R ↪ S) (E' : Env R) (F : Env S) (n : ℕ) + (h : Exec P (encodeEnv (F ∘ e)) (encodeEnv E') n) : + Exec (mapProc P e) (encodeEnv F) (encodeEnv (extendEnv e E' F)) n := by + simpa only [extend_same] using mapProc_exec P e (F ∘ e) E' F n h +end MatchingFPRAS.TreeMachine + +end OAI diff --git a/lean/OAI/Combinatorics/MatchingCount/Machines/TreeFunction.lean b/lean/OAI/Combinatorics/MatchingCount/Machines/TreeFunction.lean new file mode 100644 index 0000000000000000000000000000000000000000..8be7313bb4d211c71e6700e364aa08fe40de60bc --- /dev/null +++ b/lean/OAI/Combinatorics/MatchingCount/Machines/TreeFunction.lean @@ -0,0 +1,95 @@ +import Mathlib +import OAI.Combinatorics.MatchingCount.Machines.TreeMachine + +namespace OAI + +namespace MatchingFPRAS.TreeFunction +open TreeData TreeMachine RegisterProc + +abbrev Reg := Fin 10 +def env (x y s : Data) : Env Reg := fun i=>if i=0 then x else if i=1 then y else if i=2 then s else .nil +@[simp] lemma env0 (x y s : Data) : env x y s 0=x := rfl +@[simp] lemma env1 (x y s : Data) : env x y s 1=y := rfl +@[simp] lemma env2 (x y s : Data) : env x y s 2=s := rfl +def size (x : Data) : ℕ := (TreeData.encode x).length +@[simp] lemma size_nil : size .nil=1 := rfl +@[simp] lemma size_cons (x y : Data) : size (.cons x y)=size x+size y+1 := by + simp [size,TreeData.encode] + +def Realizes (P : Proc (K Reg)) (f : Data → Data) (t : Data → ℕ) : Prop := + ∀ x s,Exec P (encodeEnv (env x .nil s)) (encodeEnv (env (f x) .nil s)) (t x) + +lemma env_ext {x y s a b c : Data} (hx : x=a) (hy : y=b) (hs : s=c) : env x y s=env a b c := by + rw [hx,hy,hs] +lemma env_update0 (x y s a : Data) : Function.update (env x y s) 0 a=env a y s := by + funext i; fin_cases i <;> simp [env] +lemma env_update1 (x y s a : Data) : Function.update (env x y s) 1 a=env x a s := by + funext i; fin_cases i <;> simp [env] +lemma env_update2 (x y s a : Data) : Function.update (env x y s) 2 a=env x y a := by + funext i; fin_cases i <;> simp [env] +attribute [simp] env_update0 env_update1 env_update2 + +def clear (i : Reg) : Proc (K Reg) := procedure (.nil i ()) +def copy (i j : Reg) (h : i≠j) : Proc (K Reg) := procedure (.copy i j h ()) +def cons (i j : Reg) (h : i≠j) : Proc (K Reg) := procedure (.cons i j h ()) +def split (i j : Reg) (h : i≠j) : Proc (K Reg) := procedure (.split i j h ()) + +lemma copy01 (x y s : Data) : + Exec (copy 0 1 (by decide)) (encodeEnv (env x y s)) (encodeEnv (env x x s)) (size y+3*size x+4) := by + simpa only [putPair,env_update0,env_update1,env0,env1,size,copy] using copy_exec (env x y s) 0 1 (by decide) () +lemma copy10 (x y s : Data) : + Exec (copy 1 0 (by decide)) (encodeEnv (env x y s)) (encodeEnv (env y y s)) (size x+3*size y+4) := by + simpa only [putPair,env_update0,env_update1,env0,env1,size,copy] using copy_exec (env x y s) 1 0 (by decide) () +lemma cons12 (x y s : Data) : + Exec (cons 1 2 (by decide)) (encodeEnv (env x y s)) (encodeEnv (env x .nil (.cons y s))) (2*size y+3) := by + simpa only [putPair,env_update1,env_update2,env1,env2,size,cons] using cons_exec (env x y s) 1 2 (by decide) () +lemma cons02 (x y s : Data) : + Exec (cons 0 2 (by decide)) (encodeEnv (env x y s)) (encodeEnv (env .nil y (.cons x s))) (2*size x+3) := by + simpa only [putPair,env_update0,env_update2,env0,env2,size,cons] using cons_exec (env x y s) 0 2 (by decide) () +lemma cons10 (x y s : Data) : + Exec (cons 1 0 (by decide)) (encodeEnv (env x y s)) (encodeEnv (env (.cons y x) .nil s)) (2*size y+3) := by + simpa only [putPair,env_update0,env_update1,env0,env1,size,cons] using cons_exec (env x y s) 1 0 (by decide) () +lemma split12 (x y a s : Data) : + Exec (split 1 2 (by decide)) (encodeEnv (env x y (.cons a s))) (encodeEnv (env x a s)) (size y+2*size a+4) := by + simpa only [putPair,env_update1,env_update2,env1,env2,size,split] using split_exec (env x y (.cons a s)) 1 2 (by decide) () a s rfl +lemma split10 (x y z s : Data) : + Exec (split 1 0 (by decide)) (encodeEnv (env (.cons x y) z s)) (encodeEnv (env y x s)) (size z+2*size x+4) := by + simpa only [putPair,env_update0,env_update1,env0,env1,size,split] using split_exec (env (.cons x y) z s) 1 0 (by decide) () x y rfl +lemma clear0 (x y s : Data) : + Exec (clear 0) (encodeEnv (env x y s)) (encodeEnv (env .nil y s)) (size x+2) := by + simpa only [env_update0,env0,size,clear] using nil_exec (env x y s) 0 () +lemma clear1 (x y s : Data) : + Exec (clear 1) (encodeEnv (env x y s)) (encodeEnv (env x .nil s)) (size y+2) := by + simpa only [env_update1,env1,size,clear] using nil_exec (env x y s) 1 () + +lemma realizes_seq {P Q : Proc (K Reg)} {f g : Data → Data} {t u : Data → ℕ} + (hP : Realizes P f t) (hQ : Realizes Q g u) : + Realizes (seq P Q) (g ∘ f) (fun x=>t x+u (f x)) := fun x s=>(hP x s).seq (hQ (f x) s) + +def pair (P Q : Proc (K Reg)) : Proc (K Reg) := + seq (copy 0 1 (by decide)) (seq (cons 1 2 (by decide)) (seq P + (seq (split 1 2 (by decide)) (seq (cons 0 2 (by decide)) + (seq (copy 1 0 (by decide)) (seq (clear 1) (seq Q + (seq (split 1 2 (by decide)) (cons 1 0 (by decide)))))))))) + +lemma realizes_pair {P Q : Proc (K Reg)} {f g : Data → Data} {t u : Data → ℕ} + (hP : Realizes P f t) (hQ : Realizes Q g u) : + Realizes (pair P Q) (fun x=>.cons (f x) (g x)) + (fun x=>t x+u x+11*size x+6*size (f x)+31) := by + intro x s + have h1:=copy01 x .nil s + have h2:=cons12 x x s + have h3:=hP x (.cons x s) + have h4:=split12 (f x) .nil x s + have h5:=cons02 (f x) x s + have h6:=copy10 .nil x (.cons (f x) s) + have h7:=clear1 x x (.cons (f x) s) + have h8:=hQ x (.cons (f x) s) + have h9:=split12 (g x) .nil (f x) s + have h10:=cons10 (g x) (f x) s + apply (h1.seq (h2.seq (h3.seq (h4.seq (h5.seq (h6.seq (h7.seq (h8.seq (h9.seq h10))))))))).mono + simp only [size_nil] + omega +end MatchingFPRAS.TreeFunction + +end OAI diff --git a/lean/OAI/Combinatorics/MatchingCount/Machines/TreeGuideTables.lean b/lean/OAI/Combinatorics/MatchingCount/Machines/TreeGuideTables.lean new file mode 100644 index 0000000000000000000000000000000000000000..7622872f93e735201a78527b99f0bcd2d41a7d9f --- /dev/null +++ b/lean/OAI/Combinatorics/MatchingCount/Machines/TreeGuideTables.lean @@ -0,0 +1,104 @@ +import Mathlib +import OAI.Combinatorics.MatchingCount.Machines.TreeNumberedSets +import OAI.Combinatorics.MatchingCount.Algorithm.TreeTierWeights + +namespace OAI + +namespace MatchingFPRAS.NumericLadder +open TreeTyped TreeFraction ExecutableLadder Polynomial TreeTyped.Numbered Replica.Ladder + +def slotUniverse (x : TierData) : Finset ℕ := (slots x).toFinset +def slotUniverseRealizer : Realizer slotUniverse := composition slotsRealizer (listFinset natEqual leNat) +lemma polynomial_slotUniverse : PolynomialTime slotUniverseRealizer := + polynomial_composition polynomial_slots (polynomial_listFinset polynomial_natEqual polynomial_leNat) + +def guideTest (x : (TierData×ℕ)×ℕ) : Bool := + decide (x.1.2/x.1.1.2.1.lengthx.1.1.2.1.length) := composition first.fst.snd.fst listLength + let r : Realizer (fun x : (TierData×ℕ)×ℕ=>x.1.2/x.1.1.2.1.length) := composition (pair first.snd q) quotient + exact (composition (pair (composition (pair r (composition first.fst.fst.snd listLength)) less) + (composition (pair (composition (pair second q) quotient) (composition r successor)) natEqual)) boolAnd).congr + (by intro x; simp [guideTest]) +lemma polynomial_guideTest : PolynomialTime guideTestRealizer := by + unfold guideTestRealizer Realizer.fst Realizer.snd + dsimp only + apply polynomial_congr + have := polynomial_quotient + have := polynomial_successor + tree_cost + +def guideSet (x : TierData×ℕ) : Finset ℕ := (slotUniverse x.1).filter (fun j=>guideTest (x,j)) +def guideSetRealizer : Realizer guideSet := composition (pair identity (composition first slotUniverseRealizer)) + (finsetFilterWith guideTestRealizer) +lemma polynomial_guideSet : PolynomialTime guideSetRealizer := by + unfold guideSetRealizer + exact polynomial_composition (TreeTyped.polynomial_pair polynomial_identity + (polynomial_composition polynomial_first polynomial_slotUniverse)) (polynomial_finsetFilterWith polynomial_guideTest) + +def guideRows (x : TierData) : List (List ℕ) := (slots x).map (fun i=>(guideSet (x,i)).sort (·≤·)) +def guideRowsRealizer : Realizer guideRows := composition (pair identity slotsRealizer) + (mapWith (composition guideSetRealizer finsetList)) +lemma polynomial_guideRows : PolynomialTime guideRowsRealizer := by + unfold guideRowsRealizer + exact polynomial_composition (TreeTyped.polynomial_pair polynomial_identity polynomial_slots) + (polynomial_mapWith (polynomial_composition polynomial_guideSet polynomial_finsetList)) + +lemma slotUniverse_source (n : ℕ) (ft fq : List Bool) (ws : List Fraction) : + slotUniverse ((n,ft),(fq,ws))=Numbered.set (Finset.univ : Finset (Slot ft.length fq.length)) := by + ext j + simp only [slotUniverse,slots,slotCount,List.toFinset_range,Finset.mem_range,Numbered.set,Finset.mem_map, + Finset.mem_univ,true_and,Numbered.embedding] + constructor + · intro h + let z : Fin (Fintype.card (Slot ft.length fq.length)) := ⟨j,by simpa only [slot_card] using h⟩ + exact ⟨UnitRefresh.orderedEnum _ z,index_enum z⟩ + · rintro ⟨z,rfl⟩ + change index z<(ft.length+1)*fq.length + have h := ((UnitRefresh.orderedEnum (Slot ft.length fq.length)).symm z).isLt + simpa only [index,slot_card] using h + +lemma mem_guides_rank {T q : ℕ} (i j : Slot T q) : + j∈guides i ↔ rank i + (Numbered.set (guides (UnitRefresh.orderedEnum _ i))).sort (·≤·)) := by + rw [guideRows,slots,slotCount,range_slot_indices,List.map_ofFn] + apply congrArg List.ofFn + funext i + exact congrArg (fun values=>values.sort (·≤·)) + (guideSet_source n ft fq ws (UnitRefresh.orderedEnum _ i)) + +end MatchingFPRAS.NumericLadder + +end OAI diff --git a/lean/OAI/Combinatorics/MatchingCount/Machines/TreeHistorySize.lean b/lean/OAI/Combinatorics/MatchingCount/Machines/TreeHistorySize.lean new file mode 100644 index 0000000000000000000000000000000000000000..f9c394f1f44248a378c58672e721f6a003d419e8 --- /dev/null +++ b/lean/OAI/Combinatorics/MatchingCount/Machines/TreeHistorySize.lean @@ -0,0 +1,59 @@ +import Mathlib +import OAI.Combinatorics.MatchingCount.Algorithm.EmpiricalDenom +import OAI.Combinatorics.MatchingCount.Algorithm.TreeScalingCorrect + +namespace OAI + +namespace MatchingFPRAS.ExecutableSource +open TreeTyped TreeFraction ExecutableScaling BitArithmetic + +lemma fraction_weight_of_bound {B : ℕ} {q : ℚ} (h : FractionBound B (q:ℝ)) : + TreeTyped.weight (TreeFraction.repr q)≤8*B.size+3 := by + obtain ⟨hn,hd⟩:=h.num_den + have hn':=Nat.size_le_size hn + have hd':=Nat.size_le_size hd + have h₁:=weight_nat_le q.num.natAbs + have h₂:=weight_nat_le q.den + simp only [TreeFraction.repr,weight_prod] + omega + +lemma vectorRep_weight_of_bound {n B : ℕ} (s : Fin n→ℚ) + (h : ∀ i,FractionBound B (s i:ℝ)) : + TreeTyped.weight (vectorRep s)≤n*(4*n.size+8*B.size+6)+1 := by + have hb : ∀ i : Fin n,TreeTyped.weight (i.val,TreeFraction.repr (s i))≤4*n.size+8*B.size+5 := by + intro i + have h₁:=fraction_weight_of_bound (h i) + have h₂:=weight_nat_le i.val + have h₃:=Nat.size_le_size i.isLt.le + simp only [weight_prod] + omega + unfold vectorRep + rw [List.ofFn_eq_map] + have hh:=weight_map_bound (as:=List.finRange n) + (f:=fun i : Fin n=>(i.val,TreeFraction.repr (s i))) (N:=4*n.size+8*B.size+5) + (fun i _=>hb i) + simpa only [List.length_finRange] using hh + +lemma history_vector_weight {G : GraphInput} [Nontrivial (Fin G.n)] + (p : Trial.Parameters G) (j : ℕ) (hj : j≤p.K) (x : (FiniteTrial.layers p j hj).Ω) : + TreeTyped.weight (vectorRep ((FiniteTrial.layers p j hj).state x).scale)≤ + G.n*(4*G.n.size+8*((G.n+1).size+j*(G.n+1)* + (19+(p.D+1).size+2*(p.S.size+ + Fintype.card (Enlargement.SourceVertex (Fin G.n) p.K)*(G.n+1).size+1))+1)+6)+1 := by + have h:=vectorRep_weight_of_bound ((FiniteTrial.layers p j hj).state x).scale + (FiniteTrial.layers_scale_bits p j hj x) + have h₁:=size_scaleBound p j + have h₂:=size_matrixBound p + have h₃:=size_empiricalBound p + have hb : (p.scaleBound j).size≤ + (G.n+1).size+j*(G.n+1)*(19+(p.D+1).size+2*(p.S.size+ + Fintype.card (Enlargement.SourceVertex (Fin G.n) p.K)*(G.n+1).size+1))+1 := by + calc + _ ≤ (G.n+1).size+j*(G.n+1)*p.matrixBound.size+1 := h₁ + _ ≤ (G.n+1).size+j*(G.n+1)*(19+(p.D+1).size+2*p.empiricalBound.size)+1 := by gcongr + _ ≤ _ := by gcongr + exact h.trans (by gcongr) + +end MatchingFPRAS.ExecutableSource + +end OAI diff --git a/lean/OAI/Combinatorics/MatchingCount/Machines/TreeIndex.lean b/lean/OAI/Combinatorics/MatchingCount/Machines/TreeIndex.lean new file mode 100644 index 0000000000000000000000000000000000000000..a1d957b377c0fc163a7378abe3a778f6d183f780 --- /dev/null +++ b/lean/OAI/Combinatorics/MatchingCount/Machines/TreeIndex.lean @@ -0,0 +1,88 @@ +import Mathlib +import OAI.Combinatorics.MatchingCount.Complexity.TreeCostMeasure +import OAI.Combinatorics.MatchingCount.Machines.TreeSum + +namespace OAI + +namespace MatchingFPRAS.TreeTyped +open Polynomial + +variable {A : Type} [Codec A] [DecidableEq A] [BEq A] [LawfulBEq A] + +def indexStep (x : A×(A×ℕ)) : A×ℕ := (x.2.1,if x.2.1=x.1 then 0 else x.2.2+1) +def indexStepRealizer (E : Realizer (fun x : A×A=>decide (x.1=x.2))) : Realizer (indexStep (A:=A)) := + (pair second.fst (choose (composition (pair second.fst first) E) (constant 0) + (composition second.snd successor))).congr (fun x=>by simp only [indexStep,Function.comp_apply,decide_eq_true_eq,Nat.succ_eq_add_one]) +omit [BEq A] [LawfulBEq A] in +lemma polynomial_indexStep [BEq A] [LawfulBEq A] {E : Realizer (fun x : A×A=>decide (x.1=x.2))} + (hE : PolynomialTime E) : PolynomialTime (indexStepRealizer E) := by + unfold indexStepRealizer + apply polynomial_congr + exact polynomial_pair (polynomial_fst polynomial_second) + (polynomial_choose (polynomial_composition (polynomial_pair (polynomial_fst polynomial_second) polynomial_first) hE) + (polynomial_constant 0) (polynomial_composition (polynomial_snd polynomial_second) polynomial_successor)) +omit [Codec A] [DecidableEq A] [BEq A] [LawfulBEq A] in +lemma indexStep_fold_first [Codec A] [DecidableEq A] [BEq A] [LawfulBEq A] + (xs : List A) (a : A) (i : ℕ) : + (xs.foldl (fun z x=>indexStep (x,z)) (a,i)).1=a := by + induction xs generalizing i with + | nil=>rfl + | cons x xs ih=>exact ih _ +omit [Codec A] [DecidableEq A] [BEq A] [LawfulBEq A] in +lemma indexStep_fold_le [Codec A] [DecidableEq A] [BEq A] [LawfulBEq A] + (xs : List A) (a : A) (i : ℕ) : + (xs.foldl (fun z x=>indexStep (x,z)) (a,i)).2 ≤ i+xs.length := by + induction xs generalizing i with + | nil=>simp + | cons x xs ih=> + have h:=ih (if a=x then 0 else i+1) + change (xs.foldl _ (a,if a=x then 0 else i+1)).2 ≤ _ + have hb : (if a=x then 0 else i+1) ≤ i+1 := by split_ifs <;> omega + simpa only [List.length_cons] using h.trans (by omega) +lemma polynomial_indexFold {E : Realizer (fun x : A×A=>decide (x.1=x.2))} + (hE : PolynomialTime E) : PolynomialTime (fold (indexStepRealizer E)) := by + apply polynomial_fold (polynomial_indexStep hE) (10*X+20) + rintro xs ⟨a,i⟩ pre post he + have hp:=(list_length_le_weight pre).trans (weight_prefix he) + have hb:=indexStep_fold_le pre a i + have hi:=Nat.size_le_size hb + have hs:=nat_size_add i pre.length + have hn : pre.length.size ≤ pre.length := Nat.size_le.mpr Nat.lt_two_pow_self + rw [←Prod.eta (pre.foldl _ (a,i)),weight_prod,indexStep_fold_first] + have hw:=weight_nat_le (pre.foldl (fun z x=>indexStep (x,z)) (a,i)).2 + have ha:=weight_pos a + have hn':=size_le_weight i + simp only [eval_add,eval_mul,eval_ofNat,eval_X,weight_prod] + omega + +omit [Codec A] [DecidableEq A] [BEq A] [LawfulBEq A] in +lemma indexStep_fold_reverse [Codec A] [DecidableEq A] [BEq A] [LawfulBEq A] + (xs : List A) (a : A) : + (xs.reverse.foldl (fun z x=>indexStep (x,z)) (a,0)).2=xs.idxOf a := by + rw [List.foldl_reverse] + have h : xs.foldr (fun x z=>indexStep (x,z)) (a,0)=(a,xs.idxOf a) := by + induction xs with + | nil=>simp + | cons x xs ih=> + rw [List.foldr_cons,ih] + simp only [indexStep,List.idxOf_cons] + by_cases he : a=x + · subst x; simp + · simp [he,beq_eq_false_iff_ne.mpr (Ne.symm he)] + rw [h] + +def indexOf (E : Realizer (fun x : A×A=>decide (x.1=x.2))) : + Realizer (fun x : A×List A=>x.2.idxOf x.1) := + (composition (composition (pair (composition second reverse) (pair first (constant 0))) + (fold (indexStepRealizer E))) second).congr (fun x=>indexStep_fold_reverse x.2 x.1) +lemma polynomial_indexOf {E : Realizer (fun x : A×A=>decide (x.1=x.2))} + (hE : PolynomialTime E) : PolynomialTime (indexOf E) := by + unfold indexOf + apply polynomial_congr + exact polynomial_composition (polynomial_composition + (polynomial_pair (polynomial_composition polynomial_second polynomial_reverse) + (polynomial_pair polynomial_first (polynomial_constant 0))) + (polynomial_indexFold hE)) polynomial_second +end MatchingFPRAS.TreeTyped + +end OAI diff --git a/lean/OAI/Combinatorics/MatchingCount/Machines/TreeInitial.lean b/lean/OAI/Combinatorics/MatchingCount/Machines/TreeInitial.lean new file mode 100644 index 0000000000000000000000000000000000000000..b19455767df30e20e4e35a843b976de60780d7d9 --- /dev/null +++ b/lean/OAI/Combinatorics/MatchingCount/Machines/TreeInitial.lean @@ -0,0 +1,81 @@ +import Mathlib +import OAI.Combinatorics.MatchingCount.Algorithm.RationalStart +import OAI.Combinatorics.MatchingCount.Machines.TreeRefreshTables +import OAI.Combinatorics.MatchingCount.Graphs.TreeHeight + +namespace OAI + +namespace MatchingFPRAS.ExecutableSource +open TreeTyped TreeFraction TreeTyped.Numbered ExecutableBottleneck ExecutableHierarchy Enlargement RealGeometry + +def setupHierarchy (x : BagBuildInput) : BagInput := + ((buildClosure x.1,hierarchyFuel (x.1.1.1,x.2)),endpointList (x.1.2,x.1.1.2)) +def setupHierarchyRealizer : Realizer setupHierarchy := (pair + (pair (composition first buildClosureRealizer) + (composition (pair first.fst.fst second) hierarchyFuelRealizer)) + (composition (pair first.snd first.fst.snd) endpointListRealizer)).congr (fun _=>rfl) +lemma polynomial_setupHierarchy : PolynomialTime setupHierarchyRealizer := by + unfold setupHierarchyRealizer + dsimp only [Realizer.fst,Realizer.snd] + apply polynomial_congr + have := polynomial_buildClosure + have := polynomial_hierarchyFuel + have := polynomial_endpointList + tree_cost + +def sourceTables (x : BagBuildInput) : ExecutableRefresh.InitialInput := + refreshTables (setupHierarchy x) +def sourceTablesRealizer : Realizer sourceTables := composition setupHierarchyRealizer refreshTablesRealizer +lemma polynomial_sourceTables : PolynomialTime sourceTablesRealizer := + polynomial_composition polynomial_setupHierarchy polynomial_refreshTables + +def sourceInitial (x : BagBuildInput) : Finset ℕ := + ExecutableRefresh.initial (sourceTables x) +def sourceInitialRealizer : Realizer sourceInitial := composition sourceTablesRealizer ExecutableRefresh.initialRealizer +lemma polynomial_sourceInitial : PolynomialTime sourceInitialRealizer := + polynomial_composition polynomial_sourceTables ExecutableRefresh.polynomial_initial + +attribute [local instance] NumberedHierarchy.labelOrder +attribute [local instance] Transport.sym2Order Transport.bagEdgeOrder Transport.bagEdgeFintype +lemma sourceInitial_valid {n : ℕ} [Nontrivial (Fin n)] (hn : 2≤n) + (w : Fin n→Fin n→ℚ) (hw : ∀ i j,0≤w i j) (K : ℕ) + (hcap : ∀ i j,i≠j → BottleneckAlgorithm.edge w i j≤(4:ℚ)^K) + (hex : Nonempty (Transport.BagPM (RationalSource.bags w K))) : + ∃ M : Transport.BagPM (RationalSource.bags w K), + sourceInitial (((matrixRep w,List.replicate (2*K+2) false),List.range n),List.replicate (2*K) false)= + Numbered.set M.val := by + change ∃ M : Transport.BagPM (RationalSource.bags w K), + initialFromHierarchy (setupHierarchy (((matrixRep w,List.replicate (2*K+2) false),List.range n), + List.replicate (2*K) false))=Numbered.set M.val + unfold setupHierarchy + dsimp only + rw [buildClosure_repr hn w hw K,hierarchyFuel_source hn w hw K] + exact initialFromHierarchy_valid_fintype (RationalSource.realB w K) + (fun a b=>(by norm_num : (0:ℚ)≤1).trans (RationalSource.realB_floor w K a b)) + (RationalSource.realB_symm w K) (RationalSource.realB_tri w K) + (List.replicate (RationalSource.levels w K) false) (realLeft K) (realRight K) + (endpointList (List.range n,List.replicate (2*K+2) false)) + (endpointList_members K _ (List.length_replicate ..)) + (RationalSource.levels w K) (List.length_replicate ..) + (inferInstance : Fintype (RationalSource.Label w K)) + (RationalSource.bags_ranked w K hcap) (RationalSource.bags_nonempty w K) hex + +lemma sourceInitial_even {n : ℕ} [Nontrivial (Fin n)] (hn : 2≤n) (he : Even n) + (w : Fin n→Fin n→ℚ) (hw : ∀ i j,0≤w i j) (K : ℕ) + (hcap : ∀ i j,i≠j → BottleneckAlgorithm.edge w i j≤(4:ℚ)^K) : + ∃ M : Transport.BagPM (RationalSource.bags w K), + sourceInitial (((matrixRep w,List.replicate (2*K+2) false),List.range n),List.replicate (2*K) false)= + Numbered.set M.val := + sourceInitial_valid hn w hw K hcap ⟨RationalSource.startMatching w K he⟩ + +open TreePost Turing + +theorem sourceInitial_post : ∃ p : Polynomial ℕ,∀ x : BagBuildInput,∀ t : ℕ, + p.eval (packed x).length≤t → ∀ coins : Fin t→Bool, + (run (machine sourceInitialRealizer.program) (packed x) coins).state=none ∧ + (run (machine sourceInitialRealizer.program) (packed x) coins).tape.right₀= + ListBlank.mk (packed (sourceInitial x)) := + polynomial_compiles sourceInitialRealizer polynomial_sourceInitial +end MatchingFPRAS.ExecutableSource + +end OAI diff --git a/lean/OAI/Combinatorics/MatchingCount/Machines/TreeLabelCorrect.lean b/lean/OAI/Combinatorics/MatchingCount/Machines/TreeLabelCorrect.lean new file mode 100644 index 0000000000000000000000000000000000000000..b3b8f9654828c46a8ea6efdd188f5c5428a6bd7f --- /dev/null +++ b/lean/OAI/Combinatorics/MatchingCount/Machines/TreeLabelCorrect.lean @@ -0,0 +1,88 @@ +import Mathlib +import OAI.Combinatorics.MatchingCount.Graphs.LabelOrder +import OAI.Combinatorics.MatchingCount.Machines.TreeLabelTable + +namespace OAI + +namespace MatchingFPRAS.UnitRefresh +lemma ofFn_orderedEnum (A : Type) [Fintype A] [LinearOrder A] : + List.ofFn (orderedEnum A)=(Finset.univ : Finset A).sort (· ≤ ·) := by + apply List.ext_getElem + · simp + · intro i _ _ + simp only [List.getElem_ofFn] + rfl +end MatchingFPRAS.UnitRefresh + +namespace MatchingFPRAS.ExecutableHierarchy +open TreeTyped TreeFraction ExecutableBottleneck Finset + +abbrev key {n H : ℕ} {B : Fin n→Fin n→ℚ} (l : NumberedHierarchy.Label B H) : LabelKey := (l.1.val,l.2.val.val) +lemma key_injective {n H : ℕ} (B : Fin n→Fin n→ℚ) : Function.Injective (key (B:=B) (H:=H)) := by + rintro ⟨k,a⟩ ⟨j,b⟩ he + have he' : k=j := Fin.ext (congrArg Prod.fst he) + cases he' + exact congrArg (Sigma.mk k) (Subtype.ext (Fin.ext (congrArg Prod.snd he))) + +lemma labels_pairwise (x : HierarchyInput) : + (labels x).Pairwise (fun a b=>toLex a < toLex b) := by + apply List.Pairwise.filter + apply List.pairwise_flatMap.mpr + constructor + · intro k _ + apply List.pairwise_map.mpr + exact (List.pairwise_lt_range (n:=x.1.length)).imp (fun h=>by exact Prod.Lex.right _ h) + · apply (List.pairwise_lt_range (n:=x.2.length+1)).imp + intro k j hkj a ha b hb + obtain ⟨u,_,rfl⟩:=List.mem_map.mp ha + obtain ⟨v,_,rfl⟩:=List.mem_map.mp hb + exact Prod.Lex.left _ _ hkj + +lemma mem_labels_iff_key {n : ℕ} (B : Fin n→Fin n→ℚ) (hB : ∀ a b,0 ≤ B a b) + (xs : List Bool) (l : LabelKey) : + l∈labels (matrixRep B,xs) ↔ ∃ a : NumberedHierarchy.Label B xs.length,key a=l := by + rw [mem_labels,matrixRep_length] + dsimp only + constructor + · rintro ⟨hk,hv,hr⟩ + let k : Fin (xs.length+1):=⟨l.1,by omega⟩ + let v : Fin n:=⟨l.2,hv⟩ + have hr' : NumberedHierarchy.root B ((2:ℚ)^k.val) v=v := by + apply Fin.ext + exact (labelRoot_matrixRep B hB xs k v).symm.trans hr + exact ⟨⟨k,⟨v,hr'⟩⟩,rfl⟩ + · rintro ⟨a,rfl⟩ + exact ⟨Nat.le_of_lt_succ a.1.isLt,a.2.val.isLt,(labelRoot_matrixRep B hB xs a.1 a.2.val).trans (congrArg Fin.val a.2.property)⟩ + +local instance {n H : ℕ} (B : Fin n→Fin n→ℚ) : LinearOrder (NumberedHierarchy.Label B H) := NumberedHierarchy.labelOrder B H +local instance (priority := 2000) {n H : ℕ} (B : Fin n→Fin n→ℚ) : LE (NumberedHierarchy.Label B H) := (NumberedHierarchy.labelOrder B H).toLE +lemma key_le_iff {n H : ℕ} (B : Fin n→Fin n→ℚ) (a b : NumberedHierarchy.Label B H) : + toLex (key a) ≤ toLex (key b) ↔ a ≤ b := by + change _ ↔ toLex (a.1,a.2.val) ≤ toLex (b.1,b.2.val) + simp only [Prod.Lex.le_iff,key,Fin.lt_def,Fin.le_def] + exact or_congr Iff.rfl (and_congr Fin.val_inj Iff.rfl) +lemma labels_eq_sorted_keys {n : ℕ} (B : Fin n→Fin n→ℚ) (hB : ∀ a b,0 ≤ B a b) + (xs : List Bool) : + labels (matrixRep B,xs)=((univ : Finset (NumberedHierarchy.Label B xs.length)).sort (· ≤ ·)).map key := by + let R : LabelKey→LabelKey→Prop:=fun a b=>toLex a ≤ toLex b + have ha : (labels (matrixRep B,xs)).Pairwise R := (labels_pairwise _).imp (fun h=>h.le) + have hb : (((univ : Finset (NumberedHierarchy.Label B xs.length)).sort (· ≤ ·)).map key).Pairwise R := by + apply List.pairwise_map.mpr + exact (Finset.pairwise_sort _ _).imp (fun h=>(key_le_iff B _ _).mpr h) + have hn : (labels (matrixRep B,xs)).Nodup := + (labels_pairwise _).imp (fun h he=>h.ne (congrArg toLex he)) + have hm : (((univ : Finset (NumberedHierarchy.Label B xs.length)).sort (· ≤ ·)).map key).Nodup := + (Finset.sort_nodup _ _).map (key_injective B) + have hp : (labels (matrixRep B,xs)).Perm (((univ : Finset (NumberedHierarchy.Label B xs.length)).sort (· ≤ ·)).map key) := by + apply List.perm_of_nodup_nodup_toFinset_eq hn hm + ext l + simp only [List.mem_toFinset,mem_labels_iff_key B hB,List.mem_map,Finset.mem_sort,Finset.mem_univ,true_and] + exact hp.eq_of_pairwise (fun a b _ _ hab hba=>toLex.injective (le_antisymm hab hba)) ha hb +lemma labels_eq_ofFn {n : ℕ} (B : Fin n→Fin n→ℚ) (hB : ∀ a b,0 ≤ B a b) + (xs : List Bool) : + labels (matrixRep B,xs)=List.ofFn (fun i=>key (UnitRefresh.orderedEnum (NumberedHierarchy.Label B xs.length) i)) := by + change _=List.ofFn (key ∘ UnitRefresh.orderedEnum (NumberedHierarchy.Label B xs.length)) + rw [←List.map_ofFn,UnitRefresh.ofFn_orderedEnum,labels_eq_sorted_keys B hB] +end MatchingFPRAS.ExecutableHierarchy + +end OAI diff --git a/lean/OAI/Combinatorics/MatchingCount/Machines/TreeLabelTable.lean b/lean/OAI/Combinatorics/MatchingCount/Machines/TreeLabelTable.lean new file mode 100644 index 0000000000000000000000000000000000000000..0fe42a9169f12e0ee643d7da95da806db66bfff3 --- /dev/null +++ b/lean/OAI/Combinatorics/MatchingCount/Machines/TreeLabelTable.lean @@ -0,0 +1,89 @@ +import Mathlib +import OAI.Combinatorics.MatchingCount.Graphs.TreeHierarchyRoot +import OAI.Combinatorics.MatchingCount.Arithmetic.TreeDyadic + +namespace OAI + +namespace MatchingFPRAS.TreeTyped +lemma polynomial_filterWithList {A B : Type} [Codec A] [Codec B] {p : A×B→Bool} + {P : Realizer p} (hP : PolynomialTime P) : PolynomialTime (filterWith P) := by + unfold filterWith + exact polynomial_congr _ (polynomial_composition + (polynomial_composition (polynomial_mapWith (polynomial_pair polynomial_second hP)) + (polynomial_filter polynomial_second)) (polynomial_map polynomial_first)) +end MatchingFPRAS.TreeTyped + +namespace MatchingFPRAS.ExecutableHierarchy +open TreeTyped TreeFraction ExecutableBottleneck Polynomial + +abbrev LabelKey := ℕ×ℕ +abbrev HierarchyInput := Matrix×List Bool + +def labelRoot (x : HierarchyInput×LabelKey) : ℕ := + root ((x.1.1,threshold (x.1.2,x.2.1)),x.2.2) +def labelRootRealizer : Realizer labelRoot := composition + (pair (pair first.fst (composition (pair first.snd second.fst) thresholdRealizer)) second.snd) rootRealizer +lemma polynomial_labelRoot : PolynomialTime labelRootRealizer := by + apply polynomial_composition _ polynomial_root + apply polynomial_pair _ (polynomial_snd polynomial_second) + exact polynomial_pair (polynomial_fst polynomial_first) (polynomial_composition + (polynomial_pair (polynomial_snd polynomial_first) (polynomial_fst polynomial_second)) polynomial_threshold) + +def fixedRoot (x : HierarchyInput×LabelKey) : Bool := decide (labelRoot x=x.2.2) +def fixedRootRealizer : Realizer fixedRoot := composition (pair labelRootRealizer second.snd) natEqual +lemma polynomial_fixedRoot : PolynomialTime fixedRootRealizer := + polynomial_composition (polynomial_pair polynomial_labelRoot (polynomial_snd polynomial_second)) polynomial_natEqual + +def labels (x : HierarchyInput) : List LabelKey := + ((List.range (x.2.length+1)).flatMap fun k=>(List.range x.1.length).map fun v=>(k,v)).filter fun l=>fixedRoot (x,l) +def labelsRealizer : Realizer labels := by + let ks : Realizer (fun x : HierarchyInput=>List.range (x.2.length+1)) := + composition (composition (composition second listLength) successor) range + let vs : Realizer (fun x : HierarchyInput=>List.range x.1.length) := + composition (composition first listLength) range + let row : Realizer (fun x : HierarchyInput×ℕ=>(List.range x.1.1.length).map fun v=>(x.2,v)) := + composition (pair second (composition first vs)) (mapWith (pair first second)) + exact (composition (pair identity (composition (composition (pair identity ks) (mapWith row)) flatten)) + (filterWith fixedRootRealizer)).congr (fun _=>rfl) +lemma polynomial_labels : PolynomialTime labelsRealizer := by + have hk : PolynomialTime (composition (composition (composition (second (A:=Matrix) (B:=List Bool)) listLength) successor) range) := by + apply polynomial_boundedRange (polynomial_composition (polynomial_composition polynomial_second polynomial_listLength) polynomial_successor) (X+1) + intro x + have h:=(list_length_le_weight x.2).trans (weight_snd x) + simpa only [Polynomial.eval_add,Polynomial.eval_X,Polynomial.eval_one,Function.comp_apply,Nat.succ_eq_add_one] using Nat.add_le_add_right h 1 + have hv : PolynomialTime (composition (composition (first (A:=Matrix) (B:=List Bool)) listLength) range) := by + apply polynomial_boundedRange (polynomial_composition polynomial_first polynomial_listLength) X + intro x + simpa using (list_length_le_weight x.1).trans (weight_fst x) + unfold labelsRealizer + dsimp only + apply polynomial_congr + apply polynomial_composition _ (polynomial_filterWithList polynomial_fixedRoot) + apply polynomial_pair polynomial_identity + apply polynomial_composition _ polynomial_flatten + apply polynomial_composition (polynomial_pair polynomial_identity hk) + apply polynomial_mapWith + apply polynomial_composition _ (polynomial_mapWith (polynomial_pair polynomial_first polynomial_second)) + exact polynomial_pair polynomial_second (polynomial_composition polynomial_first hv) + +lemma mem_labels (x : HierarchyInput) (l : LabelKey) : + l∈labels x ↔ l.1≤x.2.length ∧ l.2 exact False.elim (hi he) + | cons x y => + obtain ⟨a,ha,hs⟩:=effect_compiles (loopCode i P) Loop.test (.branch i Loop.halt Loop.body) rfl + E E (some Loop.body) 1 (Effect.consBranch _ _ _ _ x y he) + obtain ⟨b,hb,hm⟩:=effect_compiles (loopCode i P) Loop.body (.call P Loop.test) rfl + E F (some Loop.test) (n+1) (Effect.call _ _ _ _ n h) + obtain ⟨c,hc,hg⟩:=ht + change MachineCost.run (TM2.step (RegisterControl.code (loopCode i P))) c + (RegisterControl.cfg _ (some Loop.test) F)=RegisterControl.cfg _ none G at hg + refine ⟨a+b+c,by omega,?_⟩ + change MachineCost.run (TM2.step (RegisterControl.code (loopCode i P))) (a+b+c) + (RegisterControl.cfg _ (some Loop.test) E)=RegisterControl.cfg _ none G + rw [run_add,run_add,hs,hm,hg] +end MatchingFPRAS.RegisterStructured + +namespace MatchingFPRAS.TreeLanguage +open TreeData TreeMachine RegisterProc RegisterStructured + +variable {R : Type} [DecidableEq R] +inductive Program (R : Type) [DecidableEq R] where + | leaf (P : Proc (K R)) + | seq (p q : Program R) + | select (i : R) (nil cons : Program R) + | loop (i : R) (body : Program R) + +def compile : Program R → Proc (K R) + | .leaf P => P + | .seq p q => RegisterProc.seq (compile p) (compile q) + | .select i p q => RegisterStructured.select i (compile p) (compile q) + | .loop i p => RegisterStructured.loop i (compile p) + +inductive Eval : Program R → Env R → Env R → ℕ → Prop + | leaf (P E F n) (h : Exec P (encodeEnv E) (encodeEnv F) n) : Eval (.leaf P) E F n + | seq (p q E F G n m) (h : Eval p E F n) (h' : Eval q F G m) : Eval (.seq p q) E G (n+m) + | nilBranch (i p q E F n) (hi : E i=.nil) (h : Eval p E F n) : Eval (.select i p q) E F (n+3) + | consBranch (i p q E F n) (hi : E i≠.nil) (h : Eval q E F n) : Eval (.select i p q) E F (n+3) + | loopNil (i p E) (hi : E i=.nil) : Eval (.loop i p) E E 2 + | loopStep (i p E F G n m) (hi : E i≠.nil) (h : Eval p E F n) + (ht : Eval (.loop i p) F G m) : Eval (.loop i p) E G (n+m+2) + | weaken (p E F n m) (h : Eval p E F n) (hm : n ≤ m) : Eval p E F m + +theorem compiles (p : Program R) (E F : Env R) (n : ℕ) (h : Eval p E F n) : + Exec (compile p) (encodeEnv E) (encodeEnv F) n := by + induction h with + | leaf P E F n h => exact h + | seq p q E F G n m h h' ih ih' => exact ih.seq ih' + | nilBranch i p q E F n hi h ih => exact select_nil i _ _ E F n hi ih + | consBranch i p q E F n hi h ih => + cases he : E i with + | nil => exact False.elim (hi he) + | cons x y => exact select_cons i _ _ E F n x y he ih + | loopNil i p E hi => exact loop_nil i _ E hi + | loopStep i p E F G n m hi h ht ih iht => exact loop_step i _ E F G n m hi ih iht + | weaken p E F n m h hm ih => exact ih.mono hm + +def clear (i : R) : Program R := .leaf (procedure (.nil i ())) +def copy (i j : R) (h : i≠j) : Program R := .leaf (procedure (.copy i j h ())) +def cons (i j : R) (h : i≠j) : Program R := .leaf (procedure (.cons i j h ())) +def split (i j : R) (h : i≠j) : Program R := .leaf (procedure (.split i j h ())) +lemma clear_eval (E : Env R) (i : R) : + Eval (clear i) E (Function.update E i .nil) ((TreeData.encode (E i)).length+2) := + Eval.leaf _ _ _ _ (nil_exec E i ()) +lemma copy_eval (E : Env R) (i j : R) (hij : i≠j) : + Eval (copy i j hij) E (putPair E i j (E i) (E i)) + ((TreeData.encode (E j)).length+3*(TreeData.encode (E i)).length+4) := + Eval.leaf _ _ _ _ (copy_exec E i j hij ()) +lemma cons_eval (E : Env R) (i j : R) (hij : i≠j) : + Eval (cons i j hij) E (putPair E i j .nil (.cons (E i) (E j))) + (2*(TreeData.encode (E i)).length+3) := + Eval.leaf _ _ _ _ (cons_exec E i j hij ()) +lemma split_eval (E : Env R) (i j : R) (hij : i≠j) (x y : Data) (hj : E j=.cons x y) : + Eval (split i j hij) E (putPair E i j x y) + ((TreeData.encode (E i)).length+2*(TreeData.encode x).length+4) := + Eval.leaf _ _ _ _ (split_exec E i j hij () x y hj) +end MatchingFPRAS.TreeLanguage + +end OAI diff --git a/lean/OAI/Combinatorics/MatchingCount/Machines/TreeList.lean b/lean/OAI/Combinatorics/MatchingCount/Machines/TreeList.lean new file mode 100644 index 0000000000000000000000000000000000000000..f3a652a7f54d3f6bf085f435987c926cda9917ab --- /dev/null +++ b/lean/OAI/Combinatorics/MatchingCount/Machines/TreeList.lean @@ -0,0 +1,100 @@ +import Mathlib +import OAI.Combinatorics.MatchingCount.Machines.TreeFold +import OAI.Combinatorics.MatchingCount.Machines.TreeChoice + +namespace OAI + +namespace MatchingFPRAS.TreeTyped +open TreeData TreeMachine RegisterProc TreeFunction + +variable {A B C : Type} [Codec A] [Codec B] [Codec C] +def Realizer.congr {f g : A → B} (F : Realizer f) (h : ∀ a,f a=g a) : Realizer g := + ⟨F.program,F.cost,fun a s=>by simpa only [h a] using F.correct a s⟩ + +def listCons : Realizer (fun ab : A×List A=>ab.1::ab.2) := + ⟨atom .halt,fun _=>1,fun _ _=>exec_atom .halt _ _ rfl⟩ + +def reverse : Realizer (List.reverse : List A → List A) := + (composition (pair identity (constant ([] : List A))) (fold listCons)).congr (by + intro as + change as.foldl (fun x y=>y::x) []=as.reverse + simp) + +def toBits : Realizer Nat.bits := + ⟨atom .halt,fun _=>1,fun _ _=>exec_atom .halt _ _ rfl⟩ + +def double : Realizer (fun n : ℕ=>2*n) := + (composition (pair identity identity) add).congr (fun value=>by + change value+value=2*value + omega) + +def mulStep (x : Bool×(ℕ×ℕ)) : ℕ×ℕ := + (x.2.1,2*x.2.2+(if x.1 then x.2.1 else 0)) + +def mulStepRealizer : Realizer mulStep := by + let bitP : Realizer (fun x : Bool×(ℕ×ℕ)=>x.1) := first + let nP : Realizer (fun x : Bool×(ℕ×ℕ)=>x.2.1) := composition second first + let cP : Realizer (fun x : Bool×(ℕ×ℕ)=>x.2.2) := composition second second + let vP:=choose bitP nP (constant 0) + let sumP:=composition (pair (composition cP double) vP) add + exact (pair nP sumP).congr (fun _=>rfl) + +lemma mulStep_fold (A : List Bool) (n c : ℕ) : + A.reverse.foldl (fun z b=>mulStep (b,z)) (n,c)= + (n,c*2^A.length+StackAddition.value A*n) := by + induction A generalizing c with + | nil => simp [StackAddition.value] + | cons b A ih => + simp only [List.reverse_cons,List.foldl_append,ih,List.foldl_cons,List.foldl_nil,List.length_cons] + cases b <;> simp only [mulStep,Bool.false_eq_true,↓reduceIte,StackAddition.value, + Bool.toNat_false,Bool.toNat_true,Nat.zero_add,pow_succ] <;> congr 1 <;> ring + +def multiply : Realizer (fun ab : ℕ×ℕ=>ab.1*ab.2) := by + let bitsP : Realizer (fun ab : ℕ×ℕ=>ab.1.bits.reverse) := composition (composition first toBits) reverse + let startP : Realizer (fun ab : ℕ×ℕ=>(ab.2,0)) := pair second (constant 0) + let foldP:=composition (pair bitsP startP) (fold mulStepRealizer) + exact (composition foldP second).congr (by + intro ab + change (ab.1.bits.reverse.foldl (fun z b=>mulStep (b,z)) (ab.2,0)).2=ab.1*ab.2 + rw [mulStep_fold] + simp [StackAddition.value_bits]) + +lemma size_encode_list (as : List A) : + TreeFunction.size (encode as) = 1+as.length+(as.map (fun a=>TreeFunction.size (encode a))).sum := by + induction as with + | nil => rfl + | cons a as ih => simp only [encode_list_cons,size_cons,ih,List.length_cons,List.map_cons,List.sum_cons]; omega + +lemma size_encode_mem {as : List A} {a : A} (ha : a ∈ as) : + TreeFunction.size (encode a) ≤ TreeFunction.size (encode as) := by + induction as with + | nil => simp at ha + | cons b bs ih => + simp only [List.mem_cons] at ha + simp only [encode_list_cons,size_cons] + rcases ha with rfl|ha + · omega + · have := ih ha; omega + +lemma size_encode_tail (a : A) (as : List A) : + TreeFunction.size (encode as) ≤ TreeFunction.size (encode (a::as)) := by + simp only [encode_list_cons,size_cons]; omega + +omit [Codec B] in +lemma Fold.cost_bound {f : A×B → B} (t : A×B → ℕ) (I : B → Prop) (as : List A) (b : B) (T S : ℕ) + (hb : I b) (hs : TreeFunction.size (encode as) ≤ S) + (hstep : ∀ a ∈ as,∀ z,I z → I (f (a,z)) ∧ t (a,z) ≤ T) : + Fold.cost f t as b ≤ as.length*(T+14*S+34)+10 := by + induction as generalizing b with + | nil => simp [Fold.cost] + | cons a as ih => + have ht:=hstep a (by simp) b hb + have hs' := (size_encode_tail a as).trans hs + have hb' : ∀ a ∈ as,∀ z,I z → I (f (a,z)) ∧ t (a,z) ≤ T := fun a ha z hz=>hstep a (by simp [ha]) z hz + have hh:=ih (f (a,b)) ht.1 hs' hb' + have ha:=(size_encode_mem (by simp : a ∈ a::as)).trans hs + simp only [Fold.cost,List.length_cons] + nlinarith +end MatchingFPRAS.TreeTyped + +end OAI diff --git a/lean/OAI/Combinatorics/MatchingCount/Machines/TreeListMore.lean b/lean/OAI/Combinatorics/MatchingCount/Machines/TreeListMore.lean new file mode 100644 index 0000000000000000000000000000000000000000..a809f59b77d4a3af02b7b5a78da85df9e0f571b0 --- /dev/null +++ b/lean/OAI/Combinatorics/MatchingCount/Machines/TreeListMore.lean @@ -0,0 +1,86 @@ +import Mathlib +import OAI.Combinatorics.MatchingCount.Machines.TreeListOps + +namespace OAI + +namespace MatchingFPRAS.TreeTyped +variable {A B X : Type} [Codec A] [Codec B] [Codec X] + +def takeStep (z : ℕ×(List A×List A)) : List A×List A := + match z.2.1 with + | [] => z.2 + | a::as => (as,a::z.2.2) + +def takeStepRealizer (d : A) : Realizer (takeStep (A:=A)) := + (choose (composition (composition second first) isEmpty) second + (pair (composition (composition second first) tail) + (composition (pair (composition (composition second first) (head d)) + (composition second second)) listCons))).congr (by + intro z; cases h : z.2.1 <;> simp [takeStep,h]) + +omit [Codec A] in +lemma countDown_take (n : ℕ) (as bs : List A) : + countDown (takeStep (A:=A)) n (as,bs)=(as.drop n,(as.take n).reverse++bs) := by + induction n generalizing as bs with + | zero => simp [countDown] + | succ n ih => + cases as with + | nil => simpa [countDown,takeStep] using ih [] bs + | cons a as => + simp only [countDown,takeStep,ih,List.drop_succ_cons,List.take_succ_cons, + List.reverse_cons,List.append_assoc,List.singleton_append] + +def take (d : A) : Realizer (fun x : List A×ℕ=>x.1.take x.2) := + (composition (composition (pair second (pair first (constant ([] : List A)))) + (iterateDown (takeStepRealizer d))) (composition second reverse)).congr (by + intro x + change ((countDown takeStep x.2 (x.1,[])).2).reverse=_ + rw [countDown_take] + simp) + +def flatMap {f : A → List B} (F : Realizer f) : Realizer (List.flatMap f) := by + let S : Realizer (fun x : A×List B=>(f x.1).reverse++x.2) := + composition (pair (composition (composition first F) reverse) second) append + exact (composition (composition (pair identity (constant ([] : List B))) (fold S)) reverse).congr (by + intro as + change (as.foldl (fun bs a=>(f a).reverse++bs) []).reverse=as.flatMap f + have h : ∀ bs,as.foldl (fun bs a=>(f a).reverse++bs) bs=(as.flatMap f).reverse++bs := by + induction as with + | nil => intro bs; rfl + | cons a as ih => intro bs; simp [List.foldl_cons,ih,List.reverse_append,List.append_assoc] + rw [h] + simp) + +def minimum : Realizer (fun x : ℕ×ℕ=>min x.1 x.2) := + (choose less first second).congr (by intro x; simp only [decide_eq_true_eq]; split_ifs with h <;> omega) +def maximum : Realizer (fun x : ℕ×ℕ=>max x.1 x.2) := + (choose less second first).congr (by intro x; simp only [decide_eq_true_eq]; split_ifs with h <;> omega) + +def listMin (x : List ℕ×ℕ) : ℕ := x.1.foldl min x.2 +def listMinRealizer : Realizer listMin := + (fold minimum).congr (by intro x; dsimp only [listMin]; congr 1; funext a b; exact Nat.min_comm b a) + +lemma listMin_le_default (as : List ℕ) (d : ℕ) : listMin (as,d)≤d := by + induction as generalizing d with + | nil => rfl + | cons a as ih => exact (ih (min d a)).trans (min_le_left _ _) + +lemma listMin_le {as : List ℕ} {d a : ℕ} (ha : a∈as) : listMin (as,d)≤a := by + induction as generalizing d with + | nil => simp at ha + | cons b bs ih => + simp only [List.mem_cons] at ha + rcases ha with rfl|ha + · exact (listMin_le_default bs (min d a)).trans (min_le_right _ _) + · exact ih ha + +lemma le_listMin {as : List ℕ} {d a : ℕ} (hd : a≤d) (ha : ∀ b∈as,a≤b) : + a≤listMin (as,d) := by + induction as generalizing d with + | nil => exact hd + | cons b bs ih => + apply ih (le_min hd (ha b (by simp))) + intro c hc; exact ha c (by simp [hc]) +end MatchingFPRAS.TreeTyped + +end OAI diff --git a/lean/OAI/Combinatorics/MatchingCount/Machines/TreeListOps.lean b/lean/OAI/Combinatorics/MatchingCount/Machines/TreeListOps.lean new file mode 100644 index 0000000000000000000000000000000000000000..138778c3d252ca18beca8b5c81420256dcb76c92 --- /dev/null +++ b/lean/OAI/Combinatorics/MatchingCount/Machines/TreeListOps.lean @@ -0,0 +1,119 @@ +import Mathlib +import OAI.Combinatorics.MatchingCount.Machines.TreeFrame +import OAI.Combinatorics.MatchingCount.Machines.TreeRepeat + +namespace OAI + +namespace MatchingFPRAS.TreeTyped +open TreeData TreeMachine RegisterProc TreeFunction + +variable {A B X : Type} [Codec A] [Codec B] [Codec X] + +def listCase (b : B) {g : A×List A → B} (G : Realizer g) : + Realizer (fun as : List A=>match as with | []=>b | a::as=>g (a,as)) where + program := RegisterStructured.select 0 (constant b (A:=List A)).program G.program + cost := fun as=>3+match as with | []=>(constant b (A:=List A)).cost [] | a::as=>G.cost (a,as) + correct := by + intro as s + cases as with + | nil => + have hh:=RegisterStructured.select_nil 0 _ G.program (env (encode ([] : List A)) .nil s) + (env (encode b) .nil s) _ rfl ((constant b (A:=List A)).correct [] s) + exact hh.mono (by dsimp; omega) + | cons a as => + have hh:=RegisterStructured.select_cons 0 (constant b (A:=List A)).program _ + (env (encode (a::as)) .nil s) (env (encode (g (a,as))) .nil s) _ (encode a) (encode as) rfl + (G.correct (a,as) s) + exact hh.mono (by dsimp; omega) + +def head (d : A) : Realizer (fun as : List A=>as.headD d) := + (listCase d first).congr (by intro as; cases as <;> rfl) + +def tail : Realizer (List.tail : List A → List A) := listCase [] second + +def isEmpty : Realizer (List.isEmpty : List A → Bool) := listCase true (constant false) + +def dropStep (x : ℕ×List A) : List A := x.2.tail +omit [Codec A] [Codec B] [Codec X] in +lemma countDown_drop (n : ℕ) (as : List A) : countDown (dropStep (A:=A)) n as=as.drop n := by + induction n generalizing as with + | zero => rfl + | succ n ih => + rw [countDown,ih] + exact List.drop_tail + +def drop : Realizer (fun x : List A×ℕ=>x.1.drop x.2) := + (composition (pair second first) (iterateDown (composition second tail))).congr (by + intro x; exact countDown_drop x.2 x.1) +def getD (d : A) : Realizer (fun x : List A×ℕ=>x.1.getD x.2 d) := + (composition drop (head d)).congr (by + intro x + simp only [Function.comp_apply, List.headD_eq_head?_getD, List.head?_drop, + List.getD_eq_getElem?_getD]) + +def mapStep (g : X×A → B) (z : A×(X×List B)) : X×List B := + (z.2.1,g (z.2.1,z.1)::z.2.2) +def mapStepRealizer {g : X×A → B} (G : Realizer g) : Realizer (mapStep g) := + pair (composition second first) + (composition (pair (composition (pair (composition second first) first) G) + (composition second second)) listCons) + +omit [Codec A] [Codec B] [Codec X] in +lemma mapStep_fold (g : X×A → B) (as : List A) (x : X) (bs : List B) : + as.foldl (fun z a=>mapStep g (a,z)) (x,bs)=(x,(as.map (fun a=>g (x,a))).reverse++bs) := by + induction as generalizing bs with + | nil => rfl + | cons a as ih => + change as.foldl _ (x,g (x,a)::bs)=_ + rw [ih] + simp only [List.map_cons,List.reverse_cons,List.append_assoc,List.singleton_append] + +def mapWith {g : X×A → B} (G : Realizer g) : Realizer (fun xas : X×List A=>xas.2.map (fun a=>g (xas.1,a))) := + (composition (composition (pair second (pair first (constant ([] : List B)))) (fold (mapStepRealizer G))) + (composition second reverse)).congr (by + intro xas + change ((xas.2.foldl _ (xas.1,[])).2).reverse=_ + rw [mapStep_fold] + simp) + +def map {g : A → B} (G : Realizer g) : Realizer (List.map g) := by + let S : Realizer (fun x : A×List B=>g x.1::x.2) := composition (pair (composition first G) second) listCons + exact (composition (composition (pair identity (constant ([] : List B))) (fold S)) reverse).congr (by + intro as + change (as.foldl (fun bs a=>g a::bs) []).reverse=as.map g + simp) + +def listLength : Realizer (List.length : List A → ℕ) := + (composition (pair identity (constant 0)) + (fold (composition (pair second (constant 1)) add))).congr (by + intro as + change as.foldl (fun n (_ : A)=>n+1) 0=as.length + have h : ∀ n,as.foldl (fun n (_ : A)=>n+1) n=n+as.length := by + induction as with + | nil => intro n; simp + | cons a as ih => intro n; simp only [List.foldl_cons,ih,List.length_cons]; omega + simpa only [Nat.zero_add] using h 0) + +def append : Realizer (fun x : List A×List A=>x.1++x.2) := + (composition (pair (composition first reverse) second) (fold listCons)).congr (by + intro x + change x.1.reverse.foldl (fun bs a=>a::bs) x.2=x.1++x.2 + rw [List.foldl_flip_cons_eq_append',List.reverse_reverse]) + +def filter {f : A → Bool} (F : Realizer f) : Realizer (List.filter f) := by + let S : Realizer (fun x : A×List A=>if f x.1 then x.1::x.2 else x.2) := + choose (composition first F) listCons second + exact (composition (composition (pair identity (constant ([] : List A))) (fold S)) reverse).congr (by + intro as + change (as.foldl (fun bs a=>if f a then a::bs else bs) []).reverse=as.filter f + have h : ∀ bs,as.foldl (fun bs a=>if f a then a::bs else bs) bs=(as.filter f).reverse++bs := by + induction as with + | nil => intro bs; rfl + | cons a as ih => + intro bs + cases hf : f a <;> simp [List.foldl_cons,hf,ih,List.append_assoc] + rw [h] + simp) +end MatchingFPRAS.TreeTyped + +end OAI diff --git a/lean/OAI/Combinatorics/MatchingCount/Machines/TreeLookup.lean b/lean/OAI/Combinatorics/MatchingCount/Machines/TreeLookup.lean new file mode 100644 index 0000000000000000000000000000000000000000..9032ce8299df951986e0993fa10ef5eb9cbd88ba --- /dev/null +++ b/lean/OAI/Combinatorics/MatchingCount/Machines/TreeLookup.lean @@ -0,0 +1,164 @@ +import Mathlib +import OAI.Combinatorics.MatchingCount.Machines.TreeCompiler + +namespace OAI + +namespace MatchingFPRAS.TreeData +open Data + +def ofList : List Data → Data + | [] => .nil + | x::xs => .cons x (ofList xs) +def unary : ℕ → Data + | 0 => .nil + | n+1 => .cons .nil (unary n) +lemma ofList_nil : ofList []=.nil := rfl +lemma ofList_cons (x : Data) (xs : List Data) : ofList (x::xs)=.cons x (ofList xs) := rfl +lemma unary_encode_length (n : ℕ) : (encode (unary n)).length=2*n+1 := by + induction n <;> simp_all [unary,encode]; omega +lemma encode_head_le (x y : Data) : (encode x).length≤(encode (.cons x y)).length := by + simp only [encode,List.length_cons,List.length_append]; omega +lemma encode_tail_le (x y : Data) : (encode y).length≤(encode (.cons x y)).length := by + simp only [encode,List.length_cons,List.length_append]; omega +end MatchingFPRAS.TreeData +namespace MatchingFPRAS.TreeMachine +open TreeData RegisterProc Turing MachineCost + +variable {R : Type} [DecidableEq R] +lemma SizeBound.update {E : Env R} {B : ℕ} (h : SizeBound E B) (i : R) (x : Data) + (hx : (encode x).length≤B) : SizeBound (Function.update E i x) B := by + intro j + by_cases hh : j=i + · subst j; simpa using hx + · simpa only [Function.update_of_ne hh] using h j +lemma SizeBound.putPair {E : Env R} {B : ℕ} (h : SizeBound E B) (i j : R) (x y : Data) + (hx : (encode x).length≤B) (hy : (encode y).length≤B) : SizeBound (putPair E i j x y) B := + (h.update i x hx).update j y hy +lemma SizeBound.split {E : Env R} {B : ℕ} (h : SizeBound E B) (i j : R) (x y : Data) + (he : E j=.cons x y) : SizeBound (TreeMachine.putPair E i j x y) B := by + have hh:=h j + rw [he] at hh + exact h.putPair i j x y ((encode_head_le x y).trans hh) ((encode_tail_le x y).trans hh) +end MatchingFPRAS.TreeMachine + +namespace MatchingFPRAS.TreeLookup +open TreeData TreeMachine RegisterProc + +inductive Point where + | loop | check | dec | tail | finish | found | missing | halt + deriving DecidableEq, Inhabited +instance : Fintype Point := ⟨{.loop,.check,.dec,.tail,.finish,.found,.missing,.halt},by intro p; cases p <;> simp⟩ +abbrev R := Fin 4 + +def program : Point → Instr R Point + | .loop => .branch 0 .finish .check + | .check => .branch 1 .missing .dec + | .dec => .split 2 0 (by decide) .tail + | .tail => .split 2 1 (by decide) .loop + | .finish => .branch 1 .missing .found + | .found => .split 2 1 (by decide) .halt + | .missing => .nil 2 .halt + | .halt => .halt + +def result (E : Env R) : ℕ → List Data → Env R + | 0,[] => Function.update E 2 .nil + | 0,x::xs => putPair E 2 1 x (ofList xs) + | _+1,[] => Function.update E 2 .nil + | n+1,x::xs => result (putPair (putPair E 2 0 .nil (unary n)) 2 1 x (ofList xs)) n xs + +def steps : ℕ → List Data → ℕ + | 0,_ => 4 + | _+1,[] => 4 + | n+1,_::xs => steps n xs+4 +lemma steps_le (n : ℕ) (xs : List Data) : steps n xs≤4*(n+1) := by + induction n generalizing xs with + | zero => simp [steps] + | succ n ih => + cases xs with + | nil => simp only [steps]; omega + | cons x xs => have hh:=ih xs; simp only [steps]; omega + +lemma output (E : Env R) (n : ℕ) (xs : List Data) : result E n xs 2=xs.getD n .nil := by + induction n generalizing E xs with + | zero => cases xs <;> simp [result,putPair,List.getD] + | succ n ih => cases xs with + | nil => simp [result,List.getD] + | cons x xs => simpa only [result,List.getD_cons_succ] using ih _ _ + +lemma nil_bound {E : Env R} {B : ℕ} (h : SizeBound E B) : (encode Data.nil).length≤B := by + have hp:=encode_length_pos (E 0) + have hh:=h 0 + simp only [encode,List.length_singleton] + omega +lemma halt_runs (E : Env R) (B : ℕ) (h : SizeBound E B) : Runs program B (some Point.halt) E E 1 := by + exact Runs.step (M:=program) Point.halt E none E E 0 h (Effect.halt E) (.done E) +lemma missing_runs (E : Env R) (B : ℕ) (h : SizeBound E B) : + Runs program B (some Point.missing) E (Function.update E 2 .nil) 2 := by + exact Runs.step (M:=program) Point.missing E (some Point.halt) _ _ 1 h (.nil E 2 Point.halt) + (halt_runs _ B (h.update 2 .nil (nil_bound h))) +lemma found_runs (E : Env R) (B : ℕ) (h : SizeBound E B) (x y : Data) (he : E 1=.cons x y) : + Runs program B (some Point.found) E (putPair E 2 1 x y) 2 := by + exact Runs.step (M:=program) Point.found E (some Point.halt) _ _ 1 h (.split E 2 1 (by decide) Point.halt x y he) + (halt_runs _ B (h.split 2 1 x y he)) + +theorem runs (n : ℕ) (xs : List Data) (E : Env R) (B : ℕ) (h : SizeBound E B) + (hn : E 0=unary n) (hs : E 1=ofList xs) : + Runs program B (some Point.loop) E (result E n xs) (steps n xs) ∧ + SizeBound (result E n xs) B := by + induction n generalizing E xs with + | zero => + have hn' : E 0=Data.nil := hn + cases xs with + | nil => + constructor + · exact Runs.step (M:=program) Point.loop E (some Point.finish) E _ 3 h (.nilBranch E 0 Point.finish Point.check hn') + (Runs.step (M:=program) Point.finish E (some Point.missing) E _ 2 h (.nilBranch E 1 Point.missing Point.found hs) + (missing_runs E B h)) + · exact h.update 2 .nil (nil_bound h) + | cons x xs => + have hs' : E 1=.cons x (ofList xs) := hs + constructor + · exact Runs.step (M:=program) Point.loop E (some Point.finish) E _ 3 h (.nilBranch E 0 Point.finish Point.check hn') + (Runs.step (M:=program) Point.finish E (some Point.found) E _ 2 h (.consBranch E 1 Point.missing Point.found x (ofList xs) hs') + (found_runs E B h x (ofList xs) hs')) + · exact h.split 2 1 x (ofList xs) hs' + | succ n ih => + have hn' : E 0=.cons .nil (unary n) := hn + cases xs with + | nil => + constructor + · exact Runs.step (M:=program) Point.loop E (some Point.check) E _ 3 h (.consBranch E 0 Point.finish Point.check .nil (unary n) hn') + (Runs.step (M:=program) Point.check E (some Point.missing) E _ 2 h (.nilBranch E 1 Point.missing Point.dec hs) + (missing_runs E B h)) + · exact h.update 2 .nil (nil_bound h) + | cons x xs => + have hs' : E 1=.cons x (ofList xs) := hs + let F:=putPair E 2 0 .nil (unary n) + let G:=putPair F 2 1 x (ofList xs) + have hF : SizeBound F B := h.split 2 0 .nil (unary n) hn' + have hF1 : F 1=.cons x (ofList xs) := by simpa [F,putPair] using hs' + have hG : SizeBound G B := hF.split 2 1 x (ofList xs) hF1 + have hG0 : G 0=unary n := by simp [G,F,putPair] + have hG1 : G 1=ofList xs := by simp [G,putPair] + obtain ⟨hr,hout⟩:=ih xs G hG hG0 hG1 + constructor + · have hh:=Runs.step (M:=program) Point.tail F (some Point.loop) G _ (steps n xs) hF + (.split F 2 1 (by decide) Point.loop x (ofList xs) hF1) hr + have hh':=Runs.step (M:=program) Point.dec E (some Point.tail) F _ (steps n xs+1) h + (.split E 2 0 (by decide) Point.tail .nil (unary n) hn') hh + have hh'':=Runs.step (M:=program) Point.check E (some Point.dec) E _ (steps n xs+2) h + (.consBranch E 1 Point.missing Point.dec x (ofList xs) hs') hh' + exact Runs.step Point.loop E (some Point.check) E _ (steps n xs+3) h + (.consBranch E 0 Point.finish Point.check .nil (unary n) hn') hh'' + · exact hout + +theorem stack_exec (n : ℕ) (xs : List Data) (E : Env R) (B : ℕ) (h : SizeBound E B) + (hn : E 0=unary n) (hs : E 1=ofList xs) : + Exec (compile program) (encodeEnv E) (encodeEnv (result E n xs)) (20*(n+1)*(B+1)) := by + have hh:=compile_exec program B (steps n xs) E _ (runs n xs E B h hn hs).1 + apply hh.mono + have hk:=Nat.mul_le_mul_right (5*(B+1)) (steps_le n xs) + nlinarith +end MatchingFPRAS.TreeLookup + +end OAI diff --git a/lean/OAI/Combinatorics/MatchingCount/Machines/TreeMachine.lean b/lean/OAI/Combinatorics/MatchingCount/Machines/TreeMachine.lean new file mode 100644 index 0000000000000000000000000000000000000000..63f157f877bb2bc94c38f2f7293ff6b52b5afb1a --- /dev/null +++ b/lean/OAI/Combinatorics/MatchingCount/Machines/TreeMachine.lean @@ -0,0 +1,111 @@ +import Mathlib +import OAI.Combinatorics.MatchingCount.Machines.RegisterTree + +namespace OAI + +namespace MatchingFPRAS.RegisterProc +open Turing TreeData + +def makeNil : Proc (Fin 3) := seq clearRaw (atom (.push 0 (fun _=>false) .halt)) +lemma makeNil_exec (A B C : List Bool) : Exec makeNil ![A,B,C] ![[false],B,C] (A.length+2) := by + have h₁:=clearRaw_exec A B C + have h₂ : Exec (atom (.push 0 (fun _=>false) .halt)) ![[],B,C] ![[false],B,C] 1 := by + apply exec_atom + simp only [TM2.stepAux] + congr 1 + funext i; fin_cases i <;> simp + exact (h₁.seq h₂).mono (by omega) + +variable {K : Type} [DecidableEq K] +lemma exec_on (P : Proc (Fin 3)) (a b c : K) (hab : a≠b) (hac : a≠c) (hbc : b≠c) + (S : Stack K) (A B C : List Bool) (n : ℕ) + (h : Exec P ![S a,S b,S c] ![A,B,C] n) : + Exec (reindex P (triple a b c hab hac hbc)) S (put3 S a b c A B C) n := by + have hh:=exec_reindex P (triple a b c hab hac hbc) S _ _ _ _ _ _ n h + simpa only [frame_triple,put3_same S a b c hab hac hbc] using hh +end MatchingFPRAS.RegisterProc + +namespace MatchingFPRAS.TreeMachine +open TreeData RegisterProc Turing MachineCost + +variable {R Λ : Type} [DecidableEq R] +abbrev K (R : Type) := R⊕Fin 2 +abbrev Env (R : Type) := R→Data + +def encodeEnv (E : Env R) : Stack (K R) + | .inl r => encode (E r) + | .inr _ => [] +def pairEmbedding (i j : R) (hij : i≠j) : Fin 3 ↪ K R := + triple (.inl i) (.inl j) (.inr 0) (by simpa) (by simp) (by simp) +def singleEmbedding (i : R) : Fin 3 ↪ K R := + triple (.inl i) (.inr 0) (.inr 1) (by simp) (by simp) (by simp) + +def putPair (E : Env R) (i j : R) (x y : Data) : Env R := + Function.update (Function.update E i x) j y +lemma encode_putPair (E : Env R) (i j : R) (hij : i≠j) (x y : Data) : + put3 (encodeEnv E) (.inl i) (.inl j) (.inr 0) (encode x) (encode y) []= + encodeEnv (putPair E i j x y) := by + funext k + cases k with + | inr k => fin_cases k <;> simp [put3,encodeEnv] + | inl k => + by_cases hi : k=i <;> by_cases hj : k=j <;> simp_all [put3,encodeEnv,putPair] +lemma encode_putSingle (E : Env R) (i : R) (x : Data) : + put3 (encodeEnv E) (.inl i) (.inr 0) (.inr 1) (encode x) [] []= + encodeEnv (Function.update E i x) := by + funext k + cases k with + | inr k => fin_cases k <;> simp [put3,encodeEnv] + | inl k => by_cases hi : k=i <;> simp_all [put3,encodeEnv] + +inductive Instr (R Λ : Type) where + | halt + | go (next : Λ) + | branch (i : R) (nil cons : Λ) + | nil (i : R) (next : Λ) + | copy (i j : R) (distinct : i≠j) (next : Λ) + | cons (i j : R) (distinct : i≠j) (next : Λ) + | split (i j : R) (distinct : i≠j) (next : Λ) + +def procedure : Instr R Λ → Proc (K R) + | .nil i _ => reindex makeNil (singleEmbedding i) + | .copy i j h _ => reindex RegisterProc.copy (pairEmbedding i j h) + | .cons i j h _ => reindex RegisterProc.cons (pairEmbedding i j h) + | .split i j h _ => reindex RegisterProc.split (pairEmbedding i j h) + | _ => atom .halt + +def successor : Instr R Λ → Option Λ + | .nil _ l | .copy _ _ _ l | .cons _ _ _ l | .split _ _ _ l => some l + | _ => none + +lemma nil_exec (E : Env R) (i : R) (l : Λ) : + Exec (procedure (.nil i l)) (encodeEnv E) (encodeEnv (Function.update E i .nil)) + ((encode (E i)).length+2) := by + have hh:=exec_on (K:=K R) makeNil (.inl i) (.inr 0) (.inr 1) (by simp) (by simp) (by simp) + (encodeEnv E) [false] [] [] _ (makeNil_exec (encode (E i)) [] []) + have he:=encode_putSingle E i .nil + simp only [encode] at he + rwa [he] at hh +lemma copy_exec (E : Env R) (i j : R) (hij : i≠j) (l : Λ) : + Exec (procedure (.copy i j hij l)) (encodeEnv E) (encodeEnv (putPair E i j (E i) (E i))) + ((encode (E j)).length+3*(encode (E i)).length+4) := by + have hh:=exec_on (K:=K R) RegisterProc.copy (.inl i) (.inl j) (.inr 0) (by simpa) (by simp) (by simp) + (encodeEnv E) (encode (E i)) (encode (E i)) [] _ (RegisterProc.copy_exec (encode (E i)) (encode (E j))) + rwa [encode_putPair E i j hij] at hh +lemma cons_exec (E : Env R) (i j : R) (hij : i≠j) (l : Λ) : + Exec (procedure (.cons i j hij l)) (encodeEnv E) (encodeEnv (putPair E i j .nil (.cons (E i) (E j)))) + (2*(encode (E i)).length+3) := by + have hh:=exec_on (K:=K R) RegisterProc.cons (.inl i) (.inl j) (.inr 0) (by simpa) (by simp) (by simp) + (encodeEnv E) (encode .nil) (encode (.cons (E i) (E j))) [] _ (RegisterProc.cons_exec (E i) (E j)) + rwa [encode_putPair E i j hij] at hh +lemma split_exec (E : Env R) (i j : R) (hij : i≠j) (l : Λ) (x y : Data) (he : E j=.cons x y) : + Exec (procedure (.split i j hij l)) (encodeEnv E) (encodeEnv (putPair E i j x y)) + ((encode (E i)).length+2*(encode x).length+4) := by + have h:=RegisterProc.split_exec (encode (E i)) x y + rw [←he] at h + have hh:=exec_on (K:=K R) RegisterProc.split (.inl i) (.inl j) (.inr 0) (by simpa) (by simp) (by simp) + (encodeEnv E) (encode x) (encode y) [] _ h + rwa [encode_putPair E i j hij] at hh +end MatchingFPRAS.TreeMachine + +end OAI diff --git a/lean/OAI/Combinatorics/MatchingCount/Machines/TreeMarkTable.lean b/lean/OAI/Combinatorics/MatchingCount/Machines/TreeMarkTable.lean new file mode 100644 index 0000000000000000000000000000000000000000..6bad45cc34e732be6b9b14ecf1e9e616e3cda9fb --- /dev/null +++ b/lean/OAI/Combinatorics/MatchingCount/Machines/TreeMarkTable.lean @@ -0,0 +1,132 @@ +import Mathlib +import OAI.Combinatorics.MatchingCount.Sampling.TreeProbe +import OAI.Combinatorics.MatchingCount.Sampling.TreeNumericMarking + +namespace OAI + +namespace MatchingFPRAS.ExecutableSource +open TreeTyped TreeFraction TreeTyped.Numbered ExecutableBottleneck ExecutableHierarchy ExecutableRefresh Enlargement RealGeometry ExecutableOptions + +attribute [local instance] NumberedHierarchy.labelOrder +attribute [local instance] Transport.sym2Order Transport.bagEdgeOrder Transport.bagEdgeFintype + +abbrev MarkRowInput := (BagBuildInput×ℕ)×Key +def phantomPart (x : MarkRowInput) : Fraction := + TreeFraction.div (phantomHeight (x.1.1,x.2),(x.1.2,1)) +def phantomPartRealizer : Realizer phantomPart := (composition + (pair (composition (pair first.fst second) phantomHeightRealizer) (pair first.snd (constant 1))) divRealizer).congr (fun _=>rfl) +lemma polynomial_phantomPart : PolynomialTime phantomPartRealizer := by + unfold phantomPartRealizer + apply polynomial_congr + have := polynomial_phantomHeight + have := polynomial_div + dsimp only [Realizer.fst,Realizer.snd] + tree_cost + +def markPortions (x : MarkRowInput) : Fraction×(Fraction×Fraction) := + (realPart (x.1.1,x.2),(TreeFraction.sub (phantomPart x,probePart x),probePart x)) +def markPortionsRealizer : Realizer markPortions := (pair + (composition (pair first.fst second) realPartRealizer) + (pair (composition (pair phantomPartRealizer probePartRealizer) subRealizer) probePartRealizer)).congr (fun _=>rfl) +lemma polynomial_markPortions : PolynomialTime markPortionsRealizer := by + unfold markPortionsRealizer + apply polynomial_congr + have := polynomial_realPart + have := polynomial_phantomPart + have := polynomial_probePart + have := polynomial_sub + dsimp only [Realizer.fst,Realizer.snd] + tree_cost + +lemma markPortions_source {n : ℕ} [Nontrivial (Fin n)] (hn : 2≤n) + (w : Fin n→Fin n→ℚ) (hw : ∀ i j,0(hw a b).le + have hheight : 0≤RationalSource.bagHeight w K e.color := by + unfold RationalSource.bagHeight + positivity + have hD : ((D,1) : Fraction)=TreeFraction.repr (D:ℚ) := by simp [TreeFraction.repr] + have hp : 0≤RationalSource.probePortion w K D e := RationalSource.portions_nonneg w hw K D e 2 + have hsub : RationalSource.probePortion w K D e≤RationalSource.bagHeight w K e.color/D := + sub_nonneg.mp (RationalSource.portions_nonneg w hw K D e 1) + unfold markPortions phantomPart + dsimp only + rw [realPart_source hn w hnon K,phantomHeight_source hn w hnon K, + probePart_source hn w hnon K D,hD,div_repr hheight (Nat.cast_nonneg D), + sub_repr (div_nonneg hheight (Nat.cast_nonneg D)) hp hsub] + rfl + +def threeOptions (x : Fraction×(Fraction×Fraction)) : Options ℕ := + [(0,x.1),(1,x.2.1),(2,x.2.2)] +def threeOptionsRealizer : Realizer threeOptions := (composition + (pair (pair (constant 0) first) + (composition (pair (pair (constant 1) second.fst) + (composition (pair (constant 2) second.snd) listSingleton)) listCons)) listCons).congr (fun _=>rfl) +lemma polynomial_threeOptions : PolynomialTime threeOptionsRealizer := by + unfold threeOptionsRealizer + apply polynomial_congr + have := polynomial_listSingleton (A:=ℕ×Fraction) + dsimp only [Realizer.fst,Realizer.snd] + tree_cost + +def sourceMarkRow (x : MarkRowInput) : Options ℕ := + (threeOptions (markPortions x)).map (fun a=>(a.1,TreeFraction.div (a.2,sourceBagWeight x))) +def sourceMarkRowRealizer : Realizer sourceMarkRow := (composition + (pair sourceBagWeightRealizer (composition markPortionsRealizer threeOptionsRealizer)) + (mapWith (pair second.fst (composition (pair second.snd first) divRealizer)))).congr (fun _=>rfl) +lemma polynomial_sourceMarkRow : PolynomialTime sourceMarkRowRealizer := by + unfold sourceMarkRowRealizer + apply polynomial_congr + have := polynomial_sourceBagWeight + have := polynomial_markPortions + have := polynomial_threeOptions + have := polynomial_div + dsimp only [Realizer.fst,Realizer.snd] + tree_cost +lemma sourceMarkRow_source {n : ℕ} [Nontrivial (Fin n)] (hn : 2≤n) + (w : Fin n→Fin n→ℚ) (hw : ∀ a b,0(hw a b).le) K D] + have hp:=RationalSource.portions_nonneg w hw K D e + have hb:=(RationalSource.bagWeight_pos w hw K D hD e).le + simp only [threeOptions,List.map_cons,List.map_nil,div_repr (hp _) hb] + simp only [ExecutableOptions.repr,RationalSource.markingTable,List.ofFn_succ,List.ofFn_zero] + rfl + +def sourceMarks (x : BagBuildInput×ℕ) : NumericMarking.Tables := + (sourceTables x.1).1.map (fun key=>sourceMarkRow (x,key)) +def sourceMarksRealizer : Realizer sourceMarks := rowsWith sourceMarkRowRealizer + (composition (first (A:=BagBuildInput) (B:=ℕ)) sourceTablesRealizer).fst +lemma polynomial_sourceMarks : PolynomialTime sourceMarksRealizer := + polynomial_rowsWith polynomial_sourceMarkRow + (polynomial_fst (polynomial_composition polynomial_first polynomial_sourceTables)) +lemma sourceMarks_source {n : ℕ} [Nontrivial (Fin n)] (hn : 2≤n) + (w : Fin n→Fin n→ℚ) (hw : ∀ a b,0(hw a b).le) K] + unfold sourceCatalog NumericMarking.tableRep + rw [List.map_ofFn] + congr 1 + funext i + exact sourceMarkRow_source hn w hw K D hD _ + +open TreePost Turing + +theorem sourceMarks_post : ∃ p : Polynomial ℕ,∀ x : BagBuildInput×ℕ,∀ t : ℕ, + p.eval (packed x).length≤t → ∀ coins : Fin t→Bool, + (run (machine sourceMarksRealizer.program) (packed x) coins).state=none ∧ + (run (machine sourceMarksRealizer.program) (packed x) coins).tape.right₀= + ListBlank.mk (packed (sourceMarks x)) := + polynomial_compiles sourceMarksRealizer polynomial_sourceMarks +end MatchingFPRAS.ExecutableSource + +end OAI diff --git a/lean/OAI/Combinatorics/MatchingCount/Machines/TreeMatrix.lean b/lean/OAI/Combinatorics/MatchingCount/Machines/TreeMatrix.lean new file mode 100644 index 0000000000000000000000000000000000000000..57f13be746b6accc9bd0d9d5ba868a66161ac51a --- /dev/null +++ b/lean/OAI/Combinatorics/MatchingCount/Machines/TreeMatrix.lean @@ -0,0 +1,63 @@ +import Mathlib +import OAI.Combinatorics.MatchingCount.Algorithm.TreeWeightsCorrect + +namespace OAI + +namespace MatchingFPRAS.ExecutableSource +open TreeTyped TreeFraction ExecutableBottleneck Enlargement RealGeometry + +abbrev MatrixInput := List WeightedEdge×List RawVertex + +def activityRow (x : MatrixInput×RawVertex) : List Fraction := + x.1.2.map (fun y=>activity (x.1.1,(x.2,y))) +def activityRowRealizer : Realizer activityRow := (composition + (pair (pair first.fst second) first.snd) + (mapWith (composition (pair first.fst (pair first.snd second)) activityRealizer))).congr (fun _=>rfl) +lemma polynomial_activityRow : PolynomialTime activityRowRealizer := by + unfold activityRowRealizer + apply polynomial_congr + have := polynomial_activity + dsimp only [Realizer.fst,Realizer.snd] + tree_cost + +def activityMatrix (x : MatrixInput) : Matrix := x.2.map (fun v=>activityRow (x,v)) +def activityMatrixRealizer : Realizer activityMatrix := composition (pair identity second) (mapWith activityRowRealizer) +lemma polynomial_activityMatrix : PolynomialTime activityMatrixRealizer := by + exact polynomial_composition (polynomial_pair polynomial_identity polynomial_second) + (polynomial_mapWith polynomial_activityRow) + +def materialize (x : PathTableInput) : Matrix := activityMatrix (pathTable x,vertices (x.2,x.1.2)) +def materializeRealizer : Realizer materialize := (composition (pair pathTableRealizer + (composition (pair second first.snd) verticesRealizer)) activityMatrixRealizer).congr (fun _=>rfl) +lemma polynomial_materialize : PolynomialTime materializeRealizer := by + unfold materializeRealizer + apply polynomial_congr + have := polynomial_pathTable + have := polynomial_vertices + have := polynomial_activityMatrix + dsimp only [Realizer.fst,Realizer.snd] + tree_cost + +lemma activityMatrix_repr {N : ℕ} (vs : Fin N→RawVertex) (tab : List WeightedEdge) + (w : Fin N→Fin N→ℚ) (hw : ∀ i j,activity (tab,(vs i,vs j))=TreeFraction.repr (w i j)) : + activityMatrix (tab,List.ofFn vs)=matrixRep w := by + unfold activityMatrix activityRow matrixRep + simp only [List.map_ofFn,Function.comp_def] + congr 1 + funext i + congr 1 + funext j + exact hw i j + +lemma activityMatrix_source_repr {n N : ℕ} [Nontrivial (Fin n)] (hn : 2≤n) + (w : Fin n→Fin n→ℚ) (hw : ∀ i j,0≤w i j) (K : ℕ) (fuel : List Bool) + (hf : fuel.length=2*K+2) (v : Fin N→SourceVertex (Fin n) K) : + activityMatrix (pathTable (((matrixRep w,matrixRep (RationalSource.logicalB w)),fuel),List.range n), + List.ofFn (fun i=>vertexRepr (v i)))= + matrixRep (fun i j=>RationalSource.activity w K (v i) (v j)) := by + apply activityMatrix_repr + intro i j + exact activity_source_repr hn w hw K fuel hf (v i) (v j) +end MatchingFPRAS.ExecutableSource + +end OAI diff --git a/lean/OAI/Combinatorics/MatchingCount/Machines/TreeMetadata.lean b/lean/OAI/Combinatorics/MatchingCount/Machines/TreeMetadata.lean new file mode 100644 index 0000000000000000000000000000000000000000..ec705fc16330c17aabb530c10002953df2d494eb --- /dev/null +++ b/lean/OAI/Combinatorics/MatchingCount/Machines/TreeMetadata.lean @@ -0,0 +1,65 @@ +import Mathlib +import OAI.Combinatorics.MatchingCount.Machines.TreePhantom + +namespace OAI + +namespace MatchingFPRAS.ExecutableHierarchy +open TreeTyped TreeTyped.Numbered ExecutableBottleneck NumberedHierarchy + +attribute [local instance] NumberedHierarchy.labelOrder +variable {V : Type} [Fintype V] [LinearOrder V] +lemma arbitrary_parents_fintype (B : V→V→ℚ) (hB : ∀ a b,0≤B a b) + (hsym : ∀ a b,B a b=B b a) + (htri : ∀ x y z,x≠y → x≠z → y≠z → min (B x z) (B z y)≤B x y) + (xs : List Bool) (H : ℕ) (hH : xs.length=H) (F : Fintype (Label B H)) : + letI := F + parents (matrixRep (fun i j=>B (UnitRefresh.orderedEnum V i) (UnitRefresh.orderedEnum V j)),xs)= + ExecutableDP.parentRep (UnitRefresh.numberedParent (NumberedHierarchy.parent B hsym htri (H:=H))) := by + subst H + have hF : F=ordinaryLabelFintype B xs.length := Subsingleton.elim _ _ + subst F + exact arbitrary_parents B hB hsym htri xs +end MatchingFPRAS.ExecutableHierarchy + +namespace MatchingFPRAS.ExecutableSource +open TreeTyped TreeFraction TreeTyped.Numbered ExecutableBottleneck ExecutableHierarchy ExecutableRefresh Enlargement RealGeometry + +attribute [local instance] NumberedHierarchy.labelOrder +attribute [local instance] Transport.sym2Order Transport.bagEdgeOrder Transport.bagEdgeFintype + +def sourceParents (x : BagBuildInput) : ExecutableDP.Parents := parents (setupHierarchy x).1 +def sourceParentsRealizer : Realizer sourceParents := composition setupHierarchyRealizer.fst parentsRealizer +lemma polynomial_sourceParents : PolynomialTime sourceParentsRealizer := + polynomial_composition (polynomial_fst polynomial_setupHierarchy) polynomial_parents +lemma sourceParents_source {n : ℕ} [Nontrivial (Fin n)] (hn : 2≤n) + (w : Fin n→Fin n→ℚ) (hw : ∀ a b,0≤w a b) (K : ℕ) : + sourceParents (((matrixRep w,List.replicate (2*K+2) false),List.range n),List.replicate (2*K) false)= + ExecutableDP.parentRep (UnitRefresh.numberedParent (RationalSource.parent w K)) := by + unfold sourceParents setupHierarchy + dsimp only + rw [buildClosure_repr hn w hw K,hierarchyFuel_source hn w hw K] + exact arbitrary_parents_fintype (RationalSource.realB w K) + (fun a b=>(by norm_num : (0:ℚ)≤1).trans (RationalSource.realB_floor w K a b)) + (RationalSource.realB_symm w K) (RationalSource.realB_tri w K) + (List.replicate (RationalSource.levels w K) false) (RationalSource.levels w K) + (List.length_replicate ..) (inferInstance : Fintype (RationalSource.Label w K)) + +lemma sourceTables_source {n : ℕ} [Nontrivial (Fin n)] (hn : 2≤n) + (w : Fin n→Fin n→ℚ) (hw : ∀ a b,0≤w a b) (K : ℕ) : + let x : BagBuildInput:=(((matrixRep w,List.replicate (2*K+2) false),List.range n),List.replicate (2*K) false) + sourceTables x=(sourceCatalog (RationalSource.bags w K), + ((setupBags x,ExecutableDP.parentRep (UnitRefresh.numberedParent (RationalSource.parent w K))), + (UnitRefresh.Materialized.plan (UnitRefresh.numberedRank + (fun l : RationalSource.Label w K=>l.1.val))).map Fin.val)) := by + dsimp only + apply Prod.ext + · exact sourceTables_catalog hn w hw K + apply Prod.ext + · apply Prod.ext + · rfl + · exact sourceParents_source hn w hw K + change rankPlan (sourceRanks _)=_ + rw [sourceRanks_source hn w hw K,rankPlan_eq] +end MatchingFPRAS.ExecutableSource + +end OAI diff --git a/lean/OAI/Combinatorics/MatchingCount/Machines/TreeNaturalComb.lean b/lean/OAI/Combinatorics/MatchingCount/Machines/TreeNaturalComb.lean new file mode 100644 index 0000000000000000000000000000000000000000..4c44b6791ecb6f5ae2f8ca12ded4008f88e8e567 --- /dev/null +++ b/lean/OAI/Combinatorics/MatchingCount/Machines/TreeNaturalComb.lean @@ -0,0 +1,68 @@ +import Mathlib +import OAI.Combinatorics.MatchingCount.Arithmetic.TreeNatDivision +import OAI.Combinatorics.MatchingCount.Machines.TreeRepeat + +namespace OAI + +namespace MatchingFPRAS.TreeTyped +open TreeData TreeMachine RegisterProc TreeFunction + +def successor : Realizer Nat.succ := + (composition (pair identity (constant 1)) add).congr (fun _=>rfl) + +def quotient : Realizer (fun x : ℕ×ℕ=>x.1/x.2) := composition division first +def remainder : Realizer (fun x : ℕ×ℕ=>x.1%x.2) := composition division second + +def factStep (x : ℕ×ℕ) : ℕ := x.1*x.2 +lemma fact_countDown (n a : ℕ) : countDown factStep n a=n.factorial*a := by + induction n generalizing a with + | zero => simp [countDown] + | succ n ih => + rw [countDown,ih] + simp only [factStep,Nat.factorial_succ] + ring + +def factorial : Realizer Nat.factorial := + (composition (pair identity (constant 1)) + (iterateDown multiply)).congr (by + intro n + change countDown factStep n 1=_ + rw [fact_countDown,Nat.mul_one]) + +def natChoose : Realizer (fun x : ℕ×ℕ=>x.1.choose x.2) := by + let Q := composition (pair (composition first factorial) + (composition (pair (composition second factorial) (composition subtract factorial)) multiply)) quotient + exact (choose (composition (pair second first) less) Q + (choose (composition (pair first second) less) (constant 0) (constant 1))).congr (by + intro x + change (if decide (x.2pairingStep (i,z)) (1,0)= + (UnitRefresh.pairingCount n,UnitRefresh.pairingCount (n+1)) := by + induction n with + | zero => rfl + | succ n ih => + rw [List.range_succ,List.foldl_append,ih] + simp [pairingStep,UnitRefresh.pairingCount] + +def pairingNumber : Realizer UnitRefresh.pairingCount := + (composition (composition (pair range (constant (1,0))) + (fold (pair (composition second second) + (composition (pair (composition first successor) (composition second first)) multiply)))) first).congr (by + intro n + change ((List.range n).foldl (fun z i=>pairingStep (i,z)) (1,0)).1=_ + rw [pairing_range]) + +end MatchingFPRAS.TreeTyped + +end OAI diff --git a/lean/OAI/Combinatorics/MatchingCount/Machines/TreeNumberedSets.lean b/lean/OAI/Combinatorics/MatchingCount/Machines/TreeNumberedSets.lean new file mode 100644 index 0000000000000000000000000000000000000000..22eb80b3477f081a76be94652cfec6034c7c3f90 --- /dev/null +++ b/lean/OAI/Combinatorics/MatchingCount/Machines/TreeNumberedSets.lean @@ -0,0 +1,20 @@ +import Mathlib +import OAI.Combinatorics.MatchingCount.Tapes.TreeNumberedCodec + +namespace OAI + +namespace MatchingFPRAS.TreeTyped.Numbered +variable {A : Type} [Fintype A] [LinearOrder A] +def embedding : A ↪ ℕ := ⟨index,index_injective⟩ +def set (s : Finset A) : Finset ℕ := s.map embedding +lemma sort_set (s : Finset A) : (set s).sort (·≤·)=(s.sort (·≤·)).map index := by + symm + exact Finset.map_sort embedding s (·≤·) (·≤·) (fun a _ b _=>(index_le a b).symm) +lemma encode_set (s : Finset A) : encode (set s)=encode s := by + rw [encode_finset,sort_set,encode_finset] + change TreeData.ofList (((s.sort (·≤·)).map index).map encode)= + TreeData.ofList ((s.sort (·≤·)).map (fun a=>encode (index a))) + simp only [List.map_map, Function.comp_def] +end MatchingFPRAS.TreeTyped.Numbered + +end OAI diff --git a/lean/OAI/Combinatorics/MatchingCount/Machines/TreeOrderedTransport.lean b/lean/OAI/Combinatorics/MatchingCount/Machines/TreeOrderedTransport.lean new file mode 100644 index 0000000000000000000000000000000000000000..7a78130f76a5e6686ea9234077ab5f27fe5a4d4d --- /dev/null +++ b/lean/OAI/Combinatorics/MatchingCount/Machines/TreeOrderedTransport.lean @@ -0,0 +1,96 @@ +import Mathlib +import OAI.Combinatorics.MatchingCount.Machines.TreeParentTable +import OAI.Combinatorics.MatchingCount.Graphs.TreeHierarchyReindex +import OAI.Combinatorics.MatchingCount.Graphs.TreeRankPlan + +namespace OAI + +namespace MatchingFPRAS.TreeTyped.Numbered +variable {A B C : Type} [Fintype A] [Fintype B] [LinearOrder A] [LinearOrder B] +lemma ordered_lists_transport (e : A≃o B) (f : A→C) (g : B→C) + (h : ∀ a,f a=g (e a)) : + List.ofFn (fun i=>f (UnitRefresh.orderedEnum A i))= + List.ofFn (fun i=>g (UnitRefresh.orderedEnum B i)) := by + apply List.ext_getElem + · simp only [List.length_ofFn] + exact Fintype.card_congr e.toEquiv + · intro i hi hj + simp only [List.length_ofFn] at hi hj + simp only [List.getElem_ofFn,h] + congr 1 + apply index_injective + rw [index_orderIso,index_orderedEnum,index_orderedEnum] +lemma parentTag_transport (e : A≃o B) (o : Option A) : + ExecutableDP.parentTag (o.map (UnitRefresh.orderedEnum A).symm)= + ExecutableDP.parentTag ((o.map e).map (UnitRefresh.orderedEnum B).symm) := by + cases o with + | none=>rfl + | some a=> + change (true,index a)=(true,index (e a)) + rw [index_orderIso] +end MatchingFPRAS.TreeTyped.Numbered + +namespace MatchingFPRAS.NumberedHierarchy +variable {V W : Type} [Fintype V] [Fintype W] [LinearOrder V] [LinearOrder W] +variable (B : W→W→ℚ) (e : V≃o W) +variable (hsym : ∀ a b,B a b=B b a) +variable (htri : ∀ x y z,x≠y → x≠z → y≠z → min (B x z) (B z y)≤B x y) +lemma parent_reindex {H : ℕ} (l : Label (reindex B e) H) : + (parent (reindex B e) (reindex_symm B e hsym) (reindex_tri B e htri) l).map + (labelReindex B e H)=parent B hsym htri (labelReindex B e H l) := by + unfold parent + change (if h : 0hB (e a) (e b)) (reindex_symm B e hsym) (reindex_tri B e htri)] + unfold ExecutableDP.parentRep UnitRefresh.numberedParent + exact ordered_lists_transport (labelOrderReindex B e xs.length) + (fun a=>ExecutableDP.parentTag ((NumberedHierarchy.parent (reindex B e) + (reindex_symm B e hsym) (reindex_tri B e htri) a).map + (UnitRefresh.orderedEnum (Label (reindex B e) xs.length)).symm)) + (fun a=>ExecutableDP.parentTag ((NumberedHierarchy.parent B hsym htri a).map + (UnitRefresh.orderedEnum (Label B xs.length)).symm)) (fun a=>by + rw [parentTag_transport (labelOrderReindex B e xs.length)] + change ExecutableDP.parentTag (Option.map (UnitRefresh.orderedEnum (Label B xs.length)).symm + (Option.map (labelReindex B e xs.length) + (NumberedHierarchy.parent (reindex B e) (reindex_symm B e hsym) (reindex_tri B e htri) a)))=_ + rw [parent_reindex B e hsym htri] + rfl) +include hB in +lemma arbitrary_ranks (xs : List Bool) : + ranks (matrixRep (reindex B (orderedIso V)),xs)= + List.ofFn (UnitRefresh.numberedRank (fun a : Label B xs.length=>a.1.val)) := by + let e:=orderedIso V + rw [ranks_eq _ (fun a b=>hB (e a) (e b))] + exact ordered_lists_transport (labelOrderReindex B e xs.length) (fun a=>a.1.val) (fun a=>a.1.val) (fun _=>rfl) +include hB in +lemma arbitrary_plan (xs : List Bool) : + rankPlan (ranks (matrixRep (reindex B (orderedIso V)),xs))= + (UnitRefresh.Materialized.plan (UnitRefresh.numberedRank + (fun a : Label B xs.length=>a.1.val))).map Fin.val := by + rw [arbitrary_ranks B hB,rankPlan_eq] +end MatchingFPRAS.ExecutableHierarchy + +end OAI diff --git a/lean/OAI/Combinatorics/MatchingCount/Machines/TreePairProposal.lean b/lean/OAI/Combinatorics/MatchingCount/Machines/TreePairProposal.lean new file mode 100644 index 0000000000000000000000000000000000000000..03a108bf69593e81b40e6b35b5f591fbe68b7283 --- /dev/null +++ b/lean/OAI/Combinatorics/MatchingCount/Machines/TreePairProposal.lean @@ -0,0 +1,425 @@ +import Mathlib +import OAI.Combinatorics.MatchingCount.Probability.LocalVariance + +namespace OAI + +namespace MatchingFPRAS.Transport + +section + +open Finset MatchingFPRAS.Replica + +variable {V E : Type*} [Fintype V] [DecidableEq V] [Fintype E] [DecidableEq E] + +variable (ends : E → Sym2 V) + +omit [DecidableEq V] in +lemma cycleProposal_min (w : E → ℝ) + (a b : PM (fun e v => v ∈ ends e) × PM (fun e v => v ∈ ends e)) : + min (pairLaw ends w w a) (pairLaw ends w w b)*cycleProposal a b = + pairLaw ends w w a*cycleProposal a b := by + rw [min_mul_of_nonneg _ _ (cycleProposal_nonneg a b)] + have h := cycleProposal_gibbs w a b + rw [cycleProposal_symmetric b a] at h + change pairLaw ends w w a*cycleProposal a b = pairLaw ends w w b*cycleProposal a b at h + rw [h,min_self] + + + + +theorem pairKernel_energy (hloop : ∀ e, ¬(ends e).IsDiag) + (hpar : ∀ e, (Finset.univ.filter (fun f => ends f = ends e)).card ≤ 2) + (w : E → ℝ) (hw : ∀ e, 0 < w e) (M : PM (fun e v => v ∈ ends e)) + (f g : Finset E → ℝ) : + localEnergy (metropolisCapacity (pairProposal ends hloop hpar) (pairLaw ends w w)) + (fun a => f a.1.val+g a.2.val) = pairDirichlet ends w f g := by + classical + rw [metropolis_energy] + let F := fun a : PM (fun e v => v ∈ ends e) × PM (fun e v => v ∈ ends e) => + f a.1.val+g a.2.val + let π := pairLaw ends w w + let S := ∑ a, ∑ b, min (π a) (π b)*firstLift (switchProposal ends) a b*(F a-F b)^2 + let C := ∑ a, ∑ b, min (π a) (π b)*firstLift (colorProposal ends) a b*(F a-F b)^2 + let Y := ∑ a, ∑ b, min (π a) (π b)*cycleProposal a b*(F a-F b)^2 + have he : localEnergy (offCapacity (pairProposal ends hloop hpar) π) F = (S+C+Y)/6 := by + unfold localEnergy offCapacity + change (∑ a, ∑ b, min (π a) (π b)* + ((firstLift (switchProposal ends) a b+firstLift (colorProposal ends) a b+cycleProposal a b)/3)* + (F a-F b)^2)/2 = _ + dsimp only [S,C,Y] + simp only [add_div,Finset.sum_div,← Finset.sum_add_distrib] + apply Finset.sum_congr rfl; intro a _ + apply Finset.sum_congr rfl; intro b _ + ring + have hs : S/6 = switchDirichlet (inc := fun e v => v ∈ ends e) w f := by + dsimp only [S,π,pairLaw,F] + rw [firstLift_energy _ (fun A => (gibbs_pos w hw A).le) (gibbs_sum w hw M) _ (fun A => f A.val) (fun A => g A.val)] + exact switchProposal_dirichlet ends hloop w f + have hc : C/6 = colorDirichlet ends w f := by + dsimp only [C,π,pairLaw,F] + rw [firstLift_energy _ (fun A => (gibbs_pos w hw A).le) (gibbs_sum w hw M) _ (fun A => f A.val) (fun A => g A.val)] + exact colorProposal_dirichlet ends hloop w f + have hy : Y/6 = cycleDirichlet (inc := fun e v => v ∈ ends e) w f g := by + dsimp only [Y,π] + simp_rw [cycleProposal_min] + simp only [Fintype.sum_prod_type,pairLaw,F] + simpa only [Fintype.sum_prod_type,Finset.mul_sum,mul_assoc] using + cycleProposal_dirichlet (inc := fun e v => v ∈ ends e) w f g + change localEnergy (offCapacity (pairProposal ends hloop hpar) π) F = _ + rw [he,add_div,add_div,hs,hc,hy] + rfl + +end + +section + +open Finset MatchingFPRAS.Replica + +variable {V L : Type*} [Fintype V] [DecidableEq V] [Fintype L] [DecidableEq L] + +variable {bags : V → Finset L} {G : SimpleGraph L} + +noncomputable local instance : Fintype (BagEdge bags) := Fintype.ofFinite _ + +variable (hbags : ∀ v, ∀ a ∈ bags v, ∀ b ∈ bags v, a = b ∨ G.Adj a b) + +variable (hG : G.IsAcyclic) + +noncomputable def treePairProposal : SymmetricProposal (PM (BagEdge.Incident (bags := bags)) × PM (BagEdge.Incident (bags := bags))) := + pairProposal (fun e : BagEdge bags => e.val.val.1) (fun e => e.val.property) + (fun e => BagEdge.parallels_card_le (label_memberships_le_two hbags hG) e) + +noncomputable def treePairLaw (w z : BagEdge bags → ℝ) + (a : PM (BagEdge.Incident (bags := bags)) × PM (BagEdge.Incident (bags := bags))) : ℝ := gibbs w a.1*gibbs z a.2 + +noncomputable def treePairEnergy (w z : BagEdge bags → ℝ) + (f : (PM (BagEdge.Incident (bags := bags)) × PM (BagEdge.Incident (bags := bags))) → ℝ) : ℝ := by + classical + exact localEnergy (metropolisCapacity (treePairProposal hbags hG) (treePairLaw w z)) f + +end + +section + +open Finset MatchingFPRAS.Replica + +variable {V L : Type*} [Fintype V] [DecidableEq V] [Fintype L] [DecidableEq L] + +variable {bags : V → Finset L} {G : SimpleGraph L} + +noncomputable local instance : Fintype (BagEdge bags) := Fintype.ofFinite _ + +variable {hbags : ∀ v, ∀ a ∈ bags v, ∀ b ∈ bags v, a = b ∨ G.Adj a b} + +variable {hG : G.IsAcyclic} + +variable (height : L → ℝ) (hheight : ∀ l, 0 < height l) + +variable (hstep : ∀ a b, G.Adj a b → height a ≤ 2 * height b) + +variable (D : ℝ) (hD : 1 ≤ D) (w : BagEdge bags → ℝ) + +variable (hw : ∀ e, height e.color / D ≤ w e ∧ w e ≤ 3 * height e.color) + +include hheight hstep hD hw hbags hG + +theorem tree_pair_poincare (hN : 2 ≤ Fintype.card V) + (M : PM (BagEdge.Incident (bags := bags))) + (lo hi : ℝ) (hlo : 0 < lo) (hlohi : lo ≤ hi) + (a b : PM (BagEdge.Incident (bags := bags)) → ℝ) : + let wt := fun e => max lo (min hi (w e)) + localVariance (gibbs wt) a ≤ ((10^4:ℝ)*Fintype.card V*D)^100 * + treePairEnergy hbags hG wt wt (fun z => a z.1+b z.2) := by + classical + let wt := fun e => max lo (min hi (w e)) + have hwt : ∀ e, 0 < wt e := fun e => lt_of_lt_of_le hlo (le_max_left _ _) + let af : Finset (BagEdge bags) → ℝ := fun S => if h : MatchingOn BagEdge.Incident S Finset.univ then a ⟨S,h⟩ else 0 + let bf : Finset (BagEdge bags) → ℝ := fun S => if h : MatchingOn BagEdge.Incident S Finset.univ then b ⟨S,h⟩ else 0 + have ha (A : PM (BagEdge.Incident (bags := bags))) : af A.val = a A := by simp [af,A.property] + have hb (A : PM (BagEdge.Incident (bags := bags))) : bf A.val = b A := by simp [bf,A.property] + have ht := CellDemands.pair_energy_inequality (hbags := hbags) (hG := hG) + height hheight hstep D hD w hw lo hi hlo hlohi hN M af bf + have he := pairKernel_energy (fun e : BagEdge bags => e.val.val.1) (fun e => e.val.property) + (fun e => BagEdge.parallels_card_le (label_memberships_le_two hbags hG) e) wt hwt M af bf + have he' : treePairEnergy hbags hG wt wt (fun z => af z.1.val+bf z.2.val) = + pairDirichlet (fun e : BagEdge bags => e.val.val.1) wt af bf := by + unfold treePairEnergy treePairProposal treePairLaw + unfold pairLaw at he + convert he using 1 + congr 4 <;> first | rfl | exact Subsingleton.elim _ _ + change localVariance (gibbs wt) a ≤ _ + change localVariance (gibbs wt) (fun A => af A.val) ≤ _ at ht + simp_rw [ha,hb] at he' ht + exact ht.trans_eq (congrArg (fun z => ((10^4:ℝ)*Fintype.card V*D)^100*z) he'.symm) + +end + +open Finset MatchingFPRAS.Replica + +variable {V L : Type*} [Fintype V] [DecidableEq V] [Fintype L] [DecidableEq L] + +variable {bags : V → Finset L} {G : SimpleGraph L} + +noncomputable local instance : Fintype (BagEdge bags) := Fintype.ofFinite _ + +variable {hbags : ∀ v, ∀ a ∈ bags v, ∀ b ∈ bags v, a = b ∨ G.Adj a b} + +variable {hG : G.IsAcyclic} + +variable (height : L → ℝ) (hheight : ∀ l, 0 < height l) + +variable (hstep : ∀ a b, G.Adj a b → height a ≤ 2 * height b) + +variable (D : ℝ) (hD : 1 ≤ D) (w : BagEdge bags → ℝ) + +variable (hw : ∀ e, height e.color / D ≤ w e ∧ w e ≤ 3 * height e.color) + +include hheight hstep hD hw hbags hG + +theorem adjacent_tree_pair_poincare (hN : 2 ≤ Fintype.card V) + (M : PM (BagEdge.Incident (bags := bags))) (t : ℕ) + (a b : PM (BagEdge.Incident (bags := bags)) → ℝ) : + let c : ℝ := 1+((Fintype.card V:ℝ)^2)⁻¹ + let upper := fun e => tierClamp c (t+1) (w e) + let lower := fun e => tierClamp c t (w e) + localVariance (gibbs upper) a ≤ (2*((10^4:ℝ)*Fintype.card V*D)^100) * + treePairEnergy hbags hG upper lower (fun z => a z.1+b z.2) := by + classical + let c : ℝ := 1+((Fintype.card V:ℝ)^2)⁻¹ + have hc : 1 ≤ c := by + dsimp [c]; have : 0 ≤ ((Fintype.card V:ℝ)^2)⁻¹ := by positivity + linarith + have hc0 : 0 < c := lt_of_lt_of_le (by norm_num) hc + have hp1 : 1 ≤ c^(t+1) := one_le_pow₀ hc + have hp0 : 0 < c^(t+1) := pow_pos hc0 _ + have hilo : (c^(t+1))⁻¹ ≤ c^(t+1) := (inv_le_one₀ hp0).mpr hp1 |>.trans hp1 + let upper := fun e => tierClamp c (t+1) (w e) + let lower := fun e => tierClamp c t (w e) + have hupper : ∀ e, 0 < upper e := fun e => tierClamp_pos hc0 _ _ + have hwpos : ∀ e, 0 < w e := fun e => + lt_of_lt_of_le (div_pos (hheight e.color) (lt_of_lt_of_le (by norm_num) hD)) (hw e).1 + have hv := tree_pair_poincare (hbags := hbags) (hG := hG) + height hheight hstep D hD w hw hN M (c^(t+1))⁻¹ (c^(t+1)) (inv_pos.mpr hp0) hilo a b + change localVariance (gibbs upper) a ≤ ((10^4:ℝ)*Fintype.card V*D)^100 * + treePairEnergy hbags hG upper upper (fun z => a z.1+b z.2) at hv + have hd (z : PM (BagEdge.Incident (bags := bags)) × PM (BagEdge.Incident (bags := bags))) : + (1/2:ℝ)*treePairLaw upper upper z ≤ treePairLaw upper lower z := by + have h := (adjacent_gibbs (fun e : BagEdge bags => e.val.val.1) (fun e => e.val.property) + hN w hwpos t z.2).1 + change gibbs upper z.2/2 ≤ gibbs lower z.2 at h + have h := mul_le_mul_of_nonneg_left h (gibbs_pos upper hupper z.1).le + dsimp only [treePairLaw] + nlinarith only [h] + have he := metropolis_energy_domination (treePairProposal hbags hG) + (treePairLaw upper upper) (treePairLaw upper lower) (1/2) (by norm_num) hd + (fun z => a z.1+b z.2) + change (1/2:ℝ)*treePairEnergy hbags hG upper upper (fun z => a z.1+b z.2) ≤ + treePairEnergy hbags hG upper lower (fun z => a z.1+b z.2) at he + have hL : 0 ≤ ((10^4:ℝ)*Fintype.card V*D)^100 := by positivity + have hh := mul_le_mul_of_nonneg_left he hL + change localVariance (gibbs upper) a ≤ _ + nlinarith only [hv,hh] + +end MatchingFPRAS.Transport + +namespace MatchingFPRAS.Replica.Ladder + +open Finset + +abbrev Slot (T q : ℕ) := Lex (Fin (T+1) × Fin q) + +def rank {T q : ℕ} (x : Slot T q) : ℕ := (ofLex x).1.val + +def tier {T q : ℕ} (x : Slot T q) : ℕ := T-rank x + +def base (T q : ℕ) : Finset (Slot T q) := Finset.univ.image (fun j => toLex (⟨T,by omega⟩,j)) + +def guides {T q : ℕ} (x : Slot T q) : Finset (Slot T q) := + if h : rank x < T then Finset.univ.image (fun j => toLex (⟨rank x+1,by omega⟩,j)) else ∅ + +lemma rank_le {T q : ℕ} (x : Slot T q) : rank x ≤ T := by + have h := (ofLex x).1.isLt + dsimp [rank]; omega + +lemma mem_base {T q : ℕ} (x : Slot T q) : x ∈ base T q ↔ rank x = T := by + constructor + · rintro hx + obtain ⟨j,_,hj⟩ := Finset.mem_image.mp hx + rw [← hj]; rfl + · intro hx + apply Finset.mem_image.mpr + refine ⟨(ofLex x).2,Finset.mem_univ _,?_⟩ + apply ofLex.injective + apply Prod.ext + · apply Fin.ext; exact hx.symm + · rfl + +lemma base_card (T q : ℕ) : (base T q).card = q := by + rw [base,Finset.card_image_of_injective] + · simp + · intro j k h + exact congrArg (fun x : Slot T q => (ofLex x).2) h + +lemma base_nonempty (T q : ℕ) (hq : 0 < q) : (base T q).Nonempty := by + rw [← Finset.card_pos,base_card] + exact hq + +lemma guides_base {T q : ℕ} (x : Slot T q) (hx : x ∈ base T q) : guides x = ∅ := by + simp [guides,(mem_base x).mp hx] + +lemma guides_card {T q : ℕ} (x : Slot T q) (hx : x ∉ base T q) : (guides x).card = q := by + have h : rank x < T := lt_of_le_of_ne (rank_le x) (fun he => hx ((mem_base x).mpr he)) + rw [guides,dite_eq_left h,Finset.card_image_of_injective] + · simp + · intro j k h + exact congrArg (fun x : Slot T q => (ofLex x).2) h + +lemma guides_order {T q : ℕ} (x y : Slot T q) (hy : y ∈ guides x) : x < y := by + unfold guides at hy + split_ifs at hy with h + · obtain ⟨j,_,rfl⟩ := Finset.mem_image.mp hy + exact Prod.Lex.left (ofLex x).2 j (show (ofLex x).1 < ⟨rank x+1,by omega⟩ from by + change rank x < rank x+1; omega) + · simp at hy + +lemma guides_tier {T q : ℕ} (x y : Slot T q) (hy : y ∈ guides x) : tier x = tier y+1 := by + unfold guides at hy + split_ifs at hy with h + · obtain ⟨j,_,rfl⟩ := Finset.mem_image.mp hy + simp only [tier,rank] + change T-rank x = T-(rank x+1)+1 + omega + · simp at hy + +lemma slots_card (T q : ℕ) : Fintype.card (Slot T q) = (T+1)*q := by + rw [Fintype.card_congr (ofLex : Slot T q ≃ Fin (T+1) × Fin q)] + simp + +lemma updates_count (T q : ℕ) : (∑ x : Slot T q, (guides x).card)+(base T q).card = T*q^2+q := by + classical + have hc : ((base T q)ᶜ).card = T*q := by + rw [Finset.card_compl,slots_card,base_card,Nat.add_mul,one_mul,Nat.add_sub_cancel] + have hs : ∑ x : Slot T q, (guides x).card = T*q*q := by + rw [← Finset.sum_add_sum_compl (base T q)] + have hb : (∑ x ∈ base T q, (guides x).card) = 0 := by + apply Finset.sum_eq_zero; intro x hx; rw [guides_base x hx]; rfl + have hg : (∑ x ∈ (base T q)ᶜ, (guides x).card) = ∑ x ∈ (base T q)ᶜ, q := by + apply Finset.sum_congr rfl; intro x hx + exact guides_card x (Finset.mem_compl.mp hx) + rw [hb,hg,Finset.sum_const,smul_eq_mul,hc,zero_add] + rw [hs,base_card]; ring + +end MatchingFPRAS.Replica.Ladder + +namespace MatchingFPRAS.Transport + +section + +open Finset MatchingFPRAS.Replica MatchingFPRAS.Replica.Ladder + +variable {V J : Type*} [Fintype V] [DecidableEq V] [Fintype J] [DecidableEq J] + +variable {bags : V → Finset J} {G : SimpleGraph J} + +noncomputable local instance : Fintype (BagEdge bags) := Fintype.ofFinite _ + +noncomputable def tierBase (V : Type*) [Fintype V] : ℝ := 1+((Fintype.card V:ℝ)^2)⁻¹ + +lemma tierBase_pos (V : Type*) [Fintype V] : 0 < tierBase V := by + unfold tierBase; positivity + +noncomputable def slotWeight {T q : ℕ} (w : BagEdge bags → ℝ) (x : Slot T q) (e : BagEdge bags) : ℝ := + tierClamp (tierBase V) (tier x) (w e) + +omit [DecidableEq V] [Fintype J] [DecidableEq J] in +lemma slotWeight_pos {T q : ℕ} (w : BagEdge bags → ℝ) (x : Slot T q) (e : BagEdge bags) : + 0 < slotWeight w x e := tierClamp_pos (tierBase_pos V) _ _ + +noncomputable def slotLaw {T q : ℕ} (w : BagEdge bags → ℝ) (x : Slot T q) + (A : PM (BagEdge.Incident (bags := bags))) : ℝ := gibbs (slotWeight w x) A + +omit [DecidableEq V] [DecidableEq J] in +lemma slotLaw_pos {T q : ℕ} (w : BagEdge bags → ℝ) (x : Slot T q) + (A : PM (BagEdge.Incident (bags := bags))) : 0 < slotLaw w x A := gibbs_pos _ (slotWeight_pos w x) A + +omit [DecidableEq V] [DecidableEq J] in +lemma slotLaw_sum {T q : ℕ} (w : BagEdge bags → ℝ) (x : Slot T q) + (M : PM (BagEdge.Incident (bags := bags))) : (∑ A, slotLaw w x A) = 1 := + gibbs_sum _ (slotWeight_pos w x) M + +variable (hbags : ∀ v, ∀ a ∈ bags v, ∀ b ∈ bags v, a = b ∨ G.Adj a b) + +variable (hG : G.IsAcyclic) + +noncomputable def treeLadderCapacity {T q : ℕ} (w : BagEdge bags → ℝ) (x y : Slot T q) : + PairCapacity (slotLaw w) x y := by + classical + let π : (PM (BagEdge.Incident (bags := bags)) × PM (BagEdge.Incident (bags := bags))) → ℝ := + fun a => slotLaw w x a.1*slotLaw w y a.2 + exact { + q := metropolisCapacity (treePairProposal hbags hG) π + nonneg := metropolisCapacity_nonneg _ _ (fun a => mul_nonneg (slotLaw_pos w x a.1).le (slotLaw_pos w y a.2).le) + row := metropolisCapacity_row _ _ + col := metropolisCapacity_col _ _ } + +end + +open Finset MatchingFPRAS.Replica MatchingFPRAS.Replica.Ladder + +variable {V J : Type*} [Fintype V] [DecidableEq V] [Fintype J] [DecidableEq J] + +variable {bags : V → Finset J} {G : SimpleGraph J} + +noncomputable local instance : Fintype (BagEdge bags) := Fintype.ofFinite _ + +variable {hbags : ∀ v, ∀ a ∈ bags v, ∀ b ∈ bags v, a = b ∨ G.Adj a b} + +variable {hG : G.IsAcyclic} + +variable (height : J → ℝ) (hheight : ∀ l, 0 < height l) + +variable (hstep : ∀ a b, G.Adj a b → height a ≤ 2 * height b) + +variable (D : ℕ) (hD : 1 ≤ D) (w : BagEdge bags → ℝ) + +variable (hw : ∀ e, height e.color / D ≤ w e ∧ w e ≤ 3 * height e.color) + +include hheight hstep hD hw hbags hG + +theorem concrete_ladder_poincare (hN : 2 ≤ Fintype.card V) + (M₀ : PM (BagEdge.Incident (bags := bags))) (T : ℕ) + (f : (Slot T (32*(10^4*Fintype.card V*D)^100) → PM (BagEdge.Incident (bags := bags))) → ℝ) : + let q := 32*(10^4*Fintype.card V*D)^100 + MatchingFPRAS.Replica.variance (slotLaw w) f ≤ ((8*(T*q^2+q):ℕ):ℝ)/3 * + scanEnergy (slotLaw w) guides (base T q) (treeLadderCapacity hbags hG w) f := by + classical + let q : ℕ := 32*(10^4*Fintype.card V*D)^100 + let L : ℝ := ((10^4:ℝ)*Fintype.card V*D)^100 + have hDc : (1:ℝ) ≤ (D:ℝ) := by exact_mod_cast hD + have hNp : 0 < (Fintype.card V:ℝ) := by exact_mod_cast (lt_of_lt_of_le (by decide : 0 < 2) hN) + have hDp : 0 < (D:ℝ) := lt_of_lt_of_le (by norm_num) hDc + have hL : 0 < L := by dsimp [L]; positivity + have hq : (q:ℝ) = 32*L := by norm_num [q,L,Nat.cast_mul,Nat.cast_pow] + have hqn : 0 < q := by + have : (0:ℝ) < (q:ℝ) := by rw [hq]; positivity + exact_mod_cast this + have hQ : ∀ x y : Slot T q, y ∈ guides x → + PairPoincare (slotLaw w) x y (treeLadderCapacity hbags hG w x y) (2*L) := by + intro x y hy a b + have ht := adjacent_tree_pair_poincare (hbags := hbags) (hG := hG) + height hheight hstep (D:ℝ) hDc w hw hN M₀ (tier y) a b + change localVariance (gibbs (slotWeight w x)) a ≤ (2*L)* + treePairEnergy hbags hG (slotWeight w x) (slotWeight w y) (fun z => a z.1+b z.2) + unfold slotWeight + rw [guides_tier x y hy] + exact ht + have hh := replica_gap (slotLaw w) (fun x A => (slotLaw_pos w x A).le) + (fun x => slotLaw_sum w x M₀) guides (base T q) (base_nonempty T q hqn) + q L hL hq (fun x hx => guides_card x hx) (fun x hx => guides_base x hx) + (fun x y hy => guides_order x y hy) (treeLadderCapacity hbags hG w) hQ f + rw [updates_count] at hh + simpa only [Nat.cast_mul,Nat.cast_ofNat] using hh + +end MatchingFPRAS.Transport + +end OAI diff --git a/lean/OAI/Combinatorics/MatchingCount/Machines/TreeParentTable.lean b/lean/OAI/Combinatorics/MatchingCount/Machines/TreeParentTable.lean new file mode 100644 index 0000000000000000000000000000000000000000..9e6b9bb13ab5785a2e6c34c8a7efe068b9c9741f --- /dev/null +++ b/lean/OAI/Combinatorics/MatchingCount/Machines/TreeParentTable.lean @@ -0,0 +1,113 @@ +import Mathlib +import OAI.Combinatorics.MatchingCount.Sampling.TreeDPProgram +import OAI.Combinatorics.MatchingCount.Machines.TreeIndex +import OAI.Combinatorics.MatchingCount.Machines.TreeLabelCorrect + +namespace OAI + +namespace MatchingFPRAS.ExecutableHierarchy +open TreeTyped TreeFraction ExecutableBottleneck + +def parentKey (x : HierarchyInput×LabelKey) : LabelKey := + (x.2.1-1,labelRoot (x.1,(x.2.1-1,x.2.2))) +def parentKeyRealizer : Realizer parentKey := by + let p : Realizer (fun x : HierarchyInput×LabelKey=>(x.2.1-1,x.2.2)) := pair (composition second.fst predecessor) second.snd + exact (pair (composition second.fst predecessor) (composition (pair first p) labelRootRealizer)).congr (fun _=>rfl) +lemma polynomial_parentKey : PolynomialTime parentKeyRealizer := by + unfold parentKeyRealizer Realizer.fst Realizer.snd + dsimp only + apply polynomial_congr + have := polynomial_predecessor + have := polynomial_labelRoot + tree_cost + +def parentEntry (x : (HierarchyInput×List LabelKey)×LabelKey) : Bool×ℕ := + if x.2.1=0 then (false,0) else (true,x.1.2.idxOf (parentKey (x.1.1,x.2))) +def parentEntryRealizer : Realizer parentEntry := + (choose (composition (pair second.fst (constant 0)) natEqual) (constant (false,0)) + (pair (constant true) (composition (pair (composition (pair first.fst second) parentKeyRealizer) first.snd) + (indexOf (pairEqual natEqual natEqual))))).congr (fun x=>by simp only [parentEntry,Function.comp_apply,decide_eq_true_eq]) +lemma polynomial_parentEntry : PolynomialTime parentEntryRealizer := by + unfold parentEntryRealizer Realizer.fst Realizer.snd + apply polynomial_congr + have := polynomial_parentKey + have := polynomial_indexOf (polynomial_pairEqual polynomial_natEqual polynomial_natEqual) + tree_cost + +def parents (x : HierarchyInput) : ExecutableDP.Parents := + (labels x).map fun l=>parentEntry ((x,labels x),l) +def parentsRealizer : Realizer parents := composition (pair (pair identity labelsRealizer) labelsRealizer) (mapWith parentEntryRealizer) +lemma polynomial_parents : PolynomialTime parentsRealizer := by + unfold parentsRealizer + exact polynomial_composition (polynomial_pair (polynomial_pair polynomial_identity polynomial_labels) polynomial_labels) + (polynomial_mapWith polynomial_parentEntry) + +def ranks (x : HierarchyInput) : List ℕ := (labels x).map Prod.fst +def ranksRealizer : Realizer ranks := composition labelsRealizer (map first) +lemma polynomial_ranks : PolynomialTime ranksRealizer := polynomial_composition polynomial_labels (polynomial_map polynomial_first) + +lemma idxOf_map_inj {A C : Type} [BEq A] [LawfulBEq A] [BEq C] [LawfulBEq C] (f : A→C) + (hf : Function.Injective f) (a : A) (xs : List A) : (xs.map f).idxOf (f a)=xs.idxOf a := by + induction xs with + | nil=>simp + | cons b bs ih=> + simp only [List.map_cons,List.idxOf_cons] + have he : (f b==f a)=(b==a) := by apply Bool.eq_iff_iff.mpr; simp only [beq_iff_eq, hf.eq_iff] + rw [he,ih] + +local instance {n H : ℕ} (B : Fin n→Fin n→ℚ) : LinearOrder (NumberedHierarchy.Label B H) := NumberedHierarchy.labelOrder B H +local instance (priority := 2000) {n H : ℕ} (B : Fin n→Fin n→ℚ) : LE (NumberedHierarchy.Label B H) := (NumberedHierarchy.labelOrder B H).toLE +lemma index_key {n : ℕ} (B : Fin n→Fin n→ℚ) (hB : ∀ a b,0 ≤ B a b) + (xs : List Bool) (a : NumberedHierarchy.Label B xs.length) : + (labels (matrixRep B,xs)).idxOf (key a)=((UnitRefresh.orderedEnum (NumberedHierarchy.Label B xs.length)).symm a).val := by + rw [labels_eq_ofFn B hB] + let e := UnitRefresh.orderedEnum (NumberedHierarchy.Label B xs.length) + let i := e.symm a + have hn := List.nodup_ofFn.mpr ((key_injective B).comp e.injective) + have hi : i.val < (List.ofFn (fun j=>key (e j))).length := by simpa only [List.length_ofFn] using i.isLt + have he := @List.Nodup.idxOf_getElem LabelKey (inferInstance : BEq LabelKey) inferInstance _ hn i.val hi + simp only [List.getElem_ofFn,Fin.eta,i,Function.comp_apply,Equiv.apply_symm_apply] at he + convert he using 1 + rfl + +lemma parentKey_eq {n : ℕ} (B : Fin n→Fin n→ℚ) (hB : ∀ a b,0 ≤ B a b) + (hsym : ∀ a b,B a b=B b a) + (htri : ∀ x y z,x≠y → x≠z → y≠z → min (B x z) (B z y)≤B x y) + (xs : List Bool) (a : NumberedHierarchy.Label B xs.length) (ha : 0a.1.val)) := by + unfold ranks + rw [labels_eq_ofFn B hB,List.map_ofFn] + rfl +end MatchingFPRAS.ExecutableHierarchy + +end OAI diff --git a/lean/OAI/Combinatorics/MatchingCount/Machines/TreePartialChoice.lean b/lean/OAI/Combinatorics/MatchingCount/Machines/TreePartialChoice.lean new file mode 100644 index 0000000000000000000000000000000000000000..52f0bc2133979125b2991220f1ad556d7c00d905 --- /dev/null +++ b/lean/OAI/Combinatorics/MatchingCount/Machines/TreePartialChoice.lean @@ -0,0 +1,80 @@ +import Mathlib +import OAI.Combinatorics.MatchingCount.Arithmetic.TreeSubtract +import OAI.Combinatorics.MatchingCount.Machines.TreeChoice + +namespace OAI + +namespace MatchingFPRAS.TreeTyped +open TreeData TreeMachine RegisterProc TreeFunction + +variable {A B : Type} [Codec A] [Codec B] + +def choosePartial (f : A → Bool) (g h : A → B) (F : Realizer f) + (G H : Proc (K Reg)) (t u : A → ℕ) + (hg : ∀ a s,f a=true → Exec G (encodeEnv (env (encode a) .nil s)) + (encodeEnv (env (encode (g a)) .nil s)) (t a)) + (hh : ∀ a s,f a=false → Exec H (encodeEnv (env (encode a) .nil s)) + (encodeEnv (env (encode (h a)) .nil s)) (u a)) : + Realizer (fun a=>if f a then g a else h a) where + program := seq (TreeFunction.copy 0 1 (by decide)) (seq (TreeFunction.cons 1 2 (by decide)) + (seq F.program (RegisterStructured.select 0 + (seq (TreeFunction.split 0 2 (by decide)) H) + (seq (TreeFunction.split 0 2 (by decide)) G)))) + cost := fun a=>F.cost a+(if f a then t a else u a)+7*TreeFunction.size (encode a)+18 + correct := by + intro a s + have h1:=copy01 (encode a) .nil s + have h2:=cons12 (encode a) (encode a) s + have h3:=F.correct a (.cons (encode a) s) + have h4:=split02 (encode (f a)) .nil (encode a) s + have hs : TreeFunction.size (encode (f a)) ≤ 3 := by + cases f a <;> simp [Codec.encode,bit] + cases hf : f a + · have h5:=hh a s hf + have hh':=RegisterStructured.select_nil 0 _ (seq (TreeFunction.split 0 2 (by decide)) G) + (env (encode (f a)) .nil (.cons (encode a) s)) (env (encode (h a)) .nil s) _ + (by simp [hf,Codec.encode,bit]) (h4.seq h5) + simp only [hf,Bool.false_eq_true,↓reduceIte] + apply (h1.seq (h2.seq (h3.seq hh'))).mono + simp only [hf,size_nil] + rw [hf] at hs + omega + · have h5:=hg a s hf + have hh':=RegisterStructured.select_cons 0 (seq (TreeFunction.split 0 2 (by decide)) H) _ + (env (encode (f a)) .nil (.cons (encode a) s)) (env (encode (g a)) .nil s) _ + .nil .nil (by simp [hf,Codec.encode,bit]) (h4.seq h5) + simp only [hf,↓reduceIte] + apply (h1.seq (h2.seq (h3.seq hh'))).mono + simp only [hf,size_nil] + rw [hf] at hs + omega + +def subProgram : Proc (K Reg) := seq (TreeFunction.split 1 0 (by decide)) + (seq (TreeArithmetic.sub 1 0 (by decide)) + (seq (TreeFunction.copy 1 0 (by decide)) (TreeFunction.clear 1))) +def subCost (ab : ℕ×ℕ) : ℕ := 2*TreeFunction.size (nat ab.1)+ + 9*(ab.1.bits.length+ab.2.bits.length)+4*TreeFunction.size (nat (ab.1-ab.2))+32 +lemma subProgram_exec (a b : ℕ) (s : Data) (hab : b ≤ a) : + Exec subProgram (encodeEnv (env (encode (a,b)) .nil s)) + (encodeEnv (env (nat (a-b)) .nil s)) (subCost (a,b)) := by + have h1:=split10 (nat a) (nat b) .nil s + have h2:=TreeArithmetic.sub_exec (env (nat b) (nat a) s) 1 0 (by decide) a b rfl rfl hab + simp only [putPair,env_update0,env_update1] at h2 + have h3:=copy10 .nil (nat (a-b)) s + have h4:=clear1 (nat (a-b)) (nat (a-b)) s + apply (h1.seq (h2.seq (h3.seq h4))).mono + simp only [size_nil,subCost]; omega + +def subtract : Realizer (fun ab : ℕ×ℕ=>ab.1-ab.2) := by + let Z : Realizer (fun _ : ℕ×ℕ=>0) := constant 0 + let P:=choosePartial (fun ab : ℕ×ℕ=>decide (ab.10) (fun ab=>ab.1-ab.2) + less Z.program subProgram Z.cost subCost (fun a s _=>Z.correct a s) + (fun a s h=>subProgram_exec a.1 a.2 s (by simpa only [decide_eq_false_iff_not,not_lt] using h)) + refine ⟨P.program,P.cost,?_⟩ + intro ab stack + by_cases hlt : ab.1B (UnitRefresh.orderedEnum V i) (UnitRefresh.orderedEnum V j)),xs)= + List.ofFn (UnitRefresh.numberedRank (fun a : Label B H=>a.1.val)) := by + subst H + have hF : F=ordinaryLabelFintype B xs.length := Subsingleton.elim _ _ + subst F + exact arbitrary_ranks B hB xs +end MatchingFPRAS.ExecutableHierarchy + +namespace MatchingFPRAS.ExecutableSource +open TreeTyped TreeFraction TreeTyped.Numbered ExecutableBottleneck ExecutableHierarchy ExecutableRefresh Enlargement RealGeometry + +attribute [local instance] NumberedHierarchy.labelOrder +attribute [local instance] Transport.sym2Order Transport.bagEdgeOrder Transport.bagEdgeFintype + +def sourceRanks (x : BagBuildInput) : List ℕ := ranks (setupHierarchy x).1 +def sourceRanksRealizer : Realizer sourceRanks := composition setupHierarchyRealizer.fst ranksRealizer +lemma polynomial_sourceRanks : PolynomialTime sourceRanksRealizer := + polynomial_composition (polynomial_fst polynomial_setupHierarchy) polynomial_ranks +lemma sourceRanks_source {n : ℕ} [Nontrivial (Fin n)] (hn : 2≤n) + (w : Fin n→Fin n→ℚ) (hw : ∀ a b,0≤w a b) (K : ℕ) : + sourceRanks (((matrixRep w,List.replicate (2*K+2) false),List.range n),List.replicate (2*K) false)= + List.ofFn (UnitRefresh.numberedRank (fun a : RationalSource.Label w K=>a.1.val)) := by + unfold sourceRanks setupHierarchy + dsimp only + rw [buildClosure_repr hn w hw K,hierarchyFuel_source hn w hw K] + exact arbitrary_ranks_fintype (RationalSource.realB w K) + (fun a b=>(by norm_num : (0:ℚ)≤1).trans (RationalSource.realB_floor w K a b)) + (List.replicate (RationalSource.levels w K) false) (RationalSource.levels w K) + (List.length_replicate ..) (inferInstance : Fintype (RationalSource.Label w K)) + +lemma rankLookup {L : Type} [Fintype L] [LinearOrder L] (rank : L→ℕ) (l : L) : + (List.ofFn (UnitRefresh.numberedRank rank)).getD (index l) 0=rank l := by + simp only [UnitRefresh.numberedRank,index,List.getD,List.getElem?_ofFn, + ((UnitRefresh.orderedEnum L).symm l).isLt,↓reduceDIte,Fin.eta,Option.getD_some,Equiv.apply_symm_apply] + +def sourceRank (x : BagBuildInput×Key) : ℕ := (sourceRanks x.1).getD x.2.2 0 +def sourceRankRealizer : Realizer sourceRank := composition + (pair (composition first sourceRanksRealizer) second.snd) (getDFast 0) +lemma polynomial_sourceRank : PolynomialTime sourceRankRealizer := + polynomial_composition (polynomial_pair (polynomial_composition polynomial_first polynomial_sourceRanks) + (polynomial_snd polynomial_second)) (polynomial_getDFast 0) +lemma sourceRank_source {n : ℕ} [Nontrivial (Fin n)] (hn : 2≤n) + (w : Fin n→Fin n→ℚ) (hw : ∀ a b,0≤w a b) (K : ℕ) + (e : Transport.BagEdge (RationalSource.bags w K)) : + sourceRank ((((matrixRep w,List.replicate (2*K+2) false),List.range n),List.replicate (2*K) false),sourceKey e)= + e.color.1.val := by + unfold sourceRank + dsimp only + rw [sourceRanks_source hn w hw K] + exact rankLookup _ _ + +def phantomHeight (x : BagBuildInput×Key) : Fraction := threshold (x.1.2,sourceRank x) +def phantomHeightRealizer : Realizer phantomHeight := composition + (pair first.snd sourceRankRealizer) thresholdRealizer +lemma polynomial_phantomHeight : PolynomialTime phantomHeightRealizer := + polynomial_composition (polynomial_pair (polynomial_snd polynomial_first) polynomial_sourceRank) + polynomial_threshold +lemma phantomHeight_source {n : ℕ} [Nontrivial (Fin n)] (hn : 2≤n) + (w : Fin n→Fin n→ℚ) (hw : ∀ a b,0≤w a b) (K : ℕ) + (e : Transport.BagEdge (RationalSource.bags w K)) : + phantomHeight ((((matrixRep w,List.replicate (2*K+2) false),List.range n),List.replicate (2*K) false),sourceKey e)= + TreeFraction.repr (RationalSource.bagHeight w K e.color) := by + unfold phantomHeight + dsimp only + rw [sourceRank_source hn w hw K] + apply threshold_repr + rw [List.length_replicate] + have h:=e.color.1.isLt + have hh : RationalSource.levels w K≤2*K:=Nat.findGreatest_le _ + omega + +def sourceBagWeight (x : (BagBuildInput×ℕ)×Key) : Fraction := + TreeFraction.add (realPart (x.1.1,x.2), + TreeFraction.div (phantomHeight (x.1.1,x.2),(x.1.2,1))) +def sourceBagWeightRealizer : Realizer sourceBagWeight := (composition + (pair (composition (pair first.fst second) realPartRealizer) + (composition (pair (composition (pair first.fst second) phantomHeightRealizer) + (pair first.snd (constant 1))) divRealizer)) addRealizer).congr (fun _=>rfl) +lemma polynomial_sourceBagWeight : PolynomialTime sourceBagWeightRealizer := by + unfold sourceBagWeightRealizer Realizer.fst Realizer.snd + apply polynomial_congr + have := polynomial_realPart + have := polynomial_phantomHeight + have := polynomial_div + have := TreeFraction.polynomial_add + tree_cost +lemma sourceBagWeight_source {n : ℕ} [Nontrivial (Fin n)] (hn : 2≤n) + (w : Fin n→Fin n→ℚ) (hw : ∀ a b,0≤w a b) (K D : ℕ) + (e : Transport.BagEdge (RationalSource.bags w K)) : + sourceBagWeight (((((matrixRep w,List.replicate (2*K+2) false),List.range n),List.replicate (2*K) false),D),sourceKey e)= + TreeFraction.repr (RationalSource.bagWeight w K D e) := by + unfold sourceBagWeight + dsimp only + rw [realPart_source hn w hw K,phantomHeight_source hn w hw K] + have hreal : 0≤RationalSource.realPortion w K e := by + unfold RationalSource.realPortion + apply Finset.sum_nonneg + intro a _ + split_ifs <;> first | exact pathActivity_nonneg hn w hw K _ _ | exact le_rfl + have hh : 0≤RationalSource.bagHeight w K e.color := by unfold RationalSource.bagHeight; positivity + have hD : ((D,1) : Fraction)=TreeFraction.repr (D:ℚ) := by simp [TreeFraction.repr] + rw [hD,div_repr hh (Nat.cast_nonneg D),add_repr hreal (div_nonneg hh (Nat.cast_nonneg D))] + rfl + +open TreePost Turing + +theorem sourceBagWeight_post : ∃ p : Polynomial ℕ,∀ x : (BagBuildInput×ℕ)×Key,∀ t : ℕ, + p.eval (packed x).length≤t → ∀ coins : Fin t→Bool, + (run (machine sourceBagWeightRealizer.program) (packed x) coins).state=none ∧ + (run (machine sourceBagWeightRealizer.program) (packed x) coins).tape.right₀= + ListBlank.mk (packed (sourceBagWeight x)) := + polynomial_compiles sourceBagWeightRealizer polynomial_sourceBagWeight +end MatchingFPRAS.ExecutableSource + +end OAI diff --git a/lean/OAI/Combinatorics/MatchingCount/Machines/TreePortion.lean b/lean/OAI/Combinatorics/MatchingCount/Machines/TreePortion.lean new file mode 100644 index 0000000000000000000000000000000000000000..44bd360b3bf1741a09446bf10e0fd72c4498b2b8 --- /dev/null +++ b/lean/OAI/Combinatorics/MatchingCount/Machines/TreePortion.lean @@ -0,0 +1,125 @@ +import Mathlib +import OAI.Combinatorics.MatchingCount.Machines.TreeColor + +namespace OAI + +namespace MatchingFPRAS.ExecutableSource +open TreeTyped TreeFraction TreeTyped.Numbered ExecutableBottleneck ExecutableHierarchy ExecutableRefresh Enlargement RealGeometry + +attribute [local instance] NumberedHierarchy.labelOrder +attribute [local instance] Transport.sym2Order Transport.bagEdgeOrder Transport.bagEdgeFintype + +def coloredRow (x : BagBuildInput×RawReal) : Key×Fraction := + (sourceRealKey x,path ((prepare x.1.1).1,x.2)) +def coloredRowRealizer : Realizer coloredRow := (pair sourceRealKeyRealizer + (composition (pair (composition first.fst prepareRealizer).fst second) pathRealizer)).congr (fun _=>rfl) +lemma polynomial_coloredRow : PolynomialTime coloredRowRealizer := by + unfold coloredRowRealizer Realizer.fst + apply polynomial_congr + have := polynomial_sourceRealKey + have := polynomial_prepare + have := polynomial_path + tree_cost + +def coloredRows (x : BagBuildInput) : List (Key×Fraction) := + (realEdges (x.1.2,x.1.1.2)).map (fun e=>coloredRow (x,e)) +def coloredRowsRealizer : Realizer coloredRows := composition (pair identity + (composition (pair first.snd first.fst.snd) realEdgesRealizer)) (mapWith coloredRowRealizer) +lemma polynomial_coloredRows : PolynomialTime coloredRowsRealizer := by + unfold coloredRowsRealizer + have := polynomial_realEdges + have := polynomial_coloredRow + exact polynomial_composition (polynomial_pair polynomial_identity + (polynomial_composition (polynomial_pair (polynomial_snd polynomial_first) + (polynomial_snd (polynomial_fst polynomial_first))) polynomial_realEdges)) + (polynomial_mapWith polynomial_coloredRow) + +def colorContribution (x : Key×(Key×Fraction)) : Fraction := + if x.1=x.2.1 then x.2.2 else (0,1) +def colorContributionRealizer : Realizer colorContribution := (choose + (composition (pair first second.fst) (pairEqual (pairEqual natEqual natEqual) natEqual)) second.snd + (constant ((0,1) : Fraction))).congr (by intro x; simp only [colorContribution,Function.comp_apply,decide_eq_true_eq]) +lemma polynomial_colorContribution : PolynomialTime colorContributionRealizer := by + unfold colorContributionRealizer Realizer.fst Realizer.snd + apply polynomial_congr + have := polynomial_pairEqual (polynomial_pairEqual polynomial_natEqual polynomial_natEqual) polynomial_natEqual + tree_cost + +def realPart (x : BagBuildInput×Key) : Fraction := + sum ((coloredRows x.1).map (fun row=>colorContribution (x.2,row))) +def realPartRealizer : Realizer realPart := composition + (composition (pair second (composition first coloredRowsRealizer)) (mapWith colorContributionRealizer)) sumRealizer +lemma polynomial_realPart : PolynomialTime realPartRealizer := + polynomial_composition (polynomial_composition + (polynomial_pair polynomial_second (polynomial_composition polynomial_first polynomial_coloredRows)) + (polynomial_mapWith polynomial_colorContribution)) polynomial_sum + +lemma coloredRow_source {n : ℕ} [Nontrivial (Fin n)] (hn : 2≤n) + (w : Fin n→Fin n→ℚ) (hw : ∀ i j,0≤w i j) (K : ℕ) + (a : SourceRealEdge (Fin n) K) : + coloredRow ((((matrixRep w,List.replicate (2*K+2) false),List.range n),List.replicate (2*K) false),realRepr a)= + (sourceKey (RationalSource.coloredReal w K a),TreeFraction.repr (RationalSource.pathActivity w K a.1 a.2)) := by + unfold coloredRow + rw [sourceRealKey_source hn w hw K] + unfold prepare + dsimp only + rw [close_matrixRep w hw,show BottleneckAlgorithm.close w n=RationalSource.logicalB w by simp [RationalSource.logicalB]] + rw [path_source_repr hn w hw K _ (List.length_replicate ..)] + +lemma realPart_source {n : ℕ} [Nontrivial (Fin n)] (hn : 2≤n) + (w : Fin n→Fin n→ℚ) (hw : ∀ i j,0≤w i j) (K : ℕ) + (e : Transport.BagEdge (RationalSource.bags w K)) : + realPart ((((matrixRep w,List.replicate (2*K+2) false),List.range n),List.replicate (2*K) false),sourceKey e)= + TreeFraction.repr (RationalSource.realPortion w K e) := by + let x : BagBuildInput:=(((matrixRep w,List.replicate (2*K+2) false),List.range n),List.replicate (2*K) false) + let es:=realEdges (List.range n,List.replicate (2*K+2) false) + let f : RawReal→ℚ:=fun a=>if sourceRealKey (x,a)=sourceKey e then + val (path ((prepare x.1).1,a)) else 0 + let g : SourceRealEdge (Fin n) K→ℚ:=fun a=>if RationalSource.coloredReal w K a=e then + RationalSource.pathActivity w K a.1 a.2 else 0 + have hg (a) : 0≤g a := by + dsimp only [g] + split_ifs <;> first | exact pathActivity_nonneg hn w hw K _ _ | exact le_rfl + have hrow (a : SourceRealEdge (Fin n) K) : + colorContribution (sourceKey e,coloredRow (x,realRepr a))=TreeFraction.repr (g a) := by + rw [coloredRow_source hn w hw K] + simp only [colorContribution,sourceKey_injective.eq_iff] + dsimp only [g] + by_cases h : RationalSource.coloredReal w K a=e + · simp only [h,ite_true] + · simp only [h,Ne.symm h,ite_false] + rfl + have hf (a : SourceRealEdge (Fin n) K) : f (realRepr a)=g a := by + have h:=coloredRow_source hn w hw K a + have hp:=congrArg Prod.snd h + change path ((prepare x.1).1,realRepr a)=_ at hp + have hk:=congrArg Prod.fst h + change sourceRealKey (x,realRepr a)=sourceKey (RationalSource.coloredReal w K a) at hk + dsimp only [f,g] + simp only [hk,sourceKey_injective.eq_iff,hp,val_repr (pathActivity_nonneg hn w hw K _ _)] + have hmap : (es.map fun a=>colorContribution (sourceKey e,coloredRow (x,a)))= + (es.map f).map TreeFraction.repr := by + rw [List.map_map] + apply List.map_congr_left + intro a ha + have hm : a∈(realEdges (List.range n,List.replicate (2*K+2) false)).toFinset:=List.mem_toFinset.mpr ha + rw [realEdges_finset n K _ (List.length_replicate ..)] at hm + obtain ⟨b,_,rfl⟩:=Finset.mem_image.mp hm + simpa only [Function.comp_apply,hf] using hrow b + unfold realPart coloredRows + rw [List.map_map] + change sum (es.map (fun a=>colorContribution (sourceKey e,coloredRow (x,a))))=_ + rw [hmap,sum_repr] + · congr 1 + rw [sum_realEdges n K _ (List.length_replicate ..)] + exact Finset.sum_congr rfl (fun a _=>hf a) + · intro q hq + obtain ⟨a,ha,rfl⟩:=List.mem_map.mp hq + have hm : a∈(realEdges (List.range n,List.replicate (2*K+2) false)).toFinset:=List.mem_toFinset.mpr ha + rw [realEdges_finset n K _ (List.length_replicate ..)] at hm + obtain ⟨b,_,rfl⟩:=Finset.mem_image.mp hm + rw [hf] + exact hg b +end MatchingFPRAS.ExecutableSource + +end OAI diff --git a/lean/OAI/Combinatorics/MatchingCount/Machines/TreePostRealization.lean b/lean/OAI/Combinatorics/MatchingCount/Machines/TreePostRealization.lean new file mode 100644 index 0000000000000000000000000000000000000000..f5d24a93256c4de13d975b066151b32fd00875e7 --- /dev/null +++ b/lean/OAI/Combinatorics/MatchingCount/Machines/TreePostRealization.lean @@ -0,0 +1,94 @@ +import Mathlib +import OAI.Combinatorics.MatchingCount.Machines.TreeSum + +namespace OAI + +namespace MatchingFPRAS.TreePost +open TreeTyped TreeData TreeFunction TreeMachine RegisterProc Turing Polynomial + +abbrev Alphabet := TM2to1.Γ' (K Reg) (fun _=>Bool) +noncomputable def accesses (P : Proc (K Reg)) : ℕ := + Finset.univ.sup (fun l=>StackCost.accesses (P.code l)) +lemma accesses_bound (P : Proc (K Reg)) (l : P.Label) : StackCost.accesses (P.code l)≤accesses P := + Finset.le_sup (f := fun l=>StackCost.accesses (P.code l)) (Finset.mem_univ l) +noncomputable def machine (P : Proc (K Reg)) : RandomMachine := + StackWords.compiled (FixedEncoding.enc Alphabet) (FixedEncoding.dec Alphabet) + P.code Finset.univ (StackComposition.supports_univ P.code) +noncomputable def overhead (P : Proc (K Reg)) : ℕ := + StackWords.cost (FixedEncoding.enc Alphabet) (FixedEncoding.dec Alphabet) P.code Finset.univ + +def inputStacks {A : Type} [Codec A] (a : A) : Stack (K Reg) := + encodeEnv (env (TreeTyped.encode a) .nil .nil) +lemma inputStacks_bound {A : Type} [Codec A] (a : A) : StackCost.StackBound (inputStacks a) (weight a) := by + intro i + have h:=weight_pos a + cases i with + | inr i => simp [inputStacks,encodeEnv] + | inl i => + simp only [inputStacks,encodeEnv,env] + split_ifs <;> first + | exact le_rfl + | simpa only [TreeData.encode,List.length_singleton] using (Nat.succ_le_iff.mpr h) + +noncomputable def packed {A : Type} [Codec A] (a : A) : List Symbol := + StackWords.encoded (FixedEncoding.enc Alphabet) (inputStacks a) (weight a) +noncomputable def steps {A B : Type} [Codec A] [Codec B] {f : A→B} (F : Realizer f) (a : A) : ℕ := + overhead F.program*(F.cost a*(1+2*accesses F.program*(weight a+F.cost a*accesses F.program+1)))+2 + +theorem computes {A B : Type} [Codec A] [Codec B] {f : A→B} (F : Realizer f) + (a : A) (t : ℕ) (ht : steps F a≤t) (bits : Fin t→Bool) : + (run (machine F.program) (packed a) bits).state=none ∧ + (run (machine F.program) (packed a) bits).tape.right₀=ListBlank.mk (packed (f a)) := by + obtain ⟨n,hn,he⟩:=F.correct a .nil + change MachineCost.run (TM2.step F.program.code) n + ⟨some default,default,inputStacks a⟩=⟨none,none,inputStacks (f a)⟩ at he + have hh : (MachineCost.run (TM2.step F.program.code) n + ⟨some default,default,inputStacks a⟩).l=none := by rw [he] + have ho : StackCost.StackBound (MachineCost.run (TM2.step F.program.code) n + ⟨some default,default,inputStacks a⟩).stk (weight (f a)) := by + rw [he] + exact inputStacks_bound (f a) + have htime : overhead F.program*(n*(1+2*accesses F.program*(weight a+n*accesses F.program+1)))+2≤t := by + apply le_trans _ ht + unfold steps + apply Nat.add_le_add_right + apply Nat.mul_le_mul_left + apply Nat.mul_le_mul hn + gcongr + have h:=StackWords.compiled_execution (FixedEncoding.enc Alphabet) (FixedEncoding.dec Alphabet) + (FixedEncoding.blank Alphabet) (FixedEncoding.left_inverse Alphabet) + F.program.code Finset.univ (StackComposition.supports_univ F.program.code) + (accesses F.program) (accesses_bound F.program) (inputStacks a) (weight a) (inputStacks_bound a) + n (weight (f a)) hh ho t htime bits + rw [he] at h + exact h + +lemma packed_length {A : Type} [Codec A] (a : A) : + (packed a).length=Fintype.card Alphabet*weight a := by + have hp:=weight_pos a + unfold packed StackWords.encoded FixedAlphabetCompiler.word + rw [List.length_map,FixedEncoding.bitsWord_length] + congr 1 + change ((StackWords.rows (inputStacks a) (weight a)).tail.map (fun x=>(false,x))).length+1=weight a + simp only [List.length_map,List.length_tail,StackWords.rows,List.length_ofFn] + omega +lemma weight_le_packed_length {A : Type} [Codec A] (a : A) : weight a≤(packed a).length := by + rw [packed_length] + exact Nat.le_mul_of_pos_left _ Fintype.card_pos + +theorem polynomial_compiles {A B : Type} [Codec A] [Codec B] {f : A→B} + (F : Realizer f) (hF : PolynomialTime F) : + ∃ p : Polynomial ℕ,∀ a (t : ℕ),p.eval (packed a).length≤t → ∀ bits : Fin t→Bool, + (run (machine F.program) (packed a) bits).state=none ∧ + (run (machine F.program) (packed a) bits).tape.right₀=ListBlank.mk (packed (f a)) := by + obtain ⟨p,hp⟩:=hF + let q : Polynomial ℕ:=C (overhead F.program)*(p*(1+2*C (accesses F.program)*(X+p*C (accesses F.program)+1)))+2 + refine ⟨q,fun a t ht bits=>computes F a t (le_trans ?_ ht) bits⟩ + have hc : F.cost a≤p.eval (weight a):=le_trans (Nat.le_add_right _ _) (hp a) + have hm:=polynomial_eval_monotone q (weight_le_packed_length a) + apply le_trans _ hm + simp only [q,steps,eval_add,eval_mul,eval_C,eval_X,eval_one,eval_ofNat] + gcongr +end MatchingFPRAS.TreePost + +end OAI diff --git a/lean/OAI/Combinatorics/MatchingCount/Machines/TreePredicate.lean b/lean/OAI/Combinatorics/MatchingCount/Machines/TreePredicate.lean new file mode 100644 index 0000000000000000000000000000000000000000..eb94c8adcaa8882adcec4fe886023f560edfedd2 --- /dev/null +++ b/lean/OAI/Combinatorics/MatchingCount/Machines/TreePredicate.lean @@ -0,0 +1,82 @@ +import Mathlib +import OAI.Combinatorics.MatchingCount.Machines.TreeListOps + +namespace OAI + +namespace MatchingFPRAS.TreeTyped +open TreeData TreeMachine RegisterProc TreeFunction + +variable {A B : Type} [Codec A] [Codec B] + +def boolNot : Realizer Bool.not := + (choose identity (constant false) (constant true)).congr (by intro b; cases b <;> rfl) +def boolAnd : Realizer (fun x : Bool×Bool=>x.1 && x.2) := + (choose first second (constant false)).congr (by intro x; cases x.1 <;> rfl) +def natEqual : Realizer (fun x : ℕ×ℕ=>decide (x.1=x.2)) := + (choose less (constant false) + (choose (composition (pair second first) less) (constant false) (constant true))).congr (by + intro x + change (if decide (x.1bs.any id) := + (composition (pair identity (constant false)) + (fold (choose first (constant true) second))).congr (by + intro bs + change bs.foldl (fun z b=>if b then true else z) false=bs.any id + have h : ∀ z, bs.foldl (fun z b=>if b then true else z) z=(bs.any id || z) := by + induction bs with + | nil => intro z; rfl + | cons b bs ih => + intro z + simp only [List.foldl_cons,ih,List.any_cons] + cases b <;> cases bs.any id <;> cases z <;> rfl + rw [h] + cases bs.any id <;> rfl) + +def membership : Realizer (fun x : List ℕ×ℕ=>decide (x.2∈x.1)) := + (composition (composition (pair second first) (mapWith natEqual)) any).congr (by + intro x + simp only [Function.comp_apply,List.any_map] + apply Bool.eq_iff_iff.mpr + simp only [List.any_eq_true,Function.comp_apply,decide_eq_true_eq,id_eq] + constructor + · rintro ⟨a,ha,e⟩; simpa [←e] using ha + · intro h; exact ⟨x.2,h,rfl⟩) + +def countTrue : Realizer (fun bs : List Bool=>(bs.filter id).length) := + composition (filter identity) listLength + +def countWith {p : A×B → Bool} (P : Realizer p) : + Realizer (fun x : A×List B=>(x.2.filter fun b=>p (x.1,b)).length) := + (composition (mapWith P) countTrue).congr (by + intro x; simp only [Function.comp_apply,List.filter_map,List.length_map]; rfl) + +def listSum : Realizer (List.sum : List ℕ → ℕ) := + (composition (pair identity (constant 0)) (fold add)).congr (by + intro as + change as.foldl (fun n a=>a+n) 0=as.sum + have h : ∀ z,as.foldl (fun n a=>a+n) z=as.sum+z := by + induction as with + | nil => intro z; simp + | cons a as ih => intro z; simp only [List.foldl_cons,ih,List.sum_cons]; omega + simpa using h 0) + +def listProd : Realizer (List.prod : List ℕ → ℕ) := + (composition (pair identity (constant 1)) (fold multiply)).congr (by + intro as + change as.foldl (fun n a=>a*n) 1=as.prod + have h : ∀ z,as.foldl (fun n a=>a*n) z=as.prod*z := by + induction as with + | nil => intro z; simp + | cons a as ih => intro z; simp only [List.foldl_cons,ih,List.prod_cons]; ring + simpa using h 1) + +end MatchingFPRAS.TreeTyped + +end OAI diff --git a/lean/OAI/Combinatorics/MatchingCount/Machines/TreeProgramUnique.lean b/lean/OAI/Combinatorics/MatchingCount/Machines/TreeProgramUnique.lean new file mode 100644 index 0000000000000000000000000000000000000000..2dc06c18903f59bb884080fd78f7fcd69b7adcbb --- /dev/null +++ b/lean/OAI/Combinatorics/MatchingCount/Machines/TreeProgramUnique.lean @@ -0,0 +1,46 @@ +import Mathlib +import OAI.Combinatorics.MatchingCount.Machines.TreePostRealization + +namespace OAI + +namespace MatchingFPRAS.RegisterProc +open Turing MachineCost + +variable {K : Type} [DecidableEq K] +lemma Exec.unique {P : Proc K} {S T U : Stack K} {m n : ℕ} + (h : Exec P S T m) (g : Exec P S U n) : T=U := by + obtain ⟨i,hi,he⟩:=h + obtain ⟨j,hj,hf⟩:=g + have h₁ : MachineCost.run (TM2.step P.code) (i+j) ⟨some default,none,S⟩=⟨none,none,T⟩ := by + rw [run_add,he,StackComposition.run_halted] + have h₂ : MachineCost.run (TM2.step P.code) (i+j) ⟨some default,none,S⟩=⟨none,none,U⟩ := by + rw [Nat.add_comm,run_add,hf,StackComposition.run_halted] + exact congrArg TM2.Cfg.stk (h₁.symm.trans h₂) +end MatchingFPRAS.RegisterProc + +namespace MatchingFPRAS.TreePost +open TreeTyped TreeData TreeFunction TreeMachine RegisterProc + +variable {A B C D : Type} [Codec A] [Codec B] [Codec C] [Codec D] +lemma stacks_eq_of_encode {a : A} {b : B} (h : TreeTyped.encode a=TreeTyped.encode b) : + inputStacks a=inputStacks b := by simp only [inputStacks,h] +lemma packed_eq_of_stacks {a : A} {b : B} (h : inputStacks a=inputStacks b) : packed a=packed b := by + have hw : weight a=weight b := by + have hh:=congrFun h (.inl 0) + change (TreeData.encode (TreeTyped.encode a)).length=(TreeData.encode (TreeTyped.encode b)).length + exact congrArg List.length hh + simp only [packed,h,hw] +lemma packed_eq_of_encode {a : A} {b : B} (h : TreeTyped.encode a=TreeTyped.encode b) : packed a=packed b := + packed_eq_of_stacks (stacks_eq_of_encode h) +lemma sameProgram_output {f : A→B} {g : C→D} (F : Realizer f) (G : Realizer g) + (h : F.program=G.program) (a : A) (b : C) (hi : TreeTyped.encode a=TreeTyped.encode b) : + packed (f a)=packed (g b) := by + have hf:=F.correct a .nil + have hg:=G.correct b .nil + change Exec F.program (inputStacks a) (inputStacks (f a)) _ at hf + change Exec G.program (inputStacks b) (inputStacks (g b)) _ at hg + rw [h,stacks_eq_of_encode hi] at hf + exact packed_eq_of_stacks (hf.unique hg) +end MatchingFPRAS.TreePost + +end OAI diff --git a/lean/OAI/Combinatorics/MatchingCount/Machines/TreeQuad.lean b/lean/OAI/Combinatorics/MatchingCount/Machines/TreeQuad.lean new file mode 100644 index 0000000000000000000000000000000000000000..8ee80fea14f9bdfcd0863799056b95080b143100 --- /dev/null +++ b/lean/OAI/Combinatorics/MatchingCount/Machines/TreeQuad.lean @@ -0,0 +1,61 @@ +import Mathlib +import OAI.Combinatorics.MatchingCount.Complexity.TreeCostTactic + +namespace OAI + +namespace MatchingFPRAS.TreeTyped +variable {A B : Type} [Codec A] [Codec B] + +def listProduct : Realizer (fun x : List A×List B=>x.1.product x.2) := + (composition (composition (pair second first) + (mapWith (composition (pair second first) (mapWith (pair first second))))) flatten).congr (fun _=>rfl) +lemma polynomial_listProduct : PolynomialTime (listProduct (A:=A) (B:=B)) := by + unfold listProduct + apply polynomial_congr + tree_cost + +omit [Codec A] [Codec B] in +lemma mem_listProduct (a : A) (b : B) (s : List A) (t : List B) : + (a,b)∈s.product t ↔ a∈s ∧ b∈t := List.mem_product + +abbrev Quad (A : Type) := (A×A)×(A×A) +def quadList (q : Quad A) : List A := [q.1.1,q.1.2,q.2.1,q.2.2] +def quadFn (q : Quad A) : Fin 4→A := ![q.1.1,q.1.2,q.2.1,q.2.2] +def quadOfFn (f : Fin 4→A) : Quad A := ((f 0,f 1),(f 2,f 3)) +omit [Codec A] [Codec B] in +lemma quadFn_ofFn (f : Fin 4→A) : quadFn (quadOfFn f)=f := by + funext i + fin_cases i <;> rfl +omit [Codec A] [Codec B] in +lemma quadList_ofFn (q : Quad A) : quadList q=List.ofFn (quadFn q) := by + simp [quadList,quadFn,List.ofFn_succ] +def quadListRealizer : Realizer (quadList (A:=A)) := + (composition (pair first.fst (composition (pair first.snd + (composition (pair second.fst (composition (pair second.snd (constant ([] : List A))) listCons)) listCons)) listCons)) listCons).congr (fun _=>rfl) +lemma polynomial_quadList : PolynomialTime (quadListRealizer (A:=A)) := by + unfold quadListRealizer Realizer.fst Realizer.snd + apply polynomial_congr + tree_cost + +def quads (s : List A) : List (Quad A) := (s.product s).product (s.product s) +def quadsRealizer : Realizer (quads (A:=A)) := + (composition (pair (composition (pair identity identity) listProduct) + (composition (pair identity identity) listProduct)) listProduct).congr (fun _=>rfl) +lemma polynomial_quads : PolynomialTime (quadsRealizer (A:=A)) := by + unfold quadsRealizer + apply polynomial_congr + have := polynomial_listProduct (A:=A) (B:=A) + have := polynomial_listProduct (A:=A×A) (B:=A×A) + tree_cost +omit [Codec A] [Codec B] in +lemma mem_quads (q : Quad A) (s : List A) : q∈quads s ↔ ∀ i,quadFn q i∈s := by + rcases q with ⟨⟨a,b⟩,⟨c,d⟩⟩ + simp only [quads,mem_listProduct] + constructor + · rintro ⟨⟨h0,h1⟩,⟨h2,h3⟩⟩ i + fin_cases i <;> assumption + · intro h + exact ⟨⟨h 0,h 1⟩,⟨h 2,h 3⟩⟩ +end MatchingFPRAS.TreeTyped + +end OAI diff --git a/lean/OAI/Combinatorics/MatchingCount/Machines/TreeQuadDistinct.lean b/lean/OAI/Combinatorics/MatchingCount/Machines/TreeQuadDistinct.lean new file mode 100644 index 0000000000000000000000000000000000000000..da2eb78fe4f601bb8171fa75e6d435c9ba0df69f --- /dev/null +++ b/lean/OAI/Combinatorics/MatchingCount/Machines/TreeQuadDistinct.lean @@ -0,0 +1,36 @@ +import Mathlib +import OAI.Combinatorics.MatchingCount.Machines.TreeQuad + +namespace OAI + +namespace MatchingFPRAS.TreeTyped +variable {A : Type} [Codec A] [LinearOrder A] +def listNodup (Eq : Realizer (fun x : A×A=>decide (x.1=x.2))) + (Le : Realizer (fun x : A×A=>decide (x.1≤x.2))) : Realizer (fun xs : List A=>decide xs.Nodup) := + (composition (pair (composition (listFinset Eq Le) finsetCard) listLength) natEqual).congr (by + intro xs + apply Bool.eq_iff_iff.mpr + simp only [Function.comp_apply,decide_eq_true_eq] + exact Multiset.toFinset_card_eq_card_iff_nodup (m:= (xs : Multiset A))) +lemma polynomial_listNodup {Eq : Realizer (fun x : A×A=>decide (x.1=x.2))} + {Le : Realizer (fun x : A×A=>decide (x.1≤x.2))} (hEq : PolynomialTime Eq) (hLe : PolynomialTime Le) : + PolynomialTime (listNodup Eq Le) := by + unfold listNodup + apply polynomial_congr + have := polynomial_listFinset hEq hLe + tree_cost + +def quadInjective (Eq : Realizer (fun x : A×A=>decide (x.1=x.2))) + (Le : Realizer (fun x : A×A=>decide (x.1≤x.2))) : + Realizer (fun q : Quad A=>decide (Function.Injective (quadFn q))) := + (composition quadListRealizer (listNodup Eq Le)).congr (by + intro q + apply Bool.eq_iff_iff.mpr + simp only [Function.comp_apply,decide_eq_true_eq,quadList_ofFn,List.nodup_ofFn]) +lemma polynomial_quadInjective {Eq : Realizer (fun x : A×A=>decide (x.1=x.2))} + {Le : Realizer (fun x : A×A=>decide (x.1≤x.2))} (hEq : PolynomialTime Eq) (hLe : PolynomialTime Le) : + PolynomialTime (quadInjective Eq Le) := + polynomial_congr _ (polynomial_composition polynomial_quadList (polynomial_listNodup hEq hLe)) +end MatchingFPRAS.TreeTyped + +end OAI diff --git a/lean/OAI/Combinatorics/MatchingCount/Machines/TreeRationalWeight.lean b/lean/OAI/Combinatorics/MatchingCount/Machines/TreeRationalWeight.lean new file mode 100644 index 0000000000000000000000000000000000000000..54cbf029f768c64d29a2c0928cfe922551bedd2c --- /dev/null +++ b/lean/OAI/Combinatorics/MatchingCount/Machines/TreeRationalWeight.lean @@ -0,0 +1,80 @@ +import Mathlib +import OAI.Combinatorics.MatchingCount.Graphs.TreeCycleTable + +namespace OAI + +namespace MatchingFPRAS.TreeFraction +lemma fold_product_repr (xs : List ℚ) (hx : ∀ x∈xs,0≤x) (a : ℚ) (ha : 0≤a) : + ((xs.map repr).foldl (fun a b=>mul (b,a)) (repr a))=repr (xs.prod*a) := by + induction xs generalizing a with + | nil => simp + | cons x xs ih => + have h : 0≤x:=hx x (by simp) + simp only [List.map_cons,List.foldl_cons,mul_repr h ha] + rw [ih (fun y hy=>hx y (by simp [hy])) (x*a) (mul_nonneg h ha)] + congr 1 + simp only [List.prod_cons] + ring +lemma product_repr (xs : List ℚ) (hx : ∀ x∈xs,0≤x) : product (xs.map repr)=repr xs.prod := by + unfold product + have h:=fold_product_repr xs hx 1 (by decide) + simpa only [mul_one,show repr (1:ℚ)=(1,1) from rfl] using h +end MatchingFPRAS.TreeFraction + +namespace MatchingFPRAS.TreeTyped.SparseProgram +open TreeTyped TreeFraction + +variable {E C : Type} [Codec E] [Codec C] [LinearOrder E] +attribute [local instance] Transport.Sparse.finsetOrder + +def weight (w : C×E→Fraction) (x : C×Finset E) : Fraction := + product ((x.2.sort (·≤·)).map (fun e=>w (x.1,e))) +def weightRealizer {w : C×E→Fraction} (W : Realizer w) : Realizer (weight w) := + (composition (composition (pair first (composition second finsetList)) (mapWith W)) productRealizer).congr (fun _=>rfl) +lemma polynomial_weight {w : C×E→Fraction} {W : Realizer w} (hW : PolynomialTime W) : + PolynomialTime (weightRealizer W) := by + unfold weightRealizer + apply polynomial_congr + have := polynomial_product + tree_cost + +def pairWeight (w z : C×E→Fraction) (x : C×PairState E) : Fraction := + mul (weight w (x.1,x.2.1),weight z (x.1,x.2.2)) +def pairWeightRealizer {w z : C×E→Fraction} (W : Realizer w) (Z : Realizer z) : Realizer (pairWeight w z) := + (composition (pair (composition (pair first second.fst) (weightRealizer W)) + (composition (pair first second.snd) (weightRealizer Z))) mulRealizer).congr (fun _=>rfl) +lemma polynomial_pairWeight {w z : C×E→Fraction} {W : Realizer w} {Z : Realizer z} + (hW : PolynomialTime W) (hZ : PolynomialTime Z) : PolynomialTime (pairWeightRealizer W Z) := by + unfold pairWeightRealizer Realizer.fst Realizer.snd + apply polynomial_congr + have := polynomial_mul + have := polynomial_weight hW + have := polynomial_weight hZ + tree_cost + +variable (w : C×E→Fraction) (c : C) (q : E→ℚ) (hq : ∀ e,0≤q e) + (hw : ∀ e,w (c,e)=TreeFraction.repr (q e)) +omit [Codec E] [Codec C] in +include hq hw in +lemma weight_repr (s : Finset E) : weight w (c,s)=TreeFraction.repr (∏ e∈s,q e) := by + unfold weight + dsimp only + simp only [hw] + change product ((s.sort (·≤·)).map (TreeFraction.repr ∘ q))=_ + rw [←List.map_map,product_repr _ (by intro a ha; obtain ⟨b,hb,rfl⟩:=List.mem_map.mp ha; exact hq b)] + congr 1 + simpa only [Finset.sort_toFinset] using (List.prod_toFinset q (Finset.sort_nodup s (·≤·))).symm + +variable [Fintype E] {V : Type} [Fintype V] [DecidableEq V] (ends : E→Sym2 V) +omit [Codec E] [Codec C] [Fintype E] [DecidableEq V] in +lemma pairWeight_repr (w z : C×E→Fraction) (c : C) (q r : E→ℚ) (hq : ∀ e,0≤q e) (hr : ∀ e,0≤r e) + (hw : ∀ e,w (c,e)=TreeFraction.repr (q e)) (hz : ∀ e,z (c,e)=TreeFraction.repr (r e)) + (a : Transport.PM (fun e v=>v∈ends e)×Transport.PM (fun e v=>v∈ends e)) : + pairWeight w z (c,pairRepr ends a)=TreeFraction.repr (Transport.Sparse.rationalPairWeight ends q r a) := by + unfold pairWeight pairRepr + rw [weight_repr w c q hq hw,weight_repr z c r hr hz,mul_repr (Finset.prod_nonneg (fun e _=>hq e)) + (Finset.prod_nonneg (fun e _=>hr e))] + rfl +end MatchingFPRAS.TreeTyped.SparseProgram + +end OAI diff --git a/lean/OAI/Combinatorics/MatchingCount/Machines/TreeReach.lean b/lean/OAI/Combinatorics/MatchingCount/Machines/TreeReach.lean new file mode 100644 index 0000000000000000000000000000000000000000..017c02bbaf62f83bd506d1eac8efcdcf2c689a2a --- /dev/null +++ b/lean/OAI/Combinatorics/MatchingCount/Machines/TreeReach.lean @@ -0,0 +1,130 @@ +import Mathlib +import OAI.Combinatorics.MatchingCount.Machines.TreeFiniteOps + +namespace OAI + +namespace MatchingFPRAS.TreeTyped +open Polynomial + +variable {A C : Type} [Codec A] [Codec C] [LinearOrder A] +omit [LinearOrder A] in +lemma weight_subperm {as bs : List A} (h : as.Subperm bs) : weight as≤weight bs := by + obtain ⟨cs,hc,hs⟩:=h + rw [← weight_perm hc] + exact weight_sublist hs +lemma weight_finset_subset {s t : Finset A} (h : s⊆t) : weight s≤weight t := by + apply weight_subperm + apply (Finset.sort_nodup s (·≤·)).subperm + intro a ha + simpa only [Finset.mem_sort] using h (by simpa only [Finset.mem_sort] using ha) +lemma weight_finset_union (s t : Finset A) : weight (s∪t)≤weight s+weight t := by + have h : (s∪t).sort (·≤·) |>.Subperm (s.sort (·≤·)++t.sort (·≤·)) := by + apply (Finset.sort_nodup _ _).subperm + intro a ha + simpa only [List.mem_append,Finset.mem_sort,Finset.mem_union] using ha + have hh:=weight_subperm h + have ha:=weight_append (s.sort (·≤·)) (t.sort (·≤·)) + change weight ((s∪t).sort (·≤·))≤weight (s.sort (·≤·))+weight (t.sort (·≤·)) + omega + +namespace FiniteReach +abbrev Input (C A : Type) := (C×Finset A)×Finset A +variable (p : C×(A×A) → Bool) +def grow (x : Input C A) : Finset A := + x.2 ∪ x.1.2.filter (fun b=>∃ a∈x.2,p (x.1.1,(a,b))=true) +def sweep (x : Input C A) : Input C A := (x.1,grow p x) +def reach (x : Input C A) : Finset A := (countDown (fun x=>sweep p x.2) x.1.2.card x).2 + +variable {p} +def neighbor (P : Realizer p) : + Realizer (fun x : (C×A)×Finset A=>decide (∃ a∈x.2,p (x.1.1,(a,x.1.2))=true)) := + finsetAny (composition (pair first.fst (pair second first.snd)) P) +lemma polynomial_neighbor {P : Realizer p} (hP : PolynomialTime P) : PolynomialTime (neighbor P) := by + unfold neighbor + exact polynomial_finsetAny (polynomial_composition (polynomial_pair (polynomial_fst polynomial_first) + (polynomial_pair polynomial_second (polynomial_snd polynomial_first))) hP) + +def growRealizer (P : Realizer p) + (E : Realizer (fun x : A×A=>decide (x.1=x.2))) + (R : Realizer (fun x : A×A=>decide (x.1≤x.2))) : Realizer (grow p) := + (composition (pair second (composition (pair (pair first.fst second) first.snd) + (finsetFilterWith (composition (pair (pair first.fst second) first.snd) (neighbor P))))) (finsetUnion E R)).congr (by + intro x; ext a; simp only [grow,Function.comp_apply,decide_eq_true_eq]) +lemma polynomial_grow {P : Realizer p} + {E : Realizer (fun x : A×A=>decide (x.1=x.2))} + {R : Realizer (fun x : A×A=>decide (x.1≤x.2))} + (hP : PolynomialTime P) (hE : PolynomialTime E) (hR : PolynomialTime R) : + PolynomialTime (growRealizer P E R) := by + unfold growRealizer + apply polynomial_congr + exact polynomial_composition (polynomial_pair polynomial_second (polynomial_composition + (polynomial_pair (polynomial_pair (polynomial_fst polynomial_first) polynomial_second) (polynomial_snd polynomial_first)) + (polynomial_finsetFilterWith (polynomial_composition + (polynomial_pair (polynomial_pair (polynomial_fst polynomial_first) polynomial_second) (polynomial_snd polynomial_first)) + (polynomial_neighbor hP))))) (polynomial_finsetUnion hE hR) + +def sweepRealizer (P : Realizer p) + (E : Realizer (fun x : A×A=>decide (x.1=x.2))) + (R : Realizer (fun x : A×A=>decide (x.1≤x.2))) : Realizer (sweep p) := + pair first (growRealizer P E R) +def reachRealizer (P : Realizer p) + (E : Realizer (fun x : A×A=>decide (x.1=x.2))) + (R : Realizer (fun x : A×A=>decide (x.1≤x.2))) : Realizer (reach p) := + composition (composition (pair (composition first.snd finsetCard) identity) + (iterateDown (composition second (sweepRealizer P E R)))) second + +lemma polynomial_reach {P : Realizer p} + {E : Realizer (fun x : A×A=>decide (x.1=x.2))} + {R : Realizer (fun x : A×A=>decide (x.1≤x.2))} + (hP : PolynomialTime P) (hE : PolynomialTime E) (hR : PolynomialTime R) : + PolynomialTime (reachRealizer P E R) := by + unfold reachRealizer + apply polynomial_composition _ polynomial_second + apply polynomial_boundedRepeat + (polynomial_pair (polynomial_composition (polynomial_snd polynomial_first) polynomial_finsetCard) polynomial_identity) + (polynomial_composition polynomial_second (polynomial_pair polynomial_first (polynomial_grow hP hE hR))) + X (3*X+1) (fun x _ z=>z.1=x.1 ∧ z.2⊆x.2∪x.1.2) + · intro x + have h:=list_length_le_weight (x.1.2.sort (·≤·)) + rw [Finset.length_sort] at h + simp only [eval_X,Function.comp_apply] + change x.1.2.card≤weight x + change x.1.2.card≤weight ((x.1.1,x.1.2),x.2) + rw [weight_prod,weight_prod] + change _≤weight x.1.2 at h + omega + · intro x + exact ⟨rfl,Finset.subset_union_left⟩ + · intro x k hk z ⟨hz,hs⟩ + refine ⟨hz,?_⟩ + change grow p z⊆x.2∪x.1.2 + unfold grow + apply Finset.union_subset hs + intro a ha + exact Finset.mem_union_right _ (hz ▸ (Finset.mem_filter.mp ha).1) + · intro x k z ⟨hz,hs⟩ + have h1:=weight_finset_subset hs + have h2:=weight_finset_union x.2 x.1.2 + simp only [eval_add,eval_mul,eval_ofNat,eval_X,eval_one] + change weight z≤3*weight x+1 + change weight (z.1,z.2)≤3*weight (x.1,x.2)+1 + rw [weight_prod z.1 z.2,weight_prod x.1 x.2,hz] + rw [weight_prod x.1.1 x.1.2] + omega + +omit [Codec A] [Codec C] in +lemma countDown_sweep (x : Input C A) (n : ℕ) : + countDown (fun x=>sweep p x.2) n x=(x.1,(fun s=>grow p (x.1,s))^[n] x.2) := by + induction n generalizing x with + | zero => rfl + | succ n ih => + rw [countDown,ih] + simp only [sweep,Function.iterate_succ_apply] + +omit [Codec A] [Codec C] in +lemma reach_eq (x : Input C A) : reach p x=(fun s=>grow p (x.1,s))^[x.1.2.card] x.2 := by + rw [reach,countDown_sweep] +end FiniteReach +end MatchingFPRAS.TreeTyped + +end OAI diff --git a/lean/OAI/Combinatorics/MatchingCount/Machines/TreeReachCorrect.lean b/lean/OAI/Combinatorics/MatchingCount/Machines/TreeReachCorrect.lean new file mode 100644 index 0000000000000000000000000000000000000000..6ef4104a089989d778ea70a9f2db661b90be3cc4 --- /dev/null +++ b/lean/OAI/Combinatorics/MatchingCount/Machines/TreeReachCorrect.lean @@ -0,0 +1,48 @@ +import Mathlib +import OAI.Combinatorics.MatchingCount.Machines.TreeReach +import OAI.Combinatorics.MatchingCount.Complexity.TreePolyTactic + +namespace OAI + +namespace MatchingFPRAS.TreeTyped.FiniteReach +variable {A C : Type} [Codec A] [Codec C] [LinearOrder A] [Fintype A] +variable {p : C×(A×A) → Bool} +omit [Codec A] [Codec C] +lemma grow_source (G : SimpleGraph A) [DecidableRel G.Adj] (c : C) + (hp : ∀ a b,p (c,(a,b))=decide (G.Adj a b)) (s : Finset A) : + grow p ((c,Finset.univ),s)=ComputableReach.grow G s := by + ext a + simp only [grow,ComputableReach.grow,Finset.mem_union,Finset.mem_filter,hp,decide_eq_true_eq] +lemma reach_source (G : SimpleGraph A) [DecidableRel G.Adj] (c : C) + (hp : ∀ a b,p (c,(a,b))=decide (G.Adj a b)) (s : Finset A) : + reach p ((c,Finset.univ),s)=ComputableReach.reached G s (Fintype.card A) := by + rw [reach_eq,Finset.card_univ] + have he : (fun s=>grow p ((c,Finset.univ),s))=ComputableReach.grow G := funext (grow_source G c hp) + rw [he] + rfl +lemma reach_closure (G : SimpleGraph A) [DecidableRel G.Adj] (c : C) + (hp : ∀ a b,p (c,(a,b))=decide (G.Adj a b)) (a : A) : + reach p ((c,Finset.univ),{a})=ComputableReach.closure G a := reach_source G c hp {a} +end MatchingFPRAS.TreeTyped.FiniteReach + +namespace MatchingFPRAS.TreeTyped +variable {A B C : Type} [Codec A] [Codec B] [Codec C] [LinearOrder A] [LinearOrder B] +def finsetImageWith {f : C×A → B} (F : Realizer f) + (E : Realizer (fun x : B×B=>decide (x.1=x.2))) + (R : Realizer (fun x : B×B=>decide (x.1≤x.2))) : + Realizer (fun x : C×Finset A=>x.2.image (fun a=>f (x.1,a))) := + (composition (composition (pair first (composition second finsetList)) (mapWith F)) (listFinset E R)).congr (by + intro x; ext b + simp only [Function.comp_apply,List.mem_toFinset,List.mem_map,Finset.mem_sort,Finset.mem_image]) +lemma polynomial_finsetImageWith {f : C×A → B} {F : Realizer f} + {E : Realizer (fun x : B×B=>decide (x.1=x.2))} + {R : Realizer (fun x : B×B=>decide (x.1≤x.2))} + (hF : PolynomialTime F) (hE : PolynomialTime E) (hR : PolynomialTime R) : + PolynomialTime (finsetImageWith F E R) := by + unfold finsetImageWith + apply polynomial_congr + apply polynomial_composition _ (polynomial_listFinset hE hR) + tree_poly +end MatchingFPRAS.TreeTyped + +end OAI diff --git a/lean/OAI/Combinatorics/MatchingCount/Machines/TreeRefresh.lean b/lean/OAI/Combinatorics/MatchingCount/Machines/TreeRefresh.lean new file mode 100644 index 0000000000000000000000000000000000000000..0a9c488ee9c96283d571d809302752c7591fa18d --- /dev/null +++ b/lean/OAI/Combinatorics/MatchingCount/Machines/TreeRefresh.lean @@ -0,0 +1,92 @@ +import Mathlib +import OAI.Combinatorics.MatchingCount.Machines.TreeRefreshNumbered +import OAI.Combinatorics.MatchingCount.Machines.TreePostRealization + +namespace OAI + +namespace MatchingFPRAS.ExecutableRefresh +open TreeTyped TreeTyped.Numbered ExecutableDP ExecutableUnit Transport UnitRefresh + +attribute [local instance] Transport.sym2Order Transport.bagEdgeOrder Transport.bagEdgeFintype +variable {V L : Type} [Fintype V] [LinearOrder V] [Fintype L] [LinearOrder L] +variable {bags : V→Finset L} +lemma index_min (a b : V) : Numbered.index (min a b)=min (Numbered.index a) (Numbered.index b) := by + by_cases h : a≤b + · rw [min_eq_left h,min_eq_left ((Numbered.index_le _ _).mpr h)] + · rw [min_eq_right (le_of_not_ge h),min_eq_right ((Numbered.index_le _ _).mpr (le_of_not_ge h))] +lemma index_max (a b : V) : Numbered.index (max a b)=max (Numbered.index a) (Numbered.index b) := by + by_cases h : a≤b + · rw [max_eq_right h,max_eq_right ((Numbered.index_le _ _).mpr h)] + · rw [max_eq_left (le_of_not_ge h),max_eq_left ((Numbered.index_le _ _).mpr (le_of_not_ge h))] +lemma sourceKey_numbering (p : ColoredPairing (numberedBags bags)) (i : Fin (Fintype.card V)) : + sourceKey ((numberingEquiv bags p).edgeAt (orderedEnum V i))=key (p.edgeAt i) := by + simp only [sourceKey,key,ColoredPairing.edgeAt,Sym2.inf_mk,Sym2.sup_mk] + change ((Numbered.index (min (orderedEnum V i) (orderedEnum V (p.pair.mate ((orderedEnum V).symm (orderedEnum V i))))), + Numbered.index (max (orderedEnum V i) (orderedEnum V (p.pair.mate ((orderedEnum V).symm (orderedEnum V i)))))), + Numbered.index (orderedEnum L (p.color ((orderedEnum V).symm (orderedEnum V i))))) = _ + simp only [Equiv.symm_apply_apply] + simp only [index_min,index_max,Numbered.index_orderedEnum] + rfl +lemma rowKey_numbering (p : ColoredPairing (numberedBags bags)) (i : Fin (Fintype.card V)) : + rowKey (resultRep p,i.val)=sourceKey ((numberingEquiv bags p).edgeAt (orderedEnum V i)) := by + rw [rowKey_result,sourceKey_numbering] +lemma matching_numbering (p : ColoredPairing (numberedBags bags)) : + matching (sourceCatalog bags,resultRep p)= + Numbered.set (Computable.toMatching (numberingEquiv bags p)).val := by + ext j + simp only [matching,resultRep,List.length_ofFn,List.mem_toFinset,List.mem_map,List.mem_range] + change (∃ i,iList.ofFn (bits i)))= + Numbered.set (sampleMatching k bags rank parent hb hne hp M bits).val := by + unfold refresh + rw [storedCatalog_eq ha,←sourceCatalog_eq] + rw [fastSample_represented (numberedBags bags) (numberedRank rank) (numberedParent parent) + (numberedRanked bags rank parent hb) (numberedNonempty bags hne) (numberedDecreasing rank parent hp) + (numbered_count_pos bags rank parent hb hne hp (Computable.pairingEquiv M)) a ha bits,matching_numbering] + rfl + +open TreePost Turing + +theorem source_refresh_post : ∃ p : Polynomial ℕ, + ∀ {V L : Type} [Fintype V] [LinearOrder V] [Fintype L] [LinearOrder L] + (bags : V→Finset L) (rank : L→ℕ) (parent : L→Option L) + (hb : RankedBags bags rank parent) (hne : ∀ v,(bags v).Nonempty) + (hp : ∀ l p,parent l=some p → rank pList.ofFn (bits i))) + p.eval (packed x).length≤t → ∀ coins : Fin t→Bool, + (run (machine refreshRealizer.program) (packed x) coins).state=none ∧ + (run (machine refreshRealizer.program) (packed x) coins).tape.right₀= + ListBlank.mk (packed (Numbered.set (sampleMatching k bags rank parent hb hne hp M bits).val)) := by + obtain ⟨p,hp⟩:=polynomial_compiles refreshRealizer polynomial_refresh + refine ⟨p,fun {V L} _ _ _ _ bags rank parent hb hne hpar M a ha {k} bits t ht coins=>?_⟩ + have h:=hp ((storedCatalog (a,List.range (Fintype.card L)), + ((a,parentRep (numberedParent parent)),(Materialized.plan (numberedRank rank)).map Fin.val)), + List.ofFn (fun i=>List.ofFn (bits i))) t ht coins + rwa [refresh_sampleMatching bags rank parent hb hne hpar M a ha bits] at h +end MatchingFPRAS.ExecutableRefresh + +end OAI diff --git a/lean/OAI/Combinatorics/MatchingCount/Machines/TreeRefreshCatalog.lean b/lean/OAI/Combinatorics/MatchingCount/Machines/TreeRefreshCatalog.lean new file mode 100644 index 0000000000000000000000000000000000000000..38875df6b85fb0a293b1321571d60ec842e05035 --- /dev/null +++ b/lean/OAI/Combinatorics/MatchingCount/Machines/TreeRefreshCatalog.lean @@ -0,0 +1,156 @@ +import Mathlib +import OAI.Combinatorics.MatchingCount.Machines.TreeEnumeration +import OAI.Combinatorics.MatchingCount.Machines.TreeRefreshIndexed + +namespace OAI + +namespace MatchingFPRAS.ExecutableRefresh +open TreeTyped ExecutableDP ExecutableSource Polynomial + +def sharedKey (x : Bags×Key) : Bool := + decide (x.2.2∈x.1.getD x.2.1.1 [] ∧ x.2.2∈x.1.getD x.2.1.2 []) +def sharedKeyRealizer : Realizer sharedKey := (composition (pair + (composition (pair (composition (pair first second.fst.fst) (getDFast [])) second.snd) membership) + (composition (pair (composition (pair first second.fst.snd) (getDFast [])) second.snd) membership)) + boolAnd).congr (by intro x; simp [sharedKey]) +lemma polynomial_sharedKey : PolynomialTime sharedKeyRealizer := by + unfold sharedKeyRealizer + apply polynomial_congr + dsimp only [Realizer.fst, Realizer.snd] + have := polynomial_getDFast ([] : List ℕ) + have := polynomial_membership + tree_cost + +def storedCatalog (x : Bags×List ℕ) : List Key := + ((logicalEdges (List.range x.1.length)).product x.2).filter (fun e=>sharedKey (x.1,e)) +def storedCatalogRealizer : Realizer storedCatalog := (composition (pair first + (composition (pair (composition (composition (composition first listLength) range) + logicalEdgesRealizer) second) listProduct)) (filterWith sharedKeyRealizer)).congr (fun _=>rfl) +lemma polynomial_storedCatalog : PolynomialTime storedCatalogRealizer := by + have hr : PolynomialTime (composition (composition (first (A:=Bags) (B:=List ℕ)) listLength) range) := by + apply polynomial_boundedRange (polynomial_composition polynomial_first polynomial_listLength) X + intro x + simpa only [eval_X,Function.comp_apply] using (list_length_le_weight x.1).trans (weight_fst x) + unfold storedCatalogRealizer + apply polynomial_congr + have := polynomial_filterWithList polynomial_sharedKey + have := polynomial_sharedKey + have := polynomial_logicalEdges + have := polynomial_listProduct (A:=ℕ×ℕ) (B:=ℕ) + tree_cost + +open Transport UnitRefresh + +attribute [local instance] Transport.sym2Order Transport.bagEdgeOrder Transport.bagEdgeFintype Transport.prodOrder +local instance (priority := 2000) {A B : Type} [LinearOrder A] [LinearOrder B] : LE (A×B) := Transport.prodOrder.toLE +local instance (priority := 2000) {A B : Type} [LinearOrder A] [LinearOrder B] : LT (A×B) := Transport.prodOrder.toLT +local instance (priority := 2000) {A B : Type} [LinearOrder A] [LinearOrder B] : Preorder (A×B) := Transport.prodOrder.toPreorder +local instance (priority := 2000) {V : Type} [LinearOrder V] : LT (Sym2 V) := Transport.sym2Order.toLT +local instance (priority := 2000) {V : Type} [LinearOrder V] : LE (Sym2 V) := Transport.sym2Order.toLE +variable {n m : ℕ} {bags : Fin n→Finset (Fin m)} {a : Bags} +lemma key_le (e f : BagEdge bags) : @LE.le Key Transport.prodOrder.toLE (key e) (key f) ↔ @LE.le _ Transport.bagEdgeOrder.toLE e f := by + change toLex (key e) ≤ toLex (key f) ↔ toLex e.val.val ≤ toLex f.val.val + simp only [Prod.Lex.le_iff,key,ofLex_toLex,Fin.le_def] + have hlt : (e.val.val.1.inf.val,e.val.val.1.sup.val)<(f.val.val.1.inf.val,f.val.val.1.sup.val) ↔ e.val.val.1 apply Fin.ext + · exact congrArg Prod.fst h + · exact congrArg Prod.snd h + · intro h; rw [h] + rw [hlt,heq] +lemma row_mem (ha : List.Forall₂ List.Perm a (orderedRep bags)) (i : Fin n) (j : ℕ) : + j∈a.getD i.val [] ↔ ∃ c∈bags i,c.val=j := by + rw [(rows_getD ha i.val).mem_iff] + simp only [orderedRep,List.getD,List.getElem?_ofFn,i.isLt,↓reduceDIte,Option.getD_some,bagRep,List.mem_map,Finset.mem_toList] +lemma sym_mk_inf_sup (s : Sym2 (Fin n)) : s(s.inf,s.sup)=s := + (Sym2.sortEquiv.symm_apply_apply s) +lemma sym_inf_mem (s : Sym2 (Fin n)) : s.inf∈s := by + have h:=Sym2.mem_mk_left s.inf s.sup + rwa [sym_mk_inf_sup] at h +lemma sym_sup_mem (s : Sym2 (Fin n)) : s.sup∈s := by + have h:=Sym2.mem_mk_right s.inf s.sup + rwa [sym_mk_inf_sup] at h +lemma storedCatalog_mem (ha : List.Forall₂ List.Perm a (orderedRep bags)) (e : Key) : + e∈storedCatalog (a,List.range m) ↔ ∃ b : BagEdge bags,key b=e := by + have hn : a.length=n := by simpa only [orderedRep,List.length_ofFn] using ha.length_eq + constructor + · intro he + obtain ⟨he,hs⟩:=List.mem_filter.mp he + obtain ⟨he,hc⟩:=List.mem_product.mp he + obtain ⟨he,huv⟩:=List.mem_filter.mp he + obtain ⟨hu,hv⟩:=List.mem_product.mp he + have hu : e.1.1h.ne) + have hc : (catalog bags).Nodup := List.nodup_ofFn.mpr + ((key_injective (bags:=bags)).comp (orderedEnum (BagEdge bags)).injective) + have hp : (storedCatalog (a,List.range m)).Perm (catalog bags) := by + apply (List.perm_ext_iff_of_nodup hn hc).mpr + intro e + rw [storedCatalog_mem ha] + simp only [catalog,List.mem_ofFn] + constructor + · rintro ⟨b,rfl⟩; exact ⟨(orderedEnum _).symm b,by simp⟩ + · rintro ⟨i,rfl⟩; exact ⟨(orderedEnum _ i),rfl⟩ + apply hp.eq_of_pairwise (fun _ _ _ _ h₁ h₂=>@le_antisymm _ Transport.prodOrder.toPartialOrder _ _ h₁ h₂) + (hpair.imp (fun h=>le_of_lt h)) + rw [catalog,show (fun i=>key (orderedEnum (BagEdge bags) i))=key ∘ orderedEnum (BagEdge bags) from rfl, + ←List.map_ofFn,ofFn_orderedEnum] + apply List.pairwise_map.mpr + exact (Finset.pairwise_sort _ _).imp (fun h=>(key_le _ _).mpr h) +end MatchingFPRAS.ExecutableRefresh + +end OAI diff --git a/lean/OAI/Combinatorics/MatchingCount/Machines/TreeRefreshIndexed.lean b/lean/OAI/Combinatorics/MatchingCount/Machines/TreeRefreshIndexed.lean new file mode 100644 index 0000000000000000000000000000000000000000..9c76142b3c967bb921cd10f949b530f2eaeb741b --- /dev/null +++ b/lean/OAI/Combinatorics/MatchingCount/Machines/TreeRefreshIndexed.lean @@ -0,0 +1,138 @@ +import Mathlib +import OAI.Combinatorics.MatchingCount.Sampling.TreeSamplerRows +import OAI.Combinatorics.MatchingCount.Machines.TreeIndex +import OAI.Combinatorics.MatchingCount.Machines.TreeNumberedSets + +namespace OAI + +namespace MatchingFPRAS.ExecutableRefresh +open TreeTyped TreeTyped.Numbered ExecutableDP ExecutableUnit Polynomial + +abbrev Key := (ℕ×ℕ)×ℕ + +def ordered (x : ℕ×ℕ) : ℕ×ℕ := if x.1rfl) +lemma polynomial_rowKey : PolynomialTime rowKeyRealizer := by + unfold rowKeyRealizer; apply polynomial_congr + have := polynomial_getDFast ((0,0) : ℕ×ℕ) + have := polynomial_ordered + tree_cost + +def entryIndex (x : (List Key×Result)×ℕ) : ℕ := x.1.1.idxOf (rowKey (x.1.2,x.2)) +def entryIndexRealizer : Realizer entryIndex := composition + (pair (composition (pair first.snd second) rowKeyRealizer) first.fst) + (indexOf (pairEqual (pairEqual natEqual natEqual) natEqual)) +lemma polynomial_entryIndex : PolynomialTime entryIndexRealizer := by + unfold entryIndexRealizer entryIndex + dsimp only [Realizer.fst, Realizer.snd] + have := polynomial_rowKey + have := polynomial_indexOf (polynomial_pairEqual (polynomial_pairEqual polynomial_natEqual polynomial_natEqual) polynomial_natEqual) + tree_cost + +def matching (x : List Key×Result) : Finset ℕ := + ((List.range x.2.length).map (fun i=>entryIndex (x,i))).toFinset +def matchingRealizer : Realizer matching := (composition + (composition (pair identity (composition (composition second listLength) range)) + (mapWith entryIndexRealizer)) (listFinset natEqual leNat)).congr (fun _=>rfl) +lemma polynomial_matching : PolynomialTime matchingRealizer := by + have hr : PolynomialTime (composition (composition (second (A:=List Key) (B:=Result)) listLength) range) := by + apply polynomial_boundedRange (polynomial_composition polynomial_second polynomial_listLength) X + intro x + simpa only [eval_X,Function.comp_apply] using (list_length_le_weight x.2).trans (weight_snd x) + unfold matchingRealizer; apply polynomial_congr + have := polynomial_entryIndex + have := polynomial_listFinset polynomial_natEqual polynomial_leNat + tree_cost + +section Source +open Transport UnitRefresh + +attribute [local instance] Transport.sym2Order Transport.bagEdgeOrder Transport.bagEdgeFintype +variable {n m : ℕ} {bags : Fin n→Finset (Fin m)} +def key (e : BagEdge bags) : Key := ((e.val.val.1.inf.val,e.val.val.1.sup.val),e.val.val.2.val) +def catalog (bags : Fin n→Finset (Fin m)) : List Key := + List.ofFn (fun i=>key (orderedEnum (BagEdge bags) i)) +lemma key_injective : Function.Injective (key (bags:=bags)) := by + intro a b h + apply Subtype.ext + apply Subtype.ext + apply Prod.ext + · apply Sym2.sortEquiv.injective + apply Subtype.ext + apply Prod.ext + · exact Fin.ext (congrArg (fun z=>z.1.1) h) + · exact Fin.ext (congrArg (fun z=>z.1.2) h) + · exact Fin.ext (congrArg Prod.snd h) +lemma catalog_index (e : BagEdge bags) : (catalog bags).idxOf (key e)=Numbered.index e := by + let i := (orderedEnum (BagEdge bags)).symm e + have hn : (catalog bags).Nodup := List.nodup_ofFn.mpr ((key_injective (bags:=bags)).comp (orderedEnum (BagEdge bags)).injective) + have hi : i.val<(catalog bags).length := by simp only [catalog,List.length_ofFn]; exact i.isLt + dsimp only [catalog] at hi hn + have h:=@List.Nodup.idxOf_getElem Key (inferInstance : BEq Key) inferInstance _ hn i.val hi + have hget : (List.ofFn (fun j=>key (orderedEnum (BagEdge bags) j)))[i.val]'hi=key e := by + rw [List.getElem_ofFn] + simp only [Fin.eta,i,Equiv.apply_symm_apply] + rw [hget] at h + exact h +lemma rowKey_result (p : ColoredPairing bags) (i : Fin n) : + rowKey (resultRep p,i.val)=key (p.edgeAt i) := by + unfold rowKey + rw [resultRep_getD,ordered_eq] + rfl +lemma matching_result (p : ColoredPairing bags) : + matching (catalog bags,resultRep p)=Numbered.set (Computable.toMatching p).val := by + ext j + simp only [matching,resultRep,List.length_ofFn,List.mem_toFinset,List.mem_map,List.mem_range] + change (∃ i, iList.ofFn (bits i)))= + Numbered.set (UnitRefresh.Computable.toMatching + (UnitRefresh.Materialized.sampleUnit k n bags rank parent hb hne hp hz bits)).val := by + unfold refresh + rw [fastSample_represented bags rank parent hb hne hp hz a ha bits,matching_result] +end MatchingFPRAS.ExecutableRefresh + +end OAI diff --git a/lean/OAI/Combinatorics/MatchingCount/Machines/TreeRefreshNumbered.lean b/lean/OAI/Combinatorics/MatchingCount/Machines/TreeRefreshNumbered.lean new file mode 100644 index 0000000000000000000000000000000000000000..db01720b06fbbdea8ad56b9459b568f1d7bdbf57 --- /dev/null +++ b/lean/OAI/Combinatorics/MatchingCount/Machines/TreeRefreshNumbered.lean @@ -0,0 +1,148 @@ +import Mathlib +import OAI.Combinatorics.MatchingCount.Machines.TreeRefreshCatalog + +namespace OAI + +namespace MatchingFPRAS.ExecutableRefresh +open TreeTyped TreeTyped.Numbered ExecutableDP ExecutableUnit Transport UnitRefresh + +attribute [local instance] Transport.sym2Order Transport.bagEdgeOrder Transport.bagEdgeFintype Transport.prodOrder +local instance (priority := 2000) {A B : Type} [LinearOrder A] [LinearOrder B] : LE (A×B) := Transport.prodOrder.toLE +local instance (priority := 2000) {A B : Type} [LinearOrder A] [LinearOrder B] : LT (A×B) := Transport.prodOrder.toLT +local instance (priority := 2000) {A B : Type} [LinearOrder A] [LinearOrder B] : Preorder (A×B) := Transport.prodOrder.toPreorder +local instance (priority := 2000) {V : Type} [LinearOrder V] : LT (Sym2 V) := Transport.sym2Order.toLT +local instance (priority := 2000) {V : Type} [LinearOrder V] : LE (Sym2 V) := Transport.sym2Order.toLE +variable {V L : Type} [Fintype V] [LinearOrder V] [Fintype L] [LinearOrder L] +variable {bags : V→Finset L} +def sourceKey (e : BagEdge bags) : Key := + ((Numbered.index e.val.val.1.inf,Numbered.index e.val.val.1.sup),Numbered.index e.val.val.2) +def sourceCatalog (bags : V→Finset L) : List Key := + List.ofFn (fun i=>sourceKey (orderedEnum (BagEdge bags) i)) +lemma sourceKey_injective : Function.Injective (sourceKey (bags:=bags)) := by + intro a b h + apply Subtype.ext + apply Subtype.ext + apply Prod.ext + · apply Sym2.sortEquiv.injective + apply Subtype.ext + apply Prod.ext + · exact Numbered.index_injective (congrArg (fun z=>z.1.1) h) + · exact Numbered.index_injective (congrArg (fun z=>z.1.2) h) + · exact Numbered.index_injective (congrArg Prod.snd h) +lemma index_lt (a b : V) : Numbered.index a < Numbered.index b ↔ asourceKey (orderedEnum (BagEdge bags) j)))[i.val]'hi=sourceKey e := by + rw [List.getElem_ofFn] + simp only [Fin.eta,i,Equiv.apply_symm_apply] + rw [hh] at h + exact h +lemma sourceCatalog_pairwise : (sourceCatalog bags).Pairwise (· ≤ ·) := by + rw [sourceCatalog,show (fun i=>sourceKey (orderedEnum (BagEdge bags) i))= + sourceKey ∘ orderedEnum (BagEdge bags) from rfl,←List.map_ofFn,ofFn_orderedEnum] + apply List.pairwise_map.mpr + exact (Finset.pairwise_sort _ _).imp (fun h=>(sourceKey_le _ _).mpr h) +omit [Fintype V] in +lemma source_inf_mem (s : Sym2 V) : s.inf∈s := by + have h:=Sym2.mem_mk_left s.inf s.sup + have hs : s(s.inf,s.sup)=s := Sym2.sortEquiv.symm_apply_apply s + rwa [hs] at h +omit [Fintype V] in +lemma source_sup_mem (s : Sym2 V) : s.sup∈s := by + have h:=Sym2.mem_mk_right s.inf s.sup + have hs : s(s.inf,s.sup)=s := Sym2.sortEquiv.symm_apply_apply s + rwa [hs] at h +omit [Fintype V] [Fintype L] [LinearOrder L] in +lemma edge_inf_lt_sup (e : BagEdge bags) : e.val.val.1.inf(ne_of_lt (edge_inf_lt_sup e)) ((orderedEnum V).symm.injective h)⟩,by + intro i hi + rcases Sym2.mem_iff.mp hi with rfl|rfl + · rw [mem_numberedBags] + simpa only [ColoredEdge.color,Equiv.apply_symm_apply] using e.property _ (source_inf_mem _) + · rw [mem_numberedBags] + simpa only [ColoredEdge.color,Equiv.apply_symm_apply] using e.property _ (source_sup_mem _)⟩ +lemma key_downEdge (e : BagEdge bags) : key (downEdge e)=sourceKey e := by + have h : (orderedEnum V).symm e.val.val.1.inf≤(orderedEnum V).symm e.val.val.1.sup := by + change Numbered.index e.val.val.1.inf≤Numbered.index e.val.val.1.sup + exact (Numbered.index_le _ _).mpr e.val.val.1.inf_le_sup + simp only [key,downEdge,Sym2.inf_mk,Sym2.sup_mk,inf_eq_left.mpr h,sup_eq_right.mpr h,sourceKey,Numbered.index] + +def upEdge (e : BagEdge (numberedBags bags)) : BagEdge bags := + ⟨⟨(s(orderedEnum V e.val.val.1.inf,orderedEnum V e.val.val.1.sup), + orderedEnum L e.val.val.2),by + rw [Sym2.mk_isDiag_iff] + exact fun h=>(ne_of_lt (edge_inf_lt_sup e)) ((orderedEnum V).injective h)⟩,by + intro i hi + rcases Sym2.mem_iff.mp hi with rfl|rfl + · exact (mem_numberedBags bags _ _).mp (e.property _ (sym_inf_mem _)) + · exact (mem_numberedBags bags _ _).mp (e.property _ (sym_sup_mem _))⟩ +lemma sourceKey_upEdge (e : BagEdge (numberedBags bags)) : sourceKey (upEdge e)=key e := by + have h : orderedEnum V e.val.val.1.inf≤orderedEnum V e.val.val.1.sup := by + exact ((Numbered.index_le _ _).mp (by simpa only [Numbered.index_orderedEnum,Fin.le_def] using e.val.val.1.inf_le_sup)) + simp only [sourceKey,upEdge,Sym2.inf_mk,Sym2.sup_mk,inf_eq_left.mpr h,sup_eq_right.mpr h,Numbered.index_orderedEnum,key] + +lemma sourceCatalog_eq : sourceCatalog bags=catalog (numberedBags bags) := by + have ha : (sourceCatalog bags).Nodup := List.nodup_ofFn.mpr + ((sourceKey_injective (bags:=bags)).comp (orderedEnum (BagEdge bags)).injective) + have hb : (catalog (numberedBags bags)).Nodup := List.nodup_ofFn.mpr + ((key_injective (bags:=numberedBags bags)).comp (orderedEnum (BagEdge (numberedBags bags))).injective) + have hp : (sourceCatalog bags).Perm (catalog (numberedBags bags)) := by + apply (List.perm_ext_iff_of_nodup ha hb).mpr + intro k + simp only [sourceCatalog,catalog,List.mem_ofFn] + constructor + · rintro ⟨i,rfl⟩ + refine ⟨(orderedEnum _).symm (downEdge (orderedEnum _ i)),?_⟩ + rw [Equiv.apply_symm_apply,key_downEdge] + · rintro ⟨i,rfl⟩ + refine ⟨(orderedEnum _).symm (upEdge (orderedEnum _ i)),?_⟩ + rw [Equiv.apply_symm_apply,sourceKey_upEdge] + apply hp.eq_of_pairwise (fun _ _ _ _ h₁ h₂=>@le_antisymm _ Transport.prodOrder.toPartialOrder _ _ h₁ h₂) sourceCatalog_pairwise + rw [catalog,show (fun i=>key (orderedEnum (BagEdge (numberedBags bags)) i))= + key ∘ orderedEnum (BagEdge (numberedBags bags)) from rfl,←List.map_ofFn,ofFn_orderedEnum] + apply List.pairwise_map.mpr + exact (Finset.pairwise_sort _ _).imp (fun h=>(key_le _ _).mpr h) +end MatchingFPRAS.ExecutableRefresh + +end OAI diff --git a/lean/OAI/Combinatorics/MatchingCount/Machines/TreeRefreshTables.lean b/lean/OAI/Combinatorics/MatchingCount/Machines/TreeRefreshTables.lean new file mode 100644 index 0000000000000000000000000000000000000000..d94a987bdcf66a3580325eaf13c17c5d380c74ee --- /dev/null +++ b/lean/OAI/Combinatorics/MatchingCount/Machines/TreeRefreshTables.lean @@ -0,0 +1,116 @@ +import Mathlib +import OAI.Combinatorics.MatchingCount.Graphs.TreeInitialMatching +import OAI.Combinatorics.MatchingCount.Machines.TreeOrderedTransport +import OAI.Combinatorics.MatchingCount.Graphs.TreeBags + +namespace OAI + +namespace MatchingFPRAS.ExecutableHierarchy +open TreeTyped TreeTyped.Numbered ExecutableDP ExecutableRefresh NumberedHierarchy + +def labelIndices (x : HierarchyInput) : List ℕ := List.range (labels x).length +def labelIndicesRealizer : Realizer labelIndices := (composition + labelsRealizer (composition listLength range)).congr (fun _=>rfl) +lemma polynomial_labelIndices : PolynomialTime labelIndicesRealizer := by + unfold labelIndicesRealizer + apply polynomial_congr + have h : PolynomialTime (composition (listLength (A:=LabelKey)) range) := + polynomial_boundedRange polynomial_listLength Polynomial.X (fun x=>by + simpa using list_length_le_weight x) + exact polynomial_composition polynomial_labels h + +def refreshTables (x : BagInput) : InitialInput := + let a:=bagTable x + (storedCatalog (a,labelIndices x.1),((a,parents x.1),rankPlan (ranks x.1))) +def refreshTablesRealizer : Realizer refreshTables := (pair + (composition (pair bagTableRealizer (composition first labelIndicesRealizer)) storedCatalogRealizer) + (pair (pair bagTableRealizer (composition first parentsRealizer)) + (composition (composition first ranksRealizer) rankPlanRealizer))).congr (fun _=>rfl) +lemma polynomial_refreshTables : PolynomialTime refreshTablesRealizer := by + unfold refreshTablesRealizer + apply polynomial_congr + have := polynomial_bagTable + have := polynomial_labelIndices + have := polynomial_storedCatalog + have := polynomial_parents + have := polynomial_ranks + have := polynomial_rankPlan + tree_cost + +def initialFromHierarchy (x : BagInput) : Finset ℕ := ExecutableRefresh.initial (refreshTables x) +def initialFromHierarchyRealizer : Realizer initialFromHierarchy := composition refreshTablesRealizer initialRealizer +lemma polynomial_initialFromHierarchy : PolynomialTime initialFromHierarchyRealizer := + polynomial_composition polynomial_refreshTables polynomial_initial + +attribute [local instance] NumberedHierarchy.labelOrder +attribute [local instance] Transport.sym2Order Transport.bagEdgeOrder Transport.bagEdgeFintype +variable {V : Type} [Fintype V] [LinearOrder V] +variable (B : V→V→ℚ) (hB : ∀ a b,0≤B a b) + (hsym : ∀ a b,B a b=B b a) + (htri : ∀ x y z,x≠y → x≠z → y≠z → min (B x z) (B z y)≤B x y) +include hB in +lemma arbitrary_labelIndices (xs : List Bool) : + labelIndices (ExecutableBottleneck.matrixRep (reindex B (orderedIso V)),xs)= + List.range (Fintype.card (Label B xs.length)) := by + unfold labelIndices + rw [labels_eq_ofFn _ (fun i j=>hB _ _),List.length_ofFn, + Fintype.card_congr (labelReindex B (orderedIso V) xs.length)] + +variable (xs : List Bool) {E : Type} [Fintype E] [DecidableEq E] (left right : E→V) + (es : List (ℕ×ℕ)) + (hes : ∀ p,p∈es ↔ ∃ e,(index (left e),index (right e))=p) + +include hB in +lemma refreshTables_rep : + refreshTables ((ExecutableBottleneck.matrixRep (reindex B (orderedIso V)),xs),es)= + let a:=bagTable ((ExecutableBottleneck.matrixRep (reindex B (orderedIso V)),xs),es) + (storedCatalog (a,List.range (Fintype.card (Label B xs.length))), + ((a,parentRep (UnitRefresh.numberedParent (parent B hsym htri (H:=xs.length)))), + (UnitRefresh.Materialized.plan (UnitRefresh.numberedRank + (fun l : Label B xs.length=>l.1.val))).map Fin.val)) := by + unfold refreshTables + dsimp only + rw [arbitrary_labelIndices B hB,arbitrary_parents B hB hsym htri,arbitrary_plan B hB] + +include hB hes in +lemma initialFromHierarchy_valid + (hb : UnitRefresh.RankedBags (bags B hsym htri left right xs.length) + (fun l=>l.1.val) (parent B hsym htri)) + (hne : ∀ v,(bags B hsym htri left right xs.length v).Nonempty) + (hex : Nonempty (Transport.BagPM (bags B hsym htri left right xs.length))) : + ∃ M : Transport.BagPM (bags B hsym htri left right xs.length), + initialFromHierarchy ((ExecutableBottleneck.matrixRep (reindex B (orderedIso V)),xs),es)= + Numbered.set M.val := by + unfold initialFromHierarchy + rw [refreshTables_rep B hB hsym htri] + exact initial_valid _ _ _ hb hne (fun l p h=>parent_rank B hsym htri h) hex _ + (arbitrary_bagTable_numbered B hB hsym htri xs left right es hes xs.length rfl) + +include hB hes in +lemma initialFromHierarchy_valid_fintype (H : ℕ) (hH : xs.length=H) + (F : Fintype (Label B H)) : + letI := F + UnitRefresh.RankedBags (bags B hsym htri left right H) + (fun l=>l.1.val) (parent B hsym htri) → + (∀ v,(bags B hsym htri left right H v).Nonempty) → + Nonempty (Transport.BagPM (bags B hsym htri left right H)) → + ∃ M : Transport.BagPM (bags B hsym htri left right H), + initialFromHierarchy ((ExecutableBottleneck.matrixRep (fun i j=> B + (UnitRefresh.orderedEnum V i) (UnitRefresh.orderedEnum V j)),xs),es)= + Numbered.set M.val := by + subst H + have hF : F=ordinaryLabelFintype B xs.length := Subsingleton.elim _ _ + subst F + exact initialFromHierarchy_valid B hB hsym htri xs left right es hes + +open TreePost Turing + +theorem initialFromHierarchy_post : ∃ p : Polynomial ℕ,∀ x : BagInput,∀ t : ℕ, + p.eval (packed x).length≤t → ∀ coins : Fin t→Bool, + (run (machine initialFromHierarchyRealizer.program) (packed x) coins).state=none ∧ + (run (machine initialFromHierarchyRealizer.program) (packed x) coins).tape.right₀= + ListBlank.mk (packed (initialFromHierarchy x)) := + polynomial_compiles initialFromHierarchyRealizer polynomial_initialFromHierarchy +end MatchingFPRAS.ExecutableHierarchy + +end OAI diff --git a/lean/OAI/Combinatorics/MatchingCount/Machines/TreeRepeat.lean b/lean/OAI/Combinatorics/MatchingCount/Machines/TreeRepeat.lean new file mode 100644 index 0000000000000000000000000000000000000000..76344c440a2b000add78bd9866746ccd801e955f --- /dev/null +++ b/lean/OAI/Combinatorics/MatchingCount/Machines/TreeRepeat.lean @@ -0,0 +1,120 @@ +import Mathlib +import OAI.Combinatorics.MatchingCount.Machines.TreeList +import OAI.Combinatorics.MatchingCount.Machines.TreePartialChoice + +namespace OAI + +namespace MatchingFPRAS.TreeTyped +open TreeData TreeMachine RegisterProc TreeFunction + +variable {B : Type} [Codec B] + +def predecessor : Realizer (fun n : ℕ=>n-1) := composition (pair identity (constant 1)) subtract + +def countDown (f : ℕ×B → B) : ℕ → B → B + | 0,b => b + | n+1,b => countDown f n (f (n+1,b)) + +namespace Repeat +open RegisterControl (Instr Runs Effect) + +inductive Point where | loop | check | rebuild | body | halt + deriving DecidableEq, Inhabited +instance : Fintype Point := ⟨{.loop,.check,.rebuild,.body,.halt},by intro p; cases p <;> simp⟩ +def next (f : ℕ×B → B) (nb : ℕ×B) : ℕ×B := (nb.1-1,f nb) +def nextRealizer {f : ℕ×B → B} (F : Realizer f) : Realizer (next f) := + pair (composition first predecessor) F + +def code (P : Proc (K Reg)) : Point → RegisterControl.Instr Reg Point + | .loop => .call (TreeFunction.split 1 0 (by decide)) .check + | .check => .branch 1 .halt .rebuild + | .rebuild => .call (TreeFunction.cons 1 0 (by decide)) .body + | .body => .call P .loop + | .halt => .halt + +def cost (f : ℕ×B → B) (t : ℕ×B → ℕ) : ℕ → B → ℕ + | 0,_ => 10 + | n+1,b => t (n+1,b)+4*TreeFunction.size (nat (n+1))+12+cost f t n (f (n+1,b)) + +lemma runs {f : ℕ×B → B} (F : Realizer f) (n : ℕ) (b : B) (s : Data) : + Runs (code (nextRealizer F).program) (some Point.loop) (env (encode (n,b)) .nil s) + (env (encode (countDown f n b)) .nil s) (cost f (nextRealizer F).cost n b) := by + induction n generalizing b with + | zero => + have hh : Runs (code (nextRealizer F).program) (some Point.halt) (env (encode b) .nil s) + (env (encode b) .nil s) 1 := Runs.step _ _ _ _ _ 0 1 (Effect.halt _) (Runs.done _) + have hc : Runs (code (nextRealizer F).program) (some Point.check) (env (encode b) .nil s) + (env (encode b) .nil s) 2 := Runs.step _ _ _ _ _ 1 1 (Effect.nilBranch _ 1 _ _ rfl) hh + have hs := split10 (nat 0) (encode b) .nil s + change Exec _ _ _ 7 at hs + exact Runs.step _ _ _ _ _ 2 8 (Effect.call _ _ _ _ 7 hs) hc + | succ n ih => + have hr:=ih (f (n+1,b)) + have hb:=(nextRealizer F).correct (n+1,b) s + have he : next f (n+1,b)=(n,f (n+1,b)) := by simp [next] + change Exec _ _ (encodeEnv (env (encode (next f (n+1,b))) .nil s)) _ at hb + rw [he] at hb + let c := cost f (nextRealizer F).cost n (f (n+1,b)) + let t := (nextRealizer F).cost (n+1,b) + let d := TreeFunction.size (nat (n+1)) + have hbody : Runs (code (nextRealizer F).program) (some Point.body) (env (encode (n+1,b)) .nil s) + (env (encode (countDown f n (f (n+1,b)))) .nil s) ((t+1)+c) := + Runs.step _ _ _ _ _ c (t+1) (Effect.call _ _ _ _ t hb) hr + have hcons:=cons10 (encode b) (nat (n+1)) s + have hreb : Runs (code (nextRealizer F).program) (some Point.rebuild) (env (encode b) (nat (n+1)) s) + (env (encode (countDown f n (f (n+1,b)))) .nil s) ((2*d+4)+((t+1)+c)) := + Runs.step _ _ _ _ _ _ (2*d+4) (Effect.call _ _ _ _ (2*d+3) hcons) hbody + have hn : ∃ a z,nat (n+1)=.cons a z := by + cases he : (n+1).bits with + | nil => + have hv:=StackAddition.value_bits (n+1) + rw [he] at hv + simp [StackAddition.value] at hv + | cons a z => exact ⟨bit a,bits z,by change bits (n+1).bits=Data.cons (bit a) (bits z); rw [he]; rfl⟩ + obtain ⟨a,z,ha⟩:=hn + have hc : Runs (code (nextRealizer F).program) (some Point.check) (env (encode b) (nat (n+1)) s) + (env (encode (countDown f n (f (n+1,b)))) .nil s) (1+((2*d+4)+((t+1)+c))) := + Runs.step _ _ _ _ _ _ 1 (Effect.consBranch _ 1 _ _ a z ha) hreb + have hs:=split10 (nat (n+1)) (encode b) .nil s + have hs' := hs.mono (show TreeFunction.size Data.nil+2*d+4 ≤ 2*d+5 by simp only [size_nil]; omega) + have hh : Runs (code (nextRealizer F).program) (some Point.loop) (env (encode (n+1,b)) .nil s) + (env (encode (countDown f n (f (n+1,b)))) .nil s) ((2*d+6)+(1+((2*d+4)+((t+1)+c)))) := + Runs.step _ _ _ _ _ _ (2*d+6) (Effect.call _ _ _ _ (2*d+5) hs') hc + convert hh using 1 + all_goals try rfl + simp only [cost,d,t,c] + omega +end Repeat + +def iterateDown {f : ℕ×B → B} (F : Realizer f) : Realizer (fun nb : ℕ×B=>countDown f nb.1 nb.2) := + ⟨RegisterControl.compile (Repeat.code (Repeat.nextRealizer F).program), + fun nb=>Repeat.cost f (Repeat.nextRealizer F).cost nb.1 nb.2, + fun nb s=>RegisterControl.compile_exec _ _ _ _ (Repeat.runs F nb.1 nb.2 s)⟩ + +def rangeStep (x : ℕ×List ℕ) : List ℕ := (x.1-1)::x.2 +def rangeStepRealizer : Realizer rangeStep := composition (pair (composition first predecessor) second) listCons +lemma countDown_range (n : ℕ) (as : List ℕ) : countDown rangeStep n as=List.range n++as := by + induction n generalizing as with + | zero => rfl + | succ n ih => simp [countDown,rangeStep,ih,List.range_succ,List.append_assoc] +def range : Realizer List.range := + (composition (pair identity (constant ([] : List ℕ))) (iterateDown rangeStepRealizer)).congr (by + intro n; simp [countDown_range]) + +omit [Codec B] in +lemma Repeat.cost_bound {f : ℕ×B → B} (t : ℕ×B → ℕ) (I : ℕ → B → Prop) (N : ℕ) (b : B) + (T S : ℕ) (hb : I N b) + (hstep : ∀ n simp [cost] + | succ n ih => + have hs:=hstep n (by omega) b hb + have ht:=ih (f (n+1,b)) hs.1 (fun k hk z hz=>hstep k (by omega) z hz) (fun k hk=>hsize k (by omega)) + have hz:=hsize n (by omega) + simp only [cost] + nlinarith +end MatchingFPRAS.TreeTyped + +end OAI diff --git a/lean/OAI/Combinatorics/MatchingCount/Machines/TreeScaleStateUpdate.lean b/lean/OAI/Combinatorics/MatchingCount/Machines/TreeScaleStateUpdate.lean new file mode 100644 index 0000000000000000000000000000000000000000..d4ffdaeafc266848f42b84dc88437e4526259c1d --- /dev/null +++ b/lean/OAI/Combinatorics/MatchingCount/Machines/TreeScaleStateUpdate.lean @@ -0,0 +1,75 @@ +import Mathlib +import OAI.Combinatorics.MatchingCount.Algorithm.TreeStageUpdateCorrect +import OAI.Combinatorics.MatchingCount.Algorithm.TreeStatistics + +namespace OAI + +namespace MatchingFPRAS.NumericMarking +open TreeTyped TreeFraction TreeTyped.Numbered ExecutableStatistics ExecutableLadder + + ExecutableEstimator ExecutableBottleneck ExecutableScaling ExecutableAdaptive ExecutableSource +open Finset Transport Enlargement + +variable {G : GraphInput} {j K S : ℕ} [Nontrivial (Fin G.n)] +attribute [local instance] NumberedHierarchy.labelOrder sym2Order bagEdgeOrder bagEdgeFintype +attribute [local instance] UnitRefresh.Computable.allowedDec prodOrder sumOrder +noncomputable local instance (w : Fin G.n→Fin G.n→ℚ) (K : ℕ) : + DecidableEq (SourceLabel (fun x y=>(w x y:ℝ)) K) := Classical.decEq _ +noncomputable local instance (w : Fin G.n→Fin G.n→ℚ) (K : ℕ) : + Fintype (BagEdge (sourceBags (fun x y=>(w x y:ℝ)) K)) := Fintype.ofFinite _ + +noncomputable def sourceUpdateConfig (s : FiniteTrial.ScaleState G j) (K : ℕ) : UpdateConfig := + ((FiniteTrial.sourceD (G:=G) K,List.range G.n), + ((List.ofFn (UnitRefresh.orderedEnum (LogicalEdge (Fin G.n)))).map + (fun e=>(logicalRepr e,index (RationalSource.centralEdge s.activity K e))),vectorRep s.scale)) +noncomputable def sourceStatisticsInput (s : FiniteTrial.ScaleState G j) (K : ℕ) + (x : Fin S→RationalSource.Marked s.activity K) : Inputs := + ((reweightsRep (RationalSource.bagReweight s.activity s.nextActivity K), + (FiniteTrial.sourceD (G:=G) K,(sourceKeys s.activity K).map index)),sourceSamples s.activity K x) + +lemma scaleState_update_rep (hn : 2≤G.n) (s : FiniteTrial.ScaleState G j) + (x : Fin S→RationalSource.Marked s.activity K) : + finishUpdate (sourceUpdateConfig s K,summaries (sourceStatisticsInput s K x))= + (TreeFraction.repr (s.ratioEstimate x),vectorRep (s.update hn x).scale) := by + unfold sourceStatisticsInput + rw [summaries_source s.activity s.nextActivity K x + (fun i j=>(s.activity_pos i j).le) (fun i j=>(s.nextActivity_pos i j).le)] + let z := fun e=>(∑ i,scalarProbe (fun j=>(x j).1.val) + (fun j=>selectedMarks (x j).1.val (x j).2) + (RationalSource.bagReweight s.activity s.nextActivity K) e i)/(S:ℚ) + have hr := reweight_nonneg s.activity s.nextActivity + (fun i j=>(s.activity_pos i j).le) (fun i j=>(s.nextActivity_pos i j).le) K + have hz : ∀ e,0≤z e := by + intro e + apply div_nonneg _ (Nat.cast_nonneg _) + apply Finset.sum_nonneg + intro i _ + unfold scalarProbe + split_ifs + · exact Finset.prod_nonneg (fun a _=>hr a) + · exact le_rfl + have hd : 0≤FiniteTrial.sampleAverage (RationalSource.observableD s.activity s.nextActivity K) x := by + apply div_nonneg _ (Nat.cast_nonneg _) + apply Finset.sum_nonneg + intro i _ + unfold RationalSource.observableD + split_ifs + · exact Finset.prod_nonneg (fun a _=>hr a) + · exact le_rfl + change finishUpdate (((FiniteTrial.sourceD (G:=G) K,List.range G.n), + ((List.ofFn (UnitRefresh.orderedEnum (LogicalEdge (Fin G.n)))).map + (fun e=>(logicalRepr e,index (RationalSource.centralEdge s.activity K e))),vectorRep s.scale)), + ((TreeFraction.repr (s.ratioEstimate x),TreeFraction.repr + (FiniteTrial.sampleAverage (RationalSource.observableD s.activity s.nextActivity K) x)), + (sourceKeys s.activity K).map (fun e=>(index e,TreeFraction.repr (z e)))))=_ + rw [finishUpdate_rep hn (RationalSource.centralEdge s.activity K) (sourceKeys s.activity K) + (mem_sourceKeys s.activity K) z hz _ _ _ hd s.scale (fun i=>(s.positive i).le)] + have he : z ∘ RationalSource.centralEdge s.activity K= + (fun e=>FiniteTrial.sampleAverage (RationalSource.observableProbe s.activity s.nextActivity K e) x) := by + funext e + simp only [z,Function.comp_def,scalarProbe_source,FiniteTrial.sampleAverage] + rw [he] + rfl +end MatchingFPRAS.NumericMarking + +end OAI diff --git a/lean/OAI/Combinatorics/MatchingCount/Machines/TreeSlotIndex.lean b/lean/OAI/Combinatorics/MatchingCount/Machines/TreeSlotIndex.lean new file mode 100644 index 0000000000000000000000000000000000000000..7d3a879775db0cd545567036172a8e2ad2319337 --- /dev/null +++ b/lean/OAI/Combinatorics/MatchingCount/Machines/TreeSlotIndex.lean @@ -0,0 +1,60 @@ +import Mathlib +import OAI.Combinatorics.MatchingCount.Tapes.TreeNumberedCodec + +namespace OAI + +namespace MatchingFPRAS.NumericLadder +open TreeTyped TreeTyped.Numbered Replica.Ladder + +def coordinateEquiv (T q : ℕ) : Slot T q ≃ Fin ((T+1)*q) := + ({toFun:=ofLex,invFun:=toLex,left_inv:=fun _=>rfl,right_inv:=fun _=>rfl} : Slot T q≃Fin (T+1)×Fin q).trans finProdFinEquiv +lemma coordinate_le {T q : ℕ} (a b : Slot T q) : coordinateEquiv T q a≤coordinateEquiv T q b ↔ a≤b := by + change (ofLex a).2.val+q*(ofLex a).1.val≤(ofLex b).2.val+q*(ofLex b).1.val ↔ a≤b + rw [Prod.Lex.le_iff] + have ha:=(ofLex a).2.isLt + have hb:=(ofLex b).2.isLt + change _ ↔ ((ofLex a).1.val<(ofLex b).1.val ∨ (ofLex a).1=(ofLex b).1 ∧ (ofLex a).2.val≤(ofLex b).2.val) + constructor + · intro h + by_cases hlt : (ofLex a).1.val<(ofLex b).1.val + · exact Or.inl hlt + · have hge : (ofLex b).1.val≤(ofLex a).1.val := Nat.le_of_not_gt hlt + have he : (ofLex a).1.val=(ofLex b).1.val := by + by_contra hh + have hs : (ofLex b).1.val+1≤(ofLex a).1.val := by omega + have hm:=Nat.mul_le_mul_left q hs + nlinarith + exact Or.inr ⟨Fin.ext he,by rw [he] at h; omega⟩ + · rintro (h|⟨h,h'⟩) + · have hm:=Nat.mul_le_mul_left q h + nlinarith + · rw [h]; omega + +def coordinateOrderIso (T q : ℕ) : Slot T q ≃o Fin ((T+1)*q) := + { coordinateEquiv T q with map_rel_iff' := fun {a b}=>coordinate_le a b } +lemma slot_card (T q : ℕ) : Fintype.card (Slot T q)=(T+1)*q := by simp [Slot] +def numberOrderIso (T q : ℕ) : Slot T q ≃o Fin ((T+1)*q) := by + let e : Slot T q ≃o Fin (Fintype.card (Slot T q)) := + { toEquiv := (UnitRefresh.orderedEnum (Slot T q)).symm + map_rel_iff' := by + intro a b + change ((UnitRefresh.orderedEnum (Slot T q)).symm a).val ≤ + ((UnitRefresh.orderedEnum (Slot T q)).symm b).val ↔ a ≤ b + exact index_le a b } + exact e.trans (Fin.castOrderIso (slot_card T q)) +lemma slot_index {T q : ℕ} (x : Slot T q) : index x=q*rank x+(ofLex x).2.val := by + have he : numberOrderIso T q=coordinateOrderIso T q := Subsingleton.elim _ _ + have h:=congrArg (fun e : Slot T q≃o Fin ((T+1)*q)=>(e x).val) he + change index x=(ofLex x).2.val+q*(ofLex x).1.val at h + simpa only [rank,Nat.add_comm] using h +lemma slot_default_zero (T q : ℕ) (hq : 0x.1)) +def fuelPowerRealizer : Realizer fuelPower := composition (mapWith first) productRealizer +lemma polynomial_fuelPower : PolynomialTime fuelPowerRealizer := + polynomial_composition (polynomial_mapWith polynomial_first) polynomial_product +lemma fuelPower_repr (q : ℚ) (hq : 0≤q) (fuel : List Bool) : + fuelPower (repr q,fuel)=repr (q^fuel.length) := by + unfold fuelPower + have he : fuel.map (fun _=>repr q)=(fuel.map (fun _=>q)).map repr := by simp + rw [he,product_repr _ (by intro t ht; obtain ⟨b,hb,rfl⟩:=List.mem_map.mp ht; exact hq)] + congr 1 + simp +end MatchingFPRAS.TreeFraction + +namespace MatchingFPRAS.ExecutableLadder +open TreeTyped TreeFraction + +def tierBase (n : ℕ) : Fraction := add ((1,1),div ((1,1),(n*n,1))) +def tierBaseRealizer : Realizer tierBase := (composition (pair (constant (1,1)) + (composition (pair (constant (1,1)) (pair (composition (pair identity identity) multiply) (constant 1))) divRealizer)) addRealizer).congr (fun _=>rfl) +lemma polynomial_tierBase : PolynomialTime tierBaseRealizer := by + unfold tierBaseRealizer + apply polynomial_congr + have := TreeFraction.polynomial_add + have := polynomial_div + tree_cost +lemma tierBase_repr (n : ℕ) : tierBase n=TreeFraction.repr (1+((n:ℚ)^2)⁻¹) := by + unfold tierBase + rw [←repr_nat (n*n)] + have h1 : (1,1)=TreeFraction.repr (1:ℚ) := rfl + rw [h1,div_repr (by decide) (by positivity),add_repr (by decide) (by positivity)] + simp only [Nat.cast_mul,one_div,pow_two] + +abbrev TierInput := (ℕ×List Bool)×ℕ + +def tierPower (x : TierInput) : Fraction := + fuelPower (tierBase x.1.1,x.1.2.take (x.1.2.length-x.2)) +def tierPowerRealizer : Realizer tierPower := (composition (pair (composition first.fst tierBaseRealizer) + (composition (pair first.snd (composition (pair (composition first.snd listLength) second) subtract)) takeFast)) fuelPowerRealizer).congr (fun _=>rfl) +lemma polynomial_tierPower : PolynomialTime tierPowerRealizer := by + unfold tierPowerRealizer Realizer.fst Realizer.snd + apply polynomial_congr + have := polynomial_tierBase + have := polynomial_takeFast (A:=Bool) + have := polynomial_fuelPower + tree_cost +lemma tierPower_repr (n : ℕ) (fuel : List Bool) (r : ℕ) : + tierPower ((n,fuel),r)=TreeFraction.repr ((1+((n:ℚ)^2)⁻¹)^(fuel.length-r)) := by + unfold tierPower + rw [tierBase_repr,fuelPower_repr _ (by positivity),List.length_take,min_eq_left (Nat.sub_le _ _)] + +def slotWeight (x : TierInput×Fraction) : Fraction := + maximum (div ((1,1),tierPower x.1),minimum (tierPower x.1,x.2)) +def slotWeightRealizer : Realizer slotWeight := by + let P : Realizer (fun x : TierInput×Fraction=>tierPower x.1) := (composition first tierPowerRealizer).congr (fun _=>rfl) + exact (composition (pair (composition (pair (constant (1,1)) P) divRealizer) + (composition (pair P second) minimumRealizer)) maximumRealizer).congr (fun _=>rfl) +lemma polynomial_slotWeight : PolynomialTime slotWeightRealizer := by + unfold slotWeightRealizer + dsimp only + apply polynomial_congr + have := polynomial_tierPower + have := polynomial_div + have := TreeFraction.polynomial_minimum + have := TreeFraction.polynomial_maximum + tree_cost +lemma slotWeight_repr (n : ℕ) (fuel : List Bool) (r : ℕ) (q : ℚ) (hq : 0≤q) : + slotWeight (((n,fuel),r),TreeFraction.repr q)=TreeFraction.repr + (max (((1+((n:ℚ)^2)⁻¹)^(fuel.length-r))⁻¹) + (min ((1+((n:ℚ)^2)⁻¹)^(fuel.length-r)) q)) := by + unfold slotWeight + rw [tierPower_repr] + have h1 : (1,1)=TreeFraction.repr (1:ℚ) := rfl + rw [h1,div_repr (by decide) (by positivity),minimum_repr (by positivity) hq, + maximum_repr (by positivity) (le_min (by positivity) hq)] + simp only [one_div] + +lemma slotWeight_source {V L : Type} [Fintype V] [LinearOrder V] [Fintype L] [LinearOrder L] + {bags : V→Finset L} {q : ℕ} (fuel : List Bool) (w : Transport.BagEdge bags→ℚ) + (hw : ∀ e,0≤w e) (x : Replica.Ladder.Slot fuel.length q) (e : Transport.BagEdge bags) : + slotWeight (((Fintype.card V,fuel),Replica.Ladder.rank x),TreeFraction.repr (w e))= + TreeFraction.repr (Transport.rationalSlotWeight w x e) := by + exact slotWeight_repr _ _ _ _ (hw e) +end MatchingFPRAS.ExecutableLadder + +end OAI diff --git a/lean/OAI/Combinatorics/MatchingCount/Machines/TreeStart.lean b/lean/OAI/Combinatorics/MatchingCount/Machines/TreeStart.lean new file mode 100644 index 0000000000000000000000000000000000000000..38ba7ba7877650628265dc0b541c48a630c35f6d --- /dev/null +++ b/lean/OAI/Combinatorics/MatchingCount/Machines/TreeStart.lean @@ -0,0 +1,122 @@ +import Mathlib +import OAI.Combinatorics.MatchingCount.Machines.TreeColor + +namespace OAI + +namespace MatchingFPRAS.ExecutableSource +open TreeTyped TreeFraction TreeTyped.Numbered ExecutableBottleneck ExecutableHierarchy ExecutableRefresh Enlargement RealGeometry + +attribute [local instance] NumberedHierarchy.labelOrder +attribute [local instance] Transport.sym2Order Transport.bagEdgeOrder Transport.bagEdgeFintype + +def evenTest : Realizer (fun n : ℕ=>decide (n%2=0)) := + composition (pair (composition (pair identity (constant 2)) remainder) (constant 0)) natEqual +lemma polynomial_evenTest : PolynomialTime evenTest := by + unfold evenTest + have := polynomial_remainder + tree_cost + +def mateIndex (n : ℕ) : ℕ := if n%2=0 then n+1 else n-1 +def mateIndexRealizer : Realizer mateIndex := (choose evenTest + (composition (pair identity (constant 1)) TreeTyped.add) + (composition (pair identity (constant 1)) subtract)).congr (by intro n; simp only [mateIndex,Function.comp_apply,id_eq,decide_eq_true_eq]) +lemma polynomial_mateIndex : PolynomialTime mateIndexRealizer := by + unfold mateIndexRealizer + apply polynomial_congr + have := polynomial_evenTest + tree_cost +lemma mateIndex_source {n : ℕ} (he : Even n) (i : Fin n) : + mateIndex i.val=(RationalSource.pairIndex he i).val := by + simp only [mateIndex,RationalSource.pairIndex] + split_ifs <;> rfl + +def startSelected (e : RawReal) : Bool := + Subdivision.alternating (decide (mateIndex e.1.1=e.1.2)) e.2 +def startSelectedRealizer : Realizer startSelected := + (choose (composition second evenTest) + (composition (pair (composition first.fst mateIndexRealizer) first.snd) natEqual) + (composition (composition (pair (composition first.fst mateIndexRealizer) first.snd) natEqual) boolNot)).congr + (by intro e; simp only [startSelected,Subdivision.alternating,Function.comp_apply,decide_eq_true_eq]) +lemma polynomial_startSelected : PolynomialTime startSelectedRealizer := by + unfold startSelectedRealizer + dsimp only [Realizer.fst,Realizer.snd] + apply polynomial_congr + have := polynomial_evenTest + have := polynomial_mateIndex + tree_cost +lemma startSelected_source {n : ℕ} (K : ℕ) (he : Even n) (e : SourceRealEdge (Fin n) K) : + startSelected (realRepr e)=Subdivision.alternating + (RationalSource.selectMate (RationalSource.orderedMate he) e.1) e.2.val := by + unfold startSelected realRepr logicalRepr + rw [mateIndex_source he] + congr 1 + change decide ((RationalSource.pairIndex he _).val=_)=decide (RationalSource.pairIndex he _=_) + congr 1 + exact propext Fin.val_inj + +def exactStart (x : BagBuildInput) : Finset ℕ := + (((realEdges (x.1.2,x.1.1.2)).filter startSelected).map + (fun e=>sourceRealIndex (x,e))).toFinset +def exactStartRealizer : Realizer exactStart := (composition + (composition (pair identity (composition (composition + (pair first.snd first.fst.snd) realEdgesRealizer) (filter startSelectedRealizer))) + (mapWith sourceRealIndexRealizer)) (listFinset natEqual leNat)).congr (fun _=>rfl) +lemma polynomial_exactStart : PolynomialTime exactStartRealizer := by + unfold exactStartRealizer + dsimp only [Realizer.fst,Realizer.snd] + apply polynomial_congr + have := polynomial_realEdges + have := polynomial_filter polynomial_startSelected + have := polynomial_mapWith polynomial_sourceRealIndex + have := polynomial_listFinset polynomial_natEqual polynomial_leNat + tree_cost + +lemma numbered_map_image {A B : Type} [Fintype A] [LinearOrder A] [DecidableEq B] + (f : B↪A) (s : Finset B) : Numbered.set (s.map f)=s.image (fun b=>index (f b)) := by + unfold Numbered.set + rw [Finset.map_map] + exact Finset.map_eq_image _ _ + +lemma startMatching_set {n : ℕ} [Nontrivial (Fin n)] (w : Fin n→Fin n→ℚ) + (K : ℕ) (he : Even n) : + Numbered.set (RationalSource.startMatching w K he).val= + (RationalSource.startSet K he).image (fun a=>index (RationalSource.coloredReal w K a)) := + numbered_map_image _ _ + +lemma exactStart_source {n : ℕ} [Nontrivial (Fin n)] (hn : 2≤n) (he : Even n) + (w : Fin n→Fin n→ℚ) (hw : ∀ i j,0≤w i j) (K : ℕ) : + exactStart (((matrixRep w,List.replicate (2*K+2) false),List.range n),List.replicate (2*K) false)= + Numbered.set (RationalSource.startMatching w K he).val := by + rw [startMatching_set] + ext i + change i∈(((realEdges (List.range n,List.replicate (2*K+2) false)).filter startSelected).map + (fun e=>sourceRealIndex ((((matrixRep w,List.replicate (2*K+2) false),List.range n),List.replicate (2*K) false),e))).toFinset ↔ _ + simp only [List.mem_toFinset,List.mem_map,List.mem_filter,Finset.mem_image, + RationalSource.startSet,Finset.mem_filter,Finset.mem_univ,true_and] + constructor + · rintro ⟨e,⟨he',hsel⟩,hi⟩ + have hre : e∈(realEdges (List.range n,List.replicate (2*K+2) false)).toFinset:=List.mem_toFinset.mpr he' + rw [realEdges_finset n K _ (List.length_replicate ..)] at hre + obtain ⟨a,_,rfl⟩:=Finset.mem_image.mp hre + refine ⟨a,?_,?_⟩ + · exact (startSelected_source K he a).symm.trans hsel + · exact (sourceRealIndex_source hn w hw K a).symm.trans hi + · rintro ⟨a,ha,hai⟩ + refine ⟨realRepr a,⟨?_,?_⟩,?_⟩ + · apply List.mem_toFinset.mp + rw [realEdges_finset n K _ (List.length_replicate ..)] + exact Finset.mem_image.mpr ⟨a,Finset.mem_univ _,rfl⟩ + · exact (startSelected_source K he a).trans ha + · exact (sourceRealIndex_source hn w hw K a).trans hai + +open TreePost Turing + +theorem exactStart_post : ∃ p : Polynomial ℕ,∀ x : BagBuildInput,∀ t : ℕ, + p.eval (packed x).length≤t → ∀ coins : Fin t→Bool, + (run (machine exactStartRealizer.program) (packed x) coins).state=none ∧ + (run (machine exactStartRealizer.program) (packed x) coins).tape.right₀= + ListBlank.mk (packed (exactStart x)) := + polynomial_compiles exactStartRealizer polynomial_exactStart +end MatchingFPRAS.ExecutableSource + +end OAI diff --git a/lean/OAI/Combinatorics/MatchingCount/Machines/TreeStateTable.lean b/lean/OAI/Combinatorics/MatchingCount/Machines/TreeStateTable.lean new file mode 100644 index 0000000000000000000000000000000000000000..8283aea4039cb44d68e8be9db572e143a1d94ed8 --- /dev/null +++ b/lean/OAI/Combinatorics/MatchingCount/Machines/TreeStateTable.lean @@ -0,0 +1,92 @@ +import Mathlib +import OAI.Combinatorics.MatchingCount.Machines.TreeLabelTable +import OAI.Combinatorics.MatchingCount.Machines.TreeSum + +namespace OAI + +namespace MatchingFPRAS.ExecutableLadder +open TreeTyped + +variable {I A : Type} [Codec I] [Codec A] [DecidableEq I] [Inhabited I] +abbrev StateTable (I A : Type) := List (I×A) + +def lookup (d : A) (x : StateTable I A×I) : A := + ((x.1.filter (fun z=>decide (z.1=x.2))).headD (x.2,d)).2 +def lookupRealizer (d : A) (E : Realizer (fun x : I×I=>decide (x.1=x.2))) : Realizer (lookup (I:=I) d) := by + let P : Realizer (fun x : I×(I×A)=>decide (x.2.1=x.1)) := composition (pair second.fst first) E + let F := composition (pair second first) (filterWith P) + + let H : Realizer (fun x : I×List (I×A)=>((x.2.headD (x.1,d)).2)) := + (composition (choose (composition second isEmpty) (pair first (constant d)) + (composition second (head (default,d)))) second).congr (by + intro x; rcases x with ⟨i,as⟩; cases as <;> rfl) + exact (composition (pair second F) H).congr (fun _=>rfl) +lemma polynomial_lookup (d : A) {E : Realizer (fun x : I×I=>decide (x.1=x.2))} + (hE : PolynomialTime E) : PolynomialTime (lookupRealizer d E) := by + unfold lookupRealizer + dsimp only + apply polynomial_congr + apply polynomial_composition + · exact polynomial_pair polynomial_second (polynomial_composition + (polynomial_pair polynomial_second polynomial_first) + (polynomial_filterWithList (polynomial_composition + (polynomial_pair (polynomial_fst polynomial_second) polynomial_first) hE))) + · apply polynomial_congr + have := polynomial_isEmpty (A:=I×A) + have := polynomial_head ((default : I),d) + tree_cost + +def stateRep (keys : List I) (s : I→A) : StateTable I A := keys.map (fun i=>(i,s i)) +omit [Codec I] [Codec A] [Inhabited I] in +lemma lookup_stateRep (d : A) (keys : List I) (s : I→A) (i : I) (hi : i∈keys) : + lookup d (stateRep keys s,i)=s i := by + induction keys with + | nil=>simp at hi + | cons j keys ih=> + simp only [List.mem_cons] at hi + by_cases hji : j=i + · subst j + simp [lookup,stateRep] + · have hn : i∈keys:=hi.resolve_left (Ne.symm hji) + simpa [lookup,stateRep,hji] using ih hn + +def setState (x : StateTable I A×(I×A)) : StateTable I A := + x.1.map fun z=>(z.1,if z.1=x.2.1 then x.2.2 else z.2) +def setStateRealizer (E : Realizer (fun x : I×I=>decide (x.1=x.2))) : Realizer (setState (I:=I) (A:=A)) := + (composition (pair second first) (mapWith (pair second.fst + (choose (composition (pair second.fst first.fst) E) first.snd second.snd)))).congr (by + intro x; simp only [setState,Function.comp_apply,decide_eq_true_eq]) +omit [Inhabited I] in +lemma polynomial_setState {E : Realizer (fun x : I×I=>decide (x.1=x.2))} + (hE : PolynomialTime E) : PolynomialTime (setStateRealizer (A:=A) E) := by + unfold setStateRealizer Realizer.fst Realizer.snd + apply polynomial_congr + tree_cost +omit [Codec I] [Codec A] [Inhabited I] in +lemma setState_rep (keys : List I) (s : I→A) (i : I) (a : A) : + setState (stateRep keys s,(i,a))=stateRep keys (Function.update s i a) := by + unfold setState stateRep + simp only [List.map_map] + apply List.map_congr_left + intro j hj + simp only [Function.comp_apply,Function.update_apply] + +def setPair (x : StateTable I A×((I×I)×(A×A))) : StateTable I A := + setState (setState (x.1,(x.2.1.1,x.2.2.1)),(x.2.1.2,x.2.2.2)) +def setPairRealizer (E : Realizer (fun x : I×I=>decide (x.1=x.2))) : Realizer (setPair (I:=I) (A:=A)) := + (composition (pair (composition (pair first (pair second.fst.fst second.snd.fst)) (setStateRealizer E)) + (pair second.fst.snd second.snd.snd)) (setStateRealizer E)).congr (fun _=>rfl) +omit [Inhabited I] in +lemma polynomial_setPair {E : Realizer (fun x : I×I=>decide (x.1=x.2))} + (hE : PolynomialTime E) : PolynomialTime (setPairRealizer (A:=A) E) := by + unfold setPairRealizer Realizer.fst Realizer.snd + apply polynomial_congr + have := polynomial_setState (A:=A) hE + tree_cost +omit [Codec I] [Codec A] [Inhabited I] in +lemma setPair_rep (keys : List I) (s : I→A) (i j : I) (a : A×A) : + setPair (stateRep keys s,((i,j),a))=stateRep keys (Replica.replacePair i j s a) := by + simp only [setPair,setState_rep,Replica.replacePair] +end MatchingFPRAS.ExecutableLadder + +end OAI diff --git a/lean/OAI/Combinatorics/MatchingCount/Machines/TreeSum.lean b/lean/OAI/Combinatorics/MatchingCount/Machines/TreeSum.lean new file mode 100644 index 0000000000000000000000000000000000000000..ec17e05f0ebf620628dd74e13e721fa2f536ddc9 --- /dev/null +++ b/lean/OAI/Combinatorics/MatchingCount/Machines/TreeSum.lean @@ -0,0 +1,113 @@ +import Mathlib +import OAI.Combinatorics.MatchingCount.Complexity.TreeCostTactic + +namespace OAI + +namespace MatchingFPRAS.TreeTyped +variable {A B C D : Type} [Codec A] [Codec B] [Codec C] [Codec D] + +def sumRep [Inhabited A] [Inhabited B] : A⊕B→Bool×(A×B) + | .inl a => (true,(a,default)) + | .inr b => (false,(default,b)) +instance [Inhabited A] [Inhabited B] : Codec (A⊕B) := ⟨fun x=>encode (sumRep x)⟩ + +def inl [Inhabited A] [Inhabited B] : Realizer (Sum.inl : A→A⊕B) := + (pair (constant true) (pair identity (constant (default : B)))).recode id Sum.inl (fun _=>rfl) (fun _=>rfl) +def inr [Inhabited A] [Inhabited B] : Realizer (Sum.inr : B→A⊕B) := + (pair (constant false) (pair (constant (default : A)) identity)).recode id Sum.inr (fun _=>rfl) (fun _=>rfl) +omit [Codec C] [Codec D] in +lemma polynomial_inl [Inhabited A] [Inhabited B] : PolynomialTime (inl (A:=A) (B:=B)) := by + unfold inl + apply polynomial_recode + tree_cost +omit [Codec C] [Codec D] in +lemma polynomial_inr [Inhabited A] [Inhabited B] : PolynomialTime (inr (A:=A) (B:=B)) := by + unfold inr + apply polynomial_recode + tree_cost + +def sumCases [Inhabited A] [Inhabited B] {f : C×A→D} {g : C×B→D} + (F : Realizer f) (G : Realizer g) : Realizer (fun x : C×(A⊕B)=>Sum.elim (fun a=>f (x.1,a)) (fun b=>g (x.1,b)) x.2) := + (choose second.fst (composition (pair first second.snd.fst) F) + (composition (pair first second.snd.snd) G)).recode + (fun x : C×(A⊕B)=>(x.1,sumRep x.2)) + (fun x=>Sum.elim (fun a=>f (x.1,a)) (fun b=>g (x.1,b)) x.2) + (fun _=>rfl) (by intro x; cases x.2 <;> rfl) +lemma polynomial_sumCases [Inhabited A] [Inhabited B] {f : C×A→D} {g : C×B→D} + {F : Realizer f} {G : Realizer g} (hF : PolynomialTime F) (hG : PolynomialTime G) : + PolynomialTime (sumCases F G) := by + unfold sumCases + apply polynomial_recode + dsimp only [Realizer.fst,Realizer.snd] + tree_cost + +def sumEqual [Inhabited A] [Inhabited B] [DecidableEq A] [DecidableEq B] + (E : Realizer (fun x : A×A=>decide (x.1=x.2))) + (F : Realizer (fun x : B×B=>decide (x.1=x.2))) : + Realizer (fun x : (A⊕B)×(A⊕B)=>decide (x.1=x.2)) := + (sumCases (composition (pair second first) (sumCases E (constant false))) + (composition (pair second first) (sumCases (constant false) F))).congr (by + intro x; rcases x with ⟨x,y⟩; cases x <;> cases y <;> simp [eq_comm]) +omit [Codec C] [Codec D] in +lemma polynomial_sumEqual [Inhabited A] [Inhabited B] [DecidableEq A] [DecidableEq B] + {E : Realizer (fun x : A×A=>decide (x.1=x.2))} + {F : Realizer (fun x : B×B=>decide (x.1=x.2))} + (hE : PolynomialTime E) (hF : PolynomialTime F) : PolynomialTime (sumEqual E F) := by + unfold sumEqual + apply polynomial_congr + apply polynomial_sumCases + · exact polynomial_composition (polynomial_pair polynomial_second polynomial_first) + (polynomial_sumCases hE (polynomial_constant false)) + · exact polynomial_composition (polynomial_pair polynomial_second polynomial_first) + (polynomial_sumCases (polynomial_constant false) hF) + +def sumLexLe [Inhabited A] [Inhabited B] [LinearOrder A] [LinearOrder B] + (R : Realizer (fun x : A×A=>decide (x.1≤x.2))) + (S : Realizer (fun x : B×B=>decide (x.1≤x.2))) : + Realizer (fun x : (A⊕B)×(A⊕B)=>decide (toLex x.1≤toLex x.2)) := + (sumCases (composition (pair second first) (sumCases (composition (pair second first) R) (constant false))) + (composition (pair second first) (sumCases (constant true) (composition (pair second first) S)))).congr (by + intro x; rcases x with ⟨x,y⟩; cases x <;> cases y <;> simp) +omit [Codec C] [Codec D] in +lemma polynomial_sumLexLe [Inhabited A] [Inhabited B] [LinearOrder A] [LinearOrder B] + {R : Realizer (fun x : A×A=>decide (x.1≤x.2))} + {S : Realizer (fun x : B×B=>decide (x.1≤x.2))} + (hR : PolynomialTime R) (hS : PolynomialTime S) : PolynomialTime (sumLexLe R S) := by + unfold sumLexLe + apply polynomial_congr + apply polynomial_sumCases + · exact polynomial_composition (polynomial_pair polynomial_second polynomial_first) + (polynomial_sumCases (polynomial_composition (polynomial_pair polynomial_second polynomial_first) hR) + (polynomial_constant false)) + · exact polynomial_composition (polynomial_pair polynomial_second polynomial_first) + (polynomial_sumCases (polynomial_constant true) + (polynomial_composition (polynomial_pair polynomial_second polynomial_first) hS)) + +def optionRep [Inhabited A] : Option A→Bool×A + | none => (false,default) + | some a => (true,a) +instance [Inhabited A] : Codec (Option A) := ⟨fun x=>encode (optionRep x)⟩ +def some [Inhabited A] : Realizer (Option.some : A→Option A) := + (pair (constant true) identity).recode id Option.some (fun _=>rfl) (fun _=>rfl) +omit [Codec B] [Codec C] [Codec D] in +lemma polynomial_some [Inhabited A] : PolynomialTime (some (A:=A)) := by + unfold some + apply polynomial_recode + tree_cost + +def optionCases [Inhabited A] {f : C→D} {g : C×A→D} (F : Realizer f) (G : Realizer g) : + Realizer (fun x : C×Option A=>x.2.elim (f x.1) (fun a=>g (x.1,a))) := + (choose second.fst (composition (pair first second.snd) G) (composition first F)).recode + (fun x : C×Option A=>(x.1,optionRep x.2)) + (fun x=>x.2.elim (f x.1) (fun a=>g (x.1,a))) (fun _=>rfl) (by intro x; cases x.2 <;> rfl) +omit [Codec B] in +lemma polynomial_optionCases [Inhabited A] {f : C→D} {g : C×A→D} + {F : Realizer f} {G : Realizer g} (hF : PolynomialTime F) (hG : PolynomialTime G) : + PolynomialTime (optionCases F G) := by + unfold optionCases + apply polynomial_recode + dsimp only [Realizer.fst,Realizer.snd] + tree_cost +end MatchingFPRAS.TreeTyped + +end OAI diff --git a/lean/OAI/Combinatorics/MatchingCount/Machines/TreeTransfer.lean b/lean/OAI/Combinatorics/MatchingCount/Machines/TreeTransfer.lean new file mode 100644 index 0000000000000000000000000000000000000000..b7f10859d4a0229dffa20da0322a64468e102680 --- /dev/null +++ b/lean/OAI/Combinatorics/MatchingCount/Machines/TreeTransfer.lean @@ -0,0 +1,86 @@ +import Mathlib +import OAI.Combinatorics.MatchingCount.Complexity.StackCompilerCost + +namespace OAI + +namespace MatchingFPRAS.TreeData +inductive Data where + | nil + | cons (head tail : Data) + deriving DecidableEq, Inhabited +open Data + +def encode : Data → List Bool + | .nil => [false] + | .cons a b => true::(encode a++encode b) +lemma encode_nonempty (v : Data) : encode v≠[] := by cases v <;> simp [encode] +lemma encode_length_pos (v : Data) : 0<(encode v).length := List.length_pos_iff.mpr (encode_nonempty v) +def size : Data → ℕ + | .nil => 1 + | .cons a b => 1+size a+size b +lemma encode_length (v : Data) : (encode v).length=size v := by + induction v with + | nil => rfl + | cons head tail head_ih tail_ih => + simp only [encode, List.length_cons, List.length_append, head_ih, tail_ih, size] + omega +end MatchingFPRAS.TreeData + +namespace MatchingFPRAS.TreeTransfer +open Turing MachineCost TreeData + +abbrev Store := Option Bool +abbrev Stacks := Fin 3 → List Bool +def program : Unit → TM2.Stmt (fun _ : Fin 3=>Bool) Unit Store := fun _=> + .peek 2 (fun _ b=>b) (.branch Option.isNone (.load (fun _=>none) .halt) + (.pop 2 (fun v _=>v) (.pop 0 (fun _ b=>b) + (.push 1 (fun v=>v.getD false) (.branch (fun v=>v.getD false) + (.push 2 (fun _=>false) (.push 2 (fun _=>false) (.goto (fun _=>())))) + (.goto (fun _=>()))))))) +def stackData (A B D : List Bool) : Stacks := ![A,B,D] +def cfg (l : Option Unit) (A B D : List Bool) (v : Store) : + TM2.Cfg (fun _ : Fin 3=>Bool) Unit Store := ⟨l,v,stackData A B D⟩ +@[simp] lemma stacks_zero (A B D : List Bool) : stackData A B D 0=A := rfl +@[simp] lemma stacks_one (A B D : List Bool) : stackData A B D 1=B := rfl +@[simp] lemma stacks_two (A B D : List Bool) : stackData A B D 2=D := rfl +lemma update_zero (A B D X : List Bool) : Function.update (stackData A B D) 0 X=stackData X B D := by + funext i; fin_cases i <;> simp [stackData] +lemma update_one (A B D X : List Bool) : Function.update (stackData A B D) 1 X=stackData A X D := by + funext i; fin_cases i <;> simp [stackData] +lemma update_two (A B D X : List Bool) : Function.update (stackData A B D) 2 X=stackData A B X := by + funext i; fin_cases i <;> simp [stackData] +lemma step_nil (A B D : List Bool) (v : Store) : + advance (TM2.step program) (cfg (some ()) (false::A) B (false::D) v)= + cfg (some ()) A (false::B) D (some false) := by + simp [advance,TM2.step,program,TM2.stepAux,cfg,update_zero,update_one,update_two] +lemma step_cons (A B D : List Bool) (v : Store) : + advance (TM2.step program) (cfg (some ()) (true::A) B (false::D) v)= + cfg (some ()) A (true::B) (false::false::D) (some true) := by + simp [advance,TM2.step,program,TM2.stepAux,cfg,update_zero,update_one,update_two] +lemma step_stop (A B : List Bool) (v : Store) : + advance (TM2.step program) (cfg (some ()) A B [] v)=cfg none A B [] none := by + simp [advance,TM2.step,program,TM2.stepAux,cfg] + +theorem run_tree (x : Data) (A B D : List Bool) (v : Store) : + MachineCost.run (TM2.step program) (encode x).length + (cfg (some ()) (encode x++A) B (false::D) v)= + cfg (some ()) A ((encode x).reverse++B) D (some false) := by + induction x generalizing A B D v with + | nil => simpa [encode,MachineCost.run] using step_nil A B D v + | cons x y ihx ihy => + simp only [encode,List.length_cons,List.length_append,List.cons_append] + rw [MachineCost.run,step_cons] + rw [show (encode x++encode y)++A=encode x++(encode y++A) by simp only [List.append_assoc]] + rw [run_add,ihx,ihy] + simp only [List.reverse_cons,List.reverse_append,List.append_assoc,List.singleton_append] + +theorem run_transfer (x : Data) (A B : List Bool) (v : Store) : + MachineCost.run (TM2.step program) ((encode x).length+1) + (cfg (some ()) (encode x++A) B [false] v)= + cfg none A ((encode x).reverse++B) [] none := by + rw [run_add,run_tree] + exact step_stop A ((encode x).reverse++B) (some false) +lemma accesses_bound (l : Unit) : StackCost.accesses (program l)≤6 := by cases l; decide +end MatchingFPRAS.TreeTransfer + +end OAI diff --git a/lean/OAI/Combinatorics/MatchingCount/Machines/TreeTyped.lean b/lean/OAI/Combinatorics/MatchingCount/Machines/TreeTyped.lean new file mode 100644 index 0000000000000000000000000000000000000000..d3b1217938ef6d00e9f58387c4fe9569159d2e59 --- /dev/null +++ b/lean/OAI/Combinatorics/MatchingCount/Machines/TreeTyped.lean @@ -0,0 +1,93 @@ +import Mathlib +import OAI.Combinatorics.MatchingCount.Arithmetic.TreeNumberOps +import OAI.Combinatorics.MatchingCount.Machines.TreeFunction + +namespace OAI + +namespace MatchingFPRAS.TreeTyped +open TreeData TreeMachine RegisterProc TreeFunction + +class Codec (A : Type) where + encode : A → Data +export Codec (encode) +instance : Codec Data := ⟨id⟩ +instance : Codec ℕ := ⟨nat⟩ +instance : Codec Bool := ⟨bit⟩ +instance {A B : Type} [Codec A] [Codec B] : Codec (A×B) := ⟨fun x=>.cons (encode x.1) (encode x.2)⟩ +instance {A : Type} [Codec A] : Codec (List A) := ⟨fun x=>ofList (x.map encode)⟩ +@[simp] lemma encode_prod {A B : Type} [Codec A] [Codec B] (a : A) (b : B) : + encode (a,b)=.cons (encode a) (encode b) := rfl +@[simp] lemma encode_list_nil {A : Type} [Codec A] : encode ([] : List A)=.nil := rfl +@[simp] lemma encode_list_cons {A : Type} [Codec A] (a : A) (as : List A) : + encode (a::as)=.cons (encode a) (encode as) := rfl + +def Realizes {A B : Type} [Codec A] [Codec B] (P : Proc (K Reg)) (f : A → B) (t : A → ℕ) : Prop := + ∀ a s,Exec P (encodeEnv (env (encode a) .nil s)) (encodeEnv (env (encode (f a)) .nil s)) (t a) +structure Realizer {A B : Type} [Codec A] [Codec B] (f : A → B) where + program : Proc (K Reg) + cost : A → ℕ + correct : Realizes program f cost + +variable {A B C : Type} [Codec A] [Codec B] [Codec C] + +def composition {f : A → B} {g : B → C} (F : Realizer f) (G : Realizer g) : Realizer (g ∘ f) := + ⟨seq F.program G.program,fun a=>F.cost a+G.cost (f a),fun a s=>(F.correct a s).seq (G.correct (f a) s)⟩ + +def pair {f : A → B} {g : A → C} (F : Realizer f) (G : Realizer g) : Realizer (fun a=>(f a,g a)) where + program := TreeFunction.pair F.program G.program + cost := fun a=>F.cost a+G.cost a+11*TreeFunction.size (encode a)+6*TreeFunction.size (encode (f a))+31 + correct := by + intro a s + have h1:=copy01 (encode a) .nil s + have h2:=cons12 (encode a) (encode a) s + have h3:=F.correct a (.cons (encode a) s) + have h4:=split12 (encode (f a)) .nil (encode a) s + have h5:=cons02 (encode (f a)) (encode a) s + have h6:=copy10 .nil (encode a) (.cons (encode (f a)) s) + have h7:=clear1 (encode a) (encode a) (.cons (encode (f a)) s) + have h8:=G.correct a (.cons (encode (f a)) s) + have h9:=split12 (encode (g a)) .nil (encode (f a)) s + have h10:=cons10 (encode (g a)) (encode (f a)) s + apply (h1.seq (h2.seq (h3.seq (h4.seq (h5.seq (h6.seq (h7.seq (h8.seq (h9.seq h10))))))))).mono + simp only [size_nil] + omega + +def identity : Realizer (id : A → A) := + ⟨atom .halt,fun _=>1,fun _ _=>exec_atom .halt _ _ rfl⟩ + +def first : Realizer (Prod.fst : A×B → A) where + program := seq (TreeFunction.split 1 0 (by decide)) + (seq (TreeFunction.copy 1 0 (by decide)) (TreeFunction.clear 1)) + cost := fun ab=>6*TreeFunction.size (encode ab.1)+TreeFunction.size (encode ab.2)+11 + correct := by + intro ⟨a,b⟩ s + have h1:=split10 (encode a) (encode b) .nil s + have h2:=copy10 (encode b) (encode a) s + have h3:=clear1 (encode a) (encode a) s + apply (h1.seq (h2.seq h3)).mono + simp only [size_nil]; omega + +def second : Realizer (Prod.snd : A×B → B) where + program := seq (TreeFunction.split 1 0 (by decide)) (TreeFunction.clear 1) + cost := fun ab=>3*TreeFunction.size (encode ab.1)+7 + correct := by + intro ⟨a,b⟩ s + have h1:=split10 (encode a) (encode b) .nil s + have h2:=clear1 (encode b) (encode a) s + apply (h1.seq h2).mono + simp only [size_nil]; omega + +def add : Realizer (fun ab : ℕ×ℕ=>ab.1+ab.2) where + program := seq (TreeFunction.split 1 0 (by decide)) (TreeArithmetic.add 0 1 (by decide)) + cost := fun ab=>2*TreeFunction.size (nat ab.1)+5+9*(ab.1.bits.length+ab.2.bits.length)+20 + correct := by + intro ⟨a,b⟩ s + have h1:=split10 (nat a) (nat b) .nil s + have h2:=TreeArithmetic.add_exec (env (nat b) (nat a) s) 0 1 (by decide) b a rfl rfl + rw [putPair,env_update0,env_update1,Nat.add_comm b a] at h2 + apply (h1.seq h2).mono + simp only [size_nil] + omega +end MatchingFPRAS.TreeTyped + +end OAI diff --git a/lean/OAI/Combinatorics/MatchingCount/Machines/TreeWeightTable.lean b/lean/OAI/Combinatorics/MatchingCount/Machines/TreeWeightTable.lean new file mode 100644 index 0000000000000000000000000000000000000000..7e9ca502bbd832bfb8e8e3acb06e15653d98c8ea --- /dev/null +++ b/lean/OAI/Combinatorics/MatchingCount/Machines/TreeWeightTable.lean @@ -0,0 +1,51 @@ +import Mathlib +import OAI.Combinatorics.MatchingCount.Machines.TreePhantom + +namespace OAI + +namespace MatchingFPRAS.ExecutableSource +open TreeTyped TreeFraction TreeTyped.Numbered ExecutableBottleneck ExecutableHierarchy ExecutableRefresh Enlargement RealGeometry + +attribute [local instance] NumberedHierarchy.labelOrder +attribute [local instance] Transport.sym2Order Transport.bagEdgeOrder Transport.bagEdgeFintype + +def sourceWeights (x : BagBuildInput×ℕ) : List Fraction := + (sourceTables x.1).1.map (fun key=>sourceBagWeight (x,key)) +def rowsWith {A B C : Type} [Codec A] [Codec B] [Codec C] + {f : A×B→C} {g : A→List B} (F : Realizer f) (G : Realizer g) : + Realizer (fun x=>(g x).map (fun b=>f (x,b))) := + composition (pair identity G) (mapWith F) +lemma polynomial_rowsWith {A B C : Type} [Codec A] [Codec B] [Codec C] + {f : A×B→C} {g : A→List B} {F : Realizer f} {G : Realizer g} + (hF : PolynomialTime F) (hG : PolynomialTime G) : PolynomialTime (rowsWith F G) := + polynomial_composition (polynomial_pair polynomial_identity hG) (polynomial_mapWith hF) +def sourceWeightsRealizer : Realizer sourceWeights := rowsWith sourceBagWeightRealizer + (composition (first (A:=BagBuildInput) (B:=ℕ)) sourceTablesRealizer).fst +lemma polynomial_sourceWeights : PolynomialTime sourceWeightsRealizer := + polynomial_rowsWith polynomial_sourceBagWeight + (polynomial_fst (polynomial_composition polynomial_first polynomial_sourceTables)) +lemma sourceWeights_source {n : ℕ} [Nontrivial (Fin n)] (hn : 2≤n) + (w : Fin n→Fin n→ℚ) (hw : ∀ a b,0≤w a b) (K D : ℕ) : + sourceWeights ((((matrixRep w,List.replicate (2*K+2) false),List.range n),List.replicate (2*K) false),D)= + List.ofFn (fun i=>TreeFraction.repr (RationalSource.bagWeight w K D + (UnitRefresh.orderedEnum (Transport.BagEdge (RationalSource.bags w K)) i))) := by + unfold sourceWeights + dsimp only + rw [sourceTables_catalog hn w hw K] + unfold sourceCatalog + rw [List.map_ofFn] + congr 1 + funext i + exact sourceBagWeight_source hn w hw K D _ + +open TreePost Turing + +theorem sourceWeights_post : ∃ p : Polynomial ℕ,∀ x : BagBuildInput×ℕ,∀ t : ℕ, + p.eval (packed x).length≤t → ∀ coins : Fin t→Bool, + (run (machine sourceWeightsRealizer.program) (packed x) coins).state=none ∧ + (run (machine sourceWeightsRealizer.program) (packed x) coins).tape.right₀= + ListBlank.mk (packed (sourceWeights x)) := + polynomial_compiles sourceWeightsRealizer polynomial_sourceWeights +end MatchingFPRAS.ExecutableSource + +end OAI diff --git a/lean/OAI/Combinatorics/MatchingCount/Machines/Wrapper.lean b/lean/OAI/Combinatorics/MatchingCount/Machines/Wrapper.lean new file mode 100644 index 0000000000000000000000000000000000000000..85a7f0091a6004b82b18d513a3710a56bd4286d9 --- /dev/null +++ b/lean/OAI/Combinatorics/MatchingCount/Machines/Wrapper.lean @@ -0,0 +1,100 @@ +import Mathlib +import OAI.Combinatorics.MatchingCount.Tapes.PackedExecution +import OAI.Combinatorics.MatchingCount.Machines.OnlinePhysicalProgram +import OAI.Combinatorics.MatchingCount.Machines.PhysicalProgramMap +import OAI.Combinatorics.MatchingCount.Algorithm.Algorithm +import OAI.Combinatorics.MatchingCount.Complexity.OnlineCost + +namespace OAI + +namespace MatchingFPRAS.LiteralPhysical +open Turing PhysicalPost PhysicalStream LiteralPacked TreeTyped + +noncomputable def pack : Program := Program.ofTM1 packCode .start (fun _=>0) +noncomputable def erase : Program := Program.ofTM1 (LiteralTape.eraseCode header.length) () () +noncomputable def unpack : Program := Program.ofTM1 unpackCode .start (fun _=>0) +noncomputable def post : Program := erase.seq unpack +noncomputable def packTime (n : ℕ) : ℕ := + (1+LiteralBlockMap.budget 1 (18*width) n 0)*MachineCost.programCost packCode +noncomputable def eraseTime : ℕ := MachineCost.programCost (LiteralTape.eraseCode header.length) +noncomputable def unpackTime (n : ℕ) : ℕ := + (1+LiteralBlockMap.budget (18*width) 1 n 0)*MachineCost.programCost unpackCode +noncomputable def postTime (n : ℕ) : ℕ := eraseTime+unpackTime n +lemma packTime_mono {n m : ℕ} (h : n ≤ m) : packTime n ≤ packTime m := by + unfold packTime LiteralBlockMap.budget;gcongr +lemma postTime_mono {n m : ℕ} (h : n ≤ m) : postTime n ≤ postTime m := by + unfold postTime unpackTime LiteralBlockMap.budget;gcongr +lemma pack_realizes (as : List Symbol) (ha : ∀ a∈as,a≠0) : + pack.Realizes (Tape.mk₁ as) (.done (Tape.mk₁ (TreePost.packed as))) (packTime as.length) := + Program.realizes_TM1 _ _ _ _ _ _ _ (pack_exec as ha) +lemma post_realizes (as : List Symbol) (ha : ∀ a∈as,a≠6 ∧ a≠7) : + post.Realizes (Tape.mk₁ (TreePost.packed as)) (.done (Tape.mk₁ as)) (postTime as.length) := by + have h1 : erase.Realizes (Tape.mk₁ (TreePost.packed as)) + (.done (Tape.mk₁ (as.reverse.flatMap chunk))) eraseTime := by + rw [packed_eq] + exact (Program.realizes_TM1 _ _ _ _ _ _ _ (LiteralTape.erase_exec header (as.reverse.flatMap chunk))).mono + (by simp only [Nat.one_mul];rfl) + have h2 : unpack.Realizes (Tape.mk₁ (as.reverse.flatMap chunk)) (.done (Tape.mk₁ as)) (unpackTime as.length) := + Program.realizes_TM1 _ _ _ _ _ _ _ (unpack_exec as ha) + exact Program.seq_realizes erase unpack _ (.done (Tape.mk₁ (as.reverse.flatMap chunk))) + (fun _=>.done (Tape.mk₁ as)) _ _ h1 h2 + +noncomputable def wrap {f : List Symbol→Experiment (List Symbol)} (F : OnlineTree.Realizer f) : Program := + (pack.seq (OnlineTree.physicalProgram F)).seq post +noncomputable def wrapTime {f : List Symbol→Experiment (List Symbol)} (F : OnlineTree.Realizer f) + (as : List Symbol) : ℕ := packTime as.length+OnlineTree.physicalCost F as+postTime ((f as).worst List.length) +lemma wrap_realizes {f : List Symbol→Experiment (List Symbol)} (F : OnlineTree.Realizer f) + (as : List Symbol) (ha : ∀ a∈as,a≠0) (hout : (f as).All (fun bs=>∀ b∈bs,b≠6 ∧ b≠7)) : + (wrap F).Realizes (Tape.mk₁ as) ((f as).map Tape.mk₁) (wrapTime F as) := by + have h1 : (pack.seq (OnlineTree.physicalProgram F)).Realizes (Tape.mk₁ as) + ((f as).map (fun bs=>Tape.mk₁ (TreePost.packed bs))) (packTime as.length+OnlineTree.physicalCost F as) := + Program.seq_realizes pack (OnlineTree.physicalProgram F) _ (.done (Tape.mk₁ (TreePost.packed as))) + (fun _=>(f as).map (fun bs=>Tape.mk₁ (TreePost.packed bs))) _ _ (pack_realizes as ha) (OnlineTree.physical_realizes F as) + exact Program.seq_realizes_map _ _ _ (f as) (fun bs=>Tape.mk₁ (TreePost.packed bs)) (fun bs=>.done (Tape.mk₁ bs)) + _ _ h1 ((hout.and (Experiment.all_worst (f as) List.length)).mono + (fun bs hbs=>(post_realizes bs hbs.1).mono (postTime_mono hbs.2))) + +lemma encodeNat_nonzero (n : ℕ) (a : Symbol) (ha : a∈encodeNat n) : a≠0 := by + simp only [encodeNat,List.mem_append,List.mem_map,List.mem_singleton] at ha + rcases ha with ⟨b,_,rfl⟩|rfl + · cases b <;> decide + · decide +lemma encodeRat_nonzero (q : ℚ) (a : Symbol) (ha : a∈encodeRat q) : a≠0 := by + simp only [encodeRat,encodeInt,List.mem_append] at ha + rcases ha with (ha|ha)|ha + · split_ifs at ha with hn <;> simp only [List.mem_singleton] at ha <;> subst a <;> decide + · exact encodeNat_nonzero _ _ ha + · exact encodeNat_nonzero _ _ ha +lemma input_nonzero (G : GraphInput) (ε δ : ℚ) (a : Symbol) (ha : a∈encodeInput G ε δ) : a≠0 := by + simp only [encodeInput,List.mem_append] at ha + rcases ha with (((ha|ha)|ha)|ha)|ha + · exact encodeNat_nonzero _ _ ha + · exact encodeNat_nonzero _ _ ha + · obtain ⟨e,_,he⟩:=List.mem_flatMap.mp ha + rcases List.mem_append.mp he with he|he <;> exact encodeNat_nonzero _ _ he + · exact encodeRat_nonzero _ _ ha + · exact encodeRat_nonzero _ _ ha +lemma natWord_alphabet (n : ℕ) (a : Symbol) (ha : a∈LiteralCodec.natWord n) : a≠6 ∧ a≠7 := by + simp only [LiteralCodec.natWord,LiteralCodec.fromBit,List.mem_append,List.mem_map,List.mem_singleton] at ha + rcases ha with ⟨b,_,rfl⟩|rfl + · cases b <;> decide + · decide +lemma ratWord_alphabet (q : TreeFraction.Fraction) (a : Symbol) (ha : a∈LiteralCodec.ratWord q) : a≠6 ∧ a≠7 := by + simp only [LiteralCodec.ratWord,List.mem_cons,List.mem_append] at ha + rcases ha with (rfl|ha)|ha + · decide + · exact natWord_alphabet _ _ ha + · exact natWord_alphabet _ _ ha +lemma algorithm_alphabet (as : List Symbol) : + (LiteralAlgorithm.algorithm as).All (fun bs=>∀ b∈bs,b≠6 ∧ b≠7) := by + rw [LiteralAlgorithm.algorithm,Experiment.all_map] + exact (Experiment.all_true _).mono (fun q _=>ratWord_alphabet q) +noncomputable def mainProgram : Program := wrap LiteralAlgorithm.algorithmRealizer +lemma mainProgram_realizes (G : GraphInput) (ε δ : ℚ) : + mainProgram.Realizes (Tape.mk₁ (encodeInput G ε δ)) + ((LiteralAlgorithm.algorithm (encodeInput G ε δ)).map Tape.mk₁) + (wrapTime LiteralAlgorithm.algorithmRealizer (encodeInput G ε δ)) := + wrap_realizes _ _ (input_nonzero G ε δ) (algorithm_alphabet _) +end MatchingFPRAS.LiteralPhysical + +end OAI diff --git a/lean/OAI/Combinatorics/MatchingCount/Main.lean b/lean/OAI/Combinatorics/MatchingCount/Main.lean new file mode 100644 index 0000000000000000000000000000000000000000..5442b1d1edf7c4ffd8df9d3c624ae562088e528c --- /dev/null +++ b/lean/OAI/Combinatorics/MatchingCount/Main.lean @@ -0,0 +1,33 @@ +import Mathlib +import OAI.Combinatorics.MatchingCount.Sampling.Sewn +import OAI.Combinatorics.MatchingCount.Sampling.FiniteSampler +import OAI.Combinatorics.MatchingCount.Sampling.FiniteSampler2 +import OAI.Combinatorics.MatchingCount.Sampling.FiniteSampler3 +import OAI.Combinatorics.MatchingCount.Sampling.FiniteSampler4 +import OAI.Combinatorics.MatchingCount.Algorithm.GuardBudget +import OAI.Combinatorics.MatchingCount.Machines.ProgramComposition +import OAI.Combinatorics.MatchingCount.Graphs.Output +import OAI.Combinatorics.MatchingCount.Arithmetic.TreeDivision +import OAI.Combinatorics.MatchingCount.Machines.TreeLanguage +import OAI.Combinatorics.MatchingCount.Sampling.TreeUnitCorrect +import OAI.Combinatorics.MatchingCount.Tapes.RandomReservoir +import OAI.Combinatorics.MatchingCount.Complexity.PhysicalCost +import OAI.Combinatorics.MatchingCount.Probability.MainLaw + +namespace OAI + +namespace MatchingFPRAS + +theorem thm_main : MainStatement := by + obtain ⟨C,d,hC,hbound⟩:=LiteralPhysical.mainTime_bound + refine ⟨LiteralPhysical.mainProgram.machine,C,d,hC,?_⟩ + intro G ε δ he he1 hd _hd1 + dsimp only + have hn:=hbound G ε δ he he1 hd.le + obtain ⟨hp,hz⟩:=LiteralPhysical.mainProgram_outputs G ε δ he he1 hd.le + (timeBound C d G ε δ) hn + exact ⟨hp,hz,LiteralPhysical.mainProgram_success G ε δ he he1 hd + (timeBound C d G ε δ) hn⟩ +end MatchingFPRAS + +end OAI diff --git a/lean/OAI/Combinatorics/MatchingCount/Model.lean b/lean/OAI/Combinatorics/MatchingCount/Model.lean new file mode 100644 index 0000000000000000000000000000000000000000..46406416670b42042769497340b1b2673cacc35a --- /dev/null +++ b/lean/OAI/Combinatorics/MatchingCount/Model.lean @@ -0,0 +1,104 @@ +import Mathlib + +namespace OAI + +namespace MatchingFPRAS + +/-- Each unordered edge is represented once, by increasing endpoints. -/ +structure GraphInput where + n : ℕ + edges : Finset (Fin n × Fin n) + increasing : ∀ e ∈ edges, e.1 < e.2 + +/-- Exactly one selected edge is incident to every vertex. -/ +def Perfect (G : GraphInput) (M : Finset (Fin G.n × Fin G.n)) : Prop := + M ⊆ G.edges ∧ ∀ v : Fin G.n, ∃! e, e ∈ M ∧ (e.1 = v ∨ e.2 = v) + +noncomputable def perfectMatchings (G : GraphInput) : Finset (Finset (Fin G.n × Fin G.n)) := + by + classical + exact G.edges.powerset.filter (Perfect G) + +/-- The exact unweighted count, including the empty graph. -/ +noncomputable def Z (G : GraphInput) : ℕ := (perfectMatchings G).card + +abbrev Symbol := Fin 8 + +/-- Binary numeral followed by a delimiter. Tape blank is 0; bits use 1 and 2. -/ +def encodeNat (n : ℕ) : List Symbol := + (Nat.bits n).map (fun b => if b then 2 else 1) ++ [3] + +def encodeInt (z : ℤ) : List Symbol := + (if z < 0 then [5] else [4]) ++ encodeNat z.natAbs + +/-- A rational encoded by its reduced numerator and positive denominator. -/ +def encodeRat (q : ℚ) : List Symbol := encodeInt q.num ++ encodeNat q.den + +/-- Explicit sparse graph encoding, then the two rational parameters. -/ +def encodeInput (G : GraphInput) (ε δ : ℚ) : List Symbol := + encodeNat G.n ++ encodeNat G.edges.card ++ + (((G.edges.map toLex.toEmbedding).sort (· ≤ ·)).flatMap fun e => + encodeNat (ofLex e).1.val ++ encodeNat (ofLex e).2.val) ++ + encodeRat ε ++ encodeRat δ + +/-- A uniform randomized Post-Turing machine: a single finite transition table. -/ +structure RandomMachine where + states : ℕ + transition : Fin (states + 1) → Symbol → Bool → + Option (Fin (states + 1) × Turing.TM0.Stmt Symbol) + +structure Configuration (A : RandomMachine) where + state : Option (Fin (A.states + 1)) + tape : Turing.Tape Symbol + +/-- A halted configuration is absorbing. Each nonhalting tick is exactly one +write or one move, or the detection of halt. -/ +def tick (A : RandomMachine) (c : Configuration A) (bit : Bool) : Configuration A := + match c.state with + | none => c + | some s => match A.transition s c.tape.head bit with + | none => ⟨none, c.tape⟩ + | some (s', action) => + ⟨some s', match action with + | .move d => c.tape.move d + | .write a => c.tape.write a⟩ + +def initial (A : RandomMachine) (input : List Symbol) : Configuration A := + ⟨some 0, Turing.Tape.mk₁ input⟩ + +/-- Bounded execution on a finite prefix of the random tape. -/ +def run (A : RandomMachine) (input : List Symbol) {t : ℕ} + (bits : Fin t → Bool) : Configuration A := + (List.ofFn bits).foldl (tick A) (initial A input) + +def Outputs (A : RandomMachine) (input : List Symbol) {t : ℕ} + (bits : Fin t → Bool) (q : ℚ) : Prop := + (run A input bits).state = none ∧ + (run A input bits).tape.right₀ = Turing.ListBlank.mk (encodeRat q) + +/-- A fixed-degree polynomial in input bits, ε⁻¹, and log δ⁻¹. +Natural ceilings and binary ceiling-log change this bound only by constants. -/ +def timeBound (C d : ℕ) (G : GraphInput) (ε δ : ℚ) : ℕ := + C * ((encodeInput G ε δ).length + ⌈ε⁻¹⌉₊ + Nat.clog 2 ⌈δ⁻¹⌉₊ + 1) ^ d + +noncomputable def goodTapes (A : RandomMachine) (G : GraphInput) (ε δ : ℚ) + (t : ℕ) : Finset (Fin t → Bool) := by + classical + exact Finset.univ.filter fun bits => ∃ q : ℚ, + Outputs A (encodeInput G ε δ) bits q ∧ + (1 - ε) * (Z G : ℚ) ≤ q ∧ q ≤ (1 + ε) * (Z G : ℚ) + +/-- A uniform approximation scheme using independent fair bits. All tapes halt +within the fixed polynomial bound and return a nonnegative rational. +A zero count always produces encoded zero. -/ +def MainStatement : Prop := + ∃ (A : RandomMachine) (C d : ℕ), 0 < C ∧ + ∀ (G : GraphInput) (ε δ : ℚ), 0 < ε → ε < 1 → 0 < δ → δ < 1 / 2 → + let t := timeBound C d G ε δ + (∀ bits : Fin t → Bool, ∃ q : ℚ, 0 ≤ q ∧ Outputs A (encodeInput G ε δ) bits q) ∧ + (Z G = 0 → ∀ bits : Fin t → Bool, Outputs A (encodeInput G ε δ) bits 0) ∧ + ((goodTapes A G ε δ t).card : ℚ) / (2 : ℚ) ^ t ≥ 1 - δ + +end MatchingFPRAS + +end OAI diff --git a/lean/OAI/Combinatorics/MatchingCount/Probability/AdaptiveLaw.lean b/lean/OAI/Combinatorics/MatchingCount/Probability/AdaptiveLaw.lean new file mode 100644 index 0000000000000000000000000000000000000000..945580fd70f72960bd5eeb12baa9208bc6f0c18c --- /dev/null +++ b/lean/OAI/Combinatorics/MatchingCount/Probability/AdaptiveLaw.lean @@ -0,0 +1,548 @@ +import Mathlib +import OAI.Combinatorics.MatchingCount.Sampling.Endpoints + +namespace OAI + +namespace MatchingFPRAS.Counting + +theorem trial_output_error (K : ℕ) (hK : 1 ≤ K) (epsilon : ℝ) + (he : 0 < epsilon) (he1 : epsilon < 1) (Z : ℕ → ℝ) + (hZ : ∀ j, 0 < Z j) (estimates : Fin K → ℝ) + (herr : ∀ j, |estimates j/(Z (j.val+1)/Z j.val)-1| ≤ epsilon/(100*K)) : + (1-epsilon/100)*Z K ≤ productEstimate (Z 0) estimates ∧ + productEstimate (Z 0) estimates ≤ (1+epsilon/50)*Z K := by + let f : Fin K → ℝ := fun j => estimates j/(Z (j.val+1)/Z j.val) + have hprod := stage_product_error K hK epsilon he he1 f herr + have hid : productEstimate (Z 0) estimates = (∏ j, f j)*Z K := by + rw [show (∏ j, f j)=(∏ j, estimates j)/(∏ j : Fin K, Z (j.val+1)/Z j.val) from + Finset.prod_div_distrib _ _] + rw [positive_telescope Z hZ K] + unfold productEstimate + field_simp [(hZ 0).ne', (hZ K).ne'] + rw [hid] + exact ⟨mul_le_mul_of_nonneg_right hprod.1 (hZ K).le, + mul_le_mul_of_nonneg_right hprod.2 (hZ K).le⟩ + +end MatchingFPRAS.Counting + +namespace MatchingFPRAS.UnitRefresh + +lemma pairingCount_le_half_power (n : ℕ) : pairingCount n ≤ n^(n/2) := by + induction n using Nat.twoStepInduction with + | zero => simp + | one => simp + | more n ih ih' => + rw [pairingCount_add_two,show (n+2)/2=n/2+1 by omega,pow_succ] + calc + (n+1)*pairingCount n ≤ (n+2)*((n+2)^(n/2)) := + Nat.mul_le_mul (by omega) (ih.trans (Nat.pow_le_pow_left (by omega) (n/2))) + _ = (n+2)^(n/2)*(n+2) := Nat.mul_comm _ _ + +end MatchingFPRAS.UnitRefresh + +namespace MatchingFPRAS.Trial + +open Finset Switching + +lemma initial_raw_partition (G : GraphInput) : partition (raw G 0) ∅=(Z (completeGraph G.n):ℝ) := by + rw [raw_zero,Initializer.uniform_partition,Finset.card_empty,Nat.sub_zero,one_pow,mul_one, + Fintype.card_fin,GraphBridge.complete_count] + +theorem final_padding (G : GraphInput) (ε : ℚ) (hε : 0<ε) (K : ℕ) + (hK : Counting.scheduleAdmissible G.n ε K) (hZ : 0partition (raw G j) ∅) (raw_partition_pos G heven) r hr + simp only [Counting.productEstimate,initial_raw_partition] at h + have hb := final_padding G ε hε K hK hZ + have hz : (0:ℝ)≤Z G := Nat.cast_nonneg _ + constructor + · have hmul := mul_le_mul_of_nonneg_left hb.1 (by linarith : (0:ℝ)≤1-(ε:ℝ)/100) + nlinarith [mul_nonneg he.le hz] + · have hmul := mul_le_mul_of_nonneg_left hb.2 (by positivity : (0:ℝ)≤1+(ε:ℝ)/50) + have hscalar : (1+(ε:ℝ)/50)*(1+(ε:ℝ)/32)≤1+(ε:ℝ) := by nlinarith + have hm := mul_le_mul_of_nonneg_right hscalar hz + nlinarith + +end MatchingFPRAS.Trial + +namespace MatchingFPRAS.Adaptive + +open Finset + +variable {Ω : Type*} [Fintype Ω] + +structure Law (Ω : Type*) [Fintype Ω] where + mass : Ω → ℝ + nonneg : ∀ x,0 ≤ mass x + total : ∑ x,mass x=1 + +instance : CoeFun (Law Ω) (fun _ => Ω → ℝ) := ⟨Law.mass⟩ + +noncomputable def Law.event (μ : Law Ω) (P : Ω → Prop) : ℝ := by + classical + exact ∑ x,if P x then μ x else 0 + +lemma Law.event_nonneg (μ : Law Ω) (P : Ω → Prop) : 0 ≤ μ.event P := by + classical + apply sum_nonneg + intro x _ + split_ifs + · exact μ.nonneg x + · rfl + +lemma Law.event_le_one (μ : Law Ω) (P : Ω → Prop) : μ.event P ≤ 1 := by + classical + rw [← μ.total] + apply sum_le_sum + intro x _ + split_ifs + · rfl + · exact μ.nonneg x + +noncomputable def Law.step (μ : Law Ω) (k : Ω → Law Ω) : Law Ω where + mass y := ∑ x,μ x*k x y + nonneg y := sum_nonneg fun x _ => mul_nonneg (μ.nonneg x) ((k x).nonneg y) + total := by + rw [sum_comm] + simp only [← mul_sum,Law.total,mul_one] + +lemma Law.step_event (μ : Law Ω) (k : Ω → Law Ω) (P : Ω → Prop) : + (μ.step k).event P=∑ x,μ x*(k x).event P := by + classical + unfold Law.event + change (∑ y,if P y then ∑ x,μ x*k x y else 0)=_ + simp_rw [mul_sum] + rw [sum_comm] + apply sum_congr rfl + intro y _ + split_ifs <;> simp + +theorem first_failure_step (μ : Law Ω) (k : Ω → Law Ω) (P Q : Ω → Prop) + (η : ℝ) (hη : 0 ≤ η) (h : ∀ x,P x → (k x).event (fun y => ¬Q y) ≤ η) : + (μ.step k).event (fun y => ¬Q y) ≤ μ.event (fun x => ¬P x)+η := by + classical + rw [Law.step_event,← mul_one η,← μ.total,mul_sum] + unfold Law.event + rw [← sum_add_distrib] + apply sum_le_sum + intro x _ + by_cases hx : P x + · have hh := mul_le_mul_of_nonneg_left (h x hx) (μ.nonneg x) + simpa [Law.event,hx,mul_comm] using hh + · have hh := mul_le_mul_of_nonneg_left ((k x).event_le_one (fun y => ¬Q y)) (μ.nonneg x) + have hz := mul_nonneg hη (μ.nonneg x) + dsimp [Law.event] at hh + dsimp [Law.event] + simp only [hx,not_false_eq_true,ite_true] + nlinarith + +noncomputable def Law.evolve (μ : Law Ω) (k : ℕ → Ω → Law Ω) : ℕ → Law Ω + | 0 => μ + | n+1 => (μ.evolve k n).step (k n) + +theorem first_failure_bound (μ : Law Ω) (k : ℕ → Ω → Law Ω) (P : ℕ → Ω → Prop) + (η : ℝ) (hη : 0 ≤ η) (h0 : μ.event (fun x => ¬P 0 x)=0) + (h : ∀ n x,P n x → (k n x).event (fun y => ¬P (n+1) y) ≤ η) (n : ℕ) : + (μ.evolve k n).event (fun x => ¬P n x) ≤ n*η := by + induction n with + | zero => simp [Law.evolve,h0] + | succ n ih => + change ((μ.evolve k n).step (k n)).event _ ≤ _ + have hh := first_failure_step (μ.evolve k n) (k n) (P n) (P (n+1)) η hη (h n) + push_cast + linarith + +theorem source_trial_failure (μ : Law Ω) (k : ℕ → Ω → Law Ω) (P : ℕ → Ω → Prop) + (K : ℕ) (hK : 0 < K) (h0 : μ.event (fun x => ¬P 0 x)=0) + (h : ∀ n x,P n x → (k n x).event (fun y => ¬P (n+1) y) ≤ 13/(1000*K)) : + (μ.evolve k K).event (fun x => ¬P K x) ≤ 13/1000 := by + have hh := first_failure_bound μ k P (13/(1000*K)) (by positivity) h0 h K + convert hh using 1 + have hz : (K:ℝ)≠0 := Nat.cast_ne_zero.mpr (ne_of_gt hK) + field_simp + + + +open Finset +open scoped Classical + +variable {Ω : Type*} [Fintype Ω] {Ψ : Ω → Type*} [∀ x,Fintype (Ψ x)] + +noncomputable def Law.sigma (μ : Law Ω) (ν : ∀ x,Law (Ψ x)) : Law (Sigma Ψ) where + mass z := μ z.1*ν z.1 z.2 + nonneg z := mul_nonneg (μ.nonneg z.1) ((ν z.1).nonneg z.2) + total := by + rw [Fintype.sum_sigma] + change (∑ x,∑ y,μ x*(ν x) y)=1 + simp_rw [←mul_sum,Law.total,mul_one] + exact μ.total + +lemma Law.sigma_event (μ : Law Ω) (ν : ∀ x,Law (Ψ x)) (P : Sigma Ψ → Prop) : + (μ.sigma ν).event P=∑ x,μ x*(ν x).event (fun y=>P ⟨x,y⟩) := by + unfold Law.event + rw [Fintype.sum_sigma] + apply sum_congr rfl + intro x _ + rw [mul_sum] + apply sum_congr rfl + intro y _ + split_ifs <;> simp [Law.sigma] + +lemma Law.event_mono (μ : Law Ω) {P Q : Ω → Prop} (h : ∀ x,P x→Q x) : + μ.event P ≤ μ.event Q := by + unfold Law.event + apply sum_le_sum + intro x _ + split_ifs with hp hq hq + · rfl + · exact False.elim (hq (h x hp)) + · exact μ.nonneg x + · rfl + +lemma first_failure_sigma (μ : Law Ω) (ν : ∀ x,Law (Ψ x)) + (P : Ω → Prop) (Q : Sigma Ψ → Prop) (η : ℝ) (hη : 0≤η) + (h : ∀ x,P x→(ν x).event (fun y=>¬Q ⟨x,y⟩) ≤ η) : + (μ.sigma ν).event (fun z=>¬Q z) ≤ μ.event (fun x=>¬P x)+η := by + rw [Law.sigma_event,←mul_one η,←μ.total,mul_sum] + unfold Law.event + rw [←sum_add_distrib] + apply sum_le_sum + intro x _ + by_cases hx : P x + · have hh := mul_le_mul_of_nonneg_left (h x hx) (μ.nonneg x) + simpa [Law.event,hx,mul_comm] using hh + · have hh := mul_le_mul_of_nonneg_left ((ν x).event_le_one (fun y=>¬Q ⟨x,y⟩)) (μ.nonneg x) + have hz := mul_nonneg hη (μ.nonneg x) + dsimp [Law.event] at hh + dsimp [Law.event] + simp only [hx,not_false_eq_true,ite_true] + nlinarith + + + +open Finset +open MatchingFPRAS.Enlargement MatchingFPRAS.Transport MatchingFPRAS.Replica.Ladder +open scoped Classical + +variable {Ω : Type*} [Fintype Ω] + +noncomputable def Law.changeFintype {Ω : Type*} {i j : Fintype Ω} (μ : @Law Ω i) : @Law Ω j := by + have hij : i=j := Subsingleton.elim _ _ + cases hij + exact μ + +@[simp] theorem Law.changeFintype_mass {Ω : Type*} {i j : Fintype Ω} (μ : @Law Ω i) (x : Ω) : + @Law.mass Ω j (@Law.changeFintype Ω i j μ) x = @Law.mass Ω i μ x := by + have hij : i=j := Subsingleton.elim _ _ + cases hij + rfl + +noncomputable def Law.iid (μ : Law Ω) (S : ℕ) : Law (Fin S → Ω) where + mass := Variation.iid μ.mass S + nonneg := Variation.iid_nonneg μ.mass μ.nonneg S + total := Variation.iid_sum μ.mass μ.total S + +end MatchingFPRAS.Adaptive + +namespace MatchingFPRAS.Enlargement + +open Finset MatchingFPRAS.Transport MatchingFPRAS.Adaptive MatchingFPRAS.Replica.Ladder +open scoped Classical + +variable {V : Type*} [Fintype V] [LinearOrder V] [Nontrivial V] + +noncomputable local instance (w : V → V → ℝ) (K : ℕ) : DecidableEq (SourceLabel w K) := Classical.decEq _ + +noncomputable local instance (w : V → V → ℝ) (K : ℕ) : Fintype (BagEdge (sourceBags w K)) := Fintype.ofFinite _ + +noncomputable local instance (w : V → V → ℝ) (K : ℕ) : DecidableEq (SourcePM w K) := Classical.decEq _ + +noncomputable def sourceRunLawBase (w : V → V → ℝ) (hw : ∀ a b,0¬StageGood w w₁ K σ x) < 13/(1000*T) := by + have hi : i=sourceMarkedFintype w K := Subsingleton.elim _ _ + subst i + have h := source_run_stage_budget hn w w₁ hw hw₁ hle hz K T S hT hS hK σ hσ hSσ L hL hq z + convert h using 1 + unfold Law.event Law.iid Variation.event Variation.iid sourceMarkedFintype + congr 1 + +end MatchingFPRAS.Enlargement + +namespace MatchingFPRAS.Trial + +open Finset Switching Subdivision RealGeometry Hierarchy Transport Enlargement StageAnalysis +open MatchingFPRAS.Replica MatchingFPRAS.Replica.Ladder MatchingFPRAS.Adaptive +open scoped Classical + +structure Parameters (G : GraphInput) where + hn : 2 ≤ G.n + even : Even G.n + K : ℕ + epsilon : ℚ + epsilon_pos : 0s.start p) + (ladderSteps p.N p.D p.K p.T (1/(1000*p.K*p.S))) inferInstance + +noncomputable def ScaleState.sampleLaw (p : Parameters G) {j : ℕ} (hj : j ≤ p.K) (s : ScaleState G j) : + Law (Fin p.S → SourceMarked s.activity p.K) := (s.runLaw p hj).iid p.S + +theorem ScaleState.sampleLaw_budget (p : Parameters G) {j : ℕ} (hj : j ≤ p.K) (s : ScaleState G j) + (_hs : s.Balanced p.hn) : + (s.sampleLaw p hj).event (fun x=>¬StageGood s.activity s.nextActivity p.K p.sigma x) < 13/(1000*p.K) := by + exact sourceRunLaw_budget (by simpa using p.hn) s.activity s.nextActivity s.activity_pos + (fun a b=>(s.nextActivity_pos a b).le) (fun a b _=>(s.cooling a b).2) (s.partition_pos p.even) + p.K p.K p.S p.K_pos p.S_pos (s.cap hj) p.sigma p.sigma_pos.le (by simpa using p.S_bound) + p.T (ladderTier_spec p.N p.D p.K p.N_pos) p.q_pos (fun _=>s.start p) inferInstance + +structure Layer (p : Parameters G) (j : ℕ) where + Ω : Type + finite : Fintype Ω + law : @Law Ω finite + state : Ω → ScaleState G j + ratios : Ω → Fin j → ℝ + ratios_nonneg : ∀ x i,0 ≤ ratios x i + +attribute [instance] Layer.finite + +noncomputable def Layer.good (p : Parameters G) {j : ℕ} (L : Layer p j) (x : L.Ω) : Prop := + (L.state x).Balanced p.hn ∧ ∀ i : Fin j, + |L.ratios x i/(partition (raw G (i.val+1)) ∅/partition (raw G i.val) ∅)-1| ≤ (p.epsilon:ℝ)/(100*p.K) + +noncomputable def firstLayer (p : Parameters G) : Layer p 0 where + Ω := PUnit + finite := inferInstance + law := ⟨fun _=>1,fun _=>by norm_num,by simp⟩ + state _ := initialScaleState G p.hn + ratios _ := Fin.elim0 + ratios_nonneg _ i := Fin.elim0 i + +noncomputable def Layer.append (p : Parameters G) {j : ℕ} (hj : j ≤ p.K) (L : Layer p j) : Layer p (j+1) where + Ω := Σ x : L.Ω, Fin p.S → SourceMarked (L.state x).activity p.K + finite := inferInstance + law := L.law.sigma (fun x=>(L.state x).sampleLaw p hj) + state x := (L.state x.1).update p.hn x.2 + ratios x := Fin.snoc (L.ratios x.1) ((L.state x.1).ratioEstimate x.2) + ratios_nonneg x i := by + refine Fin.lastCases ?_ (fun i=>?_) i + · simpa using (L.state x.1).ratioEstimate_nonneg p.S_pos x.2 + · simpa using L.ratios_nonneg x.1 i + +theorem Layer.append_good (p : Parameters G) {j : ℕ} (hj : j ≤ p.K) (L : Layer p j) (x : L.Ω) + (hx : L.good p x) (y : Fin p.S → SourceMarked (L.state x).activity p.K) + (hy : StageGood (L.state x).activity (L.state x).nextActivity p.K p.sigma y) : + (L.append p hj).good p ⟨x,y⟩ := by + have h := successful_update p.hn p.even p.K_pos p.epsilon p.epsilon_real_pos p.epsilon_real_lt_one + hj (L.state x) hx.1 y hy + refine ⟨h.1,?_⟩ + intro i + refine Fin.lastCases ?_ (fun i=>?_) i + · simpa [Layer.append] using h.2 + · simpa [Layer.append] using hx.2 i + +theorem Layer.append_failure (p : Parameters G) {j : ℕ} (hj : j ≤ p.K) (L : Layer p j) : + (L.append p hj).law.event (fun x=>¬(L.append p hj).good p x) ≤ + L.law.event (fun x=>¬L.good p x)+13/(1000*p.K) := by + apply first_failure_sigma L.law (fun x=>(L.state x).sampleLaw p hj) (L.good p) + ((L.append p hj).good p) _ (by positivity) + intro x hx + apply le_trans ((L.state x).sampleLaw p hj |>.event_mono ?_) + ((L.state x).sampleLaw_budget p hj hx.1).le + intro y hy hgood + exact hy (L.append_good p hj x hx y hgood) + +noncomputable def layers (p : Parameters G) : (j : ℕ) → j ≤ p.K → Layer p j + | 0, _ => firstLayer p + | j+1, h => (layers p j (by omega)).append p (by omega) + +theorem layers_failure (p : Parameters G) (j : ℕ) (hj : j ≤ p.K) : + (layers p j hj).law.event (fun x=>¬(layers p j hj).good p x) ≤ j*(13/(1000*p.K)) := by + induction j with + | zero => + have hg : ∀ x,(firstLayer p).good p x := by + intro x + constructor + · exact initial_balanced G p.hn p.even + · intro i; exact Fin.elim0 i + simp [layers,Law.event,hg] + | succ j ih => + refine le_trans ((layers p j (by omega)).append_failure p (by omega)) ?_ + calc + _ ≤ (j:ℝ)*(13/(1000*p.K))+13/(1000*p.K) := by linarith only [ih (by omega)] + _ = _ := by push_cast; ring + +noncomputable def output (p : Parameters G) (x : (layers p p.K le_rfl).Ω) : ℝ := + (Z (completeGraph G.n):ℝ)*∏ i,(layers p p.K le_rfl).ratios x i + +lemma output_nonneg (p : Parameters G) (x : (layers p p.K le_rfl).Ω) : 0 ≤ output p x := by + apply mul_nonneg (Nat.cast_nonneg _) + exact prod_nonneg fun i _=>(layers p p.K le_rfl).ratios_nonneg x i + +def Accurate (p : Parameters G) (y : ℝ) : Prop := + (1-(p.epsilon:ℝ))*(Z G:ℝ)≤y ∧ y≤(1+(p.epsilon:ℝ))*(Z G:ℝ) + +theorem good_output (p : Parameters G) (hZ : 0¬Accurate p (output p x)) ≤ 13/1000 := by + have hh := layers_failure p p.K le_rfl + have he : (p.K:ℝ)*(13/(1000*p.K))=13/1000 := by + have hk : (p.K:ℝ)≠0 := by exact_mod_cast p.K_pos.ne' + field_simp + rw [he] at hh + apply le_trans ((layers p p.K le_rfl).law.event_mono ?_) hh + intro x hx hg + exact hx (good_output p hZ x hg) + +end MatchingFPRAS.Trial + +end OAI diff --git a/lean/OAI/Combinatorics/MatchingCount/Probability/FinitePMF.lean b/lean/OAI/Combinatorics/MatchingCount/Probability/FinitePMF.lean new file mode 100644 index 0000000000000000000000000000000000000000..18f30d948e92620f074dcbce8f01e4b2b8b704ca --- /dev/null +++ b/lean/OAI/Combinatorics/MatchingCount/Probability/FinitePMF.lean @@ -0,0 +1,430 @@ +import Mathlib +import OAI.Combinatorics.MatchingCount.Graphs.RowPeak + +namespace OAI + +namespace MatchingFPRAS.Concentration + +open MeasureTheory ProbabilityTheory Finset + +variable {Ω I J : Type*} [MeasurableSpace Ω] [Fintype I] + +variable {μ : Measure Ω} [IsProbabilityMeasure μ] + +theorem hoeffding_mean (X : I → Ω → ℝ) (hi : iIndepFun X μ) + (hm : ∀ i,AEMeasurable (X i) μ) (hb : ∀ i,∀ᵐ ω ∂μ,X i ω∈Set.Icc (0:ℝ) 1) + (m : ℝ) (hmean : ∀ i,(∫ ω,X i ω ∂μ)=m) + (hI : 0 X i ω-m) (1/4) μ := by + have h := hasSubgaussianMGF_of_mem_Icc (hm i) (hb i) + rw [hmean i] at h + norm_num at h ⊢ + exact h + have hind : iIndepFun (fun i ω => X i ω-m) μ := by + exact hi.comp (fun _ x => x-m) (fun _ => by fun_prop) + have hs : HasSubgaussianMGF (fun ω => ∑ i,(X i ω-m)) + ((Fintype.card I : NNReal)/4) μ := by + simpa only [Finset.sum_const,nsmul_eq_mul,mul_one_div,Finset.card_univ] using HasSubgaussianMGF.sum_of_iIndepFun hind (s:=univ) (fun i _ => hc i) + have hh := hs.measure_ge_le (mul_nonneg hN.le ht) + have hl := hs.neg.measure_ge_le (mul_nonneg hN.le ht) + have he : -((Fintype.card I : ℝ)*t)^2 / + (2*((Fintype.card I : NNReal)/4 : NNReal)) = -2*(Fintype.card I : ℝ)*t^2 := by + push_cast + field_simp [ne_of_gt hN] + ring + rw [he] at hh hl + calc + _ ≤ μ.real ({ω | (Fintype.card I : ℝ)*t ≤ ∑ i,(X i ω-m)} ∪ + {ω | (Fintype.card I : ℝ)*t ≤ -(∑ i,(X i ω-m))}) := by + refine measureReal_mono ?_ (by finiteness) + intro ω hω + simp only [Set.mem_ofPred_eq,Set.mem_union] at hω ⊢ + by_cases h : (Fintype.card I : ℝ)*t ≤ ∑ i,(X i ω-m) + · exact Or.inl h + · right + simp only [sum_sub_distrib,sum_const,nsmul_eq_mul,Finset.card_univ] at h ⊢ + rcases lt_abs.mp hω with hv | hv + · have hv' := (lt_div_iff₀ hN).mp (by linarith : m+t < (∑ i,X i ω)/(Fintype.card I : ℝ)) + nlinarith + · have hv' := (div_lt_iff₀ hN).mp (by linarith : (∑ i,X i ω)/(Fintype.card I : ℝ) < m-t) + nlinarith + _ ≤ μ.real {ω | (Fintype.card I : ℝ)*t ≤ ∑ i,(X i ω-m)} + + μ.real {ω | (Fintype.card I : ℝ)*t ≤ -(∑ i,(X i ω-m))} := measureReal_union_le _ _ + _ ≤ _ := by simpa only [Pi.neg_apply, two_mul] using add_le_add hh hl + +theorem hoeffding_observables [Fintype J] (X : J → I → Ω → ℝ) + (hi : ∀ j,iIndepFun (X j) μ) (hm : ∀ j i,AEMeasurable (X j i) μ) + (hb : ∀ j i,∀ᵐ ω ∂μ,X j i ω∈Set.Icc (0:ℝ) 1) + (m : J → ℝ) (hmean : ∀ j i,(∫ ω,X j i ω ∂μ)=m j) + (hI : 0 ENNReal.ofReal (p x)) (by + rw [←ENNReal.ofReal_sum_of_nonneg (fun x _ => hp x),hs] + simp) + +lemma finitePMF_apply (p : Ω → ℝ) (hp : ∀ x,0 ≤ p x) (hs : ∑ x,p x=1) (x : Ω) : + (finitePMF p hp hs x).toReal=p x := by simp [finitePMF,hp x] + +theorem finite_hoeffding [DecidableEq I] (p : Ω → ℝ) (hp : ∀ x,0 ≤ p x) (hs : ∑ x,p x=1) + (f : J → Ω → ℝ) (hf : ∀ j x,f j x∈Set.Icc (0:ℝ) 1) + (hI : 0 q.toMeasure) + have hi (j : J) : iIndepFun (fun i (v : I → Ω) => f j (v i)) μ := by + exact iIndepFun_pi (fun _ : I => (measurable_of_finite (f j)).aemeasurable) + have hm (j : J) (i : I) : AEMeasurable (fun v : I → Ω => f j (v i)) μ := + (measurable_of_finite _).aemeasurable + have hb (j : J) (i : I) : ∀ᵐ v ∂μ,f j (v i)∈Set.Icc (0:ℝ) 1 := + Filter.Eventually.of_forall (fun v => hf j (v i)) + have he (j : J) (i : I) : (∫ v,f j (v i) ∂μ)=∑ x,p x*f j x := by + have hev := (measurePreserving_eval (fun _ : I => q.toMeasure) i).map_eq + have hmap := integral_map ((measurable_of_finite (Function.eval i)).aemeasurable (μ:=μ)) + ((measurable_of_finite (f j)).aestronglyMeasurable (μ:=Measure.map (Function.eval i) μ)) + rw [hev] at hmap + rw [←hmap, PMF.integral_eq_sum] + apply sum_congr rfl + intro x hx + simp [q,finitePMF_apply,smul_eq_mul] + have h := hoeffding_observables (μ:=μ) (fun j i v => f j (v i)) hi hm hb + (fun j => ∑ x,p x*f j x) he hI t ht + have hsingle (v : I → Ω) : μ.real {v}=∏ i,p (v i) := by + simp only [Measure.real,μ,Measure.pi_singleton,ENNReal.toReal_prod] + apply prod_congr rfl + intro i hi + simp [q,finitePMF,hp (v i)] + let B : Finset (I → Ω) := univ.filter (fun v => ∃ j,t < |(∑ i,f j (v i))/(Fintype.card I : ℝ)-∑ x,p x*f j x|) + have hB : (B : Set (I → Ω))={v | ∃ j,t < |(∑ i,f j (v i))/(Fintype.card I : ℝ)-∑ x,p x*f j x|} := by + ext v; simp [B] + rw [←hB,←sum_measureReal_singleton] at h + simpa only [hsingle, B, sum_filter] using h + + + +lemma observables_exp_tail (n K : ℕ) (hK : 0 exact hw _ _ + have h₁ : 0 ≤ logicalActivity w₁ he.choose.1 := by + unfold logicalActivity edgeActivity; split_ifs <;> exact hw₁ _ _ + exact ⟨div_nonneg h₁ h₀.le,(div_le_one h₀).mpr (logicalActivity_le_off w w₁ hle _)⟩ + · norm_num + · norm_num + +lemma observableD_range_off (w w₁ : V → V → ℝ) (hw : ∀ x y,0 < w x y) + (hw₁ : ∀ x y,0 ≤ w₁ x y) (hle : ∀ x y,x≠y → w₁ x y ≤ w x y) + (K : ℕ) (a : SourceMarked w K) : + 0 ≤ observableD w w₁ K a ∧ observableD w w₁ K a ≤ 1 := by + unfold observableD + split_ifs + · exact ⟨Finset.prod_nonneg (fun e _ => (bagReweight_range_off w w₁ hw hw₁ hle K e).1), + Finset.prod_le_one₀ (fun e _ => (bagReweight_range_off w w₁ hw hw₁ hle K e).1) + (fun e _ => (bagReweight_range_off w w₁ hw hw₁ hle K e).2)⟩ + · norm_num + +lemma observableProbe_range_off (w w₁ : V → V → ℝ) (hw : ∀ x y,0 < w x y) + (hw₁ : ∀ x y,0 ≤ w₁ x y) (hle : ∀ x y,x≠y → w₁ x y ≤ w x y) + (K : ℕ) (e₀ : LogicalEdge V) (a : SourceMarked w K) : + 0 ≤ observableProbe w w₁ K e₀ a ∧ observableProbe w w₁ K e₀ a ≤ 1 := by + unfold observableProbe + split_ifs + · exact ⟨Finset.prod_nonneg (fun e _ => (bagReweight_range_off w w₁ hw hw₁ hle K e).1), + Finset.prod_le_one₀ (fun e _ => (bagReweight_range_off w w₁ hw hw₁ hle K e).1) + (fun e _ => (bagReweight_range_off w w₁ hw hw₁ hle K e).2)⟩ + · norm_num + +abbrev ObservableIndex (V : Type*) [LinearOrder V] := Fin 2 ⊕ LogicalEdge V + +noncomputable def sourceObservable (w w₁ : V → V → ℝ) (K : ℕ) : + ObservableIndex V → SourceMarked w K → ℝ + | Sum.inl i => if i=0 then observableA w K else observableD w w₁ K + | Sum.inr e => observableProbe w w₁ K e + +lemma sourceObservable_range (w w₁ : V → V → ℝ) (hw : ∀ x y,0 < w x y) + (hw₁ : ∀ x y,0 ≤ w₁ x y) (hle : ∀ x y,x≠y → w₁ x y ≤ w x y) + (K : ℕ) (j : ObservableIndex V) (a : SourceMarked w K) : + sourceObservable w w₁ K j a∈Set.Icc (0:ℝ) 1 := by + cases j with + | inl i => + dsimp [sourceObservable] + split_ifs + · exact observableA_range w K a + · exact observableD_range_off w w₁ hw hw₁ hle K a + | inr e => exact observableProbe_range_off w w₁ hw hw₁ hle K e a + +omit [Nontrivial V] in +lemma observableIndex_card : Fintype.card (ObservableIndex V) ≤ (Fintype.card V)^2+2 := by + have h := Fintype.card_subtype_le (fun e : V×V => e.1 ¬StageGood w w₁ K σ x) < 13/(1000*T) := by + have hpos := sourceBagZ_pos w hw hz K (sourceD (V:=V) K) + have hq := sourceLaw_nonneg w hw K _ hpos.le + have hqs := sourceLaw_sum w K _ hpos.ne' + have hiid := Variation.iid_tv p (sourceLaw w K (sourceD (V:=V) K)) hp hpsum hq hqs S + have he := Variation.event_sub_le (Variation.iid p S) + (Variation.iid (sourceLaw w K (sourceD (V:=V) K)) S) + (by rw [Variation.iid_sum p hpsum,Variation.iid_sum _ hqs]) + (fun x => ¬StageGood w w₁ K σ x) + have hv := (le_abs_self _).trans (he.trans hiid) + have hh := source_ideal_budget w w₁ hw hw₁ hle hz K T S hT hS σ hσ hsize + have ht := mul_le_mul_of_nonneg_left htv (Nat.cast_nonneg S : (0:ℝ)≤S) + have hid : (1:ℝ)/(100*T)+(S:ℝ)*(3/(1000*T*S))=13/(1000*T) := by + have ht0 : (T:ℝ)≠0 := by exact_mod_cast hT.ne' + have hs0 : (S:ℝ)≠0 := by exact_mod_cast hS.ne' + field_simp + ring + have hh' : Variation.event (Variation.iid (sourceLaw w K (sourceD (V:=V) K)) S) + (fun x => ¬StageGood w w₁ K σ x) < 1/(100*T) := by + convert hh using 1 + unfold Variation.event Variation.iid + congr 1 + funext x + split_ifs <;> rfl + linarith + +theorem source_run_stage_budget (hn : 2 ≤ Fintype.card V) + (w w₁ : V → V → ℝ) (hw : ∀ x y,0 ¬StageGood w w₁ K σ x) < 13/(1000*T) := by + dsimp only + apply source_nearby_budget w w₁ hw hw₁ hle hz K T S hT hS σ hσ hsize + · exact sourceRun_nonneg w hw K hK L _ hq z _ + · exact sourceRun_sum w hw K hK L _ hq z _ + · have ht : (1:ℝ)≤T := by exact_mod_cast hT + have hs : (1:ℝ)≤S := by exact_mod_cast hS + have hd : (1:ℝ)<1000*T*S := by nlinarith + exact (sourceRun_tv hn w hw K hK L hL hq z _ (by positivity) + ((div_lt_one (by positivity)).mpr hd)).trans (by gcongr; norm_num) + +end MatchingFPRAS.Enlargement + +end OAI diff --git a/lean/OAI/Combinatorics/MatchingCount/Probability/LocalVariance.lean b/lean/OAI/Combinatorics/MatchingCount/Probability/LocalVariance.lean new file mode 100644 index 0000000000000000000000000000000000000000..601c053d0ef2852785b41985742b4cb68e001972 --- /dev/null +++ b/lean/OAI/Combinatorics/MatchingCount/Probability/LocalVariance.lean @@ -0,0 +1,446 @@ +import Mathlib +import OAI.Combinatorics.MatchingCount.Sampling.RelationDestinations +import OAI.Combinatorics.MatchingCount.Probability.Mean + +namespace OAI + +namespace MatchingFPRAS.Replica + +section + +open Finset + +variable {I Ω : Type*} [Fintype I] [DecidableEq I] [Fintype Ω] [DecidableEq Ω] + +variable (p : I → Ω → ℝ) + +noncomputable def localVariance (π : Ω → ℝ) (a : Ω → ℝ) : ℝ := + ∑ u, π u*(a u-∑ v, π v*a v)^2 + +def PairPoincare (x y : I) (Q : PairCapacity p x y) (C : ℝ) : Prop := + ∀ a b : Ω → ℝ, localVariance (p x) a ≤ C*localEnergy Q.q (fun z => a z.1+b z.2) + +omit [Fintype I] [DecidableEq Ω] in +lemma invariant_update (i : I) (f : (I → Ω) → ℝ) (hi : average p i f = f) + (s : I → Ω) (a : Ω) : f (Function.update s i a) = f s := by + rw [← hi] + exact average_update p i a f s + +omit [DecidableEq Ω] in +lemma pairEnergy_shift_invariant (x y : I) (Q : PairCapacity p x y) + (f d : (I → Ω) → ℝ) (hx : average p x d = d) (hy : average p y d = d) : + pairEnergy p x y Q (f-d) = pairEnergy p x y Q f := by + have he (s : I → Ω) : slice x y (f-d) s = (fun a => slice x y f s a-d s) := by + funext a + change f (replacePair x y s a)-d (Function.update (Function.update s x a.1) y a.2) = _ + rw [invariant_update p y d hy,invariant_update p x d hx] + rfl + unfold pairEnergy + simp_rw [he,localEnergy_shift] + +omit [DecidableEq Ω] in +lemma pair_poincare_global (hp : ∀ i a, 0 ≤ p i a) (hs : ∀ i, ∑ a, p i a = 1) + (x y : I) (hxy : x ≠ y) (Q : PairCapacity p x y) (C : ℝ) (hQ : PairPoincare p x y Q C) + (h k : (I → Ω) → ℝ) (hh : average p x h = 0) (hhy : average p y h = h) + (hkx : average p x k = k) : dot p h h ≤ C*pairEnergy p x y Q (h+k) := by + have hc (s : I → Ω) : (∑ a, p x a*h (Function.update s x a)) = 0 := by + change average p x h s = 0 + rw [hh]; rfl + have he (s : I → Ω) : (fun a : Ω × Ω => + h (Function.update s x a.1)+k (Function.update s y a.2)) = slice x y (h+k) s := by + funext a + change _ = h (Function.update (Function.update s x a.1) y a.2)+ + k (Function.update (Function.update s x a.1) y a.2) + rw [invariant_update p y h hhy,Function.update_comm hxy,invariant_update p x k hkx] + have hi (s : I → Ω) : average p x (fun s => (h s)^2) s ≤ + C*localEnergy Q.q (slice x y (h+k) s) := by + have hi := hQ (fun a => h (Function.update s x a)) (fun b => k (Function.update s y b)) + unfold localVariance at hi + rw [hc,he] at hi + simpa only [sub_zero,average_apply] using hi + have hi := mean_mono p hp hi + rw [mean_average p hs,mean_square,mean_mul] at hi + exact hi + +omit [DecidableEq Ω] in +lemma projection_contraction (hp : ∀ i a, 0 ≤ p i a) (P : Projection p) (f : (I → Ω) → ℝ) : + dot p (P.op f) (P.op f) ≤ dot p f f := by + have hh := dot_nonneg p hp (f-P.op f) + rw [projection_pythagoras] at hh + linarith + +noncomputable def baseEnergy (i : I) (f : (I → Ω) → ℝ) : ℝ := + dot p (f-average p i f) (f-average p i f) + +omit [DecidableEq Ω] in +lemma baseEnergy_nonneg (hp : ∀ i a, 0 ≤ p i a) (i : I) (f : (I → Ω) → ℝ) : + 0 ≤ baseEnergy p i f := dot_nonneg p hp _ + +variable [LinearOrder I] + +omit [DecidableEq Ω] in +lemma increment_base_bound (hp : ∀ i a, 0 ≤ p i a) (hs : ∀ i, ∑ a, p i a = 1) + (i : I) (f : (I → Ω) → ℝ) : + dot p (increment p Finset.univ i f) (increment p Finset.univ i f) ≤ baseEnergy p i f := by + let P := listProjection p hs ((Finset.univ.filter (i < ·)).toList) + have he : increment p Finset.univ i f = P.op (f-average p i f) := by + change avgList p _ f-average p i (avgList p _ f) = avgList p _ (f-average p i f) + rw [map_sub,average_comm_list] + rw [he] + exact projection_contraction p hp P (f-average p i f) + +omit [DecidableEq Ω] in +lemma one_pair (hp : ∀ i a, 0 ≤ p i a) (hs : ∀ i, ∑ a, p i a = 1) + (x y : I) (hxy : x < y) (Q : PairCapacity p x y) (L : ℝ) (hL : 0 ≤ L) + (hQ : PairPoincare p x y Q (2*L)) (f : (I → Ω) → ℝ) : + dot p (increment p Finset.univ x f) (increment p Finset.univ x f) ≤ + 4*L*pairEnergy p x y Q f+8*L*dot p (residual p x y f) (residual p x y f) := by + let c := pairCondition p x y f + let h := increment p Finset.univ x f + let k := average p x c-average p x (average p y c) + let d := average p x (average p y c) + have hh : h = average p y c-d := increment_pair_formula p hs x y hxy f + have hhy : average p y h = h := by + rw [hh,map_sub] + change average p y (average p y c)-average p y (average p x (average p y c)) = + average p y c-average p x (average p y c) + rw [average_comm p y x,average_idem p hs] + have hkx : average p x k = k := by + change average p x (average p x c-average p x (average p y c)) = _ + rw [map_sub,average_idem p hs,average_idem p hs] + have hdx : average p x d = d := average_idem p hs x _ + have hdy : average p y d = d := by + change average p y (average p x (average p y c)) = average p x (average p y c) + rw [average_comm,average_idem p hs] + have hhk : h+k = c-residual p x y f-d := by + rw [hh,residual_formula] + change (average p y c-d)+(average p x c-d) = + c-(c-average p x c-average p y c+average p x (average p y c))-d + dsimp [d]; abel + have hpq := pair_poincare_global p hp hs x y (ne_of_lt hxy) Q (2*L) hQ h k + (increment_center p hs Finset.univ x f) hhy hkx + rw [hhk,pairEnergy_shift_invariant p x y Q _ d hdx hdy] at hpq + have hc : pairEnergy p x y Q c ≤ pairEnergy p x y Q f := by + apply pairEnergy_avgList p hp hs (outside x y) x y _ Q f + intro i hi + have hi : x < i ∧ i ≠ y := by simpa [outside] using hi + exact ⟨ne_of_gt hi.1,hi.2⟩ + have he := pairEnergy_sub p hp x y Q c (residual p x y f) + have hr := pairEnergy_bound p hp hs x y Q (residual p x y f) + nlinarith [mul_nonneg hL (sub_nonneg.mpr hc),mul_nonneg hL (sub_nonneg.mpr hr), + mul_nonneg hL (sub_nonneg.mpr he)] + +end + +section + +open Finset + +variable {I Ω : Type*} [Fintype I] [DecidableEq I] [LinearOrder I] + [Fintype Ω] [DecidableEq Ω] + +variable (p : I → Ω → ℝ) + +noncomputable def allowed (guides : I → Finset I) : Finset (I × I) := + Finset.univ.filter (fun z => z.2 ∈ guides z.1) + +omit [LinearOrder I] in +lemma sum_allowed (guides : I → Finset I) (f : I × I → ℝ) : + (∑ z ∈ allowed guides, f z) = ∑ x, ∑ y ∈ guides x, f (x,y) := by + classical + simp only [allowed,Finset.sum_filter] + rw [Fintype.sum_prod_type] + apply Finset.sum_congr rfl; intro x _ + simpa only [Finset.filter_univ_mem] using + (Finset.sum_filter (s := Finset.univ) (fun y => y ∈ guides x) (fun y => f (x,y))).symm + +noncomputable def pairTotal (guides : I → Finset I) (Q : ∀ x y, PairCapacity p x y) + (f : (I → Ω) → ℝ) : ℝ := ∑ x, ∑ y ∈ guides x, pairEnergy p x y (Q x y) f + +noncomputable def baseTotal (base : Finset I) (f : (I → Ω) → ℝ) : ℝ := + ∑ x ∈ base, baseEnergy p x f + +noncomputable def scanEnergy (guides : I → Finset I) (base : Finset I) + (Q : ∀ x y, PairCapacity p x y) (f : (I → Ω) → ℝ) : ℝ := + (pairTotal p guides Q f+baseTotal p base f)/(2*((∑ x, (guides x).card)+base.card : ℕ)) + +omit [DecidableEq Ω] in +theorem replica_gap (hp : ∀ i a, 0 ≤ p i a) (hs : ∀ i, ∑ a, p i a = 1) + (guides : I → Finset I) (base : Finset I) (hbase : base.Nonempty) + (q : ℕ) (L : ℝ) (hL : 0 < L) (hq : (q:ℝ) = 32*L) + (hn : ∀ x ∉ base, (guides x).card = q) (hb : ∀ x ∈ base, guides x = ∅) + (horder : ∀ x y, y ∈ guides x → x < y) + (Q : ∀ x y, PairCapacity p x y) + (hQ : ∀ x y, y ∈ guides x → PairPoincare p x y (Q x y) (2*L)) + (f : (I → Ω) → ℝ) : + variance p f ≤ (8*((∑ x, (guides x).card)+base.card : ℕ)/3:ℝ)* + scanEnergy p guides base Q f := by + classical + let H : I → ℝ := fun x => dot p (increment p Finset.univ x f) (increment p Finset.univ x f) + let B := ∑ x ∈ base, H x + let A := ∑ x ∈ baseᶜ, H x + let E := pairTotal p guides Q f + let F := baseTotal p base f + have hvar : variance p f = A+B := by + have h := Finset.sum_add_sum_compl base H + rw [martingale_variance] + change (∑ x, H x) = A+B + dsimp [A,B]; linarith + exact hs + have hbaseBound : B ≤ F := Finset.sum_le_sum (fun x _ => increment_base_bound p hp hs x f) + have hE : 0 ≤ E := Finset.sum_nonneg (fun x _ => Finset.sum_nonneg + (fun y _ => pairEnergy_nonneg p hp x y (Q x y) f)) + have hF : 0 ≤ F := Finset.sum_nonneg (fun x _ => baseEnergy_nonneg p hp x f) + have hlhs : (∑ x, ∑ y ∈ guides x, H x) = (q:ℝ)*A := by + calc + _ = ∑ x, if x ∈ baseᶜ then (q:ℝ)*H x else 0 := by + apply Finset.sum_congr rfl; intro x _ + by_cases hx : x ∈ base + · simp [hb x hx,hx] + · simp [hx,hn x hx] + _ = ∑ x ∈ baseᶜ, (q:ℝ)*H x := by + simpa only [Finset.filter_univ_mem] using + (Finset.sum_filter (s := Finset.univ) (fun x => x ∈ baseᶜ) (fun x => (q:ℝ)*H x)).symm + _ = _ := by rw [Finset.mul_sum] + have hr : (∑ x, ∑ y ∈ guides x, dot p (residual p x y f) (residual p x y f)) ≤ variance p f := by + have hh := residual_sum p hp hs (allowed guides) + (fun z hz => horder z.1 z.2 (by simpa [allowed] using hz)) f + rw [sum_allowed] at hh + have hv : variance p f = ∑ s, density p s*(f s-∑ t, density p t*f t)^2 := by + unfold variance dot mean + apply Finset.sum_congr rfl; intro s _ + change density p s*(f s-∑ t, density p t*f t)*(f s-∑ t, density p t*f t) = _ + ring + rw [hv] + exact hh + have hpair := Finset.sum_le_sum (fun x (_ : x ∈ (Finset.univ : Finset I)) => + Finset.sum_le_sum (fun y hy => one_pair p hp hs x y (horder x y hy) (Q x y) L + (le_of_lt hL) (hQ x y hy) f)) + change (∑ x, ∑ y ∈ guides x, H x) ≤ _ at hpair + rw [hlhs,hq] at hpair + simp only [Finset.sum_add_distrib,← Finset.mul_sum] at hpair + change 32*L*A ≤ 4*L*E+8*L*(∑ x, ∑ y ∈ guides x, + dot p (residual p x y f) (residual p x y f)) at hpair + have hstrong : variance p f ≤ E/6+(4/3:ℝ)*F := by + apply (mul_le_mul_iff_left₀ hL).mp + nlinarith [mul_nonneg (le_of_lt hL) (sub_nonneg.mpr hr), + mul_nonneg (le_of_lt hL) (sub_nonneg.mpr hbaseBound)] + let M : ℝ := ((∑ x, (guides x).card)+base.card : ℕ) + have hM : 0 < M := by + have hnM : 0 < ((∑ x, (guides x).card)+base.card : ℕ) := + lt_of_lt_of_le (Finset.card_pos.mpr hbase) (Nat.le_add_left _ _) + dsimp [M] + exact_mod_cast hnM + change variance p f ≤ (8*M/3)*((E+F)/(2*M)) + have he : (8*M/3)*((E+F)/(2*M)) = (4/3:ℝ)*(E+F) := by + field_simp [ne_of_gt hM] + ring + rw [he] + linarith + +end + +open Finset + +variable {Ω : Type*} [Fintype Ω] [DecidableEq Ω] + +structure SymmetricProposal (Ω : Type*) [Fintype Ω] where + q : Ω → Ω → ℝ + nonneg : ∀ a b, 0 ≤ q a b + row : ∀ a, ∑ b, q a b = 1 + symmetric : ∀ a b, q a b = q b a + +noncomputable def offCapacity (P : SymmetricProposal Ω) (π : Ω → ℝ) (a b : Ω) : ℝ := + min (π a) (π b)*P.q a b + +noncomputable def metropolisCapacity (P : SymmetricProposal Ω) (π : Ω → ℝ) (a b : Ω) : ℝ := + if a = b then π a - ∑ z ∈ Finset.univ.erase a, offCapacity P π a z + else offCapacity P π a b + +omit [DecidableEq Ω] in +lemma offCapacity_nonneg (P : SymmetricProposal Ω) (π : Ω → ℝ) + (hπ : ∀ a, 0 ≤ π a) (a b : Ω) : 0 ≤ offCapacity P π a b := + mul_nonneg (le_min (hπ a) (hπ b)) (P.nonneg a b) + +omit [DecidableEq Ω] in +lemma offCapacity_le (P : SymmetricProposal Ω) (π : Ω → ℝ) + (a b : Ω) : offCapacity P π a b ≤ π a*P.q a b := + mul_le_mul_of_nonneg_right (min_le_left _ _) (P.nonneg a b) + +omit [DecidableEq Ω] in +lemma offCapacity_symmetric (P : SymmetricProposal Ω) (π : Ω → ℝ) + (a b : Ω) : offCapacity P π a b = offCapacity P π b a := by + simp only [offCapacity,min_comm (π a),P.symmetric] + +lemma offCapacity_sum_le (P : SymmetricProposal Ω) (π : Ω → ℝ) + (hπ : ∀ a, 0 ≤ π a) (a : Ω) : + (∑ z ∈ Finset.univ.erase a, offCapacity P π a z) ≤ π a := by + calc + _ ≤ ∑ z, offCapacity P π a z := Finset.sum_le_sum_of_subset_of_nonneg + (Finset.erase_subset _ _) (fun z _ _ => offCapacity_nonneg P π hπ a z) + _ ≤ ∑ z, π a*P.q a z := Finset.sum_le_sum (fun z _ => offCapacity_le P π a z) + _ = π a := by rw [← Finset.mul_sum,P.row,mul_one] + +lemma metropolisCapacity_nonneg (P : SymmetricProposal Ω) (π : Ω → ℝ) + (hπ : ∀ a, 0 ≤ π a) (a b : Ω) : 0 ≤ metropolisCapacity P π a b := by + unfold metropolisCapacity + split_ifs + · exact sub_nonneg.mpr (offCapacity_sum_le P π hπ a) + · exact offCapacity_nonneg P π hπ a b + +lemma metropolisCapacity_symmetric (P : SymmetricProposal Ω) (π : Ω → ℝ) + (a b : Ω) : metropolisCapacity P π a b = metropolisCapacity P π b a := by + by_cases h : a = b + · subst b; rfl + · simp only [metropolisCapacity,ite_eq_right h,ite_eq_right (Ne.symm h)] + exact offCapacity_symmetric P π a b + +lemma metropolisCapacity_row (P : SymmetricProposal Ω) (π : Ω → ℝ) + (a : Ω) : (∑ b, metropolisCapacity P π a b) = π a := by + rw [← Finset.sum_erase_add _ _ (Finset.mem_univ a)] + have he : (∑ b ∈ Finset.univ.erase a, metropolisCapacity P π a b) = + ∑ b ∈ Finset.univ.erase a, offCapacity P π a b := by + apply Finset.sum_congr rfl; intro b hb + rw [metropolisCapacity,ite_eq_right (Finset.ne_of_mem_erase hb).symm] + rw [he] + simp only [metropolisCapacity,ite_true] + ring + +lemma metropolisCapacity_col (P : SymmetricProposal Ω) (π : Ω → ℝ) + (b : Ω) : (∑ a, metropolisCapacity P π a b) = π b := by + simp_rw [metropolisCapacity_symmetric P π] + exact metropolisCapacity_row P π b + +noncomputable def metropolis (P : SymmetricProposal Ω) (π : Ω → ℝ) (a b : Ω) : ℝ := + metropolisCapacity P π a b / π a + +lemma metropolis_row (P : SymmetricProposal Ω) (π : Ω → ℝ) + (hπ : ∀ a, 0 < π a) (a : Ω) : (∑ b, metropolis P π a b) = 1 := by + simp only [metropolis,← Finset.sum_div,metropolisCapacity_row] + exact div_self (ne_of_gt (hπ a)) + +lemma metropolis_nonneg (P : SymmetricProposal Ω) (π : Ω → ℝ) + (hπ : ∀ a, 0 < π a) (a b : Ω) : 0 ≤ metropolis P π a b := + div_nonneg (metropolisCapacity_nonneg P π (fun a => (hπ a).le) a b) (hπ a).le + +lemma metropolis_acceptance (P : SymmetricProposal Ω) (π : Ω → ℝ) + (hπ : ∀ a, 0 < π a) (a b : Ω) (hab : a ≠ b) : + metropolis P π a b = P.q a b*min 1 (π b/π a) := by + unfold metropolis metropolisCapacity + rw [ite_eq_right hab] + unfold offCapacity + rw [mul_div_right_comm,← min_div_div_right (hπ a).le,div_self (ne_of_gt (hπ a)),mul_comm] + +lemma metropolis_detailed (P : SymmetricProposal Ω) (π : Ω → ℝ) + (hπ : ∀ a, 0 < π a) (a b : Ω) : + π a*metropolis P π a b = π b*metropolis P π b a := by + simp only [metropolis,mul_div_cancel₀ _ (ne_of_gt (hπ a)), + mul_div_cancel₀ _ (ne_of_gt (hπ b))] + exact metropolisCapacity_symmetric P π a b + +lemma metropolis_energy (P : SymmetricProposal Ω) (π : Ω → ℝ) (f : Ω → ℝ) : + localEnergy (metropolisCapacity P π) f = localEnergy (offCapacity P π) f := by + unfold localEnergy + congr 1 + apply Finset.sum_congr rfl; intro a _ + apply Finset.sum_congr rfl; intro b _ + by_cases h : a = b + · subst b; simp + · simp only [metropolisCapacity,ite_eq_right h] + +theorem metropolis_energy_domination (P : SymmetricProposal Ω) (π μ : Ω → ℝ) + (r : ℝ) (hr : 0 ≤ r) (h : ∀ a, r*π a ≤ μ a) (f : Ω → ℝ) : + r*localEnergy (metropolisCapacity P π) f ≤ localEnergy (metropolisCapacity P μ) f := by + rw [metropolis_energy,metropolis_energy] + unfold localEnergy + rw [← mul_div_assoc,Finset.mul_sum] + apply div_le_div_of_nonneg_right _ (by norm_num) + apply Finset.sum_le_sum; intro a _ + rw [Finset.mul_sum] + apply Finset.sum_le_sum; intro b _ + have hh : r*min (π a) (π b) ≤ min (μ a) (μ b) := by + apply le_min + · exact (mul_le_mul_of_nonneg_left (min_le_left _ _) hr).trans (h a) + · exact (mul_le_mul_of_nonneg_left (min_le_right _ _) hr).trans (h b) + calc + _ = (r*min (π a) (π b))*P.q a b*(f a-f b)^2 := by unfold offCapacity; ring + _ ≤ _ := mul_le_mul_of_nonneg_right + (mul_le_mul_of_nonneg_right hh (P.nonneg a b)) (sq_nonneg _) + +end MatchingFPRAS.Replica + +namespace MatchingFPRAS.Transport + +section + +open Finset MatchingFPRAS.Replica + +variable {V E : Type*} [Fintype V] [DecidableEq V] [Fintype E] [DecidableEq E] + +variable (ends : E → Sym2 V) + +attribute [local instance] Classical.propDecidable + +noncomputable def firstLift {Ω : Type*} [Fintype Ω] (q : Ω → Ω → ℝ) + (a b : Ω × Ω) : ℝ := if a.2 = b.2 then q a.1 b.1 else 0 + +lemma firstLift_row {Ω : Type*} [Fintype Ω] (q : Ω → Ω → ℝ) + (hq : ∀ a, ∑ b, q a b = 1) (a : Ω × Ω) : (∑ b, firstLift q a b) = 1 := by + classical + simp [Fintype.sum_prod_type,firstLift,hq] + +lemma firstLift_symmetric {Ω : Type*} [Fintype Ω] (q : Ω → Ω → ℝ) + (hq : ∀ a b, q a b = q b a) (a b : Ω × Ω) : firstLift q a b = firstLift q b a := by + simp [firstLift,eq_comm,hq a.1 b.1] + +noncomputable def pairProposalRaw (a b : PM (fun e v => v ∈ ends e) × PM (fun e v => v ∈ ends e)) : ℝ := + (firstLift (switchProposal ends) a b + firstLift (colorProposal ends) a b + cycleProposal a b)/3 + +noncomputable def pairProposal (hloop : ∀ e, ¬(ends e).IsDiag) + (hpar : ∀ e, (Finset.univ.filter (fun f => ends f = ends e)).card ≤ 2) : + SymmetricProposal (PM (fun e v => v ∈ ends e) × PM (fun e v => v ∈ ends e)) where + q := pairProposalRaw ends + nonneg a b := by + unfold pairProposalRaw firstLift + have hs := switchProposal_nonneg ends hloop hpar a.1 b.1 + have hc := colorProposal_nonneg ends hloop hpar a.1 b.1 + have hy := cycleProposal_nonneg a b + split_ifs <;> positivity + row a := by + unfold pairProposalRaw + rw [← Finset.sum_div,Finset.sum_add_distrib,Finset.sum_add_distrib, + firstLift_row _ (switchProposal_row ends),firstLift_row _ (colorProposal_row ends),cycleProposal_row] + norm_num + symmetric a b := by + unfold pairProposalRaw + rw [firstLift_symmetric _ (switchProposal_symmetric ends), + firstLift_symmetric _ (colorProposal_symmetric ends),cycleProposal_symmetric a b] + +noncomputable def pairLaw (w z : E → ℝ) (a : PM (fun e v => v ∈ ends e) × PM (fun e v => v ∈ ends e)) : ℝ := + gibbs w a.1*gibbs z a.2 + +end + +open Finset MatchingFPRAS.Replica + +variable {Ω : Type*} [Fintype Ω] [DecidableEq Ω] + +lemma firstLift_energy (π : Ω → ℝ) (hπ : ∀ a, 0 ≤ π a) (hs : ∑ a, π a = 1) + (q : Ω → Ω → ℝ) (f g : Ω → ℝ) : + (∑ a : Ω × Ω, ∑ b : Ω × Ω, min (π a.1*π a.2) (π b.1*π b.2)* + firstLift q a b*((f a.1+g a.2)-(f b.1+g b.2))^2) = + ∑ a, ∑ b, min (π a) (π b)*q a b*(f a-f b)^2 := by + classical + simp only [Fintype.sum_prod_type,firstLift,mul_ite,ite_mul,zero_mul,mul_zero] + simp only [Finset.sum_ite_eq,Finset.mem_univ,ite_true] + have h (a b c : Ω) : + min (π a*π b) (π c*π b)*q a c*((f a+g b)-(f c+g b))^2 = + π b*(min (π a) (π c)*q a c*(f a-f c)^2) := by + rw [← min_mul_of_nonneg _ _ (hπ b)] + ring + simp_rw [h,← Finset.mul_sum] + simp only [← Finset.sum_mul,hs,one_mul] + +end MatchingFPRAS.Transport + +end OAI diff --git a/lean/OAI/Combinatorics/MatchingCount/Probability/MainLaw.lean b/lean/OAI/Combinatorics/MatchingCount/Probability/MainLaw.lean new file mode 100644 index 0000000000000000000000000000000000000000..d57e9136fbf9c28cac0ccf7e686379016f92cb0e --- /dev/null +++ b/lean/OAI/Combinatorics/MatchingCount/Probability/MainLaw.lean @@ -0,0 +1,71 @@ +import Mathlib +import OAI.Combinatorics.MatchingCount.Algorithm.AlgorithmLaw +import OAI.Combinatorics.MatchingCount.Machines.Wrapper +import OAI.Combinatorics.MatchingCount.Machines.PhysicalProgramSeal + +namespace OAI + +namespace MatchingFPRAS.LiteralPhysical +open Turing PhysicalPost PhysicalStream LiteralAlgorithm +open scoped Classical + +def ProperTape (G : GraphInput) (T : Tape Symbol) : Prop := + ∃ q : ℚ,0≤q ∧ T.right₀=ListBlank.mk (encodeRat q) ∧ (Z G=0→q=0) +def AccurateTape (G : GraphInput) (ε : ℚ) (T : Tape Symbol) : Prop := + ∃ q : ℚ,T.right₀=ListBlank.mk (encodeRat q) ∧ (1-ε)*(Z G:ℚ)≤q ∧ q≤(1+ε)*(Z G:ℚ) +lemma properTape_of_word (G : GraphInput) (as : List Symbol) (h : Proper G as) : ProperTape G (Tape.mk₁ as) := by + obtain ⟨q,hq,rfl,hz⟩:=h + exact ⟨q,hq,by simp [Tape.mk₁,Tape.mk₂],hz⟩ +lemma accurateTape_of_word (G : GraphInput) (ε : ℚ) (as : List Symbol) (h : AccurateWord G ε as) : + AccurateTape G ε (Tape.mk₁ as) := by + obtain ⟨q,rfl,hq⟩:=h + exact ⟨q,by simp [Tape.mk₁,Tape.mk₂],hq⟩ +lemma mainProgram_all (G : GraphInput) (ε δ : ℚ) (he : 0<ε) (he1 : ε<1) (hd : 0≤δ) + (n : ℕ) (hn : wrapTime algorithmRealizer (encodeInput G ε δ)≤n) (b : Bits n) : + (MatchingFPRAS.run mainProgram.machine (encodeInput G ε δ) b).state=none ∧ + ProperTape G (MatchingFPRAS.run mainProgram.machine (encodeInput G ε δ) b).tape := by + apply (mainProgram_realizes G ε δ).run_all _ _ n hn b + rw [Experiment.all_map] + exact (algorithm_proper G ε δ he he1 hd).mono (properTape_of_word G) +lemma mainProgram_outputs (G : GraphInput) (ε δ : ℚ) (he : 0<ε) (he1 : ε<1) (hd : 0≤δ) + (n : ℕ) (hn : wrapTime algorithmRealizer (encodeInput G ε δ)≤n) : + (∀ b : Bits n,∃ q : ℚ,0≤q ∧ Outputs mainProgram.machine (encodeInput G ε δ) b q) ∧ + (Z G=0→∀ b : Bits n,Outputs mainProgram.machine (encodeInput G ε δ) b 0) := by + constructor + · intro b + obtain ⟨hh,q,hq,ht,_⟩:=mainProgram_all G ε δ he he1 hd n hn b + exact ⟨q,hq,hh,ht⟩ + · intro hz b + obtain ⟨hh,q,_hq,ht,hzq⟩:=mainProgram_all G ε δ he he1 hd n hn b + rw [hzq hz] at ht + exact ⟨hh,ht⟩ +lemma average_good (A : RandomMachine) (G : GraphInput) (ε δ : ℚ) (n : ℕ) + (hh : ∀ b : Bits n,(MatchingFPRAS.run A (encodeInput G ε δ) b).state=none) : + average (fun b : Bits n=>if AccurateTape G ε (MatchingFPRAS.run A (encodeInput G ε δ) b).tape then 1 else 0)= + ((goodTapes A G ε δ n).card:ℚ)/(2:ℚ)^n := by + have he (b : Bits n) : AccurateTape G ε (MatchingFPRAS.run A (encodeInput G ε δ) b).tape ↔ + ∃ q : ℚ,Outputs A (encodeInput G ε δ) b q ∧ (1-ε)*(Z G:ℚ)≤q ∧ q≤(1+ε)*(Z G:ℚ) := by + constructor + · rintro ⟨q,ht,hq⟩;exact ⟨q,⟨hh b,ht⟩,hq⟩ + · rintro ⟨q,⟨_,ht⟩,hq⟩;exact ⟨q,ht,hq⟩ + simp_rw [he] + simp only [average,goodTapes,Finset.sum_boole] +lemma mainProgram_success (G : GraphInput) (ε δ : ℚ) (he : 0<ε) (he1 : ε<1) (hd : 0<δ) + (n : ℕ) (hn : wrapTime algorithmRealizer (encodeInput G ε δ)≤n) : + 1-δ≤((goodTapes mainProgram.machine G ε δ n).card:ℚ)/(2:ℚ)^n := by + have hs : 1-δ≤(algorithm (encodeInput G ε δ)).mean + (fun as=>if AccurateTape G ε (Tape.mk₁ as) then 1 else 0) := by + apply (algorithm_success G ε δ he he1 hd).trans (Experiment.mean_mono _ _ _ ?_) + exact (Experiment.all_true _).mono (by + intro as _ + by_cases h : AccurateWord G ε as + · simp only [ite_eq_left h,ite_eq_left (accurateTape_of_word G ε as h),le_refl] + · simp only [ite_eq_right h];split_ifs <;> norm_num) + have hm:=(mainProgram_realizes G ε δ).run_mean (fun T=>if AccurateTape G ε T then 1 else 0) n hn + rw [Experiment.mean_map] at hm + rw [←hm,average_good mainProgram.machine G ε δ n + (fun b=>(mainProgram_all G ε δ he he1 hd.le n hn b).1)] at hs + exact hs +end MatchingFPRAS.LiteralPhysical + +end OAI diff --git a/lean/OAI/Combinatorics/MatchingCount/Probability/Marking.lean b/lean/OAI/Combinatorics/MatchingCount/Probability/Marking.lean new file mode 100644 index 0000000000000000000000000000000000000000..af9cdedeadf301b7c62e30d6f537382cc7d4a5f2 --- /dev/null +++ b/lean/OAI/Combinatorics/MatchingCount/Probability/Marking.lean @@ -0,0 +1,127 @@ +import Mathlib +import OAI.Combinatorics.MatchingCount.Probability.AdaptiveLaw +import OAI.Combinatorics.MatchingCount.Graphs.LabelOrder +import OAI.Combinatorics.MatchingCount.Sampling.TableMarking + +namespace OAI + +namespace MatchingFPRAS.Variation +lemma imageLaw_instances {A B : Type*} (F₁ F₂ : Fintype A) (f : A → B) : + @imageLaw A B F₁ f=@imageLaw A B F₂ f := by + cases Subsingleton.elim F₁ F₂ + rfl +lemma tv_instances {A : Type*} (F₁ F₂ : Fintype A) (p q : A → ℝ) : + @tv A F₁ p q=@tv A F₂ p q := by + cases Subsingleton.elim F₁ F₂ + rfl +end MatchingFPRAS.Variation +namespace MatchingFPRAS.RationalSource +open Finset Transport Variation Enlargement + +variable {V : Type*} [Fintype V] [LinearOrder V] [Nontrivial V] +attribute [local instance] NumberedHierarchy.labelOrder sym2Order bagEdgeOrder bagEdgeFintype +attribute [local instance] UnitRefresh.Computable.allowedDec prodOrder sumOrder +noncomputable local instance (w : V → V → ℚ) (K : ℕ) : DecidableEq (BagPM (bags w K)) := Classical.decEq _ +noncomputable local instance (w : V → V → ℚ) (K : ℕ) : Fintype (BagPM (bags w K)) := Fintype.ofFinite _ + +def centralEdge (w : V → V → ℚ) (K : ℕ) (e : LogicalEdge V) : BagEdge (bags w K) := + coloredReal w K (e,⟨2*(2*K+2),by omega⟩) +def probePortion (w : V → V → ℚ) (K D : ℕ) (e : BagEdge (bags w K)) : ℚ := + if ∃ q,centralEdge w K q=e then 1/(D:ℚ) else 0 +def portions (w : V → V → ℚ) (K D : ℕ) (e : BagEdge (bags w K)) : Fin 3 → ℚ := + ![realPortion w K e,bagHeight w K e.color/D-probePortion w K D e,probePortion w K D e] +lemma portions_sum (w : V → V → ℚ) (K D : ℕ) (e : BagEdge (bags w K)) : + ∑ i,portions w K D e i=bagWeight w K D e := by + simp [portions,Fin.sum_univ_succ,bagWeight] +lemma portions_nonneg (w : V → V → ℚ) (hw : ∀ x y,0 positivity +lemma bagWeight_pos (w : V → V → ℚ) (hw : ∀ x y,0(bagWeight w K D e:ℝ))) + (fun M=>product (fun e : M.val=>fun i=>(portions w K D e.val i/bagWeight w K D e.val:ℚ))) + +def markedSampler (w : V → V → ℚ) (hw : ∀ x y,0(bagWeight w K D e:ℝ)))+ + 6*Fintype.card (BagEdge (bags w K))/(2:ℝ)^k := by + have he : TableMarking.law BagEdge.Incident (fun e=>(bagWeight w K D e:ℝ)) + (markingTable w hw K D hD)=markedLaw w K D := by + unfold TableMarking.law TableMarking.portion markedLaw + simp only [markingTable_law] + have hh:=TableMarking.draw_tv_size BagEdge.Incident f + (fun e=>(bagWeight w K D e:ℝ)) (markingTable w hw K D hD) k 3 (fun _=>rfl) + rw [he] at hh + norm_num only [Nat.cast_ofNat] at hh + rw [imageLaw_instances _ (sourceMarkingBitsFintype w K k), + tv_instances _ (sourceMarkedFintype w K)] at hh + exact hh + +noncomputable def markedSamplerLaw (w : V → V → ℚ) (hw : ∀ x y,0 mean p f)) (f-(fun _ => mean p f)) + +lemma mean_dot (f : (I → Ω) → ℝ) : mean p f = dot p (fun _ => 1) f := by simp [mean,dot] + +lemma density_sum (hs : ∀ i, ∑ a, p i a = 1) : ∑ s, density p s = 1 := by + unfold density + rw [← Fintype.prod_sum] + simp_rw [hs] + simp + +lemma mean_average (hs : ∀ i, ∑ a, p i a = 1) (i : I) (f : (I → Ω) → ℝ) : + mean p (average p i f) = mean p f := by + rw [mean_dot, ← average_adjoint] + have ho : average p i (fun _ => 1) = (fun _ => 1) := by + funext s; simpa [average_apply] using hs i + rw [ho, ← mean_dot] + +lemma mean_avgList (hs : ∀ i, ∑ a, p i a = 1) (l : List I) (f : (I → Ω) → ℝ) : + mean p (avgList p l f) = mean p f := by + induction l with + | nil => rfl + | cons i l ih => rw [avgList_cons,mean_average p hs,ih] + +omit [Fintype I] in +lemma average_update (i : I) (a : Ω) (f : (I → Ω) → ℝ) (s : I → Ω) : + average p i f (Function.update s i a) = average p i f s := by + simp only [average_apply,Function.update_idem] + +lemma invariant_constant (f : (I → Ω) → ℝ) (hf : ∀ i, average p i f = f) + (s t : I → Ω) : f s = f t := by + classical + have hu (i : I) (a : Ω) (s : I → Ω) : f (Function.update s i a) = f s := by + rw [← hf i] + exact average_update p i a f s + have hpatch (S : Finset I) : f (fun i => if i ∈ S then t i else s i) = f s := by + induction S using Finset.induction_on with + | empty => simp + | @insert i S hi ih => + have he : (fun j => if j ∈ insert i S then t j else s j) = + Function.update (fun j => if j ∈ S then t j else s j) i (t i) := by + funext j + by_cases hji : j = i + · subst j; simp + · simp [hji] + rw [he,hu,ih] + simpa using (hpatch Finset.univ).symm + +lemma average_all (hs : ∀ i, ∑ a, p i a = 1) (l : List I) (hl : ∀ i, i ∈ l) + (f : (I → Ω) → ℝ) : avgList p l f = (fun _ => mean p f) := by + funext s + have hc : ∀ t, avgList p l f t = avgList p l f s := fun t => + invariant_constant p (avgList p l f) (fun i => average_list_mem p hs l i (hl i) f) t s + have hm := mean_avgList p hs l f + unfold mean at hm + simp_rw [hc] at hm + rw [← Finset.sum_mul,density_sum p hs,one_mul] at hm + exact hm + +omit [Fintype I] in +lemma avgList_fixed (l : List I) (f : (I → Ω) → ℝ) + (hf : ∀ i ∈ l, average p i f = f) : avgList p l f = f := by + induction l with + | nil => rfl + | cons i l ih => + rw [avgList_cons,ih (fun j hj => hf j (List.mem_cons_of_mem i hj)),hf i (List.mem_cons_self)] + +omit [Fintype I] in +lemma avgList_comm_list (l k : List I) (f : (I → Ω) → ℝ) : + avgList p l (avgList p k f) = avgList p k (avgList p l f) := by + induction l with + | nil => rfl + | cons i l ih => rw [avgList_cons,ih,average_comm_list,avgList_cons] + +omit [Fintype I] in +lemma avgList_congr (hs : ∀ i, ∑ a, p i a = 1) (l k : List I) + (hmem : ∀ i, i ∈ l ↔ i ∈ k) (f : (I → Ω) → ℝ) : avgList p l f = avgList p k f := by + have h₁ : avgList p l (avgList p k f) = avgList p k f := + avgList_fixed p l _ (fun i hi => average_list_mem p hs k i ((hmem i).mp hi) f) + have h₂ : avgList p k (avgList p l f) = avgList p l f := + avgList_fixed p k _ (fun i hi => average_list_mem p hs l i ((hmem i).mpr hi) f) + rw [avgList_comm_list,h₂] at h₁ + exact h₁ + +lemma projection_pythagoras (P : Projection p) (f : (I → Ω) → ℝ) : + dot p (f-P.op f) (f-P.op f) = dot p f f-dot p (P.op f) (P.op f) := by + rw [dot_sub_left p f (P.op f) (f-P.op f),dot_sub_right p f f (P.op f), + dot_sub_right p (P.op f) f (P.op f),dot_comm p (P.op f) f,P.dot_image] + ring + +end + +section + +open Finset + +variable {I Ω : Type*} [Fintype I] [DecidableEq I] [LinearOrder I] + [Fintype Ω] + +variable (p : I → Ω → ℝ) + +noncomputable def future (S : Finset I) (x : I) := avgList p ((S.filter (x < ·)).toList) + +noncomputable def increment (S : Finset I) (x : I) (f : (I → Ω) → ℝ) : (I → Ω) → ℝ := + future p S x f-average p x (future p S x f) + +lemma martingale_partial (hs : ∀ i, ∑ a, p i a = 1) (S : Finset I) (f : (I → Ω) → ℝ) : + (∑ x ∈ S, dot p (increment p S x f) (increment p S x f)) = + dot p f f-dot p (avgList p S.toList f) (avgList p S.toList f) := by + classical + induction S using Finset.induction_on_min with + | empty => simp [future,increment,avgList] + | insert a S hmin ih => + have ha : a ∉ S := fun h => (lt_irrefl a) (hmin a h) + have hfilter : (insert a S).filter (a < ·) = S := by + ext i + simp only [Finset.mem_filter,Finset.mem_insert] + constructor + · rintro ⟨hi,hai⟩; rcases hi with rfl | hi + · exact (lt_irrefl _ hai).elim + · exact hi + · intro hi; exact ⟨Or.inr hi,hmin i hi⟩ + have hother (x) (hx : x ∈ S) : (insert a S).filter (x < ·) = S.filter (x < ·) := by + ext i + simp only [Finset.mem_filter,Finset.mem_insert] + constructor + · rintro ⟨hi,hxi⟩; rcases hi with rfl | hi + · exact (not_lt_of_gt (hmin x hx) hxi).elim + · exact ⟨hi,hxi⟩ + · rintro ⟨hi,hxi⟩; exact ⟨Or.inr hi,hxi⟩ + have hc : avgList p (insert a S).toList f = average p a (avgList p S.toList f) := by + change avgList p (insert a S).toList f = avgList p (a::S.toList) f + apply avgList_congr p hs + intro i; simp + rw [Finset.sum_insert ha,hc] + have hsum : (∑ x ∈ S, dot p (increment p (insert a S) x f) + (increment p (insert a S) x f)) = ∑ x ∈ S, dot p (increment p S x f) (increment p S x f) := by + apply Finset.sum_congr rfl + intro x hx + simp only [increment,future,hother x hx] + rw [hsum,ih] + have hp := projection_pythagoras p (avgProjection p hs a) (avgList p S.toList f) + change dot p (increment p (insert a S) a f) (increment p (insert a S) a f) + _ = _ + unfold increment future + rw [hfilter] + change dot p (avgList p S.toList f-average p a (avgList p S.toList f)) + (avgList p S.toList f-average p a (avgList p S.toList f)) = + dot p (avgList p S.toList f) (avgList p S.toList f)- + dot p (average p a (avgList p S.toList f)) (average p a (avgList p S.toList f)) at hp + linarith + +lemma martingale_variance (hs : ∀ i, ∑ a, p i a = 1) (f : (I → Ω) → ℝ) : + variance p f = ∑ x, dot p (increment p Finset.univ x f) (increment p Finset.univ x f) := by + rw [martingale_partial p hs] + have hp := projection_pythagoras p (listProjection p hs Finset.univ.toList) f + change dot p (f-avgList p Finset.univ.toList f) (f-avgList p Finset.univ.toList f) = + dot p f f-dot p (avgList p Finset.univ.toList f) (avgList p Finset.univ.toList f) at hp + rw [average_all p hs Finset.univ.toList (by simp)] at hp ⊢ + exact hp + +omit [Fintype I] in +lemma increment_center (hs : ∀ i, ∑ a, p i a = 1) (S : Finset I) (x : I) (f : (I → Ω) → ℝ) : + average p x (increment p S x f) = 0 := by + simp [increment,map_sub,average_idem p hs] + +lemma average_pair_future (hs : ∀ i, ∑ a, p i a = 1) (x y : I) (hxy : x < y) + (f : (I → Ω) → ℝ) : average p y (pairCondition p x y f) = future p Finset.univ x f := by + change avgList p (y::outside x y) f = avgList p ((Finset.univ.filter (x < ·)).toList) f + apply avgList_congr p hs + intro i + simp only [List.mem_cons,Finset.mem_toList,Finset.mem_filter,Finset.mem_univ,true_and,outside] + constructor + · rintro (rfl | ⟨hi,_⟩) + · exact hxy + · exact hi + · intro hi + by_cases hiy : i=y + · exact Or.inl hiy + · exact Or.inr ⟨hi,hiy⟩ + +lemma increment_pair_formula (hs : ∀ i, ∑ a, p i a = 1) (x y : I) (hxy : x < y) + (f : (I → Ω) → ℝ) : increment p Finset.univ x f = + average p y (pairCondition p x y f)-average p x (average p y (pairCondition p x y f)) := by + rw [average_pair_future p hs x y hxy] + rfl + +end + +section + +open Finset + +variable {Ω A : Type*} [Fintype Ω] [Fintype A] + +noncomputable def localEnergy (q : Ω → Ω → ℝ) (f : Ω → ℝ) : ℝ := + (∑ a, ∑ b, q a b * (f a-f b)^2)/2 + +lemma localEnergy_nonneg (q : Ω → Ω → ℝ) (hq : ∀ a b, 0 ≤ q a b) (f : Ω → ℝ) : + 0 ≤ localEnergy q f := by + exact div_nonneg (Finset.sum_nonneg (fun a _ => Finset.sum_nonneg + (fun b _ => mul_nonneg (hq a b) (sq_nonneg _)))) (by norm_num) + +lemma localEnergy_sub (q : Ω → Ω → ℝ) (hq : ∀ a b, 0 ≤ q a b) (f g : Ω → ℝ) : + localEnergy q (f-g) ≤ 2*localEnergy q f+2*localEnergy q g := by + unfold localEnergy + have h : (∑ a, ∑ b, q a b*((f-g) a-(f-g) b)^2) ≤ + ∑ a, ∑ b, (2*(q a b*(f a-f b)^2)+2*(q a b*(g a-g b)^2)) := by + apply Finset.sum_le_sum; intro a _ + apply Finset.sum_le_sum; intro b _ + have hsq : ((f a-g a)-(f b-g b))^2 ≤ 2*(f a-f b)^2+2*(g a-g b)^2 := by + nlinarith [sq_nonneg ((f a-f b)+(g a-g b))] + change q a b*((f a-g a)-(f b-g b))^2 ≤ _ + calc + _ ≤ q a b*(2*(f a-f b)^2+2*(g a-g b)^2) := mul_le_mul_of_nonneg_left hsq (hq a b) + _ = _ := by ring + simp only [Finset.sum_add_distrib,← Finset.mul_sum] at h + linarith + +lemma localEnergy_shift (q : Ω → Ω → ℝ) (f : Ω → ℝ) (c : ℝ) : + localEnergy q (fun a => f a-c) = localEnergy q f := by + unfold localEnergy + congr 1 + apply Finset.sum_congr rfl; intro a _ + apply Finset.sum_congr rfl; intro b _ + congr 2; ring + +lemma square_average (w : A → ℝ) (hw : ∀ a, 0 ≤ w a) (hs : ∑ a, w a = 1) (f : A → ℝ) : + (∑ a, w a*f a)^2 ≤ ∑ a, w a*(f a)^2 := by + have h := Finset.sum_sq_le_sum_mul_sum_of_sq_le_mul Finset.univ + (r := fun a => w a*f a) (f := w) (g := fun a => w a*(f a)^2) + (fun a _ => hw a) (fun a _ => mul_nonneg (hw a) (sq_nonneg _)) + (fun a _ => by nlinarith [sq_nonneg (w a*f a)]) + simpa only [hs,one_mul] using h + +lemma localEnergy_average (q : Ω → Ω → ℝ) (hq : ∀ a b, 0 ≤ q a b) + (w : A → ℝ) (hw : ∀ a, 0 ≤ w a) (hs : ∑ a, w a = 1) (f : A → Ω → ℝ) : + localEnergy q (fun a => ∑ i, w i*f i a) ≤ ∑ i, w i*localEnergy q (f i) := by + have h : (∑ a, ∑ b, q a b*((∑ i, w i*f i a)-(∑ i, w i*f i b))^2) ≤ + ∑ a, ∑ b, q a b*(∑ i, w i*(f i a-f i b)^2) := by + apply Finset.sum_le_sum; intro a _ + apply Finset.sum_le_sum; intro b _ + apply mul_le_mul_of_nonneg_left _ (hq a b) + simpa only [mul_sub,Finset.sum_sub_distrib] using square_average w hw hs (fun i => f i a-f i b) + have he : (∑ a, ∑ b, q a b*(∑ i, w i*(f i a-f i b)^2)) = + ∑ i, w i*(∑ a, ∑ b, q a b*(f i a-f i b)^2) := by + simp only [Finset.mul_sum] + have hin (a : Ω) : (∑ b, ∑ i, q a b*(w i*(f i a-f i b)^2)) = + ∑ i, ∑ b, q a b*(w i*(f i a-f i b)^2) := Finset.sum_comm + simp_rw [hin] + rw [Finset.sum_comm] + apply Finset.sum_congr rfl; intro i _ + apply Finset.sum_congr rfl; intro a _ + apply Finset.sum_congr rfl; intro b _ + ring + unfold localEnergy + rw [he] at h + have := div_le_div_of_nonneg_right h (by norm_num : (0:ℝ) ≤ 2) + simpa only [Finset.sum_div,mul_div_assoc] using this + +lemma localEnergy_bound (π : Ω → ℝ) (q : Ω → Ω → ℝ) (hq : ∀ a b, 0 ≤ q a b) + (hr : ∀ a, ∑ b, q a b = π a) (hc : ∀ b, ∑ a, q a b = π b) (f : Ω → ℝ) : + localEnergy q f ≤ 2*∑ a, π a*(f a)^2 := by + have hh : (∑ a, ∑ b, q a b*(f a-f b)^2) ≤ + ∑ a, ∑ b, (2*(q a b*(f a)^2)+2*(q a b*(f b)^2)) := by + apply Finset.sum_le_sum; intro a _ + apply Finset.sum_le_sum; intro b _ + have hs : (f a-f b)^2 ≤ 2*(f a)^2+2*(f b)^2 := by nlinarith [sq_nonneg (f a+f b)] + calc + _ ≤ q a b * (2 * (f a)^2 + 2 * (f b)^2) := + mul_le_mul_of_nonneg_left hs (hq a b) + _ = _ := by ring + have hleft : (∑ a, ∑ b, q a b*(f a)^2) = ∑ a, π a*(f a)^2 := by + simp only [← Finset.sum_mul,hr] + have hright : (∑ a, ∑ b, q a b*(f b)^2) = ∑ b, π b*(f b)^2 := by + rw [Finset.sum_comm] + simp only [← Finset.sum_mul,hc] + simp only [Finset.sum_add_distrib,← Finset.mul_sum,hleft,hright] at hh + unfold localEnergy; linarith + +end + +open Finset + +variable {I Ω : Type*} [Fintype I] [DecidableEq I] [Fintype Ω] + +variable (p : I → Ω → ℝ) + +omit [DecidableEq I] [Fintype Ω] in +lemma density_nonneg (hp : ∀ i a, 0 ≤ p i a) (s : I → Ω) : 0 ≤ density p s := + Finset.prod_nonneg (fun i _ => hp i (s i)) + +lemma mean_mono (hp : ∀ i a, 0 ≤ p i a) {f g : (I → Ω) → ℝ} + (h : ∀ s, f s ≤ g s) : mean p f ≤ mean p g := + Finset.sum_le_sum (fun s _ => mul_le_mul_of_nonneg_left (h s) (density_nonneg p hp s)) + +lemma mean_nonneg (hp : ∀ i a, 0 ≤ p i a) {f : (I → Ω) → ℝ} (h : ∀ s, 0 ≤ f s) : + 0 ≤ mean p f := Finset.sum_nonneg (fun s _ => mul_nonneg (density_nonneg p hp s) (h s)) + +lemma mean_add (f g : (I → Ω) → ℝ) : mean p (f+g) = mean p f+mean p g := by + simp [mean,mul_add,Finset.sum_add_distrib] + +lemma mean_mul (c : ℝ) (f : (I → Ω) → ℝ) : mean p (fun s => c*f s) = c*mean p f := by + simp only [mean,Finset.mul_sum]; apply Finset.sum_congr rfl; intro s _; ring + +lemma mean_square (f : (I → Ω) → ℝ) : mean p (fun s => (f s)^2) = dot p f f := by + simp only [mean,dot]; apply Finset.sum_congr rfl; intro s _; ring + +structure PairCapacity (x y : I) where + q : (Ω × Ω) → (Ω × Ω) → ℝ + nonneg : ∀ a b, 0 ≤ q a b + row : ∀ a, ∑ b, q a b = p x a.1*p y a.2 + col : ∀ b, ∑ a, q a b = p x b.1*p y b.2 + +def replacePair (x y : I) (s : I → Ω) (a : Ω × Ω) : I → Ω := + Function.update (Function.update s x a.1) y a.2 + +def slice (x y : I) (f : (I → Ω) → ℝ) (s : I → Ω) (a : Ω × Ω) : ℝ := + f (replacePair x y s a) + +noncomputable def pairEnergy (x y : I) (Q : PairCapacity p x y) (f : (I → Ω) → ℝ) : ℝ := + mean p (fun s => localEnergy Q.q (slice x y f s)) + +omit [Fintype I] [Fintype Ω] in +lemma slice_sub (x y : I) (f g : (I → Ω) → ℝ) (s : I → Ω) : + slice x y (f-g) s = slice x y f s-slice x y g s := rfl + +lemma pairEnergy_nonneg (hp : ∀ i a, 0 ≤ p i a) (x y : I) (Q : PairCapacity p x y) + (f : (I → Ω) → ℝ) : 0 ≤ pairEnergy p x y Q f := + mean_nonneg p hp (fun _ => localEnergy_nonneg Q.q Q.nonneg _) + +lemma pairEnergy_sub (hp : ∀ i a, 0 ≤ p i a) (x y : I) (Q : PairCapacity p x y) + (f g : (I → Ω) → ℝ) : pairEnergy p x y Q (f-g) ≤ + 2*pairEnergy p x y Q f+2*pairEnergy p x y Q g := by + have hh := mean_mono p hp (fun s => localEnergy_sub Q.q Q.nonneg (slice x y f s) (slice x y g s)) + change mean p (fun s => localEnergy Q.q (slice x y (f-g) s)) ≤ + mean p ((fun s => 2*localEnergy Q.q (slice x y f s))+(fun s => 2*localEnergy Q.q (slice x y g s))) at hh + rw [mean_add,mean_mul,mean_mul] at hh + exact hh + +lemma slice_square_mean (hs : ∀ i, ∑ a, p i a = 1) (x y : I) (f : (I → Ω) → ℝ) : + mean p (fun s => ∑ a : Ω × Ω, (p x a.1*p y a.2)*(slice x y f s a)^2) = dot p f f := by + have he (s : I → Ω) : (∑ a : Ω × Ω, (p x a.1*p y a.2)*(slice x y f s a)^2) = + average p x (average p y (fun s => (f s)^2)) s := by + rw [Fintype.sum_prod_type] + simp only [average_apply,Finset.mul_sum] + apply Finset.sum_congr rfl; intro a _ + apply Finset.sum_congr rfl; intro b _ + unfold slice replacePair; ring + simp_rw [he] + rw [mean_average p hs,mean_average p hs,mean_square] + +lemma pairEnergy_bound (hp : ∀ i a, 0 ≤ p i a) (hs : ∀ i, ∑ a, p i a = 1) + (x y : I) (Q : PairCapacity p x y) (f : (I → Ω) → ℝ) : + pairEnergy p x y Q f ≤ 2*dot p f f := by + have hh := mean_mono p hp (fun s => localEnergy_bound (fun a => p x a.1*p y a.2) + Q.q Q.nonneg Q.row Q.col (slice x y f s)) + rw [mean_mul,slice_square_mean p hs] at hh + exact hh + +omit [Fintype I] [Fintype Ω] in +lemma replacePair_update (i x y : I) (hix : i ≠ x) (hiy : i ≠ y) + (s : I → Ω) (a : Ω × Ω) (b : Ω) : + replacePair x y (Function.update s i b) a = Function.update (replacePair x y s a) i b := by + unfold replacePair + rw [Function.update_comm hix,Function.update_comm hiy] + +omit [Fintype I] in +lemma slice_average (i x y : I) (hix : i ≠ x) (hiy : i ≠ y) + (f : (I → Ω) → ℝ) (s : I → Ω) : + slice x y (average p i f) s = (fun a => ∑ b, p i b*slice x y f (Function.update s i b) a) := by + funext a + simp only [slice,average_apply,replacePair_update i x y hix hiy] + +lemma pairEnergy_average (hp : ∀ i a, 0 ≤ p i a) (hs : ∀ i, ∑ a, p i a = 1) + (i x y : I) (hix : i ≠ x) (hiy : i ≠ y) (Q : PairCapacity p x y) (f : (I → Ω) → ℝ) : + pairEnergy p x y Q (average p i f) ≤ pairEnergy p x y Q f := by + have hh (s : I → Ω) : localEnergy Q.q (slice x y (average p i f) s) ≤ + average p i (fun s => localEnergy Q.q (slice x y f s)) s := by + rw [slice_average p i x y hix hiy] + exact localEnergy_average Q.q Q.nonneg (p i) (hp i) (hs i) (fun b => slice x y f (Function.update s i b)) + have hh := mean_mono p hp hh + rw [mean_average p hs] at hh + exact hh + +lemma pairEnergy_avgList (hp : ∀ i a, 0 ≤ p i a) (hs : ∀ i, ∑ a, p i a = 1) + (l : List I) (x y : I) (hl : ∀ i ∈ l, i ≠ x ∧ i ≠ y) (Q : PairCapacity p x y) + (f : (I → Ω) → ℝ) : pairEnergy p x y Q (avgList p l f) ≤ pairEnergy p x y Q f := by + induction l with + | nil => exact le_rfl + | cons i l ih => + rw [avgList_cons] + exact (pairEnergy_average p hp hs i x y (hl i (by simp)).1 (hl i (by simp)).2 Q _).trans + (ih (fun j hj => hl j (List.mem_cons_of_mem i hj))) + +end MatchingFPRAS.Replica + +end OAI diff --git a/lean/OAI/Combinatorics/MatchingCount/Probability/OnlineLawBridge.lean b/lean/OAI/Combinatorics/MatchingCount/Probability/OnlineLawBridge.lean new file mode 100644 index 0000000000000000000000000000000000000000..223482e2d16d2fdb84a16fb406bbdb2342b24666 --- /dev/null +++ b/lean/OAI/Combinatorics/MatchingCount/Probability/OnlineLawBridge.lean @@ -0,0 +1,27 @@ +import Mathlib +import OAI.Combinatorics.MatchingCount.Machines.OnlineUniform + +namespace OAI + +namespace MatchingFPRAS.PhysicalStream +open Finset Variation + +variable {A B C : Type} [Fintype A] [Fintype B] [Fintype C] +lemma qaverage_imageLaw (f : A→B) (h : B→ℚ) : + ((qaverage (fun a=>h (f a)) : ℚ):ℝ)=∑ b,imageLaw f b*(h b:ℝ) := by + classical + unfold imageLaw push uniform + simp only [sum_mul,ite_mul,zero_mul] + rw [sum_comm] + simp only [sum_ite_eq,mem_univ,ite_true,one_div,inv_mul_eq_div] + unfold qaverage + push_cast + rw [sum_div] +lemma qaverage_eq_of_imageLaw_eq (f : A→C) (g : B→C) + (he : imageLaw f=imageLaw g) (h : C→ℚ) : + qaverage (fun a=>h (f a))=qaverage (fun b=>h (g b)) := by + apply Rat.cast_injective (α:=ℝ) + rw [qaverage_imageLaw,qaverage_imageLaw,he] +end MatchingFPRAS.PhysicalStream + +end OAI diff --git a/lean/OAI/Combinatorics/MatchingCount/Probability/OnlineLayerLaw.lean b/lean/OAI/Combinatorics/MatchingCount/Probability/OnlineLayerLaw.lean new file mode 100644 index 0000000000000000000000000000000000000000..71197281d6ec970512e346c48e376d998fc51177 --- /dev/null +++ b/lean/OAI/Combinatorics/MatchingCount/Probability/OnlineLayerLaw.lean @@ -0,0 +1,60 @@ +import Mathlib +import OAI.Combinatorics.MatchingCount.Algorithm.OutputLengthBound +import OAI.Combinatorics.MatchingCount.Algorithm.TreeWeights +import OAI.Combinatorics.MatchingCount.Machines.OnlineUniform + +namespace OAI + +namespace MatchingFPRAS.PhysicalStream +lemma qaverage_const {A : Type} [Fintype A] [Nonempty A] (q : ℚ) : + qaverage (fun _ : A=>q)=q := by + simp only [qaverage,Finset.sum_const,Finset.card_univ,nsmul_eq_mul] + have h : (Fintype.card A:ℚ)≠0 := by exact_mod_cast Fintype.card_ne_zero + field_simp +end MatchingFPRAS.PhysicalStream + +namespace MatchingFPRAS.OnlineTrial +open PhysicalStream TreeTyped TreeFraction ExecutableSource ExecutableScaling Transport UnitRefresh Enlargement + +attribute [local instance] NumberedHierarchy.labelOrder +attribute [local instance] Transport.sym2Order Transport.bagEdgeOrder Transport.bagEdgeFintype +attribute [local instance] UnitRefresh.Computable.allowedDec Transport.prodOrder Transport.sumOrder +variable {G : GraphInput} [Nontrivial (Fin G.n)] + +lemma mean_drawAppend (p : Trial.Parameters G) {j : ℕ} (hj : j≤p.K) + (L : FiniteTrial.Layer p j) {a : ℕ} (f : (Fin a→Bool)→L.Ω) + (h : (L.append p hj).Ω→ℚ) : + qaverage (fun b=>h (L.drawAppend p hj f b))= + qaverage (fun c=>qaverage (fun b=>h ⟨f c,(L.state (f c)).drawStage p hj b⟩)) := by + change qaverage ((fun c : (Fin a→Bool)×(Fin (FiniteTrial.stageBits p)→Bool)=> + h ⟨f c.1,(L.state (f c.1)).drawStage p hj c.2⟩) ∘ pairBitsEquiv a (FiniteTrial.stageBits p))=_ + rw [qaverage_equiv,qaverage_prod] + +lemma mean_layer_succ (p : Trial.Parameters G) {j : ℕ} (hj : j+1≤p.K) + (h : (FiniteTrial.layers p (j+1) hj).Ω→ℚ) : + qaverage (fun b=>h (FiniteTrial.drawLayer p (j+1) hj b))= + qaverage (fun a=>qaverage (fun b=>h + ⟨FiniteTrial.drawLayer p j (by omega) a, + ((FiniteTrial.layers p j (by omega)).state (FiniteTrial.drawLayer p j (by omega) a)).drawStage p (by omega) b⟩)) := by + change qaverage ((fun b=>h ((FiniteTrial.layers p j (by omega)).drawAppend p (by omega) + (FiniteTrial.drawLayer p j (by omega)) b)) ∘ FiniteTrial.successorBitsEquiv j (FiniteTrial.stageBits p))=_ + rw [qaverage_equiv] + exact mean_drawAppend p (by omega) (FiniteTrial.layers p j (by omega)) + (FiniteTrial.drawLayer p j (by omega)) h + +noncomputable def product {j : ℕ} (p : Trial.Parameters G) (L : FiniteTrial.Layer p j) (x : L.Ω) : ℚ := + (Z (completeGraph G.n):ℚ)*∏ i,L.ratios x i +omit [Nontrivial (Fin G.n)] in +lemma product_nonneg [Nontrivial (Fin G.n)] {j : ℕ} (p : Trial.Parameters G) (L : FiniteTrial.Layer p j) (x : L.Ω) : + 0≤product p L x := mul_nonneg (Nat.cast_nonneg _) (Finset.prod_nonneg (fun i _=>L.ratios_nonneg x i)) +lemma product_append {j : ℕ} (p : Trial.Parameters G) (hj : j≤p.K) (L : FiniteTrial.Layer p j) + (x : (L.append p hj).Ω) : + product p (L.append p hj) x = product p L x.1 * + (L.state x.1).ratioEstimate (RationalSource.sourceMarkedEquiv (L.state x.1).activity p.K ∘ x.2) := by + unfold product FiniteTrial.Layer.append + dsimp only + rw [Fin.prod_snoc,mul_assoc] + +end MatchingFPRAS.OnlineTrial + +end OAI diff --git a/lean/OAI/Combinatorics/MatchingCount/Probability/OnlineSampleLaw.lean b/lean/OAI/Combinatorics/MatchingCount/Probability/OnlineSampleLaw.lean new file mode 100644 index 0000000000000000000000000000000000000000..b92c58823b20b985e02a5d726391736c564d0bb6 --- /dev/null +++ b/lean/OAI/Combinatorics/MatchingCount/Probability/OnlineSampleLaw.lean @@ -0,0 +1,63 @@ +import Mathlib +import OAI.Combinatorics.MatchingCount.Machines.OnlineUniform +import OAI.Combinatorics.MatchingCount.Sampling.OnlineSample + +namespace OAI + +namespace MatchingFPRAS.OnlineSample +open PhysicalStream + +abbrev LocalRandom (N k : ℕ) := Bits k × (Fin N → Bits k) +abbrev ScanRandom (N k : ℕ) := Bits k × LocalRandom N k +def localRep {N k : ℕ} (b : LocalRandom N k) : NumericLadder.Bits := + (List.ofFn b.1,List.ofFn (fun i=>List.ofFn (b.2 i))) +def scanRep {N k : ℕ} (b : ScanRandom N k) : List Bool×NumericLadder.Bits := + (List.ofFn b.1,localRep b.2) +lemma mean_words (k N : ℕ) (h : List (List Bool) → ℚ) : + (words (k,N)).mean h=qaverage (fun bs : Fin N → Bits k=>h (List.ofFn (fun i=>List.ofFn (bs i)))) := by + unfold words + rw [show List.replicate N k=List.ofFn (fun _ : Fin N=>k) by simp] + exact mean_traverse_ofFn word N (fun _=>k) (fun _ b=>List.ofFn b) (fun _=>mean_word_qaverage k) h +lemma mean_local (k N : ℕ) (h : NumericLadder.Bits → ℚ) : + (localWords (k,N)).mean h=qaverage (fun bs : LocalRandom N k=>h (localRep bs)) := by + simp only [localWords,Experiment.mean_bind,Experiment.mean_map,mean_words,mean_word_qaverage] + rw [qaverage_prod] + rfl +lemma mean_scan (k N : ℕ) (h : List Bool×NumericLadder.Bits → ℚ) : + (scan (k,N)).mean h=qaverage (fun bs : ScanRandom N k=>h (scanRep bs)) := by + simp only [scan,Experiment.mean_bind,Experiment.mean_map,mean_local,mean_word_qaverage] + rw [qaverage_prod] + rfl +lemma mean_scans (k N r : ℕ) (h : List (List Bool×NumericLadder.Bits) → ℚ) : + (scans ((k,N),r)).mean h=qaverage (fun bs : Fin r→ScanRandom N k=>h (List.ofFn (fun i=>scanRep (bs i)))) := by + unfold scans + rw [show List.replicate r (k,N)=List.ofFn (fun _ : Fin r=>(k,N)) by simp] + exact mean_traverse_ofFn scan r (fun _=>(k,N)) (fun _ b=>scanRep b) (fun _=>mean_scan k N) h +lemma mean_marks (km m : ℕ) (keys : Fin m→ℕ) (h : List (ℕ×List Bool) → ℚ) : + (marks (km,List.ofFn keys)).mean h= + qaverage (fun bs : Fin m→Bits km=>h (List.ofFn (fun i=>(keys i,List.ofFn (bs i))))) := by + simp only [marks,markRequests,List.map_ofFn] + apply mean_traverse_ofFn markWord m (fun i=>(keys i,km)) (fun i b=>(keys i,List.ofFn b)) + intro i h + simp only [markWord,Experiment.mean_map,mean_word_qaverage] + +abbrev Random (N k r m km : ℕ) := (Fin r→ScanRandom N k)×(Fin m→Bits km) +def sampleRep {N k r m km : ℕ} (keys : Fin m→ℕ) (bs : Random N k r m km) : NumericMarking.SampleBits := + (List.ofFn (fun i=>scanRep (bs.1 i)),List.ofFn (fun i=>(keys i,List.ofFn (bs.2 i)))) +lemma mean_sample (N k r m km : ℕ) (keys : Fin m→ℕ) (h : NumericMarking.SampleBits → ℚ) : + (sample (((k,N),r),(km,List.ofFn keys))).mean h= + qaverage (fun bs : Random N k r m km=>h (sampleRep keys bs)) := by + simp only [sample,Experiment.mean_bind,Experiment.mean_map,mean_marks,mean_scans] + rw [qaverage_prod] + rfl +lemma mean_many (S N k r m km : ℕ) (keys : Fin m→ℕ) (h : List NumericMarking.SampleBits → ℚ) : + (many (S,(((k,N),r),(km,List.ofFn keys)))).mean h= + qaverage (fun bs : Fin S→Random N k r m km=>h (List.ofFn (fun i=>sampleRep keys (bs i)))) := by + unfold many + rw [show List.replicate S (((k,N),r),(km,List.ofFn keys))= + List.ofFn (fun _ : Fin S=>(((k,N),r),(km,List.ofFn keys))) by simp] + exact mean_traverse_ofFn sample S (fun _=>(((k,N),r),(km,List.ofFn keys))) + (fun _ b=>sampleRep keys b) (fun _=>mean_sample N k r m km keys) h +end MatchingFPRAS.OnlineSample + +end OAI diff --git a/lean/OAI/Combinatorics/MatchingCount/Probability/Tv.lean b/lean/OAI/Combinatorics/MatchingCount/Probability/Tv.lean new file mode 100644 index 0000000000000000000000000000000000000000..1711193853113e0b7b68af2a92cefef0350203c1 --- /dev/null +++ b/lean/OAI/Combinatorics/MatchingCount/Probability/Tv.lean @@ -0,0 +1,453 @@ +import Mathlib +import OAI.Combinatorics.MatchingCount.Graphs.Marked + +namespace OAI + +namespace MatchingFPRAS.Variation + +open Finset +open scoped Classical + +variable {Ω Ψ : Type*} [Fintype Ω] [Fintype Ψ] + +noncomputable def tv (p q : Ω → ℝ) : ℝ := (∑ s,|p s-q s|)/2 + +lemma tv_nonneg (p q : Ω → ℝ) : 0 ≤ tv p q := by + unfold tv; positivity + +lemma tv_symm (p q : Ω → ℝ) : tv p q=tv q p := by + unfold tv + simp_rw [abs_sub_comm] + +lemma tv_triangle (p q r : Ω → ℝ) : tv p r ≤ tv p q+tv q r := by + unfold tv + rw [←add_div,←sum_add_distrib] + exact div_le_div_of_nonneg_right (sum_le_sum (fun s _ => abs_sub_le _ _ _)) (by norm_num) + +noncomputable def event (p : Ω → ℝ) (P : Ω → Prop) : ℝ := ∑ x,if P x then p x else 0 + +lemma event_nonneg (p : Ω → ℝ) (hp : ∀ x,0 ≤ p x) (P : Ω → Prop) : 0 ≤ event p P := by + unfold event; apply sum_nonneg; intro x _; split_ifs + · exact hp x + · exact le_rfl + +theorem event_sub_le (p q : Ω → ℝ) (hs : ∑ x,p x=∑ x,q x) (P : Ω → Prop) : + |event p P-event q P| ≤ tv p q := by + let A : Finset Ω := univ.filter P + have hz : ∑ x,(p x-q x)=0 := by rw [sum_sub_distrib,hs,sub_self] + have he : event p P-event q P=∑ x ∈ A,(p x-q x) := by + simp only [event,←sum_sub_distrib,A,sum_filter] + apply sum_congr rfl + intro x _ + split_ifs <;> simp + have hc : ∑ x ∈ Aᶜ,(p x-q x)= -(∑ x ∈ A,(p x-q x)) := by + have h := Finset.sum_add_sum_compl A (fun x => p x-q x) + rw [hz] at h + linarith + have ha := abs_sum_le_sum_abs (fun x => p x-q x) A + have hb := abs_sum_le_sum_abs (fun x => p x-q x) Aᶜ + rw [hc,abs_neg] at hb + have hab := Finset.sum_add_sum_compl A (fun x => |p x-q x|) + rw [he] + unfold tv + linarith + +noncomputable def bind (p : Ω → ℝ) (k : Ω → Ψ → ℝ) (y : Ψ) : ℝ := ∑ x,p x*k x y + +omit [Fintype Ψ] in +lemma bind_nonneg (p : Ω → ℝ) (k : Ω → Ψ → ℝ) + (hp : ∀ x,0 ≤ p x) (hk : ∀ x y,0 ≤ k x y) (y : Ψ) : 0 ≤ bind p k y := + sum_nonneg fun x _ => mul_nonneg (hp x) (hk x y) + +lemma bind_sum (p : Ω → ℝ) (k : Ω → Ψ → ℝ) (hs : ∑ x,p x=1) + (hk : ∀ x,∑ y,k x y=1) : ∑ y,bind p k y=1 := by + unfold bind + rw [sum_comm] + simp_rw [←mul_sum,hk,mul_one] + exact hs + +lemma bind_contraction (p q : Ω → ℝ) (k : Ω → Ψ → ℝ) + (hk : ∀ x y,0 ≤ k x y) (hs : ∀ x,∑ y,k x y=1) : + tv (bind p k) (bind q k) ≤ tv p q := by + unfold tv bind + apply div_le_div_of_nonneg_right _ (by norm_num) + calc + _ = ∑ y,|∑ x,(p x-q x)*k x y| := by simp only [sub_mul,sum_sub_distrib] + _ ≤ ∑ y,∑ x,|(p x-q x)*k x y| := sum_le_sum (fun y _ => abs_sum_le_sum_abs _ _) + _ = _ := by + rw [sum_comm] + simp_rw [abs_mul,abs_of_nonneg (hk _ _),←mul_sum,hs,mul_one] + +lemma bind_perturbation (p : Ω → ℝ) (k l : Ω → Ψ → ℝ) + (hp : ∀ x,0 ≤ p x) (hs : ∑ x,p x=1) (ε : ℝ) (he : ∀ x,tv (k x) (l x) ≤ ε) : + tv (bind p k) (bind p l) ≤ ε := by + unfold tv bind + have h : ∑ y,|∑ x,p x*k x y-∑ x,p x*l x y| ≤ 2*ε := by + calc + _ = ∑ y,|∑ x,p x*(k x y-l x y)| := by simp only [mul_sub,sum_sub_distrib] + _ ≤ ∑ y,∑ x,|p x*(k x y-l x y)| := sum_le_sum (fun y _ => abs_sum_le_sum_abs _ _) + _ = ∑ x,p x*(∑ y,|k x y-l x y|) := by + rw [sum_comm]; simp_rw [abs_mul,abs_of_nonneg (hp _),←mul_sum] + _ ≤ ∑ x,p x*(2*ε) := by + apply sum_le_sum + intro x _ + apply mul_le_mul_of_nonneg_left _ (hp x) + have hh := he x + unfold tv at hh + linarith + _ = _ := by rw [←sum_mul,hs,one_mul] + linarith + +noncomputable def push (p : Ω → ℝ) (f : Ω → Ψ) (y : Ψ) : ℝ := + ∑ x,if f x=y then p x else 0 + +omit [Fintype Ψ] in +lemma push_nonneg (p : Ω → ℝ) (hp : ∀ x,0 ≤ p x) (f : Ω → Ψ) (y : Ψ) : + 0 ≤ push p f y := by + unfold push; apply sum_nonneg; intro x _; split_ifs + · exact hp x + · exact le_rfl + +lemma push_sum (p : Ω → ℝ) (hs : ∑ x,p x=1) (f : Ω → Ψ) : ∑ y,push p f y=1 := by + unfold push; rw [sum_comm]; simpa using hs + +lemma push_contraction (p q : Ω → ℝ) (f : Ω → Ψ) : tv (push p f) (push q f) ≤ tv p q := by + have he (r : Ω → ℝ) : push r f=bind r (fun x y => if f x=y then 1 else 0) := by + funext y + simp only [push,bind,mul_ite,mul_one,mul_zero] + rw [he p,he q] + exact + bind_contraction p q (fun x y => if f x=y then 1 else 0) + (fun x y => by split_ifs <;> norm_num) (fun x => by simp) + +noncomputable def tensor (p : Ω → ℝ) (q : Ψ → ℝ) (x : Ω×Ψ) : ℝ := p x.1*q x.2 + +lemma tensor_tv (p q : Ω → ℝ) (r s : Ψ → ℝ) + (hp : ∀ x,0 ≤ p x) (hps : ∑ x,p x=1) (hs : ∀ y,0 ≤ s y) (hss : ∑ y,s y=1) : + tv (tensor p r) (tensor q s) ≤ tv p q+tv r s := by + have hv (x : Ω) (y : Ψ) : |p x*r y-q x*s y| ≤ p x*|r y-s y|+|p x-q x| *s y := by + have he : p x*r y-q x*s y=p x*(r y-s y)+(p x-q x)*s y := by ring + rw [he] + simpa only [abs_mul,abs_of_nonneg (hp x),abs_of_nonneg (hs y)] using abs_add_le (p x*(r y-s y)) ((p x-q x)*s y) + unfold tv tensor + rw [←add_div] + apply div_le_div_of_nonneg_right _ (by norm_num) + rw [Fintype.sum_prod_type] + calc + _ ≤ ∑ x,∑ y,(p x*|r y-s y|+|p x-q x| *s y) := sum_le_sum (fun x _ => sum_le_sum (fun y _ => hv x y)) + _ = _ := by simp_rw [sum_add_distrib,←mul_sum,hss,mul_one,←sum_mul,hps,one_mul]; ring + +lemma tv_equiv (e : Ω ≃ Ψ) (p q : Ψ → ℝ) : tv (p ∘ e) (q ∘ e)=tv p q := by + unfold tv + rw [←e.sum_comp (fun y => |p y-q y|)] + rfl + +noncomputable def iid (p : Ω → ℝ) (n : ℕ) (x : Fin n → Ω) : ℝ := ∏ i,p (x i) + +omit [Fintype Ω] in +lemma iid_nonneg (p : Ω → ℝ) (hp : ∀ x,0 ≤ p x) (n : ℕ) (x : Fin n → Ω) : 0 ≤ iid p n x := + prod_nonneg fun _ _ => hp _ + +lemma iid_sum (p : Ω → ℝ) (hs : ∑ x,p x=1) (n : ℕ) : ∑ x,iid p n x=1 := by + unfold iid + rw [←Fintype.prod_sum] + simp [hs] + +theorem iid_tv (p q : Ω → ℝ) (hp : ∀ x,0 ≤ p x) (hps : ∑ x,p x=1) + (hq : ∀ x,0 ≤ q x) (hqs : ∑ x,q x=1) (n : ℕ) : + tv (iid p n) (iid q n) ≤ n*tv p q := by + induction n with + | zero => simp [tv,iid] + | succ n ih => + let e : (Ω×(Fin n → Ω)) ≃ (Fin (n+1) → Ω) := Fin.consEquiv (fun _ : Fin (n+1) => Ω) + have hpE : iid p (n+1) ∘ e=tensor p (iid p n) := by + funext x + simp [iid,tensor,e,Fin.prod_univ_succ] + have hqE : iid q (n+1) ∘ e=tensor q (iid q n) := by + funext x + simp [iid,tensor,e,Fin.prod_univ_succ] + rw [←tv_equiv e,hpE,hqE] + have ht := tensor_tv p q (iid p n) (iid q n) hp hps (iid_nonneg q hq n) (iid_sum q hqs n) + push_cast + nlinarith + +section Product + +variable {I : Type*} [Fintype I] [DecidableEq I] + +noncomputable def product (p : I → Ω → ℝ) (x : I → Ω) : ℝ := ∏ i,p i (x i) + +lemma product_marginal (p : I → Ω → ℝ) (hs : ∀ i,∑ a,p i a=1) (j : I) : + push (product p) (fun x => x j)=p j := by + classical + funext y + let q : I → Ω → ℝ := fun i a => if i=j then (if a=y then p i a else 0) else p i a + have he (x : I → Ω) : (if x j=y then product p x else 0)=∏ i,q i (x i) := by + by_cases h : x j=y + · simp only [ite_eq_left h,product] + apply prod_congr rfl + intro i _ + by_cases hi : i=j + · subst i; simp [q,h] + · simp [q,hi] + · simp only [ite_eq_right h] + symm + apply prod_eq_zero (mem_univ j) + simp [q,h] + have hq (i : I) : ∑ a,q i a=if i=j then p j y else 1 := by + by_cases h : i=j + · subst i; simp [q] + · simp [q,h,hs i] + unfold push + simp_rw [he] + rw [←Fintype.prod_sum] + simp_rw [hq] + simp + +end Product + + +variable {B : Ω → Type*} [∀ a,Fintype (B a)] + +noncomputable def sigmaLift (p : Ω → ℝ) (k : ∀ a,B a → ℝ) (s : Sigma B) : ℝ := + p s.1*k s.1 s.2 + +omit [Fintype Ω] [∀ a,Fintype (B a)] in +lemma sigmaLift_nonneg (p : Ω → ℝ) (k : ∀ a,B a → ℝ) + (hp : ∀ a,0 ≤ p a) (hk : ∀ a b,0 ≤ k a b) (s : Sigma B) : 0 ≤ sigmaLift p k s := + mul_nonneg (hp _) (hk _ _) + +lemma sigmaLift_sum (p : Ω → ℝ) (k : ∀ a,B a → ℝ) + (hs : ∑ a,p a=1) (hk : ∀ a,∑ b,k a b=1) : ∑ s,sigmaLift p k s=1 := by + simp only [sigmaLift,Fintype.sum_sigma,←mul_sum,hk,mul_one,hs] + +lemma sigmaLift_tv (p q : Ω → ℝ) (k : ∀ a,B a → ℝ) + (hk : ∀ a b,0 ≤ k a b) (hs : ∀ a,∑ b,k a b=1) : + tv (sigmaLift p k) (sigmaLift q k)=tv p q := by + simp only [tv,sigmaLift,Fintype.sum_sigma,←sub_mul,abs_mul,abs_of_nonneg (hk _ _),←mul_sum,hs,mul_one] + + +end MatchingFPRAS.Variation + +namespace MatchingFPRAS.Transport + +def tierBound (N D K : ℕ) : ℕ := N^2*(Nat.clog 2 D+2*K+2) + +lemma base_block (N : ℕ) (hN : 0 max (D:ℝ) (3*4^K) ≤ (1+((N:ℝ)^2)⁻¹)^t) + ⟨tierBound N D K,tierBound_reaches N D K hN⟩ + +lemma ladderTier_le (N D K : ℕ) (hN : 0 simp only [walk]; split_ifs <;> norm_num + | succ n ih => exact sum_nonneg fun b _ => mul_nonneg (ih b) (div_nonneg (hC b a) (hp b).le) + +lemma walk_sum (π : Ω → ℝ) (hp : ∀ a,0<π a) (C : Ω → Ω → ℝ) + (hC : ∀ a,∑ b,C a b=π a) (z : Ω) (n : ℕ) : ∑ a,walk π C z n a=1 := by + induction n with + | zero => simp [walk] + | succ n ih => + simp only [walk,kernel] + rw [sum_comm] + simp_rw [←mul_sum,←sum_div,hC,div_self (hp _).ne',mul_one] + exact ih + +end MatchingFPRAS.FiniteChain + +namespace MatchingFPRAS.Transport + +open Finset MatchingFPRAS.Replica MatchingFPRAS.Replica.Ladder + +variable {V J : Type*} [Fintype V] [DecidableEq V] [Fintype J] [DecidableEq J] + +variable {bags : V → Finset J} + +noncomputable local instance : Fintype (BagEdge bags) := Fintype.ofFinite _ + +noncomputable local instance : DecidableEq (PM (BagEdge.Incident (bags := bags))) := Classical.decEq _ + +def topSlot (T q : ℕ) (hq : 0 x (topSlot T q hq))=slotLaw w (topSlot T q hq) := by + exact Variation.product_marginal (slotLaw w) (fun i => slotLaw_sum w i M) _ + +omit [DecidableEq V] [Fintype J] [DecidableEq J] in +lemma slotWeight_top (w : BagEdge bags → ℝ) (D K T q : ℕ) (hD : 0 sourceBag_tree_adjacent w K hK x a b ha hb) (sourceTree_isTree w K).2 wt T q + let p := Variation.push (MatchingFPRAS.FiniteChain.walk ν C z (ladderSteps N D K T ξ)) + (fun a => a (topSlot T q hq)) + Variation.tv (revealLaw w K D p) (sourceLaw w K D) ≤ ξ := by + dsimp only + let D := sourceD (V:=V) K + let N := Fintype.card (SourceVertex V K) + have hd : 0 a (topSlot T (ladderQ N D) hq))=gibbs (sourceBagWeight w K D) at hm + rw [←hm] + apply (Variation.push_contraction _ _ _).trans + exact source_ladder_sampling hn w hw K hK M₀ T z ξ hξ hξ1 + +end MatchingFPRAS.Enlargement + +end OAI diff --git a/lean/OAI/Combinatorics/MatchingCount/Probability/Variance.lean b/lean/OAI/Combinatorics/MatchingCount/Probability/Variance.lean new file mode 100644 index 0000000000000000000000000000000000000000..f87b1e83410ceaa9865b38769712c979c866ac51 --- /dev/null +++ b/lean/OAI/Combinatorics/MatchingCount/Probability/Variance.lean @@ -0,0 +1,401 @@ +import Mathlib +import OAI.Combinatorics.MatchingCount.Sampling.EndpointPair + +namespace OAI + +namespace MatchingFPRAS.Transport + +variable {V E : Type*} [Fintype V] [DecidableEq V] [Fintype E] [DecidableEq E] + +variable {inc : E → V → Prop} + +omit [DecidableEq V] [Fintype E] [DecidableEq E] in +lemma switch_denominator_bound (hinc : ∀ e, ∃ v, inc e v) (A : PM inc) : + 48 * (A.val.card.choose 2 : ℝ) ≤ 60 * (Fintype.card V : ℝ)^2 := by + have hm := A.card_le_vertices hinc + have hc : A.val.card.choose 2 ≤ (Fintype.card V)^2 := + (Nat.choose_le_pow _ _).trans (Nat.pow_le_pow_left hm 2) + have hc' : (A.val.card.choose 2 : ℝ) ≤ (Fintype.card V : ℝ)^2 := by exact_mod_cast hc + nlinarith [sq_nonneg (Fintype.card V : ℝ)] + +omit [DecidableEq V] in +lemma safe_switch_elementary (hinc : ∀ e, ∃ v, inc e v) + (w : E → ℝ) (hw : ∀ e, 0 < w e) (K : ℝ) (hK : 1 ≤ K) (f : Finset E → ℝ) : + (∑ A : PM inc, gibbs w A * ∑ B ∈ safeDestinations w K A, (f A.val-f B.val)^2) ≤ + 60 * (Fintype.card V : ℝ)^2 * K^2 * switchDirichlet (inc := inc) w f := by + classical + simp only [switchDirichlet,Finset.mul_sum] + apply Finset.sum_le_sum + intro A _ + let term (B : PM inc) := 60*(Fintype.card V : ℝ)^2*K^2 * + (min (gibbs w A) (gibbs w B)*(f A.val-f B.val)^2 / (48*(A.val.card.choose 2 : ℝ))) + change (∑ B ∈ safeDestinations w K A, gibbs w A*(f A.val-f B.val)^2) ≤ + ∑ B ∈ switchDestinations A, term B + calc + _ ≤ ∑ B ∈ safeDestinations w K A, term B := by + apply Finset.sum_le_sum + intro B hB + have h : SafeSwitch w K A B := (Finset.mem_filter.mp hB).2 + have hd : 0 < 48 * (A.val.card.choose 2 : ℝ) := by + have hc : 0 < A.val.card.choose 2 := Nat.choose_pos h.legal.two_le + positivity + have hn : 0 ≤ min (gibbs w A) (gibbs w B) * (f A.val-f B.val)^2 := + mul_nonneg (le_min (le_of_lt (gibbs_pos w hw A)) (le_of_lt (gibbs_pos w hw B))) (sq_nonneg _) + have h₁ := mul_le_mul_of_nonneg_right (h.min_capacity hw hK) (sq_nonneg (f A.val-f B.val)) + have h₂ := mul_le_mul_of_nonneg_left (scale_div_lower hn hd (switch_denominator_bound hinc A)) (sq_nonneg K) + dsimp only [term] + nlinarith only [h₁,h₂] + _ ≤ _ := by + apply Finset.sum_le_sum_of_subset_of_nonneg + · intro B hB + have h : SafeSwitch w K A B := (Finset.mem_filter.mp hB).2 + exact Finset.mem_filter.mpr ⟨Finset.mem_univ _,h.legal⟩ + · intro B _ _ + have ha := le_of_lt (gibbs_pos w hw A) + have hb := le_of_lt (gibbs_pos w hw B) + dsimp only [term] + positivity + +variable (ends : E → Sym2 V) + +omit [DecidableEq V] [Fintype E] in +lemma ColorChange.card_pos {A B : PM (fun e v => v ∈ ends e)} (h : ColorChange ends A B) : + 0 < A.val.card := by + obtain ⟨e,f,R,hef,hA,hB⟩ := h + exact Finset.card_pos.mpr ⟨e,by rw [hA]; simp⟩ + +omit [DecidableEq V] in +lemma color_elementary (w : E → ℝ) (hw : ∀ e, 0 < w e) (K : ℝ) (hK : 1 ≤ K) + (hcomp : ∀ e f, ends e = ends f → w e ≤ K*w f) (f : Finset E → ℝ) : + (∑ A : PM (fun e v => v ∈ ends e), gibbs w A * + ∑ B ∈ colorDestinations ends A, (f A.val-f B.val)^2) ≤ + 12 * (Fintype.card V : ℝ) * K * colorDirichlet ends w f := by + classical + have hinc (e : E) : ∃ v, v ∈ ends e := by + induction ends e using Sym2.inductionOn with | hf a b => exact ⟨a,by simp⟩ + simp only [colorDirichlet,Finset.mul_sum] + apply Finset.sum_le_sum + intro A _ + apply Finset.sum_le_sum + intro B hB + have h : ColorChange ends A B := (Finset.mem_filter.mp hB).2 + have hd : 0 < 12 * (A.val.card : ℝ) := by have := h.card_pos ends; positivity + have hb : 12 * (A.val.card : ℝ) ≤ 12 * (Fintype.card V : ℝ) := by + exact_mod_cast (Nat.mul_le_mul_left 12 (A.card_le_vertices hinc)) + have hn : 0 ≤ min (gibbs w A) (gibbs w B) * (f A.val-f B.val)^2 := + mul_nonneg (le_min (le_of_lt (gibbs_pos w hw A)) (le_of_lt (gibbs_pos w hw B))) (sq_nonneg _) + have h₁ := mul_le_mul_of_nonneg_right (h.min_capacity ends hw hK hcomp) (sq_nonneg (f A.val-f B.val)) + have h₂ := mul_le_mul_of_nonneg_left (scale_div_lower hn hd hb) (by linarith : 0 ≤ K) + nlinarith only [h₁,h₂] + +omit [Fintype E] in +lemma cycleSquare_common (f g : Finset E → ℝ) (A B S : Finset E) (hS : S ⊆ A ∩ B) : + cycleSquare f g A B S = 0 := by + have hSA : S ⊆ A := fun e he => (Finset.mem_inter.mp (hS he)).1 + have hSB : S ⊆ B := fun e he => (Finset.mem_inter.mp (hS he)).2 + simp only [cycleSquare,exchange,Finset.inter_eq_right.mpr hSA,Finset.inter_eq_right.mpr hSB, + Finset.sdiff_union_of_subset hSA,Finset.sdiff_union_of_subset hSB,sub_self,zero_pow (by decide : 2 ≠ 0)] + +omit [DecidableEq V] [Fintype E] in +lemma all_cycleSquare_sum (f g : Finset E → ℝ) (A B : PM inc) : + (∑ S ∈ components (inc := inc) (A.val ∪ B.val), cycleSquare f g A.val B.val S) = + ∑ S ∈ discrepancyComponents A B, cycleSquare f g A.val B.val S := by + classical + apply (Finset.sum_subset (Finset.filter_subset _ _) ?_).symm + intro S hS hnot + have hcommon : S ⊆ A.val ∩ B.val := by + by_contra h + exact hnot (Finset.mem_filter.mpr ⟨hS,h⟩) + exact cycleSquare_common f g _ _ _ hcommon + +omit [DecidableEq V] in +lemma cycle_elementary (hinc : ∀ e, ∃ v, inc e v) + (w : E → ℝ) (hw : ∀ e, 0 < w e) (f g : Finset E → ℝ) : + (∑ A : PM inc, ∑ B : PM inc, gibbs w A * gibbs w B * + ∑ S ∈ components (inc := inc) (A.val ∪ B.val), cycleSquare f g A.val B.val S) ≤ + 6 * (Fintype.card V : ℝ) * cycleDirichlet (inc := inc) w f g := by + classical + simp only [cycleDirichlet,Finset.mul_sum] + apply Finset.sum_le_sum + intro A _ + apply Finset.sum_le_sum + intro B _ + rw [← Finset.mul_sum,all_cycleSquare_sum,Finset.mul_sum] + apply Finset.sum_le_sum + intro S hS + have hcard : 0 < (discrepancyComponents A B).card := Finset.card_pos.mpr ⟨S,hS⟩ + have hd : (discrepancyComponents A B).card ≤ Fintype.card V := + (Finset.card_filter_le _ _).trans (components_card_le hinc _) + have hb : 6 * ((discrepancyComponents A B).card : ℝ) ≤ 6 * (Fintype.card V : ℝ) := by exact_mod_cast Nat.mul_le_mul_left 6 hd + have hscale := scale_div_lower (sq_nonneg ((f A.val+g B.val)-(f (exchange A.val B.val S)+g (exchange B.val A.val S)))) + (by positivity : 0 < 6 * ((discrepancyComponents A B).card : ℝ)) hb + have h := mul_le_mul_of_nonneg_left hscale + (mul_nonneg (le_of_lt (gibbs_pos w hw A)) (le_of_lt (gibbs_pos w hw B))) + dsimp only [cycleSquare] at * + nlinarith only [h] + +end MatchingFPRAS.Transport + +namespace MatchingFPRAS.FiniteVariance + +variable {Ω : Type*} [Fintype Ω] + +noncomputable def variance (π f : Ω → ℝ) : ℝ := + ∑ x, π x * (f x - ∑ y, π y * f y)^2 + +lemma variance_eq_pair (π f : Ω → ℝ) (hπ : ∑ x, π x = 1) : + variance π f = (∑ p : Ω × Ω, π p.1 * π p.2 * (f p.1-f p.2)^2) / 2 := by + let m := ∑ y, π y * f y + let s := ∑ y, π y * f y ^ 2 + have hl : variance π f = s-m^2 := by + unfold variance + change (∑ x, π x * (f x-m)^2) = s-m^2 + calc + _ = ∑ x, (π x * f x^2 - 2*m*(π x*f x) + m^2*π x) := by + apply Finset.sum_congr rfl + intro x _ + ring + _ = s-m^2 := by + rw [Finset.sum_add_distrib,Finset.sum_sub_distrib,← Finset.mul_sum,← Finset.mul_sum,hπ] + change s-2*m*m+m^2*1 = s-m^2 + ring + have hr : (∑ p : Ω × Ω, π p.1 * π p.2 * (f p.1-f p.2)^2) = 2*(s-m^2) := by + rw [Fintype.sum_prod_type] + have hin (x : Ω) : (∑ y, π x*π y*(f x-f y)^2) = π x*f x^2-2*m*(π x*f x)+s*π x := by + calc + _ = ∑ y, ((π x*f x^2)*π y - (2*π x*f x)*(π y*f y) + π x*(π y*f y^2)) := by + apply Finset.sum_congr rfl + intro y _ + ring + _ = _ := by + rw [Finset.sum_add_distrib,Finset.sum_sub_distrib,← Finset.mul_sum,← Finset.mul_sum,← Finset.mul_sum,hπ] + change (π x*f x^2)*1-(2*π x*f x)*m+π x*s = _ + ring + simp_rw [hin] + rw [Finset.sum_add_distrib,Finset.sum_sub_distrib,← Finset.mul_sum,← Finset.mul_sum,hπ] + change s-2*m*m+s*1 = 2*(s-m^2) + ring + rw [hl,hr] + ring + +end MatchingFPRAS.FiniteVariance + +namespace MatchingFPRAS + +lemma energy_coefficient_bound {N D T : ℝ} (hN1 : 1 ≤ N) (hD : 1 ≤ D) + (hT0 : 0 ≤ T) (htag : T ≤ (10*N)^30) : + 180*N^5*(1000*D)^6*T+72*N^4*(1000*D)^4*T+12*N^3*(1000*D) ≤ + ((10^4 : ℝ)*N*D)^100 := by + let K := 1000*D + have hK : 1 ≤ K := by dsimp [K]; linarith + have hN0 : 0 ≤ N := by linarith + have hDN : N ≤ N*D := by nlinarith [mul_nonneg hN0 (sub_nonneg.mpr hD)] + have hDD : D ≤ N*D := by nlinarith [mul_nonneg (sub_nonneg.mpr hN1) (le_trans (by norm_num : (0:ℝ) ≤ 1) hD)] + let B := (10^4 : ℝ)*N*D + have hB : 3 ≤ B := by dsimp [B]; nlinarith + have hNB : N ≤ B := by dsimp [B]; nlinarith + have hKB : K ≤ B := by dsimp [B,K]; nlinarith + have h10NB : 10*N ≤ B := by dsimp [B]; nlinarith + have hTB : T ≤ B^30 := htag.trans (by gcongr) + have h180 : (180:ℝ) ≤ B := by dsimp [B]; nlinarith + have h72 : (72:ℝ) ≤ B := by linarith + have h12 : (12:ℝ) ≤ B := by linarith + have hb0 : 0 ≤ B := by linarith + have hterm1 : 180*N^5*K^6*T ≤ B^42 := by + calc + _ ≤ B*B^5*B^6*B^30 := by gcongr + _ = _ := by ring + have hterm2 : 72*N^4*K^4*T ≤ B^39 := by + calc + _ ≤ B*B^4*B^4*B^30 := by gcongr + _ = _ := by ring + have hterm3 : 12*N^3*K ≤ B^5 := by + calc + _ ≤ B*B^3*B := by gcongr + _ = _ := by ring + have hp39 : B^39 ≤ B^42 := pow_le_pow_right₀ (by linarith : 1 ≤ B) (by omega) + have hp5 : B^5 ≤ B^42 := pow_le_pow_right₀ (by linarith : 1 ≤ B) (by omega) + have hcoef : 180*N^5*K^6*T+72*N^4*K^4*T+12*N^3*K ≤ B^100 := by + calc + _ ≤ 3*B^42 := by linarith + _ ≤ B*B^42 := mul_le_mul_of_nonneg_right hB (pow_nonneg hb0 _) + _ = B^43 := by ring + _ ≤ B^100 := pow_le_pow_right₀ (by linarith : 1 ≤ B) (by omega) + exact hcoef + +end MatchingFPRAS + +namespace MatchingFPRAS.Transport.CellDemands + +variable {V L : Type*} [Fintype V] [DecidableEq V] [Fintype L] [DecidableEq L] + +variable {bags : V → Finset L} {G : SimpleGraph L} + +noncomputable local instance : Fintype (BagEdge bags) := Fintype.ofFinite _ + +variable {hbags : ∀ v, ∀ a ∈ bags v, ∀ b ∈ bags v, a = b ∨ G.Adj a b} + +variable {hG : G.IsAcyclic} + +variable (height : L → ℝ) (hheight : ∀ l, 0 < height l) + +variable (hstep : ∀ a b, G.Adj a b → height a ≤ 2 * height b) + +variable (D : ℝ) (hD : 1 ≤ D) (w : BagEdge bags → ℝ) + +variable (hw : ∀ e, height e.color / D ≤ w e ∧ w e ≤ 3 * height e.color) + +variable (lo hi : ℝ) (hlo : 0 < lo) (hlohi : lo ≤ hi) + +include hheight hstep hD hw hlo hlohi hbags hG + +theorem pair_energy_inequality (hN : 2 ≤ Fintype.card V) + (M : PM (BagEdge.Incident (bags := bags))) (f g : Finset (BagEdge bags) → ℝ) : + let wt := fun e => max lo (min hi (w e)) + MatchingFPRAS.FiniteVariance.variance (gibbs (inc := BagEdge.Incident) wt) (fun A => f A.val) ≤ + ((10^4 : ℝ) * Fintype.card V * D)^100 * + pairDirichlet (fun e : BagEdge bags => e.val.val.1) wt f g := by + classical + let wt := fun e => max lo (min hi (w e)) + have hwt (e : BagEdge bags) : 0 < wt e := lt_of_lt_of_le hlo (le_max_left _ _) + let N : ℝ := Fintype.card V + let K : ℝ := 1000*D + let T : ℝ := Fintype.card (DemandTag (V := V) (E := BagEdge bags)) + let E := pairDirichlet (fun e : BagEdge bags => e.val.val.1) wt f g + have hK : 1 ≤ K := by dsimp [K]; linarith + have hN0 : 0 ≤ N := Nat.cast_nonneg _ + have hE : 0 ≤ E := by + exact add_nonneg (add_nonneg (switchDirichlet_nonneg wt hwt f) + (colorDirichlet_nonneg _ wt hwt f)) (cycleDirichlet_nonneg wt hwt f g) + have hsE : switchDirichlet (inc := BagEdge.Incident) wt f ≤ E := + (le_add_of_nonneg_right (colorDirichlet_nonneg (fun e : BagEdge bags => e.val.val.1) wt hwt f)).trans + (le_add_of_nonneg_right (cycleDirichlet_nonneg wt hwt f g)) + have hcE : colorDirichlet (fun e : BagEdge bags => e.val.val.1) wt f ≤ E := + (le_add_of_nonneg_left (switchDirichlet_nonneg (inc := BagEdge.Incident) wt hwt f)).trans + (le_add_of_nonneg_right (cycleDirichlet_nonneg wt hwt f g)) + have hyE : cycleDirichlet (inc := BagEdge.Incident) wt f g ≤ E := + le_add_of_nonneg_left (add_nonneg (switchDirichlet_nonneg wt hwt f) + (colorDirichlet_nonneg (fun e : BagEdge bags => e.val.val.1) wt hwt f)) + have hs := (safe_switch_elementary BagEdge.exists_incident wt hwt K hK f).trans + (mul_le_mul_of_nonneg_left hsE (by positivity : 0 ≤ 60*N^2*K^2)) + have hc := (color_elementary (fun e : BagEdge bags => e.val.val.1) wt hwt K hK + (color_clamp_comparability hbags height hheight hstep D hD w hw lo hi hlo) f).trans + (mul_le_mul_of_nonneg_left hcE (by positivity : 0 ≤ 12*N*K)) + have hy := (cycle_elementary BagEdge.exists_incident wt hwt f g).trans + (mul_le_mul_of_nonneg_left hyE (by positivity : 0 ≤ 6*N)) + have hl := total_cell_demand_load (hbags := hbags) (hG := hG) height hheight hstep D hD w hw lo hi hlo hlohi M f g + change (∑ d : Demand hbags hG, gibbs wt d.1.1 * gibbs wt d.1.2 * d.cellCost f) ≤ + K^4*T*((∑ A : PM BagEdge.Incident, gibbs wt A * + ∑ B ∈ safeDestinations wt K A, (f A.val-f B.val)^2) + 4* + ∑ A : PM BagEdge.Incident, ∑ B : PM BagEdge.Incident, gibbs wt A*gibbs wt B* + ∑ S ∈ components (inc := BagEdge.Incident) (A.val∪B.val), cycleSquare f g A.val B.val S) at hl + have hload := hl.trans (mul_le_mul_of_nonneg_left (add_le_add hs (mul_le_mul_of_nonneg_left hy (by norm_num))) + (by dsimp [T]; positivity : 0 ≤ K^4*T)) + have hv := variance_cell_demand_bound (hbags := hbags) (hG := hG) wt hwt M f + have hvar := hv.trans (add_le_add (mul_le_mul_of_nonneg_left hload (by positivity : 0 ≤ 3*N^3)) + (mul_le_mul_of_nonneg_left hc (by positivity : 0 ≤ N^2))) + have hraw : MatchingFPRAS.FiniteVariance.variance (gibbs (inc := BagEdge.Incident) wt) (fun A => f A.val) ≤ + (180*N^5*K^6*T+72*N^4*K^4*T+12*N^3*K)*E := by + rw [MatchingFPRAS.FiniteVariance.variance_eq_pair _ _ (gibbs_sum wt hwt M)] + calc + _ ≤ _ := hvar + _ = _ := by ring + have htag : T ≤ (10*N)^30 := by + have h := tag_card_bound (V := V) (E := BagEdge bags) (Fintype.card V) hN le_rfl (bag_edges_card_le hbags hG) + dsimp only [T,N] + exact_mod_cast h + have hT0 : 0 ≤ T := Nat.cast_nonneg _ + have hN1 : 1 ≤ N := by dsimp [N]; exact_mod_cast (show 1 ≤ Fintype.card V by omega) + have hcoef := MatchingFPRAS.energy_coefficient_bound hN1 hD hT0 htag + exact hraw.trans (mul_le_mul_of_nonneg_right hcoef hE) + +end MatchingFPRAS.Transport.CellDemands + +namespace MatchingFPRAS.Transport + +open Finset + +variable {V E : Type*} [Fintype V] [DecidableEq V] [Fintype E] [DecidableEq E] + +variable (ends : E → Sym2 V) (hloop : ∀ e, ¬(ends e).IsDiag) + +include hloop + +omit [Fintype E] [DecidableEq E] in +lemma PM.twice_card (A : PM (fun e v => v ∈ ends e)) : 2*A.val.card = Fintype.card V := by + classical + have hv (v : V) : (∑ e ∈ A.val, if v ∈ ends e then (1:ℕ) else 0) = 1 := by + obtain ⟨e,⟨he,hev⟩,hu⟩ := A.property.2 v (Finset.mem_univ v) + rw [Finset.sum_eq_single e] + · simp [hev] + · intro f hf hfe + have : v ∉ ends f := fun hfv => hfe (hu f ⟨hf,hfv⟩) + simp [this] + · exact fun h => (h he).elim + have he (e : E) : (∑ v : V, if v ∈ ends e then (1:ℕ) else 0) = 2 := by + have hs : Finset.univ.filter (fun v => v ∈ ends e) = (ends e).toFinset := by + ext v; simp + rw [← Finset.sum_filter,Finset.sum_const,smul_eq_mul,mul_one,hs] + exact Sym2.card_toFinset_of_not_isDiag _ (hloop e) + calc + _ = ∑ e ∈ A.val, ∑ v : V, if v ∈ ends e then (1:ℕ) else 0 := by + simp [he,Nat.mul_comm] + _ = ∑ v : V, ∑ e ∈ A.val, if v ∈ ends e then (1:ℕ) else 0 := by rw [Finset.sum_comm] + _ = _ := by simp [hv] + +omit [Fintype E] [DecidableEq E] in +lemma PM.card_eq (A B : PM (fun e v => v ∈ ends e)) : A.val.card = B.val.card := by + have ha := A.twice_card ends hloop + have hb := B.twice_card ends hloop + omega + +omit hloop + +omit [DecidableEq V] [Fintype E] [DecidableEq E] in +lemma matchingWeight_compare {w z : E → ℝ} (hw : ∀ e, 0 ≤ w e) + (c : ℝ) (_hc : 0 ≤ c) (h : ∀ e, w e ≤ c*z e) + (A : PM (fun e v => v ∈ ends e)) : + matchingWeight w A ≤ c^A.val.card*matchingWeight z A := by + calc + _ ≤ ∏ e ∈ A.val, c*z e := Finset.prod_le_prod₀ (fun edge _ => hw edge) (fun edge _ => h edge) + _ = _ := by simp only [Finset.prod_mul_distrib,Finset.prod_const]; rfl + +include hloop + +omit [DecidableEq E] in +lemma partition_compare {w z : E → ℝ} (hw : ∀ e, 0 ≤ w e) + (c : ℝ) (hc : 0 ≤ c) (h : ∀ e, w e ≤ c*z e) + (A : PM (fun e v => v ∈ ends e)) : + partition (inc := fun e v => v ∈ ends e) w ≤ + c^A.val.card*partition (inc := fun e v => v ∈ ends e) z := by + classical + unfold partition + rw [Finset.mul_sum] + apply Finset.sum_le_sum; intro B _ + have hh := matchingWeight_compare ends hw c hc h B + rwa [PM.card_eq ends hloop B A] at hh + +omit [DecidableEq E] in +lemma gibbs_compare {w z : E → ℝ} (hw : ∀ e, 0 < w e) (hz : ∀ e, 0 < z e) + (c : ℝ) (hc : 0 ≤ c) (hwz : ∀ e, w e ≤ c*z e) (hzw : ∀ e, z e ≤ c*w e) + (A : PM (fun e v => v ∈ ends e)) : + gibbs w A ≤ c^(Fintype.card V)*gibbs z A := by + have hwa := matchingWeight_compare ends (fun e => (hw e).le) c hc hwz A + have hpz := partition_compare ends hloop (fun e => (hz e).le) c hc hzw A + have hprod := mul_le_mul hwa hpz (le_of_lt (partition_pos z hz A)) + (mul_nonneg (pow_nonneg hc _) (matchingWeight_pos z hz A).le) + have he : c^A.val.card*c^A.val.card = c^(Fintype.card V) := by + rw [← pow_add,← A.twice_card ends hloop] + congr 1; omega + have hh : matchingWeight w A*partition (inc := fun e v => v ∈ ends e) z ≤ + c^(Fintype.card V)*matchingWeight z A*partition (inc := fun e v => v ∈ ends e) w := by + calc + _ ≤ (c^A.val.card*matchingWeight z A)*(c^A.val.card*partition (inc := fun e v => v ∈ ends e) w) := hprod + _ = _ := by rw [← he]; ring + unfold gibbs + rw [← mul_div_assoc,div_le_div_iff₀ (partition_pos w hw A) (partition_pos z hz A)] + exact hh + +end MatchingFPRAS.Transport + +end OAI diff --git a/lean/OAI/Combinatorics/MatchingCount/Sampling/AssignmentEquiv.lean b/lean/OAI/Combinatorics/MatchingCount/Sampling/AssignmentEquiv.lean new file mode 100644 index 0000000000000000000000000000000000000000..0a6be6625a4e93ea5095f9d78ee2eb9f761a57df --- /dev/null +++ b/lean/OAI/Combinatorics/MatchingCount/Sampling/AssignmentEquiv.lean @@ -0,0 +1,352 @@ +import Mathlib +import OAI.Combinatorics.MatchingCount.Graphs.Edge2 + +namespace OAI + +namespace MatchingFPRAS.UnitRefresh + +open Finset + +variable {V W L : Type*} [Fintype V] [Fintype W] [Fintype L] + [DecidableEq V] [DecidableEq W] [DecidableEq L] + +noncomputable def assignmentEquiv (b : V → Finset L) (c : W → Finset L) + (e : V ≃ W) (he : ∀ x,c (e x)=b x) : Assignment b ≃ Assignment c where + toFun f := ⟨fun y => f.val (e.symm y),fun y => by + have hy : c y=b (e.symm y) := by simpa using he (e.symm y) + rw [hy]; exact f.property (e.symm y)⟩ + invFun f := ⟨fun x => f.val (e x),fun x => by rw [←he]; exact f.property _⟩ + left_inv f := Subtype.ext (by funext x; simp) + right_inv f := Subtype.ext (by funext x; simp) + +omit [Fintype L] [DecidableEq V] [DecidableEq W] in +lemma fiberCount_equiv [Fintype L] [DecidableEq V] [DecidableEq W] + (e : V ≃ W) (f : V → L) (g : W → L) + (h : ∀ x,g (e x)=f x) (l : L) : fiberCount f l=fiberCount g l := by + unfold fiberCount + exact Fintype.card_congr (e.subtypeEquiv (fun x => by rw [h])) + +lemma assignmentPartition_equiv (b : V → Finset L) (c : W → Finset L) + (e : V ≃ W) (he : ∀ x,c (e x)=b x) (w : L → ℕ → ℕ) : + assignmentPartition b w = assignmentPartition c w := by + classical + unfold assignmentPartition + apply Fintype.sum_equiv (assignmentEquiv b c e he) + intro f + apply prod_congr rfl + intro l hl + congr 1 + apply fiberCount_equiv e + intro x + simp [assignmentEquiv] + +abbrev Private (b : V → Finset L) (l : L) := {x : V // b x={l}} + +abbrev Shared (b : V → Finset L) (l : L) := {x : V // l∈b x ∧ b x≠{l}} + +abbrev Outside (b : V → Finset L) (l : L) := {x : V // l∉b x} + +noncomputable def splitLeaf (b : V → Finset L) (l : L) : + V ≃ Private b l ⊕ Shared b l ⊕ Outside b l where + toFun x := if h : b x={l} then .inl ⟨x,h⟩ else + if h' : l∈b x then .inr (.inl ⟨x,h',h⟩) else .inr (.inr ⟨x,h'⟩) + invFun := Sum.elim Subtype.val (Sum.elim Subtype.val Subtype.val) + left_inv x := by dsimp only; split_ifs <;> rfl + right_inv x := by + rcases x with x | (x | x) + · simp [x.property] + · simp [x.property.1,x.property.2] + · have hx : b x.val≠{l} := by intro h; exact x.property (by simp [h]) + simp [hx,x.property] + +def LeafAt (b : V → Finset L) (l p : L) : Prop := + ∀ x,l∈b x → b x={l} ∨ b x={l,p} + +omit [Fintype V] [Fintype L] [DecidableEq V] in +lemma splitLeaf_bags [Fintype V] [Fintype L] [DecidableEq V] + (b : V → Finset L) (l p : L) (h : LeafAt b l p) (x : V) : + leafBags l p (fun y : Outside b l => b y.val) (splitLeaf b l x)=b x := by + classical + unfold splitLeaf + simp only [Equiv.coe_fn_mk] + split_ifs with he hm + · exact he.symm + · exact ((h x hm).resolve_left he).symm + · rfl + +theorem tree_leaf_elimination (b : V → Finset L) (l p : L) (hlp : l≠p) + (h : LeafAt b l p) (w : L → ℕ → ℕ) : + assignmentPartition b w = + assignmentPartition (fun x : Outside b l => b x.val) + (leafUpdate (Fintype.card (Private b l)) (Fintype.card (Shared b l)) l p w) := by + classical + rw [assignmentPartition_equiv b _ (splitLeaf b l) (splitLeaf_bags b l p h)] + exact leaf_elimination l p hlp _ (fun x => x.property) w + +def rootBags {U : Type*} (l : L) (b : W → Finset L) : U ⊕ W → Finset L := + Sum.elim (fun _ => {l}) b + +noncomputable def rootAssignmentEquiv {U : Type*} [Fintype U] [DecidableEq U] + (l : L) (b : W → Finset L) : Assignment (rootBags (U:=U) l b) ≃ Assignment b where + toFun f := ⟨fun x => f.val (.inr x),fun x => f.property _⟩ + invFun f := ⟨Sum.elim (fun _ => l) f.val,by + intro x; rcases x with x | x + · simp [rootBags] + · exact f.property x⟩ + left_inv f := by + apply Subtype.ext + funext x + rcases x with x | x + · have h := f.property (.inl x) + have hx : f.val (.inl x)=l := by simpa [rootBags] using h + exact hx.symm + · rfl + right_inv f := rfl + +noncomputable def rootUpdate (u : ℕ) (l : L) (w : L → ℕ → ℕ) : L → ℕ → ℕ := + fun a r => if a=l then w l u else w a r + +lemma root_elimination {U : Type*} [Fintype U] [DecidableEq U] + (l : L) (b : W → Finset L) (hb : ∀ x,l∉b x) (w : L → ℕ → ℕ) : + assignmentPartition (rootBags (U:=U) l b) w = + assignmentPartition b (rootUpdate (Fintype.card U) l w) := by + classical + unfold assignmentPartition + apply Fintype.sum_equiv (rootAssignmentEquiv l b) + intro f + have hl : fiberCount f.val l = Fintype.card U := by + rw [fiberCount_sum] + have he : (fun x : U => f.val (.inl x))=(fun _ => l) := by + funext x; simpa [rootBags] using f.property (.inl x) + rw [he,fiberCount_const,ite_eq_left rfl] + have hz : fiberCount (fun x : W => f.val (.inr x)) l=0 := by + apply fiberCount_zero + intro x hx + exact hb x (hx ▸ f.property (.inr x)) + omega + apply prod_congr rfl + intro a ha + by_cases h : a=l + · subst a; simp [rootUpdate,hl] + · simp only [rootUpdate,ite_eq_right h] + congr 1 + rw [fiberCount_sum] + have he : (fun x : U => f.val (.inl x))=(fun _ => l) := by + funext x; simpa [rootBags] using f.property (.inl x) + rw [he,fiberCount_const,ite_eq_right (Ne.symm h),zero_add] + rfl + +noncomputable def splitRoot (b : V → Finset L) (l : L) : + V ≃ {x : V // l∈b x} ⊕ Outside b l where + toFun x := if h : l∈b x then .inl ⟨x,h⟩ else .inr ⟨x,h⟩ + invFun := Sum.elim Subtype.val Subtype.val + left_inv x := by dsimp only; split_ifs <;> rfl + right_inv x := by rcases x with x | x <;> simp [x.property] + +theorem tree_root_elimination (b : V → Finset L) (l : L) + (h : ∀ x,l∈b x → b x={l}) (w : L → ℕ → ℕ) : + assignmentPartition b w = + assignmentPartition (fun x : Outside b l => b x.val) + (rootUpdate (Fintype.card {x : V // l∈b x}) l w) := by + classical + have he (x : V) : rootBags l (fun y : Outside b l => b y.val) (splitRoot b l x)=b x := by + unfold splitRoot + simp only [Equiv.coe_fn_mk] + split_ifs with hx + · exact (h x hx).symm + · rfl + rw [assignmentPartition_equiv b _ (splitRoot b l) he] + exact root_elimination l _ (fun x => x.property) w + +open Finset + +variable {V L : Type*} [Fintype V] [Fintype L] [DecidableEq V] [DecidableEq L] + +noncomputable def activePartition (b : V → Finset L) (R : Finset V) (w : L → ℕ → ℕ) : ℕ := + assignmentPartition (fun x : R => b x.val) w + +def trim (b : V → Finset L) (R : Finset V) (l : L) : Finset V := R.filter fun x => l∉b x + +def privateCount (b : V → Finset L) (R : Finset V) (l : L) : ℕ := + (R.filter fun x => b x={l}).card + +def sharedCount (b : V → Finset L) (R : Finset V) (l : L) : ℕ := + (R.filter fun x => l∈b x ∧ b x≠{l}).card + +noncomputable def activeFilterEquiv (R : Finset V) (P : V → Prop) [DecidablePred P] : + {x : R // P x.val} ≃ (R.filter P) where + toFun x := ⟨x.val.val,mem_filter.mpr ⟨x.val.property,x.property⟩⟩ + invFun x := ⟨⟨x.val,(mem_filter.mp x.property).1⟩,(mem_filter.mp x.property).2⟩ + left_inv _ := rfl + right_inv _ := rfl + +omit [Fintype V] [DecidableEq V] in +lemma active_card_filter [Fintype V] [DecidableEq V] + (R : Finset V) (P : V → Prop) [DecidablePred P] : + Fintype.card {x : R // P x.val}=(R.filter P).card := by + rw [Fintype.card_congr (activeFilterEquiv R P),Fintype.card_coe] + +omit [Fintype V] in +lemma active_outside [Fintype V] + (b : V → Finset L) (R : Finset V) (l : L) (w : L → ℕ → ℕ) : + assignmentPartition (fun x : Outside (fun y : R => b y.val) l => b x.val.val) w = + activePartition b (trim b R l) w := by + change assignmentPartition (fun x : {y : R // l∉b y.val} => b x.val.val) w = + assignmentPartition (fun x : R.filter (fun y => l∉b y) => b x.val) w + apply assignmentPartition_equiv _ _ (activeFilterEquiv R (fun x => l∉b x)) + intro x + rfl + +theorem active_leaf_elimination (b : V → Finset L) (R : Finset V) (l p : L) (hlp : l≠p) + (h : LeafAt (fun x : R => b x.val) l p) (w : L → ℕ → ℕ) : + activePartition b R w = activePartition b (trim b R l) + (leafUpdate (privateCount b R l) (sharedCount b R l) l p w) := by + unfold activePartition + rw [tree_leaf_elimination _ l p hlp h,active_outside] + rw [show Fintype.card (Private (fun x : R => b x.val) l)=privateCount b R l from + active_card_filter R (fun x => b x={l}), + show Fintype.card (Shared (fun x : R => b x.val) l)=sharedCount b R l from + active_card_filter R (fun x => l∈b x ∧ b x≠{l})] + rfl + +lemma active_root_elimination (b : V → Finset L) (R : Finset V) (l : L) + (h : ∀ x : R,l∈b x.val → b x.val={l}) (w : L → ℕ → ℕ) : + activePartition b R w = activePartition b (trim b R l) + (rootUpdate ((R.filter fun x => l∈b x).card) l w) := by + unfold activePartition + rw [tree_root_elimination _ l h,active_outside,active_card_filter R (fun x => l∈b x)] + rfl + +lemma partition_isEmpty {W : Type*} [Fintype W] [DecidableEq W] [IsEmpty W] + (b : W → Finset L) (w : L → ℕ → ℕ) : assignmentPartition b w=∏ l,w l 0 := by + classical + let : Unique (Assignment b) := + { default := ⟨isEmptyElim,fun x => isEmptyElim x⟩ + uniq := fun f => Subtype.ext (by funext x; exact isEmptyElim x) } + simp [assignmentPartition,fiberCount] + +omit [Fintype V] in +lemma active_empty [Fintype V] (b : V → Finset L) (w : L → ℕ → ℕ) : + activePartition b ∅ w=∏ l,w l 0 := partition_isEmpty _ _ + +def RankedBags (b : V → Finset L) (rank : L → ℕ) (parent : L → Option L) : Prop := + ∀ x a,a ∈ b x → ∀ a'∈b x,a≠a' → + (rank a leafUpdate (privateCount b R l) (sharedCount b R l) l p w + | none => rootUpdate ((R.filter fun x => l∈b x).card) l w + +noncomputable def tableDP (b : V → Finset L) (parent : L → Option L) : + List L → Finset V → (L → ℕ → ℕ) → (L → ℕ → ℕ) + | [],_,w => w + | l::ls,R,w => tableDP b parent ls (trim b R l) (advanceTable b R parent l w) + +def LegalPlan (b : V → Finset L) (parent : L → Option L) : List L → Finset V → Prop + | [],R => R=∅ + | l::ls,R => + (match parent l with + | some p => l≠p ∧ LeafAt (fun x : R => b x.val) l p + | none => ∀ x : R,l∈b x.val → b x.val={l}) ∧ + LegalPlan b parent ls (trim b R l) + +theorem tableDP_correct (b : V → Finset L) (parent : L → Option L) + (ls : List L) (R : Finset V) (hp : LegalPlan b parent ls R) (w : L → ℕ → ℕ) : + activePartition b R w=∏ l,tableDP b parent ls R w l 0 := by + induction ls generalizing R w with + | nil => + have hR : R=∅ := hp + subst R + exact active_empty b w + | cons l ls ih => + have ht : activePartition b R w = + activePartition b (trim b R l) (advanceTable b R parent l w) := by + cases hpar : parent l with + | none => + unfold advanceTable; rw [hpar] + exact active_root_elimination b R l (by simpa only [LegalPlan,hpar] using hp.1) w + | some p => + have h := hp.1 + simp only [hpar] at h + unfold advanceTable; rw [hpar] + exact active_leaf_elimination b R l p h.1 h.2 w + rw [ht] + exact ih _ hp.2 _ + +omit [Fintype V] [Fintype L] [DecidableEq V] in +theorem rank_order_legal [Fintype V] [Fintype L] [DecidableEq V] + (b : V → Finset L) (rank : L → ℕ) (parent : L → Option L) + (hb : RankedBags b rank parent) + (hp : ∀ l p,parent l=some p → rank p rank a'≤rank a)) + (R : Finset V) (hne : ∀ x∈R,(b x).Nonempty) + (hc : ∀ x∈R,∀ a∈b x,a∈ls) : LegalPlan b parent ls R := by + induction ls generalizing R with + | nil => + apply eq_empty_iff_forall_notMem.mpr + intro x hx + obtain ⟨a,ha⟩ := hne x hx + exact List.not_mem_nil (hc x hx a ha) + | cons l ls ih => + have hs' := List.pairwise_cons.mp hs + have hmax (x : R) (a : L) (ha : a∈b x.val) : rank a≤rank l := by + have h := hc x.val x.property a ha + rcases List.mem_cons.mp h with h | h + · exact h ▸ le_rfl + · exact hs'.1 a h + have hparent (x : R) (hl : l∈b x.val) (a : L) (ha : a∈b x.val) (hal : a≠l) : + parent l=some a := by + rcases hb x.val l hl a ha (Ne.symm hal) with h | h + · exact (Nat.not_lt_of_ge (hmax x a ha) h.1).elim + · exact h.2 + constructor + · cases hpar : parent l with + | none => + intro x hl + apply eq_singleton_iff_unique_mem.mpr + exact ⟨hl,fun a ha => by + by_contra hal + have h := hparent x hl a ha hal + rw [hpar] at h + cases h⟩ + | some p => + constructor + · intro h; subst p + exact Nat.lt_irrefl _ (hp l l hpar) + · intro x hl + by_cases h : b x.val={l} + · exact Or.inl h + · right + apply Subset.antisymm + · intro a ha + by_cases hal : a=l + · simp [hal] + · have hpa : p=a := Option.some.inj (hpar.symm.trans (hparent x hl a ha hal)) + simp [hpa] + · intro a ha + simp only [mem_insert,mem_singleton] at ha + rcases ha with ha | ha + · simpa [ha] using hl + · rw [ha] + by_contra hpn + apply h + apply eq_singleton_iff_unique_mem.mpr + refine ⟨hl,fun a ha => ?_⟩ + by_contra hal + have hpa : p=a := Option.some.inj (hpar.symm.trans (hparent x hl a ha hal)) + exact hpn (hpa ▸ ha) + · apply ih hs'.2 + · intro x hx + exact hne x (mem_filter.mp hx).1 + · intro x hx a ha + have hx' := mem_filter.mp hx + have h := hc x hx'.1 a ha + rcases List.mem_cons.mp h with hh | hh + · exact (hx'.2 (hh ▸ ha)).elim + · exact hh + +end MatchingFPRAS.UnitRefresh + +end OAI diff --git a/lean/OAI/Combinatorics/MatchingCount/Sampling/Certify.lean b/lean/OAI/Combinatorics/MatchingCount/Sampling/Certify.lean new file mode 100644 index 0000000000000000000000000000000000000000..081836c01decd6b97d9e8792c2595f858609fda5 --- /dev/null +++ b/lean/OAI/Combinatorics/MatchingCount/Sampling/Certify.lean @@ -0,0 +1,330 @@ +import Mathlib +import OAI.Combinatorics.MatchingCount.Sampling.RelationDestinations +import OAI.Combinatorics.MatchingCount.Tapes.RunBits + +namespace OAI + +namespace MatchingFPRAS.Counting + +lemma sigma_nonneg (D K : ℕ) (epsilon : ℚ) (he : 0 ≤ epsilon) : 0 ≤ sigma D K epsilon := by + unfold sigma alpha; positivity + +lemma sigma_small (D K : ℕ) (hD : 1 ≤ D) (epsilon : ℚ) : sigma D K epsilon ≤ (1:ℚ)/10000000 := by + have hDr : (1:ℚ) ≤ D := by exact_mod_cast hD + apply (min_le_left _ _).trans + apply (div_le_iff₀ (by positivity : 0 < (100:ℚ)*D)).mpr + norm_num [alpha] + linarith + +lemma sigma_times_D (D K : ℕ) (hD : 1 ≤ D) (epsilon : ℚ) : (D:ℚ)*sigma D K epsilon ≤ alpha/100 := by + have hDr : (1:ℚ) ≤ D := by exact_mod_cast hD + have hs : sigma D K epsilon ≤ alpha/(100*D) := min_le_left _ _ + have hm := (le_div_iff₀ (by positivity : 0 < (100:ℚ)*D)).mp hs + norm_num [alpha] at hm ⊢ + nlinarith only [hm] + +lemma sigma_relative (D K : ℕ) (epsilon : ℚ) : 10*sigma D K epsilon ≤ epsilon/(100*K) := by + have h : sigma D K epsilon ≤ epsilon/(1000*K) := min_le_right _ _ + calc + _ ≤ 10*(epsilon/(1000*K)) := mul_le_mul_of_nonneg_left h (by norm_num) + _ = _ := by ring + +lemma ratio_error (s a d abar dbar : ℚ) (hs : 0 ≤ s) (hs1 : s ≤ (1:ℚ)/100) + (ha : (1:ℚ)/2 ≤ a) (hR : (1:ℚ)/2 ≤ d/a ∧ d/a ≤ 1) + (haerr : |abar-a| ≤ s) (hderr : |dbar-d| ≤ s) : + |ratioEstimate abar dbar/(d/a)-1| ≤ 10*s := by + have hab := abs_le.mp haerr + have hdb := abs_le.mp hderr + have hap : 0 < a := by linarith + have habp : 0 < abar := by linarith + have hRp : 0 < d/a := by linarith [hR.1] + have hden : (1:ℚ)/5 ≤ (d/a)*abar := by + have hbar : (1:ℚ)/2-s ≤ abar := by linarith + have hm := mul_le_mul hR.1 hbar (by linarith : 0 ≤ (1:ℚ)/2-s) hRp.le + nlinarith + have hnum : |dbar-(d/a)*abar| ≤ 2*s := by + have hid : dbar-(d/a)*abar=(dbar-d)+(d/a)*(a-abar) := by + have hm : (d/a)*a=d := div_mul_cancel₀ d hap.ne' + nlinarith + rw [hid] + calc + _ ≤ |dbar-d|+|(d/a)*(a-abar)| := abs_add_le _ _ + _ = |dbar-d|+(d/a)*|abar-a| := by rw [abs_mul,abs_of_pos hRp,abs_sub_comm a abar] + _ ≤ s+(d/a)*s := add_le_add hderr (mul_le_mul_of_nonneg_left haerr hRp.le) + _ ≤ 2*s := by nlinarith [mul_le_mul_of_nonneg_right hR.2 hs] + have hid : ratioEstimate abar dbar/(d/a)-1=(dbar-(d/a)*abar)/((d/a)*abar) := by + simp only [ratioEstimate, ite_eq_left habp] + have hdne : d ≠ 0 := by intro hh; simp [hh] at hRp + field_simp [hap.ne', habp.ne', hdne] + rw [hid,abs_div,abs_of_pos (mul_pos hRp habp)] + apply (div_le_iff₀ (mul_pos hRp habp)).mpr + nlinarith [mul_le_mul_of_nonneg_right hden (show 0 ≤ 10*s by positivity)] + + + +lemma upper_error (D : ℕ) (hD : 1 ≤ D) (s d z dbar zbar : ℚ) + (hs : 0 ≤ s) (hs1 : s ≤ (1:ℚ)/100) + (hDs : (D:ℚ)*s ≤ alpha/100) (hd : (1:ℚ)/4 ≤ d) + (hg : 0 ≤ (D:ℚ)*z/d ∧ (D:ℚ)*z/d ≤ 2) + (hderr : |dbar-d| ≤ s) (hzerr : |zbar-z| ≤ s) : + alpha ≤ upperEstimate D dbar zbar ∧ upperEstimate D dbar zbar ≤ 3 ∧ + (D:ℚ)*z/d ≤ upperEstimate D dbar zbar ∧ + upperEstimate D dbar zbar ≤ (D:ℚ)*z/d+2*alpha := by + have hDr : (1:ℚ) ≤ D := by exact_mod_cast hD + have hdp : 0 < d := by linarith + have hdb := abs_le.mp hderr + have hbar : (1:ℚ)/5 ≤ dbar := by linarith + have hbarp : 0 < dbar := by linarith + let g := (D:ℚ)*z/d + have hg0 : 0 ≤ g := hg.1 + have hg2 : g ≤ 2 := hg.2 + have hnum : |(D:ℚ)*(zbar-z)+g*(d-dbar)| ≤ ((D:ℚ)+2)*s := by + calc + _ ≤ |(D:ℚ)*(zbar-z)|+|g*(d-dbar)| := abs_add_le _ _ + _ = (D:ℚ)*|zbar-z|+g*|dbar-d| := by + rw [abs_mul, abs_mul, abs_of_nonneg (Nat.cast_nonneg D), abs_of_nonneg hg0, + abs_sub_comm d dbar] + _ ≤ (D:ℚ)*s+g*s := add_le_add (mul_le_mul_of_nonneg_left hzerr (Nat.cast_nonneg D)) + (mul_le_mul_of_nonneg_left hderr hg0) + _ ≤ ((D:ℚ)+2)*s := by nlinarith [mul_le_mul_of_nonneg_right hg2 hs] + have hid : (D:ℚ)*zbar/dbar-g=((D:ℚ)*(zbar-z)+g*(d-dbar))/dbar := by + dsimp [g] + field_simp [hdp.ne', hbarp.ne'] + ring + have hraw : |(D:ℚ)*zbar/dbar-g| ≤ alpha := by + rw [hid, abs_div, abs_of_pos hbarp] + apply (div_le_iff₀ hbarp).mpr + have hsm : s ≤ (D:ℚ)*s := by nlinarith [mul_le_mul_of_nonneg_right hDr hs] + have ha : 0 < alpha := by norm_num [alpha] + have hm := mul_le_mul_of_nonneg_left hbar ha.le + norm_num [alpha] at hDs hm ⊢ + nlinarith only [hDs, hm, hnum, hsm] + have hbounds := abs_le.mp hraw + unfold upperEstimate + rw [ite_eq_left hbarp] + refine ⟨le_max_left _ _, ?_, ?_, ?_⟩ + · apply max_le + · norm_num [alpha] + · exact min_le_left _ _ + · apply le_max_of_le_right + exact le_min (by linarith) (by linarith) + · apply max_le + · have ha : 0 ≤ alpha := by norm_num [alpha] + linarith + · exact (min_le_right _ _).trans (by linarith) + + + +theorem successful_stage_estimates (D K : ℕ) (hD : 1 ≤ D) (_hK : 1 ≤ K) + (epsilon : ℚ) (he : 0 v ∈ ends e) M univ) := by + unfold MatchingOn ExistsUnique + infer_instance + +def certify (s : Finset (Finset E)) : Finset (PM (fun e v => v ∈ ends e)) := + Finset.subtype (fun A => MatchingOn (fun e v => v ∈ ends e) A univ) s + +@[simp] lemma mem_certify (s : Finset (Finset E)) (A : PM (fun e v => v ∈ ends e)) : + A ∈ certify ends s ↔ A.val ∈ s := Finset.mem_subtype + +lemma card_certify (s : Finset (Finset E)) : (certify ends s).card ≤ s.card := by + simpa only [certify,card_subtype] using + card_filter_le s (fun A => MatchingOn (fun e v => v ∈ ends e) A univ) + +def colorRaw (A : Finset E) : Finset (Finset E) := + A.biUnion fun e => (univ.filter (fun f => ends f = ends e)).image + (fun f => insert f (A.erase e)) + +def colors (A : PM (fun e v => v ∈ ends e)) : Finset (PM (fun e v => v ∈ ends e)) := + certify ends (colorRaw ends A.val) + +omit [Fintype V] in +@[simp] lemma mem_colorRaw [Fintype V] (A B : Finset E) : + B ∈ colorRaw ends A ↔ ∃ e ∈ A, ∃ f, ends f = ends e ∧ B = insert f (A.erase e) := by + simp only [colorRaw,mem_biUnion,mem_image,mem_filter,mem_univ,true_and] + constructor + · rintro ⟨e,he,f,hf,h⟩ + exact ⟨e,he,f,hf,h.symm⟩ + · rintro ⟨e,he,f,hf,h⟩ + exact ⟨e,he,f,hf,h.symm⟩ + +@[simp] lemma mem_colors (A B : PM (fun e v => v ∈ ends e)) : + B ∈ colors ends A ↔ ColorChange ends A B := by + rw [colors,mem_certify,mem_colorRaw] + constructor + · rintro ⟨e,he,f,hf,hB⟩ + refine ⟨e,f,A.val.erase e,hf.symm,?_,?_⟩ + · simpa only [union_singleton] using (insert_erase he).symm + · simpa only [union_singleton] using hB + · exact ColorChange.edit ends + +lemma colors_eq (A : PM (fun e v => v ∈ ends e)) : + colors ends A = colorDestinations ends A := by + ext B + simp [colorDestinations] + +omit [Fintype V] in +lemma colorRaw_card [Fintype V] (A : Finset E) : + (colorRaw ends A).card ≤ A.card * Fintype.card E := by + calc + _ ≤ ∑ e ∈ A, ((univ.filter (fun f => ends f = ends e)).image + (fun f => insert f (A.erase e))).card := card_biUnion_le + _ ≤ ∑ _e ∈ A, Fintype.card E := sum_le_sum fun e _ => + card_image_le.trans (card_le_univ _) + _ = _ := by simp + +def switchPatterns (A : Finset E) : Finset ((Fin 4 → V) × (Fin 4 → E)) := + univ.filter fun p => Function.Injective p.1 ∧ + (∀ i x, x ∈ ends (p.2 i) ↔ x = p.1 i ∨ x = p.1 (i+1)) ∧ + p.2 0 ≠ p.2 2 ∧ {p.2 0,p.2 2} ⊆ A + +def switchRaw (A : Finset E) : Finset (Finset E) := + (switchPatterns ends A).image fun p => (A \ {p.2 0,p.2 2}) ∪ {p.2 1,p.2 3} + +def switches (A : PM (fun e v => v ∈ ends e)) : Finset (PM (fun e v => v ∈ ends e)) := + certify ends (switchRaw ends A.val) + +@[simp] lemma mem_switches (A B : PM (fun e v => v ∈ ends e)) : + B ∈ switches ends A ↔ TwoEdgeSwitch A B := by + rw [switches,mem_certify] + constructor + · intro h + obtain ⟨⟨v,e⟩,hp,hB⟩ := mem_image.mp h + obtain ⟨hv,he,hne,hsub⟩ := (mem_filter.mp hp).2 + refine ⟨v,e,A.val \ {e 0,e 2},hv,he,?_,hB.symm⟩ + exact (sdiff_union_of_subset hsub).symm + · intro h + obtain ⟨v,e,hv,he,hne,hsub,hB⟩ := h.normal_form + exact mem_image.mpr ⟨(v,e),mem_filter.mpr ⟨mem_univ _,hv,he,hne,hsub⟩,hB.symm⟩ + +lemma switches_eq (A : PM (fun e v => v ∈ ends e)) : + switches ends A = switchDestinations A := by + ext B + simp [switchDestinations] + +lemma switchRaw_card (A : Finset E) : + (switchRaw ends A).card ≤ (Fintype.card V)^4*(Fintype.card E)^4 := by + calc + _ ≤ (switchPatterns ends A).card := card_image_le + _ ≤ Fintype.card ((Fin 4 → V) × (Fin 4 → E)) := card_le_univ _ + _ = _ := by simp + +theorem colors_card (hpar : ∀ e, (univ.filter (fun f => ends f = ends e)).card ≤ 2) + (A : PM (fun e v => v ∈ ends e)) : (colors ends A).card ≤ 2*A.val.card := by + rw [colors_eq] + exact colorDestinations_card_bound ends hpar A + +theorem switches_card (hpar : ∀ e, (univ.filter (fun f => ends f = ends e)).card ≤ 2) + (A : PM (fun e v => v ∈ ends e)) : (switches ends A).card ≤ 8*A.val.card.choose 2 := by + rw [switches_eq] + exact switchDestinations_card_bound ends hpar A + +end MatchingFPRAS.Transport.Sparse + +namespace MatchingFPRAS.ComputableReach + +open Finset + +variable {α : Type*} [Fintype α] [DecidableEq α] + +variable (G : SimpleGraph α) [DecidableRel G.Adj] + +def grow (s : Finset α) : Finset α := s ∪ univ.filter (fun b => ∃ a ∈ s, G.Adj a b) + +def reached (s : Finset α) (n : ℕ) : Finset α := (grow G)^[n] s + +def closure (a : α) : Finset α := reached G {a} (Fintype.card α) + +lemma mem_grow (s : Finset α) (b : α) : + b ∈ grow G s ↔ b ∈ s ∨ ∃ a ∈ s, G.Adj a b := by simp [grow] + +lemma subset_grow (s : Finset α) : s ⊆ grow G s := subset_union_left + +lemma grow_mono : Monotone (grow G) := by + intro s t h b hb + rcases (mem_grow G s b).mp hb with hb | ⟨a,ha,hab⟩ + · exact (mem_grow G t b).mpr (Or.inl (h hb)) + · exact (mem_grow G t b).mpr (Or.inr ⟨a,h ha,hab⟩) + +lemma reached_step (s : Finset α) (n : ℕ) : reached G s (n+1) = grow G (reached G s n) := + Function.iterate_succ_apply' _ _ _ + +lemma reached_step' (s : Finset α) (n : ℕ) : reached G s (n+1) = reached G (grow G s) n := + Function.iterate_succ_apply _ _ _ + +lemma reached_succ (s : Finset α) (n : ℕ) : reached G s n ⊆ reached G s (n+1) := by + rw [reached_step] + exact subset_grow G _ + +lemma reached_mono_time (s : Finset α) : Monotone (reached G s) := + monotone_nat_of_le_succ (reached_succ G s) + +lemma reached_reachable (a b : α) (n : ℕ) (h : b ∈ reached G {a} n) : G.Reachable a b := by + induction n generalizing b with + | zero => + have hb : b=a := by simpa [reached] using h + subst b + exact SimpleGraph.Reachable.refl a + | succ n ih => + rw [reached_step,mem_grow] at h + rcases h with h | ⟨c,hc,hcb⟩ + · exact ih b h + · exact (ih c hc).trans hcb.reachable + +lemma walk_reached {s : Finset α} {a b : α} (p : G.Walk a b) (ha : a ∈ s) : + b ∈ reached G s p.length := by + induction p generalizing s with + | nil => exact ha + | @cons a b c hab p ih => + rw [SimpleGraph.Walk.length_cons,reached_step'] + exact ih ((mem_grow G s b).mpr (Or.inr ⟨a,ha,hab⟩)) + +@[simp] theorem mem_closure (a b : α) : b ∈ closure G a ↔ G.Reachable a b := by + constructor + · exact reached_reachable G a b _ + · rintro ⟨p⟩ + exact reached_mono_time G {a} p.toPath.isPath.length_lt.le + (walk_reached G p.toPath.val (mem_singleton_self a)) + +def cellsWritten : ℕ := (Fintype.card α+1)*Fintype.card α + +omit [DecidableEq α] in +lemma cellsWritten_bound [DecidableEq α] : cellsWritten (α:=α) ≤ (Fintype.card α+1)^2 := by + unfold cellsWritten + nlinarith + +end MatchingFPRAS.ComputableReach + +end OAI diff --git a/lean/OAI/Combinatorics/MatchingCount/Sampling/ChosenChord.lean b/lean/OAI/Combinatorics/MatchingCount/Sampling/ChosenChord.lean new file mode 100644 index 0000000000000000000000000000000000000000..1daf04e0c07e24d06474e9bc29b52e3bfea40c46 --- /dev/null +++ b/lean/OAI/Combinatorics/MatchingCount/Sampling/ChosenChord.lean @@ -0,0 +1,392 @@ +import Mathlib +import OAI.Combinatorics.MatchingCount.Sampling.Components +import OAI.Combinatorics.MatchingCount.Sampling.Sewn + +namespace OAI + +namespace MatchingFPRAS.Transport.IndexedCycle + +variable {V L : Type*} [Fintype V] [DecidableEq V] [DecidableEq L] [Fintype L] + +variable {bags : V → Finset L} (c : IndexedCycle (BagEdge.Incident (bags := bags))) + +variable {G : SimpleGraph L} + +variable (hbags : ∀ v, ∀ a ∈ bags v, ∀ b ∈ bags v, a = b ∨ G.Adj a b) + +noncomputable def chosenChord (x y : ℕ) : BagEdge bags := by + classical + exact if h : x < y ∧ y < c.size ∧ (c.labelCycle hbags).Admissible x y then + c.chord hbags x y h.1 h.2.1 h.2.2 else c.edgeAt 0 + +omit [Fintype V] [DecidableEq V] [Fintype L] in +lemma chosenChord_eq (x y : ℕ) (hxy : x < y) (hy : y < c.size) + (ha : (c.labelCycle hbags).Admissible x y) : + c.chosenChord hbags x y = c.chord hbags x y hxy hy ha := by + unfold chosenChord + rw [dite_eq_left (show x < y ∧ y < c.size ∧ (c.labelCycle hbags).Admissible x y from ⟨hxy,hy,ha⟩)] + +noncomputable def diagramGain (R : Finset (BagEdge bags)) (f : Finset (BagEdge bags) → ℝ) + (x y : ℕ) : ℝ := c.signedGain R f x y (c.chosenChord hbags x y) + +noncomputable def diagramTerm (R : Finset (BagEdge bags)) (f : Finset (BagEdge bags) → ℝ) + (x p q y : ℕ) : ℝ := by + classical + exact if h : (c.labelCycle hbags).Cell x p q y ∧ y < c.size then + (c.cellCorners hbags h.1 h.2).signedLocalTerm (c.cellChords hbags h.1 h.2) + (c.cellChords_incidence hbags h.1 h.2) R f else 0 + +omit [Fintype V] [Fintype L] in +lemma diagramGain_short (R : Finset (BagEdge bags)) (f : Finset (BagEdge bags) → ℝ) + (x : ℕ) (hx : x + 1 < c.size) : c.diagramGain hbags R f x (x+1)=0 := by + have ha : (c.labelCycle hbags).Admissible x (x+1) := by + refine ⟨(c.edgeAt x).color, (c.edge_color_fixed hbags x).1, ?_⟩ + simpa only [Nat.cast_add, Nat.cast_one] using (c.edge_color_fixed hbags x).2 + unfold diagramGain + rw [c.chosenChord_eq hbags x (x+1) (by omega) hx ha, + c.chord_short hbags _ _ _ _ _ rfl] + exact c.signedGain_short R f x hx + +omit [Fintype V] [Fintype L] in +lemma diagramGain_root (R : Finset (BagEdge bags)) (f : Finset (BagEdge bags) → ℝ) : + c.diagramGain hbags R f 0 (c.size-1) = + f (R ∪ c.parityPattern 0) - f (R ∪ c.parityPattern 1) := by + have hm := c.four_le + have ha : (c.labelCycle hbags).Admissible 0 (c.size-1) := by + refine ⟨(c.edgeAt (c.size-1)).color, ?_, (c.edge_color_fixed hbags (c.size-1)).1⟩ + have hh := (c.edge_color_fixed hbags (c.size-1)).2 + have he : ((c.size-1 : ℕ) : ℤ)+1 = (0 : ℤ)+c.size := by omega + rw [he, c.labelSets_periodic hbags] at hh + simpa only [Nat.cast_zero] using hh + unfold diagramGain + rw [c.chosenChord_eq hbags 0 (c.size-1) (by omega) (by omega) ha, + c.chord_wrap hbags _ _ _ _ _ ⟨rfl,by omega⟩] + exact c.signedGain_root R f + +omit [Fintype V] [Fintype L] in +lemma diagram_cell_recurrence (R : Finset (BagEdge bags)) (f : Finset (BagEdge bags) → ℝ) + (x p q y : ℕ) (hc : (c.labelCycle hbags).Cell x p q y) (hy : y < c.size) : + c.diagramGain hbags R f x y = c.diagramTerm hbags R f x p q y + + c.diagramGain hbags R f x p + c.diagramGain hbags R f p q + + c.diagramGain hbags R f q y := by + have hxp := hc.first_pos + have hpq := hc.middle_pos + have hqy := hc.third_pos + have he : (c.labelCycle hbags).Admissible x y := by + obtain ⟨l,hl₁,hl₂⟩ := hc.exterior + exact ⟨l,hl₂,hl₁⟩ + unfold diagramGain diagramTerm + rw [dite_eq_left ⟨hc,hy⟩, + c.chosenChord_eq hbags x y (by omega) hy he, + c.chosenChord_eq hbags x p hxp (by omega) hc.first, + c.chosenChord_eq hbags p q hpq (by omega) hc.middle, + c.chosenChord_eq hbags q y hqy hy hc.third] + exact (c.cellCorners hbags hc hy).signed_cell_recurrence + (c.cellChords hbags hc hy) (c.cellChords_incidence hbags hc hy) R f + BagEdge.exists_incident + +omit [Fintype V] [Fintype L] in +theorem sum_cells_identity (R : Finset (BagEdge bags)) (f : Finset (BagEdge bags) → ℝ) + (Q : MatchingFPRAS.Cells.CycleData.Subdivision (c.labelCycle hbags) 0 (c.size-1)) : + f (R ∪ c.parityPattern 0) - f (R ∪ c.parityPattern 1) = + Q.sumCells (c.diagramTerm hbags R f) := by + rw [← c.diagramGain_root hbags R f] + exact Q.signed_cancellation_bounded (c.diagramGain hbags R f) (c.diagramTerm hbags R f) + (c.diagramGain_short hbags R f) (c.diagram_cell_recurrence hbags R f) + (by have := c.four_le; omega) + +end MatchingFPRAS.Transport.IndexedCycle + +namespace MatchingFPRAS.Cells.CycleData + +variable {L : Type*} [DecidableEq L] {G : SimpleGraph L} {m : ℕ} {C : CycleData G m} + +@[ext] structure CellIndex where + x : ℕ + p : ℕ + q : ℕ + y : ℕ + deriving DecidableEq + +namespace Subdivision + +variable {x y : ℕ} + +def cellList : {x y : ℕ} → Subdivision C x y → List CellIndex + | _, _, .edge _ => [] + | x, y, .node (p := p) (q := q) _ Q₁ Q₂ Q₃ => + ⟨x,p,q,y⟩ :: (Q₁.cellList ++ Q₂.cellList ++ Q₃.cellList) + +lemma mem_cellList {Q : Subdivision C x y} {a : CellIndex} (ha : a ∈ Q.cellList) : + x ≤ a.x ∧ a.y ≤ y ∧ C.Cell a.x a.p a.q a.y := by + induction Q with + | edge h => simp [cellList] at ha + | @node x p q y h Q₁ Q₂ Q₃ ih₁ ih₂ ih₃ => + simp only [cellList, List.mem_cons, List.mem_append] at ha + rcases ha with rfl | (ha | ha) | ha + · exact ⟨le_rfl, le_rfl, h⟩ + · obtain ⟨hx,hy,hc⟩ := ih₁ ha + exact ⟨hx, by have := h.middle_pos; have := h.third_pos; omega, hc⟩ + · obtain ⟨hx,hy,hc⟩ := ih₂ ha + exact ⟨by have := h.first_pos; omega, by have := h.third_pos; omega, hc⟩ + · obtain ⟨hx,hy,hc⟩ := ih₃ ha + exact ⟨by have := h.first_pos; have := h.middle_pos; omega, hy, hc⟩ + +lemma cellList_length (Q : Subdivision C x y) : Q.cellList.length = Q.cells := by + induction Q with + | edge h => rfl + | node h _ _ _ ih₁ ih₂ ih₃ => simp only [cellList, List.length_cons, + List.length_append, cells, ih₁, ih₂, ih₃]; omega + +lemma cellList_separated {x₁ y₁ x₂ y₂ : ℕ} (Q₁ : Subdivision C x₁ y₁) + (Q₂ : Subdivision C x₂ y₂) (h : y₁ ≤ x₂) : + ∀ a ∈ Q₁.cellList, ∀ b ∈ Q₂.cellList, a ≠ b := by + intro a ha b hb hab + subst b + obtain ⟨_,hy,hc⟩ := mem_cellList ha + obtain ⟨hx,_,_⟩ := mem_cellList hb + have := hc.first_pos + have := hc.middle_pos + have := hc.third_pos + omega + +lemma cellList_nodup (Q : Subdivision C x y) : Q.cellList.Nodup := by + induction Q with + | edge h => simp [cellList] + | @node x p q y h Q₁ Q₂ Q₃ ih₁ ih₂ ih₃ => + rw [cellList, List.nodup_cons] + refine ⟨?_, List.nodup_append.mpr ⟨List.nodup_append.mpr ⟨ih₁, ih₂, + cellList_separated Q₁ Q₂ le_rfl⟩, ih₃, ?_⟩⟩ + · intro ha + simp only [List.mem_append] at ha + rcases ha with (ha | ha) | ha + · have hh := (mem_cellList ha).2.1 + have := h.middle_pos + have := h.third_pos + simp only at hh + omega + · have hh := (mem_cellList ha).1 + have := h.first_pos + simp only at hh + omega + · have hh := (mem_cellList ha).1 + have := h.first_pos + have := h.middle_pos + simp only at hh + omega + · intro a ha b hb + rcases List.mem_append.mp ha with ha | ha + · exact cellList_separated Q₁ Q₃ (le_of_lt h.middle_pos) a ha b hb + · exact cellList_separated Q₂ Q₃ le_rfl a ha b hb + +def cellSet (Q : Subdivision C x y) : Finset CellIndex := Q.cellList.toFinset + +lemma cellSet_card (Q : Subdivision C x y) : Q.cellSet.card = Q.cells := by + rw [cellSet, List.toFinset_card_of_nodup Q.cellList_nodup, Q.cellList_length] + +lemma sumCells_eq_sum (Q : Subdivision C x y) (f : ℕ → ℕ → ℕ → ℕ → ℝ) : + Q.sumCells f = ∑ a ∈ Q.cellSet, f a.x a.p a.q a.y := by + rw [cellSet, List.sum_toFinset _ Q.cellList_nodup] + induction Q with + | edge h => rfl + | node h _ _ _ ih₁ ih₂ ih₃ => + simp only [sumCells, cellList, List.map_cons, List.map_append, List.sum_cons, + List.sum_append, ih₁, ih₂, ih₃] + ring + +end Subdivision + +end MatchingFPRAS.Cells.CycleData + +namespace MatchingFPRAS.Transport.IndexedCycle + +section + +variable {V L : Type*} [Fintype V] [DecidableEq V] [DecidableEq L] [Fintype L] + +variable {bags : V → Finset L} (c : IndexedCycle (BagEdge.Incident (bags := bags))) + +variable {G : SimpleGraph L} + +variable (hbags : ∀ v, ∀ a ∈ bags v, ∀ b ∈ bags v, a = b ∨ G.Adj a b) + +noncomputable def diagramEnergy (R : Finset (BagEdge bags)) (f : Finset (BagEdge bags) → ℝ) + (x p q y : ℕ) : ℝ := by + classical + exact if h : (c.labelCycle hbags).Cell x p q y ∧ y < c.size then + let P := c.pathsOfCell hbags h.1 h.2 + (f (R ∪ P.switched true) - f (R ∪ P.switched false))^2 + + (P.contextError R f true 2 0)^2 + (P.contextError R f false 3 1)^2 + else 0 + +omit [Fintype V] [Fintype L] in +lemma diagramEnergy_nonneg (R : Finset (BagEdge bags)) + (f : Finset (BagEdge bags) → ℝ) (x p q y : ℕ) : + 0 ≤ c.diagramEnergy hbags R f x p q y := by + unfold diagramEnergy + split_ifs <;> positivity + +omit [Fintype V] [Fintype L] in +lemma diagramTerm_sq_le (R : Finset (BagEdge bags)) + (f : Finset (BagEdge bags) → ℝ) (x p q y : ℕ) : + (c.diagramTerm hbags R f x p q y)^2 ≤ 3 * c.diagramEnergy hbags R f x p q y := by + classical + by_cases h : (c.labelCycle hbags).Cell x p q y ∧ y < c.size + · simp only [diagramTerm, diagramEnergy, dite_eq_left h] + let P := c.pathsOfCell hbags h.1 h.2 + let a := f (R ∪ P.switched true) - f (R ∪ P.switched false) + let b := P.contextError R f true 2 0 + let d := P.contextError R f false 3 1 + change (if x%2=0 then a+b-d else -(a+b-d))^2 ≤ 3*(a^2+b^2+d^2) + split_ifs <;> nlinarith [sq_nonneg (a-b), sq_nonneg (a+d), sq_nonneg (b+d)] + · simp only [diagramTerm, diagramEnergy, dite_eq_right h, zero_pow (by decide : 2≠0), mul_zero, + le_refl] + +omit [Fintype L] in +theorem cycle_cell_square_bound (R : Finset (BagEdge bags)) + (f : Finset (BagEdge bags) → ℝ) + (Q : MatchingFPRAS.Cells.CycleData.Subdivision (c.labelCycle hbags) 0 (c.size-1)) : + (f (R ∪ c.parityPattern 0) - f (R ∪ c.parityPattern 1))^2 ≤ + 3 * (Fintype.card V : ℝ) * + ∑ a ∈ Q.cellSet, c.diagramEnergy hbags R f a.x a.p a.q a.y := by + classical + let t := fun a : MatchingFPRAS.Cells.CycleData.CellIndex => + c.diagramTerm hbags R f a.x a.p a.q a.y + let e := fun a : MatchingFPRAS.Cells.CycleData.CellIndex => + c.diagramEnergy hbags R f a.x a.p a.q a.y + have hsum : 0 ≤ ∑ a ∈ Q.cellSet, e a := + Finset.sum_nonneg (fun a _ => c.diagramEnergy_nonneg hbags R f a.x a.p a.q a.y) + have hsize : c.size ≤ Fintype.card V := by + simpa only [Fintype.card_fin] using Fintype.card_le_of_injective c.vertex c.simple + have hcells : (Q.cellSet.card : ℝ) ≤ (Fintype.card V : ℝ) := by + apply Nat.cast_le.mpr + rw [Q.cellSet_card] + have := Q.cells_length + omega + have hcs := Finset.sum_mul_sq_le_sq_mul_sq Q.cellSet t (fun _ => (1:ℝ)) + simp only [mul_one, one_pow, Finset.sum_const, nsmul_eq_mul, mul_one] at hcs + have he : ∑ a ∈ Q.cellSet, (t a)^2 ≤ 3 * ∑ a ∈ Q.cellSet, e a := by + rw [Finset.mul_sum] + exact Finset.sum_le_sum (fun a _ => c.diagramTerm_sq_le hbags R f a.x a.p a.q a.y) + rw [c.sum_cells_identity hbags R f Q, Q.sumCells_eq_sum] + change (∑ a ∈ Q.cellSet, t a)^2 ≤ 3 * (Fintype.card V : ℝ) * ∑ a ∈ Q.cellSet, e a + calc + _ ≤ (∑ a ∈ Q.cellSet, t a^2) * (Q.cellSet.card : ℝ) := hcs + _ ≤ (3 * ∑ a ∈ Q.cellSet, e a) * (Q.cellSet.card : ℝ) := + mul_le_mul_of_nonneg_right he (Nat.cast_nonneg _) + _ ≤ (3 * ∑ a ∈ Q.cellSet, e a) * (Fintype.card V : ℝ) := + mul_le_mul_of_nonneg_left hcells (mul_nonneg (by norm_num) hsum) + _ = _ := by ring + +end + +variable {V L : Type*} [Fintype V] [DecidableEq V] [DecidableEq L] [Fintype L] + +variable {bags : V → Finset L} (c : IndexedCycle (BagEdge.Incident (bags := bags))) + +variable {G : SimpleGraph L} + +variable (hbags : ∀ v, ∀ a ∈ bags v, ∀ b ∈ bags v, a = b ∨ G.Adj a b) + +noncomputable def subdivision (hG : G.IsAcyclic) : + MatchingFPRAS.Cells.CycleData.Subdivision (c.labelCycle hbags) 0 (c.size-1) := + Classical.choice ((c.labelCycle hbags).quadrangulate hG c.four_le c.even) + +omit [Fintype L] in +theorem exchange_cell_square_bound {M N : Finset (BagEdge bags)} + (hM : MatchingOn BagEdge.Incident M Finset.univ) + (hN : MatchingOn BagEdge.Incident N Finset.univ) + (hU : ∀ i, c.edgeAt i ∈ M ∪ N) (hG : G.IsAcyclic) + (f : Finset (BagEdge bags) → ℝ) : + (f M - f (exchange M N c.edgeSet))^2 ≤ + 3 * (Fintype.card V : ℝ) * + ∑ a ∈ (c.subdivision hbags hG).cellSet, + c.diagramEnergy hbags (M \ c.edgeSet) f a.x a.p a.q a.y := by + classical + have hU' : ∀ i, c.edgeAt i ∈ N ∪ M := by simpa only [Finset.union_comm] using hU + have hpat := c.inter_edgeSet_parity hM hN hU + have hpat' := c.inter_edgeSet_parity hN hM hU' + have hcomp := c.cycle_edge_mem_complement hM hN hU 0 + have hMsplit : M = (M \ c.edgeSet) ∪ M ∩ c.edgeSet := by + ext e + simp only [Finset.mem_union,Finset.mem_sdiff,Finset.mem_inter] + tauto + have hX : exchange M N c.edgeSet = (M \ c.edgeSet) ∪ N ∩ c.edgeSet := rfl + rw [hpat] at hMsplit + rw [hpat'] at hX + have hb := c.cycle_cell_square_bound hbags (M \ c.edgeSet) f (c.subdivision hbags hG) + by_cases he : c.edgeAt 0 ∈ M + · have hn : c.edgeAt 0 ∉ N := fun hn => (hcomp.mp hn) he + simp only [ite_eq_left he,ite_eq_right hn] at hMsplit hX + calc + _ = (f ((M \ c.edgeSet) ∪ c.parityPattern 0) - + f ((M \ c.edgeSet) ∪ c.parityPattern 1))^2 := by rw [← hMsplit,← hX] + _ ≤ _ := hb + · have hn : c.edgeAt 0 ∈ N := by tauto + simp only [ite_eq_right he,ite_eq_left hn] at hMsplit hX + calc + _ = (f ((M \ c.edgeSet) ∪ c.parityPattern 1) - + f ((M \ c.edgeSet) ∪ c.parityPattern 0))^2 := by rw [← hMsplit,← hX] + _ = (f ((M \ c.edgeSet) ∪ c.parityPattern 0) - + f ((M \ c.edgeSet) ∪ c.parityPattern 1))^2 := by ring + _ ≤ _ := hb + +end MatchingFPRAS.Transport.IndexedCycle + +namespace MatchingFPRAS.Transport + +variable {V E : Type*} [Fintype V] [DecidableEq V] [Fintype E] [DecidableEq E] + +variable {inc : E → V → Prop} + +abbrev LongComponent (p : PM inc × PM inc) := + {S : Finset E // ∃ c : IndexedCycle inc, c.edgeSet = S ∧ ∀ i, c.edgeAt i ∈ p.1.val ∪ p.2.val} + +namespace LongComponent + +variable {p : PM inc × PM inc} (S : LongComponent p) + +noncomputable instance : Fintype (LongComponent p) := Fintype.ofFinite _ + +noncomputable def cycle : IndexedCycle inc := S.property.choose + +omit [DecidableEq V] [Fintype E] in +lemma cycle_set : S.cycle.edgeSet = S.val := S.property.choose_spec.1 + +omit [DecidableEq V] [Fintype E] in +lemma cycle_union : ∀ i, S.cycle.edgeAt i ∈ p.1.val ∪ p.2.val := S.property.choose_spec.2 + +omit [DecidableEq V] [Fintype E] in +lemma mem_components : S.val ∈ components (inc := inc) (p.1.val ∪ p.2.val) := + S.cycle_set ▸ S.cycle.edgeSet_mem_components p.1.property p.2.property S.cycle_union + +omit [DecidableEq V] [Fintype E] in +lemma anchor_recovers {T : LongComponent p} (h : S.cycle.edgeAt 0 = T.cycle.edgeAt 0) : S = T := by + apply Subtype.ext + rw [← S.cycle_set,← T.cycle_set,S.cycle.edgeSet_eq_component p.1.property p.2.property S.cycle_union, + T.cycle.edgeSet_eq_component p.1.property p.2.property T.cycle_union,h] + +end LongComponent + +end MatchingFPRAS.Transport + +namespace MatchingFPRAS.Transport.CellDemands + +variable {V L : Type*} [Fintype V] [DecidableEq V] [Fintype L] [DecidableEq L] + +variable {bags : V → Finset L} + +noncomputable local instance : Fintype (BagEdge bags) := Fintype.ofFinite _ + +variable {G : SimpleGraph L} + +variable (hbags : ∀ v, ∀ a ∈ bags v, ∀ b ∈ bags v, a = b ∨ G.Adj a b) + +variable (hG : G.IsAcyclic) + +abbrev Demand := Σ p : PM (BagEdge.Incident (bags := bags)) × PM BagEdge.Incident, + Σ S : LongComponent p, ↥(S.cycle.subdivision hbags hG).cellSet + +end MatchingFPRAS.Transport.CellDemands + +end OAI diff --git a/lean/OAI/Combinatorics/MatchingCount/Sampling/ClippedEnvelope.lean b/lean/OAI/Combinatorics/MatchingCount/Sampling/ClippedEnvelope.lean new file mode 100644 index 0000000000000000000000000000000000000000..a0665faca4935fa421722c7617a8bd82225994f9 --- /dev/null +++ b/lean/OAI/Combinatorics/MatchingCount/Sampling/ClippedEnvelope.lean @@ -0,0 +1,54 @@ +import Mathlib +import OAI.Combinatorics.MatchingCount.Sampling.DPEnvelope + +namespace OAI + +namespace MatchingFPRAS.UnitRefresh.Materialized +open Finset + +variable {V : Type} [Fintype V] {m : ℕ} +def nextEnvelope (bags : V → Finset (Fin m)) (R : Finset V) + (parent : Fin m → Option (Fin m)) (l : Fin m) (w : Fin m → ℕ) : Fin m → ℕ := + match parent l with | none=>w | some p=>mergeEnvelope w l p (sharedCount bags R l) +omit [Fintype V] in +lemma nextEnvelope_pos (bags : V → Finset (Fin m)) (R : Finset V) + (parent : Fin m → Option (Fin m)) (l : Fin m) (w : Fin m → ℕ) (hw : ∀ a,1≤w a) : + ∀ a,1≤nextEnvelope bags R parent l w a := by + cases hp : parent l with + | none => simpa only [nextEnvelope,hp] using hw + | some p => simpa only [nextEnvelope,hp] using mergeEnvelope_pos w hw l p (sharedCount bags R l) +lemma nextEnvelope_product (bags : V → Finset (Fin m)) (R : Finset V) + (parent : Fin m → Option (Fin m)) (l : Fin m) (w : Fin m → ℕ) + (hp : ∀ p,parent l=some p → p≠l) : + (∏ a,nextEnvelope bags R parent l w a)≤2^(Fintype.card V)*(∏ a,w a) := by + cases he : parent l with + | none => + simp only [nextEnvelope,he] + exact Nat.le_mul_of_pos_left _ (by positivity) + | some p => + simp only [nextEnvelope,he] + rw [mergeEnvelope_prod w l p (hp p he)] + exact Nat.mul_le_mul_right _ (Nat.pow_le_pow_right (by decide) (sharedCount_le_card bags R l)) +lemma nextEnvelope_power (bags : V → Finset (Fin m)) (R : Finset V) + (parent : Fin m → Option (Fin m)) (l : Fin m) (w : Fin m → ℕ) + (hp : ∀ p,parent l=some p → p≠l) (E : ℕ) (he : (∏ a,w a)≤2^E) : + (∏ a,nextEnvelope bags R parent l w a)≤2^(E+Fintype.card V) := by + apply (nextEnvelope_product bags R parent l w hp).trans + rw [pow_add] + simpa only [Nat.mul_comm] using Nat.mul_le_mul_left (2^(Fintype.card V)) he +lemma entry_size_budget (bags : V → Finset (Fin m)) (R : Finset V) + (parent : Fin m → Option (Fin m)) (l : Fin m) (t : Table) (w : Fin m → ℕ) + (hw : ∀ a,1≤w a) (ht : RowBound t w) + (hp : ∀ p,parent l=some p → p≠l) (E K : ℕ) (he : (∏ a,w a)≤2^E) + (hK : E+Fintype.card V+1≤K) (a : Fin m) (r : ℕ) : + (entry bags R parent l a t r).size≤K := by + have hv:=nextEnvelope_pos bags R parent l w hw + have hb : entry bags R parent l a t r≤nextEnvelope bags R parent l w a := by + cases h : parent l <;> simpa only [nextEnvelope,h] using entry_rowBound bags R parent l t w hw ht a r + have hprod:=nextEnvelope_power bags R parent l w hp E he + have hval : entry bags R parent l a t r≤2^(E+Fintype.card V) := + hb.trans ((single_le_prod (fun x _=>hv x) (mem_univ a)).trans hprod) + exact ((Nat.size_le_size hval).trans_eq (Nat.size_pow)).trans hK +end MatchingFPRAS.UnitRefresh.Materialized + +end OAI diff --git a/lean/OAI/Combinatorics/MatchingCount/Sampling/Component.lean b/lean/OAI/Combinatorics/MatchingCount/Sampling/Component.lean new file mode 100644 index 0000000000000000000000000000000000000000..e4a33f1739548af2987042e2d8e5e7b1614be57b --- /dev/null +++ b/lean/OAI/Combinatorics/MatchingCount/Sampling/Component.lean @@ -0,0 +1,399 @@ +import Mathlib +import OAI.Combinatorics.MatchingCount.Probability.LocalVariance +import OAI.Combinatorics.MatchingCount.Sampling.Certify + +namespace OAI + +namespace MatchingFPRAS.Transport.Sparse + +open Finset + +variable {V E : Type*} [Fintype V] [DecidableEq V] [Fintype E] [DecidableEq E] + +variable (ends : E → Sym2 V) + +instance decideOverlay (U : Finset E) : + DecidableRel (overlayLineGraph (fun e v => v ∈ ends e) U).Adj := by + intro e f + change Decidable (e ≠ f ∧ e ∈ U ∧ f ∈ U ∧ ∃ v, v ∈ ends e ∧ v ∈ ends f) + infer_instance + +def component (U : Finset E) (a : E) : Finset E := + U ∩ ComputableReach.closure (overlayLineGraph (fun e v => v ∈ ends e) U) a + +lemma component_eq (U : Finset E) (a : E) : + component ends U a = componentEdges (inc:=fun e v => v ∈ ends e) U a := by + ext e + simp only [component,mem_inter,ComputableReach.mem_closure,mem_componentEdges] + +def allComponents (U : Finset E) : Finset (Finset E) := U.image (component ends U) + +lemma allComponents_eq (U : Finset E) : + allComponents ends U = components (inc:=fun e v => v ∈ ends e) U := by + simp only [allComponents,components] + exact Finset.image_congr (fun a _ => component_eq ends U a) + +def discrepancies (A B : PM (fun e v => v ∈ ends e)) : Finset (Finset E) := + (allComponents ends (A.val ∪ B.val)).filter (fun S => ¬S ⊆ A.val ∩ B.val) + +lemma discrepancies_eq (A B : PM (fun e v => v ∈ ends e)) : + discrepancies ends A B = discrepancyComponents A B := by + rw [discrepancies,allComponents_eq] + rfl + +def cycle (p : PM (fun e v => v ∈ ends e) × PM (fun e v => v ∈ ends e)) + (S : Finset E) : PM (fun e v => v ∈ ends e) × PM (fun e v => v ∈ ends e) := + if h : S ∈ allComponents ends (p.1.val ∪ p.2.val) then + (⟨exchange p.1.val p.2.val S,exchange_matching p.1.property p.2.property + (component_exchange_compatible (by rwa [allComponents_eq] at h))⟩, + ⟨exchange p.2.val p.1.val S,exchange_matching p.2.property p.1.property + (component_exchange_compatible (by rwa [allComponents_eq] at h)).symm⟩) + else p + +lemma cycle_eq (p : PM (fun e v => v ∈ ends e) × PM (fun e v => v ∈ ends e)) (S : Finset E) : + cycle ends p S = cycleMove p S := by + unfold cycle cycleMove + simp only [allComponents_eq] + +lemma discrepancies_card (A B : PM (fun e v => v ∈ ends e)) : + (discrepancies ends A B).card ≤ A.val.card+B.val.card := by + calc + _ ≤ (allComponents ends (A.val ∪ B.val)).card := card_filter_le _ _ + _ ≤ (A.val ∪ B.val).card := card_image_le + _ ≤ _ := card_union_le _ _ + +end MatchingFPRAS.Transport.Sparse + +namespace MatchingFPRAS + +structure WeightedOptions (Ω : Type*) where + size : ℕ + out : Fin size → Ω + mass : Fin size → ℚ + nonneg : ∀ i, 0 ≤ mass i + total : ∑ i, mass i = 1 + +namespace WeightedOptions + +open Finset + +variable {Ω Ψ : Type*} + +def pure (a : Ω) : WeightedOptions Ω where + size := 1 + out := fun _ => a + mass := fun _ => 1 + nonneg := by simp + total := by simp + +def map (f : Ω → Ψ) (c : WeightedOptions Ω) : WeightedOptions Ψ where + size := c.size + out := f ∘ c.out + mass := c.mass + nonneg := c.nonneg + total := c.total + +def mix (p : ℚ) (hp : 0 ≤ p) (hp1 : p ≤ 1) + (a b : WeightedOptions Ω) : WeightedOptions Ω where + size := a.size+b.size + out := Fin.addCases a.out b.out + mass := Fin.addCases (fun i => p*a.mass i) (fun i => (1-p)*b.mass i) + nonneg i := by + refine Fin.addCases (fun i => ?_) (fun i => ?_) i + · simp only [Fin.addCases_left] + exact mul_nonneg hp (a.nonneg i) + · simp only [Fin.addCases_right] + exact mul_nonneg (sub_nonneg.mpr hp1) (b.nonneg i) + total := by + simp only [Fin.sum_univ_add,Fin.addCases_left,Fin.addCases_right,←mul_sum,a.total,b.total] + ring + +variable [DecidableEq Ω] + +def law (c : WeightedOptions Ω) (b : Ω) : ℚ := ∑ i, if c.out i=b then c.mass i else 0 + +lemma law_nonneg (c : WeightedOptions Ω) (b : Ω) : 0 ≤ c.law b := by + apply sum_nonneg + intro i _ + split_ifs <;> [exact c.nonneg i; exact le_rfl] + +lemma law_sum [Fintype Ω] (c : WeightedOptions Ω) : ∑ b, c.law b=1 := by + unfold law + rw [sum_comm] + simpa using c.total + +@[simp] lemma pure_law (a b : Ω) : (pure a).law b=if a=b then 1 else 0 := by + change (∑ _i : Fin 1, if a=b then (1:ℚ) else 0)=_ + simp + +lemma mix_law (p : ℚ) (hp : 0 ≤ p) (hp1 : p ≤ 1) (a b : WeightedOptions Ω) (x : Ω) : + (mix p hp hp1 a b).law x=p*a.law x+(1-p)*b.law x := by + change (∑ i : Fin (a.size+b.size), if Fin.addCases a.out b.out i=x then + Fin.addCases (fun i=>p*a.mass i) (fun i=>(1-p)*b.mass i) i else (0:ℚ))=_ + rw [Fin.sum_univ_add] + simp only [Fin.addCases_left,Fin.addCases_right,law,mul_sum] + congr 1 <;> apply sum_congr rfl <;> intro i _ <;> split_ifs <;> simp + +lemma sum_law_mul [Fintype Ω] (c : WeightedOptions Ω) (f : Ω → ℚ) : + ∑ b, c.law b*f b = ∑ i, c.mass i*f (c.out i) := by + simp only [law,sum_mul] + rw [sum_comm] + apply sum_congr rfl + intro i _ + simp only [ite_mul,zero_mul] + simp + +lemma map_law [Fintype Ω] [DecidableEq Ψ] (f : Ω → Ψ) (c : WeightedOptions Ω) (b : Ψ) : + (c.map f).law b = ∑ a, if f a=b then c.law a else 0 := by + change (∑ i : Fin c.size, if f (c.out i)=b then c.mass i else (0:ℚ))=_ + calc + _ = ∑ i, c.mass i*(if f (c.out i)=b then 1 else 0) := by + simp only [mul_ite,mul_one,mul_zero] + _ = ∑ a, c.law a*(if f a=b then 1 else 0) := + (c.sum_law_mul (fun a => if f a=b then (1:ℚ) else 0)).symm + _ = _ := by simp + +lemma map_first_law [DecidableEq Ψ] (c : WeightedOptions Ω) (a : Ψ) (b : Ω × Ψ) : + (c.map (fun x => (x,a))).law b = if a=b.2 then c.law b.1 else 0 := by + change (∑ i : Fin c.size, if (c.out i,a)=b then c.mass i else (0:ℚ))=_ + rcases b with ⟨b,d⟩ + by_cases h : a=d + · subst d + simp [law] + · simp [h] + +def accept (c : WeightedOptions Ω) (hold : Ω) (p : Ω → ℚ) + (hp : ∀ a, 0 ≤ p a) (hp1 : ∀ a, p a ≤ 1) : WeightedOptions Ω where + size := c.size+c.size + out := Fin.addCases c.out (fun _ => hold) + mass := Fin.addCases (fun i => c.mass i*p (c.out i)) + (fun i => c.mass i*(1-p (c.out i))) + nonneg i := by + refine Fin.addCases (fun i => ?_) (fun i => ?_) i + · simp only [Fin.addCases_left] + exact mul_nonneg (c.nonneg i) (hp _) + · simp only [Fin.addCases_right] + exact mul_nonneg (c.nonneg i) (sub_nonneg.mpr (hp1 _)) + total := by + simp only [Fin.sum_univ_add,Fin.addCases_left,Fin.addCases_right,←sum_add_distrib] + simp only [←mul_add,add_sub_cancel,mul_one,c.total] + +lemma accept_law (c : WeightedOptions Ω) (hold : Ω) (p : Ω → ℚ) + (hp : ∀ a, 0 ≤ p a) (hp1 : ∀ a, p a ≤ 1) (b : Ω) : + (c.accept hold p hp hp1).law b = c.law b*p b + + if hold=b then ∑ i, c.mass i*(1-p (c.out i)) else 0 := by + change (∑ i : Fin (c.size+c.size), if Fin.addCases c.out (fun _=>hold) i=b then + Fin.addCases (fun i=>c.mass i*p (c.out i)) (fun i=>c.mass i*(1-p (c.out i))) i + else (0:ℚ))=_ + rw [Fin.sum_univ_add] + simp only [Fin.addCases_left,Fin.addCases_right] + congr 1 + · rw [law,sum_mul] + apply sum_congr rfl + intro i _ + split_ifs with h + · rw [h] + · simp + · split_ifs <;> simp_all + +variable [LinearOrder Ω] + +def numbering (s : Finset Ω) : Fin s.card ≃ ↥s := (s.orderIsoOfFin rfl).toEquiv + +def uniform (s : Finset Ω) (hs : s.Nonempty) : WeightedOptions Ω where + size := s.card + out := fun i => (numbering s i).val + mass := fun _ => (s.card:ℚ)⁻¹ + nonneg := by intro i; positivity + total := by + have h : (s.card:ℚ) ≠ 0 := by exact_mod_cast hs.card_pos.ne' + simp [h] + +lemma uniform_law (s : Finset Ω) (hs : s.Nonempty) (b : Ω) : + (uniform s hs).law b=if b ∈ s then (s.card:ℚ)⁻¹ else 0 := by + unfold law uniform + change (∑ i, if (numbering s i).val=b then (s.card:ℚ)⁻¹ else 0)=_ + rw [(numbering s).sum_comp (fun i : ↥s => if i.val=b then (s.card:ℚ)⁻¹ else 0)] + rw [Finset.sum_coe_sort s (fun x : Ω => if x=b then (s.card:ℚ)⁻¹ else 0)] + simp + +def neighbors (a : Ω) (s : Finset Ω) (d : ℕ) (hd : s.card ≤ d) : WeightedOptions Ω where + size := s.card+1 + out := Fin.lastCases a (fun i => (numbering s i).val) + mass := Fin.lastCases (1-(s.card:ℚ)/d) (fun _ => (d:ℚ)⁻¹) + nonneg i := by + refine Fin.lastCases ?_ (fun j => ?_) i + · simp only [Fin.lastCases_last] + by_cases h : d=0 + · simp [h] + · have hh : (0:ℚ) if i.val=b then (d:ℚ)⁻¹ else 0)] + rw [Finset.sum_coe_sort s (fun x : Ω => if x=b then (d:ℚ)⁻¹ else 0)] + simp + +end WeightedOptions + +end MatchingFPRAS + +namespace MatchingFPRAS.Transport.Sparse + +open Finset WeightedOptions + +variable {Ω : Type*} [Fintype Ω] [LinearOrder Ω] [DecidableEq Ω] + +omit [LinearOrder Ω] in +lemma erased_eq (R : Ω → Ω → Prop) (s : Finset Ω) (a : Ω) + (hs : ∀ b, b ∈ s ↔ R a b) : s.erase a = relationDestinations R a := by + classical + ext b + simp only [mem_erase,relationDestinations,mem_filter,mem_univ,true_and,hs,ne_comm] + +lemma neighbors_real (R : Ω → Ω → Prop) (s : Finset Ω) (d : ℕ) (a b : Ω) + (hs : s=relationDestinations R a) (hd : s.card ≤ d) : + ((WeightedOptions.neighbors a s d hd).law b : ℝ) = relationProposal R d a b := by + classical + rw [WeightedOptions.neighbors_law] + push_cast + subst s + rw [relationProposal,relationOff_sum] + by_cases hab : a=b + · subst b + simp [relationDestinations] + · simp only [hab,ite_false,relationOff] + split_ifs <;> push_cast <;> simp + +variable {V E : Type*} [Fintype V] [DecidableEq V] [Fintype E] [LinearOrder E] + +variable (ends : E → Sym2 V) + +local instance finsetOrder : LinearOrder (Finset E) := + LinearOrder.lift' toColex toColex.injective + +local instance pmOrder : LinearOrder (PM (fun e v => v ∈ ends e)) := + LinearOrder.lift' Subtype.val Subtype.val_injective + +lemma color_degree (hloop : ∀ e, ¬(ends e).IsDiag) + (hpar : ∀ e, (univ.filter (fun f => ends f = ends e)).card ≤ 2) + (A : PM (fun e v => v ∈ ends e)) : ((colors ends A).erase A).card ≤ Fintype.card V := + (card_erase_le).trans ((colors_card ends hpar A).trans_eq (A.twice_card ends hloop)) + +lemma switch_degree (hloop : ∀ e, ¬(ends e).IsDiag) + (hpar : ∀ e, (univ.filter (fun f => ends f = ends e)).card ≤ 2) + (A : PM (fun e v => v ∈ ends e)) : + ((switches ends A).erase A).card ≤ 8*(Fintype.card V/2).choose 2 := by + have h : Fintype.card V/2=A.val.card := by have := A.twice_card ends hloop; omega + rw [h] + exact card_erase_le.trans (switches_card ends hpar A) + +def colorTable (hloop : ∀ e, ¬(ends e).IsDiag) + (hpar : ∀ e, (univ.filter (fun f => ends f = ends e)).card ≤ 2) + (A : PM (fun e v => v ∈ ends e)) : WeightedOptions (PM (fun e v => v ∈ ends e)) := + WeightedOptions.neighbors A ((colors ends A).erase A) (Fintype.card V) + (color_degree ends hloop hpar A) + +def switchTable (hloop : ∀ e, ¬(ends e).IsDiag) + (hpar : ∀ e, (univ.filter (fun f => ends f = ends e)).card ≤ 2) + (A : PM (fun e v => v ∈ ends e)) : WeightedOptions (PM (fun e v => v ∈ ends e)) := + WeightedOptions.neighbors A ((switches ends A).erase A) (8*(Fintype.card V/2).choose 2) + (switch_degree ends hloop hpar A) + +lemma colorTable_law (hloop : ∀ e, ¬(ends e).IsDiag) + (hpar : ∀ e, (univ.filter (fun f => ends f = ends e)).card ≤ 2) + (A B : PM (fun e v => v ∈ ends e)) : + ((colorTable ends hloop hpar A).law B : ℝ)=colorProposal ends A B := by + exact neighbors_real (ColorChange ends) ((colors ends A).erase A) (Fintype.card V) A B + (erased_eq _ _ _ (mem_colors ends A)) (color_degree ends hloop hpar A) + +lemma switchTable_law (hloop : ∀ e, ¬(ends e).IsDiag) + (hpar : ∀ e, (univ.filter (fun f => ends f = ends e)).card ≤ 2) + (A B : PM (fun e v => v ∈ ends e)) : + ((switchTable ends hloop hpar A).law B : ℝ)=switchProposal ends A B := by + exact neighbors_real (fun A B => TwoEdgeSwitch A B) ((switches ends A).erase A) + (8*(Fintype.card V/2).choose 2) A B + (erased_eq _ _ _ (mem_switches ends A)) (switch_degree ends hloop hpar A) + +def cycleTable (p : PM (fun e v => v ∈ ends e) × PM (fun e v => v ∈ ends e)) : + WeightedOptions (PM (fun e v => v ∈ ends e) × PM (fun e v => v ∈ ends e)) := + if h : (discrepancies ends p.1 p.2).Nonempty then + (WeightedOptions.uniform _ h).map (cycle ends p) + else WeightedOptions.pure p + +lemma cycleTable_law (p q : PM (fun e v => v ∈ ends e) × PM (fun e v => v ∈ ends e)) : + ((cycleTable ends p).law q : ℝ)=cycleProposal p q := by + classical + by_cases h : (discrepancies ends p.1 p.2).Nonempty + · have h' : (discrepancyComponents p.1 p.2).Nonempty := by rwa [←discrepancies_eq] + rw [cycleTable,dite_eq_left h,cycleProposal,ite_eq_left h',WeightedOptions.map_law] + push_cast + apply sum_congr rfl + intro S _ + rw [WeightedOptions.uniform_law,cycle_eq,discrepancies_eq] + unfold cycleTerm + split_ifs <;> simp_all + · have h' : ¬(discrepancyComponents p.1 p.2).Nonempty := by rwa [←discrepancies_eq] + rw [cycleTable,dite_eq_right h,cycleProposal,ite_eq_right h',WeightedOptions.pure_law] + split_ifs <;> norm_num + +def pairTable (hloop : ∀ e, ¬(ends e).IsDiag) + (hpar : ∀ e, (univ.filter (fun f => ends f = ends e)).card ≤ 2) + (p : PM (fun e v => v ∈ ends e) × PM (fun e v => v ∈ ends e)) : + WeightedOptions (PM (fun e v => v ∈ ends e) × PM (fun e v => v ∈ ends e)) := + WeightedOptions.mix (1/3) (by norm_num) (by norm_num) + ((switchTable ends hloop hpar p.1).map (fun x => (x,p.2))) + (WeightedOptions.mix (1/2) (by norm_num) (by norm_num) + ((colorTable ends hloop hpar p.1).map (fun x => (x,p.2))) + (cycleTable ends p)) + +lemma pairTable_law (hloop : ∀ e, ¬(ends e).IsDiag) + (hpar : ∀ e, (univ.filter (fun f => ends f = ends e)).card ≤ 2) + (p q : PM (fun e v => v ∈ ends e) × PM (fun e v => v ∈ ends e)) : + ((pairTable ends hloop hpar p).law q : ℝ)=pairProposalRaw ends p q := by + unfold pairTable + rw [WeightedOptions.mix_law,WeightedOptions.mix_law, + WeightedOptions.map_first_law,WeightedOptions.map_first_law] + push_cast + unfold pairProposalRaw firstLift + by_cases h : p.2=q.2 + · simp only [ite_eq_left h] + rw [switchTable_law,colorTable_law,cycleTable_law] + ring + · simp only [ite_eq_right h] + push_cast + rw [cycleTable_law] + ring + +lemma pairTable_size (hloop : ∀ e, ¬(ends e).IsDiag) + (hpar : ∀ e, (univ.filter (fun f => ends f = ends e)).card ≤ 2) + (p : PM (fun e v => v ∈ ends e) × PM (fun e v => v ∈ ends e)) : + (pairTable ends hloop hpar p).size ≤ + 8*p.1.val.card.choose 2 + 2*p.1.val.card + (p.1.val.card+p.2.val.card)+3 := by + have hs : ((switches ends p.1).erase p.1).card ≤ 8*p.1.val.card.choose 2 := card_erase_le.trans (switches_card ends hpar p.1) + have hc : ((colors ends p.1).erase p.1).card ≤ 2*p.1.val.card := card_erase_le.trans (colors_card ends hpar p.1) + have hy := discrepancies_card ends p.1 p.2 + simp only [pairTable,WeightedOptions.mix,WeightedOptions.map,switchTable,colorTable, + WeightedOptions.neighbors] + have hz : (cycleTable ends p).size ≤ p.1.val.card+p.2.val.card+1 := by + unfold cycleTable + split_ifs <;> simp only [WeightedOptions.map,WeightedOptions.uniform,WeightedOptions.pure] + · omega + · omega + omega + +end MatchingFPRAS.Transport.Sparse + +end OAI diff --git a/lean/OAI/Combinatorics/MatchingCount/Sampling/ComponentOrder.lean b/lean/OAI/Combinatorics/MatchingCount/Sampling/ComponentOrder.lean new file mode 100644 index 0000000000000000000000000000000000000000..df20311d18a3450b9a11f350b9c905340cf11d44 --- /dev/null +++ b/lean/OAI/Combinatorics/MatchingCount/Sampling/ComponentOrder.lean @@ -0,0 +1,453 @@ +import Mathlib +import OAI.Combinatorics.MatchingCount.Graphs.SafeSwitch +import OAI.Combinatorics.MatchingCount.Sampling.Underlying + +namespace OAI + +namespace MatchingFPRAS.Transport + +section + +variable {V E : Type*} [Fintype V] [DecidableEq V] [DecidableEq E] + +variable {inc : E → V → Prop} + +noncomputable def componentOrder (U : Finset E) : + Fin (components (inc := inc) U).card ≃ ↥(components (inc := inc) U) := + (Fintype.equivFinOfCardEq (Fintype.card_coe _)).symm + +noncomputable def componentPrefix (U : Finset E) (i : ℕ) : Finset E := by + classical + exact (Finset.univ.filter (fun j : Fin (components (inc := inc) U).card => j.val < i)).biUnion + (fun j => (componentOrder (inc := inc) U j).val) + +omit [Fintype V] [DecidableEq V] in +lemma mem_componentPrefix (U : Finset E) (i : ℕ) (e : E) : + e ∈ componentPrefix (inc := inc) U i ↔ + ∃ j : Fin (components (inc := inc) U).card, j.val < i ∧ e ∈ (componentOrder (inc := inc) U j).val := by + classical + simp only [componentPrefix, Finset.mem_biUnion, Finset.mem_filter, Finset.mem_univ, + true_and] + +omit [Fintype V] [DecidableEq V] in +lemma componentPrefix_zero (U : Finset E) : componentPrefix (inc := inc) U 0 = ∅ := by + ext e + simp [mem_componentPrefix] + +omit [Fintype V] [DecidableEq V] in +lemma componentPrefix_succ (U : Finset E) (i : ℕ) (hi : i < (components (inc := inc) U).card) : + componentPrefix (inc := inc) U (i+1) = + componentPrefix (inc := inc) U i ∪ (componentOrder (inc := inc) U ⟨i,hi⟩).val := by + ext e + simp only [mem_componentPrefix, Finset.mem_union] + constructor + · rintro ⟨j,hj,he⟩ + by_cases hji : j.val < i + · exact Or.inl ⟨j,hji,he⟩ + · have hje : j = ⟨i,hi⟩ := Fin.ext (by change j.val = i; omega) + exact Or.inr (hje ▸ he) + · rintro (⟨j,hj,he⟩ | he) + · exact ⟨j,by omega,he⟩ + · exact ⟨⟨i,hi⟩,by change i < i+1; omega,he⟩ + +omit [Fintype V] [DecidableEq V] in +lemma componentPrefix_full (U : Finset E) : + componentPrefix (inc := inc) U (components (inc := inc) U).card = U := by + rw [← components_cover (inc := inc) U] + conv_lhs => rw [components_cover] + ext e + simp only [mem_componentPrefix, Finset.mem_biUnion, id_eq] + constructor + · rintro ⟨j,_,he⟩ + exact ⟨(componentOrder U j).val, (componentOrder U j).property, he⟩ + · rintro ⟨S,hS,he⟩ + obtain ⟨j,hj⟩ := (componentOrder (inc := inc) U).surjective ⟨S,hS⟩ + exact ⟨j,j.isLt,by simpa only [hj] using he⟩ + +omit [Fintype V] [DecidableEq V] in +lemma componentPrefix_disjoint (U : Finset E) (i : ℕ) + (hi : i < (components (inc := inc) U).card) : + Disjoint (componentPrefix (inc := inc) U i) (componentOrder (inc := inc) U ⟨i,hi⟩).val := by + apply Finset.disjoint_left.mpr + intro e he hf + obtain ⟨j,hj,he⟩ := (mem_componentPrefix U i e).mp he + have hne : (componentOrder (inc := inc) U j).val ≠ + (componentOrder (inc := inc) U ⟨i,hi⟩).val := by + intro heq + have hh := (componentOrder (inc := inc) U).injective (Subtype.ext heq) + have hv : j.val = i := congrArg Fin.val hh + omega + exact Finset.disjoint_left.mp + (components_pairwise_disjoint U (componentOrder U j).property + (componentOrder U ⟨i,hi⟩).property hne) he hf + +omit [Fintype V] [DecidableEq V] in +lemma componentPrefix_compatible (M N : Finset E) (i : ℕ) : + ExchangeCompatible (inc := inc) M N (componentPrefix (inc := inc) (M ∪ N) i) := by + intro e he f hf v hev hfv + simp only [mem_componentPrefix] + constructor + · rintro ⟨j,hj,he'⟩ + exact ⟨j,hj,(component_exchange_compatible (componentOrder (M ∪ N) j).property + e he f hf v hev hfv).mp he'⟩ + · rintro ⟨j,hj,hf'⟩ + exact ⟨j,hj,(component_exchange_compatible (componentOrder (M ∪ N) j).property + e he f hf v hev hfv).mpr hf'⟩ + +lemma exchange_empty (M N : Finset E) : exchange M N ∅ = M := by + simp [exchange] + +lemma exchange_all (M N : Finset E) : exchange M N (M ∪ N) = N := by + ext e + simp only [mem_exchange, Finset.mem_union] + tauto + +lemma exchange_disjoint_composition (M N S T : Finset E) (h : Disjoint S T) : + exchange (exchange M N S) (exchange N M S) T = exchange M N (S ∪ T) := by + rw [exchange_composition] + congr 1 + ext e + have hh : e ∈ S → e ∉ T := fun he => Finset.disjoint_left.mp h he + simp only [Finset.mem_symmDiff, Finset.mem_union] + tauto + +omit [Fintype V] [DecidableEq V] in +lemma componentPrefix_step (M N : Finset E) (i : ℕ) + (hi : i < (components (inc := inc) (M ∪ N)).card) : + exchange M N (componentPrefix (inc := inc) (M ∪ N) (i+1)) = + exchange (exchange M N (componentPrefix (inc := inc) (M ∪ N) i)) + (exchange N M (componentPrefix (inc := inc) (M ∪ N) i)) + (componentOrder (inc := inc) (M ∪ N) ⟨i,hi⟩).val := by + rw [componentPrefix_succ _ _ hi, + exchange_disjoint_composition M N _ _ (componentPrefix_disjoint _ _ hi)] + +end + +section + +variable {V E : Type*} [Fintype V] [DecidableEq V] [Fintype E] [DecidableEq E] + +variable {inc : E → V → Prop} + +noncomputable def prefixPair (p : PM inc × PM inc) (i : ℕ) : PM inc × PM inc := + (⟨exchange p.1.val p.2.val (componentPrefix (inc := inc) (p.1.val ∪ p.2.val) i), + exchange_matching p.1.property p.2.property (componentPrefix_compatible _ _ _)⟩, + ⟨exchange p.2.val p.1.val (componentPrefix (inc := inc) (p.1.val ∪ p.2.val) i), + exchange_matching p.2.property p.1.property (componentPrefix_compatible _ _ _).symm⟩) + +omit [DecidableEq V] [Fintype E] in +lemma prefixPair_union (p : PM inc × PM inc) (i : ℕ) : + (prefixPair p i).1.val ∪ (prefixPair p i).2.val = p.1.val ∪ p.2.val := + exchange_union _ _ _ + +omit [DecidableEq V] [Fintype E] in +lemma prefixPair_involutive (i : ℕ) : Function.Involutive (fun p : PM inc × PM inc => prefixPair p i) := by + intro p + have hu := prefixPair_union p i + apply Prod.ext <;> apply Subtype.ext + · change exchange (prefixPair p i).1.val (prefixPair p i).2.val + (componentPrefix (inc := inc) ((prefixPair p i).1.val ∪ (prefixPair p i).2.val) i) = _ + rw [hu] + exact exchange_involution _ _ _ + · change exchange (prefixPair p i).2.val (prefixPair p i).1.val + (componentPrefix (inc := inc) ((prefixPair p i).1.val ∪ (prefixPair p i).2.val) i) = _ + rw [hu] + exact exchange_involution _ _ _ + +omit [DecidableEq V] [Fintype E] in +lemma prefixPair_zero (p : PM inc × PM inc) : prefixPair p 0 = p := by + apply Prod.ext <;> apply Subtype.ext <;> simp [prefixPair, componentPrefix_zero, exchange_empty] + +omit [Fintype V] [DecidableEq V] [Fintype E] in +lemma componentPrefix_eq_full (U : Finset E) (i : ℕ) + (hi : (components (inc := inc) U).card ≤ i) : componentPrefix (inc := inc) U i = U := by + calc + _ = componentPrefix (inc := inc) U (components (inc := inc) U).card := by + apply Finset.ext + intro e + simp only [mem_componentPrefix] + constructor + · rintro ⟨j,_,he⟩ + exact ⟨j,j.isLt,he⟩ + · rintro ⟨j,_,he⟩ + exact ⟨j,Nat.lt_of_lt_of_le j.isLt hi,he⟩ + _ = U := componentPrefix_full U + +omit [DecidableEq V] [Fintype E] in +lemma prefixPair_full (p : PM inc × PM inc) (i : ℕ) + (hi : (components (inc := inc) (p.1.val ∪ p.2.val)).card ≤ i) : + prefixPair p i = (p.2,p.1) := by + apply Prod.ext <;> apply Subtype.ext + · dsimp only [prefixPair] + rw [componentPrefix_eq_full _ _ hi, exchange_all] + · dsimp only [prefixPair] + rw [componentPrefix_eq_full _ _ hi, Finset.union_comm p.1.val p.2.val, exchange_all] + +noncomputable def componentAt (U : Finset E) (i : ℕ) : Finset E := + if h : i < (components (inc := inc) U).card then (componentOrder (inc := inc) U ⟨i,h⟩).val else ∅ + +omit [Fintype V] [DecidableEq V] [Fintype E] in +lemma componentAt_compatible (M N : Finset E) (i : ℕ) : + ExchangeCompatible (inc := inc) M N (componentAt (inc := inc) (M ∪ N) i) := by + classical + unfold componentAt + split_ifs with h + · exact component_exchange_compatible (componentOrder (M ∪ N) ⟨i,h⟩).property + · intro e he f hf v hev hfv + simp + +noncomputable def componentPair (p : PM inc × PM inc) (i : ℕ) : PM inc × PM inc := + (⟨exchange p.1.val p.2.val (componentAt (inc := inc) (p.1.val ∪ p.2.val) i), + exchange_matching p.1.property p.2.property (componentAt_compatible _ _ _)⟩, + ⟨exchange p.2.val p.1.val (componentAt (inc := inc) (p.1.val ∪ p.2.val) i), + exchange_matching p.2.property p.1.property (componentAt_compatible _ _ _).symm⟩) + +omit [DecidableEq V] [Fintype E] in +lemma prefixPair_step (p : PM inc × PM inc) (i : ℕ) : + prefixPair p (i+1) = componentPair (prefixPair p i) i := by + classical + by_cases h : i < (components (inc := inc) (p.1.val ∪ p.2.val)).card + · apply Prod.ext <;> apply Subtype.ext + · change exchange p.1.val p.2.val (componentPrefix (inc := inc) (p.1.val ∪ p.2.val) (i+1)) = + exchange (prefixPair p i).1.val (prefixPair p i).2.val + (componentAt (inc := inc) ((prefixPair p i).1.val ∪ (prefixPair p i).2.val) i) + rw [prefixPair_union, componentAt, dite_eq_left h] + exact componentPrefix_step _ _ _ h + · change exchange p.2.val p.1.val (componentPrefix (inc := inc) (p.1.val ∪ p.2.val) (i+1)) = + exchange (prefixPair p i).2.val (prefixPair p i).1.val + (componentAt (inc := inc) ((prefixPair p i).1.val ∪ (prefixPair p i).2.val) i) + rw [prefixPair_union, componentAt, dite_eq_left h, componentPrefix_succ _ _ h] + exact (exchange_disjoint_composition _ _ _ _ (componentPrefix_disjoint _ _ h)).symm + · have hle := Nat.le_of_not_gt h + rw [prefixPair_full p (i+1) (by omega), prefixPair_full p i hle] + apply Prod.ext <;> apply Subtype.ext <;> + simp only [componentPair, componentAt, Finset.union_comm p.2.val p.1.val, dite_eq_right h, + exchange_empty] + +omit [DecidableEq V] in +lemma prefixPair_gibbs (w : E → ℝ) (p : PM inc × PM inc) (i : ℕ) : + gibbs w (prefixPair p i).1 * gibbs w (prefixPair p i).2 = gibbs w p.1 * gibbs w p.2 := by + simp only [gibbs, div_mul_div_comm] + congr 1 + exact exchange_weight w _ _ _ + +noncomputable def componentDifference (f : PM inc → ℝ) (p : PM inc × PM inc) (i : ℕ) : ℝ := + f p.1 - f (componentPair p i).1 + +omit [DecidableEq V] [Fintype E] in +lemma prefix_difference_sum (f : PM inc → ℝ) (p : PM inc × PM inc) (n : ℕ) : + (∑ i ∈ Finset.range n, componentDifference f (prefixPair p i) i) = + f p.1 - f (prefixPair p n).1 := by + induction n with + | zero => simp [prefixPair_zero] + | succ n ih => + rw [Finset.sum_range_succ, ih] + simp only [componentDifference, ← prefixPair_step] + ring + +omit [DecidableEq V] [Fintype E] in +lemma canonical_path_square (hinc : ∀ e, ∃ v, inc e v) + (f : PM inc → ℝ) (p : PM inc × PM inc) : + (f p.1 - f p.2)^2 ≤ (Fintype.card V : ℝ) * + ∑ i ∈ Finset.range (Fintype.card V), (componentDifference f (prefixPair p i) i)^2 := by + classical + have hfull := prefixPair_full p (Fintype.card V) (components_card_le hinc _) + have hs := prefix_difference_sum f p (Fintype.card V) + rw [hfull] at hs + rw [← hs] + have hh := Finset.sum_mul_sq_le_sq_mul_sq (Finset.range (Fintype.card V)) + (fun i => componentDifference f (prefixPair p i) i) (fun _ => (1:ℝ)) + simpa only [mul_one, one_mul, one_pow, Finset.sum_const, Finset.card_range, nsmul_eq_mul, mul_comm] using hh + +omit [DecidableEq V] in +lemma sum_prefixPair (w : E → ℝ) (g : PM inc × PM inc → ℝ) (i : ℕ) : + letI : Fintype (PM inc) := Fintype.ofFinite _ + (∑ p : PM inc × PM inc, gibbs w p.1 * gibbs w p.2 * g (prefixPair p i)) = + ∑ p : PM inc × PM inc, gibbs w p.1 * gibbs w p.2 * g p := by + classical + let : Fintype (PM inc) := Fintype.ofFinite _ + let e := (prefixPair_involutive i).toPerm (fun p : PM inc × PM inc => prefixPair p i) + have hh := Equiv.sum_comp e (fun p => gibbs w p.1 * gibbs w p.2 * g p) + change (∑ p : PM inc × PM inc, gibbs w (prefixPair p i).1 * gibbs w (prefixPair p i).2 * + g (prefixPair p i)) = _ at hh + simpa only [prefixPair_gibbs] using hh + +omit [DecidableEq V] in +theorem cycle_demand_variance (hinc : ∀ e, ∃ v, inc e v) + (w : E → ℝ) (hw : ∀ e, 0 < w e) (f : PM inc → ℝ) : + letI : Fintype (PM inc) := Fintype.ofFinite _ + (∑ p : PM inc × PM inc, gibbs w p.1 * gibbs w p.2 * (f p.1 - f p.2)^2) / 2 ≤ + (Fintype.card V : ℝ) * ∑ p : PM inc × PM inc, + gibbs w p.1 * gibbs w p.2 * + ∑ i ∈ Finset.range (Fintype.card V), (componentDifference f p i)^2 := by + classical + let : Fintype (PM inc) := Fintype.ofFinite _ + have he : (∑ p : PM inc × PM inc, gibbs w p.1 * gibbs w p.2 * + ∑ i ∈ Finset.range (Fintype.card V), (componentDifference f (prefixPair p i) i)^2) = + ∑ p : PM inc × PM inc, gibbs w p.1 * gibbs w p.2 * + ∑ i ∈ Finset.range (Fintype.card V), (componentDifference f p i)^2 := by + simp_rw [Finset.mul_sum] + rw [Finset.sum_comm, Finset.sum_comm (s := Finset.univ) (t := Finset.range _)] + apply Finset.sum_congr rfl + intro i _ + exact sum_prefixPair w (fun p => (componentDifference f p i)^2) i + have hb := Finset.sum_le_sum (s := (Finset.univ : Finset (PM inc × PM inc))) + (fun p _ => mul_le_mul_of_nonneg_left (canonical_path_square hinc f p) + (mul_nonneg (le_of_lt (gibbs_pos w hw p.1)) (le_of_lt (gibbs_pos w hw p.2)))) + have hr : 0 ≤ (∑ p : PM inc × PM inc, gibbs w p.1 * gibbs w p.2 * (f p.1 - f p.2)^2) := + Finset.sum_nonneg (fun p _ => mul_nonneg + (mul_nonneg (le_of_lt (gibbs_pos w hw p.1)) (le_of_lt (gibbs_pos w hw p.2))) (sq_nonneg _)) + have hrew : (∑ p : PM inc × PM inc, gibbs w p.1 * gibbs w p.2 * + ((Fintype.card V : ℝ) * ∑ i ∈ Finset.range (Fintype.card V), + (componentDifference f (prefixPair p i) i)^2)) = + (Fintype.card V : ℝ) * ∑ p : PM inc × PM inc, gibbs w p.1 * gibbs w p.2 * + ∑ i ∈ Finset.range (Fintype.card V), (componentDifference f p i)^2 := by + rw [← he, Finset.mul_sum] + apply Finset.sum_congr rfl + intro p _ + ring + rw [hrew] at hb + linarith + +end + +variable {V E : Type*} [Fintype V] [DecidableEq V] [Fintype E] [DecidableEq E] + +variable (ends : E → Sym2 V) + +def ColorChange (A B : PM (fun e v => v ∈ ends e)) : Prop := + ∃ e f : E, ∃ R : Finset E, ends e = ends f ∧ A.val = R ∪ {e} ∧ B.val = R ∪ {f} + +noncomputable def colorDestinations (A : PM (fun e v => v ∈ ends e)) : + Finset (PM (fun e v => v ∈ ends e)) := by + classical + exact Finset.univ.filter (ColorChange ends A) + +omit [DecidableEq V] [Fintype E] in +lemma matching_inter_parallel {M : Finset E} + (hM : MatchingOn (fun e v => v ∈ ends e) M Finset.univ) + {e f : E} (he : e ∈ M) (hef : ends e = ends f) : M ∩ {e,f} = {e} := by + classical + obtain ⟨v,hv⟩ : ∃ v, v ∈ ends e := by + induction ends e using Sym2.inductionOn with | hf a b => exact ⟨a,by simp⟩ + ext a + simp only [Finset.mem_inter, Finset.mem_insert, Finset.mem_singleton] + constructor + · rintro ⟨ha, rfl | haf⟩ + · rfl + · subst a + exact hM.unique (Finset.mem_univ v) ha (hef ▸ hv) he hv + · rintro rfl + exact ⟨he,Or.inl rfl⟩ + +omit [DecidableEq V] [Fintype E] in +lemma parallel_exchange_color (p : PM (fun e v => v ∈ ends e) × PM (fun e v => v ∈ ends e)) + {S : Finset E} (hS : S ∈ components (inc := fun e v => v ∈ ends e) (p.1.val ∪ p.2.val)) + {e f : E} (he : e ∈ p.1.val) (hf : f ∈ p.2.val) (hef : ends e = ends f) (hset : S = {e,f}) : + ColorChange ends p.1 + ⟨exchange p.1.val p.2.val S,exchange_matching p.1.property p.2.property (component_exchange_compatible hS)⟩ := by + classical + refine ⟨e,f,p.1.val \ S,hef,?_,?_⟩ + · have h := matching_inter_parallel ends p.1.property he hef + rw [← hset] at h + rw [← h] + ext a + simp only [Finset.mem_union,Finset.mem_sdiff,Finset.mem_inter] + tauto + · change exchange p.1.val p.2.val S = _ + have h := matching_inter_parallel ends p.2.property hf hef.symm + rw [Finset.pair_comm,← hset] at h + exact congrArg ((p.1.val \ S) ∪ ·) h + +end MatchingFPRAS.Transport + +namespace MatchingFPRAS.Transport.CellDemands + +variable {V L : Type*} [Fintype V] [DecidableEq V] [Fintype L] [DecidableEq L] + +variable {bags : V → Finset L} {G : SimpleGraph L} + +noncomputable local instance : Fintype (BagEdge bags) := Fintype.ofFinite _ + +variable {hbags : ∀ v, ∀ a ∈ bags v, ∀ b ∈ bags v, a = b ∨ G.Adj a b} + +variable {hG : G.IsAcyclic} + +omit [Fintype L] in +lemma Demand.cellCost_nonneg (d : Demand hbags hG) (f : Finset (BagEdge bags) → ℝ) : + 0 ≤ d.cellCost f := by unfold Demand.cellCost; positivity + +omit [Fintype L] in +lemma Demand.cellCost_eq (d : Demand hbags hG) (f : Finset (BagEdge bags) → ℝ) : + d.cellCost f = d.cycle.diagramEnergy hbags d.outside f + d.2.2.val.x d.2.2.val.p d.2.2.val.q d.2.2.val.y := by + classical + rw [IndexedCycle.diagramEnergy, dite_eq_left ⟨d.cell,d.last_lt⟩] + rfl + +noncomputable def longCellCost (p : PM (BagEdge.Incident (bags := bags)) × PM (BagEdge.Incident (bags := bags))) + (f : Finset (BagEdge bags) → ℝ) : ℝ := + ∑ S : LongComponent p, ∑ a : ↥(S.cycle.subdivision hbags hG).cellSet, + (show Demand hbags hG from ⟨p,S,a⟩).cellCost f + +lemma longCellCost_nonneg (p : PM (BagEdge.Incident (bags := bags)) × PM (BagEdge.Incident (bags := bags))) + (f : Finset (BagEdge bags) → ℝ) : 0 ≤ longCellCost (hbags := hbags) (hG := hG) p f := + Finset.sum_nonneg (fun _ _ => Finset.sum_nonneg (fun _ _ => Demand.cellCost_nonneg _ _)) + +noncomputable def colorCost (A : PM (BagEdge.Incident (bags := bags))) + (f : Finset (BagEdge bags) → ℝ) : ℝ := + ∑ B ∈ colorDestinations (fun e : BagEdge bags => e.val.val.1) A, (f A.val-f B.val)^2 + +lemma colorCost_nonneg (A : PM (BagEdge.Incident (bags := bags))) + (f : Finset (BagEdge bags) → ℝ) : 0 ≤ colorCost A f := + Finset.sum_nonneg (fun _ _ => sq_nonneg _) + +theorem component_cell_bound + (p : PM (BagEdge.Incident (bags := bags)) × PM (BagEdge.Incident (bags := bags))) + (f : Finset (BagEdge bags) → ℝ) {S : Finset (BagEdge bags)} + (hS : S ∈ components (inc := BagEdge.Incident) (p.1.val ∪ p.2.val)) : + (f p.1.val - f (exchange p.1.val p.2.val S))^2 ≤ + 3 * (Fintype.card V : ℝ) * longCellCost (hbags := hbags) (hG := hG) p f + colorCost p.1 f := by + classical + rcases Overlay.component_classification (fun e : BagEdge bags => e.val.val.1) + (fun e => e.val.property) p.1.property p.2.property hS with h | ⟨c,hc,rfl⟩ + · obtain ⟨e,he,d,hd,hed,hset⟩ := h + have hcol := parallel_exchange_color (fun e : BagEdge bags => e.val.val.1) p hS he hd hed hset + have hle : (f p.1.val-f (exchange p.1.val p.2.val S))^2 ≤ colorCost p.1 f := by + exact Finset.single_le_sum (s := colorDestinations (fun e : BagEdge bags => e.val.val.1) p.1) + (a := ⟨exchange p.1.val p.2.val S,exchange_matching p.1.property p.2.property (component_exchange_compatible hS)⟩) + (f := fun B : PM BagEdge.Incident => (f p.1.val-f B.val)^2) + (fun _ _ => sq_nonneg _) (by + change _ ∈ Finset.univ.filter (ColorChange (fun e : BagEdge bags => e.val.val.1) p.1) + exact Finset.mem_filter.mpr ⟨Finset.mem_univ _,hcol⟩) + exact hle.trans (le_add_of_nonneg_left (mul_nonneg (by positivity) (longCellCost_nonneg p f))) + · let T : LongComponent p := ⟨c.edgeSet,c,rfl,hc⟩ + have hcell := T.cycle.exchange_cell_square_bound hbags p.1.property p.2.property T.cycle_union hG f + have hcost : (∑ a ∈ (T.cycle.subdivision hbags hG).cellSet, + T.cycle.diagramEnergy hbags (p.1.val \ T.cycle.edgeSet) f a.x a.p a.q a.y) = + ∑ a : ↥(T.cycle.subdivision hbags hG).cellSet, + (show Demand hbags hG from ⟨p,T,a⟩).cellCost f := by + rw [← Finset.sum_coe_sort] + apply Finset.sum_congr rfl + intro a _ + exact (Demand.cellCost_eq ⟨p,T,a⟩ f).symm + rw [hcost,T.cycle_set] at hcell + have hle : (∑ a : ↥(T.cycle.subdivision hbags hG).cellSet, + (show Demand hbags hG from ⟨p,T,a⟩).cellCost f) ≤ + longCellCost (hbags := hbags) (hG := hG) p f := + Finset.single_le_sum (f := fun S : LongComponent p => ∑ a : ↥(S.cycle.subdivision hbags hG).cellSet, + (show Demand hbags hG from ⟨p,S,a⟩).cellCost f) + (fun S _ => Finset.sum_nonneg (fun a _ => Demand.cellCost_nonneg ⟨p,S,a⟩ f)) (Finset.mem_univ T) + exact (hcell.trans (mul_le_mul_of_nonneg_left hle (by positivity))).trans + (le_add_of_nonneg_right (colorCost_nonneg p.1 f)) + +end MatchingFPRAS.Transport.CellDemands + +lemma arbitrary_sigma_sum {α : Type*} {β : α → Type*} [Fintype α] [∀ a, Fintype (β a)] + [i : Fintype (Sigma β)] (f : Sigma β → ℝ) : + (∑ d : Sigma β, f d) = ∑ a : α, ∑ b : β a, f ⟨a,b⟩ := by + have hi : i = Sigma.instFintype := Subsingleton.elim _ _ + subst hi + exact Fintype.sum_sigma f + +end OAI diff --git a/lean/OAI/Combinatorics/MatchingCount/Sampling/Components.lean b/lean/OAI/Combinatorics/MatchingCount/Sampling/Components.lean new file mode 100644 index 0000000000000000000000000000000000000000..7ad1c8c194ecba4c1da514f3532eabb71ee0e934 --- /dev/null +++ b/lean/OAI/Combinatorics/MatchingCount/Sampling/Components.lean @@ -0,0 +1,378 @@ +import Mathlib +import OAI.Combinatorics.MatchingCount.Sampling.IntervalPattern + +namespace OAI + +namespace MatchingFPRAS.Transport + +section + +variable {V E : Type*} [DecidableEq E] + +variable {inc : E → V → Prop} + +noncomputable def components (U : Finset E) : Finset (Finset E) := by + classical + exact U.image (componentEdges (inc := inc) U) + +lemma mem_components {U S : Finset E} : + S ∈ components (inc := inc) U ↔ ∃ a ∈ U, componentEdges (inc := inc) U a = S := by + classical + simp only [components, Finset.mem_image] + +omit [DecidableEq E] in +lemma componentEdges_subset (U : Finset E) (a : E) : componentEdges (inc := inc) U a ⊆ U := by + intro e he + exact ((mem_componentEdges U a e).mp he).1 + +omit [DecidableEq E] in +lemma componentEdges_self {U : Finset E} {a : E} (ha : a ∈ U) : + a ∈ componentEdges (inc := inc) U a := + (mem_componentEdges U a a).mpr ⟨ha,SimpleGraph.Reachable.refl a⟩ + +omit [DecidableEq E] in +lemma componentEdges_eq {U : Finset E} {a b : E} + (hab : (overlayLineGraph inc U).Reachable a b) : + componentEdges (inc := inc) U a = componentEdges (inc := inc) U b := by + ext e + simp only [mem_componentEdges] + exact and_congr_right (fun _ => ⟨fun h => hab.symm.trans h, fun h => hab.trans h⟩) + +lemma component_nonempty {U S : Finset E} (hS : S ∈ components (inc := inc) U) : S.Nonempty := by + obtain ⟨a,ha,rfl⟩ := mem_components.mp hS + exact ⟨a,componentEdges_self ha⟩ + +lemma component_subset {U S : Finset E} (hS : S ∈ components (inc := inc) U) : S ⊆ U := by + obtain ⟨a,ha,rfl⟩ := mem_components.mp hS + exact componentEdges_subset U a + +lemma component_eq_of_shares {U S T : Finset E} + (hS : S ∈ components (inc := inc) U) (hT : T ∈ components (inc := inc) U) + {e f : E} (he : e ∈ S) (hf : f ∈ T) {v : V} (hev : inc e v) (hfv : inc f v) : S=T := by + obtain ⟨a,ha,rfl⟩ := mem_components.mp hS + obtain ⟨b,hb,rfl⟩ := mem_components.mp hT + obtain ⟨heu,hra⟩ := (mem_componentEdges U a e).mp he + obtain ⟨hfu,hrb⟩ := (mem_componentEdges U b f).mp hf + exact componentEdges_eq ((hra.trans (shares_reachable heu hfu hev hfv)).trans hrb.symm) + +lemma components_pairwise_disjoint (U : Finset E) : + (components (inc := inc) U : Set (Finset E)).PairwiseDisjoint id := by + intro S hS T hT hne + apply Finset.disjoint_left.mpr + intro e he hf + apply hne + obtain ⟨a,ha,rfl⟩ := mem_components.mp hS + obtain ⟨b,hb,rfl⟩ := mem_components.mp hT + obtain ⟨_,hra⟩ := (mem_componentEdges U a e).mp he + obtain ⟨_,hrb⟩ := (mem_componentEdges U b e).mp hf + exact componentEdges_eq (hra.trans hrb.symm) + +lemma components_cover (U : Finset E) : (components (inc := inc) U).biUnion id = U := by + classical + ext e + simp only [Finset.mem_biUnion, id_eq] + constructor + · rintro ⟨S,hS,he⟩ + exact component_subset hS he + · intro he + exact ⟨componentEdges (inc := inc) U e, mem_components.mpr ⟨e,he,rfl⟩, + componentEdges_self he⟩ + +lemma component_exists_vertex (hinc : ∀ e, ∃ v, inc e v) + {U S : Finset E} (hS : S ∈ components (inc := inc) U) : + ∃ v, ∃ e ∈ S, inc e v := by + obtain ⟨e,he⟩ := component_nonempty hS + obtain ⟨v,hv⟩ := hinc e + exact ⟨v,e,he,hv⟩ + +noncomputable def componentVertex (hinc : ∀ e, ∃ v, inc e v) + {U : Finset E} (S : ↥(components (inc := inc) U)) : V := + (component_exists_vertex hinc S.property).choose + +lemma componentVertex_injective (hinc : ∀ e, ∃ v, inc e v) (U : Finset E) : + Function.Injective (componentVertex hinc (U := U)) := by + intro S T h + obtain ⟨e,he,hev⟩ := (component_exists_vertex hinc S.property).choose_spec + obtain ⟨f,hf,hfv⟩ := (component_exists_vertex hinc T.property).choose_spec + apply Subtype.ext + apply component_eq_of_shares S.property T.property he hf hev + change inc f (componentVertex hinc T) at hfv + change inc f (componentVertex hinc S) + rwa [h] + +lemma components_card_le [Fintype V] (hinc : ∀ e, ∃ v, inc e v) (U : Finset E) : + (components (inc := inc) U).card ≤ Fintype.card V := by + simpa only [Fintype.card_coe] using + Fintype.card_le_of_injective (componentVertex hinc (U := U)) (componentVertex_injective hinc U) + +lemma component_exchange_compatible {M N S : Finset E} + (hS : S ∈ components (inc := inc) (M ∪ N)) : ExchangeCompatible (inc := inc) M N S := by + obtain ⟨a,_,rfl⟩ := mem_components.mp hS + exact component_compatible M N a + + + +namespace IndexedCycle + +variable (c : IndexedCycle inc) + +noncomputable def edgeSet : Finset E := Finset.univ.image c.edge + +lemma mem_edgeSet (e : E) : e ∈ c.edgeSet ↔ ∃ i, i < c.size ∧ c.edgeAt i = e := by + simp only [edgeSet, Finset.mem_image, Finset.mem_univ, true_and] + constructor + · rintro ⟨i,rfl⟩ + exact ⟨i.val,i.isLt,by simp [edgeAt,index,Nat.mod_eq_of_lt i.isLt]⟩ + · rintro ⟨i,hi,rfl⟩ + exact ⟨c.index i,rfl⟩ + +lemma edgeAt_mem_edgeSet (i : ℕ) : c.edgeAt i ∈ c.edgeSet := by + apply (c.mem_edgeSet _).mpr + exact ⟨i % c.size,Nat.mod_lt _ (by have := c.four_le; omega), c.edgeAt_mod i⟩ + +lemma edgeSet_subset {U : Finset E} (hU : ∀ i, c.edgeAt i ∈ U) : c.edgeSet ⊆ U := by + intro e he + obtain ⟨i,_,rfl⟩ := (c.mem_edgeSet e).mp he + exact hU i + +omit [DecidableEq E] in +lemma previous_indices (i : ℕ) (hi : i < c.size) : + let j := (i+c.size-1) % c.size + c.index (j+1) = c.index i := by + dsimp only + apply Fin.ext + dsimp only [index] + rw [Nat.add_mod, Nat.mod_mod, ← Nat.add_mod] + have he : i + c.size - 1 + 1 = i + c.size := by have := c.four_le; omega + rw [he, Nat.add_mod, Nat.mod_self, add_zero, Nat.mod_mod] + +variable [Fintype V] + +lemma edge_incident_cycle_mem {M N : Finset E} + (hM : MatchingOn inc M Finset.univ) (hN : MatchingOn inc N Finset.univ) + (hU : ∀ i, c.edgeAt i ∈ M ∪ N) {e : E} (he : e ∈ M ∪ N) + (i : ℕ) (hi : i < c.size) (hev : inc e (c.vertexAt i)) : e ∈ c.edgeSet := by + let j := (i+c.size-1) % c.size + have hj : j < c.size := Nat.mod_lt _ (by have := c.four_le; omega) + have heq : c.edgeAt (j+1) = c.edgeAt i := congrArg c.edge (c.previous_indices i hi) + have hvq : c.vertexAt (j+1) = c.vertexAt i := congrArg c.vertex (c.previous_indices i hi) + have hji : c.edgeAt j ≠ c.edgeAt i := by rw [← heq]; exact c.consecutive_ne j hj + have hiinc := (c.edgeAt_incidence i (c.vertexAt i)).mpr (Or.inl rfl) + have hjinc : inc (c.edgeAt j) (c.vertexAt i) := + (c.edgeAt_incidence j _).mpr (Or.inr hvq.symm) + have hcomp : c.edgeAt i ∈ M ↔ c.edgeAt j ∉ M := by + rw [← heq]; exact c.adjacent_mem_complement hM hN hU j hj + by_cases hjM : c.edgeAt j ∈ M + · have hiN : c.edgeAt i ∈ N := + (Finset.mem_union.mp (hU i)).resolve_left (fun hiM => (hcomp.mp hiM) hjM) + rcases Finset.mem_union.mp he with heM | heN + · rw [hM.unique (Finset.mem_univ _) heM hev hjM hjinc] + exact c.edgeAt_mem_edgeSet j + · rw [hN.unique (Finset.mem_univ _) heN hev hiN hiinc] + exact c.edgeAt_mem_edgeSet i + · have hjN := (Finset.mem_union.mp (hU j)).resolve_left hjM + have hiM := hcomp.mpr hjM + rcases Finset.mem_union.mp he with heM | heN + · rw [hM.unique (Finset.mem_univ _) heM hev hiM hiinc] + exact c.edgeAt_mem_edgeSet i + · rw [hN.unique (Finset.mem_univ _) heN hev hjN hjinc] + exact c.edgeAt_mem_edgeSet j + +lemma edgeSet_closed {M N : Finset E} + (hM : MatchingOn inc M Finset.univ) (hN : MatchingOn inc N Finset.univ) + (hU : ∀ i, c.edgeAt i ∈ M ∪ N) {e f : E} (he : e ∈ c.edgeSet) + (hef : (overlayLineGraph inc (M ∪ N)).Adj e f) : f ∈ c.edgeSet := by + obtain ⟨i,hi,rfl⟩ := (c.mem_edgeSet e).mp he + obtain ⟨_,_,hf,v,hev,hfv⟩ := hef + rcases (c.edgeAt_incidence i v).mp hev with rfl | rfl + · exact c.edge_incident_cycle_mem hM hN hU hf i hi hfv + · have hi' : (i+1) % c.size < c.size := Nat.mod_lt _ (by have := c.four_le; omega) + apply c.edge_incident_cycle_mem hM hN hU hf ((i+1)%c.size) hi' + simpa only [c.vertexAt_mod] using hfv + +lemma edgeSet_eq_component {M N : Finset E} + (hM : MatchingOn inc M Finset.univ) (hN : MatchingOn inc N Finset.univ) + (hU : ∀ i, c.edgeAt i ∈ M ∪ N) : + c.edgeSet = componentEdges (inc := inc) (M ∪ N) (c.edgeAt 0) := by + ext e + constructor + · intro he + obtain ⟨i,hi,rfl⟩ := (c.mem_edgeSet e).mp he + exact (mem_componentEdges _ _ _).mpr ⟨hU i,c.edges_reachable _ hU i⟩ + · intro he + obtain ⟨heu,hr⟩ := (mem_componentEdges _ _ _).mp he + have hrel := (SimpleGraph.reachable_iff_reflTransGen _ _).mp hr + clear he heu hr + induction hrel with + | refl => exact c.edgeAt_mem_edgeSet 0 + | tail hpath hadj ih => exact c.edgeSet_closed hM hN hU ih hadj + +lemma edgeSet_mem_components {M N : Finset E} + (hM : MatchingOn inc M Finset.univ) (hN : MatchingOn inc N Finset.univ) + (hU : ∀ i, c.edgeAt i ∈ M ∪ N) : c.edgeSet ∈ components (inc := inc) (M ∪ N) := by + rw [c.edgeSet_eq_component hM hN hU] + exact mem_components.mpr ⟨c.edgeAt 0,hU 0,rfl⟩ + +lemma inter_edgeSet_parity {M N : Finset E} + (hM : MatchingOn inc M Finset.univ) (hN : MatchingOn inc N Finset.univ) + (hU : ∀ i, c.edgeAt i ∈ M ∪ N) : + M ∩ c.edgeSet = c.parityPattern (if c.edgeAt 0 ∈ M then 0 else 1) := by + classical + ext e + simp only [Finset.mem_inter, c.mem_edgeSet, parityPattern, mem_intervalPattern] + constructor + · rintro ⟨heM,i,hi,rfl⟩ + refine ⟨i, Nat.zero_le _,hi,?_,rfl⟩ + have hp := (c.cycle_edge_mem_parity hM hN hU i).mp heM + split_ifs at hp ⊢ <;> first | omega | tauto + · rintro ⟨i,_,hi,hpar,rfl⟩ + refine ⟨?_, i,hi,rfl⟩ + apply (c.cycle_edge_mem_parity hM hN hU i).mpr + split_ifs at hpar ⊢ <;> omega + +end IndexedCycle + +end + +variable {V E : Type*} [DecidableEq V] [DecidableEq E] + +variable {inc : E → V → Prop} + +namespace CellPaths + +variable (c : CellPaths inc) + +lemma mem_assemble_iff (M : Fin 4 → Finset E) (e : E) : + e ∈ assemble M ↔ ∃ i, e ∈ M i := by + simp only [assemble, Finset.mem_union] + constructor + · rintro ((h | h) | (h | h)) + · exact ⟨0,h⟩ + · exact ⟨2,h⟩ + · exact ⟨1,h⟩ + · exact ⟨3,h⟩ + · rintro ⟨i,hi⟩ + fin_cases i <;> tauto + +lemma assemble_update (M : Fin 4 → Finset E) + (hd : Pairwise fun i j => Disjoint (M i) (M j)) (i : Fin 4) (Q : Finset E) : + assemble (Function.update M i Q) = (assemble M \ M i) ∪ Q := by + ext e + simp only [mem_assemble_iff, Finset.mem_union, Finset.mem_sdiff] + constructor + · rintro ⟨j,hj⟩ + by_cases hji : j = i + · subst j + exact Or.inr (by simpa using hj) + · have hj' : e ∈ M j := by simpa [Function.update_of_ne hji] using hj + exact Or.inl ⟨⟨j,hj'⟩, fun hi => Finset.disjoint_left.mp (hd hji) hj' hi⟩ + · rintro (⟨⟨j,hj⟩,hi⟩ | hq) + · have hji : j ≠ i := by rintro rfl; exact hi hj + exact ⟨j, by simpa [Function.update_of_ne hji] using hj⟩ + · exact ⟨i, by simpa using hq⟩ + +def conversionPieces (b : Bool) (S : Finset (Fin 4)) (i : Fin 4) : Finset E := + if i ∈ S then (c.side i).closed (c.chord i) else c.orientationPieces b i + +def converted (b : Bool) (S : Finset (Fin 4)) : Finset E := + assemble (c.conversionPieces b S) + +lemma conversion_pieces_matching (b : Bool) (S : Finset (Fin 4)) + (hS : ∀ i ∈ S, sideBit i = b) (i : Fin 4) : + MatchingOn inc (c.conversionPieces b S i) (c.blocks b i) := by + by_cases hi : i ∈ S + · simp only [conversionPieces, ite_eq_left hi, blocks, ite_eq_left (hS i hi)] + exact (c.side i).closed_matching _ (c.chord_incidence i) + · simp only [conversionPieces, ite_eq_right hi] + exact c.orientation_pieces_matching b i + +lemma converted_matching (b : Bool) (S : Finset (Fin 4)) + (hS : ∀ i ∈ S, sideBit i = b) : + MatchingOn inc (c.converted b S) c.vertices := + c.assembled_matching b _ (c.conversion_pieces_matching b S hS) + +lemma converted_empty (b : Bool) : c.converted b ∅ = c.orientation b := by + unfold converted orientation + congr 1 + +lemma conversion_pieces_insert (b : Bool) (S : Finset (Fin 4)) (i : Fin 4) : + c.conversionPieces b (insert i S) = + Function.update (c.conversionPieces b S) i ((c.side i).closed (c.chord i)) := by + funext j + by_cases hji : j = i + · subst j; simp [conversionPieces] + · simp [conversionPieces, hji] + +lemma converted_insert (b : Bool) (S : Finset (Fin 4)) + (hS : ∀ j ∈ S, sideBit j = b) (i : Fin 4) (hi : sideBit i = b) + (hni : i ∉ S) (hinc : ∀ e, ∃ v, inc e v) : + c.converted b (insert i S) = + (c.converted b S \ (c.side i).through) ∪ (c.side i).closed (c.chord i) := by + rw [converted, c.conversion_pieces_insert] + rw [assemble_update] + · simp only [conversionPieces, ite_eq_right hni, orientationPieces, pieces, ite_eq_left hi, converted] + · intro j k hjk + exact (c.conversion_pieces_matching b S hS j).disjoint_edges + (c.conversion_pieces_matching b S hS k) hinc (c.blocks_disjoint b hjk) + +lemma converted_singleton (b : Bool) (i : Fin 4) (hi : sideBit i = b) + (hinc : ∀ e, ∃ v, inc e v) : + c.converted b {i} = c.contextOne b i := by + have h := c.converted_insert b ∅ (by simp) i hi (by simp) hinc + simpa only [converted_empty, Finset.insert_empty, contextOne] using h + +lemma converted_pair (b : Bool) (X Y : Fin 4) + (hX : sideBit X = b) (hY : sideBit Y = b) (hne : X ≠ Y) : + c.converted b {X,Y} = c.switched b := by + unfold converted switched + congr 1 + funext i + have hh : i ∈ ({X,Y} : Finset (Fin 4)) ↔ sideBit i = b := by + fin_cases X <;> fin_cases Y <;> fin_cases i <;> cases b <;> + simp_all [sideBit] + simp only [conversionPieces, hh, switchPieces, pieces, orientationPieces] + split_ifs <;> rfl + +lemma double_conversion (b : Bool) (X Y : Fin 4) + (hX : sideBit X = b) (hY : sideBit Y = b) (hne : X ≠ Y) + (hinc : ∀ e, ∃ v, inc e v) : + (c.contextOne b Y \ (c.side X).through) ∪ (c.side X).closed (c.chord X) = + c.switched b := by + rw [← c.converted_singleton b Y hY hinc, ← c.converted_insert b {Y} + (by intro i hi; have hi := Finset.mem_singleton.mp hi; subst i; exact hY) X hX + (by simpa only [Finset.mem_singleton] using hne) hinc] + exact c.converted_pair b X Y hX hY hne + +def canonicalGain (R : Finset E) (f : Finset E → ℝ) (b : Bool) (i : Fin 4) : ℝ := + f (R ∪ c.orientation b) - f (R ∪ c.contextOne b i) + +def contextError (R : Finset E) (f : Finset E → ℝ) (b : Bool) (X Y : Fin 4) : ℝ := + (f (R ∪ c.contextOne b Y) - + f (R ∪ ((c.contextOne b Y \ (c.side X).through) ∪ (c.side X).closed (c.chord X)))) - + (f (R ∪ c.orientation b) - f (R ∪ c.contextOne b X)) + +lemma opposite_pair_identity (R : Finset E) (f : Finset E → ℝ) (b : Bool) + (X Y : Fin 4) (hX : sideBit X = b) (hY : sideBit Y = b) (hne : X ≠ Y) + (hinc : ∀ e, ∃ v, inc e v) : + f (R ∪ c.orientation b) - f (R ∪ c.switched b) = + c.canonicalGain R f b Y + c.canonicalGain R f b X + c.contextError R f b X Y := by + rw [contextError, c.double_conversion b X Y hX hY hne hinc] + unfold canonicalGain + ring + +theorem single_cell_identity (R : Finset E) (f : Finset E → ℝ) + (hinc : ∀ e, ∃ v, inc e v) : + f (R ∪ c.orientation true) - f (R ∪ c.orientation false) = + (f (R ∪ c.switched true) - f (R ∪ c.switched false)) + + (c.canonicalGain R f true 0 + c.canonicalGain R f true 2) - + (c.canonicalGain R f false 1 + c.canonicalGain R f false 3) + + c.contextError R f true 2 0 - c.contextError R f false 3 1 := by + have h₀ := c.opposite_pair_identity R f true 2 0 (by decide) (by decide) (by decide) hinc + have h₁ := c.opposite_pair_identity R f false 3 1 (by decide) (by decide) (by decide) hinc + linarith + +end CellPaths + +end MatchingFPRAS.Transport + +end OAI diff --git a/lean/OAI/Combinatorics/MatchingCount/Sampling/Corner.lean b/lean/OAI/Combinatorics/MatchingCount/Sampling/Corner.lean new file mode 100644 index 0000000000000000000000000000000000000000..380459e10188e1f01ba55b5e335a5dbe1208a6b1 --- /dev/null +++ b/lean/OAI/Combinatorics/MatchingCount/Sampling/Corner.lean @@ -0,0 +1,491 @@ +import Mathlib +import OAI.Combinatorics.MatchingCount.Sampling.Span + +namespace OAI + +namespace MatchingFPRAS.Transport +variable {V L : Type*} [DecidableEq V] +variable {E : Type*} [DecidableEq E] (inc : E → V → Prop) +namespace CellPaths + +variable {inc} (c : CellPaths inc) + +def corner (i : Fin 4) : V := (c.side i).vertex 0 + +def vertices : Finset V := + ((c.side 0).inside ∪ (c.side 1).inside) ∪ ((c.side 2).inside ∪ (c.side 3).inside) ∪ + {c.corner 0, c.corner 1, c.corner 2, c.corner 3} + +omit [DecidableEq E] in +lemma ends_eq (i : Fin 4) : (c.side i).ends = {c.corner i, c.corner (i+1)} := by + simp only [OddPath.ends, c.joins, corner] + +omit [DecidableEq E] in +lemma inside_disjoint_span (i j : Fin 4) (hij : i ≠ j) : + Disjoint (c.side i).inside (c.side j).span := by + rw [← (c.side j).inside_union_ends] + exact Finset.disjoint_union_right.mpr + ⟨c.interiors_disjoint hij, c.interior_ends_disjoint i j⟩ + +omit [DecidableEq E] in +lemma opposite_ends_even : Disjoint (c.side 0).ends (c.side 2).ends := by + rw [c.ends_eq, c.ends_eq] + apply Finset.disjoint_left.mpr + intro v hv hw + simp only [Finset.mem_insert, Finset.mem_singleton] at hv hw + rcases hv with h | h <;> rcases hw with k | k + all_goals have hh := c.corners_injective (h.symm.trans k) + all_goals exact absurd hh (by decide) + +omit [DecidableEq E] in +lemma opposite_ends_odd : Disjoint (c.side 1).ends (c.side 3).ends := by + rw [c.ends_eq, c.ends_eq] + apply Finset.disjoint_left.mpr + intro v hv hw + simp only [Finset.mem_insert, Finset.mem_singleton] at hv hw + rcases hv with h | h <;> rcases hw with k | k + all_goals have hh := c.corners_injective (h.symm.trans k) + all_goals exact absurd hh (by decide) + +omit [DecidableEq E] in +lemma opposite_span_even : Disjoint (c.side 0).span (c.side 2).span := by + rw [← (c.side 0).inside_union_ends] + apply Finset.disjoint_union_left.mpr + refine ⟨c.inside_disjoint_span 0 2 (by decide), ?_⟩ + rw [← (c.side 2).inside_union_ends] + exact Finset.disjoint_union_right.mpr ⟨(c.interior_ends_disjoint 2 0).symm, + c.opposite_ends_even⟩ + +omit [DecidableEq E] in +lemma opposite_span_odd : Disjoint (c.side 1).span (c.side 3).span := by + rw [← (c.side 1).inside_union_ends] + apply Finset.disjoint_union_left.mpr + refine ⟨c.inside_disjoint_span 1 3 (by decide), ?_⟩ + rw [← (c.side 3).inside_union_ends] + exact Finset.disjoint_union_right.mpr ⟨(c.interior_ends_disjoint 3 1).symm, + c.opposite_ends_odd⟩ + +omit [DecidableEq E] in +lemma even_blocks_union : + ((c.side 0).span ∪ (c.side 2).span) ∪ + ((c.side 1).inside ∪ (c.side 3).inside) = c.vertices := by + rw [← (c.side 0).inside_union_ends, ← (c.side 2).inside_union_ends, + c.ends_eq, c.ends_eq] + ext v + simp only [vertices, Finset.mem_union, Finset.mem_insert, Finset.mem_singleton] + tauto + +omit [DecidableEq E] in +lemma odd_blocks_union : + ((c.side 1).span ∪ (c.side 3).span) ∪ + ((c.side 0).inside ∪ (c.side 2).inside) = c.vertices := by + rw [← (c.side 1).inside_union_ends, ← (c.side 3).inside_union_ends, + c.ends_eq, c.ends_eq] + ext v + simp only [vertices, Finset.mem_union, Finset.mem_insert, Finset.mem_singleton] + tauto + +def assemble (M : Fin 4 → Finset E) : Finset E := (M 0 ∪ M 2) ∪ (M 1 ∪ M 3) + +lemma matching_even_full (M : Fin 4 → Finset E) + (h0 : MatchingOn inc (M 0) (c.side 0).span) + (h2 : MatchingOn inc (M 2) (c.side 2).span) + (h1 : MatchingOn inc (M 1) (c.side 1).inside) + (h3 : MatchingOn inc (M 3) (c.side 3).inside) : + MatchingOn inc (assemble M) c.vertices := by + have h02 := h0.union h2 c.opposite_span_even + have h13 := h1.union h3 (c.interiors_disjoint (by decide : (1 : Fin 4) ≠ 3)) + have hd : Disjoint ((c.side 0).span ∪ (c.side 2).span) + ((c.side 1).inside ∪ (c.side 3).inside) := by + simp only [Finset.disjoint_union_left, Finset.disjoint_union_right] + exact ⟨⟨(c.inside_disjoint_span 1 0 (by decide)).symm, + (c.inside_disjoint_span 1 2 (by decide)).symm⟩, + ⟨(c.inside_disjoint_span 3 0 (by decide)).symm, + (c.inside_disjoint_span 3 2 (by decide)).symm⟩⟩ + simpa only [c.even_blocks_union, assemble] using h02.union h13 hd + +lemma matching_odd_full (M : Fin 4 → Finset E) + (h0 : MatchingOn inc (M 0) (c.side 0).inside) + (h2 : MatchingOn inc (M 2) (c.side 2).inside) + (h1 : MatchingOn inc (M 1) (c.side 1).span) + (h3 : MatchingOn inc (M 3) (c.side 3).span) : + MatchingOn inc (assemble M) c.vertices := by + have h02 := h0.union h2 (c.interiors_disjoint (by decide : (0 : Fin 4) ≠ 2)) + have h13 := h1.union h3 c.opposite_span_odd + have hd : Disjoint ((c.side 0).inside ∪ (c.side 2).inside) + ((c.side 1).span ∪ (c.side 3).span) := by + simp only [Finset.disjoint_union_left, Finset.disjoint_union_right] + exact ⟨⟨c.inside_disjoint_span 0 1 (by decide), c.inside_disjoint_span 2 1 (by decide)⟩, + ⟨c.inside_disjoint_span 0 3 (by decide), c.inside_disjoint_span 2 3 (by decide)⟩⟩ + have hs : ((c.side 0).inside ∪ (c.side 2).inside) ∪ + ((c.side 1).span ∪ (c.side 3).span) = c.vertices := + (Finset.union_comm _ _).trans c.odd_blocks_union + simpa only [hs, assemble] using h02.union h13 hd + +def sideBit (i : Fin 4) : Bool := decide (i.val % 2 = 0) + +def blocks (b : Bool) (i : Fin 4) : Finset V := + if sideBit i = b then (c.side i).span else (c.side i).inside + +def pieces (b : Bool) (full inner : Fin 4 → Finset E) (i : Fin 4) : Finset E := + if sideBit i = b then full i else inner i + +omit [DecidableEq E] in +lemma same_bit_spans (i j : Fin 4) (hij : i ≠ j) (hbit : sideBit i = sideBit j) : + Disjoint (c.side i).span (c.side j).span := by + fin_cases i <;> fin_cases j + all_goals try exact (hij rfl).elim + all_goals norm_num [sideBit] at hbit + · exact c.opposite_span_even + · exact c.opposite_span_odd + · exact c.opposite_span_even.symm + · exact c.opposite_span_odd.symm + +omit [DecidableEq E] in +lemma blocks_disjoint (b : Bool) : Pairwise fun i j => Disjoint (c.blocks b i) (c.blocks b j) := by + intro i j hij + by_cases hi : sideBit i = b <;> by_cases hj : sideBit j = b + · simp only [blocks, ite_eq_left hi, ite_eq_left hj] + exact c.same_bit_spans i j hij (hi.trans hj.symm) + · simp only [blocks, ite_eq_left hi, ite_eq_right hj] + exact (c.inside_disjoint_span j i hij.symm).symm + · simp only [blocks, ite_eq_right hi, ite_eq_left hj] + exact c.inside_disjoint_span i j hij + · simp only [blocks, ite_eq_right hi, ite_eq_right hj] + exact c.interiors_disjoint hij + +lemma assembled_matching (b : Bool) (M : Fin 4 → Finset E) + (hM : ∀ i, MatchingOn inc (M i) (c.blocks b i)) : + MatchingOn inc (assemble M) c.vertices := by + cases b + · apply c.matching_odd_full M <;> first + | simpa [blocks, sideBit] using hM 0 + | simpa [blocks, sideBit] using hM 1 + | simpa [blocks, sideBit] using hM 2 + | simpa [blocks, sideBit] using hM 3 + · apply c.matching_even_full M <;> first + | simpa [blocks, sideBit] using hM 0 + | simpa [blocks, sideBit] using hM 1 + | simpa [blocks, sideBit] using hM 2 + | simpa [blocks, sideBit] using hM 3 + +lemma assemble_val (b : Bool) (M : Fin 4 → Finset E) + (hM : ∀ i, MatchingOn inc (M i) (c.blocks b i)) (hinc : ∀ e, ∃ v, inc e v) : + (assemble M).val = ∑ i, (M i).val := by + have hd (i j : Fin 4) (hij : i ≠ j) : Disjoint (M i) (M j) := + (hM i).disjoint_edges (hM j) hinc (c.blocks_disjoint b hij) + have hu : Disjoint (M 0 ∪ M 2) (M 1 ∪ M 3) := by + simp only [Finset.disjoint_union_left, Finset.disjoint_union_right] + exact ⟨⟨hd 0 1 (by decide), hd 2 1 (by decide)⟩, + ⟨hd 0 3 (by decide), hd 2 3 (by decide)⟩⟩ + rw [assemble, union_val_add hu, union_val_add (hd 0 2 (by decide)), + union_val_add (hd 1 3 (by decide))] + rw [Fin.sum_univ_four] + ac_rfl + +omit [DecidableEq E] in +lemma pieces_matching (b : Bool) (full inner : Fin 4 → Finset E) + (hf : ∀ i, sideBit i = b → MatchingOn inc (full i) (c.side i).span) + (hi : ∀ i, sideBit i ≠ b → MatchingOn inc (inner i) (c.side i).inside) : + ∀ i, MatchingOn inc (pieces b full inner i) (c.blocks b i) := by + intro i + by_cases h : sideBit i = b + · simpa only [pieces, blocks, ite_eq_left h] using hf i h + · simpa only [pieces, blocks, ite_eq_right h] using hi i h + +def orientationPieces (b : Bool) : Fin 4 → Finset E := + pieces b (fun i => (c.side i).through) (fun i => (c.side i).interior) + +def switchPieces (b : Bool) : Fin 4 → Finset E := + pieces b (fun i => (c.side i).closed (c.chord i)) (fun i => (c.side i).interior) + +def repairPieces (b : Bool) (repair : Fin 4 → E) : Fin 4 → Finset E := + pieces b (fun i => (c.side i).through) (fun i => (c.side i).repaired (repair i)) + +def guidePieces (b : Bool) (repair : Fin 4 → E) : Fin 4 → Finset E := + pieces b (fun i => (c.side i).closed (c.chord i)) (fun i => (c.side i).repaired (repair i)) + +def Repairs (b : Bool) (repair : Fin 4 → E) : Prop := + ∀ i, sideBit i ≠ b → (c.side i).length ≠ 1 → ∀ v, + inc (repair i) v ↔ v = (c.side i).vertex 1 ∨ v = (c.side i).vertex ((c.side i).length - 1) + +lemma orientation_pieces_matching (b : Bool) : + ∀ i, MatchingOn inc (c.orientationPieces b i) (c.blocks b i) := + c.pieces_matching b _ _ (fun i _ => (c.side i).through_matching) + (fun i _ => (c.side i).interior_matching) + +lemma switch_pieces_matching (b : Bool) : + ∀ i, MatchingOn inc (c.switchPieces b i) (c.blocks b i) := + c.pieces_matching b _ _ (fun i _ => (c.side i).closed_matching _ (c.chord_incidence i)) + (fun i _ => (c.side i).interior_matching) + +lemma repair_pieces_matching (b : Bool) (repair : Fin 4 → E) (hr : c.Repairs b repair) : + ∀ i, MatchingOn inc (c.repairPieces b repair i) (c.blocks b i) := + c.pieces_matching b _ _ (fun i _ => (c.side i).through_matching) + (fun i hi => (c.side i).repaired_matching _ (hr i hi)) + +lemma guide_pieces_matching (b : Bool) (repair : Fin 4 → E) (hr : c.Repairs b repair) : + ∀ i, MatchingOn inc (c.guidePieces b repair i) (c.blocks b i) := + c.pieces_matching b _ _ (fun i _ => (c.side i).closed_matching _ (c.chord_incidence i)) + (fun i hi => (c.side i).repaired_matching _ (hr i hi)) + +def orientation (b : Bool) : Finset E := assemble (c.orientationPieces b) + +def switched (b : Bool) : Finset E := assemble (c.switchPieces b) + +def repaired (b : Bool) (repair : Fin 4 → E) : Finset E := assemble (c.repairPieces b repair) + +def guide (b : Bool) (repair : Fin 4 → E) : Finset E := assemble (c.guidePieces b repair) + +lemma orientation_matching (b : Bool) : MatchingOn inc (c.orientation b) c.vertices := + c.assembled_matching b _ (c.orientation_pieces_matching b) + +lemma switched_matching (b : Bool) : MatchingOn inc (c.switched b) c.vertices := + c.assembled_matching b _ (c.switch_pieces_matching b) + +lemma repaired_matching (b : Bool) (repair : Fin 4 → E) (hr : c.Repairs b repair) : + MatchingOn inc (c.repaired b repair) c.vertices := + c.assembled_matching b _ (c.repair_pieces_matching b repair hr) + +lemma guide_matching (b : Bool) (repair : Fin 4 → E) (hr : c.Repairs b repair) : + MatchingOn inc (c.guide b repair) c.vertices := + c.assembled_matching b _ (c.guide_pieces_matching b repair hr) + +lemma component_subset_assemble (M : Fin 4 → Finset E) (i : Fin 4) : M i ⊆ assemble M := by + intro e he + fin_cases i <;> simp only [assemble, Finset.mem_union] + · exact Or.inl (Or.inl he) + · exact Or.inr (Or.inl he) + · exact Or.inl (Or.inr he) + · exact Or.inr (Or.inr he) + +lemma closed_subset_guide (b : Bool) (repair : Fin 4 → E) (i : Fin 4) (hi : sideBit i = b) : + (c.side i).closed (c.chord i) ⊆ c.guide b repair := by + have h := component_subset_assemble (c.guidePieces b repair) i + simpa only [guidePieces, pieces, ite_eq_left hi, guide] using h + +def drops (r : Bool) : Multiset E := + ∑ i, if sideBit i = r then 0 else (c.side i).boundary.val + +def additions (b r : Bool) (repair : Fin 4 → E) : Multiset E := + (∑ i, if sideBit i = b then {c.chord i} else 0) + + ∑ i, if sideBit i = r then 0 else (c.side i).repairAdded (repair i) + +lemma orientation_val (b : Bool) (hinc : ∀ e, ∃ v, inc e v) : + (c.orientation b).val = ∑ i, (c.orientationPieces b i).val := + c.assemble_val b _ (c.orientation_pieces_matching b) hinc + +lemma switched_val (b : Bool) (hinc : ∀ e, ∃ v, inc e v) : + (c.switched b).val = ∑ i, (c.switchPieces b i).val := + c.assemble_val b _ (c.switch_pieces_matching b) hinc + +lemma repaired_val (r : Bool) (repair : Fin 4 → E) (hr : c.Repairs r repair) + (hinc : ∀ e, ∃ v, inc e v) : + (c.repaired r repair).val = ∑ i, (c.repairPieces r repair i).val := + c.assemble_val r _ (c.repair_pieces_matching r repair hr) hinc + +lemma guide_val (b : Bool) (repair : Fin 4 → E) (hr : c.Repairs b repair) + (hinc : ∀ e, ∃ v, inc e v) : + (c.guide b repair).val = ∑ i, (c.guidePieces b repair i).val := + c.assemble_val b _ (c.guide_pieces_matching b repair hr) hinc + +lemma two_orientation_pieces (i : Fin 4) : + (c.orientationPieces true i).val + (c.orientationPieces false i).val = + (c.side i).through.val + (c.side i).interior.val := by + cases h : sideBit i <;> simp [orientationPieces, pieces, h, add_comm] + +lemma switch_piece_val (b : Bool) (i : Fin 4) (hinc : ∀ e, ∃ v, inc e v) : + (c.switchPieces b i).val = (c.side i).interior.val + + (if sideBit i = b then {c.chord i} else 0) := by + by_cases h : sideBit i = b + · simp only [switchPieces, pieces, ite_eq_left h] + exact (c.side i).closed_val _ (c.chord_incidence i) hinc + · simp [switchPieces, pieces, h] + +lemma repair_piece_conservation (r : Bool) (repair : Fin 4 → E) + (hr : c.Repairs r repair) (i : Fin 4) (hinc : ∀ e, ∃ v, inc e v) : + (c.repairPieces r repair i).val + + (if sideBit i = r then 0 else (c.side i).boundary.val) = + (c.side i).through.val + + (if sideBit i = r then 0 else (c.side i).repairAdded (repair i)) := by + by_cases h : sideBit i = r + · simp [repairPieces, pieces, h] + · simp only [repairPieces, pieces, ite_eq_right h] + exact (c.side i).repair_conservation _ (hr i h) hinc + +lemma switch_conservation (b r : Bool) (repair : Fin 4 → E) + (hr : c.Repairs r repair) (hinc : ∀ e, ∃ v, inc e v) : + (c.orientation true).val + (c.orientation false).val + c.additions b r repair = + (c.switched b).val + (c.repaired r repair).val + c.drops r := by + rw [c.orientation_val true hinc, c.orientation_val false hinc, + c.switched_val b hinc, c.repaired_val r repair hr hinc] + simp only [additions, drops, ← Finset.sum_add_distrib] + apply Finset.sum_congr rfl + intro i _ + rw [c.two_orientation_pieces i, c.switch_piece_val b i hinc] + have h := c.repair_piece_conservation r repair hr i hinc + calc + _ = (c.side i).interior.val + (if sideBit i = b then {c.chord i} else 0) + + ((c.side i).through.val + + (if sideBit i = r then 0 else (c.side i).repairAdded (repair i))) := by ac_rfl + _ = _ := by rw [← h]; ac_rfl + +lemma guide_piece_conservation (b : Bool) (repair : Fin 4 → E) + (hr : c.Repairs b repair) (i : Fin 4) (hinc : ∀ e, ∃ v, inc e v) : + (c.orientationPieces b i).val + (c.guidePieces b repair i).val + + (if sideBit i = b then 0 else (c.side i).boundary.val) = + (c.side i).through.val + (c.side i).interior.val + + (if sideBit i = b then {c.chord i} else 0) + + (if sideBit i = b then 0 else (c.side i).repairAdded (repair i)) := by + by_cases h : sideBit i = b + · simp only [orientationPieces, guidePieces, pieces, ite_eq_left h, add_zero] + rw [(c.side i).closed_val _ (c.chord_incidence i) hinc] + ac_rfl + · simp only [orientationPieces, guidePieces, pieces, ite_eq_right h, add_zero] + have hh := (c.side i).repair_conservation _ (hr i h) hinc + calc + _ = (c.side i).interior.val + + ((c.side i).repaired (repair i)).val + (c.side i).boundary.val := rfl + _ = _ := by rw [add_assoc, hh]; ac_rfl + +lemma guide_conservation (b : Bool) (repair : Fin 4 → E) + (hr : c.Repairs b repair) (hinc : ∀ e, ∃ v, inc e v) : + (c.orientation true).val + (c.orientation false).val + c.additions b b repair = + (c.orientation b).val + (c.guide b repair).val + c.drops b := by + rw [c.orientation_val true hinc, c.orientation_val false hinc, + c.orientation_val b hinc, c.guide_val b repair hr hinc] + simp only [additions, drops, ← Finset.sum_add_distrib] + apply Finset.sum_congr rfl + intro i _ + rw [c.two_orientation_pieces i] + have h := c.guide_piece_conservation b repair hr i hinc + simpa only [add_assoc] using h.symm + +lemma boundary_card_eq (i : Fin 4) (repair : Fin 4 → E) : + (c.side i).boundary.card = 1 + ((c.side i).repairAdded (repair i)).card := by + rw [(c.side i).boundary_card] + by_cases h : (c.side i).length = 1 <;> simp [OddPath.repairAdded, h] + +omit [DecidableEq E] in +lemma additions_card (b r : Bool) (repair : Fin 4 → E) : + (c.additions b r repair).card = 2 + + ∑ i, if sideBit i = r then 0 else ((c.side i).repairAdded (repair i)).card := by + simp only [additions, Multiset.card_add, Multiset.card_sum] + have h1 : (∑ i : Fin 4, (if sideBit i = b then ({c.chord i} : Multiset E) else 0).card) = 2 := by + cases b <;> norm_num [Fin.sum_univ_four, sideBit] + rw [h1] + congr 1 + apply Finset.sum_congr rfl + intro i _ + split <;> simp + +lemma modification_cards (b r : Bool) (repair : Fin 4 → E) : + (c.drops r).card = (c.additions b r repair).card ∧ (c.drops r).card ≤ 4 := by + have hd : (c.drops r).card = 2 + + ∑ i, if sideBit i = r then 0 else ((c.side i).repairAdded (repair i)).card := by + simp only [drops, Multiset.card_sum] + have hb := c.boundary_card_eq + cases r <;> norm_num [Fin.sum_univ_four, sideBit] + all_goals rw [hb _ repair, hb _ repair]; omega + refine ⟨hd.trans (c.additions_card b r repair).symm, ?_⟩ + rw [hd] + have hle (i : Fin 4) : ((c.side i).repairAdded (repair i)).card ≤ 1 := by + by_cases h : (c.side i).length = 1 <;> simp [OddPath.repairAdded, h] + have h0 := hle 0 + have h1 := hle 1 + have h2 := hle 2 + have h3 := hle 3 + cases r <;> norm_num [Fin.sum_univ_four, sideBit] + all_goals omega + +lemma through_subset_orientation (b : Bool) (i : Fin 4) (hi : sideBit i = b) : + (c.side i).through ⊆ c.orientation b := by + have h := component_subset_assemble (c.orientationPieces b) i + simpa only [orientationPieces, pieces, ite_eq_left hi, orientation] using h + +omit [DecidableEq E] in +lemma span_subset_vertices (i : Fin 4) : (c.side i).span ⊆ c.vertices := by + rw [← (c.side i).inside_union_ends, c.ends_eq] + intro v hv + fin_cases i <;> simp only [vertices, Finset.mem_union, Finset.mem_insert, + Finset.mem_singleton] at hv ⊢ <;> tauto + +def contextOne (b : Bool) (Y : Fin 4) : Finset E := + (c.orientation b \ (c.side Y).through) ∪ (c.side Y).closed (c.chord Y) + +def guideOne (b : Bool) (repair : Fin 4 → E) (Y : Fin 4) : Finset E := + (c.guide b repair \ (c.side Y).closed (c.chord Y)) ∪ (c.side Y).through + +lemma context_one_properties (b : Bool) (repair : Fin 4 → E) (hr : c.Repairs b repair) + (Y : Fin 4) (hY : sideBit Y = b) (hinc : ∀ e, ∃ v, inc e v) : + MatchingOn inc (c.contextOne b Y) c.vertices ∧ + MatchingOn inc (c.guideOne b repair Y) c.vertices ∧ + (c.contextOne b Y).val + (c.guideOne b repair Y).val = + (c.orientation b).val + (c.guide b repair).val := by + exact pattern_interchange inc (c.orientation_matching b) (c.guide_matching b repair hr) + (c.side Y).through_matching ((c.side Y).closed_matching _ (c.chord_incidence Y)) + (c.through_subset_orientation b Y hY) (c.closed_subset_guide b repair Y hY) + (c.span_subset_vertices Y) hinc + +lemma closed_subset_guide_one (b : Bool) (repair : Fin 4 → E) (X Y : Fin 4) + (hX : sideBit X = b) (hY : sideBit Y = b) (hXY : X ≠ Y) + (hinc : ∀ e, ∃ v, inc e v) : + (c.side X).closed (c.chord X) ⊆ c.guideOne b repair Y := by + have hdis := ((c.side X).closed_matching _ (c.chord_incidence X)).disjoint_edges + ((c.side Y).closed_matching _ (c.chord_incidence Y)) hinc + (c.same_bit_spans X Y hXY (hX.trans hY.symm)) + intro e he + exact Finset.mem_union_left _ <| Finset.mem_sdiff.mpr + ⟨c.closed_subset_guide b repair X hX he, fun hh => Finset.disjoint_left.mp hdis he hh⟩ + +lemma context_one_conservation (b : Bool) (repair : Fin 4 → E) (hr : c.Repairs b repair) + (Y : Fin 4) (hY : sideBit Y = b) (hinc : ∀ e, ∃ v, inc e v) : + (c.orientation true).val + (c.orientation false).val + c.additions b b repair = + (c.contextOne b Y).val + (c.guideOne b repair Y).val + c.drops b := by + rw [(c.context_one_properties b repair hr Y hY hinc).2.2] + exact c.guide_conservation b repair hr hinc + +lemma switch_weight_bound (b r : Bool) (repair : Fin 4 → E) (hr : c.Repairs r repair) + (hinc : ∀ e, ∃ v, inc e v) (w : E → ℝ) (hw : ∀ e, 0 < w e) + (A₀ : ℝ) (hA₀ : 1 ≤ A₀) + (hcompare : ∀ e ∈ c.drops r, ∀ f ∈ c.additions b r repair, w e ≤ A₀ * w f) : + (∏ e ∈ c.orientation true, w e) * (∏ e ∈ c.orientation false, w e) ≤ + A₀ ^ 4 * ((∏ e ∈ c.switched b, w e) * ∏ e ∈ c.repaired r repair, w e) := by + have h := four_edge_weight_bound w hw A₀ hA₀ + ((c.orientation true).val + (c.orientation false).val) + ((c.switched b).val + (c.repaired r repair).val) + (c.drops r) (c.additions b r repair) (c.switch_conservation b r repair hr hinc) + (c.modification_cards b r repair).1 (c.modification_cards b r repair).2 hcompare + simpa only [Multiset.map_add, Multiset.prod_add, ← Finset.prod_eq_multiset_prod] using h + +lemma guide_weight_bound (b : Bool) (repair : Fin 4 → E) (hr : c.Repairs b repair) + (hinc : ∀ e, ∃ v, inc e v) (w : E → ℝ) (hw : ∀ e, 0 < w e) + (A₀ : ℝ) (hA₀ : 1 ≤ A₀) + (hcompare : ∀ e ∈ c.drops b, ∀ f ∈ c.additions b b repair, w e ≤ A₀ * w f) : + (∏ e ∈ c.orientation true, w e) * (∏ e ∈ c.orientation false, w e) ≤ + A₀ ^ 4 * ((∏ e ∈ c.orientation b, w e) * ∏ e ∈ c.guide b repair, w e) := by + have h := four_edge_weight_bound w hw A₀ hA₀ + ((c.orientation true).val + (c.orientation false).val) + ((c.orientation b).val + (c.guide b repair).val) + (c.drops b) (c.additions b b repair) (c.guide_conservation b repair hr hinc) + (c.modification_cards b b repair).1 (c.modification_cards b b repair).2 hcompare + simpa only [Multiset.map_add, Multiset.prod_add, ← Finset.prod_eq_multiset_prod] using h + +lemma context_one_weight_bound (b : Bool) (repair : Fin 4 → E) (hr : c.Repairs b repair) + (Y : Fin 4) (hY : sideBit Y = b) (hinc : ∀ e, ∃ v, inc e v) + (w : E → ℝ) (hw : ∀ e, 0 < w e) (A₀ : ℝ) (hA₀ : 1 ≤ A₀) + (hcompare : ∀ e ∈ c.drops b, ∀ f ∈ c.additions b b repair, w e ≤ A₀ * w f) : + (∏ e ∈ c.orientation true, w e) * (∏ e ∈ c.orientation false, w e) ≤ + A₀ ^ 4 * ((∏ e ∈ c.contextOne b Y, w e) * ∏ e ∈ c.guideOne b repair Y, w e) := by + have h := four_edge_weight_bound w hw A₀ hA₀ + ((c.orientation true).val + (c.orientation false).val) + ((c.contextOne b Y).val + (c.guideOne b repair Y).val) + (c.drops b) (c.additions b b repair) (c.context_one_conservation b repair hr Y hY hinc) + (c.modification_cards b b repair).1 (c.modification_cards b b repair).2 hcompare + simpa only [Multiset.map_add, Multiset.prod_add, ← Finset.prod_eq_multiset_prod] using h + +end CellPaths + +end MatchingFPRAS.Transport + +end OAI diff --git a/lean/OAI/Combinatorics/MatchingCount/Sampling/DPEnvelope.lean b/lean/OAI/Combinatorics/MatchingCount/Sampling/DPEnvelope.lean new file mode 100644 index 0000000000000000000000000000000000000000..77999055cc77f5ab99349a571590d646da289210 --- /dev/null +++ b/lean/OAI/Combinatorics/MatchingCount/Sampling/DPEnvelope.lean @@ -0,0 +1,168 @@ +import Mathlib +import OAI.Combinatorics.MatchingCount.Probability.AdaptiveLaw +import OAI.Combinatorics.MatchingCount.Sampling.RankOrder + +namespace OAI + +namespace MatchingFPRAS.UnitRefresh.Materialized +open Finset + +variable {V : Type} [Fintype V] {m : ℕ} + +def RowBound (t : Table) (w : Fin m → ℕ) : Prop := ∀ a r,read t a.val r ≤ w a + +def mergeEnvelope (w : Fin m → ℕ) (l p : Fin m) (s : ℕ) : Fin m → ℕ := + fun a=>if a=l then 1 else if a=p then 2^s*w l*w p else w a + +lemma mergeEnvelope_pos (w : Fin m → ℕ) (hw : ∀ a,1≤w a) (l p : Fin m) (s : ℕ) : + ∀ a,1 ≤ mergeEnvelope w l p s a := by + intro a + unfold mergeEnvelope + split_ifs + · exact le_rfl + · have hl := hw l + have hp := hw p + exact Nat.one_le_iff_ne_zero.mpr (by positivity) + · exact hw a + +lemma mergeEnvelope_prod (w : Fin m → ℕ) (l p : Fin m) (h : p≠l) (s : ℕ) : + (∏ a,mergeEnvelope w l p s a)=2^s*∏ a,w a := by + have hp : p∈(univ : Finset (Fin m)).erase l := by simp [h] + rw [←mul_prod_erase univ (mergeEnvelope w l p s) (mem_univ l), + ←mul_prod_erase (univ.erase l) (mergeEnvelope w l p s) hp, + ←mul_prod_erase univ w (mem_univ l),←mul_prod_erase (univ.erase l) w hp] + have he : (∏ a∈(univ.erase l).erase p,mergeEnvelope w l p s a)= + ∏ a∈(univ.erase l).erase p,w a := by + apply prod_congr rfl + intro a ha + have hal : a≠l := (mem_erase.mp (mem_erase.mp ha).2).1 + have hap : a≠p := (mem_erase.mp ha).1 + simp [mergeEnvelope,hal,hap] + rw [he] + simp only [mergeEnvelope,↓reduceIte,h] + ring + +omit [Fintype V] in +lemma entry_rowBound (bags : V → Finset (Fin m)) (R : Finset V) + (parent : Fin m → Option (Fin m)) (l : Fin m) (t : Table) (w : Fin m → ℕ) + (_ : ∀ a,1≤w a) (ht : RowBound t w) : + ∀ a r,entry bags R parent l a t r ≤ + match parent l with + | none => w a + | some p => mergeEnvelope w l p (sharedCount bags R l) a := by + intro a r + unfold entry + cases hp : parent l with + | none => + simp only + split_ifs with h + · subst a; exact ht l _ + · exact ht a r + | some p => + simp only + unfold mergeEnvelope + split_ifs with h h' + · exact le_rfl + · subst a + calc + _ ≤ ∑ k∈range (sharedCount bags R l+1), + (sharedCount bags R l).choose k*w l*w p := by + apply sum_le_sum + intro k hk + exact Nat.mul_le_mul (Nat.mul_le_mul_left _ (ht l _)) (ht p _) + _ = 2^(sharedCount bags R l)*w l*w p := by + rw [←sum_mul,←sum_mul,Nat.sum_range_choose] + · exact ht a r + +omit [Fintype V] in +lemma update_rowBound (bags : V → Finset (Fin m)) (R : Finset V) + (parent : Fin m → Option (Fin m)) (l : Fin m) (B : ℕ) (t : Table) (w : Fin m → ℕ) + (hw : ∀ a,1≤w a) (ht : RowBound t w) : + RowBound (update bags R parent l B t) + (match parent l with | none=>w | some p=>mergeEnvelope w l p (sharedCount bags R l)) := by + intro a r + rw [update,read_tabulate] + split_ifs + · have h := entry_rowBound bags R parent l t w hw ht a r + cases hh : parent l <;> simpa only [hh] using h + · exact Nat.zero_le _ + +lemma sharedCount_le_card (bags : V → Finset (Fin m)) (R : Finset V) (l : Fin m) : + sharedCount bags R l≤Fintype.card V := by + exact (card_le_card (filter_subset _ _)).trans (card_le_univ _) + +lemma run_envelope (bags : V → Finset (Fin m)) (parent : Fin m → Option (Fin m)) + (hp : ∀ l p,parent l=some p → p≠l) (ls : List (Fin m)) (R : Finset V) + (t : Table) (w : Fin m → ℕ) (hw : ∀ a,1≤w a) (ht : RowBound t w) : + ∃ v : Fin m → ℕ,(∀ a,1≤v a) ∧ RowBound (run bags parent ls R t) v ∧ + (∏ a,v a) ≤ 2^(Fintype.card V*ls.length)*(∏ a,w a) := by + induction ls generalizing R t w with + | nil => exact ⟨w,hw,ht,by simp⟩ + | cons l ls ih => + let v := match parent l with | none=>w | some p=>mergeEnvelope w l p (sharedCount bags R l) + have hv : ∀ a,1≤v a := by + cases hh : parent l with + | none => simpa [v,hh] using hw + | some p => simpa only [v,hh] using mergeEnvelope_pos w hw l p (sharedCount bags R l) + have hvt : RowBound (update bags R parent l (Fintype.card V*ls.length) t) v := + update_rowBound bags R parent l _ t w hw ht + have hprod : (∏ a,v a) ≤ 2^(Fintype.card V)*(∏ a,w a) := by + cases hh : parent l with + | none => + simp only [v,hh] + exact Nat.le_mul_of_pos_left _ (by positivity) + | some p => + simp only [v,hh] + rw [mergeEnvelope_prod w l p (hp l p hh)] + exact Nat.mul_le_mul_right _ (Nat.pow_le_pow_right (by decide) (sharedCount_le_card bags R l)) + obtain ⟨z,hz,hzt,hzp⟩ := ih (trim bags R l) _ v hv hvt + refine ⟨z,hz,hzt,?_⟩ + apply hzp.trans + calc + _ ≤ 2^(Fintype.card V*ls.length)*(2^Fintype.card V*∏ a,w a) := Nat.mul_le_mul_left _ hprod + _ = _ := by rw [List.length_cons,Nat.mul_add,Nat.mul_one,pow_add]; ring + +lemma run_entry_le (bags : V → Finset (Fin m)) (parent : Fin m → Option (Fin m)) + (hp : ∀ l p,parent l=some p → p≠l) (ls : List (Fin m)) (R : Finset V) + (t : Table) (w : Fin m → ℕ) (hw : ∀ a,1≤w a) (ht : RowBound t w) (a : Fin m) (r : ℕ) : + read (run bags parent ls R t) a.val r ≤ 2^(Fintype.card V*ls.length)*(∏ a,w a) := by + obtain ⟨v,hv,hvt,hvp⟩:=run_envelope bags parent hp ls R t w hw ht + exact (hvt a r).trans ((single_le_prod (fun x _=>hv x) (mem_univ a)).trans hvp) + +lemma pairingCount_pow_bound (n : ℕ) : pairingCount n ≤ 2^(n*n) := by + calc + _ ≤ n^(n/2) := pairingCount_le_half_power n + _ ≤ (2^n)^(n/2) := Nat.pow_le_pow_left (Nat.le_of_lt n.lt_two_pow_self) _ + _ = 2^(n*(n/2)) := (pow_mul _ _ _).symm + _ ≤ 2^(n*n) := Nat.pow_le_pow_right (by decide) (Nat.mul_le_mul_left _ (Nat.div_le_self _ _)) + +lemma initial_rowBound (B : ℕ) : RowBound (initial m B) (fun _ : Fin m=>2^(B*B)) := by + intro a r + rw [initial,read_tabulate] + split_ifs with h + · exact (pairingCount_pow_bound r).trans + (Nat.pow_le_pow_right (by decide) (Nat.mul_le_mul h h)) + · exact Nat.zero_le _ + +lemma run_initial_size (bags : V → Finset (Fin m)) (parent : Fin m → Option (Fin m)) + (hp : ∀ l p,parent l=some p → p≠l) (ls : List (Fin m)) (R : Finset V) + (B : ℕ) (a : Fin m) (r : ℕ) : + (read (run bags parent ls R (initial m B)) a.val r).size ≤ + Fintype.card V*ls.length+B*B*m+1 := by + have h := run_entry_le bags parent hp ls R (initial m B) (fun _=>2^(B*B)) + (fun _=>Nat.one_le_iff_ne_zero.mpr (by positivity)) (initial_rowBound B) a r + simp only [prod_const,card_univ,Fintype.card_fin,←pow_mul,←pow_add] at h + simpa only [Nat.size_pow] using Nat.size_le_size h + +lemma run_initial_product_le (bags : V → Finset (Fin m)) (parent : Fin m → Option (Fin m)) + (hp : ∀ l p,parent l=some p → p≠l) (ls : List (Fin m)) (R : Finset V) (B : ℕ) : + (∏ a : Fin m,read (run bags parent ls R (initial m B)) a.val 0) ≤ + 2^(Fintype.card V*ls.length+B*B*m) := by + obtain ⟨v,hv,hvt,hvp⟩ := run_envelope bags parent hp ls R (initial m B) + (fun _=>2^(B*B)) (fun _=>Nat.one_le_iff_ne_zero.mpr (by positivity)) (initial_rowBound B) + apply (prod_le_prod (fun a _=>hvt a 0)).trans + simpa only [prod_const,card_univ,Fintype.card_fin,←pow_mul,←pow_add] using hvp + +end MatchingFPRAS.UnitRefresh.Materialized + +end OAI diff --git a/lean/OAI/Combinatorics/MatchingCount/Sampling/DiscreteLadderSteps.lean b/lean/OAI/Combinatorics/MatchingCount/Sampling/DiscreteLadderSteps.lean new file mode 100644 index 0000000000000000000000000000000000000000..f92ee20ff739cbd38767f6f02b4785885b581bbd --- /dev/null +++ b/lean/OAI/Combinatorics/MatchingCount/Sampling/DiscreteLadderSteps.lean @@ -0,0 +1,210 @@ +import Mathlib +import OAI.Combinatorics.MatchingCount.Sampling.Sym2Order + +namespace OAI + +namespace MatchingFPRAS.Transport + +open Finset Replica Replica.Ladder Variation + +def discreteLadderSteps (N D K T m : ℕ) : ℕ := + 20*ladderL N D*ladderM N D T*(ladderLambda N D K T+Nat.clog 2 m+1) + +lemma discreteLadderSteps_eq (N D K T m : ℕ) : + discreteLadderSteps N D K T m=ladderSteps N D K T ((m:ℝ)⁻¹) := by + simp only [discreteLadderSteps,ladderSteps,inv_inv] + rw [show (2:ℝ)=(2:ℕ) by norm_cast,Real.natCeil_logb_natCast] + +variable {V L : Type*} [Fintype V] [LinearOrder V] [Fintype L] [LinearOrder L] + +variable {bags : V → Finset L} {G : SimpleGraph L} + +attribute [local instance] sym2Order bagEdgeOrder bagEdgeFintype UnitRefresh.Computable.allowedDec + +noncomputable local instance : DecidableEq (BagPM bags) := Classical.decEq _ + +attribute [local instance] prodOrder sumOrder + +variable (hbags : ∀ v,∀ a∈bags v,∀ b∈bags v,a=b ∨ G.Adj a b) (hG : G.IsAcyclic) + +variable (rank : L → ℕ) (parent : L → Option L) + +variable (hb : UnitRefresh.RankedBags bags rank parent) (hne : ∀ v,(bags v).Nonempty) + +variable (hp : ∀ l p,parent l=some p → rank p(w e:ℝ)) T (ladderQ (Fintype.card V) D)) ≤ (η:ℝ)+(m:ℝ)⁻¹ := by + have hm' : (1:ℝ)<(m:ℝ) := by exact_mod_cast hm + have hi:=ideal_ladder_sampling hbags hG height hheight hstep D K hD hN + (fun e=>(w e:ℝ)) hw hglobal M T s ((m:ℝ)⁻¹) (by positivity) (by exact inv_lt_one_of_one_lt₀ hm') + rw [←discreteLadderSteps_eq] at hi + have hb:=ladderBitRun_walk_tv hbags hG rank parent hb hne hp hq w M + (discreteLadderSteps (Fintype.card V) D K T m) η hη s + exact (tv_triangle _ _ _).trans (add_le_add hb hi) + +end MatchingFPRAS.Transport + +namespace MatchingFPRAS.BottleneckAlgorithm + +open Finset MatchingFPRAS.Switching + +variable {V : Type*} [Fintype V] [LinearOrder V] + +variable {α : Type*} [LinearOrder α] [OfNat α 1] + +def edge (w : V → V → α) (a b : V) : α := if a min (w a c) (w c b)) + +def close (w : V → V → α) : ℕ → V → V → α + | 0 => seed w + | k+1 => advance (close w k) + +@[simp] lemma close_diag (w : V → V → α) (k : ℕ) (a : V) : close w k a a=1 := by + cases k <;> simp [close,seed,advance] + +lemma close_one (w : V → V → α) (k : ℕ) (a b : V) : 1≤close w k a b := by + induction k with + | zero => + by_cases hab : a=b + · simp [close,seed,hab] + · simp [close,seed,hab] + | succ k ih => + by_cases h : a=b + · subst b; simp + · exact ih.trans (by simp [close,advance,h]) + +lemma close_mono_step (w : V → V → α) (k : ℕ) (a b : V) : + close w k a b≤close w (k+1) a b := by + by_cases h : a=b + · subst b; simp + · simp [close,advance,h] + +lemma close_mono (w : V → V → α) (a b : V) : Monotone (fun k=>close w k a b) := + monotone_nat_of_le_succ (fun k=>close_mono_step w k a b) + +lemma edge_le_close (w : V → V → α) (k : ℕ) (a b : V) (hab : a≠b) : + edge w a b≤close w k a b := by + have h : edge w a b≤close w 0 a b := by + simp [close,seed,hab] + exact h.trans (close_mono w a b (Nat.zero_le k)) + +lemma via_le_close (w : V → V → α) (k : ℕ) (a b c : V) (hab : a≠b) : + min (close w k a c) (close w k c b)≤close w (k+1) a b := by + exact (le_sup' (fun c=>min (close w k a c) (close w k c b)) (mem_univ c)).trans + (by simp [close,advance,hab]) + +lemma chain_le_close (w : V → V → α) (t : α) (a b : V) (L : List V) + (hab : a≠b) (hc : List.IsChain (fun x y=>t≤edge w x y) (a::L)) + (hn : (a::L).Nodup) (hb : b∈L) : t≤close w L.length a b := by + induction L generalizing a with + | nil => simp at hb + | cons c cs ih => + rcases List.isChain_cons_cons.mp hc with ⟨hac,hc⟩ + have han := List.nodup_cons.mp hn + have hne : a≠c := by intro h; apply han.1; simp [h] + rcases List.mem_cons.mp hb with rfl|hb + · exact hac.trans (edge_le_close w _ _ _ hne) + · have hcb : c≠b := by + intro he + exact (List.nodup_cons.mp han.2).1 (he ▸ hb) + have hh := ih c hcb hc han.2 hb + change t≤close w (cs.length+1) a b + exact (le_min (hac.trans (edge_le_close w cs.length a c hne)) hh).trans + (via_le_close w cs.length a b c hab) + +lemma close_le (w B : V → V → α) (_hdiag : ∀ a,B a a=1) (hone : ∀ a b,1≤B a b) + (hedge : ∀ a b,a≠b → edge w a b≤B a b) + (htri : ∀ a b c,a≠b → a≠c → b≠c → min (B a c) (B c b)≤B a b) + (k : ℕ) (a b : V) : close w k a b≤B a b := by + induction k generalizing a b with + | zero => + by_cases hab : a=b + · subst b; simpa [close,seed] using hone a a + · simpa [close,seed,hab] using max_le (hone a b) (hedge a b hab) + | succ k ih => + by_cases hab : a=b + · subst b; simpa using hone a a + · change (if a=b then 1 else _)≤_ + rw [ite_eq_right hab] + apply max_le (ih a b) + apply sup'_le + intro c _ + by_cases hac : a=c + · subst c + rw [close_diag] + exact (min_le_left _ _).trans (hone a b) + by_cases hbc : b=c + · subst c + rw [close_diag] + exact (min_le_right _ _).trans (hone a b) + exact (min_le_min (ih a c) (ih c b)).trans (htri a b c hab hac hbc) + +theorem real_close_eq (w : V → V → ℝ) (a b : V) : + close w (Fintype.card V) a b=bottleneck w a b := by + apply le_antisymm + · exact close_le w (bottleneck w) (by intro a; simp [bottleneck]) + (one_le_bottleneck w) (edgeActivity_le_bottleneck w) (bottleneck_ultrametric w) _ _ _ + · by_cases hab : a=b + · subst b; simp [bottleneck] + by_cases ht : 1 (w x y : ℝ)) k a b := by + induction k generalizing a b with + | zero => + unfold close seed edge + split_ifs <;> simp [Rat.cast_max] + | succ k ih => + simp only [close,advance] + split_ifs with hab + · simp + · have hh := Finset.apply_sup'_eq_sup'_comp (s:=(univ:Finset V)) + (f:=fun c=>min (close w k a c) (close w k c b)) ⟨a,mem_univ a⟩ + (fun x : ℚ => (x : ℝ)) (by intro x y; exact Rat.cast_max x y) + rw [Rat.cast_max] + apply congrArg₂ max (ih a b) + calc + _ = _ := hh + _ = _ := by + apply Finset.sup'_congr _ rfl + intro c _ + simp [Rat.cast_min,ih] + +theorem rational_close_eq (w : V → V → ℚ) (a b : V) : + ((close w (Fintype.card V) a b : ℚ) : ℝ)=bottleneck (fun x y=>(w x y:ℝ)) a b := by + rw [cast_close,real_close_eq] + +end MatchingFPRAS.BottleneckAlgorithm + +end OAI diff --git a/lean/OAI/Combinatorics/MatchingCount/Sampling/EndpointPair.lean b/lean/OAI/Combinatorics/MatchingCount/Sampling/EndpointPair.lean new file mode 100644 index 0000000000000000000000000000000000000000..9a2cca461ede3130d06e2f2cfc8de284f7219bfe --- /dev/null +++ b/lean/OAI/Combinatorics/MatchingCount/Sampling/EndpointPair.lean @@ -0,0 +1,448 @@ +import Mathlib +import OAI.Combinatorics.MatchingCount.Sampling.ComponentOrder + +namespace OAI + +namespace MatchingFPRAS.Transport.CellDemands + +variable {V L : Type*} [Fintype V] [DecidableEq V] [Fintype L] [DecidableEq L] + +variable {bags : V → Finset L} {G : SimpleGraph L} + +noncomputable local instance : Fintype (BagEdge bags) := Fintype.ofFinite _ + +variable {hbags : ∀ v, ∀ a ∈ bags v, ∀ b ∈ bags v, a = b ∨ G.Adj a b} + +variable {hG : G.IsAcyclic} + +lemma componentDifference_cell_bound + (p : PM (BagEdge.Incident (bags := bags)) × PM (BagEdge.Incident (bags := bags))) + (f : Finset (BagEdge bags) → ℝ) (i : ℕ) : + (componentDifference (fun A => f A.val) p i)^2 ≤ + 3 * (Fintype.card V : ℝ) * longCellCost (hbags := hbags) (hG := hG) p f + colorCost p.1 f := by + classical + change (f p.1.val - f (exchange p.1.val p.2.val + (componentAt (inc := BagEdge.Incident) (p.1.val ∪ p.2.val) i)))^2 ≤ _ + unfold componentAt + split_ifs with h + · exact component_cell_bound p f (componentOrder (p.1.val ∪ p.2.val) ⟨i,h⟩).property + · rw [exchange_empty, sub_self, zero_pow (by decide : 2≠0)] + exact add_nonneg (mul_nonneg (by positivity) (longCellCost_nonneg p f)) (colorCost_nonneg p.1 f) + +lemma sum_componentDifference_bound + (p : PM (BagEdge.Incident (bags := bags)) × PM (BagEdge.Incident (bags := bags))) + (f : Finset (BagEdge bags) → ℝ) : + (∑ i ∈ Finset.range (Fintype.card V), (componentDifference (fun A => f A.val) p i)^2) ≤ + (Fintype.card V : ℝ) * + (3 * (Fintype.card V : ℝ) * longCellCost (hbags := hbags) (hG := hG) p f + colorCost p.1 f) := by + have h := Finset.sum_le_sum (s := Finset.range (Fintype.card V)) + (fun i _ => componentDifference_cell_bound (hbags := hbags) (hG := hG) p f i) + simpa only [Finset.sum_const,Finset.card_range,nsmul_eq_mul] using h + +lemma sum_demand_eq (ρ : PM (BagEdge.Incident (bags := bags)) × PM (BagEdge.Incident (bags := bags)) → ℝ) + (f : Finset (BagEdge bags) → ℝ) : + (∑ d : Demand hbags hG, ρ d.1 * d.cellCost f) = + ∑ p : PM (BagEdge.Incident (bags := bags)) × PM (BagEdge.Incident (bags := bags)), + ρ p * longCellCost (hbags := hbags) (hG := hG) p f := by + classical + rw [arbitrary_sigma_sum] + simp_rw [arbitrary_sigma_sum] + simp only [longCellCost,Finset.mul_sum] + +theorem variance_cell_demand_bound (w : BagEdge bags → ℝ) (hw : ∀ e, 0 < w e) + (M : PM (BagEdge.Incident (bags := bags))) (f : Finset (BagEdge bags) → ℝ) : + (∑ p : PM (BagEdge.Incident (bags := bags)) × PM (BagEdge.Incident (bags := bags)), + gibbs w p.1 * gibbs w p.2 * (f p.1.val-f p.2.val)^2) / 2 ≤ + 3 * (Fintype.card V : ℝ)^3 * + (∑ d : Demand hbags hG, gibbs w d.1.1 * gibbs w d.1.2 * d.cellCost f) + + (Fintype.card V : ℝ)^2 * ∑ A : PM (BagEdge.Incident (bags := bags)), gibbs w A * colorCost A f := by + classical + have hv := cycle_demand_variance BagEdge.exists_incident w hw (fun A => f A.val) + have hs := Finset.sum_le_sum + (s := (Finset.univ : Finset (PM (BagEdge.Incident (bags := bags)) × PM (BagEdge.Incident (bags := bags))))) + (fun p _ => mul_le_mul_of_nonneg_left (sum_componentDifference_bound (hbags := hbags) (hG := hG) p f) + (mul_nonneg (le_of_lt (gibbs_pos w hw p.1)) (le_of_lt (gibbs_pos w hw p.2)))) + have h := hv.trans (mul_le_mul_of_nonneg_left hs (Nat.cast_nonneg (Fintype.card V))) + rw [sum_demand_eq (fun p => gibbs w p.1 * gibbs w p.2) f] + have hc : (∑ p : PM (BagEdge.Incident (bags := bags)) × PM (BagEdge.Incident (bags := bags)), + gibbs w p.1 * gibbs w p.2 * colorCost p.1 f) = + ∑ A : PM (BagEdge.Incident (bags := bags)), gibbs w A * colorCost A f := by + rw [Fintype.sum_prod_type] + apply Finset.sum_congr rfl + intro A _ + calc + _ = (gibbs w A * colorCost A f) * ∑ B : PM (BagEdge.Incident (bags := bags)), gibbs w B := by + rw [Finset.mul_sum] + apply Finset.sum_congr rfl + intro B _ + ring + _ = _ := by rw [gibbs_sum w hw M,mul_one] + have halgebra : (Fintype.card V : ℝ) * + (∑ p : PM (BagEdge.Incident (bags := bags)) × PM (BagEdge.Incident (bags := bags)), + gibbs w p.1 * gibbs w p.2 * ((Fintype.card V : ℝ) * + (3 * (Fintype.card V : ℝ) * longCellCost (hbags := hbags) (hG := hG) p f + colorCost p.1 f))) = + 3 * (Fintype.card V : ℝ)^3 * + (∑ p : PM (BagEdge.Incident (bags := bags)) × PM (BagEdge.Incident (bags := bags)), + gibbs w p.1 * gibbs w p.2 * longCellCost (hbags := hbags) (hG := hG) p f) + + (Fintype.card V : ℝ)^2 * + (∑ p : PM (BagEdge.Incident (bags := bags)) × PM (BagEdge.Incident (bags := bags)), + gibbs w p.1 * gibbs w p.2 * colorCost p.1 f) := by + simp only [Finset.mul_sum,← Finset.sum_add_distrib] + apply Finset.sum_congr rfl + intro p _ + ring + rw [halgebra,hc] at h + exact h + +end MatchingFPRAS.Transport.CellDemands + +namespace MatchingFPRAS.Transport + +section + +variable {V L : Type*} [Fintype V] [DecidableEq V] [Fintype L] [DecidableEq L] + +variable {bags : V → Finset L} {G : SimpleGraph L} + +noncomputable local instance endpointPairBagEdgeFintype : Fintype (BagEdge bags) := + Fintype.ofFinite _ + +variable (hbags : ∀ v, ∀ a ∈ bags v, ∀ b ∈ bags v, a = b ∨ G.Adj a b) + +variable (hG : G.IsAcyclic) + +include hbags hG in +omit [Fintype V] [DecidableEq V] [Fintype L] [DecidableEq L] in +lemma label_memberships_le_two (v : V) : (bags v).card ≤ 2 := by + by_contra h + have hc : G.IsNClique ((bags v).card) (bags v) := by + constructor + · intro a ha b hb hab + exact (hbags v a ha b hb).resolve_left hab + · rfl + exact hc.not_cliqueFree (hG.cliqueFree (by omega)) + +namespace BagEdge + +noncomputable def endpointPair (e : BagEdge bags) : V × V := + Classical.choose (show ∃ p : V × V, e.val.val.1 = s(p.1,p.2) from + Sym2.inductionOn e.val.val.1 (fun a b => ⟨(a,b),rfl⟩)) + +omit [Fintype V] [DecidableEq V] [Fintype L] [DecidableEq L] in +lemma endpointPair_eq (e : BagEdge bags) : e.val.val.1 = s(e.endpointPair.1,e.endpointPair.2) := + Classical.choose_spec (show ∃ p : V × V, e.val.val.1 = s(p.1,p.2) from + Sym2.inductionOn e.val.val.1 (fun a b => ⟨(a,b),rfl⟩)) + +noncomputable def verticesColor (e : BagEdge bags) : Σ v : V, V × ↥(bags v) := + ⟨e.endpointPair.1,e.endpointPair.2,⟨e.color,e.property _ (by + change e.endpointPair.1 ∈ e.val.val.1 + rw [e.endpointPair_eq] + simp)⟩⟩ + +omit [Fintype V] [DecidableEq V] [Fintype L] [DecidableEq L] in +lemma verticesColor_injective : Function.Injective (verticesColor (bags := bags)) := by + intro e f h + have h₁ : e.endpointPair.1 = f.endpointPair.1 := congrArg Sigma.fst h + have h₂ : e.endpointPair.2 = f.endpointPair.2 := congrArg (fun p => p.2.1) h + have h₃ : e.color = f.color := congrArg (fun p => p.2.2.val) h + apply Subtype.ext + apply Subtype.ext + apply Prod.ext + · rw [e.endpointPair_eq,f.endpointPair_eq,h₁,h₂] + · exact h₃ + +end BagEdge + +include hbags hG in +omit [DecidableEq V] [DecidableEq L] in +lemma bag_edges_card_le : Fintype.card (BagEdge bags) ≤ 2 * Fintype.card V ^ 2 := by + classical + calc + _ ≤ Fintype.card (Σ v : V, V × ↥(bags v)) := Fintype.card_le_of_injective BagEdge.verticesColor BagEdge.verticesColor_injective + _ = ∑ v : V, Fintype.card V * (bags v).card := by simp only [Fintype.card_sigma,Fintype.card_prod,Fintype.card_coe] + _ ≤ ∑ _v : V, Fintype.card V * 2 := + Finset.sum_le_sum (fun v _ => Nat.mul_le_mul_left _ (label_memberships_le_two hbags hG v)) + _ = _ := by simp only [Finset.sum_const,Finset.card_univ,Nat.nsmul_eq_mul]; ring + +end + +section + +variable {V E : Type*} [Fintype V] [DecidableEq V] [Fintype E] [DecidableEq E] + +variable {inc : E → V → Prop} + +omit [DecidableEq V] [Fintype E] in +lemma SafeSwitch.weight_ratio {w : E → ℝ} (hw : ∀ e, 0 < w e) {K : ℝ} + {A B : PM inc} (h : SafeSwitch w K A B) : matchingWeight w A ≤ K^2 * matchingWeight w B := by + classical + obtain ⟨v,e,R,hv,he,hA,hB,hcomp⟩ := h + have hne (i j : Fin 4) (hij : i ≠ j) (hij' : i ≠ j+1) : e i ≠ e j := by + intro h + have hi := (he i (v i)).mpr (Or.inl rfl) + rw [h] at hi + rcases (he j (v i)).mp hi with h | h + · exact hij (hv h) + · exact hij' (hv h) + have h01 : e 0 ≠ e 1 := hne 0 1 (by decide) (by decide) + have h23 : e 2 ≠ e 3 := hne 2 3 (by decide) (by decide) + have h02 : e 0 ≠ e 2 := hne 0 2 (by decide) (by decide) + have h13 : e 1 ≠ e 3 := hne 1 3 (by decide) (by decide) + have hRA : R ⊆ A.val := by rw [hA]; exact Finset.subset_union_left + have hRB : R ⊆ B.val := by rw [hB]; exact Finset.subset_union_left + have ha0 : e 0 ∈ A.val := by rw [hA]; simp + have ha2 : e 2 ∈ A.val := by rw [hA]; simp + have hb1 : e 1 ∈ B.val := by rw [hB]; simp + have hb3 : e 3 ∈ B.val := by rw [hB]; simp + have hr0 : e 0 ∉ R := by + intro hr + exact h01 (B.property.unique (Finset.mem_univ (v 1)) (hRB hr) + ((he 0 (v 1)).mpr (Or.inr rfl)) hb1 ((he 1 (v 1)).mpr (Or.inl rfl))) + have hr1 : e 1 ∉ R := by + intro hr + exact h01 (A.property.unique (Finset.mem_univ (v 1)) ha0 + ((he 0 (v 1)).mpr (Or.inr rfl)) (hRA hr) ((he 1 (v 1)).mpr (Or.inl rfl))) + have hr2 : e 2 ∉ R := by + intro hr + exact h23 (B.property.unique (Finset.mem_univ (v 3)) (hRB hr) + ((he 2 (v 3)).mpr (Or.inr rfl)) hb3 ((he 3 (v 3)).mpr (Or.inl rfl))) + have hr3 : e 3 ∉ R := by + intro hr + exact h23 (A.property.unique (Finset.mem_univ (v 3)) ha2 + ((he 2 (v 3)).mpr (Or.inr rfl)) (hRA hr) ((he 3 (v 3)).mpr (Or.inl rfl))) + have hdA : Disjoint R {e 0,e 2} := by + simp only [Finset.disjoint_insert_right,Finset.disjoint_singleton_right] + exact ⟨hr0,hr2⟩ + have hdB : Disjoint R {e 1,e 3} := by + simp only [Finset.disjoint_insert_right,Finset.disjoint_singleton_right] + exact ⟨hr1,hr3⟩ + have hp := mul_le_mul (hcomp 0 1) (hcomp 2 3) (le_of_lt (hw (e 2))) + (le_trans (le_of_lt (hw (e 0))) (hcomp 0 1)) + have hr : 0 ≤ ∏ a ∈ R, w a := Finset.prod_nonneg (fun a _ => le_of_lt (hw a)) + have h := mul_le_mul_of_nonneg_left hp hr + simp only [matchingWeight,hA,hB,Finset.prod_union hdA,Finset.prod_union hdB, + Finset.prod_pair h02,Finset.prod_pair h13] + nlinarith only [h] + +omit [DecidableEq V] in +lemma SafeSwitch.gibbs_ratio {w : E → ℝ} (hw : ∀ e, 0 < w e) {K : ℝ} + {A B : PM inc} (h : SafeSwitch w K A B) : gibbs w A ≤ K^2 * gibbs w B := by + dsimp only [gibbs] + rw [← mul_div_assoc] + exact div_le_div_of_nonneg_right (h.weight_ratio hw) (le_of_lt (partition_pos w hw A)) + +omit [DecidableEq V] in +lemma SafeSwitch.min_capacity {w : E → ℝ} (hw : ∀ e, 0 < w e) {K : ℝ} (hK : 1 ≤ K) + {A B : PM inc} (h : SafeSwitch w K A B) : gibbs w A ≤ K^2 * min (gibbs w A) (gibbs w B) := by + rw [mul_min_of_nonneg _ _ (sq_nonneg K)] + apply le_min + · have hp := le_of_lt (gibbs_pos w hw A) + have hsq : 1 ≤ K^2 := by nlinarith + nlinarith + · exact h.gibbs_ratio hw + +end + +section + +variable {V E : Type*} [Fintype V] [DecidableEq V] [Fintype E] [DecidableEq E] + +variable (ends : E → Sym2 V) + +omit [DecidableEq V] [Fintype E] in +lemma ColorChange.weight_ratio {w : E → ℝ} (hw : ∀ e, 0 < w e) {K : ℝ} (hK : 1 ≤ K) + (hcomp : ∀ e f, ends e = ends f → w e ≤ K*w f) + {A B : PM (fun e v => v ∈ ends e)} (h : ColorChange ends A B) : + matchingWeight w A ≤ K * matchingWeight w B := by + classical + obtain ⟨e,f,R,hef,hA,hB⟩ := h + by_cases heq : e = f + · have hAB : A = B := Subtype.ext (by rw [hA,hB,heq]) + subst B + have hp := le_of_lt (matchingWeight_pos w hw A) + nlinarith + · obtain ⟨v,hv⟩ : ∃ v, v ∈ ends e := by + induction ends e using Sym2.inductionOn with | hf a b => exact ⟨a,by simp⟩ + have hRA : R ⊆ A.val := by rw [hA]; exact Finset.subset_union_left + have hRB : R ⊆ B.val := by rw [hB]; exact Finset.subset_union_left + have hae : e ∈ A.val := by rw [hA]; simp + have hbf : f ∈ B.val := by rw [hB]; simp + have hre : e ∉ R := by + intro hr + exact heq (B.property.unique (Finset.mem_univ v) (hRB hr) hv hbf (hef ▸ hv)) + have hrf : f ∉ R := by + intro hr + exact heq (A.property.unique (Finset.mem_univ v) hae hv (hRA hr) (hef ▸ hv)) + have hdA : Disjoint R {e} := Finset.disjoint_singleton_right.mpr hre + have hdB : Disjoint R {f} := Finset.disjoint_singleton_right.mpr hrf + have hr : 0 ≤ ∏ a ∈ R, w a := Finset.prod_nonneg (fun a _ => le_of_lt (hw a)) + have h := mul_le_mul_of_nonneg_left (hcomp e f hef) hr + simp only [matchingWeight,hA,hB,Finset.prod_union hdA,Finset.prod_union hdB,Finset.prod_singleton] + nlinarith only [h] + +omit [DecidableEq V] in +lemma ColorChange.min_capacity {w : E → ℝ} (hw : ∀ e, 0 < w e) {K : ℝ} (hK : 1 ≤ K) + (hcomp : ∀ e f, ends e = ends f → w e ≤ K*w f) + {A B : PM (fun e v => v ∈ ends e)} (h : ColorChange ends A B) : + gibbs w A ≤ K * min (gibbs w A) (gibbs w B) := by + rw [mul_min_of_nonneg _ _ (by linarith : 0 ≤ K)] + apply le_min + · have hp := le_of_lt (gibbs_pos w hw A) + nlinarith + · dsimp only [gibbs] + rw [← mul_div_assoc] + exact div_le_div_of_nonneg_right (h.weight_ratio ends hw hK hcomp) + (le_of_lt (partition_pos w hw A)) + +end + +section + +variable {V L : Type*} [Fintype V] [DecidableEq V] [Fintype L] [DecidableEq L] + +variable {bags : V → Finset L} {G : SimpleGraph L} + +variable (hbags : ∀ v, ∀ a ∈ bags v, ∀ b ∈ bags v, a = b ∨ G.Adj a b) + +variable (height : L → ℝ) (hheight : ∀ l, 0 < height l) + +variable (hstep : ∀ a b, G.Adj a b → height a ≤ 2 * height b) + +variable (D : ℝ) (hD : 1 ≤ D) (w : BagEdge bags → ℝ) + +variable (hw : ∀ e, height e.color / D ≤ w e ∧ w e ≤ 3 * height e.color) + +variable (lo hi : ℝ) (hlo : 0 < lo) + +include hbags hheight hstep hD hw hlo in +omit [Fintype V] [DecidableEq V] [Fintype L] [DecidableEq L] in +lemma color_clamp_comparability (e f : BagEdge bags) (hef : e.val.val.1 = f.val.val.1) : + max lo (min hi (w e)) ≤ (1000*D) * max lo (min hi (w f)) := by + obtain ⟨v,hev⟩ := BagEdge.exists_incident e + have hfv : f.Incident v := by + change v ∈ f.val.val.1 + rw [← hef] + exact hev + have hc := hbags v _ (BagEdge.color_mem e hev) _ (BagEdge.color_mem f hfv) + have hh : height e.color ≤ 2 * height f.color := by + rcases hc with h | h + · rw [h]; nlinarith [hheight f.color] + · exact hstep _ _ h + have hDpos : 0 < D := by linarith + have hfpos : 0 < w f := lt_of_lt_of_le (div_pos (hheight f.color) hDpos) (hw f).1 + have hlow : height f.color ≤ w f * D := (div_le_iff₀ hDpos).mp (hw f).1 + apply IndexedCycle.common_clamp_ratio (le_of_lt hlo) (by linarith) + nlinarith [(hw e).2,mul_pos hDpos hfpos] + +end + +variable {V E : Type*} [Fintype V] [DecidableEq V] [Fintype E] [DecidableEq E] + +variable {inc : E → V → Prop} + +def TwoEdgeSwitch (A B : PM inc) : Prop := + ∃ (v : Fin 4 → V) (e : Fin 4 → E) (R : Finset E), + Function.Injective v ∧ + (∀ i x, inc (e i) x ↔ x = v i ∨ x = v (i+1)) ∧ + A.val = R ∪ {e 0,e 2} ∧ B.val = R ∪ {e 1,e 3} + +omit [DecidableEq V] [Fintype E] in +lemma SafeSwitch.legal {w : E → ℝ} {K : ℝ} {A B : PM inc} (h : SafeSwitch w K A B) : + TwoEdgeSwitch A B := by + obtain ⟨v,e,R,hv,he,hA,hB,_⟩ := h + exact ⟨v,e,R,hv,he,hA,hB⟩ + +omit [DecidableEq V] [Fintype E] in +lemma TwoEdgeSwitch.two_le {A B : PM inc} (h : TwoEdgeSwitch A B) : 2 ≤ A.val.card := by + classical + obtain ⟨v,e,R,hv,he,hA,hB⟩ := h + have h02 : e 0 ≠ e 2 := by + intro h + have h0 := (he 0 (v 0)).mpr (Or.inl rfl) + rw [h] at h0 + rcases (he 2 (v 0)).mp h0 with h | h + · have := hv h; exact (by decide : (0:Fin 4) ≠ 2) this + · have := hv h; exact (by decide : (0:Fin 4) ≠ 2+1) this + have hs : {e 0,e 2} ⊆ A.val := by rw [hA]; exact Finset.subset_union_right + simpa only [Finset.card_pair h02] using Finset.card_le_card hs + +omit [DecidableEq V] [Fintype E] [DecidableEq E] in +lemma PM.card_le_vertices (hinc : ∀ e, ∃ v, inc e v) (A : PM inc) : A.val.card ≤ Fintype.card V := by + classical + let vertex : ↥A.val → V := fun e => Classical.choose (hinc e.val) + have hv (e : ↥A.val) : inc e.val (vertex e) := Classical.choose_spec (hinc e.val) + have hinj : Function.Injective vertex := by + intro e f h + apply Subtype.ext + exact A.property.unique (Finset.mem_univ (vertex e)) e.property (hv e) f.property (h ▸ hv f) + simpa only [Fintype.card_coe] using Fintype.card_le_of_injective vertex hinj + +noncomputable def switchDestinations (A : PM inc) : Finset (PM inc) := by + classical + exact Finset.univ.filter (TwoEdgeSwitch A) + +noncomputable def discrepancyComponents (A B : PM inc) : Finset (Finset E) := by + classical + exact (components (inc := inc) (A.val ∪ B.val)).filter (fun S => ¬ S ⊆ A.val ∩ B.val) + +noncomputable def switchDirichlet (w : E → ℝ) (f : Finset E → ℝ) : ℝ := + ∑ A : PM inc, ∑ B ∈ switchDestinations A, + min (gibbs w A) (gibbs w B) * (f A.val-f B.val)^2 / (48 * (A.val.card.choose 2 : ℝ)) + +noncomputable def cycleSquare (f g : Finset E → ℝ) (A B : Finset E) (S : Finset E) : ℝ := + ((f A+g B)-(f (exchange A B S)+g (exchange B A S)))^2 + +noncomputable def cycleDirichlet (w : E → ℝ) (f g : Finset E → ℝ) : ℝ := + ∑ A : PM inc, ∑ B : PM inc, gibbs w A * gibbs w B * + (∑ S ∈ discrepancyComponents A B, cycleSquare f g A.val B.val S / + (6 * ((discrepancyComponents A B).card : ℝ))) + +variable (ends : E → Sym2 V) + +noncomputable def colorDirichlet (w : E → ℝ) (f : Finset E → ℝ) : ℝ := + ∑ A : PM (fun e v => v ∈ ends e), ∑ B ∈ colorDestinations ends A, + min (gibbs w A) (gibbs w B) * (f A.val-f B.val)^2 / (12 * (A.val.card : ℝ)) + +noncomputable def pairDirichlet (w : E → ℝ) (f g : Finset E → ℝ) : ℝ := + switchDirichlet (inc := fun e v => v ∈ ends e) w f + colorDirichlet ends w f + + cycleDirichlet (inc := fun e v => v ∈ ends e) w f g + +lemma scale_div_lower {x a b : ℝ} (hx : 0 ≤ x) (ha : 0 < a) (hab : a ≤ b) : + x ≤ b * (x/a) := by + calc + x = a * (x/a) := by field_simp [ne_of_gt ha] + _ ≤ b * (x/a) := mul_le_mul_of_nonneg_right hab (div_nonneg hx (le_of_lt ha)) + +omit [DecidableEq V] in +lemma switchDirichlet_nonneg (w : E → ℝ) (hw : ∀ e, 0 < w e) (f : Finset E → ℝ) : + 0 ≤ switchDirichlet (inc := inc) w f := by + apply Finset.sum_nonneg + intro A _ + apply Finset.sum_nonneg + intro B _ + exact div_nonneg (mul_nonneg (le_min (le_of_lt (gibbs_pos w hw A)) + (le_of_lt (gibbs_pos w hw B))) (sq_nonneg _)) (by positivity) + +omit [DecidableEq V] in +lemma colorDirichlet_nonneg (w : E → ℝ) (hw : ∀ e, 0 < w e) (f : Finset E → ℝ) : + 0 ≤ colorDirichlet ends w f := by + apply Finset.sum_nonneg + intro A _ + apply Finset.sum_nonneg + intro B _ + exact div_nonneg (mul_nonneg (le_min (le_of_lt (gibbs_pos w hw A)) + (le_of_lt (gibbs_pos w hw B))) (sq_nonneg _)) (by positivity) + +omit [DecidableEq V] in +lemma cycleDirichlet_nonneg (w : E → ℝ) (hw : ∀ e, 0 < w e) (f g : Finset E → ℝ) : + 0 ≤ cycleDirichlet (inc := inc) w f g := by + apply Finset.sum_nonneg + intro A _ + apply Finset.sum_nonneg + intro B _ + apply mul_nonneg (mul_nonneg (le_of_lt (gibbs_pos w hw A)) (le_of_lt (gibbs_pos w hw B))) + exact Finset.sum_nonneg (fun S _ => div_nonneg (sq_nonneg _) (by positivity)) + +end MatchingFPRAS.Transport + +end OAI diff --git a/lean/OAI/Combinatorics/MatchingCount/Sampling/Endpoints.lean b/lean/OAI/Combinatorics/MatchingCount/Sampling/Endpoints.lean new file mode 100644 index 0000000000000000000000000000000000000000..9ff3b68ff73d6e275fd7cf86bee69f05da5525d6 --- /dev/null +++ b/lean/OAI/Combinatorics/MatchingCount/Sampling/Endpoints.lean @@ -0,0 +1,420 @@ +import Mathlib +import OAI.Combinatorics.MatchingCount.Probability.FinitePMF +import OAI.Combinatorics.MatchingCount.Graphs.CompleteGraph + +namespace OAI + +namespace MatchingFPRAS.GraphBridge + +open Finset MatchingFPRAS.Enlargement MatchingFPRAS.Subdivision MatchingFPRAS.Representation MatchingFPRAS.Switching + +variable {n : ℕ} + +def endpoints : LogicalEdge (Fin n) ↪ (Fin n × Fin n) := ⟨Subtype.val,Subtype.val_injective⟩ + +def selectedEdges (s : LogicalEdge (Fin n) → Bool) : Finset (Fin n × Fin n) := + (univ.filter fun e => s e=true).map endpoints + +lemma mem_selected (s : LogicalEdge (Fin n) → Bool) (e : LogicalEdge (Fin n)) : + e.val ∈ selectedEdges s ↔ s e=true := by simp [selectedEdges,endpoints] + +lemma selected_increasing (s : LogicalEdge (Fin n) → Bool) : + selectedEdges s ⊆ (completeGraph n).edges := by + intro e he + obtain ⟨f,hf,rfl⟩ := mem_map.mp he + exact mem_filter.mpr ⟨mem_univ _,f.property⟩ + +def edgeSelection (M : Finset (Fin n × Fin n)) (e : LogicalEdge (Fin n)) : Bool := decide (e.val∈M) + +@[simp] lemma edgeSelection_selected (s : LogicalEdge (Fin n) → Bool) : + edgeSelection (selectedEdges s)=s := by + funext e + apply Bool.eq_iff_iff.mpr + simp [edgeSelection,mem_selected] + +lemma selected_edgeSelection (M : Finset (Fin n × Fin n)) (hM : M⊆(completeGraph n).edges) : + selectedEdges (edgeSelection M)=M := by + ext e + constructor + · intro he + obtain ⟨f,hf,rfl⟩ := mem_map.mp he + simpa [edgeSelection,endpoints] using (mem_filter.mp hf).2 + · intro he + have hi : e.1 < e.2 := (mem_filter.mp (hM he)).2 + apply mem_map.mpr + exact ⟨⟨e,hi⟩,mem_filter.mpr ⟨mem_univ _,by simp [edgeSelection,he]⟩,rfl⟩ + +lemma logical_iff_perfect (s : LogicalEdge (Fin n) → Bool) : + LogicalHoles source target ∅ ∅ s ↔ Perfect (completeGraph n) (selectedEdges s) := by + constructor + · intro hs + refine ⟨selected_increasing s,?_⟩ + intro v + obtain ⟨e,he,hu⟩ := hs.2.2 v (by simp) + refine ⟨e.val,⟨(mem_selected s e).mpr he.1,he.2⟩,?_⟩ + intro f hf + have hi := (completeGraph n).increasing f (selected_increasing s hf.1) + have hf' : s ⟨f,hi⟩=true := (mem_selected s ⟨f,hi⟩).mp hf.1 + exact congrArg Subtype.val (hu ⟨f,hi⟩ ⟨hf',hf.2⟩) + · intro hs + refine ⟨by simp,by simp,?_⟩ + intro v _ + obtain ⟨e,he,hu⟩ := hs.2 v + have hi := (completeGraph n).increasing e (hs.1 he.1) + refine ⟨⟨e,hi⟩,⟨(mem_selected s ⟨e,hi⟩).mp he.1,he.2⟩,?_⟩ + intro f hf + exact Subtype.ext (hu f.val ⟨(mem_selected s f).mpr hf.1,hf.2⟩) + +noncomputable def perfectEquiv : + {s : LogicalEdge (Fin n) → Bool // LogicalHoles source target ∅ ∅ s} ≃ + {M : Finset (Fin n × Fin n) // Perfect (completeGraph n) M} where + toFun s := ⟨selectedEdges s.val,(logical_iff_perfect s.val).mp s.property⟩ + invFun M := ⟨edgeSelection M.val,(logical_iff_perfect _).mpr (by + rw [selected_edgeSelection M.val M.property.1]; exact M.property)⟩ + left_inv s := Subtype.ext (edgeSelection_selected s.val) + right_inv M := Subtype.ext (selected_edgeSelection M.val M.property.1) + +lemma selected_prod {A : Type*} [CommMonoid A] (s : LogicalEdge (Fin n) → Bool) + (w : Fin n × Fin n → A) : + (∏ e ∈ selectedEdges s,w e)=∏ e : LogicalEdge (Fin n),if s e then w e.val else 1 := by + rw [selectedEdges,prod_map] + exact prod_filter (fun e => s e=true) (fun e => w e.val) + +theorem weighted_partition (w : Fin n → Fin n → ℝ) : + (∑ M ∈ perfectMatchings (completeGraph n),∏ e ∈ M,w e.1 e.2)=partition w ∅ := by + classical + rw [←logical_partition_eq w ∅] + let := Fintype.ofFinite {s : LogicalEdge (Fin n) → Bool // LogicalHoles source target ∅ ∅ s} + let := Fintype.ofFinite {M : Finset (Fin n × Fin n) // Perfect (completeGraph n) M} + rw [Finset.sum_subtype (perfectMatchings (completeGraph n)) (mem_perfectMatchings _)] + unfold logicalHolePartition + symm + apply Fintype.sum_equiv perfectEquiv + intro s + rw [show (perfectEquiv s).val=selectedEdges s.val from rfl,selected_prod] + apply prod_congr rfl + intro e _ + simp [logicalActivity,edgeActivity,source,target,e.property] + +noncomputable def rawActivity (G : GraphInput) (x : ℝ) (a b : Fin G.n) : ℝ := + if (min a b,max a b)∈G.edges then 1 else x + +lemma rawActivity_pos (G : GraphInput) (x : ℝ) (hx : 0 < x) : ∀ a b,0 < rawActivity G x a b := by + intro a b + unfold rawActivity + split_ifs <;> positivity + +lemma rawActivity_symm (G : GraphInput) (x : ℝ) (a b : Fin G.n) : + rawActivity G x a b=rawActivity G x b a := by simp [rawActivity,min_comm,max_comm] + +theorem raw_partition (G : GraphInput) (x : ℚ) : + (rawPartition G x:ℝ)=partition (rawActivity G x) ∅ := by + unfold rawPartition rawWeight + push_cast + rw [←weighted_partition] + apply sum_congr rfl + intro M hM + apply prod_congr rfl + intro e he + have hi := (completeGraph G.n).increasing e (((mem_perfectMatchings (completeGraph G.n) M).mp hM).1 he) + simp only [rawActivity,min_eq_left hi.le,max_eq_right hi.le] + split_ifs <;> simp + +theorem complete_count : + Z (completeGraph n)=UnitRefresh.pairingCount n := by + have h := weighted_partition (n:=n) (fun _ _ => 1) + simp only [prod_const_one,sum_const,nsmul_eq_mul,mul_one] at h + rw [Initializer.uniform_partition,card_empty,Nat.sub_zero,one_pow,mul_one,Fintype.card_fin] at h + exact_mod_cast h + +end MatchingFPRAS.GraphBridge + +namespace MatchingFPRAS.Trial + +open Finset Switching Subdivision RealGeometry Hierarchy Transport Enlargement StageAnalysis +open scoped Classical + +noncomputable def cooling (n : ℕ) : ℝ := (1+1/(n:ℝ))⁻¹ + +lemma cooling_pos (n : ℕ) : 01) := by + funext a b + simp [raw,GraphBridge.rawActivity] + +lemma raw_partition_pos (G : GraphInput) (he : Even G.n) (j : ℕ) : 0 raw G j a b*s.scale a*s.scale b + +noncomputable def ScaleState.nextActivity (s : ScaleState G j) : Fin G.n → Fin G.n → ℝ := + fun a b => raw G (j+1) a b*s.scale a*s.scale b + +lemma ScaleState.activity_pos (s : ScaleState G j) (a b : Fin G.n) : 0 < s.activity a b := + mul_pos (mul_pos (raw_pos G j a b) (s.positive a)) (s.positive b) + +lemma ScaleState.nextActivity_pos (s : ScaleState G j) (a b : Fin G.n) : 0 < s.nextActivity a b := + mul_pos (mul_pos (raw_pos G (j+1) a b) (s.positive a)) (s.positive b) + +lemma ScaleState.cooling (s : ScaleState G j) (a b : Fin G.n) : + cooling G.n*s.activity a b ≤ s.nextActivity a b ∧ s.nextActivity a b ≤ s.activity a b := by + have h := raw_cooling G j a b + constructor + · have hh := mul_le_mul_of_nonneg_right (mul_le_mul_of_nonneg_right h.1 (s.positive a).le) (s.positive b).le + simpa [ScaleState.activity,ScaleState.nextActivity,mul_assoc] using hh + · exact mul_le_mul_of_nonneg_right (mul_le_mul_of_nonneg_right h.2 (s.positive a).le) (s.positive b).le + +lemma ScaleState.activity_bound (s : ScaleState G j) (a b : Fin G.n) : s.activity a b ≤ (4:ℝ)^j := by + calc + _ ≤ 1*(2:ℝ)^j*2^j := by + apply mul_le_mul (mul_le_mul (raw_le_one G j a b) (s.upper a) (s.positive a).le (by norm_num)) + (s.upper b) (s.positive b).le (by positivity) + _ = (4:ℝ)^j := by rw [one_mul,←mul_pow]; norm_num + +lemma ScaleState.cap (s : ScaleState G j) (h : j ≤ K) (a b : Fin G.n) (_hab : a≠b) : + edgeActivity s.activity a b ≤ (4:ℝ)^K := by + unfold edgeActivity + split_ifs + all_goals exact (s.activity_bound _ _).trans (pow_le_pow_right₀ (by norm_num) h) + +lemma ScaleState.partition_pos (s : ScaleState G j) (he : Even G.n) : 0 s.positive x) + exact mul_div_mul_right _ _ hp + +noncomputable def initialScaleState (G : GraphInput) (hn : 2 ≤ G.n) : ScaleState G 0 where + scale _ := (Initializer.initialScale G.n:ℝ) + positive _ := by exact_mod_cast Initializer.initialScale_pos G.n hn + upper _ := by + unfold Initializer.initialScale + push_cast + simp only [pow_zero] + have hs : 1 ≤ Nat.sqrt (G.n-1) := Nat.le_sqrt.mpr (by omega) + have hs' : (1:ℝ) ≤ Nat.sqrt (G.n-1) := by exact_mod_cast hs + simpa using one_div_le_one_div_of_le (by norm_num : (0:ℝ)<1) hs' + +def ScaleState.Balanced (hn : 2 ≤ G.n) (s : ScaleState G j) : Prop := + (∀ i,(1:ℝ)/4 ≤ rowMax (by simpa using hn) s.activity i) ∧ + (∀ i,rowMax (by simpa using hn) s.activity i ≤ 1) + +lemma initial_balanced (G : GraphInput) (hn : 2 ≤ G.n) (he : Even G.n) : + (initialScaleState G hn).Balanced hn := by + have h := Initializer.initial_balanced (V:=Fin G.n) (by simpa using hn) (by simpa using he) + have ha : (initialScaleState G hn).activity=(fun _ _ : Fin G.n => (Initializer.initialScale G.n:ℝ)^2) := by + funext a b + simp [ScaleState.activity,raw_zero,initialScaleState,pow_two] + simpa only [ScaleState.Balanced,ha,Fintype.card_fin] using h.2 + +variable [Nontrivial (Fin G.n)] + +noncomputable local instance (w : Fin G.n → Fin G.n → ℝ) (K : ℕ) : DecidableEq (SourceLabel w K) := Classical.decEq _ + +noncomputable local instance (w : Fin G.n → Fin G.n → ℝ) (K : ℕ) : Fintype (BagEdge (sourceBags w K)) := Fintype.ofFinite _ + +noncomputable def ScaleState.matrix (s : ScaleState G j) (x : Fin S → SourceMarked s.activity K) : + Fin G.n → Fin G.n → ℝ := + estimateMatrix (sourceD (V:=Fin G.n) K) (sampleAverage (observableD s.activity s.nextActivity K) x) + (fun e => sampleAverage (observableProbe s.activity s.nextActivity K e) x) + +lemma ScaleState.matrix_bounds (s : ScaleState G j) (x : Fin S → SourceMarked s.activity K) (a b : Fin G.n) : + RealStage.alpha ≤ s.matrix x a b ∧ s.matrix x a b ≤ 3 := by + unfold ScaleState.matrix estimateMatrix RealStage.upperEstimate + split_ifs + · exact ⟨le_max_left _ _,max_le (by norm_num [RealStage.alpha]) (min_le_left _ _)⟩ + · norm_num [RealStage.alpha] + +noncomputable def ScaleState.updateVector (hn : 2 ≤ G.n) (s : ScaleState G j) + (x : Fin S → SourceMarked s.activity K) : Fin G.n → ℝ := + RealStage.scalingTrace hn (s.matrix x) G.n + +lemma ScaleState.updateVector_bounds (hn : 2 ≤ G.n) (s : ScaleState G j) + (x : Fin S → SourceMarked s.activity K) : + ∀ i,0 < s.updateVector hn x i ∧ s.updateVector hn x i ≤ 2 := by + have h := (RealStage.scalingTrace_invariant hn (s.matrix x) + (estimateMatrix_symm _ _ _) (fun a b _ => s.matrix_bounds x a b) G.n).1 + intro i + exact ⟨h.pos i,h.upper i⟩ + +noncomputable def ScaleState.update (hn : 2 ≤ G.n) (s : ScaleState G j) + (x : Fin S → SourceMarked s.activity K) : ScaleState G (j+1) where + scale i := s.scale i*s.updateVector hn x i + positive i := mul_pos (s.positive i) (s.updateVector_bounds hn x i).1 + upper i := by + rw [pow_succ] + exact mul_le_mul (s.upper i) (s.updateVector_bounds hn x i).2 + (s.updateVector_bounds hn x i).1.le (by positivity) + +lemma ScaleState.update_activity (hn : 2 ≤ G.n) (s : ScaleState G j) + (x : Fin S → SourceMarked s.activity K) : + (s.update hn x).activity=(fun a b=>s.nextActivity a b*s.updateVector hn x a*s.updateVector hn x b) := by + funext a b + simp only [ScaleState.activity,ScaleState.update,ScaleState.nextActivity] + ring + +noncomputable def ScaleState.ratioEstimate (s : ScaleState G j) (x : Fin S → SourceMarked s.activity K) : ℝ := + RealStage.ratioEstimate (sampleAverage (observableA s.activity K) x) + (sampleAverage (observableD s.activity s.nextActivity K) x) + +lemma ScaleState.ratioEstimate_nonneg (s : ScaleState G j) (_hS : 0(s.nextActivity_pos a b).le) (fun a b _=>(s.cooling a b).2) K (x i)).1 + · norm_num + +noncomputable def stageData (G : GraphInput) (hn : 2 ≤ G.n) (he : Even G.n) (K : ℕ) (hK : 0(hh.2.1 i).1,fun i=>(hh.2.1 i).2⟩ + · rw [←s.ratio] + exact hh.2.2 + +end MatchingFPRAS.Trial + +namespace MatchingFPRAS.Counting + +theorem stage_product_error (K : ℕ) (hK : 1 ≤ K) (epsilon : ℝ) + (he : 0 < epsilon) (he1 : epsilon < 1) (factors : Fin K → ℝ) + (herr : ∀ j, |factors j-1| ≤ epsilon/(100*K)) : + 1-epsilon/100 ≤ ∏ j, factors j ∧ ∏ j, factors j ≤ 1+epsilon/50 := by + classical + have hKr : (1:ℝ) ≤ K := by exact_mod_cast hK + have hKp : (0:ℝ) < K := by linarith + let t : ℝ := epsilon/(100*K) + have ht0 : 0 ≤ t := by dsimp [t]; positivity + have ht1 : t ≤ epsilon/100 := by + dsimp [t] + apply (div_le_iff₀ (by positivity : 0 < (100:ℝ)*K)).mpr + nlinarith [mul_le_mul_of_nonneg_left hKr he.le] + have hkt : (K:ℝ)*t=epsilon/100 := by dsimp [t]; field_simp + have hlo (j : Fin K) : 1-t ≤ factors j := by + have h := (abs_le.mp (herr j)).1 + change -t ≤ factors j-1 at h + linarith + have hup (j : Fin K) : factors j ≤ 1+t := by + have h := (abs_le.mp (herr j)).2 + change factors j-1 ≤ t at h + linarith + have hf0 (j : Fin K) : 0 ≤ factors j := by have := hlo j; linarith + constructor + · have hpow : 1-epsilon/100 ≤ (1-t)^K := by + have h := one_add_mul_le_pow (a := -t) (by linarith : (-2:ℝ) ≤ -t) K + simpa only [← sub_eq_add_neg, mul_neg, hkt] using h + apply hpow.trans + calc + (1-t)^K = ∏ _j : Fin K, (1-t) := by simp + _ ≤ ∏ j, factors j := Finset.prod_le_prod₀ (fun _ _ => by linarith) (fun j _ => hlo j) + · have hprod : (∏ j, factors j) ≤ Real.exp (epsilon/100) := by + calc + _ ≤ ∏ _j : Fin K, (1+t) := Finset.prod_le_prod₀ (fun j _ => hf0 j) (fun j _ => hup j) + _ ≤ Real.exp (∑ _j : Fin K, t) := Real.prod_one_add_le_exp_sum _ (fun _ => ht0) + _ = Real.exp (epsilon/100) := by simp [hkt] + apply hprod.trans + have hh := Real.exp_le_two_add_div_two_sub (x := epsilon/100) (by positivity) (by linarith) + apply hh.trans + apply (div_le_iff₀ (by linarith : 0 < 2-epsilon/100)).mpr + nlinarith [sq_nonneg epsilon] + + + +def productEstimate {K : ℕ} (initial : ℝ) (estimates : Fin K → ℝ) : ℝ := + initial * ∏ j, estimates j + + + +lemma positive_telescope (Z : ℕ → ℝ) (hZ : ∀ j, 0 < Z j) (K : ℕ) : + (∏ j : Fin K, Z (j.val+1)/Z j.val)=Z K/Z 0 := by + induction K with + | zero => simp [(hZ 0).ne'] + | succ K ih => + rw [Fin.prod_univ_castSucc] + change (∏ j : Fin K, Z (j.val+1)/Z j.val)*(Z (K+1)/Z K)=_ + rw [ih] + field_simp [(hZ K).ne', (hZ 0).ne'] + +end MatchingFPRAS.Counting + +end OAI diff --git a/lean/OAI/Combinatorics/MatchingCount/Sampling/Endpoints2.lean b/lean/OAI/Combinatorics/MatchingCount/Sampling/Endpoints2.lean new file mode 100644 index 0000000000000000000000000000000000000000..c178ce60bd94516dd4129a24dba88fad8be034d0 --- /dev/null +++ b/lean/OAI/Combinatorics/MatchingCount/Sampling/Endpoints2.lean @@ -0,0 +1,125 @@ +import Mathlib +import OAI.Combinatorics.MatchingCount.Graphs.CompleteGraph +import OAI.Combinatorics.MatchingCount.Machines.TreePostRealization + +namespace OAI + +namespace MatchingFPRAS +lemma vertex_bound_of_perfect {G : GraphInput} {M : Finset (Fin G.n×Fin G.n)} + (hM : Perfect G M) : G.n≤2*G.edges.card := by + classical + have hc : (Finset.univ : Finset (Fin G.n))⊆M.image Prod.fst ∪ M.image Prod.snd := by + intro v _ + obtain ⟨e,he,-⟩:=hM.2 v + rcases he.2 with hv|hv + · exact Finset.mem_union_left _ (Finset.mem_image.mpr ⟨e,he.1,hv⟩) + · exact Finset.mem_union_right _ (Finset.mem_image.mpr ⟨e,he.1,hv⟩) + have h₁:=Finset.card_le_card hc + have h₂:=Finset.card_union_le (M.image Prod.fst) (M.image Prod.snd) + have h₃:=Finset.card_image_le (s:=M) (f:=Prod.fst) + have h₄:=Finset.card_image_le (s:=M) (f:=Prod.snd) + have h₅:=Finset.card_le_card hM.1 + simp only [Finset.card_univ,Fintype.card_fin] at h₁ + omega + +lemma zero_of_vertex_bound {G : GraphInput} (h : 2*G.edges.card(-1:ℚ)) + have hh : (-1:ℚ)^G.n=1 := by + simpa using h.symm + exact (neg_one_pow_eq_one_iff_even (by norm_num : (-1:ℚ)≠1)).mp hh + +lemma zero_of_not_even {G : GraphInput} (he : ¬Even G.n) : Z G=0 := by + by_contra hz + obtain ⟨M,hM⟩:=Finset.card_pos.mp (Nat.pos_of_ne_zero hz) + exact he (even_of_perfect ((mem_perfectMatchings G M).mp hM)) + +lemma count_empty_graph {G : GraphInput} (hn : G.n=0) : Z G=1 := by + classical + have hv (v : Fin G.n) : False := by have := v.isLt; omega + have he : G.edges=∅ := Finset.eq_empty_of_forall_notMem (fun e _=>hv e.1) + have hp : Perfect G ∅ := ⟨Finset.empty_subset _,fun v=>False.elim (hv v)⟩ + simp only [Z,perfectMatchings,he,Finset.powerset_empty] + have hf : Finset.filter (Perfect G) {∅}=({∅} : Finset (Finset (Fin G.n×Fin G.n))) := by + ext M + simp only [Finset.mem_filter,Finset.mem_singleton] + constructor + · exact And.left + · rintro rfl + exact ⟨rfl,hp⟩ + rw [hf] + rfl + +lemma edgeCard_le_input_length (G : GraphInput) (ε δ : ℚ) : + G.edges.card≤(encodeInput G ε δ).length := by + have hl (l : List (Fin G.n ×ₗ Fin G.n)) : l.length≤ + (l.flatMap fun e=>encodeNat (ofLex e).1.val++encodeNat (ofLex e).2.val).length := by + induction l with + | nil => simp + | cons a as ih => + simp only [List.flatMap_cons,List.length_append,List.length_cons] + have ha : 1≤(encodeNat (ofLex a).1.val).length := by + simp only [encodeNat,List.length_append,List.length_map,List.length_singleton] + omega + omega + have h:=hl ((G.edges.map toLex.toEmbedding).sort (·≤·)) + simp only [Finset.length_sort,Finset.card_map] at h + simp only [encodeInput,List.length_append] + omega + +lemma positive_vertex_input_bound {G : GraphInput} (ε δ : ℚ) (hZ : 0(e.1.val,e.2.val)))) +def tooSparse (x : SparseInput) : Bool := decide (2*x.2.length max lo (min hi (w e)) + ∃ enc : DemandEncoding BagEdge.Incident (k.rawDemand M N flags), + enc.first.val = emb.outsideFirst ∪ (c.pathsOfCell hbags hc hy).switched b ∧ + gibbs wt M * gibbs wt N ≤ + (1000*D)^4 * gibbs wt enc.first * gibbs wt enc.second := by + classical + dsimp only + let k := c.cellCorners hbags hc hy + let emb := k.embeddedPair M N hU (c.cellChords hbags hc hy) + (c.cellChords_incidence hbags hc hy) flags + obtain ⟨r, hg⟩ := c.cell_has_good_pair hbags hc hy + have hr := c.cell_actual_repairs hbags hc hy r hg + let enc := emb.switchEncoding BagEdge.exists_incident b r (c.leafRepair hbags k) hr + refine ⟨enc, rfl, ?_⟩ + apply enc.gibbs_bound (fun e => max lo (min hi (w e))) + (fun e => lt_of_lt_of_le hlo (le_max_left _ _)) (1000*D) (by linarith) + · exact ((c.pathsOfCell hbags hc hy).modification_cards b r (c.leafRepair hbags k)).1 + · intro e he f hf + exact c.cell_clamp_comparability hbags height hheight hstep hc hy D hD w hw lo hi + (le_of_lt hlo) (c.drops_local hbags hc hy r he) + (c.additions_local hbags hc hy b r hg hf) + +theorem actual_error_encodings + (M N : PM (BagEdge.Incident (bags := bags))) + (hU : ∀ i, c.edgeAt i ∈ M.val ∪ N.val) + {x p q y : ℕ} (hc : (c.labelCycle hbags).Cell x p q y) (hy : y < c.size) + (flags : Fin 64) (b : Bool) (X Y : Fin 4) + (hX : CellPaths.sideBit X = b) (hY : CellPaths.sideBit Y = b) (hne : X ≠ Y) + (hl : ∀ i : Fin 4, CellPaths.sideBit i = b → (c.cellCorners hbags hc hy).length i ≠ 1) + (D : ℝ) (hD : 1 ≤ D) (w : BagEdge bags → ℝ) + (hw : ∀ e, height e.color / D ≤ w e ∧ w e ≤ 3 * height e.color) + (lo hi : ℝ) (hlo : 0 < lo) (_hlohi : lo ≤ hi) : + let k := c.cellCorners hbags hc hy + let emb := k.embeddedPair M N hU (c.cellChords hbags hc hy) + (c.cellChords_incidence hbags hc hy) flags + let cp := c.pathsOfCell hbags hc hy + let wt := fun e => max lo (min hi (w e)) + ∃ enc₀ enc₁ : DemandEncoding BagEdge.Incident (k.rawDemand M N flags), + enc₀.first.val = emb.outsideFirst ∪ cp.orientation b ∧ + enc₁.first.val = emb.outsideFirst ∪ cp.contextOne b Y ∧ + (cp.side X).closed (cp.chord X) ⊆ enc₀.second.val ∧ + (cp.side X).closed (cp.chord X) ⊆ enc₁.second.val ∧ + gibbs wt M * gibbs wt N ≤ (1000*D)^4 * gibbs wt enc₀.first * gibbs wt enc₀.second ∧ + gibbs wt M * gibbs wt N ≤ (1000*D)^4 * gibbs wt enc₁.first * gibbs wt enc₁.second := by + classical + dsimp only + let k := c.cellCorners hbags hc hy + let emb := k.embeddedPair M N hU (c.cellChords hbags hc hy) + (c.cellChords_incidence hbags hc hy) flags + have hg := c.cell_long_opposite_good hbags hc hy b hl + have hr := c.cell_actual_repairs hbags hc hy b hg + let enc₀ := emb.errorZeroEncoding BagEdge.exists_incident b (c.leafRepair hbags k) hr + let enc₁ := emb.errorOneEncoding BagEdge.exists_incident b (c.leafRepair hbags k) hr Y hY + refine ⟨enc₀, enc₁, rfl, rfl, + emb.zero_guide_contains BagEdge.exists_incident b _ hr X hX, + emb.one_guide_contains BagEdge.exists_incident b _ hr X Y hX hY hne, ?_, ?_⟩ + all_goals + first + | apply enc₀.gibbs_bound (fun e => max lo (min hi (w e))) + (fun e => lt_of_lt_of_le hlo (le_max_left _ _)) (1000*D) (by linarith) + | apply enc₁.gibbs_bound (fun e => max lo (min hi (w e))) + (fun e => lt_of_lt_of_le hlo (le_max_left _ _)) (1000*D) (by linarith) + · exact ((c.pathsOfCell hbags hc hy).modification_cards b b (c.leafRepair hbags k)).1 + · intro e he f hf + exact c.cell_clamp_comparability hbags height hheight hstep hc hy D hD w hw lo hi + (le_of_lt hlo) (c.drops_local hbags hc hy b he) + (c.additions_local hbags hc hy b b hg hf) + +end MatchingFPRAS.Transport.IndexedCycle + +namespace MatchingFPRAS.Transport + +section + +variable {V E : Type*} + +variable {inc : E → V → Prop} + +namespace IndexedCycle + +variable (c : IndexedCycle inc) + +lemma edgeAt_periodic (i : ℕ) : c.edgeAt (i + c.size) = c.edgeAt i := by + simp [edgeAt, index] + +variable [DecidableEq E] + +def intervalPattern (x y a : ℕ) : Finset E := + ((Finset.Ico x y).filter (fun i => i % 2 = a)).image c.edgeAt + +def parityPattern (a : ℕ) : Finset E := c.intervalPattern 0 c.size a + +lemma mem_intervalPattern (e : E) (x y a : ℕ) : + e ∈ c.intervalPattern x y a ↔ ∃ i, x ≤ i ∧ i < y ∧ i % 2 = a ∧ c.edgeAt i = e := by + simp only [intervalPattern, Finset.mem_image, Finset.mem_filter, Finset.mem_Ico] + aesop + +lemma intervalPattern_union {x y z : ℕ} (hxy : x ≤ y) (hyz : y ≤ z) (a : ℕ) : + c.intervalPattern x y a ∪ c.intervalPattern y z a = c.intervalPattern x z a := by + ext e + simp only [Finset.mem_union, c.mem_intervalPattern] + constructor + · rintro (⟨i,hi,hj,hp,he⟩ | ⟨i,hi,hj,hp,he⟩) + · exact ⟨i,hi,by omega,hp,he⟩ + · exact ⟨i,by omega,hj,hp,he⟩ + · rintro ⟨i,hi,hj,hp,he⟩ + by_cases h : i < y + · exact Or.inl ⟨i,hi,h,hp,he⟩ + · exact Or.inr ⟨i,by omega,hj,hp,he⟩ + +lemma intervalPattern_periodic {x y : ℕ} (a : ℕ) : + c.intervalPattern (x + c.size) (y + c.size) a = c.intervalPattern x y a := by + ext e + simp only [c.mem_intervalPattern] + constructor + · rintro ⟨i,hi,hj,hp,he⟩ + have hn : c.size ≤ i := by omega + refine ⟨i-c.size,by omega,by omega,?_,?_⟩ + · have hh := c.even + omega + · have eq : i - c.size + c.size = i := by omega + rw [← c.edgeAt_periodic, eq] + exact he + · rintro ⟨i,hi,hj,hp,he⟩ + refine ⟨i+c.size,by omega,by omega,?_,?_⟩ + · have hh := c.even + omega + · rw [c.edgeAt_periodic]; exact he + +lemma rotatedPattern {x : ℕ} (hx : x ≤ c.size) (a : ℕ) : + c.intervalPattern x (x+c.size) a = c.parityPattern a := by + rw [← c.intervalPattern_union hx (by omega) a] + have hh : c.intervalPattern c.size (x+c.size) a = c.intervalPattern 0 x a := by + simpa only [zero_add] using (c.intervalPattern_periodic (x := 0) (y := x) a) + rw [hh, Finset.union_comm, c.intervalPattern_union (by omega) hx a] + rfl + +lemma arc_through (x l : ℕ) (hx : x < c.size) (hl : 0 < l) + (hlt : l < c.size) (ho : l % 2 = 1) : + (c.arc x l hx hl hlt ho).through = c.intervalPattern x (x+l) (x%2) := by + ext e + simp only [OddPath.through, pathPattern, Finset.mem_image, Finset.mem_filter, + Finset.mem_Ico, c.mem_intervalPattern] + dsimp only [arc] + constructor + · rintro ⟨j,⟨⟨_,hj⟩,hp⟩,he⟩ + exact ⟨x+j,by omega,by omega,by omega,he⟩ + · rintro ⟨i,hi,hj,hp,he⟩ + refine ⟨i-x,⟨⟨by omega,by omega⟩,by omega⟩,?_⟩ + simpa only [Nat.add_sub_of_le hi] using he + +lemma arc_interior (x l : ℕ) (hx : x < c.size) (hl : 0 < l) + (hlt : l < c.size) (ho : l % 2 = 1) : + (c.arc x l hx hl hlt ho).interior = c.intervalPattern x (x+l) (1-x%2) := by + ext e + simp only [OddPath.interior, pathPattern, Finset.mem_image, Finset.mem_filter, + Finset.mem_Ico, c.mem_intervalPattern] + dsimp only [arc] + constructor + · rintro ⟨j,⟨⟨hj₀,hj₁⟩,hp⟩,he⟩ + exact ⟨x+j,by omega,by omega,by omega,he⟩ + · rintro ⟨i,hi,hj,hp,he⟩ + refine ⟨i-x,⟨⟨by omega,by omega⟩,by omega⟩,?_⟩ + simpa only [Nat.add_sub_of_le hi] using he + +variable [DecidableEq V] + +namespace Corners + +variable {c} (k : c.Corners) + +lemma cell_piece_interval (chord : Fin 4 → E) + (hc : ∀ i v, inc (chord i) v ↔ + v = (k.side i).vertex 0 ∨ v = (k.side i).vertex (k.side i).length) + (b : Bool) (i : Fin 4) : + (k.cellPaths chord hc).orientationPieces b i = + c.intervalPattern (k.start i) (k.stop i) (if b then k.a₀%2 else 1-k.a₀%2) := by + have hs := k.parity_start i + have hb := k.bounds i + have he : k.start i + k.length i = k.stop i := by dsimp [length]; omega + change (if CellPaths.sideBit i = b then (k.side i).through else (k.side i).interior) = _ + by_cases h : CellPaths.sideBit i = b + · rw [ite_eq_left h] + rw [show (k.side i).through = _ from c.arc_through _ _ _ _ _ _, he] + cases b <;> simp_all + · rw [ite_eq_right h] + rw [show (k.side i).interior = _ from c.arc_interior _ _ _ _ _ _, he] + cases b <;> cases hi : CellPaths.sideBit i <;> simp_all + congr 1 + omega + +lemma cell_orientation_parity (chord : Fin 4 → E) + (hc : ∀ i v, inc (chord i) v ↔ + v = (k.side i).vertex 0 ∨ v = (k.side i).vertex (k.side i).length) + (b : Bool) : + (k.cellPaths chord hc).orientation b = + c.parityPattern (if b then k.a₀%2 else 1-k.a₀%2) := by + have h₀ := k.lt₀ + have h₁ := k.lt₁ + have h₂ := k.lt₂ + have h₃ := k.lt₃ + unfold CellPaths.orientation CellPaths.assemble + simp only [k.cell_piece_interval, start, stop, Fin.isValue, Matrix.cons_val_zero, + Matrix.cons_val_one, Matrix.cons_val] + rw [show c.size + k.a₀ = k.a₀ + c.size by omega] + have h := c.rotatedPattern (x := k.a₀) (by omega) (if b then k.a₀%2 else 1-k.a₀%2) + rw [← h] + ext e + simp only [Finset.mem_union, c.mem_intervalPattern] + constructor + · rintro ((⟨i,hi,hj,hp,he⟩ | ⟨i,hi,hj,hp,he⟩) | (⟨i,hi,hj,hp,he⟩ | ⟨i,hi,hj,hp,he⟩)) <;> + exact ⟨i,by omega,by omega,hp,he⟩ + · rintro ⟨i,hi,hj,hp,he⟩ + by_cases ha : i < k.a₁ + · exact Or.inl (Or.inl ⟨i,hi,ha,hp,he⟩) + · by_cases hb : i < k.a₂ + · exact Or.inr (Or.inl ⟨i,by omega,hb,hp,he⟩) + · by_cases hd : i < k.a₃ + · exact Or.inl (Or.inr ⟨i,by omega,hd,hp,he⟩) + · exact Or.inr (Or.inr ⟨i,by omega,hj,hp,he⟩) + +end Corners + +end IndexedCycle + +end + +open scoped symmDiff + +variable {V E : Type*} [DecidableEq E] + +variable {inc : E → V → Prop} + +def exchange (M N S : Finset E) : Finset E := (M \ S) ∪ (N ∩ S) + +lemma mem_exchange (M N S : Finset E) (e : E) : + e ∈ exchange M N S ↔ (e ∈ M ∧ e ∉ S) ∨ (e ∈ N ∧ e ∈ S) := by + simp only [exchange, Finset.mem_union, Finset.mem_sdiff, Finset.mem_inter] + +lemma exchange_union (M N S : Finset E) : + exchange M N S ∪ exchange N M S = M ∪ N := by + ext e + simp only [Finset.mem_union, mem_exchange] + tauto + +lemma exchange_involution (M N S : Finset E) : + exchange (exchange M N S) (exchange N M S) S = M := by + ext e + simp only [mem_exchange] + tauto + +lemma exchange_composition (M N S T : Finset E) : + exchange (exchange M N S) (exchange N M S) T = exchange M N (S ∆ T) := by + ext e + simp only [mem_exchange, Finset.mem_symmDiff] + tauto + +lemma exchange_multiset (M N S : Finset E) : + (exchange M N S).val + (exchange N M S).val = M.val + N.val := by + apply Multiset.ext.mpr + intro e + have hc (s : Finset E) : Multiset.count e s.val = if e ∈ s then 1 else 0 := + Multiset.count_eq_of_nodup s.nodup + simp only [Multiset.count_add, hc] + by_cases hs : e ∈ S <;> by_cases hm : e ∈ M <;> by_cases hn : e ∈ N <;> + simp [mem_exchange, hs, hm, hn] + +lemma exchange_weight {R : Type*} [CommMonoid R] (w : E → R) (M N S : Finset E) : + (∏ e ∈ exchange M N S, w e) * (∏ e ∈ exchange N M S, w e) = + (∏ e ∈ M, w e) * (∏ e ∈ N, w e) := by + have h := congrArg (fun U : Multiset E => (U.map w).prod) (exchange_multiset M N S) + simpa only [Multiset.map_add, Multiset.prod_add, Finset.prod_eq_multiset_prod] using h + +def ExchangeCompatible (M N S : Finset E) : Prop := + ∀ e ∈ M, ∀ f ∈ N, ∀ v, inc e v → inc f v → (e ∈ S ↔ f ∈ S) + +omit [DecidableEq E] in +lemma ExchangeCompatible.symm {M N S : Finset E} (h : ExchangeCompatible (inc := inc) M N S) : + ExchangeCompatible (inc := inc) N M S := by + intro f hf e he v hfv hev + exact (h e he f hf v hev hfv).symm + +lemma exchange_matching [Fintype V] {M N S : Finset E} + (hM : MatchingOn inc M Finset.univ) (hN : MatchingOn inc N Finset.univ) + (h : ExchangeCompatible (inc := inc) M N S) : + MatchingOn inc (exchange M N S) Finset.univ := by + refine ⟨fun _ _ v _ => Finset.mem_univ v, ?_⟩ + intro v _ + obtain ⟨e,⟨he,hev⟩,hu⟩ := hM.2 v (Finset.mem_univ v) + obtain ⟨f,⟨hf,hfv⟩,hv⟩ := hN.2 v (Finset.mem_univ v) + have hs := h e he f hf v hev hfv + by_cases hse : e ∈ S + · have hsf := hs.mp hse + refine ⟨f, ⟨(mem_exchange M N S f).mpr (Or.inr ⟨hf,hsf⟩),hfv⟩, ?_⟩ + rintro g ⟨hg,hgv⟩ + rcases (mem_exchange M N S g).mp hg with ⟨hgm,hgs⟩ | ⟨hgn,_⟩ + · have heq := hu g ⟨hgm,hgv⟩ + exact (hgs (heq ▸ hse)).elim + · exact hv g ⟨hgn,hgv⟩ + · refine ⟨e, ⟨(mem_exchange M N S e).mpr (Or.inl ⟨he,hse⟩),hev⟩, ?_⟩ + rintro g ⟨hg,hgv⟩ + rcases (mem_exchange M N S g).mp hg with ⟨hgm,_⟩ | ⟨hgn,hgs⟩ + · exact hu g ⟨hgm,hgv⟩ + · have heq := hv g ⟨hgn,hgv⟩ + exact (hse (hs.mpr (heq ▸ hgs))).elim + +noncomputable def componentEdges (U : Finset E) (anchor : E) : Finset E := by + classical + exact U.filter ((overlayLineGraph inc U).Reachable anchor) + +omit [DecidableEq E] in +lemma mem_componentEdges (U : Finset E) (a e : E) : + e ∈ componentEdges (inc := inc) U a ↔ e ∈ U ∧ (overlayLineGraph inc U).Reachable a e := by + classical + simp only [componentEdges, Finset.mem_filter] + +lemma shares_reachable {U : Finset E} {e f : E} (he : e ∈ U) (hf : f ∈ U) + {v : V} (hev : inc e v) (hfv : inc f v) : + (overlayLineGraph inc U).Reachable e f := by + by_cases h : e = f + · subst f; exact SimpleGraph.Reachable.refl e + · exact (show (overlayLineGraph inc U).Adj e f from ⟨h,he,hf,v,hev,hfv⟩).reachable + +lemma component_compatible (M N : Finset E) (anchor : E) : + ExchangeCompatible (inc := inc) M N (componentEdges (inc := inc) (M ∪ N) anchor) := by + intro e he f hf v hev hfv + have heu := Finset.mem_union_left N he + have hfu := Finset.mem_union_right M hf + have hr := shares_reachable heu hfu hev hfv + simp only [mem_componentEdges, heu, hfu, true_and] + exact ⟨fun h => h.trans hr, fun h => h.trans hr.symm⟩ + +lemma component_exchange_matching [Fintype V] {M N : Finset E} + (hM : MatchingOn inc M Finset.univ) (hN : MatchingOn inc N Finset.univ) (anchor : E) : + MatchingOn inc (exchange M N (componentEdges (inc := inc) (M ∪ N) anchor)) Finset.univ := + exchange_matching hM hN (component_compatible M N anchor) + +lemma component_exchange_involution (M N : Finset E) (anchor : E) : + let S := componentEdges (inc := inc) (M ∪ N) anchor + exchange (exchange M N S) (exchange N M S) + (componentEdges (inc := inc) (exchange M N S ∪ exchange N M S) anchor) = M := by + dsimp only + rw [exchange_union, exchange_involution] + +end MatchingFPRAS.Transport + +end OAI diff --git a/lean/OAI/Combinatorics/MatchingCount/Sampling/LadderL.lean b/lean/OAI/Combinatorics/MatchingCount/Sampling/LadderL.lean new file mode 100644 index 0000000000000000000000000000000000000000..4cd24c1b9502b7b24bbd63b9b20db0366d69cb61 --- /dev/null +++ b/lean/OAI/Combinatorics/MatchingCount/Sampling/LadderL.lean @@ -0,0 +1,176 @@ +import Mathlib +import OAI.Combinatorics.MatchingCount.Graphs.Evolve + +namespace OAI + +namespace MatchingFPRAS.Transport + +section + +open Finset MatchingFPRAS.Replica MatchingFPRAS.Replica.Ladder + +variable {V J : Type*} [Fintype V] [DecidableEq V] [Fintype J] [DecidableEq J] + +variable {bags : V → Finset J} {G : SimpleGraph J} + +noncomputable local instance : Fintype (BagEdge bags) := Fintype.ofFinite _ + +omit [DecidableEq J] in +theorem ladder_minimum_mass + (hbags : ∀ v, ∀ a ∈ bags v, ∀ b ∈ bags v, a = b ∨ G.Adj a b) + (hG : G.IsAcyclic) (D K : ℕ) (hD : 1 ≤ D) (hN : 2 ≤ Fintype.card V) + (w : BagEdge bags → ℝ) + (hw : ∀ e, (D:ℝ)⁻¹ ≤ w e ∧ w e ≤ 3*4^K) (T q : ℕ) + (z : Slot T q → PM (BagEdge.Incident (bags := bags))) : + Real.log ((ladderLaw w T q z)⁻¹) ≤ + (10*Fintype.card V*q*(T+1)*(K+Nat.clog 2 (Fintype.card V*D+2)+1):ℕ) := by + have hl := ladderLaw_power_lower hbags hG D K hD hN w hw T q z + have hp : 0 < ladderLaw w T q z := by + apply Finset.prod_pos; intro x _; exact slotLaw_pos w x (z x) + have hu := inv_anti₀ (by positivity : (0:ℝ) < ((2:ℝ)^(10*Fintype.card V*q*(T+1)*(K+Nat.clog 2 (Fintype.card V*D+2)+1)))⁻¹) hl + rw [inv_inv] at hu + have hh := Real.log_le_log (inv_pos.mpr hp) hu + rw [Real.log_pow] at hh + have hlog : Real.log 2 ≤ 1 := by + have h := Real.log_le_sub_one_of_pos (by norm_num : (0:ℝ)<2) + linarith + have hΛ : (0:ℝ) ≤ (10*Fintype.card V*q*(T+1)*(K+Nat.clog 2 (Fintype.card V*D+2)+1):ℕ) := Nat.cast_nonneg _ + exact hh.trans (by simpa only [mul_one] using mul_le_mul_of_nonneg_left hlog hΛ) + +end + +def ladderL (N D : ℕ) : ℕ := (10^4*N*D)^100 + +def ladderQ (N D : ℕ) : ℕ := 32*ladderL N D + +def ladderM (N D T : ℕ) : ℕ := T*(ladderQ N D)^2+ladderQ N D + +def ladderLambda (N D K T : ℕ) : ℕ := + 10*N*ladderQ N D*(T+1)*(K+Nat.clog 2 (N*D+2)+1) + +noncomputable def ladderSteps (N D K T : ℕ) (ξ : ℝ) : ℕ := + 20*ladderL N D*ladderM N D T*(ladderLambda N D K T+⌈Real.logb 2 ξ⁻¹⌉₊+1) + +end MatchingFPRAS.Transport + +namespace MatchingFPRAS.FiniteChain + +lemma log_inv_le_ceil_logb {ξ : ℝ} (hξ : 0 < ξ) (hξ1 : ξ < 1) : + -Real.log ξ ≤ (⌈Real.logb 2 ξ⁻¹⌉₊:ℝ) := by + have hlog2 : 0 < Real.log 2 := Real.log_pos (by norm_num) + have hlog21 : Real.log 2 ≤ 1 := by + have h := Real.log_le_sub_one_of_pos (by norm_num : (0:ℝ)<2) + linarith + have hxi : 1 ≤ ξ⁻¹ := (one_le_inv₀ hξ).mpr hξ1.le + have hlogxi : 0 ≤ Real.log ξ⁻¹ := Real.log_nonneg hxi + have hb : 0 ≤ Real.logb 2 ξ⁻¹ := div_nonneg hlogxi hlog2.le + have he : Real.logb 2 ξ⁻¹*Real.log 2 = -Real.log ξ := by + rw [Real.logb,div_mul_cancel₀ _ hlog2.ne',Real.log_inv] + exact (by nlinarith : -Real.log ξ ≤ Real.logb 2 ξ⁻¹).trans (Nat.le_ceil _) + +lemma mixing_at_steps {a u γ Λ ξ : ℝ} {n b : ℕ} + (ha : 0 ≤ a) (hu : 0 < u) (hγ : γ ≤ 1) (hΛ : 0 ≤ Λ) + (hξ : 0 < ξ) (hb : -Real.log ξ ≤ (b:ℝ)) + (hmass : Real.log u⁻¹ ≤ Λ) + (hsteps : 2*(Λ+(b:ℝ)+1) ≤ γ*n) + (hmix : a^2 ≤ (1-γ)^n*(u⁻¹-1)) : a/2 ≤ ξ := by + have hmass' : u⁻¹ ≤ Real.exp Λ := (Real.log_le_iff_le_exp (inv_pos.mpr hu)).mp hmass + have hp : 0 ≤ 1-γ := by linarith + have he : (1-γ)^n ≤ Real.exp (-γ*(n:ℝ)) := by + calc + _ ≤ (Real.exp (-γ))^n := pow_le_pow_left₀ hp (Real.one_sub_le_exp_neg γ) n + _ = _ := by rw [← Real.exp_nat_mul]; congr 1; ring + have hsq : a^2 ≤ ξ^2 := by + calc + _ ≤ (1-γ)^n*(u⁻¹-1) := hmix + _ ≤ (1-γ)^n*Real.exp Λ := mul_le_mul_of_nonneg_left (by linarith) (pow_nonneg hp _) + _ ≤ Real.exp (-γ*(n:ℝ))*Real.exp Λ := mul_le_mul_of_nonneg_right he (Real.exp_pos _).le + _ = Real.exp (-γ*(n:ℝ)+Λ) := (Real.exp_add _ _).symm + _ ≤ Real.exp (2*Real.log ξ) := Real.exp_le_exp.mpr (by linarith) + _ = ξ^2 := by rw [show (2:ℝ)=(2:ℕ) by norm_num,Real.exp_nat_mul,Real.exp_log hξ] + nlinarith + +end MatchingFPRAS.FiniteChain + +namespace MatchingFPRAS.Transport + +open Finset MatchingFPRAS.Replica MatchingFPRAS.Replica.Ladder + +variable {V J : Type*} [Fintype V] [DecidableEq V] [Fintype J] [DecidableEq J] + +variable {bags : V → Finset J} {G : SimpleGraph J} + +noncomputable local instance : Fintype (BagEdge bags) := Fintype.ofFinite _ + +noncomputable local instance : DecidableEq (PM (BagEdge.Incident (bags := bags))) := Classical.decEq _ + +theorem ideal_ladder_sampling + (hbags : ∀ v, ∀ a ∈ bags v, ∀ b ∈ bags v, a = b ∨ G.Adj a b) + (hG : G.IsAcyclic) (height : J → ℝ) (hheight : ∀ l, 0 < height l) + (hstep : ∀ a b, G.Adj a b → height a ≤ 2*height b) + (D K : ℕ) (hD : 1 ≤ D) (hN : 2 ≤ Fintype.card V) (w : BagEdge bags → ℝ) + (hw : ∀ e, height e.color / D ≤ w e ∧ w e ≤ 3*height e.color) + (hglobal : ∀ e, (D:ℝ)⁻¹ ≤ w e ∧ w e ≤ 3*4^K) + (M₀ : PM (BagEdge.Incident (bags := bags))) (T : ℕ) + (z : Slot T (ladderQ (Fintype.card V) D) → PM (BagEdge.Incident (bags := bags))) + (ξ : ℝ) (hξ : 0 < ξ) (hξ1 : ξ < 1) : + let ν := ladderLaw w T (ladderQ (Fintype.card V) D) + let C := ladderFlow hbags hG w T (ladderQ (Fintype.card V) D) + (∑ s, |MatchingFPRAS.FiniteChain.walk ν C z (ladderSteps (Fintype.card V) D K T ξ) s-ν s|)/2 ≤ ξ := by + classical + dsimp only + let N := Fintype.card V + let L := ladderL N D + let q := ladderQ N D + let M := ladderM N D T + let Λ := ladderLambda N D K T + let b := ⌈Real.logb 2 ξ⁻¹⌉₊ + let ν := ladderLaw w T q + let C := ladderFlow hbags hG w T q + let n := ladderSteps N D K T ξ + let γ : ℝ := 3/(8*(M:ℝ)) + have hL0 : 0 < L := by + have hn : 0 < N := by dsimp [N]; omega + have hd : 0 < D := by omega + dsimp [L,ladderL]; positivity + have hq0 : 0 < q := by dsimp [q,ladderQ]; exact Nat.mul_pos (by decide) hL0 + have hM0 : 0 < M := by dsimp [M,ladderM]; omega + have hMr : (0:ℝ) < M := by exact_mod_cast hM0 + have hLr : (1:ℝ) ≤ L := by exact_mod_cast hL0 + have hΛr : (0:ℝ) ≤ Λ := Nat.cast_nonneg _ + have hγ : γ ≤ 1 := by + dsimp [γ] + apply (div_le_one (by positivity : (0:ℝ)<8*M)).mpr + have hm : (1:ℝ) ≤ M := by exact_mod_cast hM0 + linarith + have hsteps : 2*((Λ:ℝ)+(b:ℝ)+1) ≤ γ*(n:ℝ) := by + have hb0 : (0:ℝ) ≤ b := Nat.cast_nonneg _ + have hfac : (0:ℝ) ≤ (Λ:ℝ)+(b:ℝ)+1 := by positivity + calc + _ ≤ ((15:ℝ)/2)*(L:ℝ)*((Λ:ℝ)+(b:ℝ)+1) := + mul_le_mul_of_nonneg_right (by linarith) hfac + _ = _ := by + dsimp [γ,n,ladderSteps,L,M,Λ,b] + push_cast + have hm0 : (ladderM N D T:ℝ) ≠ 0 := hMr.ne' + field_simp [hm0] + ring + have hp : 0 < ν z := by + apply Finset.prod_pos; intro i _; exact slotLaw_pos w i (z i) + have hmass : Real.log ((ν z)⁻¹) ≤ (Λ:ℝ) := + ladder_minimum_mass hbags hG D K hD hN w hglobal T q z + have hmix := concrete_ladder_mixing (hbags := hbags) (hG := hG) + height hheight hstep D hD w hw hN M₀ T z n + dsimp only at hmix + have hmix' : (∑ s, |MatchingFPRAS.FiniteChain.walk ν C z n s-ν s|)^2 ≤ + (1-γ)^n*((ν z)⁻¹-1) := by + simp only [γ,ν,C,q,M,ladderM,ladderQ,ladderL,N,Nat.cast_mul,Nat.cast_ofNat] at hmix ⊢ + convert hmix using 1 + congr 4 + exact MatchingFPRAS.FiniteChain.mixing_at_steps + (Finset.sum_nonneg (fun _ _ => abs_nonneg _)) hp hγ hΛr hξ + (MatchingFPRAS.FiniteChain.log_inv_le_ceil_logb hξ hξ1) hmass hsteps hmix' + +end MatchingFPRAS.Transport + +end OAI diff --git a/lean/OAI/Combinatorics/MatchingCount/Sampling/MarkBridge.lean b/lean/OAI/Combinatorics/MatchingCount/Sampling/MarkBridge.lean new file mode 100644 index 0000000000000000000000000000000000000000..05255400bfa96977d9f0de333cad0762b682a43d --- /dev/null +++ b/lean/OAI/Combinatorics/MatchingCount/Sampling/MarkBridge.lean @@ -0,0 +1,93 @@ +import Mathlib +import OAI.Combinatorics.MatchingCount.Probability.Marking +import OAI.Combinatorics.MatchingCount.Algorithm.RelabelWeights +import OAI.Combinatorics.MatchingCount.Sampling.RelabelMarking + +namespace OAI + +namespace MatchingFPRAS.RationalSource +open Finset Transport Variation Enlargement + +variable {V : Type*} [Fintype V] [LinearOrder V] [Nontrivial V] +attribute [local instance] NumberedHierarchy.labelOrder sym2Order bagEdgeOrder bagEdgeFintype +attribute [local instance] UnitRefresh.Computable.allowedDec prodOrder sumOrder +noncomputable local instance (w : V → V → ℚ) (K : ℕ) : + DecidableEq (SourceLabel (fun x y=>(w x y:ℝ)) K) := Classical.decEq _ +noncomputable local instance (w : V → V → ℚ) (K : ℕ) : + Fintype (BagEdge (sourceBags (fun x y=>(w x y:ℝ)) K)) := Fintype.ofFinite _ +noncomputable local instance (w : V → V → ℚ) (K : ℕ) : + DecidableEq (BagPM (bags w K)) := Classical.decEq _ +noncomputable local instance (w : V → V → ℚ) (K : ℕ) : + Fintype (BagPM (bags w K)) := Fintype.ofFinite _ +noncomputable local instance (w : V → V → ℚ) (K : ℕ) : + Fintype (Marked w K) := Fintype.ofFinite _ +noncomputable local instance (w : V → V → ℚ) (K : ℕ) : + Fintype (SourceMarked (fun x y=>(w x y:ℝ)) K) := Fintype.ofFinite _ +lemma sourceEdgeEquiv_central (w : V → V → ℚ) (K : ℕ) (q : LogicalEdge V) : + sourceEdgeEquiv w K (Enlargement.centralEdge (fun x y=>(w x y:ℝ)) K q)=centralEdge w K q := + sourceEdgeEquiv_real w K _ +lemma probePortion_cast (w : V → V → ℚ) (K D : ℕ) + (e : BagEdge (sourceBags (fun x y=>(w x y:ℝ)) K)) : + (probePortion w K D (sourceEdgeEquiv w K e):ℝ)=Enlargement.probePortion (fun x y=>(w x y:ℝ)) K D e := by + classical + have he : (∃ q,centralEdge w K q=sourceEdgeEquiv w K e) ↔ + ∃ q,Enlargement.centralEdge (fun x y=>(w x y:ℝ)) K q=e := by + constructor + · rintro ⟨q,hq⟩ + exact ⟨q,(sourceEdgeEquiv w K).injective ((sourceEdgeEquiv_central w K q).trans hq)⟩ + · rintro ⟨q,rfl⟩ + exact ⟨q,(sourceEdgeEquiv_central w K q).symm⟩ + simp only [probePortion,Enlargement.probePortion,he] + split_ifs <;> push_cast <;> rfl +lemma portions_cast (w : V → V → ℚ) (K D : ℕ) + (e : BagEdge (sourceBags (fun x y=>(w x y:ℝ)) K)) (i : Fin 3) : + (portions w K D (sourceEdgeEquiv w K e) i:ℝ)=sourcePortions (fun x y=>(w x y:ℝ)) K D e i := by + fin_cases i + · exact realPortion_cast w K e + · change ((bagHeight w K (sourceEdgeEquiv w K e).color/D-probePortion w K D (sourceEdgeEquiv w K e):ℚ):ℝ)=_ + rw [Rat.cast_sub,Rat.cast_div,Rat.cast_natCast,probePortion_cast,sourceEdgeEquiv_color,bagHeight_cast] + rfl + · exact probePortion_cast w K D e +noncomputable def sourceMarkedEquiv (w : V → V → ℚ) (K : ℕ) : + SourceMarked (fun x y=>(w x y:ℝ)) K ≃ Marked w K := + markedEquiv (inc:=BagEdge.Incident (bags:=sourceBags (fun x y=>(w x y:ℝ)) K)) + (j:=BagEdge.Incident (bags:=bags w K)) (sourceEdgeEquiv w K) (fun _ _=>Iff.rfl) +lemma portions_collapse (w : V → V → ℚ) (K D : ℕ) : + Marking.collapse (fun e i=>(portions w K D e i:ℝ))=fun e=>(bagWeight w K D e:ℝ) := by + funext e + change (∑ i : Fin 3,(portions w K D e i:ℝ))=(bagWeight w K D e:ℝ) + exact_mod_cast portions_sum w K D e +lemma markedLaw_eq (w : V → V → ℚ) (hw : ∀ x y,0(portions w K D e i:ℝ)) a := by + have hc : ∀ e,Marking.collapse (fun e i=>(portions w K D e i:ℝ)) e≠0 := by + intro e + rw [portions_collapse] + dsimp only + exact_mod_cast (bagWeight_pos w hw K D hD e).ne' + have h:=Marking.law_from_reveal BagEdge.Incident (fun e i=>(portions w K D e i:ℝ)) hc a + rw [portions_collapse] at h + convert h using 1 + simp only [markedLaw,Variation.sigmaLift,product,gibbs,matchingWeight,partition,Marking.conditional, + portions_collapse,Rat.cast_div,partitionWeight] + congr 3 + ext + simp +lemma markedLaw_equiv (w : V → V → ℚ) (hw : ∀ x y,0(w x y:ℝ)) K) : + markedLaw w K D (sourceMarkedEquiv w K a)=sourceLaw (fun x y=>(w x y:ℝ)) K D a := by + rw [markedLaw_eq w hw K D hD] + change Marking.law BagEdge.Incident (fun e i=>(portions w K D e i:ℝ)) + (markedEquiv (inc:=BagEdge.Incident (bags:=sourceBags (fun x y=>(w x y:ℝ)) K)) + (j:=BagEdge.Incident (bags:=bags w K)) (sourceEdgeEquiv w K) (fun _ _=>Iff.rfl) a)=_ + rw [law_markedEquiv (inc:=BagEdge.Incident (bags:=sourceBags (fun x y=>(w x y:ℝ)) K)) + (j:=BagEdge.Incident (bags:=bags w K)) (sourceEdgeEquiv w K) (fun _ _=>Iff.rfl)] + have hp : ((fun e i=>(portions w K D e i:ℝ)) ∘ sourceEdgeEquiv w K)= + sourcePortions (fun x y=>(w x y:ℝ)) K D := by + funext e i + exact portions_cast w K D e i + rw [hp] + rfl +end MatchingFPRAS.RationalSource + +end OAI diff --git a/lean/OAI/Combinatorics/MatchingCount/Sampling/MetropolisChoice.lean b/lean/OAI/Combinatorics/MatchingCount/Sampling/MetropolisChoice.lean new file mode 100644 index 0000000000000000000000000000000000000000..b5e9d584a642ef02ecdfa7c2b40be9772c825d4e --- /dev/null +++ b/lean/OAI/Combinatorics/MatchingCount/Sampling/MetropolisChoice.lean @@ -0,0 +1,336 @@ +import Mathlib +import OAI.Combinatorics.MatchingCount.Probability.Tv +import OAI.Combinatorics.MatchingCount.Sampling.Component + +namespace OAI + +namespace MatchingFPRAS.WeightedOptions + +open Finset + +variable {Ω : Type*} [Fintype Ω] [DecidableEq Ω] + +def metropolisChoice (c : WeightedOptions Ω) (w : Ω → ℚ) (hw : ∀ a, 0 < w a) (a : Ω) : + WeightedOptions Ω := c.accept a (fun b => min 1 (w b / w a)) + (fun b => le_min zero_le_one (div_nonneg (hw b).le (hw a).le)) + (fun _ => min_le_left _ _) + +lemma real_law_sum (c : WeightedOptions Ω) : ∑ b, (c.law b : ℝ)=1 := by + exact_mod_cast c.law_sum + +lemma row_eq_of_off (f g : Ω → ℝ) (hf : ∑ x, f x=1) (hg : ∑ x, g x=1) + (a : Ω) (h : ∀ b, a≠b → f b=g b) : f=g := by + funext b + by_cases hab : a=b + · subst b + have he : ∑ b ∈ univ.erase a, f b = ∑ b ∈ univ.erase a, g b := by + apply sum_congr rfl + intro b hb + exact h b (ne_of_mem_erase hb).symm + rw [←sum_erase_add _ _ (mem_univ a)] at hf hg + linarith + · exact h b hab + +lemma min_ratio (x y : ℝ) (hx : 0 < x) : min (1:ℝ) (y/x) = min x y / x := by + by_cases h : x≤y + · rw [min_eq_left ((le_div_iff₀ hx).mpr (by simpa using h)),min_eq_left h,div_self hx.ne'] + · rw [min_eq_right ((div_le_one hx).mpr (le_of_not_ge h)),min_eq_right (le_of_not_ge h)] + +theorem metropolisChoice_law (P : Replica.SymmetricProposal Ω) (c : Ω → WeightedOptions Ω) + (hc : ∀ a b, ((c a).law b : ℝ)=P.q a b) + (w : Ω → ℚ) (hw : ∀ a, 0 < w a) (a b : Ω) : + (((c a).metropolisChoice w hw a).law b : ℝ) = + Replica.metropolis P (fun x => (w x:ℝ)) a b := by + have hpos : ∀ x, (0:ℝ) by exact_mod_cast hw x + have hsum := real_law_sum ((c a).metropolisChoice w hw a) + have he := row_eq_of_off _ _ hsum (Replica.metropolis_row P _ hpos a) a (fun b hab => ?_) + · exact congrFun he b + rw [metropolisChoice,accept_law,ite_eq_right hab,add_zero] + push_cast + rw [hc,min_ratio _ _ (hpos a)] + simp only [Replica.metropolis,Replica.metropolisCapacity,ite_eq_right hab,Replica.offCapacity] + ring + +omit [Fintype Ω] [DecidableEq Ω] in +lemma metropolisChoice_size (c : WeightedOptions Ω) (w : Ω → ℚ) (hw : ∀ a, 0 < w a) (a : Ω) : + (c.metropolisChoice w hw a).size = 2*c.size := by + simp only [metropolisChoice,accept] + omega + +end MatchingFPRAS.WeightedOptions + +namespace MatchingFPRAS.Variation + +open Finset +open scoped Classical + +variable {A B C : Type*} [Fintype A] [Fintype B] [Fintype C] + +noncomputable def uniform (A : Type*) [Fintype A] (_ : A) : ℝ := 1/Fintype.card A + +lemma uniform_nonneg (a : A) : 0≤uniform A a := by unfold uniform; positivity + +lemma uniform_sum [Nonempty A] : ∑ a : A,uniform A a=1 := by + simp only [uniform,sum_const,nsmul_eq_mul] + exact mul_one_div_cancel (by exact_mod_cast Fintype.card_ne_zero : (Fintype.card A:ℝ)≠0) + +noncomputable def imageLaw (f : A → B) : B → ℝ := push (uniform A) f + +omit [Fintype B] in +lemma imageLaw_nonneg (f : A → B) (b : B) : 0 ≤ imageLaw f b := push_nonneg _ uniform_nonneg _ _ + +lemma imageLaw_sum [Nonempty A] (f : A → B) : ∑ b,imageLaw f b=1 := push_sum _ uniform_sum _ + +omit [Fintype B] in +lemma imageLaw_eq_count (f : A → B) (b : B) : + imageLaw f b=((univ.filter (fun a=>f a=b)).card:ℝ)/Fintype.card A := by + simp only [imageLaw,push,uniform] + rw [show (∑ x,if f x=b then (1:ℝ)/Fintype.card A else 0)= + (∑ x,if f x=b then (1:ℝ) else 0)/Fintype.card A by + simp only [sum_div,ite_div,zero_div]] + simp + +lemma imageLaw_equiv (e : A ≃ B) : imageLaw e=uniform B := by + funext b + unfold imageLaw push uniform + rw [e.sum_comp (fun x=>if x=b then (1:ℝ)/Fintype.card A else 0)] + simp [Fintype.card_congr e] + +omit [Fintype C] in +lemma imageLaw_comp_equiv (e : A ≃ B) (f : B → C) : imageLaw (f ∘ e)=imageLaw f := by + funext c + unfold imageLaw push uniform + rw [Fintype.card_congr e,←e.sum_comp (fun b=>if f b=c then (1:ℝ)/Fintype.card B else 0)] + rfl + +omit [Fintype C] in +lemma push_comp (p : A → ℝ) (f : A → B) (g : B → C) : + push (push p f) g=push p (g ∘ f) := by + funext c + unfold push + have h (b : B) : (if g b=c then ∑ a,if f a=b then p a else 0 else 0)= + ∑ a,if g b=c then (if f a=b then p a else 0) else 0 := by + by_cases hh : g b=c <;> simp [hh] + simp_rw [h] + rw [sum_comm] + apply sum_congr rfl + intro a _ + simp only [←ite_and] + rw [show (fun b=>if g b=c ∧ f a=b then p a else 0)= + (fun b=>if f a=b then (if g b=c then p a else 0) else 0) by + funext b; split_ifs <;> simp_all] + simp + +omit [Fintype C] in +lemma imageLaw_comp (f : A → B) (g : B → C) : imageLaw (g ∘ f)=push (imageLaw f) g := + (push_comp _ _ _).symm + +lemma uniform_prod (a : A×B) : uniform (A×B) a=uniform A a.1*uniform B a.2 := by + simp [uniform,Fintype.card_prod,Nat.cast_mul,mul_comm] + +variable {D : Type*} [Fintype D] + +omit [Fintype C] in +lemma imageLaw_pair (f : A → B → C) : + imageLaw (fun x : A×B=>f x.1 x.2)=bind (uniform A) (fun a=>imageLaw (f a)) := by + funext c + simp only [imageLaw,push,bind,Fintype.sum_prod_type,uniform_prod,mul_sum] + apply sum_congr rfl + intro a _ + apply sum_congr rfl + intro b _ + split_ifs <;> simp + +omit [Fintype C] in +lemma bind_push (p : A → ℝ) (f : A → B) (k : B → C → ℝ) : + bind (push p f) k=bind p (fun a=>k (f a)) := by + funext c + simp only [bind,push,sum_mul,ite_mul,zero_mul] + rw [sum_comm] + apply sum_congr rfl + intro a _ + simp + +omit [Fintype C] in +lemma imageLaw_adaptive_pair (d : A → D) (f : D → B → C) : + imageLaw (fun x : A×B=>f (d x.1) x.2)=bind (imageLaw d) (fun a=>imageLaw (f a)) := by + rw [imageLaw_pair (fun a b=>f (d a) b), imageLaw,bind_push] + +theorem uniform_sigma [Nonempty A] {E : B → Type*} [∀ b,Fintype (E b)] + (e : (Σ b,E b) ≃ A) (z : A) : + push (sigmaLift (fun b=>(Fintype.card (E b):ℝ)/Fintype.card A) + (fun b=>uniform (E b))) e z=uniform A z := by + have h (s : Sigma E) : sigmaLift (fun b=>(Fintype.card (E b):ℝ)/Fintype.card A) + (fun b=>uniform (E b)) s=uniform (Sigma E) s := by + have hn : (Fintype.card (E s.1):ℝ)≠0 := by + let : Nonempty (E s.1) := ⟨s.2⟩ + exact_mod_cast Fintype.card_ne_zero + simp only [sigmaLift,uniform,Fintype.card_congr e] + field_simp + have hh := congrArg (fun p=>push p e z) (funext h) + rw [hh] + exact congrFun (imageLaw_equiv e) z + +open Finset +open scoped Classical + +variable {A B C : Type*} [Fintype A] [Fintype B] [Fintype C] + +omit [Fintype C] in +lemma imageLaw_ignore [Nonempty A] (f : B → C) : + imageLaw (fun x : A×B=>f x.2)=imageLaw f := by + rw [imageLaw_pair (fun _ b=>f b)] + funext c + simp only [bind,←sum_mul,uniform_sum,one_mul] + +omit [Fintype B] in +lemma push_sigmaLift {E : A → Type*} [∀ a,Fintype (E a)] + (p : A → ℝ) (k : ∀ a,E a → ℝ) (f : (Σ a,E a) → B) : + push (sigmaLift p k) f=bind p (fun a=>push (k a) (fun e=>f ⟨a,e⟩)) := by + funext b + simp only [push,sigmaLift,bind,Fintype.sum_sigma,mul_sum] + apply sum_congr rfl + intro a _ + apply sum_congr rfl + intro e _ + split_ifs <;> simp + +lemma imageLaw_subsingleton [Nonempty A] [Subsingleton B] (f : A → B) : + imageLaw f=uniform B := by + let : Nonempty B := ⟨f (Classical.choice (inferInstance : Nonempty A))⟩ + funext b + simp only [imageLaw,push,Subsingleton.elim (f _) b,ite_true,uniform_sum] + let : Unique B := ⟨⟨b⟩,fun x=>Subsingleton.elim x b⟩ + simp [uniform] + +lemma tv_self (p : A → ℝ) : tv p p=0 := by simp [tv] + +open scoped Classical + +lemma imageLaw_fin_skip {B C D : Type*} [Fintype B] [Nonempty B] [Fintype C] [Fintype D] + (n : ℕ) (g : (Fin (n+2) → B) → C) (d : B → D) (f : D → (Fin n → B) → C) + (hg : ∀ bits,g bits=f (d (bits (Fin.last (n+1)))) (fun i=>bits i.castSucc.castSucc)) : + imageLaw g=bind (imageLaw d) (fun c=>imageLaw (f c)) := by + let e : (B×(B×(Fin n → B))) ≃ (Fin (n+2) → B) := + (Equiv.prodCongr (Equiv.refl B) (Fin.snocEquiv (fun _ : Fin (n+1)=>B))).trans + (Fin.snocEquiv (fun _ : Fin (n+2)=>B)) + have hE : g ∘ e=(fun x : B×(B×(Fin n→B))=>f (d x.1) x.2.2) := by + funext x + rw [Function.comp_apply,hg] + simp [e,Fin.snocEquiv] + + rw [←imageLaw_comp_equiv e,hE,imageLaw_adaptive_pair d (fun c (u : B×(Fin n→B))=>f c u.2)] + simp_rw [imageLaw_ignore] + +end MatchingFPRAS.Variation + +namespace MatchingFPRAS.WeightedOptions + +open Finset Variation FiniteChoice + +variable {Ω : Type*} [Fintype Ω] [DecidableEq Ω] + +def draw (c : WeightedOptions Ω) (k : ℕ) (bits : Fin k → Bool) : Ω := + c.out (chooseBits c.mass c.total k bits) + +omit [Fintype Ω] [DecidableEq Ω] in +lemma chooseBits_imageLaw (c : WeightedOptions Ω) (k : ℕ) : + imageLaw (chooseBits c.mass c.total k) = fun i => (tapeLaw c.mass c.total k i:ℝ) := by + funext i + rw [imageLaw_eq_count] + simp only [Fintype.card_fun,Fintype.card_fin,Fintype.card_bool,Nat.cast_pow, + Nat.cast_ofNat,tapeLaw,Rat.cast_div,Rat.cast_natCast,Rat.cast_pow,Rat.cast_ofNat] + congr 2 + congr 1 + ext bits + simp only [mem_filter,mem_univ,true_and] + +omit [Fintype Ω] in +lemma realLaw_push (c : WeightedOptions Ω) : + (fun b => (c.law b:ℝ))=push (fun i=>(c.mass i:ℝ)) c.out := by + funext b + unfold law push + simp only [Rat.cast_sum,apply_ite,Rat.cast_zero] + +theorem draw_tv (c : WeightedOptions Ω) (k : ℕ) : + tv (imageLaw (c.draw k)) (fun b=>(c.law b:ℝ)) ≤ 2*c.size/(2:ℝ)^k := by + have h := fixed_bit_choice c.mass c.nonneg c.total k + rw [←tapeLaw_eq] at h + have hr : tv (fun i=>(tapeLaw c.mass c.total k i:ℝ)) (fun i=>(c.mass i:ℝ)) + ≤ 2*c.size/(2:ℝ)^k := by + change (∑ i : Fin c.size, |(tapeLaw c.mass c.total k i:ℝ)-(c.mass i:ℝ)|)/2 ≤ _ + have hh := (Rat.cast_le (K := ℝ)).mpr h + simpa only [Rat.cast_div,Rat.cast_sum,Rat.cast_abs,Rat.cast_sub,Rat.cast_mul, + Rat.cast_ofNat,Rat.cast_natCast,Rat.cast_pow] using hh + have hd : c.draw k = c.out ∘ chooseBits c.mass c.total k := rfl + rw [hd,imageLaw_comp,realLaw_push,chooseBits_imageLaw] + exact (push_contraction _ _ _).trans hr + +def runDraw (c : ℕ → Ω → WeightedOptions Ω) (z : Ω) (k : ℕ) : + (n : ℕ) → (Fin n → Fin k → Bool) → Ω + | 0, _ => z + | n+1, bits => (c n (runDraw c z k n (Fin.init bits))).draw k (bits (Fin.last n)) + +noncomputable def exactRun (c : ℕ → Ω → WeightedOptions Ω) (z : Ω) : ℕ → Ω → ℝ + | 0 => fun b => if z=b then 1 else 0 + | n+1 => bind (exactRun c z n) (fun s b => ((c n s).law b:ℝ)) + +lemma exactRun_nonneg (c : ℕ → Ω → WeightedOptions Ω) (z : Ω) (n : ℕ) (b : Ω) : + 0≤exactRun c z n b := by + induction n generalizing b with + | zero => simp only [exactRun]; split_ifs <;> norm_num + | succ n ih => exact bind_nonneg _ _ ih (fun s b => by exact_mod_cast (c n s).law_nonneg b) b + +lemma exactRun_sum (c : ℕ → Ω → WeightedOptions Ω) (z : Ω) (n : ℕ) : + ∑ b,exactRun c z n b=1 := by + induction n with + | zero => simp [exactRun] + | succ n ih => exact bind_sum _ _ ih (fun s => real_law_sum (c n s)) + +omit [DecidableEq Ω] in +lemma runDraw_law (c : ℕ → Ω → WeightedOptions Ω) (z : Ω) (k n : ℕ) : + imageLaw (runDraw c z k (n+1)) = bind (imageLaw (runDraw c z k n)) + (fun s => imageLaw ((c n s).draw k)) := by + let e : ((Fin n → Fin k → Bool) × (Fin k → Bool)) ≃ (Fin (n+1) → Fin k → Bool) := + (Equiv.prodComm _ _).trans (Fin.snocEquiv (fun _ => Fin k → Bool)) + have h : runDraw c z k (n+1) ∘ e = + (fun u => (c n (runDraw c z k n u.1)).draw k u.2) := by + funext u + change (c n (runDraw c z k n (Fin.init (Fin.snoc (α := fun _ : Fin (n+1) => Fin k → Bool) u.1 u.2)))).draw k + (Fin.snoc (α := fun _ : Fin (n+1) => Fin k → Bool) u.1 u.2 (Fin.last n)) = _ + simp only [Fin.init_snoc,Fin.snoc_last] + rw [←imageLaw_comp_equiv e,h] + exact imageLaw_adaptive_pair (runDraw c z k n) (fun s bits => (c n s).draw k bits) + +theorem runDraw_tv (c : ℕ → Ω → WeightedOptions Ω) (z : Ω) (k R n : ℕ) + (hR : ∀ j s, (c j s).size ≤ R) : + tv (imageLaw (runDraw c z k n)) (exactRun c z n) ≤ 2*n*R/(2:ℝ)^k := by + induction n with + | zero => + have h : imageLaw (runDraw c z k 0)=exactRun c z 0 := by + funext b + simp [imageLaw,push,Variation.uniform,runDraw,exactRun] + rw [h,tv_self] + norm_num + | succ n ih => + rw [runDraw_law] + change tv (bind _ _) (bind _ _)≤_ + let p := imageLaw (runDraw c z k n) + let q := exactRun c z n + let u := fun s => imageLaw ((c n s).draw k) + let v := fun s b => ((c n s).law b:ℝ) + have hu : ∀ s, tv (u s) (v s) ≤ 2*R/(2:ℝ)^k := by + intro s + exact ((c n s).draw_tv k).trans (div_le_div_of_nonneg_right + (mul_le_mul_of_nonneg_left (by exact_mod_cast hR n s) (by norm_num)) (by positivity)) + have h1 := bind_perturbation p u v (imageLaw_nonneg _) (imageLaw_sum _) _ hu + have h2 := bind_contraction p q v + (fun s b => by dsimp [v]; exact_mod_cast (c n s).law_nonneg b) (fun s => real_law_sum (c n s)) + calc + _ ≤ tv (bind p u) (bind p v)+tv (bind p v) (bind q v) := tv_triangle _ _ _ + _ ≤ 2*R/(2:ℝ)^k+2*n*R/(2:ℝ)^k := add_le_add h1 (h2.trans ih) + _ = _ := by push_cast; ring + +end MatchingFPRAS.WeightedOptions + +end OAI diff --git a/lean/OAI/Combinatorics/MatchingCount/Sampling/OnlineSample.lean b/lean/OAI/Combinatorics/MatchingCount/Sampling/OnlineSample.lean new file mode 100644 index 0000000000000000000000000000000000000000..d224e5da0389dcd4e84ac2d982f3fd3344e26724 --- /dev/null +++ b/lean/OAI/Combinatorics/MatchingCount/Sampling/OnlineSample.lean @@ -0,0 +1,68 @@ +import Mathlib +import OAI.Combinatorics.MatchingCount.Sampling.TreePreparedMarked +import OAI.Combinatorics.MatchingCount.Machines.OnlineTraverse +import OAI.Combinatorics.MatchingCount.Tapes.OnlineWord + +namespace OAI + +namespace MatchingFPRAS.OnlineSample +open PhysicalStream TreeTyped + +abbrev word (k : ℕ) : Experiment (List Bool) := OnlineWord.prepend k [] + +variable {A : Type} [Codec A] +def repeatInputRealizer : TreeTyped.Realizer (fun x : ℕ×A=>List.replicate x.1 x.2) := + (TreeTyped.composition (TreeTyped.pair TreeTyped.second (TreeTyped.composition TreeTyped.first TreeTyped.range)) + (TreeTyped.mapWith TreeTyped.first)).congr (by intro x; simp) + +def words (x : ℕ×ℕ) : Experiment (List (List Bool)) := + OnlineTree.traverseM word (List.replicate x.2 x.1) +noncomputable def wordsRealizer : OnlineTree.Realizer words := + (OnlineTree.composition (OnlineTree.deterministic (TreeTyped.composition + (TreeTyped.pair TreeTyped.second TreeTyped.first) repeatInputRealizer)) + (OnlineTree.traverse OnlineWord.naturalRealizer)).congr (by intro x h; rfl) + +def localWords (x : ℕ×ℕ) : Experiment NumericLadder.Bits := + (word x.1).bind (fun w=>(words x).map (Prod.mk w)) +noncomputable def localRealizer : OnlineTree.Realizer localWords := + OnlineTree.pair (OnlineTree.composition (OnlineTree.deterministic TreeTyped.first) OnlineWord.naturalRealizer) + wordsRealizer + +def scan (x : ℕ×ℕ) : Experiment (List Bool×NumericLadder.Bits) := + (word x.1).bind (fun w=>(localWords x).map (Prod.mk w)) +noncomputable def scanRealizer : OnlineTree.Realizer scan := + OnlineTree.pair (OnlineTree.composition (OnlineTree.deterministic TreeTyped.first) OnlineWord.naturalRealizer) + localRealizer + +def scans (x : (ℕ×ℕ)×ℕ) : Experiment (List (List Bool×NumericLadder.Bits)) := + OnlineTree.traverseM scan (List.replicate x.2 x.1) +noncomputable def scansRealizer : OnlineTree.Realizer scans := + (OnlineTree.composition (OnlineTree.deterministic (TreeTyped.composition + (TreeTyped.pair TreeTyped.second TreeTyped.first) repeatInputRealizer)) + (OnlineTree.traverse scanRealizer)).congr (by intro x h; rfl) + +def markWord (x : ℕ×ℕ) : Experiment (ℕ×List Bool) := (word x.2).map (Prod.mk x.1) +noncomputable def markWordRealizer : OnlineTree.Realizer markWord := + OnlineTree.mapSecond OnlineWord.naturalRealizer + +def markRequests (x : ℕ×List ℕ) : List (ℕ×ℕ) := x.2.map (fun i=>(i,x.1)) +def markRequestsRealizer : TreeTyped.Realizer markRequests := + (TreeTyped.mapWith (TreeTyped.pair TreeTyped.second TreeTyped.first)).congr (fun _=>rfl) +def marks (x : ℕ×List ℕ) : Experiment (List (ℕ×List Bool)) := + OnlineTree.traverseM markWord (markRequests x) +noncomputable def marksRealizer : OnlineTree.Realizer marks := + OnlineTree.composition (OnlineTree.deterministic markRequestsRealizer) (OnlineTree.traverse markWordRealizer) + +abbrev Request := ((ℕ×ℕ)×ℕ)×(ℕ×List ℕ) +def sample (x : Request) : Experiment NumericMarking.SampleBits := + (scans x.1).bind (fun s=>(marks x.2).map (Prod.mk s)) +noncomputable def sampleRealizer : OnlineTree.Realizer sample := + OnlineTree.pair (OnlineTree.composition (OnlineTree.deterministic TreeTyped.first) scansRealizer) + (OnlineTree.composition (OnlineTree.deterministic TreeTyped.second) marksRealizer) +def many (x : ℕ×Request) : Experiment (List NumericMarking.SampleBits) := + OnlineTree.traverseM sample (List.replicate x.1 x.2) +noncomputable def manyRealizer : OnlineTree.Realizer many := + OnlineTree.composition (OnlineTree.deterministic repeatInputRealizer) (OnlineTree.traverse sampleRealizer) +end MatchingFPRAS.OnlineSample + +end OAI diff --git a/lean/OAI/Combinatorics/MatchingCount/Sampling/PM.lean b/lean/OAI/Combinatorics/MatchingCount/Sampling/PM.lean new file mode 100644 index 0000000000000000000000000000000000000000..d6f837c625393edde9c86dc4bdcaa360456f211c --- /dev/null +++ b/lean/OAI/Combinatorics/MatchingCount/Sampling/PM.lean @@ -0,0 +1,394 @@ +import Mathlib +import OAI.Combinatorics.MatchingCount.Graphs.LabelCycle + +namespace OAI + +namespace MatchingFPRAS.Transport + +section + +variable {V E : Type*} [Fintype V] [DecidableEq E] + +variable (inc : E → V → Prop) + +abbrev PM := {M : Finset E // MatchingOn inc M Finset.univ} + +@[ext] structure RawDemand where + first : PM inc + second : PM inc + anchor : E + corners : Fin 4 → V + flags : Fin 64 + +structure DemandEncoding (d : RawDemand inc) where + first : PM inc + second : PM inc + added : Multiset E + dropped : Multiset E + added_card : added.card ≤ 4 + dropped_card : dropped.card ≤ 4 + conservation : d.first.val.val + d.second.val.val + added = + first.val.val + second.val.val + dropped + outside : ∀ e ∈ d.first.val ∪ d.second.val, + ¬ (overlayLineGraph inc (d.first.val ∪ d.second.val)).Reachable d.anchor e → + (e ∈ d.first.val ↔ e ∈ first.val) + +abbrev DemandTag := E × (Fin 4 → V) × Fin 64 × Bool × (Fin 4 → Option E) × (Fin 4 → Option E) + +noncomputable def padOccurrences (m : Multiset E) : Fin 4 → Option E := + fun i => m.toList[i.val]? + +omit [DecidableEq E] in +lemma padOccurrences_recovers {m n : Multiset E} (hm : m.card ≤ 4) (hn : n.card ≤ 4) + (h : padOccurrences m = padOccurrences n) : m = n := by + have hl : m.toList = n.toList := by + apply List.ext_getElem? + intro i + by_cases hi : i < 4 + · exact congrFun h ⟨i, hi⟩ + · have hm' : m.toList.length ≤ i := by rw [Multiset.length_toList]; omega + have hn' : n.toList.length ≤ i := by rw [Multiset.length_toList]; omega + rw [List.getElem?_eq_none hm', List.getElem?_eq_none hn'] + simpa only [Multiset.coe_toList] using congrArg (fun l : List E => (l : Multiset E)) hl + +omit [DecidableEq E] in +lemma tag_card [Fintype E] : Fintype.card (DemandTag (V := V) (E := E)) = + Fintype.card E * Fintype.card V ^ 4 * 128 * (Fintype.card E + 1) ^ 8 := by + simp only [DemandTag, Fintype.card_prod, Fintype.card_fun, Fintype.card_fin, + Fintype.card_bool, Fintype.card_option] + ring + +omit [DecidableEq E] in +lemma tag_card_bound [Fintype E] (N : ℕ) (hN : 2 ≤ N) (hV : Fintype.card V ≤ N) + (hE : Fintype.card E ≤ 2 * N^2) : + Fintype.card (DemandTag (V := V) (E := E)) ≤ (10*N)^30 := by + rw [tag_card] + have hp : 1 ≤ N^2 := Nat.one_le_pow 2 N (by omega) + have he : Fintype.card E + 1 ≤ 3 * N^2 := by omega + calc + _ ≤ (2*N^2) * N^4 * 128 * (3*N^2)^8 := by gcongr + _ = (2*128*3^8) * N^22 := by ring + _ ≤ 10^30 * N^30 := by + exact Nat.mul_le_mul (by norm_num) (Nat.pow_le_pow_right (by omega) (by omega)) + _ = _ := by ring + +namespace DemandEncoding + +variable {inc} + +def code {d : RawDemand inc} (a : DemandEncoding inc d) := + (a.first, a.second, d.anchor, d.corners, d.flags, + decide (d.anchor ∈ d.first.val), a.added, a.dropped) + +theorem code_recovers {d e : RawDemand inc} (a : DemandEncoding inc d) + (b : DemandEncoding inc e) (h : a.code = b.code) : d = e := by + simp only [code, Prod.mk.injEq] at h + obtain ⟨hf,hs,ha,hc,hfl,hbit,had,hdr⟩ := h + have hu : d.first.val.val + d.second.val.val = e.first.val.val + e.second.val.val := by + have hh := a.conservation + rw [hf, hs, hdr, ← b.conservation, ← had] at hh + exact add_right_cancel hh + have hunion := union_eq_of_multiset_union_eq hu + have hb : d.anchor ∈ d.first.val ↔ d.anchor ∈ e.first.val := by + rw [← ha] at hbit + exact decide_eq_decide.mp hbit + have hp := pair_reconstruction inc d.first.property d.second.property + e.first.property e.second.property hu d.anchor hb (fun f hfu hnr => by + have hm := a.outside f hfu hnr + have hn := b.outside f (hunion ▸ hfu) (by simpa only [← ha, ← hunion] using hnr) + rw [hf] at hm + exact hm.trans hn.symm) + exact RawDemand.ext (Subtype.ext hp.1) (Subtype.ext hp.2) ha hc hfl + +noncomputable def tag {d : RawDemand inc} (a : DemandEncoding inc d) : DemandTag (V := V) (E := E) := + (d.anchor, d.corners, d.flags, decide (d.anchor ∈ d.first.val), + padOccurrences a.added, padOccurrences a.dropped) + +noncomputable def finiteCode {d : RawDemand inc} (a : DemandEncoding inc d) := + (a.first, a.second, a.tag) + +theorem finiteCode_recovers {d e : RawDemand inc} (a : DemandEncoding inc d) + (b : DemandEncoding inc e) (h : a.finiteCode = b.finiteCode) : d = e := by + simp only [finiteCode, tag, Prod.mk.injEq] at h + obtain ⟨hf,hs,ha,hc,hfl,hbit,had,hdr⟩ := h + apply code_recovers a b + simp only [code, Prod.mk.injEq] + exact ⟨hf,hs,ha,hc,hfl,hbit, + padOccurrences_recovers a.added_card b.added_card had, + padOccurrences_recovers a.dropped_card b.dropped_card hdr⟩ + +theorem code_injective (P : RawDemand inc → Prop) + (encode : ∀ d : {d : RawDemand inc // P d}, DemandEncoding inc d.val) : + Function.Injective (fun d => (encode d).finiteCode) := by + intro d e h + exact Subtype.ext (finiteCode_recovers (encode d) (encode e) h) + +end DemandEncoding + +end + +section + +variable {V E : Type*} [Fintype V] [DecidableEq V] [DecidableEq E] + +variable (inc : E → V → Prop) + +structure EmbeddedCell (d : RawDemand inc) where + cell : CellPaths inc + orientation : Bool + first_pattern : cell.orientation orientation ⊆ d.first.val + second_pattern : cell.orientation (!orientation) ⊆ d.second.val + reach : ∀ e ∈ cell.orientation true ∪ cell.orientation false, + (overlayLineGraph inc (d.first.val ∪ d.second.val)).Reachable d.anchor e + +namespace EmbeddedCell + +variable {inc} {d : RawDemand inc} (c : EmbeddedCell inc d) + +variable (hinc : ∀ e, ∃ v, inc e v) + +def outsideFirst : Finset E := d.first.val \ c.cell.orientation c.orientation + +def outsideSecond : Finset E := d.second.val \ c.cell.orientation (!c.orientation) + +lemma outsideFirst_matching : MatchingOn inc c.outsideFirst (Finset.univ \ c.cell.vertices) := + d.first.property.sdiff (c.cell.orientation_matching c.orientation) c.first_pattern + +lemma outsideSecond_matching : MatchingOn inc c.outsideSecond (Finset.univ \ c.cell.vertices) := + d.second.property.sdiff (c.cell.orientation_matching (!c.orientation)) c.second_pattern + +lemma context_vertices_disjoint : Disjoint (Finset.univ \ c.cell.vertices) c.cell.vertices := + Finset.sdiff_disjoint + +def attachFirst (p : Finset E) (hp : MatchingOn inc p c.cell.vertices) : PM inc := + ⟨c.outsideFirst ∪ p, by + have h := c.outsideFirst_matching.union hp c.context_vertices_disjoint + simpa only [Finset.sdiff_union_of_subset (Finset.subset_univ _)] using h⟩ + +def attachSecond (p : Finset E) (hp : MatchingOn inc p c.cell.vertices) : PM inc := + ⟨c.outsideSecond ∪ p, by + have h := c.outsideSecond_matching.union hp c.context_vertices_disjoint + simpa only [Finset.sdiff_union_of_subset (Finset.subset_univ _)] using h⟩ + +include hinc in +lemma attachFirst_val (p : Finset E) (hp : MatchingOn inc p c.cell.vertices) : + (c.attachFirst p hp).val.val = c.outsideFirst.val + p.val := + union_val_add (c.outsideFirst_matching.disjoint_edges hp hinc c.context_vertices_disjoint) + +include hinc in +lemma attachSecond_val (p : Finset E) (hp : MatchingOn inc p c.cell.vertices) : + (c.attachSecond p hp).val.val = c.outsideSecond.val + p.val := + union_val_add (c.outsideSecond_matching.disjoint_edges hp hinc c.context_vertices_disjoint) + +include hinc in +lemma source_first_val : d.first.val.val = + c.outsideFirst.val + (c.cell.orientation c.orientation).val := by + have h := c.attachFirst_val hinc _ (c.cell.orientation_matching c.orientation) + have he : (c.attachFirst _ (c.cell.orientation_matching c.orientation)).val = d.first.val := by + exact Finset.sdiff_union_of_subset c.first_pattern + rwa [he] at h + +include hinc in +lemma source_second_val : d.second.val.val = + c.outsideSecond.val + (c.cell.orientation (!c.orientation)).val := by + have h := c.attachSecond_val hinc _ (c.cell.orientation_matching (!c.orientation)) + have he : (c.attachSecond _ (c.cell.orientation_matching (!c.orientation))).val = d.second.val := by + exact Finset.sdiff_union_of_subset c.second_pattern + rwa [he] at h + +include hinc in +lemma attach_outside (p : Finset E) (hp : MatchingOn inc p c.cell.vertices) + (e : E) (he : e ∈ d.first.val ∪ d.second.val) + (hn : ¬ (overlayLineGraph inc (d.first.val ∪ d.second.val)).Reachable d.anchor e) : + e ∈ d.first.val ↔ e ∈ (c.attachFirst p hp).val := by + have hnot (b : Bool) : e ∉ c.cell.orientation b := by + intro hm + apply hn + apply c.reach e + cases b + · exact Finset.mem_union_right _ hm + · exact Finset.mem_union_left _ hm + have hnp : e ∉ p := by + intro hm + obtain ⟨v,hv⟩ := hinc e + have hvc := hp.1 e hm v hv + rcases Finset.mem_union.mp he with he | he + · exact hnot _ (d.first.property.edge_mem_of_incident + (c.cell.orientation_matching c.orientation) c.first_pattern he hvc hv) + · exact hnot _ (d.second.property.edge_mem_of_incident + (c.cell.orientation_matching (!c.orientation)) c.second_pattern he hvc hv) + change e ∈ d.first.val ↔ e ∈ c.outsideFirst ∪ p + simp only [outsideFirst, Finset.mem_union, Finset.mem_sdiff, hnot, hnp, not_false_eq_true, + and_true, or_false] + +def encode (p q : Finset E) (hp : MatchingOn inc p c.cell.vertices) + (hq : MatchingOn inc q c.cell.vertices) (add drop : Multiset E) + (ha : add.card ≤ 4) (hd : drop.card ≤ 4) + (hcons : (c.cell.orientation true).val + (c.cell.orientation false).val + add = + p.val + q.val + drop) : DemandEncoding inc d where + first := c.attachFirst p hp + second := c.attachSecond q hq + added := add + dropped := drop + added_card := ha + dropped_card := hd + conservation := by + rw [c.source_first_val hinc, c.source_second_val hinc, + c.attachFirst_val hinc p hp, c.attachSecond_val hinc q hq] + have ho : (c.cell.orientation c.orientation).val + + (c.cell.orientation (!c.orientation)).val = + (c.cell.orientation true).val + (c.cell.orientation false).val := by + cases c.orientation <;> simp only [Bool.not_false, Bool.not_true] + ac_rfl + calc + _ = c.outsideFirst.val + c.outsideSecond.val + + ((c.cell.orientation c.orientation).val + (c.cell.orientation (!c.orientation)).val + add) := by ac_rfl + _ = c.outsideFirst.val + c.outsideSecond.val + (p.val + q.val + drop) := by rw [ho,hcons] + _ = _ := by ac_rfl + outside := c.attach_outside hinc p hp + +def switchEncoding (b r : Bool) (repair : Fin 4 → E) (hr : c.cell.Repairs r repair) : + DemandEncoding inc d := + c.encode hinc (c.cell.switched b) (c.cell.repaired r repair) + (c.cell.switched_matching b) (c.cell.repaired_matching r repair hr) + (c.cell.additions b r repair) (c.cell.drops r) + (by rw [← (c.cell.modification_cards b r repair).1]; exact (c.cell.modification_cards b r repair).2) + (c.cell.modification_cards b r repair).2 + (c.cell.switch_conservation b r repair hr hinc) + +def errorZeroEncoding (b : Bool) (repair : Fin 4 → E) (hr : c.cell.Repairs b repair) : + DemandEncoding inc d := + c.encode hinc (c.cell.orientation b) (c.cell.guide b repair) + (c.cell.orientation_matching b) (c.cell.guide_matching b repair hr) + (c.cell.additions b b repair) (c.cell.drops b) + (by rw [← (c.cell.modification_cards b b repair).1]; exact (c.cell.modification_cards b b repair).2) + (c.cell.modification_cards b b repair).2 + (c.cell.guide_conservation b repair hr hinc) + +def errorOneEncoding (b : Bool) (repair : Fin 4 → E) (hr : c.cell.Repairs b repair) + (Y : Fin 4) (hY : CellPaths.sideBit Y = b) : DemandEncoding inc d := + c.encode hinc (c.cell.contextOne b Y) (c.cell.guideOne b repair Y) + (c.cell.context_one_properties b repair hr Y hY hinc).1 + (c.cell.context_one_properties b repair hr Y hY hinc).2.1 + (c.cell.additions b b repair) (c.cell.drops b) + (by rw [← (c.cell.modification_cards b b repair).1]; exact (c.cell.modification_cards b b repair).2) + (c.cell.modification_cards b b repair).2 (by + rw [(c.cell.context_one_properties b repair hr Y hY hinc).2.2] + exact c.cell.guide_conservation b repair hr hinc) + +lemma zero_guide_contains (b : Bool) (repair : Fin 4 → E) (hr : c.cell.Repairs b repair) + (X : Fin 4) (hX : CellPaths.sideBit X = b) : + (c.cell.side X).closed (c.cell.chord X) ⊆ + (c.errorZeroEncoding hinc b repair hr).second.val := by + intro e he + exact Finset.mem_union_right _ (c.cell.closed_subset_guide b repair X hX he) + +lemma one_guide_contains (b : Bool) (repair : Fin 4 → E) (hr : c.cell.Repairs b repair) + (X Y : Fin 4) (hX : CellPaths.sideBit X = b) (hY : CellPaths.sideBit Y = b) + (hne : X ≠ Y) : + (c.cell.side X).closed (c.cell.chord X) ⊆ + (c.errorOneEncoding hinc b repair hr Y hY).second.val := by + intro e he + exact Finset.mem_union_right _ (c.cell.closed_subset_guide_one b repair X Y hX hY hne hinc he) + +end EmbeddedCell + +end + +section + +variable {V E : Type*} [Fintype V] [DecidableEq V] [Fintype E] [DecidableEq E] + +variable {inc : E → V → Prop} + +namespace IndexedCycle.Corners + +variable {c : IndexedCycle inc} (k : c.Corners) + +def rawDemand (M N : PM inc) (flags : Fin 64) : RawDemand inc := + ⟨M, N, c.edgeAt 0, (fun i => c.vertexAt (k.start i)), flags⟩ + +noncomputable def embeddedPair (M N : PM inc) + (hU : ∀ i, c.edgeAt i ∈ M.val ∪ N.val) + (chord : Fin 4 → E) + (hc : ∀ i v, inc (chord i) v ↔ + v = (k.side i).vertex 0 ∨ v = (k.side i).vertex (k.side i).length) + (flags : Fin 64) : EmbeddedCell inc (k.rawDemand M N flags) := by + classical + let a : ℕ := if c.edgeAt 0 ∈ M.val then 0 else 1 + have ha : a < 2 := by dsimp [a]; split <;> omega + have hM : ∀ t, t % 2 = a → c.edgeAt t ∈ M.val := by + intro t ht + apply (c.cycle_edge_mem_parity M.property N.property hU t).mpr + dsimp [a] at ht + split_ifs at ht ⊢ <;> omega + have hN : ∀ t, t % 2 = 1-a → c.edgeAt t ∈ N.val := by + intro t ht + apply (c.cycle_edge_mem_complement M.property N.property hU t).mpr + rw [c.cycle_edge_mem_parity M.property N.property hU t] + dsimp [a] at ht + split_ifs at ht ⊢ <;> first | omega | tauto + have hb : decide (k.a₀ % 2 = 1-a) = !decide (k.a₀ % 2 = a) := by + by_cases h : k.a₀ % 2 = a + · have hn : k.a₀ % 2 ≠ 1-a := by omega + simp [h] + omega + · have hn : k.a₀ % 2 = 1-a := by omega + simp [hn] + omega + refine ⟨k.cellPaths chord hc, decide (k.a₀ % 2 = a), + k.cell_orientation_subset chord hc M.val a ha hM, ?_, ?_⟩ + · rw [← hb] + exact k.cell_orientation_subset chord hc N.val (1-a) (by omega) hN + · intro e he + rcases Finset.mem_union.mp he with he | he + · exact k.cell_orientation_reachable chord hc _ hU true e he + · exact k.cell_orientation_reachable chord hc _ hU false e he + +end IndexedCycle.Corners + +end + +variable {V E : Type*} [Fintype V] + +variable {inc : E → V → Prop} + +noncomputable def matchingWeight (w : E → ℝ) (M : PM inc) : ℝ := ∏ e ∈ M.val, w e + +lemma matchingWeight_pos (w : E → ℝ) (hw : ∀ e, 0 < w e) (M : PM inc) : + 0 < matchingWeight w M := Finset.prod_pos (fun e _ => hw e) + +variable [Fintype E] + +noncomputable def partition (w : E → ℝ) : ℝ := by + classical + exact ∑ M : PM inc, matchingWeight w M + +lemma partition_pos (w : E → ℝ) (hw : ∀ e, 0 < w e) (M : PM inc) : + 0 < partition (inc := inc) w := by + classical + exact Finset.sum_pos' (fun A _ => le_of_lt (matchingWeight_pos w hw A)) + ⟨M, Finset.mem_univ _, matchingWeight_pos w hw M⟩ + +noncomputable def gibbs (w : E → ℝ) (M : PM inc) : ℝ := + matchingWeight w M / partition (inc := inc) w + +lemma gibbs_pos (w : E → ℝ) (hw : ∀ e, 0 < w e) (M : PM inc) : + 0 < gibbs w M := div_pos (matchingWeight_pos w hw M) (partition_pos w hw M) + +lemma gibbs_sum (w : E → ℝ) (hw : ∀ e, 0 < w e) (M : PM inc) : + letI : Fintype (PM inc) := Fintype.ofFinite _ + ∑ A : PM inc, gibbs w A = 1 := by + classical + simp only [gibbs, ← Finset.sum_div] + have hp := ne_of_gt (partition_pos w hw M) + convert div_self hp using 1 + congr 1 + unfold partition + congr 1 + ext A + simp + +end MatchingFPRAS.Transport + +end OAI diff --git a/lean/OAI/Combinatorics/MatchingCount/Sampling/PairStep.lean b/lean/OAI/Combinatorics/MatchingCount/Sampling/PairStep.lean new file mode 100644 index 0000000000000000000000000000000000000000..c8e5f2c07a2787c3083fe16319c59ebe0b1f2536 --- /dev/null +++ b/lean/OAI/Combinatorics/MatchingCount/Sampling/PairStep.lean @@ -0,0 +1,418 @@ +import Mathlib +import OAI.Combinatorics.MatchingCount.Sampling.MetropolisChoice + +namespace OAI + +namespace MatchingFPRAS.Replica + +open Finset + +variable {I Ω : Type*} [Fintype I] [DecidableEq I] [Fintype Ω] [DecidableEq Ω] + +variable (p : I → Ω → ℝ) + +omit [Fintype I] [Fintype Ω] [DecidableEq Ω] in +lemma replacePair_at (x y : I) (hxy : x≠y) (s : I → Ω) (a : Ω×Ω) : + ((replacePair x y s a) x,(replacePair x y s a) y)=a := by + simp [replacePair,hxy] + +omit [Fintype I] [Fintype Ω] [DecidableEq Ω] in +lemma replacePair_idem (x y : I) (s : I → Ω) (a b : Ω×Ω) : + replacePair x y (replacePair x y s a) b = replacePair x y s b := by + funext i + by_cases hy : i=y + · subst i; simp [replacePair] + · by_cases hx : i=x + · subst i; simp [replacePair,hy] + · simp [replacePair,hx,hy] + +noncomputable def pairStep (x y : I) (Q : PairCapacity p x y) (s t : I → Ω) : ℝ := + ∑ b : Ω×Ω, if replacePair x y s b=t then Q.q (s x,s y) b/(p x (s x)*p y (s y)) else 0 + +noncomputable def baseStep (i : I) (s t : I → Ω) : ℝ := + ∑ a : Ω, if Function.update s i a=t then p i a else 0 + +lemma local_pairFlow (hp : ∀ i a, 0