From 1aa3926dc16f88c31c662ecb6b0a265130cf2398 Mon Sep 17 00:00:00 2001 From: adamv-symbolica Date: Tue, 17 Nov 2026 11:38:04 +0000 Subject: [PATCH 01/15] Model basis, hull, and divergence in Lean Define prefix extrema and divergences on valued paths, with recursive formulations and adapters to maps and zipper focuses. Prove their algebraic, geometric, cardinality, and update laws; check finite counterexamples to stronger claims. --- lean/PathMapModel.lean | 6 + lean/PathMapModel/PathSetAlgebra.lean | 141 +++++++++++ lean/PathMapModel/PathSetCardinality.lean | 193 ++++++++++++++ lean/PathMapModel/PathSetCertificates.lean | 97 +++++++ lean/PathMapModel/PathSetChecks.lean | 47 ++++ lean/PathMapModel/PathSetDepth.lean | 95 +++++++ lean/PathMapModel/PathSetExtrema.lean | 192 ++++++++++++++ lean/PathMapModel/PathSetFork.lean | 83 ++++++ lean/PathMapModel/PathSetGeometry.lean | 153 +++++++++++ lean/PathMapModel/PathSetLCP.lean | 157 ++++++++++++ lean/PathMapModel/PathSetLaws.lean | 167 ++++++++++++ lean/PathMapModel/PathSetMasks.lean | 150 +++++++++++ lean/PathMapModel/PathSetPowers.lean | 93 +++++++ lean/PathMapModel/PathSetProduct.lean | 161 ++++++++++++ lean/PathMapModel/PathSetProofs.lean | 224 +++++++++++++++++ lean/PathMapModel/PathSetRecursive.lean | 280 +++++++++++++++++++++ lean/PathMapModel/PathSetRoots.lean | 152 +++++++++++ lean/PathMapModel/PathSetStructure.lean | 137 ++++++++++ lean/PathMapModel/PathSetUpdates.lean | 138 ++++++++++ lean/PathMapModel/PathSets.lean | 196 +++++++++++++++ 20 files changed, 2862 insertions(+) create mode 100644 lean/PathMapModel/PathSetAlgebra.lean create mode 100644 lean/PathMapModel/PathSetCardinality.lean create mode 100644 lean/PathMapModel/PathSetCertificates.lean create mode 100644 lean/PathMapModel/PathSetChecks.lean create mode 100644 lean/PathMapModel/PathSetDepth.lean create mode 100644 lean/PathMapModel/PathSetExtrema.lean create mode 100644 lean/PathMapModel/PathSetFork.lean create mode 100644 lean/PathMapModel/PathSetGeometry.lean create mode 100644 lean/PathMapModel/PathSetLCP.lean create mode 100644 lean/PathMapModel/PathSetLaws.lean create mode 100644 lean/PathMapModel/PathSetMasks.lean create mode 100644 lean/PathMapModel/PathSetPowers.lean create mode 100644 lean/PathMapModel/PathSetProduct.lean create mode 100644 lean/PathMapModel/PathSetProofs.lean create mode 100644 lean/PathMapModel/PathSetRecursive.lean create mode 100644 lean/PathMapModel/PathSetRoots.lean create mode 100644 lean/PathMapModel/PathSetStructure.lean create mode 100644 lean/PathMapModel/PathSetUpdates.lean create mode 100644 lean/PathMapModel/PathSets.lean diff --git a/lean/PathMapModel.lean b/lean/PathMapModel.lean index d2354b43..2ac85ab4 100644 --- a/lean/PathMapModel.lean +++ b/lean/PathMapModel.lean @@ -6,3 +6,9 @@ import PathMapModel.Map import PathMapModel.Spec import PathMapModel.Fuzz import PathMapModel.Check + +import PathMapModel.PathSets +import PathMapModel.PathSetLaws +import PathMapModel.PathSetProofs +import PathMapModel.PathSetChecks +import PathMapModel.PathSetCertificates diff --git a/lean/PathMapModel/PathSetAlgebra.lean b/lean/PathMapModel/PathSetAlgebra.lean new file mode 100644 index 00000000..2d647835 --- /dev/null +++ b/lean/PathMapModel/PathSetAlgebra.lean @@ -0,0 +1,141 @@ +import PathMapModel.PathSetGeometry + +namespace PathMapModel.PathSpace + +theorem divergence_congr {a b c f : PathSpace} + (ha : ∀ p, p ∈ a ↔ p ∈ c) (hb : ∀ p, p ∈ b ↔ p ∈ f) (p : Path) : + p ∈ divergence a b ↔ p ∈ divergence c f := by + simp only [mem_divergence, ha, hb] + +theorem divergence_terminal (a b : PathSpace) (p : Path) : + p ∈ divergence (union a [[]]) b ↔ p ∈ divergence a b := by + rw [divergence_union_left] + simp [union] + +theorem divergence_covered_marks {a b c : PathSpace} + (hc : ∀ x ∈ b, ∃ y ∈ a, (x ≼ y) = true) (p : Path) : + p ∈ divergence (union a b) c ↔ p ∈ divergence a c := by + rw [divergence_union_left] + simp only [union, List.mem_append] + exact ⟨fun h => h.elim id (divergence_covered_mono hc p), Or.inl⟩ + +theorem divergence_witness_absorption (a b c : PathSpace) (p : Path) : + p ∈ divergence (union a (divergence a b)) c ↔ p ∈ divergence a c := + divergence_covered_marks (fun _ h => divergence_output_covered h) p + +theorem divergence_completion_left (a b : PathSpace) (p : Path) : + p ∈ divergence (completion a) b ↔ p ∈ divergence a b := + divergence_witness_absorption a a b p + +theorem divergence_completion (a b : PathSpace) (p : Path) : + p ∈ divergence (completion a) (completion b) ↔ p ∈ divergence a b := by + rw [divergence_completion_left, divergence_comm, divergence_completion_left, divergence_comm] + +theorem branch_completion (a : PathSpace) (p : Path) : + p ∈ branches (completion a) ↔ p ∈ branches a := divergence_completion a a p + +theorem completion_idempotent (a : PathSpace) (p : Path) : + p ∈ completion (completion a) ↔ p ∈ completion a := by + simp only [completion, union, List.mem_append] + have h := branch_completion a p + simp only [completion, union] at h + grind + +theorem divergence_output_completion (a b : PathSpace) (p : Path) : + p ∈ completion (divergence a b) ↔ p ∈ divergence a b := by + change p ∈ union _ _ ↔ _ + simp only [union, List.mem_append] + exact ⟨fun h => h.elim id divergence_output_closed, Or.inl⟩ + +theorem absorbed_branch_marks (a b : PathSpace) (p : Path) : + p ∈ branches (union a (divergence a b)) ↔ p ∈ branches a := by + change p ∈ divergence _ _ ↔ p ∈ divergence _ _ + rw [divergence_witness_absorption, divergence_comm, divergence_witness_absorption] + +theorem branch_second_subset {a : PathSpace} {p : Path} + (h : p ∈ branches (branches a)) : p ∈ branches a := divergence_output_closed h + +theorem interior_branches (a : PathSpace) (p : Path) : + p ∈ divergence a (branches a) ↔ p ∈ interior (branches a) := by + change p ∈ divergence a (divergence a a) ↔ p ∈ interior (divergence a a) + rw [divergence_nested_exact] + exact ⟨And.right, fun h => ⟨((mem_interior _ _).mp h).1,h⟩⟩ + +theorem divergence_four_point_absorption {a b c f : PathSpace} {p : Path} + (h : p ∈ divergence (divergence a b) (divergence c f)) : + p ∈ divergence a c ∧ p ∈ divergence a f ∧ + p ∈ divergence b c ∧ p ∈ divergence b f := by + have h1 := divergence_nested_bound h + have h2 := divergence_nested_bound ((divergence_comm a (divergence c f) p).mp h1.1) + have h3 := divergence_nested_bound ((divergence_comm b (divergence c f) p).mp h1.2) + exact ⟨(divergence_comm c a p).mp h2.1, (divergence_comm f a p).mp h2.2, + (divergence_comm c b p).mp h3.1, (divergence_comm f b p).mp h3.2⟩ + +theorem branch_probe_exchange {a b c : PathSpace} {p : Path} + (hab : p ∈ divergence a b) (hc : p ∈ branches c) : + p ∈ divergence a c ∧ p ∈ divergence b c := by + have h := divergence_four_point_exchange hab hc + exact h.elim id id + +theorem divergence_incremental (a b c f : PathSpace) (p : Path) : + p ∈ divergence (union a c) (union b f) ↔ + p ∈ divergence a b ∨ p ∈ divergence c b ∨ p ∈ divergence a f ∨ p ∈ divergence c f := by + rw [divergence_union_left] + simp only [union, List.mem_append] + have h1 := divergence_union_right a b f p + have h2 := divergence_union_right c b f p + simp only [union, List.mem_append] at h1 h2 + grind + +theorem divergence_symmetric_difference {a b c : PathSpace} {p : Path} + (h : p ∈ symDiff (divergence a c) (divergence b c)) : + p ∈ divergence (symDiff a b) c := by + simp only [symDiff, union, List.mem_append, mem_diff] at h + rw [symDiff, divergence_union_left] + simp only [union, List.mem_append] + exact h.elim (fun h => Or.inl (divergence_difference_lower h.1 h.2)) + (fun h => Or.inr (divergence_difference_lower h.1 h.2)) + +theorem branch_intersection_lower {a b : PathSpace} {p : Path} + (h : p ∈ branches (inter a b)) : p ∈ branches a ∧ p ∈ branches b := by + constructor + · exact divergence_mono (fun q hq => ((mem_inter _ _ q).mp hq).1) + (fun q hq => ((mem_inter _ _ q).mp hq).1) p h + · exact divergence_mono (fun q hq => ((mem_inter _ _ q).mp hq).2) + (fun q hq => ((mem_inter _ _ q).mp hq).2) p h + +theorem branch_sandwich_upper {a b : PathSpace} {p : Path} + (h : p ∈ divergence a b) : p ∈ branches (union a b) := + (branches_union a b p).mpr (Or.inr (Or.inr h)) + +theorem child_of_covered {s : PathSpace} {p tail : Path} {z : UInt8} + (h : ∃ x ∈ s, (p ++ z :: tail ≼ x) = true) : Child s p z := by + obtain ⟨x,hx,hp⟩ := h + obtain ⟨r,rfl⟩ := (Path.prefix_iff_extension _ _).mp hp + exact ⟨tail ++ r, by simpa [List.append_assoc] using hx⟩ + +theorem divergence_interior_attribution {a b : PathSpace} {p : Path} + (h : p ∈ interior (divergence a b)) : p ∈ branches a ∨ p ∈ branches b := by + obtain ⟨hp,q,hq,hne,hpq⟩ := (mem_interior _ _).mp h + obtain ⟨z,tail,rfl⟩ := Path.proper_prefix_split hpq hne + have hza : Child a p z := child_of_covered (divergence_output_covered hq) + have hzb : Child b p z := child_of_covered (divergence_output_covered ((divergence_comm a b _).mp hq)) + obtain ⟨x,y,hxy,hx,hy⟩ := (mem_divergence_children _ _ _).mp hp + by_cases hxz : x = z + · exact Or.inr ((mem_divergence_children b b p).mpr ⟨y,z,by grind,hy,hzb⟩) + · exact Or.inl ((mem_divergence_children a a p).mpr ⟨x,z,hxz,hx,hza⟩) + +theorem divergence_interior_exact (a b : PathSpace) (p : Path) : + p ∈ divergence (union a b) (divergence a b) ↔ p ∈ interior (divergence a b) := by + rw [divergence_union_left] + simp only [union, List.mem_append] + have ha := divergence_nested_exact a b p + have hb := divergence_nested_exact b a p + have hx : ∀ q, q ∈ divergence b a ↔ q ∈ divergence a b := divergence_comm b a + have he := divergence_congr (fun q => Iff.rfl (a := q ∈ b)) hx p + have hi : p ∈ interior (divergence b a) ↔ p ∈ interior (divergence a b) := by + simp only [mem_interior, hx] + rw [he, hi] at hb + have hc := divergence_interior_attribution (a := a) (b := b) (p := p) + grind +end PathMapModel.PathSpace diff --git a/lean/PathMapModel/PathSetCardinality.lean b/lean/PathMapModel/PathSetCardinality.lean new file mode 100644 index 00000000..0be09c1f --- /dev/null +++ b/lean/PathMapModel/PathSetCardinality.lean @@ -0,0 +1,193 @@ +import PathMapModel.PathSetRoots + +namespace PathMapModel.PathSpace + +theorem dedup_nodup (a : PathSpace) : a.eraseDups.Nodup := by + cases a with + | nil => simp + | cons p ps => + rw [List.eraseDups_cons,List.nodup_cons] + exact ⟨by simp, dedup_nodup (ps.filter fun q => !q == p)⟩ +termination_by a.length +decreasing_by have h := List.length_filter_le (fun q => !q == p) ps; simp only [List.length_cons]; omega + +theorem count_le_length (a : PathSpace) : count a ≤ a.length := + (dedup_nodup a).length_le_of_subset (fun _ h => List.mem_eraseDups.mp h) + +theorem count_mono {a b : PathSpace} (h : ∀ p ∈ a, p ∈ b) : count a ≤ count b := + (dedup_nodup a).length_le_of_subset (fun p hp => List.mem_eraseDups.mpr (h p (List.mem_eraseDups.mp hp))) + +theorem count_congr {a b : PathSpace} (h : ∀ p, p ∈ a ↔ p ∈ b) : count a = count b := + Nat.le_antisymm (count_mono (fun p hp => (h p).mp hp)) (count_mono (fun p hp => (h p).mpr hp)) + +theorem equiv_iff (a b : PathSpace) : equiv a b = true ↔ ∀ p, p ∈ a ↔ p ∈ b := by + simp only [equiv,subset,Bool.and_eq_true,List.all_eq_true,List.contains_iff_mem] + constructor + · rintro ⟨h,k⟩ p; exact ⟨h p,k p⟩ + · intro h; exact ⟨fun p => (h p).mp,fun p => (h p).mpr⟩ + +theorem subset_iff (a b : PathSpace) : subset a b = true ↔ ∀ p ∈ a, p ∈ b := by + simp [subset,List.all_eq_true] + +theorem count_eq_zero (a : PathSpace) : count a = 0 ↔ a = [] := by + simp only [count,List.length_eq_zero_iff,List.eq_nil_iff_forall_not_mem,List.mem_eraseDups] + +theorem count_singleton (p : Path) : count [p] = 1 := by simp [count,List.eraseDups_cons] + +theorem count_nodup {a : PathSpace} (h : a.Nodup) : count a = a.length := by + apply Nat.le_antisymm (count_le_length a) + exact h.length_le_of_subset (fun _ h => List.mem_eraseDups.mpr h) + +theorem count_union_le (a b : PathSpace) : count (union a b) ≤ count a + count b := by + have he : count (union a b) = count (a.eraseDups ++ b.eraseDups) := + count_congr (by intro p; simp [union]) + rw [he] + have hh := count_le_length (a.eraseDups ++ b.eraseDups) + simpa [List.length_append,count] using hh + +/-- A relation assigning a distinct target to each source bounds cardinality. +The target can be chosen noncomputably inside a proof; no choice appears in the +executable model or the Rust implementation. -/ +theorem count_relation {a b : PathSpace} (r : Path → Path → Prop) + (hex : ∀ p ∈ a, ∃ q ∈ b, r p q) + (hinj : ∀ p ∈ a, ∀ p' ∈ a, ∀ q, r p q → r p' q → p = p') : count a ≤ count b := by + classical + let f : {p : Path // p ∈ a.eraseDups} → Path := fun p => + Classical.choose (hex p.val (List.mem_eraseDups.mp p.property)) + have hf : ∀ p, f p ∈ b ∧ r p.val (f p) := fun p => + Classical.choose_spec (hex p.val (List.mem_eraseDups.mp p.property)) + let out := a.eraseDups.attach.map f + have hout : out.Nodup := by + change (a.eraseDups.attach.map f).Pairwise (fun x y => x ≠ y) + rw [List.pairwise_map] + have hv : a.eraseDups.attach.Pairwise (fun u v => u.val ≠ v.val) := by + rw [← List.pairwise_map] + simpa [List.Nodup] using dedup_nodup a + apply hv.imp + intro u v hne he + have hp := hinj u.val (List.mem_eraseDups.mp u.property) v.val + (List.mem_eraseDups.mp v.property) (f u) (hf u).2 (he ▸ (hf v).2) + exact hne hp + have hsub : out ⊆ b.eraseDups := by + intro q hq + obtain ⟨p,_,rfl⟩ := List.mem_map.mp hq + exact List.mem_eraseDups.mpr (hf p).1 + have hlen := hout.length_le_of_subset hsub + simpa [out,count] using hlen + +theorem antichain_covered_count {a b : PathSpace} (ha : Antichain a) + (h : ∀ p ∈ a, ∃ q ∈ b, (p ≼ q) = true) : count a ≤ count b := by + apply count_relation (fun p q => (p ≼ q) = true) h + intro p hp q hq r hpr hqr + rcases Path.prefixes_comparable hpr hqr with hpq | hqp + · exact ha p hp q hq hpq + · exact (ha q hq p hp hqp).symm + +theorem output_hull_cardinality (a b : PathSpace) : + count (hull (divergence a b)) ≤ min (count (hull a)) (count (hull b)) := by + apply Nat.le_min.mpr + constructor + · apply antichain_covered_count (hull_is_antichain _) ?_ + intro p hp + obtain ⟨q,hq,hpq⟩ := divergence_output_covered (hull_subset _ hp) + obtain ⟨r,hr,hqr⟩ := hull_covers hq + exact ⟨r,hr,Path.prefix_trans hpq hqr⟩ + · apply antichain_covered_count (hull_is_antichain _) ?_ + intro p hp + obtain ⟨q,hq,hpq⟩ := divergence_output_covered ((divergence_comm a b p).mp (hull_subset _ hp)) + obtain ⟨r,hr,hqr⟩ := hull_covers hq + exact ⟨r,hr,Path.prefix_trans hpq hqr⟩ + +theorem double_covered_count {a b : PathSpace} (ha : Antichain a) + (hex : ∀ p ∈ a, ∃ w : Path × Path, w.1 ∈ b ∧ w.2 ∈ b ∧ w.1 ≠ w.2 ∧ + (p ≼ w.1) = true ∧ (p ≼ w.2) = true) : 2 * count a ≤ count b := by + classical + let f : {p : Path // p ∈ a.eraseDups} → Path × Path := fun p => + Classical.choose (hex p.val (List.mem_eraseDups.mp p.property)) + have hf : ∀ p, (f p).1 ∈ b ∧ (f p).2 ∈ b ∧ (f p).1 ≠ (f p).2 ∧ + (p.val ≼ (f p).1) = true ∧ (p.val ≼ (f p).2) = true := fun p => + Classical.choose_spec (hex p.val (List.mem_eraseDups.mp p.property)) + let out := a.eraseDups.attach.flatMap (fun p => [(f p).1,(f p).2]) + have hpref : ∀ p, ∀ q ∈ [(f p).1,(f p).2], (p.val ≼ q) = true := by + intro p q hq + simp only [List.mem_cons,List.not_mem_nil,or_false] at hq + rcases hq with rfl | rfl + · exact (hf p).2.2.2.1 + · exact (hf p).2.2.2.2 + have hout : out.Nodup := by + apply List.pairwise_flatMap.mpr + constructor + · intro p hp + exact List.Pairwise.cons (by simpa using (hf p).2.2.1) (List.Pairwise.cons (by simp) List.Pairwise.nil) + · have hv : a.eraseDups.attach.Pairwise (fun u v => u.val ≠ v.val) := by + rw [← List.pairwise_map] + simpa [List.Nodup] using dedup_nodup a + apply hv.imp + intro u v hne x hx y hy he + subst y + have hu := hpref u x hx + have hv := hpref v x hy + have hpu := List.mem_eraseDups.mp u.property + have hpv := List.mem_eraseDups.mp v.property + rcases Path.prefixes_comparable hu hv with huv | hvu + · exact hne (ha u.val hpu v.val hpv huv) + · exact hne (ha v.val hpv u.val hpu hvu).symm + have hsub : out ⊆ b.eraseDups := by + intro q hq + obtain ⟨p,_,hp⟩ := List.mem_flatMap.mp hq + apply List.mem_eraseDups.mpr + simp only [List.mem_cons,List.not_mem_nil,or_false] at hp + rcases hp with rfl | rfl + · exact (hf p).1 + · exact (hf p).2.1 + have hlen : ∀ ps : List {p : Path // p ∈ a.eraseDups}, + (ps.flatMap fun p => [(f p).1,(f p).2]).length = 2 * ps.length := by + intro ps; induction ps with + | nil => simp + | cons p ps ih => simp [ih]; omega + have hbound := hout.length_le_of_subset hsub + change (a.eraseDups.attach.flatMap _).length ≤ _ at hbound + rw [hlen] at hbound + simpa [count] using hbound + +theorem maximal_branch_double (a : PathSpace) : 2 * count (hull (branches a)) ≤ count (hull a) := by + apply double_covered_count (hull_is_antichain _) ?_ + intro p hp + obtain ⟨u,hu,v,hv,hd⟩ := (mem_divergence _ _ _).mp (hull_subset _ hp) + obtain ⟨x,hx,hux⟩ := hull_covers hu + obtain ⟨y,hy,hvy⟩ := hull_covers hv + obtain ⟨s,rfl⟩ := (Path.prefix_iff_extension _ _).mp hux + obtain ⟨t,rfl⟩ := (Path.prefix_iff_extension _ _).mp hvy + have hdiv := Path.divergence_extend_both s t hd + refine ⟨(u++s,v++t),hx,hy,?_,Path.divergence_prefix_left hdiv, + Path.divergence_prefix_left ((Path.divergence_comm _ _).trans hdiv)⟩ + intro he + dsimp only at he + rw [he,Path.divergence_self] at hdiv + contradiction + +theorem maximal_branch_count (a : PathSpace) : count (hull (branches a)) ≤ count (hull a) / 2 := by + have h := maximal_branch_double a + omega + +theorem branch_iter_leaf_weight (a : PathSpace) (n : Nat) : + 2^n * count (hull (branchIter a n)) ≤ count (hull a) := by + induction n with + | zero => simp [branchIter] + | succ n ih => + have h := Nat.mul_le_mul_left (2^n) (maximal_branch_double (branchIter a n)) + have he : 2^(n+1) * count (hull (branchIter a (n+1))) = + 2^n * (2 * count (hull (branches (branchIter a n)))) := by + simp [Nat.pow_succ,Nat.mul_assoc,branchIter] + rw [he] + exact Nat.le_trans h ih + +theorem branch_leaf_bound {a : PathSpace} {n : Nat} (h : branchIter a n ≠ []) : + 2^n ≤ count (hull a) := by + have hn : count (hull (branchIter a n)) ≠ 0 := by + intro hh + exact h ((hull_nonempty _).mp ((count_eq_zero _).mp hh)) + have hpos : 1 ≤ count (hull (branchIter a n)) := by omega + have hm := Nat.mul_le_mul_left (2^n) hpos + exact Nat.le_trans (by simpa using hm) (branch_iter_leaf_weight a n) +end PathMapModel.PathSpace diff --git a/lean/PathMapModel/PathSetCertificates.lean b/lean/PathMapModel/PathSetCertificates.lean new file mode 100644 index 00000000..f2d85555 --- /dev/null +++ b/lean/PathMapModel/PathSetCertificates.lean @@ -0,0 +1,97 @@ +import PathMapModel.PathSetUpdates + +/-! Bridges between the universally quantified set laws and the executable +Boolean catalogue. Set equations are proved pointwise; normalization preserves +membership. Cardinality and equality are explicitly set-based, so list order +and duplicate witnesses do not alter any law. -/ +namespace PathMapModel.PathSpace + +theorem normalize_equiv (a : PathSpace) : equiv (normalize a) a = true := + (equiv_iff _ _).mpr (mem_normalize a) + +theorem count_normalize (a : PathSpace) : count (normalize a) = count a := + count_congr (mem_normalize a) + +theorem normalize_empty (a : PathSpace) : normalize a = [] ↔ a = [] := by + simp only [List.eq_nil_iff_forall_not_mem,mem_normalize] + +theorem basis_congr {a b : PathSpace} (h : ∀ p, p ∈ a ↔ p ∈ b) (p : Path) : + p ∈ basis a ↔ p ∈ basis b := by simp only [mem_basis,h] + +theorem hull_congr {a b : PathSpace} (h : ∀ p, p ∈ a ↔ p ∈ b) (p : Path) : + p ∈ hull a ↔ p ∈ hull b := by simp only [mem_hull,h] + +theorem height_congr {a b : PathSpace} (h : ∀ p, p ∈ a ↔ p ∈ b) : height a = height b := by + apply Nat.le_antisymm + · apply (height_le _ _).mpr; intro p hp; exact length_le_height ((h p).mp hp) + · apply (height_le _ _).mpr; intro p hp; exact length_le_height ((h p).mpr hp) + +theorem covers_iff (a b : PathSpace) : covers a b = true ↔ ∀ p ∈ a, ∃ q ∈ b, (p ≼ q) = true := by + simp [covers,List.all_eq_true,List.any_eq_true] + +theorem basis_covers (a : PathSpace) : (covers a (hull a) && covers (basis a) a) = true := by + rw [Bool.and_eq_true,covers_iff,covers_iff] + exact ⟨fun _ h => hull_covers h,fun p h => ⟨p,basis_subset a h,Path.prefix_self p⟩⟩ + +theorem basis_prefixFree (a : PathSpace) : prefixFree (basis a) = true := + (equiv_iff _ _).mpr (fun p => (basis_idempotent a p).symm) + +theorem hull_prefixFree (a : PathSpace) : prefixFree (hull a) = true := + (equiv_iff _ _).mpr (fun p => (basis_of_hull a p).symm) + +theorem terminal_invariance (a b : PathSpace) (p : Path) : + p ∈ divergence (union a [[]]) (union b [[]]) ↔ p ∈ divergence a b := by + rw [divergence_terminal,divergence_comm,divergence_terminal,divergence_comm] + +theorem branch_epsilon (a : PathSpace) (p : Path) : + p ∈ branches (union a [[]]) ↔ p ∈ branches a := terminal_invariance a a p + +theorem output_branches {a b : PathSpace} {p : Path} + (h : p ∈ branches (divergence a b)) : + p ∈ divergence a b ∧ p ∈ branches a ∧ p ∈ branches b := + ⟨divergence_output_closed h,divergence_output_branches h⟩ + +theorem no_nonempty_branch_fixed_point {a : PathSpace} (ha : a ≠ []) : + equiv (branches a) a = false := by + cases he : equiv (branches a) a with + | false => rfl + | true => exact False.elim (branch_no_fixed_point ha ((equiv_iff _ _).mp he)) + +theorem count_eq_one (a : PathSpace) : count a = 1 ↔ ∃ p, ∀ q, q ∈ a ↔ q = p := by + constructor + · intro h + have hl : a.eraseDups.length = 1 := h + obtain ⟨p,hp⟩ := List.length_eq_one_iff.mp hl + exact ⟨p,fun q => by rw [← List.mem_eraseDups,hp]; simp⟩ + · rintro ⟨p,hp⟩ + have he : count a = count [p] := count_congr (by intro q; simpa using hp q) + rw [he,count_singleton] + +theorem singleton_prefix_test (a b : PathSpace) : + (count a == 1 && b.all (fun q => a.all (· ≼ q))) = true ↔ + ∃ p, (∀ q, q ∈ a ↔ q = p) ∧ ∀ r ∈ b, (p ≼ r) = true := by + simp only [Bool.and_eq_true,beq_iff_eq,count_eq_one,List.all_eq_true] + constructor + · rintro ⟨⟨p,hp⟩,he⟩ + exact ⟨p,hp,fun r hr => he r hr p ((hp p).mpr rfl)⟩ + · rintro ⟨p,hp,he⟩ + refine ⟨⟨p,hp⟩,?_⟩ + intro r hr q hq + have hh := (hp q).mp hq + subst q; exact he r hr + +/-- The exact Boolean zero criterion used by the executable catalogue. -/ +theorem zero_criterion_check (a b : PathSpace) : + (normalize (divergence a b)).isEmpty = + (a.isEmpty || b.isEmpty || + (count (hull a) == 1 && (hull b).all (fun q => (hull a).all (· ≼ q))) || + (count (hull b) == 1 && (hull a).all (fun q => (hull b).all (· ≼ q)))) := by + have hh : (normalize (divergence a b)).isEmpty = true ↔ + (a.isEmpty || b.isEmpty || + (count (hull a) == 1 && (hull b).all (fun q => (hull a).all (· ≼ q))) || + (count (hull b) == 1 && (hull a).all (fun q => (hull b).all (· ≼ q)))) = true := by + simp only [List.isEmpty_iff,normalize_empty,Bool.or_eq_true,singleton_prefix_test] + rw [zero_criterion] + grind + exact Bool.eq_iff_iff.mpr hh +end PathMapModel.PathSpace diff --git a/lean/PathMapModel/PathSetChecks.lean b/lean/PathMapModel/PathSetChecks.lean new file mode 100644 index 00000000..d2df394b --- /dev/null +++ b/lean/PathMapModel/PathSetChecks.lean @@ -0,0 +1,47 @@ +import PathMapModel.PathSetLaws +import PathMapModel.PathSetProofs + +set_option maxRecDepth 4096 +set_option maxHeartbeats 0 +namespace PathMapModel.PathSetChecks +open PathSpace + +def small : List PathSpace := [[], [[]], [[0]], [[1]], [[],[0]], [[],[1]], [[0],[1]], [[],[0],[1]]] +def fixtures : List PathSpace := small ++ + [[[0],[0,0],[0,1]], [[0,0],[0,1]], [[0],[1,0],[1,1,0],[1,1,1]], + [[255,0],[255,255]], [[0,0,0],[1],[0,1],[0,0,1]]] + +#guard (small.flatMap fun a => small.flatMap fun b => small.flatMap fun c => + small.map fun f => (PathSetLaws.failures (PathSetLaws.all a b c f)).isEmpty).all id +#guard (fixtures.flatMap fun a => fixtures.map fun b => + (PathSetLaws.failures (PathSetLaws.unary a ++ PathSetLaws.binary a b)).isEmpty).all id +#guard (fixtures.flatMap fun a => (List.range 4).flatMap fun m => (List.range 4).map fun n => + (PathSetLaws.failures (PathSetLaws.powers a m n)).isEmpty).all id + +-- Counterexamples are positively checked: these are NOT proposed rewrite rules. +#guard !equiv (divergence (divergence [[0,0]] [[0,1]]) [[1]]) + (divergence [[0,0]] (divergence [[0,1]] [[1]])) +#guard !equiv (divergence (inter [[0,0]] [[0,1]]) [[1]]) + (inter (divergence [[0,0]] [[1]]) (divergence [[0,1]] [[1]])) +#guard !equiv (divergence (diff [[0,0],[0,1]] [[0,0]]) [[1]]) + (diff (divergence [[0,0],[0,1]] [[1]]) (divergence [[0,0]] [[1]])) +#guard !equiv (restrict (divergence [[0,0]] [[0,1]]) [[0,0],[0,1]]) + (divergence (restrict [[0,0]] [[0,0],[0,1]]) (restrict [[0,1]] [[0,0],[0,1]])) +#guard !equiv (divergence (product [[0]] [[2]]) (product [[0,1]] [[2]])) (divergence [[0]] [[0,1]]) +#guard !equiv (divergence [[0],[1,0],[1,1,0],[1,1,1]] (branches [[0],[1,0],[1,1,0],[1,1,1]])) + (branches (branches [[0],[1,0],[1,1,0],[1,1,1]])) +#guard !equiv (divergence [[0,0],[0,1]] [[0]]) (divergence [[0,0],[0,1]] [[0,0]]) +#guard !equiv (branches [[0],[0,0],[0,1]]) (branches (basis [[0],[0,0],[0,1]])) +#guard equiv (branches [[102,111,111],[102,111,111,100]]) [] -- foo / food +#guard equiv (divergence [[102,111,111,100]] [[102,111,117,114]]) [[102,111]] -- food / four +#guard count (divergence [[0,0,0]] [[1],[0,1],[0,0,1]]) == 3 + +-- The map adapter retains values; bare paths do not supply witnesses. +def valued : PathMap Nat := PathMap.mk' [([0],10),([0,1],20),([2],30)] [[0,1,255],[3,4]] +#guard (Map.basis valued).valAt [0] == some 10 +#guard (Map.basis valued).valAt [0,1] == none +#guard (Map.hull valued).valAt [0,1] == some 20 +#guard (Map.hull valued).valAt [0] == none +#guard equiv (ofMap (Map.branches valued)) [[]] +#guard equiv (ofMap (Map.divergence valued (PathMap.mk' ([] : List (Path × Nat)) [[4,5]]))) [] +end PathMapModel.PathSetChecks diff --git a/lean/PathMapModel/PathSetDepth.lean b/lean/PathMapModel/PathSetDepth.lean new file mode 100644 index 00000000..58aa1329 --- /dev/null +++ b/lean/PathMapModel/PathSetDepth.lean @@ -0,0 +1,95 @@ +import PathMapModel.PathSetLCP + +namespace PathMapModel.Path + +theorem divergence_of_prefix {x y : Path} (h : (x ≼ y) = true) : divergence x y = none := by + obtain ⟨r,rfl⟩ := (prefix_iff_extension _ _).mp h + simpa using divergence_wrap x [] r + +theorem divergence_none_iff (x y : Path) : + divergence x y = none ↔ (x ≼ y) = true ∨ (y ≼ x) = true := by + constructor + · intro h + rcases divergence_or_comparable x y with hd | hp | hp + · simp [h] at hd + · exact Or.inl hp + · exact Or.inr hp + · rintro (h | h) + · exact divergence_of_prefix h + · rw [divergence_comm]; exact divergence_of_prefix h +end PathMapModel.Path + +namespace PathMapModel.PathSpace +private theorem foldl_max_le (ns : List Nat) (k n : Nat) : + ns.foldl max k ≤ n ↔ k ≤ n ∧ ∀ x ∈ ns, x ≤ n := by + induction ns generalizing k with + | nil => simp + | cons x xs ih => simp [ih, Nat.max_le]; grind + +theorem height_le (a : PathSpace) (n : Nat) : + height a ≤ n ↔ ∀ p ∈ a, p.length ≤ n := by + simp [height, foldl_max_le] + +theorem length_le_height {a : PathSpace} {p : Path} (hp : p ∈ a) : p.length ≤ height a := + (height_le a (height a)).mp (Nat.le_refl _) p hp + +theorem height_attained {a : PathSpace} (h : a ≠ []) : ∃ p ∈ a, height a = p.length := by + let p := a.maxOn List.length h + have hp : p ∈ a := List.maxOn_mem + refine ⟨p,hp,Nat.le_antisymm ?_ (length_le_height hp)⟩ + apply (height_le a p.length).mpr + intro q hq + exact List.le_apply_maxOn_of_mem hq + +theorem divergence_depth {a b : PathSpace} (h : divergence a b ≠ []) : + height (divergence a b) < min (height a) (height b) := by + obtain ⟨p,hp,he⟩ := height_attained h + obtain ⟨x,hx,y,hy,hd⟩ := (mem_divergence _ _ _).mp hp + have hpx := Path.divergence_length_left hd + have hpy := Path.divergence_length_right hd + have hx := length_le_height hx + have hy := length_le_height hy + omega + +theorem branch_iter_depth (a : PathSpace) (n : Nat) {p : Path} + (h : p ∈ branchIter a n) : p.length + n ≤ height a := by + induction n generalizing p with + | zero => exact length_le_height h + | succ n ih => + obtain ⟨x,hx,y,hy,hd⟩ := (mem_divergence _ _ _).mp h + have hl := Path.divergence_length_left hd + have hb := ih hx + omega + +theorem branch_depth_nilpotence (a : PathSpace) : branchIter a (height a + 1) = [] := by + apply List.eq_nil_iff_forall_not_mem.mpr + intro p hp + have h := branch_iter_depth a (height a + 1) hp + omega + +theorem branch_no_fixed_point {a : PathSpace} (h : a ≠ []) : + ¬ (∀ p, p ∈ branches a ↔ p ∈ a) := by + intro he + obtain ⟨p,hp,hmax⟩ := height_attained h + obtain ⟨x,hx,y,hy,hd⟩ := (mem_divergence _ _ _).mp ((he p).mpr hp) + have hpx := Path.divergence_length_left hd + have hx := length_le_height hx + omega + +theorem singleton_chain (q : Path) (a : PathSpace) : branches (divergence [q] a) = [] := by + apply List.eq_nil_iff_forall_not_mem.mpr + intro p hp + obtain ⟨x,hx,y,hy,hd⟩ := (mem_divergence _ _ _).mp hp + obtain ⟨qx,hqx,hpx⟩ := divergence_output_covered hx + obtain ⟨qy,hqy,hpy⟩ := divergence_output_covered hy + simp only [List.mem_singleton] at hqx hqy + subst qx; subst qy + have hn := (Path.divergence_none_iff x y).mpr (Path.prefixes_comparable hpx hpy) + simp [hd] at hn + +theorem singleton_existing_branches {q p : Path} {a : PathSpace} + (h : p ∈ interior (divergence [q] a)) : p ∈ branches a := by + rcases divergence_interior_attribution h with hs | hs + · simp [branches,divergence] at hs + · exact hs +end PathMapModel.PathSpace diff --git a/lean/PathMapModel/PathSetExtrema.lean b/lean/PathMapModel/PathSetExtrema.lean new file mode 100644 index 00000000..4f499154 --- /dev/null +++ b/lean/PathMapModel/PathSetExtrema.lean @@ -0,0 +1,192 @@ +import PathMapModel.PathSetAlgebra +import Init.Data.List.MinMaxOn + +namespace PathMapModel.Path + +theorem prefix_iff_list (p q : Path) : (p ≼ q) = true ↔ p <+: q := by + rw [prefix_iff_extension, List.prefix_iff_exists_eq_append] + +@[simp] theorem prefix_self (p : Path) : (p ≼ p) = true := + (prefix_iff_list p p).mpr List.prefix_rfl + +theorem prefix_trans {p q r : Path} (h : (p ≼ q) = true) (k : (q ≼ r) = true) : + (p ≼ r) = true := (prefix_iff_list _ _).mpr + (((prefix_iff_list _ _).mp h).trans ((prefix_iff_list _ _).mp k)) + +theorem prefix_length {p q : Path} (h : (p ≼ q) = true) : p.length ≤ q.length := + ((prefix_iff_list _ _).mp h).length_le + +theorem prefix_eq_of_length {p q : Path} (h : (p ≼ q) = true) (hl : q.length ≤ p.length) : + p = q := ((prefix_iff_list _ _).mp h).eq_of_length_le hl + +theorem prefix_antisymm {p q : Path} (h : (p ≼ q) = true) (k : (q ≼ p) = true) : p = q := + prefix_eq_of_length h (prefix_length k) + +theorem prefixes_comparable {p q r : Path} (h : (p ≼ r) = true) (k : (q ≼ r) = true) : + (p ≼ q) = true ∨ (q ≼ p) = true := by + simpa only [prefix_iff_list] using List.prefix_or_prefix_of_prefix + ((prefix_iff_list _ _).mp h) ((prefix_iff_list _ _).mp k) +end PathMapModel.Path + +namespace PathMapModel.PathSpace + +theorem hull_covers {a : PathSpace} {p : Path} (hp : p ∈ a) : + ∃ q ∈ hull a, (p ≼ q) = true := by + let s := a.filter (p ≼ ·) + have hs : p ∈ s := by simp [s,hp] + let q := s.maxOn List.length (List.ne_nil_of_mem hs) + have hq : q ∈ s := List.maxOn_mem + have hqm : q ∈ a ∧ (p ≼ q) = true := by simpa [s] using hq + refine ⟨q, (mem_hull a q).mpr ⟨hqm.1, ?_⟩, hqm.2⟩ + intro r hr hne + cases he : (q ≼ r) with + | false => rfl + | true => + have hrs : r ∈ s := by simp [s, hr, Path.prefix_trans hqm.2 he] + have hl : r.length ≤ q.length := List.le_apply_maxOn_of_mem hrs + exact False.elim (hne (Path.prefix_eq_of_length he hl).symm) + +theorem basis_below {a : PathSpace} {p : Path} (hp : p ∈ a) : + ∃ q ∈ basis a, (q ≼ p) = true := by + let s := a.filter (· ≼ p) + have hs : p ∈ s := by simp [s,hp] + let q := s.minOn List.length (List.ne_nil_of_mem hs) + have hq : q ∈ s := List.minOn_mem + have hqm : q ∈ a ∧ (q ≼ p) = true := by simpa [s] using hq + refine ⟨q, (mem_basis a q).mpr ⟨hqm.1, ?_⟩, hqm.2⟩ + intro r hr hne + cases he : (r ≼ q) with + | false => rfl + | true => + have hrs : r ∈ s := by simp [s, hr, Path.prefix_trans he hqm.2] + have hl : q.length ≤ r.length := List.apply_minOn_le_of_mem hrs + exact False.elim (hne (Path.prefix_eq_of_length he hl)) + +theorem hull_nonempty (a : PathSpace) : hull a = [] ↔ a = [] := by + constructor + · intro h + apply List.eq_nil_iff_forall_not_mem.mpr + intro p hp + obtain ⟨q,hq,_⟩ := hull_covers hp + simp [h] at hq + · rintro rfl; rfl + +theorem basis_nonempty (a : PathSpace) : basis a = [] ↔ a = [] := by + constructor + · intro h + apply List.eq_nil_iff_forall_not_mem.mpr + intro p hp + obtain ⟨q,hq,_⟩ := basis_below hp + simp [h] at hq + · rintro rfl; rfl + +theorem divergence_hull_left (a b : PathSpace) (p : Path) : + p ∈ divergence (hull a) b ↔ p ∈ divergence a b := by + exact ⟨divergence_mono (fun _ h => hull_subset a h) (fun _ h => h) p, + divergence_covered_mono (fun _ h => hull_covers h) p⟩ + +theorem divergence_hull (a b : PathSpace) (p : Path) : + p ∈ divergence (hull a) (hull b) ↔ p ∈ divergence a b := by + rw [divergence_hull_left, divergence_comm, divergence_hull_left, divergence_comm] + +theorem branch_hull (a : PathSpace) (p : Path) : + p ∈ branches (hull a) ↔ p ∈ branches a := divergence_hull a a p + +theorem basis_of_hull (a : PathSpace) (p : Path) : p ∈ basis (hull a) ↔ p ∈ hull a := by + exact ⟨basis_subset _, fun hp => (mem_basis _ _).mpr + ⟨hp, fun q hq hne => hull_antichain hq hp hne⟩⟩ + +theorem hull_of_basis (a : PathSpace) (p : Path) : p ∈ hull (basis a) ↔ p ∈ basis a := by + exact ⟨hull_subset _, fun hp => (mem_hull _ _).mpr + ⟨hp, fun q hq hne => basis_antichain hp hq (Ne.symm hne)⟩⟩ + +theorem mem_restrict (a b : PathSpace) (p : Path) : + p ∈ restrict a b ↔ p ∈ a ∧ ∃ q ∈ b, (q ≼ p) = true := by + simp [restrict, List.any_eq_true] + +theorem restriction_basis_mask (a b : PathSpace) (p : Path) : + p ∈ restrict a (basis b) ↔ p ∈ restrict a b := by + simp only [mem_restrict] + constructor + · rintro ⟨hp,q,hq,hqp⟩; exact ⟨hp,q,basis_subset b hq,hqp⟩ + · rintro ⟨hp,q,hq,hqp⟩ + obtain ⟨r,hr,hrq⟩ := basis_below hq + exact ⟨hp,r,hr,Path.prefix_trans hrq hqp⟩ + +/-- Replacing a space by any cofinal subset preserves its maximal members. -/ +theorem hull_cofinal {a b : PathSpace} (hs : ∀ p ∈ b, p ∈ a) + (hc : ∀ p ∈ a, ∃ q ∈ b, (p ≼ q) = true) (p : Path) : + p ∈ hull a ↔ p ∈ hull b := by + constructor + · intro hp + obtain ⟨q,hq,hpq⟩ := hc p (hull_subset a hp) + have he : q = p := by + by_cases hn : q = p + · exact hn + exfalso + have hf := ((mem_hull a p).mp hp).2 q (hs q hq) hn + simp [hpq] at hf + subst q + exact (mem_hull b p).mpr ⟨hq, fun q hq hn => ((mem_hull a p).mp hp).2 q (hs q hq) hn⟩ + · intro hp + refine (mem_hull a p).mpr ⟨hs p (hull_subset b hp), ?_⟩ + intro q hq hn + cases he : (p ≼ q) with + | false => rfl + | true => + obtain ⟨r,hr,hqr⟩ := hc q hq + have hpr := Path.prefix_trans he hqr + have hrn : r ≠ p := by intro hh; subst r; exact hn (Path.prefix_antisymm he hqr).symm + have hf := ((mem_hull b p).mp hp).2 r hr hrn + simp [hpr] at hf + +theorem basis_coinitial {a b : PathSpace} (hs : ∀ p ∈ b, p ∈ a) + (hc : ∀ p ∈ a, ∃ q ∈ b, (q ≼ p) = true) (p : Path) : + p ∈ basis a ↔ p ∈ basis b := by + constructor + · intro hp + obtain ⟨q,hq,hqp⟩ := hc p (basis_subset a hp) + have he : q = p := by + by_cases hn : q = p + · exact hn + exfalso + have hf := ((mem_basis a p).mp hp).2 q (hs q hq) hn + simp [hqp] at hf + subst q + exact (mem_basis b p).mpr ⟨hq, fun q hq hn => ((mem_basis a p).mp hp).2 q (hs q hq) hn⟩ + · intro hp + refine (mem_basis a p).mpr ⟨hs p (basis_subset b hp), ?_⟩ + intro q hq hn + cases he : (q ≼ p) with + | false => rfl + | true => + obtain ⟨r,hr,hrq⟩ := hc q hq + have hrp := Path.prefix_trans hrq he + have hrn : r ≠ p := by intro hh; subst r; exact hn (Path.prefix_antisymm hrq he).symm + have hf := ((mem_basis b p).mp hp).2 r hr hrn + simp [hrp] at hf + +theorem hull_union (a b : PathSpace) (p : Path) : + p ∈ hull (union a b) ↔ p ∈ hull (union (hull a) (hull b)) := by + apply hull_cofinal + · intro q hq + simp only [union, List.mem_append] at hq ⊢ + exact hq.elim (fun h => Or.inl (hull_subset a h)) (fun h => Or.inr (hull_subset b h)) + · intro q hq + simp only [union, List.mem_append] at hq ⊢ + rcases hq with hq | hq + · obtain ⟨r,hr,hqr⟩ := hull_covers hq; exact ⟨r,Or.inl hr,hqr⟩ + · obtain ⟨r,hr,hqr⟩ := hull_covers hq; exact ⟨r,Or.inr hr,hqr⟩ + +theorem basis_union (a b : PathSpace) (p : Path) : + p ∈ basis (union a b) ↔ p ∈ basis (union (basis a) (basis b)) := by + apply basis_coinitial + · intro q hq + simp only [union, List.mem_append] at hq ⊢ + exact hq.elim (fun h => Or.inl (basis_subset a h)) (fun h => Or.inr (basis_subset b h)) + · intro q hq + simp only [union, List.mem_append] at hq ⊢ + rcases hq with hq | hq + · obtain ⟨r,hr,hrq⟩ := basis_below hq; exact ⟨r,Or.inl hr,hrq⟩ + · obtain ⟨r,hr,hrq⟩ := basis_below hq; exact ⟨r,Or.inr hr,hrq⟩ +end PathMapModel.PathSpace diff --git a/lean/PathMapModel/PathSetFork.lean b/lean/PathMapModel/PathSetFork.lean new file mode 100644 index 00000000..5ce699e3 --- /dev/null +++ b/lean/PathMapModel/PathSetFork.lean @@ -0,0 +1,83 @@ +import PathMapModel.PathSetStructure + +namespace PathMapModel.Path + +theorem divergence_append_single_lcp (x y : Path) (a b : UInt8) {p : Path} + (h : divergence (x ++ [a]) (y ++ [b]) = some p) : lcp x y = p := by + induction x generalizing y p with + | nil => + cases y with + | nil => + by_cases hab : a = b + · subst b; simp at h + · simpa [divergence,lcp,hab] using h + | cons c ys => + by_cases hac : a = c + · subst c; simp [divergence] at h + · simpa [divergence,lcp,hac] using h + | cons c xs ih => + cases y with + | nil => + by_cases hcb : c = b + · subst c; simp [divergence] at h + · simpa [divergence,lcp,hcb] using h + | cons d ys => + by_cases hcd : c = d + · subst d + simp only [List.cons_append,divergence,beq_self_eq_true,if_true,Option.map_eq_some_iff] at h + obtain ⟨q,hq,rfl⟩ := h + simp [lcp,ih ys hq] + · simpa [divergence,lcp,hcd] using h + +theorem fork_witness (x y : Path) : ∃ a ∈ ([0,1] : List UInt8), ∃ b ∈ ([0,1] : List UInt8), + divergence (x ++ [a]) (y ++ [b]) = some (lcp x y) := by + induction x generalizing y with + | nil => + cases y with + | nil => exact ⟨0,by decide,1,by decide,by decide⟩ + | cons c ys => + by_cases hc : c = 0 + · subst c; exact ⟨1,by decide,0,by decide,by simp [divergence,lcp]⟩ + · exact ⟨0,by decide,0,by decide,by simp [divergence,lcp,Ne.symm hc]⟩ + | cons c xs ih => + cases y with + | nil => + by_cases hc : c = 0 + · subst c; exact ⟨0,by decide,1,by decide,by simp [divergence,lcp]⟩ + · exact ⟨0,by decide,0,by decide,by simp [divergence,lcp,hc]⟩ + | cons d ys => + by_cases hcd : c = d + · subst d + obtain ⟨a,ha,b,hb,hd⟩ := ih ys + exact ⟨a,ha,b,hb,by simp [divergence,lcp,hd]⟩ + · exact ⟨0,by decide,0,by decide,by simp [divergence,lcp,hcd]⟩ +end PathMapModel.Path + +namespace PathMapModel.PathSpace + +theorem fork_lcp (a b : PathSpace) (p : Path) : + p ∈ divergence (product a [[0],[1]]) (product b [[0],[1]]) ↔ p ∈ lcpProduct a b := by + constructor + · intro h + obtain ⟨x,hx,y,hy,hd⟩ := (mem_divergence _ _ _).mp h + obtain ⟨u,hu,c,hc,rfl⟩ := (mem_product _ _ _).mp hx + obtain ⟨v,hv,e,he,rfl⟩ := (mem_product _ _ _).mp hy + simp only [List.mem_cons,List.not_mem_nil,or_false] at hc he + rcases hc with rfl | rfl <;> rcases he with rfl | rfl <;> + exact (mem_lcpProduct _ _ _).mpr ⟨u,hu,v,hv,Path.divergence_append_single_lcp _ _ _ _ hd⟩ + · intro h + obtain ⟨u,hu,v,hv,rfl⟩ := (mem_lcpProduct _ _ _).mp h + obtain ⟨c,hc,e,he,hd⟩ := Path.fork_witness u v + have hc' : [c] ∈ ([[0],[1]] : PathSpace) := by simpa using hc + have he' : [e] ∈ ([[0],[1]] : PathSpace) := by simpa using he + exact (mem_divergence _ _ _).mpr ⟨u++[c],(mem_product _ _ _).mpr ⟨u,hu,[c],hc',rfl⟩, + v++[e],(mem_product _ _ _).mpr ⟨v,hv,[e],he',rfl⟩,hd⟩ + +theorem fork_completion (a : PathSpace) (p : Path) : + p ∈ branches (product a [[0],[1]]) ↔ p ∈ completion a := + (fork_lcp a a p).trans (lcp_diagonal a p) + +theorem range_realization (a : PathSpace) (p : Path) : + p ∈ branches (product (completion a) [[0],[1]]) ↔ p ∈ completion a := + (fork_completion (completion a) p).trans (completion_idempotent a p) +end PathMapModel.PathSpace diff --git a/lean/PathMapModel/PathSetGeometry.lean b/lean/PathMapModel/PathSetGeometry.lean new file mode 100644 index 00000000..22c6cd6d --- /dev/null +++ b/lean/PathMapModel/PathSetGeometry.lean @@ -0,0 +1,153 @@ +import PathMapModel.PathSetProofs + +/-! Geometry of divergence witnesses. These proofs are independent of finite +law batteries and hold for arbitrary paths and finite spaces. -/ +namespace PathMapModel.Path + +theorem divergence_split (x y p : Path) : divergence x y = some p ↔ + ∃ a b xs ys, a ≠ b ∧ x = p ++ a :: xs ∧ y = p ++ b :: ys := by + induction p generalizing x y with + | nil => + cases x with + | nil => simp [divergence] + | cons a xs => + cases y with + | nil => simp [divergence] + | cons b ys => + by_cases h : a = b + · subst b + simp [divergence, Option.map_eq_some_iff] + · simp [divergence, h] + | cons c p ih => + cases x with + | nil => simp [divergence] + | cons a xs => + cases y with + | nil => simp [divergence] + | cons b ys => + by_cases h : a = b + · subst b + simp only [divergence, beq_self_eq_true, if_true, Option.map_eq_some_iff, + List.cons_append, List.cons.injEq] + constructor + · rintro ⟨q, hq, hac, rfl⟩ + obtain ⟨d, e, ds, es, hde, hx, hy⟩ := (ih xs ys).mp hq + subst c + exact ⟨d, e, ds, es, hde, ⟨rfl, hx⟩, ⟨rfl, hy⟩⟩ + · rintro ⟨d, e, ds, es, hde, ⟨hac, hx⟩, ⟨_, hy⟩⟩ + exact ⟨p, (ih xs ys).mpr ⟨d, e, ds, es, hde, hx, hy⟩, hac, rfl⟩ + · simp [divergence, h, List.cons_append, List.cons.injEq] + grind + +theorem divergence_length_left {x y p : Path} (h : divergence x y = some p) : + p.length < x.length := by + obtain ⟨a, b, xs, ys, _, rfl, _⟩ := (divergence_split x y p).mp h + simp + +theorem divergence_length_right {x y p : Path} (h : divergence x y = some p) : + p.length < y.length := divergence_length_left ((divergence_comm y x).trans h) + +theorem proper_prefix_split {p q : Path} (hp : (p ≼ q) = true) (hn : p ≠ q) : + ∃ a xs, q = p ++ a :: xs := by + obtain ⟨r, rfl⟩ := (prefix_iff_extension p q).mp hp + cases r with + | nil => simp at hn + | cons a xs => exact ⟨a, xs, rfl⟩ +end PathMapModel.Path + +namespace PathMapModel.PathSpace + +/-- Next byte a at p leads to at least one valued member of the space. -/ +def Child (s : PathSpace) (p : Path) (a : UInt8) : Prop := + ∃ tail, p ++ a :: tail ∈ s + +theorem mem_divergence_children (a b : PathSpace) (p : Path) : + p ∈ divergence a b ↔ ∃ x y, x ≠ y ∧ Child a p x ∧ Child b p y := by + rw [mem_divergence] + constructor + · rintro ⟨u, hu, v, hv, h⟩ + obtain ⟨x,y,xs,ys,hxy,rfl,rfl⟩ := (Path.divergence_split u v p).mp h + exact ⟨x,y,hxy,⟨xs,hu⟩,⟨ys,hv⟩⟩ + · rintro ⟨x,y,hxy,⟨xs,hx⟩,⟨ys,hy⟩⟩ + exact ⟨_,hx,_,hy,(Path.divergence_split _ _ _).mpr ⟨x,y,xs,ys,hxy,rfl,rfl⟩⟩ + +theorem branch_sandwich_lower {a b : PathSpace} {p : Path} + (ha : p ∈ branches a) (hb : p ∈ branches b) : p ∈ divergence a b := by + obtain ⟨x,y,hxy,hx,hy⟩ := (mem_divergence_children a a p).mp ha + obtain ⟨u,v,huv,hu,hv⟩ := (mem_divergence_children b b p).mp hb + apply (mem_divergence_children a b p).mpr + by_cases h : x = u + · exact ⟨y,u,by grind,hy,hu⟩ + · exact ⟨x,u,h,hx,hu⟩ + +theorem divergence_four_point_exchange {a b c f : PathSpace} {p : Path} + (hab : p ∈ divergence a b) (hcf : p ∈ divergence c f) : + (p ∈ divergence a c ∧ p ∈ divergence b f) ∨ + (p ∈ divergence a f ∧ p ∈ divergence b c) := by + obtain ⟨w,x,hwx,hw,hx⟩ := (mem_divergence_children a b p).mp hab + obtain ⟨y,z,hyz,hy,hz⟩ := (mem_divergence_children c f p).mp hcf + by_cases hwy : w = y + · exact Or.inr ⟨(mem_divergence_children a f p).mpr ⟨w,z,by grind,hw,hz⟩, + (mem_divergence_children b c p).mpr ⟨x,y,by grind,hx,hy⟩⟩ + · by_cases hxz : x = z + · exact Or.inr ⟨(mem_divergence_children a f p).mpr ⟨w,z,by grind,hw,hz⟩, + (mem_divergence_children b c p).mpr ⟨x,y,by grind,hx,hy⟩⟩ + · exact Or.inl ⟨(mem_divergence_children a c p).mpr ⟨w,y,hwy,hw,hy⟩, + (mem_divergence_children b f p).mpr ⟨x,z,hxz,hx,hz⟩⟩ + +theorem divergence_same_side_bound {a b : PathSpace} {p : Path} + (h : p ∈ divergence a (divergence a b)) : + p ∈ branches a ∧ p ∈ divergence a b := by + have h' := divergence_nested_bound ((divergence_comm a (divergence a b) p).mp h) + exact ⟨h'.1, (divergence_comm b a p).mp h'.2⟩ + +theorem divergence_output_closed {a b : PathSpace} {p : Path} + (h : p ∈ branches (divergence a b)) : p ∈ divergence a b := by + have ha := (divergence_nested_bound h).1 + exact (divergence_same_side_bound ha).2 + +theorem divergence_output_branches {a b : PathSpace} {p : Path} + (h : p ∈ branches (divergence a b)) : p ∈ branches a ∧ p ∈ branches b := by + have hs := divergence_nested_bound h + exact ⟨(divergence_same_side_bound hs.1).1, + (divergence_nested_bound ((divergence_comm b (divergence a b) p).mp hs.2)).2⟩ + +theorem mem_interior (s : PathSpace) (p : Path) : + p ∈ interior s ↔ p ∈ s ∧ ∃ q ∈ s, p ≠ q ∧ (p ≼ q) = true := by + change p ∈ diff s (hull s) ↔ _ + rw [mem_diff, mem_hull] + constructor + · rintro ⟨hp,hn⟩ + refine ⟨hp, ?_⟩ + by_cases h : ∃ q ∈ s, p ≠ q ∧ (p ≼ q) = true + · exact h + · exfalso + apply hn + refine ⟨hp, fun q hq hne => ?_⟩ + cases he : (p ≼ q) with + | false => rfl + | true => exact False.elim (h ⟨q,hq,Ne.symm hne,he⟩) + · rintro ⟨hp,q,hq,hne,hpq⟩ + refine ⟨hp, fun hh => ?_⟩ + have hf := hh.2 q hq (Ne.symm hne) + simp [hpq] at hf + +/-- Exact nested law: original branching intersected with interior output. -/ +theorem divergence_nested_exact (a b : PathSpace) (p : Path) : + p ∈ divergence a (divergence a b) ↔ p ∈ branches a ∧ p ∈ interior (divergence a b) := by + constructor + · intro h + have hb := divergence_same_side_bound h + obtain ⟨u,hu,q,hq,hd⟩ := (mem_divergence _ _ _).mp h + have hpq := Path.divergence_prefix_left ((Path.divergence_comm q u).trans hd) + have hlen := Path.divergence_length_right hd + exact ⟨hb.1, (mem_interior _ _).mpr ⟨hb.2,q,hq,by intro he; subst q; omega,hpq⟩⟩ + · rintro ⟨hb,hi⟩ + obtain ⟨_,q,hq,hne,hpq⟩ := (mem_interior _ _).mp hi + obtain ⟨z,tail,rfl⟩ := Path.proper_prefix_split hpq hne + obtain ⟨x,y,hxy,hx,hy⟩ := (mem_divergence_children a a p).mp hb + apply (mem_divergence_children a (divergence a b) p).mpr + by_cases hxz : x = z + · exact ⟨y,z,by grind,hy,⟨tail,hq⟩⟩ + · exact ⟨x,z,hxz,hx,⟨tail,hq⟩⟩ +end PathMapModel.PathSpace diff --git a/lean/PathMapModel/PathSetLCP.lean b/lean/PathMapModel/PathSetLCP.lean new file mode 100644 index 00000000..7c709aeb --- /dev/null +++ b/lean/PathMapModel/PathSetLCP.lean @@ -0,0 +1,157 @@ +import PathMapModel.PathSetMasks + +namespace PathMapModel.Path + +theorem lcp_comm (x y : Path) : lcp x y = lcp y x := by + induction x generalizing y with + | nil => cases y <;> rfl + | cons a xs ih => + cases y with + | nil => rfl + | cons b ys => + by_cases h : a = b + · subst b; simp [lcp,ih] + · simp [lcp,h,Ne.symm h] + +theorem prefix_lcp (p x y : Path) : + (p ≼ lcp x y) = true ↔ (p ≼ x) = true ∧ (p ≼ y) = true := by + induction p generalizing x y with + | nil => simp [isPrefixOf] + | cons c ps ih => + cases x with + | nil => cases y <;> simp [lcp,isPrefixOf] + | cons a xs => + cases y with + | nil => simp [lcp,isPrefixOf] + | cons b ys => + by_cases h : a = b + · subst b; simp [lcp,isPrefixOf,ih]; grind + · simp [lcp,isPrefixOf,h]; grind + +theorem lcp_prefix_left (x y : Path) : (lcp x y ≼ x) = true := + ((prefix_lcp (lcp x y) x y).mp (prefix_self _)).1 + +theorem lcp_prefix_right (x y : Path) : (lcp x y ≼ y) = true := + ((prefix_lcp (lcp x y) x y).mp (prefix_self _)).2 + +theorem lcp_of_prefix {x y : Path} (h : (x ≼ y) = true) : lcp x y = x := + prefix_antisymm (lcp_prefix_left x y) ((prefix_lcp x x y).mpr ⟨prefix_self x,h⟩) + +@[simp] theorem lcp_self (x : Path) : lcp x x = x := lcp_of_prefix (prefix_self x) + +theorem lcp_assoc (x y z : Path) : lcp (lcp x y) z = lcp x (lcp y z) := by + apply prefix_antisymm + · have h := prefix_self (lcp (lcp x y) z) + simp only [prefix_lcp] at h ⊢ + exact ⟨h.1.1,h.1.2,h.2⟩ + · have h := prefix_self (lcp x (lcp y z)) + simp only [prefix_lcp] at h ⊢ + exact ⟨⟨h.1,h.2.1⟩,h.2.2⟩ + +theorem divergence_or_comparable (x y : Path) : + divergence x y = some (lcp x y) ∨ (x ≼ y) = true ∨ (y ≼ x) = true := by + induction x generalizing y with + | nil => exact Or.inr (Or.inl rfl) + | cons a xs ih => + cases y with + | nil => exact Or.inr (Or.inr rfl) + | cons b ys => + by_cases h : a = b + · subst b + simpa [divergence,lcp,isPrefixOf] using ih ys + · exact Or.inl (by simp [divergence,lcp,h]) + +theorem divergence_lcp {x y p : Path} (h : divergence x y = some p) : lcp x y = p := by + induction x generalizing y p with + | nil => simp at h + | cons a xs ih => + cases y with + | nil => simp at h + | cons b ys => + by_cases hab : a = b + · subst b + simp only [divergence,beq_self_eq_true,if_true,Option.map_eq_some_iff] at h + obtain ⟨q,hq,rfl⟩ := h + simp [lcp,ih hq] + · simpa [divergence,lcp,hab] using h + +theorem lcp_cases (x y p : Path) : lcp x y = p ↔ + divergence x y = some p ∨ (p = x ∧ (x ≼ y) = true) ∨ (p = y ∧ (y ≼ x) = true) := by + constructor + · rintro rfl + rcases divergence_or_comparable x y with h | h | h + · exact Or.inl h + · exact Or.inr (Or.inl ⟨lcp_of_prefix h,h⟩) + · exact Or.inr (Or.inr ⟨(lcp_comm x y).trans (lcp_of_prefix h),h⟩) + · rintro (h | ⟨rfl,h⟩ | ⟨rfl,h⟩) + · exact divergence_lcp h + · exact lcp_of_prefix h + · exact (lcp_comm _ _).trans (lcp_of_prefix h) +end PathMapModel.Path + +namespace PathMapModel.PathSpace + +theorem mem_lcpProduct (a b : PathSpace) (p : Path) : + p ∈ lcpProduct a b ↔ ∃ x ∈ a, ∃ y ∈ b, Path.lcp x y = p := by + simp [lcpProduct,List.mem_flatMap] + +theorem lcp_correction (a b : PathSpace) (p : Path) : + p ∈ lcpProduct a b ↔ p ∈ divergence a b ∨ p ∈ live a b ∨ p ∈ live b a := by + simp only [mem_lcpProduct,mem_divergence,mem_live,Path.lcp_cases] + constructor + · rintro ⟨x,hx,y,hy,h⟩ + rcases h with hd | ⟨rfl,hp⟩ | ⟨rfl,hp⟩ + · exact Or.inl ⟨x,hx,y,hy,hd⟩ + · exact Or.inr (Or.inl ⟨hx,y,hy,hp⟩) + · exact Or.inr (Or.inr ⟨hy,x,hx,hp⟩) + · rintro (⟨x,hx,y,hy,hd⟩ | ⟨hx,y,hy,hp⟩ | ⟨hy,x,hx,hp⟩) + · exact ⟨x,hx,y,hy,Or.inl hd⟩ + · exact ⟨p,hx,y,hy,Or.inr (Or.inl ⟨rfl,hp⟩)⟩ + · exact ⟨x,hx,p,hy,Or.inr (Or.inr ⟨rfl,hp⟩)⟩ + +theorem lcp_diagonal (a : PathSpace) (p : Path) : + p ∈ lcpProduct a a ↔ p ∈ completion a := by + rw [lcp_correction] + have hl : p ∈ live a a ↔ p ∈ a := by + rw [mem_live]; exact ⟨And.left,fun h => ⟨h,p,h,Path.prefix_self p⟩⟩ + simp only [completion,union,List.mem_append,hl,branches] + grind + +theorem lcp_symmetry (a b : PathSpace) (p : Path) : + p ∈ lcpProduct a b ↔ p ∈ lcpProduct b a := by + simp only [mem_lcpProduct] + constructor <;> rintro ⟨x,hx,y,hy,hd⟩ <;> + exact ⟨y,hy,x,hx,(Path.lcp_comm _ _).trans hd⟩ + +theorem lcp_associativity (a b c : PathSpace) (p : Path) : + p ∈ lcpProduct (lcpProduct a b) c ↔ p ∈ lcpProduct a (lcpProduct b c) := by + simp only [mem_lcpProduct] + constructor + · rintro ⟨xy,⟨x,hx,y,hy,rfl⟩,z,hz,hd⟩ + exact ⟨x,hx,Path.lcp y z,⟨y,hy,z,hz,rfl⟩,(Path.lcp_assoc x y z).symm.trans hd⟩ + · rintro ⟨x,hx,yz,⟨y,hy,z,hz,rfl⟩,hd⟩ + exact ⟨Path.lcp x y,⟨x,hx,y,hy,rfl⟩,z,hz,(Path.lcp_assoc x y z).trans hd⟩ + +theorem lcp_bilinearity (a b c : PathSpace) : + lcpProduct (union a b) c = union (lcpProduct a c) (lcpProduct b c) := by + simp [lcpProduct,union] + +theorem lcp_output_covered {a b : PathSpace} {p : Path} + (h : p ∈ lcpProduct a b) : ∃ x ∈ a, (p ≼ x) = true := by + obtain ⟨x,hx,y,_,rfl⟩ := (mem_lcpProduct _ _ _).mp h + exact ⟨x,hx,Path.lcp_prefix_left x y⟩ + +theorem lcp_output_completion (a b : PathSpace) (p : Path) : + p ∈ completion (lcpProduct a b) ↔ p ∈ lcpProduct a b := by + simp only [completion,union,List.mem_append] + constructor + · rintro (h | h) + · exact h + · have h1 : p ∈ divergence a (lcpProduct a b) := + divergence_covered_mono (fun _ h => lcp_output_covered h) p h + have h2 : p ∈ divergence b a := divergence_covered_mono + (a := lcpProduct a b) (fun q h => lcp_output_covered ((lcp_symmetry a b q).mp h)) p + ((divergence_comm _ _ p).mp h1) + exact (lcp_correction a b p).mpr (Or.inl ((divergence_comm _ _ p).mp h2)) + · exact Or.inl +end PathMapModel.PathSpace diff --git a/lean/PathMapModel/PathSetLaws.lean b/lean/PathMapModel/PathSetLaws.lean new file mode 100644 index 00000000..71a10868 --- /dev/null +++ b/lean/PathMapModel/PathSetLaws.lean @@ -0,0 +1,167 @@ +import PathMapModel.PathSets + +/-! Named decidable laws for property tests. `PathSetChecks` evaluates small +fixtures; the `PathSetProofs` through `PathSetCertificates` modules prove the +corresponding universally quantified statements. -/ +namespace PathMapModel.PathSetLaws +open PathSpace +abbrev Checks := List (String × Bool) +def D (a b : PathSpace) := normalize (divergence a b) +private def Br (a : PathSpace) := D a a +private def I (a : PathSpace) := diff a (hull a) +private def C (a : PathSpace) := union a (Br a) +private def M (a b : PathSpace) := normalize (lcpProduct a b) +private def E : PathSpace := [[]] +private def implies (a b : Bool) := !a || b +private def eq := PathSpace.equiv +private def sub := PathSpace.subset + +def unary (a : PathSpace) : Checks := + let br := Br a + [ ("diagonal", eq (D a a) br), + ("empty_left", eq (D [] a) []), + ("empty_right", eq (D a []) []), + ("epsilon_left", eq (D E a) []), + ("epsilon_right", eq (D a E) []), + ("branch_completion", eq (Br (C a)) br), + ("completion_idempotent", eq (C (C a)) (C a)), + ("branch_hull", eq (Br (hull a)) br), + ("branch_epsilon", eq (Br (union a E)) br), + ("branch_second_subset", sub (Br br) br), + ("interior_branches", eq (D a br) (I br)), + ("basis_subset", sub (basis a) a), + ("hull_subset", sub (hull a) a), + ("basis_idempotent", eq (basis (basis a)) (basis a)), + ("hull_idempotent", eq (hull (hull a)) (hull a)), + ("basis_of_hull", eq (basis (hull a)) (hull a)), + ("hull_of_basis", eq (hull (basis a)) (basis a)), + ("basis_antichain", prefixFree (basis a)), + ("hull_antichain", prefixFree (hull a)), + ("basis_nonempty", (basis a).isEmpty == a.isEmpty), + ("hull_nonempty", (hull a).isEmpty == a.isEmpty), + ("basis_covers", covers a (hull a) && covers (basis a) a), + ("basis_recursive", eq (basisRec (height a + 1) a) (basis a)), + ("hull_recursive", eq (hullRec (height a + 1) a) (hull a)), + ("branch_recursive", eq (divergenceRec (height a + 1) a a) br), + ("maximal_branch_count", decide (count (hull br) <= count (hull a) / 2)), + ("no_nonempty_branch_fixed_point", implies (!a.isEmpty) (!eq br a)), + ("branch_depth_nilpotence", eq (branchIter a (height a + 1)) []) ] + +def binary (a b : PathSpace) : Checks := + let x := D a b + let ha := hull a + let hb := hull b + let zero := a.isEmpty || b.isEmpty || + (count ha == 1 && hb.all (fun q => ha.all (· ≼ q))) || + (count hb == 1 && ha.all (fun p => hb.all (· ≼ p))) + let fork : PathSpace := [[0], [1]] + [ ("symmetry", eq x (D b a)), + ("terminal_invariance", eq (D (union a E) (union b E)) x), + ("hull_invariance", eq (D ha hb) x), + ("completion_invariance", eq (D (C a) (C b)) x), + ("branch_union", eq (Br (union a b)) (union (union (Br a) (Br b)) x)), + ("branch_intersection_lower", sub (Br (inter a b)) (inter (Br a) (Br b))), + ("branch_sandwich_lower", sub (inter (Br a) (Br b)) x), + ("branch_sandwich_upper", sub x (Br (union a b))), + ("output_completion", eq (C x) x), + ("absorbed_branch_marks", eq (Br (union a x)) (Br a)), + ("nested_exact", eq (D a x) (inter (Br a) (I x))), + ("interior_exact", eq (D (union a b) x) (I x)), + ("interior_attribution", sub (I x) (union (Br a) (Br b))), + ("output_branches", sub (Br x) (inter x (inter (Br a) (Br b)))), + ("first_divergence", implies (!x.isEmpty) (eq (basis x) [commonPrefix (union ha hb)])), + ("zero_criterion", x.isEmpty == zero), + ("root_heads", eq (D (head a) (head b)) (inter x E)), + ("output_heads", sub (head x) (inter (head a) (head b))), + ("tails_bound", sub (tails x) (D (tails a) (tails b))), + ("recursive_divergence", eq (divergenceRec (min (height a) (height b) + 1) a b) x), + ("live_recursive", eq (liveRec (height a + 1) a b) (live a b)), + ("output_cardinality", decide (count x <= count (hull (union a b)) - 1)), + ("output_hull_cardinality", decide (count (hull x) <= min (count ha) (count hb))), + ("output_depth", implies (!x.isEmpty) (height x < min (height a) (height b))), + ("output_covered", covers x a && covers x b), + ("fork_completion", eq (Br (product a fork)) (C a)), + ("fork_lcp", eq (D (product a fork) (product b fork)) (M a b)), + ("lcp_correction", eq (M a b) (union x (union (live a b) (live b a)))), + ("lcp_diagonal", eq (M a a) (C a)), + ("lcp_symmetry", eq (M a b) (M b a)), + ("lcp_output_completion", eq (C (M a b)) (M a b)), + ("range_realization", eq (Br (product (C a) fork)) (C a)), + ("basis_union", eq (basis (union a b)) (basis (union (basis a) (basis b)))), + ("hull_union", eq (hull (union a b)) (hull (union ha hb))), + ("restriction_basis_mask", eq (restrict a b) (restrict a (basis b))) ] + +def ternary (a b c : PathSpace) : Checks := + [ ("left_union", eq (D (union a b) c) (union (D a c) (D b c))), + ("right_union", eq (D a (union b c)) (union (D a b) (D a c))), + ("intersection_bound", sub (D (inter a b) c) (inter (D a c) (D b c))), + ("difference_lower", sub (diff (D a c) (D b c)) (D (diff a b) c)), + ("difference_upper", sub (D (diff a b) c) (D a c)), + ("symmetric_difference_bound", sub (symDiff (D a c) (D b c)) (D (symDiff a b) c)), + ("monotonicity", implies (sub a b) (sub (D a c) (D b c))), + ("prefix_extension_monotonicity", implies (covers a b) (sub (D a c) (D b c))), + ("covered_mark_invariance", implies (covers b a) (eq (D (union a b) c) (D a c))), + ("nested_absorption", sub (D (D a b) c) (inter (D a c) (D b c))), + ("witness_absorption", eq (D (union a (D a b)) c) (D a c)), + ("branch_probe_exchange", sub (inter (D a b) (Br c)) (inter (D a c) (D b c))), + ("lcp_associativity", eq (M (M a b) c) (M a (M b c))), + ("lcp_bilinearity", eq (M (union a b) c) (union (M a c) (M b c))), + ("one_mask", eq (D (restrict a c) b) (union (restrict (D a b) c) (D (live c a) b))), + ("same_mask", eq (D (restrict a c) (restrict b c)) + (union (restrict (D a b) c) (D (live c a) (live c b)))), + ("filter_partition", eq (D a b) (union (D (restrict a c) b) (D (raffinate a c) b))), + ("common_prefix_code", implies (prefixFree a && !b.isEmpty && !c.isEmpty) + (eq (D (product a b) (product a c)) (union (Br a) (product a (D b c))))) ] + +/-- The proper-prefix contributions in the full four-factor product expansion. -/ +def leftOverlap (a b x y : PathSpace) : PathSpace := + properOverlap a b fun p r => wrap p (D x (wrap r y)) + +def rightOverlap (a b x y : PathSpace) : PathSpace := + properOverlap b a fun p r => wrap p (D (wrap r x) y) + +def quaternary (a b c f : PathSpace) : Checks := + let x := D a b + let pa := live c a + let qb := live f b + [ ("four_point_absorption", sub (D (D a b) (D c f)) + (inter (inter (D a c) (D a f)) (inter (D b c) (D b f)))), + ("four_point_exchange", sub (inter (D a b) (D c f)) + (union (inter (D a c) (D b f)) (inter (D a f) (D b c)))), + ("incremental_update", eq (D (union a c) (union b f)) + (union (union x (D c b)) (union (D a f) (D c f)))), + ("two_masks", eq (D (restrict a c) (restrict b f)) + (union (union (restrict (restrict x c) f) (restrict (D a qb) c)) + (union (restrict (D pa b) f) (D pa qb)))), + ("raffination_bound", sub (D (raffinate a c) (raffinate b f)) (raffinate x (union c f))), + ("general_product", eq (D (product a c) (product b f)) + (if c.isEmpty || f.isEmpty then [] else + union (union x (product (inter a b) (D c f))) + (union (leftOverlap a b c f) (rightOverlap a b c f)))), + ("prefix_free_product", implies (prefixFree (union a b) && !c.isEmpty && !f.isEmpty) + (eq (D (product a c) (product b f)) (union x (product (inter a b) (D c f))))) ] + +def pathLaws (a b : PathSpace) (p : Path) : Checks := + let chain := D [p] b + [ ("wrap", eq (D (wrap p a) (wrap p b)) (wrap p (D a b))), + ("unwrap", eq (D (unwrap a p) (unwrap b p)) (unwrap (D a b) p)), + ("single_prefix_restriction", eq (D (restrict a [p]) (restrict b [p])) (restrict (D a b) [p])), + ("singleton_chain", eq (Br chain) []), + ("singleton_bound", decide (count chain <= min p.length (count (hull b)))), + ("singleton_existing_branches", sub (I chain) (Br b)), + ("singleton_branch_update", decide (count (diff (Br (union b [p])) (Br b)) <= 1)), + ("singleton_divergence_update", decide (count (diff (D (union a [p]) b) (D a b)) <= min p.length (count (hull b)))) ] + +def powers (a : PathSpace) (m n : Nat) : Checks := + [ ("prefix_code_powers", implies (prefixFree a) + (eq (D (power a m) (power a n)) + ((List.range (min m n)).flatMap fun i => product (power a i) (Br a)))), + ("branch_leaf_bound", implies (!(branchIter a n).isEmpty) (2^n <= count (hull a))) ] + +/-- Assumptions are executable guards, so unconstrained inputs are safe to test. -/ +def all (a b c f : PathSpace) : Checks := + unary a ++ binary a b ++ ternary a b c ++ quaternary a b c f ++ + (pathLaws a b []) ++ (pathLaws a b [0]) ++ (pathLaws a b [0,1,0]) + +def failures (checks : Checks) : List String := (checks.filter (! ·.2)).map (·.1) +end PathMapModel.PathSetLaws diff --git a/lean/PathMapModel/PathSetMasks.lean b/lean/PathMapModel/PathSetMasks.lean new file mode 100644 index 00000000..b3989e94 --- /dev/null +++ b/lean/PathMapModel/PathSetMasks.lean @@ -0,0 +1,150 @@ +import PathMapModel.PathSetExtrema + +namespace PathMapModel.Path +/-- Cutting a divergent witness either reaches the divergence or still diverges. -/ +theorem divergence_cut {x y p r : Path} (hr : (r ≼ x) = true) + (hd : divergence x y = some p) : (r ≼ p) = true ∨ divergence r y = some p := by + induction x generalizing y p r with + | nil => simp at hd + | cons a xs ih => + cases r with + | nil => exact Or.inl rfl + | cons c rs => + simp only [isPrefixOf, Bool.and_eq_true, beq_iff_eq] at hr + obtain ⟨rfl,hr⟩ := hr + cases y with + | nil => simp at hd + | cons b ys => + by_cases hab : c = b + · subst b + simp only [divergence, beq_self_eq_true, if_true, Option.map_eq_some_iff] at hd + obtain ⟨q,hq,rfl⟩ := hd + rcases ih hr hq with h | h + · exact Or.inl (by simpa [isPrefixOf] using h) + · exact Or.inr (by simp [divergence,h]) + · simp [divergence,hab] at hd + subst p + exact Or.inr (by simp [divergence,hab]) +end PathMapModel.Path + +namespace PathMapModel.PathSpace + +theorem mem_live (m a : PathSpace) (p : Path) : + p ∈ live m a ↔ p ∈ m ∧ ∃ q ∈ a, (p ≼ q) = true := by + simp [live, List.any_eq_true] + +theorem mem_raffinate (a m : PathSpace) (p : Path) : + p ∈ raffinate a m ↔ p ∈ a ∧ ∀ q ∈ m, (q ≼ p) = false := by + simp only [raffinate, mem_diff, mem_restrict] + constructor + · rintro ⟨hp,hn⟩ + refine ⟨hp, fun q hq => ?_⟩ + cases he : (q ≼ p) with + | false => exact he + | true => exact False.elim (hn ⟨hp,q,hq,he⟩) + · rintro ⟨hp,hn⟩ + exact ⟨hp, fun ⟨_,q,hq,he⟩ => by simpa [he] using hn q hq⟩ + +theorem divergence_one_mask (a b m : PathSpace) (p : Path) : + p ∈ divergence (restrict a m) b ↔ + p ∈ restrict (divergence a b) m ∨ p ∈ divergence (live m a) b := by + constructor + · intro h + obtain ⟨x,hx,y,hy,hd⟩ := (mem_divergence _ _ _).mp h + obtain ⟨hx,r,hr,hrx⟩ := (mem_restrict _ _ _).mp hx + rcases Path.divergence_cut hrx hd with hrp | hdr + · exact Or.inl ((mem_restrict _ _ _).mpr + ⟨(mem_divergence _ _ _).mpr ⟨x,hx,y,hy,hd⟩,r,hr,hrp⟩) + · exact Or.inr ((mem_divergence _ _ _).mpr + ⟨r,(mem_live _ _ _).mpr ⟨hr,x,hx,hrx⟩,y,hy,hdr⟩) + · rintro (h | h) + · obtain ⟨hp,r,hr,hrp⟩ := (mem_restrict _ _ _).mp h + obtain ⟨x,hx,y,hy,hd⟩ := (mem_divergence _ _ _).mp hp + exact (mem_divergence _ _ _).mpr ⟨x,(mem_restrict _ _ _).mpr + ⟨hx,r,hr,Path.prefix_trans hrp (Path.divergence_prefix_left hd)⟩,y,hy,hd⟩ + · apply divergence_covered_mono (a := live m a) (b := restrict a m) ?_ p h + intro r hr + obtain ⟨hr,x,hx,hrx⟩ := (mem_live _ _ _).mp hr + exact ⟨x,(mem_restrict _ _ _).mpr ⟨hx,r,hr,hrx⟩,hrx⟩ + +theorem divergence_two_masks (a b m n : PathSpace) (p : Path) : + p ∈ divergence (restrict a m) (restrict b n) ↔ + p ∈ restrict (restrict (divergence a b) m) n ∨ + p ∈ restrict (divergence a (live n b)) m ∨ + p ∈ restrict (divergence (live m a) b) n ∨ + p ∈ divergence (live m a) (live n b) := by + rw [divergence_one_mask] + have hb := divergence_one_mask b a n p + simp only [mem_restrict] at hb + rw [divergence_comm (restrict b n) a, divergence_comm b a, + divergence_comm (live n b) a] at hb + have hc := divergence_one_mask b (live m a) n p + simp only [mem_restrict] at hc + rw [divergence_comm (restrict b n) (live m a), divergence_comm b (live m a), + divergence_comm (live n b) (live m a)] at hc + simp only [mem_restrict] at hb hc ⊢ + grind + +theorem divergence_same_mask (a b m : PathSpace) (p : Path) : + p ∈ divergence (restrict a m) (restrict b m) ↔ + p ∈ restrict (divergence a b) m ∨ p ∈ divergence (live m a) (live m b) := by + rw [divergence_two_masks] + constructor + · rintro (h | h | h | h) + · exact Or.inl ((mem_restrict _ _ _).mp h).1 + · obtain ⟨hd,r,hr,hrp⟩ := (mem_restrict _ _ _).mp h + have he : p ∈ divergence a b := by + apply (divergence_comm b a p).mp + apply divergence_covered_mono (a := live m b) (fun q hq => ((mem_live _ _ _).mp hq).2) p + exact (divergence_comm a (live m b) p).mp hd + exact Or.inl ((mem_restrict _ _ _).mpr ⟨he,r,hr,hrp⟩) + · obtain ⟨hd,r,hr,hrp⟩ := (mem_restrict _ _ _).mp h + have he := divergence_covered_mono (a := live m a) (b := a) + (fun q hq => ((mem_live _ _ _).mp hq).2) p hd + exact Or.inl ((mem_restrict _ _ _).mpr ⟨he,r,hr,hrp⟩) + · exact Or.inr h + · rintro (h | h) + · exact Or.inl ((mem_restrict _ _ _).mpr ⟨h,((mem_restrict _ _ _).mp h).2⟩) + · exact Or.inr (Or.inr (Or.inr h)) + +theorem divergence_single_mask (a b : PathSpace) (q p : Path) : + p ∈ divergence (restrict a [q]) (restrict b [q]) ↔ + p ∈ restrict (divergence a b) [q] := by + rw [divergence_same_mask] + have hn : p ∉ divergence (live [q] a) (live [q] b) := by + intro h + obtain ⟨x,hx,y,hy,hd⟩ := (mem_divergence _ _ _).mp h + have hxq := ((mem_live _ _ _).mp hx).1 + have hyq := ((mem_live _ _ _).mp hy).1 + simp only [List.mem_singleton] at hxq hyq + subst x; subst y; simp at hd + exact or_iff_left hn + +theorem divergence_raffination {a b m n : PathSpace} {p : Path} + (h : p ∈ divergence (raffinate a m) (raffinate b n)) : + p ∈ raffinate (divergence a b) (union m n) := by + obtain ⟨x,hx,y,hy,hd⟩ := (mem_divergence _ _ _).mp h + obtain ⟨hx,hm⟩ := (mem_raffinate _ _ _).mp hx + obtain ⟨hy,hn⟩ := (mem_raffinate _ _ _).mp hy + refine (mem_raffinate _ _ _).mpr ⟨(mem_divergence _ _ _).mpr ⟨x,hx,y,hy,hd⟩, ?_⟩ + intro q hq + cases he : (q ≼ p) with + | false => rfl + | true => + simp only [union, List.mem_append] at hq + rcases hq with hq | hq + · have hqx := Path.prefix_trans he (Path.divergence_prefix_left hd) + simpa [hqx] using hm q hq + · have hqy := Path.prefix_trans he (Path.divergence_prefix_left ((Path.divergence_comm y x).trans hd)) + simpa [hqy] using hn q hq + +theorem divergence_filter_partition (a b m : PathSpace) (p : Path) : + p ∈ divergence a b ↔ + p ∈ union (divergence (restrict a m) b) (divergence (raffinate a m) b) := by + rw [← divergence_union_left] + apply divergence_congr _ (fun _ => Iff.rfl) p + intro q + simp only [union, List.mem_append, raffinate, mem_diff] + have hs : q ∈ restrict a m → q ∈ a := fun h => ((mem_restrict _ _ _).mp h).1 + grind +end PathMapModel.PathSpace diff --git a/lean/PathMapModel/PathSetPowers.lean b/lean/PathMapModel/PathSetPowers.lean new file mode 100644 index 00000000..edc66ea3 --- /dev/null +++ b/lean/PathMapModel/PathSetPowers.lean @@ -0,0 +1,93 @@ +import PathMapModel.PathSetProduct + +namespace PathMapModel.PathSpace + +theorem product_associative (a b c : PathSpace) (p : Path) : + p ∈ product (product a b) c ↔ p ∈ product a (product b c) := by + simp only [mem_product] + constructor + · rintro ⟨xy,⟨x,hx,y,hy,rfl⟩,z,hz,rfl⟩ + exact ⟨x,hx,y++z,⟨y,hy,z,hz,rfl⟩,by simp [List.append_assoc]⟩ + · rintro ⟨x,hx,yz,⟨y,hy,z,hz,rfl⟩,rfl⟩ + exact ⟨x++y,⟨x,hx,y,hy,rfl⟩,z,hz,by simp [List.append_assoc]⟩ + +theorem product_congr {a b c f : PathSpace} + (ha : ∀ p, p ∈ a ↔ p ∈ c) (hb : ∀ p, p ∈ b ↔ p ∈ f) (p : Path) : + p ∈ product a b ↔ p ∈ product c f := by simp only [mem_product,ha,hb] + +theorem product_nonempty {a b : PathSpace} (ha : a ≠ []) (hb : b ≠ []) : product a b ≠ [] := by + cases a with + | nil => exact False.elim (ha rfl) + | cons x xs => + cases b with + | nil => exact False.elim (hb rfl) + | cons y ys => + apply List.ne_nil_of_mem (a := x++y) + exact (mem_product _ _ _).mpr ⟨x,by simp,y,by simp,rfl⟩ + +theorem power_nonempty {a : PathSpace} (ha : a ≠ []) (n : Nat) : power a n ≠ [] := by + induction n with + | zero => simp [power] + | succ n ih => exact product_nonempty ha ih + +def powerSum (a : PathSpace) (n : Nat) : PathSpace := + (List.range n).flatMap fun i => product (power a i) (branches a) + +theorem powerSum_succ (a : PathSpace) (n : Nat) (p : Path) : + p ∈ powerSum a (n+1) ↔ p ∈ branches a ∨ p ∈ product a (powerSum a n) := by + unfold powerSum + rw [List.range_succ_eq_map] + simp only [List.flatMap_cons,List.mem_append,List.mem_flatMap,List.mem_map,power] + have hzero : ∀ s : PathSpace, product [[]] s = s := by intro s; simp [product] + rw [hzero] + constructor + · rintro (h | ⟨i,⟨j,hj,rfl⟩,hp⟩) + · exact Or.inl h + · have hh := (product_associative a (power a j) (branches a) p).mp hp + obtain ⟨x,hx,y,hy,rfl⟩ := (mem_product _ _ _).mp hh + exact Or.inr ((mem_product _ _ _).mpr ⟨x,hx,y,List.mem_flatMap.mpr ⟨j,hj,hy⟩,rfl⟩) + · rintro (h | h) + · exact Or.inl h + · obtain ⟨x,hx,y,hy,rfl⟩ := (mem_product _ _ _).mp h + obtain ⟨i,hi,hyi⟩ := List.mem_flatMap.mp hy + exact Or.inr ⟨i+1,⟨i,hi,rfl⟩,(product_associative _ _ _ _).mpr + ((mem_product _ _ _).mpr ⟨x,hx,y,hyi,rfl⟩)⟩ + +theorem prefix_code_powers {a : PathSpace} (ha : Antichain a) (m n : Nat) (p : Path) : + p ∈ divergence (power a m) (power a n) ↔ p ∈ powerSum a (min m n) := by + by_cases he : a = [] + · subst a + cases m <;> cases n <;> simp [power,powerSum,product,branches,divergence] + · induction m generalizing n p with + | zero => simp [power,powerSum] + | succ m ih => + cases n with + | zero => simp [power,powerSum] + | succ n => + simp only [power,Nat.succ_min_succ] + rw [common_prefix_code ha (power_nonempty he m) (power_nonempty he n)] + rw [powerSum_succ] + simp only [union,List.mem_append] + have hh := product_congr (fun q => Iff.rfl (a := q ∈ a)) (fun q => ih n q) p + rw [hh] + +@[simp] theorem product_empty_right (a : PathSpace) : product a [] = [] := by + apply List.eq_nil_iff_forall_not_mem.mpr + intro p + simp [mem_product] + +theorem general_product (a b x y : PathSpace) (p : Path) : + p ∈ divergence (product a x) (product b y) ↔ + p ∈ (if x.isEmpty || y.isEmpty then [] else + union (union (divergence a b) (product (inter a b) (divergence x y))) + (union (PathSetLaws.leftOverlap a b x y) (PathSetLaws.rightOverlap a b x y))) := by + by_cases hx : x = [] + · subst x; simp + · by_cases hy : y = [] + · subst y; simp + · have hxe : x.isEmpty = false := by simpa using hx + have hye : y.isEmpty = false := by simpa using hy + simp only [hxe,hye,Bool.or_self,Bool.false_eq_true,if_false,union,List.mem_append] + rw [divergence_product_nonempty a b x y hx hy] + grind +end PathMapModel.PathSpace diff --git a/lean/PathMapModel/PathSetProduct.lean b/lean/PathMapModel/PathSetProduct.lean new file mode 100644 index 00000000..6bc9588e --- /dev/null +++ b/lean/PathMapModel/PathSetProduct.lean @@ -0,0 +1,161 @@ +import PathMapModel.PathSetRecursive +import PathMapModel.PathSetLaws + +namespace PathMapModel.Path + +theorem divergence_extend_both {a b p : Path} (x y : Path) + (h : divergence a b = some p) : divergence (a ++ x) (b ++ y) = some p := by + rw [divergence_comm] + exact divergence_extend_left y ((divergence_comm b (a++x)).trans (divergence_extend_left x h)) +end PathMapModel.Path + +namespace PathMapModel.PathSpace + +theorem mem_proper_overlap (a b : PathSpace) (f : Path → Path → PathSpace) (p : Path) : + p ∈ properOverlap a b f ↔ + ∃ u ∈ a, ∃ r, r ≠ [] ∧ u ++ r ∈ b ∧ p ∈ f u r := by + simp only [properOverlap,List.mem_flatMap] + constructor + · rintro ⟨u,hu,v,hv,hp⟩ + cases hs : Path.stripPrefix u v with + | none => simp [hs] at hp + | some r => + have hvu := (Path.stripPrefix_eq u v r).mp hs + subst v + cases r with + | nil => simp only [List.append_nil] at hs; simp [hs] at hp + | cons c rs => exact ⟨u,hu,c::rs,by simp,hv,by simpa [hs] using hp⟩ + · rintro ⟨u,hu,r,hr,hv,hp⟩ + refine ⟨u,hu,u++r,hv,?_⟩ + have hs := (Path.stripPrefix_eq u (u++r) r).mpr rfl + cases r with + | nil => exact False.elim (hr rfl) + | cons c rs => simpa [hs] using hp + +theorem mem_leftOverlap (a b x y : PathSpace) (p : Path) : + p ∈ PathSetLaws.leftOverlap a b x y ↔ ∃ u ∈ a, ∃ r, r ≠ [] ∧ u ++ r ∈ b ∧ + ∃ q ∈ divergence x (wrap r y), u ++ q = p := by + simp only [PathSetLaws.leftOverlap,PathSetLaws.D] + rw [mem_proper_overlap a b (fun u r => wrap u (normalize (divergence x (wrap r y)))) p] + change (∃ u ∈ a, ∃ r, r ≠ [] ∧ u ++ r ∈ b ∧ p ∈ wrap u (normalize (divergence x (wrap r y)))) ↔ _ + simp only [mem_wrap,mem_normalize] + +theorem mem_rightOverlap (a b x y : PathSpace) (p : Path) : + p ∈ PathSetLaws.rightOverlap a b x y ↔ ∃ v ∈ b, ∃ r, r ≠ [] ∧ v ++ r ∈ a ∧ + ∃ q ∈ divergence (wrap r x) y, v ++ q = p := by + simp only [PathSetLaws.rightOverlap,PathSetLaws.D] + rw [mem_proper_overlap b a (fun v r => wrap v (normalize (divergence (wrap r x) y))) p] + change (∃ v ∈ b, ∃ r, r ≠ [] ∧ v ++ r ∈ a ∧ p ∈ wrap v (normalize (divergence (wrap r x) y))) ↔ _ + simp only [mem_wrap,mem_normalize] + +theorem divergence_product_nonempty (a b x y : PathSpace) (hx : x ≠ []) (hy : y ≠ []) (p : Path) : + p ∈ divergence (product a x) (product b y) ↔ + p ∈ divergence a b ∨ p ∈ product (inter a b) (divergence x y) ∨ + p ∈ PathSetLaws.leftOverlap a b x y ∨ p ∈ PathSetLaws.rightOverlap a b x y := by + constructor + · intro h + obtain ⟨ux,hux,vy,hvy,hd⟩ := (mem_divergence _ _ _).mp h + obtain ⟨u,hu,s,hs,rfl⟩ := (mem_product _ _ _).mp hux + obtain ⟨v,hv,t,ht,rfl⟩ := (mem_product _ _ _).mp hvy + rcases Path.divergence_or_comparable u v with hd' | hp | hp + · have he := Path.divergence_extend_both s t hd' + rw [hd,Option.some.injEq] at he + exact Or.inl ((mem_divergence _ _ _).mpr ⟨u,hu,v,hv,he ▸ hd'⟩) + · obtain ⟨r,rfl⟩ := (Path.prefix_iff_extension u v).mp hp + rw [List.append_assoc,Path.divergence_wrap] at hd + obtain ⟨q,hq,rfl⟩ := Option.map_eq_some_iff.mp hd + cases r with + | nil => + exact Or.inr (Or.inl ((mem_product _ _ _).mpr ⟨u,(mem_inter _ _ _).mpr ⟨hu,by simpa using hv⟩, + q,(mem_divergence _ _ _).mpr ⟨s,hs,t,ht,hq⟩,rfl⟩)) + | cons c rs => + exact Or.inr (Or.inr (Or.inl ((mem_leftOverlap _ _ _ _ _).mpr + ⟨u,hu,c::rs,by simp,hv,q,(mem_divergence _ _ _).mpr + ⟨s,hs,(c::rs)++t,(mem_wrap _ _ _).mpr ⟨t,ht,rfl⟩,hq⟩,rfl⟩))) + · obtain ⟨r,rfl⟩ := (Path.prefix_iff_extension v u).mp hp + rw [List.append_assoc,Path.divergence_wrap] at hd + obtain ⟨q,hq,rfl⟩ := Option.map_eq_some_iff.mp hd + cases r with + | nil => + exact Or.inr (Or.inl ((mem_product _ _ _).mpr ⟨v,(mem_inter _ _ _).mpr ⟨by simpa using hu,hv⟩, + q,(mem_divergence _ _ _).mpr ⟨s,hs,t,ht,hq⟩,rfl⟩)) + | cons c rs => + exact Or.inr (Or.inr (Or.inr ((mem_rightOverlap _ _ _ _ _).mpr + ⟨v,hv,c::rs,by simp,hu,q,(mem_divergence _ _ _).mpr + ⟨(c::rs)++s,(mem_wrap _ _ _).mpr ⟨s,hs,rfl⟩,t,ht,hq⟩,rfl⟩))) + · rintro (h | h | h | h) + · obtain ⟨u,hu,v,hv,hd⟩ := (mem_divergence _ _ _).mp h + cases x with + | nil => exact False.elim (hx rfl) + | cons s xs => + cases y with + | nil => exact False.elim (hy rfl) + | cons t ys => + exact (mem_divergence _ _ _).mpr + ⟨u++s,(mem_product _ _ _).mpr ⟨u,hu,s,by simp,rfl⟩, + v++t,(mem_product _ _ _).mpr ⟨v,hv,t,by simp,rfl⟩,Path.divergence_extend_both s t hd⟩ + · obtain ⟨u,hu,q,hq,rfl⟩ := (mem_product _ _ _).mp h + obtain ⟨hua,hub⟩ := (mem_inter _ _ _).mp hu + obtain ⟨s,hs,t,ht,hd⟩ := (mem_divergence _ _ _).mp hq + exact (mem_divergence _ _ _).mpr + ⟨u++s,(mem_product _ _ _).mpr ⟨u,hua,s,hs,rfl⟩, + u++t,(mem_product _ _ _).mpr ⟨u,hub,t,ht,rfl⟩,by simp [Path.divergence_wrap,hd]⟩ + · obtain ⟨u,hu,r,_,hv,q,hq,rfl⟩ := (mem_leftOverlap _ _ _ _ _).mp h + obtain ⟨s,hs,rt,hrt,hd⟩ := (mem_divergence _ _ _).mp hq + obtain ⟨t,ht,rfl⟩ := (mem_wrap _ _ _).mp hrt + exact (mem_divergence _ _ _).mpr + ⟨u++s,(mem_product _ _ _).mpr ⟨u,hu,s,hs,rfl⟩, + (u++r)++t,(mem_product _ _ _).mpr ⟨u++r,hv,t,ht,rfl⟩, + by simp [List.append_assoc,Path.divergence_wrap,hd]⟩ + · obtain ⟨v,hv,r,_,hu,q,hq,rfl⟩ := (mem_rightOverlap _ _ _ _ _).mp h + obtain ⟨rs,hrs,t,ht,hd⟩ := (mem_divergence _ _ _).mp hq + obtain ⟨s,hs,rfl⟩ := (mem_wrap _ _ _).mp hrs + exact (mem_divergence _ _ _).mpr + ⟨(v++r)++s,(mem_product _ _ _).mpr ⟨v++r,hu,s,hs,rfl⟩, + v++t,(mem_product _ _ _).mpr ⟨v,hv,t,ht,rfl⟩, + by simp [List.append_assoc,Path.divergence_wrap,hd]⟩ + +theorem equiv_members {a b : PathSpace} (h : equiv a b = true) (p : Path) : p ∈ a ↔ p ∈ b := by + have he : (∀ p ∈ a, p ∈ b) ∧ (∀ p ∈ b, p ∈ a) := by simpa [equiv,subset,List.all_eq_true] using h + exact ⟨he.1 p,he.2 p⟩ + +def Antichain (a : PathSpace) : Prop := ∀ p ∈ a, ∀ q ∈ a, (p ≼ q) = true → p = q + +theorem prefixFree_antichain {a : PathSpace} (h : prefixFree a = true) : Antichain a := by + intro p hp q hq hpq + have he := equiv_members h q + have hmin := (mem_basis a q).mp (he.mp hq) + by_cases hh : p = q + · exact hh + · have hf := hmin.2 p hp hh + simp [hpq] at hf + +theorem prefix_free_product {a b x y : PathSpace} (hf : Antichain (union a b)) + (hx : x ≠ []) (hy : y ≠ []) (p : Path) : + p ∈ divergence (product a x) (product b y) ↔ + p ∈ divergence a b ∨ p ∈ product (inter a b) (divergence x y) := by + rw [divergence_product_nonempty a b x y hx hy] + have hl : p ∉ PathSetLaws.leftOverlap a b x y := by + intro h + obtain ⟨u,hu,r,hr,hv,_⟩ := (mem_leftOverlap _ _ _ _ _).mp h + have he := hf u (List.mem_append_left b hu) (u++r) (List.mem_append_right a hv) + ((Path.prefix_iff_extension _ _).mpr ⟨r,rfl⟩) + have hn : r = [] := by have hh := congrArg List.length he; simpa using hh + exact hr hn + have hr : p ∉ PathSetLaws.rightOverlap a b x y := by + intro h + obtain ⟨v,hv,r,hr,hu,_⟩ := (mem_rightOverlap _ _ _ _ _).mp h + have he := hf v (List.mem_append_right a hv) (v++r) (List.mem_append_left b hu) + ((Path.prefix_iff_extension _ _).mpr ⟨r,rfl⟩) + have hn : r = [] := by have hh := congrArg List.length he; simpa using hh + exact hr hn + simp [hl,hr] + +theorem common_prefix_code {a x y : PathSpace} (hf : Antichain a) + (hx : x ≠ []) (hy : y ≠ []) (p : Path) : + p ∈ divergence (product a x) (product a y) ↔ + p ∈ union (branches a) (product a (divergence x y)) := by + have hf' : Antichain (union a a) := by intro u hu v hv; apply hf u (by simpa [union] using hu) v (by simpa [union] using hv) + rw [prefix_free_product hf' hx hy] + simp [branches,union,mem_product,mem_inter] +end PathMapModel.PathSpace diff --git a/lean/PathMapModel/PathSetProofs.lean b/lean/PathMapModel/PathSetProofs.lean new file mode 100644 index 00000000..df22649a --- /dev/null +++ b/lean/PathMapModel/PathSetProofs.lean @@ -0,0 +1,224 @@ +import PathMapModel.PathSets + +/-! Universally quantified proofs, separate from the executable law battery. -/ +namespace PathMapModel.PathSpace + +theorem basis_subset (a : PathSpace) {p : Path} (h : p ∈ basis a) : p ∈ a := + ((mem_basis a p).mp h).1 + +theorem hull_subset (a : PathSpace) {p : Path} (h : p ∈ hull a) : p ∈ a := + ((mem_hull a p).mp h).1 + +theorem basis_idempotent (a : PathSpace) (p : Path) : + p ∈ basis (basis a) ↔ p ∈ basis a := by + constructor + · exact basis_subset (basis a) + · intro hp + apply (mem_basis (basis a) p).mpr + exact ⟨hp, fun q hq hne => ((mem_basis a p).mp hp).2 q (basis_subset a hq) hne⟩ + +theorem hull_idempotent (a : PathSpace) (p : Path) : + p ∈ hull (hull a) ↔ p ∈ hull a := by + constructor + · exact hull_subset (hull a) + · intro hp + apply (mem_hull (hull a) p).mpr + exact ⟨hp, fun q hq hne => ((mem_hull a p).mp hp).2 q (hull_subset a hq) hne⟩ + +theorem basis_antichain {a : PathSpace} {p q : Path} + (hp : p ∈ basis a) (hq : q ∈ basis a) (hne : p ≠ q) : (p ≼ q) = false := + ((mem_basis a q).mp hq).2 p (basis_subset a hp) hne + +theorem hull_antichain {a : PathSpace} {p q : Path} + (hp : p ∈ hull a) (hq : q ∈ hull a) (hne : p ≠ q) : (p ≼ q) = false := + ((mem_hull a p).mp hp).2 q (hull_subset a hq) (Ne.symm hne) + +theorem mem_inter (a b : PathSpace) (p : Path) : p ∈ inter a b ↔ p ∈ a ∧ p ∈ b := by + simp [inter] + +theorem mem_diff (a b : PathSpace) (p : Path) : p ∈ diff a b ↔ p ∈ a ∧ p ∉ b := by + simp [diff] + +theorem divergence_intersection_bound {a b c : PathSpace} {p : Path} + (h : p ∈ divergence (inter a b) c) : + p ∈ divergence a c ∧ p ∈ divergence b c := by + obtain ⟨x, hx, y, hy, hd⟩ := (mem_divergence _ _ _).mp h + obtain ⟨ha, hb⟩ := (mem_inter _ _ _).mp hx + exact ⟨(mem_divergence _ _ _).mpr ⟨x, ha, y, hy, hd⟩, + (mem_divergence _ _ _).mpr ⟨x, hb, y, hy, hd⟩⟩ + +theorem divergence_difference_upper {a b c : PathSpace} {p : Path} + (h : p ∈ divergence (diff a b) c) : p ∈ divergence a c := by + apply divergence_mono (b := c) (d := c) (fun x hx => ((mem_diff a b x).mp hx).1) + (fun _ hx => hx) p h + +theorem divergence_difference_lower {a b c : PathSpace} {p : Path} + (h : p ∈ divergence a c) (hn : p ∉ divergence b c) : + p ∈ divergence (diff a b) c := by + obtain ⟨x, hx, y, hy, hd⟩ := (mem_divergence _ _ _).mp h + have nx : x ∉ b := fun hb => hn ((mem_divergence _ _ _).mpr ⟨x, hb, y, hy, hd⟩) + exact (mem_divergence _ _ _).mpr ⟨x, (mem_diff _ _ _).mpr ⟨hx, nx⟩, y, hy, hd⟩ + +theorem branches_union (a b : PathSpace) (p : Path) : + p ∈ branches (union a b) ↔ p ∈ branches a ∨ p ∈ branches b ∨ p ∈ divergence a b := by + change p ∈ divergence (union a b) (union a b) ↔ _ + rw [divergence_union_left] + simp only [union, List.mem_append] + have ha := divergence_union_right a a b p + have hb := divergence_union_right b a b p + simp only [union, List.mem_append] at ha hb + have hc := divergence_comm b a p + dsimp [branches] + grind + +/-- Singletons recover strict pair divergence from Br. -/ +theorem singleton_polarization (a b : Path) (p : Path) : + p ∈ divergence [a] [b] ↔ p ∈ branches [a,b] := by + simp [branches, divergence, Path.divergence_comm b a] + +/-- A symmetric bilinear operation with this diagonal is uniquely determined. +The empty laws are listed explicitly, as in the executable catalog. -/ +theorem divergence_unique + (f : PathSpace → PathSpace → Path → Prop) + (he : ∀ a p, ¬ f [] a p ∧ ¬ f a [] p) + (hs : ∀ a b p, f a b p ↔ f b a p) + (hl : ∀ a b c p, f (a ++ b) c p ↔ f a c p ∨ f b c p) + (hr : ∀ a b c p, f a (b ++ c) p ↔ f a b p ∨ f a c p) + (hd : ∀ a p, f a a p ↔ p ∈ branches a) : + ∀ a b p, f a b p ↔ p ∈ divergence a b := by + have hsingle : ∀ x y p, f [x] [y] p ↔ p ∈ divergence [x] [y] := by + intro x y p + have hxx : ¬ f [x] [x] p := by simpa [branches, divergence] using (hd [x] p) + have hyy : ¬ f [y] [y] p := by simpa [branches, divergence] using (hd [y] p) + have hh := hd ([x] ++ [y]) p + rw [hl, hr, hr] at hh + have hxy := hs [y] [x] p + have hp := singleton_polarization x y p + grind + intro a b p + induction a generalizing b with + | nil => simp [he, divergence] + | cons x xs ih => + have hxb : f [x] b p ↔ p ∈ divergence [x] b := by + induction b with + | nil => simp [he, divergence] + | cons y ys ihb => + change f [x] ([y] ++ ys) p ↔ _ + rw [hr, hsingle, ihb] + simpa [union] using (divergence_union_right [x] [y] ys p).symm + change f ([x] ++ xs) b p ↔ _ + rw [hl, hxb, ih] + simp [divergence, List.mem_append] +/-- Empty annihilation follows from the other three characterizing laws. -/ +theorem divergence_unique_three + (f : PathSpace → PathSpace → Path → Prop) + (hs : ∀ a b p, f a b p ↔ f b a p) + (hl : ∀ a b c p, f (a ++ b) c p ↔ f a c p ∨ f b c p) + (hr : ∀ a b c p, f a (b ++ c) p ↔ f a b p ∨ f a c p) + (hd : ∀ a p, f a a p ↔ p ∈ branches a) : + ∀ a b p, f a b p ↔ p ∈ divergence a b := by + have hempty : ∀ a p, ¬ f [] a p := by + intro a p + induction a with + | nil => simpa [branches, divergence] using hd [] p + | cons x xs ih => + have hself : ¬ f [x] [x] p := by simpa [branches, divergence] using hd [x] p + have hx : ¬ f [] [x] p := fun h => hself ((hl [] [x] [x] p).mpr (Or.inl h)) + change ¬ f [] ([x] ++ xs) p + rw [hr] + exact fun h => h.elim hx ih + exact divergence_unique f (fun a p => ⟨hempty a p, fun h => hempty a p ((hs a [] p).mp h)⟩) + hs hl hr hd + +theorem divergence_no_unit (u : PathSpace) : divergence [[]] u ≠ [[]] := by simp + +theorem divergence_not_associative : + ¬ ∀ a b c : PathSpace, equiv (divergence (divergence a b) c) + (divergence a (divergence b c)) = true := by + intro h + have bad := h [[0,0]] [[0,1]] [[1]] + exact (by decide : equiv (divergence (divergence [[0,0]] [[0,1]]) [[1]]) + (divergence [[0,0]] (divergence [[0,1]] [[1]])) ≠ true) bad + +end PathMapModel.PathSpace + +namespace PathMapModel.Path + +/-- A successful pair divergence is a prefix of each input, even if no input +stores that interior prefix as a value. -/ +theorem divergence_prefix_left {a b p : Path} (h : divergence a b = some p) : + (p ≼ a) = true := by + induction a generalizing b p with + | nil => simp [divergence] at h + | cons x xs ih => + cases b with + | nil => simp [divergence] at h + | cons y ys => + by_cases hxy : x = y + · subst y + simp only [divergence, beq_self_eq_true, if_true, Option.map_eq_some_iff] at h + obtain ⟨q, hq, rfl⟩ := h + simp [isPrefixOf, ih hq] + · simp [divergence, hxy] at h + subst p + simp [isPrefixOf] + +/-- Extending a divergent witness preserves the same divergence. -/ +theorem divergence_extend_left {a b p : Path} (tail : Path) (h : divergence a b = some p) : + divergence (a ++ tail) b = some p := by + induction a generalizing b p with + | nil => simp [divergence] at h + | cons x xs ih => + cases b with + | nil => simp [divergence] at h + | cons y ys => + by_cases hxy : x = y + · subst y + simp only [divergence, beq_self_eq_true, if_true, Option.map_eq_some_iff] at h + obtain ⟨q, hq, rfl⟩ := h + simp [divergence, ih hq] + · simp [divergence, hxy] at h ⊢ + exact h + +theorem prefix_iff_extension (p q : Path) : + (p ≼ q) = true ↔ ∃ r, q = p ++ r := by + induction p generalizing q with + | nil => simp [isPrefixOf] + | cons x xs ih => + cases q with + | nil => simp [isPrefixOf] + | cons y ys => + simp only [isPrefixOf, Bool.and_eq_true, beq_iff_eq, List.cons_append, List.cons.injEq] + rw [ih] + constructor + · rintro ⟨rfl, r, hr⟩ + exact ⟨r, rfl, hr⟩ + · rintro ⟨r, rfl, hr⟩ + exact ⟨rfl, r, hr⟩ +end PathMapModel.Path + +namespace PathMapModel.PathSpace + +theorem divergence_covered_mono {a b c : PathSpace} + (hc : ∀ x ∈ a, ∃ y ∈ b, (x ≼ y) = true) : + ∀ p, p ∈ divergence a c → p ∈ divergence b c := by + intro p hp + obtain ⟨x, hx, z, hz, hd⟩ := (mem_divergence _ _ _).mp hp + obtain ⟨y, hy, hxy⟩ := hc x hx + obtain ⟨tail, rfl⟩ := (Path.prefix_iff_extension x y).mp hxy + exact (mem_divergence _ _ _).mpr ⟨x ++ tail, hy, z, hz, Path.divergence_extend_left tail hd⟩ + +theorem divergence_output_covered {a b : PathSpace} {p : Path} + (h : p ∈ divergence a b) : ∃ x ∈ a, (p ≼ x) = true := by + obtain ⟨x, hx, y, _, hd⟩ := (mem_divergence _ _ _).mp h + exact ⟨x, hx, Path.divergence_prefix_left hd⟩ + +theorem divergence_nested_bound {a b c : PathSpace} {p : Path} + (h : p ∈ divergence (divergence a b) c) : + p ∈ divergence a c ∧ p ∈ divergence b c := by + constructor + · exact divergence_covered_mono (fun _ hx => divergence_output_covered hx) p h + · apply divergence_covered_mono (a := divergence a b) (b := b) (c := c) ?_ p h + intro x hx + exact divergence_output_covered ((divergence_comm a b x).mp hx) +end PathMapModel.PathSpace diff --git a/lean/PathMapModel/PathSetRecursive.lean b/lean/PathMapModel/PathSetRecursive.lean new file mode 100644 index 00000000..f13de11e --- /dev/null +++ b/lean/PathMapModel/PathSetRecursive.lean @@ -0,0 +1,280 @@ +import PathMapModel.PathSetFork + +namespace PathMapModel.PathSpace + +theorem basis_nil (a : PathSpace) : [] ∈ basis a ↔ [] ∈ a := by + rw [mem_basis] + constructor + · exact And.left + · intro h; refine ⟨h,?_⟩; intro q hq hn + cases q with + | nil => exact False.elim (hn rfl) + | cons c qs => rfl + +theorem basis_cons (a : PathSpace) (c : UInt8) (p : Path) : + c :: p ∈ basis a ↔ [] ∉ a ∧ p ∈ basis (unwrap a [c]) := by + constructor + · intro h + have hm := (mem_basis _ _).mp h + refine ⟨?_,(mem_basis _ _).mpr ⟨(mem_unwrap _ _ _).mpr hm.1,?_⟩⟩ + · intro hn + have hf := hm.2 [] hn (by simp) + simp [Path.isPrefixOf] at hf + · intro q hq hn + have hf := hm.2 (c::q) ((mem_unwrap _ _ _).mp hq) (by simpa using hn) + simpa [Path.isPrefixOf] using hf + · rintro ⟨hn,h⟩ + have hm := (mem_basis _ _).mp h + refine (mem_basis _ _).mpr ⟨(mem_unwrap _ _ _).mp hm.1,?_⟩ + intro q hq hne + cases q with + | nil => exact False.elim (hn hq) + | cons d qs => + by_cases hd : d = c + · subst d + have hf := hm.2 qs ((mem_unwrap _ _ _).mpr hq) (by simpa using hne) + simpa [Path.isPrefixOf] using hf + · simp [Path.isPrefixOf,hd] + +theorem hull_cons (a : PathSpace) (c : UInt8) (p : Path) : + c :: p ∈ hull a ↔ p ∈ hull (unwrap a [c]) := by + constructor + · intro h + have hm := (mem_hull _ _).mp h + refine (mem_hull _ _).mpr ⟨(mem_unwrap _ _ _).mpr hm.1,?_⟩ + intro q hq hn + have hf := hm.2 (c::q) ((mem_unwrap _ _ _).mp hq) (by simpa using hn) + simpa [Path.isPrefixOf] using hf + · intro h + have hm := (mem_hull _ _).mp h + refine (mem_hull _ _).mpr ⟨(mem_unwrap _ _ _).mp hm.1,?_⟩ + intro q hq hne + cases q with + | nil => rfl + | cons d qs => + by_cases hd : d = c + · subst d + have hf := hm.2 qs ((mem_unwrap _ _ _).mpr hq) (by simpa using hne) + simpa [Path.isPrefixOf] using hf + · simp [Path.isPrefixOf,Ne.symm hd] + +theorem head_empty (a : PathSpace) : head a = [] ↔ ∀ p ∈ a, p = [] := by + rw [List.eq_nil_iff_forall_not_mem] + constructor + · intro h p hp + cases p with + | nil => rfl + | cons c ps => exact False.elim (h [c] ((mem_head _ _).mpr ⟨c,rfl,ps,hp⟩)) + · intro h p hp + obtain ⟨c,rfl,ps,hp⟩ := (mem_head _ _).mp hp + have hh := h (c::ps) hp + simp at hh + +theorem hull_nil (a : PathSpace) : [] ∈ hull a ↔ [] ∈ a ∧ head a = [] := by + rw [mem_hull,head_empty] + simp only [Path.isPrefixOf] + grind + +theorem live_nil (m a : PathSpace) : [] ∈ live m a ↔ [] ∈ m ∧ a ≠ [] := by + cases a <;> simp [live,Path.isPrefixOf] + +theorem live_cons (m a : PathSpace) (c : UInt8) (p : Path) : + c :: p ∈ live m a ↔ p ∈ live (unwrap m [c]) (unwrap a [c]) := by + simp only [mem_live,mem_unwrap,List.singleton_append] + constructor + · rintro ⟨hp,q,hq,he⟩ + cases q with + | nil => simp [Path.isPrefixOf] at he + | cons d qs => + simp only [Path.isPrefixOf,Bool.and_eq_true,beq_iff_eq] at he + obtain ⟨rfl,he⟩ := he + exact ⟨hp,qs,hq,he⟩ + · rintro ⟨hp,q,hq,he⟩ + exact ⟨hp,c::q,hq,by simpa [Path.isPrefixOf] using he⟩ + +theorem child_of_unwrap {a : PathSpace} {c : UInt8} {p : Path} + (h : p ∈ unwrap a [c]) : Child a [] c := ⟨p,(mem_unwrap a [c] p).mp h⟩ + +theorem mem_head_expansion (a : PathSpace) (f : Path → PathSpace) (p : Path) : + p ∈ (normalize (head a)).flatMap (fun q => wrap q (f q)) ↔ + ∃ c r, Child a [] c ∧ r ∈ f [c] ∧ c :: r = p := by + simp only [List.mem_flatMap,mem_normalize,mem_head,mem_wrap] + constructor + · rintro ⟨q,⟨c,rfl,hc⟩,r,hr,rfl⟩; exact ⟨c,r,hc,hr,rfl⟩ + · rintro ⟨c,r,hc,hr,rfl⟩; exact ⟨[c],⟨c,rfl,hc⟩,r,hr,rfl⟩ + +theorem mem_common_head_expansion (a b : PathSpace) (f : Path → PathSpace) (p : Path) : + p ∈ (inter (normalize (head a)) (normalize (head b))).flatMap (fun q => wrap q (f q)) ↔ + ∃ c r, Child a [] c ∧ Child b [] c ∧ r ∈ f [c] ∧ c :: r = p := by + simp only [List.mem_flatMap,mem_inter,mem_normalize,mem_head,mem_wrap] + constructor + · rintro ⟨q,⟨⟨c,rfl,hc⟩,⟨d,hd,hd'⟩⟩,r,hr,rfl⟩ + have he : c = d := by simpa using hd + subst d; exact ⟨c,r,hc,hd',hr,rfl⟩ + · rintro ⟨c,r,hc,hd,hr,rfl⟩; exact ⟨[c],⟨⟨c,rfl,hc⟩,⟨c,rfl,hd⟩⟩,r,hr,rfl⟩ + +theorem mem_live_head_expansion (a b : PathSpace) (f : Path → PathSpace) (p : Path) : + p ∈ (normalize (inter (head a) (head b))).flatMap (fun q => wrap q (f q)) ↔ + ∃ c r, Child a [] c ∧ Child b [] c ∧ r ∈ f [c] ∧ c :: r = p := by + simp only [List.mem_flatMap,mem_inter,mem_normalize,mem_head,mem_wrap] + constructor + · rintro ⟨q,⟨⟨c,rfl,hc⟩,⟨d,hd,hd'⟩⟩,r,hr,rfl⟩ + have he : c = d := by simpa using hd + subst d; exact ⟨c,r,hc,hd',hr,rfl⟩ + · rintro ⟨c,r,hc,hd,hr,rfl⟩; exact ⟨[c],⟨⟨c,rfl,hc⟩,⟨c,rfl,hd⟩⟩,r,hr,rfl⟩ + +theorem divergence_root_test (a b : PathSpace) : + ((normalize (head a)).any (fun x => (normalize (head b)).any (· != x))) = true ↔ + [] ∈ divergence a b := by + simp only [List.any_eq_true,mem_normalize,mem_head,mem_divergence_children,bne_iff_ne] + constructor + · rintro ⟨x,⟨c,rfl,hc⟩,y,⟨d,rfl,hd⟩,hne⟩ + exact ⟨c,d,by simpa [Ne,eq_comm] using hne,hc,hd⟩ + · rintro ⟨c,d,hne,hc,hd⟩ + exact ⟨[c],⟨c,rfl,hc⟩,[d],⟨d,rfl,hd⟩,by simpa [Ne,eq_comm] using hne⟩ + +theorem basisRec_spec (n : Nat) (a : PathSpace) (p : Path) : + p ∈ basisRec n a ↔ p ∈ basis a ∧ p.length < n := by + induction n generalizing a p with + | zero => simp [basisRec] + | succ n ih => + rw [basisRec] + by_cases he : [] ∈ a + · simp only [List.contains_iff_mem.mpr he,if_true,List.mem_singleton] + cases p with + | nil => simp [basis_nil,he] + | cons c ps => simp [basis_cons,he] + · have hb : a.contains [] = false := by simpa using he + simp only [hb,Bool.false_eq_true,if_false,mem_head_expansion] + cases p with + | nil => simp [basis_nil,he] + | cons c ps => + simp only [List.cons.injEq,ih,List.length_cons,basis_cons,he,not_false_eq_true,true_and] + constructor + · rintro ⟨c',r,hc,⟨hp,hl⟩,rfl,rfl⟩; exact ⟨hp,by omega⟩ + · rintro ⟨hp,hl⟩; exact ⟨c,ps,child_of_unwrap (basis_subset _ hp),⟨hp,by omega⟩,rfl,rfl⟩ + +theorem hullRec_spec (n : Nat) (a : PathSpace) (p : Path) : + p ∈ hullRec n a ↔ p ∈ hull a ∧ p.length < n := by + induction n generalizing a p with + | zero => simp [hullRec] + | succ n ih => + simp only [hullRec,List.mem_append,mem_head_expansion] + by_cases he : (a.contains [] && (head a).isEmpty) = true + · have hh : [] ∈ a ∧ head a = [] := by simpa using he + simp only [he] + simp only [if_true] + cases p with + | nil => simp [hull_nil,hh] + | cons c ps => + simp only [List.mem_singleton,List.cons_ne_nil,false_or,List.cons.injEq,ih,List.length_cons,hull_cons] + exact ⟨fun ⟨_,_,_,⟨hp,hl⟩,rfl,rfl⟩ => ⟨hp,by omega⟩, + fun ⟨hp,hl⟩ => ⟨c,ps,child_of_unwrap (hull_subset _ hp),⟨hp,by omega⟩,rfl,rfl⟩⟩ + · have hb : (a.contains [] && (head a).isEmpty) = false := by simpa using he + simp only [hb,Bool.false_eq_true,if_false] + cases p with + | nil => simp [hull_nil]; simpa using he + | cons c ps => + simp only [List.not_mem_nil,false_or,List.cons.injEq,ih,List.length_cons,hull_cons] + exact ⟨fun ⟨_,_,_,⟨hp,hl⟩,rfl,rfl⟩ => ⟨hp,by omega⟩, + fun ⟨hp,hl⟩ => ⟨c,ps,child_of_unwrap (hull_subset _ hp),⟨hp,by omega⟩,rfl,rfl⟩⟩ + +theorem divergenceRec_spec (n : Nat) (a b : PathSpace) (p : Path) : + p ∈ divergenceRec n a b ↔ p ∈ divergence a b ∧ p.length < n := by + induction n generalizing a b p with + | zero => simp [divergenceRec] + | succ n ih => + simp only [divergenceRec,List.mem_append,mem_common_head_expansion] + by_cases he : (normalize (head a)).any (fun x => (normalize (head b)).any (· != x)) = true + · simp only [he] + simp only [if_true] + cases p with + | nil => simp [(divergence_root_test a b).mp he] + | cons c ps => + simp only [List.mem_singleton,List.cons_ne_nil,false_or,List.cons.injEq,ih,List.length_cons] + have hun := divergence_unwrap a b [c] ps + simp only [List.singleton_append] at hun + rw [← hun] + constructor + · rintro ⟨_,_,_,_,⟨hp,hl⟩,rfl,rfl⟩; exact ⟨hp,by omega⟩ + · rintro ⟨hp,hl⟩ + obtain ⟨x,hx,y,hy,hd⟩ := (mem_divergence _ _ _).mp hp + exact ⟨c,ps,child_of_unwrap hx,child_of_unwrap hy,⟨hp,by omega⟩,rfl,rfl⟩ + · have hb : (normalize (head a)).any (fun x => (normalize (head b)).any (· != x)) = false := by simpa using he + simp only [hb,Bool.false_eq_true,if_false] + cases p with + | nil => simp; exact fun h => he ((divergence_root_test a b).mpr h) + | cons c ps => + simp only [List.not_mem_nil,false_or,List.cons.injEq,ih,List.length_cons] + have hun := divergence_unwrap a b [c] ps + simp only [List.singleton_append] at hun + rw [← hun] + constructor + · rintro ⟨_,_,_,_,⟨hp,hl⟩,rfl,rfl⟩; exact ⟨hp,by omega⟩ + · rintro ⟨hp,hl⟩ + obtain ⟨x,hx,y,hy,hd⟩ := (mem_divergence _ _ _).mp hp + exact ⟨c,ps,child_of_unwrap hx,child_of_unwrap hy,⟨hp,by omega⟩,rfl,rfl⟩ + +theorem liveRec_spec (n : Nat) (m a : PathSpace) (p : Path) : + p ∈ liveRec n m a ↔ p ∈ live m a ∧ p.length < n := by + induction n generalizing m a p with + | zero => simp [liveRec] + | succ n ih => + simp only [liveRec,List.mem_append,mem_live_head_expansion] + by_cases he : (m.contains [] && !a.isEmpty) = true + · have hh : [] ∈ live m a := (live_nil m a).mpr (by simpa using he) + simp only [he] + simp only [if_true] + cases p with + | nil => simp [hh] + | cons c ps => + simp only [List.mem_singleton,List.cons_ne_nil,false_or,List.cons.injEq,ih,List.length_cons,live_cons] + constructor + · rintro ⟨_,_,_,_,⟨hp,hl⟩,rfl,rfl⟩; exact ⟨hp,by omega⟩ + · rintro ⟨hp,hl⟩ + obtain ⟨hm,q,hq,_⟩ := (mem_live _ _ _).mp hp + exact ⟨c,ps,child_of_unwrap hm,child_of_unwrap hq,⟨hp,by omega⟩,rfl,rfl⟩ + · have hb : (m.contains [] && !a.isEmpty) = false := by simpa using he + simp only [hb,Bool.false_eq_true,if_false] + cases p with + | nil => simp [live_nil]; simpa using he + | cons c ps => + simp only [List.not_mem_nil,false_or,List.cons.injEq,ih,List.length_cons,live_cons] + constructor + · rintro ⟨_,_,_,_,⟨hp,hl⟩,rfl,rfl⟩; exact ⟨hp,by omega⟩ + · rintro ⟨hp,hl⟩ + obtain ⟨hm,q,hq,_⟩ := (mem_live _ _ _).mp hp + exact ⟨c,ps,child_of_unwrap hm,child_of_unwrap hq,⟨hp,by omega⟩,rfl,rfl⟩ + +theorem basis_recursive (a : PathSpace) (p : Path) : + p ∈ basisRec (height a + 1) a ↔ p ∈ basis a := by + rw [basisRec_spec] + exact ⟨And.left,fun h => ⟨h,Nat.lt_succ_of_le (length_le_height (basis_subset a h))⟩⟩ + +theorem hull_recursive (a : PathSpace) (p : Path) : + p ∈ hullRec (height a + 1) a ↔ p ∈ hull a := by + rw [hullRec_spec] + exact ⟨And.left,fun h => ⟨h,Nat.lt_succ_of_le (length_le_height (hull_subset a h))⟩⟩ + +theorem divergence_recursive (a b : PathSpace) (p : Path) : + p ∈ divergenceRec (min (height a) (height b) + 1) a b ↔ p ∈ divergence a b := by + rw [divergenceRec_spec] + constructor + · exact And.left + · intro h + obtain ⟨x,hx,y,hy,hd⟩ := (mem_divergence _ _ _).mp h + have hpx := Path.divergence_length_left hd + have hpy := Path.divergence_length_right hd + have hax := length_le_height hx + have hby := length_le_height hy + exact ⟨h,by omega⟩ + +theorem branch_recursive (a : PathSpace) (p : Path) : + p ∈ divergenceRec (height a + 1) a a ↔ p ∈ branches a := by + simpa [branches] using divergence_recursive a a p + +theorem live_recursive (m a : PathSpace) (p : Path) : + p ∈ liveRec (height m + 1) m a ↔ p ∈ live m a := by + rw [liveRec_spec] + exact ⟨And.left,fun h => ⟨h,Nat.lt_succ_of_le (length_le_height ((mem_live _ _ _).mp h).1)⟩⟩ +end PathMapModel.PathSpace diff --git a/lean/PathMapModel/PathSetRoots.lean b/lean/PathMapModel/PathSetRoots.lean new file mode 100644 index 00000000..7fc51bd9 --- /dev/null +++ b/lean/PathMapModel/PathSetRoots.lean @@ -0,0 +1,152 @@ +import PathMapModel.PathSetPowers + +namespace PathMapModel.PathSpace + +theorem hull_is_antichain (a : PathSpace) : Antichain (hull a) := by + intro p hp q hq he + by_cases hn : p = q + · exact hn + · have hf := hull_antichain hp hq hn + simp [he] at hf + +theorem divergence_empty_iff (a b : PathSpace) : divergence a b = [] ↔ + ∀ x ∈ a, ∀ y ∈ b, (x ≼ y) = true ∨ (y ≼ x) = true := by + constructor + · intro h x hx y hy + apply (Path.divergence_none_iff x y).mp + cases hd : Path.divergence x y with + | none => rfl + | some p => + have hp := (mem_divergence a b p).mpr ⟨x,hx,y,hy,hd⟩ + simp [h] at hp + · intro h + apply List.eq_nil_iff_forall_not_mem.mpr + intro p hp + obtain ⟨x,hx,y,hy,hd⟩ := (mem_divergence _ _ _).mp hp + have hn := (Path.divergence_none_iff x y).mpr (h x hx y hy) + simp [hd] at hn + +/-- On two antichains, a single oriented comparable pair fixes the whole side. -/ +theorem comparable_antichains {a b : PathSpace} (ha : Antichain a) (hb : Antichain b) + (hc : ∀ x ∈ a, ∀ y ∈ b, (x ≼ y) = true ∨ (y ≼ x) = true) + {x y : Path} (hx : x ∈ a) (hy : y ∈ b) (hxy : (x ≼ y) = true) : + (∀ u ∈ a, u = x) ∧ (∀ v ∈ b, (x ≼ v) = true) := by + constructor + · intro u hu + rcases hc u hu y hy with huy | hyu + · rcases Path.prefixes_comparable huy hxy with hux | hxu + · exact ha u hu x hx hux + · exact (ha x hx u hu hxu).symm + · exact (ha x hx u hu (Path.prefix_trans hxy hyu)).symm + · intro v hv + rcases hc x hx v hv with hxv | hvx + · exact hxv + · have he := hb v hv y hy (Path.prefix_trans hvx hxy) + subst v; exact hxy + +/-- The exact zero criterion, phrased extensionally so duplicate list entries +cannot be mistaken for extra members. -/ +theorem zero_criterion (a b : PathSpace) : divergence a b = [] ↔ + a = [] ∨ b = [] ∨ + (∃ x, (∀ u, u ∈ hull a ↔ u = x) ∧ ∀ v ∈ hull b, (x ≼ v) = true) ∨ + (∃ y, (∀ v, v ∈ hull b ↔ v = y) ∧ ∀ u ∈ hull a, (y ≼ u) = true) := by + have he : divergence a b = [] ↔ divergence (hull a) (hull b) = [] := by + simp only [List.eq_nil_iff_forall_not_mem,divergence_hull] + rw [he,divergence_empty_iff] + constructor + · intro hc + by_cases ha : a = [] + · exact Or.inl ha + by_cases hb : b = [] + · exact Or.inr (Or.inl hb) + have hha : hull a ≠ [] := fun h => ha ((hull_nonempty a).mp h) + have hhb : hull b ≠ [] := fun h => hb ((hull_nonempty b).mp h) + obtain ⟨x,hx,_⟩ := height_attained hha + obtain ⟨y,hy,_⟩ := height_attained hhb + rcases hc x hx y hy with hxy | hyx + · obtain ⟨hs,hext⟩ := comparable_antichains (hull_is_antichain a) (hull_is_antichain b) hc hx hy hxy + exact Or.inr (Or.inr (Or.inl ⟨x,fun u => ⟨hs u,fun h => h ▸ hx⟩,hext⟩)) + · have hc' : ∀ y ∈ hull b, ∀ x ∈ hull a, (y ≼ x) = true ∨ (x ≼ y) = true := by + intro y hy x hx; exact (hc x hx y hy).symm + obtain ⟨hs,hext⟩ := comparable_antichains (hull_is_antichain b) (hull_is_antichain a) hc' hy hx hyx + exact Or.inr (Or.inr (Or.inr ⟨y,fun v => ⟨hs v,fun h => h ▸ hy⟩,hext⟩)) + · rintro (rfl | rfl | ⟨x,hx,hext⟩ | ⟨y,hy,hext⟩) + · simp [hull] + · simp [hull] + · intro u hu v hv; have he := (hx u).mp hu; subst u; exact Or.inl (hext v hv) + · intro u hu v hv; have he := (hy v).mp hv; subst v; exact Or.inr (hext u hu) + +theorem commonPrefix_spec (a : PathSpace) (ha : a ≠ []) (p : Path) : + (p ≼ commonPrefix a) = true ↔ ∀ q ∈ a, (p ≼ q) = true := by + have go : ∀ (xs : PathSpace) (q : Path), (p ≼ xs.foldl Path.lcp q) = true ↔ + (p ≼ q) = true ∧ ∀ r ∈ xs, (p ≼ r) = true := by + intro xs + induction xs with + | nil => simp + | cons r rs ih => intro q; simp [ih,Path.prefix_lcp]; grind + cases a with + | nil => exact False.elim (ha rfl) + | cons q qs => simpa [commonPrefix] using go qs q + +theorem first_divergence_covers_left {a b : PathSpace} (ha : Antichain a) {p : Path} + (hp : p ∈ basis (divergence a b)) : ∀ u ∈ a, (p ≼ u) = true := by + have hmin := (mem_basis _ _).mp hp + obtain ⟨x,hx,y,hy,hd⟩ := (mem_divergence _ _ _).mp hmin.1 + have hpx := Path.divergence_prefix_left hd + have hpy := Path.divergence_prefix_left ((Path.divergence_comm y x).trans hd) + intro u hu + rcases Path.divergence_or_comparable u p with hup | hup | hpu + · let q := Path.lcp u p + have hq : q ∈ divergence a b := by + obtain ⟨r,rfl⟩ := (Path.prefix_iff_extension p y).mp hpy + exact (mem_divergence _ _ _).mpr ⟨u,hu,p++r,hy,by + rw [Path.divergence_comm] + exact Path.divergence_extend_left r ((Path.divergence_comm p u).trans hup)⟩ + have hqp := Path.lcp_prefix_right u p + have hn : q ≠ p := by have hl := Path.divergence_length_right hup; intro hh; dsimp [q] at hh; rw [hh] at hl; omega + have hf := hmin.2 q hq hn + simp [q,hqp] at hf + · have he := ha u hu x hx (Path.prefix_trans hup hpx) + subst u + have hl := Path.prefix_length hup + have hs := Path.divergence_length_left hd + omega + · exact hpu + +theorem first_divergence (a b : PathSpace) (h : divergence a b ≠ []) (p : Path) : + p ∈ basis (divergence a b) ↔ p = commonPrefix (union (hull a) (hull b)) := by + let x := divergence (hull a) (hull b) + have hx : ∀ q, q ∈ x ↔ q ∈ divergence a b := divergence_hull a b + have hbas : ∀ q, q ∈ basis x ↔ q ∈ basis (divergence a b) := by + intro q; simp only [mem_basis,hx] + have hn : x ≠ [] := by + intro hh + apply h + apply List.eq_nil_iff_forall_not_mem.mpr + intro q hq + have hm := (hx q).mpr hq + simp [hh] at hm + have hall : ∀ q ∈ basis x, q = commonPrefix (union (hull a) (hull b)) := by + intro q hq + have hqa := first_divergence_covers_left (hull_is_antichain a) hq + have hswap : q ∈ basis (divergence (hull b) (hull a)) := by + simpa only [mem_basis,divergence_comm (hull b) (hull a)] using hq + have hqb := first_divergence_covers_left (hull_is_antichain b) hswap + obtain ⟨u,hu,v,hv,hd⟩ := (mem_divergence _ _ _).mp (basis_subset _ hq) + have hun : union (hull a) (hull b) ≠ [] := List.ne_nil_of_mem (List.mem_append_left _ hu) + have hpref := (commonPrefix_spec _ hun q).mpr (by + intro r hr; rcases List.mem_append.mp hr with hr | hr + · exact hqa r hr + · exact hqb r hr) + have hcp := (commonPrefix_spec _ hun (commonPrefix (union (hull a) (hull b)))).mp (Path.prefix_self _) + have hcq := (Path.prefix_lcp _ u v).mpr ⟨hcp u (List.mem_append_left _ hu),hcp v (List.mem_append_right _ hv)⟩ + rw [Path.divergence_lcp hd] at hcq + exact Path.prefix_antisymm hpref hcq + rw [← hbas p] + constructor + · exact hall p + · intro he + obtain ⟨q,hq,_⟩ := height_attained (fun hh => hn ((basis_nonempty x).mp hh)) + have heq := (hall q hq).trans he.symm + exact heq ▸ hq +end PathMapModel.PathSpace diff --git a/lean/PathMapModel/PathSetStructure.lean b/lean/PathMapModel/PathSetStructure.lean new file mode 100644 index 00000000..c3facdf2 --- /dev/null +++ b/lean/PathMapModel/PathSetStructure.lean @@ -0,0 +1,137 @@ +import PathMapModel.PathSetDepth + +namespace PathMapModel.Path + +theorem mem_insertSorted (a p : Path) (s : List Path) : + p ∈ insertSorted a s ↔ p = a ∨ p ∈ s := by + induction s with + | nil => simp [insertSorted] + | cons q qs ih => + by_cases h : a = q + · subst q; simp [insertSorted] + · by_cases hl : lt a q + · simp [insertSorted,h,hl] <;> grind + · simp [insertSorted,h,hl,ih] <;> grind + +theorem mem_sortDedup (s : List Path) (p : Path) : p ∈ sortDedup s ↔ p ∈ s := by + have go : ∀ (xs acc : List Path), + p ∈ xs.foldl (fun a q => insertSorted q a) acc ↔ p ∈ xs ∨ p ∈ acc := by + intro xs + induction xs with + | nil => simp + | cons q qs ih => intro acc; simp [ih,mem_insertSorted] <;> grind + simpa [sortDedup] using go s [] + +theorem stripPrefix_eq (p q r : Path) : stripPrefix p q = some r ↔ q = p ++ r := by + induction p generalizing q with + | nil => simp [stripPrefix] + | cons a ps ih => + cases q with + | nil => simp [stripPrefix] + | cons b qs => + by_cases h : a = b + · subst b; simp [stripPrefix,ih] + · simp [stripPrefix,h] <;> grind +end PathMapModel.Path + +namespace PathMapModel.PathSpace + +@[simp] theorem mem_normalize (a : PathSpace) (p : Path) : p ∈ normalize a ↔ p ∈ a := + Path.mem_sortDedup a p + +theorem mem_wrap (q : Path) (a : PathSpace) (p : Path) : + p ∈ wrap q a ↔ ∃ r ∈ a, q ++ r = p := by simp [wrap] + +theorem mem_unwrap (a : PathSpace) (q p : Path) : + p ∈ unwrap a q ↔ q ++ p ∈ a := by + simp [unwrap,List.mem_filterMap,Path.stripPrefix_eq] + +theorem mem_product (a b : PathSpace) (p : Path) : + p ∈ product a b ↔ ∃ x ∈ a, ∃ y ∈ b, x ++ y = p := by + simp [product,List.mem_flatMap] + +theorem divergence_unwrap (a b : PathSpace) (q p : Path) : + p ∈ divergence (unwrap a q) (unwrap b q) ↔ q ++ p ∈ divergence a b := by + constructor + · intro h + obtain ⟨x,hx,y,hy,hd⟩ := (mem_divergence _ _ _).mp h + exact (mem_divergence _ _ _).mpr ⟨q++x,(mem_unwrap _ _ _).mp hx, + q++y,(mem_unwrap _ _ _).mp hy,by simp [Path.divergence_wrap,hd]⟩ + · intro h + obtain ⟨x,y,hxy,⟨xs,hx⟩,⟨ys,hy⟩⟩ := (mem_divergence_children _ _ _).mp h + apply (mem_divergence_children _ _ _).mpr + refine ⟨x,y,hxy,⟨xs,?_⟩,⟨ys,?_⟩⟩ + · apply (mem_unwrap _ _ _).mpr; simpa [List.append_assoc] using hx + · apply (mem_unwrap _ _ _).mpr; simpa [List.append_assoc] using hy + +theorem divergence_wrap (a b : PathSpace) (q p : Path) : + p ∈ divergence (wrap q a) (wrap q b) ↔ p ∈ wrap q (divergence a b) := by + simp only [mem_divergence,mem_wrap] + constructor + · rintro ⟨x,⟨u,hu,rfl⟩,y,⟨v,hv,rfl⟩,hd⟩ + rw [Path.divergence_wrap] at hd + obtain ⟨r,hr,hp⟩ := Option.map_eq_some_iff.mp hd + exact ⟨r,⟨u,hu,v,hv,hr⟩,hp⟩ + · rintro ⟨r,⟨u,hu,v,hv,hd⟩,rfl⟩ + exact ⟨q++u,⟨u,hu,rfl⟩,q++v,⟨v,hv,rfl⟩,by simp [Path.divergence_wrap,hd]⟩ + +theorem mem_head (a : PathSpace) (p : Path) : + p ∈ head a ↔ ∃ c, p = [c] ∧ Child a [] c := by + simp only [head,List.mem_filterMap,Option.map_eq_some_iff] + constructor + · rintro ⟨q,hq,c,hc,rfl⟩ + cases q with + | nil => simp at hc + | cons d qs => + simp only [List.head?_cons,Option.some.injEq] at hc + subst d; exact ⟨c,rfl,qs,hq⟩ + · rintro ⟨c,rfl,qs,hq⟩ + exact ⟨c::qs,hq,c,rfl,rfl⟩ + +theorem mem_tails (a : PathSpace) (p : Path) : + p ∈ tails a ↔ ∃ c, c :: p ∈ a := by + simp only [tails,List.mem_filterMap] + constructor + · rintro ⟨q,hq,hd⟩ + cases q with + | nil => simp at hd + | cons c qs => simp only [Option.some.injEq] at hd; subst qs; exact ⟨c,hq⟩ + · rintro ⟨c,hc⟩; exact ⟨c::p,hc,rfl⟩ + +theorem child_head (a : PathSpace) (p : Path) (c : UInt8) : + Child (head a) p c ↔ p = [] ∧ Child a [] c := by + constructor + · rintro ⟨xs,hx⟩ + obtain ⟨d,hd,ys,hy⟩ := (mem_head _ _).mp hx + have hl := congrArg List.length hd + simp only [List.length_append,List.length_cons,List.length_nil] at hl + have hp : p = [] := List.eq_nil_of_length_eq_zero (by omega) + have hs : xs = [] := List.eq_nil_of_length_eq_zero (by omega) + subst p; subst xs + simp only [List.nil_append,List.cons.injEq] at hd + obtain ⟨rfl,_⟩ := hd + exact ⟨rfl,ys,hy⟩ + · rintro ⟨rfl,h⟩; exact ⟨[],(mem_head _ _).mpr ⟨c,rfl,h⟩⟩ + +theorem divergence_root_heads (a b : PathSpace) (p : Path) : + p ∈ divergence (head a) (head b) ↔ p ∈ divergence a b ∧ p = [] := by + simp only [mem_divergence_children,child_head] + constructor + · rintro ⟨x,y,hxy,⟨rfl,hx⟩,⟨_,hy⟩⟩; exact ⟨⟨x,y,hxy,hx,hy⟩,rfl⟩ + · rintro ⟨⟨x,y,hxy,hx,hy⟩,rfl⟩; exact ⟨x,y,hxy,⟨rfl,hx⟩,⟨rfl,hy⟩⟩ + +theorem divergence_output_heads {a b : PathSpace} {p : Path} + (h : p ∈ head (divergence a b)) : p ∈ head a ∧ p ∈ head b := by + obtain ⟨c,rfl,tail,ht⟩ := (mem_head _ _).mp h + have ha := child_of_covered (divergence_output_covered ht) + have hb := child_of_covered (divergence_output_covered ((divergence_comm a b _).mp ht)) + exact ⟨(mem_head _ _).mpr ⟨c,rfl,ha⟩,(mem_head _ _).mpr ⟨c,rfl,hb⟩⟩ + +theorem divergence_tails {a b : PathSpace} {p : Path} + (h : p ∈ tails (divergence a b)) : p ∈ divergence (tails a) (tails b) := by + obtain ⟨c,hc⟩ := (mem_tails _ _).mp h + have hs := (divergence_unwrap a b [c] p).mpr hc + apply divergence_mono (a := unwrap a [c]) (b := unwrap b [c]) ?_ ?_ p hs + · intro q hq; exact (mem_tails _ _).mpr ⟨c,(mem_unwrap _ _ _).mp hq⟩ + · intro q hq; exact (mem_tails _ _).mpr ⟨c,(mem_unwrap _ _ _).mp hq⟩ +end PathMapModel.PathSpace diff --git a/lean/PathMapModel/PathSetUpdates.lean b/lean/PathMapModel/PathSetUpdates.lean new file mode 100644 index 00000000..ff341785 --- /dev/null +++ b/lean/PathMapModel/PathSetUpdates.lean @@ -0,0 +1,138 @@ +import PathMapModel.PathSetCardinality + +namespace PathMapModel.PathSpace + +theorem singleton_bound (q : Path) (a : PathSpace) : + count (divergence [q] a) ≤ min q.length (count (hull a)) := by + apply Nat.le_min.mpr + constructor + · have hs : (divergence [q] a).eraseDups ⊆ (List.range q.length).map (q.take ·) := by + intro p hp + have hp' := List.mem_eraseDups.mp hp + obtain ⟨x,hx,y,hy,hd⟩ := (mem_divergence _ _ _).mp hp' + simp only [List.mem_singleton] at hx + subst x + have hlen := Path.divergence_length_left hd + have hpre := (Path.prefix_iff_list _ _).mp (Path.divergence_prefix_left hd) + have he := List.prefix_iff_eq_take.mp hpre + exact List.mem_map.mpr ⟨p.length,List.mem_range.mpr hlen,he.symm⟩ + have hh := (dedup_nodup (divergence [q] a)).length_le_of_subset hs + simpa [count] using hh + · have hc : count (divergence [q] a) = count (divergence [q] (hull a)) := by + apply count_congr + intro p + rw [divergence_comm [q] a,← divergence_hull_left a [q],divergence_comm] + rw [hc] + apply count_relation (fun p x => Path.divergence q x = some p) ?_ ?_ + · intro p hp + obtain ⟨u,hu,v,hv,hd⟩ := (mem_divergence _ _ _).mp hp + simp only [List.mem_singleton] at hu + subst u; exact ⟨v,hv,hd⟩ + · intro p hp p' hp' x h h' + exact Option.some.inj (h.symm.trans h') + +theorem singleton_outputs_comparable {q p r : Path} {a : PathSpace} + (hp : p ∈ divergence [q] a) (hr : r ∈ divergence [q] a) : + (p ≼ r) = true ∨ (r ≼ p) = true := by + obtain ⟨x,hx,hpx⟩ := divergence_output_covered hp + obtain ⟨y,hy,hry⟩ := divergence_output_covered hr + simp only [List.mem_singleton] at hx hy + subst x; subst y + exact Path.prefixes_comparable hpx hry + +theorem count_le_one_of_equal (a : PathSpace) (h : ∀ p ∈ a, ∀ q ∈ a, p = q) : count a ≤ 1 := by + cases a with + | nil => simp [count] + | cons p ps => + have hs : count (p::ps) ≤ count [p] := count_mono (by + intro q hq; exact List.mem_singleton.mpr (h q hq p (by simp))) + simpa [count_singleton] using hs + +theorem singleton_output_hull (q : Path) (a : PathSpace) : count (hull (divergence [q] a)) ≤ 1 := by + apply count_le_one_of_equal + intro p hp r hr + rcases singleton_outputs_comparable (hull_subset _ hp) (hull_subset _ hr) with hpr | hrp + · exact hull_is_antichain _ p hp r hr hpr + · exact (hull_is_antichain _ r hr p hp hrp).symm + +theorem singleton_fresh_subset {q p : Path} {a : PathSpace} + (h : p ∈ divergence [q] a) (hn : p ∉ branches a) : p ∈ hull (divergence [q] a) := by + by_cases hh : p ∈ hull (divergence [q] a) + · exact hh + · have hi : p ∈ interior (divergence [q] a) := (mem_diff _ _ _).mpr ⟨h,hh⟩ + exact False.elim (hn (singleton_existing_branches hi)) + +theorem branch_insert (q : Path) (a : PathSpace) (p : Path) : + p ∈ branches (q :: a) ↔ p ∈ branches a ∨ p ∈ divergence [q] a := by + have h := branches_union [q] a p + simpa [union,branches,divergence] using h + +theorem singleton_branch_update (q : Path) (a : PathSpace) : + count (diff (branches (union a [q])) (branches a)) ≤ 1 := by + have hs : count (diff (branches (union a [q])) (branches a)) ≤ count (hull (divergence [q] a)) := by + apply count_mono + intro p hp + obtain ⟨hp,hn⟩ := (mem_diff _ _ _).mp hp + rw [branches_union] at hp + rcases hp with hp | hp | hp + · exact False.elim (hn hp) + · simp [branches,divergence] at hp + · exact singleton_fresh_subset ((divergence_comm _ _ _).mp hp) hn + exact Nat.le_trans hs (singleton_output_hull q a) + +theorem singleton_divergence_update (a b : PathSpace) (q : Path) : + count (diff (divergence (union a [q]) b) (divergence a b)) ≤ min q.length (count (hull b)) := by + have hs : count (diff (divergence (union a [q]) b) (divergence a b)) ≤ count (divergence [q] b) := by + apply count_mono + intro p hp + obtain ⟨hp,hn⟩ := (mem_diff _ _ _).mp hp + rw [divergence_union_left] at hp + rcases List.mem_append.mp hp with hp | hp + · exact False.elim (hn hp) + · exact hp + exact Nat.le_trans hs (singleton_bound q b) + +theorem branch_count_length (a : PathSpace) : count (branches a) ≤ a.length - 1 := by + induction a with + | nil => simp [branches,count] + | cons q a ih => + cases a with + | nil => simp [branches,divergence,count] + | cons r rs => + let old := branches (r::rs) + let fresh := diff (branches (q::r::rs)) old + have hf : count fresh ≤ 1 := by + have he : ∀ p, p ∈ branches (q::r::rs) ↔ p ∈ branches (union (r::rs) [q]) := by + intro p + apply divergence_congr <;> intro u <;> simp [union] <;> grind + have hc : count fresh = count (diff (branches (union (r::rs) [q])) old) := by + apply count_congr; intro p; simp only [fresh,mem_diff,he] + rw [hc] + exact singleton_branch_update q (r::rs) + have hs : count (branches (q::r::rs)) ≤ count (union old fresh) := by + apply count_mono + intro p hp + by_cases ho : p ∈ old + · exact List.mem_append_left _ ho + · exact List.mem_append_right _ ((mem_diff _ _ _).mpr ⟨hp,ho⟩) + have hu := count_union_le old fresh + dsimp [old] at hu hs + simp only [List.length_cons] at ih ⊢ + omega + +theorem branch_count (a : PathSpace) : count (branches a) ≤ count a - 1 := by + have he : count (branches a) = count (branches a.eraseDups) := by + apply count_congr + exact divergence_congr (by intro p; simp) (by intro p; simp) + rw [he] + exact branch_count_length a.eraseDups + +theorem output_cardinality (a b : PathSpace) : + count (divergence a b) ≤ count (hull (union a b)) - 1 := by + have hs : count (divergence a b) ≤ count (branches (union a b)) := + count_mono (fun _ h => branch_sandwich_upper h) + have he : count (branches (union a b)) = count (branches (hull (union a b))) := + count_congr (fun p => (branch_hull (union a b) p).symm) + rw [he] at hs + exact Nat.le_trans hs (branch_count (hull (union a b))) +end PathMapModel.PathSpace diff --git a/lean/PathMapModel/PathSets.lean b/lean/PathMapModel/PathSets.lean new file mode 100644 index 00000000..d4c0b096 --- /dev/null +++ b/lean/PathMapModel/PathSets.lean @@ -0,0 +1,196 @@ +import PathMapModel.Map + +/-! Valued finite path sets. This independent list model deliberately differs +from the Rust zipper traversal. Lists denote sets: order/duplicates are ignored +by `equiv`. Bare structure is not membership. Basis/hull preserve payloads. -/ +namespace PathMapModel +namespace Path + +def lcp : Path → Path → Path + | a :: as, b :: bs => if a == b then a :: lcp as bs else [] + | _, _ => [] + +/-- Termination is not a next byte. -/ +def divergence : Path → Path → Option Path + | a :: as, b :: bs => if a == b then (divergence as bs).map (a :: ·) else some [] + | _, _ => none + +@[simp] theorem divergence_self (p : Path) : divergence p p = none := by + induction p with + | nil => rfl + | cons a as ih => simp [divergence, ih] + +theorem divergence_comm (p q : Path) : divergence p q = divergence q p := by + induction p generalizing q with + | nil => cases q <;> rfl + | cons a as ih => + cases q with + | nil => rfl + | cons b bs => + by_cases h : a = b + · subst b; simp [divergence, ih] + · simp [divergence, h, Ne.symm h] + +@[simp] theorem divergence_nil_left (p : Path) : divergence [] p = none := by cases p <;> rfl +@[simp] theorem divergence_nil_right (p : Path) : divergence p [] = none := by cases p <;> rfl + +theorem divergence_wrap (p a b : Path) : + divergence (p ++ a) (p ++ b) = (divergence a b).map (p ++ ·) := by + induction p with + | nil => simp + | cons c cs ih => simp [divergence, ih, Option.map_map, Function.comp_def] +end Path + +abbrev PathSpace := List Path +namespace PathSpace + +def normalize (a : PathSpace) : PathSpace := Path.sortDedup a +def subset (a b : PathSpace) : Bool := a.all b.contains +/-- Set equality is independent of enumeration and serialization order. -/ +def equiv (a b : PathSpace) : Bool := subset a b && subset b a +def union (a b : PathSpace) : PathSpace := a ++ b +def inter (a b : PathSpace) : PathSpace := a.filter b.contains +def diff (a b : PathSpace) : PathSpace := a.filter (!b.contains ·) +def symDiff (a b : PathSpace) : PathSpace := union (diff a b) (diff b a) +def product (a b : PathSpace) : PathSpace := a.flatMap fun p => b.map (p ++ ·) +def wrap (p : Path) (a : PathSpace) : PathSpace := a.map (p ++ ·) +def unwrap (a : PathSpace) (p : Path) : PathSpace := a.filterMap (Path.stripPrefix p) +def restrict (a p : PathSpace) : PathSpace := a.filter fun x => p.any (· ≼ x) +def raffinate (a p : PathSpace) : PathSpace := diff a (restrict a p) +def live (p a : PathSpace) : PathSpace := p.filter fun x => a.any (x ≼ ·) +def head (a : PathSpace) : PathSpace := a.filterMap fun p => p.head?.map (fun b => [b]) +def tails (a : PathSpace) : PathSpace := a.filterMap fun p => match p with + | [] => none + | _ :: ps => some ps + +def divergence (a b : PathSpace) : PathSpace := a.flatMap fun p => b.filterMap (Path.divergence p) +/-- Fold pairs whose second prefix properly extends the first. -/ +def properOverlap (a b : PathSpace) (f : Path → Path → PathSpace) : PathSpace := + a.flatMap fun u => b.flatMap fun v => match Path.stripPrefix u v with + | some r@(_ :: _) => f u r + | _ => [] + +def branches (a : PathSpace) : PathSpace := divergence a a +/-- Prefix-minimal members. -/ +def basis (a : PathSpace) : PathSpace := a.filter fun p => !(a.any fun q => q != p && q ≼ p) +/-- Prefix-maximal members. -/ +def hull (a : PathSpace) : PathSpace := a.filter fun p => !(a.any fun q => q != p && p ≼ q) +def interior (a : PathSpace) : PathSpace := diff a (hull a) +def completion (a : PathSpace) : PathSpace := union a (branches a) +def lcpProduct (a b : PathSpace) : PathSpace := a.flatMap fun p => b.map (Path.lcp p) +def power (a : PathSpace) : Nat → PathSpace + | 0 => [[]] + | n + 1 => product a (power a n) +def branchIter (a : PathSpace) : Nat → PathSpace + | 0 => a + | n + 1 => branches (branchIter a n) +/-- Cardinality counts distinct members, independently of their lexical order. -/ +def count (a : PathSpace) : Nat := a.eraseDups.length +def height (a : PathSpace) : Nat := (a.map List.length).foldl max 0 +def commonPrefix (a : PathSpace) : Path := match a with + | [] => [] + | p :: ps => ps.foldl Path.lcp p +def prefixFree (a : PathSpace) : Bool := equiv a (basis a) +def covers (a b : PathSpace) : Bool := a.all fun p => b.any (p ≼ ·) + +/-- Independent head-recursive definitions, fueled by maximum length + 1. -/ +def divergenceRec : Nat → PathSpace → PathSpace → PathSpace + | 0, _, _ => [] + | n + 1, a, b => + let ha := normalize (head a) + let hb := normalize (head b) + let root := if ha.any (fun x => hb.any (· != x)) then [[]] else [] + root ++ (inter ha hb).flatMap fun p => wrap p (divergenceRec n (unwrap a p) (unwrap b p)) +def basisRec : Nat → PathSpace → PathSpace + | 0, _ => [] + | n + 1, a => if a.contains [] then [[]] else + (normalize (head a)).flatMap fun p => wrap p (basisRec n (unwrap a p)) +def hullRec : Nat → PathSpace → PathSpace + | 0, _ => [] + | n + 1, a => + let root := if a.contains [] && (head a).isEmpty then [[]] else [] + root ++ (normalize (head a)).flatMap fun p => wrap p (hullRec n (unwrap a p)) +def liveRec : Nat → PathSpace → PathSpace → PathSpace + | 0, _, _ => [] + | n + 1, p, a => + let root := if p.contains [] && !a.isEmpty then [[]] else [] + root ++ (normalize (inter (head p) (head a))).flatMap fun q => + wrap q (liveRec n (unwrap p q) (unwrap a q)) + +def ofMap {V : Type} (t : PathMap V) : PathSpace := t.vals.map (·.1) + +/-- General witness theorem, not a bounded check. -/ +theorem mem_divergence (a b : PathSpace) (p : Path) : + p ∈ divergence a b ↔ ∃ x ∈ a, ∃ y ∈ b, Path.divergence x y = some p := by + simp [divergence, List.mem_flatMap, List.mem_filterMap] + +theorem divergence_comm (a b : PathSpace) (p : Path) : + p ∈ divergence a b ↔ p ∈ divergence b a := by + simp only [mem_divergence] + constructor + · rintro ⟨x, hx, y, hy, h⟩ + exact ⟨y, hy, x, hx, (Path.divergence_comm y x).trans h⟩ + · rintro ⟨y, hy, x, hx, h⟩ + exact ⟨x, hx, y, hy, (Path.divergence_comm x y).trans h⟩ + +@[simp] theorem divergence_empty_left (a : PathSpace) : divergence [] a = [] := rfl +@[simp] theorem divergence_empty_right (a : PathSpace) : divergence a [] = [] := by simp [divergence] +@[simp] theorem divergence_epsilon_left (a : PathSpace) : divergence [[]] a = [] := by simp [divergence] +@[simp] theorem divergence_epsilon_right (a : PathSpace) : divergence a [[]] = [] := by simp [divergence] + +theorem divergence_union_left (a b c : PathSpace) : + divergence (union a b) c = union (divergence a c) (divergence b c) := by + simp [divergence, union] + +theorem divergence_union_right (a b c : PathSpace) (p : Path) : + p ∈ divergence a (union b c) ↔ p ∈ union (divergence a b) (divergence a c) := by + simp only [union, List.mem_append, mem_divergence] + constructor + · rintro ⟨x, hx, y, hy | hy, h⟩ + · exact Or.inl ⟨x, hx, y, hy, h⟩ + · exact Or.inr ⟨x, hx, y, hy, h⟩ + · rintro (⟨x, hx, y, hy, h⟩ | ⟨x, hx, y, hy, h⟩) + · exact ⟨x, hx, y, Or.inl hy, h⟩ + · exact ⟨x, hx, y, Or.inr hy, h⟩ + +theorem divergence_diagonal (a : PathSpace) : divergence a a = branches a := rfl + +theorem divergence_mono {a b c d : PathSpace} + (ha : ∀ p, p ∈ a → p ∈ c) (hb : ∀ p, p ∈ b → p ∈ d) : + ∀ p, p ∈ divergence a b → p ∈ divergence c d := by + intro p hp + obtain ⟨x, hx, y, hy, h⟩ := (mem_divergence a b p).mp hp + exact (mem_divergence c d p).mpr ⟨x, ha x hx, y, hb y hy, h⟩ + +theorem mem_basis (a : PathSpace) (p : Path) : + p ∈ basis a ↔ p ∈ a ∧ ∀ q ∈ a, q ≠ p → (q ≼ p) = false := by + simp [basis, List.mem_filter, Bool.not_eq_true, List.any_eq_false] + +theorem mem_hull (a : PathSpace) (p : Path) : + p ∈ hull a ↔ p ∈ a ∧ ∀ q ∈ a, q ≠ p → (p ≼ q) = false := by + simp [hull, List.mem_filter, Bool.not_eq_true, List.any_eq_false] +end PathSpace + +namespace Map + +def basis {V : Type} (t : PathMap V) : PathMap V := + let support := PathSpace.basis (PathSpace.ofMap t) + PathMap.mk' (t.vals.filter (fun kv => support.contains kv.1)) [] +def hull {V : Type} (t : PathMap V) : PathMap V := + let support := PathSpace.hull (PathSpace.ofMap t) + PathMap.mk' (t.vals.filter (fun kv => support.contains kv.1)) [] +def divergence {V W : Type} (a : PathMap V) (b : PathMap W) : PathMap Unit := + PathMap.mk' ((PathSpace.divergence (PathSpace.ofMap a) (PathSpace.ofMap b)).map (·, ())) [] +def branches {V : Type} (a : PathMap V) : PathMap Unit := divergence a a +end Map + +namespace Zip +/-- Relative focus semantics; input and output cursor positions are unchanged. -/ +def basis {V : Type} (src out : Zip V) : Zip V := out.graftMap (Map.basis src.makeMap) +def hull {V : Type} (src out : Zip V) : Zip V := out.graftMap (Map.hull src.makeMap) +def divergence {V W : Type} (a : Zip V) (b : Zip W) (out : Zip Unit) : Zip Unit := + out.graftMap (Map.divergence a.makeMap b.makeMap) +def branches {V : Type} (src : Zip V) (out : Zip Unit) : Zip Unit := + out.graftMap (Map.branches src.makeMap) +end Zip +end PathMapModel From 594774c9ec15a24f6aed40cce24d4fce82124f50 Mon Sep 17 00:00:00 2001 From: adamv-symbolica Date: Tue, 17 Nov 2026 11:38:04 +0000 Subject: [PATCH 02/15] Add zipper basis, hull, branches, and divergence Traverse valued paths with explicit stacks and restore all zipper focuses. Termination does not count as a branch, and dangling structure supplies no valued witness. Preserve source payloads for basis and hull. Exercise the Lean law catalogue as Rust expressions and compare with an independent path-set oracle, including movement-count and focus tests. --- src/experimental.rs | 3 + src/experimental/path_sets.rs | 308 +++++++++++++++ tests/path_sets.rs | 318 ++++++++++++++++ tests/pathmap_algebra_differential.rs | 3 + tests/support/path_set_laws.rs | 529 ++++++++++++++++++++++++++ 5 files changed, 1161 insertions(+) create mode 100644 src/experimental/path_sets.rs create mode 100644 tests/path_sets.rs create mode 100644 tests/support/path_set_laws.rs diff --git a/src/experimental.rs b/src/experimental.rs index a6eb71c7..92c501e3 100644 --- a/src/experimental.rs +++ b/src/experimental.rs @@ -12,6 +12,9 @@ use crate::write_zipper::write_zipper_priv::WriteZipperPriv; #[cfg(feature = "serialization")] pub mod serialization; +/// Prefix basis, hull, branches, and cross-space divergence. +pub mod path_sets; + #[cfg(feature = "zipper_alg")] pub mod zipper_algebra; #[cfg(not(feature = "zipper_alg"))] diff --git a/src/experimental/path_sets.rs b/src/experimental/path_sets.rs new file mode 100644 index 00000000..afeeb727 --- /dev/null +++ b/src/experimental/path_sets.rs @@ -0,0 +1,308 @@ +//! Prefix extrema and divergences of **valued** paths. +//! +//! A dangling path is not a set member. Termination is not a branch: `foo` +//! and `food` have no divergence. Basis and hull retain the original values; +//! divergence and branches return unit-valued maps. +//! +//! All traversals use zipper movements and explicit heap stacks, never pairs +//! of keys, recursive Rust calls, repeated root lookups, or subtree `val_count`. +//! Replacing an existing output additionally pays its destruction/COW cost. +//! +//! ``` +//! use pathmap::{PathMap, experimental::path_sets::{basis, hull, divergence}}; +//! let mut words = PathMap::single("foo", 1); +//! words.set_val_at("food", 2); +//! assert!(basis(&words).contains("foo")); +//! assert!(!basis(&words).contains("food")); +//! assert!(hull(&words).contains("food")); +//! let points = divergence(&words, &PathMap::single("four", ())); +//! assert!(points.contains("fo")); +//! ``` + +use crate::{ + PathMap, + alloc::Allocator, + utils::{BitMask, ByteMask}, + zipper::*, +}; + +fn pop_byte(mask: &mut ByteMask) -> Option { + let byte = mask.indexed_bit::(0)?; + mask.clear_bit(byte); + Some(byte) +} + +fn clear_output>(out: &mut Out) { + out.remove_branches(false); + out.remove_val(false); +} + +struct UnaryFrame { + remaining: ByteMask, + live_children: usize, +} + +fn unary_frame(src: &Z, stop_at_value: bool) -> UnaryFrame { + UnaryFrame { + remaining: if stop_at_value && src.is_val() { + ByteMask::EMPTY + } else { + src.child_mask() + }, + live_children: 0, + } +} + +// Postorder, with a preorder cut for basis. Both zippers return to their +// entry focus, including when that focus is absent or is below the zipper root. +fn walk_unary( + src: &mut Z, + out: &mut Out, + stop_at_value: bool, + mut emit: impl FnMut(&Z, &mut Out, usize), +) { + let mut stack = vec![unary_frame(src, stop_at_value)]; + loop { + if let Some(byte) = pop_byte(&mut stack.last_mut().unwrap().remaining) { + src.descend_to_byte(byte); + out.descend_to_byte(byte); + stack.push(unary_frame(src, stop_at_value)); + } else { + let frame = stack.pop().unwrap(); + emit(src, out, frame.live_children); + let live = src.is_val() || frame.live_children != 0; + let Some(parent) = stack.last_mut() else { + break; + }; + parent.live_children += usize::from(live); + src.ascend(1); + out.ascend(1); + } + } +} + +/// Replace the output focus subtree with the prefix-minimal valued paths of +/// the input focus subtree, preserving payloads. All focuses are restored. +/// +/// Runs in O(P_basis + output + value cloning), with O(h) traversal storage, +/// where P_basis counts visited byte-prefix positions. Descendants of the first +/// value on each branch are skipped, including all descendants of a root value. +pub fn zipper_basis(src: &mut Z, out: &mut Out) +where + V: Clone + Send + Sync, + A: Allocator, + Z: ZipperMoving + ZipperValues, + Out: ZipperWriting, +{ + clear_output(out); + walk_unary(src, out, true, |src, out, _| { + if let Some(value) = src.val() { + out.set_val(value.clone()); + } + }); +} + +/// Replace the output focus subtree with the prefix-maximal valued paths of +/// the input focus subtree, preserving payloads. All focuses are restored. +/// +/// Runs in O(P + output + value cloning), with O(h) traversal storage. A value +/// with only dangling descendants is retained. Each structural byte edge is +/// traversed once down and once up; descendant counts are never recomputed. +pub fn zipper_hull(src: &mut Z, out: &mut Out) +where + V: Clone + Send + Sync, + A: Allocator, + Z: ZipperMoving + ZipperValues, + Out: ZipperWriting, +{ + clear_output(out); + walk_unary(src, out, false, |src, out, live_children| { + if live_children == 0 { + if let Some(value) = src.val() { + out.set_val(value.clone()); + } + } + }); +} + +/// Replace the output focus subtree with all prefixes having two different +/// next bytes leading to values in the input. A terminal is not a next byte. +/// Runs in O(P + output), with O(h) traversal storage; restores both focuses. +pub fn zipper_branches(src: &mut Z, out: &mut Out) +where + A: Allocator, + Z: ZipperMoving, + Out: ZipperWriting<(), A>, +{ + clear_output(out); + walk_unary(src, out, false, |_, out, live_children| { + if live_children >= 2 { + out.set_val(()); + } + }); +} + +// A one-sided fringe only needs one witness. Do not walk its remaining values. +// Distinct fringe calls cover disjoint subtrees, so this cannot cause quadratic +// rescanning. The entry focus is restored even on an early successful return. +fn has_value(src: &mut Z) -> bool { + let initial_depth = src.depth(); + let mut stack = Vec::new(); + loop { + if src.is_val() { + src.ascend(src.depth() - initial_depth); + return true; + } + stack.push(src.child_mask()); + loop { + if let Some(byte) = pop_byte(stack.last_mut().unwrap()) { + src.descend_to_byte(byte); + break; + } + stack.pop(); + if stack.is_empty() { + return false; + } + src.ascend(1); + } + } +} + +struct BinaryFrame { + left: ByteMask, + right: ByteMask, + remaining: ByteMask, + live_left: ByteMask, + live_right: ByteMask, + incoming: u8, +} + +impl BinaryFrame { + fn new(left: &L, right: &R, incoming: u8) -> Self { + let left = left.child_mask(); + let right = right.child_mask(); + Self { + left, + right, + remaining: left.or(&right), + live_left: ByteMask::EMPTY, + live_right: ByteMask::EMPTY, + incoming, + } + } +} + +/// Replace the output focus subtree with cross-space divergences. The inputs +/// may carry different payload types; only value presence is observed. +/// +/// An output p needs a valued left path p.a.x and a valued right path p.b.y +/// with a != b. A value at p does not contribute a next byte. All three focuses +/// are restored and no input is modified. +/// +/// O(C + F + output) time and O(h) traversal storage: C is the number of common +/// structural byte-prefix positions, and F is the number of positions scanned +/// to find one valued witness in each one-sided fringe subtree. Always +/// C + F = O(P_left + P_right). Dangling fringes may require a full scan; for +/// valued fringes the scan stops at the first value. These bounds count logical +/// byte prefixes, not compressed physical nodes or unique shared DAG nodes. +/// Replacing a nonempty output also costs its destruction/COW work. +pub fn zipper_divergence(left: &mut L, right: &mut R, out: &mut Out) +where + A: Allocator, + L: ZipperMoving, + R: ZipperMoving, + Out: ZipperWriting<(), A>, +{ + clear_output(out); + if left.child_count() == 0 || right.child_count() == 0 { + return; + } + let mut stack = vec![BinaryFrame::new(left, right, 0)]; + loop { + let frame = stack.last_mut().unwrap(); + if let Some(byte) = pop_byte(&mut frame.remaining) { + let in_left = frame.left.test_bit(byte); + let in_right = frame.right.test_bit(byte); + if in_left && in_right { + left.descend_to_byte(byte); + right.descend_to_byte(byte); + out.descend_to_byte(byte); + stack.push(BinaryFrame::new(left, right, byte)); + } else if in_left { + left.descend_to_byte(byte); + if has_value(left) { + frame.live_left.set_bit(byte); + } + left.ascend(1); + } else { + right.descend_to_byte(byte); + if has_value(right) { + frame.live_right.set_bit(byte); + } + right.ascend(1); + } + } else { + let frame = stack.pop().unwrap(); + let left_child = !frame.live_left.is_empty_mask(); + let right_child = !frame.live_right.is_empty_mask(); + if left_child && right_child && frame.live_left.or(&frame.live_right).count_bits() >= 2 + { + out.set_val(()); + } + let left_live = left.is_val() || left_child; + let right_live = right.is_val() || right_child; + let Some(parent) = stack.last_mut() else { + break; + }; + if left_live { + parent.live_left.set_bit(frame.incoming); + } + if right_live { + parent.live_right.set_bit(frame.incoming); + } + left.ascend(1); + right.ascend(1); + out.ascend(1); + } + } +} + +/// Prefix-minimal valued paths, with original payloads and allocator. +pub fn basis(src: &PathMap) -> PathMap { + let mut out = PathMap::new_in(src.alloc.clone()); + zipper_basis(&mut src.read_zipper(), &mut out.write_zipper()); + out +} + +/// Prefix-maximal valued paths, with original payloads and allocator. +pub fn hull(src: &PathMap) -> PathMap { + let mut out = PathMap::new_in(src.alloc.clone()); + zipper_hull(&mut src.read_zipper(), &mut out.write_zipper()); + out +} + +/// Cross-space divergences, marked with unit, using the left allocator. +pub fn divergence(left: &PathMap, right: &PathMap) -> PathMap<(), A> +where + V: Clone + Send + Sync + Unpin, + W: Clone + Send + Sync + Unpin, + A: Allocator, + B: Allocator, +{ + let mut out = PathMap::new_in(left.alloc.clone()); + zipper_divergence( + &mut left.read_zipper(), + &mut right.read_zipper(), + &mut out.write_zipper(), + ); + out +} + +/// All branch points of valued paths, marked with unit. +pub fn branches( + src: &PathMap, +) -> PathMap<(), A> { + let mut out = PathMap::new_in(src.alloc.clone()); + zipper_branches(&mut src.read_zipper(), &mut out.write_zipper()); + out +} diff --git a/tests/path_sets.rs b/tests/path_sets.rs new file mode 100644 index 00000000..a8a779eb --- /dev/null +++ b/tests/path_sets.rs @@ -0,0 +1,318 @@ +use pathmap::{ + PathMap, + experimental::path_sets::*, + utils::{BitMask, ByteMask}, + zipper::*, +}; +use std::{cell::Cell, collections::BTreeSet}; + +type Space = BTreeSet>; +fn map(s: &Space) -> PathMap<()> { + let mut m = PathMap::new(); + for p in s { + m.set_val_at(p, ()); + } + m +} +fn keys(m: &PathMap) -> Space { + m.iter().map(|(p, _)| p).collect() +} +fn assert_value_supported(m: &PathMap) { + let mut z = m.read_zipper(); + loop { + assert!( + z.at_root() || z.child_count() != 0 || z.is_val(), + "output has a dangling tip" + ); + if !z.to_next_step() { + break; + } + } +} + +fn oracle(a: &Space, b: &Space) -> Space { + a.iter() + .flat_map(|p| { + b.iter().filter_map(move |q| { + let n = p.iter().zip(q).take_while(|(x, y)| x == y).count(); + (n < p.len().min(q.len())).then(|| p[..n].to_vec()) + }) + }) + .collect() +} +fn spaces() -> Vec { + let ps = [ + vec![], + vec![0], + vec![1], + vec![0, 0], + vec![0, 1], + vec![1, 0], + vec![1, 1], + ]; + (0..128) + .map(|mask| { + ps.iter() + .enumerate() + .filter(|(i, _)| mask & (1 << i) != 0) + .map(|(_, p)| p.clone()) + .collect() + }) + .collect() +} + +#[test] +fn exhaustive_binary_spaces() { + let spaces = spaces(); + let maps: Vec<_> = spaces.iter().map(map).collect(); + for (a, ma) in spaces.iter().zip(&maps) { + let min: Space = a + .iter() + .filter(|p| !a.iter().any(|q| q != *p && p.starts_with(q))) + .cloned() + .collect(); + let max: Space = a + .iter() + .filter(|p| !a.iter().any(|q| q != *p && q.starts_with(p))) + .cloned() + .collect(); + assert_value_supported(&basis(ma)); + assert_value_supported(&hull(ma)); + assert_value_supported(&branches(ma)); + assert_eq!(keys(&basis(ma)), min); + assert_eq!(keys(&hull(ma)), max); + assert_eq!(keys(&branches(ma)), oracle(a, a)); + for (b, mb) in spaces.iter().zip(&maps) { + assert_eq!(keys(&divergence(ma, mb)), oracle(a, b), "{a:?}, {b:?}"); + } + } +} + +#[test] +fn values_dangling_paths_and_termination() { + let mut a = PathMap::new(); + for (p, v) in [("foo", 10), ("food", 20), ("four", 30)] { + a.set_val_at(p, v); + } + a.write_zipper_at_path(b"food/empty").create_path(); + a.write_zipper_at_path(b"x/empty").create_path(); + assert_eq!( + basis(&a).iter().map(|(p, v)| (p, *v)).collect::>(), + vec![(b"foo".to_vec(), 10), (b"four".to_vec(), 30)] + ); + assert_eq!( + hull(&a).iter().map(|(p, v)| (p, *v)).collect::>(), + vec![(b"food".to_vec(), 20), (b"four".to_vec(), 30)] + ); + assert_eq!(keys(&branches(&a)), [b"fo".to_vec()].into()); + let b = PathMap::single("foo", "different payload type"); + assert!(divergence(&b, &PathMap::single("food", ())).is_empty()); + let mut bare = PathMap::<()>::new(); + bare.write_zipper_at_path(b"four").create_path(); + assert!(divergence(&a, &bare).is_empty()); + assert!(basis(&bare).is_empty()); + assert!(hull(&bare).is_empty()); + assert!(branches(&bare).is_empty()); + a.set_val_at([], 99); + assert_eq!( + basis(&a).iter().map(|(p, v)| (p, *v)).collect::>(), + vec![(vec![], 99)] + ); +} + +#[test] +fn focus_relative_replacement_and_restoration() { + let mut a = PathMap::new(); + a.set_val_at("left/aa", 1); + a.set_val_at("left/ab", 2); + a.set_val_at("outside", 3); + let b = PathMap::single("right/b", ()); + let mut out = PathMap::single("keep", ()); + out.set_val_at("dest/stale", ()); + let mut l = a.read_zipper(); + l.descend_to("left/"); + let mut r = b.read_zipper(); + r.descend_to("right/"); + { + let mut o = out.write_zipper(); + o.descend_to("dest/"); + zipper_divergence(&mut l, &mut r, &mut o); + assert_eq!(l.path(), b"left/"); + assert_eq!(r.path(), b"right/"); + assert_eq!(o.path(), b"dest/"); + } + assert_eq!(keys(&out), [b"dest/".to_vec(), b"keep".to_vec()].into()); + let mut result = PathMap::single("keep", 7); + result.set_val_at("dest/stale", 8); + { + let mut o = result.write_zipper_at_path(b"dest/"); + zipper_hull(&mut l, &mut o); + assert_eq!(l.path(), b"left/"); + assert!(o.at_root()); + } + assert_eq!( + keys(&result), + [b"dest/aa".to_vec(), b"dest/ab".to_vec(), b"keep".to_vec()].into() + ); + l.descend_to("absent"); + { + let mut o = result.write_zipper_at_path(b"dest/"); + zipper_basis(&mut l, &mut o); + assert_eq!(l.path(), b"left/absent"); + assert!(o.at_root()); + } + assert_eq!(keys(&result), [b"keep".to_vec()].into()); +} + +#[test] +fn deep_compressed_stem_and_all_bytes() { + // Match the core long-key test's dense-only depth limit: those nodes + // expand every byte and use recursive teardown. + let depth = if cfg!(feature = "all_dense_nodes") { + 2048 + } else { + 20_000 + }; + let stem = vec![42; depth]; + let mut p = stem.clone(); + p.push(0); + let mut q = stem.clone(); + q.push(255); + let a = PathMap::single(&p, ()); + let b = PathMap::single(&q, ()); + assert_eq!(keys(&divergence(&a, &b)), [stem].into()); + let mut dense = PathMap::new(); + for byte in 0..=255u8 { + dense.set_val_at([byte], byte); + } + assert_eq!(keys(&branches(&dense)), [vec![]].into()); + assert_eq!(keys(&basis(&dense)), keys(&dense)); + assert_eq!(keys(&hull(&dense)), keys(&dense)); +} + +// A virtual binary trie with exact movement counts. It can describe 2^h values +// without allocating them, and panics if an algorithm requests val_count. +struct Counted { + path: Vec, + height: usize, + offset: u8, + root_value: bool, + leaf_values: bool, + moves: usize, + masks: Cell, +} +impl Counted { + fn new(height: usize) -> Self { + Self { + path: vec![], + height, + offset: 0, + root_value: false, + leaf_values: true, + moves: 0, + masks: Cell::new(0), + } + } +} +impl Zipper for Counted { + fn path_exists(&self) -> bool { + self.path.len() <= self.height + } + fn is_val(&self) -> bool { + (self.root_value && self.path.is_empty()) + || (self.leaf_values && self.path.len() == self.height) + } + fn child_count(&self) -> usize { + if self.path.len() < self.height { 2 } else { 0 } + } + fn child_mask(&self) -> ByteMask { + self.masks.set(self.masks.get() + 1); + let mut m = ByteMask::EMPTY; + if self.child_count() != 0 { + m.set_bit(self.offset); + m.set_bit(self.offset + 1); + } + m + } +} +impl ZipperValues<()> for Counted { + fn val(&self) -> Option<&()> { + self.is_val().then_some(&()) + } +} +impl ZipperMoving for Counted { + fn depth(&self) -> usize { + self.path.len() + } + fn focus_byte(&self) -> Option { + self.path.last().copied() + } + fn val_count(&self) -> usize { + panic!("subtree recount would break the bound") + } + fn descend_to>(&mut self, k: K) { + self.moves += k.as_ref().len(); + self.path.extend_from_slice(k.as_ref()); + } + fn ascend(&mut self, steps: usize) -> usize { + let n = steps.min(self.path.len()); + self.moves += n; + self.path.truncate(self.path.len() - n); + n + } + fn ascend_until(&mut self) -> usize { + self.ascend(1) + } + fn ascend_until_branch(&mut self) -> usize { + self.ascend(1) + } +} + +#[test] +fn linear_work_and_basis_cutoff() { + for h in 2..=9 { + let n = (1 << (h + 1)) - 1; + let mut a = Counted::new(h); + let mut out = PathMap::new(); + zipper_hull(&mut a, &mut out.write_zipper()); + assert_eq!(a.moves, 2 * (n - 1)); + assert_eq!(a.masks.get(), n); + assert_eq!(out.val_count(), 1 << h); + let mut a = Counted::new(h); + let mut b = Counted::new(h); + zipper_divergence(&mut a, &mut b, &mut out.write_zipper()); + assert_eq!(a.moves + b.moves, 4 * (n - 1)); + assert_eq!(out.val_count(), (1 << h) - 1); + assert_eq!(a.depth() + b.depth(), 0); + } + let mut a = Counted::new(1_000_000); + a.root_value = true; + let mut out = PathMap::new(); + zipper_basis(&mut a, &mut out.write_zipper()); + assert_eq!(a.moves, 0); + assert_eq!(a.masks.get(), 0); + assert!(out.contains([])); +} + +#[test] +fn disjoint_fringe_stops_at_first_value_and_empty_annihilates() { + let mut a = Counted::new(30); + let mut b = Counted::new(30); + b.offset = 2; + let mut out = PathMap::new(); + zipper_divergence(&mut a, &mut b, &mut out.write_zipper()); + assert_eq!(keys(&out), [vec![]].into()); + assert!(a.moves + b.moves <= 8 * 30); + let mut empty = Counted::new(0); + empty.leaf_values = false; + let mut enormous = Counted::new(1_000_000); + zipper_divergence(&mut enormous, &mut empty, &mut out.write_zipper()); + assert_eq!(enormous.moves, 0); + assert!(out.is_empty()); + let mut bare = Counted::new(8); + bare.leaf_values = false; + let mut actual = Counted::new(8); + zipper_divergence(&mut bare, &mut actual, &mut out.write_zipper()); + assert!(out.is_empty()); + assert_eq!(bare.moves + actual.moves, 4 * ((1 << 9) - 2)); +} diff --git a/tests/pathmap_algebra_differential.rs b/tests/pathmap_algebra_differential.rs index 1f0a2d6c..d4369aa9 100644 --- a/tests/pathmap_algebra_differential.rs +++ b/tests/pathmap_algebra_differential.rs @@ -336,3 +336,6 @@ fn wide_restricted_by_sparse_matches_btreeset_oracle() { assert_eq!(set_from_map(&stems), expected, "WriteZipper::restricting seed {seed}"); } } + +#[path = "support/path_set_laws.rs"] +mod path_set_laws; diff --git a/tests/support/path_set_laws.rs b/tests/support/path_set_laws.rs new file mode 100644 index 00000000..cbdb9e85 --- /dev/null +++ b/tests/support/path_set_laws.rs @@ -0,0 +1,529 @@ +//! The full named Lean catalogue, evaluated as Rust PathMap expressions. +//! Shared seeded generators come from the existing algebra differential suite. +use super::{KeySet, map_from_set, next_u64, prefix_heavy_set, set_from_map, wide_set}; +use pathmap::{ + PathMap, + experimental::path_sets::{basis, branches as br, divergence as d, hull}, + zipper::*, +}; +use std::collections::BTreeSet; +type M = PathMap<()>; +fn e() -> M { + M::single([], ()) +} +fn count(a: &M) -> usize { + a.val_count() +} +fn height(a: &M) -> usize { + a.iter().map(|(p, _)| p.len()).max().unwrap_or(0) +} +fn interior(a: &M) -> M { + a.subtract(&hull(a)) +} +fn completion(a: &M) -> M { + a.join(&br(a)) +} +fn raff(a: &M, p: &M) -> M { + a.subtract(&a.restrict(p)) +} +fn sym(a: &M, b: &M) -> M { + a.subtract(b).join(&b.subtract(a)) +} +fn covers(a: &M, b: &M) -> bool { + a.iter() + .all(|(p, _)| b.iter().any(|(q, _)| q.starts_with(&p))) +} +fn prefix_free(a: &M) -> bool { + set_from_map(a) == set_from_map(&basis(a)) +} +fn wrap(p: &[u8], a: &M) -> M { + let mut out = M::new(); + let mut z = out.write_zipper_at_path(p); + z.join_map_into(a.clone()); + // Make the helper independent of the graft_root_vals feature. + if a.get([]).is_some() { + z.set_val(()); + } + out +} +fn unwrap(a: &M, p: &[u8]) -> M { + let z = a.read_zipper_at_path(p); + let mut out = z.make_map(); + if z.is_val() { + out.set_val_at([], ()); + } + out +} +fn product(a: &M, b: &M) -> M { + let mut out = M::new(); + for (p, _) in a.iter() { + let mut z = out.write_zipper_at_path(&p); + z.join_map_into(b.clone()); + if b.get([]).is_some() { + z.set_val(()); + } + } + out +} +fn live(p: &M, a: &M) -> M { + let mut out = M::new(); + for (q, _) in p.iter() { + if a.read_zipper_at_path(&q).val_count() != 0 { + out.set_val_at(q, ()); + } + } + out +} +fn head(a: &M) -> M { + let mut out = M::new(); + for (p, _) in a.iter() { + if let Some(&c) = p.first() { + out.set_val_at([c], ()); + } + } + out +} +fn tails(a: &M) -> M { + let mut out = M::new(); + for (p, _) in a.iter() { + if !p.is_empty() { + out.set_val_at(&p[1..], ()); + } + } + out +} +fn lcp(a: &[u8], b: &[u8]) -> Vec { + a[..a.iter().zip(b).take_while(|(x, y)| x == y).count()].to_vec() +} +fn lcp_product(a: &M, b: &M) -> M { + let mut out = M::new(); + for (p, _) in a.iter() { + for (q, _) in b.iter() { + out.set_val_at(lcp(&p, &q), ()); + } + } + out +} +fn common_prefix(a: &M) -> Vec { + let mut it = a.iter(); + let Some((p, _)) = it.next() else { + return vec![]; + }; + it.fold(p, |p, (q, _)| lcp(&p, &q)) +} +fn power(a: &M, n: usize) -> M { + (0..n).fold(e(), |b, _| product(a, &b)) +} +fn branch_iter(a: &M, n: usize) -> M { + (0..n).fold(a.clone(), |b, _| br(&b)) +} +// Independent recursive specifications (no call to the operation under test). +fn basis_rec(a: &M) -> M { + if a.get([]).is_some() { + return e(); + } + head(a).iter().fold(M::new(), |out, (p, _)| { + out.join(&wrap(&p, &basis_rec(&unwrap(a, &p)))) + }) +} +fn hull_rec(a: &M) -> M { + let h = head(a); + let root = if a.get([]).is_some() && h.is_empty() { + e() + } else { + M::new() + }; + h.iter().fold(root, |out, (p, _)| { + out.join(&wrap(&p, &hull_rec(&unwrap(a, &p)))) + }) +} +fn divergence_rec(a: &M, b: &M) -> M { + let ha = head(a); + let hb = head(b); + let cross = ha.iter().any(|(p, _)| hb.iter().any(|(q, _)| p != q)); + let root = if cross { e() } else { M::new() }; + ha.meet(&hb).iter().fold(root, |out, (p, _)| { + out.join(&wrap(&p, &divergence_rec(&unwrap(a, &p), &unwrap(b, &p)))) + }) +} +fn live_rec(p: &M, a: &M) -> M { + let root = if p.get([]).is_some() && !a.is_empty() { + e() + } else { + M::new() + }; + head(p).meet(&head(a)).iter().fold(root, |out, (q, _)| { + out.join(&wrap(&q, &live_rec(&unwrap(p, &q), &unwrap(a, &q)))) + }) +} +fn overlaps(a: &M, b: &M, x: &M, y: &M) -> M { + let mut out = M::new(); + for (p, _) in a.iter() { + for (q, _) in b.iter() { + if q.len() > p.len() && q.starts_with(&p) { + out = out.join(&wrap(&p, &d(x, &wrap(&q[p.len()..], y)))); + } + if p.len() > q.len() && p.starts_with(&q) { + out = out.join(&wrap(&q, &d(&wrap(&p[q.len()..], x), y))); + } + } + } + out +} +#[derive(Default)] +struct Coverage(BTreeSet<&'static str>); +impl Coverage { + fn check(&mut self, name: &'static str, ok: bool) { + assert!(ok, "path-set law {name}"); + self.0.insert(name); + } + fn eq(&mut self, name: &'static str, a: &M, b: &M) { + assert_eq!(set_from_map(a), set_from_map(b), "path-set law {name}"); + self.0.insert(name); + } + fn sub(&mut self, name: &'static str, a: &M, b: &M) { + assert!( + set_from_map(a).is_subset(&set_from_map(b)), + "path-set law {name}: {:?} not subset of {:?}", + set_from_map(a), + set_from_map(b) + ); + self.0.insert(name); + } +} +fn laws(t: &mut Coverage, a: &M, b: &M, c: &M, f: &M) { + let x = d(a, b); + let ba = br(a); + let ha = hull(a); + let hb = hull(b); + let ca = completion(a); + let zero = M::new(); + let ep = e(); + let fork = M::single([0], ()).join(&M::single([1], ())); + t.eq("diagonal", &d(a, a), &ba); + t.eq("empty_left", &d(&zero, a), &zero); + t.eq("empty_right", &d(a, &zero), &zero); + t.eq("epsilon_left", &d(&ep, a), &zero); + t.eq("epsilon_right", &d(a, &ep), &zero); + t.eq("branch_completion", &br(&ca), &ba); + t.eq("completion_idempotent", &completion(&ca), &ca); + t.eq("branch_hull", &br(&ha), &ba); + t.eq("branch_epsilon", &br(&a.join(&ep)), &ba); + t.sub("branch_second_subset", &br(&ba), &ba); + t.eq("interior_branches", &d(a, &ba), &interior(&ba)); + t.sub("basis_subset", &basis(a), a); + t.sub("hull_subset", &ha, a); + t.eq("basis_idempotent", &basis(&basis(a)), &basis(a)); + t.eq("hull_idempotent", &hull(&ha), &ha); + t.eq("basis_of_hull", &basis(&ha), &ha); + t.eq("hull_of_basis", &hull(&basis(a)), &basis(a)); + t.check("basis_antichain", prefix_free(&basis(a))); + t.check("hull_antichain", prefix_free(&ha)); + t.check("basis_nonempty", basis(a).is_empty() == a.is_empty()); + t.check("hull_nonempty", ha.is_empty() == a.is_empty()); + t.check("basis_covers", covers(a, &ha) && covers(&basis(a), a)); + t.eq("basis_recursive", &basis_rec(a), &basis(a)); + t.eq("hull_recursive", &hull_rec(a), &ha); + t.eq("branch_recursive", &divergence_rec(a, a), &ba); + t.check("maximal_branch_count", count(&hull(&ba)) <= count(&ha) / 2); + if !a.is_empty() { + t.check( + "no_nonempty_branch_fixed_point", + set_from_map(&ba) != set_from_map(a), + ); + } + t.eq( + "branch_depth_nilpotence", + &branch_iter(a, height(a) + 1), + &zero, + ); + t.eq("symmetry", &x, &d(b, a)); + t.eq("terminal_invariance", &d(&a.join(&ep), &b.join(&ep)), &x); + t.eq("hull_invariance", &d(&ha, &hb), &x); + t.eq("completion_invariance", &d(&ca, &completion(b)), &x); + t.eq("branch_union", &br(&a.join(b)), &ba.join(&br(b)).join(&x)); + t.sub( + "branch_intersection_lower", + &br(&a.meet(b)), + &ba.meet(&br(b)), + ); + t.sub("branch_sandwich_lower", &ba.meet(&br(b)), &x); + t.sub("branch_sandwich_upper", &x, &br(&a.join(b))); + t.eq("output_completion", &completion(&x), &x); + t.eq("absorbed_branch_marks", &br(&a.join(&x)), &ba); + t.eq("nested_exact", &d(a, &x), &ba.meet(&interior(&x))); + t.eq("interior_exact", &d(&a.join(b), &x), &interior(&x)); + t.sub("interior_attribution", &interior(&x), &ba.join(&br(b))); + t.sub("output_branches", &br(&x), &x.meet(&ba.meet(&br(b)))); + if !x.is_empty() { + t.eq( + "first_divergence", + &basis(&x), + &M::single(common_prefix(&ha.join(&hb)), ()), + ); + } + let all_prefix = |u: &M, v: &M| { + u.iter() + .all(|(p, _)| v.iter().all(|(q, _)| q.starts_with(&p))) + }; + t.check( + "zero_criterion", + x.is_empty() + == (a.is_empty() + || b.is_empty() + || count(&ha) == 1 && all_prefix(&ha, &hb) + || count(&hb) == 1 && all_prefix(&hb, &ha)), + ); + t.eq("root_heads", &d(&head(a), &head(b)), &x.meet(&ep)); + t.sub("output_heads", &head(&x), &head(a).meet(&head(b))); + t.sub("tails_bound", &tails(&x), &d(&tails(a), &tails(b))); + t.eq("recursive_divergence", &divergence_rec(a, b), &x); + t.eq("live_recursive", &live_rec(a, b), &live(a, b)); + t.check( + "output_cardinality", + count(&x) <= count(&hull(&a.join(b))).saturating_sub(1), + ); + t.check( + "output_hull_cardinality", + count(&hull(&x)) <= count(&ha).min(count(&hb)), + ); + if !x.is_empty() { + t.check("output_depth", height(&x) < height(a).min(height(b))); + } + t.check("output_covered", covers(&x, a) && covers(&x, b)); + t.eq("fork_completion", &br(&product(a, &fork)), &ca); + let m = lcp_product(a, b); + t.eq("fork_lcp", &d(&product(a, &fork), &product(b, &fork)), &m); + t.eq("lcp_correction", &m, &x.join(&live(a, b)).join(&live(b, a))); + t.eq("lcp_diagonal", &lcp_product(a, a), &ca); + t.eq("lcp_symmetry", &m, &lcp_product(b, a)); + t.eq("lcp_output_completion", &completion(&m), &m); + t.eq("range_realization", &br(&product(&ca, &fork)), &ca); + t.eq( + "basis_union", + &basis(&a.join(b)), + &basis(&basis(a).join(&basis(b))), + ); + t.eq("hull_union", &hull(&a.join(b)), &hull(&ha.join(&hb))); + t.eq( + "restriction_basis_mask", + &a.restrict(b), + &a.restrict(&basis(b)), + ); + t.eq("left_union", &d(&a.join(b), c), &d(a, c).join(&d(b, c))); + t.eq("right_union", &d(a, &b.join(c)), &d(a, b).join(&d(a, c))); + t.sub( + "intersection_bound", + &d(&a.meet(b), c), + &d(a, c).meet(&d(b, c)), + ); + t.sub( + "difference_lower", + &d(a, c).subtract(&d(b, c)), + &d(&a.subtract(b), c), + ); + t.sub("difference_upper", &d(&a.subtract(b), c), &d(a, c)); + t.sub( + "symmetric_difference_bound", + &sym(&d(a, c), &d(b, c)), + &d(&sym(a, b), c), + ); + if set_from_map(a).is_subset(&set_from_map(b)) { + t.sub("monotonicity", &d(a, c), &d(b, c)); + } + if covers(a, b) { + t.sub("prefix_extension_monotonicity", &d(a, c), &d(b, c)); + } + if covers(b, a) { + t.eq("covered_mark_invariance", &d(&a.join(b), c), &d(a, c)); + } + t.sub("nested_absorption", &d(&x, c), &d(a, c).meet(&d(b, c))); + t.eq("witness_absorption", &d(&a.join(&x), c), &d(a, c)); + t.sub( + "branch_probe_exchange", + &x.meet(&br(c)), + &d(a, c).meet(&d(b, c)), + ); + t.eq( + "lcp_associativity", + &lcp_product(&m, c), + &lcp_product(a, &lcp_product(b, c)), + ); + t.eq( + "lcp_bilinearity", + &lcp_product(&a.join(b), c), + &lcp_product(a, c).join(&lcp_product(b, c)), + ); + t.eq( + "one_mask", + &d(&a.restrict(c), b), + &x.restrict(c).join(&d(&live(c, a), b)), + ); + t.eq( + "same_mask", + &d(&a.restrict(c), &b.restrict(c)), + &x.restrict(c).join(&d(&live(c, a), &live(c, b))), + ); + t.eq( + "filter_partition", + &x, + &d(&a.restrict(c), b).join(&d(&raff(a, c), b)), + ); + if prefix_free(a) && !b.is_empty() && !c.is_empty() { + t.eq( + "common_prefix_code", + &d(&product(a, b), &product(a, c)), + &ba.join(&product(a, &d(b, c))), + ); + } + t.sub( + "four_point_absorption", + &d(&x, &d(c, f)), + &d(a, c).meet(&d(a, f)).meet(&d(b, c)).meet(&d(b, f)), + ); + t.sub( + "four_point_exchange", + &x.meet(&d(c, f)), + &d(a, c).meet(&d(b, f)).join(&d(a, f).meet(&d(b, c))), + ); + t.eq( + "incremental_update", + &d(&a.join(c), &b.join(f)), + &x.join(&d(c, b)).join(&d(a, f)).join(&d(c, f)), + ); + t.eq( + "two_masks", + &d(&a.restrict(c), &b.restrict(f)), + &x.restrict(c) + .restrict(f) + .join(&d(a, &live(f, b)).restrict(c)) + .join(&d(&live(c, a), b).restrict(f)) + .join(&d(&live(c, a), &live(f, b))), + ); + t.sub( + "raffination_bound", + &d(&raff(a, c), &raff(b, f)), + &raff(&x, &c.join(f)), + ); + let prod_rhs = if c.is_empty() || f.is_empty() { + M::new() + } else { + x.join(&product(&a.meet(b), &d(c, f))) + .join(&overlaps(a, b, c, f)) + }; + t.eq( + "general_product", + &d(&product(a, c), &product(b, f)), + &prod_rhs, + ); + if prefix_free(&a.join(b)) && !c.is_empty() && !f.is_empty() { + t.eq( + "prefix_free_product", + &d(&product(a, c), &product(b, f)), + &x.join(&product(&a.meet(b), &d(c, f))), + ); + } + let mut paths = vec![vec![], vec![0], vec![0, 1, 0]]; + paths.extend(a.iter().take(2).map(|(p, _)| p)); + for p in paths { + let single = M::single(&p, ()); + let chain = d(&single, b); + t.eq("wrap", &d(&wrap(&p, a), &wrap(&p, b)), &wrap(&p, &x)); + t.eq( + "unwrap", + &d(&unwrap(a, &p), &unwrap(b, &p)), + &unwrap(&x, &p), + ); + t.eq( + "single_prefix_restriction", + &d(&a.restrict(&single), &b.restrict(&single)), + &x.restrict(&single), + ); + t.eq("singleton_chain", &br(&chain), &zero); + t.check("singleton_bound", count(&chain) <= p.len().min(count(&hb))); + t.sub("singleton_existing_branches", &interior(&chain), &br(b)); + t.check( + "singleton_branch_update", + count(&br(&b.join(&single)).subtract(&br(b))) <= 1, + ); + t.check( + "singleton_divergence_update", + count(&d(&a.join(&single), b).subtract(&x)) <= p.len().min(count(&hb)), + ); + } +} +fn power_laws(t: &mut Coverage, a: &M) { + for n in 0..=3 { + for m in 0..=3 { + if prefix_free(a) { + let rhs = + (0..m.min(n)).fold(M::new(), |out, i| out.join(&product(&power(a, i), &br(a)))); + t.eq("prefix_code_powers", &d(&power(a, m), &power(a, n)), &rhs); + } + if !branch_iter(a, n).is_empty() { + t.check("branch_leaf_bound", 2usize.pow(n as u32) <= count(&hull(a))); + } + } + } +} +fn small(seed: u64, salt: u64) -> KeySet { + let mut state = seed ^ salt; + let n = next_u64(&mut state) % 7; + (0..n) + .map(|_| { + let len = next_u64(&mut state) % 6; + (0..len) + .map(|_| ((next_u64(&mut state) >> 32) % 3) as u8) + .collect() + }) + .collect() +} +#[test] +fn seeded_full_path_set_law_catalogue() { + let mut t = Coverage::default(); + #[cfg(not(miri))] + let seeds = 256; + #[cfg(miri)] + let seeds = 2; + for seed in 0..seeds { + // Report the complete reproducible seed on any assertion failure. + let case = std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| { + let a = map_from_set(&small(seed, 11)); + let b = map_from_set(&small(seed, 23)); + let c = map_from_set(&small(seed, 47)); + let f = map_from_set(&small(seed, 97)); + laws(&mut t, &a, &b, &c, &f); + // Deliberate correlated operands exercise the guards non-vacuously. + laws(&mut t, &hull(&a), &hull(&a).join(&hull(&b)), &e(), &e()); + laws(&mut t, &a.join(&b), &b, &c, &f); + power_laws(&mut t, &hull(&a)); + })); + assert!( + case.is_ok(), + "full path-set law catalogue failed at seed {seed}" + ); + } + // Dense children and overlapping prefix terminals using existing fuzz generators. + for seed in 0..2 { + let a = map_from_set(&prefix_heavy_set(seed, 11)); + let b = map_from_set(&wide_set(seed, 23)); + laws(&mut t, &a, &b, &e(), &e()); + } + // Balanced depth-three binary trie exercises a nonempty third branch iterate. + let balanced: KeySet = (0..8) + .map(|i| vec![(i >> 2) & 1, (i >> 1) & 1, i & 1]) + .collect(); + power_laws(&mut t, &map_from_set(&balanced)); + // Ensure every catalogue name is executed, with guarded laws counted only + // when the guard is true. New Lean laws automatically require Rust coverage. + let catalog = include_str!("../../lean/PathMapModel/PathSetLaws.lean"); + let expected: BTreeSet<_> = catalog + .lines() + .filter_map(|line| { + let start = line.find("(\"")? + 2; + let tail = &line[start..]; + Some(&tail[..tail.find('"')?]) + }) + .collect(); + assert_eq!(t.0, expected, "Rust / Lean law catalogue coverage drift"); +} From 1666f5523d57656370010cf0e552d6b5d51b50a8 Mon Sep 17 00:00:00 2001 From: adamv-symbolica Date: Tue, 17 Nov 2026 11:38:04 +0000 Subject: [PATCH 03/15] Prove stable convex meet and subtraction in Lean Select common original tips for meet and unmasked original tips for subtraction. Retain the supporting interior values and prove equivalence to pruning until stable, including termination and confluence. Prove the semilattice, deletion-action, order, Boolean-pruning, geometric, and morphism laws, with valued-support adapters to maps and zipper focuses. Include counterexamples for laws requiring additional hypotheses. --- lean/PathMapModel.lean | 1 + lean/PathMapModel/Convex.lean | 212 +++++++++++++++++++++++++ lean/PathMapModel/ConvexBoolean.lean | 154 ++++++++++++++++++ lean/PathMapModel/ConvexChecks.lean | 107 +++++++++++++ lean/PathMapModel/ConvexGeometry.lean | 127 +++++++++++++++ lean/PathMapModel/ConvexMap.lean | 172 ++++++++++++++++++++ lean/PathMapModel/ConvexMorphisms.lean | 143 +++++++++++++++++ lean/PathMapModel/ConvexOrder.lean | 179 +++++++++++++++++++++ lean/PathMapModel/ConvexPruning.lean | 174 ++++++++++++++++++++ lean/PathMapModel/ConvexUnion.lean | 52 ++++++ 10 files changed, 1321 insertions(+) create mode 100644 lean/PathMapModel/Convex.lean create mode 100644 lean/PathMapModel/ConvexBoolean.lean create mode 100644 lean/PathMapModel/ConvexChecks.lean create mode 100644 lean/PathMapModel/ConvexGeometry.lean create mode 100644 lean/PathMapModel/ConvexMap.lean create mode 100644 lean/PathMapModel/ConvexMorphisms.lean create mode 100644 lean/PathMapModel/ConvexOrder.lean create mode 100644 lean/PathMapModel/ConvexPruning.lean create mode 100644 lean/PathMapModel/ConvexUnion.lean diff --git a/lean/PathMapModel.lean b/lean/PathMapModel.lean index 2ac85ab4..beae73f1 100644 --- a/lean/PathMapModel.lean +++ b/lean/PathMapModel.lean @@ -12,3 +12,4 @@ import PathMapModel.PathSetLaws import PathMapModel.PathSetProofs import PathMapModel.PathSetChecks import PathMapModel.PathSetCertificates +import PathMapModel.ConvexMap diff --git a/lean/PathMapModel/Convex.lean b/lean/PathMapModel/Convex.lean new file mode 100644 index 00000000..86d93f4b --- /dev/null +++ b/lean/PathMapModel/Convex.lean @@ -0,0 +1,212 @@ +import PathMapModel.PathSetCertificates + +/-! Stable convex operations. Equations ignore list order and duplicates. +Subtraction retains supporting interiors; its mask selects original tips. -/ +namespace PathMapModel.PathSpace + +def convexMeet (a b : PathSpace) : PathSpace := live (inter a b) (inter (hull a) (hull b)) +def convexSubtract (a b : PathSpace) : PathSpace := live a (diff (hull a) b) +abbrev Included (a b : PathSpace) : Prop := ∀ p, p ∈ a → p ∈ b +abbrev Same (a b : PathSpace) : Prop := ∀ p, p ∈ a ↔ p ∈ b +def ConvexLE (a b : PathSpace) : Prop := Included a b ∧ Included (hull a) (hull b) + +theorem same_equiv (a b : PathSpace) : Same a b ↔ equiv a b = true := (equiv_iff a b).symm + +theorem mem_convexMeet (a b : PathSpace) (p : Path) : + p ∈ convexMeet a b ↔ p ∈ a ∧ p ∈ b ∧ ∃ t, t ∈ hull a ∧ t ∈ hull b ∧ (p ≼ t) = true := by + simp only [convexMeet, mem_live, mem_inter]; grind + +theorem mem_convexSubtract (a b : PathSpace) (p : Path) : + p ∈ convexSubtract a b ↔ p ∈ a ∧ ∃ t, t ∈ hull a ∧ t ∉ b ∧ (p ≼ t) = true := by + simp only [convexSubtract, mem_live, mem_diff]; grind + +theorem live_congr {a b t u : PathSpace} (h : Same a b) (k : Same t u) : Same (live a t) (live b u) := by + intro p; simp only [mem_live, h, k] + +theorem hull_max {a : PathSpace} {p q : Path} (hp : p ∈ hull a) (hq : q ∈ a) + (h : (p ≼ q) = true) : p = q := by + by_cases hn : p = q + · exact hn + · have := ((mem_hull a p).mp hp).2 q hq (Ne.symm hn) + simp [h] at this + +theorem hull_isAntichain (a : PathSpace) : Antichain (hull a) := + fun _ hp _ hq h => hull_max hp (hull_subset a hq) h + +theorem hull_of_antichain {a : PathSpace} (h : Antichain a) : Same (hull a) a := by + intro p; rw [mem_hull]; constructor + · exact And.left + · intro hp; refine ⟨hp, ?_⟩ + intro q hq hn; cases he : p ≼ q with + | false => rfl + | true => exact False.elim (hn (h p hp q hq he).symm) + +theorem live_hull (a : PathSpace) : Same (live a (hull a)) a := by + intro p; rw [mem_live]; exact ⟨And.left, fun hp => ⟨hp, hull_covers hp⟩⟩ + +theorem hull_live {a t : PathSpace} (ht : Included t (hull a)) : Same (hull (live a t)) t := by + intro p; constructor + · intro hp + obtain ⟨ha, q, hq, hpq⟩ := (mem_live a t p).mp (hull_subset _ hp) + have hqm : q ∈ live a t := (mem_live _ _ _).mpr ⟨hull_subset _ (ht q hq), q, hq, Path.prefix_self q⟩ + have he := hull_max hp hqm hpq + exact he ▸ hq + · intro hp + apply (mem_hull _ _).mpr + refine ⟨(mem_live _ _ _).mpr ⟨hull_subset _ (ht p hp), p, hp, Path.prefix_self p⟩, ?_⟩ + intro q hq hn + exact ((mem_hull a p).mp (ht p hp)).2 q ((mem_live _ _ _).mp hq).1 hn + +theorem meet_tips_subset (a b : PathSpace) : Included (inter (hull a) (hull b)) (hull (inter a b)) := by + intro p hp; obtain ⟨ha,hb⟩ := (mem_inter _ _ _).mp hp + apply (mem_hull _ _).mpr + exact ⟨(mem_inter _ _ _).mpr ⟨hull_subset _ ha, hull_subset _ hb⟩, + fun q hq hn => ((mem_hull a p).mp ha).2 q ((mem_inter _ _ _).mp hq).1 hn⟩ + +theorem hull_convexMeet (a b : PathSpace) : Same (hull (convexMeet a b)) (inter (hull a) (hull b)) := + hull_live (meet_tips_subset a b) + +theorem hull_convexSubtract (a b : PathSpace) : Same (hull (convexSubtract a b)) (diff (hull a) b) := + hull_live (fun _ h => ((mem_diff _ _ _).mp h).1) + +theorem convexMeet_congr {a b c d : PathSpace} (h : Same a c) (k : Same b d) : + Same (convexMeet a b) (convexMeet c d) := by + intro p; simp only [mem_convexMeet, h, k, hull_congr h, hull_congr k] + +theorem convexSubtract_congr {a b c d : PathSpace} (h : Same a c) (k : Same b d) : + Same (convexSubtract a b) (convexSubtract c d) := by + intro p; simp only [mem_convexSubtract, h, k, hull_congr h] + +theorem convexMeet_subset (a b : PathSpace) : Included (convexMeet a b) (inter a b) := by + intro p hp; have := (mem_convexMeet a b p).mp hp; exact (mem_inter _ _ _).mpr ⟨this.1,this.2.1⟩ + +theorem convexSubtract_subset (a b : PathSpace) : Included (convexSubtract a b) a := + fun p hp => ((mem_convexSubtract a b p).mp hp).1 + +theorem convexMeet_comm (a b : PathSpace) : Same (convexMeet a b) (convexMeet b a) := by + intro p; simp only [mem_convexMeet]; grind + +theorem convexMeet_idem (a : PathSpace) : Same (convexMeet a a) a := by + intro p; simp only [mem_convexMeet]; constructor + · rintro ⟨h,_⟩; exact h + · intro hp; obtain ⟨t,ht,hpt⟩ := hull_covers hp; exact ⟨hp,hp,t,ht,ht,hpt⟩ + +theorem convexMeet_assoc (a b c : PathSpace) : Same (convexMeet (convexMeet a b) c) (convexMeet a (convexMeet b c)) := by + intro p; simp only [mem_convexMeet, hull_convexMeet, mem_inter]; grind + +theorem convexMeet_empty (a : PathSpace) : Same (convexMeet a []) [] := by + intro p; simp [mem_convexMeet] + +theorem convexSubtract_empty_right (a : PathSpace) : Same (convexSubtract a []) a := by + intro p; simpa [convexSubtract, mem_live, mem_diff] using live_hull a p + +theorem convexSubtract_empty_left (a : PathSpace) : Same (convexSubtract [] a) [] := by + intro p; simp [mem_convexSubtract] + +theorem convexSubtract_self (a : PathSpace) : Same (convexSubtract a a) [] := by + intro p; simp only [mem_convexSubtract, List.not_mem_nil, iff_false] + rintro ⟨_,t,ht,hn,_⟩; exact hn (hull_subset a ht) + +theorem convexMeet_zero (a b : PathSpace) : Same (convexMeet a b) [] ↔ Same (inter (hull a) (hull b)) [] := by + constructor + · intro h p; have hh := (hull_convexMeet a b p).symm.trans (hull_congr h p) + simpa only [hull, List.filter_nil] using hh + · intro h p; simp only [convexMeet, mem_live]; have := h; simp only [Same, List.not_mem_nil, iff_false] at this; grind + +theorem convexSubtract_zero (a b : PathSpace) : Same (convexSubtract a b) [] ↔ Included (hull a) b := by + constructor + · intro h p hp + have hh := hull_congr h p + rw [hull_convexSubtract] at hh + simp only [mem_diff, hull, List.filter_nil, List.not_mem_nil, iff_false] at hh + by_cases hn : p ∈ b + · exact hn + · exact False.elim (hh ⟨hp,hn⟩) + · intro h p; simp only [mem_convexSubtract, List.not_mem_nil, iff_false]; grind + +theorem convexSubtract_identity (a b : PathSpace) : Same (convexSubtract a b) a ↔ Same (inter (hull a) b) [] := by + constructor + · intro h p + have hh := hull_congr h p + simp only [hull_convexSubtract,mem_diff] at hh + simp only [mem_inter,List.not_mem_nil,iff_false]; grind + · intro h p; rw [mem_convexSubtract]; constructor + · exact And.left + · intro hp; obtain ⟨t,ht,hpt⟩ := hull_covers hp + exact ⟨hp,t,ht,fun hb => List.not_mem_nil ((h t).mp ((mem_inter _ _ _).mpr ⟨ht,hb⟩)),hpt⟩ + +theorem convexMeet_ordinary (a b : PathSpace) : Same (convexMeet a b) (inter a b) ↔ Included (hull (inter a b)) (inter (hull a) (hull b)) := by + constructor + · intro h p hp; exact (hull_convexMeet a b p).mp ((hull_congr h p).mpr hp) + · intro h p; rw [convexMeet,mem_live]; constructor + · exact And.left + · intro hp; obtain ⟨t,ht,hpt⟩ := hull_covers hp; exact ⟨hp,t,h t ht,hpt⟩ + +theorem convexSubtract_masks (a b : PathSpace) : + Same (convexSubtract a b) (convexSubtract a (inter a b)) ∧ + Same (convexSubtract a b) (convexSubtract a (inter (hull a) b)) := by + constructor <;> intro p <;> simp only [mem_convexSubtract,mem_inter] + · constructor + · grind + · rintro ⟨hp,t,ht,hn,hpt⟩; exact ⟨hp,t,ht,fun hb => hn ⟨hull_subset _ ht,hb⟩,hpt⟩ + · grind + +theorem convexSubtract_action (a b c : PathSpace) : Same (convexSubtract (convexSubtract a b) c) (convexSubtract a (union b c)) := by + intro p; simp only [mem_convexSubtract,hull_convexSubtract,mem_diff,union,List.mem_append]; grind + +theorem convexSubtract_commute (a b c : PathSpace) : Same (convexSubtract (convexSubtract a b) c) (convexSubtract (convexSubtract a c) b) := by + intro p; simp only [convexSubtract_action]; simp only [mem_convexSubtract,union,List.mem_append]; grind + +theorem convexSubtract_idem (a b : PathSpace) : Same (convexSubtract (convexSubtract a b) b) (convexSubtract a b) := by + intro p; simp only [convexSubtract_action]; simp only [mem_convexSubtract,union,List.mem_append,or_self] + +theorem convexSubtract_redundant (a b c : PathSpace) : Same (convexSubtract (convexSubtract a b) c) (convexSubtract (convexSubtract a b) (diff c b)) := by + intro p; simp only [convexSubtract_action]; simp only [mem_convexSubtract,union,List.mem_append,mem_diff]; grind + +theorem convexSubtract_meet_left (a b c : PathSpace) : Same (convexSubtract (convexMeet a b) c) (convexMeet (convexSubtract a c) b) := by + intro p; simp only [mem_convexSubtract,mem_convexMeet,hull_convexMeet,hull_convexSubtract,mem_inter,mem_diff]; grind + +theorem convexSubtract_meet_right (a b c : PathSpace) : Same (convexSubtract (convexMeet a b) c) (convexMeet a (convexSubtract b c)) := by + intro p; simp only [mem_convexSubtract,mem_convexMeet,hull_convexMeet,hull_convexSubtract,mem_inter,mem_diff]; grind + +theorem convex_four_factor (a b c d : PathSpace) : Same (convexMeet (convexSubtract a b) (convexSubtract c d)) (convexSubtract (convexMeet a c) (union b d)) := by + intro p; simp only [mem_convexSubtract,mem_convexMeet,hull_convexMeet,hull_convexSubtract,mem_inter,mem_diff,union,List.mem_append]; grind + +theorem convexSubtract_meet_both (a b c : PathSpace) : Same (convexSubtract (convexMeet a b) c) (convexMeet (convexSubtract a c) (convexSubtract b c)) := by + intro p; simp only [convex_four_factor,mem_convexSubtract,union,List.mem_append,or_self] + +theorem convexSubtract_inter (a b c : PathSpace) : Same (convexSubtract a (inter b c)) (union (convexSubtract a b) (convexSubtract a c)) := by + intro p; simp only [mem_convexSubtract,mem_inter,union,List.mem_append]; grind + +theorem convexSubtract_union (a b c : PathSpace) : Same (convexSubtract a (union b c)) (convexMeet (convexSubtract a b) (convexSubtract a c)) := by + intro p; rw [convex_four_factor] + exact (convexSubtract_congr (convexMeet_idem a) (fun _ => Iff.rfl) p).symm + +theorem convexSubtract_disjoint (a b : PathSpace) : Same (convexMeet (convexSubtract a b) b) [] := by + intro p; simp only [mem_convexMeet,hull_convexSubtract,mem_diff,List.not_mem_nil,iff_false] + rintro ⟨_,_,t,⟨_,hn⟩,ht,_⟩; exact hn (hull_subset _ ht) + +theorem convexMeet_via_subtract (a b : PathSpace) : Same (convexMeet a b) (convexSubtract (inter a b) (diff (hull (inter a b)) (inter (hull a) (hull b)))) := by + intro p; simp only [mem_convexMeet,mem_convexSubtract,mem_inter,mem_diff] + have ht := meet_tips_subset a b + simp only [Included,mem_inter] at ht + grind + +theorem convexMeet_hulls (a b : PathSpace) : Same (convexMeet (hull a) (hull b)) (inter (hull a) (hull b)) := by + intro p; simp only [mem_convexMeet,hull_idempotent,mem_inter] + exact ⟨fun h => ⟨h.1,h.2.1⟩,fun h => ⟨h.1,h.2,p,h.1,h.2,Path.prefix_self p⟩⟩ + +theorem convexSubtract_hull (a b : PathSpace) : Same (convexSubtract (hull a) b) (diff (hull a) b) := by + intro p; simp only [mem_convexSubtract,hull_idempotent,mem_diff] + constructor + · rintro ⟨hp,t,ht,hn,hpt⟩; have he := hull_max hp (hull_subset _ ht) hpt; exact ⟨hp,he ▸ hn⟩ + · rintro ⟨hp,hn⟩; exact ⟨hp,p,hp,hn,Path.prefix_self p⟩ + +theorem convexMeet_empty_left (a : PathSpace) : Same (convexMeet [] a) [] := + fun p => (convexMeet_comm [] a p).trans (convexMeet_empty a p) + +theorem convexSubtract_hull_disjoint (a b : PathSpace) : + Same (inter (hull (convexSubtract a b)) b) [] := by + intro p; simp only [mem_inter,hull_convexSubtract,mem_diff,List.not_mem_nil,iff_false]; grind + +end PathMapModel.PathSpace diff --git a/lean/PathMapModel/ConvexBoolean.lean b/lean/PathMapModel/ConvexBoolean.lean new file mode 100644 index 00000000..1a6f3870 --- /dev/null +++ b/lean/PathMapModel/ConvexBoolean.lean @@ -0,0 +1,154 @@ +import PathMapModel.ConvexUnion + +namespace PathMapModel.PathSpace + +/-- Enumerate selections without quotienting away duplicate source paths. The +public family calls this only on the duplicate-free hull. -/ +def tipChoices : PathSpace → List PathSpace + | [] => [[]] + | p :: ps => tipChoices ps ++ (tipChoices ps).map (p :: ·) + +theorem tipChoices_length (xs : PathSpace) : (tipChoices xs).length = 2 ^ xs.length := by + induction xs with + | nil => rfl + | cons p ps ih => simp only [tipChoices,List.length_append,List.length_map,ih,List.length_cons,Nat.pow_succ]; omega + +theorem tipChoices_subset {xs t : PathSpace} (h : t ∈ tipChoices xs) : Included t xs := by + induction xs generalizing t with + | nil => simp only [tipChoices,List.mem_singleton] at h; subst t; exact fun _ hp => False.elim (List.not_mem_nil hp) + | cons p ps ih => + rcases List.mem_append.mp h with h | h + · exact fun q hq => List.mem_cons_of_mem _ (ih h q hq) + · obtain ⟨u,hu,rfl⟩ := List.mem_map.mp h + intro q hq; rcases List.mem_cons.mp hq with rfl | hq + · exact List.mem_cons_self + · exact List.mem_cons_of_mem _ (ih hu q hq) + +theorem tipChoices_select (xs t : PathSpace) : xs.filter t.contains ∈ tipChoices xs := by + induction xs with + | nil => simp [tipChoices] + | cons p ps ih => + by_cases hp : p ∈ t + · simp only [List.filter_cons,List.contains_iff_mem.mpr hp,ite_true,tipChoices] + exact List.mem_append_right _ (List.mem_map.mpr ⟨_,ih,rfl⟩) + · have hf : t.contains p = false := by simp [hp] + simp only [List.filter_cons,hf,Bool.false_eq_true,ite_false,tipChoices] + exact List.mem_append_left _ ih + +theorem tipChoices_distinct {xs : PathSpace} (hx : xs.Nodup) : + (tipChoices xs).Pairwise (fun t u => ¬ Same t u) := by + induction xs with + | nil => simp [tipChoices] + | cons p ps ih => + obtain ⟨hn,hd⟩ := List.nodup_cons.mp hx + have no_p : ∀ t ∈ tipChoices ps, p ∉ t := fun t ht hp => hn (tipChoices_subset ht p hp) + rw [tipChoices,List.pairwise_append] + refine ⟨ih hd,?_,?_⟩ + · rw [List.pairwise_map] + apply List.Pairwise.imp_of_mem ?_ (ih hd) + intro t u ht hu hne he + apply hne; intro q + have hh := he q + simp only [List.mem_cons] at hh + by_cases hq : q = p + · subst q; exact iff_of_false (no_p t ht) (no_p u hu) + · simpa [hq] using hh + · intro t ht u hu + obtain ⟨v,hv,rfl⟩ := List.mem_map.mp hu + intro he; exact no_p t ht ((he p).mpr List.mem_cons_self) + +def pruningFamily (a : PathSpace) : List PathSpace := (tipChoices (hull a).eraseDups).map (live a) + +theorem pruningFamily_length (a : PathSpace) : (pruningFamily a).length = 2 ^ count (hull a) := by + simp only [pruningFamily,List.length_map,tipChoices_length,count] + +theorem pruningFamily_distinct (a : PathSpace) : (pruningFamily a).Pairwise (fun x y => ¬ Same x y) := by + rw [pruningFamily,List.pairwise_map] + apply List.Pairwise.imp_of_mem ?_ (tipChoices_distinct (dedup_nodup (hull a))) + intro t u ht hu hne he + have ts : Included t (hull a) := fun p hp => List.mem_eraseDups.mp (tipChoices_subset ht p hp) + have us : Included u (hull a) := fun p hp => List.mem_eraseDups.mp (tipChoices_subset hu p hp) + exact hne ((pruning_injective ts us).mp he) + +theorem pruningFamily_complete {a t : PathSpace} (ht : Included t (hull a)) : + ∃ r ∈ pruningFamily a, Same r (live a t) := by + let u := (hull a).eraseDups.filter t.contains + refine ⟨live a u,List.mem_map.mpr ⟨u,tipChoices_select _ t,rfl⟩,live_congr (fun _ => Iff.rfl) ?_⟩ + intro p; simp only [u,List.mem_filter,List.mem_eraseDups,List.contains_iff_mem] + exact ⟨And.right,fun hp => ⟨ht p hp,hp⟩⟩ + +theorem pruningFamily_sound {a r : PathSpace} (hr : r ∈ pruningFamily a) : + ∃ t, Included t (hull a) ∧ r = live a t := by + obtain ⟨t,ht,rfl⟩ := List.mem_map.mp hr + exact ⟨t,fun p hp => List.mem_eraseDups.mp (tipChoices_subset ht p hp),rfl⟩ + +/-- An arbitrary Boolean expression, not a fixed list of candidate laws. -/ +inductive ConvexFormula where + | atom : Nat → ConvexFormula + | bot | top + | meet : ConvexFormula → ConvexFormula → ConvexFormula + | join : ConvexFormula → ConvexFormula → ConvexFormula + | compl : ConvexFormula → ConvexFormula +namespace ConvexFormula + +def eval (v : Nat → Bool) : ConvexFormula → Bool + | .atom i => v i + | .bot => false + | .top => true + | .meet x y => eval v x && eval v y + | .join x y => eval v x || eval v y + | .compl x => !eval v x + +def tips (a : PathSpace) (v : Nat → PathSpace) (e : ConvexFormula) : PathSpace := + (hull a).filter (fun p => eval (fun i => (v i).contains p) e) +def interpret (a : PathSpace) (v : Nat → PathSpace) : ConvexFormula → PathSpace + | .atom i => live a (inter (hull a) (v i)) + | .bot => [] + | .top => a + | .meet x y => convexMeet (interpret a v x) (interpret a v y) + | .join x y => union (interpret a v x) (interpret a v y) + | .compl x => convexSubtract a (hull (interpret a v x)) + +theorem tips_subset (a : PathSpace) (v : Nat → PathSpace) (e : ConvexFormula) : Included (tips a v e) (hull a) := + fun _ h => (List.mem_filter.mp h).1 + +theorem interpret_correct (a : PathSpace) (v : Nat → PathSpace) (e : ConvexFormula) : + Same (interpret a v e) (live a (tips a v e)) := by + induction e with + | atom i => + apply live_congr (fun _ => Iff.rfl) + intro p; simp [tips,eval,mem_inter] + | bot => intro p; simp [interpret,tips,eval,mem_live] + | top => intro p; simpa [interpret,tips,eval,mem_live] using (live_hull a p).symm + | meet x y ihx ihy => + intro p + apply (convexMeet_congr ihx ihy p).trans + apply (pruning_meet (tips_subset a v x) (tips_subset a v y) p).trans + apply live_congr (fun _ => Iff.rfl) _ p + intro q; simp [tips,eval,mem_inter]; grind + | join x y ihx ihy => + intro p + have he : Same (union (interpret a v x) (interpret a v y)) (union (live a (tips a v x)) (live a (tips a v y))) := by + intro q; simp only [union,List.mem_append,ihx,ihy] + apply (he p).trans ((pruning_union a _ _ p).trans ?_) + apply live_congr (fun _ => Iff.rfl) _ p + intro q; simp [tips,eval,union]; grind + | compl x ih => + intro p + apply (convexSubtract_congr (fun _ => Iff.rfl) (hull_congr ih) p).trans + apply (pruning_complement (tips_subset a v x) p).trans + apply live_congr (fun _ => Iff.rfl) _ p + intro q; simp [tips,eval,mem_diff]; grind + +/-- Every Boolean identity transfers to the canonical prunings of every source. +This covers distributivity, absorption, complements, involution, and De Morgan. -/ +theorem transfer {e f : ConvexFormula} (h : ∀ v, eval v e = eval v f) + (a : PathSpace) (v : Nat → PathSpace) : Same (interpret a v e) (interpret a v f) := by + intro p + apply (interpret_correct a v e p).trans + apply Iff.trans _ (interpret_correct a v f p).symm + apply live_congr (fun _ => Iff.rfl) _ p + intro q; simp only [tips,List.mem_filter,h] + +end ConvexFormula +end PathMapModel.PathSpace diff --git a/lean/PathMapModel/ConvexChecks.lean b/lean/PathMapModel/ConvexChecks.lean new file mode 100644 index 00000000..d9047ede --- /dev/null +++ b/lean/PathMapModel/ConvexChecks.lean @@ -0,0 +1,107 @@ +import PathMapModel.ConvexBoolean + +/-! Kernel-reduced witnesses refuting tempting *unconditional* laws. Positive +universal laws are proved symbolically in the imported modules, not by testing. -/ +namespace PathMapModel.PathSpace +private def root : PathSpace := [[]] +private def stem : PathSpace := [[],[1]] +private def fork : PathSpace := [[],[1],[2]] + +theorem convex_counterexample_meet_monotone : + subset root stem = true ∧ subset (convexMeet root root) (convexMeet stem root) = false := by decide + +theorem convex_counterexample_subtract_monotone : + subset root stem = true ∧ subset (convexSubtract root [[1]]) (convexSubtract stem [[1]]) = false := by decide + +theorem convex_counterexample_absorption : equiv (convexMeet root (union root [[1]])) root = false := by decide + +theorem convex_counterexample_union_distribution : + equiv (convexMeet root (union root [[1]])) (union (convexMeet root root) (convexMeet root [[1]])) = false := by decide + +theorem convex_counterexample_partition : + equiv (union (convexMeet root stem) (convexSubtract root stem)) root = false := by decide + +theorem convex_counterexample_ordinary_intersection : + equiv (convexSubtract fork [[1],[2]]) (inter (convexSubtract fork [[1]]) (convexSubtract fork [[2]])) = false := by decide + +theorem convex_counterexample_source_union : + equiv (convexSubtract (union root [[1]]) [[1]]) (union (convexSubtract root [[1]]) (convexSubtract [[1]] [[1]])) = false := by decide + +theorem convex_counterexample_intersection_distribution : + equiv (convexMeet (inter root stem) root) (inter (convexMeet root root) (convexMeet stem root)) = false := by decide + +theorem convex_counterexample_hull_mask : + equiv (convexSubtract root stem) (convexSubtract root (hull stem)) = false := by decide + +theorem convex_counterexample_basis_mask : + equiv (convexSubtract [[1]] stem) (convexSubtract [[1]] (basis stem)) = false := by decide + +theorem convex_counterexample_relative_complement : + ConvexLE root root ∧ Same (convexMeet root stem) [] ∧ ¬ ConvexLE root (convexSubtract root stem) := by + refine ⟨convexLE_refl _,(same_equiv _ _).mpr (by decide),?_⟩ + intro h; have hh := h.1 [] (by decide); change [] ∈ [] at hh; exact List.not_mem_nil hh + +theorem convex_counterexample_compatible_distribution : + Antichain (union (hull [[],[2]]) (hull [[1]])) ∧ + equiv (convexMeet stem (union [[],[2]] [[1]])) (union (convexMeet stem [[],[2]]) (convexMeet stem [[1]])) = false := by + constructor + · intro p hp q hq hpq + have hh : union (hull [[],[2]]) (hull [[1]]) = [[2],[1]] := by decide + rw [hh] at hp hq + simp only [List.mem_cons,List.not_mem_nil,or_false] at hp hq + rcases hp with rfl | rfl <;> rcases hq with rfl | rfl <;> simp_all [Path.isPrefixOf] + · decide + +theorem convex_cascade_example : + convexMeet [[1],[1,2],[1,2,3]] [[1],[1,2],[1,2,4]] = [] ∧ + convexPruneStep [[1],[1,2]] [] = [[1]] ∧ + convexPrune [] 2 [[1],[1,2]] = [] := by decide + +theorem convex_supporting_interior_example : + convexSubtract [[1],[1,2],[1,3]] [[1],[1,2]] = [[1],[1,3]] ∧ + convexLiteralSubtract [[1],[1,2],[1,3]] [[1],[1,2]] = [[1,3]] := by decide + +theorem convex_literal_gap_example : + convexLiteralSubtract [[],[1],[1,1]] [[1]] = [[],[1,1]] := by decide + +/-! Concrete instances of the universal Boolean-expression transfer theorem. -/ +namespace ConvexFormula + +theorem meet_distributes (a : PathSpace) (v : Nat → PathSpace) (x y z : ConvexFormula) : + Same (interpret a v (.meet x (.join y z))) (interpret a v (.join (.meet x y) (.meet x z))) := by + apply transfer; intro w; simp only [eval]; cases eval w x <;> cases eval w y <;> cases eval w z <;> rfl + +theorem join_distributes (a : PathSpace) (v : Nat → PathSpace) (x y z : ConvexFormula) : + Same (interpret a v (.join x (.meet y z))) (interpret a v (.meet (.join x y) (.join x z))) := by + apply transfer; intro w; simp only [eval]; cases eval w x <;> cases eval w y <;> cases eval w z <;> rfl + +theorem complement_join (a : PathSpace) (v : Nat → PathSpace) (x : ConvexFormula) : + Same (interpret a v (.join x (.compl x))) a := by + exact transfer (e := .join x (.compl x)) (f := .top) (by intro w; simp [eval]) a v + +theorem complement_meet (a : PathSpace) (v : Nat → PathSpace) (x : ConvexFormula) : + Same (interpret a v (.meet x (.compl x))) [] := by + exact transfer (e := .meet x (.compl x)) (f := .bot) (by intro w; simp [eval]) a v + +theorem double_complement (a : PathSpace) (v : Nat → PathSpace) (x : ConvexFormula) : + Same (interpret a v (.compl (.compl x))) (interpret a v x) := by + apply transfer; intro w; simp [eval] + +theorem deMorgan_meet (a : PathSpace) (v : Nat → PathSpace) (x y : ConvexFormula) : + Same (interpret a v (.compl (.meet x y))) (interpret a v (.join (.compl x) (.compl y))) := by + apply transfer; intro w; simp [eval] + +theorem deMorgan_join (a : PathSpace) (v : Nat → PathSpace) (x y : ConvexFormula) : + Same (interpret a v (.compl (.join x y))) (interpret a v (.meet (.compl x) (.compl y))) := by + apply transfer; intro w; simp [eval] + +theorem absorption_meet (a : PathSpace) (v : Nat → PathSpace) (x y : ConvexFormula) : + Same (interpret a v (.meet x (.join x y))) (interpret a v x) := by + apply transfer; intro w; simp [eval]; grind + +theorem absorption_join (a : PathSpace) (v : Nat → PathSpace) (x y : ConvexFormula) : + Same (interpret a v (.join x (.meet x y))) (interpret a v x) := by + apply transfer; intro w; simp [eval]; grind + +end ConvexFormula +end PathMapModel.PathSpace diff --git a/lean/PathMapModel/ConvexGeometry.lean b/lean/PathMapModel/ConvexGeometry.lean new file mode 100644 index 00000000..df9b6c17 --- /dev/null +++ b/lean/PathMapModel/ConvexGeometry.lean @@ -0,0 +1,127 @@ +import PathMapModel.ConvexPruning + +namespace PathMapModel.PathSpace + +/-- Prefix-order convexity; this does not require prefix closure. -/ +def IsConvex (a : PathSpace) : Prop := ∀ p ∈ a, ∀ r ∈ a, ∀ q, + (p ≼ q) = true → (q ≼ r) = true → q ∈ a +def IsPrefixClosed (a : PathSpace) : Prop := ∀ r ∈ a, ∀ p, (p ≼ r) = true → p ∈ a + +theorem live_lower {a t : PathSpace} {p q : Path} (hp : p ∈ a) + (hq : q ∈ live a t) (hpq : (p ≼ q) = true) : p ∈ live a t := by + obtain ⟨_,r,hr,hqr⟩ := (mem_live _ _ _).mp hq + exact (mem_live _ _ _).mpr ⟨hp,r,hr,Path.prefix_trans hpq hqr⟩ + +theorem live_convex {a : PathSpace} (ha : IsConvex a) (t : PathSpace) : IsConvex (live a t) := by + intro p hp r hr q hpq hqr + exact live_lower (ha p ((mem_live _ _ _).mp hp).1 r ((mem_live _ _ _).mp hr).1 q hpq hqr) hr hqr + +theorem live_prefixClosed {a : PathSpace} (ha : IsPrefixClosed a) (t : PathSpace) : IsPrefixClosed (live a t) := by + intro r hr p hpr; exact live_lower (ha r ((mem_live _ _ _).mp hr).1 p hpr) hr hpr + +theorem convexMeet_convex {a b : PathSpace} (ha : IsConvex a) (hb : IsConvex b) : IsConvex (convexMeet a b) := by + apply live_convex + intro p hp r hr q hpq hqr + exact (mem_inter _ _ _).mpr ⟨ha p ((mem_inter _ _ _).mp hp).1 r ((mem_inter _ _ _).mp hr).1 q hpq hqr, + hb p ((mem_inter _ _ _).mp hp).2 r ((mem_inter _ _ _).mp hr).2 q hpq hqr⟩ + +theorem convexSubtract_convex {a : PathSpace} (ha : IsConvex a) (b : PathSpace) : IsConvex (convexSubtract a b) := live_convex ha _ + +theorem convexMeet_prefixClosed {a b : PathSpace} (ha : IsPrefixClosed a) (hb : IsPrefixClosed b) : IsPrefixClosed (convexMeet a b) := by + apply live_prefixClosed + intro r hr p hpr; exact (mem_inter _ _ _).mpr ⟨ha r ((mem_inter _ _ _).mp hr).1 p hpr,hb r ((mem_inter _ _ _).mp hr).2 p hpr⟩ + +theorem convexSubtract_prefixClosed {a : PathSpace} (ha : IsPrefixClosed a) (b : PathSpace) : IsPrefixClosed (convexSubtract a b) := live_prefixClosed ha _ + +/-- Basis of the discarded region generates precisely the pruning cut. -/ +theorem pruning_basis_cut (x t : PathSpace) : + Same (restrict x (basis (diff x (live x t)))) (diff x (live x t)) := by + intro p; rw [restriction_basis_mask,mem_restrict,mem_diff] + constructor + · rintro ⟨hp,q,hq,hqp⟩ + have hqn := ((mem_diff _ _ _).mp hq).2 + exact ⟨hp,fun hr => hqn (live_lower ((mem_diff _ _ _).mp hq).1 hr hqp)⟩ + · rintro ⟨hp,hn⟩; exact ⟨hp,p,(mem_diff _ _ _).mpr ⟨hp,hn⟩,Path.prefix_self p⟩ + +theorem pruning_basis_raffinate (x t : PathSpace) : + Same (raffinate x (basis (diff x (live x t)))) (live x t) := by + intro p; simp only [raffinate,mem_diff,pruning_basis_cut,mem_live]; grind + +theorem convexMeet_basis (a b : PathSpace) : + Same (raffinate (inter a b) (basis (diff (inter a b) (convexMeet a b)))) (convexMeet a b) := pruning_basis_raffinate _ _ + +theorem convexSubtract_basis (a b : PathSpace) : + Same (raffinate a (basis (diff a (convexSubtract a b)))) (convexSubtract a b) := pruning_basis_raffinate _ _ + +theorem divergence_convexMeet (a b c : PathSpace) : + Same (divergence (convexMeet a b) c) (divergence (inter (hull a) (hull b)) (hull c)) := by + intro p; exact (divergence_hull _ _ p).symm.trans (divergence_congr (hull_convexMeet a b) (fun _ => Iff.rfl) p) + +theorem divergence_convexSubtract (a b c : PathSpace) : + Same (divergence (convexSubtract a b) c) (divergence (diff (hull a) b) (hull c)) := by + intro p; exact (divergence_hull _ _ p).symm.trans (divergence_congr (hull_convexSubtract a b) (fun _ => Iff.rfl) p) + +theorem divergence_subtract_partition (a b c : PathSpace) : + Same (divergence a c) (union (divergence (convexSubtract a b) c) (divergence (inter (hull a) b) c)) := by + have hs : Same (hull a) (union (diff (hull a) b) (inter (hull a) b)) := by + intro p; simp only [union,List.mem_append,mem_diff,mem_inter]; grind + intro p + rw [← divergence_hull_left a c p,divergence_congr hs (fun _ => Iff.rfl),divergence_union_left] + simp only [union,List.mem_append] + have he : Same (divergence (convexSubtract a b) c) (divergence (diff (hull a) b) c) := by + intro q; exact (divergence_hull_left _ _ q).symm.trans (divergence_congr (hull_convexSubtract a b) (fun _ => Iff.rfl) q) + rw [he] + +theorem branches_convexMeet (a b : PathSpace) : Included (branches (convexMeet a b)) (inter (branches a) (branches b)) := by + intro p hp + have hs := convexMeet_subset a b + exact (mem_inter _ _ _).mpr ⟨divergence_mono (fun q hq => ((mem_inter _ _ _).mp (hs q hq)).1) (fun q hq => ((mem_inter _ _ _).mp (hs q hq)).1) p hp, + divergence_mono (fun q hq => ((mem_inter _ _ _).mp (hs q hq)).2) (fun q hq => ((mem_inter _ _ _).mp (hs q hq)).2) p hp⟩ + +theorem branches_convexSubtract (a b : PathSpace) : Included (branches (convexSubtract a b)) (branches a) := + divergence_mono (convexSubtract_subset a b) (convexSubtract_subset a b) + +theorem convex_partition (a b : PathSpace) : + Same (union (convexSubtract a b) (convexSubtract a (diff (hull a) b))) a := by + intro p; simp only [union,List.mem_append,mem_convexSubtract,mem_diff] + constructor + · grind + · intro hp; obtain ⟨t,ht,hpt⟩ := hull_covers hp + by_cases hb : t ∈ b + · exact Or.inr ⟨hp,t,ht,fun hh => hh.2 hb,hpt⟩ + · exact Or.inl ⟨hp,t,ht,hb,hpt⟩ + +theorem convex_partition_disjoint (a b : PathSpace) : + Same (convexMeet (convexSubtract a b) (convexSubtract a (diff (hull a) b))) [] := by + intro p; simp only [mem_convexMeet,hull_convexSubtract,mem_diff,List.not_mem_nil,iff_false]; grind + +theorem branches_convex_partition (a b : PathSpace) (p : Path) : + p ∈ branches a ↔ p ∈ branches (convexSubtract a b) ∨ + p ∈ branches (convexSubtract a (diff (hull a) b)) ∨ + p ∈ divergence (convexSubtract a b) (convexSubtract a (diff (hull a) b)) := by + exact (divergence_congr (convex_partition a b) (convex_partition a b) p).symm.trans (branches_union _ _ p) + +/-- Literal subtraction is a separate operator and can introduce gaps. -/ +def convexLiteralSubtract (a b : PathSpace) : PathSpace := live (diff a b) (diff (hull a) b) + +theorem convexLiteralSubtract_diff (a b : PathSpace) : Same (convexLiteralSubtract a b) (diff (convexSubtract a b) b) := by + intro p; simp only [convexLiteralSubtract,mem_live,mem_diff,mem_convexSubtract]; grind + +theorem hull_surviving_diff {a b : PathSpace} {t : Path} (ht : t ∈ hull a) (hn : t ∉ b) : t ∈ hull (diff a b) := by + apply (mem_hull _ _).mpr + exact ⟨(mem_diff _ _ _).mpr ⟨hull_subset a ht,hn⟩,fun q hq hne => ((mem_hull _ _).mp ht).2 q ((mem_diff _ _ _).mp hq).1 hne⟩ + +theorem convexLiteralSubtract_meet (a b : PathSpace) : Same (convexLiteralSubtract a b) (convexMeet a (diff a b)) := by + intro p; simp only [convexLiteralSubtract,mem_live,mem_diff,mem_convexMeet] + constructor + · rintro ⟨⟨hp,hn⟩,t,⟨ht,htn⟩,hpt⟩; exact ⟨hp,⟨hp,hn⟩,t,ht,hull_surviving_diff ht htn,hpt⟩ + · rintro ⟨hp,⟨_,hn⟩,t,ht,htd,hpt⟩ + exact ⟨⟨hp,hn⟩,t,⟨ht,((mem_diff _ _ _).mp (hull_subset _ htd)).2⟩,hpt⟩ + +theorem convexLiteralSubtract_hull (a b : PathSpace) : + Same (hull (convexLiteralSubtract a b)) (diff (hull a) b) := by + apply hull_live + intro t ht; obtain ⟨hh,hn⟩ := (mem_diff _ _ _).mp ht + exact hull_surviving_diff hh hn + +end PathMapModel.PathSpace diff --git a/lean/PathMapModel/ConvexMap.lean b/lean/PathMapModel/ConvexMap.lean new file mode 100644 index 00000000..925966d0 --- /dev/null +++ b/lean/PathMapModel/ConvexMap.lean @@ -0,0 +1,172 @@ +import PathMapModel.ConvexChecks + +/-! Adapters to the existing mixed model. Geometry uses valued paths only. +Payloads are selected from the left input; no ValOps combination is implicit. +The set algebra is commutative, but arbitrary left-biased payloads are not. -/ +namespace PathMapModel.PathMap.ConvexSupport +open PathMapModel.PathMap +theorem mem_prefixes (p q : Path) : p ∈ q.prefixes ↔ (p ≼ q) = true := by + simp only [Path.prefixes, List.mem_map, List.mem_range] + constructor + · rintro ⟨n,_,rfl⟩ + exact (Path.prefix_iff_list _ _).mpr (List.take_prefix n q) + · intro h + exact ⟨p.length,by have hl := Path.prefix_length h; omega, + ((List.prefix_iff_eq_take).mp ((Path.prefix_iff_list p q).mp h)).symm⟩ + +private theorem mem_insertValSorted_keys {V : Type} (kv : Path × V) + (xs : List (Path × V)) (p : Path) : + p ∈ (insertValSorted kv xs).map Prod.fst ↔ p = kv.1 ∨ p ∈ xs.map Prod.fst := by + induction xs with + | nil => simp [insertValSorted] + | cons x xs ih => + simp only [insertValSorted] + split <;> simp_all <;> grind + +private theorem mem_dedupVals_keys {V : Type} (xs : List (Path × V)) (p : Path) : + p ∈ (dedupVals xs).map Prod.fst ↔ p ∈ xs.map Prod.fst := by + have go : ∀ (ys acc : List (Path × V)), + p ∈ (ys.foldl (fun acc kv => + if acc.any (fun x => x.1 == kv.1) then acc else acc ++ [kv]) acc).map Prod.fst ↔ + p ∈ ys.map Prod.fst ∨ p ∈ acc.map Prod.fst := by + intro ys + induction ys with + | nil => simp + | cons kv ys ih => + intro acc + by_cases h : acc.any (fun x => x.1 == kv.1) = true + · have hk : kv.1 ∈ acc.map Prod.fst := by + obtain ⟨x,hx,he⟩ := List.any_eq_true.mp h + exact List.mem_map.mpr ⟨x,hx,by simpa using he⟩ + simp [List.foldl_cons, h, ih] + grind + · simp [List.foldl_cons, h, ih] + grind + simpa [dedupVals] using go xs [] + +theorem mem_normVals_keys {V : Type} (xs : List (Path × V)) (p : Path) : + p ∈ (normVals xs).map Prod.fst ↔ p ∈ xs.map Prod.fst := by + have go : ∀ (ys acc : List (Path × V)), + p ∈ (ys.foldl (fun acc kv => insertValSorted kv acc) acc).map Prod.fst ↔ + p ∈ ys.map Prod.fst ∨ p ∈ acc.map Prod.fst := by + intro ys + induction ys with + | nil => simp + | cons kv ys ih => + intro acc + simp [List.foldl_cons, ih, mem_insertValSorted_keys] + grind + simpa [normVals, mem_dedupVals_keys] using go (dedupVals xs) [] + +private theorem lookup_keys {V : Type} (xs : List (Path × V)) (p : Path) : + (xs.lookup p).isSome = true ↔ p ∈ xs.map Prod.fst := by + simp only [List.lookup_isSome_iff, beq_iff_eq, List.mem_map] + constructor <;> rintro ⟨kv,hkv,he⟩ <;> exact ⟨kv,hkv,he.symm⟩ + +private theorem lookup_function {V : Type} (ps : PathSpace) (f : Path → V) (p : Path) : + (ps.map fun q => (q,f q)).lookup p = + if ps.contains p then some (f p) else none := by + induction ps with + | nil => simp + | cons q qs ih => + by_cases h : p = q + · subst q; simp + · have hb : (p == q) = false := by simp [h] + simp [List.lookup_cons, hb, h, ih] + +theorem valAt_isSome_mem_paths {V : Type} (t : PathMap V) (p : Path) + (h : (t.valAt p).isSome = true) : p ∈ t.paths := by + apply (lookup_keys t.entries p).mp + cases hl : t.entries.lookup p with + | none => simp [valAt, entryAt, hl, Entry.val] at h + | some v => simp + +private theorem valuedKeys_filter {V : Type} (ps : PathSpace) (f : Path → Option V) : + (ps.filterMap fun p => (f p).map (p, ·)).map Prod.fst = + ps.filter fun p => (f p).isSome := by + induction ps with + | nil => rfl + | cons p ps ih => cases h : f p <;> simp [h, ih] + +theorem ofMap_eq_filter {V : Type} (t : PathMap V) : + PathSpace.ofMap t = t.paths.filter fun p => (t.valAt p).isSome := + valuedKeys_filter t.paths (fun p => (t.entryAt p).val) + +/-- The valued-only projection agrees with the actual mixed-model lookup. -/ +theorem mem_ofMap {V : Type} (t : PathMap V) (p : Path) : + p ∈ PathSpace.ofMap t ↔ (t.valAt p).isSome = true := by + rw [ofMap_eq_filter] + simp only [List.mem_filter] + exact ⟨And.right, fun h => ⟨valAt_isSome_mem_paths t p h,h⟩⟩ + +/-- Adding structural paths in the canonical constructor never changes values. -/ +theorem mk'_valAt {V : Type} (vs : List (Path × V)) (ps : PathSpace) (p : Path) : + (mk' vs ps).valAt p = (normVals vs).lookup p := by + let existing := Path.sortDedup + ((([] : Path) :: (ps ++ (normVals vs).map Prod.fst)).flatMap Path.prefixes) + change (match (existing.map fun q => (q,(normVals vs).lookup q)).lookup p with + | none => Entry.absent + | some none => Entry.bare + | some (some v) => Entry.valued v).val = _ + rw [lookup_function] + by_cases hp : existing.contains p = true + · simp only [hp, if_true] + cases (normVals vs).lookup p <;> rfl + · simp only [hp, Entry.val] + cases hl : (normVals vs).lookup p with + | none => rfl + | some v => + have hk : p ∈ (normVals vs).map Prod.fst := + (lookup_keys _ _).mp (by simp [hl]) + have he : p ∈ existing := by + apply (Path.mem_sortDedup _ _).mpr + exact List.mem_flatMap.mpr ⟨p,List.mem_cons.mpr + (Or.inr (List.mem_append.mpr (Or.inr hk))), + (mem_prefixes _ _).mpr (Path.prefix_self p)⟩ + exact False.elim (hp (List.contains_iff_mem.mpr he)) + +theorem mem_mk'_values {V : Type} (vs : List (Path × V)) (ps : PathSpace) (p : Path) : + p ∈ PathSpace.ofMap (mk' vs ps) ↔ p ∈ vs.map Prod.fst := by + rw [mem_ofMap, mk'_valAt, lookup_keys, mem_normVals_keys] + + +end PathMapModel.PathMap.ConvexSupport + +namespace PathMapModel.Map + +/-- Retain selected values and rebuild their structural skeleton. -/ +def selectConvexSupport {V : Type} (a : PathMap V) (support : PathSpace) : PathMap V := + PathMap.mk' (a.vals.filter (fun kv => support.contains kv.1)) [] + +def convexMeet {V W : Type} (a : PathMap V) (b : PathMap W) : PathMap V := + selectConvexSupport a (PathSpace.convexMeet (PathSpace.ofMap a) (PathSpace.ofMap b)) +def convexSubtract {V W : Type} (a : PathMap V) (b : PathMap W) : PathMap V := + selectConvexSupport a (PathSpace.convexSubtract (PathSpace.ofMap a) (PathSpace.ofMap b)) + +theorem selectConvexSupport_keys {V : Type} (a : PathMap V) (support : PathSpace) (p : Path) : + p ∈ PathSpace.ofMap (selectConvexSupport a support) ↔ p ∈ PathSpace.ofMap a ∧ p ∈ support := by + rw [selectConvexSupport,PathMap.ConvexSupport.mem_mk'_values] + simp only [PathSpace.ofMap,List.mem_map,List.mem_filter,List.contains_iff_mem] + grind + +theorem convexMeet_support {V W : Type} (a : PathMap V) (b : PathMap W) : + PathSpace.Same (PathSpace.ofMap (convexMeet a b)) (PathSpace.convexMeet (PathSpace.ofMap a) (PathSpace.ofMap b)) := by + intro p; rw [convexMeet,selectConvexSupport_keys]; constructor + · exact And.right + · intro h; exact ⟨((PathSpace.mem_convexMeet _ _ _).mp h).1,h⟩ + +theorem convexSubtract_support {V W : Type} (a : PathMap V) (b : PathMap W) : + PathSpace.Same (PathSpace.ofMap (convexSubtract a b)) (PathSpace.convexSubtract (PathSpace.ofMap a) (PathSpace.ofMap b)) := by + intro p; rw [convexSubtract,selectConvexSupport_keys]; constructor + · exact And.right + · intro h; exact ⟨PathSpace.convexSubtract_subset _ _ p h,h⟩ + +end PathMapModel.Map + +namespace PathMapModel.Zip +/-- Relative focus semantics, matching the existing Basis/Hull adapters. -/ +def convexMeet {V W : Type} (a : Zip V) (b : Zip W) (out : Zip V) : Zip V := + out.graftMap (Map.convexMeet a.makeMap b.makeMap) +def convexSubtract {V W : Type} (a : Zip V) (b : Zip W) (out : Zip V) : Zip V := + out.graftMap (Map.convexSubtract a.makeMap b.makeMap) +end PathMapModel.Zip diff --git a/lean/PathMapModel/ConvexMorphisms.lean b/lean/PathMapModel/ConvexMorphisms.lean new file mode 100644 index 00000000..58d9d28d --- /dev/null +++ b/lean/PathMapModel/ConvexMorphisms.lean @@ -0,0 +1,143 @@ +import PathMapModel.ConvexGeometry + +namespace PathMapModel.Path + +theorem prefix_append_same (r p q : Path) : (r ++ p ≼ r ++ q) = (p ≼ q) := by + induction r with + | nil => rfl + | cons c cs ih => simpa [isPrefixOf] using ih + +theorem prefix_append (p q : Path) : (p ≼ p ++ q) = true := + (prefix_iff_extension _ _).mpr ⟨q,rfl⟩ +end PathMapModel.Path + +namespace PathMapModel.PathSpace + +theorem mem_hull_max (a : PathSpace) (p : Path) : + p ∈ hull a ↔ p ∈ a ∧ ∀ q ∈ a, (p ≼ q) = true → p = q := by + constructor + · intro h; exact ⟨hull_subset _ h,fun _ hq hpq => hull_max h hq hpq⟩ + · rintro ⟨hp,h⟩; rw [mem_hull]; refine ⟨hp,?_⟩ + intro q hq hn; cases he : p ≼ q with + | false => rfl + | true => exact False.elim (hn (h q hq he).symm) + +theorem hull_unwrap (a : PathSpace) (r p : Path) : p ∈ hull (unwrap a r) ↔ r ++ p ∈ hull a := by + simp only [mem_hull_max,mem_unwrap]; constructor + · rintro ⟨hp,h⟩; refine ⟨hp,?_⟩ + intro q hq hpq + have hrq := Path.prefix_trans (Path.prefix_append r p) hpq + obtain ⟨s,rfl⟩ := (Path.prefix_iff_extension _ _).mp hrq + have he := h s hq (by simpa only [Path.prefix_append_same] using hpq) + exact congrArg (r ++ ·) he + · rintro ⟨hp,h⟩; refine ⟨hp,?_⟩ + intro q hq hpq + exact List.append_cancel_left (h (r ++ q) hq (by simpa only [Path.prefix_append_same] using hpq)) + +theorem live_unwrap (a t : PathSpace) (r p : Path) : + p ∈ live (unwrap a r) (unwrap t r) ↔ r ++ p ∈ live a t := by + simp only [mem_live,mem_unwrap]; constructor + · rintro ⟨hp,q,hq,hpq⟩; exact ⟨hp,r ++ q,hq,by simpa only [Path.prefix_append_same] using hpq⟩ + · rintro ⟨hp,q,hq,hpq⟩ + obtain ⟨s,rfl⟩ := (Path.prefix_iff_extension _ _).mp (Path.prefix_trans (Path.prefix_append r p) hpq) + exact ⟨hp,s,hq,by simpa only [Path.prefix_append_same] using hpq⟩ + +theorem convexMeet_unwrap (a b : PathSpace) (r : Path) : + Same (unwrap (convexMeet a b) r) (convexMeet (unwrap a r) (unwrap b r)) := by + intro p + have he : Same (inter (unwrap a r) (unwrap b r)) (unwrap (inter a b) r) := by + intro q; simp only [mem_inter,mem_unwrap] + have ht : Same (inter (hull (unwrap a r)) (hull (unwrap b r))) (unwrap (inter (hull a) (hull b)) r) := by + intro q; simp only [mem_inter,mem_unwrap,hull_unwrap] + exact (mem_unwrap _ _ _).trans ((live_unwrap (inter a b) (inter (hull a) (hull b)) r p).symm.trans (live_congr he ht p).symm) + +theorem convexSubtract_unwrap (a b : PathSpace) (r : Path) : + Same (unwrap (convexSubtract a b) r) (convexSubtract (unwrap a r) (unwrap b r)) := by + intro p + have ht : Same (diff (hull (unwrap a r)) (unwrap b r)) (unwrap (diff (hull a) b) r) := by + intro q; simp only [mem_diff,mem_unwrap,hull_unwrap] + exact (mem_unwrap _ _ _).trans ((live_unwrap a (diff (hull a) b) r p).symm.trans (live_congr (fun _ => Iff.rfl) ht p).symm) + +/-- Distinct prefix-code cones cannot interfere, even for empty suffixes. -/ +theorem code_prefix {code : PathSpace} (hc : Antichain code) {r s : Path} + (hr : r ∈ code) (hs : s ∈ code) (x y : Path) : + (r ++ x ≼ s ++ y) = true ↔ r = s ∧ (x ≼ y) = true := by + constructor + · intro h + have hh := Path.prefix_trans (Path.prefix_append r x) h + have he : r = s := by + rcases Path.prefixes_comparable hh (Path.prefix_append s y) with hrs | hsr + · exact hc r hr s hs hrs + · exact (hc s hs r hr hsr).symm + subst s; exact ⟨rfl,by simpa only [Path.prefix_append_same] using h⟩ + · rintro ⟨rfl,h⟩; simpa only [Path.prefix_append_same] using h + +theorem product_at {code : PathSpace} (hc : Antichain code) {r : Path} (hr : r ∈ code) + (a : PathSpace) (p : Path) : r ++ p ∈ product code a ↔ p ∈ a := by + rw [mem_product]; constructor + · rintro ⟨s,hs,q,hq,he⟩ + have hh := (code_prefix hc hr hs p q).mp (he ▸ Path.prefix_self (r ++ p)) + have heq : r = s := hh.1; subst s + have hqp := List.append_cancel_left he + exact hqp ▸ hq + · intro hp; exact ⟨r,hr,p,hp,rfl⟩ + +theorem hull_product_at {code : PathSpace} (hc : Antichain code) {r : Path} (hr : r ∈ code) + (a : PathSpace) (p : Path) : r ++ p ∈ hull (product code a) ↔ p ∈ hull a := by + simp only [mem_hull_max,product_at hc hr]; constructor + · rintro ⟨hp,h⟩; refine ⟨hp,?_⟩ + intro q hq hpq + exact List.append_cancel_left (h (r ++ q) ((product_at hc hr a q).mpr hq) (by simpa only [Path.prefix_append_same] using hpq)) + · rintro ⟨hp,h⟩; refine ⟨hp,?_⟩ + intro q hq hpq + obtain ⟨s,hs,t,ht,rfl⟩ := (mem_product _ _ _).mp hq + obtain ⟨rfl,hpt⟩ := (code_prefix hc hr hs p t).mp hpq + exact congrArg (r ++ ·) (h t ht hpt) + +theorem convexMeet_product_at {code : PathSpace} (hc : Antichain code) {r : Path} (hr : r ∈ code) + (a b : PathSpace) (p : Path) : r ++ p ∈ convexMeet (product code a) (product code b) ↔ p ∈ convexMeet a b := by + simp only [mem_convexMeet,product_at hc hr]; constructor + · rintro ⟨ha,hb,t,ht,hu,hpt⟩ + obtain ⟨s,hs,q,hq,rfl⟩ := (mem_product _ _ _).mp (hull_subset _ ht) + obtain ⟨rfl,hpq⟩ := (code_prefix hc hr hs p q).mp hpt + exact ⟨ha,hb,q,(hull_product_at hc hs a q).mp ht,(hull_product_at hc hs b q).mp hu,hpq⟩ + · rintro ⟨ha,hb,t,ht,hu,hpt⟩ + exact ⟨ha,hb,r ++ t,(hull_product_at hc hr a t).mpr ht,(hull_product_at hc hr b t).mpr hu,by simpa only [Path.prefix_append_same] using hpt⟩ + +theorem convexSubtract_product_at {code : PathSpace} (hc : Antichain code) {r : Path} (hr : r ∈ code) + (a b : PathSpace) (p : Path) : r ++ p ∈ convexSubtract (product code a) (product code b) ↔ p ∈ convexSubtract a b := by + simp only [mem_convexSubtract,product_at hc hr]; constructor + · rintro ⟨ha,t,ht,hn,hpt⟩ + obtain ⟨s,hs,q,hq,rfl⟩ := (mem_product _ _ _).mp (hull_subset _ ht) + obtain ⟨rfl,hpq⟩ := (code_prefix hc hr hs p q).mp hpt + exact ⟨ha,q,(hull_product_at hc hs a q).mp ht,fun hb => hn ((product_at hc hs b q).mpr hb),hpq⟩ + · rintro ⟨ha,t,ht,hn,hpt⟩ + exact ⟨ha,r ++ t,(hull_product_at hc hr a t).mpr ht,fun hb => hn ((product_at hc hr b t).mp hb),by simpa only [Path.prefix_append_same] using hpt⟩ + +theorem convexMeet_product {code : PathSpace} (hc : Antichain code) (a b : PathSpace) : + Same (convexMeet (product code a) (product code b)) (product code (convexMeet a b)) := by + intro p; constructor + · intro hp + obtain ⟨r,hr,q,_,rfl⟩ := (mem_product _ _ _).mp ((mem_convexMeet _ _ _).mp hp).1 + exact (product_at hc hr _ _).mpr ((convexMeet_product_at hc hr a b q).mp hp) + · intro hp; obtain ⟨r,hr,q,hq,rfl⟩ := (mem_product _ _ _).mp hp + exact (convexMeet_product_at hc hr a b q).mpr hq + +theorem convexSubtract_product {code : PathSpace} (hc : Antichain code) (a b : PathSpace) : + Same (convexSubtract (product code a) (product code b)) (product code (convexSubtract a b)) := by + intro p; constructor + · intro hp + obtain ⟨r,hr,q,_,rfl⟩ := (mem_product _ _ _).mp ((mem_convexSubtract _ _ _).mp hp).1 + exact (product_at hc hr _ _).mpr ((convexSubtract_product_at hc hr a b q).mp hp) + · intro hp; obtain ⟨r,hr,q,hq,rfl⟩ := (mem_product _ _ _).mp hp + exact (convexSubtract_product_at hc hr a b q).mpr hq + +theorem convexMeet_wrap (r : Path) (a b : PathSpace) : Same (convexMeet (wrap r a) (wrap r b)) (wrap r (convexMeet a b)) := by + have hc : Antichain [r] := by intro p hp q hq _; simp only [List.mem_singleton] at hp hq; exact hp.trans hq.symm + simpa only [product,List.flatMap_cons,List.flatMap_nil,List.append_nil,wrap] using convexMeet_product hc a b + +theorem convexSubtract_wrap (r : Path) (a b : PathSpace) : Same (convexSubtract (wrap r a) (wrap r b)) (wrap r (convexSubtract a b)) := by + have hc : Antichain [r] := by intro p hp q hq _; simp only [List.mem_singleton] at hp hq; exact hp.trans hq.symm + simpa only [product,List.flatMap_cons,List.flatMap_nil,List.append_nil,wrap] using convexSubtract_product hc a b + +end PathMapModel.PathSpace diff --git a/lean/PathMapModel/ConvexOrder.lean b/lean/PathMapModel/ConvexOrder.lean new file mode 100644 index 00000000..c825b0cd --- /dev/null +++ b/lean/PathMapModel/ConvexOrder.lean @@ -0,0 +1,179 @@ +import PathMapModel.Convex + +namespace PathMapModel.PathSpace + +theorem convexLE_refl (a : PathSpace) : ConvexLE a a := ⟨fun _ h => h, fun _ h => h⟩ +theorem convexLE_trans {a b c : PathSpace} (h : ConvexLE a b) (k : ConvexLE b c) : ConvexLE a c := + ⟨fun p hp => k.1 p (h.1 p hp),fun p hp => k.2 p (h.2 p hp)⟩ +theorem convexLE_antisymm {a b : PathSpace} (h : ConvexLE a b) (k : ConvexLE b a) : Same a b := + fun p => ⟨h.1 p,k.1 p⟩ + +theorem convexLE_iff_meet (a b : PathSpace) : ConvexLE a b ↔ Same (convexMeet a b) a := by + constructor + · intro h p; rw [mem_convexMeet]; constructor + · exact And.left + · intro hp; obtain ⟨t,ht,hpt⟩ := hull_covers hp + exact ⟨hp,h.1 p hp,t,ht,h.2 t ht,hpt⟩ + · intro h; constructor + · intro p hp; exact ((mem_convexMeet _ _ _).mp ((h p).mpr hp)).2.1 + · intro p hp; exact ((mem_inter _ _ _).mp ((hull_convexMeet _ _ _).mp ((hull_congr h p).mpr hp))).2 + +theorem convexMeet_glb (x a b : PathSpace) : ConvexLE x (convexMeet a b) ↔ ConvexLE x a ∧ ConvexLE x b := by + constructor + · intro h + have hs : Included x a ∧ Included x b := by + constructor <;> intro p hp <;> have hh := (mem_convexMeet a b p).mp (h.1 p hp) + · exact hh.1 + · exact hh.2.1 + have ht : Included (hull x) (hull a) ∧ Included (hull x) (hull b) := by + constructor <;> intro p hp <;> have hh := (mem_inter _ _ _).mp ((hull_convexMeet a b p).mp (h.2 p hp)) + · exact hh.1 + · exact hh.2 + exact ⟨⟨hs.1,ht.1⟩,⟨hs.2,ht.2⟩⟩ + · rintro ⟨ha,hb⟩; constructor + · intro p hp; obtain ⟨t,ht,hpt⟩ := hull_covers hp + exact (mem_convexMeet _ _ _).mpr ⟨ha.1 p hp,hb.1 p hp,t,ha.2 t ht,hb.2 t ht,hpt⟩ + · intro p hp; exact (hull_convexMeet a b p).mpr ((mem_inter _ _ _).mpr ⟨ha.2 p hp,hb.2 p hp⟩) + +theorem convexSubtract_universal (x a b : PathSpace) : + ConvexLE x (convexSubtract a b) ↔ ConvexLE x a ∧ ∀ p ∈ hull x, p ∉ b := by + constructor + · intro h + have ht : ∀ p ∈ hull x, p ∈ hull a ∧ p ∉ b := by + intro p hp; exact (mem_diff _ _ _).mp ((hull_convexSubtract a b p).mp (h.2 p hp)) + exact ⟨⟨fun p hp => convexSubtract_subset a b p (h.1 p hp),fun p hp => (ht p hp).1⟩,fun p hp => (ht p hp).2⟩ + · rintro ⟨ha,hb⟩; constructor + · intro p hp; obtain ⟨t,ht,hpt⟩ := hull_covers hp + exact (mem_convexSubtract _ _ _).mpr ⟨ha.1 p hp,t,ha.2 t ht,hb t ht,hpt⟩ + · intro p hp; exact (hull_convexSubtract a b p).mpr ((mem_diff _ _ _).mpr ⟨ha.2 p hp,hb p hp⟩) + +theorem convexMeet_mono {a b c d : PathSpace} (ha : ConvexLE a c) (hb : ConvexLE b d) : ConvexLE (convexMeet a b) (convexMeet c d) := by + have h := (convexMeet_glb (convexMeet a b) a b).mp (convexLE_refl _) + exact (convexMeet_glb _ _ _).mpr ⟨convexLE_trans h.1 ha,convexLE_trans h.2 hb⟩ + +theorem convexSubtract_deflationary (a b : PathSpace) : ConvexLE (convexSubtract a b) a := + ((convexSubtract_universal _ _ _).mp (convexLE_refl _)).1 + +theorem convexSubtract_mono {a c : PathSpace} (h : ConvexLE a c) (b : PathSpace) : ConvexLE (convexSubtract a b) (convexSubtract c b) := by + have hh := (convexSubtract_universal _ _ _).mp (convexLE_refl (convexSubtract a b)) + exact (convexSubtract_universal _ _ _).mpr ⟨convexLE_trans hh.1 h,hh.2⟩ + +theorem convexSubtract_antitone (a : PathSpace) {b c : PathSpace} (h : Included b c) : ConvexLE (convexSubtract a c) (convexSubtract a b) := by + have hh := (convexSubtract_universal _ _ _).mp (convexLE_refl (convexSubtract a c)) + exact (convexSubtract_universal _ _ _).mpr ⟨hh.1,fun p hp hb => hh.2 p hp (h p hb)⟩ + +theorem hull_union_compatible {a b : PathSpace} (h : Antichain (union (hull a) (hull b))) : + Same (hull (union a b)) (union (hull a) (hull b)) := + fun p => (hull_union a b p).trans (hull_of_antichain h p) + +theorem convex_union_lub {a b : PathSpace} (h : Antichain (union (hull a) (hull b))) (x : PathSpace) : + ConvexLE (union a b) x ↔ ConvexLE a x ∧ ConvexLE b x := by + simp only [ConvexLE,Included,union,List.mem_append] + have hh := hull_union_compatible h + simp only [union] at hh + simp only [hh] + grind + +theorem convex_compatible (a b : PathSpace) : + (∃ c, ConvexLE a c ∧ ConvexLE b c) ↔ Antichain (union (hull a) (hull b)) := by + constructor + · rintro ⟨c,ha,hb⟩ p hp q hq hpq + have hh : Included (union (hull a) (hull b)) (hull c) := by + intro t ht; rcases (List.mem_append.mp ht) with ht | ht + · exact ha.2 t ht + · exact hb.2 t ht + exact hull_isAntichain c p (hh p hp) q (hh q hq) hpq + · intro h; exact ⟨union a b,(convex_union_lub h _).mp (convexLE_refl _)⟩ + +/-- All Boolean operations on canonical prunings reduce to operations on tips. -/ +theorem pruning_meet {a t u : PathSpace} (ht : Included t (hull a)) (hu : Included u (hull a)) : + Same (convexMeet (live a t) (live a u)) (live a (inter t u)) := by + intro p; simp only [mem_convexMeet,hull_live ht,hull_live hu,mem_live,mem_inter]; grind + +theorem pruning_union (a t u : PathSpace) : Same (union (live a t) (live a u)) (live a (union t u)) := by + intro p; simp only [union,List.mem_append,mem_live]; grind + +theorem pruning_subtract {a t : PathSpace} (ht : Included t (hull a)) (b : PathSpace) : + Same (convexSubtract (live a t) b) (live a (diff t b)) := by + intro p; simp only [mem_convexSubtract,hull_live ht,mem_live,mem_diff]; grind + +theorem pruning_complement {a t : PathSpace} (ht : Included t (hull a)) : + Same (convexSubtract a (hull (live a t))) (live a (diff (hull a) t)) := by + intro p; simp only [mem_convexSubtract,hull_live ht,mem_live,mem_diff]; grind + +theorem pruning_order {a t u : PathSpace} (ht : Included t (hull a)) (hu : Included u (hull a)) : + ConvexLE (live a t) (live a u) ↔ Included t u := by + constructor + · intro h p hp; exact (hull_live hu p).mp (h.2 p ((hull_live ht p).mpr hp)) + · intro h; constructor + · intro p hp; obtain ⟨hp,q,hq,hpq⟩ := (mem_live _ _ _).mp hp + exact (mem_live _ _ _).mpr ⟨hp,q,h q hq,hpq⟩ + · intro p hp; exact (hull_live hu p).mpr (h p ((hull_live ht p).mp hp)) + +theorem pruning_injective {a t u : PathSpace} (ht : Included t (hull a)) (hu : Included u (hull a)) : + Same (live a t) (live a u) ↔ Same t u := by + constructor + · intro h p; exact (hull_live ht p).symm.trans ((hull_congr h p).trans (hull_live hu p)) + · intro h; exact live_congr (fun _ => Iff.rfl) h + +theorem pruning_bottom (a : PathSpace) : Same (live a []) [] := by intro p; simp [mem_live] + +theorem convexSubtract_faithful (b c : PathSpace) : + (∀ a, Same (convexSubtract a b) (convexSubtract a c)) ↔ Same b c := by + constructor + · intro h p + have hh := h [p] p + simp [mem_convexSubtract,hull] at hh + grind + · intro h a; exact convexSubtract_congr (fun _ => Iff.rfl) h + +/-- A nonempty meet; the first source prevents an artificial universal space. -/ +def convexMeetMany (a : PathSpace) : List PathSpace → PathSpace + | [] => a + | b :: bs => convexMeet a (convexMeetMany b bs) +def interMany (a : PathSpace) : List PathSpace → PathSpace + | [] => a + | b :: bs => inter a (interMany b bs) + +theorem mem_interMany (a : PathSpace) (bs : List PathSpace) (p : Path) : + p ∈ interMany a bs ↔ p ∈ a ∧ ∀ b ∈ bs, p ∈ b := by + induction bs generalizing a with + | nil => simp [interMany] + | cons b bs ih => simp only [interMany,mem_inter,ih,List.mem_cons]; grind + +theorem hull_convexMeetMany (a : PathSpace) (bs : List PathSpace) : + Same (hull (convexMeetMany a bs)) (interMany (hull a) (bs.map hull)) := by + induction bs generalizing a with + | nil => intro p; rfl + | cons b bs ih => intro p; simp only [convexMeetMany,hull_convexMeet,mem_inter,List.map_cons,interMany,ih] + +theorem convexMeetMany_normal (a : PathSpace) (bs : List PathSpace) : + Same (convexMeetMany a bs) (live (interMany a bs) (interMany (hull a) (bs.map hull))) := by + induction bs generalizing a with + | nil => exact fun p => (live_hull a p).symm + | cons b bs ih => + intro p + simp only [convexMeetMany,mem_convexMeet,hull_convexMeetMany,ih,mem_live,List.map_cons,interMany,mem_inter] + grind + +theorem convex_normal_form (a : PathSpace) (bs masks : List PathSpace) : + Same (convexSubtract (convexMeetMany a bs) masks.flatten) + (live (interMany a bs) (diff (interMany (hull a) (bs.map hull)) masks.flatten)) := by + intro p; simp only [mem_convexSubtract,hull_convexMeetMany,convexMeetMany_normal,mem_live,mem_diff]; grind + +def convexSubtractMany (a : PathSpace) : List PathSpace → PathSpace + | [] => a + | b :: bs => convexSubtractMany (convexSubtract a b) bs + +theorem convexSubtractMany_normal (a : PathSpace) (masks : List PathSpace) : + Same (convexSubtractMany a masks) (convexSubtract a masks.flatten) := by + induction masks generalizing a with + | nil => exact fun p => (convexSubtract_empty_right a p).symm + | cons b bs ih => intro p; exact (ih (convexSubtract a b) p).trans (convexSubtract_action a b bs.flatten p) + +theorem convex_many_normal_form (a : PathSpace) (bs masks : List PathSpace) : + Same (convexSubtractMany (convexMeetMany a bs) masks) + (live (interMany a bs) (diff (interMany (hull a) (bs.map hull)) masks.flatten)) := + fun p => (convexSubtractMany_normal _ _ p).trans (convex_normal_form a bs masks p) + +end PathMapModel.PathSpace diff --git a/lean/PathMapModel/ConvexPruning.lean b/lean/PathMapModel/ConvexPruning.lean new file mode 100644 index 00000000..6266eb22 --- /dev/null +++ b/lean/PathMapModel/ConvexPruning.lean @@ -0,0 +1,174 @@ +import PathMapModel.ConvexOrder + +namespace PathMapModel.PathSpace + +/-- Remove every currently exposed, unprotected tip. -/ +def convexPruneStep (x tips : PathSpace) : PathSpace := diff x (diff (hull x) tips) +def convexPrune (tips : PathSpace) : Nat → PathSpace → PathSpace + | 0, x => x + | n + 1, x => convexPruneStep (convexPrune tips n x) tips + +theorem mem_pruneStep (x tips : PathSpace) (p : Path) : + p ∈ convexPruneStep x tips ↔ p ∈ x ∧ (p ∈ tips ∨ ∃ q ∈ x, p ≠ q ∧ (p ≼ q) = true) := by + simp only [convexPruneStep,mem_diff,mem_hull]; grind + +theorem prune_subset (tips : PathSpace) (n : Nat) (x : PathSpace) : Included (convexPrune tips n x) x := by + induction n with + | zero => exact fun _ h => h + | succ n ih => intro p hp; exact ih p ((mem_pruneStep _ _ _).mp hp).1 + +theorem prune_protected {tips x : PathSpace} (ht : Included tips x) (n : Nat) : Included tips (convexPrune tips n x) := by + induction n with + | zero => exact ht + | succ n ih => intro p hp; exact (mem_pruneStep _ _ _).mpr ⟨ih p hp,Or.inl hp⟩ + +theorem prune_preserves_live {tips x : PathSpace} (ht : Included tips x) (n : Nat) : + Included (live x tips) (convexPrune tips n x) := by + induction n with + | zero => intro p hp; exact ((mem_live _ _ _).mp hp).1 + | succ n ih => + intro p hp; obtain ⟨_,t,htip,hpt⟩ := (mem_live _ _ _).mp hp + apply (mem_pruneStep _ _ _).mpr; refine ⟨ih p hp,?_⟩ + by_cases he : p = t + · exact Or.inl (he ▸ htip) + · exact Or.inr ⟨t,prune_protected ht n t htip,he,hpt⟩ + +/-- Every unsupported survivor forces a chain at least n symbols longer. -/ +theorem prune_unsupported_length (tips x : PathSpace) (n : Nat) {p : Path} + (hp : p ∈ convexPrune tips n x) (hn : ¬ ∃ t ∈ tips, (p ≼ t) = true) : + p.length + n ≤ height x := by + induction n generalizing p with + | zero => simpa only [convexPrune, Nat.add_zero] using length_le_height hp + | succ n ih => + obtain ⟨_,ht | ⟨q,hq,hne,hpq⟩⟩ := (mem_pruneStep _ _ _).mp hp + · exact False.elim (hn ⟨p,ht,Path.prefix_self p⟩) + · have hqn : ¬ ∃ t ∈ tips, (q ≼ t) = true := by + rintro ⟨t,ht,hqt⟩; exact hn ⟨t,ht,Path.prefix_trans hpq hqt⟩ + have hi := ih hq hqn + have hl := Path.prefix_length hpq + have hs : p.length < q.length := by + by_cases h : q.length ≤ p.length + · exact False.elim (hne (Path.prefix_eq_of_length hpq h)) + · omega + omega + +/-- A uniform height bound, valid even when the protected set is not maximal. -/ +theorem convexPrune_stable {tips x : PathSpace} (ht : Included tips x) {n : Nat} + (hn : height x < n) : Same (convexPrune tips n x) (live x tips) := by + intro p; constructor + · intro hp + have hx := prune_subset tips n x p hp + by_cases he : ∃ t ∈ tips, (p ≼ t) = true + · exact (mem_live _ _ _).mpr ⟨hx,he⟩ + · have hh := prune_unsupported_length tips x n hp he; omega + · exact prune_preserves_live ht n p + +theorem live_prune_fixed {tips x : PathSpace} (ht : Included tips x) : + Same (convexPruneStep (live x tips) tips) (live x tips) := by + intro p; rw [mem_pruneStep]; constructor + · exact And.left + · intro hp; obtain ⟨_,t,htip,hpt⟩ := (mem_live _ _ _).mp hp + refine ⟨hp,?_⟩ + by_cases he : p = t + · exact Or.inl (he ▸ htip) + · exact Or.inr ⟨t,(mem_live _ _ _).mpr ⟨ht t htip,t,htip,Path.prefix_self t⟩,he,hpt⟩ + +/-- Asynchronous pruning may remove any collection of exposed unprotected tips. -/ +def PruneMove (tips x y : PathSpace) : Prop := + Included y x ∧ Included (convexPruneStep x tips) y +inductive PruneTrace (tips : PathSpace) : PathSpace → PathSpace → Prop + | refl (x) : PruneTrace tips x x + | step {x y z} : PruneTrace tips x y → PruneMove tips y z → PruneTrace tips x z + +theorem pruneMove_live {tips x y : PathSpace} (ht : Included tips x) + (h : PruneMove tips x y) : Same (live x tips) (live y tips) := by + intro p; rw [mem_live,mem_live]; constructor + · rintro ⟨hp,t,hti,hpt⟩ + refine ⟨h.2 p ((mem_pruneStep _ _ _).mpr ⟨hp,?_⟩),t,hti,hpt⟩ + by_cases he : p = t + · exact Or.inl (he ▸ hti) + · exact Or.inr ⟨t,ht t hti,he,hpt⟩ + · rintro ⟨hp,t,hti,hpt⟩; exact ⟨h.1 p hp,t,hti,hpt⟩ + +theorem pruneTrace_invariant {tips x y : PathSpace} (ht : Included tips x) + (h : PruneTrace tips x y) : Included tips y ∧ Same (live x tips) (live y tips) := by + induction h with + | refl => exact ⟨ht,fun _ => Iff.rfl⟩ + | step h hm ih => + refine ⟨?_,fun p => (ih.2 p).trans (pruneMove_live ih.1 hm p)⟩ + intro p hp; exact hm.2 p ((mem_pruneStep _ _ _).mpr ⟨ih.1 p hp,Or.inl hp⟩) + +theorem prune_fixed_iff (tips x : PathSpace) : + Same (convexPruneStep x tips) x → Same x (live x tips) := by + intro h p; rw [mem_live]; constructor + · intro hp; obtain ⟨t,ht,hpt⟩ := hull_covers hp + have hh := (mem_pruneStep _ _ _).mp ((h t).mpr (hull_subset _ ht)) + rcases hh.2 with htip | ⟨q,hq,hne,htq⟩ + · exact ⟨hp,t,htip,hpt⟩ + · exact False.elim (hne (hull_max ht hq htq)) + · exact And.left + +/-- Every terminal result of arbitrary tip-removal order is the same closed form. -/ +theorem convexPrune_confluent {tips x y : PathSpace} (ht : Included tips x) + (h : PruneTrace tips x y) (hf : Same (convexPruneStep y tips) y) : + Same y (live x tips) := by + intro p; exact (prune_fixed_iff tips y hf p).trans ((pruneTrace_invariant ht h).2 p).symm + +/-- Every effective asynchronous deletion strictly decreases finite cardinality. -/ +theorem pruneMove_decreases {tips x y : PathSpace} (h : PruneMove tips x y) + (hn : ¬ Same x y) : count y < count x := by + classical + have hex : ∃ p, p ∈ x ∧ p ∉ y := by + have hs := h.1 + grind + obtain ⟨p,hp,hpn⟩ := hex + have hf : y.filter (fun q => !q == p) = y := by + apply List.filter_eq_self.mpr + intro q hq + have he : q ≠ p := fun he => hpn (he ▸ hq) + simp [he] + have hc : count (p :: y) = count y + 1 := by simp only [count,List.eraseDups_cons,hf,List.length_cons] + have hl : count (p :: y) ≤ count x := count_mono (by + intro q hq; rcases List.mem_cons.mp hq with rfl | hq + · exact hp + · exact h.1 q hq) + omega + +/-- Synchronous pruning is one permitted asynchronous schedule. -/ +theorem convexPrune_trace (tips x : PathSpace) (n : Nat) : PruneTrace tips x (convexPrune tips n x) := by + induction n with + | zero => exact .refl x + | succ n ih => + exact .step ih ⟨fun p hp => ((mem_pruneStep _ _ _).mp hp).1,fun _ h => h⟩ + +/-- Every reachable state has a bounded continuation to the same normal form. -/ +theorem convexPrune_join {tips x y : PathSpace} (ht : Included tips x) (h : PruneTrace tips x y) : + Same (convexPrune tips (height y + 1) y) (live x tips) := by + have hi := pruneTrace_invariant ht h + intro p; exact (convexPrune_stable hi.1 (Nat.lt_succ_self _) p).trans (hi.2 p).symm + +def convexMeetRec (a b : PathSpace) : PathSpace := + convexPrune (inter (hull a) (hull b)) (height (inter a b) + 1) (inter a b) +def convexSubtractRec (a b : PathSpace) : PathSpace := + let x := diff a (inter (hull a) b) + convexPrune (diff (hull a) b) (height x + 1) x + +theorem convexMeetRec_correct (a b : PathSpace) : Same (convexMeetRec a b) (convexMeet a b) := + convexPrune_stable (fun p hp => hull_subset _ (meet_tips_subset a b p hp)) (Nat.lt_succ_self _) + +theorem convexSubtractRec_correct (a b : PathSpace) : Same (convexSubtractRec a b) (convexSubtract a b) := by + have ht : Included (diff (hull a) b) (diff a (inter (hull a) b)) := by + intro p hp; obtain ⟨hh,hn⟩ := (mem_diff _ _ _).mp hp + exact (mem_diff _ _ _).mpr ⟨hull_subset a hh,fun hi => hn ((mem_inter _ _ _).mp hi).2⟩ + intro p + have hh := convexPrune_stable ht (Nat.lt_succ_self (height (diff a (inter (hull a) b)))) p + apply hh.trans + simp only [mem_live,mem_diff,mem_inter,mem_convexSubtract] + constructor + · grind + · rintro ⟨hp,t,htip,hn,hpt⟩ + refine ⟨⟨hp,?_⟩,t,⟨htip,hn⟩,hpt⟩ + rintro ⟨hh,hb⟩ + exact hn ((hull_max hh (hull_subset a htip) hpt) ▸ hb) + +end PathMapModel.PathSpace diff --git a/lean/PathMapModel/ConvexUnion.lean b/lean/PathMapModel/ConvexUnion.lean new file mode 100644 index 00000000..c7d66aea --- /dev/null +++ b/lean/PathMapModel/ConvexUnion.lean @@ -0,0 +1,52 @@ +import PathMapModel.ConvexMorphisms + +namespace PathMapModel.PathSpace + +theorem hull_in_subset {a b : PathSpace} (h : Included a b) {p : Path} (hp : p ∈ a) + (ht : p ∈ hull b) : p ∈ hull a := by + rw [mem_hull_max]; exact ⟨hp,fun q hq hpq => hull_max ht (h q hq) hpq⟩ + +theorem hull_union_cases {a b : PathSpace} {p : Path} (h : p ∈ hull (union a b)) : + p ∈ hull a ∨ p ∈ hull b := by + rcases List.mem_append.mp (hull_subset _ h) with ha | hb + · exact Or.inl (hull_in_subset (fun _ hq => List.mem_append_left _ hq) ha h) + · exact Or.inr (hull_in_subset (fun _ hq => List.mem_append_right _ hq) hb h) + +theorem convexMeet_union_subset (a : PathSpace) {b c : PathSpace} + (hb : IsPrefixClosed b) (hc : IsPrefixClosed c) : + Included (convexMeet a (union b c)) (union (convexMeet a b) (convexMeet a c)) := by + intro p hp; obtain ⟨ha,_,t,hta,ht,hpt⟩ := (mem_convexMeet _ _ _).mp hp + rcases hull_union_cases ht with htb | htc + · exact List.mem_append_left _ ((mem_convexMeet _ _ _).mpr ⟨ha,hb t (hull_subset _ htb) p hpt,t,hta,htb,hpt⟩) + · exact List.mem_append_right _ ((mem_convexMeet _ _ _).mpr ⟨ha,hc t (hull_subset _ htc) p hpt,t,hta,htc,hpt⟩) + +theorem convexMeet_union (a : PathSpace) {b c : PathSpace} + (hb : IsPrefixClosed b) (hc : IsPrefixClosed c) (h : Antichain (union (hull b) (hull c))) : + Same (convexMeet a (union b c)) (union (convexMeet a b) (convexMeet a c)) := by + intro p; refine ⟨convexMeet_union_subset a hb hc p,?_⟩ + intro hp; rcases List.mem_append.mp hp with hp | hp + · obtain ⟨ha,hb,t,hta,htb,hpt⟩ := (mem_convexMeet _ _ _).mp hp + exact (mem_convexMeet _ _ _).mpr ⟨ha,List.mem_append_left _ hb,t,hta,(hull_union_compatible h t).mpr (List.mem_append_left _ htb),hpt⟩ + · obtain ⟨ha,hc,t,hta,htc,hpt⟩ := (mem_convexMeet _ _ _).mp hp + exact (mem_convexMeet _ _ _).mpr ⟨ha,List.mem_append_right _ hc,t,hta,(hull_union_compatible h t).mpr (List.mem_append_right _ htc),hpt⟩ + +theorem convexSubtract_union_source {a b c : PathSpace} + (ha : IsPrefixClosed a) (hb : IsPrefixClosed b) (hc : IsPrefixClosed c) : + Same (convexSubtract (union a b) c) (union (convexSubtract a c) (convexSubtract b c)) := by + intro p; constructor + · intro hp; obtain ⟨_,t,ht,hn,hpt⟩ := (mem_convexSubtract _ _ _).mp hp + rcases hull_union_cases ht with hta | htb + · exact List.mem_append_left _ ((mem_convexSubtract _ _ _).mpr ⟨ha t (hull_subset _ hta) p hpt,t,hta,hn,hpt⟩) + · exact List.mem_append_right _ ((mem_convexSubtract _ _ _).mpr ⟨hb t (hull_subset _ htb) p hpt,t,htb,hn,hpt⟩) + · have lift : ∀ t ∈ union a b, t ∉ c → ∃ r ∈ hull (union a b), r ∉ c ∧ (t ≼ r) = true := by + intro t ht hn; obtain ⟨r,hr,htr⟩ := hull_covers ht + exact ⟨r,hr,fun hrc => hn (hc r hrc t htr),htr⟩ + intro hp; rcases List.mem_append.mp hp with hp | hp + · obtain ⟨hp,t,ht,hn,hpt⟩ := (mem_convexSubtract _ _ _).mp hp + obtain ⟨r,hr,hrn,htr⟩ := lift t (List.mem_append_left _ (hull_subset _ ht)) hn + exact (mem_convexSubtract _ _ _).mpr ⟨List.mem_append_left _ hp,r,hr,hrn,Path.prefix_trans hpt htr⟩ + · obtain ⟨hp,t,ht,hn,hpt⟩ := (mem_convexSubtract _ _ _).mp hp + obtain ⟨r,hr,hrn,htr⟩ := lift t (List.mem_append_right _ (hull_subset _ ht)) hn + exact (mem_convexSubtract _ _ _).mpr ⟨List.mem_append_right _ hp,r,hr,hrn,Path.prefix_trans hpt htr⟩ + +end PathMapModel.PathSpace From 5e5294e0f4b8b00508d42dc654d177665165a812 Mon Sep 17 00:00:00 2001 From: adamv-symbolica Date: Tue, 17 Nov 2026 11:38:04 +0000 Subject: [PATCH 04/15] Implement convex meet and subtraction Add native and zipper traversals that preserve left payloads, retain supporting interiors, and share unchanged subtrees. Use direct byte/list kernels with lazy reconstruction and explicit stacks for unary spines. Check both traversals against independent repeated pruning, exercise every native representation pairing, and cover dangling paths, focus restoration, allocator differences, subtree sharing, and deep spines. --- src/dense_byte_node.rs | 48 +- src/experimental.rs | 3 + src/experimental/convex.rs | 74 +++ src/experimental/convex/native.rs | 785 ++++++++++++++++++++++++ src/experimental/convex/native/tests.rs | 310 ++++++++++ src/experimental/convex/zipper.rs | 249 ++++++++ src/line_list_node.rs | 19 + src/trie_ref.rs | 9 + tests/convex.rs | 367 +++++++++++ 9 files changed, 1863 insertions(+), 1 deletion(-) create mode 100644 src/experimental/convex.rs create mode 100644 src/experimental/convex/native.rs create mode 100644 src/experimental/convex/native/tests.rs create mode 100644 src/experimental/convex/zipper.rs create mode 100644 tests/convex.rs diff --git a/src/dense_byte_node.rs b/src/dense_byte_node.rs index b82ce57f..129dfec5 100644 --- a/src/dense_byte_node.rs +++ b/src/dense_byte_node.rs @@ -13,7 +13,7 @@ use crate::trie_node::*; use crate::line_list_node::LineListNode; //NOTE: This: `core::array::from_fn(|i| i as u8);` ought to work, but https://github.com/rust-lang/rust/issues/109341 -const ALL_BYTES: [u8; 256] = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 36, 37, 38, 39, 40, 41, 42, 43, 44, 45, 46, 47, 48, 49, 50, 51, 52, 53, 54, 55, 56, 57, 58, 59, 60, 61, 62, 63, 64, 65, 66, 67, 68, 69, 70, 71, 72, 73, 74, 75, 76, 77, 78, 79, 80, 81, 82, 83, 84, 85, 86, 87, 88, 89, 90, 91, 92, 93, 94, 95, 96, 97, 98, 99, 100, 101, 102, 103, 104, 105, 106, 107, 108, 109, 110, 111, 112, 113, 114, 115, 116, 117, 118, 119, 120, 121, 122, 123, 124, 125, 126, 127, 128, 129, 130, 131, 132, 133, 134, 135, 136, 137, 138, 139, 140, 141, 142, 143, 144, 145, 146, 147, 148, 149, 150, 151, 152, 153, 154, 155, 156, 157, 158, 159, 160, 161, 162, 163, 164, 165, 166, 167, 168, 169, 170, 171, 172, 173, 174, 175, 176, 177, 178, 179, 180, 181, 182, 183, 184, 185, 186, 187, 188, 189, 190, 191, 192, 193, 194, 195, 196, 197, 198, 199, 200, 201, 202, 203, 204, 205, 206, 207, 208, 209, 210, 211, 212, 213, 214, 215, 216, 217, 218, 219, 220, 221, 222, 223, 224, 225, 226, 227, 228, 229, 230, 231, 232, 233, 234, 235, 236, 237, 238, 239, 240, 241, 242, 243, 244, 245, 246, 247, 248, 249, 250, 251, 252, 253, 254, 255]; +pub(crate) const ALL_BYTES: [u8; 256] = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 36, 37, 38, 39, 40, 41, 42, 43, 44, 45, 46, 47, 48, 49, 50, 51, 52, 53, 54, 55, 56, 57, 58, 59, 60, 61, 62, 63, 64, 65, 66, 67, 68, 69, 70, 71, 72, 73, 74, 75, 76, 77, 78, 79, 80, 81, 82, 83, 84, 85, 86, 87, 88, 89, 90, 91, 92, 93, 94, 95, 96, 97, 98, 99, 100, 101, 102, 103, 104, 105, 106, 107, 108, 109, 110, 111, 112, 113, 114, 115, 116, 117, 118, 119, 120, 121, 122, 123, 124, 125, 126, 127, 128, 129, 130, 131, 132, 133, 134, 135, 136, 137, 138, 139, 140, 141, 142, 143, 144, 145, 146, 147, 148, 149, 150, 151, 152, 153, 154, 155, 156, 157, 158, 159, 160, 161, 162, 163, 164, 165, 166, 167, 168, 169, 170, 171, 172, 173, 174, 175, 176, 177, 178, 179, 180, 181, 182, 183, 184, 185, 186, 187, 188, 189, 190, 191, 192, 193, 194, 195, 196, 197, 198, 199, 200, 201, 202, 203, 204, 205, 206, 207, 208, 209, 210, 211, 212, 213, 214, 215, 216, 217, 218, 219, 220, 221, 222, 223, 224, 225, 226, 227, 228, 229, 230, 231, 232, 233, 234, 235, 236, 237, 238, 239, 240, 241, 242, 243, 244, 245, 246, 247, 248, 249, 250, 251, 252, 253, 254, 255]; /// A ByteNode with insides that **cannot** be shared across threads pub type DenseByteNode = ByteNode, A>; @@ -410,6 +410,52 @@ impl> ByteNode impl> ByteNode where Self: TrieNodeDowncast { + /// Direct ordered output construction for the convex byte kernels. `visit` + /// selects candidate entries; entries outside it are dropped. As in pmeet, + /// slots are addressed by word-local ranks, without node iteration or edits. + /// Delay allocation and payload cloning until the first actual change. + pub(crate) fn convex_entries( + &self, visit: ByteMask, + mut entry: impl FnMut(u8, &Cf) -> AlgebraicResult, + ) -> AlgebraicResult> { + debug_assert_eq!(visit & self.mask, visit); + let mut mask = visit; + let mut output = (visit != self.mask).then(|| + ValuesVec::with_capacity_in(visit.count_bits(), self.alloc.clone())); + let mut base = 0; + for word in 0..4 { + let mut bits = visit.0[word]; + while bits != 0 { + let bit = bits.trailing_zeros(); + let slot = Self::slot_in_word(self.mask.0[word], base, bit); + let byte = (word * 64 + bit as usize) as u8; + let cf = &self.values[slot]; + let result = entry(byte, cf); + if !matches!(result, AlgebraicResult::Identity(_)) && output.is_none() { + let mut values = ValuesVec::with_capacity_in(visit.count_bits(), self.alloc.clone()); + values.v.extend(self.values[..slot].iter().cloned()); + output = Some(values); + } + match result { + AlgebraicResult::None => mask.clear_bit(byte), + AlgebraicResult::Identity(id) => { + debug_assert_eq!(id, SELF_IDENT); + if let Some(out) = &mut output { out.v.push(cf.clone()); } + }, + AlgebraicResult::Element(cf) => output.as_mut().unwrap().v.push(cf), + } + bits &= bits - 1; + } + base += self.mask.0[word].count_ones() as usize; + } + if mask.is_empty_mask() { return AlgebraicResult::None; } + match output { + None => AlgebraicResult::Identity(SELF_IDENT), + Some(values) => AlgebraicResult::Element(TrieNodeODRc::new_in( + Self::new_with_fields_in(mask, values, self.alloc.clone()), self.alloc.clone())), + } + } + /// Internal method to subtract nodes of an abstract type from the node fn psubtract_abstract(&self, other: &dyn TrieNode) -> AlgebraicResult> where V: Clone + DistributiveLattice { let mut is_identity = true; diff --git a/src/experimental.rs b/src/experimental.rs index 92c501e3..a1be1101 100644 --- a/src/experimental.rs +++ b/src/experimental.rs @@ -15,6 +15,9 @@ pub mod serialization; /// Prefix basis, hull, branches, and cross-space divergence. pub mod path_sets; +/// Stable convex meet and subtract, with zipper and physical-node traversals. +pub mod convex; + #[cfg(feature = "zipper_alg")] pub mod zipper_algebra; #[cfg(not(feature = "zipper_alg"))] diff --git a/src/experimental/convex.rs b/src/experimental/convex.rs new file mode 100644 index 00000000..f96bb87f --- /dev/null +++ b/src/experimental/convex.rs @@ -0,0 +1,74 @@ +//! Stable convex algebra on valued paths, preserving left-hand payloads. +//! +//! `meet(A,B) = live(A ∩ B, Hull(A) ∩ Hull(B))` and +//! `subtract(A,B) = live(A, Hull(A) \ B)`. In particular, a masked interior +//! survives if it supports a surviving original tip. `live(X, T)` selects the +//! paths in `X` that prefix a tip in `T`; `Hull` selects prefix-maximal valued +//! paths. Bare paths are not tips. +//! +//! The zipper and physical-node implementations are independent postorder +//! traversals. Neither materializes Hull, iterates pruning rounds, enumerates +//! pairs of keys, nor computes subtree cardinalities. Unaffected subtrees are shared. +//! +//! Geometry observes values only: a path is a tip when it has a value and no +//! strictly descending value. The result preserves left payloads without a +//! `Lattice` bound. Bare structure may be retained by sharing, so agreement with +//! Lean's canonical mixed-map adapters is by valued lookup, not bare locations. +//! +//! The zipper uses a heap stack. Native kernels recurse at branching nodes and +//! peel unary spines onto a heap stack (including valued spines). With fixed +//! node capacities, time is linear in inspected overlap, first-witness fringes, +//! and copying/writing work, with O(height) scratch space. Shared DAG nodes +//! are counted per visited occurrence. +//! Witness searches stop at the first value, but a wholly bare fringe requires +//! a full scan. Replacing an output also incurs its destruction/COW cost. +//! +//! ``` +//! use pathmap::{PathMap, experimental::convex::{convex_meet, convex_subtract}}; +//! let mut a = PathMap::new(); +//! for (p, v) in [("a", 1), ("ab", 2), ("ac", 3)] { a.set_val_at(p, v); } +//! let mut b = PathMap::new(); +//! b.set_val_at("a", ()); b.set_val_at("ab", ()); +//! assert_eq!(convex_meet(&a, &b).val_count(), 2); +//! let difference = convex_subtract(&a, &b); +//! assert_eq!(difference.get_val_at("a"), Some(&1)); // supports surviving ac +//! assert_eq!(difference.get_val_at("ab"), None); +//! assert_eq!(difference.get_val_at("ac"), Some(&3)); +//! ``` + +mod native; +mod zipper; + +pub use native::{convex_meet, convex_subtract}; +pub use zipper::{zipper_convex_meet, zipper_convex_subtract}; + +#[derive(Clone, Copy, Default)] +struct Summary { + /// The summarized subtree contains an original value. + live: bool, + /// The summarized subtree contains a retained value. + kept: bool, +} + +impl Summary { + fn include(&mut self, other: Self) { + self.live |= other.live; + self.kept |= other.kept; + } +} + +// Here the summary covers strict descendants of the candidate value. +// Testing original liveness prevents a newly exposed interior becoming +// a tip during stable pruning. Right liveness is needed only at a candidate tip. +#[inline] +fn keep_value( + s: Summary, + right_val: bool, + right_live: impl FnOnce() -> bool, +) -> bool { + if SUBTRACT { + s.kept || (!s.live && !right_val) + } else { + right_val && (s.kept || (!s.live && !right_live())) + } +} diff --git a/src/experimental/convex/native.rs b/src/experimental/convex/native.rs new file mode 100644 index 00000000..02792406 --- /dev/null +++ b/src/experimental/convex/native.rs @@ -0,0 +1,785 @@ +use super::{Summary, keep_value}; +use crate::{ + PathMap, + alloc::Allocator, + dense_byte_node::{ALL_BYTES, ByteNode, CoFree}, + line_list_node::LineListNode, + ring::{AlgebraicResult, SELF_IDENT}, + trie_node::{ + CELL_BYTE_NODE_TAG, DENSE_BYTE_NODE_TAG, EMPTY_NODE_TAG, LINE_LIST_NODE_TAG, + NODE_ITER_FINISHED, PayloadRef, TINY_REF_NODE_TAG, TaggedNodeRef, TrieNodeDowncast, + TrieNodeODRc, ValOrChild, + }, + trie_ref::TrieRefBorrowed, + utils::{BitMask, ByteMask}, + zipper::{zipper_priv::ZipperReadOnlyPriv, *}, +}; +use smallvec::SmallVec; + +// Stop at the first valued witness, including values above dangling children. +fn node_live(root: &TrieNodeODRc) -> bool { + if root + .as_tagged() + .as_list() + .is_some_and(|n| n.is_used_value_0() || n.is_used_value_1()) + { + return true; + } + let mut stack: SmallVec<[_; 8]> = + smallvec::smallvec![(root, root.as_tagged().new_iter_token())]; + while let Some((n, tok)) = stack.last_mut() { + let (next, _, child, val) = n.as_tagged().next_items(*tok, false); + if next == NODE_ITER_FINISHED { + stack.pop(); + continue; + } + if val.is_some() { + return true; + } + *tok = next; + if let Some(child) = child { + stack.push((child, child.as_tagged().new_iter_token())); + } + } + false +} + +fn ref_live_below( + right: &TrieRefBorrowed<'_, W, B>, +) -> bool { + if right.child_count() == 0 { + return false; + } + let (node, key, _) = right.borrow_raw_parts(); + let mut tok = if key.is_empty() { + node.new_iter_token() + } else { + node.iter_token_for_path(key) + }; + loop { + let (next, p, child, val) = node.next_items(tok, false); + if next == NODE_ITER_FINISHED || !p.starts_with(key) { + return false; + } + if val.is_some() || child.is_some_and(node_live) { + return true; + } + tok = next; + } +} + +type NodeResult = (Option>, Summary); + +fn cf_result( + cf: &Cf, + child: Option>, + keep: bool, +) -> AlgebraicResult { + let same_child = match (cf.rec(), &child) { + (None, None) => true, + (Some(a), Some(b)) => a.ptr_eq(b), + _ => false, + }; + if same_child && cf.has_val() == keep { + AlgebraicResult::Identity(SELF_IDENT) + } else if child.is_none() && !keep { + AlgebraicResult::None + } else { + AlgebraicResult::Element(Cf::new(child, if keep { cf.val().cloned() } else { None })) + } +} + +fn byte_live, A: Allocator>(node: &ByteNode, mask: ByteMask) -> bool { + mask.iter().any(|b| { + // The caller supplies a subset of the immutable node's mask. + let cf = unsafe { node.get_unchecked(b) }; + cf.has_val() || cf.rec().is_some_and(node_live) + }) +} + +// Dense/Dense, Dense/Cell, Cell/Dense and Cell/Cell all use this CoFree kernel, +// just as ordinary meet/join/subtract do. The right value type and allocator +// may differ; only the left payload is ever copied into the output. +fn byte_pair( + left: &ByteNode, + right: &ByteNode, + alloc: B, +) -> (AlgebraicResult>, Summary) +where + L: CoFree, + R: CoFree, + R::V: Unpin, + A: Allocator, + B: Allocator, + ByteNode: TrieNodeDowncast, +{ + let common = left.mask & right.mask; + let outside_live = byte_live(left, left.mask & !common); + let mut total = Summary { + live: outside_live, + kept: SUBTRACT && outside_live, + }; + let result = left.convex_entries(if SUBTRACT { left.mask } else { common }, |byte, l| { + if !common.test_bit(byte) { + return AlgebraicResult::Identity(SELF_IDENT); + } + let r = unsafe { right.get_unchecked(byte) }; + let (child, mut s) = match l.rec() { + None => (None, Summary::default()), + Some(lc) => child_pair::(lc, r.rec()).unwrap_or_else(|| { + let rc = r.rec().unwrap(); + node_op::( + lc, + TrieRefBorrowed::new_with_key_and_path_in(rc, || None, &[], &[], alloc.clone()), + ) + }), + }; + let keep = l.has_val() + && keep_value::(s, r.has_val(), || r.rec().is_some_and(node_live)); + s.live |= l.has_val(); + s.kept |= keep; + total.include(s); + cf_result(l, child, keep) + }); + ( + if total.kept { + result + } else { + AlgebraicResult::None + }, + total, + ) +} + +// Mixed byte/compact and compressed-offset kernel. A compact right-hand node +// contributes at most two leading bytes, so meet only visits those candidates. +// Subtraction visits the left slots, reusing the disjoint entries verbatim. +fn byte_compact( + left: &ByteNode, + right: &TrieRefBorrowed<'_, W, B>, +) -> (AlgebraicResult>, Summary) +where + L: CoFree, + W: Clone + Send + Sync + Unpin, + A: Allocator, + B: Allocator, + ByteNode: TrieNodeDowncast, +{ + let common = left.mask & right.child_mask(); + let outside_live = byte_live(left, left.mask & !common); + let mut total = Summary { + live: outside_live, + kept: SUBTRACT && outside_live, + }; + let result = left.convex_entries(if SUBTRACT { left.mask } else { common }, |byte, l| { + if !common.test_bit(byte) { + return AlgebraicResult::Identity(SELF_IDENT); + } + let (child, mut s, keep) = if right.aligned_node().is_some() { + // Byte/List uses direct right slots too, including same-key + // child/value pairs. Only an edge spanning the next node needs + // the offset/path adaptation inside child_view or keep_at. + let (child, s) = l.rec().map_or((None, Summary::default()), |lc| { + node_op::(lc, child_view(right, &[byte])) + }); + let keep = l.has_val() && keep_at::(right, &[byte], s); + (child, s, keep) + } else { + // For an offset, resolve the byte once and share that view between + // the child and value checks. + let r = right.trie_ref_at_path(&[byte]); + let (child, s) = l.rec().map_or((None, Summary::default()), |lc| { + node_op::(lc, r.clone()) + }); + let keep = l.has_val() && keep_value::(s, r.is_val(), || ref_live_below(&r)); + (child, s, keep) + }; + s.live |= l.has_val(); + s.kept |= keep; + total.include(s); + cf_result(l, child, keep) + }); + ( + if total.kept { + result + } else { + AlgebraicResult::None + }, + total, + ) +} + +fn byte_dispatch( + left: &ByteNode, + right: &TrieRefBorrowed<'_, W, B>, +) -> (AlgebraicResult>, Summary) +where + L: CoFree, + W: Clone + Send + Sync + Unpin, + A: Allocator, + B: Allocator, + ByteNode: TrieNodeDowncast, +{ + if let Some(r) = right.aligned_node() { + match r.tag() { + DENSE_BYTE_NODE_TAG => { + return byte_pair::( + left, + unsafe { r.as_dense_unchecked() }, + right.alloc(), + ); + } + CELL_BYTE_NODE_TAG => { + return byte_pair::( + left, + unsafe { r.as_cell_unchecked() }, + right.alloc(), + ); + } + _ => {} + } + } + byte_compact::(left, right) +} + +// Direct right-representation queries for the compact kernels. A query that +// crosses a child boundary uses the same native path lookup required by +// ordinary pmeet_generic; aligned local slots never go through that lookup. +fn keep_at( + right: &TrieRefBorrowed<'_, W, B>, + key: &[u8], + s: Summary, +) -> bool { + if SUBTRACT && s.kept { + return true; + } + if !s.kept && s.live { + return false; + } + if let Some(n) = right.aligned_node() { + match n.tag() { + DENSE_BYTE_NODE_TAG if key.len() == 1 => { + let d = unsafe { n.as_dense_unchecked() }; + if !d.mask.test_bit(key[0]) { + return SUBTRACT; + } + let cf = unsafe { d.get_unchecked(key[0]) }; + return keep_value::(s, cf.has_val(), || cf.rec().is_some_and(node_live)); + } + CELL_BYTE_NODE_TAG if key.len() == 1 => { + let d = unsafe { n.as_cell_unchecked() }; + if !d.mask.test_bit(key[0]) { + return SUBTRACT; + } + let cf = unsafe { d.get_unchecked(key[0]) }; + return keep_value::(s, cf.has_val(), || cf.rec().is_some_and(node_live)); + } + LINE_LIST_NODE_TAG => { + let slots = unsafe { n.as_list_unchecked() }.convex_slots(); + let crosses_child = slots.iter().any(|(p, payload)| { + matches!(payload, PayloadRef::Child(_)) + && p.len() < key.len() + && key.starts_with(p) + }); + if !crosses_child { + let value = slots + .iter() + .any(|(p, payload)| *p == key && matches!(payload, PayloadRef::Val(_))); + return keep_value::(s, value, || { + slots.iter().any(|(p, payload)| { + if !p.starts_with(key) { + return false; + } + match payload { + PayloadRef::Val(_) => p.len() > key.len(), + PayloadRef::Child(c) => node_live(c), + PayloadRef::None => false, + } + }) + }); + } + } + EMPTY_NODE_TAG => return SUBTRACT, + _ => {} + } + } + let r = right.trie_ref_at_path(key); + keep_value::(s, r.is_val(), || ref_live_below(&r)) +} + +// Recursive child kernels never inspect their focus value. Borrow an aligned +// right child directly (List/List and List/byte included), without creating a +// compressed-offset view and looking the same path up again on the next call. +fn child_view<'a, W: Clone + Send + Sync + Unpin, B: Allocator>( + right: &TrieRefBorrowed<'a, W, B>, + key: &[u8], +) -> TrieRefBorrowed<'a, W, B> { + let child = right.aligned_node().and_then(|n| match n.tag() { + LINE_LIST_NODE_TAG => unsafe { n.as_list_unchecked() } + .convex_slots() + .into_iter() + .find_map(|(p, payload)| { + if p != key { + return None; + } + if let PayloadRef::Child(c) = payload { + Some(c) + } else { + None + } + }), + DENSE_BYTE_NODE_TAG if key.len() == 1 => { + let d = unsafe { n.as_dense_unchecked() }; + if d.mask.test_bit(key[0]) { + unsafe { d.get_unchecked(key[0]) }.rec() + } else { + None + } + } + CELL_BYTE_NODE_TAG if key.len() == 1 => { + let d = unsafe { n.as_cell_unchecked() }; + if d.mask.test_bit(key[0]) { + unsafe { d.get_unchecked(key[0]) }.rec() + } else { + None + } + } + _ => None, + }); + match child { + Some(c) => TrieRefBorrowed::new_with_key_and_path_in(c, || None, &[], &[], right.alloc()), + None => right.trie_ref_at_path(key), + } +} + +// Exactly two local payload slots, using the same reconstruction helper as +// LineListNode::psubtract_dyn. Children and longer values precede their prefix +// values: a prefix value must see the final support of the other slot. +fn list_kernel( + left: &LineListNode, + right: &TrieRefBorrowed<'_, W, B>, + mut child_result: Option>, +) -> (AlgebraicResult>, Summary) +where + V: Clone + Send + Sync, + W: Clone + Send + Sync + Unpin, + A: Allocator, + B: Allocator, +{ + let slots = left.convex_slots(); + let first = if matches!(slots[1].1, PayloadRef::Child(_)) + || (matches!(slots[0].1, PayloadRef::Val(_)) && slots[1].0.len() > slots[0].0.len()) + { + 1 + } else { + 0 + }; + let mut summaries = [Summary::default(); 2]; + let mut results = [AlgebraicResult::None, AlgebraicResult::None]; + for i in [first, 1 - first] { + let (key, payload) = slots[i]; + match payload { + PayloadRef::None => {} + PayloadRef::Child(child) => { + let (out, s) = child_result.take().unwrap_or_else(|| { + node_op::(child, child_view(right, key)) + }); + summaries[i] = s; + results[i] = match out { + None => AlgebraicResult::None, + Some(out) if out.ptr_eq(child) => AlgebraicResult::Identity(SELF_IDENT), + Some(out) => AlgebraicResult::Element(ValOrChild::Child(out)), + }; + } + PayloadRef::Val(_) => { + let s = if slots[1 - i].0.starts_with(key) { + summaries[1 - i] + } else { + Summary::default() + }; + let keep = keep_at::(right, key, s); + summaries[i] = Summary { + live: true, + kept: keep, + }; + if keep { + results[i] = AlgebraicResult::Identity(SELF_IDENT); + } + } + } + } + let mut total = summaries[0]; + total.include(summaries[1]); + ( + if total.kept { + left.convex_rebuild(results) + } else { + AlgebraicResult::None + }, + total, + ) +} + +fn singleton_key<'a, V: Clone + Send + Sync, A: Allocator + 'a>( + n: TaggedNodeRef<'a, V, A>, +) -> Option<&'a [u8]> { + if n.as_list() + .is_some_and(|l| l.is_used_value_0() && !l.is_used::<1>()) + { + Some(unsafe { n.as_list_unchecked().key_unchecked::<0>() }) + } else { + None + } +} + +fn child_pair( + left: &TrieNodeODRc, + right: Option<&TrieNodeODRc>, +) -> Option> +where + V: Clone + Send + Sync, + W: Clone + Send + Sync, + A: Allocator, + B: Allocator, +{ + let Some(right) = right else { + let live = node_live(left); + let kept = SUBTRACT && live; + return Some((kept.then(|| left.clone()), Summary { live, kept })); + }; + let l = left.as_tagged(); + let r = right.as_tagged(); + if l.shared_node_id() == r.shared_node_id() { + let live = node_live(left); + let kept = !SUBTRACT && live; + return Some((kept.then(|| left.clone()), Summary { live, kept })); + } + if let (Some(l), Some(r)) = (singleton_key(l), singleton_key(r)) { + let kept = (l == r) != SUBTRACT; + return Some((kept.then(|| left.clone()), Summary { live: true, kept })); + } + None +} + +fn node_shortcut( + left: &TrieNodeODRc, + right: &TrieRefBorrowed<'_, W, B>, +) -> Option> +where + V: Clone + Send + Sync, + W: Clone + Send + Sync + Unpin, + A: Allocator, + B: Allocator, +{ + let identical = if right.child_count() != 0 { + let (r, key, _) = right.borrow_raw_parts(); + key.is_empty() && left.as_tagged().shared_node_id() == r.shared_node_id() + } else { + false + }; + if identical || (left.as_tagged().node_branches_mask(&[]) & right.child_mask()).is_empty_mask() + { + let live = node_live(left); + let kept = live && if identical { !SUBTRACT } else { SUBTRACT }; + return Some((kept.then(|| left.clone()), Summary { live, kept })); + } + // A compact node containing one value has exactly one original tip. + // Resolve it directly rather than allocating a postorder frame. + if left + .as_tagged() + .as_list() + .is_some_and(|n| n.is_used_value_0() && !n.is_used::<1>()) + { + let n = left.as_tagged(); + let key = unsafe { n.as_list_unchecked().key_unchecked::<0>() }; + let kept = keep_at::(right, key, Summary::default()); + return Some((kept.then(|| left.clone()), Summary { live: true, kept })); + } + None +} + +// Borrow the sole recursive child without enumerating node items. List nodes +// can also hold one value; a byte spine is one CoFree with an optional value. +fn byte_link, A: Allocator>( + n: &ByteNode, +) -> Option<(&[u8], &TrieNodeODRc, bool)> { + if n.mask.count_bits() != 1 { + return None; + } + let b = n.mask.indexed_bit::(0).unwrap(); + let cf = unsafe { n.get_unchecked(b) }; + cf.rec() + .map(|c| (&ALL_BYTES[b as usize..=b as usize], c, cf.has_val())) +} +fn spine_link( + n: TaggedNodeRef<'_, V, A>, +) -> Option<(&[u8], &TrieNodeODRc, bool)> { + match n.tag() { + DENSE_BYTE_NODE_TAG => byte_link(unsafe { n.as_dense_unchecked() }), + CELL_BYTE_NODE_TAG => byte_link(unsafe { n.as_cell_unchecked() }), + LINE_LIST_NODE_TAG => { + let slots = unsafe { n.as_list_unchecked() }.convex_slots(); + match (slots[0].1, slots[1].1) { + (PayloadRef::Child(_), PayloadRef::Child(_)) => None, + (PayloadRef::Child(c), other) => { + Some((slots[0].0, c, matches!(other, PayloadRef::Val(_)))) + } + (other, PayloadRef::Child(c)) => { + Some((slots[1].0, c, matches!(other, PayloadRef::Val(_)))) + } + _ => None, + } + } + _ => None, + } +} + +fn byte_spine( + left: &ByteNode, + right: &TrieRefBorrowed<'_, W, B>, + child_result: NodeResult, +) -> (AlgebraicResult>, Summary) +where + L: CoFree, + W: Clone + Send + Sync + Unpin, + A: Allocator, + B: Allocator, + ByteNode: TrieNodeDowncast, +{ + debug_assert_eq!(left.mask.count_bits(), 1); + let (mut child, mut s) = child_result; + let result = left.convex_entries(left.mask, |byte, l| { + let keep = l.has_val() && keep_at::(right, &[byte], s); + s.live |= l.has_val(); + s.kept |= keep; + cf_result(l, child.take(), keep) + }); + ( + if s.kept { + result + } else { + AlgebraicResult::None + }, + s, + ) +} + +// Same representation dispatch as ordinary algebra. `child_result` is present +// only while unwinding a unary spine, avoiding a native call per spine link. +fn native_kernel( + n: TaggedNodeRef<'_, V, A>, + right: &TrieRefBorrowed<'_, W, B>, + child_result: Option>, +) -> (AlgebraicResult>, Summary) +where + V: Clone + Send + Sync, + W: Clone + Send + Sync + Unpin, + A: Allocator, + B: Allocator, +{ + match n.tag() { + DENSE_BYTE_NODE_TAG => { + let l = unsafe { n.as_dense_unchecked() }; + match child_result { + Some(c) => byte_spine::(l, right, c), + None => byte_dispatch::(l, right), + } + } + CELL_BYTE_NODE_TAG => { + let l = unsafe { n.as_cell_unchecked() }; + match child_result { + Some(c) => byte_spine::(l, right, c), + None => byte_dispatch::(l, right), + } + } + LINE_LIST_NODE_TAG => list_kernel::( + unsafe { n.as_list_unchecked() }, + right, + child_result, + ), + EMPTY_NODE_TAG => (AlgebraicResult::None, Summary::default()), + TINY_REF_NODE_TAG => { + let tiny = unsafe { n.as_tiny_unchecked() }; + let Some(full) = tiny.into_list_node() else { + return (AlgebraicResult::None, Summary::default()); + }; + list_kernel::(&full, right, None) + } + _ => unreachable!("unsupported native node tag"), + } +} + +fn resolve( + left: &TrieNodeODRc, + result: (AlgebraicResult>, Summary), +) -> NodeResult { + let (result, s) = result; + let out = match result { + AlgebraicResult::None => None, + AlgebraicResult::Identity(id) => { + debug_assert_eq!(id, SELF_IDENT); + Some(left.clone()) + } + AlgebraicResult::Element(out) => Some(out), + }; + (out, s) +} + +// An unvalued unary link needs no right-hand cursor during reconstruction. +// Keep only its original node pointer on the spine, as the ordinary algebra +// needs only a child result at this point. +fn unvalued_link( + left: &TrieNodeODRc, + result: NodeResult, +) -> NodeResult { + let (child, s) = result; + let Some(child) = child else { + return (None, s); + }; + let n = left.as_tagged(); + if spine_link(n).unwrap().1.ptr_eq(&child) { + return (Some(left.clone()), s); + } + let result = match n.tag() { + LINE_LIST_NODE_TAG => unsafe { n.as_list_unchecked() }.convex_rebuild([ + AlgebraicResult::Element(ValOrChild::Child(child)), + AlgebraicResult::None, + ]), + DENSE_BYTE_NODE_TAG => { + let d = unsafe { n.as_dense_unchecked() }; + let mut child = Some(child); + d.convex_entries(d.mask, |_, cf| cf_result(cf, child.take(), false)) + } + CELL_BYTE_NODE_TAG => { + let d = unsafe { n.as_cell_unchecked() }; + let mut child = Some(child); + d.convex_entries(d.mask, |_, cf| cf_result(cf, child.take(), false)) + } + _ => unreachable!("unary link representation"), + }; + resolve(left, (result, s)) +} + +fn node_op( + mut left: &TrieNodeODRc, + mut right: TrieRefBorrowed<'_, W, B>, +) -> NodeResult +where + V: Clone + Send + Sync, + W: Clone + Send + Sync + Unpin, + A: Allocator, + B: Allocator, +{ + let mut spine = Vec::new(); + let mut valued_links = Vec::new(); + let mut result = loop { + if let Some(done) = node_shortcut::(left, &right) { + break done; + } + if let Some((key, child, has_value)) = spine_link(left.as_tagged()) { + let next_right = child_view(&right, key); + if has_value { + valued_links.push((spine.len(), right)); + } + spine.push(left); + left = child; + right = next_right; + } else { + break resolve( + left, + native_kernel::(left.as_tagged(), &right, None), + ); + } + }; + // If no spine link has a value, its entire support is the endpoint's. + // Reuse or discard the whole chain without per-link reconstruction or + // reference-count churn. Valued links still require the convex keep test. + if valued_links.is_empty() && !spine.is_empty() { + if result.0.is_none() { + return result; + } + if result.0.as_ref().is_some_and(|out| out.ptr_eq(left)) { + return (Some(spine[0].clone()), result.1); + } + } + while let Some(left) = spine.pop() { + if valued_links.last().is_some_and(|(i, _)| *i == spine.len()) { + let (_, right) = valued_links.pop().unwrap(); + result = resolve( + left, + native_kernel::(left.as_tagged(), &right, Some(result)), + ); + } else { + result = unvalued_link(left, result); + } + } + result +} + +fn map_op( + left: &PathMap, + right: &PathMap, +) -> PathMap +where + V: Clone + Send + Sync + Unpin, + W: Clone + Send + Sync + Unpin, + A: Allocator, + B: Allocator, +{ + if let (Some(l), Some(r)) = (left.root(), right.root()) { + if l.as_tagged().shared_node_id() == r.as_tagged().shared_node_id() { + let value = if SUBTRACT { + (right.root_val().is_none() && left.root_val().is_some() && !node_live(l)) + .then(|| left.root_val().unwrap().clone()) + } else { + right.root_val().and(left.root_val()).cloned() + }; + return PathMap::new_with_root_in( + if SUBTRACT { None } else { Some(l.clone()) }, + value, + left.alloc.clone(), + ); + } + } + let r = right.trie_ref_at_path([]); + let (node, s) = left.root().map_or((None, Summary::default()), |n| { + node_op::(n, r) + }); + let keep_root = keep_value::(s, right.root_val().is_some(), || { + ref_live_below(&right.trie_ref_at_path([])) + }); + PathMap::new_with_root_in( + node, + if keep_root { + left.root_val().cloned() + } else { + None + }, + left.alloc.clone(), + ) +} + +/// Physical-node convex meet, with lazy copy-on-write and subtree sharing. +pub fn convex_meet(left: &PathMap, right: &PathMap) -> PathMap +where + V: Clone + Send + Sync + Unpin, + W: Clone + Send + Sync + Unpin, + A: Allocator, + B: Allocator, +{ + map_op::(left, right) +} + +/// Physical-node convex subtraction, preserving left payloads. +pub fn convex_subtract(left: &PathMap, right: &PathMap) -> PathMap +where + V: Clone + Send + Sync + Unpin, + W: Clone + Send + Sync + Unpin, + A: Allocator, + B: Allocator, +{ + map_op::(left, right) +} + +#[cfg(test)] +mod tests; diff --git a/src/experimental/convex/native/tests.rs b/src/experimental/convex/native/tests.rs new file mode 100644 index 00000000..94c7c245 --- /dev/null +++ b/src/experimental/convex/native/tests.rs @@ -0,0 +1,310 @@ +use super::*; +use crate::alloc::{GlobalAlloc, global_alloc}; +use crate::dense_byte_node::{CellByteNode, DenseByteNode}; +use crate::trie_node::TrieNode; +use std::collections::{BTreeMap, BTreeSet}; + +type Node = TrieNodeODRc; +type Map = PathMap; +type Payload = ValOrChild; +const TAGS: [usize; 5] = [ + DENSE_BYTE_NODE_TAG, + CELL_BYTE_NODE_TAG, + LINE_LIST_NODE_TAG, + TINY_REF_NODE_TAG, + EMPTY_NODE_TAG, +]; + +fn list(entries: Vec<(Vec, Payload)>) -> LineListNode { + let mut node = LineListNode::new_in(global_alloc()); + for (i, (key, payload)) in entries.into_iter().enumerate() { + // At most two entries, sorted by key with children before values. + unsafe { + match i { + 0 => node.set_payload_owned::<0>(&key, payload), + 1 => node.set_payload_owned::<1>(&key, payload), + _ => unreachable!(), + } + } + } + assert!(crate::line_list_node::validate_node(&node)); + node +} +fn child(side: u64) -> Node { + let mut m = Map::new(); + m.set_val_at(b"c", 30 + side); + m.set_val_at(if side == 0 { b"d" } else { b"e" }, 40 + side); + m.root().unwrap().clone() +} +fn entries(pattern: usize, side: u64) -> Vec<(Vec, Payload)> { + let v = |p: &[u8], n| (p.to_vec(), Payload::Val(n + 100 * side)); + let c = |p: &[u8], bare| { + ( + p.to_vec(), + Payload::Child(if bare { Node::new_empty() } else { child(side) }), + ) + }; + match pattern { + 0 => vec![v(b"ab", 1), v(b"b", 2)], + 1 => vec![v(b"a", 1), c(b"ab", false)], + 2 => vec![c(b"a", false), v(b"a", 1)], + 3 => vec![c(b"ab", true), v(b"b", 2)], + 4 => vec![v(b"a", 1), v(b"ab", 2)], + 5 => vec![c(b"a", true)], + 6 => vec![c(b"a", false), c(b"b", false)], + 7 => vec![v(b"ab", 1)], + _ => unreachable!(), + } +} +fn byte>( + entries: Vec<(Vec, Payload)>, +) -> ByteNode { + let mut n = ByteNode::new_in(global_alloc()); + for (key, payload) in entries { + if key.len() == 1 { + n.set_payload_owned(key[0], payload); + } else { + n.set_child( + key[0], + Node::new_in(list(vec![(key[1..].to_vec(), payload)]), global_alloc()), + ); + } + } + n +} +// A Tiny is a real borrowed slice inside a list key, not a map that merely +// might choose a tiny representation. Empty is the actual sentinel. +fn fixture(tag: usize, pattern: usize, side: u64) -> (Node, Vec) { + let mut es = entries(pattern, side); + let (node, path) = match tag { + DENSE_BYTE_NODE_TAG => ( + Node::new_in( + byte::>(es), + global_alloc(), + ), + vec![], + ), + CELL_BYTE_NODE_TAG => ( + Node::new_in( + byte::>(es), + global_alloc(), + ), + vec![], + ), + LINE_LIST_NODE_TAG => (Node::new_in(list(es), global_alloc()), vec![]), + TINY_REF_NODE_TAG => { + es.truncate(1); + es[0].0.insert(0, b'z'); + (Node::new_in(list(es), global_alloc()), vec![b'z']) + } + EMPTY_NODE_TAG => (Node::new_empty(), vec![]), + _ => unreachable!(), + }; + (node, path) +} +fn reference<'a>(n: &'a Node, p: &[u8]) -> TrieRefBorrowed<'a, u64, GlobalAlloc> { + TrieRefBorrowed::new_with_key_and_path_in(n, || None, &[], p, global_alloc()) +} +fn own(n: TaggedNodeRef<'_, u64, GlobalAlloc>) -> Node { + if n.tag() == TINY_REF_NODE_TAG { + Node::new_in( + unsafe { n.as_tiny_unchecked() }.into_full().unwrap(), + global_alloc(), + ) + } else { + n.clone_self() + } +} +fn values(n: Option) -> BTreeMap, u64> { + Map::new_with_root_in(n, None, global_alloc()) + .iter() + .map(|(p, v)| (p, *v)) + .collect() +} +// Repeated removal, deliberately independent of the native recurrence. +fn expected( + a: &BTreeMap, u64>, + b: &BTreeMap, u64>, +) -> BTreeMap, u64> { + let tips = |m: &BTreeMap, u64>| -> BTreeSet> { + m.keys() + .filter(|p| !m.keys().any(|q| q != *p && q.starts_with(p))) + .cloned() + .collect() + }; + let at = tips(a); + let bt = tips(b); + let protected: BTreeSet<_> = at + .into_iter() + .filter(|p| { + if SUBTRACT { + !b.contains_key(p) + } else { + bt.contains(p) + } + }) + .collect(); + let mut out: BTreeMap<_, _> = a + .iter() + .filter(|(p, _)| SUBTRACT || b.contains_key(*p)) + .map(|(p, v)| (p.clone(), *v)) + .collect(); + loop { + let remove: Vec<_> = tips(&out).difference(&protected).cloned().collect(); + if remove.is_empty() { + return out; + } + for p in remove { + out.remove(&p); + } + } +} +fn matrix() { + let mut covered = BTreeSet::new(); + for lt in TAGS { + for rt in TAGS { + for lp in 0..8 { + for rp in 0..8 { + let (l, lk) = fixture(lt, lp, 0); + let (r, rk) = fixture(rt, rp, 1); + let lr = reference(&l, &lk); + let rr = reference(&r, &rk); + let lf = lr.clone().into_focus(); + let rf = rr.clone().into_focus(); + let ln = lf.try_as_tagged().unwrap_or_else(|| l.as_tagged()); + let rn = rf.try_as_tagged().unwrap_or_else(|| r.as_tagged()); + assert_eq!(ln.tag(), lt); + assert_eq!(rn.tag(), rt); + let a = values( + lf.borrow() + .cloned() + .or_else(|| (!lf.is_none()).then(|| own(ln))), + ); + let b = values( + rf.borrow() + .cloned() + .or_else(|| (!rf.is_none()).then(|| own(rn))), + ); + // Call the kernel itself: sharing, singleton, disjoint-mask, and + // spine shortcuts cannot conceal a missing dispatch arm. + let (out, summary) = native_kernel::(ln, &rr, None); + let out = out.map_into_option(|id| { + assert_eq!(id, 0); + Some(own(ln)) + }); + let out = values(out); + assert_eq!( + out, + expected::(&a, &b), + "SUBTRACT={SUBTRACT} tags={lt}/{rt} patterns={lp}/{rp}" + ); + assert_eq!(summary.live, !a.is_empty()); + assert_eq!(summary.kept, !out.is_empty()); + covered.insert((lt, rt)); + } + } + } + } + assert_eq!(covered.len(), 25); +} +#[test] +fn forced_native_meet_dispatch_matrix() { + matrix::(); +} +#[test] +fn forced_native_subtract_dispatch_matrix() { + matrix::(); +} + +#[cfg(not(feature = "nightly"))] +#[test] +fn distinct_payload_and_allocator_types() { + #[derive(Clone)] + struct RightAlloc; + impl Allocator for RightAlloc {} + let mut left = Map::new(); + let mut right = PathMap::::new_in(RightAlloc); + for b in 0..=255u8 { + left.set_val_at([b], b as u64 + 1); + left.set_val_at([b, 0], b as u64 + 1000); + right.set_val_at([b], "interior".into()); + if b % 2 == 0 { + right.set_val_at([b, 0], "tip".into()); + } + } + let meet = convex_meet(&left, &right); + let sub = convex_subtract(&left, &right); + assert_eq!(meet.val_count(), 256); + assert_eq!(sub.val_count(), 256); + for b in 0..=255u8 { + for (path, value) in [(vec![b], b as u64 + 1), (vec![b, 0], b as u64 + 1000)] { + assert_eq!(meet.get_val_at(&path), (b % 2 == 0).then_some(&value)); + assert_eq!(sub.get_val_at(&path), (b % 2 == 1).then_some(&value)); + } + } +} + +#[test] +fn native_spines_use_bounded_call_depth() { + // A 128-KiB worker stack makes accidentally recursive unary handling + // fail quickly. Construct physical spines without quadratic key inserts. + std::thread::Builder::new() + .stack_size(128 * 1024) + .spawn(|| { + let mut a = Node::new_in(list(vec![(vec![0], Payload::Val(7))]), global_alloc()); + let mut b = Node::new_in(list(vec![(vec![1], Payload::Val(9))]), global_alloc()); + for i in 0..12000 { + if i % 2 == 0 { + a = Node::new_in( + list(vec![ + (vec![0], Payload::Child(a)), + (vec![0], Payload::Val(11)), + ]), + global_alloc(), + ); + b = Node::new_in( + list(vec![ + (vec![0], Payload::Child(b)), + (vec![0], Payload::Val(12)), + ]), + global_alloc(), + ); + } else { + let mut x = DenseByteNode::new_in(global_alloc()); + x.set_child(0, a); + x.set_val(0, 13); + let mut y = CellByteNode::new_in(global_alloc()); + y.set_child(0, b); + y.set_val(0, 14); + a = Node::new_in(x, global_alloc()); + b = Node::new_in(y, global_alloc()); + } + } + assert!( + node_op::(&a, reference(&b, &[])) + .0 + .is_none() + ); + assert!( + node_op::(&a, reference(&b, &[])) + .0 + .unwrap() + .ptr_eq(&a) + ); + // Teardown explicitly: the native node Drop implementations have + // their own independent recursion limits across mixed node types. + while let Some((_, child, _)) = spine_link(a.as_tagged()) { + let next = child.clone(); + drop(a); + a = next; + } + while let Some((_, child, _)) = spine_link(b.as_tagged()) { + let next = child.clone(); + drop(b); + b = next; + } + }) + .unwrap() + .join() + .unwrap(); +} diff --git a/src/experimental/convex/zipper.rs b/src/experimental/convex/zipper.rs new file mode 100644 index 00000000..571d1484 --- /dev/null +++ b/src/experimental/convex/zipper.rs @@ -0,0 +1,249 @@ +use super::{Summary, keep_value}; +use crate::{ + alloc::Allocator, + utils::{BitMask, ByteMask}, + zipper::{zipper_priv::ZipperReadOnlyPriv, *}, +}; +use smallvec::SmallVec; + +fn pop(mask: &mut ByteMask) -> Option { + let b = mask.indexed_bit::(0)?; + mask.clear_bit(b); + Some(b) +} + +// One witness is sufficient. Fringes queried this way are disjoint. +fn zipper_live(z: &mut Z, below: bool) -> bool { + let base = z.depth(); + if !below && z.is_val() { + return true; + } + let mask = z.child_mask(); + if mask.is_empty_mask() { + return false; + } + let mut stack: SmallVec<[(ByteMask, usize); 8]> = smallvec::smallvec![(mask, base)]; + loop { + if let Some(b) = pop(&mut stack.last_mut().unwrap().0) { + z.descend_to_byte(b); + if !z.is_val() { + z.descend_until(); + } + if z.is_val() { + z.ascend(z.depth() - base); + return true; + } + stack.push((z.child_mask(), z.depth())); + } else { + stack.pop(); + let Some((_, parent)) = stack.last() else { + return false; + }; + z.ascend(z.depth() - *parent); + } + } +} + +fn graft_values(left: &L, out: &mut O) +where + V: Clone + Send + Sync, + A: Allocator, + L: ZipperInfallibleSubtries, + O: ZipperWriting, +{ + out.graft(left); + // Explicit focus handling makes semantics independent of graft_root_vals. + if let Some(v) = left.val() { + out.set_val(v.clone()); + } else { + out.remove_val(false); + } +} + +fn zipper_shortcut( + left: &mut L, + right: &R, + out: &mut O, +) -> Option +where + V: Clone + Send + Sync, + A: Allocator, + L: ZipperMoving + ZipperConcrete + ZipperInfallibleSubtries, + R: ZipperMoving + ZipperConcrete, + O: ZipperWriting, +{ + if let Some(id) = left.shared_node_id() { + if Some(id) == right.shared_node_id() { + let live = zipper_live(left, false); + if !SUBTRACT && live { + graft_values(left, out); + } + return Some(Summary { + live, + kept: !SUBTRACT && live, + }); + } + } + if right.child_count() == 0 { + let below = zipper_live(left, true); + let live = left.is_val() || below; + let kept = if SUBTRACT { + live && (below || !right.is_val()) + } else { + left.is_val() && right.is_val() && !below + }; + if kept { + if SUBTRACT { + graft_values(left, out); + } else { + out.set_val(left.val().unwrap().clone()); + } + } + return Some(Summary { live, kept }); + } + None +} + +struct ZipFrame { + children: ByteMask, + summary: Summary, + down: usize, +} + +fn zipper_frame( + left: &L, + right: &R, + out: &mut O, + down: usize, +) -> ZipFrame +where + V: Clone + Send + Sync, + A: Allocator, + L: ZipperMoving + ZipperConcrete + ZipperInfallibleSubtries, + R: ZipperMoving + ZipperConcrete, + O: ZipperWriting, +{ + let lm = left.child_mask(); + let rm = right.child_mask(); + let mut summary = Summary::default(); + let outside = lm & !rm; + if SUBTRACT && !outside.is_empty_mask() { + out.graft_masked_branches(left, outside, false); + summary.kept = zipper_live(out, true); + } + ZipFrame { + children: lm & rm, + summary, + down, + } +} + +fn zipper_op(left: &mut L, right: &mut R, out: &mut O) +where + V: Clone + Send + Sync, + A: Allocator, + L: ZipperMoving + ZipperConcrete + ZipperInfallibleSubtries, + R: ZipperMoving + ZipperConcrete, + O: ZipperWriting, +{ + out.remove_branches(false); + out.remove_val(false); + if left + .shared_node_id() + .is_some_and(|id| Some(id) == right.shared_node_id()) + { + if !SUBTRACT { + graft_values(left, out); + } + return; + } + if SUBTRACT && (left.child_mask() & right.child_mask()).is_empty_mask() { + if !left.is_val() || !right.is_val() || zipper_live(left, true) { + graft_values(left, out); + } + return; + } + if zipper_shortcut::(left, right, out).is_some() { + return; + } + let mut frames: SmallVec<[ZipFrame; 8]> = + smallvec::smallvec![zipper_frame::(left, right, out, 0)]; + loop { + if let Some(b) = pop(&mut frames.last_mut().unwrap().children) { + let before = left.depth(); + left.descend_to_byte(b); + right.descend_to_byte(b); + out.descend_to_byte(b); + // No candidate left value exists inside a compressed edge. The + // right zipper can cross its own branches in one descent. + if !left.is_val() { + left.descend_until_observed(&mut ( + MirrorPathObserver(right), + MirrorPathObserver(out), + )); + } + let down = left.depth() - before; + if let Some(s) = zipper_shortcut::(left, right, out) { + let p = &mut frames.last_mut().unwrap().summary; + p.include(s); + left.ascend(down); + right.ascend(down); + out.ascend(down); + } else { + frames.push(zipper_frame::( + left, right, out, down, + )); + } + } else { + let mut f = frames.pop().unwrap(); + if left.is_val() { + // Unmatched branches were skipped; recover original tip status + // only when needed. First-witness probes stop at the next value. + if !f.summary.kept && !f.summary.live { + f.summary.live = zipper_live(left, true); + } + let keep = + keep_value::(f.summary, right.is_val(), || zipper_live(right, true)); + if keep { + out.set_val(left.val().unwrap().clone()); + f.summary.kept = true; + } + f.summary.live = true; + } + let Some(parent) = frames.last_mut() else { + break; + }; + parent.summary.include(f.summary); + left.ascend(f.down); + right.ascend(f.down); + out.ascend(f.down); + } + } +} + +/// Replace the output focus with convex meet. All focuses are restored. +/// Compressed left edges are traversed as blocks, and right-only fringes need +/// only one valued witness. Payloads are cloned from the left; no Lattice bound. +pub fn zipper_convex_meet(left: &mut L, right: &mut R, out: &mut O) +where + V: Clone + Send + Sync, + A: Allocator, + L: ZipperMoving + ZipperConcrete + ZipperInfallibleSubtries, + R: ZipperMoving + ZipperConcrete, + O: ZipperWriting, +{ + zipper_op::(left, right, out) +} + +/// Replace the output focus with convex subtraction; preserve supporting +/// interiors even when the mask contains them. All focuses are restored. +pub fn zipper_convex_subtract(left: &mut L, right: &mut R, out: &mut O) +where + V: Clone + Send + Sync, + A: Allocator, + L: ZipperMoving + ZipperConcrete + ZipperInfallibleSubtries, + R: ZipperMoving + ZipperConcrete, + O: ZipperWriting, +{ + zipper_op::(left, right, out) +} diff --git a/src/line_list_node.rs b/src/line_list_node.rs index aa85da28..a04f2866 100644 --- a/src/line_list_node.rs +++ b/src/line_list_node.rs @@ -1248,6 +1248,25 @@ impl LineListNode { } } + /// The two physical payload slots, in storage order. No token traversal. + pub(crate) fn convex_slots(&self) -> [(&[u8], PayloadRef<'_, V, A>); 2] { + let slot0 = if self.is_used::<0>() { + unsafe { (self.key_unchecked::<0>(), self.payload_in_slot::<0>()) } + } else { (&[][..], PayloadRef::None) }; + let slot1 = if self.is_used::<1>() { + unsafe { (self.key_unchecked::<1>(), self.payload_in_slot::<1>()) } + } else { (&[][..], PayloadRef::None) }; + [slot0, slot1] + } + + /// Reuse the same direct slot reconstruction as ordinary subtract/restrict. + pub(crate) fn convex_rebuild(&self, slots: [AlgebraicResult>; 2]) + -> AlgebraicResult> + { + let [a, b] = slots; + self.combine_slot_results_into_node_result(a.map(Into::into), b.map(Into::into)) + } + /// Internal method to combine the result from separate **Non-Commutative** operations on individual slots into /// an AlgebraicResult for the whole node #[inline] diff --git a/src/trie_ref.rs b/src/trie_ref.rs index 940d0da2..04b5a708 100644 --- a/src/trie_ref.rs +++ b/src/trie_ref.rs @@ -181,6 +181,15 @@ impl Clone for TrieRefBorrowed<'_, V, A> { impl Copy for TrieRefBorrowed<'_, V, A> {} impl<'a, V: Clone + Send + Sync + 'a, A: Allocator + 'a> TrieRefBorrowed<'a, V, A> { + /// Borrow the underlying node when the focus is exactly at its boundary. + /// The focus value is stored outside this node and is not included. + #[inline] + pub(crate) fn aligned_node(&self) -> Option> { + self.focus_node + .filter(|_| self.node_key().is_empty()) + .map(|node| node.as_tagged()) + } + /// Makes a new TrieRefBorrowed from its parts #[inline(always)] fn new_from_parts( diff --git a/tests/convex.rs b/tests/convex.rs new file mode 100644 index 00000000..bbd67830 --- /dev/null +++ b/tests/convex.rs @@ -0,0 +1,367 @@ +use pathmap::{PathMap, experimental::convex::*, zipper::*}; +use std::collections::{BTreeMap, BTreeSet}; + +type Space = BTreeSet>; +fn value(p: &[u8]) -> u64 { + p.iter() + .fold(7u64, |v, b| v.wrapping_mul(257).wrapping_add(*b as u64 + 1)) +} +fn map(s: &Space) -> PathMap { + let mut m = PathMap::new(); + for p in s { + m.set_val_at(p, value(p)); + } + m +} +fn vals(m: &PathMap) -> BTreeMap, u64> { + m.iter().map(|(p, v)| (p, *v)).collect() +} +fn hull(s: &Space) -> Space { + s.iter() + .filter(|p| !s.iter().any(|q| p != &q && q.starts_with(p))) + .cloned() + .collect() +} +// Independent repeated-removal oracle, not the implementation's postorder rule. +fn prune(mut x: Space, protected: Space) -> BTreeMap, u64> { + loop { + let remove: Vec<_> = hull(&x).difference(&protected).cloned().collect(); + if remove.is_empty() { + break; + } + for p in remove { + x.remove(&p); + } + } + x.into_iter() + .map(|p| { + let v = value(&p); + (p, v) + }) + .collect() +} +fn check(a: &Space, b: &Space, ma: &PathMap, mb: &PathMap) { + let meet = prune( + a.intersection(b).cloned().collect(), + hull(a).intersection(&hull(b)).cloned().collect(), + ); + let sub = prune(a.clone(), hull(a).difference(b).cloned().collect()); + assert_eq!(vals(&convex_meet(ma, mb)), meet, "node meet {a:?} {b:?}"); + assert_eq!( + vals(&convex_subtract(ma, mb)), + sub, + "node subtract {a:?} {b:?}" + ); + let mut out = PathMap::new(); + zipper_convex_meet( + &mut ma.read_zipper(), + &mut mb.read_zipper(), + &mut out.write_zipper(), + ); + assert_eq!(vals(&out), meet, "zipper meet {a:?} {b:?}"); + zipper_convex_subtract( + &mut ma.read_zipper(), + &mut mb.read_zipper(), + &mut out.write_zipper(), + ); + assert_eq!(vals(&out), sub, "zipper subtract {a:?} {b:?}"); +} +fn spaces() -> Vec { + let ps = [ + vec![], + vec![0], + vec![1], + vec![0, 0], + vec![0, 1], + vec![1, 0], + vec![1, 1], + ]; + (0..128) + .map(|mask| { + ps.iter() + .enumerate() + .filter(|(i, _)| mask & (1 << i) != 0) + .map(|(_, p)| p.clone()) + .collect() + }) + .collect() +} +#[test] +fn exhaustive_binary_spaces() { + let ss = spaces(); + let maps: Vec<_> = ss.iter().map(map).collect(); + for (i, a) in ss.iter().enumerate() { + for (j, b) in ss.iter().enumerate() { + check(a, b, &maps[i], &maps[j]); + } + } +} +#[test] +fn dangling_paths_are_not_tips() { + let ss = spaces(); + let maps: Vec<_> = ss + .iter() + .enumerate() + .map(|(i, s)| { + let mut m = map(s); + for p in [vec![0, 0, 0], vec![1, 0, 1], vec![i as u8, 255, 0]] { + m.write_zipper_at_path(&p).create_path(); + } + m + }) + .collect(); + for (i, a) in ss.iter().enumerate() { + let clone = maps[i].clone(); + check(a, a, &maps[i], &clone); + for (j, b) in ss.iter().enumerate() { + check(a, b, &maps[i], &maps[j]); + } + } +} +#[test] +fn compressed_edges_dense_nodes_and_shared_subtrees() { + for width in [1usize, 2, 16, 80, 256] { + let mut a = Space::new(); + let mut b = Space::new(); + a.insert(vec![]); + b.insert(vec![]); + for n in 0..width { + let mut p = vec![n as u8; 151]; + for len in [1, 47, 48, 49, 97, 150] { + a.insert(p[..len].to_vec()); + if n % 3 != 0 { + b.insert(p[..len].to_vec()); + } + } + a.insert(p.clone()); + if n % 2 == 0 { + b.insert(p.clone()); + } else { + p.push(255); + b.insert(p); + } + } + let ma = map(&a); + let mb = map(&b); + check(&a, &b, &ma, &mb); + let mut shared = ma.clone(); + for p in b.iter().take(width) { + shared.set_val_at(p, value(p)); + } + let union: Space = shared.iter().map(|(p, _)| p).collect(); + check(&a, &union, &ma, &shared); + } +} +#[test] +fn focused_zipper_restores_cursors_and_preserves_outside() { + let mut a = PathMap::new(); + let mut b: PathMap = PathMap::new(); + for (p, v) in [ + (b"x".as_slice(), 1), + (b"xa", 2), + (b"xab", 3), + (b"xac", 4), + (b"z", 99), + ] { + a.set_val_at(p, v); + } + for p in [b"y".as_slice(), b"ya", b"yab", b"yada"] { + b.set_val_at(p, 9); + } + for subtract in [false, true] { + let mut out = PathMap::new(); + out.set_val_at(b"p", 80); + out.set_val_at(b"po", 81); + out.set_val_at(b"po/old", 82); + out.set_val_at(b"q", 83); + let mut l = a.read_zipper(); + l.descend_to(b"x"); + let mut r = b.read_zipper(); + r.descend_to(b"y"); + { + let mut o = out.write_zipper(); + o.descend_to(b"po"); + if subtract { + zipper_convex_subtract(&mut l, &mut r, &mut o); + } else { + zipper_convex_meet(&mut l, &mut r, &mut o); + } + assert_eq!(o.path(), b"po"); + } + assert_eq!(l.path(), b"x"); + assert_eq!(r.path(), b"y"); + let mut expected = BTreeMap::from([ + (b"p".to_vec(), 80), + (b"q".to_vec(), 83), + (b"po".to_vec(), 1), + (b"poa".to_vec(), 2), + ]); + expected.insert( + if subtract { + b"poac".to_vec() + } else { + b"poab".to_vec() + }, + if subtract { 4 } else { 3 }, + ); + assert_eq!(vals(&out), expected); + let mut empty = b.read_zipper_at_path(b"missing"); + zipper_convex_meet(&mut l, &mut empty, &mut out.write_zipper_at_path(b"po")); + assert!(empty.path().is_empty()); + assert_eq!( + vals(&out), + BTreeMap::from([(b"p".to_vec(), 80), (b"q".to_vec(), 83)]) + ); + } + let _ = convex_meet(&a, &b); + let _ = convex_subtract(&a, &b); +} +#[test] +fn deep_chain_prunes_to_stability() { + let a: Space = (0..1024).map(|n| vec![0; n]).collect(); + let mut b = a.clone(); + b.remove(&vec![0; 1023]); + b.insert([vec![0; 1022], vec![1]].concat()); + let ma = map(&a); + let mb = map(&b); + assert_eq!(convex_meet(&ma, &mb).val_count(), 0); + let mut out = PathMap::new(); + zipper_convex_meet( + &mut ma.read_zipper(), + &mut mb.read_zipper(), + &mut out.write_zipper(), + ); + assert_eq!(out.val_count(), 0); + assert_eq!(vals(&convex_subtract(&ma, &mb)), vals(&ma)); +} + +#[test] +fn randomized_shapes_and_partial_sharing() { + use rand::{Rng, SeedableRng, rngs::StdRng}; + let mut rng = StdRng::seed_from_u64(0xC0A7E); + for _ in 0..300 { + let mut pool = Space::new(); + for _ in 0..rng.random_range(1..80) { + let len = rng.random_range(0..90); + let p: Vec = (0..len).map(|_| rng.random_range(0..6)).collect(); + pool.insert(p[..rng.random_range(0..=len)].to_vec()); + pool.insert(p); + } + let a: Space = pool + .iter() + .filter(|_| rng.random_bool(0.7)) + .cloned() + .collect(); + let b: Space = pool + .iter() + .filter(|_| rng.random_bool(0.6)) + .cloned() + .collect(); + let mut ma = map(&a); + let mut mb = ma.clone(); + for p in a.difference(&b) { + mb.remove_val_at(p, false); + } + for p in b.difference(&a) { + mb.set_val_at(p, value(p)); + } + for p in &pool { + ma.write_zipper_at_path(p).create_path(); + mb.write_zipper_at_path(p).create_path(); + } + check(&a, &b, &ma, &mb); + assert_eq!(vals(&ma), a.iter().map(|p| (p.clone(), value(p))).collect()); + assert_eq!(vals(&mb), b.iter().map(|p| (p.clone(), value(p))).collect()); + } +} + +#[test] +fn subtree_reuse_does_not_clone_payloads() { + use std::sync::{ + Arc, + atomic::{AtomicUsize, Ordering}, + }; + struct Counted(Arc); + impl Clone for Counted { + fn clone(&self) -> Self { + self.0.fetch_add(1, Ordering::Relaxed); + Self(self.0.clone()) + } + } + let clones = Arc::new(AtomicUsize::new(0)); + let mut a = PathMap::new(); + let mut mask = PathMap::<()>::new(); + for n in 0..2000u32 { + let p = n.to_be_bytes(); + a.set_val_at(p, Counted(clones.clone())); + a.set_val_at([p.as_slice(), &[0]].concat(), Counted(clones.clone())); + mask.set_val_at(p, ()); + } + let shared = a.clone(); + clones.store(0, Ordering::Relaxed); + assert_eq!(convex_meet(&a, &shared).val_count(), 4000); + assert_eq!(convex_subtract(&a, &mask).val_count(), 4000); + assert_eq!(convex_subtract(&a, &shared).val_count(), 0); + assert_eq!(clones.load(Ordering::Relaxed), 0); + let mut out = PathMap::new(); + zipper_convex_meet( + &mut a.read_zipper(), + &mut shared.read_zipper(), + &mut out.write_zipper(), + ); + assert_eq!(out.val_count(), 4000); + assert_eq!(clones.load(Ordering::Relaxed), 0); +} + +#[test] +fn extracted_subtries_and_empty_bare_shared_roots() { + let mut source = PathMap::new(); + for (p, v) in [(b"abcdef".as_slice(), 10), (b"abcdefgh", 20)] { + source.set_val_at(p, v); + } + source.write_zipper_at_path(b"abcdef/bare").create_path(); + let a = source.read_zipper_at_path(b"abc").make_map(); + let mut b = PathMap::<()>::new(); + b.set_val_at(b"def", ()); + b.set_val_at(b"defgh", ()); + assert_eq!( + vals(&convex_meet(&a, &b)), + BTreeMap::from([(b"def".to_vec(), 10), (b"defgh".to_vec(), 20)]) + ); + b.remove_val_at(b"defgh", true); + assert_eq!(convex_meet(&a, &b).val_count(), 0); + assert_eq!(vals(&convex_subtract(&a, &b)), vals(&a)); + let mut empty = PathMap::::new(); + empty.write_zipper_at_path(b"bare/only").create_path(); + let mut root = empty.clone(); + root.set_val_at([], 55); + assert_eq!( + vals(&convex_subtract(&root, &empty)), + BTreeMap::from([(vec![], 55)]) + ); + assert_eq!(convex_meet(&root, &empty).val_count(), 0); + assert_eq!(convex_subtract(&empty, &root).val_count(), 0); +} + +#[test] +fn zipper_head_cell_nodes_match_dense_and_list_nodes() { + let a: Space = (0..=255u8) + .flat_map(|b| [vec![0, b], vec![0, b, 0], vec![0, b, 1]]) + .collect(); + let b: Space = (0..=255u8) + .flat_map(|b| [vec![0, b], vec![0, b, b % 3]]) + .collect(); + let mut ma = map(&a); + let mut mb = map(&b); + for m in [&mut ma, &mut mb] { + let head = m.zipper_head(); + for b in 0..=255u8 { + let path = [0, b, 255]; + let mut z = head.write_zipper_at_exclusive_path(path).unwrap(); + z.create_path(); + } + } + check(&a, &b, &ma, &mb); + check(&a, &b, &ma, &map(&b)); + check(&a, &b, &map(&a), &mb); +} From e3f71b0040accb6f12cd91dceb199e836e860bc3 Mon Sep 17 00:00:00 2001 From: adamv-symbolica Date: Tue, 17 Nov 2026 12:42:18 +0000 Subject: [PATCH 05/15] Introduce retain and prove its prefix algebra Rename the valued-prefix selection operation from live to retain throughout the Lean model. Add map and zipper adapters and a Rust zipper traversal that preserves candidate payloads and stops fringe scans at the first witness. Prove Boolean filtering, exact mask composition, canonical hull/basis masks, restriction dualities, extremum and divergence interactions, and the convex connections. Record counterexamples to invalid stronger identities. Use retain directly in the convex property tests, with exhaustive prefix spaces, independent pruning, payload/focus checks, and traversal-work bounds. --- lean/PathMapModel.lean | 1 + lean/PathMapModel/Convex.lean | 36 +-- lean/PathMapModel/ConvexBoolean.lean | 28 +- lean/PathMapModel/ConvexGeometry.lean | 40 +-- lean/PathMapModel/ConvexMorphisms.lean | 10 +- lean/PathMapModel/ConvexOrder.lean | 46 +-- lean/PathMapModel/ConvexPruning.lean | 42 +-- lean/PathMapModel/PathSetLCP.lean | 8 +- lean/PathMapModel/PathSetLaws.lean | 51 +++- lean/PathMapModel/PathSetMasks.lean | 44 +-- lean/PathMapModel/PathSetRecursive.lean | 40 +-- lean/PathMapModel/PathSets.lean | 15 +- lean/PathMapModel/Retain.lean | 355 ++++++++++++++++++++++++ lean/PathMapModel/RetainChecks.lean | 40 +++ lean/PathMapModel/RetainConvex.lean | 69 +++++ src/experimental.rs | 2 +- src/experimental/convex.rs | 6 +- src/experimental/path_sets.rs | 101 ++++++- tests/convex.rs | 19 +- tests/path_sets.rs | 80 ++++++ tests/support/path_set_laws.rs | 195 +++++++++++-- 21 files changed, 1046 insertions(+), 182 deletions(-) create mode 100644 lean/PathMapModel/Retain.lean create mode 100644 lean/PathMapModel/RetainChecks.lean create mode 100644 lean/PathMapModel/RetainConvex.lean diff --git a/lean/PathMapModel.lean b/lean/PathMapModel.lean index beae73f1..18665a61 100644 --- a/lean/PathMapModel.lean +++ b/lean/PathMapModel.lean @@ -13,3 +13,4 @@ import PathMapModel.PathSetProofs import PathMapModel.PathSetChecks import PathMapModel.PathSetCertificates import PathMapModel.ConvexMap +import PathMapModel.RetainChecks diff --git a/lean/PathMapModel/Convex.lean b/lean/PathMapModel/Convex.lean index 86d93f4b..78a31f4a 100644 --- a/lean/PathMapModel/Convex.lean +++ b/lean/PathMapModel/Convex.lean @@ -4,8 +4,8 @@ import PathMapModel.PathSetCertificates Subtraction retains supporting interiors; its mask selects original tips. -/ namespace PathMapModel.PathSpace -def convexMeet (a b : PathSpace) : PathSpace := live (inter a b) (inter (hull a) (hull b)) -def convexSubtract (a b : PathSpace) : PathSpace := live a (diff (hull a) b) +def convexMeet (a b : PathSpace) : PathSpace := retain (inter a b) (inter (hull a) (hull b)) +def convexSubtract (a b : PathSpace) : PathSpace := retain a (diff (hull a) b) abbrev Included (a b : PathSpace) : Prop := ∀ p, p ∈ a → p ∈ b abbrev Same (a b : PathSpace) : Prop := ∀ p, p ∈ a ↔ p ∈ b def ConvexLE (a b : PathSpace) : Prop := Included a b ∧ Included (hull a) (hull b) @@ -14,14 +14,14 @@ theorem same_equiv (a b : PathSpace) : Same a b ↔ equiv a b = true := (equiv_i theorem mem_convexMeet (a b : PathSpace) (p : Path) : p ∈ convexMeet a b ↔ p ∈ a ∧ p ∈ b ∧ ∃ t, t ∈ hull a ∧ t ∈ hull b ∧ (p ≼ t) = true := by - simp only [convexMeet, mem_live, mem_inter]; grind + simp only [convexMeet, mem_retain, mem_inter]; grind theorem mem_convexSubtract (a b : PathSpace) (p : Path) : p ∈ convexSubtract a b ↔ p ∈ a ∧ ∃ t, t ∈ hull a ∧ t ∉ b ∧ (p ≼ t) = true := by - simp only [convexSubtract, mem_live, mem_diff]; grind + simp only [convexSubtract, mem_retain, mem_diff]; grind -theorem live_congr {a b t u : PathSpace} (h : Same a b) (k : Same t u) : Same (live a t) (live b u) := by - intro p; simp only [mem_live, h, k] +theorem retain_congr {a b t u : PathSpace} (h : Same a b) (k : Same t u) : Same (retain a t) (retain b u) := by + intro p; simp only [mem_retain, h, k] theorem hull_max {a : PathSpace} {p q : Path} (hp : p ∈ hull a) (hq : q ∈ a) (h : (p ≼ q) = true) : p = q := by @@ -41,21 +41,21 @@ theorem hull_of_antichain {a : PathSpace} (h : Antichain a) : Same (hull a) a := | false => rfl | true => exact False.elim (hn (h p hp q hq he).symm) -theorem live_hull (a : PathSpace) : Same (live a (hull a)) a := by - intro p; rw [mem_live]; exact ⟨And.left, fun hp => ⟨hp, hull_covers hp⟩⟩ +theorem retain_hull (a : PathSpace) : Same (retain a (hull a)) a := by + intro p; rw [mem_retain]; exact ⟨And.left, fun hp => ⟨hp, hull_covers hp⟩⟩ -theorem hull_live {a t : PathSpace} (ht : Included t (hull a)) : Same (hull (live a t)) t := by +theorem hull_retain {a t : PathSpace} (ht : Included t (hull a)) : Same (hull (retain a t)) t := by intro p; constructor · intro hp - obtain ⟨ha, q, hq, hpq⟩ := (mem_live a t p).mp (hull_subset _ hp) - have hqm : q ∈ live a t := (mem_live _ _ _).mpr ⟨hull_subset _ (ht q hq), q, hq, Path.prefix_self q⟩ + obtain ⟨ha, q, hq, hpq⟩ := (mem_retain a t p).mp (hull_subset _ hp) + have hqm : q ∈ retain a t := (mem_retain _ _ _).mpr ⟨hull_subset _ (ht q hq), q, hq, Path.prefix_self q⟩ have he := hull_max hp hqm hpq exact he ▸ hq · intro hp apply (mem_hull _ _).mpr - refine ⟨(mem_live _ _ _).mpr ⟨hull_subset _ (ht p hp), p, hp, Path.prefix_self p⟩, ?_⟩ + refine ⟨(mem_retain _ _ _).mpr ⟨hull_subset _ (ht p hp), p, hp, Path.prefix_self p⟩, ?_⟩ intro q hq hn - exact ((mem_hull a p).mp (ht p hp)).2 q ((mem_live _ _ _).mp hq).1 hn + exact ((mem_hull a p).mp (ht p hp)).2 q ((mem_retain _ _ _).mp hq).1 hn theorem meet_tips_subset (a b : PathSpace) : Included (inter (hull a) (hull b)) (hull (inter a b)) := by intro p hp; obtain ⟨ha,hb⟩ := (mem_inter _ _ _).mp hp @@ -64,10 +64,10 @@ theorem meet_tips_subset (a b : PathSpace) : Included (inter (hull a) (hull b)) fun q hq hn => ((mem_hull a p).mp ha).2 q ((mem_inter _ _ _).mp hq).1 hn⟩ theorem hull_convexMeet (a b : PathSpace) : Same (hull (convexMeet a b)) (inter (hull a) (hull b)) := - hull_live (meet_tips_subset a b) + hull_retain (meet_tips_subset a b) theorem hull_convexSubtract (a b : PathSpace) : Same (hull (convexSubtract a b)) (diff (hull a) b) := - hull_live (fun _ h => ((mem_diff _ _ _).mp h).1) + hull_retain (fun _ h => ((mem_diff _ _ _).mp h).1) theorem convexMeet_congr {a b c d : PathSpace} (h : Same a c) (k : Same b d) : Same (convexMeet a b) (convexMeet c d) := by @@ -98,7 +98,7 @@ theorem convexMeet_empty (a : PathSpace) : Same (convexMeet a []) [] := by intro p; simp [mem_convexMeet] theorem convexSubtract_empty_right (a : PathSpace) : Same (convexSubtract a []) a := by - intro p; simpa [convexSubtract, mem_live, mem_diff] using live_hull a p + intro p; simpa [convexSubtract, mem_retain, mem_diff] using retain_hull a p theorem convexSubtract_empty_left (a : PathSpace) : Same (convexSubtract [] a) [] := by intro p; simp [mem_convexSubtract] @@ -111,7 +111,7 @@ theorem convexMeet_zero (a b : PathSpace) : Same (convexMeet a b) [] ↔ Same (i constructor · intro h p; have hh := (hull_convexMeet a b p).symm.trans (hull_congr h p) simpa only [hull, List.filter_nil] using hh - · intro h p; simp only [convexMeet, mem_live]; have := h; simp only [Same, List.not_mem_nil, iff_false] at this; grind + · intro h p; simp only [convexMeet, mem_retain]; have := h; simp only [Same, List.not_mem_nil, iff_false] at this; grind theorem convexSubtract_zero (a b : PathSpace) : Same (convexSubtract a b) [] ↔ Included (hull a) b := by constructor @@ -138,7 +138,7 @@ theorem convexSubtract_identity (a b : PathSpace) : Same (convexSubtract a b) a theorem convexMeet_ordinary (a b : PathSpace) : Same (convexMeet a b) (inter a b) ↔ Included (hull (inter a b)) (inter (hull a) (hull b)) := by constructor · intro h p hp; exact (hull_convexMeet a b p).mp ((hull_congr h p).mpr hp) - · intro h p; rw [convexMeet,mem_live]; constructor + · intro h p; rw [convexMeet,mem_retain]; constructor · exact And.left · intro hp; obtain ⟨t,ht,hpt⟩ := hull_covers hp; exact ⟨hp,t,h t ht,hpt⟩ diff --git a/lean/PathMapModel/ConvexBoolean.lean b/lean/PathMapModel/ConvexBoolean.lean index 1a6f3870..9df32461 100644 --- a/lean/PathMapModel/ConvexBoolean.lean +++ b/lean/PathMapModel/ConvexBoolean.lean @@ -57,7 +57,7 @@ theorem tipChoices_distinct {xs : PathSpace} (hx : xs.Nodup) : obtain ⟨v,hv,rfl⟩ := List.mem_map.mp hu intro he; exact no_p t ht ((he p).mpr List.mem_cons_self) -def pruningFamily (a : PathSpace) : List PathSpace := (tipChoices (hull a).eraseDups).map (live a) +def pruningFamily (a : PathSpace) : List PathSpace := (tipChoices (hull a).eraseDups).map (retain a) theorem pruningFamily_length (a : PathSpace) : (pruningFamily a).length = 2 ^ count (hull a) := by simp only [pruningFamily,List.length_map,tipChoices_length,count] @@ -71,14 +71,14 @@ theorem pruningFamily_distinct (a : PathSpace) : (pruningFamily a).Pairwise (fun exact hne ((pruning_injective ts us).mp he) theorem pruningFamily_complete {a t : PathSpace} (ht : Included t (hull a)) : - ∃ r ∈ pruningFamily a, Same r (live a t) := by + ∃ r ∈ pruningFamily a, Same r (retain a t) := by let u := (hull a).eraseDups.filter t.contains - refine ⟨live a u,List.mem_map.mpr ⟨u,tipChoices_select _ t,rfl⟩,live_congr (fun _ => Iff.rfl) ?_⟩ + refine ⟨retain a u,List.mem_map.mpr ⟨u,tipChoices_select _ t,rfl⟩,retain_congr (fun _ => Iff.rfl) ?_⟩ intro p; simp only [u,List.mem_filter,List.mem_eraseDups,List.contains_iff_mem] exact ⟨And.right,fun hp => ⟨ht p hp,hp⟩⟩ theorem pruningFamily_sound {a r : PathSpace} (hr : r ∈ pruningFamily a) : - ∃ t, Included t (hull a) ∧ r = live a t := by + ∃ t, Included t (hull a) ∧ r = retain a t := by obtain ⟨t,ht,rfl⟩ := List.mem_map.mp hr exact ⟨t,fun p hp => List.mem_eraseDups.mp (tipChoices_subset ht p hp),rfl⟩ @@ -102,7 +102,7 @@ def eval (v : Nat → Bool) : ConvexFormula → Bool def tips (a : PathSpace) (v : Nat → PathSpace) (e : ConvexFormula) : PathSpace := (hull a).filter (fun p => eval (fun i => (v i).contains p) e) def interpret (a : PathSpace) (v : Nat → PathSpace) : ConvexFormula → PathSpace - | .atom i => live a (inter (hull a) (v i)) + | .atom i => retain a (inter (hull a) (v i)) | .bot => [] | .top => a | .meet x y => convexMeet (interpret a v x) (interpret a v y) @@ -113,31 +113,31 @@ theorem tips_subset (a : PathSpace) (v : Nat → PathSpace) (e : ConvexFormula) fun _ h => (List.mem_filter.mp h).1 theorem interpret_correct (a : PathSpace) (v : Nat → PathSpace) (e : ConvexFormula) : - Same (interpret a v e) (live a (tips a v e)) := by + Same (interpret a v e) (retain a (tips a v e)) := by induction e with | atom i => - apply live_congr (fun _ => Iff.rfl) + apply retain_congr (fun _ => Iff.rfl) intro p; simp [tips,eval,mem_inter] - | bot => intro p; simp [interpret,tips,eval,mem_live] - | top => intro p; simpa [interpret,tips,eval,mem_live] using (live_hull a p).symm + | bot => intro p; simp [interpret,tips,eval,mem_retain] + | top => intro p; simpa [interpret,tips,eval,mem_retain] using (retain_hull a p).symm | meet x y ihx ihy => intro p apply (convexMeet_congr ihx ihy p).trans apply (pruning_meet (tips_subset a v x) (tips_subset a v y) p).trans - apply live_congr (fun _ => Iff.rfl) _ p + apply retain_congr (fun _ => Iff.rfl) _ p intro q; simp [tips,eval,mem_inter]; grind | join x y ihx ihy => intro p - have he : Same (union (interpret a v x) (interpret a v y)) (union (live a (tips a v x)) (live a (tips a v y))) := by + have he : Same (union (interpret a v x) (interpret a v y)) (union (retain a (tips a v x)) (retain a (tips a v y))) := by intro q; simp only [union,List.mem_append,ihx,ihy] apply (he p).trans ((pruning_union a _ _ p).trans ?_) - apply live_congr (fun _ => Iff.rfl) _ p + apply retain_congr (fun _ => Iff.rfl) _ p intro q; simp [tips,eval,union]; grind | compl x ih => intro p apply (convexSubtract_congr (fun _ => Iff.rfl) (hull_congr ih) p).trans apply (pruning_complement (tips_subset a v x) p).trans - apply live_congr (fun _ => Iff.rfl) _ p + apply retain_congr (fun _ => Iff.rfl) _ p intro q; simp [tips,eval,mem_diff]; grind /-- Every Boolean identity transfers to the canonical prunings of every source. @@ -147,7 +147,7 @@ theorem transfer {e f : ConvexFormula} (h : ∀ v, eval v e = eval v f) intro p apply (interpret_correct a v e p).trans apply Iff.trans _ (interpret_correct a v f p).symm - apply live_congr (fun _ => Iff.rfl) _ p + apply retain_congr (fun _ => Iff.rfl) _ p intro q; simp only [tips,List.mem_filter,h] end ConvexFormula diff --git a/lean/PathMapModel/ConvexGeometry.lean b/lean/PathMapModel/ConvexGeometry.lean index df9b6c17..b4af7867 100644 --- a/lean/PathMapModel/ConvexGeometry.lean +++ b/lean/PathMapModel/ConvexGeometry.lean @@ -7,45 +7,45 @@ def IsConvex (a : PathSpace) : Prop := ∀ p ∈ a, ∀ r ∈ a, ∀ q, (p ≼ q) = true → (q ≼ r) = true → q ∈ a def IsPrefixClosed (a : PathSpace) : Prop := ∀ r ∈ a, ∀ p, (p ≼ r) = true → p ∈ a -theorem live_lower {a t : PathSpace} {p q : Path} (hp : p ∈ a) - (hq : q ∈ live a t) (hpq : (p ≼ q) = true) : p ∈ live a t := by - obtain ⟨_,r,hr,hqr⟩ := (mem_live _ _ _).mp hq - exact (mem_live _ _ _).mpr ⟨hp,r,hr,Path.prefix_trans hpq hqr⟩ +theorem retain_lower {a t : PathSpace} {p q : Path} (hp : p ∈ a) + (hq : q ∈ retain a t) (hpq : (p ≼ q) = true) : p ∈ retain a t := by + obtain ⟨_,r,hr,hqr⟩ := (mem_retain _ _ _).mp hq + exact (mem_retain _ _ _).mpr ⟨hp,r,hr,Path.prefix_trans hpq hqr⟩ -theorem live_convex {a : PathSpace} (ha : IsConvex a) (t : PathSpace) : IsConvex (live a t) := by +theorem retain_convex {a : PathSpace} (ha : IsConvex a) (t : PathSpace) : IsConvex (retain a t) := by intro p hp r hr q hpq hqr - exact live_lower (ha p ((mem_live _ _ _).mp hp).1 r ((mem_live _ _ _).mp hr).1 q hpq hqr) hr hqr + exact retain_lower (ha p ((mem_retain _ _ _).mp hp).1 r ((mem_retain _ _ _).mp hr).1 q hpq hqr) hr hqr -theorem live_prefixClosed {a : PathSpace} (ha : IsPrefixClosed a) (t : PathSpace) : IsPrefixClosed (live a t) := by - intro r hr p hpr; exact live_lower (ha r ((mem_live _ _ _).mp hr).1 p hpr) hr hpr +theorem retain_prefixClosed {a : PathSpace} (ha : IsPrefixClosed a) (t : PathSpace) : IsPrefixClosed (retain a t) := by + intro r hr p hpr; exact retain_lower (ha r ((mem_retain _ _ _).mp hr).1 p hpr) hr hpr theorem convexMeet_convex {a b : PathSpace} (ha : IsConvex a) (hb : IsConvex b) : IsConvex (convexMeet a b) := by - apply live_convex + apply retain_convex intro p hp r hr q hpq hqr exact (mem_inter _ _ _).mpr ⟨ha p ((mem_inter _ _ _).mp hp).1 r ((mem_inter _ _ _).mp hr).1 q hpq hqr, hb p ((mem_inter _ _ _).mp hp).2 r ((mem_inter _ _ _).mp hr).2 q hpq hqr⟩ -theorem convexSubtract_convex {a : PathSpace} (ha : IsConvex a) (b : PathSpace) : IsConvex (convexSubtract a b) := live_convex ha _ +theorem convexSubtract_convex {a : PathSpace} (ha : IsConvex a) (b : PathSpace) : IsConvex (convexSubtract a b) := retain_convex ha _ theorem convexMeet_prefixClosed {a b : PathSpace} (ha : IsPrefixClosed a) (hb : IsPrefixClosed b) : IsPrefixClosed (convexMeet a b) := by - apply live_prefixClosed + apply retain_prefixClosed intro r hr p hpr; exact (mem_inter _ _ _).mpr ⟨ha r ((mem_inter _ _ _).mp hr).1 p hpr,hb r ((mem_inter _ _ _).mp hr).2 p hpr⟩ -theorem convexSubtract_prefixClosed {a : PathSpace} (ha : IsPrefixClosed a) (b : PathSpace) : IsPrefixClosed (convexSubtract a b) := live_prefixClosed ha _ +theorem convexSubtract_prefixClosed {a : PathSpace} (ha : IsPrefixClosed a) (b : PathSpace) : IsPrefixClosed (convexSubtract a b) := retain_prefixClosed ha _ /-- Basis of the discarded region generates precisely the pruning cut. -/ theorem pruning_basis_cut (x t : PathSpace) : - Same (restrict x (basis (diff x (live x t)))) (diff x (live x t)) := by + Same (restrict x (basis (diff x (retain x t)))) (diff x (retain x t)) := by intro p; rw [restriction_basis_mask,mem_restrict,mem_diff] constructor · rintro ⟨hp,q,hq,hqp⟩ have hqn := ((mem_diff _ _ _).mp hq).2 - exact ⟨hp,fun hr => hqn (live_lower ((mem_diff _ _ _).mp hq).1 hr hqp)⟩ + exact ⟨hp,fun hr => hqn (retain_lower ((mem_diff _ _ _).mp hq).1 hr hqp)⟩ · rintro ⟨hp,hn⟩; exact ⟨hp,p,(mem_diff _ _ _).mpr ⟨hp,hn⟩,Path.prefix_self p⟩ theorem pruning_basis_raffinate (x t : PathSpace) : - Same (raffinate x (basis (diff x (live x t)))) (live x t) := by - intro p; simp only [raffinate,mem_diff,pruning_basis_cut,mem_live]; grind + Same (raffinate x (basis (diff x (retain x t)))) (retain x t) := by + intro p; simp only [raffinate,mem_diff,pruning_basis_cut,mem_retain]; grind theorem convexMeet_basis (a b : PathSpace) : Same (raffinate (inter a b) (basis (diff (inter a b) (convexMeet a b)))) (convexMeet a b) := pruning_basis_raffinate _ _ @@ -102,17 +102,17 @@ theorem branches_convex_partition (a b : PathSpace) (p : Path) : exact (divergence_congr (convex_partition a b) (convex_partition a b) p).symm.trans (branches_union _ _ p) /-- Literal subtraction is a separate operator and can introduce gaps. -/ -def convexLiteralSubtract (a b : PathSpace) : PathSpace := live (diff a b) (diff (hull a) b) +def convexLiteralSubtract (a b : PathSpace) : PathSpace := retain (diff a b) (diff (hull a) b) theorem convexLiteralSubtract_diff (a b : PathSpace) : Same (convexLiteralSubtract a b) (diff (convexSubtract a b) b) := by - intro p; simp only [convexLiteralSubtract,mem_live,mem_diff,mem_convexSubtract]; grind + intro p; simp only [convexLiteralSubtract,mem_retain,mem_diff,mem_convexSubtract]; grind theorem hull_surviving_diff {a b : PathSpace} {t : Path} (ht : t ∈ hull a) (hn : t ∉ b) : t ∈ hull (diff a b) := by apply (mem_hull _ _).mpr exact ⟨(mem_diff _ _ _).mpr ⟨hull_subset a ht,hn⟩,fun q hq hne => ((mem_hull _ _).mp ht).2 q ((mem_diff _ _ _).mp hq).1 hne⟩ theorem convexLiteralSubtract_meet (a b : PathSpace) : Same (convexLiteralSubtract a b) (convexMeet a (diff a b)) := by - intro p; simp only [convexLiteralSubtract,mem_live,mem_diff,mem_convexMeet] + intro p; simp only [convexLiteralSubtract,mem_retain,mem_diff,mem_convexMeet] constructor · rintro ⟨⟨hp,hn⟩,t,⟨ht,htn⟩,hpt⟩; exact ⟨hp,⟨hp,hn⟩,t,ht,hull_surviving_diff ht htn,hpt⟩ · rintro ⟨hp,⟨_,hn⟩,t,ht,htd,hpt⟩ @@ -120,7 +120,7 @@ theorem convexLiteralSubtract_meet (a b : PathSpace) : Same (convexLiteralSubtra theorem convexLiteralSubtract_hull (a b : PathSpace) : Same (hull (convexLiteralSubtract a b)) (diff (hull a) b) := by - apply hull_live + apply hull_retain intro t ht; obtain ⟨hh,hn⟩ := (mem_diff _ _ _).mp ht exact hull_surviving_diff hh hn diff --git a/lean/PathMapModel/ConvexMorphisms.lean b/lean/PathMapModel/ConvexMorphisms.lean index 58d9d28d..2d8a3c1d 100644 --- a/lean/PathMapModel/ConvexMorphisms.lean +++ b/lean/PathMapModel/ConvexMorphisms.lean @@ -34,9 +34,9 @@ theorem hull_unwrap (a : PathSpace) (r p : Path) : p ∈ hull (unwrap a r) ↔ r intro q hq hpq exact List.append_cancel_left (h (r ++ q) hq (by simpa only [Path.prefix_append_same] using hpq)) -theorem live_unwrap (a t : PathSpace) (r p : Path) : - p ∈ live (unwrap a r) (unwrap t r) ↔ r ++ p ∈ live a t := by - simp only [mem_live,mem_unwrap]; constructor +theorem retain_unwrap (a t : PathSpace) (r p : Path) : + p ∈ retain (unwrap a r) (unwrap t r) ↔ r ++ p ∈ retain a t := by + simp only [mem_retain,mem_unwrap]; constructor · rintro ⟨hp,q,hq,hpq⟩; exact ⟨hp,r ++ q,hq,by simpa only [Path.prefix_append_same] using hpq⟩ · rintro ⟨hp,q,hq,hpq⟩ obtain ⟨s,rfl⟩ := (Path.prefix_iff_extension _ _).mp (Path.prefix_trans (Path.prefix_append r p) hpq) @@ -49,14 +49,14 @@ theorem convexMeet_unwrap (a b : PathSpace) (r : Path) : intro q; simp only [mem_inter,mem_unwrap] have ht : Same (inter (hull (unwrap a r)) (hull (unwrap b r))) (unwrap (inter (hull a) (hull b)) r) := by intro q; simp only [mem_inter,mem_unwrap,hull_unwrap] - exact (mem_unwrap _ _ _).trans ((live_unwrap (inter a b) (inter (hull a) (hull b)) r p).symm.trans (live_congr he ht p).symm) + exact (mem_unwrap _ _ _).trans ((retain_unwrap (inter a b) (inter (hull a) (hull b)) r p).symm.trans (retain_congr he ht p).symm) theorem convexSubtract_unwrap (a b : PathSpace) (r : Path) : Same (unwrap (convexSubtract a b) r) (convexSubtract (unwrap a r) (unwrap b r)) := by intro p have ht : Same (diff (hull (unwrap a r)) (unwrap b r)) (unwrap (diff (hull a) b) r) := by intro q; simp only [mem_diff,mem_unwrap,hull_unwrap] - exact (mem_unwrap _ _ _).trans ((live_unwrap a (diff (hull a) b) r p).symm.trans (live_congr (fun _ => Iff.rfl) ht p).symm) + exact (mem_unwrap _ _ _).trans ((retain_unwrap a (diff (hull a) b) r p).symm.trans (retain_congr (fun _ => Iff.rfl) ht p).symm) /-- Distinct prefix-code cones cannot interfere, even for empty suffixes. -/ theorem code_prefix {code : PathSpace} (hc : Antichain code) {r s : Path} diff --git a/lean/PathMapModel/ConvexOrder.lean b/lean/PathMapModel/ConvexOrder.lean index c825b0cd..57d9efd4 100644 --- a/lean/PathMapModel/ConvexOrder.lean +++ b/lean/PathMapModel/ConvexOrder.lean @@ -87,36 +87,36 @@ theorem convex_compatible (a b : PathSpace) : /-- All Boolean operations on canonical prunings reduce to operations on tips. -/ theorem pruning_meet {a t u : PathSpace} (ht : Included t (hull a)) (hu : Included u (hull a)) : - Same (convexMeet (live a t) (live a u)) (live a (inter t u)) := by - intro p; simp only [mem_convexMeet,hull_live ht,hull_live hu,mem_live,mem_inter]; grind + Same (convexMeet (retain a t) (retain a u)) (retain a (inter t u)) := by + intro p; simp only [mem_convexMeet,hull_retain ht,hull_retain hu,mem_retain,mem_inter]; grind -theorem pruning_union (a t u : PathSpace) : Same (union (live a t) (live a u)) (live a (union t u)) := by - intro p; simp only [union,List.mem_append,mem_live]; grind +theorem pruning_union (a t u : PathSpace) : Same (union (retain a t) (retain a u)) (retain a (union t u)) := by + intro p; simp only [union,List.mem_append,mem_retain]; grind theorem pruning_subtract {a t : PathSpace} (ht : Included t (hull a)) (b : PathSpace) : - Same (convexSubtract (live a t) b) (live a (diff t b)) := by - intro p; simp only [mem_convexSubtract,hull_live ht,mem_live,mem_diff]; grind + Same (convexSubtract (retain a t) b) (retain a (diff t b)) := by + intro p; simp only [mem_convexSubtract,hull_retain ht,mem_retain,mem_diff]; grind theorem pruning_complement {a t : PathSpace} (ht : Included t (hull a)) : - Same (convexSubtract a (hull (live a t))) (live a (diff (hull a) t)) := by - intro p; simp only [mem_convexSubtract,hull_live ht,mem_live,mem_diff]; grind + Same (convexSubtract a (hull (retain a t))) (retain a (diff (hull a) t)) := by + intro p; simp only [mem_convexSubtract,hull_retain ht,mem_retain,mem_diff]; grind theorem pruning_order {a t u : PathSpace} (ht : Included t (hull a)) (hu : Included u (hull a)) : - ConvexLE (live a t) (live a u) ↔ Included t u := by + ConvexLE (retain a t) (retain a u) ↔ Included t u := by constructor - · intro h p hp; exact (hull_live hu p).mp (h.2 p ((hull_live ht p).mpr hp)) + · intro h p hp; exact (hull_retain hu p).mp (h.2 p ((hull_retain ht p).mpr hp)) · intro h; constructor - · intro p hp; obtain ⟨hp,q,hq,hpq⟩ := (mem_live _ _ _).mp hp - exact (mem_live _ _ _).mpr ⟨hp,q,h q hq,hpq⟩ - · intro p hp; exact (hull_live hu p).mpr (h p ((hull_live ht p).mp hp)) + · intro p hp; obtain ⟨hp,q,hq,hpq⟩ := (mem_retain _ _ _).mp hp + exact (mem_retain _ _ _).mpr ⟨hp,q,h q hq,hpq⟩ + · intro p hp; exact (hull_retain hu p).mpr (h p ((hull_retain ht p).mp hp)) theorem pruning_injective {a t u : PathSpace} (ht : Included t (hull a)) (hu : Included u (hull a)) : - Same (live a t) (live a u) ↔ Same t u := by + Same (retain a t) (retain a u) ↔ Same t u := by constructor - · intro h p; exact (hull_live ht p).symm.trans ((hull_congr h p).trans (hull_live hu p)) - · intro h; exact live_congr (fun _ => Iff.rfl) h + · intro h p; exact (hull_retain ht p).symm.trans ((hull_congr h p).trans (hull_retain hu p)) + · intro h; exact retain_congr (fun _ => Iff.rfl) h -theorem pruning_bottom (a : PathSpace) : Same (live a []) [] := by intro p; simp [mem_live] +theorem pruning_bottom (a : PathSpace) : Same (retain a []) [] := by intro p; simp [mem_retain] theorem convexSubtract_faithful (b c : PathSpace) : (∀ a, Same (convexSubtract a b) (convexSubtract a c)) ↔ Same b c := by @@ -148,18 +148,18 @@ theorem hull_convexMeetMany (a : PathSpace) (bs : List PathSpace) : | cons b bs ih => intro p; simp only [convexMeetMany,hull_convexMeet,mem_inter,List.map_cons,interMany,ih] theorem convexMeetMany_normal (a : PathSpace) (bs : List PathSpace) : - Same (convexMeetMany a bs) (live (interMany a bs) (interMany (hull a) (bs.map hull))) := by + Same (convexMeetMany a bs) (retain (interMany a bs) (interMany (hull a) (bs.map hull))) := by induction bs generalizing a with - | nil => exact fun p => (live_hull a p).symm + | nil => exact fun p => (retain_hull a p).symm | cons b bs ih => intro p - simp only [convexMeetMany,mem_convexMeet,hull_convexMeetMany,ih,mem_live,List.map_cons,interMany,mem_inter] + simp only [convexMeetMany,mem_convexMeet,hull_convexMeetMany,ih,mem_retain,List.map_cons,interMany,mem_inter] grind theorem convex_normal_form (a : PathSpace) (bs masks : List PathSpace) : Same (convexSubtract (convexMeetMany a bs) masks.flatten) - (live (interMany a bs) (diff (interMany (hull a) (bs.map hull)) masks.flatten)) := by - intro p; simp only [mem_convexSubtract,hull_convexMeetMany,convexMeetMany_normal,mem_live,mem_diff]; grind + (retain (interMany a bs) (diff (interMany (hull a) (bs.map hull)) masks.flatten)) := by + intro p; simp only [mem_convexSubtract,hull_convexMeetMany,convexMeetMany_normal,mem_retain,mem_diff]; grind def convexSubtractMany (a : PathSpace) : List PathSpace → PathSpace | [] => a @@ -173,7 +173,7 @@ theorem convexSubtractMany_normal (a : PathSpace) (masks : List PathSpace) : theorem convex_many_normal_form (a : PathSpace) (bs masks : List PathSpace) : Same (convexSubtractMany (convexMeetMany a bs) masks) - (live (interMany a bs) (diff (interMany (hull a) (bs.map hull)) masks.flatten)) := + (retain (interMany a bs) (diff (interMany (hull a) (bs.map hull)) masks.flatten)) := fun p => (convexSubtractMany_normal _ _ p).trans (convex_normal_form a bs masks p) end PathMapModel.PathSpace diff --git a/lean/PathMapModel/ConvexPruning.lean b/lean/PathMapModel/ConvexPruning.lean index 6266eb22..87a590a5 100644 --- a/lean/PathMapModel/ConvexPruning.lean +++ b/lean/PathMapModel/ConvexPruning.lean @@ -22,12 +22,12 @@ theorem prune_protected {tips x : PathSpace} (ht : Included tips x) (n : Nat) : | zero => exact ht | succ n ih => intro p hp; exact (mem_pruneStep _ _ _).mpr ⟨ih p hp,Or.inl hp⟩ -theorem prune_preserves_live {tips x : PathSpace} (ht : Included tips x) (n : Nat) : - Included (live x tips) (convexPrune tips n x) := by +theorem prune_preserves_retain {tips x : PathSpace} (ht : Included tips x) (n : Nat) : + Included (retain x tips) (convexPrune tips n x) := by induction n with - | zero => intro p hp; exact ((mem_live _ _ _).mp hp).1 + | zero => intro p hp; exact ((mem_retain _ _ _).mp hp).1 | succ n ih => - intro p hp; obtain ⟨_,t,htip,hpt⟩ := (mem_live _ _ _).mp hp + intro p hp; obtain ⟨_,t,htip,hpt⟩ := (mem_retain _ _ _).mp hp apply (mem_pruneStep _ _ _).mpr; refine ⟨ih p hp,?_⟩ by_cases he : p = t · exact Or.inl (he ▸ htip) @@ -54,24 +54,24 @@ theorem prune_unsupported_length (tips x : PathSpace) (n : Nat) {p : Path} /-- A uniform height bound, valid even when the protected set is not maximal. -/ theorem convexPrune_stable {tips x : PathSpace} (ht : Included tips x) {n : Nat} - (hn : height x < n) : Same (convexPrune tips n x) (live x tips) := by + (hn : height x < n) : Same (convexPrune tips n x) (retain x tips) := by intro p; constructor · intro hp have hx := prune_subset tips n x p hp by_cases he : ∃ t ∈ tips, (p ≼ t) = true - · exact (mem_live _ _ _).mpr ⟨hx,he⟩ + · exact (mem_retain _ _ _).mpr ⟨hx,he⟩ · have hh := prune_unsupported_length tips x n hp he; omega - · exact prune_preserves_live ht n p + · exact prune_preserves_retain ht n p -theorem live_prune_fixed {tips x : PathSpace} (ht : Included tips x) : - Same (convexPruneStep (live x tips) tips) (live x tips) := by +theorem retain_prune_fixed {tips x : PathSpace} (ht : Included tips x) : + Same (convexPruneStep (retain x tips) tips) (retain x tips) := by intro p; rw [mem_pruneStep]; constructor · exact And.left - · intro hp; obtain ⟨_,t,htip,hpt⟩ := (mem_live _ _ _).mp hp + · intro hp; obtain ⟨_,t,htip,hpt⟩ := (mem_retain _ _ _).mp hp refine ⟨hp,?_⟩ by_cases he : p = t · exact Or.inl (he ▸ htip) - · exact Or.inr ⟨t,(mem_live _ _ _).mpr ⟨ht t htip,t,htip,Path.prefix_self t⟩,he,hpt⟩ + · exact Or.inr ⟨t,(mem_retain _ _ _).mpr ⟨ht t htip,t,htip,Path.prefix_self t⟩,he,hpt⟩ /-- Asynchronous pruning may remove any collection of exposed unprotected tips. -/ def PruneMove (tips x y : PathSpace) : Prop := @@ -80,9 +80,9 @@ inductive PruneTrace (tips : PathSpace) : PathSpace → PathSpace → Prop | refl (x) : PruneTrace tips x x | step {x y z} : PruneTrace tips x y → PruneMove tips y z → PruneTrace tips x z -theorem pruneMove_live {tips x y : PathSpace} (ht : Included tips x) - (h : PruneMove tips x y) : Same (live x tips) (live y tips) := by - intro p; rw [mem_live,mem_live]; constructor +theorem pruneMove_retain {tips x y : PathSpace} (ht : Included tips x) + (h : PruneMove tips x y) : Same (retain x tips) (retain y tips) := by + intro p; rw [mem_retain,mem_retain]; constructor · rintro ⟨hp,t,hti,hpt⟩ refine ⟨h.2 p ((mem_pruneStep _ _ _).mpr ⟨hp,?_⟩),t,hti,hpt⟩ by_cases he : p = t @@ -91,16 +91,16 @@ theorem pruneMove_live {tips x y : PathSpace} (ht : Included tips x) · rintro ⟨hp,t,hti,hpt⟩; exact ⟨h.1 p hp,t,hti,hpt⟩ theorem pruneTrace_invariant {tips x y : PathSpace} (ht : Included tips x) - (h : PruneTrace tips x y) : Included tips y ∧ Same (live x tips) (live y tips) := by + (h : PruneTrace tips x y) : Included tips y ∧ Same (retain x tips) (retain y tips) := by induction h with | refl => exact ⟨ht,fun _ => Iff.rfl⟩ | step h hm ih => - refine ⟨?_,fun p => (ih.2 p).trans (pruneMove_live ih.1 hm p)⟩ + refine ⟨?_,fun p => (ih.2 p).trans (pruneMove_retain ih.1 hm p)⟩ intro p hp; exact hm.2 p ((mem_pruneStep _ _ _).mpr ⟨ih.1 p hp,Or.inl hp⟩) theorem prune_fixed_iff (tips x : PathSpace) : - Same (convexPruneStep x tips) x → Same x (live x tips) := by - intro h p; rw [mem_live]; constructor + Same (convexPruneStep x tips) x → Same x (retain x tips) := by + intro h p; rw [mem_retain]; constructor · intro hp; obtain ⟨t,ht,hpt⟩ := hull_covers hp have hh := (mem_pruneStep _ _ _).mp ((h t).mpr (hull_subset _ ht)) rcases hh.2 with htip | ⟨q,hq,hne,htq⟩ @@ -111,7 +111,7 @@ theorem prune_fixed_iff (tips x : PathSpace) : /-- Every terminal result of arbitrary tip-removal order is the same closed form. -/ theorem convexPrune_confluent {tips x y : PathSpace} (ht : Included tips x) (h : PruneTrace tips x y) (hf : Same (convexPruneStep y tips) y) : - Same y (live x tips) := by + Same y (retain x tips) := by intro p; exact (prune_fixed_iff tips y hf p).trans ((pruneTrace_invariant ht h).2 p).symm /-- Every effective asynchronous deletion strictly decreases finite cardinality. -/ @@ -143,7 +143,7 @@ theorem convexPrune_trace (tips x : PathSpace) (n : Nat) : PruneTrace tips x (co /-- Every reachable state has a bounded continuation to the same normal form. -/ theorem convexPrune_join {tips x y : PathSpace} (ht : Included tips x) (h : PruneTrace tips x y) : - Same (convexPrune tips (height y + 1) y) (live x tips) := by + Same (convexPrune tips (height y + 1) y) (retain x tips) := by have hi := pruneTrace_invariant ht h intro p; exact (convexPrune_stable hi.1 (Nat.lt_succ_self _) p).trans (hi.2 p).symm @@ -163,7 +163,7 @@ theorem convexSubtractRec_correct (a b : PathSpace) : Same (convexSubtractRec a intro p have hh := convexPrune_stable ht (Nat.lt_succ_self (height (diff a (inter (hull a) b)))) p apply hh.trans - simp only [mem_live,mem_diff,mem_inter,mem_convexSubtract] + simp only [mem_retain,mem_diff,mem_inter,mem_convexSubtract] constructor · grind · rintro ⟨hp,t,htip,hn,hpt⟩ diff --git a/lean/PathMapModel/PathSetLCP.lean b/lean/PathMapModel/PathSetLCP.lean index 7c709aeb..a4b9d5ec 100644 --- a/lean/PathMapModel/PathSetLCP.lean +++ b/lean/PathMapModel/PathSetLCP.lean @@ -96,8 +96,8 @@ theorem mem_lcpProduct (a b : PathSpace) (p : Path) : simp [lcpProduct,List.mem_flatMap] theorem lcp_correction (a b : PathSpace) (p : Path) : - p ∈ lcpProduct a b ↔ p ∈ divergence a b ∨ p ∈ live a b ∨ p ∈ live b a := by - simp only [mem_lcpProduct,mem_divergence,mem_live,Path.lcp_cases] + p ∈ lcpProduct a b ↔ p ∈ divergence a b ∨ p ∈ retain a b ∨ p ∈ retain b a := by + simp only [mem_lcpProduct,mem_divergence,mem_retain,Path.lcp_cases] constructor · rintro ⟨x,hx,y,hy,h⟩ rcases h with hd | ⟨rfl,hp⟩ | ⟨rfl,hp⟩ @@ -112,8 +112,8 @@ theorem lcp_correction (a b : PathSpace) (p : Path) : theorem lcp_diagonal (a : PathSpace) (p : Path) : p ∈ lcpProduct a a ↔ p ∈ completion a := by rw [lcp_correction] - have hl : p ∈ live a a ↔ p ∈ a := by - rw [mem_live]; exact ⟨And.left,fun h => ⟨h,p,h,Path.prefix_self p⟩⟩ + have hl : p ∈ retain a a ↔ p ∈ a := by + rw [mem_retain]; exact ⟨And.left,fun h => ⟨h,p,h,Path.prefix_self p⟩⟩ simp only [completion,union,List.mem_append,hl,branches] grind diff --git a/lean/PathMapModel/PathSetLaws.lean b/lean/PathMapModel/PathSetLaws.lean index 71a10868..bfe20be7 100644 --- a/lean/PathMapModel/PathSetLaws.lean +++ b/lean/PathMapModel/PathSetLaws.lean @@ -75,14 +75,14 @@ def binary (a b : PathSpace) : Checks := ("output_heads", sub (head x) (inter (head a) (head b))), ("tails_bound", sub (tails x) (D (tails a) (tails b))), ("recursive_divergence", eq (divergenceRec (min (height a) (height b) + 1) a b) x), - ("live_recursive", eq (liveRec (height a + 1) a b) (live a b)), + ("retain_recursive", eq (retainRec (height a + 1) a b) (retain a b)), ("output_cardinality", decide (count x <= count (hull (union a b)) - 1)), ("output_hull_cardinality", decide (count (hull x) <= min (count ha) (count hb))), ("output_depth", implies (!x.isEmpty) (height x < min (height a) (height b))), ("output_covered", covers x a && covers x b), ("fork_completion", eq (Br (product a fork)) (C a)), ("fork_lcp", eq (D (product a fork) (product b fork)) (M a b)), - ("lcp_correction", eq (M a b) (union x (union (live a b) (live b a)))), + ("lcp_correction", eq (M a b) (union x (union (retain a b) (retain b a)))), ("lcp_diagonal", eq (M a a) (C a)), ("lcp_symmetry", eq (M a b) (M b a)), ("lcp_output_completion", eq (C (M a b)) (M a b)), @@ -106,9 +106,9 @@ def ternary (a b c : PathSpace) : Checks := ("branch_probe_exchange", sub (inter (D a b) (Br c)) (inter (D a c) (D b c))), ("lcp_associativity", eq (M (M a b) c) (M a (M b c))), ("lcp_bilinearity", eq (M (union a b) c) (union (M a c) (M b c))), - ("one_mask", eq (D (restrict a c) b) (union (restrict (D a b) c) (D (live c a) b))), + ("one_mask", eq (D (restrict a c) b) (union (restrict (D a b) c) (D (retain c a) b))), ("same_mask", eq (D (restrict a c) (restrict b c)) - (union (restrict (D a b) c) (D (live c a) (live c b)))), + (union (restrict (D a b) c) (D (retain c a) (retain c b)))), ("filter_partition", eq (D a b) (union (D (restrict a c) b) (D (raffinate a c) b))), ("common_prefix_code", implies (prefixFree a && !b.isEmpty && !c.isEmpty) (eq (D (product a b) (product a c)) (union (Br a) (product a (D b c))))) ] @@ -122,8 +122,8 @@ def rightOverlap (a b x y : PathSpace) : PathSpace := def quaternary (a b c f : PathSpace) : Checks := let x := D a b - let pa := live c a - let qb := live f b + let pa := retain c a + let qb := retain f b [ ("four_point_absorption", sub (D (D a b) (D c f)) (inter (inter (D a c) (D a f)) (inter (D b c) (D b f)))), ("four_point_exchange", sub (inter (D a b) (D c f)) @@ -158,9 +158,46 @@ def powers (a : PathSpace) (m n : Nat) : Checks := ((List.range (min m n)).flatMap fun i => product (power a i) (Br a)))), ("branch_leaf_bound", implies (!(branchIter a n).isEmpty) (2^n <= count (hull a))) ] +def retention (a b c f : PathSpace) : Checks := + [ ("retain_empty_left", eq (retain [] a) ([])), + ("retain_empty_right", eq (retain a []) ([])), + ("retain_self", eq (retain a a) (a)), + ("retain_union_left", eq (retain (union a b) c) (union (retain a c) (retain b c))), + ("retain_inter_left", eq (retain (inter a b) c) (inter (retain a c) (retain b c))), + ("retain_diff_left", eq (retain (diff a b) c) (diff (retain a c) (retain b c))), + ("retain_symDiff_left", eq (retain (symDiff a b) c) (symDiff (retain a c) (retain b c))), + ("retain_union_right", eq (retain a (union b c)) (union (retain a b) (retain a c))), + ("retain_filter_inter", eq (retain (retain a b) c) (inter (retain a b) (retain a c))), + ("retain_filter_comm", eq (retain (retain a b) c) (retain (retain a c) b)), + ("retain_filter_idem", eq (retain (retain a b) b) (retain a b)), + ("retain_hull_mask", eq (retain a (hull b)) (retain a b)), + ("retain_completion_mask", eq (retain a (C b)) (retain a b)), + ("retain_restrict_witnesses", eq (retain a (restrict b a)) (retain a b)), + ("restrict_retain_mask", eq (restrict a (retain b a)) (restrict a b)), + ("retain_restrict_disjoint", eq (retain a (raffinate b a)) ([])), + ("retain_restrict_source", eq (retain (restrict a b) c) (restrict (retain a c) b)), + ("retain_raffinate_source", eq (retain (raffinate a b) c) (raffinate (retain a c) b)), + ("retain_lcp_masks", eq (retain (retain a b) c) (retain a (M b c))), + ("retain_divergence_masks", eq (retain (retain a b) c) (retain a (union (D b c) (union (retain b c) (retain c b))))), + ("restrict_overlap_masks", eq (restrict (restrict a b) c) (restrict a (union (restrict b c) (restrict c b)))), + ("retain_restrict_mask", eq (retain a (restrict b c)) (union (restrict (retain a b) c) (retain a (retain c b)))), + ("restrict_retain_lcp", eq (restrict a (retain b c)) (restrict a (restrict (M a c) b))), + ("basis_retain", eq (basis (retain a b)) (retain (basis a) b)), + ("hull_restrict", eq (hull (restrict a b)) (restrict (hull a) b)), + ("retain_subset", sub (retain a b) (a)), + ("retain_inter_right_bound", sub (retain a (inter b c)) (inter (retain a b) (retain a c))), + ("retain_diff_right_bound", sub (diff (retain a b) (retain a c)) (retain a (diff b c))), + ("retain_nested_bound", sub (retain a (retain b c)) (retain (retain a b) c)), + ("retain_hull_source_bound", sub (retain (hull a) b) (hull (retain a b))), + ("divergence_retain_bound", sub (D (retain a c) (retain b f)) (inter (D a b) (D c f))), + ("branches_retain_bound", sub (Br (retain a b)) (inter (Br a) (Br b))), + ("retain_empty_duality", (retain a b).isEmpty == (restrict b a).isEmpty), + ("retain_identity", eq (retain a b) a == covers a b), + ("retain_count_bound", decide (count (retain a b) <= count a)) ] + /-- Assumptions are executable guards, so unconstrained inputs are safe to test. -/ def all (a b c f : PathSpace) : Checks := - unary a ++ binary a b ++ ternary a b c ++ quaternary a b c f ++ + unary a ++ binary a b ++ ternary a b c ++ quaternary a b c f ++ retention a b c f ++ (pathLaws a b []) ++ (pathLaws a b [0]) ++ (pathLaws a b [0,1,0]) def failures (checks : Checks) : List String := (checks.filter (! ·.2)).map (·.1) diff --git a/lean/PathMapModel/PathSetMasks.lean b/lean/PathMapModel/PathSetMasks.lean index b3989e94..644929e9 100644 --- a/lean/PathMapModel/PathSetMasks.lean +++ b/lean/PathMapModel/PathSetMasks.lean @@ -29,9 +29,9 @@ end PathMapModel.Path namespace PathMapModel.PathSpace -theorem mem_live (m a : PathSpace) (p : Path) : - p ∈ live m a ↔ p ∈ m ∧ ∃ q ∈ a, (p ≼ q) = true := by - simp [live, List.any_eq_true] +theorem mem_retain (m a : PathSpace) (p : Path) : + p ∈ retain m a ↔ p ∈ m ∧ ∃ q ∈ a, (p ≼ q) = true := by + simp [retain, List.any_eq_true] theorem mem_raffinate (a m : PathSpace) (p : Path) : p ∈ raffinate a m ↔ p ∈ a ∧ ∀ q ∈ m, (q ≼ p) = false := by @@ -47,7 +47,7 @@ theorem mem_raffinate (a m : PathSpace) (p : Path) : theorem divergence_one_mask (a b m : PathSpace) (p : Path) : p ∈ divergence (restrict a m) b ↔ - p ∈ restrict (divergence a b) m ∨ p ∈ divergence (live m a) b := by + p ∈ restrict (divergence a b) m ∨ p ∈ divergence (retain m a) b := by constructor · intro h obtain ⟨x,hx,y,hy,hd⟩ := (mem_divergence _ _ _).mp h @@ -56,38 +56,38 @@ theorem divergence_one_mask (a b m : PathSpace) (p : Path) : · exact Or.inl ((mem_restrict _ _ _).mpr ⟨(mem_divergence _ _ _).mpr ⟨x,hx,y,hy,hd⟩,r,hr,hrp⟩) · exact Or.inr ((mem_divergence _ _ _).mpr - ⟨r,(mem_live _ _ _).mpr ⟨hr,x,hx,hrx⟩,y,hy,hdr⟩) + ⟨r,(mem_retain _ _ _).mpr ⟨hr,x,hx,hrx⟩,y,hy,hdr⟩) · rintro (h | h) · obtain ⟨hp,r,hr,hrp⟩ := (mem_restrict _ _ _).mp h obtain ⟨x,hx,y,hy,hd⟩ := (mem_divergence _ _ _).mp hp exact (mem_divergence _ _ _).mpr ⟨x,(mem_restrict _ _ _).mpr ⟨hx,r,hr,Path.prefix_trans hrp (Path.divergence_prefix_left hd)⟩,y,hy,hd⟩ - · apply divergence_covered_mono (a := live m a) (b := restrict a m) ?_ p h + · apply divergence_covered_mono (a := retain m a) (b := restrict a m) ?_ p h intro r hr - obtain ⟨hr,x,hx,hrx⟩ := (mem_live _ _ _).mp hr + obtain ⟨hr,x,hx,hrx⟩ := (mem_retain _ _ _).mp hr exact ⟨x,(mem_restrict _ _ _).mpr ⟨hx,r,hr,hrx⟩,hrx⟩ theorem divergence_two_masks (a b m n : PathSpace) (p : Path) : p ∈ divergence (restrict a m) (restrict b n) ↔ p ∈ restrict (restrict (divergence a b) m) n ∨ - p ∈ restrict (divergence a (live n b)) m ∨ - p ∈ restrict (divergence (live m a) b) n ∨ - p ∈ divergence (live m a) (live n b) := by + p ∈ restrict (divergence a (retain n b)) m ∨ + p ∈ restrict (divergence (retain m a) b) n ∨ + p ∈ divergence (retain m a) (retain n b) := by rw [divergence_one_mask] have hb := divergence_one_mask b a n p simp only [mem_restrict] at hb rw [divergence_comm (restrict b n) a, divergence_comm b a, - divergence_comm (live n b) a] at hb - have hc := divergence_one_mask b (live m a) n p + divergence_comm (retain n b) a] at hb + have hc := divergence_one_mask b (retain m a) n p simp only [mem_restrict] at hc - rw [divergence_comm (restrict b n) (live m a), divergence_comm b (live m a), - divergence_comm (live n b) (live m a)] at hc + rw [divergence_comm (restrict b n) (retain m a), divergence_comm b (retain m a), + divergence_comm (retain n b) (retain m a)] at hc simp only [mem_restrict] at hb hc ⊢ grind theorem divergence_same_mask (a b m : PathSpace) (p : Path) : p ∈ divergence (restrict a m) (restrict b m) ↔ - p ∈ restrict (divergence a b) m ∨ p ∈ divergence (live m a) (live m b) := by + p ∈ restrict (divergence a b) m ∨ p ∈ divergence (retain m a) (retain m b) := by rw [divergence_two_masks] constructor · rintro (h | h | h | h) @@ -95,12 +95,12 @@ theorem divergence_same_mask (a b m : PathSpace) (p : Path) : · obtain ⟨hd,r,hr,hrp⟩ := (mem_restrict _ _ _).mp h have he : p ∈ divergence a b := by apply (divergence_comm b a p).mp - apply divergence_covered_mono (a := live m b) (fun q hq => ((mem_live _ _ _).mp hq).2) p - exact (divergence_comm a (live m b) p).mp hd + apply divergence_covered_mono (a := retain m b) (fun q hq => ((mem_retain _ _ _).mp hq).2) p + exact (divergence_comm a (retain m b) p).mp hd exact Or.inl ((mem_restrict _ _ _).mpr ⟨he,r,hr,hrp⟩) · obtain ⟨hd,r,hr,hrp⟩ := (mem_restrict _ _ _).mp h - have he := divergence_covered_mono (a := live m a) (b := a) - (fun q hq => ((mem_live _ _ _).mp hq).2) p hd + have he := divergence_covered_mono (a := retain m a) (b := a) + (fun q hq => ((mem_retain _ _ _).mp hq).2) p hd exact Or.inl ((mem_restrict _ _ _).mpr ⟨he,r,hr,hrp⟩) · exact Or.inr h · rintro (h | h) @@ -111,11 +111,11 @@ theorem divergence_single_mask (a b : PathSpace) (q p : Path) : p ∈ divergence (restrict a [q]) (restrict b [q]) ↔ p ∈ restrict (divergence a b) [q] := by rw [divergence_same_mask] - have hn : p ∉ divergence (live [q] a) (live [q] b) := by + have hn : p ∉ divergence (retain [q] a) (retain [q] b) := by intro h obtain ⟨x,hx,y,hy,hd⟩ := (mem_divergence _ _ _).mp h - have hxq := ((mem_live _ _ _).mp hx).1 - have hyq := ((mem_live _ _ _).mp hy).1 + have hxq := ((mem_retain _ _ _).mp hx).1 + have hyq := ((mem_retain _ _ _).mp hy).1 simp only [List.mem_singleton] at hxq hyq subst x; subst y; simp at hd exact or_iff_left hn diff --git a/lean/PathMapModel/PathSetRecursive.lean b/lean/PathMapModel/PathSetRecursive.lean index f13de11e..fd3f9462 100644 --- a/lean/PathMapModel/PathSetRecursive.lean +++ b/lean/PathMapModel/PathSetRecursive.lean @@ -75,12 +75,12 @@ theorem hull_nil (a : PathSpace) : [] ∈ hull a ↔ [] ∈ a ∧ head a = [] := simp only [Path.isPrefixOf] grind -theorem live_nil (m a : PathSpace) : [] ∈ live m a ↔ [] ∈ m ∧ a ≠ [] := by - cases a <;> simp [live,Path.isPrefixOf] +theorem retain_nil (m a : PathSpace) : [] ∈ retain m a ↔ [] ∈ m ∧ a ≠ [] := by + cases a <;> simp [retain,Path.isPrefixOf] -theorem live_cons (m a : PathSpace) (c : UInt8) (p : Path) : - c :: p ∈ live m a ↔ p ∈ live (unwrap m [c]) (unwrap a [c]) := by - simp only [mem_live,mem_unwrap,List.singleton_append] +theorem retain_cons (m a : PathSpace) (c : UInt8) (p : Path) : + c :: p ∈ retain m a ↔ p ∈ retain (unwrap m [c]) (unwrap a [c]) := by + simp only [mem_retain,mem_unwrap,List.singleton_append] constructor · rintro ⟨hp,q,hq,he⟩ cases q with @@ -113,7 +113,7 @@ theorem mem_common_head_expansion (a b : PathSpace) (f : Path → PathSpace) (p subst d; exact ⟨c,r,hc,hd',hr,rfl⟩ · rintro ⟨c,r,hc,hd,hr,rfl⟩; exact ⟨[c],⟨⟨c,rfl,hc⟩,⟨c,rfl,hd⟩⟩,r,hr,rfl⟩ -theorem mem_live_head_expansion (a b : PathSpace) (f : Path → PathSpace) (p : Path) : +theorem mem_retain_head_expansion (a b : PathSpace) (f : Path → PathSpace) (p : Path) : p ∈ (normalize (inter (head a) (head b))).flatMap (fun q => wrap q (f q)) ↔ ∃ c r, Child a [] c ∧ Child b [] c ∧ r ∈ f [c] ∧ c :: r = p := by simp only [List.mem_flatMap,mem_inter,mem_normalize,mem_head,mem_wrap] @@ -215,35 +215,35 @@ theorem divergenceRec_spec (n : Nat) (a b : PathSpace) (p : Path) : obtain ⟨x,hx,y,hy,hd⟩ := (mem_divergence _ _ _).mp hp exact ⟨c,ps,child_of_unwrap hx,child_of_unwrap hy,⟨hp,by omega⟩,rfl,rfl⟩ -theorem liveRec_spec (n : Nat) (m a : PathSpace) (p : Path) : - p ∈ liveRec n m a ↔ p ∈ live m a ∧ p.length < n := by +theorem retainRec_spec (n : Nat) (m a : PathSpace) (p : Path) : + p ∈ retainRec n m a ↔ p ∈ retain m a ∧ p.length < n := by induction n generalizing m a p with - | zero => simp [liveRec] + | zero => simp [retainRec] | succ n ih => - simp only [liveRec,List.mem_append,mem_live_head_expansion] + simp only [retainRec,List.mem_append,mem_retain_head_expansion] by_cases he : (m.contains [] && !a.isEmpty) = true - · have hh : [] ∈ live m a := (live_nil m a).mpr (by simpa using he) + · have hh : [] ∈ retain m a := (retain_nil m a).mpr (by simpa using he) simp only [he] simp only [if_true] cases p with | nil => simp [hh] | cons c ps => - simp only [List.mem_singleton,List.cons_ne_nil,false_or,List.cons.injEq,ih,List.length_cons,live_cons] + simp only [List.mem_singleton,List.cons_ne_nil,false_or,List.cons.injEq,ih,List.length_cons,retain_cons] constructor · rintro ⟨_,_,_,_,⟨hp,hl⟩,rfl,rfl⟩; exact ⟨hp,by omega⟩ · rintro ⟨hp,hl⟩ - obtain ⟨hm,q,hq,_⟩ := (mem_live _ _ _).mp hp + obtain ⟨hm,q,hq,_⟩ := (mem_retain _ _ _).mp hp exact ⟨c,ps,child_of_unwrap hm,child_of_unwrap hq,⟨hp,by omega⟩,rfl,rfl⟩ · have hb : (m.contains [] && !a.isEmpty) = false := by simpa using he simp only [hb,Bool.false_eq_true,if_false] cases p with - | nil => simp [live_nil]; simpa using he + | nil => simp [retain_nil]; simpa using he | cons c ps => - simp only [List.not_mem_nil,false_or,List.cons.injEq,ih,List.length_cons,live_cons] + simp only [List.not_mem_nil,false_or,List.cons.injEq,ih,List.length_cons,retain_cons] constructor · rintro ⟨_,_,_,_,⟨hp,hl⟩,rfl,rfl⟩; exact ⟨hp,by omega⟩ · rintro ⟨hp,hl⟩ - obtain ⟨hm,q,hq,_⟩ := (mem_live _ _ _).mp hp + obtain ⟨hm,q,hq,_⟩ := (mem_retain _ _ _).mp hp exact ⟨c,ps,child_of_unwrap hm,child_of_unwrap hq,⟨hp,by omega⟩,rfl,rfl⟩ theorem basis_recursive (a : PathSpace) (p : Path) : @@ -273,8 +273,8 @@ theorem branch_recursive (a : PathSpace) (p : Path) : p ∈ divergenceRec (height a + 1) a a ↔ p ∈ branches a := by simpa [branches] using divergence_recursive a a p -theorem live_recursive (m a : PathSpace) (p : Path) : - p ∈ liveRec (height m + 1) m a ↔ p ∈ live m a := by - rw [liveRec_spec] - exact ⟨And.left,fun h => ⟨h,Nat.lt_succ_of_le (length_le_height ((mem_live _ _ _).mp h).1)⟩⟩ +theorem retain_recursive (m a : PathSpace) (p : Path) : + p ∈ retainRec (height m + 1) m a ↔ p ∈ retain m a := by + rw [retainRec_spec] + exact ⟨And.left,fun h => ⟨h,Nat.lt_succ_of_le (length_le_height ((mem_retain _ _ _).mp h).1)⟩⟩ end PathMapModel.PathSpace diff --git a/lean/PathMapModel/PathSets.lean b/lean/PathMapModel/PathSets.lean index d4c0b096..55131c71 100644 --- a/lean/PathMapModel/PathSets.lean +++ b/lean/PathMapModel/PathSets.lean @@ -57,7 +57,8 @@ def wrap (p : Path) (a : PathSpace) : PathSpace := a.map (p ++ ·) def unwrap (a : PathSpace) (p : Path) : PathSpace := a.filterMap (Path.stripPrefix p) def restrict (a p : PathSpace) : PathSpace := a.filter fun x => p.any (· ≼ x) def raffinate (a p : PathSpace) : PathSpace := diff a (restrict a p) -def live (p a : PathSpace) : PathSpace := p.filter fun x => a.any (x ≼ ·) +/-- Keep candidate arguments that prefix a valued witness in the second operand. -/ +def retain (p a : PathSpace) : PathSpace := p.filter fun x => a.any (x ≼ ·) def head (a : PathSpace) : PathSpace := a.filterMap fun p => p.head?.map (fun b => [b]) def tails (a : PathSpace) : PathSpace := a.filterMap fun p => match p with | [] => none @@ -110,12 +111,12 @@ def hullRec : Nat → PathSpace → PathSpace | n + 1, a => let root := if a.contains [] && (head a).isEmpty then [[]] else [] root ++ (normalize (head a)).flatMap fun p => wrap p (hullRec n (unwrap a p)) -def liveRec : Nat → PathSpace → PathSpace → PathSpace +def retainRec : Nat → PathSpace → PathSpace → PathSpace | 0, _, _ => [] | n + 1, p, a => let root := if p.contains [] && !a.isEmpty then [[]] else [] root ++ (normalize (inter (head p) (head a))).flatMap fun q => - wrap q (liveRec n (unwrap p q) (unwrap a q)) + wrap q (retainRec n (unwrap p q) (unwrap a q)) def ofMap {V : Type} (t : PathMap V) : PathSpace := t.vals.map (·.1) @@ -173,6 +174,11 @@ end PathSpace namespace Map +/-- Keep argument values whose paths prefix a valued witness in the graph. -/ +def retain {V W : Type} (a : PathMap V) (b : PathMap W) : PathMap V := + let support := PathSpace.retain (PathSpace.ofMap a) (PathSpace.ofMap b) + PathMap.mk' (a.vals.filter (fun kv => support.contains kv.1)) [] + def basis {V : Type} (t : PathMap V) : PathMap V := let support := PathSpace.basis (PathSpace.ofMap t) PathMap.mk' (t.vals.filter (fun kv => support.contains kv.1)) [] @@ -185,6 +191,9 @@ def branches {V : Type} (a : PathMap V) : PathMap Unit := divergence a a end Map namespace Zip + +def retain {V W : Type} (src : Zip V) (witnesses : Zip W) (out : Zip V) : Zip V := + out.graftMap (Map.retain src.makeMap witnesses.makeMap) /-- Relative focus semantics; input and output cursor positions are unchanged. -/ def basis {V : Type} (src out : Zip V) : Zip V := out.graftMap (Map.basis src.makeMap) def hull {V : Type} (src out : Zip V) : Zip V := out.graftMap (Map.hull src.makeMap) diff --git a/lean/PathMapModel/Retain.lean b/lean/PathMapModel/Retain.lean new file mode 100644 index 00000000..b711b7ce --- /dev/null +++ b/lean/PathMapModel/Retain.lean @@ -0,0 +1,355 @@ +import PathMapModel.ConvexMap + +/-! Retention and restriction are the two projections of the prefix relation. +All equations are extensional on valued paths; no closure is implicit. -/ +namespace PathMapModel.PathSpace + +theorem retain_subset (a b : PathSpace) : Included (retain a b) a := + fun p h => ((mem_retain a b p).mp h).1 + +theorem retain_empty_left (a : PathSpace) : Same (retain [] a) [] := by + intro p; simp [mem_retain] + +theorem retain_empty_right (a : PathSpace) : Same (retain a []) [] := by + intro p; simp [mem_retain] + +theorem retain_self (a : PathSpace) : Same (retain a a) a := by + intro p; rw [mem_retain]; exact ⟨And.left, fun h => ⟨h,p,h,Path.prefix_self p⟩⟩ + +theorem retain_mono {a b c d : PathSpace} (h : Included a c) (k : Included b d) : + Included (retain a b) (retain c d) := by + intro p hp; obtain ⟨hp,q,hq,hpq⟩ := (mem_retain _ _ _).mp hp + exact (mem_retain _ _ _).mpr ⟨h p hp,q,k q hq,hpq⟩ + +theorem retain_union_left (a b c : PathSpace) : + Same (retain (union a b) c) (union (retain a c) (retain b c)) := by + intro p; simp only [mem_retain,union,List.mem_append]; grind + +theorem retain_inter_left (a b c : PathSpace) : + Same (retain (inter a b) c) (inter (retain a c) (retain b c)) := by + intro p; simp only [mem_retain,mem_inter]; grind + +theorem retain_diff_left (a b c : PathSpace) : + Same (retain (diff a b) c) (diff (retain a c) (retain b c)) := by + intro p; simp only [mem_retain,mem_diff]; grind + +theorem retain_symDiff_left (a b c : PathSpace) : + Same (retain (symDiff a b) c) (symDiff (retain a c) (retain b c)) := by + intro p; simp only [symDiff,mem_retain,mem_diff,union,List.mem_append]; grind + +theorem retain_union_right (a b c : PathSpace) : + Same (retain a (union b c)) (union (retain a b) (retain a c)) := by + intro p; simp only [mem_retain,union,List.mem_append]; grind + +theorem retain_inter_right_bound (a b c : PathSpace) : + Included (retain a (inter b c)) (inter (retain a b) (retain a c)) := by + intro p; simp only [mem_retain,mem_inter]; grind + +theorem retain_diff_right_bound (a b c : PathSpace) : + Included (diff (retain a b) (retain a c)) (retain a (diff b c)) := by + intro p; simp only [mem_retain,mem_diff]; grind + +theorem retain_filter_inter (a b c : PathSpace) : + Same (retain (retain a b) c) (inter (retain a b) (retain a c)) := by + intro p; simp only [mem_retain,mem_inter]; grind + +theorem retain_filter_comm (a b c : PathSpace) : + Same (retain (retain a b) c) (retain (retain a c) b) := by + intro p; simp only [mem_retain]; grind + +theorem retain_filter_idem (a b : PathSpace) : Same (retain (retain a b) b) (retain a b) := by + intro p; simp only [mem_retain]; grind + +theorem retain_nested_bound (a b c : PathSpace) : + Included (retain a (retain b c)) (retain (retain a b) c) := by + intro p hp; obtain ⟨hp,q,hq,hpq⟩ := (mem_retain _ _ _).mp hp + obtain ⟨hq,r,hr,hqr⟩ := (mem_retain _ _ _).mp hq + exact (mem_retain _ _ _).mpr ⟨(mem_retain _ _ _).mpr ⟨hp,q,hq,hpq⟩,r,hr,Path.prefix_trans hpq hqr⟩ + +theorem retain_universal (x a b : PathSpace) : + Included x (retain a b) ↔ Included x a ∧ covers x b = true := by + rw [covers_iff]; simp only [Included,mem_retain]; grind + +theorem retain_identity (a b : PathSpace) : Same (retain a b) a ↔ covers a b = true := by + rw [covers_iff]; simp only [Same,mem_retain]; grind + +/-- Replacing witnesses by their maximal members loses no prefixes. -/ +theorem retain_hull_mask (a b : PathSpace) : Same (retain a (hull b)) (retain a b) := by + intro p; rw [mem_retain,mem_retain]; constructor + · rintro ⟨hp,q,hq,hpq⟩; exact ⟨hp,q,hull_subset _ hq,hpq⟩ + · rintro ⟨hp,q,hq,hpq⟩; obtain ⟨r,hr,hqr⟩ := hull_covers hq + exact ⟨hp,r,hr,Path.prefix_trans hpq hqr⟩ + +/-- Both semijoins describe the same set of matching prefix pairs. -/ +theorem retain_restrict_empty (a b : PathSpace) : + Same (retain a b) [] ↔ Same (restrict b a) [] := by + simp only [Same,mem_retain,mem_restrict,List.not_mem_nil,iff_false]; grind + +theorem retain_restrict_witnesses (a b : PathSpace) : + Same (retain a (restrict b a)) (retain a b) := by + intro p; simp only [mem_retain,mem_restrict]; constructor + · grind + · rintro ⟨hp,q,hq,hpq⟩; exact ⟨hp,q,⟨hq,p,hp,hpq⟩,hpq⟩ + +theorem restrict_retain_mask (a b : PathSpace) : + Same (restrict a (retain b a)) (restrict a b) := by + intro p; simp only [mem_retain,mem_restrict]; constructor + · grind + · rintro ⟨hp,q,hq,hqp⟩; exact ⟨hp,q,⟨hq,p,hp,hqp⟩,hqp⟩ + +theorem retain_restrict_disjoint (a b : PathSpace) : Same (retain a (raffinate b a)) [] := by + intro p; simp only [mem_retain,raffinate,mem_diff,mem_restrict,List.not_mem_nil,iff_false]; grind + +theorem retain_subset_iff_restrict_empty (a b c : PathSpace) : + Included (retain a b) c ↔ Same (restrict b (diff a c)) [] := by + simp only [Included,Same,mem_retain,mem_restrict,mem_diff,List.not_mem_nil,iff_false]; grind + +theorem restrict_subset_iff_retain_empty (a b c : PathSpace) : + Included (restrict a b) c ↔ Same (retain b (diff a c)) [] := by + simp only [Included,Same,mem_retain,mem_restrict,mem_diff,List.not_mem_nil,iff_false]; grind + +theorem retain_restrict_source (a b c : PathSpace) : + Same (retain (restrict a b) c) (restrict (retain a c) b) := by + intro p; simp only [mem_retain,mem_restrict]; grind + +theorem retain_raffinate_source (a b c : PathSpace) : + Same (retain (raffinate a b) c) (raffinate (retain a c) b) := by + intro p; simp only [mem_retain,mem_raffinate]; grind + +theorem restrict_union_left (a b c : PathSpace) : + Same (restrict (union a b) c) (union (restrict a c) (restrict b c)) := by + intro p; simp only [mem_restrict,union,List.mem_append]; grind + +theorem restrict_inter_left (a b c : PathSpace) : + Same (restrict (inter a b) c) (inter (restrict a c) (restrict b c)) := by + intro p; simp only [mem_restrict,mem_inter]; grind + +theorem restrict_diff_left (a b c : PathSpace) : + Same (restrict (diff a b) c) (diff (restrict a c) (restrict b c)) := by + intro p; simp only [mem_restrict,mem_diff]; grind + +theorem restrict_union_right (a b c : PathSpace) : + Same (restrict a (union b c)) (union (restrict a b) (restrict a c)) := by + intro p; simp only [mem_restrict,union,List.mem_append]; grind + +theorem restrict_filter_comm (a b c : PathSpace) : + Same (restrict (restrict a b) c) (restrict (restrict a c) b) := by + intro p; simp only [mem_restrict]; grind + +theorem restrict_filter_idem (a b : PathSpace) : + Same (restrict (restrict a b) b) (restrict a b) := by + intro p; simp only [mem_restrict]; grind + +/-- Retention composes masks by their pairwise longest common prefixes. -/ +theorem retain_lcp_masks (a b c : PathSpace) : + Same (retain (retain a b) c) (retain a (lcpProduct b c)) := by + intro p; simp only [mem_retain,mem_lcpProduct]; constructor + · rintro ⟨⟨hp,q,hq,hpq⟩,r,hr,hpr⟩ + exact ⟨hp,Path.lcp q r,⟨q,hq,r,hr,rfl⟩,(Path.prefix_lcp p q r).mpr ⟨hpq,hpr⟩⟩ + · rintro ⟨hp,_,⟨q,hq,r,hr,rfl⟩,h⟩ + obtain ⟨hpq,hpr⟩ := (Path.prefix_lcp p q r).mp h + exact ⟨⟨hp,q,hq,hpq⟩,r,hr,hpr⟩ + +theorem retain_divergence_masks (a b c : PathSpace) : + Same (retain (retain a b) c) + (retain a (union (divergence b c) (union (retain b c) (retain c b)))) := by + intro p; rw [retain_lcp_masks] + apply retain_congr (fun _ => Iff.rfl) _ p + intro q; simp only [lcp_correction,union,List.mem_append] + +/-- Restriction composes masks by the longer of comparable witnesses. -/ +theorem restrict_overlap_masks (a b c : PathSpace) : + Same (restrict (restrict a b) c) (restrict a (union (restrict b c) (restrict c b))) := by + intro p; simp only [mem_restrict,union,List.mem_append]; constructor + · rintro ⟨⟨hp,q,hq,hqp⟩,r,hr,hrp⟩ + rcases Path.prefixes_comparable hqp hrp with hqr | hrq + · exact ⟨hp,r,Or.inr ⟨hr,q,hq,hqr⟩,hrp⟩ + · exact ⟨hp,q,Or.inl ⟨hq,r,hr,hrq⟩,hqp⟩ + · rintro ⟨hp,q,(⟨hq,r,hr,hrq⟩ | ⟨hq,r,hr,hrq⟩),hqp⟩ + · exact ⟨⟨hp,q,hq,hqp⟩,r,hr,Path.prefix_trans hrq hqp⟩ + · exact ⟨⟨hp,r,hr,Path.prefix_trans hrq hqp⟩,q,hq,hqp⟩ + +/-- Comparable prefixes split the mixed composition into its two orders. -/ +theorem retain_restrict_mask (a b c : PathSpace) : + Same (retain a (restrict b c)) + (union (restrict (retain a b) c) (retain a (retain c b))) := by + intro p; simp only [mem_retain,mem_restrict,union,List.mem_append]; constructor + · rintro ⟨hp,q,⟨hq,r,hr,hrq⟩,hpq⟩ + rcases Path.prefixes_comparable hpq hrq with hpr | hrp + · exact Or.inr ⟨hp,r,⟨hr,q,hq,hrq⟩,hpr⟩ + · exact Or.inl ⟨⟨hp,q,hq,hpq⟩,r,hr,hrp⟩ + · rintro (⟨⟨hp,q,hq,hpq⟩,r,hr,hrp⟩ | ⟨hp,r,⟨hr,q,hq,hrq⟩,hpr⟩) + · exact ⟨hp,q,⟨hq,r,hr,Path.prefix_trans hrp hpq⟩,hpq⟩ + · exact ⟨hp,q,⟨hq,r,hr,hrq⟩,Path.prefix_trans hpr hrq⟩ + +theorem basis_retain (a b : PathSpace) : Same (basis (retain a b)) (retain (basis a) b) := by + intro p; simp only [mem_basis,mem_retain]; constructor + · rintro ⟨⟨hp,t,ht,hpt⟩,hn⟩ + refine ⟨⟨hp,?_⟩,t,ht,hpt⟩ + intro q hq hne; cases hqp : q ≼ p with + | false => exact hqp + | true => have := hn q ⟨hq,t,ht,Path.prefix_trans hqp hpt⟩ hne; simp [hqp] at this + · rintro ⟨⟨hp,hn⟩,t,ht,hpt⟩ + exact ⟨⟨hp,t,ht,hpt⟩,fun q hq hnq => hn q hq.1 hnq⟩ + +theorem hull_restrict (a b : PathSpace) : Same (hull (restrict a b)) (restrict (hull a) b) := by + intro p; simp only [mem_hull,mem_restrict]; constructor + · rintro ⟨⟨hp,t,ht,htp⟩,hn⟩ + refine ⟨⟨hp,?_⟩,t,ht,htp⟩ + intro q hq hne; cases hpq : p ≼ q with + | false => exact hpq + | true => have := hn q ⟨hq,t,ht,Path.prefix_trans htp hpq⟩ hne; simp [hpq] at this + · rintro ⟨⟨hp,hn⟩,t,ht,htp⟩ + exact ⟨⟨hp,t,ht,htp⟩,fun q hq hnq => hn q hq.1 hnq⟩ + +theorem retain_hull_source_bound (a b : PathSpace) : + Included (retain (hull a) b) (hull (retain a b)) := by + intro p hp; obtain ⟨hp,q,hq,hpq⟩ := (mem_retain _ _ _).mp hp + apply (mem_hull _ _).mpr + exact ⟨(mem_retain _ _ _).mpr ⟨hull_subset _ hp,q,hq,hpq⟩, + fun r hr hn => ((mem_hull _ _).mp hp).2 r (retain_subset _ _ r hr) hn⟩ + +theorem retain_antichain {a : PathSpace} (h : Antichain a) (b : PathSpace) : + Antichain (retain a b) := fun p hp q hq => h p (retain_subset _ _ p hp) q (retain_subset _ _ q hq) + +/-- Two retained witnesses diverge at the same point as their extensions. -/ +theorem divergence_retain_bound (a b c d : PathSpace) : + Included (divergence (retain a c) (retain b d)) (inter (divergence a b) (divergence c d)) := by + intro p hp; apply (mem_inter _ _ _).mpr + refine ⟨divergence_mono (retain_subset a c) (retain_subset b d) p hp,?_⟩ + have h := divergence_covered_mono (a := retain a c) (b := c) + (fun q hq => ((mem_retain _ _ _).mp hq).2) p hp + apply (divergence_comm _ _ _).mp + exact divergence_covered_mono (a := retain b d) (b := d) + (fun q hq => ((mem_retain _ _ _).mp hq).2) p ((divergence_comm _ _ _).mp h) + +theorem branches_retain_bound (a b : PathSpace) : + Included (branches (retain a b)) (inter (branches a) (branches b)) := + divergence_retain_bound a a b b + + +theorem retain_covered_mask {b c : PathSpace} (h : covers b c = true) (a : PathSpace) : + Included (retain a b) (retain a c) := by + intro p hp; obtain ⟨hp,q,hq,hpq⟩ := (mem_retain _ _ _).mp hp + obtain ⟨r,hr,hqr⟩ := (covers_iff b c).mp h q hq + exact (mem_retain _ _ _).mpr ⟨hp,r,hr,Path.prefix_trans hpq hqr⟩ + +/-- An exact characterization of the order induced on witness masks. -/ +theorem retain_mask_order (b c : PathSpace) : + (∀ a, Included (retain a b) (retain a c)) ↔ covers b c = true := by + constructor + · intro h; apply (covers_iff b c).mpr + intro p hp; exact ((mem_retain _ _ _).mp (h b p ((retain_self b p).mpr hp))).2 + · intro h a; exact retain_covered_mask h a + +theorem hull_mutual_covers {b c : PathSpace} (h : covers b c = true) (k : covers c b = true) : + Same (hull b) (hull c) := by + have hb : Same (hull (union b c)) (hull b) := by + apply hull_cofinal + · intro p hp; exact List.mem_append_left _ hp + · intro p hp; rcases List.mem_append.mp hp with hp | hp + · exact ⟨p,hp,Path.prefix_self p⟩ + · exact (covers_iff c b).mp k p hp + have hc : Same (hull (union b c)) (hull c) := by + apply hull_cofinal + · intro p hp; exact List.mem_append_right _ hp + · intro p hp; rcases List.mem_append.mp hp with hp | hp + · exact (covers_iff b c).mp h p hp + · exact ⟨p,hp,Path.prefix_self p⟩ + exact fun p => (hb p).symm.trans (hc p) + +/-- Hull is the canonical representative of a retention mask. -/ +theorem retain_mask_equiv (b c : PathSpace) : + (∀ a, Same (retain a b) (retain a c)) ↔ Same (hull b) (hull c) := by + constructor + · intro h; apply hull_mutual_covers + · apply (retain_mask_order b c).mp; exact fun a p hp => (h a p).mp hp + · apply (retain_mask_order c b).mp; exact fun a p hp => (h a p).mpr hp + · intro h a p + exact (retain_hull_mask a b p).symm.trans + ((retain_congr (fun _ => Iff.rfl) h p).trans (retain_hull_mask a c p)) + +theorem retain_completion_mask (a b : PathSpace) : Same (retain a (completion b)) (retain a b) := by + intro p; simp only [mem_retain,completion,union,List.mem_append]; constructor + · rintro ⟨hp,q,hq | hq,hpq⟩ + · exact ⟨hp,q,hq,hpq⟩ + · obtain ⟨r,hr,hqr⟩ := divergence_output_covered hq + exact ⟨hp,r,hr,Path.prefix_trans hpq hqr⟩ + · rintro ⟨hp,q,hq,hpq⟩; exact ⟨hp,q,Or.inl hq,hpq⟩ + +theorem retain_antichain_inter {a b : PathSpace} (h : Antichain (union a b)) : + Same (retain a b) (inter a b) := by + intro p; rw [mem_retain,mem_inter]; constructor + · rintro ⟨hp,q,hq,hpq⟩ + have he := h p (List.mem_append_left _ hp) q (List.mem_append_right _ hq) hpq + exact ⟨hp,he ▸ hq⟩ + · rintro ⟨hp,hq⟩; exact ⟨hp,p,hq,Path.prefix_self p⟩ + +theorem retain_wrap (a b : PathSpace) (r : Path) : + Same (retain (wrap r a) (wrap r b)) (wrap r (retain a b)) := by + intro p; simp only [mem_retain,mem_wrap]; constructor + · rintro ⟨⟨x,hx,rfl⟩,_,⟨y,hy,rfl⟩,hxy⟩ + exact ⟨x,⟨hx,y,hy,by simpa only [Path.prefix_append_same] using hxy⟩,rfl⟩ + · rintro ⟨x,⟨hx,y,hy,hxy⟩,rfl⟩ + exact ⟨⟨x,hx,rfl⟩,r++y,⟨y,hy,rfl⟩,by simpa only [Path.prefix_append_same] using hxy⟩ + +theorem retain_product {code : PathSpace} (hc : Antichain code) (a b : PathSpace) : + Same (retain (product code a) (product code b)) (product code (retain a b)) := by + intro p; simp only [mem_retain,mem_product]; constructor + · rintro ⟨⟨r,hr,x,hx,rfl⟩,_,⟨s,hs,y,hy,rfl⟩,h⟩ + obtain ⟨rfl,hxy⟩ := (code_prefix hc hr hs x y).mp h + exact ⟨r,hr,x,⟨hx,y,hy,hxy⟩,rfl⟩ + · rintro ⟨r,hr,x,⟨hx,y,hy,hxy⟩,rfl⟩ + exact ⟨⟨r,hr,x,hx,rfl⟩,r++y,⟨r,hr,y,hy,rfl⟩,(code_prefix hc hr hr x y).mpr ⟨rfl,hxy⟩⟩ + +/-- The dual mixed composition also normalizes through common-prefix masks. -/ +theorem restrict_retain_lcp (a b c : PathSpace) : + Same (restrict a (retain b c)) (restrict a (restrict (lcpProduct a c) b)) := by + intro p; simp only [mem_restrict,mem_retain,mem_lcpProduct]; constructor + · rintro ⟨hp,q,⟨hq,r,hr,hqr⟩,hqp⟩ + exact ⟨hp,Path.lcp p r,⟨⟨p,hp,r,hr,rfl⟩,q,hq,(Path.prefix_lcp q p r).mpr ⟨hqp,hqr⟩⟩, + Path.lcp_prefix_left p r⟩ + · rintro ⟨hp,_,⟨⟨x,hx,r,hr,rfl⟩,q,hq,hqm⟩,hmp⟩ + exact ⟨hp,q,⟨hq,r,hr,Path.prefix_trans hqm (Path.lcp_prefix_right x r)⟩,Path.prefix_trans hqm hmp⟩ + +theorem retain_count_bound (a b : PathSpace) : count (retain a b) ≤ count a := + count_mono (retain_subset a b) + +theorem restrict_self (a : PathSpace) : Same (restrict a a) a := by + intro p; rw [mem_restrict]; exact ⟨And.left,fun h => ⟨h,p,h,Path.prefix_self p⟩⟩ + +/-- The restriction-mask order is the dual, coinitial prefix order. -/ +theorem restrict_mask_order (b c : PathSpace) : + (∀ a, Included (restrict a b) (restrict a c)) ↔ ∀ p ∈ b, ∃ q ∈ c, (q ≼ p) = true := by + constructor + · intro h p hp; exact ((mem_restrict _ _ _).mp (h b p ((restrict_self b p).mpr hp))).2 + · intro h a p hp + obtain ⟨hp,q,hq,hqp⟩ := (mem_restrict _ _ _).mp hp + obtain ⟨r,hr,hrq⟩ := h q hq + exact (mem_restrict _ _ _).mpr ⟨hp,r,hr,Path.prefix_trans hrq hqp⟩ + +/-- Basis is the canonical representative of a restriction mask. -/ +theorem restrict_mask_equiv (b c : PathSpace) : + (∀ a, Same (restrict a b) (restrict a c)) ↔ Same (basis b) (basis c) := by + constructor + · intro h + have hbc := (restrict_mask_order b c).mp (fun a p hp => (h a p).mp hp) + have hcb := (restrict_mask_order c b).mp (fun a p hp => (h a p).mpr hp) + have hb : Same (basis (union b c)) (basis b) := by + apply basis_coinitial + · intro p hp; exact List.mem_append_left _ hp + · intro p hp; rcases List.mem_append.mp hp with hp | hp + · exact ⟨p,hp,Path.prefix_self p⟩ + · exact hcb p hp + have hc : Same (basis (union b c)) (basis c) := by + apply basis_coinitial + · intro p hp; exact List.mem_append_right _ hp + · intro p hp; rcases List.mem_append.mp hp with hp | hp + · exact hbc p hp + · exact ⟨p,hp,Path.prefix_self p⟩ + exact fun p => (hb p).symm.trans (hc p) + · intro h a p + rw [← restriction_basis_mask a b,← restriction_basis_mask a c] + simp only [mem_restrict,h] + +end PathMapModel.PathSpace diff --git a/lean/PathMapModel/RetainChecks.lean b/lean/PathMapModel/RetainChecks.lean new file mode 100644 index 00000000..316710c9 --- /dev/null +++ b/lean/PathMapModel/RetainChecks.lean @@ -0,0 +1,40 @@ +import PathMapModel.RetainConvex + +/-! Kernel-checked examples and counterexamples delimit the unconditional laws. -/ +namespace PathMapModel.PathSpace + +theorem retain_function_example : + restrict [[1,1],[2,4],[3,9],[4,16],[5,25]] [[0],[2],[4],[6]] = [[2,4],[4,16]] ∧ + retain [[0],[2],[4],[6]] [[1,1],[2,4],[3,9],[4,16],[5,25]] = [[2],[4]] := by decide + +theorem retain_not_commutative : + equiv (retain [[0]] [[0,1]]) (retain [[0,1]] [[0]]) = false := by decide + +theorem retain_not_associative : + equiv (retain (retain [[]] [[0]]) [[]]) (retain [[]] (retain [[0]] [[]])) = false := by decide + +theorem retain_not_mask_intersection : + equiv (retain [[]] (inter [[0]] [[1]])) (inter (retain [[]] [[0]]) (retain [[]] [[1]])) = false := by decide + +theorem retain_not_mask_difference : + equiv (retain [[]] (diff [[0]] [[1]])) (diff (retain [[]] [[0]]) (retain [[]] [[1]])) = false := by decide + +theorem retain_not_hull_source : + equiv (hull (retain [[],[0]] [[]])) (retain (hull [[],[0]]) [[]]) = false := by decide + +theorem retain_not_basis_mask : + equiv (retain [[0]] [[],[0]]) (retain [[0]] (basis [[],[0]])) = false := by decide + +theorem retain_not_convexMeet_commutation : + equiv (retain (convexMeet [[],[0]] [[],[0]]) [[]]) + (convexMeet (retain [[],[0]] [[]]) [[],[0]]) = false := by decide + +theorem retain_divergence_bound_strict : + equiv (branches (retain [[0,0],[1,0]] [[0,1],[1,1]])) + (inter (branches [[0,0],[1,0]]) (branches [[0,1],[1,1]])) = false := by decide + +theorem retain_product_needs_prefix_code : + equiv (retain (product [[],[0]] [[1]]) (product [[],[0]] [[0,1]])) + (product [[],[0]] (retain [[1]] [[0,1]])) = false := by decide + +end PathMapModel.PathSpace diff --git a/lean/PathMapModel/RetainConvex.lean b/lean/PathMapModel/RetainConvex.lean new file mode 100644 index 00000000..18710271 --- /dev/null +++ b/lean/PathMapModel/RetainConvex.lean @@ -0,0 +1,69 @@ +import PathMapModel.Retain + +namespace PathMapModel.PathSpace + +/-- Restriction commutes with convex meet when applied to both inputs. -/ +theorem restrict_convexMeet (a b c : PathSpace) : + Same (restrict (convexMeet a b) c) (convexMeet (restrict a c) (restrict b c)) := by + intro p; simp only [mem_convexMeet,hull_restrict,mem_restrict]; constructor + · rintro ⟨⟨ha,hb,t,hta,htb,hpt⟩,q,hq,hqp⟩ + exact ⟨⟨ha,q,hq,hqp⟩,⟨hb,q,hq,hqp⟩,t, + ⟨hta,q,hq,Path.prefix_trans hqp hpt⟩,⟨htb,q,hq,Path.prefix_trans hqp hpt⟩,hpt⟩ + · rintro ⟨⟨ha,q,hq,hqp⟩,⟨hb,_⟩,t,⟨hta,_⟩,⟨htb,_⟩,hpt⟩ + exact ⟨⟨ha,hb,t,hta,htb,hpt⟩,q,hq,hqp⟩ + +theorem restrict_convexSubtract (a b c : PathSpace) : + Same (restrict (convexSubtract a b) c) (convexSubtract (restrict a c) b) := by + intro p; simp only [mem_convexSubtract,hull_restrict,mem_restrict]; constructor + · rintro ⟨⟨ha,t,ht,hn,hpt⟩,q,hq,hqp⟩ + exact ⟨⟨ha,q,hq,hqp⟩,t,⟨ht,q,hq,Path.prefix_trans hqp hpt⟩,hn,hpt⟩ + · rintro ⟨⟨ha,q,hq,hqp⟩,t,⟨ht,_⟩,hn,hpt⟩ + exact ⟨⟨ha,t,ht,hn,hpt⟩,q,hq,hqp⟩ + +theorem restrict_convexSubtract_both (a b c : PathSpace) : + Same (restrict (convexSubtract a b) c) (convexSubtract (restrict a c) (restrict b c)) := by + intro p; rw [restrict_convexSubtract] + simp only [mem_convexSubtract,hull_restrict,mem_restrict]; grind + +/-- Selecting original tips permits exact normalization of a convex meet. -/ +theorem convexMeet_retain_tips {a t : PathSpace} (ht : Included t (hull a)) (b : PathSpace) : + Same (convexMeet (retain a t) b) (retain (inter a b) (inter t (hull b))) := by + intro p; simp only [mem_convexMeet,hull_retain ht,mem_retain,mem_inter]; grind + +theorem convexMeet_retain_both {a b t u : PathSpace} + (ht : Included t (hull a)) (hu : Included u (hull b)) : + Same (convexMeet (retain a t) (retain b u)) (retain (inter a b) (inter t u)) := by + intro p; simp only [mem_convexMeet,hull_retain ht,hull_retain hu,mem_retain,mem_inter]; grind + +theorem convexMeet_pruning {a t : PathSpace} (ht : Included t (hull a)) : + Same (convexMeet a (retain a t)) (retain a t) := by + intro p; simp only [mem_convexMeet,hull_retain ht,mem_retain]; constructor + · grind + · rintro ⟨hp,q,hq,hpq⟩; exact ⟨hp,⟨hp,q,hq,hpq⟩,q,ht q hq,hq,hpq⟩ + +/-- Ordinary retention can expose a new tip; convex retention protects old tips. -/ +theorem convex_pruning_retain_bound (a b : PathSpace) : + Included (retain a (retain (hull a) b)) (retain a b) := by + intro p hp + exact (retain_congr (retain_hull a) (fun _ => Iff.rfl) p).mp + (retain_nested_bound a (hull a) b p hp) + +theorem convexMeet_retained_mask (a b : PathSpace) : + Same (convexMeet a b) (retain (inter a b) (inter (hull a) (hull b))) := fun _ => Iff.rfl + +theorem convexSubtract_retained_mask (a b : PathSpace) : + Same (convexSubtract a b) (retain a (diff (hull a) b)) := fun _ => Iff.rfl + +end PathMapModel.PathSpace + +namespace PathMapModel.Map + +theorem retain_support {V W : Type} (a : PathMap V) (b : PathMap W) : + PathSpace.Same (PathSpace.ofMap (retain a b)) (PathSpace.retain (PathSpace.ofMap a) (PathSpace.ofMap b)) := by + intro p + change p ∈ PathSpace.ofMap (selectConvexSupport a (PathSpace.retain (PathSpace.ofMap a) (PathSpace.ofMap b))) ↔ _ + rw [selectConvexSupport_keys]; constructor + · exact And.right + · intro h; exact ⟨PathSpace.retain_subset _ _ p h,h⟩ + +end PathMapModel.Map diff --git a/src/experimental.rs b/src/experimental.rs index a1be1101..121405d4 100644 --- a/src/experimental.rs +++ b/src/experimental.rs @@ -12,7 +12,7 @@ use crate::write_zipper::write_zipper_priv::WriteZipperPriv; #[cfg(feature = "serialization")] pub mod serialization; -/// Prefix basis, hull, branches, and cross-space divergence. +/// Prefix basis, hull, retention, branches, and cross-space divergence. pub mod path_sets; /// Stable convex meet and subtract, with zipper and physical-node traversals. diff --git a/src/experimental/convex.rs b/src/experimental/convex.rs index f96bb87f..f6d69302 100644 --- a/src/experimental/convex.rs +++ b/src/experimental/convex.rs @@ -1,8 +1,8 @@ //! Stable convex algebra on valued paths, preserving left-hand payloads. //! -//! `meet(A,B) = live(A ∩ B, Hull(A) ∩ Hull(B))` and -//! `subtract(A,B) = live(A, Hull(A) \ B)`. In particular, a masked interior -//! survives if it supports a surviving original tip. `live(X, T)` selects the +//! `meet(A,B) = retain(A ∩ B, Hull(A) ∩ Hull(B))` and +//! `subtract(A,B) = retain(A, Hull(A) \ B)`. In particular, a masked interior +//! survives if it supports a surviving original tip. `retain(X, T)` selects the //! paths in `X` that prefix a tip in `T`; `Hull` selects prefix-maximal valued //! paths. Bare paths are not tips. //! diff --git a/src/experimental/path_sets.rs b/src/experimental/path_sets.rs index afeeb727..906f2d97 100644 --- a/src/experimental/path_sets.rs +++ b/src/experimental/path_sets.rs @@ -2,7 +2,7 @@ //! //! A dangling path is not a set member. Termination is not a branch: `foo` //! and `food` have no divergence. Basis and hull retain the original values; -//! divergence and branches return unit-valued maps. +//! retain preserves candidate values; divergence and branches return unit-valued maps. //! //! All traversals use zipper movements and explicit heap stacks, never pairs //! of keys, recursive Rust calls, repeated root lookups, or subtree `val_count`. @@ -168,6 +168,105 @@ fn has_value(src: &mut Z) -> bool { } } +struct RetainFrame { + common: ByteMask, + fringe: ByteMask, + witnessed: bool, +} + +impl RetainFrame { + fn new(left: &L, right: &R) -> Self { + let right_mask = right.child_mask(); + let common = left.child_mask() & right_mask; + Self { + common, + fringe: right_mask & !common, + witnessed: right.is_val(), + } + } +} + +/// Retain input values whose paths prefix a valued witness in `witnesses`. +/// Replace the output focus and restore all three focuses. Witness payloads +/// are ignored; output payloads come from `src`. +/// +/// O(C + F + output + value cloning) time and O(h) traversal storage: C counts +/// common structural byte prefixes, and F counts the first-witness searches in +/// disjoint witness-only fringes. Bare fringes may require a full scan. Each +/// common edge is traversed once in each direction; no subtree recount is used. +/// Replacing an existing output also incurs its destruction/COW cost. +pub fn zipper_retain(src: &mut L, witnesses: &mut R, out: &mut Out) +where + V: Clone + Send + Sync, + A: Allocator, + L: ZipperMoving + ZipperValues, + R: ZipperMoving, + Out: ZipperWriting, +{ + clear_output(out); + if !src.is_val() && src.child_count() == 0 { + return; + } + let mut stack = vec![RetainFrame::new(src, witnesses)]; + loop { + if let Some(byte) = pop_byte(&mut stack.last_mut().unwrap().common) { + src.descend_to_byte(byte); + witnesses.descend_to_byte(byte); + out.descend_to_byte(byte); + stack.push(RetainFrame::new(src, witnesses)); + } else { + let mut frame = stack.pop().unwrap(); + while !frame.witnessed { + let Some(byte) = pop_byte(&mut frame.fringe) else { + break; + }; + witnesses.descend_to_byte(byte); + frame.witnessed = has_value(witnesses); + witnesses.ascend(1); + } + if frame.witnessed { + if let Some(value) = src.val() { + out.set_val(value.clone()); + } + } + let Some(parent) = stack.last_mut() else { + break; + }; + parent.witnessed |= frame.witnessed; + src.ascend(1); + witnesses.ascend(1); + out.ascend(1); + } + } +} + +/// Keep the valued paths of `src` that prefix a valued path in `witnesses`. +/// Preserve source payloads and allocator; dangling paths are not witnesses. +/// +/// ``` +/// use pathmap::{PathMap, experimental::path_sets::retain}; +/// let args: PathMap<_> = [0, 2, 4, 6].into_iter().map(|x| ([x], x)).collect(); +/// let graph: PathMap<_> = [[1, 1], [2, 4], [3, 9], [4, 16], [5, 25]] +/// .into_iter().map(|p| (p, ())).collect(); +/// let kept = retain(&args, &graph); +/// assert_eq!(kept.iter().map(|(p, _)| p).collect::>(), vec![vec![2], vec![4]]); +/// ``` +pub fn retain(src: &PathMap, witnesses: &PathMap) -> PathMap +where + V: Clone + Send + Sync + Unpin, + W: Clone + Send + Sync + Unpin, + A: Allocator, + B: Allocator, +{ + let mut out = PathMap::new_in(src.alloc.clone()); + zipper_retain( + &mut src.read_zipper(), + &mut witnesses.read_zipper(), + &mut out.write_zipper(), + ); + out +} + struct BinaryFrame { left: ByteMask, right: ByteMask, diff --git a/tests/convex.rs b/tests/convex.rs index bbd67830..04004c5c 100644 --- a/tests/convex.rs +++ b/tests/convex.rs @@ -1,4 +1,8 @@ -use pathmap::{PathMap, experimental::convex::*, zipper::*}; +use pathmap::{ + PathMap, + experimental::{convex::*, path_sets::retain}, + zipper::*, +}; use std::collections::{BTreeMap, BTreeSet}; type Space = BTreeSet>; @@ -46,6 +50,19 @@ fn check(a: &Space, b: &Space, ma: &PathMap, mb: &PathMap) { hull(a).intersection(&hull(b)).cloned().collect(), ); let sub = prune(a.clone(), hull(a).difference(b).cloned().collect()); + let common = map(&a.intersection(b).cloned().collect()); + let common_tips = map(&hull(a).intersection(&hull(b)).cloned().collect()); + let surviving_tips = map(&hull(a).difference(b).cloned().collect()); + assert_eq!( + vals(&retain(&common, &common_tips)), + meet, + "retain meet {a:?} {b:?}" + ); + assert_eq!( + vals(&retain(ma, &surviving_tips)), + sub, + "retain subtract {a:?} {b:?}" + ); assert_eq!(vals(&convex_meet(ma, mb)), meet, "node meet {a:?} {b:?}"); assert_eq!( vals(&convex_subtract(ma, mb)), diff --git a/tests/path_sets.rs b/tests/path_sets.rs index a8a779eb..3705bd3d 100644 --- a/tests/path_sets.rs +++ b/tests/path_sets.rs @@ -84,6 +84,14 @@ fn exhaustive_binary_spaces() { assert_eq!(keys(&branches(ma)), oracle(a, a)); for (b, mb) in spaces.iter().zip(&maps) { assert_eq!(keys(&divergence(ma, mb)), oracle(a, b), "{a:?}, {b:?}"); + let expected = a + .iter() + .filter(|p| b.iter().any(|q| q.starts_with(p))) + .cloned() + .collect(); + let retained = retain(ma, mb); + assert_eq!(keys(&retained), expected, "retain {a:?}, {b:?}"); + assert_value_supported(&retained); } } } @@ -284,6 +292,14 @@ fn linear_work_and_basis_cutoff() { assert_eq!(a.moves + b.moves, 4 * (n - 1)); assert_eq!(out.val_count(), (1 << h) - 1); assert_eq!(a.depth() + b.depth(), 0); + let mut a = Counted::new(h); + let mut b = Counted::new(h); + zipper_retain(&mut a, &mut b, &mut out.write_zipper()); + assert_eq!(a.moves + b.moves, 4 * (n - 1)); + assert_eq!(a.masks.get(), n); + assert_eq!(b.masks.get(), n); + assert_eq!(a.depth() + b.depth(), 0); + assert_eq!(out.val_count(), 1 << h); } let mut a = Counted::new(1_000_000); a.root_value = true; @@ -316,3 +332,67 @@ fn disjoint_fringe_stops_at_first_value_and_empty_annihilates() { assert!(out.is_empty()); assert_eq!(bare.moves + actual.moves, 4 * ((1 << 9) - 2)); } + +#[test] +fn retain_focus_payloads_and_bare_witnesses() { + let mut a = PathMap::new(); + for (p, v) in [("left/", 1), ("left/a", 2), ("left/ab", 3), ("left/b", 4)] { + a.set_val_at(p, v); + } + let mut b = PathMap::single("right/abc", "witness".to_owned()); + b.write_zipper_at_path(b"right/b/c").create_path(); + let mut out = PathMap::single("keep", 9); + out.set_val_at("dest/stale", 10); + let mut left = a.read_zipper(); + let mut right = b.read_zipper(); + left.descend_to("left/"); + right.descend_to("right/"); + { + let mut dest = out.write_zipper(); + dest.descend_to("dest/"); + zipper_retain(&mut left, &mut right, &mut dest); + assert_eq!(left.path(), b"left/"); + assert_eq!(right.path(), b"right/"); + assert_eq!(dest.path(), b"dest/"); + } + assert_eq!( + out.iter().map(|(p, v)| (p, *v)).collect::>(), + vec![ + (b"dest/".to_vec(), 1), + (b"dest/a".to_vec(), 2), + (b"dest/ab".to_vec(), 3), + (b"keep".to_vec(), 9) + ] + ); + right.descend_to("b"); + zipper_retain( + &mut left, + &mut right, + &mut out.write_zipper_at_path(b"dest/"), + ); + assert_eq!(keys(&out), [b"keep".to_vec()].into()); + assert_eq!(right.path(), b"right/b"); +} + +#[test] +fn retain_fringe_witness_and_empty_shortcuts() { + let mut arg = Counted::new(0); + let mut witnesses = Counted::new(30); + let mut out = PathMap::new(); + zipper_retain(&mut arg, &mut witnesses, &mut out.write_zipper()); + assert_eq!(arg.moves, 0); + assert_eq!(witnesses.moves, 60); + assert_eq!(witnesses.depth(), 0); + assert_eq!(keys(&out), [vec![]].into()); + let mut bare = Counted::new(8); + bare.leaf_values = false; + zipper_retain(&mut arg, &mut bare, &mut out.write_zipper()); + assert_eq!(bare.moves, 2 * ((1 << 9) - 2)); + assert_eq!(bare.depth(), 0); + assert!(out.is_empty()); + arg.leaf_values = false; + let mut huge = Counted::new(1_000_000); + zipper_retain(&mut arg, &mut huge, &mut out.write_zipper()); + assert_eq!(huge.moves, 0); + assert!(out.is_empty()); +} diff --git a/tests/support/path_set_laws.rs b/tests/support/path_set_laws.rs index cbdb9e85..9f9c7d7f 100644 --- a/tests/support/path_set_laws.rs +++ b/tests/support/path_set_laws.rs @@ -3,7 +3,10 @@ use super::{KeySet, map_from_set, next_u64, prefix_heavy_set, set_from_map, wide_set}; use pathmap::{ PathMap, - experimental::path_sets::{basis, branches as br, divergence as d, hull}, + experimental::{ + convex::{convex_meet as cm, convex_subtract as cs}, + path_sets::{basis, branches as br, divergence as d, hull, retain}, + }, zipper::*, }; use std::collections::BTreeSet; @@ -65,15 +68,6 @@ fn product(a: &M, b: &M) -> M { } out } -fn live(p: &M, a: &M) -> M { - let mut out = M::new(); - for (q, _) in p.iter() { - if a.read_zipper_at_path(&q).val_count() != 0 { - out.set_val_at(q, ()); - } - } - out -} fn head(a: &M) -> M { let mut out = M::new(); for (p, _) in a.iter() { @@ -146,14 +140,14 @@ fn divergence_rec(a: &M, b: &M) -> M { out.join(&wrap(&p, &divergence_rec(&unwrap(a, &p), &unwrap(b, &p)))) }) } -fn live_rec(p: &M, a: &M) -> M { +fn retain_rec(p: &M, a: &M) -> M { let root = if p.get([]).is_some() && !a.is_empty() { e() } else { M::new() }; head(p).meet(&head(a)).iter().fold(root, |out, (q, _)| { - out.join(&wrap(&q, &live_rec(&unwrap(p, &q), &unwrap(a, &q)))) + out.join(&wrap(&q, &retain_rec(&unwrap(p, &q), &unwrap(a, &q)))) }) } fn overlaps(a: &M, b: &M, x: &M, y: &M) -> M { @@ -191,7 +185,166 @@ impl Coverage { self.0.insert(name); } } +fn retention_laws(t: &mut Coverage, a: &M, b: &M, c: &M, f: &M) { + let zero = M::new(); + let same = |a: M, b: M| assert_eq!(set_from_map(&a), set_from_map(&b)); + same(cm(a, b), retain(&a.meet(b), &hull(a).meet(&hull(b)))); + same(cs(a, b), retain(a, &hull(a).subtract(b))); + same(cm(a, b).restrict(c), cm(&a.restrict(c), &b.restrict(c))); + same(cs(a, b).restrict(c), cs(&a.restrict(c), b)); + same(cs(a, b).restrict(c), cs(&a.restrict(c), &b.restrict(c))); + let tips = hull(a).meet(c); + let other_tips = hull(b).meet(f); + same( + cm(&retain(a, &tips), b), + retain(&a.meet(b), &tips.meet(&hull(b))), + ); + same( + cm(&retain(a, &tips), &retain(b, &other_tips)), + retain(&a.meet(b), &tips.meet(&other_tips)), + ); + same(cs(&retain(a, &tips), b), retain(a, &tips.subtract(b))); + same(cm(a, &retain(a, &tips)), retain(a, &tips)); + t.eq("retain_empty_left", &retain(&zero, a), &zero); + t.eq("retain_empty_right", &retain(a, &zero), &zero); + t.eq("retain_self", &retain(a, a), a); + t.eq( + "retain_union_left", + &retain(&a.join(b), c), + &retain(a, c).join(&retain(b, c)), + ); + t.eq( + "retain_inter_left", + &retain(&a.meet(b), c), + &retain(a, c).meet(&retain(b, c)), + ); + t.eq( + "retain_diff_left", + &retain(&a.subtract(b), c), + &retain(a, c).subtract(&retain(b, c)), + ); + t.eq( + "retain_symDiff_left", + &retain(&sym(a, b), c), + &sym(&retain(a, c), &retain(b, c)), + ); + t.eq( + "retain_union_right", + &retain(a, &b.join(c)), + &retain(a, b).join(&retain(a, c)), + ); + t.eq( + "retain_filter_inter", + &retain(&retain(a, b), c), + &retain(a, b).meet(&retain(a, c)), + ); + t.eq( + "retain_filter_comm", + &retain(&retain(a, b), c), + &retain(&retain(a, c), b), + ); + t.eq( + "retain_filter_idem", + &retain(&retain(a, b), b), + &retain(a, b), + ); + t.eq("retain_hull_mask", &retain(a, &hull(b)), &retain(a, b)); + t.eq( + "retain_completion_mask", + &retain(a, &completion(b)), + &retain(a, b), + ); + t.eq( + "retain_restrict_witnesses", + &retain(a, &b.restrict(a)), + &retain(a, b), + ); + t.eq( + "restrict_retain_mask", + &a.restrict(&retain(b, a)), + &a.restrict(b), + ); + t.eq("retain_restrict_disjoint", &retain(a, &raff(b, a)), &zero); + t.eq( + "retain_restrict_source", + &retain(&a.restrict(b), c), + &retain(a, c).restrict(b), + ); + t.eq( + "retain_raffinate_source", + &retain(&raff(a, b), c), + &raff(&retain(a, c), b), + ); + t.eq( + "retain_lcp_masks", + &retain(&retain(a, b), c), + &retain(a, &lcp_product(b, c)), + ); + t.eq( + "retain_divergence_masks", + &retain(&retain(a, b), c), + &retain(a, &d(b, c).join(&retain(b, c)).join(&retain(c, b))), + ); + t.eq( + "restrict_overlap_masks", + &a.restrict(b).restrict(c), + &a.restrict(&b.restrict(c).join(&c.restrict(b))), + ); + t.eq( + "retain_restrict_mask", + &retain(a, &b.restrict(c)), + &retain(a, b).restrict(c).join(&retain(a, &retain(c, b))), + ); + t.eq( + "restrict_retain_lcp", + &a.restrict(&retain(b, c)), + &a.restrict(&lcp_product(a, c).restrict(b)), + ); + t.eq("basis_retain", &basis(&retain(a, b)), &retain(&basis(a), b)); + t.eq("hull_restrict", &hull(&a.restrict(b)), &hull(a).restrict(b)); + t.sub("retain_subset", &retain(a, b), a); + t.sub( + "retain_inter_right_bound", + &retain(a, &b.meet(c)), + &retain(a, b).meet(&retain(a, c)), + ); + t.sub( + "retain_diff_right_bound", + &retain(a, b).subtract(&retain(a, c)), + &retain(a, &b.subtract(c)), + ); + t.sub( + "retain_nested_bound", + &retain(a, &retain(b, c)), + &retain(&retain(a, b), c), + ); + t.sub( + "retain_hull_source_bound", + &retain(&hull(a), b), + &hull(&retain(a, b)), + ); + t.sub( + "divergence_retain_bound", + &d(&retain(a, c), &retain(b, f)), + &d(a, b).meet(&d(c, f)), + ); + t.sub( + "branches_retain_bound", + &br(&retain(a, b)), + &br(a).meet(&br(b)), + ); + t.check( + "retain_empty_duality", + retain(a, b).is_empty() == b.restrict(a).is_empty(), + ); + t.check( + "retain_identity", + (set_from_map(&retain(a, b)) == set_from_map(a)) == covers(a, b), + ); + t.check("retain_count_bound", count(&retain(a, b)) <= count(a)); +} fn laws(t: &mut Coverage, a: &M, b: &M, c: &M, f: &M) { + retention_laws(t, a, b, c, f); let x = d(a, b); let ba = br(a); let ha = hull(a); @@ -278,7 +431,7 @@ fn laws(t: &mut Coverage, a: &M, b: &M, c: &M, f: &M) { t.sub("output_heads", &head(&x), &head(a).meet(&head(b))); t.sub("tails_bound", &tails(&x), &d(&tails(a), &tails(b))); t.eq("recursive_divergence", &divergence_rec(a, b), &x); - t.eq("live_recursive", &live_rec(a, b), &live(a, b)); + t.eq("retain_recursive", &retain_rec(a, b), &retain(a, b)); t.check( "output_cardinality", count(&x) <= count(&hull(&a.join(b))).saturating_sub(1), @@ -294,7 +447,11 @@ fn laws(t: &mut Coverage, a: &M, b: &M, c: &M, f: &M) { t.eq("fork_completion", &br(&product(a, &fork)), &ca); let m = lcp_product(a, b); t.eq("fork_lcp", &d(&product(a, &fork), &product(b, &fork)), &m); - t.eq("lcp_correction", &m, &x.join(&live(a, b)).join(&live(b, a))); + t.eq( + "lcp_correction", + &m, + &x.join(&retain(a, b)).join(&retain(b, a)), + ); t.eq("lcp_diagonal", &lcp_product(a, a), &ca); t.eq("lcp_symmetry", &m, &lcp_product(b, a)); t.eq("lcp_output_completion", &completion(&m), &m); @@ -357,12 +514,12 @@ fn laws(t: &mut Coverage, a: &M, b: &M, c: &M, f: &M) { t.eq( "one_mask", &d(&a.restrict(c), b), - &x.restrict(c).join(&d(&live(c, a), b)), + &x.restrict(c).join(&d(&retain(c, a), b)), ); t.eq( "same_mask", &d(&a.restrict(c), &b.restrict(c)), - &x.restrict(c).join(&d(&live(c, a), &live(c, b))), + &x.restrict(c).join(&d(&retain(c, a), &retain(c, b))), ); t.eq( "filter_partition", @@ -396,9 +553,9 @@ fn laws(t: &mut Coverage, a: &M, b: &M, c: &M, f: &M) { &d(&a.restrict(c), &b.restrict(f)), &x.restrict(c) .restrict(f) - .join(&d(a, &live(f, b)).restrict(c)) - .join(&d(&live(c, a), b).restrict(f)) - .join(&d(&live(c, a), &live(f, b))), + .join(&d(a, &retain(f, b)).restrict(c)) + .join(&d(&retain(c, a), b).restrict(f)) + .join(&d(&retain(c, a), &retain(f, b))), ); t.sub( "raffination_bound", From df1afcf56d9934a8bf9a126a9c4ec58aba4aea9b Mon Sep 17 00:00:00 2001 From: adamv-symbolica Date: Tue, 17 Nov 2026 15:03:49 +0000 Subject: [PATCH 06/15] Prove branch closure and closed divergence algebra --- lean/PathMapModel.lean | 1 + lean/PathMapModel/Closed.lean | 252 +++++++++++++++++++++++ lean/PathMapModel/ClosedChecks.lean | 74 +++++++ lean/PathMapModel/ClosedGeometry.lean | 151 ++++++++++++++ lean/PathMapModel/ClosedOperators.lean | 261 +++++++++++++++++++++++ lean/PathMapModel/PathSetLaws.lean | 62 +++++- tests/support/path_set_laws.rs | 273 +++++++++++++++++++++++++ 7 files changed, 1073 insertions(+), 1 deletion(-) create mode 100644 lean/PathMapModel/Closed.lean create mode 100644 lean/PathMapModel/ClosedChecks.lean create mode 100644 lean/PathMapModel/ClosedGeometry.lean create mode 100644 lean/PathMapModel/ClosedOperators.lean diff --git a/lean/PathMapModel.lean b/lean/PathMapModel.lean index 18665a61..e97c39e0 100644 --- a/lean/PathMapModel.lean +++ b/lean/PathMapModel.lean @@ -14,3 +14,4 @@ import PathMapModel.PathSetChecks import PathMapModel.PathSetCertificates import PathMapModel.ConvexMap import PathMapModel.RetainChecks +import PathMapModel.ClosedChecks diff --git a/lean/PathMapModel/Closed.lean b/lean/PathMapModel/Closed.lean new file mode 100644 index 00000000..24270100 --- /dev/null +++ b/lean/PathMapModel/Closed.lean @@ -0,0 +1,252 @@ +import PathMapModel.RetainConvex + +/-! Branch closure and the closed version of divergence. Equalities are extensional: +`completion A = A ∪ branches A = lcpProduct A A`, and `lcpProduct A B` adds +both comparable-path contributions to divergence. Closure never adds an arbitrary prefix. -/ +namespace PathMapModel.PathSpace + +/-- Closed under longest common prefixes, equivalently under branch points. -/ +def IsClosed (a : PathSpace) : Prop := ∀ x ∈ a, ∀ y ∈ a, Path.lcp x y ∈ a + +@[simp] theorem mem_completion (a : PathSpace) (p : Path) : + p ∈ completion a ↔ p ∈ a ∨ p ∈ branches a := by simp [completion, union] + +theorem completion_extensive (a : PathSpace) : Included a (completion a) := + fun p hp => (mem_completion a p).mpr (Or.inl hp) + +theorem lcp_congr {a b c d : PathSpace} (h : Same a c) (k : Same b d) : + Same (lcpProduct a b) (lcpProduct c d) := by + intro p; simp only [mem_lcpProduct, h, k] + +theorem lcp_mono {a b c d : PathSpace} (h : Included a c) (k : Included b d) : + Included (lcpProduct a b) (lcpProduct c d) := by + intro p hp; obtain ⟨x,hx,y,hy,he⟩ := (mem_lcpProduct _ _ _).mp hp + exact (mem_lcpProduct _ _ _).mpr ⟨x,h x hx,y,k y hy,he⟩ + +theorem completion_mono {a b : PathSpace} (h : Included a b) : + Included (completion a) (completion b) := by + intro p hp + exact (lcp_diagonal b p).mp (lcp_mono h h p ((lcp_diagonal a p).mpr hp)) + +theorem completion_congr {a b : PathSpace} (h : Same a b) : Same (completion a) (completion b) := by + intro p; rw [← lcp_diagonal, ← lcp_diagonal]; exact lcp_congr h h p + +theorem closed_iff_completion (a : PathSpace) : IsClosed a ↔ Same (completion a) a := by + constructor + · intro h p; constructor + · intro hp; obtain ⟨x,hx,y,hy,rfl⟩ := (mem_lcpProduct _ _ _).mp ((lcp_diagonal a p).mpr hp) + exact h x hx y hy + · exact completion_extensive a p + · intro h x hx y hy + exact (h _).mp ((lcp_diagonal a _).mp ((mem_lcpProduct _ _ _).mpr ⟨x,hx,y,hy,rfl⟩)) + +theorem closed_iff_branches (a : PathSpace) : IsClosed a ↔ Included (branches a) a := by + rw [closed_iff_completion]; simp only [Same, Included, mem_completion]; grind + +theorem closed_congr {a b : PathSpace} (h : Same a b) : IsClosed a ↔ IsClosed b := by + simp only [IsClosed, h] + +theorem closed_completion (a : PathSpace) : IsClosed (completion a) := + (closed_iff_completion _).mpr (completion_idempotent a) + +theorem closed_lcp (a b : PathSpace) : IsClosed (lcpProduct a b) := + (closed_iff_completion _).mpr (lcp_output_completion a b) + +theorem closed_divergence (a b : PathSpace) : IsClosed (divergence a b) := + (closed_iff_completion _).mpr (divergence_output_completion a b) + +theorem closed_branches (a : PathSpace) : IsClosed (branches a) := closed_divergence a a + +theorem closed_empty : IsClosed [] := by simp [IsClosed] + +theorem closed_singleton (p : Path) : IsClosed [p] := by simp [IsClosed] + +/-- The reflection into closed spaces: closure is the least closed superset. -/ +theorem completion_least {a b : PathSpace} (hb : IsClosed b) : + Included (completion a) b ↔ Included a b := by + constructor + · intro h p hp; exact h p (completion_extensive a p hp) + · intro h p hp; exact ((closed_iff_completion b).mp hb p).mp (completion_mono h p hp) + +theorem completion_empty : Same (completion []) [] := (closed_iff_completion _).mp closed_empty + +theorem completion_singleton (p : Path) : Same (completion [p]) [p] := + (closed_iff_completion _).mp (closed_singleton p) + +theorem closed_inter {a b : PathSpace} (ha : IsClosed a) (hb : IsClosed b) : IsClosed (inter a b) := by + intro x hx y hy + obtain ⟨hxa,hxb⟩ := (mem_inter _ _ _).mp hx + obtain ⟨hya,hyb⟩ := (mem_inter _ _ _).mp hy + exact (mem_inter _ _ _).mpr ⟨ha x hxa y hya,hb x hxb y hyb⟩ + +theorem completion_inter_bound (a b : PathSpace) : + Included (completion (inter a b)) (inter (completion a) (completion b)) := by + intro p hp; apply (mem_inter _ _ _).mpr + exact ⟨completion_mono (fun q hq => ((mem_inter _ _ q).mp hq).1) p hp, + completion_mono (fun q hq => ((mem_inter _ _ q).mp hq).2) p hp⟩ + +theorem completion_union (a b : PathSpace) : + Same (completion (union a b)) (union (union (completion a) (completion b)) (divergence a b)) := by + intro p; simp only [mem_completion] + rw [branches_union] + simp only [union, List.mem_append, mem_completion]; grind + +theorem completion_union_lcp (a b : PathSpace) : + Same (completion (union a b)) (union (union (completion a) (completion b)) (lcpProduct a b)) := by + intro p; rw [completion_union] + simp only [union, List.mem_append, lcp_correction, mem_retain, mem_completion]; grind + +theorem completion_union_absorb (a b : PathSpace) : + Same (completion (union (completion a) (completion b))) (completion (union a b)) := by + intro p; rw [completion_union, completion_union] + simp only [union, List.mem_append, completion_idempotent, divergence_completion] + +/-- Union of closed operands is closed precisely when it contains their divergences. -/ +theorem closed_union_iff {a b : PathSpace} (ha : IsClosed a) (hb : IsClosed b) : + IsClosed (union a b) ↔ Included (divergence a b) (union a b) := by + rw [closed_iff_completion] + have hca := (closed_iff_completion a).mp ha + have hcb := (closed_iff_completion b).mp hb + simp only [Same, Included] + simp only [completion_union] + simp only [union, List.mem_append, hca, hcb]; grind + +/-- Every closure member has a witness pair; no iterative saturation is needed. -/ +theorem completion_pair_witness (a : PathSpace) (p : Path) : + p ∈ completion a ↔ ∃ x ∈ a, ∃ y ∈ a, Path.lcp x y = p := + (lcp_diagonal a p).symm.trans (mem_lcpProduct a a p) + +theorem closed_range_lcp (a : PathSpace) : IsClosed a ↔ ∃ b c, Same a (lcpProduct b c) := by + constructor + · intro h; exact ⟨a,a,fun p => ((closed_iff_completion a).mp h p).symm.trans (lcp_diagonal a p).symm⟩ + · rintro ⟨b,c,h⟩; exact (closed_congr h).mpr (closed_lcp b c) + +theorem closed_range_branches (a : PathSpace) : IsClosed a ↔ ∃ b, Same a (branches b) := by + constructor + · intro h; exact ⟨product a [[0],[1]],fun p => + ((closed_iff_completion a).mp h p).symm.trans (fork_completion a p).symm⟩ + · rintro ⟨b,h⟩; exact (closed_congr h).mpr (closed_branches b) + +theorem closed_range_divergence (a : PathSpace) : IsClosed a ↔ ∃ b c, Same a (divergence b c) := by + constructor + · intro h; obtain ⟨b,hb⟩ := (closed_range_branches a).mp h; exact ⟨b,b,hb⟩ + · rintro ⟨b,c,h⟩; exact (closed_congr h).mpr (closed_divergence b c) + +theorem lcp_empty_left (a : PathSpace) : Same (lcpProduct [] a) [] := by simp [Same, lcpProduct] + +theorem lcp_empty_right (a : PathSpace) : Same (lcpProduct a []) [] := by simp [Same, lcpProduct] + +theorem lcp_inter_lower (a b : PathSpace) : Included (inter a b) (lcpProduct a b) := by + intro p hp; obtain ⟨ha,hb⟩ := (mem_inter _ _ _).mp hp + exact (mem_lcpProduct _ _ _).mpr ⟨p,ha,p,hb,Path.lcp_self p⟩ + +theorem lcp_union_right (a b c : PathSpace) : + Same (lcpProduct a (union b c)) (union (lcpProduct a b) (lcpProduct a c)) := by + intro p; simp only [mem_lcpProduct, union, List.mem_append]; grind + +/-- Closing either input does not change the closed divergence product. -/ +theorem lcp_completion_left (a b : PathSpace) : + Same (lcpProduct (completion a) b) (lcpProduct a b) := by + intro p; constructor + · intro hp + obtain ⟨xy,hxy,z,hz,rfl⟩ := (mem_lcpProduct _ _ _).mp hp + obtain ⟨x,hx,y,hy,rfl⟩ := (completion_pair_witness a xy).mp hxy + have hxz := (mem_lcpProduct a b _).mpr ⟨x,hx,z,hz,rfl⟩ + have hyz := (mem_lcpProduct a b _).mpr ⟨y,hy,z,hz,rfl⟩ + have he : Path.lcp (Path.lcp x z) (Path.lcp y z) = Path.lcp (Path.lcp x y) z := by + have h := Path.prefix_self (Path.lcp (Path.lcp x z) (Path.lcp y z)) + have k := Path.prefix_self (Path.lcp (Path.lcp x y) z) + apply Path.prefix_antisymm <;> simp only [Path.prefix_lcp] at h k ⊢ <;> grind + exact he ▸ closed_lcp a b _ hxz _ hyz + · exact lcp_mono (completion_extensive a) (fun _ h => h) p + +theorem lcp_completion_right (a b : PathSpace) : + Same (lcpProduct a (completion b)) (lcpProduct a b) := by + intro p; rw [lcp_symmetry, lcp_completion_left, lcp_symmetry] + +theorem lcp_completion (a b : PathSpace) : + Same (lcpProduct (completion a) (completion b)) (lcpProduct a b) := by + intro p; rw [lcp_completion_left, lcp_completion_right] + +theorem lcp_repeat (a b : PathSpace) : Same (lcpProduct a (lcpProduct a b)) (lcpProduct a b) := by + intro p; rw [← lcp_associativity] + exact (lcp_congr (lcp_diagonal a) (fun _ => Iff.rfl) p).trans (lcp_completion_left a b p) + +theorem lcp_medial (a b c d : PathSpace) : + Same (lcpProduct (lcpProduct a b) (lcpProduct c d)) (lcpProduct (lcpProduct a c) (lcpProduct b d)) := by + intro p + calc + _ ↔ p ∈ lcpProduct a (lcpProduct b (lcpProduct c d)) := lcp_associativity _ _ _ p + _ ↔ p ∈ lcpProduct a (lcpProduct (lcpProduct b c) d) := + lcp_congr (fun _ => Iff.rfl) (fun q => (lcp_associativity b c d q).symm) p + _ ↔ p ∈ lcpProduct a (lcpProduct (lcpProduct c b) d) := + lcp_congr (fun _ => Iff.rfl) (lcp_congr (lcp_symmetry b c) (fun _ => Iff.rfl)) p + _ ↔ p ∈ lcpProduct a (lcpProduct c (lcpProduct b d)) := + lcp_congr (fun _ => Iff.rfl) (lcp_associativity c b d) p + _ ↔ _ := (lcp_associativity a c _ p).symm + +theorem lcp_four_factors (a b c d : PathSpace) : + Same (lcpProduct (union a b) (union c d)) + (union (union (lcpProduct a c) (lcpProduct a d)) (union (lcpProduct b c) (lcpProduct b d))) := by + intro p; simp only [mem_lcpProduct] + simp only [union, List.mem_append, mem_lcpProduct]; grind + +theorem lcp_closed_join (a b c : PathSpace) : + Same (lcpProduct a (completion (union b c))) (union (lcpProduct a b) (lcpProduct a c)) := by + intro p; rw [lcp_completion_right, lcp_union_right] + +theorem closed_lcp_union (a b c : PathSpace) : IsClosed (union (lcpProduct a b) (lcpProduct a c)) := + (closed_congr (lcp_union_right a b c)).mp (closed_lcp a (union b c)) + +/-- Closed union is the least upper bound for inclusion. Its meet is intersection. -/ +theorem closed_join_least {a b c : PathSpace} (hc : IsClosed c) : + Included (completion (union a b)) c ↔ Included a c ∧ Included b c := by + rw [completion_least hc]; simp only [Included, union, List.mem_append]; grind + +theorem closed_join_assoc (a b c : PathSpace) : + Same (completion (union (completion (union a b)) c)) (completion (union a (completion (union b c)))) := by + have left : Same (union (union a b) c) (union a (union b c)) := by + intro p; simp only [union, List.mem_append]; grind + have absorb (x y : PathSpace) : Same (completion (union (completion x) y)) (completion (union x y)) := by + intro p; rw [completion_union, completion_union] + simp only [union, List.mem_append, completion_idempotent, divergence_completion_left] + have right (x y : PathSpace) : Same (completion (union x (completion y))) (completion (union x y)) := by + intro p; rw [completion_union, completion_union] + have hd := divergence_completion_left y x p + simp only [divergence_comm y x, divergence_comm (completion y) x] at hd + simp only [union, List.mem_append, completion_idempotent, hd] + exact fun p => (absorb _ _ p).trans ((completion_congr left p).trans (right _ _ p).symm) + +theorem closed_join_absorption {a : PathSpace} (ha : IsClosed a) (b : PathSpace) : + Same (completion (union a (inter a b))) a := by + have h : Same (union a (inter a b)) a := by + intro p; simp only [union, List.mem_append, mem_inter]; grind + exact fun p => (completion_congr h p).trans ((closed_iff_completion a).mp ha p) + +theorem closed_meet_absorption (a b : PathSpace) : Same (inter a (completion (union a b))) a := by + intro p; rw [mem_inter] + exact ⟨And.left,fun hp => ⟨hp,completion_extensive _ p (List.mem_append_left _ hp)⟩⟩ + +/-- A newly forced path is a proper prefix of the newly inserted witness. -/ +theorem completion_insert_new {a : PathSpace} {x y : Path} + (hx : x ∉ completion a) (hne : x ≠ y) (h : x ∈ completion (union a [y])) : + (x ≼ y) = true ∧ x.length < y.length := by + rw [completion_union] at h + simp only [union, List.mem_append, completion_singleton, List.mem_singleton] at h + rcases h with (h | h) | h + · exact False.elim (hx h) + · exact False.elim (hne h) + · obtain ⟨u,_,v,hv,hd⟩ := (mem_divergence _ _ _).mp h + simp only [List.mem_singleton] at hv; subst v + exact ⟨Path.divergence_prefix_left ((Path.divergence_comm _ _).trans hd),Path.divergence_length_right hd⟩ + +/-- Distinct new marks cannot force each other, even before the base space is closed. -/ +theorem completion_anti_exchange {a : PathSpace} {x y : Path} + (hx : x ∉ completion a) (hy : y ∉ completion a) (hne : x ≠ y) + (h : x ∈ completion (union a [y])) : y ∉ completion (union a [x]) := by + intro k + have hxy := (completion_insert_new hx hne h).2 + have hyx := (completion_insert_new hy hne.symm k).2 + omega + +end PathMapModel.PathSpace diff --git a/lean/PathMapModel/ClosedChecks.lean b/lean/PathMapModel/ClosedChecks.lean new file mode 100644 index 00000000..3daedc60 --- /dev/null +++ b/lean/PathMapModel/ClosedChecks.lean @@ -0,0 +1,74 @@ +import PathMapModel.ClosedOperators + +/-! Kernel-checked counterexamples delimit the closed algebra. The explicit closure +checks in the lattice examples prevent failures from being blamed on unclosed inputs. -/ +namespace PathMapModel.PathSpace + +theorem completion_not_union_preserving : + equiv (completion (union [[0]] [[1]])) (union (completion [[0]]) (completion [[1]])) = false := by decide + +theorem completion_not_inter_preserving : + equiv (completion (inter [[]] [[0],[1]])) (inter (completion [[]]) (completion [[0],[1]])) = false := by decide + +theorem completion_retain_bound_strict : + equiv (completion (retain [[0],[1]] [[]])) (retain (completion [[0],[1]]) [[]]) = false := by decide + +theorem completion_raffinate_bound_strict : + equiv (completion (raffinate [[0],[1]] [[0]])) (raffinate (completion [[0],[1]]) [[0]]) = false := by decide + +theorem completion_convexMeet_bound_strict : + equiv (completion (convexMeet [[],[0]] [[0],[1]])) + (convexMeet (completion [[],[0]]) (completion [[0],[1]])) = false := by decide + +theorem completion_convexSubtract_bound_strict : + equiv (completion (convexSubtract [[0],[1]] [[0]])) + (convexSubtract (completion [[0],[1]]) [[0]]) = false := by decide + +theorem closed_restrict_needs_closed_mask : + equiv (completion [[],[0],[1]]) [[],[0],[1]] = true ∧ + equiv (completion (restrict [[],[0],[1]] [[0],[1]])) (restrict [[],[0],[1]] [[0],[1]]) = false := by decide + +theorem lcp_not_intersection : + equiv (lcpProduct [[]] [[0]]) (inter [[]] [[0]]) = false := by decide + +theorem lcp_not_lattice_absorption : + equiv (lcpProduct [[0]] (completion (union [[0]] [[]]))) [[0]] = false := by decide + +theorem lcp_inter_bound_strict : + equiv (lcpProduct [[]] (inter [[]] [[0]])) (inter (lcpProduct [[]] [[]]) (lcpProduct [[]] [[0]])) = false := by decide + +theorem closed_lattice_not_distributive : + let a : PathSpace := [[]]; let b := [[0]]; let c := [[1]] + equiv (completion a) a = true ∧ equiv (completion b) b = true ∧ equiv (completion c) c = true ∧ + equiv (inter a (completion (union b c))) (completion (union (inter a b) (inter a c))) = false := by decide + +theorem closed_lattice_not_modular : + let a : PathSpace := [[0]]; let b := [[1]]; let c := [[],[0]] + equiv (completion a) a = true ∧ equiv (completion b) b = true ∧ equiv (completion c) c = true ∧ + subset a c = true ∧ + equiv (completion (union a (inter b c))) (inter (completion (union a b)) c) = false := by decide + +theorem lcp_retain_bound_strict : + equiv (lcpProduct (retain [[]] [[]]) (retain [[0]] [[]])) + (retain (lcpProduct [[]] [[0]]) (lcpProduct [[]] [[]])) = false := by decide + +theorem completion_not_determined_by_hull : + equiv (hull [[0]]) (hull [[],[0]]) = true ∧ + equiv (completion [[0]]) (completion [[],[0]]) = false := by decide + +/-- L closes the divergence operation by including comparable pairs; completing +its strict-divergence output alone cannot recover those pairs. -/ +theorem lcp_not_completed_divergence : + equiv (completion (divergence [[]] [[]])) (lcpProduct [[]] [[]]) = false := by decide + +theorem lcpLE_not_inclusion : + equiv (lcpProduct [[]] [[0]]) [[]] = true ∧ subset [[]] [[0]] = false := by decide + +theorem lcpLE_not_coverage : + covers [[0]] [[],[0]] = true ∧ equiv (lcpProduct [[0]] [[],[0]]) [[0]] = false := by decide + +theorem closure_does_not_add_intermediate_prefixes : + equiv (completion [[0,0],[0,1]]) [[0],[0,0],[0,1]] = true ∧ + ([] : Path) ∉ completion [[0,0],[0,1]] := by decide + +end PathMapModel.PathSpace diff --git a/lean/PathMapModel/ClosedGeometry.lean b/lean/PathMapModel/ClosedGeometry.lean new file mode 100644 index 00000000..0bf82429 --- /dev/null +++ b/lean/PathMapModel/ClosedGeometry.lean @@ -0,0 +1,151 @@ +import PathMapModel.Closed + +namespace PathMapModel.PathSpace + +theorem completion_covered {a : PathSpace} {p : Path} (h : p ∈ completion a) : + ∃ q ∈ a, (p ≼ q) = true := by + rcases (mem_completion a p).mp h with h | h + · exact ⟨p,h,Path.prefix_self p⟩ + · exact divergence_output_covered h + +theorem hull_completion (a : PathSpace) : Same (hull (completion a)) (hull a) := + hull_cofinal (completion_extensive a) (fun _ h => completion_covered h) + +theorem completion_hull (a : PathSpace) : + Same (union a (completion (hull a))) (completion a) := by + intro p + simp only [union, List.mem_append, mem_completion, branch_hull] + have hs : p ∈ hull a → p ∈ a := hull_subset a + grind + +theorem closed_basis_prefix {a : PathSpace} (ha : IsClosed a) {p : Path} (hp : p ∈ basis a) : + ∀ q ∈ a, (p ≼ q) = true := by + intro q hq + have hm := (mem_basis a p).mp hp + have hl := ha p hm.1 q hq + have he : Path.lcp p q = p := by + by_cases he : Path.lcp p q = p + · exact he + · have hf := hm.2 _ hl he + have ht := Path.lcp_prefix_left p q + simp [ht] at hf + simpa only [he] using Path.lcp_prefix_right p q + +/-- A nonempty closed space has exactly one basis path, its common prefix. -/ +theorem basis_closed {a : PathSpace} (ha : IsClosed a) (hn : a ≠ []) : + Same (basis a) [commonPrefix a] := by + have eqroot : ∀ p ∈ basis a, p = commonPrefix a := by + intro p hp + apply Path.prefix_antisymm + · exact (commonPrefix_spec a hn p).mpr (closed_basis_prefix ha hp) + · exact ((commonPrefix_spec a hn _).mp (Path.prefix_self _)) p (basis_subset a hp) + intro p; simp only [List.mem_singleton]; constructor + · exact eqroot p + · intro he + obtain ⟨q,hq,_⟩ := height_attained (fun hh => hn ((basis_nonempty a).mp hh)) + exact ((eqroot q hq).trans he.symm) ▸ hq + +theorem commonPrefix_completion {a : PathSpace} (hn : a ≠ []) : + commonPrefix (completion a) = commonPrefix a := by + have hc : completion a ≠ [] := by + intro h; apply hn; apply List.eq_nil_iff_forall_not_mem.mpr + intro p hp; have hh := completion_extensive a p hp; simp [h] at hh + apply Path.prefix_antisymm + · apply (commonPrefix_spec a hn _).mpr + intro p hp; exact ((commonPrefix_spec _ hc _).mp (Path.prefix_self _)) p (completion_extensive a p hp) + · apply (commonPrefix_spec _ hc _).mpr + intro p hp + obtain ⟨x,hx,y,hy,rfl⟩ := (completion_pair_witness a p).mp hp + have h := (commonPrefix_spec a hn _).mp (Path.prefix_self (commonPrefix a)) + exact (Path.prefix_lcp _ _ _).mpr ⟨h x hx,h y hy⟩ + +theorem basis_completion {a : PathSpace} (hn : a ≠ []) : + Same (basis (completion a)) [commonPrefix a] := by + have hc : completion a ≠ [] := by + intro h; apply hn; apply List.eq_nil_iff_forall_not_mem.mpr + intro p hp; have hh := completion_extensive a p hp; simp [h] at hh + simpa only [commonPrefix_completion hn] using basis_closed (closed_completion a) hc + +theorem hull_not_branch {a : PathSpace} {p : Path} (hp : p ∈ hull a) : p ∉ branches a := by + intro hb + obtain ⟨x,hx,y,_,hd⟩ := (mem_divergence _ _ _).mp hb + have he := hull_max hp hx (Path.divergence_prefix_left hd) + have hl := Path.divergence_length_left hd + rw [he] at hl; omega + +/-- Removing already generated branch marks preserves all tips. -/ +theorem hull_remove_branches (a : PathSpace) : Same (hull (diff a (branches a))) (hull a) := by + have h : Same (hull a) (hull (diff a (branches a))) := by + apply hull_cofinal + · intro p hp; exact ((mem_diff _ _ _).mp hp).1 + · intro p hp + obtain ⟨q,hq,hpq⟩ := hull_covers hp + exact ⟨q,(mem_diff _ _ _).mpr ⟨hull_subset a hq,hull_not_branch hq⟩,hpq⟩ + exact fun p => (h p).symm + +theorem branches_remove_branches (a : PathSpace) : Same (branches (diff a (branches a))) (branches a) := by + intro p + exact (branch_hull _ p).symm.trans + ((divergence_congr (hull_remove_branches a) (hull_remove_branches a) p).trans (branch_hull a p)) + +theorem completion_remove_branches (a : PathSpace) : + Same (completion (diff a (branches a))) (completion a) := by + intro p; simp only [mem_completion, mem_diff, branches_remove_branches]; grind + +theorem completion_diff_branches (a : PathSpace) : + Same (diff (completion a) (branches a)) (diff a (branches a)) := by + intro p; simp only [mem_diff, mem_completion]; grind + +/-- The unique least generating set consists of the marks that are not branch points. -/ +theorem completion_generators (a b : PathSpace) : + Same (completion b) (completion a) ↔ + Included (diff a (branches a)) b ∧ Included b (completion a) := by + constructor + · intro h; constructor + · intro p hp + obtain ⟨ha,hn⟩ := (mem_diff _ _ _).mp hp + have hc := (h p).mpr (completion_extensive a p ha) + rcases (mem_completion b p).mp hc with hb | hb + · exact hb + · have he : Same (branches b) (branches a) := fun q => (branch_completion b q).symm.trans + ((divergence_congr h h q).trans (branch_completion a q)) + exact False.elim (hn ((he p).mp hb)) + · intro p hp; exact (h p).mp (completion_extensive b p hp) + · rintro ⟨h,k⟩; intro p; constructor + · exact ((completion_least (closed_completion a)).mpr k) p + · intro hp + exact completion_mono h p ((completion_remove_branches a p).mpr hp) + +theorem completion_equiv_generators (a b : PathSpace) : + Same (completion a) (completion b) ↔ Same (diff a (branches a)) (diff b (branches b)) := by + constructor + · intro h p + have hb : Same (branches a) (branches b) := fun q => (branch_completion a q).symm.trans + ((divergence_congr h h q).trans (branch_completion b q)) + exact (completion_diff_branches a p).symm.trans + ((by simp only [mem_diff, h, hb] : p ∈ diff (completion a) (branches a) ↔ + p ∈ diff (completion b) (branches b)).trans (completion_diff_branches b p)) + · intro h p + exact (completion_remove_branches a p).symm.trans + ((completion_congr h p).trans (completion_remove_branches b p)) + +theorem completion_cardinality (a : PathSpace) : + count (completion a) ≤ count a + (count (hull a) - 1) := by + have h := count_union_le a (branches a) + have hb := branch_count (hull a) + have he := count_congr (branch_hull a) + change count (union a (branches a)) ≤ _ + omega + +/-- Closure removes no paths and adds at most one fewer branch point than there are tips. -/ +theorem completion_cardinality_linear (a : PathSpace) : + count a ≤ count (completion a) ∧ count (completion a) ≤ 2 * count a - 1 := by + have h := completion_cardinality a + have hk := count_mono (fun _ hp => hull_subset a hp) + have hl := count_mono (completion_extensive a) + by_cases hz : count a = 0 + · have he := (count_eq_zero a).mp hz + subst a; simp [count, completion, union, branches, divergence] + · omega + +end PathMapModel.PathSpace diff --git a/lean/PathMapModel/ClosedOperators.lean b/lean/PathMapModel/ClosedOperators.lean new file mode 100644 index 00000000..57829ec7 --- /dev/null +++ b/lean/PathMapModel/ClosedOperators.lean @@ -0,0 +1,261 @@ +import PathMapModel.ClosedGeometry + +namespace PathMapModel.PathSpace + +theorem closed_retain {a : PathSpace} (ha : IsClosed a) (b : PathSpace) : IsClosed (retain a b) := by + intro x hx y hy + obtain ⟨hx,u,hu,hxu⟩ := (mem_retain _ _ _).mp hx + have hy := ((mem_retain _ _ _).mp hy).1 + exact (mem_retain _ _ _).mpr ⟨ha x hx y hy,u,hu,Path.prefix_trans (Path.lcp_prefix_left x y) hxu⟩ + +theorem closed_raffinate {a : PathSpace} (ha : IsClosed a) (b : PathSpace) : IsClosed (raffinate a b) := by + intro x hx y hy + obtain ⟨hx,hn⟩ := (mem_raffinate _ _ _).mp hx + have hy := ((mem_raffinate _ _ _).mp hy).1 + apply (mem_raffinate _ _ _).mpr + refine ⟨ha x hx y hy,fun q hq => ?_⟩ + cases he : q ≼ Path.lcp x y with + | false => rfl + | true => + have ht := Path.prefix_trans he (Path.lcp_prefix_left x y) + have hf := hn q hq + simp [ht] at hf + +theorem closed_restrict {a b : PathSpace} (ha : IsClosed a) (hb : IsClosed b) : + IsClosed (restrict a b) := by + intro x hx y hy + obtain ⟨hx,u,hu,hux⟩ := (mem_restrict _ _ _).mp hx + obtain ⟨hy,v,hv,hvy⟩ := (mem_restrict _ _ _).mp hy + exact (mem_restrict _ _ _).mpr ⟨ha x hx y hy,Path.lcp u v,hb u hu v hv, + (Path.prefix_lcp _ _ _).mpr ⟨Path.prefix_trans (Path.lcp_prefix_left u v) hux, + Path.prefix_trans (Path.lcp_prefix_right u v) hvy⟩⟩ + +/-- The exact correction when a restriction mask is not closed. -/ +theorem completion_restrict (a b : PathSpace) : + Same (completion (restrict a b)) + (union (restrict (completion a) b) (branches (retain b a))) := by + intro p + have hd := divergence_same_mask a a b p + simp only [mem_completion, branches, hd] + simp only [union, List.mem_append, mem_restrict, mem_completion, branches] + grind + +theorem completion_restrict_closed {b : PathSpace} (hb : IsClosed b) (a : PathSpace) : + Same (completion (restrict a b)) (restrict (completion a) b) := by + intro p; rw [completion_restrict] + simp only [union, List.mem_append] + constructor + · rintro (h | h) + · exact h + · have hc : p ∈ completion (restrict a b) := + (mem_completion _ _).mpr (Or.inr ((divergence_same_mask a a b p).mpr (Or.inr h))) + have ha := completion_mono (fun q hq => ((mem_restrict _ _ q).mp hq).1) p hc + have hp := (closed_iff_branches _).mp (closed_retain hb a) p h + exact (mem_restrict _ _ _).mpr ⟨ha,p,((mem_retain _ _ _).mp hp).1,Path.prefix_self p⟩ + · exact Or.inl + +theorem completion_retain_bound (a b : PathSpace) : + Included (completion (retain a b)) (retain (completion a) b) := + (completion_least (closed_retain (closed_completion a) b)).mpr + (retain_mono (completion_extensive a) (fun _ h => h)) + +theorem completion_raffinate_bound (a b : PathSpace) : + Included (completion (raffinate a b)) (raffinate (completion a) b) := by + apply (completion_least (closed_raffinate (closed_completion a) b)).mpr + intro p hp; obtain ⟨hp,hn⟩ := (mem_raffinate _ _ _).mp hp + exact (mem_raffinate _ _ _).mpr ⟨completion_extensive a p hp,hn⟩ + +theorem closed_convexMeet {a b : PathSpace} (ha : IsClosed a) (hb : IsClosed b) : + IsClosed (convexMeet a b) := closed_retain (closed_inter ha hb) _ + +theorem closed_convexSubtract {a : PathSpace} (ha : IsClosed a) (b : PathSpace) : + IsClosed (convexSubtract a b) := closed_retain ha _ + +theorem completion_convexMeet_bound (a b : PathSpace) : + Included (completion (convexMeet a b)) (convexMeet (completion a) (completion b)) := by + apply (completion_least (closed_convexMeet (closed_completion a) (closed_completion b))).mpr + intro p hp + obtain ⟨ha,hb,t,hta,htb,hpt⟩ := (mem_convexMeet _ _ _).mp hp + exact (mem_convexMeet _ _ _).mpr ⟨completion_extensive a p ha,completion_extensive b p hb, + t,(hull_completion a t).mpr hta,(hull_completion b t).mpr htb,hpt⟩ + +theorem completion_convexSubtract_bound (a b : PathSpace) : + Included (completion (convexSubtract a b)) (convexSubtract (completion a) b) := by + apply (completion_least (closed_convexSubtract (closed_completion a) b)).mpr + intro p hp + obtain ⟨ha,t,ht,hn,hpt⟩ := (mem_convexSubtract _ _ _).mp hp + exact (mem_convexSubtract _ _ _).mpr ⟨completion_extensive a p ha,t,(hull_completion a t).mpr ht,hn,hpt⟩ + +theorem hull_completion_convexMeet (a b : PathSpace) : + Same (hull (completion (convexMeet a b))) (hull (convexMeet (completion a) (completion b))) := by + intro p; simp only [hull_completion, hull_convexMeet, mem_inter] + +theorem hull_completion_convexSubtract (a b : PathSpace) : + Same (hull (completion (convexSubtract a b))) (hull (convexSubtract (completion a) b)) := by + intro p; simp only [hull_completion, hull_convexSubtract, mem_diff] + +theorem lcp_retain_bound (a b c d : PathSpace) : + Included (lcpProduct (retain a c) (retain b d)) (retain (lcpProduct a b) (lcpProduct c d)) := by + intro p hp + obtain ⟨x,hx,y,hy,rfl⟩ := (mem_lcpProduct _ _ _).mp hp + obtain ⟨hx,u,hu,hxu⟩ := (mem_retain _ _ _).mp hx + obtain ⟨hy,v,hv,hyv⟩ := (mem_retain _ _ _).mp hy + exact (mem_retain _ _ _).mpr ⟨(mem_lcpProduct _ _ _).mpr ⟨x,hx,y,hy,rfl⟩, + Path.lcp u v,(mem_lcpProduct _ _ _).mpr ⟨u,hu,v,hv,rfl⟩, + (Path.prefix_lcp _ _ _).mpr ⟨Path.prefix_trans (Path.lcp_prefix_left x y) hxu, + Path.prefix_trans (Path.lcp_prefix_right x y) hyv⟩⟩ + +theorem lcp_inter_bound (a b c : PathSpace) : + Included (lcpProduct (inter a b) c) (inter (lcpProduct a c) (lcpProduct b c)) := by + intro p hp; exact (mem_inter _ _ _).mpr + ⟨lcp_mono (fun q hq => ((mem_inter _ _ q).mp hq).1) (fun _ h => h) p hp, + lcp_mono (fun q hq => ((mem_inter _ _ q).mp hq).2) (fun _ h => h) p hp⟩ + +theorem lcp_diff_bound (a b c : PathSpace) : + Included (diff (lcpProduct a c) (lcpProduct b c)) (lcpProduct (diff a b) c) := by + intro p hp; obtain ⟨hp,hn⟩ := (mem_diff _ _ _).mp hp + obtain ⟨x,hx,y,hy,he⟩ := (mem_lcpProduct _ _ _).mp hp + exact (mem_lcpProduct _ _ _).mpr ⟨x,(mem_diff _ _ _).mpr + ⟨hx,fun hb => hn ((mem_lcpProduct _ _ _).mpr ⟨x,hb,y,hy,he⟩)⟩,y,hy,he⟩ + +/-- All genuinely new output marks are strict divergences. -/ +theorem lcp_new_marks (a b : PathSpace) : + Same (diff (lcpProduct a b) (union a b)) (diff (divergence a b) (union a b)) := by + intro p; simp only [mem_diff, lcp_correction, mem_retain, union, List.mem_append]; grind + +theorem lcp_union_bound (a b : PathSpace) : Included (lcpProduct a b) (completion (union a b)) := by + intro p hp; obtain ⟨x,hx,y,hy,he⟩ := (mem_lcpProduct _ _ _).mp hp + exact (completion_pair_witness _ _).mpr ⟨x,List.mem_append_left _ hx,y,List.mem_append_right _ hy,he⟩ + +theorem retain_lcp_operand (a b : PathSpace) : Same (retain a (lcpProduct a b)) (retain a b) := by + intro p + exact (retain_lcp_masks a a b p).symm.trans (retain_congr (retain_self a) (fun _ => Iff.rfl) p) + +/-- Hulls of L-products are the canonical common retention masks. -/ +theorem hull_lcp_hulls (a b : PathSpace) : + Same (hull (lcpProduct (hull a) (hull b))) (hull (lcpProduct a b)) := by + apply (retain_mask_equiv _ _).mp + intro x p + rw [← retain_lcp_masks, ← retain_lcp_masks] + exact (retain_congr (retain_hull_mask x a) (fun _ => Iff.rfl) p).trans (retain_hull_mask _ b p) + +/-- The L-product has its own semilattice order; this is not ordinary inclusion. -/ +def LcpLE (a b : PathSpace) : Prop := Same (lcpProduct a b) a + +theorem lcpLE_refl_iff (a : PathSpace) : LcpLE a a ↔ IsClosed a := by + simp only [LcpLE, closed_iff_completion, Same, lcp_diagonal] + +theorem lcpLE_closed {a b : PathSpace} (h : LcpLE a b) : IsClosed a := + (closed_congr h).mp (closed_lcp a b) + +theorem lcpLE_antisymm {a b : PathSpace} (h : LcpLE a b) (k : LcpLE b a) : Same a b := + fun p => (h p).symm.trans ((lcp_symmetry a b p).trans (k p)) + +theorem lcpLE_trans {a b c : PathSpace} (h : LcpLE a b) (k : LcpLE b c) : LcpLE a c := by + intro p + exact (lcp_congr (fun q => (h q).symm) (fun _ => Iff.rfl) p).trans + ((lcp_associativity a b c p).trans ((lcp_congr (fun _ => Iff.rfl) k p).trans (h p))) + +theorem lcpLE_product_left (a b : PathSpace) : LcpLE (lcpProduct a b) a := + fun p => (lcp_symmetry _ _ p).trans (lcp_repeat a b p) + +theorem lcpLE_product_right (a b : PathSpace) : LcpLE (lcpProduct a b) b := by + intro p; rw [lcp_associativity] + exact (lcp_congr (fun _ => Iff.rfl) (lcp_diagonal b) p).trans (lcp_completion_right a b p) + +theorem lcpLE_product_iff (x a b : PathSpace) : + LcpLE x (lcpProduct a b) ↔ LcpLE x a ∧ LcpLE x b := by + constructor + · intro h; exact ⟨lcpLE_trans h (lcpLE_product_left a b),lcpLE_trans h (lcpLE_product_right a b)⟩ + · rintro ⟨h,k⟩; intro p + exact (lcp_associativity x a b p).symm.trans ((lcp_congr h (fun _ => Iff.rfl) p).trans (k p)) + +theorem lcpLE_empty (a : PathSpace) : LcpLE [] a := lcp_empty_left a + +/-- Coverage alone is insufficient: both extra output contributions must already lie in A. -/ +theorem lcpLE_iff (a b : PathSpace) : LcpLE a b ↔ + covers a b = true ∧ Included (divergence a b) a ∧ Included (retain b a) a := by + constructor + · intro h; refine ⟨?_,?_,?_⟩ + · apply (covers_iff a b).mpr + intro p hp; exact lcp_output_covered ((lcp_symmetry a b p).mp ((h p).mpr hp)) + · intro p hp; exact (h p).mp ((lcp_correction a b p).mpr (Or.inl hp)) + · intro p hp; exact (h p).mp ((lcp_correction a b p).mpr (Or.inr (Or.inr hp))) + · rintro ⟨hc,hd,ht⟩; intro p; rw [lcp_correction]; constructor + · rintro (h | h | h) + · exact hd p h + · exact retain_subset a b p h + · exact ht p h + · intro hp; exact Or.inr (Or.inl ((retain_identity a b).mpr hc p |>.mpr hp)) + +/-- Restriction needs exactly the divergences between its retained mask paths. -/ +theorem lcp_restrict (a b m : PathSpace) : + Same (lcpProduct (restrict a m) (restrict b m)) + (union (restrict (lcpProduct a b) m) (divergence (retain m a) (retain m b))) := by + intro p; constructor + · intro hp + rcases (lcp_correction _ _ p).mp hp with hd | ht | ht + · rcases (divergence_same_mask a b m p).mp hd with hr | hr + · obtain ⟨h,q,hq,hqp⟩ := (mem_restrict _ _ _).mp hr + exact List.mem_append_left _ ((mem_restrict _ _ _).mpr + ⟨(lcp_correction a b p).mpr (Or.inl h),q,hq,hqp⟩) + · exact List.mem_append_right _ hr + · obtain ⟨hr,y,hy,hpy⟩ := (mem_retain _ _ _).mp ht + obtain ⟨ha,q,hq,hqp⟩ := (mem_restrict _ _ _).mp hr + have hb := ((mem_restrict _ _ _).mp hy).1 + exact List.mem_append_left _ ((mem_restrict _ _ _).mpr + ⟨(mem_lcpProduct _ _ _).mpr ⟨p,ha,y,hb,Path.lcp_of_prefix hpy⟩,q,hq,hqp⟩) + · obtain ⟨hr,x,hx,hpx⟩ := (mem_retain _ _ _).mp ht + obtain ⟨hb,q,hq,hqp⟩ := (mem_restrict _ _ _).mp hr + have ha := ((mem_restrict _ _ _).mp hx).1 + exact List.mem_append_left _ ((mem_restrict _ _ _).mpr + ⟨(mem_lcpProduct _ _ _).mpr ⟨x,ha,p,hb,(Path.lcp_comm x p).trans (Path.lcp_of_prefix hpx)⟩,q,hq,hqp⟩) + · intro hp; rcases List.mem_append.mp hp with hr | hd + · obtain ⟨hl,q,hq,hqp⟩ := (mem_restrict _ _ _).mp hr + obtain ⟨x,hx,y,hy,rfl⟩ := (mem_lcpProduct _ _ _).mp hl + obtain ⟨hqx,hqy⟩ := (Path.prefix_lcp _ _ _).mp hqp + exact (mem_lcpProduct _ _ _).mpr ⟨x,(mem_restrict _ _ _).mpr ⟨hx,q,hq,hqx⟩, + y,(mem_restrict _ _ _).mpr ⟨hy,q,hq,hqy⟩,rfl⟩ + · exact (lcp_correction _ _ p).mpr (Or.inl ((divergence_same_mask a b m p).mpr (Or.inr hd))) + +theorem lcp_restrict_closed {m : PathSpace} (hm : IsClosed m) (a b : PathSpace) : + Same (lcpProduct (restrict a m) (restrict b m)) (restrict (lcpProduct a b) m) := by + intro p; rw [lcp_restrict]; constructor + · intro hp; rcases List.mem_append.mp hp with hr | hd + · exact hr + · obtain ⟨x,hx,y,hy,he⟩ := (mem_divergence _ _ _).mp hd + have hpm : p ∈ m := Path.divergence_lcp he ▸ + hm x ((mem_retain _ _ _).mp hx).1 y ((mem_retain _ _ _).mp hy).1 + have hl := (lcp_restrict a b m p).mpr (List.mem_append_right _ hd) + have hs := lcp_mono (fun q hq => ((mem_restrict _ _ q).mp hq).1) + (fun q hq => ((mem_restrict _ _ q).mp hq).1) p hl + exact (mem_restrict _ _ _).mpr ⟨hs,p,hpm,Path.prefix_self p⟩ + · exact List.mem_append_left _ + +theorem completion_wrap (a : PathSpace) (q : Path) : + Same (completion (wrap q a)) (wrap q (completion a)) := by + intro p + have hd := divergence_wrap a a q p + simp only [mem_completion, branches, hd, mem_wrap] + grind + +theorem completion_unwrap (a : PathSpace) (q : Path) : + Same (completion (unwrap a q)) (unwrap (completion a) q) := by + intro p + have hd := divergence_unwrap a a q p + simp only [mem_completion, branches, hd, mem_unwrap] + +theorem closed_join_comm (a b : PathSpace) : + Same (completion (union a b)) (completion (union b a)) := by + apply completion_congr; intro p; simp only [union, List.mem_append]; exact Or.comm + +theorem closed_join_idem {a : PathSpace} (ha : IsClosed a) : + Same (completion (union a a)) a := by + have h : Same (union a a) a := by intro p; simp [union] + exact fun p => (completion_congr h p).trans ((closed_iff_completion a).mp ha p) + +theorem closed_join_empty {a : PathSpace} (ha : IsClosed a) : + Same (completion (union a [])) a := by + simpa only [union, List.append_nil] using (closed_iff_completion a).mp ha + +end PathMapModel.PathSpace diff --git a/lean/PathMapModel/PathSetLaws.lean b/lean/PathMapModel/PathSetLaws.lean index bfe20be7..a09f7a3d 100644 --- a/lean/PathMapModel/PathSetLaws.lean +++ b/lean/PathMapModel/PathSetLaws.lean @@ -195,9 +195,69 @@ def retention (a b c f : PathSpace) : Checks := ("retain_identity", eq (retain a b) a == covers a b), ("retain_count_bound", decide (count (retain a b) <= count a)) ] +/-- Closed divergence and branch closure, including canonical generators and filters. -/ +def closedAlgebra (a b c f : PathSpace) : Checks := + [ ("completion_union", eq (C (union a b)) (union (union (C a) (C b)) (D a b))), + ("completion_union_lcp", eq (C (union a b)) (union (union (C a) (C b)) (M a b))), + ("completion_union_absorb", eq (C (union (C a) (C b))) (C (union a b))), + ("hull_completion", eq (hull (C a)) (hull a)), + ("completion_hull", eq (union a (C (hull a))) (C a)), + ("hull_remove_branches", eq (hull (diff a (Br a))) (hull a)), + ("branches_remove_branches", eq (Br (diff a (Br a))) (Br a)), + ("completion_remove_branches", eq (C (diff a (Br a))) (C a)), + ("completion_diff_branches", eq (diff (C a) (Br a)) (diff a (Br a))), + ("lcp_completion_left", eq (M (C a) b) (M a b)), + ("lcp_completion_right", eq (M a (C b)) (M a b)), + ("lcp_completion", eq (M (C a) (C b)) (M a b)), + ("lcp_repeat", eq (M a (M a b)) (M a b)), + ("lcp_medial", eq (M (M a b) (M c f)) (M (M a c) (M b f))), + ("lcp_four_factors", eq (M (union a b) (union c f)) (union (union (M a c) (M a f)) (union (M b c) (M b f)))), + ("lcp_closed_join", eq (M a (C (union b c))) (union (M a b) (M a c))), + ("lcp_new_marks", eq (diff (M a b) (union a b)) (diff (D a b) (union a b))), + ("retain_lcp_operand", eq (retain a (M a b)) (retain a b)), + ("hull_lcp_hulls", eq (hull (M (hull a) (hull b))) (hull (M a b))), + ("completion_restrict", eq (C (restrict a b)) (union (restrict (C a) b) (Br (retain b a)))), + ("completion_restrict_closed", eq (C (restrict a (C b))) (restrict (C a) (C b))), + ("lcp_restrict", eq (M (restrict a c) (restrict b c)) (union (restrict (M a b) c) (D (retain c a) (retain c b)))), + ("lcp_restrict_closed", eq (M (restrict a (C c)) (restrict b (C c))) (restrict (M a b) (C c))), + ("closed_inter", eq (C (inter (C a) (C b))) (inter (C a) (C b))), + ("closed_retain", eq (C (retain (C a) b)) (retain (C a) b)), + ("closed_restrict", eq (C (restrict (C a) (C b))) (restrict (C a) (C b))), + ("closed_raffinate", eq (C (raffinate (C a) b)) (raffinate (C a) b)), + ("closed_lcp_union", eq (C (union (M a b) (M a c))) (union (M a b) (M a c))), + ("closed_join_assoc", eq (C (union (C (union a b)) c)) (C (union a (C (union b c))))), + ("closed_join_comm", eq (C (union a b)) (C (union b a))), + ("closed_join_idem", eq (C (union (C a) (C a))) (C a)), + ("closed_join_empty", eq (C (union (C a) [])) (C a)), + ("closed_join_absorption", eq (C (union (C a) (inter (C a) b))) (C a)), + ("closed_meet_absorption", eq (inter a (C (union a b))) a), + ("lcpLE_product_left", eq (M (M a b) a) (M a b)), + ("lcpLE_product_right", eq (M (M a b) b) (M a b)), + ("completion_wrap", eq (C (wrap [0,1] a)) (wrap [0,1] (C a))), + ("completion_unwrap", eq (C (unwrap a [0])) (unwrap (C a) [0])), + ("completion_extensive", sub a (C a)), + ("completion_inter_bound", sub (C (inter a b)) (inter (C a) (C b))), + ("lcp_inter_lower", sub (inter a b) (M a b)), + ("lcp_inter_bound", sub (M (inter a b) c) (inter (M a c) (M b c))), + ("lcp_diff_bound", sub (diff (M a c) (M b c)) (M (diff a b) c)), + ("lcp_union_bound", sub (M a b) (C (union a b))), + ("lcp_retain_bound", sub (M (retain a c) (retain b f)) (retain (M a b) (M c f))), + ("completion_retain_bound", sub (C (retain a b)) (retain (C a) b)), + ("completion_raffinate_bound", sub (C (raffinate a b)) (raffinate (C a) b)), + ("completion_least", sub (C a) (C b) == sub a (C b)), + ("completion_generators", eq (C b) (C a) == (sub (diff a (Br a)) b && sub b (C a))), + ("completion_equiv_generators", eq (C a) (C b) == eq (diff a (Br a)) (diff b (Br b))), + ("closed_union_iff", eq (C (union (C a) (C b))) (union (C a) (C b)) == sub (D (C a) (C b)) (union (C a) (C b))), + ("closed_join_least", sub (C (union a b)) (C c) == (sub a (C c) && sub b (C c))), + ("lcpLE_iff", eq (M a b) a == (covers a b && sub (D a b) a && sub (retain b a) a)), + ("lcpLE_product_iff", eq (M a (M b c)) a == (eq (M a b) a && eq (M a c) a)), + ("completion_cardinality", decide (count (C a) <= count a + (count (hull a) - 1))), + ("completion_cardinality_linear", decide (count a <= count (C a) && count (C a) <= 2 * count a - 1)), + ("basis_completion", implies (!a.isEmpty) (eq (basis (C a)) [commonPrefix a])) ] + /-- Assumptions are executable guards, so unconstrained inputs are safe to test. -/ def all (a b c f : PathSpace) : Checks := - unary a ++ binary a b ++ ternary a b c ++ quaternary a b c f ++ retention a b c f ++ + unary a ++ binary a b ++ ternary a b c ++ quaternary a b c f ++ retention a b c f ++ closedAlgebra a b c f ++ (pathLaws a b []) ++ (pathLaws a b [0]) ++ (pathLaws a b [0,1,0]) def failures (checks : Checks) : List String := (checks.filter (! ·.2)).map (·.1) diff --git a/tests/support/path_set_laws.rs b/tests/support/path_set_laws.rs index 9f9c7d7f..8aa1c5b2 100644 --- a/tests/support/path_set_laws.rs +++ b/tests/support/path_set_laws.rs @@ -343,7 +343,226 @@ fn retention_laws(t: &mut Coverage, a: &M, b: &M, c: &M, f: &M) { ); t.check("retain_count_bound", count(&retain(a, b)) <= count(a)); } +fn closed_laws(t: &mut Coverage, a: &M, b: &M, c: &M, f: &M) { + let ca = completion(a); + let cb = completion(b); + let cc = completion(c); + let ab = lcp_product(a, b); + let ga = a.subtract(&br(a)); + let same = |x: &M, y: &M| set_from_map(x) == set_from_map(y); + let subset = |x: &M, y: &M| set_from_map(x).is_subset(&set_from_map(y)); + t.eq( + "completion_union", + &completion(&a.join(b)), + &ca.join(&cb).join(&d(a, b)), + ); + t.eq( + "completion_union_lcp", + &completion(&a.join(b)), + &ca.join(&cb).join(&ab), + ); + t.eq( + "completion_union_absorb", + &completion(&ca.join(&cb)), + &completion(&a.join(b)), + ); + t.eq("hull_completion", &hull(&ca), &hull(a)); + t.eq("completion_hull", &a.join(&completion(&hull(a))), &ca); + t.eq("hull_remove_branches", &hull(&ga), &hull(a)); + t.eq("branches_remove_branches", &br(&ga), &br(a)); + t.eq("completion_remove_branches", &completion(&ga), &ca); + t.eq("completion_diff_branches", &ca.subtract(&br(a)), &ga); + t.eq("lcp_completion_left", &lcp_product(&ca, b), &ab); + t.eq("lcp_completion_right", &lcp_product(a, &cb), &ab); + t.eq("lcp_completion", &lcp_product(&ca, &cb), &ab); + t.eq("lcp_repeat", &lcp_product(a, &ab), &ab); + t.eq( + "lcp_medial", + &lcp_product(&ab, &lcp_product(c, f)), + &lcp_product(&lcp_product(a, c), &lcp_product(b, f)), + ); + t.eq( + "lcp_four_factors", + &lcp_product(&a.join(b), &c.join(f)), + &lcp_product(a, c) + .join(&lcp_product(a, f)) + .join(&lcp_product(b, c)) + .join(&lcp_product(b, f)), + ); + t.eq( + "lcp_closed_join", + &lcp_product(a, &completion(&b.join(c))), + &ab.join(&lcp_product(a, c)), + ); + t.eq( + "lcp_new_marks", + &ab.subtract(&a.join(b)), + &d(a, b).subtract(&a.join(b)), + ); + t.eq("retain_lcp_operand", &retain(a, &ab), &retain(a, b)); + t.eq( + "hull_lcp_hulls", + &hull(&lcp_product(&hull(a), &hull(b))), + &hull(&ab), + ); + t.eq( + "completion_restrict", + &completion(&a.restrict(b)), + &ca.restrict(b).join(&br(&retain(b, a))), + ); + t.eq( + "completion_restrict_closed", + &completion(&a.restrict(&cb)), + &ca.restrict(&cb), + ); + t.eq( + "lcp_restrict", + &lcp_product(&a.restrict(c), &b.restrict(c)), + &ab.restrict(c).join(&d(&retain(c, a), &retain(c, b))), + ); + t.eq( + "lcp_restrict_closed", + &lcp_product(&a.restrict(&cc), &b.restrict(&cc)), + &ab.restrict(&cc), + ); + t.eq("closed_inter", &completion(&ca.meet(&cb)), &ca.meet(&cb)); + t.eq( + "closed_retain", + &completion(&retain(&ca, b)), + &retain(&ca, b), + ); + t.eq( + "closed_restrict", + &completion(&ca.restrict(&cb)), + &ca.restrict(&cb), + ); + t.eq( + "closed_raffinate", + &completion(&raff(&ca, b)), + &raff(&ca, b), + ); + t.eq( + "closed_lcp_union", + &completion(&ab.join(&lcp_product(a, c))), + &ab.join(&lcp_product(a, c)), + ); + t.eq( + "closed_join_assoc", + &completion(&completion(&a.join(b)).join(c)), + &completion(&a.join(&completion(&b.join(c)))), + ); + t.eq( + "closed_join_comm", + &completion(&a.join(b)), + &completion(&b.join(a)), + ); + t.eq("closed_join_idem", &completion(&ca.join(&ca)), &ca); + t.eq("closed_join_empty", &completion(&ca.join(&M::new())), &ca); + t.eq( + "closed_join_absorption", + &completion(&ca.join(&ca.meet(b))), + &ca, + ); + t.eq( + "closed_meet_absorption", + &a.meet(&completion(&a.join(b))), + a, + ); + t.eq("lcpLE_product_left", &lcp_product(&ab, a), &ab); + t.eq("lcpLE_product_right", &lcp_product(&ab, b), &ab); + t.eq( + "completion_wrap", + &completion(&wrap(&[0, 1], a)), + &wrap(&[0, 1], &ca), + ); + t.eq( + "completion_unwrap", + &completion(&unwrap(a, &[0])), + &unwrap(&ca, &[0]), + ); + t.sub("completion_extensive", a, &ca); + t.sub( + "completion_inter_bound", + &completion(&a.meet(b)), + &ca.meet(&cb), + ); + t.sub("lcp_inter_lower", &a.meet(b), &ab); + t.sub( + "lcp_inter_bound", + &lcp_product(&a.meet(b), c), + &lcp_product(a, c).meet(&lcp_product(b, c)), + ); + t.sub( + "lcp_diff_bound", + &lcp_product(a, c).subtract(&lcp_product(b, c)), + &lcp_product(&a.subtract(b), c), + ); + t.sub("lcp_union_bound", &ab, &completion(&a.join(b))); + t.sub( + "lcp_retain_bound", + &lcp_product(&retain(a, c), &retain(b, f)), + &retain(&ab, &lcp_product(c, f)), + ); + t.sub( + "completion_retain_bound", + &completion(&retain(a, b)), + &retain(&ca, b), + ); + t.sub( + "completion_raffinate_bound", + &completion(&raff(a, b)), + &raff(&ca, b), + ); + t.check("completion_least", subset(&ca, &cb) == subset(a, &cb)); + t.check( + "completion_generators", + same(&cb, &ca) == (subset(&ga, b) && subset(b, &ca)), + ); + t.check( + "completion_equiv_generators", + same(&ca, &cb) == same(&ga, &b.subtract(&br(b))), + ); + t.check( + "closed_union_iff", + same(&completion(&ca.join(&cb)), &ca.join(&cb)) == subset(&d(&ca, &cb), &ca.join(&cb)), + ); + t.check( + "closed_join_least", + subset(&completion(&a.join(b)), &cc) == (subset(a, &cc) && subset(b, &cc)), + ); + t.check( + "lcpLE_iff", + same(&ab, a) == (covers(a, b) && subset(&d(a, b), a) && subset(&retain(b, a), a)), + ); + t.check( + "lcpLE_product_iff", + same(&lcp_product(a, &lcp_product(b, c)), a) + == (same(&ab, a) && same(&lcp_product(a, c), a)), + ); + t.check( + "completion_cardinality", + count(&ca) <= count(a) + count(&hull(a)).saturating_sub(1), + ); + t.check( + "completion_cardinality_linear", + count(a) <= count(&ca) && count(&ca) <= (2 * count(a)).saturating_sub(1), + ); + if !a.is_empty() { + t.eq( + "basis_completion", + &basis(&ca), + &M::single(common_prefix(a), ()), + ); + } + assert!(same(&completion(&cm(&ca, &cb)), &cm(&ca, &cb))); + assert!(same(&completion(&cs(&ca, b)), &cs(&ca, b))); + assert!(subset(&completion(&cm(a, b)), &cm(&ca, &cb))); + assert!(subset(&completion(&cs(a, b)), &cs(&ca, b))); + assert!(same(&hull(&completion(&cm(a, b))), &hull(&cm(&ca, &cb)))); + assert!(same(&hull(&completion(&cs(a, b))), &hull(&cs(&ca, b)))); +} fn laws(t: &mut Coverage, a: &M, b: &M, c: &M, f: &M) { + closed_laws(t, a, b, c, f); retention_laws(t, a, b, c, f); let x = d(a, b); let ba = br(a); @@ -635,6 +854,60 @@ fn small(seed: u64, salt: u64) -> KeySet { }) .collect() } +/// All subsets of a depth-two binary tree, including every closed subspace. +/// Check anti-exchange and least generators independently of the named catalogue. +#[test] +fn exhaustive_branch_closure_generators() { + let paths = [ + vec![], + vec![0], + vec![1], + vec![0, 0], + vec![0, 1], + vec![1, 0], + vec![1, 1], + ]; + for mask in 0..(1usize << paths.len()) { + let keys: KeySet = paths + .iter() + .enumerate() + .filter(|(i, _)| mask & (1 << i) != 0) + .map(|(_, p)| p.clone()) + .collect(); + let a = map_from_set(&keys); + let closed = completion(&a); + let closed_keys = set_from_map(&closed); + assert_eq!(closed_keys, set_from_map(&lcp_product(&a, &a))); + let generators = a.subtract(&br(&a)); + assert_eq!(closed_keys, set_from_map(&completion(&generators))); + for x in &paths { + // Deleting a least generator strictly changes the closure. + if generators.get(x).is_some() { + assert_ne!( + closed_keys, + set_from_map(&completion(&a.subtract(&M::single(x, ())))) + ); + } + if closed_keys.contains(x) { + continue; + } + let with_x = completion(&a.join(&M::single(x, ()))); + for y in &paths { + if x == y || closed_keys.contains(y) { + continue; + } + let with_y = completion(&a.join(&M::single(y, ()))); + if with_y.get(x).is_some() { + assert!( + with_x.get(y).is_none(), + "anti-exchange: {keys:?}, {x:?}, {y:?}" + ); + } + } + } + } +} + #[test] fn seeded_full_path_set_law_catalogue() { let mut t = Coverage::default(); From 64dc98156d31bc0698205a2563a3e45db9e3b0df Mon Sep 17 00:00:00 2001 From: adamv-symbolica Date: Tue, 17 Nov 2026 16:12:56 +0000 Subject: [PATCH 07/15] Benchmark convex meet and subtraction in CI --- .github/scripts/bench_ab.py | 2 +- Cargo.toml | 4 + benches/convex.rs | 274 ++++++++++++++++++++++++++++++++++++ 3 files changed, 279 insertions(+), 1 deletion(-) create mode 100644 benches/convex.rs diff --git a/.github/scripts/bench_ab.py b/.github/scripts/bench_ab.py index 31002090..5898d72d 100755 --- a/.github/scripts/bench_ab.py +++ b/.github/scripts/bench_ab.py @@ -41,7 +41,7 @@ # and each bench here is pinned to one core), and `sla` and `multiplicities` (plain `main`s that # print no divan table). DEFAULT_BENCHES = ('shakespeare cities sparse_keys binary_keys superdense_keys act_paths zipper_head_owned product_zipper ' - 'write_zipper graft_masked_branches restrict prune oeis byte_mask serde pointcloud') + 'write_zipper graft_masked_branches restrict convex prune oeis byte_mask serde pointcloud') THRESH = 0.05 # a case is listed in the summary when |change| exceeds this diff --git a/Cargo.toml b/Cargo.toml index a7d96ebd..f9900554 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -156,6 +156,10 @@ harness = false name = "restrict" harness = false +[[bench]] +name = "convex" +harness = false + [[bench]] name = "write_zipper" harness = false diff --git a/benches/convex.rs b/benches/convex.rs new file mode 100644 index 00000000..9dae79d4 --- /dev/null +++ b/benches/convex.rs @@ -0,0 +1,274 @@ +//! Scaling of stable convex meet and subtraction, through both native nodes and zippers. +//! +//! Valued interiors exercise stable pruning; the fringe cases isolate descendant-witness searches. +//! Each sweep varies one parameter. Independent operands +//! have no shared nodes; the `shared_*` sweeps measure identity with and without a root value, +//! and sparse edits. +//! +//! Setup and a check against the hull/retain specification run outside the timing. Each timed +//! call returns a fresh map; Divan defers its destruction. The zipper measurements include opening +//! the input/output zippers, making their allocation and output lifetime comparable to the map API. +//! +//! Run with `cargo bench --bench convex`; `-- --test` checks every fixture without sampling. + +use divan::{Bencher, Divan, black_box}; +use pathmap::{ + PathMap, + experimental::{ + convex::{convex_meet, convex_subtract, zipper_convex_meet, zipper_convex_subtract}, + path_sets::{hull, retain}, + }, +}; + +type Map = PathMap; +type Pair = (Map, Map); + +fn main() { + Divan::from_args().main(); +} + +trait Operation { + const SUBTRACT: bool; + fn apply(left: &Map, right: &Map) -> Map; +} + +struct NativeMeet; +struct NativeSubtract; +struct ZipperMeet; +struct ZipperSubtract; + +impl Operation for NativeMeet { + const SUBTRACT: bool = false; + fn apply(left: &Map, right: &Map) -> Map { + convex_meet(left, right) + } +} + +impl Operation for NativeSubtract { + const SUBTRACT: bool = true; + fn apply(left: &Map, right: &Map) -> Map { + convex_subtract(left, right) + } +} + +impl Operation for ZipperMeet { + const SUBTRACT: bool = false; + fn apply(left: &Map, right: &Map) -> Map { + let mut out = Map::new(); + zipper_convex_meet( + &mut left.read_zipper(), + &mut right.read_zipper(), + &mut out.write_zipper(), + ); + out + } +} + +impl Operation for ZipperSubtract { + const SUBTRACT: bool = true; + fn apply(left: &Map, right: &Map) -> Map { + let mut out = Map::new(); + zipper_convex_subtract( + &mut left.read_zipper(), + &mut right.read_zipper(), + &mut out.write_zipper(), + ); + out + } +} + +fn measure(bencher: Bencher, (left, right): Pair) { + // Mask algebra observes only domains, even when the input payloads differ. + let left_keys: PathMap<()> = left.iter().map(|(p, _)| (p, ())).collect(); + let right_keys: PathMap<()> = right.iter().map(|(p, _)| (p, ())).collect(); + let expected = if O::SUBTRACT { + retain(&left, &hull(&left_keys).subtract(&right_keys)) + } else { + // Ordinary meet may combine payloads; convex meet keeps the left payload unchanged. + let common: Map = left + .iter() + .filter(|(p, _)| right.get(p).is_some()) + .map(|(p, v)| (p, *v)) + .collect(); + retain(&common, &hull(&left_keys).meet(&hull(&right_keys))) + }; + let actual = O::apply(&left, &right); + for (p, v) in expected.iter() { + assert_eq!(actual.get(&p), Some(v), "path {p:?}"); + } + assert_eq!(actual.val_count(), expected.val_count()); + drop((actual, expected)); + bencher.bench_local(|| O::apply(black_box(&left), black_box(&right))); +} + +/// Deterministic, distinct keys spread across the root's children, without random setup state. +fn key(i: usize) -> [u8; 8] { + (i as u64).wrapping_mul(0x9e37_79b9_7f4a_7c15).to_be_bytes() +} + +/// Common interior marks precede each leaf. Nonmatching leaves diverge only at the last byte, +/// forcing meet to discard their common interiors and subtraction to preserve those interiors. +fn independent(tips: usize, overlap: usize, stem_len: usize) -> Pair { + let mut left = Map::new(); + let mut right = Map::new(); + let stem = vec![0x55; stem_len]; + left.set_val_at(&stem, 1); + right.set_val_at(&stem, 2); + for i in 0..tips { + let mut p = stem.clone(); + p.extend(key(i)); + for end in [stem_len + 4, p.len()] { + left.set_val_at(&p[..end], i as u64 + 1); + right.set_val_at(&p[..end], i as u64 + 2); + } + p.push(0); + left.set_val_at(&p, i as u64 + 1); + *p.last_mut().unwrap() = u8::from(i >= tips * overlap / 100); + right.set_val_at(&p, i as u64 + 2); + } + (left, right) +} + +fn population(tips: usize) -> Pair { + independent(tips, 50, 0) +} + +fn overlap(percent: usize) -> Pair { + independent(4096, percent, 0) +} + +fn compressed_depth(bytes: usize) -> Pair { + independent(64, 50, bytes) +} + +/// All common marks are interiors; differing tips make meet empty after stable pruning. +/// Subtraction keeps every left mark, even though the mask contains every interior. +fn valued_depth(depth: usize) -> Pair { + let mut left = Map::new(); + let mut right = Map::new(); + let mut p = Vec::with_capacity(depth + 1); + for _ in 0..=depth { + left.set_val_at(&p, 1); + right.set_val_at(&p, 2); + p.push(0); + } + *p.last_mut().unwrap() = 1; + left.set_val_at(&p, 1); + *p.last_mut().unwrap() = 2; + right.set_val_at(&p, 2); + (left, right) +} + +/// Fixed common spines, with increasing left-only sibling branches. Subtraction can share them; +/// meet needs their liveness to avoid treating common interior marks as original tips. +fn branching(width: usize) -> Pair { + let mut left = Map::new(); + let mut right = Map::new(); + for head in 0..8 { + let mut p = vec![head]; + for _ in 0..16 { + left.set_val_at(&p, 1); + right.set_val_at(&p, 2); + p.push(0); + for sibling in 1..width { + *p.last_mut().unwrap() = sibling as u8; + left.set_val_at(&p, 1); + } + *p.last_mut().unwrap() = 0; + } + left.set_val_at(&p, 1); + right.set_val_at(&p, 2); + } + (left, right) +} + +/// Left tips coincide with right marks. Right-only descendants require one valued witness, +/// or a full scan when the entire fringe is bare. A subtree cardinality scan would make the +/// valued-fringe sweep unnecessarily linear in the number of descendants. +fn fringe(descendants: usize, valued: bool) -> Pair { + let mut left = Map::new(); + let mut right = Map::new(); + for head in 0..4 { + left.set_val_at([head], 1); + right.set_val_at([head], 2); + for i in 0..descendants { + let mut p = vec![head]; + p.extend(key(i)); + if valued { + right.set_val_at(&p, 2); + } else { + right.create_path(&p); + } + } + } + (left, right) +} + +fn rhs_fringe(descendants: usize) -> Pair { + fringe(descendants, true) +} + +fn rhs_bare_fringe(descendants: usize) -> Pair { + fringe(descendants, false) +} + +// A value at the focus suppresses ZipperConcrete::shared_node_id. Keep this case +// separate from the unvalued root so both the traversal and sharing fast path are visible. +fn shared_identity(tips: usize) -> Pair { + let (left, _) = population(tips); + let right = left.clone(); + (left, right) +} + +fn shared_unvalued_root(tips: usize) -> Pair { + let (mut left, _) = population(tips); + left.remove_val_at([], false); + let right = left.clone(); + (left, right) +} + +fn shared_edit(tips: usize) -> Pair { + let (left, mut right) = shared_identity(tips); + let mut p = key(0).to_vec(); + p.push(0); + right.remove_val_at(&p, true); + *p.last_mut().unwrap() = 1; + right.set_val_at(&p, 2); + (left, right) +} + +// Keep operation and fixture in each function name: the CI table parser records +// one group plus its argument, so nested generic groups would overwrite cases. +macro_rules! sweep { + ($name:ident, $args:expr) => { + paste::paste! { + #[divan::bench(args = $args)] + fn [](bencher: Bencher, n: usize) { + measure::(bencher, $name(n)); + } + #[divan::bench(args = $args)] + fn [](bencher: Bencher, n: usize) { + measure::(bencher, $name(n)); + } + #[divan::bench(args = $args)] + fn [](bencher: Bencher, n: usize) { + measure::(bencher, $name(n)); + } + #[divan::bench(args = $args)] + fn [](bencher: Bencher, n: usize) { + measure::(bencher, $name(n)); + } + } + }; +} + +sweep!(population, [64, 256, 1024, 4096, 16384]); +sweep!(overlap, [0, 25, 50, 75, 100]); +sweep!(compressed_depth, [0, 16, 256, 4096, 16384]); +sweep!(valued_depth, [8, 32, 128, 512, 2048]); +sweep!(branching, [2, 4, 16, 64, 256]); +sweep!(rhs_fringe, [0, 16, 256, 4096, 16384]); +sweep!(rhs_bare_fringe, [0, 16, 256, 4096]); +sweep!(shared_identity, [64, 256, 1024, 4096, 16384]); +sweep!(shared_unvalued_root, [64, 256, 1024, 4096, 16384]); +sweep!(shared_edit, [64, 256, 1024, 4096, 16384]); From c9cdf241715ef087dd5d1177d972ad76d756dcf6 Mon Sep 17 00:00:00 2001 From: adamv-symbolica Date: Tue, 17 Nov 2026 16:46:17 +0000 Subject: [PATCH 08/15] Exercise convex operations in differential program fuzzing --- .github/scripts/fuzz_ab.py | 26 +++++-- .github/workflows/ci.yml | 29 +++++++- differential/src/harness.rs | 128 ++++++++++++++++++++++++++++++++++- differential/src/repro.rs | 9 +++ lean/PathMapModel/Check.lean | 16 +++++ lean/PathMapModel/Fuzz.lean | 18 ++++- lean/differential.py | 92 +++++++++++++++++++++++-- lean/input_format.py | 2 +- lean/test_input_format.py | 54 ++++++++++++++- 9 files changed, 355 insertions(+), 19 deletions(-) diff --git a/.github/scripts/fuzz_ab.py b/.github/scripts/fuzz_ab.py index 25dedaa8..9f9d67f6 100755 --- a/.github/scripts/fuzz_ab.py +++ b/.github/scripts/fuzz_ab.py @@ -46,6 +46,13 @@ def tail(path, n=30): return '\n'.join(Path(path).read_text().splitlines()[-n:]) +def selector_count(src): + """Read the append-only operation table, including pre-versioned baselines.""" + harness = (src / 'differential' / 'src' / 'harness.rs').read_text() + match = re.search(r'pub const NOPS: usize = (\d+);', harness) + return int(match[1]) if match else 56 + + class Fuzz: def __init__(self, base, head): self.repo = Path.cwd() @@ -107,16 +114,18 @@ def prepare_base(self): git('clean', '-fdq', '--', 'differential', 'lean', cwd=self.base_src) return 'base-harness' if self.build_side('base', self.base_src) else 'none' - def run_side(self, side, src, label, n, flags): + def run_side(self, side, src, label, n, flags, selectors): env = dict(os.environ, TMPDIR=str(self.out / f'fails-{side}-{label}'), + PATHMAP_ORACLE=str(src / 'lean' / '.lake' / 'build' / 'bin' / 'pathmap-oracle'), PATHMAP_TRACE=str(self.target / f'fuzz-{side}' / 'release' / 'pathmap_trace'), PATHMAP_ACT_TRACE=str(self.target / f'fuzz-{side}' / 'release' / 'act_trace')) Path(env['TMPDIR']).mkdir(parents=True, exist_ok=True) log(f'== fuzz {label} {side}: {n} inputs, seed {self.seed}') outf = self.out / f'fuzz-{label}-{side}.txt' with open(outf, 'w') as f: - subprocess.run([str(src / 'lean' / 'differential.py'), '--random', str(n), '--seed', self.seed, + subprocess.run([str(self.repo / 'lean' / 'differential.py'), '--random', str(n), '--seed', self.seed, + '--selectors', str(selectors), '--maxlen', '300', '--max-fails', '0', '-j', self.jobs, *flags], cwd=src, env=env, stdout=f, stderr=subprocess.STDOUT) text = outf.read_text() @@ -189,7 +198,7 @@ def summarize(self, baseline): L += ['**No baseline**: base could not be built with either harness, so only head was run and nothing is gated.', ''] elif baseline == 'base-harness': L += ["Base was built with its own harness and model (head's did not build against it), " - 'so harness changes may show up as differences.', ''] + 'so harness changes may show up as differences. Random inputs use the shared selector range.', ''] new_total, unfinished = 0, 0 for label, n, _ in self.modes: hf, hs, hk = self.parse(label, 'head') @@ -272,10 +281,17 @@ def main(self): if not self.build_side('head', self.repo): sys.exit(1) baseline = self.prepare_base() + # Always use head's generator with one recorded selector count. + # A fallback baseline may not implement newly appended operations; + # those are exercised separately by the strict convex CI sweep. + selectors = selector_count(self.repo) + if baseline == 'base-harness': + selectors = min(selectors, selector_count(self.base_src)) + log(f'== shared random input encoding: {selectors} selectors') for label, n, flags in self.modes: - self.run_side('head', self.repo, label, n, flags) + self.run_side('head', self.repo, label, n, flags, selectors) if baseline != 'none': - self.run_side('base', self.base_src, label, n, flags) + self.run_side('base', self.base_src, label, n, flags, selectors) new_total, unfinished = self.summarize(baseline) return 1 if unfinished or (self.strict and new_total) else 0 finally: diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index b825c546..80f47282 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -225,7 +225,8 @@ jobs: # Regression check: head and base run on identical inputs; an input on which head diverges # from the model but base did not is reported as a warning annotation (master has known # divergences). Set FUZZ_STRICT=1 below to make that fail the job instead. - # Ordered after the tests but not gated on them: findings are warnings, and a PR whose + # Focused convex programs have no known-bug exemptions: every divergence fails. + # Ordered after the tests but not gated on them: baseline findings are warnings, and a PR whose # tests fail is exactly one whose divergences are worth seeing. needs: test if: ${{ !cancelled() && (github.event_name == 'pull_request' || github.event_name == 'workflow_dispatch') }} @@ -270,6 +271,30 @@ jobs: FUZZ_OUT: ${{ runner.temp }}/fuzz-out run: | .github/scripts/fuzz_ab.py "${{ steps.base.outputs.sha }}" "${{ github.sha }}" + - name: fuzzer encoding tests + run: | + cargo test --release -p differential --lib --target-dir "$CARGO_TARGET_DIR/fuzz-head" + python3 -m unittest discover -s lean -p 'test_input_format.py' + - name: convex programs against Lean + shell: bash + env: + PATHMAP_TRACE: ${{ env.CARGO_TARGET_DIR }}/fuzz-head/release/pathmap_trace + TMPDIR: ${{ runner.temp }}/fuzz-out/fails-convex + run: | + mkdir -p "$TMPDIR" + if python3 lean/differential.py --convex 2000 --seed 7 --strict --max-fails 0 -j 16 | tee "${{ runner.temp }}/fuzz-out/fuzz-convex-head.txt"; then + convex_status=0 + else + convex_status=$? + fi + { + printf '\n## Convex programs\n\n' + tail -n 1 "${{ runner.temp }}/fuzz-out/fuzz-convex-head.txt" + } >> "${{ runner.temp }}/fuzz-out/summary.md" + if [ "$convex_status" -ne 0 ]; then + printf 'Convex program check failed\n' >> "${{ runner.temp }}/fuzz-out/findings" + fi + exit "$convex_status" - name: comment on the PR # One comment per PR for this job (separate from the bench one): verdict, per-mode tables, # newly diverging inputs and their shrunk Rust reproducers. Created only when there is @@ -281,7 +306,7 @@ jobs: run: | python3 .github/scripts/pr_comment.py --id fuzz --title "Differential fuzz vs Lean model" \ --dir "${{ runner.temp }}/fuzz-out" --create-only-if "${{ runner.temp }}/fuzz-out/findings" \ - "${{ github.event.pull_request.number }}" "${{ steps.fuzz.outcome }}" || true + "${{ github.event.pull_request.number }}" "${{ job.status }}" || true - name: summary if: always() run: | diff --git a/differential/src/harness.rs b/differential/src/harness.rs index 0a5aa95e..43b48c2e 100644 --- a/differential/src/harness.rs +++ b/differential/src/harness.rs @@ -26,7 +26,7 @@ use core::fmt::Write as _; /// Selector count for newly generated inputs. Keep in sync with `lean/input_format.py`. /// Keep operation IDs permanently assigned. -pub const NOPS: usize = 61; +pub const NOPS: usize = 65; /// Unversioned inputs retain their original operation decoding. pub const LEGACY_NOPS: usize = 56; /// Input header marker, followed by a little-endian u16 selector count (1..=256). @@ -262,6 +262,16 @@ pub trait ReadSource: /// `None` when the zipper does not implement the trait. fn to_next_get_val_probe(&mut self) -> Option<(bool, Option, bool)>; + /// Convex operations use valued paths. ACT cannot materialise the RHS. + fn convex( + &mut self, + _left: &PathMap, + _subtract: bool, + _zipper: bool, + ) -> Option> { + None + } + fn do_graft>(&self, _wz: &mut W) -> bool { false } fn do_graft_masked>(&self, _wz: &mut W, _m: ByteMask, _ru: bool) -> bool { false } /// Currently unused: op 54 is quarantined (lean/FINDINGS.md #15). Kept so @@ -280,6 +290,23 @@ pub trait ReadSource: } impl<'a, 'p> ReadSource for ReadZipperUntracked<'a, 'p, u64> { + fn convex(&mut self, left: &PathMap, subtract: bool, zipper: bool) -> Option> { + use pathmap::experimental::convex::*; + Some(if zipper { + let mut out = PathMap::new(); + if subtract { + zipper_convex_subtract(&mut left.read_zipper(), self, &mut out.write_zipper()); + } else { + zipper_convex_meet(&mut left.read_zipper(), self, &mut out.write_zipper()); + } + out + } else if subtract { + convex_subtract(left, &self.make_map()) + } else { + convex_meet(left, &self.make_map()) + }) + } + fn dump_fork(&self) -> String { dump_fork(self) } @@ -968,6 +995,26 @@ pub fn run_ops( let v = get!(d.u8()) as u64; ("set_val_at", show_val(wz.set_val_at(&p, v).as_ref())) } + 61..=64 => { + let name = match op { + 61 => "convex_meet", + 62 => "convex_subtract", + 63 => "zipper_convex_meet", + _ => "zipper_convex_subtract", + }; + let ret = if let Some(result) = rz.convex(&wz.make_map(), op % 2 == 0, op >= 63) { + // Convex algebra specifies values, not bare structure. + // Rebuild the result's valued projection before grafting, + // matching Map.selectConvexSupport in the Lean model. + // Do not truncate: subsequent ops observe the entire map. + let canonical: PathMap = result.iter().map(|(p, v)| (p, *v)).collect(); + wz.graft_map(canonical); + "-" + } else { + SKIP_ACT + }; + (name, ret.to_string()) + } 47 => { let t = get!(d.modn(2)); // The blind-zipper addition: `descend_until` reporting the @@ -1014,7 +1061,7 @@ mod input_format_tests { #[test] fn input_header_count_controls_decoding_independently_of_current_operation_count() { - for count in [1u16, 32, 56, 57, 58, 256] { + for count in [1u16, 32, 56, 57, 58, 61, 65, 256] { let mut bytes = WIRE_MAGIC.to_vec(); bytes.extend_from_slice(&count.to_le_bytes()); bytes.extend(0..=255); @@ -1055,6 +1102,83 @@ mod input_format_tests { } } + #[test] + fn convex_programs_prune_to_stability_and_preserve_left_payloads() { + // A = {root, 0, 01}, B = {root, 0, 02}. A single pruning pass + // wrongly keeps root instead of pruning the whole chain. + let seeds = [ + 3, 0, 10, 1, 0, 11, 2, 0, 1, 12, 3, 0, 20, 1, 0, 21, 2, 0, 2, 22, 0, 0, + ]; + for (op, name) in [ + (61, "convex_meet"), + (62, "convex_subtract"), + (63, "zipper_convex_meet"), + (64, "zipper_convex_subtract"), + ] { + let mut bytes = input_header(); + bytes.extend_from_slice(&seeds); + bytes.extend_from_slice(&[op, op]); + let trace = run(&bytes, true); + let expected = if op % 2 == 0 { + "MAP0 _:10,00:11,0001:12" + } else { + "MAP0 _:-" + }; + assert!(trace.contains(expected), "{trace}"); + assert!(trace.contains(&format!("1 {name} ret=-")), "{trace}"); + let act = run_act(&bytes, false); + assert!(act.contains(&format!("0 {name} ret=skip:act")), "{act}"); + assert!(act.contains("MAP0 _:10,00:11,0001:12"), "{act}"); + assert!(emit_repro(&bytes, 256).contains(&format!("::{name}("))); + + // Same domain, different payloads: both kernels retain the LHS + // on meet and remove everything on subtract. + let mut equal = input_header(); + equal.extend_from_slice(&[2, 0, 10, 1, 0, 11, 2, 0, 20, 1, 0, 21, 0, 0, op]); + let trace = run(&equal, true); + let expected = if op % 2 == 0 { + "MAP0 _:-" + } else { + "MAP0 _:10,00:11" + }; + assert!(trace.contains(expected), "{trace}"); + } + } + + #[test] + fn convex_programs_use_relative_focus_and_ignore_bare_extensions() { + for op in 61..=64 { + let mut bytes = input_header(); + bytes.extend_from_slice(&[ + 3, 1, 3, 99, 1, 1, 7, 2, 1, 0, 8, // LHS: outside, root, tip. + 1, 2, 2, 0, 42, // RHS: matching tip, different value. + 1, 1, 1, 2, // Roots [1], [2]. + 0, 0, 2, 0, 3, 29, 4, 0, // Create bare extension of LHS tip, reset. + op, 60, 1, 1, 55, // Following write tests operand alignment and restored focus. + ]); + let trace = run(&bytes, true); + let expected = if op % 2 == 0 { + "MAP0 _:-,01:-,0101:55,03:99" + } else { + "MAP0 _:-,01:-,0100:8,0101:55,03:99" + }; + assert!(trace.contains(expected), "{trace}"); + assert!(trace.contains("4 set_val_at ret=- W=_ o01"), "{trace}"); + assert!(trace.contains("R=_ o02"), "{trace}"); + } + } + + #[test] + fn old_selector_count_does_not_decode_convex_operations() { + let mut bytes = WIRE_MAGIC.to_vec(); + bytes.extend_from_slice(&61u16.to_le_bytes()); + bytes.extend_from_slice(&[0, 0, 0, 0, 61, 0, 1, 2]); + let trace = run(&bytes, true); + assert!(trace.contains("0 descend_to"), "{trace}"); + assert!(!trace.contains("convex"), "{trace}"); + assert!(emit_repro(&bytes, 256).contains("wz.descend_to(&[2u8]);")); + } + #[test] fn trace_and_reproducer_decode_relative_writes() { let mut bytes = input_header(); diff --git a/differential/src/repro.rs b/differential/src/repro.rs index 98bc1fba..57e3c87d 100644 --- a/differential/src/repro.rs +++ b/differential/src/repro.rs @@ -221,6 +221,15 @@ pub fn emit_repro(bytes: &[u8], upto: usize) -> String { 59 => { let _t = g!(d.modn(2)); "rz.to_prev_val();".to_string() } 60 => { let p = g!(d.path(6)); let v = g!(d.u8()) as u64; format!("wz.set_val_at({}, {v});", rs_bytes(&p)) } + 61..=64 => { + let operation = if op % 2 == 0 { "convex_subtract" } else { "convex_meet" }; + let call = if op >= 63 { + format!("let mut result = PathMap::new(); pathmap::experimental::convex::zipper_{operation}(&mut left.read_zipper(), &mut rz, &mut result.write_zipper());") + } else { + format!("let result = pathmap::experimental::convex::{operation}(&left, &rz.make_map());") + }; + format!("{{ let left = wz.make_map(); {call} let canonical: PathMap = result.iter().map(|(p, v)| (p, *v)).collect(); wz.graft_map(canonical); }}") + } _ => "// nop".to_string(), }; o.push_str(&format!(" /* {step:3} */ {line}\n")); diff --git a/lean/PathMapModel/Check.lean b/lean/PathMapModel/Check.lean index d3213b0a..288833d5 100644 --- a/lean/PathMapModel/Check.lean +++ b/lean/PathMapModel/Check.lean @@ -250,6 +250,22 @@ wraps from the root, and stays within a zipper rooted below the map root. -/ #guard fixtures.all (subSelfEmptyVals ops) #guard fixtures.all (restrictSelf ops) +/-! Convex opcodes are operand-free, left-biased, and prune to stability. +These encoded examples also check ACT skips and compatibility with count 61. -/ +def convexProgram (op : UInt8) : ByteArray := ByteArray.mk <| + (Fuzz.wireMagic ++ [65, 0, + 3, 0, 10, 1, 0, 11, 2, 0, 1, 12, + 3, 0, 20, 1, 0, 21, 2, 0, 2, 22, 0, 0, op, op]).toArray + +#guard [61, 63].all (fun op => (Fuzz.run (convexProgram op)).contains "MAP0 _:-") +#guard [62, 64].all (fun op => + (Fuzz.run (convexProgram op)).contains "MAP0 _:10,00:11,0001:12") +#guard [61, 62, 63, 64].all (fun op => + (Fuzz.run (convexProgram op) 256 true).contains "MAP0 _:10,00:11,0001:12") +#guard ((Fuzz.run (ByteArray.mk + (Fuzz.wireMagic ++ [61, 0, 0, 0, 0, 0, 61, 0, 1, 2]).toArray)).head!).startsWith + "0 descend_to ret=02" + /-! ## Naive oracles `PathMap.join` / `meet` / `sub` are defined in terms of `ValOps`, which was diff --git a/lean/PathMapModel/Fuzz.lean b/lean/PathMapModel/Fuzz.lean index 99091931..41d5f046 100644 --- a/lean/PathMapModel/Fuzz.lean +++ b/lean/PathMapModel/Fuzz.lean @@ -1,4 +1,5 @@ import PathMapModel.Spec +import PathMapModel.ConvexMap /-! # Differential-fuzzing front end @@ -195,7 +196,12 @@ def showBool (b : Bool) : String := if b then "1" else "0" `op % selector_count` selects the operation (56 for headerless inputs). Ops `0`–`26` act on a target zipper chosen by a following `u8 % 2` byte (`0` = write zipper, -`1` = read zipper); ops `27`–`46` and `56` are write-zipper operations. -/ +`1` = read zipper); ops `27`–`46`, `56`, and `60`–`64` write at the focus. +Ops `61`/`62` apply native convex meet/subtract; `63`/`64` apply the zipper +implementations. They take no operands and replace the write focus with the +valued projection of the result, using the read focus as RHS. Bare result +structure is unspecified by convex algebra, so both interpreters canonicalise +it before later operations observe it. ACT skips these four operations. -/ /-- Input header marker. Must match `WIRE_MAGIC` in the Rust harness. -/ def wireMagic : List UInt8 := [80, 77, 70, 85, 90, 90, 1, 0] @@ -544,6 +550,16 @@ def step (s : St) (d : Dec) : Option (St × Dec) := do let (v, d) ← d.u8 let (old, z) := s.wz.setValAt p (UInt64.ofNat v.toNat) some (emit { s with wz := z } "set_val_at" (showVal old), d) + | 61 | 62 | 63 | 64 => do + let name := match op with + | 61 => "convex_meet" + | 62 => "convex_subtract" + | 63 => "zipper_convex_meet" + | _ => "zipper_convex_subtract" + if s.act then some (emit s name skipAct, d) else + let z := if op % 2 == 0 then s.wz.convexSubtract s.rz s.wz + else s.wz.convexMeet s.rz s.wz + some (emit { s with wz := z } name "-", d) | _ => some (emit s "nop" "-", d) /-- Run operations until the input is exhausted or `fuel` runs out. -/ diff --git a/lean/differential.py b/lean/differential.py index ec5da816..d18e240e 100755 --- a/lean/differential.py +++ b/lean/differential.py @@ -29,10 +29,10 @@ import sys import tempfile -from input_format import input_header, versioned_input +from input_format import NOPS, input_header, versioned_input ROOT = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) -ORACLE = os.path.join(ROOT, "lean", ".lake", "build", "bin", "pathmap-oracle") +ORACLE = os.environ.get("PATHMAP_ORACLE") or os.path.join(ROOT, "lean", ".lake", "build", "bin", "pathmap-oracle") # PATHMAP_TRACE / PATHMAP_ACT_TRACE override the search, for builds that live # in another target dir (CI builds two commits side by side). TRACE_CANDIDATES = [os.environ.get("PATHMAP_TRACE", "")] + [ @@ -483,8 +483,9 @@ class RandomInputs(InputSource): `randbytes` alone is ~39x faster than that loop. """ - def __init__(self, seed, count, maxlen): + def __init__(self, seed, count, maxlen, selectors=NOPS): self.seed, self.count, self.maxlen = seed, count, maxlen + self.header = input_header(selectors) def __len__(self): return self.count @@ -494,7 +495,80 @@ def name(self, idx): def get(self, idx): rng = random.Random((self.seed << 32) ^ idx) - return input_header() + rng.randbytes(rng.randrange(8, self.maxlen)) + return self.header + rng.randbytes(rng.randrange(8, self.maxlen)) + + +class ConvexInputs(InputSource): + """Stateful programs covering both kernels without unrelated known bugs. + + All four convex selectors run in every program. Seeded shapes include + shared chains, mismatched tips, root values and empty inputs; random shapes + share a small path pool. Writes between operations restore values so an + earlier empty result cannot make the rest of the program vacuous. + """ + + def __init__(self, seed, count): + self.seed, self.count = seed, count + + def __len__(self): + return self.count + + def name(self, idx): + return "convex#%05d" % idx + + def get(self, idx): + rng = random.Random((self.seed << 32) ^ idx) + shapes = [ + ([(), (0,), (0, 1)], [(), (0,), (0, 2)]), + ([(), (0,)], [()]), + ([()], [()]), + ([(0,)], [(0,), (0, 1)]), + ([], [()]), + ([(), (0,)], []), + ] + if idx % 8 < len(shapes): + left, right = shapes[idx % 8] + else: + pool = list(dict.fromkeys(tuple(rng.randrange(3) for _ in range(rng.randrange(4))) + for _ in range(12))) + left = rng.sample(pool, rng.randrange(min(7, len(pool)) + 1)) + right = rng.sample(pool, rng.randrange(min(7, len(pool)) + 1)) + layout = idx // 8 # Vary roots/focuses independently of the shape. + root0, root1 = ([3] if layout & 1 else []), ([2] if layout & 2 else []) + focus0, focus1 = ([1] if layout & 4 else []), ([0] if layout & 8 else []) + left = [(list(p), rng.randrange(128)) for p in left] + right = [(root1 + focus1 + list(p), rng.randrange(128, 256)) for p in right] + blob = bytearray(input_header()) + + def path(p): + blob.extend([len(p), *p]) + + # Outside the write focus, so every operation must preserve this value. + outside = [([0], 255)] if root0 or focus0 else [] + for entries in (outside, right): + blob.append(len(entries)) + for p, v in entries: + path(p) + blob.append(v) + path(root0) + path(root1) + for target, focus in ((0, focus0), (1, focus1)): + blob.extend([18, target]) # move_to_path + path(focus) + for op in (61, 63, 62, 64): + for p, v in left: + blob.append(60) # set_val_at, relative to the current focus + path(p) + blob.append(v) + # A dangling path must not turn an ancestor into an interior value. + blob.extend([0, 0]) + path((rng.choice(left)[0] if left else []) + [3]) + blob.extend([29, 18, 0]) + path(focus0) + blob.append(op) + # Compose the operation with itself, checking stable results. + blob.append(op) + return bytes(blob) class FileInputs(InputSource): @@ -580,6 +654,10 @@ def main(): ap = argparse.ArgumentParser() ap.add_argument("files", nargs="*") ap.add_argument("--random", type=int, default=0, help="generate N random inputs") + ap.add_argument("--convex", type=int, default=0, help="generate N focused convex programs") + ap.add_argument("--selectors", type=int, default=NOPS, choices=range(1, NOPS + 1), + metavar="N", help="selector count for random inputs (for baseline replay)") + ap.add_argument("--strict", action="store_true", help="fail on known divergences too") ap.add_argument("--seed", type=int, default=0) ap.add_argument("--maxlen", type=int, default=300) ap.add_argument("-v", "--verbose", action="store_true") @@ -608,7 +686,9 @@ def main(): if args.files: sources.append(FileInputs(args.files)) if args.random: - sources.append(RandomInputs(args.seed, args.random, args.maxlen)) + sources.append(RandomInputs(args.seed, args.random, args.maxlen, args.selectors)) + if args.convex: + sources.append(ConvexInputs(args.seed, args.convex)) source = ChainInputs(sources) n_inputs = len(source) @@ -640,7 +720,7 @@ def record(idx, msg): if args.verbose: print("ok %s" % name) return False - note = classify(msg) + note = None if args.strict else classify(msg) if note: known[note] = known.get(note, 0) + 1 if args.verbose: diff --git a/lean/input_format.py b/lean/input_format.py index 2684d338..df9385d4 100644 --- a/lean/input_format.py +++ b/lean/input_format.py @@ -3,7 +3,7 @@ WIRE_MAGIC = b"PMFUZZ\x01\x00" LEGACY_NOPS = 56 # Keep in sync with NOPS in differential/src/harness.rs. -NOPS = 61 +NOPS = 65 HEADER_SIZE = len(WIRE_MAGIC) + 2 diff --git a/lean/test_input_format.py b/lean/test_input_format.py index 9939c44f..c423bae2 100644 --- a/lean/test_input_format.py +++ b/lean/test_input_format.py @@ -3,7 +3,7 @@ import unittest from unittest.mock import patch -from differential import RandomInputs +from differential import ConvexInputs, RandomInputs from input_format import HEADER_SIZE, NOPS, WIRE_MAGIC, input_header, versioned_input import shrink @@ -22,12 +22,62 @@ def test_random_inputs_always_have_current_header(self): self.assertTrue(blob.startswith(input_header())) self.assertEqual(blob, source.get(i)) + def test_random_baseline_encoding_keeps_identical_payload(self): + current, baseline = RandomInputs(7, 20, 300), RandomInputs(7, 20, 300, selectors=61) + for i in range(len(current)): + self.assertEqual(baseline.get(i)[:HEADER_SIZE], input_header(61)) + self.assertEqual(current.get(i)[HEADER_SIZE:], baseline.get(i)[HEADER_SIZE:]) + + def test_convex_programs_are_deterministic_and_cover_every_kernel(self): + source = ConvexInputs(7, 128) + for i in range(len(source)): + blob = source.get(i) + self.assertEqual(blob, source.get(i)) + self.assertTrue(blob.startswith(input_header())) + # Decode the generated subset to verify instruction boundaries: + # matching opcode bytes inside a path or payload would be vacuous. + pos = HEADER_SIZE + + def skip_path(): + nonlocal pos + length = blob[pos] + self.assertLess(length, 6) + pos += length + 1 + + for _ in range(2): + count = blob[pos] + self.assertLess(count, 8) + pos += 1 + for _ in range(count): + skip_path() + pos += 1 + skip_path() + skip_path() + ops = [] + while pos < len(blob): + op = blob[pos] + pos += 1 + ops.append(op) + if op in (0, 18): + pos += 1 # target + skip_path() + elif op == 60: + skip_path() + pos += 1 # value + else: + self.assertIn(op, (29, 61, 62, 63, 64)) + self.assertEqual(pos, len(blob)) + self.assertLessEqual(len(ops), 256) + for op in range(61, 65): + self.assertEqual(ops.count(op), 2) + self.assertNotEqual(source.get(7), ConvexInputs(8, 128).get(7)) + def test_legacy_inputs_get_applicable_count(self): for payload in [b"", b"\x00\x00\x00\x00\x38", b"x" + WIRE_MAGIC]: self.assertEqual(versioned_input(payload), input_header(56) + payload) def test_versioned_inputs_keep_recorded_count(self): - for count in [1, 56, 57, 58, 256]: + for count in [1, 56, 57, 58, 61, 65, 256]: blob = input_header(count) + bytes(range(256)) self.assertEqual(versioned_input(blob), blob) From a3bf2e7c4ef36e5503cdf778c45af095b61d8521 Mon Sep 17 00:00:00 2001 From: adamv-symbolica Date: Wed, 18 Nov 2026 17:53:14 +0000 Subject: [PATCH 09/15] Scale convex and path-set test workloads under Miri --- src/experimental/convex/native/tests.rs | 8 ++++- tests/convex.rs | 43 ++++++++++++++++--------- tests/path_sets.rs | 12 +++++-- 3 files changed, 44 insertions(+), 19 deletions(-) diff --git a/src/experimental/convex/native/tests.rs b/src/experimental/convex/native/tests.rs index 94c7c245..072866bd 100644 --- a/src/experimental/convex/native/tests.rs +++ b/src/experimental/convex/native/tests.rs @@ -165,6 +165,11 @@ fn matrix() { for rt in TAGS { for lp in 0..8 { for rp in 0..8 { + // Retain every tag pair and every pattern on each side; + // the full Cartesian pattern matrix runs in native tests. + if cfg!(miri) && rp != lp && rp != (lp + 1) % 8 { + continue; + } let (l, lk) = fixture(lt, lp, 0); let (r, rk) = fixture(rt, rp, 1); let lr = reference(&l, &lk); @@ -253,7 +258,8 @@ fn native_spines_use_bounded_call_depth() { .spawn(|| { let mut a = Node::new_in(list(vec![(vec![0], Payload::Val(7))]), global_alloc()); let mut b = Node::new_in(list(vec![(vec![1], Payload::Val(9))]), global_alloc()); - for i in 0..12000 { + let depth = if cfg!(miri) { 64 } else { 12000 }; + for i in 0..depth { if i % 2 == 0 { a = Node::new_in( list(vec![ diff --git a/tests/convex.rs b/tests/convex.rs index 04004c5c..7f7786ce 100644 --- a/tests/convex.rs +++ b/tests/convex.rs @@ -93,7 +93,10 @@ fn spaces() -> Vec { vec![1, 0], vec![1, 1], ]; - (0..128) + // Keep roots, a chain, and a fork in the exhaustive Miri matrix. + #[cfg(miri)] + let ps = &ps[..4]; + (0..1usize << ps.len()) .map(|mask| { ps.iter() .enumerate() @@ -137,7 +140,11 @@ fn dangling_paths_are_not_tips() { } #[test] fn compressed_edges_dense_nodes_and_shared_subtrees() { - for width in [1usize, 2, 16, 80, 256] { + #[cfg(not(miri))] + let widths = [1usize, 2, 16, 80, 256]; + #[cfg(miri)] + let widths = [2usize, 17]; + for width in widths { let mut a = Space::new(); let mut b = Space::new(); a.insert(vec![]); @@ -235,10 +242,11 @@ fn focused_zipper_restores_cursors_and_preserves_outside() { } #[test] fn deep_chain_prunes_to_stability() { - let a: Space = (0..1024).map(|n| vec![0; n]).collect(); + let depth = if cfg!(miri) { 32 } else { 1024 }; + let a: Space = (0..depth).map(|n| vec![0; n]).collect(); let mut b = a.clone(); - b.remove(&vec![0; 1023]); - b.insert([vec![0; 1022], vec![1]].concat()); + b.remove(&vec![0; depth - 1]); + b.insert([vec![0; depth - 2], vec![1]].concat()); let ma = map(&a); let mb = map(&b); assert_eq!(convex_meet(&ma, &mb).val_count(), 0); @@ -256,10 +264,13 @@ fn deep_chain_prunes_to_stability() { fn randomized_shapes_and_partial_sharing() { use rand::{Rng, SeedableRng, rngs::StdRng}; let mut rng = StdRng::seed_from_u64(0xC0A7E); - for _ in 0..300 { + let rounds = if cfg!(miri) { 4 } else { 300 }; + let max_paths = if cfg!(miri) { 10 } else { 80 }; + let max_len = if cfg!(miri) { 12 } else { 90 }; + for _ in 0..rounds { let mut pool = Space::new(); - for _ in 0..rng.random_range(1..80) { - let len = rng.random_range(0..90); + for _ in 0..rng.random_range(1..max_paths) { + let len = rng.random_range(0..max_len); let p: Vec = (0..len).map(|_| rng.random_range(0..6)).collect(); pool.insert(p[..rng.random_range(0..=len)].to_vec()); pool.insert(p); @@ -308,7 +319,8 @@ fn subtree_reuse_does_not_clone_payloads() { let clones = Arc::new(AtomicUsize::new(0)); let mut a = PathMap::new(); let mut mask = PathMap::<()>::new(); - for n in 0..2000u32 { + let count = if cfg!(miri) { 32u32 } else { 2000 }; + for n in 0..count { let p = n.to_be_bytes(); a.set_val_at(p, Counted(clones.clone())); a.set_val_at([p.as_slice(), &[0]].concat(), Counted(clones.clone())); @@ -316,8 +328,8 @@ fn subtree_reuse_does_not_clone_payloads() { } let shared = a.clone(); clones.store(0, Ordering::Relaxed); - assert_eq!(convex_meet(&a, &shared).val_count(), 4000); - assert_eq!(convex_subtract(&a, &mask).val_count(), 4000); + assert_eq!(convex_meet(&a, &shared).val_count(), 2 * count as usize); + assert_eq!(convex_subtract(&a, &mask).val_count(), 2 * count as usize); assert_eq!(convex_subtract(&a, &shared).val_count(), 0); assert_eq!(clones.load(Ordering::Relaxed), 0); let mut out = PathMap::new(); @@ -326,7 +338,7 @@ fn subtree_reuse_does_not_clone_payloads() { &mut shared.read_zipper(), &mut out.write_zipper(), ); - assert_eq!(out.val_count(), 4000); + assert_eq!(out.val_count(), 2 * count as usize); assert_eq!(clones.load(Ordering::Relaxed), 0); } @@ -362,17 +374,18 @@ fn extracted_subtries_and_empty_bare_shared_roots() { #[test] fn zipper_head_cell_nodes_match_dense_and_list_nodes() { - let a: Space = (0..=255u8) + let last = if cfg!(miri) { 17u8 } else { 255 }; + let a: Space = (0..=last) .flat_map(|b| [vec![0, b], vec![0, b, 0], vec![0, b, 1]]) .collect(); - let b: Space = (0..=255u8) + let b: Space = (0..=last) .flat_map(|b| [vec![0, b], vec![0, b, b % 3]]) .collect(); let mut ma = map(&a); let mut mb = map(&b); for m in [&mut ma, &mut mb] { let head = m.zipper_head(); - for b in 0..=255u8 { + for b in 0..=last { let path = [0, b, 255]; let mut z = head.write_zipper_at_exclusive_path(path).unwrap(); z.create_path(); diff --git a/tests/path_sets.rs b/tests/path_sets.rs index 3705bd3d..5f755086 100644 --- a/tests/path_sets.rs +++ b/tests/path_sets.rs @@ -50,7 +50,10 @@ fn spaces() -> Vec { vec![1, 0], vec![1, 1], ]; - (0..128) + // Keep roots, a chain, and a fork in the exhaustive Miri matrix. + #[cfg(miri)] + let ps = &ps[..4]; + (0..1usize << ps.len()) .map(|mask| { ps.iter() .enumerate() @@ -176,7 +179,9 @@ fn focus_relative_replacement_and_restoration() { fn deep_compressed_stem_and_all_bytes() { // Match the core long-key test's dense-only depth limit: those nodes // expand every byte and use recursive teardown. - let depth = if cfg!(feature = "all_dense_nodes") { + let depth = if cfg!(miri) { + 97 + } else if cfg!(feature = "all_dense_nodes") { 2048 } else { 20_000 @@ -278,7 +283,8 @@ impl ZipperMoving for Counted { #[test] fn linear_work_and_basis_cutoff() { - for h in 2..=9 { + let max_height = if cfg!(miri) { 4 } else { 9 }; + for h in 2..=max_height { let n = (1 << (h + 1)) - 1; let mut a = Counted::new(h); let mut out = PathMap::new(); From 7e281fd1dfd308801ef4e762e6949da5a4e1835a Mon Sep 17 00:00:00 2001 From: adamv-symbolica Date: Wed, 18 Nov 2026 17:54:07 +0000 Subject: [PATCH 10/15] Move convex algebra onto the pruned Lean model Use canonical PrunedMap Unit spaces and the existing Zippy operations. Move the convex definitions, laws, and checks into PrunedModel/Convex, reuse canonical lookup and prefix lemmas, and remove the redundant list normalizer and mixed-map support implementation. Keep the mixed program oracle connected through a projection adapter and include the new directory in the CI proof audit and Rust law-catalog check. --- .github/workflows/ci.yml | 6 +- lean/PathMapModel.lean | 9 - lean/PathMapModel/ClosedChecks.lean | 74 ------- lean/PathMapModel/ConvexMap.lean | 172 --------------- lean/PathMapModel/Fuzz.lean | 2 +- lean/PathMapModel/PathSetChecks.lean | 47 ---- lean/PathMapModel/PathSets.lean | 205 ------------------ lean/PathMapModel/RetainChecks.lean | 40 ---- lean/PrunedModel.lean | 1 + lean/PrunedModel/Convex.lean | 5 + .../Convex/Algebra.lean} | 66 +++--- .../Convex/Boolean.lean} | 70 +++--- .../Convex/Checks.lean} | 51 ++--- .../Convex}/Closed.lean | 45 ++-- lean/PrunedModel/Convex/ClosedChecks.lean | 75 +++++++ .../Convex}/ClosedGeometry.lean | 30 ++- .../Convex}/ClosedOperators.lean | 39 ++-- .../Convex/Geometry.lean} | 19 +- lean/PrunedModel/Convex/Map.lean | 74 +++++++ lean/PrunedModel/Convex/Mixed.lean | 22 ++ .../Convex/Morphisms.lean} | 20 +- .../Convex/Order.lean} | 34 +-- lean/PrunedModel/Convex/Path.lean | 38 ++++ .../Convex}/PathSetAlgebra.lean | 25 ++- .../Convex}/PathSetCardinality.lean | 106 +++++---- .../Convex}/PathSetCertificates.lean | 53 ++--- lean/PrunedModel/Convex/PathSetChecks.lean | 48 ++++ .../Convex}/PathSetDepth.lean | 32 +-- .../Convex}/PathSetExtrema.lean | 34 +-- .../Convex}/PathSetFork.lean | 20 +- .../Convex}/PathSetGeometry.lean | 8 +- .../Convex}/PathSetLCP.lean | 14 +- .../Convex}/PathSetLaws.lean | 73 ++++--- .../Convex}/PathSetMasks.lean | 16 +- .../Convex}/PathSetPowers.lean | 56 +++-- .../Convex}/PathSetProduct.lean | 61 +++--- .../Convex}/PathSetProofs.lean | 86 ++++---- .../Convex}/PathSetRecursive.lean | 87 +++----- .../Convex}/PathSetRoots.lean | 55 ++--- .../Convex}/PathSetStructure.lean | 72 +----- .../Convex}/PathSetUpdates.lean | 55 ++--- lean/PrunedModel/Convex/PathSets.lean | 124 +++++++++++ .../Convex/Pruning.lean} | 21 +- .../Convex}/Retain.lean | 65 +++--- lean/PrunedModel/Convex/RetainChecks.lean | 41 ++++ .../Convex}/RetainConvex.lean | 19 +- lean/PrunedModel/Convex/Space.lean | 106 +++++++++ .../Convex/Union.lean} | 37 ++-- tests/support/path_set_laws.rs | 2 +- 49 files changed, 1188 insertions(+), 1272 deletions(-) delete mode 100644 lean/PathMapModel/ClosedChecks.lean delete mode 100644 lean/PathMapModel/ConvexMap.lean delete mode 100644 lean/PathMapModel/PathSetChecks.lean delete mode 100644 lean/PathMapModel/PathSets.lean delete mode 100644 lean/PathMapModel/RetainChecks.lean create mode 100644 lean/PrunedModel/Convex.lean rename lean/{PathMapModel/Convex.lean => PrunedModel/Convex/Algebra.lean} (83%) rename lean/{PathMapModel/ConvexBoolean.lean => PrunedModel/Convex/Boolean.lean} (69%) rename lean/{PathMapModel/ConvexChecks.lean => PrunedModel/Convex/Checks.lean} (61%) rename lean/{PathMapModel => PrunedModel/Convex}/Closed.lean (88%) create mode 100644 lean/PrunedModel/Convex/ClosedChecks.lean rename lean/{PathMapModel => PrunedModel/Convex}/ClosedGeometry.lean (89%) rename lean/{PathMapModel => PrunedModel/Convex}/ClosedOperators.lean (91%) rename lean/{PathMapModel/ConvexGeometry.lean => PrunedModel/Convex/Geometry.lean} (94%) create mode 100644 lean/PrunedModel/Convex/Map.lean create mode 100644 lean/PrunedModel/Convex/Mixed.lean rename lean/{PathMapModel/ConvexMorphisms.lean => PrunedModel/Convex/Morphisms.lean} (90%) rename lean/{PathMapModel/ConvexOrder.lean => PrunedModel/Convex/Order.lean} (90%) create mode 100644 lean/PrunedModel/Convex/Path.lean rename lean/{PathMapModel => PrunedModel/Convex}/PathSetAlgebra.lean (92%) rename lean/{PathMapModel => PrunedModel/Convex}/PathSetCardinality.lean (66%) rename lean/{PathMapModel => PrunedModel/Convex}/PathSetCertificates.lean (63%) create mode 100644 lean/PrunedModel/Convex/PathSetChecks.lean rename lean/{PathMapModel => PrunedModel/Convex}/PathSetDepth.lean (79%) rename lean/{PathMapModel => PrunedModel/Convex}/PathSetExtrema.lean (91%) rename lean/{PathMapModel => PrunedModel/Convex}/PathSetFork.lean (81%) rename lean/{PathMapModel => PrunedModel/Convex}/PathSetGeometry.lean (98%) rename lean/{PathMapModel => PrunedModel/Convex}/PathSetLCP.lean (95%) rename lean/{PathMapModel => PrunedModel/Convex}/PathSetLaws.lean (87%) rename lean/{PathMapModel => PrunedModel/Convex}/PathSetMasks.lean (94%) rename lean/{PathMapModel => PrunedModel/Convex}/PathSetPowers.lean (60%) rename lean/{PathMapModel => PrunedModel/Convex}/PathSetProduct.lean (80%) rename lean/{PathMapModel => PrunedModel/Convex}/PathSetProofs.lean (77%) rename lean/{PathMapModel => PrunedModel/Convex}/PathSetRecursive.lean (74%) rename lean/{PathMapModel => PrunedModel/Convex}/PathSetRoots.lean (79%) rename lean/{PathMapModel => PrunedModel/Convex}/PathSetStructure.lean (63%) rename lean/{PathMapModel => PrunedModel/Convex}/PathSetUpdates.lean (76%) create mode 100644 lean/PrunedModel/Convex/PathSets.lean rename lean/{PathMapModel/ConvexPruning.lean => PrunedModel/Convex/Pruning.lean} (94%) rename lean/{PathMapModel => PrunedModel/Convex}/Retain.lean (88%) create mode 100644 lean/PrunedModel/Convex/RetainChecks.lean rename lean/{PathMapModel => PrunedModel/Convex}/RetainConvex.lean (83%) create mode 100644 lean/PrunedModel/Convex/Space.lean rename lean/{PathMapModel/ConvexUnion.lean => PrunedModel/Convex/Union.lean} (53%) diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index 80f47282..a9d4be49 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -201,7 +201,7 @@ jobs: if grep -n 'declaration uses .sorry.' lake.log; then echo "::error::a declaration uses sorry"; exit 1 fi - if grep -rn "\bsorry\b\|^axiom " lean/PathMapModel lean/Main.lean; then + if grep -rn "\bsorry\b\|^axiom " lean/PathMapModel lean/PrunedModel lean/Main.lean lean/PrunedMain.lean; then echo "::error::sorry or axiom in the model sources"; exit 1 fi - name: summary @@ -212,9 +212,9 @@ jobs: echo echo "| file | theorems | guards |" echo "|---|---:|---:|" - for f in lean/PathMapModel/*.lean; do + for f in lean/PathMapModel/*.lean lean/PrunedModel/*.lean lean/PrunedModel/Convex/*.lean; do t=$(grep -c '^theorem\|^lemma' "$f" || true); g=$(grep -c '#guard' "$f" || true) - [ "$t$g" = "00" ] || echo "| $(basename "$f") | $t | $g |" + [ "$t$g" = "00" ] || echo "| ${f#lean/} | $t | $g |" done echo echo "$(grep -c 'declaration uses' lake.log || true) declaration(s) use sorry; $(grep -c '^warning' lake.log || true) warning(s) from lake build." diff --git a/lean/PathMapModel.lean b/lean/PathMapModel.lean index e97c39e0..d2354b43 100644 --- a/lean/PathMapModel.lean +++ b/lean/PathMapModel.lean @@ -6,12 +6,3 @@ import PathMapModel.Map import PathMapModel.Spec import PathMapModel.Fuzz import PathMapModel.Check - -import PathMapModel.PathSets -import PathMapModel.PathSetLaws -import PathMapModel.PathSetProofs -import PathMapModel.PathSetChecks -import PathMapModel.PathSetCertificates -import PathMapModel.ConvexMap -import PathMapModel.RetainChecks -import PathMapModel.ClosedChecks diff --git a/lean/PathMapModel/ClosedChecks.lean b/lean/PathMapModel/ClosedChecks.lean deleted file mode 100644 index 3daedc60..00000000 --- a/lean/PathMapModel/ClosedChecks.lean +++ /dev/null @@ -1,74 +0,0 @@ -import PathMapModel.ClosedOperators - -/-! Kernel-checked counterexamples delimit the closed algebra. The explicit closure -checks in the lattice examples prevent failures from being blamed on unclosed inputs. -/ -namespace PathMapModel.PathSpace - -theorem completion_not_union_preserving : - equiv (completion (union [[0]] [[1]])) (union (completion [[0]]) (completion [[1]])) = false := by decide - -theorem completion_not_inter_preserving : - equiv (completion (inter [[]] [[0],[1]])) (inter (completion [[]]) (completion [[0],[1]])) = false := by decide - -theorem completion_retain_bound_strict : - equiv (completion (retain [[0],[1]] [[]])) (retain (completion [[0],[1]]) [[]]) = false := by decide - -theorem completion_raffinate_bound_strict : - equiv (completion (raffinate [[0],[1]] [[0]])) (raffinate (completion [[0],[1]]) [[0]]) = false := by decide - -theorem completion_convexMeet_bound_strict : - equiv (completion (convexMeet [[],[0]] [[0],[1]])) - (convexMeet (completion [[],[0]]) (completion [[0],[1]])) = false := by decide - -theorem completion_convexSubtract_bound_strict : - equiv (completion (convexSubtract [[0],[1]] [[0]])) - (convexSubtract (completion [[0],[1]]) [[0]]) = false := by decide - -theorem closed_restrict_needs_closed_mask : - equiv (completion [[],[0],[1]]) [[],[0],[1]] = true ∧ - equiv (completion (restrict [[],[0],[1]] [[0],[1]])) (restrict [[],[0],[1]] [[0],[1]]) = false := by decide - -theorem lcp_not_intersection : - equiv (lcpProduct [[]] [[0]]) (inter [[]] [[0]]) = false := by decide - -theorem lcp_not_lattice_absorption : - equiv (lcpProduct [[0]] (completion (union [[0]] [[]]))) [[0]] = false := by decide - -theorem lcp_inter_bound_strict : - equiv (lcpProduct [[]] (inter [[]] [[0]])) (inter (lcpProduct [[]] [[]]) (lcpProduct [[]] [[0]])) = false := by decide - -theorem closed_lattice_not_distributive : - let a : PathSpace := [[]]; let b := [[0]]; let c := [[1]] - equiv (completion a) a = true ∧ equiv (completion b) b = true ∧ equiv (completion c) c = true ∧ - equiv (inter a (completion (union b c))) (completion (union (inter a b) (inter a c))) = false := by decide - -theorem closed_lattice_not_modular : - let a : PathSpace := [[0]]; let b := [[1]]; let c := [[],[0]] - equiv (completion a) a = true ∧ equiv (completion b) b = true ∧ equiv (completion c) c = true ∧ - subset a c = true ∧ - equiv (completion (union a (inter b c))) (inter (completion (union a b)) c) = false := by decide - -theorem lcp_retain_bound_strict : - equiv (lcpProduct (retain [[]] [[]]) (retain [[0]] [[]])) - (retain (lcpProduct [[]] [[0]]) (lcpProduct [[]] [[]])) = false := by decide - -theorem completion_not_determined_by_hull : - equiv (hull [[0]]) (hull [[],[0]]) = true ∧ - equiv (completion [[0]]) (completion [[],[0]]) = false := by decide - -/-- L closes the divergence operation by including comparable pairs; completing -its strict-divergence output alone cannot recover those pairs. -/ -theorem lcp_not_completed_divergence : - equiv (completion (divergence [[]] [[]])) (lcpProduct [[]] [[]]) = false := by decide - -theorem lcpLE_not_inclusion : - equiv (lcpProduct [[]] [[0]]) [[]] = true ∧ subset [[]] [[0]] = false := by decide - -theorem lcpLE_not_coverage : - covers [[0]] [[],[0]] = true ∧ equiv (lcpProduct [[0]] [[],[0]]) [[0]] = false := by decide - -theorem closure_does_not_add_intermediate_prefixes : - equiv (completion [[0,0],[0,1]]) [[0],[0,0],[0,1]] = true ∧ - ([] : Path) ∉ completion [[0,0],[0,1]] := by decide - -end PathMapModel.PathSpace diff --git a/lean/PathMapModel/ConvexMap.lean b/lean/PathMapModel/ConvexMap.lean deleted file mode 100644 index 925966d0..00000000 --- a/lean/PathMapModel/ConvexMap.lean +++ /dev/null @@ -1,172 +0,0 @@ -import PathMapModel.ConvexChecks - -/-! Adapters to the existing mixed model. Geometry uses valued paths only. -Payloads are selected from the left input; no ValOps combination is implicit. -The set algebra is commutative, but arbitrary left-biased payloads are not. -/ -namespace PathMapModel.PathMap.ConvexSupport -open PathMapModel.PathMap -theorem mem_prefixes (p q : Path) : p ∈ q.prefixes ↔ (p ≼ q) = true := by - simp only [Path.prefixes, List.mem_map, List.mem_range] - constructor - · rintro ⟨n,_,rfl⟩ - exact (Path.prefix_iff_list _ _).mpr (List.take_prefix n q) - · intro h - exact ⟨p.length,by have hl := Path.prefix_length h; omega, - ((List.prefix_iff_eq_take).mp ((Path.prefix_iff_list p q).mp h)).symm⟩ - -private theorem mem_insertValSorted_keys {V : Type} (kv : Path × V) - (xs : List (Path × V)) (p : Path) : - p ∈ (insertValSorted kv xs).map Prod.fst ↔ p = kv.1 ∨ p ∈ xs.map Prod.fst := by - induction xs with - | nil => simp [insertValSorted] - | cons x xs ih => - simp only [insertValSorted] - split <;> simp_all <;> grind - -private theorem mem_dedupVals_keys {V : Type} (xs : List (Path × V)) (p : Path) : - p ∈ (dedupVals xs).map Prod.fst ↔ p ∈ xs.map Prod.fst := by - have go : ∀ (ys acc : List (Path × V)), - p ∈ (ys.foldl (fun acc kv => - if acc.any (fun x => x.1 == kv.1) then acc else acc ++ [kv]) acc).map Prod.fst ↔ - p ∈ ys.map Prod.fst ∨ p ∈ acc.map Prod.fst := by - intro ys - induction ys with - | nil => simp - | cons kv ys ih => - intro acc - by_cases h : acc.any (fun x => x.1 == kv.1) = true - · have hk : kv.1 ∈ acc.map Prod.fst := by - obtain ⟨x,hx,he⟩ := List.any_eq_true.mp h - exact List.mem_map.mpr ⟨x,hx,by simpa using he⟩ - simp [List.foldl_cons, h, ih] - grind - · simp [List.foldl_cons, h, ih] - grind - simpa [dedupVals] using go xs [] - -theorem mem_normVals_keys {V : Type} (xs : List (Path × V)) (p : Path) : - p ∈ (normVals xs).map Prod.fst ↔ p ∈ xs.map Prod.fst := by - have go : ∀ (ys acc : List (Path × V)), - p ∈ (ys.foldl (fun acc kv => insertValSorted kv acc) acc).map Prod.fst ↔ - p ∈ ys.map Prod.fst ∨ p ∈ acc.map Prod.fst := by - intro ys - induction ys with - | nil => simp - | cons kv ys ih => - intro acc - simp [List.foldl_cons, ih, mem_insertValSorted_keys] - grind - simpa [normVals, mem_dedupVals_keys] using go (dedupVals xs) [] - -private theorem lookup_keys {V : Type} (xs : List (Path × V)) (p : Path) : - (xs.lookup p).isSome = true ↔ p ∈ xs.map Prod.fst := by - simp only [List.lookup_isSome_iff, beq_iff_eq, List.mem_map] - constructor <;> rintro ⟨kv,hkv,he⟩ <;> exact ⟨kv,hkv,he.symm⟩ - -private theorem lookup_function {V : Type} (ps : PathSpace) (f : Path → V) (p : Path) : - (ps.map fun q => (q,f q)).lookup p = - if ps.contains p then some (f p) else none := by - induction ps with - | nil => simp - | cons q qs ih => - by_cases h : p = q - · subst q; simp - · have hb : (p == q) = false := by simp [h] - simp [List.lookup_cons, hb, h, ih] - -theorem valAt_isSome_mem_paths {V : Type} (t : PathMap V) (p : Path) - (h : (t.valAt p).isSome = true) : p ∈ t.paths := by - apply (lookup_keys t.entries p).mp - cases hl : t.entries.lookup p with - | none => simp [valAt, entryAt, hl, Entry.val] at h - | some v => simp - -private theorem valuedKeys_filter {V : Type} (ps : PathSpace) (f : Path → Option V) : - (ps.filterMap fun p => (f p).map (p, ·)).map Prod.fst = - ps.filter fun p => (f p).isSome := by - induction ps with - | nil => rfl - | cons p ps ih => cases h : f p <;> simp [h, ih] - -theorem ofMap_eq_filter {V : Type} (t : PathMap V) : - PathSpace.ofMap t = t.paths.filter fun p => (t.valAt p).isSome := - valuedKeys_filter t.paths (fun p => (t.entryAt p).val) - -/-- The valued-only projection agrees with the actual mixed-model lookup. -/ -theorem mem_ofMap {V : Type} (t : PathMap V) (p : Path) : - p ∈ PathSpace.ofMap t ↔ (t.valAt p).isSome = true := by - rw [ofMap_eq_filter] - simp only [List.mem_filter] - exact ⟨And.right, fun h => ⟨valAt_isSome_mem_paths t p h,h⟩⟩ - -/-- Adding structural paths in the canonical constructor never changes values. -/ -theorem mk'_valAt {V : Type} (vs : List (Path × V)) (ps : PathSpace) (p : Path) : - (mk' vs ps).valAt p = (normVals vs).lookup p := by - let existing := Path.sortDedup - ((([] : Path) :: (ps ++ (normVals vs).map Prod.fst)).flatMap Path.prefixes) - change (match (existing.map fun q => (q,(normVals vs).lookup q)).lookup p with - | none => Entry.absent - | some none => Entry.bare - | some (some v) => Entry.valued v).val = _ - rw [lookup_function] - by_cases hp : existing.contains p = true - · simp only [hp, if_true] - cases (normVals vs).lookup p <;> rfl - · simp only [hp, Entry.val] - cases hl : (normVals vs).lookup p with - | none => rfl - | some v => - have hk : p ∈ (normVals vs).map Prod.fst := - (lookup_keys _ _).mp (by simp [hl]) - have he : p ∈ existing := by - apply (Path.mem_sortDedup _ _).mpr - exact List.mem_flatMap.mpr ⟨p,List.mem_cons.mpr - (Or.inr (List.mem_append.mpr (Or.inr hk))), - (mem_prefixes _ _).mpr (Path.prefix_self p)⟩ - exact False.elim (hp (List.contains_iff_mem.mpr he)) - -theorem mem_mk'_values {V : Type} (vs : List (Path × V)) (ps : PathSpace) (p : Path) : - p ∈ PathSpace.ofMap (mk' vs ps) ↔ p ∈ vs.map Prod.fst := by - rw [mem_ofMap, mk'_valAt, lookup_keys, mem_normVals_keys] - - -end PathMapModel.PathMap.ConvexSupport - -namespace PathMapModel.Map - -/-- Retain selected values and rebuild their structural skeleton. -/ -def selectConvexSupport {V : Type} (a : PathMap V) (support : PathSpace) : PathMap V := - PathMap.mk' (a.vals.filter (fun kv => support.contains kv.1)) [] - -def convexMeet {V W : Type} (a : PathMap V) (b : PathMap W) : PathMap V := - selectConvexSupport a (PathSpace.convexMeet (PathSpace.ofMap a) (PathSpace.ofMap b)) -def convexSubtract {V W : Type} (a : PathMap V) (b : PathMap W) : PathMap V := - selectConvexSupport a (PathSpace.convexSubtract (PathSpace.ofMap a) (PathSpace.ofMap b)) - -theorem selectConvexSupport_keys {V : Type} (a : PathMap V) (support : PathSpace) (p : Path) : - p ∈ PathSpace.ofMap (selectConvexSupport a support) ↔ p ∈ PathSpace.ofMap a ∧ p ∈ support := by - rw [selectConvexSupport,PathMap.ConvexSupport.mem_mk'_values] - simp only [PathSpace.ofMap,List.mem_map,List.mem_filter,List.contains_iff_mem] - grind - -theorem convexMeet_support {V W : Type} (a : PathMap V) (b : PathMap W) : - PathSpace.Same (PathSpace.ofMap (convexMeet a b)) (PathSpace.convexMeet (PathSpace.ofMap a) (PathSpace.ofMap b)) := by - intro p; rw [convexMeet,selectConvexSupport_keys]; constructor - · exact And.right - · intro h; exact ⟨((PathSpace.mem_convexMeet _ _ _).mp h).1,h⟩ - -theorem convexSubtract_support {V W : Type} (a : PathMap V) (b : PathMap W) : - PathSpace.Same (PathSpace.ofMap (convexSubtract a b)) (PathSpace.convexSubtract (PathSpace.ofMap a) (PathSpace.ofMap b)) := by - intro p; rw [convexSubtract,selectConvexSupport_keys]; constructor - · exact And.right - · intro h; exact ⟨PathSpace.convexSubtract_subset _ _ p h,h⟩ - -end PathMapModel.Map - -namespace PathMapModel.Zip -/-- Relative focus semantics, matching the existing Basis/Hull adapters. -/ -def convexMeet {V W : Type} (a : Zip V) (b : Zip W) (out : Zip V) : Zip V := - out.graftMap (Map.convexMeet a.makeMap b.makeMap) -def convexSubtract {V W : Type} (a : Zip V) (b : Zip W) (out : Zip V) : Zip V := - out.graftMap (Map.convexSubtract a.makeMap b.makeMap) -end PathMapModel.Zip diff --git a/lean/PathMapModel/Fuzz.lean b/lean/PathMapModel/Fuzz.lean index 41d5f046..c0252b25 100644 --- a/lean/PathMapModel/Fuzz.lean +++ b/lean/PathMapModel/Fuzz.lean @@ -1,5 +1,5 @@ import PathMapModel.Spec -import PathMapModel.ConvexMap +import PrunedModel.Convex.Mixed /-! # Differential-fuzzing front end diff --git a/lean/PathMapModel/PathSetChecks.lean b/lean/PathMapModel/PathSetChecks.lean deleted file mode 100644 index d2df394b..00000000 --- a/lean/PathMapModel/PathSetChecks.lean +++ /dev/null @@ -1,47 +0,0 @@ -import PathMapModel.PathSetLaws -import PathMapModel.PathSetProofs - -set_option maxRecDepth 4096 -set_option maxHeartbeats 0 -namespace PathMapModel.PathSetChecks -open PathSpace - -def small : List PathSpace := [[], [[]], [[0]], [[1]], [[],[0]], [[],[1]], [[0],[1]], [[],[0],[1]]] -def fixtures : List PathSpace := small ++ - [[[0],[0,0],[0,1]], [[0,0],[0,1]], [[0],[1,0],[1,1,0],[1,1,1]], - [[255,0],[255,255]], [[0,0,0],[1],[0,1],[0,0,1]]] - -#guard (small.flatMap fun a => small.flatMap fun b => small.flatMap fun c => - small.map fun f => (PathSetLaws.failures (PathSetLaws.all a b c f)).isEmpty).all id -#guard (fixtures.flatMap fun a => fixtures.map fun b => - (PathSetLaws.failures (PathSetLaws.unary a ++ PathSetLaws.binary a b)).isEmpty).all id -#guard (fixtures.flatMap fun a => (List.range 4).flatMap fun m => (List.range 4).map fun n => - (PathSetLaws.failures (PathSetLaws.powers a m n)).isEmpty).all id - --- Counterexamples are positively checked: these are NOT proposed rewrite rules. -#guard !equiv (divergence (divergence [[0,0]] [[0,1]]) [[1]]) - (divergence [[0,0]] (divergence [[0,1]] [[1]])) -#guard !equiv (divergence (inter [[0,0]] [[0,1]]) [[1]]) - (inter (divergence [[0,0]] [[1]]) (divergence [[0,1]] [[1]])) -#guard !equiv (divergence (diff [[0,0],[0,1]] [[0,0]]) [[1]]) - (diff (divergence [[0,0],[0,1]] [[1]]) (divergence [[0,0]] [[1]])) -#guard !equiv (restrict (divergence [[0,0]] [[0,1]]) [[0,0],[0,1]]) - (divergence (restrict [[0,0]] [[0,0],[0,1]]) (restrict [[0,1]] [[0,0],[0,1]])) -#guard !equiv (divergence (product [[0]] [[2]]) (product [[0,1]] [[2]])) (divergence [[0]] [[0,1]]) -#guard !equiv (divergence [[0],[1,0],[1,1,0],[1,1,1]] (branches [[0],[1,0],[1,1,0],[1,1,1]])) - (branches (branches [[0],[1,0],[1,1,0],[1,1,1]])) -#guard !equiv (divergence [[0,0],[0,1]] [[0]]) (divergence [[0,0],[0,1]] [[0,0]]) -#guard !equiv (branches [[0],[0,0],[0,1]]) (branches (basis [[0],[0,0],[0,1]])) -#guard equiv (branches [[102,111,111],[102,111,111,100]]) [] -- foo / food -#guard equiv (divergence [[102,111,111,100]] [[102,111,117,114]]) [[102,111]] -- food / four -#guard count (divergence [[0,0,0]] [[1],[0,1],[0,0,1]]) == 3 - --- The map adapter retains values; bare paths do not supply witnesses. -def valued : PathMap Nat := PathMap.mk' [([0],10),([0,1],20),([2],30)] [[0,1,255],[3,4]] -#guard (Map.basis valued).valAt [0] == some 10 -#guard (Map.basis valued).valAt [0,1] == none -#guard (Map.hull valued).valAt [0,1] == some 20 -#guard (Map.hull valued).valAt [0] == none -#guard equiv (ofMap (Map.branches valued)) [[]] -#guard equiv (ofMap (Map.divergence valued (PathMap.mk' ([] : List (Path × Nat)) [[4,5]]))) [] -end PathMapModel.PathSetChecks diff --git a/lean/PathMapModel/PathSets.lean b/lean/PathMapModel/PathSets.lean deleted file mode 100644 index 55131c71..00000000 --- a/lean/PathMapModel/PathSets.lean +++ /dev/null @@ -1,205 +0,0 @@ -import PathMapModel.Map - -/-! Valued finite path sets. This independent list model deliberately differs -from the Rust zipper traversal. Lists denote sets: order/duplicates are ignored -by `equiv`. Bare structure is not membership. Basis/hull preserve payloads. -/ -namespace PathMapModel -namespace Path - -def lcp : Path → Path → Path - | a :: as, b :: bs => if a == b then a :: lcp as bs else [] - | _, _ => [] - -/-- Termination is not a next byte. -/ -def divergence : Path → Path → Option Path - | a :: as, b :: bs => if a == b then (divergence as bs).map (a :: ·) else some [] - | _, _ => none - -@[simp] theorem divergence_self (p : Path) : divergence p p = none := by - induction p with - | nil => rfl - | cons a as ih => simp [divergence, ih] - -theorem divergence_comm (p q : Path) : divergence p q = divergence q p := by - induction p generalizing q with - | nil => cases q <;> rfl - | cons a as ih => - cases q with - | nil => rfl - | cons b bs => - by_cases h : a = b - · subst b; simp [divergence, ih] - · simp [divergence, h, Ne.symm h] - -@[simp] theorem divergence_nil_left (p : Path) : divergence [] p = none := by cases p <;> rfl -@[simp] theorem divergence_nil_right (p : Path) : divergence p [] = none := by cases p <;> rfl - -theorem divergence_wrap (p a b : Path) : - divergence (p ++ a) (p ++ b) = (divergence a b).map (p ++ ·) := by - induction p with - | nil => simp - | cons c cs ih => simp [divergence, ih, Option.map_map, Function.comp_def] -end Path - -abbrev PathSpace := List Path -namespace PathSpace - -def normalize (a : PathSpace) : PathSpace := Path.sortDedup a -def subset (a b : PathSpace) : Bool := a.all b.contains -/-- Set equality is independent of enumeration and serialization order. -/ -def equiv (a b : PathSpace) : Bool := subset a b && subset b a -def union (a b : PathSpace) : PathSpace := a ++ b -def inter (a b : PathSpace) : PathSpace := a.filter b.contains -def diff (a b : PathSpace) : PathSpace := a.filter (!b.contains ·) -def symDiff (a b : PathSpace) : PathSpace := union (diff a b) (diff b a) -def product (a b : PathSpace) : PathSpace := a.flatMap fun p => b.map (p ++ ·) -def wrap (p : Path) (a : PathSpace) : PathSpace := a.map (p ++ ·) -def unwrap (a : PathSpace) (p : Path) : PathSpace := a.filterMap (Path.stripPrefix p) -def restrict (a p : PathSpace) : PathSpace := a.filter fun x => p.any (· ≼ x) -def raffinate (a p : PathSpace) : PathSpace := diff a (restrict a p) -/-- Keep candidate arguments that prefix a valued witness in the second operand. -/ -def retain (p a : PathSpace) : PathSpace := p.filter fun x => a.any (x ≼ ·) -def head (a : PathSpace) : PathSpace := a.filterMap fun p => p.head?.map (fun b => [b]) -def tails (a : PathSpace) : PathSpace := a.filterMap fun p => match p with - | [] => none - | _ :: ps => some ps - -def divergence (a b : PathSpace) : PathSpace := a.flatMap fun p => b.filterMap (Path.divergence p) -/-- Fold pairs whose second prefix properly extends the first. -/ -def properOverlap (a b : PathSpace) (f : Path → Path → PathSpace) : PathSpace := - a.flatMap fun u => b.flatMap fun v => match Path.stripPrefix u v with - | some r@(_ :: _) => f u r - | _ => [] - -def branches (a : PathSpace) : PathSpace := divergence a a -/-- Prefix-minimal members. -/ -def basis (a : PathSpace) : PathSpace := a.filter fun p => !(a.any fun q => q != p && q ≼ p) -/-- Prefix-maximal members. -/ -def hull (a : PathSpace) : PathSpace := a.filter fun p => !(a.any fun q => q != p && p ≼ q) -def interior (a : PathSpace) : PathSpace := diff a (hull a) -def completion (a : PathSpace) : PathSpace := union a (branches a) -def lcpProduct (a b : PathSpace) : PathSpace := a.flatMap fun p => b.map (Path.lcp p) -def power (a : PathSpace) : Nat → PathSpace - | 0 => [[]] - | n + 1 => product a (power a n) -def branchIter (a : PathSpace) : Nat → PathSpace - | 0 => a - | n + 1 => branches (branchIter a n) -/-- Cardinality counts distinct members, independently of their lexical order. -/ -def count (a : PathSpace) : Nat := a.eraseDups.length -def height (a : PathSpace) : Nat := (a.map List.length).foldl max 0 -def commonPrefix (a : PathSpace) : Path := match a with - | [] => [] - | p :: ps => ps.foldl Path.lcp p -def prefixFree (a : PathSpace) : Bool := equiv a (basis a) -def covers (a b : PathSpace) : Bool := a.all fun p => b.any (p ≼ ·) - -/-- Independent head-recursive definitions, fueled by maximum length + 1. -/ -def divergenceRec : Nat → PathSpace → PathSpace → PathSpace - | 0, _, _ => [] - | n + 1, a, b => - let ha := normalize (head a) - let hb := normalize (head b) - let root := if ha.any (fun x => hb.any (· != x)) then [[]] else [] - root ++ (inter ha hb).flatMap fun p => wrap p (divergenceRec n (unwrap a p) (unwrap b p)) -def basisRec : Nat → PathSpace → PathSpace - | 0, _ => [] - | n + 1, a => if a.contains [] then [[]] else - (normalize (head a)).flatMap fun p => wrap p (basisRec n (unwrap a p)) -def hullRec : Nat → PathSpace → PathSpace - | 0, _ => [] - | n + 1, a => - let root := if a.contains [] && (head a).isEmpty then [[]] else [] - root ++ (normalize (head a)).flatMap fun p => wrap p (hullRec n (unwrap a p)) -def retainRec : Nat → PathSpace → PathSpace → PathSpace - | 0, _, _ => [] - | n + 1, p, a => - let root := if p.contains [] && !a.isEmpty then [[]] else [] - root ++ (normalize (inter (head p) (head a))).flatMap fun q => - wrap q (retainRec n (unwrap p q) (unwrap a q)) - -def ofMap {V : Type} (t : PathMap V) : PathSpace := t.vals.map (·.1) - -/-- General witness theorem, not a bounded check. -/ -theorem mem_divergence (a b : PathSpace) (p : Path) : - p ∈ divergence a b ↔ ∃ x ∈ a, ∃ y ∈ b, Path.divergence x y = some p := by - simp [divergence, List.mem_flatMap, List.mem_filterMap] - -theorem divergence_comm (a b : PathSpace) (p : Path) : - p ∈ divergence a b ↔ p ∈ divergence b a := by - simp only [mem_divergence] - constructor - · rintro ⟨x, hx, y, hy, h⟩ - exact ⟨y, hy, x, hx, (Path.divergence_comm y x).trans h⟩ - · rintro ⟨y, hy, x, hx, h⟩ - exact ⟨x, hx, y, hy, (Path.divergence_comm x y).trans h⟩ - -@[simp] theorem divergence_empty_left (a : PathSpace) : divergence [] a = [] := rfl -@[simp] theorem divergence_empty_right (a : PathSpace) : divergence a [] = [] := by simp [divergence] -@[simp] theorem divergence_epsilon_left (a : PathSpace) : divergence [[]] a = [] := by simp [divergence] -@[simp] theorem divergence_epsilon_right (a : PathSpace) : divergence a [[]] = [] := by simp [divergence] - -theorem divergence_union_left (a b c : PathSpace) : - divergence (union a b) c = union (divergence a c) (divergence b c) := by - simp [divergence, union] - -theorem divergence_union_right (a b c : PathSpace) (p : Path) : - p ∈ divergence a (union b c) ↔ p ∈ union (divergence a b) (divergence a c) := by - simp only [union, List.mem_append, mem_divergence] - constructor - · rintro ⟨x, hx, y, hy | hy, h⟩ - · exact Or.inl ⟨x, hx, y, hy, h⟩ - · exact Or.inr ⟨x, hx, y, hy, h⟩ - · rintro (⟨x, hx, y, hy, h⟩ | ⟨x, hx, y, hy, h⟩) - · exact ⟨x, hx, y, Or.inl hy, h⟩ - · exact ⟨x, hx, y, Or.inr hy, h⟩ - -theorem divergence_diagonal (a : PathSpace) : divergence a a = branches a := rfl - -theorem divergence_mono {a b c d : PathSpace} - (ha : ∀ p, p ∈ a → p ∈ c) (hb : ∀ p, p ∈ b → p ∈ d) : - ∀ p, p ∈ divergence a b → p ∈ divergence c d := by - intro p hp - obtain ⟨x, hx, y, hy, h⟩ := (mem_divergence a b p).mp hp - exact (mem_divergence c d p).mpr ⟨x, ha x hx, y, hb y hy, h⟩ - -theorem mem_basis (a : PathSpace) (p : Path) : - p ∈ basis a ↔ p ∈ a ∧ ∀ q ∈ a, q ≠ p → (q ≼ p) = false := by - simp [basis, List.mem_filter, Bool.not_eq_true, List.any_eq_false] - -theorem mem_hull (a : PathSpace) (p : Path) : - p ∈ hull a ↔ p ∈ a ∧ ∀ q ∈ a, q ≠ p → (p ≼ q) = false := by - simp [hull, List.mem_filter, Bool.not_eq_true, List.any_eq_false] -end PathSpace - -namespace Map - -/-- Keep argument values whose paths prefix a valued witness in the graph. -/ -def retain {V W : Type} (a : PathMap V) (b : PathMap W) : PathMap V := - let support := PathSpace.retain (PathSpace.ofMap a) (PathSpace.ofMap b) - PathMap.mk' (a.vals.filter (fun kv => support.contains kv.1)) [] - -def basis {V : Type} (t : PathMap V) : PathMap V := - let support := PathSpace.basis (PathSpace.ofMap t) - PathMap.mk' (t.vals.filter (fun kv => support.contains kv.1)) [] -def hull {V : Type} (t : PathMap V) : PathMap V := - let support := PathSpace.hull (PathSpace.ofMap t) - PathMap.mk' (t.vals.filter (fun kv => support.contains kv.1)) [] -def divergence {V W : Type} (a : PathMap V) (b : PathMap W) : PathMap Unit := - PathMap.mk' ((PathSpace.divergence (PathSpace.ofMap a) (PathSpace.ofMap b)).map (·, ())) [] -def branches {V : Type} (a : PathMap V) : PathMap Unit := divergence a a -end Map - -namespace Zip - -def retain {V W : Type} (src : Zip V) (witnesses : Zip W) (out : Zip V) : Zip V := - out.graftMap (Map.retain src.makeMap witnesses.makeMap) -/-- Relative focus semantics; input and output cursor positions are unchanged. -/ -def basis {V : Type} (src out : Zip V) : Zip V := out.graftMap (Map.basis src.makeMap) -def hull {V : Type} (src out : Zip V) : Zip V := out.graftMap (Map.hull src.makeMap) -def divergence {V W : Type} (a : Zip V) (b : Zip W) (out : Zip Unit) : Zip Unit := - out.graftMap (Map.divergence a.makeMap b.makeMap) -def branches {V : Type} (src : Zip V) (out : Zip Unit) : Zip Unit := - out.graftMap (Map.branches src.makeMap) -end Zip -end PathMapModel diff --git a/lean/PathMapModel/RetainChecks.lean b/lean/PathMapModel/RetainChecks.lean deleted file mode 100644 index 316710c9..00000000 --- a/lean/PathMapModel/RetainChecks.lean +++ /dev/null @@ -1,40 +0,0 @@ -import PathMapModel.RetainConvex - -/-! Kernel-checked examples and counterexamples delimit the unconditional laws. -/ -namespace PathMapModel.PathSpace - -theorem retain_function_example : - restrict [[1,1],[2,4],[3,9],[4,16],[5,25]] [[0],[2],[4],[6]] = [[2,4],[4,16]] ∧ - retain [[0],[2],[4],[6]] [[1,1],[2,4],[3,9],[4,16],[5,25]] = [[2],[4]] := by decide - -theorem retain_not_commutative : - equiv (retain [[0]] [[0,1]]) (retain [[0,1]] [[0]]) = false := by decide - -theorem retain_not_associative : - equiv (retain (retain [[]] [[0]]) [[]]) (retain [[]] (retain [[0]] [[]])) = false := by decide - -theorem retain_not_mask_intersection : - equiv (retain [[]] (inter [[0]] [[1]])) (inter (retain [[]] [[0]]) (retain [[]] [[1]])) = false := by decide - -theorem retain_not_mask_difference : - equiv (retain [[]] (diff [[0]] [[1]])) (diff (retain [[]] [[0]]) (retain [[]] [[1]])) = false := by decide - -theorem retain_not_hull_source : - equiv (hull (retain [[],[0]] [[]])) (retain (hull [[],[0]]) [[]]) = false := by decide - -theorem retain_not_basis_mask : - equiv (retain [[0]] [[],[0]]) (retain [[0]] (basis [[],[0]])) = false := by decide - -theorem retain_not_convexMeet_commutation : - equiv (retain (convexMeet [[],[0]] [[],[0]]) [[]]) - (convexMeet (retain [[],[0]] [[]]) [[],[0]]) = false := by decide - -theorem retain_divergence_bound_strict : - equiv (branches (retain [[0,0],[1,0]] [[0,1],[1,1]])) - (inter (branches [[0,0],[1,0]]) (branches [[0,1],[1,1]])) = false := by decide - -theorem retain_product_needs_prefix_code : - equiv (retain (product [[],[0]] [[1]]) (product [[],[0]] [[0,1]])) - (product [[],[0]] (retain [[1]] [[0,1]])) = false := by decide - -end PathMapModel.PathSpace diff --git a/lean/PrunedModel.lean b/lean/PrunedModel.lean index c4df10fd..b9415cf2 100644 --- a/lean/PrunedModel.lean +++ b/lean/PrunedModel.lean @@ -9,3 +9,4 @@ import PrunedModel.Pointwise import PrunedModel.Refine import PrunedModel.Zippy import PrunedModel.Fuzz +import PrunedModel.Convex diff --git a/lean/PrunedModel/Convex.lean b/lean/PrunedModel/Convex.lean new file mode 100644 index 00000000..1eb54b15 --- /dev/null +++ b/lean/PrunedModel/Convex.lean @@ -0,0 +1,5 @@ +import PrunedModel.Convex.Map +import PrunedModel.Convex.PathSetChecks +import PrunedModel.Convex.Checks +import PrunedModel.Convex.RetainChecks +import PrunedModel.Convex.ClosedChecks diff --git a/lean/PathMapModel/Convex.lean b/lean/PrunedModel/Convex/Algebra.lean similarity index 83% rename from lean/PathMapModel/Convex.lean rename to lean/PrunedModel/Convex/Algebra.lean index 78a31f4a..9c4b44c7 100644 --- a/lean/PathMapModel/Convex.lean +++ b/lean/PrunedModel/Convex/Algebra.lean @@ -1,8 +1,9 @@ -import PathMapModel.PathSetCertificates +import PrunedModel.Convex.PathSetCertificates -/-! Stable convex operations. Equations ignore list order and duplicates. +/-! Stable convex operations on canonical pruned maps. Subtraction retains supporting interiors; its mask selects original tips. -/ -namespace PathMapModel.PathSpace +namespace PrunedModel.Convex +open PathMapModel def convexMeet (a b : PathSpace) : PathSpace := retain (inter a b) (inter (hull a) (hull b)) def convexSubtract (a b : PathSpace) : PathSpace := retain a (diff (hull a) b) @@ -30,9 +31,6 @@ theorem hull_max {a : PathSpace} {p q : Path} (hp : p ∈ hull a) (hq : q ∈ a) · have := ((mem_hull a p).mp hp).2 q hq (Ne.symm hn) simp [h] at this -theorem hull_isAntichain (a : PathSpace) : Antichain (hull a) := - fun _ hp _ hq h => hull_max hp (hull_subset a hq) h - theorem hull_of_antichain {a : PathSpace} (h : Antichain a) : Same (hull a) a := by intro p; rw [mem_hull]; constructor · exact And.left @@ -94,46 +92,46 @@ theorem convexMeet_idem (a : PathSpace) : Same (convexMeet a a) a := by theorem convexMeet_assoc (a b c : PathSpace) : Same (convexMeet (convexMeet a b) c) (convexMeet a (convexMeet b c)) := by intro p; simp only [mem_convexMeet, hull_convexMeet, mem_inter]; grind -theorem convexMeet_empty (a : PathSpace) : Same (convexMeet a []) [] := by +theorem convexMeet_empty (a : PathSpace) : Same (convexMeet a (ofPaths [])) (ofPaths []) := by intro p; simp [mem_convexMeet] -theorem convexSubtract_empty_right (a : PathSpace) : Same (convexSubtract a []) a := by +theorem convexSubtract_empty_right (a : PathSpace) : Same (convexSubtract a (ofPaths [])) a := by intro p; simpa [convexSubtract, mem_retain, mem_diff] using retain_hull a p -theorem convexSubtract_empty_left (a : PathSpace) : Same (convexSubtract [] a) [] := by +theorem convexSubtract_empty_left (a : PathSpace) : Same (convexSubtract (ofPaths []) a) (ofPaths []) := by intro p; simp [mem_convexSubtract] -theorem convexSubtract_self (a : PathSpace) : Same (convexSubtract a a) [] := by - intro p; simp only [mem_convexSubtract, List.not_mem_nil, iff_false] +theorem convexSubtract_self (a : PathSpace) : Same (convexSubtract a a) (ofPaths []) := by + intro p; simp only [mem_convexSubtract, mem_ofPaths,List.not_mem_nil, iff_false] rintro ⟨_,t,ht,hn,_⟩; exact hn (hull_subset a ht) -theorem convexMeet_zero (a b : PathSpace) : Same (convexMeet a b) [] ↔ Same (inter (hull a) (hull b)) [] := by +theorem convexMeet_zero (a b : PathSpace) : Same (convexMeet a b) (ofPaths []) ↔ Same (inter (hull a) (hull b)) (ofPaths []) := by constructor · intro h p; have hh := (hull_convexMeet a b p).symm.trans (hull_congr h p) - simpa only [hull, List.filter_nil] using hh - · intro h p; simp only [convexMeet, mem_retain]; have := h; simp only [Same, List.not_mem_nil, iff_false] at this; grind + simpa only [mem_hull (ofPaths []), mem_ofPaths, List.not_mem_nil, false_and] using hh + · intro h p; simp only [convexMeet, mem_retain]; have := h; simp only [Same, mem_ofPaths,List.not_mem_nil, iff_false] at this; grind -theorem convexSubtract_zero (a b : PathSpace) : Same (convexSubtract a b) [] ↔ Included (hull a) b := by +theorem convexSubtract_zero (a b : PathSpace) : Same (convexSubtract a b) (ofPaths []) ↔ Included (hull a) b := by constructor · intro h p hp have hh := hull_congr h p rw [hull_convexSubtract] at hh - simp only [mem_diff, hull, List.filter_nil, List.not_mem_nil, iff_false] at hh + simp only [mem_diff, mem_hull (ofPaths []), mem_ofPaths,List.not_mem_nil,false_and, iff_false] at hh by_cases hn : p ∈ b · exact hn · exact False.elim (hh ⟨hp,hn⟩) - · intro h p; simp only [mem_convexSubtract, List.not_mem_nil, iff_false]; grind + · intro h p; simp only [mem_convexSubtract, mem_ofPaths,List.not_mem_nil, iff_false]; grind -theorem convexSubtract_identity (a b : PathSpace) : Same (convexSubtract a b) a ↔ Same (inter (hull a) b) [] := by +theorem convexSubtract_identity (a b : PathSpace) : Same (convexSubtract a b) a ↔ Same (inter (hull a) b) (ofPaths []) := by constructor · intro h p have hh := hull_congr h p simp only [hull_convexSubtract,mem_diff] at hh - simp only [mem_inter,List.not_mem_nil,iff_false]; grind + simp only [mem_inter,mem_ofPaths,List.not_mem_nil,iff_false]; grind · intro h p; rw [mem_convexSubtract]; constructor · exact And.left · intro hp; obtain ⟨t,ht,hpt⟩ := hull_covers hp - exact ⟨hp,t,ht,fun hb => List.not_mem_nil ((h t).mp ((mem_inter _ _ _).mpr ⟨ht,hb⟩)),hpt⟩ + exact ⟨hp,t,ht,fun hb => List.not_mem_nil ((mem_ofPaths [] t).mp ((h t).mp ((mem_inter _ _ _).mpr ⟨ht,hb⟩))),hpt⟩ theorem convexMeet_ordinary (a b : PathSpace) : Same (convexMeet a b) (inter a b) ↔ Included (hull (inter a b)) (inter (hull a) (hull b)) := by constructor @@ -152,16 +150,16 @@ theorem convexSubtract_masks (a b : PathSpace) : · grind theorem convexSubtract_action (a b c : PathSpace) : Same (convexSubtract (convexSubtract a b) c) (convexSubtract a (union b c)) := by - intro p; simp only [mem_convexSubtract,hull_convexSubtract,mem_diff,union,List.mem_append]; grind + intro p; simp only [mem_convexSubtract,hull_convexSubtract,mem_diff,mem_union]; grind theorem convexSubtract_commute (a b c : PathSpace) : Same (convexSubtract (convexSubtract a b) c) (convexSubtract (convexSubtract a c) b) := by - intro p; simp only [convexSubtract_action]; simp only [mem_convexSubtract,union,List.mem_append]; grind + intro p; simp only [convexSubtract_action]; simp only [mem_convexSubtract,mem_union]; grind theorem convexSubtract_idem (a b : PathSpace) : Same (convexSubtract (convexSubtract a b) b) (convexSubtract a b) := by - intro p; simp only [convexSubtract_action]; simp only [mem_convexSubtract,union,List.mem_append,or_self] + intro p; simp only [convexSubtract_action]; simp only [mem_convexSubtract,mem_union,or_self] theorem convexSubtract_redundant (a b c : PathSpace) : Same (convexSubtract (convexSubtract a b) c) (convexSubtract (convexSubtract a b) (diff c b)) := by - intro p; simp only [convexSubtract_action]; simp only [mem_convexSubtract,union,List.mem_append,mem_diff]; grind + intro p; simp only [convexSubtract_action]; simp only [mem_convexSubtract,mem_union,mem_diff]; grind theorem convexSubtract_meet_left (a b c : PathSpace) : Same (convexSubtract (convexMeet a b) c) (convexMeet (convexSubtract a c) b) := by intro p; simp only [mem_convexSubtract,mem_convexMeet,hull_convexMeet,hull_convexSubtract,mem_inter,mem_diff]; grind @@ -170,20 +168,20 @@ theorem convexSubtract_meet_right (a b c : PathSpace) : Same (convexSubtract (co intro p; simp only [mem_convexSubtract,mem_convexMeet,hull_convexMeet,hull_convexSubtract,mem_inter,mem_diff]; grind theorem convex_four_factor (a b c d : PathSpace) : Same (convexMeet (convexSubtract a b) (convexSubtract c d)) (convexSubtract (convexMeet a c) (union b d)) := by - intro p; simp only [mem_convexSubtract,mem_convexMeet,hull_convexMeet,hull_convexSubtract,mem_inter,mem_diff,union,List.mem_append]; grind + intro p; simp only [mem_convexSubtract,mem_convexMeet,hull_convexMeet,hull_convexSubtract,mem_inter,mem_diff,mem_union]; grind theorem convexSubtract_meet_both (a b c : PathSpace) : Same (convexSubtract (convexMeet a b) c) (convexMeet (convexSubtract a c) (convexSubtract b c)) := by - intro p; simp only [convex_four_factor,mem_convexSubtract,union,List.mem_append,or_self] + intro p; simp only [convex_four_factor,mem_convexSubtract,mem_union,or_self] theorem convexSubtract_inter (a b c : PathSpace) : Same (convexSubtract a (inter b c)) (union (convexSubtract a b) (convexSubtract a c)) := by - intro p; simp only [mem_convexSubtract,mem_inter,union,List.mem_append]; grind + intro p; simp only [mem_convexSubtract,mem_inter,mem_union]; grind theorem convexSubtract_union (a b c : PathSpace) : Same (convexSubtract a (union b c)) (convexMeet (convexSubtract a b) (convexSubtract a c)) := by intro p; rw [convex_four_factor] exact (convexSubtract_congr (convexMeet_idem a) (fun _ => Iff.rfl) p).symm -theorem convexSubtract_disjoint (a b : PathSpace) : Same (convexMeet (convexSubtract a b) b) [] := by - intro p; simp only [mem_convexMeet,hull_convexSubtract,mem_diff,List.not_mem_nil,iff_false] +theorem convexSubtract_disjoint (a b : PathSpace) : Same (convexMeet (convexSubtract a b) b) (ofPaths []) := by + intro p; simp only [mem_convexMeet,hull_convexSubtract,mem_diff,mem_ofPaths,List.not_mem_nil,iff_false] rintro ⟨_,_,t,⟨_,hn⟩,ht,_⟩; exact hn (hull_subset _ ht) theorem convexMeet_via_subtract (a b : PathSpace) : Same (convexMeet a b) (convexSubtract (inter a b) (diff (hull (inter a b)) (inter (hull a) (hull b)))) := by @@ -202,11 +200,11 @@ theorem convexSubtract_hull (a b : PathSpace) : Same (convexSubtract (hull a) b) · rintro ⟨hp,t,ht,hn,hpt⟩; have he := hull_max hp (hull_subset _ ht) hpt; exact ⟨hp,he ▸ hn⟩ · rintro ⟨hp,hn⟩; exact ⟨hp,p,hp,hn,Path.prefix_self p⟩ -theorem convexMeet_empty_left (a : PathSpace) : Same (convexMeet [] a) [] := - fun p => (convexMeet_comm [] a p).trans (convexMeet_empty a p) +theorem convexMeet_empty_left (a : PathSpace) : Same (convexMeet (ofPaths []) a) (ofPaths []) := + fun p => (convexMeet_comm (ofPaths []) a p).trans (convexMeet_empty a p) theorem convexSubtract_hull_disjoint (a b : PathSpace) : - Same (inter (hull (convexSubtract a b)) b) [] := by - intro p; simp only [mem_inter,hull_convexSubtract,mem_diff,List.not_mem_nil,iff_false]; grind + Same (inter (hull (convexSubtract a b)) b) (ofPaths []) := by + intro p; simp only [mem_inter,hull_convexSubtract,mem_diff,mem_ofPaths,List.not_mem_nil,iff_false]; grind -end PathMapModel.PathSpace +end PrunedModel.Convex diff --git a/lean/PathMapModel/ConvexBoolean.lean b/lean/PrunedModel/Convex/Boolean.lean similarity index 69% rename from lean/PathMapModel/ConvexBoolean.lean rename to lean/PrunedModel/Convex/Boolean.lean index 9df32461..80be3f3e 100644 --- a/lean/PathMapModel/ConvexBoolean.lean +++ b/lean/PrunedModel/Convex/Boolean.lean @@ -1,47 +1,51 @@ -import PathMapModel.ConvexUnion +import PrunedModel.Convex.Union -namespace PathMapModel.PathSpace +namespace PrunedModel.Convex +open PathMapModel /-- Enumerate selections without quotienting away duplicate source paths. The public family calls this only on the duplicate-free hull. -/ -def tipChoices : PathSpace → List PathSpace - | [] => [[]] - | p :: ps => tipChoices ps ++ (tipChoices ps).map (p :: ·) +def tipChoices : List Path → List PathSpace + | [] => [ofPaths []] + | p :: ps => tipChoices ps ++ (tipChoices ps).map (union [p] ·) -theorem tipChoices_length (xs : PathSpace) : (tipChoices xs).length = 2 ^ xs.length := by +theorem tipChoices_length (xs : List Path) : (tipChoices xs).length = 2 ^ xs.length := by induction xs with | nil => rfl | cons p ps ih => simp only [tipChoices,List.length_append,List.length_map,ih,List.length_cons,Nat.pow_succ]; omega -theorem tipChoices_subset {xs t : PathSpace} (h : t ∈ tipChoices xs) : Included t xs := by +theorem tipChoices_subset {xs : List Path} {t : PathSpace} (h : t ∈ tipChoices xs) : Included t (ofPaths xs) := by induction xs generalizing t with - | nil => simp only [tipChoices,List.mem_singleton] at h; subst t; exact fun _ hp => False.elim (List.not_mem_nil hp) + | nil => simp only [tipChoices,List.mem_singleton] at h; subst t; exact fun _ hp => False.elim (by simp at hp) | cons p ps ih => rcases List.mem_append.mp h with h | h - · exact fun q hq => List.mem_cons_of_mem _ (ih h q hq) + · exact fun q hq => (mem_ofPaths _ _).mpr (List.mem_cons_of_mem _ ((mem_ofPaths _ _).mp (ih h q hq))) · obtain ⟨u,hu,rfl⟩ := List.mem_map.mp h - intro q hq; rcases List.mem_cons.mp hq with rfl | hq - · exact List.mem_cons_self - · exact List.mem_cons_of_mem _ (ih hu q hq) + intro q hq; rcases (mem_union _ _ _).mp hq with hq | hq + · have he : q = p := by simpa using hq + subst q + simp + · exact (mem_ofPaths _ _).mpr (List.mem_cons_of_mem _ ((mem_ofPaths _ _).mp (ih hu q hq))) -theorem tipChoices_select (xs t : PathSpace) : xs.filter t.contains ∈ tipChoices xs := by +theorem tipChoices_select (xs : List Path) (t : PathSpace) : ofPaths (xs.filter (fun p => decide (p ∈ t))) ∈ tipChoices xs := by induction xs with | nil => simp [tipChoices] | cons p ps ih => by_cases hp : p ∈ t - · simp only [List.filter_cons,List.contains_iff_mem.mpr hp,ite_true,tipChoices] + · simp only [List.filter_cons,decide_eq_true hp,ite_true] + rw [ofPaths_cons p,tipChoices] exact List.mem_append_right _ (List.mem_map.mpr ⟨_,ih,rfl⟩) - · have hf : t.contains p = false := by simp [hp] + · have hf : decide (p ∈ t) = false := by simp [hp] simp only [List.filter_cons,hf,Bool.false_eq_true,ite_false,tipChoices] exact List.mem_append_left _ ih -theorem tipChoices_distinct {xs : PathSpace} (hx : xs.Nodup) : +theorem tipChoices_distinct {xs : List Path} (hx : xs.Nodup) : (tipChoices xs).Pairwise (fun t u => ¬ Same t u) := by induction xs with | nil => simp [tipChoices] | cons p ps ih => obtain ⟨hn,hd⟩ := List.nodup_cons.mp hx - have no_p : ∀ t ∈ tipChoices ps, p ∉ t := fun t ht hp => hn (tipChoices_subset ht p hp) + have no_p : ∀ t ∈ tipChoices ps, p ∉ t := fun t ht hp => hn ((mem_ofPaths _ _).mp (tipChoices_subset ht p hp)) rw [tipChoices,List.pairwise_append] refine ⟨ih hd,?_,?_⟩ · rw [List.pairwise_map] @@ -49,38 +53,38 @@ theorem tipChoices_distinct {xs : PathSpace} (hx : xs.Nodup) : intro t u ht hu hne he apply hne; intro q have hh := he q - simp only [List.mem_cons] at hh + simp only [mem_union,mem_ofPaths,List.mem_singleton] at hh by_cases hq : q = p · subst q; exact iff_of_false (no_p t ht) (no_p u hu) · simpa [hq] using hh · intro t ht u hu obtain ⟨v,hv,rfl⟩ := List.mem_map.mp hu - intro he; exact no_p t ht ((he p).mpr List.mem_cons_self) + intro he; exact no_p t ht ((he p).mpr (by simp)) -def pruningFamily (a : PathSpace) : List PathSpace := (tipChoices (hull a).eraseDups).map (retain a) +def pruningFamily (a : PathSpace) : List PathSpace := (tipChoices (hull a).keys).map (retain a) theorem pruningFamily_length (a : PathSpace) : (pruningFamily a).length = 2 ^ count (hull a) := by simp only [pruningFamily,List.length_map,tipChoices_length,count] theorem pruningFamily_distinct (a : PathSpace) : (pruningFamily a).Pairwise (fun x y => ¬ Same x y) := by rw [pruningFamily,List.pairwise_map] - apply List.Pairwise.imp_of_mem ?_ (tipChoices_distinct (dedup_nodup (hull a))) + apply List.Pairwise.imp_of_mem ?_ (tipChoices_distinct (keys_nodup (hull a))) intro t u ht hu hne he - have ts : Included t (hull a) := fun p hp => List.mem_eraseDups.mp (tipChoices_subset ht p hp) - have us : Included u (hull a) := fun p hp => List.mem_eraseDups.mp (tipChoices_subset hu p hp) + have ts : Included t (hull a) := fun p hp => Zippy.mem_keys.mp ((mem_ofPaths _ _).mp (tipChoices_subset ht p hp)) + have us : Included u (hull a) := fun p hp => Zippy.mem_keys.mp ((mem_ofPaths _ _).mp (tipChoices_subset hu p hp)) exact hne ((pruning_injective ts us).mp he) theorem pruningFamily_complete {a t : PathSpace} (ht : Included t (hull a)) : ∃ r ∈ pruningFamily a, Same r (retain a t) := by - let u := (hull a).eraseDups.filter t.contains + let u := ofPaths ((hull a).keys.filter (fun p => decide (p ∈ t))) refine ⟨retain a u,List.mem_map.mpr ⟨u,tipChoices_select _ t,rfl⟩,retain_congr (fun _ => Iff.rfl) ?_⟩ - intro p; simp only [u,List.mem_filter,List.mem_eraseDups,List.contains_iff_mem] + intro p; simp only [u,mem_ofPaths,List.mem_filter,Zippy.mem_keys,decide_eq_true_eq] exact ⟨And.right,fun hp => ⟨ht p hp,hp⟩⟩ theorem pruningFamily_sound {a r : PathSpace} (hr : r ∈ pruningFamily a) : ∃ t, Included t (hull a) ∧ r = retain a t := by obtain ⟨t,ht,rfl⟩ := List.mem_map.mp hr - exact ⟨t,fun p hp => List.mem_eraseDups.mp (tipChoices_subset ht p hp),rfl⟩ + exact ⟨t,fun p hp => Zippy.mem_keys.mp ((mem_ofPaths _ _).mp (tipChoices_subset ht p hp)),rfl⟩ /-- An arbitrary Boolean expression, not a fixed list of candidate laws. -/ inductive ConvexFormula where @@ -100,17 +104,17 @@ def eval (v : Nat → Bool) : ConvexFormula → Bool | .compl x => !eval v x def tips (a : PathSpace) (v : Nat → PathSpace) (e : ConvexFormula) : PathSpace := - (hull a).filter (fun p => eval (fun i => (v i).contains p) e) + ofPaths ((hull a).keys.filter (fun p => eval (fun i => decide (p ∈ v i)) e)) def interpret (a : PathSpace) (v : Nat → PathSpace) : ConvexFormula → PathSpace | .atom i => retain a (inter (hull a) (v i)) - | .bot => [] + | .bot => ofPaths [] | .top => a | .meet x y => convexMeet (interpret a v x) (interpret a v y) | .join x y => union (interpret a v x) (interpret a v y) | .compl x => convexSubtract a (hull (interpret a v x)) theorem tips_subset (a : PathSpace) (v : Nat → PathSpace) (e : ConvexFormula) : Included (tips a v e) (hull a) := - fun _ h => (List.mem_filter.mp h).1 + fun _ h => Zippy.mem_keys.mp (List.mem_filter.mp ((mem_ofPaths _ _).mp h)).1 theorem interpret_correct (a : PathSpace) (v : Nat → PathSpace) (e : ConvexFormula) : Same (interpret a v e) (retain a (tips a v e)) := by @@ -129,10 +133,10 @@ theorem interpret_correct (a : PathSpace) (v : Nat → PathSpace) (e : ConvexFor | join x y ihx ihy => intro p have he : Same (union (interpret a v x) (interpret a v y)) (union (retain a (tips a v x)) (retain a (tips a v y))) := by - intro q; simp only [union,List.mem_append,ihx,ihy] + intro q; simp only [mem_union,ihx,ihy] apply (he p).trans ((pruning_union a _ _ p).trans ?_) apply retain_congr (fun _ => Iff.rfl) _ p - intro q; simp [tips,eval,union]; grind + intro q; simp [tips,eval,mem_union]; grind | compl x ih => intro p apply (convexSubtract_congr (fun _ => Iff.rfl) (hull_congr ih) p).trans @@ -148,7 +152,7 @@ theorem transfer {e f : ConvexFormula} (h : ∀ v, eval v e = eval v f) apply (interpret_correct a v e p).trans apply Iff.trans _ (interpret_correct a v f p).symm apply retain_congr (fun _ => Iff.rfl) _ p - intro q; simp only [tips,List.mem_filter,h] + intro q; simp only [tips,mem_ofPaths,List.mem_filter,h] end ConvexFormula -end PathMapModel.PathSpace +end PrunedModel.Convex diff --git a/lean/PathMapModel/ConvexChecks.lean b/lean/PrunedModel/Convex/Checks.lean similarity index 61% rename from lean/PathMapModel/ConvexChecks.lean rename to lean/PrunedModel/Convex/Checks.lean index d9047ede..91c06a18 100644 --- a/lean/PathMapModel/ConvexChecks.lean +++ b/lean/PrunedModel/Convex/Checks.lean @@ -1,31 +1,32 @@ -import PathMapModel.ConvexBoolean +import PrunedModel.Convex.Boolean /-! Kernel-reduced witnesses refuting tempting *unconditional* laws. Positive universal laws are proved symbolically in the imported modules, not by testing. -/ -namespace PathMapModel.PathSpace -private def root : PathSpace := [[]] -private def stem : PathSpace := [[],[1]] -private def fork : PathSpace := [[],[1],[2]] +namespace PrunedModel.Convex +open PathMapModel +private def root : PathSpace := (ofPaths [[]]) +private def stem : PathSpace := (ofPaths [[],[1]]) +private def fork : PathSpace := (ofPaths [[],[1],[2]]) theorem convex_counterexample_meet_monotone : subset root stem = true ∧ subset (convexMeet root root) (convexMeet stem root) = false := by decide theorem convex_counterexample_subtract_monotone : - subset root stem = true ∧ subset (convexSubtract root [[1]]) (convexSubtract stem [[1]]) = false := by decide + subset root stem = true ∧ subset (convexSubtract root (ofPaths [[1]])) (convexSubtract stem (ofPaths [[1]])) = false := by decide -theorem convex_counterexample_absorption : equiv (convexMeet root (union root [[1]])) root = false := by decide +theorem convex_counterexample_absorption : equiv (convexMeet root (union root (ofPaths [[1]]))) root = false := by decide theorem convex_counterexample_union_distribution : - equiv (convexMeet root (union root [[1]])) (union (convexMeet root root) (convexMeet root [[1]])) = false := by decide + equiv (convexMeet root (union root (ofPaths [[1]]))) (union (convexMeet root root) (convexMeet root (ofPaths [[1]]))) = false := by decide theorem convex_counterexample_partition : equiv (union (convexMeet root stem) (convexSubtract root stem)) root = false := by decide theorem convex_counterexample_ordinary_intersection : - equiv (convexSubtract fork [[1],[2]]) (inter (convexSubtract fork [[1]]) (convexSubtract fork [[2]])) = false := by decide + equiv (convexSubtract fork (ofPaths [[1],[2]])) (inter (convexSubtract fork (ofPaths [[1]])) (convexSubtract fork (ofPaths [[2]]))) = false := by decide theorem convex_counterexample_source_union : - equiv (convexSubtract (union root [[1]]) [[1]]) (union (convexSubtract root [[1]]) (convexSubtract [[1]] [[1]])) = false := by decide + equiv (convexSubtract (union root (ofPaths [[1]])) (ofPaths [[1]])) (union (convexSubtract root (ofPaths [[1]])) (convexSubtract (ofPaths [[1]]) (ofPaths [[1]]))) = false := by decide theorem convex_counterexample_intersection_distribution : equiv (convexMeet (inter root stem) root) (inter (convexMeet root root) (convexMeet stem root)) = false := by decide @@ -34,35 +35,35 @@ theorem convex_counterexample_hull_mask : equiv (convexSubtract root stem) (convexSubtract root (hull stem)) = false := by decide theorem convex_counterexample_basis_mask : - equiv (convexSubtract [[1]] stem) (convexSubtract [[1]] (basis stem)) = false := by decide + equiv (convexSubtract (ofPaths [[1]]) stem) (convexSubtract (ofPaths [[1]]) (basis stem)) = false := by decide theorem convex_counterexample_relative_complement : - ConvexLE root root ∧ Same (convexMeet root stem) [] ∧ ¬ ConvexLE root (convexSubtract root stem) := by + ConvexLE root root ∧ Same (convexMeet root stem) (ofPaths []) ∧ ¬ ConvexLE root (convexSubtract root stem) := by refine ⟨convexLE_refl _,(same_equiv _ _).mpr (by decide),?_⟩ - intro h; have hh := h.1 [] (by decide); change [] ∈ [] at hh; exact List.not_mem_nil hh + intro h; have hh := h.1 [] (by decide); exact (by decide : ¬ ([] : Path) ∈ convexSubtract root stem) hh theorem convex_counterexample_compatible_distribution : - Antichain (union (hull [[],[2]]) (hull [[1]])) ∧ - equiv (convexMeet stem (union [[],[2]] [[1]])) (union (convexMeet stem [[],[2]]) (convexMeet stem [[1]])) = false := by + Antichain (union (hull (ofPaths [[],[2]])) (hull (ofPaths [[1]]))) ∧ + equiv (convexMeet stem (union (ofPaths [[],[2]]) (ofPaths [[1]]))) (union (convexMeet stem (ofPaths [[],[2]])) (convexMeet stem (ofPaths [[1]]))) = false := by constructor · intro p hp q hq hpq - have hh : union (hull [[],[2]]) (hull [[1]]) = [[2],[1]] := by decide + have hh : union (hull (ofPaths [[],[2]])) (hull (ofPaths [[1]])) = (ofPaths [[2],[1]]) := by decide rw [hh] at hp hq - simp only [List.mem_cons,List.not_mem_nil,or_false] at hp hq + simp only [mem_ofPaths,List.mem_cons,List.not_mem_nil,or_false] at hp hq rcases hp with rfl | rfl <;> rcases hq with rfl | rfl <;> simp_all [Path.isPrefixOf] · decide theorem convex_cascade_example : - convexMeet [[1],[1,2],[1,2,3]] [[1],[1,2],[1,2,4]] = [] ∧ - convexPruneStep [[1],[1,2]] [] = [[1]] ∧ - convexPrune [] 2 [[1],[1,2]] = [] := by decide + convexMeet (ofPaths [[1],[1,2],[1,2,3]]) (ofPaths [[1],[1,2],[1,2,4]]) = (ofPaths []) ∧ + convexPruneStep (ofPaths [[1],[1,2]]) (ofPaths []) = (ofPaths [[1]]) ∧ + convexPrune (ofPaths []) 2 (ofPaths [[1],[1,2]]) = (ofPaths []) := by decide theorem convex_supporting_interior_example : - convexSubtract [[1],[1,2],[1,3]] [[1],[1,2]] = [[1],[1,3]] ∧ - convexLiteralSubtract [[1],[1,2],[1,3]] [[1],[1,2]] = [[1,3]] := by decide + convexSubtract (ofPaths [[1],[1,2],[1,3]]) (ofPaths [[1],[1,2]]) = (ofPaths [[1],[1,3]]) ∧ + convexLiteralSubtract (ofPaths [[1],[1,2],[1,3]]) (ofPaths [[1],[1,2]]) = (ofPaths [[1,3]]) := by decide theorem convex_literal_gap_example : - convexLiteralSubtract [[],[1],[1,1]] [[1]] = [[],[1,1]] := by decide + convexLiteralSubtract (ofPaths [[],[1],[1,1]]) (ofPaths [[1]]) = (ofPaths [[],[1,1]]) := by decide /-! Concrete instances of the universal Boolean-expression transfer theorem. -/ namespace ConvexFormula @@ -80,7 +81,7 @@ theorem complement_join (a : PathSpace) (v : Nat → PathSpace) (x : ConvexFormu exact transfer (e := .join x (.compl x)) (f := .top) (by intro w; simp [eval]) a v theorem complement_meet (a : PathSpace) (v : Nat → PathSpace) (x : ConvexFormula) : - Same (interpret a v (.meet x (.compl x))) [] := by + Same (interpret a v (.meet x (.compl x))) (ofPaths []) := by exact transfer (e := .meet x (.compl x)) (f := .bot) (by intro w; simp [eval]) a v theorem double_complement (a : PathSpace) (v : Nat → PathSpace) (x : ConvexFormula) : @@ -104,4 +105,4 @@ theorem absorption_join (a : PathSpace) (v : Nat → PathSpace) (x y : ConvexFor apply transfer; intro w; simp [eval]; grind end ConvexFormula -end PathMapModel.PathSpace +end PrunedModel.Convex diff --git a/lean/PathMapModel/Closed.lean b/lean/PrunedModel/Convex/Closed.lean similarity index 88% rename from lean/PathMapModel/Closed.lean rename to lean/PrunedModel/Convex/Closed.lean index 24270100..0b89d3f7 100644 --- a/lean/PathMapModel/Closed.lean +++ b/lean/PrunedModel/Convex/Closed.lean @@ -1,9 +1,10 @@ -import PathMapModel.RetainConvex +import PrunedModel.Convex.RetainConvex /-! Branch closure and the closed version of divergence. Equalities are extensional: `completion A = A ∪ branches A = lcpProduct A A`, and `lcpProduct A B` adds both comparable-path contributions to divergence. Closure never adds an arbitrary prefix. -/ -namespace PathMapModel.PathSpace +namespace PrunedModel.Convex +open PathMapModel /-- Closed under longest common prefixes, equivalently under branch points. -/ def IsClosed (a : PathSpace) : Prop := ∀ x ∈ a, ∀ y ∈ a, Path.lcp x y ∈ a @@ -57,7 +58,7 @@ theorem closed_divergence (a b : PathSpace) : IsClosed (divergence a b) := theorem closed_branches (a : PathSpace) : IsClosed (branches a) := closed_divergence a a -theorem closed_empty : IsClosed [] := by simp [IsClosed] +theorem closed_empty : IsClosed (ofPaths []) := by simp [IsClosed] theorem closed_singleton (p : Path) : IsClosed [p] := by simp [IsClosed] @@ -68,7 +69,7 @@ theorem completion_least {a b : PathSpace} (hb : IsClosed b) : · intro h p hp; exact h p (completion_extensive a p hp) · intro h p hp; exact ((closed_iff_completion b).mp hb p).mp (completion_mono h p hp) -theorem completion_empty : Same (completion []) [] := (closed_iff_completion _).mp closed_empty +theorem completion_empty : Same (completion (ofPaths [])) (ofPaths []) := (closed_iff_completion _).mp closed_empty theorem completion_singleton (p : Path) : Same (completion [p]) [p] := (closed_iff_completion _).mp (closed_singleton p) @@ -89,17 +90,17 @@ theorem completion_union (a b : PathSpace) : Same (completion (union a b)) (union (union (completion a) (completion b)) (divergence a b)) := by intro p; simp only [mem_completion] rw [branches_union] - simp only [union, List.mem_append, mem_completion]; grind + simp only [mem_union, mem_completion]; grind theorem completion_union_lcp (a b : PathSpace) : Same (completion (union a b)) (union (union (completion a) (completion b)) (lcpProduct a b)) := by intro p; rw [completion_union] - simp only [union, List.mem_append, lcp_correction, mem_retain, mem_completion]; grind + simp only [mem_union, lcp_correction, mem_retain, mem_completion]; grind theorem completion_union_absorb (a b : PathSpace) : Same (completion (union (completion a) (completion b))) (completion (union a b)) := by intro p; rw [completion_union, completion_union] - simp only [union, List.mem_append, completion_idempotent, divergence_completion] + simp only [mem_union, completion_idempotent, divergence_completion] /-- Union of closed operands is closed precisely when it contains their divergences. -/ theorem closed_union_iff {a b : PathSpace} (ha : IsClosed a) (hb : IsClosed b) : @@ -109,7 +110,7 @@ theorem closed_union_iff {a b : PathSpace} (ha : IsClosed a) (hb : IsClosed b) : have hcb := (closed_iff_completion b).mp hb simp only [Same, Included] simp only [completion_union] - simp only [union, List.mem_append, hca, hcb]; grind + simp only [mem_union, hca, hcb]; grind /-- Every closure member has a witness pair; no iterative saturation is needed. -/ theorem completion_pair_witness (a : PathSpace) (p : Path) : @@ -123,7 +124,7 @@ theorem closed_range_lcp (a : PathSpace) : IsClosed a ↔ ∃ b c, Same a (lcpPr theorem closed_range_branches (a : PathSpace) : IsClosed a ↔ ∃ b, Same a (branches b) := by constructor - · intro h; exact ⟨product a [[0],[1]],fun p => + · intro h; exact ⟨product a (ofPaths [[0],[1]]),fun p => ((closed_iff_completion a).mp h p).symm.trans (fork_completion a p).symm⟩ · rintro ⟨b,h⟩; exact (closed_congr h).mpr (closed_branches b) @@ -132,9 +133,9 @@ theorem closed_range_divergence (a : PathSpace) : IsClosed a ↔ ∃ b c, Same a · intro h; obtain ⟨b,hb⟩ := (closed_range_branches a).mp h; exact ⟨b,b,hb⟩ · rintro ⟨b,c,h⟩; exact (closed_congr h).mpr (closed_divergence b c) -theorem lcp_empty_left (a : PathSpace) : Same (lcpProduct [] a) [] := by simp [Same, lcpProduct] +theorem lcp_empty_left (a : PathSpace) : Same (lcpProduct (ofPaths []) a) (ofPaths []) := by simp [Same, lcpProduct] -theorem lcp_empty_right (a : PathSpace) : Same (lcpProduct a []) [] := by simp [Same, lcpProduct] +theorem lcp_empty_right (a : PathSpace) : Same (lcpProduct a (ofPaths [])) (ofPaths []) := by simp [Same, lcpProduct] theorem lcp_inter_lower (a b : PathSpace) : Included (inter a b) (lcpProduct a b) := by intro p hp; obtain ⟨ha,hb⟩ := (mem_inter _ _ _).mp hp @@ -142,7 +143,7 @@ theorem lcp_inter_lower (a b : PathSpace) : Included (inter a b) (lcpProduct a b theorem lcp_union_right (a b c : PathSpace) : Same (lcpProduct a (union b c)) (union (lcpProduct a b) (lcpProduct a c)) := by - intro p; simp only [mem_lcpProduct, union, List.mem_append]; grind + intro p; simp only [mem_lcpProduct, mem_union]; grind /-- Closing either input does not change the closed divergence product. -/ theorem lcp_completion_left (a b : PathSpace) : @@ -189,7 +190,7 @@ theorem lcp_four_factors (a b c d : PathSpace) : Same (lcpProduct (union a b) (union c d)) (union (union (lcpProduct a c) (lcpProduct a d)) (union (lcpProduct b c) (lcpProduct b d))) := by intro p; simp only [mem_lcpProduct] - simp only [union, List.mem_append, mem_lcpProduct]; grind + simp only [mem_union, mem_lcpProduct]; grind theorem lcp_closed_join (a b c : PathSpace) : Same (lcpProduct a (completion (union b c))) (union (lcpProduct a b) (lcpProduct a c)) := by @@ -201,43 +202,43 @@ theorem closed_lcp_union (a b c : PathSpace) : IsClosed (union (lcpProduct a b) /-- Closed union is the least upper bound for inclusion. Its meet is intersection. -/ theorem closed_join_least {a b c : PathSpace} (hc : IsClosed c) : Included (completion (union a b)) c ↔ Included a c ∧ Included b c := by - rw [completion_least hc]; simp only [Included, union, List.mem_append]; grind + rw [completion_least hc]; simp only [Included, mem_union]; grind theorem closed_join_assoc (a b c : PathSpace) : Same (completion (union (completion (union a b)) c)) (completion (union a (completion (union b c)))) := by have left : Same (union (union a b) c) (union a (union b c)) := by - intro p; simp only [union, List.mem_append]; grind + intro p; simp only [mem_union]; grind have absorb (x y : PathSpace) : Same (completion (union (completion x) y)) (completion (union x y)) := by intro p; rw [completion_union, completion_union] - simp only [union, List.mem_append, completion_idempotent, divergence_completion_left] + simp only [mem_union, completion_idempotent, divergence_completion_left] have right (x y : PathSpace) : Same (completion (union x (completion y))) (completion (union x y)) := by intro p; rw [completion_union, completion_union] have hd := divergence_completion_left y x p simp only [divergence_comm y x, divergence_comm (completion y) x] at hd - simp only [union, List.mem_append, completion_idempotent, hd] + simp only [mem_union, completion_idempotent, hd] exact fun p => (absorb _ _ p).trans ((completion_congr left p).trans (right _ _ p).symm) theorem closed_join_absorption {a : PathSpace} (ha : IsClosed a) (b : PathSpace) : Same (completion (union a (inter a b))) a := by have h : Same (union a (inter a b)) a := by - intro p; simp only [union, List.mem_append, mem_inter]; grind + intro p; simp only [mem_union, mem_inter]; grind exact fun p => (completion_congr h p).trans ((closed_iff_completion a).mp ha p) theorem closed_meet_absorption (a b : PathSpace) : Same (inter a (completion (union a b))) a := by intro p; rw [mem_inter] - exact ⟨And.left,fun hp => ⟨hp,completion_extensive _ p (List.mem_append_left _ hp)⟩⟩ + exact ⟨And.left,fun hp => ⟨hp,completion_extensive _ p (mem_union_left _ hp)⟩⟩ /-- A newly forced path is a proper prefix of the newly inserted witness. -/ theorem completion_insert_new {a : PathSpace} {x y : Path} (hx : x ∉ completion a) (hne : x ≠ y) (h : x ∈ completion (union a [y])) : (x ≼ y) = true ∧ x.length < y.length := by rw [completion_union] at h - simp only [union, List.mem_append, completion_singleton, List.mem_singleton] at h + simp only [mem_union, completion_singleton, mem_ofPaths, List.mem_singleton] at h rcases h with (h | h) | h · exact False.elim (hx h) · exact False.elim (hne h) · obtain ⟨u,_,v,hv,hd⟩ := (mem_divergence _ _ _).mp h - simp only [List.mem_singleton] at hv; subst v + simp only [mem_ofPaths,List.mem_singleton] at hv; subst v exact ⟨Path.divergence_prefix_left ((Path.divergence_comm _ _).trans hd),Path.divergence_length_right hd⟩ /-- Distinct new marks cannot force each other, even before the base space is closed. -/ @@ -249,4 +250,4 @@ theorem completion_anti_exchange {a : PathSpace} {x y : Path} have hyx := (completion_insert_new hy hne.symm k).2 omega -end PathMapModel.PathSpace +end PrunedModel.Convex diff --git a/lean/PrunedModel/Convex/ClosedChecks.lean b/lean/PrunedModel/Convex/ClosedChecks.lean new file mode 100644 index 00000000..64d9c53b --- /dev/null +++ b/lean/PrunedModel/Convex/ClosedChecks.lean @@ -0,0 +1,75 @@ +import PrunedModel.Convex.ClosedOperators + +/-! Kernel-checked counterexamples delimit the closed algebra. The explicit closure +checks in the lattice examples prevent failures from being blamed on unclosed inputs. -/ +namespace PrunedModel.Convex +open PathMapModel + +theorem completion_not_union_preserving : + equiv (completion (union (ofPaths [[0]]) (ofPaths [[1]]))) (union (completion (ofPaths [[0]])) (completion (ofPaths [[1]]))) = false := by decide + +theorem completion_not_inter_preserving : + equiv (completion (inter (ofPaths [[]]) (ofPaths [[0],[1]]))) (inter (completion (ofPaths [[]])) (completion (ofPaths [[0],[1]]))) = false := by decide + +theorem completion_retain_bound_strict : + equiv (completion (retain (ofPaths [[0],[1]]) (ofPaths [[]]))) (retain (completion (ofPaths [[0],[1]])) (ofPaths [[]])) = false := by decide + +theorem completion_raffinate_bound_strict : + equiv (completion (raffinate (ofPaths [[0],[1]]) (ofPaths [[0]]))) (raffinate (completion (ofPaths [[0],[1]])) (ofPaths [[0]])) = false := by decide + +theorem completion_convexMeet_bound_strict : + equiv (completion (convexMeet (ofPaths [[],[0]]) (ofPaths [[0],[1]]))) + (convexMeet (completion (ofPaths [[],[0]])) (completion (ofPaths [[0],[1]]))) = false := by decide + +theorem completion_convexSubtract_bound_strict : + equiv (completion (convexSubtract (ofPaths [[0],[1]]) (ofPaths [[0]]))) + (convexSubtract (completion (ofPaths [[0],[1]])) (ofPaths [[0]])) = false := by decide + +theorem closed_restrict_needs_closed_mask : + equiv (completion (ofPaths [[],[0],[1]])) (ofPaths [[],[0],[1]]) = true ∧ + equiv (completion (restrict (ofPaths [[],[0],[1]]) (ofPaths [[0],[1]]))) (restrict (ofPaths [[],[0],[1]]) (ofPaths [[0],[1]])) = false := by decide + +theorem lcp_not_intersection : + equiv (lcpProduct (ofPaths [[]]) (ofPaths [[0]])) (inter (ofPaths [[]]) (ofPaths [[0]])) = false := by decide + +theorem lcp_not_lattice_absorption : + equiv (lcpProduct (ofPaths [[0]]) (completion (union (ofPaths [[0]]) (ofPaths [[]])))) (ofPaths [[0]]) = false := by decide + +theorem lcp_inter_bound_strict : + equiv (lcpProduct (ofPaths [[]]) (inter (ofPaths [[]]) (ofPaths [[0]]))) (inter (lcpProduct (ofPaths [[]]) (ofPaths [[]])) (lcpProduct (ofPaths [[]]) (ofPaths [[0]]))) = false := by decide + +theorem closed_lattice_not_distributive : + let a : PathSpace := (ofPaths [[]]); let b := (ofPaths [[0]]); let c := (ofPaths [[1]]) + equiv (completion a) a = true ∧ equiv (completion b) b = true ∧ equiv (completion c) c = true ∧ + equiv (inter a (completion (union b c))) (completion (union (inter a b) (inter a c))) = false := by decide + +theorem closed_lattice_not_modular : + let a : PathSpace := (ofPaths [[0]]); let b := (ofPaths [[1]]); let c := (ofPaths [[],[0]]) + equiv (completion a) a = true ∧ equiv (completion b) b = true ∧ equiv (completion c) c = true ∧ + subset a c = true ∧ + equiv (completion (union a (inter b c))) (inter (completion (union a b)) c) = false := by decide + +theorem lcp_retain_bound_strict : + equiv (lcpProduct (retain (ofPaths [[]]) (ofPaths [[]])) (retain (ofPaths [[0]]) (ofPaths [[]]))) + (retain (lcpProduct (ofPaths [[]]) (ofPaths [[0]])) (lcpProduct (ofPaths [[]]) (ofPaths [[]]))) = false := by decide + +theorem completion_not_determined_by_hull : + equiv (hull (ofPaths [[0]])) (hull (ofPaths [[],[0]])) = true ∧ + equiv (completion (ofPaths [[0]])) (completion (ofPaths [[],[0]])) = false := by decide + +/-- L closes the divergence operation by including comparable pairs; completing +its strict-divergence output alone cannot recover those pairs. -/ +theorem lcp_not_completed_divergence : + equiv (completion (divergence (ofPaths [[]]) (ofPaths [[]]))) (lcpProduct (ofPaths [[]]) (ofPaths [[]])) = false := by decide + +theorem lcpLE_not_inclusion : + equiv (lcpProduct (ofPaths [[]]) (ofPaths [[0]])) (ofPaths [[]]) = true ∧ subset (ofPaths [[]]) (ofPaths [[0]]) = false := by decide + +theorem lcpLE_not_coverage : + covers (ofPaths [[0]]) (ofPaths [[],[0]]) = true ∧ equiv (lcpProduct (ofPaths [[0]]) (ofPaths [[],[0]])) (ofPaths [[0]]) = false := by decide + +theorem closure_does_not_add_intermediate_prefixes : + equiv (completion (ofPaths [[0,0],[0,1]])) (ofPaths [[0],[0,0],[0,1]]) = true ∧ + ([] : Path) ∉ completion (ofPaths [[0,0],[0,1]]) := by decide + +end PrunedModel.Convex diff --git a/lean/PathMapModel/ClosedGeometry.lean b/lean/PrunedModel/Convex/ClosedGeometry.lean similarity index 89% rename from lean/PathMapModel/ClosedGeometry.lean rename to lean/PrunedModel/Convex/ClosedGeometry.lean index 0bf82429..b8330d92 100644 --- a/lean/PathMapModel/ClosedGeometry.lean +++ b/lean/PrunedModel/Convex/ClosedGeometry.lean @@ -1,6 +1,7 @@ -import PathMapModel.Closed +import PrunedModel.Convex.Closed -namespace PathMapModel.PathSpace +namespace PrunedModel.Convex +open PathMapModel theorem completion_covered {a : PathSpace} {p : Path} (h : p ∈ completion a) : ∃ q ∈ a, (p ≼ q) = true := by @@ -14,7 +15,7 @@ theorem hull_completion (a : PathSpace) : Same (hull (completion a)) (hull a) := theorem completion_hull (a : PathSpace) : Same (union a (completion (hull a))) (completion a) := by intro p - simp only [union, List.mem_append, mem_completion, branch_hull] + simp only [mem_union, mem_completion, branch_hull] have hs : p ∈ hull a → p ∈ a := hull_subset a grind @@ -32,23 +33,23 @@ theorem closed_basis_prefix {a : PathSpace} (ha : IsClosed a) {p : Path} (hp : p simpa only [he] using Path.lcp_prefix_right p q /-- A nonempty closed space has exactly one basis path, its common prefix. -/ -theorem basis_closed {a : PathSpace} (ha : IsClosed a) (hn : a ≠ []) : +theorem basis_closed {a : PathSpace} (ha : IsClosed a) (hn : a ≠ (ofPaths [])) : Same (basis a) [commonPrefix a] := by have eqroot : ∀ p ∈ basis a, p = commonPrefix a := by intro p hp apply Path.prefix_antisymm · exact (commonPrefix_spec a hn p).mpr (closed_basis_prefix ha hp) · exact ((commonPrefix_spec a hn _).mp (Path.prefix_self _)) p (basis_subset a hp) - intro p; simp only [List.mem_singleton]; constructor + intro p; simp only [mem_ofPaths,List.mem_singleton]; constructor · exact eqroot p · intro he obtain ⟨q,hq,_⟩ := height_attained (fun hh => hn ((basis_nonempty a).mp hh)) exact ((eqroot q hq).trans he.symm) ▸ hq -theorem commonPrefix_completion {a : PathSpace} (hn : a ≠ []) : +theorem commonPrefix_completion {a : PathSpace} (hn : a ≠ (ofPaths [])) : commonPrefix (completion a) = commonPrefix a := by - have hc : completion a ≠ [] := by - intro h; apply hn; apply List.eq_nil_iff_forall_not_mem.mpr + have hc : completion a ≠ (ofPaths []) := by + intro h; apply hn; apply (eq_empty_iff _).mpr intro p hp; have hh := completion_extensive a p hp; simp [h] at hh apply Path.prefix_antisymm · apply (commonPrefix_spec a hn _).mpr @@ -59,10 +60,10 @@ theorem commonPrefix_completion {a : PathSpace} (hn : a ≠ []) : have h := (commonPrefix_spec a hn _).mp (Path.prefix_self (commonPrefix a)) exact (Path.prefix_lcp _ _ _).mpr ⟨h x hx,h y hy⟩ -theorem basis_completion {a : PathSpace} (hn : a ≠ []) : +theorem basis_completion {a : PathSpace} (hn : a ≠ (ofPaths [])) : Same (basis (completion a)) [commonPrefix a] := by - have hc : completion a ≠ [] := by - intro h; apply hn; apply List.eq_nil_iff_forall_not_mem.mpr + have hc : completion a ≠ (ofPaths []) := by + intro h; apply hn; apply (eq_empty_iff _).mpr intro p hp; have hh := completion_extensive a p hp; simp [h] at hh simpa only [commonPrefix_completion hn] using basis_closed (closed_completion a) hc @@ -143,9 +144,6 @@ theorem completion_cardinality_linear (a : PathSpace) : have h := completion_cardinality a have hk := count_mono (fun _ hp => hull_subset a hp) have hl := count_mono (completion_extensive a) - by_cases hz : count a = 0 - · have he := (count_eq_zero a).mp hz - subst a; simp [count, completion, union, branches, divergence] - · omega + omega -end PathMapModel.PathSpace +end PrunedModel.Convex diff --git a/lean/PathMapModel/ClosedOperators.lean b/lean/PrunedModel/Convex/ClosedOperators.lean similarity index 91% rename from lean/PathMapModel/ClosedOperators.lean rename to lean/PrunedModel/Convex/ClosedOperators.lean index 57829ec7..3db6a1f2 100644 --- a/lean/PathMapModel/ClosedOperators.lean +++ b/lean/PrunedModel/Convex/ClosedOperators.lean @@ -1,6 +1,7 @@ -import PathMapModel.ClosedGeometry +import PrunedModel.Convex.ClosedGeometry -namespace PathMapModel.PathSpace +namespace PrunedModel.Convex +open PathMapModel theorem closed_retain {a : PathSpace} (ha : IsClosed a) (b : PathSpace) : IsClosed (retain a b) := by intro x hx y hy @@ -37,13 +38,13 @@ theorem completion_restrict (a b : PathSpace) : intro p have hd := divergence_same_mask a a b p simp only [mem_completion, branches, hd] - simp only [union, List.mem_append, mem_restrict, mem_completion, branches] + simp only [mem_union, mem_restrict, mem_completion, branches] grind theorem completion_restrict_closed {b : PathSpace} (hb : IsClosed b) (a : PathSpace) : Same (completion (restrict a b)) (restrict (completion a) b) := by intro p; rw [completion_restrict] - simp only [union, List.mem_append] + simp only [mem_union] constructor · rintro (h | h) · exact h @@ -121,11 +122,11 @@ theorem lcp_diff_bound (a b c : PathSpace) : /-- All genuinely new output marks are strict divergences. -/ theorem lcp_new_marks (a b : PathSpace) : Same (diff (lcpProduct a b) (union a b)) (diff (divergence a b) (union a b)) := by - intro p; simp only [mem_diff, lcp_correction, mem_retain, union, List.mem_append]; grind + intro p; simp only [mem_diff, lcp_correction, mem_retain, mem_union]; grind theorem lcp_union_bound (a b : PathSpace) : Included (lcpProduct a b) (completion (union a b)) := by intro p hp; obtain ⟨x,hx,y,hy,he⟩ := (mem_lcpProduct _ _ _).mp hp - exact (completion_pair_witness _ _).mpr ⟨x,List.mem_append_left _ hx,y,List.mem_append_right _ hy,he⟩ + exact (completion_pair_witness _ _).mpr ⟨x,mem_union_left _ hx,y,mem_union_right _ hy,he⟩ theorem retain_lcp_operand (a b : PathSpace) : Same (retain a (lcpProduct a b)) (retain a b) := by intro p @@ -170,7 +171,7 @@ theorem lcpLE_product_iff (x a b : PathSpace) : · rintro ⟨h,k⟩; intro p exact (lcp_associativity x a b p).symm.trans ((lcp_congr h (fun _ => Iff.rfl) p).trans (k p)) -theorem lcpLE_empty (a : PathSpace) : LcpLE [] a := lcp_empty_left a +theorem lcpLE_empty (a : PathSpace) : LcpLE (ofPaths []) a := lcp_empty_left a /-- Coverage alone is insufficient: both extra output contributions must already lie in A. -/ theorem lcpLE_iff (a b : PathSpace) : LcpLE a b ↔ @@ -197,20 +198,20 @@ theorem lcp_restrict (a b m : PathSpace) : rcases (lcp_correction _ _ p).mp hp with hd | ht | ht · rcases (divergence_same_mask a b m p).mp hd with hr | hr · obtain ⟨h,q,hq,hqp⟩ := (mem_restrict _ _ _).mp hr - exact List.mem_append_left _ ((mem_restrict _ _ _).mpr + exact mem_union_left _ ((mem_restrict _ _ _).mpr ⟨(lcp_correction a b p).mpr (Or.inl h),q,hq,hqp⟩) - · exact List.mem_append_right _ hr + · exact mem_union_right _ hr · obtain ⟨hr,y,hy,hpy⟩ := (mem_retain _ _ _).mp ht obtain ⟨ha,q,hq,hqp⟩ := (mem_restrict _ _ _).mp hr have hb := ((mem_restrict _ _ _).mp hy).1 - exact List.mem_append_left _ ((mem_restrict _ _ _).mpr + exact mem_union_left _ ((mem_restrict _ _ _).mpr ⟨(mem_lcpProduct _ _ _).mpr ⟨p,ha,y,hb,Path.lcp_of_prefix hpy⟩,q,hq,hqp⟩) · obtain ⟨hr,x,hx,hpx⟩ := (mem_retain _ _ _).mp ht obtain ⟨hb,q,hq,hqp⟩ := (mem_restrict _ _ _).mp hr have ha := ((mem_restrict _ _ _).mp hx).1 - exact List.mem_append_left _ ((mem_restrict _ _ _).mpr + exact mem_union_left _ ((mem_restrict _ _ _).mpr ⟨(mem_lcpProduct _ _ _).mpr ⟨x,ha,p,hb,(Path.lcp_comm x p).trans (Path.lcp_of_prefix hpx)⟩,q,hq,hqp⟩) - · intro hp; rcases List.mem_append.mp hp with hr | hd + · intro hp; rcases (mem_union _ _ _).mp hp with hr | hd · obtain ⟨hl,q,hq,hqp⟩ := (mem_restrict _ _ _).mp hr obtain ⟨x,hx,y,hy,rfl⟩ := (mem_lcpProduct _ _ _).mp hl obtain ⟨hqx,hqy⟩ := (Path.prefix_lcp _ _ _).mp hqp @@ -221,16 +222,16 @@ theorem lcp_restrict (a b m : PathSpace) : theorem lcp_restrict_closed {m : PathSpace} (hm : IsClosed m) (a b : PathSpace) : Same (lcpProduct (restrict a m) (restrict b m)) (restrict (lcpProduct a b) m) := by intro p; rw [lcp_restrict]; constructor - · intro hp; rcases List.mem_append.mp hp with hr | hd + · intro hp; rcases (mem_union _ _ _).mp hp with hr | hd · exact hr · obtain ⟨x,hx,y,hy,he⟩ := (mem_divergence _ _ _).mp hd have hpm : p ∈ m := Path.divergence_lcp he ▸ hm x ((mem_retain _ _ _).mp hx).1 y ((mem_retain _ _ _).mp hy).1 - have hl := (lcp_restrict a b m p).mpr (List.mem_append_right _ hd) + have hl := (lcp_restrict a b m p).mpr (mem_union_right _ hd) have hs := lcp_mono (fun q hq => ((mem_restrict _ _ q).mp hq).1) (fun q hq => ((mem_restrict _ _ q).mp hq).1) p hl exact (mem_restrict _ _ _).mpr ⟨hs,p,hpm,Path.prefix_self p⟩ - · exact List.mem_append_left _ + · exact mem_union_left _ theorem completion_wrap (a : PathSpace) (q : Path) : Same (completion (wrap q a)) (wrap q (completion a)) := by @@ -247,7 +248,7 @@ theorem completion_unwrap (a : PathSpace) (q : Path) : theorem closed_join_comm (a b : PathSpace) : Same (completion (union a b)) (completion (union b a)) := by - apply completion_congr; intro p; simp only [union, List.mem_append]; exact Or.comm + apply completion_congr; intro p; simp only [mem_union]; exact Or.comm theorem closed_join_idem {a : PathSpace} (ha : IsClosed a) : Same (completion (union a a)) a := by @@ -255,7 +256,7 @@ theorem closed_join_idem {a : PathSpace} (ha : IsClosed a) : exact fun p => (completion_congr h p).trans ((closed_iff_completion a).mp ha p) theorem closed_join_empty {a : PathSpace} (ha : IsClosed a) : - Same (completion (union a [])) a := by - simpa only [union, List.append_nil] using (closed_iff_completion a).mp ha + Same (completion (union a (ofPaths []))) a := by + simpa only [ofPaths_nil, Zippy.union_empty] using (closed_iff_completion a).mp ha -end PathMapModel.PathSpace +end PrunedModel.Convex diff --git a/lean/PathMapModel/ConvexGeometry.lean b/lean/PrunedModel/Convex/Geometry.lean similarity index 94% rename from lean/PathMapModel/ConvexGeometry.lean rename to lean/PrunedModel/Convex/Geometry.lean index b4af7867..8b57c8c1 100644 --- a/lean/PathMapModel/ConvexGeometry.lean +++ b/lean/PrunedModel/Convex/Geometry.lean @@ -1,6 +1,7 @@ -import PathMapModel.ConvexPruning +import PrunedModel.Convex.Pruning -namespace PathMapModel.PathSpace +namespace PrunedModel.Convex +open PathMapModel /-- Prefix-order convexity; this does not require prefix closure. -/ def IsConvex (a : PathSpace) : Prop := ∀ p ∈ a, ∀ r ∈ a, ∀ q, @@ -45,7 +46,7 @@ theorem pruning_basis_cut (x t : PathSpace) : theorem pruning_basis_raffinate (x t : PathSpace) : Same (raffinate x (basis (diff x (retain x t)))) (retain x t) := by - intro p; simp only [raffinate,mem_diff,pruning_basis_cut,mem_retain]; grind + intro p; simp only [raffinate,Zippy.raffination,mem_diff,pruning_basis_cut,mem_retain]; grind theorem convexMeet_basis (a b : PathSpace) : Same (raffinate (inter a b) (basis (diff (inter a b) (convexMeet a b)))) (convexMeet a b) := pruning_basis_raffinate _ _ @@ -64,10 +65,10 @@ theorem divergence_convexSubtract (a b c : PathSpace) : theorem divergence_subtract_partition (a b c : PathSpace) : Same (divergence a c) (union (divergence (convexSubtract a b) c) (divergence (inter (hull a) b) c)) := by have hs : Same (hull a) (union (diff (hull a) b) (inter (hull a) b)) := by - intro p; simp only [union,List.mem_append,mem_diff,mem_inter]; grind + intro p; simp only [mem_union,mem_diff,mem_inter]; grind intro p rw [← divergence_hull_left a c p,divergence_congr hs (fun _ => Iff.rfl),divergence_union_left] - simp only [union,List.mem_append] + simp only [mem_union] have he : Same (divergence (convexSubtract a b) c) (divergence (diff (hull a) b) c) := by intro q; exact (divergence_hull_left _ _ q).symm.trans (divergence_congr (hull_convexSubtract a b) (fun _ => Iff.rfl) q) rw [he] @@ -83,7 +84,7 @@ theorem branches_convexSubtract (a b : PathSpace) : Included (branches (convexSu theorem convex_partition (a b : PathSpace) : Same (union (convexSubtract a b) (convexSubtract a (diff (hull a) b))) a := by - intro p; simp only [union,List.mem_append,mem_convexSubtract,mem_diff] + intro p; simp only [mem_union,mem_convexSubtract,mem_diff] constructor · grind · intro hp; obtain ⟨t,ht,hpt⟩ := hull_covers hp @@ -92,8 +93,8 @@ theorem convex_partition (a b : PathSpace) : · exact Or.inl ⟨hp,t,ht,hb,hpt⟩ theorem convex_partition_disjoint (a b : PathSpace) : - Same (convexMeet (convexSubtract a b) (convexSubtract a (diff (hull a) b))) [] := by - intro p; simp only [mem_convexMeet,hull_convexSubtract,mem_diff,List.not_mem_nil,iff_false]; grind + Same (convexMeet (convexSubtract a b) (convexSubtract a (diff (hull a) b))) (ofPaths []) := by + intro p; simp only [mem_convexMeet,hull_convexSubtract,mem_diff,mem_ofPaths,List.not_mem_nil,iff_false]; grind theorem branches_convex_partition (a b : PathSpace) (p : Path) : p ∈ branches a ↔ p ∈ branches (convexSubtract a b) ∨ @@ -124,4 +125,4 @@ theorem convexLiteralSubtract_hull (a b : PathSpace) : intro t ht; obtain ⟨hh,hn⟩ := (mem_diff _ _ _).mp ht exact hull_surviving_diff hh hn -end PathMapModel.PathSpace +end PrunedModel.Convex diff --git a/lean/PrunedModel/Convex/Map.lean b/lean/PrunedModel/Convex/Map.lean new file mode 100644 index 00000000..d32a51fd --- /dev/null +++ b/lean/PrunedModel/Convex/Map.lean @@ -0,0 +1,74 @@ +import PrunedModel.Convex.Algebra + +/-! Payload-preserving operators on the existing pruned model. The canonical +constructor and lookup lemmas come from `PrunedModel`, not a second map model. -/ +namespace PrunedModel.Convex +open PathMapModel + +theorem mem_ofMap {V : Type} (a : PrunedMap V) (p : Path) : + p ∈ ofMap a ↔ (a.valAt p).isSome = true := by + simp only [ofMap, mem_ofPaths, PrunedMap.keys, PrunedMap.valAt] + exact ⟨lookup_isSome_of_mem_keys, mem_keys_of_lookup_isSome⟩ +end PrunedModel.Convex + +namespace PrunedModel.PrunedMap +open PathMapModel Convex + +/-- Select values from the left map using a unit-valued support mask. -/ +def selectSupport {V : Type} (a : PrunedMap V) (support : PathSpace) : PrunedMap V := + mk' (a.entries.filter fun kv => decide (kv.1 ∈ support)) + +theorem valAt_selectSupport {V : Type} (a : PrunedMap V) (support : PathSpace) (p : Path) : + (selectSupport a support).valAt p = if p ∈ support then a.valAt p else none := by + rw [selectSupport, valAt_mk', lookup_filter_key (fun k => decide (k ∈ support))] + simp only [decide_eq_true_eq, valAt] + +theorem selectSupport_keys {V : Type} (a : PrunedMap V) (support : PathSpace) (p : Path) : + p ∈ ofMap (selectSupport a support) ↔ p ∈ ofMap a ∧ p ∈ support := by + simp only [mem_ofMap, valAt_selectSupport] + split <;> simp_all + +def retain {V W : Type} (a : PrunedMap V) (b : PrunedMap W) : PrunedMap V := + selectSupport a (Convex.retain (ofMap a) (ofMap b)) +def basis {V : Type} (a : PrunedMap V) : PrunedMap V := selectSupport a (Convex.basis (ofMap a)) +def hull {V : Type} (a : PrunedMap V) : PrunedMap V := selectSupport a (Convex.hull (ofMap a)) +def divergence {V W : Type} (a : PrunedMap V) (b : PrunedMap W) : PathSpace := + Convex.divergence (ofMap a) (ofMap b) +def branches {V : Type} (a : PrunedMap V) : PathSpace := divergence a a + +def convexMeet {V W : Type} (a : PrunedMap V) (b : PrunedMap W) : PrunedMap V := + selectSupport a (Convex.convexMeet (ofMap a) (ofMap b)) +def convexSubtract {V W : Type} (a : PrunedMap V) (b : PrunedMap W) : PrunedMap V := + selectSupport a (Convex.convexSubtract (ofMap a) (ofMap b)) + +theorem retain_support {V W : Type} (a : PrunedMap V) (b : PrunedMap W) : + Same (ofMap (retain a b)) (Convex.retain (ofMap a) (ofMap b)) := by + intro p; rw [retain, selectSupport_keys] + exact ⟨And.right, fun h => ⟨((mem_retain _ _ _).mp h).1, h⟩⟩ + +theorem convexMeet_support {V W : Type} (a : PrunedMap V) (b : PrunedMap W) : + Same (ofMap (convexMeet a b)) (Convex.convexMeet (ofMap a) (ofMap b)) := by + intro p; rw [convexMeet, selectSupport_keys] + exact ⟨And.right, fun h => ⟨((mem_convexMeet _ _ _).mp h).1, h⟩⟩ + +theorem convexSubtract_support {V W : Type} (a : PrunedMap V) (b : PrunedMap W) : + Same (ofMap (convexSubtract a b)) (Convex.convexSubtract (ofMap a) (ofMap b)) := by + intro p; rw [convexSubtract, selectSupport_keys] + exact ⟨And.right, fun h => ⟨((mem_convexSubtract _ _ _).mp h).1, h⟩⟩ +end PrunedModel.PrunedMap + +namespace PrunedModel.PZip +/-- Relative focus semantics, with the output zipper restored by grafting. -/ +def retain {V W : Type} (a : PZip V) (b : PZip W) (out : PZip V) : PZip V := + out.graftMap (a.makeMap.retain b.makeMap) +def basis {V : Type} (a out : PZip V) : PZip V := out.graftMap a.makeMap.basis +def hull {V : Type} (a out : PZip V) : PZip V := out.graftMap a.makeMap.hull +def divergence {V W : Type} (a : PZip V) (b : PZip W) (out : PZip Unit) : PZip Unit := + out.graftMap (a.makeMap.divergence b.makeMap) +def branches {V : Type} (a : PZip V) (out : PZip Unit) : PZip Unit := + out.graftMap a.makeMap.branches +def convexMeet {V W : Type} (a : PZip V) (b : PZip W) (out : PZip V) : PZip V := + out.graftMap (a.makeMap.convexMeet b.makeMap) +def convexSubtract {V W : Type} (a : PZip V) (b : PZip W) (out : PZip V) : PZip V := + out.graftMap (a.makeMap.convexSubtract b.makeMap) +end PrunedModel.PZip diff --git a/lean/PrunedModel/Convex/Mixed.lean b/lean/PrunedModel/Convex/Mixed.lean new file mode 100644 index 00000000..2f915f3d --- /dev/null +++ b/lean/PrunedModel/Convex/Mixed.lean @@ -0,0 +1,22 @@ +import PrunedModel.Convex.Map +import PathMapModel.Map + +/-! The mixed fuzzer can contain dangling paths. Convex operations observe its +valued projection in the pruned model, then graft the canonical result back. +All operation definitions and laws live in the pruned model. -/ +namespace PathMapModel + +private def pruned {V : Type} (a : PathMap V) : PrunedModel.PrunedMap V := + PrunedModel.PrunedMap.mk' a.vals +private def mixed {V : Type} (a : PrunedModel.PrunedMap V) : PathMap V := + PathMap.mk' a.entries [] + +namespace Zip + +def convexMeet {V W : Type} (a : Zip V) (b : Zip W) (out : Zip V) : Zip V := + out.graftMap (mixed ((pruned a.makeMap).convexMeet (pruned b.makeMap))) +def convexSubtract {V W : Type} (a : Zip V) (b : Zip W) (out : Zip V) : Zip V := + out.graftMap (mixed ((pruned a.makeMap).convexSubtract (pruned b.makeMap))) + +end Zip +end PathMapModel diff --git a/lean/PathMapModel/ConvexMorphisms.lean b/lean/PrunedModel/Convex/Morphisms.lean similarity index 90% rename from lean/PathMapModel/ConvexMorphisms.lean rename to lean/PrunedModel/Convex/Morphisms.lean index 2d8a3c1d..a64ba8f8 100644 --- a/lean/PathMapModel/ConvexMorphisms.lean +++ b/lean/PrunedModel/Convex/Morphisms.lean @@ -1,6 +1,7 @@ -import PathMapModel.ConvexGeometry +import PrunedModel.Convex.Geometry namespace PathMapModel.Path +open PathMapModel theorem prefix_append_same (r p q : Path) : (r ++ p ≼ r ++ q) = (p ≼ q) := by induction r with @@ -11,7 +12,8 @@ theorem prefix_append (p q : Path) : (p ≼ p ++ q) = true := (prefix_iff_extension _ _).mpr ⟨q,rfl⟩ end PathMapModel.Path -namespace PathMapModel.PathSpace +namespace PrunedModel.Convex +open PathMapModel theorem mem_hull_max (a : PathSpace) (p : Path) : p ∈ hull a ↔ p ∈ a ∧ ∀ q ∈ a, (p ≼ q) = true → p = q := by @@ -133,11 +135,15 @@ theorem convexSubtract_product {code : PathSpace} (hc : Antichain code) (a b : P exact (convexSubtract_product_at hc hr a b q).mpr hq theorem convexMeet_wrap (r : Path) (a b : PathSpace) : Same (convexMeet (wrap r a) (wrap r b)) (wrap r (convexMeet a b)) := by - have hc : Antichain [r] := by intro p hp q hq _; simp only [List.mem_singleton] at hp hq; exact hp.trans hq.symm - simpa only [product,List.flatMap_cons,List.flatMap_nil,List.append_nil,wrap] using convexMeet_product hc a b + have hc : Antichain [r] := by intro p hp q hq _; simp only [mem_ofPaths,List.mem_singleton] at hp hq; exact hp.trans hq.symm + have hw : ∀ s : PathSpace, product [r] s = wrap r s := by + intro s; apply Zippy.ext; intro p; simp [mem_product,mem_wrap] + simpa only [hw] using convexMeet_product hc a b theorem convexSubtract_wrap (r : Path) (a b : PathSpace) : Same (convexSubtract (wrap r a) (wrap r b)) (wrap r (convexSubtract a b)) := by - have hc : Antichain [r] := by intro p hp q hq _; simp only [List.mem_singleton] at hp hq; exact hp.trans hq.symm - simpa only [product,List.flatMap_cons,List.flatMap_nil,List.append_nil,wrap] using convexSubtract_product hc a b + have hc : Antichain [r] := by intro p hp q hq _; simp only [mem_ofPaths,List.mem_singleton] at hp hq; exact hp.trans hq.symm + have hw : ∀ s : PathSpace, product [r] s = wrap r s := by + intro s; apply Zippy.ext; intro p; simp [mem_product,mem_wrap] + simpa only [hw] using convexSubtract_product hc a b -end PathMapModel.PathSpace +end PrunedModel.Convex diff --git a/lean/PathMapModel/ConvexOrder.lean b/lean/PrunedModel/Convex/Order.lean similarity index 90% rename from lean/PathMapModel/ConvexOrder.lean rename to lean/PrunedModel/Convex/Order.lean index 57d9efd4..153a495f 100644 --- a/lean/PathMapModel/ConvexOrder.lean +++ b/lean/PrunedModel/Convex/Order.lean @@ -1,6 +1,7 @@ -import PathMapModel.Convex +import PrunedModel.Convex.Algebra -namespace PathMapModel.PathSpace +namespace PrunedModel.Convex +open PathMapModel theorem convexLE_refl (a : PathSpace) : ConvexLE a a := ⟨fun _ h => h, fun _ h => h⟩ theorem convexLE_trans {a b c : PathSpace} (h : ConvexLE a b) (k : ConvexLE b c) : ConvexLE a c := @@ -68,9 +69,9 @@ theorem hull_union_compatible {a b : PathSpace} (h : Antichain (union (hull a) ( theorem convex_union_lub {a b : PathSpace} (h : Antichain (union (hull a) (hull b))) (x : PathSpace) : ConvexLE (union a b) x ↔ ConvexLE a x ∧ ConvexLE b x := by - simp only [ConvexLE,Included,union,List.mem_append] + simp only [ConvexLE,Included,mem_union] have hh := hull_union_compatible h - simp only [union] at hh + simp only [Same,mem_union] at hh simp only [hh] grind @@ -79,10 +80,10 @@ theorem convex_compatible (a b : PathSpace) : constructor · rintro ⟨c,ha,hb⟩ p hp q hq hpq have hh : Included (union (hull a) (hull b)) (hull c) := by - intro t ht; rcases (List.mem_append.mp ht) with ht | ht + intro t ht; rcases ((mem_union _ _ _).mp ht) with ht | ht · exact ha.2 t ht · exact hb.2 t ht - exact hull_isAntichain c p (hh p hp) q (hh q hq) hpq + exact hull_is_antichain c p (hh p hp) q (hh q hq) hpq · intro h; exact ⟨union a b,(convex_union_lub h _).mp (convexLE_refl _)⟩ /-- All Boolean operations on canonical prunings reduce to operations on tips. -/ @@ -91,7 +92,7 @@ theorem pruning_meet {a t u : PathSpace} (ht : Included t (hull a)) (hu : Includ intro p; simp only [mem_convexMeet,hull_retain ht,hull_retain hu,mem_retain,mem_inter]; grind theorem pruning_union (a t u : PathSpace) : Same (union (retain a t) (retain a u)) (retain a (union t u)) := by - intro p; simp only [union,List.mem_append,mem_retain]; grind + intro p; simp only [mem_union,mem_retain]; grind theorem pruning_subtract {a t : PathSpace} (ht : Included t (hull a)) (b : PathSpace) : Same (convexSubtract (retain a t) b) (retain a (diff t b)) := by @@ -116,14 +117,15 @@ theorem pruning_injective {a t u : PathSpace} (ht : Included t (hull a)) (hu : I · intro h p; exact (hull_retain ht p).symm.trans ((hull_congr h p).trans (hull_retain hu p)) · intro h; exact retain_congr (fun _ => Iff.rfl) h -theorem pruning_bottom (a : PathSpace) : Same (retain a []) [] := by intro p; simp [mem_retain] +theorem pruning_bottom (a : PathSpace) : Same (retain a (ofPaths [])) (ofPaths []) := by intro p; simp [mem_retain] theorem convexSubtract_faithful (b c : PathSpace) : (∀ a, Same (convexSubtract a b) (convexSubtract a c)) ↔ Same b c := by constructor · intro h p have hh := h [p] p - simp [mem_convexSubtract,hull] at hh + simp [mem_convexSubtract,mem_hull] at hh + have hs := Path.prefix_self p grind · intro h a; exact convexSubtract_congr (fun _ => Iff.rfl) h @@ -156,9 +158,11 @@ theorem convexMeetMany_normal (a : PathSpace) (bs : List PathSpace) : simp only [convexMeetMany,mem_convexMeet,hull_convexMeetMany,ih,mem_retain,List.map_cons,interMany,mem_inter] grind +def unionMany (spaces : List PathSpace) : PathSpace := spaces.foldr union (ofPaths []) + theorem convex_normal_form (a : PathSpace) (bs masks : List PathSpace) : - Same (convexSubtract (convexMeetMany a bs) masks.flatten) - (retain (interMany a bs) (diff (interMany (hull a) (bs.map hull)) masks.flatten)) := by + Same (convexSubtract (convexMeetMany a bs) (unionMany masks)) + (retain (interMany a bs) (diff (interMany (hull a) (bs.map hull)) (unionMany masks))) := by intro p; simp only [mem_convexSubtract,hull_convexMeetMany,convexMeetMany_normal,mem_retain,mem_diff]; grind def convexSubtractMany (a : PathSpace) : List PathSpace → PathSpace @@ -166,14 +170,14 @@ def convexSubtractMany (a : PathSpace) : List PathSpace → PathSpace | b :: bs => convexSubtractMany (convexSubtract a b) bs theorem convexSubtractMany_normal (a : PathSpace) (masks : List PathSpace) : - Same (convexSubtractMany a masks) (convexSubtract a masks.flatten) := by + Same (convexSubtractMany a masks) (convexSubtract a (unionMany masks)) := by induction masks generalizing a with | nil => exact fun p => (convexSubtract_empty_right a p).symm - | cons b bs ih => intro p; exact (ih (convexSubtract a b) p).trans (convexSubtract_action a b bs.flatten p) + | cons b bs ih => intro p; exact (ih (convexSubtract a b) p).trans (convexSubtract_action a b (unionMany bs) p) theorem convex_many_normal_form (a : PathSpace) (bs masks : List PathSpace) : Same (convexSubtractMany (convexMeetMany a bs) masks) - (retain (interMany a bs) (diff (interMany (hull a) (bs.map hull)) masks.flatten)) := + (retain (interMany a bs) (diff (interMany (hull a) (bs.map hull)) (unionMany masks))) := fun p => (convexSubtractMany_normal _ _ p).trans (convex_normal_form a bs masks p) -end PathMapModel.PathSpace +end PrunedModel.Convex diff --git a/lean/PrunedModel/Convex/Path.lean b/lean/PrunedModel/Convex/Path.lean new file mode 100644 index 00000000..20c5e67e --- /dev/null +++ b/lean/PrunedModel/Convex/Path.lean @@ -0,0 +1,38 @@ +import PathMapModel.Basic + +namespace PathMapModel.Path + +def lcp : Path → Path → Path + | a :: as, b :: bs => if a == b then a :: lcp as bs else [] + | _, _ => [] + +/-- Termination is not a next byte. -/ +def divergence : Path → Path → Option Path + | a :: as, b :: bs => if a == b then (divergence as bs).map (a :: ·) else some [] + | _, _ => none + +@[simp] theorem divergence_self (p : Path) : divergence p p = none := by + induction p with + | nil => rfl + | cons a as ih => simp [divergence, ih] + +theorem divergence_comm (p q : Path) : divergence p q = divergence q p := by + induction p generalizing q with + | nil => cases q <;> rfl + | cons a as ih => + cases q with + | nil => rfl + | cons b bs => + by_cases h : a = b + · subst b; simp [divergence, ih] + · simp [divergence, h, Ne.symm h] + +@[simp] theorem divergence_nil_left (p : Path) : divergence [] p = none := by cases p <;> rfl +@[simp] theorem divergence_nil_right (p : Path) : divergence p [] = none := by cases p <;> rfl + +theorem divergence_wrap (p a b : Path) : + divergence (p ++ a) (p ++ b) = (divergence a b).map (p ++ ·) := by + induction p with + | nil => simp + | cons c cs ih => simp [divergence, ih, Option.map_map, Function.comp_def] +end PathMapModel.Path diff --git a/lean/PathMapModel/PathSetAlgebra.lean b/lean/PrunedModel/Convex/PathSetAlgebra.lean similarity index 92% rename from lean/PathMapModel/PathSetAlgebra.lean rename to lean/PrunedModel/Convex/PathSetAlgebra.lean index 2d647835..daf6ebe4 100644 --- a/lean/PathMapModel/PathSetAlgebra.lean +++ b/lean/PrunedModel/Convex/PathSetAlgebra.lean @@ -1,6 +1,7 @@ -import PathMapModel.PathSetGeometry +import PrunedModel.Convex.PathSetGeometry -namespace PathMapModel.PathSpace +namespace PrunedModel.Convex +open PathMapModel theorem divergence_congr {a b c f : PathSpace} (ha : ∀ p, p ∈ a ↔ p ∈ c) (hb : ∀ p, p ∈ b ↔ p ∈ f) (p : Path) : @@ -8,7 +9,7 @@ theorem divergence_congr {a b c f : PathSpace} simp only [mem_divergence, ha, hb] theorem divergence_terminal (a b : PathSpace) (p : Path) : - p ∈ divergence (union a [[]]) b ↔ p ∈ divergence a b := by + p ∈ divergence (union a (ofPaths [[]])) b ↔ p ∈ divergence a b := by rw [divergence_union_left] simp [union] @@ -16,7 +17,7 @@ theorem divergence_covered_marks {a b c : PathSpace} (hc : ∀ x ∈ b, ∃ y ∈ a, (x ≼ y) = true) (p : Path) : p ∈ divergence (union a b) c ↔ p ∈ divergence a c := by rw [divergence_union_left] - simp only [union, List.mem_append] + simp only [mem_union] exact ⟨fun h => h.elim id (divergence_covered_mono hc p), Or.inl⟩ theorem divergence_witness_absorption (a b c : PathSpace) (p : Path) : @@ -36,7 +37,7 @@ theorem branch_completion (a : PathSpace) (p : Path) : theorem completion_idempotent (a : PathSpace) (p : Path) : p ∈ completion (completion a) ↔ p ∈ completion a := by - simp only [completion, union, List.mem_append] + simp only [completion, mem_union] have h := branch_completion a p simp only [completion, union] at h grind @@ -44,7 +45,7 @@ theorem completion_idempotent (a : PathSpace) (p : Path) : theorem divergence_output_completion (a b : PathSpace) (p : Path) : p ∈ completion (divergence a b) ↔ p ∈ divergence a b := by change p ∈ union _ _ ↔ _ - simp only [union, List.mem_append] + simp only [mem_union] exact ⟨fun h => h.elim id divergence_output_closed, Or.inl⟩ theorem absorbed_branch_marks (a b : PathSpace) (p : Path) : @@ -81,18 +82,18 @@ theorem divergence_incremental (a b c f : PathSpace) (p : Path) : p ∈ divergence (union a c) (union b f) ↔ p ∈ divergence a b ∨ p ∈ divergence c b ∨ p ∈ divergence a f ∨ p ∈ divergence c f := by rw [divergence_union_left] - simp only [union, List.mem_append] + simp only [mem_union] have h1 := divergence_union_right a b f p have h2 := divergence_union_right c b f p - simp only [union, List.mem_append] at h1 h2 + simp only [mem_union] at h1 h2 grind theorem divergence_symmetric_difference {a b c : PathSpace} {p : Path} (h : p ∈ symDiff (divergence a c) (divergence b c)) : p ∈ divergence (symDiff a b) c := by - simp only [symDiff, union, List.mem_append, mem_diff] at h + simp only [symDiff, mem_union, mem_diff] at h rw [symDiff, divergence_union_left] - simp only [union, List.mem_append] + simp only [mem_union] exact h.elim (fun h => Or.inl (divergence_difference_lower h.1 h.2)) (fun h => Or.inr (divergence_difference_lower h.1 h.2)) @@ -128,7 +129,7 @@ theorem divergence_interior_attribution {a b : PathSpace} {p : Path} theorem divergence_interior_exact (a b : PathSpace) (p : Path) : p ∈ divergence (union a b) (divergence a b) ↔ p ∈ interior (divergence a b) := by rw [divergence_union_left] - simp only [union, List.mem_append] + simp only [mem_union] have ha := divergence_nested_exact a b p have hb := divergence_nested_exact b a p have hx : ∀ q, q ∈ divergence b a ↔ q ∈ divergence a b := divergence_comm b a @@ -138,4 +139,4 @@ theorem divergence_interior_exact (a b : PathSpace) (p : Path) : rw [he, hi] at hb have hc := divergence_interior_attribution (a := a) (b := b) (p := p) grind -end PathMapModel.PathSpace +end PrunedModel.Convex diff --git a/lean/PathMapModel/PathSetCardinality.lean b/lean/PrunedModel/Convex/PathSetCardinality.lean similarity index 66% rename from lean/PathMapModel/PathSetCardinality.lean rename to lean/PrunedModel/Convex/PathSetCardinality.lean index 0be09c1f..a42c4b89 100644 --- a/lean/PathMapModel/PathSetCardinality.lean +++ b/lean/PrunedModel/Convex/PathSetCardinality.lean @@ -1,49 +1,41 @@ -import PathMapModel.PathSetRoots +import PrunedModel.Convex.PathSetRoots -namespace PathMapModel.PathSpace - -theorem dedup_nodup (a : PathSpace) : a.eraseDups.Nodup := by - cases a with - | nil => simp - | cons p ps => - rw [List.eraseDups_cons,List.nodup_cons] - exact ⟨by simp, dedup_nodup (ps.filter fun q => !q == p)⟩ -termination_by a.length -decreasing_by have h := List.length_filter_le (fun q => !q == p) ps; simp only [List.length_cons]; omega - -theorem count_le_length (a : PathSpace) : count a ≤ a.length := - (dedup_nodup a).length_le_of_subset (fun _ h => List.mem_eraseDups.mp h) +namespace PrunedModel.Convex +open PathMapModel theorem count_mono {a b : PathSpace} (h : ∀ p ∈ a, p ∈ b) : count a ≤ count b := - (dedup_nodup a).length_le_of_subset (fun p hp => List.mem_eraseDups.mpr (h p (List.mem_eraseDups.mp hp))) + (keys_nodup a).length_le_of_subset (fun p hp => Zippy.mem_keys.mpr (h p (Zippy.mem_keys.mp hp))) theorem count_congr {a b : PathSpace} (h : ∀ p, p ∈ a ↔ p ∈ b) : count a = count b := Nat.le_antisymm (count_mono (fun p hp => (h p).mp hp)) (count_mono (fun p hp => (h p).mpr hp)) theorem equiv_iff (a b : PathSpace) : equiv a b = true ↔ ∀ p, p ∈ a ↔ p ∈ b := by - simp only [equiv,subset,Bool.and_eq_true,List.all_eq_true,List.contains_iff_mem] - constructor - · rintro ⟨h,k⟩ p; exact ⟨h p,k p⟩ - · intro h; exact ⟨fun p => (h p).mp,fun p => (h p).mpr⟩ + simp only [equiv, decide_eq_true_eq] + exact ⟨fun h p => h ▸ Iff.rfl, Zippy.ext⟩ theorem subset_iff (a b : PathSpace) : subset a b = true ↔ ∀ p ∈ a, p ∈ b := by simp [subset,List.all_eq_true] -theorem count_eq_zero (a : PathSpace) : count a = 0 ↔ a = [] := by - simp only [count,List.length_eq_zero_iff,List.eq_nil_iff_forall_not_mem,List.mem_eraseDups] - -theorem count_singleton (p : Path) : count [p] = 1 := by simp [count,List.eraseDups_cons] - -theorem count_nodup {a : PathSpace} (h : a.Nodup) : count a = a.length := by - apply Nat.le_antisymm (count_le_length a) - exact h.length_le_of_subset (fun _ h => List.mem_eraseDups.mpr h) +theorem count_eq_zero (a : PathSpace) : count a = 0 ↔ a = (ofPaths []) := by + simp only [count,List.length_eq_zero_iff,keys_eq_nil_iff] + +theorem count_singleton (p : Path) : count [p] = 1 := by + have hle := (keys_nodup (ofPaths [p])).length_le_of_subset (l₂ := [p]) (by + intro q hq; simpa using hq) + have hne : count [p] ≠ 0 := by + intro h + have he := (count_eq_zero _).mp h + have hp : p ∈ ofPaths [p] := by simp + rw [he] at hp + simp at hp + change count [p] ≤ 1 at hle + omega theorem count_union_le (a b : PathSpace) : count (union a b) ≤ count a + count b := by - have he : count (union a b) = count (a.eraseDups ++ b.eraseDups) := - count_congr (by intro p; simp [union]) - rw [he] - have hh := count_le_length (a.eraseDups ++ b.eraseDups) - simpa [List.length_append,count] using hh + have h := (keys_nodup (union a b)).length_le_of_subset (l₂ := a.keys ++ b.keys) (by + intro p hp + simpa only [List.mem_append, mem_keys, mem_union] using hp) + simpa only [List.length_append, count] using h /-- A relation assigning a distinct target to each source bounds cardinality. The target can be chosen noncomputably inside a proof; no choice appears in the @@ -52,26 +44,26 @@ theorem count_relation {a b : PathSpace} (r : Path → Path → Prop) (hex : ∀ p ∈ a, ∃ q ∈ b, r p q) (hinj : ∀ p ∈ a, ∀ p' ∈ a, ∀ q, r p q → r p' q → p = p') : count a ≤ count b := by classical - let f : {p : Path // p ∈ a.eraseDups} → Path := fun p => - Classical.choose (hex p.val (List.mem_eraseDups.mp p.property)) + let f : {p : Path // p ∈ a.keys} → Path := fun p => + Classical.choose (hex p.val (Zippy.mem_keys.mp p.property)) have hf : ∀ p, f p ∈ b ∧ r p.val (f p) := fun p => - Classical.choose_spec (hex p.val (List.mem_eraseDups.mp p.property)) - let out := a.eraseDups.attach.map f + Classical.choose_spec (hex p.val (Zippy.mem_keys.mp p.property)) + let out := a.keys.attach.map f have hout : out.Nodup := by - change (a.eraseDups.attach.map f).Pairwise (fun x y => x ≠ y) + change (a.keys.attach.map f).Pairwise (fun x y => x ≠ y) rw [List.pairwise_map] - have hv : a.eraseDups.attach.Pairwise (fun u v => u.val ≠ v.val) := by + have hv : a.keys.attach.Pairwise (fun u v => u.val ≠ v.val) := by rw [← List.pairwise_map] - simpa [List.Nodup] using dedup_nodup a + simpa [List.Nodup] using keys_nodup a apply hv.imp intro u v hne he - have hp := hinj u.val (List.mem_eraseDups.mp u.property) v.val - (List.mem_eraseDups.mp v.property) (f u) (hf u).2 (he ▸ (hf v).2) + have hp := hinj u.val (Zippy.mem_keys.mp u.property) v.val + (Zippy.mem_keys.mp v.property) (f u) (hf u).2 (he ▸ (hf v).2) exact hne hp - have hsub : out ⊆ b.eraseDups := by + have hsub : out ⊆ b.keys := by intro q hq obtain ⟨p,_,rfl⟩ := List.mem_map.mp hq - exact List.mem_eraseDups.mpr (hf p).1 + exact Zippy.mem_keys.mpr (hf p).1 have hlen := hout.length_le_of_subset hsub simpa [out,count] using hlen @@ -102,12 +94,12 @@ theorem double_covered_count {a b : PathSpace} (ha : Antichain a) (hex : ∀ p ∈ a, ∃ w : Path × Path, w.1 ∈ b ∧ w.2 ∈ b ∧ w.1 ≠ w.2 ∧ (p ≼ w.1) = true ∧ (p ≼ w.2) = true) : 2 * count a ≤ count b := by classical - let f : {p : Path // p ∈ a.eraseDups} → Path × Path := fun p => - Classical.choose (hex p.val (List.mem_eraseDups.mp p.property)) + let f : {p : Path // p ∈ a.keys} → Path × Path := fun p => + Classical.choose (hex p.val (Zippy.mem_keys.mp p.property)) have hf : ∀ p, (f p).1 ∈ b ∧ (f p).2 ∈ b ∧ (f p).1 ≠ (f p).2 ∧ (p.val ≼ (f p).1) = true ∧ (p.val ≼ (f p).2) = true := fun p => - Classical.choose_spec (hex p.val (List.mem_eraseDups.mp p.property)) - let out := a.eraseDups.attach.flatMap (fun p => [(f p).1,(f p).2]) + Classical.choose_spec (hex p.val (Zippy.mem_keys.mp p.property)) + let out := a.keys.attach.flatMap (fun p => [(f p).1,(f p).2]) have hpref : ∀ p, ∀ q ∈ [(f p).1,(f p).2], (p.val ≼ q) = true := by intro p q hq simp only [List.mem_cons,List.not_mem_nil,or_false] at hq @@ -119,34 +111,34 @@ theorem double_covered_count {a b : PathSpace} (ha : Antichain a) constructor · intro p hp exact List.Pairwise.cons (by simpa using (hf p).2.2.1) (List.Pairwise.cons (by simp) List.Pairwise.nil) - · have hv : a.eraseDups.attach.Pairwise (fun u v => u.val ≠ v.val) := by + · have hv : a.keys.attach.Pairwise (fun u v => u.val ≠ v.val) := by rw [← List.pairwise_map] - simpa [List.Nodup] using dedup_nodup a + simpa [List.Nodup] using keys_nodup a apply hv.imp intro u v hne x hx y hy he subst y have hu := hpref u x hx have hv := hpref v x hy - have hpu := List.mem_eraseDups.mp u.property - have hpv := List.mem_eraseDups.mp v.property + have hpu := Zippy.mem_keys.mp u.property + have hpv := Zippy.mem_keys.mp v.property rcases Path.prefixes_comparable hu hv with huv | hvu · exact hne (ha u.val hpu v.val hpv huv) · exact hne (ha v.val hpv u.val hpu hvu).symm - have hsub : out ⊆ b.eraseDups := by + have hsub : out ⊆ b.keys := by intro q hq obtain ⟨p,_,hp⟩ := List.mem_flatMap.mp hq - apply List.mem_eraseDups.mpr + apply Zippy.mem_keys.mpr simp only [List.mem_cons,List.not_mem_nil,or_false] at hp rcases hp with rfl | rfl · exact (hf p).1 · exact (hf p).2.1 - have hlen : ∀ ps : List {p : Path // p ∈ a.eraseDups}, + have hlen : ∀ ps : List {p : Path // p ∈ a.keys}, (ps.flatMap fun p => [(f p).1,(f p).2]).length = 2 * ps.length := by intro ps; induction ps with | nil => simp | cons p ps ih => simp [ih]; omega have hbound := hout.length_le_of_subset hsub - change (a.eraseDups.attach.flatMap _).length ≤ _ at hbound + change (a.keys.attach.flatMap _).length ≤ _ at hbound rw [hlen] at hbound simpa [count] using hbound @@ -182,7 +174,7 @@ theorem branch_iter_leaf_weight (a : PathSpace) (n : Nat) : rw [he] exact Nat.le_trans h ih -theorem branch_leaf_bound {a : PathSpace} {n : Nat} (h : branchIter a n ≠ []) : +theorem branch_leaf_bound {a : PathSpace} {n : Nat} (h : branchIter a n ≠ (ofPaths [])) : 2^n ≤ count (hull a) := by have hn : count (hull (branchIter a n)) ≠ 0 := by intro hh @@ -190,4 +182,4 @@ theorem branch_leaf_bound {a : PathSpace} {n : Nat} (h : branchIter a n ≠ []) have hpos : 1 ≤ count (hull (branchIter a n)) := by omega have hm := Nat.mul_le_mul_left (2^n) hpos exact Nat.le_trans (by simpa using hm) (branch_iter_leaf_weight a n) -end PathMapModel.PathSpace +end PrunedModel.Convex diff --git a/lean/PathMapModel/PathSetCertificates.lean b/lean/PrunedModel/Convex/PathSetCertificates.lean similarity index 63% rename from lean/PathMapModel/PathSetCertificates.lean rename to lean/PrunedModel/Convex/PathSetCertificates.lean index f2d85555..22b3f5bf 100644 --- a/lean/PathMapModel/PathSetCertificates.lean +++ b/lean/PrunedModel/Convex/PathSetCertificates.lean @@ -1,19 +1,8 @@ -import PathMapModel.PathSetUpdates +import PrunedModel.Convex.PathSetUpdates -/-! Bridges between the universally quantified set laws and the executable -Boolean catalogue. Set equations are proved pointwise; normalization preserves -membership. Cardinality and equality are explicitly set-based, so list order -and duplicate witnesses do not alter any law. -/ -namespace PathMapModel.PathSpace - -theorem normalize_equiv (a : PathSpace) : equiv (normalize a) a = true := - (equiv_iff _ _).mpr (mem_normalize a) - -theorem count_normalize (a : PathSpace) : count (normalize a) = count a := - count_congr (mem_normalize a) - -theorem normalize_empty (a : PathSpace) : normalize a = [] ↔ a = [] := by - simp only [List.eq_nil_iff_forall_not_mem,mem_normalize] +/-! Bridges between the universally quantified laws and the executable Boolean catalogue. -/ +namespace PrunedModel.Convex +open PathMapModel theorem basis_congr {a b : PathSpace} (h : ∀ p, p ∈ a ↔ p ∈ b) (p : Path) : p ∈ basis a ↔ p ∈ basis b := by simp only [mem_basis,h] @@ -40,18 +29,18 @@ theorem hull_prefixFree (a : PathSpace) : prefixFree (hull a) = true := (equiv_iff _ _).mpr (fun p => (basis_of_hull a p).symm) theorem terminal_invariance (a b : PathSpace) (p : Path) : - p ∈ divergence (union a [[]]) (union b [[]]) ↔ p ∈ divergence a b := by + p ∈ divergence (union a (ofPaths [[]])) (union b (ofPaths [[]])) ↔ p ∈ divergence a b := by rw [divergence_terminal,divergence_comm,divergence_terminal,divergence_comm] theorem branch_epsilon (a : PathSpace) (p : Path) : - p ∈ branches (union a [[]]) ↔ p ∈ branches a := terminal_invariance a a p + p ∈ branches (union a (ofPaths [[]])) ↔ p ∈ branches a := terminal_invariance a a p theorem output_branches {a b : PathSpace} {p : Path} (h : p ∈ branches (divergence a b)) : p ∈ divergence a b ∧ p ∈ branches a ∧ p ∈ branches b := ⟨divergence_output_closed h,divergence_output_branches h⟩ -theorem no_nonempty_branch_fixed_point {a : PathSpace} (ha : a ≠ []) : +theorem no_nonempty_branch_fixed_point {a : PathSpace} (ha : a ≠ (ofPaths [])) : equiv (branches a) a = false := by cases he : equiv (branches a) a with | false => rfl @@ -60,17 +49,17 @@ theorem no_nonempty_branch_fixed_point {a : PathSpace} (ha : a ≠ []) : theorem count_eq_one (a : PathSpace) : count a = 1 ↔ ∃ p, ∀ q, q ∈ a ↔ q = p := by constructor · intro h - have hl : a.eraseDups.length = 1 := h + have hl : a.keys.length = 1 := h obtain ⟨p,hp⟩ := List.length_eq_one_iff.mp hl - exact ⟨p,fun q => by rw [← List.mem_eraseDups,hp]; simp⟩ + exact ⟨p,fun q => by rw [← mem_keys a,hp]; simp⟩ · rintro ⟨p,hp⟩ have he : count a = count [p] := count_congr (by intro q; simpa using hp q) rw [he,count_singleton] theorem singleton_prefix_test (a b : PathSpace) : - (count a == 1 && b.all (fun q => a.all (· ≼ q))) = true ↔ + (count a == 1 && b.keys.all (fun q => a.keys.all (· ≼ q))) = true ↔ ∃ p, (∀ q, q ∈ a ↔ q = p) ∧ ∀ r ∈ b, (p ≼ r) = true := by - simp only [Bool.and_eq_true,beq_iff_eq,count_eq_one,List.all_eq_true] + simp only [Bool.and_eq_true,beq_iff_eq,count_eq_one,List.all_eq_true,mem_keys] constructor · rintro ⟨⟨p,hp⟩,he⟩ exact ⟨p,hp,fun r hr => he r hr p ((hp p).mpr rfl)⟩ @@ -82,16 +71,16 @@ theorem singleton_prefix_test (a b : PathSpace) : /-- The exact Boolean zero criterion used by the executable catalogue. -/ theorem zero_criterion_check (a b : PathSpace) : - (normalize (divergence a b)).isEmpty = - (a.isEmpty || b.isEmpty || - (count (hull a) == 1 && (hull b).all (fun q => (hull a).all (· ≼ q))) || - (count (hull b) == 1 && (hull a).all (fun q => (hull b).all (· ≼ q)))) := by - have hh : (normalize (divergence a b)).isEmpty = true ↔ - (a.isEmpty || b.isEmpty || - (count (hull a) == 1 && (hull b).all (fun q => (hull a).all (· ≼ q))) || - (count (hull b) == 1 && (hull a).all (fun q => (hull b).all (· ≼ q)))) = true := by - simp only [List.isEmpty_iff,normalize_empty,Bool.or_eq_true,singleton_prefix_test] + ((divergence a b)).keys.isEmpty = + (a.keys.isEmpty || b.keys.isEmpty || + (count (hull a) == 1 && (hull b).keys.all (fun q => (hull a).keys.all (· ≼ q))) || + (count (hull b) == 1 && (hull a).keys.all (fun q => (hull b).keys.all (· ≼ q)))) := by + have hh : ((divergence a b)).keys.isEmpty = true ↔ + (a.keys.isEmpty || b.keys.isEmpty || + (count (hull a) == 1 && (hull b).keys.all (fun q => (hull a).keys.all (· ≼ q))) || + (count (hull b) == 1 && (hull a).keys.all (fun q => (hull b).keys.all (· ≼ q)))) = true := by + simp only [List.isEmpty_iff,keys_eq_nil_iff,Bool.or_eq_true,singleton_prefix_test] rw [zero_criterion] grind exact Bool.eq_iff_iff.mpr hh -end PathMapModel.PathSpace +end PrunedModel.Convex diff --git a/lean/PrunedModel/Convex/PathSetChecks.lean b/lean/PrunedModel/Convex/PathSetChecks.lean new file mode 100644 index 00000000..46bcb83b --- /dev/null +++ b/lean/PrunedModel/Convex/PathSetChecks.lean @@ -0,0 +1,48 @@ +import PrunedModel.Convex.PathSetLaws +import PrunedModel.Convex.Map + +set_option maxRecDepth 4096 +set_option maxHeartbeats 0 +namespace PrunedModel.Convex.PathSetChecks +open PathMapModel +open PrunedModel.Convex + +def small : List PathSpace := [(ofPaths []), (ofPaths [[]]), (ofPaths [[0]]), (ofPaths [[1]]), (ofPaths [[],[0]]), (ofPaths [[],[1]]), (ofPaths [[0],[1]]), (ofPaths [[],[0],[1]])] +def fixtures : List PathSpace := small ++ + [(ofPaths [[0],[0,0],[0,1]]), (ofPaths [[0,0],[0,1]]), (ofPaths [[0],[1,0],[1,1,0],[1,1,1]]), + (ofPaths [[255,0],[255,255]]), (ofPaths [[0,0,0],[1],[0,1],[0,0,1]])] + +#guard (small.flatMap fun a => small.flatMap fun b => small.flatMap fun c => + small.map fun f => (PathSetLaws.failures (PathSetLaws.all a b c f)).isEmpty).all id +#guard (fixtures.flatMap fun a => fixtures.map fun b => + (PathSetLaws.failures (PathSetLaws.unary a ++ PathSetLaws.binary a b)).isEmpty).all id +#guard (fixtures.flatMap fun a => (List.range 4).flatMap fun m => (List.range 4).map fun n => + (PathSetLaws.failures (PathSetLaws.powers a m n)).isEmpty).all id + +-- Counterexamples are positively checked: these are NOT proposed rewrite rules. +#guard !equiv (divergence (divergence (ofPaths [[0,0]]) (ofPaths [[0,1]])) (ofPaths [[1]])) + (divergence (ofPaths [[0,0]]) (divergence (ofPaths [[0,1]]) (ofPaths [[1]]))) +#guard !equiv (divergence (inter (ofPaths [[0,0]]) (ofPaths [[0,1]])) (ofPaths [[1]])) + (inter (divergence (ofPaths [[0,0]]) (ofPaths [[1]])) (divergence (ofPaths [[0,1]]) (ofPaths [[1]]))) +#guard !equiv (divergence (diff (ofPaths [[0,0],[0,1]]) (ofPaths [[0,0]])) (ofPaths [[1]])) + (diff (divergence (ofPaths [[0,0],[0,1]]) (ofPaths [[1]])) (divergence (ofPaths [[0,0]]) (ofPaths [[1]]))) +#guard !equiv (restrict (divergence (ofPaths [[0,0]]) (ofPaths [[0,1]])) (ofPaths [[0,0],[0,1]])) + (divergence (restrict (ofPaths [[0,0]]) (ofPaths [[0,0],[0,1]])) (restrict (ofPaths [[0,1]]) (ofPaths [[0,0],[0,1]]))) +#guard !equiv (divergence (product (ofPaths [[0]]) (ofPaths [[2]])) (product (ofPaths [[0,1]]) (ofPaths [[2]]))) (divergence (ofPaths [[0]]) (ofPaths [[0,1]])) +#guard !equiv (divergence (ofPaths [[0],[1,0],[1,1,0],[1,1,1]]) (branches (ofPaths [[0],[1,0],[1,1,0],[1,1,1]]))) + (branches (branches (ofPaths [[0],[1,0],[1,1,0],[1,1,1]]))) +#guard !equiv (divergence (ofPaths [[0,0],[0,1]]) (ofPaths [[0]])) (divergence (ofPaths [[0,0],[0,1]]) (ofPaths [[0,0]])) +#guard !equiv (branches (ofPaths [[0],[0,0],[0,1]])) (branches (basis (ofPaths [[0],[0,0],[0,1]]))) +#guard equiv (branches (ofPaths [[102,111,111],[102,111,111,100]])) (ofPaths []) -- foo / food +#guard equiv (divergence (ofPaths [[102,111,111,100]]) (ofPaths [[102,111,117,114]])) (ofPaths [[102,111]]) -- food / four +#guard count (divergence (ofPaths [[0,0,0]]) (ofPaths [[1],[0,1],[0,0,1]])) == 3 + +-- Payload operators preserve the original values at selected paths. +def valued : PrunedMap Nat := PrunedMap.mk' [([0],10),([0,1],20),([2],30)] +#guard valued.basis.valAt [0] == some 10 +#guard valued.basis.valAt [0,1] == none +#guard valued.hull.valAt [0,1] == some 20 +#guard valued.hull.valAt [0] == none +#guard equiv valued.branches (ofPaths [[]]) +#guard equiv (valued.divergence (PrunedMap.empty : PrunedMap Nat)) (ofPaths []) +end PrunedModel.Convex.PathSetChecks diff --git a/lean/PathMapModel/PathSetDepth.lean b/lean/PrunedModel/Convex/PathSetDepth.lean similarity index 79% rename from lean/PathMapModel/PathSetDepth.lean rename to lean/PrunedModel/Convex/PathSetDepth.lean index 58aa1329..be79733a 100644 --- a/lean/PathMapModel/PathSetDepth.lean +++ b/lean/PrunedModel/Convex/PathSetDepth.lean @@ -1,6 +1,7 @@ -import PathMapModel.PathSetLCP +import PrunedModel.Convex.PathSetLCP namespace PathMapModel.Path +open PathMapModel theorem divergence_of_prefix {x y : Path} (h : (x ≼ y) = true) : divergence x y = none := by obtain ⟨r,rfl⟩ := (prefix_iff_extension _ _).mp h @@ -19,7 +20,8 @@ theorem divergence_none_iff (x y : Path) : · rw [divergence_comm]; exact divergence_of_prefix h end PathMapModel.Path -namespace PathMapModel.PathSpace +namespace PrunedModel.Convex +open PathMapModel private theorem foldl_max_le (ns : List Nat) (k n : Nat) : ns.foldl max k ≤ n ↔ k ≤ n ∧ ∀ x ∈ ns, x ≤ n := by induction ns generalizing k with @@ -33,15 +35,15 @@ theorem height_le (a : PathSpace) (n : Nat) : theorem length_le_height {a : PathSpace} {p : Path} (hp : p ∈ a) : p.length ≤ height a := (height_le a (height a)).mp (Nat.le_refl _) p hp -theorem height_attained {a : PathSpace} (h : a ≠ []) : ∃ p ∈ a, height a = p.length := by - let p := a.maxOn List.length h - have hp : p ∈ a := List.maxOn_mem +theorem height_attained {a : PathSpace} (h : a ≠ (ofPaths [])) : ∃ p ∈ a, height a = p.length := by + let p := a.keys.maxOn List.length (fun he => h ((keys_eq_nil_iff a).mp he)) + have hp : p ∈ a := Zippy.mem_keys.mp List.maxOn_mem refine ⟨p,hp,Nat.le_antisymm ?_ (length_le_height hp)⟩ apply (height_le a p.length).mpr intro q hq - exact List.le_apply_maxOn_of_mem hq + exact List.le_apply_maxOn_of_mem (Zippy.mem_keys.mpr hq) -theorem divergence_depth {a b : PathSpace} (h : divergence a b ≠ []) : +theorem divergence_depth {a b : PathSpace} (h : divergence a b ≠ (ofPaths [])) : height (divergence a b) < min (height a) (height b) := by obtain ⟨p,hp,he⟩ := height_attained h obtain ⟨x,hx,y,hy,hd⟩ := (mem_divergence _ _ _).mp hp @@ -61,13 +63,13 @@ theorem branch_iter_depth (a : PathSpace) (n : Nat) {p : Path} have hb := ih hx omega -theorem branch_depth_nilpotence (a : PathSpace) : branchIter a (height a + 1) = [] := by - apply List.eq_nil_iff_forall_not_mem.mpr +theorem branch_depth_nilpotence (a : PathSpace) : branchIter a (height a + 1) = (ofPaths []) := by + apply (eq_empty_iff _).mpr intro p hp have h := branch_iter_depth a (height a + 1) hp omega -theorem branch_no_fixed_point {a : PathSpace} (h : a ≠ []) : +theorem branch_no_fixed_point {a : PathSpace} (h : a ≠ (ofPaths [])) : ¬ (∀ p, p ∈ branches a ↔ p ∈ a) := by intro he obtain ⟨p,hp,hmax⟩ := height_attained h @@ -76,13 +78,13 @@ theorem branch_no_fixed_point {a : PathSpace} (h : a ≠ []) : have hx := length_le_height hx omega -theorem singleton_chain (q : Path) (a : PathSpace) : branches (divergence [q] a) = [] := by - apply List.eq_nil_iff_forall_not_mem.mpr +theorem singleton_chain (q : Path) (a : PathSpace) : branches (divergence [q] a) = (ofPaths []) := by + apply (eq_empty_iff _).mpr intro p hp obtain ⟨x,hx,y,hy,hd⟩ := (mem_divergence _ _ _).mp hp obtain ⟨qx,hqx,hpx⟩ := divergence_output_covered hx obtain ⟨qy,hqy,hpy⟩ := divergence_output_covered hy - simp only [List.mem_singleton] at hqx hqy + simp only [mem_ofPaths, List.mem_singleton] at hqx hqy subst qx; subst qy have hn := (Path.divergence_none_iff x y).mpr (Path.prefixes_comparable hpx hpy) simp [hd] at hn @@ -90,6 +92,6 @@ theorem singleton_chain (q : Path) (a : PathSpace) : branches (divergence [q] a) theorem singleton_existing_branches {q p : Path} {a : PathSpace} (h : p ∈ interior (divergence [q] a)) : p ∈ branches a := by rcases divergence_interior_attribution h with hs | hs - · simp [branches,divergence] at hs + · simp [branches,mem_divergence] at hs · exact hs -end PathMapModel.PathSpace +end PrunedModel.Convex diff --git a/lean/PathMapModel/PathSetExtrema.lean b/lean/PrunedModel/Convex/PathSetExtrema.lean similarity index 91% rename from lean/PathMapModel/PathSetExtrema.lean rename to lean/PrunedModel/Convex/PathSetExtrema.lean index 4f499154..af043775 100644 --- a/lean/PathMapModel/PathSetExtrema.lean +++ b/lean/PrunedModel/Convex/PathSetExtrema.lean @@ -1,13 +1,14 @@ -import PathMapModel.PathSetAlgebra +import PrunedModel.Convex.PathSetAlgebra import Init.Data.List.MinMaxOn namespace PathMapModel.Path +open PathMapModel theorem prefix_iff_list (p q : Path) : (p ≼ q) = true ↔ p <+: q := by rw [prefix_iff_extension, List.prefix_iff_exists_eq_append] @[simp] theorem prefix_self (p : Path) : (p ≼ p) = true := - (prefix_iff_list p p).mpr List.prefix_rfl + PrunedModel.isPrefixOf_self p theorem prefix_trans {p q r : Path} (h : (p ≼ q) = true) (k : (q ≼ r) = true) : (p ≼ r) = true := (prefix_iff_list _ _).mpr @@ -28,11 +29,12 @@ theorem prefixes_comparable {p q r : Path} (h : (p ≼ r) = true) (k : (q ≼ r) ((prefix_iff_list _ _).mp h) ((prefix_iff_list _ _).mp k) end PathMapModel.Path -namespace PathMapModel.PathSpace +namespace PrunedModel.Convex +open PathMapModel theorem hull_covers {a : PathSpace} {p : Path} (hp : p ∈ a) : ∃ q ∈ hull a, (p ≼ q) = true := by - let s := a.filter (p ≼ ·) + let s := a.keys.filter (p ≼ ·) have hs : p ∈ s := by simp [s,hp] let q := s.maxOn List.length (List.ne_nil_of_mem hs) have hq : q ∈ s := List.maxOn_mem @@ -48,7 +50,7 @@ theorem hull_covers {a : PathSpace} {p : Path} (hp : p ∈ a) : theorem basis_below {a : PathSpace} {p : Path} (hp : p ∈ a) : ∃ q ∈ basis a, (q ≼ p) = true := by - let s := a.filter (· ≼ p) + let s := a.keys.filter (· ≼ p) have hs : p ∈ s := by simp [s,hp] let q := s.minOn List.length (List.ne_nil_of_mem hs) have hq : q ∈ s := List.minOn_mem @@ -62,19 +64,19 @@ theorem basis_below {a : PathSpace} {p : Path} (hp : p ∈ a) : have hl : q.length ≤ r.length := List.apply_minOn_le_of_mem hrs exact False.elim (hne (Path.prefix_eq_of_length he hl)) -theorem hull_nonempty (a : PathSpace) : hull a = [] ↔ a = [] := by +theorem hull_nonempty (a : PathSpace) : hull a = (ofPaths []) ↔ a = (ofPaths []) := by constructor · intro h - apply List.eq_nil_iff_forall_not_mem.mpr + apply (eq_empty_iff a).mpr intro p hp obtain ⟨q,hq,_⟩ := hull_covers hp simp [h] at hq · rintro rfl; rfl -theorem basis_nonempty (a : PathSpace) : basis a = [] ↔ a = [] := by +theorem basis_nonempty (a : PathSpace) : basis a = (ofPaths []) ↔ a = (ofPaths []) := by constructor · intro h - apply List.eq_nil_iff_forall_not_mem.mpr + apply (eq_empty_iff a).mpr intro p hp obtain ⟨q,hq,_⟩ := basis_below hp simp [h] at hq @@ -102,7 +104,9 @@ theorem hull_of_basis (a : PathSpace) (p : Path) : p ∈ hull (basis a) ↔ p theorem mem_restrict (a b : PathSpace) (p : Path) : p ∈ restrict a b ↔ p ∈ a ∧ ∃ q ∈ b, (q ≼ p) = true := by - simp [restrict, List.any_eq_true] + rw [Zippy.mem_restriction] + simp only [Path.prefix_iff_extension] + grind theorem restriction_basis_mask (a b : PathSpace) (p : Path) : p ∈ restrict a (basis b) ↔ p ∈ restrict a b := by @@ -170,10 +174,10 @@ theorem hull_union (a b : PathSpace) (p : Path) : p ∈ hull (union a b) ↔ p ∈ hull (union (hull a) (hull b)) := by apply hull_cofinal · intro q hq - simp only [union, List.mem_append] at hq ⊢ + simp only [mem_union] at hq ⊢ exact hq.elim (fun h => Or.inl (hull_subset a h)) (fun h => Or.inr (hull_subset b h)) · intro q hq - simp only [union, List.mem_append] at hq ⊢ + simp only [mem_union] at hq ⊢ rcases hq with hq | hq · obtain ⟨r,hr,hqr⟩ := hull_covers hq; exact ⟨r,Or.inl hr,hqr⟩ · obtain ⟨r,hr,hqr⟩ := hull_covers hq; exact ⟨r,Or.inr hr,hqr⟩ @@ -182,11 +186,11 @@ theorem basis_union (a b : PathSpace) (p : Path) : p ∈ basis (union a b) ↔ p ∈ basis (union (basis a) (basis b)) := by apply basis_coinitial · intro q hq - simp only [union, List.mem_append] at hq ⊢ + simp only [mem_union] at hq ⊢ exact hq.elim (fun h => Or.inl (basis_subset a h)) (fun h => Or.inr (basis_subset b h)) · intro q hq - simp only [union, List.mem_append] at hq ⊢ + simp only [mem_union] at hq ⊢ rcases hq with hq | hq · obtain ⟨r,hr,hrq⟩ := basis_below hq; exact ⟨r,Or.inl hr,hrq⟩ · obtain ⟨r,hr,hrq⟩ := basis_below hq; exact ⟨r,Or.inr hr,hrq⟩ -end PathMapModel.PathSpace +end PrunedModel.Convex diff --git a/lean/PathMapModel/PathSetFork.lean b/lean/PrunedModel/Convex/PathSetFork.lean similarity index 81% rename from lean/PathMapModel/PathSetFork.lean rename to lean/PrunedModel/Convex/PathSetFork.lean index 5ce699e3..ea49db5f 100644 --- a/lean/PathMapModel/PathSetFork.lean +++ b/lean/PrunedModel/Convex/PathSetFork.lean @@ -1,6 +1,7 @@ -import PathMapModel.PathSetStructure +import PrunedModel.Convex.PathSetStructure namespace PathMapModel.Path +open PathMapModel theorem divergence_append_single_lcp (x y : Path) (a b : UInt8) {p : Path} (h : divergence (x ++ [a]) (y ++ [b]) = some p) : lcp x y = p := by @@ -53,31 +54,32 @@ theorem fork_witness (x y : Path) : ∃ a ∈ ([0,1] : List UInt8), ∃ b ∈ ([ · exact ⟨0,by decide,0,by decide,by simp [divergence,lcp,hcd]⟩ end PathMapModel.Path -namespace PathMapModel.PathSpace +namespace PrunedModel.Convex +open PathMapModel theorem fork_lcp (a b : PathSpace) (p : Path) : - p ∈ divergence (product a [[0],[1]]) (product b [[0],[1]]) ↔ p ∈ lcpProduct a b := by + p ∈ divergence (product a (ofPaths [[0],[1]])) (product b (ofPaths [[0],[1]])) ↔ p ∈ lcpProduct a b := by constructor · intro h obtain ⟨x,hx,y,hy,hd⟩ := (mem_divergence _ _ _).mp h obtain ⟨u,hu,c,hc,rfl⟩ := (mem_product _ _ _).mp hx obtain ⟨v,hv,e,he,rfl⟩ := (mem_product _ _ _).mp hy - simp only [List.mem_cons,List.not_mem_nil,or_false] at hc he + simp only [mem_ofPaths,List.mem_cons,List.not_mem_nil,or_false] at hc he rcases hc with rfl | rfl <;> rcases he with rfl | rfl <;> exact (mem_lcpProduct _ _ _).mpr ⟨u,hu,v,hv,Path.divergence_append_single_lcp _ _ _ _ hd⟩ · intro h obtain ⟨u,hu,v,hv,rfl⟩ := (mem_lcpProduct _ _ _).mp h obtain ⟨c,hc,e,he,hd⟩ := Path.fork_witness u v - have hc' : [c] ∈ ([[0],[1]] : PathSpace) := by simpa using hc - have he' : [e] ∈ ([[0],[1]] : PathSpace) := by simpa using he + have hc' : [c] ∈ ((ofPaths [[0],[1]]) : PathSpace) := by simpa using hc + have he' : [e] ∈ ((ofPaths [[0],[1]]) : PathSpace) := by simpa using he exact (mem_divergence _ _ _).mpr ⟨u++[c],(mem_product _ _ _).mpr ⟨u,hu,[c],hc',rfl⟩, v++[e],(mem_product _ _ _).mpr ⟨v,hv,[e],he',rfl⟩,hd⟩ theorem fork_completion (a : PathSpace) (p : Path) : - p ∈ branches (product a [[0],[1]]) ↔ p ∈ completion a := + p ∈ branches (product a (ofPaths [[0],[1]])) ↔ p ∈ completion a := (fork_lcp a a p).trans (lcp_diagonal a p) theorem range_realization (a : PathSpace) (p : Path) : - p ∈ branches (product (completion a) [[0],[1]]) ↔ p ∈ completion a := + p ∈ branches (product (completion a) (ofPaths [[0],[1]])) ↔ p ∈ completion a := (fork_completion (completion a) p).trans (completion_idempotent a p) -end PathMapModel.PathSpace +end PrunedModel.Convex diff --git a/lean/PathMapModel/PathSetGeometry.lean b/lean/PrunedModel/Convex/PathSetGeometry.lean similarity index 98% rename from lean/PathMapModel/PathSetGeometry.lean rename to lean/PrunedModel/Convex/PathSetGeometry.lean index 22c6cd6d..55c61dab 100644 --- a/lean/PathMapModel/PathSetGeometry.lean +++ b/lean/PrunedModel/Convex/PathSetGeometry.lean @@ -1,8 +1,9 @@ -import PathMapModel.PathSetProofs +import PrunedModel.Convex.PathSetProofs /-! Geometry of divergence witnesses. These proofs are independent of finite law batteries and hold for arbitrary paths and finite spaces. -/ namespace PathMapModel.Path +open PathMapModel theorem divergence_split (x y p : Path) : divergence x y = some p ↔ ∃ a b xs ys, a ≠ b ∧ x = p ++ a :: xs ∧ y = p ++ b :: ys := by @@ -55,7 +56,8 @@ theorem proper_prefix_split {p q : Path} (hp : (p ≼ q) = true) (hn : p ≠ q) | cons a xs => exact ⟨a, xs, rfl⟩ end PathMapModel.Path -namespace PathMapModel.PathSpace +namespace PrunedModel.Convex +open PathMapModel /-- Next byte a at p leads to at least one valued member of the space. -/ def Child (s : PathSpace) (p : Path) (a : UInt8) : Prop := @@ -150,4 +152,4 @@ theorem divergence_nested_exact (a b : PathSpace) (p : Path) : by_cases hxz : x = z · exact ⟨y,z,by grind,hy,⟨tail,hq⟩⟩ · exact ⟨x,z,hxz,hx,⟨tail,hq⟩⟩ -end PathMapModel.PathSpace +end PrunedModel.Convex diff --git a/lean/PathMapModel/PathSetLCP.lean b/lean/PrunedModel/Convex/PathSetLCP.lean similarity index 95% rename from lean/PathMapModel/PathSetLCP.lean rename to lean/PrunedModel/Convex/PathSetLCP.lean index a4b9d5ec..af767acc 100644 --- a/lean/PathMapModel/PathSetLCP.lean +++ b/lean/PrunedModel/Convex/PathSetLCP.lean @@ -1,6 +1,7 @@ -import PathMapModel.PathSetMasks +import PrunedModel.Convex.PathSetMasks namespace PathMapModel.Path +open PathMapModel theorem lcp_comm (x y : Path) : lcp x y = lcp y x := by induction x generalizing y with @@ -89,7 +90,8 @@ theorem lcp_cases (x y p : Path) : lcp x y = p ↔ · exact (lcp_comm _ _).trans (lcp_of_prefix h) end PathMapModel.Path -namespace PathMapModel.PathSpace +namespace PrunedModel.Convex +open PathMapModel theorem mem_lcpProduct (a b : PathSpace) (p : Path) : p ∈ lcpProduct a b ↔ ∃ x ∈ a, ∃ y ∈ b, Path.lcp x y = p := by @@ -114,7 +116,7 @@ theorem lcp_diagonal (a : PathSpace) (p : Path) : rw [lcp_correction] have hl : p ∈ retain a a ↔ p ∈ a := by rw [mem_retain]; exact ⟨And.left,fun h => ⟨h,p,h,Path.prefix_self p⟩⟩ - simp only [completion,union,List.mem_append,hl,branches] + simp only [completion,mem_union,hl,branches] grind theorem lcp_symmetry (a b : PathSpace) (p : Path) : @@ -134,7 +136,7 @@ theorem lcp_associativity (a b c : PathSpace) (p : Path) : theorem lcp_bilinearity (a b c : PathSpace) : lcpProduct (union a b) c = union (lcpProduct a c) (lcpProduct b c) := by - simp [lcpProduct,union] + apply Zippy.ext; intro p; simp only [mem_lcpProduct, mem_union]; grind theorem lcp_output_covered {a b : PathSpace} {p : Path} (h : p ∈ lcpProduct a b) : ∃ x ∈ a, (p ≼ x) = true := by @@ -143,7 +145,7 @@ theorem lcp_output_covered {a b : PathSpace} {p : Path} theorem lcp_output_completion (a b : PathSpace) (p : Path) : p ∈ completion (lcpProduct a b) ↔ p ∈ lcpProduct a b := by - simp only [completion,union,List.mem_append] + simp only [completion,mem_union] constructor · rintro (h | h) · exact h @@ -154,4 +156,4 @@ theorem lcp_output_completion (a b : PathSpace) (p : Path) : ((divergence_comm _ _ p).mp h1) exact (lcp_correction a b p).mpr (Or.inl ((divergence_comm _ _ p).mp h2)) · exact Or.inl -end PathMapModel.PathSpace +end PrunedModel.Convex diff --git a/lean/PathMapModel/PathSetLaws.lean b/lean/PrunedModel/Convex/PathSetLaws.lean similarity index 87% rename from lean/PathMapModel/PathSetLaws.lean rename to lean/PrunedModel/Convex/PathSetLaws.lean index a09f7a3d..42f3d59a 100644 --- a/lean/PathMapModel/PathSetLaws.lean +++ b/lean/PrunedModel/Convex/PathSetLaws.lean @@ -1,28 +1,29 @@ -import PathMapModel.PathSets +import PrunedModel.Convex.PathSets /-! Named decidable laws for property tests. `PathSetChecks` evaluates small fixtures; the `PathSetProofs` through `PathSetCertificates` modules prove the corresponding universally quantified statements. -/ -namespace PathMapModel.PathSetLaws -open PathSpace +namespace PrunedModel.Convex.PathSetLaws +open PathMapModel +open PrunedModel.Convex abbrev Checks := List (String × Bool) -def D (a b : PathSpace) := normalize (divergence a b) +def D (a b : PathSpace) := (divergence a b) private def Br (a : PathSpace) := D a a private def I (a : PathSpace) := diff a (hull a) private def C (a : PathSpace) := union a (Br a) -private def M (a b : PathSpace) := normalize (lcpProduct a b) -private def E : PathSpace := [[]] +private def M (a b : PathSpace) := (lcpProduct a b) +private def E : PathSpace := (ofPaths [[]]) private def implies (a b : Bool) := !a || b -private def eq := PathSpace.equiv -private def sub := PathSpace.subset +private def eq := PrunedModel.Convex.equiv +private def sub := PrunedModel.Convex.subset def unary (a : PathSpace) : Checks := let br := Br a [ ("diagonal", eq (D a a) br), - ("empty_left", eq (D [] a) []), - ("empty_right", eq (D a []) []), - ("epsilon_left", eq (D E a) []), - ("epsilon_right", eq (D a E) []), + ("empty_left", eq (D (ofPaths []) a) (ofPaths [])), + ("empty_right", eq (D a (ofPaths [])) (ofPaths [])), + ("epsilon_left", eq (D E a) (ofPaths [])), + ("epsilon_right", eq (D a E) (ofPaths [])), ("branch_completion", eq (Br (C a)) br), ("completion_idempotent", eq (C (C a)) (C a)), ("branch_hull", eq (Br (hull a)) br), @@ -37,24 +38,24 @@ def unary (a : PathSpace) : Checks := ("hull_of_basis", eq (hull (basis a)) (basis a)), ("basis_antichain", prefixFree (basis a)), ("hull_antichain", prefixFree (hull a)), - ("basis_nonempty", (basis a).isEmpty == a.isEmpty), - ("hull_nonempty", (hull a).isEmpty == a.isEmpty), + ("basis_nonempty", (basis a).isEmptyMap == a.isEmptyMap), + ("hull_nonempty", (hull a).isEmptyMap == a.isEmptyMap), ("basis_covers", covers a (hull a) && covers (basis a) a), ("basis_recursive", eq (basisRec (height a + 1) a) (basis a)), ("hull_recursive", eq (hullRec (height a + 1) a) (hull a)), ("branch_recursive", eq (divergenceRec (height a + 1) a a) br), ("maximal_branch_count", decide (count (hull br) <= count (hull a) / 2)), - ("no_nonempty_branch_fixed_point", implies (!a.isEmpty) (!eq br a)), - ("branch_depth_nilpotence", eq (branchIter a (height a + 1)) []) ] + ("no_nonempty_branch_fixed_point", implies (!a.isEmptyMap) (!eq br a)), + ("branch_depth_nilpotence", eq (branchIter a (height a + 1)) (ofPaths [])) ] def binary (a b : PathSpace) : Checks := let x := D a b let ha := hull a let hb := hull b - let zero := a.isEmpty || b.isEmpty || - (count ha == 1 && hb.all (fun q => ha.all (· ≼ q))) || - (count hb == 1 && ha.all (fun p => hb.all (· ≼ p))) - let fork : PathSpace := [[0], [1]] + let zero := a.isEmptyMap || b.isEmptyMap || + (count ha == 1 && hb.keys.all (fun q => ha.keys.all (· ≼ q))) || + (count hb == 1 && ha.keys.all (fun p => hb.keys.all (· ≼ p))) + let fork : PathSpace := (ofPaths [[0], [1]]) [ ("symmetry", eq x (D b a)), ("terminal_invariance", eq (D (union a E) (union b E)) x), ("hull_invariance", eq (D ha hb) x), @@ -69,8 +70,8 @@ def binary (a b : PathSpace) : Checks := ("interior_exact", eq (D (union a b) x) (I x)), ("interior_attribution", sub (I x) (union (Br a) (Br b))), ("output_branches", sub (Br x) (inter x (inter (Br a) (Br b)))), - ("first_divergence", implies (!x.isEmpty) (eq (basis x) [commonPrefix (union ha hb)])), - ("zero_criterion", x.isEmpty == zero), + ("first_divergence", implies (!x.isEmptyMap) (eq (basis x) [commonPrefix (union ha hb)])), + ("zero_criterion", x.isEmptyMap == zero), ("root_heads", eq (D (head a) (head b)) (inter x E)), ("output_heads", sub (head x) (inter (head a) (head b))), ("tails_bound", sub (tails x) (D (tails a) (tails b))), @@ -78,7 +79,7 @@ def binary (a b : PathSpace) : Checks := ("retain_recursive", eq (retainRec (height a + 1) a b) (retain a b)), ("output_cardinality", decide (count x <= count (hull (union a b)) - 1)), ("output_hull_cardinality", decide (count (hull x) <= min (count ha) (count hb))), - ("output_depth", implies (!x.isEmpty) (height x < min (height a) (height b))), + ("output_depth", implies (!x.isEmptyMap) (height x < min (height a) (height b))), ("output_covered", covers x a && covers x b), ("fork_completion", eq (Br (product a fork)) (C a)), ("fork_lcp", eq (D (product a fork) (product b fork)) (M a b)), @@ -110,7 +111,7 @@ def ternary (a b c : PathSpace) : Checks := ("same_mask", eq (D (restrict a c) (restrict b c)) (union (restrict (D a b) c) (D (retain c a) (retain c b)))), ("filter_partition", eq (D a b) (union (D (restrict a c) b) (D (raffinate a c) b))), - ("common_prefix_code", implies (prefixFree a && !b.isEmpty && !c.isEmpty) + ("common_prefix_code", implies (prefixFree a && !b.isEmptyMap && !c.isEmptyMap) (eq (D (product a b) (product a c)) (union (Br a) (product a (D b c))))) ] /-- The proper-prefix contributions in the full four-factor product expansion. -/ @@ -135,10 +136,10 @@ def quaternary (a b c f : PathSpace) : Checks := (union (restrict (D pa b) f) (D pa qb)))), ("raffination_bound", sub (D (raffinate a c) (raffinate b f)) (raffinate x (union c f))), ("general_product", eq (D (product a c) (product b f)) - (if c.isEmpty || f.isEmpty then [] else + (if c.isEmptyMap || f.isEmptyMap then (ofPaths []) else union (union x (product (inter a b) (D c f))) (union (leftOverlap a b c f) (rightOverlap a b c f)))), - ("prefix_free_product", implies (prefixFree (union a b) && !c.isEmpty && !f.isEmpty) + ("prefix_free_product", implies (prefixFree (union a b) && !c.isEmptyMap && !f.isEmptyMap) (eq (D (product a c) (product b f)) (union x (product (inter a b) (D c f))))) ] def pathLaws (a b : PathSpace) (p : Path) : Checks := @@ -146,7 +147,7 @@ def pathLaws (a b : PathSpace) (p : Path) : Checks := [ ("wrap", eq (D (wrap p a) (wrap p b)) (wrap p (D a b))), ("unwrap", eq (D (unwrap a p) (unwrap b p)) (unwrap (D a b) p)), ("single_prefix_restriction", eq (D (restrict a [p]) (restrict b [p])) (restrict (D a b) [p])), - ("singleton_chain", eq (Br chain) []), + ("singleton_chain", eq (Br chain) (ofPaths [])), ("singleton_bound", decide (count chain <= min p.length (count (hull b)))), ("singleton_existing_branches", sub (I chain) (Br b)), ("singleton_branch_update", decide (count (diff (Br (union b [p])) (Br b)) <= 1)), @@ -155,12 +156,12 @@ def pathLaws (a b : PathSpace) (p : Path) : Checks := def powers (a : PathSpace) (m n : Nat) : Checks := [ ("prefix_code_powers", implies (prefixFree a) (eq (D (power a m) (power a n)) - ((List.range (min m n)).flatMap fun i => product (power a i) (Br a)))), - ("branch_leaf_bound", implies (!(branchIter a n).isEmpty) (2^n <= count (hull a))) ] + (ofPaths ((List.range (min m n)).flatMap fun i => (product (power a i) (Br a)).keys)))), + ("branch_leaf_bound", implies (!(branchIter a n).isEmptyMap) (2^n <= count (hull a))) ] def retention (a b c f : PathSpace) : Checks := - [ ("retain_empty_left", eq (retain [] a) ([])), - ("retain_empty_right", eq (retain a []) ([])), + [ ("retain_empty_left", eq (retain (ofPaths []) a) ((ofPaths []))), + ("retain_empty_right", eq (retain a (ofPaths [])) ((ofPaths []))), ("retain_self", eq (retain a a) (a)), ("retain_union_left", eq (retain (union a b) c) (union (retain a c) (retain b c))), ("retain_inter_left", eq (retain (inter a b) c) (inter (retain a c) (retain b c))), @@ -174,7 +175,7 @@ def retention (a b c f : PathSpace) : Checks := ("retain_completion_mask", eq (retain a (C b)) (retain a b)), ("retain_restrict_witnesses", eq (retain a (restrict b a)) (retain a b)), ("restrict_retain_mask", eq (restrict a (retain b a)) (restrict a b)), - ("retain_restrict_disjoint", eq (retain a (raffinate b a)) ([])), + ("retain_restrict_disjoint", eq (retain a (raffinate b a)) ((ofPaths []))), ("retain_restrict_source", eq (retain (restrict a b) c) (restrict (retain a c) b)), ("retain_raffinate_source", eq (retain (raffinate a b) c) (raffinate (retain a c) b)), ("retain_lcp_masks", eq (retain (retain a b) c) (retain a (M b c))), @@ -191,7 +192,7 @@ def retention (a b c f : PathSpace) : Checks := ("retain_hull_source_bound", sub (retain (hull a) b) (hull (retain a b))), ("divergence_retain_bound", sub (D (retain a c) (retain b f)) (inter (D a b) (D c f))), ("branches_retain_bound", sub (Br (retain a b)) (inter (Br a) (Br b))), - ("retain_empty_duality", (retain a b).isEmpty == (restrict b a).isEmpty), + ("retain_empty_duality", (retain a b).isEmptyMap == (restrict b a).isEmptyMap), ("retain_identity", eq (retain a b) a == covers a b), ("retain_count_bound", decide (count (retain a b) <= count a)) ] @@ -228,7 +229,7 @@ def closedAlgebra (a b c f : PathSpace) : Checks := ("closed_join_assoc", eq (C (union (C (union a b)) c)) (C (union a (C (union b c))))), ("closed_join_comm", eq (C (union a b)) (C (union b a))), ("closed_join_idem", eq (C (union (C a) (C a))) (C a)), - ("closed_join_empty", eq (C (union (C a) [])) (C a)), + ("closed_join_empty", eq (C (union (C a) (ofPaths []))) (C a)), ("closed_join_absorption", eq (C (union (C a) (inter (C a) b))) (C a)), ("closed_meet_absorption", eq (inter a (C (union a b))) a), ("lcpLE_product_left", eq (M (M a b) a) (M a b)), @@ -253,7 +254,7 @@ def closedAlgebra (a b c f : PathSpace) : Checks := ("lcpLE_product_iff", eq (M a (M b c)) a == (eq (M a b) a && eq (M a c) a)), ("completion_cardinality", decide (count (C a) <= count a + (count (hull a) - 1))), ("completion_cardinality_linear", decide (count a <= count (C a) && count (C a) <= 2 * count a - 1)), - ("basis_completion", implies (!a.isEmpty) (eq (basis (C a)) [commonPrefix a])) ] + ("basis_completion", implies (!a.isEmptyMap) (eq (basis (C a)) [commonPrefix a])) ] /-- Assumptions are executable guards, so unconstrained inputs are safe to test. -/ def all (a b c f : PathSpace) : Checks := @@ -261,4 +262,4 @@ def all (a b c f : PathSpace) : Checks := (pathLaws a b []) ++ (pathLaws a b [0]) ++ (pathLaws a b [0,1,0]) def failures (checks : Checks) : List String := (checks.filter (! ·.2)).map (·.1) -end PathMapModel.PathSetLaws +end PrunedModel.Convex.PathSetLaws diff --git a/lean/PathMapModel/PathSetMasks.lean b/lean/PrunedModel/Convex/PathSetMasks.lean similarity index 94% rename from lean/PathMapModel/PathSetMasks.lean rename to lean/PrunedModel/Convex/PathSetMasks.lean index 644929e9..c45d120e 100644 --- a/lean/PathMapModel/PathSetMasks.lean +++ b/lean/PrunedModel/Convex/PathSetMasks.lean @@ -1,6 +1,7 @@ -import PathMapModel.PathSetExtrema +import PrunedModel.Convex.PathSetExtrema namespace PathMapModel.Path +open PathMapModel /-- Cutting a divergent witness either reaches the divergence or still diverges. -/ theorem divergence_cut {x y p r : Path} (hr : (r ≼ x) = true) (hd : divergence x y = some p) : (r ≼ p) = true ∨ divergence r y = some p := by @@ -27,7 +28,8 @@ theorem divergence_cut {x y p r : Path} (hr : (r ≼ x) = true) exact Or.inr (by simp [divergence,hab]) end PathMapModel.Path -namespace PathMapModel.PathSpace +namespace PrunedModel.Convex +open PathMapModel theorem mem_retain (m a : PathSpace) (p : Path) : p ∈ retain m a ↔ p ∈ m ∧ ∃ q ∈ a, (p ≼ q) = true := by @@ -35,7 +37,7 @@ theorem mem_retain (m a : PathSpace) (p : Path) : theorem mem_raffinate (a m : PathSpace) (p : Path) : p ∈ raffinate a m ↔ p ∈ a ∧ ∀ q ∈ m, (q ≼ p) = false := by - simp only [raffinate, mem_diff, mem_restrict] + simp only [raffinate, Zippy.raffination, mem_diff, mem_restrict] constructor · rintro ⟨hp,hn⟩ refine ⟨hp, fun q hq => ?_⟩ @@ -116,7 +118,7 @@ theorem divergence_single_mask (a b : PathSpace) (q p : Path) : obtain ⟨x,hx,y,hy,hd⟩ := (mem_divergence _ _ _).mp h have hxq := ((mem_retain _ _ _).mp hx).1 have hyq := ((mem_retain _ _ _).mp hy).1 - simp only [List.mem_singleton] at hxq hyq + simp only [mem_ofPaths, List.mem_singleton] at hxq hyq subst x; subst y; simp at hd exact or_iff_left hn @@ -131,7 +133,7 @@ theorem divergence_raffination {a b m n : PathSpace} {p : Path} cases he : (q ≼ p) with | false => rfl | true => - simp only [union, List.mem_append] at hq + simp only [mem_union] at hq rcases hq with hq | hq · have hqx := Path.prefix_trans he (Path.divergence_prefix_left hd) simpa [hqx] using hm q hq @@ -144,7 +146,7 @@ theorem divergence_filter_partition (a b m : PathSpace) (p : Path) : rw [← divergence_union_left] apply divergence_congr _ (fun _ => Iff.rfl) p intro q - simp only [union, List.mem_append, raffinate, mem_diff] + simp only [mem_union, raffinate, Zippy.raffination, mem_diff] have hs : q ∈ restrict a m → q ∈ a := fun h => ((mem_restrict _ _ _).mp h).1 grind -end PathMapModel.PathSpace +end PrunedModel.Convex diff --git a/lean/PathMapModel/PathSetPowers.lean b/lean/PrunedModel/Convex/PathSetPowers.lean similarity index 60% rename from lean/PathMapModel/PathSetPowers.lean rename to lean/PrunedModel/Convex/PathSetPowers.lean index edc66ea3..faf71e8b 100644 --- a/lean/PathMapModel/PathSetPowers.lean +++ b/lean/PrunedModel/Convex/PathSetPowers.lean @@ -1,6 +1,7 @@ -import PathMapModel.PathSetProduct +import PrunedModel.Convex.PathSetProduct -namespace PathMapModel.PathSpace +namespace PrunedModel.Convex +open PathMapModel theorem product_associative (a b c : PathSpace) (p : Path) : p ∈ product (product a b) c ↔ p ∈ product a (product b c) := by @@ -15,49 +16,44 @@ theorem product_congr {a b c f : PathSpace} (ha : ∀ p, p ∈ a ↔ p ∈ c) (hb : ∀ p, p ∈ b ↔ p ∈ f) (p : Path) : p ∈ product a b ↔ p ∈ product c f := by simp only [mem_product,ha,hb] -theorem product_nonempty {a b : PathSpace} (ha : a ≠ []) (hb : b ≠ []) : product a b ≠ [] := by - cases a with - | nil => exact False.elim (ha rfl) - | cons x xs => - cases b with - | nil => exact False.elim (hb rfl) - | cons y ys => - apply List.ne_nil_of_mem (a := x++y) - exact (mem_product _ _ _).mpr ⟨x,by simp,y,by simp,rfl⟩ +theorem product_nonempty {a b : PathSpace} (ha : a ≠ ofPaths []) (hb : b ≠ ofPaths []) : product a b ≠ ofPaths [] := by + obtain ⟨x,hx⟩ := (ne_empty_iff a).mp ha + obtain ⟨y,hy⟩ := (ne_empty_iff b).mp hb + exact (ne_empty_iff _).mpr ⟨x++y,(mem_product _ _ _).mpr ⟨x,hx,y,hy,rfl⟩⟩ -theorem power_nonempty {a : PathSpace} (ha : a ≠ []) (n : Nat) : power a n ≠ [] := by +theorem power_nonempty {a : PathSpace} (ha : a ≠ ofPaths []) (n : Nat) : power a n ≠ ofPaths [] := by induction n with - | zero => simp [power] + | zero => exact (ne_empty_iff _).mpr ⟨[],by simp [power]⟩ | succ n ih => exact product_nonempty ha ih def powerSum (a : PathSpace) (n : Nat) : PathSpace := - (List.range n).flatMap fun i => product (power a i) (branches a) + ofPaths ((List.range n).flatMap fun i => (product (power a i) (branches a)).keys) theorem powerSum_succ (a : PathSpace) (n : Nat) (p : Path) : p ∈ powerSum a (n+1) ↔ p ∈ branches a ∨ p ∈ product a (powerSum a n) := by unfold powerSum rw [List.range_succ_eq_map] - simp only [List.flatMap_cons,List.mem_append,List.mem_flatMap,List.mem_map,power] - have hzero : ∀ s : PathSpace, product [[]] s = s := by intro s; simp [product] + simp only [mem_ofPaths,List.flatMap_cons,List.mem_append,List.mem_flatMap,List.mem_map,mem_keys,power] + have hzero : ∀ s : PathSpace, product (ofPaths [[]]) s = s := by intro s; apply Zippy.ext; intro q; simp [mem_product] rw [hzero] constructor · rintro (h | ⟨i,⟨j,hj,rfl⟩,hp⟩) · exact Or.inl h · have hh := (product_associative a (power a j) (branches a) p).mp hp obtain ⟨x,hx,y,hy,rfl⟩ := (mem_product _ _ _).mp hh - exact Or.inr ((mem_product _ _ _).mpr ⟨x,hx,y,List.mem_flatMap.mpr ⟨j,hj,hy⟩,rfl⟩) + exact Or.inr ((mem_product _ _ _).mpr ⟨x,hx,y,(mem_ofPaths _ _).mpr (List.mem_flatMap.mpr ⟨j,hj,(mem_keys _ _).mpr hy⟩),rfl⟩) · rintro (h | h) · exact Or.inl h · obtain ⟨x,hx,y,hy,rfl⟩ := (mem_product _ _ _).mp h - obtain ⟨i,hi,hyi⟩ := List.mem_flatMap.mp hy + obtain ⟨i,hi,hyi⟩ := List.mem_flatMap.mp ((mem_ofPaths _ _).mp hy) exact Or.inr ⟨i+1,⟨i,hi,rfl⟩,(product_associative _ _ _ _).mpr - ((mem_product _ _ _).mpr ⟨x,hx,y,hyi,rfl⟩)⟩ + ((mem_product _ _ _).mpr ⟨x,hx,y,(mem_keys _ _).mp hyi,rfl⟩)⟩ theorem prefix_code_powers {a : PathSpace} (ha : Antichain a) (m n : Nat) (p : Path) : p ∈ divergence (power a m) (power a n) ↔ p ∈ powerSum a (min m n) := by - by_cases he : a = [] + by_cases he : a = ofPaths [] · subst a - cases m <;> cases n <;> simp [power,powerSum,product,branches,divergence] + cases m <;> cases n <;> simp [power,powerSum,mem_product,mem_divergence,branches] · induction m generalizing n p with | zero => simp [power,powerSum] | succ m ih => @@ -67,27 +63,25 @@ theorem prefix_code_powers {a : PathSpace} (ha : Antichain a) (m n : Nat) (p : P simp only [power,Nat.succ_min_succ] rw [common_prefix_code ha (power_nonempty he m) (power_nonempty he n)] rw [powerSum_succ] - simp only [union,List.mem_append] + simp only [mem_union] have hh := product_congr (fun q => Iff.rfl (a := q ∈ a)) (fun q => ih n q) p rw [hh] -@[simp] theorem product_empty_right (a : PathSpace) : product a [] = [] := by - apply List.eq_nil_iff_forall_not_mem.mpr +@[simp] theorem product_empty_right (a : PathSpace) : product a (ofPaths []) = ofPaths [] := by + apply (eq_empty_iff _).mpr intro p simp [mem_product] theorem general_product (a b x y : PathSpace) (p : Path) : p ∈ divergence (product a x) (product b y) ↔ - p ∈ (if x.isEmpty || y.isEmpty then [] else + p ∈ (if x = ofPaths [] ∨ y = ofPaths [] then ofPaths [] else union (union (divergence a b) (product (inter a b) (divergence x y))) (union (PathSetLaws.leftOverlap a b x y) (PathSetLaws.rightOverlap a b x y))) := by - by_cases hx : x = [] + by_cases hx : x = ofPaths [] · subst x; simp - · by_cases hy : y = [] + · by_cases hy : y = ofPaths [] · subst y; simp - · have hxe : x.isEmpty = false := by simpa using hx - have hye : y.isEmpty = false := by simpa using hy - simp only [hxe,hye,Bool.or_self,Bool.false_eq_true,if_false,union,List.mem_append] + · simp only [hx,hy,or_self,if_false,mem_union] rw [divergence_product_nonempty a b x y hx hy] grind -end PathMapModel.PathSpace +end PrunedModel.Convex diff --git a/lean/PathMapModel/PathSetProduct.lean b/lean/PrunedModel/Convex/PathSetProduct.lean similarity index 80% rename from lean/PathMapModel/PathSetProduct.lean rename to lean/PrunedModel/Convex/PathSetProduct.lean index 6bc9588e..504ebf42 100644 --- a/lean/PathMapModel/PathSetProduct.lean +++ b/lean/PrunedModel/Convex/PathSetProduct.lean @@ -1,7 +1,8 @@ -import PathMapModel.PathSetRecursive -import PathMapModel.PathSetLaws +import PrunedModel.Convex.PathSetRecursive +import PrunedModel.Convex.PathSetLaws namespace PathMapModel.Path +open PathMapModel theorem divergence_extend_both {a b p : Path} (x y : Path) (h : divergence a b = some p) : divergence (a ++ x) (b ++ y) = some p := by @@ -9,25 +10,26 @@ theorem divergence_extend_both {a b p : Path} (x y : Path) exact divergence_extend_left y ((divergence_comm b (a++x)).trans (divergence_extend_left x h)) end PathMapModel.Path -namespace PathMapModel.PathSpace +namespace PrunedModel.Convex +open PathMapModel theorem mem_proper_overlap (a b : PathSpace) (f : Path → Path → PathSpace) (p : Path) : p ∈ properOverlap a b f ↔ ∃ u ∈ a, ∃ r, r ≠ [] ∧ u ++ r ∈ b ∧ p ∈ f u r := by - simp only [properOverlap,List.mem_flatMap] + simp only [properOverlap,mem_ofPaths,List.mem_flatMap,mem_keys] constructor · rintro ⟨u,hu,v,hv,hp⟩ cases hs : Path.stripPrefix u v with | none => simp [hs] at hp | some r => - have hvu := (Path.stripPrefix_eq u v r).mp hs + have hvu := (Path.stripPrefix_eq_some u v r).mp hs subst v cases r with | nil => simp only [List.append_nil] at hs; simp [hs] at hp | cons c rs => exact ⟨u,hu,c::rs,by simp,hv,by simpa [hs] using hp⟩ · rintro ⟨u,hu,r,hr,hv,hp⟩ refine ⟨u,hu,u++r,hv,?_⟩ - have hs := (Path.stripPrefix_eq u (u++r) r).mpr rfl + have hs := (Path.stripPrefix_eq_some u (u++r) r).mpr rfl cases r with | nil => exact False.elim (hr rfl) | cons c rs => simpa [hs] using hp @@ -36,19 +38,19 @@ theorem mem_leftOverlap (a b x y : PathSpace) (p : Path) : p ∈ PathSetLaws.leftOverlap a b x y ↔ ∃ u ∈ a, ∃ r, r ≠ [] ∧ u ++ r ∈ b ∧ ∃ q ∈ divergence x (wrap r y), u ++ q = p := by simp only [PathSetLaws.leftOverlap,PathSetLaws.D] - rw [mem_proper_overlap a b (fun u r => wrap u (normalize (divergence x (wrap r y)))) p] - change (∃ u ∈ a, ∃ r, r ≠ [] ∧ u ++ r ∈ b ∧ p ∈ wrap u (normalize (divergence x (wrap r y)))) ↔ _ - simp only [mem_wrap,mem_normalize] + rw [mem_proper_overlap a b (fun u r => wrap u ((divergence x (wrap r y)))) p] + change (∃ u ∈ a, ∃ r, r ≠ [] ∧ u ++ r ∈ b ∧ p ∈ wrap u ((divergence x (wrap r y)))) ↔ _ + simp only [mem_wrap] theorem mem_rightOverlap (a b x y : PathSpace) (p : Path) : p ∈ PathSetLaws.rightOverlap a b x y ↔ ∃ v ∈ b, ∃ r, r ≠ [] ∧ v ++ r ∈ a ∧ ∃ q ∈ divergence (wrap r x) y, v ++ q = p := by simp only [PathSetLaws.rightOverlap,PathSetLaws.D] - rw [mem_proper_overlap b a (fun v r => wrap v (normalize (divergence (wrap r x) y))) p] - change (∃ v ∈ b, ∃ r, r ≠ [] ∧ v ++ r ∈ a ∧ p ∈ wrap v (normalize (divergence (wrap r x) y))) ↔ _ - simp only [mem_wrap,mem_normalize] + rw [mem_proper_overlap b a (fun v r => wrap v ((divergence (wrap r x) y))) p] + change (∃ v ∈ b, ∃ r, r ≠ [] ∧ v ++ r ∈ a ∧ p ∈ wrap v ((divergence (wrap r x) y))) ↔ _ + simp only [mem_wrap] -theorem divergence_product_nonempty (a b x y : PathSpace) (hx : x ≠ []) (hy : y ≠ []) (p : Path) : +theorem divergence_product_nonempty (a b x y : PathSpace) (hx : x ≠ ofPaths []) (hy : y ≠ ofPaths []) (p : Path) : p ∈ divergence (product a x) (product b y) ↔ p ∈ divergence a b ∨ p ∈ product (inter a b) (divergence x y) ∨ p ∈ PathSetLaws.leftOverlap a b x y ∨ p ∈ PathSetLaws.rightOverlap a b x y := by @@ -85,15 +87,11 @@ theorem divergence_product_nonempty (a b x y : PathSpace) (hx : x ≠ []) (hy : ⟨(c::rs)++s,(mem_wrap _ _ _).mpr ⟨s,hs,rfl⟩,t,ht,hq⟩,rfl⟩))) · rintro (h | h | h | h) · obtain ⟨u,hu,v,hv,hd⟩ := (mem_divergence _ _ _).mp h - cases x with - | nil => exact False.elim (hx rfl) - | cons s xs => - cases y with - | nil => exact False.elim (hy rfl) - | cons t ys => - exact (mem_divergence _ _ _).mpr - ⟨u++s,(mem_product _ _ _).mpr ⟨u,hu,s,by simp,rfl⟩, - v++t,(mem_product _ _ _).mpr ⟨v,hv,t,by simp,rfl⟩,Path.divergence_extend_both s t hd⟩ + obtain ⟨s,hs⟩ := (ne_empty_iff x).mp hx + obtain ⟨t,ht⟩ := (ne_empty_iff y).mp hy + exact (mem_divergence _ _ _).mpr + ⟨u++s,(mem_product _ _ _).mpr ⟨u,hu,s,hs,rfl⟩, + v++t,(mem_product _ _ _).mpr ⟨v,hv,t,ht,rfl⟩,Path.divergence_extend_both s t hd⟩ · obtain ⟨u,hu,q,hq,rfl⟩ := (mem_product _ _ _).mp h obtain ⟨hua,hub⟩ := (mem_inter _ _ _).mp hu obtain ⟨s,hs,t,ht,hd⟩ := (mem_divergence _ _ _).mp hq @@ -116,8 +114,9 @@ theorem divergence_product_nonempty (a b x y : PathSpace) (hx : x ≠ []) (hy : by simp [List.append_assoc,Path.divergence_wrap,hd]⟩ theorem equiv_members {a b : PathSpace} (h : equiv a b = true) (p : Path) : p ∈ a ↔ p ∈ b := by - have he : (∀ p ∈ a, p ∈ b) ∧ (∀ p ∈ b, p ∈ a) := by simpa [equiv,subset,List.all_eq_true] using h - exact ⟨he.1 p,he.2 p⟩ + have he : a = b := of_decide_eq_true h + subst b + exact Iff.rfl def Antichain (a : PathSpace) : Prop := ∀ p ∈ a, ∀ q ∈ a, (p ≼ q) = true → p = q @@ -131,31 +130,31 @@ theorem prefixFree_antichain {a : PathSpace} (h : prefixFree a = true) : Anticha simp [hpq] at hf theorem prefix_free_product {a b x y : PathSpace} (hf : Antichain (union a b)) - (hx : x ≠ []) (hy : y ≠ []) (p : Path) : + (hx : x ≠ ofPaths []) (hy : y ≠ ofPaths []) (p : Path) : p ∈ divergence (product a x) (product b y) ↔ p ∈ divergence a b ∨ p ∈ product (inter a b) (divergence x y) := by rw [divergence_product_nonempty a b x y hx hy] have hl : p ∉ PathSetLaws.leftOverlap a b x y := by intro h obtain ⟨u,hu,r,hr,hv,_⟩ := (mem_leftOverlap _ _ _ _ _).mp h - have he := hf u (List.mem_append_left b hu) (u++r) (List.mem_append_right a hv) + have he := hf u ((mem_union a b _).mpr (Or.inl hu)) (u++r) ((mem_union a b _).mpr (Or.inr hv)) ((Path.prefix_iff_extension _ _).mpr ⟨r,rfl⟩) have hn : r = [] := by have hh := congrArg List.length he; simpa using hh exact hr hn have hr : p ∉ PathSetLaws.rightOverlap a b x y := by intro h obtain ⟨v,hv,r,hr,hu,_⟩ := (mem_rightOverlap _ _ _ _ _).mp h - have he := hf v (List.mem_append_right a hv) (v++r) (List.mem_append_left b hu) + have he := hf v ((mem_union a b _).mpr (Or.inr hv)) (v++r) ((mem_union a b _).mpr (Or.inl hu)) ((Path.prefix_iff_extension _ _).mpr ⟨r,rfl⟩) have hn : r = [] := by have hh := congrArg List.length he; simpa using hh exact hr hn simp [hl,hr] theorem common_prefix_code {a x y : PathSpace} (hf : Antichain a) - (hx : x ≠ []) (hy : y ≠ []) (p : Path) : + (hx : x ≠ ofPaths []) (hy : y ≠ ofPaths []) (p : Path) : p ∈ divergence (product a x) (product a y) ↔ p ∈ union (branches a) (product a (divergence x y)) := by - have hf' : Antichain (union a a) := by intro u hu v hv; apply hf u (by simpa [union] using hu) v (by simpa [union] using hv) + have hf' : Antichain (union a a) := by intro u hu v hv; apply hf u (by simpa [mem_union] using hu) v (by simpa [mem_union] using hv) rw [prefix_free_product hf' hx hy] - simp [branches,union,mem_product,mem_inter] -end PathMapModel.PathSpace + simp [branches,mem_union,mem_product,mem_inter] +end PrunedModel.Convex diff --git a/lean/PathMapModel/PathSetProofs.lean b/lean/PrunedModel/Convex/PathSetProofs.lean similarity index 77% rename from lean/PathMapModel/PathSetProofs.lean rename to lean/PrunedModel/Convex/PathSetProofs.lean index df22649a..9a157ee2 100644 --- a/lean/PathMapModel/PathSetProofs.lean +++ b/lean/PrunedModel/Convex/PathSetProofs.lean @@ -1,7 +1,8 @@ -import PathMapModel.PathSets +import PrunedModel.Convex.PathSets /-! Universally quantified proofs, separate from the executable law battery. -/ -namespace PathMapModel.PathSpace +namespace PrunedModel.Convex +open PathMapModel theorem basis_subset (a : PathSpace) {p : Path} (h : p ∈ basis a) : p ∈ a := ((mem_basis a p).mp h).1 @@ -33,12 +34,6 @@ theorem hull_antichain {a : PathSpace} {p q : Path} (hp : p ∈ hull a) (hq : q ∈ hull a) (hne : p ≠ q) : (p ≼ q) = false := ((mem_hull a p).mp hp).2 q (hull_subset a hq) (Ne.symm hne) -theorem mem_inter (a b : PathSpace) (p : Path) : p ∈ inter a b ↔ p ∈ a ∧ p ∈ b := by - simp [inter] - -theorem mem_diff (a b : PathSpace) (p : Path) : p ∈ diff a b ↔ p ∈ a ∧ p ∉ b := by - simp [diff] - theorem divergence_intersection_bound {a b c : PathSpace} {p : Path} (h : p ∈ divergence (inter a b) c) : p ∈ divergence a c ∧ p ∈ divergence b c := by @@ -63,10 +58,10 @@ theorem branches_union (a b : PathSpace) (p : Path) : p ∈ branches (union a b) ↔ p ∈ branches a ∨ p ∈ branches b ∨ p ∈ divergence a b := by change p ∈ divergence (union a b) (union a b) ↔ _ rw [divergence_union_left] - simp only [union, List.mem_append] + simp only [mem_union] have ha := divergence_union_right a a b p have hb := divergence_union_right b a b p - simp only [union, List.mem_append] at ha hb + simp only [mem_union] at ha hb have hc := divergence_comm b a p dsimp [branches] grind @@ -74,41 +69,43 @@ theorem branches_union (a b : PathSpace) (p : Path) : /-- Singletons recover strict pair divergence from Br. -/ theorem singleton_polarization (a b : Path) (p : Path) : p ∈ divergence [a] [b] ↔ p ∈ branches [a,b] := by - simp [branches, divergence, Path.divergence_comm b a] + simp [branches, mem_divergence, Path.divergence_comm b a] /-- A symmetric bilinear operation with this diagonal is uniquely determined. The empty laws are listed explicitly, as in the executable catalog. -/ theorem divergence_unique (f : PathSpace → PathSpace → Path → Prop) - (he : ∀ a p, ¬ f [] a p ∧ ¬ f a [] p) + (he : ∀ a p, ¬ f (ofPaths []) a p ∧ ¬ f a (ofPaths []) p) (hs : ∀ a b p, f a b p ↔ f b a p) (hl : ∀ a b c p, f (a ++ b) c p ↔ f a c p ∨ f b c p) (hr : ∀ a b c p, f a (b ++ c) p ↔ f a b p ∨ f a c p) (hd : ∀ a p, f a a p ↔ p ∈ branches a) : ∀ a b p, f a b p ↔ p ∈ divergence a b := by - have hsingle : ∀ x y p, f [x] [y] p ↔ p ∈ divergence [x] [y] := by + have hsingle : ∀ x y p, f [x] [y] p ↔ p ∈ divergence (ofPaths [x]) (ofPaths [y]) := by intro x y p - have hxx : ¬ f [x] [x] p := by simpa [branches, divergence] using (hd [x] p) - have hyy : ¬ f [y] [y] p := by simpa [branches, divergence] using (hd [y] p) + have hxx : ¬ f [x] [x] p := by simpa [branches, mem_divergence] using (hd [x] p) + have hyy : ¬ f [y] [y] p := by simpa [branches, mem_divergence] using (hd [y] p) have hh := hd ([x] ++ [y]) p rw [hl, hr, hr] at hh have hxy := hs [y] [x] p have hp := singleton_polarization x y p + rw [ofPaths_cons x [y]] at hp + simp only [append_eq_union] at hh grind intro a b p - induction a generalizing b with - | nil => simp [he, divergence] + induction a using space_induction generalizing b with + | nil => simp [he] | cons x xs ih => have hxb : f [x] b p ↔ p ∈ divergence [x] b := by - induction b with - | nil => simp [he, divergence] + induction b using space_induction with + | nil => simp [he] | cons y ys ihb => change f [x] ([y] ++ ys) p ↔ _ rw [hr, hsingle, ihb] simpa [union] using (divergence_union_right [x] [y] ys p).symm change f ([x] ++ xs) b p ↔ _ rw [hl, hxb, ih] - simp [divergence, List.mem_append] + rw [divergence_union_left]; simp only [mem_union] /-- Empty annihilation follows from the other three characterizing laws. -/ theorem divergence_unique_three (f : PathSpace → PathSpace → Path → Prop) @@ -117,30 +114,35 @@ theorem divergence_unique_three (hr : ∀ a b c p, f a (b ++ c) p ↔ f a b p ∨ f a c p) (hd : ∀ a p, f a a p ↔ p ∈ branches a) : ∀ a b p, f a b p ↔ p ∈ divergence a b := by - have hempty : ∀ a p, ¬ f [] a p := by + have hempty : ∀ a p, ¬ f (ofPaths []) a p := by intro a p - induction a with - | nil => simpa [branches, divergence] using hd [] p + induction a using space_induction with + | nil => simpa [branches, mem_divergence] using hd (ofPaths []) p | cons x xs ih => - have hself : ¬ f [x] [x] p := by simpa [branches, divergence] using hd [x] p - have hx : ¬ f [] [x] p := fun h => hself ((hl [] [x] [x] p).mpr (Or.inl h)) - change ¬ f [] ([x] ++ xs) p + have hself : ¬ f [x] [x] p := by simpa [branches, mem_divergence] using hd [x] p + have hx : ¬ f (ofPaths []) [x] p := fun h => hself (by + simpa only [append_eq_union, ofPaths_nil, Zippy.empty_union] using + ((hl (ofPaths []) [x] [x] p).mpr (Or.inl h))) + change ¬ f (ofPaths []) ([x] ++ xs) p rw [hr] exact fun h => h.elim hx ih - exact divergence_unique f (fun a p => ⟨hempty a p, fun h => hempty a p ((hs a [] p).mp h)⟩) + exact divergence_unique f (fun a p => ⟨hempty a p, fun h => hempty a p ((hs a (ofPaths []) p).mp h)⟩) hs hl hr hd -theorem divergence_no_unit (u : PathSpace) : divergence [[]] u ≠ [[]] := by simp +theorem divergence_no_unit (u : PathSpace) : divergence (ofPaths [[]]) u ≠ (ofPaths [[]]) := by + intro h + have he : ([] : Path) ∈ divergence (ofPaths [[]]) u := h.symm ▸ (by simp) + simp at he theorem divergence_not_associative : ¬ ∀ a b c : PathSpace, equiv (divergence (divergence a b) c) (divergence a (divergence b c)) = true := by intro h - have bad := h [[0,0]] [[0,1]] [[1]] - exact (by decide : equiv (divergence (divergence [[0,0]] [[0,1]]) [[1]]) - (divergence [[0,0]] (divergence [[0,1]] [[1]])) ≠ true) bad + have bad := h (ofPaths [[0,0]]) (ofPaths [[0,1]]) (ofPaths [[1]]) + exact (by decide : equiv (divergence (divergence (ofPaths [[0,0]]) (ofPaths [[0,1]])) (ofPaths [[1]])) + (divergence (ofPaths [[0,0]]) (divergence (ofPaths [[0,1]]) (ofPaths [[1]]))) ≠ true) bad -end PathMapModel.PathSpace +end PrunedModel.Convex namespace PathMapModel.Path @@ -181,23 +183,11 @@ theorem divergence_extend_left {a b p : Path} (tail : Path) (h : divergence a b exact h theorem prefix_iff_extension (p q : Path) : - (p ≼ q) = true ↔ ∃ r, q = p ++ r := by - induction p generalizing q with - | nil => simp [isPrefixOf] - | cons x xs ih => - cases q with - | nil => simp [isPrefixOf] - | cons y ys => - simp only [isPrefixOf, Bool.and_eq_true, beq_iff_eq, List.cons_append, List.cons.injEq] - rw [ih] - constructor - · rintro ⟨rfl, r, hr⟩ - exact ⟨r, rfl, hr⟩ - · rintro ⟨r, rfl, hr⟩ - exact ⟨rfl, r, hr⟩ + (p ≼ q) = true ↔ ∃ r, q = p ++ r := PrunedModel.Path.isPrefixOf_iff p q end PathMapModel.Path -namespace PathMapModel.PathSpace +namespace PrunedModel.Convex +open PathMapModel theorem divergence_covered_mono {a b c : PathSpace} (hc : ∀ x ∈ a, ∃ y ∈ b, (x ≼ y) = true) : @@ -221,4 +211,4 @@ theorem divergence_nested_bound {a b c : PathSpace} {p : Path} · apply divergence_covered_mono (a := divergence a b) (b := b) (c := c) ?_ p h intro x hx exact divergence_output_covered ((divergence_comm a b x).mp hx) -end PathMapModel.PathSpace +end PrunedModel.Convex diff --git a/lean/PathMapModel/PathSetRecursive.lean b/lean/PrunedModel/Convex/PathSetRecursive.lean similarity index 74% rename from lean/PathMapModel/PathSetRecursive.lean rename to lean/PrunedModel/Convex/PathSetRecursive.lean index fd3f9462..52cf4990 100644 --- a/lean/PathMapModel/PathSetRecursive.lean +++ b/lean/PrunedModel/Convex/PathSetRecursive.lean @@ -1,6 +1,7 @@ -import PathMapModel.PathSetFork +import PrunedModel.Convex.PathSetFork -namespace PathMapModel.PathSpace +namespace PrunedModel.Convex +open PathMapModel theorem basis_nil (a : PathSpace) : [] ∈ basis a ↔ [] ∈ a := by rw [mem_basis] @@ -58,8 +59,8 @@ theorem hull_cons (a : PathSpace) (c : UInt8) (p : Path) : simpa [Path.isPrefixOf] using hf · simp [Path.isPrefixOf,Ne.symm hd] -theorem head_empty (a : PathSpace) : head a = [] ↔ ∀ p ∈ a, p = [] := by - rw [List.eq_nil_iff_forall_not_mem] +theorem head_empty (a : PathSpace) : head a = (ofPaths []) ↔ ∀ p ∈ a, p = [] := by + rw [eq_empty_iff] constructor · intro h p hp cases p with @@ -70,13 +71,13 @@ theorem head_empty (a : PathSpace) : head a = [] ↔ ∀ p ∈ a, p = [] := by have hh := h (c::ps) hp simp at hh -theorem hull_nil (a : PathSpace) : [] ∈ hull a ↔ [] ∈ a ∧ head a = [] := by +theorem hull_nil (a : PathSpace) : [] ∈ hull a ↔ [] ∈ a ∧ head a = (ofPaths []) := by rw [mem_hull,head_empty] simp only [Path.isPrefixOf] grind -theorem retain_nil (m a : PathSpace) : [] ∈ retain m a ↔ [] ∈ m ∧ a ≠ [] := by - cases a <;> simp [retain,Path.isPrefixOf] +theorem retain_nil (m a : PathSpace) : [] ∈ retain m a ↔ [] ∈ m ∧ a ≠ (ofPaths []) := by + simp [mem_retain, ne_empty_iff, Path.isPrefixOf] theorem retain_cons (m a : PathSpace) (c : UInt8) (p : Path) : c :: p ∈ retain m a ↔ p ∈ retain (unwrap m [c]) (unwrap a [c]) := by @@ -96,27 +97,17 @@ theorem child_of_unwrap {a : PathSpace} {c : UInt8} {p : Path} (h : p ∈ unwrap a [c]) : Child a [] c := ⟨p,(mem_unwrap a [c] p).mp h⟩ theorem mem_head_expansion (a : PathSpace) (f : Path → PathSpace) (p : Path) : - p ∈ (normalize (head a)).flatMap (fun q => wrap q (f q)) ↔ + p ∈ bind (head a) (fun q => wrap q (f q)) ↔ ∃ c r, Child a [] c ∧ r ∈ f [c] ∧ c :: r = p := by - simp only [List.mem_flatMap,mem_normalize,mem_head,mem_wrap] + simp only [mem_bind,mem_head,mem_wrap] constructor · rintro ⟨q,⟨c,rfl,hc⟩,r,hr,rfl⟩; exact ⟨c,r,hc,hr,rfl⟩ · rintro ⟨c,r,hc,hr,rfl⟩; exact ⟨[c],⟨c,rfl,hc⟩,r,hr,rfl⟩ theorem mem_common_head_expansion (a b : PathSpace) (f : Path → PathSpace) (p : Path) : - p ∈ (inter (normalize (head a)) (normalize (head b))).flatMap (fun q => wrap q (f q)) ↔ + p ∈ bind (inter (head a) (head b)) (fun q => wrap q (f q)) ↔ ∃ c r, Child a [] c ∧ Child b [] c ∧ r ∈ f [c] ∧ c :: r = p := by - simp only [List.mem_flatMap,mem_inter,mem_normalize,mem_head,mem_wrap] - constructor - · rintro ⟨q,⟨⟨c,rfl,hc⟩,⟨d,hd,hd'⟩⟩,r,hr,rfl⟩ - have he : c = d := by simpa using hd - subst d; exact ⟨c,r,hc,hd',hr,rfl⟩ - · rintro ⟨c,r,hc,hd,hr,rfl⟩; exact ⟨[c],⟨⟨c,rfl,hc⟩,⟨c,rfl,hd⟩⟩,r,hr,rfl⟩ - -theorem mem_retain_head_expansion (a b : PathSpace) (f : Path → PathSpace) (p : Path) : - p ∈ (normalize (inter (head a) (head b))).flatMap (fun q => wrap q (f q)) ↔ - ∃ c r, Child a [] c ∧ Child b [] c ∧ r ∈ f [c] ∧ c :: r = p := by - simp only [List.mem_flatMap,mem_inter,mem_normalize,mem_head,mem_wrap] + simp only [mem_bind,mem_inter,mem_head,mem_wrap] constructor · rintro ⟨q,⟨⟨c,rfl,hc⟩,⟨d,hd,hd'⟩⟩,r,hr,rfl⟩ have he : c = d := by simpa using hd @@ -124,9 +115,9 @@ theorem mem_retain_head_expansion (a b : PathSpace) (f : Path → PathSpace) (p · rintro ⟨c,r,hc,hd,hr,rfl⟩; exact ⟨[c],⟨⟨c,rfl,hc⟩,⟨c,rfl,hd⟩⟩,r,hr,rfl⟩ theorem divergence_root_test (a b : PathSpace) : - ((normalize (head a)).any (fun x => (normalize (head b)).any (· != x))) = true ↔ + ((head a).keys.any (fun x => (head b).keys.any (· != x))) = true ↔ [] ∈ divergence a b := by - simp only [List.any_eq_true,mem_normalize,mem_head,mem_divergence_children,bne_iff_ne] + simp only [List.any_eq_true,mem_keys,mem_head,mem_divergence_children,bne_iff_ne] constructor · rintro ⟨x,⟨c,rfl,hc⟩,y,⟨d,rfl,hd⟩,hne⟩ exact ⟨c,d,by simpa [Ne,eq_comm] using hne,hc,hd⟩ @@ -140,12 +131,11 @@ theorem basisRec_spec (n : Nat) (a : PathSpace) (p : Path) : | succ n ih => rw [basisRec] by_cases he : [] ∈ a - · simp only [List.contains_iff_mem.mpr he,if_true,List.mem_singleton] + · simp only [he,if_true,mem_ofPaths,List.mem_singleton] cases p with | nil => simp [basis_nil,he] | cons c ps => simp [basis_cons,he] - · have hb : a.contains [] = false := by simpa using he - simp only [hb,Bool.false_eq_true,if_false,mem_head_expansion] + · simp only [he,if_false,mem_head_expansion] cases p with | nil => simp [basis_nil,he] | cons c ps => @@ -159,23 +149,21 @@ theorem hullRec_spec (n : Nat) (a : PathSpace) (p : Path) : induction n generalizing a p with | zero => simp [hullRec] | succ n ih => - simp only [hullRec,List.mem_append,mem_head_expansion] - by_cases he : (a.contains [] && (head a).isEmpty) = true - · have hh : [] ∈ a ∧ head a = [] := by simpa using he - simp only [he] - simp only [if_true] + simp only [hullRec,mem_union,mem_head_expansion] + by_cases he : ([] : Path) ∈ a ∧ head a = ofPaths [] + · have hh := he + rw [if_pos he] cases p with | nil => simp [hull_nil,hh] | cons c ps => - simp only [List.mem_singleton,List.cons_ne_nil,false_or,List.cons.injEq,ih,List.length_cons,hull_cons] + simp only [mem_ofPaths,List.mem_singleton,List.cons_ne_nil,false_or,List.cons.injEq,ih,List.length_cons,hull_cons] exact ⟨fun ⟨_,_,_,⟨hp,hl⟩,rfl,rfl⟩ => ⟨hp,by omega⟩, fun ⟨hp,hl⟩ => ⟨c,ps,child_of_unwrap (hull_subset _ hp),⟨hp,by omega⟩,rfl,rfl⟩⟩ - · have hb : (a.contains [] && (head a).isEmpty) = false := by simpa using he - simp only [hb,Bool.false_eq_true,if_false] + · simp only [he,if_false] cases p with | nil => simp [hull_nil]; simpa using he | cons c ps => - simp only [List.not_mem_nil,false_or,List.cons.injEq,ih,List.length_cons,hull_cons] + simp only [mem_ofPaths,List.not_mem_nil,false_or,List.cons.injEq,ih,List.length_cons,hull_cons] exact ⟨fun ⟨_,_,_,⟨hp,hl⟩,rfl,rfl⟩ => ⟨hp,by omega⟩, fun ⟨hp,hl⟩ => ⟨c,ps,child_of_unwrap (hull_subset _ hp),⟨hp,by omega⟩,rfl,rfl⟩⟩ @@ -184,14 +172,13 @@ theorem divergenceRec_spec (n : Nat) (a b : PathSpace) (p : Path) : induction n generalizing a b p with | zero => simp [divergenceRec] | succ n ih => - simp only [divergenceRec,List.mem_append,mem_common_head_expansion] - by_cases he : (normalize (head a)).any (fun x => (normalize (head b)).any (· != x)) = true - · simp only [he] - simp only [if_true] + simp only [divergenceRec,mem_union,mem_common_head_expansion] + by_cases he : (head a).keys.any (fun x => (head b).keys.any (· != x)) = true + · rw [if_pos he] cases p with | nil => simp [(divergence_root_test a b).mp he] | cons c ps => - simp only [List.mem_singleton,List.cons_ne_nil,false_or,List.cons.injEq,ih,List.length_cons] + simp only [mem_ofPaths,List.mem_singleton,List.cons_ne_nil,false_or,List.cons.injEq,ih,List.length_cons] have hun := divergence_unwrap a b [c] ps simp only [List.singleton_append] at hun rw [← hun] @@ -200,12 +187,12 @@ theorem divergenceRec_spec (n : Nat) (a b : PathSpace) (p : Path) : · rintro ⟨hp,hl⟩ obtain ⟨x,hx,y,hy,hd⟩ := (mem_divergence _ _ _).mp hp exact ⟨c,ps,child_of_unwrap hx,child_of_unwrap hy,⟨hp,by omega⟩,rfl,rfl⟩ - · have hb : (normalize (head a)).any (fun x => (normalize (head b)).any (· != x)) = false := by simpa using he + · have hb : (head a).keys.any (fun x => (head b).keys.any (· != x)) = false := by simpa using he simp only [hb,Bool.false_eq_true,if_false] cases p with | nil => simp; exact fun h => he ((divergence_root_test a b).mpr h) | cons c ps => - simp only [List.not_mem_nil,false_or,List.cons.injEq,ih,List.length_cons] + simp only [mem_ofPaths,List.not_mem_nil,false_or,List.cons.injEq,ih,List.length_cons] have hun := divergence_unwrap a b [c] ps simp only [List.singleton_append] at hun rw [← hun] @@ -220,26 +207,24 @@ theorem retainRec_spec (n : Nat) (m a : PathSpace) (p : Path) : induction n generalizing m a p with | zero => simp [retainRec] | succ n ih => - simp only [retainRec,List.mem_append,mem_retain_head_expansion] - by_cases he : (m.contains [] && !a.isEmpty) = true + simp only [retainRec,mem_union,mem_common_head_expansion] + by_cases he : ([] : Path) ∈ m ∧ a ≠ ofPaths [] · have hh : [] ∈ retain m a := (retain_nil m a).mpr (by simpa using he) - simp only [he] - simp only [if_true] + rw [if_pos he] cases p with | nil => simp [hh] | cons c ps => - simp only [List.mem_singleton,List.cons_ne_nil,false_or,List.cons.injEq,ih,List.length_cons,retain_cons] + simp only [mem_ofPaths,List.mem_singleton,List.cons_ne_nil,false_or,List.cons.injEq,ih,List.length_cons,retain_cons] constructor · rintro ⟨_,_,_,_,⟨hp,hl⟩,rfl,rfl⟩; exact ⟨hp,by omega⟩ · rintro ⟨hp,hl⟩ obtain ⟨hm,q,hq,_⟩ := (mem_retain _ _ _).mp hp exact ⟨c,ps,child_of_unwrap hm,child_of_unwrap hq,⟨hp,by omega⟩,rfl,rfl⟩ - · have hb : (m.contains [] && !a.isEmpty) = false := by simpa using he - simp only [hb,Bool.false_eq_true,if_false] + · simp only [he,if_false] cases p with | nil => simp [retain_nil]; simpa using he | cons c ps => - simp only [List.not_mem_nil,false_or,List.cons.injEq,ih,List.length_cons,retain_cons] + simp only [mem_ofPaths,List.not_mem_nil,false_or,List.cons.injEq,ih,List.length_cons,retain_cons] constructor · rintro ⟨_,_,_,_,⟨hp,hl⟩,rfl,rfl⟩; exact ⟨hp,by omega⟩ · rintro ⟨hp,hl⟩ @@ -277,4 +262,4 @@ theorem retain_recursive (m a : PathSpace) (p : Path) : p ∈ retainRec (height m + 1) m a ↔ p ∈ retain m a := by rw [retainRec_spec] exact ⟨And.left,fun h => ⟨h,Nat.lt_succ_of_le (length_le_height ((mem_retain _ _ _).mp h).1)⟩⟩ -end PathMapModel.PathSpace +end PrunedModel.Convex diff --git a/lean/PathMapModel/PathSetRoots.lean b/lean/PrunedModel/Convex/PathSetRoots.lean similarity index 79% rename from lean/PathMapModel/PathSetRoots.lean rename to lean/PrunedModel/Convex/PathSetRoots.lean index 7fc51bd9..68087911 100644 --- a/lean/PathMapModel/PathSetRoots.lean +++ b/lean/PrunedModel/Convex/PathSetRoots.lean @@ -1,6 +1,7 @@ -import PathMapModel.PathSetPowers +import PrunedModel.Convex.PathSetPowers -namespace PathMapModel.PathSpace +namespace PrunedModel.Convex +open PathMapModel theorem hull_is_antichain (a : PathSpace) : Antichain (hull a) := by intro p hp q hq he @@ -9,7 +10,7 @@ theorem hull_is_antichain (a : PathSpace) : Antichain (hull a) := by · have hf := hull_antichain hp hq hn simp [he] at hf -theorem divergence_empty_iff (a b : PathSpace) : divergence a b = [] ↔ +theorem divergence_empty_iff (a b : PathSpace) : divergence a b = ofPaths [] ↔ ∀ x ∈ a, ∀ y ∈ b, (x ≼ y) = true ∨ (y ≼ x) = true := by constructor · intro h x hx y hy @@ -20,7 +21,7 @@ theorem divergence_empty_iff (a b : PathSpace) : divergence a b = [] ↔ have hp := (mem_divergence a b p).mpr ⟨x,hx,y,hy,hd⟩ simp [h] at hp · intro h - apply List.eq_nil_iff_forall_not_mem.mpr + apply (eq_empty_iff _).mpr intro p hp obtain ⟨x,hx,y,hy,hd⟩ := (mem_divergence _ _ _).mp hp have hn := (Path.divergence_none_iff x y).mpr (h x hx y hy) @@ -44,23 +45,22 @@ theorem comparable_antichains {a b : PathSpace} (ha : Antichain a) (hb : Anticha · have he := hb v hv y hy (Path.prefix_trans hvx hxy) subst v; exact hxy -/-- The exact zero criterion, phrased extensionally so duplicate list entries -cannot be mistaken for extra members. -/ -theorem zero_criterion (a b : PathSpace) : divergence a b = [] ↔ - a = [] ∨ b = [] ∨ +/-- The exact zero criterion in terms of the maximal paths on each side. -/ +theorem zero_criterion (a b : PathSpace) : divergence a b = ofPaths [] ↔ + a = ofPaths [] ∨ b = ofPaths [] ∨ (∃ x, (∀ u, u ∈ hull a ↔ u = x) ∧ ∀ v ∈ hull b, (x ≼ v) = true) ∨ (∃ y, (∀ v, v ∈ hull b ↔ v = y) ∧ ∀ u ∈ hull a, (y ≼ u) = true) := by - have he : divergence a b = [] ↔ divergence (hull a) (hull b) = [] := by - simp only [List.eq_nil_iff_forall_not_mem,divergence_hull] + have he : divergence a b = ofPaths [] ↔ divergence (hull a) (hull b) = ofPaths [] := by + simp only [eq_empty_iff,divergence_hull] rw [he,divergence_empty_iff] constructor · intro hc - by_cases ha : a = [] + by_cases ha : a = ofPaths [] · exact Or.inl ha - by_cases hb : b = [] + by_cases hb : b = ofPaths [] · exact Or.inr (Or.inl hb) - have hha : hull a ≠ [] := fun h => ha ((hull_nonempty a).mp h) - have hhb : hull b ≠ [] := fun h => hb ((hull_nonempty b).mp h) + have hha : hull a ≠ ofPaths [] := fun h => ha ((hull_nonempty a).mp h) + have hhb : hull b ≠ ofPaths [] := fun h => hb ((hull_nonempty b).mp h) obtain ⟨x,hx,_⟩ := height_attained hha obtain ⟨y,hy,_⟩ := height_attained hhb rcases hc x hx y hy with hxy | hyx @@ -76,17 +76,20 @@ theorem zero_criterion (a b : PathSpace) : divergence a b = [] ↔ · intro u hu v hv; have he := (hx u).mp hu; subst u; exact Or.inl (hext v hv) · intro u hu v hv; have he := (hy v).mp hv; subst v; exact Or.inr (hext u hu) -theorem commonPrefix_spec (a : PathSpace) (ha : a ≠ []) (p : Path) : +theorem commonPrefix_spec (a : PathSpace) (ha : a ≠ ofPaths []) (p : Path) : (p ≼ commonPrefix a) = true ↔ ∀ q ∈ a, (p ≼ q) = true := by - have go : ∀ (xs : PathSpace) (q : Path), (p ≼ xs.foldl Path.lcp q) = true ↔ + have go : ∀ (xs : List Path) (q : Path), (p ≼ xs.foldl Path.lcp q) = true ↔ (p ≼ q) = true ∧ ∀ r ∈ xs, (p ≼ r) = true := by intro xs induction xs with | nil => simp | cons r rs ih => intro q; simp [ih,Path.prefix_lcp]; grind - cases a with - | nil => exact False.elim (ha rfl) - | cons q qs => simpa [commonPrefix] using go qs q + cases he : a.keys with + | nil => exact False.elim (ha ((keys_eq_nil_iff a).mp he)) + | cons q qs => + have hh := go qs q + simp only [commonPrefix,he] + simpa only [← mem_keys a,he,List.mem_cons,forall_eq_or_imp] using hh theorem first_divergence_covers_left {a b : PathSpace} (ha : Antichain a) {p : Path} (hp : p ∈ basis (divergence a b)) : ∀ u ∈ a, (p ≼ u) = true := by @@ -113,16 +116,16 @@ theorem first_divergence_covers_left {a b : PathSpace} (ha : Antichain a) {p : P omega · exact hpu -theorem first_divergence (a b : PathSpace) (h : divergence a b ≠ []) (p : Path) : +theorem first_divergence (a b : PathSpace) (h : divergence a b ≠ ofPaths []) (p : Path) : p ∈ basis (divergence a b) ↔ p = commonPrefix (union (hull a) (hull b)) := by let x := divergence (hull a) (hull b) have hx : ∀ q, q ∈ x ↔ q ∈ divergence a b := divergence_hull a b have hbas : ∀ q, q ∈ basis x ↔ q ∈ basis (divergence a b) := by intro q; simp only [mem_basis,hx] - have hn : x ≠ [] := by + have hn : x ≠ ofPaths [] := by intro hh apply h - apply List.eq_nil_iff_forall_not_mem.mpr + apply (eq_empty_iff _).mpr intro q hq have hm := (hx q).mpr hq simp [hh] at hm @@ -133,13 +136,13 @@ theorem first_divergence (a b : PathSpace) (h : divergence a b ≠ []) (p : Path simpa only [mem_basis,divergence_comm (hull b) (hull a)] using hq have hqb := first_divergence_covers_left (hull_is_antichain b) hswap obtain ⟨u,hu,v,hv,hd⟩ := (mem_divergence _ _ _).mp (basis_subset _ hq) - have hun : union (hull a) (hull b) ≠ [] := List.ne_nil_of_mem (List.mem_append_left _ hu) + have hun : union (hull a) (hull b) ≠ ofPaths [] := (ne_empty_iff _).mpr ⟨u,(mem_union _ _ _).mpr (Or.inl hu)⟩ have hpref := (commonPrefix_spec _ hun q).mpr (by - intro r hr; rcases List.mem_append.mp hr with hr | hr + intro r hr; rcases (mem_union _ _ _).mp hr with hr | hr · exact hqa r hr · exact hqb r hr) have hcp := (commonPrefix_spec _ hun (commonPrefix (union (hull a) (hull b)))).mp (Path.prefix_self _) - have hcq := (Path.prefix_lcp _ u v).mpr ⟨hcp u (List.mem_append_left _ hu),hcp v (List.mem_append_right _ hv)⟩ + have hcq := (Path.prefix_lcp _ u v).mpr ⟨hcp u ((mem_union _ _ _).mpr (Or.inl hu)),hcp v ((mem_union _ _ _).mpr (Or.inr hv))⟩ rw [Path.divergence_lcp hd] at hcq exact Path.prefix_antisymm hpref hcq rw [← hbas p] @@ -149,4 +152,4 @@ theorem first_divergence (a b : PathSpace) (h : divergence a b ≠ []) (p : Path obtain ⟨q,hq,_⟩ := height_attained (fun hh => hn ((basis_nonempty x).mp hh)) have heq := (hall q hq).trans he.symm exact heq ▸ hq -end PathMapModel.PathSpace +end PrunedModel.Convex diff --git a/lean/PathMapModel/PathSetStructure.lean b/lean/PrunedModel/Convex/PathSetStructure.lean similarity index 63% rename from lean/PathMapModel/PathSetStructure.lean rename to lean/PrunedModel/Convex/PathSetStructure.lean index c3facdf2..48a23dfb 100644 --- a/lean/PathMapModel/PathSetStructure.lean +++ b/lean/PrunedModel/Convex/PathSetStructure.lean @@ -1,54 +1,19 @@ -import PathMapModel.PathSetDepth +import PrunedModel.Convex.PathSetDepth -namespace PathMapModel.Path - -theorem mem_insertSorted (a p : Path) (s : List Path) : - p ∈ insertSorted a s ↔ p = a ∨ p ∈ s := by - induction s with - | nil => simp [insertSorted] - | cons q qs ih => - by_cases h : a = q - · subst q; simp [insertSorted] - · by_cases hl : lt a q - · simp [insertSorted,h,hl] <;> grind - · simp [insertSorted,h,hl,ih] <;> grind - -theorem mem_sortDedup (s : List Path) (p : Path) : p ∈ sortDedup s ↔ p ∈ s := by - have go : ∀ (xs acc : List Path), - p ∈ xs.foldl (fun a q => insertSorted q a) acc ↔ p ∈ xs ∨ p ∈ acc := by - intro xs - induction xs with - | nil => simp - | cons q qs ih => intro acc; simp [ih,mem_insertSorted] <;> grind - simpa [sortDedup] using go s [] - -theorem stripPrefix_eq (p q r : Path) : stripPrefix p q = some r ↔ q = p ++ r := by - induction p generalizing q with - | nil => simp [stripPrefix] - | cons a ps ih => - cases q with - | nil => simp [stripPrefix] - | cons b qs => - by_cases h : a = b - · subst b; simp [stripPrefix,ih] - · simp [stripPrefix,h] <;> grind -end PathMapModel.Path - -namespace PathMapModel.PathSpace - -@[simp] theorem mem_normalize (a : PathSpace) (p : Path) : p ∈ normalize a ↔ p ∈ a := - Path.mem_sortDedup a p +namespace PrunedModel.Convex +open PathMapModel theorem mem_wrap (q : Path) (a : PathSpace) (p : Path) : - p ∈ wrap q a ↔ ∃ r ∈ a, q ++ r = p := by simp [wrap] + p ∈ wrap q a ↔ ∃ r ∈ a, q ++ r = p := by + rw [Zippy.mem_wrap]; grind theorem mem_unwrap (a : PathSpace) (q p : Path) : p ∈ unwrap a q ↔ q ++ p ∈ a := by - simp [unwrap,List.mem_filterMap,Path.stripPrefix_eq] + exact Zippy.mem_unwrap theorem mem_product (a b : PathSpace) (p : Path) : p ∈ product a b ↔ ∃ x ∈ a, ∃ y ∈ b, x ++ y = p := by - simp [product,List.mem_flatMap] + rw [Zippy.mem_composition]; grind theorem divergence_unwrap (a b : PathSpace) (q p : Path) : p ∈ divergence (unwrap a q) (unwrap b q) ↔ q ++ p ∈ divergence a b := by @@ -77,26 +42,13 @@ theorem divergence_wrap (a b : PathSpace) (q p : Path) : theorem mem_head (a : PathSpace) (p : Path) : p ∈ head a ↔ ∃ c, p = [c] ∧ Child a [] c := by - simp only [head,List.mem_filterMap,Option.map_eq_some_iff] - constructor - · rintro ⟨q,hq,c,hc,rfl⟩ - cases q with - | nil => simp at hc - | cons d qs => - simp only [List.head?_cons,Option.some.injEq] at hc - subst d; exact ⟨c,rfl,qs,hq⟩ - · rintro ⟨c,rfl,qs,hq⟩ - exact ⟨c::qs,hq,c,rfl,rfl⟩ + rw [Zippy.mem_head] + simp only [Child, List.nil_append] + grind theorem mem_tails (a : PathSpace) (p : Path) : p ∈ tails a ↔ ∃ c, c :: p ∈ a := by - simp only [tails,List.mem_filterMap] - constructor - · rintro ⟨q,hq,hd⟩ - cases q with - | nil => simp at hd - | cons c qs => simp only [Option.some.injEq] at hd; subst qs; exact ⟨c,hq⟩ - · rintro ⟨c,hc⟩; exact ⟨c::p,hc,rfl⟩ + exact Zippy.mem_tailsUnion theorem child_head (a : PathSpace) (p : Path) (c : UInt8) : Child (head a) p c ↔ p = [] ∧ Child a [] c := by @@ -134,4 +86,4 @@ theorem divergence_tails {a b : PathSpace} {p : Path} apply divergence_mono (a := unwrap a [c]) (b := unwrap b [c]) ?_ ?_ p hs · intro q hq; exact (mem_tails _ _).mpr ⟨c,(mem_unwrap _ _ _).mp hq⟩ · intro q hq; exact (mem_tails _ _).mpr ⟨c,(mem_unwrap _ _ _).mp hq⟩ -end PathMapModel.PathSpace +end PrunedModel.Convex diff --git a/lean/PathMapModel/PathSetUpdates.lean b/lean/PrunedModel/Convex/PathSetUpdates.lean similarity index 76% rename from lean/PathMapModel/PathSetUpdates.lean rename to lean/PrunedModel/Convex/PathSetUpdates.lean index ff341785..52be6513 100644 --- a/lean/PathMapModel/PathSetUpdates.lean +++ b/lean/PrunedModel/Convex/PathSetUpdates.lean @@ -1,22 +1,23 @@ -import PathMapModel.PathSetCardinality +import PrunedModel.Convex.PathSetCardinality -namespace PathMapModel.PathSpace +namespace PrunedModel.Convex +open PathMapModel theorem singleton_bound (q : Path) (a : PathSpace) : count (divergence [q] a) ≤ min q.length (count (hull a)) := by apply Nat.le_min.mpr constructor - · have hs : (divergence [q] a).eraseDups ⊆ (List.range q.length).map (q.take ·) := by + · have hs : (divergence [q] a).keys ⊆ (List.range q.length).map (q.take ·) := by intro p hp - have hp' := List.mem_eraseDups.mp hp + have hp' := Zippy.mem_keys.mp hp obtain ⟨x,hx,y,hy,hd⟩ := (mem_divergence _ _ _).mp hp' - simp only [List.mem_singleton] at hx + simp only [mem_ofPaths, List.mem_singleton] at hx subst x have hlen := Path.divergence_length_left hd have hpre := (Path.prefix_iff_list _ _).mp (Path.divergence_prefix_left hd) have he := List.prefix_iff_eq_take.mp hpre exact List.mem_map.mpr ⟨p.length,List.mem_range.mpr hlen,he.symm⟩ - have hh := (dedup_nodup (divergence [q] a)).length_le_of_subset hs + have hh := (keys_nodup (divergence [q] a)).length_le_of_subset hs simpa [count] using hh · have hc : count (divergence [q] a) = count (divergence [q] (hull a)) := by apply count_congr @@ -26,7 +27,7 @@ theorem singleton_bound (q : Path) (a : PathSpace) : apply count_relation (fun p x => Path.divergence q x = some p) ?_ ?_ · intro p hp obtain ⟨u,hu,v,hv,hd⟩ := (mem_divergence _ _ _).mp hp - simp only [List.mem_singleton] at hu + simp only [mem_ofPaths, List.mem_singleton] at hu subst u; exact ⟨v,hv,hd⟩ · intro p hp p' hp' x h h' exact Option.some.inj (h.symm.trans h') @@ -36,16 +37,16 @@ theorem singleton_outputs_comparable {q p r : Path} {a : PathSpace} (p ≼ r) = true ∨ (r ≼ p) = true := by obtain ⟨x,hx,hpx⟩ := divergence_output_covered hp obtain ⟨y,hy,hry⟩ := divergence_output_covered hr - simp only [List.mem_singleton] at hx hy + simp only [mem_ofPaths, List.mem_singleton] at hx hy subst x; subst y exact Path.prefixes_comparable hpx hry theorem count_le_one_of_equal (a : PathSpace) (h : ∀ p ∈ a, ∀ q ∈ a, p = q) : count a ≤ 1 := by - cases a with - | nil => simp [count] - | cons p ps => - have hs : count (p::ps) ≤ count [p] := count_mono (by - intro q hq; exact List.mem_singleton.mpr (h q hq p (by simp))) + by_cases he : a = ofPaths [] + · rw [(count_eq_zero a).mpr he]; omega + · obtain ⟨p,hp⟩ := (ne_empty_iff a).mp he + have hs : count a ≤ count [p] := count_mono (by + intro q hq; simpa using h q hq p hp) simpa [count_singleton] using hs theorem singleton_output_hull (q : Path) (a : PathSpace) : count (hull (divergence [q] a)) ≤ 1 := by @@ -63,9 +64,9 @@ theorem singleton_fresh_subset {q p : Path} {a : PathSpace} exact False.elim (hn (singleton_existing_branches hi)) theorem branch_insert (q : Path) (a : PathSpace) (p : Path) : - p ∈ branches (q :: a) ↔ p ∈ branches a ∨ p ∈ divergence [q] a := by + p ∈ branches (union [q] a) ↔ p ∈ branches a ∨ p ∈ divergence [q] a := by have h := branches_union [q] a p - simpa [union,branches,divergence] using h + simpa [branches,mem_divergence] using h theorem singleton_branch_update (q : Path) (a : PathSpace) : count (diff (branches (union a [q])) (branches a)) ≤ 1 := by @@ -87,24 +88,28 @@ theorem singleton_divergence_update (a b : PathSpace) (q : Path) : intro p hp obtain ⟨hp,hn⟩ := (mem_diff _ _ _).mp hp rw [divergence_union_left] at hp - rcases List.mem_append.mp hp with hp | hp + rcases (mem_union _ _ _).mp hp with hp | hp · exact False.elim (hn hp) · exact hp exact Nat.le_trans hs (singleton_bound q b) -theorem branch_count_length (a : PathSpace) : count (branches a) ≤ a.length - 1 := by +theorem branch_count_length (a : List Path) : count (branches a) ≤ a.length - 1 := by induction a with - | nil => simp [branches,count] + | nil => + have he : branches (ofPaths []) = ofPaths [] := by apply Zippy.ext; intro p; simp [branches] + rw [(count_eq_zero _).mpr he]; simp | cons q a ih => cases a with - | nil => simp [branches,divergence,count] + | nil => + have he : branches [q] = ofPaths [] := by apply Zippy.ext; intro p; simp [branches,mem_divergence] + rw [(count_eq_zero _).mpr he]; simp | cons r rs => let old := branches (r::rs) let fresh := diff (branches (q::r::rs)) old have hf : count fresh ≤ 1 := by have he : ∀ p, p ∈ branches (q::r::rs) ↔ p ∈ branches (union (r::rs) [q]) := by intro p - apply divergence_congr <;> intro u <;> simp [union] <;> grind + apply divergence_congr <;> intro u <;> simp [mem_union] <;> grind have hc : count fresh = count (diff (branches (union (r::rs) [q])) old) := by apply count_congr; intro p; simp only [fresh,mem_diff,he] rw [hc] @@ -113,19 +118,19 @@ theorem branch_count_length (a : PathSpace) : count (branches a) ≤ a.length - apply count_mono intro p hp by_cases ho : p ∈ old - · exact List.mem_append_left _ ho - · exact List.mem_append_right _ ((mem_diff _ _ _).mpr ⟨hp,ho⟩) + · exact mem_union_left _ ho + · exact mem_union_right _ ((mem_diff _ _ _).mpr ⟨hp,ho⟩) have hu := count_union_le old fresh dsimp [old] at hu hs simp only [List.length_cons] at ih ⊢ omega theorem branch_count (a : PathSpace) : count (branches a) ≤ count a - 1 := by - have he : count (branches a) = count (branches a.eraseDups) := by + have he : count (branches a) = count (branches a.keys) := by apply count_congr exact divergence_congr (by intro p; simp) (by intro p; simp) rw [he] - exact branch_count_length a.eraseDups + exact branch_count_length a.keys theorem output_cardinality (a b : PathSpace) : count (divergence a b) ≤ count (hull (union a b)) - 1 := by @@ -135,4 +140,4 @@ theorem output_cardinality (a b : PathSpace) : count_congr (fun p => (branch_hull (union a b) p).symm) rw [he] at hs exact Nat.le_trans hs (branch_count (hull (union a b))) -end PathMapModel.PathSpace +end PrunedModel.Convex diff --git a/lean/PrunedModel/Convex/PathSets.lean b/lean/PrunedModel/Convex/PathSets.lean new file mode 100644 index 00000000..1f956059 --- /dev/null +++ b/lean/PrunedModel/Convex/PathSets.lean @@ -0,0 +1,124 @@ +import PrunedModel.Convex.Space +import PrunedModel.Convex.Path + +/-! Additional finite-space geometry on `PrunedMap Unit`. Ordinary set +operations are imported from Zippy, so all laws concern the same canonical +model as the existing zipper algebra. -/ +namespace PrunedModel.Convex +open PathMapModel + +def retain (p a : PathSpace) : PathSpace := + ofPaths (p.keys.filter fun x => a.keys.any (x ≼ ·)) +def divergence (a b : PathSpace) : PathSpace := + ofPaths (a.keys.flatMap fun p => b.keys.filterMap (Path.divergence p)) +/-- Fold pairs whose second prefix properly extends the first. -/ +def properOverlap (a b : PathSpace) (f : Path → Path → PathSpace) : PathSpace := + ofPaths (a.keys.flatMap fun u => b.keys.flatMap fun v => match Path.stripPrefix u v with + | some r@(_ :: _) => (f u r).keys + | _ => []) +def branches (a : PathSpace) : PathSpace := divergence a a +/-- Prefix-minimal members. -/ +def basis (a : PathSpace) : PathSpace := + ofPaths (a.keys.filter fun p => !(a.keys.any fun q => q != p && q ≼ p)) +/-- Prefix-maximal members. -/ +def hull (a : PathSpace) : PathSpace := + ofPaths (a.keys.filter fun p => !(a.keys.any fun q => q != p && p ≼ q)) +def interior (a : PathSpace) : PathSpace := diff a (hull a) +def completion (a : PathSpace) : PathSpace := union a (branches a) +def lcpProduct (a b : PathSpace) : PathSpace := + ofPaths (a.keys.flatMap fun p => b.keys.map (Path.lcp p)) +def power (a : PathSpace) : Nat → PathSpace + | 0 => ofPaths [[]] + | n + 1 => product a (power a n) +def branchIter (a : PathSpace) : Nat → PathSpace + | 0 => a + | n + 1 => branches (branchIter a n) +/-- The canonical model already has distinct keys. -/ +def count (a : PathSpace) : Nat := a.keys.length +def height (a : PathSpace) : Nat := (a.keys.map List.length).foldl max 0 +def commonPrefix (a : PathSpace) : Path := match a.keys with + | [] => [] + | p :: ps => ps.foldl Path.lcp p +def prefixFree (a : PathSpace) : Bool := equiv a (basis a) +def covers (a b : PathSpace) : Bool := a.keys.all fun p => b.keys.any (p ≼ ·) + +/-- Union a family, using the existing finite key enumeration. -/ +def bind (a : PathSpace) (f : Path → PathSpace) : PathSpace := + ofPaths (a.keys.flatMap fun p => (f p).keys) +@[simp] theorem mem_bind (a : PathSpace) (f : Path → PathSpace) (p : Path) : + p ∈ bind a f ↔ ∃ q ∈ a, p ∈ f q := by simp [bind, List.mem_flatMap] + +/-- Independent head-recursive definitions, fueled by maximum length + 1. -/ +def divergenceRec : Nat → PathSpace → PathSpace → PathSpace + | 0, _, _ => ofPaths [] + | n + 1, a, b => + let ha := head a + let hb := head b + let root := if ha.keys.any (fun x => hb.keys.any (· != x)) then ofPaths [[]] else ofPaths [] + union root (bind (inter ha hb) fun p => wrap p (divergenceRec n (unwrap a p) (unwrap b p))) +def basisRec : Nat → PathSpace → PathSpace + | 0, _ => ofPaths [] + | n + 1, a => if ([] : Path) ∈ a then ofPaths [[]] else + bind (head a) fun p => wrap p (basisRec n (unwrap a p)) +def hullRec : Nat → PathSpace → PathSpace + | 0, _ => ofPaths [] + | n + 1, a => + let root := if ([] : Path) ∈ a ∧ head a = ofPaths [] then ofPaths [[]] else ofPaths [] + union root (bind (head a) fun p => wrap p (hullRec n (unwrap a p))) +def retainRec : Nat → PathSpace → PathSpace → PathSpace + | 0, _, _ => ofPaths [] + | n + 1, p, a => + let root := if ([] : Path) ∈ p ∧ a ≠ ofPaths [] then ofPaths [[]] else ofPaths [] + union root (bind (inter (head p) (head a)) fun q => + wrap q (retainRec n (unwrap p q) (unwrap a q))) + +def ofMap {V : Type} (t : PrunedMap V) : PathSpace := ofPaths t.keys + +/-- General witness theorem, not a bounded check. -/ +theorem mem_divergence (a b : PathSpace) (p : Path) : + p ∈ divergence a b ↔ ∃ x ∈ a, ∃ y ∈ b, Path.divergence x y = some p := by + simp [divergence, List.mem_flatMap, List.mem_filterMap] + +theorem divergence_comm (a b : PathSpace) (p : Path) : + p ∈ divergence a b ↔ p ∈ divergence b a := by + simp only [mem_divergence] + constructor + · rintro ⟨x, hx, y, hy, h⟩ + exact ⟨y, hy, x, hx, (Path.divergence_comm y x).trans h⟩ + · rintro ⟨y, hy, x, hx, h⟩ + exact ⟨x, hx, y, hy, (Path.divergence_comm x y).trans h⟩ + +@[simp] theorem divergence_empty_left (a : PathSpace) : divergence (ofPaths []) a = ofPaths [] := by + apply Zippy.ext; intro p; simp [mem_divergence] +@[simp] theorem divergence_empty_right (a : PathSpace) : divergence a (ofPaths []) = ofPaths [] := by + apply Zippy.ext; intro p; simp [mem_divergence] +@[simp] theorem divergence_epsilon_left (a : PathSpace) : divergence (ofPaths [[]]) a = ofPaths [] := by + apply Zippy.ext; intro p; simp [mem_divergence] +@[simp] theorem divergence_epsilon_right (a : PathSpace) : divergence a (ofPaths [[]]) = ofPaths [] := by + apply Zippy.ext; intro p; simp [mem_divergence] + +theorem divergence_union_left (a b c : PathSpace) : + divergence (union a b) c = union (divergence a c) (divergence b c) := by + apply Zippy.ext; intro p; simp only [mem_divergence, mem_union]; grind + +theorem divergence_union_right (a b c : PathSpace) (p : Path) : + p ∈ divergence a (union b c) ↔ p ∈ union (divergence a b) (divergence a c) := by + simp only [mem_union, mem_divergence]; grind + +theorem divergence_diagonal (a : PathSpace) : divergence a a = branches a := rfl + +theorem divergence_mono {a b c d : PathSpace} + (ha : ∀ p, p ∈ a → p ∈ c) (hb : ∀ p, p ∈ b → p ∈ d) : + ∀ p, p ∈ divergence a b → p ∈ divergence c d := by + intro p hp + obtain ⟨x, hx, y, hy, h⟩ := (mem_divergence a b p).mp hp + exact (mem_divergence c d p).mpr ⟨x, ha x hx, y, hb y hy, h⟩ + +theorem mem_basis (a : PathSpace) (p : Path) : + p ∈ basis a ↔ p ∈ a ∧ ∀ q ∈ a, q ≠ p → (q ≼ p) = false := by + simp [basis, List.mem_filter, Bool.not_eq_true, List.any_eq_false] + +theorem mem_hull (a : PathSpace) (p : Path) : + p ∈ hull a ↔ p ∈ a ∧ ∀ q ∈ a, q ≠ p → (p ≼ q) = false := by + simp [hull, List.mem_filter, Bool.not_eq_true, List.any_eq_false] +end PrunedModel.Convex diff --git a/lean/PathMapModel/ConvexPruning.lean b/lean/PrunedModel/Convex/Pruning.lean similarity index 94% rename from lean/PathMapModel/ConvexPruning.lean rename to lean/PrunedModel/Convex/Pruning.lean index 87a590a5..5623cfef 100644 --- a/lean/PathMapModel/ConvexPruning.lean +++ b/lean/PrunedModel/Convex/Pruning.lean @@ -1,6 +1,7 @@ -import PathMapModel.ConvexOrder +import PrunedModel.Convex.Order -namespace PathMapModel.PathSpace +namespace PrunedModel.Convex +open PathMapModel /-- Remove every currently exposed, unprotected tip. -/ def convexPruneStep (x tips : PathSpace) : PathSpace := diff x (diff (hull x) tips) @@ -122,16 +123,14 @@ theorem pruneMove_decreases {tips x y : PathSpace} (h : PruneMove tips x y) have hs := h.1 grind obtain ⟨p,hp,hpn⟩ := hex - have hf : y.filter (fun q => !q == p) = y := by - apply List.filter_eq_self.mpr + have hd : (p :: y.keys).Nodup := List.nodup_cons.mpr ⟨by simpa using hpn,keys_nodup y⟩ + have hl := hd.length_le_of_subset (l₂ := x.keys) (by intro q hq - have he : q ≠ p := fun he => hpn (he ▸ hq) - simp [he] - have hc : count (p :: y) = count y + 1 := by simp only [count,List.eraseDups_cons,hf,List.length_cons] - have hl : count (p :: y) ≤ count x := count_mono (by - intro q hq; rcases List.mem_cons.mp hq with rfl | hq + apply Zippy.mem_keys.mpr + rcases List.mem_cons.mp hq with rfl | hq · exact hp - · exact h.1 q hq) + · exact h.1 q (Zippy.mem_keys.mp hq)) + change count y + 1 ≤ count x at hl omega /-- Synchronous pruning is one permitted asynchronous schedule. -/ @@ -171,4 +170,4 @@ theorem convexSubtractRec_correct (a b : PathSpace) : Same (convexSubtractRec a rintro ⟨hh,hb⟩ exact hn ((hull_max hh (hull_subset a htip) hpt) ▸ hb) -end PathMapModel.PathSpace +end PrunedModel.Convex diff --git a/lean/PathMapModel/Retain.lean b/lean/PrunedModel/Convex/Retain.lean similarity index 88% rename from lean/PathMapModel/Retain.lean rename to lean/PrunedModel/Convex/Retain.lean index b711b7ce..90cd5205 100644 --- a/lean/PathMapModel/Retain.lean +++ b/lean/PrunedModel/Convex/Retain.lean @@ -1,16 +1,18 @@ -import PathMapModel.ConvexMap +import PrunedModel.Convex.Map +import PrunedModel.Convex.Morphisms /-! Retention and restriction are the two projections of the prefix relation. All equations are extensional on valued paths; no closure is implicit. -/ -namespace PathMapModel.PathSpace +namespace PrunedModel.Convex +open PathMapModel theorem retain_subset (a b : PathSpace) : Included (retain a b) a := fun p h => ((mem_retain a b p).mp h).1 -theorem retain_empty_left (a : PathSpace) : Same (retain [] a) [] := by +theorem retain_empty_left (a : PathSpace) : Same (retain (ofPaths []) a) (ofPaths []) := by intro p; simp [mem_retain] -theorem retain_empty_right (a : PathSpace) : Same (retain a []) [] := by +theorem retain_empty_right (a : PathSpace) : Same (retain a (ofPaths [])) (ofPaths []) := by intro p; simp [mem_retain] theorem retain_self (a : PathSpace) : Same (retain a a) a := by @@ -23,7 +25,7 @@ theorem retain_mono {a b c d : PathSpace} (h : Included a c) (k : Included b d) theorem retain_union_left (a b c : PathSpace) : Same (retain (union a b) c) (union (retain a c) (retain b c)) := by - intro p; simp only [mem_retain,union,List.mem_append]; grind + intro p; simp only [mem_retain,mem_union]; grind theorem retain_inter_left (a b c : PathSpace) : Same (retain (inter a b) c) (inter (retain a c) (retain b c)) := by @@ -35,11 +37,11 @@ theorem retain_diff_left (a b c : PathSpace) : theorem retain_symDiff_left (a b c : PathSpace) : Same (retain (symDiff a b) c) (symDiff (retain a c) (retain b c)) := by - intro p; simp only [symDiff,mem_retain,mem_diff,union,List.mem_append]; grind + intro p; simp only [symDiff,mem_retain,mem_diff,mem_union]; grind theorem retain_union_right (a b c : PathSpace) : Same (retain a (union b c)) (union (retain a b) (retain a c)) := by - intro p; simp only [mem_retain,union,List.mem_append]; grind + intro p; simp only [mem_retain,mem_union]; grind theorem retain_inter_right_bound (a b c : PathSpace) : Included (retain a (inter b c)) (inter (retain a b) (retain a c)) := by @@ -82,8 +84,8 @@ theorem retain_hull_mask (a b : PathSpace) : Same (retain a (hull b)) (retain a /-- Both semijoins describe the same set of matching prefix pairs. -/ theorem retain_restrict_empty (a b : PathSpace) : - Same (retain a b) [] ↔ Same (restrict b a) [] := by - simp only [Same,mem_retain,mem_restrict,List.not_mem_nil,iff_false]; grind + Same (retain a b) (ofPaths []) ↔ Same (restrict b a) (ofPaths []) := by + simp only [Same,mem_retain,mem_restrict,mem_ofPaths,List.not_mem_nil,iff_false]; grind theorem retain_restrict_witnesses (a b : PathSpace) : Same (retain a (restrict b a)) (retain a b) := by @@ -97,16 +99,16 @@ theorem restrict_retain_mask (a b : PathSpace) : · grind · rintro ⟨hp,q,hq,hqp⟩; exact ⟨hp,q,⟨hq,p,hp,hqp⟩,hqp⟩ -theorem retain_restrict_disjoint (a b : PathSpace) : Same (retain a (raffinate b a)) [] := by - intro p; simp only [mem_retain,raffinate,mem_diff,mem_restrict,List.not_mem_nil,iff_false]; grind +theorem retain_restrict_disjoint (a b : PathSpace) : Same (retain a (raffinate b a)) (ofPaths []) := by + intro p; simp only [mem_retain,raffinate,Zippy.raffination,mem_diff,mem_restrict,mem_ofPaths,List.not_mem_nil,iff_false]; grind theorem retain_subset_iff_restrict_empty (a b c : PathSpace) : - Included (retain a b) c ↔ Same (restrict b (diff a c)) [] := by - simp only [Included,Same,mem_retain,mem_restrict,mem_diff,List.not_mem_nil,iff_false]; grind + Included (retain a b) c ↔ Same (restrict b (diff a c)) (ofPaths []) := by + simp only [Included,Same,mem_retain,mem_restrict,mem_diff,mem_ofPaths,List.not_mem_nil,iff_false]; grind theorem restrict_subset_iff_retain_empty (a b c : PathSpace) : - Included (restrict a b) c ↔ Same (retain b (diff a c)) [] := by - simp only [Included,Same,mem_retain,mem_restrict,mem_diff,List.not_mem_nil,iff_false]; grind + Included (restrict a b) c ↔ Same (retain b (diff a c)) (ofPaths []) := by + simp only [Included,Same,mem_retain,mem_restrict,mem_diff,mem_ofPaths,List.not_mem_nil,iff_false]; grind theorem retain_restrict_source (a b c : PathSpace) : Same (retain (restrict a b) c) (restrict (retain a c) b) := by @@ -118,7 +120,7 @@ theorem retain_raffinate_source (a b c : PathSpace) : theorem restrict_union_left (a b c : PathSpace) : Same (restrict (union a b) c) (union (restrict a c) (restrict b c)) := by - intro p; simp only [mem_restrict,union,List.mem_append]; grind + intro p; simp only [mem_restrict,mem_union]; grind theorem restrict_inter_left (a b c : PathSpace) : Same (restrict (inter a b) c) (inter (restrict a c) (restrict b c)) := by @@ -130,7 +132,7 @@ theorem restrict_diff_left (a b c : PathSpace) : theorem restrict_union_right (a b c : PathSpace) : Same (restrict a (union b c)) (union (restrict a b) (restrict a c)) := by - intro p; simp only [mem_restrict,union,List.mem_append]; grind + intro p; simp only [mem_restrict,mem_union]; grind theorem restrict_filter_comm (a b c : PathSpace) : Same (restrict (restrict a b) c) (restrict (restrict a c) b) := by @@ -155,12 +157,12 @@ theorem retain_divergence_masks (a b c : PathSpace) : (retain a (union (divergence b c) (union (retain b c) (retain c b)))) := by intro p; rw [retain_lcp_masks] apply retain_congr (fun _ => Iff.rfl) _ p - intro q; simp only [lcp_correction,union,List.mem_append] + intro q; simp only [lcp_correction,mem_union] /-- Restriction composes masks by the longer of comparable witnesses. -/ theorem restrict_overlap_masks (a b c : PathSpace) : Same (restrict (restrict a b) c) (restrict a (union (restrict b c) (restrict c b))) := by - intro p; simp only [mem_restrict,union,List.mem_append]; constructor + intro p; simp only [mem_restrict,mem_union]; constructor · rintro ⟨⟨hp,q,hq,hqp⟩,r,hr,hrp⟩ rcases Path.prefixes_comparable hqp hrp with hqr | hrq · exact ⟨hp,r,Or.inr ⟨hr,q,hq,hqr⟩,hrp⟩ @@ -173,7 +175,7 @@ theorem restrict_overlap_masks (a b c : PathSpace) : theorem retain_restrict_mask (a b c : PathSpace) : Same (retain a (restrict b c)) (union (restrict (retain a b) c) (retain a (retain c b))) := by - intro p; simp only [mem_retain,mem_restrict,union,List.mem_append]; constructor + intro p; simp only [mem_retain,mem_restrict,mem_union]; constructor · rintro ⟨hp,q,⟨hq,r,hr,hrq⟩,hpq⟩ rcases Path.prefixes_comparable hpq hrq with hpr | hrp · exact Or.inr ⟨hp,r,⟨hr,q,hq,hrq⟩,hpr⟩ @@ -227,7 +229,6 @@ theorem branches_retain_bound (a b : PathSpace) : Included (branches (retain a b)) (inter (branches a) (branches b)) := divergence_retain_bound a a b b - theorem retain_covered_mask {b c : PathSpace} (h : covers b c = true) (a : PathSpace) : Included (retain a b) (retain a c) := by intro p hp; obtain ⟨hp,q,hq,hpq⟩ := (mem_retain _ _ _).mp hp @@ -246,14 +247,14 @@ theorem hull_mutual_covers {b c : PathSpace} (h : covers b c = true) (k : covers Same (hull b) (hull c) := by have hb : Same (hull (union b c)) (hull b) := by apply hull_cofinal - · intro p hp; exact List.mem_append_left _ hp - · intro p hp; rcases List.mem_append.mp hp with hp | hp + · intro p hp; exact mem_union_left _ hp + · intro p hp; rcases (mem_union _ _ _).mp hp with hp | hp · exact ⟨p,hp,Path.prefix_self p⟩ · exact (covers_iff c b).mp k p hp have hc : Same (hull (union b c)) (hull c) := by apply hull_cofinal - · intro p hp; exact List.mem_append_right _ hp - · intro p hp; rcases List.mem_append.mp hp with hp | hp + · intro p hp; exact mem_union_right _ hp + · intro p hp; rcases (mem_union _ _ _).mp hp with hp | hp · exact (covers_iff b c).mp h p hp · exact ⟨p,hp,Path.prefix_self p⟩ exact fun p => (hb p).symm.trans (hc p) @@ -270,7 +271,7 @@ theorem retain_mask_equiv (b c : PathSpace) : ((retain_congr (fun _ => Iff.rfl) h p).trans (retain_hull_mask a c p)) theorem retain_completion_mask (a b : PathSpace) : Same (retain a (completion b)) (retain a b) := by - intro p; simp only [mem_retain,completion,union,List.mem_append]; constructor + intro p; simp only [mem_retain,completion,mem_union]; constructor · rintro ⟨hp,q,hq | hq,hpq⟩ · exact ⟨hp,q,hq,hpq⟩ · obtain ⟨r,hr,hqr⟩ := divergence_output_covered hq @@ -281,7 +282,7 @@ theorem retain_antichain_inter {a b : PathSpace} (h : Antichain (union a b)) : Same (retain a b) (inter a b) := by intro p; rw [mem_retain,mem_inter]; constructor · rintro ⟨hp,q,hq,hpq⟩ - have he := h p (List.mem_append_left _ hp) q (List.mem_append_right _ hq) hpq + have he := h p (mem_union_left _ hp) q (mem_union_right _ hq) hpq exact ⟨hp,he ▸ hq⟩ · rintro ⟨hp,hq⟩; exact ⟨hp,p,hq,Path.prefix_self p⟩ @@ -337,14 +338,14 @@ theorem restrict_mask_equiv (b c : PathSpace) : have hcb := (restrict_mask_order c b).mp (fun a p hp => (h a p).mpr hp) have hb : Same (basis (union b c)) (basis b) := by apply basis_coinitial - · intro p hp; exact List.mem_append_left _ hp - · intro p hp; rcases List.mem_append.mp hp with hp | hp + · intro p hp; exact mem_union_left _ hp + · intro p hp; rcases (mem_union _ _ _).mp hp with hp | hp · exact ⟨p,hp,Path.prefix_self p⟩ · exact hcb p hp have hc : Same (basis (union b c)) (basis c) := by apply basis_coinitial - · intro p hp; exact List.mem_append_right _ hp - · intro p hp; rcases List.mem_append.mp hp with hp | hp + · intro p hp; exact mem_union_right _ hp + · intro p hp; rcases (mem_union _ _ _).mp hp with hp | hp · exact hbc p hp · exact ⟨p,hp,Path.prefix_self p⟩ exact fun p => (hb p).symm.trans (hc p) @@ -352,4 +353,4 @@ theorem restrict_mask_equiv (b c : PathSpace) : rw [← restriction_basis_mask a b,← restriction_basis_mask a c] simp only [mem_restrict,h] -end PathMapModel.PathSpace +end PrunedModel.Convex diff --git a/lean/PrunedModel/Convex/RetainChecks.lean b/lean/PrunedModel/Convex/RetainChecks.lean new file mode 100644 index 00000000..4e90f012 --- /dev/null +++ b/lean/PrunedModel/Convex/RetainChecks.lean @@ -0,0 +1,41 @@ +import PrunedModel.Convex.RetainConvex + +/-! Kernel-checked examples and counterexamples delimit the unconditional laws. -/ +namespace PrunedModel.Convex +open PathMapModel + +theorem retain_function_example : + restrict (ofPaths [[1,1],[2,4],[3,9],[4,16],[5,25]]) (ofPaths [[0],[2],[4],[6]]) = (ofPaths [[2,4],[4,16]]) ∧ + retain (ofPaths [[0],[2],[4],[6]]) (ofPaths [[1,1],[2,4],[3,9],[4,16],[5,25]]) = (ofPaths [[2],[4]]) := by decide + +theorem retain_not_commutative : + equiv (retain (ofPaths [[0]]) (ofPaths [[0,1]])) (retain (ofPaths [[0,1]]) (ofPaths [[0]])) = false := by decide + +theorem retain_not_associative : + equiv (retain (retain (ofPaths [[]]) (ofPaths [[0]])) (ofPaths [[]])) (retain (ofPaths [[]]) (retain (ofPaths [[0]]) (ofPaths [[]]))) = false := by decide + +theorem retain_not_mask_intersection : + equiv (retain (ofPaths [[]]) (inter (ofPaths [[0]]) (ofPaths [[1]]))) (inter (retain (ofPaths [[]]) (ofPaths [[0]])) (retain (ofPaths [[]]) (ofPaths [[1]]))) = false := by decide + +theorem retain_not_mask_difference : + equiv (retain (ofPaths [[]]) (diff (ofPaths [[0]]) (ofPaths [[1]]))) (diff (retain (ofPaths [[]]) (ofPaths [[0]])) (retain (ofPaths [[]]) (ofPaths [[1]]))) = false := by decide + +theorem retain_not_hull_source : + equiv (hull (retain (ofPaths [[],[0]]) (ofPaths [[]]))) (retain (hull (ofPaths [[],[0]])) (ofPaths [[]])) = false := by decide + +theorem retain_not_basis_mask : + equiv (retain (ofPaths [[0]]) (ofPaths [[],[0]])) (retain (ofPaths [[0]]) (basis (ofPaths [[],[0]]))) = false := by decide + +theorem retain_not_convexMeet_commutation : + equiv (retain (convexMeet (ofPaths [[],[0]]) (ofPaths [[],[0]])) (ofPaths [[]])) + (convexMeet (retain (ofPaths [[],[0]]) (ofPaths [[]])) (ofPaths [[],[0]])) = false := by decide + +theorem retain_divergence_bound_strict : + equiv (branches (retain (ofPaths [[0,0],[1,0]]) (ofPaths [[0,1],[1,1]]))) + (inter (branches (ofPaths [[0,0],[1,0]])) (branches (ofPaths [[0,1],[1,1]]))) = false := by decide + +theorem retain_product_needs_prefix_code : + equiv (retain (product (ofPaths [[],[0]]) (ofPaths [[1]])) (product (ofPaths [[],[0]]) (ofPaths [[0,1]]))) + (product (ofPaths [[],[0]]) (retain (ofPaths [[1]]) (ofPaths [[0,1]]))) = false := by decide + +end PrunedModel.Convex diff --git a/lean/PathMapModel/RetainConvex.lean b/lean/PrunedModel/Convex/RetainConvex.lean similarity index 83% rename from lean/PathMapModel/RetainConvex.lean rename to lean/PrunedModel/Convex/RetainConvex.lean index 18710271..83a77c0e 100644 --- a/lean/PathMapModel/RetainConvex.lean +++ b/lean/PrunedModel/Convex/RetainConvex.lean @@ -1,6 +1,7 @@ -import PathMapModel.Retain +import PrunedModel.Convex.Retain -namespace PathMapModel.PathSpace +namespace PrunedModel.Convex +open PathMapModel /-- Restriction commutes with convex meet when applied to both inputs. -/ theorem restrict_convexMeet (a b c : PathSpace) : @@ -54,16 +55,4 @@ theorem convexMeet_retained_mask (a b : PathSpace) : theorem convexSubtract_retained_mask (a b : PathSpace) : Same (convexSubtract a b) (retain a (diff (hull a) b)) := fun _ => Iff.rfl -end PathMapModel.PathSpace - -namespace PathMapModel.Map - -theorem retain_support {V W : Type} (a : PathMap V) (b : PathMap W) : - PathSpace.Same (PathSpace.ofMap (retain a b)) (PathSpace.retain (PathSpace.ofMap a) (PathSpace.ofMap b)) := by - intro p - change p ∈ PathSpace.ofMap (selectConvexSupport a (PathSpace.retain (PathSpace.ofMap a) (PathSpace.ofMap b))) ↔ _ - rw [selectConvexSupport_keys]; constructor - · exact And.right - · intro h; exact ⟨PathSpace.retain_subset _ _ p h,h⟩ - -end PathMapModel.Map +end PrunedModel.Convex diff --git a/lean/PrunedModel/Convex/Space.lean b/lean/PrunedModel/Convex/Space.lean new file mode 100644 index 00000000..434fe194 --- /dev/null +++ b/lean/PrunedModel/Convex/Space.lean @@ -0,0 +1,106 @@ +import PrunedModel.Zippy + +/-! Convex algebra extends the existing canonical pruned model. Ordinary set +operations are Zippy's zipper programs; only the additional geometry is new. -/ +namespace PrunedModel +open PathMapModel + +abbrev PathSpace := Zippy.Space + +namespace Convex +attribute [simp] Zippy.not_mem_empty + +/-- Finite set literals use the pruned model's canonical constructor. -/ +def ofPaths (ps : List Path) : PathSpace := PrunedMap.mk' (ps.map (·, ())) +instance : Coe (List Path) PathSpace := ⟨ofPaths⟩ +instance : Append PathSpace := ⟨Zippy.union⟩ + +@[simp] theorem mem_ofPaths (ps : List Path) (p : Path) : p ∈ ofPaths ps ↔ p ∈ ps := by + change ((PrunedMap.mk' _).valAt p).isSome = true ↔ _ + rw [PrunedMap.valAt, PrunedMap.mk', lookup_normVals] + constructor + · intro h + have := mem_keys_of_lookup_isSome h + simpa using this + · intro h + apply lookup_isSome_of_mem_keys + simpa using h + +@[simp] theorem mem_keys (a : PathSpace) (p : Path) : p ∈ a.keys ↔ p ∈ a := Zippy.mem_keys + +@[simp] theorem ofPaths_keys (a : PathSpace) : ofPaths a.keys = a := by + apply Zippy.ext; intro p; simp + +abbrev union := Zippy.union +abbrev inter := Zippy.inter +abbrev diff := Zippy.subtr +abbrev product := Zippy.composition +abbrev wrap := Zippy.wrap +abbrev unwrap := Zippy.unwrap +abbrev restrict := Zippy.restriction +abbrev raffinate := Zippy.raffination +abbrev head := Zippy.head +abbrev tails := Zippy.tailsUnion + +def subset (a b : PathSpace) : Bool := a.keys.all (fun p => decide (p ∈ b)) +def equiv (a b : PathSpace) : Bool := decide (a = b) +def symDiff (a b : PathSpace) : PathSpace := union (diff a b) (diff b a) + +@[simp] theorem mem_union (a b : PathSpace) (p : Path) : + p ∈ union a b ↔ p ∈ a ∨ p ∈ b := Zippy.mem_union +theorem mem_union_left (b : PathSpace) {a : PathSpace} {p : Path} (h : p ∈ a) : p ∈ union a b := + (mem_union a b p).mpr (Or.inl h) +theorem mem_union_right (a : PathSpace) {b : PathSpace} {p : Path} (h : p ∈ b) : p ∈ union a b := + (mem_union a b p).mpr (Or.inr h) + +@[simp] theorem mem_inter (a b : PathSpace) (p : Path) : + p ∈ inter a b ↔ p ∈ a ∧ p ∈ b := Zippy.mem_inter +@[simp] theorem mem_diff (a b : PathSpace) (p : Path) : + p ∈ diff a b ↔ p ∈ a ∧ p ∉ b := Zippy.mem_subtr +@[simp] theorem mem_append (a b : PathSpace) (p : Path) : + p ∈ a ++ b ↔ p ∈ a ∨ p ∈ b := Zippy.mem_union + +theorem eq_empty_iff (a : PathSpace) : a = ofPaths [] ↔ ∀ p, p ∉ a := by + constructor + · rintro rfl; simp + · intro h; apply Zippy.ext; intro p; simp [h p] + +theorem ne_empty_iff (a : PathSpace) : a ≠ ofPaths [] ↔ ∃ p, p ∈ a := by + classical + rw [ne_eq, eq_empty_iff] + grind + +theorem ofPaths_nil : ofPaths [] = Zippy.empty := by + apply Zippy.ext; intro p; simp [Zippy.not_mem_empty] + +@[simp] theorem append_eq_union (a b : PathSpace) : a ++ b = union a b := rfl + +theorem ofPaths_cons (p : Path) (ps : List Path) : + ofPaths (p :: ps) = union [p] (ofPaths ps) := by + apply Zippy.ext; intro q; simp + +@[simp] theorem keys_eq_nil_iff (a : PathSpace) : a.keys = [] ↔ a = ofPaths [] := by + rw [List.eq_nil_iff_forall_not_mem, eq_empty_iff] + simp + +theorem keys_nodup (a : PathSpace) : a.keys.Nodup := by + have go : ∀ xs : List (Path × Unit), DistinctKeys xs → (xs.map Prod.fst).Nodup := by + intro xs + induction xs with + | nil => simp + | cons x xs ih => + rintro ⟨hx, hxs⟩ + exact List.nodup_cons.mpr ⟨hx, ih hxs⟩ + exact go a.entries (distinctKeys_of_sortedKeys a.sorted) + +/-- Induction through the canonical map's finite key enumeration. -/ +@[elab_as_elim] theorem space_induction {motive : PathSpace → Prop} (a : PathSpace) + (nil : motive (ofPaths [])) (cons : ∀ (p : Path) a, motive a → motive (union [p] a)) : motive a := by + rw [← ofPaths_keys a] + generalize a.keys = ps + induction ps with + | nil => exact nil + | cons p ps ih => rw [ofPaths_cons]; exact cons p _ ih + +end Convex +end PrunedModel diff --git a/lean/PathMapModel/ConvexUnion.lean b/lean/PrunedModel/Convex/Union.lean similarity index 53% rename from lean/PathMapModel/ConvexUnion.lean rename to lean/PrunedModel/Convex/Union.lean index c7d66aea..48d32e49 100644 --- a/lean/PathMapModel/ConvexUnion.lean +++ b/lean/PrunedModel/Convex/Union.lean @@ -1,6 +1,7 @@ -import PathMapModel.ConvexMorphisms +import PrunedModel.Convex.Morphisms -namespace PathMapModel.PathSpace +namespace PrunedModel.Convex +open PathMapModel theorem hull_in_subset {a b : PathSpace} (h : Included a b) {p : Path} (hp : p ∈ a) (ht : p ∈ hull b) : p ∈ hull a := by @@ -8,27 +9,27 @@ theorem hull_in_subset {a b : PathSpace} (h : Included a b) {p : Path} (hp : p theorem hull_union_cases {a b : PathSpace} {p : Path} (h : p ∈ hull (union a b)) : p ∈ hull a ∨ p ∈ hull b := by - rcases List.mem_append.mp (hull_subset _ h) with ha | hb - · exact Or.inl (hull_in_subset (fun _ hq => List.mem_append_left _ hq) ha h) - · exact Or.inr (hull_in_subset (fun _ hq => List.mem_append_right _ hq) hb h) + rcases (mem_union _ _ _).mp (hull_subset _ h) with ha | hb + · exact Or.inl (hull_in_subset (fun _ hq => mem_union_left _ hq) ha h) + · exact Or.inr (hull_in_subset (fun _ hq => mem_union_right _ hq) hb h) theorem convexMeet_union_subset (a : PathSpace) {b c : PathSpace} (hb : IsPrefixClosed b) (hc : IsPrefixClosed c) : Included (convexMeet a (union b c)) (union (convexMeet a b) (convexMeet a c)) := by intro p hp; obtain ⟨ha,_,t,hta,ht,hpt⟩ := (mem_convexMeet _ _ _).mp hp rcases hull_union_cases ht with htb | htc - · exact List.mem_append_left _ ((mem_convexMeet _ _ _).mpr ⟨ha,hb t (hull_subset _ htb) p hpt,t,hta,htb,hpt⟩) - · exact List.mem_append_right _ ((mem_convexMeet _ _ _).mpr ⟨ha,hc t (hull_subset _ htc) p hpt,t,hta,htc,hpt⟩) + · exact mem_union_left _ ((mem_convexMeet _ _ _).mpr ⟨ha,hb t (hull_subset _ htb) p hpt,t,hta,htb,hpt⟩) + · exact mem_union_right _ ((mem_convexMeet _ _ _).mpr ⟨ha,hc t (hull_subset _ htc) p hpt,t,hta,htc,hpt⟩) theorem convexMeet_union (a : PathSpace) {b c : PathSpace} (hb : IsPrefixClosed b) (hc : IsPrefixClosed c) (h : Antichain (union (hull b) (hull c))) : Same (convexMeet a (union b c)) (union (convexMeet a b) (convexMeet a c)) := by intro p; refine ⟨convexMeet_union_subset a hb hc p,?_⟩ - intro hp; rcases List.mem_append.mp hp with hp | hp + intro hp; rcases (mem_union _ _ _).mp hp with hp | hp · obtain ⟨ha,hb,t,hta,htb,hpt⟩ := (mem_convexMeet _ _ _).mp hp - exact (mem_convexMeet _ _ _).mpr ⟨ha,List.mem_append_left _ hb,t,hta,(hull_union_compatible h t).mpr (List.mem_append_left _ htb),hpt⟩ + exact (mem_convexMeet _ _ _).mpr ⟨ha,mem_union_left _ hb,t,hta,(hull_union_compatible h t).mpr (mem_union_left _ htb),hpt⟩ · obtain ⟨ha,hc,t,hta,htc,hpt⟩ := (mem_convexMeet _ _ _).mp hp - exact (mem_convexMeet _ _ _).mpr ⟨ha,List.mem_append_right _ hc,t,hta,(hull_union_compatible h t).mpr (List.mem_append_right _ htc),hpt⟩ + exact (mem_convexMeet _ _ _).mpr ⟨ha,mem_union_right _ hc,t,hta,(hull_union_compatible h t).mpr (mem_union_right _ htc),hpt⟩ theorem convexSubtract_union_source {a b c : PathSpace} (ha : IsPrefixClosed a) (hb : IsPrefixClosed b) (hc : IsPrefixClosed c) : @@ -36,17 +37,17 @@ theorem convexSubtract_union_source {a b c : PathSpace} intro p; constructor · intro hp; obtain ⟨_,t,ht,hn,hpt⟩ := (mem_convexSubtract _ _ _).mp hp rcases hull_union_cases ht with hta | htb - · exact List.mem_append_left _ ((mem_convexSubtract _ _ _).mpr ⟨ha t (hull_subset _ hta) p hpt,t,hta,hn,hpt⟩) - · exact List.mem_append_right _ ((mem_convexSubtract _ _ _).mpr ⟨hb t (hull_subset _ htb) p hpt,t,htb,hn,hpt⟩) + · exact mem_union_left _ ((mem_convexSubtract _ _ _).mpr ⟨ha t (hull_subset _ hta) p hpt,t,hta,hn,hpt⟩) + · exact mem_union_right _ ((mem_convexSubtract _ _ _).mpr ⟨hb t (hull_subset _ htb) p hpt,t,htb,hn,hpt⟩) · have lift : ∀ t ∈ union a b, t ∉ c → ∃ r ∈ hull (union a b), r ∉ c ∧ (t ≼ r) = true := by intro t ht hn; obtain ⟨r,hr,htr⟩ := hull_covers ht exact ⟨r,hr,fun hrc => hn (hc r hrc t htr),htr⟩ - intro hp; rcases List.mem_append.mp hp with hp | hp + intro hp; rcases (mem_union _ _ _).mp hp with hp | hp · obtain ⟨hp,t,ht,hn,hpt⟩ := (mem_convexSubtract _ _ _).mp hp - obtain ⟨r,hr,hrn,htr⟩ := lift t (List.mem_append_left _ (hull_subset _ ht)) hn - exact (mem_convexSubtract _ _ _).mpr ⟨List.mem_append_left _ hp,r,hr,hrn,Path.prefix_trans hpt htr⟩ + obtain ⟨r,hr,hrn,htr⟩ := lift t (mem_union_left _ (hull_subset _ ht)) hn + exact (mem_convexSubtract _ _ _).mpr ⟨mem_union_left _ hp,r,hr,hrn,Path.prefix_trans hpt htr⟩ · obtain ⟨hp,t,ht,hn,hpt⟩ := (mem_convexSubtract _ _ _).mp hp - obtain ⟨r,hr,hrn,htr⟩ := lift t (List.mem_append_right _ (hull_subset _ ht)) hn - exact (mem_convexSubtract _ _ _).mpr ⟨List.mem_append_right _ hp,r,hr,hrn,Path.prefix_trans hpt htr⟩ + obtain ⟨r,hr,hrn,htr⟩ := lift t (mem_union_right _ (hull_subset _ ht)) hn + exact (mem_convexSubtract _ _ _).mpr ⟨mem_union_right _ hp,r,hr,hrn,Path.prefix_trans hpt htr⟩ -end PathMapModel.PathSpace +end PrunedModel.Convex diff --git a/tests/support/path_set_laws.rs b/tests/support/path_set_laws.rs index 8aa1c5b2..74528ad2 100644 --- a/tests/support/path_set_laws.rs +++ b/tests/support/path_set_laws.rs @@ -946,7 +946,7 @@ fn seeded_full_path_set_law_catalogue() { power_laws(&mut t, &map_from_set(&balanced)); // Ensure every catalogue name is executed, with guarded laws counted only // when the guard is true. New Lean laws automatically require Rust coverage. - let catalog = include_str!("../../lean/PathMapModel/PathSetLaws.lean"); + let catalog = include_str!("../../lean/PrunedModel/Convex/PathSetLaws.lean"); let expected: BTreeSet<_> = catalog .lines() .filter_map(|line| { From 9ddacbe343f60c03121467840ff618517c595725 Mon Sep 17 00:00:00 2001 From: adamv-symbolica Date: Thu, 19 Nov 2026 12:10:28 +0000 Subject: [PATCH 11/15] Identify known fuzzer panics by stable site IDs Tag the five allowlisted panic sites and classify their explicit identifiers instead of source coordinates. Preserve value-type and phase boundaries, and keep untagged panics unexpected with locations for diagnosis. Add regression coverage for location shifts and unknown sites, and run the unit tests in the algebraic CI gate. --- .github/workflows/ci.yml | 2 +- differential/ALGEBRAIC_FUZZING.md | 2 +- differential/src/algebraic.rs | 115 ++++++++++++++++++++++-------- src/dense_byte_node.rs | 4 +- src/line_list_node.rs | 10 ++- src/trie_node.rs | 2 +- 6 files changed, 98 insertions(+), 37 deletions(-) diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index a9d4be49..959c6592 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -351,7 +351,7 @@ jobs: rustc --version && cargo --version - name: harness gate # recogniser invariants, a short sweep, and route coverage; no corpus in CI - run: cargo test --release -p differential --test algebraic + run: cargo test --release -p differential --lib --test algebraic - name: sweep (release) if: ${{ !cancelled() }} env: diff --git a/differential/ALGEBRAIC_FUZZING.md b/differential/ALGEBRAIC_FUZZING.md index 36a2b6bd..64982ea5 100644 --- a/differential/ALGEBRAIC_FUZZING.md +++ b/differential/ALGEBRAIC_FUZZING.md @@ -219,7 +219,7 @@ by value type -- bits is lawful, u64 is not: law:join-distributes-over-meet 2077 1 law:meet-distributes-over-join 1603 - law:sym-diff-is-join-minus-meet 6684 5 - panic:build:line_list_node.rs:1745 13476 13476 + panic:build:line_list_node.replace_child.missing_child 13476 13476 values:model 1258 2 values:pw1 30849 36071 ... diff --git a/differential/src/algebraic.rs b/differential/src/algebraic.rs index b4512b47..d9d1604d 100644 --- a/differential/src/algebraic.rs +++ b/differential/src/algebraic.rs @@ -787,10 +787,10 @@ pub const KNOWN: &[Known] = &[ // baseline join or meet that consumes it is what then goes wrong. Known { signature: "u64:values:subtract_zipper", cause: BIAS_OR_LOSS }, Known { signature: "u64:shape:subtract_zipper", cause: DANGLING }, - Known { signature: "u64:panic:build:line_list_node.rs:1785", cause: MERKLEIZE }, - Known { signature: "u64:panic:eval:line_list_node.rs:2732", cause: LOSS }, - Known { signature: "u64:panic:eval:line_list_node.rs:2783", cause: LOSS }, - Known { signature: "u64:panic:eval:dense_byte_node.rs:2088", cause: LOSS }, + Known { signature: "u64:panic:build:line_list_node.replace_child.missing_child", cause: MERKLEIZE }, + Known { signature: "u64:panic:eval:line_list_node.pjoin_dense.empty_result", cause: LOSS }, + Known { signature: "u64:panic:eval:line_list_node.join_into_dense.empty_result", cause: LOSS }, + Known { signature: "u64:panic:eval:cofree.combine_results.invalid_rec_identity", cause: LOSS }, // ---------------------------------------------------------------- bits // The lawful type. Everything here is a real defect: there is no value @@ -824,10 +824,10 @@ pub const KNOWN: &[Known] = &[ // operand's value (the debug assert behind cause 2 fires). Known { signature: "bits:values:subtract_zipper", cause: LOSS }, Known { signature: "bits:shape:subtract_zipper", cause: DANGLING }, - Known { signature: "bits:panic:build:line_list_node.rs:1785", cause: MERKLEIZE }, - Known { signature: "bits:panic:eval:line_list_node.rs:2732", cause: LOSS }, - Known { signature: "bits:panic:eval:line_list_node.rs:2783", cause: LOSS }, - Known { signature: "bits:panic:eval:dense_byte_node.rs:2088", cause: LOSS }, + Known { signature: "bits:panic:build:line_list_node.replace_child.missing_child", cause: MERKLEIZE }, + Known { signature: "bits:panic:eval:line_list_node.pjoin_dense.empty_result", cause: LOSS }, + Known { signature: "bits:panic:eval:line_list_node.join_into_dense.empty_result", cause: LOSS }, + Known { signature: "bits:panic:eval:cofree.combine_results.invalid_rec_identity", cause: LOSS }, // ---------------------------------------------------------------- unit // `PathMap<()>`: the set case, and lawful. Nothing here can be a value // bias, because there is no value to misplace -- so every entry is either a @@ -853,12 +853,12 @@ pub const KNOWN: &[Known] = &[ Known { signature: "unit:shape:dnf", cause: DANGLING }, Known { signature: "unit:values:subtract_zipper", cause: LOSS }, Known { signature: "unit:shape:subtract_zipper", cause: DANGLING }, - Known { signature: "unit:panic:build:line_list_node.rs:1785", cause: MERKLEIZE }, - Known { signature: "unit:panic:eval:line_list_node.rs:2732", cause: LOSS }, - Known { signature: "unit:panic:eval:dense_byte_node.rs:2088", cause: LOSS }, + Known { signature: "unit:panic:build:line_list_node.replace_child.missing_child", cause: MERKLEIZE }, + Known { signature: "unit:panic:eval:line_list_node.pjoin_dense.empty_result", cause: LOSS }, + Known { signature: "unit:panic:eval:cofree.combine_results.invalid_rec_identity", cause: LOSS }, // Fires roughly once per million random cases, and the corpus reproduces it // for all three types. - Known { signature: "unit:panic:eval:line_list_node.rs:2783", cause: LOSS }, + Known { signature: "unit:panic:eval:line_list_node.join_into_dense.empty_result", cause: LOSS }, Known { signature: "unit:values:ternary", cause: LOSS }, // ---------------------------------------------------------------- Zippy @@ -914,9 +914,9 @@ pub const KNOWN: &[Known] = &[ Known { signature: "unit:shape:pw5+zippy", cause: DANGLING }, Known { signature: "unit:shape:subtract_zipper+zippy", cause: DANGLING }, // `unwrap`'s take_map strategy feeding `wrap`'s insert_prefix one. - Known { signature: "u64:panic:eval:trie_node.rs:3247", cause: TAKE_MAP }, - Known { signature: "bits:panic:eval:trie_node.rs:3247", cause: TAKE_MAP }, - Known { signature: "unit:panic:eval:trie_node.rs:3247", cause: TAKE_MAP }, + Known { signature: "u64:panic:eval:trie_node.make_unique.empty_sentinel", cause: TAKE_MAP }, + Known { signature: "bits:panic:eval:trie_node.make_unique.empty_sentinel", cause: TAKE_MAP }, + Known { signature: "unit:panic:eval:trie_node.make_unique.empty_sentinel", cause: TAKE_MAP }, // The laws from `Zippy.lean` that fail, all of them under `PathMap::join` // losing a value: every shrunk case is `x | y` with `y` sharing nodes with // `x` (a clone, or a join result that reuses `x`'s nodes) or carrying @@ -994,10 +994,8 @@ pub enum Outcome { } std::thread_local! { - /// Where the last panic came from. The payload of an `unwrap` on `None` - /// carries no location, and the location is the whole value of a crash - /// signature -- without it every distinct panic site collapses onto one - /// line called "panic". A hook is the only way to see it. + /// The explicit panic-site identifier, or a diagnostic location for an + /// untagged panic. Only explicit identifiers belong in the known table. static PANIC_SITE: core::cell::RefCell = const { core::cell::RefCell::new(String::new()) }; /// The input [`run_all`] is checking, so a panic that aborts the process @@ -1006,6 +1004,28 @@ std::thread_local! { const { core::cell::RefCell::new(Vec::new()) }; } +/// An explicit marker identifies an assertion independently of checkout paths, +/// line shifts, and compiler-generated assertion text. Untagged panics keep +/// their location for diagnosis, but never match an allowlisted panic site. +fn panic_site(message: &str, location: Option<&std::panic::Location<'_>>) -> String { + if let Some((_, tagged)) = message.split_once("[pathmap-panic:") { + if let Some((id, _)) = tagged.split_once(']') { + if !id.is_empty() + && id.bytes().all(|b| b.is_ascii_lowercase() || b.is_ascii_digit() || b"._".contains(&b)) + { + return id.to_owned(); + } + } + } + match location { + Some(l) => { + let file = l.file().rsplit(['/', '\\']).next().unwrap_or(l.file()); + format!("unidentified:{file}:{}:{}", l.line(), l.column()) + } + None => "unidentified".to_owned(), + } +} + /// Replace the panic hook with one that records the panic site and prints /// nothing. /// @@ -1014,23 +1034,14 @@ std::thread_local! { /// cannot see where the panic came from. pub fn install_panic_hook() { std::panic::set_hook(Box::new(|info| { - let site = info - .location() - .map(|l| { - // Just the file name and line: the absolute path would make - // signatures depend on where the checkout lives. - let f = l.file(); - let f = f.rsplit('/').next().unwrap_or(f); - format!("{f}:{}", l.line()) - }) - .unwrap_or_else(|| "?".to_string()); + let msg = info.payload_as_str().unwrap_or(""); + let site = panic_site(msg, info.location()); // A panic that cannot unwind aborts the whole process, so it can never // become a finding; say what and where before the abort, or the run just // dies with "thread caused non-unwinding panic". Stable Rust cannot ask // `info` whether it unwinds, so match std's messages for the three cases: // a debug-mode unsafe-precondition check, a panic in a destructor during // unwinding, and a panic in a function that cannot unwind. - let msg = info.payload_as_str().unwrap_or(""); if msg.starts_with("unsafe precondition") || msg.starts_with("panic in a destructor") || msg.starts_with("panic in a function that cannot unwind") @@ -1233,3 +1244,47 @@ pub fn operand_values(case: &Case) -> Vec> { .map(|m| shape::values_of_shape(&shape_of_map(m))) .collect() } + +#[cfg(test)] +mod panic_site_tests { + use super::{known, panic_signature, panic_site, Phase}; + + #[track_caller] + fn site(message: &str) -> String { + panic_site(message, Some(std::panic::Location::caller())) + } + + #[test] + fn identified_panics_survive_location_and_wrapper_changes() { + let a = site("[pathmap-panic:line_list_node.replace_child.missing_child] missing child"); + let b = site("internal error: entered unreachable code: [pathmap-panic:line_list_node.replace_child.missing_child] changed detail"); + assert_eq!(a, b); + assert!(known(&panic_signature("u64", Phase::Build, &a)).is_some()); + assert!(known(&panic_signature("u64", Phase::Eval, &a)).is_none()); + assert!(known(&panic_signature("other_type", Phase::Build, &a)).is_none()); + } + + #[test] + fn untagged_panics_stay_distinct_and_unexpected() { + let a = site("called `Option::unwrap()` on a `None` value"); + let b = site("called `Option::unwrap()` on a `None` value"); + assert_ne!(a, b); + for id in [a, b, site("[pathmap-panic:new_site] missing child")] { + assert!(known(&panic_signature("u64", Phase::Build, &id)).is_none()); + } + for message in ["[pathmap-panic:]", "[pathmap-panic:unfinished", "[pathmap-panic:bad:id]"] { + assert!(site(message).starts_with("unidentified:")); + } + } + + #[test] + fn panic_allowlist_uses_only_explicit_identifiers() { + for known in super::KNOWN { + if let Some((_, suffix)) = known.signature.split_once(":panic:") { + let (_, id) = suffix.split_once(':').expect("panic phase and site"); + assert!(!id.contains(':'), "location in allowlist: {}", known.signature); + assert!(!id.starts_with("unidentified")); + } + } + } +} diff --git a/src/dense_byte_node.rs b/src/dense_byte_node.rs index 129dfec5..daaf7c65 100644 --- a/src/dense_byte_node.rs +++ b/src/dense_byte_node.rs @@ -2131,7 +2131,9 @@ impl, OtherCf: CoFree match arg_idx { 0 => self.rec().cloned(), 1 => other.rec().cloned(), - _ => unreachable!() + _ => unreachable!( + "[pathmap-panic:cofree.combine_results.invalid_rec_identity] unexpected identity operand {arg_idx}" + ) } }); let val = val_el.flatten().map_into_option(|arg_idx| { diff --git a/src/line_list_node.rs b/src/line_list_node.rs index a04f2866..b07bd512 100644 --- a/src/line_list_node.rs +++ b/src/line_list_node.rs @@ -1801,7 +1801,9 @@ impl TrieNode for LineListNode self.get_child_mut(key) } fn node_replace_child(&mut self, key: &[u8], new_node: TrieNodeODRc) { - let (consumed_bytes, child_node) = self.get_child_mut(key).unwrap(); + let (consumed_bytes, child_node) = self.get_child_mut(key).expect( + "[pathmap-panic:line_list_node.replace_child.missing_child] missing child while replacing node" + ); debug_assert!(consumed_bytes == key.len()); *child_node = new_node; } @@ -2748,7 +2750,8 @@ impl TrieNode for LineListNode match new_node.merge_from_list_node(self) { //Both nodes were empty so the join is empty too AlgebraicStatus::None => { - debug_assert!(self.node_is_empty() && other_dense_node.node_is_empty()); + debug_assert!(self.node_is_empty() && other_dense_node.node_is_empty(), + "[pathmap-panic:line_list_node.pjoin_dense.empty_result] join returned empty for nonempty operands"); AlgebraicResult::None }, AlgebraicStatus::Identity => AlgebraicResult::Identity(COUNTER_IDENT), @@ -2799,7 +2802,8 @@ impl TrieNode for LineListNode let other_dense_node = unsafe{ other_node.as_dense_unchecked() }; let mut new_node = other_dense_node.clone(); let status = new_node.merge_from_list_node(self); - debug_assert!(!status.is_none()); + debug_assert!(!status.is_none(), + "[pathmap-panic:line_list_node.join_into_dense.empty_result] join returned empty"); (AlgebraicStatus::Element, Err(TrieNodeODRc::new_in(new_node, self.alloc.clone()))) }, #[cfg(feature = "bridge_nodes")] diff --git a/src/trie_node.rs b/src/trie_node.rs index 19b7031b..7a074825 100644 --- a/src/trie_node.rs +++ b/src/trie_node.rs @@ -3244,7 +3244,7 @@ mod opaque_dyn_rc_trie_node { #[inline] pub(crate) fn make_unique(&mut self) { // Empty nodes are sentinels and cannot be made unique/mutable - assert!(!self.is_empty(), "Attempted to make_unique on an empty sentinel node"); + assert!(!self.is_empty(), "[pathmap-panic:trie_node.make_unique.empty_sentinel] Attempted to make_unique on an empty sentinel node"); let (ptr, _tag) = self.ptr.get_raw_parts(); From 6c720122c84d41904e31c3a4eba9d8ae4a7b174d Mon Sep 17 00:00:00 2001 From: adamv-symbolica Date: Thu, 19 Nov 2026 12:56:46 +0000 Subject: [PATCH 12/15] Exercise convex and path-set operators in both fuzzers --- .github/workflows/ci.yml | 8 +- differential/ALGEBRAIC_FUZZING.md | 8 +- differential/src/algebraic.rs | 91 +++++-- differential/src/algebraic/expr.rs | 36 ++- differential/src/algebraic/model.rs | 51 ++++ differential/src/algebraic/routes.rs | 57 ++++- differential/src/algebraic/value.rs | 4 +- differential/src/harness.rs | 100 +++++++- differential/src/repro.rs | 15 ++ differential/tests/algebraic.rs | 93 ++++++- lean/PathMapModel/Check.lean | 19 ++ lean/PathMapModel/Fuzz.lean | 23 +- lean/PrunedModel/Convex/Mixed.lean | 18 +- lean/differential.py | 10 +- lean/input_format.py | 2 +- lean/test_input_format.py | 10 +- src/experimental/convex/native.rs | 319 +++++++++++++++++++++++- src/experimental/convex/native/tests.rs | 316 ----------------------- 18 files changed, 808 insertions(+), 372 deletions(-) delete mode 100644 src/experimental/convex/native/tests.rs diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index 959c6592..b1e1e6c1 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -225,7 +225,7 @@ jobs: # Regression check: head and base run on identical inputs; an input on which head diverges # from the model but base did not is reported as a warning annotation (master has known # divergences). Set FUZZ_STRICT=1 below to make that fail the job instead. - # Focused convex programs have no known-bug exemptions: every divergence fails. + # Focused convex and path-set programs have no known-bug exemptions: every divergence fails. # Ordered after the tests but not gated on them: baseline findings are warnings, and a PR whose # tests fail is exactly one whose divergences are worth seeing. needs: test @@ -275,7 +275,7 @@ jobs: run: | cargo test --release -p differential --lib --target-dir "$CARGO_TARGET_DIR/fuzz-head" python3 -m unittest discover -s lean -p 'test_input_format.py' - - name: convex programs against Lean + - name: convex and path-set programs against Lean shell: bash env: PATHMAP_TRACE: ${{ env.CARGO_TARGET_DIR }}/fuzz-head/release/pathmap_trace @@ -288,11 +288,11 @@ jobs: convex_status=$? fi { - printf '\n## Convex programs\n\n' + printf '\n## Convex and path-set programs\n\n' tail -n 1 "${{ runner.temp }}/fuzz-out/fuzz-convex-head.txt" } >> "${{ runner.temp }}/fuzz-out/summary.md" if [ "$convex_status" -ne 0 ]; then - printf 'Convex program check failed\n' >> "${{ runner.temp }}/fuzz-out/findings" + printf 'Convex and path-set program check failed\n' >> "${{ runner.temp }}/fuzz-out/findings" fi exit "$convex_status" - name: comment on the PR diff --git a/differential/ALGEBRAIC_FUZZING.md b/differential/ALGEBRAIC_FUZZING.md index 64982ea5..68ca0d63 100644 --- a/differential/ALGEBRAIC_FUZZING.md +++ b/differential/ALGEBRAIC_FUZZING.md @@ -320,15 +320,17 @@ An input is the wire header, then the bytes `decode` reads: It is laid out like the main harness's (`harness::WIRE_MAGIC`, then a selector count) and the pruned harness's (`PMPRUN`, then its count), with this fuzzer's own marker. Where those two record how many operations their table had, this -records a *layout version* (`algebraic::LAYOUT`, now 1): its decoding has no +records a *layout version* (`algebraic::LAYOUT`, now 2): its decoding has no single table, so it is the version that says which decoding the payload was written for. Bump it, and keep the old decoding reachable, when a change to `decode` would give an existing input a different case. The header is optional. An input without one is layout 1, so every input written before it existed decodes as it did; a cut-short header decodes as an empty -payload. `Rng::input` writes the header in front of the same random stream as -before, so a seed still names the same cases. `--shrink` reduces only the +payload. Layout 2 adds convex meet/subtract, basis, hull, retain, divergence +and branches; layout 1 retains its original operator tables. `Rng::input` +writes the current layout, so replaying older seeds requires their original +layout header. `--shrink` reduces only the payload and writes the result with a header, so a legacy input comes out headered and decodes the same way. diff --git a/differential/src/algebraic.rs b/differential/src/algebraic.rs index d9d1604d..b3211385 100644 --- a/differential/src/algebraic.rs +++ b/differential/src/algebraic.rs @@ -65,7 +65,7 @@ pub const ALG_MAGIC: &[u8] = b"PMALGZ\x01\x00"; /// Layout version of newly generated inputs. Bump it, and keep the old /// decoding reachable, when a change to [`decode`] would give an existing /// input a different case. -pub const LAYOUT: u16 = 1; +pub const LAYOUT: u16 = 2; /// Layout of an input with no header: every input written before the header /// existed. It is the layout [`LAYOUT`] 1 decodes. pub const LEGACY_LAYOUT: u16 = 1; @@ -102,15 +102,15 @@ pub struct Gen<'a> { /// Size of the path alphabet. A small one makes operands share prefixes /// and collide; the full 256 exercises wide nodes. alphabet: u16, + layout: u16, } impl<'a> Gen<'a> { - /// A cursor over the input after its header. Layout 1 is the only - /// decoding there is, so the version is not consulted yet; a newer one - /// decodes as layout 1. + /// Layout 1 preserves the original operator tables; layout 2 adds convex + /// and path-set expressions. Unknown later versions use the latest layout. pub fn new(bytes: &'a [u8]) -> Self { - let (_layout, payload) = split_input(bytes); - Gen { bytes: payload, pos: 0, alphabet: 3 } + let (layout, payload) = split_input(bytes); + Gen { bytes: payload, pos: 0, alphabet: 3, layout } } pub fn byte(&mut self) -> u8 { let b = self.bytes.get(self.pos).copied().unwrap_or(0); @@ -253,7 +253,7 @@ fn gen_ctx(g: &mut Gen, paths: &[Vec], depth: usize) -> Ctx { }; match g.modn(8) { 0..=3 => { - let op = Op::ALL[g.modn(Op::ALL.len())]; + let op = Op::ALL[g.modn(if g.layout < 2 { 7 } else { Op::ALL.len() })]; let e = gen_expr(g, 1); let c = Box::new(gen_ctx(g, paths, depth - 1)); if g.boolean() { Ctx::Right(op, e, c) } else { Ctx::Left(op, c, e) } @@ -267,7 +267,7 @@ fn gen_ctx(g: &mut Gen, paths: &[Vec], depth: usize) -> Ctx { Ctx::Unwrap(Box::new(gen_ctx(g, paths, depth - 1)), p) } _ => { - let u = Un::ALL[g.modn(Un::ALL.len())]; + let u = Un::ALL[g.modn(if g.layout < 2 { 3 } else { Un::ALL.len() })]; Ctx::Un(u, Box::new(gen_ctx(g, paths, depth - 1))) } } @@ -383,11 +383,10 @@ fn gen_expr(g: &mut Gen, depth: usize) -> Expr { _ => Expr::Var(g.modn(OPERANDS)), }; } - // The crate's own algebra keeps three quarters of the interior nodes, so - // the chain and DNF recognisers still fire often; Zippy's operators take - // the rest. Their paths are short, because a long one rarely meets - // anything in tries this small. - let op = match g.modn(16) { + // Keep the original algebra weighted heavily enough for chain and DNF + // routes. Layout 2 appends convex/path-set operators to the binary table + // and extends the unary table. Short paths encourage prefix collisions. + let op = match g.modn(if g.layout < 2 { 16 } else { 20 }) { 0 | 1 | 2 | 3 => Op::Join, 4 | 5 | 6 => Op::Meet, 7 | 8 => Op::Subtract, @@ -399,12 +398,16 @@ fn gen_expr(g: &mut Gen, depth: usize) -> Expr { return Expr::unwrap(e, g.path(2)); } 14 => { - let u = Un::ALL[g.modn(Un::ALL.len())]; + let u = Un::ALL[g.modn(if g.layout < 2 { 3 } else { Un::ALL.len() })]; return Expr::un(u, gen_expr(g, depth - 1)); } - _ => { + 15 => { if g.boolean() { Op::Compose } else { Op::IterC } } + 16 => Op::ConvexMeet, + 17 => Op::ConvexSubtract, + 18 => Op::Retain, + _ => Op::Divergence, }; Expr::bin(op, gen_expr(g, depth - 1), gen_expr(g, depth - 1)) } @@ -527,10 +530,65 @@ pub fn check(case: &Case) -> Vec { } } + out.extend(check_path_sets(case)); out.extend(check_laws(case)); out } +/// Check each new kernel against the flat semantics of its actual inputs. +/// Whole-expression failures can inherit a known join/meet defect. These local +/// signatures ensure that exemptions for those defects cannot mask a path-set +/// regression, even when a faulty old operation produced one of its operands. +fn check_path_sets(case: &Case) -> Vec { + fn collect<'a>(e: &'a Expr, nodes: &mut Vec<(&'a Expr, &'static str)>) { + match e { + Expr::Bin(op, l, r) => { + collect(l, nodes); + collect(r, nodes); + if matches!(op, Op::ConvexMeet | Op::ConvexSubtract | Op::Retain | Op::Divergence) { + nodes.push((e, op.sym())); + } + } + Expr::Un(u, child) => { + collect(child, nodes); + if matches!(u, Un::Basis | Un::Hull | Un::Branches) { nodes.push((e, u.name())); } + } + Expr::Wrap(_, child) | Expr::Unwrap(child, _) => collect(child, nodes), + _ => {} + } + } + let mut nodes = Vec::new(); + collect(&case.expr, &mut nodes); + let mut out = Vec::new(); + for (e, name) in nodes { + // Each new operator has two strategies: map and zipper. + for k in 0..2 { + let eval = |e: &Expr| routes::eval(Route::Pointwise(k), e, &case.operands) + .filter(|o| !o.truncated()).map(|o| o.values); + let expected = match e { + Expr::Bin(op, l, r) => { + let (Some(l), Some(r)) = (eval(l), eval(r)) else { continue }; + model::apply(*op, &l, &r) + } + Expr::Un(u, child) => { + let Some(child) = eval(child) else { continue }; + model::unary(*u, &child) + } + _ => unreachable!(), + }; + let Some(actual) = eval(e) else { continue }; + if actual != expected { + out.push(Divergence { + class: Class::Values, + signature: signature::("values", &format!("path_set/{name}/pw{k}")), + detail: format!("{e}, route {k}: {}", shape::first_values_diff(&actual, &expected).unwrap()), + }); + } + } + } + out +} + /// Evaluate each law's two sides and report the ones that disagree. /// /// Laws run through the baseline route only. A law that fails under one route @@ -1188,8 +1246,7 @@ impl Rng { /// would saturate the rest to zeros and waste the draw -- and short enough /// to shrink quickly. /// A random input: the current header, then the bytes [`decode`] reads. - /// The bytes after the header are the stream this produced before the - /// header existed, so a seed still names the same cases. + /// The header fixes the operator layout used to replay the byte stream. pub fn input(&mut self) -> Vec { let n = 48 + (self.next() % 96) as usize; let mut v = input_header(); diff --git a/differential/src/algebraic/expr.rs b/differential/src/algebraic/expr.rs index e2a3452f..bc24db96 100644 --- a/differential/src/algebraic/expr.rs +++ b/differential/src/algebraic/expr.rs @@ -4,8 +4,8 @@ //! deliberately small: the point is not to cover a rich language but to give //! each expression as many *distinct implementation routes* as possible, and a //! route only exists where the crate offers one. So the operator set is -//! exactly the crate's algebra -- join, meet, subtract, symmetric difference, -//! restrict -- and the interesting structure is the shape of the tree, because +//! the crate's algebra, convex meet/subtract and the valued path-set operators. +//! The interesting structure is the shape of the tree, because //! that is what decides which routes apply: //! //! * any tree at all can be walked bottom-up with two-operand calls, so the @@ -55,11 +55,16 @@ pub enum Op { /// Zippy's `IterC src b`: `b` if `src` has a value below its root, else /// nothing. IterC, + ConvexMeet, + ConvexSubtract, + Retain, + Divergence, } impl Op { - pub const ALL: [Op; 7] = - [Op::Join, Op::Meet, Op::Subtract, Op::SymDiff, Op::Restrict, Op::Compose, Op::IterC]; + pub const ALL: [Op; 11] = + [Op::Join, Op::Meet, Op::Subtract, Op::SymDiff, Op::Restrict, Op::Compose, Op::IterC, + Op::ConvexMeet, Op::ConvexSubtract, Op::Retain, Op::Divergence]; pub fn sym(self) -> &'static str { match self { @@ -70,6 +75,10 @@ impl Op { Op::Restrict => "/", Op::Compose => ".", Op::IterC => "iter_c", + Op::ConvexMeet => "convex_meet", + Op::ConvexSubtract => "convex_subtract", + Op::Retain => "retain", + Op::Divergence => "divergence", } } @@ -107,7 +116,7 @@ impl Op { } } -/// Zippy's one-operand operators that take no path. +/// Unary space and path-set operators that take no path. #[derive(Clone, Copy, PartialEq, Eq, Debug)] pub enum Un { /// `Head s`: the first byte of every path, as one-byte paths. @@ -116,16 +125,22 @@ pub enum Un { TailsUnion, /// `TailsIntersection s`: their intersection; nothing when there are none. TailsInter, + Basis, + Hull, + Branches, } impl Un { - pub const ALL: [Un; 3] = [Un::Head, Un::TailsUnion, Un::TailsInter]; + pub const ALL: [Un; 6] = [Un::Head, Un::TailsUnion, Un::TailsInter, Un::Basis, Un::Hull, Un::Branches]; pub fn name(self) -> &'static str { match self { Un::Head => "head", Un::TailsUnion => "tails_union", Un::TailsInter => "tails_inter", + Un::Basis => "basis", + Un::Hull => "hull", + Un::Branches => "branches", } } } @@ -141,7 +156,7 @@ pub enum Kind { } impl Kind { - pub const ALL: [Kind; 13] = [ + pub const ALL: [Kind; 20] = [ Kind::Op(Op::Join), Kind::Op(Op::Meet), Kind::Op(Op::Subtract), @@ -149,12 +164,19 @@ impl Kind { Kind::Op(Op::Restrict), Kind::Op(Op::Compose), Kind::Op(Op::IterC), + Kind::Op(Op::ConvexMeet), + Kind::Op(Op::ConvexSubtract), + Kind::Op(Op::Retain), + Kind::Op(Op::Divergence), Kind::Singleton, Kind::Wrap, Kind::Unwrap, Kind::Un(Un::Head), Kind::Un(Un::TailsUnion), Kind::Un(Un::TailsInter), + Kind::Un(Un::Basis), + Kind::Un(Un::Hull), + Kind::Un(Un::Branches), ]; pub fn sym(self) -> &'static str { diff --git a/differential/src/algebraic/model.rs b/differential/src/algebraic/model.rs index c0c9f349..44a73d03 100644 --- a/differential/src/algebraic/model.rs +++ b/differential/src/algebraic/model.rs @@ -52,6 +52,9 @@ pub fn unary(u: Un, a: &Values) -> Values { Un::Head => head(a), Un::TailsUnion => tails_union(a), Un::TailsInter => tails_inter(a), + Un::Basis => basis(a), + Un::Hull => hull(a), + Un::Branches => divergence(a, a), } } @@ -64,6 +67,10 @@ pub fn apply(op: Op, a: &Values, b: &Values) -> Values { Op::Restrict => restrict(a, b), Op::Compose => compose(a, b), Op::IterC => iter_c(a, b), + Op::Retain => retain(a, b), + Op::Divergence => divergence(a, b), + Op::ConvexMeet => convex_meet(a, b), + Op::ConvexSubtract => convex_subtract(a, b), } } @@ -186,3 +193,47 @@ pub fn compose(s: &Values, t: &Values) -> Values { pub fn iter_c(src: &Values, b: &Values) -> Values { if src.keys().any(|k| !k.is_empty()) { b.clone() } else { Values::new() } } + +// Path-set operations inspect valued keys and preserve selected left payloads. +// These deliberately use flat key comparisons, independent of the trie walks. +pub fn basis(a: &Values) -> Values { + a.iter().filter(|(p, _)| !a.keys().any(|q| q.len() < p.len() && p.starts_with(q))) + .map(|(p, v)| (p.clone(), v.clone())).collect() +} + +pub fn hull(a: &Values) -> Values { + a.iter().filter(|(p, _)| !a.keys().any(|q| p.len() < q.len() && q.starts_with(p.as_slice()))) + .map(|(p, v)| (p.clone(), v.clone())).collect() +} + +pub fn retain(a: &Values, b: &Values) -> Values { + a.iter().filter(|(p, _)| b.keys().any(|q| q.starts_with(p.as_slice()))) + .map(|(p, v)| (p.clone(), v.clone())).collect() +} + +pub fn divergence(a: &Values, b: &Values) -> Values { + let mut out = Values::new(); + for p in a.keys() { + for q in b.keys() { + let n = p.iter().zip(q).take_while(|(x, y)| x == y).count(); + if n < p.len() && n < q.len() { + out.insert(p[..n].to_vec(), V::canonical()); + } + } + } + out +} + +pub fn convex_meet(a: &Values, b: &Values) -> Values { + let common: Values = a.iter().filter(|(p, _)| b.contains_key(*p)) + .map(|(p, v)| (p.clone(), v.clone())).collect(); + let ah = hull(a); + let bh = hull(b); + let tips = ah.into_iter().filter(|(p, _)| bh.contains_key(p)).collect(); + retain(&common, &tips) +} + +pub fn convex_subtract(a: &Values, b: &Values) -> Values { + let tips = hull(a).into_iter().filter(|(p, _)| !b.contains_key(p)).collect(); + retain(a, &tips) +} diff --git a/differential/src/algebraic/routes.rs b/differential/src/algebraic/routes.rs index e0b25403..b70f521c 100644 --- a/differential/src/algebraic/routes.rs +++ b/differential/src/algebraic/routes.rs @@ -25,6 +25,7 @@ //! and why dangling-path divergence is reported separately. use pathmap::PathMap; +use pathmap::experimental::{convex, path_sets}; use pathmap::experimental::zipper_algebra::{ Clause, zipper_join, zipper_join3, zipper_meet, zipper_meet3, zipper_merge_dnf, zipper_n_join, zipper_n_meet, zipper_n_subtract, zipper_n_sym_diff, zipper_subtract, @@ -50,6 +51,7 @@ pub const SUBTRACT_STRATEGIES: &[&str] = &["map", "subtract_into", "zipper_subtr pub const SYM_DIFF_STRATEGIES: &[&str] = &["zipper_sym_diff", "join_minus_meet"]; pub const RESTRICT_STRATEGIES: &[&str] = &["map", "wz_restrict"]; pub const COMPOSE_STRATEGIES: &[&str] = &["join_map_into", "wrap_join"]; +pub const PATH_SET_STRATEGIES: &[&str] = &["map", "zipper"]; pub const ITER_C_STRATEGIES: &[&str] = &["val_count", "iter"]; pub const SINGLETON_STRATEGIES: &[&str] = &["single", "set_val"]; pub const WRAP_STRATEGIES: &[&str] = &["graft_map", "prefix_zipper", "insert_prefix"]; @@ -77,6 +79,7 @@ pub fn strategies(op: Op) -> &'static [&'static str] { Op::Restrict => RESTRICT_STRATEGIES, Op::Compose => COMPOSE_STRATEGIES, Op::IterC => ITER_C_STRATEGIES, + Op::ConvexMeet | Op::ConvexSubtract | Op::Retain | Op::Divergence => PATH_SET_STRATEGIES, } } @@ -90,6 +93,7 @@ pub fn kind_strategies(kind: Kind) -> &'static [&'static str] { Kind::Un(Un::Head) => HEAD_STRATEGIES, Kind::Un(Un::TailsUnion) => TAILS_UNION_STRATEGIES, Kind::Un(Un::TailsInter) => TAILS_INTER_STRATEGIES, + Kind::Un(Un::Basis | Un::Hull | Un::Branches) => PATH_SET_STRATEGIES, } } @@ -429,10 +433,38 @@ pub fn apply(op: Op, k: usize, a: &PathMap, b: &PathMap) -> if below { b.clone() } else { PathMap::new() } } + (Op::ConvexMeet, 0) => convex::convex_meet(a, b), + (Op::ConvexSubtract, 0) => convex::convex_subtract(a, b), + (Op::Retain, 0) => path_sets::retain(a, b), + (Op::Divergence, 0) => marks(path_sets::divergence(a, b)), + (Op::ConvexMeet | Op::ConvexSubtract | Op::Retain, _) => { + let mut out = PathMap::new(); + let mut lz = a.read_zipper(); + let mut rz = b.read_zipper(); + let mut wz = out.write_zipper(); + match op { + Op::ConvexMeet => convex::zipper_convex_meet(&mut lz, &mut rz, &mut wz), + Op::ConvexSubtract => convex::zipper_convex_subtract(&mut lz, &mut rz, &mut wz), + _ => path_sets::zipper_retain(&mut lz, &mut rz, &mut wz), + } + drop(wz); + out + } + (Op::Divergence, _) => { + let mut out = PathMap::new(); + path_sets::zipper_divergence(&mut a.read_zipper(), &mut b.read_zipper(), &mut out.write_zipper()); + marks(out) + } + _ => unreachable!("strategy index out of range for {op:?}"), }) } +/// Lift unit-valued branch points into the expression's payload type. +fn marks(map: PathMap<()>) -> PathMap { + map.iter().map(|(p, ())| (p, V::canonical())).collect() +} + // ---------------------------------------------------------------- Zippy /// `Singleton p`, carrying [`FuzzValue::canonical`]. @@ -527,6 +559,25 @@ fn heads(k: usize, s: &PathMap) -> Vec { fn unary(u: Un, k: usize, s: &PathMap) -> PathMap { match u { + Un::Basis | Un::Hull => { + if k % 2 == 0 { + return if u == Un::Basis { path_sets::basis(s) } else { path_sets::hull(s) }; + } + let mut out = PathMap::new(); + if u == Un::Basis { + path_sets::zipper_basis(&mut s.read_zipper(), &mut out.write_zipper()); + } else { + path_sets::zipper_hull(&mut s.read_zipper(), &mut out.write_zipper()); + } + out + } + Un::Branches => { + if k % 2 == 0 { return marks(path_sets::branches(s)); } + let mut out = PathMap::new(); + path_sets::zipper_branches(&mut s.read_zipper(), &mut out.write_zipper()); + marks(out) + } + Un::Head => { let hs = heads(k % HEAD_STRATEGIES.len(), s); let mut out = PathMap::new(); @@ -685,7 +736,7 @@ fn ternary(e: &Expr, operands: &[PathMap]) -> Option Op::Meet => zipper_meet3(&mut za, &mut zb, &mut zc, &mut wz), Op::Subtract => zipper_subtract3(&mut za, &mut zb, &mut zc, &mut wz), Op::SymDiff => zipper_sym_diff3(&mut za, &mut zb, &mut zc, &mut wz), - Op::Restrict | Op::Compose | Op::IterC => return None, + _ => return None, } } Some(out) @@ -717,7 +768,7 @@ fn nary(e: &Expr, operands: &[PathMap], poly: bool) -> Option

zipper_n_meet(&mut zs, &mut wz), Op::Subtract => zipper_n_subtract(&mut zs, &mut wz), Op::SymDiff => zipper_n_sym_diff(&mut zs, &mut wz), - Op::Restrict | Op::Compose | Op::IterC => unreachable!(), + _ => unreachable!("operator has no n-ary route"), } }}; } @@ -729,7 +780,7 @@ fn nary(e: &Expr, operands: &[PathMap], poly: bool) -> Option

t.meet_n(&mut wz), Op::Subtract => t.subtract_n(&mut wz), Op::SymDiff => t.sym_diff_n(&mut wz), - Op::Restrict | Op::Compose | Op::IterC => unreachable!(), + _ => unreachable!("operator has no n-ary route"), } }}; } diff --git a/differential/src/algebraic/value.rs b/differential/src/algebraic/value.rs index b5661722..4937de45 100644 --- a/differential/src/algebraic/value.rs +++ b/differential/src/algebraic/value.rs @@ -81,8 +81,8 @@ pub trait FuzzValue: fn generate(g: &mut Gen) -> Self; - /// The value a constructed path carries: Zippy's `Singleton` and `Head` - /// make paths, not values, so they need one fixed value to put there. + /// The value a constructed path carries. Singleton, head, divergence and + /// branches create paths, so they need one fixed value to put there. fn canonical() -> Self; fn show(&self) -> String; diff --git a/differential/src/harness.rs b/differential/src/harness.rs index 43b48c2e..b228d8ee 100644 --- a/differential/src/harness.rs +++ b/differential/src/harness.rs @@ -18,6 +18,11 @@ use pathmap::ring::AlgebraicStatus; use pathmap::utils::ByteMask; use pathmap::zipper::*; +pub(crate) const PATH_SET_NAMES: [&str; 10] = [ + "basis", "hull", "retain", "divergence", "branches", + "zipper_basis", "zipper_hull", "zipper_retain", "zipper_divergence", "zipper_branches", +]; + // The trace is written into one growable buffer rather than a `Vec`. // It used to be ~260 separately allocated `String`s per input, thrown away as // soon as they were printed; only a divergence needs the individual lines, and @@ -26,7 +31,7 @@ use core::fmt::Write as _; /// Selector count for newly generated inputs. Keep in sync with `lean/input_format.py`. /// Keep operation IDs permanently assigned. -pub const NOPS: usize = 65; +pub const NOPS: usize = 75; /// Unversioned inputs retain their original operation decoding. pub const LEGACY_NOPS: usize = 56; /// Input header marker, followed by a little-endian u16 selector count (1..=256). @@ -272,6 +277,9 @@ pub trait ReadSource: None } + /// Binary path-set operations require a native read source, as convex ops do. + fn path_set(&mut self, _left: &PathMap, _op: usize) -> Option> { None } + fn do_graft>(&self, _wz: &mut W) -> bool { false } fn do_graft_masked>(&self, _wz: &mut W, _m: ByteMask, _ru: bool) -> bool { false } /// Currently unused: op 54 is quarantined (lean/FINDINGS.md #15). Kept so @@ -307,6 +315,25 @@ impl<'a, 'p> ReadSource for ReadZipperUntracked<'a, 'p, u64> { }) } + fn path_set(&mut self, left: &PathMap, op: usize) -> Option> { + use pathmap::experimental::path_sets::*; + Some(match op { + 67 => retain(left, &self.make_map()), + 68 => divergence(left, &self.make_map()).iter().map(|(p, ())| (p, 1)).collect(), + 72 => { + let mut out = PathMap::new(); + zipper_retain(&mut left.read_zipper(), self, &mut out.write_zipper()); + out + } + 73 => { + let mut out = PathMap::new(); + zipper_divergence(&mut left.read_zipper(), self, &mut out.write_zipper()); + out.iter().map(|(p, ())| (p, 1)).collect() + } + _ => unreachable!("not a binary path-set operation"), + }) + } + fn dump_fork(&self) -> String { dump_fork(self) } @@ -1005,7 +1032,7 @@ pub fn run_ops( let ret = if let Some(result) = rz.convex(&wz.make_map(), op % 2 == 0, op >= 63) { // Convex algebra specifies values, not bare structure. // Rebuild the result's valued projection before grafting, - // matching Map.selectConvexSupport in the Lean model. + // matching the pruned Lean model. // Do not truncate: subsequent ops observe the entire map. let canonical: PathMap = result.iter().map(|(p, v)| (p, *v)).collect(); wz.graft_map(canonical); @@ -1015,6 +1042,37 @@ pub fn run_ops( }; (name, ret.to_string()) } + 65..=74 => { + use pathmap::experimental::path_sets::*; + let left = wz.make_map(); + let result = match op { + 65 => Some(basis(&left)), + 66 => Some(hull(&left)), + 69 => Some(branches(&left).iter().map(|(p, ())| (p, 1)).collect()), + 70 | 71 => { + let mut out = PathMap::new(); + if op == 70 { + zipper_basis(&mut left.read_zipper(), &mut out.write_zipper()); + } else { + zipper_hull(&mut left.read_zipper(), &mut out.write_zipper()); + } + Some(out) + } + 74 => { + let mut out = PathMap::new(); + zipper_branches(&mut left.read_zipper(), &mut out.write_zipper()); + Some(out.iter().map(|(p, ())| (p, 1)).collect()) + } + _ => rz.path_set(&left, op), + }; + let ret = if let Some(result) = result { + // The pruned model observes valued paths only. Branch + // points carry 1 in this homogeneous u64 interpreter. + wz.graft_map(result.iter().map(|(p, v)| (p, *v)).collect()); + "-" + } else { SKIP_ACT }; + (PATH_SET_NAMES[op - 65], ret.to_string()) + } 47 => { let t = get!(d.modn(2)); // The blind-zipper addition: `descend_until` reporting the @@ -1061,7 +1119,7 @@ mod input_format_tests { #[test] fn input_header_count_controls_decoding_independently_of_current_operation_count() { - for count in [1u16, 32, 56, 57, 58, 61, 65, 256] { + for count in [1u16, 32, 56, 57, 58, 61, 65, 75, 256] { let mut bytes = WIRE_MAGIC.to_vec(); bytes.extend_from_slice(&count.to_le_bytes()); bytes.extend(0..=255); @@ -1168,6 +1226,42 @@ mod input_format_tests { } } + #[test] + fn path_set_programs_and_reproducers_preserve_the_wire_contract() { + for op in 65u8..75 { + let mut bytes = input_header(); + bytes.extend_from_slice(&[ + 4, 0, 10, 1, 0, 11, 2, 0, 1, 12, 2, 0, 2, 13, + 3, 0, 20, 1, 0, 21, 2, 0, 3, 22, 0, 0, + op, + ]); + let name = PATH_SET_NAMES[(op - 65) as usize]; + let expected = match (op - 65) % 5 { + 0 => "MAP0 _:10", + 1 => "MAP0 _:-,00:-,0001:12,0002:13", + 2 => "MAP0 _:10,00:11", + _ => "MAP0 _:-,00:1", + }; + let trace = run(&bytes, true); + assert!(trace.lines().any(|line| line == expected), "{name}: {trace}"); + assert!(trace.contains(&format!("0 {name} ret=-")), "{trace}"); + let act = run_act(&bytes, false); + if matches!((op - 65) % 5, 2 | 3) { + assert!(act.contains(&format!("0 {name} ret=skip:act")), "{act}"); + assert!(act.contains("MAP0 _:10,00:11,0001:12,0002:13"), "{act}"); + } else { + assert!(act.lines().any(|line| line == expected), "{act}"); + } + let repro = emit_repro(&bytes, 256); + assert!(repro.contains(&format!("::{name}(")), "{repro}"); + } + // Previously recorded 65-selector programs still decode 65 as op 0. + let mut old = WIRE_MAGIC.to_vec(); + old.extend_from_slice(&65u16.to_le_bytes()); + old.extend_from_slice(&[0, 0, 0, 0, 65, 0, 1, 2]); + assert!(run(&old, true).contains("0 descend_to ret=02")); + } + #[test] fn old_selector_count_does_not_decode_convex_operations() { let mut bytes = WIRE_MAGIC.to_vec(); diff --git a/differential/src/repro.rs b/differential/src/repro.rs index 57e3c87d..c0ca6571 100644 --- a/differential/src/repro.rs +++ b/differential/src/repro.rs @@ -230,6 +230,21 @@ pub fn emit_repro(bytes: &[u8], upto: usize) -> String { }; format!("{{ let left = wz.make_map(); {call} let canonical: PathMap = result.iter().map(|(p, v)| (p, *v)).collect(); wz.graft_map(canonical); }}") } + 65..=74 => { + let operation = crate::harness::PATH_SET_NAMES[op - 65]; + let binary = matches!(op, 67 | 68 | 72 | 73); + let marks = matches!(op, 68 | 69 | 73 | 74); + let call = if op >= 70 { + let rhs = if binary { "&mut rz, " } else { "" }; + format!("let mut result = PathMap::new(); pathmap::experimental::path_sets::{operation}(&mut left.read_zipper(), {rhs}&mut result.write_zipper());") + } else { + let rhs = if binary { ", &rz.make_map()" } else { "" }; + format!("let result = pathmap::experimental::path_sets::{operation}(&left{rhs});") + }; + let value = if marks { "1" } else { "*v" }; + let binding = if marks { "_" } else { "v" }; + format!("{{ let left = wz.make_map(); {call} let canonical: PathMap = result.iter().map(|(p, {binding})| (p, {value})).collect(); wz.graft_map(canonical); }}") + } _ => "// nop".to_string(), }; o.push_str(&format!(" /* {step:3} */ {line}\n")); diff --git a/differential/tests/algebraic.rs b/differential/tests/algebraic.rs index 866ddfa5..4be1f4bc 100644 --- a/differential/tests/algebraic.rs +++ b/differential/tests/algebraic.rs @@ -559,11 +559,10 @@ fn zippy_laws_apply_to_the_set_type_only() { assert!(algebraic::laws::laws::().is_empty()); } -/// The wire header: optional, and invisible to decoding. A headerless input is -/// layout 1, so it and the same bytes after a header are the same case; random -/// inputs carry the header, and seeds keep naming the cases they did before it. +/// Headerless and explicit layout-1 inputs keep their original decoding. +/// Newly generated inputs use layout 2, which adds the path-set operators. #[test] -fn input_header_does_not_change_the_case() { +fn legacy_input_layout_keeps_the_same_case() { // Building the operands can panic (the known merkleize defect); then both // forms must panic. Decode under the quiet hook, assert outside it. let shown = |b: &[u8]| { @@ -575,7 +574,13 @@ fn input_header_does_not_change_the_case() { let (pairs, cut_pair) = with_quiet_panics(|| { let pairs: Vec<_> = inputs .iter() - .map(|h| (shown(h), shown(algebraic::split_input(h).1))) + .map(|h| { + let payload = algebraic::split_input(h).1; + let mut old = algebraic::ALG_MAGIC.to_vec(); + old.extend_from_slice(&1u16.to_le_bytes()); + old.extend_from_slice(payload); + (shown(&old), shown(payload)) + }) .collect(); (pairs, (shown(&cut), shown(&[]))) }); @@ -594,3 +599,81 @@ fn input_header_does_not_change_the_case() { let main = differential::harness::input_header(); assert_eq!(algebraic::split_input(&main), (algebraic::LEGACY_LAYOUT, &main[..])); } + +#[test] +fn convex_and_path_set_routes_match_flat_semantics() { + use algebraic::{expr::Un, model, routes::{self, Route}, shape::Values}; + use pathmap::{PathMap, zipper::*}; + + // Endpoints do not branch; empty paths count as inclusive prefixes. + let a: Values = [(b"".to_vec(), 9), (b"foo".to_vec(), 10), + (b"food".to_vec(), 11), (b"four".to_vec(), 12)].into(); + let b: Values = [(b"foo".to_vec(), 20), (b"food".to_vec(), 21)].into(); + assert_eq!(model::basis(&a), [(vec![], 9)].into()); + assert_eq!(model::hull(&a), [(b"food".to_vec(), 11), (b"four".to_vec(), 12)].into()); + assert_eq!(model::retain(&a, &b), [(vec![], 9), (b"foo".to_vec(), 10), (b"food".to_vec(), 11)].into()); + assert_eq!(model::divergence(&a, &b), [(b"fo".to_vec(), 1)].into()); + assert!(model::divergence(&b, &b).is_empty()); + assert_eq!(model::convex_meet(&a, &b), [(b"foo".to_vec(), 10), (b"food".to_vec(), 11)].into()); + assert_eq!(model::convex_subtract(&a, &b), [(vec![], 9), (b"four".to_vec(), 12)].into()); + + fn check(maps: &[PathMap]) { + let expressions = [ + Expr::un(Un::Basis, Expr::Var(0)), Expr::un(Un::Hull, Expr::Var(0)), + Expr::un(Un::Branches, Expr::Var(0)), + Expr::bin(Op::Retain, Expr::Var(0), Expr::Var(1)), + Expr::bin(Op::Divergence, Expr::Var(0), Expr::Var(1)), + Expr::bin(Op::ConvexMeet, Expr::Var(0), Expr::Var(1)), + Expr::bin(Op::ConvexSubtract, Expr::Var(0), Expr::Var(1)), + ]; + for e in expressions { + let expected = routes::eval(Route::Model, &e, maps).unwrap().values; + for k in 0..routes::POINTWISE_ROUTES { + let actual = routes::eval(Route::Pointwise(k), &e, maps).unwrap().values; + assert_eq!(actual, expected, "{e}, route {k}"); + } + } + } + let maps: Vec> = [&a, &b].into_iter().map(|m| m.iter().map(|(p, v)| (p, *v)).collect()).collect(); + check(&maps); + // Exhaust every pair of small path sets, with unequal payloads and bare + // extensions. No known-finding exemptions apply to these comparisons. + let paths: &[&[u8]] = &[b"", b"a", b"ab", b"ac", b"b"]; + for left in 0..32 { + for right in 0..32 { + let maps: Vec> = [left, right].into_iter().enumerate().map(|(side, mask)| { + let mut m = PathMap::new(); + for (i, p) in paths.iter().enumerate() { + if mask & (1 << i) != 0 { m.set_val_at(p, (side * 10 + i + 1) as u64); } + } + let mut wz = m.write_zipper(); + wz.descend_to(b"abc"); + wz.create_path(); + drop(wz); + m + }).collect(); + check(&maps); + let sets: Vec> = maps.iter().map(|m| m.iter().map(|(p, _)| (p, ())).collect()).collect(); + check(&sets); + let bits: Vec> = maps.iter().map(|m| m.iter().map(|(p, v)| (p, Bits(*v))).collect()).collect(); + check(&bits); + } + } +} + +#[test] +fn current_layout_generates_every_expression_operator() { + let seen = with_quiet_panics(|| { + let mut rng = algebraic::Rng::for_job(7, 0); + let mut seen = Vec::new(); + for _ in 0..20_000 { + if let Ok(case) = std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| algebraic::decode::<()>(&rng.input()))) { + for kind in case.expr.kinds() { + if !seen.contains(&kind) { seen.push(kind); } + } + } + } + seen + }); + for kind in Kind::ALL { assert!(seen.contains(&kind), "never generated {kind:?}"); } +} diff --git a/lean/PathMapModel/Check.lean b/lean/PathMapModel/Check.lean index 288833d5..10c825a1 100644 --- a/lean/PathMapModel/Check.lean +++ b/lean/PathMapModel/Check.lean @@ -266,6 +266,25 @@ def convexProgram (op : UInt8) : ByteArray := ByteArray.mk <| (Fuzz.wireMagic ++ [61, 0, 0, 0, 0, 0, 61, 0, 1, 2]).toArray)).head!).startsWith "0 descend_to ret=02" +/-- The new selector range shares the pruned model and marks branch points with 1. -/ +def pathSetProgram (op : UInt8) : ByteArray := ByteArray.mk <| + (Fuzz.wireMagic ++ [75, 0, + 4, 0, 10, 1, 0, 11, 2, 0, 1, 12, 2, 0, 2, 13, + 3, 0, 20, 1, 0, 21, 2, 0, 3, 22, 0, 0, op]).toArray + +#guard [65, 70].all (fun op => (Fuzz.run (pathSetProgram op)).contains "MAP0 _:10") +#guard [66, 71].all (fun op => + (Fuzz.run (pathSetProgram op)).contains "MAP0 _:-,00:-,0001:12,0002:13") +#guard [67, 72].all (fun op => (Fuzz.run (pathSetProgram op)).contains "MAP0 _:10,00:11") +#guard [68, 69, 73, 74].all (fun op => (Fuzz.run (pathSetProgram op)).contains "MAP0 _:-,00:1") +#guard [67, 68, 72, 73].all (fun op => + (Fuzz.run (pathSetProgram op) 256 true).contains "MAP0 _:10,00:11,0001:12,0002:13") +#guard [65, 66, 69, 70, 71, 74].all (fun op => + Fuzz.run (pathSetProgram op) 256 true == Fuzz.run (pathSetProgram op)) +#guard ((Fuzz.run (ByteArray.mk + (Fuzz.wireMagic ++ [65, 0, 0, 0, 0, 0, 65, 0, 1, 2]).toArray)).head!).startsWith + "0 descend_to ret=02" + /-! ## Naive oracles `PathMap.join` / `meet` / `sub` are defined in terms of `ValOps`, which was diff --git a/lean/PathMapModel/Fuzz.lean b/lean/PathMapModel/Fuzz.lean index c0252b25..1860fe18 100644 --- a/lean/PathMapModel/Fuzz.lean +++ b/lean/PathMapModel/Fuzz.lean @@ -196,12 +196,16 @@ def showBool (b : Bool) : String := if b then "1" else "0" `op % selector_count` selects the operation (56 for headerless inputs). Ops `0`–`26` act on a target zipper chosen by a following `u8 % 2` byte (`0` = write zipper, -`1` = read zipper); ops `27`–`46`, `56`, and `60`–`64` write at the focus. +`1` = read zipper); ops `27`–`46`, `56`, and `60`–`74` write at the focus. Ops `61`/`62` apply native convex meet/subtract; `63`/`64` apply the zipper implementations. They take no operands and replace the write focus with the valued projection of the result, using the read focus as RHS. Bare result structure is unspecified by convex algebra, so both interpreters canonicalise -it before later operations observe it. ACT skips these four operations. -/ +it before later operations observe it. ACT skips these four operations. +Ops `65`–`69` apply basis, hull, retain, divergence and branches; `70`–`74` +apply their zipper forms. Unary operations read the write focus; binary ones +also read the read focus. Divergence and branches mark results with `1`. +ACT skips the binary path-set operations but supports the unary ones. -/ /-- Input header marker. Must match `WIRE_MAGIC` in the Rust harness. -/ def wireMagic : List UInt8 := [80, 77, 70, 85, 90, 90, 1, 0] @@ -560,6 +564,21 @@ def step (s : St) (d : Dec) : Option (St × Dec) := do let z := if op % 2 == 0 then s.wz.convexSubtract s.rz s.wz else s.wz.convexMeet s.rz s.wz some (emit { s with wz := z } name "-", d) + | 65 | 66 | 67 | 68 | 69 | 70 | 71 | 72 | 73 | 74 => do + let name := match op with + | 65 => "basis" | 66 => "hull" | 67 => "retain" + | 68 => "divergence" | 69 => "branches" + | 70 => "zipper_basis" | 71 => "zipper_hull" | 72 => "zipper_retain" + | 73 => "zipper_divergence" | _ => "zipper_branches" + let kind := (op - 65) % 5 + if s.act && (kind == 2 || kind == 3) then some (emit s name skipAct, d) else + let z := match kind with + | 0 => s.wz.basis s.wz + | 1 => s.wz.hull s.wz + | 2 => s.wz.retain s.rz s.wz + | 3 => s.wz.divergence s.rz s.wz 1 + | _ => s.wz.branches s.wz 1 + some (emit { s with wz := z } name "-", d) | _ => some (emit s "nop" "-", d) /-- Run operations until the input is exhausted or `fuel` runs out. -/ diff --git a/lean/PrunedModel/Convex/Mixed.lean b/lean/PrunedModel/Convex/Mixed.lean index 2f915f3d..364f30f1 100644 --- a/lean/PrunedModel/Convex/Mixed.lean +++ b/lean/PrunedModel/Convex/Mixed.lean @@ -1,7 +1,7 @@ import PrunedModel.Convex.Map import PathMapModel.Map -/-! The mixed fuzzer can contain dangling paths. Convex operations observe its +/-! The mixed fuzzer can contain dangling paths. Convex and path-set operations observe its valued projection in the pruned model, then graft the canonical result back. All operation definitions and laws live in the pruned model. -/ namespace PathMapModel @@ -18,5 +18,21 @@ def convexMeet {V W : Type} (a : Zip V) (b : Zip W) (out : Zip V) : Zip V := def convexSubtract {V W : Type} (a : Zip V) (b : Zip W) (out : Zip V) : Zip V := out.graftMap (mixed ((pruned a.makeMap).convexSubtract (pruned b.makeMap))) +def basis {V : Type} (a out : Zip V) : Zip V := + out.graftMap (mixed (pruned a.makeMap).basis) +def hull {V : Type} (a out : Zip V) : Zip V := + out.graftMap (mixed (pruned a.makeMap).hull) +def retain {V W : Type} (a : Zip V) (b : Zip W) (out : Zip V) : Zip V := + out.graftMap (mixed ((pruned a.makeMap).retain (pruned b.makeMap))) + +/-- Mark the pruned model's unit-valued branch points with a caller's payload. -/ +private def marks {V : Type} (a : PrunedModel.PrunedMap Unit) (v : V) : PathMap V := + PathMap.mk' (a.entries.map fun (p, _) => (p, v)) [] + +def divergence {V W : Type} (a : Zip V) (b : Zip W) (out : Zip V) (v : V) : Zip V := + out.graftMap (marks ((pruned a.makeMap).divergence (pruned b.makeMap)) v) +def branches {V : Type} (a out : Zip V) (v : V) : Zip V := + out.graftMap (marks (pruned a.makeMap).branches v) + end Zip end PathMapModel diff --git a/lean/differential.py b/lean/differential.py index d18e240e..2b129af4 100755 --- a/lean/differential.py +++ b/lean/differential.py @@ -501,7 +501,7 @@ def get(self, idx): class ConvexInputs(InputSource): """Stateful programs covering both kernels without unrelated known bugs. - All four convex selectors run in every program. Seeded shapes include + All convex and path-set selectors run in every program. Seeded shapes include shared chains, mismatched tips, root values and empty inputs; random shapes share a small path pool. Writes between operations restore values so an earlier empty result cannot make the rest of the program vacuous. @@ -525,6 +525,7 @@ def get(self, idx): ([(0,)], [(0,), (0, 1)]), ([], [()]), ([(), (0,)], []), + ([(0,), (0, 1), (0, 2)], [(0,), (0, 3)]), ] if idx % 8 < len(shapes): left, right = shapes[idx % 8] @@ -555,7 +556,10 @@ def path(p): for target, focus in ((0, focus0), (1, focus1)): blob.extend([18, target]) # move_to_path path(focus) - for op in (61, 63, 62, 64): + for op in (61, 63, 62, 64, *range(65, 75)): + # Restore exactly the same valued input, including after branches + # introduces keys that were absent from the original left map. + blob.extend([56, 0]) # remove_subtrie without moving the focus for p, v in left: blob.append(60) # set_val_at, relative to the current focus path(p) @@ -654,7 +658,7 @@ def main(): ap = argparse.ArgumentParser() ap.add_argument("files", nargs="*") ap.add_argument("--random", type=int, default=0, help="generate N random inputs") - ap.add_argument("--convex", type=int, default=0, help="generate N focused convex programs") + ap.add_argument("--convex", type=int, default=0, help="generate N focused convex and path-set programs") ap.add_argument("--selectors", type=int, default=NOPS, choices=range(1, NOPS + 1), metavar="N", help="selector count for random inputs (for baseline replay)") ap.add_argument("--strict", action="store_true", help="fail on known divergences too") diff --git a/lean/input_format.py b/lean/input_format.py index df9385d4..6b0fbef1 100644 --- a/lean/input_format.py +++ b/lean/input_format.py @@ -3,7 +3,7 @@ WIRE_MAGIC = b"PMFUZZ\x01\x00" LEGACY_NOPS = 56 # Keep in sync with NOPS in differential/src/harness.rs. -NOPS = 65 +NOPS = 75 HEADER_SIZE = len(WIRE_MAGIC) + 2 diff --git a/lean/test_input_format.py b/lean/test_input_format.py index c423bae2..32823934 100644 --- a/lean/test_input_format.py +++ b/lean/test_input_format.py @@ -28,7 +28,7 @@ def test_random_baseline_encoding_keeps_identical_payload(self): self.assertEqual(baseline.get(i)[:HEADER_SIZE], input_header(61)) self.assertEqual(current.get(i)[HEADER_SIZE:], baseline.get(i)[HEADER_SIZE:]) - def test_convex_programs_are_deterministic_and_cover_every_kernel(self): + def test_convex_and_path_set_programs_cover_every_kernel(self): source = ConvexInputs(7, 128) for i in range(len(source)): blob = source.get(i) @@ -64,11 +64,13 @@ def skip_path(): elif op == 60: skip_path() pos += 1 # value + elif op == 56: + pos += 1 # prune flag else: - self.assertIn(op, (29, 61, 62, 63, 64)) + self.assertIn(op, (29, *range(61, 75))) self.assertEqual(pos, len(blob)) self.assertLessEqual(len(ops), 256) - for op in range(61, 65): + for op in range(61, 75): self.assertEqual(ops.count(op), 2) self.assertNotEqual(source.get(7), ConvexInputs(8, 128).get(7)) @@ -77,7 +79,7 @@ def test_legacy_inputs_get_applicable_count(self): self.assertEqual(versioned_input(payload), input_header(56) + payload) def test_versioned_inputs_keep_recorded_count(self): - for count in [1, 56, 57, 58, 61, 65, 256]: + for count in [1, 56, 57, 58, 61, 65, 75, 256]: blob = input_header(count) + bytes(range(256)) self.assertEqual(versioned_input(blob), blob) diff --git a/src/experimental/convex/native.rs b/src/experimental/convex/native.rs index 02792406..9a68ba2a 100644 --- a/src/experimental/convex/native.rs +++ b/src/experimental/convex/native.rs @@ -782,4 +782,321 @@ where } #[cfg(test)] -mod tests; +mod tests { + use super::*; + use crate::alloc::{GlobalAlloc, global_alloc}; + use crate::dense_byte_node::{CellByteNode, DenseByteNode}; + use crate::trie_node::TrieNode; + use std::collections::{BTreeMap, BTreeSet}; + + type Node = TrieNodeODRc; + type Map = PathMap; + type Payload = ValOrChild; + const TAGS: [usize; 5] = [ + DENSE_BYTE_NODE_TAG, + CELL_BYTE_NODE_TAG, + LINE_LIST_NODE_TAG, + TINY_REF_NODE_TAG, + EMPTY_NODE_TAG, + ]; + + fn list(entries: Vec<(Vec, Payload)>) -> LineListNode { + let mut node = LineListNode::new_in(global_alloc()); + for (i, (key, payload)) in entries.into_iter().enumerate() { + // At most two entries, sorted by key with children before values. + unsafe { + match i { + 0 => node.set_payload_owned::<0>(&key, payload), + 1 => node.set_payload_owned::<1>(&key, payload), + _ => unreachable!(), + } + } + } + assert!(crate::line_list_node::validate_node(&node)); + node + } + fn child(side: u64) -> Node { + let mut m = Map::new(); + m.set_val_at(b"c", 30 + side); + m.set_val_at(if side == 0 { b"d" } else { b"e" }, 40 + side); + m.root().unwrap().clone() + } + fn entries(pattern: usize, side: u64) -> Vec<(Vec, Payload)> { + let v = |p: &[u8], n| (p.to_vec(), Payload::Val(n + 100 * side)); + let c = |p: &[u8], bare| { + ( + p.to_vec(), + Payload::Child(if bare { Node::new_empty() } else { child(side) }), + ) + }; + match pattern { + 0 => vec![v(b"ab", 1), v(b"b", 2)], + 1 => vec![v(b"a", 1), c(b"ab", false)], + 2 => vec![c(b"a", false), v(b"a", 1)], + 3 => vec![c(b"ab", true), v(b"b", 2)], + 4 => vec![v(b"a", 1), v(b"ab", 2)], + 5 => vec![c(b"a", true)], + 6 => vec![c(b"a", false), c(b"b", false)], + 7 => vec![v(b"ab", 1)], + _ => unreachable!(), + } + } + fn byte>( + entries: Vec<(Vec, Payload)>, + ) -> ByteNode { + let mut n = ByteNode::new_in(global_alloc()); + for (key, payload) in entries { + if key.len() == 1 { + n.set_payload_owned(key[0], payload); + } else { + n.set_child( + key[0], + Node::new_in(list(vec![(key[1..].to_vec(), payload)]), global_alloc()), + ); + } + } + n + } + // A Tiny is a real borrowed slice inside a list key, not a map that merely + // might choose a tiny representation. Empty is the actual sentinel. + fn fixture(tag: usize, pattern: usize, side: u64) -> (Node, Vec) { + let mut es = entries(pattern, side); + let (node, path) = match tag { + DENSE_BYTE_NODE_TAG => ( + Node::new_in( + byte::>(es), + global_alloc(), + ), + vec![], + ), + CELL_BYTE_NODE_TAG => ( + Node::new_in( + byte::>(es), + global_alloc(), + ), + vec![], + ), + LINE_LIST_NODE_TAG => (Node::new_in(list(es), global_alloc()), vec![]), + TINY_REF_NODE_TAG => { + es.truncate(1); + es[0].0.insert(0, b'z'); + (Node::new_in(list(es), global_alloc()), vec![b'z']) + } + EMPTY_NODE_TAG => (Node::new_empty(), vec![]), + _ => unreachable!(), + }; + (node, path) + } + fn reference<'a>(n: &'a Node, p: &[u8]) -> TrieRefBorrowed<'a, u64, GlobalAlloc> { + TrieRefBorrowed::new_with_key_and_path_in(n, || None, &[], p, global_alloc()) + } + fn own(n: TaggedNodeRef<'_, u64, GlobalAlloc>) -> Node { + if n.tag() == TINY_REF_NODE_TAG { + Node::new_in( + unsafe { n.as_tiny_unchecked() }.into_full().unwrap(), + global_alloc(), + ) + } else { + n.clone_self() + } + } + fn values(n: Option) -> BTreeMap, u64> { + Map::new_with_root_in(n, None, global_alloc()) + .iter() + .map(|(p, v)| (p, *v)) + .collect() + } + // Repeated removal, deliberately independent of the native recurrence. + fn expected( + a: &BTreeMap, u64>, + b: &BTreeMap, u64>, + ) -> BTreeMap, u64> { + let tips = |m: &BTreeMap, u64>| -> BTreeSet> { + m.keys() + .filter(|p| !m.keys().any(|q| q != *p && q.starts_with(p))) + .cloned() + .collect() + }; + let at = tips(a); + let bt = tips(b); + let protected: BTreeSet<_> = at + .into_iter() + .filter(|p| { + if SUBTRACT { + !b.contains_key(p) + } else { + bt.contains(p) + } + }) + .collect(); + let mut out: BTreeMap<_, _> = a + .iter() + .filter(|(p, _)| SUBTRACT || b.contains_key(*p)) + .map(|(p, v)| (p.clone(), *v)) + .collect(); + loop { + let remove: Vec<_> = tips(&out).difference(&protected).cloned().collect(); + if remove.is_empty() { + return out; + } + for p in remove { + out.remove(&p); + } + } + } + fn matrix() { + let mut covered = BTreeSet::new(); + for lt in TAGS { + for rt in TAGS { + for lp in 0..8 { + for rp in 0..8 { + // Retain every tag pair and every pattern on each side; + // the full Cartesian pattern matrix runs in native tests. + if cfg!(miri) && rp != lp && rp != (lp + 1) % 8 { + continue; + } + let (l, lk) = fixture(lt, lp, 0); + let (r, rk) = fixture(rt, rp, 1); + let lr = reference(&l, &lk); + let rr = reference(&r, &rk); + let lf = lr.clone().into_focus(); + let rf = rr.clone().into_focus(); + let ln = lf.try_as_tagged().unwrap_or_else(|| l.as_tagged()); + let rn = rf.try_as_tagged().unwrap_or_else(|| r.as_tagged()); + assert_eq!(ln.tag(), lt); + assert_eq!(rn.tag(), rt); + let a = values( + lf.borrow() + .cloned() + .or_else(|| (!lf.is_none()).then(|| own(ln))), + ); + let b = values( + rf.borrow() + .cloned() + .or_else(|| (!rf.is_none()).then(|| own(rn))), + ); + // Call the kernel itself: sharing, singleton, disjoint-mask, and + // spine shortcuts cannot conceal a missing dispatch arm. + let (out, summary) = native_kernel::(ln, &rr, None); + let out = out.map_into_option(|id| { + assert_eq!(id, 0); + Some(own(ln)) + }); + let out = values(out); + assert_eq!( + out, + expected::(&a, &b), + "SUBTRACT={SUBTRACT} tags={lt}/{rt} patterns={lp}/{rp}" + ); + assert_eq!(summary.live, !a.is_empty()); + assert_eq!(summary.kept, !out.is_empty()); + covered.insert((lt, rt)); + } + } + } + } + assert_eq!(covered.len(), 25); + } + #[test] + fn forced_native_meet_dispatch_matrix() { + matrix::(); + } + #[test] + fn forced_native_subtract_dispatch_matrix() { + matrix::(); + } + + #[cfg(not(feature = "nightly"))] + #[test] + fn distinct_payload_and_allocator_types() { + #[derive(Clone)] + struct RightAlloc; + impl Allocator for RightAlloc {} + let mut left = Map::new(); + let mut right = PathMap::::new_in(RightAlloc); + for b in 0..=255u8 { + left.set_val_at([b], b as u64 + 1); + left.set_val_at([b, 0], b as u64 + 1000); + right.set_val_at([b], "interior".into()); + if b % 2 == 0 { + right.set_val_at([b, 0], "tip".into()); + } + } + let meet = convex_meet(&left, &right); + let sub = convex_subtract(&left, &right); + assert_eq!(meet.val_count(), 256); + assert_eq!(sub.val_count(), 256); + for b in 0..=255u8 { + for (path, value) in [(vec![b], b as u64 + 1), (vec![b, 0], b as u64 + 1000)] { + assert_eq!(meet.get_val_at(&path), (b % 2 == 0).then_some(&value)); + assert_eq!(sub.get_val_at(&path), (b % 2 == 1).then_some(&value)); + } + } + } + + #[test] + fn native_spines_use_bounded_call_depth() { + // A 128-KiB worker stack makes accidentally recursive unary handling + // fail quickly. Construct physical spines without quadratic key inserts. + std::thread::Builder::new() + .stack_size(128 * 1024) + .spawn(|| { + let mut a = Node::new_in(list(vec![(vec![0], Payload::Val(7))]), global_alloc()); + let mut b = Node::new_in(list(vec![(vec![1], Payload::Val(9))]), global_alloc()); + let depth = if cfg!(miri) { 64 } else { 12000 }; + for i in 0..depth { + if i % 2 == 0 { + a = Node::new_in( + list(vec![ + (vec![0], Payload::Child(a)), + (vec![0], Payload::Val(11)), + ]), + global_alloc(), + ); + b = Node::new_in( + list(vec![ + (vec![0], Payload::Child(b)), + (vec![0], Payload::Val(12)), + ]), + global_alloc(), + ); + } else { + let mut x = DenseByteNode::new_in(global_alloc()); + x.set_child(0, a); + x.set_val(0, 13); + let mut y = CellByteNode::new_in(global_alloc()); + y.set_child(0, b); + y.set_val(0, 14); + a = Node::new_in(x, global_alloc()); + b = Node::new_in(y, global_alloc()); + } + } + assert!( + node_op::(&a, reference(&b, &[])) + .0 + .is_none() + ); + assert!( + node_op::(&a, reference(&b, &[])) + .0 + .unwrap() + .ptr_eq(&a) + ); + // Teardown explicitly: the native node Drop implementations have + // their own independent recursion limits across mixed node types. + while let Some((_, child, _)) = spine_link(a.as_tagged()) { + let next = child.clone(); + drop(a); + a = next; + } + while let Some((_, child, _)) = spine_link(b.as_tagged()) { + let next = child.clone(); + drop(b); + b = next; + } + }) + .unwrap() + .join() + .unwrap(); + } +} diff --git a/src/experimental/convex/native/tests.rs b/src/experimental/convex/native/tests.rs deleted file mode 100644 index 072866bd..00000000 --- a/src/experimental/convex/native/tests.rs +++ /dev/null @@ -1,316 +0,0 @@ -use super::*; -use crate::alloc::{GlobalAlloc, global_alloc}; -use crate::dense_byte_node::{CellByteNode, DenseByteNode}; -use crate::trie_node::TrieNode; -use std::collections::{BTreeMap, BTreeSet}; - -type Node = TrieNodeODRc; -type Map = PathMap; -type Payload = ValOrChild; -const TAGS: [usize; 5] = [ - DENSE_BYTE_NODE_TAG, - CELL_BYTE_NODE_TAG, - LINE_LIST_NODE_TAG, - TINY_REF_NODE_TAG, - EMPTY_NODE_TAG, -]; - -fn list(entries: Vec<(Vec, Payload)>) -> LineListNode { - let mut node = LineListNode::new_in(global_alloc()); - for (i, (key, payload)) in entries.into_iter().enumerate() { - // At most two entries, sorted by key with children before values. - unsafe { - match i { - 0 => node.set_payload_owned::<0>(&key, payload), - 1 => node.set_payload_owned::<1>(&key, payload), - _ => unreachable!(), - } - } - } - assert!(crate::line_list_node::validate_node(&node)); - node -} -fn child(side: u64) -> Node { - let mut m = Map::new(); - m.set_val_at(b"c", 30 + side); - m.set_val_at(if side == 0 { b"d" } else { b"e" }, 40 + side); - m.root().unwrap().clone() -} -fn entries(pattern: usize, side: u64) -> Vec<(Vec, Payload)> { - let v = |p: &[u8], n| (p.to_vec(), Payload::Val(n + 100 * side)); - let c = |p: &[u8], bare| { - ( - p.to_vec(), - Payload::Child(if bare { Node::new_empty() } else { child(side) }), - ) - }; - match pattern { - 0 => vec![v(b"ab", 1), v(b"b", 2)], - 1 => vec![v(b"a", 1), c(b"ab", false)], - 2 => vec![c(b"a", false), v(b"a", 1)], - 3 => vec![c(b"ab", true), v(b"b", 2)], - 4 => vec![v(b"a", 1), v(b"ab", 2)], - 5 => vec![c(b"a", true)], - 6 => vec![c(b"a", false), c(b"b", false)], - 7 => vec![v(b"ab", 1)], - _ => unreachable!(), - } -} -fn byte>( - entries: Vec<(Vec, Payload)>, -) -> ByteNode { - let mut n = ByteNode::new_in(global_alloc()); - for (key, payload) in entries { - if key.len() == 1 { - n.set_payload_owned(key[0], payload); - } else { - n.set_child( - key[0], - Node::new_in(list(vec![(key[1..].to_vec(), payload)]), global_alloc()), - ); - } - } - n -} -// A Tiny is a real borrowed slice inside a list key, not a map that merely -// might choose a tiny representation. Empty is the actual sentinel. -fn fixture(tag: usize, pattern: usize, side: u64) -> (Node, Vec) { - let mut es = entries(pattern, side); - let (node, path) = match tag { - DENSE_BYTE_NODE_TAG => ( - Node::new_in( - byte::>(es), - global_alloc(), - ), - vec![], - ), - CELL_BYTE_NODE_TAG => ( - Node::new_in( - byte::>(es), - global_alloc(), - ), - vec![], - ), - LINE_LIST_NODE_TAG => (Node::new_in(list(es), global_alloc()), vec![]), - TINY_REF_NODE_TAG => { - es.truncate(1); - es[0].0.insert(0, b'z'); - (Node::new_in(list(es), global_alloc()), vec![b'z']) - } - EMPTY_NODE_TAG => (Node::new_empty(), vec![]), - _ => unreachable!(), - }; - (node, path) -} -fn reference<'a>(n: &'a Node, p: &[u8]) -> TrieRefBorrowed<'a, u64, GlobalAlloc> { - TrieRefBorrowed::new_with_key_and_path_in(n, || None, &[], p, global_alloc()) -} -fn own(n: TaggedNodeRef<'_, u64, GlobalAlloc>) -> Node { - if n.tag() == TINY_REF_NODE_TAG { - Node::new_in( - unsafe { n.as_tiny_unchecked() }.into_full().unwrap(), - global_alloc(), - ) - } else { - n.clone_self() - } -} -fn values(n: Option) -> BTreeMap, u64> { - Map::new_with_root_in(n, None, global_alloc()) - .iter() - .map(|(p, v)| (p, *v)) - .collect() -} -// Repeated removal, deliberately independent of the native recurrence. -fn expected( - a: &BTreeMap, u64>, - b: &BTreeMap, u64>, -) -> BTreeMap, u64> { - let tips = |m: &BTreeMap, u64>| -> BTreeSet> { - m.keys() - .filter(|p| !m.keys().any(|q| q != *p && q.starts_with(p))) - .cloned() - .collect() - }; - let at = tips(a); - let bt = tips(b); - let protected: BTreeSet<_> = at - .into_iter() - .filter(|p| { - if SUBTRACT { - !b.contains_key(p) - } else { - bt.contains(p) - } - }) - .collect(); - let mut out: BTreeMap<_, _> = a - .iter() - .filter(|(p, _)| SUBTRACT || b.contains_key(*p)) - .map(|(p, v)| (p.clone(), *v)) - .collect(); - loop { - let remove: Vec<_> = tips(&out).difference(&protected).cloned().collect(); - if remove.is_empty() { - return out; - } - for p in remove { - out.remove(&p); - } - } -} -fn matrix() { - let mut covered = BTreeSet::new(); - for lt in TAGS { - for rt in TAGS { - for lp in 0..8 { - for rp in 0..8 { - // Retain every tag pair and every pattern on each side; - // the full Cartesian pattern matrix runs in native tests. - if cfg!(miri) && rp != lp && rp != (lp + 1) % 8 { - continue; - } - let (l, lk) = fixture(lt, lp, 0); - let (r, rk) = fixture(rt, rp, 1); - let lr = reference(&l, &lk); - let rr = reference(&r, &rk); - let lf = lr.clone().into_focus(); - let rf = rr.clone().into_focus(); - let ln = lf.try_as_tagged().unwrap_or_else(|| l.as_tagged()); - let rn = rf.try_as_tagged().unwrap_or_else(|| r.as_tagged()); - assert_eq!(ln.tag(), lt); - assert_eq!(rn.tag(), rt); - let a = values( - lf.borrow() - .cloned() - .or_else(|| (!lf.is_none()).then(|| own(ln))), - ); - let b = values( - rf.borrow() - .cloned() - .or_else(|| (!rf.is_none()).then(|| own(rn))), - ); - // Call the kernel itself: sharing, singleton, disjoint-mask, and - // spine shortcuts cannot conceal a missing dispatch arm. - let (out, summary) = native_kernel::(ln, &rr, None); - let out = out.map_into_option(|id| { - assert_eq!(id, 0); - Some(own(ln)) - }); - let out = values(out); - assert_eq!( - out, - expected::(&a, &b), - "SUBTRACT={SUBTRACT} tags={lt}/{rt} patterns={lp}/{rp}" - ); - assert_eq!(summary.live, !a.is_empty()); - assert_eq!(summary.kept, !out.is_empty()); - covered.insert((lt, rt)); - } - } - } - } - assert_eq!(covered.len(), 25); -} -#[test] -fn forced_native_meet_dispatch_matrix() { - matrix::(); -} -#[test] -fn forced_native_subtract_dispatch_matrix() { - matrix::(); -} - -#[cfg(not(feature = "nightly"))] -#[test] -fn distinct_payload_and_allocator_types() { - #[derive(Clone)] - struct RightAlloc; - impl Allocator for RightAlloc {} - let mut left = Map::new(); - let mut right = PathMap::::new_in(RightAlloc); - for b in 0..=255u8 { - left.set_val_at([b], b as u64 + 1); - left.set_val_at([b, 0], b as u64 + 1000); - right.set_val_at([b], "interior".into()); - if b % 2 == 0 { - right.set_val_at([b, 0], "tip".into()); - } - } - let meet = convex_meet(&left, &right); - let sub = convex_subtract(&left, &right); - assert_eq!(meet.val_count(), 256); - assert_eq!(sub.val_count(), 256); - for b in 0..=255u8 { - for (path, value) in [(vec![b], b as u64 + 1), (vec![b, 0], b as u64 + 1000)] { - assert_eq!(meet.get_val_at(&path), (b % 2 == 0).then_some(&value)); - assert_eq!(sub.get_val_at(&path), (b % 2 == 1).then_some(&value)); - } - } -} - -#[test] -fn native_spines_use_bounded_call_depth() { - // A 128-KiB worker stack makes accidentally recursive unary handling - // fail quickly. Construct physical spines without quadratic key inserts. - std::thread::Builder::new() - .stack_size(128 * 1024) - .spawn(|| { - let mut a = Node::new_in(list(vec![(vec![0], Payload::Val(7))]), global_alloc()); - let mut b = Node::new_in(list(vec![(vec![1], Payload::Val(9))]), global_alloc()); - let depth = if cfg!(miri) { 64 } else { 12000 }; - for i in 0..depth { - if i % 2 == 0 { - a = Node::new_in( - list(vec![ - (vec![0], Payload::Child(a)), - (vec![0], Payload::Val(11)), - ]), - global_alloc(), - ); - b = Node::new_in( - list(vec![ - (vec![0], Payload::Child(b)), - (vec![0], Payload::Val(12)), - ]), - global_alloc(), - ); - } else { - let mut x = DenseByteNode::new_in(global_alloc()); - x.set_child(0, a); - x.set_val(0, 13); - let mut y = CellByteNode::new_in(global_alloc()); - y.set_child(0, b); - y.set_val(0, 14); - a = Node::new_in(x, global_alloc()); - b = Node::new_in(y, global_alloc()); - } - } - assert!( - node_op::(&a, reference(&b, &[])) - .0 - .is_none() - ); - assert!( - node_op::(&a, reference(&b, &[])) - .0 - .unwrap() - .ptr_eq(&a) - ); - // Teardown explicitly: the native node Drop implementations have - // their own independent recursion limits across mixed node types. - while let Some((_, child, _)) = spine_link(a.as_tagged()) { - let next = child.clone(); - drop(a); - a = next; - } - while let Some((_, child, _)) = spine_link(b.as_tagged()) { - let next = child.clone(); - drop(b); - b = next; - } - }) - .unwrap() - .join() - .unwrap(); -} From 6eb62deada02208699ac594ddf5a63fd371f2b32 Mon Sep 17 00:00:00 2001 From: adamv-symbolica Date: Thu, 19 Nov 2026 15:47:41 +0000 Subject: [PATCH 13/15] Generate path-set laws from proved Lean theorems --- .github/workflows/ci.yml | 8 + differential/ALGEBRAIC_FUZZING.md | 12 +- differential/src/algebraic.rs | 5 +- differential/src/algebraic/laws.rs | 49 +- differential/src/algebraic/path_set_laws.rs | 2826 +++++++++++++++++++ differential/tests/algebraic.rs | 20 +- lean/LawExport.lean | 429 +++ lean/LawExport/Checks.lean | 47 + lean/PathSetLaws.lean | 42 + lean/ZippyLaws.lean | 327 +-- lean/lakefile.toml | 6 +- 11 files changed, 3442 insertions(+), 329 deletions(-) create mode 100644 differential/src/algebraic/path_set_laws.rs create mode 100644 lean/LawExport.lean create mode 100644 lean/LawExport/Checks.lean create mode 100644 lean/PathSetLaws.lean diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index b1e1e6c1..2c3aa5a3 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -196,6 +196,14 @@ jobs: cd lean lake build 2>&1 | tee ../lake.log test "${PIPESTATUS[0]}" -eq 0 + - name: generated algebraic laws are current + run: | + cd lean + lake build LawExport.Checks + lake env lean --run ZippyLaws.lean > "$RUNNER_TEMP/zippy_laws.rs" + lake env lean --run PathSetLaws.lean > "$RUNNER_TEMP/path_set_laws.rs" + diff -u ../differential/src/algebraic/zippy_laws.rs "$RUNNER_TEMP/zippy_laws.rs" + diff -u ../differential/src/algebraic/path_set_laws.rs "$RUNNER_TEMP/path_set_laws.rs" - name: no sorry, no unexpected axioms run: | if grep -n 'declaration uses .sorry.' lake.log; then diff --git a/differential/ALGEBRAIC_FUZZING.md b/differential/ALGEBRAIC_FUZZING.md index 68ca0d63..0b4940b0 100644 --- a/differential/ALGEBRAIC_FUZZING.md +++ b/differential/ALGEBRAIC_FUZZING.md @@ -140,9 +140,19 @@ file with the reason (membership lemmas, raw-zipper-op theorems, function-typed binders). ```sh -cd lean && lake env lean --run ZippyLaws.lean > ../differential/src/algebraic/zippy_laws.rs +cd lean +lake build +lake env lean --run ZippyLaws.lean > ../differential/src/algebraic/zippy_laws.rs +lake env lean --run PathSetLaws.lean > ../differential/src/algebraic/path_set_laws.rs ``` +`PathSetLaws.lean` exports the convex and path-set theorems through the same +translator. It also recognizes `Same`, inclusion and unrestricted membership +equivalences, preserving conditional laws' hypotheses. The generated file lists +every unsupported theorem and its reason. CI regenerates both files and rejects +stale output. Derived completion and LCP product use the proved combinations of +branches, divergence, retain and union; they have no separate Rust kernel. + The theorems are about `PrunedMap Unit` — a set of paths — so they are checked for `unit` only. Under `u64` or `bits` several are false for reasons that have nothing to do with the crate (subtraction removes a path only when the values diff --git a/differential/src/algebraic.rs b/differential/src/algebraic.rs index b3211385..51e8cd3a 100644 --- a/differential/src/algebraic.rs +++ b/differential/src/algebraic.rs @@ -30,6 +30,7 @@ pub mod routes; pub mod shape; pub mod value; pub mod zippy_laws; +pub mod path_set_laws; use pathmap::PathMap; use pathmap::zipper::{ZipperMoving, ZipperWriting}; @@ -619,8 +620,8 @@ pub fn check_laws(case: &Case) -> Vec { inst.pre.iter().all(|h| match h { Hyp::Holds(b) => *b, Hyp::Mem(p, e, want) => eval(e).is_some_and(|o| o.values.contains_key(p) == *want), - Hyp::Eq(l, r) => match (eval(l), eval(r)) { - (Some(l), Some(r)) => l.values == r.values, + Hyp::Eq(l, r) | Hyp::Ne(l, r) => match (eval(l), eval(r)) { + (Some(l), Some(r)) => (l.values == r.values) == matches!(h, Hyp::Eq(..)), _ => false, }, }) diff --git a/differential/src/algebraic/laws.rs b/differential/src/algebraic/laws.rs index d7ea11bc..f0aefa3d 100644 --- a/differential/src/algebraic/laws.rs +++ b/differential/src/algebraic/laws.rs @@ -14,7 +14,8 @@ //! `lean/ZippyLaws.lean` reads the *elaborated* theorems, keeps every equation //! between spaces whose operators the expression language has, and prints them //! as [`zippy_laws`](super::zippy_laws). So each law here is a theorem, not a -//! belief, and adding one means proving it. +//! belief, and adding one means proving it. `lean/PathSetLaws.lean` uses the +//! same exporter for the convex and path-set theorems in `PrunedModel.Convex`. //! //! A theorem may quantify over paths and bytes as well as spaces, and may have //! hypotheses. Hence [`ZippyLaw`] is a template: [`instantiate`] binds its @@ -93,11 +94,12 @@ pub enum Pre { Mem(P, T), NotMem(P, T), EqSpace(T, T), + NeSpace(T, T), } -/// One theorem of `Zippy.lean`, as generated. +/// One theorem exported from the pruned Lean model. pub struct ZippyLaw { - /// The theorem's name in `PrunedModel.Zippy`. + /// The theorem name; path-set names have a `path_set/` prefix. pub name: &'static str, /// How many spaces, paths and bytes it quantifies over. pub spaces: usize, @@ -108,7 +110,7 @@ pub struct ZippyLaw { pub rhs: T, } -/// The builders `zippy_laws.rs` is written in. Named after the Lean +/// The builders the generated law files are written in. Named after the Lean /// definitions, so the generated file reads like the theorems it came from. pub mod zippy { pub use super::{Pre, ZippyLaw, B, P, T}; @@ -166,6 +168,26 @@ pub mod zippy { T::Un(Un::TailsInter, Box::new(a)) } + pub fn basis(a: T) -> T { T::Un(Un::Basis, Box::new(a)) } + pub fn hull(a: T) -> T { T::Un(Un::Hull, Box::new(a)) } + pub fn branches(a: T) -> T { T::Un(Un::Branches, Box::new(a)) } + pub fn retain(a: T, b: T) -> T { bin(Op::Retain, a, b) } + pub fn divergence(a: T, b: T) -> T { bin(Op::Divergence, a, b) } + pub fn convex_meet(a: T, b: T) -> T { bin(Op::ConvexMeet, a, b) } + pub fn convex_subtract(a: T, b: T) -> T { bin(Op::ConvexSubtract, a, b) } + pub fn sym_diff(a: T, b: T) -> T { bin(Op::SymDiff, a, b) } + + // Derived operators have no separate Rust kernel. Expand their proved + // definitions in the primitive vocabulary, just as for raffination. + pub fn interior(a: T) -> T { subtr(a.clone(), hull(a)) } + pub fn completion(a: T) -> T { union(a.clone(), branches(a)) } + pub fn lcp_product(a: T, b: T) -> T { + union(divergence(a.clone(), b.clone()), union(retain(a.clone(), b.clone()), retain(b, a))) + } + pub fn convex_literal_subtract(a: T, b: T) -> T { + retain(subtr(a.clone(), b.clone()), subtr(hull(a), b)) + } + pub fn pv(i: usize) -> P { P::Var(i) } @@ -201,6 +223,9 @@ pub mod zippy { pub fn eq_space(a: T, b: T) -> Pre { Pre::EqSpace(a, b) } + pub fn ne_space(a: T, b: T) -> Pre { + Pre::NeSpace(a, b) + } } /// What a case offers for a law's variables. @@ -263,6 +288,8 @@ pub enum Hyp { Mem(Vec, Expr, bool), /// `lhs = rhs` as spaces. Eq(Expr, Expr), + /// `lhs ≠ rhs` as spaces. + Ne(Expr, Expr), } pub fn instantiate(law: &ZippyLaw, bind: &Binding) -> Instance { @@ -275,17 +302,23 @@ pub fn instantiate(law: &ZippyLaw, bind: &Binding) -> Instance { Pre::Mem(p, s) => Hyp::Mem(bind.path(p), bind.expr(s), true), Pre::NotMem(p, s) => Hyp::Mem(bind.path(p), bind.expr(s), false), Pre::EqSpace(a, b) => Hyp::Eq(bind.expr(a), bind.expr(b)), + Pre::NeSpace(a, b) => Hyp::Ne(bind.expr(a), bind.expr(b)), }) .collect(); Instance { lhs: bind.expr(&law.lhs), rhs: bind.expr(&law.rhs), pre } } -/// The laws to check for value type `V`: all of `Zippy.lean`'s for the set -/// type, none otherwise. See the module comment. +/// All generated laws for the set type, none otherwise. See the module comment. pub fn laws() -> &'static [ZippyLaw] { use std::sync::OnceLock; static LAWS: OnceLock> = OnceLock::new(); - if V::IS_SET { LAWS.get_or_init(super::zippy_laws::laws) } else { &[] } + if V::IS_SET { + LAWS.get_or_init(|| { + let mut laws = super::zippy_laws::laws(); + laws.extend(super::path_set_laws::laws()); + laws + }) + } else { &[] } } /// Whether `spaces` binds any of `law`'s space variables to something other @@ -347,7 +380,7 @@ impl std::fmt::Display for Ctx { /// The most of each kind of variable any generated law uses. The case has to /// supply at least this many; `tests/algebraic.rs` checks the bound. pub fn arity() -> (usize, usize, usize) { - super::zippy_laws::laws() + laws::<()>() .iter() .fold((0, 0, 0), |(s, p, b), l| (s.max(l.spaces), p.max(l.paths), b.max(l.bytes))) } diff --git a/differential/src/algebraic/path_set_laws.rs b/differential/src/algebraic/path_set_laws.rs new file mode 100644 index 00000000..269d8388 --- /dev/null +++ b/differential/src/algebraic/path_set_laws.rs @@ -0,0 +1,2826 @@ +// @generated by lean/PathSetLaws.lean from lean/PrunedModel/Convex/*.lean. +// Do not edit by hand. Regenerate with: +// cd lean && lake env lean --run PathSetLaws.lean > ../differential/src/algebraic/path_set_laws.rs +// +// Every entry is a theorem of PrunedModel.Convex, checked sorry-free when generated. +// 249 exported, 321 not exported (listed at the end). + +use super::laws::zippy::*; + +pub fn laws() -> Vec { + vec![ + // PrunedModel/Convex/Algebra.lean:24 + ZippyLaw { + name: "path_set/retain_congr", + spaces: 4, + paths: 0, + bytes: 0, + pre: vec![eq_space(s(0), s(1)), eq_space(s(2), s(3))], + lhs: retain(s(0), s(2)), + rhs: retain(s(1), s(3)), + }, + // PrunedModel/Convex/Algebra.lean:34 + ZippyLaw { + name: "path_set/hull_of_antichain", + spaces: 1, + paths: 0, + bytes: 0, + pre: vec![eq_space(basis(s(0)), s(0))], + lhs: hull(s(0)), + rhs: s(0), + }, + // PrunedModel/Convex/Algebra.lean:42 + ZippyLaw { + name: "path_set/retain_hull", + spaces: 1, + paths: 0, + bytes: 0, + pre: vec![], + lhs: retain(s(0), hull(s(0))), + rhs: s(0), + }, + // PrunedModel/Convex/Algebra.lean:45 + ZippyLaw { + name: "path_set/hull_retain", + spaces: 2, + paths: 0, + bytes: 0, + pre: vec![eq_space(inter(s(1), hull(s(0))), s(1))], + lhs: hull(retain(s(0), s(1))), + rhs: s(1), + }, + // PrunedModel/Convex/Algebra.lean:58 + ZippyLaw { + name: "path_set/meet_tips_subset", + spaces: 2, + paths: 0, + bytes: 0, + pre: vec![], + lhs: inter(inter(hull(s(0)), hull(s(1))), hull(inter(s(0), s(1)))), + rhs: inter(hull(s(0)), hull(s(1))), + }, + // PrunedModel/Convex/Algebra.lean:64 + ZippyLaw { + name: "path_set/hull_convexMeet", + spaces: 2, + paths: 0, + bytes: 0, + pre: vec![], + lhs: hull(convex_meet(s(0), s(1))), + rhs: inter(hull(s(0)), hull(s(1))), + }, + // PrunedModel/Convex/Algebra.lean:67 + ZippyLaw { + name: "path_set/hull_convexSubtract", + spaces: 2, + paths: 0, + bytes: 0, + pre: vec![], + lhs: hull(convex_subtract(s(0), s(1))), + rhs: subtr(hull(s(0)), s(1)), + }, + // PrunedModel/Convex/Algebra.lean:70 + ZippyLaw { + name: "path_set/convexMeet_congr", + spaces: 4, + paths: 0, + bytes: 0, + pre: vec![eq_space(s(0), s(2)), eq_space(s(1), s(3))], + lhs: convex_meet(s(0), s(1)), + rhs: convex_meet(s(2), s(3)), + }, + // PrunedModel/Convex/Algebra.lean:74 + ZippyLaw { + name: "path_set/convexSubtract_congr", + spaces: 4, + paths: 0, + bytes: 0, + pre: vec![eq_space(s(0), s(2)), eq_space(s(1), s(3))], + lhs: convex_subtract(s(0), s(1)), + rhs: convex_subtract(s(2), s(3)), + }, + // PrunedModel/Convex/Algebra.lean:78 + ZippyLaw { + name: "path_set/convexMeet_subset", + spaces: 2, + paths: 0, + bytes: 0, + pre: vec![], + lhs: inter(convex_meet(s(0), s(1)), inter(s(0), s(1))), + rhs: convex_meet(s(0), s(1)), + }, + // PrunedModel/Convex/Algebra.lean:81 + ZippyLaw { + name: "path_set/convexSubtract_subset", + spaces: 2, + paths: 0, + bytes: 0, + pre: vec![], + lhs: inter(convex_subtract(s(0), s(1)), s(0)), + rhs: convex_subtract(s(0), s(1)), + }, + // PrunedModel/Convex/Algebra.lean:84 + ZippyLaw { + name: "path_set/convexMeet_comm", + spaces: 2, + paths: 0, + bytes: 0, + pre: vec![], + lhs: convex_meet(s(0), s(1)), + rhs: convex_meet(s(1), s(0)), + }, + // PrunedModel/Convex/Algebra.lean:87 + ZippyLaw { + name: "path_set/convexMeet_idem", + spaces: 1, + paths: 0, + bytes: 0, + pre: vec![], + lhs: convex_meet(s(0), s(0)), + rhs: s(0), + }, + // PrunedModel/Convex/Algebra.lean:92 + ZippyLaw { + name: "path_set/convexMeet_assoc", + spaces: 3, + paths: 0, + bytes: 0, + pre: vec![], + lhs: convex_meet(convex_meet(s(0), s(1)), s(2)), + rhs: convex_meet(s(0), convex_meet(s(1), s(2))), + }, + // PrunedModel/Convex/Algebra.lean:95 + ZippyLaw { + name: "path_set/convexMeet_empty", + spaces: 1, + paths: 0, + bytes: 0, + pre: vec![], + lhs: convex_meet(s(0), empty()), + rhs: empty(), + }, + // PrunedModel/Convex/Algebra.lean:98 + ZippyLaw { + name: "path_set/convexSubtract_empty_right", + spaces: 1, + paths: 0, + bytes: 0, + pre: vec![], + lhs: convex_subtract(s(0), empty()), + rhs: s(0), + }, + // PrunedModel/Convex/Algebra.lean:101 + ZippyLaw { + name: "path_set/convexSubtract_empty_left", + spaces: 1, + paths: 0, + bytes: 0, + pre: vec![], + lhs: convex_subtract(empty(), s(0)), + rhs: empty(), + }, + // PrunedModel/Convex/Algebra.lean:104 + ZippyLaw { + name: "path_set/convexSubtract_self", + spaces: 1, + paths: 0, + bytes: 0, + pre: vec![], + lhs: convex_subtract(s(0), s(0)), + rhs: empty(), + }, + // PrunedModel/Convex/Algebra.lean:152 + ZippyLaw { + name: "path_set/convexSubtract_action", + spaces: 3, + paths: 0, + bytes: 0, + pre: vec![], + lhs: convex_subtract(convex_subtract(s(0), s(1)), s(2)), + rhs: convex_subtract(s(0), union(s(1), s(2))), + }, + // PrunedModel/Convex/Algebra.lean:155 + ZippyLaw { + name: "path_set/convexSubtract_commute", + spaces: 3, + paths: 0, + bytes: 0, + pre: vec![], + lhs: convex_subtract(convex_subtract(s(0), s(1)), s(2)), + rhs: convex_subtract(convex_subtract(s(0), s(2)), s(1)), + }, + // PrunedModel/Convex/Algebra.lean:158 + ZippyLaw { + name: "path_set/convexSubtract_idem", + spaces: 2, + paths: 0, + bytes: 0, + pre: vec![], + lhs: convex_subtract(convex_subtract(s(0), s(1)), s(1)), + rhs: convex_subtract(s(0), s(1)), + }, + // PrunedModel/Convex/Algebra.lean:161 + ZippyLaw { + name: "path_set/convexSubtract_redundant", + spaces: 3, + paths: 0, + bytes: 0, + pre: vec![], + lhs: convex_subtract(convex_subtract(s(0), s(1)), s(2)), + rhs: convex_subtract(convex_subtract(s(0), s(1)), subtr(s(2), s(1))), + }, + // PrunedModel/Convex/Algebra.lean:164 + ZippyLaw { + name: "path_set/convexSubtract_meet_left", + spaces: 3, + paths: 0, + bytes: 0, + pre: vec![], + lhs: convex_subtract(convex_meet(s(0), s(1)), s(2)), + rhs: convex_meet(convex_subtract(s(0), s(2)), s(1)), + }, + // PrunedModel/Convex/Algebra.lean:167 + ZippyLaw { + name: "path_set/convexSubtract_meet_right", + spaces: 3, + paths: 0, + bytes: 0, + pre: vec![], + lhs: convex_subtract(convex_meet(s(0), s(1)), s(2)), + rhs: convex_meet(s(0), convex_subtract(s(1), s(2))), + }, + // PrunedModel/Convex/Algebra.lean:170 + ZippyLaw { + name: "path_set/convex_four_factor", + spaces: 4, + paths: 0, + bytes: 0, + pre: vec![], + lhs: convex_meet(convex_subtract(s(0), s(1)), convex_subtract(s(2), s(3))), + rhs: convex_subtract(convex_meet(s(0), s(2)), union(s(1), s(3))), + }, + // PrunedModel/Convex/Algebra.lean:173 + ZippyLaw { + name: "path_set/convexSubtract_meet_both", + spaces: 3, + paths: 0, + bytes: 0, + pre: vec![], + lhs: convex_subtract(convex_meet(s(0), s(1)), s(2)), + rhs: convex_meet(convex_subtract(s(0), s(2)), convex_subtract(s(1), s(2))), + }, + // PrunedModel/Convex/Algebra.lean:176 + ZippyLaw { + name: "path_set/convexSubtract_inter", + spaces: 3, + paths: 0, + bytes: 0, + pre: vec![], + lhs: convex_subtract(s(0), inter(s(1), s(2))), + rhs: union(convex_subtract(s(0), s(1)), convex_subtract(s(0), s(2))), + }, + // PrunedModel/Convex/Algebra.lean:179 + ZippyLaw { + name: "path_set/convexSubtract_union", + spaces: 3, + paths: 0, + bytes: 0, + pre: vec![], + lhs: convex_subtract(s(0), union(s(1), s(2))), + rhs: convex_meet(convex_subtract(s(0), s(1)), convex_subtract(s(0), s(2))), + }, + // PrunedModel/Convex/Algebra.lean:183 + ZippyLaw { + name: "path_set/convexSubtract_disjoint", + spaces: 2, + paths: 0, + bytes: 0, + pre: vec![], + lhs: convex_meet(convex_subtract(s(0), s(1)), s(1)), + rhs: empty(), + }, + // PrunedModel/Convex/Algebra.lean:187 + ZippyLaw { + name: "path_set/convexMeet_via_subtract", + spaces: 2, + paths: 0, + bytes: 0, + pre: vec![], + lhs: convex_meet(s(0), s(1)), + rhs: convex_subtract(inter(s(0), s(1)), subtr(hull(inter(s(0), s(1))), inter(hull(s(0)), hull(s(1))))), + }, + // PrunedModel/Convex/Algebra.lean:193 + ZippyLaw { + name: "path_set/convexMeet_hulls", + spaces: 2, + paths: 0, + bytes: 0, + pre: vec![], + lhs: convex_meet(hull(s(0)), hull(s(1))), + rhs: inter(hull(s(0)), hull(s(1))), + }, + // PrunedModel/Convex/Algebra.lean:197 + ZippyLaw { + name: "path_set/convexSubtract_hull", + spaces: 2, + paths: 0, + bytes: 0, + pre: vec![], + lhs: convex_subtract(hull(s(0)), s(1)), + rhs: subtr(hull(s(0)), s(1)), + }, + // PrunedModel/Convex/Algebra.lean:203 + ZippyLaw { + name: "path_set/convexMeet_empty_left", + spaces: 1, + paths: 0, + bytes: 0, + pre: vec![], + lhs: convex_meet(empty(), s(0)), + rhs: empty(), + }, + // PrunedModel/Convex/Algebra.lean:206 + ZippyLaw { + name: "path_set/convexSubtract_hull_disjoint", + spaces: 2, + paths: 0, + bytes: 0, + pre: vec![], + lhs: inter(hull(convex_subtract(s(0), s(1))), s(1)), + rhs: empty(), + }, + // PrunedModel/Convex/Checks.lean:65 + ZippyLaw { + name: "path_set/convex_literal_gap_example", + spaces: 0, + paths: 0, + bytes: 0, + pre: vec![], + lhs: convex_literal_subtract(union(singleton(nil()), union(singleton(cons(lit(1), nil())), singleton(cons(lit(1), cons(lit(1), nil()))))), singleton(cons(lit(1), nil()))), + rhs: union(singleton(nil()), singleton(cons(lit(1), cons(lit(1), nil())))), + }, + // PrunedModel/Convex/Closed.lean:12 + ZippyLaw { + name: "path_set/mem_completion", + spaces: 1, + paths: 0, + bytes: 0, + pre: vec![], + lhs: completion(s(0)), + rhs: union(s(0), branches(s(0))), + }, + // PrunedModel/Convex/Closed.lean:15 + ZippyLaw { + name: "path_set/completion_extensive", + spaces: 1, + paths: 0, + bytes: 0, + pre: vec![], + lhs: inter(s(0), completion(s(0))), + rhs: s(0), + }, + // PrunedModel/Convex/Closed.lean:18 + ZippyLaw { + name: "path_set/lcp_congr", + spaces: 4, + paths: 0, + bytes: 0, + pre: vec![eq_space(s(0), s(2)), eq_space(s(1), s(3))], + lhs: lcp_product(s(0), s(1)), + rhs: lcp_product(s(2), s(3)), + }, + // PrunedModel/Convex/Closed.lean:22 + ZippyLaw { + name: "path_set/lcp_mono", + spaces: 4, + paths: 0, + bytes: 0, + pre: vec![eq_space(inter(s(0), s(2)), s(0)), eq_space(inter(s(1), s(3)), s(1))], + lhs: inter(lcp_product(s(0), s(1)), lcp_product(s(2), s(3))), + rhs: lcp_product(s(0), s(1)), + }, + // PrunedModel/Convex/Closed.lean:27 + ZippyLaw { + name: "path_set/completion_mono", + spaces: 2, + paths: 0, + bytes: 0, + pre: vec![eq_space(inter(s(0), s(1)), s(0))], + lhs: inter(completion(s(0)), completion(s(1))), + rhs: completion(s(0)), + }, + // PrunedModel/Convex/Closed.lean:32 + ZippyLaw { + name: "path_set/completion_congr", + spaces: 2, + paths: 0, + bytes: 0, + pre: vec![eq_space(s(0), s(1))], + lhs: completion(s(0)), + rhs: completion(s(1)), + }, + // PrunedModel/Convex/Closed.lean:50 + ZippyLaw { + name: "path_set/closed_completion", + spaces: 1, + paths: 0, + bytes: 0, + pre: vec![], + lhs: completion(completion(s(0))), + rhs: completion(s(0)), + }, + // PrunedModel/Convex/Closed.lean:53 + ZippyLaw { + name: "path_set/closed_lcp", + spaces: 2, + paths: 0, + bytes: 0, + pre: vec![], + lhs: completion(lcp_product(s(0), s(1))), + rhs: lcp_product(s(0), s(1)), + }, + // PrunedModel/Convex/Closed.lean:56 + ZippyLaw { + name: "path_set/closed_divergence", + spaces: 2, + paths: 0, + bytes: 0, + pre: vec![], + lhs: completion(divergence(s(0), s(1))), + rhs: divergence(s(0), s(1)), + }, + // PrunedModel/Convex/Closed.lean:59 + ZippyLaw { + name: "path_set/closed_branches", + spaces: 1, + paths: 0, + bytes: 0, + pre: vec![], + lhs: completion(branches(s(0))), + rhs: branches(s(0)), + }, + // PrunedModel/Convex/Closed.lean:61 + ZippyLaw { + name: "path_set/closed_empty", + spaces: 0, + paths: 0, + bytes: 0, + pre: vec![], + lhs: completion(empty()), + rhs: empty(), + }, + // PrunedModel/Convex/Closed.lean:63 + ZippyLaw { + name: "path_set/closed_singleton", + spaces: 0, + paths: 1, + bytes: 0, + pre: vec![], + lhs: completion(singleton(pv(0))), + rhs: singleton(pv(0)), + }, + // PrunedModel/Convex/Closed.lean:72 + ZippyLaw { + name: "path_set/completion_empty", + spaces: 0, + paths: 0, + bytes: 0, + pre: vec![], + lhs: completion(empty()), + rhs: empty(), + }, + // PrunedModel/Convex/Closed.lean:74 + ZippyLaw { + name: "path_set/completion_singleton", + spaces: 0, + paths: 1, + bytes: 0, + pre: vec![], + lhs: completion(singleton(pv(0))), + rhs: singleton(pv(0)), + }, + // PrunedModel/Convex/Closed.lean:77 + ZippyLaw { + name: "path_set/closed_inter", + spaces: 2, + paths: 0, + bytes: 0, + pre: vec![eq_space(completion(s(0)), s(0)), eq_space(completion(s(1)), s(1))], + lhs: completion(inter(s(0), s(1))), + rhs: inter(s(0), s(1)), + }, + // PrunedModel/Convex/Closed.lean:83 + ZippyLaw { + name: "path_set/completion_inter_bound", + spaces: 2, + paths: 0, + bytes: 0, + pre: vec![], + lhs: inter(completion(inter(s(0), s(1))), inter(completion(s(0)), completion(s(1)))), + rhs: completion(inter(s(0), s(1))), + }, + // PrunedModel/Convex/Closed.lean:89 + ZippyLaw { + name: "path_set/completion_union", + spaces: 2, + paths: 0, + bytes: 0, + pre: vec![], + lhs: completion(union(s(0), s(1))), + rhs: union(union(completion(s(0)), completion(s(1))), divergence(s(0), s(1))), + }, + // PrunedModel/Convex/Closed.lean:95 + ZippyLaw { + name: "path_set/completion_union_lcp", + spaces: 2, + paths: 0, + bytes: 0, + pre: vec![], + lhs: completion(union(s(0), s(1))), + rhs: union(union(completion(s(0)), completion(s(1))), lcp_product(s(0), s(1))), + }, + // PrunedModel/Convex/Closed.lean:100 + ZippyLaw { + name: "path_set/completion_union_absorb", + spaces: 2, + paths: 0, + bytes: 0, + pre: vec![], + lhs: completion(union(completion(s(0)), completion(s(1)))), + rhs: completion(union(s(0), s(1))), + }, + // PrunedModel/Convex/Closed.lean:136 + ZippyLaw { + name: "path_set/lcp_empty_left", + spaces: 1, + paths: 0, + bytes: 0, + pre: vec![], + lhs: lcp_product(empty(), s(0)), + rhs: empty(), + }, + // PrunedModel/Convex/Closed.lean:138 + ZippyLaw { + name: "path_set/lcp_empty_right", + spaces: 1, + paths: 0, + bytes: 0, + pre: vec![], + lhs: lcp_product(s(0), empty()), + rhs: empty(), + }, + // PrunedModel/Convex/Closed.lean:140 + ZippyLaw { + name: "path_set/lcp_inter_lower", + spaces: 2, + paths: 0, + bytes: 0, + pre: vec![], + lhs: inter(inter(s(0), s(1)), lcp_product(s(0), s(1))), + rhs: inter(s(0), s(1)), + }, + // PrunedModel/Convex/Closed.lean:144 + ZippyLaw { + name: "path_set/lcp_union_right", + spaces: 3, + paths: 0, + bytes: 0, + pre: vec![], + lhs: lcp_product(s(0), union(s(1), s(2))), + rhs: union(lcp_product(s(0), s(1)), lcp_product(s(0), s(2))), + }, + // PrunedModel/Convex/Closed.lean:149 + ZippyLaw { + name: "path_set/lcp_completion_left", + spaces: 2, + paths: 0, + bytes: 0, + pre: vec![], + lhs: lcp_product(completion(s(0)), s(1)), + rhs: lcp_product(s(0), s(1)), + }, + // PrunedModel/Convex/Closed.lean:164 + ZippyLaw { + name: "path_set/lcp_completion_right", + spaces: 2, + paths: 0, + bytes: 0, + pre: vec![], + lhs: lcp_product(s(0), completion(s(1))), + rhs: lcp_product(s(0), s(1)), + }, + // PrunedModel/Convex/Closed.lean:168 + ZippyLaw { + name: "path_set/lcp_completion", + spaces: 2, + paths: 0, + bytes: 0, + pre: vec![], + lhs: lcp_product(completion(s(0)), completion(s(1))), + rhs: lcp_product(s(0), s(1)), + }, + // PrunedModel/Convex/Closed.lean:172 + ZippyLaw { + name: "path_set/lcp_repeat", + spaces: 2, + paths: 0, + bytes: 0, + pre: vec![], + lhs: lcp_product(s(0), lcp_product(s(0), s(1))), + rhs: lcp_product(s(0), s(1)), + }, + // PrunedModel/Convex/Closed.lean:176 + ZippyLaw { + name: "path_set/lcp_medial", + spaces: 4, + paths: 0, + bytes: 0, + pre: vec![], + lhs: lcp_product(lcp_product(s(0), s(1)), lcp_product(s(2), s(3))), + rhs: lcp_product(lcp_product(s(0), s(2)), lcp_product(s(1), s(3))), + }, + // PrunedModel/Convex/Closed.lean:189 + ZippyLaw { + name: "path_set/lcp_four_factors", + spaces: 4, + paths: 0, + bytes: 0, + pre: vec![], + lhs: lcp_product(union(s(0), s(1)), union(s(2), s(3))), + rhs: union(union(lcp_product(s(0), s(2)), lcp_product(s(0), s(3))), union(lcp_product(s(1), s(2)), lcp_product(s(1), s(3)))), + }, + // PrunedModel/Convex/Closed.lean:195 + ZippyLaw { + name: "path_set/lcp_closed_join", + spaces: 3, + paths: 0, + bytes: 0, + pre: vec![], + lhs: lcp_product(s(0), completion(union(s(1), s(2)))), + rhs: union(lcp_product(s(0), s(1)), lcp_product(s(0), s(2))), + }, + // PrunedModel/Convex/Closed.lean:199 + ZippyLaw { + name: "path_set/closed_lcp_union", + spaces: 3, + paths: 0, + bytes: 0, + pre: vec![], + lhs: completion(union(lcp_product(s(0), s(1)), lcp_product(s(0), s(2)))), + rhs: union(lcp_product(s(0), s(1)), lcp_product(s(0), s(2))), + }, + // PrunedModel/Convex/Closed.lean:207 + ZippyLaw { + name: "path_set/closed_join_assoc", + spaces: 3, + paths: 0, + bytes: 0, + pre: vec![], + lhs: completion(union(completion(union(s(0), s(1))), s(2))), + rhs: completion(union(s(0), completion(union(s(1), s(2))))), + }, + // PrunedModel/Convex/Closed.lean:221 + ZippyLaw { + name: "path_set/closed_join_absorption", + spaces: 2, + paths: 0, + bytes: 0, + pre: vec![eq_space(completion(s(0)), s(0))], + lhs: completion(union(s(0), inter(s(0), s(1)))), + rhs: s(0), + }, + // PrunedModel/Convex/Closed.lean:227 + ZippyLaw { + name: "path_set/closed_meet_absorption", + spaces: 2, + paths: 0, + bytes: 0, + pre: vec![], + lhs: inter(s(0), completion(union(s(0), s(1)))), + rhs: s(0), + }, + // PrunedModel/Convex/ClosedGeometry.lean:12 + ZippyLaw { + name: "path_set/hull_completion", + spaces: 1, + paths: 0, + bytes: 0, + pre: vec![], + lhs: hull(completion(s(0))), + rhs: hull(s(0)), + }, + // PrunedModel/Convex/ClosedGeometry.lean:15 + ZippyLaw { + name: "path_set/completion_hull", + spaces: 1, + paths: 0, + bytes: 0, + pre: vec![], + lhs: union(s(0), completion(hull(s(0)))), + rhs: completion(s(0)), + }, + // PrunedModel/Convex/ClosedGeometry.lean:78 + ZippyLaw { + name: "path_set/hull_remove_branches", + spaces: 1, + paths: 0, + bytes: 0, + pre: vec![], + lhs: hull(subtr(s(0), branches(s(0)))), + rhs: hull(s(0)), + }, + // PrunedModel/Convex/ClosedGeometry.lean:87 + ZippyLaw { + name: "path_set/branches_remove_branches", + spaces: 1, + paths: 0, + bytes: 0, + pre: vec![], + lhs: branches(subtr(s(0), branches(s(0)))), + rhs: branches(s(0)), + }, + // PrunedModel/Convex/ClosedGeometry.lean:92 + ZippyLaw { + name: "path_set/completion_remove_branches", + spaces: 1, + paths: 0, + bytes: 0, + pre: vec![], + lhs: completion(subtr(s(0), branches(s(0)))), + rhs: completion(s(0)), + }, + // PrunedModel/Convex/ClosedGeometry.lean:96 + ZippyLaw { + name: "path_set/completion_diff_branches", + spaces: 1, + paths: 0, + bytes: 0, + pre: vec![], + lhs: subtr(completion(s(0)), branches(s(0))), + rhs: subtr(s(0), branches(s(0))), + }, + // PrunedModel/Convex/ClosedOperators.lean:6 + ZippyLaw { + name: "path_set/closed_retain", + spaces: 2, + paths: 0, + bytes: 0, + pre: vec![eq_space(completion(s(0)), s(0))], + lhs: completion(retain(s(0), s(1))), + rhs: retain(s(0), s(1)), + }, + // PrunedModel/Convex/ClosedOperators.lean:12 + ZippyLaw { + name: "path_set/closed_raffinate", + spaces: 2, + paths: 0, + bytes: 0, + pre: vec![eq_space(completion(s(0)), s(0))], + lhs: completion(raffination(s(0), s(1))), + rhs: raffination(s(0), s(1)), + }, + // PrunedModel/Convex/ClosedOperators.lean:25 + ZippyLaw { + name: "path_set/closed_restrict", + spaces: 2, + paths: 0, + bytes: 0, + pre: vec![eq_space(completion(s(0)), s(0)), eq_space(completion(s(1)), s(1))], + lhs: completion(restriction(s(0), s(1))), + rhs: restriction(s(0), s(1)), + }, + // PrunedModel/Convex/ClosedOperators.lean:35 + ZippyLaw { + name: "path_set/completion_restrict", + spaces: 2, + paths: 0, + bytes: 0, + pre: vec![], + lhs: completion(restriction(s(0), s(1))), + rhs: union(restriction(completion(s(0)), s(1)), branches(retain(s(1), s(0)))), + }, + // PrunedModel/Convex/ClosedOperators.lean:44 + ZippyLaw { + name: "path_set/completion_restrict_closed", + spaces: 2, + paths: 0, + bytes: 0, + pre: vec![eq_space(completion(s(0)), s(0))], + lhs: completion(restriction(s(1), s(0))), + rhs: restriction(completion(s(1)), s(0)), + }, + // PrunedModel/Convex/ClosedOperators.lean:58 + ZippyLaw { + name: "path_set/completion_retain_bound", + spaces: 2, + paths: 0, + bytes: 0, + pre: vec![], + lhs: inter(completion(retain(s(0), s(1))), retain(completion(s(0)), s(1))), + rhs: completion(retain(s(0), s(1))), + }, + // PrunedModel/Convex/ClosedOperators.lean:63 + ZippyLaw { + name: "path_set/completion_raffinate_bound", + spaces: 2, + paths: 0, + bytes: 0, + pre: vec![], + lhs: inter(completion(raffination(s(0), s(1))), raffination(completion(s(0)), s(1))), + rhs: completion(raffination(s(0), s(1))), + }, + // PrunedModel/Convex/ClosedOperators.lean:69 + ZippyLaw { + name: "path_set/closed_convexMeet", + spaces: 2, + paths: 0, + bytes: 0, + pre: vec![eq_space(completion(s(0)), s(0)), eq_space(completion(s(1)), s(1))], + lhs: completion(convex_meet(s(0), s(1))), + rhs: convex_meet(s(0), s(1)), + }, + // PrunedModel/Convex/ClosedOperators.lean:72 + ZippyLaw { + name: "path_set/closed_convexSubtract", + spaces: 2, + paths: 0, + bytes: 0, + pre: vec![eq_space(completion(s(0)), s(0))], + lhs: completion(convex_subtract(s(0), s(1))), + rhs: convex_subtract(s(0), s(1)), + }, + // PrunedModel/Convex/ClosedOperators.lean:75 + ZippyLaw { + name: "path_set/completion_convexMeet_bound", + spaces: 2, + paths: 0, + bytes: 0, + pre: vec![], + lhs: inter(completion(convex_meet(s(0), s(1))), convex_meet(completion(s(0)), completion(s(1)))), + rhs: completion(convex_meet(s(0), s(1))), + }, + // PrunedModel/Convex/ClosedOperators.lean:83 + ZippyLaw { + name: "path_set/completion_convexSubtract_bound", + spaces: 2, + paths: 0, + bytes: 0, + pre: vec![], + lhs: inter(completion(convex_subtract(s(0), s(1))), convex_subtract(completion(s(0)), s(1))), + rhs: completion(convex_subtract(s(0), s(1))), + }, + // PrunedModel/Convex/ClosedOperators.lean:90 + ZippyLaw { + name: "path_set/hull_completion_convexMeet", + spaces: 2, + paths: 0, + bytes: 0, + pre: vec![], + lhs: hull(completion(convex_meet(s(0), s(1)))), + rhs: hull(convex_meet(completion(s(0)), completion(s(1)))), + }, + // PrunedModel/Convex/ClosedOperators.lean:94 + ZippyLaw { + name: "path_set/hull_completion_convexSubtract", + spaces: 2, + paths: 0, + bytes: 0, + pre: vec![], + lhs: hull(completion(convex_subtract(s(0), s(1)))), + rhs: hull(convex_subtract(completion(s(0)), s(1))), + }, + // PrunedModel/Convex/ClosedOperators.lean:98 + ZippyLaw { + name: "path_set/lcp_retain_bound", + spaces: 4, + paths: 0, + bytes: 0, + pre: vec![], + lhs: inter(lcp_product(retain(s(0), s(2)), retain(s(1), s(3))), retain(lcp_product(s(0), s(1)), lcp_product(s(2), s(3)))), + rhs: lcp_product(retain(s(0), s(2)), retain(s(1), s(3))), + }, + // PrunedModel/Convex/ClosedOperators.lean:109 + ZippyLaw { + name: "path_set/lcp_inter_bound", + spaces: 3, + paths: 0, + bytes: 0, + pre: vec![], + lhs: inter(lcp_product(inter(s(0), s(1)), s(2)), inter(lcp_product(s(0), s(2)), lcp_product(s(1), s(2)))), + rhs: lcp_product(inter(s(0), s(1)), s(2)), + }, + // PrunedModel/Convex/ClosedOperators.lean:115 + ZippyLaw { + name: "path_set/lcp_diff_bound", + spaces: 3, + paths: 0, + bytes: 0, + pre: vec![], + lhs: inter(subtr(lcp_product(s(0), s(2)), lcp_product(s(1), s(2))), lcp_product(subtr(s(0), s(1)), s(2))), + rhs: subtr(lcp_product(s(0), s(2)), lcp_product(s(1), s(2))), + }, + // PrunedModel/Convex/ClosedOperators.lean:123 + ZippyLaw { + name: "path_set/lcp_new_marks", + spaces: 2, + paths: 0, + bytes: 0, + pre: vec![], + lhs: subtr(lcp_product(s(0), s(1)), union(s(0), s(1))), + rhs: subtr(divergence(s(0), s(1)), union(s(0), s(1))), + }, + // PrunedModel/Convex/ClosedOperators.lean:127 + ZippyLaw { + name: "path_set/lcp_union_bound", + spaces: 2, + paths: 0, + bytes: 0, + pre: vec![], + lhs: inter(lcp_product(s(0), s(1)), completion(union(s(0), s(1)))), + rhs: lcp_product(s(0), s(1)), + }, + // PrunedModel/Convex/ClosedOperators.lean:131 + ZippyLaw { + name: "path_set/retain_lcp_operand", + spaces: 2, + paths: 0, + bytes: 0, + pre: vec![], + lhs: retain(s(0), lcp_product(s(0), s(1))), + rhs: retain(s(0), s(1)), + }, + // PrunedModel/Convex/ClosedOperators.lean:136 + ZippyLaw { + name: "path_set/hull_lcp_hulls", + spaces: 2, + paths: 0, + bytes: 0, + pre: vec![], + lhs: hull(lcp_product(hull(s(0)), hull(s(1)))), + rhs: hull(lcp_product(s(0), s(1))), + }, + // PrunedModel/Convex/ClosedOperators.lean:193 + ZippyLaw { + name: "path_set/lcp_restrict", + spaces: 3, + paths: 0, + bytes: 0, + pre: vec![], + lhs: lcp_product(restriction(s(0), s(2)), restriction(s(1), s(2))), + rhs: union(restriction(lcp_product(s(0), s(1)), s(2)), divergence(retain(s(2), s(0)), retain(s(2), s(1)))), + }, + // PrunedModel/Convex/ClosedOperators.lean:222 + ZippyLaw { + name: "path_set/lcp_restrict_closed", + spaces: 3, + paths: 0, + bytes: 0, + pre: vec![eq_space(completion(s(0)), s(0))], + lhs: lcp_product(restriction(s(1), s(0)), restriction(s(2), s(0))), + rhs: restriction(lcp_product(s(1), s(2)), s(0)), + }, + // PrunedModel/Convex/ClosedOperators.lean:236 + ZippyLaw { + name: "path_set/completion_wrap", + spaces: 1, + paths: 1, + bytes: 0, + pre: vec![], + lhs: completion(wrap(pv(0), s(0))), + rhs: wrap(pv(0), completion(s(0))), + }, + // PrunedModel/Convex/ClosedOperators.lean:243 + ZippyLaw { + name: "path_set/completion_unwrap", + spaces: 1, + paths: 1, + bytes: 0, + pre: vec![], + lhs: completion(unwrap(s(0), pv(0))), + rhs: unwrap(completion(s(0)), pv(0)), + }, + // PrunedModel/Convex/ClosedOperators.lean:249 + ZippyLaw { + name: "path_set/closed_join_comm", + spaces: 2, + paths: 0, + bytes: 0, + pre: vec![], + lhs: completion(union(s(0), s(1))), + rhs: completion(union(s(1), s(0))), + }, + // PrunedModel/Convex/ClosedOperators.lean:253 + ZippyLaw { + name: "path_set/closed_join_idem", + spaces: 1, + paths: 0, + bytes: 0, + pre: vec![eq_space(completion(s(0)), s(0))], + lhs: completion(union(s(0), s(0))), + rhs: s(0), + }, + // PrunedModel/Convex/ClosedOperators.lean:258 + ZippyLaw { + name: "path_set/closed_join_empty", + spaces: 1, + paths: 0, + bytes: 0, + pre: vec![eq_space(completion(s(0)), s(0))], + lhs: completion(union(s(0), empty())), + rhs: s(0), + }, + // PrunedModel/Convex/Geometry.lean:38 + ZippyLaw { + name: "path_set/pruning_basis_cut", + spaces: 2, + paths: 0, + bytes: 0, + pre: vec![], + lhs: restriction(s(0), basis(subtr(s(0), retain(s(0), s(1))))), + rhs: subtr(s(0), retain(s(0), s(1))), + }, + // PrunedModel/Convex/Geometry.lean:47 + ZippyLaw { + name: "path_set/pruning_basis_raffinate", + spaces: 2, + paths: 0, + bytes: 0, + pre: vec![], + lhs: raffination(s(0), basis(subtr(s(0), retain(s(0), s(1))))), + rhs: retain(s(0), s(1)), + }, + // PrunedModel/Convex/Geometry.lean:51 + ZippyLaw { + name: "path_set/convexMeet_basis", + spaces: 2, + paths: 0, + bytes: 0, + pre: vec![], + lhs: raffination(inter(s(0), s(1)), basis(subtr(inter(s(0), s(1)), convex_meet(s(0), s(1))))), + rhs: convex_meet(s(0), s(1)), + }, + // PrunedModel/Convex/Geometry.lean:54 + ZippyLaw { + name: "path_set/convexSubtract_basis", + spaces: 2, + paths: 0, + bytes: 0, + pre: vec![], + lhs: raffination(s(0), basis(subtr(s(0), convex_subtract(s(0), s(1))))), + rhs: convex_subtract(s(0), s(1)), + }, + // PrunedModel/Convex/Geometry.lean:57 + ZippyLaw { + name: "path_set/divergence_convexMeet", + spaces: 3, + paths: 0, + bytes: 0, + pre: vec![], + lhs: divergence(convex_meet(s(0), s(1)), s(2)), + rhs: divergence(inter(hull(s(0)), hull(s(1))), hull(s(2))), + }, + // PrunedModel/Convex/Geometry.lean:61 + ZippyLaw { + name: "path_set/divergence_convexSubtract", + spaces: 3, + paths: 0, + bytes: 0, + pre: vec![], + lhs: divergence(convex_subtract(s(0), s(1)), s(2)), + rhs: divergence(subtr(hull(s(0)), s(1)), hull(s(2))), + }, + // PrunedModel/Convex/Geometry.lean:65 + ZippyLaw { + name: "path_set/divergence_subtract_partition", + spaces: 3, + paths: 0, + bytes: 0, + pre: vec![], + lhs: divergence(s(0), s(2)), + rhs: union(divergence(convex_subtract(s(0), s(1)), s(2)), divergence(inter(hull(s(0)), s(1)), s(2))), + }, + // PrunedModel/Convex/Geometry.lean:76 + ZippyLaw { + name: "path_set/branches_convexMeet", + spaces: 2, + paths: 0, + bytes: 0, + pre: vec![], + lhs: inter(branches(convex_meet(s(0), s(1))), inter(branches(s(0)), branches(s(1)))), + rhs: branches(convex_meet(s(0), s(1))), + }, + // PrunedModel/Convex/Geometry.lean:82 + ZippyLaw { + name: "path_set/branches_convexSubtract", + spaces: 2, + paths: 0, + bytes: 0, + pre: vec![], + lhs: inter(branches(convex_subtract(s(0), s(1))), branches(s(0))), + rhs: branches(convex_subtract(s(0), s(1))), + }, + // PrunedModel/Convex/Geometry.lean:85 + ZippyLaw { + name: "path_set/convex_partition", + spaces: 2, + paths: 0, + bytes: 0, + pre: vec![], + lhs: union(convex_subtract(s(0), s(1)), convex_subtract(s(0), subtr(hull(s(0)), s(1)))), + rhs: s(0), + }, + // PrunedModel/Convex/Geometry.lean:95 + ZippyLaw { + name: "path_set/convex_partition_disjoint", + spaces: 2, + paths: 0, + bytes: 0, + pre: vec![], + lhs: convex_meet(convex_subtract(s(0), s(1)), convex_subtract(s(0), subtr(hull(s(0)), s(1)))), + rhs: empty(), + }, + // PrunedModel/Convex/Geometry.lean:99 + ZippyLaw { + name: "path_set/branches_convex_partition", + spaces: 2, + paths: 0, + bytes: 0, + pre: vec![], + lhs: branches(s(0)), + rhs: union(branches(convex_subtract(s(0), s(1))), union(branches(convex_subtract(s(0), subtr(hull(s(0)), s(1)))), divergence(convex_subtract(s(0), s(1)), convex_subtract(s(0), subtr(hull(s(0)), s(1)))))), + }, + // PrunedModel/Convex/Geometry.lean:108 + ZippyLaw { + name: "path_set/convexLiteralSubtract_diff", + spaces: 2, + paths: 0, + bytes: 0, + pre: vec![], + lhs: convex_literal_subtract(s(0), s(1)), + rhs: subtr(convex_subtract(s(0), s(1)), s(1)), + }, + // PrunedModel/Convex/Geometry.lean:115 + ZippyLaw { + name: "path_set/convexLiteralSubtract_meet", + spaces: 2, + paths: 0, + bytes: 0, + pre: vec![], + lhs: convex_literal_subtract(s(0), s(1)), + rhs: convex_meet(s(0), subtr(s(0), s(1))), + }, + // PrunedModel/Convex/Geometry.lean:122 + ZippyLaw { + name: "path_set/convexLiteralSubtract_hull", + spaces: 2, + paths: 0, + bytes: 0, + pre: vec![], + lhs: hull(convex_literal_subtract(s(0), s(1))), + rhs: subtr(hull(s(0)), s(1)), + }, + // PrunedModel/Convex/Morphisms.lean:47 + ZippyLaw { + name: "path_set/convexMeet_unwrap", + spaces: 2, + paths: 1, + bytes: 0, + pre: vec![], + lhs: unwrap(convex_meet(s(0), s(1)), pv(0)), + rhs: convex_meet(unwrap(s(0), pv(0)), unwrap(s(1), pv(0))), + }, + // PrunedModel/Convex/Morphisms.lean:56 + ZippyLaw { + name: "path_set/convexSubtract_unwrap", + spaces: 2, + paths: 1, + bytes: 0, + pre: vec![], + lhs: unwrap(convex_subtract(s(0), s(1)), pv(0)), + rhs: convex_subtract(unwrap(s(0), pv(0)), unwrap(s(1), pv(0))), + }, + // PrunedModel/Convex/Morphisms.lean:119 + ZippyLaw { + name: "path_set/convexMeet_product", + spaces: 3, + paths: 0, + bytes: 0, + pre: vec![eq_space(basis(s(0)), s(0))], + lhs: convex_meet(composition(s(0), s(1)), composition(s(0), s(2))), + rhs: composition(s(0), convex_meet(s(1), s(2))), + }, + // PrunedModel/Convex/Morphisms.lean:128 + ZippyLaw { + name: "path_set/convexSubtract_product", + spaces: 3, + paths: 0, + bytes: 0, + pre: vec![eq_space(basis(s(0)), s(0))], + lhs: convex_subtract(composition(s(0), s(1)), composition(s(0), s(2))), + rhs: composition(s(0), convex_subtract(s(1), s(2))), + }, + // PrunedModel/Convex/Morphisms.lean:137 + ZippyLaw { + name: "path_set/convexMeet_wrap", + spaces: 2, + paths: 1, + bytes: 0, + pre: vec![], + lhs: convex_meet(wrap(pv(0), s(0)), wrap(pv(0), s(1))), + rhs: wrap(pv(0), convex_meet(s(0), s(1))), + }, + // PrunedModel/Convex/Morphisms.lean:143 + ZippyLaw { + name: "path_set/convexSubtract_wrap", + spaces: 2, + paths: 1, + bytes: 0, + pre: vec![], + lhs: convex_subtract(wrap(pv(0), s(0)), wrap(pv(0), s(1))), + rhs: wrap(pv(0), convex_subtract(s(0), s(1))), + }, + // PrunedModel/Convex/Order.lean:66 + ZippyLaw { + name: "path_set/hull_union_compatible", + spaces: 2, + paths: 0, + bytes: 0, + pre: vec![eq_space(basis(union(hull(s(0)), hull(s(1)))), union(hull(s(0)), hull(s(1))))], + lhs: hull(union(s(0), s(1))), + rhs: union(hull(s(0)), hull(s(1))), + }, + // PrunedModel/Convex/Order.lean:90 + ZippyLaw { + name: "path_set/pruning_meet", + spaces: 3, + paths: 0, + bytes: 0, + pre: vec![eq_space(inter(s(1), hull(s(0))), s(1)), eq_space(inter(s(2), hull(s(0))), s(2))], + lhs: convex_meet(retain(s(0), s(1)), retain(s(0), s(2))), + rhs: retain(s(0), inter(s(1), s(2))), + }, + // PrunedModel/Convex/Order.lean:94 + ZippyLaw { + name: "path_set/pruning_union", + spaces: 3, + paths: 0, + bytes: 0, + pre: vec![], + lhs: union(retain(s(0), s(1)), retain(s(0), s(2))), + rhs: retain(s(0), union(s(1), s(2))), + }, + // PrunedModel/Convex/Order.lean:97 + ZippyLaw { + name: "path_set/pruning_subtract", + spaces: 3, + paths: 0, + bytes: 0, + pre: vec![eq_space(inter(s(1), hull(s(0))), s(1))], + lhs: convex_subtract(retain(s(0), s(1)), s(2)), + rhs: retain(s(0), subtr(s(1), s(2))), + }, + // PrunedModel/Convex/Order.lean:101 + ZippyLaw { + name: "path_set/pruning_complement", + spaces: 2, + paths: 0, + bytes: 0, + pre: vec![eq_space(inter(s(1), hull(s(0))), s(1))], + lhs: convex_subtract(s(0), hull(retain(s(0), s(1)))), + rhs: retain(s(0), subtr(hull(s(0)), s(1))), + }, + // PrunedModel/Convex/Order.lean:120 + ZippyLaw { + name: "path_set/pruning_bottom", + spaces: 1, + paths: 0, + bytes: 0, + pre: vec![], + lhs: retain(s(0), empty()), + rhs: empty(), + }, + // PrunedModel/Convex/PathSetAlgebra.lean:6 + ZippyLaw { + name: "path_set/divergence_congr", + spaces: 4, + paths: 0, + bytes: 0, + pre: vec![eq_space(s(0), s(2)), eq_space(s(1), s(3))], + lhs: divergence(s(0), s(1)), + rhs: divergence(s(2), s(3)), + }, + // PrunedModel/Convex/PathSetAlgebra.lean:11 + ZippyLaw { + name: "path_set/divergence_terminal", + spaces: 2, + paths: 0, + bytes: 0, + pre: vec![], + lhs: divergence(union(s(0), singleton(nil())), s(1)), + rhs: divergence(s(0), s(1)), + }, + // PrunedModel/Convex/PathSetAlgebra.lean:23 + ZippyLaw { + name: "path_set/divergence_witness_absorption", + spaces: 3, + paths: 0, + bytes: 0, + pre: vec![], + lhs: divergence(union(s(0), divergence(s(0), s(1))), s(2)), + rhs: divergence(s(0), s(2)), + }, + // PrunedModel/Convex/PathSetAlgebra.lean:27 + ZippyLaw { + name: "path_set/divergence_completion_left", + spaces: 2, + paths: 0, + bytes: 0, + pre: vec![], + lhs: divergence(completion(s(0)), s(1)), + rhs: divergence(s(0), s(1)), + }, + // PrunedModel/Convex/PathSetAlgebra.lean:31 + ZippyLaw { + name: "path_set/divergence_completion", + spaces: 2, + paths: 0, + bytes: 0, + pre: vec![], + lhs: divergence(completion(s(0)), completion(s(1))), + rhs: divergence(s(0), s(1)), + }, + // PrunedModel/Convex/PathSetAlgebra.lean:35 + ZippyLaw { + name: "path_set/branch_completion", + spaces: 1, + paths: 0, + bytes: 0, + pre: vec![], + lhs: branches(completion(s(0))), + rhs: branches(s(0)), + }, + // PrunedModel/Convex/PathSetAlgebra.lean:38 + ZippyLaw { + name: "path_set/completion_idempotent", + spaces: 1, + paths: 0, + bytes: 0, + pre: vec![], + lhs: completion(completion(s(0))), + rhs: completion(s(0)), + }, + // PrunedModel/Convex/PathSetAlgebra.lean:45 + ZippyLaw { + name: "path_set/divergence_output_completion", + spaces: 2, + paths: 0, + bytes: 0, + pre: vec![], + lhs: completion(divergence(s(0), s(1))), + rhs: divergence(s(0), s(1)), + }, + // PrunedModel/Convex/PathSetAlgebra.lean:51 + ZippyLaw { + name: "path_set/absorbed_branch_marks", + spaces: 2, + paths: 0, + bytes: 0, + pre: vec![], + lhs: branches(union(s(0), divergence(s(0), s(1)))), + rhs: branches(s(0)), + }, + // PrunedModel/Convex/PathSetAlgebra.lean:59 + ZippyLaw { + name: "path_set/interior_branches", + spaces: 1, + paths: 0, + bytes: 0, + pre: vec![], + lhs: divergence(s(0), branches(s(0))), + rhs: interior(branches(s(0))), + }, + // PrunedModel/Convex/PathSetAlgebra.lean:81 + ZippyLaw { + name: "path_set/divergence_incremental", + spaces: 4, + paths: 0, + bytes: 0, + pre: vec![], + lhs: divergence(union(s(0), s(2)), union(s(1), s(3))), + rhs: union(divergence(s(0), s(1)), union(divergence(s(2), s(1)), union(divergence(s(0), s(3)), divergence(s(2), s(3))))), + }, + // PrunedModel/Convex/PathSetAlgebra.lean:129 + ZippyLaw { + name: "path_set/divergence_interior_exact", + spaces: 2, + paths: 0, + bytes: 0, + pre: vec![], + lhs: divergence(union(s(0), s(1)), divergence(s(0), s(1))), + rhs: interior(divergence(s(0), s(1))), + }, + // PrunedModel/Convex/PathSetCertificates.lean:7 + ZippyLaw { + name: "path_set/basis_congr", + spaces: 2, + paths: 0, + bytes: 0, + pre: vec![eq_space(s(0), s(1))], + lhs: basis(s(0)), + rhs: basis(s(1)), + }, + // PrunedModel/Convex/PathSetCertificates.lean:10 + ZippyLaw { + name: "path_set/hull_congr", + spaces: 2, + paths: 0, + bytes: 0, + pre: vec![eq_space(s(0), s(1))], + lhs: hull(s(0)), + rhs: hull(s(1)), + }, + // PrunedModel/Convex/PathSetCertificates.lean:25 + ZippyLaw { + name: "path_set/basis_prefixFree", + spaces: 1, + paths: 0, + bytes: 0, + pre: vec![], + lhs: basis(basis(s(0))), + rhs: basis(s(0)), + }, + // PrunedModel/Convex/PathSetCertificates.lean:28 + ZippyLaw { + name: "path_set/hull_prefixFree", + spaces: 1, + paths: 0, + bytes: 0, + pre: vec![], + lhs: basis(hull(s(0))), + rhs: hull(s(0)), + }, + // PrunedModel/Convex/PathSetCertificates.lean:31 + ZippyLaw { + name: "path_set/terminal_invariance", + spaces: 2, + paths: 0, + bytes: 0, + pre: vec![], + lhs: divergence(union(s(0), singleton(nil())), union(s(1), singleton(nil()))), + rhs: divergence(s(0), s(1)), + }, + // PrunedModel/Convex/PathSetCertificates.lean:35 + ZippyLaw { + name: "path_set/branch_epsilon", + spaces: 1, + paths: 0, + bytes: 0, + pre: vec![], + lhs: branches(union(s(0), singleton(nil()))), + rhs: branches(s(0)), + }, + // PrunedModel/Convex/PathSetDepth.lean:81 + ZippyLaw { + name: "path_set/singleton_chain", + spaces: 1, + paths: 1, + bytes: 0, + pre: vec![], + lhs: branches(divergence(singleton(pv(0)), s(0))), + rhs: empty(), + }, + // PrunedModel/Convex/PathSetExtrema.lean:85 + ZippyLaw { + name: "path_set/divergence_hull_left", + spaces: 2, + paths: 0, + bytes: 0, + pre: vec![], + lhs: divergence(hull(s(0)), s(1)), + rhs: divergence(s(0), s(1)), + }, + // PrunedModel/Convex/PathSetExtrema.lean:90 + ZippyLaw { + name: "path_set/divergence_hull", + spaces: 2, + paths: 0, + bytes: 0, + pre: vec![], + lhs: divergence(hull(s(0)), hull(s(1))), + rhs: divergence(s(0), s(1)), + }, + // PrunedModel/Convex/PathSetExtrema.lean:94 + ZippyLaw { + name: "path_set/branch_hull", + spaces: 1, + paths: 0, + bytes: 0, + pre: vec![], + lhs: branches(hull(s(0))), + rhs: branches(s(0)), + }, + // PrunedModel/Convex/PathSetExtrema.lean:97 + ZippyLaw { + name: "path_set/basis_of_hull", + spaces: 1, + paths: 0, + bytes: 0, + pre: vec![], + lhs: basis(hull(s(0))), + rhs: hull(s(0)), + }, + // PrunedModel/Convex/PathSetExtrema.lean:101 + ZippyLaw { + name: "path_set/hull_of_basis", + spaces: 1, + paths: 0, + bytes: 0, + pre: vec![], + lhs: hull(basis(s(0))), + rhs: basis(s(0)), + }, + // PrunedModel/Convex/PathSetExtrema.lean:111 + ZippyLaw { + name: "path_set/restriction_basis_mask", + spaces: 2, + paths: 0, + bytes: 0, + pre: vec![], + lhs: restriction(s(0), basis(s(1))), + rhs: restriction(s(0), s(1)), + }, + // PrunedModel/Convex/PathSetExtrema.lean:173 + ZippyLaw { + name: "path_set/hull_union", + spaces: 2, + paths: 0, + bytes: 0, + pre: vec![], + lhs: hull(union(s(0), s(1))), + rhs: hull(union(hull(s(0)), hull(s(1)))), + }, + // PrunedModel/Convex/PathSetExtrema.lean:185 + ZippyLaw { + name: "path_set/basis_union", + spaces: 2, + paths: 0, + bytes: 0, + pre: vec![], + lhs: basis(union(s(0), s(1))), + rhs: basis(union(basis(s(0)), basis(s(1)))), + }, + // PrunedModel/Convex/PathSetFork.lean:60 + ZippyLaw { + name: "path_set/fork_lcp", + spaces: 2, + paths: 0, + bytes: 0, + pre: vec![], + lhs: divergence(composition(s(0), union(singleton(cons(lit(0), nil())), singleton(cons(lit(1), nil())))), composition(s(1), union(singleton(cons(lit(0), nil())), singleton(cons(lit(1), nil()))))), + rhs: lcp_product(s(0), s(1)), + }, + // PrunedModel/Convex/PathSetFork.lean:78 + ZippyLaw { + name: "path_set/fork_completion", + spaces: 1, + paths: 0, + bytes: 0, + pre: vec![], + lhs: branches(composition(s(0), union(singleton(cons(lit(0), nil())), singleton(cons(lit(1), nil()))))), + rhs: completion(s(0)), + }, + // PrunedModel/Convex/PathSetFork.lean:82 + ZippyLaw { + name: "path_set/range_realization", + spaces: 1, + paths: 0, + bytes: 0, + pre: vec![], + lhs: branches(composition(completion(s(0)), union(singleton(cons(lit(0), nil())), singleton(cons(lit(1), nil()))))), + rhs: completion(s(0)), + }, + // PrunedModel/Convex/PathSetGeometry.lean:138 + ZippyLaw { + name: "path_set/divergence_nested_exact", + spaces: 2, + paths: 0, + bytes: 0, + pre: vec![], + lhs: divergence(s(0), divergence(s(0), s(1))), + rhs: inter(branches(s(0)), interior(divergence(s(0), s(1)))), + }, + // PrunedModel/Convex/PathSetLCP.lean:100 + ZippyLaw { + name: "path_set/lcp_correction", + spaces: 2, + paths: 0, + bytes: 0, + pre: vec![], + lhs: lcp_product(s(0), s(1)), + rhs: union(divergence(s(0), s(1)), union(retain(s(0), s(1)), retain(s(1), s(0)))), + }, + // PrunedModel/Convex/PathSetLCP.lean:114 + ZippyLaw { + name: "path_set/lcp_diagonal", + spaces: 1, + paths: 0, + bytes: 0, + pre: vec![], + lhs: lcp_product(s(0), s(0)), + rhs: completion(s(0)), + }, + // PrunedModel/Convex/PathSetLCP.lean:122 + ZippyLaw { + name: "path_set/lcp_symmetry", + spaces: 2, + paths: 0, + bytes: 0, + pre: vec![], + lhs: lcp_product(s(0), s(1)), + rhs: lcp_product(s(1), s(0)), + }, + // PrunedModel/Convex/PathSetLCP.lean:128 + ZippyLaw { + name: "path_set/lcp_associativity", + spaces: 3, + paths: 0, + bytes: 0, + pre: vec![], + lhs: lcp_product(lcp_product(s(0), s(1)), s(2)), + rhs: lcp_product(s(0), lcp_product(s(1), s(2))), + }, + // PrunedModel/Convex/PathSetLCP.lean:137 + ZippyLaw { + name: "path_set/lcp_bilinearity", + spaces: 3, + paths: 0, + bytes: 0, + pre: vec![], + lhs: lcp_product(union(s(0), s(1)), s(2)), + rhs: union(lcp_product(s(0), s(2)), lcp_product(s(1), s(2))), + }, + // PrunedModel/Convex/PathSetLCP.lean:146 + ZippyLaw { + name: "path_set/lcp_output_completion", + spaces: 2, + paths: 0, + bytes: 0, + pre: vec![], + lhs: completion(lcp_product(s(0), s(1))), + rhs: lcp_product(s(0), s(1)), + }, + // PrunedModel/Convex/PathSetMasks.lean:50 + ZippyLaw { + name: "path_set/divergence_one_mask", + spaces: 3, + paths: 0, + bytes: 0, + pre: vec![], + lhs: divergence(restriction(s(0), s(2)), s(1)), + rhs: union(restriction(divergence(s(0), s(1)), s(2)), divergence(retain(s(2), s(0)), s(1))), + }, + // PrunedModel/Convex/PathSetMasks.lean:72 + ZippyLaw { + name: "path_set/divergence_two_masks", + spaces: 4, + paths: 0, + bytes: 0, + pre: vec![], + lhs: divergence(restriction(s(0), s(2)), restriction(s(1), s(3))), + rhs: union(restriction(restriction(divergence(s(0), s(1)), s(2)), s(3)), union(restriction(divergence(s(0), retain(s(3), s(1))), s(2)), union(restriction(divergence(retain(s(2), s(0)), s(1)), s(3)), divergence(retain(s(2), s(0)), retain(s(3), s(1)))))), + }, + // PrunedModel/Convex/PathSetMasks.lean:90 + ZippyLaw { + name: "path_set/divergence_same_mask", + spaces: 3, + paths: 0, + bytes: 0, + pre: vec![], + lhs: divergence(restriction(s(0), s(2)), restriction(s(1), s(2))), + rhs: union(restriction(divergence(s(0), s(1)), s(2)), divergence(retain(s(2), s(0)), retain(s(2), s(1)))), + }, + // PrunedModel/Convex/PathSetMasks.lean:112 + ZippyLaw { + name: "path_set/divergence_single_mask", + spaces: 2, + paths: 1, + bytes: 0, + pre: vec![], + lhs: divergence(restriction(s(0), singleton(pv(0))), restriction(s(1), singleton(pv(0)))), + rhs: restriction(divergence(s(0), s(1)), singleton(pv(0))), + }, + // PrunedModel/Convex/PathSetMasks.lean:143 + ZippyLaw { + name: "path_set/divergence_filter_partition", + spaces: 3, + paths: 0, + bytes: 0, + pre: vec![], + lhs: divergence(s(0), s(1)), + rhs: union(divergence(restriction(s(0), s(2)), s(1)), divergence(raffination(s(0), s(2)), s(1))), + }, + // PrunedModel/Convex/PathSetPowers.lean:6 + ZippyLaw { + name: "path_set/product_associative", + spaces: 3, + paths: 0, + bytes: 0, + pre: vec![], + lhs: composition(composition(s(0), s(1)), s(2)), + rhs: composition(s(0), composition(s(1), s(2))), + }, + // PrunedModel/Convex/PathSetPowers.lean:15 + ZippyLaw { + name: "path_set/product_congr", + spaces: 4, + paths: 0, + bytes: 0, + pre: vec![eq_space(s(0), s(2)), eq_space(s(1), s(3))], + lhs: composition(s(0), s(1)), + rhs: composition(s(2), s(3)), + }, + // PrunedModel/Convex/PathSetPowers.lean:70 + ZippyLaw { + name: "path_set/product_empty_right", + spaces: 1, + paths: 0, + bytes: 0, + pre: vec![], + lhs: composition(s(0), empty()), + rhs: empty(), + }, + // PrunedModel/Convex/PathSetProduct.lean:116 + ZippyLaw { + name: "path_set/equiv_members", + spaces: 2, + paths: 0, + bytes: 0, + pre: vec![eq_space(s(0), s(1))], + lhs: s(0), + rhs: s(1), + }, + // PrunedModel/Convex/PathSetProduct.lean:123 + ZippyLaw { + name: "path_set/prefixFree_antichain", + spaces: 1, + paths: 0, + bytes: 0, + pre: vec![eq_space(basis(s(0)), s(0))], + lhs: basis(s(0)), + rhs: s(0), + }, + // PrunedModel/Convex/PathSetProduct.lean:132 + ZippyLaw { + name: "path_set/prefix_free_product", + spaces: 4, + paths: 0, + bytes: 0, + pre: vec![eq_space(basis(union(s(0), s(1))), union(s(0), s(1))), ne_space(s(2), empty()), ne_space(s(3), empty())], + lhs: divergence(composition(s(0), s(2)), composition(s(1), s(3))), + rhs: union(divergence(s(0), s(1)), composition(inter(s(0), s(1)), divergence(s(2), s(3)))), + }, + // PrunedModel/Convex/PathSetProduct.lean:153 + ZippyLaw { + name: "path_set/common_prefix_code", + spaces: 3, + paths: 0, + bytes: 0, + pre: vec![eq_space(basis(s(0)), s(0)), ne_space(s(1), empty()), ne_space(s(2), empty())], + lhs: divergence(composition(s(0), s(1)), composition(s(0), s(2))), + rhs: union(branches(s(0)), composition(s(0), divergence(s(1), s(2)))), + }, + // PrunedModel/Convex/PathSetProofs.lean:13 + ZippyLaw { + name: "path_set/basis_idempotent", + spaces: 1, + paths: 0, + bytes: 0, + pre: vec![], + lhs: basis(basis(s(0))), + rhs: basis(s(0)), + }, + // PrunedModel/Convex/PathSetProofs.lean:21 + ZippyLaw { + name: "path_set/hull_idempotent", + spaces: 1, + paths: 0, + bytes: 0, + pre: vec![], + lhs: hull(hull(s(0))), + rhs: hull(s(0)), + }, + // PrunedModel/Convex/PathSetProofs.lean:57 + ZippyLaw { + name: "path_set/branches_union", + spaces: 2, + paths: 0, + bytes: 0, + pre: vec![], + lhs: branches(union(s(0), s(1))), + rhs: union(branches(s(0)), union(branches(s(1)), divergence(s(0), s(1)))), + }, + // PrunedModel/Convex/PathSetProofs.lean:70 + ZippyLaw { + name: "path_set/singleton_polarization", + spaces: 0, + paths: 2, + bytes: 0, + pre: vec![], + lhs: divergence(singleton(pv(0)), singleton(pv(1))), + rhs: branches(union(singleton(pv(0)), singleton(pv(1)))), + }, + // PrunedModel/Convex/PathSetRoots.lean:6 + ZippyLaw { + name: "path_set/hull_is_antichain", + spaces: 1, + paths: 0, + bytes: 0, + pre: vec![], + lhs: basis(hull(s(0))), + rhs: hull(s(0)), + }, + // PrunedModel/Convex/PathSetStructure.lean:32 + ZippyLaw { + name: "path_set/divergence_wrap", + spaces: 2, + paths: 1, + bytes: 0, + pre: vec![], + lhs: divergence(wrap(pv(0), s(0)), wrap(pv(0), s(1))), + rhs: wrap(pv(0), divergence(s(0), s(1))), + }, + // PrunedModel/Convex/PathSetStructure.lean:68 + ZippyLaw { + name: "path_set/divergence_root_heads", + spaces: 2, + paths: 0, + bytes: 0, + pre: vec![], + lhs: divergence(head(s(0)), head(s(1))), + rhs: inter(divergence(s(0), s(1)), singleton(nil())), + }, + // PrunedModel/Convex/PathSetUpdates.lean:66 + ZippyLaw { + name: "path_set/branch_insert", + spaces: 1, + paths: 1, + bytes: 0, + pre: vec![], + lhs: branches(union(singleton(pv(0)), s(0))), + rhs: union(branches(s(0)), divergence(singleton(pv(0)), s(0))), + }, + // PrunedModel/Convex/PathSets.lean:82 + ZippyLaw { + name: "path_set/divergence_comm", + spaces: 2, + paths: 0, + bytes: 0, + pre: vec![], + lhs: divergence(s(0), s(1)), + rhs: divergence(s(1), s(0)), + }, + // PrunedModel/Convex/PathSets.lean:91 + ZippyLaw { + name: "path_set/divergence_empty_left", + spaces: 1, + paths: 0, + bytes: 0, + pre: vec![], + lhs: divergence(empty(), s(0)), + rhs: empty(), + }, + // PrunedModel/Convex/PathSets.lean:93 + ZippyLaw { + name: "path_set/divergence_empty_right", + spaces: 1, + paths: 0, + bytes: 0, + pre: vec![], + lhs: divergence(s(0), empty()), + rhs: empty(), + }, + // PrunedModel/Convex/PathSets.lean:95 + ZippyLaw { + name: "path_set/divergence_epsilon_left", + spaces: 1, + paths: 0, + bytes: 0, + pre: vec![], + lhs: divergence(singleton(nil()), s(0)), + rhs: empty(), + }, + // PrunedModel/Convex/PathSets.lean:97 + ZippyLaw { + name: "path_set/divergence_epsilon_right", + spaces: 1, + paths: 0, + bytes: 0, + pre: vec![], + lhs: divergence(s(0), singleton(nil())), + rhs: empty(), + }, + // PrunedModel/Convex/PathSets.lean:100 + ZippyLaw { + name: "path_set/divergence_union_left", + spaces: 3, + paths: 0, + bytes: 0, + pre: vec![], + lhs: divergence(union(s(0), s(1)), s(2)), + rhs: union(divergence(s(0), s(2)), divergence(s(1), s(2))), + }, + // PrunedModel/Convex/PathSets.lean:104 + ZippyLaw { + name: "path_set/divergence_union_right", + spaces: 3, + paths: 0, + bytes: 0, + pre: vec![], + lhs: divergence(s(0), union(s(1), s(2))), + rhs: union(divergence(s(0), s(1)), divergence(s(0), s(2))), + }, + // PrunedModel/Convex/PathSets.lean:108 + ZippyLaw { + name: "path_set/divergence_diagonal", + spaces: 1, + paths: 0, + bytes: 0, + pre: vec![], + lhs: divergence(s(0), s(0)), + rhs: branches(s(0)), + }, + // PrunedModel/Convex/Retain.lean:9 + ZippyLaw { + name: "path_set/retain_subset", + spaces: 2, + paths: 0, + bytes: 0, + pre: vec![], + lhs: inter(retain(s(0), s(1)), s(0)), + rhs: retain(s(0), s(1)), + }, + // PrunedModel/Convex/Retain.lean:12 + ZippyLaw { + name: "path_set/retain_empty_left", + spaces: 1, + paths: 0, + bytes: 0, + pre: vec![], + lhs: retain(empty(), s(0)), + rhs: empty(), + }, + // PrunedModel/Convex/Retain.lean:15 + ZippyLaw { + name: "path_set/retain_empty_right", + spaces: 1, + paths: 0, + bytes: 0, + pre: vec![], + lhs: retain(s(0), empty()), + rhs: empty(), + }, + // PrunedModel/Convex/Retain.lean:18 + ZippyLaw { + name: "path_set/retain_self", + spaces: 1, + paths: 0, + bytes: 0, + pre: vec![], + lhs: retain(s(0), s(0)), + rhs: s(0), + }, + // PrunedModel/Convex/Retain.lean:21 + ZippyLaw { + name: "path_set/retain_mono", + spaces: 4, + paths: 0, + bytes: 0, + pre: vec![eq_space(inter(s(0), s(2)), s(0)), eq_space(inter(s(1), s(3)), s(1))], + lhs: inter(retain(s(0), s(1)), retain(s(2), s(3))), + rhs: retain(s(0), s(1)), + }, + // PrunedModel/Convex/Retain.lean:26 + ZippyLaw { + name: "path_set/retain_union_left", + spaces: 3, + paths: 0, + bytes: 0, + pre: vec![], + lhs: retain(union(s(0), s(1)), s(2)), + rhs: union(retain(s(0), s(2)), retain(s(1), s(2))), + }, + // PrunedModel/Convex/Retain.lean:30 + ZippyLaw { + name: "path_set/retain_inter_left", + spaces: 3, + paths: 0, + bytes: 0, + pre: vec![], + lhs: retain(inter(s(0), s(1)), s(2)), + rhs: inter(retain(s(0), s(2)), retain(s(1), s(2))), + }, + // PrunedModel/Convex/Retain.lean:34 + ZippyLaw { + name: "path_set/retain_diff_left", + spaces: 3, + paths: 0, + bytes: 0, + pre: vec![], + lhs: retain(subtr(s(0), s(1)), s(2)), + rhs: subtr(retain(s(0), s(2)), retain(s(1), s(2))), + }, + // PrunedModel/Convex/Retain.lean:38 + ZippyLaw { + name: "path_set/retain_symDiff_left", + spaces: 3, + paths: 0, + bytes: 0, + pre: vec![], + lhs: retain(sym_diff(s(0), s(1)), s(2)), + rhs: sym_diff(retain(s(0), s(2)), retain(s(1), s(2))), + }, + // PrunedModel/Convex/Retain.lean:42 + ZippyLaw { + name: "path_set/retain_union_right", + spaces: 3, + paths: 0, + bytes: 0, + pre: vec![], + lhs: retain(s(0), union(s(1), s(2))), + rhs: union(retain(s(0), s(1)), retain(s(0), s(2))), + }, + // PrunedModel/Convex/Retain.lean:46 + ZippyLaw { + name: "path_set/retain_inter_right_bound", + spaces: 3, + paths: 0, + bytes: 0, + pre: vec![], + lhs: inter(retain(s(0), inter(s(1), s(2))), inter(retain(s(0), s(1)), retain(s(0), s(2)))), + rhs: retain(s(0), inter(s(1), s(2))), + }, + // PrunedModel/Convex/Retain.lean:50 + ZippyLaw { + name: "path_set/retain_diff_right_bound", + spaces: 3, + paths: 0, + bytes: 0, + pre: vec![], + lhs: inter(subtr(retain(s(0), s(1)), retain(s(0), s(2))), retain(s(0), subtr(s(1), s(2)))), + rhs: subtr(retain(s(0), s(1)), retain(s(0), s(2))), + }, + // PrunedModel/Convex/Retain.lean:54 + ZippyLaw { + name: "path_set/retain_filter_inter", + spaces: 3, + paths: 0, + bytes: 0, + pre: vec![], + lhs: retain(retain(s(0), s(1)), s(2)), + rhs: inter(retain(s(0), s(1)), retain(s(0), s(2))), + }, + // PrunedModel/Convex/Retain.lean:58 + ZippyLaw { + name: "path_set/retain_filter_comm", + spaces: 3, + paths: 0, + bytes: 0, + pre: vec![], + lhs: retain(retain(s(0), s(1)), s(2)), + rhs: retain(retain(s(0), s(2)), s(1)), + }, + // PrunedModel/Convex/Retain.lean:62 + ZippyLaw { + name: "path_set/retain_filter_idem", + spaces: 2, + paths: 0, + bytes: 0, + pre: vec![], + lhs: retain(retain(s(0), s(1)), s(1)), + rhs: retain(s(0), s(1)), + }, + // PrunedModel/Convex/Retain.lean:65 + ZippyLaw { + name: "path_set/retain_nested_bound", + spaces: 3, + paths: 0, + bytes: 0, + pre: vec![], + lhs: inter(retain(s(0), retain(s(1), s(2))), retain(retain(s(0), s(1)), s(2))), + rhs: retain(s(0), retain(s(1), s(2))), + }, + // PrunedModel/Convex/Retain.lean:79 + ZippyLaw { + name: "path_set/retain_hull_mask", + spaces: 2, + paths: 0, + bytes: 0, + pre: vec![], + lhs: retain(s(0), hull(s(1))), + rhs: retain(s(0), s(1)), + }, + // PrunedModel/Convex/Retain.lean:90 + ZippyLaw { + name: "path_set/retain_restrict_witnesses", + spaces: 2, + paths: 0, + bytes: 0, + pre: vec![], + lhs: retain(s(0), restriction(s(1), s(0))), + rhs: retain(s(0), s(1)), + }, + // PrunedModel/Convex/Retain.lean:96 + ZippyLaw { + name: "path_set/restrict_retain_mask", + spaces: 2, + paths: 0, + bytes: 0, + pre: vec![], + lhs: restriction(s(0), retain(s(1), s(0))), + rhs: restriction(s(0), s(1)), + }, + // PrunedModel/Convex/Retain.lean:102 + ZippyLaw { + name: "path_set/retain_restrict_disjoint", + spaces: 2, + paths: 0, + bytes: 0, + pre: vec![], + lhs: retain(s(0), raffination(s(1), s(0))), + rhs: empty(), + }, + // PrunedModel/Convex/Retain.lean:113 + ZippyLaw { + name: "path_set/retain_restrict_source", + spaces: 3, + paths: 0, + bytes: 0, + pre: vec![], + lhs: retain(restriction(s(0), s(1)), s(2)), + rhs: restriction(retain(s(0), s(2)), s(1)), + }, + // PrunedModel/Convex/Retain.lean:117 + ZippyLaw { + name: "path_set/retain_raffinate_source", + spaces: 3, + paths: 0, + bytes: 0, + pre: vec![], + lhs: retain(raffination(s(0), s(1)), s(2)), + rhs: raffination(retain(s(0), s(2)), s(1)), + }, + // PrunedModel/Convex/Retain.lean:121 + ZippyLaw { + name: "path_set/restrict_union_left", + spaces: 3, + paths: 0, + bytes: 0, + pre: vec![], + lhs: restriction(union(s(0), s(1)), s(2)), + rhs: union(restriction(s(0), s(2)), restriction(s(1), s(2))), + }, + // PrunedModel/Convex/Retain.lean:125 + ZippyLaw { + name: "path_set/restrict_inter_left", + spaces: 3, + paths: 0, + bytes: 0, + pre: vec![], + lhs: restriction(inter(s(0), s(1)), s(2)), + rhs: inter(restriction(s(0), s(2)), restriction(s(1), s(2))), + }, + // PrunedModel/Convex/Retain.lean:129 + ZippyLaw { + name: "path_set/restrict_diff_left", + spaces: 3, + paths: 0, + bytes: 0, + pre: vec![], + lhs: restriction(subtr(s(0), s(1)), s(2)), + rhs: subtr(restriction(s(0), s(2)), restriction(s(1), s(2))), + }, + // PrunedModel/Convex/Retain.lean:133 + ZippyLaw { + name: "path_set/restrict_union_right", + spaces: 3, + paths: 0, + bytes: 0, + pre: vec![], + lhs: restriction(s(0), union(s(1), s(2))), + rhs: union(restriction(s(0), s(1)), restriction(s(0), s(2))), + }, + // PrunedModel/Convex/Retain.lean:137 + ZippyLaw { + name: "path_set/restrict_filter_comm", + spaces: 3, + paths: 0, + bytes: 0, + pre: vec![], + lhs: restriction(restriction(s(0), s(1)), s(2)), + rhs: restriction(restriction(s(0), s(2)), s(1)), + }, + // PrunedModel/Convex/Retain.lean:141 + ZippyLaw { + name: "path_set/restrict_filter_idem", + spaces: 2, + paths: 0, + bytes: 0, + pre: vec![], + lhs: restriction(restriction(s(0), s(1)), s(1)), + rhs: restriction(s(0), s(1)), + }, + // PrunedModel/Convex/Retain.lean:146 + ZippyLaw { + name: "path_set/retain_lcp_masks", + spaces: 3, + paths: 0, + bytes: 0, + pre: vec![], + lhs: retain(retain(s(0), s(1)), s(2)), + rhs: retain(s(0), lcp_product(s(1), s(2))), + }, + // PrunedModel/Convex/Retain.lean:155 + ZippyLaw { + name: "path_set/retain_divergence_masks", + spaces: 3, + paths: 0, + bytes: 0, + pre: vec![], + lhs: retain(retain(s(0), s(1)), s(2)), + rhs: retain(s(0), union(divergence(s(1), s(2)), union(retain(s(1), s(2)), retain(s(2), s(1))))), + }, + // PrunedModel/Convex/Retain.lean:163 + ZippyLaw { + name: "path_set/restrict_overlap_masks", + spaces: 3, + paths: 0, + bytes: 0, + pre: vec![], + lhs: restriction(restriction(s(0), s(1)), s(2)), + rhs: restriction(s(0), union(restriction(s(1), s(2)), restriction(s(2), s(1)))), + }, + // PrunedModel/Convex/Retain.lean:175 + ZippyLaw { + name: "path_set/retain_restrict_mask", + spaces: 3, + paths: 0, + bytes: 0, + pre: vec![], + lhs: retain(s(0), restriction(s(1), s(2))), + rhs: union(restriction(retain(s(0), s(1)), s(2)), retain(s(0), retain(s(2), s(1)))), + }, + // PrunedModel/Convex/Retain.lean:187 + ZippyLaw { + name: "path_set/basis_retain", + spaces: 2, + paths: 0, + bytes: 0, + pre: vec![], + lhs: basis(retain(s(0), s(1))), + rhs: retain(basis(s(0)), s(1)), + }, + // PrunedModel/Convex/Retain.lean:197 + ZippyLaw { + name: "path_set/hull_restrict", + spaces: 2, + paths: 0, + bytes: 0, + pre: vec![], + lhs: hull(restriction(s(0), s(1))), + rhs: restriction(hull(s(0)), s(1)), + }, + // PrunedModel/Convex/Retain.lean:207 + ZippyLaw { + name: "path_set/retain_hull_source_bound", + spaces: 2, + paths: 0, + bytes: 0, + pre: vec![], + lhs: inter(retain(hull(s(0)), s(1)), hull(retain(s(0), s(1)))), + rhs: retain(hull(s(0)), s(1)), + }, + // PrunedModel/Convex/Retain.lean:214 + ZippyLaw { + name: "path_set/retain_antichain", + spaces: 2, + paths: 0, + bytes: 0, + pre: vec![eq_space(basis(s(0)), s(0))], + lhs: basis(retain(s(0), s(1))), + rhs: retain(s(0), s(1)), + }, + // PrunedModel/Convex/Retain.lean:218 + ZippyLaw { + name: "path_set/divergence_retain_bound", + spaces: 4, + paths: 0, + bytes: 0, + pre: vec![], + lhs: inter(divergence(retain(s(0), s(2)), retain(s(1), s(3))), inter(divergence(s(0), s(1)), divergence(s(2), s(3)))), + rhs: divergence(retain(s(0), s(2)), retain(s(1), s(3))), + }, + // PrunedModel/Convex/Retain.lean:228 + ZippyLaw { + name: "path_set/branches_retain_bound", + spaces: 2, + paths: 0, + bytes: 0, + pre: vec![], + lhs: inter(branches(retain(s(0), s(1))), inter(branches(s(0)), branches(s(1)))), + rhs: branches(retain(s(0), s(1))), + }, + // PrunedModel/Convex/Retain.lean:232 + ZippyLaw { + name: "path_set/retain_covered_mask", + spaces: 3, + paths: 0, + bytes: 0, + pre: vec![eq_space(retain(s(0), s(1)), s(0))], + lhs: inter(retain(s(2), s(0)), retain(s(2), s(1))), + rhs: retain(s(2), s(0)), + }, + // PrunedModel/Convex/Retain.lean:246 + ZippyLaw { + name: "path_set/hull_mutual_covers", + spaces: 2, + paths: 0, + bytes: 0, + pre: vec![eq_space(retain(s(0), s(1)), s(0)), eq_space(retain(s(1), s(0)), s(1))], + lhs: hull(s(0)), + rhs: hull(s(1)), + }, + // PrunedModel/Convex/Retain.lean:273 + ZippyLaw { + name: "path_set/retain_completion_mask", + spaces: 2, + paths: 0, + bytes: 0, + pre: vec![], + lhs: retain(s(0), completion(s(1))), + rhs: retain(s(0), s(1)), + }, + // PrunedModel/Convex/Retain.lean:281 + ZippyLaw { + name: "path_set/retain_antichain_inter", + spaces: 2, + paths: 0, + bytes: 0, + pre: vec![eq_space(basis(union(s(0), s(1))), union(s(0), s(1)))], + lhs: retain(s(0), s(1)), + rhs: inter(s(0), s(1)), + }, + // PrunedModel/Convex/Retain.lean:289 + ZippyLaw { + name: "path_set/retain_wrap", + spaces: 2, + paths: 1, + bytes: 0, + pre: vec![], + lhs: retain(wrap(pv(0), s(0)), wrap(pv(0), s(1))), + rhs: wrap(pv(0), retain(s(0), s(1))), + }, + // PrunedModel/Convex/Retain.lean:297 + ZippyLaw { + name: "path_set/retain_product", + spaces: 3, + paths: 0, + bytes: 0, + pre: vec![eq_space(basis(s(0)), s(0))], + lhs: retain(composition(s(0), s(1)), composition(s(0), s(2))), + rhs: composition(s(0), retain(s(1), s(2))), + }, + // PrunedModel/Convex/Retain.lean:307 + ZippyLaw { + name: "path_set/restrict_retain_lcp", + spaces: 3, + paths: 0, + bytes: 0, + pre: vec![], + lhs: restriction(s(0), retain(s(1), s(2))), + rhs: restriction(s(0), restriction(lcp_product(s(0), s(2)), s(1))), + }, + // PrunedModel/Convex/Retain.lean:319 + ZippyLaw { + name: "path_set/restrict_self", + spaces: 1, + paths: 0, + bytes: 0, + pre: vec![], + lhs: restriction(s(0), s(0)), + rhs: s(0), + }, + // PrunedModel/Convex/RetainConvex.lean:7 + ZippyLaw { + name: "path_set/restrict_convexMeet", + spaces: 3, + paths: 0, + bytes: 0, + pre: vec![], + lhs: restriction(convex_meet(s(0), s(1)), s(2)), + rhs: convex_meet(restriction(s(0), s(2)), restriction(s(1), s(2))), + }, + // PrunedModel/Convex/RetainConvex.lean:16 + ZippyLaw { + name: "path_set/restrict_convexSubtract", + spaces: 3, + paths: 0, + bytes: 0, + pre: vec![], + lhs: restriction(convex_subtract(s(0), s(1)), s(2)), + rhs: convex_subtract(restriction(s(0), s(2)), s(1)), + }, + // PrunedModel/Convex/RetainConvex.lean:24 + ZippyLaw { + name: "path_set/restrict_convexSubtract_both", + spaces: 3, + paths: 0, + bytes: 0, + pre: vec![], + lhs: restriction(convex_subtract(s(0), s(1)), s(2)), + rhs: convex_subtract(restriction(s(0), s(2)), restriction(s(1), s(2))), + }, + // PrunedModel/Convex/RetainConvex.lean:30 + ZippyLaw { + name: "path_set/convexMeet_retain_tips", + spaces: 3, + paths: 0, + bytes: 0, + pre: vec![eq_space(inter(s(1), hull(s(0))), s(1))], + lhs: convex_meet(retain(s(0), s(1)), s(2)), + rhs: retain(inter(s(0), s(2)), inter(s(1), hull(s(2)))), + }, + // PrunedModel/Convex/RetainConvex.lean:34 + ZippyLaw { + name: "path_set/convexMeet_retain_both", + spaces: 4, + paths: 0, + bytes: 0, + pre: vec![eq_space(inter(s(2), hull(s(0))), s(2)), eq_space(inter(s(3), hull(s(1))), s(3))], + lhs: convex_meet(retain(s(0), s(2)), retain(s(1), s(3))), + rhs: retain(inter(s(0), s(1)), inter(s(2), s(3))), + }, + // PrunedModel/Convex/RetainConvex.lean:39 + ZippyLaw { + name: "path_set/convexMeet_pruning", + spaces: 2, + paths: 0, + bytes: 0, + pre: vec![eq_space(inter(s(1), hull(s(0))), s(1))], + lhs: convex_meet(s(0), retain(s(0), s(1))), + rhs: retain(s(0), s(1)), + }, + // PrunedModel/Convex/RetainConvex.lean:46 + ZippyLaw { + name: "path_set/convex_pruning_retain_bound", + spaces: 2, + paths: 0, + bytes: 0, + pre: vec![], + lhs: inter(retain(s(0), retain(hull(s(0)), s(1))), retain(s(0), s(1))), + rhs: retain(s(0), retain(hull(s(0)), s(1))), + }, + // PrunedModel/Convex/RetainConvex.lean:52 + ZippyLaw { + name: "path_set/convexMeet_retained_mask", + spaces: 2, + paths: 0, + bytes: 0, + pre: vec![], + lhs: convex_meet(s(0), s(1)), + rhs: retain(inter(s(0), s(1)), inter(hull(s(0)), hull(s(1)))), + }, + // PrunedModel/Convex/RetainConvex.lean:55 + ZippyLaw { + name: "path_set/convexSubtract_retained_mask", + spaces: 2, + paths: 0, + bytes: 0, + pre: vec![], + lhs: convex_subtract(s(0), s(1)), + rhs: retain(s(0), subtr(hull(s(0)), s(1))), + }, + ] +} + +// Not exported: +// PrunedModel/Convex/Algebra.lean:14 path_set/same_equiv: conclusion is not an equation of spaces (Iff) +// PrunedModel/Convex/Algebra.lean:16 path_set/mem_convexMeet: conclusion is not an equation of spaces (Iff) +// PrunedModel/Convex/Algebra.lean:20 path_set/mem_convexSubtract: conclusion is not an equation of spaces (Iff) +// PrunedModel/Convex/Algebra.lean:27 path_set/hull_max: hypothesis is an equation not of spaces +// PrunedModel/Convex/Algebra.lean:108 path_set/convexMeet_zero: conclusion is not an equation of spaces (Iff) +// PrunedModel/Convex/Algebra.lean:114 path_set/convexSubtract_zero: conclusion is not an equation of spaces (Iff) +// PrunedModel/Convex/Algebra.lean:125 path_set/convexSubtract_identity: conclusion is not an equation of spaces (Iff) +// PrunedModel/Convex/Algebra.lean:136 path_set/convexMeet_ordinary: conclusion is not an equation of spaces (Iff) +// PrunedModel/Convex/Algebra.lean:143 path_set/convexSubtract_masks: conclusion is not an equation of spaces (And) +// PrunedModel/Convex/Boolean.lean:0 path_set/ConvexFormula.brecOn.eq: binder motive : PrunedModel.Convex.ConvexFormula → Sort u +// PrunedModel/Convex/Boolean.lean:12 path_set/tipChoices_length: binder xs : List PathMapModel.Path +// PrunedModel/Convex/Boolean.lean:17 path_set/tipChoices_subset: binder xs : List PathMapModel.Path +// PrunedModel/Convex/Boolean.lean:30 path_set/tipChoices_select: binder xs : List PathMapModel.Path +// PrunedModel/Convex/Boolean.lean:42 path_set/tipChoices_distinct: binder xs : List PathMapModel.Path +// PrunedModel/Convex/Boolean.lean:66 path_set/pruningFamily_length: conclusion is not an equation of spaces (equation of Nat) +// PrunedModel/Convex/Boolean.lean:69 path_set/pruningFamily_distinct: conclusion is not an equation of spaces (List.Pairwise) +// PrunedModel/Convex/Boolean.lean:77 path_set/pruningFamily_complete: conclusion is not an equation of spaces (Exists) +// PrunedModel/Convex/Boolean.lean:84 path_set/pruningFamily_sound: hypothesis is membership in something other than a space +// PrunedModel/Convex/Boolean.lean:116 path_set/ConvexFormula.tips_subset: binder v : Nat → PrunedModel.PathSpace +// PrunedModel/Convex/Boolean.lean:119 path_set/ConvexFormula.interpret_correct: binder v : Nat → PrunedModel.PathSpace +// PrunedModel/Convex/Boolean.lean:149 path_set/ConvexFormula.transfer: binder e : PrunedModel.Convex.ConvexFormula +// PrunedModel/Convex/Checks.lean:11 path_set/convex_counterexample_meet_monotone: conclusion is not an equation of spaces (And) +// PrunedModel/Convex/Checks.lean:14 path_set/convex_counterexample_subtract_monotone: conclusion is not an equation of spaces (And) +// PrunedModel/Convex/Checks.lean:17 path_set/convex_counterexample_absorption: conclusion is not an equation of spaces (equation of Bool) +// PrunedModel/Convex/Checks.lean:19 path_set/convex_counterexample_union_distribution: conclusion is not an equation of spaces (equation of Bool) +// PrunedModel/Convex/Checks.lean:22 path_set/convex_counterexample_partition: conclusion is not an equation of spaces (equation of Bool) +// PrunedModel/Convex/Checks.lean:25 path_set/convex_counterexample_ordinary_intersection: conclusion is not an equation of spaces (equation of Bool) +// PrunedModel/Convex/Checks.lean:28 path_set/convex_counterexample_source_union: conclusion is not an equation of spaces (equation of Bool) +// PrunedModel/Convex/Checks.lean:31 path_set/convex_counterexample_intersection_distribution: conclusion is not an equation of spaces (equation of Bool) +// PrunedModel/Convex/Checks.lean:34 path_set/convex_counterexample_hull_mask: conclusion is not an equation of spaces (equation of Bool) +// PrunedModel/Convex/Checks.lean:37 path_set/convex_counterexample_basis_mask: conclusion is not an equation of spaces (equation of Bool) +// PrunedModel/Convex/Checks.lean:40 path_set/convex_counterexample_relative_complement: conclusion is not an equation of spaces (And) +// PrunedModel/Convex/Checks.lean:45 path_set/convex_counterexample_compatible_distribution: conclusion is not an equation of spaces (And) +// PrunedModel/Convex/Checks.lean:56 path_set/convex_cascade_example: conclusion is not an equation of spaces (And) +// PrunedModel/Convex/Checks.lean:61 path_set/convex_supporting_interior_example: conclusion is not an equation of spaces (And) +// PrunedModel/Convex/Checks.lean:71 path_set/ConvexFormula.meet_distributes: binder v : Nat → PrunedModel.PathSpace +// PrunedModel/Convex/Checks.lean:75 path_set/ConvexFormula.join_distributes: binder v : Nat → PrunedModel.PathSpace +// PrunedModel/Convex/Checks.lean:79 path_set/ConvexFormula.complement_join: binder v : Nat → PrunedModel.PathSpace +// PrunedModel/Convex/Checks.lean:83 path_set/ConvexFormula.complement_meet: binder v : Nat → PrunedModel.PathSpace +// PrunedModel/Convex/Checks.lean:87 path_set/ConvexFormula.double_complement: binder v : Nat → PrunedModel.PathSpace +// PrunedModel/Convex/Checks.lean:91 path_set/ConvexFormula.deMorgan_meet: binder v : Nat → PrunedModel.PathSpace +// PrunedModel/Convex/Checks.lean:95 path_set/ConvexFormula.deMorgan_join: binder v : Nat → PrunedModel.PathSpace +// PrunedModel/Convex/Checks.lean:99 path_set/ConvexFormula.absorption_meet: binder v : Nat → PrunedModel.PathSpace +// PrunedModel/Convex/Checks.lean:103 path_set/ConvexFormula.absorption_join: binder v : Nat → PrunedModel.PathSpace +// PrunedModel/Convex/Closed.lean:35 path_set/closed_iff_completion: conclusion is not an equation of spaces (Iff) +// PrunedModel/Convex/Closed.lean:44 path_set/closed_iff_branches: conclusion is not an equation of spaces (Iff) +// PrunedModel/Convex/Closed.lean:47 path_set/closed_congr: conclusion is not an equation of spaces (Iff) +// PrunedModel/Convex/Closed.lean:66 path_set/completion_least: conclusion is not an equation of spaces (Iff) +// PrunedModel/Convex/Closed.lean:106 path_set/closed_union_iff: conclusion is not an equation of spaces (Iff) +// PrunedModel/Convex/Closed.lean:116 path_set/completion_pair_witness: conclusion is not an equation of spaces (Iff) +// PrunedModel/Convex/Closed.lean:120 path_set/closed_range_lcp: conclusion is not an equation of spaces (Iff) +// PrunedModel/Convex/Closed.lean:125 path_set/closed_range_branches: conclusion is not an equation of spaces (Iff) +// PrunedModel/Convex/Closed.lean:131 path_set/closed_range_divergence: conclusion is not an equation of spaces (Iff) +// PrunedModel/Convex/Closed.lean:203 path_set/closed_join_least: conclusion is not an equation of spaces (Iff) +// PrunedModel/Convex/Closed.lean:232 path_set/completion_insert_new: conclusion is not an equation of spaces (And) +// PrunedModel/Convex/Closed.lean:245 path_set/completion_anti_exchange: conclusion is not an equation of spaces (¬) +// PrunedModel/Convex/ClosedChecks.lean:8 path_set/completion_not_union_preserving: conclusion is not an equation of spaces (equation of Bool) +// PrunedModel/Convex/ClosedChecks.lean:11 path_set/completion_not_inter_preserving: conclusion is not an equation of spaces (equation of Bool) +// PrunedModel/Convex/ClosedChecks.lean:14 path_set/completion_retain_bound_strict: conclusion is not an equation of spaces (equation of Bool) +// PrunedModel/Convex/ClosedChecks.lean:17 path_set/completion_raffinate_bound_strict: conclusion is not an equation of spaces (equation of Bool) +// PrunedModel/Convex/ClosedChecks.lean:20 path_set/completion_convexMeet_bound_strict: conclusion is not an equation of spaces (equation of Bool) +// PrunedModel/Convex/ClosedChecks.lean:24 path_set/completion_convexSubtract_bound_strict: conclusion is not an equation of spaces (equation of Bool) +// PrunedModel/Convex/ClosedChecks.lean:28 path_set/closed_restrict_needs_closed_mask: conclusion is not an equation of spaces (And) +// PrunedModel/Convex/ClosedChecks.lean:32 path_set/lcp_not_intersection: conclusion is not an equation of spaces (equation of Bool) +// PrunedModel/Convex/ClosedChecks.lean:35 path_set/lcp_not_lattice_absorption: conclusion is not an equation of spaces (equation of Bool) +// PrunedModel/Convex/ClosedChecks.lean:38 path_set/lcp_inter_bound_strict: conclusion is not an equation of spaces (equation of Bool) +// PrunedModel/Convex/ClosedChecks.lean:41 path_set/closed_lattice_not_distributive: conclusion is not an equation of spaces (a let) +// PrunedModel/Convex/ClosedChecks.lean:46 path_set/closed_lattice_not_modular: conclusion is not an equation of spaces (a let) +// PrunedModel/Convex/ClosedChecks.lean:52 path_set/lcp_retain_bound_strict: conclusion is not an equation of spaces (equation of Bool) +// PrunedModel/Convex/ClosedChecks.lean:56 path_set/completion_not_determined_by_hull: conclusion is not an equation of spaces (And) +// PrunedModel/Convex/ClosedChecks.lean:62 path_set/lcp_not_completed_divergence: conclusion is not an equation of spaces (equation of Bool) +// PrunedModel/Convex/ClosedChecks.lean:65 path_set/lcpLE_not_inclusion: conclusion is not an equation of spaces (And) +// PrunedModel/Convex/ClosedChecks.lean:68 path_set/lcpLE_not_coverage: conclusion is not an equation of spaces (And) +// PrunedModel/Convex/ClosedChecks.lean:71 path_set/closure_does_not_add_intermediate_prefixes: conclusion is not an equation of spaces (And) +// PrunedModel/Convex/ClosedGeometry.lean:6 path_set/completion_covered: conclusion is not an equation of spaces (Exists) +// PrunedModel/Convex/ClosedGeometry.lean:22 path_set/closed_basis_prefix: conclusion is not an equation of spaces (equation of Bool) +// PrunedModel/Convex/ClosedGeometry.lean:36 path_set/basis_closed: path term mentions PrunedModel.Convex.commonPrefix +// PrunedModel/Convex/ClosedGeometry.lean:49 path_set/commonPrefix_completion: conclusion is not an equation of spaces (equation of PathMapModel.Path) +// PrunedModel/Convex/ClosedGeometry.lean:63 path_set/basis_completion: path term mentions PrunedModel.Convex.commonPrefix +// PrunedModel/Convex/ClosedGeometry.lean:70 path_set/hull_not_branch: conclusion is not an equation of spaces (¬) +// PrunedModel/Convex/ClosedGeometry.lean:101 path_set/completion_generators: conclusion is not an equation of spaces (Iff) +// PrunedModel/Convex/ClosedGeometry.lean:120 path_set/completion_equiv_generators: conclusion is not an equation of spaces (Iff) +// PrunedModel/Convex/ClosedGeometry.lean:133 path_set/completion_cardinality: conclusion is not an equation of spaces (LE.le) +// PrunedModel/Convex/ClosedGeometry.lean:142 path_set/completion_cardinality_linear: conclusion is not an equation of spaces (And) +// PrunedModel/Convex/ClosedOperators.lean:146 path_set/lcpLE_refl_iff: conclusion is not an equation of spaces (Iff) +// PrunedModel/Convex/ClosedOperators.lean:149 path_set/lcpLE_closed: hypothesis mentions PrunedModel.Convex.LcpLE +// PrunedModel/Convex/ClosedOperators.lean:152 path_set/lcpLE_antisymm: hypothesis mentions PrunedModel.Convex.LcpLE +// PrunedModel/Convex/ClosedOperators.lean:155 path_set/lcpLE_trans: hypothesis mentions PrunedModel.Convex.LcpLE +// PrunedModel/Convex/ClosedOperators.lean:160 path_set/lcpLE_product_left: conclusion is not an equation of spaces (PrunedModel.Convex.LcpLE) +// PrunedModel/Convex/ClosedOperators.lean:163 path_set/lcpLE_product_right: conclusion is not an equation of spaces (PrunedModel.Convex.LcpLE) +// PrunedModel/Convex/ClosedOperators.lean:167 path_set/lcpLE_product_iff: conclusion is not an equation of spaces (Iff) +// PrunedModel/Convex/ClosedOperators.lean:174 path_set/lcpLE_empty: conclusion is not an equation of spaces (PrunedModel.Convex.LcpLE) +// PrunedModel/Convex/ClosedOperators.lean:177 path_set/lcpLE_iff: conclusion is not an equation of spaces (Iff) +// PrunedModel/Convex/Geometry.lean:11 path_set/retain_lower: hypothesis is an equation not of spaces +// PrunedModel/Convex/Geometry.lean:16 path_set/retain_convex: hypothesis mentions PrunedModel.Convex.IsConvex +// PrunedModel/Convex/Geometry.lean:20 path_set/retain_prefixClosed: hypothesis mentions PrunedModel.Convex.IsPrefixClosed +// PrunedModel/Convex/Geometry.lean:23 path_set/convexMeet_convex: hypothesis mentions PrunedModel.Convex.IsConvex +// PrunedModel/Convex/Geometry.lean:29 path_set/convexSubtract_convex: hypothesis mentions PrunedModel.Convex.IsConvex +// PrunedModel/Convex/Geometry.lean:31 path_set/convexMeet_prefixClosed: hypothesis mentions PrunedModel.Convex.IsPrefixClosed +// PrunedModel/Convex/Geometry.lean:35 path_set/convexSubtract_prefixClosed: hypothesis mentions PrunedModel.Convex.IsPrefixClosed +// PrunedModel/Convex/Geometry.lean:111 path_set/hull_surviving_diff: conclusion is not an equation of spaces (Membership.mem) +// PrunedModel/Convex/Map.lean:8 path_set/mem_ofMap: binder V : Type +// PrunedModel/Convex/Morphisms.lean:18 path_set/mem_hull_max: conclusion is not an equation of spaces (Iff) +// PrunedModel/Convex/Morphisms.lean:27 path_set/hull_unwrap: conclusion is not an equation of spaces (Iff) +// PrunedModel/Convex/Morphisms.lean:39 path_set/retain_unwrap: conclusion is not an equation of spaces (Iff) +// PrunedModel/Convex/Morphisms.lean:64 path_set/code_prefix: conclusion is not an equation of spaces (Iff) +// PrunedModel/Convex/Morphisms.lean:77 path_set/product_at: conclusion is not an equation of spaces (Iff) +// PrunedModel/Convex/Morphisms.lean:87 path_set/hull_product_at: conclusion is not an equation of spaces (Iff) +// PrunedModel/Convex/Morphisms.lean:99 path_set/convexMeet_product_at: conclusion is not an equation of spaces (Iff) +// PrunedModel/Convex/Morphisms.lean:109 path_set/convexSubtract_product_at: conclusion is not an equation of spaces (Iff) +// PrunedModel/Convex/Order.lean:6 path_set/convexLE_refl: conclusion is not an equation of spaces (PrunedModel.Convex.ConvexLE) +// PrunedModel/Convex/Order.lean:7 path_set/convexLE_trans: hypothesis mentions PrunedModel.Convex.ConvexLE +// PrunedModel/Convex/Order.lean:9 path_set/convexLE_antisymm: hypothesis mentions PrunedModel.Convex.ConvexLE +// PrunedModel/Convex/Order.lean:12 path_set/convexLE_iff_meet: conclusion is not an equation of spaces (Iff) +// PrunedModel/Convex/Order.lean:22 path_set/convexMeet_glb: conclusion is not an equation of spaces (Iff) +// PrunedModel/Convex/Order.lean:39 path_set/convexSubtract_universal: conclusion is not an equation of spaces (Iff) +// PrunedModel/Convex/Order.lean:51 path_set/convexMeet_mono: hypothesis mentions PrunedModel.Convex.ConvexLE +// PrunedModel/Convex/Order.lean:55 path_set/convexSubtract_deflationary: conclusion is not an equation of spaces (PrunedModel.Convex.ConvexLE) +// PrunedModel/Convex/Order.lean:58 path_set/convexSubtract_mono: hypothesis mentions PrunedModel.Convex.ConvexLE +// PrunedModel/Convex/Order.lean:62 path_set/convexSubtract_antitone: conclusion is not an equation of spaces (PrunedModel.Convex.ConvexLE) +// PrunedModel/Convex/Order.lean:70 path_set/convex_union_lub: conclusion is not an equation of spaces (Iff) +// PrunedModel/Convex/Order.lean:78 path_set/convex_compatible: conclusion is not an equation of spaces (Iff) +// PrunedModel/Convex/Order.lean:105 path_set/pruning_order: conclusion is not an equation of spaces (Iff) +// PrunedModel/Convex/Order.lean:114 path_set/pruning_injective: conclusion is not an equation of spaces (Iff) +// PrunedModel/Convex/Order.lean:122 path_set/convexSubtract_faithful: conclusion is not an equation of spaces (Iff) +// PrunedModel/Convex/Order.lean:140 path_set/mem_interMany: binder bs : List PrunedModel.PathSpace +// PrunedModel/Convex/Order.lean:146 path_set/hull_convexMeetMany: binder bs : List PrunedModel.PathSpace +// PrunedModel/Convex/Order.lean:152 path_set/convexMeetMany_normal: binder bs : List PrunedModel.PathSpace +// PrunedModel/Convex/Order.lean:163 path_set/convex_normal_form: binder bs : List PrunedModel.PathSpace +// PrunedModel/Convex/Order.lean:172 path_set/convexSubtractMany_normal: binder masks : List PrunedModel.PathSpace +// PrunedModel/Convex/Order.lean:178 path_set/convex_many_normal_form: binder bs : List PrunedModel.PathSpace +// PrunedModel/Convex/PathSetAlgebra.lean:16 path_set/divergence_covered_marks: hypothesis is a ∀ +// PrunedModel/Convex/PathSetAlgebra.lean:56 path_set/branch_second_subset: conclusion is not an equation of spaces (Membership.mem) +// PrunedModel/Convex/PathSetAlgebra.lean:65 path_set/divergence_four_point_absorption: conclusion is not an equation of spaces (And) +// PrunedModel/Convex/PathSetAlgebra.lean:75 path_set/branch_probe_exchange: conclusion is not an equation of spaces (And) +// PrunedModel/Convex/PathSetAlgebra.lean:91 path_set/divergence_symmetric_difference: conclusion is not an equation of spaces (Membership.mem) +// PrunedModel/Convex/PathSetAlgebra.lean:100 path_set/branch_intersection_lower: conclusion is not an equation of spaces (And) +// PrunedModel/Convex/PathSetAlgebra.lean:108 path_set/branch_sandwich_upper: conclusion is not an equation of spaces (Membership.mem) +// PrunedModel/Convex/PathSetAlgebra.lean:112 path_set/child_of_covered: hypothesis mentions Exists +// PrunedModel/Convex/PathSetAlgebra.lean:118 path_set/divergence_interior_attribution: conclusion is not an equation of spaces (Or) +// PrunedModel/Convex/PathSetCardinality.lean:6 path_set/count_mono: hypothesis is a ∀ +// PrunedModel/Convex/PathSetCardinality.lean:9 path_set/count_congr: conclusion is not an equation of spaces (equation of Nat) +// PrunedModel/Convex/PathSetCardinality.lean:12 path_set/equiv_iff: conclusion is not an equation of spaces (Iff) +// PrunedModel/Convex/PathSetCardinality.lean:16 path_set/subset_iff: conclusion is not an equation of spaces (Iff) +// PrunedModel/Convex/PathSetCardinality.lean:19 path_set/count_eq_zero: conclusion is not an equation of spaces (Iff) +// PrunedModel/Convex/PathSetCardinality.lean:22 path_set/count_singleton: conclusion is not an equation of spaces (equation of Nat) +// PrunedModel/Convex/PathSetCardinality.lean:34 path_set/count_union_le: conclusion is not an equation of spaces (LE.le) +// PrunedModel/Convex/PathSetCardinality.lean:43 path_set/count_relation: binder r : PathMapModel.Path → PathMapModel.Path → Prop +// PrunedModel/Convex/PathSetCardinality.lean:70 path_set/antichain_covered_count: hypothesis is a ∀ +// PrunedModel/Convex/PathSetCardinality.lean:78 path_set/output_hull_cardinality: conclusion is not an equation of spaces (LE.le) +// PrunedModel/Convex/PathSetCardinality.lean:93 path_set/double_covered_count: hypothesis is a ∀ +// PrunedModel/Convex/PathSetCardinality.lean:145 path_set/maximal_branch_double: conclusion is not an equation of spaces (LE.le) +// PrunedModel/Convex/PathSetCardinality.lean:161 path_set/maximal_branch_count: conclusion is not an equation of spaces (LE.le) +// PrunedModel/Convex/PathSetCardinality.lean:165 path_set/branch_iter_leaf_weight: binder n : Nat +// PrunedModel/Convex/PathSetCardinality.lean:177 path_set/branch_leaf_bound: binder n : Nat +// PrunedModel/Convex/PathSetCertificates.lean:13 path_set/height_congr: conclusion is not an equation of spaces (equation of Nat) +// PrunedModel/Convex/PathSetCertificates.lean:18 path_set/covers_iff: conclusion is not an equation of spaces (Iff) +// PrunedModel/Convex/PathSetCertificates.lean:21 path_set/basis_covers: conclusion is not an equation of spaces (equation of Bool) +// PrunedModel/Convex/PathSetCertificates.lean:38 path_set/output_branches: conclusion is not an equation of spaces (And) +// PrunedModel/Convex/PathSetCertificates.lean:43 path_set/no_nonempty_branch_fixed_point: conclusion is not an equation of spaces (equation of Bool) +// PrunedModel/Convex/PathSetCertificates.lean:49 path_set/count_eq_one: conclusion is not an equation of spaces (Iff) +// PrunedModel/Convex/PathSetCertificates.lean:59 path_set/singleton_prefix_test: conclusion is not an equation of spaces (Iff) +// PrunedModel/Convex/PathSetCertificates.lean:73 path_set/zero_criterion_check: conclusion is not an equation of spaces (equation of Bool) +// PrunedModel/Convex/PathSetDepth.lean:31 path_set/height_le: binder n : Nat +// PrunedModel/Convex/PathSetDepth.lean:35 path_set/length_le_height: conclusion is not an equation of spaces (LE.le) +// PrunedModel/Convex/PathSetDepth.lean:38 path_set/height_attained: conclusion is not an equation of spaces (Exists) +// PrunedModel/Convex/PathSetDepth.lean:46 path_set/divergence_depth: conclusion is not an equation of spaces (LT.lt) +// PrunedModel/Convex/PathSetDepth.lean:56 path_set/branch_iter_depth: binder n : Nat +// PrunedModel/Convex/PathSetDepth.lean:66 path_set/branch_depth_nilpotence: mentions PrunedModel.Convex.branchIter +// PrunedModel/Convex/PathSetDepth.lean:72 path_set/branch_no_fixed_point: conclusion is not an equation of spaces (¬) +// PrunedModel/Convex/PathSetDepth.lean:92 path_set/singleton_existing_branches: conclusion is not an equation of spaces (Membership.mem) +// PrunedModel/Convex/PathSetExtrema.lean:35 path_set/hull_covers: conclusion is not an equation of spaces (Exists) +// PrunedModel/Convex/PathSetExtrema.lean:51 path_set/basis_below: conclusion is not an equation of spaces (Exists) +// PrunedModel/Convex/PathSetExtrema.lean:67 path_set/hull_nonempty: conclusion is not an equation of spaces (Iff) +// PrunedModel/Convex/PathSetExtrema.lean:76 path_set/basis_nonempty: conclusion is not an equation of spaces (Iff) +// PrunedModel/Convex/PathSetExtrema.lean:105 path_set/mem_restrict: conclusion is not an equation of spaces (Iff) +// PrunedModel/Convex/PathSetExtrema.lean:121 path_set/hull_cofinal: hypothesis is a ∀ +// PrunedModel/Convex/PathSetExtrema.lean:147 path_set/basis_coinitial: hypothesis is a ∀ +// PrunedModel/Convex/PathSetGeometry.lean:66 path_set/mem_divergence_children: conclusion is not an equation of spaces (Iff) +// PrunedModel/Convex/PathSetGeometry.lean:76 path_set/branch_sandwich_lower: conclusion is not an equation of spaces (Membership.mem) +// PrunedModel/Convex/PathSetGeometry.lean:85 path_set/divergence_four_point_exchange: conclusion is not an equation of spaces (Or) +// PrunedModel/Convex/PathSetGeometry.lean:100 path_set/divergence_same_side_bound: conclusion is not an equation of spaces (And) +// PrunedModel/Convex/PathSetGeometry.lean:106 path_set/divergence_output_closed: conclusion is not an equation of spaces (Membership.mem) +// PrunedModel/Convex/PathSetGeometry.lean:111 path_set/divergence_output_branches: conclusion is not an equation of spaces (And) +// PrunedModel/Convex/PathSetGeometry.lean:117 path_set/mem_interior: conclusion is not an equation of spaces (Iff) +// PrunedModel/Convex/PathSetLCP.lean:96 path_set/mem_lcpProduct: conclusion is not an equation of spaces (Iff) +// PrunedModel/Convex/PathSetLCP.lean:141 path_set/lcp_output_covered: conclusion is not an equation of spaces (Exists) +// PrunedModel/Convex/PathSetMasks.lean:34 path_set/mem_retain: conclusion is not an equation of spaces (Iff) +// PrunedModel/Convex/PathSetMasks.lean:38 path_set/mem_raffinate: conclusion is not an equation of spaces (Iff) +// PrunedModel/Convex/PathSetMasks.lean:125 path_set/divergence_raffination: conclusion is not an equation of spaces (Membership.mem) +// PrunedModel/Convex/PathSetPowers.lean:19 path_set/product_nonempty: conclusion is not an equation of spaces (Ne) +// PrunedModel/Convex/PathSetPowers.lean:24 path_set/power_nonempty: binder n : Nat +// PrunedModel/Convex/PathSetPowers.lean:32 path_set/powerSum_succ: binder n : Nat +// PrunedModel/Convex/PathSetPowers.lean:52 path_set/prefix_code_powers: binder m : Nat +// PrunedModel/Convex/PathSetPowers.lean:75 path_set/general_product: mentions ite +// PrunedModel/Convex/PathSetProduct.lean:16 path_set/mem_proper_overlap: binder f : PathMapModel.Path → PathMapModel.Path → PrunedModel.PathSpace +// PrunedModel/Convex/PathSetProduct.lean:37 path_set/mem_leftOverlap: conclusion is not an equation of spaces (Iff) +// PrunedModel/Convex/PathSetProduct.lean:45 path_set/mem_rightOverlap: conclusion is not an equation of spaces (Iff) +// PrunedModel/Convex/PathSetProduct.lean:53 path_set/divergence_product_nonempty: mentions PrunedModel.Convex.PathSetLaws.leftOverlap +// PrunedModel/Convex/PathSetProofs.lean:7 path_set/basis_subset: conclusion is not an equation of spaces (Membership.mem) +// PrunedModel/Convex/PathSetProofs.lean:10 path_set/hull_subset: conclusion is not an equation of spaces (Membership.mem) +// PrunedModel/Convex/PathSetProofs.lean:29 path_set/basis_antichain: conclusion is not an equation of spaces (equation of Bool) +// PrunedModel/Convex/PathSetProofs.lean:33 path_set/hull_antichain: conclusion is not an equation of spaces (equation of Bool) +// PrunedModel/Convex/PathSetProofs.lean:37 path_set/divergence_intersection_bound: conclusion is not an equation of spaces (And) +// PrunedModel/Convex/PathSetProofs.lean:45 path_set/divergence_difference_upper: conclusion is not an equation of spaces (Membership.mem) +// PrunedModel/Convex/PathSetProofs.lean:50 path_set/divergence_difference_lower: conclusion is not an equation of spaces (Membership.mem) +// PrunedModel/Convex/PathSetProofs.lean:76 path_set/divergence_unique: binder f : PrunedModel.PathSpace → PrunedModel.PathSpace → PathMapModel.Path → Prop +// PrunedModel/Convex/PathSetProofs.lean:110 path_set/divergence_unique_three: binder f : PrunedModel.PathSpace → PrunedModel.PathSpace → PathMapModel.Path → Prop +// PrunedModel/Convex/PathSetProofs.lean:132 path_set/divergence_no_unit: conclusion is not an equation of spaces (Ne) +// PrunedModel/Convex/PathSetProofs.lean:137 path_set/divergence_not_associative: conclusion is not an equation of spaces (¬) +// PrunedModel/Convex/PathSetProofs.lean:192 path_set/divergence_covered_mono: hypothesis is a ∀ +// PrunedModel/Convex/PathSetProofs.lean:201 path_set/divergence_output_covered: conclusion is not an equation of spaces (Exists) +// PrunedModel/Convex/PathSetProofs.lean:206 path_set/divergence_nested_bound: conclusion is not an equation of spaces (And) +// PrunedModel/Convex/PathSetRecursive.lean:6 path_set/basis_nil: conclusion is not an equation of spaces (Iff) +// PrunedModel/Convex/PathSetRecursive.lean:15 path_set/basis_cons: conclusion is not an equation of spaces (Iff) +// PrunedModel/Convex/PathSetRecursive.lean:40 path_set/hull_cons: conclusion is not an equation of spaces (Iff) +// PrunedModel/Convex/PathSetRecursive.lean:62 path_set/head_empty: conclusion is not an equation of spaces (Iff) +// PrunedModel/Convex/PathSetRecursive.lean:74 path_set/hull_nil: conclusion is not an equation of spaces (Iff) +// PrunedModel/Convex/PathSetRecursive.lean:79 path_set/retain_nil: conclusion is not an equation of spaces (Iff) +// PrunedModel/Convex/PathSetRecursive.lean:82 path_set/retain_cons: conclusion is not an equation of spaces (Iff) +// PrunedModel/Convex/PathSetRecursive.lean:96 path_set/child_of_unwrap: conclusion is not an equation of spaces (PrunedModel.Convex.Child) +// PrunedModel/Convex/PathSetRecursive.lean:99 path_set/mem_head_expansion: binder f : PathMapModel.Path → PrunedModel.PathSpace +// PrunedModel/Convex/PathSetRecursive.lean:107 path_set/mem_common_head_expansion: binder f : PathMapModel.Path → PrunedModel.PathSpace +// PrunedModel/Convex/PathSetRecursive.lean:117 path_set/divergence_root_test: conclusion is not an equation of spaces (Iff) +// PrunedModel/Convex/PathSetRecursive.lean:127 path_set/basisRec_spec: binder n : Nat +// PrunedModel/Convex/PathSetRecursive.lean:147 path_set/hullRec_spec: binder n : Nat +// PrunedModel/Convex/PathSetRecursive.lean:170 path_set/divergenceRec_spec: binder n : Nat +// PrunedModel/Convex/PathSetRecursive.lean:205 path_set/retainRec_spec: binder n : Nat +// PrunedModel/Convex/PathSetRecursive.lean:234 path_set/basis_recursive: mentions PrunedModel.Convex.basisRec +// PrunedModel/Convex/PathSetRecursive.lean:239 path_set/hull_recursive: mentions PrunedModel.Convex.hullRec +// PrunedModel/Convex/PathSetRecursive.lean:244 path_set/divergence_recursive: mentions PrunedModel.Convex.divergenceRec +// PrunedModel/Convex/PathSetRecursive.lean:257 path_set/branch_recursive: mentions PrunedModel.Convex.divergenceRec +// PrunedModel/Convex/PathSetRecursive.lean:261 path_set/retain_recursive: mentions PrunedModel.Convex.retainRec +// PrunedModel/Convex/PathSetRoots.lean:13 path_set/divergence_empty_iff: conclusion is not an equation of spaces (Iff) +// PrunedModel/Convex/PathSetRoots.lean:31 path_set/comparable_antichains: hypothesis is a ∀ +// PrunedModel/Convex/PathSetRoots.lean:49 path_set/zero_criterion: conclusion is not an equation of spaces (Iff) +// PrunedModel/Convex/PathSetRoots.lean:79 path_set/commonPrefix_spec: conclusion is not an equation of spaces (Iff) +// PrunedModel/Convex/PathSetRoots.lean:94 path_set/first_divergence_covers_left: conclusion is not an equation of spaces (equation of Bool) +// PrunedModel/Convex/PathSetRoots.lean:119 path_set/first_divergence: path term mentions PrunedModel.Convex.commonPrefix +// PrunedModel/Convex/PathSetStructure.lean:6 path_set/mem_wrap: conclusion is not an equation of spaces (Iff) +// PrunedModel/Convex/PathSetStructure.lean:10 path_set/mem_unwrap: conclusion is not an equation of spaces (Iff) +// PrunedModel/Convex/PathSetStructure.lean:14 path_set/mem_product: conclusion is not an equation of spaces (Iff) +// PrunedModel/Convex/PathSetStructure.lean:18 path_set/divergence_unwrap: conclusion is not an equation of spaces (Iff) +// PrunedModel/Convex/PathSetStructure.lean:43 path_set/mem_head: conclusion is not an equation of spaces (Iff) +// PrunedModel/Convex/PathSetStructure.lean:49 path_set/mem_tails: conclusion is not an equation of spaces (Iff) +// PrunedModel/Convex/PathSetStructure.lean:53 path_set/child_head: conclusion is not an equation of spaces (Iff) +// PrunedModel/Convex/PathSetStructure.lean:75 path_set/divergence_output_heads: conclusion is not an equation of spaces (And) +// PrunedModel/Convex/PathSetStructure.lean:82 path_set/divergence_tails: conclusion is not an equation of spaces (Membership.mem) +// PrunedModel/Convex/PathSetUpdates.lean:6 path_set/singleton_bound: conclusion is not an equation of spaces (LE.le) +// PrunedModel/Convex/PathSetUpdates.lean:35 path_set/singleton_outputs_comparable: conclusion is not an equation of spaces (Or) +// PrunedModel/Convex/PathSetUpdates.lean:44 path_set/count_le_one_of_equal: hypothesis is a ∀ +// PrunedModel/Convex/PathSetUpdates.lean:52 path_set/singleton_output_hull: conclusion is not an equation of spaces (LE.le) +// PrunedModel/Convex/PathSetUpdates.lean:59 path_set/singleton_fresh_subset: conclusion is not an equation of spaces (Membership.mem) +// PrunedModel/Convex/PathSetUpdates.lean:71 path_set/singleton_branch_update: conclusion is not an equation of spaces (LE.le) +// PrunedModel/Convex/PathSetUpdates.lean:84 path_set/singleton_divergence_update: conclusion is not an equation of spaces (LE.le) +// PrunedModel/Convex/PathSetUpdates.lean:96 path_set/branch_count_length: binder a : List PathMapModel.Path +// PrunedModel/Convex/PathSetUpdates.lean:128 path_set/branch_count: conclusion is not an equation of spaces (LE.le) +// PrunedModel/Convex/PathSetUpdates.lean:135 path_set/output_cardinality: conclusion is not an equation of spaces (LE.le) +// PrunedModel/Convex/PathSets.lean:48 path_set/mem_bind: binder f : PathMapModel.Path → PrunedModel.PathSpace +// PrunedModel/Convex/PathSets.lean:78 path_set/mem_divergence: conclusion is not an equation of spaces (Iff) +// PrunedModel/Convex/PathSets.lean:110 path_set/divergence_mono: hypothesis is a ∀ +// PrunedModel/Convex/PathSets.lean:117 path_set/mem_basis: conclusion is not an equation of spaces (Iff) +// PrunedModel/Convex/PathSets.lean:121 path_set/mem_hull: conclusion is not an equation of spaces (Iff) +// PrunedModel/Convex/Pruning.lean:0 path_set/PruneTrace.brecOn: binder motive : (a : PrunedModel.PathSpace) → PrunedModel.Convex.PruneTrace tips a✝¹ a → Prop +// PrunedModel/Convex/Pruning.lean:12 path_set/mem_pruneStep: conclusion is not an equation of spaces (Iff) +// PrunedModel/Convex/Pruning.lean:16 path_set/prune_subset: binder n : Nat +// PrunedModel/Convex/Pruning.lean:21 path_set/prune_protected: binder n : Nat +// PrunedModel/Convex/Pruning.lean:26 path_set/prune_preserves_retain: binder n : Nat +// PrunedModel/Convex/Pruning.lean:38 path_set/prune_unsupported_length: binder n : Nat +// PrunedModel/Convex/Pruning.lean:57 path_set/convexPrune_stable: binder n : Nat +// PrunedModel/Convex/Pruning.lean:67 path_set/retain_prune_fixed: mentions PrunedModel.Convex.convexPruneStep +// PrunedModel/Convex/Pruning.lean:84 path_set/pruneMove_retain: hypothesis mentions PrunedModel.Convex.PruneMove +// PrunedModel/Convex/Pruning.lean:94 path_set/pruneTrace_invariant: hypothesis mentions PrunedModel.Convex.PruneTrace +// PrunedModel/Convex/Pruning.lean:102 path_set/prune_fixed_iff: mentions PrunedModel.Convex.convexPruneStep +// PrunedModel/Convex/Pruning.lean:113 path_set/convexPrune_confluent: hypothesis mentions PrunedModel.Convex.PruneTrace +// PrunedModel/Convex/Pruning.lean:119 path_set/pruneMove_decreases: hypothesis mentions PrunedModel.Convex.PruneMove +// PrunedModel/Convex/Pruning.lean:137 path_set/convexPrune_trace: binder n : Nat +// PrunedModel/Convex/Pruning.lean:144 path_set/convexPrune_join: hypothesis mentions PrunedModel.Convex.PruneTrace +// PrunedModel/Convex/Pruning.lean:155 path_set/convexMeetRec_correct: mentions PrunedModel.Convex.convexMeetRec +// PrunedModel/Convex/Pruning.lean:158 path_set/convexSubtractRec_correct: mentions PrunedModel.Convex.convexSubtractRec +// PrunedModel/Convex/Retain.lean:71 path_set/retain_universal: conclusion is not an equation of spaces (Iff) +// PrunedModel/Convex/Retain.lean:75 path_set/retain_identity: conclusion is not an equation of spaces (Iff) +// PrunedModel/Convex/Retain.lean:86 path_set/retain_restrict_empty: conclusion is not an equation of spaces (Iff) +// PrunedModel/Convex/Retain.lean:105 path_set/retain_subset_iff_restrict_empty: conclusion is not an equation of spaces (Iff) +// PrunedModel/Convex/Retain.lean:109 path_set/restrict_subset_iff_retain_empty: conclusion is not an equation of spaces (Iff) +// PrunedModel/Convex/Retain.lean:239 path_set/retain_mask_order: conclusion is not an equation of spaces (Iff) +// PrunedModel/Convex/Retain.lean:263 path_set/retain_mask_equiv: conclusion is not an equation of spaces (Iff) +// PrunedModel/Convex/Retain.lean:316 path_set/retain_count_bound: conclusion is not an equation of spaces (LE.le) +// PrunedModel/Convex/Retain.lean:323 path_set/restrict_mask_order: conclusion is not an equation of spaces (Iff) +// PrunedModel/Convex/Retain.lean:333 path_set/restrict_mask_equiv: conclusion is not an equation of spaces (Iff) +// PrunedModel/Convex/RetainChecks.lean:7 path_set/retain_function_example: conclusion is not an equation of spaces (And) +// PrunedModel/Convex/RetainChecks.lean:11 path_set/retain_not_commutative: conclusion is not an equation of spaces (equation of Bool) +// PrunedModel/Convex/RetainChecks.lean:14 path_set/retain_not_associative: conclusion is not an equation of spaces (equation of Bool) +// PrunedModel/Convex/RetainChecks.lean:17 path_set/retain_not_mask_intersection: conclusion is not an equation of spaces (equation of Bool) +// PrunedModel/Convex/RetainChecks.lean:20 path_set/retain_not_mask_difference: conclusion is not an equation of spaces (equation of Bool) +// PrunedModel/Convex/RetainChecks.lean:23 path_set/retain_not_hull_source: conclusion is not an equation of spaces (equation of Bool) +// PrunedModel/Convex/RetainChecks.lean:26 path_set/retain_not_basis_mask: conclusion is not an equation of spaces (equation of Bool) +// PrunedModel/Convex/RetainChecks.lean:29 path_set/retain_not_convexMeet_commutation: conclusion is not an equation of spaces (equation of Bool) +// PrunedModel/Convex/RetainChecks.lean:33 path_set/retain_divergence_bound_strict: conclusion is not an equation of spaces (equation of Bool) +// PrunedModel/Convex/RetainChecks.lean:37 path_set/retain_product_needs_prefix_code: conclusion is not an equation of spaces (equation of Bool) +// PrunedModel/Convex/Space.lean:18 path_set/mem_ofPaths: binder ps : List PathMapModel.Path +// PrunedModel/Convex/Space.lean:29 path_set/mem_keys: conclusion is not an equation of spaces (Iff) +// PrunedModel/Convex/Space.lean:31 path_set/ofPaths_keys: space literal mentions PrunedModel.PrunedMap.keys +// PrunedModel/Convex/Space.lean:49 path_set/mem_union: both sides translate to the same term +// PrunedModel/Convex/Space.lean:51 path_set/mem_union_left: conclusion is not an equation of spaces (Membership.mem) +// PrunedModel/Convex/Space.lean:53 path_set/mem_union_right: conclusion is not an equation of spaces (Membership.mem) +// PrunedModel/Convex/Space.lean:56 path_set/mem_inter: both sides translate to the same term +// PrunedModel/Convex/Space.lean:58 path_set/mem_diff: both sides translate to the same term +// PrunedModel/Convex/Space.lean:60 path_set/mem_append: both sides translate to the same term +// PrunedModel/Convex/Space.lean:68 path_set/ne_empty_iff: conclusion is not an equation of spaces (Iff) +// PrunedModel/Convex/Space.lean:73 path_set/ofPaths_nil: both sides translate to the same term +// PrunedModel/Convex/Space.lean:76 path_set/append_eq_union: both sides translate to the same term +// PrunedModel/Convex/Space.lean:78 path_set/ofPaths_cons: binder ps : List PathMapModel.Path +// PrunedModel/Convex/Space.lean:82 path_set/keys_eq_nil_iff: conclusion is not an equation of spaces (Iff) +// PrunedModel/Convex/Space.lean:86 path_set/keys_nodup: conclusion is not an equation of spaces (List.Nodup) +// PrunedModel/Convex/Space.lean:97 path_set/space_induction: binder motive : PrunedModel.PathSpace → Prop +// PrunedModel/Convex/Union.lean:6 path_set/hull_in_subset: conclusion is not an equation of spaces (Membership.mem) +// PrunedModel/Convex/Union.lean:10 path_set/hull_union_cases: conclusion is not an equation of spaces (Or) +// PrunedModel/Convex/Union.lean:16 path_set/convexMeet_union_subset: hypothesis mentions PrunedModel.Convex.IsPrefixClosed +// PrunedModel/Convex/Union.lean:24 path_set/convexMeet_union: hypothesis mentions PrunedModel.Convex.IsPrefixClosed +// PrunedModel/Convex/Union.lean:34 path_set/convexSubtract_union_source: hypothesis mentions PrunedModel.Convex.IsPrefixClosed diff --git a/differential/tests/algebraic.rs b/differential/tests/algebraic.rs index 4be1f4bc..2925f785 100644 --- a/differential/tests/algebraic.rs +++ b/differential/tests/algebraic.rs @@ -472,13 +472,13 @@ fn every_law_variable_has_something_to_bind_to() { /// Every generated law holds in the flat model, plain and in the substitution /// and congruence instances `check_laws` derives from it. /// -/// The laws are theorems about Zippy's operators, and `model.rs` is those +/// The laws are theorems about space and path-set operators, and `model.rs` is those /// operators' membership lemmas read as code, with no trie anywhere. So a /// failure here is never the crate: it is the Lean-to-Rust translation, the /// variable binding, the derivation, or the model -- exactly the parts of the /// harness that, if wrong, would make every law finding a false one. #[test] -fn zippy_laws_hold_in_the_model() { +fn generated_laws_hold_in_the_model() { use algebraic::laws::{instantiate, laws, substituted, Binding, Hyp, Instance}; use algebraic::routes::{eval, Route}; const CASES: usize = 3_000; @@ -501,6 +501,7 @@ fn zippy_laws_hold_in_the_model() { Hyp::Holds(b) => *b, Hyp::Mem(p, e, want) => model(e).contains_key(p) == *want, Hyp::Eq(l, r) => model(l) == model(r), + Hyp::Ne(l, r) => model(l) != model(r), }) }; for (i, law) in laws::<()>().iter().enumerate() { @@ -553,7 +554,7 @@ fn zippy_laws_hold_in_the_model() { /// Laws are checked for the set type only; see `laws.rs`. #[test] -fn zippy_laws_apply_to_the_set_type_only() { +fn generated_laws_apply_to_the_set_type_only() { assert!(!algebraic::laws::laws::<()>().is_empty()); assert!(algebraic::laws::laws::().is_empty()); assert!(algebraic::laws::laws::().is_empty()); @@ -677,3 +678,16 @@ fn current_layout_generates_every_expression_operator() { }); for kind in Kind::ALL { assert!(seen.contains(&kind), "never generated {kind:?}"); } } + +#[test] +fn path_set_laws_are_registered_without_name_collisions() { + let all = algebraic::laws::laws::<()>(); + let names: std::collections::BTreeSet<_> = all.iter().map(|law| law.name).collect(); + assert_eq!(names.len(), all.len()); + for name in ["basis_idempotent", "hull_idempotent", "divergence_comm", + "branches_union", "retain_self", "convexMeet_assoc", "convexSubtract_action", + "completion_idempotent", "lcp_associativity", "hull_of_antichain"] { + assert!(names.contains(format!("path_set/{name}").as_str()), "missing {name}"); + } + assert_eq!(all.len(), algebraic::zippy_laws::laws().len() + algebraic::path_set_laws::laws().len()); +} diff --git a/lean/LawExport.lean b/lean/LawExport.lean new file mode 100644 index 00000000..022cdb08 --- /dev/null +++ b/lean/LawExport.lean @@ -0,0 +1,429 @@ +import Lean + +/-! +Shared exporter for `ZippyLaws.lean` and `PathSetLaws.lean`. + +Read elaborated theorem types, preserve supported hypotheses, and reject proofs +that depend on `sorryAx`. Operators are translated by application head; only +finite-space literals and coercions are reduced. Path-set mode also recognizes +extensional equations and their finite-set predicates. Unsupported theorems +are listed with source locations and reasons in the generated output. +-/ + +open Lean Meta + +namespace LawExport + +inductive VarKind | space | path | byte + deriving BEq + +structure Config where + ns : Name + module : Name + submodules : Bool := false + generator : String + output : String + namePrefix : String := "" + ops : List (Name × String × List VarKind) + pathSets : Bool := false + +structure St where + config : Config + + vars : Std.HashMap FVarId (VarKind × Nat) := {} + nSpace : Nat := 0 + nPath : Nat := 0 + nByte : Nat := 0 + +abbrev M := StateT St (ExceptT String MetaM) + +def fail {α} (msg : String) : M α := throwThe String msg + +def liftMeta {α} (x : MetaM α) : M α := monadLift x + +def clean (e : Expr) : MetaM Expr := do + return (← instantiateMVars e).consumeMData.headBeta + +def spaceTy : Expr := mkConst `PrunedModel.Zippy.Space +def pathTy : Expr := mkApp (mkConst ``List [Level.zero]) (mkConst ``UInt8) +def byteTy : Expr := mkConst ``UInt8 + +/-- Which variable kind a type is, if any. Types are compared up to +definitional equality, so `Space`, `PrunedMap Unit`, `Path` and `List UInt8` +are all recognised. -/ +def kindOf (ty : Expr) : MetaM (Option VarKind) := do + let ty ← clean ty + if ty.isSort then return none + if ← isDefEq ty spaceTy then return some .space + if ← isDefEq ty pathTy then return some .path + if ← isDefEq ty byteTy then return some .byte + return none + +def headName (e : Expr) : String := + match e.getAppFn with + | .const n _ => toString n + | .fvar _ => "a local function" + | .lam .. => "a lambda" + | .proj s i _ => s!"projection {s}.{i}" + | .letE .. => "a let" + | .lit _ => "a literal" + | f => s!"{f.ctorName}" + +/-- What a space-typed term mentions that is outside the vocabulary. -/ +def outside (e : Expr) : String := s!"mentions {headName e}" + +def varOf (e : Expr) (k : VarKind) : M (Option Nat) := do + match e with + | .fvar id => + match (← get).vars.get? id with + | some (k', i) => if k' == k then return some i else fail s!"variable of the wrong kind" + | none => fail "unbound local" + | _ => return none + +def litByte (e : Expr) : M (Option Nat) := do + -- `OfNat.ofNat UInt8 n inst` + if e.isAppOfArity ``OfNat.ofNat 3 then + let ty ← liftMeta (clean (e.getArg! 0)) + if ty.isConstOf ``UInt8 then + match (← liftMeta (clean (e.getArg! 1))) with + | .lit (.natVal n) => return some (n % 256) + | _ => return none + return none + +partial def byteTerm (e : Expr) : M String := do + let e ← liftMeta (clean e) + if let some i ← varOf e .byte then return s!"bv({i})" + if let some n ← litByte e then return s!"lit({n})" + fail s!"byte term {outside e}" + +partial def pathTerm (e : Expr) : M String := do + let e ← liftMeta (clean e) + if let some i ← varOf e .path then return s!"pv({i})" + if e.isAppOfArity ``List.nil 1 then return "nil()" + if e.isAppOfArity ``List.cons 3 then + return s!"cons({← byteTerm (e.getArg! 1)}, {← pathTerm (e.getArg! 2)})" + if e.isAppOfArity ``HAppend.hAppend 6 then + return s!"app({← pathTerm (e.getArg! 4)}, {← pathTerm (e.getArg! 5)})" + if e.isAppOfArity ``List.append 3 then + return s!"app({← pathTerm (e.getArg! 1)}, {← pathTerm (e.getArg! 2)})" + fail s!"path term {outside e}" + +/-- The space operators: Lean name, Rust builder, and the kind of each +explicit argument. -/ +def zippyOps : List (Name × String × List VarKind) := + [ (`PrunedModel.Zippy.empty, "empty", []), + (`PrunedModel.Zippy.singleton, "singleton", [.path]), + (`PrunedModel.Zippy.union, "union", [.space, .space]), + (`PrunedModel.Zippy.inter, "inter", [.space, .space]), + (`PrunedModel.Zippy.subtr, "subtr", [.space, .space]), + (`PrunedModel.Zippy.restriction, "restriction", [.space, .space]), + (`PrunedModel.Zippy.raffination, "raffination", [.space, .space]), + (`PrunedModel.Zippy.wrap, "wrap", [.path, .space]), + (`PrunedModel.Zippy.unwrap, "unwrap", [.space, .path]), + (`PrunedModel.Zippy.head, "head", [.space]), + (`PrunedModel.Zippy.tailsUnion, "tails_union", [.space]), + (`PrunedModel.Zippy.tailsInter, "tails_inter", [.space]), + (`PrunedModel.Zippy.composition, "composition", [.space, .space]), + (`PrunedModel.Zippy.iterC, "iter_c", [.space, .space]) ] + +mutual +partial def spaceTerm (e : Expr) : M String := do + let e ← liftMeta (clean e) + if let some i ← varOf e .space then return s!"s({i})" + if (← get).config.pathSets then + if e.isAppOfArity `PrunedModel.Convex.ofPaths 1 then + return ← spaceList (e.getArg! 0) + if e.isAppOf ``Coe.coe || e.isAppOf ``CoeT.coe || e.isAppOf ``CoeHTCT.coe then + return ← spaceTerm (← liftMeta (whnf e)) + if e.isAppOfArity ``HAppend.hAppend 6 then + return s!"union({← spaceTerm (e.getArg! 4)}, {← spaceTerm (e.getArg! 5)})" + let .const f _ := e.getAppFn | fail s!"space term {outside e}" + let some (_, rust, kinds) := (← get).config.ops.find? (·.1 == f) | fail (outside e) + let args := e.getAppArgs + unless args.size == kinds.length do + fail s!"{f} applied to {args.size} arguments, expected {kinds.length}" + let mut out := #[] + for (a, k) in args.toList.zip kinds do + out := out.push (← anyTerm a k) + return s!"{rust}({", ".intercalate out.toList})" + +partial def spaceList (e : Expr) : M String := do + let e ← liftMeta (clean e) + if e.isAppOfArity ``List.nil 1 then return "empty()" + if e.isAppOfArity ``List.cons 3 then + let p ← pathTerm (e.getArg! 1) + let tail ← liftMeta (clean (e.getArg! 2)) + if tail.isAppOfArity ``List.nil 1 then return s!"singleton({p})" + return s!"union(singleton({p}), {← spaceList tail})" + fail s!"space literal {outside e}" + +partial def anyTerm (e : Expr) (k : VarKind) : M String := + match k with + | .space => spaceTerm e + | .path => pathTerm e + | .byte => byteTerm e +end + +/-- Translate a membership formula at an arbitrary path back to its space. +Only finite-set connectives are accepted. In particular, a space mentioning +that path cannot be lifted out of the quantifier. -/ +partial def membershipSpace (e p : Expr) : MetaM (Option Expr) := do + let e ← clean e + if e.isAppOfArity ``Membership.mem 5 then + if e.getArg! 4 == p then + let a := e.getArg! 3 + if (← kindOf (e.getArg! 1)) == some .space && !a.containsFVar p.fvarId! then + return some a + if e.isConstOf ``False then return some (mkConst `PrunedModel.Zippy.empty) + if e.isAppOfArity ``Eq 3 then + unless (← kindOf (e.getArg! 0)) == some .path do return none + let a := e.getArg! 1 + let b := e.getArg! 2 + let q := if a == p then b else if b == p then a else p + if !q.containsFVar p.fvarId! then + return some (mkApp (mkConst `PrunedModel.Zippy.singleton) q) + if e.isAppOfArity ``Or 2 || e.isAppOfArity ``And 2 then + let some a ← membershipSpace (e.getArg! 0) p | return none + let rhs ← clean (e.getArg! 1) + let neg := e.isAppOf ``And && rhs.isAppOfArity ``Not 1 + let some b ← membershipSpace (if neg then rhs.getArg! 0 else rhs) p | return none + let op := if neg then `PrunedModel.Zippy.subtr + else if e.isAppOf ``And then `PrunedModel.Zippy.inter else `PrunedModel.Zippy.union + return some (mkApp2 (mkConst op) a b) + return none + +/-- Extensional lifting is valid only when the quantified path is unrestricted: +no other binder (including hypotheses) may depend on it. -/ +def pointwiseEquation (xs : Array Expr) (body : Expr) : MetaM (Option (FVarId × Expr × Expr)) := do + unless body.isAppOfArity ``Iff 2 do return none + for p in xs do + unless (← kindOf (← inferType p)) == some .path do continue + if ← xs.anyM (fun x => return (← inferType x).containsFVar p.fvarId!) then continue + let some a ← membershipSpace (body.getArg! 0) p | continue + let some b ← membershipSpace (body.getArg! 1) p | continue + return some (p.fvarId!, a, b) + return none + +/-- Supported extensional relations, represented as equations of finite sets. +These are exact equivalences, so the same translation works for hypotheses. -/ +def relation (ty : Expr) : M (Option (String × String)) := do + let ty ← liftMeta (clean ty) + if ty.isAppOfArity `PrunedModel.Convex.Same 2 then + return some (← spaceTerm (ty.getArg! 0), ← spaceTerm (ty.getArg! 1)) + if ty.isAppOfArity `PrunedModel.Convex.Included 2 then + let a ← spaceTerm (ty.getArg! 0) + let b ← spaceTerm (ty.getArg! 1) + return some (s!"inter({a}, {b})", a) + if ty.isAppOfArity `PrunedModel.Convex.Antichain 1 then + let a ← spaceTerm (ty.getArg! 0) + return some (s!"basis({a})", a) + if ty.isAppOfArity `PrunedModel.Convex.IsClosed 1 then + let a ← spaceTerm (ty.getArg! 0) + return some (s!"completion({a})", a) + if ty.isAppOfArity ``Eq 3 then + unless (ty.getArg! 2).isConstOf ``Bool.true do return none + let t ← liftMeta (clean (ty.getArg! 1)) + if t.isAppOfArity `PrunedModel.Convex.equiv 2 then + return some (← spaceTerm (t.getArg! 0), ← spaceTerm (t.getArg! 1)) + if t.isAppOfArity `PrunedModel.Convex.subset 2 then + let a ← spaceTerm (t.getArg! 0) + let b ← spaceTerm (t.getArg! 1) + return some (s!"inter({a}, {b})", a) + if t.isAppOfArity `PrunedModel.Convex.covers 2 then + let a ← spaceTerm (t.getArg! 0) + let b ← spaceTerm (t.getArg! 1) + return some (s!"retain({a}, {b})", a) + if t.isAppOfArity `PrunedModel.Convex.prefixFree 1 then + let a ← spaceTerm (t.getArg! 0) + return some (s!"basis({a})", a) + if ty.isForall then + let pair ← liftMeta <| forallTelescope ty fun xs body => do + return (← pointwiseEquation xs body).map fun (_, a, b) => (a, b) + if let some (a, b) := pair then return some (← spaceTerm a, ← spaceTerm b) + return none + +/-- A hypothesis, as a precondition. -/ +def hypothesis (ty : Expr) : M String := do + let ty ← liftMeta (clean ty) + if (← get).config.pathSets then + if let some (a, b) ← relation ty then return s!"eq_space({a}, {b})" + if ty.isAppOfArity ``Ne 3 then + if (← liftMeta (kindOf (ty.getArg! 0))) == some .space then + return s!"ne_space({← spaceTerm (ty.getArg! 1)}, {← spaceTerm (ty.getArg! 2)})" + -- `a ≠ b` + if ty.isAppOfArity ``Ne 3 then + match ← liftMeta (kindOf (ty.getArg! 0)) with + | some .path => return s!"ne_path({← pathTerm (ty.getArg! 1)}, {← pathTerm (ty.getArg! 2)})" + | some .byte => return s!"ne_byte({← byteTerm (ty.getArg! 1)}, {← byteTerm (ty.getArg! 2)})" + | _ => fail "hypothesis is a disequation of neither paths nor bytes" + -- `p ∈ s` is `@Membership.mem Path Space inst s p`: collection first. + let memOf (m : Expr) : M (Option String) := do + let m ← liftMeta (clean m) + if m.isAppOfArity ``Membership.mem 5 then + unless (← liftMeta (kindOf (m.getArg! 1))) == some .space do + fail "hypothesis is membership in something other than a space" + return some s!"{← pathTerm (m.getArg! 4)}, {← spaceTerm (m.getArg! 3)}" + return none + if let some s ← memOf ty then return s!"mem({s})" + if ty.isAppOfArity ``Not 1 then + if let some s ← memOf (ty.getArg! 0) then return s!"not_mem({s})" + fail "hypothesis is a negation other than ∉" + if ty.isAppOfArity ``Eq 3 then + unless (← liftMeta (kindOf (ty.getArg! 0))) == some .space do + fail "hypothesis is an equation not of spaces" + return s!"eq_space({← spaceTerm (ty.getArg! 1)}, {← spaceTerm (ty.getArg! 2)})" + if ty.isForall then fail "hypothesis is a ∀" + fail s!"hypothesis {outside ty}" + +structure Law where + name : String + spaces : Nat + paths : Nat + bytes : Nat + pre : Array String + lhs : String + rhs : String + +def conclusionShape (e : Expr) : String := + match e.getAppFn with + | .const n _ => + if n == ``Iff then "Iff" else if n == ``Ne then "Ne" else if n == ``Not then "¬" + else if n == ``Eq then "an equation of another type" else toString n + | _ => headName e + +def translate (config : Config) (ty : Expr) : MetaM (Except String Law) := do + -- `forallTelescope`, not `…Reducing`: a conclusion like `p ∉ s` must not be + -- unfolded into another binder. + forallTelescope ty fun xs body => do + let lifted ← if config.pathSets then pointwiseEquation xs body else pure none + let go : M Law := do + let mut pre := #[] + for x in xs do + if let some (id, _, _) := lifted then + if x.fvarId! == id then continue + let decl ← liftMeta x.fvarId!.getDecl + let bty ← liftMeta (clean decl.type) + match ← liftMeta (kindOf bty) with + | some k => + let st ← get + let (i, st') := match k with + | .space => (st.nSpace, { st with nSpace := st.nSpace + 1 }) + | .path => (st.nPath, { st with nPath := st.nPath + 1 }) + | .byte => (st.nByte, { st with nByte := st.nByte + 1 }) + set { st' with vars := st'.vars.insert x.fvarId! (k, i) } + | none => + if ← liftMeta (isProp bty) then + pre := pre.push (← hypothesis bty) + else + fail s!"binder {decl.userName} : {← liftMeta (ppExpr bty)}" + let body ← liftMeta (clean body) + let pair ← match lifted with + | some (_, a, b) => pure (some (← spaceTerm a, ← spaceTerm b)) + | none => if config.pathSets then relation body else pure none + let (lhs, rhs) ← match pair with + | some p => pure p + | none => do + unless body.isAppOfArity ``Eq 3 do + fail s!"conclusion is not an equation of spaces ({conclusionShape body})" + unless (← liftMeta (kindOf (body.getArg! 0))) == some .space do + fail s!"conclusion is not an equation of spaces (equation of {← liftMeta (ppExpr (body.getArg! 0))})" + pure (← spaceTerm (body.getArg! 1), ← spaceTerm (body.getArg! 2)) + let st ← get + return { name := "", spaces := st.nSpace, paths := st.nPath, bytes := st.nByte, + pre, lhs, rhs } + match ← (go.run' { config }).run with + | .ok l => return .ok l + | .error e => return .error e + +def relName (config : Config) (n : Name) : String := + let comps := n.components.drop config.ns.components.length + ".".intercalate (comps.map toString) + +def skipName (env : Environment) (n : Name) : Bool := + n.isInternal || isPrivateName n || isAuxRecursor env n || isNoConfusion env n || + isMatcherCore env n || isRecCore env n || + n.components.any fun c => + let s := toString c + s == "eq_def" || s.startsWith "eq_" || s.startsWith "match_" || s.startsWith "proof_" || + (s.splitOn "_proof_").length > 1 || s.startsWith "_" || s == "inj" || s == "injEq" || + s == "sizeOf_spec" + +inductive Outcome + | law (l : Law) + | skip (reason : String) + +def run (config : Config) : MetaM String := do + let env ← getEnv + let some modIdx := env.getModuleIdx? config.module | throwError "{config.module} not imported" + let mut entries : Array (String × Nat × String × Outcome) := #[] + for (n, ci) in env.constants.toList do + unless config.ns.isPrefixOf n && n != config.ns do continue + let some sourceIdx := env.getModuleIdxFor? n | continue + let sourceModule := env.header.moduleNames[sourceIdx.toNat]! + unless sourceIdx == modIdx || (config.submodules && config.module.isPrefixOf sourceModule) do continue + let source := if config.submodules then + "/".intercalate (sourceModule.components.map toString) ++ ".lean" + else s!"{sourceModule.getString!}.lean" + let .thmInfo info := ci | continue + if skipName env n then continue + let line := match ← findDeclarationRanges? n with + | some r => r.selectionRange.pos.line + | none => 0 + let name := config.namePrefix ++ relName config n + let axioms ← collectAxioms n + let outcome ← + if axioms.contains ``sorryAx then pure (.skip "depends on sorryAx") + else match ← translate config info.type with + | .error e => pure (.skip e) + | .ok l => + if l.spaces > 4 then pure (.skip s!"{l.spaces} space variables (more than 4)") + else if l.lhs == l.rhs then pure (.skip "both sides translate to the same term") + else pure (.law { l with name }) + entries := entries.push (source, line, name, outcome) + entries := entries.qsort fun a b => a.1 < b.1 || (a.1 == b.1 && (a.2.1 < b.2.1 || (a.2.1 == b.2.1 && a.2.2.1 < b.2.2.1))) + let laws := entries.filterMap fun + | (source, line, _, .law l) => some (source, line, l) + | _ => none + let skips := entries.filterMap fun + | (source, line, name, .skip r) => some (source, line, name, r) + | _ => none + let mut out := "" + let origin := "/".intercalate (config.module.components.map toString) + out := out ++ s!"// @generated by lean/{config.generator}.lean from lean/{origin}{if config.submodules then "/*.lean" else ".lean"}.\n" + out := out ++ "// Do not edit by hand. Regenerate with:\n" + out := out ++ s!"// cd lean && lake env lean --run {config.generator}.lean > ../differential/src/algebraic/{config.output}.rs\n" + out := out ++ "//\n" + out := out ++ s!"// Every entry is a theorem of {config.ns}, checked sorry-free when generated.\n" + out := out ++ s!"// {laws.size} exported, {skips.size} not exported (listed at the end).\n" + out := out ++ "\n" + out := out ++ "use super::laws::zippy::*;\n" + out := out ++ "\n" + out := out ++ "pub fn laws() -> Vec {\n" + out := out ++ " vec![\n" + for (source, line, l) in laws do + out := out ++ s!" // {source}:{line}\n" + out := out ++ " ZippyLaw {\n" + out := out ++ s!" name: \"{l.name}\",\n" + out := out ++ s!" spaces: {l.spaces},\n" + out := out ++ s!" paths: {l.paths},\n" + out := out ++ s!" bytes: {l.bytes},\n" + out := out ++ s!" pre: vec![{", ".intercalate l.pre.toList}],\n" + out := out ++ s!" lhs: {l.lhs},\n" + out := out ++ s!" rhs: {l.rhs},\n" + out := out ++ " },\n" + out := out ++ " ]\n" + out := out ++ "}\n" + out := out ++ "\n" + out := out ++ "// Not exported:\n" + for (source, line, name, r) in skips do + out := out ++ s!"// {source}:{line} {name}: {r}\n" + return out + +def generate (config : Config) : IO Unit := do + initSearchPath (← findSysroot) + let env ← importModules #[{ module := config.module }] {} (trustLevel := 1024) + let (out, _) ← ((run config).run' {} {}).toIO + { fileName := s!"<{config.generator}>", fileMap := default, maxHeartbeats := 0 } { env } + IO.print out + +end LawExport diff --git a/lean/LawExport/Checks.lean b/lean/LawExport/Checks.lean new file mode 100644 index 00000000..36e873aa --- /dev/null +++ b/lean/LawExport/Checks.lean @@ -0,0 +1,47 @@ +import LawExport +import PrunedModel.Convex + +/-! Regression checks for the logical boundary of theorem export. -/ +open Lean Meta LawExport PrunedModel + +namespace LawExport.Checks + +private def config : Config := { + ns := `PrunedModel.Convex, module := `PrunedModel.Convex + generator := "PathSetLaws", output := "path_set_laws", pathSets := true + ops := zippyOps ++ [ + (`PrunedModel.Convex.basis, "basis", [.space]), + (`PrunedModel.Convex.hull, "hull", [.space]), + (`PrunedModel.Convex.retain, "retain", [.space, .space])] +} + +private theorem restricted (a b : PathSpace) (p : PathMapModel.Path) + (ha : p ∉ a) (hb : p ∉ b) : p ∈ a ↔ p ∈ b := iff_of_false ha hb + +private theorem dependent (p : PathMapModel.Path) : + p ∈ Zippy.singleton p ↔ p ∈ Zippy.singleton p := Iff.rfl + +run_meta do + for n in [``restricted, ``dependent] do + forallTelescope (← getConstInfo n).type fun xs body => do + unless (← pointwiseEquation xs body).isNone do + throwError "unsound extensional lifting of {n}" + let .ok idem ← translate config (← getConstInfo ``Convex.basis_idempotent).type + | throwError "basis idempotence was not exported" + unless idem.paths == 0 && idem.pre.isEmpty && + idem.lhs == "basis(basis(s(0)))" && idem.rhs == "basis(s(0))" do + throwError "incorrect lifting of basis idempotence" + let .ok conditional ← translate config (← getConstInfo ``Convex.hull_of_antichain).type + | throwError "conditional hull law was not exported" + unless conditional.pre == #["eq_space(basis(s(0)), s(0))"] && + conditional.lhs == "hull(s(0))" && conditional.rhs == "s(0)" do + throwError "antichain hypothesis was lost or mistranslated" + let .ok included ← translate config (← getConstInfo ``Convex.hull_retain).type + | throwError "inclusion hypothesis was not exported" + unless included.pre == #["eq_space(inter(s(1), hull(s(0))), s(1))"] do + throwError "inclusion hypothesis was lost or mistranslated" + -- A non-equational conclusion must be rejected without probing absent args. + let .error _ ← translate config (← getConstInfo ``Convex.mem_hull).type + | throwError "unsupported quantified membership formula was exported" + +end LawExport.Checks diff --git a/lean/PathSetLaws.lean b/lean/PathSetLaws.lean new file mode 100644 index 00000000..dee6f5a3 --- /dev/null +++ b/lean/PathSetLaws.lean @@ -0,0 +1,42 @@ +import LawExport + +/-! Export the sorry-free path-set and convex laws from `PrunedModel.Convex`. +Run `lake env lean --run PathSetLaws.lean > ../differential/src/algebraic/path_set_laws.rs`. +Membership equivalences are lifted only at unrestricted universally quantified +paths. `Same`, inclusion, closure and antichain predicates use their finite-set +equations. Unsupported statements are listed in the generated file. -/ + +open LawExport + +def main : IO Unit := LawExport.generate { + ns := `PrunedModel.Convex + module := `PrunedModel.Convex + submodules := true + generator := "PathSetLaws" + output := "path_set_laws" + namePrefix := "path_set/" + pathSets := true + ops := zippyOps ++ [ + (`PrunedModel.Convex.union, "union", [.space, .space]), + (`PrunedModel.Convex.inter, "inter", [.space, .space]), + (`PrunedModel.Convex.diff, "subtr", [.space, .space]), + (`PrunedModel.Convex.product, "composition", [.space, .space]), + (`PrunedModel.Convex.restrict, "restriction", [.space, .space]), + (`PrunedModel.Convex.raffinate, "raffination", [.space, .space]), + (`PrunedModel.Convex.retain, "retain", [.space, .space]), + (`PrunedModel.Convex.divergence, "divergence", [.space, .space]), + (`PrunedModel.Convex.branches, "branches", [.space]), + (`PrunedModel.Convex.basis, "basis", [.space]), + (`PrunedModel.Convex.hull, "hull", [.space]), + (`PrunedModel.Convex.interior, "interior", [.space]), + (`PrunedModel.Convex.completion, "completion", [.space]), + (`PrunedModel.Convex.lcpProduct, "lcp_product", [.space, .space]), + (`PrunedModel.Convex.convexMeet, "convex_meet", [.space, .space]), + (`PrunedModel.Convex.convexSubtract, "convex_subtract", [.space, .space]), + (`PrunedModel.Convex.convexLiteralSubtract, "convex_literal_subtract", [.space, .space]), + (`PrunedModel.Convex.symDiff, "sym_diff", [.space, .space]), + (`PrunedModel.Convex.head, "head", [.space]), + (`PrunedModel.Convex.tails, "tails_union", [.space]), + (`PrunedModel.Convex.wrap, "wrap", [.path, .space]), + (`PrunedModel.Convex.unwrap, "unwrap", [.space, .path])] +} diff --git a/lean/ZippyLaws.lean b/lean/ZippyLaws.lean index 62c7428f..b385b2c9 100644 --- a/lean/ZippyLaws.lean +++ b/lean/ZippyLaws.lean @@ -1,314 +1,13 @@ -import Lean - -/-! -# Export `PrunedModel/Zippy.lean`'s equational laws as Rust - -Run from this directory: - - lake env lean --run ZippyLaws.lean > ../differential/src/algebraic/zippy_laws.rs - -The program imports the *elaborated* module `PrunedModel.Zippy` and walks its -theorems. A theorem is exported when every binder is a space, a path or a -byte, or a hypothesis of a supported shape (`≠` on paths or bytes, `∈`/`∉`, `=` -on spaces); its conclusion is an equation of spaces; both sides are built from -the operator vocabulary below; and its proof uses no `sorryAx`. Everything else -is listed at the end of the output with the reason it was not exported. - -Terms are translated by their application head and never unfolded: the point is -to emit the operator the theorem names. --/ - -open Lean Meta - -namespace ZippyLaws - -def zippyNs : Name := `PrunedModel.Zippy -def zippyModule : Name := `PrunedModel.Zippy - -inductive VarKind | space | path | byte - deriving BEq - -structure St where - vars : Std.HashMap FVarId (VarKind × Nat) := {} - nSpace : Nat := 0 - nPath : Nat := 0 - nByte : Nat := 0 - -abbrev M := StateT St (ExceptT String MetaM) - -def fail {α} (msg : String) : M α := throwThe String msg - -def liftMeta {α} (x : MetaM α) : M α := monadLift x - -def clean (e : Expr) : MetaM Expr := do - return (← instantiateMVars e).consumeMData.headBeta - -def spaceTy : Expr := mkConst `PrunedModel.Zippy.Space -def pathTy : Expr := mkApp (mkConst ``List [Level.zero]) (mkConst ``UInt8) -def byteTy : Expr := mkConst ``UInt8 - -/-- Which variable kind a type is, if any. Types are compared up to -definitional equality, so `Space`, `PrunedMap Unit`, `Path` and `List UInt8` -are all recognised. -/ -def kindOf (ty : Expr) : MetaM (Option VarKind) := do - let ty ← clean ty - if ty.isSort then return none - if ← isDefEq ty spaceTy then return some .space - if ← isDefEq ty pathTy then return some .path - if ← isDefEq ty byteTy then return some .byte - return none - -def headName (e : Expr) : String := - match e.getAppFn with - | .const n _ => toString n - | .fvar _ => "a local function" - | .lam .. => "a lambda" - | .proj s i _ => s!"projection {s}.{i}" - | .letE .. => "a let" - | .lit _ => "a literal" - | f => s!"{f.ctorName}" - -/-- What a space-typed term mentions that is outside the vocabulary. -/ -def outside (e : Expr) : String := s!"mentions {headName e}" - -def varOf (e : Expr) (k : VarKind) : M (Option Nat) := do - match e with - | .fvar id => - match (← get).vars.get? id with - | some (k', i) => if k' == k then return some i else fail s!"variable of the wrong kind" - | none => fail "unbound local" - | _ => return none - -def litByte (e : Expr) : M (Option Nat) := do - -- `OfNat.ofNat UInt8 n inst` - if e.isAppOfArity ``OfNat.ofNat 3 then - let ty ← liftMeta (clean (e.getArg! 0)) - if ty.isConstOf ``UInt8 then - match (← liftMeta (clean (e.getArg! 1))) with - | .lit (.natVal n) => return some (n % 256) - | _ => return none - return none - -partial def byteTerm (e : Expr) : M String := do - let e ← liftMeta (clean e) - if let some i ← varOf e .byte then return s!"bv({i})" - if let some n ← litByte e then return s!"lit({n})" - fail s!"byte term {outside e}" - -partial def pathTerm (e : Expr) : M String := do - let e ← liftMeta (clean e) - if let some i ← varOf e .path then return s!"pv({i})" - if e.isAppOfArity ``List.nil 1 then return "nil()" - if e.isAppOfArity ``List.cons 3 then - return s!"cons({← byteTerm (e.getArg! 1)}, {← pathTerm (e.getArg! 2)})" - if e.isAppOfArity ``HAppend.hAppend 6 then - return s!"app({← pathTerm (e.getArg! 4)}, {← pathTerm (e.getArg! 5)})" - if e.isAppOfArity ``List.append 3 then - return s!"app({← pathTerm (e.getArg! 1)}, {← pathTerm (e.getArg! 2)})" - fail s!"path term {outside e}" - -/-- The space operators: Lean name, Rust builder, and the kind of each -explicit argument. -/ -def ops : List (Name × String × List VarKind) := - [ (`PrunedModel.Zippy.empty, "empty", []), - (`PrunedModel.Zippy.singleton, "singleton", [.path]), - (`PrunedModel.Zippy.union, "union", [.space, .space]), - (`PrunedModel.Zippy.inter, "inter", [.space, .space]), - (`PrunedModel.Zippy.subtr, "subtr", [.space, .space]), - (`PrunedModel.Zippy.restriction, "restriction", [.space, .space]), - (`PrunedModel.Zippy.raffination, "raffination", [.space, .space]), - (`PrunedModel.Zippy.wrap, "wrap", [.path, .space]), - (`PrunedModel.Zippy.unwrap, "unwrap", [.space, .path]), - (`PrunedModel.Zippy.head, "head", [.space]), - (`PrunedModel.Zippy.tailsUnion, "tails_union", [.space]), - (`PrunedModel.Zippy.tailsInter, "tails_inter", [.space]), - (`PrunedModel.Zippy.composition, "composition", [.space, .space]), - (`PrunedModel.Zippy.iterC, "iter_c", [.space, .space]) ] - -mutual -partial def spaceTerm (e : Expr) : M String := do - let e ← liftMeta (clean e) - if let some i ← varOf e .space then return s!"s({i})" - let .const f _ := e.getAppFn | fail s!"space term {outside e}" - let some (_, rust, kinds) := ops.find? (·.1 == f) | fail (outside e) - let args := e.getAppArgs - unless args.size == kinds.length do - fail s!"{f} applied to {args.size} arguments, expected {kinds.length}" - let mut out := #[] - for (a, k) in args.toList.zip kinds do - out := out.push (← anyTerm a k) - return s!"{rust}({", ".intercalate out.toList})" - -partial def anyTerm (e : Expr) (k : VarKind) : M String := - match k with - | .space => spaceTerm e - | .path => pathTerm e - | .byte => byteTerm e -end - -/-- A hypothesis, as a precondition. -/ -def hypothesis (ty : Expr) : M String := do - let ty ← liftMeta (clean ty) - -- `a ≠ b` - if ty.isAppOfArity ``Ne 3 then - match ← liftMeta (kindOf (ty.getArg! 0)) with - | some .path => return s!"ne_path({← pathTerm (ty.getArg! 1)}, {← pathTerm (ty.getArg! 2)})" - | some .byte => return s!"ne_byte({← byteTerm (ty.getArg! 1)}, {← byteTerm (ty.getArg! 2)})" - | _ => fail "hypothesis is a disequation of neither paths nor bytes" - -- `p ∈ s` is `@Membership.mem Path Space inst s p`: collection first. - let memOf (m : Expr) : M (Option String) := do - let m ← liftMeta (clean m) - if m.isAppOfArity ``Membership.mem 5 then - unless (← liftMeta (kindOf (m.getArg! 1))) == some .space do - fail "hypothesis is membership in something other than a space" - return some s!"{← pathTerm (m.getArg! 4)}, {← spaceTerm (m.getArg! 3)}" - return none - if let some s ← memOf ty then return s!"mem({s})" - if ty.isAppOfArity ``Not 1 then - if let some s ← memOf (ty.getArg! 0) then return s!"not_mem({s})" - fail "hypothesis is a negation other than ∉" - if ty.isAppOfArity ``Eq 3 then - unless (← liftMeta (kindOf (ty.getArg! 0))) == some .space do - fail "hypothesis is an equation not of spaces" - return s!"eq_space({← spaceTerm (ty.getArg! 1)}, {← spaceTerm (ty.getArg! 2)})" - if ty.isForall then fail "hypothesis is a ∀" - fail s!"hypothesis {outside ty}" - -structure Law where - name : String - spaces : Nat - paths : Nat - bytes : Nat - pre : Array String - lhs : String - rhs : String - -def conclusionShape (e : Expr) : String := - match e.getAppFn with - | .const n _ => - if n == ``Iff then "Iff" else if n == ``Ne then "Ne" else if n == ``Not then "¬" - else if n == ``Eq then "an equation of another type" else toString n - | _ => headName e - -def translate (ty : Expr) : MetaM (Except String Law) := do - -- `forallTelescope`, not `…Reducing`: a conclusion like `p ∉ s` must not be - -- unfolded into another binder. - forallTelescope ty fun xs body => do - let go : M Law := do - let mut pre := #[] - for x in xs do - let decl ← liftMeta x.fvarId!.getDecl - let bty ← liftMeta (clean decl.type) - match ← liftMeta (kindOf bty) with - | some k => - let st ← get - let (i, st') := match k with - | .space => (st.nSpace, { st with nSpace := st.nSpace + 1 }) - | .path => (st.nPath, { st with nPath := st.nPath + 1 }) - | .byte => (st.nByte, { st with nByte := st.nByte + 1 }) - set { st' with vars := st'.vars.insert x.fvarId! (k, i) } - | none => - if ← liftMeta (isProp bty) then - pre := pre.push (← hypothesis bty) - else - fail s!"binder {decl.userName} : {← liftMeta (ppExpr bty)}" - let body ← liftMeta (clean body) - unless body.isAppOfArity ``Eq 3 do - fail s!"conclusion is not an equation of spaces ({conclusionShape body})" - unless (← liftMeta (kindOf (body.getArg! 0))) == some .space do - fail s!"conclusion is not an equation of spaces (equation of {← liftMeta (ppExpr (body.getArg! 0))})" - let lhs ← spaceTerm (body.getArg! 1) - let rhs ← spaceTerm (body.getArg! 2) - let st ← get - return { name := "", spaces := st.nSpace, paths := st.nPath, bytes := st.nByte, - pre, lhs, rhs } - match ← (go.run' {}).run with - | .ok l => return .ok l - | .error e => return .error e - -def relName (n : Name) : String := - let comps := n.components.drop zippyNs.components.length - ".".intercalate (comps.map toString) - -def skipName (env : Environment) (n : Name) : Bool := - n.isInternal || isPrivateName n || isAuxRecursor env n || isNoConfusion env n || - isMatcherCore env n || isRecCore env n || - n.components.any fun c => - let s := toString c - s == "eq_def" || s.startsWith "eq_" || s.startsWith "match_" || s.startsWith "proof_" || - (s.splitOn "_proof_").length > 1 || s.startsWith "_" || s == "inj" || s == "injEq" || - s == "sizeOf_spec" - -inductive Outcome - | law (l : Law) - | skip (reason : String) - -def run : MetaM String := do - let env ← getEnv - let some modIdx := env.getModuleIdx? zippyModule | throwError "{zippyModule} not imported" - let mut entries : Array (Nat × String × Outcome) := #[] - for (n, ci) in env.constants.toList do - unless zippyNs.isPrefixOf n && n != zippyNs do continue - unless env.getModuleIdxFor? n == some modIdx do continue - let .thmInfo info := ci | continue - if skipName env n then continue - let line := match ← findDeclarationRanges? n with - | some r => r.selectionRange.pos.line - | none => 0 - let name := relName n - let axioms ← collectAxioms n - let outcome ← - if axioms.contains ``sorryAx then pure (.skip "depends on sorryAx") - else match ← translate info.type with - | .error e => pure (.skip e) - | .ok l => - if l.spaces > 4 then pure (.skip s!"{l.spaces} space variables (more than 4)") - else if l.lhs == l.rhs then pure (.skip "both sides translate to the same term") - else pure (.law { l with name }) - entries := entries.push (line, name, outcome) - entries := entries.qsort fun a b => a.1 < b.1 || (a.1 == b.1 && a.2.1 < b.2.1) - let laws := entries.filterMap fun - | (line, _, .law l) => some (line, l) - | _ => none - let skips := entries.filterMap fun - | (line, name, .skip r) => some (line, name, r) - | _ => none - let mut out := "" - out := out ++ "// @generated by lean/ZippyLaws.lean from lean/PrunedModel/Zippy.lean.\n" - out := out ++ "// Do not edit by hand. Regenerate with:\n" - out := out ++ "// cd lean && lake env lean --run ZippyLaws.lean > ../differential/src/algebraic/zippy_laws.rs\n" - out := out ++ "//\n" - out := out ++ "// Every entry is a theorem of PrunedModel.Zippy, checked sorry-free when generated.\n" - out := out ++ s!"// {laws.size} exported, {skips.size} not exported (listed at the end).\n" - out := out ++ "\n" - out := out ++ "use super::laws::zippy::*;\n" - out := out ++ "\n" - out := out ++ "pub fn laws() -> Vec {\n" - out := out ++ " vec![\n" - for (line, l) in laws do - out := out ++ s!" // Zippy.lean:{line}\n" - out := out ++ " ZippyLaw {\n" - out := out ++ s!" name: \"{l.name}\",\n" - out := out ++ s!" spaces: {l.spaces},\n" - out := out ++ s!" paths: {l.paths},\n" - out := out ++ s!" bytes: {l.bytes},\n" - out := out ++ s!" pre: vec![{", ".intercalate l.pre.toList}],\n" - out := out ++ s!" lhs: {l.lhs},\n" - out := out ++ s!" rhs: {l.rhs},\n" - out := out ++ " },\n" - out := out ++ " ]\n" - out := out ++ "}\n" - out := out ++ "\n" - out := out ++ "// Not exported:\n" - for (line, name, r) in skips do - out := out ++ s!"// Zippy.lean:{line} {name}: {r}\n" - return out - -end ZippyLaws - -def main : IO Unit := do - initSearchPath (← findSysroot) - let env ← importModules #[{ module := `PrunedModel.Zippy }] {} (trustLevel := 1024) - let (out, _) ← (ZippyLaws.run.run' {} {}).toIO - { fileName := "", fileMap := default, maxHeartbeats := 0 } { env := env } - IO.print out +import LawExport + +/-! Export the sorry-free equational laws of `PrunedModel.Zippy`. +Run `lake env lean --run ZippyLaws.lean > ../differential/src/algebraic/zippy_laws.rs`. +The shared exporter records every unsupported theorem and its reason. -/ + +def main : IO Unit := LawExport.generate { + ns := `PrunedModel.Zippy + module := `PrunedModel.Zippy + generator := "ZippyLaws" + output := "zippy_laws" + ops := LawExport.zippyOps +} diff --git a/lean/lakefile.toml b/lean/lakefile.toml index 6f773634..728c6556 100644 --- a/lean/lakefile.toml +++ b/lean/lakefile.toml @@ -1,5 +1,5 @@ name = "pathmap-model" -defaultTargets = ["PathMapModel", "pathmap-oracle", "PrunedModel", "pruned-oracle"] +defaultTargets = ["PathMapModel", "pathmap-oracle", "PrunedModel", "pruned-oracle", "LawExport"] [[lean_lib]] name = "PathMapModel" @@ -20,3 +20,7 @@ name = "PrunedModel" [[lean_exe]] name = "pruned-oracle" root = "PrunedMain" + +# Shared translation used by the two standalone law generators. +[[lean_lib]] +name = "LawExport" From e211932df01c7de2cbda42c9328f9bd9866d094f Mon Sep 17 00:00:00 2001 From: adamv-symbolica Date: Thu, 19 Nov 2026 17:34:44 +0000 Subject: [PATCH 14/15] Replace the handwritten path-set law catalog with focused properties --- differential/src/algebraic/path_set_laws.rs | 16 +- .../Convex/PathSetCertificates.lean | 4 +- lean/PrunedModel/Convex/PathSetChecks.lean | 15 - lean/PrunedModel/Convex/PathSetLaws.lean | 265 ----- lean/PrunedModel/Convex/PathSetPowers.lean | 2 +- lean/PrunedModel/Convex/PathSetProduct.lean | 22 +- lean/PrunedModel/Convex/PathSetProofs.lean | 2 +- tests/path_set_properties.rs | 472 +++++++++ tests/pathmap_algebra_differential.rs | 3 - tests/support/path_set_laws.rs | 959 ------------------ 10 files changed, 498 insertions(+), 1262 deletions(-) delete mode 100644 lean/PrunedModel/Convex/PathSetLaws.lean create mode 100644 tests/path_set_properties.rs delete mode 100644 tests/support/path_set_laws.rs diff --git a/differential/src/algebraic/path_set_laws.rs b/differential/src/algebraic/path_set_laws.rs index 269d8388..a61e7b12 100644 --- a/differential/src/algebraic/path_set_laws.rs +++ b/differential/src/algebraic/path_set_laws.rs @@ -1749,7 +1749,7 @@ pub fn laws() -> Vec { lhs: composition(s(0), empty()), rhs: empty(), }, - // PrunedModel/Convex/PathSetProduct.lean:116 + // PrunedModel/Convex/PathSetProduct.lean:122 ZippyLaw { name: "path_set/equiv_members", spaces: 2, @@ -1759,7 +1759,7 @@ pub fn laws() -> Vec { lhs: s(0), rhs: s(1), }, - // PrunedModel/Convex/PathSetProduct.lean:123 + // PrunedModel/Convex/PathSetProduct.lean:129 ZippyLaw { name: "path_set/prefixFree_antichain", spaces: 1, @@ -1769,7 +1769,7 @@ pub fn laws() -> Vec { lhs: basis(s(0)), rhs: s(0), }, - // PrunedModel/Convex/PathSetProduct.lean:132 + // PrunedModel/Convex/PathSetProduct.lean:138 ZippyLaw { name: "path_set/prefix_free_product", spaces: 4, @@ -1779,7 +1779,7 @@ pub fn laws() -> Vec { lhs: divergence(composition(s(0), s(2)), composition(s(1), s(3))), rhs: union(divergence(s(0), s(1)), composition(inter(s(0), s(1)), divergence(s(2), s(3)))), }, - // PrunedModel/Convex/PathSetProduct.lean:153 + // PrunedModel/Convex/PathSetProduct.lean:159 ZippyLaw { name: "path_set/common_prefix_code", spaces: 3, @@ -2698,10 +2698,10 @@ pub fn laws() -> Vec { // PrunedModel/Convex/PathSetPowers.lean:32 path_set/powerSum_succ: binder n : Nat // PrunedModel/Convex/PathSetPowers.lean:52 path_set/prefix_code_powers: binder m : Nat // PrunedModel/Convex/PathSetPowers.lean:75 path_set/general_product: mentions ite -// PrunedModel/Convex/PathSetProduct.lean:16 path_set/mem_proper_overlap: binder f : PathMapModel.Path → PathMapModel.Path → PrunedModel.PathSpace -// PrunedModel/Convex/PathSetProduct.lean:37 path_set/mem_leftOverlap: conclusion is not an equation of spaces (Iff) -// PrunedModel/Convex/PathSetProduct.lean:45 path_set/mem_rightOverlap: conclusion is not an equation of spaces (Iff) -// PrunedModel/Convex/PathSetProduct.lean:53 path_set/divergence_product_nonempty: mentions PrunedModel.Convex.PathSetLaws.leftOverlap +// PrunedModel/Convex/PathSetProduct.lean:15 path_set/mem_proper_overlap: binder f : PathMapModel.Path → PathMapModel.Path → PrunedModel.PathSpace +// PrunedModel/Convex/PathSetProduct.lean:43 path_set/mem_leftOverlap: conclusion is not an equation of spaces (Iff) +// PrunedModel/Convex/PathSetProduct.lean:51 path_set/mem_rightOverlap: conclusion is not an equation of spaces (Iff) +// PrunedModel/Convex/PathSetProduct.lean:59 path_set/divergence_product_nonempty: mentions PrunedModel.Convex.leftOverlap // PrunedModel/Convex/PathSetProofs.lean:7 path_set/basis_subset: conclusion is not an equation of spaces (Membership.mem) // PrunedModel/Convex/PathSetProofs.lean:10 path_set/hull_subset: conclusion is not an equation of spaces (Membership.mem) // PrunedModel/Convex/PathSetProofs.lean:29 path_set/basis_antichain: conclusion is not an equation of spaces (equation of Bool) diff --git a/lean/PrunedModel/Convex/PathSetCertificates.lean b/lean/PrunedModel/Convex/PathSetCertificates.lean index 22b3f5bf..83d59bc5 100644 --- a/lean/PrunedModel/Convex/PathSetCertificates.lean +++ b/lean/PrunedModel/Convex/PathSetCertificates.lean @@ -1,6 +1,6 @@ import PrunedModel.Convex.PathSetUpdates -/-! Bridges between the universally quantified laws and the executable Boolean catalogue. -/ +/-! Boolean formulations of the path-set laws and their extensionality certificates. -/ namespace PrunedModel.Convex open PathMapModel @@ -69,7 +69,7 @@ theorem singleton_prefix_test (a b : PathSpace) : have hh := (hp q).mp hq subst q; exact he r hr -/-- The exact Boolean zero criterion used by the executable catalogue. -/ +/-- Boolean criterion for divergence to be empty. -/ theorem zero_criterion_check (a b : PathSpace) : ((divergence a b)).keys.isEmpty = (a.keys.isEmpty || b.keys.isEmpty || diff --git a/lean/PrunedModel/Convex/PathSetChecks.lean b/lean/PrunedModel/Convex/PathSetChecks.lean index 46bcb83b..da46bddc 100644 --- a/lean/PrunedModel/Convex/PathSetChecks.lean +++ b/lean/PrunedModel/Convex/PathSetChecks.lean @@ -1,24 +1,9 @@ -import PrunedModel.Convex.PathSetLaws import PrunedModel.Convex.Map -set_option maxRecDepth 4096 -set_option maxHeartbeats 0 namespace PrunedModel.Convex.PathSetChecks open PathMapModel open PrunedModel.Convex -def small : List PathSpace := [(ofPaths []), (ofPaths [[]]), (ofPaths [[0]]), (ofPaths [[1]]), (ofPaths [[],[0]]), (ofPaths [[],[1]]), (ofPaths [[0],[1]]), (ofPaths [[],[0],[1]])] -def fixtures : List PathSpace := small ++ - [(ofPaths [[0],[0,0],[0,1]]), (ofPaths [[0,0],[0,1]]), (ofPaths [[0],[1,0],[1,1,0],[1,1,1]]), - (ofPaths [[255,0],[255,255]]), (ofPaths [[0,0,0],[1],[0,1],[0,0,1]])] - -#guard (small.flatMap fun a => small.flatMap fun b => small.flatMap fun c => - small.map fun f => (PathSetLaws.failures (PathSetLaws.all a b c f)).isEmpty).all id -#guard (fixtures.flatMap fun a => fixtures.map fun b => - (PathSetLaws.failures (PathSetLaws.unary a ++ PathSetLaws.binary a b)).isEmpty).all id -#guard (fixtures.flatMap fun a => (List.range 4).flatMap fun m => (List.range 4).map fun n => - (PathSetLaws.failures (PathSetLaws.powers a m n)).isEmpty).all id - -- Counterexamples are positively checked: these are NOT proposed rewrite rules. #guard !equiv (divergence (divergence (ofPaths [[0,0]]) (ofPaths [[0,1]])) (ofPaths [[1]])) (divergence (ofPaths [[0,0]]) (divergence (ofPaths [[0,1]]) (ofPaths [[1]]))) diff --git a/lean/PrunedModel/Convex/PathSetLaws.lean b/lean/PrunedModel/Convex/PathSetLaws.lean deleted file mode 100644 index 42f3d59a..00000000 --- a/lean/PrunedModel/Convex/PathSetLaws.lean +++ /dev/null @@ -1,265 +0,0 @@ -import PrunedModel.Convex.PathSets - -/-! Named decidable laws for property tests. `PathSetChecks` evaluates small -fixtures; the `PathSetProofs` through `PathSetCertificates` modules prove the -corresponding universally quantified statements. -/ -namespace PrunedModel.Convex.PathSetLaws -open PathMapModel -open PrunedModel.Convex -abbrev Checks := List (String × Bool) -def D (a b : PathSpace) := (divergence a b) -private def Br (a : PathSpace) := D a a -private def I (a : PathSpace) := diff a (hull a) -private def C (a : PathSpace) := union a (Br a) -private def M (a b : PathSpace) := (lcpProduct a b) -private def E : PathSpace := (ofPaths [[]]) -private def implies (a b : Bool) := !a || b -private def eq := PrunedModel.Convex.equiv -private def sub := PrunedModel.Convex.subset - -def unary (a : PathSpace) : Checks := - let br := Br a - [ ("diagonal", eq (D a a) br), - ("empty_left", eq (D (ofPaths []) a) (ofPaths [])), - ("empty_right", eq (D a (ofPaths [])) (ofPaths [])), - ("epsilon_left", eq (D E a) (ofPaths [])), - ("epsilon_right", eq (D a E) (ofPaths [])), - ("branch_completion", eq (Br (C a)) br), - ("completion_idempotent", eq (C (C a)) (C a)), - ("branch_hull", eq (Br (hull a)) br), - ("branch_epsilon", eq (Br (union a E)) br), - ("branch_second_subset", sub (Br br) br), - ("interior_branches", eq (D a br) (I br)), - ("basis_subset", sub (basis a) a), - ("hull_subset", sub (hull a) a), - ("basis_idempotent", eq (basis (basis a)) (basis a)), - ("hull_idempotent", eq (hull (hull a)) (hull a)), - ("basis_of_hull", eq (basis (hull a)) (hull a)), - ("hull_of_basis", eq (hull (basis a)) (basis a)), - ("basis_antichain", prefixFree (basis a)), - ("hull_antichain", prefixFree (hull a)), - ("basis_nonempty", (basis a).isEmptyMap == a.isEmptyMap), - ("hull_nonempty", (hull a).isEmptyMap == a.isEmptyMap), - ("basis_covers", covers a (hull a) && covers (basis a) a), - ("basis_recursive", eq (basisRec (height a + 1) a) (basis a)), - ("hull_recursive", eq (hullRec (height a + 1) a) (hull a)), - ("branch_recursive", eq (divergenceRec (height a + 1) a a) br), - ("maximal_branch_count", decide (count (hull br) <= count (hull a) / 2)), - ("no_nonempty_branch_fixed_point", implies (!a.isEmptyMap) (!eq br a)), - ("branch_depth_nilpotence", eq (branchIter a (height a + 1)) (ofPaths [])) ] - -def binary (a b : PathSpace) : Checks := - let x := D a b - let ha := hull a - let hb := hull b - let zero := a.isEmptyMap || b.isEmptyMap || - (count ha == 1 && hb.keys.all (fun q => ha.keys.all (· ≼ q))) || - (count hb == 1 && ha.keys.all (fun p => hb.keys.all (· ≼ p))) - let fork : PathSpace := (ofPaths [[0], [1]]) - [ ("symmetry", eq x (D b a)), - ("terminal_invariance", eq (D (union a E) (union b E)) x), - ("hull_invariance", eq (D ha hb) x), - ("completion_invariance", eq (D (C a) (C b)) x), - ("branch_union", eq (Br (union a b)) (union (union (Br a) (Br b)) x)), - ("branch_intersection_lower", sub (Br (inter a b)) (inter (Br a) (Br b))), - ("branch_sandwich_lower", sub (inter (Br a) (Br b)) x), - ("branch_sandwich_upper", sub x (Br (union a b))), - ("output_completion", eq (C x) x), - ("absorbed_branch_marks", eq (Br (union a x)) (Br a)), - ("nested_exact", eq (D a x) (inter (Br a) (I x))), - ("interior_exact", eq (D (union a b) x) (I x)), - ("interior_attribution", sub (I x) (union (Br a) (Br b))), - ("output_branches", sub (Br x) (inter x (inter (Br a) (Br b)))), - ("first_divergence", implies (!x.isEmptyMap) (eq (basis x) [commonPrefix (union ha hb)])), - ("zero_criterion", x.isEmptyMap == zero), - ("root_heads", eq (D (head a) (head b)) (inter x E)), - ("output_heads", sub (head x) (inter (head a) (head b))), - ("tails_bound", sub (tails x) (D (tails a) (tails b))), - ("recursive_divergence", eq (divergenceRec (min (height a) (height b) + 1) a b) x), - ("retain_recursive", eq (retainRec (height a + 1) a b) (retain a b)), - ("output_cardinality", decide (count x <= count (hull (union a b)) - 1)), - ("output_hull_cardinality", decide (count (hull x) <= min (count ha) (count hb))), - ("output_depth", implies (!x.isEmptyMap) (height x < min (height a) (height b))), - ("output_covered", covers x a && covers x b), - ("fork_completion", eq (Br (product a fork)) (C a)), - ("fork_lcp", eq (D (product a fork) (product b fork)) (M a b)), - ("lcp_correction", eq (M a b) (union x (union (retain a b) (retain b a)))), - ("lcp_diagonal", eq (M a a) (C a)), - ("lcp_symmetry", eq (M a b) (M b a)), - ("lcp_output_completion", eq (C (M a b)) (M a b)), - ("range_realization", eq (Br (product (C a) fork)) (C a)), - ("basis_union", eq (basis (union a b)) (basis (union (basis a) (basis b)))), - ("hull_union", eq (hull (union a b)) (hull (union ha hb))), - ("restriction_basis_mask", eq (restrict a b) (restrict a (basis b))) ] - -def ternary (a b c : PathSpace) : Checks := - [ ("left_union", eq (D (union a b) c) (union (D a c) (D b c))), - ("right_union", eq (D a (union b c)) (union (D a b) (D a c))), - ("intersection_bound", sub (D (inter a b) c) (inter (D a c) (D b c))), - ("difference_lower", sub (diff (D a c) (D b c)) (D (diff a b) c)), - ("difference_upper", sub (D (diff a b) c) (D a c)), - ("symmetric_difference_bound", sub (symDiff (D a c) (D b c)) (D (symDiff a b) c)), - ("monotonicity", implies (sub a b) (sub (D a c) (D b c))), - ("prefix_extension_monotonicity", implies (covers a b) (sub (D a c) (D b c))), - ("covered_mark_invariance", implies (covers b a) (eq (D (union a b) c) (D a c))), - ("nested_absorption", sub (D (D a b) c) (inter (D a c) (D b c))), - ("witness_absorption", eq (D (union a (D a b)) c) (D a c)), - ("branch_probe_exchange", sub (inter (D a b) (Br c)) (inter (D a c) (D b c))), - ("lcp_associativity", eq (M (M a b) c) (M a (M b c))), - ("lcp_bilinearity", eq (M (union a b) c) (union (M a c) (M b c))), - ("one_mask", eq (D (restrict a c) b) (union (restrict (D a b) c) (D (retain c a) b))), - ("same_mask", eq (D (restrict a c) (restrict b c)) - (union (restrict (D a b) c) (D (retain c a) (retain c b)))), - ("filter_partition", eq (D a b) (union (D (restrict a c) b) (D (raffinate a c) b))), - ("common_prefix_code", implies (prefixFree a && !b.isEmptyMap && !c.isEmptyMap) - (eq (D (product a b) (product a c)) (union (Br a) (product a (D b c))))) ] - -/-- The proper-prefix contributions in the full four-factor product expansion. -/ -def leftOverlap (a b x y : PathSpace) : PathSpace := - properOverlap a b fun p r => wrap p (D x (wrap r y)) - -def rightOverlap (a b x y : PathSpace) : PathSpace := - properOverlap b a fun p r => wrap p (D (wrap r x) y) - -def quaternary (a b c f : PathSpace) : Checks := - let x := D a b - let pa := retain c a - let qb := retain f b - [ ("four_point_absorption", sub (D (D a b) (D c f)) - (inter (inter (D a c) (D a f)) (inter (D b c) (D b f)))), - ("four_point_exchange", sub (inter (D a b) (D c f)) - (union (inter (D a c) (D b f)) (inter (D a f) (D b c)))), - ("incremental_update", eq (D (union a c) (union b f)) - (union (union x (D c b)) (union (D a f) (D c f)))), - ("two_masks", eq (D (restrict a c) (restrict b f)) - (union (union (restrict (restrict x c) f) (restrict (D a qb) c)) - (union (restrict (D pa b) f) (D pa qb)))), - ("raffination_bound", sub (D (raffinate a c) (raffinate b f)) (raffinate x (union c f))), - ("general_product", eq (D (product a c) (product b f)) - (if c.isEmptyMap || f.isEmptyMap then (ofPaths []) else - union (union x (product (inter a b) (D c f))) - (union (leftOverlap a b c f) (rightOverlap a b c f)))), - ("prefix_free_product", implies (prefixFree (union a b) && !c.isEmptyMap && !f.isEmptyMap) - (eq (D (product a c) (product b f)) (union x (product (inter a b) (D c f))))) ] - -def pathLaws (a b : PathSpace) (p : Path) : Checks := - let chain := D [p] b - [ ("wrap", eq (D (wrap p a) (wrap p b)) (wrap p (D a b))), - ("unwrap", eq (D (unwrap a p) (unwrap b p)) (unwrap (D a b) p)), - ("single_prefix_restriction", eq (D (restrict a [p]) (restrict b [p])) (restrict (D a b) [p])), - ("singleton_chain", eq (Br chain) (ofPaths [])), - ("singleton_bound", decide (count chain <= min p.length (count (hull b)))), - ("singleton_existing_branches", sub (I chain) (Br b)), - ("singleton_branch_update", decide (count (diff (Br (union b [p])) (Br b)) <= 1)), - ("singleton_divergence_update", decide (count (diff (D (union a [p]) b) (D a b)) <= min p.length (count (hull b)))) ] - -def powers (a : PathSpace) (m n : Nat) : Checks := - [ ("prefix_code_powers", implies (prefixFree a) - (eq (D (power a m) (power a n)) - (ofPaths ((List.range (min m n)).flatMap fun i => (product (power a i) (Br a)).keys)))), - ("branch_leaf_bound", implies (!(branchIter a n).isEmptyMap) (2^n <= count (hull a))) ] - -def retention (a b c f : PathSpace) : Checks := - [ ("retain_empty_left", eq (retain (ofPaths []) a) ((ofPaths []))), - ("retain_empty_right", eq (retain a (ofPaths [])) ((ofPaths []))), - ("retain_self", eq (retain a a) (a)), - ("retain_union_left", eq (retain (union a b) c) (union (retain a c) (retain b c))), - ("retain_inter_left", eq (retain (inter a b) c) (inter (retain a c) (retain b c))), - ("retain_diff_left", eq (retain (diff a b) c) (diff (retain a c) (retain b c))), - ("retain_symDiff_left", eq (retain (symDiff a b) c) (symDiff (retain a c) (retain b c))), - ("retain_union_right", eq (retain a (union b c)) (union (retain a b) (retain a c))), - ("retain_filter_inter", eq (retain (retain a b) c) (inter (retain a b) (retain a c))), - ("retain_filter_comm", eq (retain (retain a b) c) (retain (retain a c) b)), - ("retain_filter_idem", eq (retain (retain a b) b) (retain a b)), - ("retain_hull_mask", eq (retain a (hull b)) (retain a b)), - ("retain_completion_mask", eq (retain a (C b)) (retain a b)), - ("retain_restrict_witnesses", eq (retain a (restrict b a)) (retain a b)), - ("restrict_retain_mask", eq (restrict a (retain b a)) (restrict a b)), - ("retain_restrict_disjoint", eq (retain a (raffinate b a)) ((ofPaths []))), - ("retain_restrict_source", eq (retain (restrict a b) c) (restrict (retain a c) b)), - ("retain_raffinate_source", eq (retain (raffinate a b) c) (raffinate (retain a c) b)), - ("retain_lcp_masks", eq (retain (retain a b) c) (retain a (M b c))), - ("retain_divergence_masks", eq (retain (retain a b) c) (retain a (union (D b c) (union (retain b c) (retain c b))))), - ("restrict_overlap_masks", eq (restrict (restrict a b) c) (restrict a (union (restrict b c) (restrict c b)))), - ("retain_restrict_mask", eq (retain a (restrict b c)) (union (restrict (retain a b) c) (retain a (retain c b)))), - ("restrict_retain_lcp", eq (restrict a (retain b c)) (restrict a (restrict (M a c) b))), - ("basis_retain", eq (basis (retain a b)) (retain (basis a) b)), - ("hull_restrict", eq (hull (restrict a b)) (restrict (hull a) b)), - ("retain_subset", sub (retain a b) (a)), - ("retain_inter_right_bound", sub (retain a (inter b c)) (inter (retain a b) (retain a c))), - ("retain_diff_right_bound", sub (diff (retain a b) (retain a c)) (retain a (diff b c))), - ("retain_nested_bound", sub (retain a (retain b c)) (retain (retain a b) c)), - ("retain_hull_source_bound", sub (retain (hull a) b) (hull (retain a b))), - ("divergence_retain_bound", sub (D (retain a c) (retain b f)) (inter (D a b) (D c f))), - ("branches_retain_bound", sub (Br (retain a b)) (inter (Br a) (Br b))), - ("retain_empty_duality", (retain a b).isEmptyMap == (restrict b a).isEmptyMap), - ("retain_identity", eq (retain a b) a == covers a b), - ("retain_count_bound", decide (count (retain a b) <= count a)) ] - -/-- Closed divergence and branch closure, including canonical generators and filters. -/ -def closedAlgebra (a b c f : PathSpace) : Checks := - [ ("completion_union", eq (C (union a b)) (union (union (C a) (C b)) (D a b))), - ("completion_union_lcp", eq (C (union a b)) (union (union (C a) (C b)) (M a b))), - ("completion_union_absorb", eq (C (union (C a) (C b))) (C (union a b))), - ("hull_completion", eq (hull (C a)) (hull a)), - ("completion_hull", eq (union a (C (hull a))) (C a)), - ("hull_remove_branches", eq (hull (diff a (Br a))) (hull a)), - ("branches_remove_branches", eq (Br (diff a (Br a))) (Br a)), - ("completion_remove_branches", eq (C (diff a (Br a))) (C a)), - ("completion_diff_branches", eq (diff (C a) (Br a)) (diff a (Br a))), - ("lcp_completion_left", eq (M (C a) b) (M a b)), - ("lcp_completion_right", eq (M a (C b)) (M a b)), - ("lcp_completion", eq (M (C a) (C b)) (M a b)), - ("lcp_repeat", eq (M a (M a b)) (M a b)), - ("lcp_medial", eq (M (M a b) (M c f)) (M (M a c) (M b f))), - ("lcp_four_factors", eq (M (union a b) (union c f)) (union (union (M a c) (M a f)) (union (M b c) (M b f)))), - ("lcp_closed_join", eq (M a (C (union b c))) (union (M a b) (M a c))), - ("lcp_new_marks", eq (diff (M a b) (union a b)) (diff (D a b) (union a b))), - ("retain_lcp_operand", eq (retain a (M a b)) (retain a b)), - ("hull_lcp_hulls", eq (hull (M (hull a) (hull b))) (hull (M a b))), - ("completion_restrict", eq (C (restrict a b)) (union (restrict (C a) b) (Br (retain b a)))), - ("completion_restrict_closed", eq (C (restrict a (C b))) (restrict (C a) (C b))), - ("lcp_restrict", eq (M (restrict a c) (restrict b c)) (union (restrict (M a b) c) (D (retain c a) (retain c b)))), - ("lcp_restrict_closed", eq (M (restrict a (C c)) (restrict b (C c))) (restrict (M a b) (C c))), - ("closed_inter", eq (C (inter (C a) (C b))) (inter (C a) (C b))), - ("closed_retain", eq (C (retain (C a) b)) (retain (C a) b)), - ("closed_restrict", eq (C (restrict (C a) (C b))) (restrict (C a) (C b))), - ("closed_raffinate", eq (C (raffinate (C a) b)) (raffinate (C a) b)), - ("closed_lcp_union", eq (C (union (M a b) (M a c))) (union (M a b) (M a c))), - ("closed_join_assoc", eq (C (union (C (union a b)) c)) (C (union a (C (union b c))))), - ("closed_join_comm", eq (C (union a b)) (C (union b a))), - ("closed_join_idem", eq (C (union (C a) (C a))) (C a)), - ("closed_join_empty", eq (C (union (C a) (ofPaths []))) (C a)), - ("closed_join_absorption", eq (C (union (C a) (inter (C a) b))) (C a)), - ("closed_meet_absorption", eq (inter a (C (union a b))) a), - ("lcpLE_product_left", eq (M (M a b) a) (M a b)), - ("lcpLE_product_right", eq (M (M a b) b) (M a b)), - ("completion_wrap", eq (C (wrap [0,1] a)) (wrap [0,1] (C a))), - ("completion_unwrap", eq (C (unwrap a [0])) (unwrap (C a) [0])), - ("completion_extensive", sub a (C a)), - ("completion_inter_bound", sub (C (inter a b)) (inter (C a) (C b))), - ("lcp_inter_lower", sub (inter a b) (M a b)), - ("lcp_inter_bound", sub (M (inter a b) c) (inter (M a c) (M b c))), - ("lcp_diff_bound", sub (diff (M a c) (M b c)) (M (diff a b) c)), - ("lcp_union_bound", sub (M a b) (C (union a b))), - ("lcp_retain_bound", sub (M (retain a c) (retain b f)) (retain (M a b) (M c f))), - ("completion_retain_bound", sub (C (retain a b)) (retain (C a) b)), - ("completion_raffinate_bound", sub (C (raffinate a b)) (raffinate (C a) b)), - ("completion_least", sub (C a) (C b) == sub a (C b)), - ("completion_generators", eq (C b) (C a) == (sub (diff a (Br a)) b && sub b (C a))), - ("completion_equiv_generators", eq (C a) (C b) == eq (diff a (Br a)) (diff b (Br b))), - ("closed_union_iff", eq (C (union (C a) (C b))) (union (C a) (C b)) == sub (D (C a) (C b)) (union (C a) (C b))), - ("closed_join_least", sub (C (union a b)) (C c) == (sub a (C c) && sub b (C c))), - ("lcpLE_iff", eq (M a b) a == (covers a b && sub (D a b) a && sub (retain b a) a)), - ("lcpLE_product_iff", eq (M a (M b c)) a == (eq (M a b) a && eq (M a c) a)), - ("completion_cardinality", decide (count (C a) <= count a + (count (hull a) - 1))), - ("completion_cardinality_linear", decide (count a <= count (C a) && count (C a) <= 2 * count a - 1)), - ("basis_completion", implies (!a.isEmptyMap) (eq (basis (C a)) [commonPrefix a])) ] - -/-- Assumptions are executable guards, so unconstrained inputs are safe to test. -/ -def all (a b c f : PathSpace) : Checks := - unary a ++ binary a b ++ ternary a b c ++ quaternary a b c f ++ retention a b c f ++ closedAlgebra a b c f ++ - (pathLaws a b []) ++ (pathLaws a b [0]) ++ (pathLaws a b [0,1,0]) - -def failures (checks : Checks) : List String := (checks.filter (! ·.2)).map (·.1) -end PrunedModel.Convex.PathSetLaws diff --git a/lean/PrunedModel/Convex/PathSetPowers.lean b/lean/PrunedModel/Convex/PathSetPowers.lean index faf71e8b..cdb5dc07 100644 --- a/lean/PrunedModel/Convex/PathSetPowers.lean +++ b/lean/PrunedModel/Convex/PathSetPowers.lean @@ -76,7 +76,7 @@ theorem general_product (a b x y : PathSpace) (p : Path) : p ∈ divergence (product a x) (product b y) ↔ p ∈ (if x = ofPaths [] ∨ y = ofPaths [] then ofPaths [] else union (union (divergence a b) (product (inter a b) (divergence x y))) - (union (PathSetLaws.leftOverlap a b x y) (PathSetLaws.rightOverlap a b x y))) := by + (union (leftOverlap a b x y) (rightOverlap a b x y))) := by by_cases hx : x = ofPaths [] · subst x; simp · by_cases hy : y = ofPaths [] diff --git a/lean/PrunedModel/Convex/PathSetProduct.lean b/lean/PrunedModel/Convex/PathSetProduct.lean index 504ebf42..7fbbb551 100644 --- a/lean/PrunedModel/Convex/PathSetProduct.lean +++ b/lean/PrunedModel/Convex/PathSetProduct.lean @@ -1,5 +1,4 @@ import PrunedModel.Convex.PathSetRecursive -import PrunedModel.Convex.PathSetLaws namespace PathMapModel.Path open PathMapModel @@ -34,18 +33,25 @@ theorem mem_proper_overlap (a b : PathSpace) (f : Path → Path → PathSpace) ( | nil => exact False.elim (hr rfl) | cons c rs => simpa [hs] using hp +/-- The proper-prefix contributions in the full four-factor product expansion. -/ +def leftOverlap (a b x y : PathSpace) : PathSpace := + properOverlap a b fun p r => wrap p (divergence x (wrap r y)) + +def rightOverlap (a b x y : PathSpace) : PathSpace := + properOverlap b a fun p r => wrap p (divergence (wrap r x) y) + theorem mem_leftOverlap (a b x y : PathSpace) (p : Path) : - p ∈ PathSetLaws.leftOverlap a b x y ↔ ∃ u ∈ a, ∃ r, r ≠ [] ∧ u ++ r ∈ b ∧ + p ∈ leftOverlap a b x y ↔ ∃ u ∈ a, ∃ r, r ≠ [] ∧ u ++ r ∈ b ∧ ∃ q ∈ divergence x (wrap r y), u ++ q = p := by - simp only [PathSetLaws.leftOverlap,PathSetLaws.D] + simp only [leftOverlap] rw [mem_proper_overlap a b (fun u r => wrap u ((divergence x (wrap r y)))) p] change (∃ u ∈ a, ∃ r, r ≠ [] ∧ u ++ r ∈ b ∧ p ∈ wrap u ((divergence x (wrap r y)))) ↔ _ simp only [mem_wrap] theorem mem_rightOverlap (a b x y : PathSpace) (p : Path) : - p ∈ PathSetLaws.rightOverlap a b x y ↔ ∃ v ∈ b, ∃ r, r ≠ [] ∧ v ++ r ∈ a ∧ + p ∈ rightOverlap a b x y ↔ ∃ v ∈ b, ∃ r, r ≠ [] ∧ v ++ r ∈ a ∧ ∃ q ∈ divergence (wrap r x) y, v ++ q = p := by - simp only [PathSetLaws.rightOverlap,PathSetLaws.D] + simp only [rightOverlap] rw [mem_proper_overlap b a (fun v r => wrap v ((divergence (wrap r x) y))) p] change (∃ v ∈ b, ∃ r, r ≠ [] ∧ v ++ r ∈ a ∧ p ∈ wrap v ((divergence (wrap r x) y))) ↔ _ simp only [mem_wrap] @@ -53,7 +59,7 @@ theorem mem_rightOverlap (a b x y : PathSpace) (p : Path) : theorem divergence_product_nonempty (a b x y : PathSpace) (hx : x ≠ ofPaths []) (hy : y ≠ ofPaths []) (p : Path) : p ∈ divergence (product a x) (product b y) ↔ p ∈ divergence a b ∨ p ∈ product (inter a b) (divergence x y) ∨ - p ∈ PathSetLaws.leftOverlap a b x y ∨ p ∈ PathSetLaws.rightOverlap a b x y := by + p ∈ leftOverlap a b x y ∨ p ∈ rightOverlap a b x y := by constructor · intro h obtain ⟨ux,hux,vy,hvy,hd⟩ := (mem_divergence _ _ _).mp h @@ -134,14 +140,14 @@ theorem prefix_free_product {a b x y : PathSpace} (hf : Antichain (union a b)) p ∈ divergence (product a x) (product b y) ↔ p ∈ divergence a b ∨ p ∈ product (inter a b) (divergence x y) := by rw [divergence_product_nonempty a b x y hx hy] - have hl : p ∉ PathSetLaws.leftOverlap a b x y := by + have hl : p ∉ leftOverlap a b x y := by intro h obtain ⟨u,hu,r,hr,hv,_⟩ := (mem_leftOverlap _ _ _ _ _).mp h have he := hf u ((mem_union a b _).mpr (Or.inl hu)) (u++r) ((mem_union a b _).mpr (Or.inr hv)) ((Path.prefix_iff_extension _ _).mpr ⟨r,rfl⟩) have hn : r = [] := by have hh := congrArg List.length he; simpa using hh exact hr hn - have hr : p ∉ PathSetLaws.rightOverlap a b x y := by + have hr : p ∉ rightOverlap a b x y := by intro h obtain ⟨v,hv,r,hr,hu,_⟩ := (mem_rightOverlap _ _ _ _ _).mp h have he := hf v ((mem_union a b _).mpr (Or.inr hv)) (v++r) ((mem_union a b _).mpr (Or.inl hu)) diff --git a/lean/PrunedModel/Convex/PathSetProofs.lean b/lean/PrunedModel/Convex/PathSetProofs.lean index 9a157ee2..e72fbcce 100644 --- a/lean/PrunedModel/Convex/PathSetProofs.lean +++ b/lean/PrunedModel/Convex/PathSetProofs.lean @@ -72,7 +72,7 @@ theorem singleton_polarization (a b : Path) (p : Path) : simp [branches, mem_divergence, Path.divergence_comm b a] /-- A symmetric bilinear operation with this diagonal is uniquely determined. -The empty laws are listed explicitly, as in the executable catalog. -/ +The hypotheses include both empty-space identities. -/ theorem divergence_unique (f : PathSpace → PathSpace → Path → Prop) (he : ∀ a p, ¬ f (ofPaths []) a p ∧ ¬ f a (ofPaths []) p) diff --git a/tests/path_set_properties.rs b/tests/path_set_properties.rs new file mode 100644 index 00000000..53c1ef6b --- /dev/null +++ b/tests/path_set_properties.rs @@ -0,0 +1,472 @@ +//! Properties outside the generated algebraic expression laws, including +//! cardinality, prefix coverage, recursive specifications, and closure generators. +//! Exportable equations are generated in differential/src/algebraic/path_set_laws.rs. +use pathmap::{ + PathMap, + experimental::path_sets::{basis, branches as br, divergence as d, hull, retain}, + zipper::*, +}; +use rand::{Rng, SeedableRng, rngs::StdRng}; +use std::collections::BTreeSet; + +type KeySet = BTreeSet>; +type M = PathMap<()>; + +fn e() -> M { + M::single([], ()) +} + +fn count(a: &M) -> usize { + a.val_count() +} + +fn height(a: &M) -> usize { + a.iter().map(|(p, _)| p.len()).max().unwrap_or(0) +} + +fn interior(a: &M) -> M { + a.subtract(&hull(a)) +} + +fn completion(a: &M) -> M { + a.join(&br(a)) +} + +fn raff(a: &M, p: &M) -> M { + a.subtract(&a.restrict(p)) +} + +fn sym(a: &M, b: &M) -> M { + a.subtract(b).join(&b.subtract(a)) +} + +fn covers(a: &M, b: &M) -> bool { + a.iter() + .all(|(p, _)| b.iter().any(|(q, _)| q.starts_with(&p))) +} + +fn prefix_free(a: &M) -> bool { + set_from_map(a) == set_from_map(&basis(a)) +} + +fn wrap(p: &[u8], a: &M) -> M { + let mut out = M::new(); + let mut z = out.write_zipper_at_path(p); + z.join_map_into(a.clone()); + // Make the helper independent of the graft_root_vals feature. + if a.get([]).is_some() { + z.set_val(()); + } + out +} + +fn unwrap(a: &M, p: &[u8]) -> M { + let z = a.read_zipper_at_path(p); + let mut out = z.make_map(); + if z.is_val() { + out.set_val_at([], ()); + } + out +} + +fn product(a: &M, b: &M) -> M { + let mut out = M::new(); + for (p, _) in a.iter() { + let mut z = out.write_zipper_at_path(&p); + z.join_map_into(b.clone()); + if b.get([]).is_some() { + z.set_val(()); + } + } + out +} + +fn head(a: &M) -> M { + let mut out = M::new(); + for (p, _) in a.iter() { + if let Some(&c) = p.first() { + out.set_val_at([c], ()); + } + } + out +} + +fn tails(a: &M) -> M { + let mut out = M::new(); + for (p, _) in a.iter() { + if !p.is_empty() { + out.set_val_at(&p[1..], ()); + } + } + out +} + +fn lcp(a: &[u8], b: &[u8]) -> Vec { + a[..a.iter().zip(b).take_while(|(x, y)| x == y).count()].to_vec() +} + +fn lcp_product(a: &M, b: &M) -> M { + let mut out = M::new(); + for (p, _) in a.iter() { + for (q, _) in b.iter() { + out.set_val_at(lcp(&p, &q), ()); + } + } + out +} + +fn common_prefix(a: &M) -> Vec { + let mut it = a.iter(); + let Some((p, _)) = it.next() else { + return vec![]; + }; + it.fold(p, |p, (q, _)| lcp(&p, &q)) +} + +fn power(a: &M, n: usize) -> M { + (0..n).fold(e(), |b, _| product(a, &b)) +} + +fn branch_iter(a: &M, n: usize) -> M { + (0..n).fold(a.clone(), |b, _| br(&b)) +} + +// Independent recursive specifications (no call to the operation under test). + +fn basis_rec(a: &M) -> M { + if a.get([]).is_some() { + return e(); + } + head(a).iter().fold(M::new(), |out, (p, _)| { + out.join(&wrap(&p, &basis_rec(&unwrap(a, &p)))) + }) +} + +fn hull_rec(a: &M) -> M { + let h = head(a); + let root = if a.get([]).is_some() && h.is_empty() { + e() + } else { + M::new() + }; + h.iter().fold(root, |out, (p, _)| { + out.join(&wrap(&p, &hull_rec(&unwrap(a, &p)))) + }) +} + +fn divergence_rec(a: &M, b: &M) -> M { + let ha = head(a); + let hb = head(b); + let cross = ha.iter().any(|(p, _)| hb.iter().any(|(q, _)| p != q)); + let root = if cross { e() } else { M::new() }; + ha.meet(&hb).iter().fold(root, |out, (p, _)| { + out.join(&wrap(&p, &divergence_rec(&unwrap(a, &p), &unwrap(b, &p)))) + }) +} + +fn retain_rec(p: &M, a: &M) -> M { + let root = if p.get([]).is_some() && !a.is_empty() { + e() + } else { + M::new() + }; + head(p).meet(&head(a)).iter().fold(root, |out, (q, _)| { + out.join(&wrap(&q, &retain_rec(&unwrap(p, &q), &unwrap(a, &q)))) + }) +} + +fn overlaps(a: &M, b: &M, x: &M, y: &M) -> M { + let mut out = M::new(); + for (p, _) in a.iter() { + for (q, _) in b.iter() { + if q.len() > p.len() && q.starts_with(&p) { + out = out.join(&wrap(&p, &d(x, &wrap(&q[p.len()..], y)))); + } + if p.len() > q.len() && p.starts_with(&q) { + out = out.join(&wrap(&q, &d(&wrap(&p[q.len()..], x), y))); + } + } + } + out +} + +#[track_caller] +fn assert_same(a: &M, b: &M) { + assert_eq!(set_from_map(a), set_from_map(b)); +} + +#[track_caller] +fn assert_subset(a: &M, b: &M) { + let a = set_from_map(a); + let b = set_from_map(b); + assert!(a.is_subset(&b), "{a:?} is not a subset of {b:?}"); +} + +fn retention_properties(a: &M, b: &M) { + assert_eq!(retain(a, b).is_empty(), b.restrict(a).is_empty()); + assert_eq!(set_from_map(&retain(a, b)) == set_from_map(a), covers(a, b)); + assert!(count(&retain(a, b)) <= count(a)); +} + +fn closure_properties(a: &M, b: &M, c: &M) { + let ca = completion(a); + let cb = completion(b); + let cc = completion(c); + let ab = lcp_product(a, b); + let ga = a.subtract(&br(a)); + let same = |x: &M, y: &M| set_from_map(x) == set_from_map(y); + let subset = |x: &M, y: &M| set_from_map(x).is_subset(&set_from_map(y)); + assert_same(&lcp_product(&ab, a), &ab); + assert_same(&lcp_product(&ab, b), &ab); + assert!(subset(&ca, &cb) == subset(a, &cb)); + assert!(same(&cb, &ca) == (subset(&ga, b) && subset(b, &ca))); + assert!(same(&ca, &cb) == same(&ga, &b.subtract(&br(b)))); + assert!(same(&completion(&ca.join(&cb)), &ca.join(&cb)) == subset(&d(&ca, &cb), &ca.join(&cb))); + assert!(subset(&completion(&a.join(b)), &cc) == (subset(a, &cc) && subset(b, &cc))); + assert!(same(&ab, a) == (covers(a, b) && subset(&d(a, b), a) && subset(&retain(b, a), a))); + assert!( + same(&lcp_product(a, &lcp_product(b, c)), a) + == (same(&ab, a) && same(&lcp_product(a, c), a)) + ); + assert!(count(&ca) <= count(a) + count(&hull(a)).saturating_sub(1)); + assert!(count(a) <= count(&ca) && count(&ca) <= (2 * count(a)).saturating_sub(1)); + if !a.is_empty() { + assert_same(&basis(&ca), &M::single(common_prefix(a), ())); + } +} + +fn properties(a: &M, b: &M, c: &M, f: &M) { + closure_properties(a, b, c); + retention_properties(a, b); + let x = d(a, b); + let ba = br(a); + let ha = hull(a); + let hb = hull(b); + let zero = M::new(); + assert_subset(&br(&ba), &ba); + assert_subset(&basis(a), a); + assert_subset(&ha, a); + assert_eq!(basis(a).is_empty(), a.is_empty()); + assert_eq!(ha.is_empty(), a.is_empty()); + assert!(covers(a, &ha) && covers(&basis(a), a)); + assert_same(&basis_rec(a), &basis(a)); + assert_same(&hull_rec(a), &ha); + assert_same(&divergence_rec(a, a), &ba); + assert!(count(&hull(&ba)) <= count(&ha) / 2); + if !a.is_empty() { + assert!(set_from_map(&ba) != set_from_map(a)); + } + assert_same(&branch_iter(a, height(a) + 1), &zero); + assert_subset(&br(&a.meet(b)), &ba.meet(&br(b))); + assert_subset(&ba.meet(&br(b)), &x); + assert_subset(&x, &br(&a.join(b))); + assert_subset(&interior(&x), &ba.join(&br(b))); + assert_subset(&br(&x), &x.meet(&ba.meet(&br(b)))); + if !x.is_empty() { + assert_same(&basis(&x), &M::single(common_prefix(&ha.join(&hb)), ())); + } + let all_prefix = |u: &M, v: &M| { + u.iter() + .all(|(p, _)| v.iter().all(|(q, _)| q.starts_with(&p))) + }; + assert!( + x.is_empty() + == (a.is_empty() + || b.is_empty() + || count(&ha) == 1 && all_prefix(&ha, &hb) + || count(&hb) == 1 && all_prefix(&hb, &ha)) + ); + assert_subset(&head(&x), &head(a).meet(&head(b))); + assert_subset(&tails(&x), &d(&tails(a), &tails(b))); + assert_same(&divergence_rec(a, b), &x); + assert_same(&retain_rec(a, b), &retain(a, b)); + assert!(count(&x) <= count(&hull(&a.join(b))).saturating_sub(1)); + assert!(count(&hull(&x)) <= count(&ha).min(count(&hb))); + if !x.is_empty() { + assert!(height(&x) < height(a).min(height(b))); + } + assert!(covers(&x, a) && covers(&x, b)); + // The generated expression for LCP uses divergence and retain. Check it + // against the independent all-pairs definition as well. + let m = lcp_product(a, b); + assert_same(&m, &x.join(&retain(a, b)).join(&retain(b, a))); + assert_subset(&d(&a.meet(b), c), &d(a, c).meet(&d(b, c))); + assert_subset(&d(a, c).subtract(&d(b, c)), &d(&a.subtract(b), c)); + assert_subset(&d(&a.subtract(b), c), &d(a, c)); + assert_subset(&sym(&d(a, c), &d(b, c)), &d(&sym(a, b), c)); + if set_from_map(a).is_subset(&set_from_map(b)) { + assert_subset(&d(a, c), &d(b, c)); + } + if covers(a, b) { + assert_subset(&d(a, c), &d(b, c)); + } + if covers(b, a) { + assert_same(&d(&a.join(b), c), &d(a, c)); + } + assert_subset(&d(&x, c), &d(a, c).meet(&d(b, c))); + assert_subset(&x.meet(&br(c)), &d(a, c).meet(&d(b, c))); + assert_subset( + &d(&x, &d(c, f)), + &d(a, c).meet(&d(a, f)).meet(&d(b, c)).meet(&d(b, f)), + ); + assert_subset( + &x.meet(&d(c, f)), + &d(a, c).meet(&d(b, f)).join(&d(a, f).meet(&d(b, c))), + ); + assert_subset(&d(&raff(a, c), &raff(b, f)), &raff(&x, &c.join(f))); + let prod_rhs = if c.is_empty() || f.is_empty() { + M::new() + } else { + x.join(&product(&a.meet(b), &d(c, f))) + .join(&overlaps(a, b, c, f)) + }; + assert_same(&d(&product(a, c), &product(b, f)), &prod_rhs); + let mut paths = vec![vec![], vec![0], vec![0, 1, 0]]; + paths.extend(a.iter().take(2).map(|(p, _)| p)); + for p in paths { + let single = M::single(&p, ()); + let chain = d(&single, b); + assert_same(&d(&unwrap(a, &p), &unwrap(b, &p)), &unwrap(&x, &p)); + assert!(count(&chain) <= p.len().min(count(&hb))); + assert_subset(&interior(&chain), &br(b)); + assert!(count(&br(&b.join(&single)).subtract(&br(b))) <= 1); + assert!(count(&d(&a.join(&single), b).subtract(&x)) <= p.len().min(count(&hb))); + } +} + +fn power_properties(a: &M) { + assert!(prefix_free(a)); + let max_power = if cfg!(miri) { 2 } else { 3 }; + for n in 0..=max_power { + for m in 0..=max_power { + let rhs = + (0..m.min(n)).fold(M::new(), |out, i| out.join(&product(&power(a, i), &br(a)))); + assert_same(&d(&power(a, m), &power(a, n)), &rhs); + } + } + for n in 0..=3 { + if !branch_iter(a, n).is_empty() { + assert!(2usize.pow(n as u32) <= count(&hull(a))); + } + } +} + +fn map_from_set(keys: &KeySet) -> M { + keys.iter().map(|p| (p.clone(), ())).collect() +} + +fn set_from_map(a: &M) -> KeySet { + a.iter().map(|(p, _)| p).collect() +} + +fn small(seed: u64, salt: u64) -> M { + let mut rng = StdRng::seed_from_u64(seed ^ salt); + let n = rng.random_range(0..7); + let keys: KeySet = (0..n) + .map(|_| { + let len = rng.random_range(0..6); + (0..len).map(|_| rng.random_range(0..3)).collect() + }) + .collect(); + map_from_set(&keys) +} + +/// All subsets of a depth-two binary tree, including every closed subspace. +/// Check anti-exchange and the necessity of each least generator. + +#[test] +fn exhaustive_branch_closure_generators() { + let paths = [ + vec![], + vec![0], + vec![1], + vec![0, 0], + vec![0, 1], + vec![1, 0], + vec![1, 1], + ]; + let paths = &paths[..if cfg!(miri) { 4 } else { paths.len() }]; + for mask in 0..(1usize << paths.len()) { + let keys: KeySet = paths + .iter() + .enumerate() + .filter(|(i, _)| mask & (1 << i) != 0) + .map(|(_, p)| p.clone()) + .collect(); + let a = map_from_set(&keys); + let closed = completion(&a); + let closed_keys = set_from_map(&closed); + let generators = a.subtract(&br(&a)); + for x in paths { + // Deleting a least generator strictly changes the closure. + if generators.get(x).is_some() { + assert_ne!( + closed_keys, + set_from_map(&completion(&a.subtract(&M::single(x, ())))) + ); + } + if closed_keys.contains(x) { + continue; + } + let with_x = completion(&a.join(&M::single(x, ()))); + for y in paths { + if x == y || closed_keys.contains(y) { + continue; + } + let with_y = completion(&a.join(&M::single(y, ()))); + if with_y.get(x).is_some() { + assert!( + with_x.get(y).is_none(), + "anti-exchange: {keys:?}, {x:?}, {y:?}" + ); + } + } + } + } +} + +#[test] +fn seeded_path_set_properties() { + let seeds = if cfg!(miri) { 2 } else { 256 }; + for seed in 0..seeds { + let case = std::panic::catch_unwind(|| { + let a = small(seed, 11); + let b = small(seed, 23); + let c = small(seed, 47); + let f = small(seed, 97); + properties(&a, &b, &c, &f); + // Correlated operands exercise the conditional properties. + properties(&hull(&a), &hull(&a).join(&hull(&b)), &e(), &e()); + properties(&a.join(&b), &b, &c, &f); + power_properties(&hull(&a)); + }); + assert!(case.is_ok(), "path-set properties failed at seed {seed}"); + } +} + +#[test] +fn dense_path_set_properties() { + // Values and children coexist at dense nodes, with shared prefixes and + // unequal depths. Include the root, NUL, and maximum byte explicitly. + let width = if cfg!(miri) { 4 } else { 48 }; + let mut a = e(); + let mut b = M::single([255], ()); + for i in 0..width { + a.set_val_at([0, i], ()); + a.set_val_at([0, i, 0], ()); + a.set_val_at([0, i, 255], ()); + b.set_val_at([0, i, 0], ()); + b.set_val_at([0, i, 1, 255], ()); + } + properties(&a, &b, &e(), &e()); + properties(&b, &a, &e(), &e()); +} + +#[test] +fn balanced_branch_powers() { + // The third branch iterate is nonempty, so its leaf bound is exercised. + let balanced: KeySet = (0..8) + .map(|i| vec![(i >> 2) & 1, (i >> 1) & 1, i & 1]) + .collect(); + power_properties(&map_from_set(&balanced)); +} diff --git a/tests/pathmap_algebra_differential.rs b/tests/pathmap_algebra_differential.rs index d4369aa9..1f0a2d6c 100644 --- a/tests/pathmap_algebra_differential.rs +++ b/tests/pathmap_algebra_differential.rs @@ -336,6 +336,3 @@ fn wide_restricted_by_sparse_matches_btreeset_oracle() { assert_eq!(set_from_map(&stems), expected, "WriteZipper::restricting seed {seed}"); } } - -#[path = "support/path_set_laws.rs"] -mod path_set_laws; diff --git a/tests/support/path_set_laws.rs b/tests/support/path_set_laws.rs deleted file mode 100644 index 74528ad2..00000000 --- a/tests/support/path_set_laws.rs +++ /dev/null @@ -1,959 +0,0 @@ -//! The full named Lean catalogue, evaluated as Rust PathMap expressions. -//! Shared seeded generators come from the existing algebra differential suite. -use super::{KeySet, map_from_set, next_u64, prefix_heavy_set, set_from_map, wide_set}; -use pathmap::{ - PathMap, - experimental::{ - convex::{convex_meet as cm, convex_subtract as cs}, - path_sets::{basis, branches as br, divergence as d, hull, retain}, - }, - zipper::*, -}; -use std::collections::BTreeSet; -type M = PathMap<()>; -fn e() -> M { - M::single([], ()) -} -fn count(a: &M) -> usize { - a.val_count() -} -fn height(a: &M) -> usize { - a.iter().map(|(p, _)| p.len()).max().unwrap_or(0) -} -fn interior(a: &M) -> M { - a.subtract(&hull(a)) -} -fn completion(a: &M) -> M { - a.join(&br(a)) -} -fn raff(a: &M, p: &M) -> M { - a.subtract(&a.restrict(p)) -} -fn sym(a: &M, b: &M) -> M { - a.subtract(b).join(&b.subtract(a)) -} -fn covers(a: &M, b: &M) -> bool { - a.iter() - .all(|(p, _)| b.iter().any(|(q, _)| q.starts_with(&p))) -} -fn prefix_free(a: &M) -> bool { - set_from_map(a) == set_from_map(&basis(a)) -} -fn wrap(p: &[u8], a: &M) -> M { - let mut out = M::new(); - let mut z = out.write_zipper_at_path(p); - z.join_map_into(a.clone()); - // Make the helper independent of the graft_root_vals feature. - if a.get([]).is_some() { - z.set_val(()); - } - out -} -fn unwrap(a: &M, p: &[u8]) -> M { - let z = a.read_zipper_at_path(p); - let mut out = z.make_map(); - if z.is_val() { - out.set_val_at([], ()); - } - out -} -fn product(a: &M, b: &M) -> M { - let mut out = M::new(); - for (p, _) in a.iter() { - let mut z = out.write_zipper_at_path(&p); - z.join_map_into(b.clone()); - if b.get([]).is_some() { - z.set_val(()); - } - } - out -} -fn head(a: &M) -> M { - let mut out = M::new(); - for (p, _) in a.iter() { - if let Some(&c) = p.first() { - out.set_val_at([c], ()); - } - } - out -} -fn tails(a: &M) -> M { - let mut out = M::new(); - for (p, _) in a.iter() { - if !p.is_empty() { - out.set_val_at(&p[1..], ()); - } - } - out -} -fn lcp(a: &[u8], b: &[u8]) -> Vec { - a[..a.iter().zip(b).take_while(|(x, y)| x == y).count()].to_vec() -} -fn lcp_product(a: &M, b: &M) -> M { - let mut out = M::new(); - for (p, _) in a.iter() { - for (q, _) in b.iter() { - out.set_val_at(lcp(&p, &q), ()); - } - } - out -} -fn common_prefix(a: &M) -> Vec { - let mut it = a.iter(); - let Some((p, _)) = it.next() else { - return vec![]; - }; - it.fold(p, |p, (q, _)| lcp(&p, &q)) -} -fn power(a: &M, n: usize) -> M { - (0..n).fold(e(), |b, _| product(a, &b)) -} -fn branch_iter(a: &M, n: usize) -> M { - (0..n).fold(a.clone(), |b, _| br(&b)) -} -// Independent recursive specifications (no call to the operation under test). -fn basis_rec(a: &M) -> M { - if a.get([]).is_some() { - return e(); - } - head(a).iter().fold(M::new(), |out, (p, _)| { - out.join(&wrap(&p, &basis_rec(&unwrap(a, &p)))) - }) -} -fn hull_rec(a: &M) -> M { - let h = head(a); - let root = if a.get([]).is_some() && h.is_empty() { - e() - } else { - M::new() - }; - h.iter().fold(root, |out, (p, _)| { - out.join(&wrap(&p, &hull_rec(&unwrap(a, &p)))) - }) -} -fn divergence_rec(a: &M, b: &M) -> M { - let ha = head(a); - let hb = head(b); - let cross = ha.iter().any(|(p, _)| hb.iter().any(|(q, _)| p != q)); - let root = if cross { e() } else { M::new() }; - ha.meet(&hb).iter().fold(root, |out, (p, _)| { - out.join(&wrap(&p, &divergence_rec(&unwrap(a, &p), &unwrap(b, &p)))) - }) -} -fn retain_rec(p: &M, a: &M) -> M { - let root = if p.get([]).is_some() && !a.is_empty() { - e() - } else { - M::new() - }; - head(p).meet(&head(a)).iter().fold(root, |out, (q, _)| { - out.join(&wrap(&q, &retain_rec(&unwrap(p, &q), &unwrap(a, &q)))) - }) -} -fn overlaps(a: &M, b: &M, x: &M, y: &M) -> M { - let mut out = M::new(); - for (p, _) in a.iter() { - for (q, _) in b.iter() { - if q.len() > p.len() && q.starts_with(&p) { - out = out.join(&wrap(&p, &d(x, &wrap(&q[p.len()..], y)))); - } - if p.len() > q.len() && p.starts_with(&q) { - out = out.join(&wrap(&q, &d(&wrap(&p[q.len()..], x), y))); - } - } - } - out -} -#[derive(Default)] -struct Coverage(BTreeSet<&'static str>); -impl Coverage { - fn check(&mut self, name: &'static str, ok: bool) { - assert!(ok, "path-set law {name}"); - self.0.insert(name); - } - fn eq(&mut self, name: &'static str, a: &M, b: &M) { - assert_eq!(set_from_map(a), set_from_map(b), "path-set law {name}"); - self.0.insert(name); - } - fn sub(&mut self, name: &'static str, a: &M, b: &M) { - assert!( - set_from_map(a).is_subset(&set_from_map(b)), - "path-set law {name}: {:?} not subset of {:?}", - set_from_map(a), - set_from_map(b) - ); - self.0.insert(name); - } -} -fn retention_laws(t: &mut Coverage, a: &M, b: &M, c: &M, f: &M) { - let zero = M::new(); - let same = |a: M, b: M| assert_eq!(set_from_map(&a), set_from_map(&b)); - same(cm(a, b), retain(&a.meet(b), &hull(a).meet(&hull(b)))); - same(cs(a, b), retain(a, &hull(a).subtract(b))); - same(cm(a, b).restrict(c), cm(&a.restrict(c), &b.restrict(c))); - same(cs(a, b).restrict(c), cs(&a.restrict(c), b)); - same(cs(a, b).restrict(c), cs(&a.restrict(c), &b.restrict(c))); - let tips = hull(a).meet(c); - let other_tips = hull(b).meet(f); - same( - cm(&retain(a, &tips), b), - retain(&a.meet(b), &tips.meet(&hull(b))), - ); - same( - cm(&retain(a, &tips), &retain(b, &other_tips)), - retain(&a.meet(b), &tips.meet(&other_tips)), - ); - same(cs(&retain(a, &tips), b), retain(a, &tips.subtract(b))); - same(cm(a, &retain(a, &tips)), retain(a, &tips)); - t.eq("retain_empty_left", &retain(&zero, a), &zero); - t.eq("retain_empty_right", &retain(a, &zero), &zero); - t.eq("retain_self", &retain(a, a), a); - t.eq( - "retain_union_left", - &retain(&a.join(b), c), - &retain(a, c).join(&retain(b, c)), - ); - t.eq( - "retain_inter_left", - &retain(&a.meet(b), c), - &retain(a, c).meet(&retain(b, c)), - ); - t.eq( - "retain_diff_left", - &retain(&a.subtract(b), c), - &retain(a, c).subtract(&retain(b, c)), - ); - t.eq( - "retain_symDiff_left", - &retain(&sym(a, b), c), - &sym(&retain(a, c), &retain(b, c)), - ); - t.eq( - "retain_union_right", - &retain(a, &b.join(c)), - &retain(a, b).join(&retain(a, c)), - ); - t.eq( - "retain_filter_inter", - &retain(&retain(a, b), c), - &retain(a, b).meet(&retain(a, c)), - ); - t.eq( - "retain_filter_comm", - &retain(&retain(a, b), c), - &retain(&retain(a, c), b), - ); - t.eq( - "retain_filter_idem", - &retain(&retain(a, b), b), - &retain(a, b), - ); - t.eq("retain_hull_mask", &retain(a, &hull(b)), &retain(a, b)); - t.eq( - "retain_completion_mask", - &retain(a, &completion(b)), - &retain(a, b), - ); - t.eq( - "retain_restrict_witnesses", - &retain(a, &b.restrict(a)), - &retain(a, b), - ); - t.eq( - "restrict_retain_mask", - &a.restrict(&retain(b, a)), - &a.restrict(b), - ); - t.eq("retain_restrict_disjoint", &retain(a, &raff(b, a)), &zero); - t.eq( - "retain_restrict_source", - &retain(&a.restrict(b), c), - &retain(a, c).restrict(b), - ); - t.eq( - "retain_raffinate_source", - &retain(&raff(a, b), c), - &raff(&retain(a, c), b), - ); - t.eq( - "retain_lcp_masks", - &retain(&retain(a, b), c), - &retain(a, &lcp_product(b, c)), - ); - t.eq( - "retain_divergence_masks", - &retain(&retain(a, b), c), - &retain(a, &d(b, c).join(&retain(b, c)).join(&retain(c, b))), - ); - t.eq( - "restrict_overlap_masks", - &a.restrict(b).restrict(c), - &a.restrict(&b.restrict(c).join(&c.restrict(b))), - ); - t.eq( - "retain_restrict_mask", - &retain(a, &b.restrict(c)), - &retain(a, b).restrict(c).join(&retain(a, &retain(c, b))), - ); - t.eq( - "restrict_retain_lcp", - &a.restrict(&retain(b, c)), - &a.restrict(&lcp_product(a, c).restrict(b)), - ); - t.eq("basis_retain", &basis(&retain(a, b)), &retain(&basis(a), b)); - t.eq("hull_restrict", &hull(&a.restrict(b)), &hull(a).restrict(b)); - t.sub("retain_subset", &retain(a, b), a); - t.sub( - "retain_inter_right_bound", - &retain(a, &b.meet(c)), - &retain(a, b).meet(&retain(a, c)), - ); - t.sub( - "retain_diff_right_bound", - &retain(a, b).subtract(&retain(a, c)), - &retain(a, &b.subtract(c)), - ); - t.sub( - "retain_nested_bound", - &retain(a, &retain(b, c)), - &retain(&retain(a, b), c), - ); - t.sub( - "retain_hull_source_bound", - &retain(&hull(a), b), - &hull(&retain(a, b)), - ); - t.sub( - "divergence_retain_bound", - &d(&retain(a, c), &retain(b, f)), - &d(a, b).meet(&d(c, f)), - ); - t.sub( - "branches_retain_bound", - &br(&retain(a, b)), - &br(a).meet(&br(b)), - ); - t.check( - "retain_empty_duality", - retain(a, b).is_empty() == b.restrict(a).is_empty(), - ); - t.check( - "retain_identity", - (set_from_map(&retain(a, b)) == set_from_map(a)) == covers(a, b), - ); - t.check("retain_count_bound", count(&retain(a, b)) <= count(a)); -} -fn closed_laws(t: &mut Coverage, a: &M, b: &M, c: &M, f: &M) { - let ca = completion(a); - let cb = completion(b); - let cc = completion(c); - let ab = lcp_product(a, b); - let ga = a.subtract(&br(a)); - let same = |x: &M, y: &M| set_from_map(x) == set_from_map(y); - let subset = |x: &M, y: &M| set_from_map(x).is_subset(&set_from_map(y)); - t.eq( - "completion_union", - &completion(&a.join(b)), - &ca.join(&cb).join(&d(a, b)), - ); - t.eq( - "completion_union_lcp", - &completion(&a.join(b)), - &ca.join(&cb).join(&ab), - ); - t.eq( - "completion_union_absorb", - &completion(&ca.join(&cb)), - &completion(&a.join(b)), - ); - t.eq("hull_completion", &hull(&ca), &hull(a)); - t.eq("completion_hull", &a.join(&completion(&hull(a))), &ca); - t.eq("hull_remove_branches", &hull(&ga), &hull(a)); - t.eq("branches_remove_branches", &br(&ga), &br(a)); - t.eq("completion_remove_branches", &completion(&ga), &ca); - t.eq("completion_diff_branches", &ca.subtract(&br(a)), &ga); - t.eq("lcp_completion_left", &lcp_product(&ca, b), &ab); - t.eq("lcp_completion_right", &lcp_product(a, &cb), &ab); - t.eq("lcp_completion", &lcp_product(&ca, &cb), &ab); - t.eq("lcp_repeat", &lcp_product(a, &ab), &ab); - t.eq( - "lcp_medial", - &lcp_product(&ab, &lcp_product(c, f)), - &lcp_product(&lcp_product(a, c), &lcp_product(b, f)), - ); - t.eq( - "lcp_four_factors", - &lcp_product(&a.join(b), &c.join(f)), - &lcp_product(a, c) - .join(&lcp_product(a, f)) - .join(&lcp_product(b, c)) - .join(&lcp_product(b, f)), - ); - t.eq( - "lcp_closed_join", - &lcp_product(a, &completion(&b.join(c))), - &ab.join(&lcp_product(a, c)), - ); - t.eq( - "lcp_new_marks", - &ab.subtract(&a.join(b)), - &d(a, b).subtract(&a.join(b)), - ); - t.eq("retain_lcp_operand", &retain(a, &ab), &retain(a, b)); - t.eq( - "hull_lcp_hulls", - &hull(&lcp_product(&hull(a), &hull(b))), - &hull(&ab), - ); - t.eq( - "completion_restrict", - &completion(&a.restrict(b)), - &ca.restrict(b).join(&br(&retain(b, a))), - ); - t.eq( - "completion_restrict_closed", - &completion(&a.restrict(&cb)), - &ca.restrict(&cb), - ); - t.eq( - "lcp_restrict", - &lcp_product(&a.restrict(c), &b.restrict(c)), - &ab.restrict(c).join(&d(&retain(c, a), &retain(c, b))), - ); - t.eq( - "lcp_restrict_closed", - &lcp_product(&a.restrict(&cc), &b.restrict(&cc)), - &ab.restrict(&cc), - ); - t.eq("closed_inter", &completion(&ca.meet(&cb)), &ca.meet(&cb)); - t.eq( - "closed_retain", - &completion(&retain(&ca, b)), - &retain(&ca, b), - ); - t.eq( - "closed_restrict", - &completion(&ca.restrict(&cb)), - &ca.restrict(&cb), - ); - t.eq( - "closed_raffinate", - &completion(&raff(&ca, b)), - &raff(&ca, b), - ); - t.eq( - "closed_lcp_union", - &completion(&ab.join(&lcp_product(a, c))), - &ab.join(&lcp_product(a, c)), - ); - t.eq( - "closed_join_assoc", - &completion(&completion(&a.join(b)).join(c)), - &completion(&a.join(&completion(&b.join(c)))), - ); - t.eq( - "closed_join_comm", - &completion(&a.join(b)), - &completion(&b.join(a)), - ); - t.eq("closed_join_idem", &completion(&ca.join(&ca)), &ca); - t.eq("closed_join_empty", &completion(&ca.join(&M::new())), &ca); - t.eq( - "closed_join_absorption", - &completion(&ca.join(&ca.meet(b))), - &ca, - ); - t.eq( - "closed_meet_absorption", - &a.meet(&completion(&a.join(b))), - a, - ); - t.eq("lcpLE_product_left", &lcp_product(&ab, a), &ab); - t.eq("lcpLE_product_right", &lcp_product(&ab, b), &ab); - t.eq( - "completion_wrap", - &completion(&wrap(&[0, 1], a)), - &wrap(&[0, 1], &ca), - ); - t.eq( - "completion_unwrap", - &completion(&unwrap(a, &[0])), - &unwrap(&ca, &[0]), - ); - t.sub("completion_extensive", a, &ca); - t.sub( - "completion_inter_bound", - &completion(&a.meet(b)), - &ca.meet(&cb), - ); - t.sub("lcp_inter_lower", &a.meet(b), &ab); - t.sub( - "lcp_inter_bound", - &lcp_product(&a.meet(b), c), - &lcp_product(a, c).meet(&lcp_product(b, c)), - ); - t.sub( - "lcp_diff_bound", - &lcp_product(a, c).subtract(&lcp_product(b, c)), - &lcp_product(&a.subtract(b), c), - ); - t.sub("lcp_union_bound", &ab, &completion(&a.join(b))); - t.sub( - "lcp_retain_bound", - &lcp_product(&retain(a, c), &retain(b, f)), - &retain(&ab, &lcp_product(c, f)), - ); - t.sub( - "completion_retain_bound", - &completion(&retain(a, b)), - &retain(&ca, b), - ); - t.sub( - "completion_raffinate_bound", - &completion(&raff(a, b)), - &raff(&ca, b), - ); - t.check("completion_least", subset(&ca, &cb) == subset(a, &cb)); - t.check( - "completion_generators", - same(&cb, &ca) == (subset(&ga, b) && subset(b, &ca)), - ); - t.check( - "completion_equiv_generators", - same(&ca, &cb) == same(&ga, &b.subtract(&br(b))), - ); - t.check( - "closed_union_iff", - same(&completion(&ca.join(&cb)), &ca.join(&cb)) == subset(&d(&ca, &cb), &ca.join(&cb)), - ); - t.check( - "closed_join_least", - subset(&completion(&a.join(b)), &cc) == (subset(a, &cc) && subset(b, &cc)), - ); - t.check( - "lcpLE_iff", - same(&ab, a) == (covers(a, b) && subset(&d(a, b), a) && subset(&retain(b, a), a)), - ); - t.check( - "lcpLE_product_iff", - same(&lcp_product(a, &lcp_product(b, c)), a) - == (same(&ab, a) && same(&lcp_product(a, c), a)), - ); - t.check( - "completion_cardinality", - count(&ca) <= count(a) + count(&hull(a)).saturating_sub(1), - ); - t.check( - "completion_cardinality_linear", - count(a) <= count(&ca) && count(&ca) <= (2 * count(a)).saturating_sub(1), - ); - if !a.is_empty() { - t.eq( - "basis_completion", - &basis(&ca), - &M::single(common_prefix(a), ()), - ); - } - assert!(same(&completion(&cm(&ca, &cb)), &cm(&ca, &cb))); - assert!(same(&completion(&cs(&ca, b)), &cs(&ca, b))); - assert!(subset(&completion(&cm(a, b)), &cm(&ca, &cb))); - assert!(subset(&completion(&cs(a, b)), &cs(&ca, b))); - assert!(same(&hull(&completion(&cm(a, b))), &hull(&cm(&ca, &cb)))); - assert!(same(&hull(&completion(&cs(a, b))), &hull(&cs(&ca, b)))); -} -fn laws(t: &mut Coverage, a: &M, b: &M, c: &M, f: &M) { - closed_laws(t, a, b, c, f); - retention_laws(t, a, b, c, f); - let x = d(a, b); - let ba = br(a); - let ha = hull(a); - let hb = hull(b); - let ca = completion(a); - let zero = M::new(); - let ep = e(); - let fork = M::single([0], ()).join(&M::single([1], ())); - t.eq("diagonal", &d(a, a), &ba); - t.eq("empty_left", &d(&zero, a), &zero); - t.eq("empty_right", &d(a, &zero), &zero); - t.eq("epsilon_left", &d(&ep, a), &zero); - t.eq("epsilon_right", &d(a, &ep), &zero); - t.eq("branch_completion", &br(&ca), &ba); - t.eq("completion_idempotent", &completion(&ca), &ca); - t.eq("branch_hull", &br(&ha), &ba); - t.eq("branch_epsilon", &br(&a.join(&ep)), &ba); - t.sub("branch_second_subset", &br(&ba), &ba); - t.eq("interior_branches", &d(a, &ba), &interior(&ba)); - t.sub("basis_subset", &basis(a), a); - t.sub("hull_subset", &ha, a); - t.eq("basis_idempotent", &basis(&basis(a)), &basis(a)); - t.eq("hull_idempotent", &hull(&ha), &ha); - t.eq("basis_of_hull", &basis(&ha), &ha); - t.eq("hull_of_basis", &hull(&basis(a)), &basis(a)); - t.check("basis_antichain", prefix_free(&basis(a))); - t.check("hull_antichain", prefix_free(&ha)); - t.check("basis_nonempty", basis(a).is_empty() == a.is_empty()); - t.check("hull_nonempty", ha.is_empty() == a.is_empty()); - t.check("basis_covers", covers(a, &ha) && covers(&basis(a), a)); - t.eq("basis_recursive", &basis_rec(a), &basis(a)); - t.eq("hull_recursive", &hull_rec(a), &ha); - t.eq("branch_recursive", &divergence_rec(a, a), &ba); - t.check("maximal_branch_count", count(&hull(&ba)) <= count(&ha) / 2); - if !a.is_empty() { - t.check( - "no_nonempty_branch_fixed_point", - set_from_map(&ba) != set_from_map(a), - ); - } - t.eq( - "branch_depth_nilpotence", - &branch_iter(a, height(a) + 1), - &zero, - ); - t.eq("symmetry", &x, &d(b, a)); - t.eq("terminal_invariance", &d(&a.join(&ep), &b.join(&ep)), &x); - t.eq("hull_invariance", &d(&ha, &hb), &x); - t.eq("completion_invariance", &d(&ca, &completion(b)), &x); - t.eq("branch_union", &br(&a.join(b)), &ba.join(&br(b)).join(&x)); - t.sub( - "branch_intersection_lower", - &br(&a.meet(b)), - &ba.meet(&br(b)), - ); - t.sub("branch_sandwich_lower", &ba.meet(&br(b)), &x); - t.sub("branch_sandwich_upper", &x, &br(&a.join(b))); - t.eq("output_completion", &completion(&x), &x); - t.eq("absorbed_branch_marks", &br(&a.join(&x)), &ba); - t.eq("nested_exact", &d(a, &x), &ba.meet(&interior(&x))); - t.eq("interior_exact", &d(&a.join(b), &x), &interior(&x)); - t.sub("interior_attribution", &interior(&x), &ba.join(&br(b))); - t.sub("output_branches", &br(&x), &x.meet(&ba.meet(&br(b)))); - if !x.is_empty() { - t.eq( - "first_divergence", - &basis(&x), - &M::single(common_prefix(&ha.join(&hb)), ()), - ); - } - let all_prefix = |u: &M, v: &M| { - u.iter() - .all(|(p, _)| v.iter().all(|(q, _)| q.starts_with(&p))) - }; - t.check( - "zero_criterion", - x.is_empty() - == (a.is_empty() - || b.is_empty() - || count(&ha) == 1 && all_prefix(&ha, &hb) - || count(&hb) == 1 && all_prefix(&hb, &ha)), - ); - t.eq("root_heads", &d(&head(a), &head(b)), &x.meet(&ep)); - t.sub("output_heads", &head(&x), &head(a).meet(&head(b))); - t.sub("tails_bound", &tails(&x), &d(&tails(a), &tails(b))); - t.eq("recursive_divergence", &divergence_rec(a, b), &x); - t.eq("retain_recursive", &retain_rec(a, b), &retain(a, b)); - t.check( - "output_cardinality", - count(&x) <= count(&hull(&a.join(b))).saturating_sub(1), - ); - t.check( - "output_hull_cardinality", - count(&hull(&x)) <= count(&ha).min(count(&hb)), - ); - if !x.is_empty() { - t.check("output_depth", height(&x) < height(a).min(height(b))); - } - t.check("output_covered", covers(&x, a) && covers(&x, b)); - t.eq("fork_completion", &br(&product(a, &fork)), &ca); - let m = lcp_product(a, b); - t.eq("fork_lcp", &d(&product(a, &fork), &product(b, &fork)), &m); - t.eq( - "lcp_correction", - &m, - &x.join(&retain(a, b)).join(&retain(b, a)), - ); - t.eq("lcp_diagonal", &lcp_product(a, a), &ca); - t.eq("lcp_symmetry", &m, &lcp_product(b, a)); - t.eq("lcp_output_completion", &completion(&m), &m); - t.eq("range_realization", &br(&product(&ca, &fork)), &ca); - t.eq( - "basis_union", - &basis(&a.join(b)), - &basis(&basis(a).join(&basis(b))), - ); - t.eq("hull_union", &hull(&a.join(b)), &hull(&ha.join(&hb))); - t.eq( - "restriction_basis_mask", - &a.restrict(b), - &a.restrict(&basis(b)), - ); - t.eq("left_union", &d(&a.join(b), c), &d(a, c).join(&d(b, c))); - t.eq("right_union", &d(a, &b.join(c)), &d(a, b).join(&d(a, c))); - t.sub( - "intersection_bound", - &d(&a.meet(b), c), - &d(a, c).meet(&d(b, c)), - ); - t.sub( - "difference_lower", - &d(a, c).subtract(&d(b, c)), - &d(&a.subtract(b), c), - ); - t.sub("difference_upper", &d(&a.subtract(b), c), &d(a, c)); - t.sub( - "symmetric_difference_bound", - &sym(&d(a, c), &d(b, c)), - &d(&sym(a, b), c), - ); - if set_from_map(a).is_subset(&set_from_map(b)) { - t.sub("monotonicity", &d(a, c), &d(b, c)); - } - if covers(a, b) { - t.sub("prefix_extension_monotonicity", &d(a, c), &d(b, c)); - } - if covers(b, a) { - t.eq("covered_mark_invariance", &d(&a.join(b), c), &d(a, c)); - } - t.sub("nested_absorption", &d(&x, c), &d(a, c).meet(&d(b, c))); - t.eq("witness_absorption", &d(&a.join(&x), c), &d(a, c)); - t.sub( - "branch_probe_exchange", - &x.meet(&br(c)), - &d(a, c).meet(&d(b, c)), - ); - t.eq( - "lcp_associativity", - &lcp_product(&m, c), - &lcp_product(a, &lcp_product(b, c)), - ); - t.eq( - "lcp_bilinearity", - &lcp_product(&a.join(b), c), - &lcp_product(a, c).join(&lcp_product(b, c)), - ); - t.eq( - "one_mask", - &d(&a.restrict(c), b), - &x.restrict(c).join(&d(&retain(c, a), b)), - ); - t.eq( - "same_mask", - &d(&a.restrict(c), &b.restrict(c)), - &x.restrict(c).join(&d(&retain(c, a), &retain(c, b))), - ); - t.eq( - "filter_partition", - &x, - &d(&a.restrict(c), b).join(&d(&raff(a, c), b)), - ); - if prefix_free(a) && !b.is_empty() && !c.is_empty() { - t.eq( - "common_prefix_code", - &d(&product(a, b), &product(a, c)), - &ba.join(&product(a, &d(b, c))), - ); - } - t.sub( - "four_point_absorption", - &d(&x, &d(c, f)), - &d(a, c).meet(&d(a, f)).meet(&d(b, c)).meet(&d(b, f)), - ); - t.sub( - "four_point_exchange", - &x.meet(&d(c, f)), - &d(a, c).meet(&d(b, f)).join(&d(a, f).meet(&d(b, c))), - ); - t.eq( - "incremental_update", - &d(&a.join(c), &b.join(f)), - &x.join(&d(c, b)).join(&d(a, f)).join(&d(c, f)), - ); - t.eq( - "two_masks", - &d(&a.restrict(c), &b.restrict(f)), - &x.restrict(c) - .restrict(f) - .join(&d(a, &retain(f, b)).restrict(c)) - .join(&d(&retain(c, a), b).restrict(f)) - .join(&d(&retain(c, a), &retain(f, b))), - ); - t.sub( - "raffination_bound", - &d(&raff(a, c), &raff(b, f)), - &raff(&x, &c.join(f)), - ); - let prod_rhs = if c.is_empty() || f.is_empty() { - M::new() - } else { - x.join(&product(&a.meet(b), &d(c, f))) - .join(&overlaps(a, b, c, f)) - }; - t.eq( - "general_product", - &d(&product(a, c), &product(b, f)), - &prod_rhs, - ); - if prefix_free(&a.join(b)) && !c.is_empty() && !f.is_empty() { - t.eq( - "prefix_free_product", - &d(&product(a, c), &product(b, f)), - &x.join(&product(&a.meet(b), &d(c, f))), - ); - } - let mut paths = vec![vec![], vec![0], vec![0, 1, 0]]; - paths.extend(a.iter().take(2).map(|(p, _)| p)); - for p in paths { - let single = M::single(&p, ()); - let chain = d(&single, b); - t.eq("wrap", &d(&wrap(&p, a), &wrap(&p, b)), &wrap(&p, &x)); - t.eq( - "unwrap", - &d(&unwrap(a, &p), &unwrap(b, &p)), - &unwrap(&x, &p), - ); - t.eq( - "single_prefix_restriction", - &d(&a.restrict(&single), &b.restrict(&single)), - &x.restrict(&single), - ); - t.eq("singleton_chain", &br(&chain), &zero); - t.check("singleton_bound", count(&chain) <= p.len().min(count(&hb))); - t.sub("singleton_existing_branches", &interior(&chain), &br(b)); - t.check( - "singleton_branch_update", - count(&br(&b.join(&single)).subtract(&br(b))) <= 1, - ); - t.check( - "singleton_divergence_update", - count(&d(&a.join(&single), b).subtract(&x)) <= p.len().min(count(&hb)), - ); - } -} -fn power_laws(t: &mut Coverage, a: &M) { - for n in 0..=3 { - for m in 0..=3 { - if prefix_free(a) { - let rhs = - (0..m.min(n)).fold(M::new(), |out, i| out.join(&product(&power(a, i), &br(a)))); - t.eq("prefix_code_powers", &d(&power(a, m), &power(a, n)), &rhs); - } - if !branch_iter(a, n).is_empty() { - t.check("branch_leaf_bound", 2usize.pow(n as u32) <= count(&hull(a))); - } - } - } -} -fn small(seed: u64, salt: u64) -> KeySet { - let mut state = seed ^ salt; - let n = next_u64(&mut state) % 7; - (0..n) - .map(|_| { - let len = next_u64(&mut state) % 6; - (0..len) - .map(|_| ((next_u64(&mut state) >> 32) % 3) as u8) - .collect() - }) - .collect() -} -/// All subsets of a depth-two binary tree, including every closed subspace. -/// Check anti-exchange and least generators independently of the named catalogue. -#[test] -fn exhaustive_branch_closure_generators() { - let paths = [ - vec![], - vec![0], - vec![1], - vec![0, 0], - vec![0, 1], - vec![1, 0], - vec![1, 1], - ]; - for mask in 0..(1usize << paths.len()) { - let keys: KeySet = paths - .iter() - .enumerate() - .filter(|(i, _)| mask & (1 << i) != 0) - .map(|(_, p)| p.clone()) - .collect(); - let a = map_from_set(&keys); - let closed = completion(&a); - let closed_keys = set_from_map(&closed); - assert_eq!(closed_keys, set_from_map(&lcp_product(&a, &a))); - let generators = a.subtract(&br(&a)); - assert_eq!(closed_keys, set_from_map(&completion(&generators))); - for x in &paths { - // Deleting a least generator strictly changes the closure. - if generators.get(x).is_some() { - assert_ne!( - closed_keys, - set_from_map(&completion(&a.subtract(&M::single(x, ())))) - ); - } - if closed_keys.contains(x) { - continue; - } - let with_x = completion(&a.join(&M::single(x, ()))); - for y in &paths { - if x == y || closed_keys.contains(y) { - continue; - } - let with_y = completion(&a.join(&M::single(y, ()))); - if with_y.get(x).is_some() { - assert!( - with_x.get(y).is_none(), - "anti-exchange: {keys:?}, {x:?}, {y:?}" - ); - } - } - } - } -} - -#[test] -fn seeded_full_path_set_law_catalogue() { - let mut t = Coverage::default(); - #[cfg(not(miri))] - let seeds = 256; - #[cfg(miri)] - let seeds = 2; - for seed in 0..seeds { - // Report the complete reproducible seed on any assertion failure. - let case = std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| { - let a = map_from_set(&small(seed, 11)); - let b = map_from_set(&small(seed, 23)); - let c = map_from_set(&small(seed, 47)); - let f = map_from_set(&small(seed, 97)); - laws(&mut t, &a, &b, &c, &f); - // Deliberate correlated operands exercise the guards non-vacuously. - laws(&mut t, &hull(&a), &hull(&a).join(&hull(&b)), &e(), &e()); - laws(&mut t, &a.join(&b), &b, &c, &f); - power_laws(&mut t, &hull(&a)); - })); - assert!( - case.is_ok(), - "full path-set law catalogue failed at seed {seed}" - ); - } - // Dense children and overlapping prefix terminals using existing fuzz generators. - for seed in 0..2 { - let a = map_from_set(&prefix_heavy_set(seed, 11)); - let b = map_from_set(&wide_set(seed, 23)); - laws(&mut t, &a, &b, &e(), &e()); - } - // Balanced depth-three binary trie exercises a nonempty third branch iterate. - let balanced: KeySet = (0..8) - .map(|i| vec![(i >> 2) & 1, (i >> 1) & 1, i & 1]) - .collect(); - power_laws(&mut t, &map_from_set(&balanced)); - // Ensure every catalogue name is executed, with guarded laws counted only - // when the guard is true. New Lean laws automatically require Rust coverage. - let catalog = include_str!("../../lean/PrunedModel/Convex/PathSetLaws.lean"); - let expected: BTreeSet<_> = catalog - .lines() - .filter_map(|line| { - let start = line.find("(\"")? + 2; - let tail = &line[start..]; - Some(&tail[..tail.find('"')?]) - }) - .collect(); - assert_eq!(t.0, expected, "Rust / Lean law catalogue coverage drift"); -} From 1626b64d0b437be79ec96adcb34631b24f06cca5 Mon Sep 17 00:00:00 2001 From: adamv-symbolica Date: Fri, 20 Nov 2026 14:48:49 +0000 Subject: [PATCH 15/15] Prove the exact completion gaps for convex and path-set operations --- differential/src/algebraic/path_set_laws.rs | 52 +++++- differential/tests/algebraic.rs | 4 +- lean/PrunedModel/Convex.lean | 1 + lean/PrunedModel/Convex/ClosedOperators.lean | 2 +- lean/PrunedModel/Convex/CompletionGaps.lean | 179 +++++++++++++++++++ lean/README.md | 1 + 6 files changed, 236 insertions(+), 3 deletions(-) create mode 100644 lean/PrunedModel/Convex/CompletionGaps.lean diff --git a/differential/src/algebraic/path_set_laws.rs b/differential/src/algebraic/path_set_laws.rs index a61e7b12..f4b99de8 100644 --- a/differential/src/algebraic/path_set_laws.rs +++ b/differential/src/algebraic/path_set_laws.rs @@ -3,7 +3,7 @@ // cd lean && lake env lean --run PathSetLaws.lean > ../differential/src/algebraic/path_set_laws.rs // // Every entry is a theorem of PrunedModel.Convex, checked sorry-free when generated. -// 249 exported, 321 not exported (listed at the end). +// 254 exported, 321 not exported (listed at the end). use super::laws::zippy::*; @@ -1029,6 +1029,56 @@ pub fn laws() -> Vec { lhs: completion(union(s(0), empty())), rhs: s(0), }, + // PrunedModel/Convex/CompletionGaps.lean:9 + ZippyLaw { + name: "path_set/completion_retain_gap", + spaces: 2, + paths: 0, + bytes: 0, + pre: vec![], + lhs: subtr(retain(completion(s(0)), s(1)), completion(retain(s(0), s(1)))), + rhs: subtr(retain(subtr(branches(s(0)), s(0)), s(1)), branches(retain(s(0), s(1)))), + }, + // PrunedModel/Convex/CompletionGaps.lean:18 + ZippyLaw { + name: "path_set/completion_raffinate_correction", + spaces: 2, + paths: 0, + bytes: 0, + pre: vec![], + lhs: raffination(completion(s(0)), s(1)), + rhs: subtr(completion(union(raffination(s(0), s(1)), retain(basis(s(1)), s(0)))), retain(basis(s(1)), s(0))), + }, + // PrunedModel/Convex/CompletionGaps.lean:127 + ZippyLaw { + name: "path_set/completion_convexSubtract_correction", + spaces: 2, + paths: 0, + bytes: 0, + pre: vec![], + lhs: convex_subtract(completion(s(0)), s(1)), + rhs: union(completion(convex_subtract(s(0), s(1))), divergence(subtr(hull(s(0)), s(1)), inter(hull(s(0)), s(1)))), + }, + // PrunedModel/Convex/CompletionGaps.lean:143 + ZippyLaw { + name: "path_set/completion_convexSubtract_gap", + spaces: 2, + paths: 0, + bytes: 0, + pre: vec![], + lhs: subtr(convex_subtract(completion(s(0)), s(1)), completion(convex_subtract(s(0), s(1)))), + rhs: subtr(divergence(subtr(hull(s(0)), s(1)), inter(hull(s(0)), s(1))), union(s(0), branches(subtr(hull(s(0)), s(1))))), + }, + // PrunedModel/Convex/CompletionGaps.lean:157 + ZippyLaw { + name: "path_set/completion_convexMeet_correction", + spaces: 2, + paths: 0, + bytes: 0, + pre: vec![], + lhs: convex_meet(completion(s(0)), completion(s(1))), + rhs: union(completion(convex_meet(s(0), s(1))), union(inter(divergence(inter(hull(s(0)), hull(s(1))), subtr(hull(s(0)), hull(s(1)))), completion(s(1))), inter(completion(s(0)), divergence(inter(hull(s(0)), hull(s(1))), subtr(hull(s(1)), hull(s(0))))))), + }, // PrunedModel/Convex/Geometry.lean:38 ZippyLaw { name: "path_set/pruning_basis_cut", diff --git a/differential/tests/algebraic.rs b/differential/tests/algebraic.rs index 2925f785..511fa8f2 100644 --- a/differential/tests/algebraic.rs +++ b/differential/tests/algebraic.rs @@ -686,7 +686,9 @@ fn path_set_laws_are_registered_without_name_collisions() { assert_eq!(names.len(), all.len()); for name in ["basis_idempotent", "hull_idempotent", "divergence_comm", "branches_union", "retain_self", "convexMeet_assoc", "convexSubtract_action", - "completion_idempotent", "lcp_associativity", "hull_of_antichain"] { + "completion_idempotent", "lcp_associativity", "hull_of_antichain", + "completion_retain_gap", "completion_raffinate_correction", "completion_convexMeet_correction", + "completion_convexSubtract_correction", "completion_convexSubtract_gap"] { assert!(names.contains(format!("path_set/{name}").as_str()), "missing {name}"); } assert_eq!(all.len(), algebraic::zippy_laws::laws().len() + algebraic::path_set_laws::laws().len()); diff --git a/lean/PrunedModel/Convex.lean b/lean/PrunedModel/Convex.lean index 1eb54b15..48bce843 100644 --- a/lean/PrunedModel/Convex.lean +++ b/lean/PrunedModel/Convex.lean @@ -3,3 +3,4 @@ import PrunedModel.Convex.PathSetChecks import PrunedModel.Convex.Checks import PrunedModel.Convex.RetainChecks import PrunedModel.Convex.ClosedChecks +import PrunedModel.Convex.CompletionGaps diff --git a/lean/PrunedModel/Convex/ClosedOperators.lean b/lean/PrunedModel/Convex/ClosedOperators.lean index 3db6a1f2..fe490584 100644 --- a/lean/PrunedModel/Convex/ClosedOperators.lean +++ b/lean/PrunedModel/Convex/ClosedOperators.lean @@ -1,5 +1,5 @@ import PrunedModel.Convex.ClosedGeometry - +/-! The exact corrections to the four completion bounds are proved in `CompletionGaps.lean`. -/ namespace PrunedModel.Convex open PathMapModel diff --git a/lean/PrunedModel/Convex/CompletionGaps.lean b/lean/PrunedModel/Convex/CompletionGaps.lean new file mode 100644 index 00000000..93c102da --- /dev/null +++ b/lean/PrunedModel/Convex/CompletionGaps.lean @@ -0,0 +1,179 @@ +import PrunedModel.Convex.ClosedOperators + +/-! Exact corrections to the completion bounds for retain, raffinate and the +convex operations. All differences in the gap formulas are ordinary set differences. -/ +namespace PrunedModel.Convex +open PathMapModel + +/-- Retaining after completion can keep a new fork even when the retained keys no longer fork there. -/ +theorem completion_retain_gap (a b : PathSpace) : + Same (diff (retain (completion a) b) (completion (retain a b))) + (diff (retain (diff (branches a) a) b) (branches (retain a b))) := by + intro p + simp only [mem_diff, mem_retain, mem_completion] + grind + +/-- Stop each masked path at its first mask key. These boundary marks preserve + the forks above the cuts and are removed after completion. -/ +theorem completion_raffinate_correction (a b : PathSpace) : + Same (raffinate (completion a) b) + (diff (completion (union (raffinate a b) (retain (basis b) a))) (retain (basis b) a)) := by + let boundary := retain (basis b) a + let cut := union (raffinate a b) boundary + -- Every cut key extends to an original key. + have covered : ∀ x ∈ cut, ∃ y ∈ a, (x ≼ y) = true := by + intro x hx + rcases (mem_union _ _ _).mp hx with h | h + · exact ⟨x,((mem_raffinate _ _ _).mp h).1,Path.prefix_self x⟩ + · exact ((mem_retain _ _ _).mp h).2 + -- Each original key survives or has a boundary prefix. + have truncate (x : Path) (hx : x ∈ a) : + x ∈ cut ∨ ∃ q ∈ boundary, (q ≼ x) = true := by + by_cases h : ∃ r ∈ b, (r ≼ x) = true + · obtain ⟨r,hr,hrx⟩ := h + obtain ⟨q,hq,hqr⟩ := basis_below hr + have hqx := Path.prefix_trans hqr hrx + exact Or.inr ⟨q,(mem_retain _ _ _).mpr ⟨hq,x,hx,hqx⟩,hqx⟩ + · exact Or.inl (mem_union_left _ ((mem_raffinate _ _ _).mpr ⟨hx,by grind⟩)) + -- A cut key has no proper prefix in the mask, even when it is a boundary key. + have noPrefix {x q : Path} (hx : x ∈ cut) (hq : q ∈ b) (hne : q ≠ x) : (q ≼ x) = false := by + rcases (mem_union _ _ _).mp hx with h | h + · exact ((mem_raffinate _ _ _).mp h).2 q hq + · exact ((mem_basis _ _).mp ((mem_retain _ _ _).mp h).1).2 q hq hne + intro p + change p ∈ raffinate (completion a) b ↔ p ∈ diff (completion cut) boundary + rw [mem_raffinate, mem_diff, mem_completion, mem_completion] + constructor + · rintro ⟨hp,unmasked⟩ + have outside : p ∉ boundary := by + intro h + have hn := unmasked p (basis_subset b ((mem_retain _ _ _).mp h).1) + simp at hn + refine ⟨?_,outside⟩ + rcases hp with ha | fork + · exact Or.inl (mem_union_left _ ((mem_raffinate _ _ _).mpr ⟨ha,unmasked⟩)) + · obtain ⟨x,hx,y,hy,hxy⟩ := (mem_divergence _ _ _).mp fork + have cutWitness {v w : Path} (hv : v ∈ a) (hd : Path.divergence v w = some p) : + ∃ u ∈ cut, Path.divergence u w = some p := by + rcases truncate v hv with h | ⟨q,hq,hqv⟩ + · exact ⟨v,h,hd⟩ + · refine ⟨q,mem_union_right _ hq,?_⟩ + rcases Path.divergence_cut hqv hd with hqp | hd' + · have hn := unmasked q (basis_subset b ((mem_retain _ _ _).mp hq).1) + simp [hqp] at hn + · exact hd' + obtain ⟨u,hu,huy⟩ := cutWitness hx hxy + obtain ⟨v,hv,hvu⟩ := cutWitness hy ((Path.divergence_comm y u).trans huy) + exact Or.inr ((mem_divergence _ _ _).mpr ⟨u,hu,v,hv,(Path.divergence_comm u v).trans hvu⟩) + · rintro ⟨h,outside⟩ + rcases h with h | fork + · obtain ⟨ha,unmasked⟩ := (mem_raffinate _ _ _).mp (((mem_union _ _ _).mp h).resolve_right outside) + exact ⟨Or.inl ha,unmasked⟩ + · have forkA : p ∈ branches a := by + exact divergence_covered_mono covered p ((divergence_comm cut a p).mpr + (divergence_covered_mono covered p fork)) + refine ⟨Or.inr forkA,?_⟩ + obtain ⟨x,hx,y,_,hd⟩ := (mem_divergence _ _ _).mp fork + intro q hq + cases he : q ≼ p with + | false => rfl + | true => + have hqx := Path.prefix_trans he (Path.divergence_prefix_left hd) + have hne : q ≠ x := by + have := Path.prefix_length he + have := Path.divergence_length_left hd + rintro rfl + omega + simpa [hqx] using noPrefix hx hq hne + +/-- A fork above a surviving tip either still forks among the survivors or + separates a surviving tip from a removed one. Original marks survive by coverage. -/ +private theorem retain_completion_tips (a kept removed : PathSpace) + (partition : Same (hull a) (union kept removed)) (p : Path) : + p ∈ retain (completion a) kept ↔ + p ∈ retain a kept ∨ p ∈ branches kept ∨ p ∈ divergence kept removed := by + have inHull {q : Path} (h : q ∈ kept ∨ q ∈ removed) : q ∈ hull a := + (partition q).mpr ((mem_union _ _ _).mpr h) + constructor + · intro h + obtain ⟨hc,t,ht,hpt⟩ := (mem_retain _ _ _).mp h + by_cases ha : p ∈ a + · exact Or.inl ((mem_retain _ _ _).mpr ⟨ha,t,ht,hpt⟩) + have fork := (branch_hull a p).mpr (((mem_completion _ _).mp hc).resolve_left ha) + have hne : p ≠ t := fun e => ha (e ▸ hull_subset a (inHull (Or.inl ht))) + obtain ⟨z,tail,e⟩ := Path.proper_prefix_split hpt hne + have survives : Child kept p z := ⟨tail,e ▸ ht⟩ + obtain ⟨x,y,hxy,hx,hy⟩ := (mem_divergence_children _ _ _).mp fork + have other : ∃ k, z ≠ k ∧ Child (hull a) p k := by + by_cases h : z = x + · exact ⟨y,h ▸ hxy,hy⟩ + · exact ⟨x,h,hx⟩ + obtain ⟨k,hzk,rest,hk⟩ := other + rcases (mem_union _ _ _).mp ((partition _).mp hk) with keptTip | removedTip + · exact Or.inr (Or.inl ((mem_divergence_children _ _ _).mpr ⟨z,k,hzk,survives,rest,keptTip⟩)) + · exact Or.inr (Or.inr ((mem_divergence_children _ _ _).mpr ⟨z,k,hzk,survives,rest,removedTip⟩)) + · have liftFork {s : PathSpace} (hs : Included s (hull a)) (h : p ∈ divergence kept s) : + p ∈ retain (completion a) kept := by + have fork := divergence_mono (fun _ h => inHull (Or.inl h)) hs p h + exact (mem_retain _ _ _).mpr ⟨(mem_completion _ _).mpr (Or.inr ((branch_hull a p).mp fork)), + divergence_output_covered h⟩ + rintro (h | h | h) + · exact retain_mono (completion_extensive a) (fun _ h => h) p h + · exact liftFork (fun _ h => inHull (Or.inl h)) h + · exact liftFork (fun _ h => inHull (Or.inr h)) h + +/-- Completing before subtraction also preserves every fork between a surviving + tip and a removed tip. Some such forks already belong to the smaller side. -/ +theorem completion_convexSubtract_correction (a b : PathSpace) : + Same (convexSubtract (completion a) b) + (union (completion (convexSubtract a b)) + (divergence (diff (hull a) b) (inter (hull a) b))) := by + intro p + have partition : Same (hull a) (union (diff (hull a) b) (inter (hull a) b)) := by + intro q; simp only [mem_union, mem_diff, mem_inter]; grind + have tips := retain_completion_tips _ _ _ partition p + have fork := (branch_hull (convexSubtract a b) p).symm.trans + (divergence_congr (hull_convexSubtract a b) (hull_convexSubtract a b) p) + change p ∈ branches (convexSubtract a b) ↔ p ∈ branches (diff (hull a) b) at fork + rw [mem_union, mem_completion, fork] + simpa only [convexSubtract, mem_retain, mem_diff, hull_completion, or_assoc] using tips + +/-- The disjoint gap consists of the mixed forks that were unmarked in the source + and have ceased to fork among the surviving tips. -/ +theorem completion_convexSubtract_gap (a b : PathSpace) : + Same (diff (convexSubtract (completion a) b) (completion (convexSubtract a b))) + (diff (divergence (diff (hull a) b) (inter (hull a) b)) (union a (branches (diff (hull a) b)))) := by + intro p + rw [mem_diff, completion_convexSubtract_correction, mem_union, mem_diff, mem_union] + have fork := (branch_hull (convexSubtract a b) p).symm.trans + (divergence_congr (hull_convexSubtract a b) (hull_convexSubtract a b) p) + change p ∈ branches (convexSubtract a b) ↔ p ∈ branches (diff (hull a) b) at fork + have witness := @divergence_output_covered (diff (hull a) b) (inter (hull a) b) p + simp only [convexSubtract, mem_completion, mem_retain] at * + grind + +/-- Completing each meet operand adds mixed forks of shared and exclusive tips + when the other completed operand also contains the fork. -/ +theorem completion_convexMeet_correction (a b : PathSpace) : + Same (convexMeet (completion a) (completion b)) + (union (completion (convexMeet a b)) + (union (inter (divergence (inter (hull a) (hull b)) (diff (hull a) (hull b))) (completion b)) + (inter (completion a) (divergence (inter (hull a) (hull b)) (diff (hull b) (hull a)))))) := by + intro p + let shared := inter (hull a) (hull b) + have left : Same (hull a) (union shared (diff (hull a) (hull b))) := by + intro q; simp only [shared, mem_union, mem_inter, mem_diff]; grind + have right : Same (hull b) (union shared (diff (hull b) (hull a))) := by + intro q; simp only [shared, mem_union, mem_inter, mem_diff]; grind + have ha := retain_completion_tips _ _ _ left p + have hb := retain_completion_tips _ _ _ right p + have fork := (branch_hull (convexMeet a b) p).symm.trans + (divergence_congr (hull_convexMeet a b) (hull_convexMeet a b) p) + change p ∈ branches (convexMeet a b) ↔ p ∈ branches shared at fork + have ca := completion_extensive a p + have cb := completion_extensive b p + rw [mem_union, mem_completion, fork] + simp only [convexMeet, mem_retain, mem_inter, mem_union, hull_completion, shared] at * + grind + +end PrunedModel.Convex diff --git a/lean/README.md b/lean/README.md index 9e490890..9325376f 100644 --- a/lean/README.md +++ b/lean/README.md @@ -201,6 +201,7 @@ seven operations except one in `subtract_into`. | `PrunedModel/Pointwise.lean` | `valAt` of every map operation | | `PrunedModel/Refine.lean` | each write op as `z.withTrie (z.trie.replaceAt z.focus M)` | | `PrunedModel/Zippy.lean` | each egg operator as a zipper program over `Space = PrunedMap Unit`, every `formal.egg` rule proved, `Fix` as a least post-fixpoint, the raw ops = egg ops under #104 (§10), the tour as `#guard`s | +| [`PrunedModel/Convex/CompletionGaps.lean`](PrunedModel/Convex/CompletionGaps.lean) | exact completion laws for retain, raffinate, convex meet, and convex subtraction | | `PrunedModel/Fuzz.lean`, `PrunedMain.lean` | the pruned fuzzer's wire format, op table and trace producer; the `pruned-oracle` binary | | `ZippyLaws.lean` | exports Zippy.lean's equational theorems as `differential/src/algebraic/zippy_laws.rs`: `lake build PrunedModel && lake env lean --run ZippyLaws.lean > ../differential/src/algebraic/zippy_laws.rs` |